@mastra/deployer-cloud 1.78.0-alpha.6 → 1.78.0-alpha.7

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-DH5BGEHl.js","./index-cjUvcuG5.js","./engine-compile-CUTZfOIo.js","./index-2BQyy0xI.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-DSQaR0Yq.js","./html-C2L_23MC.js","./javascript-ySlJ1b_l.js","./css-BPhBrDlE.js","./CodeDiff.es-ru6KxWJp.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-BIZ7yKXS.js","./index-CWg8N3LT.js","./engine-compile-CUTZfOIo.js","./index-2BQyy0xI.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-DSQaR0Yq.js","./html-C2L_23MC.js","./javascript-ySlJ1b_l.js","./css-BPhBrDlE.js","./CodeDiff.es-5hTLX2Rv.js"])))=>i.map(i=>d[i]);
2
2
  import{_ as Ai}from"./preload-helper-PPVm8Dsz.js";function xGt(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in e)){const i=Object.getOwnPropertyDescriptor(r,s);i&&Object.defineProperty(e,s,i.get?i:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function Iv(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _ne={exports:{}},yR={};var QMe;function bGt(){if(QMe)return yR;QMe=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,s,i){var o=null;if(i!==void 0&&(o=""+i),s.key!==void 0&&(o=""+s.key),"key"in s){i={};for(var l in s)l!=="key"&&(i[l]=s[l])}else i=s;return s=i.ref,{$$typeof:e,type:r,key:o,ref:s!==void 0?s:null,props:i}}return yR.Fragment=t,yR.jsx=n,yR.jsxs=n,yR}var ZMe;function wGt(){return ZMe||(ZMe=1,_ne.exports=bGt()),_ne.exports}var a=wGt(),Tne={exports:{}},Kr={},WMe;function SGt(){if(WMe)return Kr;WMe=1;var e={env:{}};var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),p=Symbol.iterator;function m(D){return D===null||typeof D!="object"?null:(D=p&&D[p]||D["@@iterator"],typeof D=="function"?D:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,x={};function b(D,$,z){this.props=D,this.context=$,this.refs=x,this.updater=z||v}b.prototype.isReactComponent={},b.prototype.setState=function(D,$){if(typeof D!="object"&&typeof D!="function"&&D!=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,D,$,"setState")},b.prototype.forceUpdate=function(D){this.updater.enqueueForceUpdate(this,D,"forceUpdate")};function S(){}S.prototype=b.prototype;function k(D,$,z){this.props=D,this.context=$,this.refs=x,this.updater=z||v}var j=k.prototype=new S;j.constructor=k,y(j,b.prototype),j.isPureReactComponent=!0;var C=Array.isArray;function T(){}var _={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function E(D,$,z){var U=z.ref;return{$$typeof:t,type:D,key:$,ref:U!==void 0?U:null,props:z}}function A(D,$){return E(D.type,$,D.props)}function P(D){return typeof D=="object"&&D!==null&&D.$$typeof===t}function L(D){var $={"=":"=0",":":"=2"};return"$"+D.replace(/[=:]/g,function(z){return $[z]})}var F=/\/+/g;function Q(D,$){return typeof D=="object"&&D!==null&&D.key!=null?L(""+D.key):$.toString(36)}function q(D){switch(D.status){case"fulfilled":return D.value;case"rejected":throw D.reason;default:switch(typeof D.status=="string"?D.then(T,T):(D.status="pending",D.then(function($){D.status==="pending"&&(D.status="fulfilled",D.value=$)},function($){D.status==="pending"&&(D.status="rejected",D.reason=$)})),D.status){case"fulfilled":return D.value;case"rejected":throw D.reason}}throw D}function B(D,$,z,U,G){var ne=typeof D;(ne==="undefined"||ne==="boolean")&&(D=null);var X=!1;if(D===null)X=!0;else switch(ne){case"bigint":case"string":case"number":X=!0;break;case"object":switch(D.$$typeof){case t:case n:X=!0;break;case f:return X=D._init,B(X(D._payload),$,z,U,G)}}if(X)return G=G(D),X=U===""?"."+Q(D,0):U,C(G)?(z="",X!=null&&(z=X.replace(F,"$&/")+"/"),B(G,$,z,"",function(ue){return ue})):G!=null&&(P(G)&&(G=A(G,z+(G.key==null||D&&D.key===G.key?"":(""+G.key).replace(F,"$&/")+"/")+X)),$.push(G)),1;X=0;var ee=U===""?".":U+":";if(C(D))for(var re=0;re<D.length;re++)U=D[re],ne=ee+Q(U,re),X+=B(U,$,z,ne,G);else if(re=m(D),typeof re=="function")for(D=re.call(D),re=0;!(U=D.next()).done;)U=U.value,ne=ee+Q(U,re++),X+=B(U,$,z,ne,G);else if(ne==="object"){if(typeof D.then=="function")return B(q(D),$,z,U,G);throw $=String(D),Error("Objects are not valid as a React child (found: "+($==="[object Object]"?"object with keys {"+Object.keys(D).join(", ")+"}":$)+"). If you meant to render a collection of children, use an array instead.")}return X}function V(D,$,z){if(D==null)return D;var U=[],G=0;return B(D,U,"","",function(ne){return $.call(z,ne,G++)}),U}function W(D){if(D._status===-1){var $=D._result;$=$(),$.then(function(z){(D._status===0||D._status===-1)&&(D._status=1,D._result=z)},function(z){(D._status===0||D._status===-1)&&(D._status=2,D._result=z)}),D._status===-1&&(D._status=0,D._result=$)}if(D._status===1)return D._result.default;throw D._result}var M=typeof reportError=="function"?reportError:function(D){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var $=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof D=="object"&&D!==null&&typeof D.message=="string"?String(D.message):String(D),error:D});if(!window.dispatchEvent($))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",D);return}console.error(D)},K={map:V,forEach:function(D,$,z){V(D,function(){$.apply(this,arguments)},z)},count:function(D){var $=0;return V(D,function(){$++}),$},toArray:function(D){return V(D,function($){return $})||[]},only:function(D){if(!P(D))throw Error("React.Children.only expected to receive a single React element child.");return D}};return Kr.Activity=h,Kr.Children=K,Kr.Component=b,Kr.Fragment=r,Kr.Profiler=i,Kr.PureComponent=k,Kr.StrictMode=s,Kr.Suspense=u,Kr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=_,Kr.__COMPILER_RUNTIME={__proto__:null,c:function(D){return _.H.useMemoCache(D)}},Kr.cache=function(D){return function(){return D.apply(null,arguments)}},Kr.cacheSignal=function(){return null},Kr.cloneElement=function(D,$,z){if(D==null)throw Error("The argument must be a React element, but you passed "+D+".");var U=y({},D.props),G=D.key;if($!=null)for(ne in $.key!==void 0&&(G=""+$.key),$)!N.call($,ne)||ne==="key"||ne==="__self"||ne==="__source"||ne==="ref"&&$.ref===void 0||(U[ne]=$[ne]);var ne=arguments.length-2;if(ne===1)U.children=z;else if(1<ne){for(var X=Array(ne),ee=0;ee<ne;ee++)X[ee]=arguments[ee+2];U.children=X}return E(D.type,G,U)},Kr.createContext=function(D){return D={$$typeof:l,_currentValue:D,_currentValue2:D,_threadCount:0,Provider:null,Consumer:null},D.Provider=D,D.Consumer={$$typeof:o,_context:D},D},Kr.createElement=function(D,$,z){var U,G={},ne=null;if($!=null)for(U in $.key!==void 0&&(ne=""+$.key),$)N.call($,U)&&U!=="key"&&U!=="__self"&&U!=="__source"&&(G[U]=$[U]);var X=arguments.length-2;if(X===1)G.children=z;else if(1<X){for(var ee=Array(X),re=0;re<X;re++)ee[re]=arguments[re+2];G.children=ee}if(D&&D.defaultProps)for(U in X=D.defaultProps,X)G[U]===void 0&&(G[U]=X[U]);return E(D,ne,G)},Kr.createRef=function(){return{current:null}},Kr.forwardRef=function(D){return{$$typeof:c,render:D}},Kr.isValidElement=P,Kr.lazy=function(D){return{$$typeof:f,_payload:{_status:-1,_result:D},_init:W}},Kr.memo=function(D,$){return{$$typeof:d,type:D,compare:$===void 0?null:$}},Kr.startTransition=function(D){var $=_.T,z={};_.T=z;try{var U=D(),G=_.S;G!==null&&G(z,U),typeof U=="object"&&U!==null&&typeof U.then=="function"&&U.then(T,M)}catch(ne){M(ne)}finally{$!==null&&z.types!==null&&($.types=z.types),_.T=$}},Kr.unstable_useCacheRefresh=function(){return _.H.useCacheRefresh()},Kr.use=function(D){return _.H.use(D)},Kr.useActionState=function(D,$,z){return _.H.useActionState(D,$,z)},Kr.useCallback=function(D,$){return _.H.useCallback(D,$)},Kr.useContext=function(D){return _.H.useContext(D)},Kr.useDebugValue=function(){},Kr.useDeferredValue=function(D,$){return _.H.useDeferredValue(D,$)},Kr.useEffect=function(D,$){return _.H.useEffect(D,$)},Kr.useEffectEvent=function(D){return _.H.useEffectEvent(D)},Kr.useId=function(){return _.H.useId()},Kr.useImperativeHandle=function(D,$,z){return _.H.useImperativeHandle(D,$,z)},Kr.useInsertionEffect=function(D,$){return _.H.useInsertionEffect(D,$)},Kr.useLayoutEffect=function(D,$){return _.H.useLayoutEffect(D,$)},Kr.useMemo=function(D,$){return _.H.useMemo(D,$)},Kr.useOptimistic=function(D,$){return _.H.useOptimistic(D,$)},Kr.useReducer=function(D,$,z){return _.H.useReducer(D,$,z)},Kr.useRef=function(D){return _.H.useRef(D)},Kr.useState=function(D){return _.H.useState(D)},Kr.useSyncExternalStore=function(D,$,z){return _.H.useSyncExternalStore(D,$,z)},Kr.useTransition=function(){return _.H.useTransition()},Kr.version="19.2.7",Kr}var HMe;function eP(){return HMe||(HMe=1,Tne.exports=SGt()),Tne.exports}var g=eP();const Me=Iv(g),tP=xGt({__proto__:null,default:Me},[g]);var Ine={exports:{}},xR={},Ene={exports:{}},Nne={};var GMe;function kGt(){return GMe||(GMe=1,(function(e){function t(q,B){var V=q.length;q.push(B);e:for(;0<V;){var W=V-1>>>1,M=q[W];if(0<s(M,B))q[W]=B,q[V]=M,V=W;else break e}}function n(q){return q.length===0?null:q[0]}function r(q){if(q.length===0)return null;var B=q[0],V=q.pop();if(V!==B){q[0]=V;e:for(var W=0,M=q.length,K=M>>>1;W<K;){var D=2*(W+1)-1,$=q[D],z=D+1,U=q[z];if(0>s($,V))z<M&&0>s(U,$)?(q[W]=U,q[z]=V,W=z):(q[W]=$,q[D]=V,W=D);else if(z<M&&0>s(U,V))q[W]=U,q[z]=V,W=z;else break e}}return B}function s(q,B){var V=q.sortIndex-B.sortIndex;return V!==0?V:q.id-B.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var o=Date,l=o.now();e.unstable_now=function(){return o.now()-l}}var c=[],u=[],d=1,f=null,h=3,p=!1,m=!1,v=!1,y=!1,x=typeof setTimeout=="function"?setTimeout:null,b=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;function k(q){for(var B=n(u);B!==null;){if(B.callback===null)r(u);else if(B.startTime<=q)r(u),B.sortIndex=B.expirationTime,t(c,B);else break;B=n(u)}}function j(q){if(v=!1,k(q),!m)if(n(c)!==null)m=!0,C||(C=!0,P());else{var B=n(u);B!==null&&Q(j,B.startTime-q)}}var C=!1,T=-1,_=5,N=-1;function E(){return y?!0:!(e.unstable_now()-N<_)}function A(){if(y=!1,C){var q=e.unstable_now();N=q;var B=!0;try{e:{m=!1,v&&(v=!1,b(T),T=-1),p=!0;var V=h;try{t:{for(k(q),f=n(c);f!==null&&!(f.expirationTime>q&&E());){var W=f.callback;if(typeof W=="function"){f.callback=null,h=f.priorityLevel;var M=W(f.expirationTime<=q);if(q=e.unstable_now(),typeof M=="function"){f.callback=M,k(q),B=!0;break t}f===n(c)&&r(c),k(q)}else r(c);f=n(c)}if(f!==null)B=!0;else{var K=n(u);K!==null&&Q(j,K.startTime-q),B=!1}}break e}finally{f=null,h=V,p=!1}B=void 0}}finally{B?P():C=!1}}}var P;if(typeof S=="function")P=function(){S(A)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,F=L.port2;L.port1.onmessage=A,P=function(){F.postMessage(null)}}else P=function(){x(A,0)};function Q(q,B){T=x(function(){q(e.unstable_now())},B)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(q){q.callback=null},e.unstable_forceFrameRate=function(q){0>q||125<q?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):_=0<q?Math.floor(1e3/q):5},e.unstable_getCurrentPriorityLevel=function(){return h},e.unstable_next=function(q){switch(h){case 1:case 2:case 3:var B=3;break;default:B=h}var V=h;h=B;try{return q()}finally{h=V}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(q,B){switch(q){case 1:case 2:case 3:case 4:case 5:break;default:q=3}var V=h;h=q;try{return B()}finally{h=V}},e.unstable_scheduleCallback=function(q,B,V){var W=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0<V?W+V:W):V=W,q){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=V+M,q={id:d++,callback:B,priorityLevel:q,startTime:V,expirationTime:M,sortIndex:-1},V>W?(q.sortIndex=V,t(u,q),n(c)===null&&q===n(u)&&(v?(b(T),T=-1):v=!0,Q(j,V-W))):(q.sortIndex=M,t(c,q),m||p||(m=!0,C||(C=!0,P()))),q},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(q){var B=h;return function(){var V=h;h=B;try{return q.apply(this,arguments)}finally{h=V}}}})(Nne)),Nne}var KMe;function OGt(){return KMe||(KMe=1,Ene.exports=kGt()),Ene.exports}var Ane={exports:{}},qu={};var YMe;function jGt(){if(YMe)return qu;YMe=1;var e=eP();function t(c){var u="https://react.dev/errors/"+c;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var d=2;d<arguments.length;d++)u+="&args[]="+encodeURIComponent(arguments[d])}return"Minified React error #"+c+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(t(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},s=Symbol.for("react.portal");function i(c,u,d){var f=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:f==null?null:""+f,children:c,containerInfo:u,implementation:d}}var o=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 qu.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,qu.createPortal=function(c,u){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(t(299));return i(c,u,null,d)},qu.flushSync=function(c){var u=o.T,d=r.p;try{if(o.T=null,r.p=2,c)return c()}finally{o.T=u,r.p=d,r.d.f()}},qu.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))},qu.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},qu.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin),h=typeof u.integrity=="string"?u.integrity:void 0,p=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;d==="style"?r.d.S(c,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:f,integrity:h,fetchPriority:p}):d==="script"&&r.d.X(c,{crossOrigin:f,integrity:h,fetchPriority:p,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},qu.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)},qu.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})}},qu.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)},qu.requestFormReset=function(c){r.d.r(c)},qu.unstable_batchedUpdates=function(c,u){return c(u)},qu.useFormState=function(c,u,d){return o.H.useFormState(c,u,d)},qu.useFormStatus=function(){return o.H.useHostTransitionStatus()},qu.version="19.2.7",qu}var XMe;function Urt(){if(XMe)return Ane.exports;XMe=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(),Ane.exports=jGt(),Ane.exports}var JMe;function CGt(){if(JMe)return xR;JMe=1;var e={env:{}};var t=OGt(),n=eP(),r=Urt();function s(w){var O="https://react.dev/errors/"+w;if(1<arguments.length){O+="?args[]="+encodeURIComponent(arguments[1]);for(var I=2;I<arguments.length;I++)O+="&args[]="+encodeURIComponent(arguments[I])}return"Minified React error #"+w+"; visit "+O+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function i(w){return!(!w||w.nodeType!==1&&w.nodeType!==9&&w.nodeType!==11)}function o(w){var O=w,I=w;if(w.alternate)for(;O.return;)O=O.return;else{w=O;do O=w,(O.flags&4098)!==0&&(I=O.return),w=O.return;while(w)}return O.tag===3?I:null}function l(w){if(w.tag===13){var O=w.memoizedState;if(O===null&&(w=w.alternate,w!==null&&(O=w.memoizedState)),O!==null)return O.dehydrated}return null}function c(w){if(w.tag===31){var O=w.memoizedState;if(O===null&&(w=w.alternate,w!==null&&(O=w.memoizedState)),O!==null)return O.dehydrated}return null}function u(w){if(o(w)!==w)throw Error(s(188))}function d(w){var O=w.alternate;if(!O){if(O=o(w),O===null)throw Error(s(188));return O!==w?null:w}for(var I=w,R=O;;){var H=I.return;if(H===null)break;var J=H.alternate;if(J===null){if(R=H.return,R!==null){I=R;continue}break}if(H.child===J.child){for(J=H.child;J;){if(J===I)return u(H),w;if(J===R)return u(H),O;J=J.sibling}throw Error(s(188))}if(I.return!==R.return)I=H,R=J;else{for(var oe=!1,xe=H.child;xe;){if(xe===I){oe=!0,I=H,R=J;break}if(xe===R){oe=!0,R=H,I=J;break}xe=xe.sibling}if(!oe){for(xe=J.child;xe;){if(xe===I){oe=!0,I=J,R=H;break}if(xe===R){oe=!0,R=J,I=H;break}xe=xe.sibling}if(!oe)throw Error(s(189))}}if(I.alternate!==R)throw Error(s(190))}if(I.tag!==3)throw Error(s(188));return I.stateNode.current===I?w:O}function f(w){var O=w.tag;if(O===5||O===26||O===27||O===6)return w;for(w=w.child;w!==null;){if(O=f(w),O!==null)return O;w=w.sibling}return null}var h=Object.assign,p=Symbol.for("react.element"),m=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),x=Symbol.for("react.strict_mode"),b=Symbol.for("react.profiler"),S=Symbol.for("react.consumer"),k=Symbol.for("react.context"),j=Symbol.for("react.forward_ref"),C=Symbol.for("react.suspense"),T=Symbol.for("react.suspense_list"),_=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),E=Symbol.for("react.activity"),A=Symbol.for("react.memo_cache_sentinel"),P=Symbol.iterator;function L(w){return w===null||typeof w!="object"?null:(w=P&&w[P]||w["@@iterator"],typeof w=="function"?w:null)}var F=Symbol.for("react.client.reference");function Q(w){if(w==null)return null;if(typeof w=="function")return w.$$typeof===F?null:w.displayName||w.name||null;if(typeof w=="string")return w;switch(w){case y:return"Fragment";case b:return"Profiler";case x:return"StrictMode";case C:return"Suspense";case T:return"SuspenseList";case E:return"Activity"}if(typeof w=="object")switch(w.$$typeof){case v:return"Portal";case k:return w.displayName||"Context";case S:return(w._context.displayName||"Context")+".Consumer";case j:var O=w.render;return w=w.displayName,w||(w=O.displayName||O.name||"",w=w!==""?"ForwardRef("+w+")":"ForwardRef"),w;case _:return O=w.displayName||null,O!==null?O:Q(w.type)||"Memo";case N:O=w._payload,w=w._init;try{return Q(w(O))}catch{}}return null}var q=Array.isArray,B=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,V=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,W={pending:!1,data:null,method:null,action:null},M=[],K=-1;function D(w){return{current:w}}function $(w){0>K||(w.current=M[K],M[K]=null,K--)}function z(w,O){K++,M[K]=w.current,w.current=O}var U=D(null),G=D(null),ne=D(null),X=D(null);function ee(w,O){switch(z(ne,O),z(G,w),z(U,null),O.nodeType){case 9:case 11:w=(w=O.documentElement)&&(w=w.namespaceURI)?pMe(w):0;break;default:if(w=O.tagName,O=O.namespaceURI)O=pMe(O),w=mMe(O,w);else switch(w){case"svg":w=1;break;case"math":w=2;break;default:w=0}}$(U),z(U,w)}function re(){$(U),$(G),$(ne)}function ue(w){w.memoizedState!==null&&z(X,w);var O=U.current,I=mMe(O,w.type);O!==I&&(z(G,w),z(U,I))}function te(w){G.current===w&&($(U),$(G)),X.current===w&&($(X),pR._currentValue=W)}var ie,se;function ae(w){if(ie===void 0)try{throw Error()}catch(I){var O=I.stack.trim().match(/\n( *(at )?)/);ie=O&&O[1]||"",se=-1<I.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<I.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+ie+w+se}var he=!1;function ge(w,O){if(!w||he)return"";he=!0;var I=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var R={DetermineComponentFrameRoot:function(){try{if(O){var Lt=function(){throw Error()};if(Object.defineProperty(Lt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Lt,[])}catch(wt){var mt=wt}Reflect.construct(w,[],Lt)}else{try{Lt.call()}catch(wt){mt=wt}w.call(Lt.prototype)}}else{try{throw Error()}catch(wt){mt=wt}(Lt=w())&&typeof Lt.catch=="function"&&Lt.catch(function(){})}}catch(wt){if(wt&&mt&&typeof wt.stack=="string")return[wt.stack,mt.stack]}return[null,null]}};R.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var H=Object.getOwnPropertyDescriptor(R.DetermineComponentFrameRoot,"name");H&&H.configurable&&Object.defineProperty(R.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var J=R.DetermineComponentFrameRoot(),oe=J[0],xe=J[1];if(oe&&xe){var Qe=oe.split(`
@@ -254,7 +254,7 @@ Error message: ${Kct(n)}`,cause:n}),this[iut]=!0,this.value=t}static isInstance(
254
254
 
255
255
  attempted value: ${o}
256
256
  `+(l!==o?`result of cast: ${l}`:""))}return i}_cast(t,n){let r=t===void 0?t:this.transforms.reduce((s,i)=>i.call(this,s,t,this),t);return r===void 0&&(r=this.getDefault(n)),r}_validate(t,n={},r,s){let{path:i,originalValue:o=t,strict:l=this.spec.strict}=n,c=t;l||(c=this._cast(c,Object.assign({assert:!1},n)));let u=[];for(let d of Object.values(this.internalTests))d&&u.push(d);this.runTests({path:i,value:c,originalValue:o,options:n,tests:u},r,d=>{if(d.length)return s(d,c);this.runTests({path:i,value:c,originalValue:o,options:n,tests:this.tests},r,s)})}runTests(t,n,r){let s=!1,{tests:i,value:o,originalValue:l,path:c,options:u}=t,d=v=>{s||(s=!0,n(v,o))},f=v=>{s||(s=!0,r(v,o))},h=i.length,p=[];if(!h)return f([]);let m={value:o,originalValue:l,path:c,options:u,schema:this};for(let v=0;v<i.length;v++){const y=i[v];y(m,d,function(b){b&&(Array.isArray(b)?p.push(...b):p.push(b)),--h<=0&&f(p)})}}asNestedTest({key:t,index:n,parent:r,parentPath:s,originalParent:i,options:o}){const l=t??n;if(l==null)throw TypeError("Must include `key` or `index` for nested validations");const c=typeof l=="number";let u=r[l];const d=Object.assign({},o,{strict:!0,parent:r,value:u,originalValue:i[l],key:void 0,[c?"index":"key"]:l,path:c||l.includes(".")?`${s||""}[${c?l:`"${l}"`}]`:(s?`${s}.`:"")+t});return(f,h,p)=>this.resolve(d)._validate(u,d,h,p)}validate(t,n){var r;let s=this.resolve(Object.assign({},n,{value:t})),i=(r=n?.disableStackTrace)!=null?r:s.spec.disableStackTrace;return new Promise((o,l)=>s._validate(t,n,(c,u)=>{tm.isError(c)&&(c.value=u),l(c)},(c,u)=>{c.length?l(new tm(c,u,void 0,void 0,i)):o(u)}))}validateSync(t,n){var r;let s=this.resolve(Object.assign({},n,{value:t})),i,o=(r=n?.disableStackTrace)!=null?r:s.spec.disableStackTrace;return s._validate(t,Object.assign({},n,{sync:!0}),(l,c)=>{throw tm.isError(l)&&(l.value=c),l},(l,c)=>{if(l.length)throw new tm(l,t,void 0,void 0,o);i=c}),i}isValid(t,n){return this.validate(t,n).then(()=>!0,r=>{if(tm.isError(r))return!1;throw r})}isValidSync(t,n){try{return this.validateSync(t,n),!0}catch(r){if(tm.isError(r))return!1;throw r}}_getDefault(t){let n=this.spec.default;return n==null?n:typeof n=="function"?n.call(this,t):iE(n)}getDefault(t){return this.resolve(t||{})._getDefault(t)}default(t){return arguments.length===0?this._getDefault():this.clone({default:t})}strict(t=!0){return this.clone({strict:t})}nullability(t,n){const r=this.clone({nullable:t});return r.internalTests.nullable=tI({message:n,name:"nullable",test(s){return s===null?this.schema.spec.nullable:!0}}),r}optionality(t,n){const r=this.clone({optional:t});return r.internalTests.optionality=tI({message:n,name:"optionality",test(s){return s===void 0?this.schema.spec.optional:!0}}),r}optional(){return this.optionality(!0)}defined(t=Lb.defined){return this.optionality(!1,t)}nullable(){return this.nullability(!0)}nonNullable(t=Lb.notNull){return this.nullability(!1,t)}required(t=Lb.required){return this.clone().withMutation(n=>n.nonNullable(t).defined(t))}notRequired(){return this.clone().withMutation(t=>t.nullable().optional())}transform(t){let n=this.clone();return n.transforms.push(t),n}test(...t){let n;if(t.length===1?typeof t[0]=="function"?n={test:t[0]}:n=t[0]:t.length===2?n={name:t[0],test:t[1]}:n={name:t[0],message:t[1],test:t[2]},n.message===void 0&&(n.message=Lb.default),typeof n.test!="function")throw new TypeError("`test` is a required parameters");let r=this.clone(),s=tI(n),i=n.exclusive||n.name&&r.exclusiveTests[n.name]===!0;if(n.exclusive&&!n.name)throw new TypeError("Exclusive tests must provide a unique `name` identifying the test");return n.name&&(r.exclusiveTests[n.name]=!!n.exclusive),r.tests=r.tests.filter(o=>!(o.OPTIONS.name===n.name&&(i||o.OPTIONS.test===s.OPTIONS.test))),r.tests.push(s),r}when(t,n){!Array.isArray(t)&&typeof t!="string"&&(n=t,t=".");let r=this.clone(),s=ISt(t).map(i=>new WL(i));return s.forEach(i=>{i.isSibling&&r.deps.push(i.key)}),r.conditions.push(typeof n=="function"?new gVe(s,n):gVe.fromOptions(s,n)),r}typeError(t){let n=this.clone();return n.internalTests.typeError=tI({message:t,name:"typeError",skipAbsent:!0,test(r){return this.schema._typeCheck(r)?!0:this.createError({params:{type:this.schema.type}})}}),n}oneOf(t,n=Lb.oneOf){let r=this.clone();return t.forEach(s=>{r._whitelist.add(s),r._blacklist.delete(s)}),r.internalTests.whiteList=tI({message:n,name:"oneOf",skipAbsent:!0,test(s){let i=this.schema._whitelist,o=i.resolveAll(this.resolve);return o.includes(s)?!0:this.createError({params:{values:Array.from(i).join(", "),resolved:o}})}}),r}notOneOf(t,n=Lb.notOneOf){let r=this.clone();return t.forEach(s=>{r._blacklist.add(s),r._whitelist.delete(s)}),r.internalTests.blacklist=tI({message:n,name:"notOneOf",test(s){let i=this.schema._blacklist,o=i.resolveAll(this.resolve);return o.includes(s)?this.createError({params:{values:Array.from(i).join(", "),resolved:o}}):!0}}),r}strip(t=!0){let n=this.clone();return n.spec.strip=t,n}describe(t){const n=(t?this.resolve(t):this).clone(),{label:r,meta:s,optional:i,nullable:o}=n.spec;return{meta:s,label:r,optional:i,nullable:o,default:n.getDefault(t),type:n.type,oneOf:n._whitelist.describe(),notOneOf:n._blacklist.describe(),tests:n.tests.map(c=>({name:c.OPTIONS.name,params:c.OPTIONS.params})).filter((c,u,d)=>d.findIndex(f=>f.name===c.name)===u)}}};LC.prototype.__isYupSchema__=!0;for(const e of["validate","validateSync"])LC.prototype[`${e}At`]=function(t,n,r={}){const{parent:s,parentPath:i,schema:o}=Ztr(this,t,n,r.context);return o[e](s&&s[i],Object.assign({},r,{parent:s,path:t}))};for(const e of["equals","is"])LC.prototype[e]=LC.prototype.oneOf;for(const e of["not","nope"])LC.prototype[e]=LC.prototype.notOneOf;var Wtr=/^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/;function Htr(e){const t=Gtr(e);if(!t)return Date.parse?Date.parse(e):Number.NaN;if(t.z===void 0&&t.plusMinus===void 0)return new Date(t.year,t.month,t.day,t.hour,t.minute,t.second,t.millisecond).valueOf();let n=0;return t.z!=="Z"&&t.plusMinus!==void 0&&(n=t.hourOffset*60+t.minuteOffset,t.plusMinus==="+"&&(n=0-n)),Date.UTC(t.year,t.month,t.day,t.hour,t.minute+n,t.second,t.millisecond)}function Gtr(e){var t,n;const r=Wtr.exec(e);return r?{year:vb(r[1]),month:vb(r[2],1)-1,day:vb(r[3],1),hour:vb(r[4]),minute:vb(r[5]),second:vb(r[6]),millisecond:r[7]?vb(r[7].substring(0,3)):0,precision:(t=(n=r[7])==null?void 0:n.length)!=null?t:void 0,z:r[8]||void 0,plusMinus:r[9]||void 0,hourOffset:vb(r[10]),minuteOffset:vb(r[11])}:null}function vb(e,t=0){return Number(e)||t}var Ktr=new Date(""),Ytr=e=>Object.prototype.toString.call(e)==="[object Date]",Xtr=class LSt extends LC{constructor(){super({type:"date",check(t){return Ytr(t)&&!isNaN(t.getTime())}}),this.withMutation(()=>{this.transform((t,n,r)=>!r.spec.coerce||r.isType(t)||t===null?t:(t=Htr(t),isNaN(t)?LSt.INVALID_DATE:new Date(t)))})}prepareParam(t,n){let r;if(WL.isRef(t))r=t;else{let s=this.cast(t);if(!this._typeCheck(s))throw new TypeError(`\`${n}\` must be a Date or a value that can be \`cast()\` to a Date`);r=s}return r}min(t,n=Fpe.min){let r=this.prepareParam(t,"min");return this.test({message:n,name:"min",exclusive:!0,params:{min:t},skipAbsent:!0,test(s){return s>=this.resolve(r)}})}max(t,n=Fpe.max){let r=this.prepareParam(t,"max");return this.test({message:n,name:"max",exclusive:!0,params:{max:t},skipAbsent:!0,test(s){return s<=this.resolve(r)}})}};Xtr.INVALID_DATE=Ktr;function yVe(e,t){let n=e;for(const r of t)if(n=n[r],n===void 0)return;return n}function mD(e){if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}const eke=6048e5,Jtr=864e5,enr=6e4,tnr=36e5,nnr=1e3,xVe=Symbol.for("constructDateFrom");function Do(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&xVe in e?e[xVe](t):e instanceof Date?new e.constructor(t):new Date(t)}function Hs(e,t){return Do(t||e,e)}function du(e,t,n){const r=Hs(e,n?.in);return isNaN(t)?Do(n?.in||e,NaN):(t&&r.setDate(r.getDate()+t),r)}function Sv(e,t,n){const r=Hs(e,n?.in);if(isNaN(t))return Do(n?.in||e,NaN);if(!t)return r;const s=r.getDate(),i=Do(n?.in||e,r.getTime());i.setMonth(r.getMonth()+t+1,0);const o=i.getDate();return s>=o?i:(r.setFullYear(i.getFullYear(),i.getMonth(),s),r)}let rnr={};function L_(){return rnr}function mp(e,t){const n=L_(),r=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,s=Hs(e,t?.in),i=s.getDay(),o=(i<r?7:0)+i-r;return s.setDate(s.getDate()-o),s.setHours(0,0,0,0),s}function $0(e,t){return mp(e,{...t,weekStartsOn:1})}function zSt(e,t){const n=Hs(e,t?.in),r=n.getFullYear(),s=Do(n,0);s.setFullYear(r+1,0,4),s.setHours(0,0,0,0);const i=$0(s),o=Do(n,0);o.setFullYear(r,0,4),o.setHours(0,0,0,0);const l=$0(o);return n.getTime()>=i.getTime()?r+1:n.getTime()>=l.getTime()?r:r-1}function sA(e){const t=Hs(e),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+e-+n}function $P(e,...t){const n=Do.bind(null,e||t.find(r=>typeof r=="object"));return t.map(n)}function iA(e,t){const n=Hs(e,t?.in);return n.setHours(0,0,0,0),n}function Wy(e,t,n){const[r,s]=$P(n?.in,e,t),i=iA(r),o=iA(s),l=+i-sA(i),c=+o-sA(o);return Math.round((l-c)/Jtr)}function snr(e,t){const n=zSt(e,t),r=Do(e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),$0(r)}function Bpe(e,t,n){return du(e,t*7,n)}function inr(e,t,n){return Sv(e,t*12,n)}function onr(e,t){let n,r=t?.in;return e.forEach(s=>{!r&&typeof s=="object"&&(r=Do.bind(null,s));const i=Hs(s,r);(!n||n<i||isNaN(+i))&&(n=i)}),Do(r,n||NaN)}function anr(e,t){let n,r=t?.in;return e.forEach(s=>{!r&&typeof s=="object"&&(r=Do.bind(null,s));const i=Hs(s,r);(!n||n>i||isNaN(+i))&&(n=i)}),Do(r,n||NaN)}function qf(e,t,n){const[r,s]=$P(n?.in,e,t);return+iA(r)==+iA(s)}function tke(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function nke(e){return!(!tke(e)&&typeof e!="number"||isNaN(+Hs(e)))}function j5(e,t,n){const[r,s]=$P(n?.in,e,t),i=r.getFullYear()-s.getFullYear(),o=r.getMonth()-s.getMonth();return i*12+o}function lnr(e,t,n){const[r,s]=$P(n?.in,e,t),i=mp(r,n),o=mp(s,n),l=+i-sA(i),c=+o-sA(o);return Math.round((l-c)/eke)}function rke(e,t){const n=Hs(e,t?.in),r=n.getMonth();return n.setFullYear(n.getFullYear(),r+1,0),n.setHours(23,59,59,999),n}function Kf(e,t){const n=Hs(e,t?.in);return n.setDate(1),n.setHours(0,0,0,0),n}function FSt(e,t){const n=Hs(e,t?.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}function ske(e,t){const n=L_(),r=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,s=Hs(e,t?.in),i=s.getDay(),o=(i<r?-7:0)+6-(i-r);return s.setDate(s.getDate()+o),s.setHours(23,59,59,999),s}function BSt(e,t){return ske(e,{...t,weekStartsOn:1})}const cnr={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},unr=(e,t,n)=>{let r;const s=cnr[e];return typeof s=="string"?r=s:t===1?r=s.one:r=s.other.replace("{{count}}",t.toString()),n?.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function Roe(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}const dnr={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},fnr={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},hnr={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},pnr={date:Roe({formats:dnr,defaultWidth:"full"}),time:Roe({formats:fnr,defaultWidth:"full"}),dateTime:Roe({formats:hnr,defaultWidth:"full"})},mnr={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},gnr=(e,t,n,r)=>mnr[e];function ZR(e){return(t,n)=>{const r=n?.context?String(n.context):"standalone";let s;if(r==="formatting"&&e.formattingValues){const o=e.defaultFormattingWidth||e.defaultWidth,l=n?.width?String(n.width):o;s=e.formattingValues[l]||e.formattingValues[o]}else{const o=e.defaultWidth,l=n?.width?String(n.width):e.defaultWidth;s=e.values[l]||e.values[o]}const i=e.argumentCallback?e.argumentCallback(t):t;return s[i]}}const vnr={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},ynr={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},xnr={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},bnr={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},wnr={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},Snr={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},knr=(e,t)=>{const n=Number(e),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},Onr={ordinalNumber:knr,era:ZR({values:vnr,defaultWidth:"wide"}),quarter:ZR({values:ynr,defaultWidth:"wide",argumentCallback:e=>e-1}),month:ZR({values:xnr,defaultWidth:"wide"}),day:ZR({values:bnr,defaultWidth:"wide"}),dayPeriod:ZR({values:wnr,defaultWidth:"wide",formattingValues:Snr,defaultFormattingWidth:"wide"})};function WR(e){return(t,n={})=>{const r=n.width,s=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],i=t.match(s);if(!i)return null;const o=i[0],l=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?Cnr(l,f=>f.test(o)):jnr(l,f=>f.test(o));let u;u=e.valueCallback?e.valueCallback(c):c,u=n.valueCallback?n.valueCallback(u):u;const d=t.slice(o.length);return{value:u,rest:d}}}function jnr(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function Cnr(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function _nr(e){return(t,n={})=>{const r=t.match(e.matchPattern);if(!r)return null;const s=r[0],i=t.match(e.parsePattern);if(!i)return null;let o=e.valueCallback?e.valueCallback(i[0]):i[0];o=n.valueCallback?n.valueCallback(o):o;const l=t.slice(s.length);return{value:o,rest:l}}}const Tnr=/^(\d+)(th|st|nd|rd)?/i,Inr=/\d+/i,Enr={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},Nnr={any:[/^b/i,/^(a|c)/i]},Anr={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},Pnr={any:[/1/i,/2/i,/3/i,/4/i]},$nr={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},Rnr={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},Mnr={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Dnr={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},Lnr={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},znr={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},Fnr={ordinalNumber:_nr({matchPattern:Tnr,parsePattern:Inr,valueCallback:e=>parseInt(e,10)}),era:WR({matchPatterns:Enr,defaultMatchWidth:"wide",parsePatterns:Nnr,defaultParseWidth:"any"}),quarter:WR({matchPatterns:Anr,defaultMatchWidth:"wide",parsePatterns:Pnr,defaultParseWidth:"any",valueCallback:e=>e+1}),month:WR({matchPatterns:$nr,defaultMatchWidth:"wide",parsePatterns:Rnr,defaultParseWidth:"any"}),day:WR({matchPatterns:Mnr,defaultMatchWidth:"wide",parsePatterns:Dnr,defaultParseWidth:"any"}),dayPeriod:WR({matchPatterns:Lnr,defaultMatchWidth:"any",parsePatterns:znr,defaultParseWidth:"any"})},ike={code:"en-US",formatDistance:unr,formatLong:pnr,formatRelative:gnr,localize:Onr,match:Fnr,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Bnr(e,t){const n=Hs(e,t?.in);return Wy(n,FSt(n))+1}function oke(e,t){const n=Hs(e,t?.in),r=+$0(n)-+snr(n);return Math.round(r/eke)+1}function ake(e,t){const n=Hs(e,t?.in),r=n.getFullYear(),s=L_(),i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,o=Do(t?.in||e,0);o.setFullYear(r+1,0,i),o.setHours(0,0,0,0);const l=mp(o,t),c=Do(t?.in||e,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const u=mp(c,t);return+n>=+l?r+1:+n>=+u?r:r-1}function Vnr(e,t){const n=L_(),r=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,s=ake(e,t),i=Do(t?.in||e,0);return i.setFullYear(s,0,r),i.setHours(0,0,0,0),mp(i,t)}function lke(e,t){const n=Hs(e,t?.in),r=+mp(n,t)-+Vnr(n,t);return Math.round(r/eke)+1}function Xi(e,t){const n=e<0?"-":"",r=Math.abs(e).toString().padStart(t,"0");return n+r}const e1={y(e,t){const n=e.getFullYear(),r=n>0?n:1-n;return Xi(t==="yy"?r%100:r,t.length)},M(e,t){const n=e.getMonth();return t==="M"?String(n+1):Xi(n+1,2)},d(e,t){return Xi(e.getDate(),t.length)},a(e,t){const n=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];default:return n==="am"?"a.m.":"p.m."}},h(e,t){return Xi(e.getHours()%12||12,t.length)},H(e,t){return Xi(e.getHours(),t.length)},m(e,t){return Xi(e.getMinutes(),t.length)},s(e,t){return Xi(e.getSeconds(),t.length)},S(e,t){const n=t.length,r=e.getMilliseconds(),s=Math.trunc(r*Math.pow(10,n-3));return Xi(s,t.length)}},nI={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},bVe={G:function(e,t,n){const r=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});default:return n.era(r,{width:"wide"})}},y:function(e,t,n){if(t==="yo"){const r=e.getFullYear(),s=r>0?r:1-r;return n.ordinalNumber(s,{unit:"year"})}return e1.y(e,t)},Y:function(e,t,n,r){const s=ake(e,r),i=s>0?s:1-s;if(t==="YY"){const o=i%100;return Xi(o,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):Xi(i,t.length)},R:function(e,t){const n=zSt(e);return Xi(n,t.length)},u:function(e,t){const n=e.getFullYear();return Xi(n,t.length)},Q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(r);case"QQ":return Xi(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(r);case"qq":return Xi(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,t,n){const r=e.getMonth();switch(t){case"M":case"MM":return e1.M(e,t);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(e,t,n){const r=e.getMonth();switch(t){case"L":return String(r+1);case"LL":return Xi(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(e,t,n,r){const s=lke(e,r);return t==="wo"?n.ordinalNumber(s,{unit:"week"}):Xi(s,t.length)},I:function(e,t,n){const r=oke(e);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):Xi(r,t.length)},d:function(e,t,n){return t==="do"?n.ordinalNumber(e.getDate(),{unit:"date"}):e1.d(e,t)},D:function(e,t,n){const r=Bnr(e);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Xi(r,t.length)},E:function(e,t,n){const r=e.getDay();switch(t){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(e,t,n,r){const s=e.getDay(),i=(s-r.weekStartsOn+8)%7||7;switch(t){case"e":return String(i);case"ee":return Xi(i,2);case"eo":return n.ordinalNumber(i,{unit:"day"});case"eee":return n.day(s,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(s,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(s,{width:"short",context:"formatting"});default:return n.day(s,{width:"wide",context:"formatting"})}},c:function(e,t,n,r){const s=e.getDay(),i=(s-r.weekStartsOn+8)%7||7;switch(t){case"c":return String(i);case"cc":return Xi(i,t.length);case"co":return n.ordinalNumber(i,{unit:"day"});case"ccc":return n.day(s,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(s,{width:"narrow",context:"standalone"});case"cccccc":return n.day(s,{width:"short",context:"standalone"});default:return n.day(s,{width:"wide",context:"standalone"})}},i:function(e,t,n){const r=e.getDay(),s=r===0?7:r;switch(t){case"i":return String(s);case"ii":return Xi(s,t.length);case"io":return n.ordinalNumber(s,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(e,t,n){const s=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(s,{width:"narrow",context:"formatting"});default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(e,t,n){const r=e.getHours();let s;switch(r===12?s=nI.noon:r===0?s=nI.midnight:s=r/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(s,{width:"narrow",context:"formatting"});default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},B:function(e,t,n){const r=e.getHours();let s;switch(r>=17?s=nI.evening:r>=12?s=nI.afternoon:r>=4?s=nI.morning:s=nI.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(s,{width:"narrow",context:"formatting"});default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},h:function(e,t,n){if(t==="ho"){let r=e.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return e1.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getHours(),{unit:"hour"}):e1.H(e,t)},K:function(e,t,n){const r=e.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Xi(r,t.length)},k:function(e,t,n){let r=e.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):Xi(r,t.length)},m:function(e,t,n){return t==="mo"?n.ordinalNumber(e.getMinutes(),{unit:"minute"}):e1.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getSeconds(),{unit:"second"}):e1.s(e,t)},S:function(e,t){return e1.S(e,t)},X:function(e,t,n){const r=e.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return SVe(r);case"XXXX":case"XX":return QO(r);default:return QO(r,":")}},x:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"x":return SVe(r);case"xxxx":case"xx":return QO(r);default:return QO(r,":")}},O:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+wVe(r,":");default:return"GMT"+QO(r,":")}},z:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+wVe(r,":");default:return"GMT"+QO(r,":")}},t:function(e,t,n){const r=Math.trunc(+e/1e3);return Xi(r,t.length)},T:function(e,t,n){return Xi(+e,t.length)}};function wVe(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),s=Math.trunc(r/60),i=r%60;return i===0?n+String(s):n+String(s)+t+Xi(i,2)}function SVe(e,t){return e%60===0?(e>0?"-":"+")+Xi(Math.abs(e)/60,2):QO(e,t)}function QO(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),s=Xi(Math.trunc(r/60),2),i=Xi(r%60,2);return n+s+t+i}const kVe=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});default:return t.date({width:"full"})}},VSt=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});default:return t.time({width:"full"})}},Unr=(e,t)=>{const n=e.match(/(P+)(p+)?/)||[],r=n[1],s=n[2];if(!s)return kVe(e,t);let i;switch(r){case"P":i=t.dateTime({width:"short"});break;case"PP":i=t.dateTime({width:"medium"});break;case"PPP":i=t.dateTime({width:"long"});break;default:i=t.dateTime({width:"full"});break}return i.replace("{{date}}",kVe(r,t)).replace("{{time}}",VSt(s,t))},Vpe={p:VSt,P:Unr},qnr=/^D+$/,Qnr=/^Y+$/,Znr=["D","DD","YY","YYYY"];function USt(e){return qnr.test(e)}function qSt(e){return Qnr.test(e)}function Upe(e,t,n){const r=Wnr(e,t,n);if(console.warn(r),Znr.includes(e))throw new RangeError(r)}function Wnr(e,t,n){const r=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const Hnr=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Gnr=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Knr=/^'([^]*?)'?$/,Ynr=/''/g,Xnr=/[a-zA-Z]/;function _k(e,t,n){const r=L_(),s=n?.locale??r.locale??ike,i=n?.firstWeekContainsDate??n?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=n?.weekStartsOn??n?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,l=Hs(e,n?.in);if(!nke(l))throw new RangeError("Invalid time value");let c=t.match(Gnr).map(d=>{const f=d[0];if(f==="p"||f==="P"){const h=Vpe[f];return h(d,s.formatLong)}return d}).join("").match(Hnr).map(d=>{if(d==="''")return{isToken:!1,value:"'"};const f=d[0];if(f==="'")return{isToken:!1,value:Jnr(d)};if(bVe[f])return{isToken:!0,value:d};if(f.match(Xnr))throw new RangeError("Format string contains an unescaped latin alphabet character `"+f+"`");return{isToken:!1,value:d}});s.localize.preprocessor&&(c=s.localize.preprocessor(l,c));const u={firstWeekContainsDate:i,weekStartsOn:o,locale:s};return c.map(d=>{if(!d.isToken)return d.value;const f=d.value;(!n?.useAdditionalWeekYearTokens&&qSt(f)||!n?.useAdditionalDayOfYearTokens&&USt(f))&&Upe(f,t,String(e));const h=bVe[f[0]];return h(l,f,s.localize,u)}).join("")}function Jnr(e){const t=e.match(Knr);return t?t[1].replace(Ynr,"'"):e}function err(e,t){const n=Hs(e,t?.in),r=n.getFullYear(),s=n.getMonth(),i=Do(n,0);return i.setFullYear(r,s+1,0),i.setHours(0,0,0,0),i.getDate()}function trr(){return Object.assign({},L_())}function nrr(e,t){const n=Hs(e,t?.in).getDay();return n===0?7:n}function rrr(e){return Math.trunc(+Hs(e)/1e3)}function srr(e,t){const n=Hs(e,t?.in),r=n.getMonth();return n.setFullYear(n.getFullYear(),r+1,0),n.setHours(0,0,0,0),Hs(n,t?.in)}function irr(e,t){const n=Hs(e,t?.in);return lnr(srr(n,t),Kf(n,t),t)+1}function qpe(e,t){return+Hs(e)>+Hs(t)}function QSt(e,t){return+Hs(e)<+Hs(t)}function orr(e,t){const n=arr(t)?new t(0):Do(t,0);return n.setFullYear(e.getFullYear(),e.getMonth(),e.getDate()),n.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()),n}function arr(e){return typeof e=="function"&&e.prototype?.constructor===e}const lrr=10;class ZSt{subPriority=0;validate(t,n){return!0}}class crr extends ZSt{constructor(t,n,r,s,i){super(),this.value=t,this.validateValue=n,this.setValue=r,this.priority=s,i&&(this.subPriority=i)}validate(t,n){return this.validateValue(t,this.value,n)}set(t,n,r){return this.setValue(t,n,this.value,r)}}class urr extends ZSt{priority=lrr;subPriority=-1;constructor(t,n){super(),this.context=t||(r=>Do(n,r))}set(t,n){return n.timestampIsSet?t:Do(t,orr(t,this.context))}}class Di{run(t,n,r,s){const i=this.parse(t,n,r,s);return i?{setter:new crr(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class drr extends Di{priority=140;parse(t,n,r){switch(n){case"G":case"GG":case"GGG":return r.era(t,{width:"abbreviated"})||r.era(t,{width:"narrow"});case"GGGGG":return r.era(t,{width:"narrow"});default:return r.era(t,{width:"wide"})||r.era(t,{width:"abbreviated"})||r.era(t,{width:"narrow"})}}set(t,n,r){return n.era=r,t.setFullYear(r,0,1),t.setHours(0,0,0,0),t}incompatibleTokens=["R","u","t","T"]}const wl={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},My={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function Sl(e,t){return e&&{value:t(e.value),rest:e.rest}}function za(e,t){const n=t.match(e);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function Dy(e,t){const n=t.match(e);if(!n)return null;if(n[0]==="Z")return{value:0,rest:t.slice(1)};const r=n[1]==="+"?1:-1,s=n[2]?parseInt(n[2],10):0,i=n[3]?parseInt(n[3],10):0,o=n[5]?parseInt(n[5],10):0;return{value:r*(s*tnr+i*enr+o*nnr),rest:t.slice(n[0].length)}}function WSt(e){return za(wl.anyDigitsSigned,e)}function dl(e,t){switch(e){case 1:return za(wl.singleDigit,t);case 2:return za(wl.twoDigits,t);case 3:return za(wl.threeDigits,t);case 4:return za(wl.fourDigits,t);default:return za(new RegExp("^\\d{1,"+e+"}"),t)}}function xQ(e,t){switch(e){case 1:return za(wl.singleDigitSigned,t);case 2:return za(wl.twoDigitsSigned,t);case 3:return za(wl.threeDigitsSigned,t);case 4:return za(wl.fourDigitsSigned,t);default:return za(new RegExp("^-?\\d{1,"+e+"}"),t)}}function cke(e){switch(e){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;default:return 0}}function HSt(e,t){const n=t>0,r=n?t:1-t;let s;if(r<=50)s=e||100;else{const i=r+50,o=Math.trunc(i/100)*100,l=e>=i%100;s=e+o-(l?100:0)}return n?s:1-s}function GSt(e){return e%400===0||e%4===0&&e%100!==0}class frr extends Di{priority=130;incompatibleTokens=["Y","R","u","w","I","i","e","c","t","T"];parse(t,n,r){const s=i=>({year:i,isTwoDigitYear:n==="yy"});switch(n){case"y":return Sl(dl(4,t),s);case"yo":return Sl(r.ordinalNumber(t,{unit:"year"}),s);default:return Sl(dl(n.length,t),s)}}validate(t,n){return n.isTwoDigitYear||n.year>0}set(t,n,r){const s=t.getFullYear();if(r.isTwoDigitYear){const o=HSt(r.year,s);return t.setFullYear(o,0,1),t.setHours(0,0,0,0),t}const i=!("era"in n)||n.era===1?r.year:1-r.year;return t.setFullYear(i,0,1),t.setHours(0,0,0,0),t}}class hrr extends Di{priority=130;parse(t,n,r){const s=i=>({year:i,isTwoDigitYear:n==="YY"});switch(n){case"Y":return Sl(dl(4,t),s);case"Yo":return Sl(r.ordinalNumber(t,{unit:"year"}),s);default:return Sl(dl(n.length,t),s)}}validate(t,n){return n.isTwoDigitYear||n.year>0}set(t,n,r,s){const i=ake(t,s);if(r.isTwoDigitYear){const l=HSt(r.year,i);return t.setFullYear(l,0,s.firstWeekContainsDate),t.setHours(0,0,0,0),mp(t,s)}const o=!("era"in n)||n.era===1?r.year:1-r.year;return t.setFullYear(o,0,s.firstWeekContainsDate),t.setHours(0,0,0,0),mp(t,s)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]}class prr extends Di{priority=130;parse(t,n){return xQ(n==="R"?4:n.length,t)}set(t,n,r){const s=Do(t,0);return s.setFullYear(r,0,4),s.setHours(0,0,0,0),$0(s)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]}class mrr extends Di{priority=130;parse(t,n){return xQ(n==="u"?4:n.length,t)}set(t,n,r){return t.setFullYear(r,0,1),t.setHours(0,0,0,0),t}incompatibleTokens=["G","y","Y","R","w","I","i","e","c","t","T"]}class grr extends Di{priority=120;parse(t,n,r){switch(n){case"Q":case"QQ":return dl(n.length,t);case"Qo":return r.ordinalNumber(t,{unit:"quarter"});case"QQQ":return r.quarter(t,{width:"abbreviated",context:"formatting"})||r.quarter(t,{width:"narrow",context:"formatting"});case"QQQQQ":return r.quarter(t,{width:"narrow",context:"formatting"});default:return r.quarter(t,{width:"wide",context:"formatting"})||r.quarter(t,{width:"abbreviated",context:"formatting"})||r.quarter(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=1&&n<=4}set(t,n,r){return t.setMonth((r-1)*3,1),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]}class vrr extends Di{priority=120;parse(t,n,r){switch(n){case"q":case"qq":return dl(n.length,t);case"qo":return r.ordinalNumber(t,{unit:"quarter"});case"qqq":return r.quarter(t,{width:"abbreviated",context:"standalone"})||r.quarter(t,{width:"narrow",context:"standalone"});case"qqqqq":return r.quarter(t,{width:"narrow",context:"standalone"});default:return r.quarter(t,{width:"wide",context:"standalone"})||r.quarter(t,{width:"abbreviated",context:"standalone"})||r.quarter(t,{width:"narrow",context:"standalone"})}}validate(t,n){return n>=1&&n<=4}set(t,n,r){return t.setMonth((r-1)*3,1),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]}class yrr extends Di{incompatibleTokens=["Y","R","q","Q","L","w","I","D","i","e","c","t","T"];priority=110;parse(t,n,r){const s=i=>i-1;switch(n){case"M":return Sl(za(wl.month,t),s);case"MM":return Sl(dl(2,t),s);case"Mo":return Sl(r.ordinalNumber(t,{unit:"month"}),s);case"MMM":return r.month(t,{width:"abbreviated",context:"formatting"})||r.month(t,{width:"narrow",context:"formatting"});case"MMMMM":return r.month(t,{width:"narrow",context:"formatting"});default:return r.month(t,{width:"wide",context:"formatting"})||r.month(t,{width:"abbreviated",context:"formatting"})||r.month(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=0&&n<=11}set(t,n,r){return t.setMonth(r,1),t.setHours(0,0,0,0),t}}class xrr extends Di{priority=110;parse(t,n,r){const s=i=>i-1;switch(n){case"L":return Sl(za(wl.month,t),s);case"LL":return Sl(dl(2,t),s);case"Lo":return Sl(r.ordinalNumber(t,{unit:"month"}),s);case"LLL":return r.month(t,{width:"abbreviated",context:"standalone"})||r.month(t,{width:"narrow",context:"standalone"});case"LLLLL":return r.month(t,{width:"narrow",context:"standalone"});default:return r.month(t,{width:"wide",context:"standalone"})||r.month(t,{width:"abbreviated",context:"standalone"})||r.month(t,{width:"narrow",context:"standalone"})}}validate(t,n){return n>=0&&n<=11}set(t,n,r){return t.setMonth(r,1),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]}function brr(e,t,n){const r=Hs(e,n?.in),s=lke(r,n)-t;return r.setDate(r.getDate()-s*7),Hs(r,n?.in)}class wrr extends Di{priority=100;parse(t,n,r){switch(n){case"w":return za(wl.week,t);case"wo":return r.ordinalNumber(t,{unit:"week"});default:return dl(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,r,s){return mp(brr(t,r,s),s)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]}function Srr(e,t,n){const r=Hs(e,n?.in),s=oke(r,n)-t;return r.setDate(r.getDate()-s*7),r}class krr extends Di{priority=100;parse(t,n,r){switch(n){case"I":return za(wl.week,t);case"Io":return r.ordinalNumber(t,{unit:"week"});default:return dl(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,r){return $0(Srr(t,r))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]}const Orr=[31,28,31,30,31,30,31,31,30,31,30,31],jrr=[31,29,31,30,31,30,31,31,30,31,30,31];class Crr extends Di{priority=90;subPriority=1;parse(t,n,r){switch(n){case"d":return za(wl.date,t);case"do":return r.ordinalNumber(t,{unit:"date"});default:return dl(n.length,t)}}validate(t,n){const r=t.getFullYear(),s=GSt(r),i=t.getMonth();return s?n>=1&&n<=jrr[i]:n>=1&&n<=Orr[i]}set(t,n,r){return t.setDate(r),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","Q","w","I","D","i","e","c","t","T"]}class _rr extends Di{priority=90;subpriority=1;parse(t,n,r){switch(n){case"D":case"DD":return za(wl.dayOfYear,t);case"Do":return r.ordinalNumber(t,{unit:"date"});default:return dl(n.length,t)}}validate(t,n){const r=t.getFullYear();return GSt(r)?n>=1&&n<=366:n>=1&&n<=365}set(t,n,r){return t.setMonth(0,r),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]}function uke(e,t,n){const r=L_(),s=n?.weekStartsOn??n?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,i=Hs(e,n?.in),o=i.getDay(),c=(t%7+7)%7,u=7-s,d=t<0||t>6?t-(o+u)%7:(c+u)%7-(o+u)%7;return du(i,d,n)}class Trr extends Di{priority=90;parse(t,n,r){switch(n){case"E":case"EE":case"EEE":return r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"});case"EEEEE":return r.day(t,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"});default:return r.day(t,{width:"wide",context:"formatting"})||r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=0&&n<=6}set(t,n,r,s){return t=uke(t,r,s),t.setHours(0,0,0,0),t}incompatibleTokens=["D","i","e","c","t","T"]}class Irr extends Di{priority=90;parse(t,n,r,s){const i=o=>{const l=Math.floor((o-1)/7)*7;return(o+s.weekStartsOn+6)%7+l};switch(n){case"e":case"ee":return Sl(dl(n.length,t),i);case"eo":return Sl(r.ordinalNumber(t,{unit:"day"}),i);case"eee":return r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"});case"eeeee":return r.day(t,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"});default:return r.day(t,{width:"wide",context:"formatting"})||r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=0&&n<=6}set(t,n,r,s){return t=uke(t,r,s),t.setHours(0,0,0,0),t}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]}class Err extends Di{priority=90;parse(t,n,r,s){const i=o=>{const l=Math.floor((o-1)/7)*7;return(o+s.weekStartsOn+6)%7+l};switch(n){case"c":case"cc":return Sl(dl(n.length,t),i);case"co":return Sl(r.ordinalNumber(t,{unit:"day"}),i);case"ccc":return r.day(t,{width:"abbreviated",context:"standalone"})||r.day(t,{width:"short",context:"standalone"})||r.day(t,{width:"narrow",context:"standalone"});case"ccccc":return r.day(t,{width:"narrow",context:"standalone"});case"cccccc":return r.day(t,{width:"short",context:"standalone"})||r.day(t,{width:"narrow",context:"standalone"});default:return r.day(t,{width:"wide",context:"standalone"})||r.day(t,{width:"abbreviated",context:"standalone"})||r.day(t,{width:"short",context:"standalone"})||r.day(t,{width:"narrow",context:"standalone"})}}validate(t,n){return n>=0&&n<=6}set(t,n,r,s){return t=uke(t,r,s),t.setHours(0,0,0,0),t}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]}function Nrr(e,t,n){const r=Hs(e,n?.in),s=nrr(r,n),i=t-s;return du(r,i,n)}class Arr extends Di{priority=90;parse(t,n,r){const s=i=>i===0?7:i;switch(n){case"i":case"ii":return dl(n.length,t);case"io":return r.ordinalNumber(t,{unit:"day"});case"iii":return Sl(r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"}),s);case"iiiii":return Sl(r.day(t,{width:"narrow",context:"formatting"}),s);case"iiiiii":return Sl(r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"}),s);default:return Sl(r.day(t,{width:"wide",context:"formatting"})||r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"}),s)}}validate(t,n){return n>=1&&n<=7}set(t,n,r){return t=Nrr(t,r),t.setHours(0,0,0,0),t}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"]}class Prr extends Di{priority=80;parse(t,n,r){switch(n){case"a":case"aa":case"aaa":return r.dayPeriod(t,{width:"abbreviated",context:"formatting"})||r.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaaa":return r.dayPeriod(t,{width:"narrow",context:"formatting"});default:return r.dayPeriod(t,{width:"wide",context:"formatting"})||r.dayPeriod(t,{width:"abbreviated",context:"formatting"})||r.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,n,r){return t.setHours(cke(r),0,0,0),t}incompatibleTokens=["b","B","H","k","t","T"]}class $rr extends Di{priority=80;parse(t,n,r){switch(n){case"b":case"bb":case"bbb":return r.dayPeriod(t,{width:"abbreviated",context:"formatting"})||r.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbbb":return r.dayPeriod(t,{width:"narrow",context:"formatting"});default:return r.dayPeriod(t,{width:"wide",context:"formatting"})||r.dayPeriod(t,{width:"abbreviated",context:"formatting"})||r.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,n,r){return t.setHours(cke(r),0,0,0),t}incompatibleTokens=["a","B","H","k","t","T"]}class Rrr extends Di{priority=80;parse(t,n,r){switch(n){case"B":case"BB":case"BBB":return r.dayPeriod(t,{width:"abbreviated",context:"formatting"})||r.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBBB":return r.dayPeriod(t,{width:"narrow",context:"formatting"});default:return r.dayPeriod(t,{width:"wide",context:"formatting"})||r.dayPeriod(t,{width:"abbreviated",context:"formatting"})||r.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,n,r){return t.setHours(cke(r),0,0,0),t}incompatibleTokens=["a","b","t","T"]}class Mrr extends Di{priority=70;parse(t,n,r){switch(n){case"h":return za(wl.hour12h,t);case"ho":return r.ordinalNumber(t,{unit:"hour"});default:return dl(n.length,t)}}validate(t,n){return n>=1&&n<=12}set(t,n,r){const s=t.getHours()>=12;return s&&r<12?t.setHours(r+12,0,0,0):!s&&r===12?t.setHours(0,0,0,0):t.setHours(r,0,0,0),t}incompatibleTokens=["H","K","k","t","T"]}class Drr extends Di{priority=70;parse(t,n,r){switch(n){case"H":return za(wl.hour23h,t);case"Ho":return r.ordinalNumber(t,{unit:"hour"});default:return dl(n.length,t)}}validate(t,n){return n>=0&&n<=23}set(t,n,r){return t.setHours(r,0,0,0),t}incompatibleTokens=["a","b","h","K","k","t","T"]}class Lrr extends Di{priority=70;parse(t,n,r){switch(n){case"K":return za(wl.hour11h,t);case"Ko":return r.ordinalNumber(t,{unit:"hour"});default:return dl(n.length,t)}}validate(t,n){return n>=0&&n<=11}set(t,n,r){return t.getHours()>=12&&r<12?t.setHours(r+12,0,0,0):t.setHours(r,0,0,0),t}incompatibleTokens=["h","H","k","t","T"]}class zrr extends Di{priority=70;parse(t,n,r){switch(n){case"k":return za(wl.hour24h,t);case"ko":return r.ordinalNumber(t,{unit:"hour"});default:return dl(n.length,t)}}validate(t,n){return n>=1&&n<=24}set(t,n,r){const s=r<=24?r%24:r;return t.setHours(s,0,0,0),t}incompatibleTokens=["a","b","h","H","K","t","T"]}class Frr extends Di{priority=60;parse(t,n,r){switch(n){case"m":return za(wl.minute,t);case"mo":return r.ordinalNumber(t,{unit:"minute"});default:return dl(n.length,t)}}validate(t,n){return n>=0&&n<=59}set(t,n,r){return t.setMinutes(r,0,0),t}incompatibleTokens=["t","T"]}class Brr extends Di{priority=50;parse(t,n,r){switch(n){case"s":return za(wl.second,t);case"so":return r.ordinalNumber(t,{unit:"second"});default:return dl(n.length,t)}}validate(t,n){return n>=0&&n<=59}set(t,n,r){return t.setSeconds(r,0),t}incompatibleTokens=["t","T"]}class Vrr extends Di{priority=30;parse(t,n){const r=s=>Math.trunc(s*Math.pow(10,-n.length+3));return Sl(dl(n.length,t),r)}set(t,n,r){return t.setMilliseconds(r),t}incompatibleTokens=["t","T"]}class Urr extends Di{priority=10;parse(t,n){switch(n){case"X":return Dy(My.basicOptionalMinutes,t);case"XX":return Dy(My.basic,t);case"XXXX":return Dy(My.basicOptionalSeconds,t);case"XXXXX":return Dy(My.extendedOptionalSeconds,t);default:return Dy(My.extended,t)}}set(t,n,r){return n.timestampIsSet?t:Do(t,t.getTime()-sA(t)-r)}incompatibleTokens=["t","T","x"]}class qrr extends Di{priority=10;parse(t,n){switch(n){case"x":return Dy(My.basicOptionalMinutes,t);case"xx":return Dy(My.basic,t);case"xxxx":return Dy(My.basicOptionalSeconds,t);case"xxxxx":return Dy(My.extendedOptionalSeconds,t);default:return Dy(My.extended,t)}}set(t,n,r){return n.timestampIsSet?t:Do(t,t.getTime()-sA(t)-r)}incompatibleTokens=["t","T","X"]}class Qrr extends Di{priority=40;parse(t){return WSt(t)}set(t,n,r){return[Do(t,r*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"}class Zrr extends Di{priority=20;parse(t){return WSt(t)}set(t,n,r){return[Do(t,r),{timestampIsSet:!0}]}incompatibleTokens="*"}const Wrr={G:new drr,y:new frr,Y:new hrr,R:new prr,u:new mrr,Q:new grr,q:new vrr,M:new yrr,L:new xrr,w:new wrr,I:new krr,d:new Crr,D:new _rr,E:new Trr,e:new Irr,c:new Err,i:new Arr,a:new Prr,b:new $rr,B:new Rrr,h:new Mrr,H:new Drr,K:new Lrr,k:new zrr,m:new Frr,s:new Brr,S:new Vrr,X:new Urr,x:new qrr,t:new Qrr,T:new Zrr},Hrr=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Grr=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Krr=/^'([^]*?)'?$/,Yrr=/''/g,Xrr=/\S/,Jrr=/[a-zA-Z]/;function esr(e,t,n,r){const s=()=>Do(n,NaN),i=trr(),o=i.locale??ike,l=i.firstWeekContainsDate??i.locale?.options?.firstWeekContainsDate??1,c=i.weekStartsOn??i.locale?.options?.weekStartsOn??0,u={firstWeekContainsDate:l,weekStartsOn:c,locale:o},d=[new urr(r?.in,n)],f=t.match(Grr).map(y=>{const x=y[0];if(x in Vpe){const b=Vpe[x];return b(y,o.formatLong)}return y}).join("").match(Hrr),h=[];for(let y of f){qSt(y)&&Upe(y,t,e),USt(y)&&Upe(y,t,e);const x=y[0],b=Wrr[x];if(b){const{incompatibleTokens:S}=b;if(Array.isArray(S)){const j=h.find(C=>S.includes(C.token)||C.token===x);if(j)throw new RangeError(`The format string mustn't contain \`${j.fullToken}\` and \`${y}\` at the same time`)}else if(b.incompatibleTokens==="*"&&h.length>0)throw new RangeError(`The format string mustn't contain \`${y}\` and any other token at the same time`);h.push({token:x,fullToken:y});const k=b.run(e,y,o.match,u);if(!k)return s();d.push(k.setter),e=k.rest}else{if(x.match(Jrr))throw new RangeError("Format string contains an unescaped latin alphabet character `"+x+"`");if(y==="''"?y="'":x==="'"&&(y=tsr(y)),e.indexOf(y)===0)e=e.slice(y.length);else return s()}}if(e.length>0&&Xrr.test(e))return s();const p=d.map(y=>y.priority).sort((y,x)=>x-y).filter((y,x,b)=>b.indexOf(y)===x).map(y=>d.filter(x=>x.priority===y).sort((x,b)=>b.subPriority-x.subPriority)).map(y=>y[0]);let m=Hs(n,r?.in);if(isNaN(+m))return s();const v={};for(const y of p){if(!y.validate(m,u))return s();const x=y.set(m,v,u);Array.isArray(x)?(m=x[0],Object.assign(v,x[1])):m=x}return m}function tsr(e){return e.match(Krr)[1].replace(Yrr,"'")}function dke(e,t,n){const[r,s]=$P(n?.in,e,t);return r.getFullYear()===s.getFullYear()&&r.getMonth()===s.getMonth()}function nsr(e,t,n){const[r,s]=$P(n?.in,e,t);return r.getFullYear()===s.getFullYear()}function Moe(e,t,n){return du(e,-t,n)}function Doe(e,t,n){const r=Hs(e,n?.in),s=r.getFullYear(),i=r.getDate(),o=Do(e,0);o.setFullYear(s,t,15),o.setHours(0,0,0,0);const l=err(o);return r.setMonth(t,Math.min(i,l)),r}function OVe(e,t,n){const r=Hs(e,n?.in);return isNaN(+r)?Do(e,NaN):(r.setFullYear(t),r)}function KSt(e,t){const{getFieldState:n,formState:r}=zr(),[s,i]=g.useState({expanded:t,dismissedSubmission:0}),o=n(e,r).invalid,l=o&&r.submitCount>s.dismissedSubmission;function c(u){i({expanded:u,dismissedSubmission:r.submitCount})}return{expanded:s.expanded||l,invalid:o,setExpanded:c}}const rsr=["title","name","label"];function jVe(e){return e.find(t=>typeof t=="string"&&t.trim().length>0)}function ssr(e){if(typeof e=="string")return e.trim();if(typeof e=="number"||typeof e=="boolean")return String(e);if(mD(e))return jVe(rsr.map(t=>e[t]))??jVe(Object.values(e))}function isr({children:e,onRemove:t,index:n}){const r=g.useContext(gK),s=g.useContext(KSe),i=g.useContext(SSt),{control:o}=zr(),l=Wn({control:o,name:r}),c=ssr(l),u=g.useRef(null),{expanded:d,invalid:f,setExpanded:h}=KSt(r,!c),p=`Item ${n+1}${c?`: ${c}`:""}`;return a.jsxs(gc,{open:d,onOpenChange:h,className:"overflow-hidden rounded-lg border border-border bg-background motion-reduce:[&_[data-slot=collapsible-content]]:transition-none motion-reduce:[&_svg]:transition-none",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-1 pr-1",children:[a.jsxs(Gl,{ref:u,"aria-label":f?`${p}, Needs input`:p,className:"flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-lg px-3 text-left text-caption focus-visible:-outline-offset-1",children:[a.jsx(Ha,{direction:"right",className:"size-3.5 text-muted-foreground"}),a.jsxs("span",{className:"shrink-0 text-muted-foreground",children:["Item ",n+1]}),c&&a.jsx("span",{className:"truncate text-foreground",title:c,children:c}),f&&a.jsx(Y,{as:"span",variant:"meta",className:"ml-auto shrink-0 text-destructive-foreground",children:"Needs input"})]}),!s&&a.jsx(ce,{type:"button",variant:"ghost",size:"icon-md",className:"size-11","aria-label":`Remove item ${n+1}`,onClick:()=>{t(),i?.current?.focus()},children:a.jsx(Xo,{})})]}),a.jsxs(Kl,{keepMounted:!0,className:"border-t border-border p-3",children:[e,!s&&a.jsx("div",{className:"flex justify-end pt-2",children:a.jsx(ce,{type:"button",className:"min-h-11","aria-label":`Done editing item ${n+1}`,onClick:()=>{h(!1),u.current?.focus()},icon:a.jsx(ur,{}),children:"Done"})})]})]})}function osr({label:e,children:t,onAddItem:n}){const r=g.useContext(KSe),s=g.Children.count(t),i=g.useRef(null);return a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[a.jsxs(Y,{as:"h3",variant:"caption",tone:"muted",className:"flex items-center gap-1.5",children:[a.jsx(j_n,{"aria-hidden":!0,className:"size-3.5"}),e," ",a.jsx("span",{className:"tabular-nums",children:s})]}),!r&&a.jsxs(ce,{ref:i,type:"button",variant:"ghost",size:"sm","aria-label":`Add ${e} item`,onClick:n,children:[a.jsx(Dr,{}),"Add item"]})]}),s===0?a.jsx(Y,{as:"p",variant:"caption",tone:"muted",className:"py-2",children:"No items added"}):a.jsx(SSt,{value:i,children:a.jsx("div",{className:"flex flex-col gap-2",children:t})})]})}function asr(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}function YSt(e){return{checked(t){return e.indeterminate?{}:t?{"data-checked":""}:{"data-unchecked":""}},...kp}}const lsr=g.createContext(void 0);function csr(){return g.useContext(lsr)}const XSt=g.createContext(void 0);function usr(){const e=g.useContext(XSt);if(e===void 0)throw new Error(Nr(14));return e}const dsr="data-parent",fsr=g.forwardRef(function(t,n){const{checked:r,className:s,defaultChecked:i=!1,"aria-labelledby":o,disabled:l=!1,form:c,id:u,indeterminate:d=!1,inputRef:f,name:h,onCheckedChange:p,parent:m=!1,readOnly:v=!1,render:y,required:x=!1,uncheckedValue:b,value:S,nativeButton:k=!1,style:j,...C}=t,{clearErrors:T}=Rv(),{disabled:_,name:N,setDirty:E,setFilled:A,setFocused:P,setTouched:L,state:F,validationMode:Q,validityData:q,validation:B}=Ru(),V=RG(),{labelId:W,controlId:M,registerControlId:K,getDescriptionProps:D}=yd(),$=csr(),z=$?.allValues===void 0?void 0:$.parent,U=z!==void 0,G=_||V.disabled||$?.disabled||l,ne=N??h,X=S??ne,ee=Zi(),re=Zi();let ue=u||M;U&&(m?ue=re:X!==void 0?ue=`${z.id}-${X}`:ue||=re);let te={};U&&(m?te=z.getParentProps():X!==void 0&&(te=z.getChildProps(X)));const{checked:ie=r,indeterminate:se=d,onCheckedChange:ae,...he}=te,ge=$?.value,me=g.useRef(null),ke=ul(()=>Symbol()),Ee=g.useRef(!1),{getButtonProps:qe,buttonRef:Ze}=gd({disabled:G,native:k}),Fe=$?.validation??B,[Ae,Be]=Jd({controlled:X!==void 0&&ge!==void 0&&!m?ge.includes(X):ie,default:i,name:"Checkbox",state:"checked"}),je=U?!!ie:Ae,_e=U&&se||d;Ot(()=>{K!==ti&&(Ee.current=!0,K(ke.current,ue))},[ue,K,ke]),g.useEffect(()=>{const We=ke.current;return()=>{!Ee.current||K===ti||(Ee.current=!1,K(We,void 0))}},[K,ke]),A_(me,ee,Ae,void 0,!$&&!G,h);const Ue=g.useRef(null),pe=Fe.registerInput,fe=$?X:void 0,Ie=g.useCallback(We=>pe(We,{controlRef:me,value:fe}),[pe,fe]),Ce=nf(f,Ue,m?void 0:Ie),le=l1e(o,W,Ue,!k,ue??void 0);Ot(()=>{Ue.current&&(Ue.current.indeterminate=_e,Ae&&A(!0))},[Ae,_e,A]),Jg(Ae,()=>{$||(T(ne),A(Ae),E(Ae!==q.initialValue),Fe.change(Ae))});const ve=Ol({checked:Ae,disabled:G,form:c,name:m?void 0:ne,id:k?void 0:ue??void 0,required:x,ref:Ce,style:ne?uP:SS,tabIndex:-1,type:"checkbox","aria-hidden":!0,onChange(We){if(We.nativeEvent.defaultPrevented)return;if(v){We.preventDefault();return}const tt=We.currentTarget.checked,st=Xt(Eo,We.nativeEvent);if(p?.(tt,st),!st.isCanceled&&(ae?.(tt,st),!st.isCanceled&&(Be(tt),X!==void 0&&$!==void 0&&!m&&!U))){const Ge=tt?[...$.value,X]:$.value.filter(Le=>Le!==X);$.setValue(Ge,st)}},onClick(We){We.stopPropagation()},onFocus(){me.current?.focus()}},S!==void 0?{value:($?Ae&&S:S)||""}:ai,D,We=>Fe.getValidationProps(G,We));g.useEffect(()=>{if(!z||X===void 0)return;const We=z.disabledStatesRef.current;return We.set(X,G),()=>{We.delete(X)}},[z,G,X]);const be=g.useMemo(()=>({...F,checked:je,disabled:G,readOnly:v,required:x,indeterminate:_e}),[F,je,G,v,x,_e]),$e=YSt(be),De=cn("span",t,{state:be,ref:[Ze,me,n],props:[{id:k?ue??void 0:ee,role:"checkbox","aria-checked":_e?"mixed":je,"aria-readonly":v||void 0,"aria-required":x||void 0,"aria-labelledby":le,[dsr]:m?"":void 0,onFocus(){G||P(!0)},onBlur(){const We=Ue.current;We&&(L(!0),P(!1),Q==="onBlur"&&Fe.commit($?ge:We.checked))},onKeyDown(We){if(We.key!=="Enter"||(We.preventBaseUIHandler(),We.defaultPrevented))return;const tt=Ue.current?.form??null,st=We.currentTarget,Ge=We.nativeEvent,Le=We.preventDefault,ze=Ge.preventDefault;let Se=!1;We.preventDefault=()=>{Se=!0,Le.call(We)},Ge.preventDefault=()=>{Se=!0,ze.call(Ge)},ze.call(Ge),xi(st).queueMicrotask(()=>{We.preventDefault=Le,Ge.preventDefault=ze,Se||asr(tt)?.click()})},onClick(We){if(v||G)return;We.preventDefault();const tt=Ue.current;tt&&Rj(tt,We)}},C,he,qe,D,We=>Fe.getValidationProps(G,We)],stateAttributesMapping:$e});return a.jsxs(XSt.Provider,{value:be,children:[De,!Ae&&!$&&ne&&!m&&b!==void 0&&a.jsx("input",{type:"hidden",form:c,name:ne,value:b,disabled:G}),a.jsx("input",{...ve,suppressHydrationWarning:!0})]})}),hsr=g.forwardRef(function(t,n){const{render:r,className:s,style:i,keepMounted:o=!1,...l}=t,c=usr(),u=c.checked||c.indeterminate,{mounted:d,transitionStatus:f,setMounted:h}=wp(u),p=g.useRef(null),m={...c,transitionStatus:f};Tl({open:u,ref:p,onComplete(){u||h(!1)}});const y={...YSt(c),...ih},x=o||d,b=cn("span",t,{ref:[n,p],state:m,stateAttributesMapping:y,props:l});return x?b:null}),JSt=["flex size-4 shrink-0 cursor-pointer items-center justify-center","border border-border bg-fill-hover text-background",Mi.all,"hover:border-border-strong hover:bg-fill-active","active:scale-95 active:border-border-hover active:bg-fill-strong",tD,"data-[checked]:border-foreground data-[checked]:bg-foreground data-[checked]:text-background","data-[checked]:hover:border-foreground/90 data-[checked]:hover:bg-foreground/90","data-[checked]:active:border-foreground/75 data-[checked]:active:bg-foreground/75","data-[disabled]:cursor-not-allowed data-[disabled]:border-border data-[disabled]:bg-fill-subtle data-[disabled]:active:scale-100","data-[disabled]:data-[checked]:border-muted-foreground data-[disabled]:data-[checked]:bg-muted-foreground data-[disabled]:data-[checked]:text-background"].join(" "),Kc=g.forwardRef(({className:e,checked:t,indeterminate:n,...r},s)=>{const i=t==="indeterminate";return a.jsx(fsr,{ref:s,checked:i?!1:t,indeterminate:n??i,"data-slot":"checkbox",render:a.jsx("span",{...Mx(r)}),className:Z("peer rounded-[0.3125rem]",JSt,"data-[indeterminate]:border-foreground data-[indeterminate]:bg-foreground data-[indeterminate]:text-background","data-[indeterminate]:hover:border-foreground/90 data-[indeterminate]:hover:bg-foreground/90","data-[indeterminate]:active:border-foreground/75 data-[indeterminate]:active:bg-foreground/75","data-[disabled]:data-[indeterminate]:border-muted-foreground data-[disabled]:data-[indeterminate]:bg-muted-foreground data-[disabled]:data-[indeterminate]:text-background",e),...r,children:a.jsx(hsr,{keepMounted:!0,className:Z("group/checkbox-indicator flex items-center justify-center text-current","scale-75 opacity-0 transition-[opacity,transform] duration-200 ease-out-custom","data-[checked]:scale-100 data-[checked]:opacity-100","data-[indeterminate]:scale-100 data-[indeterminate]:opacity-100","data-[starting-style]:scale-75 data-[starting-style]:opacity-0","data-[ending-style]:scale-75 data-[ending-style]:opacity-0"),children:a.jsx(psr,{})})})});Kc.displayName="Checkbox";function psr(){return a.jsxs(a.Fragment,{children:[a.jsx(ur,{className:Z("stroke-3.25 size-3 scale-95 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")}),a.jsx(mpt,{className:Z("stroke-3.25 hidden size-3 scale-95 transition-transform duration-200 ease-out-custom","group-data-[indeterminate]/checkbox-indicator:block","group-data-[indeterminate]/checkbox-indicator:scale-100")})]})}const msr=({field:e,label:t,inputProps:n})=>a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx(Kc,{onCheckedChange:r=>{const s={target:{name:n.name,value:r}};n.onChange(s)},defaultChecked:e.default,disabled:n.disabled||n.readOnly}),a.jsx(dt,{required:e.required,children:t})]});var Ar=function(){return Ar=Object.assign||function(t){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},Ar.apply(this,arguments)};function gsr(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 ekt(e,t,n){for(var r=0,s=t.length,i;r<s;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))}function HL(e){return e.mode==="multiple"}function GL(e){return e.mode==="range"}function yK(e){return e.mode==="single"}var vsr={root:"rdp",multiple_months:"rdp-multiple_months",with_weeknumber:"rdp-with_weeknumber",vhidden:"rdp-vhidden",button_reset:"rdp-button_reset",button:"rdp-button",caption:"rdp-caption",caption_start:"rdp-caption_start",caption_end:"rdp-caption_end",caption_between:"rdp-caption_between",caption_label:"rdp-caption_label",caption_dropdowns:"rdp-caption_dropdowns",dropdown:"rdp-dropdown",dropdown_month:"rdp-dropdown_month",dropdown_year:"rdp-dropdown_year",dropdown_icon:"rdp-dropdown_icon",months:"rdp-months",month:"rdp-month",table:"rdp-table",tbody:"rdp-tbody",tfoot:"rdp-tfoot",head:"rdp-head",head_row:"rdp-head_row",head_cell:"rdp-head_cell",nav:"rdp-nav",nav_button:"rdp-nav_button",nav_button_previous:"rdp-nav_button_previous",nav_button_next:"rdp-nav_button_next",nav_icon:"rdp-nav_icon",row:"rdp-row",weeknumber:"rdp-weeknumber",cell:"rdp-cell",day:"rdp-day",day_today:"rdp-day_today",day_outside:"rdp-day_outside",day_selected:"rdp-day_selected",day_disabled:"rdp-day_disabled",day_hidden:"rdp-day_hidden",day_range_start:"rdp-day_range_start",day_range_end:"rdp-day_range_end",day_range_middle:"rdp-day_range_middle"};function ysr(e,t){return _k(e,"LLLL y",t)}function xsr(e,t){return _k(e,"d",t)}function bsr(e,t){return _k(e,"LLLL",t)}function wsr(e){return"".concat(e)}function Ssr(e,t){return _k(e,"cccccc",t)}function ksr(e,t){return _k(e,"yyyy",t)}var Osr=Object.freeze({__proto__:null,formatCaption:ysr,formatDay:xsr,formatMonthCaption:bsr,formatWeekNumber:wsr,formatWeekdayName:Ssr,formatYearCaption:ksr}),jsr=function(e,t,n){return _k(e,"do MMMM (EEEE)",n)},Csr=function(){return"Month: "},_sr=function(){return"Go to next month"},Tsr=function(){return"Go to previous month"},Isr=function(e,t){return _k(e,"cccc",t)},Esr=function(e){return"Week n. ".concat(e)},Nsr=function(){return"Year: "},Asr=Object.freeze({__proto__:null,labelDay:jsr,labelMonthDropdown:Csr,labelNext:_sr,labelPrevious:Tsr,labelWeekNumber:Esr,labelWeekday:Isr,labelYearDropdown:Nsr});function Psr(){var e="buttons",t=vsr,n=ike,r={},s={},i=1,o={},l=new Date;return{captionLayout:e,classNames:t,formatters:Osr,labels:Asr,locale:n,modifiersClassNames:r,modifiers:s,numberOfMonths:i,styles:o,today:l,mode:"default"}}function $sr(e){var t=e.fromYear,n=e.toYear,r=e.fromMonth,s=e.toMonth,i=e.fromDate,o=e.toDate;return r?i=Kf(r):t&&(i=new Date(t,0,1)),s?o=rke(s):n&&(o=new Date(n,11,31)),{fromDate:i?iA(i):void 0,toDate:o?iA(o):void 0}}var tkt=g.createContext(void 0);function Rsr(e){var t,n=e.initialProps,r=Psr(),s=$sr(n),i=s.fromDate,o=s.toDate,l=(t=n.captionLayout)!==null&&t!==void 0?t:r.captionLayout;l!=="buttons"&&(!i||!o)&&(l="buttons");var c;(yK(n)||HL(n)||GL(n))&&(c=n.onSelect);var u=Ar(Ar(Ar({},r),n),{captionLayout:l,classNames:Ar(Ar({},r.classNames),n.classNames),components:Ar({},n.components),formatters:Ar(Ar({},r.formatters),n.formatters),fromDate:i,labels:Ar(Ar({},r.labels),n.labels),mode:n.mode||r.mode,modifiers:Ar(Ar({},r.modifiers),n.modifiers),modifiersClassNames:Ar(Ar({},r.modifiersClassNames),n.modifiersClassNames),onSelect:c,styles:Ar(Ar({},r.styles),n.styles),toDate:o});return a.jsx(tkt.Provider,{value:u,children:e.children})}function ea(){var e=g.useContext(tkt);if(!e)throw new Error("useDayPicker must be used within a DayPickerProvider.");return e}function nkt(e){var t=ea(),n=t.locale,r=t.classNames,s=t.styles,i=t.formatters.formatCaption;return a.jsx("div",{className:r.caption_label,style:s.caption_label,"aria-live":"polite",role:"presentation",id:e.id,children:i(e.displayMonth,{locale:n})})}function Msr(e){return a.jsx("svg",Ar({width:"8px",height:"8px",viewBox:"0 0 120 120","data-testid":"iconDropdown"},e,{children:a.jsx("path",{d:"M4.22182541,48.2218254 C8.44222828,44.0014225 15.2388494,43.9273804 19.5496459,47.9996989 L19.7781746,48.2218254 L60,88.443 L100.221825,48.2218254 C104.442228,44.0014225 111.238849,43.9273804 115.549646,47.9996989 L115.778175,48.2218254 C119.998577,52.4422283 120.07262,59.2388494 116.000301,63.5496459 L115.778175,63.7781746 L67.7781746,111.778175 C63.5577717,115.998577 56.7611506,116.07262 52.4503541,112.000301 L52.2218254,111.778175 L4.22182541,63.7781746 C-0.0739418023,59.4824074 -0.0739418023,52.5175926 4.22182541,48.2218254 Z",fill:"currentColor",fillRule:"nonzero"})}))}function rkt(e){var t,n,r=e.onChange,s=e.value,i=e.children,o=e.caption,l=e.className,c=e.style,u=ea(),d=(n=(t=u.components)===null||t===void 0?void 0:t.IconDropdown)!==null&&n!==void 0?n:Msr;return a.jsxs("div",{className:l,style:c,children:[a.jsx("span",{className:u.classNames.vhidden,children:e["aria-label"]}),a.jsx("select",{name:e.name,"aria-label":e["aria-label"],className:u.classNames.dropdown,style:u.styles.dropdown,value:s,onChange:r,children:i}),a.jsxs("div",{className:u.classNames.caption_label,style:u.styles.caption_label,"aria-hidden":"true",children:[o,a.jsx(d,{className:u.classNames.dropdown_icon,style:u.styles.dropdown_icon})]})]})}function Dsr(e){var t,n=ea(),r=n.fromDate,s=n.toDate,i=n.styles,o=n.locale,l=n.formatters.formatMonthCaption,c=n.classNames,u=n.components,d=n.labels.labelMonthDropdown;if(!r)return a.jsx(a.Fragment,{});if(!s)return a.jsx(a.Fragment,{});var f=[];if(nsr(r,s))for(var h=Kf(r),p=r.getMonth();p<=s.getMonth();p++)f.push(Doe(h,p));else for(var h=Kf(new Date),p=0;p<=11;p++)f.push(Doe(h,p));var m=function(y){var x=Number(y.target.value),b=Doe(Kf(e.displayMonth),x);e.onChange(b)},v=(t=u?.Dropdown)!==null&&t!==void 0?t:rkt;return a.jsx(v,{name:"months","aria-label":d(),className:c.dropdown_month,style:i.dropdown_month,onChange:m,value:e.displayMonth.getMonth(),caption:l(e.displayMonth,{locale:o}),children:f.map(function(y){return a.jsx("option",{value:y.getMonth(),children:l(y,{locale:o})},y.getMonth())})})}function Lsr(e){var t,n=e.displayMonth,r=ea(),s=r.fromDate,i=r.toDate,o=r.locale,l=r.styles,c=r.classNames,u=r.components,d=r.formatters.formatYearCaption,f=r.labels.labelYearDropdown,h=[];if(!s)return a.jsx(a.Fragment,{});if(!i)return a.jsx(a.Fragment,{});for(var p=s.getFullYear(),m=i.getFullYear(),v=p;v<=m;v++)h.push(OVe(FSt(new Date),v));var y=function(b){var S=OVe(Kf(n),Number(b.target.value));e.onChange(S)},x=(t=u?.Dropdown)!==null&&t!==void 0?t:rkt;return a.jsx(x,{name:"years","aria-label":f(),className:c.dropdown_year,style:l.dropdown_year,onChange:y,value:n.getFullYear(),caption:d(n,{locale:o}),children:h.map(function(b){return a.jsx("option",{value:b.getFullYear(),children:d(b,{locale:o})},b.getFullYear())})})}function zsr(e,t){var n=g.useState(e),r=n[0],s=n[1],i=t===void 0?r:t;return[i,s]}function Fsr(e){var t=e.month,n=e.defaultMonth,r=e.today,s=t||n||r||new Date,i=e.toDate,o=e.fromDate,l=e.numberOfMonths,c=l===void 0?1:l;if(i&&j5(i,s)<0){var u=-1*(c-1);s=Sv(i,u)}return o&&j5(s,o)<0&&(s=o),Kf(s)}function Bsr(){var e=ea(),t=Fsr(e),n=zsr(t,e.month),r=n[0],s=n[1],i=function(o){var l;if(!e.disableNavigation){var c=Kf(o);s(c),(l=e.onMonthChange)===null||l===void 0||l.call(e,c)}};return[r,i]}function Vsr(e,t){for(var n=t.reverseMonths,r=t.numberOfMonths,s=Kf(e),i=Kf(Sv(s,r)),o=j5(i,s),l=[],c=0;c<o;c++){var u=Sv(s,c);l.push(u)}return n&&(l=l.reverse()),l}function Usr(e,t){if(!t.disableNavigation){var n=t.toDate,r=t.pagedNavigation,s=t.numberOfMonths,i=s===void 0?1:s,o=r?i:1,l=Kf(e);if(!n)return Sv(l,o);var c=j5(n,e);if(!(c<i))return Sv(l,o)}}function qsr(e,t){if(!t.disableNavigation){var n=t.fromDate,r=t.pagedNavigation,s=t.numberOfMonths,i=s===void 0?1:s,o=r?i:1,l=Kf(e);if(!n)return Sv(l,-o);var c=j5(l,n);if(!(c<=0))return Sv(l,-o)}}var skt=g.createContext(void 0);function Qsr(e){var t=ea(),n=Bsr(),r=n[0],s=n[1],i=Vsr(r,t),o=Usr(r,t),l=qsr(r,t),c=function(f){return i.some(function(h){return dke(f,h)})},u=function(f,h){c(f)||(h&&QSt(f,h)?s(Sv(f,1+t.numberOfMonths*-1)):s(f))},d={currentMonth:r,displayMonths:i,goToMonth:s,goToDate:u,previousMonth:l,nextMonth:o,isDateDisplayed:c};return a.jsx(skt.Provider,{value:d,children:e.children})}function KL(){var e=g.useContext(skt);if(!e)throw new Error("useNavigation must be used within a NavigationProvider");return e}function CVe(e){var t,n=ea(),r=n.classNames,s=n.styles,i=n.components,o=KL().goToMonth,l=function(d){o(Sv(d,e.displayIndex?-e.displayIndex:0))},c=(t=i?.CaptionLabel)!==null&&t!==void 0?t:nkt,u=a.jsx(c,{id:e.id,displayMonth:e.displayMonth});return a.jsxs("div",{className:r.caption_dropdowns,style:s.caption_dropdowns,children:[a.jsx("div",{className:r.vhidden,children:u}),a.jsx(Dsr,{onChange:l,displayMonth:e.displayMonth}),a.jsx(Lsr,{onChange:l,displayMonth:e.displayMonth})]})}function Zsr(e){return a.jsx("svg",Ar({width:"16px",height:"16px",viewBox:"0 0 120 120"},e,{children:a.jsx("path",{d:"M69.490332,3.34314575 C72.6145263,0.218951416 77.6798462,0.218951416 80.8040405,3.34314575 C83.8617626,6.40086786 83.9268205,11.3179931 80.9992143,14.4548388 L80.8040405,14.6568542 L35.461,60 L80.8040405,105.343146 C83.8617626,108.400868 83.9268205,113.317993 80.9992143,116.454839 L80.8040405,116.656854 C77.7463184,119.714576 72.8291931,119.779634 69.6923475,116.852028 L69.490332,116.656854 L18.490332,65.6568542 C15.4326099,62.5991321 15.367552,57.6820069 18.2951583,54.5451612 L18.490332,54.3431458 L69.490332,3.34314575 Z",fill:"currentColor",fillRule:"nonzero"})}))}function Wsr(e){return a.jsx("svg",Ar({width:"16px",height:"16px",viewBox:"0 0 120 120"},e,{children:a.jsx("path",{d:"M49.8040405,3.34314575 C46.6798462,0.218951416 41.6145263,0.218951416 38.490332,3.34314575 C35.4326099,6.40086786 35.367552,11.3179931 38.2951583,14.4548388 L38.490332,14.6568542 L83.8333725,60 L38.490332,105.343146 C35.4326099,108.400868 35.367552,113.317993 38.2951583,116.454839 L38.490332,116.656854 C41.5480541,119.714576 46.4651794,119.779634 49.602025,116.852028 L49.8040405,116.656854 L100.804041,65.6568542 C103.861763,62.5991321 103.926821,57.6820069 100.999214,54.5451612 L100.804041,54.3431458 L49.8040405,3.34314575 Z",fill:"currentColor"})}))}var bQ=g.forwardRef(function(e,t){var n=ea(),r=n.classNames,s=n.styles,i=[r.button_reset,r.button];e.className&&i.push(e.className);var o=i.join(" "),l=Ar(Ar({},s.button_reset),s.button);return e.style&&Object.assign(l,e.style),a.jsx("button",Ar({},e,{ref:t,type:"button",className:o,style:l}))});function Hsr(e){var t,n,r=ea(),s=r.dir,i=r.locale,o=r.classNames,l=r.styles,c=r.labels,u=c.labelPrevious,d=c.labelNext,f=r.components;if(!e.nextMonth&&!e.previousMonth)return a.jsx(a.Fragment,{});var h=u(e.previousMonth,{locale:i}),p=[o.nav_button,o.nav_button_previous].join(" "),m=d(e.nextMonth,{locale:i}),v=[o.nav_button,o.nav_button_next].join(" "),y=(t=f?.IconRight)!==null&&t!==void 0?t:Wsr,x=(n=f?.IconLeft)!==null&&n!==void 0?n:Zsr;return a.jsxs("div",{className:o.nav,style:l.nav,children:[!e.hidePrevious&&a.jsx(bQ,{name:"previous-month","aria-label":h,className:p,style:l.nav_button_previous,disabled:!e.previousMonth,onClick:e.onPreviousClick,children:s==="rtl"?a.jsx(y,{className:o.nav_icon,style:l.nav_icon}):a.jsx(x,{className:o.nav_icon,style:l.nav_icon})}),!e.hideNext&&a.jsx(bQ,{name:"next-month","aria-label":m,className:v,style:l.nav_button_next,disabled:!e.nextMonth,onClick:e.onNextClick,children:s==="rtl"?a.jsx(x,{className:o.nav_icon,style:l.nav_icon}):a.jsx(y,{className:o.nav_icon,style:l.nav_icon})})]})}function _Ve(e){var t=ea().numberOfMonths,n=KL(),r=n.previousMonth,s=n.nextMonth,i=n.goToMonth,o=n.displayMonths,l=o.findIndex(function(m){return dke(e.displayMonth,m)}),c=l===0,u=l===o.length-1,d=t>1&&(c||!u),f=t>1&&(u||!c),h=function(){r&&i(r)},p=function(){s&&i(s)};return a.jsx(Hsr,{displayMonth:e.displayMonth,hideNext:d,hidePrevious:f,nextMonth:s,previousMonth:r,onPreviousClick:h,onNextClick:p})}function Gsr(e){var t,n=ea(),r=n.classNames,s=n.disableNavigation,i=n.styles,o=n.captionLayout,l=n.components,c=(t=l?.CaptionLabel)!==null&&t!==void 0?t:nkt,u;return s?u=a.jsx(c,{id:e.id,displayMonth:e.displayMonth}):o==="dropdown"?u=a.jsx(CVe,{displayMonth:e.displayMonth,id:e.id}):o==="dropdown-buttons"?u=a.jsxs(a.Fragment,{children:[a.jsx(CVe,{displayMonth:e.displayMonth,displayIndex:e.displayIndex,id:e.id}),a.jsx(_Ve,{displayMonth:e.displayMonth,displayIndex:e.displayIndex,id:e.id})]}):u=a.jsxs(a.Fragment,{children:[a.jsx(c,{id:e.id,displayMonth:e.displayMonth,displayIndex:e.displayIndex}),a.jsx(_Ve,{displayMonth:e.displayMonth,id:e.id})]}),a.jsx("div",{className:r.caption,style:i.caption,children:u})}function Ksr(e){var t=ea(),n=t.footer,r=t.styles,s=t.classNames.tfoot;return n?a.jsx("tfoot",{className:s,style:r.tfoot,children:a.jsx("tr",{children:a.jsx("td",{colSpan:8,children:n})})}):a.jsx(a.Fragment,{})}function Ysr(e,t,n){for(var r=n?$0(new Date):mp(new Date,{locale:e,weekStartsOn:t}),s=[],i=0;i<7;i++){var o=du(r,i);s.push(o)}return s}function Xsr(){var e=ea(),t=e.classNames,n=e.styles,r=e.showWeekNumber,s=e.locale,i=e.weekStartsOn,o=e.ISOWeek,l=e.formatters.formatWeekdayName,c=e.labels.labelWeekday,u=Ysr(s,i,o);return a.jsxs("tr",{style:n.head_row,className:t.head_row,children:[r&&a.jsx("td",{style:n.head_cell,className:t.head_cell}),u.map(function(d,f){return a.jsx("th",{scope:"col",className:t.head_cell,style:n.head_cell,"aria-label":c(d,{locale:s}),children:l(d,{locale:s})},f)})]})}function Jsr(){var e,t=ea(),n=t.classNames,r=t.styles,s=t.components,i=(e=s?.HeadRow)!==null&&e!==void 0?e:Xsr;return a.jsx("thead",{style:r.head,className:n.head,children:a.jsx(i,{})})}function eir(e){var t=ea(),n=t.locale,r=t.formatters.formatDay;return a.jsx(a.Fragment,{children:r(e.date,{locale:n})})}var fke=g.createContext(void 0);function tir(e){if(!HL(e.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return a.jsx(fke.Provider,{value:t,children:e.children})}return a.jsx(nir,{initialProps:e.initialProps,children:e.children})}function nir(e){var t=e.initialProps,n=e.children,r=t.selected,s=t.min,i=t.max,o=function(u,d,f){var h,p;(h=t.onDayClick)===null||h===void 0||h.call(t,u,d,f);var m=!!(d.selected&&s&&r?.length===s);if(!m){var v=!!(!d.selected&&i&&r?.length===i);if(!v){var y=r?ekt([],r):[];if(d.selected){var x=y.findIndex(function(b){return qf(u,b)});y.splice(x,1)}else y.push(u);(p=t.onSelect)===null||p===void 0||p.call(t,y,u,d,f)}}},l={disabled:[]};r&&l.disabled.push(function(u){var d=i&&r.length>i-1,f=r.some(function(h){return qf(h,u)});return!!(d&&!f)});var c={selected:r,onDayClick:o,modifiers:l};return a.jsx(fke.Provider,{value:c,children:n})}function hke(){var e=g.useContext(fke);if(!e)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return e}function rir(e,t){var n=t||{},r=n.from,s=n.to;return r&&s?qf(s,e)&&qf(r,e)?void 0:qf(s,e)?{from:s,to:void 0}:qf(r,e)?void 0:qpe(r,e)?{from:e,to:s}:{from:r,to:e}:s?qpe(e,s)?{from:s,to:e}:{from:e,to:s}:r?QSt(e,r)?{from:e,to:r}:{from:r,to:e}:{from:e,to:void 0}}var pke=g.createContext(void 0);function sir(e){if(!GL(e.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return a.jsx(pke.Provider,{value:t,children:e.children})}return a.jsx(iir,{initialProps:e.initialProps,children:e.children})}function iir(e){var t=e.initialProps,n=e.children,r=t.selected,s=r||{},i=s.from,o=s.to,l=t.min,c=t.max,u=function(p,m,v){var y,x;(y=t.onDayClick)===null||y===void 0||y.call(t,p,m,v);var b=rir(p,r);(x=t.onSelect)===null||x===void 0||x.call(t,b,p,m,v)},d={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(d.range_start=[i],o?(d.range_end=[o],qf(i,o)||(d.range_middle=[{after:i,before:o}])):d.range_end=[i]):o&&(d.range_start=[o],d.range_end=[o]),l&&(i&&!o&&d.disabled.push({after:Moe(i,l-1),before:du(i,l-1)}),i&&o&&d.disabled.push({after:i,before:du(i,l-1)}),!i&&o&&d.disabled.push({after:Moe(o,l-1),before:du(o,l-1)})),c){if(i&&!o&&(d.disabled.push({before:du(i,-c+1)}),d.disabled.push({after:du(i,c-1)})),i&&o){var f=Wy(o,i)+1,h=c-f;d.disabled.push({before:Moe(i,h)}),d.disabled.push({after:du(o,h)})}!i&&o&&(d.disabled.push({before:du(o,-c+1)}),d.disabled.push({after:du(o,c-1)}))}return a.jsx(pke.Provider,{value:{selected:r,onDayClick:u,modifiers:d},children:n})}function mke(){var e=g.useContext(pke);if(!e)throw new Error("useSelectRange must be used within a SelectRangeProvider");return e}function YB(e){return Array.isArray(e)?ekt([],e):e!==void 0?[e]:[]}function oir(e){var t={};return Object.entries(e).forEach(function(n){var r=n[0],s=n[1];t[r]=YB(s)}),t}var kv;(function(e){e.Outside="outside",e.Disabled="disabled",e.Selected="selected",e.Hidden="hidden",e.Today="today",e.RangeStart="range_start",e.RangeEnd="range_end",e.RangeMiddle="range_middle"})(kv||(kv={}));var air=kv.Selected,yb=kv.Disabled,lir=kv.Hidden,cir=kv.Today,Loe=kv.RangeEnd,zoe=kv.RangeMiddle,Foe=kv.RangeStart,uir=kv.Outside;function dir(e,t,n){var r,s=(r={},r[air]=YB(e.selected),r[yb]=YB(e.disabled),r[lir]=YB(e.hidden),r[cir]=[e.today],r[Loe]=[],r[zoe]=[],r[Foe]=[],r[uir]=[],r);return e.fromDate&&s[yb].push({before:e.fromDate}),e.toDate&&s[yb].push({after:e.toDate}),HL(e)?s[yb]=s[yb].concat(t.modifiers[yb]):GL(e)&&(s[yb]=s[yb].concat(n.modifiers[yb]),s[Foe]=n.modifiers[Foe],s[zoe]=n.modifiers[zoe],s[Loe]=n.modifiers[Loe]),s}var ikt=g.createContext(void 0);function fir(e){var t=ea(),n=hke(),r=mke(),s=dir(t,n,r),i=oir(t.modifiers),o=Ar(Ar({},s),i);return a.jsx(ikt.Provider,{value:o,children:e.children})}function okt(){var e=g.useContext(ikt);if(!e)throw new Error("useModifiers must be used within a ModifiersProvider");return e}function hir(e){return!!(e&&typeof e=="object"&&"before"in e&&"after"in e)}function pir(e){return!!(e&&typeof e=="object"&&"from"in e)}function mir(e){return!!(e&&typeof e=="object"&&"after"in e)}function gir(e){return!!(e&&typeof e=="object"&&"before"in e)}function vir(e){return!!(e&&typeof e=="object"&&"dayOfWeek"in e)}function yir(e,t){var n,r=t.from,s=t.to;if(r&&s){var i=Wy(s,r)<0;i&&(n=[s,r],r=n[0],s=n[1]);var o=Wy(e,r)>=0&&Wy(s,e)>=0;return o}return s?qf(s,e):r?qf(r,e):!1}function xir(e){return tke(e)}function bir(e){return Array.isArray(e)&&e.every(tke)}function wir(e,t){return t.some(function(n){if(typeof n=="boolean")return n;if(xir(n))return qf(e,n);if(bir(n))return n.includes(e);if(pir(n))return yir(e,n);if(vir(n))return n.dayOfWeek.includes(e.getDay());if(hir(n)){var r=Wy(n.before,e),s=Wy(n.after,e),i=r>0,o=s<0,l=qpe(n.before,n.after);return l?o&&i:i||o}return mir(n)?Wy(e,n.after)>0:gir(n)?Wy(n.before,e)>0:typeof n=="function"?n(e):!1})}function gke(e,t,n){var r=Object.keys(t).reduce(function(i,o){var l=t[o];return wir(e,l)&&i.push(o),i},[]),s={};return r.forEach(function(i){return s[i]=!0}),n&&!dke(e,n)&&(s.outside=!0),s}function Sir(e,t){for(var n=Kf(e[0]),r=rke(e[e.length-1]),s,i,o=n;o<=r;){var l=gke(o,t),c=!l.disabled&&!l.hidden;if(!c){o=du(o,1);continue}if(l.selected)return o;l.today&&!i&&(i=o),s||(s=o),o=du(o,1)}return i||s}var kir=365;function akt(e,t){var n=t.moveBy,r=t.direction,s=t.context,i=t.modifiers,o=t.retry,l=o===void 0?{count:0,lastFocused:e}:o,c=s.weekStartsOn,u=s.fromDate,d=s.toDate,f=s.locale,h={day:du,week:Bpe,month:Sv,year:inr,startOfWeek:function(y){return s.ISOWeek?$0(y):mp(y,{locale:f,weekStartsOn:c})},endOfWeek:function(y){return s.ISOWeek?BSt(y):ske(y,{locale:f,weekStartsOn:c})}},p=h[n](e,r==="after"?1:-1);r==="before"&&u?p=onr([u,p]):r==="after"&&d&&(p=anr([d,p]));var m=!0;if(i){var v=gke(p,i);m=!v.disabled&&!v.hidden}return m?p:l.count>kir?l.lastFocused:akt(p,{moveBy:n,direction:r,context:s,modifiers:i,retry:Ar(Ar({},l),{count:l.count+1})})}var lkt=g.createContext(void 0);function Oir(e){var t=KL(),n=okt(),r=g.useState(),s=r[0],i=r[1],o=g.useState(),l=o[0],c=o[1],u=Sir(t.displayMonths,n),d=s??(l&&t.isDateDisplayed(l))?l:u,f=function(){c(s),i(void 0)},h=function(y){i(y)},p=ea(),m=function(y,x){if(s){var b=akt(s,{moveBy:y,direction:x,context:p,modifiers:n});qf(s,b)||(t.goToDate(b,s),h(b))}},v={focusedDay:s,focusTarget:d,blur:f,focus:h,focusDayAfter:function(){return m("day","after")},focusDayBefore:function(){return m("day","before")},focusWeekAfter:function(){return m("week","after")},focusWeekBefore:function(){return m("week","before")},focusMonthBefore:function(){return m("month","before")},focusMonthAfter:function(){return m("month","after")},focusYearBefore:function(){return m("year","before")},focusYearAfter:function(){return m("year","after")},focusStartOfWeek:function(){return m("startOfWeek","before")},focusEndOfWeek:function(){return m("endOfWeek","after")}};return a.jsx(lkt.Provider,{value:v,children:e.children})}function vke(){var e=g.useContext(lkt);if(!e)throw new Error("useFocusContext must be used within a FocusProvider");return e}function jir(e,t){var n=okt(),r=gke(e,n,t);return r}var yke=g.createContext(void 0);function Cir(e){if(!yK(e.initialProps)){var t={selected:void 0};return a.jsx(yke.Provider,{value:t,children:e.children})}return a.jsx(_ir,{initialProps:e.initialProps,children:e.children})}function _ir(e){var t=e.initialProps,n=e.children,r=function(i,o,l){var c,u,d;if((c=t.onDayClick)===null||c===void 0||c.call(t,i,o,l),o.selected&&!t.required){(u=t.onSelect)===null||u===void 0||u.call(t,void 0,i,o,l);return}(d=t.onSelect)===null||d===void 0||d.call(t,i,i,o,l)},s={selected:t.selected,onDayClick:r};return a.jsx(yke.Provider,{value:s,children:n})}function ckt(){var e=g.useContext(yke);if(!e)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return e}function Tir(e,t){var n=ea(),r=ckt(),s=hke(),i=mke(),o=vke(),l=o.focusDayAfter,c=o.focusDayBefore,u=o.focusWeekAfter,d=o.focusWeekBefore,f=o.blur,h=o.focus,p=o.focusMonthBefore,m=o.focusMonthAfter,v=o.focusYearBefore,y=o.focusYearAfter,x=o.focusStartOfWeek,b=o.focusEndOfWeek,S=function(B){var V,W,M,K;yK(n)?(V=r.onDayClick)===null||V===void 0||V.call(r,e,t,B):HL(n)?(W=s.onDayClick)===null||W===void 0||W.call(s,e,t,B):GL(n)?(M=i.onDayClick)===null||M===void 0||M.call(i,e,t,B):(K=n.onDayClick)===null||K===void 0||K.call(n,e,t,B)},k=function(B){var V;h(e),(V=n.onDayFocus)===null||V===void 0||V.call(n,e,t,B)},j=function(B){var V;f(),(V=n.onDayBlur)===null||V===void 0||V.call(n,e,t,B)},C=function(B){var V;(V=n.onDayMouseEnter)===null||V===void 0||V.call(n,e,t,B)},T=function(B){var V;(V=n.onDayMouseLeave)===null||V===void 0||V.call(n,e,t,B)},_=function(B){var V;(V=n.onDayPointerEnter)===null||V===void 0||V.call(n,e,t,B)},N=function(B){var V;(V=n.onDayPointerLeave)===null||V===void 0||V.call(n,e,t,B)},E=function(B){var V;(V=n.onDayTouchCancel)===null||V===void 0||V.call(n,e,t,B)},A=function(B){var V;(V=n.onDayTouchEnd)===null||V===void 0||V.call(n,e,t,B)},P=function(B){var V;(V=n.onDayTouchMove)===null||V===void 0||V.call(n,e,t,B)},L=function(B){var V;(V=n.onDayTouchStart)===null||V===void 0||V.call(n,e,t,B)},F=function(B){var V;(V=n.onDayKeyUp)===null||V===void 0||V.call(n,e,t,B)},Q=function(B){var V;switch(B.key){case"ArrowLeft":B.preventDefault(),B.stopPropagation(),n.dir==="rtl"?l():c();break;case"ArrowRight":B.preventDefault(),B.stopPropagation(),n.dir==="rtl"?c():l();break;case"ArrowDown":B.preventDefault(),B.stopPropagation(),u();break;case"ArrowUp":B.preventDefault(),B.stopPropagation(),d();break;case"PageUp":B.preventDefault(),B.stopPropagation(),B.shiftKey?v():p();break;case"PageDown":B.preventDefault(),B.stopPropagation(),B.shiftKey?y():m();break;case"Home":B.preventDefault(),B.stopPropagation(),x();break;case"End":B.preventDefault(),B.stopPropagation(),b();break}(V=n.onDayKeyDown)===null||V===void 0||V.call(n,e,t,B)},q={onClick:S,onFocus:k,onBlur:j,onKeyDown:Q,onKeyUp:F,onMouseEnter:C,onMouseLeave:T,onPointerEnter:_,onPointerLeave:N,onTouchCancel:E,onTouchEnd:A,onTouchMove:P,onTouchStart:L};return q}function Iir(){var e=ea(),t=ckt(),n=hke(),r=mke(),s=yK(e)?t.selected:HL(e)?n.selected:GL(e)?r.selected:void 0;return s}function Eir(e){return Object.values(kv).includes(e)}function Nir(e,t){var n=[e.classNames.day];return Object.keys(t).forEach(function(r){var s=e.modifiersClassNames[r];if(s)n.push(s);else if(Eir(r)){var i=e.classNames["day_".concat(r)];i&&n.push(i)}}),n}function Air(e,t){var n=Ar({},e.styles.day);return Object.keys(t).forEach(function(r){var s;n=Ar(Ar({},n),(s=e.modifiersStyles)===null||s===void 0?void 0:s[r])}),n}function Pir(e,t,n){var r,s,i,o=ea(),l=vke(),c=jir(e,t),u=Tir(e,c),d=Iir(),f=!!(o.onDayClick||o.mode!=="default");g.useEffect(function(){var C;c.outside||l.focusedDay&&f&&qf(l.focusedDay,e)&&((C=n.current)===null||C===void 0||C.focus())},[l.focusedDay,e,n,f,c.outside]);var h=Nir(o,c).join(" "),p=Air(o,c),m=!!(c.outside&&!o.showOutsideDays||c.hidden),v=(i=(s=o.components)===null||s===void 0?void 0:s.DayContent)!==null&&i!==void 0?i:eir,y=a.jsx(v,{date:e,displayMonth:t,activeModifiers:c}),x={style:p,className:h,children:y,role:"gridcell"},b=l.focusTarget&&qf(l.focusTarget,e)&&!c.outside,S=l.focusedDay&&qf(l.focusedDay,e),k=Ar(Ar(Ar({},x),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=S||b?0:-1,r)),u),j={isButton:f,isHidden:m,activeModifiers:c,selectedDays:d,buttonProps:k,divProps:x};return j}function $ir(e){var t=g.useRef(null),n=Pir(e.date,e.displayMonth,t);return n.isHidden?a.jsx("div",{role:"gridcell"}):n.isButton?a.jsx(bQ,Ar({name:"day",ref:t},n.buttonProps)):a.jsx("div",Ar({},n.divProps))}function Rir(e){var t=e.number,n=e.dates,r=ea(),s=r.onWeekNumberClick,i=r.styles,o=r.classNames,l=r.locale,c=r.labels.labelWeekNumber,u=r.formatters.formatWeekNumber,d=u(Number(t),{locale:l});if(!s)return a.jsx("span",{className:o.weeknumber,style:i.weeknumber,children:d});var f=c(Number(t),{locale:l}),h=function(p){s(t,n,p)};return a.jsx(bQ,{name:"week-number","aria-label":f,className:o.weeknumber,style:i.weeknumber,onClick:h,children:d})}function Mir(e){var t,n,r=ea(),s=r.styles,i=r.classNames,o=r.showWeekNumber,l=r.components,c=(t=l?.Day)!==null&&t!==void 0?t:$ir,u=(n=l?.WeekNumber)!==null&&n!==void 0?n:Rir,d;return o&&(d=a.jsx("td",{className:i.cell,style:s.cell,children:a.jsx(u,{number:e.weekNumber,dates:e.dates})})),a.jsxs("tr",{className:i.row,style:s.row,children:[d,e.dates.map(function(f){return a.jsx("td",{className:i.cell,style:s.cell,role:"presentation",children:a.jsx(c,{displayMonth:e.displayMonth,date:f})},rrr(f))})]})}function TVe(e,t,n){for(var r=n?.ISOWeek?BSt(t):ske(t,n),s=n?.ISOWeek?$0(e):mp(e,n),i=Wy(r,s),o=[],l=0;l<=i;l++)o.push(du(s,l));var c=o.reduce(function(u,d){var f=n?.ISOWeek?oke(d):lke(d,n),h=u.find(function(p){return p.weekNumber===f});return h?(h.dates.push(d),u):(u.push({weekNumber:f,dates:[d]}),u)},[]);return c}function Dir(e,t){var n=TVe(Kf(e),rke(e),t);if(t?.useFixedWeeks){var r=irr(e,t);if(r<6){var s=n[n.length-1],i=s.dates[s.dates.length-1],o=Bpe(i,6-r),l=TVe(Bpe(i,1),o,t);n.push.apply(n,l)}}return n}function Lir(e){var t,n,r,s=ea(),i=s.locale,o=s.classNames,l=s.styles,c=s.hideHead,u=s.fixedWeeks,d=s.components,f=s.weekStartsOn,h=s.firstWeekContainsDate,p=s.ISOWeek,m=Dir(e.displayMonth,{useFixedWeeks:!!u,ISOWeek:p,locale:i,weekStartsOn:f,firstWeekContainsDate:h}),v=(t=d?.Head)!==null&&t!==void 0?t:Jsr,y=(n=d?.Row)!==null&&n!==void 0?n:Mir,x=(r=d?.Footer)!==null&&r!==void 0?r:Ksr;return a.jsxs("table",{id:e.id,className:o.table,style:l.table,role:"grid","aria-labelledby":e["aria-labelledby"],children:[!c&&a.jsx(v,{}),a.jsx("tbody",{className:o.tbody,style:l.tbody,children:m.map(function(b){return a.jsx(y,{displayMonth:e.displayMonth,dates:b.dates,weekNumber:b.weekNumber},b.weekNumber)})}),a.jsx(x,{displayMonth:e.displayMonth})]})}function zir(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Fir=zir()?g.useLayoutEffect:g.useEffect,Boe=!1,Bir=0;function IVe(){return"react-day-picker-".concat(++Bir)}function Vir(e){var t,n=e??(Boe?IVe():null),r=g.useState(n),s=r[0],i=r[1];return Fir(function(){s===null&&i(IVe())},[]),g.useEffect(function(){Boe===!1&&(Boe=!0)},[]),(t=e??s)!==null&&t!==void 0?t:void 0}function Uir(e){var t,n,r=ea(),s=r.dir,i=r.classNames,o=r.styles,l=r.components,c=KL().displayMonths,u=Vir(r.id?"".concat(r.id,"-").concat(e.displayIndex):void 0),d=r.id?"".concat(r.id,"-grid-").concat(e.displayIndex):void 0,f=[i.month],h=o.month,p=e.displayIndex===0,m=e.displayIndex===c.length-1,v=!p&&!m;s==="rtl"&&(t=[p,m],m=t[0],p=t[1]),p&&(f.push(i.caption_start),h=Ar(Ar({},h),o.caption_start)),m&&(f.push(i.caption_end),h=Ar(Ar({},h),o.caption_end)),v&&(f.push(i.caption_between),h=Ar(Ar({},h),o.caption_between));var y=(n=l?.Caption)!==null&&n!==void 0?n:Gsr;return a.jsxs("div",{className:f.join(" "),style:h,children:[a.jsx(y,{id:u,displayMonth:e.displayMonth,displayIndex:e.displayIndex}),a.jsx(Lir,{id:d,"aria-labelledby":u,displayMonth:e.displayMonth})]},e.displayIndex)}function qir(e){var t=ea(),n=t.classNames,r=t.styles;return a.jsx("div",{className:n.months,style:r.months,children:e.children})}function Qir(e){var t,n,r=e.initialProps,s=ea(),i=vke(),o=KL(),l=g.useState(!1),c=l[0],u=l[1];g.useEffect(function(){s.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),u(!0)))},[s.initialFocus,c,i.focus,i.focusTarget,i]);var d=[s.classNames.root,s.className];s.numberOfMonths>1&&d.push(s.classNames.multiple_months),s.showWeekNumber&&d.push(s.classNames.with_weeknumber);var f=Ar(Ar({},s.styles.root),s.style),h=Object.keys(r).filter(function(m){return m.startsWith("data-")}).reduce(function(m,v){var y;return Ar(Ar({},m),(y={},y[v]=r[v],y))},{}),p=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:qir;return a.jsx("div",Ar({className:d.join(" "),style:f,dir:s.dir,id:s.id,nonce:r.nonce,title:r.title,lang:r.lang},h,{children:a.jsx(p,{children:o.displayMonths.map(function(m,v){return a.jsx(Uir,{displayIndex:v,displayMonth:m},v)})})}))}function Zir(e){var t=e.children,n=gsr(e,["children"]);return a.jsx(Rsr,{initialProps:n,children:a.jsx(Qsr,{children:a.jsx(Cir,{initialProps:n,children:a.jsx(tir,{initialProps:n,children:a.jsx(sir,{initialProps:n,children:a.jsx(fir,{children:a.jsx(Oir,{children:t})})})})})})})}function Wir(e){return a.jsx(Zir,Ar({},e,{children:a.jsx(Qir,{initialProps:e})}))}function Qpe({className:e,classNames:t,showOutsideDays:n=!0,...r}){return a.jsx(Wir,{showOutsideDays:n,className:Z("p-3",e),classNames:{months:"flex flex-col space-y-4 sm:space-y-0 ",month:"space-y-4 text-caption",caption:"flex justify-between pt-1 items-center pl-2",caption_label:"text-label text-foreground",nav:"flex items-center",nav_button_previous:Z(Zn,"flex size-7 items-center justify-center rounded-md bg-transparent p-0 hover:bg-fill-subtle"),nav_button_next:Z(Zn,"flex size-7 items-center justify-center rounded-md bg-transparent p-0 hover:bg-fill-subtle"),dropdown_month:"w-full border-collapse space-y-1",weeknumber:"flex",day:Z("relative p-0 text-center focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-fill [&:has([aria-selected].day-outside)]:bg-fill-subtle [&:has([aria-selected].day-range-end)]:rounded-r-md",r.mode==="range"?"[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md":"[&:has([aria-selected])]:rounded-md","size-8 p-0 text-caption hover:bg-fill-subtle aria-selected:opacity-100"),day_range_start:"day-range-start rounded-l-md",day_range_end:"day-range-end rounded-r-md",day_selected:Z("bg-foreground! text-sidebar! hover:bg-foreground/90! focus:bg-foreground/90! focus:text-sidebar!",r.mode!=="range"&&"rounded-md"),day_today:"bg-fill text-foreground",day_outside:"day-outside text-muted-foreground opacity-50 aria-selected:bg-fill-subtle aria-selected:text-muted-foreground aria-selected:opacity-30",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-fill aria-selected:text-foreground",day_hidden:"invisible",head_cell:"text-meta text-muted-foreground",...t},...r})}const ukt=g.createContext(void 0);function YL(e){const t=g.useContext(ukt);if(t===void 0&&!e)throw new Error(Nr(47));return t}const Hir={...oL,disabled:e=>e.disabled,instantType:e=>e.instantType,openMethod:e=>e.openMethod,openChangeReason:e=>e.openChangeReason,modal:e=>e.modal,focusManagerModal:e=>e.focusManagerModal,stickIfOpen:e=>e.stickIfOpen,titleElementId:e=>e.titleElementId,descriptionElementId:e=>e.descriptionElementId,openOnHover:e=>e.openOnHover,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin};class Gir extends O_{constructor(t,n,r){const s=new j_;super(Kir(t,s,n,r),Yir(s),Hir)}setOpen=(t,n)=>{const r=n.reason===Ma,s=n.reason===vv&&n.event.detail===0,i=!t&&(n.reason===w_||n.reason==null),o=Z0e(n),l=this.select("activeTriggerId");if(!t&&n.reason===N0e&&n.trigger==null&&l!=null&&(n.trigger=this.context.triggerElements.getById(l)??this.select("activeTriggerElement")??void 0),this.context.onOpenChange?.(t,n),n.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(t,n);const c=()=>{const d={open:t,openChangeReason:n.reason};VH(d,t,n.trigger,o()),this.update(d)};r?(this.set("stickIfOpen",!0),this.context.stickIfOpenTimeout.start(Qft,()=>{this.set("stickIfOpen",!1)}),So.flushSync(c)):c();let u;s?u="click":i?u="dismiss":n.reason===C0&&(u="focus"),this.set("instantType",u)}}function Kir(e,t,n,r=!1){const s={...iL(),disabled:!1,modal:!1,focusManagerModal:!1,instantType:void 0,openMethod:null,openChangeReason:null,titleElementId:void 0,descriptionElementId:void 0,stickIfOpen:!0,openOnHover:!1,closeDelay:0,adaptiveOrigin:void 0,...e};return s.open&&e?.mounted===void 0&&(s.mounted=!0),s.floatingRootContext=UH(t,n,r),s}function Yir(e){return{popupRef:g.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:g.createRef(),beforeContentFocusGuardRef:g.createRef(),stickIfOpenTimeout:new Dm,triggerElements:e}}function EVe({props:e}){const{children:t,open:n,defaultOpen:r=!1,onOpenChange:s,onOpenChangeComplete:i,modal:o=!1,handle:l,triggerId:c,defaultTriggerId:u=null}=e,d=Jir(l,{modal:o,open:r,openProp:n,activeTriggerId:u,triggerIdProp:c});d.useControlledProp("openProp",n),d.useControlledProp("triggerIdProp",c);const f=d.useState("open"),h=d.useState("mounted"),p=d.useState("payload");d.useContextCallback("onOpenChange",s),d.useContextCallback("onOpenChangeComplete",i),mht(d,f),nL(d);const{forceUnmount:m}=rL(f,d,()=>{d.update({stickIfOpen:!0,openChangeReason:null})});d.useSyncedValues({modal:o}),g.useEffect(()=>{f||d.context.stickIfOpenTimeout.clear()},[d,f]),g.useImperativeHandle(e.actionsRef,()=>({unmount:m,close:()=>d.setOpen(!1,Xt(Y3))}),[m,d]);const v=f||h;return a.jsxs(ukt.Provider,{value:d,children:[l&&a.jsx(eL,{handle:l,store:d}),v&&a.jsx(eor,{store:d,modal:o}),typeof t=="function"?t({payload:p}):t]})}function Xir(e){return YL(!0)?a.jsx(EVe,{props:e}):a.jsx(V0e,{children:a.jsx(EVe,{props:e})})}function Jir(e,t){const n=BH((r,s)=>new Gir(t,r,s));return g.useEffect(()=>n.context.stickIfOpenTimeout.disposeEffect(),[n]),n}function eor({store:e,modal:t}){const n=e.useState("floatingRootContext"),r=k_(n,{outsidePressEvent:{mouse:t==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}}),s=r.reference,i=r.floating;return sL(e,{activeTriggerProps:s,inactiveTriggerProps:s,popupProps:i}),null}const tor=300,nor=g.forwardRef(function(t,n){const{render:r,className:s,style:i,disabled:o=!1,nativeButton:l=!0,handle:c,payload:u,openOnHover:d=!1,delay:f=tor,closeDelay:h=0,id:p,...m}=t,v=YL(!0),x=aL(c)??v;if(!x)throw new Error(Nr(74));const b=Zi(p),S=x.useState("isTriggerActive",b),k=x.useState("floatingRootContext"),j=x.useState("isOpenedByTrigger",b),C=x.useState("triggerPopupId",b),T=g.useRef(null),{registerTrigger:_,isMountedByThisTrigger:N}=tL(b,T,x,{payload:u,disabled:o,openOnHover:d,closeDelay:h}),E=x.useState("openChangeReason"),A=x.useState("stickIfOpen"),P=x.useState("openMethod"),L=x.useState("focusManagerModal"),F=lL(k,{enabled:!o&&d&&(P!=="touch"||E!==vv),mouseOnly:!0,move:!1,handleClose:cL(),restMs:f,delay:{close:h},triggerElementRef:T,isActiveTrigger:S,isClosing:()=>x.select("transitionStatus")==="ending"}),Q=S_(k,{stickIfOpen:A}),q=_Se(()=>x.select("open"),ne=>{x.set("openMethod",ne)}),B=x.useState("triggerProps",N),{getButtonProps:V,buttonRef:W}=gd({disabled:o,native:l}),M={open(ne){return ne&&E===vv?NN.open(ne):fP.open(ne)}},{preFocusGuardRef:K,handlePreFocusGuardFocus:D,handleFocusTargetFocus:$}=b1t(x,T),U=cn("button",t,{state:{disabled:o,open:j},ref:[W,n,_,T],props:[Q.reference,F,B,q,{[L0e]:"",id:b,"aria-haspopup":"dialog","aria-expanded":j,"aria-controls":C},m,V],stateAttributesMapping:M}),G=a.jsx(g.Fragment,{children:U},b);return N&&!L?a.jsxs(g.Fragment,{children:[a.jsx(kS,{ref:K,onFocus:D}),G,a.jsx(kS,{ref:x.context.triggerFocusTargetRef,onFocus:$})]}):G}),dkt=g.createContext(void 0);function ror(){const e=g.useContext(dkt);if(e===void 0)throw new Error(Nr(45));return e}const sor=g.forwardRef(function(t,n){const{keepMounted:r=!1,...s}=t;return YL().useState("mounted")||r?a.jsx(dkt.Provider,{value:r,children:a.jsx(J3,{ref:n,...s})}):null}),fkt=g.createContext(void 0);function ior(){const e=g.useContext(fkt);if(!e)throw new Error(Nr(46));return e}const oor=g.forwardRef(function(t,n){const{render:r,className:s,style:i,anchor:o,positionMethod:l,side:c,align:u,sideOffset:d,alignOffset:f,collisionBoundary:h="clipping-ancestors",collisionPadding:p,arrowPadding:m,sticky:v,disableAnchorTracking:y=!1,collisionAvoidance:x=RH,...b}=t,S=YL(),k=ror(),j=MH(),C=S.useState("floatingRootContext"),T=S.useState("mounted"),_=S.useState("open"),N=S.useState("openChangeReason"),E=S.useState("activeTriggerElement"),A=S.useState("modal"),P=S.useState("openMethod"),L=S.useState("positionerElement"),F=S.useState("instantType"),Q=S.useState("transitionStatus"),q=S.useState("adaptiveOrigin"),B=g.useRef(null),V=FH(L),W=hP({anchor:o,floatingRootContext:C,positionMethod:l,mounted:T,side:c,sideOffset:d,align:u,alignOffset:f,arrowPadding:m,collisionBoundary:h,collisionPadding:p,sticky:v,disableAnchorTracking:y,keepMounted:k,nodeId:j,collisionAvoidance:x,adaptiveOrigin:q}),M=C.useState("domReferenceElement");Ot(()=>{const U=M,G=B.current;if(U&&(B.current=U),G&&U&&U!==G){S.set("instantType",void 0);const ne=new AbortController;return V(()=>{S.set("instantType","trigger-change")},ne.signal),()=>{ne.abort()}}},[M,V,S]);const K=A===!0&&N!==Ma;iK(_&&K,P==="touch",L,E);const D=S.useStateSetter("positionerElement"),$={open:_,side:W.side,align:W.align,anchorHidden:W.anchorHidden,instant:F},z=pP(t,$,{styles:W.positionerStyles,transitionStatus:Q,props:b,refs:[n,D],hidden:!T,inert:!_});return a.jsxs(fkt.Provider,{value:W,children:[T&&K&&a.jsx(BL,{inert:mP(!_),cutout:E}),a.jsx(B0e,{id:j,children:z})]})}),aor=g.createContext(void 0);function lor(){const[e,t]=g.useState(0),n=ht(()=>(t(s=>s+1),()=>{t(s=>Math.max(0,s-1))}));return{context:g.useMemo(()=>({register:n}),[n]),hasClosePart:e>0}}const cor=g.forwardRef(function(t,n){const{render:r,className:s,style:i,initialFocus:o,finalFocus:l,...c}=t,u=YL(),d=ior(),f=CSe()!=null,{context:h,hasClosePart:p}=lor(),m=u.useState("open"),v=u.useState("openMethod"),y=u.useState("instantType"),x=u.useState("transitionStatus"),b=u.useState("popupProps"),S=u.useState("titleElementId"),k=u.useState("descriptionElementId"),j=u.useState("modal"),C=u.useState("mounted"),T=u.useState("openChangeReason"),_=u.useState("activeTriggerElement"),N=u.useState("floatingRootContext"),E=N.useState("floatingId"),A=u.useState("disabled"),P=u.useState("openOnHover"),L=u.useState("closeDelay");Tl({open:m,ref:u.context.popupRef,onComplete(){m&&u.context.onOpenChangeComplete?.(!0)}}),qH(N,{enabled:P&&!A,closeDelay:L});const F=o===void 0?fht(u.context.popupRef):o,Q=j!==!1&&p;u.useSyncedValue("focusManagerModal",Q);const q=u.useStateSetter("popupElement"),B={open:m,side:d.side,align:d.align,instant:y,transitionStatus:x},V=cn("div",t,{state:B,ref:[n,u.context.popupRef,q],props:[b,{id:E,role:"dialog",...xk,"aria-labelledby":S,"aria-describedby":k,onKeyDown(W){f&&Ck.has(W.key)&&W.stopPropagation()}},T_(x),c],stateAttributesMapping:__});return a.jsx(dP,{context:N,openInteractionType:v,modal:Q,disabled:!C||T===Ma,initialFocus:F,returnFocus:l,restoreFocus:"popup",previousFocusableElement:ni(_)?_:void 0,nextFocusableElement:u.context.triggerFocusTargetRef,beforeContentFocusGuardRef:u.context.beforeContentFocusGuardRef,children:a.jsx(aor.Provider,{value:h,children:V})})}),jp=Xir,of=g.forwardRef(({className:e,asChild:t,render:n,children:r,variant:s,size:i,tooltip:o,...l},c)=>{const u=$1t({render:n,asChild:t,children:r,variant:s,size:i,tooltip:o,className:e});return a.jsx(nor,{ref:c,className:u.className,render:u.render,...l,children:u.children})});of.displayName="PopoverTrigger";const ah=g.forwardRef(({className:e,container:t,align:n="center",alignOffset:r=0,side:s="bottom",sideOffset:i=4,anchor:o,positionMethod:l=Av,collisionBoundary:c,collisionPadding:u,sticky:d,arrowPadding:f,disableAnchorTracking:h,collisionAvoidance:p,...m},v)=>{const y=typeof e=="string"?e:void 0,x=tw(t),b={align:n,alignOffset:r,side:s,sideOffset:i,anchor:o,positionMethod:l,collisionBoundary:c,collisionPadding:u,sticky:d,arrowPadding:f,disableAnchorTracking:h,collisionAvoidance:p};return a.jsx(sor,{container:x,children:a.jsx(oor,{className:"z-50 outline-none",...b,children:a.jsx(cor,{ref:v,"data-slot":"popover-content",className:Z("z-50 w-72 origin-[var(--transform-origin)] rounded-xl text-foreground scrollbar-inset-xl focus-visible:outline-hidden",th,"data-[closed]:animate-out data-[closed]:fade-out-0 data-[closed]:zoom-out-95 data-[open]:animate-in data-[open]:fade-in-0 data-[open]:zoom-in-95","data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1",y&&/\bp[trblxy]?-\S+/.test(y)?!1:"px-3 py-3.5",e),...m})})})});ah.displayName="PopoverContent";const uor=({inputProps:e,field:t})=>{const{key:n,...r}=e,[s,i]=g.useState(void 0),[o,l]=g.useState(!1),c=oyt();g.useEffect(()=>{if(t.default){const f=new Date(t.default);nke(f)&&i(f)}},[t]);const u=f=>{i(f),f&&r.onChange({target:{value:f.toISOString(),name:e.name}}),l(!1)},d=()=>{i(void 0),r.onChange({target:{value:"",name:e.name}}),l(!1)};return a.jsxs(jp,{open:o,onOpenChange:l,children:[a.jsx(of,{asChild:!0,children:a.jsx(ce,{...c,variant:"default",size:"lg",className:Z("w-full",nwe),icon:a.jsx(T4,{}),children:s?a.jsx("span",{className:"text-foreground",children:_k(s,"PPP")}):a.jsx("span",{className:"text-muted-foreground",children:"Pick a date"})})}),a.jsxs(ah,{className:"w-auto bg-muted p-0",align:"start",children:[a.jsx(Qpe,{mode:"single",selected:s,onSelect:u,month:s,onMonthChange:i}),s&&a.jsx("div",{className:"p-3 pt-0",children:a.jsx(ce,{icon:a.jsx(Mn,{}),variant:"default",size:"lg",className:"w-full",onClick:d,children:"Clear"})})]})]})},dor=({field:e,path:t})=>{const{uiComponents:n}=JSe(),{control:r}=zr(),{fields:s,append:i,remove:o}=otr({control:r,name:t.join(".")}),l=e.schema?.[0]?.type;let c;l==="object"?c={}:l==="array"?c=[]:c=null;const u=e.schema?.[0];return u?a.jsx(n.ArrayWrapper,{label:k5(e),field:e,onAddItem:()=>i(c),children:s.map((d,f)=>a.jsx(gK,{value:[...t,f.toString()].join("."),children:a.jsx(n.ArrayElementWrapper,{onRemove:()=>o(f),index:f,children:a.jsx(Qj,{field:u,path:[...t,f.toString()]})})},d.id))}):a.jsx(n.ErrorMessage,{error:`[AutoForm] Unable to determine array element schema for "${k5(e)}"`})},hor=({field:e,path:t})=>{const{uiComponents:n}=JSe();return a.jsx(gK,{value:t.join("."),children:a.jsx(n.ObjectWrapper,{label:k5(e),field:e,children:Object.entries(e.schema??[]).map(([r,s])=>a.jsx(Qj,{field:s,path:[...t,s.key]},`${t.join(".")}.${s.key}`))})})},Qj=({field:e,path:t})=>{const{formComponents:n,uiComponents:r}=JSe(),{register:s,formState:{errors:i,defaultValues:o},getValues:l,control:c}=zr(),u=t.join("."),d=yVe(i,t)?.message,f=Wn({control:c,name:u}),h=f===void 0?l(u):f,p=g.useMemo(()=>{if(!o)return e.default;const x=yVe(o,t);return x===void 0?e.default:x},[o,t,e.default]),m=e.fieldConfig?.fieldWrapper||r.FieldWrapper;let v=()=>a.jsx(r.ErrorMessage,{error:`[AutoForm Configuration Error] No component found for type "${e.type}" nor a fallback`});e.type==="array"?v=dor:e.type==="object"?v=hor:e.type in n?v=n[e.type]??v:"fallback"in n&&(v=n.fallback);const y={...e,default:p};return a.jsx(m,{label:k5(e),error:d,id:u,field:y,children:a.jsx(v,{label:k5(e),field:y,value:h,error:d,id:u,path:t,inputProps:{"aria-required":e.required||void 0,key:`${u}-input`,...e.fieldConfig?.inputProps,...s(u)}},u)})},por=({field:e,path:t})=>{const{watch:n}=zr(),r=t.join("."),s=n(r),o=(e.schema?.flatMap(h=>h.schema||[])||[])?.filter(h=>h.fieldConfig?.customData?.isLiteral)||[],l=o[0];if(!l)return null;const c=o?.reduce((h,p)=>{const m=(p.fieldConfig?.customData?.literalValues??[]).map(v=>[v,v]);return h.options?.push(...m),h},{key:l.key,required:l.required,type:"select",default:l.default,description:l.description,options:[],fieldConfig:l.fieldConfig}),u=e.schema?.reduce((h,p)=>{const m=p.schema?.find(x=>x.fieldConfig?.customData?.isLiteral),v=m?.fieldConfig?.customData?.literalValues?.[0],y=p.schema?.filter(x=>x.key!==m?.key)??[];return v&&(h[v]=y),h},{}),d=e.schema?.filter(h=>!h.schema?.find(m=>m.fieldConfig?.customData?.isLiteral)),f=s?.[c.key];return a.jsxs("div",{children:[a.jsx(Qj,{field:c,path:[...t,c.key]},`${r}.${c.key}`),f&&u?.[f]&&u[f].map(h=>a.jsx(Qj,{field:h,path:[...t,h.key]},`${r}.${h.key}`)),d&&d.map(h=>a.jsx(Qj,{field:h,path:[...t,h.key]},`${r}.${h.key}`))]},e.key)},mor=({error:e})=>a.jsx(Wt,{variant:"destructive",title:e}),gor=["object","array"];function NVe({description:e,error:t}){return!e&&!t?null:a.jsxs(pt,{invalid:!!t,children:[e&&a.jsx(no,{children:e}),a.jsx(ns,{children:t})]})}const vor=({label:e,children:t,field:n,error:r})=>{const s=n.fieldConfig?.description;if(n.type==="record")return a.jsxs(E0,{className:"gap-2 pb-4 last:pb-0",children:[a.jsx(OC,{required:n.required,children:e}),t,a.jsx(NVe,{description:s,error:r})]});if(gor.includes(n.type))return a.jsxs("div",{className:"pb-4 last:pb-0",children:[t,a.jsx(NVe,{description:s,error:r})]});const i=n.type==="boolean";return a.jsxs(pt,{invalid:!!r,className:"pb-4 last:pb-0",children:[!i&&a.jsx(dt,{required:n.required,className:"block",children:e}),t,s&&a.jsx(no,{children:s}),a.jsx(ns,{children:r})]})};function yor({className:e,...t}){return a.jsx("form",{"data-slot":"form",className:Z("flex flex-col gap-4",e),...t})}const hkt=g.forwardRef(function(t,n){return a.jsx(syt,{ref:n,...t})}),xor=md(Z("flex w-full text-ellipsis text-foreground",In,"placeholder:text-muted-foreground placeholder:transition-opacity placeholder:duration-normal","focus:placeholder:opacity-70 motion-reduce:placeholder:transition-none","[&::-webkit-outer-spin-button]:m-0 [&::-webkit-outer-spin-button]:appearance-none","[&::-webkit-inner-spin-button]:m-0 [&::-webkit-inner-spin-button]:appearance-none","[&[type=number]]:[appearance:textfield]","[&::-webkit-search-cancel-button]:appearance-none"),{variants:{variant:{default:Z(Dht,"rounded-full",ewe),unstyled:rwe},size:{sm:Z(iv.sm,"px-[.75em]"),md:Z(iv.md,"px-[.75em]"),lg:Z(iv.lg,"px-[.85em]")}},defaultVariants:{variant:"default",size:"md"}});function bn({className:e,size:t,testId:n,variant:r,error:s,autoComplete:i,...o}){return a.jsx(hkt,{className:Z(xor({variant:Lht(r),size:t}),Pht,e),"data-testid":n,...ZH(s),...o,...dK(i),...Mx(o)})}const Zpe=Symbol("invalid");function AVe(e){if(e==="")return;const t=Number(e);return isNaN(t)?Zpe:t}const bor=({inputProps:e,field:t})=>{const{key:n,...r}=e;return a.jsx(bn,{type:"number",step:"any",...r,defaultValue:t.default!==void 0?Number(t.default):void 0,onChange:s=>{const i=AVe(s.target.value);i!==Zpe&&r.onChange({target:{value:i,name:e.name}})},onBlur:s=>{const i=AVe(s.target.value);i!==Zpe&&r.onChange({target:{value:i,name:e.name}})}})};function wor({label:e,children:t}){return e===vK||e===""?a.jsx("div",{className:"flex flex-col gap-2",children:t}):a.jsx(Sor,{label:e,children:t})}function Sor({label:e,children:t}){const n=g.useContext(gK),{expanded:r,invalid:s,setExpanded:i}=KSt(n,!1);return a.jsxs(gc,{open:r,onOpenChange:i,className:"motion-reduce:[&_[data-slot=collapsible-content]]:transition-none motion-reduce:[&_svg]:transition-none",children:[a.jsxs(Gl,{className:"flex min-h-11 w-full items-center gap-2 text-left text-caption text-muted-foreground",children:[a.jsx(Ha,{direction:"right",className:"size-3.5"}),a.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[a.jsx(Va,{"aria-hidden":!0,className:"size-3.5"}),e]}),s&&a.jsx(Y,{as:"span",variant:"meta",className:"ml-auto shrink-0 text-destructive-foreground",children:"Needs input"})]}),a.jsx(Kl,{keepMounted:!0,className:"border-l border-border pt-2 pl-4",children:t})]})}const kor=({inputProps:e,field:t})=>{const{onChange:n}=e,[r,s]=g.useState(()=>Object.entries(t.default||{}).map(([d,f])=>({id:d||ka(),key:d,value:f})));g.useEffect(()=>{r.length===0&&s([{id:ka(),key:"",value:""}])},[r]);const i=g.useCallback(d=>{const f=d.reduce((h,p)=>(p.key&&(h[p.key]=p.value),h),{});n?.({target:{value:f,name:e.name}})},[n,e.name]),o=(d,f,h)=>{s(p=>p.map(m=>m.id===d?{...m,[f]:h}:m))},l=()=>{i(r)},c=()=>{const d=[...r,{id:ka(),key:"",value:""}];s(d),i(d)},u=d=>{const f=r.filter(h=>h.id!==d);f.length===0&&f.push({id:ka(),key:"",value:""}),s(f),i(f)};return a.jsxs("div",{className:"grid gap-2",children:[r.map(d=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(bn,{placeholder:"Key",className:"flex-1","aria-label":"Key",value:d.key,onChange:f=>o(d.id,"key",f.target.value),onBlur:l}),a.jsx(bn,{placeholder:"Value",className:"flex-1","aria-label":"Value",value:d.value,onChange:f=>o(d.id,"value",f.target.value),onBlur:l}),a.jsx(ce,{type:"button",variant:"ghost",size:"icon-md",tooltip:"Remove pair","aria-label":"Remove pair",onClick:()=>u(d.id),children:a.jsx(Ipt,{})})]},d.id)),a.jsx(ce,{type:"button",variant:"ghost",size:"sm",className:"justify-self-start",onClick:c,icon:a.jsx(Dr,{}),children:"Add pair"})]})},Oor=({field:e,inputProps:t,value:n})=>{const{key:r,...s}=t;return a.jsxs(ms,{...s,value:n,onValueChange:i=>{const o={target:{value:i,name:t.name}};s.onChange(o)},children:[a.jsx(vs,{children:a.jsx(gs,{placeholder:"Select an option"})}),a.jsx(ys,{children:(e.options||[]).map(([i,o])=>a.jsx(hr,{value:i,children:o},i))})]})},jor=({inputProps:e,field:t})=>{const{key:n,className:r,...s}=e;return a.jsx(Pu,{...s,rows:1,className:Z("field-sizing-content max-h-48 min-h-control-md resize-none overflow-y-auto",r),defaultValue:t.default})},Cor=({children:e})=>a.jsx(ce,{type:"submit",children:e}),_or=({field:e,inputProps:t})=>{const n=t.name?.split(".")??[];return e.schema?.map((r,s)=>a.jsxs("div",{children:[a.jsx(Qj,{field:r,path:n},n.join(".")),s<(e.schema?.length??0)-1&&a.jsx(Y,{variant:"meta",className:"text-center",children:"OR"})]},r.key))};function Tor({schema:e,onSubmit:t,defaultValues:n,values:r,children:s,uiComponents:i,formComponents:o,withSubmit:l=!1,onFormInit:c,formProps:u={}}){const d=g.useMemo(()=>Str(e),[e]),f=zx({defaultValues:{...ktr(e),...n},values:r});g.useEffect(()=>{c&&c(f)},[c,f]);const h=g.useCallback(async m=>{const v=e.validateSchema(m);if(v.success)await t?.(v.data,f);else{f.clearErrors();let y=!1;v.errors?.forEach(x=>{const b=x.path.join(".");f.setError(b,{type:"custom",message:x.message},{shouldFocus:!y}),y=!0;const S=x.path?.slice?.(0,-1);S?.length>0&&f.setError(S.join("."),{type:"custom",message:x.message})})}},[e,t,f]),p=g.useMemo(()=>({schema:d,uiComponents:i,formComponents:o}),[d,i,o]);return a.jsx(S5,{...f,children:a.jsx(Atr,{value:p,children:a.jsxs(i.Form,{onSubmit:f.handleSubmit(h),...u,children:[d.fields.map(m=>a.jsx(Qj,{field:m,path:[m.key]},m.key)),s,l&&a.jsx(i.SubmitButton,{children:"Submit"})]})})})}const Ior={Form:yor,FieldWrapper:vor,ErrorMessage:mor,SubmitButton:Cor,ObjectWrapper:wor,ArrayWrapper:osr,ArrayElementWrapper:isr};function Eor({uiComponents:e,formComponents:t,readOnly:n,...r}){const s=g.useMemo(()=>({...Ior,...e}),[e]),i=g.useMemo(()=>{const o=l=>n===void 0?l:{...l,readOnly:n};return{string:l=>a.jsx(jor,{...l,inputProps:o(l.inputProps)}),number:l=>a.jsx(bor,{...l,inputProps:o(l.inputProps)}),boolean:l=>a.jsx(msr,{...l,inputProps:o(l.inputProps)}),date:l=>a.jsx(uor,{...l,inputProps:o(l.inputProps)}),select:l=>a.jsx(Oor,{...l,inputProps:o(l.inputProps)}),record:l=>a.jsx(kor,{...l,inputProps:o(l.inputProps)}),union:l=>a.jsx(_or,{...l,inputProps:o(l.inputProps)}),"discriminated-union":l=>a.jsx(por,{...l,inputProps:o(l.inputProps)}),...t}},[n,t]);return a.jsx(KSe,{value:n===!0,children:a.jsx(Tor,{...r,uiComponents:s,formComponents:i})})}function pkt(e){return e!=null&&typeof e=="object"&&"_zod"in e}function $u(e){if(!(e==null||typeof e!="object"))return pkt(e)?e._zod.def:e._def}function Nor(e){return typeof e.isOptional=="function"?e.isOptional():typeof e.safeParse=="function"?e.safeParse(void 0).success:!1}function km(e){if(e.shape&&typeof e.shape=="object")return e.shape;const t=$u(e);if(t?.shape)return typeof t.shape=="function"?t.shape():t.shape}function C5(e){const t=$u(e);return t?"innerType"in t?C5(t.innerType):"schema"in t?C5(t.schema):e:e}function Aor(e){const t=$u(e);if(t?.entries)return t.entries;if(t?.values)return t.values}function mkt(e){const t=$u(e);return t?.element??t?.type}function Por(e){return $u(e)?.valueType}function gkt(e){const t=$u(e);if(t?.values!==void 0)return Array.isArray(t.values)?t.values[0]:t.values;if(t?.value!==void 0)return t.value}function $or(e){const t=$u(e);if(t?.values!==void 0)return t.values;if(t?.value!==void 0)return[t.value]}function Ror(e){const t=$u(e);if(t?.defaultValue!==void 0)return typeof t.defaultValue=="function"?t.defaultValue():t.defaultValue}function xke(e){return $u(e)?.options}function wQ(e){const t=$u(e);if(t?.left&&t?.right)return{left:t.left,right:t.right};if(e.def?.left&&e.def?.right)return{left:e.def.left,right:e.def.right}}function Mor(e){return $u(e)?.checks??[]}function Dor(e){return e.some(t=>{if(pkt(t)){const n=$u(t);return n?.check==="string_format"&&n?.format==="datetime"}return t.kind==="datetime"})}function SQ(e){const t=km(e);if(t)return Object.keys(t).length===0;const n=wQ(e);return n?SQ(n.left)&&SQ(n.right):!1}function Sj(e){const t=$u(e);if(!t)return;const n=Ror(e);if(n!==void 0)return n;const r=gkt(e);if(r!==void 0&&(t.typeName==="ZodLiteral"||t.type==="literal"||e?.constructor?.name?.slice(1)==="ZodLiteral"))return r;if("innerType"in t)return Sj(t.innerType);if("schema"in t)return Sj(t.schema);if(km(e)&&!("left"in t))return XB(e);if("left"in t&&"right"in t){const i=km(t.left),o=km(t.right),l=i?XB(t.left):Sj(t.left),c=o?XB(t.right):Sj(t.right);return{...l,...c}}}function XB(e){const t=km(e);if(!t)return{};const n={};for(const[r,s]of Object.entries(t)){const i=Sj(s);i!==void 0&&(n[r]=i)}return n}function vkt(e,t){if(t?.fieldType)return t.fieldType;const n=e?.constructor?.name?.slice(1),r=$u(e),s=typeof r?.type=="string"?`Zod${r.type.charAt(0).toUpperCase()}${r.type.slice(1)}`:void 0,i=r?.typeName??s??n;if(i==="ZodObject"||i==="ZodIntersection")return"object";if(i==="ZodNumber")return"number";if(i==="ZodBoolean")return"boolean";if(i==="ZodString"){const o=Mor(e);return Dor(o)?"date":"string"}if(i==="ZodEnum"||i==="ZodNativeEnum")return"select";if(i==="ZodArray")return"array";if(i==="ZodRecord")return"record";if(i==="ZodUnion"){const o=xke(e);return o&&o.every(c=>{const u=km(c);return u?Object.values(u).some(d=>{const f=d?.constructor?.name?.slice(1),h=$u(d);return f==="ZodLiteral"||h?.typeName==="ZodLiteral"||h?.type==="literal"}):!1})?"discriminated-union":"union"}if(i==="ZodDiscriminatedUnion")return"discriminated-union";if(i==="ZodLiteral"){const o=gkt(e);return typeof o=="number"?"number":typeof o=="boolean"?"boolean":"string"}return"string"}function Wpe(e){const t=$u(e);if(t){if(t.typeName==="ZodEffects"&&t.effect?.type==="refinement"){const n=t.effect?.refinement;if(n){const r=Object.getOwnPropertySymbols(n);for(const s of r){const i=n[s];if(i&&typeof i=="object")return i}}}if("innerType"in t)return Wpe(t.innerType);if("schema"in t)return Wpe(t.schema)}}function u1(e,t){const n=C5(t),r=Wpe(t);let s=vkt(n,r);const i=Sj(t),o=Aor(n);let l=[];o&&(Array.isArray(o)?l=o.map(b=>[b,b]):l=Object.entries(o));let c=[];const u=km(n);u&&!wQ(n)&&(c=Object.entries(u).map(([b,S])=>u1(b,S)));const d=xke(n),f=n?.constructor?.name?.slice(1),h=$u(n),p=typeof h?.type=="string"?`Zod${h.type.charAt(0).toUpperCase()}${h.type.slice(1)}`:void 0,m=h?.typeName??p??f;(m==="ZodUnion"||m==="ZodDiscriminatedUnion")&&d&&(c=Object.entries(d).map(([b,S])=>u1(b,S)));const v=wQ(n);if(v){const{left:b,right:S}=v;let k=[],j=[];const C=km(b);if(C)k=Object.entries(C).map(([_,N])=>u1(_,N));else{const _=u1(e,b);k=_.schema??[_],s=_.type}const T=km(S);if(T)j=Object.entries(T).map(([_,N])=>u1(_,N));else{const _=u1(e,S);j=_.schema??[_],s=_.type}c=[...k,...j]}if(m==="ZodArray"){const b=mkt(n);b&&(c=[u1("0",b)])}const y=m==="ZodLiteral",x=y?$or(n):void 0;return{key:e,type:s,required:!Nor(t),default:i,description:n.description,fieldConfig:y||Object.keys(r??{})?.length>0?{...r,customData:{...r?.customData??{},...y?{isLiteral:y,literalValues:x}:{}}}:void 0,options:l,schema:c}}function Lor(e){const t=km(e);return t?{fields:Object.entries(t).map(([r,s])=>u1(r,s))}:{fields:[]}}function zor(e){const t=wQ(e);return t?[t.left,t.right]:xke(e)}function PVe(e,t){const n={};for(const[r,s]of Object.entries(e)){const i=t(r),o=i?kQ(s,i):s;o!==void 0&&(n[r]=o)}return n}function $Ve(e,t){if(!Object.values(t).every(s=>s===""||s===void 0)||e.safeParse(t).success)return!1;const r=e.safeParse(void 0);return r.success&&r.data===void 0}function kQ(e,t){const n=C5(t),r=zor(n);if(r){const l=r.reduce((c,u)=>kQ(c,u),e);return mD(l)&&$Ve(t,l)?void 0:l}const s=km(n);if(s&&mD(e)){const l=PVe(e,c=>s[c]);return $Ve(t,l)?void 0:l}const i=Por(n);if(i&&mD(e))return PVe(e,()=>i);if(Array.isArray(e)){const l=mkt(n);return l&&typeof l=="object"?e.map(c=>kQ(c,l)):e}if(!((e===""||e===null&&!t.safeParse(null).success)&&Sj(t)===void 0))return e}class For{_schema;constructor(t){if(!t)throw new Error("CustomZodProvider: schema is required");this._schema=t}getDefaultValues(){return XB(this._schema)}validateSchema(t){const n=kQ(t,this._schema),s=this._schema.safeParse(n);if(s.success)return{success:!0,data:s.data};const i=s.error;return{success:!1,errors:(i.issues??i.errors??[]).map(l=>({path:l.path,message:l.message}))}}parseSchema(){return Lor(this._schema)}}function Voe(e,t){return t?e[vK]:e}function Bor(e,t){return SQ(e)?yr({}):t?yr({[vK]:e.description?e:e.describe("Input")}):e}const ykt=g.createContext(null),Vor=({children:e})=>{const t=g.useContext(ykt);return t?a.jsx(cK,{...t,children:e}):null},Uor={SubmitButton:Vor};function bke({schema:e,onSubmit:t,onValuesChange:n,defaultValues:r,isSubmitLoading:s,submitButtonLabel:i,submitButtonIcon:o,submitButtonVariant:l,submitButtonFullWidth:c,className:u,readOnly:d,children:f,submitActions:h,leftActions:p}){const m=km(e)===void 0,v=g.useRef(null),y=g.useRef(n);g.useLayoutEffect(()=>{y.current=n},[n]),g.useEffect(()=>()=>v.current?.unsubscribe(),[]);const x=!!n,b=g.useCallback(T=>{v.current?.unsubscribe(),v.current=null,x&&(v.current=T.watch(_=>y.current?.(Voe(_,m))),y.current?.(Voe(T.getValues(),m)))},[x,m]),S=g.useMemo(()=>e?new For(Bor(e,m)):null,[e,m]),k=g.useMemo(()=>t?{isSubmitLoading:s,submitButtonLabel:i,submitButtonIcon:o,submitButtonVariant:l,submitButtonFullWidth:c,submitActions:h,leftActions:p}:null,[t,s,i,o,l,c,h,p]),j=g.useMemo(()=>m?r===void 0?void 0:{[vK]:r}:r,[m,r]),C=g.useCallback(async T=>{await t?.(Voe(T,m))},[t,m]);return S?a.jsx(ykt.Provider,{value:k,children:a.jsx(Eor,{schema:S,onSubmit:C,onFormInit:b,defaultValues:j,formProps:{className:u,noValidate:!0},uiComponents:Uor,withSubmit:!0,readOnly:d,children:f})}):(console.error("no form schema found"),null)}function wke(e){try{return{ok:!0,value:JSON.parse(e)}}catch(t){return{ok:!1,error:t instanceof Error?`Invalid JSON: ${t.message}`:"Invalid JSON"}}}function xkt(e,t){const n=vkt(C5(e));if(n==="object"&&!mD(t))return"Form input requires a JSON object. Correct the JSON first.";if(n==="array"&&!Array.isArray(t))return"Form input requires a JSON array. Correct the JSON first."}function bkt(e,t){const n=wke(t);if(!n.ok)return{ok:!1,errors:[n.error]};const r=e.safeParse(n.value);return r.success?{ok:!0,value:r.data}:{ok:!1,errors:r.error.issues.map(s=>`${s.path.join(".")||"Input"}: ${s.message}`)}}const qor=a.jsx(At,{children:a.jsx(Fm,{})});function Qor(e,t){if(!t)return{type:"form",value:e};const n=e??ber(),r=K1t(n);return r?{type:"simple",value:r}:{type:"json",value:JSON.stringify(n,null,2)}}const Ske=({schema:e,defaultValues:t,isSubmitLoading:n,submitButtonLabel:r,onSubmit:s,children:i,isProcessorWorkflow:o,submitActions:l,leftActions:c,headingSlot:u,collapsible:d=!0,submitButtonIcon:f=qor,submitButtonVariant:h="primary",submitButtonFullWidth:p,hideInputTypeLabel:m,inputTypeLabel:v="Run input",hideHeading:y})=>{const[x,b]=g.useState(()=>Qor(t,o)),S=g.useRef(t),[k,j]=g.useState([]);function C(){return x.type==="json"?wke(x.value):{ok:!0,value:x.type==="form"?S.current:x.value}}function T(F){const Q=bkt(e,F);Q.ok?s(Q.value):j(Q.errors)}function _(F){if(F===x.type)return;j([]);const Q=C();if(!Q.ok)return j([Q.error]);if(F==="json")return b({type:F,value:JSON.stringify(Q.value===void 0?{}:Q.value,null,2)});if(F==="simple"){const B=K1t(Q.value);return B?b({type:F,value:B}):j(["Simple input requires a messages array with text parts and a string phase. Correct the JSON first."])}const q=xkt(e,Q.value);return q?j([q]):b({type:F,value:Q.value})}const N=a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",children:"Trigger a run"}),E=!d&&!y,A=d||y||m,P=a.jsx(Ker,{value:x.type,onChange:_,disabled:n,includeSimple:o,compact:E}),L=a.jsxs(a.Fragment,{children:[!m&&a.jsxs("div",{className:"flex justify-between gap-3 px-5 py-3",children:[a.jsx(Y,{as:"p",variant:"caption",tone:"muted",children:v}),E&&a.jsx("div",{className:"shrink-0",children:P})]}),a.jsxs("div",{className:"px-5",children:[A&&a.jsx("div",{className:"pb-4",children:P}),a.jsx("div",{className:Z("pb-4",{"pointer-events-none opacity-50":n}),children:x.type==="json"?a.jsx(ker,{value:x.value,onChange:F=>{b({type:"json",value:F}),j([])},errors:k,isSubmitLoading:n,submitButtonLabel:r,submitButtonIcon:f,submitButtonVariant:h,submitButtonFullWidth:p,onSubmit:()=>T(x.value),submitActions:l,leftActions:c,children:i}):x.type==="simple"&&o?a.jsx(Ger,{schema:e,value:x.value,onChange:F=>b({type:"simple",value:F}),isSubmitLoading:n,submitButtonLabel:r,submitButtonIcon:f,submitButtonVariant:h,submitButtonFullWidth:p,onSubmit:s,submitActions:l,leftActions:c,children:i}):a.jsx(Zor,{schema:e,onValuesChange:F=>{S.current=F},defaultValues:x.value,isSubmitLoading:n,submitButtonLabel:r,submitButtonIcon:f,submitButtonVariant:h,submitButtonFullWidth:p,onSubmit:s,submitActions:l,leftActions:c,children:i})})]})]});return d?a.jsxs(gc,{defaultOpen:!0,children:[a.jsxs(Gl,{className:"flex w-full items-center gap-2 pb-3 text-left",children:[a.jsx(Ha,{direction:"right",className:"size-4 text-muted-foreground"}),u??N]}),a.jsx(Kl,{keepMounted:!0,children:L})]}):a.jsxs(a.Fragment,{children:[!y&&a.jsx("div",{className:"border-b border-border pb-3",children:u??N}),a.jsx("div",{children:L})]})},Zor=({schema:e,defaultValues:t,isSubmitLoading:n,submitButtonLabel:r,onSubmit:s,children:i,submitActions:o,leftActions:l,submitButtonIcon:c,submitButtonVariant:u,submitButtonFullWidth:d,onValuesChange:f})=>a.jsx(bke,{schema:e,defaultValues:t,onValuesChange:f,isSubmitLoading:n,submitButtonLabel:r,submitButtonIcon:c,submitButtonVariant:u,submitButtonFullWidth:d,onSubmit:s,readOnly:n,submitActions:o,leftActions:l,children:i});function Wor({zodSchema:e,isStreaming:t,onExecute:n,defaultValues:r,isViewingRun:s,isProcessorWorkflow:i,submitActions:o,leftActions:l,headingSlot:c,collapsible:u,submitButtonLabel:d="Run"}){return s?c&&a.jsx("div",{className:"pb-3",children:c}):e?a.jsx(Ske,{schema:e,defaultValues:r,isSubmitLoading:t,submitButtonLabel:d,inputTypeLabel:"Next run input",submitButtonVariant:"primary",submitButtonIcon:a.jsx(At,{children:a.jsx(Fm,{})}),onSubmit:n,isProcessorWorkflow:i,submitActions:o,leftActions:l,headingSlot:c,collapsible:u}):a.jsxs(a.Fragment,{children:[c&&a.jsx("div",{className:"border-b border-border pb-3",children:c}),a.jsxs("div",{className:"flex items-center justify-between gap-1 pt-3",children:[l??a.jsx("div",{}),a.jsxs("div",{className:"flex items-center gap-1",children:[o,a.jsxs(ce,{variant:"primary",disabled:t,onClick:()=>n(null),children:[t?a.jsx(At,{children:a.jsx(hc,{className:"animate-spin"})}):a.jsx(At,{children:a.jsx(Fm,{})}),d]})]})]})]})}const jl=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 9.08789 8.97168",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{d:"M1.98047 5.00977C2.17347 5.00977 2.33002 5.16639 2.33008 5.35938C2.33008 5.55242 2.17351 5.70898 1.98047 5.70898C1.27292 5.70915 0.699436 6.2827 0.699219 6.99023C0.699219 7.69795 1.27279 8.2723 1.98047 8.27246C2.68829 8.27246 3.2627 7.69805 3.2627 6.99023C3.26291 6.79738 3.4194 6.64063 3.6123 6.64062C3.80503 6.64084 3.9617 6.79751 3.96191 6.99023C3.96191 8.08413 3.07437 8.97168 1.98047 8.97168C0.886706 8.97152 0 8.08403 0 6.99023C0.000217392 5.89662 0.886841 5.00993 1.98047 5.00977ZM7.10742 5.00977C8.20105 5.00992 9.08767 5.89662 9.08789 6.99023C9.08789 8.08404 8.20119 8.97152 7.10742 8.97168C6.01359 8.97159 5.12598 8.08408 5.12598 6.99023C5.1262 6.79757 5.28294 6.64092 5.47559 6.64062C5.66849 6.64063 5.82497 6.79738 5.8252 6.99023C5.8252 7.698 6.39968 8.27238 7.10742 8.27246C7.81511 8.2723 8.38867 7.69796 8.38867 6.99023C8.38845 6.2827 7.81497 5.70914 7.10742 5.70898C6.91445 5.7089 6.75781 5.55236 6.75781 5.35938C6.75788 5.16644 6.91449 5.00985 7.10742 5.00977ZM4.54395 0C5.44471 0 6.17465 0.730134 6.1748 1.63086C6.1748 2.27964 5.79613 2.83941 5.24768 3.102C5.0501 3.1966 4.89355 3.37979 4.89355 3.59885V4.08919C4.89355 4.21279 4.94266 4.33133 5.03006 4.41873L6.80071 6.18938C6.87996 6.26863 6.99535 6.29199 7.10742 6.29199C7.49331 6.29206 7.80642 6.60438 7.80664 6.99023C7.80664 7.37627 7.49344 7.68938 7.10742 7.68945C6.72134 7.68945 6.4082 7.37632 6.4082 6.99023C6.40827 6.87818 6.38483 6.76276 6.3056 6.68353L4.8726 5.25053C4.69056 5.06849 4.39541 5.06853 4.21343 5.25061L2.78139 6.68339C2.70211 6.76271 2.67963 6.87809 2.67969 6.99023C2.67969 7.37632 2.36655 7.68945 1.98047 7.68945C1.59452 7.68929 1.28125 7.37622 1.28125 6.99023C1.28146 6.60443 1.59466 6.29215 1.98047 6.29199C2.09246 6.29199 2.2079 6.26771 2.28711 6.18854L4.05776 4.41874C4.1452 4.33133 4.19434 4.21276 4.19434 4.08912V3.59881C4.19434 3.37977 4.03781 3.19659 3.84026 3.10199C3.29183 2.83937 2.91309 2.2796 2.91309 1.63086C2.91324 0.730162 3.64322 4.61864e-05 4.54395 0Z",fill:"currentColor"})});function Hor({workflow:e,workflowId:t}){const n=Object.keys(e.steps??{}).length;return a.jsxs("div",{className:"flex w-full items-center gap-2 px-5",children:[a.jsx(At,{className:"shrink-0 text-muted-foreground",children:a.jsx(jl,{})}),a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",className:"truncate",children:e.name??t}),a.jsx(ii,{content:e.name??t,variant:"ghost",className:"shrink-0"}),a.jsxs($t,{className:"ml-auto shrink-0",children:[n," step",n===1?"":"s"]})]})}function Tk({initialKey:e,defaultValue:t,schema:n,serialize:r=JSON.stringify}){const[s]=g.useState(e),[i,o]=g.useState(()=>{try{const l=localStorage.getItem(s);if(l!==null){const c=n.safeParse(JSON.parse(l));if(c.success)return c.data}}catch{}return t});return g.useEffect(()=>{try{localStorage.setItem(s,r(i))}catch{}},[s,i,r]),[i,o]}function wkt({workflowId:e,paramsRunId:t,paramsRunStatus:n,workflow:r,isLoading:s,createWorkflowRun:i,streamWorkflow:o,observeWorkflowStream:l,isStreamingWorkflow:c,isCancellingWorkflowRun:u,cancelWorkflowRun:d,requestContext:f,runActionsSlot:h,canExecute:p}){const{result:m,setResult:v,payload:y,setPayload:x,setRunId:b,runId:S,runSnapshot:k,workflowError:j}=g.useContext(Wl),[C,T]=g.useState(!1),_=g.useRef(null),N=g.useRef(null),[E,A]=g.useState(),[P,L]=Tk({initialKey:`workflow-run-resource-id:${e}`,defaultValue:"",schema:vt()}),F=t||S,Q=E?.runId===F?E:void 0,q=F?m:null,B=Qvt(q,F),{zodSchemaToUse:V,hasStateSchema:W}=e7n(r),M=wG(q?.status),K=q?.status==="paused";g.useEffect(()=>()=>_.current?.abort(),[]);const D=async re=>{if(!r||C)return;_.current?.abort();const ue=new AbortController;_.current=ue,T(!0);try{A(void 0),v(null);const te=P.trim()||void 0,ie=await i({workflowId:e,resourceId:te});if(ue.signal.aborted)return;b(ie.runId),T(!1);const{initialState:se,inputData:ae}=re??{},he=W?ae:re;await o({workflowId:e,runId:ie.runId,inputData:he,initialState:se,requestContext:f,resourceId:te})}catch(te){ue.signal.aborted||Xe.error(te instanceof Error?te.message:"Error executing workflow")}finally{ue.signal.aborted||T(!1)}},$=async()=>{if(!F)return;const re=m?.status==="paused"||m?.status==="suspended"?m:void 0;try{const ue=await d({workflowId:e,runId:F});A({...ue,runId:F}),re&&v({...re,status:"canceled"})}catch{Xe.error("Error cancelling workflow run")}};if(g.useEffect(()=>{if(!t||!l)return;const re=`${e}:${t}`;N.current!==re&&(N.current=re,l({workflowId:e,runId:t}))},[t,l,e]),s)return a.jsx(jr,{className:"h-[calc(100vh-126px)] px-4 pt-2 pb-4",children:a.jsxs("div",{className:"space-y-4",children:[a.jsx(bt,{className:"h-10"}),a.jsx(bt,{className:"h-10"})]})});if(!r)return null;const z=B.length>0,U=q?.status==="running"||q?.status==="suspended",G=!!F,ne=q?.status??n??(c?"running":"pending"),X=a.jsx(s7n,{status:q?.status,cancelMessage:Q?.message??null,isCancelling:u,onCancel:$,disabled:!p}),ee=G?a.jsx(uer,{runId:F,status:ne,result:q,timestamp:k?.timestamp,resourceId:Tmt(k)}):a.jsx(Hor,{workflow:r,workflowId:e});return a.jsx("div",{className:"pt-3",children:a.jsxs("div",{children:[z&&c&&a.jsxs("div",{className:"-mt-5 flex items-center gap-2 border-b border-border bg-card px-5 py-2",children:[a.jsx(At,{children:a.jsx(hc,{className:"animate-spin text-foreground"})}),a.jsx(Y,{children:"Resuming workflow"})]}),p&&a.jsx(Wor,{zodSchema:V,defaultValues:y,isStreaming:C||c,onExecute:re=>{x(re),D(re)},isViewingRun:G,isProcessorWorkflow:r?.isProcessorWorkflow,collapsible:!1,headingSlot:ee,leftActions:t?void 0:a.jsx(_7n,{}),submitButtonLabel:C?"Starting…":"Run",submitActions:h?.({resourceId:P,setResourceId:L})},`${e}:${F||"new"}`),!p&&a.jsx(Y,{variant:"caption",tone:"muted",className:"px-5 py-2",children:"You don't have permission to execute workflows."}),M&&q&&a.jsx(WJn,{result:q,workflowError:j,className:"mx-5 mb-4"}),K&&p&&a.jsx("div",{className:"px-5 pt-3 pb-4",children:a.jsx(A7n,{requestContext:f,isStreaming:c,disabled:u||!!Q,children:X})}),U&&a.jsx("div",{"data-testid":"workflow-cancel-action",className:"flex justify-end px-5 pt-3 pb-4",children:X}),q&&a.jsx($Jn,{input:y,result:q},F)]})})}const Gor=({workflowId:e,runId:t,observeWorkflowStream:n,...r})=>{const{runSnapshot:s,isLoadingRunExecutionResult:i}=g.useContext(Wl),o=g.useCallback(()=>{!t||!s||wG(s.status)||n?.({workflowId:e,runId:t,storedStatus:s.status})},[e,t,s,n]);return i?a.jsxs("div",{className:"space-y-4 p-4",children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(bt,{className:"size-5 shrink-0 rounded-full"}),a.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[a.jsx(bt,{className:"h-4 w-24"}),a.jsx(bt,{className:"h-3 w-40"})]}),a.jsxs("div",{className:"shrink-0 space-y-2",children:[a.jsx(bt,{className:"ml-auto h-3 w-12"}),a.jsx(bt,{className:"ml-auto h-3 w-16"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx(bt,{className:"h-4 w-24"}),a.jsx(bt,{className:"h-7 w-28 rounded-md"})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx(bt,{className:"h-9 w-full rounded-md"}),a.jsx(bt,{className:"h-9 w-full rounded-md"}),a.jsx(bt,{className:"h-9 w-3/4 rounded-md"})]})]}):!s||!t?a.jsx("div",{className:"p-4",children:a.jsx(Y,{variant:"body",tone:"ink",className:"text-center",children:"No previous run"})}):a.jsx(wkt,{...r,paramsRunId:t,paramsRunStatus:s.status,workflowId:e,observeWorkflowStream:o},`${e}:${t}`)},Skt=g.createContext(void 0);function hf(e){const t=g.useContext(Skt);if(!e&&t===void 0)throw new Error(Nr(27));return t}const Kor=g.forwardRef(function(t,n){const{render:r,className:s,style:i,forceRender:o=!1,...l}=t,c=hf(),u=c.useState("open"),d=c.useState("nested"),f=c.useState("mounted"),h=c.useState("transitionStatus");return cn("div",t,{state:{open:u,transitionStatus:h},ref:[c.context.backdropRef,n],stateAttributesMapping:__,props:[{role:"presentation",hidden:!f,style:{userSelect:"none",WebkitUserSelect:"none"}},l],enabled:o||!d})}),xK=g.forwardRef(function(t,n){const{render:r,className:s,style:i,disabled:o=!1,nativeButton:l=!0,...c}=t,u=hf(),d=u.useState("open"),{getButtonProps:f,buttonRef:h}=gd({disabled:o,native:l}),p={disabled:o};function m(v){d&&u.setOpen(!1,Xt(N0e,v.nativeEvent))}return cn("button",t,{state:p,ref:[n,h],props:[{onClick:m},c,f]})}),kkt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,id:o,...l}=t,c=hf(),u=Zi(o);return c.useSyncedValueWithCleanup("descriptionElementId",u),cn("p",t,{ref:n,props:[{id:u},l]})}),Okt=g.createContext(void 0);function kke(){const e=g.useContext(Okt);if(e===void 0)throw new Error(Nr(26));return e}const jkt={...C_,...ih,nestedDialogOpen(e){return e?{"data-nested-dialog-open":""}:null}},Yor=g.forwardRef(function(t,n){const{render:r,className:s,style:i,finalFocus:o,initialFocus:l,...c}=t,u=hf(),d=u.useState("descriptionElementId"),f=u.useState("disablePointerDismissal"),h=u.useState("floatingRootContext"),p=u.useState("popupProps"),m=u.useState("modal"),v=u.useState("mounted"),y=u.useState("nested"),x=u.useState("nestedOpenDialogCount"),b=u.useState("open"),S=u.useState("openMethod"),k=u.useState("titleElementId"),j=u.useState("transitionStatus"),C=u.useState("role"),T=h.useState("floatingId");kke(),Tl({open:b,ref:u.context.popupRef,onComplete(){b&&u.context.onOpenChangeComplete?.(!0)}});const _=l===void 0?fht(u.context.popupRef):l,N=x>0,E=u.useStateSetter("popupElement"),P=cn("div",t,{state:{open:b,nested:y,transitionStatus:j,nestedDialogOpen:N},props:[p,{id:T,"aria-labelledby":k,"aria-describedby":d,role:C,...xk,hidden:!v,onKeyDown(L){Ck.has(L.key)&&L.stopPropagation()},style:{"--nested-dialogs":x}},c],ref:[n,u.context.popupRef,E],stateAttributesMapping:jkt});return a.jsx(dP,{context:h,openInteractionType:S,disabled:!v,closeOnFocusOut:!f,initialFocus:_,returnFocus:o,modal:m!==!1,restoreFocus:"popup",children:P})}),Ckt=g.forwardRef(function(t,n){const{keepMounted:r=!1,...s}=t,i=hf(),o=i.useState("mounted"),l=i.useState("modal"),c=i.useState("open");return o||r?a.jsx(Okt.Provider,{value:r,children:a.jsxs(J3,{ref:n,...s,children:[o&&l===!0&&a.jsx(BL,{ref:i.context.internalBackdropRef,inert:mP(!c)}),t.children]})}):null});function Xor({store:e,parentContext:t,isDrawer:n}){const r=e.useState("open"),s=e.useState("disablePointerDismissal"),i=e.useState("modal"),o=e.useState("popupElement"),l=e.useState("floatingRootContext"),[c,u]=g.useState(0),[d,f]=g.useState(0),h=c===0,p=k_(l,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?"intentional":{mouse:i==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}},outsidePress(m){if(!e.context.outsidePressEnabledRef.current||"button"in m&&m.button!==0)return!1;if("touches"in m){if(m.type==="touchend"){if(m.changedTouches.length!==1||m.touches.length!==0)return!1}else if(m.touches.length!==1)return!1}const v=qi(m);if(h&&!s){if(i){const y=e.context.internalBackdropRef.current,x=e.context.backdropRef.current;return y||x?y===v||x===v||ln(v,o)&&!v?.hasAttribute("data-base-ui-portal"):!0}return!0}return!1},escapeKey:h});return c1t(r&&i===!0,o),e.useContextCallback("onNestedDialogOpen",(m,v)=>{u(m),f(v)}),Ot(()=>(t?.onNestedDialogOpen&&(r?t.onNestedDialogOpen(c+1,d+(n?1:0)):t.onNestedDialogOpen(0,0)),()=>{t?.onNestedDialogOpen&&r&&t.onNestedDialogOpen(0,0)}),[n,r,c,d,t]),sL(e,{activeTriggerProps:p.reference,inactiveTriggerProps:p.trigger,popupProps:p.floating,nestedOpenDialogCount:c,nestedOpenDrawerCount:d}),null}const Jor={...oL,modal:e=>e.modal,nested:e=>e.nested,nestedOpenDialogCount:e=>e.nestedOpenDialogCount,nestedOpenDrawerCount:e=>e.nestedOpenDrawerCount,disablePointerDismissal:e=>e.disablePointerDismissal,openMethod:e=>e.openMethod,descriptionElementId:e=>e.descriptionElementId,titleElementId:e=>e.titleElementId,viewportElement:e=>e.viewportElement,role:e=>e.role};class ear extends O_{constructor(t,n,r){const s=new j_,i=tar(t,s,n,r);super(i,nar(s),Jor)}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};VH(r,t,n.trigger),this.update(r)}}function tar(e,t,n,r=!1){const s={...iL(),modal:!0,disablePointerDismissal:!1,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e};return s.floatingRootContext=UH(t,n,r),s}function nar(e){return{popupRef:g.createRef(),backdropRef:g.createRef(),internalBackdropRef:g.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:e,onOpenChange:void 0,onOpenChangeComplete:void 0}}function _kt(e,t){const{children:n,open:r,defaultOpen:s=!1,onOpenChange:i,onOpenChangeComplete:o,disablePointerDismissal:l=!1,modal:c=!0,actionsRef:u,handle:d,triggerId:f,defaultTriggerId:h=null}=t,p=e==="drawer",m=e==="alert-dialog",v=m?!0:c,y=m||l,x=m?"alertdialog":"dialog",b=hf(!0),S=b!=null,k={modal:v,disablePointerDismissal:y,nested:S,role:x},j=BH((A,P)=>new ear({open:s,openProp:r,activeTriggerId:h,triggerIdProp:f,...k},A,P),!0);j.useControlledProp("openProp",r),j.useControlledProp("triggerIdProp",f),j.useSyncedValues(k),j.useContextCallback("onOpenChange",i),j.useContextCallback("onOpenChangeComplete",o);const C=j.useState("open"),T=j.useState("mounted"),_=j.useState("payload");mht(j,C),nL(j);const{forceUnmount:N}=rL(C,j);g.useImperativeHandle(u,()=>({unmount:N,close:()=>j.setOpen(!1,Xt(Y3))}),[N,j]);const E=C||T;return a.jsxs(Skt.Provider,{value:j,children:[d&&a.jsx(eL,{handle:d,store:j}),E&&a.jsx(Xor,{store:j,parentContext:b?.context,isDrawer:p}),typeof n=="function"?n({payload:_}):n]})}function rar(e){return _kt("dialog",e)}const sar=g.forwardRef(function(t,n){const{render:r,className:s,style:i,children:o,...l}=t,c=kke(),u=hf(),d=u.useState("open"),f=u.useState("nested"),h=u.useState("transitionStatus"),p=u.useState("nestedOpenDialogCount"),m=u.useState("mounted"),v=u.useStateSetter("viewportElement"),y=p>0;return cn("div",t,{enabled:c||m,state:{open:d,nested:f,transitionStatus:h,nestedDialogOpen:y},ref:[n,v],stateAttributesMapping:jkt,props:[{role:"presentation",hidden:!m,style:{pointerEvents:d?void 0:"none"},children:o},l]})}),Tkt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,id:o,...l}=t,c=hf(),u=Zi(o);return c.useSyncedValueWithCleanup("titleElementId",u),cn("h2",t,{ref:n,props:[{id:u},l]})}),Ikt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,disabled:o=!1,nativeButton:l=!0,id:c,payload:u,handle:d,...f}=t,h=hf(!0),m=aL(d)??h;if(!m)throw new Error(Nr(79));const v=Zi(c),y=m.useState("floatingRootContext"),x=m.useState("isOpenedByTrigger",v),b=m.useState("triggerPopupId",v),S=g.useRef(null),{registerTrigger:k,isMountedByThisTrigger:j}=tL(v,S,m,{payload:u}),{getButtonProps:C,buttonRef:T}=gd({disabled:o,native:l}),_=S_(y),N=_Se(()=>m.select("open"),P=>{m.set("openMethod",P)}),E={disabled:o,open:x},A=m.useState("triggerProps",j);return cn("button",t,{state:E,ref:[T,n,k,S],props:[_.reference,A,N,{[L0e]:"",id:v,"aria-haspopup":"dialog","aria-expanded":x,"aria-controls":b},f,C],stateAttributesMapping:fP})});let $c=(function(e){return e.nestedDrawers="--nested-drawers",e.height="--drawer-height",e.frontmostHeight="--drawer-frontmost-height",e.swipeMovementX="--drawer-swipe-movement-x",e.swipeMovementY="--drawer-swipe-movement-y",e.snapPointOffset="--drawer-snap-point-offset",e.swipeStrength="--drawer-swipe-strength",e})({}),L1=(function(e){return e.swipeProgress="--drawer-swipe-progress",e})({});const Ekt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,forceRender:o=!1,...l}=t,c=hf(),u=c.useState("open"),d=c.useState("nested"),f=c.useState("mounted"),h=c.useState("transitionStatus");return cn("div",t,{state:{open:u,transitionStatus:h},ref:[c.context.backdropRef,n],stateAttributesMapping:__,props:[{role:"presentation",hidden:!f,style:{pointerEvents:u?void 0:"none",userSelect:"none",WebkitUserSelect:"none",[L1.swipeProgress]:"0",[$c.swipeStrength]:"1"}},l],enabled:o||!d})}),iar=xK,Nkt="data-drawer-content",OQ=g.forwardRef(function(t,n){const{render:r,className:s,style:i,...o}=t;return hf(),cn("div",t,{ref:n,props:[{[Nkt]:""},o]})}),Akt=kkt,oar=g.createContext(void 0);function Pkt(){return g.useContext(oar)}let E1=(function(e){return e[e.open=T8.open]="open",e[e.closed=T8.closed]="closed",e[e.startingStyle=T8.startingStyle]="startingStyle",e[e.endingStyle=T8.endingStyle]="endingStyle",e.expanded="data-expanded",e.nestedDrawerOpen="data-nested-drawer-open",e.nestedDrawerSwiping="data-nested-drawer-swiping",e.swipeDismiss="data-swipe-dismiss",e.swipeDirection="data-swipe-direction",e.swiping="data-swiping",e})({});const $kt=g.createContext(void 0);function bK(e){const t=g.useContext($kt);if(e!==!0&&t===void 0)throw new Error(Nr(90));return t}function Rkt(e,t){const n=e+t;return n>=0?t:-Math.sqrt(-n)-e}function RVe(e,t,n){if(!Number.isFinite(t)||t<=0)return null;if(typeof e=="number")return Number.isFinite(e)?e<=1?Pi(e,0,1)*t:e:null;const r=e.trim();if(r.endsWith("px")){const s=Number.parseFloat(r);return Number.isFinite(s)?s:null}if(r.endsWith("rem")){const s=Number.parseFloat(r);return Number.isFinite(s)?s*n:null}return null}function JB(e,t){let n=-1,r=1/0;for(let s=0;s<e.length;s+=1){const i=Math.abs(e[s]-t);i<r&&(r=i,n=s)}return n}function Mkt(){const e=hf(),{snapPoints:t,activeSnapPoint:n,setActiveSnapPoint:r,popupHeight:s}=bK(),i=e.useState("viewportElement"),[o,l]=g.useState(0),[c,u]=g.useState(16),d=ht(()=>{const m=wr(i).documentElement;l(i?i.offsetHeight:m.clientHeight);const v=parseFloat(getComputedStyle(m).fontSize);Number.isFinite(v)&&u(v)});Ot(()=>{if(d(),!i||typeof ResizeObserver!="function")return;const p=new ResizeObserver(d);return p.observe(i),()=>{p.disconnect()}},[d,i]);const f=g.useMemo(()=>{if(!t||t.length===0||o<=0||s<=0)return[];const p=Math.min(s,o),m=t.map(x=>{const b=RVe(x,o,c);if(b===null)return null;const S=Pi(b,0,p);return{value:x,height:S,offset:Math.max(0,s-S)}}).filter(x=>!!x);if(m.length<=1)return m;const v=[],y=[];for(let x=m.length-1;x>=0;x-=1){const b=m[x];y.some(k=>Math.abs(k-b.height)<=1)||(y.push(b.height),v.push(b))}return v.reverse(),v},[s,c,t,o]),h=g.useMemo(()=>{if(n===null)return;const p=f.find(x=>Object.is(x.value,n));if(p)return p;const m=Math.min(s,o),v=RVe(n,o,c);if(v===null)return;const y=Pi(v,0,m);return f[JB(f.map(x=>x.height),y)]},[n,s,f,c,o]);return{snapPoints:t,activeSnapPoint:n,setActiveSnapPoint:r,popupHeight:s,viewportHeight:o,resolvedSnapPoints:f,activeSnapPointOffset:h?.offset??null}}const Dkt=g.createContext(null);function aar(){return g.useContext(Dkt)}let MVe=!1;function lar(){MVe||(typeof CSS<"u"&&"registerProperty"in CSS&&([$c.swipeMovementX,$c.swipeMovementY,$c.snapPointOffset].forEach(e=>{try{CSS.registerProperty({name:e,syntax:"<length>",inherits:!1,initialValue:"0px"})}catch{}}),[{name:L1.swipeProgress,initialValue:"0"},{name:$c.swipeStrength,initialValue:"1"}].forEach(({name:e,initialValue:t})=>{try{CSS.registerProperty({name:e,syntax:"<number>",inherits:!1,initialValue:t})}catch{}})),MVe=!0)}const car={...__,expanded(e){return e?{[E1.expanded]:""}:null},nestedDrawerOpen(e){return e?{[E1.nestedDrawerOpen]:""}:null},nestedDrawerSwiping(e){return e?{[E1.nestedDrawerSwiping]:""}:null},swipeDirection(e){return{[E1.swipeDirection]:e}},swiping(e){return e?{[E1.swiping]:""}:null}},Lkt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,finalFocus:o,initialFocus:l,...c}=t,u=hf(),d=u.context.popupRef,{swipeDirection:f,frontmostHeight:h,hasNestedDrawer:p,nestedSwiping:m,nestedSwipeProgressStore:v,onPopupHeightChange:y,notifyParentFrontmostHeight:x,notifyParentHasNestedDrawer:b}=bK(),S=u.useState("descriptionElementId"),k=u.useState("disablePointerDismissal"),j=u.useState("floatingRootContext"),C=u.useState("popupProps"),T=u.useState("modal"),_=u.useState("mounted"),N=u.useState("nested"),E=u.useState("nestedOpenDrawerCount"),A=u.useState("transitionStatus"),P=u.useState("open"),L=u.useState("openMethod"),F=u.useState("titleElementId"),Q=u.useState("role"),q=j.useState("floatingId"),B=c.id??q,V=aar();kke();const{snapPoints:W,activeSnapPoint:M,activeSnapPointOffset:K}=Mkt(),D=E>0,$=V?.swiping??!1,z=V?.swipeStrength??null,[U,G]=g.useState(0),ne=g.useRef(0),X=ht(()=>{const me=d.current;if(!me)return;const ke=me.offsetHeight;if(ne.current>0&&h>ne.current&&ke>ne.current)return;if(ne.current>0&&p){const Ze=ne.current;G(Ze),y(Ze);return}const qe=ke;qe!==ne.current&&(ne.current=qe,G(qe),y(qe))});Ot(()=>{if(!_){ne.current=0,G(0),y(0);return}const me=d.current;if(!me||(lar(),X(),typeof ResizeObserver!="function"))return;const ke=new ResizeObserver(X);return ke.observe(me),()=>{ke.disconnect()}},[X,_,D,y,d]),Ot(()=>{const me=()=>{const qe=d.current;if(!qe)return;const Ze=v.getSnapshot();Ze>0?qe.style.setProperty(L1.swipeProgress,`${Ze}`):qe.style.setProperty(L1.swipeProgress,"0")};me();const ke=v.subscribe(me),Ee=d.current;return()=>{ke(),Ee&&Ee.style.setProperty(L1.swipeProgress,"0")}},[v,d]),Ot(()=>{if(P)return x?.(h),()=>{x?.(0)}},[h,P,x]),Ot(()=>b?(b(P||A==="ending"),()=>{b(!1)}):void 0,[b,P,A]),Tl({open:P,ref:d,onComplete(){P&&u.context.onOpenChangeComplete?.(!0)}});const ee=l===void 0?d:l,re=u.useStateSetter("popupElement"),ue={open:P,nested:N,transitionStatus:A,expanded:M===1,nestedDrawerOpen:D,nestedDrawerSwiping:m,swipeDirection:f,swiping:$};let te;U&&!(!p&&A!=="ending")&&(te=`${U}px`);const se=W&&W.length>0&&(f==="down"||f==="up");let ae=null;se&&K!==null&&(ae=f==="up"?-K:K);let he=V?V.getDragStyles():ai;if(se&&f==="down"){const me=K??0,ke=Number.parseFloat(String(he[$c.swipeMovementY]));$&&Number.isFinite(ke)?he={...he,transform:void 0,[$c.swipeMovementY]:`${Rkt(me,ke)}px`}:he={...he,transform:void 0}}const ge=cn("div",t,{state:ue,props:[C,{id:B,"aria-labelledby":F,"aria-describedby":S,role:Q,...xk,hidden:!_,onKeyDown(me){Ck.has(me.key)&&me.stopPropagation()},style:{...he,[L1.swipeProgress]:"0",[$c.nestedDrawers]:E,[$c.height]:te,[$c.snapPointOffset]:typeof ae=="number"?`${ae}px`:"0px",[$c.frontmostHeight]:h?`${h}px`:void 0,[$c.swipeStrength]:typeof z=="number"&&Number.isFinite(z)&&z>0?`${z}`:"1"}},c],ref:[n,d,re],stateAttributesMapping:car});return a.jsx(dP,{context:j,openInteractionType:L,disabled:!_,closeOnFocusOut:!k,initialFocus:ee,returnFocus:o,modal:T!==!1,restoreFocus:"popup",children:ge})}),zkt=Ckt;var DVe,LVe;function Fkt(e){const{children:t,open:n,defaultOpen:r=!1,onOpenChange:s,onOpenChangeComplete:i,disablePointerDismissal:o=!1,modal:l=!0,actionsRef:c,handle:u,triggerId:d,defaultTriggerId:f=null,swipeDirection:h="down",snapToSequentialPoints:p=!1,snapPoints:m,snapPoint:v,defaultSnapPoint:y,onSnapPointChange:x}=e,b=bK(!0),S=b?.onNestedSwipeProgressChange,k=b?.onNestedFrontmostHeightChange,j=b?.onNestedSwipingChange,C=b?.onNestedDrawerPresenceChange,[T,_]=g.useState(0),[N,E]=g.useState(0),[A,P]=g.useState(!1),[L,F]=g.useState(!1),[Q]=g.useState(uar),q=y!==void 0?y:m?.[0]??null,B=v!==void 0,[V,W]=Jd({controlled:v,default:q,name:"Drawer",state:"snapPoint"}),M=g.useRef(!1),K=g.useRef(!1),D=ht((ie,se)=>{const ae=se??Xt(Eo);x?.(ie,ae),!ae.isCanceled&&W(ie)}),$=g.useMemo(()=>B||!m||m.length===0?V:V===null||!m.some(ie=>Object.is(ie,V))?q:V,[V,B,q,m]),z=ht(ie=>{_(ie),!M.current&&ie>0&&E(ie)}),U=ht(ie=>{if(ie>0){M.current=!0,E(ie);return}M.current=!1,T>0&&E(T)}),G=ht(ie=>{P(ie)}),ne=ht(ie=>{Q.set(ie),S?.(ie)}),X=ht(ie=>{F(ie),j?.(ie)}),ee=ht((ie,se)=>{s?.(ie,se),!se.isCanceled&&!ie&&m&&m.length>0&&D(q,Xt(se.reason,se.event,se.trigger))}),re=g.useMemo(()=>({swipeDirection:h,swipeAreaActiveRef:K,snapToSequentialPoints:p,snapPoints:m,activeSnapPoint:$,setActiveSnapPoint:D,frontmostHeight:N,popupHeight:T,hasNestedDrawer:A,nestedSwiping:L,nestedSwipeProgressStore:Q,onNestedDrawerPresenceChange:G,onPopupHeightChange:z,onNestedFrontmostHeightChange:U,onNestedSwipingChange:X,onNestedSwipeProgressChange:ne,notifyParentFrontmostHeight:k,notifyParentSwipingChange:j,notifyParentSwipeProgressChange:S,notifyParentHasNestedDrawer:C}),[$,N,A,L,Q,C,S,j,k,G,U,ne,X,z,T,D,m,p,K,h]),ue=typeof t=="function"?ie=>a.jsxs(g.Fragment,{children:[DVe||(DVe=a.jsx(zVe,{})),t(ie)]}):a.jsxs(g.Fragment,{children:[LVe||(LVe=a.jsx(zVe,{})),t]}),te=_kt("drawer",{open:n,defaultOpen:r,onOpenChange:ee,onOpenChangeComplete:i,disablePointerDismissal:o,modal:l,actionsRef:c,handle:u,triggerId:d,defaultTriggerId:f,children:ue});return a.jsx($kt.Provider,{value:re,children:te})}function uar(){let e=0;const t=new Set;return{getSnapshot:()=>e,set(n){const r=Number.isFinite(n)?n:0;r!==e&&(e=r,t.forEach(s=>{s()}))},subscribe(n){return t.add(n),()=>{t.delete(n)}}}}function zVe(){const e=Pkt(),t=hf(!1),n=e?.setDrawerOpen,r=e?.removeDrawer,s=t.useState("open"),i=t.useState("nestedOpenDialogCount"),o=t.useState("popupElement"),l=i===0;return Ot(()=>{if(r)return()=>{r(t)}},[r,t]),Ot(()=>{n?.(t,s)},[s,n,t]),g.useEffect(()=>{if(!s||!l||!O4)return;const u=xi(o).CloseWatcher;if(!u)return;function d(p){t.select("open")&&t.setOpen(!1,Xt(Qkn,p))}const f=new u,h=Br(f,"close",d);return()=>{h(),f.destroy()}},[t,l,s,o]),null}function Bkt(e,t=!1){const{overflowY:n}=ud(e);return n!=="auto"&&n!=="scroll"?!1:t?e.clientHeight>0:e.scrollHeight>e.clientHeight}function dar(e,t=!1){const{overflowX:n}=ud(e);return n!=="auto"&&n!=="scroll"?!1:t?e.clientWidth>0:e.scrollWidth>e.clientWidth}function Hpe(e,t,n=!1){return t==="vertical"?Bkt(e,n):dar(e,n)}function far(e,t,n){let r=e;for(;ni(r)&&r!==t&&!sv(r);){for(const s of n)if(Hpe(r,s))return!0;r=gv(r)}return!1}function oE(e,t,n="vertical",r=!1){let s=ni(e)?e:null;for(;ni(s)&&s!==t&&!sv(s);){if(Hpe(s,n,r))return s;s=gv(s)}return Hpe(t,n,r)?t:null}function eV(e,t,n){return typeof e?.elementFromPoint=="function"?e.elementFromPoint(t,n):null}const har=40,par=10,mar=1,gar=50,FVe=16,yar=80,xar='button,a,input,select,textarea,label,[role="button"]';function Iy(e,t,n){switch(e){case"up":return-n;case"down":return n;case"left":return-t;case"right":return t;default:return 0}}function bar(e){const n=xi(e).getComputedStyle(e).transform;let r=0,s=0,i=1;if(n&&n!=="none"){const o=n.match(/matrix(?:3d)?\(([^)]+)\)/);if(o){const l=o[1].split(", ").map(parseFloat);l.length===6?(r=l[4],s=l[5],i=Math.sqrt(l[0]*l[0]+l[1]*l[1])):l.length===16&&(r=l[12],s=l[13],i=l[0])}}return{x:r,y:s,scale:i}}function I9(e){return Number.isFinite(e)&&e>0?e:null}function BVe(e,t){return`translate3d(${e.x}px,${e.y}px,0) scale(${t})`}function war(e){return e%2===1}function Uoe(e,t,n){const r=e[n];if(typeof r=="function")try{r.call(e,t)}catch(s){if(s&&typeof s=="object"&&"name"in s&&s.name==="NotFoundError")return;throw s}}function Sar(e){const{enabled:t,directions:n,elementRef:r,movementCssVars:s,canStart:i,ignoreSelectorWhenTouch:o=!0,ignoreScrollableAncestors:l=!1,swipeThreshold:c,onDismiss:u,onProgress:d,onCancel:f,onSwipeStart:h,onRelease:p,onSwipingChange:m,trackDrag:v=!0}=e,y=xar,x=n.length===1?n[0]:void 0,b=Math.max(0,typeof c=="number"?c:har),S=n.includes("left"),k=n.includes("right"),j=n.includes("up"),C=n.includes("down"),T=S||k,_=j||C,N=g.useMemo(()=>{const Se=[];return _&&Se.push("vertical"),T&&Se.push("horizontal"),Se},[T,_]),[E,A]=g.useState(void 0),[P,L]=g.useState(!1),[F,Q]=g.useState(!1),q=g.useRef({x:0,y:0}),B=g.useRef({x:0,y:0}),V=g.useRef(null),W=g.useRef({x:0,y:0,scale:1}),M=g.useRef(void 0),K=g.useRef(0),D=g.useRef(!1),$=g.useRef({x:0,y:0}),z=g.useRef(null),U=g.useRef(!1),G=g.useRef(!1),ne=g.useRef(null),X=g.useRef(!1),ee=g.useRef(!1),re=g.useRef({width:0,height:0}),ue=g.useRef(0),te=g.useRef(b),ie=g.useRef(null),se=g.useRef(null),ae=g.useRef(null),he=g.useRef({x:0,y:0}),ge=g.useRef(null),me=g.useRef(!1),ke=g.useRef(null),Ee=ht(Se=>{me.current!==Se&&(me.current=Se,L(Se),m?.(Se))});function qe(Se){if(!Se)return;const Pe=r.current,nt=ie.current;if(!Pe||!nt)return;const Pt=nt({element:Pe,direction:Se});te.current=Math.max(0,Pt)}const Ze=ht((Se,Pe)=>{const nt=Number.isFinite(Se)?Pi(Se,0,1):0,Pt=nt!==ue.current;let Vt=!1;if(Pe){const Ut=ge.current;Vt=!Ut||Ut.deltaX!==Pe.deltaX||Ut.deltaY!==Pe.deltaY||Ut.direction!==Pe.direction}!Pt&&!Vt||(ue.current=nt,Pe?ge.current=Pe:Pt&&(ge.current=null),d?.(nt,Pe))}),Fe=ht(Se=>{const Pe=r.current;if(!v||!Pe){Se||(ke.current=null);return}const nt=Pe.style,Pt=ke.current;Se?(Pt||(ke.current=[nt.transition,nt.transform]),nt.transition="none"):Pt&&([nt.transition,nt.transform]=Pt,ke.current=null);const Vt=B.current,Ut=W.current,xt=Vt.x-Ut.x,jn=Vt.y-Ut.y;Se&&(nt.transform=BVe(Vt,Ut.scale)),nt.setProperty(s.x,`${xt}px`),nt.setProperty(s.y,`${jn}px`)});function Ae(Se,Pe){if(Pe===null)return;const nt=ae.current;if(nt&&Pe>nt.time){const Pt=Math.max(Pe-nt.time,FVe);he.current={x:(Se.x-nt.x)/Pt,y:(Se.y-nt.y)/Pt}}ae.current={x:Se.x,y:Se.y,time:Pe}}const Be=g.useCallback(()=>{A(void 0),Ee(!1),Q(!1),Ze(0),te.current=b,ie.current=null,q.current={x:0,y:0},B.current={x:0,y:0},W.current={x:0,y:0,scale:1},M.current=void 0,K.current=0,D.current=!1,$.current={x:0,y:0},z.current=null,U.current=!1,V.current=null,G.current=!1,ne.current=null,X.current=!1,ee.current=!1,re.current={width:0,height:0},se.current=null,ae.current=null,he.current={x:0,y:0},ge.current=null,Fe(!1)},[Ee,b,Fe,Ze]);function je(Se){if("touches"in Se){const Pe=Se.touches[0];return Pe?{x:Pe.clientX,y:Pe.clientY}:null}return{x:Se.clientX,y:Se.clientY}}function _e(Se){return"touches"in Se?!0:Se.pointerType==="touch"}function Ue(Se,Pe){const nt=r.current?.getRootNode();return eV(nt,Se.x,Se.y)??qi(Pe)}function pe(Se,Pe){return T&&!_?oE(Se,Pe,"horizontal"):_&&!T?oE(Se,Pe,"vertical"):oE(Se,Pe,"vertical")??oE(Se,Pe,"horizontal")}function fe(Se,Pe,nt){X.current=!1;const Pt=_e(Se),Vt=Ue(Pe,Se.nativeEvent),xt=wr(r.current).body,jn=Pt&&xt?pe(Vt,xt):null,gn=nt?.ignoreScrollableTarget??!1;if(jn&&!gn||(X.current=!!(jn&&gn),(Vt?Vt.closest(y):!1)&&(!Pt||o)))return!1;const Ne=r.current;if(l&&Ne&&Vt&&N.length>0&&!(nt?.ignoreScrollableAncestors??!1)&&far(Vt,Ne,N))return!1;if(D.current=!1,M.current=void 0,K.current=0,q.current=Pe,se.current=I9(Se.timeStamp),$.current=Pe,V.current=Pe,te.current=b,ie.current=typeof c=="function"?c:null,Ne){re.current={width:Ne.offsetWidth,height:Ne.offsetHeight},qe(x);const He=bar(Ne);W.current=He,B.current={x:He.x,y:He.y},Ae({x:He.x,y:He.y},se.current),"touches"in Se||Uoe(Ne,Se.pointerId,"setPointerCapture")}return h?.(Se.nativeEvent),Ee(!0),z.current=null,U.current=!0,Ze(0),Fe(!0),!0}function Ie(){Ce(),X.current=!1,V.current=null}function Ce(){G.current=!1,ne.current=null}function le(Se){if(Ie(),!me.current)return;Ee(!1),z.current=null;const Pe=W.current;B.current={x:Pe.x,y:Pe.y},A(void 0),ee.current=!1,Fe(!1);const nt=r.current;nt&&Uoe(nt,Se.pointerId,"releasePointerCapture"),Ze(0,{deltaX:0,deltaY:0,direction:void 0}),f?.(Se.nativeEvent)}function ve(Se,Pe){const nt=xt=>Math.sign(xt)*Math.abs(xt)**.5,Pt=(xt,jn,gn)=>!jn&&xt<0||!gn&&xt>0?nt(xt):xt,Vt=T?Pt(Se,S,k):nt(Se),Ut=_?Pt(Pe,j,C):nt(Pe);return{x:Vt,y:Ut}}function be(Se,Pe,nt){const Pt=(xt,jn,gn,we,Ne)=>xt>0&&jn<=0&&we||xt<0&&jn>=Math.max(0,gn)&&Ne,Vt=Math.abs(Pe),Ut=Math.abs(nt);return _&&nt!==0&&(!T||Ut>=Vt)?Pt(nt,Se.scrollTop,Se.scrollHeight-Se.clientHeight,C,j):T&&Pe!==0&&(!_||Vt>Ut)?Pt(Pe,Se.scrollLeft,Se.scrollWidth-Se.clientWidth,k,S):null}const $e=ht(Se=>{if(!t||Se.defaultPrevented||Se.nativeEvent.defaultPrevented||!("touches"in Se)&&Se.button!==0)return;const Pe=je(Se);!Pe||(G.current=!0,ne.current=Pe,X.current=!1,ee.current=!("touches"in Se),!(i?i(Pe,{nativeEvent:Se.nativeEvent,direction:x}):!0))||fe(Se,Pe)&&Ce()});function De(Se,Pe,nt){if(!t||!me.current)return;const Pt=qi(Se.nativeEvent);if(_e(Se)&&!X.current){const Ur=Se.currentTarget;if(pe(Pt,Ur))return}if("touches"in Se||Se.preventDefault(),U.current&&(U.current=!1,v)){q.current=Pe;const Ur=I9(Se.timeStamp);Ur!==null&&(se.current=Ur)}const Vt=Pe.x,Ut=Pe.y,xt=nt.x,jn=nt.y;(jn<0&&Ut>$.current.y||jn>0&&Ut<$.current.y)&&($.current={x:$.current.x,y:Ut}),(xt<0&&Vt>$.current.x||xt>0&&Vt<$.current.x)&&($.current={x:Vt,y:$.current.y});const gn=Vt-q.current.x,we=Ut-q.current.y,Ne=Ut-$.current.y,He=Vt-$.current.x;let at=z.current;at===null&&T&&_&&Math.sqrt(gn*gn+we*we)>=mar&&(at=Math.abs(gn)>Math.abs(we)?"horizontal":"vertical",z.current=at);let ft;if(!M.current)at==="vertical"?we>0?ft="down":we<0&&(ft="up"):at==="horizontal"?gn>0?ft="right":gn<0&&(ft="left"):Math.abs(gn)>=Math.abs(we)?ft=gn>0?"right":"left":ft=we>0?"down":"up",ft&&(ft==="left"&&S||ft==="right"&&k||ft==="up"&&j||ft==="down"&&C)&&(M.current=ft,K.current=Iy(ft,gn,we),A(ft),qe(ft));else{const Ur=M.current,dr=Iy(Ur,He,Ne);dr>te.current?(D.current=!1,A(Ur)):!(S&&k)&&!(j&&C)&&K.current-dr>=par&&(D.current=!0)}const Zt=ve(gn,we);let Ft=W.current.x,Tt=W.current.y;at==="horizontal"?T&&(Ft+=Zt.x):(at==="vertical"||T&&(Ft+=Zt.x),_&&(Tt+=Zt.y));const gt=B.current,vn=Ft!==gt.x||Tt!==gt.y;B.current={x:Ft,y:Tt},vn&&Fe(!0),Ae({x:Ft,y:Tt},I9(Se.timeStamp));const dn=Ft-W.current.x,Pn=Tt-W.current.y,gr={deltaX:dn,deltaY:Pn,direction:M.current};let xs=0;const Fr=x??M.current;if(Fr){const Ur=Fr==="left"||Fr==="right"?re.current.width:re.current.height,dr=W.current.scale||1,Ti=Iy(Fr,dn,Pn);Ur>0&&dr>0&&Ti>0&&(xs=Ti/(Ur*dr))}Ze(xs,gr)}const We=ht(Se=>{if(!t)return;const Pe=B.current,nt=W.current,Pt=Pe.x-nt.x,Vt=Pe.y-nt.y,Ut={deltaX:Pt,deltaY:Vt,direction:M.current};if(!me.current){Ie(),Ze(0,Ut);return}Ee(!1),z.current=null,Ie(),ee.current=!1;const xt=r.current;xt&&("touches"in Se||Uoe(xt,Se.pointerId,"releasePointerCapture"));const jn=Pt,gn=Vt,we=se.current,Ne=I9(Se.timeStamp),He=we!==null&&Ne!==null&&Ne>we?Ne-we:0,at=He>0?Math.max(He,gar):0,ft=at>0?jn/at:0,Zt=at>0?gn/at:0;let Ft=he.current.x,Tt=he.current.y;const gt=ae.current;if(gt&&Ne!==null&&Ne>=gt.time){const xs=Ne-gt.time;if(xs<=yar){const Fr=Math.max(xs,FVe),Ur=Pe.x-gt.x,dr=Pe.y-gt.y,Ti=Ur/Fr,Ii=dr/Fr;Ti!==0&&(Ft=Ti),Ii!==0&&(Tt=Ii)}else Ft=0,Tt=0}const vn=p?.({event:Se.nativeEvent,direction:M.current,deltaX:jn,deltaY:gn,velocityX:ft,velocityY:Zt,releaseVelocityX:Ft,releaseVelocityY:Tt}),dn=typeof vn=="boolean";if(D.current&&!dn){B.current={x:nt.x,y:nt.y},A(void 0),Fe(!1),Ze(0,Ut);return}let Pn=!1,gr;if(dn)Pn=vn,gr=M.current??x;else for(const xs of n)if(Iy(xs,jn,gn)>te.current){Pn=!0,gr=xs;break}Pn&&gr?(A(gr),Q(!0),Fe(!1),u?.(Se.nativeEvent,{direction:gr})):(B.current={x:nt.x,y:nt.y},A(void 0),Fe(!1),Ze(0,Ut))}),tt=ht(Se=>{const Pe=je(Se);if(!Pe)return;let nt=!1;if(!("touches"in Se)){const Ut=war(Se.buttons);if(Ut&&(ee.current=!0),Se.buttons!==0&&!Ut){le(Se);return}if(Se.buttons===0&&ee.current){if(!me.current){We(Se);return}nt=!0}}if(!P&&G.current){if(!_e(Se)&&(Se.defaultPrevented||Se.nativeEvent.defaultPrevented)){Ie();return}if(i?i(Pe,{nativeEvent:Se.nativeEvent,direction:x}):!0){const xt=ne.current;let jn=!1;if(_e(Se)){const we=r.current;if(xt&&we){const Ne=Ue(Pe,Se.nativeEvent),at=wr(we).body,ft=at?pe(Ne,at):null;if(ft&&(ln(we,ft)||ln(ft,we))){const Zt=Pe.x-xt.x,Ft=Pe.y-xt.y,Tt=be(ft,Zt,Ft);if(Tt===!1)return;Tt===!0&&(jn=!0)}}}fe(Se,Pe,{ignoreScrollableTarget:jn,ignoreScrollableAncestors:jn})&&(xt&&jn?(Ce(),q.current=xt,$.current=xt,V.current=xt,U.current=!1):(Ce(),X.current=!1))}}const Pt=V.current,Vt=Pt===null?{x:0,y:0}:{x:Pe.x-Pt.x,y:Pe.y-Pt.y};V.current=Pe,De(Se,Pe,Vt),nt&&!("touches"in Se)&&We(Se)}),st=ht((Se,Pe)=>{tt({touches:Se.touches,currentTarget:Pe,nativeEvent:Se,defaultPrevented:Se.defaultPrevented,timeStamp:Se.timeStamp})}),Ge=g.useCallback(()=>{const Se=me.current,Pe=B.current,nt=W.current,Pt=Pe.x-nt.x,Vt=Pe.y-nt.y;return!Se&&Pt===0&&Vt===0&&!F?{[s.x]:"0px",[s.y]:"0px"}:{transition:Se?"none":void 0,transform:Se?BVe(Pe,nt.scale):void 0,[s.x]:`${Pt}px`,[s.y]:`${Vt}px`}},[F,s]),Le=g.useCallback(()=>t?{onPointerDown:$e,onPointerMove:tt,onPointerUp:We,onPointerCancel:We}:{},[t,We,tt,$e]),ze=g.useCallback(()=>t?{onTouchStart:$e,onTouchMove:tt,onTouchEnd:We,onTouchCancel:We}:{},[t,We,tt,$e]);return{swiping:P,swipeDirection:E,dragDismissed:F,getPointerProps:Le,getTouchProps:ze,moveNative:st,getDragStyles:Ge,reset:Be}}const Vkt=Tkt,kar=Ikt,Oar=g.createContext(void 0);function jar(){return g.useContext(Oar)}const Gpe=10,VVe=.5,UVe=.5,Car=300,qVe=4,QVe=.2,_ar=4,qoe=80,ZVe=360,WVe=.1,Tar=1,HVe=6,Iar=2,Ear=`[${Nkt}]`,Ukt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,children:o,...l}=t,c=hf(),u=c.context.popupRef,d=c.context.backdropRef,{swipeDirection:f,notifyParentSwipingChange:h,notifyParentSwipeProgressChange:p,frontmostHeight:m,snapToSequentialPoints:v,swipeAreaActiveRef:y}=bK(),x=Pkt(),{snapPoints:b,resolvedSnapPoints:S,activeSnapPoint:k,activeSnapPointOffset:j,setActiveSnapPoint:C,popupHeight:T}=Mkt(),_=c.useState("open"),N=c.useState("mounted"),E=c.useState("nested"),A=c.useState("nestedOpenDrawerCount"),P=c.useState("viewportElement"),L=c.useState("popupElement"),F=x?.visualStateStore,Q=A>0,q=f==="left"||f==="right"?"horizontal":"vertical",B=q==="vertical",V=B?"horizontal":"vertical",[W,M]=g.useState(null),K=g.useRef(void 0),D=g.useRef(null),$=wS(),z=g.useRef(!1),U=g.useRef(!1),G=g.useRef(""),ne=g.useRef(!1),X=g.useRef(!1),ee=g.useRef(null),re=jar(),ue=g.useMemo(()=>{if(!b||b.length<2||S.length<2||f!=="down"&&f!=="up")return null;const pe=S.map(le=>le.offset).sort((le,ve)=>le-ve),fe=pe[0],Ce=pe[1]-fe;return{minOffset:fe,range:Ce}},[S,b,f]),te=g.useMemo(()=>!ue||j===null?null:Pi((j-ue.minOffset)/ue.range,0,1),[j,ue]),ie=g.useMemo(()=>b&&b.length>0&&(f==="down"||f==="up")?f==="down"?["down","up"]:["up","down"]:[f],[b,f]),se=ht(pe=>{u.current?.toggleAttribute(E1.swipeDismiss,pe),d.current?.toggleAttribute(E1.swipeDismiss,pe)}),ae=ht(()=>{se(!1),u.current?.removeAttribute(EN.endingStyle),M(null)}),he=ht(()=>{U.current&&(U.current=!1,h?.(!1))}),ge=ht((pe,fe,Ie)=>{const Ce=_&&!E&&fe,le=Ce?pe:0,ve=_&&fe?pe:0;Ie&&p&&(p(ve),ve<=0&&he()),F?.set({swipeProgress:le,frontmostHeight:le>0?m:0});const be=d.current;if(!be)return;const $e=Ce&&le>0;be.style.setProperty(L1.swipeProgress,$e?`${le}`:"0"),$e&&m>0?be.style.setProperty($c.height,`${m}px`):be.style.removeProperty($c.height)});function me(pe,fe,Ie,Ce,le,ve,be,$e){const De=qkt(pe,fe);if(De<=0)return null;const tt=((fe==="down"||fe==="up")&&b&&b.length>0?j??0:0)+Iy(fe,Ie,Ce),st=Math.max(0,De-tt);if(st<=0)return null;const Ge=Iy(fe,be,$e),Le=Math.abs(Ge)>0?Ge:Iy(fe,le,ve);if(Le<=QVe)return null;const ze=Pi(Le,QVe,_ar),Pe=(Pi(st/ze,qoe,ZVe)-qoe)/(ZVe-qoe);return WVe+Pe*(Tar-WVe)}function ke(pe){if(U.current||!pe)return;const fe=pe.direction??f,Ie=Iy(fe,pe.deltaX,pe.deltaY);Math.abs(Ie)<Gpe||(U.current=!0,h?.(!0))}const Ee=Sar({enabled:N&&!Q,directions:ie,elementRef:c.context.popupRef,ignoreSelectorWhenTouch:!1,ignoreScrollableAncestors:!0,movementCssVars:{x:$c.swipeMovementX,y:$c.swipeMovementY},onSwipeStart(pe){if("touches"in pe||pe.pointerType==="touch")return;const fe=u.current,Ce=wr(fe).getSelection?.();if(!Ce||Ce.isCollapsed)return;const le=_r(Ce.anchorNode)?Ce.anchorNode:Ce.anchorNode?.parentElement,ve=_r(Ce.focusNode)?Ce.focusNode:Ce.focusNode?.parentElement;!ln(fe,le)&&!ln(fe,ve)||Ce.removeAllRanges()},onSwipingChange(pe){z.current=pe,Qoe(c.context.backdropRef.current,pe),!pe&&!p&&he()},swipeThreshold({element:pe,direction:fe}){return KVe(pe,fe)},canStart(pe,fe){const Ie=c.context.popupRef.current;if(!Ie)return!1;const Ce=Ie.ownerDocument,le=eV(Ie.getRootNode(),pe.x,pe.y);if(!le||!ln(Ie,le))return!1;const ve=fe.nativeEvent;return!(("touches"in ve||ve.pointerType==="touch")&&YVe(Ce,Ie))},onProgress(pe,fe){ke(fe);const Ie=!!(b&&b.length>0);if(z.current&&f==="down"&&Ie&&fe){const le=c.context.popupRef.current;le&&(le.style.removeProperty("transform"),le.style.setProperty($c.swipeMovementY,`${Rkt(j??0,fe.deltaY)}px`))}let Ce=pe;if(ue&&T>0){const le=j??ue.minOffset,ve=be=>Pi((be-ue.minOffset)/ue.range,0,1);fe&&Number.isFinite(fe.deltaY)?Ce=ve(Pi(le+fe.deltaY,0,T)):te!==null&&(Ce=te)}ge(Ce,!0,!0)},onRelease({event:pe,deltaX:fe,deltaY:Ie,direction:Ce,velocityX:le,velocityY:ve,releaseVelocityX:be,releaseVelocityY:$e}){const De=c.context.popupRef.current;if(!De){ae();return}const We=De;function tt(we){he(),se(!0),We.style.removeProperty("transition"),We.setAttribute(EN.endingStyle,""),So.flushSync(()=>{M(me(We,we,fe,Ie,le,ve,be,$e))})}if(!b||b.length===0){if(!Ce){ae();return}const we=Iy(Ce,fe,Ie);if(we<=0)return ae(),!1;if(Iy(Ce,le,ve)>=VVe)return tt(Ce),!0;const Ne=we>KVe(We,Ce);return Ne?tt(Ce):ae(),Ne}if(f!=="down"&&f!=="up"){ae();return}if(!T)return ae(),!1;if(S.length===0){ae();return}const st=f==="down"?Ie:-Ie,Ge=Math.sign(st),Le=f==="down"?$e:-$e,ze=f==="down"?ve:-ve;let Se=Le;if(Ge!==0&&Math.abs(st)>=Gpe){const we=Math.sign(Se);we!==0&&we!==Ge&&(Se=ze)}const Pe=j??0,nt=Pi(Pe+st,0,T),Pt=Math.abs(Se)>=UVe?Pi(Se,-qVe,qVe)*Car:0,Vt=v?nt:Pi(nt+Pt,0,T),Ut=Xt(x8,pe),xt=()=>(K.current=k,C(null,Ut),tt(f),!0);if(v){const we=[...S].sort((vn,dn)=>vn.offset-dn.offset),Ne=we.map(vn=>vn.offset),He=JB(Ne,Pe);let at=we[JB(Ne,Vt)];const ft=Math.sign(Se),Zt=Ge!==0&&ft!==0&&ft===Ge&&Math.abs(Se)>=UVe;let Ft=Vt;if(Zt){const vn=Pi(He+Ge,0,we.length-1);if(vn!==He){const dn=we[vn];(Ge>0?Vt<dn.offset:Vt>dn.offset)&&(at=dn,Ft=dn.offset)}else if(Ge>0)return xt()}const Tt=Math.abs(Ft-T),gt=Math.abs(Ft-at.offset);return Tt<gt?xt():(C(at.value,Ut),ae(),!1)}if(Se>=VVe&&st>0)return xt();const jn=S[JB(S.map(we=>we.offset),Vt)];return Math.abs(Vt-T)<Math.abs(Vt-jn.offset)?xt():(C(jn.value,Ut),ae(),!1)},onDismiss(pe){F?.set({swipeProgress:0,frontmostHeight:0});const fe=c.context.backdropRef.current;fe&&(fe.style.setProperty(L1.swipeProgress,"0"),fe.style.removeProperty($c.height));const Ie=Xt(x8,pe);if(c.setOpen(!1,Ie),Ie.isCanceled){const Ce=K.current;Ce!==void 0&&C(Ce,Xt(x8,pe)),K.current=void 0,D.current?.(),ae();return}if(c.select("open")){const Ce=pe;$.request(()=>{if(c.select("open")){const le=K.current;le!==void 0&&C(le,Xt(x8,Ce)),K.current=void 0,ae(),D.current?.()}else K.current=void 0});return}K.current=void 0,se(!0)}}),qe=Ee.getPointerProps(),Ze=Ee.getTouchProps(),{moveNative:Fe,reset:Ae}=Ee;D.current=Ae,g.useEffect(()=>{const pe=P??L;if(!pe)return;const fe=pe,Ie=wr(fe);function Ce(ve,be,$e){const De=B?$e.clientY-be.lastY:$e.clientX-be.lastX;if(ve.touches.length===2||YVe(Ie,fe)||!_||!N||Q||Lar(be,ve,$e,B))return;const tt=be.scrollTarget;if(!tt||tt===Ie.documentElement||tt===Ie.body){ve.cancelable&&ve.preventDefault(),ve.stopPropagation(),Fe(ve,fe);return}if(!zar(tt,q)){ve.cancelable&&ve.preventDefault(),ve.stopPropagation();return}if(De!==0){const st=Far(tt,q,f,De);be.allowSwipe?ve.cancelable&&ve.preventDefault():ve.cancelable&&st?(be.allowSwipe=!0,ve.preventDefault()):be.allowSwipe=!1}be.allowSwipe===!0&&(ve.stopPropagation(),Fe(ve,fe))}function le(ve){if(re?.onTouchMove(ve),X.current)return;const be=ee.current,$e=ve.touches[0];!$e||!be||(Ce(ve,be,$e),Dar(be,$e))}return Br(Ie,"touchmove",le,{passive:!1,capture:!0})},[N,Q,_,L,B,q,f,Fe,P,re]),Ot(()=>{!ue||Ee.swiping||ge(!_||E?0:te??0,!0,!1)},[ge,m,E,p,_,te,ue,Ee.swiping,c,F]),Ot(()=>{if(p)return _||p(0),()=>{p(0)}},[p,_]),Ot(()=>{_&&(y.current||Ae(),ae())},[ae,_,Ae,y]),Ot(()=>{const pe=d.current;return()=>{F?.set({swipeProgress:0,frontmostHeight:0}),Qoe(pe,!1);const fe=d.current;fe!==pe&&Qoe(fe,!1),he()}},[d,he,F]);const Be=g.useMemo(()=>({swiping:Ee.swiping,getDragStyles:Ee.getDragStyles,swipeStrength:W??null,setSwipeDismissed:se}),[se,Ee.getDragStyles,Ee.swiping,W]);function je(pe){X.current=pe,ee.current=null}function _e(){je(!1),G.current="",ne.current=!1}function Ue(pe){return G.current="",pe.pointerType!=="touch"}return a.jsx(sar,{ref:n,className:s,style:i,render:r,...Ol(l,{onPointerDown(pe){if(G.current=pe.pointerType,ne.current=pe.pointerType==="pen",!_||!N||Q)return;const fe=eV(pe.currentTarget.getRootNode(),pe.clientX,pe.clientY);GVe(fe)||Nar(fe)||pe.pointerType!=="touch"&&qe.onPointerDown?.(pe)},onPointerMove(pe){pe.pointerType!=="touch"&&qe.onPointerMove?.(pe)},onPointerUp(pe){Ue(pe)&&qe.onPointerUp?.(pe)},onPointerCancel(pe){Ue(pe)&&qe.onPointerCancel?.(pe)},onTouchStart(pe){if(G.current==="pen"&&ne.current){ne.current=!1,je(!1);return}if(!_||!N||Q){je(!1);return}const Ie=pe.touches[0];if(!Ie)return;if(Mar(pe)){je(!1);return}const Ce=pe.currentTarget,le=eV(Ce.getRootNode(),Ie.clientX,Ie.clientY),ve=qi(pe.nativeEvent),be=_r(ve)?ve:Ce;if(!ln(Ce,be)){je(!0);return}if(re?.onTouchStart(pe),GVe(le)){je(!0);return}X.current=!1;const $e=oE(be,Ce,q),De=oE(be,Ce,V)!=null;let We=null;$e&&(We=Zkt($e,q,f)?null:!1),ee.current={startX:Ie.clientX,startY:Ie.clientY,lastX:Ie.clientX,lastY:Ie.clientY,scrollTarget:$e,hasCrossAxisScrollableContent:De,allowSwipe:We,preserveNativeCrossAxisScroll:!1,drawerAxisAttributed:!1},Ze.onTouchStart?.(pe)},onTouchEnd(pe){re?.onTouchEnd(pe),_e(),Ze.onTouchEnd?.(pe)},onTouchCancel(pe){re?.onTouchCancel(),_e(),Ze.onTouchCancel?.(pe)},"data-nested-dialog-open":void 0}),children:a.jsx(Dkt.Provider,{value:Be,children:o})})});function Qoe(e,t){e?.toggleAttribute(E1.swiping,t)}function GVe(e){return!!e?.closest(kOn)}function Nar(e){return!!e?.closest(Ear)}function qkt(e,t){return t==="left"||t==="right"?e.offsetWidth:e.offsetHeight}function KVe(e,t){return Math.max(qkt(e,t)*.5,Gpe)}function Aar(e,t){return e instanceof t.HTMLInputElement&&e.type==="range"}function Par(e){return e.tagName==="INPUT"||e.tagName==="TEXTAREA"}function $ar(e,t){const n=_r(e.anchorNode)?e.anchorNode:e.anchorNode?.parentElement,r=_r(e.focusNode)?e.focusNode:e.focusNode?.parentElement;return e.containsNode(t,!0)||ln(t,n)||ln(t,r)}function YVe(e,t){const n=ic(e);if(n&&ln(t,n)&&Par(n)){const{selectionStart:s,selectionEnd:i}=n;if(s!=null&&i!=null&&s<i)return!0}const r=e.getSelection?.();return!r||r.isCollapsed?!1:$ar(r,t)}function Rar(e,t){return e.composedPath().some(n=>Aar(n,t))}function Mar(e){return Rar(e.nativeEvent,xi(e.currentTarget))}function Dar(e,t){e.lastX=t.clientX,e.lastY=t.clientY}function Lar(e,t,n,r){if(e.preserveNativeCrossAxisScroll)return!0;if(e.drawerAxisAttributed||e.allowSwipe===!0||!e.hasCrossAxisScrollableContent)return!1;if(!t.cancelable)return e.preserveNativeCrossAxisScroll=!0,!0;const s=r?n.clientY-e.startY:n.clientX-e.startX,i=r?n.clientX-e.startX:n.clientY-e.startY,o=Math.abs(s),l=Math.abs(i);return l>=HVe&&l>o+Iar?(e.preserveNativeCrossAxisScroll=!0,!0):o>=HVe?(e.drawerAxisAttributed=!0,!1):!0}function zar(e,t){return Qkt(e,t).max>0}function Qkt(e,t){if(t==="vertical"){const r=Math.max(0,e.scrollHeight-e.clientHeight);return{offset:e.scrollTop,max:r}}const n=Math.max(0,e.scrollWidth-e.clientWidth);return{offset:e.scrollLeft,max:n}}function Zkt(e,t,n){const r=Wkt(n,t),{offset:s,max:i}=Qkt(e,t);return r?s<=0:s>=i}function Far(e,t,n,r){return(Wkt(n,t)?r>0:r<0)?Zkt(e,t,n):!1}function Wkt(e,t){return t==="vertical"?e==="down":e==="right"}const Bar=md("drawer-backdrop fixed inset-0 z-50",{variants:{overlay:{visible:"bg-scrim backdrop-blur-xs",transparent:"bg-transparent",none:"hidden"}},defaultVariants:{overlay:"visible"}}),Var=md("fixed z-50 flex",{variants:{side:{top:"items-start justify-center",bottom:"items-end justify-center",left:"items-stretch justify-start",right:"items-stretch justify-end"},layout:{default:"inset-0",floating:"p-2 sm:p-3",floatingOverlay:"inset-0 p-2 sm:p-3"}},compoundVariants:[{side:"right",layout:"floating",className:"inset-y-0 right-0 w-[calc(32rem+1.5rem)] max-w-full sm:w-[calc(32rem+2rem)]"},{side:"left",layout:"floating",className:"inset-y-0 left-0 w-[calc(32rem+1.5rem)] max-w-full sm:w-[calc(32rem+2rem)]"},{side:"bottom",layout:"floating",className:"inset-x-0 bottom-0 h-[calc(85dvh+1.5rem)] max-h-full sm:h-[calc(85dvh+2rem)]"},{side:"top",layout:"floating",className:"inset-x-0 top-0 h-[calc(85dvh+1.5rem)] max-h-full sm:h-[calc(85dvh+2rem)]"}],defaultVariants:{side:"bottom",layout:"default"}}),Uar=md(Z("drawer-popup group/popup relative z-50 box-border flex [touch-action:auto] flex-col overflow-y-auto overscroll-contain will-change-transform outline-none","text-foreground",Tht,"data-[swiping]:select-none","after:pointer-events-none after:absolute after:inset-0 after:bg-transparent after:transition-[background-color] after:duration-[450ms] after:content-['']","data-[nested-drawer-open]:after:bg-black/25"),{variants:{side:{bottom:"",top:"",left:"",right:""},variant:{default:"",floating:"drawer-popup-floating pointer-events-auto rounded-lg"}},compoundVariants:[{side:"bottom",variant:"default",className:"-mb-12 h-[var(--drawer-height,auto)] max-h-[calc(85vh_+_3rem)] w-full rounded-t-xl pb-12"},{side:"top",variant:"default",className:"-mt-12 h-[var(--drawer-height,auto)] max-h-[calc(85vh_+_3rem)] w-full rounded-b-xl pt-12"},{side:"left",variant:"default",className:"h-full w-[20rem] max-w-[85vw] rounded-r-xl"},{side:"right",variant:"default",className:"h-full w-[20rem] max-w-[85vw] rounded-l-xl"},{side:["left","right"],variant:"floating",className:"h-[calc(100dvh-1.5rem)] w-[32rem] max-w-[calc(100vw-1.5rem)] sm:h-[calc(100dvh-2rem)] sm:max-w-[calc(100vw-2rem)]"},{side:["top","bottom"],variant:"floating",className:"max-h-[calc(85dvh-1.5rem)] w-[calc(100vw-1.5rem)] sm:max-h-[calc(85dvh-2rem)] sm:w-[calc(100vw-2rem)]"}],defaultVariants:{side:"bottom",variant:"default"}}),qar={top:"up",bottom:"down",left:"left",right:"right"},Qar=(e,t)=>e!=="auto"?e:t==="floating"?"none":"visible",Hkt=g.createContext({side:"bottom",variant:"default",resolvedOverlay:"visible"}),wK=()=>g.useContext(Hkt),Zar=(e,t)=>e!=="floating"?"default":t==="none"?"floating":"floatingOverlay";function z_({side:e="bottom",variant:t="default",overlay:n="auto",modal:r,disablePointerDismissal:s,children:i,...o}){const l=Qar(n,t),c=r??(l==="none"?!1:void 0),u=s??(l==="none"?!0:void 0),d=g.useMemo(()=>({side:e,variant:t,resolvedOverlay:l}),[e,t,l]);return a.jsx(Hkt.Provider,{value:d,children:a.jsx(Fkt,{swipeDirection:qar[e],modal:c,disablePointerDismissal:u,...o,children:i})})}z_.displayName="Drawer";function Gkt({asChild:e,children:t,...n}){const r=e&&g.isValidElement(t)?{render:t}:{};return a.jsx(kar,{...r,...n,children:e?void 0:t})}Gkt.displayName="DrawerTrigger";const SK=g.forwardRef(({asChild:e,children:t,...n},r)=>{const s=e&&g.isValidElement(t)?{render:t}:{};return a.jsx(iar,{ref:r,...s,...n,children:e?void 0:t})});SK.displayName="DrawerClose";const Oke=zkt,Kkt=OQ,kK=g.forwardRef(({className:e,overlay:t,...n},r)=>{const{resolvedOverlay:s}=wK(),i=t??s;return a.jsx(Ekt,{ref:r,"data-slot":"drawer-backdrop","data-overlay":i,className:Z(Bar({overlay:i}),e),...n})});kK.displayName="DrawerBackdrop";const OK=g.forwardRef(({className:e,side:t,variant:n,...r},s)=>{const i=wK(),o=t??i.side,l=n??i.variant,c=Zar(l,i.resolvedOverlay);return a.jsx(Ukt,{ref:s,"data-slot":"drawer-viewport","data-variant":l,className:Z(Var({side:o,layout:c}),e),...r})});OK.displayName="DrawerViewport";const jK=g.forwardRef(({className:e,side:t,variant:n,...r},s)=>{const i=wK(),o=t??i.side,l=n??i.variant;return a.jsx(Lkt,{ref:s,"data-slot":"drawer-popup","data-variant":l,className:Z(Uar({side:o,variant:l}),e),...r})});jK.displayName="DrawerPopup";const Ykt=Z("transition-opacity duration-300 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:duration-0","group-data-[nested-drawer-open]/popup:opacity-0"),Kpe=()=>a.jsx("div",{"aria-hidden":!0,"data-slot":"drawer-handle",className:Z("mx-auto my-2 h-1 w-12 shrink-0 rounded-full bg-muted",Ykt)});Kpe.displayName="DrawerHandleBar";const Xkt=({side:e,variant:t})=>t!=="floating"||e!=="left"&&e!=="right"?null:a.jsx("div",{"aria-hidden":!0,"data-slot":"drawer-side-handle",className:Z("absolute top-1/2 z-10 flex h-20 w-5 -translate-y-1/2 cursor-ew-resize touch-none items-center justify-center select-none lg:hidden",e==="right"?"-left-2":"-right-2"),children:a.jsx("div",{className:"h-10 w-1 rounded-full bg-border-strong"})});Xkt.displayName="DrawerFloatingSideHandle";const XL=g.forwardRef(({className:e,children:t,variant:n,showCloseButton:r=!0,...s},i)=>{const{side:o,variant:l,resolvedOverlay:c}=wK(),u=n??l,d=o==="top"||o==="bottom";return a.jsxs(Oke,{children:[c!=="none"&&a.jsx(kK,{}),a.jsx(OK,{variant:u,children:a.jsxs(jK,{ref:i,variant:u,className:e,...s,children:[d&&o==="bottom"&&a.jsx(Kpe,{}),a.jsx(Xkt,{side:o,variant:u}),a.jsxs("div",{"data-slot":"drawer-content",className:Z("relative flex min-h-0 flex-1 flex-col","[&>form]:flex [&>form]:min-h-0 [&>form]:flex-1 [&>form]:flex-col [&>form]:gap-0",Ykt),children:[r&&a.jsx(Jkt,{}),t]}),d&&o==="top"&&a.jsx(Kpe,{})]})})]})});XL.displayName="DrawerContent";const Jkt=()=>a.jsx(SK,{asChild:!0,children:a.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm",className:"absolute top-3 right-3 z-10","aria-label":"Close",children:a.jsx(Mn,{})})});Jkt.displayName="DrawerDefaultCloseButton";const jke=({className:e,...t})=>a.jsx("div",{"data-slot":"drawer-header",className:Z("flex flex-col gap-0.5 px-3 py-2.5 pr-12 text-left",e),...t});jke.displayName="DrawerHeader";const Cke=({className:e,...t})=>a.jsx("div",{"data-slot":"drawer-body",className:Z("flex-1 px-3 py-2.5",e),...t});Cke.displayName="DrawerBody";const RP=g.forwardRef(({className:e,...t},n)=>a.jsx(Vkt,{ref:n,className:Z("text-subheading text-foreground",e),...t}));RP.displayName="DrawerTitle";const JL=g.forwardRef(({className:e,...t},n)=>a.jsx(Akt,{ref:n,className:Z("text-caption text-muted-foreground",e),...t}));JL.displayName="DrawerDescription";const Ik=(e=1024)=>{const t=`(max-width: ${e-1}px)`,n=g.useCallback(r=>{const s=window.matchMedia(t);return s.addEventListener("change",r),()=>s.removeEventListener("change",r)},[t]);return g.useSyncExternalStore(n,()=>window.matchMedia(t).matches,()=>!1)},eOt=g.createContext({intent:"default",pending:!1});function CK(){return g.useContext(eOt)}const _K={sm:"min-h-control-sm",md:"min-h-control-md",lg:"min-h-control-lg"},TK="h-auto min-w-0 max-w-full whitespace-normal wrap-anywhere max-[22rem]:w-full",War=640,Har="[&>form]:flex [&>form]:min-h-0 [&>form]:flex-1 [&>form]:flex-col [&>form]:gap-0",Gar=["dialog-popup-motion fixed top-1/2 left-1/2 z-50 flex w-[calc(100%-2rem)] -translate-1/2 flex-col rounded-xl py-3 outline-hidden",Har,Tht].join(" "),Kar={sm:"max-h-[calc(100dvh-4rem)] max-w-sm",md:"max-h-[calc(100dvh-4rem)] max-w-lg",lg:"max-h-[calc(100dvh-4rem)] max-w-2xl",xl:"max-h-[calc(100dvh-4rem)] max-w-4xl",full:"h-[calc(100dvh-2rem)]"},tOt=()=>Ik(War);function Yr({intent:e="default",pending:t=!1,open:n,defaultOpen:r=!1,onOpenChange:s,disablePointerDismissal:i,...o}){const l=tOt(),[c,u]=g.useState(r),d={...o,open:n??c,disablePointerDismissal:i??e==="destructive"};function f(h,p){if(!h&&t){p.cancel();return}u(h),s?.(h,p)}return a.jsx(eOt.Provider,{value:{intent:e,pending:t},children:l?a.jsx(z_,{...d,onOpenChange:f}):a.jsx(rar,{...d,onOpenChange:f})})}const _ke=Ikt,Yar=Ckt,Xar=xK;function Jar({className:e,...t}){return a.jsx(Kor,{"data-slot":"dialog-overlay",className:Z("dialog-backdrop-motion fixed inset-0 z-50 bg-scrim backdrop-blur-xs",e),...t})}function Xr({className:e,children:t,size:n="md",showOverlay:r=!0,showCloseButton:s=!0,overlayClassName:i,initialFocus:o,...l}){const{intent:c,pending:u}=CK(),d=tOt(),f=g.useRef(null),h=c==="destructive",p={"data-slot":"dialog-content","data-size":n,"data-intent":c,role:h?"alertdialog":"dialog",initialFocus:o??(h&&s?f:!0),"aria-busy":u||void 0,...l},m=s&&a.jsx(xK,{ref:f,disabled:u,"data-slot":"dialog-close",className:Z("absolute right-4",d?"top-1.5":"top-4"),render:a.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":"Close",children:a.jsx(Mn,{})})});return d?a.jsxs(XL,{...p,showCloseButton:!1,className:Z("pb-3",n==="full"&&"h-[calc(85vh+3rem)]",s&&"[&_[data-slot=dialog-header]]:pr-12",e),children:[t,m,a.jsx("div",{"aria-hidden":!0,className:"h-12 shrink-0"})]}):a.jsxs(Yar,{children:[r&&a.jsx(Jar,{className:i}),a.jsxs(Yor,{...p,className:Z(Gar,Kar[n],s&&"[&_[data-slot=dialog-header]]:pr-12",e),children:[t,m]})]})}function Jr({className:e,...t}){return a.jsx("div",{"data-slot":"dialog-header",className:Z("flex min-w-0 shrink-0 flex-col gap-1 px-5 py-2",e),...t})}function Yo({className:e,...t}){return a.jsx("div",{"data-slot":"dialog-footer",className:Z("flex shrink-0 flex-wrap items-center justify-end gap-2 px-5 py-2",e),...t})}function Qr({className:e,layout:t="scroll",flush:n=!1,children:r,...s}){const i=Z("flex min-w-0 flex-col gap-4 text-body wrap-break-word text-muted-foreground",!n&&"px-5 py-2",e);return t==="fill"?a.jsx("div",{"data-slot":"dialog-body",className:Z("min-h-0 flex-1",i),...s,children:r}):a.jsx(jr,{className:"flex min-h-0 min-w-0 flex-1 flex-col",mask:!0,children:a.jsx(Au,{className:"h-auto min-h-0",children:a.jsx("div",{"data-slot":"dialog-body",className:i,...s,children:r})})})}function Zr({className:e,...t}){return a.jsx(Tkt,{className:Z("text-heading wrap-break-word text-foreground",e),...t})}function Lo({className:e,...t}){return a.jsx(kkt,{className:Z("text-body wrap-break-word text-muted-foreground",e),...t})}function _a({disabled:e,size:t="md",...n}){const{pending:r}=CK();return a.jsx(xK,{render:a.jsx(ce,{size:t,variant:"ghost",className:Z(TK,_K[t]),children:n.children}),...n,disabled:e||r})}function Bt(e){return a.jsx(Yr,{...e,modal:!0,disablePointerDismissal:!0})}function elr({size:e="sm",...t}){return a.jsx(Xr,{"data-slot":"alert-dialog-content",size:e,showCloseButton:!1,...t,role:"alertdialog"})}function tlr({children:e,...t}){return a.jsx(Xar,{render:a.jsx(ce,{variant:"primary",size:"md",className:Z(TK,_K.md),children:e}),...t})}Bt.Trigger=_ke;Bt.Content=elr;Bt.Header=Jr;Bt.Footer=Yo;Bt.Body=Qr;Bt.Title=Zr;Bt.Description=Lo;Bt.Action=tlr;Bt.Cancel=_a;const nOt=({children:e,"aria-label":t="Threads",embedded:n=!1})=>a.jsx("div",{className:Z("size-full",!n&&"pb-2 pl-2"),children:a.jsx("nav",{"aria-label":t,className:Z("flex h-full flex-col gap-1 overflow-y-auto p-1",!n&&Z(pr,"rounded-studio-panel")),children:e})}),nlr=({render:e,children:t})=>a.jsx(ce,{render:e,variant:"ghost",className:"w-full justify-start rounded-xl px-3",children:t}),rlr=()=>a.jsx("div",{role:"separator","aria-orientation":"horizontal",className:"-mx-1 h-px shrink-0 bg-border/40"}),Ype=({children:e})=>a.jsx("ol",{className:"flex flex-col gap-1","data-testid":"thread-list",children:e}),Xpe=({as:e,href:t,to:n,isActive:r,onClick:s,onDelete:i,deleteLabel:o="delete",actions:l,className:c,children:u})=>a.jsxs("li",{className:"group relative",children:[a.jsx(ce,{render:e?g.createElement(e,{href:t,to:n}):void 0,onClick:s,variant:"ghost",className:Z("w-full min-w-0 justify-start rounded-xl px-3 text-left",(i||l)&&"pr-9",r&&"bg-fill-hover text-foreground",c),children:a.jsx("span",{className:"min-w-0 flex-1",children:u})}),i&&a.jsx(ce,{variant:"ghost",size:"icon-sm",className:"absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100",onClick:i,"aria-label":o,children:a.jsx(Mn,{})}),l&&a.jsx("div",{className:"absolute top-1/2 right-px flex -translate-y-1/2 items-center opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 has-data-popup-open:opacity-100",children:l})]}),rOt=({children:e})=>a.jsx(Y,{as:"p",variant:"caption",tone:"muted",className:"px-3 py-2",children:e}),slr=yr({status:rg(["running","failed","canceled","pending","waiting","paused","suspended","success"]),timestamp:sc().optional()}),ilr=yr({output:z4()});function olr(e){const t=slr.safeParse(e);return t.success?t.data:void 0}function alr(e){if(e==null)return null;const t=_n().safeParse(e);if(t.success)return t.data;const n=ilr.safeParse(e),r=n.success?n.data.output:e;try{return JSON.stringify(r)}catch{return null}}function llr({timestamp:e,resourceId:t}){return e===void 0&&!t?null:a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",className:"flex w-full min-w-0 items-center gap-1.5",children:[e!==void 0&&a.jsx("time",{className:"shrink-0",dateTime:new Date(e).toISOString(),children:rs(e,"date-time")}),t&&a.jsx("span",{className:"min-w-0 truncate",title:`Resource ${t}`,children:e===void 0?t:`· ${t}`})]})}const clr=({workflowId:e,runId:t,canDelete:n})=>{const[r,s]=g.useState(!0),[i,o]=g.useState(null),{Link:l,paths:c,navigate:u}=Sn(),{isLoading:d,error:f,data:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v}=TDn({workflowId:e,summary:!0}),{data:y}=Omt({workflowId:e,runId:t??"",queryOptions:{enabled:!!(e&&t)}}),x=alr(y?.payload),{mutateAsync:b}=IDn({workflowId:e}),S=async j=>{try{await b({runId:j}),Xe.success("Workflow run deleted successfully"),o(null),u(c.workflowLink(e))}catch{Xe.error("Failed to delete workflow run"),o(null)}},k=h||[];return a.jsxs(a.Fragment,{children:[a.jsxs(gc,{open:r,onOpenChange:s,className:"flex min-h-0 flex-col",children:[a.jsxs(Gl,{className:"flex shrink-0 items-center gap-2 px-4 py-3 text-left text-caption text-muted-foreground",children:[a.jsx(Ha,{direction:"right",className:"size-4 text-muted-foreground"}),a.jsx("span",{children:"Recent runs"}),!d&&!f&&a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",children:[k.length,v?"+":""]})]}),a.jsx(Kl,{keepMounted:!0,fill:!0,className:"flex min-h-0 flex-col",children:a.jsx(jr,{className:"min-h-0 w-full flex-1",mask:{top:!1},children:d?a.jsx("div",{className:"p-4",children:a.jsx(bt,{className:"h-32"})}):a.jsx(nOt,{"aria-label":"Workflow runs",embedded:!0,children:k.length===0?a.jsx(rOt,{children:f?"Unable to load workflow runs.":"Your run history will appear here once you run the workflow"}):a.jsxs(Ype,{children:[k.map(j=>{const C=j.runId===t,T=olr(j.snapshot),_=C?x:null;return a.jsx(Xpe,{as:l,to:c.workflowRunLink(e,j.runId),isActive:C,onDelete:n?()=>o(j.runId):void 0,deleteLabel:"delete run",className:"h-auto min-h-0 items-stretch py-1",children:a.jsxs("span",{className:"flex w-full min-w-0 items-center gap-2.5 px-1 text-left",children:[T&&a.jsx("span",{className:"shrink-0",children:a.jsx(Z1t,{status:T.status})}),a.jsxs("span",{className:"flex min-w-0 flex-1 flex-col items-start gap-0.5",children:[a.jsx("span",{className:"flex w-full min-w-0 items-center gap-2",children:a.jsx(Y,{as:"span",variant:"column",tone:"ink",className:"min-w-0 flex-1 truncate",title:j.runId,children:j.runId})}),a.jsx(llr,{timestamp:Kfe(T?.timestamp),resourceId:Tmt(j)}),_&&a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"block w-full min-w-0 truncate",children:_})]})]})},`run-${j.runId}`)}),m&&a.jsx("li",{className:"flex items-center justify-center py-2",children:a.jsx(At,{children:a.jsx(On,{})})}),a.jsx("li",{children:a.jsx("div",{ref:p})})]})})})})]}),a.jsx(ulr,{open:!!i,onOpenChange:()=>o(null),onDelete:()=>{i&&S(i)}})]})},ulr=({open:e,onOpenChange:t,onDelete:n})=>a.jsx(Bt,{open:e,onOpenChange:t,children:a.jsxs(Bt.Content,{children:[a.jsxs(Bt.Header,{children:[a.jsx(Bt.Title,{children:"Are you absolutely sure?"}),a.jsx(Bt.Description,{children:"This action cannot be undone. This will permanently delete the workflow run and remove it from our servers."})]}),a.jsxs(Bt.Footer,{children:[a.jsx(Bt.Cancel,{children:"Cancel"}),a.jsx(Bt.Action,{onClick:n,children:"Continue"})]})]})}),sOt=g.createContext(0);function E9(e,t=!1){return{maxZoom:1,padding:t?"20px":{left:`${e+40}px`,right:"40px",top:"40px",bottom:"64px"}}}const dlr=md("pointer-events-none block transition-all duration-150 ease-out motion-reduce:transition-none",{variants:{variant:{line:"h-3/4 w-px bg-linear-to-b from-transparent via-foreground/30 to-transparent opacity-0",pill:"h-10 w-0.5 rounded-full bg-foreground/30"}},defaultVariants:{variant:"line"}}),Tke=({variant:e,className:t})=>a.jsx("span",{"aria-hidden":!0,className:Z(dlr({variant:e}),t)}),Ike=380,flr="workflow-canvas-left-panel-width",hlr=8,XVe=16,Eke=`${pr} rounded-studio-panel`,iOt=g.createContext(void 0);function Zoe(e,t){return Math.max(Ike,Math.min(e,t))}function plr(){const e=g.useContext(iOt);if(!e)return null;const t=s=>{s.button===0&&(s.preventDefault(),s.currentTarget.setPointerCapture(s.pointerId))},n=s=>{s.currentTarget.hasPointerCapture(s.pointerId)&&e.resizeTo(s.clientX)},r=s=>{s.key!=="ArrowLeft"&&s.key!=="ArrowRight"||(s.preventDefault(),e.resizeBy(s.key==="ArrowRight"?XVe:-XVe))};return a.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panel","aria-valuenow":e.width,"aria-valuemin":Ike,tabIndex:0,className:"group/resize pointer-events-auto absolute inset-y-0 left-full flex w-2 cursor-col-resize touch-none items-center justify-center outline-hidden",onPointerDown:t,onPointerMove:n,onKeyDown:r,children:a.jsx(Tke,{className:"group-hover/resize:opacity-100 group-focus-visible/resize:via-border-focus group-focus-visible/resize:opacity-100 group-active/resize:via-foreground/45 group-active/resize:opacity-100"})})}const mlr=({children:e,leftSlot:t})=>{const n=Ik(),r=g.useRef(null),[s,i]=Tk({initialKey:flr,defaultValue:Ike,schema:ds()}),[o,l]=g.useState(Number.POSITIVE_INFINITY);if(g.useLayoutEffect(()=>{const p=r.current;if(!p)return;const m=()=>l(Math.floor(p.getBoundingClientRect().width/2));m();const v=new ResizeObserver(m);return v.observe(p),()=>v.disconnect()},[n]),n)return a.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden",children:[a.jsx("div",{className:"relative min-h-45 min-w-0 flex-1 overflow-hidden",children:e}),t&&a.jsx("div",{className:"min-h-0 min-w-0 basis-[44%] overflow-hidden bg-background",children:t})]});const c=Zoe(s,o),u=p=>{const m=r.current;m&&i(Zoe(p-m.getBoundingClientRect().left,o))},d=p=>i(Zoe(c+p,o)),f=t?c-hlr:0,h={"--workflow-left-panel-width":`${f}px`};return a.jsxs("div",{className:"relative min-h-0 min-w-0 flex-1 overflow-hidden",style:h,children:[a.jsx(sOt,{value:f,children:a.jsx("div",{ref:r,className:"absolute inset-0 min-h-0 min-w-0 overflow-hidden",children:e})}),t&&a.jsx(iOt,{value:{width:c,resizeTo:u,resizeBy:d},children:a.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-0 z-10 min-w-0",style:{width:c},children:t})})]})},oOt=Z(Eke,"pointer-events-auto");function aOt({className:e,children:t}){return a.jsxs("div",{className:Z("relative flex min-h-0 min-w-0 flex-col",e),children:[t,a.jsx(plr,{})]})}function glr({workflowId:e,onClick:t}){const{Link:n,paths:r}=Sn();return a.jsx(ce,{render:a.jsx(n,{href:`${r.workflowLink(e)}/graph`}),variant:"ghost",size:"icon-md",tooltip:"New workflow run",onClick:t,children:a.jsx(Dr,{})})}function vlr({children:e,workflowId:t,showNewRunButton:n,onNewRun:r}){const{result:s}=g.useContext(Wl),[i,o]=g.useState(!0);return a.jsx(aOt,{className:"max-h-[75%] flex-initial",children:a.jsxs(gc,{render:a.jsx("section",{}),open:i,onOpenChange:o,"data-testid":"workflow-information-top-section",className:Z(oOt,"flex min-h-0 min-w-0 flex-col overflow-hidden"),children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-1 pr-2",children:[a.jsxs(Gl,{className:"flex min-w-0 flex-1 items-center gap-2 px-4 py-3 text-column text-muted-foreground",children:[a.jsx(Ha,{direction:"right",className:"size-4 text-muted-foreground"}),a.jsx("span",{children:"Workflow run"}),!i&&s?.status&&a.jsx(G1t,{status:s.status})]}),n&&a.jsx(glr,{workflowId:t,onClick:()=>{o(!0),r()}})]}),a.jsx(Kl,{keepMounted:!0,fill:!0,className:"flex min-h-0 flex-col",children:a.jsx(jr,{"data-testid":"workflow-information-top-scroll-area",className:"min-h-0 flex-1 border-t border-border",mask:{top:!1,bottom:!1},children:a.jsx(Au,{className:"h-full",children:e})})})]})})}function ylr(e){return a.jsx(wkt,{...e})}function xlr({runId:e,observeWorkflowStream:t,...n}){return a.jsx(Gor,{...n,runId:e,observeWorkflowStream:t})}function blr({workflowId:e,activeRunId:t,canDelete:n}){return a.jsx(aOt,{className:"mt-auto max-h-[min(35%,280px)] shrink-0",children:a.jsx("section",{className:Z(oOt,"flex min-h-0 min-w-0 flex-col overflow-hidden"),children:a.jsx(clr,{workflowId:e,runId:t,canDelete:n})})})}function wlr({workflowId:e,initialRunId:t,requestContext:n,runActionsSlot:r,canExecute:s,canDelete:i}){const{data:o,isLoading:l,error:c}=wL({workflowId:e,requestContext:n,queryOptions:{enabled:!!e}}),{createWorkflowRun:u,streamWorkflow:d,isStreamingWorkflow:f,observeWorkflowStream:h,resumeWorkflow:p,cancelWorkflowRun:m,isCancellingWorkflowRun:v,clearData:y,runId:x}=g.useContext(Wl),{setSelectedStepId:b}=bG(),S=t||x,k={workflowId:e,workflow:o??void 0,isLoading:l,createWorkflowRun:u,streamWorkflow:d,resumeWorkflow:p,isStreamingWorkflow:f,isCancellingWorkflowRun:v,cancelWorkflowRun:m,requestContext:n,runActionsSlot:r,canExecute:s};if(g.useEffect(()=>{if(c){const C=c instanceof Error?c.message:"Failed to load workflow";Xe.error(`Error loading workflow: ${C}`)}},[c]),c)return null;if(!e)return a.jsx("div",{"data-testid":"workflow-information-panel",className:"workflow-information-panel pointer-events-none flex size-full min-h-0 flex-col gap-2 p-2"});const j=()=>{y(),b(null)};return a.jsxs("div",{"data-testid":"workflow-information-panel",className:"workflow-information-panel pointer-events-none flex size-full min-h-0 flex-col gap-2 p-2",children:[a.jsx(vlr,{workflowId:e,showNewRunButton:!!S,onNewRun:j,children:t?a.jsx(xlr,{...k,runId:t,observeWorkflowStream:h}):a.jsx(ylr,{...k})}),a.jsx(blr,{workflowId:e,activeRunId:S,canDelete:i})]})}function Nke(e,t){return Smt(`mastra-tracing-options:${e}:${t}`)}const JVe={runId:"",payload:null,override:null};function Slr(e){const[t,n]=g.useState(JVe),r=e??t.runId,s=t.override?.runId===r?t.override.result:null,i=g.useCallback(d=>n(f=>({...f,runId:d})),[]),o=g.useCallback(d=>n(f=>({...f,payload:d})),[]),l=g.useCallback(d=>n(f=>({...f,override:d&&{runId:e??f.runId,result:d}})),[e]),c=g.useCallback(d=>n(f=>f.override?.runId===d?{...f,override:null}:f),[]),u=g.useCallback(()=>n(JVe),[]);return{runId:r,payload:t.payload,override:s,setRunId:i,setPayload:o,setResult:l,dropOverride:c,reset:u}}const klr=5e3,Olr=e=>wG(e.state.data?.status)?!1:klr;function jlr(e){return{...e,timestamp:Kfe(e.updatedAt)??Kfe(e.createdAt)}}function Clr(e,t,{poll:n}){const{data:r,isLoading:s}=Omt({workflowId:e,runId:t,queryOptions:{enabled:!!(e&&t),refetchInterval:n?Olr:void 0}});return{persistedRun:g.useMemo(()=>r&&jlr(r),[r]),isLoading:s}}function _lr({runId:e,debugMode:t,tracingOptions:n}){const[r,s]=g.useState(),{streamWorkflow:i,streamResult:o,isStreaming:l,observeWorkflowStream:c,closeStreamsAndReset:u,resumeWorkflowStream:d,timeTravelWorkflowStream:f}=M0n({debugMode:t,tracingOptions:n,onError:b=>Xe.error(b.message)}),h=r?.runId===e,p=h&&o?o:null,m=h&&l,v=h&&r?.mode==="observe",y=g.useCallback((b,S="execute")=>s({runId:b,mode:S}),[]),x=g.useCallback(()=>{u(),s(void 0)},[u]);return{result:p,isOpen:m,isObserving:v,select:y,close:x,streamWorkflow:i.mutateAsync,resumeWorkflowStream:d.mutateAsync,observeWorkflowStream:c.mutate,timeTravelWorkflowStream:f.mutateAsync}}const Ake=g.createContext(null);function Ek(){const e=g.useContext(Ake);if(!e)throw new Error("useWorkflowStepDetail must be used within WorkflowStepDetailProvider");return e}const Tlr={};function Ilr({children:e,snapshot:t,workflowId:n,initialRunId:r,withoutTimeTravel:s=!1,requestContext:i=Tlr,tracingOptions:o}){const l=g.useContext(Ake)?.resetStepDetail,[c,u]=g.useState(!1),{data:d,isLoading:f,error:h}=wL({workflowId:n,requestContext:i,queryOptions:{enabled:!!n}}),p=mr(),m=D0n(),v=L0n(),{runId:y,payload:x,override:b,setRunId:S,setPayload:k,setResult:j,dropOverride:C,reset:T}=Slr(r),{result:_,isOpen:N,isObserving:E,select:A,close:P,streamWorkflow:L,resumeWorkflowStream:F,observeWorkflowStream:Q,timeTravelWorkflowStream:q}=_lr({runId:y,debugMode:c,tracingOptions:o}),B=b??_,V=!r&&wG(B?.status),W=r||(V?y:""),{persistedRun:M,isLoading:K}=Clr(n,W,{poll:!N}),D=M??t,$=g.useMemo(()=>D?UDn(D):null,[D]),z=g.useMemo(()=>WDn(B,$),[B,$]),U=r?D:void 0,G=E&&_mt(z?.status),ne=N&&!G,X=g.useMemo(()=>U?GDn(U,$?.input):x,[U,$,x]),ee=g.useCallback(me=>{l?.(),S(me)},[l,S]),re=g.useCallback(()=>{l?.(),P(),T()},[l,P,T]);g.useEffect(()=>re,[n,r,re]);const ue=g.useCallback((me,ke)=>{A(me,ke),C(me)},[A,C]),te=g.useCallback((me,ke)=>p.invalidateQueries({queryKey:kmt(me,ke),exact:!0}),[p]),ie=g.useCallback(async me=>{ue(me.runId),await L(me)},[ue,L]),se=g.useCallback(async me=>{ue(me.runId);try{await F(me)}finally{await te(me.workflowId,me.runId)}},[te,ue,F]),ae=g.useCallback(me=>{if(me.storedStatus==="suspended"){P();return}ue(me.runId,"observe"),Q({workflowId:me.workflowId,runId:me.runId,storeRunResult:null})},[P,ue,Q]),he=g.useCallback(async me=>{ue(me.runId);try{await q(me)}finally{await te(me.workflowId,me.runId)}},[te,ue,q]),ge=g.useMemo(()=>({workflowId:n,workflow:d??void 0,workflowError:h??null,isLoading:f,runId:y,setRunId:ee,result:z,setResult:j,streamResult:_,payload:X,setPayload:k,clearData:re,snapshot:t,runSnapshot:U,isLoadingRunExecutionResult:K,isStreamingWorkflow:ne,isCancellingWorkflowRun:v.isPending,createWorkflowRun:m.mutateAsync,streamWorkflow:ie,resumeWorkflow:se,observeWorkflowStream:ae,timeTravelWorkflowStream:he,cancelWorkflowRun:v.mutateAsync,closeStreamsAndReset:P,withoutTimeTravel:s,debugMode:c,setDebugMode:u}),[n,d,h,f,y,ee,z,j,_,X,k,re,t,U,K,ne,v.isPending,m.mutateAsync,ie,se,ae,he,v.mutateAsync,P,s,c]);return a.jsx(Wl.Provider,{value:ge,children:e})}function Pke(e){return a.jsx(Ilr,{...e,requestContext:xr("workflow",e.workflowId)[0],tracingOptions:Nke("workflow",e.workflowId)[0]})}function lOt({children:e}){const[t,n]=g.useState(null),[r,s]=g.useState(null),i=g.useMemo(()=>({selectedStepId:t,hoverStepId:r,setSelectedStepId:n,setHoverStepId:s}),[t,r]);return a.jsx(jmt.Provider,{value:i,children:e})}function cOt({children:e}){const[t,n]=g.useState(null),r=g.useRef(void 0),s=g.useCallback(({stepName:d,stepId:f,mapConfig:h})=>{r.current=void 0,n({type:"map-config",stepName:d,stepId:f,mapConfig:h})},[]),i=g.useCallback(({label:d,stepGraph:f,fullStep:h})=>{r.current=void 0,n({type:"nested-graph",stepName:d,nestedGraph:{label:d,stepGraph:f,fullStep:h}})},[]),o=g.useCallback(()=>{r.current=void 0,n(null)},[]),l=g.useCallback(()=>{const d=r.current;o(),d?.isConnected&&d.focus({preventScroll:!0})},[o]),c=g.useCallback((d,f)=>{r.current=f,n({type:"data",selection:d})},[]),u=g.useMemo(()=>({stepDetail:t,showMapConfig:s,showNestedGraph:i,showData:c,closeStepDetail:l,resetStepDetail:o}),[t,s,i,c,l,o]);return a.jsx(Ake.Provider,{value:u,children:e})}const Elr=e=>a.jsx("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{d:"M5.25684 12.6387L10.4003 3.36133H11.7432L6.5997 12.6387H5.25684Z",fill:"currentColor"})}),$ke=({children:e,label:t,className:n,listClassName:r})=>a.jsx("nav",{"aria-label":t,className:n,children:a.jsx("ol",{className:Z("flex items-center gap-0.5",r),children:e})}),Fx=e=>a.jsx(bt,{className:"h-3 w-24",...e}),_5=({className:e,as:t,isCurrent:n,action:r,switcher:s,icon:i,isLoading:o,children:l,...c})=>{const u=t||"span",d=!!(n&&s);return a.jsxs(a.Fragment,{children:[a.jsxs("li",{className:Z("group flex h-control-sm min-w-0 items-center",n?"shrink":"shrink-0",d&&"relative rounded-full has-[[data-slot=crumb-switcher]_[data-popup-open]]:bg-fill-subtle has-[[data-slot=crumb-switcher]_button:enabled]:hover:bg-fill-subtle has-[[data-slot=crumb-switcher]_button:enabled]:active:bg-fill"),children:[a.jsxs(u,{"aria-current":n?"page":void 0,className:Z("inline-flex min-w-0 items-center gap-2 overflow-hidden rounded-full px-[.9em]",iv.sm,In,n?"max-w-xs cursor-default text-foreground":Z(Zn,"max-w-48 cursor-pointer hover:bg-fill-subtle active:bg-fill"),e),...c,children:[i&&a.jsx(At,{className:Z("-ml-[.3em] shrink-0 opacity-50 group-hover:opacity-100","transition-opacity duration-normal ease-out-custom"),children:i}),o?a.jsx(Fx,{}):a.jsx("span",{className:"min-w-0 flex-1 truncate",children:l})]}),s&&a.jsx("span",{"data-slot":"crumb-switcher",className:Z("-ml-1 flex h-control-sm shrink-0 items-center",d&&"[&_button]:bg-transparent! [&_button:enabled]:after:absolute [&_button:enabled]:after:inset-0 [&_button:enabled]:after:rounded-full"),children:s}),r&&a.jsx("span",{className:"-ml-1 flex h-control-sm shrink-0 items-center",children:r})]}),!n&&a.jsx("li",{role:"separator",className:"flex h-full items-center",children:a.jsx(At,{className:"text-placeholder",children:a.jsx(Elr,{})})})]})},MP={variant:"ghost",size:"icon-sm",align:"end"};function Nlr(e,t,n,r,s,i,o,l,c,u=2){const d=aOn(n.current,{event:e,orientation:r,loopFocus:s,rtl:i,cols:u,disabledIndices:o,minIndex:l,maxIndex:c,prevIndex:t>c?l:t,stopEvent:!0});return Y1(n.current,d)?void 0:d}const uOt=g.createContext(void 0),dOt=g.createContext(void 0),fOt=g.createContext(void 0),hOt=g.createContext(!1),pOt=g.createContext("");function ag(){const e=g.useContext(uOt);if(!e)throw new Error(Nr(22));return e}function IK(){const e=g.useContext(dOt);if(!e)throw new Error(Nr(23));return e}function e6(){const e=g.useContext(fOt);if(!e)throw new Error(Nr(24));return e}function mOt(){return g.useContext(pOt)}function Alr(){return g.useContext(hOt)}const fn={id:e=>e.id,labelId:e=>e.labelId,items:e=>e.items,selectedValue:e=>e.selectedValue,hasSelectedValue:e=>{const{selectedValue:t,selectionMode:n}=e;return t==null?!1:n==="multiple"&&Array.isArray(t)?t.length>0:!0},hasNullItemLabel:(e,t)=>t?nSt(e.items):!1,open:e=>e.open,mounted:e=>e.mounted,forceMounted:e=>e.forceMounted,inline:e=>e.inline,activeIndex:e=>e.activeIndex,selectedIndex:e=>e.selectedIndex,isActive:(e,t)=>e.activeIndex===t,isSelected:(e,t)=>{const n=e.isItemEqualToValue,r=e.selectedValue;return Array.isArray(r)?r.some(s=>Um(t,s,n)):Um(t,r,n)},transitionStatus:e=>e.transitionStatus,popupProps:e=>e.popupProps,listProps:e=>e.listProps,inputProps:e=>e.inputProps,triggerProps:e=>e.triggerProps,itemProps:e=>e.itemProps,positionerElement:e=>e.positionerElement,listElement:e=>e.listElement,popupId:e=>e.popupId,triggerElement:e=>e.triggerElement,inputElement:e=>e.inputElement,inputGroupElement:e=>e.inputGroupElement,popupSide:e=>e.popupSide,openMethod:e=>e.openMethod,inputInsidePopup:e=>e.inputInsidePopup,inputOwnsFormValue:e=>e.inputOwnsFormValue,selectionMode:e=>e.selectionMode,name:e=>e.name,form:e=>e.form,disabled:e=>e.disabled,readOnly:e=>e.readOnly,required:e=>e.required,grid:e=>e.grid,virtualized:e=>e.virtualized,itemToStringLabel:e=>e.itemToStringLabel,isItemEqualToValue:e=>e.isItemEqualToValue,modal:e=>e.modal,autoHighlight:e=>e.autoHighlight};function gOt(e){return e==null?void 0:`${e}-popup`}function vOt(e,t){return(n,r)=>n==null?!1:e.contains(n,r,t)}function Plr(e,t,n){return(r,s)=>{if(r==null)return!1;if(!s)return!0;const i=n!=null?Lh(n,t):"";return i&&e.contains(i,s)&&i.length===s.length?!0:e.contains(r,s,t)}}function Rke(e){return Array.isArray(e)?e.map(t=>Rke(t)).join(","):e==null?"":String(e)}const eUe=new Map;function yOt(e={}){const t={usage:"search",sensitivity:"base",ignorePunctuation:!0,...e},n=`${Rke(e.locale)}|${JSON.stringify(t)}`,r=eUe.get(n);if(r)return r;const s=new Intl.Collator(e.locale,t),i={contains(o,l,c){if(!l)return!0;const u=Lh(o,c);for(let d=0;d<=u.length-l.length;d+=1)if(s.compare(u.slice(d,d+l.length),l)===0)return!0;return!1},startsWith(o,l,c){if(!l)return!0;const u=Lh(o,c);return s.compare(u.slice(0,l.length),l)===0},endsWith(o,l,c){if(!l)return!0;const u=Lh(o,c),d=l.length;return u.length>=d&&s.compare(u.slice(u.length-d),l)===0}};return eUe.set(n,i),i}const $lr=yOt;function Rlr(e={}){const{multiple:t=!1,value:n,...r}=e,s=yOt(r),i=g.useCallback((o,l,c)=>t?vOt(s,c)(o,l):Plr(s,c,n)(o,l),[s,n,t]);return g.useMemo(()=>({...s,contains:i}),[i,s])}const xOt=Symbol("none"),Woe={value:xOt,index:-1};function Mlr(e){const{id:t,onOpenChangeComplete:n,defaultSelectedValue:r=null,selectedValue:s,onSelectedValueChange:i,defaultInputValue:o,inputValue:l,open:c,defaultOpen:u=!1,selectionMode:d,onItemHighlighted:f,name:h,form:p,disabled:m=!1,readOnly:v=!1,required:y=!1,inputRef:x,grid:b=!1,items:S,filteredItems:k,filter:j,openOnInputClick:C=!0,autoHighlight:T=!1,keepHighlight:_=!1,highlightItemOnHover:N=!0,loopFocus:E=!0,itemToStringLabel:A,itemToStringValue:P,isItemEqualToValue:L=eSt,virtualized:F=!1,inline:Q=!1,fillInputOnItemPress:q=!0,modal:B=!1,limit:V=-1,autoComplete:W="list",formAutoComplete:M,locale:K,submitOnItemClick:D=!1}=e,{clearErrors:$}=Rv(),{setDirty:z,validityData:U,setFilled:G,name:ne,disabled:X,setTouched:ee,setFocused:re,validationMode:ue,validation:te}=Ru(),ie=Nx(),se=kk({id:t}),ae=$lr({locale:K}),[he,ge]=g.useState(!1),[me,ke]=g.useState(null),Ee=g.useRef([]),qe=g.useRef([]),Ze=g.useRef(null),Fe=g.useRef(null),Ae=g.useRef(null),Be=g.useRef(null),je=g.useRef(null),_e=g.useRef(!0),Ue=g.useRef(!1),pe=g.useRef(null),fe=g.useRef(null),Ie=g.useRef(null),Ce=g.useRef(Woe),le=g.useRef(null),ve=g.useRef([]),be=g.useRef(null),$e=X||m,De=ne??h,We=d==="multiple",tt=d==="single",st=l!==void 0||o!==void 0,Ge=S!==void 0,Le=k!==void 0;let ze;T==="always"?ze="always":ze=T?"input-change":!1;const[Se,Pe]=Jd({controlled:s,default:We?r??Lf:r,name:"Combobox",state:"selectedValue"}),nt=g.useMemo(()=>j===null?()=>!0:j!==void 0?j:vOt(ae,A),[j,ae,A]),Pt=ul(()=>st?o??"":tt?Lh(Se,A):"").current,[Vt,Ut]=Jd({controlled:l,default:Pt,name:"Combobox",state:"inputValue"}),[xt,jn]=Jd({controlled:c,default:u,name:"Combobox",state:"open"}),gn=LSe(S),we=me??String(Vt).trim(),Ne=tt?Lh(Se,A):"",He=tt&&!he&&we!==""&&Ne.length===we.length&&ae.contains(Ne,we),at=He?"":we,ft=Ge&&Le&&He,Zt=g.useMemo(()=>S?gn?S.flatMap(mn=>mn.items):S:Lf,[S,gn]),Ft=g.useMemo(()=>{if(k&&!ft)return k;if(!S)return Lf;if(gn){const En=S,Ns=[];let Ei=0;for(const ta of En){if(V>-1&&Ei>=V)break;const $a=V>-1?V-Ei:1/0,Oo=at===""?ta.items.slice(0,$a):[];if(at!=="")for(const Yl of ta.items){if(Oo.length>=$a)break;nt(Yl,at,A)&&Oo.push(Yl)}if(Oo.length>0){const Yl={...ta,items:Oo};Ns.push(Yl),Ei+=Oo.length}}return Ns}if(at==="")return V>-1?Zt.slice(0,V):Zt;const mn=[];for(const En of Zt){if(V>-1&&mn.length>=V)break;nt(En,at,A)&&mn.push(En)}return mn},[k,ft,S,gn,at,V,nt,A,Zt]),Tt=g.useMemo(()=>gn?Ft.flatMap(En=>En.items):Ft,[Ft,gn]),gt=ul(()=>{let mn=null;return Q&&xt&&Ge&&d!=="none"&&(mn=joe(Tt,Se,L,We)),new uht({id:se,labelId:void 0,selectedValue:Se,open:xt,items:S,selectionMode:d,listRef:Ee,labelsRef:qe,popupRef:Ze,emptyRef:je,inputRef:Fe,startDismissRef:Ae,endDismissRef:Be,keyboardActiveRef:_e,chipsContainerRef:pe,clearRef:fe,valuesRef:ve,pointerDownItemRef:be,selectionEventRef:Ie,name:De,form:p,disabled:$e,readOnly:v,required:y,grid:b,virtualized:F,openOnInputClick:C,itemToStringLabel:A,isItemEqualToValue:L,modal:B,autoHighlight:ze,submitOnItemClick:D,hasInputValue:st,mounted:!1,forceMounted:!1,transitionStatus:"idle",inline:Q,activeIndex:null,selectedIndex:mn,popupProps:{},listProps:{},inputProps:{},triggerProps:{},itemProps:ai,positionerElement:null,listElement:null,popupId:void 0,triggerElement:null,inputElement:null,inputGroupElement:null,popupSide:null,openMethod:null,inputInsidePopup:!0,inputOwnsFormValue:d==="none",onOpenChangeComplete:ti,setOpen:ti,setInputValue:ti,setSelectedValue:ti,setIndices:ti,handleSelection:ti,forceMount:ti,requestSubmit:ti})}).current,vn=d==="none"?Vt:Se,dn=g.useMemo(()=>d==="none"?vn:Array.isArray(Se)?Se.map(mn=>Wg(mn,P)):Wg(Se,P),[vn,P,d,Se]),Pn=ht(f),gr=ht(n),xs=St(gt,fn.activeIndex),Fr=St(gt,fn.selectedIndex),Ur=St(gt,fn.positionerElement),dr=St(gt,fn.listElement),Ti=St(gt,fn.triggerElement),Ii=St(gt,fn.inputElement),Pa=St(gt,fn.inputGroupElement),Hr=St(gt,fn.inline),Ka=St(gt,fn.inputInsidePopup),mg=St(gt,fn.inputOwnsFormValue),ga=aa(Ti),{mounted:wc,setMounted:fh,transitionStatus:Cd}=wp(xt),{openMethod:Pp,triggerProps:$p}=TSe(xt),hh=ht(()=>dn);A_(Ka?ga:Fe,se,vn,hh,!$e,h);const Gr=ht(()=>{S?qe.current=Tt.map(mn=>Lh(mn,A)):gt.set("forceMounted",!0)}),Es=ht((mn,En,Ns)=>{if(En===-1){if(Ce.current===Woe)return;Ce.current=Woe}else Ce.current={value:mn,index:En};Pn(mn,PH(Ns,void 0,{index:En}))}),Ks=ht(mn=>{gt.update(mn);const En=mn.activeIndex;if(En===void 0)return;const Ns=mn.type||Eo;En===null?Es(void 0,-1,Ns):Es(ve.current[En],En,Ns)}),Ya=ht((mn,En)=>{if(Ue.current=En.reason===Oy,e.onInputValueChange?.(mn,En),!En.isCanceled){if(En.reason===OE){xt&&me!==null&&ke(null);const Ns=En.event,Ei=Ns.inputType;if(Ns.type==="compositionend"||Ei!=null&&Ei!==""&&Ei!=="insertReplacementText"){const $a=mn.trim()!=="";$a&&ge(!0),le.current={hasQuery:$a};const Oo=gt.state.listElement;if(!gt.state.virtualized&&Oo){const Yl=Ze.current;for(const vf of CN(Oo.firstElementChild??Oo)){if(!ni(vf)||(Yl?!ln(Yl,vf):vf.getAttribute("role")==="dialog"))break;if(Bkt(vf)){vf.scrollTop=0;break}}}$a&&ze&&gt.state.activeIndex==null&&(xt||Hr)&&gt.set("activeIndex",0)}}else En.reason===Oy&&mn===""&&gt.state.inputInsidePopup&&(le.current={hasQuery:!1,selection:!0});Ut(mn)}}),gf=ht((mn,En)=>{if(xt!==mn&&(En.reason===w_&&Ge&&Tt.length===0&&!je.current&&En.allowPropagation(),e.onOpenChange?.(mn,En),!En.isCanceled&&(mn&&Ka&&!Hr&&me!==null&&(ge(!1),ke(null),Vt!==""&&En.reason!==OE&&Ya("",Xt(Oy,En.event))),!mn&&he&&(tt?(Hr||ke(we),we===""&&ge(!1)):We&&(Hr||ke(we),Ka&&Ks({activeIndex:null}),(!Ka||Hr)&&Ya("",Xt(Oy,En.event)))),jn(mn),!mn&&Ka&&(En.reason===C0||En.reason===K3)&&(ee(!0),re(!1),ue==="onBlur")))){const Ns=d==="none"?Vt:Se;te.commit(Ns)}}),hi=ht((mn,En)=>{if(i?.(mn,En),En.isCanceled)return;Pe(mn),(d==="none"&&Ze.current&&q||tt&&!gt.state.inputInsidePopup)&&Ya(Lh(mn,A),Xt(En.reason,En.event))}),_d=ht((mn,En)=>{const Ns=qi(mn),Ei=Ie.current??mn;Ie.current=null;const ta=Xt(K1,Ei),$a=Ns?.closest("a")?.getAttribute("href");if($a){$a.startsWith("#")&&gf(!1,ta);return}if(We){const Oo=Array.isArray(Se)?Se:[],vf=Oer(Oo,En,L)?tSt(Oo,En,L):[...Oo,En];if(hi(vf,ta),ta.isCanceled||!(Fe.current?Fe.current.value.trim()!=="":!1))return;gt.state.inputInsidePopup?Ya("",Xt(Oy,ta.event)):gf(!1,ta)}else{if(hi(En,ta),ta.isCanceled)return;gf(!1,ta)}}),gg=ht(()=>{const mn=te.inputRef.current?.form??gt.state.inputElement?.form;mn&&typeof mn.requestSubmit=="function"&&mn.requestSubmit()}),Kx=ht(()=>{if(fh(!1),gr?.(!1),ge(!1),ke(null),Ks(d==="none"?{activeIndex:null,selectedIndex:null}:{activeIndex:null}),We&&Fe.current&&Fe.current.value!==""&&!Ue.current&&Ya("",Xt(Oy)),tt)if(gt.state.inputInsidePopup)Fe.current&&Fe.current.value!==""&&Ya("",Xt(Oy));else{const mn=Lh(Se,A);Fe.current&&Fe.current.value!==mn&&Ya(mn,Xt(mn===""?Oy:Eo))}}),Sc=g.useMemo(()=>Hr&&Ur?{current:Ur.closest('[role="dialog"]')}:Ze,[Hr,Ur]);Tl({enabled:!e.actionsRef,open:xt,ref:Sc,onComplete(){xt||Kx()}}),g.useImperativeHandle(e.actionsRef,()=>({unmount:Kx}),[Kx]),Ot(function(){if(xt||(be.current=null,d==="none"))return;const En=Ge?Zt:ve.current;Ks({selectedIndex:joe(En,Se,L,We)})},[xt,Se,d,We,Ge,Zt,L,Ks]),Ot(()=>{S&&(ve.current=Tt,Ee.current.length=Tt.length)},[S,Tt]),Ot(()=>{const mn=le.current;if(mn){const Yl=xt||Hr||gt.state.positionerElement?.hidden===!1;if(mn.hasQuery)ze&&Yl&&gt.set("activeIndex",0),le.current=null;else if(String(Vt).trim()===""&&(le.current=null,Yl)){const vf=mn.selection;ze==="always"&&!vf&&gt.state.selectionMode==="none"&&gt.set("activeIndex",0),queueMicrotask(()=>{if(!gt.state.open&&!gt.state.inline||Fe.current&&Fe.current.value.trim()!=="")return;const ph=gt.state.selectedValue,Yv=gt.state.selectionMode==="multiple",Qz=Yv&&Array.isArray(ph)?ph[ph.length-1]:ph,nu=gt.state.selectionMode!=="none"&&Qz!=null;if(nu||vf){const Jx=Ge||Le?Tt:ve.current;gt.set("activeIndex",nu?joe(Jx,ph,gt.state.isItemEqualToValue,Yv):null)}else ze==="always"&&gt.set("activeIndex",0)})}}if(!xt&&!Hr)return;const Ns=Ge||Le?Tt:ve.current,Ei=gt.state.activeIndex;if(Ei==null){if(ze==="always"&&Ns.length>0){gt.set("activeIndex",0);return}Es(void 0,-1,Eo);return}if(Ei>=Ns.length){Es(void 0,-1,Eo),gt.set("activeIndex",null);return}const ta=Ns[Ei],$a=Ce.current.value,Oo=$a!==xOt&&Um(ta,$a,gt.state.isItemEqualToValue);(Ce.current.index!==Ei||!Oo)&&Es(ta,Ei,Eo)},[xs,ze,Es,Le,Ge,Tt,Hr,xt,gt,Vt]),Ot(()=>{if(d==="none"){G(String(Vt)!=="");return}G(We?Array.isArray(Se)&&Se.length>0:Se!=null)},[G,d,Vt,Se,We]),g.useEffect(()=>{Ge&&ze&&Tt.length===0&&Ks({activeIndex:null})},[Ge,ze,Tt.length,Ks]);function Yk(mn){const En=U.initialValue;return Array.isArray(mn)&&Array.isArray(En)?!uK(mn,En,(Ns,Ei)=>Um(Ns,Ei,L)):mn!==En}Jg(we,()=>{!xt||we===""||we===String(Pt)||ge(!0)});function Xk(){const mn=Lh(Se,A);Vt!==mn&&Ya(mn,Xt(Eo))}Jg(Se,()=>{d!=="none"&&($(De),z(Yk(Se)),te.change(Se),tt&&!st&&!Ka&&Xk())}),Jg(Vt,()=>{d==="none"&&($(De),z(Vt!==U.initialValue),te.change(Vt))}),Jg(S,()=>{!tt||st||Ka||he||Xk()});const vg=vht({open:Hr?!0:xt,onOpenChange:gf,elements:{reference:Ka?Ti:Ii,floating:Ur}}),Yx=b?"grid":"listbox",Jk=xt||Hr,_$=Jk?"true":"false",yg=g.useMemo(()=>{const mn=Ii?.tagName==="INPUT",En=Ii==null||mn,Ns=En||Jk,Ei=En?{autoComplete:"off",spellCheck:"false",autoCorrect:"off",autoCapitalize:"none"}:{};return Ns&&(Ei.role="combobox",Ei["aria-expanded"]=_$,Ei["aria-haspopup"]=Yx,Ei["aria-controls"]=Jk?dr?.id:void 0,Ei["aria-autocomplete"]=W),{reference:Ei,floating:{role:"presentation"}}},[Ii,Jk,_$,Yx,dr?.id,W]),Uz=S_(vg,{enabled:!v&&!$e&&C,event:"mousedown-only",toggle:!1,touchOpenDelay:Ka?0:100,reason:qkn}),eO=k_(vg,{enabled:!v&&!$e&&!Hr,outsidePressEvent:{mouse:"sloppy",touch:"intentional"},bubbles:Hr?!0:void 0,outsidePress(mn){const En=qi(mn);return!ln(Ti,En)&&!ln(fe.current,En)&&!ln(pe.current,En)&&!ln(Pa,En)}}),Xx=Y0e(vg,{enabled:!v&&!$e,id:se,listRef:Ee,activeIndex:xs,selectedIndex:Fr,virtual:!0,loopFocus:E,allowEscape:E&&!ze,focusItemOnOpen:he||d==="none"&&!ze?!1:"auto",focusItemOnHover:N,resetOnPointerLeave:!_,orientation:b?"horizontal":void 0,rtl:ie==="rtl",disabledIndices:Lf,grid:b?Nlr:void 0,onNavigate(mn,En){!En&&!xt||Cd==="ending"||Ks(En?{activeIndex:mn,type:_e.current?A0e:_ft}:{activeIndex:mn})}}),tO=g.useMemo(()=>Ol(Xx.reference,{onKeyDown(mn){b&&gt.state.activeIndex==null&&(mn.key==="ArrowLeft"||mn.key==="ArrowRight")&&mn.preventBaseUIHandler()}},eO.reference,Uz.reference,yg.reference),[Xx.reference,eO.reference,Uz.reference,yg.reference,b,gt]),T$=g.useMemo(()=>Ol(xk,eO.floating),[eO.floating]),I$=g.useMemo(()=>Ol(Xx.floating,yg.floating),[Xx.floating,yg.floating]),Ow=g.useMemo(()=>{const mn=Xx.item;return mn?{...mn,onFocus:void 0}:ai},[Xx.item]);X1t(()=>{gt.update({inline:Q,popupProps:T$,listProps:I$,inputProps:tO,triggerProps:$p,itemProps:Ow,setOpen:gf,setInputValue:Ya,setSelectedValue:hi,setIndices:Ks,handleSelection:_d,forceMount:Gr,requestSubmit:gg,onOpenChangeComplete:gr})}),Ot(()=>{gt.update({id:se,selectedValue:Se,open:xt,mounted:wc,transitionStatus:Cd,items:S,inline:Q,popupProps:T$,listProps:I$,inputProps:tO,triggerProps:$p,openMethod:Pp,itemProps:Ow,selectionMode:d,name:De,form:p,disabled:$e,readOnly:v,required:y,grid:b,virtualized:F,openOnInputClick:C,itemToStringLabel:A,modal:B,autoHighlight:ze,isItemEqualToValue:L,submitOnItemClick:D,hasInputValue:st,inputOwnsFormValue:d==="none"&&(Q||!gt.state.inputInsidePopup)})},[gt,se,Se,xt,wc,Cd,S,T$,I$,tO,Ow,Pp,$p,d,De,$e,v,y,b,F,C,A,B,L,D,st,Q,ze,p]);const xg=nf(x,te.inputRef),E$=g.useMemo(()=>({query:we,hasItems:Ge,filteredItems:Ft,flatFilteredItems:Tt}),[we,Ge,Ft,Tt]),N$=g.useMemo(()=>Array.isArray(vn)?"":Wg(vn,P),[vn,P]),jw=We&&Array.isArray(Se)&&Se.length>0,Kv=We||d==="none"&&mg?void 0:De,qz=g.useMemo(()=>!We||!Array.isArray(Se)||!De?null:Se.map(mn=>{const En=Wg(mn,P);return a.jsx("input",{type:"hidden",form:p,name:De,value:En,disabled:$e},En)}),[We,Se,p,De,P,$e]),A$=a.jsxs(g.Fragment,{children:[e.children,a.jsx("input",{...te.getValidationProps($e,{onFocus(){if(Ka){Ti?.focus();return}(Fe.current||Ti)?.focus()},onChange(mn){if(mn.nativeEvent.defaultPrevented||$e||v)return;const En=mn.currentTarget.value,Ns=En.toLowerCase(),Ei=Xt(Eo,mn.nativeEvent),ta=()=>ve.current.findIndex(Oo=>Wg(Oo,P).toLowerCase()===Ns||Lh(Oo,A).toLowerCase()===Ns);function $a(){if(We)return;if(d==="none"){Ya(En,Ei);return}let Oo=ta();Oo===-1&&(Oo=ve.current.findIndex((vf,ph)=>{const Yv=qe.current[ph];return Yv!=null&&Yv.toLowerCase()===Ns}));const Yl=Oo===-1?void 0:ve.current[Oo];Yl!=null&&hi?.(Yl,Ei)}tt&&(Gr(),S&&ta()===-1&&gt.set("forceMounted",!0)),queueMicrotask($a)}}),id:se&&Kv==null?`${se}-hidden-input`:void 0,form:p,name:Kv,autoComplete:M,disabled:$e,required:y&&!jw,readOnly:v,value:N$,ref:xg,style:Kv?uP:SS,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),qz]});return a.jsx(uOt.Provider,{value:gt,children:a.jsx(dOt.Provider,{value:vg,children:a.jsx(hOt.Provider,{value:Ge,children:a.jsx(fOt.Provider,{value:E$,children:a.jsx(pOt.Provider,{value:Vt,children:A$})})})})})}function jQ(e){const{multiple:t=!1,defaultValue:n,value:r,onValueChange:s,autoComplete:i,...o}=e;return a.jsx(Mlr,{...o,selectionMode:t?"multiple":"single",selectedValue:r,defaultSelectedValue:n,onSelectedValueChange:s,formAutoComplete:i})}function tUe(e){const{children:t,placeholder:n}=e,r=ag(),s=St(r,fn.itemToStringLabel),i=St(r,fn.selectedValue),o=St(r,fn.items),l=St(r,fn.selectionMode)==="multiple",c=St(r,fn.hasSelectedValue),u=!c&&n!=null&&t==null,d=St(r,fn.hasNullItemLabel,u);let f=null;return typeof t=="function"?f=t(i):t!=null?f=t:!c&&n!=null&&!d?f=n:l&&Array.isArray(i)?f=rSt(i,o,s):f=zSe(i,o,s),a.jsx(g.Fragment,{children:f})}const bOt={...NN,...kp,popupSide:e=>e?{"data-popup-side":e}:null,listEmpty:e=>e?{"data-list-empty":""}:null},Dlr=g.createContext(void 0);function Llr(){return g.useContext(Dlr)}const wOt=g.createContext(void 0);function Mke(e){const t=g.useContext(wOt);if(t===void 0&&!e)throw new Error(Nr(21));return t}const SOt=g.forwardRef(function(t,n){const r=ag(),{buttonRef:s,getButtonProps:i}=gd({native:!1}),o=nf(n,s);function l(u){r.state.setOpen(!1,Xt(N0e,u.nativeEvent,u.currentTarget))}const c=i({onClick:l});return a.jsx("span",{ref:o,...c,"aria-label":"Dismiss",tabIndex:void 0,style:uP})});function kOt(e){const t=St(e,fn.mounted),n=St(e,fn.popupSide),r=St(e,fn.positionerElement);return t&&r?n:null}function EK(){return e6().filteredItems.length===0}function zlr(e){return e==="rtl"?["ArrowRight","ArrowLeft"]:["ArrowLeft","ArrowRight"]}function Flr(e,t){const n=e>=t-1?t-2:e;return n>=0?n:void 0}function OOt(e,t,n){const r=e.state.listRef.current[t];r&&(e.state.selectionEventRef.current=n,r.click(),e.state.selectionEventRef.current=null)}const Dke=g.forwardRef(function(t,n){const{render:r,className:s,disabled:i=!1,id:o,style:l,...c}=t,{state:u,disabled:d,setTouched:f,setFocused:h,validationMode:p,validation:m}=Ru(),{labelId:v}=yd(),y=Llr(),b=!!Mke(!0),S=ag(),k=mOt(),j=Nx(),C=St(S,fn.required),T=St(S,fn.disabled),_=St(S,fn.readOnly),N=St(S,fn.name),E=St(S,fn.form),A=St(S,fn.selectionMode),P=St(S,fn.autoHighlight),L=St(S,fn.inputProps),F=St(S,fn.triggerProps),Q=St(S,fn.open),q=St(S,fn.mounted),B=St(S,fn.selectedValue),V=St(S,fn.id),W=St(S,fn.inline),M=St(S,fn.modal),K=!!P,D=kOt(S),$=d||T||i,z=EK(),U=b||W,G=!U||M,ne=Zi(o??(U?void 0:V)),X=b?Hvt:u,[ee,re]=g.useState(null),ue=g.useRef(!1),te=g.useRef(null),ie=g.useRef(!1),se=A==="none"&&!b,ae=ht(Fe=>{const Ae=b||S.state.inline;Ae&&!S.state.hasInputValue&&S.state.setInputValue("",Xt(Eo)),S.update({inputElement:Fe,inputInsidePopup:Ae,inputOwnsFormValue:se})}),he=b?c:m.getValidationProps($,c);function ge(){S.state.setIndices({activeIndex:null,selectedIndex:null,type:S.state.keyboardActiveRef.current?A0e:_ft})}function me(){S.state.keyboardActiveRef.current=!1}const ke={...X,open:Q,disabled:$,readOnly:_,popupSide:D,listEmpty:z};function Ee(Fe){if(!y)return;let Ae;const{highlightedChipIndex:Be}=y,je=y.chipsRef.current.length,[_e,Ue]=zlr(j);return Be!==void 0?(Fe.key===_e?(Fe.preventDefault(),Be>0?Ae=Be-1:Ae=void 0):Fe.key===Ue?(Fe.preventDefault(),Be<je-1?Ae=Be+1:Ae=void 0):(Fe.key==="Backspace"||Fe.key==="Delete")&&(Fe.preventDefault(),Ae=Flr(Be,B.length),ge()),Ae):(Fe.key===_e&&(Fe.currentTarget.selectionStart??0)===0&&B.length>0&&(Fe.preventDefault(),Ae=je>0?je-1:void 0),Ae)}const qe=cn("input",t,{state:ke,ref:[n,S.state.inputRef,ae],props:[L,F,{value:ee??k,"aria-readonly":_||void 0,"aria-required":C||void 0,"aria-labelledby":v,disabled:$,readOnly:_,required:A==="none"?C:void 0,form:E,...se&&N&&{name:N},id:ne,onFocus(){if(h(!0),!W||!ie.current)return;ie.current=!1;const Fe=te.current;Fe==null||!Object.hasOwn(S.state.valuesRef.current,Fe)||S.state.setIndices({activeIndex:Fe})},onBlur(){f(!0),h(!1);const Fe=S.state.activeIndex;if(W&&Fe!==null&&P!=="always"&&(te.current=Fe,ie.current=!0,S.state.setIndices({activeIndex:null})),p==="onBlur"){const Ae=A==="none"?k:B;m.commit(Ae)}},onCompositionStart(Fe){O4||(ue.current=!0,re(Fe.currentTarget.value))},onCompositionEnd(Fe){ue.current=!1;const Ae=Fe.currentTarget.value;re(null),S.state.setInputValue(Ae,Xt(OE,Fe.nativeEvent))},onChange(Fe){const Ae=Fe.nativeEvent,Be=Ae.inputType,je=!Be||Be==="insertReplacementText",_e=ue.current||!je;function Ue(Ce){_||$||!Ce||!_e||(S.state.setOpen(!0,Xt(OE,Ae)),K||ge())}if(ue.current){const Ce=Fe.currentTarget.value;re(Ce),Ce===""&&!S.state.openOnInputClick&&!S.state.inputInsidePopup&&S.state.setOpen(!1,Xt(Oy,Ae));const le=Ce.trim(),ve=K&&le!=="";Ue(le),Q&&S.state.activeIndex!==null&&!ve&&ge();return}const pe=Xt(OE,Ae);if(S.state.setInputValue(Fe.currentTarget.value,pe),pe.isCanceled)return;const fe=Fe.currentTarget.value==="",Ie=Xt(Oy,Ae);fe&&!S.state.inputInsidePopup&&(A==="single"&&S.state.setSelectedValue(null,Ie),S.state.openOnInputClick||S.state.setOpen(!1,Ie)),Ue(Fe.currentTarget.value.trim()),Q&&S.state.activeIndex!==null&&!K&&ge()},onKeyDown(Fe){if($||_||Fe.ctrlKey||Fe.shiftKey||Fe.altKey||Fe.metaKey)return;S.state.keyboardActiveRef.current=!0;const Ae=Fe.currentTarget,Be=Ae.scrollWidth-Ae.clientWidth,je=j==="rtl";if(Fe.key==="Home"){oc(Fe);const pe=HLe&&je?Ae.value.length:0;Ae.setSelectionRange(pe,pe),Ae.scrollLeft=0;return}if(Fe.key==="End"){oc(Fe);const pe=HLe&&je?0:Ae.value.length;Ae.setSelectionRange(pe,pe),Ae.scrollLeft=je?-Be:Be;return}if(!q&&Fe.key==="Escape"){const pe=A==="multiple"&&Array.isArray(B)?B.length===0:B===null,fe=Xt(w_,Fe.nativeEvent),Ie=A==="multiple"?[]:null;S.state.setInputValue("",fe),S.state.setSelectedValue(Ie,fe),!pe&&!S.state.inline&&!fe.isPropagationAllowed&&Fe.stopPropagation();return}if(y&&Fe.key==="Backspace"&&Ae.value===""&&y.highlightedChipIndex===void 0&&Array.isArray(B)&&B.length>0){const pe=y.chipsRef.current.length,fe=pe>0?pe-1:B.length-1,Ie=B.filter((Ce,le)=>le!==fe);ge(),S.state.setSelectedValue(Ie,Xt(Eo,Fe.nativeEvent));return}const _e=y?.highlightedChipIndex!==void 0,Ue=Ee(Fe);if(y?.setHighlightedChipIndex(Ue),Ue!==void 0?y?.chipsRef.current[Ue]?.focus():_e&&S.state.inputRef.current?.focus(),Fe.which!==229&&Fe.key==="Enter"&&Q){const pe=S.state.activeIndex,fe=Fe.nativeEvent;if(pe===null){if(W)return;S.state.setOpen(!1,Xt(Eo,fe));return}oc(Fe),OOt(S,pe,fe)}},onPointerMove:me,onPointerDown:me},he],stateAttributesMapping:bOt}),Ze=b?a.jsx(a1e.Provider,{value:Gvt,children:qe}):qe;return a.jsxs(g.Fragment,{children:[Q&&G&&a.jsx(SOt,{ref:S.state.startDismissRef}),Ze]})}),jOt=g.forwardRef(function(t,n){const{render:r,className:s,nativeButton:i=!0,disabled:o=!1,id:l,style:c,...u}=t,{state:d,disabled:f,setTouched:h,setFocused:p,validationMode:m,validation:v}=Ru(),{labelId:y}=yd(),x=ag(),b=St(x,fn.selectionMode),S=St(x,fn.disabled),k=St(x,fn.readOnly),j=St(x,fn.required),C=St(x,fn.positionerElement),T=St(x,fn.listElement),_=St(x,fn.popupId),N=St(x,fn.triggerProps),E=St(x,fn.inputInsidePopup),A=St(x,fn.id),P=St(x,fn.labelId),L=St(x,fn.open),F=St(x,fn.selectedValue),Q=St(x,fn.activeIndex),q=St(x,fn.selectedIndex),B=St(x,fn.hasSelectedValue),V=IK(),W=mOt(),M=bo(),K=f||S||o,D=EK(),$=kOt(x);kk({id:E?l:void 0});const z=E?l??A:l,U=FSe(y,P);let G;L&&E?G=_??gOt(A):L&&(G=T?.id);const ne=g.useRef("");function X(he){ne.current=he.pointerType}const{reference:ee}=X0e(V,{enabled:!L&&!k&&!S&&b==="single",listRef:x.state.labelsRef,activeIndex:Q,selectedIndex:q,onMatch(he){const ge=x.state.valuesRef.current[he];ge!==void 0&&x.state.setSelectedValue(ge,Xt(Eo))}}),{reference:re}=S_(V,{enabled:!k&&!S,event:"mousedown"}),{buttonRef:ue,getButtonProps:te}=gd({native:i,disabled:K}),ie={...d,open:L,disabled:K,popupSide:$,listEmpty:D,placeholder:b==="none"?!1:!B},se=ht(he=>{x.set("triggerElement",he)});return cn("button",t,{ref:[n,ue,se],state:ie,props:[N,re,ee,{id:z,tabIndex:E?0:-1,role:E?"combobox":void 0,"aria-expanded":L,"aria-haspopup":E?"dialog":"listbox","aria-controls":G,"aria-required":E&&j||void 0,"aria-labelledby":U,onPointerDown:X,onPointerEnter:X,onFocus(){p(!0),!(K||k)&&M.start(0,x.state.forceMount)},onBlur(he){if(!ln(C,he.relatedTarget)&&(h(!0),p(!1),m==="onBlur")){const ge=b==="none"?W:F;v.commit(ge)}},onMouseDown(he){if(K||k||(E||V.set("domReferenceElement",he.currentTarget),x.state.forceMount(),ne.current!=="touch"&&(x.state.inputRef.current?.focus(),E||he.preventDefault()),L))return;const ge=wr(he.currentTarget);function me(ke){const Ee=x.state.triggerElement;if(!Ee)return;const qe=qi(ke),Ze=x.state.positionerElement,Fe=x.state.listElement;ln(Ee,qe)||ln(Ze,qe)||ln(Fe,qe)||ESe(ke,Ee)||x.state.setOpen(!1,Xt(AH,ke))}E&&ge.addEventListener("mouseup",me,{once:!0})},onKeyDown(he){k||(he.key==="ArrowDown"||he.key==="ArrowUp")&&(oc(he),x.state.setOpen(!0,Xt(j4,he.nativeEvent)),x.state.inputRef.current?.focus())}},v.getValidationProps(K,u),te],stateAttributesMapping:bOt})}),Blr=g.createContext(null);function Vlr(){return g.useContext(Blr)}function Ulr(e){const{children:t}=e,{filteredItems:n}=e6(),r=Vlr(),s=r?r.items:n;return a.jsx(g.Fragment,{children:s.map(t)})}const COt=g.forwardRef(function(t,n){var r;const{render:s,className:i,style:o,children:l,...c}=t,u=ag(),d=IK(),f=!!Mke(!0),{filteredItems:h,hasItems:p}=e6(),m=St(u,fn.selectionMode),v=St(u,fn.grid),y=St(u,fn.listProps),x=St(u,fn.virtualized),b=St(u,fn.forceMounted),S=m==="multiple",k=h.length===0,j=ht(P=>{u.set("positionerElement",P)}),C=ht(P=>{u.set("listElement",P)}),T=g.useMemo(()=>typeof l=="function"?r||(r=a.jsx(Ulr,{children:l})):l,[l]),_={empty:k},N=d.useState("floatingId"),E=cn("div",t,{state:_,ref:[n,C,f?null:j],props:[y,{children:T,tabIndex:-1,id:N,role:v?"grid":"listbox","aria-multiselectable":S?"true":void 0,onKeyDown(P){if(!(u.state.disabled||u.state.readOnly)&&P.key==="Enter"){const L=u.state.activeIndex;if(L==null)return;oc(P),OOt(u,L,P.nativeEvent)}},onKeyDownCapture(){u.state.keyboardActiveRef.current=!0},onPointerMoveCapture(){u.state.keyboardActiveRef.current=!1}},c]});if(x)return E;const A=p&&!b?void 0:u.state.labelsRef;return a.jsx(EP,{elementsRef:u.state.listRef,labelsRef:A,children:E})}),qlr="⁠",Qlr=200;function Zlr(e){const t=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT);let n=null;for(;t.nextNode();){const r=t.currentNode;r.nodeValue!==""&&(n=r)}return n}function _Ot(){const e=bo(),t=g.useRef(null);return g.useEffect(()=>{if(G3)return;const n=t.current;if(n==null)return;const r=Zlr(n);if(r==null)return;const s=r.data,i=`${s}${qlr}`;return r.nodeValue=i,e.start(Qlr,()=>{r.nodeValue===i&&(r.nodeValue=s)}),()=>{e.clear(),r.nodeValue===i&&(r.nodeValue=s)}},[t,e]),t}const nUe=g.forwardRef(function(t,n){const{render:r,className:s,style:i,children:o,...l}=t,c=_Ot();return cn("div",t,{ref:[n,c],props:[{children:o,role:"status","aria-live":"polite","aria-atomic":!0},l]})}),TOt=g.createContext(void 0);function Wlr(){const e=g.useContext(TOt);if(e===void 0)throw new Error(Nr(20));return e}const Lke=g.forwardRef(function(t,n){const{keepMounted:r=!1,...s}=t,i=ag(),o=St(i,fn.mounted),l=St(i,fn.forceMounted);return o||r||l?a.jsx(TOt.Provider,{value:r,children:a.jsx(J3,{ref:n,...s})}):null}),zke=g.forwardRef(function(t,n){const{render:r,className:s,anchor:i,positionMethod:o,side:l,align:c,sideOffset:u,alignOffset:d,collisionBoundary:f="clipping-ancestors",collisionPadding:h,arrowPadding:p,sticky:m,disableAnchorTracking:v=!1,collisionAvoidance:y=z0e,style:x,...b}=t,S=ag(),k=IK(),j=Wlr(),C=St(S,fn.modal),T=St(S,fn.open),_=St(S,fn.mounted),N=St(S,fn.openMethod),E=St(S,fn.positionerElement),A=St(S,fn.triggerElement),P=St(S,fn.inputElement),L=St(S,fn.inputGroupElement),F=St(S,fn.inputInsidePopup),Q=St(S,fn.transitionStatus),q=EK(),V=hP({anchor:i??(F?A:L??P),floatingRootContext:k,positionMethod:o,mounted:_,side:l,sideOffset:u,align:c,alignOffset:d,arrowPadding:p,collisionBoundary:f,collisionPadding:h,sticky:m,disableAnchorTracking:v,keepMounted:j,collisionAvoidance:y,lazyFlip:!0});iK(T&&C,N==="touch",E,A);const W={open:T,side:V.side,align:V.align,anchorHidden:V.anchorHidden,empty:q};Ot(()=>{S.set("popupSide",V.side)},[S,V.side]);const M=ht(D=>{S.set("positionerElement",D)}),K=pP(t,W,{styles:V.positionerStyles,transitionStatus:Q,props:b,refs:[n,M],hidden:!_,inert:!T});return a.jsxs(wOt.Provider,{value:V,children:[_&&C&&a.jsx(BL,{inert:mP(!T),cutout:L??P??A}),K]})}),Hlr={...C_,...ih},Fke=g.forwardRef(function(t,n){const{render:r,className:s,style:i,initialFocus:o,finalFocus:l,...c}=t,u=ag(),d=Mke(),f=IK(),h=St(u,fn.mounted),p=St(u,fn.open),m=St(u,fn.openMethod),v=St(u,fn.popupProps),y=St(u,fn.transitionStatus),x=St(u,fn.inputInsidePopup),b=St(u,fn.inputElement),S=St(u,fn.modal),k=St(u,fn.id),j=EK(),C=c.id??(x?gOt(k):void 0);Ot(()=>(u.set("popupId",u.state.popupRef.current?.id||C),()=>{u.set("popupId",void 0)}),[u,C]),Tl({open:p,ref:u.state.popupRef,onComplete(){p&&u.state.onOpenChangeComplete(!0)}});const T={open:p,side:d.side,align:d.align,anchorHidden:d.anchorHidden,transitionStatus:y,empty:j},_=cn("div",t,{state:T,ref:[n,u.state.popupRef],props:[v,{id:C,role:x?"dialog":"presentation",onFocus(L){const F=qi(L.nativeEvent);m!=="touch"&&(ln(u.state.listElement,F)||F===L.currentTarget)&&u.state.inputRef.current?.focus()}},T_(y),c],stateAttributesMapping:Hlr}),E=o===void 0?x?L=>L==="touch"?u.state.popupRef.current:b:!1:o;let A;l!=null?A=l:A=x?void 0:!1;const P=!x||S;return a.jsx(dP,{context:f,disabled:!h,modal:P,openInteractionType:m,initialFocus:E,returnFocus:A,getInsideElements:()=>[u.state.startDismissRef.current,u.state.endDismissRef.current],children:a.jsxs(g.Fragment,{children:[_,P&&a.jsx(SOt,{ref:u.state.endDismissRef})]})})}),IOt=g.createContext(void 0);function EOt(){const e=g.useContext(IOt);if(!e)throw new Error(Nr(19));return e}const Glr=g.createContext(!1);function Klr(){return g.useContext(Glr)}function NOt(e){const{componentProps:t,forwardedRef:n,virtualized:r,indexFromFilter:s}=e,{render:i,className:o,style:l,value:c=null,index:u,disabled:d=!1,nativeButton:f=!1,...h}=t,p=g.useRef(null),m=ew({guess:!0,index:u,textRef:p}),v=ag(),y=Klr(),x=Alr(),b=St(v,fn.selectionMode),S=St(v,fn.disabled),k=St(v,fn.readOnly),j=St(v,fn.isItemEqualToValue),C=S||d,T=b!=="none",_=u??s??m.index,N=_!==-1,E=St(v,fn.id),A=St(v,fn.isActive,_),P=St(v,fn.isSelected,c),L=St(v,fn.itemProps),F=g.useRef(null),Q=E!=null&&N?`${E}-${_}`:void 0,q=P&&T;Ot(()=>{if(!(N&&(r||u!=null)))return;const U=v.state.listRef.current;return U[_]=F.current,()=>{delete U[_]}},[N,r,_,u,v]),Ot(()=>{if(!N||x)return;const z=v.state.valuesRef.current;return z[_]=c,()=>{delete z[_]}},[N,x,_,c,v]),Ot(()=>{if(!N||x)return;const z=v.state.selectedValue,U=Array.isArray(z)?z[z.length-1]:z;Um(c,U,j)&&v.set("selectedIndex",_)},[N,x,v,_,c,j]);const{getButtonProps:B,buttonRef:V}=gd({disabled:C,focusableWhenDisabled:!0,native:f,composite:!0}),W={disabled:C,selected:q,highlighted:A};function M(z){function U(){v.state.handleSelection(z,c)}v.state.submitOnItemClick?(So.flushSync(U),v.state.requestSubmit()):U()}const K={id:Q,role:y?"gridcell":"option","aria-selected":T?q:void 0,tabIndex:void 0,onPointerDownCapture(z){z.isPrimary&&(v.state.pointerDownItemRef.current=z.currentTarget),z.preventDefault()},onMouseDown(z){z.preventDefault()},onClick(z){C||k||M(z.nativeEvent)},onMouseUp(z){const U=v.state.pointerDownItemRef.current===z.currentTarget;v.state.pointerDownItemRef.current=null,!(C||k||z.button!==0||U||!A)&&M(z.nativeEvent)}},D=cn("div",t,{ref:[V,n,m.ref,F],state:W,props:[L,K,h,B]}),$=g.useMemo(()=>({selected:q,textRef:p}),[q,p]);return a.jsx(IOt.Provider,{value:$,children:D})}function Ylr(e){const{componentProps:t,forwardedRef:n}=e,r=ag(),s=St(r,fn.isItemEqualToValue),{flatFilteredItems:i}=e6(),o=VE(i,t.value??null,s);return a.jsx(NOt,{componentProps:t,forwardedRef:n,virtualized:!0,indexFromFilter:o})}const AOt=g.memo(g.forwardRef(function(t,n){const r=ag(),s=St(r,fn.virtualized);return s&&t.index==null?a.jsx(Ylr,{componentProps:t,forwardedRef:n}):a.jsx(NOt,{componentProps:t,forwardedRef:n,virtualized:s,indexFromFilter:void 0})})),POt=g.forwardRef(function(t,n){const{selected:r}=EOt();return t.keepMounted||r?a.jsx(Xlr,{...t,ref:n}):null}),Xlr=g.memo(g.forwardRef((e,t)=>{const{render:n,className:r,style:s,keepMounted:i,...o}=e,{selected:l}=EOt(),c=g.useRef(null),{transitionStatus:u,setMounted:d}=wp(l),h=cn("span",e,{ref:[t,c],state:{selected:l,transitionStatus:u},props:[{"aria-hidden":!0,children:"✔️"},o],stateAttributesMapping:ih});return Tl({open:l,ref:c,onComplete(){l||d(!1)}}),h})),$Ot=g.forwardRef(function(t,n){const{render:r,className:s,style:i,children:o,...l}=t,{filteredItems:c}=e6(),u=ag(),d=_Ot(),f=c.length===0?o:null;return cn("div",t,{ref:[n,u.state.emptyRef,d],props:[{children:f,role:"status","aria-live":"polite","aria-atomic":!0},l]})});function Jlr(e){return e==="link"?"ghost":e}function ROt({variant:e,size:t,className:n}){const r=Jlr(e);return Z(vP({variant:r,size:t}),r==="default"&&Rht,!iwe(t)&&Z(Mht,"justify-between"),J0e[r],"data-[placeholder]:text-muted-foreground",nwe,n)}const Jpe=md(og,{variants:{multiple:{false:"",true:""}},defaultVariants:{multiple:!1}}),is={root:"flex flex-col gap-1.5",chevron:"ml-2 h-4 w-4 shrink-0 text-muted-foreground",placeholder:"text-muted-foreground",popup:Z(PP,"max-h-none overflow-hidden p-0"),positioner:Z(AP,"pointer-events-auto"),searchContainer:zE.container,searchIcon:zE.icon,searchInput:Z(zE.input,"disabled:cursor-not-allowed disabled:opacity-50"),empty:Z(hQ,"empty:hidden"),list:"p-1 empty:p-0",listScroller:"max-h-dropdown overflow-y-auto overflow-x-hidden",item:Jpe({multiple:!1}),itemMulti:Jpe({multiple:!0}),itemRightSlot:"ml-auto flex items-center gap-2 shrink-0",checkContainer:Z(M_,"ml-0"),checkIcon:"size-full",optionText:"flex flex-col gap-0.5 min-w-0",optionLabel:"truncate",optionDescription:"text-caption text-muted-foreground truncate",optionEnd:"ml-auto flex items-center shrink-0"};function ecr({children:e,className:t}){return a.jsx("div",{className:Z("grid gap-2 text-foreground",t),children:e})}function MOt({children:e,name:t,className:n}){return a.jsxs(Y,{variant:"body-sm",role:"alert",id:t!==void 0?`error-${t}`:void 0,className:Z("flex gap-1 text-destructive-foreground",n),children:[a.jsx(At,{size:"xs",className:"mt-1 shrink-0","aria-hidden":!0,children:a.jsx(xP,{})}),a.jsx("span",{children:e})]})}function DOt({children:e}){return a.jsx(Y,{variant:"caption",tone:"muted",children:e})}function tcr({children:e,name:t,htmlFor:n=`input-${t}`,required:r,disabled:s=!1,size:i="default",className:o}){return a.jsxs("label",{htmlFor:n,className:Z("inline-flex items-center text-label",{"text-body":i==="bigger","text-foreground":!s,"text-muted-foreground":s},o),children:[e,r?a.jsxs(a.Fragment,{children:[a.jsx("span",{"aria-hidden":!0,className:Z("ml-0.5",s?"text-muted-foreground":"text-destructive-foreground"),children:"*"}),a.jsx("span",{className:"sr-only",children:" (required)"})]}):null]})}function ncr({children:e,className:t,layout:n="vertical",labelColumnWidth:r}){return a.jsx("div",{className:Z("relative grid gap-2 text-foreground",{"horizontal-field-block grid-cols-[auto_1fr] items-baseline":n==="horizontal"},t),style:n==="horizontal"&&r?{gridTemplateColumns:`${r} 1fr`}:void 0,children:e})}function rcr({name:e,helpText:t,errorMsg:n}){return a.jsx("div",{className:"h-[1lh] min-w-0 overflow-hidden text-body-sm [&>p]:truncate",children:n?a.jsx(MOt,{name:e,className:"truncate",children:n}):t?a.jsx(DOt,{children:t}):null})}const scr=Object.assign({},{Layout:ncr,Column:ecr,Label:tcr,HelpText:DOt,ErrorMsg:MOt,Message:rcr}),icr=e=>`error-${e}`,rUe=[],ocr=[];function Hoe(e){return e.multiple===!0}const LOt=g.forwardRef((e,t)=>a.jsx(AOt,{ref:Du(t),...e}));LOt.displayName="ComboboxItem";function sUe({option:e}){return a.jsxs("span",{className:is.optionText,children:[a.jsx("span",{className:is.optionLabel,children:e.label}),e.description&&a.jsx("span",{className:is.optionDescription,children:e.description})]})}function fl(e){const{options:t,placeholder:n=Hoe(e)?"Select options...":"Select option...",searchPlaceholder:r="Search...",emptyText:s="No option found.",className:i,disabled:o=!1,variant:l="default",size:c="md",open:u,onOpenChange:d,container:f,id:h,"aria-label":p,"aria-describedby":m,align:v="start",showChevron:y=!0,iconOnlyValue:x=!1,allowCustomValue:b=!1,onInputValueChange:S,error:k,name:j}=e,C=Hoe(e),T=C?e.clearLabel:void 0,_=kP(),N=g.useId(),E=j??N,A=[m,k?icr(E):void 0].filter(Boolean).join(" ")||void 0,[P,L]=g.useState(""),F=P.trim(),Q=!C&&b&&F&&!t.some(re=>re.value===F)?{label:`Use “${F}”`,value:F}:void 0,q=Q?[Q,...t]:t,B=C?e.value??rUe:rUe,V=g.useMemo(()=>new Set(B),[B]),W=C?null:t.find(re=>re.value===e.value)??null,M=C?t.filter(re=>V.has(re.value)):ocr,K=M.length===0?n:`${M.length} selected`,D=()=>{Hoe(e)&&e.onValueChange?.([])},$=tw(f),{contains:z}=Rlr(),U=g.useCallback((re,ue)=>z(re.label,ue)||(re.keywords?.some(te=>z(te,ue))??!1),[z]),G=Bv(),ne=iwe(c),X=a.jsxs(a.Fragment,{children:[a.jsxs(jOt,{id:h,"aria-label":p??(h||_?void 0:C?"Select options":"Select option"),...Mx({"aria-label":p}),...ZH(!!k),"aria-describedby":A,"data-shape":ne?"icon":void 0,className:ROt({variant:l,size:c,className:Z(x&&"w-auto px-2.5",i)}),children:[ne?a.jsx("span",{className:"sr-only",children:C?K:a.jsx(tUe,{placeholder:n})}):C?a.jsx("span",{className:Z("truncate",M.length===0&&is.placeholder),children:K}):a.jsxs("span",{className:Z("flex min-w-0 flex-1 items-center",x?"justify-center":"gap-2"),children:[W?.start,a.jsx("span",{className:"truncate",children:W?.displayLabel??a.jsx(tUe,{placeholder:n})})]}),y?a.jsx("span",{className:"flex shrink-0 items-center",children:a.jsx(Kht,{className:Z(is.chevron,(ne||x)&&"ml-0")})}):null]}),a.jsx(Lke,{container:$,children:a.jsx(zke,{align:v,sideOffset:4,positionMethod:Av,className:is.positioner,children:a.jsxs(Fke,{className:is.popup,children:[a.jsxs("div",{className:is.searchContainer,children:[a.jsx(wu,{className:is.searchIcon}),a.jsx(Dke,{className:is.searchInput,placeholder:r,...pp})]}),a.jsx($Ot,{className:is.empty,children:s}),a.jsx(jr,{maxHeight:"var(--spacing-dropdown)",children:a.jsx(Au,{className:"scroll-py-8",children:a.jsx("div",{className:G.containerClassName,...G.getContainerProps({}),children:a.jsx(US,{menu:G,children:a.jsx(COt,{className:is.list,children:re=>{const ue=V.has(re.value);return a.jsx(LOt,{value:re,className:Jpe({multiple:C}),children:C?a.jsxs(a.Fragment,{children:[re.start,a.jsx(sUe,{option:re}),a.jsxs("span",{className:is.itemRightSlot,children:[re.end?a.jsx("div",{className:is.optionEnd,children:re.end}):null,a.jsx("span",{className:is.checkContainer,children:ue?a.jsx(ur,{className:is.checkIcon}):null})]})]}):a.jsxs(a.Fragment,{children:[re.start,a.jsx(sUe,{option:re}),a.jsxs("span",{className:is.itemRightSlot,children:[re.end?a.jsx("div",{className:is.optionEnd,children:re.end}):null,a.jsx("span",{className:is.checkContainer,children:a.jsx(POt,{children:a.jsx(ur,{className:is.checkIcon})})})]})]})},re.value)}})})})})}),B.length>0&&T?a.jsx("div",{className:Z("border-t","border-border","p-1"),children:a.jsx(ce,{type:"button",variant:"destructive-ghost",size:"sm",className:"w-full justify-start",onClick:D,icon:a.jsx(Mn,{}),children:T})}):null]})})})]}),ee=C?a.jsx(jQ,{multiple:!0,autoHighlight:!0,items:q,filter:U,value:M,onValueChange:re=>e.onValueChange?.((re??[]).map(ue=>ue.value)),disabled:o,open:u,onOpenChange:d,children:X}):a.jsx(jQ,{autoHighlight:!0,items:q,filter:U,value:W,inputValue:P,onInputValueChange:re=>{L(re),S?.(re)},onValueChange:re=>{re&&(e.onValueChange?.(re.value),L(""),S?.(""))},disabled:o,open:u,onOpenChange:d,children:X});return k?a.jsxs("div",{className:is.root,children:[ee,a.jsx(scr.ErrorMsg,{name:E,children:k})]}):ee}function acr({value:e,onValueChange:t,placeholder:n="Select a workflow...",searchPlaceholder:r="Search workflows...",emptyText:s="No workflows found.",className:i,disabled:o=!1,variant:l,size:c,"aria-label":u,align:d,requestContext:f}){const{data:h={},isLoading:p,isError:m,error:v}=tg({requestContext:f}),{navigate:y,paths:x}=Sn();g.useEffect(()=>{if(m){const k=v instanceof Error?v.message:"Failed to load workflows";Xe.error(`Error loading workflows: ${k}`)}},[m,v]);const b=Object.keys(h).map(k=>({label:h[k]?.name||k,value:k})),S=k=>{t?t(k):k&&k!==e&&y(x.workflowLink(k))};return a.jsx(fl,{options:b,value:e,onValueChange:S,placeholder:p?"Loading workflows...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||p||m,variant:l,size:c,"aria-label":u,align:d})}function lcr(){const{workflowId:e}=Cr(),{data:t,isLoading:n}=tg();return e?n?a.jsx(Fx,{}):t?.[e]?.name||e:null}function ccr(){const{workflowId:e}=Cr();return e?a.jsx(acr,{value:e,...MP,"aria-label":"Switch workflow"}):null}function ucr(){const{runId:e}=Cr();return e?e.split("-")[0]:null}function dcr(){const{runId:e}=Cr();return e?a.jsx(ii,{content:e,tooltip:"Copy run id",variant:"ghost",size:"icon-sm"}):null}const fcr=e=>a.jsxs("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M11.0313 7.97578C11.0313 9.34436 9.92183 10.4538 8.55324 10.4538C7.18466 10.4538 6.0752 9.34436 6.0752 7.97578C6.0752 6.60719 7.18466 5.49773 8.55324 5.49773C9.92183 5.49773 11.0313 6.60719 11.0313 7.97578ZM11.0313 7.97578H14.573",stroke:"currentColor",strokeWidth:"1.33333",strokeLinecap:"round"}),a.jsx("path",{d:"M12.967 4.46154C11.9273 3.14431 10.3165 2.29883 8.50814 2.29883C5.37277 2.29883 2.83105 4.84055 2.83105 7.97591C2.83105 11.1113 5.37277 13.653 8.50814 13.653C10.3165 13.653 11.9273 12.8075 12.967 11.4903",stroke:"currentColor",strokeWidth:"1.33333",strokeLinecap:"round"})]});function hcr(){return a.jsx(ce,{render:a.jsx("a",{target:"_blank",rel:"noopener noreferrer",href:"/swagger-ui"}),variant:"ghost",size:"sm",icon:a.jsx(fcr,{}),children:"API endpoints"})}function pcr(e){if("Component"in e&&e.Component){const t=e.Component;return a.jsx(t,{})}return"node"in e?e.node:e.label}function Dt({crumbs:e}){if(e.length===0)return null;const t=e.length-1;return a.jsx($ke,{label:"Breadcrumb",className:"min-w-0 flex-1 overflow-hidden",listClassName:"min-w-0",children:e.map((n,r)=>{const s=r===t,i=!s&&n.to,o=n.icon,l=n.Action,c=n.Switcher;return a.jsx(_5,{as:i?lc:"span",to:i?n.to:void 0,isCurrent:s,icon:o?a.jsx(o,{}):void 0,action:l?a.jsx(l,{}):void 0,switcher:c?a.jsx(c,{}):void 0,children:pcr(n)},n.id)})})}const DP=({queryOptions:e}={})=>{const t=Ke();return Ct({queryKey:["mastra-packages"],queryFn:()=>t.getSystemPackages(),...e})},zOt=()=>{const{data:e,isLoading:t}=DP();return{hasObservability:!!(e?.observabilityEnabled??e?.packages?.some(r=>r.name==="@mastra/observability")),isLoading:t}},mcr=40,gcr="",eme=e=>new Date(e.createdAt).getTime(),vcr=(e,t)=>eme(e)-eme(t),NK=({threadId:e,agentId:t,memory:n,requestContext:r,queryOptions:s})=>{const i=Ke();return Mm({queryKey:["memory","messages",e,t,r],initialPageParam:gcr,queryFn:n&&e?({pageParam:o})=>i.listThreadMessages(e,{agentId:t,requestContext:r,includeSystemReminders:!0,perPage:mcr,orderBy:{field:"createdAt",direction:"DESC"},filter:o?{dateRange:{end:new Date(o)}}:void 0}):Q0,getNextPageParam:(o,l,c)=>{if(!o.hasMore||o.messages.length===0)return;const u=new Date(Math.min(...o.messages.map(eme))).toISOString();return u===c?void 0:u},select:o=>{const l=new Set,c=o.pages.flatMap(u=>u.messages).filter(u=>l.has(u.id)?!1:(l.add(u.id),!0)).sort(vcr);return{...o,messages:c}},staleTime:0,gcTime:0,retry:!1,refetchOnWindowFocus:!1,...s})};function ycr({agentId:e,path:t,agentVersionId:n,requestContext:r,queryOptions:s}){const i=Ke();return Ct({queryKey:["agent-plan",e,n,t,r],queryFn:()=>(n?i.getAgent(e,{versionId:n}):i.getAgent(e)).readPlan(t,r),retry:!1,...s})}const xcr={"background-task-running":"running","background-task-output":"running","background-task-completed":"completed","background-task-failed":"failed","background-task-cancelled":"cancelled","background-task-suspended":"suspended","background-task-resumed":"running"};function bcr(e={}){const{enabled:t=!0,agentId:n,runId:r,threadId:s,resourceId:i,taskId:o}=e,l=Ke(),[c,u]=g.useState({}),[d,f]=g.useState(!1),[h,p]=g.useState(null),m=g.useRef(null),v=g.useRef(null),y=g.useRef(0),x=g.useMemo(()=>Object.values(c).filter(N=>N.status==="running"),[c]),b=g.useMemo(()=>Object.values(c).filter(N=>N.status==="completed"),[c]),S=g.useMemo(()=>Object.values(c).filter(N=>N.status==="failed"),[c]),k=g.useCallback(()=>{v.current?.cancel().catch(()=>{}),v.current=null,m.current?.abort(),m.current=null,f(!1)},[]),j=g.useCallback(async()=>{const N=++y.current;k(),p(null);const E=new AbortController;m.current=E;try{const A=await l.streamBackgroundTasks({agentId:n,runId:r,threadId:s,resourceId:i,taskId:o});if(!A){p(new Error("Stream connection failed"));return}N===y.current&&f(!0);const P=A.getReader();for(v.current=P;!E.signal.aborted;){const{done:L,value:F}=await P.read();if(L)break;const Q=F;Q.type!=="background-task-output"&&u(q=>({...q,[Q.payload.taskId]:{...q[Q.payload.taskId],...Q.payload,status:xcr[Q.type],args:("args"in Q.payload?Q.payload.args:void 0)??q[Q.payload.taskId]?.args??{}}}))}}catch(A){A?.name!=="AbortError"&&N===y.current&&p(A instanceof Error?A:new Error(String(A)))}finally{N===y.current&&f(!1)}},[l,n,r,s,i,o,k]);g.useEffect(()=>{if(!t){k();return}return j(),k},[t,j,k]);const C=g.useCallback(()=>{k()},[k]),T=g.useCallback(()=>{j()},[j]);return{tasks:c,isConnected:d,error:h,disconnect:C,reconnect:T,runningTasks:x,completedTasks:b,failedTasks:S,clearCompletedAndFailedTasks:()=>{u(N=>{const E={...N};return Object.values(E).forEach(A=>{(A.status==="completed"||A.status==="failed"||A.status==="cancelled"||A.status==="timed_out")&&delete E[A.taskId]}),E})}}}const wcr=({backgroundTaskId:e,queryOptions:t})=>{const n=Ke();return Ct({queryKey:["background-task",e],queryFn:()=>n.getBackgroundTask(e),...t})},Scr=(e,t)=>["browser-session-probe",e,t],kcr={hasSession:!0,screencastAvailable:!0},Ocr=e=>!e||typeof e!="object"?!1:"status"in e&&e.status===404||"statusCode"in e&&e.statusCode===404;function jcr({agentId:e,threadId:t,queryOptions:n}){const r=Ke();return Ct({queryKey:Scr(e,t),queryFn:async()=>{if(!e)return{hasSession:!1,screencastAvailable:!1};try{return await r.getAgent(e).browserSession(t)}catch(s){if(Ocr(s))return kcr;throw s}},refetchOnWindowFocus:!0,staleTime:0,retry:1,...n})}const Ccr="MODEL_NOT_ALLOWED";function _cr(e){if(!e||typeof e!="object")return null;const t=e;if(t.status!==422)return null;const n=t.body;if(n?.error?.code!==Ccr)return null;const r=n.error;return{message:r.message||t.message||"Model not allowed by admin policy",attempted:r.attempted,offendingLabel:r.offendingLabel}}const zC=({queryOptions:e,...t}={})=>{const n=Ke(),r=Object.keys(t).length>0?t:void 0;return Ct({queryKey:["stored-agents",r],queryFn:()=>n.listStoredAgents(r),...e})},AK=({agentId:e,status:t,requestContext:n,queryOptions:r}={})=>{const s=Ke();return Ct({queryKey:["stored-agent",e,t,n],queryFn:async()=>{if(!e)return null;try{return await s.getStoredAgent(e).details(n,{status:t})}catch(i){if(i&&typeof i=="object"&&"status"in i&&i.status===404)return null;throw i}},retry:!1,...r})},Bke=({agentId:e,requestContext:t,queryOptions:n}={})=>{const r=Ke();return Ct({queryKey:["stored-agent-dependents",e,t],queryFn:()=>r.getStoredAgent(e).dependents(t),retry:!1,...n})},FC=({agentId:e,requestContext:t,queryOptions:n}={})=>{const r=Ke(),s=mr(),i=o=>{_cr(o)&&s.invalidateQueries({queryKey:["builder-settings"]})};return{createStoredAgent:wn({mutationFn:o=>r.createStoredAgent(o),onSuccess:o=>{s.setQueryData(["stored-agent",o.id,"draft",t],o),s.setQueryData(["stored-agent",o.id,void 0,t],o),s.invalidateQueries({queryKey:["stored-agents"]}),s.invalidateQueries({queryKey:["agents"]}),s.invalidateQueries({queryKey:["agent",o.id]})},onError:i,...n?.createStoredAgent}),updateStoredAgent:wn({mutationFn:o=>{if(!e)throw new Error("agentId is required for update");return r.getStoredAgent(e).update(o,t)},onSuccess:()=>{s.invalidateQueries({queryKey:["stored-agents"]}),s.invalidateQueries({queryKey:["agents"]}),e&&(s.invalidateQueries({queryKey:["stored-agent",e]}),s.invalidateQueries({queryKey:["agent",e]}))},onError:i,...n?.updateStoredAgent}),deleteStoredAgent:wn({mutationFn:()=>{if(!e)throw new Error("agentId is required for delete");return r.getStoredAgent(e).delete(t)},onSuccess:()=>{s.invalidateQueries({queryKey:["stored-agents"]}),s.invalidateQueries({queryKey:["agents"]}),e&&(s.removeQueries({queryKey:["stored-agent",e]}),s.removeQueries({queryKey:["agent",e]}))},...n?.deleteStoredAgent})}},t6=({agentId:e,params:t,requestContext:n,queryOptions:r})=>{const s=Ke();return Ct({queryKey:["agent-versions",e,t,n],queryFn:e?()=>s.getStoredAgent(e).listVersions(t,n):Q0,...r})},FOt=({agentId:e,versionId:t,requestContext:n,queryOptions:r})=>{const s=Ke();return Ct({queryKey:["agent-version",e,t,n],queryFn:()=>s.getStoredAgent(e).getVersion(t,n),...r})},Tcr=({agentId:e,fromVersionId:t,toVersionId:n,requestContext:r,queryOptions:s})=>{const i=Ke();return Ct({queryKey:["agent-versions-compare",e,t,n,r],queryFn:()=>i.getStoredAgent(e).compareVersions(t,n,r),...s})};function iUe(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Icr(e,t,n,r){const s=Ke(),[i,o]=g.useState(!1),[l,c]=g.useState(null),[u,d]=g.useState("thread"),[f,h]=g.useState("markdown"),[p,m]=g.useState(!0),[v,y]=g.useState(!1),x=g.useRef(0),b=g.useCallback(async()=>{const k=++x.current;m(!0);try{if(!e||!t){c(null),m(!1);return}const j=await s.getWorkingMemory({agentId:e,threadId:t,resourceId:n,requestContext:r});if(k!==x.current)return;const{workingMemory:C,source:T,workingMemoryTemplate:_,threadExists:N}=j;if(o(N),c(C),d(T),h(_?.format||"markdown"),_?.format==="json"){let E="";C?E=iUe(C):_?.content?E=iUe(_.content):E="",c(E)}else c(C||_?.content||"")}catch(j){if(k!==x.current)return;c(null),console.error("Error fetching working memory",j)}finally{k===x.current&&m(!1)}},[e,t,n,s,r]);return g.useEffect(()=>{b()},[b]),{threadExists:i,workingMemoryData:l,workingMemorySource:u,workingMemoryFormat:f,isLoading:p,isUpdating:v,refetch:b,updateWorkingMemory:async k=>{y(!0);try{if(f==="json")try{JSON.parse(k)}catch{throw new Error("Invalid JSON working memory")}await s.updateWorkingMemory({agentId:e,threadId:t,workingMemory:k,resourceId:n,requestContext:r}),b()}catch(j){throw console.error("Error updating working memory",j),j}finally{y(!1)}}}}const bd=({agentId:e,requestContext:t,queryOptions:n}={})=>{const r=Ke();return Ct({queryKey:["agent",e,t],queryFn:()=>e?r.getAgent(e).details(t):null,retry:!1,...n})},Cp=({requestContext:e,queryOptions:t}={})=>{const n=Ke();return Ct({queryKey:["agents",e],queryFn:()=>n.listAgents(e),...t})},Ecr=({agentId:e,queryOptions:t})=>{const n=Ke(),r=mr();return wn({mutationFn:async s=>n.getAgent(e).reorderModelList(s),onSuccess:()=>{r.invalidateQueries({queryKey:["agent",e]})},onError:s=>{console.error("Error reordering model list",s)},...t})},Ncr=({agentId:e,queryOptions:t})=>{const n=Ke(),r=mr();return wn({mutationFn:async s=>n.getAgent(e).updateModelInModelList(s),onSuccess:()=>{r.invalidateQueries({queryKey:["agent",e]})},onError:s=>{console.error("Error updating model in model list",s)},...t})};function Acr({queryOptions:e}={}){const t=Ke();return wn({mutationFn:({agentId:n,threadId:r})=>t.getAgent(n).closeBrowser(r),onError:n=>{console.error("[useCloseBrowser] Error closing browser:",n)},...e})}function Nk({queryOptions:e}={}){const t=Ke();return Ct({queryKey:["stored-skills"],queryFn:()=>t.listStoredSkills(),...e})}const n6=({queryOptions:e}={})=>{const t=Ke();return Ct({queryKey:["channels","platforms"],queryFn:()=>t.channels.listPlatforms(),staleTime:60*1e3,retry:!1,...e})},BOt=({platform:e,agentId:t,queryOptions:n})=>{const r=Ke();return Ct({queryKey:["channels","installations",e,t],queryFn:()=>r.channels.listInstallations(e,t),staleTime:10*1e3,retry:!1,...n})},Pcr=({platform:e,queryOptions:t})=>{const n=Ke(),r=mr();return wn({mutationFn:s=>n.channels.reconcileInstallation(e,s),onSuccess:()=>{r.invalidateQueries({queryKey:["channels","installations",e]})},...t})},$cr=({platform:e,queryOptions:t})=>{const n=Ke(),r=mr();return wn({mutationFn:({agentId:s,options:i})=>n.channels.connect(e,s,{...i,redirectUrl:window.location.href}),onSuccess:()=>{r.invalidateQueries({queryKey:["channels","installations",e]})},...t})},VOt=({platform:e,queryOptions:t})=>{const n=Ke(),r=mr();return wn({mutationFn:s=>n.channels.disconnect(e,s),onSuccess:()=>{r.invalidateQueries({queryKey:["channels","installations",e]})},...t})},Rcr=({queryOptions:e}={})=>{const t=Ke();return wn({mutationFn:async({agentId:n,toolId:r,input:s,playgroundRequestContext:i})=>{const o=new f_;return Object.entries(i??{}).forEach(([l,c])=>{o.set(l,c)}),t.getAgent(n).executeTool(r,{data:s,requestContext:o})},...e})};function Mcr({value:e,onValueChange:t,placeholder:n="Select an agent...",searchPlaceholder:r="Search agents...",emptyText:s="No agents found.",className:i,disabled:o=!1,variant:l,size:c,"aria-label":u,align:d}){const{data:f={},isLoading:h,isError:p,error:m}=Cp(),{navigate:v,paths:y}=Sn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load agents";Xe.error(`Error loading agents: ${S}`)}},[p,m]);const x=Object.keys(f).map(S=>({label:f[S]?.name||S,value:S})),b=S=>{t?t(S):S&&S!==e&&v(y.agentLink(S))};return a.jsx(fl,{options:x,value:e,onValueChange:b,placeholder:h?"Loading agents...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||h||p,variant:l,size:c,"aria-label":u,align:d})}function Dcr(){const{agentId:e}=Cr(),{data:t,isLoading:n}=Cp();return e?n?a.jsx(Fx,{}):t?.[e]?.name||e:null}function Lcr(){const{agentId:e}=Cr();return e?a.jsx(Mcr,{value:e,...MP,"aria-label":"Switch agent"}):null}const PK=e=>{const t=JSON.stringify(e);return g.useCallback(n=>{const r={};return JSON.parse(t).forEach((s,i)=>{r[s]=n[i]?.data}),{data:r,isLoading:n.some(s=>s.isLoading),error:n.find(s=>s.error)?.error??null}},[t])},UOt=({datasetId:e,itemId:t,queryOptions:n})=>{const r=Ke();return Ct({queryKey:["dataset-item",e,t],queryFn:()=>r.getDatasetItem(e,t),retry:!1,...n})},oUe=10,oA=({datasetId:e,search:t,version:n,orderBy:r,queryOptions:s})=>{const i=Ke(),{inView:o,setRef:l}=X0(),c=Mm({queryKey:["dataset-items",e,t,n,r],queryFn:async({pageParam:f})=>await i.listDatasetItems(e,{page:f,perPage:oUe,search:t||void 0,version:n||void 0,orderBy:r}),initialPageParam:0,getNextPageParam:(f,h,p)=>{if(f?.items?.length&&!((p+1)*oUe>=(f?.pagination?.total??0)))return p+1},retry:!1,...s}),u=c.data?.pages.flatMap(f=>f?.items??[])??[],d=c.data?.pages[0]?.pagination?.total;return g.useEffect(()=>{o&&c.hasNextPage&&!c.isFetchingNextPage&&c.fetchNextPage()},[o,c]),{...c,data:u,total:d,setEndOfListElement:l}},pl=({queryOptions:e}={})=>{const t=Ke(),n=mr(),r=wn({mutationFn:h=>t.createDataset(h),onSuccess:()=>{n.invalidateQueries({queryKey:["datasets"]})},...e?.createDataset}),s=wn({mutationFn:h=>t.updateDataset(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["datasets"]}),n.invalidateQueries({queryKey:["dataset",p.datasetId]})},...e?.updateDataset}),i=wn({mutationFn:h=>t.deleteDataset(h),onSuccess:()=>{n.invalidateQueries({queryKey:["datasets"]})},...e?.deleteDataset}),o=wn({mutationFn:h=>t.addDatasetItem(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["dataset-items",p.datasetId]}),n.invalidateQueries({queryKey:["dataset",p.datasetId]}),n.invalidateQueries({queryKey:["dataset-versions",p.datasetId]})},...e?.addItem}),l=wn({mutationFn:h=>t.updateDatasetItem(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["dataset-items",p.datasetId]}),n.invalidateQueries({queryKey:["dataset-item",p.datasetId,p.itemId]}),n.invalidateQueries({queryKey:["dataset-item-versions",p.datasetId,p.itemId]}),n.invalidateQueries({queryKey:["dataset-versions",p.datasetId]})},...e?.updateItem}),c=wn({mutationFn:({datasetId:h,itemId:p})=>t.deleteDatasetItem(h,p),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["dataset-items",p.datasetId]}),n.invalidateQueries({queryKey:["dataset",p.datasetId]}),n.invalidateQueries({queryKey:["dataset-versions",p.datasetId]})},...e?.deleteItem}),u=wn({mutationFn:({datasetId:h,itemId:p})=>t.purgeDatasetItem(h,p),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["dataset-items",p.datasetId]}),n.invalidateQueries({queryKey:["dataset-item",p.datasetId,p.itemId]}),n.invalidateQueries({queryKey:["dataset-item-versions",p.datasetId,p.itemId]}),n.invalidateQueries({queryKey:["dataset-experiment-results"]}),n.invalidateQueries({queryKey:["experiment-results"]}),n.invalidateQueries({queryKey:["review-items"]}),n.invalidateQueries({queryKey:["dataset-review-items"]}),n.invalidateQueries({queryKey:["dataset-completed-items"]}),n.invalidateQueries({queryKey:["experiment-review-summary"]})},...e?.purgeItem}),d=wn({mutationFn:h=>t.batchInsertDatasetItems(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["dataset-items",p.datasetId]}),n.invalidateQueries({queryKey:["dataset",p.datasetId]}),n.invalidateQueries({queryKey:["dataset-versions",p.datasetId]})},...e?.batchInsertItems}),f=wn({mutationFn:h=>t.batchDeleteDatasetItems(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["dataset-items",p.datasetId]}),n.invalidateQueries({queryKey:["dataset",p.datasetId]}),n.invalidateQueries({queryKey:["dataset-versions",p.datasetId]})},...e?.batchDeleteItems});return{createDataset:r,updateDataset:s,deleteDataset:i,addItem:o,updateItem:l,deleteItem:c,purgeItem:u,deleteItems:wn({mutationFn:async({datasetId:h,itemIds:p})=>t.batchDeleteDatasetItems({datasetId:h,itemIds:p}),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["dataset-items",p.datasetId]}),n.invalidateQueries({queryKey:["dataset",p.datasetId]}),n.invalidateQueries({queryKey:["dataset-versions",p.datasetId]})},...e?.deleteItems}),batchInsertItems:d,batchDeleteItems:f,triggerExperiment:wn({mutationFn:h=>t.triggerDatasetExperiment(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["dataset-experiments",p.datasetId]})},...e?.triggerExperiment}),deleteExperiment:wn({mutationFn:h=>t.deleteExperiment(h),onSuccess:()=>{n.invalidateQueries({queryKey:["experiments"]}),n.invalidateQueries({queryKey:["experiment"]}),n.invalidateQueries({queryKey:["dataset-experiments"]}),n.invalidateQueries({queryKey:["dataset-experiment"]}),n.invalidateQueries({queryKey:["dataset-experiment-results"]}),n.invalidateQueries({queryKey:["review-items"]}),n.invalidateQueries({queryKey:["completed-items"]}),n.invalidateQueries({queryKey:["experiment-review-summary"]})},...e?.deleteExperiment}),updateExperiment:wn({mutationFn:h=>t.updateDatasetExperiment(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["experiments"]}),n.invalidateQueries({queryKey:["experiment",p.experimentId]}),n.invalidateQueries({queryKey:["dataset-experiments",p.datasetId]}),n.invalidateQueries({queryKey:["dataset-experiment",p.datasetId,p.experimentId]})},...e?.updateExperiment}),updateExperimentResult:wn({mutationFn:h=>t.updateDatasetExperimentResult(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["experiment-results",p.experimentId]}),n.invalidateQueries({queryKey:["dataset-experiment-results"]}),n.invalidateQueries({queryKey:["review-items"]}),n.invalidateQueries({queryKey:["dataset-review-items"]}),n.invalidateQueries({queryKey:["dataset-completed-items"]}),n.invalidateQueries({queryKey:["experiment-review-summary"]})},...e?.updateExperimentResult})}},Ak=({pagination:e,queryOptions:t}={})=>{const n=Ke();return Ct({queryKey:["datasets",e],queryFn:()=>n.listDatasets(e),placeholderData:r=>r,...t})},zcr=20,Fcr=({filter:e,orderBy:t,queryOptions:n}={})=>{const r=Ke(),{inView:s,setRef:i}=X0(),o=e?.targetType||void 0,l=e?.targetId?[e.targetId]:void 0,c=Mm({queryKey:["datasets","infinite",{targetType:o,targetIds:l,orderBy:t}],queryFn:({pageParam:u})=>r.listDatasets({page:u,perPage:zcr,targetType:o,targetIds:l,orderBy:t}),initialPageParam:0,getNextPageParam:(u,d,f)=>{if(!(!u?.datasets?.length||!u.pagination?.hasMore))return f+1},select:u=>u.pages.flatMap(d=>d?.datasets??[]),...n});return g.useEffect(()=>{s&&c.hasNextPage&&!c.isFetchingNextPage&&c.fetchNextPage()},[s,c]),{...c,setEndOfListElement:i}},Vv=({datasetId:e,queryOptions:t})=>{const n=Ke();return Ct({queryKey:["dataset",e],queryFn:()=>n.getDataset(e),...t})},Bcr=({datasetId:e,experimentIds:t,baselineId:n,queryOptions:r})=>{const s=Ke();return Ct({queryKey:["compare-experiments",e,t,n],queryFn:()=>s.compareExperiments({datasetId:e,experimentIds:t,baselineId:n}),...r})},$K=2e3,tme=100,Vcr=100,RK=e=>e==="running"||e==="pending",qOt=(e,t,n)=>({queryKey:["dataset-experiment",t,n],queryFn:()=>e.getDatasetExperiment(t,n),gcTime:0,staleTime:0,refetchInterval:r=>RK(r.state.data?.status)?$K:!1}),QOt=(e,t,n)=>({queryKey:["dataset-experiment-scores",t,n],queryFn:async()=>{const r=[];let s=0;for(;;){const o=await e.listScoresByRunId({runId:t,page:s,perPage:Vcr});if(r.push(...o.scores),!o.pagination.hasMore)break;s++}const i={};for(const o of r)(i[o.entityId]??=[]).push(o);return i},refetchInterval:RK(n)?$K:!1}),Ucr=(e,t,n,r)=>({queryKey:["dataset-experiment-results-all",t,n,r],queryFn:async()=>{const s=[];let i=0;for(;;){const o=await e.listDatasetExperimentResults(t,n,{page:i,perPage:tme});if(s.push(...o.results),!o.pagination.hasMore||o.results.length===0)break;i++}return s},refetchInterval:RK(r)?$K:!1}),ZOt=({datasetId:e,experimentId:t,queryOptions:n})=>{const r=Ke(),{queryKey:s,queryFn:i,gcTime:o,staleTime:l,refetchInterval:c}=qOt(r,e,t);return Ct({queryKey:s,queryFn:i,gcTime:o,staleTime:l,refetchInterval:c,...n})},Vke=({datasetId:e,experimentIds:t})=>{const n=Ke(),r=PK(t);return Rm({queries:t.map(s=>qOt(n,e,s)),combine:r})},qcr=({datasetId:e,experimentId:t,experimentStatus:n,orderBy:r,queryOptions:s})=>{const i=Ke(),{inView:o,setRef:l}=X0(),c=Mm({queryKey:["dataset-experiment-results",e,t,n,r],queryFn:async({pageParam:u})=>i.listDatasetExperimentResults(e,t,{page:u,perPage:tme,orderBy:r}),initialPageParam:0,getNextPageParam:(u,d,f)=>{if(u?.results?.length&&!((f+1)*tme>=(u?.pagination?.total??0)))return f+1},refetchInterval:RK(n)?$K:!1,select:u=>u.pages.flatMap(d=>d?.results??[]),...s});return g.useEffect(()=>{o&&c.hasNextPage&&!c.isFetchingNextPage&&c.fetchNextPage()},[o,c]),{...c,setEndOfListElement:l}},Qcr=({datasetId:e,experiments:t})=>{const n=Ke(),r=PK(t.map(s=>s.id));return Rm({queries:t.map(s=>Ucr(n,e,s.id,s.status)),combine:r})},r6=({experimentId:e,experimentStatus:t,queryOptions:n})=>{const r=Ke(),{queryKey:s,queryFn:i,refetchInterval:o}=QOt(r,e,t);return Ct({queryKey:s,queryFn:i,refetchInterval:o,...n})},Zcr=({experiments:e})=>{const t=Ke(),n=PK(e.map(r=>r.id));return Rm({queries:e.map(r=>QOt(t,r.id,r.status)),combine:n})},Wcr=({datasetId:e,itemId:t,queryOptions:n})=>{const r=Ke();return Ct({queryKey:["dataset-item-versions",e,t],queryFn:async()=>((await r.getItemHistory(e,t))?.history??[]).map((s,i)=>({id:s.id,datasetId:s.datasetId,datasetVersion:s.datasetVersion,input:s.input,groundTruth:s.groundTruth,expectedTrajectory:s.expectedTrajectory,toolMocks:s.toolMocks??void 0,scorerIds:s.scorerIds??void 0,requestContext:s.requestContext??void 0,metadata:s.metadata??void 0,validTo:s.validTo,isDeleted:s.isDeleted,createdAt:s.createdAt,updatedAt:s.updatedAt,isLatest:i===0})),...n})},Hcr=({datasetId:e,itemId:t,datasetVersion:n,latestVersion:r,queryOptions:s})=>{const i=Ke();return Ct({queryKey:["dataset-item-version",e,t,n],queryFn:async()=>{const o=await i.getDatasetItemVersion(e,t,n);return{id:o.id,datasetId:o.datasetId,datasetVersion:o.datasetVersion,input:o.input,groundTruth:o.groundTruth,expectedTrajectory:o.expectedTrajectory,toolMocks:o.toolMocks??void 0,scorerIds:o.scorerIds??void 0,requestContext:o.requestContext??void 0,metadata:o.metadata??void 0,validTo:null,isDeleted:!1,createdAt:o.createdAt,updatedAt:o.updatedAt,isLatest:r!=null?n===r:!1}},...s})},Gcr=10,WOt=({datasetId:e,queryOptions:t})=>{const n=Ke();return Mm({queryKey:["dataset-versions",e],queryFn:async({pageParam:r})=>n.listDatasetVersions(e,{page:r,perPage:Gcr}),initialPageParam:0,getNextPageParam:(r,s,i)=>{if(r?.pagination?.hasMore)return i+1},select:r=>r.pages.flatMap(s=>s?.versions??[]).map((s,i)=>({id:s.id,datasetId:s.datasetId,version:s.version,createdAt:s.createdAt,isCurrent:i===0})),...t})},Kcr=({pagination:e,queryOptions:t}={})=>{const n=Ke();return Ct({queryKey:["experiments",e],queryFn:()=>n.listExperiments(e),...t})},HOt=({experimentId:e,queryOptions:t})=>{const n=Ke();return Ct({queryKey:["experiment",e],queryFn:()=>n.getExperiment(e),...t})};function Ycr({workflowId:e,queryOptions:t}){const n=Ke();return Ct({queryKey:["workflow-schema",e],queryFn:async()=>{if(!e)throw new Error("No workflow selected");return n.getWorkflow(e).getSchema()},staleTime:300*1e3,...t})}function GOt({value:e,onValueChange:t,placeholder:n="Select a dataset...",searchPlaceholder:r="Search datasets...",emptyText:s="No datasets found.",className:i,disabled:o=!1,variant:l,size:c,"aria-label":u,align:d,container:f}){const{data:h,isLoading:p,isError:m,error:v}=Ak(),{navigate:y,paths:x}=Sn();g.useEffect(()=>{if(m){const j=v instanceof Error?v.message:"Failed to load datasets";Xe.error(`Error loading datasets: ${j}`)}},[m,v]);const S=(h?.datasets??[]).map(j=>({label:j.name,value:j.id})),k=j=>{t?t(j):j&&j!==e&&y(x.datasetLink(j))};return a.jsx(fl,{options:S,value:e,onValueChange:k,placeholder:p?"Loading datasets...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||p||m,variant:l,size:c,"aria-label":u,align:d,container:f})}function Xcr(){const{datasetId:e}=Cr(),{data:t,isLoading:n}=Ak();return e?n?a.jsx(Fx,{}):t?.datasets?.find(r=>r.id===e)?.name??e:null}function Jcr(){const{datasetId:e}=Cr();return e?a.jsx(GOt,{value:e,...MP,"aria-label":"Switch dataset"}):null}const eur=({serverId:e,appResourceUri:t,queryOptions:n})=>{const r=Ke();return Ct({queryKey:["mcp-app-resource",e,t],queryFn:async()=>t?(await r.readMcpServerResource(e,t)).contents[0]?.text??null:null,enabled:t!==void 0,...n})};function KOt({queryOptions:e}={}){const t=Ke();return Ct({queryKey:["mcp-app-tools"],queryFn:async()=>{const n={},{servers:r}=await t.getMcpServers();if(!r?.length)return n;const s=await Promise.allSettled(r.map(async i=>{const{tools:o}=await t.getMcpServerTools(i.id);return{serverId:i.id,tools:o}}));for(const i of s){if(i.status!=="fulfilled")continue;const{serverId:o,tools:l}=i.value;for(const c of l){const u=c._meta?.ui?.resourceUri;if(u){const d=c.name,f={serverId:o,toolId:d,toolName:c.name,resourceUri:u};n[d]=f,c.name!==d&&(n[c.name]=f),n[`${o}_${c.name}`]=f}}}return n},staleTime:6e4,refetchOnWindowFocus:!1,...e})}const tur=({serverId:e,toolId:t,requestContext:n,queryOptions:r})=>{const s=Ke();return Ct({queryKey:["mcp-server-tool",e,t],queryFn:()=>s.getMcpServerTool(e,t).details(n),...r})},nur=({serverId:e,toolId:t,queryOptions:n})=>{const r=Ke();return wn({mutationFn:({data:s,requestContext:i})=>r.getMcpServerTool(e,t).execute({data:s,requestContext:i}),...n})},YOt=({selectedServer:e,queryOptions:t})=>{const n=Ke();return Ct({queryKey:["mcpserver-tools",e?.id],queryFn:async()=>{const r=(await n.getMcpServerTools(e?.id)).tools,s={};return r.forEach(i=>{s[i.name]=i}),s},retry:!1,refetchOnWindowFocus:!1,...t})},LP=({requestContext:e,queryOptions:t}={})=>{const n=Ke();return Ct({queryKey:["mcp-servers"],queryFn:async()=>(await n.getMcpServers(e)).servers,...t})};async function aUe(e){if((e.headers.get("content-type")??"").includes("text/event-stream")){const t=(await e.text()).split(`
257
- `);for(const n of t)if(n.startsWith("data:")){const r=n.slice(5).trim();if(r)return JSON.parse(r)}throw new Error("No data found in SSE response")}return e.json()}async function rur(e,t){const n={...t,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},r=await fetch(e,{method:"POST",headers:n,credentials:"include",body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"mastra-playground",version:"1.0.0"}}})});if(!r.ok)throw new Error(`Initialize failed: ${r.status} ${r.statusText}`);const s=r.headers.get("Mcp-Session-Id");await aUe(r);const i={...n};s&&(i["Mcp-Session-Id"]=s),await fetch(e,{method:"POST",headers:i,credentials:"include",body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})});const o=await fetch(e,{method:"POST",headers:i,credentials:"include",body:JSON.stringify({jsonrpc:"2.0",id:2,method:"tools/list"})});if(!o.ok)throw new Error(`tools/list failed: ${o.status} ${o.statusText}`);return{tools:(await aUe(o)).result?.tools??[]}}const sur=({queryOptions:e}={})=>{const t=Ke().options?.headers??{};return wn({mutationFn:n=>rur(n,t),...e})};function XOt({value:e,onValueChange:t,placeholder:n="Select an MCP server...",searchPlaceholder:r="Search MCP servers...",emptyText:s="No MCP servers found.",className:i,disabled:o=!1,variant:l,size:c,"aria-label":u,align:d,container:f}){const{data:h=[],isLoading:p,isError:m,error:v}=LP(),{navigate:y,paths:x}=Sn();g.useEffect(()=>{if(m){const k=v instanceof Error?v.message:"Failed to load MCP servers";Xe.error(`Error loading MCP servers: ${k}`)}},[m,v]);const b=h.map(k=>({label:k.name,value:k.id})),S=k=>{t?t(k):k&&k!==e&&y(x.mcpServerLink(k))};return a.jsx(fl,{options:b,value:e,onValueChange:S,placeholder:p?"Loading MCP servers...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||p||m,variant:l,size:c,"aria-label":u,align:d,container:f})}function iur(){const{serverId:e}=Cr(),{data:t,isLoading:n}=LP();return e?n?a.jsx(Fx,{}):t?.find(r=>r.id===e)?.name||e:null}function our(){const{serverId:e}=Cr();return e?a.jsx(XOt,{value:e,...MP,"aria-label":"Switch MCP server"}):null}const zP=({requestContext:e,queryOptions:t}={})=>{const n=Ke();return Ct({queryKey:["processors"],queryFn:()=>n.listProcessors(e),...t})},JOt=({processorId:e,requestContext:t,queryOptions:n})=>{const r=Ke();return Ct({queryKey:["processor",e],queryFn:()=>r.getProcessor(e).details(t),...n})},aur=({requestContext:e,queryOptions:t}={})=>{const n=Ke();return wn({mutationFn:async({processorId:r,phase:s,messages:i,agentId:o})=>n.getProcessor(r).execute({phase:s,messages:i,agentId:o,requestContext:e}),...t})};function lur({value:e,onValueChange:t,placeholder:n="Select a processor...",searchPlaceholder:r="Search processors...",emptyText:s="No processors found.",className:i,disabled:o=!1,variant:l,size:c,"aria-label":u,align:d}){const{data:f={},isLoading:h,isError:p,error:m}=zP(),{navigate:v,paths:y}=Sn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load processors";Xe.error(`Error loading processors: ${S}`)}},[p,m]);const x=Object.keys(f).filter(S=>{const k=f[S];return k?.phases&&k.phases.length>0}).map(S=>({label:f[S]?.name||S,value:S})),b=S=>{t?t(S):S&&S!==e&&(f[S]?.isWorkflow?v(y.workflowLink(S)+"/graph"):v(y.processorLink(S)))};return a.jsx(fl,{options:x,value:e,onValueChange:b,placeholder:h?"Loading processors...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||h||p,variant:l,size:c,"aria-label":u,align:d})}function cur(){const{processorId:e}=Cr(),{data:t,isLoading:n}=zP();return e?n?a.jsx(Fx,{}):t?.[e]?.name||e:null}function uur(){const{processorId:e}=Cr();return e?a.jsx(lur,{value:e,...MP,"aria-label":"Switch processor"}):null}const Goe=[400,401,403,404,501];function Cs(e){if(!e||typeof e!="object")return!1;if("status"in e&&e.status===401||"statusCode"in e&&e.statusCode===401)return!0;if("message"in e){const t=e.message;if(typeof t=="string")return/\bstatus:\s*401\b/.test(t)}return!1}function _s(e){if(!e||typeof e!="object")return!1;if("status"in e&&e.status===403||"statusCode"in e&&e.statusCode===403)return!0;if("message"in e){const t=e.message;if(typeof t=="string")return/\bstatus:\s*403\b/.test(t)}return!1}function Pk(e){if(!e||typeof e!="object")return!1;if("status"in e&&e.status===404||"statusCode"in e&&e.statusCode===404)return!0;if("message"in e){const t=e.message;if(typeof t=="string")return/\bstatus:\s*404\b/.test(t)}return!1}function s6(e,t){if(!e||typeof e!="object"||!("message"in e))return!1;const n=e.message;return typeof n!="string"?!1:n.includes(`does not support listing ${t}`)}const dur=["Observability storage domain is not available","Scores storage domain is not available"];function i6(e){if(!e||typeof e!="object"||!("message"in e))return!1;const t=e.message;return typeof t!="string"?!1:dur.some(n=>t.includes(n))}function ejt(e){if(!e||typeof e!="object")return!1;if("status"in e){const t=e.status;return Goe.includes(t)}if("statusCode"in e){const t=e.statusCode;return Goe.includes(t)}if("message"in e){const t=e.message;if(typeof t=="string")return Goe.some(n=>new RegExp(`\\bstatus:\\s*${n}\\b`).test(t))}return!1}function fur(e,t){return ejt(t)?!1:e<3}const hur=25,pur=15e3;function mur(e){return s6(e.state.error,"scores")||i6(e.state.error)?!1:pur}function gur(e,t,n){if(e?.pagination?.hasMore)return n+1}function vur(e){const t=new Set;return e.pages.flatMap(n=>n.scores??[]).filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const yur=({scorerId:e,entityId:t,entityType:n,queryOptions:r})=>{const s=Ke(),{inView:i,setRef:o}=X0(),l=Mm({queryKey:["scores",e,t,n],queryFn:({pageParam:f})=>s.listScoresByScorerId({scorerId:e,page:f,perPage:hur,entityId:t,entityType:n}),initialPageParam:0,getNextPageParam:gur,select:f=>vur(f),refetchInterval:mur,...r}),{hasNextPage:c,isFetchingNextPage:u,fetchNextPage:d}=l;return g.useEffect(()=>{i&&c&&!u&&d()},[i,c,u,d]),{...l,setEndOfListElement:o}},xur=e=>{const t=Ke(),[n,r]=g.useState(null),[s,i]=g.useState(!0),[o,l]=g.useState(null);return g.useEffect(()=>{(async()=>{i(!0),l(null);try{const u=await t.getScorer(e);r(u)}catch(u){r(null);const d=u instanceof Error?u:new Error("Error fetching scorer");l(d),console.error("Error fetching scorer",u)}finally{i(!1)}})()},[e,t]),{scorer:n,isLoading:s,error:o}},tjt=({requestContext:e,queryOptions:t}={})=>{const n=Ke();return Ct({queryKey:["scorers",e],queryFn:()=>n.listScorers(e),staleTime:0,gcTime:0,...t})},bur=15e3;function wur(e){return s6(e.state.error,"scores")||i6(e.state.error)?!1:bur}const Uke=({traceId:e="",spanId:t="",page:n,queryOptions:r})=>{const s=Ke();return Ct({queryKey:["trace-span-scores",e,t,n],queryFn:()=>s.listScoresBySpan({traceId:e,spanId:t,page:n||0,perPage:10}),refetchInterval:wur,gcTime:0,staleTime:0,...r})},Sur=({queryOptions:e}={})=>{const t=Ke();return wn({mutationFn:async({scorerName:n,traceId:r,spanId:s})=>await t.score({scorerName:n,targets:[{traceId:r,spanId:s}]}),...e})},njt=({scorerId:e,status:t,requestContext:n,queryOptions:r}={})=>{const s=Ke();return Ct({queryKey:["stored-scorer",e,t,n],queryFn:()=>e?s.getStoredScorer(e).details(n,{status:t}):null,...r})},rjt=({scorerId:e,requestContext:t,queryOptions:n}={})=>{const r=Ke(),s=mr();return{createStoredScorer:wn({mutationFn:i=>r.createStoredScorer(i),onSuccess:()=>{s.invalidateQueries({queryKey:["stored-scorers"]}),s.invalidateQueries({queryKey:["scorers"]})},...n?.createStoredScorer}),updateStoredScorer:wn({mutationFn:i=>{if(!e)throw new Error("scorerId is required for update");return r.getStoredScorer(e).update(i,t)},onSuccess:()=>{s.invalidateQueries({queryKey:["stored-scorers"]}),s.invalidateQueries({queryKey:["scorers"]}),e&&s.invalidateQueries({queryKey:["stored-scorer",e]})},...n?.updateStoredScorer}),deleteStoredScorer:wn({mutationFn:()=>{if(!e)throw new Error("scorerId is required for delete");return r.getStoredScorer(e).delete(t)},onSuccess:()=>{s.invalidateQueries({queryKey:["stored-scorers"]}),s.invalidateQueries({queryKey:["scorers"]}),e&&s.invalidateQueries({queryKey:["stored-scorer",e]})},...n?.deleteStoredScorer})}},sjt=({scorerId:e,params:t,requestContext:n,queryOptions:r})=>{const s=Ke();return Ct({queryKey:["scorer-versions",e,t,n],queryFn:()=>s.getStoredScorer(e).listVersions(t,n),...r})},kur=({scorerId:e,versionId:t,requestContext:n,queryOptions:r})=>{const s=Ke();return Ct({queryKey:["scorer-version",e,t,n],queryFn:()=>s.getStoredScorer(e).getVersion(t,n),...r})},Bx=(e,t)=>tjt({...e,requestContext:t});function Our({value:e,onValueChange:t,placeholder:n="Select a scorer...",searchPlaceholder:r="Search scorers...",emptyText:s="No scorers found.",className:i,disabled:o=!1,variant:l,size:c,"aria-label":u,align:d}){const{data:f={},isLoading:h,isError:p,error:m}=Bx(),{navigate:v,paths:y}=Sn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load scorers";Xe.error(`Error loading scorers: ${S}`)}},[p,m]);const x=Object.keys(f).map(S=>({label:f[S]?.scorer.config.name||S,value:S})),b=S=>{t?t(S):S&&S!==e&&v(y.scorerLink(S))};return a.jsx(fl,{options:x,value:e,onValueChange:b,placeholder:h?"Loading scorers...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||h||p,variant:l,size:c,"aria-label":u,align:d})}function jur(){const{scorerId:e}=Cr(),{data:t,isLoading:n}=Bx();return e?n?a.jsx(Fx,{}):t?.[e]?.scorer.config.name||e:null}function Cur(){const{scorerId:e}=Cr();return e?a.jsx(Our,{value:e,...MP,"aria-label":"Switch scorer"}):null}function _ur(){const{scorerId:e}=Cr(),{data:t,isLoading:n}=njt({scorerId:e,status:"draft",queryOptions:{enabled:!!e}});return e?n?a.jsx(Fx,{}):t?.name??"Scorer not found":null}const Vo=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 8.82265 8.51434",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M6.76646 6.16953C6.56909 6.10559 6.40521 5.96585 6.31087 5.78107C6.21653 5.5963 6.19945 5.38161 6.2634 5.18424C6.32735 4.98687 6.46708 4.82299 6.65186 4.72865C6.83663 4.63431 7.05132 4.61723 7.24869 4.68118C7.45933 4.74996 7.6849 4.75913 7.90043 4.70768C8.11596 4.65622 8.31306 4.54615 8.46992 4.38963C8.62678 4.23312 8.73729 4.03626 8.78921 3.82084C8.84114 3.60542 8.83246 3.37984 8.76414 3.16904C8.69582 2.95825 8.57052 2.77046 8.4021 2.62646C8.23368 2.48246 8.02871 2.38785 7.80986 2.35311C7.59101 2.31836 7.36681 2.34484 7.16208 2.4296C6.95734 2.51436 6.78004 2.6541 6.64979 2.83337C6.39274 3.18567 6.05613 3.47228 5.66736 3.66987C5.27858 3.86747 4.84864 3.97046 4.41254 3.97046C3.97643 3.97046 3.54649 3.86747 3.15772 3.66987C2.76895 3.47228 2.43234 3.18567 2.17528 2.83337C2.04528 2.65368 1.86807 2.51346 1.66329 2.42826C1.45852 2.34306 1.23415 2.3162 1.01505 2.35065C0.795944 2.3851 0.590648 2.47951 0.421892 2.62344C0.253137 2.76736 0.127507 2.95519 0.0589124 3.16611C-0.00968171 3.37703 -0.0185632 3.60282 0.0332514 3.81848C0.0850661 4.03414 0.195555 4.23125 0.352484 4.38799C0.509413 4.54472 0.706659 4.65497 0.92238 4.70652C1.1381 4.75808 1.36388 4.74892 1.57472 4.68007C1.77224 4.61634 1.98698 4.63369 2.1717 4.72829C2.35643 4.82289 2.49601 4.987 2.55973 5.18452C2.62346 5.38203 2.60611 5.59677 2.51151 5.7815C2.41691 5.96623 2.2528 6.10581 2.05528 6.16953C1.84456 6.23788 1.65684 6.36317 1.51288 6.53155C1.36893 6.69993 1.27434 6.90485 1.23959 7.12364C1.20483 7.34242 1.23126 7.56656 1.31596 7.77126C1.40065 7.97597 1.5403 8.15326 1.71948 8.28354C1.89865 8.41382 2.11036 8.49201 2.33121 8.50946C2.55205 8.52692 2.77342 8.48296 2.97083 8.38244C3.16825 8.28193 3.33402 8.12877 3.44981 7.93992C3.56561 7.75106 3.62692 7.53386 3.62697 7.31233C3.62697 7.10501 3.70933 6.90619 3.85592 6.7596C4.00251 6.613 4.20134 6.53065 4.40865 6.53065C4.61596 6.53065 4.81479 6.613 4.96138 6.7596C5.10797 6.90619 5.19033 7.10501 5.19033 7.31233C5.19027 7.53399 5.25152 7.75136 5.36731 7.94037C5.4831 8.12939 5.64892 8.2827 5.84642 8.38334C6.04392 8.48399 6.26541 8.52804 6.4864 8.51063C6.70738 8.49322 6.91924 8.41502 7.09854 8.28469C7.27785 8.15436 7.41761 7.97698 7.50237 7.77216C7.58713 7.56734 7.61359 7.34307 7.57882 7.12414C7.54404 6.90522 7.44939 6.70018 7.30534 6.53171C7.16128 6.36323 6.97344 6.23789 6.76257 6.16953H6.76646Z",fill:"currentColor"}),a.jsx("path",{d:"M4.41198 2.40337C5.07565 2.40337 5.61367 1.86536 5.61367 1.20168C5.61367 0.538012 5.07565 0 4.41198 0C3.74831 0 3.2103 0.538012 3.2103 1.20168C3.2103 1.86536 3.74831 2.40337 4.41198 2.40337Z",fill:"currentColor"})]}),ijt=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 8.64637 9.45103",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{d:"M7.80735 5.87241C7.63209 5.97219 7.43696 6.06166 7.22844 6.13866C6.46456 6.42068 5.43714 6.58649 4.32296 6.58649C3.20873 6.58649 2.18135 6.4207 1.41747 6.13866C1.20889 6.06164 1.01385 5.97223 0.838558 5.87241V7.59003C0.838558 7.62341 0.855765 7.70759 1.00172 7.83512C1.14707 7.96201 1.38219 8.09563 1.70829 8.21605C2.3572 8.45563 3.28149 8.61268 4.32296 8.61269C5.36456 8.61269 6.28937 8.45568 6.9383 8.21605C7.26428 8.09566 7.49888 7.96198 7.64419 7.83512C7.79024 7.70754 7.80735 7.62342 7.80735 7.59003V5.87241ZM7.80735 3.00789C7.63214 3.10763 7.4369 3.19647 7.22844 3.27345C6.46455 3.55549 5.43719 3.72129 4.32296 3.72129C3.20868 3.72128 2.18136 3.55552 1.41747 3.27345C1.20896 3.19645 1.01381 3.10766 0.838558 3.00789V4.72551C0.838558 4.7589 0.855657 4.84301 1.00172 4.97059C1.14707 5.09749 1.38219 5.23111 1.70829 5.35153C2.3572 5.59109 3.28154 5.74747 4.32296 5.74748C5.36456 5.74748 6.28937 5.59116 6.9383 5.35153C7.26432 5.23112 7.49887 5.09747 7.64419 4.97059C7.7536 4.87505 7.79089 4.80404 7.80257 4.76033L7.80735 4.72551V3.00789ZM7.80735 1.86099C7.80735 1.82758 7.79045 1.74291 7.64419 1.61522C7.49887 1.48838 7.26421 1.35534 6.9383 1.23497C6.28937 0.995339 5.36456 0.838331 4.32296 0.838331C3.28149 0.83834 2.3572 0.995383 1.70829 1.23497C1.38219 1.35539 1.14707 1.48832 1.00172 1.61522C0.855475 1.7429 0.838558 1.82758 0.838558 1.86099C0.838673 1.89462 0.855968 1.97882 1.00172 2.10607C1.14707 2.23297 1.38219 2.3659 1.70829 2.48632C2.3572 2.7259 3.28149 2.88295 4.32296 2.88296C5.36456 2.88296 6.28937 2.72595 6.9383 2.48632C7.26421 2.36595 7.49887 2.23291 7.64419 2.10607C7.78996 1.97881 7.80724 1.89462 7.80735 1.86099ZM8.64637 7.59003C8.64637 7.95465 8.44458 8.25006 8.1958 8.46728C7.94608 8.68529 7.60876 8.86274 7.22844 9.00318C6.46455 9.28522 5.43718 9.45102 4.32296 9.45102C3.20869 9.45101 2.18135 9.28525 1.41747 9.00318C1.03715 8.86274 0.699831 8.68529 0.450113 8.46728C0.201377 8.25007 0.000227451 7.9546 0.000227451 7.59003V1.86099C0.000227451 1.49643 0.201388 1.20095 0.450113 0.983742C0.699831 0.765728 1.03715 0.588275 1.41747 0.447838C2.18136 0.165769 3.20868 8.74396e-06 4.32296 0C5.43719 0 6.46455 0.165797 7.22844 0.447838C7.60876 0.588275 7.94608 0.765728 8.1958 0.983742C8.44457 1.20096 8.64637 1.49638 8.64637 1.86099V7.59003Z",fill:"currentColor"})}),Tur=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 9.83952 9.3295",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.67171 0.838331H6.70163V4.05307L9.68767 8.09999C10.0634 8.6093 9.69869 9.32932 9.06643 9.3295H0.772551C0.140289 9.3293 -0.223777 8.60929 0.151995 8.09999L3.13804 4.05307V0.838331H2.17136V0H7.67171V0.838331ZM3.97705 4.32955L3.89513 4.44015L2.34681 6.53802H7.49285L5.94453 4.44015L5.86261 4.32955V0.860859H3.97705V4.32955Z",fill:"currentColor"})}),Iur=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 10.0412 8.39395",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M0 0.916539C0 0.410349 0.410349 0 0.916539 0C1.42273 0 1.83308 0.410349 1.83308 0.916539C1.83308 1.42273 1.42273 1.83308 0.916539 1.83308C0.410349 1.83308 0 1.42273 0 0.916539Z",fill:"currentColor"}),a.jsx("path",{d:"M2.88569 0.916539C2.88569 0.410349 3.29604 0 3.80223 0C4.30842 0 4.71877 0.410349 4.71877 0.916539C4.71877 1.42273 4.30842 1.83308 3.80223 1.83308C3.29604 1.83308 2.88569 1.42273 2.88569 0.916539Z",fill:"currentColor"}),a.jsx("path",{d:"M5.77139 0.916539C5.77139 0.410349 6.18174 0 6.68793 0H9.12465C9.63084 0 10.0412 0.410349 10.0412 0.916539C10.0412 1.42273 9.63084 1.83308 9.12465 1.83308H6.68793C6.18174 1.83308 5.77139 1.42273 5.77139 0.916539Z",fill:"currentColor"}),a.jsx("path",{d:"M0 4.19696C0 3.69077 0.410351 3.28042 0.916541 3.28042C1.42273 3.28042 1.83308 3.69077 1.83308 4.19696C1.83308 4.70315 1.42273 5.1135 0.916541 5.1135C0.410351 5.1135 0 4.70315 0 4.19696Z",fill:"currentColor"}),a.jsx("path",{d:"M2.8857 4.19694C2.8857 3.69075 3.29605 3.2804 3.80224 3.2804C4.30843 3.2804 4.71877 3.69075 4.71877 4.19694C4.71877 4.70313 4.30843 5.11348 3.80224 5.11348C3.29605 5.11348 2.8857 4.70313 2.8857 4.19694Z",fill:"currentColor"}),a.jsx("path",{d:"M5.77139 4.19694C5.77139 3.69075 6.18174 3.2804 6.68793 3.2804H9.12466C9.63085 3.2804 10.0412 3.69075 10.0412 4.19694C10.0412 4.70313 9.63085 5.11348 9.12466 5.11348H6.68793C6.18174 5.11348 5.77139 4.70313 5.77139 4.19694Z",fill:"currentColor"}),a.jsx("path",{d:"M0 7.47738C0 6.97119 0.410351 6.56084 0.916541 6.56084C1.42273 6.56084 1.83308 6.97119 1.83308 7.47738C1.83308 7.98357 1.42273 8.39392 0.916541 8.39392C0.410351 8.39392 0 7.98357 0 7.47738Z",fill:"currentColor"}),a.jsx("path",{d:"M2.8857 7.47741C2.8857 6.97122 3.29605 6.56087 3.80224 6.56087C4.30843 6.56087 4.71877 6.97122 4.71877 7.47741C4.71877 7.9836 4.30843 8.39395 3.80224 8.39395C3.29605 8.39395 2.8857 7.9836 2.8857 7.47741Z",fill:"currentColor"}),a.jsx("path",{d:"M5.77139 7.47741C5.77139 6.97122 6.18174 6.56087 6.68793 6.56087H9.12466C9.63085 6.56087 10.0412 6.97122 10.0412 7.47741C10.0412 7.9836 9.63085 8.39395 9.12466 8.39395H6.68793C6.18174 8.39395 5.77139 7.9836 5.77139 7.47741Z",fill:"currentColor"})]}),F_=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 9.52233 10.4982",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M2.39065 4.27882L4.93898 1.73049C5.10578 1.56368 5.37622 1.56368 5.54303 1.73049C5.70983 1.89729 5.70983 2.16773 5.54303 2.33454L2.9947 4.88287C2.53924 5.33834 2.53929 6.0768 2.99475 6.53226C3.45022 6.9877 4.18863 6.98771 4.64409 6.53226L7.19242 3.98393C7.35922 3.81713 7.62967 3.81714 7.79647 3.98393C7.96328 4.15074 7.96328 4.42118 7.79647 4.58798L5.24814 7.13631C4.45907 7.92537 3.17978 7.92536 2.39071 7.13631C1.60163 6.34724 1.60158 5.0679 2.39065 4.27882Z",fill:"currentColor"}),a.jsx("path",{d:"M3.50354 5.43862C3.5236 5.3983 3.55044 5.36049 3.58404 5.32688L6.06565 2.84527C6.52112 2.3898 6.52112 1.65128 6.06565 1.19581C5.61018 0.740366 4.87172 0.740412 4.41626 1.19587L0.729138 4.88287C0.562334 5.04967 0.291892 5.04968 0.125089 4.88287C-0.0416875 4.71607 -0.0417052 4.44562 0.125089 4.27882L3.81221 0.591824C4.60128 -0.197241 5.88062 -0.197289 6.6697 0.591765C7.12856 1.05062 7.32058 1.67529 7.24578 2.27292C7.84449 2.19687 8.47073 2.38872 8.93052 2.84849C9.7196 3.63757 9.7196 4.91697 8.93052 5.70605L8.20316 6.44191L6.20449 8.44058C5.83765 8.80741 5.83765 9.40219 6.20449 9.76902C6.37128 9.93582 6.37129 10.2063 6.20449 10.3731C6.03769 10.5399 5.76724 10.5399 5.60044 10.3731C4.9 9.67263 4.9 8.53697 5.60044 7.83653L7.59911 5.83786L8.32647 5.102C8.78194 4.64653 8.78194 3.90801 8.32647 3.45254C7.871 2.9971 7.13254 2.99714 6.67707 3.4526L4.17576 5.95392C4.00896 6.12072 3.73851 6.12071 3.57171 5.95392C3.43204 5.81425 3.40932 5.60193 3.50354 5.43862Z",fill:"currentColor"})]}),Eur=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 8.98824 8.33142",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M5.70011e-05 6.409V0H1.04865V6.409C1.04875 6.89152 1.43994 7.28283 1.92248 7.28283H8.3581V8.33142H1.92248C0.860814 8.33142 0.000149953 7.47065 5.70011e-05 6.409Z",fill:"currentColor"}),a.jsx("path",{d:"M8.08006 0.945713C8.27714 0.733828 8.6087 0.72151 8.82077 0.918405C9.03289 1.11551 9.04518 1.44767 8.84808 1.6598L6.08595 4.63218C5.90127 4.83085 5.59525 4.85557 5.38074 4.68953L4.03177 3.64571L2.74765 5.07183C2.55386 5.28688 2.22206 5.30441 2.00694 5.11074C1.79189 4.91695 1.77435 4.58515 1.96803 4.37003L3.57915 2.58278L3.65357 2.51451C3.83887 2.37494 4.09997 2.37165 4.28982 2.51861L5.64358 3.56652L8.08006 0.945713Z",fill:"currentColor"})]});function aj(e){return a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 10.123 10.123",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M4.50195 1.53809H5.62109V0H6.75098V1.53809H7.5293L7.64258 1.54395C8.19939 1.60066 8.63379 2.0708 8.63379 2.64258V3.37305H10.123V4.50195H8.63379V5.62109H10.123V6.75H8.63379V7.57812L8.62891 7.69141C8.57589 8.2109 8.16211 8.62387 7.64258 8.67676L7.5293 8.68262H6.75098V10.123H5.62109V8.68262H4.50195V10.123H3.37305V8.68262H2.59375L2.48047 8.67676C1.96102 8.62383 1.54817 8.21082 1.49512 7.69141L1.48926 7.57812V6.75H0V5.62109H1.48926V4.50195H0V3.37305H1.48926V2.64258C1.48926 2.07084 1.92371 1.60071 2.48047 1.54395L2.59375 1.53809H3.37305V0H4.50195V1.53809ZM2.61914 7.55273H7.50488V2.66699H2.61914V7.55273Z",fill:"currentColor"})})}const Nur=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 11.185 11.185",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M9.57258 2.71626C9.57245 2.19794 9.14778 1.77075 8.61819 1.77075H2.56605C2.0377 1.77075 1.61179 2.19752 1.61165 2.71626V6.51162C1.61179 7.02856 2.03401 7.45487 2.5616 7.45713L3.12802 7.45935V9.21487L5.52178 7.55857L5.66764 7.45713H8.61819C9.14653 7.45713 9.57245 7.03036 9.57258 6.51162V2.71626ZM10.7099 6.51162C10.7097 7.66541 9.76766 8.59441 8.61819 8.59441H6.0223L3.51081 10.3336C3.25841 10.5083 2.86505 10.6555 2.4809 10.4558C2.09483 10.2551 1.99075 9.84577 1.99075 9.53473V8.51222C1.11705 8.26321 0.474488 7.46395 0.474378 6.51162V2.71626C0.474511 1.56248 1.41657 0.633479 2.56605 0.633479H8.61819C9.77051 0.633479 10.7097 1.56448 10.7099 2.71626V6.51162Z",fill:"currentColor"})}),rw=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 8.94379 8.92126",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M6.13251 5.43413C6.51629 5.43413 6.82744 5.74533 6.82748 6.1291C6.82748 6.5129 6.51631 6.82407 6.13251 6.82407C5.74877 6.824 5.43754 6.51286 5.43754 6.1291C5.43759 5.74537 5.74879 5.4342 6.13251 5.43413Z",fill:"currentColor"}),a.jsx("path",{d:"M5.92771 2.29722C6.13122 2.09376 6.46147 2.09379 6.665 2.29722C6.86843 2.50075 6.86846 2.831 6.665 3.03451L3.03724 6.66227C2.83373 6.86578 2.5035 6.86572 2.29995 6.66227C2.0965 6.45872 2.09644 6.12849 2.29995 5.92498L5.92771 2.29722Z",fill:"currentColor"}),a.jsx("path",{d:"M2.842 2.12791C3.22572 2.12799 3.53694 2.43914 3.53696 2.82288C3.53696 3.20664 3.22573 3.51777 2.842 3.51785C2.45819 3.51785 2.14703 3.20668 2.14703 2.82288C2.14705 2.4391 2.45821 2.12791 2.842 2.12791Z",fill:"currentColor"}),a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.38455 0.00887484C8.26052 0.0979278 8.94379 0.837945 8.94379 1.73742V7.18384C8.94369 8.08322 8.26046 8.82334 7.38455 8.91238L7.20705 8.92126H1.73742L1.55992 8.91238C0.683828 8.82351 0.000101213 8.08336 0 7.18384V1.73742C0 0.837813 0.683761 0.0977507 1.55992 0.00887484L1.73742 0H7.20705L7.38455 0.00887484ZM1.73742 0.839013C1.24121 0.839013 0.839013 1.24121 0.839013 1.73742V7.18384C0.839121 7.67996 1.24128 8.08293 1.73742 8.08293H7.20705C7.70305 8.08276 8.10535 7.67985 8.10546 7.18384V1.73742C8.10546 1.24131 7.70312 0.83918 7.20705 0.839013H1.73742Z",fill:"currentColor"})]}),Aur=e=>a.jsx("svg",{width:"17",height:"18",viewBox:"0 0 17 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M8.40864 11.9983C7.58064 11.9733 6.84164 11.6153 6.31564 11.0563C6.31464 11.0563 6.31464 11.0553 6.31464 11.0553C5.78864 10.4963 5.47564 9.73633 5.50064 8.90833C5.52564 8.08033 5.88464 7.34133 6.44364 6.81533C7.00264 6.28833 7.76264 5.97633 8.59064 6.00133C9.41864 6.02633 10.1576 6.38433 10.6836 6.94333H10.6846C11.2106 7.50333 11.5236 8.26233 11.4986 9.09033C11.4726 9.91833 11.1146 10.6583 10.5556 11.1843C9.99664 11.7103 9.23664 12.0233 8.40864 11.9983ZM16.1266 8.15033L14.3606 7.74033C14.2316 7.14133 14.0146 6.57633 13.7216 6.05733L14.7726 4.57933C14.9116 4.38533 14.8926 4.12033 14.7296 3.94633L13.9206 3.08733C13.7576 2.91333 13.4946 2.87933 13.2916 3.00533L11.7526 3.96533C11.2526 3.64133 10.7016 3.39033 10.1116 3.22633L9.80964 1.43833C9.76964 1.20333 9.56964 1.02833 9.33164 1.02133L8.15264 0.985326C7.91364 0.978326 7.70364 1.14033 7.64964 1.37233L7.24064 3.13933C6.64164 3.26733 6.07664 3.48433 5.55664 3.77733L4.07864 2.72633C3.88464 2.58833 3.61964 2.60633 3.44664 2.76933L2.58664 3.57833C2.41364 3.74133 2.37964 4.00533 2.50564 4.20733L3.46564 5.74633C3.14164 6.24633 2.89064 6.79833 2.72564 7.38833L0.937635 7.68933C0.702635 7.72933 0.528635 7.92933 0.520635 8.16733L0.485635 9.34733C0.477635 9.58533 0.639635 9.79533 0.872635 9.84933L2.63864 10.2583C2.76764 10.8573 2.98464 11.4233 3.27764 11.9423L2.22564 13.4203C2.08764 13.6143 2.10564 13.8793 2.26964 14.0523L3.07864 14.9123C3.24164 15.0853 3.50464 15.1203 3.70664 14.9933L5.24564 14.0333C5.74663 14.3583 6.29764 14.6093 6.88764 14.7733L7.18964 16.5613C7.22864 16.7963 7.42864 16.9713 7.66764 16.9783L8.84663 17.0143C9.08564 17.0213 9.29564 16.8593 9.34964 16.6273L9.75864 14.8603C10.3576 14.7323 10.9226 14.5153 11.4416 14.2213L12.9206 15.2733C13.1146 15.4113 13.3786 15.3933 13.5526 15.2293L14.4116 14.4213C14.5856 14.2573 14.6196 13.9943 14.4936 13.7923L13.5336 12.2533C13.8576 11.7523 14.1086 11.2013 14.2726 10.6113L16.0616 10.3103C16.2966 10.2703 16.4706 10.0703 16.4776 9.83233L16.5136 8.65233C16.5206 8.41433 16.3586 8.20433 16.1266 8.15033Z",fill:"currentColor"})}),fd=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 11.185 11.185",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.0293 1.16491L4.81958 0.801671L4.81955 0.801686L5.0293 1.16491ZM5.75391 1.16491L5.96365 0.801686L5.96363 0.801671L5.75391 1.16491ZM9.04492 3.06531L9.25474 2.70212L9.25467 2.70208L9.04492 3.06531ZM9.40723 7.49304L9.82666 7.49332V7.49304H9.40723ZM9.04492 8.11999L8.8352 7.75675L8.83518 7.75676L9.04492 8.11999ZM5.75391 10.0204L5.96363 10.3836L5.96365 10.3836L5.75391 10.0204ZM5.0293 10.0204L4.81955 10.3836L4.81963 10.3837L5.0293 10.0204ZM1.73828 8.11999L1.94803 7.75676L1.948 7.75675L1.73828 8.11999ZM1.37598 7.49304H0.956538L0.956538 7.49332L1.37598 7.49304ZM1.73828 3.06531L1.94802 3.42854L1.94803 3.42853L1.73828 3.06531ZM5.59277 3.38366L5.59283 2.96423H5.59277V3.38366ZM3.38379 5.59167L2.96435 5.59159V5.59167H3.38379ZM5.59277 7.80066V8.2201H5.59283L5.59277 7.80066ZM7.80078 5.59167H8.22022V5.59159L7.80078 5.59167ZM5.0293 1.16491L5.23902 1.52816C5.33331 1.47372 5.44989 1.47372 5.54419 1.52816L5.75391 1.16491L5.96363 0.801671C5.60978 0.59738 5.17342 0.59738 4.81958 0.801671L5.0293 1.16491ZM5.75391 1.16491L5.54416 1.52814L8.83518 3.42853L9.04492 3.06531L9.25467 2.70208L5.96365 0.801686L5.75391 1.16491ZM9.04492 3.06531L8.83511 3.42849C8.92979 3.48319 8.98779 3.5839 8.98779 3.69226H9.40723H9.82666C9.82666 3.28328 9.60799 2.90619 9.25474 2.70212L9.04492 3.06531ZM9.40723 3.69226H8.98779V7.49304H9.40723H9.82666V3.69226H9.40723ZM9.40723 7.49304L8.98779 7.49276C8.98772 7.6015 8.92949 7.70231 8.8352 7.75675L9.04492 8.11999L9.25464 8.48324C9.60821 8.2791 9.82639 7.90167 9.82666 7.49332L9.40723 7.49304ZM9.04492 8.11999L8.83518 7.75676L5.54416 9.65715L5.75391 10.0204L5.96365 10.3836L9.25467 8.48322L9.04492 8.11999ZM5.75391 10.0204L5.54419 9.65714C5.44996 9.71154 5.33331 9.71156 5.23897 9.65711L5.0293 10.0204L4.81963 10.3837C5.17339 10.5878 5.60977 10.5879 5.96363 10.3836L5.75391 10.0204ZM5.0293 10.0204L5.23904 9.65715L1.94803 7.75676L1.73828 8.11999L1.52854 8.48322L4.81955 10.3836L5.0293 10.0204ZM1.73828 8.11999L1.948 7.75675C1.85371 7.70231 1.79549 7.6015 1.79541 7.49276L1.37598 7.49304L0.956538 7.49332C0.956809 7.90167 1.17499 8.2791 1.52856 8.48324L1.73828 8.11999ZM1.37598 7.49304H1.79542V3.69226H1.37598H0.956538V7.49304H1.37598ZM1.37598 3.69226H1.79542C1.79542 3.58378 1.85339 3.48318 1.94802 3.42854L1.73828 3.06531L1.52854 2.70207C1.17507 2.90617 0.956538 3.2833 0.956538 3.69226H1.37598ZM1.73828 3.06531L1.94803 3.42853L5.23904 1.52814L5.0293 1.16491L4.81955 0.801686L1.52854 2.70208L1.73828 3.06531ZM5.59277 3.38366V2.96423C4.14162 2.96423 2.96463 4.14015 2.96435 5.59159L3.38379 5.59167L3.80323 5.59175C3.80342 4.60382 4.60458 3.8031 5.59277 3.8031V3.38366ZM3.38379 5.59167H2.96435C2.96435 7.04322 4.14132 8.2201 5.59277 8.2201V7.80066V7.38122C4.6046 7.38122 3.80323 6.57991 3.80323 5.59167H3.38379ZM5.59277 7.80066L5.59283 8.2201C7.04429 8.2199 8.22022 7.04294 8.22022 5.59167H7.80078H7.38134C7.38134 6.57999 6.58061 7.38108 5.59272 7.38122L5.59277 7.80066ZM7.80078 5.59167L8.22022 5.59159C8.21994 4.14043 7.04398 2.96443 5.59283 2.96423L5.59277 3.38366L5.59272 3.8031C6.58062 3.80324 7.38115 4.60374 7.38134 5.59175L7.80078 5.59167Z",fill:"currentColor"})}),Sx=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 9.45892 8.88606",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M8.53702 7.36403C8.98547 7.36403 9.34918 7.70502 9.34918 8.12535C9.34906 8.54559 8.9854 8.88606 8.53702 8.88606H5.6839C5.23552 8.88606 4.87186 8.54559 4.87174 8.12535C4.87174 7.70502 5.23545 7.36403 5.6839 7.36403H8.53702Z",fill:"currentColor"}),a.jsx("path",{d:"M8.53702 3.67209C8.98547 3.67209 9.34918 4.01309 9.34918 4.43342C9.34911 4.8537 8.98543 5.19413 8.53702 5.19413H5.6839C5.23549 5.19413 4.87181 4.8537 4.87174 4.43342C4.87174 4.01309 5.23545 3.67209 5.6839 3.67209H8.53702Z",fill:"currentColor"}),a.jsx("path",{d:"M8.67155 0C9.10635 2.06584e-05 9.45892 0.341006 9.45892 0.761326C9.45878 1.18153 9.10627 1.52201 8.67155 1.52203H2.88163C2.4469 1.52203 2.0944 1.18154 2.09427 0.761326C2.09427 0.340993 2.44681 3.80132e-08 2.88163 0H8.67155Z",fill:"currentColor"}),a.jsx("path",{d:"M0.757606 0.760086V4.01122H3.50594V4.76883H0.759466L0.762566 5.4291C0.76837 6.70703 1.8058 7.73972 3.08374 7.73973H3.67953V8.49796H3.08374C1.38863 8.49795 0.0120204 7.1273 0.00433981 5.4322L0 4.39188V0.760086H0.757606Z",fill:"currentColor"})]}),Pur=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 9.55888 8.30616",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{d:"M0 7.18794V1.11823C-4.80684e-08 0.5005 0.5005 2.79299e-06 1.11823 0H3.17924C3.48658 0 3.78038 0.126314 3.99163 0.349532L5.09347 1.5135C5.14625 1.56923 5.21948 1.60085 5.29623 1.60088H8.44065C9.05838 1.60088 9.55888 2.10206 9.55888 2.7198V7.18794C9.55888 7.80567 9.05838 8.30616 8.44065 8.30616H1.11823C0.500524 8.30614 4.41663e-06 7.80565 0 7.18794ZM0.838331 7.18794C0.838332 7.34235 0.963819 7.46781 1.11823 7.46783H8.44065C8.59509 7.46783 8.72055 7.34237 8.72055 7.18794V2.7198C8.72055 2.56536 8.59509 2.4399 8.44065 2.4399H5.29623C4.98896 2.43986 4.69506 2.31353 4.48384 2.09037L3.38268 0.925714C3.32987 0.869949 3.25604 0.838331 3.17924 0.838331H1.11823C0.963799 0.838334 0.838331 0.963798 0.838331 1.11823V7.18794Z",fill:"currentColor"})}),$ur=typeof window<"u"&&window.MASTRA_SIGNALS_UI==="true",Rur={name:"Intelligence",url:"/intelligence",activePaths:["/intelligence"],Icon:lpt,isOnMastraPlatform:!0,hidden:!$ur},qke=[{key:"primitives",title:"Primitives",items:[{name:"Agents",url:"/agents",Icon:Vo,isOnMastraPlatform:!0},{name:"Prompts",url:"/prompts",Icon:Nur,isOnMastraPlatform:!0},{name:"Workflows",url:"/workflows",Icon:jl,isOnMastraPlatform:!0},{name:"Processors",url:"/processors",Icon:aj,isOnMastraPlatform:!1,foldable:!0},{name:"MCP Servers",url:"/mcps",Icon:F_,isOnMastraPlatform:!0,foldable:!0},{name:"Tools",url:"/tools",Icon:fd,isOnMastraPlatform:!0,foldable:!0},{name:"Workspaces",url:"/workspaces",Icon:Pur,isOnMastraPlatform:!0,foldable:!0}]},{key:"evaluation",title:"Evaluation",items:[{name:"Scorers",url:"/scorers",Icon:rw,isOnMastraPlatform:!0},{name:"Datasets",url:"/datasets",Icon:ijt,isOnMastraPlatform:!0},{name:"Experiments",url:"/experiments",Icon:Tur,isOnMastraPlatform:!0},{name:"Review Queue",url:"/experiments/review-queue",Icon:Jht,isOnMastraPlatform:!0}]},{key:"observability",title:"Observability",items:[{name:"Metrics",url:"/metrics",Icon:Eur,isOnMastraPlatform:!0},{name:"Traces",url:"/traces",Icon:Sx,isOnMastraPlatform:!0},Rur,{name:"Logs",url:"/logs",Icon:Iur,isOnMastraPlatform:!0}]}],Qke=[{name:"Settings",url:"/settings",Icon:Aur,isOnMastraPlatform:!1},{name:"Resources",url:"/resources",Icon:Zht,isOnMastraPlatform:!0}],Mur=[...qke.flatMap(e=>e.items),...Qke];function Dur(e){return Mur.find(t=>t.url===e)}function Ts(e,t){const n=Dur(e);if(!n)throw new Error(`navCrumb: unknown nav url "${e}"`);return{id:`nav:${e}`,label:n.name,icon:n.Icon,to:e,...t}}const Zke=e=>{if(!e)return"";try{return decodeURIComponent(e)}catch{return e}},ojt=e=>{const t=Zke(e);return t.length>8?`${t.slice(0,8)}...`:t},ajt={id:"agent",Component:Dcr,Switcher:Lcr},Lur={id:"scorer",Component:jur,Switcher:Cur},zur={id:"processor",Component:cur,Switcher:uur},Fur={id:"mcp-server",Component:iur,Switcher:our},lUe={id:"workflow",Component:lcr,Switcher:ccr},MK={id:"dataset",Component:Xcr,Switcher:Jcr},ljt={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",diff:"diff",patch:"diff",css:"css",scss:"css",html:"html",htm:"html",xml:"xml",svg:"xml",sql:"sql"};let Koe=null;function Bur(){return Koe||(Koe=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Ai(()=>import("./core-DH5BGEHl.js"),__vite__mapDeps([0,1,2,3,4]),import.meta.url),Ai(()=>import("./engine-javascript-DSQaR0Yq.js"),__vite__mapDeps([5,2,3]),import.meta.url)]);return e({themes:[Ai(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Ai(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Ai(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Ai(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Ai(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Ai(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Ai(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Ai(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Ai(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Ai(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Ai(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Ai(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Ai(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Ai(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([6,7,8]),import.meta.url),Ai(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Ai(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Koe}async function Vur(e,t){const n=ljt[t?.toLowerCase()];if(!n)return null;const r=await Bur(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function cjt(e){const t=e?.split(".").pop()?.toLowerCase();return t?ljt[t]:void 0}let cUe;const ujt=()=>cUe??=Promise.all([Ai(()=>import("./standalone-Dfz2oS5J.js"),[],import.meta.url),Ai(()=>import("./babel-lWBcy2sH.js"),[],import.meta.url),Ai(()=>import("./estree-Dd9JfUIE.js"),[],import.meta.url)]).catch(e=>{throw cUe=void 0,e}),T5=async e=>{const[t,n,r]=await ujt();return await t.format(e,{semi:!1,parser:"json",printWidth:80,tabWidth:2,plugins:[n,r]})},djt=async e=>{const[t,n,r]=await ujt();return await t.format(e,{parser:"babel-ts",printWidth:80,tabWidth:2,plugins:[n,r]})},CQ=e=>{try{const t=JSON.parse(e);return!!t&&typeof t=="object"}catch{return!1}},Uur=ji(vt(),Q2n());function Yoe(e,t){if(!e)return"__custom__";for(const[n,r]of Object.entries(e))if(JSON.stringify(r)===t)return n;return"__custom__"}function qur(e){try{return JSON.stringify(JSON.parse(e))}catch{return null}}const fjt=({label:e,presets:t,value:n,onSave:r,editorClassName:s="h-[400px]",labelTooltip:i,headerActions:o})=>{const l=JSON.stringify(n??{}),c=JSON.stringify(n??{},null,2),[u,d]=g.useState(c),[f,h]=g.useState(c),[p,m]=g.useState(()=>Yoe(t,l)),{handleCopy:v}=Vm({text:u}),[y,x]=g.useState(l);y!==l&&(x(l),d(c),h(c),m(Yoe(t,l)));const b=g.useMemo(()=>{const N=qur(u);return N?N!==l:u!==f},[l,u,f]),S=()=>{let N;try{N=JSON.parse(u)}catch{Xe.error("Invalid JSON");return}const E=Uur.safeParse(N);if(!E.success){Xe.error(`${e} must be a JSON object`);return}r(E.data)},k=()=>{d(f),m(Yoe(t,l))},j=Z(Zn,In),C=async()=>{if(!CQ(u)){Xe.error("Invalid JSON");return}const N=await T5(u);d(N)},T=async N=>{if(m(N),N==="__custom__"||!t)return;const E=t[N];if(E){const A=await T5(JSON.stringify(E));d(A)}},_=N=>{d(N),p!=="__custom__"&&m("__custom__")};return a.jsx(Wc,{children:a.jsxs("div",{children:[a.jsxs(pt,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs(dt,{info:i,children:[e," (JSON)"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[o,a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:C,className:j,children:a.jsx(At,{children:a.jsx(Va,{})})})}),a.jsxs(Bn,{children:["Format the ",e," JSON"]})]}),a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:v,className:j,children:a.jsx(At,{children:a.jsx(Lm,{})})})}),a.jsxs(Bn,{children:["Copy ",e]})]})]})]}),t&&Object.keys(t).length>0&&a.jsxs(pt,{children:[a.jsxs(dt,{className:"sr-only",children:[e," preset"]}),a.jsxs(ms,{value:p,onValueChange:T,children:[a.jsx(vs,{children:a.jsx(gs,{placeholder:"Select a preset..."})}),a.jsxs(ys,{children:[a.jsx(hr,{value:"__custom__",children:"Custom"}),Object.keys(t).map(N=>a.jsx(hr,{value:N,children:N},N))]})]})]}),a.jsx(Or,{value:u,onChange:_,showCopyButton:!1,className:s})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[b&&a.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:`Revert ${e} changes`,onClick:k,children:a.jsx(Mn,{})}),a.jsx(ce,{icon:a.jsx(ur,{}),type:"button",onClick:S,children:"Save"})]})]})})},Qur={align:"shift"};function hjt({label:e,icon:t,open:n,onOpenChange:r,children:s}){return a.jsxs(jp,{open:n,onOpenChange:r,children:[a.jsx(of,{variant:"ghost",size:"icon-md",type:"button",tooltip:e,"aria-label":e,children:t}),a.jsx(ah,{align:"start",collisionAvoidance:Qur,className:"w-[min(480px,calc(100vw-2rem))] p-0",children:a.jsx("div",{onSubmit:i=>i.stopPropagation(),children:a.jsx(jr,{className:"w-full",maxHeight:"min(600px, calc(100dvh - 8rem))",children:a.jsx("div",{className:"space-y-4 p-4",children:s})})})})]})}function Zur(){return g.useMemo(()=>{const e=typeof window<"u"?window.MASTRA_REQUEST_CONTEXT_PRESETS:void 0;if(!e||e==="%%MASTRA_REQUEST_CONTEXT_PRESETS%%")return null;try{const t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}catch{console.warn("Failed to parse request context presets")}return null},[])}function Wke({entityType:e,entityId:t}){const[n,r]=g.useState(!1),[s,i]=xr(e,t),o=Zur(),l=c=>{i(c),Xe.success("Request context saved locally"),r(!1)};return a.jsx(hjt,{label:"Request context",icon:a.jsx(MIn,{}),open:n,onOpenChange:r,children:a.jsx(fjt,{label:"Request Context",presets:o,value:s,onSave:l,editorClassName:"h-[260px]"})})}function pjt({entityType:e,entityId:t,extraFields:n,onSaveExtra:r,onOpenChange:s}){const[i,o]=g.useState(!1),[l,c]=Nke(e,t),u=f=>{o(f),s?.(f)},d=f=>{c(f),r?.(),Xe.success("Run options saved locally"),u(!1)};return a.jsxs(hjt,{label:"Run options",icon:a.jsx(Sx,{}),open:i,onOpenChange:u,children:[n,a.jsx(fjt,{label:"Tracing Options",value:l,onSave:d,editorClassName:"h-[260px]"})]})}function Wur({workflowId:e,resourceId:t,setResourceId:n}){const[r,s]=g.useState(t);return a.jsxs(a.Fragment,{children:[a.jsx(Wke,{entityType:"workflow",entityId:e}),a.jsx(pjt,{entityType:"workflow",entityId:e,onOpenChange:i=>{i&&s(t)},onSaveExtra:()=>n(r),extraFields:a.jsxs(pt,{children:[a.jsx(dt,{children:"Resource ID"}),a.jsx(bn,{value:r,onChange:i=>s(i.target.value),placeholder:"e.g. tenant-42"}),a.jsx(no,{children:"Ignored when server auth derives the resource ID from the user."})]})})]})}function _Q({icon:e,label:t,tooltipContent:n,docsHref:r}){return a.jsxs(Qn,{children:[a.jsx(Fn,{render:a.jsx("span",{role:"button",tabIndex:0,"aria-disabled":"true","aria-label":t,className:"inline-flex",children:a.jsx(ce,{variant:"ghost",size:"icon-md",disabled:!0,"aria-hidden":"true",tabIndex:-1,children:e})})}),a.jsx(Bn,{side:"bottom",className:"max-w-[calc(100dvw-1rem)]",children:a.jsxs("span",{children:[n," ",a.jsxs("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:Z("inline-flex items-center gap-1 text-inherit underline hover:text-foreground",In),children:["Learn more",a.jsx(Zs,{className:"size-3"})]})]})})]})}const Hur=({scheduleId:e,queryOptions:t})=>{const n=Ke();return Ct({queryKey:["schedule",e],queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return n.getSchedule(e)},...t})},DK=({queryOptions:e,...t}={})=>{const n=Ke();return Ct({queryKey:["schedules",t],queryFn:async()=>(await n.listSchedules(t)).schedules,...e})},uUe=25,Gur=({scheduleId:e,queryOptions:t})=>{const n=Ke(),{inView:r,setRef:s}=X0(),i=Mm({queryKey:["schedule-triggers",e],initialPageParam:void 0,queryFn:async({pageParam:d})=>e?n.listScheduleTriggers(e,{limit:uUe,toActualFireAt:d}):{triggers:[]},getNextPageParam:d=>{if(!(!d?.triggers?.length||d.triggers.length<uUe))return d.triggers[d.triggers.length-1].actualFireAt},refetchInterval:d=>(d.state.data?.pages.flatMap(f=>f.triggers)??[]).some(f=>f.run?f.run.status==="pending"||f.run.status==="running"||f.run.status==="waiting":f.outcome==="published")?5e3:!1,...t}),o=i.data?.pages.flatMap(d=>d?.triggers??[])??[],{hasNextPage:l,isFetchingNextPage:c,fetchNextPage:u}=i;return g.useEffect(()=>{r&&l&&!c&&u()},[r,l,c,u]),{...i,data:o,setEndOfListElement:s}},Kur=({scheduleId:e,queryOptions:t})=>{const n=Ke(),r=mr();return wn({mutationFn:async s=>{if(!e)throw new Error("scheduleId is required");return s==="pause"?n.pauseSchedule(e):n.resumeSchedule(e)},onSuccess:()=>{r.invalidateQueries({queryKey:["schedule",e]}),r.invalidateQueries({queryKey:["schedules"]})},...t})};function Xoe({value:e,icon:t,label:n}){return a.jsxs(si,{value:e,children:[a.jsx(At,{size:"xs",children:t}),a.jsx(Y,{variant:"caption",className:"text-inherit",children:n})]})}function Yur({workflowId:e,activeTab:t,showObservability:n=!1}){const{navigate:r}=Sn(),{data:s,isSuccess:i}=DK({workflowId:e}),o=s?.length??0,l=encodeURIComponent(e),c={graph:`/workflows/${l}/graph`,traces:`/workflows/${l}/traces`,schedules:`/workflows/${l}/schedules`},u=f=>{f!=="none"&&r(c[f])},d=i&&o===0;return a.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 p-1.5",children:[a.jsx(Hc,{value:t,defaultTab:t,onValueChange:u,className:"min-w-0",children:a.jsxs(Gc,{variant:"pill-ghost",children:[a.jsx(Xoe,{value:"graph",icon:a.jsx(jl,{}),label:"Graph"}),n&&a.jsx(Xoe,{value:"traces",icon:a.jsx(Sx,{}),label:"Traces"}),!d&&a.jsx(Xoe,{value:"schedules",icon:a.jsx(T0,{}),label:o>0?`Schedules (${o})`:"Schedules"})]})}),(!n||d)&&a.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-0.5",children:[!n&&a.jsx(_Q,{icon:a.jsx(Sx,{}),label:"Traces",tooltipContent:a.jsxs(a.Fragment,{children:["Add ",a.jsx("code",{children:"@mastra/observability"})," to enable Traces."]}),docsHref:"https://mastra.ai/docs/observability/overview"}),d&&a.jsx(_Q,{icon:a.jsx(T0,{}),label:"Schedules",tooltipContent:"Configure a schedule on this workflow to enable Schedules.",docsHref:"https://mastra.ai/docs/workflows/scheduled-workflows"})]})]})}const Xur=({children:e})=>{const{workflowId:t,runId:n}=Cr();return a.jsx(_we,{resetKeys:[t,n],title:"Unable to display this workflow",description:"The workflow data could not be displayed. Try again or open another workflow.",children:a.jsx(tdr,{children:e})})},Jur=e=>e==="graph"||e==="traces"||e==="schedules",edr=({workflowId:e})=>{const t=Lr();return G0({"g$+t":()=>t(`/workflows/${encodeURIComponent(e)}/traces`)}),null};function tdr({children:e}){const{workflowId:t,runId:n}=Cr(),r=d0e("/workflows/:workflowId/:tab/*"),{isLoading:s}=wL({workflowId:t,requestContext:xr("workflow",t)[0],queryOptions:{enabled:!!t}}),{hasObservability:i}=zOt(),o=Jur(r?.params.tab)?r.params.tab:"none",l=[Ts("/workflows"),n?{...lUe,to:`/workflows/${encodeURIComponent(t??"")}/graph`}:lUe,...n?[{id:"workflow-run",Component:ucr,Action:dcr}]:[]];if(!t)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:l}),children:[a.jsx("h1",{className:"sr-only",children:t}),a.jsx("div",{className:"flex h-full flex-col items-center justify-center",children:a.jsx(Y,{variant:"body",tone:"ink",className:"text-center",children:"No workflow ID provided"})})]});if(s&&o==="graph")return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:l}),children:[a.jsx("h1",{className:"sr-only",children:t}),a.jsx(bt,{className:"h-full"})]});const c=u=>a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:l}),headerActions:a.jsx(hcr,{}),children:[a.jsx("h1",{className:"sr-only",children:t}),a.jsxs("div",{className:"grid h-full min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[auto_minmax(0,1fr)]",children:[a.jsx(Yur,{workflowId:t,activeTab:o,showObservability:i}),u]})]});return a.jsxs(xst,{children:[a.jsx(edr,{workflowId:t}),o==="graph"?a.jsx(cOt,{children:a.jsx(Pke,{workflowId:t,initialRunId:n,children:a.jsx(lOt,{children:c(a.jsx(mlr,{leftSlot:a.jsx(ndr,{workflowId:t,initialRunId:n}),children:e}))})})},t):c(e)]})}function ndr({workflowId:e,initialRunId:t}){const[n]=xr("workflow",e),{canExecute:r,canDelete:s}=Za();return a.jsx(wlr,{workflowId:e,initialRunId:t,requestContext:n,runActionsSlot:i=>a.jsx(Wur,{workflowId:e,...i}),canExecute:r("workflows"),canDelete:s("workflows")})}const mjt=md(Z(pr,"rounded-xl transition-all duration-normal ease-out-custom motion-reduce:transition-none"),{variants:{elevation:{flat:"shadow-none",raised:""},interactive:{true:Z(gP,twe,"cursor-pointer active:scale-99"),false:""}},compoundVariants:[{elevation:"flat",interactive:!0,class:Ax}],defaultVariants:{elevation:"raised",interactive:!1}}),hl=g.forwardRef(({className:e,elevation:t,interactive:n,as:r,...s},i)=>{const o=r||(n?"button":"div");return a.jsx(o,{ref:i,type:o==="button"?"button":void 0,className:Z(mjt({elevation:t,interactive:n}),e),...s})});hl.displayName="Card";function gjt({className:e,elevation:t,LinkComponent:n="a",...r}){return a.jsx(n,{className:Z(mjt({elevation:t,interactive:!0}),e),...r})}const TQ=g.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,className:Z("flex flex-col space-y-1.5 px-3 py-1",e),...t}));TQ.displayName="CardHeader";const sw=g.forwardRef(({className:e,...t},n)=>a.jsx("h3",{ref:n,className:Z("text-subheading text-foreground",e),...t}));sw.displayName="CardTitle";const Zj=g.forwardRef(({className:e,...t},n)=>a.jsx("p",{ref:n,className:Z("text-caption text-muted-foreground",e),...t}));Zj.displayName="CardDescription";const rdr=md("",{variants:{density:{default:"p-3",compact:"p-2"}},defaultVariants:{density:"default"}}),qm=g.forwardRef(({className:e,density:t,...n},r)=>a.jsx("div",{ref:r,className:Z(rdr({density:t}),e),...n}));qm.displayName="CardContent";const sdr=g.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,className:Z("flex items-center p-3 pt-0",e),...t}));sdr.displayName="CardFooter";const dUe=["blue","green","orange","purple","pink","amber","cyan"];function Hke(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}const LK=e=>dUe[Hke(e)%dUe.length]??"blue",v0=e=>`var(--badge-${e}-indicator)`,idr={blue:"bg-badge-blue-strong text-badge-blue-foreground",green:"bg-badge-green-strong text-badge-green-foreground",orange:"bg-badge-orange-strong text-badge-orange-foreground",purple:"bg-badge-purple-strong text-badge-purple-foreground",pink:"bg-badge-pink-strong text-badge-pink-foreground",amber:"bg-badge-amber-strong text-badge-amber-foreground",cyan:"bg-badge-cyan-strong text-badge-cyan-foreground"},vjt=e=>idr[e],odr=e=>({background:`var(--badge-${e}-strong)`,foreground:`var(--badge-${e}-foreground)`,tint:`var(--badge-${e}-indicator)`}),fUe={goal:"green",outcome:"orange",behavior:"blue",sentiment:"purple"},hUe=["pink","amber"],adr={green:"fill-badge-green-strong",orange:"fill-badge-orange-strong",blue:"fill-badge-blue-strong",purple:"fill-badge-purple-strong",pink:"fill-badge-pink-strong",amber:"fill-badge-amber-strong"},ldr={green:"stroke-badge-green-edge",orange:"stroke-badge-orange-edge",blue:"stroke-badge-blue-edge",purple:"stroke-badge-purple-edge",pink:"stroke-badge-pink-edge",amber:"stroke-badge-amber-edge"};function Gke(e){const t=e.toLowerCase();return(Object.hasOwn(fUe,t)?fUe[t]:void 0)??hUe[Hke(t)%hUe.length]??"pink"}function Vx(e){return`var(--chart-${Gke(e)})`}function yjt(e){return adr[Gke(e)]}function cdr(e){return ldr[Gke(e)]}const FP=[{name:"goal",label:"Goal",description:"What the user wanted from the interaction.",order:0,builtIn:!0,enabled:!0,status:"ready"},{name:"sentiment",label:"Sentiment",description:"The tone the user expressed during the interaction.",order:1,builtIn:!0,enabled:!0,status:"ready"},{name:"behavior",label:"Behavior",description:"What the agent did in response.",order:2,builtIn:!0,enabled:!0,status:"ready"},{name:"outcome",label:"Outcome",description:"How the interaction ended.",order:3,builtIn:!0,enabled:!0,status:"ready"}];FP.map(e=>e.name);Object.fromEntries(FP.map(e=>[e.name,e.description]));function o6(e,t){const n=[...new Set(t??e.map(s=>s.name))],r=new Map(e.map(s=>[s.name,s.order]));return n.sort((s,i)=>{const o=r.get(s),l=r.get(i);return o===void 0&&l===void 0?0:o===void 0?1:l===void 0?-1:o-l})}function gp(e,t){return e.find(n=>n.name===t)?.label??udr(t)}function QS(e,t){return e.find(n=>n.name===t)?.description||void 0}function udr(e){return e.split(/[-_]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function zK(e){return`${e} ${e===1?"trace":"traces"}`}function ddr(e){return`${e} ${e===1?"theme":"themes"}`}function xjt(e,t){if(t<=0)return`${zK(e)} in this snapshot`;const n=Math.round(e/t);return`${e} of ${n} traces in this snapshot (${Math.round(t*100)}%)`}const Kke={timeZone:"UTC"};function I5(e){return FE(e,{...Kke,now:0})??e}function FK(e){return rs(e,"date-time",Kke)??e}function nme(e,t){return eer(e,t,Kke)??`${e}–${t}`}const fdr=[["chat.completion","1.2s"],["tool.search_docs","340ms"],["workflow.support","2.8s"]],IQ=e=>({color:Vx(e)}),pUe=()=>a.jsxs("div",{"aria-hidden":"true",className:"relative hidden h-full items-center lg:flex",children:[a.jsx("div",{className:"w-full border-t border-dashed border-border"}),a.jsx("span",{className:"absolute left-1/2 size-2.5 -translate-x-1/2 rounded-full bg-brand-green-indicator"})]});function E5(e){return new Intl.NumberFormat("en-US").format(e)}function hdr(e,t){return t?{title:"No Trace Intelligence themes in this date range.",body:"Choose a wider snapshot date range, or wait for newly processed traces to form recurring themes."}:!e||e.status==="collecting"?{title:"Collecting traces for Trace Intelligence.",body:"Trace Intelligence starts grouping recurring patterns after your deployed agents send enough completed traces."}:e.status==="ready"?{title:"Trace Intelligence themes are ready.",body:"Select at least two available trace signal types to see how goals, outcomes, behaviors, and sentiment connect."}:{title:"Analyzing traces for Trace Intelligence.",body:"Trace signals have started processing. Themes appear after enough generated and embedded trace signals form recurring patterns."}}function pdr({progress:e}){const t=e.signalCatalog??FP,n=t.filter(s=>s.enabled).length,r=t.filter(s=>s.enabled&&s.status==="ready").length;return a.jsxs("dl",{className:"mt-4 grid gap-2 sm:grid-cols-3",children:[a.jsxs("div",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:Sa({tone:"muted",variant:"caption"}),children:"Traces analyzed"}),a.jsx("dd",{className:Z(Sa({tone:"ink",variant:"heading"}),"mt-1"),children:E5(e.traceCount)})]}),a.jsxs("div",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:Sa({tone:"muted",variant:"caption"}),children:"Trace signal types ready"}),a.jsxs("dd",{className:Z(Sa({tone:"ink",variant:"heading"}),"mt-1"),children:[e.signalCatalog?r:e.availableSignals.length," of ",n]})]}),a.jsxs("div",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:Sa({tone:"muted",variant:"caption"}),children:"Status"}),a.jsx("dd",{className:Z(Sa({tone:"ink",variant:"heading"}),"mt-1 capitalize"),children:e.status})]})]})}function mdr({progress:e}){if(!e)return null;const t=e.signalCatalog??FP;return a.jsx("ul",{"aria-label":"Trace signal processing progress",className:"mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-4",children:o6(t,t.filter(n=>n.enabled).map(n=>n.name)).map(n=>{const r=e.signals[n]??{generated:0,embedded:0},s=t.find(l=>l.name===n),i=gp(t,n),o=s?s.status==="ready":e.availableSignals.includes(n);return a.jsxs("li",{className:"rounded-md border border-border bg-background px-3 py-2",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx(Y,{as:"span",variant:"subheading",style:IQ(n),children:i}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:o?"Themes ready":"Processing"})]}),a.jsxs(Y,{variant:"caption",tone:"muted",className:"mt-1",children:[E5(r.generated)," generated · ",E5(r.embedded)," embedded"]})]},n)})})}function gdr({progress:e,signalCatalog:t}){const n=e?.signalCatalog??t,r=n.filter(s=>s.enabled&&s.status!=="ready");return r.length===0?null:a.jsxs("section",{className:"rounded-lg border border-border bg-background p-4","aria-labelledby":"pending-signals-heading",children:[a.jsx(Y,{as:"h2",variant:"subheading",tone:"ink",id:"pending-signals-heading",children:"Signals building themes"}),a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-1",children:"Themes appear once enough new traces are analyzed, embedded, and clustered."}),a.jsx("ul",{"aria-label":"Pending trace signals",className:"mt-3 grid gap-2 sm:grid-cols-2",children:r.map(s=>{const i=e?.signals[s.name]??{generated:0,embedded:0};return a.jsxs("li",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx(Y,{font:"body",as:"span",variant:"subheading",style:IQ(s.name),children:gp(n,s.name)}),a.jsx(Y,{font:"body",as:"span",variant:"caption",tone:"muted",className:"capitalize",children:s.status})]}),QS(n,s.name)?a.jsx(Y,{font:"body",variant:"caption",tone:"muted",className:"mt-1",children:QS(n,s.name)}):null,a.jsxs(Y,{font:"body",variant:"caption",tone:"muted",className:"mt-1",children:[E5(i.generated)," generated · ",E5(i.embedded)," embedded"]})]},s.name)})})]})}const rme=({actionSlot:e,LinkComponent:t="a",progress:n,signalCatalog:r,isRangeEmpty:s})=>{const i=hdr(n,s),o=r??n?.signalCatalog??FP,c=o6(o,o.filter(u=>u.enabled).map(u=>u.name)).map(u=>({key:u,label:gp(o,u),description:QS(o,u)}));return a.jsx("section",{className:"min-h-full w-full bg-sidebar p-6 md:px-10 lg:px-12 xl:px-[4.375rem]",children:a.jsxs("div",{className:"mx-auto w-full max-w-260",children:[a.jsxs("header",{children:[a.jsxs(Y,{variant:"eyebrow",tone:"muted",className:"flex items-center gap-2",children:[a.jsx("span",{"aria-hidden":"true",className:"size-2 rounded-full bg-brand-green-indicator"}),"Trace Intelligence"]}),a.jsx(Y,{as:"h1",variant:"display",tone:"ink",className:"mt-2",children:"Understand what drives every agent interaction"}),a.jsx(Y,{tone:"muted",className:"mt-2 max-w-180",children:"Trace Intelligence groups recurring goals, outcomes, behaviors, and sentiment across completed traces."})]}),a.jsxs("div",{role:"list","aria-label":"Trace Intelligence analysis pipeline",className:"mt-14 grid gap-4 lg:grid-cols-[17.5rem_4.5rem_17.5rem_4.5rem_minmax(0,1fr)] lg:gap-0",children:[a.jsxs("div",{role:"listitem",className:"min-h-50 p-5",children:[a.jsx(Y,{as:"h2",variant:"heading",tone:"ink",children:"Traces"}),a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-0.5",children:"Every agent interaction"}),a.jsx(Y,{variant:"eyebrow",tone:"muted",className:"mt-5",children:"Input"}),a.jsx("div",{className:"mt-2.5 space-y-2",children:fdr.map(([u,d])=>a.jsxs("div",{className:Z(pr,"flex items-center justify-between rounded px-3 py-1.5"),children:[a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"muted",children:u}),a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"muted",children:d})]},u))})]}),a.jsx(pUe,{}),a.jsxs(hl,{as:"div",role:"listitem",className:"flex min-h-50 flex-col items-center p-5 text-center",elevation:"raised",children:[a.jsx(Y,{as:"h2",variant:"heading",tone:"ink",children:"Trace Intelligence"}),a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-0.5",children:"Finds recurring themes"}),a.jsx("div",{"aria-hidden":"true",className:"mt-5 flex size-14 items-center justify-center rounded-full border border-brand-green-indicator bg-fill-subtle",children:a.jsx(I_,{className:"size-4 text-brand-green-indicator"})}),a.jsx(Y,{variant:"meta",tone:"muted",className:"mt-3 max-w-40",children:"Clusters similar trace signals into themes for each dimension"})]}),a.jsx(pUe,{}),a.jsxs("div",{role:"listitem",className:"min-h-50 p-5",children:[a.jsx(Y,{as:"h2",variant:"heading",tone:"ink",children:"Theme analysis"}),a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-0.5",children:"How recurring patterns connect"}),a.jsx(Y,{variant:"eyebrow",tone:"muted",className:"mt-5",children:"Output"}),a.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:c.map(u=>a.jsxs(Y,{as:"span",variant:"column",className:"inline-flex items-center gap-2 rounded border border-border bg-card px-2.5 py-1.5",style:IQ(u.key),children:[a.jsx("span",{"aria-hidden":"true",className:"size-1.5 rounded-full bg-current"}),u.label]},u.key))})]})]}),a.jsxs("section",{className:"mt-10","aria-labelledby":"signal-definitions-heading",children:[a.jsx(Y,{as:"h2",variant:"heading",tone:"ink",id:"signal-definitions-heading",children:"What each trace signal means"}),a.jsx("ul",{"aria-label":"Trace signal definitions",className:"mt-4 grid gap-3 sm:grid-cols-2",children:c.map(u=>a.jsxs("li",{className:"px-1 py-2",children:[a.jsx(Y,{as:"h3",variant:"subheading",style:IQ(u.key),children:u.label}),u.description?a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-1.5",children:u.description}):null]},u.key))})]}),a.jsxs("aside",{className:"mt-9 rounded-md border border-border bg-background px-5 py-4",children:[a.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[a.jsx("span",{"aria-hidden":"true",className:"mt-1.5 size-2 shrink-0 rounded-full bg-warning-indicator"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs(Y,{variant:"caption",tone:"muted",children:[a.jsx(Y,{as:"strong",variant:"column",tone:"ink",children:i.title})," ",i.body]}),n?a.jsx(pdr,{progress:n}):null,a.jsx(mdr,{progress:n})]})]}),a.jsxs("div",{className:"mt-4 flex shrink-0 flex-wrap items-center gap-2 sm:justify-end",children:[e,a.jsxs(ce,{icon:a.jsx(Zs,{}),render:a.jsx("a",{href:"https://mastra.ai/en/docs/mastra-platform/trace-intelligence",target:"_blank",rel:"noopener noreferrer"}),size:"sm",children:["Read the docs",a.jsx("span",{className:"sr-only",children:" (opens in new tab)"})]}),a.jsx(ce,{icon:a.jsx(Sx,{}),render:a.jsx(t,{href:"/traces"}),variant:"primary",size:"sm",children:"View incoming traces"})]})]})]})})};function mUe(e){return a.jsx(rme,{...e})}async function vdr(e){const t=await fetch(e,{credentials:"include"});if(!t.ok)throw Object.assign(new Error(`Trace Intelligence request failed (${t.status})`),{status:t.status});return t.json()}const k2={cacheScope:"oss-studio",request:vdr,LinkComponent:"a",getTraceHref:e=>`/traces?traceId=${encodeURIComponent(e)}`,signalCatalog:FP},Yke=g.createContext(k2);function pa(){return g.useContext(Yke)}function ydr(e,t){const n=new URLSearchParams({entityType:t});return e(`/api/learning/entities?${n}`)}function xdr(e,t,n){const r=new URLSearchParams({entityType:n});return e(`/api/learning/entities/${encodeURIComponent(t)}/progress?${r}`)}function bjt(e,t,n,r,s,i,o=24){const l=new URLSearchParams({entityType:n,signalNames:r.join(","),presentation:"landmarks",limit:String(o)});return s&&l.set("from",s.toISOString()),i&&l.set("to",i.toISOString()),e(`/api/learning/entities/${encodeURIComponent(t)}/theme-snapshots?${l}`)}function wjt(e,t,n,r,s,i=8){const o=new URLSearchParams({entityType:n,signalNames:r.join(","),snapshotId:s,themeLimitPerStage:String(i)});return e(`/api/learning/entities/${encodeURIComponent(t)}/theme-flow?${o}`)}function bdr(e,t,n,r,s,i){const o=new URLSearchParams({entityType:n,signalName:r,snapshotId:s});return e(Xke(t,i,`?${o}`))}function a6(e){return e.map(t=>`${t.signalName}:${t.kind==="theme"?t.themeId:"noise"}`).join(",")}function wdr(e,t,n,r,s,i,o=20,l=0,c=[]){const u=new URLSearchParams({entityType:n,signalName:r,snapshotId:s,limit:String(o),offset:String(l)});return c.length>0&&u.set("filterThemes",a6(c)),e(Xke(t,i,`/examples?${u}`))}function Sdr(e,t,n,r,s,i=100){const o=new URLSearchParams({entityType:n,signalName:r,limit:String(i)});return e(Xke(t,s,`/history?${o}`))}function kdr(e,t,n,r,s){const i=new URLSearchParams({entityType:n,signalName:r,snapshotId:s});return e(kjt(t,`?${i}`))}function Odr(e,t,n,r,s,i=20,o=0,l=[]){const c=new URLSearchParams({entityType:n,signalName:r,snapshotId:s,limit:String(i),offset:String(o)});return l.length>0&&c.set("filterThemes",a6(l)),e(kjt(t,`/examples?${c}`))}async function Sjt(e,t,n,r,s){const i=await gUe(e,t,n,r,s,0),o=[...i.paths],l={...i.themes};let c=i.nextOffset;for(;c!==void 0;){const u=await gUe(e,t,n,r,s,c);o.push(...u.paths),Object.assign(l,u.themes),c=u.nextOffset}return{snapshot:i.snapshot,signals:i.signals,themes:l,paths:o}}function gUe(e,t,n,r,s,i){const o=new URLSearchParams({entityType:n,signalNames:r.join(","),snapshotId:s,limit:"500",offset:String(i)});return e(`/api/learning/entities/${encodeURIComponent(t)}/theme-paths?${o}`)}function jdr(e,t){return e(`/api/learning/traces/${encodeURIComponent(t)}/summary`)}function Xke(e,t,n){return`/api/learning/entities/${encodeURIComponent(e)}/themes/${encodeURIComponent(t)}${n}`}function kjt(e,t){return`/api/learning/entities/${encodeURIComponent(e)}/noise${t}`}function Ojt(e,t,n=!0){const{cacheScope:r,request:s}=pa();return Ct({queryKey:["entity-learning",r,t,e,"progress"],queryFn:()=>xdr(s,e??"",t),enabled:n&&!!e})}function jjt(e){const{cacheScope:t,request:n}=pa();return Ct({queryKey:["entity-learning",t,"entities",e],queryFn:()=>ydr(n,e)})}function Cjt(e,t,n,r,s){const{cacheScope:i,request:o}=pa(),l=r?.toISOString(),c=s?.toISOString();return Ct({queryKey:["entity-learning",i,t,e,"theme-snapshots",n,l,c],queryFn:()=>bjt(o,e,t,n,r,s),enabled:n.length>=2,staleTime:3e4})}const Cdr=.01;function _dr(e,t){return String(e[t.id])}function Tdr(e,t){const n=String(e[`${t.id}Label`]),r=e[`${t.id}Description`];return typeof r=="string"&&r.trim()?`${n}
257
+ `);for(const n of t)if(n.startsWith("data:")){const r=n.slice(5).trim();if(r)return JSON.parse(r)}throw new Error("No data found in SSE response")}return e.json()}async function rur(e,t){const n={...t,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},r=await fetch(e,{method:"POST",headers:n,credentials:"include",body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"mastra-playground",version:"1.0.0"}}})});if(!r.ok)throw new Error(`Initialize failed: ${r.status} ${r.statusText}`);const s=r.headers.get("Mcp-Session-Id");await aUe(r);const i={...n};s&&(i["Mcp-Session-Id"]=s),await fetch(e,{method:"POST",headers:i,credentials:"include",body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"})});const o=await fetch(e,{method:"POST",headers:i,credentials:"include",body:JSON.stringify({jsonrpc:"2.0",id:2,method:"tools/list"})});if(!o.ok)throw new Error(`tools/list failed: ${o.status} ${o.statusText}`);return{tools:(await aUe(o)).result?.tools??[]}}const sur=({queryOptions:e}={})=>{const t=Ke().options?.headers??{};return wn({mutationFn:n=>rur(n,t),...e})};function XOt({value:e,onValueChange:t,placeholder:n="Select an MCP server...",searchPlaceholder:r="Search MCP servers...",emptyText:s="No MCP servers found.",className:i,disabled:o=!1,variant:l,size:c,"aria-label":u,align:d,container:f}){const{data:h=[],isLoading:p,isError:m,error:v}=LP(),{navigate:y,paths:x}=Sn();g.useEffect(()=>{if(m){const k=v instanceof Error?v.message:"Failed to load MCP servers";Xe.error(`Error loading MCP servers: ${k}`)}},[m,v]);const b=h.map(k=>({label:k.name,value:k.id})),S=k=>{t?t(k):k&&k!==e&&y(x.mcpServerLink(k))};return a.jsx(fl,{options:b,value:e,onValueChange:S,placeholder:p?"Loading MCP servers...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||p||m,variant:l,size:c,"aria-label":u,align:d,container:f})}function iur(){const{serverId:e}=Cr(),{data:t,isLoading:n}=LP();return e?n?a.jsx(Fx,{}):t?.find(r=>r.id===e)?.name||e:null}function our(){const{serverId:e}=Cr();return e?a.jsx(XOt,{value:e,...MP,"aria-label":"Switch MCP server"}):null}const zP=({requestContext:e,queryOptions:t}={})=>{const n=Ke();return Ct({queryKey:["processors"],queryFn:()=>n.listProcessors(e),...t})},JOt=({processorId:e,requestContext:t,queryOptions:n})=>{const r=Ke();return Ct({queryKey:["processor",e],queryFn:()=>r.getProcessor(e).details(t),...n})},aur=({requestContext:e,queryOptions:t}={})=>{const n=Ke();return wn({mutationFn:async({processorId:r,phase:s,messages:i,agentId:o})=>n.getProcessor(r).execute({phase:s,messages:i,agentId:o,requestContext:e}),...t})};function lur({value:e,onValueChange:t,placeholder:n="Select a processor...",searchPlaceholder:r="Search processors...",emptyText:s="No processors found.",className:i,disabled:o=!1,variant:l,size:c,"aria-label":u,align:d}){const{data:f={},isLoading:h,isError:p,error:m}=zP(),{navigate:v,paths:y}=Sn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load processors";Xe.error(`Error loading processors: ${S}`)}},[p,m]);const x=Object.keys(f).filter(S=>{const k=f[S];return k?.phases&&k.phases.length>0}).map(S=>({label:f[S]?.name||S,value:S})),b=S=>{t?t(S):S&&S!==e&&(f[S]?.isWorkflow?v(y.workflowLink(S)+"/graph"):v(y.processorLink(S)))};return a.jsx(fl,{options:x,value:e,onValueChange:b,placeholder:h?"Loading processors...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||h||p,variant:l,size:c,"aria-label":u,align:d})}function cur(){const{processorId:e}=Cr(),{data:t,isLoading:n}=zP();return e?n?a.jsx(Fx,{}):t?.[e]?.name||e:null}function uur(){const{processorId:e}=Cr();return e?a.jsx(lur,{value:e,...MP,"aria-label":"Switch processor"}):null}const Goe=[400,401,403,404,501];function Cs(e){if(!e||typeof e!="object")return!1;if("status"in e&&e.status===401||"statusCode"in e&&e.statusCode===401)return!0;if("message"in e){const t=e.message;if(typeof t=="string")return/\bstatus:\s*401\b/.test(t)}return!1}function _s(e){if(!e||typeof e!="object")return!1;if("status"in e&&e.status===403||"statusCode"in e&&e.statusCode===403)return!0;if("message"in e){const t=e.message;if(typeof t=="string")return/\bstatus:\s*403\b/.test(t)}return!1}function Pk(e){if(!e||typeof e!="object")return!1;if("status"in e&&e.status===404||"statusCode"in e&&e.statusCode===404)return!0;if("message"in e){const t=e.message;if(typeof t=="string")return/\bstatus:\s*404\b/.test(t)}return!1}function s6(e,t){if(!e||typeof e!="object"||!("message"in e))return!1;const n=e.message;return typeof n!="string"?!1:n.includes(`does not support listing ${t}`)}const dur=["Observability storage domain is not available","Scores storage domain is not available"];function i6(e){if(!e||typeof e!="object"||!("message"in e))return!1;const t=e.message;return typeof t!="string"?!1:dur.some(n=>t.includes(n))}function ejt(e){if(!e||typeof e!="object")return!1;if("status"in e){const t=e.status;return Goe.includes(t)}if("statusCode"in e){const t=e.statusCode;return Goe.includes(t)}if("message"in e){const t=e.message;if(typeof t=="string")return Goe.some(n=>new RegExp(`\\bstatus:\\s*${n}\\b`).test(t))}return!1}function fur(e,t){return ejt(t)?!1:e<3}const hur=25,pur=15e3;function mur(e){return s6(e.state.error,"scores")||i6(e.state.error)?!1:pur}function gur(e,t,n){if(e?.pagination?.hasMore)return n+1}function vur(e){const t=new Set;return e.pages.flatMap(n=>n.scores??[]).filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const yur=({scorerId:e,entityId:t,entityType:n,queryOptions:r})=>{const s=Ke(),{inView:i,setRef:o}=X0(),l=Mm({queryKey:["scores",e,t,n],queryFn:({pageParam:f})=>s.listScoresByScorerId({scorerId:e,page:f,perPage:hur,entityId:t,entityType:n}),initialPageParam:0,getNextPageParam:gur,select:f=>vur(f),refetchInterval:mur,...r}),{hasNextPage:c,isFetchingNextPage:u,fetchNextPage:d}=l;return g.useEffect(()=>{i&&c&&!u&&d()},[i,c,u,d]),{...l,setEndOfListElement:o}},xur=e=>{const t=Ke(),[n,r]=g.useState(null),[s,i]=g.useState(!0),[o,l]=g.useState(null);return g.useEffect(()=>{(async()=>{i(!0),l(null);try{const u=await t.getScorer(e);r(u)}catch(u){r(null);const d=u instanceof Error?u:new Error("Error fetching scorer");l(d),console.error("Error fetching scorer",u)}finally{i(!1)}})()},[e,t]),{scorer:n,isLoading:s,error:o}},tjt=({requestContext:e,queryOptions:t}={})=>{const n=Ke();return Ct({queryKey:["scorers",e],queryFn:()=>n.listScorers(e),staleTime:0,gcTime:0,...t})},bur=15e3;function wur(e){return s6(e.state.error,"scores")||i6(e.state.error)?!1:bur}const Uke=({traceId:e="",spanId:t="",page:n,queryOptions:r})=>{const s=Ke();return Ct({queryKey:["trace-span-scores",e,t,n],queryFn:()=>s.listScoresBySpan({traceId:e,spanId:t,page:n||0,perPage:10}),refetchInterval:wur,gcTime:0,staleTime:0,...r})},Sur=({queryOptions:e}={})=>{const t=Ke();return wn({mutationFn:async({scorerName:n,traceId:r,spanId:s})=>await t.score({scorerName:n,targets:[{traceId:r,spanId:s}]}),...e})},njt=({scorerId:e,status:t,requestContext:n,queryOptions:r}={})=>{const s=Ke();return Ct({queryKey:["stored-scorer",e,t,n],queryFn:()=>e?s.getStoredScorer(e).details(n,{status:t}):null,...r})},rjt=({scorerId:e,requestContext:t,queryOptions:n}={})=>{const r=Ke(),s=mr();return{createStoredScorer:wn({mutationFn:i=>r.createStoredScorer(i),onSuccess:()=>{s.invalidateQueries({queryKey:["stored-scorers"]}),s.invalidateQueries({queryKey:["scorers"]})},...n?.createStoredScorer}),updateStoredScorer:wn({mutationFn:i=>{if(!e)throw new Error("scorerId is required for update");return r.getStoredScorer(e).update(i,t)},onSuccess:()=>{s.invalidateQueries({queryKey:["stored-scorers"]}),s.invalidateQueries({queryKey:["scorers"]}),e&&s.invalidateQueries({queryKey:["stored-scorer",e]})},...n?.updateStoredScorer}),deleteStoredScorer:wn({mutationFn:()=>{if(!e)throw new Error("scorerId is required for delete");return r.getStoredScorer(e).delete(t)},onSuccess:()=>{s.invalidateQueries({queryKey:["stored-scorers"]}),s.invalidateQueries({queryKey:["scorers"]}),e&&s.invalidateQueries({queryKey:["stored-scorer",e]})},...n?.deleteStoredScorer})}},sjt=({scorerId:e,params:t,requestContext:n,queryOptions:r})=>{const s=Ke();return Ct({queryKey:["scorer-versions",e,t,n],queryFn:()=>s.getStoredScorer(e).listVersions(t,n),...r})},kur=({scorerId:e,versionId:t,requestContext:n,queryOptions:r})=>{const s=Ke();return Ct({queryKey:["scorer-version",e,t,n],queryFn:()=>s.getStoredScorer(e).getVersion(t,n),...r})},Bx=(e,t)=>tjt({...e,requestContext:t});function Our({value:e,onValueChange:t,placeholder:n="Select a scorer...",searchPlaceholder:r="Search scorers...",emptyText:s="No scorers found.",className:i,disabled:o=!1,variant:l,size:c,"aria-label":u,align:d}){const{data:f={},isLoading:h,isError:p,error:m}=Bx(),{navigate:v,paths:y}=Sn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load scorers";Xe.error(`Error loading scorers: ${S}`)}},[p,m]);const x=Object.keys(f).map(S=>({label:f[S]?.scorer.config.name||S,value:S})),b=S=>{t?t(S):S&&S!==e&&v(y.scorerLink(S))};return a.jsx(fl,{options:x,value:e,onValueChange:b,placeholder:h?"Loading scorers...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||h||p,variant:l,size:c,"aria-label":u,align:d})}function jur(){const{scorerId:e}=Cr(),{data:t,isLoading:n}=Bx();return e?n?a.jsx(Fx,{}):t?.[e]?.scorer.config.name||e:null}function Cur(){const{scorerId:e}=Cr();return e?a.jsx(Our,{value:e,...MP,"aria-label":"Switch scorer"}):null}function _ur(){const{scorerId:e}=Cr(),{data:t,isLoading:n}=njt({scorerId:e,status:"draft",queryOptions:{enabled:!!e}});return e?n?a.jsx(Fx,{}):t?.name??"Scorer not found":null}const Vo=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 8.82265 8.51434",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M6.76646 6.16953C6.56909 6.10559 6.40521 5.96585 6.31087 5.78107C6.21653 5.5963 6.19945 5.38161 6.2634 5.18424C6.32735 4.98687 6.46708 4.82299 6.65186 4.72865C6.83663 4.63431 7.05132 4.61723 7.24869 4.68118C7.45933 4.74996 7.6849 4.75913 7.90043 4.70768C8.11596 4.65622 8.31306 4.54615 8.46992 4.38963C8.62678 4.23312 8.73729 4.03626 8.78921 3.82084C8.84114 3.60542 8.83246 3.37984 8.76414 3.16904C8.69582 2.95825 8.57052 2.77046 8.4021 2.62646C8.23368 2.48246 8.02871 2.38785 7.80986 2.35311C7.59101 2.31836 7.36681 2.34484 7.16208 2.4296C6.95734 2.51436 6.78004 2.6541 6.64979 2.83337C6.39274 3.18567 6.05613 3.47228 5.66736 3.66987C5.27858 3.86747 4.84864 3.97046 4.41254 3.97046C3.97643 3.97046 3.54649 3.86747 3.15772 3.66987C2.76895 3.47228 2.43234 3.18567 2.17528 2.83337C2.04528 2.65368 1.86807 2.51346 1.66329 2.42826C1.45852 2.34306 1.23415 2.3162 1.01505 2.35065C0.795944 2.3851 0.590648 2.47951 0.421892 2.62344C0.253137 2.76736 0.127507 2.95519 0.0589124 3.16611C-0.00968171 3.37703 -0.0185632 3.60282 0.0332514 3.81848C0.0850661 4.03414 0.195555 4.23125 0.352484 4.38799C0.509413 4.54472 0.706659 4.65497 0.92238 4.70652C1.1381 4.75808 1.36388 4.74892 1.57472 4.68007C1.77224 4.61634 1.98698 4.63369 2.1717 4.72829C2.35643 4.82289 2.49601 4.987 2.55973 5.18452C2.62346 5.38203 2.60611 5.59677 2.51151 5.7815C2.41691 5.96623 2.2528 6.10581 2.05528 6.16953C1.84456 6.23788 1.65684 6.36317 1.51288 6.53155C1.36893 6.69993 1.27434 6.90485 1.23959 7.12364C1.20483 7.34242 1.23126 7.56656 1.31596 7.77126C1.40065 7.97597 1.5403 8.15326 1.71948 8.28354C1.89865 8.41382 2.11036 8.49201 2.33121 8.50946C2.55205 8.52692 2.77342 8.48296 2.97083 8.38244C3.16825 8.28193 3.33402 8.12877 3.44981 7.93992C3.56561 7.75106 3.62692 7.53386 3.62697 7.31233C3.62697 7.10501 3.70933 6.90619 3.85592 6.7596C4.00251 6.613 4.20134 6.53065 4.40865 6.53065C4.61596 6.53065 4.81479 6.613 4.96138 6.7596C5.10797 6.90619 5.19033 7.10501 5.19033 7.31233C5.19027 7.53399 5.25152 7.75136 5.36731 7.94037C5.4831 8.12939 5.64892 8.2827 5.84642 8.38334C6.04392 8.48399 6.26541 8.52804 6.4864 8.51063C6.70738 8.49322 6.91924 8.41502 7.09854 8.28469C7.27785 8.15436 7.41761 7.97698 7.50237 7.77216C7.58713 7.56734 7.61359 7.34307 7.57882 7.12414C7.54404 6.90522 7.44939 6.70018 7.30534 6.53171C7.16128 6.36323 6.97344 6.23789 6.76257 6.16953H6.76646Z",fill:"currentColor"}),a.jsx("path",{d:"M4.41198 2.40337C5.07565 2.40337 5.61367 1.86536 5.61367 1.20168C5.61367 0.538012 5.07565 0 4.41198 0C3.74831 0 3.2103 0.538012 3.2103 1.20168C3.2103 1.86536 3.74831 2.40337 4.41198 2.40337Z",fill:"currentColor"})]}),ijt=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 8.64637 9.45103",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{d:"M7.80735 5.87241C7.63209 5.97219 7.43696 6.06166 7.22844 6.13866C6.46456 6.42068 5.43714 6.58649 4.32296 6.58649C3.20873 6.58649 2.18135 6.4207 1.41747 6.13866C1.20889 6.06164 1.01385 5.97223 0.838558 5.87241V7.59003C0.838558 7.62341 0.855765 7.70759 1.00172 7.83512C1.14707 7.96201 1.38219 8.09563 1.70829 8.21605C2.3572 8.45563 3.28149 8.61268 4.32296 8.61269C5.36456 8.61269 6.28937 8.45568 6.9383 8.21605C7.26428 8.09566 7.49888 7.96198 7.64419 7.83512C7.79024 7.70754 7.80735 7.62342 7.80735 7.59003V5.87241ZM7.80735 3.00789C7.63214 3.10763 7.4369 3.19647 7.22844 3.27345C6.46455 3.55549 5.43719 3.72129 4.32296 3.72129C3.20868 3.72128 2.18136 3.55552 1.41747 3.27345C1.20896 3.19645 1.01381 3.10766 0.838558 3.00789V4.72551C0.838558 4.7589 0.855657 4.84301 1.00172 4.97059C1.14707 5.09749 1.38219 5.23111 1.70829 5.35153C2.3572 5.59109 3.28154 5.74747 4.32296 5.74748C5.36456 5.74748 6.28937 5.59116 6.9383 5.35153C7.26432 5.23112 7.49887 5.09747 7.64419 4.97059C7.7536 4.87505 7.79089 4.80404 7.80257 4.76033L7.80735 4.72551V3.00789ZM7.80735 1.86099C7.80735 1.82758 7.79045 1.74291 7.64419 1.61522C7.49887 1.48838 7.26421 1.35534 6.9383 1.23497C6.28937 0.995339 5.36456 0.838331 4.32296 0.838331C3.28149 0.83834 2.3572 0.995383 1.70829 1.23497C1.38219 1.35539 1.14707 1.48832 1.00172 1.61522C0.855475 1.7429 0.838558 1.82758 0.838558 1.86099C0.838673 1.89462 0.855968 1.97882 1.00172 2.10607C1.14707 2.23297 1.38219 2.3659 1.70829 2.48632C2.3572 2.7259 3.28149 2.88295 4.32296 2.88296C5.36456 2.88296 6.28937 2.72595 6.9383 2.48632C7.26421 2.36595 7.49887 2.23291 7.64419 2.10607C7.78996 1.97881 7.80724 1.89462 7.80735 1.86099ZM8.64637 7.59003C8.64637 7.95465 8.44458 8.25006 8.1958 8.46728C7.94608 8.68529 7.60876 8.86274 7.22844 9.00318C6.46455 9.28522 5.43718 9.45102 4.32296 9.45102C3.20869 9.45101 2.18135 9.28525 1.41747 9.00318C1.03715 8.86274 0.699831 8.68529 0.450113 8.46728C0.201377 8.25007 0.000227451 7.9546 0.000227451 7.59003V1.86099C0.000227451 1.49643 0.201388 1.20095 0.450113 0.983742C0.699831 0.765728 1.03715 0.588275 1.41747 0.447838C2.18136 0.165769 3.20868 8.74396e-06 4.32296 0C5.43719 0 6.46455 0.165797 7.22844 0.447838C7.60876 0.588275 7.94608 0.765728 8.1958 0.983742C8.44457 1.20096 8.64637 1.49638 8.64637 1.86099V7.59003Z",fill:"currentColor"})}),Tur=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 9.83952 9.3295",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.67171 0.838331H6.70163V4.05307L9.68767 8.09999C10.0634 8.6093 9.69869 9.32932 9.06643 9.3295H0.772551C0.140289 9.3293 -0.223777 8.60929 0.151995 8.09999L3.13804 4.05307V0.838331H2.17136V0H7.67171V0.838331ZM3.97705 4.32955L3.89513 4.44015L2.34681 6.53802H7.49285L5.94453 4.44015L5.86261 4.32955V0.860859H3.97705V4.32955Z",fill:"currentColor"})}),Iur=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 10.0412 8.39395",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M0 0.916539C0 0.410349 0.410349 0 0.916539 0C1.42273 0 1.83308 0.410349 1.83308 0.916539C1.83308 1.42273 1.42273 1.83308 0.916539 1.83308C0.410349 1.83308 0 1.42273 0 0.916539Z",fill:"currentColor"}),a.jsx("path",{d:"M2.88569 0.916539C2.88569 0.410349 3.29604 0 3.80223 0C4.30842 0 4.71877 0.410349 4.71877 0.916539C4.71877 1.42273 4.30842 1.83308 3.80223 1.83308C3.29604 1.83308 2.88569 1.42273 2.88569 0.916539Z",fill:"currentColor"}),a.jsx("path",{d:"M5.77139 0.916539C5.77139 0.410349 6.18174 0 6.68793 0H9.12465C9.63084 0 10.0412 0.410349 10.0412 0.916539C10.0412 1.42273 9.63084 1.83308 9.12465 1.83308H6.68793C6.18174 1.83308 5.77139 1.42273 5.77139 0.916539Z",fill:"currentColor"}),a.jsx("path",{d:"M0 4.19696C0 3.69077 0.410351 3.28042 0.916541 3.28042C1.42273 3.28042 1.83308 3.69077 1.83308 4.19696C1.83308 4.70315 1.42273 5.1135 0.916541 5.1135C0.410351 5.1135 0 4.70315 0 4.19696Z",fill:"currentColor"}),a.jsx("path",{d:"M2.8857 4.19694C2.8857 3.69075 3.29605 3.2804 3.80224 3.2804C4.30843 3.2804 4.71877 3.69075 4.71877 4.19694C4.71877 4.70313 4.30843 5.11348 3.80224 5.11348C3.29605 5.11348 2.8857 4.70313 2.8857 4.19694Z",fill:"currentColor"}),a.jsx("path",{d:"M5.77139 4.19694C5.77139 3.69075 6.18174 3.2804 6.68793 3.2804H9.12466C9.63085 3.2804 10.0412 3.69075 10.0412 4.19694C10.0412 4.70313 9.63085 5.11348 9.12466 5.11348H6.68793C6.18174 5.11348 5.77139 4.70313 5.77139 4.19694Z",fill:"currentColor"}),a.jsx("path",{d:"M0 7.47738C0 6.97119 0.410351 6.56084 0.916541 6.56084C1.42273 6.56084 1.83308 6.97119 1.83308 7.47738C1.83308 7.98357 1.42273 8.39392 0.916541 8.39392C0.410351 8.39392 0 7.98357 0 7.47738Z",fill:"currentColor"}),a.jsx("path",{d:"M2.8857 7.47741C2.8857 6.97122 3.29605 6.56087 3.80224 6.56087C4.30843 6.56087 4.71877 6.97122 4.71877 7.47741C4.71877 7.9836 4.30843 8.39395 3.80224 8.39395C3.29605 8.39395 2.8857 7.9836 2.8857 7.47741Z",fill:"currentColor"}),a.jsx("path",{d:"M5.77139 7.47741C5.77139 6.97122 6.18174 6.56087 6.68793 6.56087H9.12466C9.63085 6.56087 10.0412 6.97122 10.0412 7.47741C10.0412 7.9836 9.63085 8.39395 9.12466 8.39395H6.68793C6.18174 8.39395 5.77139 7.9836 5.77139 7.47741Z",fill:"currentColor"})]}),F_=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 9.52233 10.4982",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M2.39065 4.27882L4.93898 1.73049C5.10578 1.56368 5.37622 1.56368 5.54303 1.73049C5.70983 1.89729 5.70983 2.16773 5.54303 2.33454L2.9947 4.88287C2.53924 5.33834 2.53929 6.0768 2.99475 6.53226C3.45022 6.9877 4.18863 6.98771 4.64409 6.53226L7.19242 3.98393C7.35922 3.81713 7.62967 3.81714 7.79647 3.98393C7.96328 4.15074 7.96328 4.42118 7.79647 4.58798L5.24814 7.13631C4.45907 7.92537 3.17978 7.92536 2.39071 7.13631C1.60163 6.34724 1.60158 5.0679 2.39065 4.27882Z",fill:"currentColor"}),a.jsx("path",{d:"M3.50354 5.43862C3.5236 5.3983 3.55044 5.36049 3.58404 5.32688L6.06565 2.84527C6.52112 2.3898 6.52112 1.65128 6.06565 1.19581C5.61018 0.740366 4.87172 0.740412 4.41626 1.19587L0.729138 4.88287C0.562334 5.04967 0.291892 5.04968 0.125089 4.88287C-0.0416875 4.71607 -0.0417052 4.44562 0.125089 4.27882L3.81221 0.591824C4.60128 -0.197241 5.88062 -0.197289 6.6697 0.591765C7.12856 1.05062 7.32058 1.67529 7.24578 2.27292C7.84449 2.19687 8.47073 2.38872 8.93052 2.84849C9.7196 3.63757 9.7196 4.91697 8.93052 5.70605L8.20316 6.44191L6.20449 8.44058C5.83765 8.80741 5.83765 9.40219 6.20449 9.76902C6.37128 9.93582 6.37129 10.2063 6.20449 10.3731C6.03769 10.5399 5.76724 10.5399 5.60044 10.3731C4.9 9.67263 4.9 8.53697 5.60044 7.83653L7.59911 5.83786L8.32647 5.102C8.78194 4.64653 8.78194 3.90801 8.32647 3.45254C7.871 2.9971 7.13254 2.99714 6.67707 3.4526L4.17576 5.95392C4.00896 6.12072 3.73851 6.12071 3.57171 5.95392C3.43204 5.81425 3.40932 5.60193 3.50354 5.43862Z",fill:"currentColor"})]}),Eur=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 8.98824 8.33142",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M5.70011e-05 6.409V0H1.04865V6.409C1.04875 6.89152 1.43994 7.28283 1.92248 7.28283H8.3581V8.33142H1.92248C0.860814 8.33142 0.000149953 7.47065 5.70011e-05 6.409Z",fill:"currentColor"}),a.jsx("path",{d:"M8.08006 0.945713C8.27714 0.733828 8.6087 0.72151 8.82077 0.918405C9.03289 1.11551 9.04518 1.44767 8.84808 1.6598L6.08595 4.63218C5.90127 4.83085 5.59525 4.85557 5.38074 4.68953L4.03177 3.64571L2.74765 5.07183C2.55386 5.28688 2.22206 5.30441 2.00694 5.11074C1.79189 4.91695 1.77435 4.58515 1.96803 4.37003L3.57915 2.58278L3.65357 2.51451C3.83887 2.37494 4.09997 2.37165 4.28982 2.51861L5.64358 3.56652L8.08006 0.945713Z",fill:"currentColor"})]});function aj(e){return a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 10.123 10.123",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M4.50195 1.53809H5.62109V0H6.75098V1.53809H7.5293L7.64258 1.54395C8.19939 1.60066 8.63379 2.0708 8.63379 2.64258V3.37305H10.123V4.50195H8.63379V5.62109H10.123V6.75H8.63379V7.57812L8.62891 7.69141C8.57589 8.2109 8.16211 8.62387 7.64258 8.67676L7.5293 8.68262H6.75098V10.123H5.62109V8.68262H4.50195V10.123H3.37305V8.68262H2.59375L2.48047 8.67676C1.96102 8.62383 1.54817 8.21082 1.49512 7.69141L1.48926 7.57812V6.75H0V5.62109H1.48926V4.50195H0V3.37305H1.48926V2.64258C1.48926 2.07084 1.92371 1.60071 2.48047 1.54395L2.59375 1.53809H3.37305V0H4.50195V1.53809ZM2.61914 7.55273H7.50488V2.66699H2.61914V7.55273Z",fill:"currentColor"})})}const Nur=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 11.185 11.185",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M9.57258 2.71626C9.57245 2.19794 9.14778 1.77075 8.61819 1.77075H2.56605C2.0377 1.77075 1.61179 2.19752 1.61165 2.71626V6.51162C1.61179 7.02856 2.03401 7.45487 2.5616 7.45713L3.12802 7.45935V9.21487L5.52178 7.55857L5.66764 7.45713H8.61819C9.14653 7.45713 9.57245 7.03036 9.57258 6.51162V2.71626ZM10.7099 6.51162C10.7097 7.66541 9.76766 8.59441 8.61819 8.59441H6.0223L3.51081 10.3336C3.25841 10.5083 2.86505 10.6555 2.4809 10.4558C2.09483 10.2551 1.99075 9.84577 1.99075 9.53473V8.51222C1.11705 8.26321 0.474488 7.46395 0.474378 6.51162V2.71626C0.474511 1.56248 1.41657 0.633479 2.56605 0.633479H8.61819C9.77051 0.633479 10.7097 1.56448 10.7099 2.71626V6.51162Z",fill:"currentColor"})}),rw=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 8.94379 8.92126",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M6.13251 5.43413C6.51629 5.43413 6.82744 5.74533 6.82748 6.1291C6.82748 6.5129 6.51631 6.82407 6.13251 6.82407C5.74877 6.824 5.43754 6.51286 5.43754 6.1291C5.43759 5.74537 5.74879 5.4342 6.13251 5.43413Z",fill:"currentColor"}),a.jsx("path",{d:"M5.92771 2.29722C6.13122 2.09376 6.46147 2.09379 6.665 2.29722C6.86843 2.50075 6.86846 2.831 6.665 3.03451L3.03724 6.66227C2.83373 6.86578 2.5035 6.86572 2.29995 6.66227C2.0965 6.45872 2.09644 6.12849 2.29995 5.92498L5.92771 2.29722Z",fill:"currentColor"}),a.jsx("path",{d:"M2.842 2.12791C3.22572 2.12799 3.53694 2.43914 3.53696 2.82288C3.53696 3.20664 3.22573 3.51777 2.842 3.51785C2.45819 3.51785 2.14703 3.20668 2.14703 2.82288C2.14705 2.4391 2.45821 2.12791 2.842 2.12791Z",fill:"currentColor"}),a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.38455 0.00887484C8.26052 0.0979278 8.94379 0.837945 8.94379 1.73742V7.18384C8.94369 8.08322 8.26046 8.82334 7.38455 8.91238L7.20705 8.92126H1.73742L1.55992 8.91238C0.683828 8.82351 0.000101213 8.08336 0 7.18384V1.73742C0 0.837813 0.683761 0.0977507 1.55992 0.00887484L1.73742 0H7.20705L7.38455 0.00887484ZM1.73742 0.839013C1.24121 0.839013 0.839013 1.24121 0.839013 1.73742V7.18384C0.839121 7.67996 1.24128 8.08293 1.73742 8.08293H7.20705C7.70305 8.08276 8.10535 7.67985 8.10546 7.18384V1.73742C8.10546 1.24131 7.70312 0.83918 7.20705 0.839013H1.73742Z",fill:"currentColor"})]}),Aur=e=>a.jsx("svg",{width:"17",height:"18",viewBox:"0 0 17 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M8.40864 11.9983C7.58064 11.9733 6.84164 11.6153 6.31564 11.0563C6.31464 11.0563 6.31464 11.0553 6.31464 11.0553C5.78864 10.4963 5.47564 9.73633 5.50064 8.90833C5.52564 8.08033 5.88464 7.34133 6.44364 6.81533C7.00264 6.28833 7.76264 5.97633 8.59064 6.00133C9.41864 6.02633 10.1576 6.38433 10.6836 6.94333H10.6846C11.2106 7.50333 11.5236 8.26233 11.4986 9.09033C11.4726 9.91833 11.1146 10.6583 10.5556 11.1843C9.99664 11.7103 9.23664 12.0233 8.40864 11.9983ZM16.1266 8.15033L14.3606 7.74033C14.2316 7.14133 14.0146 6.57633 13.7216 6.05733L14.7726 4.57933C14.9116 4.38533 14.8926 4.12033 14.7296 3.94633L13.9206 3.08733C13.7576 2.91333 13.4946 2.87933 13.2916 3.00533L11.7526 3.96533C11.2526 3.64133 10.7016 3.39033 10.1116 3.22633L9.80964 1.43833C9.76964 1.20333 9.56964 1.02833 9.33164 1.02133L8.15264 0.985326C7.91364 0.978326 7.70364 1.14033 7.64964 1.37233L7.24064 3.13933C6.64164 3.26733 6.07664 3.48433 5.55664 3.77733L4.07864 2.72633C3.88464 2.58833 3.61964 2.60633 3.44664 2.76933L2.58664 3.57833C2.41364 3.74133 2.37964 4.00533 2.50564 4.20733L3.46564 5.74633C3.14164 6.24633 2.89064 6.79833 2.72564 7.38833L0.937635 7.68933C0.702635 7.72933 0.528635 7.92933 0.520635 8.16733L0.485635 9.34733C0.477635 9.58533 0.639635 9.79533 0.872635 9.84933L2.63864 10.2583C2.76764 10.8573 2.98464 11.4233 3.27764 11.9423L2.22564 13.4203C2.08764 13.6143 2.10564 13.8793 2.26964 14.0523L3.07864 14.9123C3.24164 15.0853 3.50464 15.1203 3.70664 14.9933L5.24564 14.0333C5.74663 14.3583 6.29764 14.6093 6.88764 14.7733L7.18964 16.5613C7.22864 16.7963 7.42864 16.9713 7.66764 16.9783L8.84663 17.0143C9.08564 17.0213 9.29564 16.8593 9.34964 16.6273L9.75864 14.8603C10.3576 14.7323 10.9226 14.5153 11.4416 14.2213L12.9206 15.2733C13.1146 15.4113 13.3786 15.3933 13.5526 15.2293L14.4116 14.4213C14.5856 14.2573 14.6196 13.9943 14.4936 13.7923L13.5336 12.2533C13.8576 11.7523 14.1086 11.2013 14.2726 10.6113L16.0616 10.3103C16.2966 10.2703 16.4706 10.0703 16.4776 9.83233L16.5136 8.65233C16.5206 8.41433 16.3586 8.20433 16.1266 8.15033Z",fill:"currentColor"})}),fd=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 11.185 11.185",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.0293 1.16491L4.81958 0.801671L4.81955 0.801686L5.0293 1.16491ZM5.75391 1.16491L5.96365 0.801686L5.96363 0.801671L5.75391 1.16491ZM9.04492 3.06531L9.25474 2.70212L9.25467 2.70208L9.04492 3.06531ZM9.40723 7.49304L9.82666 7.49332V7.49304H9.40723ZM9.04492 8.11999L8.8352 7.75675L8.83518 7.75676L9.04492 8.11999ZM5.75391 10.0204L5.96363 10.3836L5.96365 10.3836L5.75391 10.0204ZM5.0293 10.0204L4.81955 10.3836L4.81963 10.3837L5.0293 10.0204ZM1.73828 8.11999L1.94803 7.75676L1.948 7.75675L1.73828 8.11999ZM1.37598 7.49304H0.956538L0.956538 7.49332L1.37598 7.49304ZM1.73828 3.06531L1.94802 3.42854L1.94803 3.42853L1.73828 3.06531ZM5.59277 3.38366L5.59283 2.96423H5.59277V3.38366ZM3.38379 5.59167L2.96435 5.59159V5.59167H3.38379ZM5.59277 7.80066V8.2201H5.59283L5.59277 7.80066ZM7.80078 5.59167H8.22022V5.59159L7.80078 5.59167ZM5.0293 1.16491L5.23902 1.52816C5.33331 1.47372 5.44989 1.47372 5.54419 1.52816L5.75391 1.16491L5.96363 0.801671C5.60978 0.59738 5.17342 0.59738 4.81958 0.801671L5.0293 1.16491ZM5.75391 1.16491L5.54416 1.52814L8.83518 3.42853L9.04492 3.06531L9.25467 2.70208L5.96365 0.801686L5.75391 1.16491ZM9.04492 3.06531L8.83511 3.42849C8.92979 3.48319 8.98779 3.5839 8.98779 3.69226H9.40723H9.82666C9.82666 3.28328 9.60799 2.90619 9.25474 2.70212L9.04492 3.06531ZM9.40723 3.69226H8.98779V7.49304H9.40723H9.82666V3.69226H9.40723ZM9.40723 7.49304L8.98779 7.49276C8.98772 7.6015 8.92949 7.70231 8.8352 7.75675L9.04492 8.11999L9.25464 8.48324C9.60821 8.2791 9.82639 7.90167 9.82666 7.49332L9.40723 7.49304ZM9.04492 8.11999L8.83518 7.75676L5.54416 9.65715L5.75391 10.0204L5.96365 10.3836L9.25467 8.48322L9.04492 8.11999ZM5.75391 10.0204L5.54419 9.65714C5.44996 9.71154 5.33331 9.71156 5.23897 9.65711L5.0293 10.0204L4.81963 10.3837C5.17339 10.5878 5.60977 10.5879 5.96363 10.3836L5.75391 10.0204ZM5.0293 10.0204L5.23904 9.65715L1.94803 7.75676L1.73828 8.11999L1.52854 8.48322L4.81955 10.3836L5.0293 10.0204ZM1.73828 8.11999L1.948 7.75675C1.85371 7.70231 1.79549 7.6015 1.79541 7.49276L1.37598 7.49304L0.956538 7.49332C0.956809 7.90167 1.17499 8.2791 1.52856 8.48324L1.73828 8.11999ZM1.37598 7.49304H1.79542V3.69226H1.37598H0.956538V7.49304H1.37598ZM1.37598 3.69226H1.79542C1.79542 3.58378 1.85339 3.48318 1.94802 3.42854L1.73828 3.06531L1.52854 2.70207C1.17507 2.90617 0.956538 3.2833 0.956538 3.69226H1.37598ZM1.73828 3.06531L1.94803 3.42853L5.23904 1.52814L5.0293 1.16491L4.81955 0.801686L1.52854 2.70208L1.73828 3.06531ZM5.59277 3.38366V2.96423C4.14162 2.96423 2.96463 4.14015 2.96435 5.59159L3.38379 5.59167L3.80323 5.59175C3.80342 4.60382 4.60458 3.8031 5.59277 3.8031V3.38366ZM3.38379 5.59167H2.96435C2.96435 7.04322 4.14132 8.2201 5.59277 8.2201V7.80066V7.38122C4.6046 7.38122 3.80323 6.57991 3.80323 5.59167H3.38379ZM5.59277 7.80066L5.59283 8.2201C7.04429 8.2199 8.22022 7.04294 8.22022 5.59167H7.80078H7.38134C7.38134 6.57999 6.58061 7.38108 5.59272 7.38122L5.59277 7.80066ZM7.80078 5.59167L8.22022 5.59159C8.21994 4.14043 7.04398 2.96443 5.59283 2.96423L5.59277 3.38366L5.59272 3.8031C6.58062 3.80324 7.38115 4.60374 7.38134 5.59175L7.80078 5.59167Z",fill:"currentColor"})}),Sx=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 9.45892 8.88606",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M8.53702 7.36403C8.98547 7.36403 9.34918 7.70502 9.34918 8.12535C9.34906 8.54559 8.9854 8.88606 8.53702 8.88606H5.6839C5.23552 8.88606 4.87186 8.54559 4.87174 8.12535C4.87174 7.70502 5.23545 7.36403 5.6839 7.36403H8.53702Z",fill:"currentColor"}),a.jsx("path",{d:"M8.53702 3.67209C8.98547 3.67209 9.34918 4.01309 9.34918 4.43342C9.34911 4.8537 8.98543 5.19413 8.53702 5.19413H5.6839C5.23549 5.19413 4.87181 4.8537 4.87174 4.43342C4.87174 4.01309 5.23545 3.67209 5.6839 3.67209H8.53702Z",fill:"currentColor"}),a.jsx("path",{d:"M8.67155 0C9.10635 2.06584e-05 9.45892 0.341006 9.45892 0.761326C9.45878 1.18153 9.10627 1.52201 8.67155 1.52203H2.88163C2.4469 1.52203 2.0944 1.18154 2.09427 0.761326C2.09427 0.340993 2.44681 3.80132e-08 2.88163 0H8.67155Z",fill:"currentColor"}),a.jsx("path",{d:"M0.757606 0.760086V4.01122H3.50594V4.76883H0.759466L0.762566 5.4291C0.76837 6.70703 1.8058 7.73972 3.08374 7.73973H3.67953V8.49796H3.08374C1.38863 8.49795 0.0120204 7.1273 0.00433981 5.4322L0 4.39188V0.760086H0.757606Z",fill:"currentColor"})]}),Pur=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 9.55888 8.30616",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{d:"M0 7.18794V1.11823C-4.80684e-08 0.5005 0.5005 2.79299e-06 1.11823 0H3.17924C3.48658 0 3.78038 0.126314 3.99163 0.349532L5.09347 1.5135C5.14625 1.56923 5.21948 1.60085 5.29623 1.60088H8.44065C9.05838 1.60088 9.55888 2.10206 9.55888 2.7198V7.18794C9.55888 7.80567 9.05838 8.30616 8.44065 8.30616H1.11823C0.500524 8.30614 4.41663e-06 7.80565 0 7.18794ZM0.838331 7.18794C0.838332 7.34235 0.963819 7.46781 1.11823 7.46783H8.44065C8.59509 7.46783 8.72055 7.34237 8.72055 7.18794V2.7198C8.72055 2.56536 8.59509 2.4399 8.44065 2.4399H5.29623C4.98896 2.43986 4.69506 2.31353 4.48384 2.09037L3.38268 0.925714C3.32987 0.869949 3.25604 0.838331 3.17924 0.838331H1.11823C0.963799 0.838334 0.838331 0.963798 0.838331 1.11823V7.18794Z",fill:"currentColor"})}),$ur=typeof window<"u"&&window.MASTRA_SIGNALS_UI==="true",Rur={name:"Intelligence",url:"/intelligence",activePaths:["/intelligence"],Icon:lpt,isOnMastraPlatform:!0,hidden:!$ur},qke=[{key:"primitives",title:"Primitives",items:[{name:"Agents",url:"/agents",Icon:Vo,isOnMastraPlatform:!0},{name:"Prompts",url:"/prompts",Icon:Nur,isOnMastraPlatform:!0},{name:"Workflows",url:"/workflows",Icon:jl,isOnMastraPlatform:!0},{name:"Processors",url:"/processors",Icon:aj,isOnMastraPlatform:!1,foldable:!0},{name:"MCP Servers",url:"/mcps",Icon:F_,isOnMastraPlatform:!0,foldable:!0},{name:"Tools",url:"/tools",Icon:fd,isOnMastraPlatform:!0,foldable:!0},{name:"Workspaces",url:"/workspaces",Icon:Pur,isOnMastraPlatform:!0,foldable:!0}]},{key:"evaluation",title:"Evaluation",items:[{name:"Scorers",url:"/scorers",Icon:rw,isOnMastraPlatform:!0},{name:"Datasets",url:"/datasets",Icon:ijt,isOnMastraPlatform:!0},{name:"Experiments",url:"/experiments",Icon:Tur,isOnMastraPlatform:!0},{name:"Review Queue",url:"/experiments/review-queue",Icon:Jht,isOnMastraPlatform:!0}]},{key:"observability",title:"Observability",items:[{name:"Metrics",url:"/metrics",Icon:Eur,isOnMastraPlatform:!0},{name:"Traces",url:"/traces",Icon:Sx,isOnMastraPlatform:!0},Rur,{name:"Logs",url:"/logs",Icon:Iur,isOnMastraPlatform:!0}]}],Qke=[{name:"Settings",url:"/settings",Icon:Aur,isOnMastraPlatform:!1},{name:"Resources",url:"/resources",Icon:Zht,isOnMastraPlatform:!0}],Mur=[...qke.flatMap(e=>e.items),...Qke];function Dur(e){return Mur.find(t=>t.url===e)}function Ts(e,t){const n=Dur(e);if(!n)throw new Error(`navCrumb: unknown nav url "${e}"`);return{id:`nav:${e}`,label:n.name,icon:n.Icon,to:e,...t}}const Zke=e=>{if(!e)return"";try{return decodeURIComponent(e)}catch{return e}},ojt=e=>{const t=Zke(e);return t.length>8?`${t.slice(0,8)}...`:t},ajt={id:"agent",Component:Dcr,Switcher:Lcr},Lur={id:"scorer",Component:jur,Switcher:Cur},zur={id:"processor",Component:cur,Switcher:uur},Fur={id:"mcp-server",Component:iur,Switcher:our},lUe={id:"workflow",Component:lcr,Switcher:ccr},MK={id:"dataset",Component:Xcr,Switcher:Jcr},ljt={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",diff:"diff",patch:"diff",css:"css",scss:"css",html:"html",htm:"html",xml:"xml",svg:"xml",sql:"sql"};let Koe=null;function Bur(){return Koe||(Koe=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Ai(()=>import("./core-BIZ7yKXS.js"),__vite__mapDeps([0,1,2,3,4]),import.meta.url),Ai(()=>import("./engine-javascript-DSQaR0Yq.js"),__vite__mapDeps([5,2,3]),import.meta.url)]);return e({themes:[Ai(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Ai(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Ai(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Ai(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Ai(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Ai(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Ai(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Ai(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Ai(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Ai(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Ai(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Ai(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Ai(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Ai(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([6,7,8]),import.meta.url),Ai(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Ai(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Koe}async function Vur(e,t){const n=ljt[t?.toLowerCase()];if(!n)return null;const r=await Bur(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function cjt(e){const t=e?.split(".").pop()?.toLowerCase();return t?ljt[t]:void 0}let cUe;const ujt=()=>cUe??=Promise.all([Ai(()=>import("./standalone-Dfz2oS5J.js"),[],import.meta.url),Ai(()=>import("./babel-lWBcy2sH.js"),[],import.meta.url),Ai(()=>import("./estree-Dd9JfUIE.js"),[],import.meta.url)]).catch(e=>{throw cUe=void 0,e}),T5=async e=>{const[t,n,r]=await ujt();return await t.format(e,{semi:!1,parser:"json",printWidth:80,tabWidth:2,plugins:[n,r]})},djt=async e=>{const[t,n,r]=await ujt();return await t.format(e,{parser:"babel-ts",printWidth:80,tabWidth:2,plugins:[n,r]})},CQ=e=>{try{const t=JSON.parse(e);return!!t&&typeof t=="object"}catch{return!1}},Uur=ji(vt(),Q2n());function Yoe(e,t){if(!e)return"__custom__";for(const[n,r]of Object.entries(e))if(JSON.stringify(r)===t)return n;return"__custom__"}function qur(e){try{return JSON.stringify(JSON.parse(e))}catch{return null}}const fjt=({label:e,presets:t,value:n,onSave:r,editorClassName:s="h-[400px]",labelTooltip:i,headerActions:o})=>{const l=JSON.stringify(n??{}),c=JSON.stringify(n??{},null,2),[u,d]=g.useState(c),[f,h]=g.useState(c),[p,m]=g.useState(()=>Yoe(t,l)),{handleCopy:v}=Vm({text:u}),[y,x]=g.useState(l);y!==l&&(x(l),d(c),h(c),m(Yoe(t,l)));const b=g.useMemo(()=>{const N=qur(u);return N?N!==l:u!==f},[l,u,f]),S=()=>{let N;try{N=JSON.parse(u)}catch{Xe.error("Invalid JSON");return}const E=Uur.safeParse(N);if(!E.success){Xe.error(`${e} must be a JSON object`);return}r(E.data)},k=()=>{d(f),m(Yoe(t,l))},j=Z(Zn,In),C=async()=>{if(!CQ(u)){Xe.error("Invalid JSON");return}const N=await T5(u);d(N)},T=async N=>{if(m(N),N==="__custom__"||!t)return;const E=t[N];if(E){const A=await T5(JSON.stringify(E));d(A)}},_=N=>{d(N),p!=="__custom__"&&m("__custom__")};return a.jsx(Wc,{children:a.jsxs("div",{children:[a.jsxs(pt,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs(dt,{info:i,children:[e," (JSON)"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[o,a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:C,className:j,children:a.jsx(At,{children:a.jsx(Va,{})})})}),a.jsxs(Bn,{children:["Format the ",e," JSON"]})]}),a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:v,className:j,children:a.jsx(At,{children:a.jsx(Lm,{})})})}),a.jsxs(Bn,{children:["Copy ",e]})]})]})]}),t&&Object.keys(t).length>0&&a.jsxs(pt,{children:[a.jsxs(dt,{className:"sr-only",children:[e," preset"]}),a.jsxs(ms,{value:p,onValueChange:T,children:[a.jsx(vs,{children:a.jsx(gs,{placeholder:"Select a preset..."})}),a.jsxs(ys,{children:[a.jsx(hr,{value:"__custom__",children:"Custom"}),Object.keys(t).map(N=>a.jsx(hr,{value:N,children:N},N))]})]})]}),a.jsx(Or,{value:u,onChange:_,showCopyButton:!1,className:s})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[b&&a.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:`Revert ${e} changes`,onClick:k,children:a.jsx(Mn,{})}),a.jsx(ce,{icon:a.jsx(ur,{}),type:"button",onClick:S,children:"Save"})]})]})})},Qur={align:"shift"};function hjt({label:e,icon:t,open:n,onOpenChange:r,children:s}){return a.jsxs(jp,{open:n,onOpenChange:r,children:[a.jsx(of,{variant:"ghost",size:"icon-md",type:"button",tooltip:e,"aria-label":e,children:t}),a.jsx(ah,{align:"start",collisionAvoidance:Qur,className:"w-[min(480px,calc(100vw-2rem))] p-0",children:a.jsx("div",{onSubmit:i=>i.stopPropagation(),children:a.jsx(jr,{className:"w-full",maxHeight:"min(600px, calc(100dvh - 8rem))",children:a.jsx("div",{className:"space-y-4 p-4",children:s})})})})]})}function Zur(){return g.useMemo(()=>{const e=typeof window<"u"?window.MASTRA_REQUEST_CONTEXT_PRESETS:void 0;if(!e||e==="%%MASTRA_REQUEST_CONTEXT_PRESETS%%")return null;try{const t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}catch{console.warn("Failed to parse request context presets")}return null},[])}function Wke({entityType:e,entityId:t}){const[n,r]=g.useState(!1),[s,i]=xr(e,t),o=Zur(),l=c=>{i(c),Xe.success("Request context saved locally"),r(!1)};return a.jsx(hjt,{label:"Request context",icon:a.jsx(MIn,{}),open:n,onOpenChange:r,children:a.jsx(fjt,{label:"Request Context",presets:o,value:s,onSave:l,editorClassName:"h-[260px]"})})}function pjt({entityType:e,entityId:t,extraFields:n,onSaveExtra:r,onOpenChange:s}){const[i,o]=g.useState(!1),[l,c]=Nke(e,t),u=f=>{o(f),s?.(f)},d=f=>{c(f),r?.(),Xe.success("Run options saved locally"),u(!1)};return a.jsxs(hjt,{label:"Run options",icon:a.jsx(Sx,{}),open:i,onOpenChange:u,children:[n,a.jsx(fjt,{label:"Tracing Options",value:l,onSave:d,editorClassName:"h-[260px]"})]})}function Wur({workflowId:e,resourceId:t,setResourceId:n}){const[r,s]=g.useState(t);return a.jsxs(a.Fragment,{children:[a.jsx(Wke,{entityType:"workflow",entityId:e}),a.jsx(pjt,{entityType:"workflow",entityId:e,onOpenChange:i=>{i&&s(t)},onSaveExtra:()=>n(r),extraFields:a.jsxs(pt,{children:[a.jsx(dt,{children:"Resource ID"}),a.jsx(bn,{value:r,onChange:i=>s(i.target.value),placeholder:"e.g. tenant-42"}),a.jsx(no,{children:"Ignored when server auth derives the resource ID from the user."})]})})]})}function _Q({icon:e,label:t,tooltipContent:n,docsHref:r}){return a.jsxs(Qn,{children:[a.jsx(Fn,{render:a.jsx("span",{role:"button",tabIndex:0,"aria-disabled":"true","aria-label":t,className:"inline-flex",children:a.jsx(ce,{variant:"ghost",size:"icon-md",disabled:!0,"aria-hidden":"true",tabIndex:-1,children:e})})}),a.jsx(Bn,{side:"bottom",className:"max-w-[calc(100dvw-1rem)]",children:a.jsxs("span",{children:[n," ",a.jsxs("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:Z("inline-flex items-center gap-1 text-inherit underline hover:text-foreground",In),children:["Learn more",a.jsx(Zs,{className:"size-3"})]})]})})]})}const Hur=({scheduleId:e,queryOptions:t})=>{const n=Ke();return Ct({queryKey:["schedule",e],queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return n.getSchedule(e)},...t})},DK=({queryOptions:e,...t}={})=>{const n=Ke();return Ct({queryKey:["schedules",t],queryFn:async()=>(await n.listSchedules(t)).schedules,...e})},uUe=25,Gur=({scheduleId:e,queryOptions:t})=>{const n=Ke(),{inView:r,setRef:s}=X0(),i=Mm({queryKey:["schedule-triggers",e],initialPageParam:void 0,queryFn:async({pageParam:d})=>e?n.listScheduleTriggers(e,{limit:uUe,toActualFireAt:d}):{triggers:[]},getNextPageParam:d=>{if(!(!d?.triggers?.length||d.triggers.length<uUe))return d.triggers[d.triggers.length-1].actualFireAt},refetchInterval:d=>(d.state.data?.pages.flatMap(f=>f.triggers)??[]).some(f=>f.run?f.run.status==="pending"||f.run.status==="running"||f.run.status==="waiting":f.outcome==="published")?5e3:!1,...t}),o=i.data?.pages.flatMap(d=>d?.triggers??[])??[],{hasNextPage:l,isFetchingNextPage:c,fetchNextPage:u}=i;return g.useEffect(()=>{r&&l&&!c&&u()},[r,l,c,u]),{...i,data:o,setEndOfListElement:s}},Kur=({scheduleId:e,queryOptions:t})=>{const n=Ke(),r=mr();return wn({mutationFn:async s=>{if(!e)throw new Error("scheduleId is required");return s==="pause"?n.pauseSchedule(e):n.resumeSchedule(e)},onSuccess:()=>{r.invalidateQueries({queryKey:["schedule",e]}),r.invalidateQueries({queryKey:["schedules"]})},...t})};function Xoe({value:e,icon:t,label:n}){return a.jsxs(si,{value:e,children:[a.jsx(At,{size:"xs",children:t}),a.jsx(Y,{variant:"caption",className:"text-inherit",children:n})]})}function Yur({workflowId:e,activeTab:t,showObservability:n=!1}){const{navigate:r}=Sn(),{data:s,isSuccess:i}=DK({workflowId:e}),o=s?.length??0,l=encodeURIComponent(e),c={graph:`/workflows/${l}/graph`,traces:`/workflows/${l}/traces`,schedules:`/workflows/${l}/schedules`},u=f=>{f!=="none"&&r(c[f])},d=i&&o===0;return a.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 p-1.5",children:[a.jsx(Hc,{value:t,defaultTab:t,onValueChange:u,className:"min-w-0",children:a.jsxs(Gc,{variant:"pill-ghost",children:[a.jsx(Xoe,{value:"graph",icon:a.jsx(jl,{}),label:"Graph"}),n&&a.jsx(Xoe,{value:"traces",icon:a.jsx(Sx,{}),label:"Traces"}),!d&&a.jsx(Xoe,{value:"schedules",icon:a.jsx(T0,{}),label:o>0?`Schedules (${o})`:"Schedules"})]})}),(!n||d)&&a.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-0.5",children:[!n&&a.jsx(_Q,{icon:a.jsx(Sx,{}),label:"Traces",tooltipContent:a.jsxs(a.Fragment,{children:["Add ",a.jsx("code",{children:"@mastra/observability"})," to enable Traces."]}),docsHref:"https://mastra.ai/docs/observability/overview"}),d&&a.jsx(_Q,{icon:a.jsx(T0,{}),label:"Schedules",tooltipContent:"Configure a schedule on this workflow to enable Schedules.",docsHref:"https://mastra.ai/docs/workflows/scheduled-workflows"})]})]})}const Xur=({children:e})=>{const{workflowId:t,runId:n}=Cr();return a.jsx(_we,{resetKeys:[t,n],title:"Unable to display this workflow",description:"The workflow data could not be displayed. Try again or open another workflow.",children:a.jsx(tdr,{children:e})})},Jur=e=>e==="graph"||e==="traces"||e==="schedules",edr=({workflowId:e})=>{const t=Lr();return G0({"g$+t":()=>t(`/workflows/${encodeURIComponent(e)}/traces`)}),null};function tdr({children:e}){const{workflowId:t,runId:n}=Cr(),r=d0e("/workflows/:workflowId/:tab/*"),{isLoading:s}=wL({workflowId:t,requestContext:xr("workflow",t)[0],queryOptions:{enabled:!!t}}),{hasObservability:i}=zOt(),o=Jur(r?.params.tab)?r.params.tab:"none",l=[Ts("/workflows"),n?{...lUe,to:`/workflows/${encodeURIComponent(t??"")}/graph`}:lUe,...n?[{id:"workflow-run",Component:ucr,Action:dcr}]:[]];if(!t)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:l}),children:[a.jsx("h1",{className:"sr-only",children:t}),a.jsx("div",{className:"flex h-full flex-col items-center justify-center",children:a.jsx(Y,{variant:"body",tone:"ink",className:"text-center",children:"No workflow ID provided"})})]});if(s&&o==="graph")return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:l}),children:[a.jsx("h1",{className:"sr-only",children:t}),a.jsx(bt,{className:"h-full"})]});const c=u=>a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:l}),headerActions:a.jsx(hcr,{}),children:[a.jsx("h1",{className:"sr-only",children:t}),a.jsxs("div",{className:"grid h-full min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[auto_minmax(0,1fr)]",children:[a.jsx(Yur,{workflowId:t,activeTab:o,showObservability:i}),u]})]});return a.jsxs(xst,{children:[a.jsx(edr,{workflowId:t}),o==="graph"?a.jsx(cOt,{children:a.jsx(Pke,{workflowId:t,initialRunId:n,children:a.jsx(lOt,{children:c(a.jsx(mlr,{leftSlot:a.jsx(ndr,{workflowId:t,initialRunId:n}),children:e}))})})},t):c(e)]})}function ndr({workflowId:e,initialRunId:t}){const[n]=xr("workflow",e),{canExecute:r,canDelete:s}=Za();return a.jsx(wlr,{workflowId:e,initialRunId:t,requestContext:n,runActionsSlot:i=>a.jsx(Wur,{workflowId:e,...i}),canExecute:r("workflows"),canDelete:s("workflows")})}const mjt=md(Z(pr,"rounded-xl transition-all duration-normal ease-out-custom motion-reduce:transition-none"),{variants:{elevation:{flat:"shadow-none",raised:""},interactive:{true:Z(gP,twe,"cursor-pointer active:scale-99"),false:""}},compoundVariants:[{elevation:"flat",interactive:!0,class:Ax}],defaultVariants:{elevation:"raised",interactive:!1}}),hl=g.forwardRef(({className:e,elevation:t,interactive:n,as:r,...s},i)=>{const o=r||(n?"button":"div");return a.jsx(o,{ref:i,type:o==="button"?"button":void 0,className:Z(mjt({elevation:t,interactive:n}),e),...s})});hl.displayName="Card";function gjt({className:e,elevation:t,LinkComponent:n="a",...r}){return a.jsx(n,{className:Z(mjt({elevation:t,interactive:!0}),e),...r})}const TQ=g.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,className:Z("flex flex-col space-y-1.5 px-3 py-1",e),...t}));TQ.displayName="CardHeader";const sw=g.forwardRef(({className:e,...t},n)=>a.jsx("h3",{ref:n,className:Z("text-subheading text-foreground",e),...t}));sw.displayName="CardTitle";const Zj=g.forwardRef(({className:e,...t},n)=>a.jsx("p",{ref:n,className:Z("text-caption text-muted-foreground",e),...t}));Zj.displayName="CardDescription";const rdr=md("",{variants:{density:{default:"p-3",compact:"p-2"}},defaultVariants:{density:"default"}}),qm=g.forwardRef(({className:e,density:t,...n},r)=>a.jsx("div",{ref:r,className:Z(rdr({density:t}),e),...n}));qm.displayName="CardContent";const sdr=g.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,className:Z("flex items-center p-3 pt-0",e),...t}));sdr.displayName="CardFooter";const dUe=["blue","green","orange","purple","pink","amber","cyan"];function Hke(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}const LK=e=>dUe[Hke(e)%dUe.length]??"blue",v0=e=>`var(--badge-${e}-indicator)`,idr={blue:"bg-badge-blue-strong text-badge-blue-foreground",green:"bg-badge-green-strong text-badge-green-foreground",orange:"bg-badge-orange-strong text-badge-orange-foreground",purple:"bg-badge-purple-strong text-badge-purple-foreground",pink:"bg-badge-pink-strong text-badge-pink-foreground",amber:"bg-badge-amber-strong text-badge-amber-foreground",cyan:"bg-badge-cyan-strong text-badge-cyan-foreground"},vjt=e=>idr[e],odr=e=>({background:`var(--badge-${e}-strong)`,foreground:`var(--badge-${e}-foreground)`,tint:`var(--badge-${e}-indicator)`}),fUe={goal:"green",outcome:"orange",behavior:"blue",sentiment:"purple"},hUe=["pink","amber"],adr={green:"fill-badge-green-strong",orange:"fill-badge-orange-strong",blue:"fill-badge-blue-strong",purple:"fill-badge-purple-strong",pink:"fill-badge-pink-strong",amber:"fill-badge-amber-strong"},ldr={green:"stroke-badge-green-edge",orange:"stroke-badge-orange-edge",blue:"stroke-badge-blue-edge",purple:"stroke-badge-purple-edge",pink:"stroke-badge-pink-edge",amber:"stroke-badge-amber-edge"};function Gke(e){const t=e.toLowerCase();return(Object.hasOwn(fUe,t)?fUe[t]:void 0)??hUe[Hke(t)%hUe.length]??"pink"}function Vx(e){return`var(--chart-${Gke(e)})`}function yjt(e){return adr[Gke(e)]}function cdr(e){return ldr[Gke(e)]}const FP=[{name:"goal",label:"Goal",description:"What the user wanted from the interaction.",order:0,builtIn:!0,enabled:!0,status:"ready"},{name:"sentiment",label:"Sentiment",description:"The tone the user expressed during the interaction.",order:1,builtIn:!0,enabled:!0,status:"ready"},{name:"behavior",label:"Behavior",description:"What the agent did in response.",order:2,builtIn:!0,enabled:!0,status:"ready"},{name:"outcome",label:"Outcome",description:"How the interaction ended.",order:3,builtIn:!0,enabled:!0,status:"ready"}];FP.map(e=>e.name);Object.fromEntries(FP.map(e=>[e.name,e.description]));function o6(e,t){const n=[...new Set(t??e.map(s=>s.name))],r=new Map(e.map(s=>[s.name,s.order]));return n.sort((s,i)=>{const o=r.get(s),l=r.get(i);return o===void 0&&l===void 0?0:o===void 0?1:l===void 0?-1:o-l})}function gp(e,t){return e.find(n=>n.name===t)?.label??udr(t)}function QS(e,t){return e.find(n=>n.name===t)?.description||void 0}function udr(e){return e.split(/[-_]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function zK(e){return`${e} ${e===1?"trace":"traces"}`}function ddr(e){return`${e} ${e===1?"theme":"themes"}`}function xjt(e,t){if(t<=0)return`${zK(e)} in this snapshot`;const n=Math.round(e/t);return`${e} of ${n} traces in this snapshot (${Math.round(t*100)}%)`}const Kke={timeZone:"UTC"};function I5(e){return FE(e,{...Kke,now:0})??e}function FK(e){return rs(e,"date-time",Kke)??e}function nme(e,t){return eer(e,t,Kke)??`${e}–${t}`}const fdr=[["chat.completion","1.2s"],["tool.search_docs","340ms"],["workflow.support","2.8s"]],IQ=e=>({color:Vx(e)}),pUe=()=>a.jsxs("div",{"aria-hidden":"true",className:"relative hidden h-full items-center lg:flex",children:[a.jsx("div",{className:"w-full border-t border-dashed border-border"}),a.jsx("span",{className:"absolute left-1/2 size-2.5 -translate-x-1/2 rounded-full bg-brand-green-indicator"})]});function E5(e){return new Intl.NumberFormat("en-US").format(e)}function hdr(e,t){return t?{title:"No Trace Intelligence themes in this date range.",body:"Choose a wider snapshot date range, or wait for newly processed traces to form recurring themes."}:!e||e.status==="collecting"?{title:"Collecting traces for Trace Intelligence.",body:"Trace Intelligence starts grouping recurring patterns after your deployed agents send enough completed traces."}:e.status==="ready"?{title:"Trace Intelligence themes are ready.",body:"Select at least two available trace signal types to see how goals, outcomes, behaviors, and sentiment connect."}:{title:"Analyzing traces for Trace Intelligence.",body:"Trace signals have started processing. Themes appear after enough generated and embedded trace signals form recurring patterns."}}function pdr({progress:e}){const t=e.signalCatalog??FP,n=t.filter(s=>s.enabled).length,r=t.filter(s=>s.enabled&&s.status==="ready").length;return a.jsxs("dl",{className:"mt-4 grid gap-2 sm:grid-cols-3",children:[a.jsxs("div",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:Sa({tone:"muted",variant:"caption"}),children:"Traces analyzed"}),a.jsx("dd",{className:Z(Sa({tone:"ink",variant:"heading"}),"mt-1"),children:E5(e.traceCount)})]}),a.jsxs("div",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:Sa({tone:"muted",variant:"caption"}),children:"Trace signal types ready"}),a.jsxs("dd",{className:Z(Sa({tone:"ink",variant:"heading"}),"mt-1"),children:[e.signalCatalog?r:e.availableSignals.length," of ",n]})]}),a.jsxs("div",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:Sa({tone:"muted",variant:"caption"}),children:"Status"}),a.jsx("dd",{className:Z(Sa({tone:"ink",variant:"heading"}),"mt-1 capitalize"),children:e.status})]})]})}function mdr({progress:e}){if(!e)return null;const t=e.signalCatalog??FP;return a.jsx("ul",{"aria-label":"Trace signal processing progress",className:"mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-4",children:o6(t,t.filter(n=>n.enabled).map(n=>n.name)).map(n=>{const r=e.signals[n]??{generated:0,embedded:0},s=t.find(l=>l.name===n),i=gp(t,n),o=s?s.status==="ready":e.availableSignals.includes(n);return a.jsxs("li",{className:"rounded-md border border-border bg-background px-3 py-2",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx(Y,{as:"span",variant:"subheading",style:IQ(n),children:i}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:o?"Themes ready":"Processing"})]}),a.jsxs(Y,{variant:"caption",tone:"muted",className:"mt-1",children:[E5(r.generated)," generated · ",E5(r.embedded)," embedded"]})]},n)})})}function gdr({progress:e,signalCatalog:t}){const n=e?.signalCatalog??t,r=n.filter(s=>s.enabled&&s.status!=="ready");return r.length===0?null:a.jsxs("section",{className:"rounded-lg border border-border bg-background p-4","aria-labelledby":"pending-signals-heading",children:[a.jsx(Y,{as:"h2",variant:"subheading",tone:"ink",id:"pending-signals-heading",children:"Signals building themes"}),a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-1",children:"Themes appear once enough new traces are analyzed, embedded, and clustered."}),a.jsx("ul",{"aria-label":"Pending trace signals",className:"mt-3 grid gap-2 sm:grid-cols-2",children:r.map(s=>{const i=e?.signals[s.name]??{generated:0,embedded:0};return a.jsxs("li",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx(Y,{font:"body",as:"span",variant:"subheading",style:IQ(s.name),children:gp(n,s.name)}),a.jsx(Y,{font:"body",as:"span",variant:"caption",tone:"muted",className:"capitalize",children:s.status})]}),QS(n,s.name)?a.jsx(Y,{font:"body",variant:"caption",tone:"muted",className:"mt-1",children:QS(n,s.name)}):null,a.jsxs(Y,{font:"body",variant:"caption",tone:"muted",className:"mt-1",children:[E5(i.generated)," generated · ",E5(i.embedded)," embedded"]})]},s.name)})})]})}const rme=({actionSlot:e,LinkComponent:t="a",progress:n,signalCatalog:r,isRangeEmpty:s})=>{const i=hdr(n,s),o=r??n?.signalCatalog??FP,c=o6(o,o.filter(u=>u.enabled).map(u=>u.name)).map(u=>({key:u,label:gp(o,u),description:QS(o,u)}));return a.jsx("section",{className:"min-h-full w-full bg-sidebar p-6 md:px-10 lg:px-12 xl:px-[4.375rem]",children:a.jsxs("div",{className:"mx-auto w-full max-w-260",children:[a.jsxs("header",{children:[a.jsxs(Y,{variant:"eyebrow",tone:"muted",className:"flex items-center gap-2",children:[a.jsx("span",{"aria-hidden":"true",className:"size-2 rounded-full bg-brand-green-indicator"}),"Trace Intelligence"]}),a.jsx(Y,{as:"h1",variant:"display",tone:"ink",className:"mt-2",children:"Understand what drives every agent interaction"}),a.jsx(Y,{tone:"muted",className:"mt-2 max-w-180",children:"Trace Intelligence groups recurring goals, outcomes, behaviors, and sentiment across completed traces."})]}),a.jsxs("div",{role:"list","aria-label":"Trace Intelligence analysis pipeline",className:"mt-14 grid gap-4 lg:grid-cols-[17.5rem_4.5rem_17.5rem_4.5rem_minmax(0,1fr)] lg:gap-0",children:[a.jsxs("div",{role:"listitem",className:"min-h-50 p-5",children:[a.jsx(Y,{as:"h2",variant:"heading",tone:"ink",children:"Traces"}),a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-0.5",children:"Every agent interaction"}),a.jsx(Y,{variant:"eyebrow",tone:"muted",className:"mt-5",children:"Input"}),a.jsx("div",{className:"mt-2.5 space-y-2",children:fdr.map(([u,d])=>a.jsxs("div",{className:Z(pr,"flex items-center justify-between rounded px-3 py-1.5"),children:[a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"muted",children:u}),a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"muted",children:d})]},u))})]}),a.jsx(pUe,{}),a.jsxs(hl,{as:"div",role:"listitem",className:"flex min-h-50 flex-col items-center p-5 text-center",elevation:"raised",children:[a.jsx(Y,{as:"h2",variant:"heading",tone:"ink",children:"Trace Intelligence"}),a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-0.5",children:"Finds recurring themes"}),a.jsx("div",{"aria-hidden":"true",className:"mt-5 flex size-14 items-center justify-center rounded-full border border-brand-green-indicator bg-fill-subtle",children:a.jsx(I_,{className:"size-4 text-brand-green-indicator"})}),a.jsx(Y,{variant:"meta",tone:"muted",className:"mt-3 max-w-40",children:"Clusters similar trace signals into themes for each dimension"})]}),a.jsx(pUe,{}),a.jsxs("div",{role:"listitem",className:"min-h-50 p-5",children:[a.jsx(Y,{as:"h2",variant:"heading",tone:"ink",children:"Theme analysis"}),a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-0.5",children:"How recurring patterns connect"}),a.jsx(Y,{variant:"eyebrow",tone:"muted",className:"mt-5",children:"Output"}),a.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:c.map(u=>a.jsxs(Y,{as:"span",variant:"column",className:"inline-flex items-center gap-2 rounded border border-border bg-card px-2.5 py-1.5",style:IQ(u.key),children:[a.jsx("span",{"aria-hidden":"true",className:"size-1.5 rounded-full bg-current"}),u.label]},u.key))})]})]}),a.jsxs("section",{className:"mt-10","aria-labelledby":"signal-definitions-heading",children:[a.jsx(Y,{as:"h2",variant:"heading",tone:"ink",id:"signal-definitions-heading",children:"What each trace signal means"}),a.jsx("ul",{"aria-label":"Trace signal definitions",className:"mt-4 grid gap-3 sm:grid-cols-2",children:c.map(u=>a.jsxs("li",{className:"px-1 py-2",children:[a.jsx(Y,{as:"h3",variant:"subheading",style:IQ(u.key),children:u.label}),u.description?a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-1.5",children:u.description}):null]},u.key))})]}),a.jsxs("aside",{className:"mt-9 rounded-md border border-border bg-background px-5 py-4",children:[a.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[a.jsx("span",{"aria-hidden":"true",className:"mt-1.5 size-2 shrink-0 rounded-full bg-warning-indicator"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs(Y,{variant:"caption",tone:"muted",children:[a.jsx(Y,{as:"strong",variant:"column",tone:"ink",children:i.title})," ",i.body]}),n?a.jsx(pdr,{progress:n}):null,a.jsx(mdr,{progress:n})]})]}),a.jsxs("div",{className:"mt-4 flex shrink-0 flex-wrap items-center gap-2 sm:justify-end",children:[e,a.jsxs(ce,{icon:a.jsx(Zs,{}),render:a.jsx("a",{href:"https://mastra.ai/en/docs/mastra-platform/trace-intelligence",target:"_blank",rel:"noopener noreferrer"}),size:"sm",children:["Read the docs",a.jsx("span",{className:"sr-only",children:" (opens in new tab)"})]}),a.jsx(ce,{icon:a.jsx(Sx,{}),render:a.jsx(t,{href:"/traces"}),variant:"primary",size:"sm",children:"View incoming traces"})]})]})]})})};function mUe(e){return a.jsx(rme,{...e})}async function vdr(e){const t=await fetch(e,{credentials:"include"});if(!t.ok)throw Object.assign(new Error(`Trace Intelligence request failed (${t.status})`),{status:t.status});return t.json()}const k2={cacheScope:"oss-studio",request:vdr,LinkComponent:"a",getTraceHref:e=>`/traces?traceId=${encodeURIComponent(e)}`,signalCatalog:FP},Yke=g.createContext(k2);function pa(){return g.useContext(Yke)}function ydr(e,t){const n=new URLSearchParams({entityType:t});return e(`/api/learning/entities?${n}`)}function xdr(e,t,n){const r=new URLSearchParams({entityType:n});return e(`/api/learning/entities/${encodeURIComponent(t)}/progress?${r}`)}function bjt(e,t,n,r,s,i,o=24){const l=new URLSearchParams({entityType:n,signalNames:r.join(","),presentation:"landmarks",limit:String(o)});return s&&l.set("from",s.toISOString()),i&&l.set("to",i.toISOString()),e(`/api/learning/entities/${encodeURIComponent(t)}/theme-snapshots?${l}`)}function wjt(e,t,n,r,s,i=8){const o=new URLSearchParams({entityType:n,signalNames:r.join(","),snapshotId:s,themeLimitPerStage:String(i)});return e(`/api/learning/entities/${encodeURIComponent(t)}/theme-flow?${o}`)}function bdr(e,t,n,r,s,i){const o=new URLSearchParams({entityType:n,signalName:r,snapshotId:s});return e(Xke(t,i,`?${o}`))}function a6(e){return e.map(t=>`${t.signalName}:${t.kind==="theme"?t.themeId:"noise"}`).join(",")}function wdr(e,t,n,r,s,i,o=20,l=0,c=[]){const u=new URLSearchParams({entityType:n,signalName:r,snapshotId:s,limit:String(o),offset:String(l)});return c.length>0&&u.set("filterThemes",a6(c)),e(Xke(t,i,`/examples?${u}`))}function Sdr(e,t,n,r,s,i=100){const o=new URLSearchParams({entityType:n,signalName:r,limit:String(i)});return e(Xke(t,s,`/history?${o}`))}function kdr(e,t,n,r,s){const i=new URLSearchParams({entityType:n,signalName:r,snapshotId:s});return e(kjt(t,`?${i}`))}function Odr(e,t,n,r,s,i=20,o=0,l=[]){const c=new URLSearchParams({entityType:n,signalName:r,snapshotId:s,limit:String(i),offset:String(o)});return l.length>0&&c.set("filterThemes",a6(l)),e(kjt(t,`/examples?${c}`))}async function Sjt(e,t,n,r,s){const i=await gUe(e,t,n,r,s,0),o=[...i.paths],l={...i.themes};let c=i.nextOffset;for(;c!==void 0;){const u=await gUe(e,t,n,r,s,c);o.push(...u.paths),Object.assign(l,u.themes),c=u.nextOffset}return{snapshot:i.snapshot,signals:i.signals,themes:l,paths:o}}function gUe(e,t,n,r,s,i){const o=new URLSearchParams({entityType:n,signalNames:r.join(","),snapshotId:s,limit:"500",offset:String(i)});return e(`/api/learning/entities/${encodeURIComponent(t)}/theme-paths?${o}`)}function jdr(e,t){return e(`/api/learning/traces/${encodeURIComponent(t)}/summary`)}function Xke(e,t,n){return`/api/learning/entities/${encodeURIComponent(e)}/themes/${encodeURIComponent(t)}${n}`}function kjt(e,t){return`/api/learning/entities/${encodeURIComponent(e)}/noise${t}`}function Ojt(e,t,n=!0){const{cacheScope:r,request:s}=pa();return Ct({queryKey:["entity-learning",r,t,e,"progress"],queryFn:()=>xdr(s,e??"",t),enabled:n&&!!e})}function jjt(e){const{cacheScope:t,request:n}=pa();return Ct({queryKey:["entity-learning",t,"entities",e],queryFn:()=>ydr(n,e)})}function Cjt(e,t,n,r,s){const{cacheScope:i,request:o}=pa(),l=r?.toISOString(),c=s?.toISOString();return Ct({queryKey:["entity-learning",i,t,e,"theme-snapshots",n,l,c],queryFn:()=>bjt(o,e,t,n,r,s),enabled:n.length>=2,staleTime:3e4})}const Cdr=.01;function _dr(e,t){return String(e[t.id])}function Tdr(e,t){const n=String(e[`${t.id}Label`]),r=e[`${t.id}Description`];return typeof r=="string"&&r.trim()?`${n}
258
258
  ${r}`:n}function Idr(e,t){return Number(e[`${t.id}TraceCount`])}function Edr(e){const t=new Map;for(const i of e.stages)for(const o of i.nodes)t.set(o.nodeId,{signalName:i.signalName,node:o});const n=new Set(e.links.flatMap(i=>{const o=t.get(i.sourceNodeId),l=t.get(i.targetNodeId);return[...o?[o.signalName]:[],...l?[l.signalName]:[]]})),r=e.stages.filter(i=>n.has(i.signalName)).map(i=>({id:i.signalName,label:Adr(i.signalName)})),s=[];for(const i of e.links){const o=t.get(i.sourceNodeId),l=t.get(i.targetNodeId);!o||!l||s.push({[o.signalName]:o.node.nodeId,[`${o.signalName}Label`]:xUe(o.node),[`${o.signalName}Description`]:o.node.description,[`${o.signalName}TraceCount`]:o.node.traceCount,[l.signalName]:l.node.nodeId,[`${l.signalName}Label`]:xUe(l.node),[`${l.signalName}Description`]:l.node.description,[`${l.signalName}TraceCount`]:l.node.traceCount,traceCount:i.traceCount,layoutTraceCount:"layoutTraceCount"in i?i.layoutTraceCount:i.traceCount})}return{columns:r,records:s}}function Ndr(e){return Edr(e)}function vUe(e,t){return e.length===0?[]:[...new Set([(t-1+e.length)%e.length,t,(t+1)%e.length])].sort((r,s)=>r-s).flatMap(r=>{const s=e[r];return s?[s.snapshotId]:[]})}function yUe(e,t){const n=e.stages.map(l=>{const c=new Map;for(const d of t){const f=d.stages.find(h=>h.signalName===l.signalName);for(const h of f?.nodes??[])c.has(h.nodeId)||c.set(h.nodeId,c.size)}const u=l.nodes.filter(d=>d.traceCount>0).sort((d,f)=>(c.get(d.nodeId)??Number.MAX_SAFE_INTEGER)-(c.get(f.nodeId)??Number.MAX_SAFE_INTEGER));return{...l,nodes:u}}),r=new Set(n.flatMap(l=>l.nodes.map(c=>c.nodeId))),s=new Map,i=new Map;for(const l of t)for(const c of l.links){const u=`${c.sourceNodeId}\0${c.targetNodeId}`;s.set(u,Math.max(s.get(u)??0,c.traceCount)),i.has(u)||i.set(u,i.size)}const o=e.links.filter(l=>l.traceCount>0&&r.has(l.sourceNodeId)&&r.has(l.targetNodeId)).sort((l,c)=>{const u=`${l.sourceNodeId}\0${l.targetNodeId}`,d=`${c.sourceNodeId}\0${c.targetNodeId}`;return(i.get(u)??0)-(i.get(d)??0)}).map(l=>{const c=`${l.sourceNodeId}\0${l.targetNodeId}`;return{...l,layoutTraceCount:Math.max(Cdr,s.get(c)??l.traceCount)}});return{...e,stages:n,links:o}}function xUe(e){return e.kind==="noise"?"Noise":e.label}function Adr(e){return`${e.slice(0,1).toUpperCase()}${e.slice(1)}`}function N5(e,t){const n=e.cutoffAt?FK(e.cutoffAt):nme(e.startedAt,e.endedAt);if(!t)return n;const{traceCount:r,themeCount:s}=Pdr(t);return`${n} · ${zK(r)} · ${ddr(s)}`}function Pdr(e){return{traceCount:e.stages[0]?.traceCount??e.snapshot.traceCount,themeCount:e.stages.reduce((t,n)=>t+n.nodes.filter(r=>r.kind==="theme").length,0)}}function Tc(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var $dr=typeof Symbol=="function"&&Symbol.observable||"@@observable",bUe=$dr,Joe=()=>Math.random().toString(36).substring(7).split("").join("."),Rdr={INIT:`@@redux/INIT${Joe()}`,REPLACE:`@@redux/REPLACE${Joe()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${Joe()}`},EQ=Rdr;function Jke(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function eOe(e,t,n){if(typeof e!="function")throw new Error(Tc(2));if(typeof t=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(Tc(0));if(typeof t=="function"&&typeof n>"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(Tc(1));return n(eOe)(e,t)}let r=e,s=t,i=new Map,o=i,l=0,c=!1;function u(){o===i&&(o=new Map,i.forEach((y,x)=>{o.set(x,y)}))}function d(){if(c)throw new Error(Tc(3));return s}function f(y){if(typeof y!="function")throw new Error(Tc(4));if(c)throw new Error(Tc(5));let x=!0;u();const b=l++;return o.set(b,y),function(){if(x){if(c)throw new Error(Tc(6));x=!1,u(),o.delete(b),i=null}}}function h(y){if(!Jke(y))throw new Error(Tc(7));if(typeof y.type>"u")throw new Error(Tc(8));if(typeof y.type!="string")throw new Error(Tc(17));if(c)throw new Error(Tc(9));try{c=!0,s=r(s,y)}finally{c=!1}return(i=o).forEach(b=>{b()}),y}function p(y){if(typeof y!="function")throw new Error(Tc(10));r=y,h({type:EQ.REPLACE})}function m(){const y=f;return{subscribe(x){if(typeof x!="object"||x===null)throw new Error(Tc(11));function b(){const k=x;k.next&&k.next(d())}return b(),{unsubscribe:y(b)}},[bUe](){return this}}}return h({type:EQ.INIT}),{dispatch:h,subscribe:f,getState:d,replaceReducer:p,[bUe]:m}}function Mdr(e){Object.keys(e).forEach(t=>{const n=e[t];if(typeof n(void 0,{type:EQ.INIT})>"u")throw new Error(Tc(12));if(typeof n(void 0,{type:EQ.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(Tc(13))})}function _jt(e){const t=Object.keys(e),n={};for(let i=0;i<t.length;i++){const o=t[i];typeof e[o]=="function"&&(n[o]=e[o])}const r=Object.keys(n);let s;try{Mdr(n)}catch(i){s=i}return function(o={},l){if(s)throw s;let c=!1;const u={};for(let d=0;d<r.length;d++){const f=r[d],h=n[f],p=o[f],m=h(p,l);if(typeof m>"u")throw l&&l.type,new Error(Tc(14));u[f]=m,c=c||m!==p}return c=c||r.length!==Object.keys(o).length,c?u:o}}function wUe(e,t){return function(...n){return t(e.apply(this,n))}}function SUe(e,t){if(typeof e=="function")return wUe(e,t);if(typeof e!="object"||e===null)throw new Error(Tc(16));const n={};for(const r in e){const s=e[r];typeof s=="function"&&(n[r]=wUe(s,t))}return n}function A5(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,n)=>(...r)=>t(n(...r)))}function Tjt(...e){return t=>(n,r)=>{const s=t(n,r);let i=()=>{throw new Error(Tc(15))};const o={getState:s.getState,dispatch:(c,...u)=>i(c,...u)},l=e.map(c=>c(o));return i=A5(...l)(s.dispatch),{...s,dispatch:i}}}function Ijt(e){return Jke(e)&&"type"in e&&typeof e.type=="string"}var eae={exports:{}},tae={};var kUe;function Ddr(){if(kUe)return tae;kUe=1;var e=eP();function t(c,u){return c===u&&(c!==0||1/c===1/u)||c!==c&&u!==u}var n=typeof Object.is=="function"?Object.is:t,r=e.useSyncExternalStore,s=e.useRef,i=e.useEffect,o=e.useMemo,l=e.useDebugValue;return tae.useSyncExternalStoreWithSelector=function(c,u,d,f,h){var p=s(null);if(p.current===null){var m={hasValue:!1,value:null};p.current=m}else m=p.current;p=o(function(){function y(j){if(!x){if(x=!0,b=j,j=f(j),h!==void 0&&m.hasValue){var C=m.value;if(h(C,j))return S=C}return S=j}if(C=S,n(b,j))return C;var T=f(j);return h!==void 0&&h(C,T)?(b=j,C):(b=j,S=T)}var x=!1,b,S,k=d===void 0?null:d;return[function(){return y(u())},k===null?void 0:function(){return y(k())}]},[u,d,f,h]);var v=r(c,p[0],p[1]);return i(function(){m.hasValue=!0,m.value=v},[v]),l(v),v},tae}var OUe;function Ldr(){return OUe||(OUe=1,eae.exports=Ddr()),eae.exports}Ldr();var zdr=g.version.startsWith("19"),Fdr=Symbol.for(zdr?"react.transitional.element":"react.element"),Bdr=Symbol.for("react.portal"),Vdr=Symbol.for("react.fragment"),Udr=Symbol.for("react.strict_mode"),qdr=Symbol.for("react.profiler"),Qdr=Symbol.for("react.consumer"),Zdr=Symbol.for("react.context"),Ejt=Symbol.for("react.forward_ref"),Wdr=Symbol.for("react.suspense"),Hdr=Symbol.for("react.suspense_list"),tOe=Symbol.for("react.memo"),Gdr=Symbol.for("react.lazy"),Kdr=Ejt,Ydr=tOe;function Xdr(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case Fdr:switch(e=e.type,e){case Vdr:case qdr:case Udr:case Wdr:case Hdr:return e;default:switch(e=e&&e.$$typeof,e){case Zdr:case Ejt:case Gdr:case tOe:return e;case Qdr:return e;default:return t}}case Bdr:return t}}}function Jdr(e){return Xdr(e)===tOe}function efr(e,t,n,r,{areStatesEqual:s,areOwnPropsEqual:i,areStatePropsEqual:o}){let l=!1,c,u,d,f,h;function p(b,S){return c=b,u=S,d=e(c,u),f=t(r,u),h=n(d,f,u),l=!0,h}function m(){return d=e(c,u),t.dependsOnOwnProps&&(f=t(r,u)),h=n(d,f,u),h}function v(){return e.dependsOnOwnProps&&(d=e(c,u)),t.dependsOnOwnProps&&(f=t(r,u)),h=n(d,f,u),h}function y(){const b=e(c,u),S=!o(b,d);return d=b,S&&(h=n(d,f,u)),h}function x(b,S){const k=!i(S,u),j=!s(b,c,S,u);return c=b,u=S,k&&j?m():k?v():j?y():h}return function(S,k){return l?x(S,k):p(S,k)}}function tfr(e,{initMapStateToProps:t,initMapDispatchToProps:n,initMergeProps:r,...s}){const i=t(e,s),o=n(e,s),l=r(e,s);return efr(i,o,l,e,s)}function nfr(e,t){const n={};for(const r in e){const s=e[r];typeof s=="function"&&(n[r]=(...i)=>t(s(...i)))}return n}function sme(e){return function(n){const r=e(n);function s(){return r}return s.dependsOnOwnProps=!1,s}}function jUe(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function Njt(e,t){return function(r,{displayName:s}){const i=function(l,c){return i.dependsOnOwnProps?i.mapToProps(l,c):i.mapToProps(l,void 0)};return i.dependsOnOwnProps=!0,i.mapToProps=function(l,c){i.mapToProps=e,i.dependsOnOwnProps=jUe(e);let u=i(l,c);return typeof u=="function"&&(i.mapToProps=u,i.dependsOnOwnProps=jUe(u),u=i(l,c)),u},i}}function nOe(e,t){return(n,r)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${r.wrappedComponentName}.`)}}function rfr(e){return e&&typeof e=="object"?sme(t=>nfr(e,t)):e?typeof e=="function"?Njt(e):nOe(e,"mapDispatchToProps"):sme(t=>({dispatch:t}))}function sfr(e){return e?typeof e=="function"?Njt(e):nOe(e,"mapStateToProps"):sme(()=>({}))}function ifr(e,t,n){return{...n,...e,...t}}function ofr(e){return function(n,{displayName:r,areMergedPropsEqual:s}){let i=!1,o;return function(c,u,d){const f=e(c,u,d);return i?s(f,o)||(o=f):(i=!0,o=f),o}}}function afr(e){return e?typeof e=="function"?ofr(e):nOe(e,"mergeProps"):()=>ifr}function lfr(e){e()}function cfr(){let e=null,t=null;return{clear(){e=null,t=null},notify(){lfr(()=>{let n=e;for(;n;)n.callback(),n=n.next})},get(){const n=[];let r=e;for(;r;)n.push(r),r=r.next;return n},subscribe(n){let r=!0;const s=t={callback:n,next:null,prev:t};return s.prev?s.prev.next=s:e=s,function(){!r||e===null||(r=!1,s.next?s.next.prev=s.prev:t=s.prev,s.prev?s.prev.next=s.next:e=s.next)}}}}var CUe={notify(){},get:()=>[]};function Ajt(e,t){let n,r=CUe,s=0,i=!1;function o(v){d();const y=r.subscribe(v);let x=!1;return()=>{x||(x=!0,y(),f())}}function l(){r.notify()}function c(){m.onStateChange&&m.onStateChange()}function u(){return i}function d(){s++,n||(n=t?t.addNestedSub(c):e.subscribe(c),r=cfr())}function f(){s--,n&&s===0&&(n(),n=void 0,r.clear(),r=CUe)}function h(){i||(i=!0,d())}function p(){i&&(i=!1,f())}const m={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:u,trySubscribe:h,tryUnsubscribe:p,getListeners:()=>r};return m}var ufr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",dfr=ufr(),ffr=()=>typeof navigator<"u"&&navigator.product==="ReactNative",hfr=ffr(),pfr=()=>dfr||hfr?g.useLayoutEffect:g.useEffect,NQ=pfr();function _Ue(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function tV(e,t){if(_Ue(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s=0;s<n.length;s++)if(!Object.prototype.hasOwnProperty.call(t,n[s])||!_Ue(e[n[s]],t[n[s]]))return!1;return!0}var mfr={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},gfr={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},vfr={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},Pjt={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},yfr={[Kdr]:vfr,[Ydr]:Pjt};function TUe(e){return Jdr(e)?Pjt:yfr[e.$$typeof]||mfr}var xfr=Object.defineProperty,bfr=Object.getOwnPropertyNames,IUe=Object.getOwnPropertySymbols,wfr=Object.getOwnPropertyDescriptor,Sfr=Object.getPrototypeOf,EUe=Object.prototype;function ime(e,t){if(typeof t!="string"){if(EUe){const i=Sfr(t);i&&i!==EUe&&ime(e,i)}let n=bfr(t);IUe&&(n=n.concat(IUe(t)));const r=TUe(e),s=TUe(t);for(let i=0;i<n.length;++i){const o=n[i];if(!gfr[o]&&!(s&&s[o])&&!(r&&r[o])){const l=wfr(t,o);try{xfr(e,o,l)}catch{}}}}return e}var kfr=Symbol.for("react-redux-context"),Ofr=typeof globalThis<"u"?globalThis:{};function jfr(){if(!g.createContext)return{};const e=Ofr[kfr]??=new Map;let t=e.get(g.createContext);return t||(t=g.createContext(null),e.set(g.createContext,t)),t}var $jt=jfr(),Cfr=[null,null];function _fr(e,t,n){NQ(()=>e(...t),n)}function Tfr(e,t,n,r,s,i){e.current=r,n.current=!1,s.current&&(s.current=null,i())}function Ifr(e,t,n,r,s,i,o,l,c,u,d){if(!e)return()=>{};let f=!1,h=null;const p=()=>{if(f||!l.current)return;const v=t.getState();let y,x;try{y=r(v,s.current)}catch(b){x=b,h=b}x||(h=null),y===i.current?o.current||u():(i.current=y,c.current=y,o.current=!0,d())};return n.onStateChange=p,n.trySubscribe(),p(),()=>{if(f=!0,n.tryUnsubscribe(),n.onStateChange=null,h)throw h}}function Efr(e,t){return e===t}function Nfr(e,t,n,{pure:r,areStatesEqual:s=Efr,areOwnPropsEqual:i=tV,areStatePropsEqual:o=tV,areMergedPropsEqual:l=tV,forwardRef:c=!1,context:u=$jt}={}){const d=u,f=sfr(e),h=rfr(t),p=afr(n),m=!!e;return y=>{const x=y.displayName||y.name||"Component",b=`Connect(${x})`,S={shouldHandleStateChanges:m,displayName:b,wrappedComponentName:x,WrappedComponent:y,initMapStateToProps:f,initMapDispatchToProps:h,initMergeProps:p,areStatesEqual:s,areStatePropsEqual:o,areOwnPropsEqual:i,areMergedPropsEqual:l};function k(T){const[_,N,E]=g.useMemo(()=>{const{reactReduxForwardedRef:te,...ie}=T;return[T.context,te,ie]},[T]),A=g.useMemo(()=>{let te=d;return _?.Consumer,te},[_,d]),P=g.useContext(A),L=!!T.store&&!!T.store.getState&&!!T.store.dispatch,F=!!P&&!!P.store,Q=L?T.store:P.store,q=F?P.getServerState:Q.getState,B=g.useMemo(()=>tfr(Q.dispatch,S),[Q]),[V,W]=g.useMemo(()=>{if(!m)return Cfr;const te=Ajt(Q,L?void 0:P.subscription),ie=te.notifyNestedSubs.bind(te);return[te,ie]},[Q,L,P]),M=g.useMemo(()=>L?P:{...P,subscription:V},[L,P,V]),K=g.useRef(void 0),D=g.useRef(E),$=g.useRef(void 0),z=g.useRef(!1),U=g.useRef(!1),G=g.useRef(void 0);NQ(()=>(U.current=!0,()=>{U.current=!1}),[]);const ne=g.useMemo(()=>()=>$.current&&E===D.current?$.current:B(Q.getState(),E),[Q,E]),X=g.useMemo(()=>ie=>V?Ifr(m,Q,V,B,D,K,z,U,$,W,ie):()=>{},[V]);_fr(Tfr,[D,K,z,E,$,W]);let ee;try{ee=g.useSyncExternalStore(X,ne,q?()=>B(q(),E):ne)}catch(te){throw G.current&&(te.message+=`
259
259
  The error may be correlated with this previous error:
260
260
  ${G.current.stack}
@@ -672,7 +672,7 @@ window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-
672
672
  `),r=t.split(`
673
673
  `),s=n.length,i=r.length,o=Array.from({length:s+1},()=>new Array(i+1).fill(0));for(let d=1;d<=s;d++)for(let f=1;f<=i;f++)n[d-1]===r[f-1]?o[d][f]=o[d-1][f-1]+1:o[d][f]=Math.max(o[d-1][f],o[d][f-1]);const l=[];let c=s,u=i;for(;c>0||u>0;)c>0&&u>0&&n[c-1]===r[u-1]?(l.push({type:"equal",text:n[c-1]}),c--,u--):u>0&&(c===0||o[c][u-1]>=o[c-1][u])?(l.push({type:"added",text:r[u-1]}),u--):(l.push({type:"removed",text:n[c-1]}),c--);return l.reverse()}function Cye(e){return e.type==="prompt_block"&&typeof e.content=="string"?e.content:null}function nvs({promptBlockId:e}){const{data:t}=Nz({blockId:e,queryOptions:{enabled:!!e}}),n=t?.content??"";return n?a.jsx(ii,{content:n,tooltip:"Copy prompt block text",size:"sm"}):null}function PM({block:e}){const t=Cye(e);return t?a.jsx(ii,{content:t,tooltip:"Copy prompt text",size:"sm"}):e.type==="prompt_block_ref"&&(typeof e.promptBlockId=="string"||typeof e.id=="string")?a.jsx(nvs,{promptBlockId:e.promptBlockId??e.id}):null}function rvs({previousBlocks:e,currentBlocks:t}){const n=Array.isArray(e)?e:[],r=Array.isArray(t)?t:[],s=r.map(l=>Cye(l)??""),i=n.map(l=>Cye(l)??"");if(n.length<=1&&r.length<=1){const l=i[0]??"",c=s[0]??"",u=n[0];if(l===c)return a.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[u&&a.jsx("div",{className:"absolute top-2 right-2",children:a.jsx(PM,{block:u})}),a.jsx(Y,{variant:"caption",tone:"muted",font:"mono",className:"whitespace-pre-wrap",children:l||"(empty)"})]});const d=$et(l,c);return a.jsxs("div",{className:"relative overflow-hidden rounded-md border border-border",children:[u&&a.jsx("div",{className:"absolute top-2 right-2 z-10",children:a.jsx(PM,{block:u})}),d.map((f,h)=>a.jsxs(Y,{as:"p",variant:"body",tone:"muted",className:Z("px-3 py-0.5 wrap-break-word whitespace-pre-wrap",f.type==="removed"&&"bg-destructive-subtle text-destructive-subtle-foreground",f.type==="added"&&"bg-success-subtle text-success-subtle-foreground"),children:[a.jsx("span",{className:"mr-2 inline-block w-4 shrink-0 text-muted-foreground/50 select-none",children:f.type==="removed"?"−":f.type==="added"?"+":" "}),f.text||" "]},h))]})}const o=Math.max(n.length,r.length);return a.jsx("div",{className:"flex flex-col gap-2",children:Array.from({length:o},(l,c)=>{const u=n[c],d=r[c],f=i[c]??"",h=s[c]??"";if(!u&&d)return a.jsxs("div",{className:"rounded-md border border-success-edge bg-success-subtle p-3",children:[a.jsx(Y,{variant:"meta",className:"mb-1 text-success-subtle-foreground",children:"+ Added block"}),a.jsx(Y,{variant:"caption",className:"whitespace-pre-wrap text-success-subtle-foreground",children:h})]},c);if(u&&!d)return a.jsxs("div",{className:"relative rounded-md border border-destructive-edge bg-destructive-subtle p-3",children:[a.jsx("div",{className:"absolute top-2 right-2",children:a.jsx(PM,{block:u})}),a.jsx(Y,{variant:"meta",className:"mb-1 text-destructive-subtle-foreground",children:"− Removed in latest"}),a.jsx(Y,{variant:"caption",className:"whitespace-pre-wrap text-destructive-subtle-foreground",children:f})]},c);if(f===h)return a.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[u&&a.jsx("div",{className:"absolute top-2 right-2",children:a.jsx(PM,{block:u})}),a.jsx(Y,{variant:"caption",tone:"muted",font:"mono",className:"whitespace-pre-wrap",children:f||"(empty)"})]},c);const p=$et(f,h);return a.jsxs("div",{className:"relative overflow-hidden rounded-md border border-border",children:[u&&a.jsx("div",{className:"absolute top-2 right-2 z-10",children:a.jsx(PM,{block:u})}),p.map((m,v)=>a.jsxs(Y,{as:"p",variant:"body",tone:"muted",className:Z("px-3 py-0.5 wrap-break-word whitespace-pre-wrap",m.type==="removed"&&"bg-destructive-subtle text-destructive-subtle-foreground",m.type==="added"&&"bg-success-subtle text-success-subtle-foreground"),children:[a.jsx("span",{className:"mr-2 inline-block w-4 shrink-0 text-muted-foreground/50 select-none",children:m.type==="removed"?"−":m.type==="added"?"+":" "}),m.text||" "]},v))]},c)})})}function svs({promptBlockId:e}){const{data:t,isLoading:n}=Nz({blockId:e,queryOptions:{enabled:!!e}});if(n)return a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(On,{className:"h-4 w-4"})});const r=t?.content??"";return a.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[r&&a.jsx("div",{className:"absolute top-2 right-2",children:a.jsx(ii,{content:r,tooltip:"Copy prompt block text",size:"sm"})}),t?.name&&a.jsx(Y,{variant:"meta",tone:"muted",className:"mb-1",children:t.name}),a.jsx(Y,{variant:"caption",tone:"muted",font:"mono",className:"whitespace-pre-wrap",children:r||"(empty)"})]})}function UBt({blocks:e}){const t=Array.isArray(e)?e:[];return t.length===0?a.jsx(Y,{variant:"caption",tone:"muted",className:"py-2",children:"No instruction blocks configured"}):a.jsx("div",{className:"flex flex-col gap-2",children:t.map((n,r)=>{if(n.type==="prompt_block_ref"){const i=n.promptBlockId??n.id;return a.jsx(svs,{promptBlockId:i},i??r)}const s=typeof n.content=="string"?n.content:"";return a.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[s&&a.jsx("div",{className:"absolute top-2 right-2",children:a.jsx(ii,{content:s,tooltip:"Copy prompt text",size:"sm"})}),a.jsx(Y,{variant:"caption",tone:"muted",font:"mono",className:"whitespace-pre-wrap",children:s||"(empty)"})]},n.id??r)})})}function ivs({previousTools:e,currentTools:t}){const n=new Set(e?Object.keys(e):[]),r=new Set(t?Object.keys(t):[]),s=[...new Set([...n,...r])].sort();return a.jsx("div",{className:"flex flex-col gap-1.5",children:s.map(i=>{const o=n.has(i),l=r.has(i);let c;return o&&l?c="same":o?c="removed":c="added",a.jsxs("div",{className:Z("flex items-center gap-2 rounded-md border px-3 py-1.5",c==="removed"&&"border-destructive-edge bg-destructive-subtle",c==="added"&&"border-success-edge bg-success-subtle",c==="same"&&"border-border bg-background"),children:[a.jsx(Y,{variant:"caption",font:"mono",className:Z(c==="removed"&&"text-destructive-subtle-foreground line-through",c==="added"&&"text-success-subtle-foreground"),children:i}),c==="removed"&&a.jsx($t,{variant:"destructive",className:"ml-auto",children:"removed in latest"}),c==="added"&&a.jsx($t,{variant:"success",className:"ml-auto",children:"added in latest"})]},i)})})}function ovs({tools:e}){const t=e?Object.entries(e):[];return t.length===0?a.jsx(Y,{variant:"caption",tone:"muted",className:"py-2",children:"No tools configured"}):a.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(([n,r])=>a.jsxs("div",{className:"rounded-md border border-border bg-background px-3 py-1.5",children:[a.jsx(Y,{variant:"caption",tone:"ink",font:"mono",children:n}),r?.description?a.jsx(Y,{variant:"meta",tone:"muted",className:"mt-0.5",children:String(r.description)}):null]},n))})}function avs({previousVars:e,currentVars:t}){const n=e?.properties??{},r=t?.properties??{},s=new Set(Object.keys(n)),i=new Set(Object.keys(r)),o=[...new Set([...s,...i])].sort();return o.length===0?a.jsx(Y,{variant:"caption",tone:"muted",className:"py-2",children:"No variables configured"}):a.jsx("div",{className:"flex flex-col gap-1.5",children:o.map(l=>{const c=s.has(l),u=i.has(l);let d;return c&&u?d="same":c?d="removed":d="added",a.jsxs("div",{className:Z("flex items-center gap-2 rounded-md border px-3 py-1.5",d==="removed"&&"border-destructive-edge bg-destructive-subtle",d==="added"&&"border-success-edge bg-success-subtle",d==="same"&&"border-border bg-background"),children:[a.jsx(Y,{variant:"caption",font:"mono",className:Z(d==="removed"&&"text-destructive-subtle-foreground line-through",d==="added"&&"text-success-subtle-foreground"),children:`{{${l}}}`}),d==="removed"&&a.jsx($t,{variant:"destructive",className:"ml-auto",children:"removed in latest"}),d==="added"&&a.jsx($t,{variant:"success",className:"ml-auto",children:"added in latest"})]},l)})})}function lvs({variables:e}){const t=e?.properties??{},n=Object.entries(t);return n.length===0?a.jsx(Y,{variant:"caption",tone:"muted",className:"py-2",children:"No variables configured"}):a.jsx("div",{className:"flex flex-col gap-1.5",children:n.map(([r,s])=>a.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border bg-background px-3 py-1.5",children:[a.jsx(Y,{variant:"caption",tone:"ink",font:"mono",children:`{{${r}}}`}),s?.type?a.jsx($t,{children:String(s.type)}):null]},r))})}function cvs({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r}=El(),s=r.watch("tools"),i=r.watch("variables"),o=r.watch("instructionBlocks"),l=s?Object.keys(s).length:0,{data:c,isLoading:u}=Tcr({agentId:e,fromVersionId:t,toVersionId:n,queryOptions:{enabled:!!e&&!!t&&!!n}}),d=g.useMemo(()=>{const x=new Map;if(c?.diffs)for(const b of c.diffs)x.set(b.field,{previousValue:b.previousValue,currentValue:b.currentValue});return x},[c]),f=d.get("instructions"),h=d.get("tools"),p=d.get("requestContextSchema"),m=f?a.jsx($t,{variant:"warning",size:"sm",children:"modified"}):null,v=h?a.jsx($t,{variant:"warning",size:"sm",children:"modified"}):l>0?a.jsx($t,{size:"sm",children:`${l}`}):null,y=p?a.jsx($t,{variant:"warning",size:"sm",children:"modified"}):null;return u?a.jsx("div",{className:"flex items-center justify-center py-5",children:a.jsx(On,{className:"h-5 w-5"})}):a.jsxs(Hc,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[a.jsxs(Gc,{variant:"pill-ghost",className:"shrink-0",children:[a.jsx(si,{value:"variables",children:a.jsx(tN,{title:"Variables",icon:a.jsx(Va,{}),badge:y})}),a.jsx(si,{value:"instructions",children:a.jsx(tN,{title:"System Prompt",icon:a.jsx(I_,{}),badge:m})}),a.jsx(si,{value:"tools",children:a.jsx(tN,{title:"Tools",icon:a.jsx(dd,{}),badge:v})})]}),a.jsx(No,{value:"variables",className:"px-4 py-4",children:p?a.jsx(avs,{previousVars:p.previousValue,currentVars:p.currentValue}):a.jsx(lvs,{variables:i})}),a.jsx(No,{value:"instructions",className:"px-4 py-4",children:f?a.jsx(rvs,{previousBlocks:f.previousValue,currentBlocks:f.currentValue}):a.jsx(UBt,{blocks:o})}),a.jsx(No,{value:"tools",className:"px-4 py-4",children:h?a.jsx(ivs,{previousTools:h.previousValue,currentTools:h.currentValue}):a.jsx(ovs,{tools:s})})]})}function uvs({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r,readOnly:s,isCodeAgentOverride:i,editorConfig:o}=El(),{isInstructionsLocked:l}=oT(i,o),c=r.watch("tools"),u=r.watch("instructionBlocks"),d=r.watch("variables"),f=c?Object.keys(c).length:0,h=g.useMemo(()=>Object.entries(d?.properties??{}),[d]),p=s&&!!t&&!!n&&t!==n;return a.jsxs("div",{className:"flex h-full flex-col",children:[a.jsx("div",{className:"border-b border-border px-4 py-3"}),a.jsx(jr,{className:"min-h-0 flex-1",children:p?a.jsx(cvs,{agentId:e,selectedVersionId:t,latestVersionId:n}):a.jsxs(Hc,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[a.jsxs(Gc,{variant:"pill-ghost",className:"shrink-0",children:[a.jsx(si,{value:"variables",children:a.jsx(tN,{title:"Variables",icon:a.jsx(Va,{})})}),a.jsx(si,{value:"instructions",children:a.jsx(tN,{title:"System Prompt",icon:a.jsx(I_,{})})}),a.jsx(si,{value:"tools",children:a.jsx(tN,{title:"Tools",icon:a.jsx(dd,{}),badge:f>0?a.jsx($t,{size:"sm",children:`${f}`}):void 0})})]}),a.jsx(No,{value:"variables",className:"py-0",children:a.jsxs("div",{className:"flex flex-col gap-1 px-4 py-4",children:[h.length>0?a.jsx("div",{className:"flex flex-col",children:h.map(([m,v])=>a.jsx(VBt,{name:m,prop:v,depth:0},m))}):null,a.jsx(Y,{variant:"meta",tone:"muted",className:"mt-1",children:h.length>0?"Defined via requestContextSchema in code.":"No variables defined. Add a requestContextSchema to your agent to define variables."})]})}),a.jsxs(No,{value:"instructions",className:"px-4 py-0 pb-4",children:[a.jsx("div",{className:"flex flex-col gap-3 pt-4 pb-2",children:a.jsxs(Y,{variant:"caption",tone:"muted",children:["Add instruction blocks to your agent. Blocks are combined in order to form the system prompt. You can"," ",a.jsxs(Qn,{children:[a.jsx(Fn,{className:Z("inline cursor-pointer underline decoration-dotted",Zn,In),children:"use variables"}),a.jsx(Bn,{side:"bottom",align:"start",className:"max-w-72",children:a.jsxs("span",{children:["Use ",a.jsx(rh,{className:"text-column text-foreground",children:"{{variableName}}"})," syntax to insert dynamic values into your instruction blocks."]})})]})," ","as part of your instruction blocks."]})}),s||l?a.jsx(UBt,{blocks:u}):a.jsx(mBt,{})]}),a.jsx(No,{value:"tools",className:"px-4 py-0 pb-4",children:a.jsx(gBt,{})})]})})]})}function Jce(e){return typeof e=="object"&&e!==null}function dvs(e){if(!Jce(e))return{};const t={};return typeof e.maxSteps=="number"&&(t.maxSteps=e.maxSteps),Jce(e.modelSettings)&&(t.modelSettings=e.modelSettings),Jce(e.providerOptions)&&(t.providerOptions=e.providerOptions),t}function RNe(e){if(!e)return{modelSettings:{}};const t=dvs(e.defaultOptions),{maxOutputTokens:n,...r}=t.modelSettings??{};return{modelSettings:{...r,...n!==void 0&&{maxTokens:n},...t.maxSteps!==void 0&&{maxSteps:t.maxSteps},...t.providerOptions!==void 0&&{providerOptions:t.providerOptions}}}}function MNe({agentId:e}){return a.jsxs(a.Fragment,{children:[a.jsx(Wke,{entityType:"agent",entityId:e}),a.jsx(pjt,{entityType:"agent",entityId:e})]})}function fvs({ctx:e}){const{isDirty:t}=ZSe({control:e.form.control}),n=e.handleSaveDraft,r=e.isSavingDraft??!1,s=e.isCodeSourceAgent??!1;if(!t)return null;const i=s?"Save to filesystem":"Save draft",o=s?"You have unsaved changes to the agent configuration. Save to filesystem to ensure the chat uses your latest changes.":"You have unsaved changes to the agent configuration. Save your draft to ensure the chat uses your latest changes.";return a.jsx(Wt,{variant:"warning",title:"Unsaved changes",className:"mx-4 mt-3 mb-0",action:n&&a.jsx(ce,{type:"button",variant:"default",size:"sm",onClick:()=>n(),disabled:r,icon:a.jsx(Bm,{}),children:r?"Saving...":i}),children:a.jsx(Wt.Message,{children:o})})}function hvs({agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s}){const i=g.useMemo(()=>ka(),[e]),o=xr("agent",e)[0],l=Object.keys(o).length>0,c=qXr(),{data:u}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),d=g.useMemo(()=>RNe(u),[u]);return a.jsx(f4t,{agentId:e,defaultSettings:d,children:a.jsx(CX,{children:a.jsxs(_X,{agentId:e,threadId:i,enabled:!!(u?.hasBrowser??u?.browserTools?.length),children:[a.jsx(gNe,{children:a.jsx(EX,{children:a.jsx(HJr,{enabled:!0,threadId:i,agentId:e,requestContext:l?o:void 0,children:a.jsxs("div",{className:"flex h-full flex-col",children:[c&&a.jsx(fvs,{ctx:c}),a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx(KNe,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,supportsMemory:u?.supportsMemory,threadId:i,memory:s,modelList:u?.modelList,isNewThread:!0,runOptionsSlot:a.jsx(MNe,{agentId:e})},i)})]})})},i)}),a.jsx(MDt,{})]},`session-${e}-${i}`)},`browser-${e}-${i}`)})}function pvs({agentId:e,activeVersionId:t,selectedVersionId:n,onVersionSelect:r,isDirty:s,isSavingDraft:i,isPublishing:o,hasDraft:l,readOnly:c,isCodeSourceAgent:u=!1,showCodeModeActions:d=!1,canOpenPr:f=!1,openPrTitle:h,onSaveDraft:p,onPublish:m,onDownloadJson:v,onOpenPr:y,isViewingPreviousVersion:x=!1}){const[b,S]=g.useState(!1),[k,j]=g.useState(""),{data:C}=t6({agentId:e,params:{orderBy:{direction:"DESC"}},queryOptions:{enabled:!!e}}),T=g.useMemo(()=>C?.versions??[],[C?.versions]),_=T[0],E=(t?T.find(q=>q.id===t):void 0)?.versionNumber,A=g.useMemo(()=>T.map(q=>{const B=q.id===t,V=E!==void 0&&q.versionNumber>E;return{value:q.id,label:`${u?"Save":"v"}${q.versionNumber} - ${rs(q.createdAt,"date-time")??""}`,description:q.changeMessage||void 0,end:u?a.jsx($t,{variant:B?"success":"info",children:B?"Current":"Saved"}):B?a.jsx($t,{variant:"success",children:"Published"}):V?a.jsx($t,{variant:"info",children:"Draft"}):void 0}}),[T,t,E,u]),P=n??_?.id??"",L=c||!s||i||o,F=u?"Code mode saves write override JSON to filesystem-backed editor storage. This dropdown shows saved override snapshots for this agent.":"Changes are saved as draft versions. When you're ready, publish a version to make it the active configuration used in production.",Q=g.useCallback(async()=>{if(i)return;const q=k.trim();await p(q||void 0),S(!1),j("")},[k,p,i]);return{versionSelector:a.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-card px-4 py-3",children:[T.length>0?a.jsx(fl,{options:A,value:P,onValueChange:r,placeholder:"Select version...",variant:"ghost",className:"min-w-0 flex-1"}):a.jsx(Y,{variant:"meta",tone:"muted",children:u?"No filesystem saves yet":"No versions yet"}),P&&a.jsx(ii,{content:P,tooltip:"Copy version ID",size:"sm"}),a.jsx(hG,{"aria-label":"Version information",side:"bottom",align:"start",contentClassName:"max-w-56",children:F}),a.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[c&&a.jsx($t,{variant:"warning",children:"Read-only"}),!c&&l&&!u&&a.jsx($t,{variant:"info",children:"Unpublished"})]})]}),actionBar:a.jsxs("div",{className:"flex items-center justify-end border-t border-border bg-card px-3 py-2",children:[d?a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[a.jsx(ce,{variant:"default",size:"md",onClick:()=>{v?.()},icon:a.jsx(fp,{}),children:"Download JSON"}),f?a.jsx(ce,{variant:"primary",size:"md",onClick:()=>{y?.()},title:h,icon:a.jsx(opt,{}),children:"Open PR"}):a.jsx(ce,{variant:"primary",size:"md",onClick:()=>{p()},disabled:L,children:i?a.jsxs(a.Fragment,{children:[a.jsx(On,{className:"size-3.5"}),"Saving…"]}):a.jsxs(a.Fragment,{children:[a.jsx(At,{size:"xs",children:a.jsx(Bm,{})}),"Save to filesystem"]})})]}):c&&!x?null:a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[a.jsxs(mc,{children:[a.jsx(ce,{variant:"default",onClick:()=>p(),disabled:L,children:i?a.jsxs(a.Fragment,{children:[a.jsx(On,{className:"size-3.5"}),"Saving…"]}):a.jsxs(a.Fragment,{children:[a.jsx(At,{size:"xs",children:a.jsx(Bm,{})}),"Save New Version"]})}),a.jsxs(lt,{children:[a.jsx(lt.Trigger,{asChild:!0,children:a.jsx(ce,{variant:"default",disabled:L,"aria-label":"More save options",children:a.jsx(fc,{className:"size-3.5"})})}),a.jsx(lt.Content,{align:"end",children:a.jsxs(lt.Item,{onSelect:()=>S(!0),children:[a.jsx(At,{size:"xs",children:a.jsx(hL,{})}),"Save with message"]})})]})]}),a.jsx(ce,{variant:"primary",size:"md",onClick:m,disabled:x?n===t||o||i:c||!l||o||i,children:o?a.jsxs(a.Fragment,{children:[a.jsx(On,{className:"size-3.5"}),"Publishing…"]}):a.jsxs(a.Fragment,{children:[a.jsx(At,{size:"xs",children:a.jsx(ur,{})}),x?"Publish This Version":"Publish"]})})]}),a.jsx(Yr,{open:b,onOpenChange:S,pending:i,children:a.jsxs(Xr,{children:[a.jsxs(Jr,{children:[a.jsx(Zr,{children:"Save New Version"}),a.jsx(Lo,{children:"Add a message to describe the changes in this version."})]}),a.jsx(Qr,{children:a.jsxs(pt,{children:[a.jsx(dt,{children:"Change message"}),a.jsx(bn,{placeholder:"Describe what changed...",value:k,onChange:q=>j(q.target.value),onKeyDown:q=>{q.key==="Enter"&&Q()},disabled:i,autoFocus:!0})]})}),a.jsxs(Yo,{children:[a.jsx(_a,{children:"Cancel"}),a.jsx(Ca,{onConfirm:Q,children:"Save Version"})]})]})})]})}}function mvs({agentId:e,activeVersionId:t,selectedVersionId:n,latestVersionId:r,onVersionSelect:s,isDirty:i,isSavingDraft:o,isPublishing:l,hasDraft:c,readOnly:u,isCodeSourceAgent:d,showCodeModeActions:f,canOpenPr:h,openPrTitle:p,onSaveDraft:m,onPublish:v,onDownloadJson:y,onOpenPr:x,isViewingPreviousVersion:b}){const{versionSelector:S,actionBar:k}=pvs({agentId:e,activeVersionId:t,selectedVersionId:n,onVersionSelect:s,isDirty:i,isSavingDraft:o,isPublishing:l,hasDraft:c,readOnly:u,isCodeSourceAgent:d,showCodeModeActions:f,canOpenPr:h,openPrTitle:p,onSaveDraft:m,onPublish:v,onDownloadJson:y,onOpenPr:x,isViewingPreviousVersion:b});return a.jsxs($Ne,{children:[S,a.jsx("div",{className:"px-4 pt-3",children:a.jsx(Y,{variant:"caption",tone:"muted",children:"Edit your agent's system prompt, tools, and variables below."})}),a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx(uvs,{agentId:e,selectedVersionId:n,latestVersionId:r})}),k]})}function gvs({agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s,activeVersionId:i,selectedVersionId:o,latestVersionId:l,onVersionSelect:c,isDirty:u,isSavingDraft:d,isPublishing:f,hasDraft:h,readOnly:p,isCodeSourceAgent:m,showCodeModeActions:v,canOpenPr:y,openPrTitle:x,onSaveDraft:b,onPublish:S,onDownloadJson:k,onOpenPr:j,isViewingPreviousVersion:C}){return a.jsx(vye,{agentId:e,leftDrawerLabel:"Open configuration",leftSlot:a.jsx(mvs,{agentId:e,activeVersionId:i,selectedVersionId:o,latestVersionId:l,onVersionSelect:c,isDirty:u,isSavingDraft:d,isPublishing:f,hasDraft:h,readOnly:p,isCodeSourceAgent:m,showCodeModeActions:v,canOpenPr:y,openPrTitle:x,onSaveDraft:b,onPublish:S,onDownloadJson:k,onOpenPr:j,isViewingPreviousVersion:C}),children:a.jsx(hvs,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s})})}function HJ(e,t,n){const r=e.get(t);if(r!==void 0)return r;const s=n();return e.set(t,s),s}const vvs=3e4;function qBt(e){return s6(e.state.error,"feedback")||i6(e.state.error)?!1:vvs}const DNe={input:"Input",inputStep:"Input step",llmRequest:"LLM request",llmResponse:"LLM response",outputStream:"Output stream",outputResult:"Output result",outputStep:"Output step",toolResult:"Tool result",requestError:"Request error"};function GJ(e){const t=e.attributes?.processorPhase;return typeof t=="string"&&Object.hasOwn(DNe,t)?t:void 0}function QBt(e,t){const n=GJ(e);if(!(!n||Object.keys(t).length===0))return{phase:n,phaseLabel:DNe[n],data:t}}function yvs(e,t){return QBt(e,t)}function xvs(e,t){return QBt(e,t)}const bvs=["processorPhase","processorExecutor","processorIndex","hookDurationMs","messageListMutations","tripwireAbort"];function ZBt(e){const t=GJ(e);if(!t)return;const n=e.attributes??{},r=Array.isArray(n.messageListMutations)?n.messageListMutations:void 0,s=typeof n.tripwireAbort=="object"&&n.tripwireAbort!==null?n.tripwireAbort:void 0,i=new Set(bvs);n.messageListMutations!==void 0&&!r&&i.delete("messageListMutations"),n.tripwireAbort!==void 0&&!s&&i.delete("tripwireAbort");const o={};for(const[l,c]of Object.entries(n))i.has(l)||(o[l]=c);return{phase:t,phaseLabel:DNe[t],executor:n.processorExecutor,processorIndex:n.processorIndex,hookDurationMs:n.hookDurationMs,messageListMutations:r,tripwireAbort:s,...Object.keys(o).length>0?{rest:o}:{}}}const Nj=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),eue=e=>e.status==="suspended"||e.status==="aborted"||e.status==="interrupted",wvs=["agent_run","model_step","model_inference"];function WBt(e){const t=e.input;if(t==null)return;if(e.spanType==="agent_run"&&e.metadata?.resumed===!0)return{type:"agent-run-resume",value:Nj(t)?t:{resumeData:t}};if(GJ(e)){const r=Nj(t)?yvs(e,t):void 0;return r?{type:"processor",value:r}:{type:"json",value:t}}if(typeof t=="string")return{type:"text",value:t};if(Array.isArray(t))return wvs.includes(e.spanType)?{type:"messages",value:t}:{type:"json",value:t};if(!Nj(t))return{type:"json",value:t};const n=e.spanType==="agent_run";if((n||e.spanType==="model_generation")&&"messages"in t){const{messages:r}=t;if(typeof r=="string")return{type:"text",value:r};if(Array.isArray(r))return{type:"messages",value:r};if(Nj(r))return{type:"messages",value:[r]}}if(n){if(typeof t.role=="string")return{type:"messages",value:[t]};if("toolCallId"in t||"toolName"in t||"resumeData"in t)return{type:"agent-run-resume",value:t}}return{type:"json",value:t}}function HBt(e){const t=e.output;if(t!=null){if(GJ(e)){const n=Nj(t)?xvs(e,t):void 0;return n?{type:"processor",value:n}:{type:"json",value:t}}if(typeof t=="string")return{type:"text",value:t};if(!Nj(t))return{type:"json",value:t};switch(e.spanType){case"agent_run":return eue(t)?{type:"interrupted",value:t}:{type:"agent-run-result",value:t};case"model_generation":return eue(t)?{type:"interrupted",value:t}:{type:"model-generation-result",value:t};case"model_step":return eue(t)?{type:"interrupted",value:t}:{type:"model-step-result",value:t};case"model_inference":return{type:"model-step-result",value:t};default:return{type:"json",value:t}}}}const Svs=e=>Nj(e)&&typeof e.message=="string";function kvs(e){return Svs(e.error)?e.error:void 0}const $z=300*1e3;function Ovs({traceId:e,spanId:t,depth:n,queryOptions:r}){return Ke(),Ct({queryKey:["branch",e,t,n],queryFn:async()=>{throw new Error("traceId and spanId are required")},staleTime:0,...r})}const z2={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"};function Ret(e){return Object.values(od).find(t=>t===e)}const LNe=({entityType:e,rootOnly:t=!1,queryOptions:n}={})=>{const r=Ke();return Ct({queryKey:e?["observability-entity-names","by-type",e]:["observability-entity-names","all",t?"root-only":"all-types"],queryFn:async()=>{try{if(e){const i=Ret(e);return i?await r.getEntityNames({entityType:i}):{names:[]}}if(!t)return await r.getEntityNames();const s=await Promise.all(Object.values(z2).map(i=>{const o=Ret(i);return o?r.getEntityNames({entityType:o}):{names:[]}}));return{names:Array.from(new Set(s.flatMap(i=>i?.names??[]))).sort()}}catch{return{names:[]}}},select:s=>s?.names??[],retry:!1,staleTime:$z,...n})},zNe=({queryOptions:e}={})=>{const t=Ke();return Ct({queryKey:["observability-environments"],queryFn:async()=>{try{return await t.getEnvironments()}catch{return{environments:[]}}},select:n=>n?.environments??[],retry:!1,staleTime:$z,...e})},GBt=({queryOptions:e}={})=>{const t=Ke();return Ct({queryKey:["observability-service-names"],queryFn:async()=>{try{return await t.getServiceNames()}catch{return{serviceNames:[]}}},select:n=>n?.serviceNames??[],retry:!1,staleTime:$z,...e})},jvs=1e3*60*60*24*30;function FNe({traceId:e,spanId:t,queryOptions:n}){const r=Ke();return Ct({queryKey:["span-detail",e,t],queryFn:async()=>{if(!e||!t)throw new Error("Trace ID and Span ID are required");return r.getSpan(e,t)},staleTime:s=>s.state.data?.span?.endedAt?jvs:0,...n})}const KBt=({queryOptions:e}={})=>{const t=Ke();return Ct({queryKey:["observability-tags"],queryFn:async()=>{try{return await t.getTags()}catch{return{tags:[]}}},select:n=>n?.tags??[],retry:!1,staleTime:$z,...e})};function Cvs({threadId:e,queryOptions:t}){const n=Ke(),{data:r}=Ct({queryKey:["thread-trace-count",e],queryFn:()=>n.listTracesLight({filters:{threadId:e??""},pagination:{page:0,perPage:25}}),select:s=>(s.spans?.length??0)>1,...t});return r??!1}const BNe=(e,t)=>({queryKey:["trace-spans",t],queryFn:async()=>{if(!t)throw new Error("Trace ID is required");return await e.getTrace(t)},staleTime:0});function aT({traceId:e,passive:t=!1,queryOptions:n}){const r=Ke(),{queryKey:s,queryFn:i,enabled:o,staleTime:l}=BNe(r,e);return Ct({queryKey:s,queryFn:i,enabled:o,staleTime:l,refetchOnMount:!t,refetchOnWindowFocus:!t,refetchOnReconnect:!t,...n})}function _vs(){const e=Ke(),t=mr();return n=>t.fetchQuery(BNe(e,n))}function Tvs({traceId:e,anchorSpanId:t,listMode:n,depth:r,queryOptions:s}){const i=n==="branches",o=aT({traceId:e,queryOptions:{enabled:!!e,...s?.trace}});return Ovs({traceId:null,spanId:null,depth:r,queryOptions:{enabled:i,...s?.branch}}),{spans:o.data?.spans,anchorSpanId:void 0,isLoading:o.isLoading,isError:o.isError,error:o.error}}function Ivs(e){return e?.page.next??void 0}function Evs(e){const t=new Set;return e.pages.flatMap(n=>n.traces.filter(r=>t.has(r.traceId)?!1:(t.add(r.traceId),!0)))}const tue=e=>typeof e=="string"?e:e.toISOString();function Nvs(e){return{traceId:e.traceId,rootSpanId:e.spanId,name:e.name,entityId:e.entityId??null,parentSpanId:e.parentSpanId??null,createdAt:tue(e.createdAt),metadata:e.metadata??null,inputPreview:e.inputPreview??null,outputPreview:e.outputPreview??null,errorPreview:e.errorPreview??null,threadId:e.threadId??null,resourceId:e.resourceId??null,startedAt:tue(e.startedAt),endedAt:e.endedAt==null?e.endedAt:tue(e.endedAt),entityName:e.entityName??null,entityType:e.entityType??null,environment:null,status:e.status}}function Avs(e){const t=new Set;return e.pages.flatMap(n=>n.spans.flatMap(r=>t.has(r.traceId)?[]:(t.add(r.traceId),[Nvs(r)])))}function Pvs(e){return e.pagination?.hasMore?e.pagination.page+1:void 0}function $vs({query:e,limit:t=25,enabled:n=!0,withQueryTrace:r=!0,legacyFilters:s,queryOptions:i}){const o=Ke(),{inView:l,setRef:c}=X0(),u=Mm({queryKey:["trace-query",e,t],queryFn:e?async({pageParam:E})=>{const A=await new hj({...o.options,retries:0}).queryTraces({...e,page:{limit:t,after:E??null}});if("traces"in A&&"page"in A)return A;throw new Error("Expected a cursor-paginated trace query response")}:Q0,initialPageParam:void 0,getNextPageParam:Ivs,select:Evs,retry:!1,placeholderData:px,enabled:n&&r,...i?.traceQuery}),d=e?.orderBy,f=d?.[0]?.direction==="asc"?"ASC":"DESC",h=Mm({queryKey:["trace-query-legacy",s,t,d],queryFn:({pageParam:E})=>o.listTracesLight({filters:s,pagination:{page:E,perPage:t},orderBy:{field:"startedAt",direction:f}}),initialPageParam:0,getNextPageParam:Pvs,select:Avs,retry:!1,placeholderData:px,enabled:n&&!r,...i?.legacy}),{data:p,hasNextPage:m,isFetchingNextPage:v,fetchNextPage:y,isLoading:x,isPlaceholderData:b,isFetching:S,isRefetching:k,fetchStatus:j,isError:C,error:T,refetch:_,isFetchNextPageError:N}=r?u:h;return g.useEffect(()=>{n&&l&&m&&!S&&!N&&y()},[n,l,m,S,N,y]),{data:p,hasNextPage:m,isFetchingNextPage:v,fetchNextPage:y,isLoading:x,isPlaceholderData:b,isFetching:S,isRefetching:k,fetchStatus:j,isError:C,error:T,refetch:_,setEndOfListElement:c}}const _ye="mastra_model_total_input_tokens",YBt="mastra_model_total_output_tokens",Met=500;function Rvs(e){const t=[];for(let n=0;n<e.length;n+=Met)t.push(e.slice(n,n+Met));return t}function Mvs(){return{estimatedCost:0,hasEstimatedCost:!1,costUnits:new Set,hasUnknownCostUnit:!1}}function Dvs(e,t){for(const n of t.groups){const r=n.dimensions.traceId,s=n.dimensions.name;if(!r||s!==_ye&&s!==YBt)continue;const i=HJ(e,r,Mvs),o=s===_ye?"inputTokens":"outputTokens";i[o]=(i[o]??0)+n.value,n.estimatedCost!=null&&(i.estimatedCost+=n.estimatedCost,i.hasEstimatedCost=!0,n.costUnit?i.costUnits.add(n.costUnit.toLowerCase()):i.hasUnknownCostUnit=!0)}}function Lvs(e){const t=new Map;for(const[n,r]of e){const s={inputTokens:r.inputTokens,outputTokens:r.outputTokens};r.hasEstimatedCost&&!r.hasUnknownCostUnit&&r.costUnits.size===1&&(s.estimatedCost=r.estimatedCost,s.costUnit=[...r.costUnits][0]),t.set(n,s)}return t}function Tye({traceIds:e,enabled:t,autoRefetch:n,queryOptions:r}){const s=Ke(),i=[...new Set(e)].toSorted(),o=`${s.options.baseUrl||(typeof window>"u"?"local":window.location.origin||"local")}:${s.options.apiPrefix??"/api"}`;return Ct({queryKey:["trace-usage",o,i],enabled:t&&i.length>0,queryFn:async()=>{const l=Rvs(i),c=await Promise.allSettled(l.map(d=>s.getMetricBreakdown({name:[_ye,YBt],aggregation:"sum",groupBy:["traceId","name"],filters:{traceIds:d},limit:d.length*2}))),u=new Map;for(const d of c)d.status==="fulfilled"&&Dvs(u,d.value);return Lvs(u)},placeholderData:(l,c)=>c?.queryKey[1]===o?l:void 0,refetchInterval:t&&n?1e4:!1,...r})}const XBt=({traceId:e,spanId:t,queryOptions:n})=>{const r=Ke(),s=mr();return wn({mutationFn:({text:i})=>r.createFeedback({feedback:{traceId:e,...t?{spanId:t}:{},feedbackType:"comment",feedbackSource:"user",value:i}}),onSuccess:()=>s.invalidateQueries({queryKey:t?["span-feedback",e,t]:["trace-feedback",e]}),...n})},JBt=({traceId:e,spanId:t,queryOptions:n})=>{const r=Ke(),s=mr();return wn({mutationFn:({feedbackId:i})=>r.deleteFeedback({feedbackIds:[i]}),onSuccess:()=>s.invalidateQueries({queryKey:t?["span-feedback",e,t]:["trace-feedback",e]}),...n})},VNe=({traceId:e="",spanId:t="",page:n,queryOptions:r})=>{const s=Ke(),i=n??0;return Ct({queryKey:["span-feedback",e,t,i],queryFn:()=>s.listFeedback({filters:{traceId:e,spanId:t},pagination:{page:i,perPage:10}}),refetchInterval:qBt,gcTime:0,staleTime:0,...r})},KJ=({traceId:e="",page:t,queryOptions:n})=>{const r=Ke(),s=t??0;return Ct({queryKey:["trace-feedback",e,s],queryFn:()=>r.listFeedback({filters:{traceId:e},pagination:{page:s,perPage:10}}),select:i=>{const o=i.feedback.filter(l=>!l.spanId);return i.pagination?{...i,feedback:o,pagination:{...i.pagination,total:o.length}}:{...i,feedback:o}},refetchInterval:qBt,gcTime:0,staleTime:0,...n})},eVt=100,Det={canonicalFields:[],observedFields:[],observedFieldsTruncated:!1},zvs="TRACE_QUERY_DISCOVERY_UNSUPPORTED",Fvs=e=>e instanceof hv&&typeof e.body=="object"&&e.body!==null&&e.body.code===zvs,Bvs=e=>["trace-query-fields",e.from,e.to],tVt=(e,t,n,r)=>async({query:s,signal:i})=>{const{values:o}=await e.getTraceQueryValues({timeRange:t,predicateScope:n,path:r,search:s.trim()||void 0,limit:eVt},{signal:i});return o.map(({value:l})=>({value:l}))},Vvs=({timeRange:e,queryOptions:t})=>{const n=Ke(),r=Ct({queryKey:Bvs(e),queryFn:async({signal:o})=>{try{return await n.getTraceQueryFields({timeRange:e,predicateScope:"trace",limit:eVt},{signal:o})}catch(l){if(Fvs(l))return Det;throw l}},retry:!1,staleTime:$z,placeholderData:px,...t}),s=r.data?.observedFields,i=r.data?.canonicalFields??Det.canonicalFields;return{fields:g.useMemo(()=>(s??[]).map(o=>({path:o.path,suggestions:tVt(n,e,"trace",o.path)})),[s,n,e]),canonicalFields:i,isLoading:r.isLoading,error:r.error}};function Uvs(){const e=Ke();return`mastra:traces:columns:${e.options.baseUrl||(typeof window>"u"?"local":window.location.origin||"local")}:${e.options.apiPrefix??"/api"}`}const Iye=(e,t)=>e==="number"?Number(t):e==="boolean"?t.toLowerCase()==="true":t,qa=e=>"kind"in e&&e.kind==="group",UNe=new Set(["runId","sessionId","requestId","userId","organizationId","serviceName","experimentId"]),qvs=["is","isNot","in","notIn","exists","notExists","gt","gte","lt","lte","matches","notMatches"],qNe=e=>qvs.includes(e),Eye=e=>"nodes"in e,Qvs={is:"eq",isNot:"ne",in:"in",notIn:"notIn",exists:"exists",notExists:"notExists",gt:"gt",gte:"gte",lt:"lt",lte:"lte",matches:"matches",notMatches:"notMatches"},nVt=new Set(["durationMs","spans.durationMs","scores.score","feedback.value"]),Zvs=new Set(["entityType","status","entityName","environment","traceId","threadId","resourceId","durationMs"]),Wvs=new Set(["threadId","resourceId","environment","durationMs"]),rVt={isNot:"is",notIn:"in",notExists:"exists",notMatches:"matches"},Hvs=e=>e in rVt,sVt=["spans","scores","feedback"];function Gvs(e){if(e==="entityId")return{scope:"spans",path:"entityId"};for(const t of sVt)if(e.startsWith(`${t}.`)&&e.length>t.length+1)return{scope:t,path:e.slice(t.length+1)};return{path:e}}function Let(e,t,n){const r=Qvs[e];switch(r){case"exists":case"notExists":return{op:r,path:t};case"in":case"notIn":return n.length?{op:r,value:{path:t},set:n}:void 0;case"matches":case"notMatches":{const[s]=n;return typeof s=="string"?{op:r,left:{path:t},right:{literal:s}}:void 0}default:{if(!n.length)return;if(n.length>1){if(r==="eq")return{op:"in",value:{path:t},set:n};if(r==="ne")return{op:"notIn",value:{path:t},set:n}}const[s]=n;return s===void 0?void 0:{op:r,left:{path:t},right:{literal:s}}}}}function Kvs(e,t){if(e==="exists"||e==="notExists")return{op:e,path:"tags"};const n=e==="notIn"||e==="isNot",r=t.map(i=>({op:n?"notIncludes":"includes",path:"tags",value:i})),s=r.length<=1?r[0]:{op:n?"and":"or",args:r};return!s||!n?s:{op:"or",args:[s,{op:"notExists",path:"tags"}]}}const Yvs=new Set(["spans.error"]);function Xvs(e,t){if(UNe.has(e.fieldId)||t.has(e.fieldId))return;const n=e.operatorId??(e.fieldId==="tags"?"in":"is"),r=n==="exists"||n==="notExists";if(Yvs.has(e.fieldId)&&!r)return;const s=(Array.isArray(e.value)?e.value:[e.value]).filter(f=>typeof f=="string"&&!!f.trim()&&!QNe(f,n));if(!s.length&&!r)return;if(e.fieldId==="tags"){const f=Kvs(n,s);return f?{predicate:f}:void 0}let i=e.fieldId,o=s;if(i.startsWith("metadata.")){if(i.length===9)return}else if(i==="rootEntityType"||i==="entityType")i="entityType";else if(i==="status"){if(o=s.filter(f=>f!=="running"),!o.length&&!r)return}else if(nVt.has(i)&&(o=s.map(Number).filter(f=>!Number.isNaN(f)),!o.length&&!r))return;if((n==="matches"||n==="notMatches")&&(o=o.filter(f=>/[\p{L}\p{M}\p{N}]/u.test(String(f))),!o.length))return;const{scope:l,path:c}=Gvs(i),u=i.startsWith("metadata.");if(!l&&!u&&!Zvs.has(i))return;if(l&&Hvs(n)){const f=Let(rVt[n],c,o);return f?{predicate:{[l]:{none:f}}}:void 0}const d=Let(n,c,o);if(d)return l?{scope:l,predicate:d}:(n==="isNot"||n==="notIn")&&(u||Wvs.has(i))?{predicate:{op:"or",args:[d,{op:"notExists",path:c}]}}:{predicate:d}}function iVt(e,{mergeRelated:t,excludedFieldIds:n}){const r=[],s={spans:[],scores:[],feedback:[]};for(const i of e){const o=Xvs(i,n);o&&("scope"in o?t?s[o.scope].push(o.predicate):r.push({[o.scope]:{some:o.predicate}}):r.push(o.predicate))}for(const i of sVt){const[o,...l]=s[i];if(!o)continue;const c=l.length?{op:"and",args:[o,...l]}:o;r.push({[i]:{some:c}})}return r}function oVt(e,t){const n=e.nodes.filter(s=>!Eye(s)),r=iVt(n,{mergeRelated:e.logic==="and",excludedFieldIds:t});for(const s of e.nodes){if(!Eye(s))continue;const i=oVt(s,t);i&&r.push(i)}if(r.length!==0)return r.length===1?r[0]:{op:e.logic,args:r}}function zet({rootEntityType:e,status:t,dateFrom:n,dateTo:r,tokens:s,groups:i=[],excludedFieldIds:o=new Set,now:l}){const c=[];e&&c.push({op:"eq",left:{path:"entityType"},right:{literal:e}}),t&&t!=="running"&&c.push({op:"eq",left:{path:"status"},right:{literal:t}}),c.push(...iVt(s,{mergeRelated:!0,excludedFieldIds:o}));for(const u of i){const d=oVt(u,o);d&&c.push(d)}return{timeRange:{from:(n??new Date(l.getTime()-10080*60*1e3)).toISOString(),to:(r??l).toISOString()},...c.length?{where:{op:"and",args:c}}:{}}}const aVt=[{label:"Agent",entityType:z2.AGENT},{label:"Workflow",entityType:z2.WORKFLOW},{label:"Scorer",entityType:z2.SCORER},{label:"Ingest",entityType:z2.INGEST}],Jvs=[{label:"Running",value:"running"},{label:"Success",value:"success"},{label:"Error",value:"error"}],S3="metadata.",CW="filterMetadata.",lVt=e=>e.startsWith(S3)&&e.length>S3.length,YJ=e=>e.startsWith(CW)&&e.length>CW.length,eys=e=>CW+e.slice(S3.length),tys=e=>S3+e.slice(CW.length),S$="rootEntityType",k$="status",Fet={rootEntityType:S$,status:k$},B1="listMode",_V="anchorSpanId",nys=new Set(["traces","branches"]),V1="datePreset",w1="dateFrom",S1="dateTo",rys=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),yl={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",traceId:"filterTraceId",durationMs:"filterDurationMs",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId","spans.name":"filterSpanName","spans.spanType":"filterSpanType","spans.model":"filterSpanModel","spans.provider":"filterSpanProvider","spans.durationMs":"filterSpanDurationMs","spans.error":"filterSpanError","scores.scorerId":"filterScorerId","scores.score":"filterScore","feedback.feedbackType":"filterFeedbackType","feedback.value":"filterFeedbackValue","feedback.comment":"filterFeedbackComment"},XJ=Object.keys(yl),cVt=".op",oS=e=>e+cVt,uVt=e=>e.endsWith(cVt),dVt=e=>e==="exists"||e==="notExists",sys=e=>e==="in"||e==="notIn",qA=e=>e.operatorId??(Array.isArray(e.value)?"in":"is"),QNe=(e,t)=>e==="Any"&&t!=="matches"&&t!=="notMatches",Nye=(e,t)=>{const n=e.get(oS(t));return n!==null&&qNe(n)?n:void 0},iys=new Set(["running","success","error"]),ZNe="mastra:traces:saved-filters";function oys(e,t=ZNe){const n=Tys(e),r=e.get(V1);r&&r!=="custom"&&n.set(V1,r);const s=GNe(n).filter(i=>i.nodes.length>0);n.delete(i_);for(const i of s)n.append(i_,HNe(i));if(!n.toString()){ays(t);return}try{localStorage.setItem(t,n.toString())}catch{}}function ays(e=ZNe){try{localStorage.removeItem(e)}catch{}}function lys(e=ZNe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function cys(e){if(e.has(V1)||e.has(w1)||e.has(S1)||e.has(S$)||e.has(k$)||e.has(B1)||e.has(i_))return!0;for(const t of XJ)if(e.has(yl[t]))return!0;for(const t of e.keys())if(YJ(t))return!0;return!1}const uys=[{id:"is",label:"is",widensTo:"in"},{id:"isNot",label:"is not",widensTo:"notIn"},{id:"in",label:"is any of",arity:"many"},{id:"notIn",label:"is none of",arity:"many"},{id:"exists",label:"exists",arity:"none"},{id:"notExists",label:"does not exist",arity:"none"},{id:"gt",label:"greater than"},{id:"gte",label:"at least"},{id:"lt",label:"less than"},{id:"lte",label:"at most"},{id:"matches",label:"matches",freeText:!0},{id:"notMatches",label:"does not match",freeText:!0}],F2=["is","isNot","in","notIn","exists","notExists"],dys=[...F2,"matches","notMatches"],Bet=["is","isNot","in","notIn"],fys=["is","isNot","gt","gte","lt","lte","exists","notExists"],hys=["gt","gte","lt","lte"],pys=["exists","notExists"],mys=["in","notIn","exists","notExists"],gys={in:"includes",notIn:"notIncludes",exists:"exists",notExists:"notExists"},Vet=["is","in"],vys=["is"],yys={rootEntityType:"Primitive type",entityName:"Primitive name",entityId:"Primitive ID",status:"Status",tags:"Tags",serviceName:"Service Name",environment:"Environment",traceId:"Trace ID",runId:"Run ID",threadId:"Thread ID",sessionId:"Session ID",requestId:"Request ID",resourceId:"Resource ID",userId:"User ID",organizationId:"Organization ID",experimentId:"Experiment ID","spans.name":"Span name","spans.spanType":"Span type","spans.model":"Model","spans.provider":"Provider",durationMs:"Duration (ms)","spans.durationMs":"Span duration (ms)","spans.error":"Span error","scores.scorerId":"Scorer","scores.score":"Score","feedback.feedbackType":"Feedback type","feedback.value":"Feedback value","feedback.comment":"Feedback comment"},xys={timeRange:fC,rootEntityType:Wht,entityName:Px,entityId:hwe,status:QCn,tags:lAn,serviceName:MNn,environment:Pv,traceId:Ept,runId:Fm,threadId:hL,sessionId:nG,requestId:bpt,resourceId:H0,userId:EAn,organizationId:lwe,experimentId:dL,"spans.name":PN,"spans.spanType":FNn,"spans.model":I_,"spans.provider":XU,durationMs:yx,"spans.durationMs":yx,"spans.error":Xd,"scores.scorerId":Sp,"scores.score":XEn,"feedback.feedbackType":yAn,"feedback.value":rx,"feedback.comment":mEn},WNe=e=>xys[e],JJ=e=>"var(--muted-foreground)",WI=e=>({id:e,label:yys[e]??e,icon:WNe(e),color:JJ()}),bys=["entityId","traceId","runId","threadId","sessionId","requestId","resourceId","userId","organizationId","experimentId"],wys=["spans.name","spans.spanType","spans.model","spans.provider","spans.durationMs","spans.error","scores.scorerId","scores.score","feedback.feedbackType","feedback.value","feedback.comment"],fVt=new Set(["spans.error"]),Sys=new Set(["spans.name","feedback.comment"]),kys=new Set(["feedback.comment"]),wI=(e,t)=>e.label.localeCompare(t.label);function Oys(e,t){const n=e.find(i=>i.path==="tags");if(!n)return;const r=mys.filter(i=>n.operators.includes(gys[i]??""));if(r.length===0)return;const s=n.valueSuggestions?t?.("trace","tags"):void 0;return{...WI("tags"),operators:r,...s?{suggestions:s}:{}}}function jys({availableRootEntityNames:e,availableEnvironments:t,hiddenFieldIds:n=[],metadataFields:r=[],canonicalTraceFields:s=[],valueSuggestions:i,withQueryTrace:o=!0,withRootDuration:l=!1}){const c=(k,j,C=F2)=>({...WI(k),operators:C,strict:!0,suggestions:j}),u=k=>({...WI(k),operators:k==="traceId"?Bet:F2}),d=k=>{const[j,C]=k.split("."),T=kys.has(k)?void 0:i?.(j,C);return{...WI(k),operators:Sys.has(k)?dys:F2,...T?{strict:!0,suggestions:T}:{}}},f=k=>({...WI(k),type:"number",operators:fys}),h=k=>({...WI(k),operators:pys}),p=[c("rootEntityType",aVt.map(k=>({value:k.entityType,label:k.label})),Vet),c("entityName",e.map(k=>({value:k})),Bet),c("status",Jvs.filter(k=>k.value!=="running").map(k=>({value:k.value,label:k.label})),Vet),c("environment",t.map(k=>({value:k})))],m=bys.map(u),v=["spans","scores","feedback"].flatMap(k=>wys.filter(j=>j.startsWith(`${k}.`)).map(j=>nVt.has(j)?f(j):fVt.has(j)?h(j):d(j)).sort(wI)),y=r.filter(({path:k})=>lVt(k)).map(({path:k,suggestions:j})=>({id:k,label:k.slice(S3.length),icon:Va,color:JJ(),operators:F2,suggestions:j})),x=Oys(s,i),b=x?[x]:[],S=new Set(n);return o?[...[...p,...b].sort(wI),...[...m,...l?[{...f("durationMs"),operators:hys}]:[]].sort(wI),...v,...y.sort(wI)].filter(k=>!UNe.has(k.id)).map(k=>S.has(k.id)?{...k,hidden:!0}:k):[...p.sort(wI),...m.sort(wI)].map(k=>({...k,operators:vys,...S.has(k.id)?{hidden:!0}:{}}))}function hVt(e){return e.map(t=>({id:t.fieldId,fieldId:t.fieldId,operatorId:qA(t),value:QNe(t.value,qA(t))?"":t.value}))}function pVt(e){return e.map(mVt)}function mVt(e){const t={fieldId:e.fieldId,value:Array.isArray(e.value)?e.value.map(String):String(e.value)};return qNe(e.operatorId)&&e.operatorId!==qA(t)&&(t.operatorId=e.operatorId),t}function Uet(e,t){return{logic:"and",nodes:[...hVt(e),...t.map(gVt)]}}function gVt(e){return{id:e.id,kind:"group",logic:e.logic,nodes:e.nodes.map(t=>Eye(t)?gVt(t):{id:t.id??t.fieldId,fieldId:t.fieldId,operatorId:qA(t),value:QNe(t.value,qA(t))?"":t.value})}}function Cys(e){const t=e.nodes.filter(r=>!qa(r)),n=e.nodes.filter(qa).map(vVt);return{tokens:pVt(t),groups:n}}function vVt(e){const t=e.nodes.map(n=>qa(n)?vVt(n):{id:n.id,...mVt(n)});return{id:e.id,logic:e.logic,nodes:t}}function _ys(e){const t=[],n=new Map([[S$,"rootEntityType"],[k$,"status"]]);for(const s of XJ)n.set(yl[s],s);const r=new Set;for(const[s]of e.entries()){if(uVt(s))continue;const i=YJ(s)?tys(s):n.get(s);if(!i||r.has(i))continue;r.add(i);const o=Nye(e,s),l=e.getAll(s);if(fVt.has(i)&&(o?!dVt(o):l[0]))continue;if(i==="tags"||sys(o)){t.push({fieldId:i,value:l.filter(Boolean),...o?{operatorId:o}:{}});continue}const c=l[0];c!==void 0&&t.push({fieldId:i,value:c,...o?{operatorId:o}:{}})}return t}function Tys(e){const t=new URLSearchParams,n=i=>{const o=Nye(e,i),l=e.getAll(i).filter(c=>c||dVt(o));if(l.length){for(const c of l)t.append(i,c);o&&t.set(oS(i),o)}};n(S$),n(k$);const r=e.get(B1);r&&t.set(B1,r);for(const i of XJ){const o=yl[i];if(i==="tags"){for(const c of e.getAll(o))t.append(o,c);const l=Nye(e,o);l&&e.has(o)&&t.set(oS(o),l);continue}n(o)}const s=new Set;for(const i of e.keys())!YJ(i)||uVt(i)||s.has(i)||(s.add(i),n(i));for(const i of GNe(e))t.append(i_,HNe(i));return t}function qet(e,t,n=[]){for(const r of Object.values(Fet))e.delete(r),e.delete(oS(r));e.delete(i_);for(const r of XJ){const s=yl[r];e.delete(s),e.delete(oS(s))}for(const r of Array.from(e.keys()))YJ(r)&&e.delete(r);for(const r of t){const s=lVt(r.fieldId)?eys(r.fieldId):Fet[r.fieldId]??yl[r.fieldId];if(!s)continue;if(Array.isArray(r.value))if(r.value.length===0)e.append(s,"");else for(const l of r.value)e.append(s,l);else e.set(s,r.value.trim());const i=qA(r),o=r.fieldId==="tags"?"in":"is";i!==o&&e.set(oS(s),i)}for(const r of n)e.append(i_,HNe(r))}const i_="filterGroup",HNe=e=>JSON.stringify(e);function GNe(e){return e.getAll(i_).map(Iys).filter(t=>t!==void 0)}function Iys(e){try{return xVt(JSON.parse(e))}catch{return}}const yVt=e=>typeof e=="object"&&e!==null,Eys=e=>Array.isArray(e)&&e.every(t=>typeof t=="string");function xVt(e){if(!yVt(e)||typeof e.id!="string"||e.logic!=="and"&&e.logic!=="or"||!Array.isArray(e.nodes))return;const t=e.nodes.map(Nys).filter(n=>n!==void 0);return{id:e.id,logic:e.logic,nodes:t}}function Nys(e){if(!yVt(e))return;if("nodes"in e)return xVt(e);if(typeof e.id!="string"||typeof e.fieldId!="string"||typeof e.value!="string"&&!Eys(e.value))return;const t={id:e.id,fieldId:e.fieldId,value:e.value};return typeof e.operatorId=="string"&&qNe(e.operatorId)&&(t.operatorId=e.operatorId),t}function Ays({rootEntityType:e,status:t,dateFrom:n,dateTo:r,tokens:s}){const i={};e&&(i.entityType=e),t&&(i.status=t),n&&(i.startedAt={start:n}),r&&(i.endedAt={end:r});for(const o of s){if(o.fieldId==="tags"){Array.isArray(o.value)&&o.value.length>0?i.tags=o.value:typeof o.value=="string"&&o.value.trim()&&(i.tags=[o.value.trim()]);continue}if(typeof o.value=="string"&&o.value.trim()&&o.value!=="Any")switch(o.fieldId){case"entityId":i.entityId=o.value;break;case"entityName":i.entityName=o.value;break;case"traceId":i.traceId=o.value;break;case"runId":i.runId=o.value;break;case"threadId":i.threadId=o.value;break;case"sessionId":i.sessionId=o.value;break;case"requestId":i.requestId=o.value;break;case"resourceId":i.resourceId=o.value;break;case"userId":i.userId=o.value;break;case"organizationId":i.organizationId=o.value;break;case"serviceName":i.serviceName=o.value;break;case"environment":i.environment=o.value;break;case"experimentId":i.experimentId=o.value;break}}return i}function nue({value:e,icon:t,label:n}){return a.jsxs(si,{value:e,children:[a.jsx(At,{size:"xs",children:t}),a.jsx(Y,{variant:"caption",className:"text-inherit",children:n})]})}function Pys({agentId:e,activeTab:t,threadId:n,showPlayground:r=!1,showObservability:s=!1}){const{navigate:i}=Sn(),o={chat:`/agents/${e}/threads/${n??"new"}`,versions:`/agents/${e}/editor`,traces:n?`/agents/${e}/traces?${new URLSearchParams({[yl.threadId]:n})}`:`/agents/${e}/traces`},l=c=>{c!=="none"&&i(o[c])};return a.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 p-1.5",children:[a.jsx(Hc,{value:t,defaultTab:t,onValueChange:l,className:"min-w-0",children:a.jsxs(Gc,{variant:"pill-ghost",children:[a.jsx(nue,{value:"chat",icon:a.jsx(hL,{}),label:"Chat"}),s&&a.jsx(nue,{value:"traces",icon:a.jsx(Sx,{}),label:"Traces"}),r&&a.jsx(nue,{value:"versions",icon:a.jsx(PN,{}),label:"Editor"})]})}),(!s||!r)&&a.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-0.5",children:[!s&&a.jsx(_Q,{icon:a.jsx(Sx,{}),label:"Traces",tooltipContent:a.jsxs(a.Fragment,{children:["Add ",a.jsx("code",{children:"@mastra/observability"})," to enable Traces."]}),docsHref:"https://mastra.ai/docs/observability/overview"}),!r&&a.jsx(_Q,{icon:a.jsx(PN,{}),label:"Editor",tooltipContent:"Add @mastra/editor to enable the Editor.",docsHref:"https://mastra.ai/docs/editor/overview"})]})]})}const $ys=({agentId:e})=>{const t=Ke(),{data:n=[]}=n6(),r=n.filter(l=>l.isConfigured),s=Rm({queries:r.map(l=>({queryKey:["channels","installations",l.id,e],queryFn:()=>t.channels.listInstallations(l.id,e),staleTime:10*1e3,retry:!1}))}),i=r.flatMap((l,c)=>{const u=s[c]?.data;return!u||u.some(d=>d.status==="active")?[]:[{platform:l,isPending:u.some(d=>d.status==="pending")}]});if(i.length===0)return null;const o=s.some(l=>l.data?.length);return a.jsx(hl,{elevation:"flat","data-testid":"agent-channels-card",children:a.jsxs(qm,{className:"flex flex-col gap-1",children:[a.jsx(sw,{children:o?"Finish connecting your channels":"Connect your channels"}),a.jsx("ul",{className:"divide-y divide-border",children:i.map(({platform:l,isPending:c})=>a.jsx(Rys,{platform:l,agentId:e,isPending:c},l.id))})]})})};function Rys({platform:e,agentId:t,isPending:n}){const{connect:r,isConnecting:s}=jX(e.id);return J_e({platform:e.id,agentId:t,hasPendingInstall:n}),a.jsxs("li",{className:"flex items-center gap-3 py-2.5",children:[a.jsx(OX,{platform:e.id,className:"h-5 w-5 shrink-0"}),a.jsx(Y,{as:"span",variant:"body",tone:"ink",className:"min-w-0 flex-1 truncate",children:e.name}),n?a.jsx($t,{variant:"warning",size:"sm",indicator:"dot",children:"Pending"}):null,a.jsx(ce,{icon:a.jsx(iG,{}),size:"sm",variant:"default",onClick:()=>r(t),disabled:s,children:s?"Connecting...":"Connect"})]})}function Aye(){return a.jsxs("div",{className:"min-h-0 space-y-4 overflow-hidden pt-4",children:[a.jsx("div",{className:"flex justify-start",children:a.jsx(bt,{className:"h-10 w-2/3 rounded-2xl"})}),a.jsx("div",{className:"flex justify-end",children:a.jsx(bt,{className:"h-12 w-3/5 rounded-2xl"})}),a.jsx("div",{className:"flex justify-start",children:a.jsxs("div",{className:"w-4/5 space-y-2",children:[a.jsx(bt,{className:"h-4 w-full rounded-full"}),a.jsx(bt,{className:"h-4 w-5/6 rounded-full"}),a.jsx(bt,{className:"h-4 w-2/3 rounded-full"})]})})]})}function bVt(){return a.jsx("div",{className:"grid h-full min-h-0 w-full overflow-hidden px-4 py-4 md:px-10",children:a.jsxs("div",{className:"mx-auto grid h-full min-h-0 w-full max-w-[80ch] grid-rows-[1fr_auto]",children:[a.jsx(Aye,{}),a.jsx(wVt,{})]})})}function wVt(){return a.jsxs("div",{className:"rounded-3xl border border-border bg-background px-3 py-2.5",children:[a.jsx(bt,{className:"h-5 w-1/2 rounded-full"}),a.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[a.jsx(bt,{className:"h-control-md w-24 rounded-full"}),a.jsx(bt,{className:"h-control-md w-control-md rounded-full"})]})]})}function Mys(){return a.jsx("div",{className:"flex h-full min-h-0 w-full flex-col items-center justify-center px-4 py-4 md:px-10","data-testid":"agent-landing-skeleton","aria-busy":"true",children:a.jsxs("div",{className:"flex w-full max-w-[80ch] flex-col gap-6",children:[a.jsxs("div",{className:"flex flex-col items-center gap-4",children:[a.jsx(bt,{className:"h-avatar-lg w-avatar-lg rounded-full"}),a.jsx(bt,{className:"h-7 w-2/3 rounded-full"})]}),a.jsx(wVt,{}),a.jsxs("div",{className:"flex flex-col gap-1 px-3",children:[a.jsx(bt,{className:"h-control-md w-2/3 rounded-full"}),a.jsx(bt,{className:"h-control-md w-1/2 rounded-full"}),a.jsx(bt,{className:"h-control-md w-3/5 rounded-full"})]})]})})}const z7=({label:e,children:t})=>a.jsxs("div",{className:"space-y-2",children:[a.jsx(Y,{as:"p",variant:"body",tone:"muted",children:e}),t]});function Dys(e,t){if(!e||JDt(e).toLowerCase()!=="anthropic")return!1;if(!t)return!0;const r=t.toLowerCase();return/[^0-9]4[.-]5/.test(r)||/[^0-9][5-9][.-]\d/.test(r)}function Lys({provider:e,modelId:t,settings:n,setSettings:r}){const s=Dys(e,t),i=g.useEffectEvent(()=>{r({...n,modelSettings:{...n?.modelSettings,topP:void 0}})}),o=e&&t?`${e}-${t}`:void 0,l=n?.modelSettings?.topP,c=n?.modelSettings?.temperature;return g.useEffect(()=>{s&&o&&(l===void 0||c===void 0||i())},[s,o,l,c]),{hasSamplingRestriction:s}}const zys=({canEdit:e=!0})=>{const{settings:t,setSettings:n}=uTe(),[r,s]=g.useState(""),[i,o]=g.useState(!1),[l,c]=g.useState(null),{handleCopy:u}=Vm({text:r}),d=JSON.stringify(t?.modelSettings?.providerOptions??{});g.useEffect(()=>{(async()=>{if(!CQ(d)){c("Invalid JSON");return}const v=await T5(d);s(v)})()},[d]);const f=async()=>{if(c(null),!CQ(r)){c("Invalid JSON");return}const m=await T5(r);s(m)},h=async()=>{try{c(null);const m=JSON.parse(r);n({...t,modelSettings:{...t?.modelSettings,providerOptions:m}}),o(!0),setTimeout(()=>{o(!1)},1e3)}catch(m){console.error("error",m),c("Invalid JSON")}},p=Z(Zn,In);return a.jsx(Wc,{children:a.jsxs("div",{className:"@container/advanced",children:[a.jsxs("div",{className:"grid grid-cols-1 gap-2 pb-2 @xs/advanced:grid-cols-2",children:[a.jsxs(pt,{children:[a.jsx(dt,{children:"Frequency Penalty"}),a.jsx(bn,{type:"number",step:"0.1",min:"-1",max:"1",readOnly:!e,value:t?.modelSettings?.frequencyPenalty??"",onChange:m=>n({...t,modelSettings:{...t?.modelSettings,frequencyPenalty:m.target.value?Number(m.target.value):void 0}})})]}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Presence Penalty"}),a.jsx(bn,{type:"number",step:"0.1",min:"-1",max:"1",readOnly:!e,value:t?.modelSettings?.presencePenalty??"",onChange:m=>n({...t,modelSettings:{...t?.modelSettings,presencePenalty:m.target.value?Number(m.target.value):void 0}})})]}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Top K"}),a.jsx(bn,{type:"number",readOnly:!e,value:t?.modelSettings?.topK||"",onChange:m=>n({...t,modelSettings:{...t?.modelSettings,topK:m.target.value?Number(m.target.value):void 0}})})]}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Max Tokens"}),a.jsx(bn,{type:"number",readOnly:!e,value:t?.modelSettings?.maxTokens||"",onChange:m=>n({...t,modelSettings:{...t?.modelSettings,maxTokens:m.target.value?Number(m.target.value):void 0}})})]}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Max Steps"}),a.jsx(bn,{type:"number",readOnly:!e,value:t?.modelSettings?.maxSteps||"",onChange:m=>n({...t,modelSettings:{...t?.modelSettings,maxSteps:m.target.value?Number(m.target.value):void 0}})})]}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Max Retries"}),a.jsx(bn,{type:"number",readOnly:!e,value:t?.modelSettings?.maxRetries||"",onChange:m=>n({...t,modelSettings:{...t?.modelSettings,maxRetries:m.target.value?Number(m.target.value):void 0}})})]}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Seed"}),a.jsx(bn,{type:"number",readOnly:!e,value:t?.modelSettings?.seed||"",onChange:m=>n({...t,modelSettings:{...t?.modelSettings,seed:m.target.value?Number(m.target.value):void 0}})})]})]}),a.jsxs(pt,{invalid:!!l,className:"gap-1",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx(dt,{children:"Provider Options"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:f,className:p,"aria-label":"Format Provider Options",children:a.jsx(At,{children:a.jsx(Va,{})})})}),a.jsx(Bn,{children:"Format the Provider Options JSON"})]}),a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:u,className:p,"aria-label":"Copy Provider Options",children:a.jsx(At,{children:a.jsx(Lm,{})})})}),a.jsx(Bn,{children:"Copy Provider Options"})]}),e&&a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:h,className:p,"aria-label":"Save Provider Options",children:a.jsx(At,{children:i?a.jsx(ur,{}):a.jsx(Bm,{})})})}),a.jsx(Bn,{children:i?"Saved":"Save Provider Options"})]})]})]}),a.jsx(Or,{value:r,onChange:s,language:"json",editable:e,showCopyButton:!1,className:"h-75"}),a.jsx(ns,{children:l})]})]})})},Fys=({hasMemory:e,hasSubAgents:t,disabled:n})=>{const r=e&&t,s=n||!r,i=a.jsxs(lm,{disabled:s,children:[a.jsx(Yh,{value:"network",className:"text-foreground"}),a.jsx(dt,{children:"Network"})]});if(r)return i;const o=[];return e||o.push("memory enabled"),t||o.push("at least one sub-agent"),a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:i}),a.jsx(Bn,{children:a.jsxs("p",{children:["Network is not available. Please make sure you have ",o.join(" and "),"."]})})]})},Bys=({supported:e,disabled:t})=>{const n=t||!e,r=a.jsxs(lm,{disabled:n,children:[a.jsx(Yh,{value:"streamSubscription",className:"text-foreground"}),a.jsx(dt,{children:"Stream subscription (default)"})]});return e?r:a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:r}),a.jsx(Bn,{children:a.jsx("p",{children:"Stream subscription is not supported for this agent."})})]})},Vys=({agentId:e})=>{const{data:t,isLoading:n}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:r,isLoading:s}=Qk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{settings:i,setSettings:o,resetAll:l}=uTe(),{canEdit:c}=Za(),[u,d]=g.useState(!1),[f,h]=g.useState(!1),p=c("agents"),{hasSamplingRestriction:m}=Lys({provider:t?.provider,modelId:t?.modelId,settings:i,setSettings:o});if(!n&&!t)return null;const v=!!r?.result,y=!!(t&&Object.keys(t.agents||{}).length>0),x=t?.modelVersion,b=x==="v2"||x==="v3",S=t?.supportsMemory!==!1;let k;t&&(b?i?.modelSettings?.chatWithNetwork?k="network":i?.modelSettings?.chatWithGenerate?k="generate":i?.modelSettings?.chatWithLegacyStream||!S?k="stream":k="streamSubscription":k=i?.modelSettings?.chatWithGenerateLegacy?"generateLegacy":"streamLegacy");const j=m&&(i?.modelSettings?.temperature!==void 0||i?.modelSettings?.topP!==void 0);return a.jsxs(a.Fragment,{children:[a.jsxs(jp,{open:f,onOpenChange:(C,T)=>{if(!C&&u){T?.cancel?.();return}h(C)},children:[a.jsx(of,{asChild:!0,children:a.jsx(ce,{variant:"ghost",size:"icon-md",type:"button",tooltip:"Model settings","data-testid":"composer-model-settings-trigger",children:a.jsx(GNn,{})})}),a.jsx(ah,{align:"start",className:"w-80 p-4",children:n||s?a.jsx(bt,{className:"h-40 w-full","data-testid":"composer-model-settings-skeleton"}):a.jsxs("section",{className:"@container space-y-5",children:[a.jsx(z7,{label:"Chat Method",children:a.jsxs(H6,{value:k,disabled:!p,onValueChange:C=>p&&o({...i,modelSettings:{...i?.modelSettings,chatWithGenerateLegacy:C==="generateLegacy",chatWithGenerate:C==="generate",chatWithLegacyStream:C==="stream",chatWithNetwork:C==="network"}}),className:"flex flex-col gap-3",children:[!b&&a.jsxs(lm,{disabled:!p,children:[a.jsx(Yh,{value:"generateLegacy",className:"text-foreground"}),a.jsx(dt,{children:"Generate (Legacy)"})]}),b&&a.jsxs(lm,{disabled:!p,children:[a.jsx(Yh,{value:"generate",className:"text-foreground"}),a.jsx(dt,{children:"Generate"})]}),!b&&a.jsxs(lm,{disabled:!p,children:[a.jsx(Yh,{value:"streamLegacy",className:"text-foreground"}),a.jsx(dt,{children:"Stream (Legacy)"})]}),b&&a.jsx(Bys,{supported:S,disabled:!p}),b&&a.jsxs(lm,{disabled:!p,children:[a.jsx(Yh,{value:"stream",className:"text-foreground"}),a.jsx(dt,{children:"Stream"})]}),b&&a.jsx(Fys,{hasMemory:v,hasSubAgents:y,disabled:!p})]})}),a.jsx(z7,{label:"Require Tool Approval",children:a.jsx(Kc,{checked:i?.modelSettings?.requireToolApproval,disabled:!p,onCheckedChange:C=>p&&o({...i,modelSettings:{...i?.modelSettings,requireToolApproval:C}})})}),j&&a.jsxs("div",{"data-testid":"sampling-restriction-banner",className:"flex items-center gap-2 rounded bg-card px-3 py-2 text-muted-foreground",children:[a.jsx(yv,{className:"h-3.5 w-3.5 shrink-0"}),a.jsx(Y,{as:"span",variant:"caption",children:i?.modelSettings?.temperature!==void 0?"Claude 4.5+ models only accept Temperature OR Top P. Clear Temperature to use Top P.":"Claude 4.5+ models only accept Temperature OR Top P. Setting Temperature will clear Top P."})]}),a.jsx(z7,{label:"Temperature",children:a.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[a.jsx(Uve,{value:[i?.modelSettings?.temperature??-.1],max:1,min:-.1,step:.1,disabled:!p,onValueChange:C=>p&&o({...i,modelSettings:{...i?.modelSettings,temperature:C[0]<0?void 0:C[0]}})}),a.jsx(Y,{as:"p",variant:"caption",tone:"muted",children:i?.modelSettings?.temperature??"n/a"})]})}),a.jsx(z7,{label:"Top P",children:a.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[a.jsx(Uve,{disabled:!p,onValueChange:C=>p&&o({...i,modelSettings:{...i?.modelSettings,topP:C[0]<0?void 0:C[0]}}),value:[i?.modelSettings?.topP??-.1],max:1,min:-.1,step:.1}),a.jsx(Y,{as:"p",variant:"caption",tone:"muted",children:i?.modelSettings?.topP??"n/a"})]})}),a.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[a.jsx(ce,{icon:a.jsx(E_,{}),variant:"ghost",size:"sm",type:"button",disabled:!p,onClick:()=>p&&l(),children:"Reset"}),a.jsx(ce,{icon:a.jsx(mL,{}),variant:"default",size:"sm",type:"button",disabled:!p,onClick:()=>d(!0),children:"Advanced Settings"})]})]})})]}),a.jsx(Yr,{open:u,onOpenChange:d,children:a.jsxs(Xr,{size:"lg",children:[a.jsx(Jr,{children:a.jsx(Zr,{children:"Advanced model settings"})}),a.jsx(Qr,{children:a.jsx(zys,{canEdit:p})})]})})]})},Uys=()=>{const{data:e}=DP();return{isLiveKitAvailable:e?.liveKitConnectionRouteEnabled!==!1}},qys="/voice/livekit/connection-details",Qet="lk.agent.state",Qys="lk.transcription",Zys="lk.transcription_final";function Wys(e,t,n,r,s){return(e.find(l=>l.id===t)?e.map(l=>l.id===t?{...l,text:l.text+r,final:l.final||s}:l):[...e,{id:t,role:n,text:r,final:s}]).slice(-20)}const Hys=({agentId:e,threadId:t,onCallStarted:n})=>{const{baseUrl:r,headers:s}=gL(),{isLiveKitAvailable:i}=Uys(),o=mr(),l=g.useRef(n);g.useEffect(()=>{l.current=n},[n]);const[c,u]=g.useState("idle"),[d,f]=g.useState("initializing"),[h,p]=g.useState([]),m=g.useRef(null),v=g.useRef(null),y=g.useRef(null),x=g.useRef(0),b=g.useRef(null),S=g.useCallback(()=>{t&&o.invalidateQueries({queryKey:["memory","messages",t]}),e&&o.invalidateQueries({queryKey:["memory","threads",e,e]})},[e,o,t]),k=g.useCallback(()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{y.current=null,S()},600)},[S]),j=g.useCallback(()=>{x.current+=1,b.current?.abort(),b.current=null;const _=m.current;m.current=null,_&&_.disconnect(),y.current&&(clearTimeout(y.current),y.current=null),v.current=null,u("idle"),f("initializing")},[]);g.useEffect(()=>j,[j]);const C=g.useCallback(()=>{j(),p([]),S()},[j,S]),T=g.useCallback(async()=>{if(c!=="idle"||!i)return;const _=x.current+=1,N=new AbortController;b.current=N;const E=()=>x.current!==_;u("connecting"),p([]);try{const A=await fetch(`${r}${qys}`,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify({agentId:e,threadId:t,resourceId:e}),signal:N.signal});if(E())return;if(!A.ok){const V=await A.json().catch(()=>({}));throw new Error(V.error??"LiveKit voice is not configured for this server. Add liveKitConnectionRoute() to server.apiRoutes and run a voice worker.")}const P=await A.json();if(E())return;const{Room:L,RoomEvent:F,Track:Q}=await Ai(async()=>{const{Room:V,RoomEvent:W,Track:M}=await import("./livekit-client.esm-CKIgC2IJ.js");return{Room:V,RoomEvent:W,Track:M}},[],import.meta.url);if(E())return;const q=new L;m.current=q;const B=new Audio;if(B.autoplay=!0,v.current=B,q.on(F.TrackSubscribed,V=>{V.kind===Q.Kind.Audio&&v.current&&V.attach(v.current)}),q.on(F.ParticipantAttributesChanged,(V,W)=>{const M=V[Qet]??W.attributes[Qet];M&&W.identity!==P.participantName&&f(M)}),q.on(F.Disconnected,()=>{m.current===q&&j()}),q.registerTextStreamHandler(Qys,async(V,W)=>{const M=W.identity===P.participantName?"user":"agent",K=V.info.attributes?.[Zys]==="true";for await(const D of V)p($=>Wys($,V.info.id,M,D,K));M==="agent"&&k()}),await q.connect(P.serverUrl,P.participantToken),E()){q.disconnect(),m.current===q&&(m.current=null);return}if(await q.localParticipant.setMicrophoneEnabled(!0),E()){q.disconnect(),m.current===q&&(m.current=null);return}u("active"),S(),await Promise.resolve(l.current?.()).catch(()=>{})}catch(A){if(N.signal.aborted||E())return;j(),Su.error(A instanceof Error?A.message:"Failed to start the voice call.")}},[e,r,j,s,i,S,k,c,t]);return{status:c,agentState:d,captions:h,isLiveKitAvailable:i,start:()=>{T()},stop:C}},Gys=({voiceCall:e})=>{const{isLiveKitAvailable:t}=e;return e.status==="idle"?a.jsx(ce,{variant:"ghost",size:"icon-md",type:"button","aria-label":"Start voice call","aria-disabled":!t||void 0,tooltip:t?"Start voice call":"Configure @mastra/livekit to start voice calls.","data-testid":"voice-call-button",onClick:()=>e.start(),children:a.jsx(nNn,{})}):e.status==="connecting"?a.jsx(ce,{variant:"ghost",size:"icon-md",type:"button",tooltip:"Connecting…","data-testid":"voice-call-button",children:a.jsx(hc,{className:"animate-spin"})}):a.jsx(ce,{variant:"destructive-ghost",size:"icon-md",type:"button",tooltip:"End voice call","data-testid":"voice-call-button",onClick:()=>e.stop(),children:a.jsx(eNn,{})})},Kys={initializing:"Connecting…",listening:"Listening…",thinking:"Thinking…",speaking:"Speaking…"},Zet=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(e[n]?.role===t)return e[n]},Yys=({voiceCall:e})=>{if(e.status==="idle")return null;const t=Zet(e.captions,"user"),n=Zet(e.captions,"agent"),r=e.status==="connecting"?"Connecting…":Kys[e.agentState];return a.jsxs("div",{"data-testid":"voice-call-panel",className:Z(pr,"mx-auto mb-2 w-full max-w-3xl rounded-[16px] px-4 py-3"),children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:Z("h-2 w-2 rounded-full",e.status==="connecting"&&"bg-muted-foreground",e.status==="active"&&e.agentState==="speaking"&&"animate-pulse bg-success-indicator",e.status==="active"&&e.agentState!=="speaking"&&"bg-success-indicator")}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:r})]}),t&&a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-2 truncate","data-testid":"voice-caption-user",children:t.text}),n&&a.jsx(Y,{variant:"caption",tone:"ink",className:"mt-1","data-testid":"voice-caption-agent",children:n.text})]})},Xys=300,Jys=[],exs=(e,t)=>{const[n,r]=g.useState(!1);return g.useEffect(()=>{if(!e){r(!1);return}const s=setTimeout(()=>r(!0),t);return()=>clearTimeout(s)},[e,t]),n},txs=e=>e?e.content.parts.some(n=>{if(n.type==="reasoning"||n.type==="text")return"state"in n&&n.state==="streaming";if(n.type==="tool-invocation")return"toolInvocation"in n&&n.toolInvocation.state!=="result";if(n.type==="dynamic-tool"||n.type.startsWith("tool-")){const r="state"in n?n.state:void 0;return r!=="output-available"&&r!=="output-error"}return!1}):!1,nxs=({turns:e})=>e.length===0?null:a.jsx("div",{"data-testid":"thread-rail-layer",className:"pointer-events-none absolute inset-y-0 left-4 z-20 hidden @min-[58rem]:block",children:a.jsx(EJr,{turns:e,className:"pointer-events-auto sticky top-1/2 -translate-y-1/2"})}),rxs=({agentName:e,agentId:t,threadId:n,suggestedPrompts:r,hasModelList:s,hideModelSwitcher:i,runOptionsSlot:o,refreshThreadList:l,isHistoryLoading:c,onLoadPrevious:u,isLoadingPrevious:d})=>{const f=g.useRef(null),{draft:h,updateDraft:p}=vNe(n),m=OXr(),{isRunning:v}=f$(),[y]=xr("agent",t??""),{isSpeaking:x,readAloud:b,stop:S}=gcs(t,y,{onError:B=>Su.error(B instanceof Error?B.message:"Voice generation failed.")}),{hasSession:k,viewMode:j}=U6(),C=k&&(j==="collapsed"||j==="expanded"),T=m.length===0,_=m[m.length-1],N=v&&(_?.role!=="assistant"||!txs(_)),E=exs(N,Xys),A=g.useMemo(()=>UJr(m),[m]),P=g.useMemo(()=>new Set(A.map(B=>B.messageId)),[A]),L=QJr(m,{key:Dve,opensTurn:B=>P.has(B.id)}),F=T&&!c,[Q,q]=g.useState(F);return g.useEffect(()=>{if(Q!==F){if(F||!v){q(F);return}yp(()=>q(!1))}},[F,Q,v]),a.jsx(kcs,{controlled:h&&p?{value:h.attachments,onChange:B=>p(V=>({...V,attachments:typeof B=="function"?B(V.attachments):B}))}:void 0,children:a.jsx(Ag,{className:"h-full",scroller:{autoScroll:!0,defaultScrollPosition:"last-anchor",onReachStart:u,preserveScrollOnPrepend:!!u},"data-testid":"thread-wrapper",children:a.jsx(Ag.Stage,{children:a.jsxs(Ag.Viewport,{style:{overflowAnchor:"none"},children:[a.jsx(nxs,{turns:A}),a.jsxs(Ag.Content,{className:Q?"flex-none":void 0,children:[d&&a.jsx(Ag.Column,{"data-testid":"thread-history-older-skeleton","aria-busy":"true","aria-label":"Loading older messages",className:"py-3",children:a.jsx(Aye,{})}),T&&c?a.jsx(Ag.Column,{"data-testid":"thread-history-skeleton","aria-busy":"true",className:"flex-1 py-4",children:a.jsx(Aye,{})}):Q?null:a.jsxs(Ag.Column,{ref:f,"data-testid":"thread-message-column",className:"relative flex-1 gap-4 py-4",children:[a.jsx(Zcs,{containerRef:f}),a.jsx(N4t,{children:L.map((B,V)=>{const W=V===L.length-1,M=W&&v&&B.opensTurn&&V>0;return a.jsxs(Ag.Turn,{opensTurn:B.opensTurn,holdsRoom:M,className:"gap-4",children:[B.entries.map(K=>a.jsx(kTe,{messageId:K.id,scrollAnchor:P.has(K.id),children:a.jsx(iye,{message:K,hasModelList:s,isSpeaking:x,onReadAloud:b,onStopSpeaking:S})},Dve(K))),W&&E&&a.jsx(fve,{})]},B.key)})}),!v&&a.jsx(YJr,{})]})]}),a.jsxs(Ag.Dock,{"data-testid":Q?"thread-landing":void 0,className:Q?"static flex flex-1 flex-col justify-center py-12 before:hidden":void 0,children:[Q?null:a.jsx(Ag.ScrollButton,{}),a.jsxs(Ag.Column,{className:Q?"gap-6 px-1 md:px-1":"gap-2 px-1 md:px-1",children:[Q?a.jsxs(a.Fragment,{children:[a.jsx(sxs,{agentName:e}),t?a.jsx($ys,{agentId:t}):null]}):a.jsxs(a.Fragment,{children:[C&&t&&n&&a.jsx(RDt,{agentName:e}),a.jsx(_us,{})]}),a.jsx("div",{className:Q?"starter-prompt":void 0,children:a.jsx(ixs,{agentId:t,threadId:n,hasModelList:s,hideModelSwitcher:i,runOptionsSlot:o,refreshThreadList:l})}),Q?a.jsx(Jcs,{prompts:r??Jys}):null]})]})]})})})})},sxs=({agentName:e})=>a.jsxs("div",{"data-testid":"thread-welcome",className:"flex w-full flex-col items-center gap-4",children:[a.jsx("div",{className:"starter-heading",children:a.jsx(JS,{name:e||"Agent",size:"lg"})}),a.jsxs(Y,{as:"h1",variant:"display",tone:"muted",className:"starter-heading mx-auto max-w-2xl text-center font-normal text-balance",children:["What can ",a.jsx("span",{className:"font-medium text-foreground",children:e||"this agent"})," do for you today?"]})]}),ixs=({agentId:e,threadId:t,hasModelList:n,hideModelSwitcher:r,runOptionsSlot:s,refreshThreadList:i})=>{const{threadInput:o,setThreadInput:l,updateDraft:c,draftStatus:u}=vNe(t),d=g.useRef(null),f=g.useRef(!1),h=g.useRef(0);g.useEffect(()=>()=>{h.current++},[]);const[p,m]=g.useState(),v=fTe(),{attachments:y,toCoreUserMessages:x,clear:b,restore:S,isAddingAttachments:k}=_z(),{isRunning:j,canSendWhileStreaming:C,cancelRun:T}=f$(),[_,N]=g.useState(0),{canExecute:E}=Za(),A=E("agents"),P=!A||!!u?.restoring;Kcs(d,{threadId:t,disabled:P});const L=Hys({agentId:e,threadId:t,onCallStarted:i}),F=o.trim().length===0&&y.length===0,Q=j&&!C,q=async()=>{if(F||Q||!A||u?.restoring||k||f.current)return;f.current=!0;const B=h.current,V=y,W=new Set(V.map(D=>D.id)),M=D=>D?`${o}
674
674
 
675
- ${D}`:o,K=()=>{h.current===B&&(c?c(D=>({text:M(D.text),attachments:[...V,...D.attachments]})):(l(M),S(V)),m("Your message could not be sent. Your draft has been restored."))};m(void 0);try{const D=y.length>0?await x():void 0;if(h.current!==B)return;c?c($=>({text:$.text===o?"":$.text,attachments:$.attachments.filter(z=>!W.has(z.id))})):(l(""),b()),N($=>$+1),Promise.resolve(v({message:o,attachments:D})).then($=>{$===!1&&K()})}catch{h.current===B&&m("Attachments could not be prepared. Your draft has been kept.")}finally{f.current=!1}};return a.jsxs("div",{className:"relative",style:{viewTransitionName:"agent-chat-composer"},children:[a.jsx(Yys,{voiceCall:L}),(p||u?.error)&&a.jsx(Y,{variant:"caption",role:"alert",children:p||u?.error}),u?.restoring&&a.jsx(Y,{variant:"caption",role:"status",className:"sr-only",children:"Restoring draft…"}),a.jsx(Qcs,{disabled:!A||u?.restoring,children:a.jsx(L4t,{className:"relative",onSubmit:B=>{B.preventDefault(),q()},children:a.jsx(F4t,{busy:j,children:a.jsxs(z4t,{sendingPulseKey:_,children:[a.jsx(Bcs,{}),a.jsx(V4t,{ref:d,value:o,placeholder:A?"Enter your message...":"You don't have permission to execute agents",onChange:B=>{l(B.target.value)},onKeyDown:B=>{if(!(B.nativeEvent.isComposing||B.keyCode===229)&&B.key==="Enter"&&!B.shiftKey){if(Q)return;B.preventDefault(),B.stopPropagation(),q()}},disabled:P}),e&&!n&&!r&&a.jsx(Xhs,{}),a.jsx(U4t,{children:a.jsx(axs,{canExecute:A,agentId:e,runOptionsSlot:s,showModelSwitcher:!!(e&&!n&&!r),isEmpty:F,isRunning:j,canSendWhileStreaming:C,onCancel:()=>{T()},onSetText:B=>{l(B)},voiceCall:L})})]})})})})]})},oxs=({agentId:e,onTranscript:t})=>{const[n]=xr("agent",e??""),{start:r,stop:s,isListening:i,transcript:o}=B0n({agentId:e,requestContext:n});return g.useEffect(()=>{o&&g.startTransition(()=>t(o))},[t,o]),a.jsx(ce,{variant:"ghost",size:"icon-md",type:"button",tooltip:i?"Stop dictation":"Start dictation",onClick:()=>i?s():r(),children:i?a.jsx(Pye,{}):a.jsx(wEn,{})})},axs=({canExecute:e=!0,agentId:t,showModelSwitcher:n,runOptionsSlot:r,isEmpty:s,isRunning:i,canSendWhileStreaming:o,onCancel:l,onSetText:c,voiceCall:u})=>a.jsxs(a.Fragment,{children:[(n&&t||r)&&a.jsxs("div",{className:"flex max-w-full shrink-0 items-center gap-1.5",children:[n&&t&&a.jsxs(a.Fragment,{children:[a.jsx(Yhs,{}),a.jsx(Vys,{agentId:t})]}),r]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[e&&a.jsx(Ocs,{}),e&&a.jsx(oxs,{agentId:t,onTranscript:c}),e&&t&&u&&a.jsx(Gys,{voiceCall:u})]}),a.jsx(lxs,{canExecute:e,isEmpty:s,isRunning:i,canSendWhileStreaming:o,onCancel:l})]})]}),lxs=({canExecute:e=!0,isEmpty:t,isRunning:n,canSendWhileStreaming:r,onCancel:s})=>{const{isAddingAttachments:i}=_z();return n&&!r?a.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:a.jsx(Pye,{})}):a.jsxs(a.Fragment,{children:[a.jsx(ce,{type:"submit",variant:"default",size:"icon-md",tooltip:e?"Send":"No permission to execute",disabled:!e||t||i,children:a.jsx(bk,{})}),n&&a.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:a.jsx(Pye,{})})]})},Pye=()=>a.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:Zn,children:[a.jsx("circle",{cx:"12",cy:"12",r:"10"}),a.jsx("rect",{width:"6",height:"6",x:"9",y:"9",rx:"1"})]}),KNe=({agentId:e,agentName:t,threadId:n,memory:r,refreshThreadList:s,modelVersion:i,agentVersionId:o,supportsMemory:l,modelList:c,messageId:u,suggestedPrompts:d,isNewThread:f,hideModelSwitcher:h,runOptionsSlot:p})=>{const{settings:m}=uTe(),v=xr("agent",e)[0],{data:y,isLoading:x,fetchNextPage:b,hasNextPage:S,isFetchingNextPage:k}=NK({agentId:e,threadId:f?void 0:n,memory:r??!1,requestContext:v});g.useEffect(()=>{u&&y&&!x&&setTimeout(()=>{const _=document.querySelector(`[data-message-id="${u}"]`);_&&(_.scrollIntoView({behavior:"smooth",block:"center"}),_.classList.add("bg-muted"),setTimeout(()=>{_.classList.remove("bg-muted")},2e3))},100)},[u,y,x]);const j=g.useRef({threadId:n,messages:[]});j.current.threadId!==n&&(j.current={threadId:n,messages:[]});const C=y?.messages??j.current.messages,T=()=>{k||b()};return a.jsx(HXr,{agentId:e,agentName:t,modelVersion:i,agentVersionId:o,supportsMemory:l,threadId:n,initialMessages:C,refreshThreadList:s,settings:m,requestContext:v,children:a.jsx(rxs,{agentName:t??"",agentId:e,threadId:n,suggestedPrompts:d,hasModelList:!!c,hideModelSwitcher:h,refreshThreadList:s,runOptionsSlot:p,isHistoryLoading:x,onLoadPrevious:S?T:void 0,isLoadingPrevious:k})})};function _W(){return a.jsx(Yt,{tone:"error",titleSlot:"Agent not found",descriptionSlot:"This agent may have been renamed or removed. Reload to check again, or choose another agent.",actionSlot:a.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[a.jsx(ce,{onClick:()=>window.location.reload(),children:"Reload"}),a.jsx(ce,{render:a.jsx(lc,{to:"/agents"}),children:"Choose agent"})]})})}function Wet(){const{agentId:e,threadId:t}=Cr(),[n]=wi(),{data:r,isLoading:s,error:i}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:o}=Qk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),l=Lr(),c=t==="new",u=g.useMemo(()=>ka(),[t]),d=!!o?.result,{refetch:f}=aTe({resourceId:e,agentId:e,isMemoryEnabled:d,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!d}});g.useEffect(()=>{d&&(t||l(`/agents/${e}/session/new`))},[d,t,e,l]);const h=n.get("messageId")??void 0,p=g.useMemo(()=>RNe(r),[r]);if(i&&Cs(i))return a.jsx(ci,{variant:"fill"});if(i&&_s(i))return a.jsx(Gs,{variant:"fill",resource:"agents"});if(s)return a.jsx(cxs,{});if(i&&Pk(i))return a.jsx(_W,{});if(i)return a.jsx(Yt,{tone:"error",titleSlot:"Failed to load agent",descriptionSlot:i.message});if(!r)return a.jsx(_W,{});const m=c?u:t??u,v=async()=>{await f(),c&&l(`/agents/${e}/session/${u}`)};return a.jsx(f4t,{agentId:e,defaultSettings:p,children:a.jsx(O4t,{agentId:e,threadId:m,resourceId:e,children:a.jsx(CX,{children:a.jsx(_X,{agentId:e,threadId:m,enabled:!!(r?.hasBrowser??r?.browserTools?.length),children:a.jsx(gNe,{children:a.jsx(_4t,{children:a.jsx(EX,{children:a.jsxs(It,{variant:"fit",children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(d4t,{}),a.jsx("div",{className:"relative grid h-full min-h-0",children:a.jsx(KNe,{agentId:e,agentName:r?.name,modelVersion:r?.modelVersion,supportsMemory:r?.supportsMemory,threadId:m,memory:d,refreshThreadList:v,modelList:r?.modelList,messageId:h,isNewThread:c,hideModelSwitcher:!0,runOptionsSlot:a.jsx(MNe,{agentId:e})},m)})]})})})})},`session-${e}-${m}`)},`browser-${e}-${m}`)})})}const cxs=()=>a.jsxs(It,{variant:"fit",children:[a.jsx("h1",{className:"sr-only",children:"Agent session"}),a.jsx(d4t,{}),a.jsx("div",{className:"relative grid h-full overflow-y-auto pt-4","data-testid":"agent-session-skeleton","aria-busy":"true",children:a.jsx(bVt,{})})]}),uxs={purple:{icon:"text-badge-purple-indicator"},amber:{icon:"text-badge-amber-indicator"},emerald:{icon:"text-badge-green-indicator"},sky:{icon:"text-badge-blue-indicator"},cyan:{icon:"text-badge-cyan-indicator"},orange:{icon:"text-badge-orange-indicator"}},nN=e=>e?Object.keys(e).length:0,eee=e=>e>0?String(e):"Off",SVt=e=>(e?.inputProcessors?.length??0)+(e?.outputProcessors?.length??0),kVt=e=>!!e?.result,OVt=(e,t)=>!!(t&&e&&e.editor!==!1);function O$({view:e,label:t,status:n,description:r,docsHref:s,enabled:i,tone:o,icon:l}){const c=uxs[o].icon;return e==="chip"?a.jsx("span",{"aria-label":`${t}: ${n}`,className:Z("pointer-events-none inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1 text-muted-foreground",i?c:void 0),children:a.jsx("span",{className:"size-3 shrink-0 [&>svg]:size-3",children:l})}):a.jsxs("a",{"aria-label":`${t}: ${n}`,href:s,target:"_blank",rel:"noopener noreferrer",className:Z("group/capability-row flex min-w-0 items-start gap-2 rounded-md px-2 py-1.5","hover:bg-fill-subtle",bi,Zn,In),children:[a.jsx("span",{className:Z("mt-0.5 size-3.5 shrink-0 text-muted-foreground [&>svg]:size-3.5",In,i?c:"group-hover/capability-row:text-foreground"),children:l}),a.jsxs("span",{className:"min-w-0 flex-1",children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[a.jsx(Y,{as:"span",variant:"meta",tone:"ink",className:"min-w-0 truncate",children:t}),a.jsx(Y,{as:"span",variant:"meta",tone:"muted",className:"shrink-0 tabular-nums",children:n})]}),a.jsx(Y,{as:"span",variant:"meta",tone:"muted",className:"mt-0.5 block",children:r})]}),a.jsx(Zs,{className:Z("mt-0.5 size-3 shrink-0 text-muted-foreground group-hover/capability-row:text-foreground",In)})]})}function Het({agentId:e,view:t}){const{data:n,isLoading:r}=Qk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=kVt(n),i=s?n?.memoryType==="gateway"?"Gateway":"On":"Off",o=r?"Checking":i;return a.jsx(O$,{view:t,label:"Memory",status:o,description:s?"Conversation history and configured memory features are available for this agent.":"This agent has no memory configured, so conversations are not saved as memory-backed threads.",docsHref:"https://mastra.ai/docs/memory/overview",enabled:s,tone:"purple",icon:a.jsx(d$,{})})}function Get({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{isCmsAvailable:s,isLoading:i}=Hx(),o=OVt(n,s),l=n?.editor===!1,c=t6({agentId:e,params:{orderBy:{field:"createdAt",direction:"DESC"}},queryOptions:{enabled:!!e&&o}}),u=c.data?.total??c.data?.versions.length??0,d=r||i||o&&c.isLoading,f=u>0?String(u):"Ready",p=d?"Checking":o?f:l?"Locked":"Off",v=o?"Editor is available for versioned agent overrides.":l?"This code-defined agent explicitly disables editor overrides.":"Register MastraEditor to enable versioned agent overrides.";return a.jsx(O$,{view:t,label:"Editor",status:p,description:v,docsHref:"https://mastra.ai/docs/editor/overview",enabled:o,tone:"amber",icon:a.jsx(Vc,{})})}function Ket({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=nN(n?.tools);return a.jsx(O$,{view:t,label:"Tools",status:r?"Checking":eee(s),description:s>0?`${s} tool${s===1?"":"s"} available.`:"No tools are configured.",docsHref:"https://mastra.ai/docs/agents/using-tools-and-mcp",enabled:s>0,tone:"emerald",icon:a.jsx(dd,{})})}function Yet({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=nN(n?.workflows);return a.jsx(O$,{view:t,label:"Workflows",status:r?"Checking":eee(s),description:s>0?`${s} workflow${s===1?"":"s"} available.`:"No workflows are attached to this agent.",docsHref:"https://mastra.ai/docs/workflows/overview",enabled:s>0,tone:"sky",icon:a.jsx(wk,{})})}function Xet({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=nN(n?.agents);return a.jsx(O$,{view:t,label:"Sub-agents",status:r?"Checking":eee(s),description:s>0?`${s} sub-agent${s===1?"":"s"} available.`:"No sub-agents are attached to this agent.",docsHref:"https://mastra.ai/docs/agents/supervisor-agents",enabled:s>0,tone:"cyan",icon:a.jsx(awe,{})})}function Jet({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=SVt(n);return a.jsx(O$,{view:t,label:"Processors",status:r?"Checking":eee(s),description:s>0?`${s} input/output processor${s===1?"":"s"} configured.`:"No input or output processors are configured.",docsHref:"https://mastra.ai/docs/agents/processors",enabled:s>0,tone:"orange",icon:a.jsx(_pt,{})})}function dxs({agentId:e}){const{data:t}=Qk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:n}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{isCmsAvailable:r}=Hx(),s=[kVt(t),OVt(n,r),nN(n?.tools)>0,nN(n?.workflows)>0,nN(n?.agents)>0,SVt(n)>0],i=s.filter(Boolean).length;return a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",className:"shrink-0",children:[i,"/",s.length]})}function fxs({agentId:e}){const[t,n]=g.useState(!1);return a.jsx(gc,{open:t,onOpenChange:n,children:a.jsxs("div",{className:"shrink-0 border-t border-border",children:[a.jsx(Gl,{asChild:!0,"aria-label":t?"Hide capability details":"Show capability details",children:a.jsxs("button",{type:"button","data-testid":"agent-capabilities-footer",className:Z("flex w-full cursor-pointer items-center gap-1.5 px-2 py-2 text-left hover:bg-fill-subtle focus-visible:bg-fill-subtle active:bg-fill aria-expanded:bg-fill-hover data-[panel-open]:bg-fill-hover",Ax,Zn,In),children:[a.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden",children:[a.jsx(Het,{agentId:e,view:"chip"}),a.jsx(Get,{agentId:e,view:"chip"}),a.jsx(Ket,{agentId:e,view:"chip"}),a.jsx(Yet,{agentId:e,view:"chip"}),a.jsx(Xet,{agentId:e,view:"chip"}),a.jsx(Jet,{agentId:e,view:"chip"})]}),a.jsx(dxs,{agentId:e}),a.jsx(Ha,{direction:"right",className:"size-3.5 text-muted-foreground"})]})}),a.jsx(Kl,{className:"px-2 pb-2",children:a.jsxs("div",{className:"grid gap-1",children:[a.jsx(Het,{agentId:e,view:"row"}),a.jsx(Get,{agentId:e,view:"row"}),a.jsx(Ket,{agentId:e,view:"row"}),a.jsx(Yet,{agentId:e,view:"row"}),a.jsx(Xet,{agentId:e,view:"row"}),a.jsx(Jet,{agentId:e,view:"row"})]})})]})})}function hxs(e){let t=e;for(let n=0;n<3&&typeof t=="string";n++)try{const r=JSON.parse(t);if(typeof r=="object"&&r!==null)return r;if(typeof r=="string"&&r!==t){t=r;continue}break}catch{break}return t}function pxs(e){return typeof e=="object"&&e!==null&&"parts"in e&&Array.isArray(e.parts)}function mxs(e){const t=e.type;return t==="data-om-status"||t==="data-om-observation-start"||t==="data-om-observation-end"||t==="data-om-buffering-start"||t==="data-om-buffering-end"||t==="data-om-activation"}function gxs(e,t){switch(e.type){case"data-om-status":return{type:"status",timestamp:t,pendingTokens:e.data.windows?.active?.messages?.tokens,observationTokens:e.data.windows?.active?.observations?.tokens,observationThreshold:e.data.windows?.active?.messages?.threshold,reflectionThreshold:e.data.windows?.active?.observations?.threshold};case"data-om-observation-start":return{type:"observation-start",timestamp:e.data.startedAt,pendingTokens:e.data.tokensToObserve,observationThreshold:e.data.config?.messageTokens,reflectionThreshold:e.data.config?.observationTokens};case"data-om-observation-end":return{type:"observation-end",timestamp:e.data.completedAt,observationTokens:e.data.observationTokens};case"data-om-buffering-start":return{type:"buffering-start",timestamp:e.data.startedAt,pendingTokens:e.data.tokensToBuffer,observationThreshold:e.data.config?.messageTokens,reflectionThreshold:e.data.config?.observationTokens};case"data-om-buffering-end":return{type:"buffering-end",timestamp:e.data.completedAt,observationTokens:e.data.bufferedTokens};case"data-om-activation":return{type:"activation",timestamp:e.data.activatedAt,pendingTokens:e.data.tokensActivated,observationTokens:e.data.observationTokens,observationThreshold:e.data.config?.messageTokens,reflectionThreshold:e.data.config?.observationTokens,generationCount:e.data.generationCount}}}function vxs(e){const t=[];for(const n of e){const r=hxs(n.content);if(pxs(r))for(const s of r.parts)mxs(s)&&t.push(gxs(s,new Date(n.createdAt).toISOString()))}return t.sort((n,r)=>n.timestamp.localeCompare(r.timestamp)),t}function QA(e){return/[Zz+-]\d{0,4}$/.test(e.trim())?new Date(e).getTime():new Date(e.trim().replace(" ","T")+"Z").getTime()}function yxs(e){if(e.length===0)return{tMin:0,tMax:1};let t=1/0,n=-1/0;for(const r of e){const s=QA(r);s<t&&(t=s),s>n&&(n=s)}return t===n?{tMin:t,tMax:t+1}:{tMin:t,tMax:n}}function Rz(e,t){return(QA(e)-t.tMin)/(t.tMax-t.tMin)}function YNe(e,t){return new Date(t.tMin+e*(t.tMax-t.tMin))}function xxs(e,t){return YNe(e,t).getTime()}function jVt(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function bxs(e){return QA(jVt(e))}function wxs(e,t){if(t==null)return null;const r=e.map(s=>({id:s.id,t:QA(jVt(s))})).toSorted((s,i)=>s.t-i.t).findLast(s=>s.t<=t);return r?r.id:null}function ett(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function Sxs(e){return[...e].sort((t,n)=>QA(ett(t))-QA(ett(n)))}function kxs({markers:e,omRecords:t,observationThreshold:n,reflectionThreshold:r}){const s=[...e].filter(o=>o.type==="status"&&(o.pendingTokens!=null||o.observationTokens!=null)).sort((o,l)=>o.timestamp.localeCompare(l.timestamp)).at(-1),i=Sxs(t).at(-1);return{messageTokens:s?.pendingTokens??i?.pendingMessageTokens,messageThreshold:s?.observationThreshold??n,memoryTokens:s?.observationTokens??i?.observationTokenCount,memoryThreshold:s?.reflectionThreshold??r}}function zD(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function Oxs(e,t,n){const r=e.map(i=>({ts:String(zD(i)),pendingMessageTokens:i.pendingMessageTokens})),s=t.flatMap(i=>i.pendingTokens==null?[]:{ts:i.timestamp,pendingMessageTokens:i.pendingTokens});return[...r,...s].sort((i,o)=>i.ts.localeCompare(o.ts)).map(i=>({t:Rz(i.ts,n),pendingMessageTokens:i.pendingMessageTokens}))}function jxs(e,t,n){const r=[...e.map(i=>({ts:String(zD(i)),observationTokenCount:i.observationTokenCount})),...t.flatMap(i=>i.type!=="status"||i.observationTokens==null?[]:{ts:i.timestamp,observationTokenCount:i.observationTokens})].sort((i,o)=>i.ts.localeCompare(o.ts));let s=0;return r.map(i=>(s=Math.max(s,i.observationTokenCount),{t:Rz(i.ts,n),observationTokenCount:s}))}function Cxs(e,t){const n=e.flatMap(s=>s.observationTokens==null||s.type!=="buffering-end"&&s.type!=="activation"?[]:{ts:s.timestamp,bufferedObservationTokenCount:s.type==="activation"?-s.observationTokens:s.observationTokens}).sort((s,i)=>s.ts.localeCompare(i.ts));let r=0;return n.map(s=>(r=Math.max(0,r+s.bufferedObservationTokenCount),{t:Rz(s.ts,t),bufferedObservationTokenCount:r}))}function _xs(e,t){return[...e].sort((n,r)=>String(zD(n)).localeCompare(String(zD(r)))).map(n=>({t:Rz(String(zD(n)),t),event:1}))}function Txs(e,t){return[...e].sort((n,r)=>new Date(n.createdAt).getTime()-new Date(r.createdAt).getTime()).map(n=>({t:Rz(new Date(n.createdAt).toISOString(),t),event:1,role:n.role}))}function Ixs(e,t,n){const r=new Map;for(const c of e)c.t!==void 0&&r.set(c.t,Number(c[t]??0));const s=n.reduce((c,u)=>{const d=c.get(u.t);return d?d.push(u):c.set(u.t,[u]),c},new Map),i=Array.from(new Set([...r.keys(),...s.keys()])).sort((c,u)=>c-u);let o=0;const l=[];for(const c of i){const u=r.get(c);u!=null&&(o=u);const d=s.get(c);if(d)for(const f of d)l.push({...f,t:c,[t]:o});else l.push({t:c,[t]:o})}return l}function Exs(e,t,n){if(n==null)return;const r=Math.max(0,...e.map(s=>Number(s[t])||0));return Math.max(r,n)}function Nxs(e){return e==null?null:Number(e)}function Axs(e){return!!e?.event}const Pxs="var(--chart-green)",$xs="var(--chart-amber)",ttt="var(--chart-pink)";function Rxs({domain:e}){const t=[0,.25,.5,.75,1];return a.jsxs("div",{className:"grid grid-cols-[6rem_1fr] items-center",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"flex items-center self-stretch border-r border-border pl-3",children:"Time"}),a.jsx("div",{className:"flex justify-between px-1 py-1.5",children:t.map(n=>a.jsx(Y,{tone:"muted",as:"span",variant:"meta",font:"mono",children:rs(YNe(n,e),"date-time-seconds",{timeZone:"UTC"})},n))})]})}function XNe({active:e,payload:t,domain:n,showValue:r}){if(!e||!t?.length)return null;const s=t[0]?.payload?.t,i=n!=null&&s!=null?rs(YNe(s,n),"date-time-seconds",{timeZone:"UTC"}):null,o=t.filter(l=>l.name!=="t"&&l.name!=="time"&&l.value!=null);return r?a.jsxs("div",{className:`${th} flex flex-col gap-0.5 rounded px-2 py-1.5 tabular-nums`,children:[i&&a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx(Y,{as:"span",variant:"meta",tone:"muted",children:"time"}),a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"ink",children:i})]}),o.map(l=>a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx(Y,{as:"span",variant:"meta",tone:"muted",children:l.name}),a.jsx(Y,{as:"span",variant:"meta",tone:"ink",children:typeof l.value=="number"?Math.round(l.value).toLocaleString():String(l.value)})]},l.name))]}):a.jsx(Y,{as:"p",variant:"meta",className:`${th} rounded px-2 py-1`,children:i&&a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"ink",children:i})})}function Mxs({label:e,data:t,dataKey:n,color:r,gradientId:s,domain:i,zoomDomain:o,threshold:l}){const c=Exs(t,n,l);return a.jsxs("div",{className:"relative grid grid-cols-[6rem_1fr] items-center border-b border-border hover:z-10",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"flex items-center self-stretch border-r border-border pl-3",children:e}),a.jsx("div",{children:a.jsx(hA,{width:"100%",height:32,children:a.jsxs(MMr,{data:t,margin:{top:0,right:0,bottom:0,left:0},children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:s,x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"0%",stopColor:r,stopOpacity:.35}),a.jsx("stop",{offset:"100%",stopColor:r,stopOpacity:.03})]})}),a.jsx(E6,{dataKey:"t",type:"number",domain:o,allowDataOverflow:!0,hide:!0}),a.jsx(N6,{type:"number",domain:c!=null?[0,c]:void 0,hide:!0}),a.jsx(j6,{content:a.jsx(XNe,{domain:i,showValue:!0}),cursor:{stroke:"var(--border)"}}),a.jsx(HY,{type:"linear",dataKey:n,stroke:r,strokeWidth:1,fill:`url(#${s})`,isAnimationActive:!1}),l!=null&&a.jsx(ZY,{y:l,stroke:"var(--border-strong)",strokeDasharray:"4 3"})]})})})]})}function Dxs({label:e,data:t,color:n,height:r=32,domain:s,zoomDomain:i}){return a.jsxs("div",{className:"relative grid grid-cols-[6rem_1fr] items-center border-b border-border hover:z-10",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"flex items-center self-stretch border-r border-border pl-3",children:e}),a.jsx("div",{children:a.jsx(hA,{width:"100%",height:r,children:a.jsxs($Mr,{margin:{top:0,right:0,bottom:0,left:0},children:[a.jsx(E6,{dataKey:"t",type:"number",domain:i,allowDataOverflow:!0,hide:!0}),a.jsx(N6,{dataKey:"event",type:"number",domain:[0,2],hide:!0}),a.jsx(j6,{content:a.jsx(XNe,{domain:s}),cursor:!1}),a.jsx(eAt,{data:t,fill:n,isAnimationActive:!1,shape:o=>{const l=o.cx;return a.jsxs("g",{children:[a.jsx("rect",{x:l-6,y:0,width:12,height:r,fill:"transparent"}),a.jsx("rect",{x:l-1.5,y:0,width:3,height:r,fill:n})]})}})]})})})]})}function ntt({label:e,areaData:t,areaDataKey:n,eventData:r,color:s,gradientId:i,domain:o,zoomDomain:l,threshold:c,height:u=44,onSelectT:d}){const f=Ixs(t,n,r);return a.jsxs("div",{className:"relative grid grid-cols-[6rem_1fr] items-center border-b border-border hover:z-10",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"flex items-center self-stretch border-r border-border pl-3",children:e}),a.jsx("div",{children:a.jsx(hA,{width:"100%",height:u,children:a.jsxs(bCe,{margin:{top:0,right:0,bottom:0,left:0},onClick:h=>{const p=Nxs(h?.activeLabel);p!=null&&d&&d(p)},className:d?"cursor-pointer":void 0,children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:i,x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"0%",stopColor:s,stopOpacity:.35}),a.jsx("stop",{offset:"100%",stopColor:s,stopOpacity:.06})]})}),a.jsx(E6,{dataKey:"t",type:"number",domain:l,allowDataOverflow:!0,hide:!0}),a.jsx(N6,{yAxisId:"area",dataKey:n,type:"number",hide:!0,domain:[0,"dataMax"]}),a.jsx(j6,{content:a.jsx(XNe,{domain:o,showValue:!0}),cursor:!1}),a.jsx(HY,{yAxisId:"area",data:f,type:"linear",dataKey:n,stroke:s,strokeWidth:1,fill:`url(#${i})`,isAnimationActive:!1,activeDot:{r:5,stroke:s,strokeWidth:2,fill:"var(--background)"},dot:h=>Axs(h.payload)?a.jsx("circle",{cx:h.cx,cy:h.cy,r:4,fill:s}):a.jsx(a.Fragment,{})}),c!=null&&a.jsx(ZY,{yAxisId:"area",y:c,stroke:"var(--border-strong)",strokeDasharray:"4 3"})]})})})]})}function Lxs({tDomain:e,zoomLeft:t,zoomRight:n,onZoomLeftChange:r,onZoomRightChange:s,onReset:i}){const o=g.useRef(null),l=g.useRef(null),c=e.tMax-e.tMin,u=c>0?(t-e.tMin)/c*100:0,d=c>0?(n-e.tMin)/c*100:100,f=g.useCallback(h=>{const p=o.current;if(!p)return null;const m=p.getBoundingClientRect(),v=Math.max(0,Math.min(1,(h-m.left)/m.width));return e.tMin+v*(e.tMax-e.tMin)},[e.tMin,e.tMax]);return g.useEffect(()=>{const h=m=>{if(!l.current)return;const v=f(m.clientX);v!=null&&(l.current==="left"?r(Math.min(v,n)):s(Math.max(v,t)))},p=()=>{l.current=null};return window.addEventListener("mousemove",h),window.addEventListener("mouseup",p),()=>{window.removeEventListener("mousemove",h),window.removeEventListener("mouseup",p)}},[f,t,n,r,s]),a.jsxs("div",{className:"grid grid-cols-[6rem_1fr] items-center border-b border-border",children:[a.jsxs("div",{className:"flex items-center gap-1 self-stretch border-r border-border pl-3",children:[a.jsx(Y,{variant:"meta",tone:"muted",children:"Zoom"}),a.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":"Reset zoom",onClick:i,children:a.jsx(E_,{className:"size-3"})})]}),a.jsxs("div",{ref:o,"data-zoom-track":"",className:"relative h-6 cursor-pointer select-none",onMouseDown:h=>{const p=f(h.clientX);if(p==null)return;h.preventDefault();const m=Math.abs(p-t),v=Math.abs(p-n);m<=v?(r(Math.min(p,n)),l.current="left"):(s(Math.max(p,t)),l.current="right")},children:[a.jsx("div",{"data-zoom-part":"before",className:"absolute inset-y-0 left-0 bg-background/60",style:{width:`${u}%`}}),a.jsx("div",{"data-zoom-part":"band",className:"absolute inset-y-0 border-y border-surface-rim bg-fill-subtle",style:{left:`${u}%`,right:`${100-d}%`}}),a.jsx("div",{"data-zoom-part":"after",className:"absolute inset-y-0 right-0 bg-background/60",style:{width:`${100-d}%`}}),a.jsx("div",{"data-zoom-handle":"left",className:"absolute inset-y-0 w-1 cursor-col-resize bg-foreground/50 hover:bg-foreground",style:{left:`${u}%`,transform:"translateX(-50%)"},onMouseDown:h=>{h.preventDefault(),h.stopPropagation(),l.current="left"}}),a.jsx("div",{"data-zoom-handle":"right",className:"absolute inset-y-0 w-1 cursor-col-resize bg-foreground/50 hover:bg-foreground",style:{left:`${d}%`,transform:"translateX(-50%)"},onMouseDown:h=>{h.preventDefault(),h.stopPropagation(),l.current="right"}})]})]})}const zxs={tMin:0,tMax:1};function Fxs({omRecords:e,markers:t,messages:n,tDomain:r,observationThreshold:s,reflectionThreshold:i,onSelectTimestamp:o,zoomRange:l,onZoomRangeChange:c}){const u=r??zxs,d=g.useCallback(Q=>{o?.(xxs(Q,u))},[o,u]),f=l!=null&&c!=null,[h,p]=g.useState(u.tMin),[m,v]=g.useState(u.tMax);g.useEffect(()=>{f||(p(u.tMin),v(u.tMax))},[u.tMin,u.tMax,f]);const y=f?l.left:h,x=f?l.right:m,b=g.useCallback(Q=>{f?c({left:Q,right:x}):p(Q)},[f,c,x]),S=g.useCallback(Q=>{f?c({left:y,right:Q}):v(Q)},[f,c,y]),k=g.useCallback(()=>{f?c({left:u.tMin,right:u.tMax}):(p(u.tMin),v(u.tMax))},[f,c,u.tMin,u.tMax]),j=u.tMax-u.tMin,C=j>0?(y-u.tMin)/j:0,T=j>0?(x-u.tMin)/j:1,_=[C,T],N=g.useMemo(()=>Txs(n,u),[n,u]),E=g.useMemo(()=>Oxs(e,t,u),[e,t,u]),A=g.useMemo(()=>jxs(e,t,u),[e,t,u]),P=g.useMemo(()=>Cxs(t,u),[t,u]),L=g.useMemo(()=>_xs(e,u),[e,u]);return N.length>0||E.length>0||A.length>0||L.length>0?a.jsxs("div",{className:"flex flex-col pr-2 pb-2 [&_.recharts-surface]:outline-none",children:[a.jsx(ntt,{label:"Messages",areaData:E,areaDataKey:"pendingMessageTokens",eventData:N,color:Pxs,gradientId:"grad-messages",domain:u,zoomDomain:_,threshold:s,onSelectT:o?d:void 0}),a.jsx(ntt,{label:"Observations",areaData:A,areaDataKey:"observationTokenCount",eventData:L,color:$xs,gradientId:"grad-observations",domain:u,zoomDomain:_,threshold:i,onSelectT:o?d:void 0}),P.length>0&&a.jsx(Mxs,{label:"Buffered obs",data:P,dataKey:"bufferedObservationTokenCount",color:ttt,gradientId:"grad-buffered-obs",domain:u,zoomDomain:_,threshold:i}),L.length>0&&a.jsx(Dxs,{label:"Events",data:L,color:ttt,domain:u,zoomDomain:_}),a.jsx(Rxs,{domain:u}),a.jsx(Lxs,{tDomain:u,zoomLeft:y,zoomRight:x,onZoomLeftChange:b,onZoomRightChange:S,onReset:k})]}):null}const Bxs=g.lazy(()=>Ai(async()=>{const{CodeDiff:e}=await import("./CodeDiff.es-ru6KxWJp.js");return{CodeDiff:e}},__vite__mapDeps([9,4,1,3]),import.meta.url).then(({CodeDiff:e})=>({default:e})));function Vxs(e){if(!e)return null;const t=e.match(/^(\d{1,2}):(\d{2})$/);if(!t)return e;const[,n,r]=t;return rs(new Date(2e3,0,1,Number(n),Number(r)),"time")??e}function Uxs(e,t){if(t)return{card:"bg-transparent border-transparent",text:"text-muted-foreground",time:"text-muted-foreground"};if(!e)return{card:"border-border bg-background",text:"text-foreground",time:"text-muted-foreground"};const n=Yve[e];return{card:n.card,text:"text-foreground",time:n.time}}function qxs(e){const t=e.trim();if(!t)return null;if(t.startsWith("* ->")||t.startsWith("->")){const n=t.replace(/^\*?\s*->\s*/,"").trim();return n?{text:n,time:null,priority:null,children:[]}:null}if(t.startsWith("-")){const n=t.replace(/^-\s*/,"").trim();return n?{text:n,time:null,priority:null,children:[]}:null}if(t.startsWith("*")){let n=t.slice(1).trimStart(),r=null;for(const[o,l]of Object.entries(Kve))if(n.startsWith(o)){r=l,n=n.slice(o.length).trimStart();break}let s=null;const i=n.match(/^\((\d{1,2}:\d{2})\)/);if(i){const[o,l]=i;o!==void 0&&l!==void 0&&(s=l,n=n.slice(o.length).trimStart())}if(n)return{text:n,time:s,priority:r,children:[]}}return{text:t,time:null,priority:null,children:[]}}function Qxs(e){const t="<observations>",n=e.indexOf(t),r=n===-1?-1:e.indexOf("</observations>",n+t.length),s=(r===-1?e:e.slice(n+t.length,r)).trim();if(!s)return[];const i=s.split(`
675
+ ${D}`:o,K=()=>{h.current===B&&(c?c(D=>({text:M(D.text),attachments:[...V,...D.attachments]})):(l(M),S(V)),m("Your message could not be sent. Your draft has been restored."))};m(void 0);try{const D=y.length>0?await x():void 0;if(h.current!==B)return;c?c($=>({text:$.text===o?"":$.text,attachments:$.attachments.filter(z=>!W.has(z.id))})):(l(""),b()),N($=>$+1),Promise.resolve(v({message:o,attachments:D})).then($=>{$===!1&&K()})}catch{h.current===B&&m("Attachments could not be prepared. Your draft has been kept.")}finally{f.current=!1}};return a.jsxs("div",{className:"relative",style:{viewTransitionName:"agent-chat-composer"},children:[a.jsx(Yys,{voiceCall:L}),(p||u?.error)&&a.jsx(Y,{variant:"caption",role:"alert",children:p||u?.error}),u?.restoring&&a.jsx(Y,{variant:"caption",role:"status",className:"sr-only",children:"Restoring draft…"}),a.jsx(Qcs,{disabled:!A||u?.restoring,children:a.jsx(L4t,{className:"relative",onSubmit:B=>{B.preventDefault(),q()},children:a.jsx(F4t,{busy:j,children:a.jsxs(z4t,{sendingPulseKey:_,children:[a.jsx(Bcs,{}),a.jsx(V4t,{ref:d,value:o,placeholder:A?"Enter your message...":"You don't have permission to execute agents",onChange:B=>{l(B.target.value)},onKeyDown:B=>{if(!(B.nativeEvent.isComposing||B.keyCode===229)&&B.key==="Enter"&&!B.shiftKey){if(Q)return;B.preventDefault(),B.stopPropagation(),q()}},disabled:P}),e&&!n&&!r&&a.jsx(Xhs,{}),a.jsx(U4t,{children:a.jsx(axs,{canExecute:A,agentId:e,runOptionsSlot:s,showModelSwitcher:!!(e&&!n&&!r),isEmpty:F,isRunning:j,canSendWhileStreaming:C,onCancel:()=>{T()},onSetText:B=>{l(B)},voiceCall:L})})]})})})})]})},oxs=({agentId:e,onTranscript:t})=>{const[n]=xr("agent",e??""),{start:r,stop:s,isListening:i,transcript:o}=B0n({agentId:e,requestContext:n});return g.useEffect(()=>{o&&g.startTransition(()=>t(o))},[t,o]),a.jsx(ce,{variant:"ghost",size:"icon-md",type:"button",tooltip:i?"Stop dictation":"Start dictation",onClick:()=>i?s():r(),children:i?a.jsx(Pye,{}):a.jsx(wEn,{})})},axs=({canExecute:e=!0,agentId:t,showModelSwitcher:n,runOptionsSlot:r,isEmpty:s,isRunning:i,canSendWhileStreaming:o,onCancel:l,onSetText:c,voiceCall:u})=>a.jsxs(a.Fragment,{children:[(n&&t||r)&&a.jsxs("div",{className:"flex max-w-full shrink-0 items-center gap-1.5",children:[n&&t&&a.jsxs(a.Fragment,{children:[a.jsx(Yhs,{}),a.jsx(Vys,{agentId:t})]}),r]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[e&&a.jsx(Ocs,{}),e&&a.jsx(oxs,{agentId:t,onTranscript:c}),e&&t&&u&&a.jsx(Gys,{voiceCall:u})]}),a.jsx(lxs,{canExecute:e,isEmpty:s,isRunning:i,canSendWhileStreaming:o,onCancel:l})]})]}),lxs=({canExecute:e=!0,isEmpty:t,isRunning:n,canSendWhileStreaming:r,onCancel:s})=>{const{isAddingAttachments:i}=_z();return n&&!r?a.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:a.jsx(Pye,{})}):a.jsxs(a.Fragment,{children:[a.jsx(ce,{type:"submit",variant:"default",size:"icon-md",tooltip:e?"Send":"No permission to execute",disabled:!e||t||i,children:a.jsx(bk,{})}),n&&a.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:a.jsx(Pye,{})})]})},Pye=()=>a.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:Zn,children:[a.jsx("circle",{cx:"12",cy:"12",r:"10"}),a.jsx("rect",{width:"6",height:"6",x:"9",y:"9",rx:"1"})]}),KNe=({agentId:e,agentName:t,threadId:n,memory:r,refreshThreadList:s,modelVersion:i,agentVersionId:o,supportsMemory:l,modelList:c,messageId:u,suggestedPrompts:d,isNewThread:f,hideModelSwitcher:h,runOptionsSlot:p})=>{const{settings:m}=uTe(),v=xr("agent",e)[0],{data:y,isLoading:x,fetchNextPage:b,hasNextPage:S,isFetchingNextPage:k}=NK({agentId:e,threadId:f?void 0:n,memory:r??!1,requestContext:v});g.useEffect(()=>{u&&y&&!x&&setTimeout(()=>{const _=document.querySelector(`[data-message-id="${u}"]`);_&&(_.scrollIntoView({behavior:"smooth",block:"center"}),_.classList.add("bg-muted"),setTimeout(()=>{_.classList.remove("bg-muted")},2e3))},100)},[u,y,x]);const j=g.useRef({threadId:n,messages:[]});j.current.threadId!==n&&(j.current={threadId:n,messages:[]});const C=y?.messages??j.current.messages,T=()=>{k||b()};return a.jsx(HXr,{agentId:e,agentName:t,modelVersion:i,agentVersionId:o,supportsMemory:l,threadId:n,initialMessages:C,refreshThreadList:s,settings:m,requestContext:v,children:a.jsx(rxs,{agentName:t??"",agentId:e,threadId:n,suggestedPrompts:d,hasModelList:!!c,hideModelSwitcher:h,refreshThreadList:s,runOptionsSlot:p,isHistoryLoading:x,onLoadPrevious:S?T:void 0,isLoadingPrevious:k})})};function _W(){return a.jsx(Yt,{tone:"error",titleSlot:"Agent not found",descriptionSlot:"This agent may have been renamed or removed. Reload to check again, or choose another agent.",actionSlot:a.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[a.jsx(ce,{onClick:()=>window.location.reload(),children:"Reload"}),a.jsx(ce,{render:a.jsx(lc,{to:"/agents"}),children:"Choose agent"})]})})}function Wet(){const{agentId:e,threadId:t}=Cr(),[n]=wi(),{data:r,isLoading:s,error:i}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:o}=Qk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),l=Lr(),c=t==="new",u=g.useMemo(()=>ka(),[t]),d=!!o?.result,{refetch:f}=aTe({resourceId:e,agentId:e,isMemoryEnabled:d,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!d}});g.useEffect(()=>{d&&(t||l(`/agents/${e}/session/new`))},[d,t,e,l]);const h=n.get("messageId")??void 0,p=g.useMemo(()=>RNe(r),[r]);if(i&&Cs(i))return a.jsx(ci,{variant:"fill"});if(i&&_s(i))return a.jsx(Gs,{variant:"fill",resource:"agents"});if(s)return a.jsx(cxs,{});if(i&&Pk(i))return a.jsx(_W,{});if(i)return a.jsx(Yt,{tone:"error",titleSlot:"Failed to load agent",descriptionSlot:i.message});if(!r)return a.jsx(_W,{});const m=c?u:t??u,v=async()=>{await f(),c&&l(`/agents/${e}/session/${u}`)};return a.jsx(f4t,{agentId:e,defaultSettings:p,children:a.jsx(O4t,{agentId:e,threadId:m,resourceId:e,children:a.jsx(CX,{children:a.jsx(_X,{agentId:e,threadId:m,enabled:!!(r?.hasBrowser??r?.browserTools?.length),children:a.jsx(gNe,{children:a.jsx(_4t,{children:a.jsx(EX,{children:a.jsxs(It,{variant:"fit",children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(d4t,{}),a.jsx("div",{className:"relative grid h-full min-h-0",children:a.jsx(KNe,{agentId:e,agentName:r?.name,modelVersion:r?.modelVersion,supportsMemory:r?.supportsMemory,threadId:m,memory:d,refreshThreadList:v,modelList:r?.modelList,messageId:h,isNewThread:c,hideModelSwitcher:!0,runOptionsSlot:a.jsx(MNe,{agentId:e})},m)})]})})})})},`session-${e}-${m}`)},`browser-${e}-${m}`)})})}const cxs=()=>a.jsxs(It,{variant:"fit",children:[a.jsx("h1",{className:"sr-only",children:"Agent session"}),a.jsx(d4t,{}),a.jsx("div",{className:"relative grid h-full overflow-y-auto pt-4","data-testid":"agent-session-skeleton","aria-busy":"true",children:a.jsx(bVt,{})})]}),uxs={purple:{icon:"text-badge-purple-indicator"},amber:{icon:"text-badge-amber-indicator"},emerald:{icon:"text-badge-green-indicator"},sky:{icon:"text-badge-blue-indicator"},cyan:{icon:"text-badge-cyan-indicator"},orange:{icon:"text-badge-orange-indicator"}},nN=e=>e?Object.keys(e).length:0,eee=e=>e>0?String(e):"Off",SVt=e=>(e?.inputProcessors?.length??0)+(e?.outputProcessors?.length??0),kVt=e=>!!e?.result,OVt=(e,t)=>!!(t&&e&&e.editor!==!1);function O$({view:e,label:t,status:n,description:r,docsHref:s,enabled:i,tone:o,icon:l}){const c=uxs[o].icon;return e==="chip"?a.jsx("span",{"aria-label":`${t}: ${n}`,className:Z("pointer-events-none inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1 text-muted-foreground",i?c:void 0),children:a.jsx("span",{className:"size-3 shrink-0 [&>svg]:size-3",children:l})}):a.jsxs("a",{"aria-label":`${t}: ${n}`,href:s,target:"_blank",rel:"noopener noreferrer",className:Z("group/capability-row flex min-w-0 items-start gap-2 rounded-md px-2 py-1.5","hover:bg-fill-subtle",bi,Zn,In),children:[a.jsx("span",{className:Z("mt-0.5 size-3.5 shrink-0 text-muted-foreground [&>svg]:size-3.5",In,i?c:"group-hover/capability-row:text-foreground"),children:l}),a.jsxs("span",{className:"min-w-0 flex-1",children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[a.jsx(Y,{as:"span",variant:"meta",tone:"ink",className:"min-w-0 truncate",children:t}),a.jsx(Y,{as:"span",variant:"meta",tone:"muted",className:"shrink-0 tabular-nums",children:n})]}),a.jsx(Y,{as:"span",variant:"meta",tone:"muted",className:"mt-0.5 block",children:r})]}),a.jsx(Zs,{className:Z("mt-0.5 size-3 shrink-0 text-muted-foreground group-hover/capability-row:text-foreground",In)})]})}function Het({agentId:e,view:t}){const{data:n,isLoading:r}=Qk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=kVt(n),i=s?n?.memoryType==="gateway"?"Gateway":"On":"Off",o=r?"Checking":i;return a.jsx(O$,{view:t,label:"Memory",status:o,description:s?"Conversation history and configured memory features are available for this agent.":"This agent has no memory configured, so conversations are not saved as memory-backed threads.",docsHref:"https://mastra.ai/docs/memory/overview",enabled:s,tone:"purple",icon:a.jsx(d$,{})})}function Get({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{isCmsAvailable:s,isLoading:i}=Hx(),o=OVt(n,s),l=n?.editor===!1,c=t6({agentId:e,params:{orderBy:{field:"createdAt",direction:"DESC"}},queryOptions:{enabled:!!e&&o}}),u=c.data?.total??c.data?.versions.length??0,d=r||i||o&&c.isLoading,f=u>0?String(u):"Ready",p=d?"Checking":o?f:l?"Locked":"Off",v=o?"Editor is available for versioned agent overrides.":l?"This code-defined agent explicitly disables editor overrides.":"Register MastraEditor to enable versioned agent overrides.";return a.jsx(O$,{view:t,label:"Editor",status:p,description:v,docsHref:"https://mastra.ai/docs/editor/overview",enabled:o,tone:"amber",icon:a.jsx(Vc,{})})}function Ket({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=nN(n?.tools);return a.jsx(O$,{view:t,label:"Tools",status:r?"Checking":eee(s),description:s>0?`${s} tool${s===1?"":"s"} available.`:"No tools are configured.",docsHref:"https://mastra.ai/docs/agents/using-tools-and-mcp",enabled:s>0,tone:"emerald",icon:a.jsx(dd,{})})}function Yet({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=nN(n?.workflows);return a.jsx(O$,{view:t,label:"Workflows",status:r?"Checking":eee(s),description:s>0?`${s} workflow${s===1?"":"s"} available.`:"No workflows are attached to this agent.",docsHref:"https://mastra.ai/docs/workflows/overview",enabled:s>0,tone:"sky",icon:a.jsx(wk,{})})}function Xet({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=nN(n?.agents);return a.jsx(O$,{view:t,label:"Sub-agents",status:r?"Checking":eee(s),description:s>0?`${s} sub-agent${s===1?"":"s"} available.`:"No sub-agents are attached to this agent.",docsHref:"https://mastra.ai/docs/agents/supervisor-agents",enabled:s>0,tone:"cyan",icon:a.jsx(awe,{})})}function Jet({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=SVt(n);return a.jsx(O$,{view:t,label:"Processors",status:r?"Checking":eee(s),description:s>0?`${s} input/output processor${s===1?"":"s"} configured.`:"No input or output processors are configured.",docsHref:"https://mastra.ai/docs/agents/processors",enabled:s>0,tone:"orange",icon:a.jsx(_pt,{})})}function dxs({agentId:e}){const{data:t}=Qk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:n}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{isCmsAvailable:r}=Hx(),s=[kVt(t),OVt(n,r),nN(n?.tools)>0,nN(n?.workflows)>0,nN(n?.agents)>0,SVt(n)>0],i=s.filter(Boolean).length;return a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",className:"shrink-0",children:[i,"/",s.length]})}function fxs({agentId:e}){const[t,n]=g.useState(!1);return a.jsx(gc,{open:t,onOpenChange:n,children:a.jsxs("div",{className:"shrink-0 border-t border-border",children:[a.jsx(Gl,{asChild:!0,"aria-label":t?"Hide capability details":"Show capability details",children:a.jsxs("button",{type:"button","data-testid":"agent-capabilities-footer",className:Z("flex w-full cursor-pointer items-center gap-1.5 px-2 py-2 text-left hover:bg-fill-subtle focus-visible:bg-fill-subtle active:bg-fill aria-expanded:bg-fill-hover data-[panel-open]:bg-fill-hover",Ax,Zn,In),children:[a.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden",children:[a.jsx(Het,{agentId:e,view:"chip"}),a.jsx(Get,{agentId:e,view:"chip"}),a.jsx(Ket,{agentId:e,view:"chip"}),a.jsx(Yet,{agentId:e,view:"chip"}),a.jsx(Xet,{agentId:e,view:"chip"}),a.jsx(Jet,{agentId:e,view:"chip"})]}),a.jsx(dxs,{agentId:e}),a.jsx(Ha,{direction:"right",className:"size-3.5 text-muted-foreground"})]})}),a.jsx(Kl,{className:"px-2 pb-2",children:a.jsxs("div",{className:"grid gap-1",children:[a.jsx(Het,{agentId:e,view:"row"}),a.jsx(Get,{agentId:e,view:"row"}),a.jsx(Ket,{agentId:e,view:"row"}),a.jsx(Yet,{agentId:e,view:"row"}),a.jsx(Xet,{agentId:e,view:"row"}),a.jsx(Jet,{agentId:e,view:"row"})]})})]})})}function hxs(e){let t=e;for(let n=0;n<3&&typeof t=="string";n++)try{const r=JSON.parse(t);if(typeof r=="object"&&r!==null)return r;if(typeof r=="string"&&r!==t){t=r;continue}break}catch{break}return t}function pxs(e){return typeof e=="object"&&e!==null&&"parts"in e&&Array.isArray(e.parts)}function mxs(e){const t=e.type;return t==="data-om-status"||t==="data-om-observation-start"||t==="data-om-observation-end"||t==="data-om-buffering-start"||t==="data-om-buffering-end"||t==="data-om-activation"}function gxs(e,t){switch(e.type){case"data-om-status":return{type:"status",timestamp:t,pendingTokens:e.data.windows?.active?.messages?.tokens,observationTokens:e.data.windows?.active?.observations?.tokens,observationThreshold:e.data.windows?.active?.messages?.threshold,reflectionThreshold:e.data.windows?.active?.observations?.threshold};case"data-om-observation-start":return{type:"observation-start",timestamp:e.data.startedAt,pendingTokens:e.data.tokensToObserve,observationThreshold:e.data.config?.messageTokens,reflectionThreshold:e.data.config?.observationTokens};case"data-om-observation-end":return{type:"observation-end",timestamp:e.data.completedAt,observationTokens:e.data.observationTokens};case"data-om-buffering-start":return{type:"buffering-start",timestamp:e.data.startedAt,pendingTokens:e.data.tokensToBuffer,observationThreshold:e.data.config?.messageTokens,reflectionThreshold:e.data.config?.observationTokens};case"data-om-buffering-end":return{type:"buffering-end",timestamp:e.data.completedAt,observationTokens:e.data.bufferedTokens};case"data-om-activation":return{type:"activation",timestamp:e.data.activatedAt,pendingTokens:e.data.tokensActivated,observationTokens:e.data.observationTokens,observationThreshold:e.data.config?.messageTokens,reflectionThreshold:e.data.config?.observationTokens,generationCount:e.data.generationCount}}}function vxs(e){const t=[];for(const n of e){const r=hxs(n.content);if(pxs(r))for(const s of r.parts)mxs(s)&&t.push(gxs(s,new Date(n.createdAt).toISOString()))}return t.sort((n,r)=>n.timestamp.localeCompare(r.timestamp)),t}function QA(e){return/[Zz+-]\d{0,4}$/.test(e.trim())?new Date(e).getTime():new Date(e.trim().replace(" ","T")+"Z").getTime()}function yxs(e){if(e.length===0)return{tMin:0,tMax:1};let t=1/0,n=-1/0;for(const r of e){const s=QA(r);s<t&&(t=s),s>n&&(n=s)}return t===n?{tMin:t,tMax:t+1}:{tMin:t,tMax:n}}function Rz(e,t){return(QA(e)-t.tMin)/(t.tMax-t.tMin)}function YNe(e,t){return new Date(t.tMin+e*(t.tMax-t.tMin))}function xxs(e,t){return YNe(e,t).getTime()}function jVt(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function bxs(e){return QA(jVt(e))}function wxs(e,t){if(t==null)return null;const r=e.map(s=>({id:s.id,t:QA(jVt(s))})).toSorted((s,i)=>s.t-i.t).findLast(s=>s.t<=t);return r?r.id:null}function ett(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function Sxs(e){return[...e].sort((t,n)=>QA(ett(t))-QA(ett(n)))}function kxs({markers:e,omRecords:t,observationThreshold:n,reflectionThreshold:r}){const s=[...e].filter(o=>o.type==="status"&&(o.pendingTokens!=null||o.observationTokens!=null)).sort((o,l)=>o.timestamp.localeCompare(l.timestamp)).at(-1),i=Sxs(t).at(-1);return{messageTokens:s?.pendingTokens??i?.pendingMessageTokens,messageThreshold:s?.observationThreshold??n,memoryTokens:s?.observationTokens??i?.observationTokenCount,memoryThreshold:s?.reflectionThreshold??r}}function zD(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function Oxs(e,t,n){const r=e.map(i=>({ts:String(zD(i)),pendingMessageTokens:i.pendingMessageTokens})),s=t.flatMap(i=>i.pendingTokens==null?[]:{ts:i.timestamp,pendingMessageTokens:i.pendingTokens});return[...r,...s].sort((i,o)=>i.ts.localeCompare(o.ts)).map(i=>({t:Rz(i.ts,n),pendingMessageTokens:i.pendingMessageTokens}))}function jxs(e,t,n){const r=[...e.map(i=>({ts:String(zD(i)),observationTokenCount:i.observationTokenCount})),...t.flatMap(i=>i.type!=="status"||i.observationTokens==null?[]:{ts:i.timestamp,observationTokenCount:i.observationTokens})].sort((i,o)=>i.ts.localeCompare(o.ts));let s=0;return r.map(i=>(s=Math.max(s,i.observationTokenCount),{t:Rz(i.ts,n),observationTokenCount:s}))}function Cxs(e,t){const n=e.flatMap(s=>s.observationTokens==null||s.type!=="buffering-end"&&s.type!=="activation"?[]:{ts:s.timestamp,bufferedObservationTokenCount:s.type==="activation"?-s.observationTokens:s.observationTokens}).sort((s,i)=>s.ts.localeCompare(i.ts));let r=0;return n.map(s=>(r=Math.max(0,r+s.bufferedObservationTokenCount),{t:Rz(s.ts,t),bufferedObservationTokenCount:r}))}function _xs(e,t){return[...e].sort((n,r)=>String(zD(n)).localeCompare(String(zD(r)))).map(n=>({t:Rz(String(zD(n)),t),event:1}))}function Txs(e,t){return[...e].sort((n,r)=>new Date(n.createdAt).getTime()-new Date(r.createdAt).getTime()).map(n=>({t:Rz(new Date(n.createdAt).toISOString(),t),event:1,role:n.role}))}function Ixs(e,t,n){const r=new Map;for(const c of e)c.t!==void 0&&r.set(c.t,Number(c[t]??0));const s=n.reduce((c,u)=>{const d=c.get(u.t);return d?d.push(u):c.set(u.t,[u]),c},new Map),i=Array.from(new Set([...r.keys(),...s.keys()])).sort((c,u)=>c-u);let o=0;const l=[];for(const c of i){const u=r.get(c);u!=null&&(o=u);const d=s.get(c);if(d)for(const f of d)l.push({...f,t:c,[t]:o});else l.push({t:c,[t]:o})}return l}function Exs(e,t,n){if(n==null)return;const r=Math.max(0,...e.map(s=>Number(s[t])||0));return Math.max(r,n)}function Nxs(e){return e==null?null:Number(e)}function Axs(e){return!!e?.event}const Pxs="var(--chart-green)",$xs="var(--chart-amber)",ttt="var(--chart-pink)";function Rxs({domain:e}){const t=[0,.25,.5,.75,1];return a.jsxs("div",{className:"grid grid-cols-[6rem_1fr] items-center",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"flex items-center self-stretch border-r border-border pl-3",children:"Time"}),a.jsx("div",{className:"flex justify-between px-1 py-1.5",children:t.map(n=>a.jsx(Y,{tone:"muted",as:"span",variant:"meta",font:"mono",children:rs(YNe(n,e),"date-time-seconds",{timeZone:"UTC"})},n))})]})}function XNe({active:e,payload:t,domain:n,showValue:r}){if(!e||!t?.length)return null;const s=t[0]?.payload?.t,i=n!=null&&s!=null?rs(YNe(s,n),"date-time-seconds",{timeZone:"UTC"}):null,o=t.filter(l=>l.name!=="t"&&l.name!=="time"&&l.value!=null);return r?a.jsxs("div",{className:`${th} flex flex-col gap-0.5 rounded px-2 py-1.5 tabular-nums`,children:[i&&a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx(Y,{as:"span",variant:"meta",tone:"muted",children:"time"}),a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"ink",children:i})]}),o.map(l=>a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx(Y,{as:"span",variant:"meta",tone:"muted",children:l.name}),a.jsx(Y,{as:"span",variant:"meta",tone:"ink",children:typeof l.value=="number"?Math.round(l.value).toLocaleString():String(l.value)})]},l.name))]}):a.jsx(Y,{as:"p",variant:"meta",className:`${th} rounded px-2 py-1`,children:i&&a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"ink",children:i})})}function Mxs({label:e,data:t,dataKey:n,color:r,gradientId:s,domain:i,zoomDomain:o,threshold:l}){const c=Exs(t,n,l);return a.jsxs("div",{className:"relative grid grid-cols-[6rem_1fr] items-center border-b border-border hover:z-10",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"flex items-center self-stretch border-r border-border pl-3",children:e}),a.jsx("div",{children:a.jsx(hA,{width:"100%",height:32,children:a.jsxs(MMr,{data:t,margin:{top:0,right:0,bottom:0,left:0},children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:s,x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"0%",stopColor:r,stopOpacity:.35}),a.jsx("stop",{offset:"100%",stopColor:r,stopOpacity:.03})]})}),a.jsx(E6,{dataKey:"t",type:"number",domain:o,allowDataOverflow:!0,hide:!0}),a.jsx(N6,{type:"number",domain:c!=null?[0,c]:void 0,hide:!0}),a.jsx(j6,{content:a.jsx(XNe,{domain:i,showValue:!0}),cursor:{stroke:"var(--border)"}}),a.jsx(HY,{type:"linear",dataKey:n,stroke:r,strokeWidth:1,fill:`url(#${s})`,isAnimationActive:!1}),l!=null&&a.jsx(ZY,{y:l,stroke:"var(--border-strong)",strokeDasharray:"4 3"})]})})})]})}function Dxs({label:e,data:t,color:n,height:r=32,domain:s,zoomDomain:i}){return a.jsxs("div",{className:"relative grid grid-cols-[6rem_1fr] items-center border-b border-border hover:z-10",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"flex items-center self-stretch border-r border-border pl-3",children:e}),a.jsx("div",{children:a.jsx(hA,{width:"100%",height:r,children:a.jsxs($Mr,{margin:{top:0,right:0,bottom:0,left:0},children:[a.jsx(E6,{dataKey:"t",type:"number",domain:i,allowDataOverflow:!0,hide:!0}),a.jsx(N6,{dataKey:"event",type:"number",domain:[0,2],hide:!0}),a.jsx(j6,{content:a.jsx(XNe,{domain:s}),cursor:!1}),a.jsx(eAt,{data:t,fill:n,isAnimationActive:!1,shape:o=>{const l=o.cx;return a.jsxs("g",{children:[a.jsx("rect",{x:l-6,y:0,width:12,height:r,fill:"transparent"}),a.jsx("rect",{x:l-1.5,y:0,width:3,height:r,fill:n})]})}})]})})})]})}function ntt({label:e,areaData:t,areaDataKey:n,eventData:r,color:s,gradientId:i,domain:o,zoomDomain:l,threshold:c,height:u=44,onSelectT:d}){const f=Ixs(t,n,r);return a.jsxs("div",{className:"relative grid grid-cols-[6rem_1fr] items-center border-b border-border hover:z-10",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"flex items-center self-stretch border-r border-border pl-3",children:e}),a.jsx("div",{children:a.jsx(hA,{width:"100%",height:u,children:a.jsxs(bCe,{margin:{top:0,right:0,bottom:0,left:0},onClick:h=>{const p=Nxs(h?.activeLabel);p!=null&&d&&d(p)},className:d?"cursor-pointer":void 0,children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:i,x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"0%",stopColor:s,stopOpacity:.35}),a.jsx("stop",{offset:"100%",stopColor:s,stopOpacity:.06})]})}),a.jsx(E6,{dataKey:"t",type:"number",domain:l,allowDataOverflow:!0,hide:!0}),a.jsx(N6,{yAxisId:"area",dataKey:n,type:"number",hide:!0,domain:[0,"dataMax"]}),a.jsx(j6,{content:a.jsx(XNe,{domain:o,showValue:!0}),cursor:!1}),a.jsx(HY,{yAxisId:"area",data:f,type:"linear",dataKey:n,stroke:s,strokeWidth:1,fill:`url(#${i})`,isAnimationActive:!1,activeDot:{r:5,stroke:s,strokeWidth:2,fill:"var(--background)"},dot:h=>Axs(h.payload)?a.jsx("circle",{cx:h.cx,cy:h.cy,r:4,fill:s}):a.jsx(a.Fragment,{})}),c!=null&&a.jsx(ZY,{yAxisId:"area",y:c,stroke:"var(--border-strong)",strokeDasharray:"4 3"})]})})})]})}function Lxs({tDomain:e,zoomLeft:t,zoomRight:n,onZoomLeftChange:r,onZoomRightChange:s,onReset:i}){const o=g.useRef(null),l=g.useRef(null),c=e.tMax-e.tMin,u=c>0?(t-e.tMin)/c*100:0,d=c>0?(n-e.tMin)/c*100:100,f=g.useCallback(h=>{const p=o.current;if(!p)return null;const m=p.getBoundingClientRect(),v=Math.max(0,Math.min(1,(h-m.left)/m.width));return e.tMin+v*(e.tMax-e.tMin)},[e.tMin,e.tMax]);return g.useEffect(()=>{const h=m=>{if(!l.current)return;const v=f(m.clientX);v!=null&&(l.current==="left"?r(Math.min(v,n)):s(Math.max(v,t)))},p=()=>{l.current=null};return window.addEventListener("mousemove",h),window.addEventListener("mouseup",p),()=>{window.removeEventListener("mousemove",h),window.removeEventListener("mouseup",p)}},[f,t,n,r,s]),a.jsxs("div",{className:"grid grid-cols-[6rem_1fr] items-center border-b border-border",children:[a.jsxs("div",{className:"flex items-center gap-1 self-stretch border-r border-border pl-3",children:[a.jsx(Y,{variant:"meta",tone:"muted",children:"Zoom"}),a.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":"Reset zoom",onClick:i,children:a.jsx(E_,{className:"size-3"})})]}),a.jsxs("div",{ref:o,"data-zoom-track":"",className:"relative h-6 cursor-pointer select-none",onMouseDown:h=>{const p=f(h.clientX);if(p==null)return;h.preventDefault();const m=Math.abs(p-t),v=Math.abs(p-n);m<=v?(r(Math.min(p,n)),l.current="left"):(s(Math.max(p,t)),l.current="right")},children:[a.jsx("div",{"data-zoom-part":"before",className:"absolute inset-y-0 left-0 bg-background/60",style:{width:`${u}%`}}),a.jsx("div",{"data-zoom-part":"band",className:"absolute inset-y-0 border-y border-surface-rim bg-fill-subtle",style:{left:`${u}%`,right:`${100-d}%`}}),a.jsx("div",{"data-zoom-part":"after",className:"absolute inset-y-0 right-0 bg-background/60",style:{width:`${100-d}%`}}),a.jsx("div",{"data-zoom-handle":"left",className:"absolute inset-y-0 w-1 cursor-col-resize bg-foreground/50 hover:bg-foreground",style:{left:`${u}%`,transform:"translateX(-50%)"},onMouseDown:h=>{h.preventDefault(),h.stopPropagation(),l.current="left"}}),a.jsx("div",{"data-zoom-handle":"right",className:"absolute inset-y-0 w-1 cursor-col-resize bg-foreground/50 hover:bg-foreground",style:{left:`${d}%`,transform:"translateX(-50%)"},onMouseDown:h=>{h.preventDefault(),h.stopPropagation(),l.current="right"}})]})]})}const zxs={tMin:0,tMax:1};function Fxs({omRecords:e,markers:t,messages:n,tDomain:r,observationThreshold:s,reflectionThreshold:i,onSelectTimestamp:o,zoomRange:l,onZoomRangeChange:c}){const u=r??zxs,d=g.useCallback(Q=>{o?.(xxs(Q,u))},[o,u]),f=l!=null&&c!=null,[h,p]=g.useState(u.tMin),[m,v]=g.useState(u.tMax);g.useEffect(()=>{f||(p(u.tMin),v(u.tMax))},[u.tMin,u.tMax,f]);const y=f?l.left:h,x=f?l.right:m,b=g.useCallback(Q=>{f?c({left:Q,right:x}):p(Q)},[f,c,x]),S=g.useCallback(Q=>{f?c({left:y,right:Q}):v(Q)},[f,c,y]),k=g.useCallback(()=>{f?c({left:u.tMin,right:u.tMax}):(p(u.tMin),v(u.tMax))},[f,c,u.tMin,u.tMax]),j=u.tMax-u.tMin,C=j>0?(y-u.tMin)/j:0,T=j>0?(x-u.tMin)/j:1,_=[C,T],N=g.useMemo(()=>Txs(n,u),[n,u]),E=g.useMemo(()=>Oxs(e,t,u),[e,t,u]),A=g.useMemo(()=>jxs(e,t,u),[e,t,u]),P=g.useMemo(()=>Cxs(t,u),[t,u]),L=g.useMemo(()=>_xs(e,u),[e,u]);return N.length>0||E.length>0||A.length>0||L.length>0?a.jsxs("div",{className:"flex flex-col pr-2 pb-2 [&_.recharts-surface]:outline-none",children:[a.jsx(ntt,{label:"Messages",areaData:E,areaDataKey:"pendingMessageTokens",eventData:N,color:Pxs,gradientId:"grad-messages",domain:u,zoomDomain:_,threshold:s,onSelectT:o?d:void 0}),a.jsx(ntt,{label:"Observations",areaData:A,areaDataKey:"observationTokenCount",eventData:L,color:$xs,gradientId:"grad-observations",domain:u,zoomDomain:_,threshold:i,onSelectT:o?d:void 0}),P.length>0&&a.jsx(Mxs,{label:"Buffered obs",data:P,dataKey:"bufferedObservationTokenCount",color:ttt,gradientId:"grad-buffered-obs",domain:u,zoomDomain:_,threshold:i}),L.length>0&&a.jsx(Dxs,{label:"Events",data:L,color:ttt,domain:u,zoomDomain:_}),a.jsx(Rxs,{domain:u}),a.jsx(Lxs,{tDomain:u,zoomLeft:y,zoomRight:x,onZoomLeftChange:b,onZoomRightChange:S,onReset:k})]}):null}const Bxs=g.lazy(()=>Ai(async()=>{const{CodeDiff:e}=await import("./CodeDiff.es-5hTLX2Rv.js");return{CodeDiff:e}},__vite__mapDeps([9,4,1,3]),import.meta.url).then(({CodeDiff:e})=>({default:e})));function Vxs(e){if(!e)return null;const t=e.match(/^(\d{1,2}):(\d{2})$/);if(!t)return e;const[,n,r]=t;return rs(new Date(2e3,0,1,Number(n),Number(r)),"time")??e}function Uxs(e,t){if(t)return{card:"bg-transparent border-transparent",text:"text-muted-foreground",time:"text-muted-foreground"};if(!e)return{card:"border-border bg-background",text:"text-foreground",time:"text-muted-foreground"};const n=Yve[e];return{card:n.card,text:"text-foreground",time:n.time}}function qxs(e){const t=e.trim();if(!t)return null;if(t.startsWith("* ->")||t.startsWith("->")){const n=t.replace(/^\*?\s*->\s*/,"").trim();return n?{text:n,time:null,priority:null,children:[]}:null}if(t.startsWith("-")){const n=t.replace(/^-\s*/,"").trim();return n?{text:n,time:null,priority:null,children:[]}:null}if(t.startsWith("*")){let n=t.slice(1).trimStart(),r=null;for(const[o,l]of Object.entries(Kve))if(n.startsWith(o)){r=l,n=n.slice(o.length).trimStart();break}let s=null;const i=n.match(/^\((\d{1,2}:\d{2})\)/);if(i){const[o,l]=i;o!==void 0&&l!==void 0&&(s=l,n=n.slice(o.length).trimStart())}if(n)return{text:n,time:s,priority:r,children:[]}}return{text:t,time:null,priority:null,children:[]}}function Qxs(e){const t="<observations>",n=e.indexOf(t),r=n===-1?-1:e.indexOf("</observations>",n+t.length),s=(r===-1?e:e.slice(n+t.length,r)).trim();if(!s)return[];const i=s.split(`
676
676
  `),o=[];let l=null,c=null;for(const u of i){const d=u.trim();if(!d)continue;if(d.startsWith("Date:")){let m=d.slice(5).trim(),v=null;if(m.endsWith(")")){const y=m.lastIndexOf("("),x=y===-1?"":m.slice(y+1,-1);y>0&&x&&!x.includes(")")&&(v=x.trim(),m=m.slice(0,y).trim())}if(m){l={title:m,relativeTime:v,items:[]},o.push(l),c=null;continue}}l||(l={title:"Recent",relativeTime:null,items:[]},o.push(l));const h=(u.match(/^(\s*)/)?.[1]?.length??0)>=2&&(d.startsWith("* ->")||d.startsWith("->")||d.startsWith("-")),p=qxs(u);if(p){if(h&&c){c.children.push(p);continue}l.items.push(p),c=p}}return o}function CVt({items:e,nested:t=!1}){return a.jsx("div",{className:t?"space-y-2 border-l border-border pl-4":"space-y-3",children:e.map((n,r)=>{const s=Uxs(n.priority,t);return a.jsx("div",{className:"space-y-2",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"w-12 shrink-0 pt-2 text-right",children:n.time&&a.jsx(Y,{as:"span",variant:"meta",font:"mono",className:s.time,children:Vxs(n.time)})}),a.jsxs("div",{className:Z("min-w-0 flex-1 rounded-md border px-3 py-2",s.card),children:[a.jsx(Y,{className:Z("break-words whitespace-pre-wrap",s.text),children:n.text}),n.children.length>0&&a.jsx("div",{className:"mt-3",children:a.jsx(CVt,{items:n.children,nested:!0})})]})]})},`${n.text.slice(0,20)}-${r}`)})})}function Zxs({observations:e}){const t=g.useMemo(()=>Qxs(e),[e]);return t.length===0?a.jsx(Y,{variant:"caption",tone:"muted",className:"italic",children:"Initialized"}):a.jsx("div",{className:"space-y-5",children:t.map((n,r)=>a.jsxs("section",{className:"space-y-3",children:[a.jsx("div",{className:"flex items-baseline justify-between gap-3 border-b border-border pb-2",children:a.jsxs("div",{className:"min-w-0",children:[a.jsx(Y,{as:"h3",variant:"column",tone:"ink",children:n.title}),n.relativeTime&&a.jsx(Y,{variant:"meta",tone:"muted",children:n.relativeTime})]})}),a.jsx(CVt,{items:n.items})]},`${n.title}-${r}`))})}function Wxs({records:e,selectedRecordId:t,onSelectRecord:n}){return e.length<=1?null:a.jsxs("div",{className:"flex w-50 min-w-45 flex-col overflow-hidden border-l border-border",children:[a.jsx("div",{className:"border-b border-border px-4 py-2",children:a.jsx(Y,{tone:"ink",children:"History"})}),a.jsx("div",{className:"flex-1 overflow-y-auto",children:e.map(r=>{const s=r.id===t;return a.jsx("button",{type:"button",onClick:()=>n(r.id),className:Z("text-foreground","w-full cursor-pointer truncate border-l-2 border-l-transparent px-3 py-2 text-left hover:bg-fill-subtle",s&&"border-l-foreground bg-fill-hover"),children:a.jsx(Y,{as:"span",variant:"caption",className:"block",children:r.activeObservations||a.jsx("span",{className:"text-muted-foreground italic",children:r.isObserving||r.isReflecting?"Processing…":"Initialized"})})},r.id)})})]})}function Hxs({records:e,selectedRecordId:t,onSelectRecord:n,isLoading:r}){const[s,i]=g.useState(!1),o=g.useMemo(()=>[...e].sort((f,h)=>new Date(f.createdAt).getTime()-new Date(h.createdAt).getTime()),[e]),l=t?o.find(f=>f.id===t):o[o.length-1],c=l?o.findIndex(f=>f.id===l.id):-1,u=c>0?o[c-1]:null;if(g.useEffect(()=>{const f=o.at(-1);!t&&f&&n(f.id)},[t,o,n]),r)return a.jsxs("div",{className:"space-y-4 p-4",children:[a.jsx(bt,{className:"h-6 w-40"}),a.jsx(bt,{className:"h-32 w-full"}),a.jsx(bt,{className:"h-32 w-full"})]});if(!l)return a.jsx(Yt,{titleSlot:"No observations",descriptionSlot:"No observational memory snapshots available for this thread.",variant:"fill"});const d=typeof l.activeObservations=="string"?l.activeObservations:"";return a.jsxs("div",{className:"flex size-full overflow-hidden",children:[a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:[u&&a.jsx("div",{className:"border-b border-border px-4 py-2",children:a.jsx("div",{className:"flex items-start justify-end gap-3",children:a.jsxs(pt,{orientation:"horizontal",className:"gap-1.5",children:[a.jsx(Kc,{checked:s,onCheckedChange:f=>i(f===!0)}),a.jsx(dt,{size:"smaller",children:"Show diff"})]})})}),a.jsx("div",{"data-testid":"observation-detail-body",className:"flex-1 overflow-y-auto p-4",children:s&&u?a.jsx(g.Suspense,{fallback:a.jsx(bt,{className:"h-32"}),children:a.jsx(Bxs,{codeA:typeof u.activeObservations=="string"?u.activeObservations:"",codeB:d,filename:"observations.md",layout:"unified",className:"rounded-xl"})}):d?a.jsx(Zxs,{observations:d}):a.jsx(Y,{variant:"caption",tone:"muted",className:"italic",children:l.isObserving||l.isReflecting?"Processing…":"Initialized"})})]}),a.jsx(Wxs,{records:o,selectedRecordId:l.id,onSelectRecord:n})]})}function rtt(e){if(e===0)return"0";const t=e/1e3,n=t<.1?2:1;return t.toFixed(n).replace(/\.0+$/,"").replace(/(\.\d*[1-9])0$/,"$1")}const Gxs={messages:"text-chart-blue",memory:"text-chart-purple",warning:"text-warning-foreground"};function stt({label:e,value:t,max:n,tone:r}){const s=Math.max(0,Math.min(100,t/n*100));return a.jsxs("div",{className:Z("min-w-0 flex-1",Gxs[r]),children:[a.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[a.jsx(Y,{as:"span",variant:"meta",tone:"ink",className:"uppercase",children:e}),a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",className:"tabular-nums",children:[rtt(t),"/",rtt(n),"k"]})]}),a.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-white/[0.08]",children:a.jsx("div",{className:"h-full rounded-full bg-current/80",style:{width:`${s}%`}})})]})}function Kxs({messageTokens:e,messageThreshold:t,memoryTokens:n,memoryThreshold:r,memoryLabel:s="Memory"}){const i=e!=null&&t!=null&&t>0,o=n!=null&&r!=null&&r>0;return!i&&!o?null:a.jsx("div",{className:"border-b border-border px-3 py-2",children:a.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[i?a.jsx(stt,{label:"Messages",value:e,max:t,tone:"messages"}):null,o?a.jsx(stt,{label:s,value:n,max:r,tone:"memory"}):null]})})}function Yxs({messages:e,omRecords:t,isLoading:n=!1,onClose:r,selectedTimestamp:s,onSelectTimestamp:i,contextWindow:o}){const[l,c]=g.useState(null),u=g.useMemo(()=>vxs(e),[e]),d=g.useMemo(()=>yxs(e.map(j=>new Date(j.createdAt).toISOString())),[e]),f=g.useMemo(()=>kxs({markers:u,omRecords:t}),[u,t]),h=o?.memoryTokens??f.memoryTokens,p=o?.memoryThreshold??f.memoryThreshold,[m,v]=g.useState({left:d.tMin,right:d.tMax});g.useEffect(()=>{v({left:d.tMin,right:d.tMax})},[d.tMin,d.tMax]);const y=m.left<=d.tMin&&m.right>=d.tMax,x=g.useMemo(()=>y?t:t.filter(j=>{const C=bxs(j);return C>=m.left&&C<=m.right}),[t,y,m.left,m.right]),b=g.useMemo(()=>s!=null?wxs(x,s):null,[x,s]),S=l!=null&&x.some(j=>j.id===l)?l:null,k=b??S;return a.jsxs("div",{className:"flex size-full flex-col overflow-hidden",children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2.5",children:[a.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"Back to memory",onClick:()=>r?.(),children:a.jsx(vd,{})}),a.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 text-foreground",children:[a.jsx(d$,{className:"size-4 shrink-0"}),a.jsx(Y,{as:"span",variant:"column",children:"Observational memory"})]})]}),n?a.jsxs("div",{"data-testid":"memory-studio-loading",className:"flex flex-1 flex-col gap-3 p-4",children:[a.jsx(bt,{className:"h-6 w-40"}),a.jsx(bt,{className:"h-32 w-full"}),a.jsx(bt,{className:"h-16 w-full"})]}):a.jsxs("div",{className:"grid min-h-0 flex-1 grid-rows-[1fr_auto] overflow-hidden",children:[a.jsx("div",{className:"flex min-h-0 flex-col overflow-hidden",children:a.jsx(Hxs,{records:x,selectedRecordId:k,onSelectRecord:c,isLoading:n})}),a.jsxs("div",{className:"border-t border-border",children:[a.jsx(Kxs,{messageTokens:o?.messageTokens??f.messageTokens,messageThreshold:o?.messageThreshold??f.messageThreshold,memoryTokens:h,memoryThreshold:p,memoryLabel:"Observations"}),a.jsx(Fxs,{omRecords:t,markers:u,messages:e,tDomain:d,onSelectTimestamp:i,zoomRange:m,onZoomRangeChange:v})]})]})]})}const Xxs=2e3;function Jxs({agentId:e,threadId:t}){const{isPanelOpen:n,closePanel:r,selectedTimestamp:s,setSelectedTimestamp:i}=PX(),{isObservingFromStream:o,isReflectingFromStream:l,observationsUpdatedAt:c,streamProgress:u}=AX(),d=o||l,{data:f}=oTe({threadId:t,agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!t&&t!=="new"&&!!e}}),h=f?.resourceId??e,{data:p}=Zk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:m,isLoading:v,refetch:y}=l4t({agentId:n?e:void 0,threadId:n?t:void 0,resourceId:h}),{data:x,isLoading:b,refetch:S}=gXr({threadId:n?t:void 0});if(g.useEffect(()=>{!n||c===0||(y(),S())},[n,c,y,S]),g.useEffect(()=>{if(!n||!d)return;const T=setInterval(()=>{y(),S()},Xxs);return()=>clearInterval(T)},[n,d,y,S]),!n)return null;const k=p?.config?.observationalMemory,j=u?.threadId===t?u:null,C=mNe({record:m?.record,liveProgress:j,agentConfig:k});return a.jsx("div",{"data-testid":"memory-sidebar-om-detail-subpanel",className:"h-full min-h-0 min-w-0 overflow-hidden bg-card",children:a.jsx(Yxs,{messages:x?.messages??[],omRecords:m?.history??[],isLoading:v||b,onClose:r,selectedTimestamp:s,onSelectTimestamp:i,contextWindow:{messageTokens:C.messageTokens,messageThreshold:C.messageThreshold,memoryTokens:C.observationTokens,memoryThreshold:C.observationThreshold}})})}function ebs(e){const{data:t}=Zk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),n=t?.config;return{recentMessages:P7t(n?.lastMessages,n?.messageHistory),semanticRecallOn:!!n?.semanticRecall,workingMemoryOn:!!n?.workingMemory?.enabled,observationalOn:!!n?.observationalMemory?.enabled}}const itt="agent-memory-sidebar-tab-v2",tbs=()=>{const[e,t]=g.useState(()=>{const r=sessionStorage.getItem(itt)||"threads";return r==="threads"||r==="memory"?r:"threads"}),n=g.useCallback(r=>{t(r),sessionStorage.setItem(itt,r)},[]);return{selectedTab:e,handleTabChange:n}},nbs=e=>e>=85?"bg-warning-indicator":e>=60?"bg-info-indicator":"bg-success-indicator";function F7({icon:e,tooltip:t,enabled:n,value:r}){return a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsxs("span",{className:Z("inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 transition-colors duration-normal",n?"border-border bg-muted text-foreground":"border-border text-muted-foreground/50"),children:[a.jsx(e,{className:"h-3 w-3 shrink-0"}),r!==void 0&&a.jsx(Y,{as:"span",variant:"meta",className:"tabular-nums",children:r})]})}),a.jsx(Bn,{children:t})]})}function rbs(){return a.jsxs("div",{"data-testid":"memory-sidebar-skeleton",className:"flex h-full min-h-0 w-full flex-col gap-2.5 p-3",children:[a.jsx(bt,{className:"h-3 w-28"}),a.jsx(bt,{className:"h-3 w-20"}),a.jsx(bt,{className:"h-3 w-24"}),a.jsx(bt,{className:"h-3 w-16"})]})}function sbs({agentId:e,threadId:t,threads:n,onDelete:r,isThreadsLoading:s}){return a.jsx($Ne,{children:a.jsx(ibs,{agentId:e,threadId:t,threads:n,onDelete:r,isThreadsLoading:s})})}function ibs({agentId:e,threadId:t,threads:n,onDelete:r,threadsSlot:s,isThreadsLoading:i}){const{data:o,isLoading:l}=Qk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),c=!!o?.result,u=o?.memoryType,{selectedTab:d,handleTabChange:f}=tbs(),{isPanelOpen:h}=PX(),{streamProgress:p}=AX(),{recentMessages:m,semanticRecallOn:v,workingMemoryOn:y,observationalOn:x}=ebs(e),b=d==="memory",S=g.useRef(null),k=g.useRef(null),[j,C]=g.useState({height:0,offset:0}),T=x&&h,_=p?.threadId===t?p:null,{data:N}=oTe({threadId:t,agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!t&&t!=="new"&&!!e}}),{data:E}=Zk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:A}=l4t({agentId:x?e:void 0,threadId:x?t:void 0,resourceId:N?.resourceId??e}),P=E?.config?.observationalMemory,{messageTokens:L,messageThreshold:F}=mNe({record:A?.record,liveProgress:_,agentConfig:P}),q=(!!_||!!A?.record)&&F>0?Math.min(100,Math.round(L/F*100)):void 0;return g.useLayoutEffect(()=>{if(b||T||!c)return;const B=S.current,V=k.current;if(!B||!V)return;const W=()=>{const K=getComputedStyle(B),D=Number.parseFloat(K.borderTopWidth)||0,$=Number.parseFloat(K.borderBottomWidth)||0,z=Number.parseFloat(K.marginTop)||0,U=Number.parseFloat(K.marginBottom)||0,G=Math.ceil(V.getBoundingClientRect().height+D+$),ne=Math.ceil(G+z+U);C(X=>X.height===G&&X.offset===ne?X:{height:G,offset:ne})};if(W(),typeof ResizeObserver>"u")return;const M=new ResizeObserver(W);return M.observe(V),()=>M.disconnect()},[c,m.description,q,x,v,b,T,y]),l?a.jsx(rbs,{}):T?a.jsx("div",{"data-testid":"memory-sidebar-panel",className:"h-full min-h-0 min-w-0",children:a.jsx(Jxs,{agentId:e,threadId:t})}):a.jsxs("div",{className:"flex h-full min-h-0 w-full flex-col overflow-hidden",children:[a.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",children:[a.jsx("div",{"aria-hidden":b&&c,inert:b&&c?!0:void 0,"data-testid":"memory-sidebar-thread-layer",className:Z("memory-sidebar-thread-layer absolute inset-0 flex min-h-0 flex-col overflow-hidden",b&&c?"pointer-events-none opacity-0":"opacity-100"),children:a.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",style:{paddingBottom:c&&j.offset||void 0},children:s||(c?a.jsx(A7t,{resourceId:e,resourceType:"agent",threads:n??[],threadId:t,onDelete:r??(()=>{}),embedded:!0,isLoading:i},e):a.jsx(Yt,{titleSlot:"Memory not enabled",descriptionSlot:"Conversations are only saved as threads when the agent has memory configured.",actionSlot:a.jsx(ce,{icon:a.jsx(Zs,{}),render:a.jsx("a",{href:"https://mastra.ai/docs/memory/overview",target:"_blank",rel:"noopener noreferrer"}),children:"View documentation"})}))})}),c?a.jsxs("div",{ref:S,"data-testid":"memory-sidebar-overlay",className:Z("memory-sidebar-overlay absolute inset-x-0 bottom-0 z-10 box-border flex min-h-0 flex-col overflow-hidden",b?Z(pr,"top-1 m-1 rounded-xl"):"state-layer m-1 rounded-xl border border-surface-rim bg-muted"),style:{height:b?void 0:j.height||void 0},children:[a.jsxs("button",{ref:k,type:"button",onClick:()=>f(b?"threads":"memory"),"aria-pressed":b,"data-testid":"memory-sidebar-card",className:"group/memory-card w-full shrink-0 cursor-pointer bg-transparent px-3 py-2.5 text-left",children:[a.jsxs("span",{className:"flex items-center justify-between gap-2",children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 text-foreground",children:[a.jsx(d$,{className:"h-4 w-4 shrink-0"}),a.jsx(Y,{as:"span",variant:"column",children:"Memory"})]}),b?a.jsx(fc,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):a.jsx(YH,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]}),b?null:a.jsx(Wc,{delay:150,timeout:400,children:a.jsxs("span",{"data-testid":"memory-config-badges",className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[a.jsx(F7,{icon:hL,tooltip:m.description,enabled:m.enabled,value:m.maxMessages}),a.jsx(F7,{icon:wu,tooltip:v?"Semantic recall is on - retrieves relevant past messages":"Semantic recall is off",enabled:v}),a.jsx(F7,{icon:REn,tooltip:y?"Working memory is on - persists notes across the conversation":"Working memory is off",enabled:y}),a.jsx(F7,{icon:Fa,tooltip:x?"Observational memory is on - learns from the conversation":"Observational memory is off",enabled:x})]})}),q!==void 0?a.jsx("span",{"data-testid":"memory-card-observation-bar","data-percent":q,className:"mt-2 block h-1 w-full overflow-hidden rounded-full bg-fill",children:a.jsx("span",{className:Z("block h-full rounded-full transition-all duration-normal",nbs(q)),style:{width:`${q}%`}})}):null]}),b&&a.jsx("div",{className:"memory-card-content min-h-0 flex-1 overflow-y-auto border-t border-border",children:a.jsx(cps,{agentId:e,threadId:t,memoryType:u})})]}):null]}),a.jsx(fxs,{agentId:e})]})}function obs({agentId:e,threadId:t}){const n=xr("agent",e)[0],{mutateAsync:r}=vXr(n),{paths:s,navigate:i}=Sn(),{data:o}=Qk({agentId:e,requestContext:n,queryOptions:{enabled:!!e}}),l=!!o?.result,{data:c,isLoading:u}=aTe({agentId:e,isMemoryEnabled:l,resourceId:e,requestContext:n,queryOptions:{enabled:l}}),d=(c??[]).map(h=>({...h,createdAt:new Date(h.createdAt),updatedAt:new Date(h.updatedAt)})),f=async h=>{try{await r({threadId:h,agentId:e})}catch{Xe.error("Failed to delete chat");return}Xe.success("Chat deleted successfully"),h===t&&i(s.agentNewThreadLink(e))};return a.jsx(sbs,{agentId:e,threadId:t,threads:d,onDelete:f,isThreadsLoading:u})}const abs=()=>{const e=$X();return G0({"{":()=>e?.toggle()}),null},Rd=e=>e.nullable().transform(t=>t??void 0).optional(),ott=Rn({frequencyPenalty:Rd(ds()),presencePenalty:Rd(ds()),maxRetries:Rd(ds()),maxSteps:Rd(ds()),maxTokens:Rd(ds()),temperature:Rd(ds()),topK:Rd(ds()),topP:Rd(ds()),seed:Rd(ds()),providerOptions:Rd(ji(vt(),ji(vt(),yDn()))),chatWithGenerateLegacy:Rd(Da()),chatWithGenerate:Rd(Da()),chatWithLegacyStream:Rd(Da()),chatWithNetwork:Rd(Da()),requireToolApproval:Rd(Da())}),lbs=Rn({provider:vt(),model:vt()}),_Vt=ji(vt(),ua());function cbs(e){const t=_Vt.safeParse(e);if(!t.success)return;const n={};for(const[r,s]of Object.entries(ott.shape)){if(!Object.hasOwn(t.data,r))continue;const i=s.safeParse(t.data[r]);i.success&&(n[r]=i.data)}return ott.parse(n)}const ubs=_Vt.transform(e=>{const t=lbs.safeParse(e.selection);return{selection:t.success?t.data:void 0,modelSettings:cbs(e.modelSettings)}});function dbs(e){return JSON.stringify({...e,modelSettings:e.modelSettings&&Object.fromEntries(Object.entries(e.modelSettings).map(([t,n])=>[t,n===void 0?null:n]))})}function fbs(e){const t=`mastra-thread-preferences-${JSON.stringify([e.agentId,e.threadId])}`;return a.jsx(hbs,{...e,storageKey:t},t)}function hbs({children:e,defaultProvider:t,defaultModel:n,defaultSettings:r,storageKey:s}){const[i,o]=Tk({initialKey:s,defaultValue:{},schema:ubs,serialize:dbs}),{data:l,isError:c}=K0(),u=l?.modelPolicy,{models:d,isLoading:f,isError:h}=fw({enabled:u?.active===!0}),p=u?.active&&u.allowed!==void 0,m=!!l&&!c&&!(p&&(f||h)),v=i.selection,y=!u?.active||u.allowed===void 0||d.some(E=>io(E.provider)===io(v?.provider??"")&&(!v?.model||E.model===v.model)),x=u?.active&&u.pickerVisible===!1,b=m&&!x&&y?v:void 0,k=!c&&u?.active&&(x||m&&v&&!y)?u?.default:void 0,j=c||p&&h&&!x?"Unable to verify model policy. Using the agent default until policy data is available. Your saved model is unchanged.":void 0,C=b?.provider??k?.provider??t,T=b?.model??k?.modelId??n,_=(b||k)&&C&&T?`${C}/${T}`:void 0,N={modelSettings:{...Pve.modelSettings,...r?.modelSettings,...i.modelSettings}};return a.jsx(yTe.Provider,{value:{provider:C,model:T,modelOverride:_,modelWarning:j,setProvider:E=>o(A=>({...A,selection:{provider:E,model:""}})),setModel:(E,A)=>o(P=>({...P,selection:{provider:E,model:A}}))},children:a.jsx(cTe.Provider,{value:{settings:N,setSettings:E=>o(A=>({...A,modelSettings:E.modelSettings})),resetAll:()=>o(E=>({...E,modelSettings:void 0}))},children:e})})}const pbs=6;function mbs(e){const t=e?.suggestedPrompts;if(!Array.isArray(t))return[];const n=[],r=new Set;for(const s of t){if(typeof s!="string")continue;const i=s.trim();if(!(!i||r.has(i))&&(n.push(i),r.add(i),n.length===pbs))break}return n}function gbs(){const{agentId:e,threadId:t}=Cr(),n=Ke(),{data:r,error:s}=Zl(),i=r&&bp(r),o=i?r.user.id:void 0,l=r?.enabled===!1||!!i,c=[n.options.baseUrl,n.options.apiPrefix,o,e],u=JSON.stringify([...c,t??"new"]),[d]=wi(),{data:f,isLoading:h,error:p}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:m,isLoading:v}=Qk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),y=Lr(),x=$X(),b=g.useRef(null),S=t==="new",k=g.useMemo(()=>ka(),[t]),j=JSON.stringify([...c,k]),C=g.useRef(void 0);g.useLayoutEffect(()=>(C.current=S?j:void 0,()=>{C.current=void 0}),[S,j]);const T=!!m?.result,{data:_,isLoading:N,refetch:E}=aTe({agentId:e,isMemoryEnabled:T,resourceId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!T}}),A=d.get("messageId")??void 0,P=mbs(f?.metadata),L=g.useMemo(()=>RNe(f),[f]);if(p&&Cs(p))return a.jsx(ci,{variant:"fill"});if(p&&_s(p))return a.jsx(Gs,{variant:"fill",resource:"agents"});if(!r&&s)return a.jsx(Yt,{tone:"error",titleSlot:"Failed to check authentication",descriptionSlot:"Reload the page to try again. Your saved drafts have not been changed."});if(h||!r)return a.jsx(vye,{agentId:e,leftSlot:S&&!v&&!T?void 0:a.jsx(ybs,{agentId:e}),leftDrawerLabel:"Threads",children:S?a.jsx(Mys,{}):a.jsx(xbs,{})});if(p&&Pk(p))return a.jsx(_W,{});if(p)return a.jsx(Yt,{tone:"error",titleSlot:"Failed to load agent",descriptionSlot:p.message});if(!f)return a.jsx(_W,{});const F=S?k:t??k,Q=S&&!T&&(N||!_?.length),q=async()=>{if(S&&C.current===j){const B=b.current;l&&await B?.move(j),C.current===j&&B===b.current&&y(`/agents/${e}/threads/${k}`,{replace:!0})}x?.expandIfAutoCollapsed(),await E()};return a.jsx(fbs,{agentId:e,threadId:F,defaultProvider:io(f.provider??""),defaultModel:f.modelId??"",defaultSettings:L,children:a.jsx(O4t,{agentId:e,threadId:F,resourceId:e,children:a.jsx(CX,{children:a.jsx(_X,{agentId:e,threadId:F,enabled:!!(f?.hasBrowser??f?.browserTools?.length),children:a.jsx(gNe,{ref:b,persistence:l?{key:u,threadId:F}:void 0,children:a.jsx(_4t,{children:a.jsx(UXr,{children:a.jsxs(EX,{children:[a.jsx(abs,{}),a.jsx(vye,{agentId:e,leftSlot:Q?void 0:a.jsx(obs,{agentId:e,threadId:F}),leftDrawerLabel:"Threads",children:a.jsx("div",{className:"relative flex h-full min-h-0 flex-col",children:a.jsx("div",{className:"relative grid min-h-0 flex-1",children:a.jsx(KNe,{agentId:e,agentName:f?.name,modelVersion:f?.modelVersion,supportsMemory:f?.supportsMemory,threadId:F,memory:T,refreshThreadList:q,modelList:f?.modelList,messageId:A,suggestedPrompts:P,isNewThread:S,runOptionsSlot:a.jsx(MNe,{agentId:e})})})},F)})]},`${e}-${F}`)},`memory-timeline-${e}-${F}`)})},`${l}:${JSON.stringify([...c,F])}`)},`session-${e}-${F}`)},`browser-${e}-${F}`)})})}function vbs(){const{agentId:e}=Cr();return a.jsx(ZXr,{children:a.jsx(gbs,{})},e)}const ybs=({agentId:e})=>a.jsx($Ne,{children:a.jsx(A7t,{threads:[],threadId:"",onDelete:()=>{},resourceId:e,resourceType:"agent",embedded:!0,isLoading:!0})}),xbs=()=>a.jsx("div",{className:"relative grid h-full overflow-y-auto pt-4","data-testid":"agent-thread-skeleton","aria-busy":"true",children:a.jsx(bVt,{})}),TVt=()=>{const{data:e}=DP();return e?.editorSource==="code"?"code":"db"},Mz=()=>{const e=window.MASTRA_CLOUD_API_ENDPOINT,t=window.MASTRA_PLATFORM_PROJECT_ID,n=window.MASTRA_ORGANIZATION_ID,r=window.MASTRA_PLATFORM_OBSERVABILITY_ENDPOINT;return{isMastraPlatform:!!e,mastraPlatformEndpoint:e,mastraPlatformApiEndpoint:e,mastraPlatformProjectId:t,mastraOrganizationId:n,platformObservabilityEndpoint:r}};function bbs(){const{agentId:e}=Cr(),[t,n]=g.useState(null),{data:r,isLoading:s,error:i}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:o}=Qk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),l=TVt(),{isMastraPlatform:c,mastraPlatformApiEndpoint:u,mastraPlatformProjectId:d}=Mz(),{data:f,isLoading:h}=t6({agentId:e,params:{orderBy:{direction:"DESC"}},queryOptions:{enabled:!!e}}),p=(f?.versions?.length??0)>0,{data:m,isLoading:v}=AK({agentId:e,status:"draft",queryOptions:{enabled:!!e&&p}}),y=r?.source==="code",x=y&&l==="code",b=!oT(y,r?.editor).isFullyLocked,S=x&&b,k=S&&c&&!!u&&!!d,j=k?"Open a pull request for these JSON changes":void 0,C=s||h||p&&v,T=!!o?.result,{data:_}=FOt({agentId:e??"",versionId:t??"",queryOptions:{enabled:!!e&&!!t}}),N=m?.activeVersionId,E=f?.versions?.[0],A=!!(E&&E.id!==N),P=!!t&&!!_,L=P&&t!==E?.id,F=g.useMemo(()=>P&&_?_:m||(r?zBt(r):{}),[P,_,m,r]),{form:Q,handlePublish:q,handleSaveDraft:B,handleDownloadJson:V,handleOpenPr:W,isSubmitting:M,isSavingDraft:K,isDirty:D}=PNe({mode:"edit",agentId:e??"",dataSource:F,isCodeAgentOverride:y,hasStoredOverride:y&&!!m,editorConfig:r?.editor,saveSuccessMessage:x?"Saved to filesystem":void 0,onSuccess:()=>{}}),$=g.useCallback(async()=>{L&&t?await q(t):await q()},[q,L,t]),z=g.useCallback(async()=>{!u||!d||await W({platformApiEndpoint:u,projectId:d})},[W,u,d]),U=g.useCallback(G=>{G===E?.id?n(null):n(G)},[E?.id]);return i&&Cs(i)?a.jsx(ci,{variant:"fill"}):i&&_s(i)?a.jsx(Gs,{variant:"fill",resource:"agents"}):C?a.jsx(On,{fill:!0}):i&&Pk(i)?a.jsx("div",{className:"py-4 text-center",children:"Agent not found"}):i?a.jsx(Yt,{tone:"error",titleSlot:"Failed to load agent",descriptionSlot:i.message}):r?a.jsx(I4t,{form:Q,mode:"edit",agentId:e,isSubmitting:M,isSavingDraft:K,handlePublish:q,handleSaveDraft:B,isCodeAgentOverride:y,isCodeSourceAgent:x,readOnly:L||!b,editorConfig:r?.editor,children:a.jsx(gvs,{agentId:e,agentName:r?.name,modelVersion:r?.modelVersion,agentVersionId:t??E?.id,hasMemory:T,activeVersionId:N,selectedVersionId:t??void 0,latestVersionId:E?.id,onVersionSelect:U,isDirty:D,isSavingDraft:K,isPublishing:M,hasDraft:A,readOnly:L||!b,isCodeSourceAgent:x,showCodeModeActions:S,canOpenPr:k,openPrTitle:j,onSaveDraft:B,onPublish:$,onDownloadJson:V,onOpenPr:z,isViewingPreviousVersion:L})}):a.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}const att=/mac|iphone|ipad|ipod/i;function wbs(){if(typeof navigator>"u")return!1;const e=navigator,t=e.userAgentData?.platform||e.platform||"",n=e.userAgent||"";return att.test(t)||att.test(n)}function JNe(){const[e]=g.useState(wbs);return e}function Sbs(e){const t=JNe();return g.useMemo(()=>{const n=e.trim().toUpperCase();return`${t?"⌘":"Ctrl"} ${n}`},[t,e])}const eAe="root",kbs=e=>Array.isArray(e)?{logic:"and",nodes:e}:e,Obs=(e,t)=>t?e.nodes.filter(n=>!qa(n)):e,rue=e=>{const t=[],n=(r,s)=>{for(const i of r)qa(i)?n(i.nodes,i.id):t.push(s?{item:i,groupId:s}:{item:i})};return n(e.nodes,void 0),t},IVt=(e,t)=>{for(const n of e){if(!qa(n))continue;if(n.id===t)return n;const r=IVt(n.nodes,t);if(r)return r}},EVt=(e,t)=>IVt(e.nodes,t),jbs=(e,t)=>{const n=(r,s)=>{for(const i of r){if(!qa(i))continue;if(i.id===t)return s;const o=n(i.nodes,s+1);if(o)return o}return 0};return n(e.nodes,1)},tAe=e=>e.nodes.reduce((t,n)=>t+(qa(n)?tAe(n):1),0),NVt=e=>[e.id,...e.nodes.flatMap(t=>qa(t)?NVt(t):[t.id])],tee=(e,t,n)=>e.map(r=>qa(r)?r.id===t?n(r):{...r,nodes:tee(r.nodes,t,n)}:r),AVt=(e,t)=>e.map(n=>qa(n)?{...n,nodes:AVt(n.nodes,t)}:t(n)),nAe=(e,t)=>e.filter(t).map(n=>qa(n)?{...n,nodes:nAe(n.nodes,t)}:n),ltt=(e,t,n)=>({...e,nodes:AVt(e.nodes,r=>r.id===t?{...r,...n}:r)}),ctt=(e,t)=>({...e,nodes:nAe(e.nodes,n=>n.id!==t)}),PVt=e=>e.flatMap(t=>{if(!qa(t))return[t];const n=PVt(t.nodes);return n.length===0?[]:[{...t,nodes:n}]}),$Vt=e=>({...e,nodes:PVt(e.nodes)}),utt=(e,t,n)=>!t||t===eAe?{...e,nodes:[...e.nodes,n]}:{...e,nodes:tee(e.nodes,t,r=>({...r,nodes:[...r.nodes,n]}))},Cbs=(e,t,n)=>{const r=o=>{const l=n.find(c=>c.id===o);return l?.arity==="many"?l.id:l?.widensTo},s=r(e.operatorId);if(!s||s!==r(t.operatorId)||!n.some(o=>o.id===s))return t;const i=[e.value,t.value].flat().filter(o=>o!=="");return{operatorId:s,value:i.filter((o,l)=>i.indexOf(o)===l)}},_bs=(e,t,n)=>t===eAe?{...e,logic:n}:{...e,nodes:tee(e.nodes,t,r=>({...r,logic:n}))},Tbs=(e,t,n)=>!t||t===eAe?{...e,nodes:[...e.nodes,n]}:{...e,nodes:tee(e.nodes,t,r=>({...r,nodes:[...r.nodes,n]}))},Ibs=(e,t)=>$Vt({...e,nodes:nAe(e.nodes,n=>qa(n)||t.has(n.id))}),$ye=["field","operator","value","remove"],Ebs=[...$ye].reverse(),Nbs=3,rAe="data-filter-bar-scope",sue=e=>e?.closest(`[${rAe}]`)??null,dtt=e=>e?e.operatorId?"operator":"field":"none",RVt=g.createContext(null);function bc(){const e=g.useContext(RVt);if(!e)throw new Error("FilterBar compound components must be rendered inside <FilterBar>.");return e}let ftt=0;function htt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(ftt+=1,`filter-${ftt}`)}function MVt(e){return e?.arity==="many"?[]:""}const rj=(e,t=new Set)=>{for(const n of e)t.add(n.id),qa(n)&&rj(n.nodes,t);return t},DVt=(e,t,n)=>{const r=new Map(t.map(o=>[o.id,o])),s=new Set,i=[];for(const o of e){const l=r.get(o.id);l?(s.add(o.id),i.push(qa(l)&&qa(o)?{...l,nodes:DVt(o.nodes,l.nodes,n)}:l)):n.has(o.id)&&i.push(o)}for(const o of t)s.has(o.id)||i.push(o);return i};function Abs({fields:e,operators:t,value:n,onValueChange:r,createItemId:s,maxDepth:i=Nbs,ariaLabel:o,describeSuggestionsError:l,children:c}){const u=g.useRef(new Map),d=g.useRef(null),f=Array.isArray(n),h=g.useMemo(()=>kbs(n),[n]),p=g.useRef(h);p.current=h;const[m,v]=g.useState(""),[y,x]=g.useState(()=>new Set),[b,S]=g.useState(void 0),[k,j]=g.useState(null),C=g.useCallback(fe=>r(Obs(fe,f)),[r,f]),T=g.useCallback(fe=>e.find(Ie=>Ie.id===fe),[e]),_=g.useCallback(fe=>t.find(Ie=>Ie.id===fe),[t]),N=g.useCallback(fe=>{if(!fe.operators)return t;const Ie=new Set(fe.operators);return t.filter(Ce=>Ie.has(Ce.id))},[t]),E=g.useCallback(fe=>v(fe),[]),[A,P]=g.useState(null),L=g.useRef(A);L.current=A;const[F,Q]=g.useState(null),q=g.useCallback(()=>Q(fe=>fe?{...fe,glint:!1}:null),[]),[B,V]=g.useState(()=>new Set),W=g.useCallback(fe=>{V(Ie=>{if(!Ie.has(fe))return Ie;const Ce=new Set(Ie);return Ce.delete(fe),Ce})},[]),M=g.useCallback(fe=>{const Ie=[...fe];Ie.length!==0&&V(Ce=>new Set([...Ce,...Ie]))},[]),K=g.useRef(h.nodes),{rendered:D,items:$,leaving:z,rootGroupOf:U}=g.useMemo(()=>{const fe=rj(h.nodes);let Ie=B.size===0?h:{...h,nodes:DVt(K.current,h.nodes,B)};F&&!fe.has(F.item.id)&&(Ie=utt(Ie,F.groupId,F.item)),K.current=Ie.nodes;const Ce=rj(Ie.nodes),le=new Set([...B].filter(be=>Ce.has(be)&&!fe.has(be))),ve=new Map;for(const be of Ie.nodes)if(qa(be))for(const{item:$e}of rue({nodes:[be]}))ve.set($e.id,be.id);return{rendered:Ie,items:rue(Ie).map(be=>be.item),leaving:le,rootGroupOf:ve}},[h,F,B]),G=g.useCallback((fe,Ie)=>{if(!s||Ie!==void 0)return;const Ce=s(fe);return p.current.nodes.find(le=>!qa(le)&&le.id===Ce)},[s]),ne=g.useCallback(fe=>s&&b===void 0&&!G(fe,void 0)?s(fe):htt(),[s,b,G]),X=g.useCallback(fe=>{Q(null),P(Ie=>fe?{...fe,id:Ie?.fieldId===fe.fieldId?Ie.id:ne(fe.fieldId),from:dtt(Ie),groupId:b}:null)},[ne,b]),ee=g.useCallback(({fieldId:fe,operatorId:Ie},Ce)=>{const le=L.current?.id??ne(fe),ve=L.current?.groupId??b,be=dtt(L.current);P(null);const $e=G(fe,ve);if($e){const We=T(fe),tt=Cbs($e,{operatorId:Ie,value:Ce},We?N(We):[]),st={...$e,...tt};C(ltt(p.current,$e.id,tt)),Q({item:st,from:be,glint:!0}),E("Filter updated");return}const De={id:le,fieldId:fe,operatorId:Ie,value:Ce};C(utt(p.current,ve,De)),Q({item:De,from:be,glint:!0,groupId:ve}),E("Filter added")},[C,E,ne,b,G,T,N]),re=g.useCallback((fe,Ie)=>{C(ltt(p.current,fe,Ie))},[C]),ue=g.useCallback(fe=>{M([fe]),C(ctt(p.current,fe)),Q(null),E("Filter removed")},[C,E,M]),te=g.useCallback(fe=>{S(Ie=>Ie&&fe.has(Ie)?void 0:Ie)},[]),ie=g.useCallback(fe=>{const Ie=p.current,Ce=EVt(Ie,fe),le=new Set(Ce?NVt(Ce):[fe]);M(le),C(ctt(Ie,fe)),Q(null),P(null),te(le),j(ve=>ve===fe?null:ve),E("Advanced filter removed")},[C,E,M,te]),se=g.useCallback((fe,Ie)=>{const Ce={id:htt(),kind:"group",logic:Ie,nodes:[]};return C(Tbs(p.current,fe,Ce)),Q(null),P(null),S(Ce.id),E(fe?"Nested group added":"Advanced filter added"),Ce.id},[C,E]),ae=g.useCallback((fe,Ie)=>{C(_bs(p.current,fe,Ie)),E(`Conditions joined with ${Ie}`)},[C,E]),he=g.useCallback(fe=>jbs(p.current,fe),[]),ge=g.useCallback(fe=>{if(j(fe),fe!==null)return;const Ie=p.current,Ce=$Vt(Ie),le=rj(Ce.nodes),ve=new Set([...rj(Ie.nodes)].filter(be=>!le.has(be)));ve.size>0&&(M(ve),C(Ce)),P(null),S(void 0)},[C,M]),me=g.useCallback(()=>{d.current?.focus()},[]),ke=g.useCallback(fe=>{S(fe),P(null),fe===void 0&&me()},[me]),Ee=g.useCallback(()=>{const fe=p.current,Ie=Ibs(fe,y),Ce=rj(Ie.nodes),le=new Set([...rj(fe.nodes)].filter(ve=>!Ce.has(ve)));M(le),C(Ie),Q(null),P(null),S(void 0),j(null),E("All filters removed")},[C,E,y,M]),qe=rue(h).some(({item:fe})=>!y.has(fe.id)),Ze=g.useCallback((fe,Ie)=>{x(Ce=>{if(Ce.has(fe)===Ie)return Ce;const le=new Set(Ce);return Ie?le.add(fe):le.delete(fe),le})},[]),Fe=g.useCallback((fe,Ie,Ce)=>{const le=`${fe}:${Ie}`;Ce?u.current.set(le,Ce):u.current.delete(le)},[]),Ae=g.useCallback(fe=>{fe?d.current=fe:d.current?.isConnected||(d.current=null)},[]),Be=g.useRef($);Be.current=$;const je=g.useRef(U);je.current=U;const _e=g.useCallback((fe,Ie,Ce)=>{const le=Be.current,ve=je.current,be=le[fe-Ie],$e=be?[...$ye].map(tt=>u.current.get(`${be.id}:${tt}`)).find(Boolean):null,De=sue(typeof document>"u"?null:document.activeElement)??sue($e)??void 0,We=Ie===-1?Ebs:$ye;for(let tt=fe;tt>=0&&tt<le.length;tt+=Ie){const st=le[tt];if(!st)break;const Ge=[st.id,ve.get(st.id)].filter(Le=>Le!==void 0);for(const Le of Ge)for(const ze of[Ce,...We]){const Se=u.current.get(`${Le}:${ze}`);if(Se&&(De===void 0||sue(Se)===De))return Se.focus(),!0}}return!1},[]),Ue=g.useCallback(fe=>{_e(fe+1,1,"value")||_e(fe-1,-1,"value")||me()},[_e,me]),pe=g.useMemo(()=>({fields:e,operators:t,items:$,expression:D,groupsEnabled:!f,maxDepth:i,draft:A,setDraft:X,commitDraft:ee,lastCommit:F,settleCommit:q,updateItem:re,removeItem:ue,leaving:z,settleRemove:W,clear:Ee,hasRemovableItems:qe,registerNonRemovable:Ze,addGroup:se,removeGroup:ie,setLogic:ae,getGroupDepth:he,openGroupId:k,setOpenGroup:ge,inputTarget:b,openGroupInput:ke,getField:T,getOperator:_,getFieldOperators:N,registerSegment:Fe,registerInput:Ae,focusChip:_e,focusInput:me,focusAfterRemove:Ue,announce:E,announcement:m,ariaLabel:o,describeSuggestionsError:l}),[e,t,$,D,f,i,A,X,ee,F,q,re,ue,z,W,Ee,qe,Ze,se,ie,ae,he,k,ge,b,ke,T,_,N,Fe,Ae,_e,me,Ue,E,m,o,l]);return a.jsx(RVt.Provider,{value:pe,children:c})}function LVt({option:e}){return a.jsxs(a.Fragment,{children:[e.start,a.jsx("span",{className:"min-w-0 truncate",children:e.label??e.value})]})}const zVt=g.forwardRef((e,t)=>a.jsx(AOt,{ref:Du(t),...e}));zVt.displayName="FilterBarOptionItem";function rN({getKey:e,renderOption:t,isSelected:n,isLoading:r,error:s,emptyText:i="No results.","aria-label":o,"aria-multiselectable":l}){const{describeSuggestionsError:c}=bc(),u=!r&&s===void 0,d=Bv();return a.jsxs(a.Fragment,{children:[r&&a.jsxs(nUe,{className:is.empty,children:[a.jsx(On,{size:"sm"}),a.jsx("span",{children:"Loading…"})]}),!r&&s!==void 0&&a.jsx(nUe,{className:is.empty,children:c?.(s)??"Couldn't load values."}),a.jsx($Ot,{className:is.empty,children:u?i:null}),a.jsx("div",{className:Z(is.listScroller,"max-h-[min(var(--spacing-dropdown),60dvh)]",d.containerClassName),...d.getContainerProps({}),children:a.jsx(US,{menu:d,children:a.jsx(COt,{"aria-label":o,"aria-multiselectable":l,className:is.list,children:f=>{const h=n?.(f)??!1;return a.jsxs(zVt,{value:f,"data-selected":h||void 0,className:Z(is.item,"min-w-0"),children:[a.jsx("span",{className:"flex min-w-0 flex-1 items-center gap-1.5 truncate",children:t(f)}),a.jsx("span",{className:is.itemRightSlot,children:a.jsx("span",{className:is.checkContainer,children:n?h&&a.jsx(ur,{className:is.checkIcon}):a.jsx(POt,{children:a.jsx(ur,{className:is.checkIcon})})})})]},e(f))}})})})]})}function sAe(e,t){const n=t.toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return!0;const r=e.toLowerCase();return n.every(s=>r.includes(s))}function iAe(e,t,n){return sAe(n?n(e):String(e),t)}const Pbs=150,$bs=[{value:"true",label:"True"},{value:"false",label:"False"}],FVt=e=>e?.suggestions??(e?.type==="boolean"?$bs:void 0);function Rbs({field:e,operatorId:t,query:n,enabled:r}){const s=FVt(e),i=typeof s=="function"?s:void 0,o=Array.isArray(s)?s:void 0,[l,c]=g.useState([]),[u,d]=g.useState(!1),[f,h]=g.useState(void 0),p=g.useRef(0),m=g.useRef(i);m.current=i;const v=!!i;return g.useEffect(()=>{if(!v||!r){c([]),d(!1),h(void 0);return}const x=++p.current,b=new AbortController;d(!0);const S=setTimeout(()=>{Promise.resolve().then(()=>m.current?.({query:n,operatorId:t,signal:b.signal})??[]).then(k=>{x===p.current&&(c(k),h(void 0),d(!1))}).catch(k=>{x!==p.current||b.signal.aborted||(h(k),d(!1))})},Pbs);return()=>{clearTimeout(S),b.abort()}},[v,r,n,t]),{options:g.useMemo(()=>o?o.filter(x=>sAe(x.label??x.value,n)):l,[o,l,n]),isLoading:!!i&&u,error:f,hasSuggestions:!!s}}const ptt=e=>Array.isArray(e)?e.map(String):[];function BVt({field:e,operator:t,query:n,enabled:r,initialValue:s,setQuery:i,onCommit:o}){const l=t?.arity==="many",[c,u]=g.useState(()=>ptt(s)),d=g.useRef(s);d.current=s,g.useEffect(()=>{u(r?ptt(d.current):[])},[r]);const f=t?.freeText===!0,h=Rbs({field:f?void 0:e,operatorId:t?.id??"",query:n,enabled:r}),p=e?.type,m=(!e?.strict||f)&&p!=="boolean",v=g.useMemo(()=>{if(!l)return h.options;const E=Mbs(c,h.options,h.hasSuggestions,n);return E.length===0?h.options:[...h.options,...E]},[l,c,h.options,h.hasSuggestions,n]),y=g.useCallback(E=>{u(A=>A.includes(E)?A.filter(P=>P!==E):[...A,E])},[]),x=g.useCallback(E=>o(Array.isArray(E)?E.map(A=>Iye(p,A)):Iye(p,E)),[o,p]),b=g.useCallback(E=>{l?y(E.value):x(E.value)},[l,y,x]),S=g.useCallback(()=>c.length===0?!1:(x(c),!0),[c,x]),k=g.useCallback(E=>m&&E.length>0&&(p!=="number"||Number.isFinite(Number(E)))&&(!f||/[\p{L}\p{M}\p{N}]/u.test(E)),[m,f,p]);function j(){const E=n.trim();return k(E)?(u(A=>A.includes(E)?A:[...A,E]),i(""),!0):!1}const C=g.useCallback(()=>{const E=n.trim();return k(E)?(x(l?c.includes(E)?c:[...c,E]:E),!0):!1},[k,n,l,c,x]);function T(){return l?j():C()}function _(){return h.options.length===0?C()||S():S()||C()}function N(E,A){return E.key!=="Enter"?!1:l&&(E.ctrlKey||E.metaKey)?(E.preventDefault(),_()):A===null?(E.preventDefault(),T()):!1}return{isMany:l,selected:c,toggle:y,options:v,isLoading:h.isLoading,error:h.error,hasSuggestions:h.hasSuggestions,hasOptions:h.hasSuggestions||v.length>0,allowFreeText:m,canCommitQuery:k(n.trim()),handleSelect:b,handleKeyDown:N,submitFreeText:T,commitDone:_}}function Mbs(e,t,n,r){const s=new Set(t.map(o=>o.value)),i=o=>!n||sAe(o,r);return e.filter(o=>!s.has(o)&&i(o)).map(o=>({value:o}))}const nee=Z("filter-bar-segment flex max-w-48 min-w-0 items-center gap-1 overflow-hidden px-2 text-label whitespace-nowrap outline-none"),VVt="sm",UVt={autoHighlight:"always",keepHighlight:!0},qVt=Z("filter-bar-chip relative flex max-w-full items-stretch divide-x divide-border overflow-hidden rounded-full py-px",WH,tp[VVt]),sN=Z(nee,"cursor-pointer hover:bg-fill-subtle hover:text-foreground","focus-visible:bg-fill-hover focus-visible:text-foreground data-[popup-open]:bg-fill-hover data-[popup-open]:text-foreground");function ree({field:e,label:t}){const n=e?.icon;return a.jsxs(a.Fragment,{children:[n&&a.jsx(n,{className:"size-[1.1em] shrink-0","aria-hidden":!0}),a.jsx("span",{className:"truncate",children:t??e?.label})]})}const Rye=e=>e?.color?{color:e.color}:void 0,Dbs=(e,t)=>e==="none"?0:e==="field"||t?1:2,TW=(e,t)=>{const n=FVt(t),r=Array.isArray(n)?n:void 0,s=i=>r?.find(o=>o.value===String(i))?.label??String(i);return Array.isArray(e)?e.map(s).join(", "):s(e)},Lbs=(e,t)=>!Array.isArray(e)||e.length<2?TW(e,t):`${TW(e.slice(0,1),t)} +${e.length-1}`,QVt=g.createContext(null),Gk=()=>{const e=g.useContext(QVt);if(!e)throw new Error("FilterBarChip segments must be rendered inside <FilterBarChip>.");return e};function zbs(e){return e instanceof Element&&!!e.closest('[data-slot="filter-bar-editor"]')}function jx({item:e,readOnly:t=!1,removable:n=!0,draft:r=!1,className:s,children:i}){const o=bc(),[l,c]=g.useState(null),u=o.getField(e.fieldId),d=o.getOperator(e.operatorId),f=o.items.findIndex(E=>E.id===e.id),h=g.useRef(null),p=o.leaving.has(e.id),m=!r&&(t||!n),{registerNonRemovable:v,settleRemove:y}=o;g.useEffect(()=>(v(e.id,m),()=>v(e.id,!1)),[v,e.id,m]),g.useEffect(()=>{const E=h.current;if(!p||!E)return;const A=typeof E.getAnimations=="function"?E.getAnimations({subtree:!0}):[];if(A.length===0){y(e.id);return}let P=!1;return Promise.all(A.map(L=>L.finished)).then(()=>{P||y(e.id)}).catch(()=>{}),()=>{P=!0}},[p,e.id,y]);const x=u?o.getFieldOperators(u).length===1:!1,b=[u?.label??e.fieldId,x?"":d?.label??e.operatorId,r?"":TW(e.value,u)].filter(Boolean).join(" "),S=!r&&o.lastCommit?.item.id===e.id?o.lastCommit:null,k=r?o.draft?.from??"none":S?.from??"none",j=Dbs(k,x),C=S?.glint??!1,T=g.useCallback(E=>{if(t||r||p||zbs(E.target))return;const A=Array.from(h.current?.querySelectorAll("[data-filter-bar-segment]")??[]),P=A.findIndex(L=>L===E.target);switch(E.key){case"ArrowRight":{E.preventDefault();const L=A[P+1];L?L.focus():o.focusChip(f+1,1,"field")||o.focusInput();return}case"ArrowLeft":{E.preventDefault();const L=A[P-1];L?L.focus():o.focusChip(f-1,-1,"remove");return}case"Delete":case"Backspace":if(!n)return;E.preventDefault(),o.removeItem(e.id),o.focusAfterRemove(f);return}},[t,r,p,n,o,f,e.id]),_=g.useMemo(()=>({item:e,index:f,field:u,operator:d,openSegment:l,setOpenSegment:c,readOnly:t,draft:r,leaving:p,operatorImplied:x}),[e,f,u,d,l,t,r,p,x]),N=i??a.jsxs(a.Fragment,{children:[a.jsx(GVt,{}),a.jsx(KVt,{}),a.jsx(YVt,{}),n&&a.jsx(XVt,{})]});return a.jsx(QVt.Provider,{value:_,children:a.jsxs("div",{ref:h,role:"group","aria-label":b,"aria-hidden":r||p||void 0,"data-slot":"filter-bar-chip","data-draft":r||void 0,"data-readonly":t||void 0,"data-leaving":p||void 0,"data-shine":C&&!p||void 0,className:Z(qVt,p&&"pointer-events-none",s),style:{"--filter-bar-segments-settled":j,"--filter-bar-chip-shine":u?.color??"currentColor"},onKeyDown:T,onClick:E=>E.stopPropagation(),onAnimationEnd:E=>{E.animationName==="filter-bar-chip-shine"&&o.settleCommit()},children:[t&&a.jsx("span",{className:Z(nee,"pr-0 text-muted-foreground [--filter-bar-segment-padding:0.5rem_0]"),title:"This filter is locked",children:a.jsx(Nu,{className:"size-[1.1em]"})}),N]})})}const ZVt=g.createContext({highlighted:null});function oAe({placeholder:e,icon:t=wu,inputMode:n,onKeyDown:r}){const{highlighted:s}=g.useContext(ZVt);return a.jsxs("div",{className:is.searchContainer,children:[a.jsx(t,{className:is.searchIcon}),a.jsx(Dke,{className:is.searchInput,placeholder:e,inputMode:n,...pp,onKeyDown:i=>r?.(i,s)})]})}function aAe({segment:e,label:t,fullLabel:n=t,ariaLabel:r,items:s,itemToString:i,filter:o,value:l=null,query:c,onQueryChange:u,onSelect:d,onOpen:f,children:h}){const p=bc(),m=Gk(),v=tw(),y=m.openSegment===e,[x,b]=g.useState(null),S=e==="field",k=S?a.jsx(ree,{field:m.field,label:t}):a.jsx("span",{className:"truncate",children:t});return m.readOnly||m.draft||m.leaving?a.jsx("span",{className:Z(nee,S&&"text-foreground"),style:S?Rye(m.field):void 0,title:n,children:k}):a.jsxs(jQ,{items:s,itemToStringLabel:i,itemToStringValue:i,filter:o,value:l,onValueChange:(j,C)=>{C.cancel(),j!==null&&d(j)},inputValue:c,onInputValueChange:(j,C)=>{C.reason==="input-change"&&u(j)},onItemHighlighted:j=>b(j??null),open:y,onOpenChange:j=>{j?f?.():u(""),m.setOpenSegment(j?e:null)},...UVt,modal:!1,children:[a.jsx(jOt,{ref:j=>p.registerSegment(m.item.id,e,j),render:a.jsx("button",{type:"button","data-filter-bar-segment":"",tabIndex:e==="value"?0:-1,"aria-label":`${r}: ${n}`,title:n,className:Z(sN,S&&"text-foreground"),style:S?Rye(m.field):void 0}),children:k}),a.jsx(Lke,{container:v,children:a.jsx(zke,{align:"start",sideOffset:D_,positionMethod:Av,className:is.positioner,children:a.jsx(Fke,{className:Z(is.popup,"min-w-44"),"data-slot":"filter-bar-editor",children:a.jsx(ZVt.Provider,{value:{highlighted:x},children:h})})})})]})}const Fbs=e=>e.label,Bbs=e=>e.label,Vbs=e=>e.label??e.value;function Ubs(){const e=bc(),t=Gk(),[n,r]=g.useState(""),s=g.useCallback(i=>{const o=e.getFieldOperators(i),l=o.find(u=>u.id===t.item.operatorId)??o[0],c=l?.arity!==t.operator?.arity;e.updateItem(t.item.id,{fieldId:i.id,operatorId:l?.id??t.item.operatorId,value:c||i.id!==t.item.fieldId?MVt(l):t.item.value}),t.setOpenSegment(null)},[e,t]);return a.jsxs(aAe,{segment:"field",ariaLabel:"Field",label:t.field?.label??t.item.fieldId,items:e.fields,itemToString:Fbs,filter:iAe,value:t.field,query:n,onQueryChange:r,onSelect:s,children:[a.jsx(oAe,{placeholder:"Change field…"}),a.jsx(rN,{"aria-label":"Fields",getKey:i=>i.id,renderOption:i=>a.jsx(ree,{field:i}),emptyText:"No matching field."})]})}function qbs(){const e=bc(),t=Gk(),[n,r]=g.useState(""),s=g.useMemo(()=>t.field?e.getFieldOperators(t.field):e.operators,[e,t.field]),i=g.useCallback(o=>{const l=(o.arity??"one")!==(t.operator?.arity??"one");e.updateItem(t.item.id,{operatorId:o.id,value:l?MVt(o):t.item.value}),t.setOpenSegment(null)},[e,t]);return a.jsxs(aAe,{segment:"operator",ariaLabel:"Operator",label:t.operator?.label??t.item.operatorId,items:s,itemToString:Bbs,filter:iAe,value:t.operator,query:n,onQueryChange:r,onSelect:i,children:[a.jsx(oAe,{placeholder:"Change operator…"}),a.jsx(rN,{"aria-label":"Operators",getKey:o=>o.id,renderOption:o=>o.label,emptyText:"No matching operator."})]})}function Qbs(){const e=bc(),t=Gk(),n=t.openSegment==="value",[r,s]=g.useState(""),i=g.useCallback(()=>t.setOpenSegment(null),[t]),o=g.useCallback(u=>{e.updateItem(t.item.id,{value:u}),i()},[e,t.item.id,i]),l=BVt({field:t.field,operator:t.operator,query:r,enabled:n,initialValue:t.item.value,setQuery:s,onCommit:o}),c=Kbs[t.field?.type??"text"];return a.jsx(aAe,{segment:"value",ariaLabel:"Value",label:Lbs(t.item.value,t.field)||"…",fullLabel:TW(t.item.value,t.field)||"…",items:l.options,itemToString:Vbs,filter:null,query:r,onQueryChange:s,onSelect:l.handleSelect,onOpen:()=>s(!Array.isArray(t.item.value)&&!t.field?.suggestions?String(t.item.value):""),children:a.jsx(c,{step:l,onCancel:i})})}function WVt({step:e,onCancel:t}){const n=Gk(),r=JNe()?"⌘↵":"Ctrl ↵";return a.jsxs(a.Fragment,{children:[e.hasOptions&&a.jsx(rN,{"aria-label":"Values","aria-multiselectable":e.isMany||void 0,getKey:s=>s.value,renderOption:s=>a.jsx(LVt,{option:s}),isSelected:s=>e.isMany?e.selected.includes(s.value):String(n.item.value)===s.value,isLoading:e.isLoading,error:e.error,emptyText:e.allowFreeText?"No suggestions — press Enter to use your text.":"No matching value."}),e.isMany&&a.jsxs("div",{className:"flex items-center justify-end gap-1 border-t border-border p-1",children:[a.jsx(ce,{size:"sm",variant:"ghost",onClick:t,children:"Cancel"}),a.jsxs(ce,{size:"sm",variant:"default",onClick:()=>e.commitDone(),children:["Done",a.jsx(Hd,{size:"xs",children:r})]})]})]})}function Zbs(e,t){return e.hasSuggestions?e.allowFreeText?`Search or type a ${t}…`:`Search ${t}s…`:`Type a ${t}…`}function HVt({step:e,onCancel:t,inputMode:n,noun:r}){return a.jsxs(a.Fragment,{children:[a.jsx(oAe,{icon:e.hasSuggestions?wu:Vc,inputMode:n,placeholder:Zbs(e,r),onKeyDown:(s,i)=>{const o=e.hasSuggestions?i:null;(e.handleKeyDown(s,o)||s.key==="Enter"&&o===null)&&s.preventBaseUIHandler()}}),a.jsx(WVt,{step:e,onCancel:t})]})}function Wbs(e){return a.jsx(HVt,{...e,noun:"value"})}function Hbs(e){return a.jsx(HVt,{...e,inputMode:"decimal",noun:"number"})}function Gbs(e){return a.jsx(WVt,{...e})}const Kbs={text:Wbs,number:Hbs,boolean:Gbs};function GVt(){return a.jsx(Ubs,{})}function KVt(){const e=Gk();return e.operatorImplied||e.draft&&!e.operator?null:a.jsx(qbs,{})}function YVt(){const e=Gk();return e.draft||(e.operator?.arity??"one")==="none"?null:a.jsx(Qbs,{})}function XVt(){const e=bc(),t=Gk();if(t.readOnly||t.draft)return null;const n=Z(sN,"px-1.5 text-muted-foreground [--filter-bar-segment-padding:0.375rem]");if(t.leaving)return a.jsx("span",{className:n,children:a.jsx(Mn,{className:"size-[1.1em]"})});const r=`Remove ${t.field?.label??t.item.fieldId} filter`;return a.jsx("button",{type:"button","data-filter-bar-segment":"",tabIndex:-1,"aria-label":r,title:r,ref:s=>e.registerSegment(t.item.id,"remove",s),className:n,onClick:()=>{e.removeItem(t.item.id),e.focusAfterRemove(t.index)},children:a.jsx(Mn,{className:"size-[1.1em]"})})}jx.Field=GVt;jx.Operator=KVt;jx.Value=YVt;jx.Remove=XVt;const Ybs=e=>"label"in e&&e.label?e.label:"value"in e?e.value:"",Xbs=[],JVt="__filter-bar-advanced__",Jbs={id:JVt,label:"Advanced filter…",icon:Va,operators:[]};function eUt(e){return bc().inputTarget!==e.groupId?null:a.jsx(e0s,{...e})}function e0s({placeholder:e="Filter…",className:t,"aria-label":n="Add filter",groupId:r,onLeave:s}){const i=bc(),o=tw(),l=g.useRef(null),[c,u]=g.useState(!1),[d,f]=g.useState(""),[h,p]=g.useState(null),[m,v]=g.useState(!1),y=JNe()?"⌘↵":"Ctrl ↵",{draft:x,setDraft:b,commitDraft:S}=i,k=x?x.operatorId?"value":"operator":"field",j=x?i.getField(x.fieldId):void 0,C=x?.operatorId?i.getOperator(x.operatorId):void 0,T=g.useMemo(()=>j?i.getFieldOperators(j):[],[i,j]),_=i.groupsEnabled&&r===void 0,N=g.useMemo(()=>{const X=i.fields.filter(ee=>!ee.hidden);return _?[...X,Jbs]:X},[i.fields,_]),E=r?EVt(i.expression,r):void 0;g.useEffect(()=>{r&&l.current?.focus()},[r]);const A=g.useCallback(X=>{So.flushSync(()=>v(!0)),X(),v(!1)},[]),P=g.useCallback(X=>A(()=>b(X)),[A,b]),L=g.useCallback(()=>{b(null),f("")},[b]),F=g.useCallback(()=>{u(!1),L()},[L]),Q=g.useCallback((X,ee,re)=>{A(()=>S({fieldId:X,operatorId:ee},re)),f(""),l.current?.focus()},[A,S]),q=g.useCallback((X,ee)=>{if(ee.arity==="none"){Q(X,ee.id,"");return}P({fieldId:X,operatorId:ee.id}),f("")},[Q,P]),B=g.useCallback(X=>{if(X.id===JVt){const ue=i.addGroup(void 0,"or");i.setOpenGroup(ue),i.openGroupInput(ue),f(""),u(!1);return}const[ee,...re]=i.getFieldOperators(X);if(X.search&&ee&&d.trim()!==""){Q(X.id,ee.id,Iye(X.type,d));return}if(ee&&re.length===0){q(X.id,ee);return}P({fieldId:X.id}),f("")},[i,Q,d,q,P]),V=BVt({field:j,operator:C,query:d,enabled:c&&k==="value",setQuery:f,onCommit:X=>{x?.operatorId&&Q(x.fieldId,x.operatorId,X)}}),W=g.useCallback(()=>r?(i.openGroupInput(void 0),s?.(),!0):!1,[i,r,s]),M=g.useCallback(()=>{if(k==="value"&&x){const X=j?T.length===1:!1;P(X?null:{fieldId:x.fieldId})}else k==="operator"?P(null):W()||u(!1);f("")},[k,x,j,T,P,W]),K=X=>{k==="field"?B(X):k==="operator"&&x?q(x.fieldId,X):V.handleSelect(X)},D=X=>{if(X.key==="Escape"){X.preventDefault(),X.stopPropagation(),X.preventBaseUIHandler(),M();return}if(!c&&(X.key==="ArrowDown"||X.key==="Enter")){X.preventDefault(),X.preventBaseUIHandler(),u(!0);return}if(d===""){if(X.key==="Backspace"){if(X.preventDefault(),X.preventBaseUIHandler(),k!=="field")M();else if(E){const ee=E.nodes.findLast(re=>!i.leaving.has(re.id));ee?i.removeItem(ee.id):W()}else{const ee=i.items.findLast(re=>!i.leaving.has(re.id));ee&&i.removeItem(ee.id)}return}if(X.key==="ArrowLeft"&&k==="field"){i.focusChip(i.items.length-1,-1,"remove")&&X.preventDefault();return}}if(c){if(X.key==="Tab"&&h&&k!=="value"&&(k==="operator"||d!=="")){X.preventDefault(),X.preventBaseUIHandler(),K(h);return}if(k==="value"){const ee=V.hasSuggestions?h:null;(V.handleKeyDown(X,ee)||X.key==="Enter"&&ee===null)&&X.preventBaseUIHandler()}}},$={field:N,operator:T,value:V.options},z=m?Xbs:$[k],U=g.useCallback((X,ee,re)=>"search"in X&&X.search===!0||iAe(X,ee,re),[]),G=k==="field"?"Search fields…":k==="operator"?"Search operators…":"Search values…",ne=k==="field"?e:k==="operator"?"Operator…":V.hasSuggestions&&V.allowFreeText?"Search or type a value…":j?.type==="number"?"Number…":"Value…";return a.jsx(a.Fragment,{children:a.jsxs(jQ,{items:z,itemToStringLabel:Ybs,filter:k==="value"?null:U,value:null,onValueChange:(X,ee)=>{ee.cancel(),X&&K(X)},inputValue:d,onInputValueChange:(X,ee)=>{ee.reason==="input-change"&&(f(X),c||u(!0))},onItemHighlighted:X=>p(X??null),open:c,onOpenChange:(X,ee)=>{!X&&ee.reason==="escape-key"||!X&&ee.reason==="outside-press"&&ee.event.target instanceof Node&&l.current?.contains(ee.event.target)||(X?u(!0):F())},...UVt,modal:!1,children:[a.jsxs("div",{"data-slot":"filter-bar-input-trigger",className:Z(ROt({variant:"default",size:VVt}),"w-auto cursor-text","focus-within:bg-fill-hover",SCn,k==="field"?"min-w-40":"min-w-28",t),children:[a.jsx(fpt,{"aria-hidden":!0,className:"-ml-[.3em] shrink-0 text-muted-foreground"}),a.jsx(Dke,{ref:X=>{l.current=X,i.registerInput(X)},"aria-label":n,spellCheck:!1,...pp,"data-slot":"filter-bar-input","data-step":k,"data-target":E?.id,inputMode:k==="value"&&j?.type==="number"?"decimal":void 0,placeholder:ne,className:Z(rwe,"min-w-0 flex-1 bg-transparent","placeholder:text-muted-foreground placeholder:transition-opacity placeholder:duration-normal focus:placeholder:opacity-70"),onFocus:()=>u(!0),onKeyDown:D})]}),a.jsx(Lke,{container:o,children:a.jsx(zke,{align:"start",sideOffset:D_,positionMethod:Av,className:is.positioner,children:a.jsxs(Fke,{className:Z(is.popup,"min-w-56"),"data-slot":"filter-bar-editor",children:[(k!=="value"||V.hasSuggestions)&&a.jsxs("div",{className:Z(is.searchContainer,"cursor-text"),"data-slot":"filter-bar-search",onMouseDown:X=>X.preventDefault(),onClick:()=>l.current?.focus(),children:[a.jsx(wu,{className:is.searchIcon}),a.jsx("span",{className:Z(is.searchInput,"flex items-center truncate",d===""&&is.placeholder),children:d===""?G:d})]}),k==="field"&&a.jsx(rN,{"aria-label":"Fields",getKey:X=>X.id,renderOption:X=>a.jsxs(a.Fragment,{children:[a.jsx(ree,{field:X}),X.search&&d!==""&&a.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:[i.getFieldOperators(X)[0]?.label,' "',d,'"']})]}),emptyText:"No matching field."}),k==="operator"&&a.jsx(rN,{"aria-label":"Operators",getKey:X=>X.id,renderOption:X=>X.label,emptyText:"No matching operator."}),k==="value"&&V.hasOptions&&a.jsx(rN,{"aria-label":"Values","aria-multiselectable":V.isMany||void 0,getKey:X=>X.value,renderOption:X=>a.jsx(LVt,{option:X}),isSelected:X=>V.isMany&&V.selected.includes(X.value),isLoading:V.isLoading,error:V.error,emptyText:V.allowFreeText?"No suggestions — press Enter to use your text.":"No matching value."}),k==="value"&&!V.hasSuggestions&&a.jsxs("div",{className:"flex items-center justify-between gap-2 py-1 pr-1 pl-[.9em]",children:[a.jsx(Y,{variant:"caption",tone:"muted",children:"Type a value"}),a.jsxs(ce,{size:"sm",variant:"default",disabled:!V.canCommitQuery,onMouseDown:X=>X.preventDefault(),onClick:()=>V.submitFreeText(),children:["Apply",a.jsx(Hd,{size:"xs",children:"↵"})]})]}),k==="value"&&V.isMany&&a.jsx("div",{className:"flex items-center justify-end gap-1 border-t border-border p-1",children:a.jsxs(ce,{size:"sm",variant:"default",onMouseDown:X=>X.preventDefault(),onClick:()=>V.commitDone(),children:["Done",a.jsx(Hd,{size:"xs",children:y})]})})]})})})]})})}function tUt(e,t,n){const{settleRemove:r}=bc();g.useEffect(()=>{const s=n.current;if(!t||!s)return;const i=typeof s.getAnimations=="function"?s.getAnimations({subtree:!0}):[];if(i.length===0){r(e);return}let o=!1;return Promise.all(i.map(l=>l.finished)).then(()=>{o||r(e)}).catch(()=>{}),()=>{o=!0}},[t,e,r,n])}const nUt="flex h-control-sm w-14 shrink-0 items-center justify-center rounded-md text-column tracking-wide text-muted-foreground uppercase";function t0s({groupId:e,logic:t,className:n}){const r=bc(),s=t==="and"?"or":"and";return a.jsx("button",{type:"button","data-slot":"filter-bar-logic","data-logic":t,"aria-label":`Joined with ${t}, switch to ${s}`,title:`Switch to ${s}`,className:Z(nUt,"filter-bar-logic cursor-pointer border border-border bg-fill-subtle outline-none","hover:bg-fill-hover hover:text-foreground focus-visible:bg-fill-hover focus-visible:text-foreground",n),onClick:()=>r.setLogic(e,s),children:t})}function n0s({groupId:e,logic:t}){const n=bc();return a.jsx("div",{role:"radiogroup","aria-label":"Group logic",className:"flex h-control-sm items-center gap-0.5 rounded-md border border-border bg-fill-subtle p-0.5",children:["and","or"].map(r=>a.jsx("button",{type:"button",role:"radio","aria-checked":t===r,"aria-label":`Join with ${r}`,className:Z("h-full cursor-pointer rounded-sm px-1.5 text-column tracking-wide uppercase outline-none","focus-visible:bg-fill-hover",t===r?"bg-fill-hover text-foreground":"text-muted-foreground hover:text-foreground"),onClick:()=>t!==r&&n.setLogic(e,r),children:r},r))})}function rUt({group:e,depth:t,onRemove:n,removeLabel:r="Remove group",className:s}){const i=bc(),o=g.useRef(null),l=g.useRef(!1),c=i.inputTarget===e.id,u=t<i.maxDepth;g.useEffect(()=>{c||!l.current||(l.current=!1,o.current?.focus())},[c]);const d=[],f=h=>d.length===0?a.jsx("span",{className:nUt,children:"where"},`${h}:where`):a.jsx(t0s,{groupId:e.id,logic:e.logic},`${h}:logic`);for(const h of e.nodes)d.push(a.jsxs(g.Fragment,{children:[f(h.id),qa(h)?a.jsx(r0s,{group:h,depth:t+1}):a.jsx(jx,{item:h,className:"w-fit"})]},h.id));if(i.draft&&i.draft.groupId===e.id){const{id:h,fieldId:p,operatorId:m=""}=i.draft;d.push(a.jsxs(g.Fragment,{children:[f(h),a.jsx(jx,{draft:!0,item:{id:h,fieldId:p,operatorId:m,value:""},className:"w-fit"})]},h))}return c&&d.push(a.jsxs(g.Fragment,{children:[f("input"),a.jsx(eUt,{groupId:e.id,placeholder:"Add condition…",onLeave:()=>{l.current=!0}})]},"input")),a.jsxs("div",{"data-slot":"filter-bar-group-editor","data-depth":t,role:"group","aria-label":`Conditions joined with ${e.logic}`,className:Z("flex min-w-0 flex-col",s),children:[d.length>0&&a.jsx("div",{className:"grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-2 gap-y-1.5 p-2",children:d}),a.jsxs("div",{"data-slot":"filter-bar-editor-actions",className:Z("flex w-full items-center gap-1 p-1",d.length>0&&"border-t border-border"),children:[!c&&a.jsx(ce,{ref:o,variant:"ghost",size:"sm",icon:a.jsx(Dr,{}),onClick:()=>i.openGroupInput(e.id),children:"Condition"}),a.jsx(ce,{variant:"ghost",size:"sm",icon:a.jsx(_S,{}),className:"text-muted-foreground",tooltip:u?void 0:`Groups can nest ${i.maxDepth} levels deep`,disabled:!u,onClick:()=>i.addGroup(e.id,e.logic==="and"?"or":"and"),children:"Group"}),n&&a.jsx(ce,{variant:"ghost",size:"sm",icon:a.jsx(Xo,{}),className:"ml-auto text-muted-foreground","aria-label":r,onClick:n,children:"Clear all"})]})]})}function r0s({group:e,depth:t}){const n=bc(),r=g.useRef(null),s=n.leaving.has(e.id);tUt(e.id,s,r);const i=tAe(e);return a.jsxs("div",{ref:r,"data-slot":"filter-bar-editor-nested","data-leaving":s||void 0,"aria-hidden":s||void 0,className:Z("filter-bar-editor-nested w-full overflow-hidden rounded-lg border border-border",s&&"pointer-events-none"),children:[a.jsxs("div",{className:"flex items-center gap-2 border-b border-border px-2 py-1",children:[a.jsx(wP,{className:"size-3.5 text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"label",tone:"ink",children:"Group"}),a.jsxs(Y,{as:"span",variant:"label",tone:"muted",children:["· ",i," ",i===1?"condition":"conditions"]}),a.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[a.jsx(n0s,{groupId:e.id,logic:e.logic}),a.jsx(ce,{variant:"ghost",size:"icon-sm",tooltip:"Remove group",disabled:s,onClick:()=>n.removeGroup(e.id),children:a.jsx(Xo,{})})]})]}),a.jsx(rUt,{group:e,depth:t})]})}function sUt({group:e,className:t}){const n=bc(),r=g.useRef(null),s=g.useRef(null),i=n.leaving.has(e.id),o=n.openGroupId===e.id,l=tAe(e),c=n.items.findIndex(h=>iUt(e,h.id)),u=c===-1?n.items.length:c;tUt(e.id,i,r);const d=h=>{if(i)return;const p=Array.from(r.current?.querySelectorAll("[data-filter-bar-segment]")??[]),m=p.findIndex(v=>v===h.target);if(m!==-1)switch(h.key){case"ArrowRight":{h.preventDefault();const v=p[m+1];v?v.focus():n.focusChip(u+l,1,"field")||n.focusInput();return}case"ArrowLeft":{h.preventDefault();const v=p[m-1];v?v.focus():n.focusChip(u-1,-1,"remove");return}case"Delete":case"Backspace":h.preventDefault(),f();return}},f=()=>{n.removeGroup(e.id),n.focusAfterRemove(u)};return a.jsxs(jp,{open:o,onOpenChange:h=>n.setOpenGroup(h?e.id:null),children:[a.jsxs("div",{ref:r,role:"group","aria-label":`Advanced filter, ${l} ${l===1?"condition":"conditions"}`,"aria-hidden":i||void 0,"data-slot":"filter-bar-advanced","data-leaving":i||void 0,className:Z("filter-bar-advanced",qVt,i&&"pointer-events-none",t),onKeyDown:d,children:[a.jsxs(of,{ref:h=>{s.current=h,n.registerSegment(e.id,"field",i?null:h)},render:a.jsx("button",{type:"button"}),"data-filter-bar-segment":"field",className:Z(sN,"gap-1.5"),title:"Edit advanced filter",children:[a.jsx(Va,{className:"size-[1.1em] shrink-0","aria-hidden":!0}),a.jsx("span",{className:"truncate",children:"Advanced filter"}),l>0&&a.jsx(Y,{as:"span",variant:"column",tone:"muted","aria-hidden":!0,children:l})]}),i?a.jsx("span",{"aria-hidden":!0,className:Z(sN,"px-1.5"),children:a.jsx(Mn,{className:"size-[1.1em]"})}):a.jsx("button",{type:"button",ref:h=>n.registerSegment(e.id,"remove",h),"data-filter-bar-segment":"remove","aria-label":"Remove advanced filter",title:"Remove advanced filter",className:Z(sN,"px-1.5"),onClick:f,children:a.jsx(Mn,{className:"size-[1.1em]"})})]}),a.jsxs(ah,{align:"start",className:"w-[min(92vw,44rem)] p-0",[rAe]:"advanced",finalFocus:s,children:[a.jsxs("div",{className:"flex items-center gap-2 border-b border-border px-3 py-2",children:[a.jsx(Va,{className:"size-3.5 text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"label",tone:"ink",children:"Advanced filter"}),a.jsx(Y,{as:"span",variant:"column",tone:"muted",className:"rounded-md bg-fill-subtle px-1.5",children:l}),a.jsx(ce,{variant:"ghost",size:"icon-sm",className:"ml-auto",tooltip:"Close",onClick:()=>n.setOpenGroup(null),children:a.jsx(Mn,{})})]}),a.jsx(rUt,{group:e,depth:1,removeLabel:"Remove advanced filter",onRemove:()=>{n.setOpenGroup(null),f()}})]})]})}const iUt=(e,t)=>e.nodes.some(n=>n.id===t?!0:"kind"in n&&iUt(n,t));function s0s({label:e}){const t=bc();return t.hasRemovableItems?a.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":e,tooltip:e,onClick:n=>{n.stopPropagation(),t.clear(),t.focusInput()},children:a.jsx(Mn,{})}):null}function i0s({className:e,clearLabel:t,children:n}){const r=bc();return a.jsxs("div",{role:"group","aria-label":r.ariaLabel,"data-slot":"filter-bar",[rAe]:"bar",className:Z("flex w-full flex-wrap items-center gap-1",e),children:[n,a.jsx("span",{className:"flex shrink-0 items-center empty:hidden",children:a.jsx(s0s,{label:t})}),a.jsx(B0,{"aria-live":"polite",children:r.announcement})]})}function kl({fields:e,operators:t,value:n,onValueChange:r,createItemId:s,maxDepth:i,"aria-label":o="Filters",describeSuggestionsError:l,clearLabel:c="Clear filters",className:u,children:d}){return a.jsx(Abs,{fields:e,operators:t,value:n,onValueChange:r,createItemId:s,maxDepth:i,ariaLabel:o,describeSuggestionsError:l,children:a.jsx(i0s,{className:u,clearLabel:c,children:d})})}function o0s({renderChip:e=a0s}){const t=bc(),n=[];for(const r of t.expression.nodes){const s=qa(r)?a.jsx(sUt,{group:r}):e(r);s!==null&&n.push(a.jsx(g.Fragment,{children:s},r.id))}if(t.draft&&!t.draft.groupId){const{id:r,fieldId:s,operatorId:i=""}=t.draft;n.push(a.jsx(g.Fragment,{children:a.jsx(jx,{draft:!0,item:{id:r,fieldId:s,operatorId:i,value:""}})},r))}return a.jsx(a.Fragment,{children:n})}const a0s=e=>a.jsx(jx,{item:e});kl.Chips=o0s;kl.Chip=jx;kl.AdvancedChip=sUt;kl.Input=eUt;const l0s=1440*60*1e3,Dz=({queryOptions:e}={})=>{const t=Ke();return Ct({queryKey:["observability-capabilities"],queryFn:()=>t.getObservabilityCapabilities(),retry:!1,staleTime:l0s,...e})},see=()=>{const{data:e,isLoading:t}=Dz();return{isLoading:t,enabled:!t&&(e?.capabilities.traceQuery??!0)}},c0s=()=>{const{data:e,isLoading:t}=Dz();return{isLoading:t,enabled:!t&&(e?.capabilities.traceQueryDiscovery??!0)}},u0s=()=>{const{data:e,isLoading:t}=Dz();return{isLoading:t,enabled:!t&&(e?.capabilities.traceQueryRootDuration??!1)}},d0s=()=>{const{data:e,isLoading:t}=Dz();return{isLoading:t,enabled:!t&&(e?.capabilities.feedback??!0)}};function f0s(e){return e.startsWith("agent-")}function h0s(e){return e.match(/^(?:mcp_)?tool:\s*'(.*?)'/)?.[1]??e}function oUt(e){return aUt(e,[])}function aUt(e,t){if(!e)return t;for(const n of e){const r=n.stepType==="tool_call"||n.stepType==="mcp_tool_call";if(r&&n.name){const s=h0s(n.name),i="toolArgs"in n?n.toolArgs:void 0,o="toolResult"in n?n.toolResult:void 0;t.push({toolName:s,args:i??{},output:o??null,...f0s(s)?{matchArgs:"ignore"}:{}})}!r&&n.children?.length&&aUt(n.children,t)}return t}function p0s(e){const t=(()=>{try{const r=JSON.stringify(e.input);return r?r.length>40?`${r.slice(0,40)}…`:r:""}catch{return""}})(),n=Tv(e.id)??e.id;return t?`${n} — ${t}`:n}function m0s({traceId:e,isOpen:t,onClose:n,level:r=2}){const s=Ke(),{data:i,isLoading:o}=Ct({queryKey:["trace-trajectory",e],queryFn:()=>s.getTraceTrajectory(e??""),enabled:t&&!!e}),l=i?.steps?oUt(i.steps):[],c=l.length>0?rv(l,2):"";return a.jsxs(xo,{dialogTitle:"Add Tool Mocks to Item",dialogDescription:"Append trace-derived tool mocks to an existing dataset item",isOpen:t,onClose:n,level:r,children:[a.jsxs(xo.Top,{children:[a.jsxs(lv,{children:[a.jsx(Fa,{})," ",Tv(e)]}),"›",a.jsxs(lv,{children:[a.jsx(dd,{})," Add Tool Mocks to Item"]})]}),a.jsxs(xo.Content,{children:[a.jsx(xo.Header,{children:a.jsxs(xo.Heading,{children:[a.jsx(dd,{})," Add Tool Mocks to Item"]})}),o?a.jsx(Y,{as:"p",variant:"body",tone:"muted",className:"px-2 py-4",children:"Loading tool calls from trace..."}):a.jsx(g0s,{initialMocksJson:c,onClose:n},e??"no-trace")]})]})}function g0s({initialMocksJson:e,onClose:t}){const[n,r]=g.useState(""),[s,i]=g.useState(""),[o,l]=g.useState(e),{data:c,isLoading:u}=Ak(),d=c?.datasets??[],{data:f=[],isLoading:h}=oA({datasetId:n,queryOptions:{enabled:!!n}}),{data:p,isFetching:m}=UOt({datasetId:n,itemId:s,queryOptions:{enabled:!!n&&!!s}}),{updateItem:v}=pl(),y=(()=>{if(!o.trim())return!1;try{const S=JSON.parse(o);return Array.isArray(S)&&S.length>0}catch{return!1}})(),x=S=>{r(S),i("")},b=async S=>{if(S.preventDefault(),!n||!s){Xe.error("Please select a dataset and an item");return}let k;try{const T=o.trim()?JSON.parse(o):[];if(!Array.isArray(T)){Xe.error("Tool Mocks must be a JSON array");return}k=T}catch{Xe.error("Tool Mocks must be valid JSON");return}if(k.length===0){Xe.error("There are no tool mocks to add");return}if(!p||p.id!==s){Xe.error("Item is still loading, please try again");return}const C=[...p.toolMocks??[],...k];try{await v.mutateAsync({datasetId:n,itemId:s,toolMocks:C}),Xe.success(`Added ${k.length} tool mock(s) to the item`),t()}catch(T){Xe.error(`Failed to add tool mocks: ${T instanceof Error?T.message:"Unknown error"}`)}};return a.jsxs(Ga,{onSubmit:b,children:[a.jsxs(pt,{children:[a.jsx(dt,{required:!0,children:"Dataset"}),a.jsxs(ms,{value:n,onValueChange:x,disabled:u,children:[a.jsx(vs,{children:a.jsx(gs,{placeholder:u?"Loading datasets...":"Select a dataset"})}),a.jsx(ys,{children:d.length===0?a.jsx(Y,{as:"p",variant:"body",tone:"muted",className:"px-2 py-4 text-center",children:"No datasets available"}):d.map(S=>a.jsx(hr,{value:S.id,children:S.name},S.id))})]})]}),a.jsxs(pt,{children:[a.jsx(dt,{required:!0,children:"Item"}),a.jsxs(ms,{value:s,onValueChange:i,disabled:!n||h,children:[a.jsx(vs,{children:a.jsx(gs,{placeholder:n?h?"Loading items...":"Select an item":"Select a dataset first"})}),a.jsx(ys,{children:f.length===0?a.jsx(Y,{as:"p",variant:"body",tone:"muted",className:"px-2 py-4 text-center",children:"No items available"}):f.map(S=>a.jsx(hr,{value:S.id,children:p0s(S)},S.id))})]})]}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Tool Mocks (JSON)"}),a.jsx(Or,{value:o,onChange:l,showCopyButton:!1,className:"min-h-40"}),a.jsx(no,{children:"Seeded from the trace's tool calls. Edit or remove entries before appending."})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[a.jsx(ce,{icon:a.jsx(Mn,{}),type:"button",onClick:t,children:"Cancel"}),a.jsx(ce,{icon:a.jsx(Dr,{}),type:"submit",variant:"default",disabled:v.isPending||m||!y||!n||!s||p?.id!==s,children:v.isPending?"Adding...":"Append Tool Mocks"})]})]})}function v0s(e){if(e?.input==null)return"{}";const t=e.input,r=e.spanType==="agent_run"&&t&&typeof t=="object"&&!Array.isArray(t)&&"messages"in t?t.messages??e.input:e.input;return rv(r,2)}function y0s({traceDetails:e,rootSpanId:t,traceId:n,isOpen:r,onClose:s,level:i=2}){const o=Ke(),{data:l}=FNe({traceId:!e&&r?n:null,spanId:!e&&r?t:null,queryOptions:{enabled:!!(!e&&r&&n)&&!!(!e&&r&&t)}}),c=e??l?.span,{data:u,isLoading:d}=Ct({queryKey:["trace-trajectory",n],queryFn:()=>o.getTraceTrajectory(n??""),enabled:r&&!!n}),f=u?.steps&&u.steps.length>0?rv({steps:u.steps.map(m=>{const{name:v,stepType:y,children:x,...b}=m,S={name:v,stepType:y};for(const[k,j]of Object.entries(b))j!=null&&k!=="durationMs"&&k!=="metadata"&&(S[k]=j);return S}),ordering:"relaxed"},2):void 0,h=u?.steps?oUt(u.steps):[],p=h.length>0?rv(h,2):void 0;return a.jsx(J9t,{initialInput:v0s(c),initialGroundTruth:c?.output!=null?rv(c.output,2):"",initialTrajectory:f,trajectoryLoading:d,initialToolMocks:p,breadcrumb:a.jsxs(lv,{children:[a.jsx(Fa,{})," ",Tv(n)]}),isOpen:r,onClose:s,level:i,source:n?{type:"trace",referenceId:n}:void 0})}const x0s={"last-24h":"the last 24 hours","last-3d":"the last 3 days","last-7d":"the last 7 days","last-14d":"the last 14 days","last-30d":"the last 30 days"},iue="Pick a wider time range — older traces may fall outside the current window.";function b0s({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No traces for ${x0s[e]}`,description:iue}:t&&n?{title:`No traces between ${rs(t,"date-time")} and ${rs(n,"date-time")}`,description:iue}:t?{title:`No traces since ${rs(t,"date-time")}`,description:iue}:{title:"No traces yet",description:"Traces will appear here once agents, workflows, or tools are executed."}}const w0s=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=b0s({datePreset:e,dateFrom:t,dateTo:n});return a.jsx(Yt,{titleSlot:r,descriptionSlot:s,variant:"fill"})};function lUt({queryOptions:e}={}){const t=Ke(),n=mr();return wn({mutationFn:({feedbackId:r,reviewStatus:s})=>t.updateFeedbackReviewStatus({feedbackId:r,reviewStatus:s}),onSuccess:()=>Promise.all([n.invalidateQueries({queryKey:["trace-feedback"]}),n.invalidateQueries({queryKey:["span-feedback"]})]),...e})}function S0s(e){return e==="needs-review"?"warning":e==="complete"||e==="reviewed"?"success":"neutral"}function lAe({status:e,children:t,...n}){return a.jsx($t,{size:"xs",...n,variant:S0s(e),children:t??e})}function k0s(e){const t=e.author;return t?t.name||t.email||t.id:void 0}const cUt=g.createContext(null);function lT(){const e=g.useContext(cUt);if(!e)throw new Error("Comment compounds must be rendered within Comment");return e}const O0s=md("flex flex-col",{variants:{variant:{default:"gap-2",embed:Z(pr,"gap-1 rounded-xl p-3"),thread:""}},defaultVariants:{variant:"default"}}),uUt=g.forwardRef(({className:e,variant:t="default",...n},r)=>a.jsx(cUt.Provider,{value:t,children:a.jsx("div",{ref:r,"data-slot":"comment","data-variant":t,className:Z(O0s({variant:t}),e),...n})}));uUt.displayName="Comment";const j0s={default:"gap-3",embed:"gap-2",thread:""},dUt=g.forwardRef(({className:e,...t},n)=>{const r=lT();return a.jsx("ul",{ref:n,"data-slot":"comment-list",className:Z("flex flex-col",j0s[r],e),...t})});dUt.displayName="CommentList";const C0s={default:"flex flex-col gap-1",embed:"flex flex-col gap-1",thread:"relative flex gap-2 rounded-lg px-2 hover:bg-fill-subtle"},Mye=g.forwardRef(({className:e,continued:t=!1,highlighted:n=!1,...r},s)=>{const i=lT(),o=i==="thread"?"div":"li";return a.jsx(o,{ref:s,"data-slot":"comment-item",className:Z("group/comment-item",C0s[i],i==="thread"&&(t?"py-0.5":"py-1.5"),n&&"bg-info-subtle",e),...r})});Mye.displayName="CommentItem";const fUt=g.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,"data-slot":"comment-item-avatar",className:Z("w-6 shrink-0 pt-0.5",e),...t}));fUt.displayName="CommentItemAvatar";const hUt=g.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,"data-slot":"comment-item-content",className:Z("min-w-0 flex-1",e),...t}));hUt.displayName="CommentItemContent";const _0s={default:"flex items-center gap-2",embed:"flex items-center gap-2",thread:"flex items-baseline gap-1.5"},Dye=g.forwardRef(({className:e,...t},n)=>{const r=lT();return a.jsx("div",{ref:n,"data-slot":"comment-item-header",className:Z(_0s[r],e),...t})});Dye.displayName="CommentItemHeader";const T0s={default:"subheading",embed:"subheading",thread:"column"},I0s={default:"text-foreground",embed:"text-foreground",thread:"truncate text-foreground"},pUt=g.forwardRef(({className:e,...t},n)=>{const r=lT();return a.jsx(Y,{ref:n,as:"span",variant:T0s[r],"data-slot":"comment-item-author",className:Z(I0s[r],e),...t})});pUt.displayName="CommentItemAuthor";const E0s={default:"text-caption text-muted-foreground",embed:"text-caption text-muted-foreground",thread:"text-meta text-placeholder shrink-0"},mUt=g.forwardRef(({className:e,...t},n)=>{const r=lT();return a.jsx("time",{ref:n,"data-slot":"comment-item-timestamp",className:Z(E0s[r],e),...t})});mUt.displayName="CommentItemTimestamp";const N0s={default:"body",embed:"body",thread:"caption"},A0s={default:"whitespace-pre-wrap text-foreground border-l border-border pl-3",embed:"whitespace-pre-wrap text-foreground",thread:""},gUt=g.forwardRef(({className:e,...t},n)=>{const r=lT();return jwe({defaultTagName:r==="thread"?"div":"p",props:{...t,ref:n,"data-slot":"comment-item-body",className:Z(Sa({variant:N0s[r]}),A0s[r],e)}})});gUt.displayName="CommentItemBody";const P0s={default:"flex items-center gap-1 opacity-0 group-focus-within/comment-item:opacity-100 group-hover/comment-item:opacity-100 motion-safe:transition-opacity",embed:"",thread:"ml-auto flex shrink-0 items-center gap-0.5 self-center transition-opacity duration-200 ease-out motion-reduce:transition-none pointer-fine:opacity-0 pointer-fine:group-focus-within/comment-item:opacity-100 pointer-fine:group-hover/comment-item:opacity-100"},vUt=g.forwardRef(({className:e,...t},n)=>{const r=lT();return r==="embed"?null:a.jsx("div",{ref:n,"data-slot":"comment-item-actions",className:Z(P0s[r],e),...t})});vUt.displayName="CommentItemActions";function $0s({status:e}){const t=e==="reviewed"?"reviewed":"needs-review";return a.jsx(lAe,{"data-slot":"feedback-review-status",status:t,children:t==="reviewed"?"Reviewed":"Needs review"})}function R0s(e){const t=e.comment||(typeof e.value=="string"?e.value:"");return t||(e.feedbackType==="thumbs"?e.value===1?"👍":"👎":String(e.value??""))}function M0s({variant:e,items:t,onRequestDelete:n,isDeleting:r,onMarkReviewed:s,pendingFeedbackId:i}){const o=t.map((l,c)=>{const u=new Date(l.timestamp),d=k0s(l),f=d?a.jsx(JS,{name:d,src:l.author?.avatarUrl,size:"sm"}):null,h=d&&a.jsx(pUt,{children:d}),p=a.jsx(mUt,{dateTime:u.toISOString(),children:rs(u,"date-time")}),m=l.feedbackId,v=a.jsx($0s,{status:l.reviewStatus}),y=!!(s&&m&&l.reviewStatus!=="reviewed"),x=!!(n&&m),b=m&&(y||x)&&a.jsx(vUt,{children:a.jsxs(lt,{children:[a.jsx(lt.Trigger,{render:a.jsx(ce,{size:"icon-sm",variant:"ghost","aria-label":"Feedback actions",children:a.jsx(AN,{})})}),a.jsxs(lt.Content,{align:"end",children:[y&&a.jsxs(lt.Item,{disabled:i===m,onSelect:()=>s?.(m),children:[a.jsx(At,{size:"xs",children:a.jsx(Jht,{})}),"Mark reviewed"]}),x&&a.jsxs(lt.Item,{disabled:r,onSelect:()=>n?.(m),children:[a.jsx(At,{size:"xs",children:a.jsx(Xo,{})}),"Delete feedback"]})]})]})}),S=a.jsx(gUt,{children:R0s(l)}),k=m??`${l.traceId}-${c}`;return e==="thread"?a.jsxs(Mye,{children:[f&&a.jsx(fUt,{children:f}),a.jsxs(hUt,{children:[a.jsxs(Dye,{children:[h,p,v,b]}),S]})]},k):a.jsxs(Mye,{children:[a.jsxs(Dye,{children:[f,h,p,v,b]}),S]},k)});return e==="thread"?a.jsx(a.Fragment,{children:o}):a.jsx(dUt,{children:o})}function yUt({feedbackData:e,isLoadingFeedbackData:t,onPageChange:n,onSubmit:r,isSubmitting:s=!1,onDelete:i,isDeleting:o=!1,variant:l="thread",onMarkReviewed:c,pendingFeedbackId:u}){const[d,f]=g.useState(""),[h,p]=g.useState(),m=d.trim().length===0||s,v=e?.feedback??[],y=e?.pagination?.page??0,x=e?.pagination?.hasMore??!1,b=async()=>{if(!(!h||!i))try{await i(h),p(void 0)}catch{}};return a.jsxs(uUt,{variant:l,className:"min-h-0 gap-3",children:[a.jsx("form",{"aria-label":"Leave feedback",className:"flex w-full items-center gap-2",onSubmit:async S=>{if(S.preventDefault(),!m)try{await r(d.trim()),f("")}catch{}},children:a.jsxs(nPt,{size:"sm",children:[a.jsx(rPt,{"aria-label":"Leave feedback",placeholder:"Leave feedback...",value:d,onChange:S=>f(S.target.value)}),a.jsx(hge,{align:"inline-end",children:a.jsx(sPt,{type:"submit","aria-label":"Send feedback",disabled:m,children:a.jsx(bk,{})})})]})}),a.jsx("div",{className:"min-h-0 overflow-y-auto",children:t?a.jsx(Y,{variant:"body",tone:"muted",children:"Loading feedback..."}):v.length===0?a.jsx(Y,{variant:"body",tone:"muted",className:"text-center",children:"No feedback yet"}):a.jsx(M0s,{variant:l,items:v,onRequestDelete:i?p:void 0,isDeleting:o,onMarkReviewed:c,pendingFeedbackId:u})}),(x||y>0)&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ce,{icon:a.jsx(yP,{}),size:"sm",variant:"ghost",disabled:y===0,onClick:()=>n?.(y-1),children:"Previous"}),a.jsx(ce,{icon:a.jsx(Lc,{}),size:"sm",variant:"ghost",disabled:!x,onClick:()=>n?.(y+1),children:"Next"})]}),a.jsx(Bt,{open:h!==void 0,onOpenChange:S=>{!S&&!o&&p(void 0)},children:a.jsxs(Bt.Content,{children:[a.jsxs(Bt.Header,{children:[a.jsx(Bt.Title,{children:"Delete feedback?"}),a.jsx(Bt.Description,{children:"This permanently deletes this feedback comment. This action cannot be undone."})]}),a.jsxs(Bt.Footer,{children:[a.jsx(Bt.Cancel,{disabled:o,children:"Cancel"}),a.jsx(ce,{icon:a.jsx(Xo,{}),variant:"primary",disabled:o,onClick:b,children:o?"Deleting…":"Delete"})]})]})})]})}function xUt({traceId:e,spanId:t}){const[n,r]=g.useState(0),{data:s,isLoading:i}=VNe({traceId:e,spanId:t,page:n,queryOptions:{enabled:!!e&&!!t}}),{mutateAsync:o,isPending:l}=XBt({traceId:e,spanId:t}),{mutateAsync:c,isPending:u}=JBt({traceId:e,spanId:t}),d=lUt();return a.jsx(yUt,{feedbackData:s,isLoadingFeedbackData:i,onPageChange:r,onSubmit:f=>o({text:f}),isSubmitting:l,onDelete:f=>c({feedbackId:f}),isDeleting:u,onMarkReviewed:f=>d.mutate({feedbackId:f,reviewStatus:"reviewed"}),pendingFeedbackId:d.isPending?d.variables.feedbackId:void 0})}const D0s=["type","input","duration","endTime","environment","inputTokens","outputTokens","totalTokens","estimatedCost"],cAe=["inputTokens","outputTokens","totalTokens","estimatedCost"],bUt=["traceId","threadId","resourceId","entityId"],wUt={traceId:"Trace ID",threadId:"Thread ID",resourceId:"Resource ID",entityId:"Primitive ID"},s0={visibleColumns:["type","input","duration","estimatedCost"],customColumns:[],metadataKeys:[]},SUt=3,L0s=new Set([2,SUt]),z0s=new Set(D0s),F0s=new Set(cAe),B0s=new Set(bUt);function V0s(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function U0s(e){return typeof e=="string"&&z0s.has(e)}function q0s(e){return typeof e=="string"&&B0s.has(e)}function Q0s(e){if(!Array.isArray(e))return[];const t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);return[...new Set(t)]}function Z0s(e){if(!e)return s0;try{const t=JSON.parse(e);if(!V0s(t)||!L0s.has(t.version))return s0;const n=Array.isArray(t.visibleColumns)?[...new Set(t.visibleColumns.filter(U0s))]:[...s0.visibleColumns],r=Array.isArray(t.customColumns)?[...new Set(t.customColumns.filter(q0s))]:[];return{visibleColumns:n,customColumns:r,metadataKeys:Q0s(t.metadataKeys)}}catch{return s0}}function W0s(e){return JSON.stringify({version:SUt,visibleColumns:e.visibleColumns,customColumns:e.customColumns,metadataKeys:e.metadataKeys})}function H0s(e){const t=new Set(e.visibleColumns),n=["startTime"];t.has("type")&&n.push("type"),n.push("name"),t.has("input")&&n.push("input"),n.push("status");for(const r of["duration","endTime","environment",...cAe])t.has(r)&&n.push(r);return n.push(...e.customColumns.map(r=>`custom:${r}`)),n.push(...e.metadataKeys.map(r=>`metadata:${r}`)),n}function kUt(e){const t=new Set(e.visibleColumns),n=["11rem"];t.has("type")&&n.push("7rem"),n.push(t.has("input")?"14rem":"minmax(8rem,1fr)"),t.has("input")&&n.push("minmax(8rem,1fr)"),n.push("6rem"),t.has("duration")&&n.push("7rem"),t.has("endTime")&&n.push("11rem"),t.has("environment")&&n.push("8rem"),t.has("inputTokens")&&n.push("8rem"),t.has("outputTokens")&&n.push("8rem"),t.has("totalTokens")&&n.push("8rem"),t.has("estimatedCost")&&n.push("8rem");for(const r of e.customColumns)n.push("minmax(8rem,14rem)");for(const r of e.metadataKeys)n.push("minmax(8rem,14rem)");return n.join(" ")}const G0s=/^(?:agent|workflow|scorer) run: '(.+?)'(.*)$/;function K0s(e){return e&&e.replace(G0s,"$1$2")}function Y0s(e,t){if(!e||!Object.prototype.hasOwnProperty.call(e,t))return;const n=e[t];if(n!=null){if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean"||typeof n=="bigint")return String(n);try{return JSON.stringify(n)??void 0}catch{return}}}function Cc(e,t){return e.visibleColumns.includes(t)}function X0s(e){return e.visibleColumns.some(OUt)}function OUt(e){return F0s.has(e)}const J0s=[],ews=["type","input","duration","endTime","environment"],mtt={type:"Primitive type",input:"Input",duration:"Duration",endTime:"End",environment:"Environment",inputTokens:"Input tokens",outputTokens:"Output tokens",totalTokens:"Total tokens",estimatedCost:"Estimated cost"};function tws({preferences:e,availableMetadataKeys:t=J0s,usageDisabledReason:n,withQueryTrace:r=!0,onToggleColumn:s,onAddCustomColumn:i,onRemoveCustomColumn:o,onAddMetadataColumn:l,onRemoveMetadataColumn:c,onReset:u}){const[d,f]=g.useState(!1),[h,p]=g.useState(""),[m,v]=g.useState(),y=g.useMemo(()=>{const S=t.filter(k=>!e.metadataKeys.includes(k));return h&&!S.includes(h)&&S.push(h),S.map(k=>({label:k,value:k}))},[t,e.metadataKeys,h]),x=S=>{f(S),S||(p(""),v(void 0))},b=S=>{S.preventDefault();const k=h.trim();if(!k){v("Enter a metadata key.");return}if(e.metadataKeys.includes(k)){v("That metadata column is already visible.");return}l(k),x(!1)};return a.jsxs(a.Fragment,{children:[a.jsxs(lt,{children:[a.jsx(lt.Trigger,{render:a.jsx(ce,{variant:"ghost",size:"md",icon:a.jsx(tpt,{"aria-hidden":!0}),children:"Columns"})}),a.jsxs(lt.Content,{align:"end",className:"min-w-56",children:[a.jsx(lt.Label,{children:"Standard columns"}),ews.map(S=>a.jsx(lt.CheckboxItem,{checked:e.visibleColumns.includes(S),onCheckedChange:()=>s(S),children:mtt[S]},S)),a.jsx(lt.Separator,{}),a.jsx(lt.Label,{children:"Usage columns"}),cAe.map(S=>a.jsx(lt.CheckboxItem,{checked:e.visibleColumns.includes(S),disabled:!!n,onCheckedChange:()=>s(S),children:mtt[S]},S)),n&&a.jsx(Y,{variant:"meta",tone:"faint",className:"px-2 py-1",role:"note",children:n}),a.jsx(lt.Separator,{}),a.jsx(lt.Label,{children:"Custom columns"}),bUt.map(S=>{const k=e.customColumns.includes(S);return a.jsx(lt.CheckboxItem,{checked:k,onCheckedChange:()=>k?o(S):i(S),children:wUt[S]},S)}),(r||e.metadataKeys.length>0)&&a.jsxs(a.Fragment,{children:[a.jsx(lt.Separator,{}),a.jsx(lt.Label,{children:"Metadata columns"}),e.metadataKeys.map(S=>a.jsx(lt.CheckboxItem,{checked:!0,title:S,onCheckedChange:()=>c(S),children:S},S)),r&&a.jsxs(lt.Item,{onSelect:()=>f(!0),children:[a.jsx(Dr,{"aria-hidden":!0}),"Add metadata column"]})]}),a.jsx(lt.Separator,{}),a.jsx(lt.Item,{onSelect:u,children:"Reset to defaults"})]})]}),r&&a.jsx(Yr,{open:d,onOpenChange:x,children:a.jsx(Xr,{children:a.jsxs(Ga,{onSubmit:b,className:"gap-0",children:[a.jsxs(Jr,{children:[a.jsx(Zr,{children:"Add metadata column"}),a.jsx(Lo,{children:"Pick a top-level trace metadata key observed in the current time range, or type one. Only the key is saved, never its values."})]}),a.jsx(Qr,{children:a.jsxs(pt,{invalid:!!m,children:[a.jsx(dt,{children:"Metadata key"}),a.jsx(fl,{options:y,value:h,onValueChange:S=>{p(S),v(void 0)},allowCustomValue:!0,placeholder:"Select a metadata key…",searchPlaceholder:"Search metadata keys…",emptyText:"No metadata keys observed. Type one to add it."}),a.jsx(ns,{children:m})]})}),a.jsxs(Yo,{children:[a.jsx(_a,{children:"Cancel"}),a.jsx(Ca,{type:"submit",children:"Add column"})]})]})})})]})}function IW({traceId:e,variant:t}){const[n,r]=g.useState(0),{data:s,isLoading:i}=KJ({traceId:e,page:n,queryOptions:{enabled:!!e}}),{mutateAsync:o,isPending:l}=XBt({traceId:e}),{mutateAsync:c,isPending:u}=JBt({traceId:e}),d=lUt();return a.jsx(yUt,{feedbackData:s,isLoadingFeedbackData:i,onPageChange:r,onSubmit:f=>o({text:f}),isSubmitting:l,onDelete:f=>c({feedbackId:f}),isDeleting:u,variant:t,onMarkReviewed:f=>d.mutate({feedbackId:f,reviewStatus:"reviewed"}),pendingFeedbackId:d.isPending?d.variables.feedbackId:void 0})}const o_="timeRange",EW={id:o_,label:"Time",icon:WNe(o_),color:JJ(),type:"text",operators:["is"],hidden:!0},k3={id:o_,fieldId:o_,operatorId:"is",value:""},nws=e=>e instanceof HTMLElement&&e.hasAttribute("data-filter-bar-segment");function jUt(e){const t=bc();return a.jsxs(jx,{item:k3,removable:!1,children:[a.jsx("span",{className:Z(nee,"text-foreground"),style:Rye(EW),children:a.jsx(ree,{field:EW})}),a.jsx("div",{className:"contents",onKeyDown:n=>{nws(n.target)||n.stopPropagation()},children:a.jsx(DCe,{...e,renderTrigger:({label:n,disabled:r})=>a.jsx("button",{type:"button",ref:s=>t.registerSegment(k3.id,"value",s),"data-filter-bar-segment":"",disabled:r,"aria-label":`Value: ${n}`,title:n,className:sN,children:a.jsx("span",{className:"truncate",children:n})})})})]})}function uAe({error:e,resource:t,errorTitle:n}){if(Cs(e))return a.jsx(ci,{});if(_s(e))return a.jsx(Gs,{resource:t});const r=e instanceof Error?MLr(e):void 0;return a.jsx(Yt,{tone:"error",titleSlot:n,descriptionSlot:r?.error??"Unknown error"})}function rws(e,t,n){const r=new Array(e);return new Proxy(r,{get(s,i,o){if(typeof i=="string"){const l=i.charCodeAt(0);if(l>=48&&l<=57){const c=+i;if(Number.isInteger(c)&&c>=0&&c<e){let u=s[c];if(!u){const d=t[c*2];u=s[c]={index:c,key:n(c),start:d,size:t[c*2+1],end:d+t[c*2+1],lane:0}}return u}}if(i==="length")return e}return Reflect.get(s,i,o)}})}function SI(e,t,n){let r=n.initialDeps??[],s,i=!0;function o(){const l=e();return(l.length!==r.length||l.some((u,d)=>r[d]!==u))&&(r=l,s=t(...l),n?.onChange&&!(i&&n.skipInitialOnChange)&&n.onChange(s),i=!1),s}return o.updateDeps=l=>{r=l},o}function gtt(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const sws=(e,t)=>Math.abs(e-t)<1.01,iws=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}};let $M;const oue=()=>{if($M!==void 0)return $M;if(typeof navigator>"u")return $M=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return $M=!0;const e=navigator.maxTouchPoints;return $M=navigator.platform==="MacIntel"&&e!==void 0&&e>0},vtt=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},ows=e=>e,aws=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,s=new Array(r);for(let i=0;i<r;i++)s[i]=t+i;return s},lws=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=o=>{const{width:l,height:c}=o;t({width:Math.round(l),height:Math.round(c)})};if(s(vtt(n)),!r.ResizeObserver)return()=>{};const i=new r.ResizeObserver(o=>{const l=()=>{const c=o[0];if(c?.borderBoxSize){const u=c.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(vtt(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},NW={passive:!0},cws=typeof window>"u"?!0:"onscrollend"in window,uws=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const s=e.targetWindow;if(!s)return;const i=e.options.useScrollendEvent&&cws;let o=0;const l=i?null:iws(s,()=>t(o,!1),e.options.isScrollingResetDelay),c=f=>()=>{o=n(r),l?.(),t(o,f)},u=c(!0),d=c(!1);return r.addEventListener("scroll",u,NW),i&&r.addEventListener("scrollend",d,NW),()=>{r.removeEventListener("scroll",u),i&&r.removeEventListener("scrollend",d)}},dws=(e,t)=>uws(e,t,n=>{const{horizontal:r,isRtl:s}=e.options;return r?n.scrollLeft*(s&&-1||1):n.scrollTop}),fws=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),s=n.options.getItemKey(r);return n.itemSizeCache.get(s)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),s=n.options.getItemKey(r),i=n.itemSizeCache.get(s);if(i!==void 0)return i}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},hws=(e,{adjustments:t=0,behavior:n},r)=>{var s,i;(i=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||i.call(s,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},pws=hws;class mws{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(i=>{const o=()=>{const l=i.target,c=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[u,d]of this.elementsCache)if(d===l){this.elementsCache.delete(u);break}return}this.shouldMeasureDuringScroll(c)&&this.resizeItem(c,this.options.measureElement(l,i,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var i;return(i=r())==null?void 0:i.observe(s,{box:"border-box"})},unobserve:s=>{var i;return(i=r())==null?void 0:i.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{var r,s;const i={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:ows,rangeExtractor:aws,onChange:()=>{},measureElement:fws,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const h in n){const p=n[h];p!==void 0&&(i[h]=p)}const o=this.options;let l=null,c=null,u=!1;if(o!==void 0&&o.enabled&&i.enabled&&i.anchorTo==="end"&&this.scrollElement!==null){const h=o.count,p=i.count,m=this.getMeasurements(),v=h>0?((r=m[0])==null?void 0:r.key)??o.getItemKey(0):null,y=h>0?((s=m[h-1])==null?void 0:s.key)??o.getItemKey(h-1):null;if(p!==h||h>0&&p>0&&(i.getItemKey(0)!==v||i.getItemKey(p-1)!==y)){u=!0;const S=h>0?this.getVirtualItemForOffset(this.getScrollOffset())??m[0]:null;S&&(l=[S.key,this.getScrollOffset()-S.start]);const k=i.followOnAppend===!0?"auto":i.followOnAppend||null;k&&p>h&&this.isAtEnd(o.scrollEndThreshold)&&(h===0||i.getItemKey(p-1)!==y)&&(c=k)}}this.options=i,u&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,f=0;if(l&&this.scrollOffset!==null){const[h,p]=l,m=this.getMeasurements(),{count:v,getItemKey:y}=this.options;let x=0;for(;x<v&&y(x)!==h;)x++;if(x<v){const b=m[x];if(b){const S=b.start+p;S!==this.scrollOffset&&(f=S-this.scrollOffset,this.scrollOffset=S,d=!0)}}}(d||c)&&(this.pendingScrollAnchor=[d?l[0]:null,d?l[1]:0,c,f])},this.notify=n=>{var r,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=SI(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(i=>{this.observer.observe(i)}),this.unsubs.push(this.options.observeElementRect(this,i=>{this.scrollRect=i,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(i,o)=>{if(o&&this._intendedScrollOffset===null&&i===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(i-this._intendedScrollOffset)<1.5&&(i=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=o?l===i?this.scrollDirection:l<i?"forward":"backward":null,this.scrollOffset=i,this.isScrolling=o,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const i=this.scrollElement,o=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!oue()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};i.addEventListener("touchstart",o,NW),i.addEventListener("touchend",l,NW),this.unsubs.push(()=>{i.removeEventListener("touchstart",o),i.removeEventListener("touchend",l),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const s=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,s&&this.scrollElement&&this.options.enabled){const[i,o,l,c]=s;i!==null&&!l&&(oue()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?c!==0&&(this._iosDeferredAdjustment+=c):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const s=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=s,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const s=new Map,i=new Map;for(let o=r-1;o>=0;o--){const l=n[o];if(s.has(l.lane))continue;const c=i.get(l.lane);if(c==null||l.end>c.end?i.set(l.lane,l):l.end<c.end&&s.set(l.lane,!0),s.size===this.options.lanes)break}return i.size===this.options.lanes?Array.from(i.values()).sort((o,l)=>o.end===l.end?o.index-l.index:o.end-l.end)[0]:void 0},this.getMeasurementOptions=SI(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(n,r,s,i,o,l,c)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:o,lanes:l,laneAssignmentMode:c}),{key:!1}),this.getMeasurements=SI(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:s,getItemKey:i,enabled:o,lanes:l,laneAssignmentMode:c},u)=>{const d=this.itemSizeCache;if(!o)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const m of this.laneAssignments.keys())m>=n&&this.laneAssignments.delete(m);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(m=>{this.itemSizeCache.set(m.key,m.size)}));const f=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),l===1){const m=this.options.gap,v=n*2;let y=this._flatMeasurements;if(!y||y.length<v){const S=new Float64Array(v);y&&f>0&&S.set(y.subarray(0,f*2)),y=S,this._flatMeasurements=y}let x;if(f===0)x=r+s;else{const S=f-1;x=y[S*2]+y[S*2+1]+m}for(let S=f;S<n;S++){const k=i(S),j=d.get(k),C=typeof j=="number"?j:this.options.estimateSize(S);y[S*2]=x,y[S*2+1]=C,x+=C+m}const b=rws(n,y,i);return this.measurementsCache=b,b}const h=this.measurementsCache.slice(0,f),p=new Array(l).fill(void 0);for(let m=0;m<f;m++){const v=h[m];v&&(p[v.lane]=m)}for(let m=f;m<n;m++){const v=i(m),y=this.laneAssignments.get(m);let x,b;const S=c==="estimate"||d.has(v);if(y!==void 0&&this.options.lanes>1){x=y;const T=p[x],_=T!==void 0?h[T]:void 0;b=_?_.end+this.options.gap:r+s}else{const T=this.options.lanes===1?h[m-1]:this.getFurthestMeasurement(h,m);b=T?T.end+this.options.gap:r+s,x=T?T.lane:m%this.options.lanes,this.options.lanes>1&&S&&this.laneAssignments.set(m,x)}const k=d.get(v),j=typeof k=="number"?k:this.options.estimateSize(m),C=b+j;h[m]={index:m,start:b,size:j,end:C,key:v,lane:x},p[x]=m}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=SI(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,i)=>n.length===0||r===0?(this.range=null,null):(this.range=vws(n,r,s,i,i===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=SI(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,i,o)=>i===null||o===null?[]:n({startIndex:i,endIndex:o,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const i=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),o=Math.max(0,s-i),l=Math.min(this.options.count-1,s+i);return n>=o&&n<=l}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((o,l)=>{o.isConnected||(this.observer.unobserve(o),this.elementsCache.delete(l))});return}const r=this.indexFromElement(n),s=this.options.getItemKey(r),i=this.elementsCache.get(s);i!==n&&(i&&this.observer.unobserve(i),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s,i;if(n<0||n>=this.options.count)return;let o,l,c;const u=this._flatMeasurements;if(this.options.lanes===1&&u!==null)c=this.options.getItemKey(n),l=u[n*2],o=u[n*2+1];else{const h=this.measurementsCache[n];if(!h)return;c=h.key,l=h.start,o=h.size}const d=this.itemSizeCache.get(c)??o,f=r-d;if(f!==0){const h=this.options.anchorTo==="end"&&((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,p=h?this.getTotalSize():0,m=((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:c,start:l,size:o,end:l+o,lane:0},f,this):l<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(c)||this.scrollDirection!=="backward"));(this.pendingMin===null||n<this.pendingMin)&&(this.pendingMin=n),this.itemSizeCache.set(c,r),this.itemSizeCacheVersion++,h?this.applyScrollAdjustment(this.getTotalSize()-p):m&&this.applyScrollAdjustment(f),this.notify(!1)}},this.getVirtualItems=SI(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let i=0,o=n.length;i<o;i++){const l=n[i],c=r[l];s.push(c)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const s=this._flatMeasurements,i=this.options.lanes===1&&s!=null,o=CUt(0,r.length-1,i?l=>s[l*2]:l=>gtt(r[l]).start,n);return gtt(r[o])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,s=0)=>{if(!this.scrollElement)return 0;const i=this.getSize(),o=this.getScrollOffset();r==="auto"&&(r=n>=o+i?"end":"start"),r==="center"?n+=(s-i)/2:r==="end"&&(n-=i);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getSize(),i=this.getScrollOffset(),o=this.measurementsCache[n];if(!o)return;if(r==="auto")if(o.end>=i+s-this.options.scrollPaddingEnd)r="end";else if(o.start<=i+this.options.scrollPaddingStart)r="start";else return[i,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const l=r==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,o.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const i=this.getOffsetForAlignment(n,r),o=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getOffsetForIndex(n,r);if(!i)return;const[o,l]=i,c=this.now();this.scrollState={index:n,align:l,behavior:s,startedAt:c,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,i=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:i,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1){const i=r.length-1,o=this._flatMeasurements;o!=null?s=o[i*2]+o[i*2+1]:s=((n=r[i])==null?void 0:n.end)??0}else{const i=Array(this.options.lanes).fill(null);let o=r.length-1;for(;o>=0&&i.some(l=>l===null);){const l=r[o];i[l.lane]===null&&(i[l.lane]=l.end),o--}s=Math.max(...i.filter(l=>l!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const s of r)s&&this.itemSizeCache.has(s.key)&&n.push({index:s.index,key:s.key,start:s.start,size:s.size,end:s.end,lane:s.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(oue()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=r?r[0]:this.scrollState.lastTargetOffset,i=1,o=s!==this.scrollState.lastTargetOffset;if(!o&&sws(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=i){this.getScrollOffset()!==s&&this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,o){const l=this.getSize()||600,c=Math.abs(s-this.getScrollOffset()),u=this.scrollState.behavior==="smooth"&&c>l;this.scrollState.lastTargetOffset=s,u||(this.scrollState.behavior="auto"),this._scrollToOffset(s,{adjustments:void 0,behavior:u?"smooth":"auto"})}this.scheduleScrollReconcile()}}const CUt=(e,t,n,r)=>{for(;e<=t;){const s=(e+t)/2|0,i=n(s);if(i<r)e=s+1;else if(i>r)t=s-1;else return s}return e>0?e-1:0};function gws(e,t,n){let r=0;for(;r<=t;){const s=(r+t)/2|0,i=e[s*2];if(i<n)r=s+1;else if(i>n)t=s-1;else return s}return r>0?r-1:0}function vws(e,t,n,r,s){const i=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:i};if(r===1&&s!==null){const u=gws(s,i,n);let d=u;const f=n+t;for(;d<i&&s[d*2]+s[d*2+1]<f;)d++;return{startIndex:u,endIndex:d}}let l=CUt(0,i,u=>e[u].start,n),c=l;if(r===1)for(;c<i&&e[c].end<n+t;)c++;else if(r>1){const u=Array(r).fill(0);for(;c<i&&u.some(f=>f<n+t);){const f=e[c];u[f.lane]=f.end,c++}const d=Array(r).fill(n+t);for(;l>=0&&d.some(f=>f>=n);){const f=e[l];d[f.lane]=f.start,l--}l=Math.max(0,l-l%r),c=Math.min(i,c+(r-1-c%r))}return{startIndex:l,endIndex:c}}const aue=typeof document<"u"?g.useLayoutEffect:g.useEffect;function yws({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const s=g.useReducer(u=>u+1,0)[1],i=g.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});i.current.enabled=t,i.current.mode=n;const o=u=>{const d=i.current;if(!d.enabled||!d.container)return;const f=u.getTotalSize();if(f!==d.lastSize){d.lastSize=f;const x=u.options.horizontal?"width":"height";d.container.style[x]=`${f}px`}const h=!!u.options.horizontal,p=d.mode==="transform",m=h?"left":"top",v=u.options.scrollMargin,y=u.getVirtualItems();for(const x of y){const b=x.start-v,S=u.elementsCache.get(x.key);S&&d.lastPositions.get(S)!==b&&(d.lastPositions.set(S,b),p?S.style.transform=h?`translate3d(${b}px, 0, 0)`:`translate3d(0, ${b}px, 0)`:S.style[m]=`${b}px`)}},l={...r,onChange:(u,d)=>{var f;const h=i.current;let p=!0;if(h.enabled){o(u);const m=u.range,v=h.prevRange;p=!v||v.isScrolling!==u.isScrolling||v.startIndex!==m?.startIndex||v.endIndex!==m?.endIndex,p&&(h.prevRange=m?{startIndex:m.startIndex,endIndex:m.endIndex,isScrolling:u.isScrolling}:null)}p&&(e&&d?So.flushSync(s):s()),(f=r.onChange)==null||f.call(r,u,d)}},[c]=g.useState(()=>{const u=new mws(l);return Object.assign(u,{containerRef:d=>{const f=i.current;if(f.container=d,f.lastSize=null,d&&f.enabled){const h=u.getTotalSize();f.lastSize=h;const p=u.options.horizontal?"width":"height";d.style[p]=`${h}px`}}})});return c.setOptions(l),aue(()=>c._didMount(),[]),aue(()=>c._willUpdate()),aue(()=>{o(c)}),c}function _Ut(e){return yws({observeElementRect:lws,observeElementOffset:dws,scrollToFn:pws,...e})}function AW(e,t){const n=qS(e)?.getTime(),r=qS(t)?.getTime();if(!(n===void 0||r===void 0||r<n))return r-n}function xws(e,t=100){if(e==null)return"";const n=Array.isArray(e)?e:e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.messages)?e.messages:null;if(n){const o=n.filter(l=>l?.role==="user").map(l=>typeof l.content=="string"?l.content:Array.isArray(l.content)?l.content.map(c=>typeof c=="string"?c:c?.type==="text"&&typeof c.text=="string"?c.text:"").filter(Boolean).join(" "):"").filter(Boolean).join(" | ");return o.length>t?o.slice(0,t)+"…":o}if(typeof e=="string")return e.length>t?e.slice(0,t)+"…":e;const r=JSON.stringify(e);return r.length>t?r.slice(0,t)+"…":r}function bws(e){return e?.attributes?.finishReason==="length"}function wws(e){const t=e?.attributes?.usage;if(!t)return"The model stopped generating because it reached the maximum token limit. The response was truncated and may be incomplete.";const n=t.inputTokens??0,r=t.outputTokens??0,s=t.totalTokens??n+r;return n>0||r>0?`The model stopped generating because it reached the maximum token limit. The response was truncated and may be incomplete.
677
677
 
678
678
  Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generating because it reached the maximum token limit (${s} tokens). The response was truncated and may be incomplete.`}const Sws=new Intl.NumberFormat("en-US",{notation:"compact",maximumSignificantDigits:3}),kws=new Intl.NumberFormat("en-US"),Ows=new Set(Intl.supportedValuesOf("currency"));function TUt(e){return e!==void 0&&Ows.has(e.toUpperCase())}function Lye(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:e,...t})}function FD(e,{currency:t}={}){if(!TUt(t))return Sws.format(e);const n=Math.abs(e);return n<100?jws(e,{currency:t}):n<1e3?Lye(t,{maximumFractionDigits:0}).format(e):Lye(t,{notation:"compact",maximumSignificantDigits:3}).format(e)}function jws(e,{currency:t}={}){if(!TUt(t))return kws.format(e);const n=Lye(t,{}),r=10**-(n.resolvedOptions().maximumFractionDigits??2);return e!==0&&Math.abs(e)<r?`${e<0?"-":""}<${n.format(r)}`:n.format(e)}function IUt(e,t){const n=!t||t.toLowerCase()==="usd",r=e>0&&e<.01?"<0.01":e.toFixed(2);return n?r.startsWith("<")?"<$0.01":`$${r}`:`${r} ${t}`}const Cws=36,_ws=8,Tws=20;function Iws(e,t){return e[t]}function Ews(e,t){const n=new Set;for(const r of e){const s=r[t];if(typeof s=="string"&&s&&n.add(s),n.size>=Tws)break}return[...n]}function Nws(e){if(!(e?.inputTokens===void 0&&e?.outputTokens===void 0))return(e?.inputTokens??0)+(e?.outputTokens??0)}function Aws({traces:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,filtersApplied:i,featuredTraceId:o,featuredSpanId:l,isBranchesMode:c,recentlyAddedKeys:u,columnPreferences:d=s0,usageByTraceId:f,onTraceClick:h,createdSort:p,onSortChange:m,onFilterByField:v,listId:y="all-traces"}){const x=g.useRef(null),b=kUt(d),S=H0s(d),k=_Ut({count:e.length,getScrollElement:()=>x.current,estimateSize:()=>Cws,overscan:_ws}),{getRowProps:j}=Fu({count:e.length,containerRef:x,onNavigate:E=>k.scrollToIndex(E),global:!0}),C=k.getVirtualItems(),T=k.getTotalSize(),_=C[0]?.start??0,N=C.length>0?Math.max(0,T-(C[C.length-1]?.end??0)):0;return a.jsxs(Yi,{reorderable:!0,id:y,columns:b,columnKeys:S,fit:"container",scrollRef:x,className:"min-w-0",children:[a.jsxs(Yi.Top,{children:[m?a.jsx(Yi.SortableTopCell,{sortKey:"startedAt",sort:p,onSortChange:m,children:"Start"}):a.jsx(Yi.TopCell,{children:"Start"}),Cc(d,"type")&&a.jsx(Yi.TopCell,{children:"Primitive type"}),a.jsx(Yi.TopCell,{children:"Primitive name"}),Cc(d,"input")&&a.jsx(Yi.TopCell,{children:"Input"}),a.jsx(Yi.TopCell,{children:"Status"}),Cc(d,"duration")&&a.jsx(Yi.TopCell,{className:"justify-end text-right",children:"Duration"}),Cc(d,"endTime")&&a.jsx(Yi.TopCell,{children:"End"}),Cc(d,"environment")&&a.jsx(Yi.TopCell,{children:"Environment"}),Cc(d,"inputTokens")&&a.jsx(Yi.TopCell,{className:"justify-end text-right",children:"Input tokens"}),Cc(d,"outputTokens")&&a.jsx(Yi.TopCell,{className:"justify-end text-right",children:"Output tokens"}),Cc(d,"totalTokens")&&a.jsx(Yi.TopCell,{className:"justify-end text-right",children:"Total tokens"}),Cc(d,"estimatedCost")&&a.jsx(Yi.TopCell,{className:"justify-end text-right",children:"Est. cost"}),d.customColumns.map(E=>{const A=wUt[E],P=v?Ews(e,E):[];return!v||P.length===0?a.jsx(Yi.TopCell,{children:A},E):a.jsx(Yi.TopCell,{className:"overflow-visible",children:a.jsxs(lt,{children:[a.jsx(lt.Trigger,{render:a.jsxs("button",{type:"button",className:Z("flex min-w-0 items-center gap-1 rounded-sm hover:text-foreground",bi),children:[a.jsx("span",{className:"min-w-0 truncate",children:A}),a.jsx(fpt,{"aria-hidden":!0,className:"size-[1.2em] shrink-0"})]})}),a.jsxs(lt.Content,{align:"start",children:[a.jsx(lt.Label,{children:"Filter by value"}),P.map(L=>a.jsx(lt.Item,{onSelect:()=>v(E,L),children:a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",className:"min-w-0 truncate",children:L})},L))]})]})},E)}),d.metadataKeys.map(E=>a.jsx(Yi.TopCellWithTooltip,{tooltip:E,children:E},E))]}),t?a.jsx(tPt,{columnCount:ICe(b).length}):e.length===0?a.jsx(Yi.NoMatch,{message:i?"No traces found for applied filters":"No traces found yet"}):a.jsxs(a.Fragment,{children:[a.jsx(Yi.Spacer,{height:_}),C.map(E=>{const A=e[E.index];if(!A)return null;const P=A.traceId===o&&(l==null||A.spanId===l),L=`${A.traceId}:${A.spanId??""}`,F=u?.has(L)??!1,Q=A.startedAt??A.createdAt,q=f?.get(A.traceId);return a.jsxs(Yi.RowButton,{ref:k.measureElement,"data-index":E.index,...j(E.index),onClick:()=>h(A),featured:P,className:Z(F&&"animate-row-highlight"),children:[a.jsx(Yi.CreatedCell,{timestamp:Q,preset:"day-time-seconds"}),Cc(d,"type")&&a.jsx(Yi.TypeCell,{entityType:A.entityType}),a.jsx(Yi.NameCell,{name:A.entityName||A.name,parentSpanId:A.parentSpanId,showLevelTooltip:c}),Cc(d,"input")&&a.jsx(Yi.InputCell,{input:A.inputPreview??xws(A.input)}),a.jsx(Yi.StatusCell,{status:A.status}),Cc(d,"duration")&&a.jsx(Te.NumberCell,{font:"mono",children:Uc(AW(A.startedAt,A.endedAt))}),Cc(d,"endTime")&&a.jsx(Yi.CreatedCell,{timestamp:A.endedAt??"",preset:"day-time-seconds"}),Cc(d,"environment")&&a.jsx(Te.TextCell,{children:A.environment||"—"}),Cc(d,"inputTokens")&&a.jsx(Te.NumberCell,{children:q?.inputTokens===void 0?void 0:FD(q.inputTokens)}),Cc(d,"outputTokens")&&a.jsx(Te.NumberCell,{children:q?.outputTokens===void 0?void 0:FD(q.outputTokens)}),Cc(d,"totalTokens")&&a.jsx(Te.NumberCell,{children:(()=>{const B=Nws(q);return B===void 0?void 0:FD(B)})()}),Cc(d,"estimatedCost")&&a.jsx(Te.NumberCell,{children:q?.estimatedCost===void 0?void 0:IUt(q.estimatedCost,q.costUnit)}),d.customColumns.map(B=>a.jsx(Te.TextCell,{font:"mono",children:Iws(A,B)??void 0},B)),d.metadataKeys.map(B=>{const V=Y0s(A.metadata,B);return a.jsx(Te.TextCell,{font:"mono",children:V},B)})]},L)}),a.jsx(Yi.Spacer,{height:N}),a.jsx(Yi.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})]})}function Pws({columnPreferences:e=s0}){const t=kUt(e);return a.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2",role:"status","aria-label":"Loading traces","data-testid":"traces-page-skeleton",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(bt,{className:"h-control-md min-w-64 flex-1"}),a.jsx(bt,{className:"h-control-md w-28"})]}),a.jsx(Lu,{columns:t,fit:"container"})]})}function lue(e){if(typeof window>"u")return s0;try{return Z0s(window.localStorage.getItem(e)??void 0)}catch{return s0}}function $ws(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,W0s(t))}catch{}}function Rws(){const e=Uvs(),[t,n]=g.useState(()=>({storageKey:e,preferences:lue(e),shouldPersist:!1})),r=t.storageKey===e?t.preferences:lue(e);g.useEffect(()=>{t.storageKey===e&&t.shouldPersist&&$ws(e,t.preferences)},[t,e]);const s=f=>{n(h=>{const p=h.storageKey===e?h.preferences:lue(e),m=f(p);return{storageKey:e,preferences:m,shouldPersist:!0}})};return{preferences:r,toggleColumn:f=>{s(h=>{const p=h.visibleColumns.includes(f);return{...h,visibleColumns:p?h.visibleColumns.filter(m=>m!==f):[...h.visibleColumns,f]}})},addCustomColumn:f=>{s(h=>h.customColumns.includes(f)?h:{...h,customColumns:[...h.customColumns,f]})},removeCustomColumn:f=>{s(h=>({...h,customColumns:h.customColumns.filter(p=>p!==f)}))},addMetadataColumn:f=>{const h=f.trim();h&&s(p=>p.metadataKeys.includes(h)?p:{...p,metadataKeys:[...p.metadataKeys,h]})},removeMetadataColumn:f=>{s(h=>({...h,metadataKeys:h.metadataKeys.filter(p=>p!==f)}))},resetColumns:()=>s(()=>s0)}}function ytt(e,t){if(!t?.length)return e;const n=new URLSearchParams(e);for(const r of t)n.delete(r),n.delete(oS(r));return n}function Mws(e,t,n){const{storageKey:r,skipHydration:s,excludeParams:i}=n??{},o=g.useRef(!1);return g.useEffect(()=>{if(s||o.current||(o.current=!0,cys(e)))return;const l=lys(r),c=l&&ytt(l,i);c?.toString()&&t(u=>{const d=new URLSearchParams(u);for(const[f,h]of c)d.append(f,h);return d},{replace:!0})},[]),g.useCallback((l,c)=>{t(u=>{const d=typeof l=="function"?l(u):l;return oys(ytt(d,i),r),d},c)},[t,r,i])}function Dws(e,t,n,r){const s=g.useMemo(()=>t?e.findIndex(c=>c.traceId===t&&n==null):-1,[e,t,n]),i=c=>r(c.traceId,void 0),o=s>0?()=>{const c=e[s-1];c&&i(c)}:void 0,l=s>=0&&s<e.length-1?()=>{const c=e[s+1];c&&i(c)}:void 0;return{featuredTraceIdx:s,handlePreviousTrace:o,handleNextTrace:l}}const TV="traceId",$b="spanId",wy="tab",cue="spanView",Sy="scoreId",B2="highlightSpanIds",RM=1440*60*1e3,Lws={"last-24h":RM,"last-3d":3*RM,"last-7d":7*RM,"last-14d":14*RM,"last-30d":30*RM};function kI(e){e.delete(TV),e.delete($b),e.delete(_V),e.delete(wy),e.delete(Sy),e.delete(B2)}function zws(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const z=e.get(V1);return z&&z!=="all"&&rys.has(z)?z:"last-7d"},[e]),i=e.get(w1),o=e.get(S1),l=g.useMemo(()=>{if(s==="custom"){if(!i)return;const U=new Date(i);return Number.isNaN(U.getTime())?void 0:U}const z=Lws[s];return z?new Date(Date.now()-z):void 0},[s,i]),c=g.useMemo(()=>{if(s!=="custom"||!o)return;const z=new Date(o);return Number.isNaN(z.getTime())?void 0:z},[s,o]),u=g.useRef(s);u.current=s;const d=e.get(TV)||void 0,f=e.get($b)||void 0,h=e.get(_V)||void 0,p=e.get(wy),m=p==="feedback"?"feedback":p==="details"?"details":void 0,v=e.get(cue)==="timeline"?"timeline":"tree",y=e.get(Sy)||void 0,x=e.get(B2),b=g.useMemo(()=>x?x.split(",").filter(Boolean):[],[x]),S=g.useMemo(()=>{const z=e.get(B1);return z&&nys.has(z)?z:"traces"},[e]),k=g.useMemo(()=>aVt.find(z=>z.entityType===e.get(S$)),[e]),j=g.useMemo(()=>{const z=e.get(k$);return z&&iys.has(z)?z:void 0},[e]),C=g.useMemo(()=>_ys(e),[e]),T=g.useMemo(()=>GNe(e),[e]),_=g.useCallback((z,U,G)=>{t(ne=>{const X=new URLSearchParams(ne);return z?X.set(TV,z):X.delete(TV),U?X.set($b,U):X.delete($b),G?X.set(_V,G):X.delete(_V),X.delete(wy),X.delete(Sy),X.delete(B2),X},{replace:!0})},[t]),N=g.useCallback(()=>_(""),[_]),E=g.useCallback(z=>{const U=e.get($b)||null;z!==U&&t(G=>{const ne=new URLSearchParams(G);return z?ne.set($b,z):ne.delete($b),ne.delete(wy),ne.delete(Sy),ne},{replace:!0})},[e,t]),A=g.useCallback(()=>E(null),[E]),P=g.useCallback(z=>{t(U=>{const G=new URLSearchParams(U);return z==="timeline"?G.set(cue,z):G.delete(cue),G},{replace:!0})},[t]),L=g.useCallback(z=>{const U=e.get(wy)||null;z!==U&&t(G=>{const ne=new URLSearchParams(G);return z&&z!=="details"?ne.set(wy,z):ne.delete(wy),ne.delete(Sy),ne},{replace:!0})},[e,t]),F=g.useCallback((z,U)=>{const G=U&&U!=="details"?U:null;z===(e.get($b)||null)&&G===(e.get(wy)||null)&&!e.get(Sy)||t(X=>{const ee=new URLSearchParams(X);return ee.set($b,z),G?ee.set(wy,G):ee.delete(wy),ee.delete(Sy),ee},{replace:!0})},[e,t]),Q=g.useCallback(z=>{const U=e.get(Sy)||null;z!==U&&t(G=>{const ne=new URLSearchParams(G);return z?ne.set(Sy,z):ne.delete(Sy),ne},{replace:!0})},[e,t]),q=g.useCallback(z=>{t(U=>{const G=new URLSearchParams(U);return z.length===0?G.delete(B2):G.set(B2,z.join(",")),G},{replace:!0})},[t]),B=g.useCallback((z,U=[])=>{t(G=>{const ne=new URLSearchParams(G);return qet(ne,z,U),kI(ne),ne},{replace:!0})},[t]),V=B,W=g.useCallback((z,U)=>{if(u.current!=="custom")return;const G=U==="from"?w1:S1;t(ne=>{const X=new URLSearchParams(ne);return z?X.set(G,z.toISOString()):X.delete(G),kI(X),X},{replace:!0})},[t]),M=g.useCallback((z,U)=>{u.current==="custom"&&t(G=>{const ne=new URLSearchParams(G);return z?ne.set(w1,z.toISOString()):ne.delete(w1),U?ne.set(S1,U.toISOString()):ne.delete(S1),kI(ne),ne},{replace:!0})},[t]),K=g.useCallback(z=>{u.current=z,t(U=>{const G=new URLSearchParams(U);return z==="last-7d"?(G.delete(V1),G.delete(w1),G.delete(S1)):z==="custom"?G.set(V1,"custom"):(G.set(V1,z),G.delete(w1),G.delete(S1)),kI(G),G},{replace:!0})},[t]),D=g.useCallback(z=>{t(U=>{const G=new URLSearchParams(U);return z==="traces"?G.delete(B1):G.set(B1,z),kI(G),G},{replace:!0})},[t]),$=g.useCallback(()=>{t(z=>{const U=new URLSearchParams(z);return U.delete(B1),qet(U,[]),kI(U),U},{replace:!0}),r?.()},[t,r]);return{searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,traceIdParam:d,spanIdParam:f,anchorSpanIdParam:h,spanTabParam:m,spanViewParam:v,scoreIdParam:y,highlightSpanIdsParam:b,listMode:S,selectedEntityOption:k,selectedStatus:j,filterTokens:C,filterGroups:T,handleTraceClick:_,handleTraceClose:N,handleSpanChange:E,handleSpanClose:A,handleSpanTabChange:L,handleSpanViewChange:P,handleSpanChangeWithTab:F,handleScoreChange:Q,handleHighlightSpans:q,handleListModeChange:D,handleFilterTokensChange:V,handleDateChange:W,handleDateRangeChange:M,handleDatePresetChange:K,handleRemoveAll:$,applyFilterTokens:B}}function Fws(e){return e.map(t=>({traceId:t.traceId,spanId:t.rootSpanId,parentSpanId:t.parentSpanId,name:K0s(t.name),createdAt:t.createdAt,inputPreview:t.inputPreview,metadata:t.metadata,entityId:t.entityId,entityName:t.entityName,entityType:t.entityType,threadId:t.threadId,resourceId:t.resourceId,environment:t.environment,status:t.status,startedAt:t.startedAt,endedAt:t.endedAt}))}const EUt=1e4;function Bws(e){return e instanceof hv&&e.status>=400&&e.status<500}function Vws(e){return Bws(e)?!1:EUt}function NUt({query:e,orderBy:t,rolling:n=!0,initialAutoRefetch:r=!0,withQueryTrace:s,legacyFilters:i,limit:o,enabled:l}){const[c,u]=g.useState(()=>new Date),[d,f]=g.useState(r),h=d&&!n?m=>Vws(m.state.error):!1,p=$vs({queryOptions:{traceQuery:{refetchInterval:h,refetchOnWindowFocus:d},legacy:{refetchInterval:h,refetchOnWindowFocus:d}},query:t?{...e(c),orderBy:t}:e(c),withQueryTrace:s,legacyFilters:i,limit:o,enabled:l});return g.useEffect(()=>{if(!d||!n||p.error)return;const m=setInterval(()=>u(new Date),EUt);return()=>clearInterval(m)},[d,n,p.error]),{...p,rows:Fws(p.data??[]),autoRefetch:d,setAutoRefetch:f}}const zye="sort",Fye="dir",Uws="page";function qws(e,t,n){const r=e.get(zye);if(!r||!t.includes(r))return n;const i=e.get(Fye)==="desc"?"desc":"asc";return{key:r,direction:i}}function cT({searchParams:e,setSearchParams:t,allowedKeys:n,defaultSort:r}){const s=e.get(zye),i=e.get(Fye),o=g.useMemo(()=>qws(e,n,r),[s,i,n,r]),l=g.useCallback((c,u)=>{t(d=>{const f=new URLSearchParams(d);return f.set(zye,u),f.set(Fye,c),f.delete(Uws),f},{replace:!0})},[t]);return{sort:o,onSortChange:l}}const Qws=new Set(["ObservabilityStorageClickhouseVNext","ObservabilityStorageDuckDB","ObservabilityInMemory","ObservabilitySpanner","ObservabilityStoragePostgresVNext"]),j$=()=>{const{isMastraPlatform:e}=Mz(),{data:t,isLoading:n,error:r}=Dz(),s=t?.observabilityStorageType,i=t?.capabilities?.metrics??(s?Qws.has(s):!1);return{supportsMetrics:e||i,isInMemory:!e&&s==="ObservabilityInMemory",isLoading:!e&&n,error:e?void 0:r}};function Us({value:e,className:t}){return a.jsx(Cl,{code:JSON.stringify(e??null,null,2),lang:"json","data-slot":"span-payload-json",className:Z(pr,"rounded-lg p-3 text-wrap break-all text-muted-foreground",t,"text-caption")})}function dAe({value:e}){if(typeof e!="object"||e===null||Array.isArray(e))return a.jsx(Us,{value:e});const t=e,n=t.url??t.image??t.data,r=t.mediaType??t.mimeType;if(typeof n!="string"||!/^https?:\/\//i.test(n))return a.jsx(Us,{value:e});try{const i=new URL(n);if(i.username||i.password)return a.jsx(Us,{value:e})}catch{return a.jsx(Us,{value:e})}const s=typeof t.filename=="string"?t.filename:typeof t.name=="string"?t.name:void 0;return a.jsx(XE,{type:t.type==="image"||typeof r=="string"&&r.startsWith("image/")?"image":"file",contentType:typeof r=="string"?r:void 0,src:n,name:s})}const xtt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function AUt({value:e,showLabel:t=!0}){if(!xtt(e))return a.jsx(Us,{value:e});const n=e.type==="tool-invocation"?e.toolInvocation:e;if(!xtt(n)||typeof n.toolName!="string"||!n.toolName)return a.jsx(Us,{value:e});const r="args"in n?n.args:n.input,s="result"in n?n.result:n.output,i=n.isError===!0||n.state==="output-error",o=typeof n.errorText=="string"?n.errorText:void 0,{icon:l,label:c,detail:u,description:d}=W_(n.toolName,r),f=r!==void 0||s!==void 0||o!==void 0;return a.jsxs("div",{"data-slot":"span-payload-tool",className:"flex flex-col gap-2",children:[t&&a.jsx(BD,{children:e.type==="tool-result"?"Tool result":"Tool call"}),a.jsx(jTe,{status:i?"error":"idle",header:a.jsx(pX,{icon:a.jsx(l,{"aria-hidden":!0}),label:c,detail:u,description:d}),children:f&&a.jsxs("div",{className:"flex flex-col gap-3",children:[r!==void 0&&a.jsx(lp,{label:"Arguments",children:a.jsx(Us,{value:r})}),s!==void 0&&a.jsx(lp,{label:"Result",children:a.jsx(Us,{value:s})}),o!==void 0&&a.jsx(lp,{label:"Error",children:a.jsx(Us,{value:o})})]})})]})}function BD({children:e}){return a.jsx(Y,{as:"span",variant:"meta",tone:"faint",className:"block uppercase",children:e})}function lp({label:e,children:t}){return a.jsxs("div",{"data-slot":"span-payload-field",className:"flex flex-col gap-1.5",children:[a.jsx(BD,{children:e}),t]})}function dk({children:e}){return a.jsx("div",{"data-slot":"span-payload-markdown",className:"text-foreground",children:a.jsx(_l,{children:e})})}function ym({label:e,children:t,defaultOpen:n=!1}){return a.jsxs(gc,{defaultOpen:n,children:[a.jsxs(Gl,{className:"flex items-center gap-1 text-meta text-placeholder uppercase",children:[a.jsx(Ha,{direction:"right",className:"size-3"}),e]}),a.jsx(Kl,{className:"pt-1.5",children:t})]})}function fAe({toolCalls:e}){return a.jsx("ul",{"data-slot":"span-payload-tool-calls",className:"flex flex-col gap-2",children:e.map((t,n)=>a.jsx("li",{children:a.jsx(AUt,{value:t,showLabel:!1})},n))})}const PW=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Zws(e){const t=e.split(`
@@ -696,7 +696,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
696
696
  ]`,zOs=[{name:"input",description:"What the agent receives. A string or any JSON value.",required:!0},{name:"groundTruth",description:"Expected answer used by scorers.",required:!1},{name:"metadata",description:"Any object, useful for filtering and grouping.",required:!1}];function FOs(){const{isCopied:e,handleCopy:t}=Vm({text:Qtt,showToast:!1});return a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsx(Y,{variant:"column",tone:"ink",className:"flex h-8 items-center",children:"Each item looks like this"}),a.jsx("dl",{className:"divide-y divide-border rounded-lg border border-border",children:zOs.map(n=>a.jsxs("div",{className:"grid grid-cols-[7rem_1fr] gap-3 px-3 py-2.5",children:[a.jsx("dt",{className:Sa({tone:"ink",variant:"meta"}),children:a.jsx(rh,{children:n.name})}),a.jsxs("dd",{className:"flex flex-col items-start gap-1.5 text-muted-foreground",children:[a.jsx(Y,{as:"span",variant:"meta",children:n.description}),n.required?a.jsx($t,{variant:"success",size:"xs",children:"required"}):a.jsx($t,{variant:"neutral",emphasis:"subtle",size:"xs",children:"optional"})]})]},n.name))}),a.jsxs("div",{className:"overflow-hidden rounded-lg border border-border",children:[a.jsxs("div",{className:"flex items-center justify-between border-b border-border bg-card py-1.5 pr-1.5 pl-3",children:[a.jsx(Y,{as:"span",variant:"meta",tone:"muted",font:"mono",children:"example.json"}),a.jsx(ce,{icon:e?a.jsx(ur,{}):a.jsx(Lm,{}),variant:"ghost",size:"sm",onClick:t,children:e?"Copied":"Copy"})]}),a.jsx(Or,{variant:"embedded",language:"json",editable:!1,lineNumbers:!1,showCopyButton:!1,value:Qtt,className:"p-3"})]}),a.jsx(ce,{variant:"ghost",render:a.jsx("a",{href:LOs,target:"_blank",rel:"noopener noreferrer"}),className:"self-start",icon:a.jsx(Zs,{}),children:"Datasets documentation"})]})}const yue=10,BOs=`[
697
697
  { "input": "…", "groundTruth": "…" }
698
698
  ]`,Ztt="flex min-h-0 flex-1 flex-col py-0";function VOs({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:s,pastedText:i,onPastedTextChange:o,validation:l,isImporting:c}){return a.jsxs(Hc,{value:e,defaultTab:"upload",onValueChange:t,className:"flex h-full flex-col gap-3",children:[a.jsxs(Gc,{variant:"pill",children:[a.jsx(si,{value:"upload",children:"Upload file"}),a.jsx(si,{value:"paste",children:"Paste JSON"})]}),a.jsx(No,{value:"upload",className:Ztt,children:n?a.jsx(ZOs,{file:n,validation:l,onReplace:s,isImporting:c}):a.jsx(UOs,{onFileSelect:r,disabled:c})}),a.jsx(No,{value:"paste",className:Ztt,children:a.jsx(Or,{"aria-label":"JSON items",language:"json",lineNumbers:!1,showCopyButton:!1,placeholder:BOs,value:i,onChange:o,editable:!c,className:"min-h-50 flex-1"})})]})}function UOs({onFileSelect:e,disabled:t}){const[n,r]=g.useState(!1),s=g.useCallback(c=>{const u=c.target.files?.[0];u&&e(u),c.target.value=""},[e]),i=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!0)},[]),o=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!1)},[]),l=g.useCallback(c=>{if(c.preventDefault(),c.stopPropagation(),r(!1),t)return;const u=c.dataTransfer.files?.[0];u&&e(u)},[t,e]);return a.jsxs("div",{"data-testid":"json-dropzone",onDragOver:i,onDragLeave:o,onDrop:l,className:Z("relative flex flex-1 flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-card px-4 py-6 text-center","hover:border-success-edge hover:bg-success-subtle",n&&"border-success-edge bg-success-subtle",t&&"cursor-wait opacity-60"),children:[a.jsx("input",{type:"file",accept:".json,application/json","aria-label":"Choose a JSON file",onChange:s,disabled:t,className:"absolute inset-0 cursor-pointer opacity-0"}),a.jsx("div",{className:"flex size-9 items-center justify-center rounded-md border border-border bg-background text-muted-foreground",children:a.jsx(cG,{className:"size-4"})}),a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx(Y,{tone:"ink",children:"Drop a JSON file here"}),a.jsxs(Y,{variant:"caption",tone:"muted",children:["or ",a.jsx("span",{className:"underline",children:"choose a file"})," from your computer"]})]}),a.jsxs(Y,{variant:"meta",tone:"muted",children:[".json · an array of items · up to ",_Ae]})]})}function qOs(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function QOs(e){return typeof e=="string"?e:JSON.stringify(e)??""}function ZOs({file:e,validation:t,onReplace:n,isImporting:r}){const s="rows"in t?t.rows:[],i="total"in t?t.total:0,o=s.slice(0,yue);return a.jsxs("div",{"data-testid":"json-file-card",className:"rounded-lg border border-border",children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[a.jsx(eG,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"caption",tone:"ink",font:"mono",className:"min-w-0 flex-1 truncate",children:e.name}),a.jsx(Y,{as:"span",variant:"meta",tone:"muted",className:"shrink-0",children:qOs(e.size)}),a.jsx(ce,{icon:a.jsx(vx,{}),variant:"ghost",size:"sm",onClick:n,disabled:r,children:"Replace"})]}),o.map(l=>a.jsxs("div",{className:"grid grid-cols-[2rem_1fr_auto] items-center gap-2 border-t border-border px-3 py-1.5",children:[a.jsx(Y,{as:"span",variant:"meta",tone:"muted",children:l.index}),a.jsx(Y,{as:"span",variant:"caption",tone:"ink",font:"mono",className:"truncate",children:QOs(l.input)}),l.hasInput?l.hasGroundTruth?null:a.jsx($t,{variant:"warning",size:"xs",children:"no groundTruth"}):a.jsx($t,{variant:"destructive",size:"xs",children:"no input"})]},l.index)),i>yue&&a.jsxs(Y,{as:"p",variant:"meta",tone:"muted",className:"border-t border-border px-3 py-1.5",children:["+ ",i-yue," more"]})]})}const WOs=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function HOs({datasetId:e,datasetName:t,open:n,onOpenChange:r,onSuccess:s}){const[i,o]=g.useState("upload"),[l,c]=g.useState(null),[u,d]=g.useState(""),[f,h]=g.useState(null),[p,m]=g.useState(""),[v,y]=g.useState(!1),x=g.useRef(0),{batchInsertItems:b}=pl(),S=i==="upload"?u:p,k=g.useMemo(()=>i==="upload"&&f?{status:"error",kind:"parse",message:f}:Wks(S),[i,f,S]),j=g.useCallback(async E=>{const A=++x.current;if(!E.name.toLowerCase().endsWith(".json")){h("Only .json files are supported");return}if(E.size>dqt){h(`File is larger than ${_Ae}`);return}try{const P=await WOs(E);if(A!==x.current)return;c({name:E.name,size:E.size}),d(P),h(null)}catch{if(A!==x.current)return;h("Could not read the file")}},[]),C=g.useCallback(()=>{x.current++,c(null),d(""),h(null)},[]),T=g.useCallback(()=>{x.current++,o("upload"),c(null),d(""),h(null),m("")},[]),_=g.useCallback(()=>{r(!1),setTimeout(T,150)},[r,T]),N=g.useCallback(async()=>{if(k.status==="ready"){y(!0);try{await b.mutateAsync({datasetId:e,items:k.items}),Xe.success(`Imported ${k.total} item${k.total!==1?"s":""}`),s?.(),r(!1),setTimeout(T,150)}catch(E){Xe.error(E instanceof Error?E.message:"Failed to import items")}finally{y(!1)}}},[k,b,e,s,r,T]);return a.jsx(Yr,{open:n,onOpenChange:_,pending:v,children:a.jsxs(Xr,{size:"xl",children:[a.jsxs(Jr,{children:[a.jsx(Zr,{children:"Import into dataset"}),a.jsxs(Lo,{children:["Add items to ",t?a.jsx("span",{className:"text-foreground",children:t}):"this dataset"," from a JSON file or paste them directly."]})]}),a.jsx(Qr,{flush:!0,children:a.jsxs("div",{className:"grid divide-y divide-border md:grid-cols-[1.15fr_1fr] md:divide-x md:divide-y-0",children:[a.jsx("div",{className:"flex min-h-[360px] flex-col p-4",children:a.jsx(VOs,{tab:i,onTabChange:o,file:l,onFileSelect:j,onReplace:C,pastedText:p,onPastedTextChange:m,validation:k,isImporting:v})}),a.jsx("div",{className:"p-4",children:a.jsx(FOs,{})})]})}),a.jsxs(Yo,{children:[a.jsx(GOs,{validation:k}),a.jsx(_a,{children:"Cancel"}),a.jsxs(Ca,{onConfirm:N,disabled:k.status!=="ready",children:[v&&a.jsx(On,{}),k.status==="ready"?`Import ${k.total} item${k.total!==1?"s":""}`:"Import"]})]})]})})}function GOs({validation:e}){const t=Z("size-1.5 shrink-0 rounded-full",e.status==="idle"&&"bg-muted-foreground",e.status==="ready"&&"bg-success-indicator",e.status==="error"&&"bg-destructive-indicator");let n;switch(e.status){case"idle":n="No items yet";break;case"ready":n=a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"b",variant:"label",tone:"ink",children:e.total})," ","item",e.total!==1?"s":""," ready",e.missingGroundTruthCount>0&&` · ${e.missingGroundTruthCount} without groundTruth`]});break;case"error":switch(e.kind){case"parse":n=`Not valid JSON — ${e.message}`;break;case"not-array":n="Top level must be an array of items";break;case"empty":n="The array has no items";break;case"too-large":n=`JSON is larger than ${_Ae}`;break;case"missing-input":n=a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"b",variant:"label",tone:"ink",children:e.missingInputCount})," ","of ",e.total," item",e.total!==1?"s":""," ",e.missingInputCount!==1?"have":"has"," no"," ",a.jsx(rh,{children:"input"})]});break}break}return a.jsxs("div",{role:"status",className:"mr-auto flex min-w-0 items-center gap-2",children:[a.jsx("span",{className:t}),a.jsx(Y,{tone:"muted",as:"span",variant:"caption",className:"truncate",children:n})]})}function KOs(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"?!0:!!e.closest('[role="dialog"]:not([data-item-panel])')}function yqt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=i=>{i.defaultPrevented||KOs(i.target)||(i.key==="PageUp"?(i.preventDefault(),t?.()):i.key==="PageDown"?(i.preventDefault(),n?.()):i.key==="Escape"&&(i.preventDefault(),r()))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,n,r])}const xqt=g.createContext(null);function YOs({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=Lr(),o=d0e("/datasets/:datasetId/items/:itemId")?.params.itemId,l=g.useCallback(p=>{s(`/datasets/${e}/items/${encodeURIComponent(p)}`)},[s,e]),c=g.useCallback(()=>{s(`/datasets/${e}`)},[s,e]),u=g.useMemo(()=>o?t.findIndex(p=>p.id===o):-1,[t,o]),d=g.useMemo(()=>{if(u<=0)return;const p=t[u-1].id;return()=>l(p)},[u,t,l]),f=g.useMemo(()=>{if(u<0||u>=t.length-1)return;const p=t[u+1].id;return()=>l(p)},[u,t,l]);yqt({active:!!o,onPrevious:d,onNext:f,onClose:c});const h=g.useMemo(()=>({datasetId:e,items:t,isLoadingItems:n,currentItemId:o,openItem:l,close:c,goToPreviousItem:d,goToNextItem:f}),[e,t,n,o,l,c,d,f]);return a.jsx(xqt.Provider,{value:h,children:r})}function bqt(){const e=g.useContext(xqt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}const XOs=["createdAt"];function JOs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s,belowToolbarSlot:i}){const[o,l]=wi(),{activeVersion:c}=TAe(o,l),{sort:u,onSortChange:d}=cT({searchParams:o,setSearchParams:l,allowedKeys:XOs}),f=g.useMemo(()=>u?{field:u.key,direction:u.direction==="asc"?"ASC":"DESC"}:void 0,[u]),[h,p]=g.useState(!1),[m,v]=g.useState(!1),[y,x]=g.useState(!1),[b,S]=g.useState([]),[k,j]=g.useState(!1),[C,T]=g.useState([]),[_,N]=g.useState(!1),[E,A]=g.useState([]),[P,L]=g.useState(0),[F,Q]=g.useState(""),[q]=YY(F,300),{data:B}=Vv({datasetId:e,queryOptions:{enabled:!!e}}),{data:V=[],isLoading:W,setEndOfListElement:M,isFetchingNextPage:K,hasNextPage:D}=oA({datasetId:e,search:q||void 0,version:c,orderBy:f,queryOptions:{enabled:!!e}}),{deleteItems:$}=pl(),{currentItemId:z,openItem:U,close:G}=bqt(),ne=ae=>{z===ae?G():U(ae)},X=ae=>{S(ae),x(!0)},ee=ae=>{T(ae),j(!0)},re=ae=>{j(ae),ae||(T([]),L(he=>he+1))},ue=ae=>{A(ae),N(!0)},te=async()=>{await $.mutateAsync({datasetId:e,itemIds:E}),Xe.success(`Deleted ${E.length} items`),N(!1),A([]),L(ae=>ae+1)},ie=ae=>{x(!1),S([]),L(he=>he+1),n?.(ae)},se=ae=>{x(ae),ae||(S([]),L(he=>he+1))};return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid h-full overflow-auto",children:a.jsx(DOs,{items:V,leftSlot:r,rightSlot:s,belowToolbarSlot:i,isLoading:W,onItemClick:ne,featuredItemId:z,onAddClick:t??(()=>{}),onImportClick:()=>p(!0),onImportJsonClick:()=>v(!0),onBulkDeleteClick:ue,onCreateDatasetClick:X,onAddToDatasetClick:ee,datasetName:B?.name,clearSelectionTrigger:P,setEndOfListElement:M,isFetchingNextPage:K,hasNextPage:D,searchQuery:F,activeSearchQuery:q,onSearchChange:Q,sort:u,onSortChange:d,currentDatasetVersion:B?.version})}),a.jsx(EOs,{datasetId:e,open:h,onOpenChange:p}),a.jsx(HOs,{datasetId:e,datasetName:B?.name,open:m,onOpenChange:v}),a.jsx(dOs,{open:y,onOpenChange:se,items:b,onSuccess:ie}),a.jsx(fOs,{open:k,onOpenChange:re,items:C,currentDatasetId:e}),a.jsx(Bt,{open:_,onOpenChange:N,children:a.jsxs(Bt.Content,{children:[a.jsxs(Bt.Header,{children:[a.jsx(Bt.Title,{children:"Delete Items"}),a.jsxs(Bt.Description,{children:["Are you sure you want to delete ",E.length," item",E.length!==1?"s":"","? This action cannot be undone."]})]}),a.jsxs(Bt.Footer,{children:[a.jsx(Bt.Cancel,{children:"Cancel"}),a.jsx(Bt.Action,{onClick:te,children:$.isPending?"Deleting...":"Delete"})]})]})})]})}const Wtt="__create_tag__";function ejs({datasetId:e}){const{data:t}=Vv({datasetId:e,queryOptions:{enabled:!!e}}),{data:n}=Ak(),{updateDataset:r}=pl(),[s,i]=g.useState(""),o=g.useMemo(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),l=g.useMemo(()=>iqt(n?.datasets??[]),[n?.datasets]),c=g.useMemo(()=>{const h=l.map(v=>({label:v,value:v,end:o.includes(v)?a.jsx(ur,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),p=s.trim();return p.length>0&&!l.includes(p)&&!o.includes(p)?[{label:`Create "${p}"`,value:Wtt},...h]:h},[l,o,s]),u=h=>{r.mutate({datasetId:e,tags:h},{onError:()=>Xe.error("Failed to update tags")})},d=h=>{const p=h===Wtt?s.trim():h;!p||o.includes(p)||u([...o,p])},f=h=>{u(o.filter(p=>p!==h))};return a.jsxs("div",{"data-testid":"dataset-tags-editor",className:"flex flex-wrap items-center gap-2",children:[o.map(h=>a.jsxs(oee,{value:h,size:"md",className:"gap-1 pr-1",children:[h,a.jsx("button",{type:"button","aria-label":`Remove tag ${h}`,disabled:r.isPending,onClick:()=>f(h),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:a.jsx(Mn,{className:"size-3"})})]},h)),a.jsx(fl,{options:c,value:void 0,onValueChange:d,onInputValueChange:i,placeholder:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(Px,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",size:"sm",className:"w-auto min-w-0",disabled:r.isPending})]})}function wqt({overrideEnabled:e,onOverrideEnabledChange:t,selectedScorerIds:n,onSelectedScorerIdsChange:r,disabled:s=!1}){return a.jsxs("div",{className:"grid gap-3",children:[a.jsxs(pt,{orientation:"horizontal",disabled:s,className:"gap-3",children:[a.jsx(pc,{checked:e,onCheckedChange:t}),a.jsx(dt,{children:"Override dataset scorers"})]}),a.jsx(Y,{variant:"caption",tone:"muted",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?a.jsx(lee,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function iN({field:e,errors:t}){return t.length===0?null:a.jsx(ns,{children:a.jsx("span",{className:"space-y-1",children:t.map(n=>a.jsxs("span",{className:"block",children:[a.jsxs("code",{className:"rounded bg-destructive-subtle px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},`${n.path}:${n.message}`))})})}function tjs(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 njs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,i]=g.useState("{}"),[o,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[h,p]=g.useState(!1),[m,v]=g.useState([]),[y,x]=g.useState(""),[b,S]=g.useState(null),{addItem:k}=pl(),j=()=>{i("{}"),l(""),u(""),f(""),p(!1),v([]),x(""),S(null)},C=P=>{j(),n(P)},T=async P=>{P.preventDefault();let L;try{L=JSON.parse(s)}catch{Xe.error("Input must be valid JSON");return}let F;if(o.trim())try{F=JSON.parse(o)}catch{Xe.error("Ground Truth must be valid JSON");return}let Q;if(c.trim())try{Q=JSON.parse(c)}catch{Xe.error("Expected Trajectory must be valid JSON");return}let q;if(d.trim())try{const V=JSON.parse(d);if(!Array.isArray(V)){Xe.error("Tool Mocks must be a JSON array");return}q=V}catch{Xe.error("Tool Mocks must be valid JSON");return}let B;if(y.trim())try{B=JSON.parse(y)}catch{Xe.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:L,groundTruth:F,expectedTrajectory:Q,toolMocks:q,scorerIds:h?m:void 0,requestContext:B}),Xe.success("Item added successfully"),C(!1),r?.()}catch(V){const W=tjs(V);W?S(W):Xe.error(`Failed to add item: ${V instanceof Error?V.message:"Unknown error"}`)}},_=P=>{i(P),b?.field==="input"&&S(null)},N=P=>{l(P),b?.field==="groundTruth"&&S(null)},E=P=>{f(P),b?.field==="toolMocks"&&S(null)},A=()=>{C(!1)};return a.jsxs(xo,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[a.jsx(xo.Top,{children:"Add Item"}),a.jsxs(xo.Content,{children:[a.jsx(xo.Header,{children:a.jsx(xo.Heading,{children:"Add Item"})}),a.jsxs(Ga,{onSubmit:T,children:[a.jsxs(pt,{invalid:b?.field==="input",children:[a.jsx(dt,{required:!0,children:"Input (JSON)"}),a.jsx(Or,{value:s,onChange:_,showCopyButton:!1,className:"min-h-[240px]"}),b?.field==="input"&&a.jsx(iN,{field:"input",errors:b.errors})]}),a.jsxs(pt,{invalid:b?.field==="groundTruth",children:[a.jsx(dt,{children:"Ground Truth (JSON, optional)"}),a.jsx(Or,{value:o,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),b?.field==="groundTruth"&&a.jsx(iN,{field:"groundTruth",errors:b.errors})]}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Expected Trajectory (JSON, optional)"}),a.jsx(Or,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),a.jsxs(pt,{invalid:b?.field==="toolMocks",children:[a.jsx(dt,{children:"Tool Mocks (JSON array, optional)"}),a.jsx(Or,{value:d,onChange:E,showCopyButton:!1,className:"min-h-[200px]"}),b?.field==="toolMocks"&&a.jsx(iN,{field:"toolMocks",errors:b.errors})]}),a.jsx(wqt,{overrideEnabled:h,onOverrideEnabledChange:p,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Request Context (JSON, optional)"}),a.jsx(Or,{value:y,onChange:x,showCopyButton:!1,className:"min-h-[200px]"})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[a.jsx(ce,{icon:a.jsx(Mn,{}),type:"button",onClick:A,children:"Cancel"}),a.jsx(ce,{icon:a.jsx(Dr,{}),type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}const BO=e=>JSON.stringify(e??null,null,2),rjs=[{key:"input",title:"Input",icon:a.jsx(I4,{}),value:e=>BO(e.input)},{key:"groundTruth",title:"Ground Truth",icon:a.jsx(Lj,{}),value:e=>BO(e.groundTruth)},{key:"expectedTrajectory",title:"Expected Trajectory",icon:a.jsx(Swe,{}),value:e=>e.expectedTrajectory!=null?BO(e.expectedTrajectory):void 0},{key:"toolMocks",title:"Tool Mocks",icon:a.jsx(dd,{}),value:e=>BO(e.toolMocks??[])},{key:"scorerIds",title:"Scorers",icon:a.jsx(dpt,{}),value:e=>e.scorerIds===void 0?"Inherited from dataset":BO(e.scorerIds)},{key:"requestContext",title:"Request Context",icon:a.jsx(Va,{}),value:e=>e.requestContext!=null?BO(e.requestContext):void 0},{key:"metadata",title:"Metadata",icon:a.jsx(Px,{}),value:e=>BO(e.metadata)}];function Zye({item:e,diff:t}){return a.jsxs(a.Fragment,{children:[a.jsxs(Kt,{children:[a.jsx(Kt.Key,{children:"Dataset Id"}),a.jsx(Kt.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:e.datasetId,children:e.datasetId}),a.jsx(Kt.Key,{children:"Version"}),a.jsxs(Kt.Value,{children:["v",e.datasetVersion]}),a.jsx(Kt.Key,{children:"Created"}),a.jsx(Kt.Value,{children:rs(e.createdAt,"date-time")}),a.jsx(Kt.Key,{children:"Updated"}),a.jsx(Kt.Value,{children:e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime()?rs(e.updatedAt,"date-time"):"n/a"})]}),a.jsx("div",{className:"mt-3 grid gap-3",children:rjs.map(n=>{const r=n.value(e),s=t?n.value(t.against):void 0;return r===void 0&&s===void 0?null:a.jsx(_t.CodeSection,{title:n.title,icon:n.icon,codeStr:r??"",diff:t?{against:s??"",side:t.side}:void 0},n.key)})})]})}function sjs({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:s,setMetadataValue:i,trajectoryValue:o,setTrajectoryValue:l,toolMocksValue:c,setToolMocksValue:u,scorerOverrideEnabled:d,setScorerOverrideEnabled:f,selectedScorerIds:h,setSelectedScorerIds:p,requestContextValue:m,setRequestContextValue:v,validationErrors:y,onSave:x,onCancel:b,isSaving:S}){return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"mb-4",children:a.jsxs(Y,{as:"h3",variant:"heading",className:"flex items-center gap-2",children:[a.jsx(Vc,{className:"h-5 w-5"})," Edit Item"]})}),a.jsxs("div",{className:"space-y-6",children:[a.jsxs(pt,{invalid:y?.field==="input",children:[a.jsx(dt,{required:!0,children:"Input (JSON)"}),a.jsx(Or,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&a.jsx(iN,{field:"input",errors:y.errors})]}),a.jsxs(pt,{invalid:y?.field==="groundTruth",children:[a.jsx(dt,{children:"Ground Truth (JSON, optional)"}),a.jsx(Or,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&a.jsx(iN,{field:"groundTruth",errors:y.errors})]}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Expected Trajectory (JSON, optional)"}),a.jsx(Or,{value:o,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs(pt,{invalid:y?.field==="toolMocks",children:[a.jsx(dt,{children:"Tool Mocks (JSON array, optional)"}),a.jsxs(no,{children:["Ordered static mocks served in place of executing the tool. Each entry is"," ",a.jsx("code",{children:'{ "toolName", "args", "output" }'}),". Calling a mocked tool with non-matching args fails the item; unmocked tools run live."]}),a.jsx(Or,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&a.jsx(iN,{field:"toolMocks",errors:y.errors})]}),a.jsx(wqt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:h,onSelectedScorerIdsChange:p,disabled:S}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Request Context (JSON, optional)"}),a.jsx(Or,{value:m,onChange:v,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Metadata (JSON, optional)"}),a.jsx(Or,{value:s,onChange:i,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs("div",{className:"flex gap-2 pt-4",children:[a.jsx(ce,{icon:a.jsx(ur,{}),variant:"primary",onClick:x,disabled:S,children:S?"Saving...":"Save Changes"}),a.jsx(ce,{icon:a.jsx(Mn,{}),onClick:b,disabled:S,children:"Cancel"})]})]})]})}const ijs=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function ojs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,onTargetNameChange:s,container:i}){const{data:o,isLoading:l}=Cp(),{data:c,isLoading:u}=tg({}),{data:d,isLoading:f}=Bx(),h=e==="agent"?Object.entries(o??{}).map(([x,b])=>({value:x,label:b.name??x})):e==="workflow"?Object.entries(c??{}).map(([x,b])=>({value:x,label:b.name??x})):e==="scorer"?Object.entries(d??{}).map(([x,b])=>({value:x,label:b.scorer?.config?.name??x})):[],p=e==="agent"&&l||e==="workflow"&&u||e==="scorer"&&f,m=x=>{t(x),r(""),s?.(void 0)},v=x=>{r(x),s?.(h.find(b=>b.value===x)?.label||x)},y=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs(pt,{children:[a.jsx(dt,{children:"Target Type"}),a.jsx(fl,{options:ijs,value:e,onValueChange:m,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:i})]}),e&&a.jsxs(pt,{children:[a.jsx(dt,{children:y}),a.jsx(fl,{options:h,value:n,onValueChange:v,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:i})]})]})}function Sqt(e){return e?Yks(e,fqt()):""}function Htt(e){return{name:e.name??Sqt(e.targetId),description:e.description??"",datasetId:e.datasetId??"",version:e.version,targetType:e.targetType??"",targetId:e.targetId??"",scorerIds:e.scorerIds,requestContextValues:{},requestContextRaw:""}}function ajs(e){const t=zx({defaultValues:Htt(e)});return{form:t,changeTargetName:s=>{e.name!==void 0||t.getValues("name")!==t.formState.defaultValues?.name||t.resetField("name",{defaultValue:Sqt(s)})},resetForm:()=>t.reset(Htt(e))}}const ljs=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function cjs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return MS(e)}catch(r){return console.error("Failed to parse requestContextSchema:",r),null}},[e]);return n?a.jsxs(E0,{children:[a.jsx(OC,{children:"Request Context"}),a.jsx(bke,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):a.jsx("div",{role:"alert",children:a.jsx(Wt,{variant:"destructive",children:"Failed to parse request context schema"})})}function xue({index:e,done:t,isLast:n,children:r}){return a.jsxs("li",{className:"flex gap-4",children:[a.jsxs("div",{className:"flex flex-col items-center",children:[a.jsx(Y,{as:"span",variant:"meta",tone:"muted","aria-hidden":"true",className:Z("flex size-6 shrink-0 items-center justify-center rounded-full border",t?"border-success-edge bg-success-subtle text-success-subtle-foreground":"border-border"),children:e}),!n&&a.jsx("span",{"aria-hidden":"true",className:"mt-2 w-px flex-1 bg-border"})]}),a.jsx("div",{className:Z("min-w-0 flex-1 space-y-3",!n&&"pb-4"),children:r})]})}function cee({initialDatasetId:e,initialDatasetVersion:t,initialScorerIds:n,initialTargetType:r,initialTargetId:s,initialName:i,initialDescription:o,open:l,onOpenChange:c,onSuccess:u}){const d=g.useRef(null),{form:f,changeTargetName:h,resetForm:p}=ajs({name:i,description:o,datasetId:e,version:t,targetType:r,targetId:s,scorerIds:n}),{register:m,setValue:v,watch:y}=f,[x,b,S,k,j,C,T,_]=y(["name","datasetId","version","targetType","targetId","scorerIds","requestContextValues","requestContextRaw"]),{triggerExperiment:N}=pl(),{data:E}=Vv({datasetId:b,queryOptions:{enabled:!!b}}),{total:A}=oA({datasetId:b,search:void 0,version:S,queryOptions:{enabled:!!b}}),P=E?.requestContextSchema,L=E?.scorerIds??[],F=C===void 0&&L.length>0,Q=C??L,q=!!(P&&Object.keys(P).length>0),B=x.trim(),V=!!(b&&k&&j&&B),W=N.isPending,M=[!b&&"dataset",!j&&"target",j&&!B&&"name"].filter(Boolean),K=q?Object.values(T).some(ne=>ne!==void 0&&ne!==""):_.trim().length>0,D=ne=>{v("datasetId",ne),v("version",void 0),v("scorerIds",n),v("requestContextValues",{})},$=()=>{if(q){const ne=Object.entries(T).filter(([,X])=>X!==void 0&&X!=="");return ne.length>0?Object.fromEntries(ne):void 0}if(_.trim()){let ne;try{ne=JSON.parse(_)}catch{throw new Error("Request Context must be valid JSON")}if(!ne||typeof ne!="object"||Array.isArray(ne))throw new Error("Request Context must be a JSON object");return ne}},z=f.handleSubmit(async({description:ne})=>{if(!b||!k||!j||!B)return;let X;try{X=$()}catch(ee){const re=ee instanceof Error?ee.message:"Request Context must be valid JSON";Su.error(re);return}try{const ee=await N.mutateAsync({datasetId:b,name:B,description:ne.trim()||void 0,targetType:k,targetId:j,scorerIds:Q.length>0?Q:void 0,version:S,requestContext:X});Su.success("Experiment triggered successfully"),c(!1),u?.(ee.experimentId),p()}catch(ee){const re=ee instanceof Error?ee.message:"Failed to trigger experiment";Su.error(re)}}),U=()=>{c(!1),p()},G=ne=>{(ne.metaKey||ne.ctrlKey)&&ne.key==="Enter"&&V&&!W&&(ne.preventDefault(),z())};return a.jsx(Yr,{open:l,onOpenChange:U,pending:W,children:a.jsxs(Xr,{ref:d,size:"lg",onKeyDown:G,children:[a.jsxs(Jr,{children:[a.jsx(Zr,{children:"Run experiment"}),a.jsx(Lo,{children:"Pick a dataset, choose what to run it against, and optionally score the results."})]}),a.jsxs(Qr,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs(pt,{children:[a.jsx(dt,{children:"Name"}),a.jsx(bn,{...m("name"),placeholder:"Enter experiment name",autoFocus:!0,disabled:W})]}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Description"}),a.jsx(Pu,{...m("description"),placeholder:"Enter experiment description (optional)",disabled:W,rows:2})]})]}),a.jsxs("ol",{className:"list-none",children:[a.jsxs(xue,{index:1,done:!!b,children:[a.jsxs("div",{className:"grid grid-cols-[1fr_140px] gap-3",children:[a.jsxs(pt,{children:[a.jsx(dt,{children:"Dataset"}),a.jsx(GOt,{value:b,onValueChange:D,container:d})]}),b&&a.jsxs(pt,{children:[a.jsx(dt,{children:"Version"}),a.jsx(vqt,{datasetId:b,value:S??null,onValueChange:ne=>v("version",ne??void 0),container:d})]})]}),b&&A!==void 0&&a.jsxs(Y,{variant:"meta",tone:"muted",children:[A," ",A===1?"item":"items"]})]}),a.jsxs(xue,{index:2,done:!!j,children:[a.jsx(ojs,{targetType:k,setTargetType:ne=>v("targetType",ne),targetId:j,setTargetId:ne=>v("targetId",ne),onTargetNameChange:h,container:d}),k&&!j&&a.jsxs(Y,{variant:"meta",tone:"muted",children:["Choose ",k==="agent"?"an":"a"," ",k," to run"]})]}),a.jsx(xue,{index:3,done:Q.length>0,isLast:!0,children:a.jsx(lee,{selectedScorers:Q,setSelectedScorers:ne=>v("scorerIds",ne),disabled:W,container:d,helperText:F?"Pre-filled from the dataset's default scorers.":"Scores are computed after each item runs."})})]}),a.jsxs(gc,{children:[a.jsxs(Gl,{className:"flex items-center gap-2 text-caption",children:[a.jsx(Ha,{direction:"right",className:"size-4"}),"Request Context (JSON, optional)",K&&a.jsx($t,{size:"xs",variant:"blue",children:"set"})]}),a.jsx(Kl,{className:"pt-3",children:q?a.jsx(cjs,{requestContextSchema:P,onChange:ne=>v("requestContextValues",ne)}):a.jsx(Or,{value:_,onChange:ne=>v("requestContextRaw",ne),showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),a.jsxs(Yo,{children:[a.jsx("p",{"data-testid":"experiment-run-status","aria-live":"polite",className:"mr-auto flex items-center gap-2",children:M.length===0?a.jsxs(a.Fragment,{children:[a.jsx($t,{variant:"success",indicator:"dot",children:"Ready"}),a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",children:[A??0," items · ",k," · ",Q.length," scorers"]})]}):a.jsxs($t,{variant:"neutral",indicator:"dot",children:["Missing ",M.join(", ")]})}),a.jsx(_a,{children:"Cancel"}),a.jsx(Ca,{onConfirm:z,disabled:!V,children:W?a.jsxs(a.Fragment,{children:[a.jsx(On,{className:"h-4 w-4"}),"Running..."]}):a.jsxs(a.Fragment,{children:["Run",a.jsxs("span",{className:"ml-1 inline-flex gap-0.5","aria-hidden":"true",children:[a.jsx(Hd,{size:"xs",children:ljs?"⌘":"Ctrl"}),a.jsx(Hd,{size:"xs",children:"↵"})]})]})})]})]})})}const Wye="mastra_model_total_input_tokens",kqt="mastra_model_total_output_tokens",ujs=2e3,Gtt=()=>({estimatedCost:0,costUnits:new Set,hasUnknownCostUnit:!1});function Ktt(e,t,n){e[t]=(e[t]??0)+n.value,n.estimatedCost!=null&&(e.estimatedCost+=n.estimatedCost,n.costUnit?e.costUnits.add(n.costUnit.toLowerCase()):e.hasUnknownCostUnit=!0)}function Ytt(e){const t=!e.hasUnknownCostUnit&&e.costUnits.size===1;return{inputTokens:e.inputTokens,outputTokens:e.outputTokens,estimatedCost:t?e.estimatedCost:void 0,costUnit:t?[...e.costUnits][0]:void 0}}function djs(e){const t=Gtt(),n=new Map;for(const s of e.groups){const i=s.dimensions.name;if(i!==Wye&&i!==kqt)continue;const o=i===Wye?"inputTokens":"outputTokens";Ktt(t,o,s);const l=s.dimensions.traceId;l&&Ktt(HJ(n,l,Gtt),o,s)}const r={};for(const[s,i]of n)r[s]=Ytt(i);return{summary:Ytt(t),traces:r}}const IAe=({experiments:e,supportsMetrics:t})=>{const n=Ke(),r=PK(e.map(s=>s.id));return Rm({queries:e.map(({id:s,status:i})=>({queryKey:["experiment-item-usage",s],queryFn:async()=>djs(await n.getMetricBreakdown({name:[Wye,kqt],aggregation:"sum",groupBy:["traceId","name"],filters:{experimentId:s}})),enabled:t,refetchInterval:i==="running"||i==="pending"?ujs:!1})),combine:r})},fjs=({experimentId:e,experimentStatus:t,supportsMetrics:n,queryOptions:r})=>{const s=Ke(),i=!!e&&n,o=Ct({queryKey:["experiment-metrics",e],refetchInterval:t==="running"||t==="pending"?2e3:!1,queryFn:async()=>{if(!e)throw new Error("experimentId is required");const l={experimentId:e},[c,u,d]=await Promise.all([s.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:l}),s.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"avg",filters:l}),s.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:l})]);return{totalTokens:c.value??null,estimatedCost:c.estimatedCost??null,costUnit:c.costUnit??null,avgAgentDurationMs:u.value??null,agentRuns:d.value??null}},...r});return{data:o.data,isLoading:o.isLoading,isEnabled:i}},hjs=({traceId:e,queryOptions:t})=>{const n=Ke();return Ct({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return n.getTraceLight(e)},...t})};function Oqt({datasetId:e,target:t,queryOptions:n}){const r=Ke(),s={perPage:100};return t?.targetType&&(s.targetType=t.targetType),t?.targetId&&(s.targetId=t.targetId),Ct({queryKey:["experiments",s],queryFn:()=>r.listExperiments(s),...n})}function pjs({datasetId:e,target:t,orderBy:n,queryOptions:r}){const s=Ke(),{inView:i,setRef:o}=X0(),l=t?.targetType||void 0,c=t?.targetId||void 0,u=Mm({queryKey:e?["dataset-experiments",e,"infinite",{targetType:l,targetId:c,orderBy:n}]:["experiments","infinite",{targetType:l,targetId:c,orderBy:n}],queryFn:({pageParam:d})=>{const f={page:d,perPage:100};return l&&(f.targetType=l),c&&(f.targetId=c),n&&(f.orderBy=n),e?s.listDatasetExperiments(e,f):s.listExperiments(f)},initialPageParam:0,getNextPageParam:(d,f,h)=>{if(!(!d?.experiments?.length||!d.pagination?.hasMore))return h+1},select:d=>d.pages.flatMap(f=>f?.experiments??[]),...r});return g.useEffect(()=>{i&&u.hasNextPage&&!u.isFetchingNextPage&&u.fetchNextPage()},[i,u]),{...u,setEndOfListElement:o}}const jqt=g.createContext(null);function mjs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:i,children:o}){const l=Lr(),u=d0e("/experiments/:experimentId/items/:itemId")?.params.itemId,d=g.useCallback(y=>{l(`/experiments/${e}/items/${encodeURIComponent(y)}`)},[l,e]),f=g.useCallback(()=>{l(`/experiments/${e}`)},[l,e]),h=g.useMemo(()=>u?r.findIndex(y=>y.itemId===u):-1,[r,u]),p=g.useMemo(()=>{if(h<=0)return;const y=r[h-1].itemId;return()=>d(y)},[h,r,d]),m=g.useMemo(()=>{if(h<0||h>=r.length-1)return;const y=r[h+1].itemId;return()=>d(y)},[h,r,d]);yqt({active:!!u,onPrevious:p,onNext:m,onClose:f});const v=g.useMemo(()=>({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:i,currentItemId:u,openItem:d,close:f,goToPreviousItem:p,goToNextItem:m}),[e,t,n,r,s,i,u,d,f,p,m]);return a.jsx(jqt.Provider,{value:v,children:o})}function EAe(){const e=g.useContext(jqt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}function Hye(e,t){if(!e||typeof e!="object"||!(t in e))return;const n=e[t];return typeof n=="string"&&n?n:void 0}function NAe(e){if(e.targetType==="agent")return Hye(e.output,"text")}function Cqt(e){if(e.targetType)return NAe(e);const{output:t}=e;if(!(t==null||t===""))return typeof t=="string"?t:JSON.stringify(t)}function gjs(e){const t=[];return e.some(n=>Cqt(n))&&t.push({name:"output",label:"Output",size:"20rem"}),e.some(n=>uee(n))&&t.push({name:"error",label:"Error",size:"20rem"}),t}function uee(e){const t=Hye(e.error,"message");if(t)return t;if(!(e.targetType!=="agent"||!e.output||typeof e.output!="object"))return Hye(e.output.error,"message")}const VD=e=>e!=null?e.toFixed(2):"-",_qt=e=>Uc(e)??"-",vjs=(e,t)=>e!=null&&t!=null?e-t:null,yjs=new Set(Intl.supportedValuesOf("currency")),zz=(e,t)=>{if(e===void 0)return"-";const n=e!==0&&Math.abs(e)<1?{maximumSignificantDigits:3}:{minimumFractionDigits:2,maximumFractionDigits:2},r=(t??"usd").toUpperCase();return yjs.has(r)?new Intl.NumberFormat("en-US",{style:"currency",currency:r,...n}).format(e):`${new Intl.NumberFormat("en-US",n).format(e)} ${t}`},Tqt=e=>t=>zz(t,e),xjs=new Intl.NumberFormat("en-US"),aS=e=>e!==void 0?xjs.format(e):"-",WA=e=>{if(!(e?.inputTokens===void 0&&e?.outputTokens===void 0))return(e.inputTokens??0)+(e.outputTokens??0)};function Iqt({scorerId:e,reason:t,nested:n=!1}){const r="text-muted-foreground hover:text-foreground [&>svg]:size-3.5";return a.jsxs(Uk,{children:[a.jsx(yw,{delay:0,closeDelay:100,render:n?a.jsx("span",{"aria-hidden":!0,"data-testid":`score-reason-${e}`,className:`flex ${r}`}):a.jsx("button",{type:"button","aria-label":`Show ${e} reason`,className:`cursor-pointer ${r}`}),children:a.jsx(yv,{})}),a.jsx(xw,{side:"left",align:"start",className:"max-h-80 max-w-100 overflow-y-auto",onClick:s=>s.stopPropagation(),children:a.jsx(_l,{children:t})})]})}const bjs=new Set(["itemId","id","status","input","output","error","tags","scores","cost","tokens","duration"]);function Eqt({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:i,scorerIds:o,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,emptyMessage:d="No results yet",selectedIds:f,onToggleSelect:h,onToggleSelectAll:p}){const{Link:m,paths:v}=Sn(),y=!!(f&&h),x=s.filter(W=>bjs.has(W.name)||o?.includes(W.name)),b=[y?"2rem":"",...x.map(W=>W.size)].filter(Boolean).join(" "),S=W=>x.some(M=>M.name===W),k=S("itemId")||S("id"),j=S("status"),C=S("input"),T=S("output"),_=S("error"),N=S("tags"),E=S("scores"),A=S("cost"),P=S("tokens"),L=S("duration"),F=f?e.filter(W=>f.has(W.id)).length:0,Q=e.length>0&&F===e.length,{containerRef:q,getRowProps:B}=Fu({count:e.length}),V=W=>o?.includes(W.name)?a.jsx(Te.TopCell,{children:a.jsxs(m,{href:v.scorerLink(W.name),className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[a.jsx(rw,{}),a.jsx("span",{className:"min-w-0 truncate",children:W.label})]})},W.name):a.jsx(Te.TopCell,{children:W.label},W.name);return t?a.jsx(Lu,{columns:b}):a.jsxs(Te,{columns:b,className:"min-w-0",scrollRef:q,children:[a.jsxs(Te.Top,{hasLeadingCell:y,children:[y&&(p?a.jsx(Te.TopSelectCell,{checked:Q?!0:F>0?"indeterminate":!1,onToggle:p,"aria-label":"Select all"}):a.jsx(Te.TopCell,{children:" "})),y?a.jsx(Te.TopCells,{colStart:2,children:x.map(V)}):x.map(V)]}),e.length===0?a.jsx(Te.NoMatch,{message:d}):a.jsxs(a.Fragment,{children:[e.map((W,M)=>{const K=!!W.error,D=W.id===n,$=a.jsxs(a.Fragment,{children:[k&&a.jsx(Te.Cell,{className:"text-muted-foreground",children:W.itemId?.slice(0,8)??""}),j&&a.jsx(Te.Cell,{className:"flex items-center","data-testid":`result-status-${W.id}`,children:W.status?a.jsx(lAe,{status:W.status}):a.jsx("span",{className:"text-placeholder",children:"—"})}),C&&a.jsx(Te.TextCell,{font:"mono",children:Ojs(kjs(W.input),200)}),T&&a.jsx(Te.Cell,{className:"truncate font-mono","data-testid":`result-output-${W.id}`,children:Cqt(W)??""}),_&&a.jsx(Te.Cell,{className:"truncate text-destructive-foreground","data-testid":`result-error-${W.id}`,children:uee(W)??""}),N&&a.jsx(Te.Cell,{className:"flex items-center gap-1 overflow-hidden","data-testid":`result-tags-${W.id}`,children:W.tags?.map(z=>a.jsx(oee,{value:z,className:"shrink-0"},z))}),E&&a.jsx(Te.Cell,{children:a.jsx(wjs,{scores:W.scores})}),A&&a.jsx(Te.Cell,{className:"text-muted-foreground tabular-nums","data-testid":`result-cost-${W.id}`,children:zz(W.usage?.estimatedCost,W.usage?.costUnit)}),P&&a.jsx(Te.Cell,{className:"text-muted-foreground tabular-nums","data-testid":`result-tokens-${W.id}`,children:aS(WA(W.usage))}),L&&a.jsx(Te.Cell,{className:"text-muted-foreground tabular-nums","data-testid":`result-duration-${W.id}`,children:Uc(Sjs(W))??"-"}),o?.map(z=>{const G=i?.[W.itemId]?.find(X=>X.scorerId===z),ne=G?.reason?.trim();return a.jsxs(Te.Cell,{className:"flex items-center gap-1.5 text-muted-foreground tabular-nums",children:[G!=null?G.score.toFixed(3):"-",ne&&a.jsx(Iqt,{scorerId:z,reason:ne,nested:!0})]},z)})]});return y?a.jsxs(Te.RowWrapper,{children:[a.jsx(Te.SelectCell,{checked:f.has(W.id),onToggle:()=>h(W.id),"aria-label":`Select result ${W.itemId}`}),a.jsx(Te.RowButton,{colStart:2,featured:D,variant:K?"error":"default","data-selected":D||void 0,onClick:()=>r(W.id),...B(M),children:$})]},W.id):a.jsx(Te.RowButton,{featured:D,variant:K?"error":"default","data-selected":D||void 0,onClick:()=>r(W.id),...B(M),children:$},W.id)}),a.jsx(Te.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function wjs({scores:e}){const t=Array.isArray(e)?e.map(n=>n.score).filter(n=>n!=null):Object.values(e??{});return t.length===0?a.jsx(Y,{variant:"meta",tone:"faint",children:"—"}):a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(At,{size:"xs",className:"text-muted-foreground",children:a.jsx(Sp,{})}),a.jsx(Y,{variant:"meta",tone:"muted",font:"mono",children:t[0].toFixed(2)}),t.length>1&&a.jsxs($t,{children:["+",t.length-1]})]})}function Sjs({startedAt:e,completedAt:t}){if(!(!e||!t))return new Date(t).getTime()-new Date(e).getTime()}function kjs(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Ojs(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function jjs({experimentId:e,experimentStatus:t,results:n,isLoading:r,setEndOfListElement:s,isFetchingNextPage:i,hasNextPage:o,selectedIds:l,onToggleSelect:c,onToggleSelectAll:u,supportsMetrics:d=!1}){const{currentItemId:f,openItem:h,close:p}=EAe(),m=g.useMemo(()=>f?n.find(T=>T.itemId===f)?.id??null:null,[n,f]),{data:v}=r6({experimentId:e,experimentStatus:t,queryOptions:{enabled:!!e}}),y=g.useMemo(()=>[{id:e,status:t}],[e,t]),{data:x}=IAe({experiments:y,supportsMetrics:d}),b=x[e]?.traces,S=g.useMemo(()=>b?n.map(T=>({...T,usage:T.traceId?b[T.traceId]:void 0})):n,[n,b]),k=g.useMemo(()=>{if(!v)return[];const T=new Set;for(const _ of Object.values(v))for(const N of _)T.add(N.scorerId);return[...T].sort()},[v]),j=g.useCallback(T=>{const _=n.find(N=>N.id===T);_&&(_.itemId===f?p():h(_.itemId))},[n,f,p,h]),C=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"auto"},{name:"input",label:"Input",size:"20rem"},...gjs(n),...d?[{name:"cost",label:"Cost",size:"auto"},{name:"tokens",label:"Tokens",size:"auto"}]:[],{name:"duration",label:"Duration",size:"auto"},...k.map(T=>({name:T,label:T,size:"auto"}))],[n,k,d]);return a.jsx("div",{className:"h-full min-h-0 min-w-0 overflow-y-auto",children:a.jsx(Eqt,{results:S,isLoading:r,featuredResultId:m,onResultClick:j,columns:C,scoresByItemId:v,scorerIds:k,setEndOfListElement:s,isFetchingNextPage:i,hasNextPage:o,selectedIds:l,onToggleSelect:c,onToggleSelectAll:u})})}const Cjs="minmax(9rem,1fr)",_js="minmax(8rem,16rem)",Tjs="1fr",Ijs="auto auto auto auto auto auto auto",py={experiment:"Experiment",description:"Description",dataset:"Dataset",target:"Target",status:"Status",items:"Items",succeeded:"Processed",failed:"Errored",review:"Review",date:"Date"},Ejs={completed:"neutral",running:"warning",failed:"destructive",pending:"neutral"},gE={completed:"Run completed",running:"Run in progress",failed:"Run failed",pending:"Run queued"},Xtt={pending:{icon:a.jsx(fC,{className:"size-4 text-warning-foreground"}),label:gE.pending},running:{icon:a.jsx(On,{size:"sm"}),label:gE.running},completed:{icon:a.jsx(Yht,{className:"size-4 text-muted-foreground"}),label:gE.completed},failed:{icon:a.jsx(cwe,{className:"size-4 text-destructive-foreground"}),label:gE.failed}};function Njs({status:e,className:t}){const n=Xtt[e]??Xtt.pending;return a.jsxs(Qn,{children:[a.jsx(Fn,{render:a.jsx("span",{tabIndex:0,className:Z("flex shrink-0 items-center",t),children:n.icon})}),a.jsx(Bn,{children:n.label})]})}function Ajs({children:e,className:t}){return a.jsx("div",{className:Z("grid content-start gap-4 overflow-y-auto",t),children:e})}function Pjs({children:e,className:t}){return a.jsx("div",{className:"flex w-full overflow-y-auto",children:a.jsx("div",{className:Z("grid w-full content-start gap-4 overflow-y-auto",t),children:e})})}function $js({children:e,className:t}){return a.jsx("div",{className:Z("flex w-full flex-wrap items-center justify-between gap-3 gap-x-4",t),children:e})}const Nqt=Object.assign(Pjs,{Content:Ajs,Toolbar:$js});function Rjs({children:e,className:t}){return a.jsx("div",{className:Z("grid size-full grid-cols-1 overflow-y-auto",t),children:e})}const Mjs={agent:"blue",workflow:"cyan",model:"purple",mcp:"green",tool:"amber",workspace:"orange"},Djs=Object.keys(Mjs);[...Djs];function Ljs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${rs(n,"date-time")}`}return`v${e}`}function zjs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=WOt({datasetId:e,queryOptions:{enabled:!!e}}),i=(s??[]).map(o=>({value:String(o.version),label:`${Ljs(o.version,o.createdAt)}${o.isCurrent?" (current)":""}`}));return a.jsxs(Nqt.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[a.jsx("div",{}),a.jsxs(ms,{value:t??"",onValueChange:o=>r?.(o,n??""),children:[a.jsx(vs,{"aria-label":"Version A",size:"md",children:a.jsx(gs,{placeholder:"Select version"})}),a.jsx(ys,{children:i.map(o=>a.jsx(hr,{value:o.value,children:o.label},o.value))})]}),a.jsxs(ms,{value:n??"",onValueChange:o=>r?.(t??"",o),children:[a.jsx(vs,{"aria-label":"Version B",size:"md",children:a.jsx(gs,{placeholder:"Select an option"})}),a.jsx(ys,{children:i.map(o=>a.jsx(hr,{value:o.value,children:o.label},o.value))})]}),a.jsx("div",{})]})}const AV={added:{badgeVariant:"info",borderColor:"border-info-edge",icon:a.jsx(Dr,{}),tooltip:"Added in this version"},changed:{badgeVariant:"warning",borderColor:"border-warning-edge",icon:a.jsx(GEn,{}),tooltip:"Changed in this version"},same:{badgeVariant:"success",borderColor:"border-success-edge",icon:a.jsx(npt,{}),tooltip:"Same in both versions"}};function bue({red:e=!1,tooltip:t}){return a.jsxs(Qn,{children:[a.jsx(Fn,{render:a.jsx("span",{}),role:"img",tabIndex:0,"aria-label":t,className:Z("rounded",bi),children:a.jsx(qht,{className:Z("h-5 w-5 text-muted-foreground/40",{"text-destructive-foreground":e})})}),a.jsx(Bn,{children:t})]})}function B7({href:e,tooltip:t,className:n,children:r}){const{Link:s}=Sn(),i=a.jsx(s,{href:e,className:Z("flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left hover:bg-fill-subtle",Mi.colors,bi,n),children:r});return t===void 0?i:a.jsxs(Qn,{children:[a.jsx(Fn,{render:i}),a.jsx(Bn,{children:t})]})}function wue({variant:e,version:t}){if(!e)return a.jsxs(Y,{as:"span",tone:"muted",children:["v. ",t]});const{badgeVariant:n,icon:r,tooltip:s}=AV[e];return a.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&a.jsxs(Y,{as:"span",tone:"muted",className:"flex min-w-16 justify-end pr-3",children:["v. ",t]}),a.jsx("span",{className:"inline-flex",role:"img","aria-label":s,children:a.jsx($t,{variant:n,size:"xs",icon:r})})]})}function Fjs(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function Jtt({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function Bjs({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:i}){const o=t>n;return a.jsx("div",{className:"overflow-y-auto",children:a.jsx("ul",{className:"grid content-start",children:r.map(({id:l})=>{const c=s.get(l),u=i.get(l),d=Fjs(c,u),f=Jtt({otherVersionExists:u!==void 0,status:d,isNewer:o}),h=Jtt({otherVersionExists:c!==void 0,status:d,isNewer:!o});return a.jsxs("li",{className:Z("text-foreground","grid grid-cols-[1fr_1fr_1fr_10rem] gap-3 overflow-hidden rounded-lg border border-transparent border-t-border px-3 py-[3px] pb-[2px] first:border-t-transparent",Mi.colors),children:[a.jsx(Y,{as:"p",variant:"body",tone:"faint",className:"truncate py-[0.6rem]",children:l}),d!=="same"?a.jsxs(a.Fragment,{children:[c?.datasetVersion?a.jsx(B7,{href:`/datasets/${e}/items/${l}`,className:"gap-2",tooltip:f?AV[f].tooltip:void 0,children:a.jsx(wue,{variant:f,version:c.datasetVersion})}):a.jsx("div",{className:"flex items-center justify-center",children:a.jsx(bue,{red:o,tooltip:o?"Deleted in this version":"Not present in this version"})}),u?.datasetVersion?a.jsx(B7,{href:`/datasets/${e}/items/${l}`,className:"gap-2",tooltip:h?AV[h].tooltip:void 0,children:a.jsx(wue,{variant:h,version:u.datasetVersion})}):a.jsx("div",{className:"flex items-center justify-center",children:a.jsx(bue,{red:!o,tooltip:o?"Not present in this version":"Deleted in this version"})})]}):a.jsx(B7,{href:`/datasets/${e}/items/${l}`,className:"col-span-2 gap-2",tooltip:AV.same.tooltip,children:a.jsx(wue,{variant:"same",version:u?.datasetVersion})}),d==="changed"?a.jsx(B7,{href:`/datasets/${e}/items/${l}/versions?version=${c?.datasetVersion}&compare=${u?.datasetVersion}`,children:"Compare"}):a.jsx("div",{children:a.jsx(bue,{tooltip:"Comparing is available only for changed items"})})]},l)})})})}function Vjs(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 Ujs({item:e,itemId:t,fallback:n,onClose:r,...s}){const i=e?.id??t;return a.jsx(_t,{open:!!i,onClose:r,title:`Dataset item ${i??""}`,children:e?a.jsx(qjs,{item:e,onClose:r,...s},e.id):t?a.jsxs(a.Fragment,{children:[a.jsxs(_t.Header,{children:[a.jsx(_t.CloseButton,{onClick:r,tooltip:"Close detail panel"}),a.jsxs(_t.Heading,{children:["Item",a.jsx(_t.CopyId,{id:t})]})]}),n]}):null})}function qjs({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:i}=Sn(),{updateItem:o,deleteItem:l}=pl(),[c,u]=g.useState(!1),[d,f]=g.useState(""),[h,p]=g.useState(""),[m,v]=g.useState(""),[y,x]=g.useState(""),[b,S]=g.useState(""),[k,j]=g.useState(t.scorerIds!==void 0),[C,T]=g.useState(t.scorerIds??[]),[_,N]=g.useState(""),[E,A]=g.useState(null),[P,L]=g.useState(!1);g.useEffect(()=>{t&&(f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),x(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),S(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),j(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),L(!1),A(null))},[t?.id]);const F=n.findIndex(D=>D.id===t.id),Q=F>0?()=>r(n[F-1].id):void 0,q=F>=0&&F<n.length-1?()=>r(n[F+1].id):void 0,B=async()=>{let D;try{D=JSON.parse(d)}catch{Xe.error("Input must be valid JSON");return}let $;if(h.trim())try{$=JSON.parse(h)}catch{Xe.error("Ground Truth must be valid JSON");return}let z;if(m.trim())try{z=JSON.parse(m)}catch{Xe.error("Metadata must be valid JSON");return}let U=null;if(y.trim())try{U=JSON.parse(y)}catch{Xe.error("Expected Trajectory must be valid JSON");return}let G;if(b.trim())try{const ee=JSON.parse(b);if(!Array.isArray(ee)){Xe.error("Tool Mocks must be a JSON array");return}G=ee}catch{Xe.error("Tool Mocks must be valid JSON");return}else G=[];let ne;if(_.trim())try{ne=JSON.parse(_)}catch{Xe.error("Request Context must be valid JSON");return}let X;k?X=C:t.scorerIds!==void 0&&(X=null);try{const ee=await o.mutateAsync({datasetId:e,itemId:t.id,input:D,groundTruth:$,metadata:z,expectedTrajectory:U,toolMocks:G,scorerIds:X,requestContext:ne});Xe.success("Item updated successfully"),j(ee.scorerIds!==void 0),T(ee.scorerIds??[]),u(!1),A(null)}catch(ee){const re=Vjs(ee);re?A(re):Xe.error(`Failed to update item: ${ee instanceof Error?ee.message:"Unknown error"}`)}},V=()=>{f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),x(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),S(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),j(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},W=D=>{f(D),E?.field==="input"&&A(null)},M=D=>{p(D),E?.field==="groundTruth"&&A(null)},K=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Xe.success("Item deleted successfully"),L(!1),s()}catch(D){Xe.error(`Failed to delete item: ${D instanceof Error?D.message:"Unknown error"}`)}};return a.jsxs(a.Fragment,{children:[a.jsxs(_t.Header,{children:[a.jsx(_t.CloseButton,{onClick:s,tooltip:"Close detail panel"}),a.jsxs(_t.Heading,{children:["Item",a.jsx(_t.CopyId,{id:t.id})]}),a.jsxs(_t.HeaderActions,{children:[!c&&a.jsxs(a.Fragment,{children:[a.jsx(ce,{render:a.jsx(i,{href:`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`}),size:"sm",variant:"ghost",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:a.jsx(oG,{})}),a.jsxs(lt,{children:[a.jsx(lt.Trigger,{asChild:!0,children:a.jsx(ce,{size:"sm",variant:"ghost",tooltip:"Open actions menu","aria-label":"Open actions menu",children:a.jsx(W0,{})})}),a.jsxs(lt.Content,{align:"end",className:"w-48",children:[a.jsxs(lt.Item,{onSelect:()=>u(!0),children:[a.jsx(Vc,{}),"Edit"]}),a.jsxs(lt.Item,{onSelect:()=>L(!0),variant:"destructive",children:[a.jsx(Xo,{}),"Delete Item"]})]})]})]}),a.jsx(_t.NextPrevNav,{onPrevious:Q,onNext:q,previousLabel:"Go to previous item",nextLabel:"Go to next item"})]})]}),a.jsx(_t.Content,{children:c?a.jsx(sjs,{inputValue:d,setInputValue:W,groundTruthValue:h,setGroundTruthValue:M,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:x,toolMocksValue:b,setToolMocksValue:S,scorerOverrideEnabled:k,setScorerOverrideEnabled:j,selectedScorerIds:C,setSelectedScorerIds:T,requestContextValue:_,setRequestContextValue:N,validationErrors:E,onSave:B,onCancel:V,isSaving:o.isPending}):a.jsx(Zye,{item:t})}),a.jsx(Bt,{open:P,onOpenChange:L,children:a.jsxs(Bt.Content,{children:[a.jsxs(Bt.Header,{children:[a.jsx(Bt.Title,{children:"Delete Item"}),a.jsx(Bt.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),a.jsxs(Bt.Footer,{children:[a.jsx(Bt.Cancel,{children:"Cancel"}),a.jsx(Bt.Action,{onClick:K,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function Qjs(){const{datasetId:e,items:t,isLoadingItems:n,currentItemId:r,openItem:s,close:i}=bqt(),o=g.useMemo(()=>r?t.find(d=>d.id===r):void 0,[t,r]),{data:l,isLoading:c}=UOt({datasetId:o?"":e,itemId:!o&&r?r:"",queryOptions:{enabled:!!(!o&&e)&&!!(!o&&r&&r)}}),u=o??l??void 0;return a.jsx(Ujs,{datasetId:e,item:u,itemId:r,fallback:n||c?a.jsx(_t.LoadingData,{}):a.jsxs(_t.NoData,{children:['No loaded item "',r,'".']}),items:t,onItemChange:s,onClose:i})}function V7({crumbs:e,children:t}){return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:e}),children:[a.jsx("h1",{className:"sr-only",children:"Dataset"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:t})]})}function Zjs(){const{datasetId:e,itemId:t}=Cr(),n=[Ts("/datasets"),{...MK,to:`/datasets/${encodeURIComponent(e)}`},...t?[{id:"dataset-items",label:"Items"},{id:"dataset-item",label:ojt(t)}]:[]],r=Lr(),[s,i]=wi(),{activeVersion:o,handleVersionChange:l}=TAe(s,i),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[h,p]=g.useState(!1),[m,v]=g.useState(!1),{data:y,error:x,isLoading:b}=Vv({datasetId:e,queryOptions:{enabled:!!e}}),{data:S=[],isLoading:k}=oA({datasetId:e,search:void 0,version:o,queryOptions:{enabled:!!e}}),j=!k&&S.length===0;if(b)return null;if(x&&Cs(x))return a.jsx(V7,{crumbs:n,children:a.jsx(ci,{})});if(x&&_s(x))return a.jsx(V7,{crumbs:n,children:a.jsx(Gs,{resource:"datasets"})});if(x&&Pk(x)||!b&&!x&&!y)return a.jsx(V7,{crumbs:n,children:a.jsx(Yt,{titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:a.jsx(ce,{render:a.jsx(lc,{to:"/datasets"}),icon:a.jsx(vd,{}),children:"Back to Datasets"})})});if(x)return a.jsx(V7,{crumbs:n,children:a.jsx(Yt,{tone:"error",titleSlot:"Failed to load dataset",descriptionSlot:x instanceof Error?x.message:"An unexpected error occurred. Please try again."})});const C=_=>{r(`/experiments/${_}`)},T=()=>{r("/datasets")};return a.jsxs(YOs,{datasetId:e,items:S,isLoadingItems:k,children:[a.jsxs("div",{className:"h-full",children:[a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:n}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{children:a.jsx(JOs,{datasetId:e,onAddItemClick:()=>f(!0),belowToolbarSlot:a.jsx(ejs,{datasetId:e}),leftSlot:a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"mr-3 whitespace-nowrap",children:y?.createdAt?`Created ${rs(y.createdAt,"date-time")}`:""}),rightSlot:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ce,{render:a.jsx(lc,{to:`/experiments?dataset=${e}`}),icon:a.jsx(dL,{}),children:"View experiments"}),a.jsx(vqt,{datasetId:e,value:o,onValueChange:l,currentVersion:y?.version,className:"w-36"}),j?a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsx("span",{className:"cursor-not-allowed",children:a.jsx("div",{className:"pointer-events-none opacity-50",inert:!0,"aria-disabled":"true",children:a.jsx(ce,{variant:"primary",icon:a.jsx(Dr,{}),children:"New experiment"})})})}),a.jsx(Bn,{children:"Add items to the dataset before running an experiment"})]}):a.jsx(ce,{variant:"primary",onClick:()=>u(!0),icon:a.jsx(Dr,{}),children:"New experiment"}),a.jsxs(lt,{children:[a.jsx(lt.Trigger,{asChild:!0,children:a.jsx(ce,{size:"lg","aria-label":"Dataset actions menu",children:a.jsx(W0,{})})}),a.jsxs(lt.Content,{align:"end",className:"w-48",children:[a.jsxs(lt.Item,{onSelect:()=>{r(`/datasets/${e}/edit`)},children:[a.jsx(Vc,{})," Edit Dataset"]}),a.jsxs(lt.Item,{onSelect:()=>v(!0),children:[a.jsx(Lm,{})," Duplicate Dataset"]}),a.jsxs(lt.Item,{onSelect:()=>p(!0),variant:"destructive",children:[a.jsx(Xo,{})," Delete Dataset"]})]})]})]})})})]}),a.jsx(Qjs,{})]}),a.jsx(cee,{initialDatasetId:e,initialDatasetVersion:o??void 0,open:c,onOpenChange:u,onSuccess:C},`${e}:${o??"latest"}`),a.jsx(njs,{datasetId:e,open:d,onOpenChange:f}),y&&a.jsx(hOs,{open:m,onOpenChange:v,sourceDatasetId:y.id,sourceDatasetName:y.name,sourceDatasetDescription:y.description,sourceDatasetTargetType:y.targetType}),y&&a.jsx(vOs,{open:h,onOpenChange:p,datasetId:y.id,datasetName:y.name,onSuccess:T})]})}const Aqt=[Ts("/datasets"),MK,{id:"dataset-edit",label:"Edit dataset"}];function Sue({children:e}){return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Aqt}),children:[a.jsx("h1",{className:"sr-only",children:"Edit dataset"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:e})]})}function Wjs(){const{datasetId:e}=Cr(),t=Lr(),{data:n,error:r,isLoading:s}=Vv({datasetId:e,queryOptions:{enabled:!!e}}),i=()=>{t(`/datasets/${e}`)};return s?null:r&&Cs(r)?a.jsx(Sue,{children:a.jsx(ci,{})}):r&&_s(r)?a.jsx(Sue,{children:a.jsx(Gs,{resource:"datasets"})}):r||!n?a.jsx(Sue,{children:a.jsx(Yt,{tone:"error",titleSlot:"Failed to load dataset",descriptionSlot:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Aqt}),children:[a.jsx("h1",{className:"sr-only",children:"Edit dataset"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[a.jsx(Uh,{className:"mb-6 p-0",children:a.jsxs(Uh.Column,{children:[a.jsxs(Uh.Title,{children:[a.jsx(zm,{})," Edit dataset"]}),a.jsx(Uh.Description,{children:n.name})]})}),a.jsx(hl,{className:"p-4",children:a.jsx(gOs,{dataset:{id:n.id,name:n.name,description:n.description||"",inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema,scorerIds:n.scorerIds},onSuccess:i,onCancel:i})})]})})]})}function ent(e,t){return{id:e.id,datasetId:t,datasetVersion:e.datasetVersion,input:e.input,groundTruth:e.groundTruth,expectedTrajectory:e.expectedTrajectory,toolMocks:e.toolMocks,scorerIds:e.scorerIds,requestContext:e.requestContext,metadata:e.metadata,createdAt:e.createdAt,updatedAt:e.updatedAt}}function tnt(e,t){return e.map(n=>{const r=typeof n.updatedAt=="string"?new Date(n.updatedAt):n.updatedAt;return{value:String(n.datasetVersion),label:a.jsxs("span",{className:"flex w-full items-center gap-2",children:[a.jsxs("span",{children:[a.jsxs("b",{children:["v. ",n.datasetVersion]})," · ",rs(r,"date-time")]}),n.isLatest?a.jsx($t,{variant:"blue",size:"xs",className:"ml-auto",children:"Latest"}):null]}),disabled:t?.has(n.datasetVersion)??!1}})}function nnt(e){const t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function Hjs(){const{datasetId:e,itemId:t}=Cr(),[n,r]=wi(),s=[Ts("/datasets"),MK,{id:"dataset-item",label:ojt(t),to:e&&t?`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`:void 0},{id:"dataset-item-versions",label:"Item Version History"}],i=nnt(n.get("version")),o=nnt(n.get("compare")),l=n.get("view")==="diff",{data:c,error:u}=Vv({datasetId:e??"",queryOptions:{enabled:!!e}}),{data:d,isLoading:f}=Wcr({datasetId:e??"",itemId:t??"",queryOptions:{enabled:!!e&&!!t}}),h=(i!=null?d?.find(T=>T.datasetVersion===i):void 0)??d?.[0],p=h?.datasetVersion??null,m=o!=null&&o!==p?o:null,{data:v,isLoading:y}=Hcr({datasetId:e??"",itemId:t??"",datasetVersion:m??0,latestVersion:c?.version,queryOptions:{enabled:!!e&&!!t&&(m??0)>0}}),x=(T,_)=>r(N=>{const E=new URLSearchParams(N);return _==null?E.delete(T):E.set(T,String(_)),E},{replace:!0});if(u&&Cs(u))return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx(ci,{variant:"fill"})]});if(u&&_s(u))return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx(Gs,{variant:"fill",resource:"datasets"})]});if(!e||!t)return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsx("div",{className:"py-5 text-center text-muted-foreground",children:a.jsx("p",{children:"Item not found."})})})]});const b=!!(h&&v),S=l&&b,k=h?ent(h,e):null,j=v?ent(v,e):null,C=(h?.datasetVersion??0)<(v?.datasetVersion??0);return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:s}),headerActions:b&&a.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>x("view",l?null:"diff"),children:l?a.jsxs(a.Fragment,{children:[a.jsx(dwe,{})," Default View"]}):a.jsxs(a.Fragment,{children:[a.jsx(wIn,{})," Diff View"]})}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsxs("div",{className:"grid min-h-0 grid-cols-1 gap-4 md:grid-cols-2",children:[a.jsxs(hl,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[a.jsx(TQ,{children:a.jsx(rnt,{label:"Version",value:p!=null?String(p):"",options:tnt(d??[],m!=null?new Set([m]):void 0),onValueChange:T=>x("version",Number(T))})}),a.jsx(qm,{className:"grid content-start gap-5 overflow-y-auto",children:f?a.jsx(Y,{as:"p",variant:"body",tone:"muted",children:"Loading..."}):k?a.jsx(Zye,{item:k,diff:S&&j?{against:j,side:C?"a":"b"}:void 0}):a.jsx(Y,{as:"p",variant:"body",tone:"muted",children:"Item data not available"})})]}),a.jsxs(hl,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[a.jsx(TQ,{children:a.jsx(rnt,{label:"Compare version",value:m!=null?String(m):"",placeholder:"Select a version to compare",options:tnt(d??[],p!=null?new Set([p]):void 0),onValueChange:T=>x("compare",Number(T))})}),a.jsx(qm,{className:"grid content-start gap-5 overflow-y-auto",children:m==null?a.jsx(Yt,{className:"h-full",titleSlot:"No version selected",descriptionSlot:"Pick a version above to compare it with the one on the left."}):y?a.jsx(Y,{as:"p",variant:"body",tone:"muted",children:"Loading..."}):j?a.jsx(Zye,{item:j,diff:S&&k?{against:k,side:C?"b":"a"}:void 0}):a.jsxs(Y,{as:"p",variant:"body",tone:"muted",children:["Version ",m," not found"]})})]})]})]})}function rnt({label:e,value:t,options:n,placeholder:r="Select version",onValueChange:s}){return a.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-center gap-4",children:[a.jsx(oG,{className:"size-4 opacity-50"}),a.jsxs(ms,{value:t,onValueChange:s,children:[a.jsx(vs,{"aria-label":e,className:"w-full",children:a.jsx(gs,{placeholder:r,className:"flex-1"})}),a.jsx(ys,{children:n.map(i=>a.jsx(hr,{value:i.value,disabled:i.disabled,children:i.label},i.value))})]})]})}const U7=[Ts("/datasets"),MK,{id:"dataset-versions",label:"Versions"}];function Gjs(){const{datasetId:e}=Cr(),[t]=wi(),n=t.get("ids")?.split(",").map(Number).filter(m=>!isNaN(m)&&m>0)??[],r=Lr(),{data:s,error:i}=Vv({datasetId:e??"",queryOptions:{enabled:!!e}}),o=oA({datasetId:e??"",search:void 0,version:n[0]??null,queryOptions:{enabled:!!e}}),l=oA({datasetId:e??"",search:void 0,version:n[1]??null,queryOptions:{enabled:!!e}}),c=g.useMemo(()=>o.data??[],[o.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const m=new Map;for(const v of[...c,...u])m.has(v.id)||m.set(v.id,{id:v.id,createdAt:new Date(v.createdAt)});return[...m.values()].sort((v,y)=>y.createdAt.getTime()-v.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(m=>[m.id,m])),[c]),h=g.useMemo(()=>new Map(u.map(m=>[m.id,m])),[u]);if(i&&Cs(i))return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:U7}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx(ci,{variant:"fill"})]});if(i&&_s(i))return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:U7}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx(Gs,{variant:"fill",resource:"datasets"})]});if(!e||n.length<2)return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:U7}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsx("div",{className:"py-5 text-center text-muted-foreground",children:a.jsx("p",{children:"Select at least two versions to compare."})})})]});const p=(m,v)=>{r(`/datasets/${e}/versions?ids=${m},${v}`,{replace:!0})};return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:U7}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:a.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-4",children:[a.jsxs(Uh,{children:[a.jsxs(Uh.Column,{children:[a.jsxs(Uh.Title,{children:[a.jsx(INn,{})," Compare Dataset Versions"]}),a.jsx(Uh.Description,{children:a.jsxs(lv,{children:[a.jsx(oG,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),a.jsx(Uh.Column,{children:a.jsx(ce,{render:a.jsx(lc,{to:`/datasets/${e}`}),icon:a.jsx(vd,{}),children:"Back to Dataset"})})]}),a.jsx(Rjs,{children:a.jsxs(Nqt,{children:[a.jsx(zjs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:p}),a.jsx(Bjs,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:h})]})})]})})]})}const Kjs=[Ts("/datasets"),{id:"dataset-new",label:"Create new dataset"}];function Yjs(){const e=Lr(),[t]=wi(),n=t.get("targetType"),r=aee(n)?n:void 0,s=t.get("targetIds"),i=r&&s?s.split(",").map(l=>l.trim()).filter(Boolean):void 0,o=l=>{e(`/datasets/${l}`)};return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Kjs}),children:[a.jsx("h1",{className:"sr-only",children:"Create new dataset"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[a.jsx(Uh,{className:"mb-6 p-0",children:a.jsxs(Uh.Column,{children:[a.jsxs(Uh.Title,{children:[a.jsx(zm,{})," Create new dataset"]}),a.jsx(Uh.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),a.jsx(hl,{className:"p-4",children:a.jsx(lOs,{targetType:r,targetIds:i,onSuccess:o,onCancel:()=>{e(-1)}})})]})})]})}const Pqt=(e,{experimentId:t,targetType:n,targetId:r,experiments:s,isLoadingExperiments:i=!1,queryOptions:o})=>{const l=Ke(),c=s!==void 0,{data:u,isLoading:d}=Oqt({datasetId:void 0,target:{targetType:n,targetId:r},queryOptions:{enabled:!c}}),f=c?s:u?.experiments,h=c?i:d,p=t?f?.filter(v=>v.id===t):f,m=Ct({queryKey:["review-items",e,t??"all",c?"supplied":"discovered",c?void 0:n||"all",c?void 0:r||"all",p?.map(v=>[v.datasetId,v.id])],queryFn:async()=>!p||p.length===0?[]:(await Promise.all(p.map(async v=>{if(!v.datasetId)return[];try{const{results:y}=await l.listDatasetExperimentResults(v.datasetId,v.id);return y.filter(x=>x.status===e).map(x=>({id:x.id,input:x.input,output:x.output,error:x.error,itemId:x.itemId,experimentId:x.experimentId,datasetId:v.datasetId??void 0,traceId:x.traceId??void 0,scores:x.scores?Object.fromEntries(x.scores.map(b=>[b.scorerId,b.score??0])):{},tags:x.tags??[],targetType:x.targetType,createdAt:x.createdAt,startedAt:x.startedAt,completedAt:x.completedAt,status:x.status,groundTruth:x.groundTruth,toolMockReport:x.toolMockReport}))}catch{return[]}}))).flat(),enabled:!!f,refetchOnWindowFocus:!1,...o});return{...m,isLoading:m.isLoading||h}},Xjs=(e={})=>Pqt("needs-review",e),Jjs=(e={})=>Pqt("complete",e);function eCs({queryOptions:e}={}){const t=Ke();return Ct({queryKey:["experiment-review-summary"],queryFn:()=>t.getExperimentReviewSummary(),...e})}function $qt({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:s}){const{deleteExperiment:i}=pl(),o=async()=>{try{await i.mutateAsync(n),Xe.success("Experiment deleted successfully"),t(!1),s?.()}catch(l){Xe.error(`Failed to delete experiment: ${l instanceof Error?l.message:"Unknown error"}`)}};return a.jsx(Bt,{open:e,onOpenChange:t,children:a.jsxs(Bt.Content,{children:[a.jsxs(Bt.Header,{children:[a.jsx(Bt.Title,{children:"Delete Experiment"}),a.jsxs(Bt.Description,{children:['Are you sure you want to delete "',r||n,'"? This will permanently delete the experiment, all its results, and the traces it produced, including their spans and any scores, feedback, metrics and logs attached to those traces. This action cannot be undone.']})]}),a.jsxs(Bt.Footer,{children:[a.jsx(Bt.Cancel,{children:"Cancel"}),a.jsx(ce,{icon:a.jsx(Xo,{}),variant:"primary",onClick:o,disabled:i.isPending,children:i.isPending?"Deleting...":"Delete"})]})]})})}function Rqt(e){const t=Tv(e.id)??e.id;return e.name||`Experiment #${t}`}const tCs=60;function nCs({experiment:e}){return a.jsx("span",{className:"block min-w-0 truncate text-left text-muted-foreground",children:Rqt(e)})}function rCs({experiment:e}){const t=e.description;if(!t)return a.jsx("span",{className:"text-placeholder",children:"—"});const n=a.jsx("span",{className:"block min-w-0 truncate text-left text-muted-foreground",children:t});return t.length<=tCs?n:a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:n}),a.jsx(Bn,{children:t})]})}function sCs(){const{data:e}=Cp(),{data:t}=tg(),{data:n}=Bx(),{data:r}=zP();return{agents:e,workflows:t,scorers:n,processors:r}}const iCs={agent:Vo,workflow:jl,scorer:rw,processor:aj},oCs={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},aCs="External (caller-run)";function lCs(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:i,targetId:o}=e;if(!o)return aCs;switch(i){case"agent":return t?.[o]?.name??o;case"workflow":return n?.[o]?.name??o;case"scorer":return r?.[o]?.scorer?.config?.name??o;case"processor":return s?.[o]?.name??o;default:return o}}function cCs({experiment:e,datasetName:t,review:n}){const r=e.status??"pending",s=e.succeededCount??0,i=e.failedCount??0,o=e.totalItems??0;return a.jsxs(a.Fragment,{children:[a.jsx(Te.Cell,{children:a.jsx(nCs,{experiment:e})}),a.jsx(Te.Cell,{children:a.jsx(rCs,{experiment:e})}),t!==void 0&&a.jsx(Te.TextCell,{children:t}),a.jsx(Te.Cell,{children:a.jsx(uCs,{experiment:e})}),a.jsx(Te.Cell,{children:a.jsx($t,{variant:Ejs[r]??"neutral",indicator:"dot",children:gE[r]??r})}),a.jsx(Te.TextCell,{className:"text-center",children:o}),a.jsx(Te.TextCell,{className:"text-center",children:s}),a.jsx(Te.TextCell,{className:"text-center",children:a.jsx("span",{className:i>0?"text-destructive-foreground":"",children:i})}),a.jsx(Te.Cell,{className:"text-center",children:a.jsx(dCs,{review:n})}),a.jsx(Te.TextCell,{children:rs(e.createdAt,"date")??"—"})]})}function uCs({experiment:e}){const t=sCs(),n=lCs(e,t),r=e.targetId?e.targetType:null,s=r?iCs[r]:null;return a.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[s&&a.jsx("span",{className:"flex text-muted-foreground",role:"img","aria-label":oCs[r],children:a.jsx(s,{})}),a.jsx("span",{className:r?"truncate":"truncate text-placeholder",children:n})]})}function dCs({review:e}){if(!e)return a.jsx("span",{className:"text-placeholder",children:"—"});const t=e.needsReview+e.complete;return t===0?a.jsx("span",{className:"text-placeholder",children:"—"}):e.needsReview>0?a.jsxs($t,{size:"xs",variant:"warning",children:[e.needsReview," pending"]}):a.jsxs($t,{size:"xs",variant:"success",children:[e.complete,"/",t," reviewed"]})}const fCs=`${Cjs} ${_js} ${Tjs} ${Ijs}`,kue=`${fCs} auto`,hCs=[{label:py.experiment},{label:py.description},{label:py.dataset},{label:py.target},{label:py.status,sortKey:"status"},{label:py.items,className:"text-center"},{label:py.succeeded,className:"text-center"},{label:py.failed,className:"text-center"},{label:py.review,className:"text-center"},{label:py.date,sortKey:"createdAt"}],pCs=e=>e.stopPropagation();function mCs({experiment:e,rowProps:t,onSelect:n,featured:r,comparable:s,onDelete:i,leadingCell:o,children:l}){const c=o?2:void 0,{paths:u,Link:d}=Sn(),f=g.useRef(null);return a.jsxs(Te.RowWrapper,{...t,onSelectRow:n??(()=>f.current?.click()),children:[o,n?a.jsx(Te.RowButton,{colStart:c,colEnd:-2,featured:r,variant:s?"info":"default",tabIndex:-1,onClick:h=>{h.stopPropagation(),n()},children:l}):a.jsx(Te.RowLink,{ref:f,colStart:c,colEnd:-2,featured:r,variant:s?"info":"default",to:u.experimentLink(e.id),LinkComponent:d,tabIndex:-1,onClick:pCs,children:l}),a.jsx(Te.ActionsCell,{className:"pl-2",children:a.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"Delete experiment","aria-label":`Delete experiment ${e.name??e.id}`,onClick:h=>{h.stopPropagation(),i()},children:a.jsx(Xo,{className:"size-4"})})})]})}function gCs({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:i="all",datasetFilter:o="all",selection:l,onSelectExperiment:c,selectedExperimentId:u,keyboardGlobal:d=!0,isFetchingNextPage:f,hasNextPage:h,setEndOfListElement:p,sort:m,onSortChange:v}){const y=g.useMemo(()=>{const A=new Map;return t?.forEach(P=>A.set(P.id,P.name)),A},[t]),x=g.useMemo(()=>m?e:[...e].sort((A,P)=>{const L=A.createdAt?new Date(A.createdAt).getTime():0;return(P.createdAt?new Date(P.createdAt).getTime():0)-L}),[e,m]),b=g.useMemo(()=>{const A=s.toLowerCase();return x.filter(P=>{const L=P.datasetId?y.get(P.datasetId)??"":"",F=!A||P.id.toLowerCase().includes(A)||(P.name??"").toLowerCase().includes(A)||L.toLowerCase().includes(A)||(P.targetId??"").toLowerCase().includes(A),Q=i==="all"||P.status===i,q=o==="all"||P.datasetId===o;return F&&Q&&q})},[x,s,y,i,o]),{containerRef:S,getRowProps:k}=Fu({count:b.length,global:d}),[j,C]=g.useState(null);if(r)return a.jsx(Lu,{columns:kue});const _=(l?.selectedExperimentIds.length??0)===0||b.length===0?!1:b.every(A=>l?.selectedExperimentIds.includes(A.id))?!0:"indeterminate",N=l?`auto ${kue}`:kue,E=hCs.map(A=>A.sortKey&&v?a.jsx(Te.SortableTopCell,{className:A.className,sortKey:A.sortKey,sort:m?.key===A.sortKey?m.direction:void 0,onSortChange:v,children:A.label},A.label):a.jsx(Te.TopCell,{className:A.className,children:A.label},A.label));return a.jsxs(Te,{columns:N,scrollRef:S,children:[a.jsx(Te.Top,{hasLeadingCell:l!==void 0,children:l?a.jsxs(a.Fragment,{children:[a.jsx(Te.TopSelectCell,{checked:_,onToggle:()=>l.onToggleAll(b.map(A=>A.id)),"aria-label":"Select all experiments"}),a.jsxs(Te.TopCells,{colStart:2,children:[E,a.jsx(Te.TopCell,{"aria-hidden":!0,children:null})]})]}):a.jsxs(a.Fragment,{children:[E,a.jsx(Te.TopCell,{"aria-hidden":!0,children:null})]})}),b.length===0&&!h?a.jsx(Te.NoMatch,{message:"No experiments match your filters"}):null,b.map((A,P)=>{const L=A.datasetId?y.get(A.datasetId)??Tv(A.datasetId)??A.datasetId:"—",F=a.jsx(cCs,{experiment:A,datasetName:L,review:n?.get(A.id)}),Q=l?.selectedExperimentIds.includes(A.id)??!1,q=l?.comparableDatasetId!==void 0&&A.datasetId===l.comparableDatasetId;return a.jsx(mCs,{experiment:A,rowProps:k(P),onSelect:c?()=>c(A):void 0,featured:Q||u===A.id,comparable:q,onDelete:()=>C(A),leadingCell:l&&a.jsx(Te.SelectCell,{checked:Q,onToggle:()=>l.onToggleSelection(A.id),"aria-label":`Select experiment ${A.id}`}),children:F},A.id)}),a.jsx(Te.NextPageLoading,{isLoading:f,hasMore:h,setEndOfListElement:p}),j&&a.jsx($qt,{open:!0,onOpenChange:A=>{A||C(null)},experimentId:j.id,experimentName:j.name??void 0})]})}const vCs=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function yCs(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const xCs=({onRunExperiment:e})=>a.jsx(Yt,{titleSlot:"No Experiments yet",descriptionSlot:a.jsxs(a.Fragment,{children:["Run an experiment from a dataset to evaluate ",a.jsx("br",{}),"your agents and workflows."]}),actionSlot:a.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e&&a.jsx(ce,{variant:"primary",onClick:e,icon:a.jsx(Dr,{}),children:"New experiment"}),a.jsx(ce,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Experiments Documentation"})]}),variant:"fill"});function bCs({selectedCount:e,onClearSelection:t,onCompare:n,compareDisabledReason:r}){const s=e===0;return a.jsxs("div",{className:"flex items-center gap-1 whitespace-nowrap",children:[a.jsxs(ce,{variant:"ghost",size:"sm",disabled:s,iconEnd:s?void 0:a.jsx(Mn,{}),onClick:t,tooltip:s?void 0:"Clear selection",className:"mr-2 tabular-nums",children:[e," selected"]}),r?a.jsxs(Qn,{children:[a.jsx(Fn,{render:a.jsx("span",{className:"cursor-not-allowed",tabIndex:0}),children:a.jsx(ce,{size:"sm",disabled:!0,tabIndex:-1,icon:a.jsx(z6e,{}),children:"Compare"})}),a.jsx(Bn,{children:r})]}):a.jsx(ce,{size:"sm",onClick:n,icon:a.jsx(z6e,{}),children:"Compare"})]})}function wCs({datasetId:e}){return a.jsx(Y,{as:"p",variant:"body-sm",tone:"muted",role:"note","aria-label":"Comparable experiments",className:"min-w-0 truncate",children:e?a.jsxs(a.Fragment,{children:["Comparable experiments share dataset"," ",a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",tone:"ink",title:e,children:e})]}):"Select an experiment to highlight comparable ones"})}const AAe="search",PAe="status",$Ae="dataset",HA="all",SCs=[{id:"contains",label:"contains"},{id:"is",label:"is"}],kCs=vCs.filter(e=>e.value!==HA),OCs=({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:s})=>{const i=[];return e&&i.push(cv(AAe,e,"contains")),i.push(...wAe({targetType:r,targetId:s})),t!==HA&&i.push(cv(PAe,t)),n!==HA&&i.push(cv($Ae,n)),i},jCs=e=>({...SAe(e),search:uv(e,AAe),statusFilter:uv(e,PAe)||HA,datasetFilter:uv(e,$Ae)||HA});function CCs({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:s,datasetOptions:i,onChange:o}){const l=kAe(r),c=g.useMemo(()=>[{id:AAe,label:"Search",icon:wu,search:!0,operators:["contains"]},...l,{id:PAe,label:"Status",icon:bP,color:v0("orange"),operators:["is"],strict:!0,suggestions:kCs},{id:$Ae,label:"Dataset",icon:zm,color:v0("blue"),operators:["is"],strict:!0,suggestions:i.filter(d=>d.value!==HA)}],[l,i]),u=g.useMemo(()=>OCs({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:s}),[e,t,n,r,s]);return a.jsxs(kl,{fields:c,operators:SCs,value:u,onValueChange:d=>o(jCs(d)),createItemId:d=>d,"aria-label":"Experiments filters",className:"min-w-64 flex-1",children:[a.jsx(kl.Chips,{}),a.jsx(kl.Input,{placeholder:"Filter experiments…"})]})}function _Cs({search:e,statusFilter:t,datasetFilter:n,datasetOptions:r,targetType:s,targetId:i,onFiltersChange:o,selection:l,comparableDatasetId:c}){return a.jsxs(a.Fragment,{children:[a.jsx(rr,{children:a.jsx(rr.Start,{children:a.jsx(CCs,{search:e,statusFilter:t,datasetFilter:n,datasetOptions:r,targetType:s,targetId:i,onChange:o})})}),a.jsxs(rr,{children:[a.jsx(rr.Start,{className:"self-end",children:a.jsx(wCs,{datasetId:c})}),a.jsx(rr.End,{children:a.jsx(bCs,{...l})})]})]})}const TCs={present:!1,targetType:null,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},snt=e=>e?e instanceof Date?e.toISOString():e:null,ICs=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},ECs=(e,t,n,r)=>{if(!e)return TCs;const s=new Map;for(const i of n??[])s.set(i.scorerId,i.reason??null);return{present:!0,targetType:t?.targetType??null,output:e.output,metadata:t?.metadata??null,comment:t?.comment??null,error:t?.error??null,startedAt:snt(t?.startedAt),completedAt:snt(t?.completedAt),scores:Object.entries(e.scores).map(([i,o])=>({scorerId:i,value:o,reason:s.get(i)??null})).sort((i,o)=>i.scorerId.localeCompare(o.scorerId)),usage:t?.traceId?r?.[t.traceId]:void 0}},NCs=(e,t)=>{const n={};for(const r of new Set([...e.scores,...t.scores].map(s=>s.scorerId))){const s=e.scores.find(o=>o.scorerId===r)?.value??null,i=t.scores.find(o=>o.scorerId===r)?.value??null;n[r]=s!=null&&i!=null?i-s:null}return n};function O3(e){return!e.startedAt||!e.completedAt?null:new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime()}function Gye(e){const t=e.scores.map(n=>n.value).filter(n=>n!=null);return t.length>0?t.reduce((n,r)=>n+r,0)/t.length:null}const ACs=(e,t)=>{const n=Gye(e),r=Gye(t);return n!=null&&r!=null?r-n:void 0},PCs=(e,t)=>{const n=O3(e),r=O3(t);return n!=null&&r!=null?r-n:null},$Cs=(e,t)=>{const n=e.usage?.estimatedCost,r=t.usage?.estimatedCost;if(!(n===void 0||r===void 0))return e.usage?.costUnit===t.usage?.costUnit?r-n:void 0},RCs=(e,t)=>{const n=WA(e.usage),r=WA(t.usage);return n!==void 0&&r!==void 0?r-n:void 0},MCs=({comparison:e,experimentIds:t,resultsById:n,scoresById:r,usageById:s})=>{if(!e)return[];const i=new Map(t.map(o=>[o,ICs(n?.[o])]));return e.items.map(o=>{const l=t.map(u=>ECs(o.results[u],i.get(u)?.get(o.itemId),r?.[u]?.[o.itemId],s?.[u]?.traces)),[c]=l;return{itemId:o.itemId,input:o.input,groundTruth:o.groundTruth,sides:l.map((u,d)=>({...u,experimentId:t[d],role:d===0?"baseline":"contender",deltas:d===0?null:NCs(c,u),durationDeltaMs:d===0?null:PCs(c,u),costDelta:d===0?void 0:$Cs(c,u),tokenDelta:d===0?void 0:RCs(c,u),averageScoreDelta:d===0?void 0:ACs(c,u)}))}})};function oN({value:e}){return a.jsx("div",{className:"min-w-0 p-3 text-foreground",children:typeof e=="string"?a.jsx(_l,{children:e}):a.jsx(Cl,{code:JSON.stringify(e??null,null,2),lang:"json",className:"text-caption text-wrap break-all text-muted-foreground"})})}const dee="grid content-start gap-5";function Gg({title:e,actions:t,tone:n="default",collapsible:r=!0,framed:s=!1,children:i}){const o=FX({collapsedHeight:160}),l=r?a.jsx(W6,{state:o,expandLabel:"Expand",children:i}):i;return a.jsxs("section",{className:"grid min-w-0 gap-2",children:[a.jsxs("div",{className:"flex h-7 items-center justify-between gap-2",children:[a.jsx(_t.SectionHeading,{className:Z(n==="negative"&&"text-destructive-foreground"),children:e}),a.jsx("div",{className:"ml-auto flex items-center gap-1",children:t})]}),a.jsxs("div",{role:"region","aria-label":e,className:"min-w-0",children:[s?n==="negative"?a.jsx("div",{className:"min-w-0 overflow-hidden rounded-lg border border-destructive-edge bg-destructive-subtle",children:l}):a.jsx(hl,{className:"min-w-0 overflow-hidden",children:l}):l,r&&o.isExpanded&&o.isClipped&&a.jsx("div",{className:"flex justify-center pt-1",children:a.jsx(ce,{size:"sm",variant:"ghost",icon:a.jsx(pL,{}),onClick:()=>o.setExpanded(!1),children:"Collapse"})})]})]})}function int({label:e,value:t}){return t==null?null:a.jsx(Gg,{title:e,framed:!0,children:a.jsx(oN,{value:t})})}const DCs=e=>e.toFixed(2);function LCs({delta:e,format:t=DCs,higherIsBetter:n=!0}){const r=n?e>0:e<0,s=e===0?"text-muted-foreground":r?"text-success-indicator":"text-destructive-foreground",i=e>0?"+":e<0?"-":"";return a.jsxs("span",{className:Z("inline-flex items-center gap-1 tabular-nums",s),children:[i,t(Math.abs(e)),a.jsx("span",{"aria-hidden":!0,className:"inline-flex size-3.5 shrink-0 [&>svg]:size-3.5",children:e>0?a.jsx(owe,{}):e<0?a.jsx(Vht,{}):null})]})}function Mqt({scorerId:e}){const{Link:t,paths:n}=Sn();return a.jsx(t,{href:n.scorerLink(e),"aria-label":`Open ${e}`,className:"min-w-0 truncate hover:text-foreground hover:underline",children:e})}function RAe({metrics:e}){if(e.length===0)return null;const t=e.some(n=>n.delta!=null);return a.jsx("dl",{className:Z("grid auto-rows-[minmax(1.5rem,auto)] items-center gap-x-4 gap-y-1",t?"grid-cols-[minmax(0,1fr)_auto_auto]":"grid-cols-[minmax(0,1fr)_auto]"),children:e.map(({id:n,icon:r,label:s,value:i,delta:o,formatDelta:l,higherIsBetter:c,emphasis:u})=>a.jsxs(g.Fragment,{children:[a.jsxs("dt",{className:"flex min-w-0 items-center gap-1.5 text-body-sm text-muted-foreground [&>svg]:size-3.5 [&>svg]:shrink-0",children:[r,s]}),a.jsx("dd",{className:Z("flex min-w-0 justify-end text-right text-foreground tabular-nums",u?"text-heading font-semibold":"text-body-sm"),children:i}),t&&a.jsx("dd",{className:"flex justify-end text-body-sm",children:o!=null&&a.jsx(LCs,{delta:o,format:l,higherIsBetter:c})})]},n))})}function Kye({usage:e,showUsage:t,durationMs:n,costDelta:r,tokenDelta:s,durationDeltaMs:i,averageScore:o,scores:l}){const c=e?.costUnit,u=t?[{id:"cost",icon:a.jsx(JH,{}),label:"Cost",value:zz(e?.estimatedCost,c),delta:r??null,formatDelta:Tqt(c),higherIsBetter:!1}]:[],d=t?[{id:"tokens",icon:a.jsx(H0,{}),label:"Tokens",value:aS(WA(e)),delta:s??null,formatDelta:aS,higherIsBetter:!1}]:[],f=n==null?[]:[{id:"duration",icon:a.jsx(fC,{}),label:"Duration",value:Uc(n)??"-",delta:i??null,formatDelta:_qt,higherIsBetter:!1}],h=o?[{id:"avg-score",icon:a.jsx(Sp,{}),label:"Avg score",value:VD(o.value),delta:o.delta??null}]:[];return[...u,...f,...h,...d,...l.map(p=>({id:`scorer:${p.scorerId}`,icon:a.jsx(rw,{}),label:p.label??a.jsx(Mqt,{scorerId:p.scorerId}),value:p.reason?.trim()?a.jsxs("span",{className:"flex items-center gap-1.5",children:[VD(p.value),a.jsx(Iqt,{scorerId:p.scorerId,reason:p.reason})]}):VD(p.value),delta:p.delta??null}))]}function ont(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function zCs(e,t){return Kye({usage:e.usage,showUsage:t,durationMs:O3(e),costDelta:e.costDelta,tokenDelta:e.tokenDelta,durationDeltaMs:e.durationDeltaMs,averageScore:e.scores.length>0?{value:Gye(e),delta:e.averageScoreDelta}:void 0,scores:e.scores.map(n=>({scorerId:n.scorerId,value:n.value,reason:n.reason,delta:e.deltas?.[n.scorerId]??null}))})}function FCs({column:e,isLoading:t,showUsage:n=!1}){if(t)return a.jsx("div",{className:"flex h-32 items-center justify-center",children:a.jsx(On,{})});if(!e.present)return a.jsx(Y,{tone:"muted",className:"py-5 text-center",children:"Not present in this experiment"});const r=ont(e.output),s=NAe(e),i=uee(e),o=zCs(e,n);return a.jsxs("div",{className:dee,children:[o.length>0&&a.jsx(Gg,{title:"Metrics",collapsible:!1,children:a.jsx(RAe,{metrics:o})}),i?a.jsx(Gg,{title:"Error",tone:"negative",framed:!0,actions:a.jsx(ii,{content:i}),children:a.jsx(Y,{tone:"muted",className:"p-3 break-words",children:i})}):a.jsx(Gg,{title:"Output",framed:!0,actions:a.jsx(ii,{content:r}),children:a.jsx(oN,{value:s??e.output})}),e.comment&&a.jsx(Gg,{title:"Comment",framed:!0,children:a.jsx(oN,{value:e.comment})}),e.metadata&&Object.keys(e.metadata).length>0&&a.jsx(Gg,{title:"Metadata",children:a.jsx("dl",{className:"grid gap-1",children:Object.entries(e.metadata).map(([l,c])=>a.jsxs("div",{className:"flex items-start justify-between gap-4",children:[a.jsx("dt",{className:Sa({tone:"muted",variant:"body"}),children:l}),a.jsx("dd",{className:Z(Sa({tone:"ink",variant:"body",font:"mono"}),"break-all"),children:ont(c)})]},l))})})]})}function BCs({datasetId:e,version:t,differsFromBaseline:n}){const{Link:r,paths:s}=Sn();return a.jsxs("span",{className:Z("flex min-w-0 items-center gap-2",n&&"text-warning-foreground"),children:[n&&a.jsx("span",{className:"min-w-0 truncate",children:"differs from baseline"}),a.jsxs(r,{href:`${s.datasetLink(e)}?version=${t}`,"aria-label":`Open dataset v${t}`,className:"shrink-0 hover:underline",children:["v",t]})]})}const ant={baseline:"purple",contender:"blue"};function VCs({role:e,label:t,experiment:n,summary:r,metrics:s,baselineMetrics:i,versionMismatch:o,onSetBaseline:l,showUsage:c=!1}){const{Link:u,paths:d}=Sn(),f=n?Tv(n.id)??n.id:null,h=n?.createdAt?new Date(n.createdAt):null,p=e==="contender",m=(b,S)=>p?vjs(b,S):null,v=n?[...n.targetId?[{id:"target",icon:n.targetType==="agent"?a.jsx(Vo,{}):a.jsx(uAn,{}),label:n.targetType==="agent"?"Agent":"Target",value:n.targetType==="agent"?a.jsx(u,{href:d.agentLink(n.targetId),className:"min-w-0 truncate hover:underline",children:n.targetId}):a.jsx("span",{className:"min-w-0 truncate",children:n.targetId}),delta:null}]:[],...n.datasetId&&n.datasetVersion!=null?[{id:"dataset-version",icon:a.jsx(oG,{}),label:"Dataset version",value:a.jsx(BCs,{datasetId:n.datasetId,version:n.datasetVersion,differsFromBaseline:o}),delta:null}]:[],...h?[{id:"created-at",icon:a.jsx(T4,{}),label:"Created",value:rs(h,"date"),delta:null}]:[]]:[],y=c?s:void 0,x=[...y?[{id:"total-cost",icon:a.jsx(JH,{}),label:"Total cost",value:zz(y.cost,y.costUnit),delta:y.costUnit===i?.costUnit?m(y.cost,i?.cost):null,formatDelta:Tqt(y.costUnit),higherIsBetter:!1,emphasis:!0}]:[],...s?[{id:"avg-duration",icon:a.jsx(fC,{}),label:"Avg duration",value:Uc(s.averageDurationMs)??"-",delta:m(s.averageDurationMs,i?.averageDurationMs),formatDelta:_qt,higherIsBetter:!1,emphasis:!0}]:[],...s&&r&&r.length>0?[{id:"avg-score",icon:a.jsx(Sp,{}),label:"Avg score",value:VD(s.averageScore),delta:m(s.averageScore,i?.averageScore),emphasis:!0}]:[],...y?[{id:"total-tokens",icon:a.jsx(H0,{}),label:"Total tokens",value:aS(y.tokens),delta:m(y.tokens,i?.tokens),formatDelta:aS,higherIsBetter:!1}]:[],...v,...s?[{id:"errors",icon:a.jsx(xP,{}),label:"Errors",value:String(s.errorCount),delta:m(s.errorCount,i?.errorCount),formatDelta:String,higherIsBetter:!1}]:[],...(r??[]).map(({scorerId:b,average:S,delta:k})=>({id:`scorer:${b}`,icon:a.jsx(rw,{}),label:a.jsx(Mqt,{scorerId:b}),value:VD(S),delta:p?k:null}))];return a.jsxs("div",{className:dee,children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n&&a.jsx(ce,{render:a.jsx(u,{href:`/experiments/${n.id}`}),size:"sm",className:"max-w-full min-w-0","aria-label":`Open experiment ${n.name||f}`,children:a.jsx("span",{className:"min-w-0 truncate",children:n.name||f})}),a.jsx("div",{className:"ml-auto shrink-0",children:l?a.jsxs(Qn,{children:[a.jsx(Fn,{render:a.jsx("button",{type:"button","aria-label":"Set as baseline",onClick:l,className:Z("cursor-pointer rounded-[7px] hover:brightness-110",bi)}),children:a.jsx($t,{variant:ant[e],size:"md",icon:a.jsx(rx,{}),children:t})}),a.jsx(Bn,{children:"Set as baseline"})]}):a.jsx($t,{variant:ant[e],size:"md",icon:e==="baseline"?a.jsx(rx,{className:"fill-current"}):a.jsx(rx,{}),children:t})})]}),x.length>0&&a.jsx(Gg,{title:"Summary",collapsible:!1,children:a.jsx(RAe,{metrics:x})})]})}const q7="min-w-0 px-4 py-3",lnt="grid border-border xl:grid-cols-[minmax(22rem,26rem)_repeat(var(--compare-cols),minmax(32rem,1fr))] xl:divide-x xl:divide-border",Oue=e=>e===0?"Baseline":`Contender ${e}`,Yye=e=>e!=null,Xye=e=>e.length>0?e.reduce((t,n)=>t+n,0)/e.length:null,cnt=(e,t,n)=>Xye(e.map(r=>r.sides[t]?.scores.find(s=>s.scorerId===n)?.value??null).filter(Yye)),UCs=(e,t)=>{const n=e.map(r=>r.sides[t]).filter(r=>r?.present);return{errorCount:n.filter(r=>r.error).length,averageScore:Xye(n.flatMap(r=>r.scores.map(s=>s.value)).filter(Yye)),averageDurationMs:Xye(n.map(O3).filter(Yye))}};function qCs({datasetId:e,baselineId:t,contenderIds:n,onSetBaseline:r}){const s=g.useMemo(()=>[t,...n],[t,n]),{data:i,isLoading:o,error:l}=Bcr({datasetId:e,experimentIds:s,baselineId:t,queryOptions:{enabled:!!e&&!!t&&n.length>0}}),{data:c,isLoading:u}=Vke({datasetId:e,experimentIds:s}),d=g.useMemo(()=>s.map(C=>({id:C,status:c[C]?.status})),[s,c]),{data:f,isLoading:h}=Qcr({datasetId:e,experiments:d}),{data:p}=Zcr({experiments:d}),{supportsMetrics:m,isLoading:v}=j$(),{data:y,isLoading:x}=IAe({experiments:d,supportsMetrics:m}),b=g.useMemo(()=>MCs({comparison:i,experimentIds:s,resultsById:f,scoresById:p,usageById:y}),[i,s,f,p,y]),S=g.useMemo(()=>{const C=[...new Set(b.flatMap(T=>T.sides.flatMap(_=>_.scores.map(N=>N.scorerId))))].sort();return s.map((T,_)=>C.map(N=>{const E=cnt(b,_,N),A=cnt(b,0,N),P=_>0&&E!=null&&A!=null?E-A:null;return{scorerId:N,average:E,delta:P}}))},[b,s]),k=g.useMemo(()=>s.map((C,T)=>{const _=y[C]?.summary;return{...UCs(b,T),cost:_?.estimatedCost,costUnit:_?.costUnit,tokens:WA(_)}}),[b,s,y]);if(o||u||v||x)return a.jsx("div",{className:"pointer-events-none fixed inset-0 flex items-center justify-center",children:a.jsx(On,{})});if(l)return a.jsx(Wt,{variant:"warning",title:"Error loading comparison",children:a.jsx(Wt.Message,{children:l instanceof Error?l.message:"Unknown error"})});if(!i||i.items.length===0)return a.jsx(Y,{as:"p",variant:"body",tone:"muted",className:"py-5 text-center",children:"No comparison data"});const j=c[t];return a.jsx(jr,{orientation:"horizontal",mask:{x:"6rem"},children:a.jsxs("div",{role:"table","aria-label":"Experiments comparison",className:"grid",style:{"--compare-cols":s.length},children:[a.jsxs("div",{role:"row",className:Z(lnt,"border-b"),children:[a.jsx("div",{role:"columnheader","aria-label":"Items",className:Z("text-muted-foreground",`${q7} uppercase`),children:a.jsx(Y,{as:"span",variant:"caption",className:"block",children:"Items"})}),s.map((C,T)=>{const _=c[C]??void 0;return a.jsx("div",{role:"columnheader","aria-label":Oue(T),className:q7,children:a.jsx(VCs,{role:T===0?"baseline":"contender",label:Oue(T),experiment:_,summary:S[T],metrics:h?void 0:k[T],baselineMetrics:h?void 0:k[0],versionMismatch:T>0&&_&&j?_?.datasetVersion!==j?.datasetVersion:void 0,onSetBaseline:T>0&&r?()=>r(C):void 0,showUsage:m})},C)})]}),b.map(C=>a.jsxs("div",{role:"row","aria-label":C.itemId,className:Z(lnt,"border-b"),children:[a.jsxs("div",{role:"cell",className:Z(q7,dee),children:[a.jsx(int,{label:"Input",value:C.input}),a.jsx(int,{label:"Ground truth",value:C.groundTruth})]}),C.sides.map((T,_)=>a.jsx("div",{role:"cell","aria-label":Oue(_),className:q7,children:a.jsx(FCs,{column:T,isLoading:h,showUsage:m})},T.experimentId))]},C.itemId))]})})}const PV=10;function QCs(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}const CI=[Ts("/experiments")],ZCs=["createdAt","status"];function WCs(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,i]=g.useState(!1),[o,l]=g.useState([]),c=Lr(),[u,d]=wi(),{sort:f,onSortChange:h}=cT({searchParams:u,setSearchParams:d,allowedKeys:ZCs}),p=g.useMemo(()=>f?{field:f.key,direction:f.direction==="asc"?"ASC":"DESC"}:void 0,[f]),m=u.get("dataset")??"all",{targetType:v,targetId:y}=cqt(),x=G=>{t(G.search),r(G.statusFilter),d(ne=>{const X=new URLSearchParams(ne),ee=(re,ue)=>{ue?X.set(re,ue):X.delete(re)};return ee("dataset",G.datasetFilter==="all"?"":G.datasetFilter),ee(w0,G.targetType),ee(ex,G.targetType===v?G.targetId:""),X},{replace:!0})},{data:b,isLoading:S,error:k}=Ak(),{data:j,isLoading:C,error:T,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:E}=pjs({datasetId:m==="all"?void 0:m,target:{targetType:v,targetId:y},orderBy:p}),{data:A}=eCs(),P=g.useMemo(()=>b?.datasets??[],[b?.datasets]),L=g.useMemo(()=>j??[],[j]),F=g.useMemo(()=>yCs(P),[P]),Q=g.useMemo(()=>QCs(A),[A]),q=S||C,B=T||k,V=G=>{const ne=new Set(L.map(X=>X.id));l(X=>{const ee=X.filter(re=>ne.has(re));return ee.includes(G)?ee.filter(re=>re!==G):ee.length>=PV?[...ee.slice(0,PV-1),G]:[...ee,G]})},W=G=>{l(ne=>ne.length>0?[]:G.slice(0,PV))},{selectedIds:M,selectedDatasetIds:K}=g.useMemo(()=>{const G=new Map(L.map(X=>[X.id,X.datasetId])),ne=o.filter(X=>G.has(X));return{selectedIds:ne,selectedDatasetIds:new Set(ne.map(X=>G.get(X)))}},[L,o]),D=L.find(G=>G.id===M[0])?.datasetId??void 0,$=M.length<2?"Select at least two experiments to compare":K.size!==1?"Only experiments from the same dataset, highlighted in the list, can be compared":void 0,z=()=>{if(M.length<2||$)return;const[G,...ne]=M,[X]=K;if(!X)return;const ee=new URLSearchParams({dataset:X,baseline:G});for(const re of ne)ee.append("contender",re);c(`/experiments/compare?${ee.toString()}`)};if(B&&Cs(B))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:CI}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(ci,{variant:"fill"})]});if(T&&_s(T))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:CI}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Gs,{variant:"fill",resource:"experiments"})]});if(k&&_s(k))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:CI}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Gs,{variant:"fill",resource:"datasets"})]});if(B)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:CI}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Yt,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:B.message})]});const U=a.jsx(cee,{open:s,onOpenChange:i,onSuccess:G=>{c(`/experiments/${G}`)}});return L.length===0&&!q&&m==="all"&&!v?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:CI}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(xCs,{onRunExperiment:()=>i(!0)}),U]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:CI}),headerActions:a.jsx(ce,{variant:"primary",size:"sm",icon:a.jsx(Dr,{}),onClick:()=>i(!0),children:"New experiment"}),actionRow:a.jsx(_Cs,{search:e,statusFilter:n,datasetFilter:m,datasetOptions:F,targetType:v,targetId:y,onFiltersChange:x,selection:{selectedCount:M.length,onClearSelection:()=>l([]),onCompare:z,compareDisabledReason:$},comparableDatasetId:D}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(gCs,{experiments:L,datasets:P,reviewByExperiment:Q,isLoading:q,search:e,statusFilter:n,datasetFilter:m,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:E,sort:f,onSortChange:h,selection:{selectedExperimentIds:M,onToggleSelection:V,onToggleAll:W,comparableDatasetId:D}}),U]})}const HCs={baseline:"bg-badge-purple-indicator",contender:"bg-badge-blue-indicator"};function Dqt({experimentId:e,name:t,role:n,className:r,trailing:s}){const{Link:i,paths:o}=Sn(),l=t||e.slice(0,8);return a.jsxs(ce,{render:a.jsx(i,{href:o.experimentLink(e)}),variant:"ghost",size:"sm",className:Z("max-w-48 min-w-0",r),"aria-label":`Open experiment ${l}`,children:[n&&a.jsx("span",{"aria-hidden":"true",className:Z("size-1.5 shrink-0 rounded-full",HCs[n])}),a.jsx("span",{className:"min-w-0 truncate",children:l}),s&&a.jsx("span",{className:"ml-auto flex shrink-0",children:s})]})}function MAe(){const[e]=wi(),t=e.get("dataset")??void 0,n=e.get("baseline")??void 0,r=g.useMemo(()=>[...new Set(e.getAll("contender"))].filter(s=>s&&s!==n).slice(0,PV-1),[e,n]);return{datasetId:t,baselineId:n,contenderIds:r}}function Lqt(){const{datasetId:e,baselineId:t,contenderIds:n}=MAe(),r=!!(e&&t&&n.length>0);return{datasetId:e,experimentIds:r&&t?[t,...n]:[]}}function GCs(){const{experimentIds:e}=Lqt();return e.length>0?`Comparing ${e.length} experiments`:"Comparing"}function KCs(){const{datasetId:e,experimentIds:t}=Lqt(),{data:n}=Vke({datasetId:e??"",experimentIds:t});return t.length===0?null:a.jsxs(Uk,{children:[a.jsx(yw,{delay:0,closeDelay:100,render:a.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"Show compared experiments",children:a.jsx(fc,{})})}),a.jsx(xw,{side:"bottom",align:"end",sideOffset:4,showArrow:!1,className:"w-72 p-1.5",children:a.jsx("ul",{"aria-label":"Compared experiments",className:"grid gap-0.5",children:t.map((r,s)=>a.jsx("li",{className:"grid",children:a.jsx(Dqt,{className:"w-full max-w-none justify-start",experimentId:r,name:n[r]?.name,role:s===0?"baseline":"contender",trailing:s===0&&a.jsx($t,{variant:"purple",size:"sm",icon:a.jsx(rx,{className:"fill-current"}),children:"Baseline"})})},r))})})]})}function YCs(){const{datasetId:e}=MAe(),{Link:t,paths:n}=Sn(),{data:r,isLoading:s}=Vv({datasetId:e??"",queryOptions:{enabled:!!e}});if(!e||s)return null;const i=r?.name||e;return a.jsx(t,{href:n.datasetLink(e),"aria-label":`Open dataset ${i}`,className:Z("flex max-w-64 min-w-0 rounded-[7px] hover:brightness-110",bi),children:a.jsx($t,{size:"md",icon:a.jsx(zm,{}),className:"max-w-full min-w-0",children:a.jsx("span",{className:"min-w-0 truncate",children:i})})})}function XCs({experimentIds:e}){return e.map((t,n)=>a.jsxs("span",{className:"flex items-center gap-2",children:[n>0&&n===e.length-1&&"and",a.jsxs("span",{className:"flex items-center",children:[a.jsx(Dqt,{experimentId:t}),n<e.length-2&&","]})]},t))}function JCs({datasetId:e,baselineId:t,contenderIds:n}){const[,r]=wi(),s=g.useMemo(()=>[t,...n],[t,n]),{data:i,isLoading:o,error:l}=Vke({datasetId:e,experimentIds:s}),c=u=>{const d=new URLSearchParams({dataset:e,baseline:u});for(const f of s)f!==u&&d.append("contender",f);r(d)};return l&&Cs(l)?a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Compare"}),a.jsx(ci,{variant:"fill"})]}):l&&_s(l)?a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Compare"}),a.jsx(Gs,{variant:"fill",resource:"experiments"})]}):l&&!Pk(l)?a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Compare"}),a.jsx(Yt,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:l.message})]}):!o&&(l||s.some(u=>!i[u]))?a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Compare"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsxs("div",{className:"py-5 text-center text-muted-foreground",children:[a.jsxs(Y,{as:"p",children:["Experiments must belong to the same dataset (",e,") to be compared."]}),a.jsxs(Y,{className:"mt-2 flex items-center justify-center gap-2",children:["One of",a.jsx(XCs,{experimentIds:s}),"was not found in it."]})]})})]}):a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsxs("div",{className:"grid w-full content-start",children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Experiments comparison"}),a.jsx(qCs,{datasetId:e,baselineId:t,contenderIds:n,onSetBaseline:c})]})})}function e_s(){const{datasetId:e,baselineId:t,contenderIds:n}=MAe();return!e||!t||n.length===0?a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Compare"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsxs("div",{className:"py-5 text-center text-muted-foreground",children:[a.jsx(Y,{as:"p",children:"Select two to ten experiments to compare."}),a.jsxs(Y,{className:"mt-2",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentId}","&contender=","{experimentId}","&contender=","{experimentId}"]})]})})]}):a.jsx(JCs,{datasetId:e,baselineId:t,contenderIds:n})}const t_s=[Ts("/experiments"),{id:"experiments-compare",Component:GCs,Switcher:KCs}];function n_s(){return a.jsx(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:t_s}),headerActions:a.jsx(YCs,{}),children:a.jsx(e_s,{})})}function r_s({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[i,o]=g.useState(e.description??""),{updateExperiment:l}=pl(),c=!!r.trim(),u=async d=>{if(d.preventDefault(),!(!c||l.isPending||!e.datasetId))try{await l.mutateAsync({datasetId:e.datasetId,experimentId:e.id,name:r.trim(),description:i.trim()}),Xe.success("Experiment renamed"),n(!1)}catch(f){Xe.error(`Failed to rename experiment: ${f instanceof Error?f.message:"Unknown error"}`)}};return a.jsx(Yr,{open:t,onOpenChange:n,pending:l.isPending,children:a.jsxs(Xr,{children:[a.jsx(Jr,{children:a.jsx(Zr,{children:"Rename Experiment"})}),a.jsxs(Ga,{onSubmit:u,children:[a.jsxs(Qr,{children:[a.jsxs(pt,{children:[a.jsx(dt,{required:!0,children:"Name"}),a.jsx(bn,{required:!0,value:r,onChange:d=>s(d.target.value),placeholder:"Enter experiment name",autoFocus:!0})]}),a.jsxs(pt,{children:[a.jsx(dt,{children:"Description"}),a.jsx(bn,{value:i,onChange:d=>o(d.target.value),placeholder:"Enter experiment description (optional)"})]})]}),a.jsxs(Yo,{children:[a.jsx(_a,{children:"Cancel"}),a.jsx(Ca,{type:"submit",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})]})})}function s_s(e){const{data:t}=r6({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}});return g.useMemo(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!t)return[];const n=new Set;for(const r of Object.values(t))for(const s of r)n.add(s.scorerId);return[...n].sort()},[e.scorerIds,t])}const i_s=["agent","workflow","scorer"];function o_s({experiment:e}){const[t,n]=g.useState(!1),r=Lr(),{paths:s}=Sn(),i=s_s(e),o=i_s.find(c=>c===e.targetType),l=e.status==="running"||e.status==="pending";return!e.datasetId||!o||!e.targetId?null:a.jsxs(a.Fragment,{children:[a.jsx(ce,{variant:"primary",size:"sm",onClick:()=>n(!0),disabled:l,tooltip:l?"Available once this run finishes":"Run this experiment again with the same configuration",icon:a.jsx(Fm,{}),children:"Rerun"}),t&&a.jsx(cee,{open:!0,onOpenChange:n,initialDatasetId:e.datasetId,initialDatasetVersion:e.datasetVersion??void 0,initialTargetType:o,initialTargetId:e.targetId,initialScorerIds:i,initialName:e.name??void 0,initialDescription:e.description??void 0,onSuccess:c=>{r(s.experimentLink(c))}},i.join(","))]})}function a_s({experiment:e,onDeleteClick:t}){const[n,r]=g.useState(!1),s=!!e.datasetId,i=s||!!t;return a.jsxs(a.Fragment,{children:[a.jsx(o_s,{experiment:e}),i&&a.jsxs(lt,{children:[a.jsx(lt.Trigger,{asChild:!0,children:a.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":"Experiment actions menu",children:a.jsx(W0,{})})}),a.jsxs(lt.Content,{align:"end",className:"w-48",children:[s&&a.jsxs(lt.Item,{onSelect:()=>r(!0),children:[a.jsx(Vc,{})," Rename Experiment"]}),t&&a.jsxs(lt.Item,{onSelect:t,variant:"destructive",children:[a.jsx(Xo,{})," Delete Experiment"]})]})]}),n&&a.jsx(r_s,{experiment:e,open:!0,onOpenChange:r})]})}function l_s(e){const{data:t,isLoading:n}=aT({traceId:e,queryOptions:{enabled:!!e}}),s=t?.spans.find(d=>!d.parentSpanId)?.entityType==="agent",{supportsMetrics:i,isLoading:o}=j$(),l=s&&i,c=Tye({traceIds:e?[e]:[],enabled:l,autoRefetch:!1}),u=l&&(c.isLoading||c.isPlaceholderData);return{usage:e?c.data?.get(e):void 0,isLoading:!!e&&(n||o||u)}}const unt="__create_tag__";function zqt({selectedResults:e,vocabulary:t,onAddTag:n,disabled:r,variant:s}){const[i,o]=g.useState(""),l=g.useMemo(()=>[...t].sort(),[t]),c=g.useMemo(()=>{if(e.length===0)return new Set;const[f,...h]=e;return new Set((f.tags??[]).filter(p=>h.every(m=>(m.tags??[]).includes(p))))},[e]),u=g.useMemo(()=>{const f=l.map(m=>({label:m,value:m,end:c.has(m)?a.jsx(ur,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),h=i.trim();return h.length>0&&!l.includes(h)?[{label:`Create "${h}"`,value:unt},...f]:f},[l,c,i]),d=f=>{const h=f===unt?i.trim():f;!h||c.has(h)||n(h)};return a.jsx(fl,{"data-testid":"experiment-results-tag-picker",options:u,value:void 0,onValueChange:d,onInputValueChange:o,placeholder:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(Px,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:s,size:"sm",className:"w-auto min-w-0",disabled:r})}function jue(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function c_s({report:e}){const{served:t,unconsumed:n,liveCalls:r,failure:s}=e,i=[...t.map(o=>({outcome:"served",toolName:o.toolName,args:o.args})),...r.map(o=>({outcome:"live",toolName:o.toolName,args:o.args})),...n.map(o=>({outcome:"unconsumed",toolName:o.toolName,args:o.args}))];return a.jsxs("div",{className:"grid gap-2","data-testid":"tool-mock-report",children:[a.jsx(_t.SectionHeading,{icon:a.jsx(dd,{}),children:"Tool Mocks"}),s&&a.jsx(Wt,{variant:"destructive",title:"Mock mismatch",children:a.jsxs(Wt.Message,{children:[a.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),a.jsxs(Y,{as:"span",variant:"caption",className:"mt-1 block",children:["Called with: ",a.jsx(rh,{children:jue(s.args)})]}),n.length>0&&a.jsxs(Y,{as:"span",variant:"caption",className:"mt-1 block",children:["Unconsumed mocks: ",a.jsx(rh,{children:n.map(o=>jue(o.args)).join(", ")})]})]})}),a.jsx("div",{className:"divide-y divide-border rounded border border-border",children:i.map((o,l)=>a.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-1.5",children:[a.jsxs(Y,{as:"span",variant:"body",className:"min-w-0 truncate",children:[a.jsx(Y,{as:"span",variant:"body-sm",tone:"muted",font:"mono",children:o.toolName}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",font:"mono",className:"ml-2",children:jue(o.args)})]}),a.jsx(Y,{as:"span",variant:"caption",className:`shrink-0 rounded px-2 py-0.5 ${u_s(o.outcome)}`,children:o.outcome})]},`${o.outcome}-${o.toolName}-${l}`))})]})}function u_s(e){switch(e){case"served":return"bg-success-subtle text-success-subtle-foreground";case"live":return"bg-badge-orange-subtle text-badge-orange-foreground";case"unconsumed":return"bg-muted-foreground/10 text-muted-foreground"}}function d_s({result:e,itemId:t,fallback:n,title:r,onClose:s,variant:i="drawer",...o}){const l=r??(t?`Experiment item ${t}`:`Experiment result ${e?.id??""}`),c=e?a.jsx(f_s,{result:e,onClose:s,...o}):t?a.jsxs(a.Fragment,{children:[a.jsxs(_t.Header,{children:[a.jsxs(_t.Heading,{children:["Experiment item",a.jsx(_t.CopyId,{id:t})]}),a.jsx(_t.HeaderActions,{children:a.jsx(_t.CloseButton,{icon:"x",onClick:s})})]}),n]}):null;return i==="inline"?c?a.jsx(_t,{variant:"inline",title:l,children:c}):null:a.jsx(_t,{open:!!(e??t),onClose:s,title:l,depth:1,children:c})}function f_s({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:i,onScoreClick:o,featuredScoreId:l,onFlagForReview:c,onTagsChange:u,tagVocabulary:d=[],isUpdatingTags:f=!1,experimentLink:h,onComplete:p,feedbackTabSlot:m}){const v=Cue(e.input),y=Cue(e.output),x=NAe(e),b=c&&e.status!=="needs-review"&&e.status!=="complete",S=Array.isArray(e.tags)?e.tags:[],k=g.useMemo(()=>[e],[e]),j=!!u||S.length>0,{Link:C}=Sn(),T=m&&e.traceId?e.traceId:void 0,{data:_}=KJ({traceId:T,queryOptions:{enabled:!!T}}),{usage:N,isLoading:E}=l_s(e.traceId),A=E&&(e.targetType==null||e.targetType==="agent"),P=Kye({usage:N,showUsage:!!N||A,durationMs:O3(e),scores:[]}).map(q=>A&&(q.id==="cost"||q.id==="tokens")?{...q,value:a.jsx(bt,{"aria-hidden":!0,className:"h-4 w-14"})}:q),L=typeof e.error=="string"&&e.error?e.error:uee(e),F=[...P,{id:"item-id",icon:a.jsx(hwe,{}),label:"Item Id",value:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"font-mono",title:e.itemId,children:Tv(e.itemId)}),a.jsx(ii,{content:e.itemId,tooltip:"Copy Item Id to clipboard",variant:"link"})]}),delta:null},...e.createdAt?[{id:"created",icon:a.jsx(T4,{}),label:"Created",value:rs(e.createdAt,"date-time"),delta:null}]:[],...e.status?[{id:"status",icon:a.jsx(eTn,{}),label:"Status",value:a.jsx(lAe,{status:e.status}),delta:null}]:[],...j?[{id:"tags",icon:a.jsx(Px,{}),label:"Tags",value:a.jsx(p_s,{tags:S,selectedResults:k,onTagsChange:u,tagVocabulary:d,isUpdatingTags:f}),delta:null}]:[],...Kye({showUsage:!1,durationMs:null,scores:(t??[]).map(q=>({scorerId:q.scorerId,value:q.score,reason:q.reason,label:o?a.jsx(h_s,{scorerId:q.scorerId,featured:l===q.id,onClick:()=>o(q.id)}):void 0}))})],Q=a.jsx(_t.Content,{children:a.jsxs("div",{className:dee,children:[a.jsx(RAe,{metrics:F}),a.jsx(Gg,{title:"Input",framed:!0,actions:a.jsx(ii,{content:v}),children:a.jsx(oN,{value:e.input})}),e.groundTruth!=null&&a.jsx(Gg,{title:"Ground Truth",framed:!0,actions:a.jsx(ii,{content:Cue(e.groundTruth)}),children:a.jsx(oN,{value:e.groundTruth})}),L?a.jsx(Gg,{title:"Error",tone:"negative",framed:!0,actions:a.jsx(ii,{content:L}),children:a.jsx(Y,{tone:"muted",className:"p-3 break-words",children:L})}):a.jsx(Gg,{title:"Output",framed:!0,actions:a.jsx(ii,{content:y}),children:a.jsx(oN,{value:x??e.output})}),e.toolMockReport&&a.jsx(c_s,{report:e.toolMockReport})]})});return a.jsxs(a.Fragment,{children:[a.jsxs(_t.Header,{children:[a.jsx(_t.Heading,{children:"Experiment result"}),a.jsxs(_t.HeaderActions,{children:[b&&a.jsx(ce,{size:"sm",variant:"primary",onClick:()=>c(e.id),icon:a.jsx(ept,{}),children:"Request review"}),p&&e.status==="needs-review"&&a.jsx(ce,{size:"sm",variant:"primary",onClick:p,icon:a.jsx(bP,{}),children:"Mark as reviewed"}),h&&a.jsx(ce,{size:"sm",variant:"ghost",render:a.jsx(C,{href:h}),tooltip:"See experiment","aria-label":"See experiment",children:a.jsx(dL,{})}),e.traceId&&i&&a.jsx(ce,{size:"sm",variant:"ghost",onClick:i,tooltip:"See trace","aria-label":"See trace",children:a.jsx(Sx,{})}),a.jsx(_t.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Go to previous result",nextLabel:"Go to next result"}),a.jsx(_t.CloseButton,{icon:"x",onClick:s})]})]}),T?a.jsxs(Hc,{defaultTab:"details",className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[a.jsx(_t.Header,{children:a.jsxs(Gc,{variant:"pill-ghost",size:"sm",children:[a.jsx(si,{value:"details",children:"Details"}),a.jsxs(si,{value:"feedback",children:["Feedback",_?.pagination?.total!=null&&a.jsxs(a.Fragment,{children:[" (",_.pagination.total,")"]})]})]})}),a.jsx(No,{value:"details",flush:!0,children:Q}),a.jsx(No,{value:"feedback",flush:!0,children:a.jsx(_t.Content,{children:m({traceId:T})})})]}):Q]})}function h_s({scorerId:e,featured:t,onClick:n}){return a.jsx("button",{type:"button","aria-pressed":t,onClick:n,className:Z("min-w-0 cursor-pointer truncate hover:text-foreground hover:underline",t&&"text-foreground"),children:e})}function p_s({tags:e,selectedResults:t,onTagsChange:n,tagVocabulary:r,isUpdatingTags:s}){return a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-1.5",children:[e.map(i=>a.jsxs(oee,{value:i,className:n?"gap-1 pr-1":void 0,children:[i,n&&a.jsx("button",{type:"button","aria-label":`Remove tag ${i}`,disabled:s,onClick:()=>n(e.filter(o=>o!==i)),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:a.jsx(Mn,{className:"size-3"})})]},i)),n&&a.jsx(zqt,{selectedResults:t,vocabulary:r,onAddTag:i=>n([...e,i]),disabled:s,variant:"ghost"})]})}function Cue(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function m_s(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function g_s({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s}){return a.jsx(_t,{open:!!e,onClose:r,title:e?`Score ${e.scorerId}`:"Score",depth:2,children:e&&a.jsx(v_s,{score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s})})}function v_s({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s}){const i=m_s(e),o=i?"N/A — code-based scorer":"N/A — step not configured";return a.jsxs(a.Fragment,{children:[a.jsxs(_t.Header,{children:[a.jsx(_t.CloseButton,{onClick:r,tooltip:"Close score panel"}),a.jsxs(_t.Heading,{children:["Score",a.jsx(_t.CopyId,{id:e.scorerId})]}),a.jsxs(_t.HeaderActions,{children:[s&&e.traceId&&a.jsx(ce,{size:"sm",variant:"ghost",onClick:s,tooltip:"See trace","aria-label":"See trace",children:a.jsx(Sx,{})}),(n||t)&&a.jsx(_t.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Go to previous score",nextLabel:"Go to next score"})]})]}),a.jsx(_t.Content,{children:a.jsxs("div",{className:"grid gap-3",children:[a.jsx(_t.CodeSection,{title:`Score: ${e.score}`,icon:a.jsx(Sp,{}),codeStr:e.reason||o,simplified:!0}),!i&&a.jsxs(a.Fragment,{children:[a.jsx(_t.CodeSection,{title:"Preprocess Prompt",icon:a.jsx(Jp,{}),codeStr:e.preprocessPrompt||o,simplified:!0}),a.jsx(_t.CodeSection,{title:"Analyze Prompt",icon:a.jsx(Jp,{}),codeStr:e.analyzePrompt||o,simplified:!0}),a.jsx(_t.CodeSection,{title:"Generate Score Prompt",icon:a.jsx(Jp,{}),codeStr:e.generateScorePrompt||o,simplified:!0}),a.jsx(_t.CodeSection,{title:"Generate Reason Prompt",icon:a.jsx(Jp,{}),codeStr:e.generateReasonPrompt||o,simplified:!0})]})]})})]})}function Fqt(e,t){const[n,r]=g.useState(null),[s,i]=g.useState(void 0),[o,l]=g.useState(null),[c,u]=g.useState(t);t!==c&&(u(t),r(null),i(void 0),l(null));const d=e?.find(f=>f.id===o)??null;return{featuredTraceId:n,setFeaturedTraceId:r,featuredSpanId:s,setFeaturedSpanId:i,featuredScoreId:o,setFeaturedScoreId:l,featuredScore:d}}function Bqt({result:e,scores:t,state:n,withQueryTrace:r,withFeedback:s,...i}){const o=Fqt(t,e?.id),{navigate:l}=Sn(),{featuredTraceId:c,setFeaturedTraceId:u,featuredSpanId:d,setFeaturedSpanId:f,featuredScoreId:h,setFeaturedScoreId:p,featuredScore:m}=n??o,v=E=>{p(A=>E===A?null:E),u(null),f(void 0)},y=E=>{E&&(u(E),f(void 0),p(null))},x=()=>{if(!h||!t)return;const E=t.findIndex(A=>A.id===h);if(E>=0&&E<t.length-1)return()=>p(t[E+1].id)},b=()=>{if(!h||!t)return;const E=t.findIndex(A=>A.id===h);if(E>0)return()=>p(t[E-1].id)},{data:S,isLoading:k}=hjs({traceId:c,queryOptions:{enabled:!!c}}),j=S?.spans,C=j?.find(E=>!E.parentSpanId),{data:T}=KJ({traceId:c??void 0,queryOptions:{enabled:s&&!!c}}),{data:_}=VNe({traceId:c??void 0,spanId:d,queryOptions:{enabled:s&&!!c&&!!d}}),{data:N}=Uke({traceId:c??void 0,spanId:C?.spanId,page:0,queryOptions:{enabled:!!c&&!!C?.spanId}});return a.jsxs(a.Fragment,{children:[a.jsx(d_s,{...i,result:e,scores:t,onScoreClick:v,featuredScoreId:h,onShowTrace:e?.traceId?()=>y(e.traceId):void 0,feedbackTabSlot:s?({traceId:E})=>a.jsx(IW,{traceId:E},E):void 0}),a.jsx(g_s,{score:m??void 0,onNext:x(),onPrevious:b(),onClose:()=>p(null),onShowTrace:m?()=>y(m.traceId):void 0}),a.jsx(gAe,{size:"wide",depth:2,traceId:c??void 0,spans:j,isLoadingSpans:k,selectedSpanId:d??null,onClose:()=>{u(null),f(void 0)},onSpanSelect:f,showUnavailableFeaturesMsg:!1,traceHref:c?`/traces?traceId=${encodeURIComponent(c)}`:void 0,anchorSpanId:C?.spanId,withQueryTrace:r,withFeedback:s,onOpenScore:(E,A)=>l(n_e(E,A)),feedbackTabBadge:s?T?.pagination?.total??void 0:void 0,feedbackTabSlot:s?({traceId:E})=>a.jsx(IW,{traceId:E}):void 0,scoresTabBadge:N?.pagination?.total??void 0,scoresTabSlot:({traceId:E,rootSpanId:A})=>A?a.jsx(eNe,{traceId:E,spanId:A,onScoreSelect:P=>{t?.some(L=>L.id===P)&&(u(null),f(void 0),p(P))}}):null,spanFeedbackTabBadge:s?_?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:s?({traceId:E,spanId:A})=>E&&A?a.jsx(xUt,{traceId:E,spanId:A},`${E}:${A}`):null:void 0})]})}function dnt({withQueryTrace:e,withFeedback:t,variant:n}){const{currentItemId:r,experimentId:s,datasetId:i,experimentStatus:o,results:l,isLoadingResults:c,hasNextPage:u,close:d,goToPreviousItem:f,goToNextItem:h}=EAe(),p=g.useMemo(()=>r?l.find(k=>k.itemId===r):void 0,[l,r]),{data:m}=r6({experimentId:s,experimentStatus:o,queryOptions:{enabled:!!s}}),{updateExperimentResult:v}=pl(),y=g.useCallback(async k=>{try{await v.mutateAsync({datasetId:i,experimentId:s,resultId:k,status:"needs-review"}),Xe("Result flagged for review")}catch{Xe.error("Failed to flag result for review")}},[i,s,v]),x=g.useCallback(async k=>{try{await v.mutateAsync({datasetId:i,experimentId:s,resultId:k,status:"complete"}),Xe("Result marked as reviewed")}catch{Xe.error("Failed to complete result")}},[i,s,v]),b=p?m?.[p.itemId]:void 0,S=Fqt(b,p?.id);return a.jsx(Bqt,{variant:n,result:p,itemId:r,fallback:c||u?a.jsx(_t.LoadingData,{}):a.jsxs(_t.NoData,{children:['No loaded result for item "',r,'".']}),scores:b,state:S,withQueryTrace:e,withFeedback:t,onPrevious:f,onNext:h,onClose:d,onComplete:p?()=>x(p.id):void 0,onFlagForReview:p?()=>{y(p.id)}:void 0})}const fee=g.createContext(null);function y_s({children:e}){const[t,n]=g.useState(null),[r,s]=g.useState([]),[i,o]=g.useState(!0),c=!Ik()&&i,u=g.useRef(null),d=g.useRef(0),f=g.useCallback((y,x)=>{const b=d.current+1;return d.current=b,s(S=>[...S.filter(k=>k.owner!==y),{owner:y,priority:x,order:b}]),()=>{s(S=>S.filter(k=>!(k.owner===y&&k.order===b)))}},[]),h=g.useMemo(()=>{let y;for(const x of r)(!y||x.priority>y.priority||x.priority===y.priority&&x.order>y.order)&&(y=x);return y?.owner??null},[r]),p=g.useCallback(()=>u.current?.toggle(),[]),m=g.useCallback(y=>o(y<=0),[]),v=g.useMemo(()=>({el:t,setEl:n,activeOwner:h,register:f,panelHandle:u,isCollapsed:c,onPanelResize:m,toggle:p}),[h,t,c,m,f,p]);return a.jsx(fee.Provider,{value:v,children:e})}function fnt(e){const t=g.use(fee);return a.jsx("div",{ref:t?.setEl??void 0,...e})}function Vqt({owner:e,priority:t=0,children:n}){const r=g.use(fee),s=r?.register;return g.useEffect(()=>{if(s)return s(e,t)},[e,t,s]),!r?.el||r.activeOwner!==e?null:So.createPortal(n,r.el)}const hnt=()=>{},x_s={current:null};function Fz(){const e=g.use(fee);if(!e)return{hasPanel:!1,isCollapsed:!0,onPanelResize:hnt,panelHandle:x_s,toggle:hnt};const{activeOwner:t,isCollapsed:n,onPanelResize:r,panelHandle:s,toggle:i}=e;return{hasPanel:t!==null,isCollapsed:n,onPanelResize:r,panelHandle:s,toggle:i}}function b_s(e){const{currentItemId:t,close:n}=EAe(),{hasPanel:r,isCollapsed:s,panelHandle:i}=Fz(),o=Ik(),l=g.useRef(!1);g.useEffect(()=>{if(!t||!r)return;const u=requestAnimationFrame(()=>i.current?.expand());return()=>cancelAnimationFrame(u)},[t,r,i]);const c=g.useEffectEvent(()=>n());return g.useEffect(()=>{if(!r){l.current=!1;return}if(!s){l.current=!0;return}if(!(!l.current||!t)){if(l.current=!1,!document.querySelector('[data-separator="active"]')){c();return}return window.addEventListener("pointerup",c,{once:!0}),()=>window.removeEventListener("pointerup",c)}},[r,s,t]),o?a.jsx(dnt,{...e}):t?a.jsx(Vqt,{owner:"experiment-item",children:a.jsx(dnt,{...e,variant:"inline"})}):null}function Uqt({children:e,className:t}){return a.jsx("div",{className:"@container",children:a.jsx("div",{className:Z("grid gap-4 *:min-w-0! @xl:grid-cols-2 @3xl:has-[>:nth-child(5)]:grid-cols-3 @4xl:grid-cols-[repeat(auto-fit,minmax(12rem,1fr))] @6xl:has-[>:nth-child(5)]:grid-cols-[repeat(auto-fit,minmax(12rem,1fr))]!",t),children:e})})}const qqt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],GA="rootEntityType",KA={tags:"filterTags",entityName:"filterEntityName",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId",provider:"filterProvider",model:"filterModel"},hee=Object.keys(KA),Qqt="mastra:metrics:saved-filters";function w_s(e){const t=N_s(e);try{localStorage.setItem(Qqt,t.toString())}catch{}}function S_s(){try{const e=localStorage.getItem(Qqt);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function k_s(e){if(e.has(GA))return!0;for(const t of hee)if(e.has(KA[t]))return!0;return!1}const DAe="hasAll",O_s=[{id:"is",label:"is"},{id:DAe,label:"has all of",arity:"many"}],j_s={rootEntityType:"Primitive type",entityName:"Primitive name",tags:"Tags",serviceName:"Service Name",environment:"Environment",threadId:"Thread ID",resourceId:"Resource ID",userId:"User ID",organizationId:"Organization ID",runId:"Run ID",sessionId:"Session ID",requestId:"Request ID",experimentId:"Experiment ID",provider:"Provider",model:"Model"},C_s={provider:XU,model:I_},__s=["threadId","resourceId","userId","organizationId","runId","sessionId","requestId","experimentId"],pnt=e=>({id:e,label:j_s[e],icon:C_s[e]??WNe(e),color:JJ()}),mnt=(e,t)=>e.label.localeCompare(t.label);function Zqt({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r}){const s=(d,f)=>({...pnt(d),operators:["is"],strict:!0,suggestions:f}),i=d=>({...pnt(d),operators:["is"]}),o=d=>d.map(f=>({value:f})),l=[s("rootEntityType",qqt.map(d=>({value:d.entityType,label:d.label}))),s("entityName",o(t)),{...s("tags",o(e)),operators:[DAe]},s("serviceName",o(n)),s("environment",o(r))],c=__s.map(i),u=["provider","model"].map(d=>({...i(d),hidden:!0}));return[...l.toSorted(mnt),...c.toSorted(mnt),...u]}function T_s(e){return e.map(t=>{if(t.fieldId==="tags"){const r=[t.value].flat().filter(s=>s!=="");return{id:t.fieldId,fieldId:t.fieldId,operatorId:DAe,value:r}}const n=Array.isArray(t.value)?t.value[0]??"":t.value;return{id:t.fieldId,fieldId:t.fieldId,operatorId:"is",value:Jye(n)?"":n}})}function I_s(e){return e.map(t=>({fieldId:t.fieldId,value:Array.isArray(t.value)?t.value.map(String):String(t.value)}))}function E_s(e){const t=[],n=new Map([[GA,"rootEntityType"]]);for(const s of hee)n.set(KA[s],s);const r=new Set;for(const[s]of e.entries()){const i=n.get(s);if(!i||r.has(i))continue;if(r.add(i),i==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:i,value:l.filter(Boolean)});continue}if(i==="rootEntityType"||i==="entityName"||i==="serviceName"||i==="environment"||i==="provider"||i==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:i,value:l});continue}}const o=e.get(s);o!==null&&t.push({fieldId:i,value:o})}return t}function N_s(e){const t=new URLSearchParams,n=e.getAll(GA);for(const r of n)t.append(GA,r);for(const r of hee){const s=KA[r],i=e.getAll(s);for(const o of i)t.append(s,o)}return t}function A_s(e,t){e.delete(GA);for(const n of hee)e.delete(KA[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?GA:KA[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(i=>typeof i=="string"&&i!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const i of s)e.append(r,i)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const P_s="Any";function Jye(e){const t=e.trim();return t===""||t===P_s}const $_s=new Set(qqt.map(e=>e.entityType));function gnt(e){const t=e.trim();return $_s.has(t)?t:void 0}function R_s(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(i=>typeof i=="string").map(i=>i.trim()).filter(i=>!Jye(i));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const i=s[0],o=i!==void 0?gnt(i):void 0;o&&(t.rootEntityType=o)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Jye(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const i=gnt(s);i&&(t.rootEntityType=i)}else t[r]=s}}return t}const Wqt=[{label:"Last 24 hours",value:"24h"},{label:"Last 3 days",value:"3d"},{label:"Last 7 days",value:"7d"},{label:"Last 14 days",value:"14d"},{label:"Last 30 days",value:"30d"}],M_s=new Set(Wqt.map(e=>e.value));function D_s(e){return typeof e=="string"&&(M_s.has(e)||e==="custom")}const Hqt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",comparisonLabel:"vs previous 24h",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}"});function Kk(){return g.useContext(Hqt)}function L_s(e,t){return e!=="custom"?Wqt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${FE(t.from)} – ${FE(t.to)}`:FE(t.from)??"":"Custom range"}const vnt=3600*1e3;function z_s(e,t){if(e!=="custom")return`vs previous ${e}`;const n=t?.to?.getTime()??Date.now(),r=t?.from?.getTime()??n-24*vnt,s=Math.round((n-r)/vnt);return`vs previous ${s>24&&s%24===0?`${s/24}d`:`${s}h`}`}function F_s({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:i,onCustomRangeChange:o}){const l=g.useMemo(()=>JSON.stringify(n),[n]),c=g.useMemo(()=>n,[l]),u=g.useMemo(()=>R_s(c),[c]),d=g.useMemo(()=>JSON.stringify(u),[u]),f=L_s(t,i),h=z_s(t,i),p=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:i,setCustomRange:o??(()=>{}),dateRangeLabel:f,comparisonLabel:h,filterTokens:c,setFilterTokens:s,dimensionalFilter:u,dimensionalFilterKey:d}),[t,r,i,o,f,h,c,s,u,d]);return a.jsx(Hqt.Provider,{value:p,children:e})}const B_s=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function V_s(e){switch(e){case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return"last-24h"}}function U_s(e){switch(e){case"last-3d":return"3d";case"last-7d":return"7d";case"last-14d":return"14d";case"last-30d":return"30d";case"custom":return"custom";default:return"24h"}}function q_s(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=Kk();return a.jsx(jUt,{preset:V_s(e),onPresetChange:s=>t(U_s(s)),dateFrom:n?.from,dateTo:n?.to,onDateRangeChange:(s,i)=>r({from:s,to:i}),presets:B_s})}function pee({onClick:e}){return a.jsx(ce,{onClick:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:a.jsx(Fa,{})})}function Gqt({onClick:e}){return a.jsx(ce,{onClick:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:a.jsx(lEn,{})})}function Q_s({children:e,reveal:t="always",className:n}){return a.jsx("div",{className:Z("flex shrink-0 items-center gap-1 self-center",t==="hover"&&"opacity-0 transition-opacity duration-150 group-hover/metrics-card:opacity-100 focus-within:opacity-100",n),children:e})}function Z_s({children:e,className:t}){return a.jsx("div",{className:Z("overflow-x-auto overflow-y-hidden [&_tbody>tr:last-child]:border-b-0",t),children:e})}function Kqt({children:e,className:t}){return a.jsx(Y,{tone:"faint",className:Z("mt-0.5",t),children:e})}function W_s({message:e="Failed to load data",className:t}){return a.jsx("div",{className:Z("flex flex-col items-center justify-center gap-3",t),children:a.jsx(Y,{variant:"caption",className:"text-destructive-foreground",children:e})})}function H_s({className:e}){return a.jsx("div",{className:Z("flex items-center justify-center",e),children:a.jsx(On,{size:"md",variant:"pulse",className:"text-placeholder"})})}function G_s({message:e="No data yet",className:t}){return a.jsx("div",{className:Z("flex h-full items-center justify-center",t),children:a.jsx(Y,{tone:"faint",children:e})})}function ynt({children:e,className:t}){return a.jsx(hl,{className:Z("group/metrics-card grid min-h-72 min-w-80 flex-1 grid-rows-[auto_1fr] gap-4 px-4 py-3 2xl:min-w-120 md:min-w-88 lg:min-w-sm xl:min-w-104",t),children:e})}function K_s({value:e,label:t,isLoading:n=!1,className:r}){return n?a.jsxs("div",{className:Z("order-last flex shrink-0 flex-col items-end",r),children:[a.jsx(rq,{line:"text-body",className:"h-4 w-14"}),t&&a.jsx(rq,{line:"text-body mt-0.5",className:"w-10"})]}):a.jsxs("div",{className:Z("order-last text-right",r),children:[a.jsx(Y,{tone:"muted",className:"tabular-nums",children:e}),t&&a.jsx(Y,{tone:"faint",className:"mt-0.5",children:t})]})}function Y_s({value:e,onValueChange:t,children:n}){return a.jsx(Hc,{value:e,onValueChange:t,defaultTab:e,children:a.jsx(Gc,{variant:"pill-ghost",size:"sm",children:n})})}function X_s({className:e,...t}){return a.jsx(si,{...t,className:Z("h-6 px-2.5 text-column",e)})}function Yqt({children:e,className:t,as:n="h2"}){return a.jsx(n,{className:Z("text-body text-foreground",t),children:e})}function J_s(e){if("children"in e)return a.jsx("div",{className:e.className,children:e.children});const{title:t,description:n,titleAs:r}=e;return a.jsxs("div",{className:e.className,children:[a.jsx(Yqt,{as:r,children:t}),n&&a.jsx(Kqt,{children:n})]})}function eTs({children:e,className:t}){return a.jsx("div",{className:Z("flex min-w-0 flex-wrap items-center justify-between gap-x-4 gap-y-2 [&>*:first-child]:min-w-0 [&>*:last-child:not(:first-child)]:ml-auto",t),children:e})}function tTs({children:e,className:t}){return a.jsx("div",{className:Z("flex items-start gap-4 [&>:first-child]:min-w-0 [&>:first-child]:flex-1",t),children:e})}const vi=Object.assign(ynt,{Root:ynt,Kpi:Jh,TopBar:tTs,Toolbar:eTs,Tabs:Y_s,Tab:X_s,Actions:Q_s,TitleAndDescription:J_s,Title:Yqt,Description:Kqt,Summary:K_s,Loading:H_s,Error:W_s,Content:Z_s,NoData:G_s});function uT({isEmpty:e=!1,emptyMessage:t="No data in this range.",children:n}){return a.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[n,e&&a.jsx(vi.NoData,{message:t,className:"absolute inset-0"})]})}function sh({title:e,description:t,summary:n,actions:r,toolbar:s,isUpdating:i=!1,className:o,children:l}){const c=Z("transition-opacity duration-200",i&&"opacity-50");return a.jsxs(vi,{className:Z("min-h-0! min-w-0!",o),children:[a.jsxs(vi.TopBar,{children:[a.jsx(vi.TitleAndDescription,{title:e,description:t}),r&&a.jsx(vi.Actions,{reveal:"hover",children:r}),n&&a.jsx("div",{className:Z("order-last flex w-24 shrink-0 justify-end",c),children:n})]}),a.jsxs(vi.Content,{className:"flex flex-col gap-4 overflow-visible",children:[s,a.jsx("div",{className:Z("relative flex h-60 min-h-0 min-w-0 flex-col",c),children:l})]})]})}function dT(){return a.jsx(vi.Error,{message:"Couldn't load this data. Try again in a moment.",className:"h-full"})}function U1({label:e,icon:t,isError:n=!1,...r}){return a.jsxs(Jh,{children:[a.jsx(Jh.Label,{icon:a.jsx(t,{}),children:e}),n?a.jsx(nTs,{}):a.jsx(rTs,{...r})]})}function nTs(){return a.jsxs(a.Fragment,{children:[a.jsx(Jh.ValueRow,{className:"mt-1",children:a.jsx(Jh.Value,{children:"—"})}),a.jsx(Jh.Footer,{detail:a.jsx("span",{className:"text-destructive-foreground",children:"Couldn't load"})})]})}function rTs({value:e,change:t,lowerIsBetter:n,detail:r,previous:s,comparison:i,isLoading:o=!1,isUpdating:l=!1}){const c=Z("transition-opacity duration-200",l&&"opacity-50");return a.jsxs(a.Fragment,{children:[a.jsxs(Jh.ValueRow,{className:Z("mt-1",c),isLoading:o,children:[a.jsx(Jh.Value,{children:e}),t!==void 0&&a.jsx(Jh.Change,{changePct:t,comparison:i,lowerIsBetter:n,prevValue:s})]}),a.jsx(Jh.Footer,{detail:r,prevValue:t===void 0?void 0:s,isLoading:o,className:c})]})}const sTs={2:"@3xl:grid-cols-2",3:"@3xl:grid-cols-2 @7xl:grid-cols-3"},iTs={1:"",2:"@3xl:col-span-2",full:"col-span-full"};function f1({children:e,columns:t=3,className:n}){return a.jsx("div",{className:Z("@container",n),children:a.jsx("div",{className:Z("grid gap-4",sTs[t]),children:e})})}function oTs({children:e,span:t=1,className:n}){return a.jsx("div",{className:Z("min-w-0 *:w-full *:min-w-0!",iTs[t],n),children:e})}f1.Item=oTs;const exe=1440*60*1e3,aTs={"24h":exe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function lTs(e,t,n){if(e!=="custom"){const r=aTs[e]??exe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-exe),end:t?.to??new Date(n)}}function cTs({datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}){const s=g.useRef(null),i=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==i)&&(s.current={key:i,anchor:Date.now()});const o=s.current.anchor,l=g.useMemo(()=>lTs(e,t,o),[e,t,o]);return{datePreset:e,customRange:t,timestamp:l,filters:g.useMemo(()=>({timestamp:l,...n}),[l,r]),dimensionalFilter:n,filterKey:g.useMemo(()=>`${i}|${r}`,[i,r])}}function uTs(e){const t=Ke(),{filters:n,filterKey:r,queryOptions:s}=e;return Ct({queryKey:["metrics","active-threads-kpi",r],queryFn:()=>t.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:n,comparePeriod:"previous_period"}),...s})}function Xqt(e){const t=Ke(),{filters:n,filterKey:r,queryOptions:s}=e;return Ct({queryKey:["metrics","agent-runs-kpi",r],queryFn:()=>t.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:n,comparePeriod:"previous_period"}),...s})}function dTs(e){const t=Ke(),{filters:n,filterKey:r,queryOptions:s}=e;return Ct({queryKey:["metrics","model-cost-kpi",r],queryFn:async()=>{const i=await t.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:n,comparePeriod:"previous_period"});return{cost:i.estimatedCost??null,costUnit:i.costUnit??null,previousCost:i.previousEstimatedCost??null,costChangePercent:i.costChangePercent??null}},...s})}new Set(Intl.supportedValuesOf("currency"));function fTs(e){const t=Ke(),{filters:n,filterKey:r,queryOptions:s}=e;return Ct({queryKey:["metrics","token-usage-by-agent",r],queryFn:async()=>{const i={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:n},[o,l]=await Promise.all([t.getMetricBreakdown({...i,name:["mastra_model_total_input_tokens"]}),t.getMetricBreakdown({...i,name:["mastra_model_total_output_tokens"]})]),c=new Map,u=f=>HJ(c,f,()=>({input:0,output:0,cost:null,costUnit:null})),d=(f,h)=>{h.estimatedCost!=null&&(f.cost=(f.cost??0)+h.estimatedCost,h.costUnit&&(f.costUnit=h.costUnit))};for(const f of o.groups){const h=u(f.dimensions.entityName??"unknown");h.input=f.value,d(h,f)}for(const f of l.groups){const h=u(f.dimensions.entityName??"unknown");h.output=f.value,d(h,f)}return Array.from(c.entries()).map(([f,h])=>({name:f,input:h.input,output:h.output,total:h.input+h.output,cost:h.cost,costUnit:h.costUnit})).sort((f,h)=>h.total-f.total)},...s})}function hTs(e){const t=Ke(),{filters:n,filterKey:r,queryOptions:s}=e;return Ct({queryKey:["metrics","total-tokens-kpi",r],queryFn:async()=>{const[i,o]=await Promise.all([t.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:n,comparePeriod:"previous_period"}),t.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:n,comparePeriod:"previous_period"})]),l=i.value!=null||o.value!=null,c=i.previousValue!=null||o.previousValue!=null,u=(i.value??0)+(o.value??0),d=(i.previousValue??0)+(o.previousValue??0),f=c&&d>0?(u-d)/d*100:null;return{value:l?u:null,previousValue:c?d:null,changePercent:f}},...s})}async function _ue(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const i of r.groups){const o=i.dimensions.entityName??"unknown",l=i.dimensions.status??"ok",c=HJ(s,o,()=>({completed:0,errors:0}));l==="error"?c.errors+=i.value:c.completed+=i.value}return Array.from(s.entries()).map(([i,o])=>({name:i,...o})).sort((i,o)=>o.completed+o.errors-(i.completed+i.errors))}function pTs(e){const t=Ke(),{filters:n,filterKey:r,queryOptions:s}=e;return Ct({queryKey:["metrics","trace-volume",r],queryFn:async()=>{const[i,o,l]=await Promise.all([_ue(t,"mastra_agent_duration_ms",n),_ue(t,"mastra_workflow_duration_ms",n),_ue(t,"mastra_tool_duration_ms",n)]);return{agentData:i,workflowData:o,toolData:l}},...s})}function mf(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=Kk();return cTs({datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r})}function dv(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}K`:e>=1e3?`${(e/1e3).toFixed(2)}K`:String(Math.round(e))}function xnt(e){return e>=1e4?`${(e/1e3).toFixed(1)}s`:e>=1e3?`${(e/1e3).toFixed(2)}s`:`${Math.round(e)}ms`}function txe(e){const t=e*100;return t===0?"0%":t<.1?"<0.1%":`${t<10?t.toFixed(2):t.toFixed(1)}%`}function eC(e){return e>0&&e<.01?"<$0.01":`$${e.toFixed(2)}`}function mTs(e){return e>=1e6?`${+(e/1e6).toFixed(1)}M`:e>=1e3?`${+(e/1e3).toFixed(1)}K`:String(Math.round(e))}function gTs(e){return e>=1e3?`${+(e/1e3).toFixed(1)}s`:`${Math.round(e)}ms`}const mee={placeholderData:px},LAe=e=>e==null?"—":dv(e),vTs=e=>e==null?"—":eC(e),gee=e=>e==null||!Number.isFinite(e)?void 0:e,zAe=e=>e==null?void 0:dv(e),yTs=e=>e==null?void 0:eC(e);function xTs(){return a.jsxs(Uqt,{children:[a.jsx(bTs,{}),a.jsx(wTs,{}),a.jsx(STs,{}),a.jsx(kTs,{})]})}function bTs(){const{comparisonLabel:e}=Kk(),{data:t,isLoading:n,isPlaceholderData:r,isError:s}=Xqt({...mf(),queryOptions:mee});return a.jsx(U1,{label:"Agent runs",icon:awe,value:LAe(t?.value),change:gee(t?.changePercent),detail:"in this range",previous:zAe(t?.previousValue),comparison:e,isLoading:n,isUpdating:r,isError:s})}function wTs(){const{comparisonLabel:e}=Kk(),{data:t,isLoading:n,isPlaceholderData:r,isError:s}=dTs({...mf(),queryOptions:mee});return a.jsx(U1,{label:"Model cost",icon:JH,value:vTs(t?.cost),change:gee(t?.costChangePercent),lowerIsBetter:!0,detail:"estimated",previous:yTs(t?.previousCost),comparison:e,isLoading:n,isUpdating:r,isError:s})}function STs(){const{comparisonLabel:e}=Kk(),{data:t,isLoading:n,isPlaceholderData:r,isError:s}=hTs({...mf(),queryOptions:mee});return a.jsx(U1,{label:"Tokens",icon:H0,value:LAe(t?.value),change:gee(t?.changePercent),detail:"input and output",previous:zAe(t?.previousValue),comparison:e,isLoading:n,isUpdating:r,isError:s})}function kTs(){const{comparisonLabel:e}=Kk(),{data:t,isLoading:n,isPlaceholderData:r,isError:s}=uTs({...mf(),queryOptions:mee});return a.jsx(U1,{label:"Threads",icon:bwe,value:LAe(t?.value),change:gee(t?.changePercent),detail:"with agent runs",previous:zAe(t?.previousValue),comparison:e,isLoading:n,isUpdating:r,isError:s})}const Jqt=36e5,OTs=24*Jqt,jTs=(e,t)=>t.getTime()-e.getTime()>OTs+Jqt,Q7=e=>e.toLocaleDateString("en-US",{month:"short",day:"numeric"}),bnt=e=>e.toLocaleTimeString("en-US",{hour:"numeric"});function CTs(e,t,n){const r=new Date(e);if(t>=24)return{ts:e,label:Q7(r),edgeLabel:Q7(r),time:r.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})};const s=r.toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric"}),i=`${Q7(r)}, ${bnt(r)}`;return n?{ts:e,label:r.getHours()===0?Q7(r):i,edgeLabel:i,time:s}:{ts:e,label:bnt(r),edgeLabel:i,time:s}}const eQt=36e5,Z7=24*eQt,W7=eQt;function fT(e,t){const n=t.getTime()-e.getTime();return n<=Z7+W7?{interval:"1h",stepHours:1}:n<=3*Z7+W7?{interval:"1h",stepHours:3}:n<=7*Z7+W7?{interval:"1h",stepHours:6}:n<=14*Z7+W7?{interval:"1h",stepHours:12}:{interval:"1d",stepHours:24}}const FAe=e=>e==="1h"?1:24;function BAe(e,t){const n=new Date(e);if(t>=24)return new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime();const r=Math.floor(n.getHours()/t)*t;return new Date(n.getFullYear(),n.getMonth(),n.getDate(),r).getTime()}function tQt(e,t){const n=new Date(e);return t>=24?new Date(n.getFullYear(),n.getMonth(),n.getDate()+1).getTime():BAe(new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()+t).getTime(),t)}function VAe(e,t,n){const r=jTs(e,t),s=[];for(let i=BAe(e.getTime(),n);i<=t.getTime();i=tQt(i,n))s.push(CTs(i,n,r));return s}function UAe(e,t){const n=new Map(e.map((r,s)=>[r.ts,s]));return r=>n.get(BAe(new Date(r.timestamp).getTime(),t))}function vee(e,t){return{from:new Date(e),to:new Date(tQt(e,t))}}const Tue={input:"mastra_model_total_input_tokens",output:"mastra_model_total_output_tokens",cacheRead:"mastra_model_input_cache_read_tokens"},_Ts="mastra_agent_duration_ms";function qAe(){const e=Ke(),{filters:t,filterKey:n,timestamp:r}=mf(),{interval:s,stepHours:i}=fT(r.start,r.end);return Ct({queryKey:["metrics","activity",n,s],placeholderData:px,queryFn:async()=>{const o=v=>e.getMetricTimeSeries({name:[v],interval:s,aggregation:"sum",filters:t}),[l,c,u,d]=await Promise.all([o(Tue.input),o(Tue.output),o(Tue.cacheRead),e.getMetricTimeSeries({name:[_Ts],interval:s,aggregation:"count",groupBy:["status"],filters:t})]),f=VAe(r.start,r.end,i).map(v=>({...v,input:0,cacheRead:0,output:0,cost:0,completed:0,failed:0,failureRate:0})),h=UAe(f,i),p=v=>{const y=h(v);return y===void 0?void 0:f[y]},m=(v,y)=>{for(const x of v){const b=p(x);b&&(b[y]+=x.value,y!=="cacheRead"&&(b.cost+=x.estimatedCost??0))}};for(const v of l.series)m(v.points,"input");for(const v of c.series)m(v.points,"output");for(const v of u.series)m(v.points,"cacheRead");for(const v of d.series){const y=/error|fail/i.test(v.name)?"failed":"completed";for(const x of v.points){const b=p(x);b&&(b[y]+=x.value)}}for(const v of f){v.input=Math.max(v.input-v.cacheRead,0);const y=v.completed+v.failed;v.failureRate=y>0?v.failed/y:0}return f}})}const QAe={xKey:"label",timestampKey:"ts",tooltipLabelKey:"time"},ZAe={...QAe,xKey:"edgeLabel"},mu={green:"var(--chart-share-1)",sky:"var(--chart-share-2)",violet:"var(--chart-share-3)",teal:"var(--chart-share-4)",indigo:"var(--chart-share-5)",error:"var(--chart-red)",neutral:"var(--muted-foreground)"};function yee({data:e,series:t,className:n}){return a.jsx("div",{className:Z("flex flex-wrap items-center gap-x-4 gap-y-1",n),children:t.map(r=>{const s=e?r.aggregate?.(e):void 0;return a.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[r.dashed?a.jsx("span",{className:"h-0 w-3 shrink-0 border-t-2 border-dashed",style:{borderColor:r.color}}):a.jsx("div",{className:"size-2 shrink-0 rounded-[2px]",style:{backgroundColor:r.color}}),a.jsx(Y,{as:"span",variant:"body-sm",tone:"muted",className:"max-w-48 truncate",children:r.label}),s&&a.jsxs(Y,{as:"span",variant:"body-sm",tone:"muted",className:"-ml-1 tabular-nums",children:[s.value,s.suffix&&a.jsxs(Y,{as:"span",variant:"body-sm",tone:"faint",children:[" ",s.suffix]})]})]},r.dataKey)})})}function nQt({active:e,payload:t,label:n,suffix:r,formatValue:s=c=>c.toLocaleString("en-US"),showTotal:i=!1,labelKey:o,formatByKey:l}){if(!e||!t?.length)return null;const c=p=>typeof p=="number"&&Number.isFinite(p),u=t.reduce((p,m)=>p+(c(m.value)?m.value:0),0),d=o?String(t[0]?.payload?.[o]??n??""):n,f=p=>l?.[String(p.dataKey)]??s,h=p=>c(p.value)?f(p)(p.value):typeof p.value=="number"||p.value==null?"—":p.value;return a.jsxs(wCe,{children:[a.jsx(Y,{variant:"column",tone:"ink",className:"mb-1",children:d}),a.jsxs("div",{className:"grid grid-cols-[auto_1fr_auto] items-center gap-x-2 gap-y-1",children:[t.map(p=>a.jsxs("div",{className:"contents",children:[a.jsx("span",{className:"size-2 rounded-[2px]",style:{backgroundColor:p.color}}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"max-w-40 truncate",children:p.name}),a.jsxs("span",{className:"text-right font-mono text-foreground tabular-nums",children:[h(p),c(p.value)&&r]})]},p.name)),i&&a.jsxs("div",{className:"col-span-3 grid grid-cols-subgrid items-center border-t border-border pt-1",children:[a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"col-span-2",children:"Total"}),a.jsxs("span",{className:"text-right font-mono text-foreground tabular-nums",children:[s(u),r]})]})]})]})}const xee={top:8,right:0,bottom:0,left:0},WAe=22,HAe=11;function TTs(e,t){let n=t;const r=()=>(n=(n*9301+49297)%233280,n/233280);let s=.45;return Array.from({length:e},()=>(s=Math.min(.85,Math.max(.25,s+(r()-.5)*.3)),s))}function rQt({kind:e,height:t=210,className:n}){const r=`ghost${g.useId().replace(/:/g,"")}`,s=Upt(),i=TTs(e==="bar"?24:16,e==="bar"?7:11),{ghost:o,mask:l,peak:c}=e==="bar"?ITs(i):ETs(i),u=a.jsxs(a.Fragment,{children:[a.jsxs("defs",{children:[a.jsxs("linearGradient",{id:`${r}-band`,x1:"0",y1:"0",x2:"1",y2:"0",children:[a.jsx("stop",{offset:"0",stopColor:"var(--foreground)",stopOpacity:0}),a.jsx("stop",{offset:"0.5",stopColor:"var(--foreground)",stopOpacity:c}),a.jsx("stop",{offset:"1",stopColor:"var(--foreground)",stopOpacity:0})]}),a.jsx("mask",{id:`${r}-mask`,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"100",height:"100",children:l})]}),o,a.jsx("g",{mask:`url(#${r}-mask)`,children:a.jsx("rect",{width:40,height:100,fill:`url(#${r}-band)`,className:"animate-[chart-ghost-sweep_2s_infinite]",style:{animationDelay:s}})})]}),d=a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"min-h-0 flex-1",style:{paddingTop:xee.top},children:a.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",className:"block size-full","aria-hidden":!0,children:u})}),a.jsx("div",{style:{height:WAe}})]});return t==="fill"?a.jsx("div",{role:"status","aria-label":"Loading chart",className:Z("relative min-h-45 w-full flex-1",n),children:a.jsx("div",{className:"absolute inset-0 flex flex-col",children:d})}):a.jsx("div",{role:"status","aria-label":"Loading chart",className:Z("flex w-full flex-col",n),style:{height:t},children:d})}function ITs(e){const t=100/e.length,n=e.map((r,s)=>a.jsx("rect",{x:s*t+t*.15,width:t*.7,y:100-r*100,height:r*100,rx:.4},s));return{ghost:a.jsx("g",{fill:"var(--foreground)",fillOpacity:.07,children:n}),mask:a.jsx("g",{fill:"white",children:n}),peak:.09}}function ETs(e){const t=100/(e.length-1),n=e.map((i,o)=>[o*t,100-i*100]),r=n.map(([i,o],l)=>{const c=n[l-1];if(!c)return`M${i},${o}`;const[u,d]=c,f=(u+i)/2;return`C${f},${d} ${f},${o} ${i},${o}`}).join(" "),s=`${r} L100,100 L0,100 Z`;return{ghost:a.jsxs(a.Fragment,{children:[a.jsx("path",{d:s,fill:"var(--foreground)",fillOpacity:.025}),a.jsx("path",{d:r,fill:"none",stroke:"var(--foreground)",strokeOpacity:.12,strokeWidth:1.75,vectorEffect:"non-scaling-stroke"})]}),mask:a.jsxs(a.Fragment,{children:[a.jsx("path",{d:s,fill:"white",fillOpacity:.2}),a.jsx("path",{d:r,fill:"none",stroke:"white",strokeWidth:1.75,vectorEffect:"non-scaling-stroke"})]}),peak:.18}}const sQt={vertical:!1,stroke:"var(--border)",strokeDasharray:"3 3",strokeOpacity:.5},NTs={stroke:"var(--border)",strokeDasharray:"3 3",strokeWidth:.8};function iQt(){const e=g.useRef(null),[t,n]=g.useState({width:0,height:0});return g.useLayoutEffect(()=>{const s=e.current?.getBoundingClientRect();s&&n({width:s.width,height:s.height})},[]),{size:t,onResize:(s,i)=>n(o=>o.width===s&&o.height===i?o:{width:s,height:i}),ref:e}}function ATs(e){if(!e)return 3;const t=e-WAe-xee.top;return Math.min(5,Math.max(3,Math.round(t/48)+1))}const $V=6e4,wnt=1440*$V,PTs=[5,10,15,30,60,120,180,240,360,720,1440,2880,10080],$Ts=48,oQt=e=>e.length*HAe*.58;function RTs(e,t,n,r="auto"){const s=t.length-1;if(s<0)return new Set;const i=new Set([0,s]);if(r==="edges"||t.length<3)return i;const o=Math.max(...t.map(p=>oQt(p))),l=Math.floor(n/(o+$Ts));if(l<3)return i;const c=e.every(MTs)?e:void 0,u=c?(c[1]??0)-(c[0]??0):0,d=c?((c[s]??0)-(c[0]??0)+u)/$V:0,f=c?PTs.find(p=>p*$V>=u&&p*$V%u===0&&d/p<=l):void 0;if(!c||!(u>0)||f===void 0){const p=Math.ceil(t.length/l),m=new Set;for(let v=0;v<=s;v+=p)m.add(v);return m.has(s)||(s%p<p/2&&m.delete(s-s%p),m.add(s)),m.size<3?i:m}const h=new Set;return c.forEach((p,m)=>{const v=new Date(p),y=new Date(v.getFullYear(),v.getMonth(),v.getDate()).getTime(),x=u>=wnt||v.getHours()===0&&v.getMinutes()===0;(f<1440?v.getSeconds()===0&&(v.getHours()*60+v.getMinutes())%f===0:x&&Math.round(y/wnt)%(f/1440)===0)&&h.add(m)}),h.size<3?i:h}function MTs(e){return typeof e=="number"&&Number.isFinite(e)}const aQt=3,lQt=e=>e!==void 0&&Number.isFinite(e)&&e>0?e:0;function DTs(e,t,n,{gap:r=0,minSize:s=aQt}={}){const i=e.map(lQt),o=i[t]??0;if(!(o>0)||!Number.isFinite(n.y)||!Number.isFinite(n.height))return;const l=n.height/o,c=i.slice(0,t).reduce((k,j)=>k+j,0),u=n.y+n.height+c*l,d=i.flatMap((k,j)=>k>0?[j]:[]),f=i.reduce((k,j)=>k+j,0)*l,h=r*(d.length-1),p=k=>m[k]??0,m=i.map(k=>k>0&&f>0?Math.max(k*l*(f-h)/f,0):0),v=d.filter(k=>p(k)<s),y=d.filter(k=>p(k)>=s),x=v.reduce((k,j)=>k+s-p(j),0),b=y.reduce((k,j)=>k+p(j)-s,0);for(const k of v)m[k]=s;for(const k of y)m[k]=b>=x?p(k)-(b>0?(p(k)-s)/b*x:0):s;let S=u;for(const k of d){if(S-=p(k),k===t)return{y:S,height:p(k)};S-=r}}function LTs(e,t,{minSize:n=aQt}={}){if(!(!(lQt(e)>0)||!Number.isFinite(t.y)||!Number.isFinite(t.height)))return t.height>=n?t:{y:t.y+t.height-n,height:n}}function zTs({x:e=0,y:t=0,payload:n,picked:r,count:s,plotWidth:i}){if(!n||!i||!r.has(n.index))return null;const o=String(n.value),l=n.offset??0,c=l>0?e-l*(2*n.index+1):e-n.index*i/Math.max(s-1,1),u=oQt(o)/2,d=Math.min(Math.max(e,c+u),c+i-u);return a.jsx("text",{x:d,y:t,dy:"0.71em",textAnchor:"middle",fontSize:HAe,fill:qrt,children:o})}const nxe=new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}),cQt={fontSize:HAe,fill:qrt};function uQt({data:e,xKey:t,timestampKey:n,xLabels:r,plotWidth:s}){const i=e.map(c=>String(c[t]??"")),o=e.map(c=>{const u=c[n];return typeof u=="number"?u:void 0}),l=RTs(o,i,s,r);return a.jsx(E6,{dataKey:t,height:WAe,tick:c=>a.jsx(zTs,{...c,picked:l,count:e.length,plotWidth:s}),tickLine:!1,axisLine:!1,tickMargin:6,interval:0})}const dQt=44;function rxe({id:e=0,show:t,size:n,formatter:r,domain:s,right:i=!1}){return a.jsx(N6,{yAxisId:e,hide:!t,orientation:i?"right":"left",tick:cQt,tickLine:!1,axisLine:!1,width:"auto",tickMargin:4,tickFormatter:r,domain:s,tickCount:ATs(n.height)})}function fQt({height:e,plotRef:t,onResize:n,clickable:r,children:s}){const i=Z("w-full [&_.recharts-surface]:overflow-visible [&_.recharts-surface]:outline-none","[&_*:focus:not(:focus-visible)]:outline-none",r&&"[&_.recharts-surface]:cursor-pointer");return e==="fill"?a.jsx("div",{className:"relative min-h-45 flex-1",children:a.jsx("div",{ref:t,className:Z("absolute inset-0",i),children:a.jsx(hA,{width:"100%",height:"100%",onResize:n,children:s})})}):a.jsx("div",{ref:t,className:i,style:{height:e},children:a.jsx(hA,{width:"100%",height:"100%",onResize:n,children:s})})}function hQt(){return`chart${g.useId().replace(/:/g,"")}`}const FTs=2,BTs=2,VTs=.75,UTs=.55,qTs=3,QTs=.3;function ZTs({fill:e,color:t,capped:n,keys:r,dataKey:s}){return function({x:o=0,width:l=0,index:c,payload:u,...d}){const f=r.map(S=>Number(u?.[S])||0),h=r.indexOf(s),p={y:d.y??0,height:Math.max(d.height??0,0)},m=r.length>1?DTs(f,h,p,{gap:BTs}):LTs(f[h]??0,p);if(!m)return a.jsx("g",{});const{y:v,height:y}=m,x=Math.min(FTs,Math.floor(y/3)),b={"data-bucket":c,style:{transition:"opacity 150ms ease-out"}};return n?a.jsxs("g",{...b,children:[a.jsx(ZE,{x:o,y:v,width:l,height:y,radius:x,fill:t,fillOpacity:UTs}),a.jsx(ZE,{x:o,y:v,width:l,height:Math.min(qTs,y),radius:x,fill:t})]}):a.jsx("g",{...b,children:a.jsx(ZE,{x:o,y:v,width:l,height:y,radius:x,fill:e})})}}function WTs({scope:e,setter:t}){const[n,r]=g.useState();return g.useLayoutEffect(()=>{t.current=r},[t]),n===void 0?null:a.jsx("style",{children:`[data-chart-scope="${e}"] [data-bucket]:not([data-bucket="${n}"]){opacity:${QTs}}`})}function pQt(e){const{data:t,series:n,overlay:r,height:s=210,showLegend:i=!0,isLoading:o=!1,className:l}=e,c=hQt(),u=Z(s==="fill"&&"flex min-h-0 flex-1 flex-col",l),d=r?[...n,{...r,dashed:!0}]:n;return a.jsxs("div",{className:u,"data-chart-scope":c,children:[i&&a.jsx(yee,{data:o?void 0:t,series:d,className:"mb-4"}),o?a.jsx(rQt,{kind:"bar",height:s}):a.jsx(HTs,{...e,id:c})]})}function HTs({data:e,series:t,height:n=210,yDomain:r,valueFormatter:s,axisFormatter:i,referenceLine:o,variant:l="gradient",showYAxis:c=!0,showTotal:u=t.length>1,xKey:d="time",timestampKey:f="tsMs",xLabels:h="auto",tooltipLabelKey:p,onBucketClick:m,overlay:v,id:y}){const x=g.useRef(()=>{}),{size:b,onResize:S,ref:k}=iQt(),j=t.map(E=>E.dataKey).join("\0"),C=t.map(E=>E.color).join("\0"),T=g.useMemo(()=>{const E=j.split("\0"),A=C.split("\0");return E.map((P,L)=>ZTs({fill:`url(#${y}-bar-${L})`,color:A[L]??"",capped:l==="capped",keys:E,dataKey:P}))},[j,C,l,y]),_=s??nxe.format,N=b.width-(c?dQt:0);return a.jsxs(a.Fragment,{children:[a.jsx(WTs,{scope:y,setter:x}),a.jsx(fQt,{height:n,plotRef:k,onResize:S,clickable:!!m,children:a.jsxs(bCe,{data:e,margin:xee,onMouseMove:E=>{const A=E?.activeTooltipIndex;x.current(A==null?void 0:Number(A))},onMouseLeave:()=>x.current(void 0),onClick:E=>{const A=E?.activeTooltipIndex,P=A==null?void 0:e[Number(A)];m&&P&&m(P,Number(A))},children:[a.jsx("defs",{children:t.map((E,A)=>a.jsxs("linearGradient",{id:`${y}-bar-${A}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"0%",stopColor:E.color,stopOpacity:1}),a.jsx("stop",{offset:"100%",stopColor:E.color,stopOpacity:VTs})]},E.dataKey))}),a.jsx(aCe,{...sQt}),uQt({data:e,xKey:d,timestampKey:f,xLabels:h,plotWidth:N}),rxe({show:c,size:b,formatter:i??_,domain:r}),v&&rxe({id:"overlay",show:!1,size:b,formatter:v.valueFormatter??nxe.format,right:!0}),a.jsx(j6,{cursor:!1,content:a.jsx(nQt,{formatValue:_,showTotal:u&&!v,labelKey:p,formatByKey:v?.valueFormatter?{[v.dataKey]:v.valueFormatter}:void 0})}),t.map((E,A)=>a.jsx(XNt,{dataKey:E.dataKey,name:E.label,stackId:"1",fill:E.color,maxBarSize:28,isAnimationActive:!1,shape:T[A]},E.dataKey)),v&&a.jsx(fCe,{yAxisId:"overlay",type:"monotone",dataKey:v.dataKey,name:v.label,stroke:v.color,strokeWidth:1.75,strokeDasharray:"4 3",dot:!1,activeDot:{r:3.5,fill:v.color,stroke:"var(--background)",strokeWidth:2},isAnimationActive:!1,connectNulls:!0}),o&&a.jsx(ZY,{y:o.value,ifOverflow:"extendDomain",stroke:o.color,strokeDasharray:"4 4",label:{value:o.label,position:"insideTopLeft",...cQt}})]})})]})}const GTs=[{dataKey:"input",label:"Input",color:mu.green},{dataKey:"cacheRead",label:"Cache read",color:mu.violet},{dataKey:"output",label:"Output",color:mu.sky}],KTs=[{dataKey:"cost",label:"Cost",color:mu.green}],YTs=e=>`$${e.toFixed(e<10?1:0)}`;function XTs({onViewTraces:e,onTimeRangeClick:t}){const[n,r]=g.useState("tokens"),{data:s=[],isLoading:i,isError:o,isPlaceholderData:l}=qAe(),{timestamp:c}=mf(),{stepHours:u}=fT(c.start,c.end),d=s.reduce((v,y)=>v+y.input+y.cacheRead+y.output,0),f=s.reduce((v,y)=>v+y.cost,0),h=n==="tokens",p=h?GTs:KTs,m={title:"Token usage",description:h?"Input, cache reads and output.":"Estimated model spend.",actions:e&&a.jsx(pee,{onClick:e}),toolbar:a.jsxs(vi.Toolbar,{children:[a.jsx(yee,{series:p}),a.jsxs(vi.Tabs,{value:n,onValueChange:r,children:[a.jsx(vi.Tab,{value:"tokens",children:"Tokens"}),a.jsx(vi.Tab,{value:"cost",children:"Cost"})]})]})};return o?a.jsx(sh,{...m,children:a.jsx(dT,{})}):a.jsx(sh,{...m,summary:a.jsx(vi.Summary,{value:h?dv(d):eC(f),label:h?"tokens":"cost",isLoading:i}),isUpdating:l,children:a.jsx(uT,{isEmpty:!i&&d===0&&f===0,emptyMessage:"No model calls in this range.",children:a.jsx(pQt,{data:s,series:p,height:"fill",showLegend:!1,valueFormatter:h?dv:eC,axisFormatter:h?mTs:YTs,onBucketClick:t&&(v=>t(vee(Number(v.ts),u))),isLoading:i,...QAe})})})}const JTs=[{dataKey:"completed",label:"Completed",color:mu.green},{dataKey:"failed",label:"Failed",color:mu.error}];function eIs({onTimeRangeClick:e}){const{data:t=[],isLoading:n,isError:r,isPlaceholderData:s}=qAe(),{timestamp:i}=mf(),{stepHours:o}=fT(i.start,i.end),l=t.reduce((u,d)=>u+d.completed+d.failed,0),c={title:"Agent runs",description:"Completed and failed runs."};return r?a.jsx(sh,{...c,children:a.jsx(dT,{})}):a.jsx(sh,{...c,summary:a.jsx(vi.Summary,{value:dv(l),label:"runs",isLoading:n}),isUpdating:s,children:a.jsx(uT,{isEmpty:!n&&l===0,emptyMessage:"No agent runs in this range.",children:a.jsx(pQt,{data:t,series:JTs,height:"fill",xLabels:"edges",valueFormatter:dv,onBucketClick:e&&(u=>e(vee(Number(u.ts),o))),isLoading:n,...ZAe})})})}const Snt=1.75,tIs=.12,nIs=12;function rIs({points:e}){const[t,n]=e??[];return!t||!n?null:a.jsx("line",{x1:0,x2:0,y1:t.y,y2:n.y,...NTs,className:"pointer-events-none transition-transform duration-150 ease-out",style:{transform:`translateX(${t.x}px)`}})}function GAe(e){const{data:t,series:n,height:r=210,showLegend:s=!0,isLoading:i=!1,className:o}=e,l=Z(r==="fill"&&"flex min-h-0 flex-1 flex-col",o);return a.jsxs("div",{className:l,children:[s&&a.jsx(yee,{data:i?void 0:t,series:n,className:"mb-4"}),i?a.jsx(rQt,{kind:"line",height:r}):a.jsx(sIs,{...e})]})}function sIs({data:e,series:t,height:n=210,yDomain:r,onPointClick:s,onBucketClick:i,xKey:o="time",timestampKey:l="tsMs",xLabels:c="auto",tooltipLabelKey:u,showDots:d=!1,valueFormatter:f,axisFormatter:h,showYAxis:p=!0}){const m=hQt(),{size:v,onResize:y,ref:x}=iQt(),b=f??nxe.format,S=C=>e.filter(T=>typeof T[C]=="number").length<=nIs,k=v.width-(p?dQt:0),j=C=>({r:3.5,fill:C.color,stroke:"var(--background)",strokeWidth:2,...s&&{style:{cursor:"pointer"},onClick:(T,_)=>{knt(_)&&knt(_.payload)&&s(_.payload,C.dataKey)}}});return a.jsx(fQt,{height:n,plotRef:x,onResize:y,clickable:!!i,children:a.jsxs(bCe,{data:e,margin:xee,onClick:C=>{const T=C?.activeTooltipIndex,_=T==null?void 0:e[Number(T)];i&&_&&i(_,Number(T))},children:[a.jsx("defs",{children:t.map((C,T)=>a.jsxs("linearGradient",{id:`${m}-area-${T}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"0%",stopColor:C.color,stopOpacity:tIs}),a.jsx("stop",{offset:"95%",stopColor:C.color,stopOpacity:0})]},C.dataKey))}),a.jsx(aCe,{...sQt}),uQt({data:e,xKey:o,timestampKey:l,xLabels:c,plotWidth:k}),rxe({show:p,size:v,formatter:h??b,domain:r}),a.jsx(j6,{content:a.jsx(nQt,{formatValue:b,labelKey:u}),cursor:a.jsx(rIs,{})}),t.map((C,T)=>{const _={type:"monotone",dataKey:C.dataKey,name:C.label,stroke:C.color,strokeWidth:C.emphasis?Snt+.5:Snt,strokeDasharray:C.dashed?"4 3":void 0,dot:d||S(C.dataKey)?{r:3,fill:C.color,strokeWidth:0}:!1,activeDot:j(C),isAnimationActive:!1,connectNulls:!0};return C.dashed?a.jsx(fCe,{..._},C.dataKey):a.jsx(HY,{..._,fill:`url(#${m}-area-${T})`,fillOpacity:1},C.dataKey)})]})})}function knt(e){return typeof e=="object"&&e!==null}const iIs=[{dataKey:"failureRate",label:"Failed runs",color:mu.error}],oIs=e=>`${Math.round(e*100)}%`;function aIs({onViewErrors:e,onTimeRangeClick:t}){const{data:n=[],isLoading:r,isError:s,isPlaceholderData:i}=qAe(),{timestamp:o}=mf(),{stepHours:l}=fT(o.start,o.end),c=n.reduce((h,p)=>h+p.completed+p.failed,0),u=n.reduce((h,p)=>h+p.failed,0),d=u===0?[0,1]:void 0,f={title:"Failure rate",description:"Share of agent runs that failed.",actions:e&&a.jsx(Gqt,{onClick:e})};return s?a.jsx(sh,{...f,children:a.jsx(dT,{})}):a.jsx(sh,{...f,summary:a.jsx(vi.Summary,{value:txe(c>0?u/c:0),label:"failed",isLoading:r}),isUpdating:i,children:a.jsx(uT,{isEmpty:!r&&c===0,emptyMessage:"No agent runs in this range.",children:a.jsx(GAe,{data:n,series:iIs,height:"fill",xLabels:"edges",valueFormatter:txe,axisFormatter:oIs,yDomain:d,onBucketClick:t&&(h=>t(vee(Number(h.ts),l))),isLoading:r,...ZAe})})})}const lIs={agents:"mastra_agent_duration_ms",workflows:"mastra_workflow_duration_ms",tools:"mastra_tool_duration_ms"},Ont=["agents","workflows","tools"];function cIs(){const e=Ke(),{filters:t,filterKey:n,timestamp:r}=mf(),{interval:s}=fT(r.start,r.end),i=FAe(s);return Ct({queryKey:["metrics","latency-percentiles",n,s],placeholderData:px,queryFn:async()=>{const o=await Promise.all(Ont.map(u=>e.getMetricPercentiles({name:lIs[u],percentiles:[.5,.95],interval:s,filters:t}))),l=VAe(r.start,r.end,i),c=UAe(l,i);return o.forEach((u,d)=>{const f=Ont[d];if(f)for(const h of u.series){const p=uIs(f,h.percentile);if(p)for(const m of h.points){const v=l[c(m)??-1];v&&(v[p]=Math.round(m.value))}}}),l}})}function uIs(e,t){if(t===.5)return`${e}P50`;if(t===.95)return`${e}P95`}const dIs={agents:od.AGENT,workflows:od.WORKFLOW_RUN,tools:od.TOOL};function fIs(e){return[{dataKey:`${e}P50`,label:"P50",color:mu.sky},{dataKey:`${e}P95`,label:"P95",color:mu.green,emphasis:!0}]}const hIs={agents:"agent runs",workflows:"workflow runs",tools:"tool calls"};function pIs({onViewTraces:e,onTimeRangeClick:t}){const[n,r]=g.useState("agents"),{data:s=[],isLoading:i,isError:o,isPlaceholderData:l}=cIs(),{timestamp:c}=mf(),u=FAe(fT(c.start,c.end).interval),d=fIs(n),f=Math.max(0,...s.map(p=>p[`${n}P95`]??0)),h={title:"Latency",description:"Duration percentiles.",actions:e&&a.jsx(pee,{onClick:()=>e(dIs[n])}),toolbar:a.jsxs(vi.Toolbar,{children:[a.jsx(yee,{series:d}),a.jsxs(vi.Tabs,{value:n,onValueChange:r,children:[a.jsx(vi.Tab,{value:"agents",children:"Agents"}),a.jsx(vi.Tab,{value:"workflows",children:"Workflows"}),a.jsx(vi.Tab,{value:"tools",children:"Tools"})]})]})};return o?a.jsx(sh,{...h,children:a.jsx(dT,{})}):a.jsx(sh,{...h,summary:a.jsx(vi.Summary,{value:f>0?xnt(f):"—",label:"peak P95",isLoading:i}),isUpdating:l,children:a.jsx(uT,{isEmpty:!i&&f===0,emptyMessage:`No ${hIs[n]} in this range.`,children:a.jsx(GAe,{data:s,series:d,height:"fill",xLabels:"edges",showLegend:!1,valueFormatter:xnt,axisFormatter:gTs,onBucketClick:t&&(p=>t(vee(Number(p.ts),u))),isLoading:i,...ZAe})})})}function mQt({columns:e=[],valueLabel:t,valueWidth:n="w-14",className:r}){return a.jsxs("div",{"aria-hidden":!0,className:Z("flex shrink-0 items-center gap-3 text-column text-placeholder",r),children:[e.map(s=>a.jsx("span",{className:Z("shrink-0 text-right",s.width??"w-16"),children:s.label},s.label)),a.jsx("span",{className:"w-12 shrink-0 text-right",children:"Share"}),a.jsx("span",{className:Z("shrink-0 text-right",n),children:t})]})}const gQt="-mx-2 flex w-[calc(100%+1rem)] items-center gap-3 rounded-md px-2 py-1 text-left",aN="shrink-0 text-right text-body-sm tabular-nums";function mIs({row:e,columns:t,valueWidth:n,share:r,highlighted:s,dimmed:i,onHover:o,LinkComponent:l}){const c=Z(gQt,"transition-[background-color,opacity] duration-150",s&&"bg-fill-subtle",(e.href||e.onClick)&&"hover:bg-fill-subtle");return a.jsx("li",{children:a.jsxs(gIs,{row:e,LinkComponent:l,className:c,style:{opacity:i?.5:1},onMouseEnter:o,children:[a.jsx("span",{className:"size-2 shrink-0 rounded-[2px]",style:{backgroundColor:e.paint.color,opacity:e.paint.alpha}}),a.jsx(vIs,{row:e}),t.map((u,d)=>a.jsx("span",{className:Z(aN,"text-muted-foreground",u.width??"w-16"),children:e.cells?.[d]},u.label)),a.jsx("span",{className:Z(aN,"w-12 text-muted-foreground"),children:r}),a.jsx("span",{className:Z(aN,"text-foreground",n),children:e.value})]})})}function gIs({row:e,LinkComponent:t,...n}){if(e.href){const r=t??"a";return a.jsx(r,{href:e.href,...n})}return e.onClick?a.jsx("button",{type:"button",onClick:e.onClick,...n}):a.jsx("div",{...n})}function vIs({row:e}){return typeof e.label!="string"?a.jsx("span",{className:"flex min-w-0 flex-1",title:e.title,children:e.label}):a.jsx("span",{className:"min-w-0 flex-1 truncate",title:e.title??e.label,children:a.jsx(Y,{as:"span",variant:"body-sm",tone:"ink",children:e.label})})}const yIs="var(--chart-share-1)",jnt=[1,2,3,4,5].map(e=>`var(--chart-share-${e})`),xIs=[3,4,2,5,1].map(e=>`var(--chart-share-${e})`),bIs=[1,.7,.48,.32,.2,.14],bee={color:"var(--chart-share-rest)",alpha:1},wIs=50,l_="__rest";function vQt(e,t,n){if(n==="hues"){const r=jnt.includes(e)?[e,...jnt.filter(s=>s!==e)]:[e,...xIs];return Array.from({length:t},(s,i)=>({color:r[i%r.length]??e,alpha:[1,.55,.3][Math.floor(i/r.length)]??.2}))}return Array.from({length:t},(r,s)=>({color:e,alpha:bIs[s]??.1}))}const KAe=e=>e.reduce((t,n)=>t+Math.max(n.share,0),0);function SIs(e){return e.map(t=>Number.isFinite(t.share)&&t.share>0?t:{...t,share:0}).toSorted((t,n)=>n.share-t.share)}function kIs(e,{limit:t,other:n,color:r,palette:s}){if(e.length<=t+1)return{shown:Cnt(e,r,s),rest:[]};const i=e.slice(t),o=n?.(i),l={key:l_,label:`Other (${i.length})`,share:KAe(i),value:o?.value,cells:o?.cells,paint:bee,segment:l_};return{shown:[...Cnt(e.slice(0,t),r,s),l],rest:i}}function Cnt(e,t,n){const r=vQt(t,e.length,n);return e.map((s,i)=>({...s,paint:r[i]??bee,segment:s.key}))}function OIs(e,{count:t,activeKey:n,color:r,palette:s}){const i=Math.min(t,e.length,wIs),o=vQt(r,i,s),l=new Map(e.map((u,d)=>[u.key,d]));return{shown:jIs(e,t,n).map(u=>{const d=l.get(u.key)??e.length;return{...u,paint:o[d]??bee,segment:d<i?u.key:l_}}),rest:e.slice(i)}}function jIs(e,t,n){const r=e.slice(0,t),s=n?e.findIndex(o=>o.key===n):-1,i=s>=t?e[s]:void 0;return i?[...r,i]:r}function CIs(e,t){const n=e.filter(o=>o.segment!==l_).map(o=>({key:o.key,share:o.share,paint:o.paint})),r=t.length?[{key:l_,share:KAe(t),paint:bee}]:[],s=[...n,...r].filter(o=>o.share>0),i=s.reduce((o,l)=>o+l.share,0);return s.map(o=>({key:o.key,paint:o.paint,grow:o.share/i*100}))}function _Is(e,t){if(t!==void 0)return e.find(n=>n.key===t)?.segment??t}const TIs=(e,t)=>t!==void 0&&t!==e;function IIs(e,t){return t===void 0||t===e.key?!1:!(t===l_&&e.segment===l_)}const EIs=(e,t)=>{const n=e/(t||1);return n>0?n<.001?"<0.1%":`${(n*100).toFixed(n<.1?1:0)}%`:"0%"};function NIs({shown:e,total:t,limit:n,pageSize:r,onMore:s,onLess:i}){if(t<=n)return null;const o=t-e,l="flex items-center gap-1.5 rounded-md px-2 py-1 text-body-sm font-medium text-muted-foreground transition-colors duration-150 hover:bg-fill-subtle hover:text-foreground",c=new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1});return a.jsxs("li",{className:"-mx-2 flex items-center gap-1",children:[o>0&&a.jsxs("button",{type:"button",onClick:s,className:l,children:[a.jsx(fc,{className:"size-3.5 shrink-0"}),"Show ",Math.min(o,r)," more"]}),e>n&&a.jsxs("button",{type:"button",onClick:i,className:l,children:[a.jsx(YH,{className:"size-3.5 shrink-0"}),"Show top ",n]}),o>0&&a.jsxs("span",{className:"ml-auto pr-2 text-body-sm text-placeholder tabular-nums",children:[c.format(e)," of ",c.format(t)]})]})}const _nt=["w-32","w-24","w-36","w-20","w-28"];function H7({className:e}){return a.jsxs(a.Fragment,{children:["​",a.jsx(bt,{className:Z("absolute top-1/2 h-3.5 -translate-y-1/2",e)})]})}function AIs({rows:e,columns:t,valueWidth:n}){return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"flex h-2",children:a.jsx(bt,{className:"size-full rounded-full"})}),a.jsx("ul",{className:"grid min-w-0 grid-cols-1 gap-0.5","aria-busy":!0,children:Array.from({length:e},(r,s)=>a.jsxs("li",{className:gQt,children:[a.jsx(bt,{className:"size-2 shrink-0 rounded-[2px]"}),a.jsx("span",{className:"min-w-0 flex-1",children:a.jsx(Y,{as:"span",variant:"body-sm",className:"relative",children:a.jsx(H7,{className:Z("left-0",_nt[s%_nt.length])})})}),t.map(i=>a.jsx("span",{className:Z(aN,"relative",i.width??"w-16"),children:a.jsx(H7,{className:"right-0 w-10"})},i.label)),a.jsx("span",{className:Z(aN,"relative w-12"),children:a.jsx(H7,{className:"right-0 w-9"})}),a.jsx("span",{className:Z(aN,"relative",n),children:a.jsx(H7,{className:"right-0 w-12"})})]},s))})]})}function j3({showHeader:e=!0,className:t,...n}){const{columns:r=[],valueLabel:s,valueWidth:i="w-14"}=n;return a.jsxs("div",{className:Z("grid grid-cols-1 gap-4",t),children:[e&&a.jsx("div",{className:"flex justify-end",children:a.jsx(mQt,{columns:r,valueLabel:s,valueWidth:i})}),a.jsx(PIs,{...n})]})}function PIs({rows:e,columns:t=[],valueLabel:n,valueWidth:r="w-14",palette:s="shades",color:i=yIs,limit:o=5,overflow:l="other",pageSize:c=50,other:u,activeKey:d,emptyState:f="No data in this range.",isLoading:h=!1,LinkComponent:p}){const[m,v]=g.useState(),[y,x]=g.useState(0),b=o+y*c;if(h)return a.jsx(AIs,{rows:l==="other"?o+1:o,columns:t,valueWidth:r});const S=SIs(e);if(S.length===0)return a.jsx(Y,{variant:"body-sm",tone:"muted",className:"py-6 text-center",children:f});const k=KAe(S),j=l==="more",{shown:C,rest:T}=j?OIs(S,{count:b,activeKey:d,color:i,palette:s}):kIs(S,{limit:o,other:u,color:i,palette:s}),_=CIs(C,T),N=_Is(C,m),E=()=>v(void 0);return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"flex h-2 gap-0.5",onMouseLeave:E,children:_.map(A=>a.jsx("span",{"data-testid":"metrics-share-segment",onMouseEnter:()=>v(A.key),className:"h-full min-w-[3px] transition-opacity duration-150 first:rounded-l-full last:rounded-r-full",style:{flex:`${A.grow} 1 0`,backgroundColor:A.paint.color,opacity:A.paint.alpha*(TIs(A.key,N)?.3:1)}},A.key))}),a.jsxs("ul",{className:"grid min-w-0 grid-cols-1 gap-0.5",onMouseLeave:E,children:[C.map(A=>a.jsx(mIs,{row:A,columns:t,valueWidth:r,share:EIs(A.share,k),highlighted:m===A.key||d===A.key,dimmed:IIs(A,m),onHover:()=>v(A.key),LinkComponent:p},A.key)),j&&a.jsx(NIs,{shown:Math.min(b,S.length),total:S.length,limit:o,pageSize:c,onMore:()=>x(A=>A+1),onLess:()=>x(0)})]})]})}j3.Header=mQt;const $Is={agents:od.AGENT,workflows:od.WORKFLOW_RUN,tools:od.TOOL},Tnt=[{label:"Error rate"}],Int=(e,t)=>txe(t>0?e/t:0);function RIs({onViewTraces:e,onViewErrors:t,onEntityClick:n}){const[r,s]=g.useState("agents"),i=$Is[r],o=pTs({...mf(),queryOptions:{placeholderData:px}}),l={agents:o.data?.agentData??[],workflows:o.data?.workflowData??[],tools:o.data?.toolData??[]},c=l[r],u=c.map(p=>({key:p.name,label:p.name,share:p.completed+p.errors,value:dv(p.completed+p.errors),cells:[Int(p.errors,p.completed+p.errors)],onClick:n&&(()=>n(i,p.name))})),d=new Map(c.map(p=>[p.name,p.errors])),f=[...l.agents,...l.workflows,...l.tools].reduce((p,m)=>p+m.completed+m.errors,0),h={title:"Trace volume",description:"Runs and calls, with error rate.",actions:(e||t)&&a.jsxs(a.Fragment,{children:[e&&a.jsx(pee,{onClick:()=>e(i)}),t&&a.jsx(Gqt,{onClick:()=>t(i)})]}),toolbar:a.jsxs(vi.Toolbar,{children:[a.jsxs(vi.Tabs,{value:r,onValueChange:s,children:[a.jsx(vi.Tab,{value:"agents",children:"Agents"}),a.jsx(vi.Tab,{value:"workflows",children:"Workflows"}),a.jsx(vi.Tab,{value:"tools",children:"Tools"})]}),a.jsx(j3.Header,{columns:Tnt,valueLabel:"Runs"})]})};return o.isError?a.jsx(sh,{...h,children:a.jsx(dT,{})}):a.jsx(sh,{...h,summary:a.jsx(vi.Summary,{value:dv(f),label:"runs and calls",isLoading:o.isLoading}),isUpdating:o.isPlaceholderData,children:a.jsx(uT,{children:a.jsx(j3,{rows:u,columns:Tnt,valueLabel:"Runs",showHeader:!1,color:mu.sky,other:p=>{const m=p.reduce((y,x)=>y+(d.get(x.key)??0),0),v=p.reduce((y,x)=>y+x.share,0);return{value:dv(v),cells:[Int(m,v)]}},emptyState:"No runs in this range.",isLoading:o.isLoading},r)})})}const MIs=["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],DIs=100;function yQt(e){const t=Ke(),{filters:n,filterKey:r}=mf();return Ct({queryKey:["metrics","token-spend",e,r],placeholderData:px,queryFn:async()=>{const{groups:s}=await t.getMetricBreakdown({name:MIs,groupBy:[e],aggregation:"sum",orderDirection:"DESC",limit:DIs,filters:n});return s.map(i=>({key:String(i.dimensions[e]??"unknown"),tokens:i.value,cost:i.estimatedCost??0}))}})}const LIs={placeholderData:px},Ent=[{label:"Tokens"}];function zIs(e){const[t,n]=g.useState("agents");return t==="models"?a.jsx(BIs,{...e,onViewChange:n}):t==="threads"?a.jsx(VIs,{...e,onViewChange:n}):a.jsx(FIs,{...e,onViewChange:n})}function FIs(e){const{onAgentClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:s,isError:i}=fTs({...mf(),queryOptions:LIs}),o=n.map(l=>({key:l.name,cost:l.cost??0,tokens:l.total,onClick:t&&(()=>t(l.name))}));return a.jsx(YAe,{view:"agents",...e,rows:o,isLoading:r,isUpdating:s,isError:i})}function BIs(e){const{onModelClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:s,isError:i}=yQt("model"),o=n.map(l=>({...l,onClick:t&&(()=>t(l.key))}));return a.jsx(YAe,{view:"models",...e,rows:o,isLoading:r,isUpdating:s,isError:i})}function VIs(e){const{onThreadClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:s,isError:i}=yQt("threadId"),o=n.map(l=>({...l,onClick:t&&(()=>t(l.key))}));return a.jsx(YAe,{view:"threads",...e,rows:o,isLoading:r,isUpdating:s,isError:i})}function YAe({view:e,onViewChange:t,onViewTraces:n,rows:r,isLoading:s,isUpdating:i,isError:o}){const l=new Map(r.map(d=>[d.key,d.tokens])),c=r.map(d=>({key:d.key,label:d.key,share:d.cost,value:eC(d.cost),cells:[dv(d.tokens)],onClick:d.onClick})),u={title:"Usage",description:"Who is spending: cost share, with tokens.",actions:n&&a.jsx(pee,{onClick:n}),toolbar:a.jsxs(vi.Toolbar,{children:[a.jsxs(vi.Tabs,{value:e,onValueChange:t,children:[a.jsx(vi.Tab,{value:"agents",children:"Agents"}),a.jsx(vi.Tab,{value:"models",children:"Models"}),a.jsx(vi.Tab,{value:"threads",children:"Threads"})]}),a.jsx(j3.Header,{columns:Ent,valueLabel:"Cost"})]})};return o?a.jsx(sh,{...u,children:a.jsx(dT,{})}):a.jsx(sh,{...u,summary:a.jsx(vi.Summary,{value:eC(r.reduce((d,f)=>d+f.cost,0)),label:"cost",isLoading:s}),isUpdating:i,children:a.jsx(uT,{children:a.jsx(j3,{rows:c,columns:Ent,valueLabel:"Cost",showHeader:!1,color:mu.green,other:d=>({value:eC(d.reduce((f,h)=>f+h.share,0)),cells:[dv(d.reduce((f,h)=>f+(l.get(h.key)??0),0))]}),emptyState:"No model usage in this range.",isLoading:s})})})}const UIs=100;function qIs(){const e=Ke(),{filters:t,filterKey:n,timestamp:r}=mf(),{interval:s}=fT(r.start,r.end),i=FAe(s);return Ct({queryKey:["metrics","scores",n,s],placeholderData:px,queryFn:async()=>{const o=await e.listScores({filters:t,pagination:{page:0,perPage:UIs}}),l=new Map(o.scores.map(p=>[p.scorerId,p.scorerName??p.scorerId])),c=[...l.keys()].toSorted(),u=await Promise.all(c.map(p=>Promise.all([e.getScoreAggregate({scorerId:p,aggregation:"avg",filters:t}),e.getScoreTimeSeries({scorerId:p,aggregation:"avg",interval:s,filters:t})]))),d=VAe(r.start,r.end,i),f=UAe(d,i),h=[];return u.forEach(([p,m],v)=>{const y=c[v];if(y){h.push({scorerId:y,name:l.get(y)??y,average:p.value??0});for(const x of m.series)for(const b of x.points){const S=d[f(b)??-1];S&&(S[y]=b.value)}}}),{scorers:h,buckets:d}}})}const Nnt=[mu.green,mu.sky,mu.violet,mu.teal,mu.indigo],xQt=e=>e.toFixed(2),QIs=e=>e.toFixed(1);function ZIs(e){return e.map(({scorerId:t,name:n,average:r},s)=>({dataKey:t,label:n,color:Nnt[s%Nnt.length]??mu.neutral,aggregate:()=>({value:xQt(r)})}))}function WIs(){const{data:e,isLoading:t,isError:n,isPlaceholderData:r}=qIs(),s=e?.scorers??[],i={title:"Scores",description:"Average scorer result, 0 to 1."};return n?a.jsx(sh,{...i,children:a.jsx(dT,{})}):a.jsx(sh,{...i,summary:a.jsx(vi.Summary,{value:String(s.length),label:s.length===1?"scorer":"scorers",isLoading:t}),isUpdating:r,children:a.jsx(uT,{isEmpty:!t&&s.length===0,emptyMessage:"No scores in this range.",children:a.jsx(GAe,{data:e?.buckets??[],series:ZIs(s),height:"fill",yDomain:[0,1],valueFormatter:xQt,axisFormatter:QIs,isLoading:t,...QAe})})})}function HIs({experiment:e,metrics:t}){const{data:n}=r6({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}}),r=g.useMemo(()=>[{id:e.id,status:e.status}],[e.id,e.status]),{data:s,isLoading:i}=IAe({experiments:r,supportsMetrics:t?.isEnabled??!1}),o=g.useMemo(()=>{if(!n)return;const v=Object.values(n).flat();return v.length===0?null:v.reduce((y,x)=>y+x.score,0)/v.length},[n]),l=e.startedAt??e.createdAt,c=(()=>{if(!e.startedAt||!e.completedAt)return"—";const v=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return Uc(v)??"—"})(),u=s[e.id]?.summary,d=WA(u),f=u?.inputTokens===void 0&&u?.outputTokens===void 0?"input + output":`${aS(u.inputTokens??0)} in · ${aS(u.outputTokens??0)} out`,h=t?.isEnabled?t.data?.avgAgentDurationMs:void 0,p=h==null?void 0:Uc(Math.round(h)),m=p?`${p} avg per item`:l?`started ${rs(new Date(l),"date-time")}`:"not started";return a.jsxs(Uqt,{children:[t?.isEnabled&&a.jsx(U1,{label:"Total cost",icon:JH,value:u?.estimatedCost===void 0?"—":zz(u.estimatedCost,u.costUnit),detail:"estimated",isLoading:i}),a.jsx(U1,{label:"Run duration",icon:yx,value:c,detail:m}),t?.isEnabled&&a.jsx(U1,{label:"Total tokens",icon:H0,value:d===void 0?"—":aS(d),detail:f,isLoading:i}),a.jsx(U1,{label:"Avg score",icon:Sp,value:o==null?"—":o.toFixed(3),detail:o==null?"no scores":"across all scorers",isLoading:o===void 0})]})}function GIs({selection:e}){const{selectedIds:t,selectedResults:n,tagVocabulary:r,isFlagging:s,isTagging:i}=e,o=s||i,l=t.size===0;return a.jsxs("div",{className:"flex min-h-8 items-center gap-2 whitespace-nowrap",children:[a.jsxs(ce,{variant:"ghost",size:"sm",disabled:l,iconEnd:l?void 0:a.jsx(Mn,{}),onClick:e.clearSelection,tooltip:l?void 0:"Clear selection",className:"tabular-nums",children:[t.size," selected"]}),!l&&a.jsxs(a.Fragment,{children:[a.jsx(ce,{size:"sm",disabled:o,onClick:e.flagSelectedForReview,icon:a.jsx(ept,{}),children:"Request review"}),a.jsx(zqt,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:o})]})]})}function KIs({experiment:e}){const{status:t,totalItems:n,succeededCount:r,failedCount:s}=e,i=r+s,o=n===1?"item":"items";return a.jsx(Yt,{variant:"fill",as:"h2",iconSlot:a.jsx(On,{}),titleSlot:gE[t],descriptionSlot:a.jsxs("span",{className:"tabular-nums",children:[i," / ",n," ",o," finished"]})})}const bQt=()=>{const{experimentId:e}=Cr(),{data:t}=HOt({experimentId:e??"",queryOptions:{enabled:!!e,retryOnMount:!1}});return{experimentId:e,experiment:t}},wQt=()=>{const{experimentId:e,experiment:t}=bQt(),n=t?.datasetId??"",{data:r}=ZOt({datasetId:n,experimentId:e??"",queryOptions:{enabled:!!(n&&e),retryOnMount:!1}});return r??t};function YIs(){const{experimentId:e,experiment:t}=bQt();if(!e)return null;const n=e.length>8?`${e.slice(0,8)}...`:e;return t?.name||n}function XIs(){const e=wQt();return e?.status?a.jsx(Njs,{status:e.status}):null}function JIs(){const e=wQt();if(!e||e.status==="running"||e.status==="pending")return null;const{totalItems:t,failedCount:n}=e,r=`${t} ${t===1?"item":"items"}`;return a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"whitespace-nowrap tabular-nums",children:n>0?`${r} · ${n} errored`:r})}function eEs({datasetId:e,experimentId:t}){const[n,r]=g.useState(!1),{updateExperimentResult:s}=pl();return{addTag:g.useCallback(async(o,l)=>{const c=l.filter(d=>!(d.tags??[]).includes(o));if(n||c.length===0)return;r(!0);let u=0;try{u=(await Promise.allSettled(c.map(f=>s.mutateAsync({datasetId:e,experimentId:t,resultId:f.id,tags:[...f.tags??[],o]})))).filter(f=>f.status==="fulfilled").length}finally{r(!1)}u>0?Xe(`Tag "${o}" added to ${u} result${u>1?"s":""}`):Xe.error("Failed to add tag")},[e,t,n,s]),isPending:n}}function tEs(e,t){const{data:n}=Vv({datasetId:e,queryOptions:{enabled:!!e}});return g.useMemo(()=>[...new Set([...n?.tags??[],...t.flatMap(r=>r.tags??[])])].sort(),[n?.tags,t])}function nEs({datasetId:e,experimentId:t,results:n}){const[r,s]=g.useState(new Set),[i,o]=g.useState(!1),{updateExperimentResult:l}=pl(),{addTag:c,isPending:u}=eEs({datasetId:e,experimentId:t}),d=tEs(e,n),f=g.useMemo(()=>n.filter(x=>r.has(x.id)),[n,r]),h=g.useCallback(x=>{s(b=>{const S=new Set(b);return S.has(x)?S.delete(x):S.add(x),S})},[]),p=g.useCallback(()=>s(new Set),[]),m=g.useCallback(()=>{s(x=>n.length>0&&n.every(b=>x.has(b.id))?new Set:new Set(n.map(b=>b.id)))},[n]),v=g.useCallback(async()=>{if(i||r.size===0)return;o(!0);const x=new Set;try{for(const b of r)try{await l.mutateAsync({datasetId:e,experimentId:t,resultId:b,status:"needs-review"}),x.add(b)}catch{}}finally{o(!1)}x.size>0&&(s(b=>{const S=new Set(b);for(const k of x)S.delete(k);return S}),Xe(`${x.size} result${x.size>1?"s":""} flagged for review`))},[e,t,i,r,l]),y=g.useCallback(x=>c(x,f),[c,f]);return{selectedIds:r,selectedResults:f,toggleSelect:h,toggleSelectAll:m,clearSelection:p,flagSelectedForReview:v,isFlagging:i,addTagToSelected:y,isTagging:u,tagVocabulary:d}}const rEs=[];function G7({crumbs:e,children:t}){return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:e}),children:[a.jsx("h1",{className:"sr-only",children:"Experiment"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:t})]})}function sEs(){const{experimentId:e}=Cr(),t=[Ts("/experiments"),{id:"experiment",Component:YIs,icon:XIs,Action:JIs}],n=Lr(),[r,s]=g.useState(!1),i=see(),{data:o,isLoading:l,error:c}=HOt({experimentId:e??"",queryOptions:{enabled:!!e}}),u=o?.datasetId??"",{data:d,isLoading:f,error:h}=ZOt({datasetId:u,experimentId:e??"",queryOptions:{enabled:!!u&&!!e}}),p=d?.status==="completed"||d?.status==="failed",{data:m,isLoading:v,setEndOfListElement:y,isFetchingNextPage:x,hasNextPage:b}=qcr({datasetId:u,experimentId:e??"",experimentStatus:d?.status,queryOptions:{enabled:!!u&&!!e&&p}}),{supportsMetrics:S}=j$(),k=fjs({experimentId:e,experimentStatus:d?.status,supportsMetrics:S,queryOptions:{enabled:!!e&&S&&p}}),j=nEs({datasetId:u,experimentId:e??"",results:m??rEs}),C=c??h;if(!e||l||f)return null;if(C&&Cs(C))return a.jsx(G7,{crumbs:t,children:a.jsx(ci,{})});if(C&&_s(C))return a.jsx(G7,{crumbs:t,children:a.jsx(Gs,{resource:"datasets"})});const T=a.jsx(G7,{crumbs:t,children:a.jsx(Yt,{titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:a.jsx(ce,{render:a.jsx(lc,{to:"/experiments"}),icon:a.jsx(vd,{}),children:"Back to Experiments"})})});return C&&Pk(C)?T:C?a.jsx(G7,{crumbs:t,children:a.jsx(Yt,{tone:"error",titleSlot:"Failed to load experiment",descriptionSlot:C instanceof Error?C.message:"An unexpected error occurred. Please try again."})}):!u||!d?T:a.jsx(mjs,{experimentId:e,datasetId:u,experimentStatus:d.status,results:m??[],isLoadingResults:v,hasNextPage:b,children:a.jsxs("div",{className:"h-full",children:[a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),headerActions:a.jsx(a_s,{experiment:d,onDeleteClick:()=>s(!0)}),children:[a.jsx("h1",{className:"sr-only",children:e}),p?a.jsxs("div",{className:"grid content-start gap-4",children:[a.jsx(HIs,{experiment:d,metrics:k}),a.jsxs("div",{className:"grid content-start gap-1",children:[a.jsx(GIs,{selection:j}),a.jsx(jjs,{experimentId:e,experimentStatus:d.status,results:m??[],isLoading:v,setEndOfListElement:y,isFetchingNextPage:x,hasNextPage:b,selectedIds:j.selectedIds,onToggleSelect:j.toggleSelect,onToggleSelectAll:j.toggleSelectAll,supportsMetrics:S})]})]}):a.jsx(KIs,{experiment:d})]}),a.jsx(b_s,{withQueryTrace:i.enabled,withFeedback:i.enabled}),a.jsx($qt,{open:r,onOpenChange:s,experimentId:e,experimentName:d.name??void 0,onSuccess:()=>n("/experiments")})]})})}function iEs({tag:e,onRename:t,onRemove:n}){const[r,s]=g.useState(!1),[i,o]=g.useState(e),l=g.useRef(null);g.useEffect(()=>{r&&(l.current?.focus(),l.current?.select())},[r]);const c=()=>{const u=i.trim();u&&u!==e&&t(u),s(!1)};return r?a.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1",children:[a.jsx(bn,{variant:"unstyled",ref:l,value:i,onChange:u=>o(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),c()),u.key==="Escape"&&(o(e),s(!1))},onBlur:c,className:"h-auto w-20 bg-transparent px-0 py-0.5 text-caption text-muted-foreground outline-hidden"}),a.jsx("button",{type:"button",onMouseDown:u=>{u.preventDefault(),c()},className:Z(Zn,"p-0.5"),children:a.jsx(ur,{className:"h-3 w-3"})})]}):a.jsxs("span",{className:"group inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1.5 py-0.5 text-muted-foreground",children:[a.jsx(Y,{as:"span",variant:"caption",children:e}),a.jsx("button",{type:"button",onClick:()=>{o(e),s(!0)},className:Z(Zn,"p-0.5 opacity-0 transition-opacity group-hover:opacity-100"),title:"Edit tag",children:a.jsx(Vc,{className:"h-3 w-3"})}),a.jsx("button",{type:"button",onClick:n,className:"p-0.5 text-placeholder opacity-0 transition-opacity group-hover:opacity-100 hover:text-destructive-foreground",title:"Remove tag",children:a.jsx(Mn,{className:"h-3 w-3"})})]})}function oEs({selectedCount:e,vocabulary:t,onApplyTag:n,onRemoveTag:r,onNewTag:s,size:i="sm"}){const[o,l]=g.useState(!1),[c,u]=g.useState(""),d=t.filter(h=>h.toLowerCase().includes(c.toLowerCase())),f=c.trim()&&!t.includes(c.trim());return a.jsxs(jp,{open:o,onOpenChange:l,children:[a.jsx(of,{asChild:!0,children:a.jsxs(ce,{size:i,icon:a.jsx(Px,{}),children:["Tag ",e," items"]})}),a.jsxs(ah,{className:"w-56 p-2",align:"end",children:[a.jsx(bn,{value:c,onChange:h=>u(h.target.value),onKeyDown:h=>{h.key==="Enter"&&c.trim()&&(h.preventDefault(),f?s(c.trim()):n(c.trim()),u(""))},placeholder:"Search or create tag...",className:"mb-1 h-7 text-caption",autoFocus:!0}),a.jsxs("div",{className:"max-h-40 space-y-0.5 overflow-y-auto",children:[d.map(h=>a.jsxs("div",{className:"flex items-center justify-between rounded px-2 py-1 hover:bg-fill-subtle",children:[a.jsx("button",{type:"button",onClick:()=>n(h),className:"flex-1 text-left text-muted-foreground",children:a.jsx(Y,{as:"span",variant:"caption",className:"block",children:h})}),a.jsx("button",{type:"button",onClick:()=>r(h),className:"ml-2 text-placeholder hover:text-destructive-foreground",children:a.jsx(Mn,{className:"h-3 w-3"})})]},h)),f&&a.jsx("button",{type:"button",onClick:()=>{s(c.trim()),u("")},className:"w-full rounded px-2 py-1 text-left text-info-indicator hover:bg-fill-subtle",children:a.jsxs(Y,{as:"span",variant:"caption",className:"block",children:['Create & apply "',c.trim(),'"']})})]})]})]})}const aEs=[{name:"itemId",label:"Item ID",size:"auto"},{name:"input",label:"Input",size:"20rem"},{name:"tags",label:"Tags",size:"auto"},{name:"scores",label:"Scores",size:"6rem"}],Iue="__untagged__",K7="all",lEs=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}];function cEs({datasetId:e,experimentId:t,experiments:n,isLoadingExperiments:r,targetType:s,targetId:i,featuredItemId:o,toolbarStart:l,renderFilters:c,toolbarEnd:u,onCreateScorer:d,breadcrumbs:f,withQueryTrace:h,withFeedback:p}){const m=Ke(),{paths:v}=Sn(),{data:y}=Vv({datasetId:e??"",queryOptions:{enabled:!!e}}),{data:x,isLoading:b}=Xjs({experimentId:t,targetType:s,targetId:i,experiments:n,isLoadingExperiments:r}),{data:S,isLoading:k}=Jjs({experimentId:t,targetType:s,targetId:i,experiments:n,isLoadingExperiments:r}),{updateExperimentResult:j}=pl(),[C,T]=g.useState(o??null);g.useEffect(()=>{o!==void 0&&T(o)},[o]);const[_,N]=g.useState(null),[E,A]=g.useState(new Set),[P,L]=g.useState(!1),[F,Q]=g.useState(!1),[q,B]=g.useState(!1),[V,W]=g.useState(""),[M,K]=g.useState(""),[D,$]=g.useState(""),[z,U]=g.useState([]),[G,ne]=g.useState(!1),X=g.useMemo(()=>x??[],[x]),ee=g.useMemo(()=>{const ze=new Set;if(y?.tags)for(const Se of y.tags)ze.add(Se);for(const Se of X)for(const Pe of Se.tags)ze.add(Pe);return[...ze].sort()},[y,X]),re=g.useMemo(()=>_?_===Iue?X.filter(ze=>ze.tags.length===0):X.filter(ze=>ze.tags.includes(_)):X,[X,_]),ue=g.useMemo(()=>{const ze=new Map;let Se=0;for(const nt of X){nt.tags.length===0&&Se++;for(const Pt of nt.tags)ze.set(Pt,(ze.get(Pt)??0)+1)}const Pe=[...ze.entries()].sort((nt,Pt)=>Pt[1]-nt[1]).map(([nt])=>({value:nt,label:nt}));return[{value:K7,label:"All tags"},...Se>0?[{value:Iue,label:"Untagged"}]:[],...Pe]},[X]),te=!!_||P,ie=g.useCallback(()=>{N(null),L(!1),T(null)},[]),se=g.useCallback((ze,Se)=>{const Pe=X.find(nt=>nt.id===ze);Pe?.experimentId&&Pe?.datasetId&&j.mutate({datasetId:Pe.datasetId,experimentId:Pe.experimentId,resultId:Pe.id,tags:Se})},[X,j]),ae=g.useCallback(ze=>{const Se=X.find(Pe=>Pe.id===ze);A(Pe=>{const nt=new Set(Pe);return nt.delete(ze),nt}),C===ze&&T(null),Se?.experimentId&&Se?.datasetId&&j.mutate({datasetId:Se.datasetId,experimentId:Se.experimentId,resultId:Se.id,status:null})},[X,j,C]),he=g.useCallback(ze=>{const Se=X.find(Pe=>Pe.id===ze);A(Pe=>{const nt=new Set(Pe);return nt.delete(ze),nt}),C===ze&&T(null),Se?.experimentId&&Se?.datasetId&&j.mutate({datasetId:Se.datasetId,experimentId:Se.experimentId,resultId:Se.id,status:"complete"})},[X,j,C]),ge=g.useMemo(()=>{const ze=P?S??[]:re;return!P||!_?ze:_===Iue?ze.filter(Se=>Se.tags.length===0):ze.filter(Se=>Se.tags.includes(_))},[P,S,re,_]),me=P?k:!1,ke=g.useMemo(()=>new Set(ge.map(ze=>ze.id)),[ge]),Ee=g.useMemo(()=>[...E].filter(ze=>ke.has(ze)).length,[E,ke]),qe=ge.length>0&&Ee===ge.length,Ze=g.useCallback(ze=>{A(Se=>{const Pe=new Set(Se);return Pe.has(ze)?Pe.delete(ze):Pe.add(ze),Pe})},[]),Fe=g.useCallback(()=>{A(qe?new Set:new Set(ge.map(ze=>ze.id)))},[qe,ge]),Ae=g.useCallback(ze=>{for(const Se of E){const Pe=X.find(nt=>nt.id===Se);Pe&&!Pe.tags.includes(ze)&&se(Se,[...Pe.tags,ze])}},[X,E,se]),Be=g.useCallback(ze=>{for(const Se of E){const Pe=X.find(nt=>nt.id===Se);Pe&&Pe.tags.includes(ze)&&se(Se,Pe.tags.filter(nt=>nt!==ze))}},[X,E,se]),je=g.useCallback(()=>{for(const ze of E)he(ze);A(new Set)},[E,he]),_e=g.useCallback(()=>{for(const ze of E)ae(ze);A(new Set)},[E,ae]),Ue=g.useCallback(()=>{W(""),B(!0)},[]),pe=g.useCallback(async()=>{if(!(!M||!D)){Q(!0),B(!1);try{const ze=X.filter(Pe=>E.has(Pe.id));if(ze.length===0){Q(!1);return}const Se=await m.clusterFailures({modelId:`${M}/${D}`,items:ze.map(Pe=>({id:Pe.id,input:Pe.input,output:Pe.output??void 0,error:typeof Pe.error=="string"?Pe.error:Pe.error?String(Pe.error):void 0,scores:Pe.scores,existingTags:Pe.tags.length>0?Pe.tags:void 0})),availableTags:ee.length>0?ee:void 0,prompt:V||void 0});Se.proposedTags&&Se.proposedTags.length>0&&(U(Se.proposedTags.map(Pe=>({...Pe,accepted:!0}))),ne(!0))}catch(ze){console.error("Analysis failed:",ze)}finally{Q(!1)}}},[M,D,X,E,m,ee,V]),fe=g.useCallback(()=>{for(const ze of z){if(!ze.accepted)continue;const Se=X.find(Pe=>Pe.id===ze.itemId);if(Se){const Pe=[...new Set([...Se.tags,...ze.tags])];se(Se.id,Pe)}}ne(!1)},[z,X,se]),Ie=g.useCallback(ze=>{T(Se=>Se===ze?null:ze)},[]),Ce=g.useMemo(()=>C?ge.find(ze=>ze.id===C)??null:null,[C,ge]),{data:le}=r6({experimentId:Ce?.experimentId??"",queryOptions:{enabled:!!Ce?.experimentId}}),ve=C?ge.findIndex(ze=>ze.id===C):-1,be=ve>0?()=>T(ge[ve-1].id):void 0,$e=ve>=0&&ve<ge.length-1?()=>T(ge[ve+1].id):void 0,De=!P&&E.size>0,We=!!d&&!P&&re.length>0,tt=P?"completed":"review",st=ze=>{L(ze==="completed"),T(null)},Ge=a.jsxs(rr,{children:[a.jsx(rr.Start,{children:c?a.jsxs(a.Fragment,{children:[l,c({status:tt,onStatusChange:st,tag:_,onTagChange:N,tagOptions:ue.filter(ze=>ze.value!==K7)})]}):a.jsxs(a.Fragment,{children:[l,a.jsxs(ms,{value:tt,onValueChange:ze=>st(ze==="completed"?"completed":"review"),children:[a.jsx(vs,{"aria-label":"Status",size:"md",className:"whitespace-nowrap",children:a.jsx(gs,{placeholder:"Select an option"})}),a.jsx(ys,{children:lEs.map(ze=>a.jsx(hr,{value:ze.value,children:ze.label},ze.value))})]}),ue.length>1&&a.jsxs(ms,{value:_??K7,onValueChange:ze=>N(ze===K7?null:ze),children:[a.jsx(vs,{"aria-label":"Tags",size:"md",className:"whitespace-nowrap",children:a.jsx(gs,{placeholder:"Select an option"})}),a.jsx(ys,{children:ue.map(ze=>a.jsx(hr,{value:ze.value,children:ze.label},ze.value))})]}),te&&a.jsx(ce,{onClick:ie,size:"sm",variant:"default",icon:a.jsx(Mn,{}),children:"Reset"})]})}),(De||u||We)&&a.jsxs(rr.End,{children:[u,We&&a.jsxs(ce,{size:"md",onClick:()=>d?.(re.map(ze=>({input:ze.input,output:ze.output}))),children:[a.jsx(At,{size:"xs",children:a.jsx(Sp,{})}),"Create Scorer"]}),De&&a.jsxs(a.Fragment,{children:[a.jsx(oEs,{size:"md",selectedCount:E.size,vocabulary:ee,onApplyTag:Ae,onRemoveTag:Be,onNewTag:ze=>Ae(ze)}),a.jsx(ce,{variant:"primary",onClick:je,icon:a.jsx(bP,{}),children:"Mark as reviewed"}),a.jsxs(lt,{children:[a.jsx(lt.Trigger,{asChild:!0,children:a.jsx(ce,{disabled:F,"aria-label":"More actions",children:F?a.jsx(On,{className:"h-4 w-4"}):a.jsx(AN,{})})}),a.jsxs(lt.Content,{align:"end",children:[a.jsxs(lt.Item,{onSelect:Ue,children:[a.jsx(At,{size:"xs",children:a.jsx(lG,{})}),"Analyze"]}),a.jsx(lt.Separator,{}),a.jsxs(lt.Item,{onSelect:_e,children:[a.jsx(At,{size:"xs",children:a.jsx(Xo,{})}),"Remove from queue"]})]})]})]})]})]});if(b)return a.jsxs(It,{breadcrumbs:f,actionRow:Ge,children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(On,{fill:!0})]});const Le=a.jsx(Bqt,{withQueryTrace:h,withFeedback:p,result:Ce??void 0,title:`Review item ${Ce?.id??""}`,scores:Ce?le?.[Ce.itemId]:void 0,experimentLink:Ce?.experimentId?v.experimentItemLink(Ce.experimentId,Ce.itemId):void 0,onComplete:P||!Ce?void 0:()=>he(Ce.id),onPrevious:be,onNext:$e,onClose:()=>T(null)});return a.jsxs(It,{breadcrumbs:f,actionRow:Ge,children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(Yr,{open:q,onOpenChange:B,children:a.jsxs(Xr,{children:[a.jsxs(Jr,{children:[a.jsx(Zr,{children:"Analyze Items"}),a.jsx(Lo,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),a.jsxs(Qr,{children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs(pt,{className:"gap-1",children:[a.jsx(dt,{children:"Provider"}),a.jsx(zk,{value:M,onValueChange:K})]}),a.jsxs(pt,{className:"gap-1",children:[a.jsx(dt,{children:"Model"}),a.jsx(Fk,{llmId:M,value:D,onValueChange:$})]})]}),a.jsxs(Y,{variant:"meta",tone:"muted",children:[E.size," item",E.size!==1?"s":""," will be analyzed"]}),a.jsxs(pt,{className:"gap-1",children:[a.jsx(dt,{children:"Instructions (optional)"}),a.jsx(Pu,{className:"text-caption",value:V,onChange:ze=>W(ze.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3})]})]}),a.jsxs(Yo,{children:[a.jsx(_a,{children:"Cancel"}),a.jsx(Ca,{onConfirm:pe,disabled:!M||!D||F,children:"Analyze"})]})]})}),a.jsx(Yr,{open:G,onOpenChange:ne,children:a.jsxs(Xr,{size:"lg",children:[a.jsxs(Jr,{children:[a.jsx(Zr,{children:"Review Proposed Tags"}),a.jsxs(Lo,{children:[z.filter(ze=>ze.accepted).length," of ",z.length," proposals selected"]})]}),a.jsx(Qr,{children:z.map((ze,Se)=>{const Pe=X.find(nt=>nt.id===ze.itemId);return a.jsx("div",{className:Z("rounded-lg border p-3",!ze.accepted&&"opacity-50"),children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Kc,{checked:ze.accepted,onCheckedChange:nt=>U(Pt=>Pt.map((Vt,Ut)=>Ut===Se?{...Vt,accepted:!!nt}:Vt))}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"block truncate",children:Pe?typeof Pe.input=="string"?Pe.input.slice(0,100):JSON.stringify(Pe.input).slice(0,100):ze.itemId}),a.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:ze.tags.map((nt,Pt)=>a.jsx(iEs,{tag:nt,onRename:Vt=>U(Ut=>Ut.map((xt,jn)=>jn===Se?{...xt,tags:xt.tags.map((gn,we)=>we===Pt?Vt:gn)}:xt)),onRemove:()=>U(Vt=>Vt.map((Ut,xt)=>xt===Se?{...Ut,tags:Ut.tags.filter((jn,gn)=>gn!==Pt)}:Ut))},`${nt}-${Pt}`))}),ze.reason&&a.jsx(Y,{variant:"meta",tone:"muted",className:"mt-1 block italic",children:ze.reason})]})]})},ze.itemId)})}),a.jsxs(Yo,{children:[a.jsx(_a,{children:"Cancel"}),a.jsxs(Ca,{onConfirm:fe,disabled:z.filter(ze=>ze.accepted).length===0,children:["Accept ",z.filter(ze=>ze.accepted).length," proposals"]})]})]})}),a.jsxs("div",{className:"grid h-full min-h-0 w-full grid-cols-1 gap-4 overflow-hidden",children:[a.jsx("div",{className:"min-h-0 w-full overflow-hidden",children:me?a.jsx(On,{fill:!0}):ge.length===0?a.jsx(Yt,{titleSlot:P?"No completed reviews yet":"No items to review",descriptionSlot:P?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here.",variant:"fill"}):a.jsx(Eqt,{results:ge,isLoading:!1,featuredResultId:C,onResultClick:Ie,columns:aEs,selectedIds:P?void 0:E,onToggleSelect:P?void 0:Ze,onToggleSelectAll:P?void 0:Fe})}),Le]})]})}const XAe="experiment",JAe="status",ePe="tag",uEs=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}],dEs=[{id:"is",label:"is"}],fEs=({targetType:e,targetId:t,experimentId:n,status:r,tag:s})=>{const i=wAe({targetType:e,targetId:t});return n&&i.push(cv(XAe,n)),r!=="review"&&i.push(cv(JAe,r)),s&&i.push(cv(ePe,s)),i},hEs=e=>({...SAe(e),experimentId:uv(e,XAe),status:uv(e,JAe)==="completed"?"completed":"review",tag:uv(e,ePe)||null});function pEs({targetType:e,targetId:t,experimentId:n,status:r,tag:s,experiments:i,tagOptions:o,onChange:l}){const c=kAe(e),u=g.useMemo(()=>[...c,{id:XAe,label:"Experiment",icon:dL,color:v0("pink"),strict:!0,suggestions:i.map(f=>({value:f.id,label:Rqt(f)}))},{id:JAe,label:"Status",icon:bP,color:v0("orange"),strict:!0,suggestions:uEs},{id:ePe,label:"Tag",icon:Px,color:v0("pink"),strict:!0,hidden:o.length===0,suggestions:o}],[c,i,o]),d=g.useMemo(()=>fEs({targetType:e,targetId:t,experimentId:n,status:r,tag:s}),[e,t,n,r,s]);return a.jsxs(kl,{fields:u,operators:dEs,value:d,onValueChange:f=>l(hEs(f)),createItemId:f=>f,"aria-label":"Review queue filters",className:"min-w-64 flex-1",children:[a.jsx(kl.Chips,{}),a.jsx(kl.Input,{placeholder:"Filter review queue…"})]})}const Y7=[Ts("/experiments"),Ts("/experiments/review-queue")],Eue="experiment",Ant="review";function mEs(){const[e,t]=wi(),n=e.get(w0),r=aee(n)?n:"",s=r?e.get(ex)??"":"",i=e.get(Eue),o=e.get(Ant),{Link:l,paths:c}=Sn(),u=see(),{data:d,error:f}=Oqt({datasetId:void 0,target:{targetType:r,targetId:s}}),h=d?.experiments.find(m=>m.id===i),p=(m,v)=>{m.status!==v.status&&v.onStatusChange(m.status),m.tag!==v.tag&&v.onTagChange(m.tag),t(y=>{const x=new URLSearchParams(y),b=m.targetType!==r,k=b||m.targetId!==s?"":m.experimentId,j=b?"":m.targetId;return m.targetType?x.set(w0,m.targetType):x.delete(w0),j?x.set(ex,j):x.delete(ex),k?x.set(Eue,k):x.delete(Eue),x.delete(Ant),x},{replace:!0})};return f&&Cs(f)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Y7}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(ci,{variant:"fill"})]}):f&&_s(f)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Y7}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(Gs,{variant:"fill",resource:"experiments"})]}):f?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Y7}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(Yt,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:f.message})]}):a.jsx(cEs,{withQueryTrace:u.enabled,withFeedback:u.enabled,breadcrumbs:a.jsx(Dt,{crumbs:Y7}),datasetId:h?.datasetId??void 0,experimentId:i??void 0,targetType:r,targetId:s,featuredItemId:o,renderFilters:m=>a.jsx(pEs,{targetType:r,targetId:s,experimentId:i??"",status:m.status,tag:m.tag,experiments:d?.experiments??[],tagOptions:m.tagOptions,onChange:v=>p(v,m)}),toolbarEnd:i?a.jsx(ce,{render:a.jsx(l,{href:c.experimentLink(i)}),icon:a.jsx(owe,{}),children:"See experiment"}):void 0})}function gEs({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return a.jsxs("li",{className:"flex items-center justify-between border-b py-2",children:[a.jsxs("div",{children:[a.jsx(Y,{as:"p",variant:"caption",font:"mono",children:e.connectionId}),a.jsxs(Y,{as:"p",variant:"caption",tone:"muted",children:[e.label??"(no label)"," · ",e.status,e.scope?` · ${e.scope}`:"",t&&e.authorId?` · author: ${e.authorId}`:""]})]}),a.jsx("button",{type:"button",className:"text-destructive-foreground underline disabled:opacity-50",onClick:r,disabled:n,children:"Disconnect"})]})}function SQt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return a.jsx("ul",{className:"space-y-1",children:e.map(s=>a.jsx(gEs,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function vEs({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return a.jsx("div",{className:"space-y-4",children:e.map(([s,i])=>a.jsxs("div",{children:[a.jsx(Y,{as:"h3",variant:"subheading",tone:"ink","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),a.jsx(SQt,{connections:i,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function yEs({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:s,isLoading:i,error:o,disconnectPending:l,disconnectError:c,onDisconnect:u}){return a.jsxs("div",{className:"space-y-2 rounded border p-4",children:[a.jsx(Y,{as:"h2",variant:"heading",children:"Existing connections"}),!e||!t?a.jsx("p",{className:"text-muted-foreground",children:"Pick a provider and toolkit to list connections."}):i?a.jsx("p",{className:"text-muted-foreground",children:"Loading…"}):o?a.jsx("p",{className:"text-destructive-foreground",children:String(o)}):n.length===0?a.jsx("p",{className:"text-muted-foreground",children:"No connections."}):r?a.jsx(vEs,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):a.jsx(SQt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?a.jsx("p",{className:"text-destructive-foreground",children:String(c)}):null]})}function xEs({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:i,providersError:o,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:h,onToolkitChange:p,onLabelChange:m,onConnect:v}){return a.jsxs("div",{className:"space-y-4 rounded border p-4",children:[a.jsxs(pt,{invalid:!!o,disabled:i,children:[a.jsx(dt,{children:"Provider"}),a.jsxs(ms,{value:n,onValueChange:h,children:[a.jsx(vs,{children:a.jsx(gs,{placeholder:i?"Loading providers…":"Select provider"})}),a.jsx(ys,{children:e.map(y=>a.jsx(hr,{value:y.id,children:`${y.displayName??y.name} (${y.id})`},y.id))})]}),a.jsx(ns,{children:o?String(o):void 0})]}),a.jsxs(pt,{invalid:!!c,disabled:!n||l,children:[a.jsx(dt,{children:"Toolkit"}),a.jsxs(ms,{value:r,onValueChange:p,children:[a.jsx(vs,{children:a.jsx(gs,{placeholder:l?"Loading toolkits…":"Select toolkit"})}),a.jsx(ys,{children:t.map(y=>a.jsx(hr,{value:y.slug,children:`${y.name} (${y.slug})`},y.slug))})]}),a.jsx(ns,{children:c?String(c):void 0})]}),a.jsxs(pt,{disabled:!n||!r,children:[a.jsx(dt,{children:"Label (optional)"}),a.jsx(bn,{placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value)})]}),a.jsx(ce,{type:"button",variant:"primary",onClick:v,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?a.jsx("div",{role:"alert",children:a.jsx(Wt,{variant:"destructive",children:String(d)})}):null,f?a.jsxs(Wt,{variant:"success",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]}):null]})}const Pnt=e=>e.authorId?.trim()||"shared",bEs=(e,t)=>{if(!t||new Set(e.map(Pnt)).size<=1)return null;const r=new Map;for(const i of e){const o=Pnt(i);r.set(o,[...r.get(o)??[],i])}const s=Array.from(r.entries());return s.sort(([i],[o])=>i==="shared"?1:o==="shared"?-1:i.localeCompare(o)),s},wEs=["*","tool-providers:*","tool-providers:admin"];function SEs(){const{data:e}=Xm();return e?.permissions?.some(t=>wEs.includes(t))??!1}const kEs=[{id:"integrations",label:"Integrations"}];function OEs(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,i]=g.useState(""),o=s$(),l=lX({providerId:e||null,queryOptions:{enabled:!!e}}),c=aRt({providerId:e||null,toolkit:n||null}),u=iRt(),d=oRt(),f=SEs(),h=o.data?.providers??[],p=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>bEs(m,f),[m,f]),y=S=>{t(S),r("")},x=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{i(""),c.refetch()}})},b=S=>{d.mutate({providerId:e,connectionId:S})};return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:kEs}),children:[a.jsx("h1",{className:"sr-only",children:"Integrations"}),a.jsxs("div",{className:"max-w-3xl space-y-6",children:[a.jsx(Y,{as:"p",variant:"body",tone:"muted",children:"Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect."}),a.jsx(xEs,{providers:h,toolkits:p,providerId:e,toolkit:n,label:s,providersLoading:o.isLoading,providersError:o.error,toolkitsLoading:l.isLoading,toolkitsError:l.error,authorizePending:u.isPending,authorizeError:u.error,authorizedConnection:u.data,onProviderChange:y,onToolkitChange:r,onLabelChange:i,onConnect:x}),a.jsx(yEs,{providerId:e,toolkit:n,connections:m,groupedByAuthor:v,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:b})]})]})}function jEs({title:e,description:t,errorBanner:n,children:r}){return a.jsxs("div",{"data-testid":"login-page",className:"w-full max-w-sm space-y-6 p-6",children:[a.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[a.jsx(z0,{className:"h-10 w-10"}),a.jsx(Y,{as:"h1",variant:"heading",tone:"ink",children:e})]}),t,n,r]})}function kQt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:i}=Zl(),{mutate:o,isPending:l,error:c}=Nwn(),{mutate:u,isPending:d,error:f}=Pwn(),{mutate:h,isPending:p}=Pdt(),[m,v]=g.useState(n),[y,x]=g.useState(""),[b,S]=g.useState(""),[k,j]=g.useState("");if(i)return a.jsx("div",{className:"text-muted-foreground",children:"Loading..."});if(!s?.enabled||!s?.login)return a.jsx("div",{className:"text-muted-foreground",children:"Authentication is not configured"});const{login:C}=s,T=C.type==="sso"||C.type==="both",_=C.type==="credentials"||C.type==="both",N=C.sso,E=C.signUpEnabled!==!1,A=m==="signin"||!E,P=A?l:d,L=A?c:f,F=()=>{t?t():e?window.location.href=e:window.location.href=NX("/")},Q=M=>{M.preventDefault(),A?o({email:b,password:k},{onSuccess:F}):u({email:b,password:k,name:y||void 0},{onSuccess:F})},q=()=>{h({redirectUri:e},{onSuccess:M=>{window.location.href=M.url}})},B=()=>{v(A?"signup":"signin")},V=C.description?a.jsxs("div",{className:"flex items-start gap-2.5 rounded-md border border-border bg-sidebar p-3",children:[a.jsx(Nu,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),a.jsx(Y,{tone:"muted",children:C.description})]}):null,W=r?a.jsx("div",{role:"alert",children:a.jsx(Wt,{variant:"destructive",children:r})}):null;return a.jsxs(jEs,{title:A?"Sign in to Mastra Studio":"Create your account",description:V,errorBanner:W,children:[_&&a.jsxs(Ga,{onSubmit:Q,children:[!A&&a.jsxs(pt,{children:[a.jsx(dt,{children:"Name"}),a.jsx(bn,{name:"name",type:"text",autoComplete:"name",value:y,onChange:M=>x(M.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),a.jsxs(pt,{children:[a.jsx(dt,{required:!0,children:"Email"}),a.jsx(bn,{name:"email",type:"email",autoComplete:"email",value:b,onChange:M=>S(M.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"}),a.jsx(ns,{})]}),a.jsxs(pt,{children:[a.jsx(dt,{required:!0,children:"Password"}),a.jsx(bn,{name:"password",type:"password",autoComplete:A?"current-password":"new-password",value:k,onChange:M=>j(M.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"}),a.jsx(ns,{})]}),L?a.jsx("div",{role:"alert",children:a.jsx(Wt,{variant:"destructive",children:L.message})}):null,a.jsx(ce,{icon:a.jsx(vwe,{}),type:"submit",disabled:P,className:"w-full",size:"lg",children:P?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),E&&a.jsxs("div",{className:"text-center",children:[a.jsx(Y,{as:"span",variant:"body",tone:"muted",children:A?"Don't have an account? ":"Already have an account? "}),a.jsx("button",{type:"button",onClick:B,className:"text-foreground hover:underline",children:a.jsx(Y,{as:"span",variant:"body",className:"block",children:A?"Sign up":"Sign in"})})]})]}),T&&_&&a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"absolute inset-0 flex items-center",children:a.jsx("div",{className:"w-full border-t border-border"})}),a.jsx("div",{className:"relative flex justify-center",children:a.jsx(Y,{as:"span",variant:"body",tone:"muted",className:"bg-sidebar px-2",children:"or continue with"})})]}),T&&N&&a.jsxs(ce,{onClick:q,disabled:p,className:"w-full",size:"lg",children:[N.icon&&a.jsx("span",{className:"mr-2",children:N.icon}),p?"Redirecting...":N.text||"Sign in"]})]})}function CEs(){const[e]=wi(),t=Lr(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",i=e.get("error_description")||e.get("error")||null,o=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return a.jsx(kQt,{redirectUri:n,onSuccess:o,initialMode:s,errorMessage:i})}function _Es({disabled:e,onClear:t,onRemoveAll:n,onSave:r,onRemoveSaved:s}){const i=!!(n||r||s);return!t&&!i?null:a.jsxs("div",{className:"flex items-center gap-2",children:[t&&a.jsx(ce,{disabled:e,size:"md",onClick:t,icon:a.jsx(Mn,{}),children:"Clear"}),i&&a.jsxs(lt,{children:[a.jsx(lt.Trigger,{asChild:!0,children:a.jsx(ce,{disabled:e,size:"md","aria-label":"More filter actions",children:a.jsx(W0,{})})}),a.jsxs(lt.Content,{align:"end",children:[n&&a.jsxs(lt.Item,{onSelect:()=>n(),children:[a.jsx(Mn,{}),"Remove all filters"]}),n&&(r||s)&&a.jsx(lt.Separator,{}),r&&a.jsxs(lt.Item,{onSelect:()=>r(),children:[a.jsx(Bm,{}),"Save filters for next time"]}),s&&a.jsxs(lt.Item,{onSelect:()=>s(),children:[a.jsx(Xo,{}),"Remove saved filters"]})]})]})]})}const TEs=Z(og,"min-w-0 focus:text-foreground");function Nue({role:e,checked:t,label:n,onClick:r}){return a.jsxs("button",{ref:Du(),type:"button",role:e,"aria-checked":t,"data-selected":t||void 0,"data-pick-multi-item":"",title:n,className:TEs,onClick:r,children:[a.jsx("span",{className:"min-w-0 flex-1 truncate",children:n}),t&&a.jsx("span",{className:M_,children:a.jsx(ur,{})})]})}function OQt({field:e,tokens:t,onChange:n}){const[r,s]=g.useState(""),i=Bv(),o={className:Z("max-h-[80dvh] overflow-auto p-1",i.containerClassName),...i.getContainerProps({})},l=g.useMemo(()=>{const f=r.trim().toLowerCase();return f?e.options.filter(h=>h.label.toLowerCase().includes(f)):e.options},[e.options,r]),c=g.useMemo(()=>t.find(f=>f.fieldId===e.id),[t,e.id]),u=typeof c?.value=="string"?c.value:e.multi?void 0:e.defaultValue,d=g.useMemo(()=>{const f=c?.value;return Array.isArray(f)?f:typeof f=="string"?[f]:[]},[c]);return a.jsxs(a.Fragment,{children:[e.searchable!==!1&&a.jsxs("div",{className:zE.container,children:[a.jsx(wu,{className:zE.icon}),a.jsx("input",{type:"text",value:r,onChange:f=>s(f.target.value),placeholder:`Search ${e.label.toLowerCase()}...`,className:zE.input,...pp,onKeyDown:f=>{if(f.key!=="ArrowDown")return;const p=f.currentTarget.closest("[data-pick-multi-panel]")?.querySelector("[data-pick-multi-item]:not([disabled])");p&&(f.preventDefault(),f.stopPropagation(),p.focus())}})]}),e.isLoading?a.jsxs("div",{className:Z(hQ,"m-1"),children:[a.jsx(On,{size:"sm",className:"size-3 text-muted-foreground"}),"Loading options…"]}):l.length===0?a.jsx("div",{className:Z(hQ,"m-1"),children:e.emptyText??"No option found."}):e.multi?a.jsx("div",{...o,children:a.jsx(US,{menu:i,children:l.map(f=>{const h=d.includes(f.value);return a.jsx(Nue,{role:"checkbox",checked:h,label:f.label,onClick:()=>n(e.id,h?d.filter(p=>p!==f.value):[...d,f.value])},f.value)})})}):a.jsx("div",{role:"radiogroup",...o,children:a.jsxs(US,{menu:i,children:[l.map(f=>a.jsx(Nue,{role:"radio",checked:u===f.value,label:f.label,onClick:()=>n(e.id,f.value)},f.value)),!e.omitAnyOption&&a.jsx(Nue,{role:"radio",checked:u==="Any",label:"Any",onClick:()=>n(e.id,"Any")})]})})]})}function tPe(e){return Array.isArray(e)?e.length===0?"Any":e.join(", "):e}const IEs="This filter is set by the current context and cannot be removed here.";function EEs(e,t){return e.kind==="pick-multi"&&e.options?Array.isArray(t)?t.length===0?"Any":t.map(n=>e.options.find(r=>r.value===n)?.label??n).join(", "):e.options.find(n=>n.value===t)?.label??t:tPe(t)}function NEs({field:e,value:t,tooltipContent:n}){const r=EEs(e,t),s=`${e.label} filter is locked by context`;return a.jsx(Wc,{delayDuration:150,children:a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsxs(mc,{"data-locked-field-id":e.id,"data-property-filter-pill":"locked",tabIndex:0,"aria-label":s,children:[a.jsx(gm,{children:e.label}),a.jsx(gm,{children:"is"}),a.jsx(gm,{children:r}),a.jsx(gm,{children:a.jsx(Nu,{})})]})}),a.jsx(Bn,{children:n})]})})}function AEs({field:e,value:t,onChange:n,onRemove:r,disabled:s,autoFocus:i}){const[o,l]=g.useState(t),c=g.useRef(null);return g.useEffect(()=>{o.trim()!==t&&l(t)},[t]),g.useEffect(()=>{i&&c.current?.focus()},[i]),a.jsxs(mc,{children:[a.jsx(gm,{children:e.label}),a.jsx(gm,{children:"is"}),a.jsx(bn,{ref:c,disabled:s,value:o,placeholder:e.placeholder??`Enter ${e.label}`,onChange:u=>{const d=u.target.value;l(d),d.trim()!==t&&n(d)},onKeyDown:u=>{if(u.key==="Enter"){u.preventDefault();const d=o.trim();d!==t&&n(d)}else u.key==="Escape"&&(u.preventDefault(),l(t),u.currentTarget.blur())}}),a.jsx(ce,{type:"button",disabled:s,"aria-label":`Remove ${e.label} filter`,onMouseDown:u=>u.preventDefault(),onClick:r,children:a.jsx(Mn,{})})]})}function PEs({field:e,token:t,tokens:n,onChange:r,onRemove:s,disabled:i}){const[o,l]=g.useState(!1);return a.jsxs(mc,{children:[a.jsx(gm,{children:e.label}),a.jsx(gm,{children:"is"}),a.jsxs(jp,{open:o,onOpenChange:l,children:[a.jsx(of,{asChild:!0,children:a.jsx(ce,{type:"button",disabled:i,children:tPe(t.value)})}),a.jsx(ah,{align:"start",sideOffset:D_,className:"w-64 p-0","data-pick-multi-panel":!0,children:a.jsx(OQt,{field:e,tokens:n,onChange:r})})]}),a.jsx(ce,{type:"button",disabled:i,"aria-label":`Remove ${e.label} filter`,onClick:s,children:a.jsx(Mn,{})})]})}function $Es({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:s,lockedFieldIds:i,lockedTooltipContent:o=IEs}){if(t.length===0)return null;const l=new Set(i??[]),c=(d,f)=>{const h=[...t];h[d]=f,n(h)},u=d=>{n(t.filter((f,h)=>h!==d))};return a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:t.map((d,f)=>{const h=e.find(p=>p.id===d.fieldId);return h?l.has(d.fieldId)?a.jsx(NEs,{field:h,value:d.value,tooltipContent:o},`${d.fieldId}-${f}`):h.kind==="text"&&!Array.isArray(d.value)?a.jsx(AEs,{field:h,value:d.value,disabled:r,autoFocus:s===d.fieldId,onChange:p=>c(f,{fieldId:d.fieldId,value:p}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):h.kind==="pick-multi"?a.jsx(PEs,{field:h,token:d,tokens:t,disabled:r,onChange:(p,m)=>c(f,{fieldId:p,value:m}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):a.jsxs(mc,{children:[a.jsx(gm,{children:h.label}),a.jsx(gm,{children:"is"}),a.jsx(gm,{children:tPe(d.value)}),a.jsx(ce,{type:"button",disabled:r,"aria-label":`Remove ${h.label} filter`,onClick:()=>u(f),children:a.jsx(Mn,{})})]},`${d.fieldId}-${f}`):null})})}const jQt=Z(og,"focus:text-foreground"),nPe=g.forwardRef((e,t)=>a.jsx("button",{type:"button",role:"menuitem","data-filter-item":"",ref:Du(t),...e}));nPe.displayName="FilterMenuButton";function REs({fields:e,tokens:t,onTokensChange:n,label:r="Add Filter",disabled:s,size:i,onStartTextFilter:o,hiddenFieldIds:l}){const c=g.useMemo(()=>{if(!l||l.length===0)return e;const P=new Set(l);return e.filter(L=>!P.has(L.id))},[e,l]),[u,d]=g.useState(!1),f=Bv(),[h,p]=g.useState(),[m,v]=g.useState([]),[y,x]=g.useState(),[b,S]=g.useState(),k=g.useRef(!1),j=g.useCallback(P=>{S(L=>L===P?void 0:P)},[]),C=g.useCallback(()=>S(void 0),[]);g.useEffect(()=>{u||S(void 0)},[u]);const T=g.useMemo(()=>c.find(P=>P.id===h),[c,h]),_=g.useMemo(()=>{const P=new Set;for(const L of t){const F=e.find(Q=>Q.id===L.fieldId);F&&F.kind!=="pick-multi"&&P.add(L.fieldId)}return P},[t,e]),N=g.useCallback(()=>{p(void 0),v([]),x(void 0)},[]);g.useEffect(()=>{u||N()},[u,N]);const E=g.useCallback((P,L)=>{const F=t.findIndex(q=>q.fieldId===P);if(Array.isArray(L)&&L.length===0){if(F===-1)return;n(t.filter((q,B)=>B!==F));return}if(F===-1){n([...t,{fieldId:P,value:L}]);return}const Q=[...t];Q[F]={fieldId:P,value:L},n(Q)},[n,t]),A=g.useCallback(()=>{if(!T){x("Choose a property first.");return}if(_.has(T.id)){x(`Remove the existing ${T.label} filter before adding another.`);return}if(m.length===0){x(`Choose at least one ${T.label.toLowerCase()} value.`);return}n([...t,{fieldId:T.id,value:m}]),d(!1)},[m,n,T,_,t]);return a.jsxs(jp,{open:u,onOpenChange:d,children:[a.jsx(of,{asChild:!0,children:a.jsx(ce,{size:i,disabled:s,icon:a.jsx(F6e,{}),children:r})}),a.jsx(ah,{align:"end",sideOffset:D_,className:Z("w-64",T?"p-3":"p-1"),initialFocus:!1,finalFocus:()=>k.current?(k.current=!1,!1):!0,children:a.jsxs("div",{className:Z("grid",T&&"gap-3"),children:[T&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{type:"button","aria-label":"Back to properties",className:Z(Zn,In),onClick:N,children:a.jsx(vd,{className:"size-4"})}),a.jsx(vIn,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:`${T.label} · is`})]}),!T&&a.jsx("div",{role:"menu",className:Z("max-h-[80dvh] overflow-auto",f.containerClassName),...f.getContainerProps({}),onKeyDown:P=>{if(P.key!=="ArrowDown"&&P.key!=="ArrowUp"&&P.key!=="Home"&&P.key!=="End")return;const L=Array.from(P.currentTarget.querySelectorAll("[data-filter-item]:not([disabled])"));if(L.length===0)return;P.preventDefault();const F=document.activeElement,Q=L.findIndex(B=>B===F);let q;P.key==="Home"?q=0:P.key==="End"?q=L.length-1:P.key==="ArrowDown"?q=Q<0?0:(Q+1)%L.length:q=Q<=0?L.length-1:Q-1,L[q]?.focus()},children:a.jsx(US,{menu:f,children:c.length>0?c.map(P=>{const L=_.has(P.id);return P.kind==="pick-multi"?a.jsx(MEs,{field:P,tokens:t,onChange:E,open:b===P.id,onToggle:j,onClose:C},P.id):a.jsxs(nPe,{className:Z(jQt,"group"),disabled:L,onClick:()=>{if(x(void 0),P.kind==="text"){n([...t,{fieldId:P.id,value:""}]),o?.(P.id),k.current=!0,d(!1);return}p(P.id)},children:[a.jsx("span",{className:"truncate",children:P.label}),L?a.jsx("span",{className:"ml-auto text-muted-foreground",children:"In use"}):a.jsx("span",{className:Z(VL,"text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 group-focus:opacity-100"),children:a.jsx(Dr,{})})]},P.id)}):a.jsx("div",{className:hQ,children:"No matching property."})})}),T&&a.jsxs(pt,{invalid:!!y,children:[a.jsx(fl,{multiple:!0,options:T.options??[],value:m,onValueChange:P=>{v(P),x(void 0)},placeholder:T.placeholder??`Choose ${T.label}`,searchPlaceholder:`Search ${T.label.toLowerCase()}...`,emptyText:T.emptyText??"No option found.",size:"md","aria-label":T.label}),a.jsx(ns,{children:y})]}),T&&a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.jsx(ce,{icon:a.jsx(Mn,{}),variant:"ghost",size:"md",onClick:()=>d(!1),children:"Cancel"}),a.jsx(ce,{icon:a.jsx(F6e,{}),size:"md",onClick:A,children:"Add filter"})]})]})})]})}function MEs({field:e,tokens:t,onChange:n,open:r,onToggle:s,onClose:i}){const o=g.useRef(null);return a.jsxs(jp,{open:r,onOpenChange:l=>{l?s(e.id):i()},children:[a.jsx(of,{asChild:!0,children:a.jsxs(nPe,{className:jQt,onKeyDown:l=>{l.key!=="ArrowRight"&&l.key!=="ArrowLeft"||(r||s(e.id),l.preventDefault(),requestAnimationFrame(()=>{o.current?.querySelector('input, button, [tabindex]:not([tabindex="-1"])')?.focus()}))},children:[r&&a.jsx(Lc,{className:"text-muted-foreground"}),a.jsx("span",{className:"truncate",children:e.label}),!r&&a.jsx("span",{className:Z(VL,"text-muted-foreground"),children:a.jsx(Lc,{})})]})}),a.jsx(ah,{ref:o,side:"right",align:"start",sideOffset:D_,className:"w-64 p-0",initialFocus:!1,onKeyDown:l=>{if(l.key!=="ArrowDown"&&l.key!=="ArrowUp"&&l.key!=="Home"&&l.key!=="End")return;const c=Array.from(l.currentTarget.querySelectorAll("[data-pick-multi-item]:not([disabled])"));if(c.length===0)return;l.preventDefault(),l.stopPropagation();const u=document.activeElement,d=c.findIndex(h=>h===u);let f;l.key==="Home"?f=0:l.key==="End"?f=c.length-1:l.key==="ArrowDown"?f=d<0?0:(d+1)%c.length:f=d<=0?c.length-1:d-1,c[f]?.focus()},"data-pick-multi-panel":!0,children:a.jsx(OQt,{field:e,tokens:t,onChange:n})})]})}function DEs({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:i,depth:o}){const l=e?$C(e.timestamp)??"":"";return a.jsx(_t,{open:!!e,onClose:t,title:e?`Log ${l}`:"Log",depth:o,children:e&&a.jsxs(a.Fragment,{children:[a.jsxs(_t.Header,{children:[a.jsx(_t.CloseButton,{onClick:t}),a.jsxs(_t.Heading,{children:["Log · ",l]}),a.jsx(_t.HeaderActions,{children:a.jsx(_t.NextPrevNav,{onPrevious:s,onNext:i,previousLabel:"Go to previous log",nextLabel:"Go to next log"})})]}),a.jsx(_t.Content,{children:a.jsxs("div",{className:"grid gap-6 p-2",children:[a.jsxs(Kt,{children:[e.entityType&&a.jsxs(a.Fragment,{children:[a.jsx(Kt.Key,{children:"Entity Type"}),a.jsx(Kt.Value,{children:e.entityType})]}),e.entityName&&a.jsxs(a.Fragment,{children:[a.jsx(Kt.Key,{children:"Entity Name"}),a.jsx(Kt.Value,{children:e.entityName})]}),e.serviceName&&a.jsxs(a.Fragment,{children:[a.jsx(Kt.Key,{children:"Service"}),a.jsx(Kt.Value,{children:e.serviceName})]}),e.environment&&a.jsxs(a.Fragment,{children:[a.jsx(Kt.Key,{children:"Environment"}),a.jsx(Kt.Value,{children:e.environment})]}),e.source&&a.jsxs(a.Fragment,{children:[a.jsx(Kt.Key,{children:"Source"}),a.jsx(Kt.Value,{children:e.source})]}),e.metadata&&Object.entries(e.metadata).map(([c,u])=>a.jsxs(g.Fragment,{children:[a.jsx(Kt.Key,{children:c}),a.jsx(Kt.Value,{children:String(u)})]},c))]}),a.jsx(_t.CodeSection,{title:"Message",codeStr:e.message,simplified:!0}),(e.traceId||e.spanId)&&a.jsxs("div",{className:"grid gap-2",children:[e.traceId&&a.jsxs(mc,{className:"w-full min-w-0",children:[a.jsxs(ce,{className:"min-w-0 flex-1 justify-between overflow-hidden",icon:a.jsx(dp,{}),onClick:()=>e.traceId&&n?.(e.traceId),children:[a.jsx("span",{children:"Trace"}),a.jsxs(Y,{as:"span",variant:"caption",tone:"faint",className:"ml-auto min-w-0 truncate",children:["# ",e.traceId]})]}),a.jsx(ii,{content:e.traceId,tooltip:"Copy Trace ID to clipboard"})]}),e.spanId&&a.jsxs(mc,{className:"w-full min-w-0",children:[a.jsxs(ce,{className:"min-w-0 flex-1 justify-between overflow-hidden",disabled:!e.traceId||!r,onClick:()=>e.traceId&&e.spanId&&r?.(e.traceId,e.spanId),icon:a.jsx(dp,{}),children:[a.jsx("span",{children:"Span"}),a.jsxs(Y,{as:"span",variant:"caption",tone:"faint",className:"ml-auto min-w-0 truncate",children:["# ",e.spanId]})]}),a.jsx(ii,{content:e.spanId,tooltip:"Copy Span ID to clipboard"})]})]}),e.data&&Object.keys(e.data).length>0&&a.jsx(_t.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2)})]})})]})})}function LEs({error:e,resource:t,errorTitle:n}){if(Cs(e))return a.jsx(ci,{});if(_s(e))return a.jsx(Gs,{resource:t});if(i6(e))return a.jsx(Yt,{titleSlot:"Observability storage is not available",descriptionSlot:"The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio."});if(s6(e,"logs"))return a.jsx(Yt,{titleSlot:"Logs are not available with your current storage",descriptionSlot:"The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio."});const r=e instanceof Error?e.message:void 0;return a.jsx(Yt,{tone:"error",titleSlot:n,descriptionSlot:r??"Unknown error"})}const zEs={debug:"neutral",info:"info",warn:"warning",error:"destructive",fatal:"destructive"};function FEs({level:e}){return a.jsx(ma,{children:a.jsx($t,{variant:zEs[e],children:e})})}function BEs({entityType:e,className:t}){const n=Z("size-3.5 shrink-0 text-placeholder",t);switch(e.toLowerCase()){case"agent":return a.jsx(Vo,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return a.jsx(jl,{className:n,"aria-hidden":!0});case"tool":return a.jsx(fd,{className:n,"aria-hidden":!0});default:return null}}function VEs({entityType:e,entityName:t}){const n=e??"";return a.jsxs(ma,{className:"flex min-w-0 items-center gap-2",children:[a.jsx(BEs,{entityType:n}),t?a.jsx(Y,{as:"span",variant:"body-sm",className:"min-w-0 truncate",children:t}):"-"]})}function UEs({message:e}){return a.jsx(ma,{className:"min-w-0 truncate font-mono text-body-sm text-muted-foreground",children:e})}function qEs({data:e}){if(!e||Object.keys(e).length===0)return a.jsx(ma,{children:null});const t=Object.entries(e).map(([n,r])=>{if(typeof r=="string")return`${n}: ${r}`;try{return`${n}: ${JSON.stringify(r)}`}catch{return`${n}: <unserializable>`}}).join(", ");return a.jsx(ECe,{font:"mono",children:t})}const Ml=Object.assign(A6,{Top:$6,TopCell:dw,SortableTopCell:sX,TopCellWithTooltip:rX,TopCellSmart:YAt,RowWrapper:$Ce,RowButton:P6,RowLink:PCe,Spacer:RCe,NoMatch:nX,DateCell:BAt,TimeCell:UAt,LevelCell:FEs,EntityCell:VEs,MessageCell:UEs,DataCell:qEs,NextPageLoading:tX}),$nt="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",QEs=36,ZEs=8;function WEs({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:i,featuredLogId:o,onLogClick:l,timestampSort:c,onSortChange:u}){const d=g.useRef(null),f=_Ut({count:e.length,getScrollElement:()=>d.current,estimateSize:()=>QEs,overscan:ZEs}),{getRowProps:h}=Fu({count:e.length,containerRef:d,onNavigate:b=>f.scrollToIndex(b),global:!0}),p=g.useRef(t);if(g.useEffect(()=>{p.current&&!t&&d.current?.dispatchEvent(new Event("scroll")),p.current=t},[t]),t)return a.jsx(Lu,{columns:$nt,fit:"container"});const m=f.getVirtualItems(),v=f.getTotalSize(),y=m[0]?.start??0,x=m.length>0?Math.max(0,v-(m[m.length-1]?.end??0)):0;return a.jsxs(Ml,{columns:$nt,scrollRef:d,className:"min-w-0",fit:"container",children:[a.jsxs(Ml.Top,{children:[u?a.jsx(Ml.SortableTopCell,{sortKey:"timestamp",sort:c,onSortChange:u,children:"Date"}):a.jsx(Ml.TopCell,{children:"Date"}),a.jsx(Ml.TopCell,{children:"Time"}),a.jsx(Ml.TopCell,{children:"Level"}),a.jsx(Ml.TopCell,{children:"Entity"}),a.jsx(Ml.TopCell,{children:"Message"}),a.jsx(Ml.TopCell,{children:"Data"})]}),e.length===0?a.jsx(Ml.NoMatch,{message:"No logs match your search"}):a.jsxs(a.Fragment,{children:[a.jsx(Ml.Spacer,{height:y}),m.map(b=>{const S=e[b.index];if(!S)return null;const k=i.get(S);if(!k)return null;const j=k===o;return a.jsxs(Ml.RowButton,{ref:f.measureElement,"data-index":b.index,...h(b.index),onClick:()=>l(S),featured:j,variant:S.level==="error"||S.level==="fatal"?"error":"default",children:[a.jsx(Ml.DateCell,{timestamp:S.timestamp}),a.jsx(Ml.TimeCell,{timestamp:S.timestamp}),a.jsx(Ml.LevelCell,{level:S.level}),a.jsx(Ml.EntityCell,{entityType:S.entityType,entityName:S.entityName}),a.jsx(Ml.MessageCell,{message:S.message}),a.jsx(Ml.DataCell,{data:S.data})]},k)}),a.jsx(Ml.Spacer,{height:x})]}),a.jsx(Ml.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function HEs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:i,filterTokens:o,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=o.length>0,d=o.some(f=>GEs(f,i));return u?a.jsxs("div",{className:Z("grid grid-cols-[1fr_auto] items-start gap-3"),children:[a.jsx($Es,{fields:i,tokens:o,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&a.jsx(_Es,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function GEs(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}const KEs={"last-24h":"the last 24 hours","last-3d":"the last 3 days","last-7d":"the last 7 days","last-14d":"the last 14 days","last-30d":"the last 30 days"},Aue="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function YEs({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${KEs[e]}`,description:Aue}:t&&n?{title:`No logs between ${rs(t,"date-time")} and ${rs(n,"date-time")}`,description:Aue}:t?{title:`No logs since ${rs(t,"date-time")}`,description:Aue}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const XEs=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=YEs({datePreset:e,dateFrom:t,dateTo:n});return a.jsx(Yt,{titleSlot:r,descriptionSlot:s,actionSlot:a.jsx(ce,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Logging Documentation"}),variant:"fill"})},X7={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},CQt=[{label:"Agent",entityType:X7.AGENT},{label:"Workflow",entityType:X7.WORKFLOW},{label:"Scorer",entityType:X7.SCORER},{label:"Ingest",entityType:X7.INGEST}],JEs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],U0="rootEntityType",Hb="datePreset",Gb="dateFrom",Kb="dateTo",eNs=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Ll={level:"filterLevel",tags:"filterTags",entityName:"filterEntityName",traceId:"filterTraceId",spanId:"filterSpanId",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId"},Bz=Object.keys(Ll),rPe=new Set(["tags"]),sPe="mastra:logs:saved-filters";function tNs(e,t=sPe){const n=oNs(e),r=e.get(Hb);r&&n.set(Hb,r);const s=e.get(Gb);s&&n.set(Gb,s);const i=e.get(Kb);i&&n.set(Kb,i);try{localStorage.setItem(t,n.toString())}catch{}}function nNs(e=sPe){try{localStorage.removeItem(e)}catch{}}function Rnt(e=sPe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function rNs(e){if(e.has(Hb)||e.has(Gb)||e.has(Kb)||e.has(U0))return!0;for(const t of Bz)if(e.has(Ll[t]))return!0;return!1}function sNs({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const i=[{id:"rootEntityType",label:"Primitive type",kind:"pick-multi",searchable:!1,options:CQt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"level",label:"Level",kind:"pick-multi",searchable:!1,options:JEs.map(u=>({label:u.label,value:u.value})),placeholder:"Choose level",emptyText:"No levels."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"spanId",label:"Span ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],o=(u,d)=>u.label.localeCompare(d.label),l=i.filter(u=>u.kind==="pick-multi").sort(o),c=i.filter(u=>u.kind==="text").sort(o);return[...l,...c]}function iNs(e){const t=[],n=new Map([[U0,"rootEntityType"]]);for(const s of Bz)n.set(Ll[s],s);const r=new Set;for(const[s]of e.entries()){const i=n.get(s);if(!i||r.has(i))continue;if(r.add(i),rPe.has(i)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:i,value:l.filter(Boolean)});continue}const o=e.get(s);o!==null&&t.push({fieldId:i,value:o})}return t}function oNs(e){const t=new URLSearchParams,n=e.get(U0);n&&t.set(U0,n);for(const r of Bz){const s=Ll[r];if(rPe.has(r)){for(const o of e.getAll(s))t.append(s,o);continue}const i=e.get(s);i&&t.set(s,i)}return t}function aNs(e,t){e.delete(U0);for(const n of Bz)e.delete(Ll[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(U0,n.value);continue}const r=Ll[n.fieldId];if(r){if(rPe.has(n.fieldId)&&Array.isArray(n.value)){if(n.value.length===0)e.append(r,"");else for(const s of n.value)e.append(r,s);continue}typeof n.value=="string"&&e.set(r,n.value.trim())}}}function lNs({rootEntityType:e,dateFrom:t,dateTo:n,tokens:r}){const s={};e&&(s.rootEntityType=e),(t||n)&&(s.timestamp={...t?{start:t}:{},...n?{end:n}:{}});for(const i of r){if(i.fieldId==="tags"){Array.isArray(i.value)&&i.value.length>0?s.tags=i.value:typeof i.value=="string"&&i.value.trim()&&(s.tags=[i.value.trim()]);continue}if(i.fieldId==="level"){typeof i.value=="string"&&i.value.trim()&&i.value!=="Any"&&(s.level=i.value);continue}if(typeof i.value=="string"&&i.value.trim()&&i.value!=="Any")switch(i.fieldId){case"entityName":s.rootEntityName=i.value;break;case"traceId":s.traceId=i.value;break;case"spanId":s.spanId=i.value;break;case"runId":s.runId=i.value;break;case"threadId":s.threadId=i.value;break;case"sessionId":s.sessionId=i.value;break;case"requestId":s.requestId=i.value;break;case"resourceId":s.resourceId=i.value;break;case"userId":s.userId=i.value;break;case"organizationId":s.organizationId=i.value;break;case"serviceName":s.serviceName=i.value;break;case"environment":s.environment=i.value;break;case"experimentId":s.experimentId=i.value;break}}return s}function cNs(e,t){return t.map(n=>{const r=e.find(s=>s.id===n.fieldId);return r?r.kind==="text"?{fieldId:n.fieldId,value:""}:r.kind==="pick-multi"?r.multi?{fieldId:n.fieldId,value:[]}:{fieldId:n.fieldId,value:"Any"}:n:n})}const uNs="Filters setting for Logs saved",dNs="Filters setting for Logs cleared up";function fNs(e,t,n){const{storageKey:r,messages:s,skipHydration:i}={},[o,l]=g.useState(()=>Rnt(r)!==null),c=g.useCallback(()=>{tNs(e,r),l(!0);const f=s?.saved??uNs;f!==!1&&Xe.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{nNs(r),l(!1);const f=s?.cleared??dNs;f!==!1&&Xe.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(i||d.current||(d.current=!0,rNs(e)))return;const f=Rnt(r);f&&t(h=>{const p=new URLSearchParams(h);for(const[m,v]of f)p.append(m,v);return p},{replace:!0})},[]),{hasSavedFilters:o,handleSave:c,handleRemoveSaved:u}}function hNs(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function pNs(e){const t=new Map;for(const n of e){if(n.logId){t.set(n,n.logId);continue}const r=n.timestamp instanceof Date?n.timestamp.toISOString():n.timestamp;t.set(n,hNs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function mNs(e,t,n,r){const s=g.useMemo(()=>pNs(e),[e]),i=g.useMemo(()=>{const p=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&p.set(y,{log:v,idx:m})}return p},[e,s]),l=(t?i.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(p=>s.get(p),[s]),d=g.useCallback(p=>{const m=s.get(p);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const p=e[l-1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0,h=l>=0&&l<e.length-1?()=>{const p=e[l+1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:h}}const sxe="logId",ixe="traceId",oxe="spanId",LM=1440*60*1e3,gNs={"last-24h":LM,"last-3d":3*LM,"last-7d":7*LM,"last-14d":14*LM,"last-30d":30*LM};function J7(e){e.delete(sxe),e.delete(ixe),e.delete(oxe)}function vNs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const j=e.get(Hb);return j&&eNs.has(j)?j:"last-24h"},[e]),i=e.get(Gb),o=e.get(Kb),l=g.useMemo(()=>{if(s==="custom"){if(!i)return;const C=new Date(i);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const j=gNs[s];return j?new Date(Date.now()-j):void 0},[s,i]),c=g.useMemo(()=>{if(s!=="custom"||!o)return;const j=new Date(o);return Number.isNaN(j.getTime())?void 0:j},[s,o]),u=g.useRef(s);u.current=s;const d=e.get(sxe),f=e.get(ixe),h=e.get(oxe),p=g.useMemo(()=>CQt.find(j=>j.entityType===e.get(U0)),[e]),m=g.useMemo(()=>iNs(e),[e]),v=g.useCallback(j=>{t(C=>{const T=new URLSearchParams(C);for(const[_,N]of Object.entries(j)){const E=_==="logId"?sxe:_==="traceId"?ixe:oxe;N?T.set(E,N):T.delete(E)}return T},{replace:!0})},[t]),y=g.useCallback(j=>{t(C=>{const T=new URLSearchParams(C);return aNs(T,j),J7(T),T},{replace:!0})},[t]),x=y,b=g.useCallback((j,C)=>{if(u.current!=="custom")return;const T=C==="from"?Gb:Kb;t(_=>{const N=new URLSearchParams(_);return j?N.set(T,j.toISOString()):N.delete(T),J7(N),N},{replace:!0})},[t]),S=g.useCallback(j=>{u.current=j,t(C=>{const T=new URLSearchParams(C);return j==="last-24h"?(T.delete(Hb),T.delete(Gb),T.delete(Kb)):j==="custom"?T.set(Hb,"custom"):(T.set(Hb,j),T.delete(Gb),T.delete(Kb)),J7(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(j=>{const C=new URLSearchParams(j);C.delete(U0);for(const T of Bz)C.delete(Ll[T]);return C.delete(Hb),C.delete(Gb),C.delete(Kb),J7(C),C},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:h,selectedEntityOption:p,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:x,handleDateChange:b,handleDatePresetChange:S,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,h,p,m,v,x,b,S,k,y])}const yNs=20,xNs=1e4,bNs={field:"timestamp",direction:"DESC"};function wNs(e,t,n){if(e?.pagination?.hasMore)return n+1}function SNs(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const i=s.logId??JSON.stringify(s);t.has(i)||(t.add(i),n.push(s))}return n}function kNs(e){return s6(e.state.error,"logs")||i6(e.state.error)?!1:xNs}const ONs=({filters:e,orderBy:t=bNs,queryOptions:n}={})=>{const r=Ke(),{inView:s,setRef:i}=X0(),{hasNextPage:o,isFetchingNextPage:l,fetchNextPage:c,data:u,isLoading:d,isError:f,error:h}=Mm({queryKey:["logs",e,t],queryFn:({pageParam:p})=>r.listLogsVNext({pagination:{page:p,perPage:yNs},filters:e,orderBy:t}),initialPageParam:0,getNextPageParam:wNs,select:SNs,retry:!1,refetchInterval:kNs,...n});return g.useEffect(()=>{s&&o&&!l&&c()},[s,o,l,c]),{data:u,hasNextPage:o,isFetchingNextPage:l,fetchNextPage:c,isLoading:d,isError:f,error:h,setEndOfListElement:i}},Pue=[Ts("/logs")],jNs=["timestamp"],CNs={key:"timestamp",direction:"desc"};function _Ns(){const[e,t]=wi(),n=Lr(),r=vNs(e,t),s=see(),{sort:i,onSortChange:o}=cT({searchParams:e,setSearchParams:t,allowedKeys:jNs,defaultSort:CNs}),l=g.useMemo(()=>({field:"timestamp",direction:i?.direction==="asc"?"ASC":"DESC"}),[i?.direction]),c=fNs(e,t),[u,d]=g.useState(),{data:f=[],isPending:h}=KBt(),{data:p=[],isPending:m}=LNe({entityType:r.selectedEntityOption?.entityType,rootOnly:!0}),{data:v=[],isPending:y}=zNe(),{data:x=[],isPending:b}=GBt(),S=g.useMemo(()=>sNs({availableTags:f,availableRootEntityNames:p,availableServiceNames:x,availableEnvironments:v,loading:{tags:h,entityNames:m,serviceNames:b,environments:y}}),[f,p,x,v,h,m,b,y]),k=g.useMemo(()=>lNs({rootEntityType:r.selectedEntityOption?.entityType,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo,tokens:r.filterTokens}),[r.filterTokens,r.selectedDateFrom,r.selectedDateTo,r.selectedEntityOption]),{data:j=[],isLoading:C,error:T,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:E}=ONs({filters:k,orderBy:l}),{logIdMap:A,featuredLog:P,handleLogClick:L,handlePreviousLog:F,handleNextLog:Q}=mNs(j,r.featuredLogId,r.handleFeaturedChange,r.featuredTraceId),{data:q,isLoading:B}=aT({traceId:r.featuredTraceId??null,queryOptions:{enabled:!!r.featuredTraceId}}),V=g.useCallback(()=>r.applyFilterTokens(cNs(S,r.filterTokens)),[S,r]),W=g.useCallback(()=>r.handleFeaturedChange({logId:null}),[r]),M=g.useCallback(G=>r.handleFeaturedChange({traceId:G,spanId:null}),[r]),K=g.useCallback((G,ne)=>r.handleFeaturedChange({traceId:G,spanId:ne}),[r]),D=g.useCallback(()=>r.handleFeaturedChange({traceId:null,spanId:null}),[r]),$=g.useCallback(G=>r.handleFeaturedChange({spanId:G??null}),[r]),z=a.jsxs(a.Fragment,{children:[a.jsx(rr,{children:a.jsxs(rr.Start,{children:[a.jsx(DCe,{preset:r.datePreset,onPresetChange:r.handleDatePresetChange,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo,onDateChange:r.handleDateChange,disabled:C,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),a.jsx(REs,{fields:S,tokens:r.filterTokens,onTokensChange:r.handleFilterTokensChange,disabled:C,onStartTextFilter:d})]})}),a.jsx(HEs,{isLoading:C,filterFields:S,filterTokens:r.filterTokens,onFilterTokensChange:r.handleFilterTokensChange,onClear:V,onRemoveAll:r.handleRemoveAll,onSave:c.handleSave,onRemoveSaved:c.hasSavedFilters?c.handleRemoveSaved:void 0,autoFocusFilterFieldId:u})]});if(T)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Pue}),actionRow:z,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsx(LEs,{error:T,resource:"logs",errorTitle:"Failed to load logs"})})]});const U=!!r.selectedEntityOption||r.filterTokens.length>0;return j.length===0&&!C&&!U?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Pue}),actionRow:z,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx(XEs,{datePreset:r.datePreset,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Pue}),actionRow:z,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx(WEs,{logs:j,isLoading:C,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:E,logIdMap:A,featuredLogId:r.featuredLogId,onLogClick:L,timestampSort:i?.direction,onSortChange:o}),a.jsx(DEs,{log:P??void 0,onClose:W,onTraceClick:M,onSpanClick:K,onPrevious:F,onNext:Q}),a.jsx(gAe,{depth:2,traceId:P?r.featuredTraceId??void 0:void 0,spans:q?.spans,isLoadingSpans:B,selectedSpanId:r.featuredSpanId??null,onSpanSelect:$,onClose:D,withQueryTrace:s.enabled,withFeedback:s.enabled,onOpenScore:(G,ne)=>n(n_e(G,ne))})]})}const TNs={name:e=>e.name||e.id};function INs({server:e,rowProps:t}){const{paths:n,Link:r}=Sn(),i=Ke().options.baseUrl,l=e.transports?.includes("sse")??!0?"sse":"mcp",c=i?`${i}/api/mcp/${e.id}/${l}`:"",{data:u}=YOt({selectedServer:e}),d=Object.values(u||{}),f=d.length,h=d.filter(v=>v.toolType==="agent").length,p=d.filter(v=>v.toolType==="workflow").length,m=cf(e.name,50);return a.jsxs(Te.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[a.jsx(Te.NameCell,{children:m}),a.jsx(Te.DescriptionCell,{children:c}),a.jsx(Te.TextCell,{className:"text-center",children:h||""}),a.jsx(Te.TextCell,{className:"text-center",children:f||""}),a.jsx(Te.TextCell,{className:"text-center",children:p||""})]})}function ENs({mcpServers:e,isLoading:t,search:n="",sort:r,onSortChange:s}){const i=g.useMemo(()=>{const c=n.toLowerCase();return qk(e.filter(u=>u.name?.toLowerCase().includes(c)||u.id?.toLowerCase().includes(c)),r,TNs)},[e,n,r]),{containerRef:o,getRowProps:l}=Fu({count:i.length,global:!0});return t?a.jsx(Lu,{columns:"auto 1fr auto auto auto"}):a.jsxs(Te,{columns:"auto 1fr auto auto auto",scrollRef:o,children:[a.jsxs(Te.Top,{children:[s?a.jsx(Te.SortableTopCell,{sortKey:"name",sort:r?.key==="name"?r.direction:void 0,onSortChange:s,children:"Name"}):a.jsx(Te.TopCell,{children:"Name"}),a.jsx(Te.TopCell,{children:"URL"}),a.jsx(Te.TopCellSmart,{long:"Agents",short:a.jsx(Vo,{}),tooltip:"Agent Tools",className:"text-center"}),a.jsx(Te.TopCellSmart,{long:"Tools",short:a.jsx(fd,{}),tooltip:"Tools",className:"text-center"}),a.jsx(Te.TopCellSmart,{long:"Workflows",short:a.jsx(jl,{}),tooltip:"Workflow Tools",className:"text-center"})]}),i.length===0&&n?a.jsx(Te.NoMatch,{message:"No MCP Servers match your search"}):null,i.map((c,u)=>a.jsx(INs,{server:c,rowProps:l(u)},c.id))]})}const NNs=()=>a.jsx(Yt,{titleSlot:"No MCP Servers yet",descriptionSlot:a.jsxs(a.Fragment,{children:["MCP servers are not configured yet. ",a.jsx("br",{}),"More information in the documentation."]}),actionSlot:a.jsx(ce,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"MCP Documentation"}),variant:"fill"}),zM=[Ts("/mcps")],ANs=()=>{const{data:e=[],isLoading:t,error:n}=LP(),[r,s]=g.useState(""),[i,o]=g.useState();return n&&Cs(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:zM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(ci,{variant:"fill"})]}):n&&_s(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:zM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(Gs,{variant:"fill",resource:"MCP servers"})]}):n?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:zM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(Yt,{tone:"error",variant:"fill",titleSlot:"Failed to load MCP servers",descriptionSlot:n.message})]}):e.length===0&&!t?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:zM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(NNs,{})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:zM}),actionRow:a.jsx(rr,{children:a.jsx(rr.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(pf,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})})}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(ENs,{mcpServers:e,isLoading:t,search:r,sort:i,onSortChange:(l,c)=>o({key:c,direction:l})})]})};function Yf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function PNs(e){if(!Yf(e))return;if(Yf(e.ui)&&typeof e.ui.resourceUri=="string")return e.ui.resourceUri;const t=e["ui/resourceUri"];return typeof t=="string"?t:void 0}function $Ns(e){return Yf(e)&&e.status==="suspended"}function RNs(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(2)} s`}function MNs(e){return e===void 0?"undefined":JSON.stringify(e,null,2)}function _Qt(e){return e.status==="error"?e.error:MNs(e.output)}function DNs({status:e,output:t,error:n},r){if(r!==void 0){if(e==="success")return{status:"success",output:t,durationMs:r};if(e==="error")return{status:"error",error:LNs(n),durationMs:r}}}function LNs(e){return e instanceof Error?JSON.stringify({error:e.message},null,2):JSON.stringify({error:String(e)},null,2)}function wee(e){return a.jsx(hye,{className:"min-h-control-md",...e})}function zNs({zodInputSchema:e,isRunning:t,onRun:n,requestContextEntityType:r,requestContextEntityId:s}){const i=!SQ(e),[o,l]=g.useState({view:"form",value:void 0}),c=g.useRef(void 0),[u,d]=g.useState([]);function f(m){if(m===o.view)return;if(d([]),o.view==="form")return l({view:"json",value:JSON.stringify(c.current??{},null,2)});const v=wke(o.value);if(!v.ok)return d([v.error]);const y=xkt(e,v.value);if(y)return d([y]);c.current=v.value,l({view:"form",value:v.value})}function h(m){const v=bkt(e,m);v.ok?n(v.value):d(v.errors)}const p={isSubmitLoading:t,submitButtonLabel:"Run",submitButtonIcon:a.jsx(Fm,{}),submitButtonVariant:"primary"};return a.jsxs(BA,{children:[a.jsx(wee,{action:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(Wke,{entityType:r,entityId:s}),a.jsx(Hc,{defaultTab:"form",value:o.view,onValueChange:f,children:a.jsxs(Gc,{size:"md",children:[a.jsxs(si,{value:"form",disabled:t,children:[a.jsx(At,{size:"sm",children:a.jsx(wpt,{})}),"Form"]}),a.jsxs(si,{value:"json",disabled:t,children:[a.jsx(At,{size:"sm",children:a.jsx(Va,{})}),"JSON"]})]})})]}),children:a.jsx(VA,{children:"Request"})}),a.jsx(x$,{children:a.jsx("div",{className:"p-4",children:o.view==="json"?a.jsxs("div",{className:"grid gap-4",children:[a.jsxs(pt,{invalid:u.length>0,children:[a.jsx(Or,{variant:"embedded",language:"json",value:o.value,onChange:m=>{l({view:"json",value:m}),d([])},editable:!t,"aria-label":"Request JSON"}),u.length>0&&a.jsx(ns,{children:u.map(m=>a.jsx("span",{className:"block",children:m},m))})]}),a.jsx(cK,{...p,onSubmit:()=>h(o.value)})]}):a.jsx(bke,{...p,schema:e,defaultValues:o.value,onValuesChange:m=>{c.current=m},onSubmit:n,className:"gap-0",children:!i&&a.jsx(Y,{variant:"body-sm",tone:"muted",className:"pb-4",children:"This tool takes no input. Run it as is."})})})})]})}function FNs({isRunning:e,lastRun:t}){return e?a.jsx(Yt,{iconSlot:a.jsx(On,{}),titleSlot:"Running…",descriptionSlot:"Waiting for the tool to respond."}):t?a.jsx(Cl,{code:_Qt(t),lang:"json",className:"overflow-x-auto p-4 text-caption whitespace-pre"}):a.jsx(Yt,{iconSlot:a.jsx(PNn,{}),titleSlot:"No response yet",descriptionSlot:"Run the tool to see its output here."})}function BNs({run:e}){return a.jsxs("div",{className:"flex items-center gap-2",children:[e.status==="success"?a.jsx($t,{variant:"success",emphasis:"subtle",indicator:"dot",children:"Success"}):a.jsx($t,{variant:"destructive",emphasis:"subtle",indicator:"dot",children:"Error"}),a.jsx(Y,{as:"span",variant:"caption",font:"mono",tone:"muted",children:RNs(e.durationMs)}),a.jsx(ii,{content:_Qt(e),copyMessage:"Response copied",tooltip:"Copy response",size:"icon-sm"})]})}function VNs({isRunning:e,lastRun:t}){return a.jsxs(BA,{className:"h-full",children:[a.jsx(wee,{action:!e&&t&&a.jsx(BNs,{run:t}),children:a.jsx(VA,{children:"Response"})}),a.jsx(x$,{className:"grid min-h-48 flex-1 content-center",children:a.jsx(FNs,{isRunning:e,lastRun:t})})]})}function TQt({zodInputSchema:e,execution:t,requestContextEntityType:n,requestContextEntityId:r}){const[s]=xr(n,r),[i,o]=g.useState(),l=async u=>{const d=performance.now();await t.execute(u,s).catch(()=>{}),o(performance.now()-d)},c=t.status==="pending";return a.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-6",children:[a.jsx(zNs,{zodInputSchema:e,isRunning:c,onRun:l,requestContextEntityType:n,requestContextEntityId:r}),a.jsx(VNs,{isRunning:c,lastRun:DNs(t,i)})]})}function IQt(e){return Yf(e)?MS(e):yr({})}function UNs({serverId:e,tool:t}){const{mutateAsync:n,status:r,data:s,error:i}=nur({serverId:e,toolId:t.name}),{data:o}=eur({serverId:e,appResourceUri:PNs(t._meta)}),l=IQt(t.inputSchema),c={execute:(u,d)=>n({data:u,requestContext:d}),status:r,output:s,error:i};return a.jsxs("div",{className:"grid content-start gap-6",children:[o&&a.jsx(P9t,{html:o,toolName:t.name,onToolCall:(u,d)=>n({data:d})}),$Ns(s)&&a.jsxs(Wt,{variant:"warning",children:["This tool asked for more input, which Studio cannot provide. The suspend payload below shows what it needs. Call it from an MCP client with an ",a.jsx(rh,{children:"inputRequests"})," handler to finish the request."]}),a.jsx(TQt,{zodInputSchema:l,execution:c,requestContextEntityType:"mcp-tool",requestContextEntityId:`${e}:${t.name}`})]})}const EQt=g.createContext(void 0),qNs=EQt.Provider;function iPe(){const e=g.useContext(EQt);if(e===void 0)throw new Error("useOpenToolId must be used inside ToolDrawer");return e}function QNs({description:e}){const t=FX({collapsedHeight:140});return a.jsx(W6,{state:t,expandLabel:"Read more",children:a.jsx(_l,{children:e})})}function NQt({description:e,overview:t,playground:n,canRun:r}){return a.jsx(a.Fragment,{children:a.jsxs(Hc,{defaultTab:"overview",className:"grid flex-1 grid-rows-[auto_1fr] gap-4 overflow-visible",children:[a.jsxs(Gc,{variant:"pill",size:"sm",children:[a.jsx(si,{value:"overview",children:"Overview"}),a.jsx(si,{value:"playground",disabled:!r,disabledTooltip:"You don't have permission to execute tools.",children:"Playground"})]}),a.jsxs(No,{value:"overview",flush:!0,className:"content-start gap-6",children:[e&&a.jsx(hl,{className:"p-4",children:a.jsx(QNs,{description:e})}),t]}),a.jsx(No,{value:"playground",flush:!0,keepMounted:!0,className:"h-full",children:r&&n})]})})}function ZNs(e){return e.map(t=>JSON.stringify(t)).join(" | ")}function Mnt(e){return e.map(C3).join(" | ")}function C3(e){return Yf(e)?Array.isArray(e.enum)?ZNs(e.enum):"const"in e?JSON.stringify(e.const):Array.isArray(e.anyOf)?Mnt(e.anyOf):Array.isArray(e.oneOf)?Mnt(e.oneOf):Array.isArray(e.type)?e.type.join(" | "):e.type==="array"?`${C3(e.items)}[]`:AQt(e)?`Record<string, ${C3(e.additionalProperties)}>`:typeof e.type=="string"?e.type:"unknown":"unknown"}function WNs(e,t,n,{defaultsAreOptional:r=!1}){const s=Yf(t)?t:{},i="default"in s;return{name:e,type:C3(s),required:n.has(e)&&!(r&&i),description:typeof s.description=="string"?s.description:void 0,defaultValue:i?JSON.stringify(s.default):void 0}}function HNs(e,t={}){if(!Yf(e)||!Yf(e.properties))return[];const n=new Set(Array.isArray(e.required)?e.required.filter(r=>typeof r=="string"):[]);return Object.entries(e.properties).map(([r,s])=>WNs(r,s,n,t))}function AQt(e){return Yf(e)&&e.type==="object"&&!Yf(e.properties)&&Yf(e.additionalProperties)}function GNs(e){return Yf(e)&&(e.type==="object"||Yf(e.properties))}const KNs=["type","properties","items","enum","const","anyOf","oneOf","allOf","$ref"];function YNs(e){return!Yf(e)||!KNs.some(t=>t in e)}function XNs(){return a.jsxs(a.Fragment,{children:[a.jsx("span",{"aria-hidden":!0,className:"ml-0.5 text-destructive-indicator",children:"*"}),a.jsx("span",{className:"sr-only",children:" (required)"})]})}function JNs({field:e}){return a.jsxs(a.Fragment,{children:[e.description,e.defaultValue!==void 0&&a.jsxs("span",{className:"block",children:["Default ",e.defaultValue]})]})}function eAs({field:e}){const t=!!e.description||e.defaultValue!==void 0;return a.jsx(Tz,{label:a.jsxs(Y,{as:"span",variant:"body-sm",font:"mono",tone:"ink",children:[e.name,e.required&&a.jsx(XNs,{})]}),description:t&&a.jsx(JNs,{field:e}),children:a.jsx(Y,{as:"span",variant:"caption",font:"mono",tone:"muted",children:e.type})})}function axe({message:e}){return a.jsx(Tz,{label:a.jsx(Y,{as:"span",variant:"body-sm",tone:"muted",children:e})})}function tAs({schema:e,emptyMessage:t,defaultsAreOptional:n}){if(YNs(e))return a.jsx(axe,{message:t});if(!GNs(e)||AQt(e))return a.jsx(Tz,{label:"Type",children:a.jsx(Y,{as:"span",variant:"caption",font:"mono",tone:"muted",children:C3(e)})});const r=HNs(e,{defaultsAreOptional:n});return r.length===0?a.jsx(axe,{message:t}):r.map(s=>a.jsx(eAs,{field:s},s.name))}function $ue({title:e,...t}){return a.jsxs(BA,{children:[a.jsx(wee,{children:a.jsx(VA,{children:e})}),a.jsx(x$,{children:a.jsx(tAs,{...t})})]})}function PQt({inputSchema:e,outputSchema:t,requestContextSchema:n,footer:r}){return a.jsxs("div",{className:"grid gap-6",children:[a.jsx($ue,{title:"Input",schema:e,emptyMessage:"This tool takes no input.",defaultsAreOptional:!0}),a.jsx($ue,{title:"Output",schema:t,emptyMessage:"No output schema defined."}),n!==void 0&&a.jsx($ue,{title:"Request context",schema:n,emptyMessage:"No request context fields.",defaultsAreOptional:!0}),r]})}function nAs({serverId:e}){const t=iPe(),{canExecute:n}=Za(),{data:r,isLoading:s}=tur({serverId:e,toolId:t});return s?a.jsx(_t.LoadingData,{}):r?a.jsx(NQt,{description:r.description,overview:a.jsx(PQt,{inputSchema:r.inputSchema}),canRun:n("tools"),playground:a.jsx(UNs,{serverId:e,tool:r})}):a.jsxs(_t.NoData,{children:['This server has no tool "',t,'".']})}const $Qt={agent:Vo,workflow:jl,tool:fd},Dnt="auto 1fr auto",rAs={tool:"Tool",agent:"Agent",workflow:"Workflow"};function sAs(e){return e in $Qt}function iAs({type:e}){const t=sAs(e)?e:"tool",n=$Qt[t],r=rAs[t];return a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsx("span",{"aria-label":t,className:"inline-flex text-muted-foreground [&>svg]:size-4",children:a.jsx(n,{})})}),a.jsx(Bn,{children:r})]})}const oAs=yr({ui:yr({resourceUri:_n().optional()}).optional(),"ui/resourceUri":_n().optional()});function aAs(e){const t=oAs.safeParse(e);return t.success?!!(t.data.ui?.resourceUri?.startsWith("ui://")||t.data["ui/resourceUri"]?.startsWith("ui://")):!1}function lAs({server:e}){const[t,n]=g.useState(""),{data:r={},isLoading:s}=YOt({selectedServer:e}),{Link:i,paths:o}=Sn(),l=g.useMemo(()=>{const d=t.toLowerCase();return Object.values(r).filter(f=>f.name.toLowerCase().includes(d)||f.description?.toLowerCase().includes(d))},[r,t]),{containerRef:c,getRowProps:u}=Fu({count:l.length});return a.jsxs("section",{className:"flex flex-col gap-3",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[a.jsx(Y,{as:"h2",variant:"heading",children:"Available tools"}),a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(pf,{onSearch:n,label:"Filter tools",placeholder:"Filter by name",shortcutDisabled:!0})})]}),s?a.jsx(Lu,{columns:Dnt}):a.jsxs(Te,{columns:Dnt,scrollRef:c,children:[a.jsxs(Te.Top,{children:[a.jsx(Te.TopCell,{children:"Name"}),a.jsx(Te.TopCell,{children:"Description"}),a.jsx(Te.TopCell,{className:"justify-center text-center",children:"Type"})]}),l.length===0&&t?a.jsx(Te.NoMatch,{message:"No tools match your search"}):null,l.map((d,f)=>a.jsxs(Te.RowLink,{to:o.mcpServerToolLink(e.id,d.name),LinkComponent:i,...u(f),children:[a.jsx(Te.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-2",children:[d.name,aAs(d._meta)&&a.jsx($t,{size:"xs",children:"App"})]})}),a.jsx(Te.DescriptionCell,{children:d.description}),a.jsx(Te.TextCell,{className:"justify-center text-center",children:a.jsx(iAs,{type:d.toolType??"tool"})})]},d.name))]})]})}const cAs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const c=window.MASTRA_SERVER_HOST,u=window.MASTRA_SERVER_PORT;let d=null;c&&u&&(d=`http://${c}:${u}`);const f=d||"http://localhost:4111",h=`${f}/api/mcp/${t.id}/sse`,p=`${f}/api/mcp/${t.id}/mcp`;s({sseUrl:h,httpStreamUrl:p})},[t]),e)return null;if(!t)return a.jsx(Y,{as:"h1",variant:"heading",tone:"muted",className:"py-20 text-center",children:"Server not found"});const i=t.transports?.includes("sse")??!0,o=`npx -y mcp-remote ${i?n:r}`,l=[{value:"http",label:"HTTP",description:"Use for stateless HTTP transport with streamable responses.",content:r,tooltip:"Copy HTTP Stream URL"},...i?[{value:"sse",label:"SSE",description:"Use for real-time communication via SSE.",content:n,tooltip:"Copy SSE URL"}]:[],{value:"cli",label:"CLI",description:"Use for local command-line access via npx and mcp-remote.",content:o,tooltip:"Copy Command Line Config"}];return a.jsxs("div",{className:"flex flex-col gap-6 pt-4",children:[a.jsx(hl,{children:a.jsxs(Hc,{defaultTab:"http",children:[a.jsxs(TQ,{className:"flex-row items-center justify-between gap-3 space-y-0 border-b border-border",children:[a.jsx(sw,{className:"shrink-0",children:"Connect"}),a.jsx("div",{className:"min-w-0",children:a.jsx(Gc,{variant:"pill-ghost",size:"sm",children:l.map(c=>a.jsx(si,{value:c.value,children:c.label},c.value))})})]}),l.map(c=>a.jsx(No,{value:c.value,flush:!0,children:a.jsxs(qm,{className:"flex flex-col gap-3",children:[a.jsx(Y,{tone:"muted",children:c.description}),a.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg bg-muted py-2 pr-2 pl-3",children:[a.jsx(Y,{as:"span",font:"mono",className:"min-w-0 break-all",children:c.content}),a.jsx(ii,{tooltip:c.tooltip,content:c.content})]})]})},c.value))]})}),a.jsx(lAs,{server:t})]})};function RQt(){const[e,t]=wi();return{toolId:e.get("tool")??void 0,close:()=>t(s=>{const i=new URLSearchParams(s);return i.delete("tool"),i},{replace:!0})}}function oPe({children:e}){const{toolId:t,close:n}=RQt();return a.jsxs(_t,{open:t!==void 0,onClose:n,title:t??"",children:[a.jsxs(_t.Header,{children:[a.jsxs(_t.Heading,{children:[a.jsx(At,{size:"sm",className:"text-muted-foreground",children:a.jsx(fd,{})}),a.jsx("span",{className:"truncate",children:t})]}),a.jsx(_t.HeaderActions,{children:a.jsx(_t.CloseButton,{icon:"x",tooltip:"Close tool",onClick:n})})]}),a.jsx(_t.Content,{className:"flex flex-col gap-4 px-3",children:t&&a.jsx(qNs,{value:t,children:e},t)})]})}const uAs=()=>{const{serverId:e}=Cr(),t=[Ts("/mcps"),Fur],{data:n=[],isLoading:r}=LP(),s=n.find(l=>l.id===e),i=s?.transports?.includes("sse")??!0,o=r||s?a.jsxs(Dc,{children:[a.jsx(Dc.Title,{isLoading:r,children:s?.name}),s&&a.jsx(Dc.Meta,{beside:!0,children:a.jsxs($t,{size:"sm",children:["v",s.version_detail.version]})}),s&&a.jsx(Dc.Description,{children:i?"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case.":"This MCP server speaks Streamable HTTP only (protocol 2026-07-28)."})]}):void 0;return a.jsxs(It,{variant:"narrow",breadcrumbs:a.jsx(Dt,{crumbs:t}),header:o,children:[a.jsx(cAs,{isLoading:r,server:s}),e&&a.jsx(oPe,{children:a.jsx(nAs,{serverId:e})})]})},UD=[Ts("/metrics")],Lnt=e=>e.fieldId===o_;function dAs({fields:e}){const{filterTokens:t,setFilterTokens:n}=Kk(),r=[k3,...T_s(t)];return a.jsxs(kl,{fields:[EW,...e],operators:O_s,value:r,onValueChange:s=>n(I_s(s.filter(i=>!Lnt(i)))),createItemId:s=>s,"aria-label":"Metrics filters",className:"min-w-64 flex-1",children:[a.jsx(kl.Chips,{renderChip:s=>Lnt(s)?a.jsx(q_s,{}):a.jsx(kl.Chip,{item:s})}),a.jsx(kl.Input,{placeholder:"Filter metrics…"})]})}function lxe({children:e,filterFields:t}){return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UD}),actionRow:a.jsx(rr,{children:a.jsx(rr.Start,{children:a.jsx(dAs,{fields:t})})}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),e]})}function fAs({error:e}){return Cs(e)?a.jsx(ci,{}):_s(e)?a.jsx(Gs,{resource:"metrics"}):a.jsx(Yt,{tone:"error",titleSlot:"Failed to load storage capabilities",descriptionSlot:e.message})}const znt=Zqt({availableTags:[],availableEntityNames:[],availableServiceNames:[],availableEnvironments:[]});function hAs({children:e}){const{supportsMetrics:t,isLoading:n,error:r}=j$();return n?a.jsx(lxe,{filterFields:znt,children:a.jsxs("div",{className:"flex h-full items-center justify-center gap-2",children:[a.jsx(On,{"aria-label":"Loading storage capabilities"}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:"Loading storage capabilities"})]})}):r?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsx(fAs,{error:r})})]}):t?e:a.jsx(lxe,{filterFields:znt,children:a.jsx(Yt,{titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:a.jsx(ce,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Metrics Documentation"}),variant:"fill"})})}function pAs(e){switch(e){case"24h":return"last-24h";case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return}}function MQt(e,t,n,r,s,i,o){if(o){e.set(t,"custom"),e.set(n,o.from.toISOString()),e.set(r,o.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),i?.from&&e.set(n,i.from.toISOString()),i?.to&&e.set(r,i.to.toISOString());return}const l=pAs(s);l&&e.set(t,l)}function rl(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function DQt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function mAs({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const i=new URLSearchParams;i.set(B1,"branches"),MQt(i,V1,w1,S1,e,t,r.window);const o=r.rootEntityType??n.rootEntityType;o&&i.set(S$,o),r.status&&i.set(k$,r.status),rl(i,yl.entityName,r.entityName??n.entityName),rl(i,yl.threadId,r.threadId??n.threadId),rl(i,yl.resourceId,r.resourceId??n.resourceId),rl(i,yl.runId,n.runId),rl(i,yl.sessionId,n.sessionId),rl(i,yl.requestId,n.requestId),rl(i,yl.userId,n.userId),rl(i,yl.organizationId,n.organizationId),rl(i,yl.experimentId,n.experimentId),rl(i,yl.serviceName,n.serviceName),rl(i,yl.environment,n.environment),DQt(i,yl.tags,n.tags);const l=i.toString();return l?`${s}?${l}`:s}function gAs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const i=new URLSearchParams;MQt(i,Hb,Gb,Kb,e,t,r.window);const o=r.rootEntityType??n.rootEntityType;o&&i.set(U0,o),rl(i,Ll.entityName,r.entityName??n.entityName),rl(i,Ll.threadId,r.threadId??n.threadId),rl(i,Ll.resourceId,r.resourceId??n.resourceId),rl(i,Ll.runId,n.runId),rl(i,Ll.sessionId,n.sessionId),rl(i,Ll.requestId,n.requestId),rl(i,Ll.userId,n.userId),rl(i,Ll.organizationId,n.organizationId),rl(i,Ll.experimentId,n.experimentId),rl(i,Ll.serviceName,n.serviceName),rl(i,Ll.environment,n.environment),DQt(i,Ll.tags,n.tags),r.status==="error"&&i.append(Ll.level,"error");const l=i.toString();return l?`${s}?${l}`:s}function vAs(){const{datePreset:e,customRange:t,dimensionalFilter:n}=Kk(),r=Lr(),s={preset:e,customRange:t,dashboardFilter:n};return{openTraces:(l={})=>{r(mAs({...s,scope:l}))},openLogs:(l={})=>{r(gAs({...s,scope:l}))}}}const Rue="period",eB="dateFrom",tB="dateTo";function yAs(){const[e,t]=wi(),n=e.get(Rue),r=D_s(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=p=>{if(!p)return;const m=new Date(p);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(eB)),h=d(e.get(tB));if(!(!f&&!h))return{from:f,to:h}},[r,e.toString()]),i=g.useMemo(()=>E_s(e),[e.toString()]),o=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d==="24h"?h.delete(Rue):h.set(Rue,d),d!=="custom"&&(h.delete(eB),h.delete(tB)),h},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d?.from?h.set(eB,d.from.toISOString()):h.delete(eB),d?.to?h.set(tB,d.to.toISOString()):h.delete(tB),h},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return A_s(h,d),w_s(h),h},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,k_s(e)))return;const d=S_s();d&&t(f=>{const h=new URLSearchParams(f);for(const[p,m]of d)h.append(p,m);return h},{replace:!0})},[]),a.jsx(F_s,{preset:r,filterTokens:i,onPresetChange:o,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:a.jsx(hAs,{children:a.jsx(xAs,{})})})}function xAs(){const{error:e}=Xqt(mf()),{isInMemory:t}=j$(),{data:n}=KBt(),{data:r}=LNe(),{data:s}=GBt(),{data:i}=zNe(),o=Zqt({availableTags:n??[],availableEntityNames:r??[],availableServiceNames:s??[],availableEnvironments:i??[]});return e&&Cs(e)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(ci,{variant:"fill"})]}):e&&_s(e)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(Gs,{variant:"fill",resource:"metrics"})]}):e?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(Yt,{tone:"error",variant:"fill",titleSlot:"Failed to load metrics",descriptionSlot:e.message})]}):a.jsx(lxe,{filterFields:o,children:a.jsxs("div",{className:"grid content-start gap-4",children:[t&&a.jsx(Wt,{variant:"info",title:"Metrics are not persisted",children:a.jsx(Wt.Message,{children:"This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner."})}),a.jsx(bAs,{})]})})}function bAs(){const{openTraces:e,openLogs:t}=vAs(),n=od.AGENT;return a.jsxs("div",{className:"grid content-start gap-4 pb-6",children:[a.jsx(xTs,{}),a.jsx(XTs,{onViewTraces:()=>e(),onTimeRangeClick:r=>e({window:r})}),a.jsxs(f1,{columns:3,children:[a.jsx(f1.Item,{children:a.jsx(eIs,{onTimeRangeClick:r=>e({rootEntityType:n,window:r})})}),a.jsx(f1.Item,{children:a.jsx(aIs,{onViewErrors:()=>t({rootEntityType:n,status:"error"}),onTimeRangeClick:r=>e({rootEntityType:n,status:"error",window:r})})}),a.jsx(f1.Item,{span:2,className:"@7xl:col-span-1",children:a.jsx(pIs,{onViewTraces:r=>e({rootEntityType:r}),onTimeRangeClick:r=>e({window:r})})})]}),a.jsxs(f1,{columns:2,children:[a.jsx(f1.Item,{children:a.jsx(RIs,{onViewTraces:r=>e({rootEntityType:r}),onViewErrors:r=>t({rootEntityType:r,status:"error"}),onEntityClick:(r,s)=>e({rootEntityType:r,entityName:s})})}),a.jsx(f1.Item,{children:a.jsx(zIs,{onViewTraces:()=>e(),onAgentClick:r=>e({rootEntityType:n,entityName:r}),onModelClick:r=>e({model:r}),onThreadClick:r=>e({threadId:r})})})]}),a.jsx(WIs,{})]})}function wAs(){const{isCmsAvailable:e}=Hx(),{paths:t}=Sn();return e?a.jsx(IX,{href:t.cmsPromptBlockCreateLink(),tooltip:"Create a prompt",children:"New prompt"}):null}const FM=[Ts("/prompts")],SAs=50,kAs=["updatedAt"];function OAs(){const[e,t]=g.useState(""),[n,r]=g.useState(0),[s,i]=wi(),{sort:o,onSortChange:l}=cT({searchParams:s,setSearchParams:i,allowedKeys:kAs}),c=g.useMemo(()=>o?{field:o.key,direction:o.direction==="asc"?"ASC":"DESC"}:void 0,[o]),{data:u,isLoading:d,error:f,isPlaceholderData:h}=J7t({page:n,perPage:SAs,orderBy:c}),p=u?.promptBlocks??[],m=u?.hasMore??!1,v=g.useCallback(()=>{h||r(S=>S+1)},[h]),y=g.useCallback(()=>{h||r(S=>Math.max(0,S-1))},[h]),x=g.useCallback(S=>{t(S),r(0)},[]),b=g.useCallback((S,k)=>{l(S,k),r(0)},[l]);return f&&Cs(f)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:FM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(ci,{variant:"fill"})]}):f&&_s(f)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:FM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(Gs,{variant:"fill",resource:"prompt blocks"})]}):f?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:FM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(Yt,{tone:"error",variant:"fill",titleSlot:"Failed to load prompt blocks",descriptionSlot:f.message})]}):p.length===0&&!d&&n===0?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:FM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(Ems,{})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:FM}),headerActions:a.jsx(wAs,{}),actionRow:a.jsx(rr,{children:a.jsx(rr.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(pf,{onSearch:x,label:"Filter prompts",placeholder:"Filter by name or description"})})})}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(Ims,{promptBlocks:p,isLoading:d,search:e,currentPage:n,hasMore:m,onNextPage:v,onPrevPage:y,updatedSort:o?.direction,onSortChange:b})]})}const jAs=[Ts("/resources")],CAs=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:NTn,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:Zht,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Zs,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:hL,href:"https://discord.gg/mastra-ai",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:uwe,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:lwe,href:"https://mastra.ai/contact?ref=studio",external:!0}];function _As(){return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:jAs}),children:[a.jsx("h1",{className:"sr-only",children:"Resources"}),a.jsx("div",{children:a.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:CAs.map(e=>a.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group state-layer flex flex-col gap-3 rounded-lg border border-border bg-background p-5 hover:border-border-strong",children:[a.jsxs("div",{className:"flex items-center gap-2.5",children:[a.jsx(e.icon,{className:Z("h-5 w-5 text-muted-foreground group-hover:text-info-indicator",In)}),a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",children:e.title}),e.external&&a.jsx(Zs,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})]}),a.jsx(Y,{variant:"caption",tone:"muted",children:e.description})]},e.href))})})]})}function Fnt(){const{isCmsAvailable:e}=Hx(),{paths:t}=Sn();return e?a.jsx(IX,{href:t.cmsScorersCreateLink(),tooltip:"Create a scorer",children:"New scorer"}):null}const BM=[Ts("/scorers")];function TAs(){const{data:e={},isLoading:t,error:n}=Bx(),[r,s]=g.useState(""),[i,o]=g.useState("all"),[l,c]=g.useState();if(n&&Cs(n))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(ci,{variant:"fill"})]});if(n&&_s(n))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Gs,{variant:"fill",resource:"scorers"})]});if(n)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Yt,{tone:"error",variant:"fill",titleSlot:"Failed to load scorers",descriptionSlot:n.message})]});if(Object.keys(e).length===0&&!t)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BM}),headerActions:a.jsx(Fnt,{}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(bfs,{})]});const u=i!=="all"||r!=="",d=()=>{s(""),o("all")};return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BM}),headerActions:a.jsx(Fnt,{}),actionRow:a.jsx(Sfs,{search:r,onSearchChange:s,sourceFilter:i,onSourceFilterChange:o,onReset:d,hasActiveFilters:u}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(xfs,{scorers:e,isLoading:t,search:r,sourceFilter:i,sort:l,onSortChange:(f,h)=>c({key:h,direction:f})})]})}const LQt=["input","entity"],IAs={input:"Input",entity:"Entity"};function EAs(e){const t=["auto","auto","minmax(0, 10rem)"];return e.has("entity")&&t.push("minmax(0, 14rem)"),e.has("input")&&t.push("minmax(0, 40rem)"),t.join(" ")}function NAs(){const[e,t]=g.useState(new Set),n=g.useMemo(()=>new Set(LQt.filter(i=>!e.has(i))),[e]),r=g.useMemo(()=>EAs(n),[n]),s=g.useCallback(i=>{t(o=>{const l=new Set(o);return l.has(i)?l.delete(i):l.add(i),l})},[]);return{visibleColumns:n,columns:r,toggleColumn:s}}function AAs({visibleColumns:e,toggleColumn:t}){return a.jsxs(lt,{children:[a.jsx(lt.Trigger,{asChild:!0,children:a.jsx(ce,{icon:a.jsx(tpt,{}),children:"Columns"})}),a.jsxs(lt.Content,{align:"end",children:[a.jsx(lt.Label,{children:"Toggle columns"}),LQt.map(n=>a.jsx(lt.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:IAs[n]},n))]})]})}const Bnt=[Ts("/scorers"),Lur],PAs=["date","score"];function $As(){const{scorerId:e}=Cr(),[t,n]=wi(),r=t.get("scoreId")??void 0,[s,i]=g.useState(r),[o,l]=g.useState(!1),c=Lr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:h}=xur(e),p=NAs(),{data:m={},isLoading:v,error:y}=Cp(),{isLoading:x,error:b}=tg({}),{sort:S,onSortChange:k}=cT({searchParams:t,setSearchParams:n,allowedKeys:PAs}),{data:j=[],isLoading:C,error:T,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:E}=yur({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),A=g.useMemo(()=>qk(j,S,{date:X=>X.createdAt,score:X=>typeof X.score=="number"?X.score:void 0}),[j,S]),P=g.useMemo(()=>f?.agentIds?.filter(X=>m[X]).map(X=>({value:X,label:m[X].name,type:"AGENT"}))||[],[f?.agentIds,m]),L=g.useMemo(()=>f?.workflowIds?.map(X=>({value:X,label:X,type:"WORKFLOW"}))||[],[f?.workflowIds]),F=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...P,...L],[P,L]),Q=t.get("entity")??"all",q=F.find(X=>X.value===Q);q&&q.value!==u?.value&&d(q),g.useEffect(()=>{if(h){const X=h instanceof Error?h.message:"Failed to load scorer";Xe.error(`Error loading scorer: ${X}`)}},[h]),g.useEffect(()=>{if(y){const X=y instanceof Error?y.message:"Failed to load agents";Xe.error(`Error loading agents: ${X}`)}},[y]),g.useEffect(()=>{if(b){const X=b instanceof Error?b.message:"Failed to load workflows";Xe.error(`Error loading workflows: ${X}`)}},[b]);const B=X=>{X?.value&&n(ee=>{const re=new URLSearchParams(ee);return re.set("entity",X.value),re})};g.useEffect(()=>{const X=t.get("scoreId")??void 0;if(X===s)return;if(!X){i(void 0);return}A.find(re=>re.id===X)&&i(X)},[t,A]);const V=g.useCallback(X=>{i(X||void 0),n(ee=>{const re=new URLSearchParams(ee);return X?re.set("scoreId",X):re.delete("scoreId"),re})},[n]);if(!f)return null;const W=Cs(h)||Cs(y)||Cs(b),M=h&&_s(h),K=!W&&!M&&(h||y||b),D=!C&&A.length===0,$=u?.value!=="all",z=f?.source==="stored",U=e?a.jsx(cee,{open:o,onOpenChange:l,initialScorerIds:[e],onSuccess:X=>{c(`/experiments/${X}`)}}):null,G=z?a.jsxs(lt,{children:[a.jsx(lt.Trigger,{asChild:!0,children:a.jsx(ce,{size:"lg","aria-label":"Scorer actions menu",children:a.jsx(W0,{})})}),a.jsx(lt.Content,{align:"end",className:"w-48",children:a.jsxs(lt.Item,{onSelect:()=>{c(`/cms/scorers/${e}/edit`)},children:[a.jsx(Vc,{})," Edit Scorer"]})})]}):null;if(W||M||K||D&&!$){const X=(h instanceof Error?h.message:void 0)??(y instanceof Error?y.message:void 0)??(b instanceof Error?b.message:void 0)??"An unexpected error occurred",ee=W||M||K;return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Bnt}),actionRow:!ee&&G?a.jsx(rr,{children:a.jsx(rr.End,{children:G})}):void 0,children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:"flex h-full items-center justify-center",children:W?a.jsx(ci,{}):M?a.jsx(Gs,{resource:"scorers"}):K?a.jsx(Yt,{tone:"error",titleSlot:"Failed to load scorer",descriptionSlot:X}):a.jsx(sfs,{onRunExperiment:()=>l(!0)})}),U]})}return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Bnt}),actionRow:a.jsxs(rr,{children:[a.jsx(rr.Start,{children:a.jsx(vfs,{selectedEntity:u,entityOptions:F,onEntityChange:B,onReset:()=>{n(X=>{const ee=new URLSearchParams(X);return ee.set("entity","all"),ee})},isLoading:C||v||x})}),a.jsxs(rr.End,{children:[a.jsx(AAs,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),a.jsx(ce,{variant:"primary",onClick:()=>l(!0),icon:a.jsx(Dr,{}),children:"New experiment"}),G]})]}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(rfs,{scores:A,isLoading:C,selectedScoreId:s,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:E,onScoreClick:V,errorMsg:T?.message,columnsState:p,sort:S,onSortChange:k}),U]})}const zQt=g.createContext(void 0);function RAs({value:e,onValueChange:t,"aria-label":n,size:r="md",iconOnly:s=!1,className:i,children:o,...l}){const c=g.useRef(new Map),u=g.useRef(null),d={iconOnly:s,registerItem:(h,p)=>c.current.set(h,p),unregisterItem:h=>c.current.delete(h)},f=h=>typeof h=="string"&&c.current.has(h);return g.useLayoutEffect(()=>{const h=u.current,p=c.current.get(e);if(!h)return;if(!p){h.hidden=!0;return}const m=()=>{h.style.width=`${p.offsetWidth}px`,h.style.transform=`translateX(${p.offsetLeft}px)`};m();let v;h.hidden&&(h.hidden=!1,v=requestAnimationFrame(()=>h.setAttribute("data-ready","")));const y=typeof ResizeObserver>"u"?void 0:new ResizeObserver(m);return c.current.forEach(x=>y?.observe(x)),()=>{v!==void 0&&cancelAnimationFrame(v),y?.disconnect()}},[e,o]),a.jsx(zQt.Provider,{value:d,children:a.jsxs(c3t,{...l,value:e,onValueChange:h=>{f(h)&&t(h)},"aria-label":n,...Mx({"aria-label":n,"aria-labelledby":l["aria-labelledby"]}),"data-slot":"segmented-control","data-size":r,className:Z(pr,"relative inline-flex w-fit shrink-0 items-stretch rounded-full p-0.5",s&&"gap-0.5",tp[r],"data-[disabled]:opacity-50",i),children:[a.jsx("span",{ref:u,hidden:!0,"aria-hidden":"true","data-slot":"segmented-control-thumb",className:Z("pointer-events-none absolute inset-y-0.5 left-0 rounded-full bg-fill-hover ring-1 ring-border ring-inset","motion-safe:data-[ready]:transition-[transform,width] motion-safe:data-[ready]:duration-normal motion-safe:data-[ready]:ease-out-custom")}),o]})})}function MAs({value:e,disabled:t,className:n,children:r,ref:s,...i}){const o=g.useContext(zQt);if(!o)throw new Error("SegmentedControlItem must be used inside a SegmentedControl");const{iconOnly:l,registerItem:c,unregisterItem:u}=o,d=Sk(s,f=>(f&&c(e,f),()=>u(e)));return a.jsx(l3t,{...i,render:a.jsx("span",{"aria-labelledby":i["aria-labelledby"]}),ref:d,value:e,disabled:t,"data-slot":"segmented-control-item",className:Z("relative inline-flex cursor-pointer items-center justify-center gap-1.5 rounded-full text-label whitespace-nowrap select-none",l?"aspect-square":"px-3",t&&"opacity-50","[&_svg]:size-3.5 [&_svg]:shrink-0","text-muted-foreground hover:text-foreground data-[checked]:text-foreground","focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-border-focus","data-[disabled]:cursor-not-allowed data-[disabled]:hover:text-muted-foreground",In,n),children:r})}const DAs=[{value:"system",label:"System",icon:a.jsx(gpt,{})},{value:"light",label:"Light",icon:a.jsx(iAn,{})},{value:"dark",label:"Dark",icon:a.jsx(CEn,{})}];function LAs(e,t){if(e.some(r=>r.value===t))return t;const[n]=e;return n?n.value:"system"}const zAs=({value:e,onChange:t,options:n=DAs,size:r="md","aria-label":s="Theme",...i})=>{const{theme:o,setTheme:l}=ySe(),c=e??o,u=t??l,d=LAs(n,c);return a.jsx(RAs,{...i,"aria-label":s,iconOnly:!0,size:r==="xs"?"sm":r,value:d,onValueChange:u,children:n.map(f=>a.jsx(MAs,{value:f.value,"aria-label":f.label,children:f.icon},f.value))})},FAs=[Ts("/settings")],BAs=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=gL();return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:FAs}),children:[a.jsx("h1",{className:"sr-only",children:"Settings"}),a.jsx(qfs,{children:a.jsxs("div",{className:"mx-auto flex max-w-4xl flex-col gap-8",children:[a.jsxs(BA,{children:[a.jsxs(hye,{children:[a.jsx(VA,{children:"General"}),a.jsx(rJe,{children:"Stored in this browser."})]}),a.jsx(x$,{children:a.jsx(Tz,{label:"Theme",description:"Customize the appearance of the studio.",children:a.jsx(zAs,{})})})]}),a.jsxs(BA,{children:[a.jsxs(hye,{children:[a.jsx(VA,{children:"Mastra Connection"}),a.jsx(rJe,{children:"Configure the Mastra instance URL, API prefix, and request headers used by the studio."})]}),a.jsx(O7t,{variant:"factory",initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})]})]})})]})};function VAs(){const[e]=wi(),t=Lr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return a.jsx(kQt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}async function FQt(){const e=await fetch("https://mastra.ai/api/templates.json");if(!e.ok)throw new Error(`Failed to fetch templates: ${e.statusText}`);const t=[{title:"Weather Agent",slug:"weather-agent",githubUrl:"https://github.com/mastra-ai/weather-agent",description:"Get weather information of any city.",longDescription:"One Agent, one Workflow and one Tool to bring you the weather in your city.",imageURL:"",tags:["Agent","Workflow","Tool"],useCase:"",supportedProviders:["openai","anthropic","google","groq"],agents:["weatherAgent"],tools:["weatherTool"],workflows:["weatherWorkflow"]},...await e.json()];return{templates:t,tags:Array.from(new Set(t.flatMap(n=>n.tags))),providers:Array.from(new Set(t.flatMap(n=>n.supportedProviders)))}}async function UAs({repo:e,owner:t}){const n=await fetch(`https://api.github.com/repos/${t}/${e}`);if(!n.ok)throw new Error(`Failed to fetch template: ${n.statusText}`);const r=await n.json();if(!r.is_template)throw new Error("Repo is not a template, please update the repo settings to make it a template");return{title:r.name,slug:r.name,description:r.description??"",imageURL:"",tags:[],useCase:"",longDescription:r.description??"",githubUrl:r.html_url,supportedProviders:[]}}async function qAs({repoOrSlug:e,owner:t}){const{templates:n}=await FQt(),r=n.find(s=>s.slug===e);if(!r){if(e.startsWith("template-")){const i=n.find(o=>`template-${o.slug}`===e);if(i)return i}const s=await UAs({repo:e,owner:t});if(s)return s;throw new Error(`Template ${e} not found`)}return r}async function QAs({repo:e,owner:t,branch:n}){const r=`https://raw.githubusercontent.com/${t}/${e}/${n}/.env.example`,s=await fetch(r);return s.ok?(await s.text()).split(`
699
- `).reduce((i,o)=>{if(!o||o.startsWith("#"))return i;const[l,c]=o.split("=");return l&&(i[l]=c?.split("")?.every(u=>u==="*")?"":c?.replaceAll('"',"")),i},{}):{}}const ZAs=({queryOptions:e}={})=>Ct({queryKey:["mastra-templates"],queryFn:FQt,...e}),WAs=({repoOrSlug:e,owner:t,queryOptions:n})=>Ct({queryKey:["template-repo",e,t],queryFn:()=>qAs({repoOrSlug:e,owner:t}),...n}),HAs=({repo:e,owner:t,branch:n,queryOptions:r})=>Ct({queryKey:["template-repo-env-vars",e,t,n],queryFn:()=>QAs({repo:e,owner:t,branch:n}),...r}),GAs=({queryOptions:e}={})=>{const t=Ke();return Ct({queryKey:["agent-builder-workflow"],queryFn:async()=>await t.getAgentBuilderAction("merge-template").details(),...e})},KAs=({queryOptions:e}={})=>{const t=Ke();return wn({mutationFn:async({runId:n})=>await t.getAgentBuilderAction("merge-template").createRun({runId:n}),...e})},YAs=({queryOptions:e}={})=>{const t=Ke();return wn({mutationFn:async({runId:n})=>await t.getAgentBuilderAction("merge-template").runById(n),...e})},Vnt=e=>{if(typeof e=="string")return e;if(e==null)return"Unknown error";if(e instanceof Error)return typeof e.message=="string"&&e.message.length>0?e.message:"Unknown error";if(typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e)},Unt=(e,t,n)=>{let r={...t};if(!(r.payload?.workflowState?.steps&&Object.keys(r.payload.workflowState.steps).length>0)&&n?.allSteps&&(r.payload={...r.payload,workflowState:{...r.payload?.workflowState,steps:Object.keys(n.allSteps).reduce((s,i)=>(s[i]={id:i,description:n.allSteps[i].description,status:"pending"},s),{})}}),e.type==="start"||e.type==="workflow-start"){const s={};n?.allSteps&&Object.entries(n.allSteps).forEach(([o,l])=>{s[o]={id:l.id,description:l.description,status:"pending"}});const i=e.runId||e.payload?.runId;r={...r,runId:i,eventTimestamp:new Date().toISOString(),status:"running",phase:"initializing",payload:{workflowState:{status:"running",steps:s},currentStep:null}}}if(e.type==="step-start"||e.type==="workflow-step-start"){const s=e.payload.id;r={...r,phase:"processing",payload:{...r.payload,currentStep:{id:s,status:"running",startTime:new Date,...e.payload},workflowState:{...r.payload.workflowState,steps:{...r.payload.workflowState.steps,[s]:{...r.payload.workflowState.steps[s],status:"running",startTime:new Date,...e.payload}}}}}}if(e.type==="step-result"||e.type==="workflow-step-result"){const s=e.payload.id,i=e.payload.status,o=e.payload.error;if(r={...r,payload:{...r.payload,currentStep:{...r.payload.currentStep,status:e.payload.status,output:e.payload.output,error:e.payload.error,endTime:new Date},workflowState:{...r.payload.workflowState,steps:{...r.payload.workflowState.steps,[s]:{...r.payload.workflowState.steps[s],status:e.payload.status,output:e.payload.output,error:e.payload.error,endTime:new Date}}}}},i==="failed"&&o){const l=Vnt(o);r={...r,status:"failed",error:l,phase:"error",failedStep:{id:s,error:l,description:e.payload.description||s},payload:{...r.payload,workflowState:{...r.payload.workflowState,status:"failed"}},errorTimestamp:new Date}}}if((e.type==="step-finish"||e.type==="workflow-step-finish")&&(r={...r,payload:{...r.payload,currentStep:null}}),(e.type==="finish"||e.type==="workflow-finish")&&(r.phase==="error"||r.status==="failed"?r={...r,completedAt:new Date}:r={...r,status:e.payload.status||"completed",phase:"completed",payload:{...r.payload,currentStep:null,workflowState:{...r.payload.workflowState,status:e.payload.status||"completed"}},completedAt:new Date}),e.type==="error"){const s=Vnt(e.payload.error);r={...r,status:"failed",error:s,phase:"error",payload:{...r.payload,workflowState:{...r.payload.workflowState,status:"failed"}},errorTimestamp:new Date}}return{newState:r}},XAs=(e,t)=>{try{localStorage.setItem(`template-install-${e}`,JSON.stringify({state:t,timestamp:Date.now()}))}catch(n){console.warn("Failed to save template state to localStorage:",n)}},BQt=(e,t)=>{const[n,r]=g.useState({}),[s,i]=g.useState(!1);return{streamResult:n,isStreaming:s,processStream:async(l,c)=>{if(i(!0),r({}),!l)throw new Error("No stream returned");const u=l.getReader();let d={runId:c||t,eventTimestamp:new Date().toISOString(),phase:"running",payload:{workflowState:{steps:{}},currentStep:null}};try{for(;;){const{done:f,value:h}=await u.read();if(f)break;const{newState:p}=Unt(h,d,e);if(d=p,r(p),h.runId||c||t){const m=h.runId||c||t;XAs(m,p)}}}catch(f){console.error("💥 [processStream] Error processing template installation stream:",f);const{newState:h}=Unt({type:"error",payload:{error:f instanceof Error?f.message:"Unknown error"}},d,e);r(h)}finally{i(!1),u.releaseLock()}}}},JAs=({workflowInfo:e,queryOptions:t}={})=>{const n=Ke(),{streamResult:r,isStreaming:s,processStream:i}=BQt(e);return{streamInstall:wn({mutationFn:async({inputData:o,selectedModel:l,runId:c})=>{for(let d=1;d<=3;d++)try{const f=n.getAgentBuilderAction("merge-template"),h=new f_;h.set("selectedModel",l);const p=await f.stream({inputData:o,requestContext:h},c);await i(p,c);return}catch(f){console.error(`💥 [streamInstall] Attempt ${d} failed:`,f);const h=f?.message?.includes("Failed to fetch")||f?.message?.includes("NetworkError")||f?.message?.includes("network error")||f?.message?.includes("fetch")||f?.code==="NETWORK_ERROR"||f?.name==="TypeError";if(console.warn(`Stream attempt ${d}/3 failed:`,f),h){const p=c?`Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${c}`:"Network error during template installation (likely hot reload). Please try again.";throw console.error("🔌 Stream network error:",p),new Error(p)}throw console.error("❌ [streamInstall] Non-network error or max retries reached, throwing:",f),f}},...t?.streamInstall}),streamResult:r,isStreaming:s}},ePs=({workflowInfo:e,queryOptions:t}={})=>{const n=Ke(),{streamResult:r,isStreaming:s,processStream:i}=BQt(e);return{observeInstall:wn({mutationFn:async({runId:o})=>{for(let u=1;u<=3;u++)try{const d=await n.getAgentBuilderAction("merge-template").observeStream({runId:o});await i(d,o);return}catch(d){console.error(`💥 [observeInstall] Attempt ${u} failed:`,d);const f=d?.message?.includes("Failed to fetch")||d?.message?.includes("NetworkError")||d?.message?.includes("network error")||d?.message?.includes("fetch")||d?.code==="NETWORK_ERROR"||d?.name==="TypeError";if(console.warn(`ObserveStream attempt ${u}/3 failed:`,d),f&&u<3){console.info(`🔄 ObserveStream network error detected (likely hot reload), retrying in 2000ms... (attempt ${u+1}/3)`),await new Promise(h=>setTimeout(h,2e3));continue}throw console.error("❌ [observeInstall] Non-network error or max retries reached, throwing:",d),d}},...t?.observeInstall}),streamResult:r,isStreaming:s}};function tPs(e){return e.replace(/\/$/,"").split("/").pop()}function nPs({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?a.jsx("div",{className:Z("grid gap-y-4",n),children:Array.from({length:5}).map((i,o)=>a.jsx("div",{className:"h-16 animate-pulse rounded-lg bg-card"},o))}):a.jsx("div",{className:Z("grid gap-y-4",n),children:e.map(i=>{const o=i?.agents||i?.tools||i?.networks||i?.workflows||i?.mcp;return a.jsxs("article",{className:Z(pr,"state-layer grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg"),children:[a.jsxs(s,{to:`/templates/${i.slug}`,className:Z("group grid",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":i.imageURL}),children:[i.imageURL&&a.jsx("div",{className:"overflow-hidden",children:a.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${i.imageURL})`}})}),a.jsxs("div",{className:Z("grid w-full gap-0.5 px-4 py-3","[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground"),children:[a.jsx(Y,{as:"h2",tone:"ink",children:i.title}),a.jsx(Y,{className:Z(xx,In),children:i.description}),a.jsxs("div",{className:"mt-3 hidden flex-wrap items-center gap-4 text-muted-foreground 2xl:flex",children:[o&&a.jsxs("ul",{className:Z("text-muted-foreground","m-0 flex list-none gap-4 p-0","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5"),children:[i?.agents&&i.agents.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(Vo,{})," ",i.agents.length]})}),i?.tools&&i.tools.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(fd,{})," ",i.tools.length]})}),i?.networks&&i.networks.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(vpt,{})," ",i.networks.length]})}),i?.workflows&&i.workflows.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(wk,{})," ",i.workflows.length]})}),i?.mcp&&i.mcp.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(F_,{})," ",i.mcp.length]})})]}),o&&i.supportedProviders&&a.jsx("small",{children:a.jsx(Y,{as:"span",variant:"body",children:"|"})}),a.jsx("div",{className:"flex items-center gap-4",children:i.supportedProviders.map(l=>a.jsx(Y,{tone:"muted",as:"span",variant:"body",children:l},l))})]})]})]}),a.jsx("a",{href:i.githubUrl,className:Z("group ml-auto hidden items-center gap-2 pr-4","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:a.jsx(Y,{as:"span",variant:"body",children:a.jsxs("span",{className:Z("flex items-center gap-2 rounded bg-sidebar px-2 py-1",Eht,xx,In),children:[a.jsx(TX,{})," ",tPs(i.githubUrl)]})})})]},i.slug)})})}function rPs({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:i,searchTerm:o,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?a.jsxs("div",{className:Z("flex h-[6.5rem] items-center gap-5","[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card",u),children:[a.jsx("div",{})," ",a.jsx("div",{})," ",a.jsx("div",{})]}):a.jsxs("div",{className:Z("sticky top-0 mx-auto flex flex-wrap gap-4 bg-background py-5",u),children:[a.jsx(Zc,{label:"Search templates",placeholder:"Search Template",value:o,onValueChange:l}),a.jsxs(ms,{value:t,onValueChange:s,children:[a.jsx(vs,{"aria-label":"Filter by tag",size:"md",children:a.jsx(gs,{placeholder:"Select an option"})}),a.jsx(ys,{children:e.map(f=>a.jsx(hr,{value:f.value,children:f.label},f.value))})]}),a.jsxs(ms,{value:r,onValueChange:i,children:[a.jsx(vs,{"aria-label":"Filter by provider",size:"md",children:a.jsx(gs,{placeholder:"Select an option"})}),a.jsx(ys,{children:n.map(f=>a.jsx(hr,{value:f.value,children:f.label},f.value))})]}),c&&a.jsx(ce,{onClick:c,icon:a.jsx(Mn,{}),children:"Reset"})]})}const sPs=[{id:"templates",label:"Templates"}];function iPs(){const{data:e,isLoading:t}=ZAs(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[i,o]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(b=>{f.push({value:b,label:b})});const h=[{value:"all",label:"Any provider"}];(s||[]).forEach(b=>{h.push({value:b,label:b})});const p=(b,S)=>{S==="tag"?o(b):S==="provider"&&c(b)},m=b=>{d(b)},v=()=>{o("all"),c("all"),d("")},y=n.filter(b=>!(u&&!b.title.toLowerCase().includes(u)&&!b.description.toLowerCase().includes(u)||i!=="all"&&!b.tags.includes(i)||l!=="all"&&!b.supportedProviders.includes(l))),x=u||i!=="all"||l!=="all";return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:sPs}),children:[a.jsx("h1",{className:"sr-only",children:"Templates"}),a.jsx(vL,{children:a.jsxs(Mpt,{children:[a.jsx(At,{children:a.jsx(X1,{})}),"Templates"]})}),a.jsxs("div",{className:Z("z-10 h-full w-full overflow-y-auto px-5 pb-12"),children:[a.jsx(rPs,{selectedTag:i,onTagChange:b=>p(b,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:b=>p(b,"provider"),providerOptions:h,searchTerm:u,onSearchChange:m,onReset:x?v:void 0,className:"max-w-[80rem]",isLoading:t}),a.jsx(nPs,{templates:y,linkComponent:lc,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const oPs="1.78.0-alpha.6";function See({children:e,className:t}){return a.jsx("div",{className:Z("transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12",t),children:e})}function aPs({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,i=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",o=()=>s?{icon:a.jsx(Xd,{className:"text-warning-foreground"}),title:"Template Installed with Warnings"}:{icon:a.jsx(qTn,{}),title:"Template Installation Failed"},{icon:l,title:c}=o();return a.jsxs(See,{className:"mb-5 content-center space-y-4 text-muted-foreground",children:[a.jsxs("div",{className:"grid content-center items-center justify-items-center gap-4 [&>svg]:h-8 [&>svg]:w-8",children:[l,a.jsxs("div",{className:"space-y-2 text-center",children:[a.jsx(Y,{variant:"subheading",tone:"ink",children:c}),a.jsx(Y,{tone:"muted",children:i()})]})]}),t&&t.length>0&&a.jsxs("details",{children:[a.jsx("summary",{className:Z(Zn,"cursor-pointer text-center select-none"),children:a.jsxs(Y,{as:"span",variant:"caption",className:"block",children:["Show Validation Issues (",t.length,")"]})}),a.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-muted p-3 text-left",children:t.map((u,d)=>a.jsxs("div",{className:"border-l-2 border-destructive-indicator pl-2",children:[a.jsx(Y,{as:"p",variant:"column",className:"text-destructive-foreground",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),a.jsx(Cl,{className:"mt-1 text-caption wrap-break-word whitespace-pre-wrap text-muted-foreground",code:u.message})]},d))})]}),n&&!s&&a.jsxs("details",{children:[a.jsx("summary",{className:Z(Zn,"cursor-pointer text-center select-none"),children:a.jsx(Y,{as:"span",variant:"caption",className:"block",children:"Show Details"})}),a.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-muted p-3 text-left",children:a.jsx(Cl,{className:"text-caption wrap-break-word whitespace-pre-wrap",code:n})})]})]})}const lPs=g.createContext(null);function cPs(){const e=g.useContext(lPs);return e||{registerResetFn:()=>{},triggerReset:()=>{}}}const VQt=({defaultProvider:e,defaultModel:t,updateModel:n,resetModel:r})=>{const[s]=g.useState(e),[i]=g.useState(t),[o,l]=g.useState(t),[c,u]=g.useState(e||""),[d,f]=g.useState(!1),[h,p]=g.useState(!1),[m,v]=g.useState(!1),{data:y,isLoading:x}=R6(),b=Y0(),{models:S}=fw(),k=g.useMemo(()=>y?.providers||[],[y]);g.useEffect(()=>{l(t),u(e||"")},[t,e]);const j=io(c),T=KE(k,j)?.id||j,_=async F=>{if(l(F),F&&T){f(!0);try{const Q=await n({provider:T,modelId:F});console.info("Model updated:",Q)}catch(Q){console.error("Failed to update model:",Q)}finally{f(!1)}}},N=F=>{const Q=io(F);u(Q),Q!==j&&(l(""),v(!0))},{registerResetFn:E}=cPs();if(g.useEffect(()=>(E(()=>{if(h||m)return;if(j&&j!==s&&(!o||o==="")){u(io(s)),l(i);const V=KE(k,s)?.id||s;V&&i&&n({provider:V,modelId:i}).catch(W=>{console.error("Failed to reset model:",W)})}}),()=>{E(null)}),[E,j,o,s,i,n,h,m,k]),x)return a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(On,{}),a.jsx(Y,{as:"span",tone:"muted",children:"Loading providers..."})]});const A=async()=>{if(!r){console.warn("Reset model function not provided");return}try{f(!0),await r()}catch(F){console.error("Failed to reset model:",F)}finally{f(!1)}},P=KE(k,j);if(b.active&&b.pickerVisible===!1){const F=b.default&&b.default.provider&&b.default.modelId?`${b.default.provider}/${b.default.modelId}`:c&&o?`${c}/${o}`:"Locked by admin";return a.jsxs("div",{className:Z(pr,"flex items-center gap-2 rounded-md px-3 py-2"),"data-testid":"agent-metadata-model-locked",children:[a.jsx(Nu,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"caption",tone:"ink",className:"truncate",children:F}),a.jsx(Y,{as:"span",variant:"meta",tone:"muted",className:"ml-auto shrink-0",children:"Set by admin"})]})}const L=!!(j&&o)&&b.active&&b.allowed!==void 0&&!S.some(F=>io(F.provider)===j&&F.model===o);return a.jsxs("div",{className:"@container",children:[a.jsxs("div",{className:"flex w-full flex-col items-stretch gap-2 @xs:flex-row @xs:items-center",children:[a.jsx("div",{className:"w-full @xs:w-2/5",children:a.jsx(zk,{value:j,onValueChange:N,open:h,onOpenChange:p})}),a.jsx("div",{className:"w-full @xs:w-3/5",children:a.jsx(Fk,{llmId:j,value:o,onValueChange:_,open:m,onOpenChange:v})}),a.jsx(ce,{variant:"default",size:"md",onClick:A,disabled:d,className:"flex items-center gap-1.5 border-0! whitespace-nowrap",title:"Reset to original model",children:a.jsx(E_,{className:"h-3.5 w-3.5"})})]}),L&&a.jsx("div",{className:"p-2 pt-2","data-testid":"agent-metadata-model-stale-warning",children:a.jsx(Wt,{variant:"warning",title:"Model not allowed",children:a.jsxs(Wt.Message,{children:[a.jsxs("code",{className:"rounded bg-fill-hover px-1 py-0.5",children:[c,"/",o]})," ","is no longer allowed by the admin policy. Pick a different model to save changes."]})})}),P&&!P.connected&&a.jsx("div",{className:"p-2 pt-2",children:a.jsx(Wt,{variant:"warning",title:"Provider not connected",children:a.jsxs(Wt.Message,{children:["Set the"," ",a.jsx("code",{className:"rounded bg-fill-hover px-1 py-0.5",children:Array.isArray(P.envVar)?P.envVar.join(", "):P.envVar})," ","environment"," ",Array.isArray(P.envVar)&&P.envVar.length>1?"variables":"variable"," to use this provider."]})})})]})};function uPs({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:i,handleVariableChange:o,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return a.jsx(See,{children:a.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5",children:[a.jsxs(Y,{as:"h2",variant:"heading",tone:"muted",className:Z("flex items-center gap-2","[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]"),children:["Install Template ",a.jsx(ypt,{})]}),a.jsxs(pt,{orientation:"horizontal",children:[a.jsx(dt,{children:"Template AI Model Provider"}),a.jsx(ayt,{className:"flex-1",children:a.jsxs(ms,{name:"template-provider",value:t,onValueChange:n,children:[a.jsx(vs,{size:"md",children:a.jsx(gs,{placeholder:"Select"})}),a.jsx(ys,{children:e.map(h=>a.jsx(hr,{value:h.value,children:h.label},h.value))})]})})]}),t&&Object.entries(r||{}).length>0&&a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h3",tone:"muted",children:"Set required Environmental Variables"}),a.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?a.jsxs("div",{className:Z("text-muted-foreground","col-span-2 flex items-center justify-center gap-4","[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50","animate-in duration-300 fade-in"),children:[a.jsx(On,{}),a.jsxs(Y,{as:"span",variant:"caption",className:"block",children:[" ","Loading variables..."]})]}):Object.entries(r).map(([h,p])=>a.jsxs(g.Fragment,{children:[a.jsxs(pt,{className:"w-full",children:[a.jsx(dt,{className:"sr-only",children:"Key"}),a.jsx(bn,{name:`env-${h}`,value:h,disabled:!0,className:"w-full"})]}),a.jsxs(pt,{invalid:s.includes(h),className:"w-full",children:[a.jsx(dt,{className:"sr-only",children:"Value"}),a.jsx(bn,{name:h,value:p,onChange:o,autoComplete:"off",className:"w-full"}),a.jsx(ns,{children:s.includes(h)?"Value is required.":void 0})]})]},h))}),a.jsxs("div",{className:"relative mt-3.5 border-t border-border pt-12",children:[a.jsx("div",{className:"absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full bg-background",children:a.jsx(Y,{tone:"muted",as:"span",variant:"caption",className:"block",children:"And"})}),a.jsx(Y,{as:"h3",tone:"muted",children:"Set AI Model for Template Installation"}),a.jsx(Y,{tone:"muted",className:"mt-2 mb-5",children:"This model will be used by the workflow to process and install the template"}),a.jsx(VQt,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&a.jsx(ce,{className:Z("state-layer mt-4 flex min-h-10 w-full items-center justify-center gap-2 rounded-lg bg-card text-foreground","[&_svg]:h-[1.1em] [&_svg]:text-foreground [&>svg]:w-[1.1em]"),onClick:i,disabled:!t||!u||!d||s.length>0||c,children:c?a.jsxs(a.Fragment,{children:[a.jsx(On,{className:"h-4 w-4"})," Installing..."]}):a.jsxs(a.Fragment,{children:["Install ",a.jsx(dp,{})]})})]})})}function dPs({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:i}){const o=i?`feat/install-template-${i}`:"feat/install-template-[slug]";return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"mt-5 grid items-center",children:a.jsxs("div",{className:Z("flex items-center gap-3","[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[a.jsx(X1,{}),a.jsx("h2",{className:Z({"flex min-w-[50%] rounded-lg bg-muted":r}),children:a.jsx(Y,{as:"span",variant:"title",className:"block",children:r?a.jsx(a.Fragment,{children:" "}):e})})]})}),a.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[a.jsxs("div",{className:"grid",children:[a.jsx(Y,{tone:"muted",className:Z("mt-2 mb-4",{"rounded-lg bg-muted":r}),children:r?a.jsx(a.Fragment,{children:" "}):t}),!r&&i&&a.jsxs("div",{className:Z("mb-4 rounded-lg border border-border bg-background p-4","flex items-start gap-3"),children:[a.jsx("div",{className:"mt-0.5 shrink-0",children:a.jsx(yv,{className:"h-[1.1em] w-[1.1em] text-info-indicator"})}),a.jsxs("div",{className:"flex-1 space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(PN,{className:"h-[1em] w-[1em] text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",children:"A new Git branch will be created"})]}),a.jsxs("div",{className:"space-y-1",children:[a.jsxs(Y,{tone:"muted",as:"p",variant:"caption",children:[a.jsx(Y,{as:"span",variant:"column",children:"Branch name:"})," ",a.jsx(rh,{children:o})]}),a.jsx(Y,{tone:"muted",as:"p",variant:"caption",children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&a.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:Z(Zn,"mt-auto flex items-center gap-2"),children:[a.jsx(TX,{}),a.jsx(Y,{as:"span",variant:"body",className:"block",children:n?.split("/")?.pop()})]})]}),s&&a.jsx(oNe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function qnt(e){switch(e){case"running":return a.jsx(On,{size:"sm","aria-hidden":!0});case"success":return a.jsx(ur,{"aria-hidden":!0});case"failed":return a.jsx(Mn,{"aria-hidden":!0});default:return null}}function fPs(){return a.jsx("svg",{viewBox:"0 0 24 24",className:"text-placeholder","aria-hidden":!0,children:a.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function hPs({status:e,variant:t}){return t==="plain"?a.jsx("span",{className:Z("flex size-4 items-center justify-center self-center [&>svg]:size-4",Mi.colors,{"[&>svg]:text-success-indicator":e==="success","[&>svg]:text-destructive-foreground":e==="failed"}),children:e==="pending"?a.jsx(fPs,{}):qnt(e)}):a.jsx("span",{className:Z("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Mi.colors,Mi.transform,{"[&>svg]:text-success-indicator":e==="success","[&>svg]:text-destructive-foreground":e==="failed","border border-dashed border-placeholder":e==="pending","[&>svg]:size-4":e!=="running","bg-success-subtle":e==="success","bg-destructive-subtle":e==="failed","scale-110":e==="success"||e==="failed"}),children:qnt(e)})}function pPs({step:e,isActive:t,position:n,variant:r="default"}){const s=t||e.status==="success"?"ink":"muted";return a.jsxs("div",{className:Z("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",Mi.colors,{"border border-transparent":r==="default","border-dashed border-placeholder bg-card":t&&r==="default"}),children:[a.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[a.jsxs(Y,{as:"span",tone:s,className:Z("flex min-w-6 justify-end",Mi.colors),children:[n,"."]}),a.jsxs("div",{className:"min-w-0",children:[a.jsx(Y,{as:"h4",tone:s,className:Mi.colors,children:e.title}),e.description&&a.jsx(Y,{tone:"faint",className:Z("-mt-0.5",{truncate:r==="plain"}),children:e.description})]})]}),a.jsx(hPs,{status:e.status,variant:r})]})}function mPs({currentStep:e,steps:t=[],className:n}){return a.jsx("div",{className:Z(n),children:t.map((r,s)=>a.jsx(pPs,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function gPs({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return a.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[a.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>a.jsx("div",{className:Z("relative flex h-8 items-center justify-end",Mi.colors,{"bg-success-subtle":r.status==="success"&&e?.[s-1]?.status==="success"}),children:a.jsx("div",{className:Z("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-fill text-column text-muted-foreground motion-reduce:transition-none",Mi.colors,Mi.transform,{"border border-dashed border-placeholder":r.status==="pending","scale-110 bg-success-subtle text-success-subtle-foreground":r.status==="success","scale-110 bg-destructive-subtle text-destructive-subtle-foreground":r.status==="failed"}),children:r.status==="running"?a.jsx(On,{}):s+1})},r.id))}),a.jsxs("div",{className:Z("text-center text-caption text-muted-foreground",Mi.colors),children:[n," of ",t," steps completed"]})]})}function vPs({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",i=t?.payload?.workflowState,o=t?.payload?.currentStep,l=t?.error,c=i?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),h=f.length,p=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:o?.id===v}));return a.jsxs(See,{className:"mb-5 content-center space-y-6 text-muted-foreground",children:[a.jsxs("div",{className:"text-center",children:[a.jsx(Y,{as:"h3",variant:"heading",tone:"ink",children:p()}),(t?.runId||n)&&a.jsxs(Y,{as:"p",variant:"caption",tone:"muted",className:"mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&h>0&&!["error"].includes(s)&&a.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-4",children:a.jsx(gPs,{steps:m})}),l&&s==="error"&&a.jsxs("div",{className:Z("text-foreground","flex items-center gap-3 rounded-lg bg-destructive-subtle p-4","[&>svg]:h-6 [&>svg]:w-6 [&>svg]:text-destructive-foreground [&>svg]:opacity-70"),children:[a.jsx(zEn,{}),a.jsx(Y,{as:"span",variant:"body",className:"block",children:l||"Something went wrong"})]}),u&&a.jsx(mPs,{steps:m,currentStep:o,className:"pb-4"}),!u&&s==="initializing"&&a.jsxs("div",{className:Z("text-muted-foreground","grid justify-items-center gap-4 text-center"),children:[a.jsx(On,{}),a.jsx(Y,{as:"p",variant:"body",children:"This may take some time..."})]})]})}function yPs({name:e,installedEntities:t}){return a.jsxs(See,{className:Z("grid content-center items-center justify-items-center gap-4","[&>svg]:h-8 [&>svg]:w-8"),children:[a.jsx(ypt,{}),a.jsx(Y,{as:"h2",variant:"heading",children:"Done!"}),a.jsxs(Y,{tone:"muted",className:"text-center",children:["The ",a.jsx("b",{className:"text-muted-foreground",children:e})," template has been successfully installed.",t&&t.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&a.jsx(oNe,{data:t})]})}function xPs(){const{templateSlug:e}=Cr(),t=[{id:"templates",label:"Templates",to:"/templates"},{id:"template",label:Zke(e)}],[n,r]=wi(),[s,i]=g.useState(""),[o,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState({}),[h,p]=g.useState([]),[m,v]=g.useState(null),[y,x]=g.useState(!1),[b,S]=g.useState(""),[k,j]=g.useState(!1),[C,T]=g.useState(!1),[_,N]=g.useState([]),{data:E,isLoading:A}=WAs({repoOrSlug:e,owner:"mastra-ai"}),L=oPs?.includes("beta")??!1?"beta":"main",{data:F,isLoading:Q}=HAs({repo:E?.githubUrl?new URL(E.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:L}),{data:q,isLoading:B}=GAs(),{mutateAsync:V,isPending:W}=KAs(),{mutateAsync:M}=YAs(),{streamInstall:K,streamResult:D,isStreaming:$}=JAs({workflowInfo:q}),{observeInstall:z,streamResult:U,isStreaming:G}=ePs({workflowInfo:q});g.useEffect(()=>{const se=n.get("runId");se&&!y&&!m&&!$&&!G&&(console.info("🔄 Checking completed run after hot reload:",{runId:se}),S(se),M({runId:se}).then(ae=>{const he=ae.snapshot;if(he?.status==="success"&&he?.result?.success)x(!0);else if(he?.result?.success===!1)if(he?.result?.validationResults&&!he?.result?.validationResults?.valid&&he?.result?.validationResults?.remainingErrors>0){const{remainingErrors:me,errors:ke}=he.result.validationResults,Ee=`Template installation completed but ${me} validation issue${me>1?"s":""} remain unresolved.`;v(Ee),N(ke||[])}else{const me=he?.result?.message||he?.result?.error||"Template installation failed";v(typeof me=="string"?me:String(me))}}).catch(ae=>{console.error("❌ Failed to fetch run details:",ae),v("Failed to retrieve installation status after reload")}))},[n,y,m,$,G,M]),g.useEffect(()=>{const se=n.get("runId"),ae=n.get("resume"),he=n.get("provider");if(se&&ae==="true"&&he&&!$&&!G&&!k&&!C&&q){S(se),j(!0);try{M({runId:se}).then(ge=>{if(ge.snapshot?.status==="running")return z.mutateAsync({runId:se})}).then(()=>{r(ge=>{const me=new URLSearchParams(ge);return me.delete("resume"),me})}).catch(ge=>{console.error("❌ Failed to resume template installation:",ge),ge.message?.includes("404")||ge.message?.includes("not found")?v("Template installation run not found. It may have expired or been completed."):v("Failed to resume template installation. Please try again.")})}catch(ge){console.error("❌ Auto-resume failed with error:",ge),v("Failed to resume template installation. Please refresh and try again.")}}},[n,e,$,G,k,C,q,M,z,r]);const ne=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],X=[{key:"tools",label:"Tools",value:E?.tools?.length?E.tools.map(se=>se).join(", "):"n/a",icon:a.jsx(fd,{})},{key:"agents",label:"Agents",value:E?.agents?.length?E.agents.map(se=>se).join(", "):"n/a",icon:a.jsx(Vo,{})},{key:"workflows",label:"Workflows",value:E?.workflows?.length?E.workflows.map(se=>se).join(", "):"n/a",icon:a.jsx(wk,{})},{key:"providers",label:"Providers",value:E?.supportedProviders?.length?E.supportedProviders.join(", "):"n/a",icon:a.jsx(_0,{})},{key:"tags",label:"Tags",value:E?.tags?.length?E.tags.join(", "):"n/a",icon:a.jsx(Px,{})}],ee=[{...X[0]},{...X[1]},{...X[2]}].filter(se=>se.value!=="n/a");g.useEffect(()=>{F&&f(F)},[F]),g.useEffect(()=>{const se=D||U;se?.phase==="error"&&se?.error&&v(typeof se.error=="string"?se.error:String(se.error))},[D?.phase,D?.error,U?.phase,U?.error]);const re=se=>{i(se)},ue=async se=>(l(se.provider),u(se.modelId),{message:"Model updated successfully"}),te=async()=>{const se=Object.entries(d).reduce((ae,[he,ge])=>(ge===""&&ae.push(he),ae),[]);if(se.length>0){p(se);return}if(E){v(null),x(!1),S(""),T(!0);try{const he={repo:E.githubUrl||`https://github.com/mastra-ai/template-${E.slug}`,ref:L,slug:E.slug,variables:d},{runId:ge}=await V({});S(ge),r(me=>{const ke=new URLSearchParams(me);return ke.set("runId",ge),ke.set("resume","true"),ke.set("provider",s||"openai"),ke}),await K.mutateAsync({inputData:he,selectedModel:{provider:o,modelId:c},runId:ge})}catch(ae){T(!1),v(ae?.message||"Template installation failed"),console.error("Template installation failed",ae)}}},ie=se=>{const{name:ae,value:he}=se.target;he.trim()===""?p(ge=>[...ge,ae]):p(ge=>ge.filter(me=>me!==ae)),f(ge=>({...ge,[ae]:he}))};return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:Z("h-full w-full overflow-y-scroll lg:px-12"),children:a.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-4",children:[a.jsx(dPs,{isLoading:A,title:E?.title,description:E?.longDescription,imageURL:E?.imageURL,githubUrl:E?.githubUrl,infoData:X,templateSlug:e}),E&&a.jsxs(a.Fragment,{children:[($||G)&&a.jsx(vPs,{name:E.title,streamResult:G?U:D,runId:b,workflowInfo:q}),y&&a.jsx(yPs,{name:E.title,installedEntities:ee,linkComponent:lc}),m&&a.jsx(aPs,{errorMsg:m,validationErrors:_.length>0?_:D?.validationResults?.errors||U?.validationResults?.errors}),!$&&!G&&!y&&!m&&a.jsx(uPs,{providerOptions:ne,selectedProvider:s,onProviderChange:re,variables:d,setVariables:f,errors:h,setErrors:p,handleInstallTemplate:te,handleVariableChange:ie,isLoadingEnvVars:Q||B,isInstalling:W,defaultModelProvider:o,defaultModelId:c,onModelUpdate:ue})]})]})})]})}const bPs=()=>a.jsx(Yt,{titleSlot:"No Workflows yet",descriptionSlot:a.jsxs(a.Fragment,{children:["Mastra workflows are not configured yet. ",a.jsx("br",{}),"More information in the documentation."]}),actionSlot:a.jsx(ce,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/workflows/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Workflows Documentation"}),variant:"fill"});function wPs(e,t,n){return qk(e,t,{name:r=>r.name,running:r=>n[r.id]?.running??0,suspended:r=>n[r.id]?.suspended??0,steps:r=>Object.keys(r.steps??{}).length})}function SPs(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function kPs(e){const t=new Map;for(const[n,r]of Object.entries(e))t.set(n,n),r.name&&t.set(r.name,n);return t}function OPs(e,t,n){const r=kPs(t),s=[],i=(o,l,c,u,d,f)=>{const h=SPs(o).filter(v=>{const y=r.get(v);return y===void 0||!u.has(y)});if(s.push({kind:"workflow",workflow:o,pathKey:l,depth:c,nestedIds:h,guides:d,isLastChild:f}),!n.has(l)||h.length===0)return;const p=new Set(u).add(o.id),m=c===0?[]:[...d,!f];for(const[v,y]of h.entries()){const x=v===h.length-1,b=r.get(y);if(b===void 0){s.push({kind:"unregistered",stepId:y,description:o.allSteps?.[y]?.description,pathKey:`${l}/${y}`,depth:c+1,guides:m,isLastChild:x});continue}const S=t[b];S&&i({...S,id:b},`${l}/${b}`,c+1,p,m,x)}};for(const o of e)i(o,o.id,0,new Set([o.id]),[],!1);return s}const Qnt="auto 24rem minmax(0, 1fr) auto auto auto";function UQt({guides:e,isLastChild:t}){return a.jsxs("span",{"aria-hidden":!0,className:"-my-6 flex shrink-0 self-stretch",children:[e.map((n,r)=>a.jsx("span",{className:Z("w-6",n&&"border-l border-border")},r)),a.jsxs("span",{className:"relative w-6",children:[a.jsx("span",{className:Z("absolute top-0 left-0 border-l border-border",t?"h-1/2":"h-full")}),a.jsx("span",{className:"absolute top-1/2 left-0 w-3.5 border-b border-border"})]})]})}function qQt({row:e,isExpanded:t,onToggle:n}){const r=e.kind==="workflow"&&e.nestedIds.length>0,s=e.kind==="workflow"?e.workflow.name:e.stepId;return a.jsx("div",{className:"flex items-center pl-5",children:r?a.jsx("button",{type:"button","aria-expanded":t,"aria-label":`${t?"Collapse":"Expand"} nested workflows of ${s}`,className:Z(Zn,"relative grid size-5 shrink-0 place-items-center before:absolute before:-inset-1.5 before:content-['']"),onClick:i=>{i.stopPropagation(),n()},children:a.jsx(Ha,{direction:"right",className:"size-4"})}):a.jsx("span",{className:"size-5 shrink-0","aria-hidden":!0})})}const jPs=e=>e.stopPropagation();function nB({sortKey:e,sort:t,onSortChange:n,children:r}){return n?a.jsx(Te.SortableTopCell,{sortKey:e,sort:t?.key===e?t.direction:void 0,onSortChange:s=>n(s,e),children:r}):a.jsx(Te.TopCell,{children:r})}function CPs({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:s}){const{paths:i,Link:o}=Sn(),l=g.useRef(null),{workflow:c,nestedIds:u}=e,d=cf(c.name,50),f=cf(c.description??"",200),h=Object.keys(c.steps??{}).length,p=r?.running??0,m=r?.suspended??0,v=u.length>0;return a.jsxs(Te.RowWrapper,{...s,onSelectRow:()=>l.current?.click(),children:[a.jsx(qQt,{row:e,isExpanded:t,onToggle:n}),a.jsxs(Te.RowLink,{ref:l,colStart:2,to:i.workflowLink(c.id),LinkComponent:o,tabIndex:-1,onClick:jPs,children:[a.jsx(Te.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-1.5",children:[e.depth>0?a.jsx(UQt,{guides:e.guides,isLastChild:e.isLastChild}):null,a.jsx("span",{className:"truncate",children:d}),c.origin==="dynamic"?a.jsx($t,{size:"xs",variant:"blue",title:"Registered via the dynamic-workflows API",children:"Dynamic"}):null,v?a.jsxs(Y,{as:"span",variant:"body-sm",tone:"muted",title:`Nested workflows: ${u.join(", ")}`,className:"inline-flex shrink-0 items-center gap-1",children:[a.jsx(wk,{"aria-hidden":!0,className:"size-3.5"}),u.length]}):null]})}),a.jsx(Te.DescriptionCell,{children:f}),a.jsx(Te.TextCell,{className:"text-center",children:p>0?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-info-indicator","aria-label":`${p} run${p===1?"":"s"} in progress`,children:[a.jsx("span",{"aria-hidden":!0,className:"size-2 rounded-full bg-info-indicator motion-safe:animate-pulse"}),p]}):""}),a.jsx(Te.TextCell,{className:"text-center",children:m>0?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-warning-foreground","aria-label":`${m} run${m===1?"":"s"} awaiting input`,children:[a.jsx(IS,{"aria-hidden":!0,className:"size-3.5"}),m]}):""}),a.jsx(Te.TextCell,{className:"text-center",children:h||""})]})]})}function _Ps({workflows:e,isLoading:t,search:n="",sort:r,onSortChange:s,requestContext:i}){const[o,l]=g.useState(new Set),c=$Dn({requestContext:i}),u=g.useMemo(()=>Object.entries(e).map(([x,b])=>({...b,id:x})),[e]),d=g.useMemo(()=>{const x=n.toLowerCase();return u.filter(b=>b.name?.toLowerCase().includes(x)||b.description?.toLowerCase().includes(x))},[u,n]),f=g.useMemo(()=>wPs(d,r,c),[d,r,c]),h=g.useMemo(()=>OPs(f,e,o),[f,e,o]),p=g.useMemo(()=>{const x=new Map;for(const b of h)b.kind==="workflow"&&x.set(b.pathKey,x.size);return x},[h]),{containerRef:m,getRowProps:v}=Fu({count:p.size,global:!0}),y=x=>{l(b=>{const S=new Set(b);return S.has(x)?S.delete(x):S.add(x),S})};return t?a.jsx(Lu,{columns:Qnt,fit:"container"}):a.jsxs(Te,{columns:Qnt,fit:"container",scrollRef:m,children:[a.jsxs(Te.Top,{children:[a.jsx(Te.TopCell,{children:a.jsx("span",{className:"sr-only",children:"Expand"})}),a.jsx(nB,{sortKey:"name",sort:r,onSortChange:s,children:"Name"}),a.jsx(Te.TopCell,{children:"Description"}),a.jsx(nB,{sortKey:"running",sort:r,onSortChange:s,children:"Running"}),a.jsx(nB,{sortKey:"suspended",sort:r,onSortChange:s,children:"Pending input"}),a.jsx(nB,{sortKey:"steps",sort:r,onSortChange:s,children:"Number of steps"})]}),h.length===0&&n?a.jsx(Te.NoMatch,{message:"No Workflows match your search"}):null,h.map(x=>{const b=o.has(x.pathKey),S=()=>y(x.pathKey);return x.kind==="unregistered"?a.jsxs(Te.RowStatic,{className:"gap-0 px-0",children:[a.jsx(qQt,{row:x,isExpanded:b,onToggle:S}),a.jsxs("div",{className:"col-span-5 col-start-2 grid grid-cols-subgrid gap-4 px-3",children:[a.jsx(Te.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(UQt,{guides:x.guides,isLastChild:x.isLastChild}),a.jsx("span",{className:"truncate",children:cf(x.stepId,50)}),a.jsxs(Qn,{children:[a.jsx(Fn,{render:a.jsx(Y,{as:"span",variant:"body-sm",tone:"muted"}),role:"note",tabIndex:0,className:Z("shrink-0 rounded-sm",bi),children:"not registered"}),a.jsx(Bn,{className:"max-w-72",children:"Runs as a step of its parent workflow. Add it to the workflows of your Mastra instance to open, run, and inspect it on its own page."})]})]})}),a.jsx(Te.DescriptionCell,{children:cf(x.description??"",200)}),a.jsx(Te.TextCell,{className:"text-center",children:""}),a.jsx(Te.TextCell,{className:"text-center",children:""}),a.jsx(Te.TextCell,{className:"text-center",children:""})]})]},`workflow-${x.pathKey}`):a.jsx(CPs,{row:x,isExpanded:b,onToggle:S,runCount:c[x.workflow.id],rowProps:v(p.get(x.pathKey)??-1)},`workflow-${x.pathKey}`)})]})}const VM=[Ts("/workflows")];function TPs(){const{data:e,isLoading:t,error:n}=tg(),[r,s]=g.useState(""),[i,o]=g.useState();return n&&Cs(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:VM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(ci,{variant:"fill"})]}):n&&_s(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:VM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Gs,{variant:"fill",resource:"workflows"})]}):n?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:VM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Yt,{tone:"error",variant:"fill",titleSlot:"Failed to load workflows",descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:VM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(bPs,{})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:VM}),actionRow:a.jsxs(rr,{children:[a.jsx(rr.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(pf,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})})}),a.jsx(rr.End,{children:a.jsx(ce,{render:a.jsx(lc,{to:"/workflows/schedules"}),variant:"primary",icon:a.jsx(T0,{}),children:"Schedules"})})]}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(_Ps,{workflows:e||{},isLoading:t,search:r,sort:i,onSortChange:(l,c)=>o({key:c,direction:l})})]})}const IPs={active:"bg-success-indicator",paused:"bg-info-indicator",completed:"bg-muted-foreground"},EPs={active:"text-success-indicator",paused:"text-info-indicator",completed:"text-muted-foreground"},QQt=({status:e})=>a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${IPs[e]}`,"aria-hidden":!0}),a.jsx(Y,{as:"span",variant:"caption",className:EPs[e],children:e})]});function ZQt({status:e}){const{icon:t,color:n}=NPs(e);return a.jsxs("span",{className:`inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[a.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),a.jsx(Y,{as:"span",variant:"caption",children:e})]})}function NPs(e){switch(e){case"success":return{icon:a.jsx(ur,{size:14}),color:"text-success-indicator"};case"failed":return{icon:a.jsx(Mn,{size:14}),color:"text-destructive-foreground"};case"running":return{icon:a.jsx(On,{}),color:"text-muted-foreground"};case"suspended":return{icon:a.jsx(XH,{size:14}),color:"text-info-indicator"};case"canceled":return{icon:a.jsx(uL,{size:14}),color:"text-muted-foreground"};case"pending":case"waiting":return{icon:a.jsx(fC,{size:14}),color:"text-muted-foreground"};default:return{icon:null,color:"text-muted-foreground"}}}const Znt="auto auto auto auto 1fr",APs=3e4,PPs=5*6e4;function $Ps({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:i}){const{Link:o,paths:l}=Sn(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=Fu({count:u});let h=-1;return t?a.jsx(Lu,{columns:Znt}):e.length===0?a.jsx(Y,{variant:"body",tone:"muted",className:"p-4",children:"No trigger history yet."}):a.jsxs(Te,{columns:Znt,className:"min-w-0",scrollRef:d,children:[a.jsxs(Te.Top,{children:[a.jsx(Te.TopCell,{children:"Run"}),a.jsx(Te.TopCell,{children:"Status"}),a.jsx(Te.TopCell,{children:"Started"}),a.jsx(Te.TopCell,{children:"Duration"}),a.jsx(Te.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=Uc(m,{signed:!0}),y=p.outcome==="failed",x=y?p.error:p.run?.error,b=Math.abs(m),S=!y&&b>APs&&b<=PPs,k=`${p.scheduleId}-${p.runId}-${p.actualFireAt}`,j=c(p);j&&(h+=1);const C=a.jsx(Y,{as:"span",variant:"caption",font:"mono",tone:j?"ink":"muted",className:"whitespace-nowrap",children:p.runId}),T=a.jsxs(a.Fragment,{children:[a.jsx(Te.Cell,{children:C}),a.jsx(Te.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2",children:[y?a.jsxs(Y,{as:"span",variant:"caption",className:"inline-flex items-center gap-1.5 whitespace-nowrap text-destructive-foreground",children:[a.jsx(Xd,{size:14}),"publish failed"]}):p.run?a.jsx(ZQt,{status:p.run.status}):a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),x?a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-destructive-foreground",children:a.jsx(Xd,{size:14})})}),a.jsx(Bn,{children:x})]}):null]})}),a.jsx(Te.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[p.actualFireAt?a.jsx(BE,{value:p.actualFireAt}):"—",S?a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-info-indicator",children:a.jsx(Xd,{size:14})})}),a.jsxs(Bn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),a.jsx(Te.Cell,{children:p.run?a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",children:Uc(p.run.durationMs)||"—"}):a.jsx("span",{className:"text-muted-foreground",children:"—"})}),a.jsx(Te.Cell,{children:" "})]});return j?a.jsx(Te.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:o,...f(h),children:T},k):a.jsx(Te.RowStatic,{children:T},k)}),a.jsx(Te.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:i})]})}const WQt={id:"workflow-schedules",label:"Schedules",icon:T0,to:"/workflows/schedules"};function rB({label:e,children:t}){return a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"uppercase",children:e}),a.jsx("div",{children:a.jsx(Y,{as:"span",variant:"body",className:"block",children:t})})]})}function RPs(){const{scheduleId:e}=Cr(),t=[Ts("/workflows"),WQt,{id:"schedule",label:Zke(e),icon:T0}],{paths:n}=Sn(),{data:r,error:s}=Hur({scheduleId:e,queryOptions:{enabled:!!e}}),{data:i,isLoading:o,error:l,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d}=Gur({scheduleId:e,queryOptions:{enabled:!!e}}),f=Kur({scheduleId:e});if(s&&Cs(s))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(ci,{variant:"fill"})]});if(s&&_s(s))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Gs,{variant:"fill",resource:"schedules"})]});if(s)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Yt,{tone:"error",variant:"fill",titleSlot:"Failed to load schedule",descriptionSlot:s.message})]});const h=r?.workflowId,p=r?.agentId;return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),actionRow:a.jsx(rr,{children:a.jsxs(rr.End,{children:[a.jsx(ce,{render:a.jsx(lc,{to:n.schedulesLink()}),variant:"ghost",icon:a.jsx(vd,{}),children:"Back to schedules"}),h?a.jsx(ce,{icon:a.jsx(jl,{}),render:a.jsx(lc,{to:n.workflowLink(h)}),variant:"ghost",children:"Open workflow"}):null,r?a.jsx(ce,{onClick:()=>{const m=r.status==="active"?"pause":"resume";f.mutate(m,{onSuccess:()=>Xe.success(m==="pause"?"Schedule paused":"Schedule resumed"),onError:v=>Xe.error(v.message)})},disabled:f.isPending,"data-testid":"schedule-toggle-button",children:r.status==="active"?a.jsxs(a.Fragment,{children:[a.jsx(IS,{}),"Pause"]}):a.jsxs(a.Fragment,{children:[a.jsx(Fm,{}),"Resume"]})}):null]})}),children:[a.jsx("h1",{className:"sr-only",children:e}),r?a.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-4 overflow-hidden",children:[a.jsxs("div",{className:"flex h-fit flex-col gap-4 rounded-md border border-border p-4",children:[a.jsx(rB,{label:p?"Agent":"Workflow",children:h?a.jsx(lc,{to:n.workflowLink(h),className:"text-foreground hover:underline",children:h}):p?a.jsx(lc,{to:n.agentLink(p),className:"text-foreground hover:underline",children:p}):"—"}),a.jsxs(rB,{label:"Cron",children:[a.jsx(Y,{as:"span",variant:"body",font:"mono",children:r.cron}),r.timezone?a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"ml-2",children:r.timezone}):null]}),a.jsx(rB,{label:"Status",children:a.jsx(QQt,{status:r.status})}),a.jsx(rB,{label:"Next fire",children:r.nextFireAt?a.jsx(BE,{value:r.nextFireAt}):"—"})]}),a.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[a.jsx(Y,{variant:"body",className:"mb-3",children:"Trigger history"}),l?a.jsx(Yt,{tone:"error",titleSlot:"Failed to load trigger history",descriptionSlot:l.message}):a.jsx($Ps,{triggers:i??[],isLoading:o,workflowId:h,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d})]})]}):null]})}const MPs={target:e=>e.workflowId??e.agentId??"",status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},Wnt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function DPs({schedules:e,isLoading:t,search:n="",sort:r,onSortChange:s}){const{paths:i,Link:o}=Sn(),l=g.useMemo(()=>{const f=n.toLowerCase(),h=f?e.filter(p=>p.id.toLowerCase().includes(f)||(p.workflowId??p.agentId??"").toLowerCase().includes(f)):e;return qk(h,r,MPs)},[e,n,r]),{containerRef:c,getRowProps:u}=Fu({count:l.length,global:!0});if(t)return a.jsx(Lu,{columns:Wnt});const d=(f,h)=>s?a.jsx(Te.SortableTopCell,{sortKey:f,sort:r?.key===f?r.direction:void 0,onSortChange:s,children:h}):a.jsx(Te.TopCell,{children:h});return a.jsxs(Te,{columns:Wnt,className:"min-w-0",scrollRef:c,children:[a.jsxs(Te.Top,{children:[d("target","Target"),a.jsx(Te.TopCell,{children:"Schedule ID"}),a.jsx(Te.TopCell,{children:"Cron"}),d("status","Status"),d("nextFireAt","Next fire"),d("lastFireAt","Last run")]}),l.length===0&&n?a.jsx(Te.NoMatch,{message:"No schedules match your search"}):null,l.length===0&&!n?a.jsx(Te.NoMatch,{message:"No schedules configured"}):null,l.map((f,h)=>a.jsxs(Te.RowLink,{to:i.scheduleLink(f.id),LinkComponent:o,...u(h),children:[a.jsx(Te.NameCell,{children:f.workflowId??f.agentId}),a.jsx(Te.Cell,{className:"min-w-0",children:a.jsx(Y,{as:"span",variant:"body-sm",tone:"muted",font:"mono",className:"block truncate",title:f.id,children:f.id})}),a.jsx(Te.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx(Y,{as:"span",variant:"caption",font:"mono",children:f.cron}),f.timezone?a.jsx(Y,{as:"span",variant:"meta",tone:"muted",children:f.timezone}):null]})}),a.jsx(Te.Cell,{children:a.jsx(QQt,{status:f.status})}),a.jsx(Te.Cell,{children:f.nextFireAt?a.jsx(BE,{value:f.nextFireAt}):"—"}),a.jsx(Te.Cell,{children:f.lastRun?a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx(ZQt,{status:f.lastRun.status}),f.lastFireAt?a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:a.jsx(BE,{value:f.lastFireAt})}):null]}):f.lastFireAt?a.jsx(BE,{value:f.lastFireAt}):a.jsx("span",{className:"text-muted-foreground",children:"Never"})})]},f.id))]})}function HQt({workflowId:e}={}){const{data:t,isLoading:n,error:r}=DK(e?{workflowId:e}:{}),[s,i]=g.useState(""),[o,l]=g.useState();return r?a.jsx(Yt,{tone:"error",titleSlot:"Failed to load schedules",descriptionSlot:r.message}):a.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[a.jsx("div",{className:"max-w-120",children:a.jsx(pf,{onSearch:i,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),a.jsx("div",{className:"overflow-y-auto",children:a.jsx(DPs,{schedules:t??[],isLoading:n,search:s,sort:o,onSortChange:(c,u)=>l({key:u,direction:c})})})]})}const Mue=[Ts("/workflows"),WQt];function LPs(){const[e]=wi(),t=e.get("workflowId")??void 0,{error:n}=DK(t?{workflowId:t}:{});return n&&Cs(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Mue}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(ci,{variant:"fill"})]}):n&&_s(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Mue}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(Gs,{variant:"fill",resource:"schedules"})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Mue}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx("div",{className:"h-full",children:a.jsx(HQt,{workflowId:t})})]})}const zPs={"--belt-hue":"var(--warning-indicator)"};function FPs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function BPs(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e),[r]=n;if(n.length===1&&r)return r}return t}function VPs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:a.jsxs("section",{className:Z(Eke,"pointer-events-auto relative isolate"),"data-testid":"workflow-suspended-steps","aria-label":"Step suspended",children:[a.jsxs("div",{className:"max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]",children:[a.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border bg-background px-5 py-4",children:[a.jsxs(Y,{as:"h2",variant:"column",tone:"ink",className:"flex items-center gap-2",children:[a.jsx(At,{children:a.jsx(XH,{})}),"Step suspended"]}),a.jsx($t,{variant:"orange",emphasis:"subtle",children:"Needs input"})]}),e.map(s=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const o=i?.resumeSchema?MS(hC(i.resumeSchema)):Ef(_n(),Ff());return a.jsx(UPs,{step:s,stepSchema:o,description:i.description,onResume:r},`${s.runId}-${s.stepId}`)})]}),a.jsx(C5t,{status:"ready",label:"Needs input",className:"before:hidden",style:zPs})]})}function UPs({step:e,stepSchema:t,description:n,onResume:r}){const[s,i]=g.useState(!1),[o,l]=g.useState(!1),c=async u=>{l(!0);try{await r({stepId:e.stepId.split("."),runId:e.runId,resumeData:u})}catch(d){Xe.error(d instanceof Error?d.message:"Error resuming workflow")}finally{l(!1)}};return a.jsxs("div",{className:"space-y-5 p-5 [&+&]:border-t [&+&]:border-border",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(Y,{as:"p",variant:"subheading",tone:"ink",className:"break-words",children:e.stepId}),n&&a.jsx(Y,{as:"p",variant:"caption",tone:"muted",children:n})]}),e.suspendPayload!==void 0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs(Y,{as:"p",variant:"caption",tone:"muted",className:"flex items-center gap-2",children:[a.jsx(At,{children:a.jsx(TEn,{})}),"The step is asking"]}),a.jsxs(gc,{open:s,onOpenChange:i,children:[a.jsxs(Gl,{className:Z(pr,"flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5"),children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[a.jsx(At,{children:a.jsx(Ha,{direction:"right",className:"text-muted-foreground"})}),a.jsx(Y,{as:"span",variant:"body",tone:"ink",className:"truncate",children:BPs(e.suspendPayload,e.stepId)})]}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"shrink-0",children:FPs(e.suspendPayload)})]}),a.jsx(Kl,{children:a.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:a.jsx(Or,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs(Y,{as:"p",variant:"caption",tone:"muted",className:"flex items-center gap-2",children:[a.jsx(At,{children:a.jsx(AEn,{})}),"Your response"]}),a.jsx("div",{className:"-mx-5",children:a.jsx(Ske,{schema:t,isSubmitLoading:o,submitButtonLabel:"Resume",submitButtonVariant:"primary",submitButtonIcon:a.jsx(Fm,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:c})})]})]})}function qPs({hidden:e,requestContext:t,canResume:n}){const{result:r,workflow:s,runId:i,isStreamingWorkflow:o}=g.useContext(Wl),l=Qvt(r,i),c=n7n(t),u=r?.status==="suspended"&&l.length>0&&!o;return!s||!u||!n?null:a.jsx("div",{hidden:e,"data-testid":"workflow-suspended-overlay",className:"pointer-events-none absolute top-12 right-2 z-30 w-95 max-w-[calc(100%-16px)] animate-in duration-300 fade-in-0 slide-in-from-top-2 motion-reduce:animate-none",children:a.jsx(VPs,{suspendedSteps:l,workflow:s,isStreaming:o,onResume:c})},i)}const Hnt={success:{label:"Completed",icon:ur},failed:{label:"Failed",icon:cwe},suspended:{label:"Needs input",icon:IS},waiting:{label:"Waiting",icon:yx},paused:{label:"Paused",icon:IS},skipped:{label:"Skipped",icon:ZNn},running:{label:"Running",icon:hc},canceled:{label:"Canceled",icon:uL}},QPs={label:"Status unavailable",icon:aTn};function ZPs({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:s,onOpenInput:i,onOpenOutput:o}){const l=Object.hasOwn(Hnt,e.status)?Hnt[e.status]:QPs,c=l.icon,u=RSe(e.status),d=e.stepId.slice(0,e.stepId.lastIndexOf(".")),f=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(".")+1):e.stepId;return a.jsxs("div",{"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&s(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&s(null),className:Z("grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1","@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2",(t||n)&&"bg-fill-subtle"),children:[a.jsxs("button",{type:"button","aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,className:Z("text-foreground","flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left focus-visible:rounded-sm aria-disabled:cursor-default",bi),children:[a.jsx("span",{"aria-label":l.label,className:Z("grid size-6 flex-none place-items-center rounded-md border border-border bg-background",Q1t[u]),children:a.jsx(c,{"aria-hidden":!0,className:Z("size-3.5",e.status==="running"&&"motion-safe:animate-spin")})}),a.jsxs("span",{className:"min-w-0",children:[a.jsx(Y,{as:"span",variant:"meta",className:"block truncate",children:f}),e.isNestedEntry&&a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",className:"flex min-w-0 items-center gap-1",children:[a.jsx(fwe,{"aria-hidden":!0,className:"size-3 shrink-0"}),a.jsx("span",{className:"truncate",children:d})]})]})]}),a.jsx("div",{className:"relative h-5 min-w-0 overflow-hidden rounded-sm bg-muted @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]","aria-hidden":!0,children:e.timing&&a.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:Z("absolute top-0 h-full min-w-0.5 rounded-sm",HJn[u]),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),a.jsx(Y,{as:"span",variant:"meta",tone:"muted",className:"text-right whitespace-nowrap",title:e.timing&&e.spansSuspension?"Includes time spent suspended waiting for input":void 0,children:e.timing?a.jsx(Y,{as:"span",variant:"meta",font:"mono",children:Uc(e.timing.durationMs)}):a.jsx("span",{"aria-label":"Timing unavailable",children:"—"})}),a.jsxs("div",{className:"flex items-center",children:[a.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:e.step.input===void 0,onClick:h=>i(e,h.currentTarget),children:a.jsx(HH,{})}),a.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:e.step.output===void 0,onClick:h=>o(e,h.currentTarget),children:a.jsx(KH,{})})]})]})}const WPs=e=>e.includes("."),HPs=e=>e==="input"||e.endsWith(".input"),Gnt=1;function GPs(e,t){const n=MSe(e),r=n?.isLive?Math.max(t,n.start):n?.end;return{span:n&&r!==void 0?{start:n.start,end:r}:void 0,isLive:n?.isLive??!1,spansSuspension:n?.spansSuspension??!1}}function KPs(e,t){const n=Object.entries(e).filter(([l])=>!HPs(l)).map(([l,c])=>({stepId:l,step:c,...GPs(c,t)})).sort((l,c)=>(l.span?.start??1/0)-(c.span?.start??1/0)||l.stepId.localeCompare(c.stepId)),r=n.flatMap(l=>l.span?[l.span]:[]),s=Math.min(...r.map(l=>l.start)),i=Math.max(s,...r.map(l=>l.end)),o=Math.max(i-s,1);return n.map(({stepId:l,step:c,span:u,isLive:d,spansSuspension:f})=>{let h;if(u){const p=u.end-u.start,m=Math.min((u.start-s)/o*100,100-Gnt),v=Math.min(Math.max(p/o*100,Gnt),100-m);h={durationMs:p,offsetPct:m,widthPct:v}}return{stepId:l,step:c,status:lK(c)?"suspended":c.status,timing:h,spansSuspension:f,isRunning:d,isNestedEntry:WPs(l)}})}function YPs(){const{steps:e}=m$(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=bG(),[i,o]=g.useState(()=>Date.now()),[l,c]=g.useState(!0),[u,d]=g.useState(!1),{showData:f}=Ek(),h=g.useRef(null),p=KPs(e,i),m=p.some(v=>v.isRunning);return Vpt(h,{enabled:m&&!l}),g.useEffect(()=>{if(!m||l)return;const v=setInterval(()=>o(Date.now()),100);return()=>clearInterval(v)},[m,l]),p.length===0?null:a.jsx("div",{"data-testid":"workflow-timeline",className:"relative z-20 shrink-0 px-2 pb-2",children:a.jsxs(gc,{open:!l,onOpenChange:v=>c(!v),className:Z(pr,"@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl"),children:[a.jsxs("div",{className:"flex items-center",children:[a.jsxs(Gl,{className:"flex min-h-11 min-w-0 flex-1 items-center gap-2 px-3.5 py-2.5 text-caption text-foreground hover:bg-fill-subtle","aria-label":l?"Expand timeline":"Collapse timeline",children:[a.jsx("span",{children:a.jsx(Hht,{"aria-hidden":!0,className:"size-4 text-muted-foreground"})}),a.jsx("span",{children:"Timeline"}),a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",children:[p.length," events"]}),a.jsx("span",{className:"ml-auto",children:a.jsx(Ha,{direction:"right",className:"size-4"})})]}),!l&&a.jsx(ce,{variant:"ghost",size:"icon-sm",tooltip:u?"Restore timeline height":"Enlarge timeline","aria-pressed":u,onClick:()=>d(!u),className:"mr-2 shrink-0",children:u?a.jsx(U_n,{}):a.jsx(Kht,{})})]}),a.jsx(Kl,{children:a.jsx("div",{ref:h,"data-testid":"workflow-timeline-list",className:Z("overflow-auto overscroll-contain px-1.5 pb-1.5",u?"max-h-[min(720px,calc(100dvh-112px))]":"max-h-[min(320px,40dvh)]"),children:p.map(v=>a.jsx(ZPs,{row:v,isSelected:t===v.stepId,isHovered:n===v.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:(y,x)=>f({type:"step-input",stepId:y.stepId},x),onOpenOutput:(y,x)=>f({type:"step-output",stepId:y.stepId},x)},v.stepId))})})]})})}const XPs=({workflowId:e,workflow:t,isLoading:n})=>{const[r]=xr("workflow",e),{canExecute:s,isLoading:i}=Za(),{stepDetail:o}=Ek(),l=Ik(),c=o?.type==="data",u=a.jsxs("div",{className:"[container-type:size] relative h-full min-h-0",children:[a.jsx(U5t,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),a.jsx(qPs,{hidden:c,requestContext:r,canResume:!i&&s("workflows")}),c&&a.jsx("div",{className:"pointer-events-auto absolute top-12 right-2 z-30 flex max-h-[calc(100cqh-64px)] w-[440px] max-w-[calc(100%-16px)] flex-col",children:a.jsx(kV,{requestContext:r})}),a.jsx("div",{className:"pointer-events-none absolute right-0 bottom-0 left-[var(--workflow-left-panel-width,0px)] z-20",children:a.jsx(YPs,{})})]});return l&&o&&!c?a.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:a.jsx(kV,{requestContext:r})}):a.jsxs("div",{className:"relative h-full min-h-0",children:[u,a.jsxs(b$,{className:"pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2",children:[a.jsx(ap,{id:"workflow-graph",className:"pointer-events-none min-w-0"}),o&&!c&&a.jsxs(a.Fragment,{children:[a.jsx(uk,{className:"pointer-events-auto"}),a.jsx(ap,{id:"workflow-step-detail",minSize:300,maxSize:"60%",defaultSize:420,className:"min-w-0",children:a.jsx("div",{className:"pointer-events-auto h-full min-h-0 overflow-hidden rounded-studio-panel border border-border bg-background",children:a.jsx(kV,{requestContext:r})})})]})]})]})},Knt=()=>{const{workflowId:e}=Cr(),{data:t,isLoading:n,error:r}=wL({workflowId:e,requestContext:xr("workflow",e)[0],queryOptions:{enabled:!!e}});return r&&Cs(r)?a.jsx(ci,{variant:"fill"}):r&&_s(r)?a.jsx(Gs,{variant:"fill",resource:"workflows"}):a.jsx(XPs,{workflowId:e,workflow:t??void 0,isLoading:n})};function JPs(){const{workflowId:e}=Cr(),{error:t}=DK(e?{workflowId:e}:{});if(!e)return null;let n;return t&&Cs(t)?n=a.jsx(ci,{variant:"fill"}):t&&_s(t)?n=a.jsx(Gs,{variant:"fill",resource:"schedules"}):n=a.jsx("div",{className:"h-full",children:a.jsx(HQt,{workflowId:e})}),a.jsxs(It,{children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),n]})}function e$s(){const{workflowId:e}=Cr();return e?a.jsx(vAe,{scopedEntityId:e,scopedEntityType:od.WORKFLOW_RUN}):null}const GQt=g.createContext(null);function tu(){const e=g.useContext(GQt);if(!e)throw new Error("Workspace components must be rendered inside <Workspace.Root>");return e}const t$s=e=>e?.status;function n$s(e,t){return Cs(e)?"Your session has expired. Sign in again to continue.":_s(e)?"You don't have permission to access this.":Pk(e)?"This path no longer exists.":t$s(e)===501?"This workspace does not support this operation.":t}function kee({error:e,fallback:t,className:n}){return a.jsx(Wt,{variant:"destructive",className:n,children:a.jsx(Wt.Message,{children:n$s(e,t)})})}const r$s=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function s$s(e){const t=r$s.exec(e);return t?{frontmatter:t[1]??"",body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function i$s({content:e}){const{frontmatter:t,body:n}=s$s(e);return a.jsxs(a.Fragment,{children:[t!==null&&a.jsx("div",{"data-testid":"workspace-frontmatter",className:"border-b border-border",children:a.jsx(l$,{code:t,lang:"yaml",overflow:"wrap",className:"rounded-none border-0 bg-transparent [&_pre]:p-4"})}),a.jsx("div",{className:"p-4",children:a.jsx(_l,{children:n})})]})}function o$s(){const{activeFilePath:e}=tu();return e?a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",tone:"muted",className:"truncate","data-testid":"workspace-file-path",children:e}):null}function a$s({path:e,content:t,mimeType:n}){return IRt(e,n)?a.jsx("div",{className:"flex justify-center p-4",children:a.jsx("img",{src:`data:${n||"image/png"};base64,${t}`,alt:e.split("/").pop(),className:"max-w-full object-contain"})}):ERt(e,n)?a.jsx("div",{className:"flex justify-center p-4",children:a.jsx("video",{controls:!0,"aria-label":e.split("/").pop(),className:"max-w-full",children:a.jsx("source",{src:`data:${LGe(e,n)};base64,${t}`,type:LGe(e,n)})})}):Ozr(e)?a.jsx(i$s,{content:t}):a.jsx(l$,{code:t,lang:cjt(e),overflow:"scroll",className:"rounded-none border-0 bg-transparent [&_pre]:p-4"})}function l$s({renderPreview:e}){const{workspaceId:t,activeFilePath:n}=tu(),{data:r,isLoading:s,error:i}=Pzr({workspaceId:t,path:n,queryOptions:{enabled:!!n}});if(!n)return null;if(s)return a.jsxs("div",{"aria-busy":"true",className:"flex flex-col gap-2 p-4",children:[a.jsx(bt,{className:"h-4 w-1/2"}),a.jsx(bt,{className:"h-4 w-5/6"}),a.jsx(bt,{className:"h-4 w-2/3"})]});if(!r)return a.jsx(kee,{error:i,fallback:"Could not load file.",className:"m-4"});const o={path:n,content:r.content,mimeType:r.mimeType};return e?.(o)??a.jsx(a$s,{...o})}const YA=".",KQt=(e,t)=>e===YA?t:`${e}/${t}`,Ynt=e=>e.split("/").slice(0,-1).map((t,n,r)=>r.slice(0,n+1).join("/")),YQt=e=>{const t=e.lastIndexOf("/");return t===-1?YA:e.slice(0,t)};function XQt({labeled:e=!1}={}){const{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=tu(),s=mr(),[i,o]=g.useState(!1),[l,c]=g.useState(""),[u,d]=g.useState(!1);if(!n||r(YA))return null;const f=l.trim().replace(/^\.?\/+|\/+$/g,""),h=async()=>{if(f){d(!0);try{await n(f),await s.invalidateQueries({queryKey:["workspace",t,"fs","list",YQt(f)]}),o(!1),c("")}catch{}finally{d(!1)}}};return a.jsxs(a.Fragment,{children:[e?a.jsx(ce,{variant:"ghost",icon:a.jsx(_S,{}),onClick:()=>o(!0),children:"New folder"}):a.jsx(ce,{variant:"ghost",size:"icon-sm",tooltip:"New folder",onClick:()=>o(!0),children:a.jsx(_S,{})}),a.jsx(Yr,{open:i,onOpenChange:o,pending:u,children:a.jsx(Xr,{size:"sm",children:a.jsxs("form",{onSubmit:p=>{p.preventDefault(),h()},children:[a.jsx(Jr,{children:a.jsx(Zr,{children:"New folder"})}),a.jsx(Qr,{children:a.jsx(bn,{autoFocus:!0,"aria-label":"Folder path",placeholder:"docs/guides",value:l,onChange:p=>c(p.target.value)})}),a.jsxs(Yo,{children:[a.jsx(_a,{children:"Cancel"}),a.jsx(ce,{type:"submit",variant:"primary",disabled:!f||u,children:"Create"})]})]})})})]})}function Xnt(e){return`${e.topSource}/${e.name}`}function Jnt(e){const t=NRt(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function c$s({open:e,onOpenChange:t,workspaceId:n,onInstall:r,isInstalling:s,installedSkillIds:i=[],installedSkillNames:o=[],writableMounts:l,installedSkillPaths:c}){const[u,d]=g.useState(""),[f,h]=g.useState(null),[p,m]=g.useState(),v=l?.some(Q=>Q.path===p)?p:l?.[0]?.path,{data:y,isLoading:x}=Czr({workspaceId:n,queryOptions:{enabled:!!n}}),b=jzr({workspaceId:n}),S=g.useMemo(()=>f?.topSource?NRt(f.topSource,f.name):null,[f]),k=g.useMemo(()=>!S||!f?null:`https://skills.sh/${S.owner}/${S.repo}/${f.name}`,[S,f]),{data:j,isLoading:C}=_zr({workspaceId:n,owner:S?.owner,repo:S?.repo,skillPath:f?.name,queryOptions:{enabled:!!n&&!!S&&!!f}}),T=uw(Q=>{Q.trim().length>=2&&b.mutate(Q)},300),_=g.useCallback(Q=>{d(Q),T(Q)},[T]),N=g.useMemo(()=>u.trim().length>=2?b.data?.skills??[]:y?.skills??[],[u,b.data,y]),E=b.isPending,A=u.trim().length>=2,P=g.useMemo(()=>{if(!f)return!1;const Q=Jnt(f);return!!(Q&&i.includes(Q)||o.includes(f.name))},[f,i,o]),L=g.useCallback(()=>{!f||!S||r({repository:`${S.owner}/${S.repo}`,skillName:f.name,mount:l&&l.length>1?v:void 0})},[f,S,r,l,v]),F=g.useCallback(Q=>{Q||(d(""),h(null),m(void 0)),t(Q)},[t]);return a.jsx(Yr,{open:e,onOpenChange:F,pending:s,children:a.jsxs(Xr,{size:"xl",className:"h-[80vh]",children:[a.jsxs(Jr,{children:[a.jsx(Zr,{children:"Add Skill"}),a.jsx(Lo,{children:"Search and install skills from the community registry"})]}),a.jsxs(Qr,{layout:"fill",children:[a.jsx(Zc,{label:"Search skills",placeholder:"Search skills...",value:u,onValueChange:_}),a.jsxs("div",{className:"flex min-h-0 flex-1 gap-4",children:[a.jsxs("div",{className:"flex min-h-0 w-1/2 flex-col",children:[a.jsx(Y,{as:"p",variant:"eyebrow",tone:"muted",className:"mb-2",children:A?"Search Results":"Popular Skills"}),a.jsx(jr,{className:"flex-1 rounded-lg border border-border",children:a.jsx(Au,{className:!x&&!E&&N.length===0?"flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col":void 0,children:x||E?a.jsx("div",{className:"flex items-center justify-center py-5",children:a.jsx(hc,{className:"size-6 animate-spin text-muted-foreground"})}):N.length===0?a.jsxs("div",{className:"flex flex-1 flex-col items-center-safe justify-center-safe py-5 text-muted-foreground",children:[a.jsx(uL,{className:"mb-2 size-8"}),a.jsx(Y,{children:A?"No skills found":"No skills available"})]}):a.jsx("div",{className:"space-y-1 p-2",children:N.map(Q=>{const q=Xnt(Q),B=Jnt(Q),V=B&&i.includes(B)||o.includes(Q.name),W=f?Xnt(f):null;return a.jsx("button",{onClick:()=>h(Q),className:Z("w-full rounded-md px-3 py-2 text-left","hover:bg-fill-subtle",W===q&&"border border-border-strong bg-fill-hover"),children:a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",className:"truncate",children:Q.name}),V&&a.jsxs(Y,{as:"span",variant:"meta",className:"inline-flex items-center gap-1 rounded bg-info-subtle px-1.5 py-0.5 text-info-subtle-foreground",children:[a.jsx(ur,{className:"size-2.5"}),"Installed"]})]}),a.jsx(Y,{as:"p",variant:"caption",tone:"muted",className:"truncate",children:Q.topSource})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-1 text-muted-foreground",children:[a.jsx(fp,{className:"size-3"}),a.jsx(Y,{as:"span",variant:"caption",children:Q.installs.toLocaleString()})]})]})},q)})})})})]}),a.jsxs("div",{className:"flex min-h-0 w-1/2 flex-col",children:[a.jsx(Y,{as:"p",variant:"eyebrow",tone:"muted",className:"mb-2",children:"Preview"}),a.jsx("div",{className:"flex flex-1 flex-col overflow-hidden rounded-lg border border-border",children:f?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"border-b border-border bg-card p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"rounded-lg bg-muted p-2",children:a.jsx(q6,{className:"size-5 text-muted-foreground"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx(Y,{as:"h3",variant:"subheading",tone:"ink",className:"truncate",children:f.name}),a.jsxs("div",{className:"mt-1 flex items-center gap-3 text-muted-foreground",children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(TX,{className:"size-3"}),a.jsx(Y,{as:"span",variant:"caption",className:"block",children:f.topSource})]}),a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(fp,{className:"size-3"}),a.jsxs(Y,{as:"span",variant:"caption",className:"block",children:[f.installs.toLocaleString()," installs"]})]})]})]}),S&&a.jsx("a",{href:`https://github.com/${S.owner}/${S.repo}`,target:"_blank",rel:"noopener noreferrer",className:Z(Zn,In),title:"View on GitHub",children:a.jsx(Zs,{className:"size-4"})})]})}),C?a.jsx("div",{className:"flex flex-1 items-center justify-center",children:a.jsx(hc,{className:"size-6 animate-spin text-muted-foreground"})}):j?a.jsx(jr,{className:"flex-1",children:a.jsx("div",{className:"p-4",children:a.jsx(_l,{children:j})})}):a.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-muted-foreground",children:[a.jsx(X1,{className:"mb-2 size-8"}),a.jsx(Y,{children:"Preview unavailable"}),k&&a.jsxs("a",{href:k,target:"_blank",rel:"noopener noreferrer",className:"mt-2 flex items-center gap-1 text-info-indicator hover:underline",children:[a.jsxs(Y,{as:"span",variant:"caption",className:"block",children:["View on skills.sh"," "]}),a.jsx(Zs,{className:"size-3"})]})]})]}):a.jsxs("div",{className:"flex h-full flex-col items-center justify-center text-muted-foreground",children:[a.jsx(X1,{className:"mb-2 size-8"}),a.jsx(Y,{children:"Select a skill to preview"})]})})]})]}),f&&l&&l.length>1&&a.jsxs(pt,{orientation:"horizontal",className:Z(pr,"gap-3 rounded-lg p-3"),children:[a.jsx(wP,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx(dt,{className:"whitespace-nowrap",children:"Install to"}),a.jsxs(ms,{value:v,onValueChange:m,children:[a.jsx(vs,{className:"flex-1",children:a.jsx(gs,{})}),a.jsx(ys,{children:l.map(Q=>{const q=Q.displayName??Q.name??Q.provider??"unknown";return a.jsxs(hr,{value:Q.path,children:[q," (",Q.path,")"]},Q.path)})})]})]})]}),f&&a.jsxs(Yo,{children:[P&&l&&l.length>1&&(()=>{const Q=c?.[f.name];if(!Q)return null;const q=l.find(B=>Q.startsWith(B.path+"/")||Q===B.path);return q?a.jsxs(Y,{as:"span",variant:"caption",tone:"muted",className:"mr-auto",children:["Installed at ",q.path]}):null})(),a.jsx(_a,{children:"Cancel"}),a.jsx(Ca,{onConfirm:L,disabled:!S||P,"data-testid":"install-skill-button",children:s?"Installing...":P?"Already Installed":"Install"})]})]})})}function JQt({labeled:e=!1}){const{workspaceId:t,addSkill:n}=tu(),[r,s]=g.useState(!1),[i,o]=g.useState(!1);if(!n)return null;const{onInstall:l,...c}=n,u=async d=>{o(!0);try{await l(d),s(!1)}catch{}finally{o(!1)}};return a.jsxs(a.Fragment,{children:[e?a.jsxs(ce,{variant:"ghost",onClick:()=>s(!0),children:[a.jsx(zfe,{}),"Add skill"]}):a.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":"Add skill",tooltip:"Add skill",onClick:()=>s(!0),children:a.jsx(zfe,{})}),a.jsx(c$s,{...c,open:r,onOpenChange:s,workspaceId:t,onInstall:d=>{u(d)},isInstalling:i})]})}function u$s({workspaceId:e,activeFilePath:t,onDelete:n,onCreateDirectory:r,onActiveFileChange:s,readOnlyPaths:i,searchFiles:o=!0,searchSkills:l=!0,fileCount:c,skillCount:u,addSkill:d,children:f}){const[h,p]=g.useState(!1),[m,v]=g.useState(""),[y,x]=g.useState(()=>new Set(Ynt(t??""))),[b,S]=g.useState(t);if(t!==b){S(t);const C=Ynt(t??"").filter(T=>!y.has(T));C.length>0&&x(new Set([...y,...C]))}const k=i?.join(`
699
+ `).reduce((i,o)=>{if(!o||o.startsWith("#"))return i;const[l,c]=o.split("=");return l&&(i[l]=c?.split("")?.every(u=>u==="*")?"":c?.replaceAll('"',"")),i},{}):{}}const ZAs=({queryOptions:e}={})=>Ct({queryKey:["mastra-templates"],queryFn:FQt,...e}),WAs=({repoOrSlug:e,owner:t,queryOptions:n})=>Ct({queryKey:["template-repo",e,t],queryFn:()=>qAs({repoOrSlug:e,owner:t}),...n}),HAs=({repo:e,owner:t,branch:n,queryOptions:r})=>Ct({queryKey:["template-repo-env-vars",e,t,n],queryFn:()=>QAs({repo:e,owner:t,branch:n}),...r}),GAs=({queryOptions:e}={})=>{const t=Ke();return Ct({queryKey:["agent-builder-workflow"],queryFn:async()=>await t.getAgentBuilderAction("merge-template").details(),...e})},KAs=({queryOptions:e}={})=>{const t=Ke();return wn({mutationFn:async({runId:n})=>await t.getAgentBuilderAction("merge-template").createRun({runId:n}),...e})},YAs=({queryOptions:e}={})=>{const t=Ke();return wn({mutationFn:async({runId:n})=>await t.getAgentBuilderAction("merge-template").runById(n),...e})},Vnt=e=>{if(typeof e=="string")return e;if(e==null)return"Unknown error";if(e instanceof Error)return typeof e.message=="string"&&e.message.length>0?e.message:"Unknown error";if(typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e)},Unt=(e,t,n)=>{let r={...t};if(!(r.payload?.workflowState?.steps&&Object.keys(r.payload.workflowState.steps).length>0)&&n?.allSteps&&(r.payload={...r.payload,workflowState:{...r.payload?.workflowState,steps:Object.keys(n.allSteps).reduce((s,i)=>(s[i]={id:i,description:n.allSteps[i].description,status:"pending"},s),{})}}),e.type==="start"||e.type==="workflow-start"){const s={};n?.allSteps&&Object.entries(n.allSteps).forEach(([o,l])=>{s[o]={id:l.id,description:l.description,status:"pending"}});const i=e.runId||e.payload?.runId;r={...r,runId:i,eventTimestamp:new Date().toISOString(),status:"running",phase:"initializing",payload:{workflowState:{status:"running",steps:s},currentStep:null}}}if(e.type==="step-start"||e.type==="workflow-step-start"){const s=e.payload.id;r={...r,phase:"processing",payload:{...r.payload,currentStep:{id:s,status:"running",startTime:new Date,...e.payload},workflowState:{...r.payload.workflowState,steps:{...r.payload.workflowState.steps,[s]:{...r.payload.workflowState.steps[s],status:"running",startTime:new Date,...e.payload}}}}}}if(e.type==="step-result"||e.type==="workflow-step-result"){const s=e.payload.id,i=e.payload.status,o=e.payload.error;if(r={...r,payload:{...r.payload,currentStep:{...r.payload.currentStep,status:e.payload.status,output:e.payload.output,error:e.payload.error,endTime:new Date},workflowState:{...r.payload.workflowState,steps:{...r.payload.workflowState.steps,[s]:{...r.payload.workflowState.steps[s],status:e.payload.status,output:e.payload.output,error:e.payload.error,endTime:new Date}}}}},i==="failed"&&o){const l=Vnt(o);r={...r,status:"failed",error:l,phase:"error",failedStep:{id:s,error:l,description:e.payload.description||s},payload:{...r.payload,workflowState:{...r.payload.workflowState,status:"failed"}},errorTimestamp:new Date}}}if((e.type==="step-finish"||e.type==="workflow-step-finish")&&(r={...r,payload:{...r.payload,currentStep:null}}),(e.type==="finish"||e.type==="workflow-finish")&&(r.phase==="error"||r.status==="failed"?r={...r,completedAt:new Date}:r={...r,status:e.payload.status||"completed",phase:"completed",payload:{...r.payload,currentStep:null,workflowState:{...r.payload.workflowState,status:e.payload.status||"completed"}},completedAt:new Date}),e.type==="error"){const s=Vnt(e.payload.error);r={...r,status:"failed",error:s,phase:"error",payload:{...r.payload,workflowState:{...r.payload.workflowState,status:"failed"}},errorTimestamp:new Date}}return{newState:r}},XAs=(e,t)=>{try{localStorage.setItem(`template-install-${e}`,JSON.stringify({state:t,timestamp:Date.now()}))}catch(n){console.warn("Failed to save template state to localStorage:",n)}},BQt=(e,t)=>{const[n,r]=g.useState({}),[s,i]=g.useState(!1);return{streamResult:n,isStreaming:s,processStream:async(l,c)=>{if(i(!0),r({}),!l)throw new Error("No stream returned");const u=l.getReader();let d={runId:c||t,eventTimestamp:new Date().toISOString(),phase:"running",payload:{workflowState:{steps:{}},currentStep:null}};try{for(;;){const{done:f,value:h}=await u.read();if(f)break;const{newState:p}=Unt(h,d,e);if(d=p,r(p),h.runId||c||t){const m=h.runId||c||t;XAs(m,p)}}}catch(f){console.error("💥 [processStream] Error processing template installation stream:",f);const{newState:h}=Unt({type:"error",payload:{error:f instanceof Error?f.message:"Unknown error"}},d,e);r(h)}finally{i(!1),u.releaseLock()}}}},JAs=({workflowInfo:e,queryOptions:t}={})=>{const n=Ke(),{streamResult:r,isStreaming:s,processStream:i}=BQt(e);return{streamInstall:wn({mutationFn:async({inputData:o,selectedModel:l,runId:c})=>{for(let d=1;d<=3;d++)try{const f=n.getAgentBuilderAction("merge-template"),h=new f_;h.set("selectedModel",l);const p=await f.stream({inputData:o,requestContext:h},c);await i(p,c);return}catch(f){console.error(`💥 [streamInstall] Attempt ${d} failed:`,f);const h=f?.message?.includes("Failed to fetch")||f?.message?.includes("NetworkError")||f?.message?.includes("network error")||f?.message?.includes("fetch")||f?.code==="NETWORK_ERROR"||f?.name==="TypeError";if(console.warn(`Stream attempt ${d}/3 failed:`,f),h){const p=c?`Network error during template installation (likely hot reload). Please refresh the page to resume from where you left off using runId: ${c}`:"Network error during template installation (likely hot reload). Please try again.";throw console.error("🔌 Stream network error:",p),new Error(p)}throw console.error("❌ [streamInstall] Non-network error or max retries reached, throwing:",f),f}},...t?.streamInstall}),streamResult:r,isStreaming:s}},ePs=({workflowInfo:e,queryOptions:t}={})=>{const n=Ke(),{streamResult:r,isStreaming:s,processStream:i}=BQt(e);return{observeInstall:wn({mutationFn:async({runId:o})=>{for(let u=1;u<=3;u++)try{const d=await n.getAgentBuilderAction("merge-template").observeStream({runId:o});await i(d,o);return}catch(d){console.error(`💥 [observeInstall] Attempt ${u} failed:`,d);const f=d?.message?.includes("Failed to fetch")||d?.message?.includes("NetworkError")||d?.message?.includes("network error")||d?.message?.includes("fetch")||d?.code==="NETWORK_ERROR"||d?.name==="TypeError";if(console.warn(`ObserveStream attempt ${u}/3 failed:`,d),f&&u<3){console.info(`🔄 ObserveStream network error detected (likely hot reload), retrying in 2000ms... (attempt ${u+1}/3)`),await new Promise(h=>setTimeout(h,2e3));continue}throw console.error("❌ [observeInstall] Non-network error or max retries reached, throwing:",d),d}},...t?.observeInstall}),streamResult:r,isStreaming:s}};function tPs(e){return e.replace(/\/$/,"").split("/").pop()}function nPs({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?a.jsx("div",{className:Z("grid gap-y-4",n),children:Array.from({length:5}).map((i,o)=>a.jsx("div",{className:"h-16 animate-pulse rounded-lg bg-card"},o))}):a.jsx("div",{className:Z("grid gap-y-4",n),children:e.map(i=>{const o=i?.agents||i?.tools||i?.networks||i?.workflows||i?.mcp;return a.jsxs("article",{className:Z(pr,"state-layer grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg"),children:[a.jsxs(s,{to:`/templates/${i.slug}`,className:Z("group grid",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":i.imageURL}),children:[i.imageURL&&a.jsx("div",{className:"overflow-hidden",children:a.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${i.imageURL})`}})}),a.jsxs("div",{className:Z("grid w-full gap-0.5 px-4 py-3","[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground"),children:[a.jsx(Y,{as:"h2",tone:"ink",children:i.title}),a.jsx(Y,{className:Z(xx,In),children:i.description}),a.jsxs("div",{className:"mt-3 hidden flex-wrap items-center gap-4 text-muted-foreground 2xl:flex",children:[o&&a.jsxs("ul",{className:Z("text-muted-foreground","m-0 flex list-none gap-4 p-0","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5"),children:[i?.agents&&i.agents.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(Vo,{})," ",i.agents.length]})}),i?.tools&&i.tools.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(fd,{})," ",i.tools.length]})}),i?.networks&&i.networks.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(vpt,{})," ",i.networks.length]})}),i?.workflows&&i.workflows.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(wk,{})," ",i.workflows.length]})}),i?.mcp&&i.mcp.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(F_,{})," ",i.mcp.length]})})]}),o&&i.supportedProviders&&a.jsx("small",{children:a.jsx(Y,{as:"span",variant:"body",children:"|"})}),a.jsx("div",{className:"flex items-center gap-4",children:i.supportedProviders.map(l=>a.jsx(Y,{tone:"muted",as:"span",variant:"body",children:l},l))})]})]})]}),a.jsx("a",{href:i.githubUrl,className:Z("group ml-auto hidden items-center gap-2 pr-4","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:a.jsx(Y,{as:"span",variant:"body",children:a.jsxs("span",{className:Z("flex items-center gap-2 rounded bg-sidebar px-2 py-1",Eht,xx,In),children:[a.jsx(TX,{})," ",tPs(i.githubUrl)]})})})]},i.slug)})})}function rPs({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:i,searchTerm:o,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?a.jsxs("div",{className:Z("flex h-[6.5rem] items-center gap-5","[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card",u),children:[a.jsx("div",{})," ",a.jsx("div",{})," ",a.jsx("div",{})]}):a.jsxs("div",{className:Z("sticky top-0 mx-auto flex flex-wrap gap-4 bg-background py-5",u),children:[a.jsx(Zc,{label:"Search templates",placeholder:"Search Template",value:o,onValueChange:l}),a.jsxs(ms,{value:t,onValueChange:s,children:[a.jsx(vs,{"aria-label":"Filter by tag",size:"md",children:a.jsx(gs,{placeholder:"Select an option"})}),a.jsx(ys,{children:e.map(f=>a.jsx(hr,{value:f.value,children:f.label},f.value))})]}),a.jsxs(ms,{value:r,onValueChange:i,children:[a.jsx(vs,{"aria-label":"Filter by provider",size:"md",children:a.jsx(gs,{placeholder:"Select an option"})}),a.jsx(ys,{children:n.map(f=>a.jsx(hr,{value:f.value,children:f.label},f.value))})]}),c&&a.jsx(ce,{onClick:c,icon:a.jsx(Mn,{}),children:"Reset"})]})}const sPs=[{id:"templates",label:"Templates"}];function iPs(){const{data:e,isLoading:t}=ZAs(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[i,o]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(b=>{f.push({value:b,label:b})});const h=[{value:"all",label:"Any provider"}];(s||[]).forEach(b=>{h.push({value:b,label:b})});const p=(b,S)=>{S==="tag"?o(b):S==="provider"&&c(b)},m=b=>{d(b)},v=()=>{o("all"),c("all"),d("")},y=n.filter(b=>!(u&&!b.title.toLowerCase().includes(u)&&!b.description.toLowerCase().includes(u)||i!=="all"&&!b.tags.includes(i)||l!=="all"&&!b.supportedProviders.includes(l))),x=u||i!=="all"||l!=="all";return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:sPs}),children:[a.jsx("h1",{className:"sr-only",children:"Templates"}),a.jsx(vL,{children:a.jsxs(Mpt,{children:[a.jsx(At,{children:a.jsx(X1,{})}),"Templates"]})}),a.jsxs("div",{className:Z("z-10 h-full w-full overflow-y-auto px-5 pb-12"),children:[a.jsx(rPs,{selectedTag:i,onTagChange:b=>p(b,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:b=>p(b,"provider"),providerOptions:h,searchTerm:u,onSearchChange:m,onReset:x?v:void 0,className:"max-w-[80rem]",isLoading:t}),a.jsx(nPs,{templates:y,linkComponent:lc,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const oPs="1.78.0-alpha.7";function See({children:e,className:t}){return a.jsx("div",{className:Z("transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12",t),children:e})}function aPs({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,i=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",o=()=>s?{icon:a.jsx(Xd,{className:"text-warning-foreground"}),title:"Template Installed with Warnings"}:{icon:a.jsx(qTn,{}),title:"Template Installation Failed"},{icon:l,title:c}=o();return a.jsxs(See,{className:"mb-5 content-center space-y-4 text-muted-foreground",children:[a.jsxs("div",{className:"grid content-center items-center justify-items-center gap-4 [&>svg]:h-8 [&>svg]:w-8",children:[l,a.jsxs("div",{className:"space-y-2 text-center",children:[a.jsx(Y,{variant:"subheading",tone:"ink",children:c}),a.jsx(Y,{tone:"muted",children:i()})]})]}),t&&t.length>0&&a.jsxs("details",{children:[a.jsx("summary",{className:Z(Zn,"cursor-pointer text-center select-none"),children:a.jsxs(Y,{as:"span",variant:"caption",className:"block",children:["Show Validation Issues (",t.length,")"]})}),a.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-muted p-3 text-left",children:t.map((u,d)=>a.jsxs("div",{className:"border-l-2 border-destructive-indicator pl-2",children:[a.jsx(Y,{as:"p",variant:"column",className:"text-destructive-foreground",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),a.jsx(Cl,{className:"mt-1 text-caption wrap-break-word whitespace-pre-wrap text-muted-foreground",code:u.message})]},d))})]}),n&&!s&&a.jsxs("details",{children:[a.jsx("summary",{className:Z(Zn,"cursor-pointer text-center select-none"),children:a.jsx(Y,{as:"span",variant:"caption",className:"block",children:"Show Details"})}),a.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-muted p-3 text-left",children:a.jsx(Cl,{className:"text-caption wrap-break-word whitespace-pre-wrap",code:n})})]})]})}const lPs=g.createContext(null);function cPs(){const e=g.useContext(lPs);return e||{registerResetFn:()=>{},triggerReset:()=>{}}}const VQt=({defaultProvider:e,defaultModel:t,updateModel:n,resetModel:r})=>{const[s]=g.useState(e),[i]=g.useState(t),[o,l]=g.useState(t),[c,u]=g.useState(e||""),[d,f]=g.useState(!1),[h,p]=g.useState(!1),[m,v]=g.useState(!1),{data:y,isLoading:x}=R6(),b=Y0(),{models:S}=fw(),k=g.useMemo(()=>y?.providers||[],[y]);g.useEffect(()=>{l(t),u(e||"")},[t,e]);const j=io(c),T=KE(k,j)?.id||j,_=async F=>{if(l(F),F&&T){f(!0);try{const Q=await n({provider:T,modelId:F});console.info("Model updated:",Q)}catch(Q){console.error("Failed to update model:",Q)}finally{f(!1)}}},N=F=>{const Q=io(F);u(Q),Q!==j&&(l(""),v(!0))},{registerResetFn:E}=cPs();if(g.useEffect(()=>(E(()=>{if(h||m)return;if(j&&j!==s&&(!o||o==="")){u(io(s)),l(i);const V=KE(k,s)?.id||s;V&&i&&n({provider:V,modelId:i}).catch(W=>{console.error("Failed to reset model:",W)})}}),()=>{E(null)}),[E,j,o,s,i,n,h,m,k]),x)return a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(On,{}),a.jsx(Y,{as:"span",tone:"muted",children:"Loading providers..."})]});const A=async()=>{if(!r){console.warn("Reset model function not provided");return}try{f(!0),await r()}catch(F){console.error("Failed to reset model:",F)}finally{f(!1)}},P=KE(k,j);if(b.active&&b.pickerVisible===!1){const F=b.default&&b.default.provider&&b.default.modelId?`${b.default.provider}/${b.default.modelId}`:c&&o?`${c}/${o}`:"Locked by admin";return a.jsxs("div",{className:Z(pr,"flex items-center gap-2 rounded-md px-3 py-2"),"data-testid":"agent-metadata-model-locked",children:[a.jsx(Nu,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"caption",tone:"ink",className:"truncate",children:F}),a.jsx(Y,{as:"span",variant:"meta",tone:"muted",className:"ml-auto shrink-0",children:"Set by admin"})]})}const L=!!(j&&o)&&b.active&&b.allowed!==void 0&&!S.some(F=>io(F.provider)===j&&F.model===o);return a.jsxs("div",{className:"@container",children:[a.jsxs("div",{className:"flex w-full flex-col items-stretch gap-2 @xs:flex-row @xs:items-center",children:[a.jsx("div",{className:"w-full @xs:w-2/5",children:a.jsx(zk,{value:j,onValueChange:N,open:h,onOpenChange:p})}),a.jsx("div",{className:"w-full @xs:w-3/5",children:a.jsx(Fk,{llmId:j,value:o,onValueChange:_,open:m,onOpenChange:v})}),a.jsx(ce,{variant:"default",size:"md",onClick:A,disabled:d,className:"flex items-center gap-1.5 border-0! whitespace-nowrap",title:"Reset to original model",children:a.jsx(E_,{className:"h-3.5 w-3.5"})})]}),L&&a.jsx("div",{className:"p-2 pt-2","data-testid":"agent-metadata-model-stale-warning",children:a.jsx(Wt,{variant:"warning",title:"Model not allowed",children:a.jsxs(Wt.Message,{children:[a.jsxs("code",{className:"rounded bg-fill-hover px-1 py-0.5",children:[c,"/",o]})," ","is no longer allowed by the admin policy. Pick a different model to save changes."]})})}),P&&!P.connected&&a.jsx("div",{className:"p-2 pt-2",children:a.jsx(Wt,{variant:"warning",title:"Provider not connected",children:a.jsxs(Wt.Message,{children:["Set the"," ",a.jsx("code",{className:"rounded bg-fill-hover px-1 py-0.5",children:Array.isArray(P.envVar)?P.envVar.join(", "):P.envVar})," ","environment"," ",Array.isArray(P.envVar)&&P.envVar.length>1?"variables":"variable"," to use this provider."]})})})]})};function uPs({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:i,handleVariableChange:o,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return a.jsx(See,{children:a.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5",children:[a.jsxs(Y,{as:"h2",variant:"heading",tone:"muted",className:Z("flex items-center gap-2","[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]"),children:["Install Template ",a.jsx(ypt,{})]}),a.jsxs(pt,{orientation:"horizontal",children:[a.jsx(dt,{children:"Template AI Model Provider"}),a.jsx(ayt,{className:"flex-1",children:a.jsxs(ms,{name:"template-provider",value:t,onValueChange:n,children:[a.jsx(vs,{size:"md",children:a.jsx(gs,{placeholder:"Select"})}),a.jsx(ys,{children:e.map(h=>a.jsx(hr,{value:h.value,children:h.label},h.value))})]})})]}),t&&Object.entries(r||{}).length>0&&a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h3",tone:"muted",children:"Set required Environmental Variables"}),a.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?a.jsxs("div",{className:Z("text-muted-foreground","col-span-2 flex items-center justify-center gap-4","[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50","animate-in duration-300 fade-in"),children:[a.jsx(On,{}),a.jsxs(Y,{as:"span",variant:"caption",className:"block",children:[" ","Loading variables..."]})]}):Object.entries(r).map(([h,p])=>a.jsxs(g.Fragment,{children:[a.jsxs(pt,{className:"w-full",children:[a.jsx(dt,{className:"sr-only",children:"Key"}),a.jsx(bn,{name:`env-${h}`,value:h,disabled:!0,className:"w-full"})]}),a.jsxs(pt,{invalid:s.includes(h),className:"w-full",children:[a.jsx(dt,{className:"sr-only",children:"Value"}),a.jsx(bn,{name:h,value:p,onChange:o,autoComplete:"off",className:"w-full"}),a.jsx(ns,{children:s.includes(h)?"Value is required.":void 0})]})]},h))}),a.jsxs("div",{className:"relative mt-3.5 border-t border-border pt-12",children:[a.jsx("div",{className:"absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full bg-background",children:a.jsx(Y,{tone:"muted",as:"span",variant:"caption",className:"block",children:"And"})}),a.jsx(Y,{as:"h3",tone:"muted",children:"Set AI Model for Template Installation"}),a.jsx(Y,{tone:"muted",className:"mt-2 mb-5",children:"This model will be used by the workflow to process and install the template"}),a.jsx(VQt,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&a.jsx(ce,{className:Z("state-layer mt-4 flex min-h-10 w-full items-center justify-center gap-2 rounded-lg bg-card text-foreground","[&_svg]:h-[1.1em] [&_svg]:text-foreground [&>svg]:w-[1.1em]"),onClick:i,disabled:!t||!u||!d||s.length>0||c,children:c?a.jsxs(a.Fragment,{children:[a.jsx(On,{className:"h-4 w-4"})," Installing..."]}):a.jsxs(a.Fragment,{children:["Install ",a.jsx(dp,{})]})})]})})}function dPs({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:i}){const o=i?`feat/install-template-${i}`:"feat/install-template-[slug]";return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"mt-5 grid items-center",children:a.jsxs("div",{className:Z("flex items-center gap-3","[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[a.jsx(X1,{}),a.jsx("h2",{className:Z({"flex min-w-[50%] rounded-lg bg-muted":r}),children:a.jsx(Y,{as:"span",variant:"title",className:"block",children:r?a.jsx(a.Fragment,{children:" "}):e})})]})}),a.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[a.jsxs("div",{className:"grid",children:[a.jsx(Y,{tone:"muted",className:Z("mt-2 mb-4",{"rounded-lg bg-muted":r}),children:r?a.jsx(a.Fragment,{children:" "}):t}),!r&&i&&a.jsxs("div",{className:Z("mb-4 rounded-lg border border-border bg-background p-4","flex items-start gap-3"),children:[a.jsx("div",{className:"mt-0.5 shrink-0",children:a.jsx(yv,{className:"h-[1.1em] w-[1.1em] text-info-indicator"})}),a.jsxs("div",{className:"flex-1 space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(PN,{className:"h-[1em] w-[1em] text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",children:"A new Git branch will be created"})]}),a.jsxs("div",{className:"space-y-1",children:[a.jsxs(Y,{tone:"muted",as:"p",variant:"caption",children:[a.jsx(Y,{as:"span",variant:"column",children:"Branch name:"})," ",a.jsx(rh,{children:o})]}),a.jsx(Y,{tone:"muted",as:"p",variant:"caption",children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&a.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:Z(Zn,"mt-auto flex items-center gap-2"),children:[a.jsx(TX,{}),a.jsx(Y,{as:"span",variant:"body",className:"block",children:n?.split("/")?.pop()})]})]}),s&&a.jsx(oNe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function qnt(e){switch(e){case"running":return a.jsx(On,{size:"sm","aria-hidden":!0});case"success":return a.jsx(ur,{"aria-hidden":!0});case"failed":return a.jsx(Mn,{"aria-hidden":!0});default:return null}}function fPs(){return a.jsx("svg",{viewBox:"0 0 24 24",className:"text-placeholder","aria-hidden":!0,children:a.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function hPs({status:e,variant:t}){return t==="plain"?a.jsx("span",{className:Z("flex size-4 items-center justify-center self-center [&>svg]:size-4",Mi.colors,{"[&>svg]:text-success-indicator":e==="success","[&>svg]:text-destructive-foreground":e==="failed"}),children:e==="pending"?a.jsx(fPs,{}):qnt(e)}):a.jsx("span",{className:Z("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Mi.colors,Mi.transform,{"[&>svg]:text-success-indicator":e==="success","[&>svg]:text-destructive-foreground":e==="failed","border border-dashed border-placeholder":e==="pending","[&>svg]:size-4":e!=="running","bg-success-subtle":e==="success","bg-destructive-subtle":e==="failed","scale-110":e==="success"||e==="failed"}),children:qnt(e)})}function pPs({step:e,isActive:t,position:n,variant:r="default"}){const s=t||e.status==="success"?"ink":"muted";return a.jsxs("div",{className:Z("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",Mi.colors,{"border border-transparent":r==="default","border-dashed border-placeholder bg-card":t&&r==="default"}),children:[a.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[a.jsxs(Y,{as:"span",tone:s,className:Z("flex min-w-6 justify-end",Mi.colors),children:[n,"."]}),a.jsxs("div",{className:"min-w-0",children:[a.jsx(Y,{as:"h4",tone:s,className:Mi.colors,children:e.title}),e.description&&a.jsx(Y,{tone:"faint",className:Z("-mt-0.5",{truncate:r==="plain"}),children:e.description})]})]}),a.jsx(hPs,{status:e.status,variant:r})]})}function mPs({currentStep:e,steps:t=[],className:n}){return a.jsx("div",{className:Z(n),children:t.map((r,s)=>a.jsx(pPs,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function gPs({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return a.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[a.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>a.jsx("div",{className:Z("relative flex h-8 items-center justify-end",Mi.colors,{"bg-success-subtle":r.status==="success"&&e?.[s-1]?.status==="success"}),children:a.jsx("div",{className:Z("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-fill text-column text-muted-foreground motion-reduce:transition-none",Mi.colors,Mi.transform,{"border border-dashed border-placeholder":r.status==="pending","scale-110 bg-success-subtle text-success-subtle-foreground":r.status==="success","scale-110 bg-destructive-subtle text-destructive-subtle-foreground":r.status==="failed"}),children:r.status==="running"?a.jsx(On,{}):s+1})},r.id))}),a.jsxs("div",{className:Z("text-center text-caption text-muted-foreground",Mi.colors),children:[n," of ",t," steps completed"]})]})}function vPs({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",i=t?.payload?.workflowState,o=t?.payload?.currentStep,l=t?.error,c=i?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),h=f.length,p=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:o?.id===v}));return a.jsxs(See,{className:"mb-5 content-center space-y-6 text-muted-foreground",children:[a.jsxs("div",{className:"text-center",children:[a.jsx(Y,{as:"h3",variant:"heading",tone:"ink",children:p()}),(t?.runId||n)&&a.jsxs(Y,{as:"p",variant:"caption",tone:"muted",className:"mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&h>0&&!["error"].includes(s)&&a.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-4",children:a.jsx(gPs,{steps:m})}),l&&s==="error"&&a.jsxs("div",{className:Z("text-foreground","flex items-center gap-3 rounded-lg bg-destructive-subtle p-4","[&>svg]:h-6 [&>svg]:w-6 [&>svg]:text-destructive-foreground [&>svg]:opacity-70"),children:[a.jsx(zEn,{}),a.jsx(Y,{as:"span",variant:"body",className:"block",children:l||"Something went wrong"})]}),u&&a.jsx(mPs,{steps:m,currentStep:o,className:"pb-4"}),!u&&s==="initializing"&&a.jsxs("div",{className:Z("text-muted-foreground","grid justify-items-center gap-4 text-center"),children:[a.jsx(On,{}),a.jsx(Y,{as:"p",variant:"body",children:"This may take some time..."})]})]})}function yPs({name:e,installedEntities:t}){return a.jsxs(See,{className:Z("grid content-center items-center justify-items-center gap-4","[&>svg]:h-8 [&>svg]:w-8"),children:[a.jsx(ypt,{}),a.jsx(Y,{as:"h2",variant:"heading",children:"Done!"}),a.jsxs(Y,{tone:"muted",className:"text-center",children:["The ",a.jsx("b",{className:"text-muted-foreground",children:e})," template has been successfully installed.",t&&t.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&a.jsx(oNe,{data:t})]})}function xPs(){const{templateSlug:e}=Cr(),t=[{id:"templates",label:"Templates",to:"/templates"},{id:"template",label:Zke(e)}],[n,r]=wi(),[s,i]=g.useState(""),[o,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState({}),[h,p]=g.useState([]),[m,v]=g.useState(null),[y,x]=g.useState(!1),[b,S]=g.useState(""),[k,j]=g.useState(!1),[C,T]=g.useState(!1),[_,N]=g.useState([]),{data:E,isLoading:A}=WAs({repoOrSlug:e,owner:"mastra-ai"}),L=oPs?.includes("beta")??!1?"beta":"main",{data:F,isLoading:Q}=HAs({repo:E?.githubUrl?new URL(E.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:L}),{data:q,isLoading:B}=GAs(),{mutateAsync:V,isPending:W}=KAs(),{mutateAsync:M}=YAs(),{streamInstall:K,streamResult:D,isStreaming:$}=JAs({workflowInfo:q}),{observeInstall:z,streamResult:U,isStreaming:G}=ePs({workflowInfo:q});g.useEffect(()=>{const se=n.get("runId");se&&!y&&!m&&!$&&!G&&(console.info("🔄 Checking completed run after hot reload:",{runId:se}),S(se),M({runId:se}).then(ae=>{const he=ae.snapshot;if(he?.status==="success"&&he?.result?.success)x(!0);else if(he?.result?.success===!1)if(he?.result?.validationResults&&!he?.result?.validationResults?.valid&&he?.result?.validationResults?.remainingErrors>0){const{remainingErrors:me,errors:ke}=he.result.validationResults,Ee=`Template installation completed but ${me} validation issue${me>1?"s":""} remain unresolved.`;v(Ee),N(ke||[])}else{const me=he?.result?.message||he?.result?.error||"Template installation failed";v(typeof me=="string"?me:String(me))}}).catch(ae=>{console.error("❌ Failed to fetch run details:",ae),v("Failed to retrieve installation status after reload")}))},[n,y,m,$,G,M]),g.useEffect(()=>{const se=n.get("runId"),ae=n.get("resume"),he=n.get("provider");if(se&&ae==="true"&&he&&!$&&!G&&!k&&!C&&q){S(se),j(!0);try{M({runId:se}).then(ge=>{if(ge.snapshot?.status==="running")return z.mutateAsync({runId:se})}).then(()=>{r(ge=>{const me=new URLSearchParams(ge);return me.delete("resume"),me})}).catch(ge=>{console.error("❌ Failed to resume template installation:",ge),ge.message?.includes("404")||ge.message?.includes("not found")?v("Template installation run not found. It may have expired or been completed."):v("Failed to resume template installation. Please try again.")})}catch(ge){console.error("❌ Auto-resume failed with error:",ge),v("Failed to resume template installation. Please refresh and try again.")}}},[n,e,$,G,k,C,q,M,z,r]);const ne=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],X=[{key:"tools",label:"Tools",value:E?.tools?.length?E.tools.map(se=>se).join(", "):"n/a",icon:a.jsx(fd,{})},{key:"agents",label:"Agents",value:E?.agents?.length?E.agents.map(se=>se).join(", "):"n/a",icon:a.jsx(Vo,{})},{key:"workflows",label:"Workflows",value:E?.workflows?.length?E.workflows.map(se=>se).join(", "):"n/a",icon:a.jsx(wk,{})},{key:"providers",label:"Providers",value:E?.supportedProviders?.length?E.supportedProviders.join(", "):"n/a",icon:a.jsx(_0,{})},{key:"tags",label:"Tags",value:E?.tags?.length?E.tags.join(", "):"n/a",icon:a.jsx(Px,{})}],ee=[{...X[0]},{...X[1]},{...X[2]}].filter(se=>se.value!=="n/a");g.useEffect(()=>{F&&f(F)},[F]),g.useEffect(()=>{const se=D||U;se?.phase==="error"&&se?.error&&v(typeof se.error=="string"?se.error:String(se.error))},[D?.phase,D?.error,U?.phase,U?.error]);const re=se=>{i(se)},ue=async se=>(l(se.provider),u(se.modelId),{message:"Model updated successfully"}),te=async()=>{const se=Object.entries(d).reduce((ae,[he,ge])=>(ge===""&&ae.push(he),ae),[]);if(se.length>0){p(se);return}if(E){v(null),x(!1),S(""),T(!0);try{const he={repo:E.githubUrl||`https://github.com/mastra-ai/template-${E.slug}`,ref:L,slug:E.slug,variables:d},{runId:ge}=await V({});S(ge),r(me=>{const ke=new URLSearchParams(me);return ke.set("runId",ge),ke.set("resume","true"),ke.set("provider",s||"openai"),ke}),await K.mutateAsync({inputData:he,selectedModel:{provider:o,modelId:c},runId:ge})}catch(ae){T(!1),v(ae?.message||"Template installation failed"),console.error("Template installation failed",ae)}}},ie=se=>{const{name:ae,value:he}=se.target;he.trim()===""?p(ge=>[...ge,ae]):p(ge=>ge.filter(me=>me!==ae)),f(ge=>({...ge,[ae]:he}))};return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:Z("h-full w-full overflow-y-scroll lg:px-12"),children:a.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-4",children:[a.jsx(dPs,{isLoading:A,title:E?.title,description:E?.longDescription,imageURL:E?.imageURL,githubUrl:E?.githubUrl,infoData:X,templateSlug:e}),E&&a.jsxs(a.Fragment,{children:[($||G)&&a.jsx(vPs,{name:E.title,streamResult:G?U:D,runId:b,workflowInfo:q}),y&&a.jsx(yPs,{name:E.title,installedEntities:ee,linkComponent:lc}),m&&a.jsx(aPs,{errorMsg:m,validationErrors:_.length>0?_:D?.validationResults?.errors||U?.validationResults?.errors}),!$&&!G&&!y&&!m&&a.jsx(uPs,{providerOptions:ne,selectedProvider:s,onProviderChange:re,variables:d,setVariables:f,errors:h,setErrors:p,handleInstallTemplate:te,handleVariableChange:ie,isLoadingEnvVars:Q||B,isInstalling:W,defaultModelProvider:o,defaultModelId:c,onModelUpdate:ue})]})]})})]})}const bPs=()=>a.jsx(Yt,{titleSlot:"No Workflows yet",descriptionSlot:a.jsxs(a.Fragment,{children:["Mastra workflows are not configured yet. ",a.jsx("br",{}),"More information in the documentation."]}),actionSlot:a.jsx(ce,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/workflows/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Workflows Documentation"}),variant:"fill"});function wPs(e,t,n){return qk(e,t,{name:r=>r.name,running:r=>n[r.id]?.running??0,suspended:r=>n[r.id]?.suspended??0,steps:r=>Object.keys(r.steps??{}).length})}function SPs(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function kPs(e){const t=new Map;for(const[n,r]of Object.entries(e))t.set(n,n),r.name&&t.set(r.name,n);return t}function OPs(e,t,n){const r=kPs(t),s=[],i=(o,l,c,u,d,f)=>{const h=SPs(o).filter(v=>{const y=r.get(v);return y===void 0||!u.has(y)});if(s.push({kind:"workflow",workflow:o,pathKey:l,depth:c,nestedIds:h,guides:d,isLastChild:f}),!n.has(l)||h.length===0)return;const p=new Set(u).add(o.id),m=c===0?[]:[...d,!f];for(const[v,y]of h.entries()){const x=v===h.length-1,b=r.get(y);if(b===void 0){s.push({kind:"unregistered",stepId:y,description:o.allSteps?.[y]?.description,pathKey:`${l}/${y}`,depth:c+1,guides:m,isLastChild:x});continue}const S=t[b];S&&i({...S,id:b},`${l}/${b}`,c+1,p,m,x)}};for(const o of e)i(o,o.id,0,new Set([o.id]),[],!1);return s}const Qnt="auto 24rem minmax(0, 1fr) auto auto auto";function UQt({guides:e,isLastChild:t}){return a.jsxs("span",{"aria-hidden":!0,className:"-my-6 flex shrink-0 self-stretch",children:[e.map((n,r)=>a.jsx("span",{className:Z("w-6",n&&"border-l border-border")},r)),a.jsxs("span",{className:"relative w-6",children:[a.jsx("span",{className:Z("absolute top-0 left-0 border-l border-border",t?"h-1/2":"h-full")}),a.jsx("span",{className:"absolute top-1/2 left-0 w-3.5 border-b border-border"})]})]})}function qQt({row:e,isExpanded:t,onToggle:n}){const r=e.kind==="workflow"&&e.nestedIds.length>0,s=e.kind==="workflow"?e.workflow.name:e.stepId;return a.jsx("div",{className:"flex items-center pl-5",children:r?a.jsx("button",{type:"button","aria-expanded":t,"aria-label":`${t?"Collapse":"Expand"} nested workflows of ${s}`,className:Z(Zn,"relative grid size-5 shrink-0 place-items-center before:absolute before:-inset-1.5 before:content-['']"),onClick:i=>{i.stopPropagation(),n()},children:a.jsx(Ha,{direction:"right",className:"size-4"})}):a.jsx("span",{className:"size-5 shrink-0","aria-hidden":!0})})}const jPs=e=>e.stopPropagation();function nB({sortKey:e,sort:t,onSortChange:n,children:r}){return n?a.jsx(Te.SortableTopCell,{sortKey:e,sort:t?.key===e?t.direction:void 0,onSortChange:s=>n(s,e),children:r}):a.jsx(Te.TopCell,{children:r})}function CPs({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:s}){const{paths:i,Link:o}=Sn(),l=g.useRef(null),{workflow:c,nestedIds:u}=e,d=cf(c.name,50),f=cf(c.description??"",200),h=Object.keys(c.steps??{}).length,p=r?.running??0,m=r?.suspended??0,v=u.length>0;return a.jsxs(Te.RowWrapper,{...s,onSelectRow:()=>l.current?.click(),children:[a.jsx(qQt,{row:e,isExpanded:t,onToggle:n}),a.jsxs(Te.RowLink,{ref:l,colStart:2,to:i.workflowLink(c.id),LinkComponent:o,tabIndex:-1,onClick:jPs,children:[a.jsx(Te.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-1.5",children:[e.depth>0?a.jsx(UQt,{guides:e.guides,isLastChild:e.isLastChild}):null,a.jsx("span",{className:"truncate",children:d}),c.origin==="dynamic"?a.jsx($t,{size:"xs",variant:"blue",title:"Registered via the dynamic-workflows API",children:"Dynamic"}):null,v?a.jsxs(Y,{as:"span",variant:"body-sm",tone:"muted",title:`Nested workflows: ${u.join(", ")}`,className:"inline-flex shrink-0 items-center gap-1",children:[a.jsx(wk,{"aria-hidden":!0,className:"size-3.5"}),u.length]}):null]})}),a.jsx(Te.DescriptionCell,{children:f}),a.jsx(Te.TextCell,{className:"text-center",children:p>0?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-info-indicator","aria-label":`${p} run${p===1?"":"s"} in progress`,children:[a.jsx("span",{"aria-hidden":!0,className:"size-2 rounded-full bg-info-indicator motion-safe:animate-pulse"}),p]}):""}),a.jsx(Te.TextCell,{className:"text-center",children:m>0?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-warning-foreground","aria-label":`${m} run${m===1?"":"s"} awaiting input`,children:[a.jsx(IS,{"aria-hidden":!0,className:"size-3.5"}),m]}):""}),a.jsx(Te.TextCell,{className:"text-center",children:h||""})]})]})}function _Ps({workflows:e,isLoading:t,search:n="",sort:r,onSortChange:s,requestContext:i}){const[o,l]=g.useState(new Set),c=$Dn({requestContext:i}),u=g.useMemo(()=>Object.entries(e).map(([x,b])=>({...b,id:x})),[e]),d=g.useMemo(()=>{const x=n.toLowerCase();return u.filter(b=>b.name?.toLowerCase().includes(x)||b.description?.toLowerCase().includes(x))},[u,n]),f=g.useMemo(()=>wPs(d,r,c),[d,r,c]),h=g.useMemo(()=>OPs(f,e,o),[f,e,o]),p=g.useMemo(()=>{const x=new Map;for(const b of h)b.kind==="workflow"&&x.set(b.pathKey,x.size);return x},[h]),{containerRef:m,getRowProps:v}=Fu({count:p.size,global:!0}),y=x=>{l(b=>{const S=new Set(b);return S.has(x)?S.delete(x):S.add(x),S})};return t?a.jsx(Lu,{columns:Qnt,fit:"container"}):a.jsxs(Te,{columns:Qnt,fit:"container",scrollRef:m,children:[a.jsxs(Te.Top,{children:[a.jsx(Te.TopCell,{children:a.jsx("span",{className:"sr-only",children:"Expand"})}),a.jsx(nB,{sortKey:"name",sort:r,onSortChange:s,children:"Name"}),a.jsx(Te.TopCell,{children:"Description"}),a.jsx(nB,{sortKey:"running",sort:r,onSortChange:s,children:"Running"}),a.jsx(nB,{sortKey:"suspended",sort:r,onSortChange:s,children:"Pending input"}),a.jsx(nB,{sortKey:"steps",sort:r,onSortChange:s,children:"Number of steps"})]}),h.length===0&&n?a.jsx(Te.NoMatch,{message:"No Workflows match your search"}):null,h.map(x=>{const b=o.has(x.pathKey),S=()=>y(x.pathKey);return x.kind==="unregistered"?a.jsxs(Te.RowStatic,{className:"gap-0 px-0",children:[a.jsx(qQt,{row:x,isExpanded:b,onToggle:S}),a.jsxs("div",{className:"col-span-5 col-start-2 grid grid-cols-subgrid gap-4 px-3",children:[a.jsx(Te.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(UQt,{guides:x.guides,isLastChild:x.isLastChild}),a.jsx("span",{className:"truncate",children:cf(x.stepId,50)}),a.jsxs(Qn,{children:[a.jsx(Fn,{render:a.jsx(Y,{as:"span",variant:"body-sm",tone:"muted"}),role:"note",tabIndex:0,className:Z("shrink-0 rounded-sm",bi),children:"not registered"}),a.jsx(Bn,{className:"max-w-72",children:"Runs as a step of its parent workflow. Add it to the workflows of your Mastra instance to open, run, and inspect it on its own page."})]})]})}),a.jsx(Te.DescriptionCell,{children:cf(x.description??"",200)}),a.jsx(Te.TextCell,{className:"text-center",children:""}),a.jsx(Te.TextCell,{className:"text-center",children:""}),a.jsx(Te.TextCell,{className:"text-center",children:""})]})]},`workflow-${x.pathKey}`):a.jsx(CPs,{row:x,isExpanded:b,onToggle:S,runCount:c[x.workflow.id],rowProps:v(p.get(x.pathKey)??-1)},`workflow-${x.pathKey}`)})]})}const VM=[Ts("/workflows")];function TPs(){const{data:e,isLoading:t,error:n}=tg(),[r,s]=g.useState(""),[i,o]=g.useState();return n&&Cs(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:VM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(ci,{variant:"fill"})]}):n&&_s(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:VM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Gs,{variant:"fill",resource:"workflows"})]}):n?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:VM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Yt,{tone:"error",variant:"fill",titleSlot:"Failed to load workflows",descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:VM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(bPs,{})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:VM}),actionRow:a.jsxs(rr,{children:[a.jsx(rr.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(pf,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})})}),a.jsx(rr.End,{children:a.jsx(ce,{render:a.jsx(lc,{to:"/workflows/schedules"}),variant:"primary",icon:a.jsx(T0,{}),children:"Schedules"})})]}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(_Ps,{workflows:e||{},isLoading:t,search:r,sort:i,onSortChange:(l,c)=>o({key:c,direction:l})})]})}const IPs={active:"bg-success-indicator",paused:"bg-info-indicator",completed:"bg-muted-foreground"},EPs={active:"text-success-indicator",paused:"text-info-indicator",completed:"text-muted-foreground"},QQt=({status:e})=>a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${IPs[e]}`,"aria-hidden":!0}),a.jsx(Y,{as:"span",variant:"caption",className:EPs[e],children:e})]});function ZQt({status:e}){const{icon:t,color:n}=NPs(e);return a.jsxs("span",{className:`inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[a.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),a.jsx(Y,{as:"span",variant:"caption",children:e})]})}function NPs(e){switch(e){case"success":return{icon:a.jsx(ur,{size:14}),color:"text-success-indicator"};case"failed":return{icon:a.jsx(Mn,{size:14}),color:"text-destructive-foreground"};case"running":return{icon:a.jsx(On,{}),color:"text-muted-foreground"};case"suspended":return{icon:a.jsx(XH,{size:14}),color:"text-info-indicator"};case"canceled":return{icon:a.jsx(uL,{size:14}),color:"text-muted-foreground"};case"pending":case"waiting":return{icon:a.jsx(fC,{size:14}),color:"text-muted-foreground"};default:return{icon:null,color:"text-muted-foreground"}}}const Znt="auto auto auto auto 1fr",APs=3e4,PPs=5*6e4;function $Ps({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:i}){const{Link:o,paths:l}=Sn(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=Fu({count:u});let h=-1;return t?a.jsx(Lu,{columns:Znt}):e.length===0?a.jsx(Y,{variant:"body",tone:"muted",className:"p-4",children:"No trigger history yet."}):a.jsxs(Te,{columns:Znt,className:"min-w-0",scrollRef:d,children:[a.jsxs(Te.Top,{children:[a.jsx(Te.TopCell,{children:"Run"}),a.jsx(Te.TopCell,{children:"Status"}),a.jsx(Te.TopCell,{children:"Started"}),a.jsx(Te.TopCell,{children:"Duration"}),a.jsx(Te.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=Uc(m,{signed:!0}),y=p.outcome==="failed",x=y?p.error:p.run?.error,b=Math.abs(m),S=!y&&b>APs&&b<=PPs,k=`${p.scheduleId}-${p.runId}-${p.actualFireAt}`,j=c(p);j&&(h+=1);const C=a.jsx(Y,{as:"span",variant:"caption",font:"mono",tone:j?"ink":"muted",className:"whitespace-nowrap",children:p.runId}),T=a.jsxs(a.Fragment,{children:[a.jsx(Te.Cell,{children:C}),a.jsx(Te.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2",children:[y?a.jsxs(Y,{as:"span",variant:"caption",className:"inline-flex items-center gap-1.5 whitespace-nowrap text-destructive-foreground",children:[a.jsx(Xd,{size:14}),"publish failed"]}):p.run?a.jsx(ZQt,{status:p.run.status}):a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),x?a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-destructive-foreground",children:a.jsx(Xd,{size:14})})}),a.jsx(Bn,{children:x})]}):null]})}),a.jsx(Te.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[p.actualFireAt?a.jsx(BE,{value:p.actualFireAt}):"—",S?a.jsxs(Qn,{children:[a.jsx(Fn,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-info-indicator",children:a.jsx(Xd,{size:14})})}),a.jsxs(Bn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),a.jsx(Te.Cell,{children:p.run?a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",children:Uc(p.run.durationMs)||"—"}):a.jsx("span",{className:"text-muted-foreground",children:"—"})}),a.jsx(Te.Cell,{children:" "})]});return j?a.jsx(Te.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:o,...f(h),children:T},k):a.jsx(Te.RowStatic,{children:T},k)}),a.jsx(Te.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:i})]})}const WQt={id:"workflow-schedules",label:"Schedules",icon:T0,to:"/workflows/schedules"};function rB({label:e,children:t}){return a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"uppercase",children:e}),a.jsx("div",{children:a.jsx(Y,{as:"span",variant:"body",className:"block",children:t})})]})}function RPs(){const{scheduleId:e}=Cr(),t=[Ts("/workflows"),WQt,{id:"schedule",label:Zke(e),icon:T0}],{paths:n}=Sn(),{data:r,error:s}=Hur({scheduleId:e,queryOptions:{enabled:!!e}}),{data:i,isLoading:o,error:l,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d}=Gur({scheduleId:e,queryOptions:{enabled:!!e}}),f=Kur({scheduleId:e});if(s&&Cs(s))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(ci,{variant:"fill"})]});if(s&&_s(s))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Gs,{variant:"fill",resource:"schedules"})]});if(s)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Yt,{tone:"error",variant:"fill",titleSlot:"Failed to load schedule",descriptionSlot:s.message})]});const h=r?.workflowId,p=r?.agentId;return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),actionRow:a.jsx(rr,{children:a.jsxs(rr.End,{children:[a.jsx(ce,{render:a.jsx(lc,{to:n.schedulesLink()}),variant:"ghost",icon:a.jsx(vd,{}),children:"Back to schedules"}),h?a.jsx(ce,{icon:a.jsx(jl,{}),render:a.jsx(lc,{to:n.workflowLink(h)}),variant:"ghost",children:"Open workflow"}):null,r?a.jsx(ce,{onClick:()=>{const m=r.status==="active"?"pause":"resume";f.mutate(m,{onSuccess:()=>Xe.success(m==="pause"?"Schedule paused":"Schedule resumed"),onError:v=>Xe.error(v.message)})},disabled:f.isPending,"data-testid":"schedule-toggle-button",children:r.status==="active"?a.jsxs(a.Fragment,{children:[a.jsx(IS,{}),"Pause"]}):a.jsxs(a.Fragment,{children:[a.jsx(Fm,{}),"Resume"]})}):null]})}),children:[a.jsx("h1",{className:"sr-only",children:e}),r?a.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-4 overflow-hidden",children:[a.jsxs("div",{className:"flex h-fit flex-col gap-4 rounded-md border border-border p-4",children:[a.jsx(rB,{label:p?"Agent":"Workflow",children:h?a.jsx(lc,{to:n.workflowLink(h),className:"text-foreground hover:underline",children:h}):p?a.jsx(lc,{to:n.agentLink(p),className:"text-foreground hover:underline",children:p}):"—"}),a.jsxs(rB,{label:"Cron",children:[a.jsx(Y,{as:"span",variant:"body",font:"mono",children:r.cron}),r.timezone?a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"ml-2",children:r.timezone}):null]}),a.jsx(rB,{label:"Status",children:a.jsx(QQt,{status:r.status})}),a.jsx(rB,{label:"Next fire",children:r.nextFireAt?a.jsx(BE,{value:r.nextFireAt}):"—"})]}),a.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[a.jsx(Y,{variant:"body",className:"mb-3",children:"Trigger history"}),l?a.jsx(Yt,{tone:"error",titleSlot:"Failed to load trigger history",descriptionSlot:l.message}):a.jsx($Ps,{triggers:i??[],isLoading:o,workflowId:h,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d})]})]}):null]})}const MPs={target:e=>e.workflowId??e.agentId??"",status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},Wnt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function DPs({schedules:e,isLoading:t,search:n="",sort:r,onSortChange:s}){const{paths:i,Link:o}=Sn(),l=g.useMemo(()=>{const f=n.toLowerCase(),h=f?e.filter(p=>p.id.toLowerCase().includes(f)||(p.workflowId??p.agentId??"").toLowerCase().includes(f)):e;return qk(h,r,MPs)},[e,n,r]),{containerRef:c,getRowProps:u}=Fu({count:l.length,global:!0});if(t)return a.jsx(Lu,{columns:Wnt});const d=(f,h)=>s?a.jsx(Te.SortableTopCell,{sortKey:f,sort:r?.key===f?r.direction:void 0,onSortChange:s,children:h}):a.jsx(Te.TopCell,{children:h});return a.jsxs(Te,{columns:Wnt,className:"min-w-0",scrollRef:c,children:[a.jsxs(Te.Top,{children:[d("target","Target"),a.jsx(Te.TopCell,{children:"Schedule ID"}),a.jsx(Te.TopCell,{children:"Cron"}),d("status","Status"),d("nextFireAt","Next fire"),d("lastFireAt","Last run")]}),l.length===0&&n?a.jsx(Te.NoMatch,{message:"No schedules match your search"}):null,l.length===0&&!n?a.jsx(Te.NoMatch,{message:"No schedules configured"}):null,l.map((f,h)=>a.jsxs(Te.RowLink,{to:i.scheduleLink(f.id),LinkComponent:o,...u(h),children:[a.jsx(Te.NameCell,{children:f.workflowId??f.agentId}),a.jsx(Te.Cell,{className:"min-w-0",children:a.jsx(Y,{as:"span",variant:"body-sm",tone:"muted",font:"mono",className:"block truncate",title:f.id,children:f.id})}),a.jsx(Te.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx(Y,{as:"span",variant:"caption",font:"mono",children:f.cron}),f.timezone?a.jsx(Y,{as:"span",variant:"meta",tone:"muted",children:f.timezone}):null]})}),a.jsx(Te.Cell,{children:a.jsx(QQt,{status:f.status})}),a.jsx(Te.Cell,{children:f.nextFireAt?a.jsx(BE,{value:f.nextFireAt}):"—"}),a.jsx(Te.Cell,{children:f.lastRun?a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx(ZQt,{status:f.lastRun.status}),f.lastFireAt?a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:a.jsx(BE,{value:f.lastFireAt})}):null]}):f.lastFireAt?a.jsx(BE,{value:f.lastFireAt}):a.jsx("span",{className:"text-muted-foreground",children:"Never"})})]},f.id))]})}function HQt({workflowId:e}={}){const{data:t,isLoading:n,error:r}=DK(e?{workflowId:e}:{}),[s,i]=g.useState(""),[o,l]=g.useState();return r?a.jsx(Yt,{tone:"error",titleSlot:"Failed to load schedules",descriptionSlot:r.message}):a.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[a.jsx("div",{className:"max-w-120",children:a.jsx(pf,{onSearch:i,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),a.jsx("div",{className:"overflow-y-auto",children:a.jsx(DPs,{schedules:t??[],isLoading:n,search:s,sort:o,onSortChange:(c,u)=>l({key:u,direction:c})})})]})}const Mue=[Ts("/workflows"),WQt];function LPs(){const[e]=wi(),t=e.get("workflowId")??void 0,{error:n}=DK(t?{workflowId:t}:{});return n&&Cs(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Mue}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(ci,{variant:"fill"})]}):n&&_s(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Mue}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(Gs,{variant:"fill",resource:"schedules"})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Mue}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx("div",{className:"h-full",children:a.jsx(HQt,{workflowId:t})})]})}const zPs={"--belt-hue":"var(--warning-indicator)"};function FPs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function BPs(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e),[r]=n;if(n.length===1&&r)return r}return t}function VPs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:a.jsxs("section",{className:Z(Eke,"pointer-events-auto relative isolate"),"data-testid":"workflow-suspended-steps","aria-label":"Step suspended",children:[a.jsxs("div",{className:"max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]",children:[a.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border bg-background px-5 py-4",children:[a.jsxs(Y,{as:"h2",variant:"column",tone:"ink",className:"flex items-center gap-2",children:[a.jsx(At,{children:a.jsx(XH,{})}),"Step suspended"]}),a.jsx($t,{variant:"orange",emphasis:"subtle",children:"Needs input"})]}),e.map(s=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const o=i?.resumeSchema?MS(hC(i.resumeSchema)):Ef(_n(),Ff());return a.jsx(UPs,{step:s,stepSchema:o,description:i.description,onResume:r},`${s.runId}-${s.stepId}`)})]}),a.jsx(C5t,{status:"ready",label:"Needs input",className:"before:hidden",style:zPs})]})}function UPs({step:e,stepSchema:t,description:n,onResume:r}){const[s,i]=g.useState(!1),[o,l]=g.useState(!1),c=async u=>{l(!0);try{await r({stepId:e.stepId.split("."),runId:e.runId,resumeData:u})}catch(d){Xe.error(d instanceof Error?d.message:"Error resuming workflow")}finally{l(!1)}};return a.jsxs("div",{className:"space-y-5 p-5 [&+&]:border-t [&+&]:border-border",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(Y,{as:"p",variant:"subheading",tone:"ink",className:"break-words",children:e.stepId}),n&&a.jsx(Y,{as:"p",variant:"caption",tone:"muted",children:n})]}),e.suspendPayload!==void 0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs(Y,{as:"p",variant:"caption",tone:"muted",className:"flex items-center gap-2",children:[a.jsx(At,{children:a.jsx(TEn,{})}),"The step is asking"]}),a.jsxs(gc,{open:s,onOpenChange:i,children:[a.jsxs(Gl,{className:Z(pr,"flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5"),children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[a.jsx(At,{children:a.jsx(Ha,{direction:"right",className:"text-muted-foreground"})}),a.jsx(Y,{as:"span",variant:"body",tone:"ink",className:"truncate",children:BPs(e.suspendPayload,e.stepId)})]}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"shrink-0",children:FPs(e.suspendPayload)})]}),a.jsx(Kl,{children:a.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:a.jsx(Or,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs(Y,{as:"p",variant:"caption",tone:"muted",className:"flex items-center gap-2",children:[a.jsx(At,{children:a.jsx(AEn,{})}),"Your response"]}),a.jsx("div",{className:"-mx-5",children:a.jsx(Ske,{schema:t,isSubmitLoading:o,submitButtonLabel:"Resume",submitButtonVariant:"primary",submitButtonIcon:a.jsx(Fm,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:c})})]})]})}function qPs({hidden:e,requestContext:t,canResume:n}){const{result:r,workflow:s,runId:i,isStreamingWorkflow:o}=g.useContext(Wl),l=Qvt(r,i),c=n7n(t),u=r?.status==="suspended"&&l.length>0&&!o;return!s||!u||!n?null:a.jsx("div",{hidden:e,"data-testid":"workflow-suspended-overlay",className:"pointer-events-none absolute top-12 right-2 z-30 w-95 max-w-[calc(100%-16px)] animate-in duration-300 fade-in-0 slide-in-from-top-2 motion-reduce:animate-none",children:a.jsx(VPs,{suspendedSteps:l,workflow:s,isStreaming:o,onResume:c})},i)}const Hnt={success:{label:"Completed",icon:ur},failed:{label:"Failed",icon:cwe},suspended:{label:"Needs input",icon:IS},waiting:{label:"Waiting",icon:yx},paused:{label:"Paused",icon:IS},skipped:{label:"Skipped",icon:ZNn},running:{label:"Running",icon:hc},canceled:{label:"Canceled",icon:uL}},QPs={label:"Status unavailable",icon:aTn};function ZPs({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:s,onOpenInput:i,onOpenOutput:o}){const l=Object.hasOwn(Hnt,e.status)?Hnt[e.status]:QPs,c=l.icon,u=RSe(e.status),d=e.stepId.slice(0,e.stepId.lastIndexOf(".")),f=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(".")+1):e.stepId;return a.jsxs("div",{"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&s(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&s(null),className:Z("grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1","@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2",(t||n)&&"bg-fill-subtle"),children:[a.jsxs("button",{type:"button","aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,className:Z("text-foreground","flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left focus-visible:rounded-sm aria-disabled:cursor-default",bi),children:[a.jsx("span",{"aria-label":l.label,className:Z("grid size-6 flex-none place-items-center rounded-md border border-border bg-background",Q1t[u]),children:a.jsx(c,{"aria-hidden":!0,className:Z("size-3.5",e.status==="running"&&"motion-safe:animate-spin")})}),a.jsxs("span",{className:"min-w-0",children:[a.jsx(Y,{as:"span",variant:"meta",className:"block truncate",children:f}),e.isNestedEntry&&a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",className:"flex min-w-0 items-center gap-1",children:[a.jsx(fwe,{"aria-hidden":!0,className:"size-3 shrink-0"}),a.jsx("span",{className:"truncate",children:d})]})]})]}),a.jsx("div",{className:"relative h-5 min-w-0 overflow-hidden rounded-sm bg-muted @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]","aria-hidden":!0,children:e.timing&&a.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:Z("absolute top-0 h-full min-w-0.5 rounded-sm",HJn[u]),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),a.jsx(Y,{as:"span",variant:"meta",tone:"muted",className:"text-right whitespace-nowrap",title:e.timing&&e.spansSuspension?"Includes time spent suspended waiting for input":void 0,children:e.timing?a.jsx(Y,{as:"span",variant:"meta",font:"mono",children:Uc(e.timing.durationMs)}):a.jsx("span",{"aria-label":"Timing unavailable",children:"—"})}),a.jsxs("div",{className:"flex items-center",children:[a.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:e.step.input===void 0,onClick:h=>i(e,h.currentTarget),children:a.jsx(HH,{})}),a.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:e.step.output===void 0,onClick:h=>o(e,h.currentTarget),children:a.jsx(KH,{})})]})]})}const WPs=e=>e.includes("."),HPs=e=>e==="input"||e.endsWith(".input"),Gnt=1;function GPs(e,t){const n=MSe(e),r=n?.isLive?Math.max(t,n.start):n?.end;return{span:n&&r!==void 0?{start:n.start,end:r}:void 0,isLive:n?.isLive??!1,spansSuspension:n?.spansSuspension??!1}}function KPs(e,t){const n=Object.entries(e).filter(([l])=>!HPs(l)).map(([l,c])=>({stepId:l,step:c,...GPs(c,t)})).sort((l,c)=>(l.span?.start??1/0)-(c.span?.start??1/0)||l.stepId.localeCompare(c.stepId)),r=n.flatMap(l=>l.span?[l.span]:[]),s=Math.min(...r.map(l=>l.start)),i=Math.max(s,...r.map(l=>l.end)),o=Math.max(i-s,1);return n.map(({stepId:l,step:c,span:u,isLive:d,spansSuspension:f})=>{let h;if(u){const p=u.end-u.start,m=Math.min((u.start-s)/o*100,100-Gnt),v=Math.min(Math.max(p/o*100,Gnt),100-m);h={durationMs:p,offsetPct:m,widthPct:v}}return{stepId:l,step:c,status:lK(c)?"suspended":c.status,timing:h,spansSuspension:f,isRunning:d,isNestedEntry:WPs(l)}})}function YPs(){const{steps:e}=m$(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=bG(),[i,o]=g.useState(()=>Date.now()),[l,c]=g.useState(!0),[u,d]=g.useState(!1),{showData:f}=Ek(),h=g.useRef(null),p=KPs(e,i),m=p.some(v=>v.isRunning);return Vpt(h,{enabled:m&&!l}),g.useEffect(()=>{if(!m||l)return;const v=setInterval(()=>o(Date.now()),100);return()=>clearInterval(v)},[m,l]),p.length===0?null:a.jsx("div",{"data-testid":"workflow-timeline",className:"relative z-20 shrink-0 px-2 pb-2",children:a.jsxs(gc,{open:!l,onOpenChange:v=>c(!v),className:Z(pr,"@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl"),children:[a.jsxs("div",{className:"flex items-center",children:[a.jsxs(Gl,{className:"flex min-h-11 min-w-0 flex-1 items-center gap-2 px-3.5 py-2.5 text-caption text-foreground hover:bg-fill-subtle","aria-label":l?"Expand timeline":"Collapse timeline",children:[a.jsx("span",{children:a.jsx(Hht,{"aria-hidden":!0,className:"size-4 text-muted-foreground"})}),a.jsx("span",{children:"Timeline"}),a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",children:[p.length," events"]}),a.jsx("span",{className:"ml-auto",children:a.jsx(Ha,{direction:"right",className:"size-4"})})]}),!l&&a.jsx(ce,{variant:"ghost",size:"icon-sm",tooltip:u?"Restore timeline height":"Enlarge timeline","aria-pressed":u,onClick:()=>d(!u),className:"mr-2 shrink-0",children:u?a.jsx(U_n,{}):a.jsx(Kht,{})})]}),a.jsx(Kl,{children:a.jsx("div",{ref:h,"data-testid":"workflow-timeline-list",className:Z("overflow-auto overscroll-contain px-1.5 pb-1.5",u?"max-h-[min(720px,calc(100dvh-112px))]":"max-h-[min(320px,40dvh)]"),children:p.map(v=>a.jsx(ZPs,{row:v,isSelected:t===v.stepId,isHovered:n===v.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:(y,x)=>f({type:"step-input",stepId:y.stepId},x),onOpenOutput:(y,x)=>f({type:"step-output",stepId:y.stepId},x)},v.stepId))})})]})})}const XPs=({workflowId:e,workflow:t,isLoading:n})=>{const[r]=xr("workflow",e),{canExecute:s,isLoading:i}=Za(),{stepDetail:o}=Ek(),l=Ik(),c=o?.type==="data",u=a.jsxs("div",{className:"[container-type:size] relative h-full min-h-0",children:[a.jsx(U5t,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),a.jsx(qPs,{hidden:c,requestContext:r,canResume:!i&&s("workflows")}),c&&a.jsx("div",{className:"pointer-events-auto absolute top-12 right-2 z-30 flex max-h-[calc(100cqh-64px)] w-[440px] max-w-[calc(100%-16px)] flex-col",children:a.jsx(kV,{requestContext:r})}),a.jsx("div",{className:"pointer-events-none absolute right-0 bottom-0 left-[var(--workflow-left-panel-width,0px)] z-20",children:a.jsx(YPs,{})})]});return l&&o&&!c?a.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:a.jsx(kV,{requestContext:r})}):a.jsxs("div",{className:"relative h-full min-h-0",children:[u,a.jsxs(b$,{className:"pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2",children:[a.jsx(ap,{id:"workflow-graph",className:"pointer-events-none min-w-0"}),o&&!c&&a.jsxs(a.Fragment,{children:[a.jsx(uk,{className:"pointer-events-auto"}),a.jsx(ap,{id:"workflow-step-detail",minSize:300,maxSize:"60%",defaultSize:420,className:"min-w-0",children:a.jsx("div",{className:"pointer-events-auto h-full min-h-0 overflow-hidden rounded-studio-panel border border-border bg-background",children:a.jsx(kV,{requestContext:r})})})]})]})]})},Knt=()=>{const{workflowId:e}=Cr(),{data:t,isLoading:n,error:r}=wL({workflowId:e,requestContext:xr("workflow",e)[0],queryOptions:{enabled:!!e}});return r&&Cs(r)?a.jsx(ci,{variant:"fill"}):r&&_s(r)?a.jsx(Gs,{variant:"fill",resource:"workflows"}):a.jsx(XPs,{workflowId:e,workflow:t??void 0,isLoading:n})};function JPs(){const{workflowId:e}=Cr(),{error:t}=DK(e?{workflowId:e}:{});if(!e)return null;let n;return t&&Cs(t)?n=a.jsx(ci,{variant:"fill"}):t&&_s(t)?n=a.jsx(Gs,{variant:"fill",resource:"schedules"}):n=a.jsx("div",{className:"h-full",children:a.jsx(HQt,{workflowId:e})}),a.jsxs(It,{children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),n]})}function e$s(){const{workflowId:e}=Cr();return e?a.jsx(vAe,{scopedEntityId:e,scopedEntityType:od.WORKFLOW_RUN}):null}const GQt=g.createContext(null);function tu(){const e=g.useContext(GQt);if(!e)throw new Error("Workspace components must be rendered inside <Workspace.Root>");return e}const t$s=e=>e?.status;function n$s(e,t){return Cs(e)?"Your session has expired. Sign in again to continue.":_s(e)?"You don't have permission to access this.":Pk(e)?"This path no longer exists.":t$s(e)===501?"This workspace does not support this operation.":t}function kee({error:e,fallback:t,className:n}){return a.jsx(Wt,{variant:"destructive",className:n,children:a.jsx(Wt.Message,{children:n$s(e,t)})})}const r$s=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function s$s(e){const t=r$s.exec(e);return t?{frontmatter:t[1]??"",body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function i$s({content:e}){const{frontmatter:t,body:n}=s$s(e);return a.jsxs(a.Fragment,{children:[t!==null&&a.jsx("div",{"data-testid":"workspace-frontmatter",className:"border-b border-border",children:a.jsx(l$,{code:t,lang:"yaml",overflow:"wrap",className:"rounded-none border-0 bg-transparent [&_pre]:p-4"})}),a.jsx("div",{className:"p-4",children:a.jsx(_l,{children:n})})]})}function o$s(){const{activeFilePath:e}=tu();return e?a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",tone:"muted",className:"truncate","data-testid":"workspace-file-path",children:e}):null}function a$s({path:e,content:t,mimeType:n}){return IRt(e,n)?a.jsx("div",{className:"flex justify-center p-4",children:a.jsx("img",{src:`data:${n||"image/png"};base64,${t}`,alt:e.split("/").pop(),className:"max-w-full object-contain"})}):ERt(e,n)?a.jsx("div",{className:"flex justify-center p-4",children:a.jsx("video",{controls:!0,"aria-label":e.split("/").pop(),className:"max-w-full",children:a.jsx("source",{src:`data:${LGe(e,n)};base64,${t}`,type:LGe(e,n)})})}):Ozr(e)?a.jsx(i$s,{content:t}):a.jsx(l$,{code:t,lang:cjt(e),overflow:"scroll",className:"rounded-none border-0 bg-transparent [&_pre]:p-4"})}function l$s({renderPreview:e}){const{workspaceId:t,activeFilePath:n}=tu(),{data:r,isLoading:s,error:i}=Pzr({workspaceId:t,path:n,queryOptions:{enabled:!!n}});if(!n)return null;if(s)return a.jsxs("div",{"aria-busy":"true",className:"flex flex-col gap-2 p-4",children:[a.jsx(bt,{className:"h-4 w-1/2"}),a.jsx(bt,{className:"h-4 w-5/6"}),a.jsx(bt,{className:"h-4 w-2/3"})]});if(!r)return a.jsx(kee,{error:i,fallback:"Could not load file.",className:"m-4"});const o={path:n,content:r.content,mimeType:r.mimeType};return e?.(o)??a.jsx(a$s,{...o})}const YA=".",KQt=(e,t)=>e===YA?t:`${e}/${t}`,Ynt=e=>e.split("/").slice(0,-1).map((t,n,r)=>r.slice(0,n+1).join("/")),YQt=e=>{const t=e.lastIndexOf("/");return t===-1?YA:e.slice(0,t)};function XQt({labeled:e=!1}={}){const{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=tu(),s=mr(),[i,o]=g.useState(!1),[l,c]=g.useState(""),[u,d]=g.useState(!1);if(!n||r(YA))return null;const f=l.trim().replace(/^\.?\/+|\/+$/g,""),h=async()=>{if(f){d(!0);try{await n(f),await s.invalidateQueries({queryKey:["workspace",t,"fs","list",YQt(f)]}),o(!1),c("")}catch{}finally{d(!1)}}};return a.jsxs(a.Fragment,{children:[e?a.jsx(ce,{variant:"ghost",icon:a.jsx(_S,{}),onClick:()=>o(!0),children:"New folder"}):a.jsx(ce,{variant:"ghost",size:"icon-sm",tooltip:"New folder",onClick:()=>o(!0),children:a.jsx(_S,{})}),a.jsx(Yr,{open:i,onOpenChange:o,pending:u,children:a.jsx(Xr,{size:"sm",children:a.jsxs("form",{onSubmit:p=>{p.preventDefault(),h()},children:[a.jsx(Jr,{children:a.jsx(Zr,{children:"New folder"})}),a.jsx(Qr,{children:a.jsx(bn,{autoFocus:!0,"aria-label":"Folder path",placeholder:"docs/guides",value:l,onChange:p=>c(p.target.value)})}),a.jsxs(Yo,{children:[a.jsx(_a,{children:"Cancel"}),a.jsx(ce,{type:"submit",variant:"primary",disabled:!f||u,children:"Create"})]})]})})})]})}function Xnt(e){return`${e.topSource}/${e.name}`}function Jnt(e){const t=NRt(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function c$s({open:e,onOpenChange:t,workspaceId:n,onInstall:r,isInstalling:s,installedSkillIds:i=[],installedSkillNames:o=[],writableMounts:l,installedSkillPaths:c}){const[u,d]=g.useState(""),[f,h]=g.useState(null),[p,m]=g.useState(),v=l?.some(Q=>Q.path===p)?p:l?.[0]?.path,{data:y,isLoading:x}=Czr({workspaceId:n,queryOptions:{enabled:!!n}}),b=jzr({workspaceId:n}),S=g.useMemo(()=>f?.topSource?NRt(f.topSource,f.name):null,[f]),k=g.useMemo(()=>!S||!f?null:`https://skills.sh/${S.owner}/${S.repo}/${f.name}`,[S,f]),{data:j,isLoading:C}=_zr({workspaceId:n,owner:S?.owner,repo:S?.repo,skillPath:f?.name,queryOptions:{enabled:!!n&&!!S&&!!f}}),T=uw(Q=>{Q.trim().length>=2&&b.mutate(Q)},300),_=g.useCallback(Q=>{d(Q),T(Q)},[T]),N=g.useMemo(()=>u.trim().length>=2?b.data?.skills??[]:y?.skills??[],[u,b.data,y]),E=b.isPending,A=u.trim().length>=2,P=g.useMemo(()=>{if(!f)return!1;const Q=Jnt(f);return!!(Q&&i.includes(Q)||o.includes(f.name))},[f,i,o]),L=g.useCallback(()=>{!f||!S||r({repository:`${S.owner}/${S.repo}`,skillName:f.name,mount:l&&l.length>1?v:void 0})},[f,S,r,l,v]),F=g.useCallback(Q=>{Q||(d(""),h(null),m(void 0)),t(Q)},[t]);return a.jsx(Yr,{open:e,onOpenChange:F,pending:s,children:a.jsxs(Xr,{size:"xl",className:"h-[80vh]",children:[a.jsxs(Jr,{children:[a.jsx(Zr,{children:"Add Skill"}),a.jsx(Lo,{children:"Search and install skills from the community registry"})]}),a.jsxs(Qr,{layout:"fill",children:[a.jsx(Zc,{label:"Search skills",placeholder:"Search skills...",value:u,onValueChange:_}),a.jsxs("div",{className:"flex min-h-0 flex-1 gap-4",children:[a.jsxs("div",{className:"flex min-h-0 w-1/2 flex-col",children:[a.jsx(Y,{as:"p",variant:"eyebrow",tone:"muted",className:"mb-2",children:A?"Search Results":"Popular Skills"}),a.jsx(jr,{className:"flex-1 rounded-lg border border-border",children:a.jsx(Au,{className:!x&&!E&&N.length===0?"flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col":void 0,children:x||E?a.jsx("div",{className:"flex items-center justify-center py-5",children:a.jsx(hc,{className:"size-6 animate-spin text-muted-foreground"})}):N.length===0?a.jsxs("div",{className:"flex flex-1 flex-col items-center-safe justify-center-safe py-5 text-muted-foreground",children:[a.jsx(uL,{className:"mb-2 size-8"}),a.jsx(Y,{children:A?"No skills found":"No skills available"})]}):a.jsx("div",{className:"space-y-1 p-2",children:N.map(Q=>{const q=Xnt(Q),B=Jnt(Q),V=B&&i.includes(B)||o.includes(Q.name),W=f?Xnt(f):null;return a.jsx("button",{onClick:()=>h(Q),className:Z("w-full rounded-md px-3 py-2 text-left","hover:bg-fill-subtle",W===q&&"border border-border-strong bg-fill-hover"),children:a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",className:"truncate",children:Q.name}),V&&a.jsxs(Y,{as:"span",variant:"meta",className:"inline-flex items-center gap-1 rounded bg-info-subtle px-1.5 py-0.5 text-info-subtle-foreground",children:[a.jsx(ur,{className:"size-2.5"}),"Installed"]})]}),a.jsx(Y,{as:"p",variant:"caption",tone:"muted",className:"truncate",children:Q.topSource})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-1 text-muted-foreground",children:[a.jsx(fp,{className:"size-3"}),a.jsx(Y,{as:"span",variant:"caption",children:Q.installs.toLocaleString()})]})]})},q)})})})})]}),a.jsxs("div",{className:"flex min-h-0 w-1/2 flex-col",children:[a.jsx(Y,{as:"p",variant:"eyebrow",tone:"muted",className:"mb-2",children:"Preview"}),a.jsx("div",{className:"flex flex-1 flex-col overflow-hidden rounded-lg border border-border",children:f?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"border-b border-border bg-card p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"rounded-lg bg-muted p-2",children:a.jsx(q6,{className:"size-5 text-muted-foreground"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx(Y,{as:"h3",variant:"subheading",tone:"ink",className:"truncate",children:f.name}),a.jsxs("div",{className:"mt-1 flex items-center gap-3 text-muted-foreground",children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(TX,{className:"size-3"}),a.jsx(Y,{as:"span",variant:"caption",className:"block",children:f.topSource})]}),a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(fp,{className:"size-3"}),a.jsxs(Y,{as:"span",variant:"caption",className:"block",children:[f.installs.toLocaleString()," installs"]})]})]})]}),S&&a.jsx("a",{href:`https://github.com/${S.owner}/${S.repo}`,target:"_blank",rel:"noopener noreferrer",className:Z(Zn,In),title:"View on GitHub",children:a.jsx(Zs,{className:"size-4"})})]})}),C?a.jsx("div",{className:"flex flex-1 items-center justify-center",children:a.jsx(hc,{className:"size-6 animate-spin text-muted-foreground"})}):j?a.jsx(jr,{className:"flex-1",children:a.jsx("div",{className:"p-4",children:a.jsx(_l,{children:j})})}):a.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-muted-foreground",children:[a.jsx(X1,{className:"mb-2 size-8"}),a.jsx(Y,{children:"Preview unavailable"}),k&&a.jsxs("a",{href:k,target:"_blank",rel:"noopener noreferrer",className:"mt-2 flex items-center gap-1 text-info-indicator hover:underline",children:[a.jsxs(Y,{as:"span",variant:"caption",className:"block",children:["View on skills.sh"," "]}),a.jsx(Zs,{className:"size-3"})]})]})]}):a.jsxs("div",{className:"flex h-full flex-col items-center justify-center text-muted-foreground",children:[a.jsx(X1,{className:"mb-2 size-8"}),a.jsx(Y,{children:"Select a skill to preview"})]})})]})]}),f&&l&&l.length>1&&a.jsxs(pt,{orientation:"horizontal",className:Z(pr,"gap-3 rounded-lg p-3"),children:[a.jsx(wP,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx(dt,{className:"whitespace-nowrap",children:"Install to"}),a.jsxs(ms,{value:v,onValueChange:m,children:[a.jsx(vs,{className:"flex-1",children:a.jsx(gs,{})}),a.jsx(ys,{children:l.map(Q=>{const q=Q.displayName??Q.name??Q.provider??"unknown";return a.jsxs(hr,{value:Q.path,children:[q," (",Q.path,")"]},Q.path)})})]})]})]}),f&&a.jsxs(Yo,{children:[P&&l&&l.length>1&&(()=>{const Q=c?.[f.name];if(!Q)return null;const q=l.find(B=>Q.startsWith(B.path+"/")||Q===B.path);return q?a.jsxs(Y,{as:"span",variant:"caption",tone:"muted",className:"mr-auto",children:["Installed at ",q.path]}):null})(),a.jsx(_a,{children:"Cancel"}),a.jsx(Ca,{onConfirm:L,disabled:!S||P,"data-testid":"install-skill-button",children:s?"Installing...":P?"Already Installed":"Install"})]})]})})}function JQt({labeled:e=!1}){const{workspaceId:t,addSkill:n}=tu(),[r,s]=g.useState(!1),[i,o]=g.useState(!1);if(!n)return null;const{onInstall:l,...c}=n,u=async d=>{o(!0);try{await l(d),s(!1)}catch{}finally{o(!1)}};return a.jsxs(a.Fragment,{children:[e?a.jsxs(ce,{variant:"ghost",onClick:()=>s(!0),children:[a.jsx(zfe,{}),"Add skill"]}):a.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":"Add skill",tooltip:"Add skill",onClick:()=>s(!0),children:a.jsx(zfe,{})}),a.jsx(c$s,{...c,open:r,onOpenChange:s,workspaceId:t,onInstall:d=>{u(d)},isInstalling:i})]})}function u$s({workspaceId:e,activeFilePath:t,onDelete:n,onCreateDirectory:r,onActiveFileChange:s,readOnlyPaths:i,searchFiles:o=!0,searchSkills:l=!0,fileCount:c,skillCount:u,addSkill:d,children:f}){const[h,p]=g.useState(!1),[m,v]=g.useState(""),[y,x]=g.useState(()=>new Set(Ynt(t??""))),[b,S]=g.useState(t);if(t!==b){S(t);const C=Ynt(t??"").filter(T=>!y.has(T));C.length>0&&x(new Set([...y,...C]))}const k=i?.join(`
700
700
  `)??"",j=g.useMemo(()=>({workspaceId:e,activeFilePath:t,setActiveFilePath:s,isSearching:h,setSearching:C=>{p(C),C||v("")},query:m,setQuery:v,onDelete:n,onCreateDirectory:r,isReadOnly:C=>(k?k.split(`
701
701
  `):[]).some(_=>_==="."||C===_||C.startsWith(`${_}/`)),searchFiles:o,searchSkills:l,fileCount:c,skillCount:u,addSkill:d,openFolders:y,setFolderOpen:(C,T)=>x(_=>{if(_.has(C)===T)return _;const N=new Set(_);return T?N.add(C):N.delete(C),N})}),[e,t,h,m,n,r,s,k,o,l,c,u,d,y]);return a.jsx(GQt.Provider,{value:j,children:f})}const eZt=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{d:"M9 1.5H4C3.44772 1.5 3 1.94772 3 2.5V13.5C3 14.0523 3.44772 14.5 4 14.5H12C12.5523 14.5 13 14.0523 13 13.5V5.5M9 1.5L13 5.5M9 1.5V5.5H13",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})}),d$s=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{d:"M7.25 12.5C10.1495 12.5 12.5 10.1495 12.5 7.25C12.5 4.35051 10.1495 2 7.25 2C4.35051 2 2 4.35051 2 7.25C2 10.1495 4.35051 12.5 7.25 12.5ZM11 11L14 14",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})});function f$s(){const{isSearching:e,setSearching:t,searchFiles:n,searchSkills:r}=tu();return!n&&!r?null:a.jsx(ce,{variant:"ghost",size:"icon-sm",tooltip:"Search files and skills","aria-pressed":e,onClick:()=>t(!e),children:a.jsx(d$s,{})})}function h$s(){const{isSearching:e}=tu();return e?a.jsx(m$s,{}):a.jsx(p$s,{})}const ert=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function p$s(){const{fileCount:e,skillCount:t}=tu();return a.jsxs(Y,{as:"span",variant:"label",tone:"muted",className:"block min-w-0 truncate",children:[a.jsx("span",{children:e===void 0?"Files":ert(e,"File")}),t===void 0?null:a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"span",variant:"label",tone:"faint","aria-hidden":!0,className:"mx-1.5",children:"·"}),a.jsx("span",{children:ert(t,"Skill")})]})]})}function m$s(){const{setSearching:e,setQuery:t}=tu(),[n,r]=g.useState(""),[,s]=g.useTransition();return a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(bn,{type:"search",size:"sm",autoFocus:!0,"aria-label":"Search query",placeholder:"Search files and skills",value:n,onChange:i=>{const o=i.target.value;r(o),s(()=>t(o))},onKeyDown:i=>{i.key==="Escape"&&e(!1)}}),a.jsx(ce,{variant:"ghost",size:"icon-sm",tooltip:"Close search",onClick:()=>e(!1),children:a.jsx(Mn,{})})]})}function g$s(){const{workspaceId:e,query:t,activeFilePath:n,setActiveFilePath:r,searchFiles:s,searchSkills:i}=tu(),{data:o,isLoading:l,isError:c,error:u}=Dzr({workspaceId:e,query:t,files:s,skills:i,queryOptions:{enabled:t.trim().length>0&&(s||i)}});return t.trim()?l?a.jsxs("div",{"aria-busy":"true",className:"flex flex-col gap-2 p-2",children:[a.jsx(bt,{className:"h-4 w-3/4"}),a.jsx(bt,{className:"h-4 w-2/3"})]}):c?a.jsx(kee,{error:u,fallback:"Search failed.",className:"m-2"}):o?.length?a.jsx("ul",{"aria-label":"Search results",className:"flex flex-col py-1",children:o.map(d=>a.jsx("li",{children:a.jsxs("button",{type:"button",title:d.path,onClick:()=>r(d.path),className:Z("text-foreground","flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left hover:bg-fill-subtle",n===d.path&&"bg-fill"),children:[a.jsx(At,{size:"sm",children:d.kind==="skill"?a.jsx(q6,{}):a.jsx(eZt,{})}),a.jsx(Y,{as:"span",variant:"body-sm",className:"truncate",children:d.label})]})},d.path))}):a.jsx(Yt,{titleSlot:"No results"}):a.jsx(Yt,{titleSlot:"Search files and skills",descriptionSlot:"Type to find matching content."})}function v$s({mount:e}){switch(e.icon||e.provider){case"aws-s3":case"s3":return a.jsx(X$t,{className:"text-foreground"});case"google-cloud":case"google-cloud-storage":case"gcs":return a.jsx(eRt,{});case"azure-blob":case"azure":return a.jsx(J$t,{className:"text-badge-blue-indicator"});case"cloudflare":case"cloudflare-r2":case"r2":return a.jsx(XU,{className:"text-badge-orange-indicator"});case"minio":return a.jsx(Lfe,{className:"text-badge-red-indicator"});case"database":return a.jsx(zm,{className:"text-badge-green-indicator"});case"local":case"folder":return a.jsx(wP,{className:"text-badge-amber-indicator"});case"hard-drive":return a.jsx(Lfe,{className:"text-muted-foreground"});default:return a.jsx(XU,{className:"text-muted-foreground"})}}const y$s=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{d:"M2.5 4H13.5M6 4V2.5H10V4M4 4L4.75 13.5H11.25L12 4M6.75 6.5V11M9.25 6.5V11",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})}),x$s=e=>{const t=["B","KB","MB","GB","TB"],n=e>0?Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1):0;return`${parseFloat((e/1024**n).toFixed(1))} ${t[n]}`};function b$s(){const{workspaceId:e,activeFilePath:t,setActiveFilePath:n}=tu(),{data:r,isLoading:s,error:i}=z6({workspaceId:e,path:YA}),[o,l]=g.useState(null);return s?a.jsx(j$s,{}):r?a.jsxs(a.Fragment,{children:[a.jsx(kr,{"aria-label":"Workspace files",selectedId:t,onSelect:n,className:"py-1",children:a.jsx(tZt,{entries:r,parent:YA,onRequestDelete:l})}),a.jsx(O$s,{entry:o,onClose:()=>l(null)})]}):a.jsx(kee,{error:i,fallback:"Could not load files.",className:"m-2"})}function tZt({entries:e,parent:t,onRequestDelete:n}){return e.map(r=>{const s=KQt(t,r.name);return r.type==="directory"?a.jsx(w$s,{name:r.name,path:s,mount:r.mount,onRequestDelete:n},r.name):a.jsx(k$s,{name:r.name,size:r.size,path:s,onRequestDelete:n},r.name)})}function nZt({children:e}){return a.jsx("span",{className:"ml-auto flex shrink-0 items-center gap-1 opacity-0 group-focus-within:opacity-100 group-hover:opacity-100",children:e})}function rZt({name:e,onClick:t}){return a.jsx(ce,{variant:"destructive-ghost",size:"icon-sm",tooltip:`Delete ${e}`,onClick:n=>{n.stopPropagation(),t()},onKeyDown:n=>n.stopPropagation(),children:a.jsx(y$s,{})})}function w$s({name:e,path:t,mount:n,onRequestDelete:r}){const{workspaceId:s,onDelete:i,onCreateDirectory:o,isReadOnly:l,openFolders:c,setFolderOpen:u}=tu(),d=c.has(t),{isLoading:f}=z6({workspaceId:s,path:t,queryOptions:{enabled:d}}),[h,p]=g.useState(!1),m=i&&!l(t),v=o&&!l(t);return a.jsxs(kr.Folder,{id:t,open:d,onOpenChange:y=>u(t,y),children:[a.jsxs(kr.FolderTrigger,{actions:m||v?a.jsxs(nZt,{children:[v?a.jsx(ce,{variant:"ghost",size:"icon-sm",tooltip:`New folder in ${e}`,onClick:y=>{y.stopPropagation(),u(t,!0),p(!0)},onKeyDown:y=>y.stopPropagation(),children:a.jsx(_S,{})}):null,m?a.jsx(rZt,{name:e,onClick:()=>r({path:t,type:"directory"})}):null]}):void 0,children:[a.jsx(kr.Icon,{children:n?a.jsx("span",{role:"img","aria-label":`Mount: ${n.displayName??n.provider}`,title:[n.displayName??n.provider,n.description].filter(Boolean).join(" — "),className:"flex",children:a.jsx(v$s,{mount:n})}):a.jsx(zUt,{})}),a.jsx(kr.Label,{children:e}),n?.status==="error"?a.jsx("span",{role:"img","aria-label":`Mount error: ${n.error??"unavailable"}`,title:n.error,className:"flex shrink-0",children:a.jsx(xP,{className:"size-3 text-destructive-foreground"})}):null,n&&l(t)?a.jsx("span",{role:"img","aria-label":"Read-only",title:"Read-only",className:"flex shrink-0",children:a.jsx(Nu,{className:"size-3 text-muted-foreground"})}):null,d&&f?a.jsx("span",{className:"flex shrink-0 animate-in delay-200 fill-mode-backwards fade-in",children:a.jsx(On,{size:"sm","aria-label":`Loading ${e}`,className:"size-3 text-muted-foreground"})}):null]}),a.jsx(kr.FolderContent,{children:d?a.jsx(S$s,{path:t,creating:h,onCreated:()=>p(!1),onRequestDelete:r}):null})]})}function S$s({path:e,creating:t,onCreated:n,onRequestDelete:r}){const{workspaceId:s,onCreateDirectory:i}=tu(),o=mr(),{data:l,isLoading:c,error:u}=z6({workspaceId:s,path:e}),d=async f=>{try{await i?.(KQt(e,f.replace(/^\/+|\/+$/g,"")))}catch{return}n(),await o.invalidateQueries({queryKey:["workspace",s,"fs","list",e]})};return a.jsxs(a.Fragment,{children:[t?a.jsx(kr.Input,{type:"folder",placeholder:"Folder name",onSubmit:f=>{d(f)},onCancel:n}):null,c?null:l?a.jsx(tZt,{entries:l,parent:e,onRequestDelete:r}):a.jsx(kee,{error:u,fallback:"Could not load folder.",className:"my-1 mr-1"})]})}function k$s({name:e,size:t,path:n,onRequestDelete:r}){const{onDelete:s,isReadOnly:i,activeFilePath:o}=tu(),l=s&&!i(n),c=n===o,u=g.useRef(null);return g.useEffect(()=>{c&&u.current?.scrollIntoView?.({block:"nearest"})},[c]),a.jsxs(kr.File,{ref:u,id:n,children:[a.jsx(kr.Icon,{children:a.jsx(eZt,{})}),a.jsx(kr.Label,{children:e}),a.jsxs(nZt,{children:[t!==void 0?a.jsx(Y,{as:"span",variant:"caption",tone:"faint",font:"mono",children:x$s(t)}):null,l?a.jsx(rZt,{name:e,onClick:()=>r({path:n,type:"file"})}):null]})]})}function O$s({entry:e,onClose:t}){const{workspaceId:n,activeFilePath:r,setActiveFilePath:s,onDelete:i}=tu(),o=mr(),[l,c]=g.useState(!1),u=e?.path.split("/").pop(),d=async()=>{if(!(!e||!i)){c(!0);try{await i(e)}catch{return}finally{c(!1)}(r===e.path||r?.startsWith(`${e.path}/`))&&s(void 0),o.removeQueries({queryKey:["workspace",n,"fs","list",e.path]}),await o.invalidateQueries({queryKey:["workspace",n,"fs","list",YQt(e.path)]}),t()}};let f=null;return e&&(f=e.type==="directory"?`This permanently deletes the folder "${u}" and everything inside it.`:`This permanently deletes "${u}".`),a.jsx(Bt,{open:e!==null,onOpenChange:h=>{!h&&!l&&t()},children:a.jsxs(Bt.Content,{children:[a.jsxs(Bt.Header,{children:[a.jsxs(Bt.Title,{children:["Delete ",e?.type==="directory"?"folder":"file","?"]}),a.jsxs(Bt.Description,{children:[f," This action cannot be undone."]})]}),a.jsxs(Bt.Footer,{children:[a.jsx(Bt.Cancel,{disabled:l,children:"Cancel"}),a.jsx(ce,{variant:"destructive",disabled:l,onClick:()=>{d()},children:l?"Deleting…":"Delete"})]})]})})}function j$s(){return a.jsxs("div",{"data-testid":"workspace-tree-skeleton","aria-busy":"true",className:"flex flex-col gap-2 py-2 pl-[18px]",children:[a.jsx(bt,{className:"h-4 w-3/4"}),a.jsx(bt,{className:"h-4 w-1/2"}),a.jsx(bt,{className:"h-4 w-2/3"})]})}function C$s({children:e,...t}){return a.jsx(u$s,{...t,children:a.jsx(_$s,{children:e})})}function _$s({children:e}){const{workspaceId:t}=tu(),{data:n,error:r}=z6({workspaceId:t,path:YA});return(n?n.length===0:Pk(r))?a.jsx(Yt,{variant:"fill",titleSlot:"This workspace is empty",descriptionSlot:"Files written by your agents will show up here.",actionSlot:a.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[a.jsx(XQt,{labeled:!0}),a.jsx(JQt,{labeled:!0})]})}):a.jsx("div",{className:"size-full overflow-hidden",children:a.jsx(b$,{className:"size-full min-h-0 min-w-0",orientation:"horizontal",children:e})})}function T$s({children:e}){return a.jsxs(a.Fragment,{children:[a.jsx(_Ne,{direction:"left",id:"workspace-aside",minSize:200,maxSize:"50%",defaultSize:"25%",collapsible:!1,className:"min-w-0",children:a.jsx("div",{className:"flex h-full min-h-0 flex-col",children:e})}),a.jsx(uk,{className:"w-px bg-border"})]})}function I$s({children:e,actions:t}){const{isSearching:n}=tu();return a.jsxs("div",{className:"flex h-11 shrink-0 items-center gap-2 border-b border-border px-3",children:[a.jsx("div",{className:"min-w-0 flex-1",children:e}),t&&!n?a.jsx("div",{className:"flex shrink-0 items-center gap-1",children:t}):null]})}function E$s(){const{isSearching:e}=tu();return a.jsx(jr,{className:"min-h-0 flex-1 px-2 py-1",children:e?a.jsx(g$s,{}):a.jsx(b$s,{})})}function N$s({children:e}){return a.jsx(ap,{id:"workspace-active-file",className:"flex min-w-0 flex-col",minSize:30,children:e})}function A$s({children:e}){return a.jsx("div",{className:"flex h-11 shrink-0 items-center gap-2 border-b border-border px-4",children:e})}function P$s({renderPreview:e}){const{activeFilePath:t}=tu();return t?a.jsx(jr,{className:"min-h-0 flex-1",children:a.jsx(l$s,{renderPreview:e})}):a.jsx(Yt,{variant:"fill",titleSlot:"Select a file"})}const Pg={Root:C$s,Aside:T$s,AsideHeader:I$s,Search:h$s,SearchToggle:f$s,CreateDirectory:XQt,Tree:E$s,ActiveFile:N$s,ActiveFileHeader:A$s,FilePath:o$s,ActiveFileContent:P$s};function $$s({asideActions:e,renderPreview:t,...n}){return a.jsxs(Pg.Root,{...n,children:[a.jsxs(Pg.Aside,{children:[a.jsx(Pg.AsideHeader,{actions:a.jsxs(a.Fragment,{children:[a.jsx(Pg.SearchToggle,{}),a.jsx(Pg.CreateDirectory,{}),a.jsx(JQt,{}),e]}),children:a.jsx(Pg.Search,{})}),a.jsx(Pg.Tree,{})]}),a.jsxs(Pg.ActiveFile,{children:[a.jsx(Pg.ActiveFileHeader,{children:a.jsx(Pg.FilePath,{})}),a.jsx(Pg.ActiveFileContent,{renderPreview:t})]})]})}const R$s=()=>a.jsx(Yt,{titleSlot:"No Workspaces yet",descriptionSlot:a.jsxs(a.Fragment,{children:["Add a workspace to your Mastra configuration to ",a.jsx("br",{}),"manage files, skills, and enable semantic search."]}),actionSlot:a.jsx(ce,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/workspace/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Workspaces Documentation"}),variant:"fill"}),M$s=()=>a.jsx(Yt,{titleSlot:"Workspace Not Configured",descriptionSlot:a.jsxs(a.Fragment,{children:["No workspace is configured. Add a workspace to your ",a.jsx("br",{}),"Mastra configuration to manage files, skills, and enable semantic search."]}),actionSlot:a.jsx(ce,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/workspace/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Workspaces Documentation"}),variant:"fill"}),D$s=()=>a.jsx(Yt,{titleSlot:"Workspace Not Supported",descriptionSlot:a.jsxs(a.Fragment,{children:["The workspace feature requires a newer version of ",a.jsx("code",{className:"text-foreground",children:"@mastra/core"}),".",a.jsx("br",{}),"Please upgrade your dependencies to enable workspace functionality."]}),actionSlot:a.jsx(ce,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/workspace/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Workspaces Documentation"}),variant:"fill"}),Due=".agents/skills",L$s=e=>e.replace(/^\.?\/+|\/+$/g,"");function z$s({workspaceId:e,showInitWarning:t,skills:n}){const{data:r}=z6({workspaceId:e,path:Due,queryOptions:{enabled:!!n}}),s=n&&r?r.filter(i=>i.type==="directory"&&!n.some(o=>o.name===i.name||L$s(o.path)===`${Due}/${i.name}`)):[];return!t&&s.length===0?null:a.jsxs("div",{className:"flex shrink-0 flex-col gap-2 border-b border-border p-3",children:[t&&a.jsx(Wt,{variant:"warning",children:a.jsxs(Wt.Message,{children:["File search requires ",a.jsx("code",{children:"workspace.init()"})," to index files from your configured"," ",a.jsx("code",{children:"autoIndexPaths"}),"."]})}),s.length>0&&a.jsx(Wt,{variant:"warning",title:"Skills installed but not discovered",children:a.jsxs(Wt.Message,{children:[s.map(i=>i.name).join(", ")," ",s.length===1?"is":"are"," in"," ",a.jsx("code",{children:Due})," but not discovered. Add this path to your workspace skills configuration to see ",s.length===1?"it":"them","."]})})]})}const a1=[Ts("/workspaces")],trt=e=>_s(e)?"you don't have permission to modify this workspace":e instanceof Error?e.message:"Unknown error";function nrt(){const{workspaceId:e}=Cr(),[t,n]=wi(),r=Lr(),s=mr(),i=t.get("file"),{data:o,error:l,isLoading:c}=PRt(),u=o?.workspaces??[],d=e??u[0]?.id,{data:f,isLoading:h,error:p}=ARt({workspaceId:d,queryOptions:{enabled:!!d}}),m=Cs(l)||Cs(p),v=_s(l)||_s(p),y=ive(l)||ive(p),x=d?u.find(me=>me.id===d):void 0,b=me=>{const ke=new URLSearchParams(t);for(const[Ee,qe]of Object.entries(me))qe===null?ke.delete(Ee):ke.set(Ee,qe);n(ke)},S=me=>{r(`/workspaces/${me}`)},k=me=>{b({file:me??null})},j=i??void 0,C=Nzr(),T=Azr(),{data:_,refetch:N}=Lzr({workspaceId:d,queryOptions:{enabled:!!d}}),E=Tzr(),A=Izr(),P=Ezr(),L=me=>{const ke=/^\.agents\/skills\/([^/]+)$/.exec(me);return ke?ue.find(qe=>qe.path?.replace(/^\.?\/+|\/+$/g,"")===me)?.name??ke[1]:void 0},F=async()=>{if(d)try{const me=await A.mutateAsync({workspaceId:d}),ke=me.updated.filter(Ee=>!Ee.success);ke.length>0?Xe.error(`Failed to update ${ke.map(Ee=>Ee.skillName).join(", ")}`):Xe.success(`${me.updated.length} skill(s) updated`),s.invalidateQueries({queryKey:["workspace",d,"fs"]})}catch(me){Xe.error(`Failed to update skills: ${me instanceof Error?me.message:"Unknown error"}`)}},Q=async({path:me,type:ke})=>{if(!d)return;const Ee=ke==="directory"?L(me):void 0;if(!Ee){try{await C.mutateAsync({path:me,recursive:!0,force:!0,workspaceId:d})}catch(qe){throw Xe.error(`Failed to delete ${me}: ${trt(qe)}`),qe}return}try{if(!(await P.mutateAsync({workspaceId:d,skillName:Ee})).success)throw new Error(`Failed to remove skill "${Ee}"`);Xe.success(`Skill "${Ee}" removed`),N()}catch(qe){throw Xe.error(qe instanceof Error?qe.message:"Failed to remove skill"),qe}},q=f?.isWorkspaceConfigured??!1,B=f?.capabilities?.hasFilesystem??!1,V=f?.capabilities?.hasSkills??!1,W=x?.safety?.readOnly??!1,{canEdit:M,canDelete:K,canExecute:D,isLoading:$}=Za(),z=!$&&M("workspaces")&&!W,U=!$&&K("workspaces")&&!W,G=!$&&D("workspaces"),ne=B&&V&&z,X=f?.mounts,ee=X?.filter(me=>!me.readOnly).map(me=>({path:me.path,displayName:me.displayName,icon:me.icon,provider:me.provider,name:me.name})),re=async me=>{if(d)try{const ke=await E.mutateAsync({...me,workspaceId:d});if(!ke.success)throw new Error("Unknown error");s.invalidateQueries({queryKey:["workspace",d,"fs"]}),N(),Xe.success(`Skill "${ke.skillName}" installed successfully (${ke.filesWritten} files)`)}catch(ke){throw Xe.error(`Failed to install skill: ${ke instanceof Error?ke.message:"Unknown error"}`),ke}},ue=_?.skills??[],te=_?.isSkillsConfigured??!1,ie=G&&B&&!!(f?.capabilities?.canBM25||f?.capabilities?.canVector),se=G&&V&&te&&ue.length>0,ae=W?["."]:(X??[]).filter(me=>me.readOnly).map(me=>me.path.replace(/^\/+|\/+$/g,"")||".");if(c)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:a1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(On,{fill:!0})]});if(m)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:a1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(ci,{variant:"fill"})]});if(v)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:a1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(Gs,{variant:"fill",resource:"workspaces"})]});if(y)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:a1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(D$s,{})]});const he=l||p;if(he)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:a1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(Yt,{tone:"error",variant:"fill",titleSlot:"Failed to load workspace",descriptionSlot:he.message})]});if(!c&&u.length===0)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:a1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(R$s,{})]});if(!h&&!c&&!q)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:a1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(M$s,{})]});const ge=u.map(me=>({value:me.id,label:me.name,description:me.source==="agent"?`Agent: ${me.agentName}`:"Global workspace",end:a.jsxs("span",{className:"flex shrink-0 gap-1",children:[me.safety?.readOnly&&a.jsx($t,{size:"xs",variant:"warning",children:"Read-only"}),me.capabilities.hasFilesystem&&a.jsx($t,{size:"xs",children:"FS"}),me.capabilities.hasSandbox&&a.jsx($t,{size:"xs",children:"Sandbox"}),me.capabilities.hasSkills&&a.jsx($t,{size:"xs",children:"Skills"})]})}));return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:a1}),headerActions:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(fl,{"aria-label":"Workspace",variant:"ghost",className:"w-auto",options:ge,value:x?.id,onValueChange:S,placeholder:"Select workspace",searchPlaceholder:"Search workspaces...",emptyText:"No workspaces found."}),W&&a.jsx($t,{size:"xs",variant:"warning",children:"Read-only"})]}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsxs("div",{className:"flex min-h-0 flex-col",children:[B&&d&&a.jsx(z$s,{workspaceId:d,showInitWarning:ie&&!h&&f?.status!=="ready",skills:V&&_?ue:void 0}),B&&d&&a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx($$s,{workspaceId:d,activeFilePath:j,onActiveFileChange:k,readOnlyPaths:ae,skillCount:V&&_?ue.length:void 0,searchFiles:ie,searchSkills:se,onCreateDirectory:z?async me=>{try{await T.mutateAsync({path:me,recursive:!0,workspaceId:d})}catch(ke){throw Xe.error(`Failed to create ${me}: ${trt(ke)}`),ke}}:void 0,asideActions:ne&&ue.some(me=>me.path?.includes(".agents/skills/"))?a.jsx(ce,{variant:"ghost",size:"icon-sm",tooltip:"Update skills",disabled:A.isPending,onClick:()=>{F()},children:a.jsx(vx,{className:A.isPending?"animate-spin":void 0})}):void 0,addSkill:ne?{onInstall:re,installedSkillIds:ue.filter(me=>me.skillsShSource).map(me=>`${me.skillsShSource.owner}/${me.skillsShSource.repo}/${me.name}`),installedSkillNames:ue.filter(me=>!me.skillsShSource).map(me=>me.name),writableMounts:ee,installedSkillPaths:Object.fromEntries(ue.filter(me=>me.path).map(me=>[me.name,me.path]))}:void 0,onDelete:U?Q:void 0},d)}),!B&&!h&&a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx(Yt,{variant:"fill",titleSlot:"No filesystem or skills configured",descriptionSlot:"Add a filesystem or skills to this workspace to browse its files here."})})]})]})}function sZt({children:e,className:t,mobileHeader:n,ref:r,sidebar:s,...i}){return a.jsxs("div",{ref:r,"data-slot":"app-shell",className:Z("h-full min-h-0",s&&"lg:grid lg:grid-cols-[auto_minmax(0,1fr)] lg:grid-rows-[1fr]",t),...i,children:[s,a.jsxs("div",{"data-slot":"app-shell-content",className:"flex h-full min-h-0 min-w-0 flex-col",children:[n,a.jsx("div",{"data-slot":"app-shell-body",className:Z("flex min-h-0 flex-1 flex-col","lg:py-2 lg:pr-2",s?"lg:pl-0":"lg:pl-2"),children:e})]})]})}function iZt({children:e,className:t}){return a.jsx("div",{"data-slot":"main-card",className:Z("relative min-h-0 flex-1 overflow-hidden lg:rounded-studio-frame lg:p-px lg:shadow-raised",yCn,t),children:e})}function F$s(){return a.jsxs("div",{className:"h-screen bg-sidebar",children:[a.jsx(dG,{position:"bottom-right"}),a.jsx(vSe,{defaultTheme:"system",children:a.jsx(Wc,{delayDuration:0,children:a.jsx(sZt,{children:a.jsx(iZt,{className:"flex items-center justify-center overflow-y-auto",children:a.jsx(gx,{})})})})})]})}function B$s({className:e,children:t,...n}){return a.jsx("footer",{"data-slot":"sidebar-footer",className:Z("mt-auto shrink-0 space-y-1.5",e),...n,children:t})}const aPe=Me.createContext(null),oZt=Me.createContext(null);function Gx(){return Me.useContext(aPe)}function pg(){const e=Me.useContext(aPe),t=Me.useContext(oZt);if(!e||!t)throw new Error("useSidebar must be used within a SidebarProvider.");return{...e,...t}}const V$s=g.forwardRef(function({className:t,children:n,action:r,...s},i){const{state:o}=pg();return a.jsxs("div",{ref:i,"data-slot":"sidebar-footer-meta","data-state":o,className:Z("grid min-h-10 grid-cols-[minmax(0,1fr)_auto_0fr] items-center border-t border-border px-2 py-1 text-meta text-muted-foreground","transition-[grid-template-columns] duration-slow ease-out-custom motion-reduce:transition-none",o==="collapsed"&&"grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] px-0",t),...s,children:[a.jsx("div",{"aria-hidden":o==="collapsed",className:Z("min-w-0 truncate transition-opacity duration-normal ease-out-custom motion-reduce:transition-none",o==="collapsed"&&"opacity-0"),children:n}),r,a.jsx("span",{"aria-hidden":!0})]})}),U$s=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`,q$s=76,Q$s=100,Z$s=60,W$s=22.5,H$s=.18,rrt=110,aZt=[0,.08,.16,.25,.34,.44,.55,.66,.78,.89,1],lZt={neutral:{colorVar:"--foreground",peak:.08,grain:!0,text:"text-muted-foreground"},warning:{colorVar:"--warning-indicator",peak:.16,grain:!1,text:"text-warning-foreground"},danger:{colorVar:"--destructive-indicator",peak:.16,grain:!1,text:"text-destructive-foreground"}};function cZt(e){const t=1-e;return t*t*t}function G$s(e,t){return`linear-gradient(to right, ${aZt.map(r=>{const s=(t*cZt(r)*100).toFixed(2);return`color-mix(in oklch, var(${e}) ${s}%, transparent) ${(r*100).toFixed(0)}%`}).join(", ")})`}function srt(e,t){const n=aZt.map(r=>{const s=(t+(100-t)*r).toFixed(2);return`rgb(0 0 0 / ${cZt(r).toFixed(3)}) ${s}%`});return`linear-gradient(${e}, rgb(0 0 0 / 1) 0%, ${n.join(", ")})`}const K$s=`${srt("to bottom",Z$s)}, ${srt("to right",W$s)}`;function irt({tone:e}){const t=lZt[e];return a.jsx("span",{"aria-hidden":!0,"data-slot":"sidebar-meter-bloom",className:"pointer-events-none absolute inset-x-0 top-0 -z-10",style:{height:Q$s,backgroundImage:G$s(t.colorVar,t.peak),maskImage:K$s,maskComposite:"intersect"},children:t.grain?a.jsx("span",{"aria-hidden":!0,className:"absolute inset-0",style:{backgroundImage:U$s,backgroundRepeat:"repeat",backgroundSize:`${rrt}px ${rrt}px`,opacity:H$s}}):null})}const Y$s=g.forwardRef(function({label:t,value:n,status:r,tone:s="neutral",icon:i,action:o,href:l,linkLabel:c,LinkComponent:u,state:d,className:f,...h},p){const m=Gx(),v=d??m?.state??"default",y=u??m?.LinkComponent??"a",x=v==="collapsed",b=lZt[s];return x?a.jsxs("div",{ref:p,"data-slot":"sidebar-meter","data-tone":s,"data-state":v,className:Z("relative isolate flex items-center justify-center overflow-hidden rounded-lg border border-border bg-background px-1 py-2",f),...h,children:[a.jsx(irt,{tone:s}),l?a.jsx(y,{href:l,className:"absolute inset-0 rounded-lg","aria-label":c}):null,a.jsx(Y,{as:"span",variant:"meta",tone:"ink",className:"pointer-events-none relative tabular-nums",children:n})]}):a.jsxs("div",{ref:p,"data-slot":"sidebar-meter","data-tone":s,"data-state":v,className:Z("relative isolate flex flex-col justify-center overflow-hidden rounded-lg border border-border bg-background px-3",l&&gP,f),style:{height:q$s},...h,children:[a.jsx(irt,{tone:s}),l?a.jsx(y,{href:l,className:"absolute inset-0 rounded-lg","aria-label":c}):null,a.jsxs("div",{className:"pointer-events-none relative",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[s==="neutral"?null:i,a.jsx(Y,{as:"span",variant:"column",tone:"muted",children:t}),o?a.jsx("span",{className:"pointer-events-auto",children:o}):null]}),a.jsx(Y,{variant:"heading",tone:"ink",className:"mt-0.5 leading-tight tabular-nums",children:n}),r?a.jsx("div",{className:"mt-1 text-meta",children:a.jsx("p",{className:Z("truncate",b.text),children:r})}):null]})]})});function X$s({logo:e,title:t,className:n,...r}){const{state:s}=pg();return a.jsxs("div",{"data-slot":"sidebar-brand",className:Z("flex min-w-0 flex-1 items-center gap-2",n),...r,children:[e?a.jsx("span",{className:"shrink-0",children:e}):null,s==="collapsed"?a.jsx(B0,{children:t}):a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",className:"truncate font-body tracking-tight",children:t})]})}const J$s=g.forwardRef(function({className:t,children:n,...r},s){const{state:i,isMobile:o}=pg();return a.jsx("header",{ref:s,"data-slot":"sidebar-command-header","data-state":i,className:Z("flex h-header-default shrink-0 items-center gap-1 overflow-hidden",i==="collapsed"?"px-3":"pr-2 pl-3.5",i!=="collapsed"&&!o&&"w-[calc(var(--sidebar-width)-1rem)]",i==="collapsed"&&"[&_[data-slot=sidebar-search-trigger]]:hidden",t),...r,children:n})});function uZt({className:e,onClick:t,...n}){const{desktopState:r,isMobile:s,toggleSidebar:i}=pg(),o=r==="collapsed";return s?null:a.jsxs(Qn,{children:[a.jsx(Fn,{render:a.jsx("button",{type:"button","aria-label":"Toggle sidebar","aria-expanded":!o,...n,onClick:l=>{t?.(l),l.defaultPrevented||i()},className:Z("flex items-center justify-center rounded-md text-muted-foreground","size-7",!o&&"ml-auto","hover:bg-fill-subtle hover:text-foreground","transition-colors duration-normal ease-out-custom motion-reduce:transition-none",bi,"[&_svg]:size-4 [&_svg]:text-muted-foreground [&:hover_svg]:text-foreground",e),children:a.jsx(xpt,{})})}),a.jsx(Bn,{children:a.jsxs("span",{className:"inline-flex items-center gap-1.5",children:["Toggle Sidebar",a.jsx(Hd,{size:"xs",className:"bg-muted text-muted-foreground",children:"["})]})})]})}const ort="animate-[sidebar-hold_var(--resize-dur)] motion-reduce:animate-none";function eRs({className:e,children:t,collapsedLogo:n,actions:r,...s}){const i=Gx(),o=i?.state==="collapsed",l=i?.isMobile??!1;return a.jsxs("header",{"data-slot":"sidebar-header",className:Z("flex h-header-default shrink-0 items-center gap-2",o?"px-1":"pr-2 pl-3.5",o&&r&&"h-auto flex-col gap-3 py-3",!o&&!l&&"w-[calc(var(--sidebar-width)-1rem)]",e),...s,children:[o&&n?a.jsxs("div",{className:"group/collapsed-logo relative ml-0.5 grid size-9 shrink-0 place-items-center",children:[a.jsx("span",{className:Z(ort,"grid place-items-center transition-opacity duration-normal [--sidebar-hold-opacity:1] group-focus-within/collapsed-logo:opacity-0 group-hover/sidebar:opacity-0 motion-reduce:transition-none"),children:n}),l?null:a.jsx("div",{className:Z(ort,"absolute inset-0 grid place-items-center opacity-0 transition-opacity duration-normal [--sidebar-hold-opacity:0] group-hover/sidebar:opacity-100 focus-within:opacity-100 motion-reduce:transition-none"),children:a.jsx(uZt,{})})]}):t,r]})}const tRs=g.forwardRef(function({className:t,children:n,shortcut:r,type:s="button",...i},o){return a.jsxs("button",{ref:o,"data-slot":"sidebar-search-trigger",type:s,className:Z("group inline-flex size-control-md shrink-0 items-center justify-center gap-1.5 rounded-full border border-transparent hover:bg-fill-subtle",Zn,In,bi,"[&_svg]:size-4 [&_svg]:shrink-0",r&&"w-auto px-2",t),...i,children:[n,r?a.jsx(Hd,{size:"xs",className:Z("bg-surface-overlay-soft active:scale-100",xx),children:r}):null]})});function nRs({"aria-label":e="Main",children:t,className:n,...r}){const s=Gx()?.isMobile??!1;return a.jsx("nav",{"aria-label":e,className:Z("-mr-1.5 flex min-h-0 flex-1 flex-col","[&_[data-slot=scroll-area-scrollbar][data-orientation=vertical]]:w-1 [&_[data-slot=scroll-area-scrollbar][data-orientation=vertical]]:p-0","focus-within:[&_[data-slot=scroll-area-scrollbar][data-orientation=vertical][data-has-overflow-y]]:opacity-100",s&&"[&_a]:min-h-11 [&_a]:touch-manipulation [&_button]:min-h-11 [&_button]:touch-manipulation",n),...r,children:a.jsx(jr,{className:"min-h-0 flex-1",mask:{top:"3rem",bottom:"5rem"},children:a.jsx(Au,{className:"px-0.5",children:a.jsx("div",{className:"pr-1.5",children:t})})})})}function dZt({children:e,icon:t,action:n,className:r,state:s,href:i,isActive:o,LinkComponent:l,...c}){const u=Gx(),f=(s??u?.state??"default")==="default",h=l??u?.LinkComponent??"a",p=o?"text-foreground":"text-muted-foreground";return a.jsx("div",{className:Z("flex min-w-0 items-center",f?"mt-3 min-h-7":"h-10",r),children:f?a.jsxs(a.Fragment,{children:[t?a.jsx("span",{"aria-hidden":"true",className:Z("flex shrink-0 pl-3 [&_svg]:size-4",p),children:t}):null,a.jsx("header",{...c,className:Z("max-w-full min-w-0 flex-1 truncate text-column",t?"pl-2":"pl-3",p),children:i?a.jsx(h,{href:i,className:Z("block min-w-0 truncate transition-colors duration-normal",{"hover:text-foreground":!o,"text-foreground":o}),children:e}):e}),n]}):a.jsxs(a.Fragment,{children:[a.jsx(B0,{asChild:!0,children:a.jsx("header",{...c,children:e})}),a.jsx("div",{"aria-hidden":"true",className:"mx-3 h-px flex-1 bg-border"}),n?a.jsx(B0,{children:n}):null]})})}function lPe({children:e,className:t,state:n,...r}){const s=Gx();return(n??s?.state??"default")==="collapsed"?a.jsx(B0,{children:e}):a.jsx("span",{...r,className:Z("min-w-0 flex-1 truncate text-left",t),children:e})}const rRs=md("flex min-w-0 cursor-pointer items-center rounded-lg text-label whitespace-nowrap",{variants:{size:{sm:tp.sm,md:tp.md,lg:tp.lg}},defaultVariants:{size:"md"}}),sRs=e=>e<=0?"gap-2 py-1 px-3":e===1?`gap-2 py-1 pr-3 pl-8 ${tp.md}`:e===2?`gap-2 py-1 pr-3 pl-10 ${tp.md}`:`gap-2 py-1 pr-3 pl-12 ${tp.md}`,iRs=Z("rounded-lg text-muted-foreground hover:text-foreground",gP),oRs="bg-fill text-foreground",aRs=Z("my-2 border border-transparent bg-brand-green text-black hover:text-black hover:brightness-95"),fZt=({isActive:e,isFeatured:t})=>Z(iRs,e&&oRs,t&&aRs),hZt=({isCollapsed:e,level:t=0,size:n})=>Z(rRs({size:n}),"w-full justify-start",In,"[&_svg]:size-4 [&_svg]:shrink-0",bi,!e&&sRs(t),e&&"gap-0 px-[13.5px] py-0"),pZt=({isActive:e,isCollapsed:t,isFeatured:n,level:r,size:s}={})=>Z(hZt({isCollapsed:t,level:r,size:s}),fZt({isActive:e,isFeatured:n}));function cPe({link:e,state:t,children:n,isActive:r,size:s,render:i,action:o,className:l,LinkComponent:c,level:u,subItems:d,asChild:f=!1,...h}){if(i&&f)throw new Error("SidebarNavLink accepts either `render` or `asChild`, not both.");const p=Gx(),m=t??p?.state??"default",v=c??p?.LinkComponent??"a",y=m==="collapsed",x=e?.variant==="featured",b=u??(e?.indent?1:0),S=y?void 0:o,k=S?Z(hZt({level:b,size:s}),"flex-1 pr-1"):Z(pZt({isActive:r,isCollapsed:y,isFeatured:x,level:b,size:s}),e?.opensView&&!y&&"pr-1");return a.jsxs("li",{...h,className:Z("relative flex min-w-0 flex-col",l),children:[a.jsx(dRs,{action:S,surfaceClassName:fZt({isActive:r,isFeatured:x}),children:a.jsx(uRs,{label:cRs(e,y),children:lRs({render:i,asChild:f,children:n,link:e,state:m,Link:v,isActive:r,className:k})})}),!y&&d]})}function lRs({render:e,asChild:t,children:n,link:r,state:s,Link:i,isActive:o,className:l}){const c=o?"page":void 0,u=r?.opensView&&s!=="collapsed"?a.jsx(Lc,{"aria-hidden":"true",className:"!size-3.5"}):null;if(e||t){const f=e??n;if(!Me.isValidElement(f))throw new Error("SidebarNavLink requires a valid React element child when `asChild` is true so it can apply `SlottedNavChildProps` and merge `itemClassName`.");return Me.cloneElement(f,{className:Z(l,f.props.className),"aria-current":c,children:a.jsxs(a.Fragment,{children:[f.props.children,u]})})}if(!r)return n;const d=/^(https?:)?\/\//.test(r.url)?{target:"_blank",rel:"noreferrer"}:{};return a.jsxs(i,{href:r.url,...d,"aria-current":c,className:l,children:[r.icon,a.jsx(lPe,{state:s,children:r.name}),n,u]})}function cRs(e,t){if(e)return e.tooltipMsg?t?`${e.name} | ${e.tooltipMsg}`:e.tooltipMsg:t?e.name:void 0}function uRs({label:e,children:t}){return Me.isValidElement(t)?a.jsxs(Qn,{disabled:!e,children:[a.jsx(Fn,{render:t}),e?a.jsx(Bn,{side:"right",align:"center",sideOffset:16,children:e}):null]}):t}function dRs({action:e,surfaceClassName:t,children:n}){return e?a.jsxs("div",{className:Z("flex min-w-0 items-center pr-1",t),children:[n,e]}):n}function uPe({className:e,children:t,...n}){return a.jsx("ul",{className:Z("grid grid-cols-[minmax(0,1fr)] content-center items-start gap-0.5",e),...n,children:t})}function mZt({className:e,children:t,...n}){return a.jsx("section",{className:Z("relative grid grid-cols-[minmax(0,1fr)] content-center items-start",e),...n,children:t})}function gZt({className:e,...t}){return a.jsx("div",{role:"separator","aria-orientation":"horizontal",className:Z("relative min-h-5",'[&:after]:absolute [&:after]:inset-x-3 [&:after]:top-1/2 [&:after]:block [&:after]:h-0 [&:after]:border-t [&:after]:border-border [&:after]:content-[""]',e),...t})}function fRs({foldedCount:e,expanded:t,onExpandedChange:n,state:r,className:s,...i}){const o=Gx();return(r??o?.state??"default")==="collapsed"||e<=0?null:a.jsx("button",{type:"button","aria-expanded":t,onClick:()=>n(!t),className:Z(Sa({variant:"caption",tone:"muted"}),"self-start rounded-md pl-3 text-left hover:text-foreground",In,bi,s),...i,children:t?"Show less":`Show ${e} more`})}const vZt=Me.createContext(void 0);function yZt(){const e=Me.useContext(vZt);if(!e)throw new Error("Sidebar.NavStack components must be used within Sidebar.NavStack.");return e}function hRs({value:e,rootValue:t="root",onValueChange:n,children:r,className:s,...i}){function o(l){n(t),requestAnimationFrame(()=>{const c=l?.current;c&&!c.closest("[inert]")&&c.focus()})}return a.jsx(vZt.Provider,{value:{activeValue:e,rootValue:t,closeView:o},children:a.jsx("div",{"data-slot":"sidebar-nav-stack","data-value":e,className:Z("relative grid min-w-0 overflow-hidden",s),...i,children:r})})}function xZt(e,t,n){return Z("col-start-1 row-start-1 min-w-0 transition-[opacity,translate] duration-normal ease-out-custom will-change-[opacity,translate] motion-reduce:transition-none",e&&"relative translate-x-0 opacity-100",!e&&"pointer-events-none absolute inset-0 opacity-0",!e&&t==="root"&&"-translate-x-2",!e&&t==="view"&&"translate-x-2",n)}function pRs({children:e,className:t,...n}){const{state:r}=pg(),{activeValue:s,rootValue:i}=yZt(),o=r==="collapsed"||s===i;return a.jsx("div",{...n,"data-slot":"sidebar-nav-stack-root","aria-hidden":!o,inert:!o,className:xZt(o,"root",t),children:e})}function mRs({value:e,title:t,backLabel:n="Back to main navigation",returnFocusRef:r,onBack:s,children:i,className:o,...l}){const{state:c}=pg(),{activeValue:u,closeView:d}=yZt(),f=c!=="collapsed"&&u===e,h=Me.useRef(null),p=Me.useRef(f);Me.useEffect(()=>{f&&!p.current&&h.current?.focus(),p.current=f},[f]),Me.useEffect(()=>{if(!f)return;function v(y){y.key!=="Escape"||y.defaultPrevented||(y.preventDefault(),d(r),s?.())}return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[f,d,s,r]);function m(){d(r),s?.()}return a.jsxs("div",{...l,"data-slot":"sidebar-nav-stack-view","data-value":e,"aria-hidden":!f,inert:!f,className:xZt(f,"view",o),children:[a.jsxs("button",{ref:h,type:"button","aria-label":`${n}: ${t}`,onClick:m,className:Z(pZt(),"mb-2 grid grid-cols-[2rem_1fr_2rem] px-1"),children:[a.jsx(vd,{className:"justify-self-center","aria-hidden":"true"}),a.jsx("span",{className:"min-w-0 truncate text-center",children:t}),a.jsx("span",{"aria-hidden":"true"})]}),i]})}const gRs=Object.assign(hRs,{Root:pRs,View:mRs});function vRs({className:e,icon:t,"aria-label":n="Open navigation menu",onClick:r,...s}){const{isMobile:i,mobileTriggerRef:o,setOpenMobile:l}=pg();return a.jsx("button",{ref:o,type:"button","aria-label":n,"aria-hidden":!i,tabIndex:i?0:-1,"data-mobile-only":!0,...s,onClick:c=>{r?.(c),c.defaultPrevented||l(!0)},className:Z("inline-flex size-10 items-center justify-center rounded-md","[[data-sidebar-mobile='false']_&]:hidden","[[data-sidebar-mobile-present='true']_&]:invisible",Zn,"hover:bg-fill-subtle",bi,e),children:t??a.jsx(hpt,{className:"size-5"})})}const art="sidebar:state",lrt="sidebar:width",crt="--sidebar-width",Lue=(e,t,n)=>Math.min(n,Math.max(t,e)),yRs=typeof window<"u"?Me.useLayoutEffect:Me.useEffect;function bZt({children:e,defaultState:t="default",defaultWidth:n=240,minWidth:r=200,maxWidth:s=480,collapseBelow:i,collapsedWidth:o=64,disableKeyboardShortcut:l=!0,storageKey:c,mobileBreakpoint:u=1024,mobileWidth:d=360,LinkComponent:f}){const h=Math.max(0,Math.min(r,s)),p=Math.max(h,s),m=Math.max(0,Math.min(o,p)),v=Lue(n,h,p),y=i??h,x=c?`${c}:${art}`:art,b=c?`${c}:${lrt}`:lrt,S=()=>{if(typeof window>"u")return{state:t,width:v};try{let se=t,ae=v;const he=window.localStorage.getItem(x);(he==="collapsed"||he==="default")&&(se=he);const ge=window.localStorage.getItem(b);if(ge!==null){const me=Number(ge);Number.isFinite(me)&&(ae=Lue(me,h,p))}return{state:se,width:ae}}catch{return{state:t,width:v}}},k=Me.useRef(null);k.current===null&&(k.current=S());const j=k.current,[C,T]=Me.useState(j.state),[_,N]=Me.useState(j.width),[E,A]=Me.useState(!1),[P,L]=Me.useState(!1),[F,Q]=Me.useState(!1),q=Me.useRef(!1),B=Me.useRef(null),V=Me.useRef(j.width),W=Me.useRef(j.state);W.current=C;const M=Me.useRef(null);Me.useEffect(()=>{if(typeof window>"u")return;const se=window.matchMedia(`(max-width: ${u-1}px)`),ae=()=>A(se.matches);return ae(),se.addEventListener("change",ae),()=>se.removeEventListener("change",ae)},[u]);const K=Me.useCallback(se=>{q.current=se,se&&Q(!0),L(se)},[]);Me.useEffect(()=>{!E&&P&&(K(!1),Q(!1))},[E,P,K]);const D=Me.useCallback(se=>{const ae=M.current;ae&&ae.style.setProperty(crt,`${se}px`)},[]);yRs(()=>{D(C==="collapsed"?m:V.current)},[C,m,D]);const $=Me.useCallback(se=>{try{window.localStorage.setItem(x,se)}catch{}},[x]),z=Me.useCallback(()=>{if(E){K(!q.current);return}T(se=>{const ae=se==="default"?"collapsed":"default";return W.current=ae,$(ae),ae})},[E,$,K]),U=Me.useCallback(se=>{const ae=Lue(se,h,p);V.current=ae,D(ae)},[h,p,D]),G=Me.useCallback(()=>{W.current="collapsed",$("collapsed"),T("collapsed")},[$]),ne=Me.useCallback(()=>{W.current="default",$("default"),T("default")},[$]),X=Me.useCallback(()=>{N(V.current);try{window.localStorage.setItem(x,W.current),window.localStorage.setItem(b,String(V.current))}catch{}},[x,b]),ee=Me.useCallback(se=>{const ae=M.current;ae&&(se?ae.setAttribute("data-sidebar-gesture","active"):ae.removeAttribute("data-sidebar-gesture"))},[]);Me.useEffect(()=>{if(l)return;const se=ae=>{if(ae.code==="KeyB"&&(ae.metaKey||ae.ctrlKey)&&!(ae.altKey||ae.shiftKey)){if(ae.target instanceof HTMLElement){const he=ae.target.tagName;if(he==="INPUT"||he==="TEXTAREA"||he==="SELECT"||ae.target.isContentEditable)return}ae.preventDefault(),z()}};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[l,z]);const re=E?"default":C,ue=Me.useMemo(()=>({state:re,desktopState:C,width:_,minWidth:h,maxWidth:p,collapseBelow:y,collapsedWidth:m,isMobile:E,toggleSidebar:z,setWidth:U,collapse:G,expand:ne,commit:X,setGestureActive:ee,LinkComponent:f}),[re,C,_,h,p,y,m,E,z,U,G,ne,X,ee,f]),te=Me.useMemo(()=>({openMobile:P,mobileTriggerRef:B,setOpenMobile:K,setMobileDrawerPresent:Q}),[P,K]),ie={[crt]:`${j.state==="collapsed"?m:j.width}px`,"--sidebar-width-mobile":`${d}px`,display:"contents"};return a.jsx("div",{ref:M,"data-sidebar-scope":!0,"data-sidebar-state":C,"data-sidebar-mobile":E?"true":"false","data-sidebar-mobile-present":F?"true":"false",style:ie,suppressHydrationWarning:!0,children:a.jsx(aPe.Provider,{value:ue,children:a.jsx(oZt.Provider,{value:te,children:e})})})}const urt=10,xRs=5;function bRs({children:e,className:t,mobileMode:n="drawer"}){const{state:r,width:s,minWidth:i,maxWidth:o,collapseBelow:l,collapsedWidth:c,isMobile:u,openMobile:d,mobileTriggerRef:f,setOpenMobile:h,setMobileDrawerPresent:p,setWidth:m,collapse:v,expand:y,commit:x,toggleSidebar:b,setGestureActive:S}=pg(),k=r==="collapsed",j=k&&c===0,C=g.useRef(!1),T=g.useRef(null);g.useEffect(()=>()=>{T.current?.(),T.current=null},[]);const _=g.useCallback(L=>{if(L.button!==0)return;L.preventDefault(),C.current=!1,S(!0);const F=L.clientX,Q=L.currentTarget,q=L.pointerId;try{Q.setPointerCapture(q)}catch{}const B=Q.parentElement,V=B?B.getBoundingClientRect().left:0,W=document.body.style.cursor,M=document.body.style.userSelect,K=$=>{if($.pointerId!==q)return;const z=$.clientX-F;if(!C.current){if(Math.abs(z)<=xRs)return;C.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none"}const U=$.clientX-V;if(l>0&&U<l){v();return}y(),m(U)},D=$=>{$&&$.pointerId!==q||(window.removeEventListener("pointermove",K),window.removeEventListener("pointerup",D),window.removeEventListener("pointercancel",D),document.body.style.cursor=W,document.body.style.userSelect=M,S(!1),x(),T.current=null)};T.current=()=>D(),window.addEventListener("pointermove",K),window.addEventListener("pointerup",D),window.addEventListener("pointercancel",D)},[l,m,y,v,x,S]),N=g.useCallback(()=>{if(C.current){C.current=!1;return}b()},[b]),E=g.useCallback(L=>{switch(L.key){case"Enter":case" ":{L.preventDefault(),b();return}case"ArrowLeft":{if(L.preventDefault(),k)return;m(s-urt),x();return}case"ArrowRight":{if(L.preventDefault(),k){y(),x();return}m(s+urt),x();return}case"Home":{L.preventDefault(),y(),m(i),x();return}case"End":{L.preventDefault(),y(),m(o),x();return}}},[k,s,i,o,m,y,x,b]),A=g.useCallback(L=>{if(!(L.target instanceof Element))return;const F=L.target.closest("a");!F||!F.hasAttribute("href")||L.button!==0||L.metaKey||L.ctrlKey||L.shiftKey||L.altKey||F.target==="_blank"||F.hasAttribute("download")||h(!1)},[h]);if(u)return a.jsx(z_,{side:"left",open:d,onOpenChange:h,onOpenChangeComplete:L=>{L||p(!1)},children:a.jsxs(XL,{"data-mobile-mode":n,finalFocus:f,showCloseButton:n==="drawer",className:Z("border-0 bg-sidebar text-foreground",n==="takeover"?"w-[calc(100%-3.5rem)] max-w-none overflow-visible rounded-l-none rounded-r-3xl pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]":"w-3/4 max-w-(--sidebar-width-mobile) overflow-hidden rounded-none",t),children:[n==="takeover"?a.jsx(SK,{asChild:!0,children:a.jsx("button",{type:"button","aria-label":"Close",className:"group absolute top-2 -right-12 z-10 inline-flex size-11 touch-manipulation items-center justify-center transition-opacity duration-fast group-data-[ending-style]/popup:opacity-0 focus-visible:outline-hidden motion-reduce:duration-0",children:a.jsx("span",{className:Z(th,xx,Eht,"inline-flex size-9 items-center justify-center rounded-full backdrop-blur-sm group-focus-visible:ring-1 group-focus-visible:ring-border-focus"),children:a.jsx(hpt,{className:"size-4"})})})}):null,a.jsx(B0,{asChild:!0,children:a.jsx(RP,{children:"Navigation"})}),a.jsx(B0,{asChild:!0,children:a.jsx(JL,{children:"Primary site navigation drawer"})}),a.jsx("div",{onClick:A,className:Z("flex h-full min-h-0 flex-col overflow-hidden py-2",n==="takeover"?"px-4":"px-3"),children:e})]})});const P=k?c:s;return a.jsxs("div",{className:Z("sidebar-layout group/sidebar t-resize relative min-h-0 shrink-0 self-stretch bg-sidebar text-foreground","w-(--sidebar-width)","in-data-[sidebar-gesture=active]:transition-none",t,j&&"border-r-0 border-transparent"),children:[a.jsx("div",{className:Z("flex h-full min-h-0 flex-col overflow-hidden","transition-opacity duration-200 motion-reduce:transition-none","p-2",j&&"pointer-events-none p-0 opacity-0"),children:e}),a.jsx("div",{role:"separator","aria-orientation":"vertical","aria-valuenow":k?void 0:P,"aria-valuemin":k?void 0:i,"aria-valuemax":k?void 0:o,"aria-valuetext":k?"collapsed":`${P} pixels`,"aria-label":`Resize sidebar. Arrow keys to resize, Enter to ${k?"expand":"collapse"}.`,tabIndex:0,onPointerDown:_,onClick:N,onKeyDown:E,className:Z("group absolute top-0 -right-1 z-10 h-full w-2 cursor-col-resize touch-none","flex items-center justify-center","focus-visible:outline-hidden"),children:a.jsx(Tke,{className:Z("via-foreground/30 group-hover:opacity-100","group-focus-visible:via-border-focus group-focus-visible:opacity-100","in-data-[sidebar-gesture=active]:via-foreground/45 in-data-[sidebar-gesture=active]:opacity-100")})})]})}function wRs({"aria-label":e="Sidebar",mobileMode:t="takeover",variant:n="default",children:r,...s}){const i=Gx(),o=n==="raised"&&!i?.isMobile;return a.jsx("aside",{"aria-label":e,className:"contents",children:a.jsx(bRs,{mobileMode:t,...s,children:o?a.jsx("div",{"data-slot":"sidebar-surface",className:Z("-mr-2 -ml-4 flex min-h-0 flex-1 flex-col overflow-hidden rounded-r-xl py-1.5",i?.state==="collapsed"?"pr-2 pl-4":"pr-3.5 pl-5.5",Iht),children:r}):r})})}const Oee=["sidebar","more","hidden"],wZt={sidebar:"Always show",more:"Hide in More menu",hidden:"Never show"},SRs=ji(vt(),ff(Oee)),kRs="mastra:sidebar:link-visibility";function _3(e){return`${e.url}:${e.name}`}function drt(e,t){return`${e}:${t.name}`}function SZt(e,t){return e.defaultVisible??t<2?"sidebar":"more"}function kZt(e){return Oee.some(t=>t===e)}function ORs({open:e,onOpenChange:t,returnFocusRef:n,sections:r,placementOf:s,onPlacementChange:i}){const o=g.useId(),l=r.filter(c=>(c.moreLinks?.length??0)>0);return a.jsx(Yr,{open:e,onOpenChange:t,children:a.jsxs(Xr,{size:"md",finalFocus:n,children:[a.jsxs(Jr,{children:[a.jsx(Zr,{children:"Customize sidebar"}),a.jsx(Lo,{children:"Choose where each optional link appears. Changes save automatically in this browser."})]}),a.jsx(Qr,{className:"space-y-5",children:l.map(c=>{const u=c.moreLinks??[],d=c.title?`${o}-${c.key}`:void 0;return a.jsxs("section",{"aria-labelledby":d,"aria-label":d?void 0:c.key,className:"space-y-2",children:[c.title?a.jsx(Y,{as:"h3",id:d,variant:"label",tone:"muted",children:c.title}):null,a.jsx("ul",{className:"divide-y divide-border rounded-lg border border-border",children:u.map(f=>a.jsxs("li",{className:"flex min-h-11 items-center gap-2.5 py-1.5 pr-1.5 pl-3",children:[a.jsx("span",{"aria-hidden":"true",className:"flex shrink-0 text-muted-foreground [&_svg]:size-4",children:f.icon}),a.jsx(Y,{as:"span",variant:"body-sm",className:"min-w-0 flex-1 truncate",children:f.name}),a.jsxs(ms,{value:s(c.key,f,u.length),onValueChange:h=>{kZt(h)&&i(c.key,f,h)},children:[a.jsx(vs,{size:"sm",variant:"ghost",className:"w-44 shrink-0","aria-label":`${f.name} placement`,children:a.jsx(gs,{})}),a.jsx(ys,{children:Oee.map(h=>a.jsx(hr,{value:h,children:wZt[h]},h))})]})]},_3(f)))})]},c.key)})})]})})}function dPe({link:e,activeCandidates:t,level:n=0,isActive:r,...s}){const i=e.children??[];return a.jsx(cPe,{...s,link:e,isActive:r?.(e,t)??e.isActive,level:n,subItems:i.length>0?a.jsx(uPe,{className:"mt-0.5",children:i.map(o=>a.jsx(dPe,{link:o,activeCandidates:t,level:n+1,isActive:r},_3(o)))}):null})}function jRs({link:e,activeCandidates:t,isActive:n,placement:r,onPlacementChange:s,onCustomize:i}){const o=g.useRef(null);return a.jsxs(yo,{children:[a.jsx(yo.Trigger,{ref:l=>{o.current=l},render:a.jsx(dPe,{link:e,activeCandidates:t,isActive:n})}),a.jsxs(yo.Content,{"aria-label":`${e.name} options`,children:[a.jsx(yo.RadioGroup,{value:r,onValueChange:l=>{kZt(l)&&s(l)},children:Oee.map(l=>a.jsx(yo.RadioItem,{value:l,children:wZt[l]},l))}),a.jsx(yo.Separator,{}),a.jsx(yo.Item,{onClick:()=>i(o.current?.querySelector("a")??null),children:"Customize sidebar…"})]})]})}function CRs({links:e,activeCandidates:t,isActive:n,placementOf:r,onPlacementChange:s,onCustomize:i}){const l=Gx()?.LinkComponent??"a",c=v=>n?.(v,t)??v.isActive??!1,u=e.filter(v=>c(v)||r(v)==="sidebar"),d=e.filter(v=>!u.includes(v)&&r(v)==="more"),f=e.some(v=>r(v)!==SZt(v,e.length)),h=e.length>1||d.length>0||f,p=g.useRef(null);function m(v,y=!1){return a.jsxs(g.Fragment,{children:[a.jsxs(lt.Item,{nativeButton:!1,inset:y,render:a.jsx(l,{href:v.url,.../^(https?:)?\/\//.test(v.url)?{target:"_blank",rel:"noreferrer"}:{}}),"aria-current":c(v)?"page":void 0,children:[v.icon,v.name]}),v.children?.map(x=>m(x,!0))]},_3(v))}return a.jsxs(a.Fragment,{children:[u.map(v=>a.jsx(jRs,{link:v,activeCandidates:t,isActive:n,placement:r(v),onPlacementChange:y=>s(v,y),onCustomize:y=>i(y,()=>p.current)},_3(v))),h?a.jsxs(lt,{modal:!1,children:[a.jsx(cPe,{link:{name:"More",url:"",icon:a.jsx(AN,{})},render:a.jsxs(lt.Trigger,{ref:p,render:a.jsx("button",{type:"button"}),"aria-label":"More",children:[a.jsx(AN,{"aria-hidden":"true"}),a.jsx(lPe,{children:"More"})]})}),a.jsxs(lt.Content,{align:"start","aria-label":"More navigation",className:"min-w-44",children:[d.map(v=>m(v)),d.length>0&&a.jsx(lt.Separator,{}),a.jsxs(lt.Item,{onClick:()=>i(p.current,()=>p.current),children:[a.jsx(mL,{}),"Customize sidebar"]})]})]}):null]})}function _Rs({sections:e,isActive:t,className:n,visibilityStorageKey:r}){const s=g.useId(),[i,o]=g.useState(!1),l=g.useRef(null),c=g.useRef(()=>null),[u,d]=Tk({initialKey:r,defaultValue:{},schema:SRs});function f(v,y,x){return u[drt(v,y)]??SZt(y,x)}function h(v,y){l.current=v,c.current=y,o(!0)}function p(v){!v&&!l.current?.isConnected&&(l.current=c.current()),o(v)}function m(v,y,x){d(b=>({...b,[drt(v,y)]:x}))}return a.jsxs(a.Fragment,{children:[e.map(v=>{const y=v.links.length>0&&v.separator,x=v.title?`${s}-${v.key}`:void 0,b=v.moreLinks??[],S=[...v.links,...b];return a.jsxs(mZt,{className:n,"aria-labelledby":x,"aria-label":x?void 0:v.key,children:[y?a.jsx(gZt,{className:"[&:after]:border-border"}):null,v.title?a.jsx(dZt,{id:x,href:v.href,isActive:v.isHeaderActive,children:v.title}):null,a.jsxs(uPe,{children:[v.links.map(k=>a.jsx(dPe,{link:k,activeCandidates:S,isActive:t},_3(k))),b.length>0?a.jsx(CRs,{links:b,activeCandidates:S,isActive:t,placementOf:k=>f(v.key,k,b.length),onPlacementChange:(k,j)=>m(v.key,k,j),onCustomize:h}):null]})]},v.key)}),a.jsx(ORs,{open:i,onOpenChange:p,returnFocusRef:l,sections:e,placementOf:f,onPlacementChange:m})]})}function TRs({visibilityStorageKey:e=kRs,...t}){return a.jsx(_Rs,{...t,visibilityStorageKey:e},e)}const ho=Object.assign(wRs,{Brand:X$s,CommandHeader:J$s,Footer:B$s,FooterMeta:V$s,Header:eRs,Meter:Y$s,MobileTrigger:vRs,Nav:nRs,NavHeader:dZt,NavLabel:lPe,NavLink:cPe,NavList:uPe,NavSection:mZt,NavSeparator:gZt,NavShowMore:fRs,NavStack:gRs,Provider:bZt,SearchTrigger:tRs,Sections:TRs,Trigger:uZt});function IRs(){const{data:e,isLoading:t}=Zl(),{isLoading:n,canAccessAgentBuilder:r}=$x();return t||n?{isVisible:!1}:e?!!e.enabled&&!bp(e)?{isVisible:!1}:{isVisible:r}:{isVisible:!1}}function OZt(){const{isImpersonating:e,impersonatedRole:t,stopImpersonation:n}=pG();return!e||!t?null:a.jsxs("div",{className:"mx-3 mb-2 flex items-center gap-2 rounded-md border border-info-edge bg-info-subtle px-3 py-1.5",children:[a.jsx(Fa,{className:"h-3.5 w-3.5 shrink-0 text-info-subtle-foreground"}),a.jsxs(Y,{variant:"meta",className:"truncate text-info-subtle-foreground",children:["Previewing ",a.jsx("span",{className:"font-medium capitalize",children:t.name})," experience"]}),a.jsx("button",{type:"button",onClick:n,className:"ml-auto shrink-0 rounded p-0.5 text-info-subtle-foreground hover:bg-info-edge",title:"Exit role preview",children:a.jsx(Mn,{className:"h-3 w-3"})})]})}var frt=1,ERs=.9,NRs=.8,ARs=.17,zue=.1,Fue=.999,PRs=.9999,$Rs=.99,RRs=/[\\\/_+.#"@\[\(\{&]/,MRs=/[\\\/_+.#"@\[\(\{&]/g,DRs=/[\s-]/,jZt=/[\s-]/g;function cxe(e,t,n,r,s,i,o){if(i===t.length)return s===e.length?frt:$Rs;var l=`${s},${i}`;if(o[l]!==void 0)return o[l];for(var c=r.charAt(i),u=n.indexOf(c,s),d=0,f,h,p,m;u>=0;)f=cxe(e,t,n,r,u+1,i+1,o),f>d&&(u===s?f*=frt:RRs.test(e.charAt(u-1))?(f*=NRs,p=e.slice(s,u-1).match(MRs),p&&s>0&&(f*=Math.pow(Fue,p.length))):DRs.test(e.charAt(u-1))?(f*=ERs,m=e.slice(s,u-1).match(jZt),m&&s>0&&(f*=Math.pow(Fue,m.length))):(f*=ARs,s>0&&(f*=Math.pow(Fue,u-s))),e.charAt(u)!==t.charAt(i)&&(f*=PRs)),(f<zue&&n.charAt(u-1)===r.charAt(i+1)||r.charAt(i+1)===r.charAt(i)&&n.charAt(u-1)!==r.charAt(i))&&(h=cxe(e,t,n,r,u+1,i+2,o),h*zue>f&&(f=h*zue)),f>d&&(d=f),u=n.indexOf(c,u+1);return o[l]=d,d}function hrt(e){return e.toLowerCase().replace(jZt," ")}function LRs(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,cxe(e,t,hrt(e),hrt(t),0,0,{})}function lS(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e?.(s),n===!1||!s||!s.defaultPrevented)return t?.(s)}}function prt(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function XA(...e){return t=>{let n=!1;const r=e.map(s=>{const i=prt(s,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let s=0;s<r.length;s++){const i=r[s];typeof i=="function"?i():prt(e[s],null)}}}}function hT(...e){return g.useCallback(XA(...e),e)}function zRs(e,t=[]){let n=[];function r(i,o){const l=g.createContext(o);l.displayName=i+"Context";const c=n.length;n=[...n,o];const u=f=>{const{scope:h,children:p,...m}=f,v=h?.[e]?.[c]||l,y=g.useMemo(()=>m,Object.values(m));return a.jsx(v.Provider,{value:y,children:p})};u.displayName=i+"Provider";function d(f,h,p={}){const{optional:m=!1}=p,v=h?.[e]?.[c]||l,y=g.useContext(v);if(y)return y;if(o!==void 0)return o;if(!m)throw new Error(`\`${f}\` must be used within \`${i}\``)}return[u,d]}const s=()=>{const i=n.map(o=>g.createContext(o));return function(l){const c=l?.[e]||i;return g.useMemo(()=>({[`__scope${e}`]:{...l,[e]:c}}),[l,c])}};return s.scopeName=e,[r,FRs(s,...t)]}function FRs(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(i){const o=r.reduce((l,{useScope:c,scopeName:u})=>{const f=c(i)[`__scope${u}`];return{...l,...f}},{});return g.useMemo(()=>({[`__scope${t.scopeName}`]:o}),[o])}};return n.scopeName=t.scopeName,n}var T3=globalThis?.document?g.useLayoutEffect:()=>{},BRs=tP[" useId ".trim().toString()]||(()=>{}),VRs=0;function S0(e){const[t,n]=g.useState(BRs());return T3(()=>{n(r=>r??String(VRs++))},[e]),t?`radix-${t}`:""}var URs=tP[" useInsertionEffect ".trim().toString()]||T3;function qRs({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[s,i,o]=QRs({defaultProp:t,onChange:n}),l=e!==void 0,c=l?e:s;{const d=g.useRef(e!==void 0);g.useEffect(()=>{const f=d.current;f!==l&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${l?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=l},[l,r])}const u=g.useCallback(d=>{if(l){const f=ZRs(d)?d(e):d;f!==e&&o.current?.(f)}else i(d)},[l,e,i,o]);return[c,u]}function QRs({defaultProp:e,onChange:t}){const[n,r]=g.useState(e),s=g.useRef(n),i=g.useRef(t);return URs(()=>{i.current=t},[t]),g.useEffect(()=>{s.current!==n&&(i.current?.(n),s.current=n)},[n,s]),[n,r,i]}function ZRs(e){return typeof e=="function"}function CZt(e){const t=g.forwardRef((n,r)=>{let{children:s,...i}=n,o=null,l=!1;const c=[];mrt(s)&&typeof sB=="function"&&(s=sB(s._payload)),g.Children.forEach(s,h=>{if(YRs(h)){l=!0;const p=h;let m="child"in p.props?p.props.child:p.props.children;mrt(m)&&typeof sB=="function"&&(m=sB(m._payload)),o=HRs(p,m),c.push(o?.props?.children)}else c.push(h)}),o?o=g.cloneElement(o,void 0,c):!l&&g.Children.count(s)===1&&g.isValidElement(s)&&(o=s);const u=o?KRs(o):void 0,d=hT(r,u);if(!o){if(s||s===0)throw new Error(l?tMs(e):eMs(e));return s}const f=GRs(i,o.props??{});return o.type!==g.Fragment&&(f.ref=r?d:u),g.cloneElement(o,f)});return t.displayName=`${e}.Slot`,t}var WRs=Symbol.for("radix.slottable"),HRs=(e,t)=>{if("child"in e.props){const n=e.props.child;return g.isValidElement(n)?g.cloneElement(n,void 0,e.props.children(n.props.children)):null}return g.isValidElement(t)?t:null};function GRs(e,t){const n={...t};for(const r in t){const s=e[r],i=t[r];/^on[A-Z]/.test(r)?s&&i?n[r]=(...l)=>{const c=i(...l);return s(...l),c}:s&&(n[r]=s):r==="style"?n[r]={...s,...i}:r==="className"&&(n[r]=[s,i].filter(Boolean).join(" "))}return{...e,...n}}function KRs(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function YRs(e){return g.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===WRs}var XRs=Symbol.for("react.lazy");function mrt(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===XRs&&"_payload"in e&&JRs(e._payload)}function JRs(e){return typeof e=="object"&&e!==null&&"then"in e}var eMs=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,tMs=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,sB=tP[" use ".trim().toString()],nMs=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Uu=nMs.reduce((e,t)=>{const n=CZt(`Primitive.${t}`),r=g.forwardRef((s,i)=>{const{asChild:o,...l}=s,c=o?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),a.jsx(c,{...l,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function rMs(e,t){e&&So.flushSync(()=>e.dispatchEvent(t))}function I3(e){const t=g.useRef(e);return g.useEffect(()=>{t.current=e}),g.useMemo(()=>((...n)=>t.current?.(...n)),[])}var sMs="DismissableLayer",uxe="dismissableLayer.update",iMs="dismissableLayer.pointerDownOutside",oMs="dismissableLayer.focusOutside",grt,fPe=g.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),_Zt=g.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:l,onDismiss:c,...u}=e,d=g.useContext(fPe),[f,h]=g.useState(null),p=f?.ownerDocument??globalThis?.document,[,m]=g.useState({}),v=hT(t,h),y=Array.from(d.layers),[x]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),b=x?y.indexOf(x):-1,S=f?y.indexOf(f):-1,k=d.layersWithOutsidePointerEventsDisabled.size>0,j=S>=b,C=g.useRef(!1),T=dMs(A=>{i?.(A),l?.(A),A.defaultPrevented||c?.()},{ownerDocument:p,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:C,dismissableSurfaces:d.dismissableSurfaces,shouldHandlePointerDownOutside:g.useCallback(A=>{if(!(A instanceof Node))return!1;const P=[...d.branches].some(L=>L.contains(A));return j&&!P},[d.branches,j])}),_=fMs(A=>{if(r&&C.current)return;const P=A.target;[...d.branches].some(F=>F.contains(P))||(o?.(A),l?.(A),A.defaultPrevented||c?.())},p),N=f?S===y.length-1:!1,E=I3(A=>{A.key==="Escape"&&(s?.(A),!A.defaultPrevented&&c&&(A.preventDefault(),c()))});return g.useEffect(()=>{if(N)return p.addEventListener("keydown",E,{capture:!0}),()=>p.removeEventListener("keydown",E,{capture:!0})},[p,N,E]),g.useEffect(()=>{if(f)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(grt=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(f)),d.layers.add(f),vrt(),()=>{n&&(d.layersWithOutsidePointerEventsDisabled.delete(f),d.layersWithOutsidePointerEventsDisabled.size===0&&(p.body.style.pointerEvents=grt))}},[f,p,n,d]),g.useEffect(()=>()=>{f&&(d.layers.delete(f),d.layersWithOutsidePointerEventsDisabled.delete(f),vrt())},[f,d]),g.useEffect(()=>{const A=()=>m({});return document.addEventListener(uxe,A),()=>document.removeEventListener(uxe,A)},[]),a.jsx(Uu.div,{...u,ref:v,style:{pointerEvents:k?j?"auto":"none":void 0,...e.style},onFocusCapture:lS(e.onFocusCapture,_.onFocusCapture),onBlurCapture:lS(e.onBlurCapture,_.onBlurCapture),onPointerDownCapture:lS(e.onPointerDownCapture,T.onPointerDownCapture)})});_Zt.displayName=sMs;var aMs="DismissableLayerBranch",lMs=g.forwardRef((e,t)=>{const n=g.useContext(fPe),r=g.useRef(null),s=hT(t,r);return g.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),a.jsx(Uu.div,{...e,ref:s})});lMs.displayName=aMs;function cMs(){const e=g.useContext(fPe),[t,n]=g.useState(null);return g.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var uMs=()=>!0;function dMs(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:s,dismissableSurfaces:i,shouldHandlePointerDownOutside:o=uMs}=t,l=I3(e),c=g.useRef(!1),u=g.useRef(!1),d=g.useRef(new Map),f=g.useRef(()=>{});return g.useEffect(()=>{function h(){u.current=!1,s.current=!1,d.current.clear()}function p(){return Array.from(d.current.values()).some(Boolean)}function m(S){if(!u.current)return;const k=S.target;k instanceof Node&&[...i].some(C=>C.contains(k))||d.current.set(S.type,!0),S.type==="click"&&window.setTimeout(()=>{u.current&&f.current()},0)}function v(S){u.current&&d.current.set(S.type,!1)}const y=S=>{if(S.target&&!c.current){let k=function(){n.removeEventListener("click",f.current);const C=p();h(),C||TZt(iMs,l,j,{discrete:!0})};if(!o(S.target)){n.removeEventListener("click",f.current),h(),c.current=!1;return}const j={originalEvent:S};u.current=!0,s.current=r&&S.button===0,d.current.clear(),!r||S.button!==0?k():(n.removeEventListener("click",f.current),f.current=k,n.addEventListener("click",f.current,{once:!0}))}else n.removeEventListener("click",f.current),h();c.current=!1},x=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const S of x)n.addEventListener(S,m,!0),n.addEventListener(S,v);const b=window.setTimeout(()=>{n.addEventListener("pointerdown",y)},0);return()=>{window.clearTimeout(b),n.removeEventListener("pointerdown",y),n.removeEventListener("click",f.current);for(const S of x)n.removeEventListener(S,m,!0),n.removeEventListener(S,v)}},[n,l,r,s,i,o]),{onPointerDownCapture:()=>c.current=!0}}function fMs(e,t=globalThis?.document){const n=I3(e),r=g.useRef(!1);return g.useEffect(()=>{const s=i=>{i.target&&!r.current&&TZt(oMs,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",s),()=>t.removeEventListener("focusin",s)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function vrt(){const e=new CustomEvent(uxe);document.dispatchEvent(e)}function TZt(e,t,n,{discrete:r}){const s=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&s.addEventListener(e,t,{once:!0}),r?rMs(s,i):s.dispatchEvent(i)}var Bue="focusScope.autoFocusOnMount",Vue="focusScope.autoFocusOnUnmount",yrt={bubbles:!1,cancelable:!0},hMs="FocusScope",IZt=g.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:i,...o}=e,[l,c]=g.useState(null),u=I3(s),d=I3(i),f=g.useRef(null),h=hT(t,c),p=g.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;g.useEffect(()=>{if(r){let v=function(S){if(p.paused||!l)return;const k=S.target;l.contains(k)?f.current=k:h1(f.current,{select:!0})},y=function(S){if(p.paused||!l)return;const k=S.relatedTarget;k!==null&&(l.contains(k)||h1(f.current,{select:!0}))},x=function(S){if(document.activeElement===document.body)for(const j of S)j.removedNodes.length>0&&h1(l)};document.addEventListener("focusin",v),document.addEventListener("focusout",y);const b=new MutationObserver(x);return l&&b.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",v),document.removeEventListener("focusout",y),b.disconnect()}}},[r,l,p.paused]),g.useEffect(()=>{if(l){brt.add(p);const v=document.activeElement;if(!l.contains(v)){const x=new CustomEvent(Bue,yrt);l.addEventListener(Bue,u),l.dispatchEvent(x),x.defaultPrevented||(pMs(xMs(EZt(l)),{select:!0}),document.activeElement===v&&h1(l))}return()=>{l.removeEventListener(Bue,u),setTimeout(()=>{const x=new CustomEvent(Vue,yrt);l.addEventListener(Vue,d),l.dispatchEvent(x),x.defaultPrevented||h1(v??document.body,{select:!0}),l.removeEventListener(Vue,d),brt.remove(p)},0)}}},[l,u,d,p]);const m=g.useCallback(v=>{if(!n&&!r||p.paused)return;const y=v.key==="Tab"&&!v.altKey&&!v.ctrlKey&&!v.metaKey,x=document.activeElement;if(y&&x){const b=v.currentTarget,[S,k]=mMs(b);S&&k?!v.shiftKey&&x===k?(v.preventDefault(),n&&h1(S,{select:!0})):v.shiftKey&&x===S&&(v.preventDefault(),n&&h1(k,{select:!0})):x===b&&v.preventDefault()}},[n,r,p.paused]);return a.jsx(Uu.div,{tabIndex:-1,...o,ref:h,onKeyDown:m})});IZt.displayName=hMs;function pMs(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(h1(r,{select:t}),document.activeElement!==n)return}function mMs(e){const t=EZt(e),n=xrt(t,e),r=xrt(t.reverse(),e);return[n,r]}function EZt(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 xrt(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):gMs(r,{upTo:t})))return r}function gMs(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 vMs(e){return e instanceof HTMLInputElement&&"select"in e}function h1(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&vMs(e)&&t&&e.select()}}var brt=yMs();function yMs(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=wrt(e,t),e.unshift(t)},remove(t){e=wrt(e,t),e[0]?.resume()}}}function wrt(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function xMs(e){return e.filter(t=>t.tagName!=="A")}var bMs="Portal",NZt=g.forwardRef((e,t)=>{const{container:n,...r}=e,[s,i]=g.useState(!1);T3(()=>i(!0),[]);const o=n||s&&globalThis?.document?.body;return o?So.createPortal(a.jsx(Uu.div,{...r,ref:t}),o):null});NZt.displayName=bMs;function wMs(e,t){return g.useReducer((n,r)=>t[n][r]??n,e)}var jee=e=>{const{present:t,children:n}=e,r=SMs(t),s=typeof n=="function"?n({present:r.isPresent}):g.Children.only(n),i=kMs(r.ref,OMs(s));return typeof n=="function"||r.isPresent?g.cloneElement(s,{ref:i}):null};jee.displayName="Presence";function SMs(e){const[t,n]=g.useState(),r=g.useRef(null),s=g.useRef(e),i=g.useRef("none"),o=g.useRef(void 0),l=e?"mounted":"unmounted",[c,u]=wMs(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return g.useEffect(()=>{c==="mounted"?(i.current=o.current??UM(r.current),o.current=void 0):i.current="none"},[c]),T3(()=>{const d=r.current,f=s.current;if(f!==e){const p=i.current,m=UM(d);e?(o.current=m,u("MOUNT")):m==="none"||d?.display==="none"?u("UNMOUNT"):u(f&&p!==m?"ANIMATION_OUT":"UNMOUNT"),s.current=e}},[e,u]),T3(()=>{if(t){let d;const f=t.ownerDocument.defaultView??window,h=m=>{const y=UM(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&y&&(u("ANIMATION_END"),!s.current)){const x=t.style.animationFillMode;t.style.animationFillMode="forwards",d=f.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=x)})}},p=m=>{m.target===t&&(i.current=UM(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{f.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:g.useCallback(d=>{if(d){const f=getComputedStyle(d);r.current=f,o.current=UM(f)}else r.current=null;n(d)},[])}}function Srt(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function kMs(...e){const t=g.useRef(e);return t.current=e,g.useCallback(n=>{const r=t.current;let s=!1;const i=r.map(o=>{const l=Srt(o,n);return!s&&typeof l=="function"&&(s=!0),l});if(s)return()=>{for(let o=0;o<i.length;o++){const l=i[o];typeof l=="function"?l():Srt(r[o],null)}}},[])}function UM(e){return e?.animationName||"none"}function OMs(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var iB=0,_I=null;function jMs(){g.useEffect(()=>{_I||(_I={start:krt(),end:krt()});const{start:e,end:t}=_I;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),iB++,()=>{iB===1&&(_I?.start.remove(),_I?.end.remove(),_I=null),iB=Math.max(0,iB-1)}},[])}function krt(){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 zy=function(){return zy=Object.assign||function(t){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},zy.apply(this,arguments)};function AZt(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 CMs(e,t,n){if(n||arguments.length===2)for(var r=0,s=t.length,i;r<s;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))}var RV="right-scroll-bar-position",MV="width-before-scroll-bar",_Ms="with-scroll-bars-hidden",TMs="--removed-body-scroll-bar-size";function Uue(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function IMs(e,t){var n=g.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 EMs=typeof window<"u"?g.useLayoutEffect:g.useEffect,Ort=new WeakMap;function NMs(e,t){var n=IMs(null,function(r){return e.forEach(function(s){return Uue(s,r)})});return EMs(function(){var r=Ort.get(n);if(r){var s=new Set(r),i=new Set(e),o=n.current;s.forEach(function(l){i.has(l)||Uue(l,null)}),i.forEach(function(l){s.has(l)||Uue(l,o)})}Ort.set(n,e)},[e]),n}function AMs(e){return e}function PMs(e,t){t===void 0&&(t=AMs);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(i){var o=t(i,r);return n.push(o),function(){n=n.filter(function(l){return l!==o})}},assignSyncMedium:function(i){for(r=!0;n.length;){var o=n;n=[],o.forEach(i)}n={push:function(l){return i(l)},filter:function(){return n}}},assignMedium:function(i){r=!0;var o=[];if(n.length){var l=n;n=[],l.forEach(i),o=n}var c=function(){var d=o;o=[],d.forEach(i)},u=function(){return Promise.resolve().then(c)};u(),n={push:function(d){o.push(d),u()},filter:function(d){return o=o.filter(d),n}}}};return s}function $Ms(e){e===void 0&&(e={});var t=PMs(null);return t.options=zy({async:!0,ssr:!1},e),t}var PZt=function(e){var t=e.sideCar,n=AZt(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 g.createElement(r,zy({},n))};PZt.isSideCarExport=!0;function RMs(e,t){return e.useMedium(t),PZt}var $Zt=$Ms(),que=function(){},Cee=g.forwardRef(function(e,t){var n=g.useRef(null),r=g.useState({onScrollCapture:que,onWheelCapture:que,onTouchMoveCapture:que}),s=r[0],i=r[1],o=e.forwardProps,l=e.children,c=e.className,u=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,p=e.noRelative,m=e.noIsolation,v=e.inert,y=e.allowPinchZoom,x=e.as,b=x===void 0?"div":x,S=e.gapMode,k=AZt(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),j=h,C=NMs([n,t]),T=zy(zy({},k),s);return g.createElement(g.Fragment,null,d&&g.createElement(j,{sideCar:$Zt,removeScrollBar:u,shards:f,noRelative:p,noIsolation:m,inert:v,setCallbacks:i,allowPinchZoom:!!y,lockRef:n,gapMode:S}),o?g.cloneElement(g.Children.only(l),zy(zy({},T),{ref:C})):g.createElement(b,zy({},T,{className:c,ref:C}),l))});Cee.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Cee.classNames={fullWidth:MV,zeroRight:RV};var MMs=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function DMs(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=MMs();return t&&e.setAttribute("nonce",t),e}function LMs(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function zMs(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var FMs=function(){var e=0,t=null;return{add:function(n){e==0&&(t=DMs())&&(LMs(t,n),zMs(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},BMs=function(){var e=FMs();return function(t,n){g.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},RZt=function(){var e=BMs(),t=function(n){var r=n.styles,s=n.dynamic;return e(r,s),null};return t},VMs={left:0,top:0,right:0,gap:0},Que=function(e){return parseInt(e||"",10)||0},UMs=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[Que(n),Que(r),Que(s)]},qMs=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return VMs;var t=UMs(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])}},QMs=RZt(),lN="data-scroll-locked",ZMs=function(e,t,n,r){var s=e.left,i=e.top,o=e.right,l=e.gap;return n===void 0&&(n="margin"),`
702
702
  .`.concat(_Ms,` {