@mastra/deployer-vercel 1.2.2 → 1.2.3-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-avAmkB1u.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-hbcxDBH-.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js"])))=>i.map(i=>d[i]);
2
2
  import{_ as Eo}from"./preload-helper-PPVm8Dsz.js";function Hzt(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 Pj=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Cc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var YQ={exports:{}},fA={};var vRe;function Wzt(){if(vRe)return fA;vRe=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 fA.Fragment=t,fA.jsx=n,fA.jsxs=n,fA}var yRe;function Zzt(){return yRe||(yRe=1,YQ.exports=Wzt()),YQ.exports}var o=Zzt(),XQ={exports:{}},Br={},bRe;function Gzt(){if(bRe)return Br;bRe=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 g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function w(U,P,q){this.props=U,this.context=P,this.refs=b,this.updater=q||g}w.prototype.isReactComponent={},w.prototype.setState=function(U,P){if(typeof U!="object"&&typeof U!="function"&&U!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,U,P,"setState")},w.prototype.forceUpdate=function(U){this.updater.enqueueForceUpdate(this,U,"forceUpdate")};function S(){}S.prototype=w.prototype;function k(U,P,q){this.props=U,this.context=P,this.refs=b,this.updater=q||g}var _=k.prototype=new S;_.constructor=k,y(_,w.prototype),_.isPureReactComponent=!0;var C=Array.isArray;function E(){}var j={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function I(U,P,q){var Z=q.ref;return{$$typeof:t,type:U,key:P,ref:Z!==void 0?Z:null,props:q}}function R(U,P){return I(U.type,P,U.props)}function $(U){return typeof U=="object"&&U!==null&&U.$$typeof===t}function F(U){var P={"=":"=0",":":"=2"};return"$"+U.replace(/[=:]/g,function(q){return P[q]})}var D=/\/+/g;function V(U,P){return typeof U=="object"&&U!==null&&U.key!=null?F(""+U.key):P.toString(36)}function W(U){switch(U.status){case"fulfilled":return U.value;case"rejected":throw U.reason;default:switch(typeof U.status=="string"?U.then(E,E):(U.status="pending",U.then(function(P){U.status==="pending"&&(U.status="fulfilled",U.value=P)},function(P){U.status==="pending"&&(U.status="rejected",U.reason=P)})),U.status){case"fulfilled":return U.value;case"rejected":throw U.reason}}throw U}function L(U,P,q,Z,X){var te=typeof U;(te==="undefined"||te==="boolean")&&(U=null);var J=!1;if(U===null)J=!0;else switch(te){case"bigint":case"string":case"number":J=!0;break;case"object":switch(U.$$typeof){case t:case n:J=!0;break;case f:return J=U._init,L(J(U._payload),P,q,Z,X)}}if(J)return X=X(U),J=Z===""?"."+V(U,0):Z,C(X)?(q="",J!=null&&(q=J.replace(D,"$&/")+"/"),L(X,P,q,"",function(de){return de})):X!=null&&($(X)&&(X=R(X,q+(X.key==null||U&&U.key===X.key?"":(""+X.key).replace(D,"$&/")+"/")+J)),P.push(X)),1;J=0;var ee=Z===""?".":Z+":";if(C(U))for(var ae=0;ae<U.length;ae++)Z=U[ae],te=ee+V(Z,ae),J+=L(Z,P,q,te,X);else if(ae=m(U),typeof ae=="function")for(U=ae.call(U),ae=0;!(Z=U.next()).done;)Z=Z.value,te=ee+V(Z,ae++),J+=L(Z,P,q,te,X);else if(te==="object"){if(typeof U.then=="function")return L(W(U),P,q,Z,X);throw P=String(U),Error("Objects are not valid as a React child (found: "+(P==="[object Object]"?"object with keys {"+Object.keys(U).join(", ")+"}":P)+"). If you meant to render a collection of children, use an array instead.")}return J}function z(U,P,q){if(U==null)return U;var Z=[],X=0;return L(U,Z,"","",function(te){return P.call(q,te,X++)}),Z}function B(U){if(U._status===-1){var P=U._result;P=P(),P.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=P)}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 P=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof U=="object"&&U!==null&&typeof U.message=="string"?String(U.message):String(U),error:U});if(!window.dispatchEvent(P))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",U);return}console.error(U)},G={map:z,forEach:function(U,P,q){z(U,function(){P.apply(this,arguments)},q)},count:function(U){var P=0;return z(U,function(){P++}),P},toArray:function(U){return z(U,function(P){return P})||[]},only:function(U){if(!$(U))throw Error("React.Children.only expected to receive a single React element child.");return U}};return Br.Activity=p,Br.Children=G,Br.Component=w,Br.Fragment=r,Br.Profiler=a,Br.PureComponent=k,Br.StrictMode=s,Br.Suspense=u,Br.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=j,Br.__COMPILER_RUNTIME={__proto__:null,c:function(U){return j.H.useMemoCache(U)}},Br.cache=function(U){return function(){return U.apply(null,arguments)}},Br.cacheSignal=function(){return null},Br.cloneElement=function(U,P,q){if(U==null)throw Error("The argument must be a React element, but you passed "+U+".");var Z=y({},U.props),X=U.key;if(P!=null)for(te in P.key!==void 0&&(X=""+P.key),P)!N.call(P,te)||te==="key"||te==="__self"||te==="__source"||te==="ref"&&P.ref===void 0||(Z[te]=P[te]);var te=arguments.length-2;if(te===1)Z.children=q;else if(1<te){for(var J=Array(te),ee=0;ee<te;ee++)J[ee]=arguments[ee+2];Z.children=J}return I(U.type,X,Z)},Br.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},Br.createElement=function(U,P,q){var Z,X={},te=null;if(P!=null)for(Z in P.key!==void 0&&(te=""+P.key),P)N.call(P,Z)&&Z!=="key"&&Z!=="__self"&&Z!=="__source"&&(X[Z]=P[Z]);var J=arguments.length-2;if(J===1)X.children=q;else if(1<J){for(var ee=Array(J),ae=0;ae<J;ae++)ee[ae]=arguments[ae+2];X.children=ee}if(U&&U.defaultProps)for(Z in J=U.defaultProps,J)X[Z]===void 0&&(X[Z]=J[Z]);return I(U,te,X)},Br.createRef=function(){return{current:null}},Br.forwardRef=function(U){return{$$typeof:c,render:U}},Br.isValidElement=$,Br.lazy=function(U){return{$$typeof:f,_payload:{_status:-1,_result:U},_init:B}},Br.memo=function(U,P){return{$$typeof:d,type:U,compare:P===void 0?null:P}},Br.startTransition=function(U){var P=j.T,q={};j.T=q;try{var Z=U(),X=j.S;X!==null&&X(q,Z),typeof Z=="object"&&Z!==null&&typeof Z.then=="function"&&Z.then(E,M)}catch(te){M(te)}finally{P!==null&&q.types!==null&&(P.types=q.types),j.T=P}},Br.unstable_useCacheRefresh=function(){return j.H.useCacheRefresh()},Br.use=function(U){return j.H.use(U)},Br.useActionState=function(U,P,q){return j.H.useActionState(U,P,q)},Br.useCallback=function(U,P){return j.H.useCallback(U,P)},Br.useContext=function(U){return j.H.useContext(U)},Br.useDebugValue=function(){},Br.useDeferredValue=function(U,P){return j.H.useDeferredValue(U,P)},Br.useEffect=function(U,P){return j.H.useEffect(U,P)},Br.useEffectEvent=function(U){return j.H.useEffectEvent(U)},Br.useId=function(){return j.H.useId()},Br.useImperativeHandle=function(U,P,q){return j.H.useImperativeHandle(U,P,q)},Br.useInsertionEffect=function(U,P){return j.H.useInsertionEffect(U,P)},Br.useLayoutEffect=function(U,P){return j.H.useLayoutEffect(U,P)},Br.useMemo=function(U,P){return j.H.useMemo(U,P)},Br.useOptimistic=function(U,P){return j.H.useOptimistic(U,P)},Br.useReducer=function(U,P,q){return j.H.useReducer(U,P,q)},Br.useRef=function(U){return j.H.useRef(U)},Br.useState=function(U){return j.H.useState(U)},Br.useSyncExternalStore=function(U,P,q){return j.H.useSyncExternalStore(U,P,q)},Br.useTransition=function(){return j.H.useTransition()},Br.version="19.2.6",Br}var xRe;function iN(){return xRe||(xRe=1,XQ.exports=Gzt()),XQ.exports}var v=iN();const Le=Cc(v),oN=Hzt({__proto__:null,default:Le},[v]);var KQ={exports:{}},pA={},JQ={exports:{}},eY={};var wRe;function Qzt(){return wRe||(wRe=1,(function(e){function t(W,L){var z=W.length;W.push(L);e:for(;0<z;){var B=z-1>>>1,M=W[B];if(0<s(M,L))W[B]=L,W[z]=M,z=B;else break e}}function n(W){return W.length===0?null:W[0]}function r(W){if(W.length===0)return null;var L=W[0],z=W.pop();if(z!==L){W[0]=z;e:for(var B=0,M=W.length,G=M>>>1;B<G;){var U=2*(B+1)-1,P=W[U],q=U+1,Z=W[q];if(0>s(P,z))q<M&&0>s(Z,P)?(W[B]=Z,W[q]=z,B=q):(W[B]=P,W[U]=z,B=U);else if(q<M&&0>s(Z,z))W[B]=Z,W[q]=z,B=q;else break e}}return L}function s(W,L){var z=W.sortIndex-L.sortIndex;return z!==0?z:W.id-L.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var a=performance;e.unstable_now=function(){return a.now()}}else{var i=Date,l=i.now();e.unstable_now=function(){return i.now()-l}}var c=[],u=[],d=1,f=null,p=3,h=!1,m=!1,g=!1,y=!1,b=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;function k(W){for(var L=n(u);L!==null;){if(L.callback===null)r(u);else if(L.startTime<=W)r(u),L.sortIndex=L.expirationTime,t(c,L);else break;L=n(u)}}function _(W){if(g=!1,k(W),!m)if(n(c)!==null)m=!0,C||(C=!0,$());else{var L=n(u);L!==null&&V(_,L.startTime-W)}}var C=!1,E=-1,j=5,N=-1;function I(){return y?!0:!(e.unstable_now()-N<j)}function R(){if(y=!1,C){var W=e.unstable_now();N=W;var L=!0;try{e:{m=!1,g&&(g=!1,w(E),E=-1),h=!0;var z=p;try{t:{for(k(W),f=n(c);f!==null&&!(f.expirationTime>W&&I());){var B=f.callback;if(typeof B=="function"){f.callback=null,p=f.priorityLevel;var M=B(f.expirationTime<=W);if(W=e.unstable_now(),typeof M=="function"){f.callback=M,k(W),L=!0;break t}f===n(c)&&r(c),k(W)}else r(c);f=n(c)}if(f!==null)L=!0;else{var G=n(u);G!==null&&V(_,G.startTime-W),L=!1}}break e}finally{f=null,p=z,h=!1}L=void 0}}finally{L?$():C=!1}}}var $;if(typeof S=="function")$=function(){S(R)};else if(typeof MessageChannel<"u"){var F=new MessageChannel,D=F.port2;F.port1.onmessage=R,$=function(){D.postMessage(null)}}else $=function(){b(R,0)};function V(W,L){E=b(function(){W(e.unstable_now())},L)}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(W){W.callback=null},e.unstable_forceFrameRate=function(W){0>W||125<W?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):j=0<W?Math.floor(1e3/W):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_next=function(W){switch(p){case 1:case 2:case 3:var L=3;break;default:L=p}var z=p;p=L;try{return W()}finally{p=z}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(W,L){switch(W){case 1:case 2:case 3:case 4:case 5:break;default:W=3}var z=p;p=W;try{return L()}finally{p=z}},e.unstable_scheduleCallback=function(W,L,z){var B=e.unstable_now();switch(typeof z=="object"&&z!==null?(z=z.delay,z=typeof z=="number"&&0<z?B+z:B):z=B,W){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,W={id:d++,callback:L,priorityLevel:W,startTime:z,expirationTime:M,sortIndex:-1},z>B?(W.sortIndex=z,t(u,W),n(c)===null&&W===n(u)&&(g?(w(E),E=-1):g=!0,V(_,z-B))):(W.sortIndex=M,t(c,W),m||h||(m=!0,C||(C=!0,$()))),W},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(W){var L=p;return function(){var z=p;p=L;try{return W.apply(this,arguments)}finally{p=z}}}})(eY)),eY}var SRe;function Yzt(){return SRe||(SRe=1,JQ.exports=Qzt()),JQ.exports}var tY={exports:{}},cu={};var kRe;function Xzt(){if(kRe)return cu;kRe=1;var e=iN();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 cu.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,cu.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)},cu.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()}},cu.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))},cu.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},cu.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})}},cu.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)},cu.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})}},cu.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)},cu.requestFormReset=function(c){r.d.r(c)},cu.unstable_batchedUpdates=function(c,u){return c(u)},cu.useFormState=function(c,u,d){return i.H.useFormState(c,u,d)},cu.useFormStatus=function(){return i.H.useHostTransitionStatus()},cu.version="19.2.6",cu}var ORe;function Vnt(){if(ORe)return tY.exports;ORe=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(),tY.exports=Xzt(),tY.exports}var _Re;function Kzt(){if(_Re)return pA;_Re=1;var e={env:{}};var t=Yzt(),n=iN(),r=Vnt();function s(x){var O="https://react.dev/errors/"+x;if(1<arguments.length){O+="?args[]="+encodeURIComponent(arguments[1]);for(var T=2;T<arguments.length;T++)O+="&args[]="+encodeURIComponent(arguments[T])}return"Minified React error #"+x+"; visit "+O+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function a(x){return!(!x||x.nodeType!==1&&x.nodeType!==9&&x.nodeType!==11)}function i(x){var O=x,T=x;if(x.alternate)for(;O.return;)O=O.return;else{x=O;do O=x,(O.flags&4098)!==0&&(T=O.return),x=O.return;while(x)}return O.tag===3?T:null}function l(x){if(x.tag===13){var O=x.memoizedState;if(O===null&&(x=x.alternate,x!==null&&(O=x.memoizedState)),O!==null)return O.dehydrated}return null}function c(x){if(x.tag===31){var O=x.memoizedState;if(O===null&&(x=x.alternate,x!==null&&(O=x.memoizedState)),O!==null)return O.dehydrated}return null}function u(x){if(i(x)!==x)throw Error(s(188))}function d(x){var O=x.alternate;if(!O){if(O=i(x),O===null)throw Error(s(188));return O!==x?null:x}for(var T=x,A=O;;){var H=T.return;if(H===null)break;var Q=H.alternate;if(Q===null){if(A=H.return,A!==null){T=A;continue}break}if(H.child===Q.child){for(Q=H.child;Q;){if(Q===T)return u(H),x;if(Q===A)return u(H),O;Q=Q.sibling}throw Error(s(188))}if(T.return!==A.return)T=H,A=Q;else{for(var ie=!1,we=H.child;we;){if(we===T){ie=!0,T=H,A=Q;break}if(we===A){ie=!0,A=H,T=Q;break}we=we.sibling}if(!ie){for(we=Q.child;we;){if(we===T){ie=!0,T=Q,A=H;break}if(we===A){ie=!0,A=Q,T=H;break}we=we.sibling}if(!ie)throw Error(s(189))}}if(T.alternate!==A)throw Error(s(190))}if(T.tag!==3)throw Error(s(188));return T.stateNode.current===T?x:O}function f(x){var O=x.tag;if(O===5||O===26||O===27||O===6)return x;for(x=x.child;x!==null;){if(O=f(x),O!==null)return O;x=x.sibling}return null}var p=Object.assign,h=Symbol.for("react.element"),m=Symbol.for("react.transitional.element"),g=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),w=Symbol.for("react.profiler"),S=Symbol.for("react.consumer"),k=Symbol.for("react.context"),_=Symbol.for("react.forward_ref"),C=Symbol.for("react.suspense"),E=Symbol.for("react.suspense_list"),j=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),I=Symbol.for("react.activity"),R=Symbol.for("react.memo_cache_sentinel"),$=Symbol.iterator;function F(x){return x===null||typeof x!="object"?null:(x=$&&x[$]||x["@@iterator"],typeof x=="function"?x:null)}var D=Symbol.for("react.client.reference");function V(x){if(x==null)return null;if(typeof x=="function")return x.$$typeof===D?null:x.displayName||x.name||null;if(typeof x=="string")return x;switch(x){case y:return"Fragment";case w:return"Profiler";case b:return"StrictMode";case C:return"Suspense";case E:return"SuspenseList";case I:return"Activity"}if(typeof x=="object")switch(x.$$typeof){case g:return"Portal";case k:return x.displayName||"Context";case S:return(x._context.displayName||"Context")+".Consumer";case _:var O=x.render;return x=x.displayName,x||(x=O.displayName||O.name||"",x=x!==""?"ForwardRef("+x+")":"ForwardRef"),x;case j:return O=x.displayName||null,O!==null?O:V(x.type)||"Memo";case N:O=x._payload,x=x._init;try{return V(x(O))}catch{}}return null}var W=Array.isArray,L=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,B={pending:!1,data:null,method:null,action:null},M=[],G=-1;function U(x){return{current:x}}function P(x){0>G||(x.current=M[G],M[G]=null,G--)}function q(x,O){G++,M[G]=x.current,x.current=O}var Z=U(null),X=U(null),te=U(null),J=U(null);function ee(x,O){switch(q(te,O),q(X,x),q(Z,null),O.nodeType){case 9:case 11:x=(x=O.documentElement)&&(x=x.namespaceURI)?zAe(x):0;break;default:if(x=O.tagName,O=O.namespaceURI)O=zAe(O),x=BAe(O,x);else switch(x){case"svg":x=1;break;case"math":x=2;break;default:x=0}}P(Z),q(Z,x)}function ae(){P(Z),P(X),P(te)}function de(x){x.memoizedState!==null&&q(J,x);var O=Z.current,T=BAe(O,x.type);O!==T&&(q(X,x),q(Z,T))}function Y(x){X.current===x&&(P(Z),P(X)),J.current===x&&(P(J),lA._currentValue=B)}var ne,ce;function pe(x){if(ne===void 0)try{throw Error()}catch(T){var O=T.stack.trim().match(/\n( *(at )?)/);ne=O&&O[1]||"",ce=-1<T.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<T.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+ne+x+ce}var le=!1;function ve(x,O){if(!x||le)return"";le=!0;var T=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var A={DetermineComponentFrameRoot:function(){try{if(O){var Ct=function(){throw Error()};if(Object.defineProperty(Ct.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ct,[])}catch(dt){var lt=dt}Reflect.construct(x,[],Ct)}else{try{Ct.call()}catch(dt){lt=dt}x.call(Ct.prototype)}}else{try{throw Error()}catch(dt){lt=dt}(Ct=x())&&typeof Ct.catch=="function"&&Ct.catch(function(){})}}catch(dt){if(dt&&lt&&typeof dt.stack=="string")return[dt.stack,lt.stack]}return[null,null]}};A.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var H=Object.getOwnPropertyDescriptor(A.DetermineComponentFrameRoot,"name");H&&H.configurable&&Object.defineProperty(A.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Q=A.DetermineComponentFrameRoot(),ie=Q[0],we=Q[1];if(ie&&we){var Be=ie.split(`
@@ -228,7 +228,7 @@ Please change the parent <Route path="${y}"> to <Route path="${y==="/"?"*":`${y}
228
228
  \${}
229
229
  }
230
230
  }`,{label:"class",detail:"definition",type:"keyword"}),Md('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),Md('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],vgt=D0e.concat([Md("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),Md("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),Md("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),D5e=new wpt,ygt=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function DA(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const c2n=["FunctionDeclaration"],u2n={FunctionDeclaration:DA("function"),ClassDeclaration:DA("class"),ClassExpression:()=>!0,EnumDeclaration:DA("constant"),TypeAliasDeclaration:DA("type"),NamespaceDeclaration:DA("namespace"),VariableDefinition(e,t){e.matchContext(c2n)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function bgt(e,t){let n=D5e.get(t);if(n)return n;let r=[],s=!0;function a(i,l){let c=e.sliceString(i.from,i.to);r.push({label:c,type:l})}return t.cursor(La.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=u2n[i.name];if(l&&l(i,a)||ygt.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of bgt(e,i.node))r.push(l);return!1}}),D5e.set(t,r),r}const Hz=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,L0e=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function xgt(e){let t=fi(e.state).resolveInner(e.pos,-1);if(L0e.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&Hz.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)ygt.has(s.name)&&(r=r.concat(bgt(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:Hz}}function nK(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 wgt(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=fi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?nK(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?nK(t,n.parent,""):L0e.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&Hz.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?nK(t,n,""):e.explicit?{path:[],name:""}:null}function d2n(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 f2n(e){let t=new Map;return n=>{let r=wgt(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=d2n(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:Hz}}}const qh=gO.define({name:"javascript",parser:l2n.configure({props:[S_.add({IfStatement:fj({except:/^\s*({|else\b)/}),TryStatement:fj({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:iNn,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:aNn({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":fj({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}}),k_.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":v0e,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:"$"}}),Sgt={test:e=>/^JSX/.test(e.name),facet:Qq({commentTokens:{block:{open:"{/*",close:"*/}"}}})},F0e=qh.configure({dialect:"ts"},"typescript"),z0e=qh.configure({dialect:"jsx",props:[h0e.add(e=>e.isTop?[Sgt]:void 0)]}),B0e=qh.configure({dialect:"jsx ts",props:[h0e.add(e=>e.isTop?[Sgt]:void 0)]},"typescript");let kgt=e=>({label:e,type:"keyword"});const Ogt="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(kgt),p2n=Ogt.concat(["declare","implements","private","protected","public"].map(kgt));function Wz(e={}){let t=e.jsx?e.typescript?B0e:z0e:e.typescript?F0e:qh,n=e.typescript?vgt.concat(p2n):D0e.concat(Ogt);return new yO(t,[qh.data.of({autocomplete:HNn(L0e,Smt(n))}),qh.data.of({autocomplete:xgt}),e.jsx?_gt:[]])}function h2n(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 L5e(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 m2n=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),_gt=It.inputHandler.of((e,t,n,r,s)=>{if((m2n?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!qh.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u;let{head:d}=c,f=fi(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=L5e(i.doc,m.firstChild,d))||((u=m.firstChild)===null||u===void 0?void 0:u.name)=="JSXFragmentTag")){let g=`${p}>`;return{range:vt.cursor(d+g.length,-1),changes:{from:d,insert:g}}}}else if(r==">"){let h=h2n(f);if(h&&h.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(p=L5e(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 g2n(e,t){return t||(t={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:!0,node:!0,es6:!0,es2015:!0,es2017:!0,es2020:!0},rules:{}},e.getRules().forEach((n,r)=>{var s;!((s=n.meta.docs)===null||s===void 0)&&s.recommended&&(t.rules[r]=2)})),n=>{let{state:r}=n,s=[];for(let{from:a,to:i}of qh.findRegions(r)){let l=r.doc.lineAt(a),c={line:l.number-1,col:a-l.from,pos:a};for(let u of e.verify(r.sliceDoc(a,i),t))s.push(v2n(u,r.doc,c))}return s}}function F5e(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function v2n(e,t,n){let r=F5e(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?F5e(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 e6=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:_gt,completionPath:wgt,esLint:g2n,javascript:Wz,javascriptLanguage:qh,jsxLanguage:z0e,localCompletionSource:xgt,scopeCompletionSource:f2n,snippets:D0e,tsxLanguage:B0e,typescriptLanguage:F0e,typescriptSnippets:vgt},Symbol.toStringTag,{value:"Module"})),LA=["_blank","_self","_top","_parent"],rK=["ascii","utf-8","utf-16","latin1","latin1"],sK=["get","post","put","delete"],aK=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],Vf=["true","false"],Jn={},y2n={a:{attrs:{href:null,ping:null,type:null,media:null,target:LA,hreflang:null}},abbr:Jn,address:Jn,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:Jn,aside:Jn,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:Jn,base:{attrs:{href:null,target:LA}},bdi:Jn,bdo:Jn,blockquote:{attrs:{cite:null}},body:Jn,br:Jn,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:aK,formmethod:sK,formnovalidate:["novalidate"],formtarget:LA,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:Jn,center:Jn,cite:Jn,code:Jn,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:Jn,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:Jn,div:Jn,dl:Jn,dt:Jn,em:Jn,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:Jn,figure:Jn,footer:Jn,form:{attrs:{action:null,name:null,"accept-charset":rK,autocomplete:["on","off"],enctype:aK,method:sK,novalidate:["novalidate"],target:LA}},h1:Jn,h2:Jn,h3:Jn,h4:Jn,h5:Jn,h6:Jn,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:Jn,hgroup:Jn,hr:Jn,html:{attrs:{manifest:null}},i:Jn,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:aK,formmethod:sK,formnovalidate:["novalidate"],formtarget:LA,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:Jn,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:Jn,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:Jn,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:rK,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:Jn,noscript:Jn,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:Jn,param:{attrs:{name:null,value:null}},pre:Jn,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:Jn,rt:Jn,ruby:Jn,samp:Jn,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:rK}},section:Jn,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:Jn,source:{attrs:{src:null,type:null,media:null}},span:Jn,strong:Jn,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:Jn,summary:Jn,sup:Jn,table:Jn,tbody:Jn,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:Jn,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:Jn,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:Jn,time:{attrs:{datetime:null}},title:Jn,tr:Jn,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:Jn,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:Jn},Cgt={accesskey:null,class:null,contenteditable:Vf,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:Vf,autocorrect:Vf,autocapitalize:Vf,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":Vf,"aria-autocomplete":["inline","list","both","none"],"aria-busy":Vf,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":Vf,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":Vf,"aria-hidden":Vf,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":Vf,"aria-multiselectable":Vf,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":Vf,"aria-relevant":null,"aria-required":Vf,"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},Egt="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 Egt)Cgt[e]=null;let b$=class{constructor(t,n){this.tags={...y2n,...t},this.globalAttrs={...Cgt,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}};b$.default=new b$;function rT(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 sT(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function jgt(e,t,n){let r=n.tags[rT(e,sT(t))];return r?.children||n.allTags}function U0e(e,t){let n=[];for(let r=sT(t);r&&!r.type.isTop;r=sT(r.parent)){let s=rT(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 Tgt=/^[:\-\.\w\u00b7-\uffff]*$/;function z5e(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=sT(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:jgt(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(U0e(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function B5e(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:U0e(e.doc,t).map((a,i)=>({label:a,apply:a+s,type:"type",boost:99-i})),validFor:Tgt}}function b2n(e,t,n,r){let s=[],a=0;for(let i of jgt(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of U0e(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function x2n(e,t,n,r,s){let a=sT(n),i=a?t.tags[rT(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:Tgt}}function w2n(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=sT(n),p=f?t.tags[rT(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 Ngt(e,t){let{state:n,pos:r}=t,s=fi(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)?B5e(n,s,s.from,r):z5e(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?z5e(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?B5e(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?x2n(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?w2n(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?b2n(n,e,s,r):null}function S2n(e){return Ngt(b$.default,e)}function k2n(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new b$(t,n):b$.default;return s=>Ngt(r,s)}const O2n=qh.parser.configure({top:"SingleExpression"}),Igt=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:F0e.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:z0e.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:B0e.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:O2n},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:qh.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:Vz.parser}],Agt=[{name:"style",parser:Vz.parser.configure({top:"Styles"})}].concat(Egt.map(e=>({name:e,parser:qh.parser}))),Rgt=gO.define({name:"html",parser:QAn.configure({props:[S_.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}}),k_.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}}}),mmt.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),I9=Rgt.configure({wrap:ugt(Igt,Agt)});function _2n(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=ugt((e.nestedLanguages||[]).concat(Igt),(e.nestedAttributes||[]).concat(Agt)));let r=n?Rgt.configure({wrap:n,dialect:t}):t?I9.configure({dialect:t}):I9;return new yO(r,[I9.data.of({autocomplete:k2n(e)}),e.autoCloseTags!==!1?C2n:[],Wz().support,IRn().support])}const U5e=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),C2n=It.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!I9.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=fi(i).resolveInner(h,-1),g;if(p&&r==">"&&m.name=="EndTag"){let y=m.parent;if(((d=(u=y.parent)===null||u===void 0?void 0:u.lastChild)===null||d===void 0?void 0:d.name)!="CloseTag"&&(g=rT(i.doc,y.parent,h))&&!U5e.has(g)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),w=`</${g}>`;return{range:c,changes:{from:h,to:b,insert:w}}}}else if(p&&r=="/"&&m.name=="IncompleteCloseTag"){let y=m.parent;if(m.from==h-2&&((f=y.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(g=rT(i.doc,y,h))&&!U5e.has(g)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),w=`${g}>`;return{range:vt.cursor(h+w.length,-1),changes:{from:h,to:b,insert:w}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),Pgt=Qq({commentTokens:{block:{open:"<!--",close:"-->"}}}),$gt=new Rr,Mgt=XIn.configure({props:[k_.add(e=>!e.is("Block")||e.is("Document")||wpe(e)!=null||E2n(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),$gt.add(wpe),S_.add({Document:()=>null}),hw.add({Document:Pgt})]});function wpe(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function E2n(e){return e.name=="OrderedList"||e.name=="BulletList"}function j2n(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=wpe(r.type))!=null&&s<=t)break;n=r}return n.to}const T2n=rmt.of((e,t,n)=>{for(let r=fi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop($gt);if(s==null)continue;let a=j2n(r,s);if(a>n)return{from:n,to:a}}return null});function q0e(e){return new mp(Pgt,e,[],"markdown")}const Dgt=q0e(Mgt),N2n=Mgt.configure([lAn,uAn,cAn,dAn,{props:[k_.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),wO=q0e(N2n);function I2n(e,t){return n=>{if(n&&e){let r=null;if(n=/\S*/.exec(n)[0],typeof e=="function"?r=e(n):r=Ym.matchLanguageName(e,n,!0),r instanceof Ym)return r.support?r.support.language.parser:vO.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class iK{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(+Fgt(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function Lgt(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 iK(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 iK(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 iK(a.parent,c,c+d,i[1],u,f,a))}}return r}function Fgt(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function oK(e,t,n,r=0){for(let s=-1,a=e;;){if(a.name=="ListItem"){let l=Fgt(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 V0e(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(NN)!=" ")return e;let r=Sg(e,4,n),s="";for(let a=r;a>0;)a>=4?(s+=" ",a-=4):(s+=" ",a--);return s+e.slice(n)}const zgt=(e={})=>({state:t,dispatch:n})=>{let r=fi(t),{doc:s}=t,a=null,i=t.changeByRange(l=>{if(!l.empty||!wO.isActiveAt(t,l.from,-1)&&!wO.isActiveAt(t,l.from,1))return a={range:l};let c=l.from,u=s.lineAt(c),d=Lgt(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,w=f.node.getChild("ListItem","ListItem");if(b.to>=c||w&&w.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"&&oK(f.item,s,C,-2),S&&S.node.name=="OrderedList"&&oK(S.item,s,C),{range:vt.cursor(k+_.length),changes:C}}else{let S=V5e(d,t,u);return{range:vt.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),w=/>\s*$/.exec(b.text);if(w&&w.index==f.from){let S=t.changes([{from:b.from+w.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"&&oK(f.item,s,h);let m=f.item&&f.item.from<u.from,g="";if(!m||/^[\s\d.)\-+*>]*/.exec(u.text)[0].length>=f.to)for(let b=0,w=d.length-1;b<=w;b++)g+=b==w&&!m?d[b].marker(s,1):d[b].blank(b<w?Sg(u.text,4,d[b+1].from)-g.length:null);let y=c;for(;y>u.from&&/\s/.test(u.text.charAt(y-u.from-1));)y--;return g=V0e(g,t),A2n(f.node,t.doc)&&(g=V5e(d,t,u)+t.lineBreak+g),h.push({from:y,to:c,insert:t.lineBreak+g}),{range:vt.cursor(y+g.length+1),changes:h}});return a?!1:(n(t.update(i,{scrollIntoView:!0,userEvent:"input"})),!0)},Bgt=zgt();function q5e(e){return e.name=="QuoteMark"||e.name=="ListMark"}function A2n(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 V5e(e,t,n){let r="";for(let s=0,a=e.length-2;s<=a;s++)r+=e[s].blank(s<a?Sg(n.text,4,e[s+1].from)-r.length:null,s<a);return V0e(r,t)}function R2n(e,t){let n=e.resolveInner(t,-1),r=t;q5e(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(q5e(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const Ugt=({state:e,dispatch:t})=>{let n=fi(e),r=null,s=e.changeByRange(a=>{let i=a.from,{doc:l}=e;if(a.empty&&wO.isActiveAt(e,a.from)){let c=l.lineAt(i),u=Lgt(R2n(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:vt.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(Sg(c.text,4,d.to)-Sg(c.text,4,d.from));return p==c.from&&(h=V0e(h,e)),{range:vt.cursor(p+h.length),changes:{from:p,to:c.from+d.to,insert:h}}}if(p<i)return{range:vt.cursor(p),changes:{from:p,to:i}}}}}return r={range:a}});return r?!1:(t(e.update(s,{scrollIntoView:!0,userEvent:"delete"})),!0)},qgt=[{key:"Enter",run:Bgt},{key:"Backspace",run:Ugt}],Vgt=_2n({matchClosingTags:!1});function H0e(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=Dgt,completeHTMLTags:a=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=Vgt}=e;if(!(s instanceof Jq))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,T2n],d;i&&u.push(Hgt),n instanceof yO?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?I2n(t,d):void 0;c.push(JIn({codeParser:f,htmlParser:l.language.parser})),r&&u.push(Pg.high(TN.of(qgt)));let p=q0e(s.configure(c));return a&&u.push(p.data.of({autocomplete:P2n})),new yO(p,u)}function P2n(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=fi(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:$2n(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let lK=null;function $2n(){if(lK)return lK;let e=S2n(new w0e(os.create({extensions:Vgt}),0,!0));return lK=e?e.options:[]}const M2n=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,Hgt=It.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),!wO.isActiveAt(t.state,r.from,1)))return!1;let a=fi(t.state),i=!1;return a.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||M2n.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)}}),D2n=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:Dgt,deleteMarkupBackward:Ugt,insertNewlineContinueMarkup:Bgt,insertNewlineContinueMarkupCommand:zgt,markdown:H0e,markdownKeymap:qgt,markdownLanguage:wO,pasteURLAsLink:Hgt},Symbol.toStringTag,{value:"Module"}));function SO(){return SO=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},SO.apply(null,arguments)}var L2n=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=It.theme(i,{dark:t==="dark"}),d=$g.define(a),f=[u,D1(d)];return f},F2n={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)"},z2n=[{tag:fe.comment,color:"#6272a4"},{tag:fe.string,color:"#f1fa8c"},{tag:fe.atom,color:"#bd93f9"},{tag:fe.meta,color:"#f8f8f2"},{tag:[fe.keyword,fe.operator,fe.tagName],color:"#ff79c6"},{tag:[fe.function(fe.propertyName),fe.propertyName],color:"#66d9ef"},{tag:[fe.definition(fe.variableName),fe.function(fe.variableName),fe.className,fe.attributeName],color:"#50fa7b"},{tag:fe.atom,color:"#bd93f9"}],AN=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 L2n({theme:r,settings:SO({},F2n,a),styles:[...z2n,...l]})};AN();function Wgt(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 B2n=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=Z0e(e.state,n.from);return r.line?U2n(e):r.block?V2n(e):!1};function W0e(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 U2n=W0e(Z2n,0),q2n=W0e(Zgt,0),V2n=W0e((e,t)=>Zgt(e,t,W2n(t)),0);function Z0e(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const FA=50;function H2n(e,{open:t,close:n},r,s){let a=e.sliceDoc(r-FA,r),i=e.sliceDoc(s,s+FA),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*FA?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+FA),f=e.sliceDoc(s-FA,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 W2n(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 Zgt(e,t,n=t.selection.ranges){let r=n.map(a=>Z0e(t,a.from).block);if(!r.every(a=>a))return null;let s=n.map((a,i)=>H2n(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 Z2n(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=Z0e(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 Spe=Ny.define(),G2n=Ny.define(),Q2n=On.define(),Ggt=On.define({combine(e){return Iy(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)})}}),Qgt=ml.define({create(){return Dv.empty},update(e,t){let n=t.state.facet(Ggt),r=t.annotation(Spe);if(r){let c=Qd.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=Zz(d,d.length,n.minDepth,c):d=Kgt(d,t.startState.selection),new Dv(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(G2n);if((s=="full"||s=="before")&&(e=e.isolate()),t.annotation(El.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=Qd.fromTransaction(t),i=t.annotation(El.time),l=t.annotation(El.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 Dv(e.done.map(Qd.fromJSON),e.undone.map(Qd.fromJSON))}});function Y2n(e={}){return[Qgt,Ggt.of(e),It.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?Ygt:t.inputType=="historyRedo"?kpe:null;return r?(t.preventDefault(),r(n)):!1}})]}function eV(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(Qgt,!1);if(!s)return!1;let a=s.pop(e,n,t);return a?(r(a),!0):!1}}const Ygt=eV(0,!1),kpe=eV(1,!1),X2n=eV(0,!0),K2n=eV(1,!0);class Qd{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 Qd(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 Qd(t.changes&&_l.fromJSON(t.changes),[],t.mapped&&Qv.fromJSON(t.mapped),t.startSelection&&vt.fromJSON(t.startSelection),t.selectionsAfter.map(vt.fromJSON))}static fromTransaction(t,n){let r=Rh;for(let s of t.startState.facet(Q2n)){let a=s(t);a.length&&(r=r.concat(a))}return!r.length&&t.changes.empty?null:new Qd(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,Rh)}static selection(t){return new Qd(void 0,Rh,void 0,void 0,t)}}function Zz(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 J2n(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 ePn(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function Xgt(e,t){return e.length?t.length?e.concat(t):e:t}const Rh=[],tPn=200;function Kgt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-tPn));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),Zz(e,e.length-1,1e9,n.setSelAfter(r)))}else return[Qd.selection([t])]}function nPn(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 cK(e,t){if(!e.length)return e;let n=e.length,r=Rh;for(;n;){let s=rPn(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?[Qd.selection(r)]:Rh}function rPn(e,t,n){let r=Xgt(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):Rh,n);if(!e.changes)return Qd.selection(r);let s=e.changes.map(t),a=t.mapDesc(e.changes,!0),i=e.mapped?e.mapped.composeDesc(a):a;return new Qd(s,vr.mapEffects(e.effects,t),i,e.startSelection.map(a),r)}const sPn=/^(input\.type|delete)($|\.)/;class Dv{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 Dv(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||sPn.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(a,J2n(l.changes,t.changes))||r=="input.type.compose")?i=Zz(i,i.length-1,s.minDepth,new Qd(t.changes.compose(l.changes),Xgt(vr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,Rh)):i=Zz(i,i.length,s.minDepth,t),new Dv(i,Rh,n,r)}addSelection(t,n,r,s){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:Rh;return a.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&ePn(a[a.length-1],t)?this:new Dv(Kgt(this.done,t),this.undone,n,r)}addMapping(t){return new Dv(cK(this.done,t),cK(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:Spe.of({side:t,rest:nPn(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(a.changes){let l=s.length==1?Rh:s.slice(0,s.length-1);return a.mapped&&(l=cK(l,a.mapped)),n.update({changes:a.changes,selection:a.startSelection,effects:a.effects,annotations:Spe.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}Dv.empty=new Dv(Rh,Rh);const aPn=[{key:"Mod-z",run:Ygt,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:kpe,preventDefault:!0},{linux:"Ctrl-Shift-z",run:kpe,preventDefault:!0},{key:"Mod-u",run:X2n,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:K2n,preventDefault:!0}];function RN(e,t){return vt.create(e.ranges.map(t),e.mainIndex)}function Mg(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function Dg({state:e,dispatch:t},n){let r=RN(e.selection,n);return r.eq(e.selection,!0)?!1:(t(Mg(e,r)),!0)}function tV(e,t){return vt.cursor(t?e.to:e.from)}function Jgt(e,t){return Dg(e,n=>n.empty?e.moveByChar(n,t):tV(n,t))}function Fu(e){return e.textDirectionAt(e.state.selection.main.head)==xi.LTR}const evt=e=>Jgt(e,!Fu(e)),tvt=e=>Jgt(e,Fu(e));function nvt(e,t){return Dg(e,n=>n.empty?e.moveByGroup(n,t):tV(n,t))}const iPn=e=>nvt(e,!Fu(e)),oPn=e=>nvt(e,Fu(e));function lPn(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 nV(e,t,n){let r=fi(e).resolveInner(t.head),s=n?Rr.closedBy:Rr.openedBy;for(let c=t.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;lPn(e,u,s)?r=u:c=n?u.to:u.from}let a=r.type.prop(s),i,l;return a&&(i=n?Mv(e,r.from,1):Mv(e,r.to,-1))&&i.matched?l=n?i.end.to:i.end.from:l=n?r.to:r.from,vt.cursor(l,n?-1:1)}const cPn=e=>Dg(e,t=>nV(e.state,t,!Fu(e))),uPn=e=>Dg(e,t=>nV(e.state,t,Fu(e)));function rvt(e,t){return Dg(e,n=>{if(!n.empty)return tV(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const svt=e=>rvt(e,!1),avt=e=>rvt(e,!0);function ivt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let a of e.state.facet(It.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 ovt(e,t){let n=ivt(e),{state:r}=e,s=RN(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):tV(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=It.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(Mg(r,s),{effects:a}),!0}const H5e=e=>ovt(e,!1),Ope=e=>ovt(e,!0);function L1(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=vt.cursor(r.from+a))}return s}const dPn=e=>Dg(e,t=>L1(e,t,!0)),fPn=e=>Dg(e,t=>L1(e,t,!1)),pPn=e=>Dg(e,t=>L1(e,t,!Fu(e))),hPn=e=>Dg(e,t=>L1(e,t,Fu(e))),mPn=e=>Dg(e,t=>vt.cursor(e.lineBlockAt(t.head).from,1)),gPn=e=>Dg(e,t=>vt.cursor(e.lineBlockAt(t.head).to,-1));function vPn(e,t,n){let r=!1,s=RN(e.selection,a=>{let i=Mv(e,a.head,-1)||Mv(e,a.head,1)||a.head>0&&Mv(e,a.head-1,1)||a.head<e.doc.length&&Mv(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 vt.cursor(l)});return r?(t(Mg(e,s)),!0):!1}const yPn=({state:e,dispatch:t})=>vPn(e,t);function bm(e,t){let n=RN(e.state.selection,r=>{let s=t(r);return vt.range(r.anchor,s.head,s.goalColumn,s.bidiLevel||void 0,s.assoc)});return n.eq(e.state.selection)?!1:(e.dispatch(Mg(e.state,n)),!0)}function lvt(e,t){return bm(e,n=>e.moveByChar(n,t))}const cvt=e=>lvt(e,!Fu(e)),uvt=e=>lvt(e,Fu(e));function dvt(e,t){return bm(e,n=>e.moveByGroup(n,t))}const bPn=e=>dvt(e,!Fu(e)),xPn=e=>dvt(e,Fu(e)),wPn=e=>bm(e,t=>nV(e.state,t,!Fu(e))),SPn=e=>bm(e,t=>nV(e.state,t,Fu(e)));function fvt(e,t){return bm(e,n=>e.moveVertically(n,t))}const pvt=e=>fvt(e,!1),hvt=e=>fvt(e,!0);function mvt(e,t){return bm(e,n=>e.moveVertically(n,t,ivt(e).height))}const W5e=e=>mvt(e,!1),Z5e=e=>mvt(e,!0),kPn=e=>bm(e,t=>L1(e,t,!0)),OPn=e=>bm(e,t=>L1(e,t,!1)),_Pn=e=>bm(e,t=>L1(e,t,!Fu(e))),CPn=e=>bm(e,t=>L1(e,t,Fu(e))),EPn=e=>bm(e,t=>vt.cursor(e.lineBlockAt(t.head).from)),jPn=e=>bm(e,t=>vt.cursor(e.lineBlockAt(t.head).to)),G5e=({state:e,dispatch:t})=>(t(Mg(e,{anchor:0})),!0),Q5e=({state:e,dispatch:t})=>(t(Mg(e,{anchor:e.doc.length})),!0),Y5e=({state:e,dispatch:t})=>(t(Mg(e,{anchor:e.selection.main.anchor,head:0})),!0),X5e=({state:e,dispatch:t})=>(t(Mg(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),TPn=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),NPn=({state:e,dispatch:t})=>{let n=rV(e).map(({from:r,to:s})=>vt.range(r,Math.min(s+1,e.doc.length)));return t(e.update({selection:vt.create(n),userEvent:"select"})),!0},IPn=({state:e,dispatch:t})=>{let n=RN(e.selection,r=>{let s=fi(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 vt.range(l.to,l.from)}return r});return n.eq(e.selection)?!1:(t(Mg(e,n)),!0)};function gvt(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(Mg(n,vt.create(s,s.length-1))),!0)}const APn=e=>gvt(e,!1),RPn=e=>gvt(e,!0),PPn=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=vt.create([n.main]):n.main.empty||(r=vt.create([vt.cursor(n.main.head)])),r?(t(Mg(e,r)),!0):!1};function U3(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=t6(e,c,!1)):c>i&&(n="delete.forward",c=t6(e,c,!0)),i=Math.min(i,c),l=Math.max(l,c)}else i=t6(e,i,!1),l=t6(e,l,!0);return i==l?{range:a}:{changes:{from:i,to:l},range:vt.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"?It.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function t6(e,t,n){if(e instanceof It)for(let r of e.state.facet(It.atomicRanges).map(s=>s(e)))r.between(t,t,(s,a)=>{s<t&&a>t&&(t=n?a:s)});return t}const vvt=(e,t,n)=>U3(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=Sg(l,a.tabSize),d=u%bO(a)||bO(a);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=vc(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=vc(i.text,c-i.from,!1,!1)+i.from);return c}),_pe=e=>vvt(e,!1,!0),yvt=e=>vvt(e,!0,!1),bvt=(e,t)=>U3(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=vc(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}),xvt=e=>bvt(e,!1),$Pn=e=>bvt(e,!0),MPn=e=>U3(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),DPn=e=>U3(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),LPn=e=>U3(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),FPn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:va.of(["",""])},range:vt.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},zPn=({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:vc(a.text,s-a.from,!1)+a.from,l=s==a.to?s+1:vc(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:vt.cursor(l)}});return n.changes.empty?!1:(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function rV(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 wvt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let a of rV(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(vt.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(vt.range(c.anchor-l,c.head-l))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:vt.create(s,e.selection.mainIndex),userEvent:"move.line"})),!0):!1}const BPn=({state:e,dispatch:t})=>wvt(e,t,!1),UPn=({state:e,dispatch:t})=>wvt(e,t,!0);function Svt(e,t,n){if(e.readOnly)return!1;let r=[];for(let a of rV(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 qPn=({state:e,dispatch:t})=>Svt(e,t,!1),VPn=({state:e,dispatch:t})=>Svt(e,t,!0),HPn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(rV(t).map(({from:s,to:a})=>(s>0?s--:a<t.doc.length&&a++,{from:s,to:a}))),r=RN(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 WPn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=fi(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(Rr.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 K5e=kvt(!1),ZPn=kvt(!0);function kvt(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&&WPn(t,a);e&&(a=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new Yq(t,{simulateBreak:a,simulateDoubleBreak:!!c}),d=m0e(u,a);for(d==null&&(d=Sg(/^\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=["",d$(t,d)];return c&&f.push(d$(t,u.lineIndent(l.from,-1))),{changes:{from:a,to:i,insert:va.of(f)},range:vt.cursor(a+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function G0e(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:vt.range(a.mapPos(r.anchor,1),a.mapPos(r.head,1))}})}const GPn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new Yq(e,{overrideIndentation:a=>{let i=n[a];return i??-1}}),s=G0e(e,(a,i,l)=>{let c=m0e(r,a.from);if(c==null)return;/\S/.test(a.text)||(c=0);let u=/^\s*/.exec(a.text)[0],d=d$(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},Ovt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(G0e(e,(n,r)=>{r.push({from:n.from,insert:e.facet(NN)})}),{userEvent:"input.indent"})),!0),_vt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(G0e(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let a=Sg(s,e.tabSize),i=0,l=d$(e,Math.max(0,a-bO(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),QPn=e=>(e.setTabFocusMode(),!0),YPn=[{key:"Ctrl-b",run:evt,shift:cvt,preventDefault:!0},{key:"Ctrl-f",run:tvt,shift:uvt},{key:"Ctrl-p",run:svt,shift:pvt},{key:"Ctrl-n",run:avt,shift:hvt},{key:"Ctrl-a",run:mPn,shift:EPn},{key:"Ctrl-e",run:gPn,shift:jPn},{key:"Ctrl-d",run:yvt},{key:"Ctrl-h",run:_pe},{key:"Ctrl-k",run:MPn},{key:"Ctrl-Alt-h",run:xvt},{key:"Ctrl-o",run:FPn},{key:"Ctrl-t",run:zPn},{key:"Ctrl-v",run:Ope}],XPn=[{key:"ArrowLeft",run:evt,shift:cvt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:iPn,shift:bPn,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:pPn,shift:_Pn,preventDefault:!0},{key:"ArrowRight",run:tvt,shift:uvt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:oPn,shift:xPn,preventDefault:!0},{mac:"Cmd-ArrowRight",run:hPn,shift:CPn,preventDefault:!0},{key:"ArrowUp",run:svt,shift:pvt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:G5e,shift:Y5e},{mac:"Ctrl-ArrowUp",run:H5e,shift:W5e},{key:"ArrowDown",run:avt,shift:hvt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:Q5e,shift:X5e},{mac:"Ctrl-ArrowDown",run:Ope,shift:Z5e},{key:"PageUp",run:H5e,shift:W5e},{key:"PageDown",run:Ope,shift:Z5e},{key:"Home",run:fPn,shift:OPn,preventDefault:!0},{key:"Mod-Home",run:G5e,shift:Y5e},{key:"End",run:dPn,shift:kPn,preventDefault:!0},{key:"Mod-End",run:Q5e,shift:X5e},{key:"Enter",run:K5e,shift:K5e},{key:"Mod-a",run:TPn},{key:"Backspace",run:_pe,shift:_pe,preventDefault:!0},{key:"Delete",run:yvt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:xvt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:$Pn,preventDefault:!0},{mac:"Mod-Backspace",run:DPn,preventDefault:!0},{mac:"Mod-Delete",run:LPn,preventDefault:!0}].concat(YPn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),KPn=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:cPn,shift:wPn},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:uPn,shift:SPn},{key:"Alt-ArrowUp",run:BPn},{key:"Shift-Alt-ArrowUp",run:qPn},{key:"Alt-ArrowDown",run:UPn},{key:"Shift-Alt-ArrowDown",run:VPn},{key:"Mod-Alt-ArrowUp",run:APn},{key:"Mod-Alt-ArrowDown",run:RPn},{key:"Escape",run:PPn},{key:"Mod-Enter",run:ZPn},{key:"Alt-l",mac:"Ctrl-l",run:NPn},{key:"Mod-i",run:IPn,preventDefault:!0},{key:"Mod-[",run:_vt},{key:"Mod-]",run:Ovt},{key:"Mod-Alt-\\",run:GPn},{key:"Shift-Mod-k",run:HPn},{key:"Shift-Mod-\\",run:yPn},{key:"Mod-/",run:B2n},{key:"Alt-A",run:q2n},{key:"Ctrl-m",mac:"Shift-Alt-m",run:QPn}].concat(XPn),JPn={key:"Tab",run:Ovt,shift:_vt},J5e=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class vx{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(J5e(l)):J5e,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 Ud(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=Yxe(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=kv(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"&&(vx.prototype[Symbol.iterator]=function(){return this});const Cvt={from:-1,to:-1,match:/.*/.exec(""),precise:!0},Q0e="gm"+(/x/.unicode==null?"":"u");class Evt{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=Cvt,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new jvt(t,n,r,s,a);this.re=new RegExp(n,Q0e+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=Gz(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=Gz(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 uK=new WeakMap;class hj{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=uK.get(t);if(!s||s.from>=r||s.to<=n){let l=new hj(n,t.sliceString(n,r));return uK.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)),uK.set(t,new hj(i,a)),new hj(n,a.slice(n-i,r-i))}}class jvt{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=Cvt,this.matchPos=Gz(t,s),this.re=new RegExp(n,Q0e+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=hj.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=Gz(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=hj.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(Evt.prototype[Symbol.iterator]=jvt.prototype[Symbol.iterator]=function(){return this});function e$n(e){try{return new RegExp(e,Q0e),!0}catch{return!1}}function Gz(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 t$n=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=MTn(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(a=>{let i=a&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(a.elements.line.value);if(!i){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,u,d,f]=i,p=d?+d.slice(1):0,h=u?+u:l.number;if(u&&f){let y=h/100;c&&(y=y*(c=="-"?-1:1)+l.number/t.doc.lines),h=Math.round(t.doc.lines*y)}else u&&c&&(h=h*(c=="-"?-1:1)+l.number);let m=t.doc.line(Math.max(1,Math.min(t.doc.lines,h))),g=vt.cursor(m.from+Math.max(0,Math.min(p,m.length)));e.dispatch({effects:[r,It.scrollIntoView(g.from,{y:"center"})],selection:g})}),!0},n$n={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},r$n=On.define({combine(e){return Iy(e,n$n,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function s$n(e){return[c$n,l$n]}const a$n=Cn.mark({class:"cm-selectionMatch"}),i$n=Cn.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function eLe(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=fo.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=fo.Word)}function o$n(e,t,n,r){return e(t.sliceDoc(n,n+1))==fo.Word&&e(t.sliceDoc(r-1,r))==fo.Word}const l$n=yo.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(r$n),{state:n}=e,r=n.selection;if(r.ranges.length>1)return Cn.none;let s=r.main,a,i=null;if(s.empty){if(!t.highlightWordAroundCursor)return Cn.none;let c=n.wordAt(s.head);if(!c)return Cn.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 Cn.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),i=n.charCategorizer(s.head),!(eLe(i,n,s.from,s.to)&&o$n(i,n,s.from,s.to)))return Cn.none}else if(a=n.sliceDoc(s.from,s.to),!a)return Cn.none}let l=[];for(let c of e.visibleRanges){let u=new vx(n.doc,a,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||eLe(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(i$n.range(d,f)):(d>=s.to||f<=s.from)&&l.push(a$n.range(d,f)),l.length>t.maxMatches))return Cn.none}}return Cn.set(l)}},{decorations:e=>e.decorations}),c$n=It.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),u$n=({state:e,dispatch:t})=>{let{selection:n}=e,r=vt.create(n.ranges.map(s=>e.wordAt(s.head)||vt.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function d$n(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 vx(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new vx(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 f$n=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return u$n({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=d$n(e,r);return s?(t(e.update({selection:e.selection.addRange(vt.range(s.from,s.to),!1),effects:It.scrollIntoView(s.to)})),!0):!1},PN=On.define({combine(e){return Iy(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new C$n(t),scrollToMatch:t=>It.scrollIntoView(t)})}});class Tvt{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||e$n(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
231
- `:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new y$n(this):new m$n(this)}getCursor(t,n=0,r){let s=t.doc?t:os.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?gE(this,s,n,r):mE(this,s,n,r)}}class Nvt{constructor(t){this.spec=t}}function p$n(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 mE(e,t,n,r){let s;return e.wholeWord&&(s=h$n(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=p$n(e.test,t,s)),new vx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function h$n(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(Qz(s,n-a))!=fo.Word||t(Yz(s,n-a))!=fo.Word)&&(t(Yz(s,r-a))!=fo.Word||t(Qz(s,r-a))!=fo.Word))}class m$n extends Nvt{constructor(t){super(t)}nextMatch(t,n,r){let s=mE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=mE(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=mE(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=mE(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=mE(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 g$n(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function gE(e,t,n,r){let s;return e.wholeWord&&(s=v$n(t.charCategorizer(t.selection.main.head))),e.test&&(s=g$n(e.test,t,s)),new Evt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function Qz(e,t){return e.slice(vc(e,t,!1),t)}function Yz(e,t){return e.slice(t,vc(e,t))}function v$n(e){return(t,n,r)=>!r[0].length||(e(Qz(r.input,r.index))!=fo.Word||e(Yz(r.input,r.index))!=fo.Word)&&(e(Yz(r.input,r.index+r[0].length))!=fo.Word||e(Qz(r.input,r.index+r[0].length))!=fo.Word)}class y$n extends Nvt{nextMatch(t,n,r){let s=gE(this.spec,t,r,t.doc.length).next();return s.done&&(s=gE(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=gE(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=gE(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=gE(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 x$=vr.define(),Y0e=vr.define(),Iw=ml.define({create(e){return new dK(Cpe(e).create(),null)},update(e,t){for(let n of t.effects)n.is(x$)?e=new dK(n.value.create(),e.panel):n.is(Y0e)&&(e=new dK(e.query,n.value?X0e:null));return e},provide:e=>u$.from(e,t=>t.panel)});class dK{constructor(t,n){this.query=t,this.panel=n}}const b$n=Cn.mark({class:"cm-searchMatch"}),x$n=Cn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),w$n=yo.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Iw))}update(e){let t=e.state.field(Iw);(t!=e.startState.field(Iw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Cn.none;let{view:n}=this,r=new bd;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?x$n:b$n)})}return r.finish()}},{decorations:e=>e.decorations});function q3(e){return t=>{let n=t.state.field(Iw,!1);return n&&n.query.spec.valid?e(t,n):Rvt(t)}}const Xz=q3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=vt.single(r.from,r.to),a=e.state.facet(PN);return e.dispatch({selection:s,effects:[K0e(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),Avt(e),!0}),Kz=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=vt.single(s.from,s.to),i=e.state.facet(PN);return e.dispatch({selection:a,effects:[K0e(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),Avt(e),!0}),S$n=q3((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:vt.create(n.map(r=>vt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),k$n=({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 vx(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(vt.range(l.value.from,l.value.to))}return t(e.update({selection:vt.create(a,i),userEvent:"select.search.matches"})),!0},tLe=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}),d.push(It.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=vt.single(i.from,i.to).map(f),d.push(K0e(e,i)),d.push(n.facet(PN).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),O$n=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:It.announce.of(r),userEvent:"input.replace.all"}),!0});function X0e(e){return e.state.facet(PN).createPanel(e)}function Cpe(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(PN);return new Tvt({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 Ivt(e){let t=p0e(e,X0e);return t&&t.dom.querySelector("[main-field]")}function Avt(e){let t=Ivt(e);t&&t==e.root.activeElement&&t.select()}const Rvt=e=>{let t=e.state.field(Iw,!1);if(t&&t.panel){let n=Ivt(e);if(n&&n!=e.root.activeElement){let r=Cpe(e.state,t.query.spec);r.valid&&e.dispatch({effects:x$.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Y0e.of(!0),t?x$.of(Cpe(e.state,t.query.spec)):vr.appendConfig.of(j$n)]});return!0},Pvt=e=>{let t=e.state.field(Iw,!1);if(!t||!t.panel)return!1;let n=p0e(e,X0e);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Y0e.of(!1)}),!0},_$n=[{key:"Mod-f",run:Rvt,scope:"editor search-panel"},{key:"F3",run:Xz,shift:Kz,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:Xz,shift:Kz,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Pvt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:k$n},{key:"Mod-Alt-g",run:t$n},{key:"Mod-d",run:f$n,preventDefault:!0}];class C$n{constructor(t){this.view=t;let n=this.query=t.state.field(Iw).query.spec;this.commit=this.commit.bind(this),this.searchField=ii("input",{value:n.search,placeholder:Hf(t,"Find"),"aria-label":Hf(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=ii("input",{value:n.replace,placeholder:Hf(t,"Replace"),"aria-label":Hf(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=ii("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=ii("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=ii("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return ii("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=ii("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>Xz(t),[Hf(t,"next")]),r("prev",()=>Kz(t),[Hf(t,"previous")]),r("select",()=>S$n(t),[Hf(t,"all")]),ii("label",null,[this.caseField,Hf(t,"match case")]),ii("label",null,[this.reField,Hf(t,"regexp")]),ii("label",null,[this.wordField,Hf(t,"by word")]),...t.state.readOnly?[]:[ii("br"),this.replaceField,r("replace",()=>tLe(t),[Hf(t,"replace")]),r("replaceAll",()=>O$n(t),[Hf(t,"replace all")])],ii("button",{name:"close",onclick:()=>Pvt(t),"aria-label":Hf(t,"close"),type:"button"},["×"])])}commit(){let t=new Tvt({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:x$.of(t)}))}keydown(t){Wjn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?Kz:Xz)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),tLe(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(x$)&&!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(PN).top}}function Hf(e,t){return e.state.phrase(t)}const n6=30,r6=/[\s\.,:;?!]/;function K0e(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-n6),i=Math.min(s,n+n6),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<n6;c++)if(!r6.test(l[c+1])&&r6.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-n6;c--)if(!r6.test(l[c-1])&&r6.test(l[c])){l=l.slice(0,c);break}}return It.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const E$n=It.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"}}),j$n=[Iw,Pg.low(w$n),E$n];class nLe{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class lk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(w$).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new bd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((g,y)=>Math.min(g,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let g=a[d];if(g.from==p&&(g.to>g.from||g.to==p))l.push(g),d++,h=Math.min(g.to,h);else{h=Math.min(g.from,h);break}}let m=B$n(l);if(l.some(g=>g.from==g.to||g.from==g.to-1&&r.doc.lineAt(g.from).to==g.from))i.add(p,p,Cn.widget({widget:new D$n(m),diagnostics:l.slice()}));else{let g=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,Cn.mark({class:"cm-lintRange cm-lintRange-"+m+g,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let g=0;g<l.length;g++)l[g].to<=c&&l.splice(g--,1)}let u=i.finish();return new lk(u,n,aT(u))}}function aT(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 nLe(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new nLe(r.from,a,r.diagnostic)}}),r}function T$n(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(w$).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is($vt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function N$n(e,t){return e.field(gp,!1)?t:t.concat(vr.appendConfig.of(U$n))}const $vt=vr.define(),J0e=vr.define(),Mvt=vr.define(),gp=ml.define({create(){return new lk(Cn.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=aT(n,e.selected.diagnostic,a)||aT(n,null,a)}!n.size&&s&&t.state.facet(w$).autoPanel&&(s=null),e=new lk(n,s,r)}for(let n of t.effects)if(n.is($vt)){let r=t.state.facet(w$).autoPanel?n.value.length?S$.open:null:e.panel;e=lk.init(n.value,r,t.state)}else n.is(J0e)?e=new lk(e.diagnostics,n.value?S$.open:null,e.selected):n.is(Mvt)&&(e=new lk(e.diagnostics,e.panel,n.value));return e},provide:e=>[u$.from(e,t=>t.panel),It.decorations.from(e,t=>t.diagnostics)]}),I$n=Cn.mark({class:"cm-lintRange cm-lintRange-active"});function A$n(e,t,n){let{diagnostics:r}=e.state.field(gp),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(w$).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:R$n(e,s)}}}:null}function R$n(e,t){return ii("ul",{class:"cm-tooltip-lint"},t.map(n=>Lvt(e,n,!1)))}const P$n=e=>{let t=e.state.field(gp,!1);(!t||!t.panel)&&e.dispatch({effects:N$n(e.state,[J0e.of(!0)])});let n=p0e(e,S$.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},rLe=e=>{let t=e.state.field(gp,!1);return!t||!t.panel?!1:(e.dispatch({effects:J0e.of(!1)}),!0)},$$n=e=>{let t=e.state.field(gp,!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)},M$n=[{key:"Mod-Shift-m",run:P$n,preventDefault:!0},{key:"F8",run:$$n}],w$=On.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Iy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:sLe,tooltipFilter:sLe,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 sLe(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function Dvt(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 Lvt(e,t,n){var r;let s=n?Dvt(t.actions):[];return ii("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},ii("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=aT(e.state.field(gp).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),ii("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return ii("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&ii("div",{class:"cm-diagnosticSource"},t.source))}class D$n extends Wp{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return ii("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class aLe{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Lvt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class S${constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)rLe(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=Dvt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=aT(this.view.state.field(gp).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=ii("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=ii("div",{class:"cm-panel-lint"},this.list,ii("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>rLe(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(gp).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(gp),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 aLe(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 aLe(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(gp),r=aT(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:Mvt.of(r)})}static open(t){return new S$(t)}}function L$n(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 s6(e){return L$n(`<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 F$n=It.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:s6("#d11")},".cm-lintRange-warning":{backgroundImage:s6("orange")},".cm-lintRange-info":{backgroundImage:s6("#999")},".cm-lintRange-hint":{backgroundImage:s6("#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 z$n(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function B$n(e){let t="hint",n=1;for(let r of e){let s=z$n(r.severity);s>n&&(n=s,t=r.severity)}return t}const U$n=[gp,It.decorations.compute([gp],e=>{let{selected:t,panel:n}=e.field(gp);return!t||!n||t.from==t.to?Cn.none:Cn.set([I$n.range(t.from,t.to)])}),PTn(A$n,{hideOn:T$n}),F$n];var iLe=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(IIn)),t.defaultKeymap!==!1&&(a=a.concat(KPn)),t.searchKeymap!==!1&&(a=a.concat(_$n)),t.historyKeymap!==!1&&(a=a.concat(aPn)),t.foldKeymap!==!1&&(a=a.concat(gNn)),t.completionKeymap!==!1&&(a=a.concat(Amt)),t.lintKeymap!==!1&&(a=a.concat(M$n));var i=[];return t.lineNumbers!==!1&&i.push(WTn()),t.highlightActiveLineGutter!==!1&&i.push(QTn()),t.highlightSpecialChars!==!1&&i.push(lTn()),t.history!==!1&&i.push(Y2n()),t.foldGutter!==!1&&i.push(xNn()),t.drawSelection!==!1&&i.push(Kjn()),t.dropCursor!==!1&&i.push(rTn()),t.allowMultipleSelections!==!1&&i.push(os.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(lNn()),t.syntaxHighlighting!==!1&&i.push(D1(ONn,{fallback:!0})),t.bracketMatching!==!1&&i.push(INn()),t.closeBrackets!==!1&&i.push(EIn()),t.autocompletion!==!1&&i.push(Imt()),t.rectangularSelection!==!1&&i.push(STn()),s!==!1&&i.push(_Tn()),t.highlightActiveLine!==!1&&i.push(hTn()),t.highlightSelectionMatches!==!1&&i.push(s$n()),t.tabSize&&typeof t.tabSize=="number"&&i.push(NN.of(" ".repeat(t.tabSize))),i.concat([TN.of(a.flat())]).filter(Boolean)};const q$n="#e5c07b",oLe="#e06c75",V$n="#56b6c2",H$n="#ffffff",A9="#abb2bf",Epe="#7d8799",W$n="#61afef",Z$n="#98c379",lLe="#d19a66",G$n="#c678dd",Q$n="#21252b",cLe="#2c313a",uLe="#282c34",fK="#353a42",Y$n="#3E4451",dLe="#528bff",X$n=It.theme({"&":{color:A9,backgroundColor:uLe},".cm-content":{caretColor:dLe},".cm-cursor, .cm-dropCursor":{borderLeftColor:dLe},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:Y$n},".cm-panels":{backgroundColor:Q$n,color:A9},".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:uLe,color:Epe,border:"none"},".cm-activeLineGutter":{backgroundColor:cLe},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:fK},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:fK,borderBottomColor:fK},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:cLe,color:A9}}},{dark:!0}),K$n=$g.define([{tag:fe.keyword,color:G$n},{tag:[fe.name,fe.deleted,fe.character,fe.propertyName,fe.macroName],color:oLe},{tag:[fe.function(fe.variableName),fe.labelName],color:W$n},{tag:[fe.color,fe.constant(fe.name),fe.standard(fe.name)],color:lLe},{tag:[fe.definition(fe.name),fe.separator],color:A9},{tag:[fe.typeName,fe.className,fe.number,fe.changed,fe.annotation,fe.modifier,fe.self,fe.namespace],color:q$n},{tag:[fe.operator,fe.operatorKeyword,fe.url,fe.escape,fe.regexp,fe.link,fe.special(fe.string)],color:V$n},{tag:[fe.meta,fe.comment],color:Epe},{tag:fe.strong,fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.link,color:Epe,textDecoration:"underline"},{tag:fe.heading,fontWeight:"bold",color:oLe},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:lLe},{tag:[fe.processingInstruction,fe.string,fe.inserted],color:Z$n},{tag:fe.invalid,color:H$n}]),J$n=[X$n,D1(K$n)];var eMn=It.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),tMn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,g=[];switch(s&&g.unshift(TN.of([JPn])),m&&(typeof m=="boolean"?g.unshift(iLe()):g.unshift(iLe(m))),p&&g.unshift(yTn(p)),d){case"light":g.push(eMn);break;case"dark":g.push(J$n);break;case"none":break;default:g.push(d);break}return i===!1&&g.push(It.editable.of(!1)),c&&g.push(os.readOnly.of(!0)),[...g]},nMn=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 rMn{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 fLe{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 pK=null,sMn=()=>typeof window>"u"?new fLe:(pK||(pK=new fLe),pK),pLe=Ny.define(),aMn=200,iMn=[];function oMn(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?iMn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,g=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,w=e.width,S=w===void 0?null:w,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,E=C===void 0?null:C,j=e.placeholder,N=j===void 0?"":j,I=e.editable,R=I===void 0?!0:I,$=e.readOnly,F=$===void 0?!1:$,D=e.indentWithTab,V=D===void 0?!0:D,W=e.basicSetup,L=W===void 0?!0:W,z=e.root,B=e.initialState,M=v.useState(),G=M[0],U=M[1],P=v.useState(),q=P[0],Z=P[1],X=v.useState(),te=X[0],J=X[1],ee=v.useState(()=>({current:null}))[0],ae=v.useState(()=>({current:null}))[0],de=It.theme({"&":{height:h,minHeight:g,maxHeight:b,width:S,minWidth:_,maxWidth:E},"& .cm-scroller":{height:"100% !important"}}),Y=It.updateListener.of(pe=>{if(pe.docChanged&&typeof r=="function"&&!pe.transactions.some(ye=>ye.annotation(pLe))){ee.current?ee.current.reset():(ee.current=new rMn(()=>{if(ae.current){var ye=ae.current;ae.current=null,ye()}ee.current=null},aMn),sMn().add(ee.current));var le=pe.state.doc,ve=le.toString();r(ve,pe)}s&&s(nMn(pe))}),ne=tMn({theme:f,editable:R,readOnly:F,placeholder:N,indentWithTab:V,basicSetup:L}),ce=[Y,de,...ne];return i&&typeof i=="function"&&ce.push(It.updateListener.of(i)),ce=ce.concat(c),v.useLayoutEffect(()=>{if(G&&!te){var pe={doc:t,selection:n,extensions:ce},le=B?os.fromJSON(B.json,pe,B.fields):os.create(pe);if(J(le),!q){var ve=new It({state:le,parent:G,root:z});Z(ve),a&&a(ve,le)}}return()=>{q&&(J(void 0),Z(void 0))}},[G,te]),v.useEffect(()=>{e.container&&U(e.container)},[e.container]),v.useEffect(()=>()=>{q&&(q.destroy(),Z(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[q]),v.useEffect(()=>{u&&q&&q.focus()},[u,q]),v.useEffect(()=>{q&&q.dispatch({effects:vr.reconfigure.of(ce)})},[f,c,h,g,b,S,_,E,N,R,F,V,L,r,i]),v.useEffect(()=>{if(t!==void 0){var pe=q?q.state.doc.toString():"";if(q&&t!==pe){var le=ee.current&&!ee.current.isDone,ve=()=>{q&&t!==q.state.doc.toString()&&q.dispatch({changes:{from:0,to:q.state.doc.toString().length,insert:t||""},annotations:[pLe.of(!0)]})};le?ae.current=ve:ve()}}},[t,q]),{state:te,setState:J,view:q,setView:Z,container:G,setContainer:U}}var lMn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],Xc=v.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,g=e.height,y=e.minHeight,b=e.maxHeight,w=e.width,S=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,E=e.indentWithTab,j=e.editable,N=e.readOnly,I=e.root,R=e.initialState,$=Wgt(e,lMn),F=v.useRef(null),D=oMn({root:I,value:s,autoFocus:p,theme:m,height:g,minHeight:y,maxHeight:b,width:w,minWidth:S,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:E,editable:j,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:R}),V=D.state,W=D.view,L=D.container,z=D.setContainer;v.useImperativeHandle(t,()=>({editor:F.current,state:V,view:W}),[F,L,V,W]);var B=v.useCallback(G=>{F.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",SO({ref:B,className:""+M+(n?" "+n:"")},$))});Xc.displayName="CodeMirror";const cMn=async e=>{if(typeof navigator>"u"||!navigator.clipboard?.writeText)return!1;try{return await navigator.clipboard.writeText(e),!0}catch{return!1}},uMn=e=>{if(typeof document>"u"||typeof document.execCommand!="function")return!1;const t=document.createElement("textarea"),n=document.activeElement instanceof HTMLElement?document.activeElement:null;t.value=e,t.setAttribute("readonly",""),t.setAttribute("aria-hidden","true"),t.style.position="fixed",t.style.top="0",t.style.left="0",t.style.width="1px",t.style.height="1px",t.style.opacity="0",t.style.pointerEvents="none",document.body.appendChild(t);try{return t.focus(),t.select(),t.setSelectionRange(0,e.length),document.execCommand("copy")}catch{return!1}finally{t.remove(),n?.focus({preventScroll:!0})}},dMn=async e=>e?await cMn(e)?!0:uMn(e):!1;function $p(e){const{copyMessage:t="Copied to clipboard!",copiedDuration:n=2e3,showToast:r=!0}=e,s="text"in e,a=s?e.text:void 0,[i,l]=v.useState(!1),c=v.useRef(null),u=v.useCallback(f=>{dMn(f).then(p=>{if(!p){r&&De.error("Failed to copy to clipboard.");return}r&&De.success(t),l(!0),c.current&&(clearTimeout(c.current),c.current=null),c.current=setTimeout(()=>{l(!1)},n)})},[n,t,r]),d=v.useCallback(()=>{a&&u(a)},[u,a]);return s?{isCopied:i,handleCopy:d,copyToClipboard:u}:{isCopied:i,copyToClipboard:u}}function ya({content:e,copyMessage:t,tooltip:n="Copy to clipboard",size:r="sm",variant:s,className:a}){const[i,l]=v.useState(!1),{handleCopy:c}=$p({text:e,copyMessage:t}),u=()=>{c(),l(!0),setTimeout(()=>l(!1),2e3)};return o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsx(ue,{onClick:u,type:"button",size:r,variant:s,className:a,"aria-label":i?"Copied!":n,children:i?o.jsx(hx,{}):o.jsx(Mft,{})})}),o.jsx(Bn,{children:i?"Copied!":n})]})}const fMn="mastra-theme",pMn="mastra-playground-store",jpe=e=>e==="dark"||e==="light"||e==="system",hMn=e=>{try{const t=e.getItem(pMn);if(!t)return;const r=JSON.parse(t)?.state?.theme;return jpe(r)?r:void 0}catch{return}},mMn=(e=fMn)=>({get(){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(jpe(t))return t;const n=hMn(window.localStorage);return n?(window.localStorage.setItem(e,n),n):null}catch{return null}},set(t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}},subscribe(t){if(typeof window>"u")return()=>{};const n=r=>{if(r.key===e){if(r.newValue===null){t(null);return}jpe(r.newValue)&&t(r.newValue)}};return window.addEventListener("storage",n),()=>window.removeEventListener("storage",n)}}),Fvt=v.createContext(null),zvt="(prefers-color-scheme: dark)",gMn=typeof window>"u"?v.useEffect:v.useLayoutEffect,Bvt=()=>typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia(zvt).matches?"dark":"light",Uvt=e=>{if(typeof window>"u"||typeof window.matchMedia!="function")return()=>{};const t=window.matchMedia(zvt);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},vMn=(e,t)=>{e.classList.remove(t==="dark"?"light":"dark"),e.classList.add(t)},qvt=({children:e,defaultTheme:t="system",storageKey:n,target:r})=>{const s=v.useMemo(()=>mMn(n),[n]),a=v.useRef(null),[i,l]=v.useState(()=>s.get()??t),c=v.useSyncExternalStore(Uvt,Bvt,()=>"dark");v.useEffect(()=>s.subscribe(f=>l(f??t)),[s,t]);const u=i==="system"?c:i;gMn(()=>{const f=r??(typeof window>"u"?null:window.document.documentElement);a.current&&a.current!==f&&a.current.classList.remove("dark","light"),f&&vMn(f,u),a.current=f},[u,r]);const d=v.useMemo(()=>({theme:i,resolvedTheme:u,systemTheme:c,setTheme:f=>{l(f),s.set(f)}}),[i,u,c,s]);return o.jsx(Fvt.Provider,{value:d,children:e})},yMn=()=>{},$N=()=>{const e=v.useContext(Fvt),t=v.useSyncExternalStore(Uvt,Bvt,()=>"dark");return v.useMemo(()=>e??{theme:"system",resolvedTheme:t,systemTheme:t,setTheme:yMn},[e,t])};function bMn(e){return new yO(y0e.define(e))}const Vvt=[Ym.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Eo(()=>Promise.resolve().then(()=>e6),[],import.meta.url).then(e=>e.javascript())}}),Ym.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Eo(()=>Promise.resolve().then(()=>qNn),void 0,import.meta.url).then(e=>e.json())}}),Ym.of({name:"JSX",extensions:["jsx"],load(){return Eo(()=>Promise.resolve().then(()=>e6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),Ym.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Eo(()=>Promise.resolve().then(()=>D2n),void 0,import.meta.url).then(e=>e.markdown())}}),Ym.of({name:"TSX",extensions:["tsx"],load(){return Eo(()=>Promise.resolve().then(()=>e6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),Ym.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Eo(()=>Promise.resolve().then(()=>e6),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),Ym.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Eo(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>bMn(e.shell))}})];function xMn(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 wMn(e){const t=xMn(e);return Imt({override:[SMn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function SMn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,p)=>{const g=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:g},selection:{anchor:f+g.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const kMn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,OMn=Cn.mark({class:"cm-variable-highlight"}),hLe=new Hht({regexp:kMn,decoration:()=>OMn}),_Mn=yo.fromClass(class{decorations;constructor(e){this.decorations=hLe.createDeco(e)}update(e){this.decorations=hLe.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),CMn=_Mn;function EMn(){const e=AN({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:[fe.className,fe.propertyName],color:"var(--neutral6)"},{tag:fe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.heading1,fe.heading2,fe.heading3,fe.heading4,fe.heading5,fe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:fe.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:fe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:fe.url,color:"var(--accent3)"},{tag:fe.monospace,color:"var(--neutral6)"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=It.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 jMn(){const e=It.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=$g.define([{tag:[fe.comment,fe.bracket],color:"var(--neutral2)"},{tag:[fe.string,fe.meta,fe.regexp],color:"var(--accent1)"},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:"var(--accent6)"},{tag:[fe.keyword,fe.operator,fe.tagName],color:"var(--accent2)"},{tag:[fe.function(fe.propertyName),fe.propertyName],color:"var(--accent5)"},{tag:[fe.definition(fe.variableName),fe.function(fe.variableName),fe.className,fe.attributeName],color:"var(--accent3)"},{tag:[fe.variableName,fe.number],color:"var(--accent5)"},{tag:[fe.name,fe.quote],color:"var(--accent1)"},{tag:fe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.heading1,fe.heading2,fe.heading3,fe.heading4,fe.heading5,fe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[fe.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:fe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:fe.url,color:"var(--accent3)"},{tag:fe.monospace,color:"var(--neutral6)"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:[fe.deleted],color:"var(--accent2)"},{tag:fe.invalid,color:"var(--error)"},{tag:[fe.standard(fe.tagName)],color:"var(--accent1)"}]);return[e,D1(t)]}const Ay=()=>{const e=$N().resolvedTheme==="dark";return v.useMemo(()=>e?EMn():jMn(),[e])},Qr=v.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,...h},m)=>{const g=Ay(),y=e?JSON.stringify(e,null,2):t??"",b=v.useMemo(()=>{const w=[];return f&&w.push(It.lineWrapping),a==="json"?w.push(af):a==="markdown"&&w.push(H0e({base:wO,codeLanguages:Vvt})),i&&a==="markdown"&&w.push(CMn),c&&a==="markdown"&&w.push(wMn(c)),p===!1&&w.push(os.readOnly.of(!0)),w},[a,i,c,p,f]);return o.jsxs("div",{className:K("rounded-md bg-surface3 p-1 font-mono relative border border-border1 overflow-hidden",s),...h,children:[r&&o.jsx(ya,{content:y,className:"absolute top-2 right-2 z-20"}),o.jsx(Xc,{ref:m,value:y,theme:g,extensions:b,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),TMn={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash"};let hK=null;function NMn(){return hK||(hK=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Eo(()=>import("./core-avAmkB1u.js"),__vite__mapDeps([0,1,2]),import.meta.url),Eo(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Eo(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Eo(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Eo(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Eo(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Eo(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Eo(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Eo(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Eo(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Eo(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Eo(()=>import("./python-DhUJRlN_.js"),[],import.meta.url)],engine:t()})})()),hK}async function IMn(e,t){const n=TMn[t?.toLowerCase()];if(!n)return null;const r=await NMn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}const Of=({children:e,className:t,onClick:n})=>o.jsx("div",{tabIndex:n?0:void 0,onKeyDown:r=>{n&&(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n?.())},className:K("flex gap-3 group/entity bg-surface3 rounded-xl border border-border1 py-3 px-4",n&&"cursor-pointer hover:bg-surface4 transition-all",t),onClick:n,children:e}),Hvt=({children:e,className:t,style:n})=>o.jsx(Ue,{size:"lg",className:K("text-neutral3 mt-1 shrink-0",t),style:n,children:e}),_f=({children:e,className:t})=>o.jsx(ge,{as:"p",variant:"ui-lg",className:K("text-neutral6 font-medium",t),children:e}),Zp=({children:e,className:t})=>o.jsx(ge,{as:"div",variant:"ui-sm",className:K("text-neutral3",t),children:e}),Cf=({children:e,className:t})=>o.jsx("div",{className:K("flex-1 w-full",t),children:e});function Ds({resource:e,title:t,description:n,actionSlot:r,className:s}){const a="Permission Denied",i=e?`You don't have permission to access ${e}. Contact your administrator for access.`:"You don't have permission to access this resource. Contact your administrator for access.";return o.jsx(Lr,{className:s,iconSlot:o.jsx(Ue,{size:"lg",className:"text-neutral3",children:o.jsx(gOn,{})}),titleSlot:t??a,descriptionSlot:n??i,actionSlot:r})}function Vs({title:e,description:t,className:n}){const[r,s]=v.useState(!1),a=We(),i=v.useCallback(async()=>{try{s(!0);const{baseUrl:l="",apiPrefix:c}=a.options||{},u=(c||"/api").trim(),d=(u.startsWith("/")?u:`/${u}`).replace(/\/$/,""),f=new URLSearchParams({redirect_uri:window.location.href}),p=`${l}${d}/auth/sso/login?${f}`,h=await fetch(p,{credentials:"include",headers:{"Content-Type":"application/json"}});if(h.ok){const m=await h.json();window.location.href=m.url}}finally{s(!1)}},[a]);return o.jsx(Lr,{className:n,iconSlot:o.jsx(Ue,{size:"lg",className:"text-neutral3",children:o.jsx(Jkn,{})}),titleSlot:e??"Session Expired",descriptionSlot:t??"Your session has expired. Please log in again to continue.",actionSlot:o.jsx(ue,{variant:"default",onClick:i,disabled:r,children:r?"Redirecting...":"Log in"})})}const Vh=e=>o.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 34 21",fill:"none",...e,children:o.jsx("path",{d:"M4.49805 11.6934C6.98237 11.6934 8.99609 13.7081 8.99609 16.1924C8.9959 18.6765 6.98225 20.6904 4.49805 20.6904C2.01394 20.6903 0.000196352 18.6765 0 16.1924C0 13.7081 2.01382 11.6935 4.49805 11.6934ZM10.3867 0C12.8709 0 14.8846 2.01388 14.8848 4.49805C14.8848 4.8377 14.847 5.16846 14.7755 5.48643C14.4618 6.88139 14.1953 8.4633 14.9928 9.65L16.2575 11.5319C16.3363 11.6491 16.4727 11.7115 16.6137 11.703C16.7369 11.6957 16.8525 11.6343 16.9214 11.5318L18.1876 9.64717C18.9772 8.47198 18.7236 6.90783 18.4205 5.52484C18.3523 5.21392 18.3164 4.89094 18.3164 4.55957C18.3167 2.07546 20.3313 0.0615234 22.8154 0.0615234C25.2994 0.0617476 27.3132 2.0756 27.3135 4.55957C27.3135 4.93883 27.2665 5.30712 27.178 5.65896C26.8547 6.94441 26.5817 8.37932 27.2446 9.52714L28.459 11.6301C28.4819 11.6697 28.5245 11.6934 28.5703 11.6934C31.0545 11.6935 33.0684 13.7081 33.0684 16.1924C33.0682 18.6765 31.0544 20.6903 28.5703 20.6904C26.0861 20.6904 24.0725 18.6765 24.0723 16.1924C24.0723 15.8049 24.1212 15.4288 24.2133 15.0701C24.5458 13.7746 24.8298 12.3251 24.1609 11.1668L23.0044 9.16384C22.9656 9.09659 22.8931 9.05859 22.8154 9.05859C22.7983 9.05859 22.7824 9.06614 22.7728 9.08033L21.4896 10.9895C20.686 12.1851 20.9622 13.781 21.284 15.1851C21.3582 15.5089 21.3975 15.8461 21.3975 16.1924C21.3973 18.6764 19.3834 20.6902 16.8994 20.6904C14.4152 20.6904 12.4006 18.6765 12.4004 16.1924C12.4004 15.932 12.4226 15.6768 12.4651 15.4286C12.6859 14.14 12.8459 12.7122 12.1167 11.6271L11.2419 10.3253C10.6829 9.49347 9.71913 9.05932 8.78286 8.70188C7.0906 8.05584 5.88867 6.41734 5.88867 4.49805C5.88886 2.0139 7.90254 3.29835e-05 10.3867 0Z",fill:"currentColor"})}),AMn=sl(K("flex w-full text-neutral6 border bg-transparent","transition-all duration-normal ease-out-custom","placeholder:text-neutral2 placeholder:transition-opacity placeholder:duration-normal","focus:placeholder:opacity-70","min-h-[80px] resize-y"),{variants:{variant:{default:K(hz,"rounded-xl",$k),filled:K(hz,"rounded-xl",$k),outline:K(cft,"rounded-xl",$k),unstyled:uft},size:{sm:"px-2 py-1.5 text-ui-sm",md:"px-3 py-2 text-ui-md",default:"px-3 py-2 text-ui-md",lg:"px-4 py-3 text-ui-lg"}},defaultVariants:{variant:"default",size:"default"}}),Yl=v.forwardRef(({className:e,size:t,testId:n,variant:r,error:s,...a},i)=>o.jsx("textarea",{className:K(AMn({variant:r,size:t}),s&&"border-error focus-visible:border-error",e),"data-testid":n,ref:i,"aria-invalid":s,...a}));Yl.displayName="Textarea";function RMn(e){const{store:t,parentContext:n,actionsRef:r,isDrawer:s}=e,a=t.useState("open");Xdt(t,a),_3(t);const{forceUnmount:i}=C3(a,t),l=v.useCallback(()=>{t.setOpen(!1,Vt(w3))},[t]);return v.useImperativeHandle(r,()=>({unmount:i,close:l}),[i,l]),{parentContext:n,isDrawer:s}}function PMn({store:e,dialogRoot:t}){const{parentContext:n,isDrawer:r}=t,s=e.useState("open"),a=e.useState("disablePointerDismissal"),i=e.useState("modal"),l=e.useState("popupElement"),c=e.useState("floatingRootContext"),[u,d]=v.useState(0),[f,p]=v.useState(0),h=u===0,m=g_(c,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?"intentional":{mouse:i==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}},outsidePress(w){if(!e.context.outsidePressEnabledRef.current||"button"in w&&w.button!==0||"touches"in w&&w.touches.length!==1)return!1;const S=Si(w);if(h&&!a){const k=S;return i&&(e.context.internalBackdropRef.current||e.context.backdropRef.current)?e.context.internalBackdropRef.current===k||e.context.backdropRef.current===k||dn(k,l)&&!k?.hasAttribute("data-base-ui-portal"):!0}return!1},escapeKey:h});cpt(s&&i===!0,l),e.useContextCallback("onNestedDialogOpen",(w,S)=>{d(w),p(S)}),e.useContextCallback("onNestedDialogClose",()=>{d(0),p(0)}),v.useEffect(()=>(n?.onNestedDialogOpen&&s&&n.onNestedDialogOpen(u+1,f+(r?1:0)),n?.onNestedDialogClose&&!s&&n.onNestedDialogClose(),()=>{n?.onNestedDialogClose&&s&&n.onNestedDialogClose()}),[r,s,u,f,n]);const g=m.reference??ms,y=m.trigger??ms,b=v.useMemo(()=>Ro(_y,m.floating),[m.floating]);return E3(e,{activeTriggerProps:g,inactiveTriggerProps:y,popupProps:b,nestedOpenDialogCount:u,nestedOpenDrawerCount:f}),null}const ewe=v.createContext(!1),Wvt=v.createContext(void 0);function kd(e){const t=v.useContext(Wvt);if(e===!1&&t===void 0)throw new Error(Sr(27));return t}const $Mn={...T3,modal:ct(e=>e.modal),nested:ct(e=>e.nested),nestedOpenDialogCount:ct(e=>e.nestedOpenDialogCount),nestedOpenDrawerCount:ct(e=>e.nestedOpenDrawerCount),disablePointerDismissal:ct(e=>e.disablePointerDismissal),openMethod:ct(e=>e.openMethod),descriptionElementId:ct(e=>e.descriptionElementId),titleElementId:ct(e=>e.titleElementId),viewportElement:ct(e=>e.viewportElement),role:ct(e=>e.role)};class twe extends bN{constructor(t,n,r=!1){const s=new v_,a=MMn(t);a.floatingRootContext=kq(s,n,r),super(a,{popupRef:v.createRef(),backdropRef:v.createRef(),internalBackdropRef:v.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:s,onOpenChange:void 0,onOpenChangeComplete:void 0},$Mn)}setOpen=(t,n)=>{if(n.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},!t&&n.trigger==null&&this.state.activeTriggerId!=null&&(n.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(t,n),n.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(t,n);const r={open:t};Sq(r,t,n.trigger),this.update(r)};static useStore(t,n){return wq(t,(s,a)=>new twe(n,s,a),!0).store}}function MMn(e={}){return{...j3(),modal:!0,disablePointerDismissal:!1,popupElement:null,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e}}function Zvt(e,t="dialog"){const{children:n,open:r,defaultOpen:s=!1,onOpenChange:a,onOpenChangeComplete:i,disablePointerDismissal:l=!1,modal:c=!0,actionsRef:u,handle:d,triggerId:f,defaultTriggerId:p=null}=e,h=t==="drawer",m=t==="alert-dialog",g=m?!0:c,y=m||l,b=m?"alertdialog":"dialog",w=kd(!0),k={modal:g,disablePointerDismissal:y,nested:!!w,role:b},_=twe.useStore(d?.store,{open:s,openProp:r,activeTriggerId:p,triggerIdProp:f,...k});f_(()=>{const $=r===void 0&&_.state.open===!1&&s===!0?{open:!0,activeTriggerId:p}:null;m?_.update($?{...k,...$}:k):$&&_.update($)}),_.useControlledProp("openProp",r),_.useControlledProp("triggerIdProp",f),_.useSyncedValues(k),_.useContextCallback("onOpenChange",a),_.useContextCallback("onOpenChangeComplete",i);const C=_.useState("open"),E=_.useState("mounted"),j=_.useState("payload"),N=RMn({store:_,actionsRef:u,parentContext:w?.store.context,isDrawer:h}),I=C||E,R=v.useMemo(()=>({store:_}),[_]);return o.jsx(ewe.Provider,{value:!1,children:o.jsxs(Wvt.Provider,{value:R,children:[I&&o.jsx(PMn,{store:_,dialogRoot:N}),typeof n=="function"?n({payload:j}):n]})})}function DMn(e){return Zvt(e,"alert-dialog")}const LMn={...kf,...ec},Gvt=v.forwardRef(function(t,n){const{render:r,className:s,style:a,forceRender:i=!1,...l}=t,{store:c}=kd(),u=c.useState("open"),d=c.useState("nested"),f=c.useState("mounted"),p=c.useState("transitionStatus");return En("div",t,{state:{open:u,transitionStatus:p},ref:[c.context.backdropRef,n],stateAttributesMapping:LMn,props:[{role:"presentation",hidden:!f,style:{userSelect:"none",WebkitUserSelect:"none"}},l],enabled:i||!d})}),V3=v.forwardRef(function(t,n){const{render:r,className:s,style:a,disabled:i=!1,nativeButton:l=!0,...c}=t,{store:u}=kd(),d=u.useState("open"),{getButtonProps:f,buttonRef:p}=Sd({disabled:i,native:l}),h={disabled:i};function m(g){d&&u.setOpen(!1,Vt(qbe,g.nativeEvent))}return En("button",t,{state:h,ref:[n,p],props:[{onClick:m},c,f]})}),nwe=v.forwardRef(function(t,n){const{render:r,className:s,style:a,id:i,...l}=t,{store:c}=kd(),u=Li(i);return c.useSyncedValueWithCleanup("descriptionElementId",u),En("p",t,{ref:n,props:[{id:u},l]})});let FMn=(function(e){return e.nestedDialogs="--nested-dialogs",e})({}),zMn=(function(e){return e[e.open=ld.open]="open",e[e.closed=ld.closed]="closed",e[e.startingStyle=ld.startingStyle]="startingStyle",e[e.endingStyle=ld.endingStyle]="endingStyle",e.nested="data-nested",e.nestedDialogOpen="data-nested-dialog-open",e})({});const Qvt=v.createContext(void 0);function rwe(){const e=v.useContext(Qvt);if(e===void 0)throw new Error(Sr(26));return e}const mj="ArrowUp",kk="ArrowDown",k$="ArrowLeft",gj="ArrowRight",H3="Home",W3="End",Yvt="PageUp",Xvt="PageDown",Kvt=new Set([k$,gj]),BMn=new Set([k$,gj,H3,W3]),Jvt=new Set([mj,kk]),UMn=new Set([mj,kk,H3,W3]),eyt=new Set([...Kvt,...Jvt]),F1=new Set([...eyt,H3,W3]),tyt="Shift",qMn="Control",VMn="Alt",HMn="Meta",WMn=new Set([tyt,qMn,VMn,HMn]);function ZMn(e){return Ia(e)&&e.tagName==="INPUT"}function mLe(e){return!!(ZMn(e)&&e.selectionStart!=null||Ia(e)&&e.tagName==="TEXTAREA")}function gLe(e,t,n,r){if(!e||!t||!t.scrollTo)return;let s=e.scrollLeft,a=e.scrollTop;const i=e.clientWidth<e.scrollWidth,l=e.clientHeight<e.scrollHeight;if(i&&r!=="vertical"){const c=vLe(e,t,"left"),u=a6(e),d=a6(t);n==="ltr"&&(c+t.offsetWidth+d.scrollMarginRight>e.scrollLeft+e.clientWidth-u.scrollPaddingRight?s=c+t.offsetWidth+d.scrollMarginRight-e.clientWidth+u.scrollPaddingRight:c-d.scrollMarginLeft<e.scrollLeft+u.scrollPaddingLeft&&(s=c-d.scrollMarginLeft-u.scrollPaddingLeft)),n==="rtl"&&(c-d.scrollMarginRight<e.scrollLeft+u.scrollPaddingLeft?s=c-d.scrollMarginLeft-u.scrollPaddingLeft:c+t.offsetWidth+d.scrollMarginRight>e.scrollLeft+e.clientWidth-u.scrollPaddingRight&&(s=c+t.offsetWidth+d.scrollMarginRight-e.clientWidth+u.scrollPaddingRight))}if(l&&r!=="horizontal"){const c=vLe(e,t,"top"),u=a6(e),d=a6(t);c-d.scrollMarginTop<e.scrollTop+u.scrollPaddingTop?a=c-d.scrollMarginTop-u.scrollPaddingTop:c+t.offsetHeight+d.scrollMarginBottom>e.scrollTop+e.clientHeight-u.scrollPaddingBottom&&(a=c+t.offsetHeight+d.scrollMarginBottom-e.clientHeight+u.scrollPaddingBottom)}e.scrollTo({left:s,top:a,behavior:"auto"})}function vLe(e,t,n){const r=n==="left"?"offsetLeft":"offsetTop";let s=0;for(;t.offsetParent&&(s+=t[r],t.offsetParent!==e);)t=t.offsetParent;return s}function a6(e){const t=getComputedStyle(e);return{scrollMarginTop:parseFloat(t.scrollMarginTop)||0,scrollMarginRight:parseFloat(t.scrollMarginRight)||0,scrollMarginBottom:parseFloat(t.scrollMarginBottom)||0,scrollMarginLeft:parseFloat(t.scrollMarginLeft)||0,scrollPaddingTop:parseFloat(t.scrollPaddingTop)||0,scrollPaddingRight:parseFloat(t.scrollPaddingRight)||0,scrollPaddingBottom:parseFloat(t.scrollPaddingBottom)||0,scrollPaddingLeft:parseFloat(t.scrollPaddingLeft)||0}}const GMn={...kf,...ec,nestedDialogOpen(e){return e?{[zMn.nestedDialogOpen]:""}:null}},nyt=v.forwardRef(function(t,n){const{render:r,className:s,style:a,finalFocus:i,initialFocus:l,...c}=t,{store:u}=kd(),d=u.useState("descriptionElementId"),f=u.useState("disablePointerDismissal"),p=u.useState("floatingRootContext"),h=u.useState("popupProps"),m=u.useState("modal"),g=u.useState("mounted"),y=u.useState("nested"),b=u.useState("nestedOpenDialogCount"),w=u.useState("open"),S=u.useState("openMethod"),k=u.useState("titleElementId"),_=u.useState("transitionStatus"),C=u.useState("role"),E=p.useState("floatingId"),j=c.id??E;rwe(),tc({open:w,ref:u.context.popupRef,onComplete(){w&&u.context.onOpenChangeComplete?.(!0)}});function N(V){return V==="touch"?u.context.popupRef.current:!0}const I=l===void 0?N:l,R=b>0,$=u.useStateSetter("popupElement"),D=En("div",t,{state:{open:w,nested:y,transitionStatus:_,nestedDialogOpen:R},props:[h,{id:j,"aria-labelledby":k??void 0,"aria-describedby":d??void 0,role:C,..._y,hidden:!g,onKeyDown(V){F1.has(V.key)&&V.stopPropagation()},style:{[FMn.nestedDialogs]:b}},c],ref:[n,u.context.popupRef,$],stateAttributesMapping:GMn});return o.jsx(yN,{context:p,openInteractionType:S,disabled:!g,closeOnFocusOut:!f,initialFocus:I,returnFocus:i,modal:m!==!1,restoreFocus:"popup",children:D})}),swe=v.forwardRef(function(t,n){const{keepMounted:r=!1,...s}=t,{store:a}=kd(),i=a.useState("mounted"),l=a.useState("modal"),c=a.useState("open");return i||r?o.jsx(Qvt.Provider,{value:r,children:o.jsxs(k3,{ref:n,...s,children:[i&&l===!0&&o.jsx(P3,{ref:a.context.internalBackdropRef,inert:kN(!c)}),t.children]})}):null}),awe=v.forwardRef(function(t,n){const{render:r,className:s,style:a,id:i,...l}=t,{store:c}=kd(),u=Li(i);return c.useSyncedValueWithCleanup("titleElementId",u),En("h2",t,{ref:n,props:[{id:u},l]})}),iwe=v.forwardRef(function(t,n){const{render:r,className:s,style:a,disabled:i=!1,nativeButton:l=!0,id:c,payload:u,handle:d,...f}=t,p=kd(!0),h=d?.store??p?.store;if(!h)throw new Error(Sr(79));const m=Li(c),g=h.useState("floatingRootContext"),y=h.useState("isOpenedByTrigger",m),b=h.useState("triggerPopupId",m),w=v.useRef(null),{registerTrigger:S,isMountedByThisTrigger:k}=O3(m,w,h,{payload:u}),{getButtonProps:_,buttonRef:C}=Sd({disabled:i,native:l}),E=m_(g,{enabled:g!=null}),j=$xe(()=>h.select("open"),R=>{h.set("openMethod",R)}),N={disabled:i,open:y},I=h.useState("triggerProps",k);return En("button",t,{state:N,ref:[C,n,S,w],props:[E.reference,I,j,{[Ybe]:"",id:m,"aria-haspopup":"dialog","aria-expanded":y,"aria-controls":b},f,_],stateAttributesMapping:xN})}),QMn=iwe;let yLe=(function(e){return e[e.open=ld.open]="open",e[e.closed=ld.closed]="closed",e[e.startingStyle=ld.startingStyle]="startingStyle",e[e.endingStyle=ld.endingStyle]="endingStyle",e.nested="data-nested",e.nestedDialogOpen="data-nested-dialog-open",e})({});const YMn={...kf,...ec,nested(e){return e?{[yLe.nested]:""}:null},nestedDialogOpen(e){return e?{[yLe.nestedDialogOpen]:""}:null}},XMn=v.forwardRef(function(t,n){const{render:r,className:s,style:a,children:i,...l}=t,c=rwe(),{store:u}=kd(),d=u.useState("open"),f=u.useState("nested"),p=u.useState("transitionStatus"),h=u.useState("nestedOpenDialogCount"),m=u.useState("mounted"),g=u.useStateSetter("viewportElement"),y=h>0;return En("div",t,{enabled:c||m,state:{open:d,nested:f,transitionStatus:p,nestedDialogOpen:y},ref:[n,g],stateAttributesMapping:YMn,props:[{role:"presentation",hidden:!m,style:{pointerEvents:d?void 0:"none"},children:i},l]})});function Z3(e,t){return e&&v.isValidElement(t)?{render:t}:void 0}const KMn=DMn;function Tt({open:e,onOpenChange:t,children:n}){return o.jsx(KMn,{open:e,onOpenChange:t,children:n})}const ryt=v.forwardRef(({asChild:e,children:t,...n},r)=>o.jsx(QMn,{ref:r,...Z3(e,t),...n,children:e?void 0:t}));ryt.displayName="AlertDialogTrigger";const syt=swe,owe=v.forwardRef(({className:e,...t},n)=>o.jsx(Gvt,{ref:n,className:K("dialog-overlay-anim fixed inset-0 z-50 bg-overlay backdrop-blur-xs",e),...t}));owe.displayName="AlertDialogOverlay";const ayt=v.forwardRef(({className:e,...t},n)=>o.jsxs(syt,{children:[o.jsx(owe,{}),o.jsx(nyt,{ref:n,"data-slot":"alert-dialog-content",className:K("dialog-content-anim","fixed left-[50%] top-[50%] z-50 grid translate-x-[-50%] translate-y-[-50%]","w-full max-w-[calc(100%-2rem)] sm:max-w-lg","rounded-xl border border-border1/40 bg-surface2/96 backdrop-blur-md shadow-dialog",e),...t})]}));ayt.displayName="AlertDialogContent";const iyt=({className:e,...t})=>o.jsx("div",{className:K("flex flex-col gap-0.5 px-4 py-3 text-left",e),...t});iyt.displayName="AlertDialogHeader";const oyt=({className:e,...t})=>o.jsx("div",{className:K("flex flex-col-reverse gap-1.5 px-4 py-2.5 sm:flex-row sm:justify-end",e),...t});oyt.displayName="AlertDialogFooter";const lyt=({className:e,...t})=>o.jsx("div",{className:K("overflow-y-auto px-4 py-3.5 max-h-[50vh]",e),...t});lyt.displayName="AlertDialogBody";const cyt=v.forwardRef(({className:e,...t},n)=>o.jsx(awe,{ref:n,className:K("text-ui-md font-medium",e),...t}));cyt.displayName="AlertDialogTitle";const uyt=v.forwardRef(({className:e,...t},n)=>o.jsx(nwe,{ref:n,className:K("text-ui-sm text-neutral3",e),...t}));uyt.displayName="AlertDialogDescription";const dyt=v.forwardRef(({className:e,...t},n)=>o.jsx(V3,{ref:n,className:K(A3({variant:"primary",size:"lg"}),e),...t}));dyt.displayName="AlertDialogAction";const fyt=v.forwardRef(({className:e,...t},n)=>o.jsx(V3,{ref:n,className:K(A3({variant:"default",size:"lg"}),e),...t}));fyt.displayName="AlertDialogCancel";Tt.Trigger=ryt;Tt.Portal=syt;Tt.Overlay=owe;Tt.Content=ayt;Tt.Header=iyt;Tt.Footer=oyt;Tt.Body=lyt;Tt.Title=cyt;Tt.Description=uyt;Tt.Action=dyt;Tt.Cancel=fyt;function JMn(e){if(!e)return null;for(const t of e.elements){const n=t.tagName;if(n==="BUTTON"||n==="INPUT"){const r=t;if(r.type==="submit")return r}}return null}let bLe=(function(e){return e.checked="data-checked",e.unchecked="data-unchecked",e.indeterminate="data-indeterminate",e.disabled="data-disabled",e.readonly="data-readonly",e.required="data-required",e.valid="data-valid",e.invalid="data-invalid",e.touched="data-touched",e.dirty="data-dirty",e.filled="data-filled",e.focused="data-focused",e})({});function pyt(e){return v.useMemo(()=>({checked(t){return e.indeterminate?{}:t?{[bLe.checked]:""}:{[bLe.unchecked]:""}},...M1}),[e.indeterminate])}const e3n=v.createContext({disabled:!1});function hyt(){return v.useContext(e3n)}function lwe(e,t,n,r=!0,s){const[a,i]=v.useState(),l=Li(s?`${s}-label`:void 0),c=e??t??a;return Nt(()=>{const u=e||t||!r?void 0:t3n(n.current,l);a!==u&&i(u)}),c}function t3n(e,t){const n=n3n(e);if(n)return!n.id&&t&&(n.id=t),n.id||void 0}function n3n(e){if(!e)return;const t=e.parentElement;if(t&&t.tagName==="LABEL")return t;const n=e.id;if(n){const s=e.nextElementSibling;if(s&&s.htmlFor===n)return s}const r=e.labels;return r&&r[0]}const r3n=v.createContext(void 0);function s3n(e=!0){const t=v.useContext(r3n);if(t===void 0&&!e)throw new Error(Sr(3));return t}const myt=v.createContext(void 0);function a3n(){const e=v.useContext(myt);if(e===void 0)throw new Error(Sr(14));return e}const i3n="data-parent",o3n=v.forwardRef(function(t,n){const{checked:r,className:s,defaultChecked:a=!1,"aria-labelledby":i,disabled:l=!1,form:c,id:u,indeterminate:d=!1,inputRef:f,name:p,onCheckedChange:h,parent:m=!1,readOnly:g=!1,render:y,required:b=!1,uncheckedValue:w,value:S,nativeButton:k=!1,style:_,...C}=t,{clearErrors:E}=_N(),{disabled:j,name:N,setDirty:I,setFilled:R,setFocused:$,setTouched:F,state:D,validationMode:V,validityData:W,shouldValidateOnChange:L,validation:z}=vm(),B=hyt(),{labelId:M,controlId:G,registerControlId:U,getDescriptionProps:P}=zx(),q=s3n(),Z=q?.parent,X=Z&&q.allValues,te=j||B.disabled||q?.disabled||l,J=N??p,ee=S??J,ae=Li(),de=Li();let Y=G;X?Y=m?de:`${Z.id}-${ee}`:u&&(Y=u);let ne={};X&&(m?ne=q.parent.getParentProps():ee&&(ne=q.parent.getChildProps(ee)));const{checked:ce=r,indeterminate:pe=d,onCheckedChange:le,...ve}=ne,ye=q?.value,Se=q?.setValue,Ne=q?.defaultValue,ke=v.useRef(null),Ie=Sc(()=>Symbol("checkbox-control")),ze=v.useRef(!1),{getButtonProps:oe,buttonRef:se}=Sd({disabled:te,native:k}),re=q?.validation??z,[he,xe]=sf({controlled:ee&&ye&&!m?ye.includes(ee):ce,default:ee&&Ne&&!m?Ne.includes(ee):a,name:"Checkbox",state:"checked"});Nt(()=>{U!==ga&&(ze.current=!0,U(Ie.current,Y))},[Y,U,Ie]),v.useEffect(()=>{const qe=Ie.current;return()=>{!ze.current||U===ga||(ze.current=!1,U(qe,void 0))}},[U,Ie]),ON(ke,ae,he,void 0,!q);const Ee=v.useRef(null),Pe=Ru(f,Ee,re.inputRef),Qe=lwe(i,M,Ee,!k,Y??void 0);Nt(()=>{Ee.current&&(Ee.current.indeterminate=pe,he&&R(!0))},[he,pe,R]),Rv(he,()=>{q&&!m||(E(J),R(he),I(he!==W.initialValue),L()?re.commit(he):re.commit(he,!0))});const Ze=Ro({checked:he,disabled:te,form:c,name:m?void 0:J,id:k?void 0:Y??void 0,required:b,ref:Pe,style:J?vN:t1,tabIndex:-1,type:"checkbox","aria-hidden":!0,onChange(qe){if(qe.nativeEvent.defaultPrevented)return;if(g){qe.preventDefault();return}const Ke=qe.currentTarget.checked,Ge=Vt(No,qe.nativeEvent);if(le?.(Ke,Ge),h?.(Ke,Ge),!Ge.isCanceled&&(xe(Ke),ee&&ye&&Se&&!m&&!X)){const Ot=Ke?[...ye,ee]:ye.filter(yt=>yt!==ee);Se(Ot,Ge)}},onFocus(){ke.current?.focus()}},S!==void 0?{value:(q?he&&S:S)||""}:ms,P,q?re.getValidationProps:re.getInputValidationProps),Ce=X?!!ce:he,je=X&&pe||d;v.useEffect(()=>{if(!Z||!ee)return;const qe=Z.disabledStatesRef.current;return qe.set(ee,te),()=>{qe.delete(ee)}},[Z,te,ee]);const _e=v.useMemo(()=>({...D,checked:Ce,disabled:te,readOnly:g,required:b,indeterminate:je}),[D,Ce,te,g,b,je]),Oe=pyt(_e),Re=En("span",t,{state:_e,ref:[se,ke,n,q?.registerControlRef],props:[{id:k?Y??void 0:ae,role:"checkbox","aria-checked":pe?"mixed":he,"aria-readonly":g||void 0,"aria-required":b||void 0,"aria-labelledby":Qe,[i3n]:m?"":void 0,onFocus(){$(!0)},onBlur(){const qe=Ee.current;qe&&(F(!0),$(!1),V==="onBlur"&&re.commit(q?ye:qe.checked))},onKeyDown(qe){if(qe.key!=="Enter"||(qe.preventBaseUIHandler(),qe.defaultPrevented))return;const Ke=Ee.current?.form??null,Ge=qe.currentTarget,Ot=qe.nativeEvent,yt=qe.preventDefault,nn=Ot.preventDefault;let bt=!1;qe.preventDefault=()=>{bt=!0,yt.call(qe)},Ot.preventDefault=()=>{bt=!0,nn.call(Ot)},nn.call(Ot),Ks(Ge).queueMicrotask(()=>{qe.preventDefault=yt,Ot.preventDefault=nn,bt||JMn(Ke)?.click()})},onClick(qe){if(g||te)return;qe.preventDefault();const Ke=Ee.current;Ke&&Ke.dispatchEvent(new(Ks(Ke)).PointerEvent("click",{bubbles:!0,shiftKey:qe.shiftKey,ctrlKey:qe.ctrlKey,altKey:qe.altKey,metaKey:qe.metaKey}))}},P,re.getValidationProps,C,ve,oe],stateAttributesMapping:Oe});return o.jsxs(myt.Provider,{value:_e,children:[Re,!he&&!q&&J&&!m&&w!==void 0&&o.jsx("input",{type:"hidden",form:c,name:J,value:w}),o.jsx("input",{...Ze,suppressHydrationWarning:!0})]})}),l3n=v.forwardRef(function(t,n){const{render:r,className:s,style:a,keepMounted:i=!1,...l}=t,c=a3n(),u=c.checked||c.indeterminate,{mounted:d,transitionStatus:f,setMounted:p}=Ag(u),h=v.useRef(null),m={...c,transitionStatus:f};tc({open:u,ref:h,onComplete(){u||p(!1)}});const y={...pyt(c),...ec,...M1},b=i||d,w=En("span",t,{ref:[n,h],state:m,stateAttributesMapping:y,props:l});return b?w:null}),$o=v.forwardRef(({className:e,checked:t,indeterminate:n,...r},s)=>{const a=t==="indeterminate";return o.jsx(o3n,{ref:s,checked:a?!1:t,indeterminate:n??a,"data-slot":"checkbox",className:K("peer flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[0.3125rem]","border border-neutral6/[0.06] bg-neutral6/[0.12] text-surface1 outline-hidden",is.all,"hover:border-neutral6/[0.12] hover:bg-neutral6/[0.16]","active:scale-95 active:border-neutral6/[0.18] active:bg-neutral6/[0.18]","focus-visible:border-neutral5/50 focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-neutral5/55","data-[checked]:border-neutral6 data-[checked]:bg-neutral6 data-[checked]:text-surface1","data-[indeterminate]:border-neutral6 data-[indeterminate]:bg-neutral6 data-[indeterminate]:text-surface1","data-[checked]:hover:border-neutral5 data-[checked]:hover:bg-neutral5","data-[indeterminate]:hover:border-neutral5 data-[indeterminate]:hover:bg-neutral5","data-[checked]:active:border-neutral4 data-[checked]:active:bg-neutral4","data-[indeterminate]:active:border-neutral4 data-[indeterminate]:active:bg-neutral4","data-[disabled]:cursor-not-allowed data-[disabled]:border-neutral6/[0.38] data-[disabled]:bg-neutral6/[0.38] data-[disabled]:hover:border-neutral6/[0.38] data-[disabled]:hover:bg-neutral6/[0.38] data-[disabled]:active:scale-100","data-[disabled]:data-[checked]:border-neutral6/[0.38] data-[disabled]:data-[checked]:bg-neutral6/[0.38] data-[disabled]:data-[checked]:text-neutral6","data-[disabled]:data-[indeterminate]:border-neutral6/[0.38] data-[disabled]:data-[indeterminate]:bg-neutral6/[0.38] data-[disabled]:data-[indeterminate]:text-neutral6",e),...r,children:o.jsx(l3n,{keepMounted:!0,className:K("group/checkbox-indicator flex items-center justify-center text-current","opacity-0 scale-75 transition-[opacity,transform] duration-200 ease-out-custom","data-[checked]:opacity-100 data-[checked]:scale-100","data-[indeterminate]:opacity-100 data-[indeterminate]:scale-100","data-[starting-style]:opacity-0 data-[starting-style]:scale-75","data-[ending-style]:opacity-0 data-[ending-style]:scale-75"),children:o.jsx(c3n,{})})})});$o.displayName="Checkbox";function c3n(){return o.jsxs(o.Fragment,{children:[o.jsx(hx,{className:K("size-3 scale-95 stroke-[3.25] transition-[stroke-dashoffset,transform] duration-200 ease-out-custom","[stroke-dasharray:28] [stroke-dashoffset:28]","group-data-[checked]/checkbox-indicator:[stroke-dashoffset:0]","group-data-[checked]/checkbox-indicator:scale-100","group-data-[indeterminate]/checkbox-indicator:hidden")}),o.jsx(aOn,{className:K("hidden size-3 scale-95 stroke-[3.25] transition-transform duration-200 ease-out-custom","group-data-[indeterminate]/checkbox-indicator:block","group-data-[indeterminate]/checkbox-indicator:scale-100")})]})}function u3n(e){const{open:t,defaultOpen:n,onOpenChange:r,disabled:s}=e,[a,i]=sf({controlled:t,default:n,name:"Collapsible",state:"open"}),{mounted:l,setMounted:c,transitionStatus:u}=Ag(a,!0,!0),d=Li(),[f,p]=v.useState(),h=f??d,m=mt(g=>{const y=!a,b=Vt(xg,g.nativeEvent);r(y,b),!b.isCanceled&&i(y)});return v.useMemo(()=>({disabled:s,handleTrigger:m,mounted:l,open:a,panelId:h,setMounted:c,setOpen:i,setPanelIdState:p,transitionStatus:u}),[s,m,l,a,h,c,i,p,u])}const gyt=v.createContext(void 0);function vyt(){const e=v.useContext(gyt);if(e===void 0)throw new Error(Sr(15));return e}let cwe=(function(e){return e.open="data-open",e.closed="data-closed",e[e.startingStyle=wg.startingStyle]="startingStyle",e[e.endingStyle=wg.endingStyle]="endingStyle",e})({}),d3n=(function(e){return e.panelOpen="data-panel-open",e})({});const f3n={[cwe.open]:""},p3n={[cwe.closed]:""},h3n={open(e){return e?{[d3n.panelOpen]:""}:null}},m3n={open(e){return e?f3n:p3n}},yyt={...m3n,...ec},g3n=v.forwardRef(function(t,n){const{render:r,className:s,defaultOpen:a=!1,disabled:i=!1,onOpenChange:l,open:c,style:u,...d}=t,f=mt(l),p=u3n({open:c,defaultOpen:a,onOpenChange:f,disabled:i}),h=v.useMemo(()=>({open:p.open,disabled:p.disabled,transitionStatus:p.transitionStatus}),[p.open,p.disabled,p.transitionStatus]),m=v.useMemo(()=>({...p,onOpenChange:f,state:h}),[p,f,h]),g=En("div",t,{state:h,ref:n,props:d,stateAttributesMapping:yyt});return o.jsx(gyt.Provider,{value:m,children:g})}),v3n={...h3n,...ec},y3n=v.forwardRef(function(t,n){const{panelId:r,open:s,handleTrigger:a,state:i,disabled:l}=vyt(),{className:c,disabled:u=l,id:d,render:f,nativeButton:p=!0,style:h,...m}=t,{getButtonProps:g,buttonRef:y}=Sd({disabled:u,focusableWhenDisabled:!0,native:p});return En("button",t,{state:i,ref:[n,y],props:[{"aria-controls":s?r:void 0,"aria-expanded":s,onClick:a},m,g],stateAttributesMapping:v3n})}),zA={height:void 0,width:void 0};function b3n(e){const{externalRef:t,hiddenUntilFound:n,id:r,keepMounted:s,mounted:a,onOpenChange:i,open:l,setMounted:c,setOpen:u,transitionStatus:d}=e,f=v.useRef(null),p=v.useRef(null),[h,m]=v.useState(zA),g=v.useRef(zA),y=v.useRef(!1),b=v.useRef(l),w=v.useRef(!1),[S,k]=v.useState(!1),_=v.useRef(null),C=Ru(t,f),E=Yi({mounted:a,open:l}),j=xq(f,!1,!1),N=!l&&!a,I=S?"idle":d,R=l&&(b.current||w.current),$=!l&&a&&p.current==="css-animation"&&h.height===void 0&&h.width===void 0?g.current:h,F=n&&N&&p.current!=="css-animation",D=mt((B,M=!0)=>{M&&(g.current=B),m(B)}),V=mt(()=>{_.current?.(),_.current=null}),W=mt(B=>{V(),_.current=()=>{_.current=null,B()}}),L=mt(()=>{l&&a&&p.current==="css-animation"&&(w.current=!0)});Nt(()=>{!S||d==="starting"||k(!1)},[S,d]),v.useEffect(()=>()=>{L(),V()},[L,V]),Nt(()=>{const B=f.current;if(!B)return;!l&&_.current&&V();const M=x3n(B,R);if(p.current=M,l&&d==="idle"&&b.current&&M==="css-animation"){g.current=AC(B);return}if(l&&d==="starting"){const P=y.current;if(y.current=!1,M==="none"){D(AC(B)),k(!0);return}if(M==="css-transition"){const q=w3n(B);if(D(AC(B)),!P)return q;const Z=BA(B,"transition-duration","0s");return W(Z),k(!0),q}if(M==="css-animation"){if(D(AC(B)),!P){BA(B,"animation-name","none")();return}const q=BA(B,"animation-name","none"),Z=BA(B,"animation-duration","0s");q(),W(Z),k(!0);return}}if(!l&&a&&(d==="idle"||d==="starting")){if(M==="none"){D(zA,!1),c(!1);return}M==="css-animation"&&(b.current=!1,w.current=!1),D(AC(B));return}if(d!=="ending")return;if(M==="none"){c(!1);return}const G=AC(B);if(!((G.height??0)>0||(G.width??0)>0)){c(!1);return}D(G),M==="css-animation"&&BA(B,"animation-name","none")()},[a,l,V,D,c,W,R,d]),tc({enabled:l&&a&&I==="idle",open:!0,ref:f,onComplete(){l&&D(zA,!1)}}),v.useEffect(()=>{if(l||!a||I!=="ending"||!f.current)return;const M=new AbortController;let G=-1;function U(){E.current.open||(c(!1),D(zA,!1))}return G=Bd.request(()=>{M.signal.aborted||j(U,M.signal)}),()=>{Bd.cancel(G),M.abort()}},[E,a,l,I,j,D,c]),Nt(()=>{const B=f.current;!B||!n||!N||B.setAttribute("hidden","until-found")},[N,n]),v.useEffect(function(){const M=f.current;if(!M)return;function G(U){y.current=!0,u(!0),i(!0,Vt(No,U))}return Ur(M,"beforematch",G)},[i,u]);const z=s||n||a||l;return{height:$.height,props:{...F?{[cwe.startingStyle]:""}:void 0,hidden:N,id:r},ref:C,shouldPreventOpenAnimation:R,shouldRender:z,transitionStatus:I,width:$.width}}function AC(e){return{height:e.scrollHeight,width:e.scrollWidth}}function x3n(e,t=!1){const n=Ks(e).getComputedStyle(e),r=(n.animationName.split(",").map(a=>a.trim()).some(a=>a!==""&&a!=="none")||t)&&xLe(n.animationDuration),s=xLe(n.transitionDuration);return r&&s||s?"css-transition":r?"css-animation":"none"}function xLe(e){return e.split(",").map(t=>t.trim()).some(t=>t!==""&&Number.parseFloat(t)>0)}function BA(e,t,n){const r=e.style.getPropertyValue(t),s=e.style.getPropertyPriority(t);return e.style.setProperty(t,n),()=>{if(r===""){e.style.removeProperty(t);return}e.style.setProperty(t,r,s)}}function w3n(e){const t={"justify-content":e.style.justifyContent,"align-items":e.style.alignItems,"align-content":e.style.alignContent,"justify-items":e.style.justifyItems};Object.keys(t).forEach(s=>{e.style.setProperty(s,"initial","important")});function n(){Object.entries(t).forEach(([s,a])=>{if(a===""){e.style.removeProperty(s);return}e.style.setProperty(s,a)})}const r=Bd.request(n);return()=>{Bd.cancel(r),n()}}let wLe=(function(e){return e.collapsiblePanelHeight="--collapsible-panel-height",e.collapsiblePanelWidth="--collapsible-panel-width",e})({});const S3n=v.forwardRef(function(t,n){const{className:r,hiddenUntilFound:s,keepMounted:a,render:i,id:l,style:c,...u}=t,{mounted:d,onOpenChange:f,open:p,panelId:h,setMounted:m,setPanelIdState:g,setOpen:y,state:b,transitionStatus:w}=vyt(),S=s??!1,k=a??!1;Nt(()=>{if(l)return g(l),()=>{g(void 0)}},[l,g]);const{height:_,props:C,ref:E,shouldPreventOpenAnimation:j,shouldRender:N,transitionStatus:I,width:R}=b3n({externalRef:n,hiddenUntilFound:S,id:h,keepMounted:k,mounted:d,onOpenChange:f,open:p,setMounted:m,setOpen:y,transitionStatus:w}),$={...b,transitionStatus:I},F=Idt(c,$),D=En("div",{...t,style:void 0},{state:$,ref:E,props:[C,{style:{[wLe.collapsiblePanelHeight]:_===void 0?"auto":`${_}px`,[wLe.collapsiblePanelWidth]:R===void 0?"auto":`${R}px`}},u,F?{style:F}:void 0,j?{style:{animationName:"none"}}:void 0],stateAttributesMapping:yyt});return N?D:null}),Mp=g3n,mf=Le.forwardRef(({className:e,asChild:t,children:n,...r},s)=>{const a=t&&Le.isValidElement(n)?{render:n}:{};return o.jsx(y3n,{ref:s,"data-slot":"collapsible-trigger",className:K("-outline-offset-2",is.colors,$3.visible,"hover:text-neutral5","[&>svg]:transition-transform [&>svg]:duration-normal [&>svg]:ease-out-custom","[&[data-panel-open]>svg]:rotate-90",e),...a,...r,children:t?void 0:n})});mf.displayName="CollapsibleTrigger";const gf=Le.forwardRef(({className:e,children:t,...n},r)=>o.jsx(S3n,{ref:r,"data-slot":"collapsible-content",className:K("overflow-hidden","h-[var(--collapsible-panel-height)] transition-[height] duration-normal ease-out-custom","data-[starting-style]:h-0 data-[ending-style]:h-0"),...n,children:o.jsx("div",{className:e,children:t})}));gf.displayName="CollapsibleContent";var SLe=1,k3n=.9,O3n=.8,_3n=.17,mK=.1,gK=.999,C3n=.9999,E3n=.99,j3n=/[\\\/_+.#"@\[\(\{&]/,T3n=/[\\\/_+.#"@\[\(\{&]/g,N3n=/[\s-]/,byt=/[\s-]/g;function Tpe(e,t,n,r,s,a,i){if(a===t.length)return s===e.length?SLe:E3n;var l=`${s},${a}`;if(i[l]!==void 0)return i[l];for(var c=r.charAt(a),u=n.indexOf(c,s),d=0,f,p,h,m;u>=0;)f=Tpe(e,t,n,r,u+1,a+1,i),f>d&&(u===s?f*=SLe:j3n.test(e.charAt(u-1))?(f*=O3n,h=e.slice(s,u-1).match(T3n),h&&s>0&&(f*=Math.pow(gK,h.length))):N3n.test(e.charAt(u-1))?(f*=k3n,m=e.slice(s,u-1).match(byt),m&&s>0&&(f*=Math.pow(gK,m.length))):(f*=_3n,s>0&&(f*=Math.pow(gK,u-s))),e.charAt(u)!==t.charAt(a)&&(f*=C3n)),(f<mK&&n.charAt(u-1)===r.charAt(a+1)||r.charAt(a+1)===r.charAt(a)&&n.charAt(u-1)!==r.charAt(a))&&(p=Tpe(e,t,n,r,u+1,a+2,i),p*mK>f&&(f=p*mK)),f>d&&(d=f),u=n.indexOf(c,u+1);return i[l]=d,d}function kLe(e){return e.toLowerCase().replace(byt," ")}function I3n(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tpe(e,t,kLe(e),kLe(t),0,0,{})}var vK="focusScope.autoFocusOnMount",yK="focusScope.autoFocusOnUnmount",OLe={bubbles:!1,cancelable:!0},A3n="FocusScope",xyt=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:a,...i}=e,[l,c]=v.useState(null),u=Hj(s),d=Hj(a),f=v.useRef(null),p=Ig(t,g=>c(g)),h=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let g=function(S){if(h.paused||!l)return;const k=S.target;l.contains(k)?f.current=k:G0(f.current,{select:!0})},y=function(S){if(h.paused||!l)return;const k=S.relatedTarget;k!==null&&(l.contains(k)||G0(f.current,{select:!0}))},b=function(S){if(document.activeElement===document.body)for(const _ of S)_.removedNodes.length>0&&G0(l)};document.addEventListener("focusin",g),document.addEventListener("focusout",y);const w=new MutationObserver(b);return l&&w.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",y),w.disconnect()}}},[r,l,h.paused]),v.useEffect(()=>{if(l){CLe.add(h);const g=document.activeElement;if(!l.contains(g)){const b=new CustomEvent(vK,OLe);l.addEventListener(vK,u),l.dispatchEvent(b),b.defaultPrevented||(R3n(L3n(wyt(l)),{select:!0}),document.activeElement===g&&G0(l))}return()=>{l.removeEventListener(vK,u),setTimeout(()=>{const b=new CustomEvent(yK,OLe);l.addEventListener(yK,d),l.dispatchEvent(b),b.defaultPrevented||G0(g??document.body,{select:!0}),l.removeEventListener(yK,d),CLe.remove(h)},0)}}},[l,u,d,h]);const m=v.useCallback(g=>{if(!n&&!r||h.paused)return;const y=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,b=document.activeElement;if(y&&b){const w=g.currentTarget,[S,k]=P3n(w);S&&k?!g.shiftKey&&b===k?(g.preventDefault(),n&&G0(S,{select:!0})):g.shiftKey&&b===S&&(g.preventDefault(),n&&G0(k,{select:!0})):b===w&&g.preventDefault()}},[n,r,h.paused]);return o.jsx(wf.div,{tabIndex:-1,...i,ref:p,onKeyDown:m})});xyt.displayName=A3n;function R3n(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(G0(r,{select:t}),document.activeElement!==n)return}function P3n(e){const t=wyt(e),n=_Le(t,e),r=_Le(t.reverse(),e);return[n,r]}function wyt(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function _Le(e,t){for(const n of e)if(!$3n(n,{upTo:t}))return n}function $3n(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function M3n(e){return e instanceof HTMLInputElement&&"select"in e}function G0(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&M3n(e)&&t&&e.select()}}var CLe=D3n();function D3n(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=ELe(e,t),e.unshift(t)},remove(t){e=ELe(e,t),e[0]?.resume()}}}function ELe(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function L3n(e){return e.filter(t=>t.tagName!=="A")}var bK=0;function F3n(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??jLe()),document.body.insertAdjacentElement("beforeend",e[1]??jLe()),bK++,()=>{bK===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),bK--}},[])}function jLe(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var _v=function(){return _v=Object.assign||function(t){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},_v.apply(this,arguments)};function Syt(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]]);return n}function z3n(e,t,n){if(n||arguments.length===2)for(var r=0,s=t.length,a;r<s;r++)(a||!(r in t))&&(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}var R9="right-scroll-bar-position",P9="width-before-scroll-bar",B3n="with-scroll-bars-hidden",U3n="--removed-body-scroll-bar-size";function xK(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function q3n(e,t){var n=v.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var s=n.value;s!==r&&(n.value=r,n.callback(r,s))}}}})[0];return n.callback=t,n.facade}var V3n=typeof window<"u"?v.useLayoutEffect:v.useEffect,TLe=new WeakMap;function H3n(e,t){var n=q3n(null,function(r){return e.forEach(function(s){return xK(s,r)})});return V3n(function(){var r=TLe.get(n);if(r){var s=new Set(r),a=new Set(e),i=n.current;s.forEach(function(l){a.has(l)||xK(l,null)}),a.forEach(function(l){s.has(l)||xK(l,i)})}TLe.set(n,e)},[e]),n}function W3n(e){return e}function Z3n(e,t){t===void 0&&(t=W3n);var n=[],r=!1,s={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(a){var i=t(a,r);return n.push(i),function(){n=n.filter(function(l){return l!==i})}},assignSyncMedium:function(a){for(r=!0;n.length;){var i=n;n=[],i.forEach(a)}n={push:function(l){return a(l)},filter:function(){return n}}},assignMedium:function(a){r=!0;var i=[];if(n.length){var l=n;n=[],l.forEach(a),i=n}var c=function(){var d=i;i=[],d.forEach(a)},u=function(){return Promise.resolve().then(c)};u(),n={push:function(d){i.push(d),u()},filter:function(d){return i=i.filter(d),n}}}};return s}function G3n(e){e===void 0&&(e={});var t=Z3n(null);return t.options=_v({async:!0,ssr:!1},e),t}var kyt=function(e){var t=e.sideCar,n=Syt(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return v.createElement(r,_v({},n))};kyt.isSideCarExport=!0;function Q3n(e,t){return e.useMedium(t),kyt}var Oyt=G3n(),wK=function(){},sV=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:wK,onWheelCapture:wK,onTouchMoveCapture:wK}),s=r[0],a=r[1],i=e.forwardProps,l=e.children,c=e.className,u=e.removeScrollBar,d=e.enabled,f=e.shards,p=e.sideCar,h=e.noRelative,m=e.noIsolation,g=e.inert,y=e.allowPinchZoom,b=e.as,w=b===void 0?"div":b,S=e.gapMode,k=Syt(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),_=p,C=H3n([n,t]),E=_v(_v({},k),s);return v.createElement(v.Fragment,null,d&&v.createElement(_,{sideCar:Oyt,removeScrollBar:u,shards:f,noRelative:h,noIsolation:m,inert:g,setCallbacks:a,allowPinchZoom:!!y,lockRef:n,gapMode:S}),i?v.cloneElement(v.Children.only(l),_v(_v({},E),{ref:C})):v.createElement(w,_v({},E,{className:c,ref:C}),l))});sV.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};sV.classNames={fullWidth:P9,zeroRight:R9};var Y3n=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function X3n(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Y3n();return t&&e.setAttribute("nonce",t),e}function K3n(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function J3n(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var eDn=function(){var e=0,t=null;return{add:function(n){e==0&&(t=X3n())&&(K3n(t,n),J3n(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},tDn=function(){var e=eDn();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},_yt=function(){var e=tDn(),t=function(n){var r=n.styles,s=n.dynamic;return e(r,s),null};return t},nDn={left:0,top:0,right:0,gap:0},SK=function(e){return parseInt(e||"",10)||0},rDn=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],s=t[e==="padding"?"paddingRight":"marginRight"];return[SK(n),SK(r),SK(s)]},sDn=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return nDn;var t=rDn(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},aDn=_yt(),vj="data-scroll-locked",iDn=function(e,t,n,r){var s=e.left,a=e.top,i=e.right,l=e.gap;return n===void 0&&(n="margin"),`
231
+ `:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new y$n(this):new m$n(this)}getCursor(t,n=0,r){let s=t.doc?t:os.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?gE(this,s,n,r):mE(this,s,n,r)}}class Nvt{constructor(t){this.spec=t}}function p$n(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 mE(e,t,n,r){let s;return e.wholeWord&&(s=h$n(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=p$n(e.test,t,s)),new vx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function h$n(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(Qz(s,n-a))!=fo.Word||t(Yz(s,n-a))!=fo.Word)&&(t(Yz(s,r-a))!=fo.Word||t(Qz(s,r-a))!=fo.Word))}class m$n extends Nvt{constructor(t){super(t)}nextMatch(t,n,r){let s=mE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=mE(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=mE(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=mE(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=mE(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 g$n(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function gE(e,t,n,r){let s;return e.wholeWord&&(s=v$n(t.charCategorizer(t.selection.main.head))),e.test&&(s=g$n(e.test,t,s)),new Evt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function Qz(e,t){return e.slice(vc(e,t,!1),t)}function Yz(e,t){return e.slice(t,vc(e,t))}function v$n(e){return(t,n,r)=>!r[0].length||(e(Qz(r.input,r.index))!=fo.Word||e(Yz(r.input,r.index))!=fo.Word)&&(e(Yz(r.input,r.index+r[0].length))!=fo.Word||e(Qz(r.input,r.index+r[0].length))!=fo.Word)}class y$n extends Nvt{nextMatch(t,n,r){let s=gE(this.spec,t,r,t.doc.length).next();return s.done&&(s=gE(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=gE(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=gE(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=gE(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 x$=vr.define(),Y0e=vr.define(),Iw=ml.define({create(e){return new dK(Cpe(e).create(),null)},update(e,t){for(let n of t.effects)n.is(x$)?e=new dK(n.value.create(),e.panel):n.is(Y0e)&&(e=new dK(e.query,n.value?X0e:null));return e},provide:e=>u$.from(e,t=>t.panel)});class dK{constructor(t,n){this.query=t,this.panel=n}}const b$n=Cn.mark({class:"cm-searchMatch"}),x$n=Cn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),w$n=yo.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Iw))}update(e){let t=e.state.field(Iw);(t!=e.startState.field(Iw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Cn.none;let{view:n}=this,r=new bd;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?x$n:b$n)})}return r.finish()}},{decorations:e=>e.decorations});function q3(e){return t=>{let n=t.state.field(Iw,!1);return n&&n.query.spec.valid?e(t,n):Rvt(t)}}const Xz=q3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=vt.single(r.from,r.to),a=e.state.facet(PN);return e.dispatch({selection:s,effects:[K0e(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),Avt(e),!0}),Kz=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=vt.single(s.from,s.to),i=e.state.facet(PN);return e.dispatch({selection:a,effects:[K0e(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),Avt(e),!0}),S$n=q3((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:vt.create(n.map(r=>vt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),k$n=({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 vx(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(vt.range(l.value.from,l.value.to))}return t(e.update({selection:vt.create(a,i),userEvent:"select.search.matches"})),!0},tLe=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}),d.push(It.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=vt.single(i.from,i.to).map(f),d.push(K0e(e,i)),d.push(n.facet(PN).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),O$n=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:It.announce.of(r),userEvent:"input.replace.all"}),!0});function X0e(e){return e.state.facet(PN).createPanel(e)}function Cpe(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(PN);return new Tvt({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 Ivt(e){let t=p0e(e,X0e);return t&&t.dom.querySelector("[main-field]")}function Avt(e){let t=Ivt(e);t&&t==e.root.activeElement&&t.select()}const Rvt=e=>{let t=e.state.field(Iw,!1);if(t&&t.panel){let n=Ivt(e);if(n&&n!=e.root.activeElement){let r=Cpe(e.state,t.query.spec);r.valid&&e.dispatch({effects:x$.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Y0e.of(!0),t?x$.of(Cpe(e.state,t.query.spec)):vr.appendConfig.of(j$n)]});return!0},Pvt=e=>{let t=e.state.field(Iw,!1);if(!t||!t.panel)return!1;let n=p0e(e,X0e);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Y0e.of(!1)}),!0},_$n=[{key:"Mod-f",run:Rvt,scope:"editor search-panel"},{key:"F3",run:Xz,shift:Kz,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:Xz,shift:Kz,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Pvt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:k$n},{key:"Mod-Alt-g",run:t$n},{key:"Mod-d",run:f$n,preventDefault:!0}];class C$n{constructor(t){this.view=t;let n=this.query=t.state.field(Iw).query.spec;this.commit=this.commit.bind(this),this.searchField=ii("input",{value:n.search,placeholder:Hf(t,"Find"),"aria-label":Hf(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=ii("input",{value:n.replace,placeholder:Hf(t,"Replace"),"aria-label":Hf(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=ii("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=ii("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=ii("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return ii("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=ii("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>Xz(t),[Hf(t,"next")]),r("prev",()=>Kz(t),[Hf(t,"previous")]),r("select",()=>S$n(t),[Hf(t,"all")]),ii("label",null,[this.caseField,Hf(t,"match case")]),ii("label",null,[this.reField,Hf(t,"regexp")]),ii("label",null,[this.wordField,Hf(t,"by word")]),...t.state.readOnly?[]:[ii("br"),this.replaceField,r("replace",()=>tLe(t),[Hf(t,"replace")]),r("replaceAll",()=>O$n(t),[Hf(t,"replace all")])],ii("button",{name:"close",onclick:()=>Pvt(t),"aria-label":Hf(t,"close"),type:"button"},["×"])])}commit(){let t=new Tvt({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:x$.of(t)}))}keydown(t){Wjn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?Kz:Xz)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),tLe(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(x$)&&!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(PN).top}}function Hf(e,t){return e.state.phrase(t)}const n6=30,r6=/[\s\.,:;?!]/;function K0e(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-n6),i=Math.min(s,n+n6),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<n6;c++)if(!r6.test(l[c+1])&&r6.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-n6;c--)if(!r6.test(l[c-1])&&r6.test(l[c])){l=l.slice(0,c);break}}return It.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const E$n=It.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"}}),j$n=[Iw,Pg.low(w$n),E$n];class nLe{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class lk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(w$).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new bd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((g,y)=>Math.min(g,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let g=a[d];if(g.from==p&&(g.to>g.from||g.to==p))l.push(g),d++,h=Math.min(g.to,h);else{h=Math.min(g.from,h);break}}let m=B$n(l);if(l.some(g=>g.from==g.to||g.from==g.to-1&&r.doc.lineAt(g.from).to==g.from))i.add(p,p,Cn.widget({widget:new D$n(m),diagnostics:l.slice()}));else{let g=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,Cn.mark({class:"cm-lintRange cm-lintRange-"+m+g,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let g=0;g<l.length;g++)l[g].to<=c&&l.splice(g--,1)}let u=i.finish();return new lk(u,n,aT(u))}}function aT(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 nLe(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new nLe(r.from,a,r.diagnostic)}}),r}function T$n(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(w$).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is($vt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function N$n(e,t){return e.field(gp,!1)?t:t.concat(vr.appendConfig.of(U$n))}const $vt=vr.define(),J0e=vr.define(),Mvt=vr.define(),gp=ml.define({create(){return new lk(Cn.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=aT(n,e.selected.diagnostic,a)||aT(n,null,a)}!n.size&&s&&t.state.facet(w$).autoPanel&&(s=null),e=new lk(n,s,r)}for(let n of t.effects)if(n.is($vt)){let r=t.state.facet(w$).autoPanel?n.value.length?S$.open:null:e.panel;e=lk.init(n.value,r,t.state)}else n.is(J0e)?e=new lk(e.diagnostics,n.value?S$.open:null,e.selected):n.is(Mvt)&&(e=new lk(e.diagnostics,e.panel,n.value));return e},provide:e=>[u$.from(e,t=>t.panel),It.decorations.from(e,t=>t.diagnostics)]}),I$n=Cn.mark({class:"cm-lintRange cm-lintRange-active"});function A$n(e,t,n){let{diagnostics:r}=e.state.field(gp),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(w$).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:R$n(e,s)}}}:null}function R$n(e,t){return ii("ul",{class:"cm-tooltip-lint"},t.map(n=>Lvt(e,n,!1)))}const P$n=e=>{let t=e.state.field(gp,!1);(!t||!t.panel)&&e.dispatch({effects:N$n(e.state,[J0e.of(!0)])});let n=p0e(e,S$.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},rLe=e=>{let t=e.state.field(gp,!1);return!t||!t.panel?!1:(e.dispatch({effects:J0e.of(!1)}),!0)},$$n=e=>{let t=e.state.field(gp,!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)},M$n=[{key:"Mod-Shift-m",run:P$n,preventDefault:!0},{key:"F8",run:$$n}],w$=On.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Iy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:sLe,tooltipFilter:sLe,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 sLe(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function Dvt(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 Lvt(e,t,n){var r;let s=n?Dvt(t.actions):[];return ii("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},ii("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=aT(e.state.field(gp).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),ii("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return ii("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&ii("div",{class:"cm-diagnosticSource"},t.source))}class D$n extends Wp{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return ii("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class aLe{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Lvt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class S${constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)rLe(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=Dvt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=aT(this.view.state.field(gp).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=ii("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=ii("div",{class:"cm-panel-lint"},this.list,ii("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>rLe(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(gp).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(gp),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 aLe(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 aLe(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(gp),r=aT(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:Mvt.of(r)})}static open(t){return new S$(t)}}function L$n(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 s6(e){return L$n(`<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 F$n=It.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:s6("#d11")},".cm-lintRange-warning":{backgroundImage:s6("orange")},".cm-lintRange-info":{backgroundImage:s6("#999")},".cm-lintRange-hint":{backgroundImage:s6("#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 z$n(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function B$n(e){let t="hint",n=1;for(let r of e){let s=z$n(r.severity);s>n&&(n=s,t=r.severity)}return t}const U$n=[gp,It.decorations.compute([gp],e=>{let{selected:t,panel:n}=e.field(gp);return!t||!n||t.from==t.to?Cn.none:Cn.set([I$n.range(t.from,t.to)])}),PTn(A$n,{hideOn:T$n}),F$n];var iLe=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(IIn)),t.defaultKeymap!==!1&&(a=a.concat(KPn)),t.searchKeymap!==!1&&(a=a.concat(_$n)),t.historyKeymap!==!1&&(a=a.concat(aPn)),t.foldKeymap!==!1&&(a=a.concat(gNn)),t.completionKeymap!==!1&&(a=a.concat(Amt)),t.lintKeymap!==!1&&(a=a.concat(M$n));var i=[];return t.lineNumbers!==!1&&i.push(WTn()),t.highlightActiveLineGutter!==!1&&i.push(QTn()),t.highlightSpecialChars!==!1&&i.push(lTn()),t.history!==!1&&i.push(Y2n()),t.foldGutter!==!1&&i.push(xNn()),t.drawSelection!==!1&&i.push(Kjn()),t.dropCursor!==!1&&i.push(rTn()),t.allowMultipleSelections!==!1&&i.push(os.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(lNn()),t.syntaxHighlighting!==!1&&i.push(D1(ONn,{fallback:!0})),t.bracketMatching!==!1&&i.push(INn()),t.closeBrackets!==!1&&i.push(EIn()),t.autocompletion!==!1&&i.push(Imt()),t.rectangularSelection!==!1&&i.push(STn()),s!==!1&&i.push(_Tn()),t.highlightActiveLine!==!1&&i.push(hTn()),t.highlightSelectionMatches!==!1&&i.push(s$n()),t.tabSize&&typeof t.tabSize=="number"&&i.push(NN.of(" ".repeat(t.tabSize))),i.concat([TN.of(a.flat())]).filter(Boolean)};const q$n="#e5c07b",oLe="#e06c75",V$n="#56b6c2",H$n="#ffffff",A9="#abb2bf",Epe="#7d8799",W$n="#61afef",Z$n="#98c379",lLe="#d19a66",G$n="#c678dd",Q$n="#21252b",cLe="#2c313a",uLe="#282c34",fK="#353a42",Y$n="#3E4451",dLe="#528bff",X$n=It.theme({"&":{color:A9,backgroundColor:uLe},".cm-content":{caretColor:dLe},".cm-cursor, .cm-dropCursor":{borderLeftColor:dLe},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:Y$n},".cm-panels":{backgroundColor:Q$n,color:A9},".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:uLe,color:Epe,border:"none"},".cm-activeLineGutter":{backgroundColor:cLe},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:fK},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:fK,borderBottomColor:fK},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:cLe,color:A9}}},{dark:!0}),K$n=$g.define([{tag:fe.keyword,color:G$n},{tag:[fe.name,fe.deleted,fe.character,fe.propertyName,fe.macroName],color:oLe},{tag:[fe.function(fe.variableName),fe.labelName],color:W$n},{tag:[fe.color,fe.constant(fe.name),fe.standard(fe.name)],color:lLe},{tag:[fe.definition(fe.name),fe.separator],color:A9},{tag:[fe.typeName,fe.className,fe.number,fe.changed,fe.annotation,fe.modifier,fe.self,fe.namespace],color:q$n},{tag:[fe.operator,fe.operatorKeyword,fe.url,fe.escape,fe.regexp,fe.link,fe.special(fe.string)],color:V$n},{tag:[fe.meta,fe.comment],color:Epe},{tag:fe.strong,fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.link,color:Epe,textDecoration:"underline"},{tag:fe.heading,fontWeight:"bold",color:oLe},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:lLe},{tag:[fe.processingInstruction,fe.string,fe.inserted],color:Z$n},{tag:fe.invalid,color:H$n}]),J$n=[X$n,D1(K$n)];var eMn=It.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),tMn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,g=[];switch(s&&g.unshift(TN.of([JPn])),m&&(typeof m=="boolean"?g.unshift(iLe()):g.unshift(iLe(m))),p&&g.unshift(yTn(p)),d){case"light":g.push(eMn);break;case"dark":g.push(J$n);break;case"none":break;default:g.push(d);break}return i===!1&&g.push(It.editable.of(!1)),c&&g.push(os.readOnly.of(!0)),[...g]},nMn=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 rMn{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 fLe{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 pK=null,sMn=()=>typeof window>"u"?new fLe:(pK||(pK=new fLe),pK),pLe=Ny.define(),aMn=200,iMn=[];function oMn(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?iMn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,g=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,w=e.width,S=w===void 0?null:w,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,E=C===void 0?null:C,j=e.placeholder,N=j===void 0?"":j,I=e.editable,R=I===void 0?!0:I,$=e.readOnly,F=$===void 0?!1:$,D=e.indentWithTab,V=D===void 0?!0:D,W=e.basicSetup,L=W===void 0?!0:W,z=e.root,B=e.initialState,M=v.useState(),G=M[0],U=M[1],P=v.useState(),q=P[0],Z=P[1],X=v.useState(),te=X[0],J=X[1],ee=v.useState(()=>({current:null}))[0],ae=v.useState(()=>({current:null}))[0],de=It.theme({"&":{height:h,minHeight:g,maxHeight:b,width:S,minWidth:_,maxWidth:E},"& .cm-scroller":{height:"100% !important"}}),Y=It.updateListener.of(pe=>{if(pe.docChanged&&typeof r=="function"&&!pe.transactions.some(ye=>ye.annotation(pLe))){ee.current?ee.current.reset():(ee.current=new rMn(()=>{if(ae.current){var ye=ae.current;ae.current=null,ye()}ee.current=null},aMn),sMn().add(ee.current));var le=pe.state.doc,ve=le.toString();r(ve,pe)}s&&s(nMn(pe))}),ne=tMn({theme:f,editable:R,readOnly:F,placeholder:N,indentWithTab:V,basicSetup:L}),ce=[Y,de,...ne];return i&&typeof i=="function"&&ce.push(It.updateListener.of(i)),ce=ce.concat(c),v.useLayoutEffect(()=>{if(G&&!te){var pe={doc:t,selection:n,extensions:ce},le=B?os.fromJSON(B.json,pe,B.fields):os.create(pe);if(J(le),!q){var ve=new It({state:le,parent:G,root:z});Z(ve),a&&a(ve,le)}}return()=>{q&&(J(void 0),Z(void 0))}},[G,te]),v.useEffect(()=>{e.container&&U(e.container)},[e.container]),v.useEffect(()=>()=>{q&&(q.destroy(),Z(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[q]),v.useEffect(()=>{u&&q&&q.focus()},[u,q]),v.useEffect(()=>{q&&q.dispatch({effects:vr.reconfigure.of(ce)})},[f,c,h,g,b,S,_,E,N,R,F,V,L,r,i]),v.useEffect(()=>{if(t!==void 0){var pe=q?q.state.doc.toString():"";if(q&&t!==pe){var le=ee.current&&!ee.current.isDone,ve=()=>{q&&t!==q.state.doc.toString()&&q.dispatch({changes:{from:0,to:q.state.doc.toString().length,insert:t||""},annotations:[pLe.of(!0)]})};le?ae.current=ve:ve()}}},[t,q]),{state:te,setState:J,view:q,setView:Z,container:G,setContainer:U}}var lMn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],Xc=v.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,g=e.height,y=e.minHeight,b=e.maxHeight,w=e.width,S=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,E=e.indentWithTab,j=e.editable,N=e.readOnly,I=e.root,R=e.initialState,$=Wgt(e,lMn),F=v.useRef(null),D=oMn({root:I,value:s,autoFocus:p,theme:m,height:g,minHeight:y,maxHeight:b,width:w,minWidth:S,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:E,editable:j,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:R}),V=D.state,W=D.view,L=D.container,z=D.setContainer;v.useImperativeHandle(t,()=>({editor:F.current,state:V,view:W}),[F,L,V,W]);var B=v.useCallback(G=>{F.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",SO({ref:B,className:""+M+(n?" "+n:"")},$))});Xc.displayName="CodeMirror";const cMn=async e=>{if(typeof navigator>"u"||!navigator.clipboard?.writeText)return!1;try{return await navigator.clipboard.writeText(e),!0}catch{return!1}},uMn=e=>{if(typeof document>"u"||typeof document.execCommand!="function")return!1;const t=document.createElement("textarea"),n=document.activeElement instanceof HTMLElement?document.activeElement:null;t.value=e,t.setAttribute("readonly",""),t.setAttribute("aria-hidden","true"),t.style.position="fixed",t.style.top="0",t.style.left="0",t.style.width="1px",t.style.height="1px",t.style.opacity="0",t.style.pointerEvents="none",document.body.appendChild(t);try{return t.focus(),t.select(),t.setSelectionRange(0,e.length),document.execCommand("copy")}catch{return!1}finally{t.remove(),n?.focus({preventScroll:!0})}},dMn=async e=>e?await cMn(e)?!0:uMn(e):!1;function $p(e){const{copyMessage:t="Copied to clipboard!",copiedDuration:n=2e3,showToast:r=!0}=e,s="text"in e,a=s?e.text:void 0,[i,l]=v.useState(!1),c=v.useRef(null),u=v.useCallback(f=>{dMn(f).then(p=>{if(!p){r&&De.error("Failed to copy to clipboard.");return}r&&De.success(t),l(!0),c.current&&(clearTimeout(c.current),c.current=null),c.current=setTimeout(()=>{l(!1)},n)})},[n,t,r]),d=v.useCallback(()=>{a&&u(a)},[u,a]);return s?{isCopied:i,handleCopy:d,copyToClipboard:u}:{isCopied:i,copyToClipboard:u}}function ya({content:e,copyMessage:t,tooltip:n="Copy to clipboard",size:r="sm",variant:s,className:a}){const[i,l]=v.useState(!1),{handleCopy:c}=$p({text:e,copyMessage:t}),u=()=>{c(),l(!0),setTimeout(()=>l(!1),2e3)};return o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsx(ue,{onClick:u,type:"button",size:r,variant:s,className:a,"aria-label":i?"Copied!":n,children:i?o.jsx(hx,{}):o.jsx(Mft,{})})}),o.jsx(Bn,{children:i?"Copied!":n})]})}const fMn="mastra-theme",pMn="mastra-playground-store",jpe=e=>e==="dark"||e==="light"||e==="system",hMn=e=>{try{const t=e.getItem(pMn);if(!t)return;const r=JSON.parse(t)?.state?.theme;return jpe(r)?r:void 0}catch{return}},mMn=(e=fMn)=>({get(){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(jpe(t))return t;const n=hMn(window.localStorage);return n?(window.localStorage.setItem(e,n),n):null}catch{return null}},set(t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}},subscribe(t){if(typeof window>"u")return()=>{};const n=r=>{if(r.key===e){if(r.newValue===null){t(null);return}jpe(r.newValue)&&t(r.newValue)}};return window.addEventListener("storage",n),()=>window.removeEventListener("storage",n)}}),Fvt=v.createContext(null),zvt="(prefers-color-scheme: dark)",gMn=typeof window>"u"?v.useEffect:v.useLayoutEffect,Bvt=()=>typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia(zvt).matches?"dark":"light",Uvt=e=>{if(typeof window>"u"||typeof window.matchMedia!="function")return()=>{};const t=window.matchMedia(zvt);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},vMn=(e,t)=>{e.classList.remove(t==="dark"?"light":"dark"),e.classList.add(t)},qvt=({children:e,defaultTheme:t="system",storageKey:n,target:r})=>{const s=v.useMemo(()=>mMn(n),[n]),a=v.useRef(null),[i,l]=v.useState(()=>s.get()??t),c=v.useSyncExternalStore(Uvt,Bvt,()=>"dark");v.useEffect(()=>s.subscribe(f=>l(f??t)),[s,t]);const u=i==="system"?c:i;gMn(()=>{const f=r??(typeof window>"u"?null:window.document.documentElement);a.current&&a.current!==f&&a.current.classList.remove("dark","light"),f&&vMn(f,u),a.current=f},[u,r]);const d=v.useMemo(()=>({theme:i,resolvedTheme:u,systemTheme:c,setTheme:f=>{l(f),s.set(f)}}),[i,u,c,s]);return o.jsx(Fvt.Provider,{value:d,children:e})},yMn=()=>{},$N=()=>{const e=v.useContext(Fvt),t=v.useSyncExternalStore(Uvt,Bvt,()=>"dark");return v.useMemo(()=>e??{theme:"system",resolvedTheme:t,systemTheme:t,setTheme:yMn},[e,t])};function bMn(e){return new yO(y0e.define(e))}const Vvt=[Ym.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Eo(()=>Promise.resolve().then(()=>e6),[],import.meta.url).then(e=>e.javascript())}}),Ym.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Eo(()=>Promise.resolve().then(()=>qNn),void 0,import.meta.url).then(e=>e.json())}}),Ym.of({name:"JSX",extensions:["jsx"],load(){return Eo(()=>Promise.resolve().then(()=>e6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),Ym.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Eo(()=>Promise.resolve().then(()=>D2n),void 0,import.meta.url).then(e=>e.markdown())}}),Ym.of({name:"TSX",extensions:["tsx"],load(){return Eo(()=>Promise.resolve().then(()=>e6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),Ym.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Eo(()=>Promise.resolve().then(()=>e6),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),Ym.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Eo(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>bMn(e.shell))}})];function xMn(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 wMn(e){const t=xMn(e);return Imt({override:[SMn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function SMn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,p)=>{const g=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:g},selection:{anchor:f+g.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const kMn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,OMn=Cn.mark({class:"cm-variable-highlight"}),hLe=new Hht({regexp:kMn,decoration:()=>OMn}),_Mn=yo.fromClass(class{decorations;constructor(e){this.decorations=hLe.createDeco(e)}update(e){this.decorations=hLe.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),CMn=_Mn;function EMn(){const e=AN({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:[fe.className,fe.propertyName],color:"var(--neutral6)"},{tag:fe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.heading1,fe.heading2,fe.heading3,fe.heading4,fe.heading5,fe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:fe.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:fe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:fe.url,color:"var(--accent3)"},{tag:fe.monospace,color:"var(--neutral6)"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=It.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 jMn(){const e=It.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=$g.define([{tag:[fe.comment,fe.bracket],color:"var(--neutral2)"},{tag:[fe.string,fe.meta,fe.regexp],color:"var(--accent1)"},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:"var(--accent6)"},{tag:[fe.keyword,fe.operator,fe.tagName],color:"var(--accent2)"},{tag:[fe.function(fe.propertyName),fe.propertyName],color:"var(--accent5)"},{tag:[fe.definition(fe.variableName),fe.function(fe.variableName),fe.className,fe.attributeName],color:"var(--accent3)"},{tag:[fe.variableName,fe.number],color:"var(--accent5)"},{tag:[fe.name,fe.quote],color:"var(--accent1)"},{tag:fe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.heading1,fe.heading2,fe.heading3,fe.heading4,fe.heading5,fe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[fe.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:fe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:fe.url,color:"var(--accent3)"},{tag:fe.monospace,color:"var(--neutral6)"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:[fe.deleted],color:"var(--accent2)"},{tag:fe.invalid,color:"var(--error)"},{tag:[fe.standard(fe.tagName)],color:"var(--accent1)"}]);return[e,D1(t)]}const Ay=()=>{const e=$N().resolvedTheme==="dark";return v.useMemo(()=>e?EMn():jMn(),[e])},Qr=v.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,...h},m)=>{const g=Ay(),y=e?JSON.stringify(e,null,2):t??"",b=v.useMemo(()=>{const w=[];return f&&w.push(It.lineWrapping),a==="json"?w.push(af):a==="markdown"&&w.push(H0e({base:wO,codeLanguages:Vvt})),i&&a==="markdown"&&w.push(CMn),c&&a==="markdown"&&w.push(wMn(c)),p===!1&&w.push(os.readOnly.of(!0)),w},[a,i,c,p,f]);return o.jsxs("div",{className:K("rounded-md bg-surface3 p-1 font-mono relative border border-border1 overflow-hidden",s),...h,children:[r&&o.jsx(ya,{content:y,className:"absolute top-2 right-2 z-20"}),o.jsx(Xc,{ref:m,value:y,theme:g,extensions:b,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),TMn={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash"};let hK=null;function NMn(){return hK||(hK=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Eo(()=>import("./core-hbcxDBH-.js"),__vite__mapDeps([0,1,2]),import.meta.url),Eo(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Eo(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Eo(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Eo(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Eo(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Eo(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Eo(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Eo(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Eo(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Eo(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Eo(()=>import("./python-DhUJRlN_.js"),[],import.meta.url)],engine:t()})})()),hK}async function IMn(e,t){const n=TMn[t?.toLowerCase()];if(!n)return null;const r=await NMn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}const Of=({children:e,className:t,onClick:n})=>o.jsx("div",{tabIndex:n?0:void 0,onKeyDown:r=>{n&&(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n?.())},className:K("flex gap-3 group/entity bg-surface3 rounded-xl border border-border1 py-3 px-4",n&&"cursor-pointer hover:bg-surface4 transition-all",t),onClick:n,children:e}),Hvt=({children:e,className:t,style:n})=>o.jsx(Ue,{size:"lg",className:K("text-neutral3 mt-1 shrink-0",t),style:n,children:e}),_f=({children:e,className:t})=>o.jsx(ge,{as:"p",variant:"ui-lg",className:K("text-neutral6 font-medium",t),children:e}),Zp=({children:e,className:t})=>o.jsx(ge,{as:"div",variant:"ui-sm",className:K("text-neutral3",t),children:e}),Cf=({children:e,className:t})=>o.jsx("div",{className:K("flex-1 w-full",t),children:e});function Ds({resource:e,title:t,description:n,actionSlot:r,className:s}){const a="Permission Denied",i=e?`You don't have permission to access ${e}. Contact your administrator for access.`:"You don't have permission to access this resource. Contact your administrator for access.";return o.jsx(Lr,{className:s,iconSlot:o.jsx(Ue,{size:"lg",className:"text-neutral3",children:o.jsx(gOn,{})}),titleSlot:t??a,descriptionSlot:n??i,actionSlot:r})}function Vs({title:e,description:t,className:n}){const[r,s]=v.useState(!1),a=We(),i=v.useCallback(async()=>{try{s(!0);const{baseUrl:l="",apiPrefix:c}=a.options||{},u=(c||"/api").trim(),d=(u.startsWith("/")?u:`/${u}`).replace(/\/$/,""),f=new URLSearchParams({redirect_uri:window.location.href}),p=`${l}${d}/auth/sso/login?${f}`,h=await fetch(p,{credentials:"include",headers:{"Content-Type":"application/json"}});if(h.ok){const m=await h.json();window.location.href=m.url}}finally{s(!1)}},[a]);return o.jsx(Lr,{className:n,iconSlot:o.jsx(Ue,{size:"lg",className:"text-neutral3",children:o.jsx(Jkn,{})}),titleSlot:e??"Session Expired",descriptionSlot:t??"Your session has expired. Please log in again to continue.",actionSlot:o.jsx(ue,{variant:"default",onClick:i,disabled:r,children:r?"Redirecting...":"Log in"})})}const Vh=e=>o.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 34 21",fill:"none",...e,children:o.jsx("path",{d:"M4.49805 11.6934C6.98237 11.6934 8.99609 13.7081 8.99609 16.1924C8.9959 18.6765 6.98225 20.6904 4.49805 20.6904C2.01394 20.6903 0.000196352 18.6765 0 16.1924C0 13.7081 2.01382 11.6935 4.49805 11.6934ZM10.3867 0C12.8709 0 14.8846 2.01388 14.8848 4.49805C14.8848 4.8377 14.847 5.16846 14.7755 5.48643C14.4618 6.88139 14.1953 8.4633 14.9928 9.65L16.2575 11.5319C16.3363 11.6491 16.4727 11.7115 16.6137 11.703C16.7369 11.6957 16.8525 11.6343 16.9214 11.5318L18.1876 9.64717C18.9772 8.47198 18.7236 6.90783 18.4205 5.52484C18.3523 5.21392 18.3164 4.89094 18.3164 4.55957C18.3167 2.07546 20.3313 0.0615234 22.8154 0.0615234C25.2994 0.0617476 27.3132 2.0756 27.3135 4.55957C27.3135 4.93883 27.2665 5.30712 27.178 5.65896C26.8547 6.94441 26.5817 8.37932 27.2446 9.52714L28.459 11.6301C28.4819 11.6697 28.5245 11.6934 28.5703 11.6934C31.0545 11.6935 33.0684 13.7081 33.0684 16.1924C33.0682 18.6765 31.0544 20.6903 28.5703 20.6904C26.0861 20.6904 24.0725 18.6765 24.0723 16.1924C24.0723 15.8049 24.1212 15.4288 24.2133 15.0701C24.5458 13.7746 24.8298 12.3251 24.1609 11.1668L23.0044 9.16384C22.9656 9.09659 22.8931 9.05859 22.8154 9.05859C22.7983 9.05859 22.7824 9.06614 22.7728 9.08033L21.4896 10.9895C20.686 12.1851 20.9622 13.781 21.284 15.1851C21.3582 15.5089 21.3975 15.8461 21.3975 16.1924C21.3973 18.6764 19.3834 20.6902 16.8994 20.6904C14.4152 20.6904 12.4006 18.6765 12.4004 16.1924C12.4004 15.932 12.4226 15.6768 12.4651 15.4286C12.6859 14.14 12.8459 12.7122 12.1167 11.6271L11.2419 10.3253C10.6829 9.49347 9.71913 9.05932 8.78286 8.70188C7.0906 8.05584 5.88867 6.41734 5.88867 4.49805C5.88886 2.0139 7.90254 3.29835e-05 10.3867 0Z",fill:"currentColor"})}),AMn=sl(K("flex w-full text-neutral6 border bg-transparent","transition-all duration-normal ease-out-custom","placeholder:text-neutral2 placeholder:transition-opacity placeholder:duration-normal","focus:placeholder:opacity-70","min-h-[80px] resize-y"),{variants:{variant:{default:K(hz,"rounded-xl",$k),filled:K(hz,"rounded-xl",$k),outline:K(cft,"rounded-xl",$k),unstyled:uft},size:{sm:"px-2 py-1.5 text-ui-sm",md:"px-3 py-2 text-ui-md",default:"px-3 py-2 text-ui-md",lg:"px-4 py-3 text-ui-lg"}},defaultVariants:{variant:"default",size:"default"}}),Yl=v.forwardRef(({className:e,size:t,testId:n,variant:r,error:s,...a},i)=>o.jsx("textarea",{className:K(AMn({variant:r,size:t}),s&&"border-error focus-visible:border-error",e),"data-testid":n,ref:i,"aria-invalid":s,...a}));Yl.displayName="Textarea";function RMn(e){const{store:t,parentContext:n,actionsRef:r,isDrawer:s}=e,a=t.useState("open");Xdt(t,a),_3(t);const{forceUnmount:i}=C3(a,t),l=v.useCallback(()=>{t.setOpen(!1,Vt(w3))},[t]);return v.useImperativeHandle(r,()=>({unmount:i,close:l}),[i,l]),{parentContext:n,isDrawer:s}}function PMn({store:e,dialogRoot:t}){const{parentContext:n,isDrawer:r}=t,s=e.useState("open"),a=e.useState("disablePointerDismissal"),i=e.useState("modal"),l=e.useState("popupElement"),c=e.useState("floatingRootContext"),[u,d]=v.useState(0),[f,p]=v.useState(0),h=u===0,m=g_(c,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?"intentional":{mouse:i==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}},outsidePress(w){if(!e.context.outsidePressEnabledRef.current||"button"in w&&w.button!==0||"touches"in w&&w.touches.length!==1)return!1;const S=Si(w);if(h&&!a){const k=S;return i&&(e.context.internalBackdropRef.current||e.context.backdropRef.current)?e.context.internalBackdropRef.current===k||e.context.backdropRef.current===k||dn(k,l)&&!k?.hasAttribute("data-base-ui-portal"):!0}return!1},escapeKey:h});cpt(s&&i===!0,l),e.useContextCallback("onNestedDialogOpen",(w,S)=>{d(w),p(S)}),e.useContextCallback("onNestedDialogClose",()=>{d(0),p(0)}),v.useEffect(()=>(n?.onNestedDialogOpen&&s&&n.onNestedDialogOpen(u+1,f+(r?1:0)),n?.onNestedDialogClose&&!s&&n.onNestedDialogClose(),()=>{n?.onNestedDialogClose&&s&&n.onNestedDialogClose()}),[r,s,u,f,n]);const g=m.reference??ms,y=m.trigger??ms,b=v.useMemo(()=>Ro(_y,m.floating),[m.floating]);return E3(e,{activeTriggerProps:g,inactiveTriggerProps:y,popupProps:b,nestedOpenDialogCount:u,nestedOpenDrawerCount:f}),null}const ewe=v.createContext(!1),Wvt=v.createContext(void 0);function kd(e){const t=v.useContext(Wvt);if(e===!1&&t===void 0)throw new Error(Sr(27));return t}const $Mn={...T3,modal:ct(e=>e.modal),nested:ct(e=>e.nested),nestedOpenDialogCount:ct(e=>e.nestedOpenDialogCount),nestedOpenDrawerCount:ct(e=>e.nestedOpenDrawerCount),disablePointerDismissal:ct(e=>e.disablePointerDismissal),openMethod:ct(e=>e.openMethod),descriptionElementId:ct(e=>e.descriptionElementId),titleElementId:ct(e=>e.titleElementId),viewportElement:ct(e=>e.viewportElement),role:ct(e=>e.role)};class twe extends bN{constructor(t,n,r=!1){const s=new v_,a=MMn(t);a.floatingRootContext=kq(s,n,r),super(a,{popupRef:v.createRef(),backdropRef:v.createRef(),internalBackdropRef:v.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:s,onOpenChange:void 0,onOpenChangeComplete:void 0},$Mn)}setOpen=(t,n)=>{if(n.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},!t&&n.trigger==null&&this.state.activeTriggerId!=null&&(n.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(t,n),n.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(t,n);const r={open:t};Sq(r,t,n.trigger),this.update(r)};static useStore(t,n){return wq(t,(s,a)=>new twe(n,s,a),!0).store}}function MMn(e={}){return{...j3(),modal:!0,disablePointerDismissal:!1,popupElement:null,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e}}function Zvt(e,t="dialog"){const{children:n,open:r,defaultOpen:s=!1,onOpenChange:a,onOpenChangeComplete:i,disablePointerDismissal:l=!1,modal:c=!0,actionsRef:u,handle:d,triggerId:f,defaultTriggerId:p=null}=e,h=t==="drawer",m=t==="alert-dialog",g=m?!0:c,y=m||l,b=m?"alertdialog":"dialog",w=kd(!0),k={modal:g,disablePointerDismissal:y,nested:!!w,role:b},_=twe.useStore(d?.store,{open:s,openProp:r,activeTriggerId:p,triggerIdProp:f,...k});f_(()=>{const $=r===void 0&&_.state.open===!1&&s===!0?{open:!0,activeTriggerId:p}:null;m?_.update($?{...k,...$}:k):$&&_.update($)}),_.useControlledProp("openProp",r),_.useControlledProp("triggerIdProp",f),_.useSyncedValues(k),_.useContextCallback("onOpenChange",a),_.useContextCallback("onOpenChangeComplete",i);const C=_.useState("open"),E=_.useState("mounted"),j=_.useState("payload"),N=RMn({store:_,actionsRef:u,parentContext:w?.store.context,isDrawer:h}),I=C||E,R=v.useMemo(()=>({store:_}),[_]);return o.jsx(ewe.Provider,{value:!1,children:o.jsxs(Wvt.Provider,{value:R,children:[I&&o.jsx(PMn,{store:_,dialogRoot:N}),typeof n=="function"?n({payload:j}):n]})})}function DMn(e){return Zvt(e,"alert-dialog")}const LMn={...kf,...ec},Gvt=v.forwardRef(function(t,n){const{render:r,className:s,style:a,forceRender:i=!1,...l}=t,{store:c}=kd(),u=c.useState("open"),d=c.useState("nested"),f=c.useState("mounted"),p=c.useState("transitionStatus");return En("div",t,{state:{open:u,transitionStatus:p},ref:[c.context.backdropRef,n],stateAttributesMapping:LMn,props:[{role:"presentation",hidden:!f,style:{userSelect:"none",WebkitUserSelect:"none"}},l],enabled:i||!d})}),V3=v.forwardRef(function(t,n){const{render:r,className:s,style:a,disabled:i=!1,nativeButton:l=!0,...c}=t,{store:u}=kd(),d=u.useState("open"),{getButtonProps:f,buttonRef:p}=Sd({disabled:i,native:l}),h={disabled:i};function m(g){d&&u.setOpen(!1,Vt(qbe,g.nativeEvent))}return En("button",t,{state:h,ref:[n,p],props:[{onClick:m},c,f]})}),nwe=v.forwardRef(function(t,n){const{render:r,className:s,style:a,id:i,...l}=t,{store:c}=kd(),u=Li(i);return c.useSyncedValueWithCleanup("descriptionElementId",u),En("p",t,{ref:n,props:[{id:u},l]})});let FMn=(function(e){return e.nestedDialogs="--nested-dialogs",e})({}),zMn=(function(e){return e[e.open=ld.open]="open",e[e.closed=ld.closed]="closed",e[e.startingStyle=ld.startingStyle]="startingStyle",e[e.endingStyle=ld.endingStyle]="endingStyle",e.nested="data-nested",e.nestedDialogOpen="data-nested-dialog-open",e})({});const Qvt=v.createContext(void 0);function rwe(){const e=v.useContext(Qvt);if(e===void 0)throw new Error(Sr(26));return e}const mj="ArrowUp",kk="ArrowDown",k$="ArrowLeft",gj="ArrowRight",H3="Home",W3="End",Yvt="PageUp",Xvt="PageDown",Kvt=new Set([k$,gj]),BMn=new Set([k$,gj,H3,W3]),Jvt=new Set([mj,kk]),UMn=new Set([mj,kk,H3,W3]),eyt=new Set([...Kvt,...Jvt]),F1=new Set([...eyt,H3,W3]),tyt="Shift",qMn="Control",VMn="Alt",HMn="Meta",WMn=new Set([tyt,qMn,VMn,HMn]);function ZMn(e){return Ia(e)&&e.tagName==="INPUT"}function mLe(e){return!!(ZMn(e)&&e.selectionStart!=null||Ia(e)&&e.tagName==="TEXTAREA")}function gLe(e,t,n,r){if(!e||!t||!t.scrollTo)return;let s=e.scrollLeft,a=e.scrollTop;const i=e.clientWidth<e.scrollWidth,l=e.clientHeight<e.scrollHeight;if(i&&r!=="vertical"){const c=vLe(e,t,"left"),u=a6(e),d=a6(t);n==="ltr"&&(c+t.offsetWidth+d.scrollMarginRight>e.scrollLeft+e.clientWidth-u.scrollPaddingRight?s=c+t.offsetWidth+d.scrollMarginRight-e.clientWidth+u.scrollPaddingRight:c-d.scrollMarginLeft<e.scrollLeft+u.scrollPaddingLeft&&(s=c-d.scrollMarginLeft-u.scrollPaddingLeft)),n==="rtl"&&(c-d.scrollMarginRight<e.scrollLeft+u.scrollPaddingLeft?s=c-d.scrollMarginLeft-u.scrollPaddingLeft:c+t.offsetWidth+d.scrollMarginRight>e.scrollLeft+e.clientWidth-u.scrollPaddingRight&&(s=c+t.offsetWidth+d.scrollMarginRight-e.clientWidth+u.scrollPaddingRight))}if(l&&r!=="horizontal"){const c=vLe(e,t,"top"),u=a6(e),d=a6(t);c-d.scrollMarginTop<e.scrollTop+u.scrollPaddingTop?a=c-d.scrollMarginTop-u.scrollPaddingTop:c+t.offsetHeight+d.scrollMarginBottom>e.scrollTop+e.clientHeight-u.scrollPaddingBottom&&(a=c+t.offsetHeight+d.scrollMarginBottom-e.clientHeight+u.scrollPaddingBottom)}e.scrollTo({left:s,top:a,behavior:"auto"})}function vLe(e,t,n){const r=n==="left"?"offsetLeft":"offsetTop";let s=0;for(;t.offsetParent&&(s+=t[r],t.offsetParent!==e);)t=t.offsetParent;return s}function a6(e){const t=getComputedStyle(e);return{scrollMarginTop:parseFloat(t.scrollMarginTop)||0,scrollMarginRight:parseFloat(t.scrollMarginRight)||0,scrollMarginBottom:parseFloat(t.scrollMarginBottom)||0,scrollMarginLeft:parseFloat(t.scrollMarginLeft)||0,scrollPaddingTop:parseFloat(t.scrollPaddingTop)||0,scrollPaddingRight:parseFloat(t.scrollPaddingRight)||0,scrollPaddingBottom:parseFloat(t.scrollPaddingBottom)||0,scrollPaddingLeft:parseFloat(t.scrollPaddingLeft)||0}}const GMn={...kf,...ec,nestedDialogOpen(e){return e?{[zMn.nestedDialogOpen]:""}:null}},nyt=v.forwardRef(function(t,n){const{render:r,className:s,style:a,finalFocus:i,initialFocus:l,...c}=t,{store:u}=kd(),d=u.useState("descriptionElementId"),f=u.useState("disablePointerDismissal"),p=u.useState("floatingRootContext"),h=u.useState("popupProps"),m=u.useState("modal"),g=u.useState("mounted"),y=u.useState("nested"),b=u.useState("nestedOpenDialogCount"),w=u.useState("open"),S=u.useState("openMethod"),k=u.useState("titleElementId"),_=u.useState("transitionStatus"),C=u.useState("role"),E=p.useState("floatingId"),j=c.id??E;rwe(),tc({open:w,ref:u.context.popupRef,onComplete(){w&&u.context.onOpenChangeComplete?.(!0)}});function N(V){return V==="touch"?u.context.popupRef.current:!0}const I=l===void 0?N:l,R=b>0,$=u.useStateSetter("popupElement"),D=En("div",t,{state:{open:w,nested:y,transitionStatus:_,nestedDialogOpen:R},props:[h,{id:j,"aria-labelledby":k??void 0,"aria-describedby":d??void 0,role:C,..._y,hidden:!g,onKeyDown(V){F1.has(V.key)&&V.stopPropagation()},style:{[FMn.nestedDialogs]:b}},c],ref:[n,u.context.popupRef,$],stateAttributesMapping:GMn});return o.jsx(yN,{context:p,openInteractionType:S,disabled:!g,closeOnFocusOut:!f,initialFocus:I,returnFocus:i,modal:m!==!1,restoreFocus:"popup",children:D})}),swe=v.forwardRef(function(t,n){const{keepMounted:r=!1,...s}=t,{store:a}=kd(),i=a.useState("mounted"),l=a.useState("modal"),c=a.useState("open");return i||r?o.jsx(Qvt.Provider,{value:r,children:o.jsxs(k3,{ref:n,...s,children:[i&&l===!0&&o.jsx(P3,{ref:a.context.internalBackdropRef,inert:kN(!c)}),t.children]})}):null}),awe=v.forwardRef(function(t,n){const{render:r,className:s,style:a,id:i,...l}=t,{store:c}=kd(),u=Li(i);return c.useSyncedValueWithCleanup("titleElementId",u),En("h2",t,{ref:n,props:[{id:u},l]})}),iwe=v.forwardRef(function(t,n){const{render:r,className:s,style:a,disabled:i=!1,nativeButton:l=!0,id:c,payload:u,handle:d,...f}=t,p=kd(!0),h=d?.store??p?.store;if(!h)throw new Error(Sr(79));const m=Li(c),g=h.useState("floatingRootContext"),y=h.useState("isOpenedByTrigger",m),b=h.useState("triggerPopupId",m),w=v.useRef(null),{registerTrigger:S,isMountedByThisTrigger:k}=O3(m,w,h,{payload:u}),{getButtonProps:_,buttonRef:C}=Sd({disabled:i,native:l}),E=m_(g,{enabled:g!=null}),j=$xe(()=>h.select("open"),R=>{h.set("openMethod",R)}),N={disabled:i,open:y},I=h.useState("triggerProps",k);return En("button",t,{state:N,ref:[C,n,S,w],props:[E.reference,I,j,{[Ybe]:"",id:m,"aria-haspopup":"dialog","aria-expanded":y,"aria-controls":b},f,_],stateAttributesMapping:xN})}),QMn=iwe;let yLe=(function(e){return e[e.open=ld.open]="open",e[e.closed=ld.closed]="closed",e[e.startingStyle=ld.startingStyle]="startingStyle",e[e.endingStyle=ld.endingStyle]="endingStyle",e.nested="data-nested",e.nestedDialogOpen="data-nested-dialog-open",e})({});const YMn={...kf,...ec,nested(e){return e?{[yLe.nested]:""}:null},nestedDialogOpen(e){return e?{[yLe.nestedDialogOpen]:""}:null}},XMn=v.forwardRef(function(t,n){const{render:r,className:s,style:a,children:i,...l}=t,c=rwe(),{store:u}=kd(),d=u.useState("open"),f=u.useState("nested"),p=u.useState("transitionStatus"),h=u.useState("nestedOpenDialogCount"),m=u.useState("mounted"),g=u.useStateSetter("viewportElement"),y=h>0;return En("div",t,{enabled:c||m,state:{open:d,nested:f,transitionStatus:p,nestedDialogOpen:y},ref:[n,g],stateAttributesMapping:YMn,props:[{role:"presentation",hidden:!m,style:{pointerEvents:d?void 0:"none"},children:i},l]})});function Z3(e,t){return e&&v.isValidElement(t)?{render:t}:void 0}const KMn=DMn;function Tt({open:e,onOpenChange:t,children:n}){return o.jsx(KMn,{open:e,onOpenChange:t,children:n})}const ryt=v.forwardRef(({asChild:e,children:t,...n},r)=>o.jsx(QMn,{ref:r,...Z3(e,t),...n,children:e?void 0:t}));ryt.displayName="AlertDialogTrigger";const syt=swe,owe=v.forwardRef(({className:e,...t},n)=>o.jsx(Gvt,{ref:n,className:K("dialog-overlay-anim fixed inset-0 z-50 bg-overlay backdrop-blur-xs",e),...t}));owe.displayName="AlertDialogOverlay";const ayt=v.forwardRef(({className:e,...t},n)=>o.jsxs(syt,{children:[o.jsx(owe,{}),o.jsx(nyt,{ref:n,"data-slot":"alert-dialog-content",className:K("dialog-content-anim","fixed left-[50%] top-[50%] z-50 grid translate-x-[-50%] translate-y-[-50%]","w-full max-w-[calc(100%-2rem)] sm:max-w-lg","rounded-xl border border-border1/40 bg-surface2/96 backdrop-blur-md shadow-dialog",e),...t})]}));ayt.displayName="AlertDialogContent";const iyt=({className:e,...t})=>o.jsx("div",{className:K("flex flex-col gap-0.5 px-4 py-3 text-left",e),...t});iyt.displayName="AlertDialogHeader";const oyt=({className:e,...t})=>o.jsx("div",{className:K("flex flex-col-reverse gap-1.5 px-4 py-2.5 sm:flex-row sm:justify-end",e),...t});oyt.displayName="AlertDialogFooter";const lyt=({className:e,...t})=>o.jsx("div",{className:K("overflow-y-auto px-4 py-3.5 max-h-[50vh]",e),...t});lyt.displayName="AlertDialogBody";const cyt=v.forwardRef(({className:e,...t},n)=>o.jsx(awe,{ref:n,className:K("text-ui-md font-medium",e),...t}));cyt.displayName="AlertDialogTitle";const uyt=v.forwardRef(({className:e,...t},n)=>o.jsx(nwe,{ref:n,className:K("text-ui-sm text-neutral3",e),...t}));uyt.displayName="AlertDialogDescription";const dyt=v.forwardRef(({className:e,...t},n)=>o.jsx(V3,{ref:n,className:K(A3({variant:"primary",size:"lg"}),e),...t}));dyt.displayName="AlertDialogAction";const fyt=v.forwardRef(({className:e,...t},n)=>o.jsx(V3,{ref:n,className:K(A3({variant:"default",size:"lg"}),e),...t}));fyt.displayName="AlertDialogCancel";Tt.Trigger=ryt;Tt.Portal=syt;Tt.Overlay=owe;Tt.Content=ayt;Tt.Header=iyt;Tt.Footer=oyt;Tt.Body=lyt;Tt.Title=cyt;Tt.Description=uyt;Tt.Action=dyt;Tt.Cancel=fyt;function JMn(e){if(!e)return null;for(const t of e.elements){const n=t.tagName;if(n==="BUTTON"||n==="INPUT"){const r=t;if(r.type==="submit")return r}}return null}let bLe=(function(e){return e.checked="data-checked",e.unchecked="data-unchecked",e.indeterminate="data-indeterminate",e.disabled="data-disabled",e.readonly="data-readonly",e.required="data-required",e.valid="data-valid",e.invalid="data-invalid",e.touched="data-touched",e.dirty="data-dirty",e.filled="data-filled",e.focused="data-focused",e})({});function pyt(e){return v.useMemo(()=>({checked(t){return e.indeterminate?{}:t?{[bLe.checked]:""}:{[bLe.unchecked]:""}},...M1}),[e.indeterminate])}const e3n=v.createContext({disabled:!1});function hyt(){return v.useContext(e3n)}function lwe(e,t,n,r=!0,s){const[a,i]=v.useState(),l=Li(s?`${s}-label`:void 0),c=e??t??a;return Nt(()=>{const u=e||t||!r?void 0:t3n(n.current,l);a!==u&&i(u)}),c}function t3n(e,t){const n=n3n(e);if(n)return!n.id&&t&&(n.id=t),n.id||void 0}function n3n(e){if(!e)return;const t=e.parentElement;if(t&&t.tagName==="LABEL")return t;const n=e.id;if(n){const s=e.nextElementSibling;if(s&&s.htmlFor===n)return s}const r=e.labels;return r&&r[0]}const r3n=v.createContext(void 0);function s3n(e=!0){const t=v.useContext(r3n);if(t===void 0&&!e)throw new Error(Sr(3));return t}const myt=v.createContext(void 0);function a3n(){const e=v.useContext(myt);if(e===void 0)throw new Error(Sr(14));return e}const i3n="data-parent",o3n=v.forwardRef(function(t,n){const{checked:r,className:s,defaultChecked:a=!1,"aria-labelledby":i,disabled:l=!1,form:c,id:u,indeterminate:d=!1,inputRef:f,name:p,onCheckedChange:h,parent:m=!1,readOnly:g=!1,render:y,required:b=!1,uncheckedValue:w,value:S,nativeButton:k=!1,style:_,...C}=t,{clearErrors:E}=_N(),{disabled:j,name:N,setDirty:I,setFilled:R,setFocused:$,setTouched:F,state:D,validationMode:V,validityData:W,shouldValidateOnChange:L,validation:z}=vm(),B=hyt(),{labelId:M,controlId:G,registerControlId:U,getDescriptionProps:P}=zx(),q=s3n(),Z=q?.parent,X=Z&&q.allValues,te=j||B.disabled||q?.disabled||l,J=N??p,ee=S??J,ae=Li(),de=Li();let Y=G;X?Y=m?de:`${Z.id}-${ee}`:u&&(Y=u);let ne={};X&&(m?ne=q.parent.getParentProps():ee&&(ne=q.parent.getChildProps(ee)));const{checked:ce=r,indeterminate:pe=d,onCheckedChange:le,...ve}=ne,ye=q?.value,Se=q?.setValue,Ne=q?.defaultValue,ke=v.useRef(null),Ie=Sc(()=>Symbol("checkbox-control")),ze=v.useRef(!1),{getButtonProps:oe,buttonRef:se}=Sd({disabled:te,native:k}),re=q?.validation??z,[he,xe]=sf({controlled:ee&&ye&&!m?ye.includes(ee):ce,default:ee&&Ne&&!m?Ne.includes(ee):a,name:"Checkbox",state:"checked"});Nt(()=>{U!==ga&&(ze.current=!0,U(Ie.current,Y))},[Y,U,Ie]),v.useEffect(()=>{const qe=Ie.current;return()=>{!ze.current||U===ga||(ze.current=!1,U(qe,void 0))}},[U,Ie]),ON(ke,ae,he,void 0,!q);const Ee=v.useRef(null),Pe=Ru(f,Ee,re.inputRef),Qe=lwe(i,M,Ee,!k,Y??void 0);Nt(()=>{Ee.current&&(Ee.current.indeterminate=pe,he&&R(!0))},[he,pe,R]),Rv(he,()=>{q&&!m||(E(J),R(he),I(he!==W.initialValue),L()?re.commit(he):re.commit(he,!0))});const Ze=Ro({checked:he,disabled:te,form:c,name:m?void 0:J,id:k?void 0:Y??void 0,required:b,ref:Pe,style:J?vN:t1,tabIndex:-1,type:"checkbox","aria-hidden":!0,onChange(qe){if(qe.nativeEvent.defaultPrevented)return;if(g){qe.preventDefault();return}const Ke=qe.currentTarget.checked,Ge=Vt(No,qe.nativeEvent);if(le?.(Ke,Ge),h?.(Ke,Ge),!Ge.isCanceled&&(xe(Ke),ee&&ye&&Se&&!m&&!X)){const Ot=Ke?[...ye,ee]:ye.filter(yt=>yt!==ee);Se(Ot,Ge)}},onFocus(){ke.current?.focus()}},S!==void 0?{value:(q?he&&S:S)||""}:ms,P,q?re.getValidationProps:re.getInputValidationProps),Ce=X?!!ce:he,je=X&&pe||d;v.useEffect(()=>{if(!Z||!ee)return;const qe=Z.disabledStatesRef.current;return qe.set(ee,te),()=>{qe.delete(ee)}},[Z,te,ee]);const _e=v.useMemo(()=>({...D,checked:Ce,disabled:te,readOnly:g,required:b,indeterminate:je}),[D,Ce,te,g,b,je]),Oe=pyt(_e),Re=En("span",t,{state:_e,ref:[se,ke,n,q?.registerControlRef],props:[{id:k?Y??void 0:ae,role:"checkbox","aria-checked":pe?"mixed":he,"aria-readonly":g||void 0,"aria-required":b||void 0,"aria-labelledby":Qe,[i3n]:m?"":void 0,onFocus(){$(!0)},onBlur(){const qe=Ee.current;qe&&(F(!0),$(!1),V==="onBlur"&&re.commit(q?ye:qe.checked))},onKeyDown(qe){if(qe.key!=="Enter"||(qe.preventBaseUIHandler(),qe.defaultPrevented))return;const Ke=Ee.current?.form??null,Ge=qe.currentTarget,Ot=qe.nativeEvent,yt=qe.preventDefault,nn=Ot.preventDefault;let bt=!1;qe.preventDefault=()=>{bt=!0,yt.call(qe)},Ot.preventDefault=()=>{bt=!0,nn.call(Ot)},nn.call(Ot),Ks(Ge).queueMicrotask(()=>{qe.preventDefault=yt,Ot.preventDefault=nn,bt||JMn(Ke)?.click()})},onClick(qe){if(g||te)return;qe.preventDefault();const Ke=Ee.current;Ke&&Ke.dispatchEvent(new(Ks(Ke)).PointerEvent("click",{bubbles:!0,shiftKey:qe.shiftKey,ctrlKey:qe.ctrlKey,altKey:qe.altKey,metaKey:qe.metaKey}))}},P,re.getValidationProps,C,ve,oe],stateAttributesMapping:Oe});return o.jsxs(myt.Provider,{value:_e,children:[Re,!he&&!q&&J&&!m&&w!==void 0&&o.jsx("input",{type:"hidden",form:c,name:J,value:w}),o.jsx("input",{...Ze,suppressHydrationWarning:!0})]})}),l3n=v.forwardRef(function(t,n){const{render:r,className:s,style:a,keepMounted:i=!1,...l}=t,c=a3n(),u=c.checked||c.indeterminate,{mounted:d,transitionStatus:f,setMounted:p}=Ag(u),h=v.useRef(null),m={...c,transitionStatus:f};tc({open:u,ref:h,onComplete(){u||p(!1)}});const y={...pyt(c),...ec,...M1},b=i||d,w=En("span",t,{ref:[n,h],state:m,stateAttributesMapping:y,props:l});return b?w:null}),$o=v.forwardRef(({className:e,checked:t,indeterminate:n,...r},s)=>{const a=t==="indeterminate";return o.jsx(o3n,{ref:s,checked:a?!1:t,indeterminate:n??a,"data-slot":"checkbox",className:K("peer flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[0.3125rem]","border border-neutral6/[0.06] bg-neutral6/[0.12] text-surface1 outline-hidden",is.all,"hover:border-neutral6/[0.12] hover:bg-neutral6/[0.16]","active:scale-95 active:border-neutral6/[0.18] active:bg-neutral6/[0.18]","focus-visible:border-neutral5/50 focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-neutral5/55","data-[checked]:border-neutral6 data-[checked]:bg-neutral6 data-[checked]:text-surface1","data-[indeterminate]:border-neutral6 data-[indeterminate]:bg-neutral6 data-[indeterminate]:text-surface1","data-[checked]:hover:border-neutral5 data-[checked]:hover:bg-neutral5","data-[indeterminate]:hover:border-neutral5 data-[indeterminate]:hover:bg-neutral5","data-[checked]:active:border-neutral4 data-[checked]:active:bg-neutral4","data-[indeterminate]:active:border-neutral4 data-[indeterminate]:active:bg-neutral4","data-[disabled]:cursor-not-allowed data-[disabled]:border-neutral6/[0.38] data-[disabled]:bg-neutral6/[0.38] data-[disabled]:hover:border-neutral6/[0.38] data-[disabled]:hover:bg-neutral6/[0.38] data-[disabled]:active:scale-100","data-[disabled]:data-[checked]:border-neutral6/[0.38] data-[disabled]:data-[checked]:bg-neutral6/[0.38] data-[disabled]:data-[checked]:text-neutral6","data-[disabled]:data-[indeterminate]:border-neutral6/[0.38] data-[disabled]:data-[indeterminate]:bg-neutral6/[0.38] data-[disabled]:data-[indeterminate]:text-neutral6",e),...r,children:o.jsx(l3n,{keepMounted:!0,className:K("group/checkbox-indicator flex items-center justify-center text-current","opacity-0 scale-75 transition-[opacity,transform] duration-200 ease-out-custom","data-[checked]:opacity-100 data-[checked]:scale-100","data-[indeterminate]:opacity-100 data-[indeterminate]:scale-100","data-[starting-style]:opacity-0 data-[starting-style]:scale-75","data-[ending-style]:opacity-0 data-[ending-style]:scale-75"),children:o.jsx(c3n,{})})})});$o.displayName="Checkbox";function c3n(){return o.jsxs(o.Fragment,{children:[o.jsx(hx,{className:K("size-3 scale-95 stroke-[3.25] transition-[stroke-dashoffset,transform] duration-200 ease-out-custom","[stroke-dasharray:28] [stroke-dashoffset:28]","group-data-[checked]/checkbox-indicator:[stroke-dashoffset:0]","group-data-[checked]/checkbox-indicator:scale-100","group-data-[indeterminate]/checkbox-indicator:hidden")}),o.jsx(aOn,{className:K("hidden size-3 scale-95 stroke-[3.25] transition-transform duration-200 ease-out-custom","group-data-[indeterminate]/checkbox-indicator:block","group-data-[indeterminate]/checkbox-indicator:scale-100")})]})}function u3n(e){const{open:t,defaultOpen:n,onOpenChange:r,disabled:s}=e,[a,i]=sf({controlled:t,default:n,name:"Collapsible",state:"open"}),{mounted:l,setMounted:c,transitionStatus:u}=Ag(a,!0,!0),d=Li(),[f,p]=v.useState(),h=f??d,m=mt(g=>{const y=!a,b=Vt(xg,g.nativeEvent);r(y,b),!b.isCanceled&&i(y)});return v.useMemo(()=>({disabled:s,handleTrigger:m,mounted:l,open:a,panelId:h,setMounted:c,setOpen:i,setPanelIdState:p,transitionStatus:u}),[s,m,l,a,h,c,i,p,u])}const gyt=v.createContext(void 0);function vyt(){const e=v.useContext(gyt);if(e===void 0)throw new Error(Sr(15));return e}let cwe=(function(e){return e.open="data-open",e.closed="data-closed",e[e.startingStyle=wg.startingStyle]="startingStyle",e[e.endingStyle=wg.endingStyle]="endingStyle",e})({}),d3n=(function(e){return e.panelOpen="data-panel-open",e})({});const f3n={[cwe.open]:""},p3n={[cwe.closed]:""},h3n={open(e){return e?{[d3n.panelOpen]:""}:null}},m3n={open(e){return e?f3n:p3n}},yyt={...m3n,...ec},g3n=v.forwardRef(function(t,n){const{render:r,className:s,defaultOpen:a=!1,disabled:i=!1,onOpenChange:l,open:c,style:u,...d}=t,f=mt(l),p=u3n({open:c,defaultOpen:a,onOpenChange:f,disabled:i}),h=v.useMemo(()=>({open:p.open,disabled:p.disabled,transitionStatus:p.transitionStatus}),[p.open,p.disabled,p.transitionStatus]),m=v.useMemo(()=>({...p,onOpenChange:f,state:h}),[p,f,h]),g=En("div",t,{state:h,ref:n,props:d,stateAttributesMapping:yyt});return o.jsx(gyt.Provider,{value:m,children:g})}),v3n={...h3n,...ec},y3n=v.forwardRef(function(t,n){const{panelId:r,open:s,handleTrigger:a,state:i,disabled:l}=vyt(),{className:c,disabled:u=l,id:d,render:f,nativeButton:p=!0,style:h,...m}=t,{getButtonProps:g,buttonRef:y}=Sd({disabled:u,focusableWhenDisabled:!0,native:p});return En("button",t,{state:i,ref:[n,y],props:[{"aria-controls":s?r:void 0,"aria-expanded":s,onClick:a},m,g],stateAttributesMapping:v3n})}),zA={height:void 0,width:void 0};function b3n(e){const{externalRef:t,hiddenUntilFound:n,id:r,keepMounted:s,mounted:a,onOpenChange:i,open:l,setMounted:c,setOpen:u,transitionStatus:d}=e,f=v.useRef(null),p=v.useRef(null),[h,m]=v.useState(zA),g=v.useRef(zA),y=v.useRef(!1),b=v.useRef(l),w=v.useRef(!1),[S,k]=v.useState(!1),_=v.useRef(null),C=Ru(t,f),E=Yi({mounted:a,open:l}),j=xq(f,!1,!1),N=!l&&!a,I=S?"idle":d,R=l&&(b.current||w.current),$=!l&&a&&p.current==="css-animation"&&h.height===void 0&&h.width===void 0?g.current:h,F=n&&N&&p.current!=="css-animation",D=mt((B,M=!0)=>{M&&(g.current=B),m(B)}),V=mt(()=>{_.current?.(),_.current=null}),W=mt(B=>{V(),_.current=()=>{_.current=null,B()}}),L=mt(()=>{l&&a&&p.current==="css-animation"&&(w.current=!0)});Nt(()=>{!S||d==="starting"||k(!1)},[S,d]),v.useEffect(()=>()=>{L(),V()},[L,V]),Nt(()=>{const B=f.current;if(!B)return;!l&&_.current&&V();const M=x3n(B,R);if(p.current=M,l&&d==="idle"&&b.current&&M==="css-animation"){g.current=AC(B);return}if(l&&d==="starting"){const P=y.current;if(y.current=!1,M==="none"){D(AC(B)),k(!0);return}if(M==="css-transition"){const q=w3n(B);if(D(AC(B)),!P)return q;const Z=BA(B,"transition-duration","0s");return W(Z),k(!0),q}if(M==="css-animation"){if(D(AC(B)),!P){BA(B,"animation-name","none")();return}const q=BA(B,"animation-name","none"),Z=BA(B,"animation-duration","0s");q(),W(Z),k(!0);return}}if(!l&&a&&(d==="idle"||d==="starting")){if(M==="none"){D(zA,!1),c(!1);return}M==="css-animation"&&(b.current=!1,w.current=!1),D(AC(B));return}if(d!=="ending")return;if(M==="none"){c(!1);return}const G=AC(B);if(!((G.height??0)>0||(G.width??0)>0)){c(!1);return}D(G),M==="css-animation"&&BA(B,"animation-name","none")()},[a,l,V,D,c,W,R,d]),tc({enabled:l&&a&&I==="idle",open:!0,ref:f,onComplete(){l&&D(zA,!1)}}),v.useEffect(()=>{if(l||!a||I!=="ending"||!f.current)return;const M=new AbortController;let G=-1;function U(){E.current.open||(c(!1),D(zA,!1))}return G=Bd.request(()=>{M.signal.aborted||j(U,M.signal)}),()=>{Bd.cancel(G),M.abort()}},[E,a,l,I,j,D,c]),Nt(()=>{const B=f.current;!B||!n||!N||B.setAttribute("hidden","until-found")},[N,n]),v.useEffect(function(){const M=f.current;if(!M)return;function G(U){y.current=!0,u(!0),i(!0,Vt(No,U))}return Ur(M,"beforematch",G)},[i,u]);const z=s||n||a||l;return{height:$.height,props:{...F?{[cwe.startingStyle]:""}:void 0,hidden:N,id:r},ref:C,shouldPreventOpenAnimation:R,shouldRender:z,transitionStatus:I,width:$.width}}function AC(e){return{height:e.scrollHeight,width:e.scrollWidth}}function x3n(e,t=!1){const n=Ks(e).getComputedStyle(e),r=(n.animationName.split(",").map(a=>a.trim()).some(a=>a!==""&&a!=="none")||t)&&xLe(n.animationDuration),s=xLe(n.transitionDuration);return r&&s||s?"css-transition":r?"css-animation":"none"}function xLe(e){return e.split(",").map(t=>t.trim()).some(t=>t!==""&&Number.parseFloat(t)>0)}function BA(e,t,n){const r=e.style.getPropertyValue(t),s=e.style.getPropertyPriority(t);return e.style.setProperty(t,n),()=>{if(r===""){e.style.removeProperty(t);return}e.style.setProperty(t,r,s)}}function w3n(e){const t={"justify-content":e.style.justifyContent,"align-items":e.style.alignItems,"align-content":e.style.alignContent,"justify-items":e.style.justifyItems};Object.keys(t).forEach(s=>{e.style.setProperty(s,"initial","important")});function n(){Object.entries(t).forEach(([s,a])=>{if(a===""){e.style.removeProperty(s);return}e.style.setProperty(s,a)})}const r=Bd.request(n);return()=>{Bd.cancel(r),n()}}let wLe=(function(e){return e.collapsiblePanelHeight="--collapsible-panel-height",e.collapsiblePanelWidth="--collapsible-panel-width",e})({});const S3n=v.forwardRef(function(t,n){const{className:r,hiddenUntilFound:s,keepMounted:a,render:i,id:l,style:c,...u}=t,{mounted:d,onOpenChange:f,open:p,panelId:h,setMounted:m,setPanelIdState:g,setOpen:y,state:b,transitionStatus:w}=vyt(),S=s??!1,k=a??!1;Nt(()=>{if(l)return g(l),()=>{g(void 0)}},[l,g]);const{height:_,props:C,ref:E,shouldPreventOpenAnimation:j,shouldRender:N,transitionStatus:I,width:R}=b3n({externalRef:n,hiddenUntilFound:S,id:h,keepMounted:k,mounted:d,onOpenChange:f,open:p,setMounted:m,setOpen:y,transitionStatus:w}),$={...b,transitionStatus:I},F=Idt(c,$),D=En("div",{...t,style:void 0},{state:$,ref:E,props:[C,{style:{[wLe.collapsiblePanelHeight]:_===void 0?"auto":`${_}px`,[wLe.collapsiblePanelWidth]:R===void 0?"auto":`${R}px`}},u,F?{style:F}:void 0,j?{style:{animationName:"none"}}:void 0],stateAttributesMapping:yyt});return N?D:null}),Mp=g3n,mf=Le.forwardRef(({className:e,asChild:t,children:n,...r},s)=>{const a=t&&Le.isValidElement(n)?{render:n}:{};return o.jsx(y3n,{ref:s,"data-slot":"collapsible-trigger",className:K("-outline-offset-2",is.colors,$3.visible,"hover:text-neutral5","[&>svg]:transition-transform [&>svg]:duration-normal [&>svg]:ease-out-custom","[&[data-panel-open]>svg]:rotate-90",e),...a,...r,children:t?void 0:n})});mf.displayName="CollapsibleTrigger";const gf=Le.forwardRef(({className:e,children:t,...n},r)=>o.jsx(S3n,{ref:r,"data-slot":"collapsible-content",className:K("overflow-hidden","h-[var(--collapsible-panel-height)] transition-[height] duration-normal ease-out-custom","data-[starting-style]:h-0 data-[ending-style]:h-0"),...n,children:o.jsx("div",{className:e,children:t})}));gf.displayName="CollapsibleContent";var SLe=1,k3n=.9,O3n=.8,_3n=.17,mK=.1,gK=.999,C3n=.9999,E3n=.99,j3n=/[\\\/_+.#"@\[\(\{&]/,T3n=/[\\\/_+.#"@\[\(\{&]/g,N3n=/[\s-]/,byt=/[\s-]/g;function Tpe(e,t,n,r,s,a,i){if(a===t.length)return s===e.length?SLe:E3n;var l=`${s},${a}`;if(i[l]!==void 0)return i[l];for(var c=r.charAt(a),u=n.indexOf(c,s),d=0,f,p,h,m;u>=0;)f=Tpe(e,t,n,r,u+1,a+1,i),f>d&&(u===s?f*=SLe:j3n.test(e.charAt(u-1))?(f*=O3n,h=e.slice(s,u-1).match(T3n),h&&s>0&&(f*=Math.pow(gK,h.length))):N3n.test(e.charAt(u-1))?(f*=k3n,m=e.slice(s,u-1).match(byt),m&&s>0&&(f*=Math.pow(gK,m.length))):(f*=_3n,s>0&&(f*=Math.pow(gK,u-s))),e.charAt(u)!==t.charAt(a)&&(f*=C3n)),(f<mK&&n.charAt(u-1)===r.charAt(a+1)||r.charAt(a+1)===r.charAt(a)&&n.charAt(u-1)!==r.charAt(a))&&(p=Tpe(e,t,n,r,u+1,a+2,i),p*mK>f&&(f=p*mK)),f>d&&(d=f),u=n.indexOf(c,u+1);return i[l]=d,d}function kLe(e){return e.toLowerCase().replace(byt," ")}function I3n(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Tpe(e,t,kLe(e),kLe(t),0,0,{})}var vK="focusScope.autoFocusOnMount",yK="focusScope.autoFocusOnUnmount",OLe={bubbles:!1,cancelable:!0},A3n="FocusScope",xyt=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:a,...i}=e,[l,c]=v.useState(null),u=Hj(s),d=Hj(a),f=v.useRef(null),p=Ig(t,g=>c(g)),h=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let g=function(S){if(h.paused||!l)return;const k=S.target;l.contains(k)?f.current=k:G0(f.current,{select:!0})},y=function(S){if(h.paused||!l)return;const k=S.relatedTarget;k!==null&&(l.contains(k)||G0(f.current,{select:!0}))},b=function(S){if(document.activeElement===document.body)for(const _ of S)_.removedNodes.length>0&&G0(l)};document.addEventListener("focusin",g),document.addEventListener("focusout",y);const w=new MutationObserver(b);return l&&w.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",y),w.disconnect()}}},[r,l,h.paused]),v.useEffect(()=>{if(l){CLe.add(h);const g=document.activeElement;if(!l.contains(g)){const b=new CustomEvent(vK,OLe);l.addEventListener(vK,u),l.dispatchEvent(b),b.defaultPrevented||(R3n(L3n(wyt(l)),{select:!0}),document.activeElement===g&&G0(l))}return()=>{l.removeEventListener(vK,u),setTimeout(()=>{const b=new CustomEvent(yK,OLe);l.addEventListener(yK,d),l.dispatchEvent(b),b.defaultPrevented||G0(g??document.body,{select:!0}),l.removeEventListener(yK,d),CLe.remove(h)},0)}}},[l,u,d,h]);const m=v.useCallback(g=>{if(!n&&!r||h.paused)return;const y=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,b=document.activeElement;if(y&&b){const w=g.currentTarget,[S,k]=P3n(w);S&&k?!g.shiftKey&&b===k?(g.preventDefault(),n&&G0(S,{select:!0})):g.shiftKey&&b===S&&(g.preventDefault(),n&&G0(k,{select:!0})):b===w&&g.preventDefault()}},[n,r,h.paused]);return o.jsx(wf.div,{tabIndex:-1,...i,ref:p,onKeyDown:m})});xyt.displayName=A3n;function R3n(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(G0(r,{select:t}),document.activeElement!==n)return}function P3n(e){const t=wyt(e),n=_Le(t,e),r=_Le(t.reverse(),e);return[n,r]}function wyt(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function _Le(e,t){for(const n of e)if(!$3n(n,{upTo:t}))return n}function $3n(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function M3n(e){return e instanceof HTMLInputElement&&"select"in e}function G0(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&M3n(e)&&t&&e.select()}}var CLe=D3n();function D3n(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=ELe(e,t),e.unshift(t)},remove(t){e=ELe(e,t),e[0]?.resume()}}}function ELe(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function L3n(e){return e.filter(t=>t.tagName!=="A")}var bK=0;function F3n(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??jLe()),document.body.insertAdjacentElement("beforeend",e[1]??jLe()),bK++,()=>{bK===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),bK--}},[])}function jLe(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var _v=function(){return _v=Object.assign||function(t){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},_v.apply(this,arguments)};function Syt(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]]);return n}function z3n(e,t,n){if(n||arguments.length===2)for(var r=0,s=t.length,a;r<s;r++)(a||!(r in t))&&(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}var R9="right-scroll-bar-position",P9="width-before-scroll-bar",B3n="with-scroll-bars-hidden",U3n="--removed-body-scroll-bar-size";function xK(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function q3n(e,t){var n=v.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var s=n.value;s!==r&&(n.value=r,n.callback(r,s))}}}})[0];return n.callback=t,n.facade}var V3n=typeof window<"u"?v.useLayoutEffect:v.useEffect,TLe=new WeakMap;function H3n(e,t){var n=q3n(null,function(r){return e.forEach(function(s){return xK(s,r)})});return V3n(function(){var r=TLe.get(n);if(r){var s=new Set(r),a=new Set(e),i=n.current;s.forEach(function(l){a.has(l)||xK(l,null)}),a.forEach(function(l){s.has(l)||xK(l,i)})}TLe.set(n,e)},[e]),n}function W3n(e){return e}function Z3n(e,t){t===void 0&&(t=W3n);var n=[],r=!1,s={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(a){var i=t(a,r);return n.push(i),function(){n=n.filter(function(l){return l!==i})}},assignSyncMedium:function(a){for(r=!0;n.length;){var i=n;n=[],i.forEach(a)}n={push:function(l){return a(l)},filter:function(){return n}}},assignMedium:function(a){r=!0;var i=[];if(n.length){var l=n;n=[],l.forEach(a),i=n}var c=function(){var d=i;i=[],d.forEach(a)},u=function(){return Promise.resolve().then(c)};u(),n={push:function(d){i.push(d),u()},filter:function(d){return i=i.filter(d),n}}}};return s}function G3n(e){e===void 0&&(e={});var t=Z3n(null);return t.options=_v({async:!0,ssr:!1},e),t}var kyt=function(e){var t=e.sideCar,n=Syt(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return v.createElement(r,_v({},n))};kyt.isSideCarExport=!0;function Q3n(e,t){return e.useMedium(t),kyt}var Oyt=G3n(),wK=function(){},sV=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:wK,onWheelCapture:wK,onTouchMoveCapture:wK}),s=r[0],a=r[1],i=e.forwardProps,l=e.children,c=e.className,u=e.removeScrollBar,d=e.enabled,f=e.shards,p=e.sideCar,h=e.noRelative,m=e.noIsolation,g=e.inert,y=e.allowPinchZoom,b=e.as,w=b===void 0?"div":b,S=e.gapMode,k=Syt(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),_=p,C=H3n([n,t]),E=_v(_v({},k),s);return v.createElement(v.Fragment,null,d&&v.createElement(_,{sideCar:Oyt,removeScrollBar:u,shards:f,noRelative:h,noIsolation:m,inert:g,setCallbacks:a,allowPinchZoom:!!y,lockRef:n,gapMode:S}),i?v.cloneElement(v.Children.only(l),_v(_v({},E),{ref:C})):v.createElement(w,_v({},E,{className:c,ref:C}),l))});sV.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};sV.classNames={fullWidth:P9,zeroRight:R9};var Y3n=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function X3n(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Y3n();return t&&e.setAttribute("nonce",t),e}function K3n(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function J3n(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var eDn=function(){var e=0,t=null;return{add:function(n){e==0&&(t=X3n())&&(K3n(t,n),J3n(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},tDn=function(){var e=eDn();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},_yt=function(){var e=tDn(),t=function(n){var r=n.styles,s=n.dynamic;return e(r,s),null};return t},nDn={left:0,top:0,right:0,gap:0},SK=function(e){return parseInt(e||"",10)||0},rDn=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],s=t[e==="padding"?"paddingRight":"marginRight"];return[SK(n),SK(r),SK(s)]},sDn=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return nDn;var t=rDn(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},aDn=_yt(),vj="data-scroll-locked",iDn=function(e,t,n,r){var s=e.left,a=e.top,i=e.right,l=e.gap;return n===void 0&&(n="margin"),`
232
232
  .`.concat(B3n,` {
233
233
  overflow: hidden `).concat(r,`;
234
234
  padding-right: `).concat(l,"px ").concat(r,`;
@@ -768,7 +768,7 @@ window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-
768
768
  "groundTruth": "Expected result (optional)",
769
769
  "metadata": { "key": "value" } // optional
770
770
  }
771
- ]`})]})]})}function Srs({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 border-accent2/30 rounded-md p-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-accent2 mb-2",children:[o.jsx(Ue,{children:o.jsx(kp,{className:"w-4 h-4"})}),o.jsxs("span",{className:"font-medium text-sm",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-sm text-accent2/80 space-y-1",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-xs text-accent2/60 mt-2",children:["+",r," more error",r!==1?"s":""]})]})}function krs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=v.useState("upload"),[i,l]=v.useState(null),[c,u]=v.useState({current:0,total:0}),[d,f]=v.useState(null),[p,h]=v.useState(!1),{parseFile:m,isParsing:g,error:y}=yns(),{batchInsertItems:b}=_i(),w=v.useCallback(async I=>{try{const R=await m(I);l(R),a("preview")}catch{}},[m]),S=v.useCallback(async()=>{if(!i||i.items.length===0)return;a("importing"),h(!0);const{items:I}=i;u({current:0,total:I.length});try{await b.mutateAsync({datasetId:e,items:I.map(R=>({input:R.input,groundTruth:R.groundTruth,metadata:R.metadata}))}),f({success:I.length,errors:0})}catch{f({success:0,errors:I.length})}u({current:I.length,total:I.length}),h(!1),a("complete")},[i,b,e]),k=v.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&De.success(`Imported ${d.success} item${d.success!==1?"s":""}`),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150)},[n,r,d]),_=v.useCallback(()=>{p||(n(!1),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150))},[p,n]),C=i&&i.items.length>0&&i.errors.length===0,E=()=>{switch(s){case"upload":return o.jsx(wrs,{onFileSelect:w,isParsing:g,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(Srs,{errors:i.errors}),o.jsx("div",{className:"text-sm text-neutral4",children:"Please fix the errors in your JSON file and try again."})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-sm text-neutral4",children:["Found ",i.items.length," valid item",i.items.length!==1?"s":""," to import."]}),o.jsx(xrs,{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(Gt,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-lg font-medium text-neutral1",children:"Importing items..."}),o.jsxs("div",{className:"text-sm text-neutral4 mt-1",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-lg font-medium text-neutral1",children:"Import Complete"}),o.jsxs("div",{className:"text-sm text-neutral4 mt-1",children:[d?.success??0," item",d?.success!==1?"s":""," imported",d&&d.errors>0&&o.jsxs("span",{className:"text-accent2",children:[" ","(",d.errors," error",d.errors!==1?"s":"",")"]})]})]})]})}},j=()=>{switch(s){case"upload":return o.jsx(ue,{onClick:_,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(ue,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(ue,{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(ue,{variant:"primary",onClick:k,children:"Done"})}},N={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(br,{open:t,onOpenChange:_,children:o.jsxs(xr,{className:"max-w-2xl max-h-[90vh]",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:N[s]}),o.jsx(Qs,{children:"Import dataset items from a JSON file."})]}),o.jsx(Ar,{className:"min-h-[200px] max-h-[50vh] overflow-y-auto",children:E()}),o.jsx(kc,{className:"px-6 pt-4 flex justify-end gap-2",children:j()})]})})}const xTe=e=>{const t=We(),{data:n}=GM(e),r=n?.experiments;return wt({queryKey:["dataset-review-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="needs-review").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})},Ors=e=>{const t=We(),{data:n}=GM(e),r=n?.experiments;return wt({queryKey:["dataset-completed-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="complete").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})};function _rs(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 r9t({datasetId:e,experimentId:t,featuredItemId:n}){const r=We(),{data:s}=Ux(e),{data:a,isLoading:i}=xTe(e),{data:l,isLoading:c}=Ors(e),u=v.useMemo(()=>t?(a??[]).filter(Ce=>Ce.experimentId===t):a,[a,t]),d=v.useMemo(()=>t?(l??[]).filter(Ce=>Ce.experimentId===t):l,[l,t]),{updateExperimentResult:f}=_i(),[p,h]=v.useState(n??null);v.useEffect(()=>{n!==void 0&&h(n)},[n]);const[m,g]=v.useState(null),[y,b]=v.useState(new Set),[w,S]=v.useState(!1),[k,_]=v.useState(!1),[C,E]=v.useState(!1),[j,N]=v.useState(""),[I,R]=v.useState(""),[$,F]=v.useState(""),[D,V]=v.useState([]),[W,L]=v.useState(!1),[z,B]=v.useState(null),M=v.useMemo(()=>z??u??[],[z,u]);v.useEffect(()=>{B(null)},[e,t]),v.useEffect(()=>{u&&z===null&&B(u)},[u,z]);const G=v.useMemo(()=>{const Ce=new Set;if(s?.tags)for(const je of s.tags)Ce.add(je);for(const je of M)for(const _e of je.tags)Ce.add(_e);return[...Ce].sort()},[s,M]),U=v.useCallback(Ce=>{!s||!e||(s.tags??[]).includes(Ce)},[s,e]),P=v.useMemo(()=>m?m==="__untagged__"?M.filter(Ce=>Ce.tags.length===0):M.filter(Ce=>Ce.tags.includes(m)):M,[M,m]),q=v.useMemo(()=>{const Ce=new Map;for(const je of M)for(const _e of je.tags)Ce.set(_e,(Ce.get(_e)??0)+1);return[...Ce.entries()].sort((je,_e)=>_e[1]-je[1])},[M]),Z=v.useMemo(()=>M.filter(Ce=>Ce.tags.length===0).length,[M]),X=v.useMemo(()=>{let Ce=0;return m&&Ce++,w&&Ce++,Ce},[m,w]),te=v.useCallback((Ce,je)=>{B(Oe=>(Oe??[]).map(Re=>Re.id===Ce?{...Re,tags:je}:Re));const _e=M.find(Oe=>Oe.id===Ce);_e?.experimentId&&_e?.datasetId&&f.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,tags:je})},[M,f]),J=v.useCallback((Ce,je)=>{const _e=M.find(Oe=>Oe.id===Ce);_e?.traceId&&je!==void 0&&r.createFeedback({feedback:{traceId:_e.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:je==="positive"?1:-1,experimentId:_e.experimentId??void 0,sourceId:_e.id}}).catch(()=>{}),B(Oe=>(Oe??[]).map(Re=>Re.id===Ce?{...Re,rating:je}:Re))},[M,r]),ee=v.useCallback((Ce,je)=>{const _e=M.find(Oe=>Oe.id===Ce);_e?.traceId&&r.createFeedback({feedback:{traceId:_e.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:je,comment:je,experimentId:_e.experimentId??void 0,sourceId:_e.id}}).catch(()=>{}),B(Oe=>(Oe??[]).map(Re=>Re.id===Ce?{...Re,comment:je}:Re))},[M,r]),ae=v.useCallback(Ce=>{const je=M.find(_e=>_e.id===Ce);B(_e=>(_e??[]).filter(Oe=>Oe.id!==Ce)),b(_e=>{const Oe=new Set(_e);return Oe.delete(Ce),Oe}),p===Ce&&h(null),je?.experimentId&&je?.datasetId&&f.mutate({datasetId:je.datasetId,experimentId:je.experimentId,resultId:je.id,status:null})},[M,f,p]),de=v.useCallback(Ce=>{const je=M.find(_e=>_e.id===Ce);B(_e=>(_e??[]).filter(Oe=>Oe.id!==Ce)),b(_e=>{const Oe=new Set(_e);return Oe.delete(Ce),Oe}),p===Ce&&h(null),je?.experimentId&&je?.datasetId&&f.mutate({datasetId:je.datasetId,experimentId:je.experimentId,resultId:je.id,status:"complete"})},[M,f,p]),Y=v.useMemo(()=>{const Ce=w?d??[]:P;return!w||!m?Ce:m==="__untagged__"?Ce.filter(je=>je.tags.length===0):Ce.filter(je=>je.tags.includes(m))},[w,d,P,m]),ne=w?c:!1,ce=v.useMemo(()=>new Set(Y.map(Ce=>Ce.id)),[Y]),pe=v.useMemo(()=>[...y].filter(Ce=>ce.has(Ce)).length,[y,ce]),le=Y.length>0&&pe===Y.length,ve=pe>0&&!le,ye=v.useCallback(Ce=>{b(je=>{const _e=new Set(je);return _e.has(Ce)?_e.delete(Ce):_e.add(Ce),_e})},[]),Se=v.useCallback(()=>{b(le?new Set:new Set(Y.map(Ce=>Ce.id)))},[le,Y]),Ne=v.useCallback(Ce=>{for(const je of y){const _e=M.find(Oe=>Oe.id===je);_e&&!_e.tags.includes(Ce)&&te(je,[..._e.tags,Ce])}},[M,y,te]),ke=v.useCallback(Ce=>{for(const je of y){const _e=M.find(Oe=>Oe.id===je);_e&&_e.tags.includes(Ce)&&te(je,_e.tags.filter(Oe=>Oe!==Ce))}},[M,y,te]),Ie=v.useCallback(()=>{for(const Ce of y)de(Ce);b(new Set)},[y,de]),ze=v.useCallback(()=>{for(const Ce of y)ae(Ce);b(new Set)},[y,ae]),oe=v.useCallback(()=>{N(""),E(!0)},[]),se=v.useCallback(async()=>{if(!(!I||!$)){_(!0),E(!1);try{const Ce=M.filter(_e=>y.has(_e.id));if(Ce.length===0){_(!1);return}const je=await r.clusterFailures({modelId:`${I}/${$}`,items:Ce.map(_e=>({id:_e.id,input:_e.input,output:_e.output??void 0,error:typeof _e.error=="string"?_e.error:_e.error?String(_e.error):void 0,scores:_e.scores,existingTags:_e.tags.length>0?_e.tags:void 0})),availableTags:G.length>0?G:void 0,prompt:j||void 0});je.proposedTags&&je.proposedTags.length>0&&(V(je.proposedTags.map(_e=>({..._e,accepted:!0}))),L(!0))}catch(Ce){console.error("Analysis failed:",Ce)}finally{_(!1)}}},[I,$,M,y,r,G,j]),re=v.useCallback(()=>{for(const Ce of D){if(!Ce.accepted)continue;const je=M.find(_e=>_e.id===Ce.itemId);if(je){const _e=[...new Set([...je.tags,...Ce.tags])];te(je.id,_e)}}L(!1)},[D,M,te]),he=v.useCallback(Ce=>{h(je=>je===Ce?null:Ce)},[]),xe=v.useMemo(()=>p?Y.find(Ce=>Ce.id===p)??null:null,[p,Y]),Ee=p?Y.findIndex(Ce=>Ce.id===p):-1,Pe=Ee>0?()=>h(Y[Ee-1].id):void 0,Qe=Ee>=0&&Ee<Y.length-1?()=>h(Y[Ee+1].id):void 0,Ze="auto minmax(15rem,1fr) 10rem 8rem 6rem 6rem";return i?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(Gt,{className:"w-6 h-6"})}):o.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[o.jsx(br,{open:C,onOpenChange:E,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Analyze Items"}),o.jsx(Qs,{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(Rt,{className:"text-xs mb-1 block",children:"Provider"}),o.jsx(zy,{value:I,onValueChange:R})]}),o.jsxs("div",{children:[o.jsx(Rt,{className:"text-xs mb-1 block",children:"Model"}),o.jsx(By,{llmId:I,value:$,onValueChange:F})]})]}),o.jsxs(ge,{variant:"ui-xs",className:"text-neutral3",children:[y.size," item",y.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Rt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx(Yl,{value:j,onChange:Ce=>N(Ce.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"text-xs mt-1"})]})]}),o.jsxs(kc,{children:[o.jsx(ue,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),o.jsxs(ue,{onClick:se,disabled:!I||!$||k,children:[k?o.jsx(Gt,{className:"w-4 h-4 mr-1"}):null,"Analyze"]})]})]})}),o.jsx(br,{open:W,onOpenChange:L,children:o.jsxs(xr,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Review Proposed Tags"}),o.jsxs(Qs,{children:[D.filter(Ce=>Ce.accepted).length," of ",D.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:D.map((Ce,je)=>{const _e=M.find(Oe=>Oe.id===Ce.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!Ce.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx($o,{checked:Ce.accepted,onCheckedChange:Oe=>V(Re=>Re.map((qe,Ke)=>Ke===je?{...qe,accepted:!!Oe}:qe))}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 truncate block",children:_e?typeof _e.input=="string"?_e.input.slice(0,100):JSON.stringify(_e.input).slice(0,100):Ce.itemId}),o.jsx("div",{className:"flex gap-1 flex-wrap mt-1.5",children:Ce.tags.map((Oe,Re)=>o.jsx(U8t,{tag:Oe,onRename:qe=>V(Ke=>Ke.map((Ge,Ot)=>Ot===je?{...Ge,tags:Ge.tags.map((yt,nn)=>nn===Re?qe:yt)}:Ge)),onRemove:()=>V(qe=>qe.map((Ke,Ge)=>Ge===je?{...Ke,tags:Ke.tags.filter((Ot,yt)=>yt!==Re)}:Ke))},`${Oe}-${Re}`))}),Ce.reason&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:Ce.reason})]})]})},Ce.itemId)})}),o.jsxs(kc,{children:[o.jsx(ue,{variant:"outline",onClick:()=>L(!1),children:"Cancel"}),o.jsxs(ue,{onClick:re,disabled:D.filter(Ce=>Ce.accepted).length===0,children:["Accept ",D.filter(Ce=>Ce.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:K("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",xe&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid gap-8 content-start w-full overflow-y-auto",children:[o.jsxs("div",{className:"flex items-center justify-between w-full flex-wrap gap-4 gap-x-6",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(ft,{children:[o.jsx(ft.Trigger,{asChild:!0,children:o.jsxs(ue,{variant:"outline",size:"md",children:[o.jsx(vlt,{}),"Filter",X>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:X})]})}),o.jsxs(ft.Content,{align:"start",className:K("min-w-48"),children:[o.jsxs(ft.Sub,{children:[o.jsxs(ft.SubTrigger,{children:["Status",w&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(ft.SubContent,{children:[o.jsx(ft.CheckboxItem,{checked:!w,onCheckedChange:()=>{S(!1),h(null)},onSelect:Ce=>Ce.preventDefault(),children:"Review Queue"}),o.jsx(ft.CheckboxItem,{checked:w,onCheckedChange:()=>{S(!0),h(null)},onSelect:Ce=>Ce.preventDefault(),children:"Completed"})]})]}),o.jsxs(ft.Sub,{children:[o.jsxs(ft.SubTrigger,{children:["Tags",m&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(ft.SubContent,{children:[o.jsx(ft.CheckboxItem,{checked:!m,onCheckedChange:()=>g(null),onSelect:Ce=>Ce.preventDefault(),children:"All"}),Z>0&&o.jsx(ft.CheckboxItem,{checked:m==="__untagged__",onCheckedChange:()=>g(m==="__untagged__"?null:"__untagged__"),onSelect:Ce=>Ce.preventDefault(),children:"Untagged"}),q.length>0&&o.jsx(ft.Separator,{}),q.map(([Ce])=>o.jsx(ft.CheckboxItem,{checked:m===Ce,onCheckedChange:()=>g(m===Ce?null:Ce),onSelect:je=>je.preventDefault(),children:Ce},Ce))]})]}),X>0&&o.jsxs(o.Fragment,{children:[o.jsx(ft.Separator,{}),o.jsxs(ft.Item,{onSelect:()=>{g(null),S(!1),h(null)},children:[o.jsx(vs,{}),"Clear all filters"]})]})]})]}),X>0&&o.jsxs(ue,{variant:"outline",size:"md",onClick:()=>{g(null),S(!1),h(null)},children:[o.jsx(vs,{}),"Reset"]})]}),!w&&y.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(B8t,{selectedCount:y.size,vocabulary:G,onApplyTag:Ne,onRemoveTag:ke,onNewTag:Ce=>Ne(Ce)}),o.jsxs(ft,{children:[o.jsx(ft.Trigger,{asChild:!0,children:o.jsxs(ue,{disabled:k,children:[k?o.jsx(Gt,{className:"w-4 h-4"}):o.jsx(Ue,{size:"sm",children:o.jsx(Na,{})}),"Actions"]})}),o.jsxs(ft.Content,{align:"end",children:[o.jsxs(ft.Item,{onSelect:Ie,children:[o.jsx(Ue,{size:"sm",children:o.jsx(rO,{})}),"Complete"]}),o.jsxs(ft.Item,{onSelect:ze,children:[o.jsx(Ue,{size:"sm",children:o.jsx(Jc,{})}),"Remove"]}),o.jsx(ft.Separator,{}),o.jsxs(ft.Item,{onSelect:oe,children:[o.jsx(Ue,{size:"sm",children:o.jsx(bg,{})}),"Analyze"]})]})]})]})]}),ne?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(Gt,{className:"w-6 h-6"})}):Y.length===0?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsxs("div",{className:"text-center px-8",children:[o.jsx(ge,{variant:"ui-sm",className:"text-neutral3 block",children:w?"No completed reviews yet":"No items to review"}),o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 mt-2 block",children:w?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})]})}):o.jsxs(me,{columns:Ze,className:"min-w-0",children:[o.jsxs(me.Top,{hasLeadingCell:!0,children:[w?o.jsx(me.TopCell,{children:" "}):o.jsx(me.TopSelectCell,{checked:le?!0:ve?"indeterminate":!1,onToggle:()=>Se(),"aria-label":"Select all"}),o.jsxs(me.TopCells,{colStart:2,children:[o.jsx(me.TopCell,{children:"Input"}),o.jsx(me.TopCell,{children:"Comment"}),o.jsx(me.TopCell,{children:"Tags"}),o.jsx(me.TopCell,{children:"Rating"}),o.jsx(me.TopCell,{children:"Scores"})]})]}),Y.map(Ce=>{const je=Ce.scores?Object.entries(Ce.scores):[],_e=p===Ce.id,Oe=o.jsxs(o.Fragment,{children:[o.jsx(me.Cell,{height:"compact",className:"min-w-0 text-neutral4",children:o.jsx("span",{className:"block truncate",children:_rs(Ce.input,200)})}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:Ce.comment?o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 truncate",children:Ce.comment}):o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:Ce.tags.length>0?o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 truncate",children:Ce.tags.join(", ")}):o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(me.Cell,{height:"compact",children:[Ce.rating==="positive"&&o.jsx(Ue,{size:"sm",className:"text-positive1",children:o.jsx(Jye,{})}),Ce.rating==="negative"&&o.jsx(Ue,{size:"sm",className:"text-negative1",children:o.jsx(Kye,{})}),!Ce.rating&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(me.Cell,{height:"compact",children:je.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Ue,{size:"sm",className:"text-neutral3",children:o.jsx(Jh,{})}),o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 font-mono",children:je[0][1].toFixed(2)}),je.length>1&&o.jsxs(fn,{variant:"default",children:["+",je.length-1]})]}):o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(me.RowWrapper,{children:[w?o.jsx(me.Cell,{height:"compact",className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":Ce.error?"Error":"Success",title:Ce.error?"Error":"Success",className:K("w-2 h-2 rounded-full",Ce.error?"bg-red-700":"bg-green-600")})}):o.jsx(me.SelectCell,{checked:y.has(Ce.id),onToggle:()=>ye(Ce.id),"aria-label":`Select item ${Ce.id}`}),o.jsx(me.RowButton,{flushLeft:!0,colStart:2,featured:_e,onClick:()=>he(Ce.id),children:Oe})]},Ce.id)})]})]}),xe&&o.jsx(z8t,{item:xe,isCompleted:w,tagVocabulary:G,onRate:Ce=>J(xe.id,Ce),onSetTags:Ce=>{te(xe.id,Ce);for(const je of Ce)G.includes(je)||U(je)},onComment:Ce=>ee(xe.id,Ce),onRemove:()=>ae(xe.id),onComplete:w?void 0:()=>de(xe.id),onPrevious:Pe,onNext:Qe,onClose:()=>h(null)})]})]})}function Crs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n}){const{navigate:r}=yn(),[s,a]=ji(),{tab:i,activeVersion:l,handleTabChange:c}=bTe(s,a),[u,d]=v.useState(!1),[f,p]=v.useState(!1),[h,m]=v.useState(!1),[g,y]=v.useState([]),[b,w]=v.useState(!1),[S,k]=v.useState([]),[_,C]=v.useState(!1),[E,j]=v.useState([]),[N,I]=v.useState(0),[R,$]=v.useState(null),[F,D]=v.useState(""),[V]=Zwe(F,300),{data:W}=Ux(e),{data:L=[],total:z,isLoading:B,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:U}=C1(e,V||void 0,l),{total:P}=C1(e,void 0,l),[q,Z]=v.useState({}),{data:X,isLoading:te}=GM(e,void 0,q),{data:J}=GM(e),{deleteItems:ee}=_i(),ae=X?.experiments??[],de=J?.experiments??[],Y=Hns({hasSearchQuery:!!V,filteredItemsLength:L.length,unfilteredItemsTotal:P,itemsTotal:z}),{data:ne}=xTe(e),ce=ne?.length??0,pe=re=>{$(re)},le=()=>{$(null)},ve=re=>{y(re),m(!0)},ye=re=>{k(re),w(!0)},Se=re=>{w(re),re||(k([]),I(he=>he+1))},Ne=re=>{r(`/datasets/${e}/items?items=${re.join(",")}`)},ke=re=>{r(`/datasets/${e}/versions?ids=${re.join(",")}`)},Ie=re=>{j(re),C(!0)},ze=async()=>{await ee.mutateAsync({datasetId:e,itemIds:E}),De.success(`Deleted ${E.length} items`),C(!1),j([]),I(re=>re+1)},oe=re=>{m(!1),y([]),I(he=>he+1),n?.(re)},se=re=>{m(re),re||(y([]),I(he=>he+1))};return o.jsxs(o.Fragment,{children:[o.jsxs(tu,{defaultTab:"items",value:i,onValueChange:c,className:"grid grid-rows-[auto_1fr] h-full",children:[o.jsxs(eu,{children:[o.jsxs(Vr,{value:"items",children:["Items ",o.jsx(Xs,{color:"gray",children:Y})]}),o.jsxs(Vr,{value:"experiments",children:["Experiments",o.jsx(Xs,{color:"gray",children:ae.length})]}),o.jsxs(Vr,{value:"review",children:["Review",ce>0&&o.jsx(Xs,{color:"orange",children:ce})]})]}),o.jsx(ps,{value:"items",className:"grid overflow-auto mt-5 pb-0",children:o.jsx(brs,{datasetId:e,items:L,isLoading:B,featuredItemId:R,onItemSelect:pe,onItemClose:le,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>p(!0),onBulkDeleteClick:Ie,onCreateDatasetClick:ve,onAddToDatasetClick:ye,onCompareItemsClick:Ne,datasetName:W?.name,clearSelectionTrigger:N,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:U,searchQuery:F,activeSearchQuery:V,onSearchChange:D,currentDatasetVersion:W?.version,onCompareVersionsClick:ke})}),o.jsx(ps,{value:"experiments",className:"grid overflow-auto mt-5 pb-0",children:o.jsx(lrs,{experiments:ae,allExperiments:de,isLoading:te,datasetId:e,filters:q,onFiltersChange:Z})}),o.jsx(ps,{value:"review",className:"overflow-auto mt-2 pb-0",children:o.jsx(r9t,{datasetId:e})})]}),o.jsx(ers,{datasetId:e,open:u,onOpenChange:d}),o.jsx(krs,{datasetId:e,open:f,onOpenChange:p}),o.jsx(Pns,{open:h,onOpenChange:se,items:g,onSuccess:oe}),o.jsx($ns,{open:b,onOpenChange:Se,items:S,currentDatasetId:e}),o.jsx(Tt,{open:_,onOpenChange:C,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Items"}),o.jsxs(Tt.Description,{children:["Are you sure you want to delete ",E.length," item",E.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(Tt.Footer,{children:[o.jsx(Tt.Cancel,{children:"Cancel"}),o.jsx(Tt.Action,{onClick:ze,children:ee.isPending?"Deleting...":"Delete"})]})]})})]})}function Ers(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 rse({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-xs text-destructive",children:[o.jsxs("code",{className:"bg-destructive/10 px-1 rounded",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function jrs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=v.useState("{}"),[i,l]=v.useState(""),[c,u]=v.useState(""),[d,f]=v.useState(""),[p,h]=v.useState(""),[m,g]=v.useState(null),{addItem:y}=_i(),b=async C=>{C.preventDefault();let E;try{E=JSON.parse(s)}catch{De.error("Input must be valid JSON");return}let j;if(i.trim())try{j=JSON.parse(i)}catch{De.error("Ground Truth must be valid JSON");return}let N;if(c.trim())try{N=JSON.parse(c)}catch{De.error("Expected Trajectory must be valid JSON");return}let I;if(d.trim())try{const $=JSON.parse(d);if(!Array.isArray($)){De.error("Tool Mocks must be a JSON array");return}I=$}catch{De.error("Tool Mocks must be valid JSON");return}let R;if(p.trim())try{R=JSON.parse(p)}catch{De.error("Request Context must be valid JSON");return}try{await y.mutateAsync({datasetId:e,input:E,groundTruth:j,expectedTrajectory:N,toolMocks:I,requestContext:R}),De.success("Item added successfully"),g(null),a("{}"),l(""),u(""),f(""),h(""),n(!1),r?.()}catch($){const F=Ers($);F?g(F):De.error(`Failed to add item: ${$ instanceof Error?$.message:"Unknown error"}`)}},w=C=>{a(C),m?.field==="input"&&g(null)},S=C=>{l(C),m?.field==="groundTruth"&&g(null)},k=C=>{f(C),m?.field==="toolMocks"&&g(null)},_=()=>{a("{}"),l(""),u(""),f(""),h(""),g(null),n(!1)};return o.jsx(br,{open:t,onOpenChange:n,children:o.jsxs(xr,{className:"max-w-lg",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Add Item"})}),o.jsx(Ar,{children:o.jsxs("form",{onSubmit:b,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Qr,{value:s,onChange:w,showCopyButton:!1,className:"min-h-[120px]"}),m?.field==="input"&&o.jsx(rse,{field:"input",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Qr,{value:i,onChange:S,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="groundTruth"&&o.jsx(rse,{field:"groundTruth",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Qr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Qr,{value:d,onChange:k,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="toolMocks"&&o.jsx(rse,{field:"toolMocks",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Qr,{value:p,onChange:h,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ue,{type:"button",onClick:_,children:"Cancel"}),o.jsx(ue,{type:"submit",variant:"primary",disabled:y.isPending,children:y.isPending?"Adding...":"Add Item"})]})]})})]})})}function Trs({item:e}){return o.jsx(ua,{withMargins:!1,children:o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{size:"smaller",children:[o.jsx(dN,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(ya,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(ua.Description,{children:[o.jsxs(jl,{children:[o.jsx(llt,{})," Created ",er(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(jl,{children:[o.jsx(i_,{})," Version v",e.datasetVersion]})]})]})})}function wTe({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(Ywe,{children:[o.jsx(Ps.CodeSection,{title:"Input",icon:o.jsx(aO,{}),codeStr:t}),o.jsx(Ps.CodeSection,{title:"Ground Truth",icon:o.jsx(hg,{}),codeStr:n}),s&&o.jsx(Ps.CodeSection,{title:"Expected Trajectory",icon:o.jsx(Gye,{}),codeStr:s}),o.jsx(Ps.CodeSection,{title:"Metadata",icon:o.jsx(hN,{}),codeStr:r})]})}function Nrs({selectedScorers:e,setSelectedScorers:t,disabled:n=!1,container:r}){const{data:s,isLoading:a}=eh(),i=v.useMemo(()=>s?Object.entries(s).map(([l,c])=>({value:l,label:c.scorer?.config?.name||l,description:c.scorer?.config?.description||""})):[],[s]);return o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Rt,{children:"Scorers (Optional)"}),o.jsx(Xl,{multiple:!0,options:i,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||a,container:r})]})}const Irs=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Ars({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=km(),{data:l,isLoading:c}=Uy(),{data:u,isLoading:d}=eh(),f=e==="agent"?Object.entries(a??{}).map(([g,y])=>({value:g,label:y.name??g})):e==="workflow"?Object.entries(l??{}).map(([g,y])=>({value:g,label:y.name??g})):e==="scorer"?Object.entries(u??{}).map(([g,y])=>({value:g,label:y.scorer?.config?.name??g})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=g=>{t(g),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Rt,{children:"Target Type"}),o.jsx(Xl,{options:Irs,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(Rt,{children:m}),o.jsx(Xl,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}function Rrs({requestContextSchema:e,onChange:t}){const n=v.useMemo(()=>{try{return um(lm(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(Rt,{children:"Request Context"}),o.jsx(HD,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-sm text-destructive",children:"Failed to parse request context schema"})}function Prs({datasetId:e,version:t,requestContextSchema:n,open:r,onOpenChange:s,onSuccess:a}){const i=v.useRef(null),[l,c]=v.useState(""),[u,d]=v.useState(""),[f,p]=v.useState([]),[h,m]=v.useState({}),[g,y]=v.useState(""),{triggerExperiment:b}=_i(),w=!!(n&&Object.keys(n).length>0),S=l&&u,k=b.isPending,_=()=>{c(""),d(""),p([]),m({}),y("")},C=()=>{if(w){const N=Object.entries(h).filter(([,I])=>I!==void 0&&I!=="");return N.length>0?Object.fromEntries(N):void 0}if(g.trim()){let N;try{N=JSON.parse(g)}catch{throw new Error("Request Context must be valid JSON")}if(!N||typeof N!="object"||Array.isArray(N))throw new Error("Request Context must be a JSON object");return N}},E=async()=>{if(!S)return;let N;try{N=C()}catch(I){const R=I instanceof Error?I.message:"Request Context must be valid JSON";ju.error(R);return}try{const I=await b.mutateAsync({datasetId:e,targetType:l,targetId:u,scorerIds:f.length>0?f:void 0,version:t,requestContext:N});ju.success("Experiment triggered successfully"),s(!1),a?.(I.experimentId),_()}catch(I){const R=I instanceof Error?I.message:"Failed to trigger experiment";ju.error(R)}},j=()=>{k||(s(!1),_())};return o.jsx(br,{open:r,onOpenChange:j,children:o.jsxs(xr,{ref:i,children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Run Experiment"}),o.jsx(Qs,{children:t?`Execute items from ${er(new Date(t),"MMM d, yyyy")} version against a target.`:"Execute all items in this dataset against a target."})]}),o.jsxs(Ar,{className:"grid gap-6",children:[o.jsx(Ars,{targetType:l,setTargetType:c,targetId:u,setTargetId:d,container:i}),l&&l!=="scorer"&&o.jsx(Nrs,{selectedScorers:f,setSelectedScorers:p,disabled:k,container:i}),w?o.jsx(Rrs,{requestContextSchema:n,onChange:m}):o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{children:"Request Context (JSON, optional)"}),o.jsx(Qr,{value:g,onChange:y,showCopyButton:!1,className:"min-h-[80px]"})]})]}),o.jsxs(kc,{className:"px-6 pt-4",children:[o.jsx(ue,{onClick:j,disabled:k,children:"Cancel"}),o.jsx(ue,{variant:"primary",onClick:E,disabled:!S||k,children:k?o.jsxs(o.Fragment,{children:[o.jsx(Gt,{className:"w-4 h-4"}),"Running..."]}):"Run"})]})]})})}const $rs=e=>{const t=We();return wt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},enabled:!!e})};function sse(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function Mrs({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(bn.SectionHeading,{icon:o.jsx(tm,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(In,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(In.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: ",sse(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>sse(i.args)).join(", ")]})]})}),o.jsx("div",{className:"rounded border border-border1 divide-y divide-border1 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:"font-mono text-neutral4",children:i.toolName}),o.jsx("span",{className:"ml-2 font-mono text-xs text-neutral3",children:sse(i.args)})]}),o.jsx("span",{className:`shrink-0 text-xs px-2 py-0.5 rounded ${Drs(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function Drs(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 Lrs({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d,onCollapsedChange:f}){const[p,h]=v.useState(!1),m=d??p,g=f??h,y=!!e?.error,b=Z8(e?.input),w=Z8(e?.output),S=Z8(e?.groundTruth),k=u&&e.status!=="needs-review"&&e.status!=="complete",_=Array.isArray(e.tags)?e.tags:[];return o.jsxs(bn,{collapsed:m,children:[o.jsxs(bn.Header,{children:[o.jsxs(bn.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs($r,{className:"ml-auto shrink-0",children:[f&&o.jsx(ue,{size:"md",tooltip:m?"Expand panel":"Collapse panel",onClick:()=>g(!m),children:m?o.jsx(flt,{}):o.jsx(dlt,{})}),o.jsx(bn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),o.jsxs(ue,{size:"md",onClick:a,disabled:!e.traceId,children:[o.jsx(wOe,{}),"Trace"]}),o.jsx(bn.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!m&&o.jsxs(bn.Content,{children:[o.jsxs("div",{className:"grid gap-4 mb-6",children:[o.jsxs(zt,{children:[o.jsx(zt.Key,{children:"Item Id"}),o.jsx(zt.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(zt.Key,{children:"Created"}),o.jsx(zt.Value,{children:er(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),y&&o.jsx(In,{variant:"destructive",title:"Error",children:o.jsx(In.Message,{children:Z8(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(me,{columns:"1fr 1fr",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Scorer"}),o.jsx(me.TopCell,{children:"Score"})]}),t.map(C=>o.jsxs(me.RowButton,{featured:c===C.id,onClick:()=>l?.(C.id),children:[o.jsx(me.Cell,{height:"compact",children:C.scorerId}),o.jsx(me.MonoCell,{children:C.score.toFixed(3)})]},C.id))]}),e.toolMockReport&&o.jsx(Mrs,{report:e.toolMockReport}),(e.status||_.length>0||k)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(bn.SectionHeading,{icon:o.jsx(hN,{}),className:"mb-2",children:"Review"}),(e.status||_.length>0)&&o.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.status&&o.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${e.status==="needs-review"?"bg-orange-500/10 text-orange-400":e.status==="complete"?"bg-accent1/10 text-accent1":"bg-neutral3/10 text-neutral4"}`,children:e.status}),_.map(C=>o.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-surface4 text-neutral4",children:C},C))]}),k&&o.jsx("div",{children:o.jsxs(ue,{size:"sm",onClick:()=>u(e.id),children:[o.jsx(GU,{}),"Flag for Review"]})}),e.status==="needs-review"&&i&&o.jsx("div",{children:o.jsxs(ue,{size:"sm",onClick:i,children:[o.jsx(Pa,{}),"Review"]})})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(bn.CodeSection,{title:"Input",icon:o.jsx(dN,{}),codeStr:b}),o.jsx(bn.CodeSection,{title:"Output",icon:o.jsx(hg,{}),codeStr:w}),o.jsx(bn.CodeSection,{title:"Ground Truth",icon:o.jsx(Xye,{}),codeStr:S})]})]})]})}function Z8(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Frs({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:a,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,selectedIds:d,onToggleSelect:f}){const p=!!(d&&f),h=[p?"auto":"",...s.map(g=>g.size)].filter(Boolean).join(" "),m=s.some(g=>g.name==="input");return t?o.jsx(el,{columns:h}):o.jsxs(me,{columns:h,className:"min-w-0",children:[o.jsxs(me.Top,{hasLeadingCell:p,children:[p&&o.jsx(me.TopCell,{children:" "}),p?o.jsx(me.TopCells,{colStart:2,children:s.map(g=>o.jsx(me.TopCell,{children:g.label},g.name))}):s.map(g=>o.jsx(me.TopCell,{children:g.label},g.name))]}),e.length===0?o.jsx(me.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map(g=>{const y=!!g.error,b=g.id===n,w=o.jsxs(o.Fragment,{children:[o.jsx(me.IdCell,{id:g.itemId}),o.jsx(me.Cell,{height:"compact",children:o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsx("div",{className:"flex items-center justify-center w-10 relative bg-transparent h-full",children:o.jsx("div",{role:"img","aria-label":y?"Error":"Success",className:K("w-2 h-2 rounded-full",y?"bg-red-700":"bg-green-600")})})}),o.jsx(Bn,{children:y?"Error":"Success"})]})}),m&&o.jsx(me.MonoCell,{children:Brs(zrs(g.input),200)}),i?.map(S=>{const _=a?.[g.itemId]?.find(C=>C.scorerId===S);return o.jsx(me.Cell,{height:"compact",className:"font-mono text-neutral3 text-ui-smd",children:_!=null?_.score.toFixed(3):"-"},S)})]});return p?o.jsxs(me.RowWrapper,{children:[o.jsx(me.SelectCell,{checked:d.has(g.id),onToggle:()=>f(g.id),"aria-label":`Select result ${g.itemId}`}),o.jsx(me.RowButton,{flushLeft:!0,colStart:2,featured:b,onClick:()=>r(g.id),children:w})]},g.id):o.jsx(me.RowButton,{featured:b,onClick:()=>r(g.id),children:w},g.id)}),o.jsx(me.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function zrs(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Brs(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function Urs(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function qrs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i}){const[l,c]=v.useState(!1),u=a??l,d=i??c,f=Urs(e),p=f?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(bn,{collapsed:u,children:[o.jsxs(bn.Header,{children:[o.jsxs(bn.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs($r,{className:"ml-auto shrink-0",children:[i&&o.jsx(ue,{size:"md",tooltip:u?"Expand panel":"Collapse panel",onClick:()=>d(!u),children:u?o.jsx(flt,{}):o.jsx(dlt,{})}),(n||t)&&o.jsx(bn.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&o.jsxs(ue,{size:"md",onClick:s,disabled:!e.traceId,children:[o.jsx(wOe,{}),"Trace"]}),o.jsx(bn.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!u&&o.jsx(bn.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(bn.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(Jh,{}),codeStr:e.reason||p,simplified:!0}),!f&&o.jsxs(o.Fragment,{children:[o.jsx(bn.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(bh,{}),codeStr:e.preprocessPrompt||p,simplified:!0}),o.jsx(bn.CodeSection,{title:"Analyze Prompt",icon:o.jsx(bh,{}),codeStr:e.analyzePrompt||p,simplified:!0}),o.jsx(bn.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(bh,{}),codeStr:e.generateScorePrompt||p,simplified:!0}),o.jsx(bn.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(bh,{}),codeStr:e.generateReasonPrompt||p,simplified:!0})]})]})})]})}const $Qe=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"avg",label:"Avg Score",size:"1fr"},{name:"count",label:"Items Scored",size:"1fr"}];function Vrs({scoresByItemId:e,experimentStatus:t}){const n=v.useMemo(()=>{if(!e)return[];const r={};for(const s of Object.values(e))for(const a of s)r[a.scorerId]||(r[a.scorerId]={sum:0,count:0}),r[a.scorerId].sum+=a.score,r[a.scorerId].count++;return Object.entries(r).map(([s,{sum:a,count:i}])=>({scorerId:s,avg:a/i,count:i})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))},[e]);if(n.length===0){const r=t==="running"||t==="pending",s=e!==void 0;let a,i;return r?(a="Experiment in progress",i="Summary metrics will appear here once the experiment completes."):s?(a="No scorers configured",i="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(a="Loading scores",i="Fetching scorer results…"),o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(Lr,{iconSlot:o.jsx(Jh,{className:"w-8 h-8 text-neutral3"}),titleSlot:a,descriptionSlot:i})})}return o.jsxs(gn,{children:[o.jsxs(gn.Header,{columns:$Qe,children:[o.jsx(gn.HeaderCol,{children:"Scorer"}),o.jsx(gn.HeaderCol,{children:"Avg Score"}),o.jsx(gn.HeaderCol,{children:"Items Scored"})]}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:n.map(({scorerId:r,avg:s,count:a})=>o.jsxs(gn.Row,{columns:$Qe,children:[o.jsx(gn.TextCell,{children:r}),o.jsx(gn.TextCell,{className:"font-mono",children:s.toFixed(3)}),o.jsx(gn.TextCell,{className:"font-mono",children:a})]},r))})})]})}function s9t({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const[c,u]=v.useState(null),[d,f]=v.useState(null),[p,h]=v.useState(void 0),[m,g]=v.useState(null),[y,b]=v.useState(new Set),[w,S]=v.useState(!1),[k,_]=v.useState(!1),[C,E]=v.useState(!1),[j,N]=v.useState(!1),{updateExperimentResult:I}=_i(),R=v.useCallback(se=>{b(re=>{const he=new Set(re);return he.has(se)?he.delete(se):he.add(se),he})},[]),$=v.useCallback(()=>b(new Set),[]),F=v.useCallback(()=>{const se=r.filter(re=>!!re.error).map(re=>re.id);b(new Set(se))},[r]),D=v.useCallback(async se=>{if(w||se.length===0)return;S(!0);let re=0;const he=new Set;try{for(const xe of se)try{await I.mutateAsync({datasetId:t,experimentId:e,resultId:xe,status:"needs-review"}),re++,he.add(xe)}catch{}}finally{S(!1)}he.size>0&&b(xe=>{const Ee=new Set(xe);for(const Pe of he)Ee.delete(Pe);return Ee}),re>0&&De(`${re} result${re>1?"s":""} flagged for review`)},[t,e,w,I]),V=r.find(se=>se.id===c)??null,[W,L]=v.useState("summary"),[z,B]=v.useState(null),M=se=>{L(se),se!=="reviews"&&B(null)},{data:G}=xTe(t),U=(G??[]).filter(se=>se.experimentId===e).length,{data:P}=M8t(e,n),q=v.useMemo(()=>{if(!P)return[];const se=new Set;for(const re of Object.values(P))for(const he of re)se.add(he.scorerId);return[...se].sort()},[P]),Z=se=>{u(se),f(null),h(void 0),g(null)},X=se=>{Z(se===c?null:se)},te=()=>{Z(null)},J=()=>{if(!V)return;const se=r.findIndex(re=>re.id===V.id);if(se>=0&&se<r.length-1)return()=>Z(r[se+1].id)},ee=()=>{if(!V)return;const se=r.findIndex(re=>re.id===V.id);if(se>0)return()=>Z(r[se-1].id)},ae=V?P?.[V.itemId]:void 0,de=ae?.find(se=>se.id===m)??null,Y=se=>{g(se===m?null:se),f(null),h(void 0)},ne=()=>{if(!m||!ae)return;const se=ae.findIndex(re=>re.id===m);if(se>=0&&se<ae.length-1)return()=>g(ae[se+1].id)},ce=()=>{if(!m||!ae)return;const se=ae.findIndex(re=>re.id===m);if(se>0)return()=>g(ae[se-1].id)},{data:pe,isLoading:le}=$rs(d),ve=pe?.spans,{data:ye,isLoading:Se}=pI(d,p),Ne=ye?.span,{handlePreviousSpan:ke,handleNextSpan:Ie}=KH(ve,p??null,h),ze=(()=>{const se=[],re=!!de,he=!!d;return se.push(k?"auto":re||he?"2fr":"1fr"),re&&se.push(j?"auto":"3fr"),he&&se.push(C?"auto":"3fr"),he&&p&&se.push("3fr"),se.join(" ")})(),oe=v.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"status",label:"Status",size:"5rem"},{name:"input",label:"Input",size:"minmax(15rem,1fr)"},...q.map(se=>({name:se,label:se,size:"12rem"}))],[q]);return o.jsxs(tu,{defaultTab:"summary",value:W,onValueChange:M,className:"grid grid-rows-[auto_1fr] h-full overflow-hidden",children:[o.jsxs(eu,{children:[o.jsx(Vr,{value:"summary",children:"Summary"}),o.jsx(Vr,{value:"results",children:"Results"}),o.jsxs(Vr,{value:"reviews",children:["Reviews",U>0&&o.jsx(Xs,{color:"orange",children:U})]})]}),o.jsx(ps,{value:"summary",className:"overflow-y-auto mt-5",children:o.jsx(Vrs,{scoresByItemId:P,experimentStatus:n})}),o.jsx(ps,{value:"reviews",className:"overflow-auto mt-2 pb-0",children:o.jsx(r9t,{datasetId:t,experimentId:e,featuredItemId:z})}),o.jsxs(ps,{value:"results",className:"grid grid-rows-[auto_1fr] overflow-hidden mt-2",children:[o.jsxs("div",{className:"mb-4",children:[y.size>0&&o.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-surface3",children:[o.jsxs(ge,{variant:"ui-xs",className:"text-neutral5 font-medium",children:[y.size," selected"]}),o.jsx("div",{className:"flex-1"}),o.jsxs(ue,{variant:"outline",size:"sm",disabled:w,onClick:()=>D([...y]),children:[o.jsx(Ue,{size:"sm",children:o.jsx(GU,{})}),"Flag for Review"]}),o.jsx(ue,{variant:"ghost",size:"sm",onClick:$,children:"Clear"})]}),r.length>0&&y.size===0&&!s&&o.jsx("div",{className:"flex items-center gap-2 px-4 py-2",children:o.jsx(ue,{variant:"ghost",size:"sm",onClick:F,children:"Select loaded failures"})})]}),o.jsxs("div",{className:K("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",V&&"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"flex overflow-y-auto w-full",children:o.jsx("div",{className:"grid gap-8 content-start w-full overflow-y-auto",children:o.jsx(Frs,{results:r,isLoading:s,featuredResultId:c,onResultClick:X,columns:oe,scoresByItemId:P,scorerIds:q,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:y,onToggleSelect:R})})}),V&&o.jsxs("div",{className:"grid gap-4 max-h-full min-h-0 overflow-auto content-start",style:{gridTemplateRows:ze},children:[o.jsx(Lrs,{result:V,scores:ae,onPrevious:ee(),onNext:J(),onClose:te,onScoreClick:Y,featuredScoreId:m,onShowTrace:()=>{V.traceId&&(f(V.traceId),h(void 0),g(null),_(!0),E(!1))},onOpenInReview:()=>{B(V.id),L("reviews")},onFlagForReview:se=>D([se]),collapsed:k,onCollapsedChange:_}),de&&o.jsx(qrs,{score:de,onNext:ne(),onPrevious:ce(),onClose:()=>g(null),onShowTrace:()=>{de.traceId&&(f(de.traceId),h(void 0),_(!0),N(!0),E(!1))},collapsed:j,onCollapsedChange:N}),d&&o.jsxs(o.Fragment,{children:[o.jsx(TOe,{traceId:d,spans:ve,isLoading:le,onClose:()=>{f(null),h(void 0),_(!1),N(!1)},onSpanSelect:h,initialSpanId:p??null,placement:"traces-list",showUnavailableFeaturesMsg:!1,collapsed:C,onCollapsedChange:E,LinkComponent:R3,traceHref:`/traces/${d}`}),p&&o.jsx(YH,{traceId:d,spanId:p,span:Ne,isLoading:Se,onPrevious:ke,onNext:Ie,onClose:()=>h(void 0)})]})]})]})]})]})}const Hrs={pending:o.jsx(sO,{}),running:o.jsx(Fde,{}),completed:o.jsx(Js,{}),failed:o.jsx(vs,{})};function Wrs({experiment:e,className:t}){const n=e.status,r=e.totalItems-e.succeededCount-e.failedCount;return o.jsxs("div",{className:K("grid justify-items-end gap-3",t),children:[o.jsxs("div",{className:"flex p-1 px-3 text-ui-lg capitalize text-neutral4 gap-2 items-center bg-surface5 rounded-lg ",children:[o.jsx("span",{className:K("w-5 h-5 flex items-center justify-center rounded-full text-black","[&>svg]:w-4 [&>svg]:h-4",{"bg-green-700":n==="completed","bg-red-700":n==="failed","bg-cyan-600":n==="running","bg-yellow-600":n==="pending"}),children:Hrs[n]}),e.status]}),o.jsxs("div",{className:K("flex items-center gap-3 text-neutral3 text-ui-md ","[&>span]:flex [&>span]:gap-1 [&>span]:items-center ","[&_b]:text-neutral4 [&_b]:font-semibold"),children:[o.jsxs("span",{children:["Total: ",o.jsx("b",{children:e.totalItems})]}),o.jsxs("span",{children:["Succeeded: ",o.jsx("b",{children:e.succeededCount})]}),o.jsxs("span",{children:["Failed: ",o.jsx("b",{children:e.failedCount})]}),(n==="pending"||n==="running")&&o.jsxs("span",{children:["Pending: ",o.jsx("b",{children:r})]})]})]})}function Zrs({onPrevious:e,onNext:t,previousAriaLabel:n="Previous",nextAriaLabel:r="Next"}){return o.jsxs($r,{spacing:"close",children:[o.jsxs(ue,{onClick:e,disabled:!e,"aria-label":n,children:[o.jsx($q,{})," Prev"]}),o.jsxs(ue,{onClick:t,disabled:!t,"aria-label":r,children:["Next",o.jsx(Rq,{})]})]})}function STe({delta:e}){const t=e>0?o.jsx(Xs,{size:"small",color:"green",intensity:"muted",children:o.jsx(i3,{})}):e<0?o.jsx(Xs,{size:"small",color:"red",intensity:"muted",children:o.jsx(Won,{})}):null;return o.jsxs("span",{className:K("font-mono text-sm text-neutral4 min-w-20"),children:[o.jsx("span",{className:"w-3 inline-block",children:e>0?"+ ":e<0?"- ":""}),Math.abs(e).toFixed(2)," ",t]})}function G8(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Grs({item:e,baselineId:t,contenderId:n,baselineVersion:r,contenderVersion:s,onPrevious:a,onNext:i,onClose:l}){const c=e.results[t],u=e.results[n],d=!!(c&&u),f=new Set;if(c)for(const h of Object.keys(c.scores))f.add(h);if(u)for(const h of Object.keys(u.scores))f.add(h);const p=[...f].sort();return o.jsxs(Gr,{withLeftSeparator:!0,children:[o.jsxs(Gr.Toolbar,{children:[o.jsx(Zrs,{onPrevious:a,onNext:i,previousAriaLabel:"Previous comparison item",nextAriaLabel:"Next comparison item"}),o.jsx($r,{children:o.jsx(ue,{onClick:l,"aria-label":"Close comparison detail panel",children:o.jsx(vs,{})})})]}),o.jsxs(Gr.Content,{className:"pb-6",children:[o.jsx(ua,{withMargins:!1,children:o.jsx(ua.Column,{children:o.jsxs(ua.Title,{size:"smaller",children:[o.jsx(dN,{})," ",e.itemId]})})}),d?o.jsx(o.Fragment,{children:o.jsxs(Ywe,{children:[p.length>0&&o.jsxs("div",{className:"grid gap-3",children:[o.jsx("h4",{className:"text-sm font-medium text-neutral5",children:"Scores"}),o.jsx("div",{className:"grid gap-2",children:p.map(h=>{const m=c?.scores[h]??null,g=u?.scores[h]??null,y=m!=null&&g!=null?g-m:null;return o.jsxs("div",{className:"flex items-center justify-between gap-4 px-3 py-2 rounded-lg bg-surface2",children:[o.jsx("span",{className:"text-sm text-neutral5 font-medium",children:h}),o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("span",{className:"text-sm text-neutral3",children:[m!=null?m.toFixed(3):"-"," →"," ",g!=null?g.toFixed(3):"-"]}),y!=null&&o.jsx(STe,{delta:y})]})]},h)})})]}),o.jsx(Ps.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(Xs,{color:"purple",children:"Baseline "})," Experiment Output"]}),icon:o.jsx(hg,{}),codeStr:G8(c?.output)}),o.jsx(Ps.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(Xs,{color:"cyan",children:"Contender "})," Experiment Output"]}),icon:o.jsx(hg,{}),codeStr:G8(u?.output)}),o.jsx(Ps.CodeSection,{title:"Item Input",icon:o.jsx(aO,{}),codeStr:G8(e.input)}),o.jsx(Ps.CodeSection,{title:"Item Ground Truth",icon:o.jsx(Xye,{}),codeStr:G8(e.groundTruth)})]})}):o.jsx(In,{variant:"warning",title:"Comparison not available",children:o.jsx(In.Message,{children:(()=>{const h=c?"Contender":"Baseline",m=c?s:r;return o.jsxs(o.Fragment,{children:["The ",h," experiment was run against dataset",m!=null?` v. ${m}`:"",", which does not contain this item."]})})()})})]})]})}function Qrs({items:e,baselineId:t,contenderId:n,scorerIds:r,featuredItemId:s,columns:a,onItemClick:i}){return o.jsx(Gr,{children:o.jsxs(gn,{children:[o.jsxs(gn.Header,{columns:a,children:[o.jsx(gn.HeaderCol,{children:"Item ID"}),!s&&r.map(l=>o.jsx(gn.HeaderCol,{className:"flex justify-center",children:l},l))]}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:e.map(l=>{const c=l.results[t],u=l.results[n],d=!!(c&&u);return o.jsx(gn.Row,{children:o.jsxs(gn.RowButton,{item:{id:l.itemId},columns:a,isFeatured:s===l.itemId,onClick:i,children:[o.jsx(gn.IdCell,{id:l.itemId,className:d?"":"text-neutral1"}),!s&&o.jsx(o.Fragment,{children:r.map(f=>{const p=c?.scores[f]??null,h=u?.scores[f]??null,m=p!=null&&h!=null?h-p:null;return o.jsx(gn.Cell,{className:"flex items-center gap-5 justify-center font-mono",children:m!=null?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"flex items-center text-neutral2 min-w-24",children:[p?.toFixed(2)," → ",h?.toFixed(2)]}),o.jsx(STe,{delta:m})]}):o.jsx("span",{className:"text-neutral1",children:"-"})},f)})})]})},l.itemId)})})})]})})}const Yrs={baseline:{label:"Baseline",color:"purple",customStyle:"items-end justify-items-end [&>div]:justify-end border-r-0 rounded-r-none"},contender:{label:"Contender",color:"cyan",customStyle:"items-start justify-items-start [&>div]:justify-start border-l-0 rounded-l-none"}};function MQe({datasetId:e,experiment:t,type:n}){const{Link:r}=yn(),{label:s,color:a,customStyle:i}=Yrs[n];if(!t)return null;const l=t.createdAt?new Date(t.createdAt):null;return o.jsxs("div",{className:`grid border-2 border-border1 rounded-lg p-5 gap-3 ${i}`,children:[o.jsxs("div",{className:"flex items-center gap-3 w-full overflow-clip",children:[n==="contender"&&o.jsxs(Xs,{size:"small",color:a,children:[s,o.jsx(hm,{})]}),o.jsx(ue,{as:r,href:`/datasets/${e}/experiments/${t.id}`,children:o.jsx("span",{className:"truncate min-w-0",children:t.id})}),n==="baseline"&&o.jsxs(Xs,{size:"small",color:a,children:[o.jsx(Ec,{})," ",s]})]}),o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-ui-sm text-neutral3",children:[o.jsxs(jl,{children:[o.jsx(Xye,{})," ",t.targetType," / ",t.targetId]}),o.jsxs(jl,{children:[o.jsx(XU,{})," v",t.datasetVersion??"—"]}),l&&o.jsxs(jl,{children:[o.jsx(clt,{})," ",er(l,"MMM d, yyyy HH:mm")]})]})]})}function Xrs({datasetId:e,experimentIdA:t,experimentIdB:n,onSwap:r}){const[s,a]=v.useState(null),{data:i,isLoading:l,error:c}=lns(e,t,n),{data:u}=CU(e,t),{data:d}=CU(e,n),f=u&&d&&u.datasetVersion!==d.datasetVersion,p=v.useMemo(()=>{if(!i)return[];const E=new Set;for(const j of i.items)for(const N of Object.values(j.results))if(N)for(const I of Object.keys(N.scores))E.add(I);return[...E].sort()},[i]),h=v.useMemo(()=>{if(!i||p.length===0)return[];const E=i.baselineId,j=t===E?n:t;return p.map(N=>{let I=0,R=0,$=0,F=0;for(const L of i.items){const z=L.results[E]?.scores[N],B=L.results[j]?.scores[N];z!=null&&(I+=z,$++),B!=null&&(R+=B,F++)}const D=$>0?I/$:null,V=F>0?R/F:null,W=D!=null&&V!=null?V-D:null;return{scorerId:N,avgA:D,avgB:V,delta:W}})},[i,p,t,n]),m=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"baselineAvg",label:"Baseline Avg",size:"1fr"},{name:"comparisonAvg",label:"Comparison Avg",size:"1fr"},{name:"delta",label:"Delta",size:"1fr"}],g=v.useMemo(()=>[{name:"itemId",label:"Item ID",size:"8rem"},...s?[]:p.map(E=>({name:E,label:E,size:"1fr"}))],[p,s]),y=i?.items.find(E=>E.itemId===s)??null,b=E=>{a(E===s?null:E)},w=()=>{a(null)},S=()=>{if(!i||!s)return;const E=i.items.findIndex(j=>j.itemId===s);if(E>=0&&E<i.items.length-1)return()=>a(i.items[E+1].itemId)},k=()=>{if(!i||!s)return;const E=i.items.findIndex(j=>j.itemId===s);if(E>0)return()=>a(i.items[E-1].itemId)};if(l)return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx(Gt,{})});if(c)return o.jsx(In,{variant:"warning",title:"Error loading comparison",children:o.jsx(In.Message,{children:c instanceof Error?c.message:"Unknown error"})});if(!i||i.items.length===0)return o.jsx("div",{className:"text-neutral4 text-sm text-center py-8",children:"No comparison data"});const _=i.baselineId,C=t===_?n:t;return o.jsxs("div",{className:"grid gap-10",children:[u&&d&&o.jsxs("div",{className:K("relative grid xl:grid-cols-[1fr_auto_1fr] gap-4 xl:gap-0"),children:[o.jsx(MQe,{datasetId:e,experiment:u,type:"baseline"}),o.jsx("div",{className:"relative flex items-center justify-center px-[2vw] before:absolute before:inset-y-0 before:left-1/2 before:-translate-x-1/2 before:w-[2px] before:bg-border1",children:o.jsx("div",{className:"relative z-1 bg-surface2 rounded-lg p-2",children:o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsx(ue,{onClick:r,children:"VS"})}),o.jsx(Bn,{children:"Switch the order"})]})})}),o.jsx(MQe,{datasetId:e,experiment:d,type:"contender"})]}),f&&o.jsx(In,{variant:"warning",title:"Version mismatch",children:o.jsxs(In.Message,{children:["These experiments used different dataset versions (v",u.datasetVersion," vs v",d.datasetVersion,"). Results may not be directly comparable."]})}),h.length>0&&o.jsxs(gn,{children:[o.jsxs(gn.Header,{columns:m,children:[o.jsx(gn.HeaderCol,{children:"Scorer"}),o.jsx(gn.HeaderCol,{className:"flex justify-center",children:o.jsxs(h9e,{children:[o.jsx(Xs,{color:"purple",size:"small",intensity:"muted",children:"Baseline"}),o.jsx(Xs,{color:"purple",size:"small",children:"Avg"})]})}),o.jsx(gn.HeaderCol,{className:"flex justify-center",children:o.jsxs(h9e,{children:[o.jsx(Xs,{color:"cyan",size:"small",intensity:"muted",children:"Contender"}),o.jsx(Xs,{color:"cyan",size:"small",children:"Avg"})]})}),o.jsx(gn.HeaderCol,{className:"flex justify-center",children:"Delta"})]}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:h.map(({scorerId:E,avgA:j,avgB:N,delta:I})=>o.jsxs(gn.Row,{columns:m,children:[o.jsx(gn.TextCell,{children:E}),o.jsx(gn.TextCell,{className:"text-center font-mono",children:j!=null?j.toFixed(3):"-"}),o.jsx(gn.TextCell,{className:"text-center font-mono",children:N!=null?N.toFixed(3):"-"}),o.jsx(gn.TextCell,{className:"flex justify-center",children:I!=null?o.jsx(STe,{delta:I}):"-"})]},E))})})]}),o.jsxs(Yv,{className:K({"grid-cols-[1fr_2fr]":!!y}),children:[o.jsx(Qrs,{items:i.items,baselineId:_,contenderId:C,scorerIds:p,featuredItemId:s,columns:g,onItemClick:b}),!!y&&o.jsx(Grs,{item:y,baselineId:_,contenderId:C,baselineVersion:u?.datasetVersion,contenderVersion:d?.datasetVersion,onPrevious:k(),onNext:S(),onClose:w})]})]})}function Krs({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=yTe(e,t),[l,c]=v.useState(!1),[u,d]=v.useState(new Set),f=b=>{n?.(b)},p=b=>s==null?b.isLatest:b.datasetVersion===s,h=b=>{d(w=>{const S=new Set(w);if(S.has(b))S.delete(b);else if(S.size>=2){const[k]=Array.from(S);return new Set([k,b])}else S.add(b);return S})},m=()=>{c(!1),d(new Set)},g=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(Gr,{className:"min-w-56",children:[l?o.jsx(Gr.Toolbar,{className:"grid justify-stretch gap-3 w-full",children:o.jsxs($r,{children:[o.jsx(ue,{onClick:m,children:"Cancel"}),o.jsx(ue,{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(Gr.Toolbar,{children:o.jsxs(ue,{onClick:g,className:"w-full",children:[o.jsx(Qw,{})," Compare Ver."]})})}),i?o.jsx(Jrs,{}):o.jsxs(gn,{children:[o.jsx(gn.Header,{children:o.jsx(gn.HeaderCol,{children:"Item Version History"})}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:a?.map(b=>{const w=String(b.datasetVersion),S=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(gn.Row,{isSelected:l&&u.has(w),children:[l&&o.jsx(gn.LabelCell,{children:o.jsx($o,{checked:u.has(w),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||h(w)},"aria-label":`Select version ${b.datasetVersion}`})}),o.jsx(gn.RowButton,{item:b,columns:[{name:"version",label:"Item Version History",size:"1fr"}],isFeatured:p(b),onClick:()=>f(b),className:"py-2",children:o.jsx(gn.VersionCell,{version:b.datasetVersion,date:S,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function Jrs(){return o.jsxs(gn,{children:[o.jsx(gn.Header,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(gn.HeaderCol,{children:"Item Version History"})}),o.jsx(gn.Items,{children:Array.from({length:3}).map((e,t)=>o.jsx(gn.Row,{children:o.jsx(gn.RowButton,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(gn.TextCell,{isLoading:!0,children:"Loading..."})})},t))})]})}function ess(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${er(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function tss({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=mTe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${ess(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(Gr.Toolbar,{className:"grid grid-cols-[1fr_1fr_1fr_10rem] gap-4 w-full",children:[o.jsx("div",{}),o.jsx(bc,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(bc,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const nss=[{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"}],rss={added:{color:"blue",borderColor:"border-blue-900",icon:o.jsx(Fr,{}),tooltip:"Added in this version"},changed:{color:"orange",borderColor:"border-yellow-900",icon:o.jsx(jlt,{}),tooltip:"Changed in this version"},same:{color:"green",borderColor:"border-green-900",icon:o.jsx(gcn,{}),tooltip:"Same in both versions"}};function ase({red:e=!1,tooltip:t}){return o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsx(nln,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),t&&o.jsx(Bn,{children:t})]})}function VS({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{color:n,icon:r,tooltip:s}=rss[e];return o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"pr-3 text-ui-md text-neutral4 min-w-16 flex justify-end",children:["v. ",t]}),o.jsx(Xs,{color:n,size:"small",children:r})]})}),o.jsx(Bn,{children:s})]})}function sss(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function ass({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=yn(),l=t>n;return o.jsx(gn,{children:o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=sss(u,d);return o.jsxs(gn.Row,{columns:nss,children:[o.jsx(gn.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!d&&l?o.jsx(VS,{variant:"added",version:u.datasetVersion}):f==="changed"&&l?o.jsx(VS,{variant:"changed",version:u.datasetVersion}):o.jsx(VS,{version:u.datasetVersion})}):o.jsx(gn.Cell,{className:"justify-center flex items-center",children:o.jsx(ase,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!u&&!l?o.jsx(VS,{variant:"added",version:d.datasetVersion}):f==="changed"&&!l?o.jsx(VS,{variant:"changed",version:d.datasetVersion}):o.jsx(VS,{version:d.datasetVersion})}):o.jsx(gn.Cell,{className:"justify-center flex items-center",children:o.jsx(ase,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",children:o.jsx(VS,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?ids=${u?.datasetVersion},${d?.datasetVersion}`,children:"Compare"}):o.jsx(gn.Cell,{children:o.jsx(ase,{tooltip:o.jsxs(o.Fragment,{children:["Comparing is available",o.jsx("br",{})," only for changed items"]})})})]},c)})})})})}const DQe={needsReview:"#facc15",complete:"#22c55e"},iss=[{label:"Needs Review",color:DQe.needsReview},{label:"Reviewed",color:DQe.complete}];function oss({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=v.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,p=0;const h=[];for(const m of e.counts){const g=m.needsReview+m.complete;if(g===0)continue;p+=g,g>f&&(f=g);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,w=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);h.push({name:w,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(mT,{data:a,segments:iss,maxVal:i,fmt:u=>String(u)}):o.jsx(Bt.NoData,{message:"No items have been sent to review yet"})})]})}function kTe(){const e=We();return wt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function a9t(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 lss(e,t){const n=new Map,r=a9t(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 css(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 uss=10;function dss(){const[e,t]=v.useState(!1),[n,r]=v.useState(""),[s,a]=v.useState("all"),[i,l]=v.useState("all"),[c,u]=v.useState("all"),[d,f]=v.useState(0),{data:p,isLoading:h,error:m}=Rg({page:d,perPage:uss}),{data:g,isLoading:y,error:b}=VZ(),{data:w}=kTe(),S=v.useMemo(()=>p?.datasets??[],[p?.datasets]),k=p?.pagination?.hasMore??!1,_=v.useMemo(()=>g?.experiments??[],[g?.experiments]),C=v.useMemo(()=>Cns(S),[S]),E=v.useMemo(()=>lss(w,_),[w,_]),j=h||y,N=m||b,I=()=>t(!0),R=v.useCallback(()=>f(B=>B+1),[]),$=v.useCallback(()=>f(B=>Math.max(0,B-1)),[]),F=v.useCallback(B=>{r(B),f(0)},[]),D=v.useCallback(B=>{a(B),f(0)},[]),V=v.useCallback(B=>{l(B),f(0)},[]),W=v.useCallback(B=>{u(B),f(0)},[]);if(N&&gs(N))return o.jsx(lr,{children:o.jsx(Vs,{})});if(N&&ys(N))return o.jsx(lr,{children:o.jsx(Ds,{resource:"datasets"})});if(N)return o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load datasets",message:N.message})});if(S.length===0&&!j&&d===0)return o.jsxs(o.Fragment,{children:[o.jsx(lr,{children:o.jsx(Ins,{onCreateClick:I})}),o.jsx(Pve,{open:e,onOpenChange:t})]});const L=s!=="all"||i!=="all"||c!=="all"||n!=="",z=()=>{r(""),a("all"),l("all"),u("all"),f(0)};return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Rns,{search:n,onSearchChange:F,targetFilter:s,onTargetFilterChange:D,experimentFilter:i,onExperimentFilterChange:V,tagFilter:c,onTagFilterChange:W,tagOptions:C,onReset:z,hasActiveFilters:L,onCreateClick:I})}),o.jsx(Nns,{datasets:S,experiments:_,reviewByDataset:E,isLoading:j,search:n,targetFilter:s,experimentFilter:i,tagFilter:c,currentPage:d,hasMore:k,onNextPage:R,onPrevPage:$}),o.jsx(Pve,{open:e,onOpenChange:t})]})}function Q8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function fss(){const{datasetId:e}=dr(),t=bs(),[n,r]=ji(),{activeVersion:s}=bTe(n,r),[a,i]=v.useState(!1),[l,c]=v.useState(!1),[u,d]=v.useState(!1),[f,p]=v.useState(!1),[h,m]=v.useState(!1),{data:g,error:y,isLoading:b}=Ux(e),{data:w=[],isLoading:S}=C1(e,void 0,s),k=!S&&w.length===0;if(b)return null;if(y&&gs(y))return o.jsx(Q8,{children:o.jsx(Vs,{})});if(y&&ys(y))return o.jsx(Q8,{children:o.jsx(Ds,{resource:"datasets"})});if(y&&uOe(y)||!b&&!y&&!g)return o.jsx(Q8,{children:o.jsx(Lr,{iconSlot:o.jsx(ay,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(ue,{as:ci,to:"/datasets",children:[o.jsx(Ec,{}),"Back to Datasets"]})})});if(y)return o.jsx(Q8,{children:o.jsx(Fi,{title:"Failed to load dataset",message:y instanceof Error?y.message:"An unexpected error occurred. Please try again."})});const _=E=>{t(`/datasets/${e}/experiments/${E}`)},C=()=>{t("/datasets")};return o.jsxs(o.Fragment,{children:[o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{children:[o.jsxs(Lt.Column,{children:[g?.description&&o.jsx("p",{className:"text-ui-smd text-neutral3 mb-1",children:g.description}),o.jsxs(zt,{numOfCol:2,children:[o.jsx(zt.Key,{children:"Created at"}),o.jsx(zt.Value,{children:g?.createdAt?er(new Date(g.createdAt),"MMM d, yyyy"):""}),o.jsx(zt.Key,{children:"Latest version"}),o.jsxs(zt.Value,{children:["v",g?.version??""]})]})]}),o.jsx(Lt.Column,{children:o.jsxs($r,{children:[k?o.jsxs(Wn,{children:[o.jsx(zn,{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(ue,{variant:"primary",children:[o.jsx(Pp,{}),s!=null?`Run on v${s}`:"Run Experiment"]})})})}),o.jsx(Bn,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(ue,{variant:"primary",onClick:()=>i(!0),children:[o.jsx(Pp,{}),s!=null?`Run on v${s}`:"Run Experiment"]}),o.jsxs(ft,{children:[o.jsx(ft.Trigger,{asChild:!0,children:o.jsx(ue,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(l3,{})})}),o.jsxs(ft.Content,{align:"end",className:"w-48",children:[o.jsxs(ft.Item,{onSelect:()=>d(!0),children:[o.jsx(em,{})," Edit Dataset"]}),o.jsxs(ft.Item,{onSelect:()=>m(!0),children:[o.jsx(Rp,{})," Duplicate Dataset"]}),o.jsxs(ft.Item,{onSelect:()=>p(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(Jc,{})," Delete Dataset"]})]})]})]})})]})}),o.jsx(Lt.MainArea,{children:o.jsx(Crs,{datasetId:e,onAddItemClick:()=>c(!0)})})]}),o.jsx(Prs,{datasetId:e,version:s??void 0,requestContextSchema:g?.requestContextSchema,open:a,onOpenChange:i,onSuccess:_}),o.jsx(jrs,{datasetId:e,open:l,onOpenChange:c}),g&&o.jsx(Fns,{open:u,onOpenChange:d,dataset:{id:g.id,name:g.name,description:g?.description||"",targetType:g.targetType,inputSchema:g.inputSchema,groundTruthSchema:g.groundTruthSchema,requestContextSchema:g.requestContextSchema}}),g&&o.jsx(Mns,{open:h,onOpenChange:m,sourceDatasetId:g.id,sourceDatasetName:g.name,sourceDatasetDescription:g.description,sourceDatasetTargetType:g.targetType}),g&&o.jsx(Bns,{open:f,onOpenChange:p,datasetId:g.id,datasetName:g.name,onSuccess:C})]})}function i9t({experiment:e}){const{Link:t,paths:n}=yn(),{data:r}=km(),{data:s}=Uy(),{data:a}=eh(),i=()=>{switch(e.targetType){case"agent":return n.agentLink(e.targetId);case"workflow":return n.workflowLink(e.targetId);case"scorer":return n.scorerLink(e.targetId);default:return"#"}},l=()=>{const u=e.targetId;if(!u)return u;switch(e.targetType){case"agent":return r?.[u]?.name??u;case"workflow":return s?.[u]?.name??u;case"scorer":return a?.[u]?.scorer?.config?.name??u;default:return u}},c=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${n.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{children:[o.jsx(Lt.Column,{children:o.jsxs(zt,{numOfCol:2,children:[o.jsx(zt.Key,{children:"Created at"}),o.jsx(zt.Value,{children:er(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")}),e.completedAt&&o.jsxs(o.Fragment,{children:[o.jsx(zt.Key,{children:"Completed at"}),o.jsx(zt.Value,{children:er(new Date(e.completedAt),"MMM d, yyyy 'at' h:mm a")})]}),o.jsx(zt.Key,{children:"Target"}),o.jsx(zt.ValueLink,{href:i(),as:t,children:l()}),e.agentVersion&&o.jsxs(o.Fragment,{children:[o.jsx(zt.Key,{children:"Version"}),c?o.jsx(zt.ValueLink,{href:c,as:t,children:e.agentVersion}):o.jsx(zt.Value,{children:e.agentVersion})]})]})}),o.jsx(Lt.Column,{children:o.jsx(Wrs,{experiment:e})})]})})}function Y8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function pss(){const{datasetId:e,experimentId:t}=dr(),{data:n,isLoading:r,error:s}=CU(e,t),{data:a,isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u}=BZ({datasetId:e,experimentId:t,experimentStatus:n?.status});return!e||!t||r?null:s&&gs(s)?o.jsx(Y8,{children:o.jsx(Vs,{})}):s&&ys(s)?o.jsx(Y8,{children:o.jsx(Ds,{resource:"datasets"})}):s&&uOe(s)||!r&&!s&&!n?o.jsx(Y8,{children:o.jsx(Lr,{iconSlot:o.jsx(Bye,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${t}".`,actionSlot:o.jsxs(ue,{as:ci,to:`/datasets/${e}?tab=experiments`,children:[o.jsx(Ec,{}),"Back to Dataset"]})})}):s?o.jsx(Y8,{children:o.jsx(Fi,{title:"Failed to load experiment",message:s instanceof Error?s.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx(i9t,{experiment:n}),o.jsx(Lt.MainArea,{children:o.jsx(s9t,{experimentId:t,datasetId:e,experimentStatus:n.status,results:a??[],isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u})})]})}function hss(){const{datasetId:e}=dr(),[t,n]=ji(),{error:r}=Ux(e??""),s=t.get("baseline")??"",a=t.get("contender")??"";return r&&gs(r)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):r&&ys(r)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||!s||!a?o.jsx(cs,{children:o.jsx(dy,{children:o.jsxs("div",{className:"text-neutral4 text-center py-8",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"text-sm mt-2",children:["Use the URL format: /datasets/","{datasetId}","/experiments?baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):o.jsx(cs,{children:o.jsx(dy,{children:o.jsxs("div",{className:"max-w-[100rem] w-full px-12 mx-auto grid content-start ",children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Qw,{})," Dataset Experiments Comparison"]}),o.jsxs(ua.Description,{children:["Comparing"," ",o.jsx(ci,{to:`/datasets/${e}/experiments/${s}`,children:s.slice(0,8)})," vs"," ",o.jsx(ci,{to:`/datasets/${e}/experiments/${a}`,children:a.slice(0,8)})]})]}),o.jsx(ua.Column,{children:o.jsxs(ue,{as:ci,to:`/datasets/${e}`,children:[o.jsx(Ec,{}),"Back to Dataset"]})})]}),o.jsx(Xrs,{datasetId:e,experimentIdA:s,experimentIdB:a,onSwap:()=>{n({baseline:a,contender:s})}})]})})})}function mss(){const{datasetId:e,itemId:t}=dr(),{Link:n}=yn(),r=bs(),{data:s,isLoading:a,error:i}=yTe(e??"",t??""),{updateItem:l,deleteItem:c}=_i(),{data:u}=Ux(e??""),d=s?.[0]??null,f=d?.isDeleted??!1,[p,h]=v.useState(null),m=v.useMemo(()=>!d||f?{input:"",groundTruth:"",metadata:"",trajectory:"",toolMocks:"",requestContext:""}:{input:JSON.stringify(d.input,null,2),groundTruth:d.groundTruth?JSON.stringify(d.groundTruth,null,2):"",metadata:d.metadata?JSON.stringify(d.metadata,null,2):"",trajectory:d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):"",toolMocks:d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):"",requestContext:d.requestContext?JSON.stringify(d.requestContext,null,2):""},[d,f]),g=d?.datasetVersion??0,[y,b]=v.useState(!1),[w,S]=v.useState(m.input),[k,_]=v.useState(m.groundTruth),[C,E]=v.useState(m.metadata),[j,N]=v.useState(m.trajectory),[I,R]=v.useState(m.toolMocks),[$,F]=v.useState(m.requestContext),[D,V]=v.useState(g);g!==D&&(V(g),S(m.input),_(m.groundTruth),E(m.metadata),N(m.trajectory),R(m.toolMocks),F(m.requestContext));const[W,L]=v.useState(!1),z=J=>{h(f?J:J.isLatest?null:J)},B=()=>{h(null)},M=!f&&p!=null,G=()=>{M||b(!0)},U=()=>{M||L(!0)},P=async()=>{if(!e||!t)return;let J;try{J=JSON.parse(w)}catch{De.error("Input must be valid JSON");return}let ee;if(k.trim())try{ee=JSON.parse(k)}catch{De.error("Ground Truth must be valid JSON");return}let ae;if(C.trim())try{ae=JSON.parse(C)}catch{De.error("Metadata must be valid JSON");return}let de;const Y=j!==m.trajectory;if(Y&&j.trim())try{de=JSON.parse(j)}catch{De.error("Expected Trajectory must be valid JSON");return}let ne;const ce=I!==m.toolMocks;if(ce&&I.trim())try{const ve=JSON.parse(I);if(!Array.isArray(ve)){De.error("Tool Mocks must be a JSON array");return}ne=ve}catch{De.error("Tool Mocks must be valid JSON");return}let pe;const le=$!==m.requestContext;if(le&&$.trim())try{pe=JSON.parse($)}catch{De.error("Request Context must be valid JSON");return}try{await l.mutateAsync({datasetId:e,itemId:t,input:J,groundTruth:ee,metadata:ae,...Y?{expectedTrajectory:de??null}:{},...ce?{toolMocks:ne??[]}:{},...le?{requestContext:pe}:{}}),De.success("Item updated successfully"),b(!1)}catch(ve){De.error(`Failed to update item: ${ve instanceof Error?ve.message:"Unknown error"}`)}},q=()=>{d&&(S(JSON.stringify(d.input,null,2)),_(d.groundTruth?JSON.stringify(d.groundTruth,null,2):""),E(d.metadata?JSON.stringify(d.metadata,null,2):""),N(d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):""),R(d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):""),F(d.requestContext?JSON.stringify(d.requestContext,null,2):"")),b(!1)},Z=async()=>{if(!(!e||!t))try{await c.mutateAsync({datasetId:e,itemId:t}),De.success("Item deleted successfully"),L(!1),r(`/datasets/${e}`)}catch(J){De.error(`Failed to delete item: ${J instanceof Error?J.message:"Unknown error"}`)}},X=p??d,te=X?{id:t??"",datasetId:e??"",datasetVersion:X.datasetVersion,input:X.input,groundTruth:X.groundTruth,expectedTrajectory:X.expectedTrajectory,metadata:X.metadata,createdAt:X.createdAt,updatedAt:X.updatedAt}:null;return i&&gs(i)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):i&&ys(i)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):a?null:!e||!t||!s||s.length===0?o.jsx(cs,{children:o.jsx(dy,{children:o.jsx("div",{className:"text-neutral3 p-4",children:"Item not found"})})}):o.jsxs(o.Fragment,{children:[o.jsx(cs,{children:o.jsx("div",{className:"h-full overflow-hidden px-6 pb-4",children:o.jsxs("div",{className:"grid gap-6 max-w-[60rem] mx-auto grid-rows-[auto_1fr] h-full",children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(dN,{}),t," ",o.jsx(ya,{content:t})]}),o.jsx(ua.Description,{children:o.jsxs(jl,{children:["Item of ",o.jsx(ay,{})," ",u?.name]})}),o.jsxs(ua.Description,{children:[o.jsxs(jl,{children:[o.jsx(llt,{})," Created at"," ",d?.createdAt?er(new Date(d.createdAt),"MMM d, yyyy"):""]}),o.jsxs(jl,{children:[o.jsx(i_,{})," Latest version v",d?.datasetVersion??""]})]})]}),o.jsx(ua.Column,{children:!y&&!f&&o.jsxs($r,{children:[o.jsxs(ue,{onClick:G,disabled:M,title:M?"Return to latest version to edit":void 0,children:[o.jsx(jlt,{})," Edit"]}),o.jsxs(ue,{onClick:U,disabled:M,title:M?"Return to latest version to delete":void 0,children:[o.jsx(Jc,{})," Delete"]})]})})]}),o.jsxs(Yv,{className:y?"grid-cols-1":"grid-cols-[1fr_auto]",children:[o.jsxs(Gr,{withRightSeparator:!y,children:[f&&d&&o.jsx(In,{variant:"destructive",title:"Item deleted",children:o.jsxs(In.Message,{children:["This item was deleted at version v",d.datasetVersion]})}),!f&&M&&p&&o.jsx(In,{variant:"warning",title:"Previous version",action:o.jsxs(In.Button,{onClick:B,children:[o.jsx(rlt,{})," Return to the latest version"]}),children:o.jsxs(In.Message,{children:["Viewing version v",p.datasetVersion]})}),y?o.jsx(n9t,{inputValue:w,setInputValue:S,groundTruthValue:k,setGroundTruthValue:_,metadataValue:C,setMetadataValue:E,trajectoryValue:j,setTrajectoryValue:N,toolMocksValue:I,setToolMocksValue:R,requestContextValue:$,setRequestContextValue:F,validationErrors:null,onSave:P,onCancel:q,isSaving:l.isPending}):te?o.jsx(wTe,{item:te,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})]}),!y&&o.jsx(Gr,{children:o.jsx(Krs,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:z,onCompareVersionsClick:J=>{r(`/datasets/${e}/items/${t}/versions?ids=${J.join(",")}`)},activeVersion:p?.datasetVersion??null})})]})]})})}),o.jsx(Tt,{open:W,onOpenChange:L,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Item"}),o.jsx(Tt.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(Tt.Footer,{children:[o.jsx(Tt.Cancel,{children:"Cancel"}),o.jsx(Tt.Action,{onClick:Z,children:c.isPending?"Deleting...":"Delete"})]})]})})]})}function LQe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function gss(){const{datasetId:e}=dr(),[t,n]=ji(),r=t.get("items")?.split(",").filter(Boolean)??[],{data:s,error:a}=Ux(e??""),{Link:i}=yn(),[l,c]=v.useState(!1),{data:u}=EU(e??"",r[0]??""),{data:d}=EU(e??"",r[1]??"");return a&&gs(a)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):a&&ys(a)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||r.length<2?o.jsx(cs,{children:o.jsx(dy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two items to compare."})})})}):o.jsxs(cs,{children:[o.jsx(Ty,{owner:"dataset-items-compare",children:o.jsxs(ue,{as:ci,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(Ec,{}),"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]":l}),children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Qw,{}),"Compare Dataset Items"]}),o.jsx(ua.Description,{children:o.jsxs(jl,{children:["Comparing ",r.length," items of"," ",o.jsx(ci,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:s?.name||e?.slice(0,8)})]})})]}),o.jsx(ua.Column,{children:o.jsx($r,{children:o.jsx(ue,{variant:"primary",onClick:()=>c(f=>!f),children:l?o.jsxs(o.Fragment,{children:[o.jsx(mlt,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(lcn,{})," Diff View"]})})})})]}),o.jsx(Yv,{className:"grid-cols-[1fr_3vw_1fr]",children:r.map((f,p)=>o.jsxs(v.Fragment,{children:[o.jsx(vss,{datasetId:e,itemId:f,Link:i,idx:p,itemIds:r,showContent:!l,onItemChange:h=>{const m=[...r];m[p]=h,n({items:m.join(",")})}}),p==0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},f))}),l&&u&&d&&o.jsx(X1e,{codeA:LQe(u),codeB:LQe(d)})]})})]})}function vss({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=EU(e,t),{data:u}=C1(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(Gr,{children:[o.jsxs(Gr.Toolbar,{className:"flex gap-4",children:[o.jsxs(ba,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(wa,{"aria-label":"Item",children:o.jsx(xa,{placeholder:"Select item"})}),o.jsx(Sa,{children:f.map(p=>o.jsx(qr,{value:p.value,disabled:p.disabled,children:p.label},p.value))})]}),o.jsxs(ue,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(i_,{}),"Versions"]})]}),i&&o.jsx(Gr.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(Trs,{item:l}),o.jsx(wTe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function FQe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function yss(){const{datasetId:e,itemId:t}=dr(),[n,r]=ji(),[s,a]=v.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(h=>!isNaN(h)&&h>0)??[],{data:l,error:c}=Ux(e??""),{Link:u}=yn(),{data:d}=yTe(e??"",t??""),{data:f}=Mve(e??"",t??"",i[0]??0,l?.version),{data:p}=Mve(e??"",t??"",i[1]??0,l?.version);return c&&gs(c)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):c&&ys(c)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||!t||i.length<2?o.jsx(cs,{children:o.jsx(dy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two versions to compare."})})})}):o.jsxs(cs,{children:[o.jsx(Ty,{owner:"dataset-item-versions-compare",children:o.jsxs(ue,{as:ci,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(Ec,{}),"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(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Qw,{}),"Compare Dataset Item Versions"]}),o.jsx(ua.Description,{children:o.jsxs(jl,{children:["Comparing ",i.length," versions of"," ",o.jsx(ci,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(ua.Column,{children:o.jsx($r,{children:o.jsx(ue,{variant:"primary",onClick:()=>a(h=>!h),children:s?o.jsxs(o.Fragment,{children:[o.jsx(mlt,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(Zcn,{})," Diff View"]})})})})]}),o.jsx(Yv,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((h,m)=>o.jsxs(v.Fragment,{children:[o.jsx(bss,{datasetId:e,itemId:t,datasetVersion:h,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:g=>{const y=[...i];y[m]=g,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),s&&f&&p&&o.jsx(X1e,{codeA:FQe(f),codeB:FQe(p)})]})})]})}function bss({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}=Mve(e,t,n,r),p=new Set(a.filter((g,y)=>y!==l)),h=s.map(g=>{const y=typeof g.updatedAt=="string"?new Date(g.updatedAt):g.updatedAt;return{value:String(g.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",g.datasetVersion]})," - ",er(y,"MMM d, yyyy h:mm a"),g.isLatest?o.jsx(Xs,{color:"blue",size:"small",children:"Latest"}):null]}),disabled:p.has(g.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(Gr,{children:[o.jsxs(Gr.Toolbar,{className:"grid gap-4 grid-cols-[auto_1fr]",children:[o.jsx(i_,{className:"w-6 h-6 opacity-50"}),o.jsxs(ba,{name:`compare-version-${l}`,value:String(n),onValueChange:g=>u(Number(g)),children:[o.jsx(wa,{"aria-label":"Version",className:"w-full",children:o.jsx(xa,{placeholder:"Select version"})}),o.jsx(Sa,{children:h.map(g=>o.jsx(qr,{value:g.value,disabled:g.disabled,children:g.label},g.value))})]})]}),c&&o.jsx(Gr.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(wTe,{item:m,Link:i})})]})}function xss(){const{datasetId:e}=dr(),[t]=ji(),n=t.get("ids")?.split(",").map(Number).filter(g=>!isNaN(g)&&g>0)??[],r=bs(),{data:s,error:a}=Ux(e??""),i=C1(e??"",void 0,n[0]??null),l=C1(e??"",void 0,n[1]??null),c=v.useMemo(()=>i.data??[],[i.data]),u=v.useMemo(()=>l.data??[],[l.data]),d=v.useMemo(()=>{const g=new Map;for(const y of[...c,...u])g.has(y.id)||g.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...g.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=v.useMemo(()=>new Map(c.map(g=>[g.id,g])),[c]),p=v.useMemo(()=>new Map(u.map(g=>[g.id,g])),[u]);if(a&&gs(a))return o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})});if(a&&ys(a))return o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(cs,{children:o.jsx(dy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const h=(g,y,b)=>{r(`/datasets/${e}/items/${g}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(g,y)=>{r(`/datasets/${e}/versions?ids=${g},${y}`,{replace:!0})};return o.jsx(cs,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Tdn,{})," Compare Dataset Versions"]}),o.jsx(ua.Description,{children:o.jsxs(jl,{children:[o.jsx(i_,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(ua.Column,{children:o.jsxs(ue,{as:ci,to:`/datasets/${e}`,children:[o.jsx(Ec,{}),"Back to Dataset"]})})]}),o.jsx(Yv,{children:o.jsxs(Gr,{children:[o.jsx(tss,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(ass,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p,onItemClick:h})]})})]})})})}function wss(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 Sss({scorers:e,datasets:t,experiments:n,avgScore:r,prevAvgScore:s,totalNeedsReview:a,isLoadingScorers:i,isLoadingDatasets:l,isLoadingExperiments:c,isLoadingScores:u,isLoadingReview:d}){const f=e?Object.keys(e).length:void 0,p=t?.length,h=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,g=wss(n);return o.jsxs(o.Fragment,{children:[o.jsxs(Kr,{children:[o.jsx(Kr.Label,{children:"Total Scorers"}),i?o.jsx(Kr.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(Kr.Value,{children:String(f)}),o.jsx(Kr.NoChange,{message:"Static count"})]}):o.jsx(Kr.NoData,{})]}),o.jsxs(Kr,{children:[o.jsx(Kr.Label,{children:"Total Datasets"}),l?o.jsx(Kr.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Kr.Value,{children:String(p)}),o.jsx(Kr.NoChange,{message:"Static count"})]}):o.jsx(Kr.NoData,{})]}),o.jsxs(Kr,{children:[o.jsx(Kr.Label,{children:"Avg Score"}),u?o.jsx(Kr.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(Kr.Value,{children:String(r)}),m?o.jsx(Kr.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(Kr.NoChange,{})]}):o.jsx(Kr.NoData,{})]}),o.jsxs(Kr,{children:[o.jsx(Kr.Label,{children:"Total Experiments"}),c?o.jsx(Kr.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Kr.Value,{children:String(h)}),g?o.jsx(Kr.Change,{changePct:g.changePct,prevValue:g.prevValue}):o.jsx(Kr.NoChange,{})]}):o.jsx(Kr.NoData,{})]}),o.jsxs(Kr,{children:[o.jsx(Kr.Label,{children:"Needs Review"}),d?o.jsx(Kr.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(Kr.Value,{children:String(a)}),a>0?o.jsx(Kr.NoChange,{message:"items pending review"}):o.jsx(Kr.NoChange,{message:"All caught up"})]}):o.jsx(Kr.NoData,{})]})]})}const zQe="auto 1fr auto auto auto auto auto auto auto";function kss(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}const Oss={completed:"success",running:"warning",failed:"error",pending:"neutral"};function _ss({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all"}){const{paths:l,Link:c}=yn(),u=v.useMemo(()=>{const p=new Map;return t?.forEach(h=>p.set(h.id,h.name)),p},[t]),d=v.useMemo(()=>[...e].sort((p,h)=>{const m=p.createdAt?new Date(p.createdAt).getTime():0;return(h.createdAt?new Date(h.createdAt).getTime():0)-m}),[e]),f=v.useMemo(()=>{const p=s.toLowerCase();return d.filter(h=>{const m=h.datasetId?u.get(h.datasetId)??"":"",g=!p||h.id.toLowerCase().includes(p)||m.toLowerCase().includes(p)||(h.targetId??"").toLowerCase().includes(p),y=a==="all"||h.status===a,b=i==="all"||h.datasetId===i;return g&&y&&b})},[d,s,u,a,i]);return r?o.jsx(el,{columns:zQe}):o.jsxs(me,{columns:zQe,variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Experiment"}),o.jsx(me.TopCell,{children:"Dataset"}),o.jsx(me.TopCell,{children:"Target"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{className:"text-center",children:"Items"}),o.jsx(me.TopCell,{className:"text-center",children:"Succeeded"}),o.jsx(me.TopCell,{className:"text-center",children:"Failed"}),o.jsx(me.TopCell,{className:"text-center",children:"Review"}),o.jsx(me.TopCell,{children:"Date"})]}),f.map(p=>{const h=p.datasetId?u.get(p.datasetId)??p.datasetId.slice(0,8):"—",m=p.status??"pending",g=p.succeededCount??0,y=p.failedCount??0,b=p.totalItems??0,w=b>0?Math.round(g/b*100):0;return o.jsxs(me.RowLink,{to:l.experimentLink(p.id),LinkComponent:c,children:[o.jsx(me.NameCell,{className:"font-mono",children:p.id.slice(0,8)}),o.jsx(me.TextCell,{children:h}),o.jsx(me.Cell,{children:o.jsxs("span",{className:"truncate",children:[p.targetType," ",p.targetId]})}),o.jsx(me.Cell,{children:o.jsx(ug,{variant:Oss[m]??"neutral",withDot:!0,children:m})}),o.jsx(me.TextCell,{className:"text-center",children:b}),o.jsx(me.TextCell,{className:"text-center",children:o.jsxs("span",{className:g>0?"text-accent1":"",children:[g," (",w,"%)"]})}),o.jsx(me.TextCell,{className:"text-center",children:o.jsx("span",{className:y>0?"text-accent2":"",children:y})}),o.jsx(me.Cell,{className:"text-center",children:(()=>{const S=n?.get(p.id);if(!S)return o.jsx("span",{className:"text-neutral2",children:"—"});const k=S.needsReview+S.complete;return k===0?o.jsx("span",{className:"text-neutral2",children:"—"}):S.needsReview>0?o.jsxs(Xs,{size:"small",color:"yellow",children:[S.needsReview," pending"]}):o.jsxs(Xs,{size:"small",color:"green",children:[S.complete,"/",k," reviewed"]})})()}),o.jsx(me.TextCell,{children:kss(p.createdAt)})]},p.id)})]})}const Css=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function Ess(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const X8={completed:"#22c55e",running:"#facc15",pending:"#fb923c",failed:"#f87171"},jss=[{label:"Completed",color:X8.completed},{label:"Running",color:X8.running},{label:"Pending",color:X8.pending},{label:"Failed",color:X8.failed}];function Tss({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=v.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const p=f.datasetId??"unknown";c.has(p)||c.set(p,{completed:0,running:0,pending:0,failed:0});const h=c.get(p),m=f.status;m in h&&h[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,p])=>{const h=p.completed+p.running+p.pending+p.failed;return h>u&&(u=h),{name:l.get(f)??f.slice(0,12),values:[p.completed,p.running,p.pending,p.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(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(mT,{data:s,segments:jss,maxVal:a,fmt:l=>String(l)}):o.jsx(Bt.NoData,{message:"No experiments have been run yet"})})]})}const Nss=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(xf,{}),titleSlot:"No Experiments yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Run an experiment from a dataset to evaluate ",o.jsx("br",{}),"your agents and workflows."]}),actionSlot:o.jsx("div",{className:"flex flex-col items-center gap-2",children:o.jsxs(ue,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/evals/datasets/running-experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(Pa,{})]})})})});function Iss({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c}){return o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(jf,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t}),o.jsxs($r,{children:[o.jsx(bc,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...Css],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(bc,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(ue,{onClick:l,size:"sm",variant:"default",children:[o.jsx(vs,{className:"size-3"})," Reset"]})]})]})}function Ass(){const{data:e,isLoading:t,error:n}=eh(),{data:r,isLoading:s,error:a}=Rg(),{data:i,isLoading:l,error:c}=VZ(),{data:u,isLoading:d,isError:f,error:p}=QXr(),{data:h,isLoading:m,isError:g,error:y}=kTe(),b=r?.datasets,w=i?.experiments,S=v.useMemo(()=>css(h),[h]),k=n||a||c||p||y;return k&&gs(k)?o.jsx(lr,{children:o.jsx(Vs,{})}):k&&ys(k)?o.jsx(lr,{children:o.jsx(Ds,{resource:"evaluation"})}):k?o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load evaluation data",message:k.message})}):o.jsx(Lt,{width:"wide",height:"full",children:o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsx(Wpe,{children:o.jsx(Sss,{scorers:e,datasets:b,experiments:w,avgScore:u?.avgScore??null,prevAvgScore:u?.prevAvgScore??null,totalNeedsReview:S.needsReview,isLoadingScorers:t,isLoadingDatasets:s,isLoadingExperiments:l,isLoadingScores:d,isLoadingReview:m})}),o.jsx(FXr,{summaryData:u?.summaryData??[],overTimeData:u?.overTimeData??[],scorerNames:u?.scorerNames??[],avgScore:u?.avgScore??null,isLoading:d,isError:f}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(Ans,{experiments:w,isLoading:l,isError:!!c}),o.jsx(Tss,{experiments:w,datasets:b,isLoading:l,isError:!!c})]}),o.jsx(oss,{reviewSummary:h,experiments:w,datasets:b,isLoading:m,isError:!!g})]})})}function Rss(){const[e,t]=v.useState(""),[n,r]=v.useState("all"),[s,a]=v.useState("all"),{data:i,isLoading:l,error:c}=Rg(),{data:u,isLoading:d,error:f}=VZ(),{data:p}=kTe(),h=v.useMemo(()=>i?.datasets??[],[i?.datasets]),m=v.useMemo(()=>u?.experiments??[],[u?.experiments]),g=v.useMemo(()=>Ess(h),[h]),y=v.useMemo(()=>a9t(p),[p]),b=l||d,w=f||c;if(w&&gs(w))return o.jsx(lr,{children:o.jsx(Vs,{})});if(f&&ys(f))return o.jsx(lr,{children:o.jsx(Ds,{resource:"experiments"})});if(c&&ys(c))return o.jsx(lr,{children:o.jsx(Ds,{resource:"datasets"})});if(w)return o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load experiments",message:w.message})});if(m.length===0&&!b)return o.jsx(lr,{children:o.jsx(Nss,{})});const S=n!=="all"||s!=="all"||e!=="",k=()=>{t(""),r("all"),a("all")};return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Iss,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:g,onReset:k,hasActiveFilters:S})}),o.jsx(_ss,{experiments:m,datasets:h,reviewByExperiment:y,isLoading:b,search:e,statusFilter:n,datasetFilter:s})]})}function K8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function Pss(){const{experimentId:e}=dr(),{data:t,isLoading:n}=VZ(),s=t?.experiments?.find(h=>h.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=CU(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p}=BZ({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&gs(l)?o.jsx(K8,{children:o.jsx(Vs,{})}):l&&ys(l)?o.jsx(K8,{children:o.jsx(Ds,{resource:"datasets"})}):l&&uOe(l)||!n&&!s||!i&&!l&&!a?o.jsx(K8,{children:o.jsx(Lr,{iconSlot:o.jsx(Bye,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(ue,{as:ci,to:"/experiments",children:[o.jsx(Ec,{}),"Back to Experiments"]})})}):l?o.jsx(K8,{children:o.jsx(Fi,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx(i9t,{experiment:a}),o.jsx(Lt.MainArea,{children:o.jsx(s9t,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p})})]})}function $ss({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 o9t({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx($ss,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function Mss({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(o9t,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function Dss({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(Mss,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(o9t,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function Lss({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:a,providersError:i,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:p,onToolkitChange:h,onLabelChange:m,onConnect:g}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>p(y.target.value),disabled:a,children:[o.jsx("option",{value:"",children:"— select provider —"}),e.map(y=>o.jsxs("option",{value:y.id,children:[y.displayName??y.name," (",y.id,")"]},y.id))]}),a&&o.jsx("span",{className:"text-gray-500",children:"Loading providers…"}),i?o.jsx("span",{className:"text-red-600",children:String(i)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"toolkit-select",children:"Toolkit"}),o.jsxs("select",{id:"toolkit-select",className:"border rounded px-2 py-1 w-full",value:r,onChange:y=>h(y.target.value),disabled:!n||l,children:[o.jsx("option",{value:"",children:"— select toolkit —"}),t.map(y=>o.jsxs("option",{value:y.slug,children:[y.name," (",y.slug,")"]},y.slug))]}),l&&o.jsx("span",{className:"text-gray-500",children:"Loading toolkits…"}),c?o.jsx("span",{className:"text-red-600",children:String(c)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"label-input",children:"Label (optional)"}),o.jsx("input",{id:"label-input",type:"text",className:"border rounded px-2 py-1 w-full",placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value),disabled:!n||!r})]}),o.jsx("button",{type:"button",className:"bg-blue-600 text-white rounded px-4 py-2 disabled:opacity-50",onClick:g,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const BQe=e=>e.authorId?.trim()||"shared",Fss=(e,t)=>{if(!t||new Set(e.map(BQe)).size<=1)return null;const r=new Map;for(const a of e){const i=BQe(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},zss=["*","tool-providers:*","tool-providers:admin"];function Bss(){const{data:e}=Sm();return e?.permissions?.some(t=>zss.includes(t))??!1}function Uss(){const[e,t]=v.useState(""),[n,r]=v.useState(""),[s,a]=v.useState(""),i=gI(),l=CW(e||null),c=PPt(e||null,n||null),u=RPt(),d=IPt(),f=Bss(),p=i.data?.providers??[],h=l.data?.data??[],m=v.useMemo(()=>c.data?.items??[],[c.data?.items]),g=v.useMemo(()=>Fss(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()}})},w=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(Lss,{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(Dss,{providerId:e,toolkit:n,connections:m,groupedByAuthor:g,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:w})]})}function qss({title:e,description:t,errorBanner:n,children:r}){return o.jsx("div",{"data-testid":"login-page",className:"flex min-h-screen items-center justify-center bg-surface1",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(Vh,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-xl font-semibold text-neutral6",children:e})]}),t,n,r]})})}function l9t({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=rc(),{mutate:i,isPending:l,error:c}=qDr(),{mutate:u,isPending:d,error:f}=HDr(),{mutate:p,isPending:h}=J2t(),[m,g]=v.useState(n),[y,b]=v.useState(""),[w,S]=v.useState(""),[k,_]=v.useState("");if(a)return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-surface1",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-surface1",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:C}=s,E=C.type==="sso"||C.type==="both",j=C.type==="credentials"||C.type==="both",N=C.sso,I=C.signUpEnabled!==!1,R=m==="signin"||!I,$=R?l:d,F=R?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href="/"},V=M=>{M.preventDefault(),R?i({email:w,password:k},{onSuccess:D}):u({email:w,password:k,name:y||void 0},{onSuccess:D})},W=()=>{p({redirectUri:e},{onSuccess:M=>{window.location.href=M.url}})},L=()=>{g(R?"signup":"signin")},z=C.description?o.jsxs("div",{className:"flex items-start gap-2.5 rounded-md border border-border1 bg-surface1 p-3",children:[o.jsx(pf,{className:"mt-0.5 h-4 w-4 shrink-0 text-neutral4"}),o.jsx("p",{className:"text-sm text-neutral3",children:C.description})]}):null,B=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(qss,{title:R?"Sign in to Mastra Studio":"Create your account",description:z,errorBanner:B,children:[j&&o.jsxs("form",{onSubmit:V,className:"space-y-4",children:[!R&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"block text-sm text-neutral4",children:"Name"}),o.jsx(kn,{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:"block text-sm text-neutral4",children:"Email"}),o.jsx(kn,{id:"email",type:"email",value:w,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:"block text-sm text-neutral4",children:"Password"}),o.jsx(kn,{id:"password",type:"password",value:k,onChange:M=>_(M.target.value),placeholder:R?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),F&&o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:F.message}),o.jsx(ue,{type:"submit",disabled:$,className:"w-full",size:"lg",children:$?R?"Signing in...":"Creating account...":R?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-center text-sm",children:[o.jsx("span",{className:"text-neutral3",children:R?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:L,className:"text-neutral6 hover:underline",children:R?"Sign up":"Sign in"})]})]}),E&&j&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"w-full border-t border-border1"})}),o.jsx("div",{className:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 px-2 text-neutral3",children:"or continue with"})})]}),E&&N&&o.jsxs(ue,{onClick:W,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 Vss(){const[e]=ji(),t=bs(),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(l9t,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}function Hss(){const[e,t]=ji(),n=KSr(e,t),r=tkr(e,t),[s,a]=v.useState(),[i,l]=v.useState(!1),{data:c=[],isPending:u}=NOe(),{data:d=[],isPending:f}=IOe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=AOe(),{data:m=[],isPending:g}=ROe(),y=v.useMemo(()=>w1r({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:g,environments:h}}),[c,d,m,p,u,f,g,h]),b=v.useMemo(()=>_1r({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:w=[],isLoading:S,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E}=YSr({filters:b}),{logIdMap:j,featuredLog:N,handleLogClick:I,handlePreviousLog:R,handleNextLog:$}=skr(w,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:F,isLoading:D}=XH(n.featuredTraceId??null),{data:V,isLoading:W}=pI(n.featuredTraceId??"",n.featuredSpanId??""),L=v.useCallback(()=>n.applyFilterTokens(C1r(y,n.filterTokens)),[y,n]),z=v.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),B=v.useCallback(X=>n.handleFeaturedChange({traceId:X,spanId:null}),[n]),M=v.useCallback((X,te)=>n.handleFeaturedChange({traceId:X,spanId:te}),[n]),G=v.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),U=v.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),P=v.useCallback(X=>n.handleFeaturedChange({spanId:X??null}),[n]),q=o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(wSe,{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(Wwe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx(zSr,{isLoading:S,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:L,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Lt,{width:"wide",height:"full",children:[q,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx($Sr,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return w.length===0&&!S&&!Z?o.jsxs(Lt,{width:"wide",height:"full",children:[q,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(VSr,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Lt,{width:"wide",height:"full",children:[q,o.jsx(MSr,{logCollapsed:i,listSlot:o.jsx(FSr,{logs:w,isLoading:S,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E,logIdMap:j,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(PSr,{log:N,onClose:z,onTraceClick:B,onSpanClick:M,onPrevious:R,onNext:$,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(ATt,{traceId:n.featuredTraceId,spans:F?.spans,isLoading:D,onClose:G,onSpanSelect:P,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(oSr,{spanId:n.featuredSpanId,span:V?.span,isLoading:W,onClose:U}):null})]})}function Wss({server:e}){const{paths:t,Link:n}=yn(),s=We().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=G6t(e),l=Object.values(i||{}),c=l.length,u=l.filter(p=>p.toolType==="agent").length,d=l.filter(p=>p.toolType==="workflow").length,f=om(e.name,50);return o.jsxs(me.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(me.NameCell,{children:f}),o.jsx(me.DescriptionCell,{children:a}),o.jsx(me.TextCell,{className:"text-center",children:u||""}),o.jsx(me.TextCell,{className:"text-center",children:c||""}),o.jsx(me.TextCell,{className:"text-center",children:d||""})]})}function Zss({mcpServers:e,isLoading:t,search:n=""}){const r=v.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(el,{columns:"auto 1fr auto auto auto"}):o.jsxs(me,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Name"}),o.jsx(me.TopCell,{children:"URL"}),o.jsx(me.TopCellSmart,{long:"Agents",short:o.jsx(rl,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(me.TopCellSmart,{long:"Tools",short:o.jsx(Gp,{}),tooltip:"Tools",className:"text-center"}),o.jsx(me.TopCellSmart,{long:"Workflows",short:o.jsx(_d,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(me.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(Wss,{server:s},s.id))]})}const Gss=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(xf,{}),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(ue,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Pa,{})]})})}),Qss=()=>{const{data:e=[],isLoading:t,error:n}=PZ(),[r,s]=v.useState("");return n&&gs(n)?o.jsx(lr,{children:o.jsx(Vs,{})}):n&&ys(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"MCP servers"})}):n?o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(lr,{children:o.jsx(Gss,{})}):o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(jf,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(Zss,{mcpServers:e,isLoading:t,search:r})]})},Yss=(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 Xss({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=yn(),i=v.useMemo(()=>Yss(e,t),[e,t]),l=v.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(el,{columns:"auto 1fr auto"}):o.jsxs(me,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Name"}),o.jsx(me.TopCell,{children:"Description"}),o.jsx(me.TopCellSmart,{long:"Agents",short:o.jsx(rl,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(me.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=om(c.id,50),d=om(c.description??"",200),f=c.agents.length;return o.jsxs(me.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(me.NameCell,{children:u}),o.jsx(me.DescriptionCell,{children:d}),o.jsx(me.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const Kss=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(xf,{}),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(ue,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Pa,{})]})})}),Jss=()=>{const e=We();return Rn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new r_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw De.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},eas=({toolId:e})=>{const{canExecute:t}=al(),n=t("tools"),{data:r={}}=km(),s=v.useMemo(()=>{for(const g of Object.values(r))if(g.tools){const y=Object.values(g.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=rDr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=Jss(),{requestContext:p}=_s();v.useEffect(()=>{if(l){const g=l instanceof Error?l.message:"Failed to load tool";De.error(`Error loading tool: ${g}`)}},[l]);const h=async(g,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:g,requestContext:b})},m=c?.inputSchema?um(lm(jx(c?.inputSchema))):Ss({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(At,{className:"h-8 w-48 mb-4"}),o.jsx(At,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(iTe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function tas({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}=mI(),{data:p={},isLoading:h,isError:m,error:g}=km(),{navigate:y,paths:b}=yn();v.useEffect(()=>{if(d){const _=f instanceof Error?f.message:"Failed to load tools";De.error(`Error loading tools: ${_}`)}},[d,f]),v.useEffect(()=>{if(m){const _=g instanceof Error?g.message:"Failed to load agents";De.error(`Error loading agents: ${_}`)}},[m,g]);const w=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(C=>{w.has(C.id)||w.set(C.id,C)})}),Object.values(c).forEach(_=>{w.has(_.id)||w.set(_.id,_)});const S=Array.from(w.values()).map(_=>({label:_.id,value:_.id})),k=_=>{t?t(_):_&&_!==e&&y(b.toolLink(_))};return o.jsx(Xl,{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 nas=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=v.useState({sseUrl:"",httpStreamUrl:""});if(v.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(dy,{children:o.jsx(ge,{as:"h1",variant:"header-md",className:"text-neutral3 font-medium py-20 text-center",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(dy,{isDivided:!0,children:[o.jsxs("div",{className:"px-8 py-12 mx-auto max-w-2xl w-full",children:[o.jsx(ge,{as:"h1",variant:"header-md",className:"text-neutral6 font-medium pb-4",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(fn,{icon:o.jsx(aTt,{className:"text-neutral6"}),className:"rounded-r-sm text-neutral4!",children:"Version"}),o.jsx(fn,{className:"rounded-l-sm text-neutral4!",children:t.version_detail.version})]}),o.jsx(ge,{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:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(fn,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ge,{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(ge,{className:"px-2 py-1 bg-surface4 rounded-lg",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(ya,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(fn,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ge,{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(ge,{className:"px-2 py-1 bg-surface4 rounded-lg",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(ya,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(fn,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",children:"CLI"}),children:"Command Line"}),o.jsx(ge,{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(ge,{className:"px-2 py-1 bg-surface4 rounded-lg",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(ya,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"h-full overflow-y-scroll border-l border-border1",children:o.jsx(ras,{server:t})})]})},ras=({server:e})=>{const{data:t={},isLoading:n}=G6t(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"p-5 overflow-y-scroll",children:[o.jsxs("div",{className:"text-neutral6 flex gap-2 items-center",children:[o.jsx(Ue,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(D_,{})}),o.jsx(ge,{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(aas,{tool:a,serverId:e.id},s)})})]})};function sas(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 aas=({tool:e,serverId:t})=>{const n=v.useRef(null),{Link:r,paths:s}=yn(),a=u8t[e.toolType||"tool"],i=sas(e._meta);return o.jsxs(Of,{onClick:()=>n.current?.click(),children:[o.jsx(Hvt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Cf,{children:[o.jsx(_f,{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(fn,{className:"text-[10px] py-0",children:"App"})]})}),o.jsx(Zp,{children:e.description})]})]})},ias=()=>{const{serverId:e}=dr(),{data:t=[],isLoading:n}=PZ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(nas,{isLoading:n,server:r})})};function oas(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 las=({toolId:e,serverId:t})=>{const{canExecute:n}=al(),r=n("tools"),s=We(),{data:a,isLoading:i,error:l}=Yje(t,e),{mutateAsync:c,isPending:u,data:d}=WQr(t,e),f=a?oas(a._meta):void 0,{data:p}=wt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=v.useCallback(async(y,b)=>await c(b),[c]);v.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";De.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(At,{className:"h-8 w-48 mb-4"}),o.jsx(At,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let g;try{g=um(lm(a.inputSchema))}catch(y){console.error("Error processing input schema:",y),De.error("Failed to process tool input schema."),g=Ss({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-b border-border1 p-4",children:o.jsx(Z6t,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(iTe,{executionResult:d,isExecutingTool:u,zodInputSchema:g,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},cas=()=>{const{serverId:e,toolId:t}=dr(),{data:n,isLoading:r}=Yje(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(las,{toolId:t,serverId:e})})},UQe={agents:Os.AGENT,workflows:Os.WORKFLOW_RUN,tools:Os.TOOL};function uas(){const{data:e,isLoading:t,isError:n}=a1r(),{getTracesHref:r,getBucketTracesHref:s}=fI(),{Link:a}=yn(),i=bs();return o.jsx(Hwr,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:UQe[l]},c.tsMs,"1h"))},actions:l=>o.jsx($D,{href:r({rootEntityType:UQe[l]}),LinkComponent:a})})}function das(){const e=h1r(),t=m1r(),{getTracesHref:n}=fI(),{Link:r}=yn();return o.jsx(Zwr,{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 fas(){const{data:e,isLoading:t,isError:n}=kTt();return o.jsx(MD,{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 pas(){const{data:e,isLoading:t,isError:n}=n1r();return o.jsx(MD,{label:"Total Model Cost",value:e?.cost!=null?gg(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?gg(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function has(){const{data:e,isLoading:t,isError:n}=r1r();return o.jsx(MD,{label:"Total Tokens",value:e?.value!=null?yc(e.value):null,prevValue:e?.previousValue!=null?yc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function mas(){const{data:e,isLoading:t,isError:n}=f1r();return o.jsx(MD,{label:"Total Threads",value:e?.value!=null?yc(e.value):null,prevValue:e?.previousValue!=null?yc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function gas(){const{data:e,isLoading:t,isError:n}=p1r();return o.jsx(MD,{label:"Total Resources",value:e?.value!=null?yc(e.value):null,prevValue:e?.previousValue!=null?yc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function vas({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=>yas(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(Hwe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(qwe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function yas(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 bas(){const{data:e,isLoading:t,isError:n}=s1r(),{getTracesHref:r}=fI(),{Link:s}=yn();return o.jsx(Gwr,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Os.AGENT}),actions:o.jsx($D,{href:r({rootEntityType:Os.AGENT}),LinkComponent:s})})}function xas(){const{data:e,isLoading:t,isError:n}=o1r(),{getTracesHref:r}=fI(),{Link:s}=yn();return o.jsx(Ywr,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Os.AGENT,entityName:a.name}),actions:o.jsx($D,{href:r({rootEntityType:Os.AGENT}),LinkComponent:s})})}function was(){const{data:e,isLoading:t,isError:n}=d1r(),{getTracesHref:r}=fI(),{Link:s}=yn();return o.jsx(Jwr,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx($D,{href:r(),LinkComponent:s})})}const J8={agents:Os.AGENT,workflows:Os.WORKFLOW_RUN,tools:Os.TOOL};function Sas(){const{data:e,isLoading:t,isError:n}=i1r(),{getTracesHref:r,getLogsHref:s}=fI(),{Link:a}=yn();return o.jsx(e1r,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:J8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:J8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx($D,{href:r({rootEntityType:J8[i]}),LinkComponent:a}),o.jsx(qwr,{href:s({rootEntityType:J8[i],status:"error"}),LinkComponent:a})]})})}const kas=new Set(["ObservabilityStorageClickhouseVNext","ObservabilityStorageDuckDB","ObservabilityInMemory","ObservabilitySpanner"]),ise="period",e9="dateFrom",t9="dateTo";function Oas(){const[e,t]=ji(),n=e.get(ise),r=Mwr(n)?n:"24h",s=v.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(e9)),p=d(e.get(t9));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=v.useMemo(()=>Twr(e),[e.toString()]),i=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(ise):p.set(ise,d),d!=="custom"&&(p.delete(e9),p.delete(t9)),p},{replace:!0})},[t]),l=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(e9,d.from.toISOString()):p.delete(e9),d?.to?p.set(t9,d.to.toISOString()):p.delete(t9),p},{replace:!0})},[t]),c=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return Iwr(p,d),p},{replace:!0})},[t]),u=v.useRef(!1);return v.useEffect(()=>{if(u.current||(u.current=!0,Ewr(e)))return;const d=xTt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(Lwr,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(_as,{})})}function _as(){const[e]=ji(),{error:t,isLoading:n}=kTt(),{filterTokens:r,setFilterTokens:s}=QH(),[a,i]=v.useState(),{data:l,isLoading:c}=U4(),u=l?.observabilityStorageType,d=u?kas.has(u):!1,f=u==="ObservabilityInMemory",{data:p,isLoading:h}=NOe(),{data:m,isLoading:g}=IOe(),{data:y,isLoading:b}=ROe(),{data:w,isLoading:S}=AOe(),k=v.useMemo(()=>jwr({availableTags:p??[],availableEntityNames:m??[],availableServiceNames:y??[],availableEnvironments:w??[],loading:{tags:h,entityNames:g,serviceNames:b,environments:S}}),[p,m,y,w,h,g,b,S]),[_,C]=v.useState(()=>xTt()!==null),E=v.useCallback(()=>{_wr(e),C(!0),De.success("Filters setting for Metrics saved")},[e]),j=v.useCallback(()=>{Cwr(),C(!1),De.success("Filters setting for Metrics cleared up")},[]),N=v.useCallback(()=>{s([])},[s]),I=v.useCallback(()=>{const R=r.map($=>{const F=k.find(D=>D.id===$.fieldId);return F?F.kind==="text"?{fieldId:$.fieldId,value:""}:F.kind==="pick-multi"?F.multi?{fieldId:$.fieldId,value:[]}:{fieldId:$.fieldId,value:"Any"}:F.kind==="multi-select"?{fieldId:$.fieldId,value:[]}:$:$});s(R)},[k,r,s]);return t&&gs(t)?o.jsx(lr,{children:o.jsx(Vs,{})}):t&&ys(t)?o.jsx(lr,{children:o.jsx(Ds,{resource:"metrics"})}):t?o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Uwr,{}),o.jsx(Wwe,{fields:k,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(vas,{isLoading:n,filterFields:k,filterTokens:r,onFilterTokensChange:s,onClear:I,onRemoveAll:N,onSave:E,onRemoveSaved:_?j:void 0,autoFocusFilterFieldId:a})]}),c?null:d?o.jsxs("div",{className:"grid gap-8 content-start pb-10",children:[f&&o.jsx(In,{variant:"info",title:"Metrics are not persisted",children:o.jsx(In.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, or Spanner."})}),o.jsxs(Wpe,{children:[o.jsx(fas,{}),o.jsx(pas,{}),o.jsx(has,{}),o.jsx(mas,{}),o.jsx(gas,{})]}),o.jsxs(Wpe,{children:[o.jsx(bas,{}),o.jsx(xas,{}),o.jsx(was,{}),o.jsx(das,{}),o.jsx(Sas,{}),o.jsx(uas,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(xf,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Spanner, or in-memory storage for observability. Relational databases (PostgreSQL, LibSQL) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsxs(ue,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Pa,{})]})})})]})}function Cas(){const{paths:e}=yn(),{data:t,isLoading:n,error:r}=d8t(),{isCmsAvailable:s}=wI(),[a,i]=v.useState(""),l=t?.promptBlocks??[];return r&&gs(r)?o.jsx(lr,{children:o.jsx(Vs,{})}):r&&ys(r)?o.jsx(lr,{children:o.jsx(Ds,{resource:"prompt blocks"})}):r?o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load prompt blocks",message:r.message})}):l.length===0&&!n?o.jsx(lr,{children:o.jsx(PKr,{})}):o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(jf,{onSearch:i,label:"Filter prompts",placeholder:"Filter by name or description"})}),s&&o.jsxs(ue,{as:ci,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Fr,{}),"Create Prompt"]})]})}),o.jsx(RKr,{promptBlocks:l,isLoading:n,search:a})]})}function Eas(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx(kYr,{children:o.jsx(kve,{})})})})}const jas=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:pcn,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:ilt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Pa,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:qj,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:hlt,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:olt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Tas(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 max-w-3xl",children:jas.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group flex flex-col gap-3 rounded-lg border border-border1 bg-surface2 p-5 transition-colors hover:border-accent1 hover:bg-surface3",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"h-5 w-5 text-icon3 group-hover:text-accent1 transition-colors"}),o.jsx("span",{className:"text-ui-md font-medium text-text1",children:e.title}),e.external&&o.jsx(Pa,{className:"h-3.5 w-3.5 text-icon3 ml-auto opacity-0 group-hover:opacity-100 transition-opacity"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function Nas(){const{data:e={},isLoading:t,error:n}=eh(),[r,s]=v.useState(""),[a,i]=v.useState("all");if(n&&gs(n))return o.jsx(lr,{children:o.jsx(Vs,{})});if(n&&ys(n))return o.jsx(lr,{children:o.jsx(Ds,{resource:"scorers"})});if(n)return o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(lr,{children:o.jsx(BXr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(qXr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(zXr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Ias(){const{scorerId:e}=dr(),[t,n]=ji(),r=t.get("scoreId")??void 0,[s,a]=v.useState(r),[i,l]=v.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=DXr(e),{data:d={},isLoading:f,error:p}=km(),{isLoading:h,error:m}=Uy(),{data:g=[],isLoading:y,error:b,isFetchingNextPage:w,hasNextPage:S,setEndOfListElement:k}=MXr({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),_=v.useMemo(()=>c?.agentIds?.filter(B=>d[B]).map(B=>({value:B,label:d[B].name,type:"AGENT"}))||[],[c?.agentIds,d]),C=v.useMemo(()=>c?.workflowIds?.map(B=>({value:B,label:B,type:"WORKFLOW"}))||[],[c?.workflowIds]),E=v.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},..._,...C],[_,C]),j=t.get("entity")??"all",N=E.find(B=>B.value===j);N&&N.value!==i?.value&&l(N),v.useEffect(()=>{if(u){const B=u instanceof Error?u.message:"Failed to load scorer";De.error(`Error loading scorer: ${B}`)}},[u]),v.useEffect(()=>{if(p){const B=p instanceof Error?p.message:"Failed to load agents";De.error(`Error loading agents: ${B}`)}},[p]),v.useEffect(()=>{if(m){const B=m instanceof Error?m.message:"Failed to load workflows";De.error(`Error loading workflows: ${B}`)}},[m]);const I=B=>{B?.value&&n(M=>{const G=new URLSearchParams(M);return G.set("entity",B.value),G})};v.useEffect(()=>{const B=t.get("scoreId")??void 0;if(B===s)return;if(!B){a(void 0);return}g.find(G=>G.id===B)&&a(B)},[t,g]);const R=v.useCallback(B=>{a(B||void 0),n(M=>{const G=new URLSearchParams(M);return B?G.set("scoreId",B):G.delete("scoreId"),G})},[n]);if(!c)return null;const $=gs(u)||gs(p)||gs(m),F=u&&ys(u),D=!$&&!F&&(u||p||m),V=!y&&g.length===0,W=i?.value!=="all",L=c?.scorer?.source==="stored"?o.jsx(Ty,{owner:"scorer-detail",children:o.jsxs(ue,{variant:"default",as:ci,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(em,{})," Edit"]})}):null;if($||F||D||V&&!W){const B=(u instanceof Error?u.message:void 0)??(p instanceof Error?p.message:void 0)??(m instanceof Error?m.message:void 0)??"An unexpected error occurred";return o.jsxs(Lt,{width:"wide",height:"full",children:[L,o.jsx(Lt.MainArea,{isCentered:!0,children:$?o.jsx(Vs,{}):F?o.jsx(Ds,{resource:"scorers"}):D?o.jsx(Fi,{title:"Failed to load scorer",message:B}):o.jsx(IXr,{})})]})}return o.jsxs(Lt,{width:"wide",children:[L,o.jsx(Lt.TopArea,{children:o.jsx(AXr,{selectedEntity:i,entityOptions:E,onEntityChange:I,onReset:()=>{n(B=>{const M=new URLSearchParams(B);return M.set("entity","all"),M})},isLoading:y||f||h})}),o.jsx(NXr,{scores:g,isLoading:y,selectedScoreId:s,isFetchingNextPage:w,hasNextPage:S,setEndOfListElement:k,onScoreClick:R,errorMsg:b?.message})]})}function Aas({label:e,description:t,htmlFor:n,className:r,children:s}){return o.jsxs("div",{className:K("flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",r),"data-slot":"settings-row",children:[o.jsxs("div",{children:[n?o.jsx(Rt,{htmlFor:n,className:"text-sm font-medium",children:e}):o.jsx("p",{className:"text-sm font-medium",children:e}),t&&o.jsx("p",{className:"text-sm text-neutral3",children:t})]}),s]})}const c9t=[{value:"dark",label:"Dark",Icon:Uun},{value:"light",label:"Light",Icon:Xdn},{value:"system",label:"System",Icon:Olt}],Ras=e=>c9t.some(t=>t.value===e);function Pas({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex min-w-0 max-w-full 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 $as=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=Axe(),{theme:r,setTheme:s}=$N();return o.jsx(Lt,{width:"narrow",children:o.jsxs(Lt.MainArea,{className:"flex flex-col gap-5 mt-6",children:[o.jsx(she,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(Aas,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(ba,{value:r,onValueChange:a=>{Ras(a)&&s(a)},children:[o.jsx(wa,{id:"theme",className:"w-full sm:w-48",children:o.jsx(xa,{className:"inline-flex min-w-0 max-w-full items-center"})}),o.jsx(Sa,{children:c9t.map(a=>o.jsx(qr,{value:a.value,children:o.jsx(Pas,{option:a})},a.value))})]})})}),o.jsx(she,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(X6t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function Mas(){const[e]=ji(),t=bs(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(l9t,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function Das(e){return e.replace(/\/$/,"").split("/").pop()}function HZ({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 Las({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:"h-16 bg-surface3 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:"w-full h-full bg-cover thumb transition-scale 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:"hidden 2xl:flex text-neutral3 text-ui-md flex-wrap items-center gap-4 mt-3",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(rl,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Gp,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(_lt,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(eq,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(D_,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"flex items-center text-neutral3 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:"flex items-center gap-2 px-2 py-1 rounded bg-surface1 group-hover:bg-surface2 text-neutral3 transition-colors group-hover:text-neutral5",children:[o.jsx(iTt,{})," ",Das(a.githubUrl)]})})]},a.slug)})})}function Fas({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(iT,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(bc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(bc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(ue,{onClick:c,children:["Reset ",o.jsx(vs,{})]})]})}function zas(){const{data:e,isLoading:t}=FPr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=v.useState("all"),[l,c]=v.useState("all"),[u,d]=v.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(w=>{f.push({value:w,label:w})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(w=>{p.push({value:w,label:w})});const h=(w,S)=>{S==="tag"?i(w):S==="provider"&&c(w)},m=w=>{d(w)},g=()=>{i("all"),c("all"),d("")},y=n.filter(w=>!(u&&!w.title.toLowerCase().includes(u)&&!w.description.toLowerCase().includes(u)||a!=="all"&&!w.tags.includes(a)||l!=="all"&&!w.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(cs,{children:[o.jsx(qxe,{children:o.jsxs(hpt,{children:[o.jsx(Ue,{children:o.jsx(Hv,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(Fas,{selectedTag:a,onTagChange:w=>h(w,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:w=>h(w,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?g:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(Las,{templates:y,linkComponent:ci,className:"max-w-[80rem] mx-auto",isLoading:t})]})]})}const Bas="1.47.0";function Uas({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(kp,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(Ucn,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(HZ,{className:"space-y-4 text-neutral3 mb-8 content-center",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:"text-center space-y-2",children:[o.jsx("p",{className:"text-ui-md font-medium text-neutral5",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:"cursor-pointer text-neutral3 hover:text-neutral4 select-none text-center",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 p-3 bg-gray-100 dark:bg-gray-800 rounded text-xs overflow-auto max-h-60 text-left space-y-2",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"text-xs font-mono text-gray-700 dark:text-gray-300 mt-1 whitespace-pre-wrap wrap-break-word",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"cursor-pointer text-neutral3 hover:text-neutral4 select-none text-center",children:"Show Details"}),o.jsx("div",{className:"mt-4 p-3 bg-gray-100 dark:bg-gray-800 rounded text-xs font-mono overflow-auto max-h-60 text-left",children:o.jsx("div",{className:"whitespace-pre-wrap wrap-break-word",children:n})})]})]})}function qas({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(HZ,{children:o.jsxs("div",{className:"max-w-[40rem] my-4 p-4 lg:p-8 mx-auto gap-8 grid",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(Clt,{})]}),o.jsx(bc,{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] gap-4 items-start",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(Gt,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(v.Fragment,{children:[o.jsx(_O,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(_O,{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-t border-border1 pt-12 mt-3.5 relative",children:[o.jsx("div",{className:"absolute w-8 h-8 rounded-full bg-surface2 top-0 left-1/2 -translate-x-1/2 -translate-y-4 text-ui-sm text-neutral3 flex items-center justify-center",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(Y6t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ue,{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(Gt,{className:"w-4 h-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(hm,{})]})})]})})}function Vas({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(Hv,{}),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 lg:grid-cols-[1fr_1fr] gap-x-24",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:"shrink-0 mt-0.5",children:o.jsx(Mx,{className:"w-[1.1em] h-[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(Vye,{className:"w-[1em] h-[1em] text-neutral4"}),o.jsx("span",{className:"text-ui-md font-medium text-neutral5",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 px-1.5 py-0.5 rounded text-ui-sm 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:"flex items-center gap-2 mt-auto text-neutral3 text-ui-md hover:text-neutral5",children:[o.jsx(iTt,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(v1e,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Has({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=g=>g==="input"||g.endsWith(".input")||g.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(g)||/[0-9a-f]{8,}/.test(g)?!1:r?.allSteps?g in r.allSteps:!0,f=Object.entries(c).filter(([g,y])=>d(g)),p=f.length,h=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([g,y])=>({id:g,status:y?.status,description:y?.description,title:g.charAt(0).toUpperCase()+g.slice(1).replace(/-/g," "),isActive:i?.id===g}));return o.jsxs(HZ,{className:"space-y-6 text-neutral3 mb-8 content-center",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-lg font-semibold text-neutral5",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"mt-2 text-ui-sm text-neutral3",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"max-w-[30rem] w-full mx-auto px-6",children:o.jsx(qWn,{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(Kun,{}),l||"Something went wrong"]}),u&&o.jsx(UWn,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-center text-sm text-neutral3 grid gap-4 justify-items-center",children:[o.jsx(Gt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Was({name:e,installedEntities:t}){return o.jsxs(HZ,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Clt,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-center text-neutral3 ",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(v1e,{data:t})]})}function Zas(){const{templateSlug:e}=dr(),[t,n]=ji(),[r,s]=v.useState(""),[a,i]=v.useState(""),[l,c]=v.useState(""),[u,d]=v.useState({}),[f,p]=v.useState([]),[h,m]=v.useState(null),[g,y]=v.useState(!1),[b,w]=v.useState(""),[S,k]=v.useState(!1),[_,C]=v.useState(!1),[E,j]=v.useState([]),{data:N,isLoading:I}=zPr({repoOrSlug:e,owner:"mastra-ai"}),$=Bas?.includes("beta")??!1?"beta":"main",{data:F,isLoading:D}=BPr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:$}),{data:V,isLoading:W}=UPr(),{mutateAsync:L,isPending:z}=qPr(),{mutateAsync:B}=VPr(),{streamInstall:M,streamResult:G,isStreaming:U}=WPr(V),{observeInstall:P,streamResult:q,isStreaming:Z}=ZPr(V);v.useEffect(()=>{const ne=t.get("runId");ne&&!g&&!h&&!U&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),w(ne),B({runId:ne}).then(ce=>{const pe=ce.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:ve,errors:ye}=pe.result.validationResults,Se=`Template installation completed but ${ve} validation issue${ve>1?"s":""} remain unresolved.`;m(Se),j(ye||[])}else{const ve=pe?.result?.message||pe?.result?.error||"Template installation failed";m(typeof ve=="string"?ve:String(ve))}}).catch(ce=>{console.error("❌ Failed to fetch run details:",ce),m("Failed to retrieve installation status after reload")}))},[t,g,h,U,Z,B]),v.useEffect(()=>{const ne=t.get("runId"),ce=t.get("resume"),pe=t.get("provider");if(ne&&ce==="true"&&pe&&!U&&!Z&&!S&&!_&&V){w(ne),k(!0);try{B({runId:ne}).then(le=>{if(le.snapshot?.status==="running")return P.mutateAsync({runId:ne})}).then(()=>{n(le=>{const ve=new URLSearchParams(le);return ve.delete("resume"),ve})}).catch(le=>{console.error("❌ Failed to resume template installation:",le),le.message?.includes("404")||le.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(le){console.error("❌ Auto-resume failed with error:",le),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,U,Z,S,_,V,B,P,n]);const X=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],te=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Gp,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(rl,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(eq,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Iv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(hN,{})}],J=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");v.useEffect(()=>{F&&d(F)},[F]),v.useEffect(()=>{const ne=G||q;ne?.phase==="error"&&ne?.error&&m(typeof ne.error=="string"?ne.error:String(ne.error))},[G?.phase,G?.error,q?.phase,q?.error]);const ee=ne=>{s(ne)},ae=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),de=async()=>{const ne=Object.entries(u).reduce((ce,[pe,le])=>(le===""&&ce.push(pe),ce),[]);if(ne.length>0){p(ne);return}if(N){m(null),y(!1),w(""),C(!0);try{const pe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:$,slug:N.slug,variables:u},{runId:le}=await L({});w(le),n(ve=>{const ye=new URLSearchParams(ve);return ye.set("runId",le),ye.set("resume","true"),ye.set("provider",r||"openai"),ye}),await M.mutateAsync({inputData:pe,selectedModel:{provider:a,modelId:l},runId:le})}catch(ce){C(!1),m(ce?.message||"Template installation failed"),console.error("Template installation failed",ce)}}},Y=ne=>{const{name:ce,value:pe}=ne.target;pe.trim()===""?p(le=>[...le,ce]):p(le=>le.filter(ve=>ve!==ce)),d(le=>({...le,[ce]:pe}))};return o.jsx(cs,{children:o.jsx("div",{className:K("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"p-6 w-full max-w-[80rem] mx-auto grid gap-y-4",children:[o.jsx(Vas,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(U||Z)&&o.jsx(Has,{name:N.title,streamResult:Z?q:G,runId:b,workflowInfo:V}),g&&o.jsx(Was,{name:N.title,installedEntities:J,linkComponent:ci}),h&&o.jsx(Uas,{errorMsg:h,validationErrors:E.length>0?E:G?.validationResults?.errors||q?.validationResults?.errors}),!U&&!Z&&!g&&!h&&o.jsx(qas,{providerOptions:X,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:de,handleVariableChange:Y,isLoadingEnvVars:D||W,isInstalling:z,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const Gas=()=>{const{toolId:e,agentId:t}=dr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(gKr,{toolId:e,agentId:t})})},Qas=()=>{const{toolId:e}=dr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(eas,{toolId:e})})};function Yas(){const{traceId:e}=dr(),[t,n]=ji(),r=bs(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=v.useState(s??null),[d,f]=v.useState(),[p,h]=v.useState(i),[m,g]=v.useState(0),[y,b]=v.useState(!1),{data:w,isLoading:S,error:k}=XH(e),_=v.useMemo(()=>w?.spans??[],[w?.spans]),C=v.useMemo(()=>_.find(ae=>ae.parentSpanId==null),[_]),{data:E,isLoading:j}=pI(e,c??"");v.useEffect(()=>g(0),[e,c]);const{data:N,isLoading:I}=eh(),{data:R,isLoading:$}=o8t({traceId:e,spanId:c??void 0,page:m}),[F,D]=v.useState(0);v.useEffect(()=>D(0),[e,c]);const{data:V,isLoading:W}=J8t({traceId:e,page:F});v.useEffect(()=>{if(l&&R?.scores&&!d){const ae=R.scores.find(de=>de.id===l);ae&&f(ae)}},[l,R?.scores,d]);const L=v.useCallback(ae=>{const de=new URLSearchParams(t);for(const[Y,ne]of Object.entries(ae))ne===null||ne===""?de.delete(Y):de.set(Y,ne);n(de,{replace:!0})},[t,n]),z=v.useCallback(ae=>{const de=ae??null,Y=de===c;u(de),Y||(f(void 0),h("details"),L({spanId:de,tab:null,scoreId:null}))},[c,L]),B=v.useCallback(()=>{u(null),f(void 0),h("details"),L({spanId:null,tab:null,scoreId:null})},[L]),M=v.useCallback(ae=>{u(ae),f(void 0),h("details"),L({spanId:ae,tab:null,scoreId:null})},[L]),{handlePreviousSpan:G,handleNextSpan:U}=KH(_,c,M),P=v.useCallback(ae=>{const de=ae;h(de),f(void 0),L({tab:de==="details"?null:de,scoreId:null})},[L]),q=v.useCallback(ae=>{f(ae),L({scoreId:ae.id})},[L]),Z=v.useCallback(()=>{f(void 0),L({scoreId:null})},[L]),X=v.useCallback(()=>{r("/observability")},[r]),te=v.useCallback(()=>{h("scoring"),C&&c!==C.spanId?(u(C.spanId),f(void 0),L({spanId:C.spanId,tab:"scoring",scoreId:null})):L({tab:"scoring"})},[C,c,L]),J=C?o.jsx(Ty,{owner:"trace-detail",children:o.jsxs($r,{children:[o.jsxs(ue,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:te,children:[o.jsx(Pln,{}),"Evaluate"]}),o.jsxs(ue,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(fd,{}),"Save"]})]})}):null,ee=C?o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{children:o.jsx(TTt,{rootSpan:C,numOfCol:3})})}):null;return k?o.jsxs(Lt,{height:"full",children:[J,ee&&o.jsx(Lt.TopArea,{children:ee}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(RTt,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Lt,{children:[J,ee&&o.jsx(Lt.TopArea,{children:ee}),o.jsx(G8t,{rootSpanId:C?.spanId,traceId:e,isOpen:y,onClose:()=>b(!1)}),o.jsxs("div",{className:K("grid h-full min-h-0 gap-4 overflow-hidden items-start mt-4",c?"grid-cols-[2fr_3fr]":"grid-cols-[1fr]"),children:[o.jsx(TOe,{traceId:e,spans:_,isLoading:S,onClose:X,onSpanSelect:z,onEvaluateTrace:te,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!S&&o.jsxs("div",{className:K("grid gap-4 max-h-full min-h-0 overflow-auto",d?"grid-rows-[1fr_1fr]":"grid-rows-[1fr]"),children:[o.jsx(YH,{traceId:e,spanId:c,span:E?.span,isLoading:j,onClose:B,onPrevious:G,onNext:U,activeTab:p,onTabChange:P,feedbackTabBadge:V?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(Y8t,{feedbackData:V,onPageChange:D,isLoadingFeedbackData:W}),scoringTabBadge:R?.pagination?.total??void 0,scoringTabSlot:({span:ae,traceId:de,spanId:Y})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(K8t,{traceId:de,isTopLevelSpan:!ae.parentSpanId,spanId:Y,entityType:ae.attributes?.agentId||ae.entityType===Os.AGENT?"Agent":ae.attributes?.workflowId||ae.entityType===Os.WORKFLOW_RUN?"Workflow":void 0,scorers:N,isLoadingScorers:I}),o.jsx(X8t,{scoresData:R,onPageChange:g,isLoadingScoresData:$,onScoreSelect:q})]})}),d&&o.jsx(sTe,{score:d,onClose:Z})]})]})]})}function Xas(){const{data:e,isLoading:t,error:n}=Uy(),[r,s]=v.useState("");return n&&gs(n)?o.jsx(lr,{children:o.jsx(Vs,{})}):n&&ys(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"workflows"})}):n?o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(lr,{children:o.jsx(Qzr,{})}):o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(jf,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(ue,{as:ci,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(o3,{}),"Schedules"]})]})}),o.jsx(Gzr,{workflows:e||{},isLoading:t,search:r})]})}const Kas={active:"bg-accent1",paused:"bg-accent3"},Jas={active:"text-accent1",paused:"text-accent3"},u9t=({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 ${Kas[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${Jas[e]}`,children:e})]}),Rj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),sP=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 d9t({status:e}){const{icon:t,color:n}=eis(e);return o.jsxs("span",{className:`inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function eis(e){switch(e){case"success":return{icon:o.jsx(Js,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(vs,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Gt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(ZU,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(xf,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(sO,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const qQe="auto auto auto auto 1fr";function tis(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 nis(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 ris=3e4,sis=5*6e4;function ais({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=yn();return t?o.jsx(el,{columns:qQe}):e.length===0?o.jsx(ge,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(me,{columns:qQe,className:"min-w-0",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Run"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{children:"Started"}),o.jsx(me.TopCell,{children:"Duration"}),o.jsx(me.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=nis(u),f=`Scheduled ${Rj(c.scheduledFireAt)} — published ${Rj(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),g=!p&&m>ris&&m<=sis,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),w=o.jsx("span",{className:b?"text-accent1 font-mono text-ui-sm whitespace-nowrap":"text-neutral3 font-mono text-ui-sm whitespace-nowrap",children:c.runId}),S=o.jsxs(o.Fragment,{children:[o.jsx(me.Cell,{height:"compact",children:w}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm text-accent2",children:[o.jsx(kp,{size:14}),"publish failed"]}):c.run?o.jsx(d9t,{status:c.run.status}):o.jsx("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm text-neutral3",children:"pending"}),h?o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(kp,{size:14})})}),o.jsx(Bn,{children:h})]}):null]})}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:sP(c.actualFireAt)}),g?o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(kp,{size:14})})}),o.jsxs(Bn,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(me.Cell,{height:"compact",children:c.run?o.jsx("span",{children:tis(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(me.Cell,{height:"compact",children:" "})]});return b?o.jsx(me.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:S},y):o.jsx(me.RowStatic,{children:S},y)}),o.jsx(me.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const iis=e=>{const t=We();return wt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},VQe=25,ois=e=>{const t=We(),{inView:n,setRef:r}=P_(),s=R1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:VQe,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<VQe))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return v.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},lis=e=>{const t=We(),n=Hr();return Rn({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"]}),De.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{De.error(r.message)}})};function n9({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 uppercase tracking-wide",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function cis(){const{scheduleId:e}=dr(),{paths:t}=yn(),{data:n,error:r}=iis(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=ois(e),d=lis(e);if(r&&gs(r))return o.jsx(lr,{children:o.jsx(Vs,{})});if(r&&ys(r))return o.jsx(lr,{children:o.jsx(Ds,{resource:"schedules"})});if(r)return o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load schedule",message:r.message})});const f=n?.target.type==="workflow"?n.target.workflowId:void 0;return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{className:"justify-end",children:o.jsxs(Lt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(ue,{as:ci,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(Ec,{}),"Back to schedules"]}),f?o.jsx(ue,{as:ci,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ue,{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(Elt,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Pp,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid gap-6 h-full overflow-hidden grid-cols-[minmax(0,20rem)_1fr]",children:[o.jsxs("div",{className:"flex flex-col gap-4 border border-border1 rounded-md p-4 h-fit",children:[o.jsx(n9,{label:"Workflow",children:f?o.jsx(ci,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):"—"}),o.jsxs(n9,{label:"Cron",children:[o.jsx("code",{className:"font-mono text-ui-md",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 ml-2 text-ui-sm",children:n.timezone}):null]}),o.jsx(n9,{label:"Status",children:o.jsx(u9t,{status:n.status})}),o.jsx(n9,{label:"Next fire",children:o.jsx("span",{title:Rj(n.nextFireAt),children:sP(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ge,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Fi,{title:"Failed to load trigger history",message:i.message}):o.jsx(ais,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const HQe="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function uis({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=yn(),a=v.useMemo(()=>{const i=n.toLowerCase();return i?e.filter(l=>l.id.toLowerCase().includes(i)||l.target.workflowId.toLowerCase().includes(i)):e},[e,n]);return t?o.jsx(el,{columns:HQe}):o.jsxs(me,{columns:HQe,variant:"striped",className:"min-w-0",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Workflow"}),o.jsx(me.TopCell,{children:"Schedule ID"}),o.jsx(me.TopCell,{children:"Cron"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{children:"Next fire"}),o.jsx(me.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(me.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(me.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(me.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(me.NameCell,{children:i.target.workflowId}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"block truncate font-mono text-ui-smd text-neutral3",title:i.id,children:i.id})}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"font-mono text-ui-sm",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(me.Cell,{height:"compact",children:o.jsx(u9t,{status:i.status})}),o.jsx(me.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:Rj(i.nextFireAt),children:sP(i.nextFireAt)})}),o.jsx(me.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(d9t,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:Rj(i.lastFireAt),children:i.lastFireAt?sP(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:Rj(i.lastFireAt),children:sP(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function dis({workflowId:e}={}){const{data:t,isLoading:n,error:r}=Bxe(e?{workflowId:e}:{}),[s,a]=v.useState("");return r?o.jsx(Fi,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid grid-rows-[auto_1fr] gap-4 h-full overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(jf,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(uis,{schedules:t??[],isLoading:n,search:s})})]})}function fis(){const[e]=ji(),t=e.get("workflowId")??void 0,{error:n}=Bxe(t?{workflowId:t}:{});return n&&gs(n)?o.jsx(lr,{children:o.jsx(Vs,{})}):n&&ys(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"schedules"})}):o.jsx(Lt,{children:o.jsx("div",{className:"h-full",children:o.jsx(dis,{workflowId:t})})})}function pis({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=b_e({stepGraph:e}),[a,i]=v.useState(!1),[l,c,u]=IAt(r),[d]=AAt(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=K$t({edges:d,workflowName:n,stepGraph:e});return v.useEffect(()=>{t&&setTimeout(()=>{i(!0)},500)},[t]),o.jsx("div",{className:"w-full h-full relative bg-surface1",children:a?o.jsxs(NAt,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(ECe,{position:"bottom-left"}),o.jsx(PAt,{variant:ty.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"w-full h-full flex items-center justify-center",children:o.jsx(Gt,{})})})}function his(){const{stepDetail:e,closeStepDetail:t}=yW();return e?o.jsxs("div",{className:"flex flex-col h-full","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border1 bg-surface1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(Lde,{className:"w-4 h-4",style:{color:xu.map}}),e.type==="nested-graph"&&o.jsx(_d,{className:"w-4 h-4",style:{color:xu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ge,{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(ge,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"p-1 hover:bg-surface3 rounded transition-colors","aria-label":"Close",children:o.jsx(vs,{className:"w-4 h-4 text-neutral3"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(nP,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(y_e,{children:o.jsx(pis,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function mis(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function gis(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 vis({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"space-y-5 rounded-lg border border-border1 bg-surface4 p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ge,{as:"p",variant:"ui-md",className:"flex items-center gap-2 text-neutral6 font-semibold",children:[o.jsx(Ue,{children:o.jsx(ZU,{})}),"Step suspended"]}),o.jsx(fn,{variant:"warning",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?um(lm(jx(i.resumeSchema))):rp(ur(),DT());return o.jsx(yis,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function yis({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=v.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ge,{as:"p",variant:"ui-md",className:"text-neutral6 font-medium truncate",children:e.stepId}),n&&o.jsx(ge,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ge,{as:"p",variant:"ui-sm",className:"flex items-center gap-2 text-neutral3",children:[o.jsx(Ue,{children:o.jsx(Vun,{})}),"The step is asking"]}),o.jsxs(Mp,{open:a,onOpenChange:i,children:[o.jsxs(mf,{className:"flex w-full items-center justify-between gap-2 rounded-lg border border-border1 bg-surface3 px-3 py-2.5",children:[o.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[o.jsx(Ue,{children:o.jsx(la,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ge,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:gis(e.suspendPayload,e.stepId)})]}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:mis(e.suspendPayload)})]}),o.jsx(gf,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Qr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ge,{as:"p",variant:"ui-sm",className:"flex items-center gap-2 text-neutral3",children:[o.jsx(Ue,{children:o.jsx(Zun,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(zB,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Pp,{}),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 bis(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=v.useContext(Rl),{runId:a}=dr(),i=BAt(e,r??""),l=tPr(),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:"absolute top-2 right-2 z-20 w-[380px] max-w-[calc(100%-1rem)] max-h-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 duration-300",children:o.jsx(vis,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const xis=e=>e.includes("."),wis=e=>e==="input"||e.endsWith(".input"),Sis=1;function kis(e){return`${Number((e/1e3).toPrecision(3))}s`}function Ois(e,t){const n=Object.entries(e).filter(([i])=>!wis(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,Sis);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:xis(i)}})}const _is=({status:e})=>o.jsxs(Ue,{children:[e==="success"&&o.jsx(w0r,{className:"text-accent1"}),e==="failed"&&o.jsx(k0r,{className:"text-accent2"}),e==="suspended"&&o.jsx(ZU,{className:"text-accent3"}),e==="waiting"&&o.jsx(Dde,{className:"text-accent5"}),e==="skipped"&&o.jsx(Dde,{className:"text-icon3"}),e==="running"&&o.jsx(ia,{className:"text-accent6 animate-spin"})]}),Cis={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function f9t(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const WQe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},Eis=e=>{const t=e;return q$t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},jis=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=Eis(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(_is,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ue,{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(Hdn,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(uU,{indicators:c,className:"shrink-0"})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"block min-w-0 max-w-full justify-self-stretch overflow-hidden text-ellipsis whitespace-nowrap text-left text-neutral6",children:f9t(e.stepId)}),o.jsx("div",{className:"relative h-2 min-w-0 rounded bg-surface4",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 ${Cis[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ue,{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(qdn,{})})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"w-20 justify-self-end text-right text-neutral3 tabular-nums",children:kis(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function Tis(){const{steps:e}=l4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=JH(),[a,i]=v.useState(()=>Date.now()),[l,c]=v.useState(!1),[u,d]=v.useState(null),f=v.useRef(null);mwe(f,{enabled:!l});const p=Ois(e,a),h=p.some(m=>m.isRunning);return v.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),v.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden rounded-studio-panel border border-border1/50 bg-surface3 p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(ge,{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:"rounded-md p-1 text-neutral3 transition-colors hover:bg-surface4 hover:text-neutral6",children:o.jsx(Na,{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,g)=>o.jsx(jis,{row:m,index:g,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:WQe(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:WQe(y.step.output)})},`timeline-item-${m.stepId}-${g}`))})]})}),o.jsx(br,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(qAt,{data:u.data,title:`${f9t(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const Nis=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=yW();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(J$t,{workflowId:e,workflow:t,isLoading:n}),o.jsx(bis,{}),o.jsx(Tis,{})]})}),r&&o.jsx("div",{className:"w-[420px] min-h-0 overflow-hidden border-l border-border1",children:o.jsx(his,{})})]})},ZQe=()=>{const{workflowId:e}=dr(),{data:t,isLoading:n,error:r}=e4(e);return r&&gs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})}):r&&ys(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"workflows"})}):o.jsx(k_e,{children:o.jsx(Nis,{workflowId:e,workflow:t??void 0,isLoading:n})})};function Iis(e,t){if(e==null)return{};var n,r,s=Wgt(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 Dve(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 Ais(e){if(Array.isArray(e))return Dve(e)}function Ris(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Pis(e,t){if(e){if(typeof e=="string")return Dve(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)?Dve(e,t):void 0}}function $is(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
771
+ ]`})]})]})}function Srs({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 border-accent2/30 rounded-md p-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-accent2 mb-2",children:[o.jsx(Ue,{children:o.jsx(kp,{className:"w-4 h-4"})}),o.jsxs("span",{className:"font-medium text-sm",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-sm text-accent2/80 space-y-1",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-xs text-accent2/60 mt-2",children:["+",r," more error",r!==1?"s":""]})]})}function krs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=v.useState("upload"),[i,l]=v.useState(null),[c,u]=v.useState({current:0,total:0}),[d,f]=v.useState(null),[p,h]=v.useState(!1),{parseFile:m,isParsing:g,error:y}=yns(),{batchInsertItems:b}=_i(),w=v.useCallback(async I=>{try{const R=await m(I);l(R),a("preview")}catch{}},[m]),S=v.useCallback(async()=>{if(!i||i.items.length===0)return;a("importing"),h(!0);const{items:I}=i;u({current:0,total:I.length});try{await b.mutateAsync({datasetId:e,items:I.map(R=>({input:R.input,groundTruth:R.groundTruth,metadata:R.metadata}))}),f({success:I.length,errors:0})}catch{f({success:0,errors:I.length})}u({current:I.length,total:I.length}),h(!1),a("complete")},[i,b,e]),k=v.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&De.success(`Imported ${d.success} item${d.success!==1?"s":""}`),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150)},[n,r,d]),_=v.useCallback(()=>{p||(n(!1),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150))},[p,n]),C=i&&i.items.length>0&&i.errors.length===0,E=()=>{switch(s){case"upload":return o.jsx(wrs,{onFileSelect:w,isParsing:g,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(Srs,{errors:i.errors}),o.jsx("div",{className:"text-sm text-neutral4",children:"Please fix the errors in your JSON file and try again."})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-sm text-neutral4",children:["Found ",i.items.length," valid item",i.items.length!==1?"s":""," to import."]}),o.jsx(xrs,{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(Gt,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-lg font-medium text-neutral1",children:"Importing items..."}),o.jsxs("div",{className:"text-sm text-neutral4 mt-1",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-lg font-medium text-neutral1",children:"Import Complete"}),o.jsxs("div",{className:"text-sm text-neutral4 mt-1",children:[d?.success??0," item",d?.success!==1?"s":""," imported",d&&d.errors>0&&o.jsxs("span",{className:"text-accent2",children:[" ","(",d.errors," error",d.errors!==1?"s":"",")"]})]})]})]})}},j=()=>{switch(s){case"upload":return o.jsx(ue,{onClick:_,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(ue,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(ue,{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(ue,{variant:"primary",onClick:k,children:"Done"})}},N={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(br,{open:t,onOpenChange:_,children:o.jsxs(xr,{className:"max-w-2xl max-h-[90vh]",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:N[s]}),o.jsx(Qs,{children:"Import dataset items from a JSON file."})]}),o.jsx(Ar,{className:"min-h-[200px] max-h-[50vh] overflow-y-auto",children:E()}),o.jsx(kc,{className:"px-6 pt-4 flex justify-end gap-2",children:j()})]})})}const xTe=e=>{const t=We(),{data:n}=GM(e),r=n?.experiments;return wt({queryKey:["dataset-review-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="needs-review").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})},Ors=e=>{const t=We(),{data:n}=GM(e),r=n?.experiments;return wt({queryKey:["dataset-completed-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="complete").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})};function _rs(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 r9t({datasetId:e,experimentId:t,featuredItemId:n}){const r=We(),{data:s}=Ux(e),{data:a,isLoading:i}=xTe(e),{data:l,isLoading:c}=Ors(e),u=v.useMemo(()=>t?(a??[]).filter(Ce=>Ce.experimentId===t):a,[a,t]),d=v.useMemo(()=>t?(l??[]).filter(Ce=>Ce.experimentId===t):l,[l,t]),{updateExperimentResult:f}=_i(),[p,h]=v.useState(n??null);v.useEffect(()=>{n!==void 0&&h(n)},[n]);const[m,g]=v.useState(null),[y,b]=v.useState(new Set),[w,S]=v.useState(!1),[k,_]=v.useState(!1),[C,E]=v.useState(!1),[j,N]=v.useState(""),[I,R]=v.useState(""),[$,F]=v.useState(""),[D,V]=v.useState([]),[W,L]=v.useState(!1),[z,B]=v.useState(null),M=v.useMemo(()=>z??u??[],[z,u]);v.useEffect(()=>{B(null)},[e,t]),v.useEffect(()=>{u&&z===null&&B(u)},[u,z]);const G=v.useMemo(()=>{const Ce=new Set;if(s?.tags)for(const je of s.tags)Ce.add(je);for(const je of M)for(const _e of je.tags)Ce.add(_e);return[...Ce].sort()},[s,M]),U=v.useCallback(Ce=>{!s||!e||(s.tags??[]).includes(Ce)},[s,e]),P=v.useMemo(()=>m?m==="__untagged__"?M.filter(Ce=>Ce.tags.length===0):M.filter(Ce=>Ce.tags.includes(m)):M,[M,m]),q=v.useMemo(()=>{const Ce=new Map;for(const je of M)for(const _e of je.tags)Ce.set(_e,(Ce.get(_e)??0)+1);return[...Ce.entries()].sort((je,_e)=>_e[1]-je[1])},[M]),Z=v.useMemo(()=>M.filter(Ce=>Ce.tags.length===0).length,[M]),X=v.useMemo(()=>{let Ce=0;return m&&Ce++,w&&Ce++,Ce},[m,w]),te=v.useCallback((Ce,je)=>{B(Oe=>(Oe??[]).map(Re=>Re.id===Ce?{...Re,tags:je}:Re));const _e=M.find(Oe=>Oe.id===Ce);_e?.experimentId&&_e?.datasetId&&f.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,tags:je})},[M,f]),J=v.useCallback((Ce,je)=>{const _e=M.find(Oe=>Oe.id===Ce);_e?.traceId&&je!==void 0&&r.createFeedback({feedback:{traceId:_e.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:je==="positive"?1:-1,experimentId:_e.experimentId??void 0,sourceId:_e.id}}).catch(()=>{}),B(Oe=>(Oe??[]).map(Re=>Re.id===Ce?{...Re,rating:je}:Re))},[M,r]),ee=v.useCallback((Ce,je)=>{const _e=M.find(Oe=>Oe.id===Ce);_e?.traceId&&r.createFeedback({feedback:{traceId:_e.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:je,comment:je,experimentId:_e.experimentId??void 0,sourceId:_e.id}}).catch(()=>{}),B(Oe=>(Oe??[]).map(Re=>Re.id===Ce?{...Re,comment:je}:Re))},[M,r]),ae=v.useCallback(Ce=>{const je=M.find(_e=>_e.id===Ce);B(_e=>(_e??[]).filter(Oe=>Oe.id!==Ce)),b(_e=>{const Oe=new Set(_e);return Oe.delete(Ce),Oe}),p===Ce&&h(null),je?.experimentId&&je?.datasetId&&f.mutate({datasetId:je.datasetId,experimentId:je.experimentId,resultId:je.id,status:null})},[M,f,p]),de=v.useCallback(Ce=>{const je=M.find(_e=>_e.id===Ce);B(_e=>(_e??[]).filter(Oe=>Oe.id!==Ce)),b(_e=>{const Oe=new Set(_e);return Oe.delete(Ce),Oe}),p===Ce&&h(null),je?.experimentId&&je?.datasetId&&f.mutate({datasetId:je.datasetId,experimentId:je.experimentId,resultId:je.id,status:"complete"})},[M,f,p]),Y=v.useMemo(()=>{const Ce=w?d??[]:P;return!w||!m?Ce:m==="__untagged__"?Ce.filter(je=>je.tags.length===0):Ce.filter(je=>je.tags.includes(m))},[w,d,P,m]),ne=w?c:!1,ce=v.useMemo(()=>new Set(Y.map(Ce=>Ce.id)),[Y]),pe=v.useMemo(()=>[...y].filter(Ce=>ce.has(Ce)).length,[y,ce]),le=Y.length>0&&pe===Y.length,ve=pe>0&&!le,ye=v.useCallback(Ce=>{b(je=>{const _e=new Set(je);return _e.has(Ce)?_e.delete(Ce):_e.add(Ce),_e})},[]),Se=v.useCallback(()=>{b(le?new Set:new Set(Y.map(Ce=>Ce.id)))},[le,Y]),Ne=v.useCallback(Ce=>{for(const je of y){const _e=M.find(Oe=>Oe.id===je);_e&&!_e.tags.includes(Ce)&&te(je,[..._e.tags,Ce])}},[M,y,te]),ke=v.useCallback(Ce=>{for(const je of y){const _e=M.find(Oe=>Oe.id===je);_e&&_e.tags.includes(Ce)&&te(je,_e.tags.filter(Oe=>Oe!==Ce))}},[M,y,te]),Ie=v.useCallback(()=>{for(const Ce of y)de(Ce);b(new Set)},[y,de]),ze=v.useCallback(()=>{for(const Ce of y)ae(Ce);b(new Set)},[y,ae]),oe=v.useCallback(()=>{N(""),E(!0)},[]),se=v.useCallback(async()=>{if(!(!I||!$)){_(!0),E(!1);try{const Ce=M.filter(_e=>y.has(_e.id));if(Ce.length===0){_(!1);return}const je=await r.clusterFailures({modelId:`${I}/${$}`,items:Ce.map(_e=>({id:_e.id,input:_e.input,output:_e.output??void 0,error:typeof _e.error=="string"?_e.error:_e.error?String(_e.error):void 0,scores:_e.scores,existingTags:_e.tags.length>0?_e.tags:void 0})),availableTags:G.length>0?G:void 0,prompt:j||void 0});je.proposedTags&&je.proposedTags.length>0&&(V(je.proposedTags.map(_e=>({..._e,accepted:!0}))),L(!0))}catch(Ce){console.error("Analysis failed:",Ce)}finally{_(!1)}}},[I,$,M,y,r,G,j]),re=v.useCallback(()=>{for(const Ce of D){if(!Ce.accepted)continue;const je=M.find(_e=>_e.id===Ce.itemId);if(je){const _e=[...new Set([...je.tags,...Ce.tags])];te(je.id,_e)}}L(!1)},[D,M,te]),he=v.useCallback(Ce=>{h(je=>je===Ce?null:Ce)},[]),xe=v.useMemo(()=>p?Y.find(Ce=>Ce.id===p)??null:null,[p,Y]),Ee=p?Y.findIndex(Ce=>Ce.id===p):-1,Pe=Ee>0?()=>h(Y[Ee-1].id):void 0,Qe=Ee>=0&&Ee<Y.length-1?()=>h(Y[Ee+1].id):void 0,Ze="auto minmax(15rem,1fr) 10rem 8rem 6rem 6rem";return i?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(Gt,{className:"w-6 h-6"})}):o.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[o.jsx(br,{open:C,onOpenChange:E,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Analyze Items"}),o.jsx(Qs,{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(Rt,{className:"text-xs mb-1 block",children:"Provider"}),o.jsx(zy,{value:I,onValueChange:R})]}),o.jsxs("div",{children:[o.jsx(Rt,{className:"text-xs mb-1 block",children:"Model"}),o.jsx(By,{llmId:I,value:$,onValueChange:F})]})]}),o.jsxs(ge,{variant:"ui-xs",className:"text-neutral3",children:[y.size," item",y.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Rt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx(Yl,{value:j,onChange:Ce=>N(Ce.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"text-xs mt-1"})]})]}),o.jsxs(kc,{children:[o.jsx(ue,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),o.jsxs(ue,{onClick:se,disabled:!I||!$||k,children:[k?o.jsx(Gt,{className:"w-4 h-4 mr-1"}):null,"Analyze"]})]})]})}),o.jsx(br,{open:W,onOpenChange:L,children:o.jsxs(xr,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Review Proposed Tags"}),o.jsxs(Qs,{children:[D.filter(Ce=>Ce.accepted).length," of ",D.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:D.map((Ce,je)=>{const _e=M.find(Oe=>Oe.id===Ce.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!Ce.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx($o,{checked:Ce.accepted,onCheckedChange:Oe=>V(Re=>Re.map((qe,Ke)=>Ke===je?{...qe,accepted:!!Oe}:qe))}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 truncate block",children:_e?typeof _e.input=="string"?_e.input.slice(0,100):JSON.stringify(_e.input).slice(0,100):Ce.itemId}),o.jsx("div",{className:"flex gap-1 flex-wrap mt-1.5",children:Ce.tags.map((Oe,Re)=>o.jsx(U8t,{tag:Oe,onRename:qe=>V(Ke=>Ke.map((Ge,Ot)=>Ot===je?{...Ge,tags:Ge.tags.map((yt,nn)=>nn===Re?qe:yt)}:Ge)),onRemove:()=>V(qe=>qe.map((Ke,Ge)=>Ge===je?{...Ke,tags:Ke.tags.filter((Ot,yt)=>yt!==Re)}:Ke))},`${Oe}-${Re}`))}),Ce.reason&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:Ce.reason})]})]})},Ce.itemId)})}),o.jsxs(kc,{children:[o.jsx(ue,{variant:"outline",onClick:()=>L(!1),children:"Cancel"}),o.jsxs(ue,{onClick:re,disabled:D.filter(Ce=>Ce.accepted).length===0,children:["Accept ",D.filter(Ce=>Ce.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:K("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",xe&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid gap-8 content-start w-full overflow-y-auto",children:[o.jsxs("div",{className:"flex items-center justify-between w-full flex-wrap gap-4 gap-x-6",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(ft,{children:[o.jsx(ft.Trigger,{asChild:!0,children:o.jsxs(ue,{variant:"outline",size:"md",children:[o.jsx(vlt,{}),"Filter",X>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:X})]})}),o.jsxs(ft.Content,{align:"start",className:K("min-w-48"),children:[o.jsxs(ft.Sub,{children:[o.jsxs(ft.SubTrigger,{children:["Status",w&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(ft.SubContent,{children:[o.jsx(ft.CheckboxItem,{checked:!w,onCheckedChange:()=>{S(!1),h(null)},onSelect:Ce=>Ce.preventDefault(),children:"Review Queue"}),o.jsx(ft.CheckboxItem,{checked:w,onCheckedChange:()=>{S(!0),h(null)},onSelect:Ce=>Ce.preventDefault(),children:"Completed"})]})]}),o.jsxs(ft.Sub,{children:[o.jsxs(ft.SubTrigger,{children:["Tags",m&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(ft.SubContent,{children:[o.jsx(ft.CheckboxItem,{checked:!m,onCheckedChange:()=>g(null),onSelect:Ce=>Ce.preventDefault(),children:"All"}),Z>0&&o.jsx(ft.CheckboxItem,{checked:m==="__untagged__",onCheckedChange:()=>g(m==="__untagged__"?null:"__untagged__"),onSelect:Ce=>Ce.preventDefault(),children:"Untagged"}),q.length>0&&o.jsx(ft.Separator,{}),q.map(([Ce])=>o.jsx(ft.CheckboxItem,{checked:m===Ce,onCheckedChange:()=>g(m===Ce?null:Ce),onSelect:je=>je.preventDefault(),children:Ce},Ce))]})]}),X>0&&o.jsxs(o.Fragment,{children:[o.jsx(ft.Separator,{}),o.jsxs(ft.Item,{onSelect:()=>{g(null),S(!1),h(null)},children:[o.jsx(vs,{}),"Clear all filters"]})]})]})]}),X>0&&o.jsxs(ue,{variant:"outline",size:"md",onClick:()=>{g(null),S(!1),h(null)},children:[o.jsx(vs,{}),"Reset"]})]}),!w&&y.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(B8t,{selectedCount:y.size,vocabulary:G,onApplyTag:Ne,onRemoveTag:ke,onNewTag:Ce=>Ne(Ce)}),o.jsxs(ft,{children:[o.jsx(ft.Trigger,{asChild:!0,children:o.jsxs(ue,{disabled:k,children:[k?o.jsx(Gt,{className:"w-4 h-4"}):o.jsx(Ue,{size:"sm",children:o.jsx(Na,{})}),"Actions"]})}),o.jsxs(ft.Content,{align:"end",children:[o.jsxs(ft.Item,{onSelect:Ie,children:[o.jsx(Ue,{size:"sm",children:o.jsx(rO,{})}),"Complete"]}),o.jsxs(ft.Item,{onSelect:ze,children:[o.jsx(Ue,{size:"sm",children:o.jsx(Jc,{})}),"Remove"]}),o.jsx(ft.Separator,{}),o.jsxs(ft.Item,{onSelect:oe,children:[o.jsx(Ue,{size:"sm",children:o.jsx(bg,{})}),"Analyze"]})]})]})]})]}),ne?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(Gt,{className:"w-6 h-6"})}):Y.length===0?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsxs("div",{className:"text-center px-8",children:[o.jsx(ge,{variant:"ui-sm",className:"text-neutral3 block",children:w?"No completed reviews yet":"No items to review"}),o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 mt-2 block",children:w?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})]})}):o.jsxs(me,{columns:Ze,className:"min-w-0",children:[o.jsxs(me.Top,{hasLeadingCell:!0,children:[w?o.jsx(me.TopCell,{children:" "}):o.jsx(me.TopSelectCell,{checked:le?!0:ve?"indeterminate":!1,onToggle:()=>Se(),"aria-label":"Select all"}),o.jsxs(me.TopCells,{colStart:2,children:[o.jsx(me.TopCell,{children:"Input"}),o.jsx(me.TopCell,{children:"Comment"}),o.jsx(me.TopCell,{children:"Tags"}),o.jsx(me.TopCell,{children:"Rating"}),o.jsx(me.TopCell,{children:"Scores"})]})]}),Y.map(Ce=>{const je=Ce.scores?Object.entries(Ce.scores):[],_e=p===Ce.id,Oe=o.jsxs(o.Fragment,{children:[o.jsx(me.Cell,{height:"compact",className:"min-w-0 text-neutral4",children:o.jsx("span",{className:"block truncate",children:_rs(Ce.input,200)})}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:Ce.comment?o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 truncate",children:Ce.comment}):o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:Ce.tags.length>0?o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 truncate",children:Ce.tags.join(", ")}):o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(me.Cell,{height:"compact",children:[Ce.rating==="positive"&&o.jsx(Ue,{size:"sm",className:"text-positive1",children:o.jsx(Jye,{})}),Ce.rating==="negative"&&o.jsx(Ue,{size:"sm",className:"text-negative1",children:o.jsx(Kye,{})}),!Ce.rating&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(me.Cell,{height:"compact",children:je.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Ue,{size:"sm",className:"text-neutral3",children:o.jsx(Jh,{})}),o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 font-mono",children:je[0][1].toFixed(2)}),je.length>1&&o.jsxs(fn,{variant:"default",children:["+",je.length-1]})]}):o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(me.RowWrapper,{children:[w?o.jsx(me.Cell,{height:"compact",className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":Ce.error?"Error":"Success",title:Ce.error?"Error":"Success",className:K("w-2 h-2 rounded-full",Ce.error?"bg-red-700":"bg-green-600")})}):o.jsx(me.SelectCell,{checked:y.has(Ce.id),onToggle:()=>ye(Ce.id),"aria-label":`Select item ${Ce.id}`}),o.jsx(me.RowButton,{flushLeft:!0,colStart:2,featured:_e,onClick:()=>he(Ce.id),children:Oe})]},Ce.id)})]})]}),xe&&o.jsx(z8t,{item:xe,isCompleted:w,tagVocabulary:G,onRate:Ce=>J(xe.id,Ce),onSetTags:Ce=>{te(xe.id,Ce);for(const je of Ce)G.includes(je)||U(je)},onComment:Ce=>ee(xe.id,Ce),onRemove:()=>ae(xe.id),onComplete:w?void 0:()=>de(xe.id),onPrevious:Pe,onNext:Qe,onClose:()=>h(null)})]})]})}function Crs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n}){const{navigate:r}=yn(),[s,a]=ji(),{tab:i,activeVersion:l,handleTabChange:c}=bTe(s,a),[u,d]=v.useState(!1),[f,p]=v.useState(!1),[h,m]=v.useState(!1),[g,y]=v.useState([]),[b,w]=v.useState(!1),[S,k]=v.useState([]),[_,C]=v.useState(!1),[E,j]=v.useState([]),[N,I]=v.useState(0),[R,$]=v.useState(null),[F,D]=v.useState(""),[V]=Zwe(F,300),{data:W}=Ux(e),{data:L=[],total:z,isLoading:B,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:U}=C1(e,V||void 0,l),{total:P}=C1(e,void 0,l),[q,Z]=v.useState({}),{data:X,isLoading:te}=GM(e,void 0,q),{data:J}=GM(e),{deleteItems:ee}=_i(),ae=X?.experiments??[],de=J?.experiments??[],Y=Hns({hasSearchQuery:!!V,filteredItemsLength:L.length,unfilteredItemsTotal:P,itemsTotal:z}),{data:ne}=xTe(e),ce=ne?.length??0,pe=re=>{$(re)},le=()=>{$(null)},ve=re=>{y(re),m(!0)},ye=re=>{k(re),w(!0)},Se=re=>{w(re),re||(k([]),I(he=>he+1))},Ne=re=>{r(`/datasets/${e}/items?items=${re.join(",")}`)},ke=re=>{r(`/datasets/${e}/versions?ids=${re.join(",")}`)},Ie=re=>{j(re),C(!0)},ze=async()=>{await ee.mutateAsync({datasetId:e,itemIds:E}),De.success(`Deleted ${E.length} items`),C(!1),j([]),I(re=>re+1)},oe=re=>{m(!1),y([]),I(he=>he+1),n?.(re)},se=re=>{m(re),re||(y([]),I(he=>he+1))};return o.jsxs(o.Fragment,{children:[o.jsxs(tu,{defaultTab:"items",value:i,onValueChange:c,className:"grid grid-rows-[auto_1fr] h-full",children:[o.jsxs(eu,{children:[o.jsxs(Vr,{value:"items",children:["Items ",o.jsx(Xs,{color:"gray",children:Y})]}),o.jsxs(Vr,{value:"experiments",children:["Experiments",o.jsx(Xs,{color:"gray",children:ae.length})]}),o.jsxs(Vr,{value:"review",children:["Review",ce>0&&o.jsx(Xs,{color:"orange",children:ce})]})]}),o.jsx(ps,{value:"items",className:"grid overflow-auto mt-5 pb-0",children:o.jsx(brs,{datasetId:e,items:L,isLoading:B,featuredItemId:R,onItemSelect:pe,onItemClose:le,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>p(!0),onBulkDeleteClick:Ie,onCreateDatasetClick:ve,onAddToDatasetClick:ye,onCompareItemsClick:Ne,datasetName:W?.name,clearSelectionTrigger:N,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:U,searchQuery:F,activeSearchQuery:V,onSearchChange:D,currentDatasetVersion:W?.version,onCompareVersionsClick:ke})}),o.jsx(ps,{value:"experiments",className:"grid overflow-auto mt-5 pb-0",children:o.jsx(lrs,{experiments:ae,allExperiments:de,isLoading:te,datasetId:e,filters:q,onFiltersChange:Z})}),o.jsx(ps,{value:"review",className:"overflow-auto mt-2 pb-0",children:o.jsx(r9t,{datasetId:e})})]}),o.jsx(ers,{datasetId:e,open:u,onOpenChange:d}),o.jsx(krs,{datasetId:e,open:f,onOpenChange:p}),o.jsx(Pns,{open:h,onOpenChange:se,items:g,onSuccess:oe}),o.jsx($ns,{open:b,onOpenChange:Se,items:S,currentDatasetId:e}),o.jsx(Tt,{open:_,onOpenChange:C,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Items"}),o.jsxs(Tt.Description,{children:["Are you sure you want to delete ",E.length," item",E.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(Tt.Footer,{children:[o.jsx(Tt.Cancel,{children:"Cancel"}),o.jsx(Tt.Action,{onClick:ze,children:ee.isPending?"Deleting...":"Delete"})]})]})})]})}function Ers(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 rse({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-xs text-destructive",children:[o.jsxs("code",{className:"bg-destructive/10 px-1 rounded",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function jrs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=v.useState("{}"),[i,l]=v.useState(""),[c,u]=v.useState(""),[d,f]=v.useState(""),[p,h]=v.useState(""),[m,g]=v.useState(null),{addItem:y}=_i(),b=async C=>{C.preventDefault();let E;try{E=JSON.parse(s)}catch{De.error("Input must be valid JSON");return}let j;if(i.trim())try{j=JSON.parse(i)}catch{De.error("Ground Truth must be valid JSON");return}let N;if(c.trim())try{N=JSON.parse(c)}catch{De.error("Expected Trajectory must be valid JSON");return}let I;if(d.trim())try{const $=JSON.parse(d);if(!Array.isArray($)){De.error("Tool Mocks must be a JSON array");return}I=$}catch{De.error("Tool Mocks must be valid JSON");return}let R;if(p.trim())try{R=JSON.parse(p)}catch{De.error("Request Context must be valid JSON");return}try{await y.mutateAsync({datasetId:e,input:E,groundTruth:j,expectedTrajectory:N,toolMocks:I,requestContext:R}),De.success("Item added successfully"),g(null),a("{}"),l(""),u(""),f(""),h(""),n(!1),r?.()}catch($){const F=Ers($);F?g(F):De.error(`Failed to add item: ${$ instanceof Error?$.message:"Unknown error"}`)}},w=C=>{a(C),m?.field==="input"&&g(null)},S=C=>{l(C),m?.field==="groundTruth"&&g(null)},k=C=>{f(C),m?.field==="toolMocks"&&g(null)},_=()=>{a("{}"),l(""),u(""),f(""),h(""),g(null),n(!1)};return o.jsx(br,{open:t,onOpenChange:n,children:o.jsxs(xr,{className:"max-w-lg",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Add Item"})}),o.jsx(Ar,{children:o.jsxs("form",{onSubmit:b,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Qr,{value:s,onChange:w,showCopyButton:!1,className:"min-h-[120px]"}),m?.field==="input"&&o.jsx(rse,{field:"input",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Qr,{value:i,onChange:S,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="groundTruth"&&o.jsx(rse,{field:"groundTruth",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Qr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Qr,{value:d,onChange:k,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="toolMocks"&&o.jsx(rse,{field:"toolMocks",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Qr,{value:p,onChange:h,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ue,{type:"button",onClick:_,children:"Cancel"}),o.jsx(ue,{type:"submit",variant:"primary",disabled:y.isPending,children:y.isPending?"Adding...":"Add Item"})]})]})})]})})}function Trs({item:e}){return o.jsx(ua,{withMargins:!1,children:o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{size:"smaller",children:[o.jsx(dN,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(ya,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(ua.Description,{children:[o.jsxs(jl,{children:[o.jsx(llt,{})," Created ",er(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(jl,{children:[o.jsx(i_,{})," Version v",e.datasetVersion]})]})]})})}function wTe({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(Ywe,{children:[o.jsx(Ps.CodeSection,{title:"Input",icon:o.jsx(aO,{}),codeStr:t}),o.jsx(Ps.CodeSection,{title:"Ground Truth",icon:o.jsx(hg,{}),codeStr:n}),s&&o.jsx(Ps.CodeSection,{title:"Expected Trajectory",icon:o.jsx(Gye,{}),codeStr:s}),o.jsx(Ps.CodeSection,{title:"Metadata",icon:o.jsx(hN,{}),codeStr:r})]})}function Nrs({selectedScorers:e,setSelectedScorers:t,disabled:n=!1,container:r}){const{data:s,isLoading:a}=eh(),i=v.useMemo(()=>s?Object.entries(s).map(([l,c])=>({value:l,label:c.scorer?.config?.name||l,description:c.scorer?.config?.description||""})):[],[s]);return o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Rt,{children:"Scorers (Optional)"}),o.jsx(Xl,{multiple:!0,options:i,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||a,container:r})]})}const Irs=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Ars({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=km(),{data:l,isLoading:c}=Uy(),{data:u,isLoading:d}=eh(),f=e==="agent"?Object.entries(a??{}).map(([g,y])=>({value:g,label:y.name??g})):e==="workflow"?Object.entries(l??{}).map(([g,y])=>({value:g,label:y.name??g})):e==="scorer"?Object.entries(u??{}).map(([g,y])=>({value:g,label:y.scorer?.config?.name??g})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=g=>{t(g),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Rt,{children:"Target Type"}),o.jsx(Xl,{options:Irs,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(Rt,{children:m}),o.jsx(Xl,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}function Rrs({requestContextSchema:e,onChange:t}){const n=v.useMemo(()=>{try{return um(lm(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(Rt,{children:"Request Context"}),o.jsx(HD,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-sm text-destructive",children:"Failed to parse request context schema"})}function Prs({datasetId:e,version:t,requestContextSchema:n,open:r,onOpenChange:s,onSuccess:a}){const i=v.useRef(null),[l,c]=v.useState(""),[u,d]=v.useState(""),[f,p]=v.useState([]),[h,m]=v.useState({}),[g,y]=v.useState(""),{triggerExperiment:b}=_i(),w=!!(n&&Object.keys(n).length>0),S=l&&u,k=b.isPending,_=()=>{c(""),d(""),p([]),m({}),y("")},C=()=>{if(w){const N=Object.entries(h).filter(([,I])=>I!==void 0&&I!=="");return N.length>0?Object.fromEntries(N):void 0}if(g.trim()){let N;try{N=JSON.parse(g)}catch{throw new Error("Request Context must be valid JSON")}if(!N||typeof N!="object"||Array.isArray(N))throw new Error("Request Context must be a JSON object");return N}},E=async()=>{if(!S)return;let N;try{N=C()}catch(I){const R=I instanceof Error?I.message:"Request Context must be valid JSON";ju.error(R);return}try{const I=await b.mutateAsync({datasetId:e,targetType:l,targetId:u,scorerIds:f.length>0?f:void 0,version:t,requestContext:N});ju.success("Experiment triggered successfully"),s(!1),a?.(I.experimentId),_()}catch(I){const R=I instanceof Error?I.message:"Failed to trigger experiment";ju.error(R)}},j=()=>{k||(s(!1),_())};return o.jsx(br,{open:r,onOpenChange:j,children:o.jsxs(xr,{ref:i,children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Run Experiment"}),o.jsx(Qs,{children:t?`Execute items from ${er(new Date(t),"MMM d, yyyy")} version against a target.`:"Execute all items in this dataset against a target."})]}),o.jsxs(Ar,{className:"grid gap-6",children:[o.jsx(Ars,{targetType:l,setTargetType:c,targetId:u,setTargetId:d,container:i}),l&&l!=="scorer"&&o.jsx(Nrs,{selectedScorers:f,setSelectedScorers:p,disabled:k,container:i}),w?o.jsx(Rrs,{requestContextSchema:n,onChange:m}):o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{children:"Request Context (JSON, optional)"}),o.jsx(Qr,{value:g,onChange:y,showCopyButton:!1,className:"min-h-[80px]"})]})]}),o.jsxs(kc,{className:"px-6 pt-4",children:[o.jsx(ue,{onClick:j,disabled:k,children:"Cancel"}),o.jsx(ue,{variant:"primary",onClick:E,disabled:!S||k,children:k?o.jsxs(o.Fragment,{children:[o.jsx(Gt,{className:"w-4 h-4"}),"Running..."]}):"Run"})]})]})})}const $rs=e=>{const t=We();return wt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},enabled:!!e})};function sse(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function Mrs({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(bn.SectionHeading,{icon:o.jsx(tm,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(In,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(In.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: ",sse(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>sse(i.args)).join(", ")]})]})}),o.jsx("div",{className:"rounded border border-border1 divide-y divide-border1 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:"font-mono text-neutral4",children:i.toolName}),o.jsx("span",{className:"ml-2 font-mono text-xs text-neutral3",children:sse(i.args)})]}),o.jsx("span",{className:`shrink-0 text-xs px-2 py-0.5 rounded ${Drs(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function Drs(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 Lrs({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d,onCollapsedChange:f}){const[p,h]=v.useState(!1),m=d??p,g=f??h,y=!!e?.error,b=Z8(e?.input),w=Z8(e?.output),S=Z8(e?.groundTruth),k=u&&e.status!=="needs-review"&&e.status!=="complete",_=Array.isArray(e.tags)?e.tags:[];return o.jsxs(bn,{collapsed:m,children:[o.jsxs(bn.Header,{children:[o.jsxs(bn.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs($r,{className:"ml-auto shrink-0",children:[f&&o.jsx(ue,{size:"md",tooltip:m?"Expand panel":"Collapse panel",onClick:()=>g(!m),children:m?o.jsx(flt,{}):o.jsx(dlt,{})}),o.jsx(bn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),o.jsxs(ue,{size:"md",onClick:a,disabled:!e.traceId,children:[o.jsx(wOe,{}),"Trace"]}),o.jsx(bn.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!m&&o.jsxs(bn.Content,{children:[o.jsxs("div",{className:"grid gap-4 mb-6",children:[o.jsxs(zt,{children:[o.jsx(zt.Key,{children:"Item Id"}),o.jsx(zt.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(zt.Key,{children:"Created"}),o.jsx(zt.Value,{children:er(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),y&&o.jsx(In,{variant:"destructive",title:"Error",children:o.jsx(In.Message,{children:Z8(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(me,{columns:"1fr 1fr",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Scorer"}),o.jsx(me.TopCell,{children:"Score"})]}),t.map(C=>o.jsxs(me.RowButton,{featured:c===C.id,onClick:()=>l?.(C.id),children:[o.jsx(me.Cell,{height:"compact",children:C.scorerId}),o.jsx(me.MonoCell,{children:C.score.toFixed(3)})]},C.id))]}),e.toolMockReport&&o.jsx(Mrs,{report:e.toolMockReport}),(e.status||_.length>0||k)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(bn.SectionHeading,{icon:o.jsx(hN,{}),className:"mb-2",children:"Review"}),(e.status||_.length>0)&&o.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.status&&o.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${e.status==="needs-review"?"bg-orange-500/10 text-orange-400":e.status==="complete"?"bg-accent1/10 text-accent1":"bg-neutral3/10 text-neutral4"}`,children:e.status}),_.map(C=>o.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-surface4 text-neutral4",children:C},C))]}),k&&o.jsx("div",{children:o.jsxs(ue,{size:"sm",onClick:()=>u(e.id),children:[o.jsx(GU,{}),"Flag for Review"]})}),e.status==="needs-review"&&i&&o.jsx("div",{children:o.jsxs(ue,{size:"sm",onClick:i,children:[o.jsx(Pa,{}),"Review"]})})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(bn.CodeSection,{title:"Input",icon:o.jsx(dN,{}),codeStr:b}),o.jsx(bn.CodeSection,{title:"Output",icon:o.jsx(hg,{}),codeStr:w}),o.jsx(bn.CodeSection,{title:"Ground Truth",icon:o.jsx(Xye,{}),codeStr:S})]})]})]})}function Z8(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Frs({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:a,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,selectedIds:d,onToggleSelect:f}){const p=!!(d&&f),h=[p?"auto":"",...s.map(g=>g.size)].filter(Boolean).join(" "),m=s.some(g=>g.name==="input");return t?o.jsx(el,{columns:h}):o.jsxs(me,{columns:h,className:"min-w-0",children:[o.jsxs(me.Top,{hasLeadingCell:p,children:[p&&o.jsx(me.TopCell,{children:" "}),p?o.jsx(me.TopCells,{colStart:2,children:s.map(g=>o.jsx(me.TopCell,{children:g.label},g.name))}):s.map(g=>o.jsx(me.TopCell,{children:g.label},g.name))]}),e.length===0?o.jsx(me.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map(g=>{const y=!!g.error,b=g.id===n,w=o.jsxs(o.Fragment,{children:[o.jsx(me.IdCell,{id:g.itemId}),o.jsx(me.Cell,{height:"compact",children:o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsx("div",{className:"flex items-center justify-center w-10 relative bg-transparent h-full",children:o.jsx("div",{role:"img","aria-label":y?"Error":"Success",className:K("w-2 h-2 rounded-full",y?"bg-red-700":"bg-green-600")})})}),o.jsx(Bn,{children:y?"Error":"Success"})]})}),m&&o.jsx(me.MonoCell,{children:Brs(zrs(g.input),200)}),i?.map(S=>{const _=a?.[g.itemId]?.find(C=>C.scorerId===S);return o.jsx(me.Cell,{height:"compact",className:"font-mono text-neutral3 text-ui-smd",children:_!=null?_.score.toFixed(3):"-"},S)})]});return p?o.jsxs(me.RowWrapper,{children:[o.jsx(me.SelectCell,{checked:d.has(g.id),onToggle:()=>f(g.id),"aria-label":`Select result ${g.itemId}`}),o.jsx(me.RowButton,{flushLeft:!0,colStart:2,featured:b,onClick:()=>r(g.id),children:w})]},g.id):o.jsx(me.RowButton,{featured:b,onClick:()=>r(g.id),children:w},g.id)}),o.jsx(me.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function zrs(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Brs(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function Urs(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function qrs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i}){const[l,c]=v.useState(!1),u=a??l,d=i??c,f=Urs(e),p=f?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(bn,{collapsed:u,children:[o.jsxs(bn.Header,{children:[o.jsxs(bn.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs($r,{className:"ml-auto shrink-0",children:[i&&o.jsx(ue,{size:"md",tooltip:u?"Expand panel":"Collapse panel",onClick:()=>d(!u),children:u?o.jsx(flt,{}):o.jsx(dlt,{})}),(n||t)&&o.jsx(bn.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&o.jsxs(ue,{size:"md",onClick:s,disabled:!e.traceId,children:[o.jsx(wOe,{}),"Trace"]}),o.jsx(bn.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!u&&o.jsx(bn.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(bn.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(Jh,{}),codeStr:e.reason||p,simplified:!0}),!f&&o.jsxs(o.Fragment,{children:[o.jsx(bn.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(bh,{}),codeStr:e.preprocessPrompt||p,simplified:!0}),o.jsx(bn.CodeSection,{title:"Analyze Prompt",icon:o.jsx(bh,{}),codeStr:e.analyzePrompt||p,simplified:!0}),o.jsx(bn.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(bh,{}),codeStr:e.generateScorePrompt||p,simplified:!0}),o.jsx(bn.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(bh,{}),codeStr:e.generateReasonPrompt||p,simplified:!0})]})]})})]})}const $Qe=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"avg",label:"Avg Score",size:"1fr"},{name:"count",label:"Items Scored",size:"1fr"}];function Vrs({scoresByItemId:e,experimentStatus:t}){const n=v.useMemo(()=>{if(!e)return[];const r={};for(const s of Object.values(e))for(const a of s)r[a.scorerId]||(r[a.scorerId]={sum:0,count:0}),r[a.scorerId].sum+=a.score,r[a.scorerId].count++;return Object.entries(r).map(([s,{sum:a,count:i}])=>({scorerId:s,avg:a/i,count:i})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))},[e]);if(n.length===0){const r=t==="running"||t==="pending",s=e!==void 0;let a,i;return r?(a="Experiment in progress",i="Summary metrics will appear here once the experiment completes."):s?(a="No scorers configured",i="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(a="Loading scores",i="Fetching scorer results…"),o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(Lr,{iconSlot:o.jsx(Jh,{className:"w-8 h-8 text-neutral3"}),titleSlot:a,descriptionSlot:i})})}return o.jsxs(gn,{children:[o.jsxs(gn.Header,{columns:$Qe,children:[o.jsx(gn.HeaderCol,{children:"Scorer"}),o.jsx(gn.HeaderCol,{children:"Avg Score"}),o.jsx(gn.HeaderCol,{children:"Items Scored"})]}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:n.map(({scorerId:r,avg:s,count:a})=>o.jsxs(gn.Row,{columns:$Qe,children:[o.jsx(gn.TextCell,{children:r}),o.jsx(gn.TextCell,{className:"font-mono",children:s.toFixed(3)}),o.jsx(gn.TextCell,{className:"font-mono",children:a})]},r))})})]})}function s9t({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const[c,u]=v.useState(null),[d,f]=v.useState(null),[p,h]=v.useState(void 0),[m,g]=v.useState(null),[y,b]=v.useState(new Set),[w,S]=v.useState(!1),[k,_]=v.useState(!1),[C,E]=v.useState(!1),[j,N]=v.useState(!1),{updateExperimentResult:I}=_i(),R=v.useCallback(se=>{b(re=>{const he=new Set(re);return he.has(se)?he.delete(se):he.add(se),he})},[]),$=v.useCallback(()=>b(new Set),[]),F=v.useCallback(()=>{const se=r.filter(re=>!!re.error).map(re=>re.id);b(new Set(se))},[r]),D=v.useCallback(async se=>{if(w||se.length===0)return;S(!0);let re=0;const he=new Set;try{for(const xe of se)try{await I.mutateAsync({datasetId:t,experimentId:e,resultId:xe,status:"needs-review"}),re++,he.add(xe)}catch{}}finally{S(!1)}he.size>0&&b(xe=>{const Ee=new Set(xe);for(const Pe of he)Ee.delete(Pe);return Ee}),re>0&&De(`${re} result${re>1?"s":""} flagged for review`)},[t,e,w,I]),V=r.find(se=>se.id===c)??null,[W,L]=v.useState("summary"),[z,B]=v.useState(null),M=se=>{L(se),se!=="reviews"&&B(null)},{data:G}=xTe(t),U=(G??[]).filter(se=>se.experimentId===e).length,{data:P}=M8t(e,n),q=v.useMemo(()=>{if(!P)return[];const se=new Set;for(const re of Object.values(P))for(const he of re)se.add(he.scorerId);return[...se].sort()},[P]),Z=se=>{u(se),f(null),h(void 0),g(null)},X=se=>{Z(se===c?null:se)},te=()=>{Z(null)},J=()=>{if(!V)return;const se=r.findIndex(re=>re.id===V.id);if(se>=0&&se<r.length-1)return()=>Z(r[se+1].id)},ee=()=>{if(!V)return;const se=r.findIndex(re=>re.id===V.id);if(se>0)return()=>Z(r[se-1].id)},ae=V?P?.[V.itemId]:void 0,de=ae?.find(se=>se.id===m)??null,Y=se=>{g(se===m?null:se),f(null),h(void 0)},ne=()=>{if(!m||!ae)return;const se=ae.findIndex(re=>re.id===m);if(se>=0&&se<ae.length-1)return()=>g(ae[se+1].id)},ce=()=>{if(!m||!ae)return;const se=ae.findIndex(re=>re.id===m);if(se>0)return()=>g(ae[se-1].id)},{data:pe,isLoading:le}=$rs(d),ve=pe?.spans,{data:ye,isLoading:Se}=pI(d,p),Ne=ye?.span,{handlePreviousSpan:ke,handleNextSpan:Ie}=KH(ve,p??null,h),ze=(()=>{const se=[],re=!!de,he=!!d;return se.push(k?"auto":re||he?"2fr":"1fr"),re&&se.push(j?"auto":"3fr"),he&&se.push(C?"auto":"3fr"),he&&p&&se.push("3fr"),se.join(" ")})(),oe=v.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"status",label:"Status",size:"5rem"},{name:"input",label:"Input",size:"minmax(15rem,1fr)"},...q.map(se=>({name:se,label:se,size:"12rem"}))],[q]);return o.jsxs(tu,{defaultTab:"summary",value:W,onValueChange:M,className:"grid grid-rows-[auto_1fr] h-full overflow-hidden",children:[o.jsxs(eu,{children:[o.jsx(Vr,{value:"summary",children:"Summary"}),o.jsx(Vr,{value:"results",children:"Results"}),o.jsxs(Vr,{value:"reviews",children:["Reviews",U>0&&o.jsx(Xs,{color:"orange",children:U})]})]}),o.jsx(ps,{value:"summary",className:"overflow-y-auto mt-5",children:o.jsx(Vrs,{scoresByItemId:P,experimentStatus:n})}),o.jsx(ps,{value:"reviews",className:"overflow-auto mt-2 pb-0",children:o.jsx(r9t,{datasetId:t,experimentId:e,featuredItemId:z})}),o.jsxs(ps,{value:"results",className:"grid grid-rows-[auto_1fr] overflow-hidden mt-2",children:[o.jsxs("div",{className:"mb-4",children:[y.size>0&&o.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-surface3",children:[o.jsxs(ge,{variant:"ui-xs",className:"text-neutral5 font-medium",children:[y.size," selected"]}),o.jsx("div",{className:"flex-1"}),o.jsxs(ue,{variant:"outline",size:"sm",disabled:w,onClick:()=>D([...y]),children:[o.jsx(Ue,{size:"sm",children:o.jsx(GU,{})}),"Flag for Review"]}),o.jsx(ue,{variant:"ghost",size:"sm",onClick:$,children:"Clear"})]}),r.length>0&&y.size===0&&!s&&o.jsx("div",{className:"flex items-center gap-2 px-4 py-2",children:o.jsx(ue,{variant:"ghost",size:"sm",onClick:F,children:"Select loaded failures"})})]}),o.jsxs("div",{className:K("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",V&&"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"flex overflow-y-auto w-full",children:o.jsx("div",{className:"grid gap-8 content-start w-full overflow-y-auto",children:o.jsx(Frs,{results:r,isLoading:s,featuredResultId:c,onResultClick:X,columns:oe,scoresByItemId:P,scorerIds:q,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:y,onToggleSelect:R})})}),V&&o.jsxs("div",{className:"grid gap-4 max-h-full min-h-0 overflow-auto content-start",style:{gridTemplateRows:ze},children:[o.jsx(Lrs,{result:V,scores:ae,onPrevious:ee(),onNext:J(),onClose:te,onScoreClick:Y,featuredScoreId:m,onShowTrace:()=>{V.traceId&&(f(V.traceId),h(void 0),g(null),_(!0),E(!1))},onOpenInReview:()=>{B(V.id),L("reviews")},onFlagForReview:se=>D([se]),collapsed:k,onCollapsedChange:_}),de&&o.jsx(qrs,{score:de,onNext:ne(),onPrevious:ce(),onClose:()=>g(null),onShowTrace:()=>{de.traceId&&(f(de.traceId),h(void 0),_(!0),N(!0),E(!1))},collapsed:j,onCollapsedChange:N}),d&&o.jsxs(o.Fragment,{children:[o.jsx(TOe,{traceId:d,spans:ve,isLoading:le,onClose:()=>{f(null),h(void 0),_(!1),N(!1)},onSpanSelect:h,initialSpanId:p??null,placement:"traces-list",showUnavailableFeaturesMsg:!1,collapsed:C,onCollapsedChange:E,LinkComponent:R3,traceHref:`/traces/${d}`}),p&&o.jsx(YH,{traceId:d,spanId:p,span:Ne,isLoading:Se,onPrevious:ke,onNext:Ie,onClose:()=>h(void 0)})]})]})]})]})]})}const Hrs={pending:o.jsx(sO,{}),running:o.jsx(Fde,{}),completed:o.jsx(Js,{}),failed:o.jsx(vs,{})};function Wrs({experiment:e,className:t}){const n=e.status,r=e.totalItems-e.succeededCount-e.failedCount;return o.jsxs("div",{className:K("grid justify-items-end gap-3",t),children:[o.jsxs("div",{className:"flex p-1 px-3 text-ui-lg capitalize text-neutral4 gap-2 items-center bg-surface5 rounded-lg ",children:[o.jsx("span",{className:K("w-5 h-5 flex items-center justify-center rounded-full text-black","[&>svg]:w-4 [&>svg]:h-4",{"bg-green-700":n==="completed","bg-red-700":n==="failed","bg-cyan-600":n==="running","bg-yellow-600":n==="pending"}),children:Hrs[n]}),e.status]}),o.jsxs("div",{className:K("flex items-center gap-3 text-neutral3 text-ui-md ","[&>span]:flex [&>span]:gap-1 [&>span]:items-center ","[&_b]:text-neutral4 [&_b]:font-semibold"),children:[o.jsxs("span",{children:["Total: ",o.jsx("b",{children:e.totalItems})]}),o.jsxs("span",{children:["Succeeded: ",o.jsx("b",{children:e.succeededCount})]}),o.jsxs("span",{children:["Failed: ",o.jsx("b",{children:e.failedCount})]}),(n==="pending"||n==="running")&&o.jsxs("span",{children:["Pending: ",o.jsx("b",{children:r})]})]})]})}function Zrs({onPrevious:e,onNext:t,previousAriaLabel:n="Previous",nextAriaLabel:r="Next"}){return o.jsxs($r,{spacing:"close",children:[o.jsxs(ue,{onClick:e,disabled:!e,"aria-label":n,children:[o.jsx($q,{})," Prev"]}),o.jsxs(ue,{onClick:t,disabled:!t,"aria-label":r,children:["Next",o.jsx(Rq,{})]})]})}function STe({delta:e}){const t=e>0?o.jsx(Xs,{size:"small",color:"green",intensity:"muted",children:o.jsx(i3,{})}):e<0?o.jsx(Xs,{size:"small",color:"red",intensity:"muted",children:o.jsx(Won,{})}):null;return o.jsxs("span",{className:K("font-mono text-sm text-neutral4 min-w-20"),children:[o.jsx("span",{className:"w-3 inline-block",children:e>0?"+ ":e<0?"- ":""}),Math.abs(e).toFixed(2)," ",t]})}function G8(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Grs({item:e,baselineId:t,contenderId:n,baselineVersion:r,contenderVersion:s,onPrevious:a,onNext:i,onClose:l}){const c=e.results[t],u=e.results[n],d=!!(c&&u),f=new Set;if(c)for(const h of Object.keys(c.scores))f.add(h);if(u)for(const h of Object.keys(u.scores))f.add(h);const p=[...f].sort();return o.jsxs(Gr,{withLeftSeparator:!0,children:[o.jsxs(Gr.Toolbar,{children:[o.jsx(Zrs,{onPrevious:a,onNext:i,previousAriaLabel:"Previous comparison item",nextAriaLabel:"Next comparison item"}),o.jsx($r,{children:o.jsx(ue,{onClick:l,"aria-label":"Close comparison detail panel",children:o.jsx(vs,{})})})]}),o.jsxs(Gr.Content,{className:"pb-6",children:[o.jsx(ua,{withMargins:!1,children:o.jsx(ua.Column,{children:o.jsxs(ua.Title,{size:"smaller",children:[o.jsx(dN,{})," ",e.itemId]})})}),d?o.jsx(o.Fragment,{children:o.jsxs(Ywe,{children:[p.length>0&&o.jsxs("div",{className:"grid gap-3",children:[o.jsx("h4",{className:"text-sm font-medium text-neutral5",children:"Scores"}),o.jsx("div",{className:"grid gap-2",children:p.map(h=>{const m=c?.scores[h]??null,g=u?.scores[h]??null,y=m!=null&&g!=null?g-m:null;return o.jsxs("div",{className:"flex items-center justify-between gap-4 px-3 py-2 rounded-lg bg-surface2",children:[o.jsx("span",{className:"text-sm text-neutral5 font-medium",children:h}),o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("span",{className:"text-sm text-neutral3",children:[m!=null?m.toFixed(3):"-"," →"," ",g!=null?g.toFixed(3):"-"]}),y!=null&&o.jsx(STe,{delta:y})]})]},h)})})]}),o.jsx(Ps.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(Xs,{color:"purple",children:"Baseline "})," Experiment Output"]}),icon:o.jsx(hg,{}),codeStr:G8(c?.output)}),o.jsx(Ps.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(Xs,{color:"cyan",children:"Contender "})," Experiment Output"]}),icon:o.jsx(hg,{}),codeStr:G8(u?.output)}),o.jsx(Ps.CodeSection,{title:"Item Input",icon:o.jsx(aO,{}),codeStr:G8(e.input)}),o.jsx(Ps.CodeSection,{title:"Item Ground Truth",icon:o.jsx(Xye,{}),codeStr:G8(e.groundTruth)})]})}):o.jsx(In,{variant:"warning",title:"Comparison not available",children:o.jsx(In.Message,{children:(()=>{const h=c?"Contender":"Baseline",m=c?s:r;return o.jsxs(o.Fragment,{children:["The ",h," experiment was run against dataset",m!=null?` v. ${m}`:"",", which does not contain this item."]})})()})})]})]})}function Qrs({items:e,baselineId:t,contenderId:n,scorerIds:r,featuredItemId:s,columns:a,onItemClick:i}){return o.jsx(Gr,{children:o.jsxs(gn,{children:[o.jsxs(gn.Header,{columns:a,children:[o.jsx(gn.HeaderCol,{children:"Item ID"}),!s&&r.map(l=>o.jsx(gn.HeaderCol,{className:"flex justify-center",children:l},l))]}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:e.map(l=>{const c=l.results[t],u=l.results[n],d=!!(c&&u);return o.jsx(gn.Row,{children:o.jsxs(gn.RowButton,{item:{id:l.itemId},columns:a,isFeatured:s===l.itemId,onClick:i,children:[o.jsx(gn.IdCell,{id:l.itemId,className:d?"":"text-neutral1"}),!s&&o.jsx(o.Fragment,{children:r.map(f=>{const p=c?.scores[f]??null,h=u?.scores[f]??null,m=p!=null&&h!=null?h-p:null;return o.jsx(gn.Cell,{className:"flex items-center gap-5 justify-center font-mono",children:m!=null?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"flex items-center text-neutral2 min-w-24",children:[p?.toFixed(2)," → ",h?.toFixed(2)]}),o.jsx(STe,{delta:m})]}):o.jsx("span",{className:"text-neutral1",children:"-"})},f)})})]})},l.itemId)})})})]})})}const Yrs={baseline:{label:"Baseline",color:"purple",customStyle:"items-end justify-items-end [&>div]:justify-end border-r-0 rounded-r-none"},contender:{label:"Contender",color:"cyan",customStyle:"items-start justify-items-start [&>div]:justify-start border-l-0 rounded-l-none"}};function MQe({datasetId:e,experiment:t,type:n}){const{Link:r}=yn(),{label:s,color:a,customStyle:i}=Yrs[n];if(!t)return null;const l=t.createdAt?new Date(t.createdAt):null;return o.jsxs("div",{className:`grid border-2 border-border1 rounded-lg p-5 gap-3 ${i}`,children:[o.jsxs("div",{className:"flex items-center gap-3 w-full overflow-clip",children:[n==="contender"&&o.jsxs(Xs,{size:"small",color:a,children:[s,o.jsx(hm,{})]}),o.jsx(ue,{as:r,href:`/datasets/${e}/experiments/${t.id}`,children:o.jsx("span",{className:"truncate min-w-0",children:t.id})}),n==="baseline"&&o.jsxs(Xs,{size:"small",color:a,children:[o.jsx(Ec,{})," ",s]})]}),o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-ui-sm text-neutral3",children:[o.jsxs(jl,{children:[o.jsx(Xye,{})," ",t.targetType," / ",t.targetId]}),o.jsxs(jl,{children:[o.jsx(XU,{})," v",t.datasetVersion??"—"]}),l&&o.jsxs(jl,{children:[o.jsx(clt,{})," ",er(l,"MMM d, yyyy HH:mm")]})]})]})}function Xrs({datasetId:e,experimentIdA:t,experimentIdB:n,onSwap:r}){const[s,a]=v.useState(null),{data:i,isLoading:l,error:c}=lns(e,t,n),{data:u}=CU(e,t),{data:d}=CU(e,n),f=u&&d&&u.datasetVersion!==d.datasetVersion,p=v.useMemo(()=>{if(!i)return[];const E=new Set;for(const j of i.items)for(const N of Object.values(j.results))if(N)for(const I of Object.keys(N.scores))E.add(I);return[...E].sort()},[i]),h=v.useMemo(()=>{if(!i||p.length===0)return[];const E=i.baselineId,j=t===E?n:t;return p.map(N=>{let I=0,R=0,$=0,F=0;for(const L of i.items){const z=L.results[E]?.scores[N],B=L.results[j]?.scores[N];z!=null&&(I+=z,$++),B!=null&&(R+=B,F++)}const D=$>0?I/$:null,V=F>0?R/F:null,W=D!=null&&V!=null?V-D:null;return{scorerId:N,avgA:D,avgB:V,delta:W}})},[i,p,t,n]),m=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"baselineAvg",label:"Baseline Avg",size:"1fr"},{name:"comparisonAvg",label:"Comparison Avg",size:"1fr"},{name:"delta",label:"Delta",size:"1fr"}],g=v.useMemo(()=>[{name:"itemId",label:"Item ID",size:"8rem"},...s?[]:p.map(E=>({name:E,label:E,size:"1fr"}))],[p,s]),y=i?.items.find(E=>E.itemId===s)??null,b=E=>{a(E===s?null:E)},w=()=>{a(null)},S=()=>{if(!i||!s)return;const E=i.items.findIndex(j=>j.itemId===s);if(E>=0&&E<i.items.length-1)return()=>a(i.items[E+1].itemId)},k=()=>{if(!i||!s)return;const E=i.items.findIndex(j=>j.itemId===s);if(E>0)return()=>a(i.items[E-1].itemId)};if(l)return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx(Gt,{})});if(c)return o.jsx(In,{variant:"warning",title:"Error loading comparison",children:o.jsx(In.Message,{children:c instanceof Error?c.message:"Unknown error"})});if(!i||i.items.length===0)return o.jsx("div",{className:"text-neutral4 text-sm text-center py-8",children:"No comparison data"});const _=i.baselineId,C=t===_?n:t;return o.jsxs("div",{className:"grid gap-10",children:[u&&d&&o.jsxs("div",{className:K("relative grid xl:grid-cols-[1fr_auto_1fr] gap-4 xl:gap-0"),children:[o.jsx(MQe,{datasetId:e,experiment:u,type:"baseline"}),o.jsx("div",{className:"relative flex items-center justify-center px-[2vw] before:absolute before:inset-y-0 before:left-1/2 before:-translate-x-1/2 before:w-[2px] before:bg-border1",children:o.jsx("div",{className:"relative z-1 bg-surface2 rounded-lg p-2",children:o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsx(ue,{onClick:r,children:"VS"})}),o.jsx(Bn,{children:"Switch the order"})]})})}),o.jsx(MQe,{datasetId:e,experiment:d,type:"contender"})]}),f&&o.jsx(In,{variant:"warning",title:"Version mismatch",children:o.jsxs(In.Message,{children:["These experiments used different dataset versions (v",u.datasetVersion," vs v",d.datasetVersion,"). Results may not be directly comparable."]})}),h.length>0&&o.jsxs(gn,{children:[o.jsxs(gn.Header,{columns:m,children:[o.jsx(gn.HeaderCol,{children:"Scorer"}),o.jsx(gn.HeaderCol,{className:"flex justify-center",children:o.jsxs(h9e,{children:[o.jsx(Xs,{color:"purple",size:"small",intensity:"muted",children:"Baseline"}),o.jsx(Xs,{color:"purple",size:"small",children:"Avg"})]})}),o.jsx(gn.HeaderCol,{className:"flex justify-center",children:o.jsxs(h9e,{children:[o.jsx(Xs,{color:"cyan",size:"small",intensity:"muted",children:"Contender"}),o.jsx(Xs,{color:"cyan",size:"small",children:"Avg"})]})}),o.jsx(gn.HeaderCol,{className:"flex justify-center",children:"Delta"})]}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:h.map(({scorerId:E,avgA:j,avgB:N,delta:I})=>o.jsxs(gn.Row,{columns:m,children:[o.jsx(gn.TextCell,{children:E}),o.jsx(gn.TextCell,{className:"text-center font-mono",children:j!=null?j.toFixed(3):"-"}),o.jsx(gn.TextCell,{className:"text-center font-mono",children:N!=null?N.toFixed(3):"-"}),o.jsx(gn.TextCell,{className:"flex justify-center",children:I!=null?o.jsx(STe,{delta:I}):"-"})]},E))})})]}),o.jsxs(Yv,{className:K({"grid-cols-[1fr_2fr]":!!y}),children:[o.jsx(Qrs,{items:i.items,baselineId:_,contenderId:C,scorerIds:p,featuredItemId:s,columns:g,onItemClick:b}),!!y&&o.jsx(Grs,{item:y,baselineId:_,contenderId:C,baselineVersion:u?.datasetVersion,contenderVersion:d?.datasetVersion,onPrevious:k(),onNext:S(),onClose:w})]})]})}function Krs({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=yTe(e,t),[l,c]=v.useState(!1),[u,d]=v.useState(new Set),f=b=>{n?.(b)},p=b=>s==null?b.isLatest:b.datasetVersion===s,h=b=>{d(w=>{const S=new Set(w);if(S.has(b))S.delete(b);else if(S.size>=2){const[k]=Array.from(S);return new Set([k,b])}else S.add(b);return S})},m=()=>{c(!1),d(new Set)},g=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(Gr,{className:"min-w-56",children:[l?o.jsx(Gr.Toolbar,{className:"grid justify-stretch gap-3 w-full",children:o.jsxs($r,{children:[o.jsx(ue,{onClick:m,children:"Cancel"}),o.jsx(ue,{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(Gr.Toolbar,{children:o.jsxs(ue,{onClick:g,className:"w-full",children:[o.jsx(Qw,{})," Compare Ver."]})})}),i?o.jsx(Jrs,{}):o.jsxs(gn,{children:[o.jsx(gn.Header,{children:o.jsx(gn.HeaderCol,{children:"Item Version History"})}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:a?.map(b=>{const w=String(b.datasetVersion),S=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(gn.Row,{isSelected:l&&u.has(w),children:[l&&o.jsx(gn.LabelCell,{children:o.jsx($o,{checked:u.has(w),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||h(w)},"aria-label":`Select version ${b.datasetVersion}`})}),o.jsx(gn.RowButton,{item:b,columns:[{name:"version",label:"Item Version History",size:"1fr"}],isFeatured:p(b),onClick:()=>f(b),className:"py-2",children:o.jsx(gn.VersionCell,{version:b.datasetVersion,date:S,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function Jrs(){return o.jsxs(gn,{children:[o.jsx(gn.Header,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(gn.HeaderCol,{children:"Item Version History"})}),o.jsx(gn.Items,{children:Array.from({length:3}).map((e,t)=>o.jsx(gn.Row,{children:o.jsx(gn.RowButton,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(gn.TextCell,{isLoading:!0,children:"Loading..."})})},t))})]})}function ess(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${er(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function tss({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=mTe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${ess(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(Gr.Toolbar,{className:"grid grid-cols-[1fr_1fr_1fr_10rem] gap-4 w-full",children:[o.jsx("div",{}),o.jsx(bc,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(bc,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const nss=[{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"}],rss={added:{color:"blue",borderColor:"border-blue-900",icon:o.jsx(Fr,{}),tooltip:"Added in this version"},changed:{color:"orange",borderColor:"border-yellow-900",icon:o.jsx(jlt,{}),tooltip:"Changed in this version"},same:{color:"green",borderColor:"border-green-900",icon:o.jsx(gcn,{}),tooltip:"Same in both versions"}};function ase({red:e=!1,tooltip:t}){return o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsx(nln,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),t&&o.jsx(Bn,{children:t})]})}function VS({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{color:n,icon:r,tooltip:s}=rss[e];return o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"pr-3 text-ui-md text-neutral4 min-w-16 flex justify-end",children:["v. ",t]}),o.jsx(Xs,{color:n,size:"small",children:r})]})}),o.jsx(Bn,{children:s})]})}function sss(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function ass({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=yn(),l=t>n;return o.jsx(gn,{children:o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=sss(u,d);return o.jsxs(gn.Row,{columns:nss,children:[o.jsx(gn.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!d&&l?o.jsx(VS,{variant:"added",version:u.datasetVersion}):f==="changed"&&l?o.jsx(VS,{variant:"changed",version:u.datasetVersion}):o.jsx(VS,{version:u.datasetVersion})}):o.jsx(gn.Cell,{className:"justify-center flex items-center",children:o.jsx(ase,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!u&&!l?o.jsx(VS,{variant:"added",version:d.datasetVersion}):f==="changed"&&!l?o.jsx(VS,{variant:"changed",version:d.datasetVersion}):o.jsx(VS,{version:d.datasetVersion})}):o.jsx(gn.Cell,{className:"justify-center flex items-center",children:o.jsx(ase,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",children:o.jsx(VS,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?ids=${u?.datasetVersion},${d?.datasetVersion}`,children:"Compare"}):o.jsx(gn.Cell,{children:o.jsx(ase,{tooltip:o.jsxs(o.Fragment,{children:["Comparing is available",o.jsx("br",{})," only for changed items"]})})})]},c)})})})})}const DQe={needsReview:"#facc15",complete:"#22c55e"},iss=[{label:"Needs Review",color:DQe.needsReview},{label:"Reviewed",color:DQe.complete}];function oss({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=v.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,p=0;const h=[];for(const m of e.counts){const g=m.needsReview+m.complete;if(g===0)continue;p+=g,g>f&&(f=g);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,w=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);h.push({name:w,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(mT,{data:a,segments:iss,maxVal:i,fmt:u=>String(u)}):o.jsx(Bt.NoData,{message:"No items have been sent to review yet"})})]})}function kTe(){const e=We();return wt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function a9t(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 lss(e,t){const n=new Map,r=a9t(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 css(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 uss=10;function dss(){const[e,t]=v.useState(!1),[n,r]=v.useState(""),[s,a]=v.useState("all"),[i,l]=v.useState("all"),[c,u]=v.useState("all"),[d,f]=v.useState(0),{data:p,isLoading:h,error:m}=Rg({page:d,perPage:uss}),{data:g,isLoading:y,error:b}=VZ(),{data:w}=kTe(),S=v.useMemo(()=>p?.datasets??[],[p?.datasets]),k=p?.pagination?.hasMore??!1,_=v.useMemo(()=>g?.experiments??[],[g?.experiments]),C=v.useMemo(()=>Cns(S),[S]),E=v.useMemo(()=>lss(w,_),[w,_]),j=h||y,N=m||b,I=()=>t(!0),R=v.useCallback(()=>f(B=>B+1),[]),$=v.useCallback(()=>f(B=>Math.max(0,B-1)),[]),F=v.useCallback(B=>{r(B),f(0)},[]),D=v.useCallback(B=>{a(B),f(0)},[]),V=v.useCallback(B=>{l(B),f(0)},[]),W=v.useCallback(B=>{u(B),f(0)},[]);if(N&&gs(N))return o.jsx(lr,{children:o.jsx(Vs,{})});if(N&&ys(N))return o.jsx(lr,{children:o.jsx(Ds,{resource:"datasets"})});if(N)return o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load datasets",message:N.message})});if(S.length===0&&!j&&d===0)return o.jsxs(o.Fragment,{children:[o.jsx(lr,{children:o.jsx(Ins,{onCreateClick:I})}),o.jsx(Pve,{open:e,onOpenChange:t})]});const L=s!=="all"||i!=="all"||c!=="all"||n!=="",z=()=>{r(""),a("all"),l("all"),u("all"),f(0)};return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Rns,{search:n,onSearchChange:F,targetFilter:s,onTargetFilterChange:D,experimentFilter:i,onExperimentFilterChange:V,tagFilter:c,onTagFilterChange:W,tagOptions:C,onReset:z,hasActiveFilters:L,onCreateClick:I})}),o.jsx(Nns,{datasets:S,experiments:_,reviewByDataset:E,isLoading:j,search:n,targetFilter:s,experimentFilter:i,tagFilter:c,currentPage:d,hasMore:k,onNextPage:R,onPrevPage:$}),o.jsx(Pve,{open:e,onOpenChange:t})]})}function Q8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function fss(){const{datasetId:e}=dr(),t=bs(),[n,r]=ji(),{activeVersion:s}=bTe(n,r),[a,i]=v.useState(!1),[l,c]=v.useState(!1),[u,d]=v.useState(!1),[f,p]=v.useState(!1),[h,m]=v.useState(!1),{data:g,error:y,isLoading:b}=Ux(e),{data:w=[],isLoading:S}=C1(e,void 0,s),k=!S&&w.length===0;if(b)return null;if(y&&gs(y))return o.jsx(Q8,{children:o.jsx(Vs,{})});if(y&&ys(y))return o.jsx(Q8,{children:o.jsx(Ds,{resource:"datasets"})});if(y&&uOe(y)||!b&&!y&&!g)return o.jsx(Q8,{children:o.jsx(Lr,{iconSlot:o.jsx(ay,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(ue,{as:ci,to:"/datasets",children:[o.jsx(Ec,{}),"Back to Datasets"]})})});if(y)return o.jsx(Q8,{children:o.jsx(Fi,{title:"Failed to load dataset",message:y instanceof Error?y.message:"An unexpected error occurred. Please try again."})});const _=E=>{t(`/datasets/${e}/experiments/${E}`)},C=()=>{t("/datasets")};return o.jsxs(o.Fragment,{children:[o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{children:[o.jsxs(Lt.Column,{children:[g?.description&&o.jsx("p",{className:"text-ui-smd text-neutral3 mb-1",children:g.description}),o.jsxs(zt,{numOfCol:2,children:[o.jsx(zt.Key,{children:"Created at"}),o.jsx(zt.Value,{children:g?.createdAt?er(new Date(g.createdAt),"MMM d, yyyy"):""}),o.jsx(zt.Key,{children:"Latest version"}),o.jsxs(zt.Value,{children:["v",g?.version??""]})]})]}),o.jsx(Lt.Column,{children:o.jsxs($r,{children:[k?o.jsxs(Wn,{children:[o.jsx(zn,{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(ue,{variant:"primary",children:[o.jsx(Pp,{}),s!=null?`Run on v${s}`:"Run Experiment"]})})})}),o.jsx(Bn,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(ue,{variant:"primary",onClick:()=>i(!0),children:[o.jsx(Pp,{}),s!=null?`Run on v${s}`:"Run Experiment"]}),o.jsxs(ft,{children:[o.jsx(ft.Trigger,{asChild:!0,children:o.jsx(ue,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(l3,{})})}),o.jsxs(ft.Content,{align:"end",className:"w-48",children:[o.jsxs(ft.Item,{onSelect:()=>d(!0),children:[o.jsx(em,{})," Edit Dataset"]}),o.jsxs(ft.Item,{onSelect:()=>m(!0),children:[o.jsx(Rp,{})," Duplicate Dataset"]}),o.jsxs(ft.Item,{onSelect:()=>p(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(Jc,{})," Delete Dataset"]})]})]})]})})]})}),o.jsx(Lt.MainArea,{children:o.jsx(Crs,{datasetId:e,onAddItemClick:()=>c(!0)})})]}),o.jsx(Prs,{datasetId:e,version:s??void 0,requestContextSchema:g?.requestContextSchema,open:a,onOpenChange:i,onSuccess:_}),o.jsx(jrs,{datasetId:e,open:l,onOpenChange:c}),g&&o.jsx(Fns,{open:u,onOpenChange:d,dataset:{id:g.id,name:g.name,description:g?.description||"",targetType:g.targetType,inputSchema:g.inputSchema,groundTruthSchema:g.groundTruthSchema,requestContextSchema:g.requestContextSchema}}),g&&o.jsx(Mns,{open:h,onOpenChange:m,sourceDatasetId:g.id,sourceDatasetName:g.name,sourceDatasetDescription:g.description,sourceDatasetTargetType:g.targetType}),g&&o.jsx(Bns,{open:f,onOpenChange:p,datasetId:g.id,datasetName:g.name,onSuccess:C})]})}function i9t({experiment:e}){const{Link:t,paths:n}=yn(),{data:r}=km(),{data:s}=Uy(),{data:a}=eh(),i=()=>{switch(e.targetType){case"agent":return n.agentLink(e.targetId);case"workflow":return n.workflowLink(e.targetId);case"scorer":return n.scorerLink(e.targetId);default:return"#"}},l=()=>{const u=e.targetId;if(!u)return u;switch(e.targetType){case"agent":return r?.[u]?.name??u;case"workflow":return s?.[u]?.name??u;case"scorer":return a?.[u]?.scorer?.config?.name??u;default:return u}},c=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${n.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{children:[o.jsx(Lt.Column,{children:o.jsxs(zt,{numOfCol:2,children:[o.jsx(zt.Key,{children:"Created at"}),o.jsx(zt.Value,{children:er(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")}),e.completedAt&&o.jsxs(o.Fragment,{children:[o.jsx(zt.Key,{children:"Completed at"}),o.jsx(zt.Value,{children:er(new Date(e.completedAt),"MMM d, yyyy 'at' h:mm a")})]}),o.jsx(zt.Key,{children:"Target"}),o.jsx(zt.ValueLink,{href:i(),as:t,children:l()}),e.agentVersion&&o.jsxs(o.Fragment,{children:[o.jsx(zt.Key,{children:"Version"}),c?o.jsx(zt.ValueLink,{href:c,as:t,children:e.agentVersion}):o.jsx(zt.Value,{children:e.agentVersion})]})]})}),o.jsx(Lt.Column,{children:o.jsx(Wrs,{experiment:e})})]})})}function Y8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function pss(){const{datasetId:e,experimentId:t}=dr(),{data:n,isLoading:r,error:s}=CU(e,t),{data:a,isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u}=BZ({datasetId:e,experimentId:t,experimentStatus:n?.status});return!e||!t||r?null:s&&gs(s)?o.jsx(Y8,{children:o.jsx(Vs,{})}):s&&ys(s)?o.jsx(Y8,{children:o.jsx(Ds,{resource:"datasets"})}):s&&uOe(s)||!r&&!s&&!n?o.jsx(Y8,{children:o.jsx(Lr,{iconSlot:o.jsx(Bye,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${t}".`,actionSlot:o.jsxs(ue,{as:ci,to:`/datasets/${e}?tab=experiments`,children:[o.jsx(Ec,{}),"Back to Dataset"]})})}):s?o.jsx(Y8,{children:o.jsx(Fi,{title:"Failed to load experiment",message:s instanceof Error?s.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx(i9t,{experiment:n}),o.jsx(Lt.MainArea,{children:o.jsx(s9t,{experimentId:t,datasetId:e,experimentStatus:n.status,results:a??[],isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u})})]})}function hss(){const{datasetId:e}=dr(),[t,n]=ji(),{error:r}=Ux(e??""),s=t.get("baseline")??"",a=t.get("contender")??"";return r&&gs(r)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):r&&ys(r)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||!s||!a?o.jsx(cs,{children:o.jsx(dy,{children:o.jsxs("div",{className:"text-neutral4 text-center py-8",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"text-sm mt-2",children:["Use the URL format: /datasets/","{datasetId}","/experiments?baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):o.jsx(cs,{children:o.jsx(dy,{children:o.jsxs("div",{className:"max-w-[100rem] w-full px-12 mx-auto grid content-start ",children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Qw,{})," Dataset Experiments Comparison"]}),o.jsxs(ua.Description,{children:["Comparing"," ",o.jsx(ci,{to:`/datasets/${e}/experiments/${s}`,children:s.slice(0,8)})," vs"," ",o.jsx(ci,{to:`/datasets/${e}/experiments/${a}`,children:a.slice(0,8)})]})]}),o.jsx(ua.Column,{children:o.jsxs(ue,{as:ci,to:`/datasets/${e}`,children:[o.jsx(Ec,{}),"Back to Dataset"]})})]}),o.jsx(Xrs,{datasetId:e,experimentIdA:s,experimentIdB:a,onSwap:()=>{n({baseline:a,contender:s})}})]})})})}function mss(){const{datasetId:e,itemId:t}=dr(),{Link:n}=yn(),r=bs(),{data:s,isLoading:a,error:i}=yTe(e??"",t??""),{updateItem:l,deleteItem:c}=_i(),{data:u}=Ux(e??""),d=s?.[0]??null,f=d?.isDeleted??!1,[p,h]=v.useState(null),m=v.useMemo(()=>!d||f?{input:"",groundTruth:"",metadata:"",trajectory:"",toolMocks:"",requestContext:""}:{input:JSON.stringify(d.input,null,2),groundTruth:d.groundTruth?JSON.stringify(d.groundTruth,null,2):"",metadata:d.metadata?JSON.stringify(d.metadata,null,2):"",trajectory:d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):"",toolMocks:d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):"",requestContext:d.requestContext?JSON.stringify(d.requestContext,null,2):""},[d,f]),g=d?.datasetVersion??0,[y,b]=v.useState(!1),[w,S]=v.useState(m.input),[k,_]=v.useState(m.groundTruth),[C,E]=v.useState(m.metadata),[j,N]=v.useState(m.trajectory),[I,R]=v.useState(m.toolMocks),[$,F]=v.useState(m.requestContext),[D,V]=v.useState(g);g!==D&&(V(g),S(m.input),_(m.groundTruth),E(m.metadata),N(m.trajectory),R(m.toolMocks),F(m.requestContext));const[W,L]=v.useState(!1),z=J=>{h(f?J:J.isLatest?null:J)},B=()=>{h(null)},M=!f&&p!=null,G=()=>{M||b(!0)},U=()=>{M||L(!0)},P=async()=>{if(!e||!t)return;let J;try{J=JSON.parse(w)}catch{De.error("Input must be valid JSON");return}let ee;if(k.trim())try{ee=JSON.parse(k)}catch{De.error("Ground Truth must be valid JSON");return}let ae;if(C.trim())try{ae=JSON.parse(C)}catch{De.error("Metadata must be valid JSON");return}let de;const Y=j!==m.trajectory;if(Y&&j.trim())try{de=JSON.parse(j)}catch{De.error("Expected Trajectory must be valid JSON");return}let ne;const ce=I!==m.toolMocks;if(ce&&I.trim())try{const ve=JSON.parse(I);if(!Array.isArray(ve)){De.error("Tool Mocks must be a JSON array");return}ne=ve}catch{De.error("Tool Mocks must be valid JSON");return}let pe;const le=$!==m.requestContext;if(le&&$.trim())try{pe=JSON.parse($)}catch{De.error("Request Context must be valid JSON");return}try{await l.mutateAsync({datasetId:e,itemId:t,input:J,groundTruth:ee,metadata:ae,...Y?{expectedTrajectory:de??null}:{},...ce?{toolMocks:ne??[]}:{},...le?{requestContext:pe}:{}}),De.success("Item updated successfully"),b(!1)}catch(ve){De.error(`Failed to update item: ${ve instanceof Error?ve.message:"Unknown error"}`)}},q=()=>{d&&(S(JSON.stringify(d.input,null,2)),_(d.groundTruth?JSON.stringify(d.groundTruth,null,2):""),E(d.metadata?JSON.stringify(d.metadata,null,2):""),N(d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):""),R(d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):""),F(d.requestContext?JSON.stringify(d.requestContext,null,2):"")),b(!1)},Z=async()=>{if(!(!e||!t))try{await c.mutateAsync({datasetId:e,itemId:t}),De.success("Item deleted successfully"),L(!1),r(`/datasets/${e}`)}catch(J){De.error(`Failed to delete item: ${J instanceof Error?J.message:"Unknown error"}`)}},X=p??d,te=X?{id:t??"",datasetId:e??"",datasetVersion:X.datasetVersion,input:X.input,groundTruth:X.groundTruth,expectedTrajectory:X.expectedTrajectory,metadata:X.metadata,createdAt:X.createdAt,updatedAt:X.updatedAt}:null;return i&&gs(i)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):i&&ys(i)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):a?null:!e||!t||!s||s.length===0?o.jsx(cs,{children:o.jsx(dy,{children:o.jsx("div",{className:"text-neutral3 p-4",children:"Item not found"})})}):o.jsxs(o.Fragment,{children:[o.jsx(cs,{children:o.jsx("div",{className:"h-full overflow-hidden px-6 pb-4",children:o.jsxs("div",{className:"grid gap-6 max-w-[60rem] mx-auto grid-rows-[auto_1fr] h-full",children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(dN,{}),t," ",o.jsx(ya,{content:t})]}),o.jsx(ua.Description,{children:o.jsxs(jl,{children:["Item of ",o.jsx(ay,{})," ",u?.name]})}),o.jsxs(ua.Description,{children:[o.jsxs(jl,{children:[o.jsx(llt,{})," Created at"," ",d?.createdAt?er(new Date(d.createdAt),"MMM d, yyyy"):""]}),o.jsxs(jl,{children:[o.jsx(i_,{})," Latest version v",d?.datasetVersion??""]})]})]}),o.jsx(ua.Column,{children:!y&&!f&&o.jsxs($r,{children:[o.jsxs(ue,{onClick:G,disabled:M,title:M?"Return to latest version to edit":void 0,children:[o.jsx(jlt,{})," Edit"]}),o.jsxs(ue,{onClick:U,disabled:M,title:M?"Return to latest version to delete":void 0,children:[o.jsx(Jc,{})," Delete"]})]})})]}),o.jsxs(Yv,{className:y?"grid-cols-1":"grid-cols-[1fr_auto]",children:[o.jsxs(Gr,{withRightSeparator:!y,children:[f&&d&&o.jsx(In,{variant:"destructive",title:"Item deleted",children:o.jsxs(In.Message,{children:["This item was deleted at version v",d.datasetVersion]})}),!f&&M&&p&&o.jsx(In,{variant:"warning",title:"Previous version",action:o.jsxs(In.Button,{onClick:B,children:[o.jsx(rlt,{})," Return to the latest version"]}),children:o.jsxs(In.Message,{children:["Viewing version v",p.datasetVersion]})}),y?o.jsx(n9t,{inputValue:w,setInputValue:S,groundTruthValue:k,setGroundTruthValue:_,metadataValue:C,setMetadataValue:E,trajectoryValue:j,setTrajectoryValue:N,toolMocksValue:I,setToolMocksValue:R,requestContextValue:$,setRequestContextValue:F,validationErrors:null,onSave:P,onCancel:q,isSaving:l.isPending}):te?o.jsx(wTe,{item:te,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})]}),!y&&o.jsx(Gr,{children:o.jsx(Krs,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:z,onCompareVersionsClick:J=>{r(`/datasets/${e}/items/${t}/versions?ids=${J.join(",")}`)},activeVersion:p?.datasetVersion??null})})]})]})})}),o.jsx(Tt,{open:W,onOpenChange:L,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Item"}),o.jsx(Tt.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(Tt.Footer,{children:[o.jsx(Tt.Cancel,{children:"Cancel"}),o.jsx(Tt.Action,{onClick:Z,children:c.isPending?"Deleting...":"Delete"})]})]})})]})}function LQe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function gss(){const{datasetId:e}=dr(),[t,n]=ji(),r=t.get("items")?.split(",").filter(Boolean)??[],{data:s,error:a}=Ux(e??""),{Link:i}=yn(),[l,c]=v.useState(!1),{data:u}=EU(e??"",r[0]??""),{data:d}=EU(e??"",r[1]??"");return a&&gs(a)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):a&&ys(a)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||r.length<2?o.jsx(cs,{children:o.jsx(dy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two items to compare."})})})}):o.jsxs(cs,{children:[o.jsx(Ty,{owner:"dataset-items-compare",children:o.jsxs(ue,{as:ci,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(Ec,{}),"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]":l}),children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Qw,{}),"Compare Dataset Items"]}),o.jsx(ua.Description,{children:o.jsxs(jl,{children:["Comparing ",r.length," items of"," ",o.jsx(ci,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:s?.name||e?.slice(0,8)})]})})]}),o.jsx(ua.Column,{children:o.jsx($r,{children:o.jsx(ue,{variant:"primary",onClick:()=>c(f=>!f),children:l?o.jsxs(o.Fragment,{children:[o.jsx(mlt,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(lcn,{})," Diff View"]})})})})]}),o.jsx(Yv,{className:"grid-cols-[1fr_3vw_1fr]",children:r.map((f,p)=>o.jsxs(v.Fragment,{children:[o.jsx(vss,{datasetId:e,itemId:f,Link:i,idx:p,itemIds:r,showContent:!l,onItemChange:h=>{const m=[...r];m[p]=h,n({items:m.join(",")})}}),p==0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},f))}),l&&u&&d&&o.jsx(X1e,{codeA:LQe(u),codeB:LQe(d)})]})})]})}function vss({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=EU(e,t),{data:u}=C1(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(Gr,{children:[o.jsxs(Gr.Toolbar,{className:"flex gap-4",children:[o.jsxs(ba,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(wa,{"aria-label":"Item",children:o.jsx(xa,{placeholder:"Select item"})}),o.jsx(Sa,{children:f.map(p=>o.jsx(qr,{value:p.value,disabled:p.disabled,children:p.label},p.value))})]}),o.jsxs(ue,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(i_,{}),"Versions"]})]}),i&&o.jsx(Gr.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(Trs,{item:l}),o.jsx(wTe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function FQe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function yss(){const{datasetId:e,itemId:t}=dr(),[n,r]=ji(),[s,a]=v.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(h=>!isNaN(h)&&h>0)??[],{data:l,error:c}=Ux(e??""),{Link:u}=yn(),{data:d}=yTe(e??"",t??""),{data:f}=Mve(e??"",t??"",i[0]??0,l?.version),{data:p}=Mve(e??"",t??"",i[1]??0,l?.version);return c&&gs(c)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):c&&ys(c)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||!t||i.length<2?o.jsx(cs,{children:o.jsx(dy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two versions to compare."})})})}):o.jsxs(cs,{children:[o.jsx(Ty,{owner:"dataset-item-versions-compare",children:o.jsxs(ue,{as:ci,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(Ec,{}),"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(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Qw,{}),"Compare Dataset Item Versions"]}),o.jsx(ua.Description,{children:o.jsxs(jl,{children:["Comparing ",i.length," versions of"," ",o.jsx(ci,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(ua.Column,{children:o.jsx($r,{children:o.jsx(ue,{variant:"primary",onClick:()=>a(h=>!h),children:s?o.jsxs(o.Fragment,{children:[o.jsx(mlt,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(Zcn,{})," Diff View"]})})})})]}),o.jsx(Yv,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((h,m)=>o.jsxs(v.Fragment,{children:[o.jsx(bss,{datasetId:e,itemId:t,datasetVersion:h,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:g=>{const y=[...i];y[m]=g,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),s&&f&&p&&o.jsx(X1e,{codeA:FQe(f),codeB:FQe(p)})]})})]})}function bss({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}=Mve(e,t,n,r),p=new Set(a.filter((g,y)=>y!==l)),h=s.map(g=>{const y=typeof g.updatedAt=="string"?new Date(g.updatedAt):g.updatedAt;return{value:String(g.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",g.datasetVersion]})," - ",er(y,"MMM d, yyyy h:mm a"),g.isLatest?o.jsx(Xs,{color:"blue",size:"small",children:"Latest"}):null]}),disabled:p.has(g.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(Gr,{children:[o.jsxs(Gr.Toolbar,{className:"grid gap-4 grid-cols-[auto_1fr]",children:[o.jsx(i_,{className:"w-6 h-6 opacity-50"}),o.jsxs(ba,{name:`compare-version-${l}`,value:String(n),onValueChange:g=>u(Number(g)),children:[o.jsx(wa,{"aria-label":"Version",className:"w-full",children:o.jsx(xa,{placeholder:"Select version"})}),o.jsx(Sa,{children:h.map(g=>o.jsx(qr,{value:g.value,disabled:g.disabled,children:g.label},g.value))})]})]}),c&&o.jsx(Gr.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(wTe,{item:m,Link:i})})]})}function xss(){const{datasetId:e}=dr(),[t]=ji(),n=t.get("ids")?.split(",").map(Number).filter(g=>!isNaN(g)&&g>0)??[],r=bs(),{data:s,error:a}=Ux(e??""),i=C1(e??"",void 0,n[0]??null),l=C1(e??"",void 0,n[1]??null),c=v.useMemo(()=>i.data??[],[i.data]),u=v.useMemo(()=>l.data??[],[l.data]),d=v.useMemo(()=>{const g=new Map;for(const y of[...c,...u])g.has(y.id)||g.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...g.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=v.useMemo(()=>new Map(c.map(g=>[g.id,g])),[c]),p=v.useMemo(()=>new Map(u.map(g=>[g.id,g])),[u]);if(a&&gs(a))return o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})});if(a&&ys(a))return o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(cs,{children:o.jsx(dy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const h=(g,y,b)=>{r(`/datasets/${e}/items/${g}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(g,y)=>{r(`/datasets/${e}/versions?ids=${g},${y}`,{replace:!0})};return o.jsx(cs,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Tdn,{})," Compare Dataset Versions"]}),o.jsx(ua.Description,{children:o.jsxs(jl,{children:[o.jsx(i_,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(ua.Column,{children:o.jsxs(ue,{as:ci,to:`/datasets/${e}`,children:[o.jsx(Ec,{}),"Back to Dataset"]})})]}),o.jsx(Yv,{children:o.jsxs(Gr,{children:[o.jsx(tss,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(ass,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p,onItemClick:h})]})})]})})})}function wss(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 Sss({scorers:e,datasets:t,experiments:n,avgScore:r,prevAvgScore:s,totalNeedsReview:a,isLoadingScorers:i,isLoadingDatasets:l,isLoadingExperiments:c,isLoadingScores:u,isLoadingReview:d}){const f=e?Object.keys(e).length:void 0,p=t?.length,h=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,g=wss(n);return o.jsxs(o.Fragment,{children:[o.jsxs(Kr,{children:[o.jsx(Kr.Label,{children:"Total Scorers"}),i?o.jsx(Kr.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(Kr.Value,{children:String(f)}),o.jsx(Kr.NoChange,{message:"Static count"})]}):o.jsx(Kr.NoData,{})]}),o.jsxs(Kr,{children:[o.jsx(Kr.Label,{children:"Total Datasets"}),l?o.jsx(Kr.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Kr.Value,{children:String(p)}),o.jsx(Kr.NoChange,{message:"Static count"})]}):o.jsx(Kr.NoData,{})]}),o.jsxs(Kr,{children:[o.jsx(Kr.Label,{children:"Avg Score"}),u?o.jsx(Kr.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(Kr.Value,{children:String(r)}),m?o.jsx(Kr.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(Kr.NoChange,{})]}):o.jsx(Kr.NoData,{})]}),o.jsxs(Kr,{children:[o.jsx(Kr.Label,{children:"Total Experiments"}),c?o.jsx(Kr.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Kr.Value,{children:String(h)}),g?o.jsx(Kr.Change,{changePct:g.changePct,prevValue:g.prevValue}):o.jsx(Kr.NoChange,{})]}):o.jsx(Kr.NoData,{})]}),o.jsxs(Kr,{children:[o.jsx(Kr.Label,{children:"Needs Review"}),d?o.jsx(Kr.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(Kr.Value,{children:String(a)}),a>0?o.jsx(Kr.NoChange,{message:"items pending review"}):o.jsx(Kr.NoChange,{message:"All caught up"})]}):o.jsx(Kr.NoData,{})]})]})}const zQe="auto 1fr auto auto auto auto auto auto auto";function kss(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}const Oss={completed:"success",running:"warning",failed:"error",pending:"neutral"};function _ss({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all"}){const{paths:l,Link:c}=yn(),u=v.useMemo(()=>{const p=new Map;return t?.forEach(h=>p.set(h.id,h.name)),p},[t]),d=v.useMemo(()=>[...e].sort((p,h)=>{const m=p.createdAt?new Date(p.createdAt).getTime():0;return(h.createdAt?new Date(h.createdAt).getTime():0)-m}),[e]),f=v.useMemo(()=>{const p=s.toLowerCase();return d.filter(h=>{const m=h.datasetId?u.get(h.datasetId)??"":"",g=!p||h.id.toLowerCase().includes(p)||m.toLowerCase().includes(p)||(h.targetId??"").toLowerCase().includes(p),y=a==="all"||h.status===a,b=i==="all"||h.datasetId===i;return g&&y&&b})},[d,s,u,a,i]);return r?o.jsx(el,{columns:zQe}):o.jsxs(me,{columns:zQe,variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Experiment"}),o.jsx(me.TopCell,{children:"Dataset"}),o.jsx(me.TopCell,{children:"Target"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{className:"text-center",children:"Items"}),o.jsx(me.TopCell,{className:"text-center",children:"Succeeded"}),o.jsx(me.TopCell,{className:"text-center",children:"Failed"}),o.jsx(me.TopCell,{className:"text-center",children:"Review"}),o.jsx(me.TopCell,{children:"Date"})]}),f.map(p=>{const h=p.datasetId?u.get(p.datasetId)??p.datasetId.slice(0,8):"—",m=p.status??"pending",g=p.succeededCount??0,y=p.failedCount??0,b=p.totalItems??0,w=b>0?Math.round(g/b*100):0;return o.jsxs(me.RowLink,{to:l.experimentLink(p.id),LinkComponent:c,children:[o.jsx(me.NameCell,{className:"font-mono",children:p.id.slice(0,8)}),o.jsx(me.TextCell,{children:h}),o.jsx(me.Cell,{children:o.jsxs("span",{className:"truncate",children:[p.targetType," ",p.targetId]})}),o.jsx(me.Cell,{children:o.jsx(ug,{variant:Oss[m]??"neutral",withDot:!0,children:m})}),o.jsx(me.TextCell,{className:"text-center",children:b}),o.jsx(me.TextCell,{className:"text-center",children:o.jsxs("span",{className:g>0?"text-accent1":"",children:[g," (",w,"%)"]})}),o.jsx(me.TextCell,{className:"text-center",children:o.jsx("span",{className:y>0?"text-accent2":"",children:y})}),o.jsx(me.Cell,{className:"text-center",children:(()=>{const S=n?.get(p.id);if(!S)return o.jsx("span",{className:"text-neutral2",children:"—"});const k=S.needsReview+S.complete;return k===0?o.jsx("span",{className:"text-neutral2",children:"—"}):S.needsReview>0?o.jsxs(Xs,{size:"small",color:"yellow",children:[S.needsReview," pending"]}):o.jsxs(Xs,{size:"small",color:"green",children:[S.complete,"/",k," reviewed"]})})()}),o.jsx(me.TextCell,{children:kss(p.createdAt)})]},p.id)})]})}const Css=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function Ess(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const X8={completed:"#22c55e",running:"#facc15",pending:"#fb923c",failed:"#f87171"},jss=[{label:"Completed",color:X8.completed},{label:"Running",color:X8.running},{label:"Pending",color:X8.pending},{label:"Failed",color:X8.failed}];function Tss({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=v.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const p=f.datasetId??"unknown";c.has(p)||c.set(p,{completed:0,running:0,pending:0,failed:0});const h=c.get(p),m=f.status;m in h&&h[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,p])=>{const h=p.completed+p.running+p.pending+p.failed;return h>u&&(u=h),{name:l.get(f)??f.slice(0,12),values:[p.completed,p.running,p.pending,p.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(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(mT,{data:s,segments:jss,maxVal:a,fmt:l=>String(l)}):o.jsx(Bt.NoData,{message:"No experiments have been run yet"})})]})}const Nss=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(xf,{}),titleSlot:"No Experiments yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Run an experiment from a dataset to evaluate ",o.jsx("br",{}),"your agents and workflows."]}),actionSlot:o.jsx("div",{className:"flex flex-col items-center gap-2",children:o.jsxs(ue,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/evals/datasets/running-experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(Pa,{})]})})})});function Iss({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c}){return o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(jf,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t}),o.jsxs($r,{children:[o.jsx(bc,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...Css],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(bc,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(ue,{onClick:l,size:"sm",variant:"default",children:[o.jsx(vs,{className:"size-3"})," Reset"]})]})]})}function Ass(){const{data:e,isLoading:t,error:n}=eh(),{data:r,isLoading:s,error:a}=Rg(),{data:i,isLoading:l,error:c}=VZ(),{data:u,isLoading:d,isError:f,error:p}=QXr(),{data:h,isLoading:m,isError:g,error:y}=kTe(),b=r?.datasets,w=i?.experiments,S=v.useMemo(()=>css(h),[h]),k=n||a||c||p||y;return k&&gs(k)?o.jsx(lr,{children:o.jsx(Vs,{})}):k&&ys(k)?o.jsx(lr,{children:o.jsx(Ds,{resource:"evaluation"})}):k?o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load evaluation data",message:k.message})}):o.jsx(Lt,{width:"wide",height:"full",children:o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsx(Wpe,{children:o.jsx(Sss,{scorers:e,datasets:b,experiments:w,avgScore:u?.avgScore??null,prevAvgScore:u?.prevAvgScore??null,totalNeedsReview:S.needsReview,isLoadingScorers:t,isLoadingDatasets:s,isLoadingExperiments:l,isLoadingScores:d,isLoadingReview:m})}),o.jsx(FXr,{summaryData:u?.summaryData??[],overTimeData:u?.overTimeData??[],scorerNames:u?.scorerNames??[],avgScore:u?.avgScore??null,isLoading:d,isError:f}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(Ans,{experiments:w,isLoading:l,isError:!!c}),o.jsx(Tss,{experiments:w,datasets:b,isLoading:l,isError:!!c})]}),o.jsx(oss,{reviewSummary:h,experiments:w,datasets:b,isLoading:m,isError:!!g})]})})}function Rss(){const[e,t]=v.useState(""),[n,r]=v.useState("all"),[s,a]=v.useState("all"),{data:i,isLoading:l,error:c}=Rg(),{data:u,isLoading:d,error:f}=VZ(),{data:p}=kTe(),h=v.useMemo(()=>i?.datasets??[],[i?.datasets]),m=v.useMemo(()=>u?.experiments??[],[u?.experiments]),g=v.useMemo(()=>Ess(h),[h]),y=v.useMemo(()=>a9t(p),[p]),b=l||d,w=f||c;if(w&&gs(w))return o.jsx(lr,{children:o.jsx(Vs,{})});if(f&&ys(f))return o.jsx(lr,{children:o.jsx(Ds,{resource:"experiments"})});if(c&&ys(c))return o.jsx(lr,{children:o.jsx(Ds,{resource:"datasets"})});if(w)return o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load experiments",message:w.message})});if(m.length===0&&!b)return o.jsx(lr,{children:o.jsx(Nss,{})});const S=n!=="all"||s!=="all"||e!=="",k=()=>{t(""),r("all"),a("all")};return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Iss,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:g,onReset:k,hasActiveFilters:S})}),o.jsx(_ss,{experiments:m,datasets:h,reviewByExperiment:y,isLoading:b,search:e,statusFilter:n,datasetFilter:s})]})}function K8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function Pss(){const{experimentId:e}=dr(),{data:t,isLoading:n}=VZ(),s=t?.experiments?.find(h=>h.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=CU(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p}=BZ({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&gs(l)?o.jsx(K8,{children:o.jsx(Vs,{})}):l&&ys(l)?o.jsx(K8,{children:o.jsx(Ds,{resource:"datasets"})}):l&&uOe(l)||!n&&!s||!i&&!l&&!a?o.jsx(K8,{children:o.jsx(Lr,{iconSlot:o.jsx(Bye,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(ue,{as:ci,to:"/experiments",children:[o.jsx(Ec,{}),"Back to Experiments"]})})}):l?o.jsx(K8,{children:o.jsx(Fi,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx(i9t,{experiment:a}),o.jsx(Lt.MainArea,{children:o.jsx(s9t,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p})})]})}function $ss({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 o9t({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx($ss,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function Mss({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(o9t,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function Dss({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(Mss,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(o9t,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function Lss({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:a,providersError:i,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:p,onToolkitChange:h,onLabelChange:m,onConnect:g}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>p(y.target.value),disabled:a,children:[o.jsx("option",{value:"",children:"— select provider —"}),e.map(y=>o.jsxs("option",{value:y.id,children:[y.displayName??y.name," (",y.id,")"]},y.id))]}),a&&o.jsx("span",{className:"text-gray-500",children:"Loading providers…"}),i?o.jsx("span",{className:"text-red-600",children:String(i)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"toolkit-select",children:"Toolkit"}),o.jsxs("select",{id:"toolkit-select",className:"border rounded px-2 py-1 w-full",value:r,onChange:y=>h(y.target.value),disabled:!n||l,children:[o.jsx("option",{value:"",children:"— select toolkit —"}),t.map(y=>o.jsxs("option",{value:y.slug,children:[y.name," (",y.slug,")"]},y.slug))]}),l&&o.jsx("span",{className:"text-gray-500",children:"Loading toolkits…"}),c?o.jsx("span",{className:"text-red-600",children:String(c)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"label-input",children:"Label (optional)"}),o.jsx("input",{id:"label-input",type:"text",className:"border rounded px-2 py-1 w-full",placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value),disabled:!n||!r})]}),o.jsx("button",{type:"button",className:"bg-blue-600 text-white rounded px-4 py-2 disabled:opacity-50",onClick:g,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const BQe=e=>e.authorId?.trim()||"shared",Fss=(e,t)=>{if(!t||new Set(e.map(BQe)).size<=1)return null;const r=new Map;for(const a of e){const i=BQe(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},zss=["*","tool-providers:*","tool-providers:admin"];function Bss(){const{data:e}=Sm();return e?.permissions?.some(t=>zss.includes(t))??!1}function Uss(){const[e,t]=v.useState(""),[n,r]=v.useState(""),[s,a]=v.useState(""),i=gI(),l=CW(e||null),c=PPt(e||null,n||null),u=RPt(),d=IPt(),f=Bss(),p=i.data?.providers??[],h=l.data?.data??[],m=v.useMemo(()=>c.data?.items??[],[c.data?.items]),g=v.useMemo(()=>Fss(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()}})},w=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(Lss,{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(Dss,{providerId:e,toolkit:n,connections:m,groupedByAuthor:g,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:w})]})}function qss({title:e,description:t,errorBanner:n,children:r}){return o.jsx("div",{"data-testid":"login-page",className:"flex min-h-screen items-center justify-center bg-surface1",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(Vh,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-xl font-semibold text-neutral6",children:e})]}),t,n,r]})})}function l9t({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=rc(),{mutate:i,isPending:l,error:c}=qDr(),{mutate:u,isPending:d,error:f}=HDr(),{mutate:p,isPending:h}=J2t(),[m,g]=v.useState(n),[y,b]=v.useState(""),[w,S]=v.useState(""),[k,_]=v.useState("");if(a)return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-surface1",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-surface1",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:C}=s,E=C.type==="sso"||C.type==="both",j=C.type==="credentials"||C.type==="both",N=C.sso,I=C.signUpEnabled!==!1,R=m==="signin"||!I,$=R?l:d,F=R?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href="/"},V=M=>{M.preventDefault(),R?i({email:w,password:k},{onSuccess:D}):u({email:w,password:k,name:y||void 0},{onSuccess:D})},W=()=>{p({redirectUri:e},{onSuccess:M=>{window.location.href=M.url}})},L=()=>{g(R?"signup":"signin")},z=C.description?o.jsxs("div",{className:"flex items-start gap-2.5 rounded-md border border-border1 bg-surface1 p-3",children:[o.jsx(pf,{className:"mt-0.5 h-4 w-4 shrink-0 text-neutral4"}),o.jsx("p",{className:"text-sm text-neutral3",children:C.description})]}):null,B=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(qss,{title:R?"Sign in to Mastra Studio":"Create your account",description:z,errorBanner:B,children:[j&&o.jsxs("form",{onSubmit:V,className:"space-y-4",children:[!R&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"block text-sm text-neutral4",children:"Name"}),o.jsx(kn,{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:"block text-sm text-neutral4",children:"Email"}),o.jsx(kn,{id:"email",type:"email",value:w,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:"block text-sm text-neutral4",children:"Password"}),o.jsx(kn,{id:"password",type:"password",value:k,onChange:M=>_(M.target.value),placeholder:R?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),F&&o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:F.message}),o.jsx(ue,{type:"submit",disabled:$,className:"w-full",size:"lg",children:$?R?"Signing in...":"Creating account...":R?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-center text-sm",children:[o.jsx("span",{className:"text-neutral3",children:R?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:L,className:"text-neutral6 hover:underline",children:R?"Sign up":"Sign in"})]})]}),E&&j&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"w-full border-t border-border1"})}),o.jsx("div",{className:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 px-2 text-neutral3",children:"or continue with"})})]}),E&&N&&o.jsxs(ue,{onClick:W,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 Vss(){const[e]=ji(),t=bs(),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(l9t,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}function Hss(){const[e,t]=ji(),n=KSr(e,t),r=tkr(e,t),[s,a]=v.useState(),[i,l]=v.useState(!1),{data:c=[],isPending:u}=NOe(),{data:d=[],isPending:f}=IOe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=AOe(),{data:m=[],isPending:g}=ROe(),y=v.useMemo(()=>w1r({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:g,environments:h}}),[c,d,m,p,u,f,g,h]),b=v.useMemo(()=>_1r({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:w=[],isLoading:S,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E}=YSr({filters:b}),{logIdMap:j,featuredLog:N,handleLogClick:I,handlePreviousLog:R,handleNextLog:$}=skr(w,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:F,isLoading:D}=XH(n.featuredTraceId??null),{data:V,isLoading:W}=pI(n.featuredTraceId??"",n.featuredSpanId??""),L=v.useCallback(()=>n.applyFilterTokens(C1r(y,n.filterTokens)),[y,n]),z=v.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),B=v.useCallback(X=>n.handleFeaturedChange({traceId:X,spanId:null}),[n]),M=v.useCallback((X,te)=>n.handleFeaturedChange({traceId:X,spanId:te}),[n]),G=v.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),U=v.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),P=v.useCallback(X=>n.handleFeaturedChange({spanId:X??null}),[n]),q=o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(wSe,{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(Wwe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx(zSr,{isLoading:S,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:L,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Lt,{width:"wide",height:"full",children:[q,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx($Sr,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return w.length===0&&!S&&!Z?o.jsxs(Lt,{width:"wide",height:"full",children:[q,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(VSr,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Lt,{width:"wide",height:"full",children:[q,o.jsx(MSr,{logCollapsed:i,listSlot:o.jsx(FSr,{logs:w,isLoading:S,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E,logIdMap:j,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(PSr,{log:N,onClose:z,onTraceClick:B,onSpanClick:M,onPrevious:R,onNext:$,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(ATt,{traceId:n.featuredTraceId,spans:F?.spans,isLoading:D,onClose:G,onSpanSelect:P,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(oSr,{spanId:n.featuredSpanId,span:V?.span,isLoading:W,onClose:U}):null})]})}function Wss({server:e}){const{paths:t,Link:n}=yn(),s=We().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=G6t(e),l=Object.values(i||{}),c=l.length,u=l.filter(p=>p.toolType==="agent").length,d=l.filter(p=>p.toolType==="workflow").length,f=om(e.name,50);return o.jsxs(me.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(me.NameCell,{children:f}),o.jsx(me.DescriptionCell,{children:a}),o.jsx(me.TextCell,{className:"text-center",children:u||""}),o.jsx(me.TextCell,{className:"text-center",children:c||""}),o.jsx(me.TextCell,{className:"text-center",children:d||""})]})}function Zss({mcpServers:e,isLoading:t,search:n=""}){const r=v.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(el,{columns:"auto 1fr auto auto auto"}):o.jsxs(me,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Name"}),o.jsx(me.TopCell,{children:"URL"}),o.jsx(me.TopCellSmart,{long:"Agents",short:o.jsx(rl,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(me.TopCellSmart,{long:"Tools",short:o.jsx(Gp,{}),tooltip:"Tools",className:"text-center"}),o.jsx(me.TopCellSmart,{long:"Workflows",short:o.jsx(_d,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(me.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(Wss,{server:s},s.id))]})}const Gss=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(xf,{}),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(ue,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Pa,{})]})})}),Qss=()=>{const{data:e=[],isLoading:t,error:n}=PZ(),[r,s]=v.useState("");return n&&gs(n)?o.jsx(lr,{children:o.jsx(Vs,{})}):n&&ys(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"MCP servers"})}):n?o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(lr,{children:o.jsx(Gss,{})}):o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(jf,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(Zss,{mcpServers:e,isLoading:t,search:r})]})},Yss=(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 Xss({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=yn(),i=v.useMemo(()=>Yss(e,t),[e,t]),l=v.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(el,{columns:"auto 1fr auto"}):o.jsxs(me,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Name"}),o.jsx(me.TopCell,{children:"Description"}),o.jsx(me.TopCellSmart,{long:"Agents",short:o.jsx(rl,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(me.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=om(c.id,50),d=om(c.description??"",200),f=c.agents.length;return o.jsxs(me.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(me.NameCell,{children:u}),o.jsx(me.DescriptionCell,{children:d}),o.jsx(me.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const Kss=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(xf,{}),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(ue,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Pa,{})]})})}),Jss=()=>{const e=We();return Rn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new r_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw De.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},eas=({toolId:e})=>{const{canExecute:t}=al(),n=t("tools"),{data:r={}}=km(),s=v.useMemo(()=>{for(const g of Object.values(r))if(g.tools){const y=Object.values(g.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=rDr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=Jss(),{requestContext:p}=_s();v.useEffect(()=>{if(l){const g=l instanceof Error?l.message:"Failed to load tool";De.error(`Error loading tool: ${g}`)}},[l]);const h=async(g,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:g,requestContext:b})},m=c?.inputSchema?um(lm(jx(c?.inputSchema))):Ss({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(At,{className:"h-8 w-48 mb-4"}),o.jsx(At,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(iTe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function tas({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}=mI(),{data:p={},isLoading:h,isError:m,error:g}=km(),{navigate:y,paths:b}=yn();v.useEffect(()=>{if(d){const _=f instanceof Error?f.message:"Failed to load tools";De.error(`Error loading tools: ${_}`)}},[d,f]),v.useEffect(()=>{if(m){const _=g instanceof Error?g.message:"Failed to load agents";De.error(`Error loading agents: ${_}`)}},[m,g]);const w=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(C=>{w.has(C.id)||w.set(C.id,C)})}),Object.values(c).forEach(_=>{w.has(_.id)||w.set(_.id,_)});const S=Array.from(w.values()).map(_=>({label:_.id,value:_.id})),k=_=>{t?t(_):_&&_!==e&&y(b.toolLink(_))};return o.jsx(Xl,{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 nas=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=v.useState({sseUrl:"",httpStreamUrl:""});if(v.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(dy,{children:o.jsx(ge,{as:"h1",variant:"header-md",className:"text-neutral3 font-medium py-20 text-center",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(dy,{isDivided:!0,children:[o.jsxs("div",{className:"px-8 py-12 mx-auto max-w-2xl w-full",children:[o.jsx(ge,{as:"h1",variant:"header-md",className:"text-neutral6 font-medium pb-4",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(fn,{icon:o.jsx(aTt,{className:"text-neutral6"}),className:"rounded-r-sm text-neutral4!",children:"Version"}),o.jsx(fn,{className:"rounded-l-sm text-neutral4!",children:t.version_detail.version})]}),o.jsx(ge,{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:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(fn,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ge,{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(ge,{className:"px-2 py-1 bg-surface4 rounded-lg",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(ya,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(fn,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ge,{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(ge,{className:"px-2 py-1 bg-surface4 rounded-lg",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(ya,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(fn,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",children:"CLI"}),children:"Command Line"}),o.jsx(ge,{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(ge,{className:"px-2 py-1 bg-surface4 rounded-lg",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(ya,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"h-full overflow-y-scroll border-l border-border1",children:o.jsx(ras,{server:t})})]})},ras=({server:e})=>{const{data:t={},isLoading:n}=G6t(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"p-5 overflow-y-scroll",children:[o.jsxs("div",{className:"text-neutral6 flex gap-2 items-center",children:[o.jsx(Ue,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(D_,{})}),o.jsx(ge,{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(aas,{tool:a,serverId:e.id},s)})})]})};function sas(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 aas=({tool:e,serverId:t})=>{const n=v.useRef(null),{Link:r,paths:s}=yn(),a=u8t[e.toolType||"tool"],i=sas(e._meta);return o.jsxs(Of,{onClick:()=>n.current?.click(),children:[o.jsx(Hvt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Cf,{children:[o.jsx(_f,{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(fn,{className:"text-[10px] py-0",children:"App"})]})}),o.jsx(Zp,{children:e.description})]})]})},ias=()=>{const{serverId:e}=dr(),{data:t=[],isLoading:n}=PZ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(nas,{isLoading:n,server:r})})};function oas(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 las=({toolId:e,serverId:t})=>{const{canExecute:n}=al(),r=n("tools"),s=We(),{data:a,isLoading:i,error:l}=Yje(t,e),{mutateAsync:c,isPending:u,data:d}=WQr(t,e),f=a?oas(a._meta):void 0,{data:p}=wt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=v.useCallback(async(y,b)=>await c(b),[c]);v.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";De.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(At,{className:"h-8 w-48 mb-4"}),o.jsx(At,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let g;try{g=um(lm(a.inputSchema))}catch(y){console.error("Error processing input schema:",y),De.error("Failed to process tool input schema."),g=Ss({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-b border-border1 p-4",children:o.jsx(Z6t,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(iTe,{executionResult:d,isExecutingTool:u,zodInputSchema:g,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},cas=()=>{const{serverId:e,toolId:t}=dr(),{data:n,isLoading:r}=Yje(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(las,{toolId:t,serverId:e})})},UQe={agents:Os.AGENT,workflows:Os.WORKFLOW_RUN,tools:Os.TOOL};function uas(){const{data:e,isLoading:t,isError:n}=a1r(),{getTracesHref:r,getBucketTracesHref:s}=fI(),{Link:a}=yn(),i=bs();return o.jsx(Hwr,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:UQe[l]},c.tsMs,"1h"))},actions:l=>o.jsx($D,{href:r({rootEntityType:UQe[l]}),LinkComponent:a})})}function das(){const e=h1r(),t=m1r(),{getTracesHref:n}=fI(),{Link:r}=yn();return o.jsx(Zwr,{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 fas(){const{data:e,isLoading:t,isError:n}=kTt();return o.jsx(MD,{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 pas(){const{data:e,isLoading:t,isError:n}=n1r();return o.jsx(MD,{label:"Total Model Cost",value:e?.cost!=null?gg(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?gg(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function has(){const{data:e,isLoading:t,isError:n}=r1r();return o.jsx(MD,{label:"Total Tokens",value:e?.value!=null?yc(e.value):null,prevValue:e?.previousValue!=null?yc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function mas(){const{data:e,isLoading:t,isError:n}=f1r();return o.jsx(MD,{label:"Total Threads",value:e?.value!=null?yc(e.value):null,prevValue:e?.previousValue!=null?yc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function gas(){const{data:e,isLoading:t,isError:n}=p1r();return o.jsx(MD,{label:"Total Resources",value:e?.value!=null?yc(e.value):null,prevValue:e?.previousValue!=null?yc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function vas({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=>yas(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(Hwe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(qwe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function yas(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 bas(){const{data:e,isLoading:t,isError:n}=s1r(),{getTracesHref:r}=fI(),{Link:s}=yn();return o.jsx(Gwr,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Os.AGENT}),actions:o.jsx($D,{href:r({rootEntityType:Os.AGENT}),LinkComponent:s})})}function xas(){const{data:e,isLoading:t,isError:n}=o1r(),{getTracesHref:r}=fI(),{Link:s}=yn();return o.jsx(Ywr,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Os.AGENT,entityName:a.name}),actions:o.jsx($D,{href:r({rootEntityType:Os.AGENT}),LinkComponent:s})})}function was(){const{data:e,isLoading:t,isError:n}=d1r(),{getTracesHref:r}=fI(),{Link:s}=yn();return o.jsx(Jwr,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx($D,{href:r(),LinkComponent:s})})}const J8={agents:Os.AGENT,workflows:Os.WORKFLOW_RUN,tools:Os.TOOL};function Sas(){const{data:e,isLoading:t,isError:n}=i1r(),{getTracesHref:r,getLogsHref:s}=fI(),{Link:a}=yn();return o.jsx(e1r,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:J8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:J8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx($D,{href:r({rootEntityType:J8[i]}),LinkComponent:a}),o.jsx(qwr,{href:s({rootEntityType:J8[i],status:"error"}),LinkComponent:a})]})})}const kas=new Set(["ObservabilityStorageClickhouseVNext","ObservabilityStorageDuckDB","ObservabilityInMemory","ObservabilitySpanner"]),ise="period",e9="dateFrom",t9="dateTo";function Oas(){const[e,t]=ji(),n=e.get(ise),r=Mwr(n)?n:"24h",s=v.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(e9)),p=d(e.get(t9));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=v.useMemo(()=>Twr(e),[e.toString()]),i=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(ise):p.set(ise,d),d!=="custom"&&(p.delete(e9),p.delete(t9)),p},{replace:!0})},[t]),l=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(e9,d.from.toISOString()):p.delete(e9),d?.to?p.set(t9,d.to.toISOString()):p.delete(t9),p},{replace:!0})},[t]),c=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return Iwr(p,d),p},{replace:!0})},[t]),u=v.useRef(!1);return v.useEffect(()=>{if(u.current||(u.current=!0,Ewr(e)))return;const d=xTt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(Lwr,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(_as,{})})}function _as(){const[e]=ji(),{error:t,isLoading:n}=kTt(),{filterTokens:r,setFilterTokens:s}=QH(),[a,i]=v.useState(),{data:l,isLoading:c}=U4(),u=l?.observabilityStorageType,d=u?kas.has(u):!1,f=u==="ObservabilityInMemory",{data:p,isLoading:h}=NOe(),{data:m,isLoading:g}=IOe(),{data:y,isLoading:b}=ROe(),{data:w,isLoading:S}=AOe(),k=v.useMemo(()=>jwr({availableTags:p??[],availableEntityNames:m??[],availableServiceNames:y??[],availableEnvironments:w??[],loading:{tags:h,entityNames:g,serviceNames:b,environments:S}}),[p,m,y,w,h,g,b,S]),[_,C]=v.useState(()=>xTt()!==null),E=v.useCallback(()=>{_wr(e),C(!0),De.success("Filters setting for Metrics saved")},[e]),j=v.useCallback(()=>{Cwr(),C(!1),De.success("Filters setting for Metrics cleared up")},[]),N=v.useCallback(()=>{s([])},[s]),I=v.useCallback(()=>{const R=r.map($=>{const F=k.find(D=>D.id===$.fieldId);return F?F.kind==="text"?{fieldId:$.fieldId,value:""}:F.kind==="pick-multi"?F.multi?{fieldId:$.fieldId,value:[]}:{fieldId:$.fieldId,value:"Any"}:F.kind==="multi-select"?{fieldId:$.fieldId,value:[]}:$:$});s(R)},[k,r,s]);return t&&gs(t)?o.jsx(lr,{children:o.jsx(Vs,{})}):t&&ys(t)?o.jsx(lr,{children:o.jsx(Ds,{resource:"metrics"})}):t?o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Uwr,{}),o.jsx(Wwe,{fields:k,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(vas,{isLoading:n,filterFields:k,filterTokens:r,onFilterTokensChange:s,onClear:I,onRemoveAll:N,onSave:E,onRemoveSaved:_?j:void 0,autoFocusFilterFieldId:a})]}),c?null:d?o.jsxs("div",{className:"grid gap-8 content-start pb-10",children:[f&&o.jsx(In,{variant:"info",title:"Metrics are not persisted",children:o.jsx(In.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, or Spanner."})}),o.jsxs(Wpe,{children:[o.jsx(fas,{}),o.jsx(pas,{}),o.jsx(has,{}),o.jsx(mas,{}),o.jsx(gas,{})]}),o.jsxs(Wpe,{children:[o.jsx(bas,{}),o.jsx(xas,{}),o.jsx(was,{}),o.jsx(das,{}),o.jsx(Sas,{}),o.jsx(uas,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(xf,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Spanner, or in-memory storage for observability. Relational databases (PostgreSQL, LibSQL) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsxs(ue,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Pa,{})]})})})]})}function Cas(){const{paths:e}=yn(),{data:t,isLoading:n,error:r}=d8t(),{isCmsAvailable:s}=wI(),[a,i]=v.useState(""),l=t?.promptBlocks??[];return r&&gs(r)?o.jsx(lr,{children:o.jsx(Vs,{})}):r&&ys(r)?o.jsx(lr,{children:o.jsx(Ds,{resource:"prompt blocks"})}):r?o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load prompt blocks",message:r.message})}):l.length===0&&!n?o.jsx(lr,{children:o.jsx(PKr,{})}):o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(jf,{onSearch:i,label:"Filter prompts",placeholder:"Filter by name or description"})}),s&&o.jsxs(ue,{as:ci,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Fr,{}),"Create Prompt"]})]})}),o.jsx(RKr,{promptBlocks:l,isLoading:n,search:a})]})}function Eas(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx(kYr,{children:o.jsx(kve,{})})})})}const jas=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:pcn,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:ilt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Pa,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:qj,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:hlt,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:olt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Tas(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 max-w-3xl",children:jas.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group flex flex-col gap-3 rounded-lg border border-border1 bg-surface2 p-5 transition-colors hover:border-accent1 hover:bg-surface3",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"h-5 w-5 text-icon3 group-hover:text-accent1 transition-colors"}),o.jsx("span",{className:"text-ui-md font-medium text-text1",children:e.title}),e.external&&o.jsx(Pa,{className:"h-3.5 w-3.5 text-icon3 ml-auto opacity-0 group-hover:opacity-100 transition-opacity"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function Nas(){const{data:e={},isLoading:t,error:n}=eh(),[r,s]=v.useState(""),[a,i]=v.useState("all");if(n&&gs(n))return o.jsx(lr,{children:o.jsx(Vs,{})});if(n&&ys(n))return o.jsx(lr,{children:o.jsx(Ds,{resource:"scorers"})});if(n)return o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(lr,{children:o.jsx(BXr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(qXr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(zXr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Ias(){const{scorerId:e}=dr(),[t,n]=ji(),r=t.get("scoreId")??void 0,[s,a]=v.useState(r),[i,l]=v.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=DXr(e),{data:d={},isLoading:f,error:p}=km(),{isLoading:h,error:m}=Uy(),{data:g=[],isLoading:y,error:b,isFetchingNextPage:w,hasNextPage:S,setEndOfListElement:k}=MXr({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),_=v.useMemo(()=>c?.agentIds?.filter(B=>d[B]).map(B=>({value:B,label:d[B].name,type:"AGENT"}))||[],[c?.agentIds,d]),C=v.useMemo(()=>c?.workflowIds?.map(B=>({value:B,label:B,type:"WORKFLOW"}))||[],[c?.workflowIds]),E=v.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},..._,...C],[_,C]),j=t.get("entity")??"all",N=E.find(B=>B.value===j);N&&N.value!==i?.value&&l(N),v.useEffect(()=>{if(u){const B=u instanceof Error?u.message:"Failed to load scorer";De.error(`Error loading scorer: ${B}`)}},[u]),v.useEffect(()=>{if(p){const B=p instanceof Error?p.message:"Failed to load agents";De.error(`Error loading agents: ${B}`)}},[p]),v.useEffect(()=>{if(m){const B=m instanceof Error?m.message:"Failed to load workflows";De.error(`Error loading workflows: ${B}`)}},[m]);const I=B=>{B?.value&&n(M=>{const G=new URLSearchParams(M);return G.set("entity",B.value),G})};v.useEffect(()=>{const B=t.get("scoreId")??void 0;if(B===s)return;if(!B){a(void 0);return}g.find(G=>G.id===B)&&a(B)},[t,g]);const R=v.useCallback(B=>{a(B||void 0),n(M=>{const G=new URLSearchParams(M);return B?G.set("scoreId",B):G.delete("scoreId"),G})},[n]);if(!c)return null;const $=gs(u)||gs(p)||gs(m),F=u&&ys(u),D=!$&&!F&&(u||p||m),V=!y&&g.length===0,W=i?.value!=="all",L=c?.scorer?.source==="stored"?o.jsx(Ty,{owner:"scorer-detail",children:o.jsxs(ue,{variant:"default",as:ci,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(em,{})," Edit"]})}):null;if($||F||D||V&&!W){const B=(u instanceof Error?u.message:void 0)??(p instanceof Error?p.message:void 0)??(m instanceof Error?m.message:void 0)??"An unexpected error occurred";return o.jsxs(Lt,{width:"wide",height:"full",children:[L,o.jsx(Lt.MainArea,{isCentered:!0,children:$?o.jsx(Vs,{}):F?o.jsx(Ds,{resource:"scorers"}):D?o.jsx(Fi,{title:"Failed to load scorer",message:B}):o.jsx(IXr,{})})]})}return o.jsxs(Lt,{width:"wide",children:[L,o.jsx(Lt.TopArea,{children:o.jsx(AXr,{selectedEntity:i,entityOptions:E,onEntityChange:I,onReset:()=>{n(B=>{const M=new URLSearchParams(B);return M.set("entity","all"),M})},isLoading:y||f||h})}),o.jsx(NXr,{scores:g,isLoading:y,selectedScoreId:s,isFetchingNextPage:w,hasNextPage:S,setEndOfListElement:k,onScoreClick:R,errorMsg:b?.message})]})}function Aas({label:e,description:t,htmlFor:n,className:r,children:s}){return o.jsxs("div",{className:K("flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",r),"data-slot":"settings-row",children:[o.jsxs("div",{children:[n?o.jsx(Rt,{htmlFor:n,className:"text-sm font-medium",children:e}):o.jsx("p",{className:"text-sm font-medium",children:e}),t&&o.jsx("p",{className:"text-sm text-neutral3",children:t})]}),s]})}const c9t=[{value:"dark",label:"Dark",Icon:Uun},{value:"light",label:"Light",Icon:Xdn},{value:"system",label:"System",Icon:Olt}],Ras=e=>c9t.some(t=>t.value===e);function Pas({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex min-w-0 max-w-full 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 $as=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=Axe(),{theme:r,setTheme:s}=$N();return o.jsx(Lt,{width:"narrow",children:o.jsxs(Lt.MainArea,{className:"flex flex-col gap-5 mt-6",children:[o.jsx(she,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(Aas,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(ba,{value:r,onValueChange:a=>{Ras(a)&&s(a)},children:[o.jsx(wa,{id:"theme",className:"w-full sm:w-48",children:o.jsx(xa,{className:"inline-flex min-w-0 max-w-full items-center"})}),o.jsx(Sa,{children:c9t.map(a=>o.jsx(qr,{value:a.value,children:o.jsx(Pas,{option:a})},a.value))})]})})}),o.jsx(she,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(X6t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function Mas(){const[e]=ji(),t=bs(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(l9t,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function Das(e){return e.replace(/\/$/,"").split("/").pop()}function HZ({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 Las({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:"h-16 bg-surface3 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:"w-full h-full bg-cover thumb transition-scale 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:"hidden 2xl:flex text-neutral3 text-ui-md flex-wrap items-center gap-4 mt-3",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(rl,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Gp,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(_lt,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(eq,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(D_,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"flex items-center text-neutral3 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:"flex items-center gap-2 px-2 py-1 rounded bg-surface1 group-hover:bg-surface2 text-neutral3 transition-colors group-hover:text-neutral5",children:[o.jsx(iTt,{})," ",Das(a.githubUrl)]})})]},a.slug)})})}function Fas({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(iT,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(bc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(bc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(ue,{onClick:c,children:["Reset ",o.jsx(vs,{})]})]})}function zas(){const{data:e,isLoading:t}=FPr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=v.useState("all"),[l,c]=v.useState("all"),[u,d]=v.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(w=>{f.push({value:w,label:w})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(w=>{p.push({value:w,label:w})});const h=(w,S)=>{S==="tag"?i(w):S==="provider"&&c(w)},m=w=>{d(w)},g=()=>{i("all"),c("all"),d("")},y=n.filter(w=>!(u&&!w.title.toLowerCase().includes(u)&&!w.description.toLowerCase().includes(u)||a!=="all"&&!w.tags.includes(a)||l!=="all"&&!w.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(cs,{children:[o.jsx(qxe,{children:o.jsxs(hpt,{children:[o.jsx(Ue,{children:o.jsx(Hv,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(Fas,{selectedTag:a,onTagChange:w=>h(w,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:w=>h(w,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?g:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(Las,{templates:y,linkComponent:ci,className:"max-w-[80rem] mx-auto",isLoading:t})]})]})}const Bas="1.48.0-alpha.0";function Uas({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(kp,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(Ucn,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(HZ,{className:"space-y-4 text-neutral3 mb-8 content-center",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:"text-center space-y-2",children:[o.jsx("p",{className:"text-ui-md font-medium text-neutral5",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:"cursor-pointer text-neutral3 hover:text-neutral4 select-none text-center",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 p-3 bg-gray-100 dark:bg-gray-800 rounded text-xs overflow-auto max-h-60 text-left space-y-2",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"text-xs font-mono text-gray-700 dark:text-gray-300 mt-1 whitespace-pre-wrap wrap-break-word",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"cursor-pointer text-neutral3 hover:text-neutral4 select-none text-center",children:"Show Details"}),o.jsx("div",{className:"mt-4 p-3 bg-gray-100 dark:bg-gray-800 rounded text-xs font-mono overflow-auto max-h-60 text-left",children:o.jsx("div",{className:"whitespace-pre-wrap wrap-break-word",children:n})})]})]})}function qas({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(HZ,{children:o.jsxs("div",{className:"max-w-[40rem] my-4 p-4 lg:p-8 mx-auto gap-8 grid",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(Clt,{})]}),o.jsx(bc,{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] gap-4 items-start",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(Gt,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(v.Fragment,{children:[o.jsx(_O,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(_O,{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-t border-border1 pt-12 mt-3.5 relative",children:[o.jsx("div",{className:"absolute w-8 h-8 rounded-full bg-surface2 top-0 left-1/2 -translate-x-1/2 -translate-y-4 text-ui-sm text-neutral3 flex items-center justify-center",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(Y6t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ue,{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(Gt,{className:"w-4 h-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(hm,{})]})})]})})}function Vas({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(Hv,{}),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 lg:grid-cols-[1fr_1fr] gap-x-24",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:"shrink-0 mt-0.5",children:o.jsx(Mx,{className:"w-[1.1em] h-[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(Vye,{className:"w-[1em] h-[1em] text-neutral4"}),o.jsx("span",{className:"text-ui-md font-medium text-neutral5",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 px-1.5 py-0.5 rounded text-ui-sm 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:"flex items-center gap-2 mt-auto text-neutral3 text-ui-md hover:text-neutral5",children:[o.jsx(iTt,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(v1e,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Has({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=g=>g==="input"||g.endsWith(".input")||g.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(g)||/[0-9a-f]{8,}/.test(g)?!1:r?.allSteps?g in r.allSteps:!0,f=Object.entries(c).filter(([g,y])=>d(g)),p=f.length,h=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([g,y])=>({id:g,status:y?.status,description:y?.description,title:g.charAt(0).toUpperCase()+g.slice(1).replace(/-/g," "),isActive:i?.id===g}));return o.jsxs(HZ,{className:"space-y-6 text-neutral3 mb-8 content-center",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-lg font-semibold text-neutral5",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"mt-2 text-ui-sm text-neutral3",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"max-w-[30rem] w-full mx-auto px-6",children:o.jsx(qWn,{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(Kun,{}),l||"Something went wrong"]}),u&&o.jsx(UWn,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-center text-sm text-neutral3 grid gap-4 justify-items-center",children:[o.jsx(Gt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Was({name:e,installedEntities:t}){return o.jsxs(HZ,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Clt,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-center text-neutral3 ",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(v1e,{data:t})]})}function Zas(){const{templateSlug:e}=dr(),[t,n]=ji(),[r,s]=v.useState(""),[a,i]=v.useState(""),[l,c]=v.useState(""),[u,d]=v.useState({}),[f,p]=v.useState([]),[h,m]=v.useState(null),[g,y]=v.useState(!1),[b,w]=v.useState(""),[S,k]=v.useState(!1),[_,C]=v.useState(!1),[E,j]=v.useState([]),{data:N,isLoading:I}=zPr({repoOrSlug:e,owner:"mastra-ai"}),$=Bas?.includes("beta")??!1?"beta":"main",{data:F,isLoading:D}=BPr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:$}),{data:V,isLoading:W}=UPr(),{mutateAsync:L,isPending:z}=qPr(),{mutateAsync:B}=VPr(),{streamInstall:M,streamResult:G,isStreaming:U}=WPr(V),{observeInstall:P,streamResult:q,isStreaming:Z}=ZPr(V);v.useEffect(()=>{const ne=t.get("runId");ne&&!g&&!h&&!U&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),w(ne),B({runId:ne}).then(ce=>{const pe=ce.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:ve,errors:ye}=pe.result.validationResults,Se=`Template installation completed but ${ve} validation issue${ve>1?"s":""} remain unresolved.`;m(Se),j(ye||[])}else{const ve=pe?.result?.message||pe?.result?.error||"Template installation failed";m(typeof ve=="string"?ve:String(ve))}}).catch(ce=>{console.error("❌ Failed to fetch run details:",ce),m("Failed to retrieve installation status after reload")}))},[t,g,h,U,Z,B]),v.useEffect(()=>{const ne=t.get("runId"),ce=t.get("resume"),pe=t.get("provider");if(ne&&ce==="true"&&pe&&!U&&!Z&&!S&&!_&&V){w(ne),k(!0);try{B({runId:ne}).then(le=>{if(le.snapshot?.status==="running")return P.mutateAsync({runId:ne})}).then(()=>{n(le=>{const ve=new URLSearchParams(le);return ve.delete("resume"),ve})}).catch(le=>{console.error("❌ Failed to resume template installation:",le),le.message?.includes("404")||le.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(le){console.error("❌ Auto-resume failed with error:",le),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,U,Z,S,_,V,B,P,n]);const X=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],te=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Gp,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(rl,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(eq,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Iv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(hN,{})}],J=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");v.useEffect(()=>{F&&d(F)},[F]),v.useEffect(()=>{const ne=G||q;ne?.phase==="error"&&ne?.error&&m(typeof ne.error=="string"?ne.error:String(ne.error))},[G?.phase,G?.error,q?.phase,q?.error]);const ee=ne=>{s(ne)},ae=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),de=async()=>{const ne=Object.entries(u).reduce((ce,[pe,le])=>(le===""&&ce.push(pe),ce),[]);if(ne.length>0){p(ne);return}if(N){m(null),y(!1),w(""),C(!0);try{const pe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:$,slug:N.slug,variables:u},{runId:le}=await L({});w(le),n(ve=>{const ye=new URLSearchParams(ve);return ye.set("runId",le),ye.set("resume","true"),ye.set("provider",r||"openai"),ye}),await M.mutateAsync({inputData:pe,selectedModel:{provider:a,modelId:l},runId:le})}catch(ce){C(!1),m(ce?.message||"Template installation failed"),console.error("Template installation failed",ce)}}},Y=ne=>{const{name:ce,value:pe}=ne.target;pe.trim()===""?p(le=>[...le,ce]):p(le=>le.filter(ve=>ve!==ce)),d(le=>({...le,[ce]:pe}))};return o.jsx(cs,{children:o.jsx("div",{className:K("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"p-6 w-full max-w-[80rem] mx-auto grid gap-y-4",children:[o.jsx(Vas,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(U||Z)&&o.jsx(Has,{name:N.title,streamResult:Z?q:G,runId:b,workflowInfo:V}),g&&o.jsx(Was,{name:N.title,installedEntities:J,linkComponent:ci}),h&&o.jsx(Uas,{errorMsg:h,validationErrors:E.length>0?E:G?.validationResults?.errors||q?.validationResults?.errors}),!U&&!Z&&!g&&!h&&o.jsx(qas,{providerOptions:X,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:de,handleVariableChange:Y,isLoadingEnvVars:D||W,isInstalling:z,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const Gas=()=>{const{toolId:e,agentId:t}=dr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(gKr,{toolId:e,agentId:t})})},Qas=()=>{const{toolId:e}=dr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(eas,{toolId:e})})};function Yas(){const{traceId:e}=dr(),[t,n]=ji(),r=bs(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=v.useState(s??null),[d,f]=v.useState(),[p,h]=v.useState(i),[m,g]=v.useState(0),[y,b]=v.useState(!1),{data:w,isLoading:S,error:k}=XH(e),_=v.useMemo(()=>w?.spans??[],[w?.spans]),C=v.useMemo(()=>_.find(ae=>ae.parentSpanId==null),[_]),{data:E,isLoading:j}=pI(e,c??"");v.useEffect(()=>g(0),[e,c]);const{data:N,isLoading:I}=eh(),{data:R,isLoading:$}=o8t({traceId:e,spanId:c??void 0,page:m}),[F,D]=v.useState(0);v.useEffect(()=>D(0),[e,c]);const{data:V,isLoading:W}=J8t({traceId:e,page:F});v.useEffect(()=>{if(l&&R?.scores&&!d){const ae=R.scores.find(de=>de.id===l);ae&&f(ae)}},[l,R?.scores,d]);const L=v.useCallback(ae=>{const de=new URLSearchParams(t);for(const[Y,ne]of Object.entries(ae))ne===null||ne===""?de.delete(Y):de.set(Y,ne);n(de,{replace:!0})},[t,n]),z=v.useCallback(ae=>{const de=ae??null,Y=de===c;u(de),Y||(f(void 0),h("details"),L({spanId:de,tab:null,scoreId:null}))},[c,L]),B=v.useCallback(()=>{u(null),f(void 0),h("details"),L({spanId:null,tab:null,scoreId:null})},[L]),M=v.useCallback(ae=>{u(ae),f(void 0),h("details"),L({spanId:ae,tab:null,scoreId:null})},[L]),{handlePreviousSpan:G,handleNextSpan:U}=KH(_,c,M),P=v.useCallback(ae=>{const de=ae;h(de),f(void 0),L({tab:de==="details"?null:de,scoreId:null})},[L]),q=v.useCallback(ae=>{f(ae),L({scoreId:ae.id})},[L]),Z=v.useCallback(()=>{f(void 0),L({scoreId:null})},[L]),X=v.useCallback(()=>{r("/observability")},[r]),te=v.useCallback(()=>{h("scoring"),C&&c!==C.spanId?(u(C.spanId),f(void 0),L({spanId:C.spanId,tab:"scoring",scoreId:null})):L({tab:"scoring"})},[C,c,L]),J=C?o.jsx(Ty,{owner:"trace-detail",children:o.jsxs($r,{children:[o.jsxs(ue,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:te,children:[o.jsx(Pln,{}),"Evaluate"]}),o.jsxs(ue,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(fd,{}),"Save"]})]})}):null,ee=C?o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{children:o.jsx(TTt,{rootSpan:C,numOfCol:3})})}):null;return k?o.jsxs(Lt,{height:"full",children:[J,ee&&o.jsx(Lt.TopArea,{children:ee}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(RTt,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Lt,{children:[J,ee&&o.jsx(Lt.TopArea,{children:ee}),o.jsx(G8t,{rootSpanId:C?.spanId,traceId:e,isOpen:y,onClose:()=>b(!1)}),o.jsxs("div",{className:K("grid h-full min-h-0 gap-4 overflow-hidden items-start mt-4",c?"grid-cols-[2fr_3fr]":"grid-cols-[1fr]"),children:[o.jsx(TOe,{traceId:e,spans:_,isLoading:S,onClose:X,onSpanSelect:z,onEvaluateTrace:te,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!S&&o.jsxs("div",{className:K("grid gap-4 max-h-full min-h-0 overflow-auto",d?"grid-rows-[1fr_1fr]":"grid-rows-[1fr]"),children:[o.jsx(YH,{traceId:e,spanId:c,span:E?.span,isLoading:j,onClose:B,onPrevious:G,onNext:U,activeTab:p,onTabChange:P,feedbackTabBadge:V?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(Y8t,{feedbackData:V,onPageChange:D,isLoadingFeedbackData:W}),scoringTabBadge:R?.pagination?.total??void 0,scoringTabSlot:({span:ae,traceId:de,spanId:Y})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(K8t,{traceId:de,isTopLevelSpan:!ae.parentSpanId,spanId:Y,entityType:ae.attributes?.agentId||ae.entityType===Os.AGENT?"Agent":ae.attributes?.workflowId||ae.entityType===Os.WORKFLOW_RUN?"Workflow":void 0,scorers:N,isLoadingScorers:I}),o.jsx(X8t,{scoresData:R,onPageChange:g,isLoadingScoresData:$,onScoreSelect:q})]})}),d&&o.jsx(sTe,{score:d,onClose:Z})]})]})]})}function Xas(){const{data:e,isLoading:t,error:n}=Uy(),[r,s]=v.useState("");return n&&gs(n)?o.jsx(lr,{children:o.jsx(Vs,{})}):n&&ys(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"workflows"})}):n?o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(lr,{children:o.jsx(Qzr,{})}):o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(jf,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(ue,{as:ci,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(o3,{}),"Schedules"]})]})}),o.jsx(Gzr,{workflows:e||{},isLoading:t,search:r})]})}const Kas={active:"bg-accent1",paused:"bg-accent3"},Jas={active:"text-accent1",paused:"text-accent3"},u9t=({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 ${Kas[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${Jas[e]}`,children:e})]}),Rj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),sP=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 d9t({status:e}){const{icon:t,color:n}=eis(e);return o.jsxs("span",{className:`inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function eis(e){switch(e){case"success":return{icon:o.jsx(Js,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(vs,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Gt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(ZU,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(xf,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(sO,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const qQe="auto auto auto auto 1fr";function tis(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 nis(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 ris=3e4,sis=5*6e4;function ais({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=yn();return t?o.jsx(el,{columns:qQe}):e.length===0?o.jsx(ge,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(me,{columns:qQe,className:"min-w-0",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Run"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{children:"Started"}),o.jsx(me.TopCell,{children:"Duration"}),o.jsx(me.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=nis(u),f=`Scheduled ${Rj(c.scheduledFireAt)} — published ${Rj(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),g=!p&&m>ris&&m<=sis,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),w=o.jsx("span",{className:b?"text-accent1 font-mono text-ui-sm whitespace-nowrap":"text-neutral3 font-mono text-ui-sm whitespace-nowrap",children:c.runId}),S=o.jsxs(o.Fragment,{children:[o.jsx(me.Cell,{height:"compact",children:w}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm text-accent2",children:[o.jsx(kp,{size:14}),"publish failed"]}):c.run?o.jsx(d9t,{status:c.run.status}):o.jsx("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm text-neutral3",children:"pending"}),h?o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(kp,{size:14})})}),o.jsx(Bn,{children:h})]}):null]})}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:sP(c.actualFireAt)}),g?o.jsxs(Wn,{children:[o.jsx(zn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(kp,{size:14})})}),o.jsxs(Bn,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(me.Cell,{height:"compact",children:c.run?o.jsx("span",{children:tis(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(me.Cell,{height:"compact",children:" "})]});return b?o.jsx(me.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:S},y):o.jsx(me.RowStatic,{children:S},y)}),o.jsx(me.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const iis=e=>{const t=We();return wt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},VQe=25,ois=e=>{const t=We(),{inView:n,setRef:r}=P_(),s=R1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:VQe,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<VQe))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return v.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},lis=e=>{const t=We(),n=Hr();return Rn({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"]}),De.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{De.error(r.message)}})};function n9({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 uppercase tracking-wide",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function cis(){const{scheduleId:e}=dr(),{paths:t}=yn(),{data:n,error:r}=iis(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=ois(e),d=lis(e);if(r&&gs(r))return o.jsx(lr,{children:o.jsx(Vs,{})});if(r&&ys(r))return o.jsx(lr,{children:o.jsx(Ds,{resource:"schedules"})});if(r)return o.jsx(lr,{children:o.jsx(Fi,{title:"Failed to load schedule",message:r.message})});const f=n?.target.type==="workflow"?n.target.workflowId:void 0;return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{className:"justify-end",children:o.jsxs(Lt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(ue,{as:ci,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(Ec,{}),"Back to schedules"]}),f?o.jsx(ue,{as:ci,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ue,{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(Elt,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Pp,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid gap-6 h-full overflow-hidden grid-cols-[minmax(0,20rem)_1fr]",children:[o.jsxs("div",{className:"flex flex-col gap-4 border border-border1 rounded-md p-4 h-fit",children:[o.jsx(n9,{label:"Workflow",children:f?o.jsx(ci,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):"—"}),o.jsxs(n9,{label:"Cron",children:[o.jsx("code",{className:"font-mono text-ui-md",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 ml-2 text-ui-sm",children:n.timezone}):null]}),o.jsx(n9,{label:"Status",children:o.jsx(u9t,{status:n.status})}),o.jsx(n9,{label:"Next fire",children:o.jsx("span",{title:Rj(n.nextFireAt),children:sP(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ge,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Fi,{title:"Failed to load trigger history",message:i.message}):o.jsx(ais,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const HQe="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function uis({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=yn(),a=v.useMemo(()=>{const i=n.toLowerCase();return i?e.filter(l=>l.id.toLowerCase().includes(i)||l.target.workflowId.toLowerCase().includes(i)):e},[e,n]);return t?o.jsx(el,{columns:HQe}):o.jsxs(me,{columns:HQe,variant:"striped",className:"min-w-0",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Workflow"}),o.jsx(me.TopCell,{children:"Schedule ID"}),o.jsx(me.TopCell,{children:"Cron"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{children:"Next fire"}),o.jsx(me.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(me.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(me.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(me.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(me.NameCell,{children:i.target.workflowId}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"block truncate font-mono text-ui-smd text-neutral3",title:i.id,children:i.id})}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"font-mono text-ui-sm",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(me.Cell,{height:"compact",children:o.jsx(u9t,{status:i.status})}),o.jsx(me.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:Rj(i.nextFireAt),children:sP(i.nextFireAt)})}),o.jsx(me.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(d9t,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:Rj(i.lastFireAt),children:i.lastFireAt?sP(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:Rj(i.lastFireAt),children:sP(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function dis({workflowId:e}={}){const{data:t,isLoading:n,error:r}=Bxe(e?{workflowId:e}:{}),[s,a]=v.useState("");return r?o.jsx(Fi,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid grid-rows-[auto_1fr] gap-4 h-full overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(jf,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(uis,{schedules:t??[],isLoading:n,search:s})})]})}function fis(){const[e]=ji(),t=e.get("workflowId")??void 0,{error:n}=Bxe(t?{workflowId:t}:{});return n&&gs(n)?o.jsx(lr,{children:o.jsx(Vs,{})}):n&&ys(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"schedules"})}):o.jsx(Lt,{children:o.jsx("div",{className:"h-full",children:o.jsx(dis,{workflowId:t})})})}function pis({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=b_e({stepGraph:e}),[a,i]=v.useState(!1),[l,c,u]=IAt(r),[d]=AAt(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=K$t({edges:d,workflowName:n,stepGraph:e});return v.useEffect(()=>{t&&setTimeout(()=>{i(!0)},500)},[t]),o.jsx("div",{className:"w-full h-full relative bg-surface1",children:a?o.jsxs(NAt,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(ECe,{position:"bottom-left"}),o.jsx(PAt,{variant:ty.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"w-full h-full flex items-center justify-center",children:o.jsx(Gt,{})})})}function his(){const{stepDetail:e,closeStepDetail:t}=yW();return e?o.jsxs("div",{className:"flex flex-col h-full","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border1 bg-surface1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(Lde,{className:"w-4 h-4",style:{color:xu.map}}),e.type==="nested-graph"&&o.jsx(_d,{className:"w-4 h-4",style:{color:xu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ge,{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(ge,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"p-1 hover:bg-surface3 rounded transition-colors","aria-label":"Close",children:o.jsx(vs,{className:"w-4 h-4 text-neutral3"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(nP,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(y_e,{children:o.jsx(pis,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function mis(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function gis(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 vis({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"space-y-5 rounded-lg border border-border1 bg-surface4 p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ge,{as:"p",variant:"ui-md",className:"flex items-center gap-2 text-neutral6 font-semibold",children:[o.jsx(Ue,{children:o.jsx(ZU,{})}),"Step suspended"]}),o.jsx(fn,{variant:"warning",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?um(lm(jx(i.resumeSchema))):rp(ur(),DT());return o.jsx(yis,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function yis({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=v.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ge,{as:"p",variant:"ui-md",className:"text-neutral6 font-medium truncate",children:e.stepId}),n&&o.jsx(ge,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ge,{as:"p",variant:"ui-sm",className:"flex items-center gap-2 text-neutral3",children:[o.jsx(Ue,{children:o.jsx(Vun,{})}),"The step is asking"]}),o.jsxs(Mp,{open:a,onOpenChange:i,children:[o.jsxs(mf,{className:"flex w-full items-center justify-between gap-2 rounded-lg border border-border1 bg-surface3 px-3 py-2.5",children:[o.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[o.jsx(Ue,{children:o.jsx(la,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ge,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:gis(e.suspendPayload,e.stepId)})]}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:mis(e.suspendPayload)})]}),o.jsx(gf,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Qr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ge,{as:"p",variant:"ui-sm",className:"flex items-center gap-2 text-neutral3",children:[o.jsx(Ue,{children:o.jsx(Zun,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(zB,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Pp,{}),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 bis(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=v.useContext(Rl),{runId:a}=dr(),i=BAt(e,r??""),l=tPr(),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:"absolute top-2 right-2 z-20 w-[380px] max-w-[calc(100%-1rem)] max-h-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 duration-300",children:o.jsx(vis,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const xis=e=>e.includes("."),wis=e=>e==="input"||e.endsWith(".input"),Sis=1;function kis(e){return`${Number((e/1e3).toPrecision(3))}s`}function Ois(e,t){const n=Object.entries(e).filter(([i])=>!wis(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,Sis);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:xis(i)}})}const _is=({status:e})=>o.jsxs(Ue,{children:[e==="success"&&o.jsx(w0r,{className:"text-accent1"}),e==="failed"&&o.jsx(k0r,{className:"text-accent2"}),e==="suspended"&&o.jsx(ZU,{className:"text-accent3"}),e==="waiting"&&o.jsx(Dde,{className:"text-accent5"}),e==="skipped"&&o.jsx(Dde,{className:"text-icon3"}),e==="running"&&o.jsx(ia,{className:"text-accent6 animate-spin"})]}),Cis={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function f9t(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const WQe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},Eis=e=>{const t=e;return q$t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},jis=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=Eis(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(_is,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ue,{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(Hdn,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(uU,{indicators:c,className:"shrink-0"})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"block min-w-0 max-w-full justify-self-stretch overflow-hidden text-ellipsis whitespace-nowrap text-left text-neutral6",children:f9t(e.stepId)}),o.jsx("div",{className:"relative h-2 min-w-0 rounded bg-surface4",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 ${Cis[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ue,{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(qdn,{})})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"w-20 justify-self-end text-right text-neutral3 tabular-nums",children:kis(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function Tis(){const{steps:e}=l4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=JH(),[a,i]=v.useState(()=>Date.now()),[l,c]=v.useState(!1),[u,d]=v.useState(null),f=v.useRef(null);mwe(f,{enabled:!l});const p=Ois(e,a),h=p.some(m=>m.isRunning);return v.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),v.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden rounded-studio-panel border border-border1/50 bg-surface3 p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(ge,{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:"rounded-md p-1 text-neutral3 transition-colors hover:bg-surface4 hover:text-neutral6",children:o.jsx(Na,{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,g)=>o.jsx(jis,{row:m,index:g,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:WQe(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:WQe(y.step.output)})},`timeline-item-${m.stepId}-${g}`))})]})}),o.jsx(br,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(qAt,{data:u.data,title:`${f9t(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const Nis=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=yW();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(J$t,{workflowId:e,workflow:t,isLoading:n}),o.jsx(bis,{}),o.jsx(Tis,{})]})}),r&&o.jsx("div",{className:"w-[420px] min-h-0 overflow-hidden border-l border-border1",children:o.jsx(his,{})})]})},ZQe=()=>{const{workflowId:e}=dr(),{data:t,isLoading:n,error:r}=e4(e);return r&&gs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})}):r&&ys(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"workflows"})}):o.jsx(k_e,{children:o.jsx(Nis,{workflowId:e,workflow:t??void 0,isLoading:n})})};function Iis(e,t){if(e==null)return{};var n,r,s=Wgt(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 Dve(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 Ais(e){if(Array.isArray(e))return Dve(e)}function Ris(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Pis(e,t){if(e){if(typeof e=="string")return Dve(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)?Dve(e,t):void 0}}function $is(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
772
772
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Lve(e){return Ais(e)||Ris(e)||Pis(e)||$is()}function YM(e){"@babel/helpers - typeof";return YM=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},YM(e)}function Mis(e,t){if(YM(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(YM(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Dis(e){var t=Mis(e,"string");return YM(t)=="symbol"?t:t+""}function p9t(e,t,n){return(t=Dis(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function GQe(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 KE(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?GQe(Object(n),!0).forEach(function(r){p9t(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):GQe(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Lis(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 ose={};function Fis(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return ose[t]||(ose[t]=Lis(e)),ose[t]}function zis(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=Fis(r);return s.reduce(function(a,i){return KE(KE({},a),n[i])},t)}function QQe(e){return e.join(" ")}function Bis(e,t){var n=0;return function(r){return n+=1,r.map(function(s,a){return h9t({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(a)})})}}function h9t(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=Bis(n,a),p;if(!a)p=KE(KE({},l),{},{className:QQe(l.className)});else{var h=Object.keys(n).reduce(function(b,w){return w.split(".").forEach(function(S){b.includes(S)||b.push(S)}),b},[]),m=l.className&&l.className.includes("token")?["token"]:[],g=l.className&&m.concat(l.className.filter(function(b){return!h.includes(b)}));p=KE(KE({},l),{},{className:QQe(g)||void 0,style:zis(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return Le.createElement(u,SO({key:i},p),y)}}const Uis=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var qis=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function YQe(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 Sw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?YQe(Object(n),!0).forEach(function(r){p9t(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):YQe(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var Vis=/\n/g;function His(e){return e.match(Vis)}function Wis(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map(function(s,a){var i=a+n;return Le.createElement("span",{key:"line-".concat(a),className:"react-syntax-highlighter-line-number",style:typeof r=="function"?r(i):r},"".concat(i,`
773
773
  `))})}function Zis(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 Le.createElement("code",{style:Object.assign({},n,s)},Wis({lines:t.replace(/\n$/,"").split(`
774
774
  `),style:i,startingLineNumber:l}))}function Gis(e){return"".concat(e.toString().length,".25em")}function m9t(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 g9t(e,t,n){var r={display:"inline-block",minWidth:Gis(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,a=Sw(Sw({},r),s);return a}function mF(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?Sw({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(Lve(m.className.trim().split(/\s+/)),Lve(u)):u,n&&a){var g=g9t(r,n,s);t.unshift(m9t(n,g))}return f&d&&(m.style=Sw({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function v9t(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(mF({children:[s],className:Lve(new Set(t))}));else if(s.children){var a=t.concat(s.properties.className);v9t(s.children,a).forEach(function(i){return n.push(i)})}}return n}function Qis(e,t,n,r,s,a,i,l,c){var u,d=v9t(e.value),f=[],p=-1,h=0;function m(_,C){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return mF({children:_,lineNumber:C,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:E,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function g(_,C){if(r&&C&&s){var E=g9t(l,C,i);_.unshift(m9t(C,E))}return _}function y(_,C){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||E.length>0?m(_,C,E):g(_,C)}for(var b=function(){var C=d[h],E=C.children[0].value,j=His(E);if(j){var N=E.split(`