@mastra/deployer-cloud 1.75.0-alpha.8 → 1.75.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/studio/assets/{CodeDiff.es-B7T1Sq6b.js → CodeDiff.es-CB_gYanJ.js} +1 -1
- package/dist/studio/assets/{core-DbjTmJHj.js → core-DERPlZmN.js} +1 -1
- package/dist/studio/assets/{index-DhZ-a7Mm.js → index-8LAG8mz_.js} +1 -1
- package/dist/studio/assets/{index-BZg0p4AG.js → index-BGtB2z61.js} +2 -2
- package/dist/studio/assets/{main-mhgQxnym.js → main-BdkpmTmk.js} +4 -4
- package/dist/studio/index.html +1 -1
- package/package.json +7 -7
- package/versions.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-DERPlZmN.js","./index-8LAG8mz_.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-CB_gYanJ.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{_ as Ii}from"./preload-helper-PPVm8Dsz.js";function LQt(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 pv(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var fte={exports:{}},V$={};var A$e;function zQt(){if(A$e)return V$;A$e=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 V$.Fragment=t,V$.jsx=n,V$.jsxs=n,V$}var P$e;function FQt(){return P$e||(P$e=1,fte.exports=zQt()),fte.exports}var a=FQt(),hte={exports:{}},Jr={},$$e;function BQt(){if($$e)return Jr;$$e=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(L){return L===null||typeof L!="object"?null:(L=p&&L[p]||L["@@iterator"],typeof L=="function"?L:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,x={};function b(L,$,F){this.props=L,this.context=$,this.refs=x,this.updater=F||v}b.prototype.isReactComponent={},b.prototype.setState=function(L,$){if(typeof L!="object"&&typeof L!="function"&&L!=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,L,$,"setState")},b.prototype.forceUpdate=function(L){this.updater.enqueueForceUpdate(this,L,"forceUpdate")};function S(){}S.prototype=b.prototype;function k(L,$,F){this.props=L,this.context=$,this.refs=x,this.updater=F||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 I(L,$,F){var U=F.ref;return{$$typeof:t,type:L,key:$,ref:U!==void 0?U:null,props:F}}function P(L,$){return I(L.type,$,L.props)}function A(L){return typeof L=="object"&&L!==null&&L.$$typeof===t}function D(L){var $={"=":"=0",":":"=2"};return"$"+L.replace(/[=:]/g,function(F){return $[F]})}var z=/\/+/g;function Q(L,$){return typeof L=="object"&&L!==null&&L.key!=null?D(""+L.key):$.toString(36)}function q(L){switch(L.status){case"fulfilled":return L.value;case"rejected":throw L.reason;default:switch(typeof L.status=="string"?L.then(T,T):(L.status="pending",L.then(function($){L.status==="pending"&&(L.status="fulfilled",L.value=$)},function($){L.status==="pending"&&(L.status="rejected",L.reason=$)})),L.status){case"fulfilled":return L.value;case"rejected":throw L.reason}}throw L}function B(L,$,F,U,K){var ne=typeof L;(ne==="undefined"||ne==="boolean")&&(L=null);var X=!1;if(L===null)X=!0;else switch(ne){case"bigint":case"string":case"number":X=!0;break;case"object":switch(L.$$typeof){case t:case n:X=!0;break;case f:return X=L._init,B(X(L._payload),$,F,U,K)}}if(X)return K=K(L),X=U===""?"."+Q(L,0):U,C(K)?(F="",X!=null&&(F=X.replace(z,"$&/")+"/"),B(K,$,F,"",function(ue){return ue})):K!=null&&(A(K)&&(K=P(K,F+(K.key==null||L&&L.key===K.key?"":(""+K.key).replace(z,"$&/")+"/")+X)),$.push(K)),1;X=0;var te=U===""?".":U+":";if(C(L))for(var oe=0;oe<L.length;oe++)U=L[oe],ne=te+Q(U,oe),X+=B(U,$,F,ne,K);else if(oe=m(L),typeof oe=="function")for(L=oe.call(L),oe=0;!(U=L.next()).done;)U=U.value,ne=te+Q(U,oe++),X+=B(U,$,F,ne,K);else if(ne==="object"){if(typeof L.then=="function")return B(q(L),$,F,U,K);throw $=String(L),Error("Objects are not valid as a React child (found: "+($==="[object Object]"?"object with keys {"+Object.keys(L).join(", ")+"}":$)+"). If you meant to render a collection of children, use an array instead.")}return X}function V(L,$,F){if(L==null)return L;var U=[],K=0;return B(L,U,"","",function(ne){return $.call(F,ne,K++)}),U}function H(L){if(L._status===-1){var $=L._result;$=$(),$.then(function(F){(L._status===0||L._status===-1)&&(L._status=1,L._result=F)},function(F){(L._status===0||L._status===-1)&&(L._status=2,L._result=F)}),L._status===-1&&(L._status=0,L._result=$)}if(L._status===1)return L._result.default;throw L._result}var M=typeof reportError=="function"?reportError:function(L){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var $=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof L=="object"&&L!==null&&typeof L.message=="string"?String(L.message):String(L),error:L});if(!window.dispatchEvent($))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",L);return}console.error(L)},G={map:V,forEach:function(L,$,F){V(L,function(){$.apply(this,arguments)},F)},count:function(L){var $=0;return V(L,function(){$++}),$},toArray:function(L){return V(L,function($){return $})||[]},only:function(L){if(!A(L))throw Error("React.Children.only expected to receive a single React element child.");return L}};return Jr.Activity=h,Jr.Children=G,Jr.Component=b,Jr.Fragment=r,Jr.Profiler=i,Jr.PureComponent=k,Jr.StrictMode=s,Jr.Suspense=u,Jr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=_,Jr.__COMPILER_RUNTIME={__proto__:null,c:function(L){return _.H.useMemoCache(L)}},Jr.cache=function(L){return function(){return L.apply(null,arguments)}},Jr.cacheSignal=function(){return null},Jr.cloneElement=function(L,$,F){if(L==null)throw Error("The argument must be a React element, but you passed "+L+".");var U=y({},L.props),K=L.key;if($!=null)for(ne in $.key!==void 0&&(K=""+$.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=F;else if(1<ne){for(var X=Array(ne),te=0;te<ne;te++)X[te]=arguments[te+2];U.children=X}return I(L.type,K,U)},Jr.createContext=function(L){return L={$$typeof:l,_currentValue:L,_currentValue2:L,_threadCount:0,Provider:null,Consumer:null},L.Provider=L,L.Consumer={$$typeof:o,_context:L},L},Jr.createElement=function(L,$,F){var U,K={},ne=null;if($!=null)for(U in $.key!==void 0&&(ne=""+$.key),$)N.call($,U)&&U!=="key"&&U!=="__self"&&U!=="__source"&&(K[U]=$[U]);var X=arguments.length-2;if(X===1)K.children=F;else if(1<X){for(var te=Array(X),oe=0;oe<X;oe++)te[oe]=arguments[oe+2];K.children=te}if(L&&L.defaultProps)for(U in X=L.defaultProps,X)K[U]===void 0&&(K[U]=X[U]);return I(L,ne,K)},Jr.createRef=function(){return{current:null}},Jr.forwardRef=function(L){return{$$typeof:c,render:L}},Jr.isValidElement=A,Jr.lazy=function(L){return{$$typeof:f,_payload:{_status:-1,_result:L},_init:H}},Jr.memo=function(L,$){return{$$typeof:d,type:L,compare:$===void 0?null:$}},Jr.startTransition=function(L){var $=_.T,F={};_.T=F;try{var U=L(),K=_.S;K!==null&&K(F,U),typeof U=="object"&&U!==null&&typeof U.then=="function"&&U.then(T,M)}catch(ne){M(ne)}finally{$!==null&&F.types!==null&&($.types=F.types),_.T=$}},Jr.unstable_useCacheRefresh=function(){return _.H.useCacheRefresh()},Jr.use=function(L){return _.H.use(L)},Jr.useActionState=function(L,$,F){return _.H.useActionState(L,$,F)},Jr.useCallback=function(L,$){return _.H.useCallback(L,$)},Jr.useContext=function(L){return _.H.useContext(L)},Jr.useDebugValue=function(){},Jr.useDeferredValue=function(L,$){return _.H.useDeferredValue(L,$)},Jr.useEffect=function(L,$){return _.H.useEffect(L,$)},Jr.useEffectEvent=function(L){return _.H.useEffectEvent(L)},Jr.useId=function(){return _.H.useId()},Jr.useImperativeHandle=function(L,$,F){return _.H.useImperativeHandle(L,$,F)},Jr.useInsertionEffect=function(L,$){return _.H.useInsertionEffect(L,$)},Jr.useLayoutEffect=function(L,$){return _.H.useLayoutEffect(L,$)},Jr.useMemo=function(L,$){return _.H.useMemo(L,$)},Jr.useOptimistic=function(L,$){return _.H.useOptimistic(L,$)},Jr.useReducer=function(L,$,F){return _.H.useReducer(L,$,F)},Jr.useRef=function(L){return _.H.useRef(L)},Jr.useState=function(L){return _.H.useState(L)},Jr.useSyncExternalStore=function(L,$,F){return _.H.useSyncExternalStore(L,$,F)},Jr.useTransition=function(){return _.H.useTransition()},Jr.version="19.2.7",Jr}var R$e;function gA(){return R$e||(R$e=1,hte.exports=BQt()),hte.exports}var g=gA();const Re=pv(g),vA=LQt({__proto__:null,default:Re},[g]);var pte={exports:{}},U$={},mte={exports:{}},gte={};var M$e;function VQt(){return M$e||(M$e=1,(function(e){function t(q,B){var V=q.length;q.push(B);e:for(;0<V;){var H=V-1>>>1,M=q[H];if(0<s(M,B))q[H]=B,q[V]=M,V=H;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 H=0,M=q.length,G=M>>>1;H<G;){var L=2*(H+1)-1,$=q[L],F=L+1,U=q[F];if(0>s($,V))F<M&&0>s(U,$)?(q[H]=U,q[F]=V,H=F):(q[H]=$,q[L]=V,H=L);else if(F<M&&0>s(U,V))q[H]=U,q[F]=V,H=F;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,A());else{var B=n(u);B!==null&&Q(j,B.startTime-q)}}var C=!1,T=-1,_=5,N=-1;function I(){return y?!0:!(e.unstable_now()-N<_)}function P(){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&&I());){var H=f.callback;if(typeof H=="function"){f.callback=null,h=f.priorityLevel;var M=H(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 G=n(u);G!==null&&Q(j,G.startTime-q),B=!1}}break e}finally{f=null,h=V,p=!1}B=void 0}}finally{B?A():C=!1}}}var A;if(typeof S=="function")A=function(){S(P)};else if(typeof MessageChannel<"u"){var D=new MessageChannel,z=D.port2;D.port1.onmessage=P,A=function(){z.postMessage(null)}}else A=function(){x(P,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 H=e.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0<V?H+V:H):V=H,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>H?(q.sortIndex=V,t(u,q),n(c)===null&&q===n(u)&&(v?(b(T),T=-1):v=!0,Q(j,V-H))):(q.sortIndex=M,t(c,q),m||p||(m=!0,C||(C=!0,A()))),q},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(q){var B=h;return function(){var V=h;h=B;try{return q.apply(this,arguments)}finally{h=V}}}})(gte)),gte}var D$e;function UQt(){return D$e||(D$e=1,mte.exports=VQt()),mte.exports}var vte={exports:{}},zu={};var L$e;function qQt(){if(L$e)return zu;L$e=1;var e=gA();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 zu.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,zu.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)},zu.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()}},zu.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))},zu.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},zu.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})}},zu.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)},zu.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})}},zu.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)},zu.requestFormReset=function(c){r.d.r(c)},zu.unstable_batchedUpdates=function(c,u){return c(u)},zu.useFormState=function(c,u,d){return o.H.useFormState(c,u,d)},zu.useFormStatus=function(){return o.H.useHostTransitionStatus()},zu.version="19.2.7",zu}var z$e;function ftt(){if(z$e)return vte.exports;z$e=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(),vte.exports=qQt(),vte.exports}var F$e;function QQt(){if(F$e)return U$;F$e=1;var e={env:{}};var t=UQt(),n=gA(),r=ftt();function s(w){var O="https://react.dev/errors/"+w;if(1<arguments.length){O+="?args[]="+encodeURIComponent(arguments[1]);for(var E=2;E<arguments.length;E++)O+="&args[]="+encodeURIComponent(arguments[E])}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,E=w;if(w.alternate)for(;O.return;)O=O.return;else{w=O;do O=w,(O.flags&4098)!==0&&(E=O.return),w=O.return;while(w)}return O.tag===3?E: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 E=w,R=O;;){var W=E.return;if(W===null)break;var J=W.alternate;if(J===null){if(R=W.return,R!==null){E=R;continue}break}if(W.child===J.child){for(J=W.child;J;){if(J===E)return u(W),w;if(J===R)return u(W),O;J=J.sibling}throw Error(s(188))}if(E.return!==R.return)E=W,R=J;else{for(var ie=!1,be=W.child;be;){if(be===E){ie=!0,E=W,R=J;break}if(be===R){ie=!0,R=W,E=J;break}be=be.sibling}if(!ie){for(be=J.child;be;){if(be===E){ie=!0,E=J,R=W;break}if(be===R){ie=!0,R=J,E=W;break}be=be.sibling}if(!ie)throw Error(s(189))}}if(E.alternate!==R)throw Error(s(190))}if(E.tag!==3)throw Error(s(188));return E.stateNode.current===E?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"),I=Symbol.for("react.activity"),P=Symbol.for("react.memo_cache_sentinel"),A=Symbol.iterator;function D(w){return w===null||typeof w!="object"?null:(w=A&&w[A]||w["@@iterator"],typeof w=="function"?w:null)}var z=Symbol.for("react.client.reference");function Q(w){if(w==null)return null;if(typeof w=="function")return w.$$typeof===z?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 I:return"Activity"}if(typeof w=="object")switch(w.$$typeof){case v:return"Portal";case k:return w.displayName||"Context";case S:return(w._context.displayName||"Context")+".Consumer";case 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,H={pending:!1,data:null,method:null,action:null},M=[],G=-1;function L(w){return{current:w}}function $(w){0>G||(w.current=M[G],M[G]=null,G--)}function F(w,O){G++,M[G]=w.current,w.current=O}var U=L(null),K=L(null),ne=L(null),X=L(null);function te(w,O){switch(F(ne,O),F(K,w),F(U,null),O.nodeType){case 9:case 11:w=(w=O.documentElement)&&(w=w.namespaceURI)?t$e(w):0;break;default:if(w=O.tagName,O=O.namespaceURI)O=t$e(O),w=n$e(O,w);else switch(w){case"svg":w=1;break;case"math":w=2;break;default:w=0}}$(U),F(U,w)}function oe(){$(U),$(K),$(ne)}function ue(w){w.memoizedState!==null&&F(X,w);var O=U.current,E=n$e(O,w.type);O!==E&&(F(K,w),F(U,E))}function ee(w){K.current===w&&($(U),$(K)),X.current===w&&($(X),L$._currentValue=H)}var se,re;function ae(w){if(se===void 0)try{throw Error()}catch(E){var O=E.stack.trim().match(/\n( *(at )?)/);se=O&&O[1]||"",re=-1<E.stack.indexOf(`
|
|
3
3
|
at`)?" (<anonymous>)":-1<E.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
4
4
|
`+se+w+re}var pe=!1;function ve(w,O){if(!w||pe)return"";pe=!0;var E=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var R={DetermineComponentFrameRoot:function(){try{if(O){var Dt=function(){throw Error()};if(Object.defineProperty(Dt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Dt,[])}catch(xt){var ht=xt}Reflect.construct(w,[],Dt)}else{try{Dt.call()}catch(xt){ht=xt}w.call(Dt.prototype)}}else{try{throw Error()}catch(xt){ht=xt}(Dt=w())&&typeof Dt.catch=="function"&&Dt.catch(function(){})}}catch(xt){if(xt&&ht&&typeof xt.stack=="string")return[xt.stack,ht.stack]}return[null,null]}};R.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var W=Object.getOwnPropertyDescriptor(R.DetermineComponentFrameRoot,"name");W&&W.configurable&&Object.defineProperty(R.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var J=R.DetermineComponentFrameRoot(),ie=J[0],be=J[1];if(ie&&be){var Qe=ie.split(`
|
|
@@ -254,7 +254,7 @@ Error message: ${Qot(n)}`,cause:n}),this[eat]=!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)=>{Yp.isError(c)&&(c.value=u),l(c)},(c,u)=>{c.length?l(new Yp(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 Yp.isError(l)&&(l.value=c),l},(l,c)=>{if(l.length)throw new Yp(l,t,void 0,void 0,o);i=c}),i}isValid(t,n){return this.validate(t,n).then(()=>!0,r=>{if(Yp.isError(r))return!1;throw r})}isValidSync(t,n){try{return this.validateSync(t,n),!0}catch(r){if(Yp.isError(r))return!1;throw r}}_getDefault(t){let n=this.spec.default;return n==null?n:typeof n=="function"?n.call(this,t):NE(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=jT({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=jT({message:n,name:"optionality",test(s){return s===void 0?this.schema.spec.optional:!0}}),r}optional(){return this.optionality(!0)}defined(t=xb.defined){return this.optionality(!1,t)}nullable(){return this.nullability(!0)}nonNullable(t=xb.notNull){return this.nullability(!1,t)}required(t=xb.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=xb.default),typeof n.test!="function")throw new TypeError("`test` is a required parameters");let r=this.clone(),s=jT(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=P0t(t).map(i=>new lL(i));return s.forEach(i=>{i.isSibling&&r.deps.push(i.key)}),r.conditions.push(typeof n=="function"?new X9e(s,n):X9e.fromOptions(s,n)),r}typeError(t){let n=this.clone();return n.internalTests.typeError=jT({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=xb.oneOf){let r=this.clone();return t.forEach(s=>{r._whitelist.add(s),r._blacklist.delete(s)}),r.internalTests.whiteList=jT({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=xb.notOneOf){let r=this.clone();return t.forEach(s=>{r._blacklist.add(s),r._whitelist.delete(s)}),r.internalTests.blacklist=jT({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)}}};uC.prototype.__isYupSchema__=!0;for(const e of["validate","validateSync"])uC.prototype[`${e}At`]=function(t,n,r={}){const{parent:s,parentPath:i,schema:o}=aYn(this,t,n,r.context);return o[e](s&&s[i],Object.assign({},r,{parent:s,path:t}))};for(const e of["equals","is"])uC.prototype[e]=uC.prototype.oneOf;for(const e of["not","nope"])uC.prototype[e]=uC.prototype.notOneOf;var lYn=/^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/;function cYn(e){const t=uYn(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 uYn(e){var t,n;const r=lYn.exec(e);return r?{year:eb(r[1]),month:eb(r[2],1)-1,day:eb(r[3],1),hour:eb(r[4]),minute:eb(r[5]),second:eb(r[6]),millisecond:r[7]?eb(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:eb(r[10]),minuteOffset:eb(r[11])}:null}function eb(e,t=0){return Number(e)||t}var dYn=new Date(""),fYn=e=>Object.prototype.toString.call(e)==="[object Date]",hYn=class V0t extends uC{constructor(){super({type:"date",check(t){return fYn(t)&&!isNaN(t.getTime())}}),this.withMutation(()=>{this.transform((t,n,r)=>!r.spec.coerce||r.isType(t)||t===null?t:(t=cYn(t),isNaN(t)?V0t.INVALID_DATE:new Date(t)))})}prepareParam(t,n){let r;if(lL.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=jhe.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=jhe.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)}})}};hYn.INVALID_DATE=dYn;function e7e(e,t){let n=e;for(const r of t)if(n=n[r],n===void 0)return;return n}function D2(e){if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}const O1e=6048e5,pYn=864e5,mYn=6e4,gYn=36e5,vYn=1e3,t7e=Symbol.for("constructDateFrom");function Ro(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&t7e in e?e[t7e](t):e instanceof Date?new e.constructor(t):new Date(t)}function Xs(e,t){return Ro(t||e,e)}function nu(e,t,n){const r=Xs(e,n?.in);return isNaN(t)?Ro(n?.in||e,NaN):(t&&r.setDate(r.getDate()+t),r)}function cv(e,t,n){const r=Xs(e,n?.in);if(isNaN(t))return Ro(n?.in||e,NaN);if(!t)return r;const s=r.getDate(),i=Ro(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 yYn={};function a_(){return yYn}function lp(e,t){const n=a_(),r=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,s=Xs(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 f0(e,t){return lp(e,{...t,weekStartsOn:1})}function U0t(e,t){const n=Xs(e,t?.in),r=n.getFullYear(),s=Ro(n,0);s.setFullYear(r+1,0,4),s.setHours(0,0,0,0);const i=f0(s),o=Ro(n,0);o.setFullYear(r,0,4),o.setHours(0,0,0,0);const l=f0(o);return n.getTime()>=i.getTime()?r+1:n.getTime()>=l.getTime()?r:r-1}function jN(e){const t=Xs(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 JA(e,...t){const n=Ro.bind(null,e||t.find(r=>typeof r=="object"));return t.map(n)}function CN(e,t){const n=Xs(e,t?.in);return n.setHours(0,0,0,0),n}function Ny(e,t,n){const[r,s]=JA(n?.in,e,t),i=CN(r),o=CN(s),l=+i-jN(i),c=+o-jN(o);return Math.round((l-c)/pYn)}function xYn(e,t){const n=U0t(e,t),r=Ro(e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),f0(r)}function Che(e,t,n){return nu(e,t*7,n)}function bYn(e,t,n){return cv(e,t*12,n)}function wYn(e,t){let n,r=t?.in;return e.forEach(s=>{!r&&typeof s=="object"&&(r=Ro.bind(null,s));const i=Xs(s,r);(!n||n<i||isNaN(+i))&&(n=i)}),Ro(r,n||NaN)}function SYn(e,t){let n,r=t?.in;return e.forEach(s=>{!r&&typeof s=="object"&&(r=Ro.bind(null,s));const i=Xs(s,r);(!n||n>i||isNaN(+i))&&(n=i)}),Ro(r,n||NaN)}function qf(e,t,n){const[r,s]=JA(n?.in,e,t);return+CN(r)==+CN(s)}function j1e(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function C1e(e){return!(!j1e(e)&&typeof e!="number"||isNaN(+Xs(e)))}function Z4(e,t,n){const[r,s]=JA(n?.in,e,t),i=r.getFullYear()-s.getFullYear(),o=r.getMonth()-s.getMonth();return i*12+o}function kYn(e,t,n){const[r,s]=JA(n?.in,e,t),i=lp(r,n),o=lp(s,n),l=+i-jN(i),c=+o-jN(o);return Math.round((l-c)/O1e)}function _1e(e,t){const n=Xs(e,t?.in),r=n.getMonth();return n.setFullYear(n.getFullYear(),r+1,0),n.setHours(23,59,59,999),n}function Gf(e,t){const n=Xs(e,t?.in);return n.setDate(1),n.setHours(0,0,0,0),n}function q0t(e,t){const n=Xs(e,t?.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}function T1e(e,t){const n=a_(),r=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,s=Xs(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 Q0t(e,t){return T1e(e,{...t,weekStartsOn:1})}const OYn={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"}},jYn=(e,t,n)=>{let r;const s=OYn[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 bie(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}const CYn={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},_Yn={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},TYn={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},EYn={date:bie({formats:CYn,defaultWidth:"full"}),time:bie({formats:_Yn,defaultWidth:"full"}),dateTime:bie({formats:TYn,defaultWidth:"full"})},IYn={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},NYn=(e,t,n,r)=>IYn[e];function vR(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 AYn={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},PYn={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},$Yn={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"]},RYn={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"]},MYn={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"}},DYn={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"}},LYn=(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"},zYn={ordinalNumber:LYn,era:vR({values:AYn,defaultWidth:"wide"}),quarter:vR({values:PYn,defaultWidth:"wide",argumentCallback:e=>e-1}),month:vR({values:$Yn,defaultWidth:"wide"}),day:vR({values:RYn,defaultWidth:"wide"}),dayPeriod:vR({values:MYn,defaultWidth:"wide",formattingValues:DYn,defaultFormattingWidth:"wide"})};function yR(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)?BYn(l,f=>f.test(o)):FYn(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 FYn(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function BYn(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function VYn(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 UYn=/^(\d+)(th|st|nd|rd)?/i,qYn=/\d+/i,QYn={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},ZYn={any:[/^b/i,/^(a|c)/i]},WYn={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},HYn={any:[/1/i,/2/i,/3/i,/4/i]},GYn={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},KYn={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]},YYn={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},XYn={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]},JYn={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},eXn={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}},tXn={ordinalNumber:VYn({matchPattern:UYn,parsePattern:qYn,valueCallback:e=>parseInt(e,10)}),era:yR({matchPatterns:QYn,defaultMatchWidth:"wide",parsePatterns:ZYn,defaultParseWidth:"any"}),quarter:yR({matchPatterns:WYn,defaultMatchWidth:"wide",parsePatterns:HYn,defaultParseWidth:"any",valueCallback:e=>e+1}),month:yR({matchPatterns:GYn,defaultMatchWidth:"wide",parsePatterns:KYn,defaultParseWidth:"any"}),day:yR({matchPatterns:YYn,defaultMatchWidth:"wide",parsePatterns:XYn,defaultParseWidth:"any"}),dayPeriod:yR({matchPatterns:JYn,defaultMatchWidth:"any",parsePatterns:eXn,defaultParseWidth:"any"})},E1e={code:"en-US",formatDistance:jYn,formatLong:EYn,formatRelative:NYn,localize:zYn,match:tXn,options:{weekStartsOn:0,firstWeekContainsDate:1}};function nXn(e,t){const n=Xs(e,t?.in);return Ny(n,q0t(n))+1}function I1e(e,t){const n=Xs(e,t?.in),r=+f0(n)-+xYn(n);return Math.round(r/O1e)+1}function N1e(e,t){const n=Xs(e,t?.in),r=n.getFullYear(),s=a_(),i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,o=Ro(t?.in||e,0);o.setFullYear(r+1,0,i),o.setHours(0,0,0,0);const l=lp(o,t),c=Ro(t?.in||e,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const u=lp(c,t);return+n>=+l?r+1:+n>=+u?r:r-1}function rXn(e,t){const n=a_(),r=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,s=N1e(e,t),i=Ro(t?.in||e,0);return i.setFullYear(s,0,r),i.setHours(0,0,0,0),lp(i,t)}function A1e(e,t){const n=Xs(e,t?.in),r=+lp(n,t)-+rXn(n,t);return Math.round(r/O1e)+1}function Ki(e,t){const n=e<0?"-":"",r=Math.abs(e).toString().padStart(t,"0");return n+r}const Tw={y(e,t){const n=e.getFullYear(),r=n>0?n:1-n;return Ki(t==="yy"?r%100:r,t.length)},M(e,t){const n=e.getMonth();return t==="M"?String(n+1):Ki(n+1,2)},d(e,t){return Ki(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 Ki(e.getHours()%12||12,t.length)},H(e,t){return Ki(e.getHours(),t.length)},m(e,t){return Ki(e.getMinutes(),t.length)},s(e,t){return Ki(e.getSeconds(),t.length)},S(e,t){const n=t.length,r=e.getMilliseconds(),s=Math.trunc(r*Math.pow(10,n-3));return Ki(s,t.length)}},CT={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},n7e={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 Tw.y(e,t)},Y:function(e,t,n,r){const s=N1e(e,r),i=s>0?s:1-s;if(t==="YY"){const o=i%100;return Ki(o,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):Ki(i,t.length)},R:function(e,t){const n=U0t(e);return Ki(n,t.length)},u:function(e,t){const n=e.getFullYear();return Ki(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 Ki(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 Ki(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 Tw.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 Ki(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=A1e(e,r);return t==="wo"?n.ordinalNumber(s,{unit:"week"}):Ki(s,t.length)},I:function(e,t,n){const r=I1e(e);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):Ki(r,t.length)},d:function(e,t,n){return t==="do"?n.ordinalNumber(e.getDate(),{unit:"date"}):Tw.d(e,t)},D:function(e,t,n){const r=nXn(e);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Ki(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 Ki(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 Ki(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 Ki(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=CT.noon:r===0?s=CT.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=CT.evening:r>=12?s=CT.afternoon:r>=4?s=CT.morning:s=CT.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 Tw.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getHours(),{unit:"hour"}):Tw.H(e,t)},K:function(e,t,n){const r=e.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Ki(r,t.length)},k:function(e,t,n){let r=e.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):Ki(r,t.length)},m:function(e,t,n){return t==="mo"?n.ordinalNumber(e.getMinutes(),{unit:"minute"}):Tw.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getSeconds(),{unit:"second"}):Tw.s(e,t)},S:function(e,t){return Tw.S(e,t)},X:function(e,t,n){const r=e.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return s7e(r);case"XXXX":case"XX":return gO(r);default:return gO(r,":")}},x:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"x":return s7e(r);case"xxxx":case"xx":return gO(r);default:return gO(r,":")}},O:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+r7e(r,":");default:return"GMT"+gO(r,":")}},z:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+r7e(r,":");default:return"GMT"+gO(r,":")}},t:function(e,t,n){const r=Math.trunc(+e/1e3);return Ki(r,t.length)},T:function(e,t,n){return Ki(+e,t.length)}};function r7e(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+Ki(i,2)}function s7e(e,t){return e%60===0?(e>0?"-":"+")+Ki(Math.abs(e)/60,2):gO(e,t)}function gO(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),s=Ki(Math.trunc(r/60),2),i=Ki(r%60,2);return n+s+t+i}const i7e=(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"})}},Z0t=(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"})}},sXn=(e,t)=>{const n=e.match(/(P+)(p+)?/)||[],r=n[1],s=n[2];if(!s)return i7e(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}}",i7e(r,t)).replace("{{time}}",Z0t(s,t))},_he={p:Z0t,P:sXn},iXn=/^D+$/,oXn=/^Y+$/,aXn=["D","DD","YY","YYYY"];function W0t(e){return iXn.test(e)}function H0t(e){return oXn.test(e)}function The(e,t,n){const r=lXn(e,t,n);if(console.warn(r),aXn.includes(e))throw new RangeError(r)}function lXn(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 cXn=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,uXn=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,dXn=/^'([^]*?)'?$/,fXn=/''/g,hXn=/[a-zA-Z]/;function nk(e,t,n){const r=a_(),s=n?.locale??r.locale??E1e,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=Xs(e,n?.in);if(!C1e(l))throw new RangeError("Invalid time value");let c=t.match(uXn).map(d=>{const f=d[0];if(f==="p"||f==="P"){const h=_he[f];return h(d,s.formatLong)}return d}).join("").match(cXn).map(d=>{if(d==="''")return{isToken:!1,value:"'"};const f=d[0];if(f==="'")return{isToken:!1,value:pXn(d)};if(n7e[f])return{isToken:!0,value:d};if(f.match(hXn))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&&H0t(f)||!n?.useAdditionalDayOfYearTokens&&W0t(f))&&The(f,t,String(e));const h=n7e[f[0]];return h(l,f,s.localize,u)}).join("")}function pXn(e){const t=e.match(dXn);return t?t[1].replace(fXn,"'"):e}function mXn(e,t){const n=Xs(e,t?.in),r=n.getFullYear(),s=n.getMonth(),i=Ro(n,0);return i.setFullYear(r,s+1,0),i.setHours(0,0,0,0),i.getDate()}function gXn(){return Object.assign({},a_())}function vXn(e,t){const n=Xs(e,t?.in).getDay();return n===0?7:n}function yXn(e){return Math.trunc(+Xs(e)/1e3)}function xXn(e,t){const n=Xs(e,t?.in),r=n.getMonth();return n.setFullYear(n.getFullYear(),r+1,0),n.setHours(0,0,0,0),Xs(n,t?.in)}function bXn(e,t){const n=Xs(e,t?.in);return kYn(xXn(n,t),Gf(n,t),t)+1}function Ehe(e,t){return+Xs(e)>+Xs(t)}function G0t(e,t){return+Xs(e)<+Xs(t)}function wXn(e,t){const n=SXn(t)?new t(0):Ro(t,0);return n.setFullYear(e.getFullYear(),e.getMonth(),e.getDate()),n.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()),n}function SXn(e){return typeof e=="function"&&e.prototype?.constructor===e}const kXn=10;class K0t{subPriority=0;validate(t,n){return!0}}class OXn extends K0t{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 jXn extends K0t{priority=kXn;subPriority=-1;constructor(t,n){super(),this.context=t||(r=>Ro(n,r))}set(t,n){return n.timestampIsSet?t:Ro(t,wXn(t,this.context))}}class Ri{run(t,n,r,s){const i=this.parse(t,n,r,s);return i?{setter:new OXn(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class CXn extends Ri{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 vl={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}/},by={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 yl(e,t){return e&&{value:t(e.value),rest:e.rest}}function La(e,t){const n=t.match(e);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function wy(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*gYn+i*mYn+o*vYn),rest:t.slice(n[0].length)}}function Y0t(e){return La(vl.anyDigitsSigned,e)}function ll(e,t){switch(e){case 1:return La(vl.singleDigit,t);case 2:return La(vl.twoDigits,t);case 3:return La(vl.threeDigits,t);case 4:return La(vl.fourDigits,t);default:return La(new RegExp("^\\d{1,"+e+"}"),t)}}function kq(e,t){switch(e){case 1:return La(vl.singleDigitSigned,t);case 2:return La(vl.twoDigitsSigned,t);case 3:return La(vl.threeDigitsSigned,t);case 4:return La(vl.fourDigitsSigned,t);default:return La(new RegExp("^-?\\d{1,"+e+"}"),t)}}function P1e(e){switch(e){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;default:return 0}}function X0t(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 J0t(e){return e%400===0||e%4===0&&e%100!==0}class _Xn extends Ri{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 yl(ll(4,t),s);case"yo":return yl(r.ordinalNumber(t,{unit:"year"}),s);default:return yl(ll(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=X0t(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 TXn extends Ri{priority=130;parse(t,n,r){const s=i=>({year:i,isTwoDigitYear:n==="YY"});switch(n){case"Y":return yl(ll(4,t),s);case"Yo":return yl(r.ordinalNumber(t,{unit:"year"}),s);default:return yl(ll(n.length,t),s)}}validate(t,n){return n.isTwoDigitYear||n.year>0}set(t,n,r,s){const i=N1e(t,s);if(r.isTwoDigitYear){const l=X0t(r.year,i);return t.setFullYear(l,0,s.firstWeekContainsDate),t.setHours(0,0,0,0),lp(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),lp(t,s)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]}class EXn extends Ri{priority=130;parse(t,n){return kq(n==="R"?4:n.length,t)}set(t,n,r){const s=Ro(t,0);return s.setFullYear(r,0,4),s.setHours(0,0,0,0),f0(s)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]}class IXn extends Ri{priority=130;parse(t,n){return kq(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 NXn extends Ri{priority=120;parse(t,n,r){switch(n){case"Q":case"QQ":return ll(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 AXn extends Ri{priority=120;parse(t,n,r){switch(n){case"q":case"qq":return ll(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 PXn extends Ri{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 yl(La(vl.month,t),s);case"MM":return yl(ll(2,t),s);case"Mo":return yl(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 $Xn extends Ri{priority=110;parse(t,n,r){const s=i=>i-1;switch(n){case"L":return yl(La(vl.month,t),s);case"LL":return yl(ll(2,t),s);case"Lo":return yl(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 RXn(e,t,n){const r=Xs(e,n?.in),s=A1e(r,n)-t;return r.setDate(r.getDate()-s*7),Xs(r,n?.in)}class MXn extends Ri{priority=100;parse(t,n,r){switch(n){case"w":return La(vl.week,t);case"wo":return r.ordinalNumber(t,{unit:"week"});default:return ll(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,r,s){return lp(RXn(t,r,s),s)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]}function DXn(e,t,n){const r=Xs(e,n?.in),s=I1e(r,n)-t;return r.setDate(r.getDate()-s*7),r}class LXn extends Ri{priority=100;parse(t,n,r){switch(n){case"I":return La(vl.week,t);case"Io":return r.ordinalNumber(t,{unit:"week"});default:return ll(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,r){return f0(DXn(t,r))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]}const zXn=[31,28,31,30,31,30,31,31,30,31,30,31],FXn=[31,29,31,30,31,30,31,31,30,31,30,31];class BXn extends Ri{priority=90;subPriority=1;parse(t,n,r){switch(n){case"d":return La(vl.date,t);case"do":return r.ordinalNumber(t,{unit:"date"});default:return ll(n.length,t)}}validate(t,n){const r=t.getFullYear(),s=J0t(r),i=t.getMonth();return s?n>=1&&n<=FXn[i]:n>=1&&n<=zXn[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 VXn extends Ri{priority=90;subpriority=1;parse(t,n,r){switch(n){case"D":case"DD":return La(vl.dayOfYear,t);case"Do":return r.ordinalNumber(t,{unit:"date"});default:return ll(n.length,t)}}validate(t,n){const r=t.getFullYear();return J0t(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 $1e(e,t,n){const r=a_(),s=n?.weekStartsOn??n?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,i=Xs(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 nu(i,d,n)}class UXn extends Ri{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=$1e(t,r,s),t.setHours(0,0,0,0),t}incompatibleTokens=["D","i","e","c","t","T"]}class qXn extends Ri{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 yl(ll(n.length,t),i);case"eo":return yl(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=$1e(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 QXn extends Ri{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 yl(ll(n.length,t),i);case"co":return yl(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=$1e(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 ZXn(e,t,n){const r=Xs(e,n?.in),s=vXn(r,n),i=t-s;return nu(r,i,n)}class WXn extends Ri{priority=90;parse(t,n,r){const s=i=>i===0?7:i;switch(n){case"i":case"ii":return ll(n.length,t);case"io":return r.ordinalNumber(t,{unit:"day"});case"iii":return yl(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 yl(r.day(t,{width:"narrow",context:"formatting"}),s);case"iiiiii":return yl(r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"}),s);default:return yl(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=ZXn(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 HXn extends Ri{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(P1e(r),0,0,0),t}incompatibleTokens=["b","B","H","k","t","T"]}class GXn extends Ri{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(P1e(r),0,0,0),t}incompatibleTokens=["a","B","H","k","t","T"]}class KXn extends Ri{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(P1e(r),0,0,0),t}incompatibleTokens=["a","b","t","T"]}class YXn extends Ri{priority=70;parse(t,n,r){switch(n){case"h":return La(vl.hour12h,t);case"ho":return r.ordinalNumber(t,{unit:"hour"});default:return ll(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 XXn extends Ri{priority=70;parse(t,n,r){switch(n){case"H":return La(vl.hour23h,t);case"Ho":return r.ordinalNumber(t,{unit:"hour"});default:return ll(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 JXn extends Ri{priority=70;parse(t,n,r){switch(n){case"K":return La(vl.hour11h,t);case"Ko":return r.ordinalNumber(t,{unit:"hour"});default:return ll(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 eJn extends Ri{priority=70;parse(t,n,r){switch(n){case"k":return La(vl.hour24h,t);case"ko":return r.ordinalNumber(t,{unit:"hour"});default:return ll(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 tJn extends Ri{priority=60;parse(t,n,r){switch(n){case"m":return La(vl.minute,t);case"mo":return r.ordinalNumber(t,{unit:"minute"});default:return ll(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 nJn extends Ri{priority=50;parse(t,n,r){switch(n){case"s":return La(vl.second,t);case"so":return r.ordinalNumber(t,{unit:"second"});default:return ll(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 rJn extends Ri{priority=30;parse(t,n){const r=s=>Math.trunc(s*Math.pow(10,-n.length+3));return yl(ll(n.length,t),r)}set(t,n,r){return t.setMilliseconds(r),t}incompatibleTokens=["t","T"]}class sJn extends Ri{priority=10;parse(t,n){switch(n){case"X":return wy(by.basicOptionalMinutes,t);case"XX":return wy(by.basic,t);case"XXXX":return wy(by.basicOptionalSeconds,t);case"XXXXX":return wy(by.extendedOptionalSeconds,t);default:return wy(by.extended,t)}}set(t,n,r){return n.timestampIsSet?t:Ro(t,t.getTime()-jN(t)-r)}incompatibleTokens=["t","T","x"]}class iJn extends Ri{priority=10;parse(t,n){switch(n){case"x":return wy(by.basicOptionalMinutes,t);case"xx":return wy(by.basic,t);case"xxxx":return wy(by.basicOptionalSeconds,t);case"xxxxx":return wy(by.extendedOptionalSeconds,t);default:return wy(by.extended,t)}}set(t,n,r){return n.timestampIsSet?t:Ro(t,t.getTime()-jN(t)-r)}incompatibleTokens=["t","T","X"]}class oJn extends Ri{priority=40;parse(t){return Y0t(t)}set(t,n,r){return[Ro(t,r*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"}class aJn extends Ri{priority=20;parse(t){return Y0t(t)}set(t,n,r){return[Ro(t,r),{timestampIsSet:!0}]}incompatibleTokens="*"}const lJn={G:new CXn,y:new _Xn,Y:new TXn,R:new EXn,u:new IXn,Q:new NXn,q:new AXn,M:new PXn,L:new $Xn,w:new MXn,I:new LXn,d:new BXn,D:new VXn,E:new UXn,e:new qXn,c:new QXn,i:new WXn,a:new HXn,b:new GXn,B:new KXn,h:new YXn,H:new XXn,K:new JXn,k:new eJn,m:new tJn,s:new nJn,S:new rJn,X:new sJn,x:new iJn,t:new oJn,T:new aJn},cJn=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,uJn=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,dJn=/^'([^]*?)'?$/,fJn=/''/g,hJn=/\S/,pJn=/[a-zA-Z]/;function mJn(e,t,n,r){const s=()=>Ro(n,NaN),i=gXn(),o=i.locale??E1e,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 jXn(r?.in,n)],f=t.match(uJn).map(y=>{const x=y[0];if(x in _he){const b=_he[x];return b(y,o.formatLong)}return y}).join("").match(cJn),h=[];for(let y of f){H0t(y)&&The(y,t,e),W0t(y)&&The(y,t,e);const x=y[0],b=lJn[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(pJn))throw new RangeError("Format string contains an unescaped latin alphabet character `"+x+"`");if(y==="''"?y="'":x==="'"&&(y=gJn(y)),e.indexOf(y)===0)e=e.slice(y.length);else return s()}}if(e.length>0&&hJn.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=Xs(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 gJn(e){return e.match(dJn)[1].replace(fJn,"'")}function R1e(e,t,n){const[r,s]=JA(n?.in,e,t);return r.getFullYear()===s.getFullYear()&&r.getMonth()===s.getMonth()}function vJn(e,t,n){const[r,s]=JA(n?.in,e,t);return r.getFullYear()===s.getFullYear()}function wie(e,t,n){return nu(e,-t,n)}function Sie(e,t,n){const r=Xs(e,n?.in),s=r.getFullYear(),i=r.getDate(),o=Ro(e,0);o.setFullYear(s,t,15),o.setHours(0,0,0,0);const l=mXn(o);return r.setMonth(t,Math.min(i,l)),r}function o7e(e,t,n){const r=Xs(e,n?.in);return isNaN(+r)?Ro(e,NaN):(r.setFullYear(t),r)}function ewt(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 yJn=["title","name","label"];function a7e(e){return e.find(t=>typeof t=="string"&&t.trim().length>0)}function xJn(e){if(typeof e=="string")return e.trim();if(typeof e=="number"||typeof e=="boolean")return String(e);if(D2(e))return a7e(yJn.map(t=>e[t]))??a7e(Object.values(e))}function bJn({children:e,onRemove:t,index:n}){const r=g.useContext(pG),s=g.useContext(b1e),i=g.useContext(C0t),{control:o}=zr(),l=Qn({control:o,name:r}),c=xJn(l),u=g.useRef(null),{expanded:d,invalid:f,setExpanded:h}=ewt(r,!c),p=`Item ${n+1}${c?`: ${c}`:""}`;return a.jsxs(Wl,{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(wl,{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(Gs,{"aria-hidden":!0,className:"size-3.5 shrink-0 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(de,{type:"button",variant:"ghost",size:"icon-md",className:"size-11","aria-label":`Remove item ${n+1}`,onClick:()=>{t(),i?.current?.focus()},children:a.jsx(Go,{})})]}),a.jsxs(Sl,{keepMounted:!0,className:"border-t border-border p-3",children:[e,!s&&a.jsx("div",{className:"flex justify-end pt-2",children:a.jsx(de,{type:"button",className:"min-h-11","aria-label":`Done editing item ${n+1}`,onClick:()=>{h(!1),u.current?.focus()},icon:a.jsx(pr,{}),children:"Done"})})]})]})}function wJn({label:e,children:t,onAddItem:n}){const r=g.useContext(b1e),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(zkn,{"aria-hidden":!0,className:"size-3.5"}),e," ",a.jsx("span",{className:"tabular-nums",children:s})]}),!r&&a.jsxs(de,{ref:i,type:"button",variant:"ghost",size:"sm","aria-label":`Add ${e} item`,onClick:n,children:[a.jsx(bs,{}),"Add item"]})]}),s===0?a.jsx(Y,{as:"p",variant:"caption",tone:"muted",className:"py-2",children:"No items added"}):a.jsx(C0t,{value:i,children:a.jsx("div",{className:"flex flex-col gap-2",children:t})})]})}function SJn(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 twt(e){return{checked(t){return e.indeterminate?{}:t?{"data-checked":""}:{"data-unchecked":""}},...yp}}const kJn=g.createContext(void 0);function OJn(){return g.useContext(kJn)}const nwt=g.createContext(void 0);function jJn(){const e=g.useContext(nwt);if(e===void 0)throw new Error(Pr(14));return e}const CJn="data-parent",_Jn=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}=wv(),{disabled:_,name:N,setDirty:I,setFilled:P,setFocused:A,setTouched:D,state:z,validationMode:Q,validityData:q,validation:B}=_u(),V=MH(),{labelId:H,controlId:M,registerControlId:G,getDescriptionProps:L}=hd(),$=OJn(),F=$?.allValues===void 0?void 0:$.parent,U=F!==void 0,K=_||V.disabled||$?.disabled||l,ne=N??h,X=S??ne,te=Qi(),oe=Qi();let ue=u||M;U&&(m?ue=oe:X!==void 0?ue=`${F.id}-${X}`:ue||=oe);let ee={};U&&(m?ee=F.getParentProps():X!==void 0&&(ee=F.getChildProps(X)));const{checked:se=r,indeterminate:re=d,onCheckedChange:ae,...pe}=ee,ve=$?.value,he=g.useRef(null),Oe=ol(()=>Symbol()),Ee=g.useRef(!1),{getButtonProps:Fe,buttonRef:qe}=ud({disabled:K,native:k}),Be=$?.validation??B,[Pe,Ve]=Kd({controlled:X!==void 0&&ve!==void 0&&!m?ve.includes(X):se,default:i,name:"Checkbox",state:"checked"}),Ce=U?!!se:Pe,Te=U&&re||d;Tt(()=>{G!==di&&(Ee.current=!0,G(Oe.current,ue))},[ue,G,Oe]),g.useEffect(()=>{const He=Oe.current;return()=>{!Ee.current||G===di||(Ee.current=!1,G(He,void 0))}},[G,Oe]),t_(he,te,Pe,void 0,!$&&!K,h);const _e=g.useRef(null),ce=Be.registerInput,ye=$?X:void 0,Me=g.useCallback(He=>ce(He,{controlRef:he,value:ye}),[ce,ye]),Ie=Jd(f,_e,m?void 0:Me),le=A0e(o,H,_e,!k,ue??void 0);Tt(()=>{_e.current&&(_e.current.indeterminate=Te,Pe&&P(!0))},[Pe,Te,P]),Zg(Pe,()=>{$||(T(ne),P(Pe),I(Pe!==q.initialValue),Be.change(Pe))});const xe=Dl({checked:Pe,disabled:K,form:c,name:m?void 0:ne,id:k?void 0:ue??void 0,required:x,ref:Ie,style:ne?CA:G1,tabIndex:-1,type:"checkbox","aria-hidden":!0,onChange(He){if(He.nativeEvent.defaultPrevented)return;if(v){He.preventDefault();return}const De=He.currentTarget.checked,tt=Yt(To,He.nativeEvent);if(p?.(De,tt),!tt.isCanceled&&(ae?.(De,tt),!tt.isCanceled&&(Ve(De),X!==void 0&&$!==void 0&&!m&&!U))){const Ze=De?[...$.value,X]:$.value.filter(rt=>rt!==X);$.setValue(Ze,tt)}},onClick(He){He.stopPropagation()},onFocus(){he.current?.focus()}},S!==void 0?{value:($?Pe&&S:S)||""}:ai,L,He=>Be.getValidationProps(K,He));g.useEffect(()=>{if(!F||X===void 0)return;const He=F.disabledStatesRef.current;return He.set(X,K),()=>{He.delete(X)}},[F,K,X]);const Se=g.useMemo(()=>({...z,checked:Ce,disabled:K,readOnly:v,required:x,indeterminate:Te}),[z,Ce,K,v,x,Te]),$e=twt(Se),ze=pn("span",t,{state:Se,ref:[qe,he,n],props:[{id:k?ue??void 0:te,role:"checkbox","aria-checked":Te?"mixed":Ce,"aria-readonly":v||void 0,"aria-required":x||void 0,"aria-labelledby":le,[CJn]:m?"":void 0,onFocus(){K||A(!0)},onBlur(){const He=_e.current;He&&(D(!0),A(!1),Q==="onBlur"&&Be.commit($?ve:He.checked))},onKeyDown(He){if(He.key!=="Enter"||(He.preventBaseUIHandler(),He.defaultPrevented))return;const De=_e.current?.form??null,tt=He.currentTarget,Ze=He.nativeEvent,rt=He.preventDefault,At=Ze.preventDefault;let me=!1;He.preventDefault=()=>{me=!0,rt.call(He)},Ze.preventDefault=()=>{me=!0,At.call(Ze)},At.call(Ze),xi(tt).queueMicrotask(()=>{He.preventDefault=rt,Ze.preventDefault=At,me||SJn(De)?.click()})},onClick(He){if(v||K)return;He.preventDefault();const De=_e.current;De&&aj(De,He)}},C,pe,Fe,L,He=>Be.getValidationProps(K,He)],stateAttributesMapping:$e});return a.jsxs(nwt.Provider,{value:Se,children:[ze,!Pe&&!$&&ne&&!m&&b!==void 0&&a.jsx("input",{type:"hidden",form:c,name:ne,value:b,disabled:K}),a.jsx("input",{...xe,suppressHydrationWarning:!0})]})}),TJn=g.forwardRef(function(t,n){const{render:r,className:s,style:i,keepMounted:o=!1,...l}=t,c=jJn(),u=c.checked||c.indeterminate,{mounted:d,transitionStatus:f,setMounted:h}=Wm(u),p=g.useRef(null),m={...c,transitionStatus:f};ql({open:u,ref:p,onComplete(){u||h(!1)}});const y={...twt(c),...gp},x=o||d,b=pn("span",t,{ref:[n,p],state:m,stateAttributesMapping:y,props:l});return x?b:null}),rwt=["flex size-4 shrink-0 cursor-pointer items-center justify-center","border border-border bg-fill-hover text-background",ro.all,"hover:border-border-strong hover:bg-fill-active","active:scale-95 active:border-border-hover active:bg-fill-strong",nU,"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(" "),Iu=g.forwardRef(({className:e,checked:t,indeterminate:n,...r},s)=>{const i=t==="indeterminate";return a.jsx(_Jn,{ref:s,checked:i?!1:t,indeterminate:n??i,"data-slot":"checkbox",render:a.jsx("span",{...wx(r)}),className:Z("peer rounded-[0.3125rem]",rwt,"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(TJn,{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(EJn,{})})})});Iu.displayName="Checkbox";function EJn(){return a.jsxs(a.Fragment,{children:[a.jsx(pr,{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(_dt,{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 IJn=({field:e,label:t,inputProps:n})=>a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx(Iu,{onCheckedChange:r=>{const s={target:{name:n.name,value:r}};n.onChange(s)},defaultChecked:e.default,disabled:n.disabled||n.readOnly}),a.jsx(lt,{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 NJn(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 swt(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 cL(e){return e.mode==="multiple"}function uL(e){return e.mode==="range"}function gG(e){return e.mode==="single"}var AJn={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 PJn(e,t){return nk(e,"LLLL y",t)}function $Jn(e,t){return nk(e,"d",t)}function RJn(e,t){return nk(e,"LLLL",t)}function MJn(e){return"".concat(e)}function DJn(e,t){return nk(e,"cccccc",t)}function LJn(e,t){return nk(e,"yyyy",t)}var zJn=Object.freeze({__proto__:null,formatCaption:PJn,formatDay:$Jn,formatMonthCaption:RJn,formatWeekNumber:MJn,formatWeekdayName:DJn,formatYearCaption:LJn}),FJn=function(e,t,n){return nk(e,"do MMMM (EEEE)",n)},BJn=function(){return"Month: "},VJn=function(){return"Go to next month"},UJn=function(){return"Go to previous month"},qJn=function(e,t){return nk(e,"cccc",t)},QJn=function(e){return"Week n. ".concat(e)},ZJn=function(){return"Year: "},WJn=Object.freeze({__proto__:null,labelDay:FJn,labelMonthDropdown:BJn,labelNext:VJn,labelPrevious:UJn,labelWeekNumber:QJn,labelWeekday:qJn,labelYearDropdown:ZJn});function HJn(){var e="buttons",t=AJn,n=E1e,r={},s={},i=1,o={},l=new Date;return{captionLayout:e,classNames:t,formatters:zJn,labels:WJn,locale:n,modifiersClassNames:r,modifiers:s,numberOfMonths:i,styles:o,today:l,mode:"default"}}function GJn(e){var t=e.fromYear,n=e.toYear,r=e.fromMonth,s=e.toMonth,i=e.fromDate,o=e.toDate;return r?i=Gf(r):t&&(i=new Date(t,0,1)),s?o=_1e(s):n&&(o=new Date(n,11,31)),{fromDate:i?CN(i):void 0,toDate:o?CN(o):void 0}}var iwt=g.createContext(void 0);function KJn(e){var t,n=e.initialProps,r=HJn(),s=GJn(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;(gG(n)||cL(n)||uL(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(iwt.Provider,{value:u,children:e.children})}function Yo(){var e=g.useContext(iwt);if(!e)throw new Error("useDayPicker must be used within a DayPickerProvider.");return e}function owt(e){var t=Yo(),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 YJn(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 awt(e){var t,n,r=e.onChange,s=e.value,i=e.children,o=e.caption,l=e.className,c=e.style,u=Yo(),d=(n=(t=u.components)===null||t===void 0?void 0:t.IconDropdown)!==null&&n!==void 0?n:YJn;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 XJn(e){var t,n=Yo(),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(vJn(r,s))for(var h=Gf(r),p=r.getMonth();p<=s.getMonth();p++)f.push(Sie(h,p));else for(var h=Gf(new Date),p=0;p<=11;p++)f.push(Sie(h,p));var m=function(y){var x=Number(y.target.value),b=Sie(Gf(e.displayMonth),x);e.onChange(b)},v=(t=u?.Dropdown)!==null&&t!==void 0?t:awt;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 JJn(e){var t,n=e.displayMonth,r=Yo(),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(o7e(q0t(new Date),v));var y=function(b){var S=o7e(Gf(n),Number(b.target.value));e.onChange(S)},x=(t=u?.Dropdown)!==null&&t!==void 0?t:awt;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 eer(e,t){var n=g.useState(e),r=n[0],s=n[1],i=t===void 0?r:t;return[i,s]}function ter(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&&Z4(i,s)<0){var u=-1*(c-1);s=cv(i,u)}return o&&Z4(s,o)<0&&(s=o),Gf(s)}function ner(){var e=Yo(),t=ter(e),n=eer(t,e.month),r=n[0],s=n[1],i=function(o){var l;if(!e.disableNavigation){var c=Gf(o);s(c),(l=e.onMonthChange)===null||l===void 0||l.call(e,c)}};return[r,i]}function rer(e,t){for(var n=t.reverseMonths,r=t.numberOfMonths,s=Gf(e),i=Gf(cv(s,r)),o=Z4(i,s),l=[],c=0;c<o;c++){var u=cv(s,c);l.push(u)}return n&&(l=l.reverse()),l}function ser(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=Gf(e);if(!n)return cv(l,o);var c=Z4(n,e);if(!(c<i))return cv(l,o)}}function ier(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=Gf(e);if(!n)return cv(l,-o);var c=Z4(l,n);if(!(c<=0))return cv(l,-o)}}var lwt=g.createContext(void 0);function oer(e){var t=Yo(),n=ner(),r=n[0],s=n[1],i=rer(r,t),o=ser(r,t),l=ier(r,t),c=function(f){return i.some(function(h){return R1e(f,h)})},u=function(f,h){c(f)||(h&&G0t(f,h)?s(cv(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(lwt.Provider,{value:d,children:e.children})}function dL(){var e=g.useContext(lwt);if(!e)throw new Error("useNavigation must be used within a NavigationProvider");return e}function l7e(e){var t,n=Yo(),r=n.classNames,s=n.styles,i=n.components,o=dL().goToMonth,l=function(d){o(cv(d,e.displayIndex?-e.displayIndex:0))},c=(t=i?.CaptionLabel)!==null&&t!==void 0?t:owt,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(XJn,{onChange:l,displayMonth:e.displayMonth}),a.jsx(JJn,{onChange:l,displayMonth:e.displayMonth})]})}function aer(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 ler(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 Oq=g.forwardRef(function(e,t){var n=Yo(),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 cer(e){var t,n,r=Yo(),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:ler,x=(n=f?.IconLeft)!==null&&n!==void 0?n:aer;return a.jsxs("div",{className:o.nav,style:l.nav,children:[!e.hidePrevious&&a.jsx(Oq,{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(Oq,{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 c7e(e){var t=Yo().numberOfMonths,n=dL(),r=n.previousMonth,s=n.nextMonth,i=n.goToMonth,o=n.displayMonths,l=o.findIndex(function(m){return R1e(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(cer,{displayMonth:e.displayMonth,hideNext:d,hidePrevious:f,nextMonth:s,previousMonth:r,onPreviousClick:h,onNextClick:p})}function uer(e){var t,n=Yo(),r=n.classNames,s=n.disableNavigation,i=n.styles,o=n.captionLayout,l=n.components,c=(t=l?.CaptionLabel)!==null&&t!==void 0?t:owt,u;return s?u=a.jsx(c,{id:e.id,displayMonth:e.displayMonth}):o==="dropdown"?u=a.jsx(l7e,{displayMonth:e.displayMonth,id:e.id}):o==="dropdown-buttons"?u=a.jsxs(a.Fragment,{children:[a.jsx(l7e,{displayMonth:e.displayMonth,displayIndex:e.displayIndex,id:e.id}),a.jsx(c7e,{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(c7e,{displayMonth:e.displayMonth,id:e.id})]}),a.jsx("div",{className:r.caption,style:i.caption,children:u})}function der(e){var t=Yo(),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 fer(e,t,n){for(var r=n?f0(new Date):lp(new Date,{locale:e,weekStartsOn:t}),s=[],i=0;i<7;i++){var o=nu(r,i);s.push(o)}return s}function her(){var e=Yo(),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=fer(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 per(){var e,t=Yo(),n=t.classNames,r=t.styles,s=t.components,i=(e=s?.HeadRow)!==null&&e!==void 0?e:her;return a.jsx("thead",{style:r.head,className:n.head,children:a.jsx(i,{})})}function mer(e){var t=Yo(),n=t.locale,r=t.formatters.formatDay;return a.jsx(a.Fragment,{children:r(e.date,{locale:n})})}var M1e=g.createContext(void 0);function ger(e){if(!cL(e.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return a.jsx(M1e.Provider,{value:t,children:e.children})}return a.jsx(ver,{initialProps:e.initialProps,children:e.children})}function ver(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?swt([],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(M1e.Provider,{value:c,children:n})}function D1e(){var e=g.useContext(M1e);if(!e)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return e}function yer(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:Ehe(r,e)?{from:e,to:s}:{from:r,to:e}:s?Ehe(e,s)?{from:s,to:e}:{from:e,to:s}:r?G0t(e,r)?{from:e,to:r}:{from:r,to:e}:{from:e,to:void 0}}var L1e=g.createContext(void 0);function xer(e){if(!uL(e.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return a.jsx(L1e.Provider,{value:t,children:e.children})}return a.jsx(ber,{initialProps:e.initialProps,children:e.children})}function ber(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=yer(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:wie(i,l-1),before:nu(i,l-1)}),i&&o&&d.disabled.push({after:i,before:nu(i,l-1)}),!i&&o&&d.disabled.push({after:wie(o,l-1),before:nu(o,l-1)})),c){if(i&&!o&&(d.disabled.push({before:nu(i,-c+1)}),d.disabled.push({after:nu(i,c-1)})),i&&o){var f=Ny(o,i)+1,h=c-f;d.disabled.push({before:wie(i,h)}),d.disabled.push({after:nu(o,h)})}!i&&o&&(d.disabled.push({before:nu(o,-c+1)}),d.disabled.push({after:nu(o,c-1)}))}return a.jsx(L1e.Provider,{value:{selected:r,onDayClick:u,modifiers:d},children:n})}function z1e(){var e=g.useContext(L1e);if(!e)throw new Error("useSelectRange must be used within a SelectRangeProvider");return e}function sB(e){return Array.isArray(e)?swt([],e):e!==void 0?[e]:[]}function wer(e){var t={};return Object.entries(e).forEach(function(n){var r=n[0],s=n[1];t[r]=sB(s)}),t}var uv;(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"})(uv||(uv={}));var Ser=uv.Selected,tb=uv.Disabled,ker=uv.Hidden,Oer=uv.Today,kie=uv.RangeEnd,Oie=uv.RangeMiddle,jie=uv.RangeStart,jer=uv.Outside;function Cer(e,t,n){var r,s=(r={},r[Ser]=sB(e.selected),r[tb]=sB(e.disabled),r[ker]=sB(e.hidden),r[Oer]=[e.today],r[kie]=[],r[Oie]=[],r[jie]=[],r[jer]=[],r);return e.fromDate&&s[tb].push({before:e.fromDate}),e.toDate&&s[tb].push({after:e.toDate}),cL(e)?s[tb]=s[tb].concat(t.modifiers[tb]):uL(e)&&(s[tb]=s[tb].concat(n.modifiers[tb]),s[jie]=n.modifiers[jie],s[Oie]=n.modifiers[Oie],s[kie]=n.modifiers[kie]),s}var cwt=g.createContext(void 0);function _er(e){var t=Yo(),n=D1e(),r=z1e(),s=Cer(t,n,r),i=wer(t.modifiers),o=Ar(Ar({},s),i);return a.jsx(cwt.Provider,{value:o,children:e.children})}function uwt(){var e=g.useContext(cwt);if(!e)throw new Error("useModifiers must be used within a ModifiersProvider");return e}function Ter(e){return!!(e&&typeof e=="object"&&"before"in e&&"after"in e)}function Eer(e){return!!(e&&typeof e=="object"&&"from"in e)}function Ier(e){return!!(e&&typeof e=="object"&&"after"in e)}function Ner(e){return!!(e&&typeof e=="object"&&"before"in e)}function Aer(e){return!!(e&&typeof e=="object"&&"dayOfWeek"in e)}function Per(e,t){var n,r=t.from,s=t.to;if(r&&s){var i=Ny(s,r)<0;i&&(n=[s,r],r=n[0],s=n[1]);var o=Ny(e,r)>=0&&Ny(s,e)>=0;return o}return s?qf(s,e):r?qf(r,e):!1}function $er(e){return j1e(e)}function Rer(e){return Array.isArray(e)&&e.every(j1e)}function Mer(e,t){return t.some(function(n){if(typeof n=="boolean")return n;if($er(n))return qf(e,n);if(Rer(n))return n.includes(e);if(Eer(n))return Per(e,n);if(Aer(n))return n.dayOfWeek.includes(e.getDay());if(Ter(n)){var r=Ny(n.before,e),s=Ny(n.after,e),i=r>0,o=s<0,l=Ehe(n.before,n.after);return l?o&&i:i||o}return Ier(n)?Ny(e,n.after)>0:Ner(n)?Ny(n.before,e)>0:typeof n=="function"?n(e):!1})}function F1e(e,t,n){var r=Object.keys(t).reduce(function(i,o){var l=t[o];return Mer(e,l)&&i.push(o),i},[]),s={};return r.forEach(function(i){return s[i]=!0}),n&&!R1e(e,n)&&(s.outside=!0),s}function Der(e,t){for(var n=Gf(e[0]),r=_1e(e[e.length-1]),s,i,o=n;o<=r;){var l=F1e(o,t),c=!l.disabled&&!l.hidden;if(!c){o=nu(o,1);continue}if(l.selected)return o;l.today&&!i&&(i=o),s||(s=o),o=nu(o,1)}return i||s}var Ler=365;function dwt(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:nu,week:Che,month:cv,year:bYn,startOfWeek:function(y){return s.ISOWeek?f0(y):lp(y,{locale:f,weekStartsOn:c})},endOfWeek:function(y){return s.ISOWeek?Q0t(y):T1e(y,{locale:f,weekStartsOn:c})}},p=h[n](e,r==="after"?1:-1);r==="before"&&u?p=wYn([u,p]):r==="after"&&d&&(p=SYn([d,p]));var m=!0;if(i){var v=F1e(p,i);m=!v.disabled&&!v.hidden}return m?p:l.count>Ler?l.lastFocused:dwt(p,{moveBy:n,direction:r,context:s,modifiers:i,retry:Ar(Ar({},l),{count:l.count+1})})}var fwt=g.createContext(void 0);function zer(e){var t=dL(),n=uwt(),r=g.useState(),s=r[0],i=r[1],o=g.useState(),l=o[0],c=o[1],u=Der(t.displayMonths,n),d=s??(l&&t.isDateDisplayed(l))?l:u,f=function(){c(s),i(void 0)},h=function(y){i(y)},p=Yo(),m=function(y,x){if(s){var b=dwt(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(fwt.Provider,{value:v,children:e.children})}function B1e(){var e=g.useContext(fwt);if(!e)throw new Error("useFocusContext must be used within a FocusProvider");return e}function Fer(e,t){var n=uwt(),r=F1e(e,n,t);return r}var V1e=g.createContext(void 0);function Ber(e){if(!gG(e.initialProps)){var t={selected:void 0};return a.jsx(V1e.Provider,{value:t,children:e.children})}return a.jsx(Ver,{initialProps:e.initialProps,children:e.children})}function Ver(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(V1e.Provider,{value:s,children:n})}function hwt(){var e=g.useContext(V1e);if(!e)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return e}function Uer(e,t){var n=Yo(),r=hwt(),s=D1e(),i=z1e(),o=B1e(),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,H,M,G;gG(n)?(V=r.onDayClick)===null||V===void 0||V.call(r,e,t,B):cL(n)?(H=s.onDayClick)===null||H===void 0||H.call(s,e,t,B):uL(n)?(M=i.onDayClick)===null||M===void 0||M.call(i,e,t,B):(G=n.onDayClick)===null||G===void 0||G.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)},I=function(B){var V;(V=n.onDayTouchCancel)===null||V===void 0||V.call(n,e,t,B)},P=function(B){var V;(V=n.onDayTouchEnd)===null||V===void 0||V.call(n,e,t,B)},A=function(B){var V;(V=n.onDayTouchMove)===null||V===void 0||V.call(n,e,t,B)},D=function(B){var V;(V=n.onDayTouchStart)===null||V===void 0||V.call(n,e,t,B)},z=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:z,onMouseEnter:C,onMouseLeave:T,onPointerEnter:_,onPointerLeave:N,onTouchCancel:I,onTouchEnd:P,onTouchMove:A,onTouchStart:D};return q}function qer(){var e=Yo(),t=hwt(),n=D1e(),r=z1e(),s=gG(e)?t.selected:cL(e)?n.selected:uL(e)?r.selected:void 0;return s}function Qer(e){return Object.values(uv).includes(e)}function Zer(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(Qer(r)){var i=e.classNames["day_".concat(r)];i&&n.push(i)}}),n}function Wer(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 Her(e,t,n){var r,s,i,o=Yo(),l=B1e(),c=Fer(e,t),u=Uer(e,c),d=qer(),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=Zer(o,c).join(" "),p=Wer(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:mer,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 Ger(e){var t=g.useRef(null),n=Her(e.date,e.displayMonth,t);return n.isHidden?a.jsx("div",{role:"gridcell"}):n.isButton?a.jsx(Oq,Ar({name:"day",ref:t},n.buttonProps)):a.jsx("div",Ar({},n.divProps))}function Ker(e){var t=e.number,n=e.dates,r=Yo(),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(Oq,{name:"week-number","aria-label":f,className:o.weeknumber,style:i.weeknumber,onClick:h,children:d})}function Yer(e){var t,n,r=Yo(),s=r.styles,i=r.classNames,o=r.showWeekNumber,l=r.components,c=(t=l?.Day)!==null&&t!==void 0?t:Ger,u=(n=l?.WeekNumber)!==null&&n!==void 0?n:Ker,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})},yXn(f))})]})}function u7e(e,t,n){for(var r=n?.ISOWeek?Q0t(t):T1e(t,n),s=n?.ISOWeek?f0(e):lp(e,n),i=Ny(r,s),o=[],l=0;l<=i;l++)o.push(nu(s,l));var c=o.reduce(function(u,d){var f=n?.ISOWeek?I1e(d):A1e(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 Xer(e,t){var n=u7e(Gf(e),_1e(e),t);if(t?.useFixedWeeks){var r=bXn(e,t);if(r<6){var s=n[n.length-1],i=s.dates[s.dates.length-1],o=Che(i,6-r),l=u7e(Che(i,1),o,t);n.push.apply(n,l)}}return n}function Jer(e){var t,n,r,s=Yo(),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=Xer(e.displayMonth,{useFixedWeeks:!!u,ISOWeek:p,locale:i,weekStartsOn:f,firstWeekContainsDate:h}),v=(t=d?.Head)!==null&&t!==void 0?t:per,y=(n=d?.Row)!==null&&n!==void 0?n:Yer,x=(r=d?.Footer)!==null&&r!==void 0?r:der;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 etr(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var ttr=etr()?g.useLayoutEffect:g.useEffect,Cie=!1,ntr=0;function d7e(){return"react-day-picker-".concat(++ntr)}function rtr(e){var t,n=e??(Cie?d7e():null),r=g.useState(n),s=r[0],i=r[1];return ttr(function(){s===null&&i(d7e())},[]),g.useEffect(function(){Cie===!1&&(Cie=!0)},[]),(t=e??s)!==null&&t!==void 0?t:void 0}function str(e){var t,n,r=Yo(),s=r.dir,i=r.classNames,o=r.styles,l=r.components,c=dL().displayMonths,u=rtr(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:uer;return a.jsxs("div",{className:f.join(" "),style:h,children:[a.jsx(y,{id:u,displayMonth:e.displayMonth,displayIndex:e.displayIndex}),a.jsx(Jer,{id:d,"aria-labelledby":u,displayMonth:e.displayMonth})]},e.displayIndex)}function itr(e){var t=Yo(),n=t.classNames,r=t.styles;return a.jsx("div",{className:n.months,style:r.months,children:e.children})}function otr(e){var t,n,r=e.initialProps,s=Yo(),i=B1e(),o=dL(),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:itr;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(str,{displayIndex:v,displayMonth:m},v)})})}))}function atr(e){var t=e.children,n=NJn(e,["children"]);return a.jsx(KJn,{initialProps:n,children:a.jsx(oer,{children:a.jsx(Ber,{initialProps:n,children:a.jsx(ger,{initialProps:n,children:a.jsx(xer,{initialProps:n,children:a.jsx(_er,{children:a.jsx(zer,{children:t})})})})})})})}function ltr(e){return a.jsx(atr,Ar({},e,{children:a.jsx(otr,{initialProps:e})}))}function Ihe({className:e,classNames:t,showOutsideDays:n=!0,...r}){return a.jsx(ltr,{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(Fn,"flex size-7 items-center justify-center rounded-md bg-transparent p-0 hover:bg-fill-subtle"),nav_button_next:Z(Fn,"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 pwt=g.createContext(void 0);function fL(e){const t=g.useContext(pwt);if(t===void 0&&!e)throw new Error(Pr(47));return t}const ctr={...k3,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 utr extends HC{constructor(t,n,r){const s=new GC;super(dtr(t,s,n,r),ftr(s),ctr)}setOpen=(t,n)=>{const r=n.reason===Ra,s=n.reason===iv&&n.event.detail===0,i=!t&&(n.reason===QC||n.reason==null),o=bbe(n),l=this.select("activeTriggerId");if(!t&&n.reason===ibe&&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};WW(d,t,n.trigger,o()),this.update(d)};r?(this.set("stickIfOpen",!0),this.context.stickIfOpenTimeout.start(rut,()=>{this.set("stickIfOpen",!1)}),bo.flushSync(c)):c();let u;s?u="click":i?u="dismiss":n.reason===r0&&(u="focus"),this.set("instantType",u)}}function dtr(e,t,n,r=!1){const s={...S3(),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=HW(t,n,r),s}function ftr(e){return{popupRef:g.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:g.createRef(),beforeContentFocusGuardRef:g.createRef(),stickIfOpenTimeout:new Pm,triggerElements:e}}function f7e({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=ptr(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),_ut(d,f),x3(d);const{forceUnmount:m}=b3(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,Yt(p3))}),[m,d]);const v=f||h;return a.jsxs(pwt.Provider,{value:d,children:[l&&a.jsx(v3,{handle:l,store:d}),v&&a.jsx(mtr,{store:d,modal:o}),typeof t=="function"?t({payload:p}):t]})}function htr(e){return fL(!0)?a.jsx(f7e,{props:e}):a.jsx(gbe,{children:a.jsx(f7e,{props:e})})}function ptr(e,t){const n=ZW((r,s)=>new utr(t,r,s));return g.useEffect(()=>n.context.stickIfOpenTimeout.disposeEffect(),[n]),n}function mtr({store:e,modal:t}){const n=e.useState("floatingRootContext"),r=WC(n,{outsidePressEvent:{mouse:t==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}}),s=r.reference,i=r.floating;return w3(e,{activeTriggerProps:s,inactiveTriggerProps:s,popupProps:i}),null}const gtr=300,vtr=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=gtr,closeDelay:h=0,id:p,...m}=t,v=fL(!0),x=O3(c)??v;if(!x)throw new Error(Pr(74));const b=Qi(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}=y3(b,T,x,{payload:u,disabled:o,openOnHover:d,closeDelay:h}),I=x.useState("openChangeReason"),P=x.useState("stickIfOpen"),A=x.useState("openMethod"),D=x.useState("focusManagerModal"),z=j3(k,{enabled:!o&&d&&(A!=="touch"||I!==iv),mouseOnly:!0,move:!1,handleClose:C3(),restMs:f,delay:{close:h},triggerElementRef:T,isActiveTrigger:S,isClosing:()=>x.select("transitionStatus")==="ending"}),Q=ZC(k,{stickIfOpen:P}),q=Xwe(()=>x.select("open"),ne=>{x.set("openMethod",ne)}),B=x.useState("triggerProps",N),{getButtonProps:V,buttonRef:H}=ud({disabled:o,native:l}),M={open(ne){return ne&&I===iv?XI.open(ne):TA.open(ne)}},{preFocusGuardRef:G,handlePreFocusGuardFocus:L,handleFocusTargetFocus:$}=jbt(x,T),U=pn("button",t,{state:{disabled:o,open:j},ref:[H,n,_,T],props:[Q.reference,z,B,q,{[fbe]:"",id:b,"aria-haspopup":"dialog","aria-expanded":j,"aria-controls":C},m,V],stateAttributesMapping:M}),K=a.jsx(g.Fragment,{children:U},b);return N&&!D?a.jsxs(g.Fragment,{children:[a.jsx(K1,{ref:G,onFocus:L}),K,a.jsx(K1,{ref:x.context.triggerFocusTargetRef,onFocus:$})]}):K}),mwt=g.createContext(void 0);function ytr(){const e=g.useContext(mwt);if(e===void 0)throw new Error(Pr(45));return e}const xtr=g.forwardRef(function(t,n){const{keepMounted:r=!1,...s}=t;return fL().useState("mounted")||r?a.jsx(mwt.Provider,{value:r,children:a.jsx(g3,{ref:n,...s})}):null}),gwt=g.createContext(void 0);function btr(){const e=g.useContext(gwt);if(!e)throw new Error(Pr(46));return e}const wtr=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=FW,...b}=t,S=fL(),k=ytr(),j=BW(),C=S.useState("floatingRootContext"),T=S.useState("mounted"),_=S.useState("open"),N=S.useState("openChangeReason"),I=S.useState("activeTriggerElement"),P=S.useState("modal"),A=S.useState("openMethod"),D=S.useState("positionerElement"),z=S.useState("instantType"),Q=S.useState("transitionStatus"),q=S.useState("adaptiveOrigin"),B=g.useRef(null),V=QW(D),H=EA({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");Tt(()=>{const U=M,K=B.current;if(U&&(B.current=U),K&&U&&U!==K){S.set("instantType",void 0);const ne=new AbortController;return V(()=>{S.set("instantType","trigger-change")},ne.signal),()=>{ne.abort()}}},[M,V,S]);const G=P===!0&&N!==Ra;oG(_&&G,A==="touch",D,I);const L=S.useStateSetter("positionerElement"),$={open:_,side:H.side,align:H.align,anchorHidden:H.anchorHidden,instant:z},F=IA(t,$,{styles:H.positionerStyles,transitionStatus:Q,props:b,refs:[n,L],hidden:!T,inert:!_});return a.jsxs(gwt.Provider,{value:H,children:[T&&G&&a.jsx(sL,{inert:NA(!_),cutout:I}),a.jsx(mbe,{id:j,children:F})]})}),Str=g.createContext(void 0);function ktr(){const[e,t]=g.useState(0),n=pt(()=>(t(s=>s+1),()=>{t(s=>Math.max(0,s-1))}));return{context:g.useMemo(()=>({register:n}),[n]),hasClosePart:e>0}}const Otr=g.forwardRef(function(t,n){const{render:r,className:s,style:i,initialFocus:o,finalFocus:l,...c}=t,u=fL(),d=btr(),f=Ywe()!=null,{context:h,hasClosePart:p}=ktr(),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"),I=N.useState("floatingId"),P=u.useState("disabled"),A=u.useState("openOnHover"),D=u.useState("closeDelay");ql({open:m,ref:u.context.popupRef,onComplete(){m&&u.context.onOpenChangeComplete?.(!0)}}),GW(N,{enabled:A&&!P,closeDelay:D});const z=o===void 0?Out(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=pn("div",t,{state:B,ref:[n,u.context.popupRef,q],props:[b,{id:I,role:"dialog",...ZS,"aria-labelledby":S,"aria-describedby":k,onKeyDown(H){f&&ek.has(H.key)&&H.stopPropagation()}},XC(x),c],stateAttributesMapping:YC});return a.jsx(_A,{context:N,openInteractionType:v,modal:Q,disabled:!C||T===Ra,initialFocus:z,returnFocus:l,restoreFocus:"popup",previousFocusableElement:si(_)?_:void 0,nextFocusableElement:u.context.triggerFocusTargetRef,beforeContentFocusGuardRef:u.context.beforeContentFocusGuardRef,children:a.jsx(Str.Provider,{value:h,children:V})})}),bp=htr,rf=g.forwardRef(({className:e,asChild:t,render:n,children:r,variant:s,size:i,tooltip:o,...l},c)=>{const u=Lbt({render:n,asChild:t,children:r,variant:s,size:i,tooltip:o,className:e});return a.jsx(vtr,{ref:c,className:u.className,render:u.render,...l,children:u.children})});rf.displayName="PopoverTrigger";const nh=g.forwardRef(({className:e,container:t,align:n="center",alignOffset:r=0,side:s="bottom",sideOffset:i=4,anchor:o,positionMethod:l=vv,collisionBoundary:c,collisionPadding:u,sticky:d,arrowPadding:f,disableAnchorTracking:h,collisionAvoidance:p,...m},v)=>{const y=typeof e=="string"?e:void 0,x=A0(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(xtr,{container:x,children:a.jsx(wtr,{className:"z-50 outline-none",...b,children:a.jsx(Otr,{ref:v,"data-slot":"popover-content",className:Z("z-50 w-72 origin-[var(--transform-origin)] rounded-xl text-foreground focus-visible:outline-hidden",Jf,"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})})})});nh.displayName="PopoverContent";const jtr=({inputProps:e,field:t})=>{const{key:n,...r}=e,[s,i]=g.useState(void 0),[o,l]=g.useState(!1),c=dmt();g.useEffect(()=>{if(t.default){const f=new Date(t.default);C1e(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(bp,{open:o,onOpenChange:l,children:[a.jsx(rf,{asChild:!0,children:a.jsx(de,{...c,variant:"default",size:"lg",className:Z("w-full",Ibe),icon:a.jsx(rU,{}),children:s?a.jsx("span",{className:"text-foreground",children:nk(s,"PPP")}):a.jsx("span",{className:"text-muted-foreground",children:"Pick a date"})})}),a.jsxs(nh,{className:"w-auto bg-muted p-0",align:"start",children:[a.jsx(Ihe,{mode:"single",selected:s,onSelect:u,month:s,onMonthChange:i}),s&&a.jsx("div",{className:"p-3 pt-0",children:a.jsx(de,{icon:a.jsx(Ln,{}),variant:"default",size:"lg",className:"w-full",onClick:d,children:"Clear"})})]})]})},Ctr=({field:e,path:t})=>{const{uiComponents:n}=k1e(),{control:r}=zr(),{fields:s,append:i,remove:o}=wKn({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:q4(e),field:e,onAddItem:()=>i(c),children:s.map((d,f)=>a.jsx(pG,{value:[...t,f.toString()].join("."),children:a.jsx(n.ArrayElementWrapper,{onRemove:()=>o(f),index:f,children:a.jsx(gj,{field:u,path:[...t,f.toString()]})})},d.id))}):a.jsx(n.ErrorMessage,{error:`[AutoForm] Unable to determine array element schema for "${q4(e)}"`})},_tr=({field:e,path:t})=>{const{uiComponents:n}=k1e();return a.jsx(pG,{value:t.join("."),children:a.jsx(n.ObjectWrapper,{label:q4(e),field:e,children:Object.entries(e.schema??[]).map(([r,s])=>a.jsx(gj,{field:s,path:[...t,s.key]},`${t.join(".")}.${s.key}`))})})},gj=({field:e,path:t})=>{const{formComponents:n,uiComponents:r}=k1e(),{register:s,formState:{errors:i,defaultValues:o},getValues:l,control:c}=zr(),u=t.join("."),d=e7e(i,t)?.message,f=Qn({control:c,name:u}),h=f===void 0?l(u):f,p=g.useMemo(()=>{if(!o)return e.default;const x=e7e(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=Ctr:e.type==="object"?v=_tr: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:q4(e),error:d,id:u,field:y,children:a.jsx(v,{label:q4(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)})},Ttr=({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(gj,{field:c,path:[...t,c.key]},`${r}.${c.key}`),f&&u?.[f]&&u[f].map(h=>a.jsx(gj,{field:h,path:[...t,h.key]},`${r}.${h.key}`)),d&&d.map(h=>a.jsx(gj,{field:h,path:[...t,h.key]},`${r}.${h.key}`))]},e.key)},Etr=({error:e})=>a.jsx(Wt,{variant:"destructive",title:e}),Itr=["object","array"];function h7e({description:e,error:t}){return!e&&!t?null:a.jsxs(ft,{invalid:!!t,children:[e&&a.jsx(eo,{children:e}),a.jsx(cs,{children:t})]})}const Ntr=({label:e,children:t,field:n,error:r})=>{const s=n.fieldConfig?.description;if(n.type==="record")return a.jsxs(a0,{className:"gap-2 pb-4 last:pb-0",children:[a.jsx(l0,{required:n.required,children:e}),t,a.jsx(h7e,{description:s,error:r})]});if(Itr.includes(n.type))return a.jsxs("div",{className:"pb-4 last:pb-0",children:[t,a.jsx(h7e,{description:s,error:r})]});const i=n.type==="boolean";return a.jsxs(ft,{invalid:!!r,className:"pb-4 last:pb-0",children:[!i&&a.jsx(lt,{required:n.required,children:e}),t,s&&a.jsx(eo,{children:s}),a.jsx(cs,{children:r})]})};function Atr({className:e,...t}){return a.jsx("form",{"data-slot":"form",className:Z("flex flex-col gap-4",e),...t})}const vwt=g.forwardRef(function(t,n){return a.jsx(cmt,{ref:n,...t})}),Ptr=dd(Z("flex w-full text-ellipsis text-foreground",On,"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(Wut,"rounded-full",Tbe),unstyled:Nbe},size:{sm:Z(Xg.sm,"px-[.75em]"),md:Z(Xg.md,"px-[.75em]"),lg:Z(Xg.lg,"px-[.85em]")}},defaultVariants:{variant:"default",size:"md"}});function Sn({className:e,size:t,testId:n,variant:r,error:s,...i}){return a.jsx(vwt,{className:Z(Ptr({variant:Hut(r),size:t}),Uut,e),"data-testid":n,...XW(s),...i,...wx(i)})}const $tr=({inputProps:e,field:t})=>{const{key:n,...r}=e;return a.jsx(Sn,{type:"number",step:"any",...r,defaultValue:t.default!==void 0?Number(t.default):void 0,onChange:s=>{const i=s.target.value;i!==""&&!isNaN(Number(i))&&r.onChange({target:{value:i,name:e.name}})},onBlur:s=>{const i=s.target.value;i!==""&&!isNaN(Number(i))&&r.onChange({target:{value:Number(i),name:e.name}})}})};function Rtr({label:e,children:t}){return e===mG||e===""?a.jsx("div",{className:"flex flex-col gap-2",children:t}):a.jsx(Mtr,{label:e,children:t})}function Mtr({label:e,children:t}){const n=g.useContext(pG),{expanded:r,invalid:s,setExpanded:i}=ewt(n,!1);return a.jsxs(Wl,{open:r,onOpenChange:i,className:"motion-reduce:[&_[data-slot=collapsible-content]]:transition-none motion-reduce:[&_svg]:transition-none",children:[a.jsxs(wl,{className:"flex min-h-11 w-full items-center gap-2 text-left text-caption text-muted-foreground",children:[a.jsx(Gs,{"aria-hidden":!0,className:"size-3.5 shrink-0"}),a.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[a.jsx(al,{"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(Sl,{keepMounted:!0,className:"border-l border-border pt-2 pl-4",children:t})]})}const Dtr=({inputProps:e,field:t})=>{const{onChange:n}=e,[r,s]=g.useState(()=>Object.entries(t.default||{}).map(([d,f])=>({id:d||wa(),key:d,value:f})));g.useEffect(()=>{r.length===0&&s([{id:wa(),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:wa(),key:"",value:""}];s(d),i(d)},u=d=>{const f=r.filter(h=>h.id!==d);f.length===0&&f.push({id:wa(),key:"",value:""}),s(f),i(f)};return a.jsxs("div",{className:"space-y-3",children:[r.map(d=>a.jsxs("div",{className:"relative space-y-2 rounded-lg border p-4",children:[a.jsx(de,{type:"button","aria-label":"Remove pair",className:"absolute top-2 right-2",onClick:()=>u(d.id),children:a.jsx(Bdt,{className:"size-4"})}),a.jsxs("div",{className:"space-y-2 pt-4",children:[a.jsx(Sn,{"aria-label":"Key",placeholder:"Key",value:d.key,onChange:f=>o(d.id,"key",f.target.value),onBlur:l}),a.jsx(Sn,{"aria-label":"Value",placeholder:"Value",value:d.value,onChange:f=>o(d.id,"value",f.target.value),onBlur:l})]})]},d.id)),a.jsx(de,{type:"button",className:"w-full",onClick:c,icon:a.jsx(bs,{}),children:"Add Key-Value Pair"})]})},Ltr=({field:e,inputProps:t,value:n})=>{const{key:r,...s}=t;return a.jsxs(Ur,{...s,value:n,onValueChange:i=>{const o={target:{value:i,name:t.name}};s.onChange(o)},children:[a.jsx(Qr,{children:a.jsx(qr,{placeholder:"Select an option"})}),a.jsx(Zr,{children:(e.options||[]).map(([i,o])=>a.jsx(or,{value:i,children:o},i))})]})},ztr=({inputProps:e,field:t})=>{const{key:n,className:r,...s}=e;return a.jsx(Ou,{...s,rows:1,className:Z("field-sizing-content max-h-48 min-h-control-md resize-none overflow-y-auto",r),defaultValue:t.default})},Ftr=({children:e})=>a.jsx(de,{type:"submit",children:e}),Btr=({field:e,inputProps:t})=>{const n=t.name?.split(".")??[];return e.schema?.map((r,s)=>a.jsxs("div",{children:[a.jsx(gj,{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 Vtr({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(()=>DKn(e),[e]),f=tk({defaultValues:{...LKn(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(U4,{...f,children:a.jsx(WKn,{value:p,children:a.jsxs(i.Form,{onSubmit:f.handleSubmit(h),...u,children:[d.fields.map(m=>a.jsx(gj,{field:m,path:[m.key]},m.key)),s,l&&a.jsx(i.SubmitButton,{children:"Submit"})]})})})}const Utr={Form:Atr,FieldWrapper:Ntr,ErrorMessage:Etr,SubmitButton:Ftr,ObjectWrapper:Rtr,ArrayWrapper:wJn,ArrayElementWrapper:bJn};function qtr({uiComponents:e,formComponents:t,readOnly:n,...r}){const s=g.useMemo(()=>({...Utr,...e}),[e]),i=g.useMemo(()=>{const o=l=>n===void 0?l:{...l,readOnly:n};return{string:l=>a.jsx(ztr,{...l,inputProps:o(l.inputProps)}),number:l=>a.jsx($tr,{...l,inputProps:o(l.inputProps)}),boolean:l=>a.jsx(IJn,{...l,inputProps:o(l.inputProps)}),date:l=>a.jsx(jtr,{...l,inputProps:o(l.inputProps)}),select:l=>a.jsx(Ltr,{...l,inputProps:o(l.inputProps)}),record:l=>a.jsx(Dtr,{...l,inputProps:o(l.inputProps)}),union:l=>a.jsx(Btr,{...l,inputProps:o(l.inputProps)}),"discriminated-union":l=>a.jsx(Ttr,{...l,inputProps:o(l.inputProps)}),...t}},[n,t]);return a.jsx(b1e,{value:n===!0,children:a.jsx(Vtr,{...r,uiComponents:s,formComponents:i})})}function ywt(e){return e!=null&&typeof e=="object"&&"_zod"in e}function ju(e){if(!(e==null||typeof e!="object"))return ywt(e)?e._zod.def:e._def}function Qtr(e){return typeof e.isOptional=="function"?e.isOptional():typeof e.safeParse=="function"?e.safeParse(void 0).success:!1}function xm(e){if(e.shape&&typeof e.shape=="object")return e.shape;const t=ju(e);if(t?.shape)return typeof t.shape=="function"?t.shape():t.shape}function W4(e){const t=ju(e);return t?"innerType"in t?W4(t.innerType):"schema"in t?W4(t.schema):e:e}function Ztr(e){const t=ju(e);if(t?.entries)return t.entries;if(t?.values)return t.values}function xwt(e){const t=ju(e);return t?.element??t?.type}function Wtr(e){return ju(e)?.valueType}function bwt(e){const t=ju(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 Htr(e){const t=ju(e);if(t?.values!==void 0)return t.values;if(t?.value!==void 0)return[t.value]}function Gtr(e){const t=ju(e);if(t?.defaultValue!==void 0)return typeof t.defaultValue=="function"?t.defaultValue():t.defaultValue}function U1e(e){return ju(e)?.options}function jq(e){const t=ju(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 Ktr(e){return ju(e)?.checks??[]}function Ytr(e){return e.some(t=>{if(ywt(t)){const n=ju(t);return n?.check==="string_format"&&n?.format==="datetime"}return t.kind==="datetime"})}function Cq(e){const t=xm(e);if(t)return Object.keys(t).length===0;const n=jq(e);return n?Cq(n.left)&&Cq(n.right):!1}function HO(e){const t=ju(e);if(!t)return;const n=Gtr(e);if(n!==void 0)return n;const r=bwt(e);if(r!==void 0&&(t.typeName==="ZodLiteral"||t.type==="literal"||e?.constructor?.name?.slice(1)==="ZodLiteral"))return r;if("innerType"in t)return HO(t.innerType);if("schema"in t)return HO(t.schema);if(xm(e)&&!("left"in t))return iB(e);if("left"in t&&"right"in t){const i=xm(t.left),o=xm(t.right),l=i?iB(t.left):HO(t.left),c=o?iB(t.right):HO(t.right);return{...l,...c}}}function iB(e){const t=xm(e);if(!t)return{};const n={};for(const[r,s]of Object.entries(t)){const i=HO(s);i!==void 0&&(n[r]=i)}return n}function wwt(e,t){if(t?.fieldType)return t.fieldType;const n=e?.constructor?.name?.slice(1),r=ju(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=Ktr(e);return Ytr(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=U1e(e);return o&&o.every(c=>{const u=xm(c);return u?Object.values(u).some(d=>{const f=d?.constructor?.name?.slice(1),h=ju(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=bwt(e);return typeof o=="number"?"number":typeof o=="boolean"?"boolean":"string"}return"string"}function Nhe(e){const t=ju(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 Nhe(t.innerType);if("schema"in t)return Nhe(t.schema)}}function Lw(e,t){const n=W4(t),r=Nhe(t);let s=wwt(n,r);const i=HO(t),o=Ztr(n);let l=[];o&&(Array.isArray(o)?l=o.map(b=>[b,b]):l=Object.entries(o));let c=[];const u=xm(n);u&&!jq(n)&&(c=Object.entries(u).map(([b,S])=>Lw(b,S)));const d=U1e(n),f=n?.constructor?.name?.slice(1),h=ju(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])=>Lw(b,S)));const v=jq(n);if(v){const{left:b,right:S}=v;let k=[],j=[];const C=xm(b);if(C)k=Object.entries(C).map(([_,N])=>Lw(_,N));else{const _=Lw(e,b);k=_.schema??[_],s=_.type}const T=xm(S);if(T)j=Object.entries(T).map(([_,N])=>Lw(_,N));else{const _=Lw(e,S);j=_.schema??[_],s=_.type}c=[...k,...j]}if(m==="ZodArray"){const b=xwt(n);b&&(c=[Lw("0",b)])}const y=m==="ZodLiteral",x=y?Htr(n):void 0;return{key:e,type:s,required:!Qtr(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 Xtr(e){const t=xm(e);return t?{fields:Object.entries(t).map(([r,s])=>Lw(r,s))}:{fields:[]}}function Jtr(e){const t=jq(e);return t?[t.left,t.right]:U1e(e)}function p7e(e,t){const n={};for(const[r,s]of Object.entries(e)){const i=t(r),o=i?_q(s,i):s;o!==void 0&&(n[r]=o)}return n}function m7e(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 _q(e,t){const n=W4(t),r=Jtr(n);if(r){const l=r.reduce((c,u)=>_q(c,u),e);return D2(l)&&m7e(t,l)?void 0:l}const s=xm(n);if(s&&D2(e)){const l=p7e(e,c=>s[c]);return m7e(t,l)?void 0:l}const i=Wtr(n);if(i&&D2(e))return p7e(e,()=>i);if(Array.isArray(e)){const l=xwt(n);return l&&typeof l=="object"?e.map(c=>_q(c,l)):e}if(!((e===""||e===null&&!t.safeParse(null).success)&&HO(t)===void 0))return e}class enr{_schema;constructor(t){if(!t)throw new Error("CustomZodProvider: schema is required");this._schema=t}getDefaultValues(){return iB(this._schema)}validateSchema(t){const n=_q(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 Xtr(this._schema)}}function _ie(e,t){return t?e[mG]:e}function tnr(e,t){return Cq(e)?vr({}):t?vr({[mG]:e.description?e:e.describe("Input")}):e}const Swt=g.createContext(null),nnr=({children:e})=>{const t=g.useContext(Swt);return t?a.jsx(a1e,{...t,children:e}):null},rnr={SubmitButton:nnr};function q1e({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=xm(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?.(_ie(_,m))),y.current?.(_ie(T.getValues(),m)))},[x,m]),S=g.useMemo(()=>e?new enr(tnr(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:{[mG]:r}:r,[m,r]),C=g.useCallback(async T=>{await t?.(_ie(T,m))},[t,m]);return S?a.jsx(Swt.Provider,{value:k,children:a.jsx(qtr,{schema:S,onSubmit:C,onFormInit:b,defaultValues:j,formProps:{className:u,noValidate:!0},uiComponents:rnr,withSubmit:!0,readOnly:d,children:f})}):(console.error("no form schema found"),null)}const snr=a.jsx(Nt,{children:a.jsx(ku,{})});function inr(e,t){if(!t)return{type:"form",value:e};const n=e??MGn(),r=Jbt(n);return r?{type:"simple",value:r}:{type:"json",value:JSON.stringify(n,null,2)}}function g7e(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 onr(e,t){const n=wwt(W4(e));if(n==="object"&&!D2(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."}const Q1e=({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=snr,submitButtonVariant:h="primary",submitButtonFullWidth:p,hideInputTypeLabel:m,inputTypeLabel:v="Run input",hideHeading:y})=>{const[x,b]=g.useState(()=>inr(t,o)),S=g.useRef(t),[k,j]=g.useState([]);function C(){return x.type==="json"?g7e(x.value):{ok:!0,value:x.type==="form"?S.current:x.value}}function T(z){const Q=g7e(z);if(!Q.ok)return j([Q.error]);const q=e.safeParse(Q.value);q.success?s(q.data):j(q.error.issues.map(B=>`${B.path.join(".")||"Input"}: ${B.message}`))}function _(z){if(z===x.type)return;j([]);const Q=C();if(!Q.ok)return j([Q.error]);if(z==="json")return b({type:z,value:JSON.stringify(Q.value===void 0?{}:Q.value,null,2)});if(z==="simple"){const B=Jbt(Q.value);return B?b({type:z,value:B}):j(["Simple input requires a messages array with text parts and a string phase. Correct the JSON first."])}const q=onr(e,Q.value);return q?j([q]):b({type:z,value:Q.value})}const N=a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",children:"Trigger a run"}),I=!d&&!y,P=d||y||m,A=a.jsx(dKn,{value:x.type,onChange:_,disabled:n,includeSimple:o,compact:I}),D=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}),I&&a.jsx("div",{className:"shrink-0",children:A})]}),a.jsxs("div",{className:"px-5",children:[P&&a.jsx("div",{className:"pb-4",children:A}),a.jsx("div",{className:Z("pb-4",{"pointer-events-none opacity-50":n}),children:x.type==="json"?a.jsx(zGn,{value:x.value,onChange:z=>{b({type:"json",value:z}),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(uKn,{schema:e,value:x.value,onChange:z=>b({type:"simple",value:z}),isSubmitLoading:n,submitButtonLabel:r,submitButtonIcon:f,submitButtonVariant:h,submitButtonFullWidth:p,onSubmit:s,submitActions:l,leftActions:c,children:i}):a.jsx(anr,{schema:e,onValuesChange:z=>{S.current=z},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(Wl,{defaultOpen:!0,children:[a.jsxs(wl,{className:"flex w-full items-center gap-2 pb-3 text-left",children:[a.jsx(Gs,{className:"size-4 shrink-0 text-muted-foreground"}),u??N]}),a.jsx(Sl,{keepMounted:!0,children:D})]}):a.jsxs(a.Fragment,{children:[!y&&a.jsx("div",{className:"border-b border-border pb-3",children:u??N}),a.jsx("div",{children:D})]})},anr=({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(q1e,{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 lnr({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(Q1e,{schema:e,defaultValues:r,isSubmitLoading:t,submitButtonLabel:d,inputTypeLabel:"Next run input",submitButtonVariant:"primary",submitButtonIcon:a.jsx(Nt,{children:a.jsx(ku,{})}),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(de,{variant:"primary",disabled:t,onClick:()=>n(null),children:[t?a.jsx(Nt,{children:a.jsx(dc,{className:"animate-spin"})}):a.jsx(Nt,{children:a.jsx(ku,{})}),d]})]})]})]})}const xl=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 cnr({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(Nt,{className:"shrink-0 text-muted-foreground",children:a.jsx(xl,{})}),a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",className:"truncate",children:e.name??t}),a.jsx(io,{content:e.name??t,variant:"ghost",className:"shrink-0"}),a.jsxs(Ft,{className:"ml-auto shrink-0",children:[n," step",n===1?"":"s"]})]})}const kwt=g.createContext(void 0);function hL(){const e=g.useContext(kwt);if(e===void 0)throw new Error(Pr(53));return e}const unr=500,Ahe=16;function u1(e,t,n){if(!e)return 0;const r=getComputedStyle(e),s=`${t}${n==="x"?"Inline":"Block"}`,i=parseFloat(r[`${s}Start`]);return n==="x"&&t==="margin"?i*2:i+parseFloat(r[`${s}End`])}const _T=e=>t=>t?{[e]:""}:null,vG={hasOverflowX:_T("data-has-overflow-x"),hasOverflowY:_T("data-has-overflow-y"),overflowXStart:_T("data-overflow-x-start"),overflowXEnd:_T("data-overflow-x-end"),overflowYStart:_T("data-overflow-y-start"),overflowYEnd:_T("data-overflow-y-end"),cornerHidden:()=>null},dnr={x:0,y:0},v7e={width:0,height:0},fnr={xStart:!1,xEnd:!1,yStart:!1,yEnd:!1},hnr={x:!0,y:!0,corner:!0},pnr=g.forwardRef(function(t,n){const{render:r,className:s,overflowEdgeThreshold:i,style:o,...l}=t,{xStart:c,xEnd:u,yStart:d,yEnd:f}=mnr(i),h=Qi(),p=No(),m=No(),{nonce:v,disableStyleElements:y}=Wwe(),[x,b]=g.useState(!1),[S,k]=g.useState(!1),[j,C]=g.useState(!1),[T,_]=g.useState(!1),[N,I]=g.useState(!1),[P,A]=g.useState(v7e),[D,z]=g.useState(v7e),[Q,q]=g.useState(fnr),[B,V]=g.useState(hnr),H=g.useRef(null),M=g.useRef(null),G=g.useRef(null),L=g.useRef(null),$=g.useRef(null),F=g.useRef(null),U=g.useRef(null),K=g.useRef(null),ne=g.useRef(0),X=g.useRef(0),te=g.useRef(0),oe=g.useRef(0),ue=g.useRef("vertical"),ee=g.useRef(dnr),se=g.useRef(null);function re(Ce){const Te=Ce?C:k,_e=Ce?p:m;Te(!0),_e.start(unr,()=>{Te(!1)})}const ae=pt(Ce=>{const Te=Ce.x-ee.current.x,_e=Ce.y-ee.current.y;ee.current=Ce,_e!==0&&re(!0),Te!==0&&re(!1)}),pe=pt(()=>{const Ce=M.current;Ce&&se.current===null&&(se.current=Ce.style.scrollSnapType,Ce.style.scrollSnapType="none")}),ve=pt(Ce=>{if(Ce.button!==0||K.current!==null&&(ue.current==="vertical"?$.current:F.current)?.hasPointerCapture(K.current))return;K.current=Ce.pointerId,ne.current=Ce.clientY,X.current=Ce.clientX,ue.current=Ce.currentTarget.getAttribute("data-orientation");const Te=M.current;Te&&(te.current=Te.scrollTop,oe.current=Te.scrollLeft,pe()),(ue.current==="vertical"?$.current:F.current)?.setPointerCapture(Ce.pointerId)}),he=pt(Ce=>{if(Ce.pointerId!==K.current)return;K.current=null,(ue.current==="vertical"?C:k)(!1),se.current!==null&&(M.current&&(M.current.style.scrollSnapType=se.current),se.current=null);const Te=ue.current==="vertical"?$.current:F.current;Te?.hasPointerCapture(Ce.pointerId)&&Te.releasePointerCapture(Ce.pointerId)}),Oe=pt(Ce=>{if(Ce.pointerId!==K.current)return;if(Ce.buttons%2===0){he(Ce);return}const Te=M.current;if(!Te)return;const _e=ue.current==="vertical",ce=_e?$.current:F.current,ye=_e?G.current:L.current;if(!ce||!ye)return;const Me=_e?"y":"x",Ie=u1(ye,"padding",Me),le=u1(ce,"margin",Me),xe=_e?ce.offsetHeight:ce.offsetWidth,$e=(_e?ye.offsetHeight:ye.offsetWidth)-xe-Ie-le,ze=_e?Ce.clientY-ne.current:Ce.clientX-X.current,He=$e<=0?0:ze/$e,De=_e?Te.scrollHeight:Te.scrollWidth,tt=_e?Te.clientHeight:Te.clientWidth,rt=(_e?te.current:oe.current)+He*(De-tt);_e?Te.scrollTop=rt:Te.scrollLeft=rt,Ce.preventDefault(),re(_e)});function Ee(Ce){_(Ce.pointerType==="touch")}function Fe(Ce){if(Ee(Ce),Ce.pointerType!=="touch"){const Te=ln(H.current,Ce.target);b(Te)}}const qe=g.useMemo(()=>({scrolling:S||j,hasOverflowX:!B.x,hasOverflowY:!B.y,overflowXStart:Q.xStart,overflowXEnd:Q.xEnd,overflowYStart:Q.yStart,overflowYEnd:Q.yEnd,cornerHidden:B.corner}),[S,j,B.x,B.y,B.corner,Q]),Be={role:"presentation",onPointerEnter:Fe,onPointerMove:Fe,onPointerDown:Ee,onPointerLeave(){b(!1)},style:{position:"relative","--scroll-area-corner-height":`${P.height}px`,"--scroll-area-corner-width":`${P.width}px`}},Pe=pn("div",t,{state:qe,ref:[n,H],props:[Be,l],stateAttributesMapping:vG}),Ve=g.useMemo(()=>({handlePointerDown:ve,handlePointerMove:Oe,handlePointerUp:he,handleScroll:ae,disableViewportSnap:pe,cornerSize:P,setCornerSize:A,thumbSize:D,setThumbSize:z,hasMeasuredScrollbar:N,setHasMeasuredScrollbar:I,touchModality:T,cornerRef:U,scrollingX:S,scrollingY:j,hovering:x,setHovering:b,viewportRef:M,scrollbarYRef:G,scrollbarXRef:L,thumbYRef:$,thumbXRef:F,rootId:h,hiddenState:B,setHiddenState:V,overflowEdges:Q,setOverflowEdges:q,viewportState:qe,overflowEdgeThreshold:{xStart:c,xEnd:u,yStart:d,yEnd:f}}),[ve,Oe,he,ae,pe,P,D,N,T,S,j,x,h,B,Q,qe,c,u,d,f]);return a.jsxs(kwt.Provider,{value:Ve,children:[!y&&V4.getElement(v),Pe]})});function mnr(e){const t=typeof e=="number"?{xStart:e,xEnd:e,yStart:e,yEnd:e}:e;return{xStart:Math.max(0,t?.xStart||0),xEnd:Math.max(0,t?.xEnd||0),yStart:Math.max(0,t?.yStart||0),yEnd:Math.max(0,t?.yEnd||0)}}const Owt=g.createContext(void 0);function gnr(){const e=g.useContext(Owt);if(e===void 0)throw new Error(Pr(55));return e}const jwt=["--scroll-area-overflow-x-start","--scroll-area-overflow-x-end","--scroll-area-overflow-y-start","--scroll-area-overflow-y-end"];let y7e=!1;function vnr(){y7e||gx||(typeof CSS<"u"&&"registerProperty"in CSS&&jwt.forEach(e=>{try{CSS.registerProperty({name:e,syntax:"<length>",inherits:!1,initialValue:"0px"})}catch{}}),y7e=!0)}const ynr=g.forwardRef(function(t,n){const{render:r,className:s,style:i,...o}=t,{viewportRef:l,scrollbarYRef:c,scrollbarXRef:u,thumbYRef:d,thumbXRef:f,cornerRef:h,cornerSize:p,setCornerSize:m,setThumbSize:v,rootId:y,setHiddenState:x,hiddenState:b,setHasMeasuredScrollbar:S,handleScroll:k,touchModality:j,setHovering:C,setOverflowEdges:T,overflowEdgeThreshold:_,viewportState:N}=hL(),I=vx(),P=g.useRef(!0),A=g.useRef([NaN,NaN,NaN,NaN]),D=No(),z=No(),Q=pt(()=>{const M=l.current,G=c.current,L=u.current,$=d.current,F=f.current,U=h.current;if(!M)return;const K=M.scrollHeight,ne=M.scrollWidth,X=M.clientHeight,te=M.clientWidth,oe=M.scrollTop,ue=M.scrollLeft,ee=A.current,se=Number.isNaN(ee[0]);if(ee[0]=X,ee[1]=K,ee[2]=te,ee[3]=ne,se&&S(!0),K===0||ne===0)return;const re=xnr(M),ae=re.y,pe=re.x,ve=te/ne,he=X/K,Oe=Math.max(0,ne-te),Ee=Math.max(0,K-X);let Fe=0,qe=0;pe||(Fe=yhe(I==="rtl"?-ue:ue,Oe),qe=Oe-Fe);const Be=ae?0:yhe(oe,Ee),Pe=ae?0:Ee-Be,Ve=pe?0:te,Ce=ae?0:X;let Te=0,_e=0;!pe&&!ae&&(Te=G?.offsetWidth||0,_e=L?.offsetHeight||0);const ce=p.width===0&&p.height===0,ye=ce?Te:0,Me=ce?_e:0,Ie=u1(L,"padding","x"),le=u1(G,"padding","y"),xe=u1(F,"margin","x"),Se=u1($,"margin","y"),$e=Ve-Ie-xe,ze=Ce-le-Se,He=L?Math.min(L.offsetWidth-ye,$e):$e,De=G?Math.min(G.offsetHeight-Me,ze):ze,tt=Math.max(Ahe,He*ve),Ze=Math.max(Ahe,De*he);if(v(me=>M8(me,{width:tt,height:Ze})),G&&$){const me=G.offsetHeight-Ze-le-Se,Le=x7e($,"--scroll-area-thumb-height",oe,Ee,K,Ze,me);$.style.transform=`translate3d(0,${Le}px,0)`}if(L&&F){const me=L.offsetWidth-tt-Ie-xe,Le=I==="rtl"?-ue:ue,et=x7e(F,"--scroll-area-thumb-width",Le,Oe,ne,tt,me);F.style.transform=`translate3d(${I==="rtl"?-et:et}px,0,0)`}const rt=[Fe,qe,Be,Pe];jwt.forEach((me,Le)=>{M.style.setProperty(me,`${rt[Le]}px`)}),U&&m(me=>M8(me,{width:Te,height:_e})),x(me=>M8(me,re));const At={xStart:!pe&&Fe>_.xStart,xEnd:!pe&&qe>_.xEnd,yStart:!ae&&Be>_.yStart,yEnd:!ae&&Pe>_.yEnd};T(me=>M8(me,At))});Tt(()=>{vnr()},[]),Tt(()=>{queueMicrotask(Q)},[Q,b,I,_.xStart,_.xEnd,_.yStart,_.yEnd]),Tt(()=>{l.current?.matches(":hover")&&C(!0)},[l,C]),Tt(()=>{const M=l.current;if(typeof ResizeObserver>"u"||!M)return;let G=!1;const L=new ResizeObserver(()=>{if(!G){G=!0;const $=A.current;if($[0]===M.clientHeight&&$[1]===M.scrollHeight&&$[2]===M.clientWidth&&$[3]===M.scrollWidth)return}Q()});return L.observe(M),z.start(0,()=>{const $=M.getAnimations({subtree:!0});$.length!==0&&Promise.allSettled($.map(F=>F.finished)).then(Q).catch(()=>{})}),()=>{L.disconnect(),z.clear()}},[Q,l,z]);function q(){P.current=!1}const B={role:"presentation",...y&&{"data-id":`${y}-viewport`},tabIndex:b.x&&b.y?-1:0,className:V4.className,style:{overflow:"scroll"},onScroll(){l.current&&(Q(),(j||!P.current)&&k({x:l.current.scrollLeft,y:l.current.scrollTop}),D.start(100,()=>{P.current=!0}))},onWheel:q,onPointerMove:q,onPointerEnter:q,onKeyDown:q},V=pn("div",t,{ref:[n,l],state:N,props:[B,o],stateAttributesMapping:vG}),H=g.useMemo(()=>({computeThumbPosition:Q}),[Q]);return a.jsx(Owt.Provider,{value:H,children:V})});function xnr(e){const t=e.clientHeight>=e.scrollHeight,n=e.clientWidth>=e.scrollWidth;return{y:t,x:n,corner:t||n}}function M8(e,t){for(const n in t)if(e[n]!==t[n])return t;return e}function x7e(e,t,n,r,s,i,o){const l=Ni(n,0,r),c=n-l,u=Math.max(Ahe,i*s/(s+Math.abs(c)));return e.style.setProperty(t,c?`${u}px`:""),(r?l/r*o:0)+(c>0?i-u:0)}const Cwt=g.createContext(void 0);function bnr(){const e=g.useContext(Cwt);if(e===void 0)throw new Error(Pr(54));return e}const wnr=g.forwardRef(function(t,n){const{render:r,className:s,orientation:i="vertical",keepMounted:o=!1,style:l,...c}=t,{hovering:u,scrollingX:d,scrollingY:f,hiddenState:h,scrollbarYRef:p,scrollbarXRef:m,viewportRef:v,thumbYRef:y,thumbXRef:x,handlePointerDown:b,handlePointerUp:S,handleScroll:k,disableViewportSnap:j,rootId:C,thumbSize:T,hasMeasuredScrollbar:_,viewportState:N}=hL(),I=i==="vertical",P={...N,hovering:u,scrolling:I?f:d,orientation:i},A=vx(),D=!_&&!o,z=I?h.y:h.x,Q=o||!z;g.useEffect(()=>{if(!Q)return;const V=v.current,H=I?p.current:m.current;if(!H)return;function M(G){if(!V||G.ctrlKey)return;const L=!I,$=L?"scrollLeft":"scrollTop",F=L?G.deltaX:G.deltaY;if(F===0)return;const U=L?V.scrollWidth-V.clientWidth:V.scrollHeight-V.clientHeight,K=L&&A==="rtl"?-U:0,ne=L&&A==="rtl"?0:U,X=V[$];X<=K&&F<0||X>=ne&&F>0||(G.preventDefault(),V[$]=Math.min(ne,Math.max(K,X+F)),k({x:V.scrollLeft,y:V.scrollTop}))}return Br(H,"wheel",M,{passive:!1})},[A,k,I,m,p,Q,v]);const q={...C&&{"data-id":`${C}-scrollbar`},onPointerDown(V){if(V.button!==0)return;const H=Ui(V.nativeEvent),M=I?y.current:x.current;if(M&&ln(M,H))return;const G=v.current;if(!G)return;const L=I?p.current:m.current;if(!M||!L)return;const $=I?"y":"x",F=u1(M,"margin",$),U=u1(L,"padding",$),K=I?M.offsetHeight:M.offsetWidth,ne=L.getBoundingClientRect(),X=I?V.clientY-ne.top-K/2-U+F/2:V.clientX-ne.left-K/2-U+F/2,te=I?G.scrollHeight:G.scrollWidth,oe=I?G.clientHeight:G.clientWidth,ee=(I?L.offsetHeight:L.offsetWidth)-K-U-F;if(ee<=0)return;const se=X/ee,re=te-oe;j(),I?G.scrollTop=se*re:A==="rtl"?G.scrollLeft=-(1-se)*re:G.scrollLeft=se*re,k({x:G.scrollLeft,y:G.scrollTop}),b(V)},onPointerUp:S,onPointerCancel:S,style:{position:"absolute",touchAction:"none",WebkitUserSelect:"none",userSelect:"none",visibility:D?"hidden":void 0,...I?{top:0,bottom:"var(--scroll-area-corner-height)",insetInlineEnd:0,"--scroll-area-thumb-height":`${T.height}px`}:{insetInlineStart:0,insetInlineEnd:"var(--scroll-area-corner-width)",bottom:0,"--scroll-area-thumb-width":`${T.width}px`}}},B=pn("div",t,{ref:[n,I?p:m],state:P,props:[q,c],stateAttributesMapping:vG});return Q?a.jsx(Cwt.Provider,{value:i,children:B}):null}),Snr=g.forwardRef(function(t,n){const{render:r,className:s,style:i,...o}=t,{computeThumbPosition:l}=gnr(),{hasMeasuredScrollbar:c,viewportState:u}=hL(),d=g.useRef(null),f=g.useRef(c);return Tt(()=>{if(typeof ResizeObserver>"u")return;let p=!1;const m=new ResizeObserver(()=>{!p&&(p=!0,!f.current)||l()});return d.current&&m.observe(d.current),()=>{m.disconnect()}},[l]),pn("div",t,{ref:[n,d],state:u,stateAttributesMapping:vG,props:[{role:"presentation",style:{minWidth:"fit-content"}},o]})}),knr=g.forwardRef(function(t,n){const{render:r,className:s,style:i,...o}=t,{thumbYRef:l,thumbXRef:c,handlePointerDown:u,handlePointerMove:d,handlePointerUp:f,scrollingX:h,scrollingY:p,hasMeasuredScrollbar:m}=hL(),v=bnr(),y=v==="vertical";return pn("div",t,{ref:[n,y?l:c],state:{scrolling:y?p:h,orientation:v},props:[{onPointerDown:u,onPointerMove:d,onPointerUp:f,onPointerCancel:f,style:{visibility:m?void 0:"hidden",...y?{height:"var(--scroll-area-thumb-height)"}:{width:"var(--scroll-area-thumb-width)"}}},o]})}),Onr=g.forwardRef(function(t,n){const{render:r,className:s,style:i,...o}=t,{cornerRef:l,cornerSize:c,hiddenState:u}=hL(),d=pn("div",t,{ref:[n,l],props:[{style:{position:"absolute",bottom:0,insetInlineEnd:0,width:c.width,height:c.height}},o]});return u.corner?null:d}),jnr=8,_wt=(e,{enabled:t=!0})=>{const n=g.useRef(t),r=g.useRef(null),s=g.useRef(!1),i=g.useRef(null);Re.useEffect(()=>{if(!t||!e?.current)return;const o=e.current,l=()=>{n.current&&(r.current!==null&&cancelAnimationFrame(r.current),r.current=requestAnimationFrame(()=>{n.current&&(o.scrollTop=o.scrollHeight),r.current=null}))},c=new MutationObserver(l);c.observe(o,{childList:!0,subtree:!0,characterData:!0});const u=new ResizeObserver(l);u.observe(o);const d=()=>{r.current!==null&&(cancelAnimationFrame(r.current),r.current=null)},f=()=>{n.current=!1,d()},h=()=>{s.current=!0,i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{s.current=!1,i.current=null},250)},p=y=>{h(),y.deltaY<0&&f()},m=y=>{h(),["ArrowUp","PageUp","Home"].includes(y.key)&&f()},v=y=>{const x=y.target,b=x.scrollTop+x.clientHeight,S=x.scrollHeight;if(b>=S-jnr){n.current=!0;return}s.current&&(n.current=!1,d())};return o.addEventListener("wheel",p,{passive:!0}),o.addEventListener("touchmove",h,{passive:!0}),o.addEventListener("pointerdown",h),o.addEventListener("keydown",m),o.addEventListener("scroll",v),l(),()=>{o.removeEventListener("wheel",p),o.removeEventListener("touchmove",h),o.removeEventListener("pointerdown",h),o.removeEventListener("keydown",m),o.removeEventListener("scroll",v),c.disconnect(),u.disconnect(),d(),i.current!==null&&(window.clearTimeout(i.current),i.current=null)}},[t,e])},Cnr=100,_nr=20,Tnr=1,Enr=16,Phe="2rem",D8="0px",Inr=["mask-t-from-[calc(100%-min(var(--scroll-area-fade-top),var(--scroll-area-overflow-y-start,0px)))]","mask-b-from-[calc(100%-min(var(--scroll-area-fade-bottom),var(--scroll-area-overflow-y-end,0px)))]","mask-l-from-[calc(100%-min(var(--scroll-area-fade-left),var(--scroll-area-overflow-x-start,0px)))]","mask-r-from-[calc(100%-min(var(--scroll-area-fade-right),var(--scroll-area-overflow-x-end,0px)))]"].join(" "),Ew=e=>e===!0?Phe:e;function Nnr(e,t){if(e===!1)return{top:!1,bottom:!1,left:!1,right:!1};const n=(t==="vertical"||t==="both")&&Phe,r=(t==="horizontal"||t==="both")&&Phe,s={top:n,bottom:n,left:r,right:r};return e===!0||e===void 0||(e.y!==void 0&&(s.top=Ew(e.y),s.bottom=Ew(e.y)),e.x!==void 0&&(s.left=Ew(e.x),s.right=Ew(e.x)),e.top!==void 0&&(s.top=Ew(e.top)),e.bottom!==void 0&&(s.bottom=Ew(e.bottom)),e.left!==void 0&&(s.left=Ew(e.left)),e.right!==void 0&&(s.right=Ew(e.right))),s}const Anr=e=>({"--scroll-area-fade-top":e.top||D8,"--scroll-area-fade-bottom":e.bottom||D8,"--scroll-area-fade-left":e.left||D8,"--scroll-area-fade-right":e.right||D8});function b7e(e,t,n){const r=e??t;return Number.isFinite(r)?Math.max(n,r):Math.max(n,t)}const w7e=({direction:e,label:t,onStartScrolling:n,onStopScrolling:r,onKeyboardScroll:s})=>{const i=e==="left"?$A:Gs;return a.jsx("button",{type:"button","aria-label":t,className:Z("absolute inset-y-1 z-10 hidden w-8 cursor-pointer items-center justify-center rounded-md border-0 bg-transparent hover:bg-fill-subtle active:bg-fill",Fn,On,$i,e==="left"?"left-1 group-data-[overflow-x-start]/scroll-area:flex":"right-1 group-data-[overflow-x-end]/scroll-area:flex"),onPointerDown:o=>n(e,o),onPointerUp:r,onPointerLeave:r,onPointerCancel:r,onBlur:r,onClick:o=>{o.detail===0&&s(e)},children:a.jsx(i,{"aria-hidden":"true",className:"size-4"})})},Pnr=({areaRef:e,scrollButtons:t})=>{const n=g.useRef(null),r=typeof t=="object"?t:void 0,s=b7e(r?.scrollSpeed,Cnr,Tnr),i=b7e(r?.scrollIntervalTime,_nr,Enr),o=r?.leftLabel??"Scroll left",l=r?.rightLabel??"Scroll right",c=g.useCallback(()=>{n.current&&(clearInterval(n.current),n.current=null)},[]),u=g.useCallback((f,h=1)=>{const p=e.current;p&&p.scrollBy({left:f==="right"?s*h:-s*h,behavior:"smooth"})},[e,s]),d=g.useCallback((f,h)=>{h?.preventDefault(),h?.stopPropagation(),h?.currentTarget.setPointerCapture?.(h.pointerId),c(),u(f,2),n.current=setInterval(()=>{u(f)},i)},[i,u,c]);return g.useEffect(()=>()=>{c()},[c]),a.jsxs(a.Fragment,{children:[a.jsx(w7e,{direction:"left",label:o,onStartScrolling:d,onStopScrolling:c,onKeyboardScroll:f=>u(f,2)}),a.jsx(w7e,{direction:"right",label:l,onStartScrolling:d,onStopScrolling:c,onKeyboardScroll:f=>u(f,2)})]})},Z1e=g.createContext(null);function $nr(){const e=g.use(Z1e);if(!e)throw new Error("ScrollAreaViewport must be a direct child of ScrollArea");return e}function sf({className:e,children:t,ref:n}){const r=$nr(),{areaRef:s}=r,i=g.useMemo(()=>KS(s,n),[s,n]);return a.jsx(ynr,{ref:i,className:Z(r.className,e),style:r.style,children:a.jsx(Snr,{style:r.contentStyle,children:a.jsx(Z1e,{value:null,children:t})})})}function Nr({className:e,children:t,maxHeight:n,autoScroll:r=!1,orientation:s="vertical",scrollButtons:i,mask:o,revealScrollbarOnHover:l=!0,...c}){const u=g.useRef(null);_wt(u,{enabled:r});const d=Nnr(o,s),f=Object.values(d).some(Boolean),h=Anr(d);n&&(h.maxHeight=n),s==="vertical"?(h.overflowX="hidden",h.overflowY="scroll"):s==="horizontal"&&(h.overflowX="scroll",h.overflowY="hidden");const p=s==="vertical"?{minWidth:"0px"}:s==="horizontal"?{minHeight:"0px"}:void 0,m={areaRef:u,className:Z("size-full",f&&Inr),style:h,contentStyle:p},v=g.Children.toArray(t).filter(x=>g.isValidElement(x)&&x.type===sf).length;if(v>1)throw new Error("ScrollArea takes at most one ScrollAreaViewport");const y=v===1;return a.jsxs(pnr,{className:Z("group/scroll-area relative overflow-hidden",e),...c,children:[a.jsx(Z1e,{value:m,children:y?t:a.jsx(sf,{children:t})}),i&&s!=="vertical"&&a.jsx(Pnr,{areaRef:u,scrollButtons:i}),(s==="vertical"||s==="both")&&a.jsx(S7e,{orientation:"vertical",revealOnHover:l}),(s==="horizontal"||s==="both")&&a.jsx(S7e,{orientation:"horizontal",revealOnHover:l}),s==="both"&&a.jsx(Onr,{})]})}function S7e({className:e,orientation:t="vertical",revealOnHover:n=!0,...r}){return a.jsx(wnr,{"data-slot":"scroll-area-scrollbar",orientation:t,className:Z("flex touch-none transition-opacity duration-normal ease-out-custom select-none","opacity-0 data-[scrolling]:opacity-100 data-[scrolling]:duration-0",n&&"data-[hovering]:opacity-100",t==="vertical"&&"h-full w-1.5 p-px",t==="horizontal"&&"h-1.5 w-full flex-col p-px",e),...r,children:a.jsx(knr,{className:"relative flex-1 rounded-full bg-muted-foreground/30 hover:bg-muted-foreground/60"})})}function eP({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 Twt({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(Ql),[C,T]=g.useState(!1),_=g.useRef(null),N=g.useRef(null),[I,P]=g.useState(),[A,D]=eP({initialKey:`workflow-run-resource-id:${e}`,defaultValue:"",schema:vt()}),z=t||S,Q=I?.runId===z?I:void 0,q=z?m:null,B=Kpt(q,z),{zodSchemaToUse:V,hasStateSchema:H}=I6n(r),M=SH(q?.status),G=q?.status==="paused";g.useEffect(()=>()=>_.current?.abort(),[]);const L=async oe=>{if(!r||C)return;_.current?.abort();const ue=new AbortController;_.current=ue,T(!0);try{P(void 0),v(null);const ee=A.trim()||void 0,se=await i({workflowId:e,resourceId:ee});if(ue.signal.aborted)return;b(se.runId),T(!1);const{initialState:re,inputData:ae}=oe??{},pe=H?ae:oe;await o({workflowId:e,runId:se.runId,inputData:pe,initialState:re,requestContext:f,resourceId:ee})}catch(ee){ue.signal.aborted||Ge.error(ee instanceof Error?ee.message:"Error executing workflow")}finally{ue.signal.aborted||T(!1)}},$=async()=>{if(!z)return;const oe=m?.status==="paused"||m?.status==="suspended"?m:void 0;try{const ue=await d({workflowId:e,runId:z});P({...ue,runId:z}),oe&&v({...oe,status:"canceled"})}catch{Ge.error("Error cancelling workflow run")}};if(g.useEffect(()=>{if(!t||!l)return;const oe=`${e}:${t}`;N.current!==oe&&(N.current=oe,l({workflowId:e,runId:t}))},[t,l,e]),s)return a.jsx(Nr,{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 F=B.length>0,U=q?.status==="running"||q?.status==="suspended",K=!!z,ne=q?.status??n??(c?"running":"pending"),X=a.jsx($6n,{status:q?.status,cancelMessage:Q?.message??null,isCancelling:u,onCancel:$,disabled:!p}),te=K?a.jsx(EGn,{runId:z,status:ne,result:q,timestamp:k?.timestamp,resourceId:Pft(k)}):a.jsx(cnr,{workflow:r,workflowId:e});return a.jsx("div",{className:"pt-3",children:a.jsxs("div",{children:[F&&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(Nt,{children:a.jsx(dc,{className:"animate-spin text-foreground"})}),a.jsx(Y,{children:"Resuming workflow"})]}),p&&a.jsx(lnr,{zodSchema:V,defaultValues:y,isStreaming:C||c,onExecute:oe=>{x(oe),L(oe)},isViewingRun:K,isProcessorWorkflow:r?.isProcessorWorkflow,collapsible:!1,headingSlot:te,leftActions:t?void 0:a.jsx(ezn,{}),submitButtonLabel:C?"Starting…":"Run",submitActions:h?.({resourceId:A,setResourceId:D})},`${e}:${z||"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(fGn,{result:q,workflowError:j,className:"mx-5 mb-4"}),G&&p&&a.jsx("div",{className:"px-5 pt-3 pb-4",children:a.jsx(izn,{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(oGn,{input:y,result:q},z)]})})}const Rnr=({workflowId:e,runId:t,observeWorkflowStream:n,...r})=>{const{runSnapshot:s,isLoadingRunExecutionResult:i}=g.useContext(Ql),o=g.useCallback(()=>{!t||!s||SH(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(Twt,{...r,paramsRunId:t,paramsRunStatus:s.status,workflowId:e,observeWorkflowStream:o},`${e}:${t}`)};function Mnr({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=WC(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=Ui(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 pbt(r&&i===!0,o),e.useContextCallback("onNestedDialogOpen",(m,v)=>{u(m),f(v)}),Tt(()=>(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]),w3(e,{activeTriggerProps:p.reference,inactiveTriggerProps:p.trigger,popupProps:p.floating,nestedOpenDialogCount:c,nestedOpenDrawerCount:d}),null}const Ewt=g.createContext(void 0);function hf(e){const t=g.useContext(Ewt);if(!e&&t===void 0)throw new Error(Pr(27));return t}const Dnr={...k3,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 Lnr extends HC{constructor(t,n,r){const s=new GC,i=znr(t,s,n,r);super(i,Fnr(s),Dnr)}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};WW(r,t,n.trigger),this.update(r)}}function znr(e,t,n,r=!1){const s={...S3(),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=HW(t,n,r),s}function Fnr(e){return{popupRef:g.createRef(),backdropRef:g.createRef(),internalBackdropRef:g.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:e,onOpenChange:void 0,onOpenChangeComplete:void 0}}function W1e(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=ZW((P,A)=>new Lnr({open:s,openProp:r,activeTriggerId:h,triggerIdProp:f,...k},P,A),!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");_ut(j,C),x3(j);const{forceUnmount:N}=b3(C,j);g.useImperativeHandle(u,()=>({unmount:N,close:()=>j.setOpen(!1,Yt(p3))}),[N,j]);const I=C||T;return a.jsxs(Ewt.Provider,{value:j,children:[d&&a.jsx(v3,{handle:d,store:j}),I&&a.jsx(Mnr,{store:j,parentContext:b?.context,isDrawer:p}),typeof n=="function"?n({payload:_}):n]})}function Bnr(e){return W1e("alert-dialog",e)}const Vnr=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 pn("div",t,{state:{open:u,transitionStatus:h},ref:[c.context.backdropRef,n],stateAttributesMapping:YC,props:[{role:"presentation",hidden:!f,style:{userSelect:"none",WebkitUserSelect:"none"}},l],enabled:o||!d})}),yG=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}=ud({disabled:o,native:l}),p={disabled:o};function m(v){d&&u.setOpen(!1,Yt(ibe,v.nativeEvent))}return pn("button",t,{state:p,ref:[n,h],props:[{onClick:m},c,f]})}),Iwt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,id:o,...l}=t,c=hf(),u=Qi(o);return c.useSyncedValueWithCleanup("descriptionElementId",u),pn("p",t,{ref:n,props:[{id:u},l]})}),Nwt=g.createContext(void 0);function H1e(){const e=g.useContext(Nwt);if(e===void 0)throw new Error(Pr(26));return e}const Awt={...KC,...gp,nestedDialogOpen(e){return e?{"data-nested-dialog-open":""}:null}},Pwt=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");H1e(),ql({open:b,ref:u.context.popupRef,onComplete(){b&&u.context.onOpenChangeComplete?.(!0)}});const _=l===void 0?Out(u.context.popupRef):l,N=x>0,I=u.useStateSetter("popupElement"),A=pn("div",t,{state:{open:b,nested:y,transitionStatus:j,nestedDialogOpen:N},props:[p,{id:T,"aria-labelledby":k,"aria-describedby":d,role:C,...ZS,hidden:!v,onKeyDown(D){ek.has(D.key)&&D.stopPropagation()},style:{"--nested-dialogs":x}},c],ref:[n,u.context.popupRef,I],stateAttributesMapping:Awt});return a.jsx(_A,{context:h,openInteractionType:S,disabled:!v,closeOnFocusOut:!f,initialFocus:_,returnFocus:o,modal:m!==!1,restoreFocus:"popup",children:A})}),$wt=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(Nwt.Provider,{value:r,children:a.jsxs(g3,{ref:n,...s,children:[o&&l===!0&&a.jsx(sL,{ref:i.context.internalBackdropRef,inert:NA(!c)}),t.children]})}):null}),Rwt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,id:o,...l}=t,c=hf(),u=Qi(o);return c.useSyncedValueWithCleanup("titleElementId",u),pn("h2",t,{ref:n,props:[{id:u},l]})}),G1e=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=O3(d)??h;if(!m)throw new Error(Pr(79));const v=Qi(c),y=m.useState("floatingRootContext"),x=m.useState("isOpenedByTrigger",v),b=m.useState("triggerPopupId",v),S=g.useRef(null),{registerTrigger:k,isMountedByThisTrigger:j}=y3(v,S,m,{payload:u}),{getButtonProps:C,buttonRef:T}=ud({disabled:o,native:l}),_=ZC(y),N=Xwe(()=>m.select("open"),A=>{m.set("openMethod",A)}),I={disabled:o,open:x},P=m.useState("triggerProps",j);return pn("button",t,{state:I,ref:[T,n,k,S],props:[_.reference,P,N,{[fbe]:"",id:v,"aria-haspopup":"dialog","aria-expanded":x,"aria-controls":b},f,C],stateAttributesMapping:TA})}),Unr=G1e,qnr=g.forwardRef(function(t,n){const{render:r,className:s,style:i,children:o,...l}=t,c=H1e(),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 pn("div",t,{enabled:c||m,state:{open:d,nested:f,transitionStatus:h,nestedDialogOpen:y},ref:[n,v],stateAttributesMapping:Awt,props:[{role:"presentation",hidden:!m,style:{pointerEvents:d?void 0:"none"},children:o},l]})});function Qnr(e){return W1e("dialog",e)}const K1e=g.createContext({intent:"default",pending:!1});function xG(){return g.useContext(K1e)}const bG={sm:"min-h-control-sm",md:"min-h-control-md",lg:"min-h-control-lg"},wG="h-auto min-w-0 max-w-full whitespace-normal wrap-anywhere max-[22rem]:w-full",Mwt=["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","[&>form]:flex [&>form]:min-h-0 [&>form]:flex-1 [&>form]:flex-col [&>form]:gap-0",zut].join(" "),Dwt={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)]"};function rs({intent:e="default",pending:t=!1,onOpenChange:n,disablePointerDismissal:r,...s}){return a.jsx(K1e.Provider,{value:{intent:e,pending:t},children:a.jsx(Qnr,{...s,disablePointerDismissal:r??e==="destructive",onOpenChange:(i,o)=>{if(!i&&t){o.cancel();return}n?.(i,o)}})})}const Lwt=G1e,zwt=$wt;function Fwt({className:e,...t}){return a.jsx(Vnr,{"data-slot":"dialog-overlay",className:Z("dialog-backdrop-motion fixed inset-0 z-50 bg-scrim backdrop-blur-xs",e),...t})}function ss({className:e,children:t,size:n="md",showOverlay:r=!0,showCloseButton:s=!0,overlayClassName:i,initialFocus:o,...l}){const{intent:c,pending:u}=xG(),d=g.useRef(null),f=c==="destructive";return a.jsxs(zwt,{children:[r&&a.jsx(Fwt,{className:i}),a.jsxs(Pwt,{"data-slot":"dialog-content","data-size":n,"data-intent":c,role:f?"alertdialog":"dialog",initialFocus:o??(f&&s?d:!0),"aria-busy":u||void 0,className:Z(Mwt,Dwt[n],"[&_[data-slot=dialog-header]]:pr-12",e),...l,children:[t,s&&a.jsx(yG,{ref:d,disabled:u,"data-slot":"dialog-close",className:"absolute top-4 right-4",render:a.jsx(de,{variant:"ghost",size:"icon-sm","aria-label":"Close",children:a.jsx(Ln,{})})})]})]})}function es({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 Ho({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 Gr({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(Nr,{className:"flex min-h-0 min-w-0 flex-1 flex-col",mask:!0,children:a.jsx(sf,{className:"h-auto min-h-0",children:a.jsx("div",{"data-slot":"dialog-body",className:i,...s,children:r})})})}function Kr({className:e,...t}){return a.jsx(Rwt,{className:Z("text-heading wrap-break-word text-foreground",e),...t})}function Mo({className:e,...t}){return a.jsx(Iwt,{className:Z("text-body wrap-break-word text-muted-foreground",e),...t})}function ja({disabled:e,size:t="md",...n}){const{pending:r}=xG();return a.jsx(yG,{render:a.jsx(de,{size:t,variant:"ghost",className:Z(wG,bG[t]),children:n.children}),...n,disabled:e||r})}const Znr={intent:"default",pending:!1};function Ut(e){return a.jsx(K1e.Provider,{value:Znr,children:a.jsx(Bnr,{...e})})}function Wnr({className:e,size:t="sm",...n}){return a.jsxs(zwt,{children:[a.jsx(Fwt,{}),a.jsx(Pwt,{"data-slot":"alert-dialog-content","data-size":t,className:Z(Mwt,Dwt[t],e),...n})]})}function Hnr({children:e,...t}){return a.jsx(yG,{render:a.jsx(de,{variant:"primary",size:"md",className:Z(wG,bG.md),children:e}),...t})}Ut.Trigger=Unr;Ut.Content=Wnr;Ut.Header=es;Ut.Footer=Ho;Ut.Body=Gr;Ut.Title=Kr;Ut.Description=Mo;Ut.Action=Hnr;Ut.Cancel=ja;const Bwt=({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(hr,"rounded-studio-panel")),children:e})}),Gnr=({render:e,children:t})=>a.jsx(de,{render:e,variant:"ghost",className:"w-full justify-start rounded-xl px-3",children:t}),Knr=()=>a.jsx("div",{role:"separator","aria-orientation":"horizontal",className:"-mx-1 h-px shrink-0 bg-border/40"}),$he=({children:e})=>a.jsx("ol",{className:"flex flex-col gap-1","data-testid":"thread-list",children:e}),Rhe=({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(de,{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(de,{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(Ln,{})}),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})]}),Vwt=({children:e})=>a.jsx(Y,{as:"p",variant:"caption",tone:"muted",className:"px-3 py-2",children:e}),Ynr=vr({status:Gm(["running","failed","canceled","pending","waiting","paused","suspended","success"]),timestamp:nc().optional()}),Xnr=vr({output:i4()});function Jnr(e){const t=Ynr.safeParse(e);return t.success?t.data:void 0}function err(e){if(e==null)return null;const t=Cn().safeParse(e);if(t.success)return t.data;const n=Xnr.safeParse(e),r=n.success?n.data.output:e;try{return JSON.stringify(r)}catch{return null}}function trr({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:is(e,"date-time")}),t&&a.jsx("span",{className:"min-w-0 truncate",title:`Resource ${t}`,children:e===void 0?t:`· ${t}`})]})}const nrr=({workflowId:e,runId:t,canDelete:n})=>{const[r,s]=g.useState(!0),[i,o]=g.useState(null),{Link:l,paths:c,navigate:u}=hn(),{isLoading:d,error:f,data:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v}=o$n({workflowId:e,summary:!0}),{data:y}=Ift({workflowId:e,runId:t??"",queryOptions:{enabled:!!(e&&t)}}),x=err(y?.payload),{mutateAsync:b}=a$n({workflowId:e}),S=async j=>{try{await b({runId:j}),Ge.success("Workflow run deleted successfully"),o(null),u(c.workflowLink(e))}catch{Ge.error("Failed to delete workflow run"),o(null)}},k=h||[];return a.jsxs(a.Fragment,{children:[a.jsxs(Wl,{open:r,onOpenChange:s,className:"flex min-h-0 flex-col",children:[a.jsxs(wl,{className:"flex shrink-0 items-center gap-2 px-4 py-3 text-left text-caption text-muted-foreground",children:[a.jsx(Gs,{"aria-hidden":!0,className:"size-4 shrink-0 text-muted-foreground motion-reduce:transition-none"}),a.jsx("span",{children:"Recent runs"}),!d&&!f&&a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",children:[k.length,v?"+":""]})]}),a.jsx(Sl,{keepMounted:!0,fill:!0,className:"flex min-h-0 flex-col",children:a.jsx(Nr,{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(Bwt,{"aria-label":"Workflow runs",embedded:!0,children:k.length===0?a.jsx(Vwt,{children:f?"Unable to load workflow runs.":"Your run history will appear here once you run the workflow"}):a.jsxs($he,{children:[k.map(j=>{const C=j.runId===t,T=Jnr(j.snapshot),_=C?x:null;return a.jsx(Rhe,{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(Kbt,{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(trr,{timestamp:$de(T?.timestamp),resourceId:Pft(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(Nt,{children:a.jsx(An,{})})}),a.jsx("li",{children:a.jsx("div",{ref:p})})]})})})})]}),a.jsx(rrr,{open:!!i,onOpenChange:()=>o(null),onDelete:()=>{i&&S(i)}})]})},rrr=({open:e,onOpenChange:t,onDelete:n})=>a.jsx(Ut,{open:e,onOpenChange:t,children:a.jsxs(Ut.Content,{children:[a.jsxs(Ut.Header,{children:[a.jsx(Ut.Title,{children:"Are you absolutely sure?"}),a.jsx(Ut.Description,{children:"This action cannot be undone. This will permanently delete the workflow run and remove it from our servers."})]}),a.jsxs(Ut.Footer,{children:[a.jsx(Ut.Cancel,{children:"Cancel"}),a.jsx(Ut.Action,{onClick:n,children:"Continue"})]})]})}),Uwt=g.createContext(0);function L8(e,t=!1){return{maxZoom:1,padding:t?"20px":{left:`${e+40}px`,right:"40px",top:"40px",bottom:"64px"}}}const srr=dd("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"}}),Y1e=({variant:e,className:t})=>a.jsx("span",{"aria-hidden":!0,className:Z(srr({variant:e}),t)}),tP=(e=1024)=>{const t=g.useMemo(()=>`(max-width: ${e-1}px)`,[e]),[n,r]=g.useState(!1);return g.useLayoutEffect(()=>{const s=window.matchMedia(t),i=()=>r(s.matches);return i(),s.addEventListener("change",i),()=>s.removeEventListener("change",i)},[t]),n},X1e=380,irr="workflow-canvas-left-panel-width",orr=8,k7e=16,J1e=`${hr} rounded-studio-panel`,qwt=g.createContext(void 0);function Tie(e,t){return Math.max(X1e,Math.min(e,t))}function arr(){const e=g.useContext(qwt);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"?k7e:-k7e))};return a.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panel","aria-valuenow":e.width,"aria-valuemin":X1e,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(Y1e,{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 lrr=({children:e,leftSlot:t})=>{const n=tP(),r=g.useRef(null),[s,i]=eP({initialKey:irr,defaultValue:X1e,schema:Ss()}),[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=Tie(s,o),u=p=>{const m=r.current;m&&i(Tie(p-m.getBoundingClientRect().left,o))},d=p=>i(Tie(c+p,o)),f=t?c-orr: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(Uwt,{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(qwt,{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})})]})},Qwt=Z(J1e,"pointer-events-auto");function Zwt({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(arr,{})]})}function crr({workflowId:e,onClick:t}){const{Link:n,paths:r}=hn();return a.jsx(de,{render:a.jsx(n,{href:`${r.workflowLink(e)}/graph`}),variant:"ghost",size:"icon-md",tooltip:"New workflow run",onClick:t,children:a.jsx(bs,{})})}function urr({children:e,workflowId:t,showNewRunButton:n,onNewRun:r}){const{result:s}=g.useContext(Ql),[i,o]=g.useState(!0);return a.jsx(Zwt,{className:"max-h-[75%] flex-initial",children:a.jsxs(Wl,{render:a.jsx("section",{}),open:i,onOpenChange:o,"data-testid":"workflow-information-top-section",className:Z(Qwt,"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(wl,{className:"flex min-w-0 flex-1 items-center gap-2 px-4 py-3 text-column text-muted-foreground",children:[a.jsx(Gs,{"aria-hidden":!0,className:"size-4 shrink-0 text-muted-foreground motion-reduce:transition-none"}),a.jsx("span",{children:"Workflow run"}),!i&&s?.status&&a.jsx(Xbt,{status:s.status})]}),n&&a.jsx(crr,{workflowId:t,onClick:()=>{o(!0),r()}})]}),a.jsx(Sl,{keepMounted:!0,fill:!0,className:"flex min-h-0 flex-col",children:a.jsx(Nr,{"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(sf,{className:"h-full",children:e})})})]})})}function drr(e){return a.jsx(Twt,{...e})}function frr({runId:e,observeWorkflowStream:t,...n}){return a.jsx(Rnr,{...n,runId:e,observeWorkflowStream:t})}function hrr({workflowId:e,activeRunId:t,canDelete:n}){return a.jsx(Zwt,{className:"mt-auto max-h-[min(35%,280px)] shrink-0",children:a.jsx("section",{className:Z(Qwt,"flex min-h-0 min-w-0 flex-col overflow-hidden"),children:a.jsx(nrr,{workflowId:e,runId:t,canDelete:n})})})}function prr({workflowId:e,initialRunId:t,requestContext:n,runActionsSlot:r,canExecute:s,canDelete:i}){const{data:o,isLoading:l,error:c}=L3({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(Ql),{setSelectedStepId:b}=wH(),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";Ge.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(urr,{workflowId:e,showNewRunButton:!!S,onNewRun:j,children:t?a.jsx(frr,{...k,runId:t,observeWorkflowStream:h}):a.jsx(drr,{...k})}),a.jsx(hrr,{workflowId:e,activeRunId:S,canDelete:i})]})}function eSe(e,t){return Tft(`mastra-tracing-options:${e}:${t}`)}const O7e={runId:"",payload:null,override:null};function mrr(e){const[t,n]=g.useState(O7e),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(O7e),[]);return{runId:r,payload:t.payload,override:s,setRunId:i,setPayload:o,setResult:l,dropOverride:c,reset:u}}const grr=5e3,vrr=e=>SH(e.state.data?.status)?!1:grr;function yrr(e){return{...e,timestamp:$de(e.updatedAt)??$de(e.createdAt)}}function xrr(e,t,{poll:n}){const{data:r,isLoading:s}=Ift({workflowId:e,runId:t,queryOptions:{enabled:!!(e&&t),refetchInterval:n?vrr:void 0}});return{persistedRun:g.useMemo(()=>r&&yrr(r),[r]),isLoading:s}}function brr({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}=evn({debugMode:t,tracingOptions:n,onError:b=>Ge.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 tSe=g.createContext(null);function rk(){const e=g.useContext(tSe);if(!e)throw new Error("useWorkflowStepDetail must be used within WorkflowStepDetailProvider");return e}const wrr={};function Srr({children:e,snapshot:t,workflowId:n,initialRunId:r,withoutTimeTravel:s=!1,requestContext:i=wrr,tracingOptions:o}){const l=g.useContext(tSe)?.resetStepDetail,[c,u]=g.useState(!1),{data:d,isLoading:f,error:h}=L3({workflowId:n,requestContext:i,queryOptions:{enabled:!!n}}),p=yr(),m=tvn(),v=nvn(),{runId:y,payload:x,override:b,setRunId:S,setPayload:k,setResult:j,dropOverride:C,reset:T}=mrr(r),{result:_,isOpen:N,isObserving:I,select:P,close:A,streamWorkflow:D,resumeWorkflowStream:z,observeWorkflowStream:Q,timeTravelWorkflowStream:q}=brr({runId:y,debugMode:c,tracingOptions:o}),B=b??_,V=!r&&SH(B?.status),H=r||(V?y:""),{persistedRun:M,isLoading:G}=xrr(n,H,{poll:!N}),L=M??t,$=g.useMemo(()=>L?w$n(L):null,[L]),F=g.useMemo(()=>k$n(B,$),[B,$]),U=r?L:void 0,K=I&&C$n(F?.status),ne=N&&!K,X=g.useMemo(()=>U?j$n(U,$?.input):x,[U,$,x]),te=g.useCallback(he=>{l?.(),S(he)},[l,S]),oe=g.useCallback(()=>{l?.(),A(),T()},[l,A,T]);g.useEffect(()=>oe,[n,r,oe]);const ue=g.useCallback((he,Oe)=>{P(he,Oe),C(he)},[P,C]),ee=g.useCallback((he,Oe)=>p.invalidateQueries({queryKey:Eft(he,Oe),exact:!0}),[p]),se=g.useCallback(async he=>{ue(he.runId),await D(he)},[ue,D]),re=g.useCallback(async he=>{ue(he.runId);try{await z(he)}finally{await ee(he.workflowId,he.runId)}},[ee,ue,z]),ae=g.useCallback(he=>{if(he.storedStatus==="suspended"){A();return}ue(he.runId,"observe"),Q({workflowId:he.workflowId,runId:he.runId,storeRunResult:null})},[A,ue,Q]),pe=g.useCallback(async he=>{ue(he.runId);try{await q(he)}finally{await ee(he.workflowId,he.runId)}},[ee,ue,q]),ve=g.useMemo(()=>({workflowId:n,workflow:d??void 0,workflowError:h??null,isLoading:f,runId:y,setRunId:te,result:F,setResult:j,streamResult:_,payload:X,setPayload:k,clearData:oe,snapshot:t,runSnapshot:U,isLoadingRunExecutionResult:G,isStreamingWorkflow:ne,isCancellingWorkflowRun:v.isPending,createWorkflowRun:m.mutateAsync,streamWorkflow:se,resumeWorkflow:re,observeWorkflowStream:ae,timeTravelWorkflowStream:pe,cancelWorkflowRun:v.mutateAsync,closeStreamsAndReset:A,withoutTimeTravel:s,debugMode:c,setDebugMode:u}),[n,d,h,f,y,te,F,j,_,X,k,oe,t,U,G,ne,v.isPending,m.mutateAsync,se,re,ae,pe,v.mutateAsync,A,s,c]);return a.jsx(Ql.Provider,{value:ve,children:e})}function nSe(e){return a.jsx(Srr,{...e,requestContext:wr("workflow",e.workflowId)[0],tracingOptions:eSe("workflow",e.workflowId)[0]})}function Wwt({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(Nft.Provider,{value:i,children:e})}function Hwt({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(tSe.Provider,{value:u,children:e})}const krr=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"})}),rSe=({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})}),Ox=e=>a.jsx(bt,{className:"h-3 w-24",...e}),H4=({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]",Xg.sm,On,n?"max-w-xs cursor-default text-foreground":Z(Fn,"max-w-48 cursor-pointer hover:bg-fill-subtle active:bg-fill"),e),...c,children:[i&&a.jsx(Nt,{className:Z("-ml-[.3em] shrink-0 opacity-50 group-hover:opacity-100","transition-opacity duration-normal ease-out-custom"),children:i}),o?a.jsx(Ox,{}):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(Nt,{className:"text-placeholder",children:a.jsx(krr,{})})})]})},l_={variant:"ghost",size:"icon-sm",align:"end"};function Orr(e,t,n,r,s,i,o,l,c,u=2){const d=Cwn(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 O1(n.current,d)?void 0:d}const Gwt=g.createContext(void 0),Kwt=g.createContext(void 0),Ywt=g.createContext(void 0),Xwt=g.createContext(!1),Jwt=g.createContext("");function Jm(){const e=g.useContext(Gwt);if(!e)throw new Error(Pr(22));return e}function SG(){const e=g.useContext(Kwt);if(!e)throw new Error(Pr(23));return e}function pL(){const e=g.useContext(Ywt);if(!e)throw new Error(Pr(24));return e}function e1t(){return g.useContext(Jwt)}function jrr(){return g.useContext(Xwt)}const dn={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?i0t(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=>Lm(t,s,n)):Lm(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 t1t(e){return e==null?void 0:`${e}-popup`}function Crr(e,t){return(n,r)=>n==null?!1:e.contains(n,r,t)}function sSe(e){return Array.isArray(e)?e.map(t=>sSe(t)).join(","):e==null?"":String(e)}const j7e=new Map;function _rr(e={}){const t={usage:"search",sensitivity:"base",ignorePunctuation:!0,...e},n=`${sSe(e.locale)}|${JSON.stringify(t)}`,r=j7e.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=Kp(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=Kp(o,c);return s.compare(u.slice(0,l.length),l)===0},endsWith(o,l,c){if(!l)return!0;const u=Kp(o,c),d=l.length;return u.length>=d&&s.compare(u.slice(u.length-d),l)===0}};return j7e.set(n,i),i}const Trr=_rr;function n1t(e,t=!1){const{overflowY:n}=id(e);return n!=="auto"&&n!=="scroll"?!1:t?e.clientHeight>0:e.scrollHeight>e.clientHeight}function Err(e,t=!1){const{overflowX:n}=id(e);return n!=="auto"&&n!=="scroll"?!1:t?e.clientWidth>0:e.scrollWidth>e.clientWidth}function Mhe(e,t,n=!1){return t==="vertical"?n1t(e,n):Err(e,n)}function Irr(e,t,n){let r=e;for(;si(r)&&r!==t&&!Yg(r);){for(const s of n)if(Mhe(r,s))return!0;r=sv(r)}return!1}function AE(e,t,n="vertical",r=!1){let s=si(e)?e:null;for(;si(s)&&s!==t&&!Yg(s);){if(Mhe(s,n,r))return s;s=sv(s)}return Mhe(t,n,r)?t:null}const r1t=Symbol("none"),Eie={value:r1t,index:-1};function Nrr(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:I=!0,itemToStringLabel:P,itemToStringValue:A,isItemEqualToValue:D=r0t,virtualized:z=!1,inline:Q=!1,fillInputOnItemPress:q=!0,modal:B=!1,limit:V=-1,autoComplete:H="list",formAutoComplete:M,locale:G,submitOnItemClick:L=!1}=e,{clearErrors:$}=wv(),{setDirty:F,validityData:U,setFilled:K,name:ne,disabled:X,setTouched:te,setFocused:oe,validationMode:ue,validation:ee}=_u(),se=vx(),re=YS({id:t}),ae=Trr({locale:G}),[pe,ve]=g.useState(!1),[he,Oe]=g.useState(null),Ee=g.useRef([]),Fe=g.useRef([]),qe=g.useRef(null),Be=g.useRef(null),Pe=g.useRef(null),Ve=g.useRef(null),Ce=g.useRef(null),Te=g.useRef(!0),_e=g.useRef(!1),ce=g.useRef(null),ye=g.useRef(null),Me=g.useRef(null),Ie=g.useRef(Eie),le=g.useRef(null),xe=g.useRef([]),Se=g.useRef(null),$e=X||m,ze=ne??h,He=d==="multiple",De=d==="single",tt=l!==void 0||o!==void 0,Ze=S!==void 0,rt=k!==void 0;let At;T==="always"?At="always":At=T?"input-change":!1;const[me,Le]=Kd({controlled:s,default:He?r??Lf:r,name:"Combobox",state:"selectedValue"}),et=g.useMemo(()=>j===null?()=>!0:j!==void 0?j:Crr(ae,P),[j,ae,P]),Ot=ol(()=>tt?o??"":De?Kp(me,P):"").current,[Bt,Qt]=Kd({controlled:l,default:Ot,name:"Combobox",state:"inputValue"}),[yt,bn]=Kd({controlled:c,default:u,name:"Combobox",state:"open"}),yn=l1e(S),we=he??String(Bt).trim(),Ne=De?Kp(me,P):"",We=De&&!pe&&we!==""&&Ne.length===we.length&&ae.contains(Ne,we),it=We?"":we,ct=Ze&&rt&&We,Ht=g.useMemo(()=>S?yn?S.flatMap(gn=>gn.items):S:Lf,[S,yn]),Vt=g.useMemo(()=>{if(k&&!ct)return k;if(!S)return Lf;if(yn){const Tn=S,Ns=[];let Ti=0;for(const Jo of Tn){if(V>-1&&Ti>=V)break;const Pa=V>-1?V-Ti:1/0,So=it===""?Jo.items.slice(0,Pa):[];if(it!=="")for(const Kl of Jo.items){if(So.length>=Pa)break;et(Kl,it,P)&&So.push(Kl)}if(So.length>0){const Kl={...Jo,items:So};Ns.push(Kl),Ti+=So.length}}return Ns}if(it==="")return V>-1?Ht.slice(0,V):Ht;const gn=[];for(const Tn of Ht){if(V>-1&&gn.length>=V)break;et(Tn,it,P)&&gn.push(Tn)}return gn},[k,ct,S,yn,it,V,et,P,Ht]),_t=g.useMemo(()=>yn?Vt.flatMap(Tn=>Tn.items):Vt,[Vt,yn]),mt=ol(()=>{let gn=null;return Q&&yt&&Ze&&d!=="none"&&(gn=uie(_t,me,D,He)),new Sut({id:re,labelId:void 0,selectedValue:me,open:yt,items:S,selectionMode:d,listRef:Ee,labelsRef:Fe,popupRef:qe,emptyRef:Ce,inputRef:Be,startDismissRef:Pe,endDismissRef:Ve,keyboardActiveRef:Te,chipsContainerRef:ce,clearRef:ye,valuesRef:xe,pointerDownItemRef:Se,selectionEventRef:Me,name:ze,form:p,disabled:$e,readOnly:v,required:y,grid:b,virtualized:z,openOnInputClick:C,itemToStringLabel:P,isItemEqualToValue:D,modal:B,autoHighlight:At,submitOnItemClick:L,hasInputValue:tt,mounted:!1,forceMounted:!1,transitionStatus:"idle",inline:Q,activeIndex:null,selectedIndex:gn,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:di,setOpen:di,setInputValue:di,setSelectedValue:di,setIndices:di,handleSelection:di,forceMount:di,requestSubmit:di})}).current,vn=d==="none"?Bt:me,un=g.useMemo(()=>d==="none"?vn:Array.isArray(me)?me.map(gn=>Fg(gn,A)):Fg(me,A),[vn,A,d,me]),Rn=pt(f),xr=pt(n),ws=wt(mt,dn.activeIndex),Fr=wt(mt,dn.selectedIndex),Wr=wt(mt,dn.positionerElement),mr=wt(mt,dn.listElement),Ci=wt(mt,dn.triggerElement),_i=wt(mt,dn.inputElement),Aa=wt(mt,dn.inputGroupElement),Yr=wt(mt,dn.inline),Za=wt(mt,dn.inputInsidePopup),lg=wt(mt,dn.inputOwnsFormValue),ma=ia(Ci),{mounted:yc,setMounted:ah,transitionStatus:bd}=Wm(yt),{openMethod:Tp,triggerProps:Ep}=Jwe(yt),lh=pt(()=>un);t_(Za?ma:Be,re,vn,lh,!$e,h);const Xr=pt(()=>{S?Fe.current=_t.map(gn=>Kp(gn,P)):mt.set("forceMounted",!0)}),Is=pt((gn,Tn,Ns)=>{if(Tn===-1){if(Ie.current===Eie)return;Ie.current=Eie}else Ie.current={value:gn,index:Tn};Rn(gn,LW(Ns,void 0,{index:Tn}))}),ei=pt(gn=>{mt.update(gn);const Tn=gn.activeIndex;if(Tn===void 0)return;const Ns=gn.type||To;Tn===null?Is(void 0,-1,Ns):Is(xe.current[Tn],Tn,Ns)}),Wa=pt((gn,Tn)=>{if(_e.current=Tn.reason===ly,e.onInputValueChange?.(gn,Tn),!Tn.isCanceled){if(Tn.reason===GE){yt&&he!==null&&Oe(null);const Ns=Tn.event,Ti=Ns.inputType;if(Ns.type==="compositionend"||Ti!=null&&Ti!==""&&Ti!=="insertReplacementText"){const Pa=gn.trim()!=="";Pa&&ve(!0),le.current={hasQuery:Pa};const So=mt.state.listElement;if(!mt.state.virtualized&&So){const Kl=qe.current;for(const gf of WI(So.firstElementChild??So)){if(!si(gf)||(Kl?!ln(Kl,gf):gf.getAttribute("role")==="dialog"))break;if(n1t(gf)){gf.scrollTop=0;break}}}Pa&&At&&mt.state.activeIndex==null&&(yt||Yr)&&mt.set("activeIndex",0)}}else Tn.reason===ly&&gn===""&&mt.state.inputInsidePopup&&(le.current={hasQuery:!1,selection:!0});Qt(gn)}}),mf=pt((gn,Tn)=>{if(yt!==gn&&(Tn.reason===QC&&Ze&&_t.length===0&&!Ce.current&&Tn.allowPropagation(),e.onOpenChange?.(gn,Tn),!Tn.isCanceled&&(gn&&Za&&!Yr&&he!==null&&(ve(!1),Oe(null),Bt!==""&&Tn.reason!==GE&&Wa("",Yt(ly,Tn.event))),!gn&&pe&&(De?(Yr||Oe(we),we===""&&ve(!1)):He&&(Yr||Oe(we),Za&&ei({activeIndex:null}),(!Za||Yr)&&Wa("",Yt(ly,Tn.event)))),bn(gn),!gn&&Za&&(Tn.reason===r0||Tn.reason===h3)&&(te(!0),oe(!1),ue==="onBlur")))){const Ns=d==="none"?Bt:me;ee.commit(Ns)}}),mi=pt((gn,Tn)=>{if(i?.(gn,Tn),Tn.isCanceled)return;Le(gn),(d==="none"&&qe.current&&q||De&&!mt.state.inputInsidePopup)&&Wa(Kp(gn,P),Yt(Tn.reason,Tn.event))}),wd=pt((gn,Tn)=>{const Ns=Ui(gn),Ti=Me.current??gn;Me.current=null;const Jo=Yt(k1,Ti),Pa=Ns?.closest("a")?.getAttribute("href");if(Pa){Pa.startsWith("#")&&mf(!1,Jo);return}if(He){const So=Array.isArray(me)?me:[],gf=FGn(So,Tn,D)?s0t(So,Tn,D):[...So,Tn];if(mi(gf,Jo),Jo.isCanceled||!(Be.current?Be.current.value.trim()!=="":!1))return;mt.state.inputInsidePopup?Wa("",Yt(ly,Jo.event)):mf(!1,Jo)}else{if(mi(Tn,Jo),Jo.isCanceled)return;mf(!1,Jo)}}),cg=pt(()=>{const gn=ee.inputRef.current?.form??mt.state.inputElement?.form;gn&&typeof gn.requestSubmit=="function"&&gn.requestSubmit()}),Nx=pt(()=>{if(ah(!1),xr?.(!1),ve(!1),Oe(null),ei(d==="none"?{activeIndex:null,selectedIndex:null}:{activeIndex:null}),He&&Be.current&&Be.current.value!==""&&!_e.current&&Wa("",Yt(ly)),De)if(mt.state.inputInsidePopup)Be.current&&Be.current.value!==""&&Wa("",Yt(ly));else{const gn=Kp(me,P);Be.current&&Be.current.value!==gn&&Wa(gn,Yt(gn===""?ly:To))}}),xc=g.useMemo(()=>Yr&&Wr?{current:Wr.closest('[role="dialog"]')}:qe,[Yr,Wr]);ql({enabled:!e.actionsRef,open:yt,ref:xc,onComplete(){yt||Nx()}}),g.useImperativeHandle(e.actionsRef,()=>({unmount:Nx}),[Nx]),Tt(function(){if(yt||(Se.current=null,d==="none"))return;const Tn=Ze?Ht:xe.current;ei({selectedIndex:uie(Tn,me,D,He)})},[yt,me,d,He,Ze,Ht,D,ei]),Tt(()=>{S&&(xe.current=_t,Ee.current.length=_t.length)},[S,_t]),Tt(()=>{const gn=le.current;if(gn){const Kl=yt||Yr||mt.state.positionerElement?.hidden===!1;if(gn.hasQuery)At&&Kl&&mt.set("activeIndex",0),le.current=null;else if(String(Bt).trim()===""&&(le.current=null,Kl)){const gf=gn.selection;At==="always"&&!gf&&mt.state.selectionMode==="none"&&mt.set("activeIndex",0),queueMicrotask(()=>{if(!mt.state.open&&!mt.state.inline||Be.current&&Be.current.value.trim()!=="")return;const ch=mt.state.selectedValue,Dv=mt.state.selectionMode==="multiple",X6=Dv&&Array.isArray(ch)?ch[ch.length-1]:ch,Wc=mt.state.selectionMode!=="none"&&X6!=null;if(Wc||gf){const $x=Ze||rt?_t:xe.current;mt.set("activeIndex",Wc?uie($x,ch,mt.state.isItemEqualToValue,Dv):null)}else At==="always"&&mt.set("activeIndex",0)})}}if(!yt&&!Yr)return;const Ns=Ze||rt?_t:xe.current,Ti=mt.state.activeIndex;if(Ti==null){if(At==="always"&&Ns.length>0){mt.set("activeIndex",0);return}Is(void 0,-1,To);return}if(Ti>=Ns.length){Is(void 0,-1,To),mt.set("activeIndex",null);return}const Jo=Ns[Ti],Pa=Ie.current.value,So=Pa!==r1t&&Lm(Jo,Pa,mt.state.isItemEqualToValue);(Ie.current.index!==Ti||!So)&&Is(Jo,Ti,To)},[ws,At,Is,rt,Ze,_t,Yr,yt,mt,Bt]),Tt(()=>{if(d==="none"){K(String(Bt)!=="");return}K(He?Array.isArray(me)&&me.length>0:me!=null)},[K,d,Bt,me,He]),g.useEffect(()=>{Ze&&At&&_t.length===0&&ei({activeIndex:null})},[Ze,At,_t.length,ei]);function Sk(gn){const Tn=U.initialValue;return Array.isArray(gn)&&Array.isArray(Tn)?!cG(gn,Tn,(Ns,Ti)=>Lm(Ns,Ti,D)):gn!==Tn}Zg(we,()=>{!yt||we===""||we===String(Ot)||ve(!0)});function kk(){const gn=Kp(me,P);Bt!==gn&&Wa(gn,Yt(To))}Zg(me,()=>{d!=="none"&&($(ze),F(Sk(me)),ee.change(me),De&&!tt&&!Za&&kk())}),Zg(Bt,()=>{d==="none"&&($(ze),F(Bt!==U.initialValue),ee.change(Bt))}),Zg(S,()=>{!De||tt||Za||pe||kk()});const ug=Eut({open:Yr?!0:yt,onOpenChange:mf,elements:{reference:Za?Ci:_i,floating:Wr}}),Ax=b?"grid":"listbox",Ok=yt||Yr,YP=Ok?"true":"false",dg=g.useMemo(()=>{const gn=_i?.tagName==="INPUT",Tn=_i==null||gn,Ns=Tn||Ok,Ti=Tn?{autoComplete:"off",spellCheck:"false",autoCorrect:"off",autoCapitalize:"none"}:{};return Ns&&(Ti.role="combobox",Ti["aria-expanded"]=YP,Ti["aria-haspopup"]=Ax,Ti["aria-controls"]=Ok?mr?.id:void 0,Ti["aria-autocomplete"]=H),{reference:Ti,floating:{role:"presentation"}}},[_i,Ok,YP,Ax,mr?.id,H]),K6=ZC(ug,{enabled:!v&&!$e&&C,event:"mousedown-only",toggle:!1,touchOpenDelay:Za?0:100,reason:cwn}),jk=WC(ug,{enabled:!v&&!$e&&!Yr,outsidePressEvent:{mouse:"sloppy",touch:"intentional"},bubbles:Yr?!0:void 0,outsidePress(gn){const Tn=Ui(gn);return!ln(Ci,Tn)&&!ln(ye.current,Tn)&&!ln(ce.current,Tn)&&!ln(Aa,Tn)}}),Px=jbe(ug,{enabled:!v&&!$e,id:re,listRef:Ee,activeIndex:ws,selectedIndex:Fr,virtual:!0,loopFocus:I,allowEscape:I&&!At,focusItemOnOpen:pe||d==="none"&&!At?!1:"auto",focusItemOnHover:N,resetOnPointerLeave:!_,orientation:b?"horizontal":void 0,rtl:se==="rtl",disabledIndices:Lf,grid:b?Orr:void 0,onNavigate(gn,Tn){!Tn&&!yt||bd==="ending"||ei(Tn?{activeIndex:gn,type:Te.current?obe:zct}:{activeIndex:gn})}}),Ck=g.useMemo(()=>Dl(Px.reference,{onKeyDown(gn){b&&mt.state.activeIndex==null&&(gn.key==="ArrowLeft"||gn.key==="ArrowRight")&&gn.preventBaseUIHandler()}},jk.reference,K6.reference,dg.reference),[Px.reference,jk.reference,K6.reference,dg.reference,b,mt]),XP=g.useMemo(()=>Dl(ZS,jk.floating),[jk.floating]),JP=g.useMemo(()=>Dl(Px.floating,dg.floating),[Px.floating,dg.floating]),Y0=g.useMemo(()=>{const gn=Px.item;return gn?{...gn,onFocus:void 0}:ai},[Px.item]);t0t(()=>{mt.update({inline:Q,popupProps:XP,listProps:JP,inputProps:Ck,triggerProps:Ep,itemProps:Y0,setOpen:mf,setInputValue:Wa,setSelectedValue:mi,setIndices:ei,handleSelection:wd,forceMount:Xr,requestSubmit:cg,onOpenChangeComplete:xr})}),Tt(()=>{mt.update({id:re,selectedValue:me,open:yt,mounted:yc,transitionStatus:bd,items:S,inline:Q,popupProps:XP,listProps:JP,inputProps:Ck,triggerProps:Ep,openMethod:Tp,itemProps:Y0,selectionMode:d,name:ze,form:p,disabled:$e,readOnly:v,required:y,grid:b,virtualized:z,openOnInputClick:C,itemToStringLabel:P,modal:B,autoHighlight:At,isItemEqualToValue:D,submitOnItemClick:L,hasInputValue:tt,inputOwnsFormValue:d==="none"&&(Q||!mt.state.inputInsidePopup)})},[mt,re,me,yt,yc,bd,S,XP,JP,Ck,Y0,Tp,Ep,d,ze,$e,v,y,b,z,C,P,B,D,L,tt,Q,At,p]);const fg=Jd(x,ee.inputRef),e$=g.useMemo(()=>({query:we,hasItems:Ze,filteredItems:Vt,flatFilteredItems:_t}),[we,Ze,Vt,_t]),t$=g.useMemo(()=>Array.isArray(vn)?"":Fg(vn,A),[vn,A]),X0=He&&Array.isArray(me)&&me.length>0,Mv=He||d==="none"&&lg?void 0:ze,Y6=g.useMemo(()=>!He||!Array.isArray(me)||!ze?null:me.map(gn=>{const Tn=Fg(gn,A);return a.jsx("input",{type:"hidden",form:p,name:ze,value:Tn,disabled:$e},Tn)}),[He,me,p,ze,A,$e]),n$=a.jsxs(g.Fragment,{children:[e.children,a.jsx("input",{...ee.getValidationProps($e,{onFocus(){if(Za){Ci?.focus();return}(Be.current||Ci)?.focus()},onChange(gn){if(gn.nativeEvent.defaultPrevented||$e||v)return;const Tn=gn.currentTarget.value,Ns=Tn.toLowerCase(),Ti=Yt(To,gn.nativeEvent),Jo=()=>xe.current.findIndex(So=>Fg(So,A).toLowerCase()===Ns||Kp(So,P).toLowerCase()===Ns);function Pa(){if(He)return;if(d==="none"){Wa(Tn,Ti);return}let So=Jo();So===-1&&(So=xe.current.findIndex((gf,ch)=>{const Dv=Fe.current[ch];return Dv!=null&&Dv.toLowerCase()===Ns}));const Kl=So===-1?void 0:xe.current[So];Kl!=null&&mi?.(Kl,Ti)}De&&(Xr(),S&&Jo()===-1&&mt.set("forceMounted",!0)),queueMicrotask(Pa)}}),id:re&&Mv==null?`${re}-hidden-input`:void 0,form:p,name:Mv,autoComplete:M,disabled:$e,required:y&&!X0,readOnly:v,value:t$,ref:fg,style:Mv?CA:G1,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),Y6]});return a.jsx(Gwt.Provider,{value:mt,children:a.jsx(Kwt.Provider,{value:ug,children:a.jsx(Xwt.Provider,{value:Ze,children:a.jsx(Ywt.Provider,{value:e$,children:a.jsx(Jwt.Provider,{value:Bt,children:n$})})})})})}function Tq(e){const{multiple:t=!1,defaultValue:n,value:r,onValueChange:s,autoComplete:i,...o}=e;return a.jsx(Nrr,{...o,selectionMode:t?"multiple":"single",selectedValue:r,defaultSelectedValue:n,onSelectedValueChange:s,formAutoComplete:i})}function C7e(e){const{children:t,placeholder:n}=e,r=Jm(),s=wt(r,dn.itemToStringLabel),i=wt(r,dn.selectedValue),o=wt(r,dn.items),l=wt(r,dn.selectionMode)==="multiple",c=wt(r,dn.hasSelectedValue),u=!c&&n!=null&&t==null,d=wt(r,dn.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=o0t(i,o,s):f=c1e(i,o,s),a.jsx(g.Fragment,{children:f})}const s1t={...XI,...yp,popupSide:e=>e?{"data-popup-side":e}:null,listEmpty:e=>e?{"data-list-empty":""}:null},Arr=g.createContext(void 0);function Prr(){return g.useContext(Arr)}const i1t=g.createContext(void 0);function iSe(e){const t=g.useContext(i1t);if(t===void 0&&!e)throw new Error(Pr(21));return t}const o1t=g.forwardRef(function(t,n){const r=Jm(),{buttonRef:s,getButtonProps:i}=ud({native:!1}),o=Jd(n,s);function l(u){r.state.setOpen(!1,Yt(ibe,u.nativeEvent,u.currentTarget))}const c=i({onClick:l});return a.jsx("span",{ref:o,...c,"aria-label":"Dismiss",tabIndex:void 0,style:CA})});function a1t(e){const t=wt(e,dn.mounted),n=wt(e,dn.popupSide),r=wt(e,dn.positionerElement);return t&&r?n:null}function kG(){return pL().filteredItems.length===0}function $rr(e){return e==="rtl"?["ArrowRight","ArrowLeft"]:["ArrowLeft","ArrowRight"]}function Rrr(e,t){const n=e>=t-1?t-2:e;return n>=0?n:void 0}function l1t(e,t,n){const r=e.state.listRef.current[t];r&&(e.state.selectionEventRef.current=n,r.click(),e.state.selectionEventRef.current=null)}const oSe=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}=_u(),{labelId:v}=hd(),y=Prr(),b=!!iSe(!0),S=Jm(),k=e1t(),j=vx(),C=wt(S,dn.required),T=wt(S,dn.disabled),_=wt(S,dn.readOnly),N=wt(S,dn.name),I=wt(S,dn.form),P=wt(S,dn.selectionMode),A=wt(S,dn.autoHighlight),D=wt(S,dn.inputProps),z=wt(S,dn.triggerProps),Q=wt(S,dn.open),q=wt(S,dn.mounted),B=wt(S,dn.selectedValue),V=wt(S,dn.id),H=wt(S,dn.inline),M=wt(S,dn.modal),G=!!A,L=a1t(S),$=d||T||i,F=kG(),U=b||H,K=!U||M,ne=Qi(o??(U?void 0:V)),X=b?Jpt:u,[te,oe]=g.useState(null),ue=g.useRef(!1),ee=g.useRef(null),se=g.useRef(!1),re=P==="none"&&!b,ae=pt(Be=>{const Pe=b||S.state.inline;Pe&&!S.state.hasInputValue&&S.state.setInputValue("",Yt(To)),S.update({inputElement:Be,inputInsidePopup:Pe,inputOwnsFormValue:re})}),pe=b?c:m.getValidationProps($,c);function ve(){S.state.setIndices({activeIndex:null,selectedIndex:null,type:S.state.keyboardActiveRef.current?obe:zct})}function he(){S.state.keyboardActiveRef.current=!1}const Oe={...X,open:Q,disabled:$,readOnly:_,popupSide:L,listEmpty:F};function Ee(Be){if(!y)return;let Pe;const{highlightedChipIndex:Ve}=y,Ce=y.chipsRef.current.length,[Te,_e]=$rr(j);return Ve!==void 0?(Be.key===Te?(Be.preventDefault(),Ve>0?Pe=Ve-1:Pe=void 0):Be.key===_e?(Be.preventDefault(),Ve<Ce-1?Pe=Ve+1:Pe=void 0):(Be.key==="Backspace"||Be.key==="Delete")&&(Be.preventDefault(),Pe=Rrr(Ve,B.length),ve()),Pe):(Be.key===Te&&(Be.currentTarget.selectionStart??0)===0&&B.length>0&&(Be.preventDefault(),Pe=Ce>0?Ce-1:void 0),Pe)}const Fe=pn("input",t,{state:Oe,ref:[n,S.state.inputRef,ae],props:[D,z,{value:te??k,"aria-readonly":_||void 0,"aria-required":C||void 0,"aria-labelledby":v,disabled:$,readOnly:_,required:P==="none"?C:void 0,form:I,...re&&N&&{name:N},id:ne,onFocus(){if(h(!0),!H||!se.current)return;se.current=!1;const Be=ee.current;Be==null||!Object.hasOwn(S.state.valuesRef.current,Be)||S.state.setIndices({activeIndex:Be})},onBlur(){f(!0),h(!1);const Be=S.state.activeIndex;if(H&&Be!==null&&A!=="always"&&(ee.current=Be,se.current=!0,S.state.setIndices({activeIndex:null})),p==="onBlur"){const Pe=P==="none"?k:B;m.commit(Pe)}},onCompositionStart(Be){QD||(ue.current=!0,oe(Be.currentTarget.value))},onCompositionEnd(Be){ue.current=!1;const Pe=Be.currentTarget.value;oe(null),S.state.setInputValue(Pe,Yt(GE,Be.nativeEvent))},onChange(Be){const Pe=Be.nativeEvent,Ve=Pe.inputType,Ce=!Ve||Ve==="insertReplacementText",Te=ue.current||!Ce;function _e(Ie){_||$||!Ie||!Te||(S.state.setOpen(!0,Yt(GE,Pe)),G||ve())}if(ue.current){const Ie=Be.currentTarget.value;oe(Ie),Ie===""&&!S.state.openOnInputClick&&!S.state.inputInsidePopup&&S.state.setOpen(!1,Yt(ly,Pe));const le=Ie.trim(),xe=G&&le!=="";_e(le),Q&&S.state.activeIndex!==null&&!xe&&ve();return}const ce=Yt(GE,Pe);if(S.state.setInputValue(Be.currentTarget.value,ce),ce.isCanceled)return;const ye=Be.currentTarget.value==="",Me=Yt(ly,Pe);ye&&!S.state.inputInsidePopup&&(P==="single"&&S.state.setSelectedValue(null,Me),S.state.openOnInputClick||S.state.setOpen(!1,Me)),_e(Be.currentTarget.value.trim()),Q&&S.state.activeIndex!==null&&!G&&ve()},onKeyDown(Be){if($||_||Be.ctrlKey||Be.shiftKey||Be.altKey||Be.metaKey)return;S.state.keyboardActiveRef.current=!0;const Pe=Be.currentTarget,Ve=Pe.scrollWidth-Pe.clientWidth,Ce=j==="rtl";if(Be.key==="Home"){sc(Be);const ce=M5e&&Ce?Pe.value.length:0;Pe.setSelectionRange(ce,ce),Pe.scrollLeft=0;return}if(Be.key==="End"){sc(Be);const ce=M5e&&Ce?0:Pe.value.length;Pe.setSelectionRange(ce,ce),Pe.scrollLeft=Ce?-Ve:Ve;return}if(!q&&Be.key==="Escape"){const ce=P==="multiple"&&Array.isArray(B)?B.length===0:B===null,ye=Yt(QC,Be.nativeEvent),Me=P==="multiple"?[]:null;S.state.setInputValue("",ye),S.state.setSelectedValue(Me,ye),!ce&&!S.state.inline&&!ye.isPropagationAllowed&&Be.stopPropagation();return}if(y&&Be.key==="Backspace"&&Pe.value===""&&y.highlightedChipIndex===void 0&&Array.isArray(B)&&B.length>0){const ce=y.chipsRef.current.length,ye=ce>0?ce-1:B.length-1,Me=B.filter((Ie,le)=>le!==ye);ve(),S.state.setSelectedValue(Me,Yt(To,Be.nativeEvent));return}const Te=y?.highlightedChipIndex!==void 0,_e=Ee(Be);if(y?.setHighlightedChipIndex(_e),_e!==void 0?y?.chipsRef.current[_e]?.focus():Te&&S.state.inputRef.current?.focus(),Be.which!==229&&Be.key==="Enter"&&Q){const ce=S.state.activeIndex,ye=Be.nativeEvent;if(ce===null){if(H)return;S.state.setOpen(!1,Yt(To,ye));return}sc(Be),l1t(S,ce,ye)}},onPointerMove:he,onPointerDown:he},pe],stateAttributesMapping:s1t}),qe=b?a.jsx(N0e.Provider,{value:emt,children:Fe}):Fe;return a.jsxs(g.Fragment,{children:[Q&&K&&a.jsx(o1t,{ref:S.state.startDismissRef}),qe]})}),c1t=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}=_u(),{labelId:y}=hd(),x=Jm(),b=wt(x,dn.selectionMode),S=wt(x,dn.disabled),k=wt(x,dn.readOnly),j=wt(x,dn.required),C=wt(x,dn.positionerElement),T=wt(x,dn.listElement),_=wt(x,dn.popupId),N=wt(x,dn.triggerProps),I=wt(x,dn.inputInsidePopup),P=wt(x,dn.id),A=wt(x,dn.labelId),D=wt(x,dn.open),z=wt(x,dn.selectedValue),Q=wt(x,dn.activeIndex),q=wt(x,dn.selectedIndex),B=wt(x,dn.hasSelectedValue),V=SG(),H=e1t(),M=No(),G=f||S||o,L=kG(),$=a1t(x);YS({id:I?l:void 0});const F=I?l??P:l,U=u1e(y,A);let K;D&&I?K=_??t1t(P):D&&(K=T?.id);const ne=g.useRef("");function X(pe){ne.current=pe.pointerType}const{reference:te}=Cbe(V,{enabled:!D&&!k&&!S&&b==="single",listRef:x.state.labelsRef,activeIndex:Q,selectedIndex:q,onMatch(pe){const ve=x.state.valuesRef.current[pe];ve!==void 0&&x.state.setSelectedValue(ve,Yt(To))}}),{reference:oe}=ZC(V,{enabled:!k&&!S,event:"mousedown"}),{buttonRef:ue,getButtonProps:ee}=ud({native:i,disabled:G}),se={...d,open:D,disabled:G,popupSide:$,listEmpty:L,placeholder:b==="none"?!1:!B},re=pt(pe=>{x.set("triggerElement",pe)});return pn("button",t,{ref:[n,ue,re],state:se,props:[N,oe,te,{id:F,tabIndex:I?0:-1,role:I?"combobox":void 0,"aria-expanded":D,"aria-haspopup":I?"dialog":"listbox","aria-controls":K,"aria-required":I&&j||void 0,"aria-labelledby":U,onPointerDown:X,onPointerEnter:X,onFocus(){p(!0),!(G||k)&&M.start(0,x.state.forceMount)},onBlur(pe){if(!ln(C,pe.relatedTarget)&&(h(!0),p(!1),m==="onBlur")){const ve=b==="none"?H:z;v.commit(ve)}},onMouseDown(pe){if(G||k||(I||V.set("domReferenceElement",pe.currentTarget),x.state.forceMount(),ne.current!=="touch"&&(x.state.inputRef.current?.focus(),I||pe.preventDefault()),D))return;const ve=kr(pe.currentTarget);function he(Oe){const Ee=x.state.triggerElement;if(!Ee)return;const Fe=Ui(Oe),qe=x.state.positionerElement,Be=x.state.listElement;ln(Ee,Fe)||ln(qe,Fe)||ln(Be,Fe)||t1e(Oe,Ee)||x.state.setOpen(!1,Yt(DW,Oe))}I&&ve.addEventListener("mouseup",he,{once:!0})},onKeyDown(pe){k||(pe.key==="ArrowDown"||pe.key==="ArrowUp")&&(sc(pe),x.state.setOpen(!0,Yt(ZD,pe.nativeEvent)),x.state.inputRef.current?.focus())}},v.getValidationProps(G,u),ee],stateAttributesMapping:s1t})}),Mrr=g.createContext(null);function Drr(){return g.useContext(Mrr)}function Lrr(e){const{children:t}=e,{filteredItems:n}=pL(),r=Drr(),s=r?r.items:n;return a.jsx(g.Fragment,{children:s.map(t)})}const u1t=g.forwardRef(function(t,n){var r;const{render:s,className:i,style:o,children:l,...c}=t,u=Jm(),d=SG(),f=!!iSe(!0),{filteredItems:h,hasItems:p}=pL(),m=wt(u,dn.selectionMode),v=wt(u,dn.grid),y=wt(u,dn.listProps),x=wt(u,dn.virtualized),b=wt(u,dn.forceMounted),S=m==="multiple",k=h.length===0,j=pt(A=>{u.set("positionerElement",A)}),C=pt(A=>{u.set("listElement",A)}),T=g.useMemo(()=>typeof l=="function"?r||(r=a.jsx(Lrr,{children:l})):l,[l]),_={empty:k},N=d.useState("floatingId"),I=pn("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(A){if(!(u.state.disabled||u.state.readOnly)&&A.key==="Enter"){const D=u.state.activeIndex;if(D==null)return;sc(A),l1t(u,D,A.nativeEvent)}},onKeyDownCapture(){u.state.keyboardActiveRef.current=!0},onPointerMoveCapture(){u.state.keyboardActiveRef.current=!1}},c]});if(x)return I;const P=p&&!b?void 0:u.state.labelsRef;return a.jsx(HA,{elementsRef:u.state.listRef,labelsRef:P,children:I})}),zrr="",Frr=200;function Brr(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 d1t(){const e=No(),t=g.useRef(null);return g.useEffect(()=>{if(f3)return;const n=t.current;if(n==null)return;const r=Brr(n);if(r==null)return;const s=r.data,i=`${s}${zrr}`;return r.nodeValue=i,e.start(Frr,()=>{r.nodeValue===i&&(r.nodeValue=s)}),()=>{e.clear(),r.nodeValue===i&&(r.nodeValue=s)}},[t,e]),t}const _7e=g.forwardRef(function(t,n){const{render:r,className:s,style:i,children:o,...l}=t,c=d1t();return pn("div",t,{ref:[n,c],props:[{children:o,role:"status","aria-live":"polite","aria-atomic":!0},l]})}),f1t=g.createContext(void 0);function Vrr(){const e=g.useContext(f1t);if(e===void 0)throw new Error(Pr(20));return e}const aSe=g.forwardRef(function(t,n){const{keepMounted:r=!1,...s}=t,i=Jm(),o=wt(i,dn.mounted),l=wt(i,dn.forceMounted);return o||r||l?a.jsx(f1t.Provider,{value:r,children:a.jsx(g3,{ref:n,...s})}):null}),lSe=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=hbe,style:x,...b}=t,S=Jm(),k=SG(),j=Vrr(),C=wt(S,dn.modal),T=wt(S,dn.open),_=wt(S,dn.mounted),N=wt(S,dn.openMethod),I=wt(S,dn.positionerElement),P=wt(S,dn.triggerElement),A=wt(S,dn.inputElement),D=wt(S,dn.inputGroupElement),z=wt(S,dn.inputInsidePopup),Q=wt(S,dn.transitionStatus),q=kG(),V=EA({anchor:i??(z?P:D??A),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});oG(T&&C,N==="touch",I,P);const H={open:T,side:V.side,align:V.align,anchorHidden:V.anchorHidden,empty:q};Tt(()=>{S.set("popupSide",V.side)},[S,V.side]);const M=pt(L=>{S.set("positionerElement",L)}),G=IA(t,H,{styles:V.positionerStyles,transitionStatus:Q,props:b,refs:[n,M],hidden:!_,inert:!T});return a.jsxs(i1t.Provider,{value:V,children:[_&&C&&a.jsx(sL,{inert:NA(!T),cutout:D??A??P}),G]})}),Urr={...KC,...gp},cSe=g.forwardRef(function(t,n){const{render:r,className:s,style:i,initialFocus:o,finalFocus:l,...c}=t,u=Jm(),d=iSe(),f=SG(),h=wt(u,dn.mounted),p=wt(u,dn.open),m=wt(u,dn.openMethod),v=wt(u,dn.popupProps),y=wt(u,dn.transitionStatus),x=wt(u,dn.inputInsidePopup),b=wt(u,dn.inputElement),S=wt(u,dn.modal),k=wt(u,dn.id),j=kG(),C=c.id??(x?t1t(k):void 0);Tt(()=>(u.set("popupId",u.state.popupRef.current?.id||C),()=>{u.set("popupId",void 0)}),[u,C]),ql({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},_=pn("div",t,{state:T,ref:[n,u.state.popupRef],props:[v,{id:C,role:x?"dialog":"presentation",onFocus(D){const z=Ui(D.nativeEvent);m!=="touch"&&(ln(u.state.listElement,z)||z===D.currentTarget)&&u.state.inputRef.current?.focus()}},XC(y),c],stateAttributesMapping:Urr}),I=o===void 0?x?D=>D==="touch"?u.state.popupRef.current:b:!1:o;let P;l!=null?P=l:P=x?void 0:!1;const A=!x||S;return a.jsx(_A,{context:f,disabled:!h,modal:A,openInteractionType:m,initialFocus:I,returnFocus:P,getInsideElements:()=>[u.state.startDismissRef.current,u.state.endDismissRef.current],children:a.jsxs(g.Fragment,{children:[_,A&&a.jsx(o1t,{ref:u.state.endDismissRef})]})})}),h1t=g.createContext(void 0);function p1t(){const e=g.useContext(h1t);if(!e)throw new Error(Pr(19));return e}const qrr=g.createContext(!1);function Qrr(){return g.useContext(qrr)}function m1t(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=N0({guess:!0,index:u,textRef:p}),v=Jm(),y=Qrr(),x=jrr(),b=wt(v,dn.selectionMode),S=wt(v,dn.disabled),k=wt(v,dn.readOnly),j=wt(v,dn.isItemEqualToValue),C=S||d,T=b!=="none",_=u??s??m.index,N=_!==-1,I=wt(v,dn.id),P=wt(v,dn.isActive,_),A=wt(v,dn.isSelected,c),D=wt(v,dn.itemProps),z=g.useRef(null),Q=I!=null&&N?`${I}-${_}`:void 0,q=A&&T;Tt(()=>{if(!(N&&(r||u!=null)))return;const U=v.state.listRef.current;return U[_]=z.current,()=>{delete U[_]}},[N,r,_,u,v]),Tt(()=>{if(!N||x)return;const F=v.state.valuesRef.current;return F[_]=c,()=>{delete F[_]}},[N,x,_,c,v]),Tt(()=>{if(!N||x)return;const F=v.state.selectedValue,U=Array.isArray(F)?F[F.length-1]:F;Lm(c,U,j)&&v.set("selectedIndex",_)},[N,x,v,_,c,j]);const{getButtonProps:B,buttonRef:V}=ud({disabled:C,focusableWhenDisabled:!0,native:f,composite:!0}),H={disabled:C,selected:q,highlighted:P};function M(F){function U(){v.state.handleSelection(F,c)}v.state.submitOnItemClick?(bo.flushSync(U),v.state.requestSubmit()):U()}const G={id:Q,role:y?"gridcell":"option","aria-selected":T?q:void 0,tabIndex:void 0,onPointerDownCapture(F){F.isPrimary&&(v.state.pointerDownItemRef.current=F.currentTarget),F.preventDefault()},onMouseDown(F){F.preventDefault()},onClick(F){C||k||M(F.nativeEvent)},onMouseUp(F){const U=v.state.pointerDownItemRef.current===F.currentTarget;v.state.pointerDownItemRef.current=null,!(C||k||F.button!==0||U||!P)&&M(F.nativeEvent)}},L=pn("div",t,{ref:[V,n,m.ref,z],state:H,props:[D,G,h,B]}),$=g.useMemo(()=>({selected:q,textRef:p}),[q,p]);return a.jsx(h1t.Provider,{value:$,children:L})}function Zrr(e){const{componentProps:t,forwardedRef:n}=e,r=Jm(),s=wt(r,dn.isItemEqualToValue),{flatFilteredItems:i}=pL(),o=hI(i,t.value??null,s);return a.jsx(m1t,{componentProps:t,forwardedRef:n,virtualized:!0,indexFromFilter:o})}const g1t=g.memo(g.forwardRef(function(t,n){const r=Jm(),s=wt(r,dn.virtualized);return s&&t.index==null?a.jsx(Zrr,{componentProps:t,forwardedRef:n}):a.jsx(m1t,{componentProps:t,forwardedRef:n,virtualized:s,indexFromFilter:void 0})})),v1t=g.forwardRef(function(t,n){const{selected:r}=p1t();return t.keepMounted||r?a.jsx(Wrr,{...t,ref:n}):null}),Wrr=g.memo(g.forwardRef((e,t)=>{const{render:n,className:r,style:s,keepMounted:i,...o}=e,{selected:l}=p1t(),c=g.useRef(null),{transitionStatus:u,setMounted:d}=Wm(l),h=pn("span",e,{ref:[t,c],state:{selected:l,transitionStatus:u},props:[{"aria-hidden":!0,children:"✔️"},o],stateAttributesMapping:gp});return ql({open:l,ref:c,onComplete(){l||d(!1)}}),h})),y1t=g.forwardRef(function(t,n){const{render:r,className:s,style:i,children:o,...l}=t,{filteredItems:c}=pL(),u=Jm(),d=d1t(),f=c.length===0?o:null;return pn("div",t,{ref:[n,u.state.emptyRef,d],props:[{children:f,role:"status","aria-live":"polite","aria-atomic":!0},l]})});function Hrr(e){return e==="link"?"ghost":e}function x1t({variant:e,size:t,className:n}){const r=Hrr(e);return Z(PA({variant:r,size:t}),r==="default"&&Qut,!Pbe(t)&&Z(Zut,"justify-between"),_be[r],"data-[placeholder]:text-muted-foreground",Ibe,n)}const Dhe=dd(Xm,{variants:{multiple:{false:"",true:""}},defaultVariants:{multiple:!1}}),as={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(XA,"max-h-none overflow-hidden p-0"),positioner:Z(YA,"pointer-events-auto"),searchContainer:uI.container,searchIcon:uI.icon,searchInput:Z(uI.input,"disabled:cursor-not-allowed disabled:opacity-50"),empty:Z(vq,"empty:hidden"),list:"p-1 empty:p-0",listScroller:"max-h-dropdown overflow-y-auto overflow-x-hidden",item:Dhe({multiple:!1}),itemMulti:Dhe({multiple:!0}),itemRightSlot:"ml-auto flex items-center gap-2 shrink-0",checkContainer:Z(i_,"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 Grr({children:e,className:t}){return a.jsx("div",{className:Z("grid gap-2 text-foreground",t),children:e})}function b1t({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(Nt,{size:"xs",className:"mt-1 shrink-0","aria-hidden":!0,children:a.jsx(RA,{})}),a.jsx("span",{children:e})]})}function w1t({children:e}){return a.jsx(Y,{variant:"caption",tone:"muted",children:e})}function Krr({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 Yrr({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 Xrr({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(b1t,{name:e,className:"truncate",children:n}):t?a.jsx(w1t,{children:t}):null})}const Jrr=Object.assign({},{Layout:Yrr,Column:Grr,Label:Krr,HelpText:w1t,ErrorMsg:b1t,Message:Xrr}),esr=e=>`error-${e}`,T7e=[],tsr=[];function Iie(e){return e.multiple===!0}const S1t=g.forwardRef((e,t)=>a.jsx(g1t,{ref:Eu(t),...e}));S1t.displayName="ComboboxItem";function E7e({option:e}){return a.jsxs("span",{className:as.optionText,children:[a.jsx("span",{className:as.optionLabel,children:e.label}),e.description&&a.jsx("span",{className:as.optionDescription,children:e.description})]})}function Ca(e){const{options:t,placeholder:n=Iie(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=Iie(e),T=C?e.clearLabel:void 0,_=BA(),N=g.useId(),I=j??N,P=[m,k?esr(I):void 0].filter(Boolean).join(" ")||void 0,[A,D]=g.useState(""),z=A.trim(),Q=!C&&b&&z&&!t.some(X=>X.value===z)?{label:`Use “${z}”`,value:z}:void 0,q=Q?[Q,...t]:t,B=C?e.value??T7e:T7e,V=g.useMemo(()=>new Set(B),[B]),H=C?null:t.find(X=>X.value===e.value)??null,M=C?t.filter(X=>V.has(X.value)):tsr,G=M.length===0?n:`${M.length} selected`,L=()=>{Iie(e)&&e.onValueChange?.([])},$=A0(f),F=_v(),U=Pbe(c),K=a.jsxs(a.Fragment,{children:[a.jsxs(c1t,{id:h,"aria-label":p??(h||_?void 0:C?"Select options":"Select option"),...wx({"aria-label":p}),...XW(!!k),"aria-describedby":P,"data-shape":U?"icon":void 0,className:x1t({variant:l,size:c,className:Z(x&&"w-auto px-2.5",i)}),children:[U?a.jsx("span",{className:"sr-only",children:C?G:a.jsx(C7e,{placeholder:n})}):C?a.jsx("span",{className:Z("truncate",M.length===0&&as.placeholder),children:G}):a.jsxs("span",{className:Z("flex min-w-0 flex-1 items-center",x?"justify-center":"gap-2"),children:[H?.start,a.jsx("span",{className:"truncate",children:H?.displayLabel??a.jsx(C7e,{placeholder:n})})]}),y?a.jsx("span",{className:"flex shrink-0 items-center",children:a.jsx(adt,{className:Z(as.chevron,(U||x)&&"ml-0")})}):null]}),a.jsx(aSe,{container:$,children:a.jsx(lSe,{align:v,sideOffset:4,positionMethod:vv,className:as.positioner,children:a.jsxs(cSe,{className:as.popup,children:[a.jsxs("div",{className:as.searchContainer,children:[a.jsx(Hd,{className:as.searchIcon}),a.jsx(oSe,{className:as.searchInput,placeholder:r})]}),a.jsx(y1t,{className:as.empty,children:s}),a.jsx(Nr,{maxHeight:"var(--spacing-dropdown)",children:a.jsx(sf,{className:"scroll-py-8",children:a.jsx("div",{className:F.containerClassName,...F.getContainerProps({}),children:a.jsx(Dm,{menu:F,children:a.jsx(u1t,{className:as.list,children:X=>{const te=V.has(X.value);return a.jsx(S1t,{value:X,className:Dhe({multiple:C}),children:C?a.jsxs(a.Fragment,{children:[X.start,a.jsx(E7e,{option:X}),a.jsxs("span",{className:as.itemRightSlot,children:[X.end?a.jsx("div",{className:as.optionEnd,children:X.end}):null,a.jsx("span",{className:as.checkContainer,children:te?a.jsx(pr,{className:as.checkIcon}):null})]})]}):a.jsxs(a.Fragment,{children:[X.start,a.jsx(E7e,{option:X}),a.jsxs("span",{className:as.itemRightSlot,children:[X.end?a.jsx("div",{className:as.optionEnd,children:X.end}):null,a.jsx("span",{className:as.checkContainer,children:a.jsx(v1t,{children:a.jsx(pr,{className:as.checkIcon})})})]})]})},X.value)}})})})})}),B.length>0&&T?a.jsx("div",{className:Z("border-t","border-border","p-1"),children:a.jsx(de,{type:"button",variant:"destructive-ghost",size:"sm",className:"w-full justify-start",onClick:L,icon:a.jsx(Ln,{}),children:T})}):null]})})})]}),ne=C?a.jsx(Tq,{multiple:!0,autoHighlight:!0,items:q,value:M,onValueChange:X=>e.onValueChange?.((X??[]).map(te=>te.value)),disabled:o,open:u,onOpenChange:d,children:K}):a.jsx(Tq,{autoHighlight:!0,items:q,value:H,inputValue:A,onInputValueChange:X=>{D(X),S?.(X)},onValueChange:X=>{X&&(e.onValueChange?.(X.value),D(""),S?.(""))},disabled:o,open:u,onOpenChange:d,children:K});return k?a.jsxs("div",{className:as.root,children:[ne,a.jsx(Jrr.ErrorMsg,{name:I,children:k})]}):ne}function nsr({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}=vp({requestContext:f}),{navigate:y,paths:x}=hn();g.useEffect(()=>{if(m){const k=v instanceof Error?v.message:"Failed to load workflows";Ge.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(Ca,{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 rsr(){const{workflowId:e}=fr(),{data:t,isLoading:n}=vp();return e?n?a.jsx(Ox,{}):t?.[e]?.name||e:null}function ssr(){const{workflowId:e}=fr();return e?a.jsx(nsr,{value:e,...l_,"aria-label":"Switch workflow"}):null}function isr(){const{runId:e}=fr();return e?e.split("-")[0]:null}function osr(){const{runId:e}=fr();return e?a.jsx(io,{content:e,tooltip:"Copy run id",variant:"ghost",size:"icon-sm"}):null}const asr=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 lsr(){return a.jsx(de,{render:a.jsx("a",{target:"_blank",rel:"noopener noreferrer",href:"/swagger-ui"}),variant:"ghost",size:"sm",icon:a.jsx(asr,{}),children:"API endpoints"})}function csr(e){if("Component"in e&&e.Component){const t=e.Component;return a.jsx(t,{})}return"node"in e?e.node:e.label}function Pt({crumbs:e}){if(e.length===0)return null;const t=e.length-1;return a.jsx(rSe,{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(H4,{as:i?oc:"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:csr(n)},n.id)})})}const nP=({queryOptions:e}={})=>{const t=Ye();return kt({queryKey:["mastra-packages"],queryFn:()=>t.getSystemPackages(),...e})},k1t=()=>{const{data:e,isLoading:t}=nP();return{hasObservability:!!(e?.observabilityEnabled??e?.packages?.some(r=>r.name==="@mastra/observability")),isLoading:t}},usr=40,dsr="",Lhe=e=>new Date(e.createdAt).getTime(),fsr=(e,t)=>Lhe(e)-Lhe(t),OG=({threadId:e,agentId:t,memory:n,requestContext:r,queryOptions:s})=>{const i=Ye();return Am({queryKey:["memory","messages",e,t,r],initialPageParam:dsr,queryFn:n&&e?({pageParam:o})=>i.listThreadMessages(e,{agentId:t,requestContext:r,includeSystemReminders:!0,perPage:usr,orderBy:{field:"createdAt",direction:"DESC"},filter:o?{dateRange:{end:new Date(o)}}:void 0}):k0,getNextPageParam:(o,l,c)=>{if(!o.hasMore||o.messages.length===0)return;const u=new Date(Math.min(...o.messages.map(Lhe))).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(fsr);return{...o,messages:c}},staleTime:0,gcTime:0,retry:!1,refetchOnWindowFocus:!1,...s})};function hsr({agentId:e,path:t,agentVersionId:n,requestContext:r,queryOptions:s}){const i=Ye();return kt({queryKey:["agent-plan",e,n,t,r],queryFn:()=>(n?i.getAgent(e,{versionId:n}):i.getAgent(e)).readPlan(t,r),retry:!1,...s})}const psr={"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 msr(e={}){const{enabled:t=!0,agentId:n,runId:r,threadId:s,resourceId:i,taskId:o}=e,l=Ye(),[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 I=new AbortController;m.current=I;try{const P=await l.streamBackgroundTasks({agentId:n,runId:r,threadId:s,resourceId:i,taskId:o});if(!P){p(new Error("Stream connection failed"));return}N===y.current&&f(!0);const A=P.getReader();for(v.current=A;!I.signal.aborted;){const{done:D,value:z}=await A.read();if(D)break;const Q=z;Q.type!=="background-task-output"&&u(q=>({...q,[Q.payload.taskId]:{...q[Q.payload.taskId],...Q.payload,status:psr[Q.type],args:("args"in Q.payload?Q.payload.args:void 0)??q[Q.payload.taskId]?.args??{}}}))}}catch(P){P?.name!=="AbortError"&&N===y.current&&p(P instanceof Error?P:new Error(String(P)))}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 I={...N};return Object.values(I).forEach(P=>{(P.status==="completed"||P.status==="failed"||P.status==="cancelled"||P.status==="timed_out")&&delete I[P.taskId]}),I})}}}const gsr=({backgroundTaskId:e,queryOptions:t})=>{const n=Ye();return kt({queryKey:["background-task",e],queryFn:()=>n.getBackgroundTask(e),...t})},vsr=(e,t)=>["browser-session-probe",e,t],ysr={hasSession:!0,screencastAvailable:!0},xsr=e=>!e||typeof e!="object"?!1:"status"in e&&e.status===404||"statusCode"in e&&e.statusCode===404;function bsr({agentId:e,threadId:t,queryOptions:n}){const r=Ye();return kt({queryKey:vsr(e,t),queryFn:async()=>{if(!e)return{hasSession:!1,screencastAvailable:!1};try{return await r.getAgent(e).browserSession(t)}catch(s){if(xsr(s))return ysr;throw s}},refetchOnWindowFocus:!0,staleTime:0,retry:1,...n})}const wsr="MODEL_NOT_ALLOWED";function Ssr(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!==wsr)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 dC=({queryOptions:e,...t}={})=>{const n=Ye(),r=Object.keys(t).length>0?t:void 0;return kt({queryKey:["stored-agents",r],queryFn:()=>n.listStoredAgents(r),...e})},jG=({agentId:e,status:t,requestContext:n,queryOptions:r}={})=>{const s=Ye();return kt({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})},uSe=({agentId:e,requestContext:t,queryOptions:n}={})=>{const r=Ye();return kt({queryKey:["stored-agent-dependents",e,t],queryFn:()=>r.getStoredAgent(e).dependents(t),retry:!1,...n})},fC=({agentId:e,requestContext:t,queryOptions:n}={})=>{const r=Ye(),s=yr(),i=o=>{Ssr(o)&&s.invalidateQueries({queryKey:["builder-settings"]})};return{createStoredAgent:kn({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:kn({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:kn({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})}},mL=({agentId:e,params:t,requestContext:n,queryOptions:r})=>{const s=Ye();return kt({queryKey:["agent-versions",e,t,n],queryFn:e?()=>s.getStoredAgent(e).listVersions(t,n):k0,...r})},O1t=({agentId:e,versionId:t,requestContext:n,queryOptions:r})=>{const s=Ye();return kt({queryKey:["agent-version",e,t,n],queryFn:()=>s.getStoredAgent(e).getVersion(t,n),...r})},ksr=({agentId:e,fromVersionId:t,toVersionId:n,requestContext:r,queryOptions:s})=>{const i=Ye();return kt({queryKey:["agent-versions-compare",e,t,n,r],queryFn:()=>i.getStoredAgent(e).compareVersions(t,n,r),...s})};function I7e(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Osr(e,t,n,r){const s=Ye(),[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 I="";C?I=I7e(C):_?.content?I=I7e(_.content):I="",c(I)}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 md=({agentId:e,requestContext:t,queryOptions:n}={})=>{const r=Ye();return kt({queryKey:["agent",e,t],queryFn:()=>e?r.getAgent(e).details(t):null,retry:!1,...n})},pf=({requestContext:e,queryOptions:t}={})=>{const n=Ye();return kt({queryKey:["agents",e],queryFn:()=>n.listAgents(e),...t})},jsr=({agentId:e,queryOptions:t})=>{const n=Ye(),r=yr();return kn({mutationFn:async s=>n.getAgent(e).reorderModelList(s),onSuccess:()=>{r.invalidateQueries({queryKey:["agent",e]})},onError:s=>{console.error("Error reordering model list",s)},...t})},Csr=({agentId:e,queryOptions:t})=>{const n=Ye(),r=yr();return kn({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 _sr({queryOptions:e}={}){const t=Ye();return kn({mutationFn:({agentId:n,threadId:r})=>t.getAgent(n).closeBrowser(r),onError:n=>{console.error("[useCloseBrowser] Error closing browser:",n)},...e})}function sk({queryOptions:e}={}){const t=Ye();return kt({queryKey:["stored-skills"],queryFn:()=>t.listStoredSkills(),...e})}const CG=({queryOptions:e}={})=>{const t=Ye();return kt({queryKey:["channels","platforms"],queryFn:()=>t.channels.listPlatforms(),staleTime:60*1e3,retry:!1,...e})},j1t=({platform:e,agentId:t,queryOptions:n})=>{const r=Ye();return kt({queryKey:["channels","installations",e,t],queryFn:()=>r.channels.listInstallations(e,t),staleTime:10*1e3,retry:!1,...n})},Tsr=({platform:e,queryOptions:t})=>{const n=Ye(),r=yr();return kn({mutationFn:s=>n.channels.reconcileInstallation(e,s),onSuccess:()=>{r.invalidateQueries({queryKey:["channels","installations",e]})},...t})},Esr=({platform:e,queryOptions:t})=>{const n=Ye(),r=yr();return kn({mutationFn:({agentId:s,options:i})=>n.channels.connect(e,s,{...i,redirectUrl:window.location.href}),onSuccess:()=>{r.invalidateQueries({queryKey:["channels","installations",e]})},...t})},C1t=({platform:e,queryOptions:t})=>{const n=Ye(),r=yr();return kn({mutationFn:s=>n.channels.disconnect(e,s),onSuccess:()=>{r.invalidateQueries({queryKey:["channels","installations",e]})},...t})},Isr=({queryOptions:e}={})=>{const t=Ye();return kn({mutationFn:async({agentId:n,toolId:r,input:s,playgroundRequestContext:i})=>{const o=new RC;return Object.entries(i??{}).forEach(([l,c])=>{o.set(l,c)}),t.getAgent(n).executeTool(r,{data:s,requestContext:o})},...e})};function Nsr({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}=pf(),{navigate:v,paths:y}=hn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load agents";Ge.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(Ca,{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 Asr(){const{agentId:e}=fr(),{data:t,isLoading:n}=pf();return e?n?a.jsx(Ox,{}):t?.[e]?.name||e:null}function Psr(){const{toolId:e}=fr();return e??null}function $sr(){const{agentId:e}=fr();return e?a.jsx(Nsr,{value:e,...l_,"aria-label":"Switch agent"}):null}const _1t=({datasetId:e,itemId:t,queryOptions:n})=>{const r=Ye();return kt({queryKey:["dataset-item",e,t],queryFn:()=>r.getDatasetItem(e,t),retry:!1,...n})},N7e=10,_N=({datasetId:e,search:t,version:n,orderBy:r,queryOptions:s})=>{const i=Ye(),{inView:o,setRef:l}=E0(),c=Am({queryKey:["dataset-items",e,t,n,r],queryFn:async({pageParam:f})=>await i.listDatasetItems(e,{page:f,perPage:N7e,search:t||void 0,version:n||void 0,orderBy:r}),initialPageParam:0,getNextPageParam:(f,h,p)=>{if(f?.items?.length&&!((p+1)*N7e>=(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}},ul=({queryOptions:e}={})=>{const t=Ye(),n=yr(),r=kn({mutationFn:h=>t.createDataset(h),onSuccess:()=>{n.invalidateQueries({queryKey:["datasets"]})},...e?.createDataset}),s=kn({mutationFn:h=>t.updateDataset(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["datasets"]}),n.invalidateQueries({queryKey:["dataset",p.datasetId]})},...e?.updateDataset}),i=kn({mutationFn:h=>t.deleteDataset(h),onSuccess:()=>{n.invalidateQueries({queryKey:["datasets"]})},...e?.deleteDataset}),o=kn({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=kn({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=kn({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=kn({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=kn({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=kn({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:kn({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:kn({mutationFn:h=>t.triggerDatasetExperiment(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["dataset-experiments",p.datasetId]})},...e?.triggerExperiment}),deleteExperiment:kn({mutationFn:h=>t.deleteExperiment(h),onSuccess:()=>{n.invalidateQueries({queryKey:["experiments"]}),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:kn({mutationFn:h=>t.updateDatasetExperiment(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["experiments"]}),n.invalidateQueries({queryKey:["dataset-experiments",p.datasetId]}),n.invalidateQueries({queryKey:["dataset-experiment",p.datasetId,p.experimentId]})},...e?.updateExperiment}),updateExperimentResult:kn({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})}},ik=({pagination:e,queryOptions:t}={})=>{const n=Ye();return kt({queryKey:["datasets",e],queryFn:()=>n.listDatasets(e),placeholderData:r=>r,...t})},Rsr=20,Msr=({filter:e,orderBy:t,queryOptions:n}={})=>{const r=Ye(),{inView:s,setRef:i}=E0(),o=e?.targetType||void 0,l=e?.targetId?[e.targetId]:void 0,c=Am({queryKey:["datasets","infinite",{targetType:o,targetIds:l,orderBy:t}],queryFn:({pageParam:u})=>r.listDatasets({page:u,perPage:Rsr,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}},Tv=({datasetId:e,queryOptions:t})=>{const n=Ye();return kt({queryKey:["dataset",e],queryFn:()=>n.getDataset(e),...t})},Dsr=({datasetId:e,experimentIdA:t,experimentIdB:n,options:r,queryOptions:s})=>{const i=Ye();return kt({queryKey:["compare-experiments",e,t,n,r],queryFn:()=>i.compareExperiments({datasetId:e,experimentIdA:t,experimentIdB:n,...r}),...s})},G4=({datasetId:e,experimentId:t,queryOptions:n})=>{const r=Ye();return kt({queryKey:["dataset-experiment",e,t],queryFn:()=>r.getDatasetExperiment(e,t),gcTime:0,staleTime:0,refetchInterval:s=>{const i=s.state.data?.status;return i==="running"||i==="pending"?2e3:!1},...n})},A7e=100,zhe=({datasetId:e,experimentId:t,experimentStatus:n,orderBy:r,queryOptions:s})=>{const i=Ye(),{inView:o,setRef:l}=E0(),c=Am({queryKey:["dataset-experiment-results",e,t,n,r],queryFn:async({pageParam:u})=>i.listDatasetExperimentResults(e,t,{page:u,perPage:A7e,orderBy:r}),initialPageParam:0,getNextPageParam:(u,d,f)=>{if(u?.results?.length&&!((f+1)*A7e>=(u?.pagination?.total??0)))return f+1},refetchInterval:n==="running"||n==="pending"?2e3:!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}},yS=({experimentId:e,experimentStatus:t,queryOptions:n})=>{const r=Ye();return kt({queryKey:["dataset-experiment-scores",e,t],queryFn:async()=>{const s=[];let i=0;const o=100;for(;;){const c=await r.listScoresByRunId({runId:e,page:i,perPage:o});if(s.push(...c.scores),!c.pagination.hasMore)break;i++}const l={};for(const c of s)l[c.entityId]||(l[c.entityId]=[]),l[c.entityId].push(c);return l},refetchInterval:t==="running"||t==="pending"?2e3:!1,...n})},Lsr=({datasetId:e,itemId:t,queryOptions:n})=>{const r=Ye();return kt({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})},zsr=({datasetId:e,itemId:t,datasetVersion:n,latestVersion:r,queryOptions:s})=>{const i=Ye();return kt({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})},Fsr=10,T1t=({datasetId:e,queryOptions:t})=>{const n=Ye();return Am({queryKey:["dataset-versions",e],queryFn:async({pageParam:r})=>n.listDatasetVersions(e,{page:r,perPage:Fsr}),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})},dSe=({pagination:e,queryOptions:t}={})=>{const n=Ye();return kt({queryKey:["experiments",e],queryFn:()=>n.listExperiments(e),...t})};function Bsr({workflowId:e,queryOptions:t}){const n=Ye();return kt({queryKey:["workflow-schema",e],queryFn:async()=>{if(!e)throw new Error("No workflow selected");return n.getWorkflow(e).getSchema()},staleTime:300*1e3,...t})}function E1t({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}=ik(),{navigate:y,paths:x}=hn();g.useEffect(()=>{if(m){const j=v instanceof Error?v.message:"Failed to load datasets";Ge.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(Ca,{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 Vsr(){const{datasetId:e}=fr(),{data:t,isLoading:n}=ik();return e?n?a.jsx(Ox,{}):t?.datasets?.find(r=>r.id===e)?.name??e:null}function Usr(){const{datasetId:e}=fr();return e?a.jsx(E1t,{value:e,...l_,"aria-label":"Switch dataset"}):null}function I1t({queryOptions:e}={}){const t=Ye();return kt({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 fSe=({serverId:e,toolId:t,requestContext:n,queryOptions:r})=>{const s=Ye();return kt({queryKey:["mcp-server-tool",e,t],queryFn:()=>s.getMcpServerTool(e,t).details(n),...r})},qsr=({serverId:e,toolId:t,queryOptions:n})=>{const r=Ye();return kn({mutationFn:({data:s,requestContext:i})=>r.getMcpServerTool(e,t).execute({data:s,requestContext:i}),...n})},N1t=({selectedServer:e,queryOptions:t})=>{const n=Ye();return kt({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})},rP=({requestContext:e,queryOptions:t}={})=>{const n=Ye();return kt({queryKey:["mcp-servers"],queryFn:async()=>(await n.getMcpServers(e)).servers,...t})};async function P7e(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 Qsr(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 P7e(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 P7e(o)).result?.tools??[]}}const Zsr=({queryOptions:e}={})=>{const t=Ye().options?.headers??{};return kn({mutationFn:n=>Qsr(n,t),...e})};function A1t({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}=rP(),{navigate:y,paths:x}=hn();g.useEffect(()=>{if(m){const k=v instanceof Error?v.message:"Failed to load MCP servers";Ge.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(Ca,{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 Wsr(){const{serverId:e}=fr(),{data:t,isLoading:n}=rP();return e?n?a.jsx(Ox,{}):t?.find(r=>r.id===e)?.name||e:null}function Hsr(){const{serverId:e}=fr();return e?a.jsx(A1t,{value:e,...l_,"aria-label":"Switch MCP server"}):null}function Gsr(){const{serverId:e,toolId:t}=fr(),{data:n}=fSe({serverId:e??"",toolId:t??"",queryOptions:{enabled:!!e&&!!t}});return n?.name??t??null}const c_=({requestContext:e,queryOptions:t}={})=>{const n=Ye();return kt({queryKey:["processors"],queryFn:()=>n.listProcessors(e),...t})},P1t=({processorId:e,requestContext:t,queryOptions:n})=>{const r=Ye();return kt({queryKey:["processor",e],queryFn:()=>r.getProcessor(e).details(t),...n})},Ksr=({requestContext:e,queryOptions:t}={})=>{const n=Ye();return kn({mutationFn:async({processorId:r,phase:s,messages:i,agentId:o})=>n.getProcessor(r).execute({phase:s,messages:i,agentId:o,requestContext:e}),...t})};function Ysr({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}=c_(),{navigate:v,paths:y}=hn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load processors";Ge.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(Ca,{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 Xsr(){const{processorId:e}=fr(),{data:t,isLoading:n}=c_();return e?n?a.jsx(Ox,{}):t?.[e]?.name||e:null}function Jsr(){const{processorId:e}=fr();return e?a.jsx(Ysr,{value:e,...l_,"aria-label":"Switch processor"}):null}const Nie=[400,401,403,404,501];function _s(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 Ts(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 ok(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 gL(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 eir=["Observability storage domain is not available","Scores storage domain is not available"];function vL(e){if(!e||typeof e!="object"||!("message"in e))return!1;const t=e.message;return typeof t!="string"?!1:eir.some(n=>t.includes(n))}function $1t(e){if(!e||typeof e!="object")return!1;if("status"in e){const t=e.status;return Nie.includes(t)}if("statusCode"in e){const t=e.statusCode;return Nie.includes(t)}if("message"in e){const t=e.message;if(typeof t=="string")return Nie.some(n=>new RegExp(`\\bstatus:\\s*${n}\\b`).test(t))}return!1}function tir(e,t){return $1t(t)?!1:e<3}const nir=25,rir=15e3;function sir(e){return gL(e.state.error,"scores")||vL(e.state.error)?!1:rir}function iir(e,t,n){if(e?.pagination?.hasMore)return n+1}function oir(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 air=({scorerId:e,entityId:t,entityType:n,queryOptions:r})=>{const s=Ye(),{inView:i,setRef:o}=E0(),l=Am({queryKey:["scores",e,t,n],queryFn:({pageParam:f})=>s.listScoresByScorerId({scorerId:e,page:f,perPage:nir,entityId:t,entityType:n}),initialPageParam:0,getNextPageParam:iir,select:f=>oir(f),refetchInterval:sir,...r}),{hasNextPage:c,isFetchingNextPage:u,fetchNextPage:d}=l;return g.useEffect(()=>{i&&c&&!u&&d()},[i,c,u,d]),{...l,setEndOfListElement:o}},lir=e=>{const t=Ye(),[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}},R1t=({requestContext:e,queryOptions:t}={})=>{const n=Ye();return kt({queryKey:["scorers",e],queryFn:()=>n.listScorers(e),staleTime:0,gcTime:0,...t})},cir=15e3;function uir(e){return gL(e.state.error,"scores")||vL(e.state.error)?!1:cir}const hSe=({traceId:e="",spanId:t="",page:n,queryOptions:r})=>{const s=Ye();return kt({queryKey:["trace-span-scores",e,t,n],queryFn:()=>s.listScoresBySpan({traceId:e,spanId:t,page:n||0,perPage:10}),refetchInterval:uir,gcTime:0,staleTime:0,...r})},dir=({queryOptions:e}={})=>{const t=Ye();return kn({mutationFn:async({scorerName:n,traceId:r,spanId:s})=>await t.score({scorerName:n,targets:[{traceId:r,spanId:s}]}),...e})},M1t=({scorerId:e,status:t,requestContext:n,queryOptions:r}={})=>{const s=Ye();return kt({queryKey:["stored-scorer",e,t,n],queryFn:()=>e?s.getStoredScorer(e).details(n,{status:t}):null,...r})},D1t=({scorerId:e,requestContext:t,queryOptions:n}={})=>{const r=Ye(),s=yr();return{createStoredScorer:kn({mutationFn:i=>r.createStoredScorer(i),onSuccess:()=>{s.invalidateQueries({queryKey:["stored-scorers"]}),s.invalidateQueries({queryKey:["scorers"]})},...n?.createStoredScorer}),updateStoredScorer:kn({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:kn({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})}},L1t=({scorerId:e,params:t,requestContext:n,queryOptions:r})=>{const s=Ye();return kt({queryKey:["scorer-versions",e,t,n],queryFn:()=>s.getStoredScorer(e).listVersions(t,n),...r})},fir=({scorerId:e,versionId:t,requestContext:n,queryOptions:r})=>{const s=Ye();return kt({queryKey:["scorer-version",e,t,n],queryFn:()=>s.getStoredScorer(e).getVersion(t,n),...r})},eg=(e,t)=>R1t({...e,requestContext:t});function hir({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}=eg(),{navigate:v,paths:y}=hn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load scorers";Ge.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(Ca,{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 pir(){const{scorerId:e}=fr(),{data:t,isLoading:n}=eg();return e?n?a.jsx(Ox,{}):t?.[e]?.scorer.config.name||e:null}function mir(){const{scorerId:e}=fr();return e?a.jsx(hir,{value:e,...l_,"aria-label":"Switch scorer"}):null}function gir(){const{scorerId:e}=fr(),{data:t,isLoading:n}=M1t({scorerId:e,status:"draft",queryOptions:{enabled:!!e}});return e?n?a.jsx(Ox,{}):t?.name??"Scorer not found":null}const sP=({requestContext:e,queryOptions:t}={})=>{const n=Ye();return kt({queryKey:["tools",e],queryFn:()=>n.listTools(e),...t})},vir=({toolId:e,requestContext:t,queryOptions:n})=>{const r=Ye();return kt({queryKey:["tool",e,t],queryFn:()=>r.getTool(e).details(t),...n})},yir=({queryOptions:e}={})=>{const t=Ye();return kn({mutationFn:async({toolId:n,input:r,requestContext:s})=>{const i=new RC;return Object.entries(s??{}).forEach(([o,l])=>{i.set(o,l)}),t.getTool(n).execute({data:r,requestContext:i})},...e})};function xir({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:i,disabled:o=!1,variant:l,size:c,"aria-label":u,align:d}){const{data:f={},isLoading:h,isError:p,error:m}=sP(),{data:v={},isLoading:y,isError:x,error:b}=pf(),{navigate:S,paths:k}=hn();g.useEffect(()=>{if(p){const _=m instanceof Error?m.message:"Failed to load tools";Ge.error(`Error loading tools: ${_}`)}},[p,m]),g.useEffect(()=>{if(x){const _=b instanceof Error?b.message:"Failed to load agents";Ge.error(`Error loading agents: ${_}`)}},[x,b]);const j=new Map;Object.values(v).forEach(_=>{_.tools&&Object.values(_.tools).forEach(N=>{j.has(N.id)||j.set(N.id,N)})}),Object.values(f).forEach(_=>{j.has(_.id)||j.set(_.id,_)});const C=Array.from(j.values()).map(_=>({label:_.id,value:_.id})),T=_=>{t?t(_):_&&_!==e&&S(k.toolLink(_))};return a.jsx(Ca,{options:C,value:e,onValueChange:T,placeholder:h||y?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||h||y||p||x,variant:l,size:c,"aria-label":u,align:d})}function bir(){const{toolId:e}=fr();return e??null}function wir(){const{toolId:e}=fr();return e?a.jsx(xir,{value:e,...l_,"aria-label":"Switch tool"}):null}const zo=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"})]}),pSe=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"})}),Sir=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"})}),kir=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"})]}),u_=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"})]}),Oir=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 AO(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 jir=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"})}),jx=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"})]}),Cir=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"})}),of=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"})}),ox=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"})]}),_ir=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"})}),Tir=typeof window<"u"&&window.MASTRA_SIGNALS_UI==="true",Eir={name:"Intelligence",url:"/intelligence",activePaths:["/intelligence"],Icon:xdt,isOnMastraPlatform:!0,hidden:!Tir},mSe=[{key:"primitives",title:"Primitives",items:[{name:"Agents",url:"/agents",Icon:zo,isOnMastraPlatform:!0},{name:"Prompts",url:"/prompts",Icon:jir,isOnMastraPlatform:!0},{name:"Workflows",url:"/workflows",Icon:xl,isOnMastraPlatform:!0},{name:"Processors",url:"/processors",Icon:AO,isOnMastraPlatform:!1,foldable:!0},{name:"MCP Servers",url:"/mcps",Icon:u_,isOnMastraPlatform:!0,foldable:!0},{name:"Tools",url:"/tools",Icon:of,isOnMastraPlatform:!0,foldable:!0},{name:"Workspaces",url:"/workspaces",Icon:_ir,isOnMastraPlatform:!0,foldable:!0}]},{key:"evaluation",title:"Evaluation",items:[{name:"Scorers",url:"/scorers",Icon:jx,isOnMastraPlatform:!0},{name:"Datasets",url:"/datasets",Icon:pSe,isOnMastraPlatform:!0},{name:"Experiments",url:"/experiments",Icon:Sir,isOnMastraPlatform:!0},{name:"Review Queue",url:"/experiments/review-queue",Icon:E3,isOnMastraPlatform:!0}]},{key:"observability",title:"Observability",items:[{name:"Metrics",url:"/metrics",Icon:Oir,isOnMastraPlatform:!0},{name:"Traces",url:"/traces",Icon:ox,isOnMastraPlatform:!0},Eir,{name:"Logs",url:"/logs",Icon:kir,isOnMastraPlatform:!0}]}],gSe=[{name:"Settings",url:"/settings",Icon:Cir,isOnMastraPlatform:!1},{name:"Resources",url:"/resources",Icon:ndt,isOnMastraPlatform:!0}],Iir=[...mSe.flatMap(e=>e.items),...gSe];function Nir(e){return Iir.find(t=>t.url===e)}function hs(e,t){const n=Nir(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 vSe=e=>{if(!e)return"";try{return decodeURIComponent(e)}catch{return e}},ySe=e=>{const t=vSe(e);return t.length>8?`${t.slice(0,8)}...`:t},xSe={id:"agent",Component:Asr,Switcher:$sr},Air={id:"scorer",Component:pir,Switcher:mir},Pir={id:"tool",Component:bir,Switcher:wir},$ir={id:"processor",Component:Xsr,Switcher:Jsr},z1t={id:"mcp-server",Component:Wsr,Switcher:Hsr},$7e={id:"workflow",Component:rsr,Switcher:ssr},_G={id:"dataset",Component:Vsr,Switcher:Usr},F1t={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 Aie=null;function Rir(){return Aie||(Aie=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Ii(()=>import("./core-DbjTmJHj.js"),__vite__mapDeps([0,1,2,3,4]),import.meta.url),Ii(()=>import("./engine-javascript-DSQaR0Yq.js"),__vite__mapDeps([5,2,3]),import.meta.url)]);return e({themes:[Ii(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Ii(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Ii(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Ii(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Ii(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Ii(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Ii(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Ii(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Ii(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Ii(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Ii(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Ii(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Ii(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Ii(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([6,7,8]),import.meta.url),Ii(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Ii(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Aie}async function Mir(e,t){const n=F1t[t?.toLowerCase()];if(!n)return null;const r=await Rir(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function B1t(e){const t=e?.split(".").pop()?.toLowerCase();return t?F1t[t]:void 0}function Dir({children:e,tooltip:t}){const r=`${typeof e=="string"?e.replace(/\s*\([^)]*\)/g,""):"Request context"} details`;return a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(lt,{children:e}),t&&a.jsx(pc,{delay:10,children:a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("button",{type:"button","aria-label":r,className:Z(Fn,On,"rounded-sm",$i),children:a.jsx(Nt,{size:"xs",children:a.jsx(op,{})})})}),a.jsx(Nn,{side:"top",className:"max-w-60",children:t})]})})]})}let R7e;const V1t=()=>R7e??=Promise.all([Ii(()=>import("./standalone-Dfz2oS5J.js"),[],import.meta.url),Ii(()=>import("./babel-lWBcy2sH.js"),[],import.meta.url),Ii(()=>import("./estree-Dd9JfUIE.js"),[],import.meta.url)]).catch(e=>{throw R7e=void 0,e}),K4=async e=>{const[t,n,r]=await V1t();return await t.format(e,{semi:!1,parser:"json",printWidth:80,tabWidth:2,plugins:[n,r]})},U1t=async e=>{const[t,n,r]=await V1t();return await t.format(e,{parser:"babel-ts",printWidth:80,tabWidth:2,plugins:[n,r]})},Eq=e=>{try{const t=JSON.parse(e);return!!t&&typeof t=="object"}catch{return!1}},Lir=Oi(vt(),kPn());function Pie(e,t){if(!e)return"__custom__";for(const[n,r]of Object.entries(e))if(JSON.stringify(r)===t)return n;return"__custom__"}function zir(e){try{return JSON.stringify(JSON.parse(e))}catch{return null}}const q1t=({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(()=>Pie(t,l)),{handleCopy:v}=Mm({text:u}),[y,x]=g.useState(l);y!==l&&(x(l),d(c),h(c),m(Pie(t,l)));const b=g.useMemo(()=>{const N=zir(u);return N?N!==l:u!==f},[l,u,f]),S=()=>{let N;try{N=JSON.parse(u)}catch{Ge.error("Invalid JSON");return}const I=Lir.safeParse(N);if(!I.success){Ge.error(`${e} must be a JSON object`);return}r(I.data)},k=()=>{d(f),m(Pie(t,l))},j=Z(Fn,On),C=async()=>{if(!Eq(u)){Ge.error("Invalid JSON");return}const N=await K4(u);d(N)},T=async N=>{if(m(N),N==="__custom__"||!t)return;const I=t[N];if(I){const P=await K4(JSON.stringify(I));d(P)}},_=N=>{d(N),p!=="__custom__"&&m("__custom__")};return a.jsx(pc,{children:a.jsxs("div",{children:[a.jsxs(ft,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs(Dir,{tooltip:i,children:[e," (JSON)"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[o,a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("button",{type:"button",onClick:C,className:j,children:a.jsx(Nt,{children:a.jsx(al,{})})})}),a.jsxs(Nn,{children:["Format the ",e," JSON"]})]}),a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("button",{type:"button",onClick:v,className:j,children:a.jsx(Nt,{children:a.jsx($m,{})})})}),a.jsxs(Nn,{children:["Copy ",e]})]})]})]}),t&&Object.keys(t).length>0&&a.jsxs(ft,{children:[a.jsxs(lt,{className:"sr-only",children:[e," preset"]}),a.jsxs(Ur,{value:p,onValueChange:T,children:[a.jsx(Qr,{children:a.jsx(qr,{placeholder:"Select a preset..."})}),a.jsxs(Zr,{children:[a.jsx(or,{value:"__custom__",children:"Custom"}),Object.keys(t).map(N=>a.jsx(or,{value:N,children:N},N))]})]})]}),a.jsx(Cr,{value:u,onChange:_,showCopyButton:!1,className:s})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[b&&a.jsx(de,{variant:"default",size:"icon-md",type:"button",tooltip:`Revert ${e} changes`,onClick:k,children:a.jsx(Ln,{})}),a.jsx(de,{icon:a.jsx(pr,{}),type:"button",onClick:S,children:"Save"})]})]})})},Fir={align:"shift"};function Q1t({label:e,icon:t,open:n,onOpenChange:r,children:s}){return a.jsxs(bp,{open:n,onOpenChange:r,children:[a.jsx(rf,{variant:"ghost",size:"icon-md",type:"button",tooltip:e,"aria-label":e,children:t}),a.jsx(nh,{align:"start",collisionAvoidance:Fir,className:"w-[min(480px,calc(100vw-2rem))] p-0",children:a.jsx("div",{onSubmit:i=>i.stopPropagation(),children:a.jsx(Nr,{className:"w-full",maxHeight:"min(600px, calc(100dvh - 8rem))",children:a.jsx("div",{className:"space-y-4 p-4",children:s})})})})]})}function Bir(){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 bSe({entityType:e,entityId:t}){const[n,r]=g.useState(!1),[s,i]=wr(e,t),o=Bir(),l=c=>{i(c),Ge.success("Request context saved locally"),r(!1)};return a.jsx(Q1t,{label:"Request context",icon:a.jsx(Qjn,{}),open:n,onOpenChange:r,children:a.jsx(q1t,{label:"Request Context",presets:o,value:s,onSave:l,editorClassName:"h-[260px]"})})}function Z1t({entityType:e,entityId:t,extraFields:n,onSaveExtra:r,onOpenChange:s}){const[i,o]=g.useState(!1),[l,c]=eSe(e,t),u=f=>{o(f),s?.(f)},d=f=>{c(f),r?.(),Ge.success("Run options saved locally"),u(!1)};return a.jsxs(Q1t,{label:"Run options",icon:a.jsx(ox,{}),open:i,onOpenChange:u,children:[n,a.jsx(q1t,{label:"Tracing Options",value:l,onSave:d,editorClassName:"h-[260px]"})]})}function Vir({workflowId:e,resourceId:t,setResourceId:n}){const[r,s]=g.useState(t);return a.jsxs(a.Fragment,{children:[a.jsx(bSe,{entityType:"workflow",entityId:e}),a.jsx(Z1t,{entityType:"workflow",entityId:e,onOpenChange:i=>{i&&s(t)},onSaveExtra:()=>n(r),extraFields:a.jsxs(ft,{children:[a.jsx(lt,{children:"Resource ID"}),a.jsx(Sn,{value:r,onChange:i=>s(i.target.value),placeholder:"e.g. tenant-42"}),a.jsx(eo,{children:"Ignored when server auth derives the resource ID from the user."})]})})]})}function Iq({icon:e,label:t,tooltipContent:n,docsHref:r}){return a.jsxs($n,{children:[a.jsx(In,{render:a.jsx("span",{role:"button",tabIndex:0,"aria-disabled":"true","aria-label":t,className:"inline-flex",children:a.jsx(de,{variant:"ghost",size:"icon-md",disabled:!0,"aria-hidden":"true",tabIndex:-1,children:e})})}),a.jsx(Nn,{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",On),children:["Learn more",a.jsx(Vs,{className:"size-3"})]})]})})]})}const Uir=({scheduleId:e,queryOptions:t})=>{const n=Ye();return kt({queryKey:["schedule",e],queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return n.getSchedule(e)},...t})},TG=({queryOptions:e,...t}={})=>{const n=Ye();return kt({queryKey:["schedules",t],queryFn:async()=>(await n.listSchedules(t)).schedules,...e})},M7e=25,qir=({scheduleId:e,queryOptions:t})=>{const n=Ye(),{inView:r,setRef:s}=E0(),i=Am({queryKey:["schedule-triggers",e],initialPageParam:void 0,queryFn:async({pageParam:d})=>e?n.listScheduleTriggers(e,{limit:M7e,toActualFireAt:d}):{triggers:[]},getNextPageParam:d=>{if(!(!d?.triggers?.length||d.triggers.length<M7e))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}},Qir=({scheduleId:e,queryOptions:t})=>{const n=Ye(),r=yr();return kn({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 $ie({value:e,icon:t,label:n}){return a.jsxs(ls,{value:e,children:[a.jsx(Nt,{size:"xs",children:t}),a.jsx(Y,{variant:"caption",className:"text-inherit",children:n})]})}function Zir({workflowId:e,activeTab:t,showObservability:n=!1}){const{navigate:r}=hn(),{data:s,isSuccess:i}=TG({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(Hl,{value:t,defaultTab:t,onValueChange:u,className:"min-w-0",children:a.jsxs(Gl,{variant:"pill-ghost",children:[a.jsx($ie,{value:"graph",icon:a.jsx(xl,{}),label:"Graph"}),n&&a.jsx($ie,{value:"traces",icon:a.jsx(ox,{}),label:"Traces"}),!d&&a.jsx($ie,{value:"schedules",icon:a.jsx(i0,{}),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(Iq,{icon:a.jsx(ox,{}),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(Iq,{icon:a.jsx(i0,{}),label:"Schedules",tooltipContent:"Configure a schedule on this workflow to enable Schedules.",docsHref:"https://mastra.ai/docs/workflows/scheduled-workflows"})]})]})}const Wir=({children:e})=>{const{workflowId:t,runId:n}=fr();return a.jsx(Jbe,{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(Kir,{children:e})})},Hir=e=>e==="graph"||e==="traces"||e==="schedules",Gir=({workflowId:e})=>{const t=Lr();return C0({"g$+t":()=>t(`/workflows/${encodeURIComponent(e)}/traces`)}),null};function Kir({children:e}){const{workflowId:t,runId:n}=fr(),r=Dxe("/workflows/:workflowId/:tab/*"),{isLoading:s}=L3({workflowId:t,requestContext:wr("workflow",t)[0],queryOptions:{enabled:!!t}}),{hasObservability:i}=k1t(),o=Hir(r?.params.tab)?r.params.tab:"none",l=[hs("/workflows"),n?{...$7e,to:`/workflows/${encodeURIComponent(t??"")}/graph`}:$7e,...n?[{id:"workflow-run",Component:isr,Action:osr}]:[]];if(!t)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{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(St,{breadcrumbs:a.jsx(Pt,{crumbs:l}),children:[a.jsx("h1",{className:"sr-only",children:t}),a.jsx(bt,{className:"h-full"})]});const c=u=>a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:l}),headerActions:a.jsx(lsr,{}),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(Zir,{workflowId:t,activeTab:o,showObservability:i}),u]})]});return a.jsxs(gtt,{children:[a.jsx(Gir,{workflowId:t}),o==="graph"?a.jsx(Hwt,{children:a.jsx(nSe,{workflowId:t,initialRunId:n,children:a.jsx(Wwt,{children:c(a.jsx(lrr,{leftSlot:a.jsx(Yir,{workflowId:t,initialRunId:n}),children:e}))})})},t):c(e)]})}function Yir({workflowId:e,initialRunId:t}){const[n]=wr("workflow",e),{canExecute:r,canDelete:s}=Ta();return a.jsx(prr,{workflowId:e,initialRunId:t,requestContext:n,runActionsSlot:i=>a.jsx(Vir,{workflowId:e,...i}),canExecute:r("workflows"),canDelete:s("workflows")})}const W1t=dd(Z(hr,"rounded-xl transition-all duration-normal ease-out-custom motion-reduce:transition-none"),{variants:{elevation:{flat:"shadow-none",raised:""},interactive:{true:Z(AA,Ebe,"cursor-pointer active:scale-99"),false:""}},compoundVariants:[{elevation:"flat",interactive:!0,class:yx}],defaultVariants:{elevation:"raised",interactive:!1}}),hc=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(W1t({elevation:t,interactive:n}),e),...s})});hc.displayName="Card";function H1t({className:e,elevation:t,LinkComponent:n="a",...r}){return a.jsx(n,{className:Z(W1t({elevation:t,interactive:!0}),e),...r})}const Nq=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}));Nq.displayName="CardHeader";const ak=g.forwardRef(({className:e,...t},n)=>a.jsx("h3",{ref:n,className:Z("text-subheading text-foreground",e),...t}));ak.displayName="CardTitle";const vj=g.forwardRef(({className:e,...t},n)=>a.jsx("p",{ref:n,className:Z("text-caption text-muted-foreground",e),...t}));vj.displayName="CardDescription";const Xir=dd("",{variants:{density:{default:"p-3",compact:"p-2"}},defaultVariants:{density:"default"}}),dv=g.forwardRef(({className:e,density:t,...n},r)=>a.jsx("div",{ref:r,className:Z(Xir({density:t}),e),...n}));dv.displayName="CardContent";const Jir=g.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,className:Z("flex items-center p-3 pt-0",e),...t}));Jir.displayName="CardFooter";const D7e=["blue","green","orange","purple","pink","amber","cyan"];function wSe(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 iP=e=>D7e[wSe(e)%D7e.length]??"blue",Di=e=>`var(--badge-${e}-indicator)`,eor={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"},G1t=e=>eor[e],tor=e=>({background:`var(--badge-${e}-strong)`,foreground:`var(--badge-${e}-foreground)`,tint:`var(--badge-${e}-indicator)`}),L7e={goal:"green",outcome:"orange",behavior:"blue",sentiment:"purple"},z7e=["pink","amber"],nor={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"},ror={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 SSe(e){const t=e.toLowerCase();return(Object.hasOwn(L7e,t)?L7e[t]:void 0)??z7e[wSe(t)%z7e.length]??"pink"}function Cx(e){return`var(--chart-${SSe(e)})`}function K1t(e){return nor[SSe(e)]}function sor(e){return ror[SSe(e)]}const oP=[{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"}];oP.map(e=>e.name);Object.fromEntries(oP.map(e=>[e.name,e.description]));function yL(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 cp(e,t){return e.find(n=>n.name===t)?.label??ior(t)}function xS(e,t){return e.find(n=>n.name===t)?.description||void 0}function ior(e){return e.split(/[-_]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function EG(e){return`${e} ${e===1?"trace":"traces"}`}function oor(e){return`${e} ${e===1?"theme":"themes"}`}function Y1t(e,t){if(t<=0)return`${EG(e)} in this snapshot`;const n=Math.round(e/t);return`${e} of ${n} traces in this snapshot (${Math.round(t*100)}%)`}const kSe={timeZone:"UTC"};function Y4(e){return dI(e,{...kSe,now:0})??e}function IG(e){return is(e,"date-time",kSe)??e}function Fhe(e,t){return xGn(e,t,kSe)??`${e}–${t}`}const aor=[["chat.completion","1.2s"],["tool.search_docs","340ms"],["workflow.support","2.8s"]],Aq=e=>({color:Cx(e)}),F7e=()=>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 X4(e){return new Intl.NumberFormat("en-US").format(e)}function lor(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 cor({progress:e}){const t=e.signalCatalog??oP,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(hr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:$l({tone:"muted",variant:"caption"}),children:"Traces analyzed"}),a.jsx("dd",{className:Z($l({tone:"ink",variant:"heading"}),"mt-1"),children:X4(e.traceCount)})]}),a.jsxs("div",{className:Z(hr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:$l({tone:"muted",variant:"caption"}),children:"Trace signal types ready"}),a.jsxs("dd",{className:Z($l({tone:"ink",variant:"heading"}),"mt-1"),children:[e.signalCatalog?r:e.availableSignals.length," of ",n]})]}),a.jsxs("div",{className:Z(hr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:$l({tone:"muted",variant:"caption"}),children:"Status"}),a.jsx("dd",{className:Z($l({tone:"ink",variant:"heading"}),"mt-1 capitalize"),children:e.status})]})]})}function uor({progress:e}){if(!e)return null;const t=e.signalCatalog??oP;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:yL(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=cp(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:Aq(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:[X4(r.generated)," generated · ",X4(r.embedded)," embedded"]})]},n)})})}function dor({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(hr,"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:Aq(s.name),children:cp(n,s.name)}),a.jsx(Y,{font:"body",as:"span",variant:"caption",tone:"muted",className:"capitalize",children:s.status})]}),xS(n,s.name)?a.jsx(Y,{font:"body",variant:"caption",tone:"muted",className:"mt-1",children:xS(n,s.name)}):null,a.jsxs(Y,{font:"body",variant:"caption",tone:"muted",className:"mt-1",children:[X4(i.generated)," generated · ",X4(i.embedded)," embedded"]})]},s.name)})})]})}const Bhe=({actionSlot:e,LinkComponent:t="a",progress:n,signalCatalog:r,isRangeEmpty:s})=>{const i=lor(n,s),o=r??n?.signalCatalog??oP,c=yL(o,o.filter(u=>u.enabled).map(u=>u.name)).map(u=>({key:u,label:cp(o,u),description:xS(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:aor.map(([u,d])=>a.jsxs("div",{className:Z(hr,"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(F7e,{}),a.jsxs(hc,{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(MA,{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(F7e,{}),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:Aq(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:Aq(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(cor,{progress:n}):null,a.jsx(uor,{progress:n})]})]}),a.jsxs("div",{className:"mt-4 flex shrink-0 flex-wrap items-center gap-2 sm:justify-end",children:[e,a.jsxs(de,{icon:a.jsx(Vs,{}),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(de,{icon:a.jsx(ox,{}),render:a.jsx(t,{href:"/traces"}),variant:"primary",size:"sm",children:"View incoming traces"})]})]})]})})};function B7e(e){return a.jsx(Bhe,{...e})}async function hor(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 HM={cacheScope:"oss-studio",request:hor,LinkComponent:"a",getTraceHref:e=>`/traces?traceId=${encodeURIComponent(e)}`,signalCatalog:oP},OSe=g.createContext(HM);function ha(){return g.useContext(OSe)}function por(e,t){const n=new URLSearchParams({entityType:t});return e(`/api/learning/entities?${n}`)}function mor(e,t,n){const r=new URLSearchParams({entityType:n});return e(`/api/learning/entities/${encodeURIComponent(t)}/progress?${r}`)}function X1t(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 J1t(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 gor(e,t,n,r,s,i){const o=new URLSearchParams({entityType:n,signalName:r,snapshotId:s});return e(jSe(t,i,`?${o}`))}function xL(e){return e.map(t=>`${t.signalName}:${t.kind==="theme"?t.themeId:"noise"}`).join(",")}function vor(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",xL(c)),e(jSe(t,i,`/examples?${u}`))}function yor(e,t,n,r,s,i=100){const o=new URLSearchParams({entityType:n,signalName:r,limit:String(i)});return e(jSe(t,s,`/history?${o}`))}function xor(e,t,n,r,s){const i=new URLSearchParams({entityType:n,signalName:r,snapshotId:s});return e(tSt(t,`?${i}`))}function bor(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",xL(l)),e(tSt(t,`/examples?${c}`))}async function eSt(e,t,n,r,s){const i=await V7e(e,t,n,r,s,0),o=[...i.paths],l={...i.themes};let c=i.nextOffset;for(;c!==void 0;){const u=await V7e(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 V7e(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 wor(e,t){return e(`/api/learning/traces/${encodeURIComponent(t)}/summary`)}function jSe(e,t,n){return`/api/learning/entities/${encodeURIComponent(e)}/themes/${encodeURIComponent(t)}${n}`}function tSt(e,t){return`/api/learning/entities/${encodeURIComponent(e)}/noise${t}`}function nSt(e,t,n=!0){const{cacheScope:r,request:s}=ha();return kt({queryKey:["entity-learning",r,t,e,"progress"],queryFn:()=>mor(s,e??"",t),enabled:n&&!!e})}function rSt(e){const{cacheScope:t,request:n}=ha();return kt({queryKey:["entity-learning",t,"entities",e],queryFn:()=>por(n,e)})}function sSt(e,t,n,r,s){const{cacheScope:i,request:o}=ha(),l=r?.toISOString(),c=s?.toISOString();return kt({queryKey:["entity-learning",i,t,e,"theme-snapshots",n,l,c],queryFn:()=>X1t(o,e,t,n,r,s),enabled:n.length>=2,staleTime:3e4})}const Sor=.01;function kor(e,t){return String(e[t.id])}function Oor(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 Qsr(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 P7e(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 P7e(o)).result?.tools??[]}}const Zsr=({queryOptions:e}={})=>{const t=Ye().options?.headers??{};return kn({mutationFn:n=>Qsr(n,t),...e})};function A1t({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}=rP(),{navigate:y,paths:x}=hn();g.useEffect(()=>{if(m){const k=v instanceof Error?v.message:"Failed to load MCP servers";Ge.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(Ca,{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 Wsr(){const{serverId:e}=fr(),{data:t,isLoading:n}=rP();return e?n?a.jsx(Ox,{}):t?.find(r=>r.id===e)?.name||e:null}function Hsr(){const{serverId:e}=fr();return e?a.jsx(A1t,{value:e,...l_,"aria-label":"Switch MCP server"}):null}function Gsr(){const{serverId:e,toolId:t}=fr(),{data:n}=fSe({serverId:e??"",toolId:t??"",queryOptions:{enabled:!!e&&!!t}});return n?.name??t??null}const c_=({requestContext:e,queryOptions:t}={})=>{const n=Ye();return kt({queryKey:["processors"],queryFn:()=>n.listProcessors(e),...t})},P1t=({processorId:e,requestContext:t,queryOptions:n})=>{const r=Ye();return kt({queryKey:["processor",e],queryFn:()=>r.getProcessor(e).details(t),...n})},Ksr=({requestContext:e,queryOptions:t}={})=>{const n=Ye();return kn({mutationFn:async({processorId:r,phase:s,messages:i,agentId:o})=>n.getProcessor(r).execute({phase:s,messages:i,agentId:o,requestContext:e}),...t})};function Ysr({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}=c_(),{navigate:v,paths:y}=hn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load processors";Ge.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(Ca,{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 Xsr(){const{processorId:e}=fr(),{data:t,isLoading:n}=c_();return e?n?a.jsx(Ox,{}):t?.[e]?.name||e:null}function Jsr(){const{processorId:e}=fr();return e?a.jsx(Ysr,{value:e,...l_,"aria-label":"Switch processor"}):null}const Nie=[400,401,403,404,501];function _s(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 Ts(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 ok(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 gL(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 eir=["Observability storage domain is not available","Scores storage domain is not available"];function vL(e){if(!e||typeof e!="object"||!("message"in e))return!1;const t=e.message;return typeof t!="string"?!1:eir.some(n=>t.includes(n))}function $1t(e){if(!e||typeof e!="object")return!1;if("status"in e){const t=e.status;return Nie.includes(t)}if("statusCode"in e){const t=e.statusCode;return Nie.includes(t)}if("message"in e){const t=e.message;if(typeof t=="string")return Nie.some(n=>new RegExp(`\\bstatus:\\s*${n}\\b`).test(t))}return!1}function tir(e,t){return $1t(t)?!1:e<3}const nir=25,rir=15e3;function sir(e){return gL(e.state.error,"scores")||vL(e.state.error)?!1:rir}function iir(e,t,n){if(e?.pagination?.hasMore)return n+1}function oir(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 air=({scorerId:e,entityId:t,entityType:n,queryOptions:r})=>{const s=Ye(),{inView:i,setRef:o}=E0(),l=Am({queryKey:["scores",e,t,n],queryFn:({pageParam:f})=>s.listScoresByScorerId({scorerId:e,page:f,perPage:nir,entityId:t,entityType:n}),initialPageParam:0,getNextPageParam:iir,select:f=>oir(f),refetchInterval:sir,...r}),{hasNextPage:c,isFetchingNextPage:u,fetchNextPage:d}=l;return g.useEffect(()=>{i&&c&&!u&&d()},[i,c,u,d]),{...l,setEndOfListElement:o}},lir=e=>{const t=Ye(),[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}},R1t=({requestContext:e,queryOptions:t}={})=>{const n=Ye();return kt({queryKey:["scorers",e],queryFn:()=>n.listScorers(e),staleTime:0,gcTime:0,...t})},cir=15e3;function uir(e){return gL(e.state.error,"scores")||vL(e.state.error)?!1:cir}const hSe=({traceId:e="",spanId:t="",page:n,queryOptions:r})=>{const s=Ye();return kt({queryKey:["trace-span-scores",e,t,n],queryFn:()=>s.listScoresBySpan({traceId:e,spanId:t,page:n||0,perPage:10}),refetchInterval:uir,gcTime:0,staleTime:0,...r})},dir=({queryOptions:e}={})=>{const t=Ye();return kn({mutationFn:async({scorerName:n,traceId:r,spanId:s})=>await t.score({scorerName:n,targets:[{traceId:r,spanId:s}]}),...e})},M1t=({scorerId:e,status:t,requestContext:n,queryOptions:r}={})=>{const s=Ye();return kt({queryKey:["stored-scorer",e,t,n],queryFn:()=>e?s.getStoredScorer(e).details(n,{status:t}):null,...r})},D1t=({scorerId:e,requestContext:t,queryOptions:n}={})=>{const r=Ye(),s=yr();return{createStoredScorer:kn({mutationFn:i=>r.createStoredScorer(i),onSuccess:()=>{s.invalidateQueries({queryKey:["stored-scorers"]}),s.invalidateQueries({queryKey:["scorers"]})},...n?.createStoredScorer}),updateStoredScorer:kn({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:kn({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})}},L1t=({scorerId:e,params:t,requestContext:n,queryOptions:r})=>{const s=Ye();return kt({queryKey:["scorer-versions",e,t,n],queryFn:()=>s.getStoredScorer(e).listVersions(t,n),...r})},fir=({scorerId:e,versionId:t,requestContext:n,queryOptions:r})=>{const s=Ye();return kt({queryKey:["scorer-version",e,t,n],queryFn:()=>s.getStoredScorer(e).getVersion(t,n),...r})},eg=(e,t)=>R1t({...e,requestContext:t});function hir({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}=eg(),{navigate:v,paths:y}=hn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load scorers";Ge.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(Ca,{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 pir(){const{scorerId:e}=fr(),{data:t,isLoading:n}=eg();return e?n?a.jsx(Ox,{}):t?.[e]?.scorer.config.name||e:null}function mir(){const{scorerId:e}=fr();return e?a.jsx(hir,{value:e,...l_,"aria-label":"Switch scorer"}):null}function gir(){const{scorerId:e}=fr(),{data:t,isLoading:n}=M1t({scorerId:e,status:"draft",queryOptions:{enabled:!!e}});return e?n?a.jsx(Ox,{}):t?.name??"Scorer not found":null}const sP=({requestContext:e,queryOptions:t}={})=>{const n=Ye();return kt({queryKey:["tools",e],queryFn:()=>n.listTools(e),...t})},vir=({toolId:e,requestContext:t,queryOptions:n})=>{const r=Ye();return kt({queryKey:["tool",e,t],queryFn:()=>r.getTool(e).details(t),...n})},yir=({queryOptions:e}={})=>{const t=Ye();return kn({mutationFn:async({toolId:n,input:r,requestContext:s})=>{const i=new RC;return Object.entries(s??{}).forEach(([o,l])=>{i.set(o,l)}),t.getTool(n).execute({data:r,requestContext:i})},...e})};function xir({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:i,disabled:o=!1,variant:l,size:c,"aria-label":u,align:d}){const{data:f={},isLoading:h,isError:p,error:m}=sP(),{data:v={},isLoading:y,isError:x,error:b}=pf(),{navigate:S,paths:k}=hn();g.useEffect(()=>{if(p){const _=m instanceof Error?m.message:"Failed to load tools";Ge.error(`Error loading tools: ${_}`)}},[p,m]),g.useEffect(()=>{if(x){const _=b instanceof Error?b.message:"Failed to load agents";Ge.error(`Error loading agents: ${_}`)}},[x,b]);const j=new Map;Object.values(v).forEach(_=>{_.tools&&Object.values(_.tools).forEach(N=>{j.has(N.id)||j.set(N.id,N)})}),Object.values(f).forEach(_=>{j.has(_.id)||j.set(_.id,_)});const C=Array.from(j.values()).map(_=>({label:_.id,value:_.id})),T=_=>{t?t(_):_&&_!==e&&S(k.toolLink(_))};return a.jsx(Ca,{options:C,value:e,onValueChange:T,placeholder:h||y?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||h||y||p||x,variant:l,size:c,"aria-label":u,align:d})}function bir(){const{toolId:e}=fr();return e??null}function wir(){const{toolId:e}=fr();return e?a.jsx(xir,{value:e,...l_,"aria-label":"Switch tool"}):null}const zo=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"})]}),pSe=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"})}),Sir=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"})}),kir=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"})]}),u_=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"})]}),Oir=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 AO(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 jir=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"})}),jx=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"})]}),Cir=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"})}),of=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"})}),ox=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"})]}),_ir=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"})}),Tir=typeof window<"u"&&window.MASTRA_SIGNALS_UI==="true",Eir={name:"Intelligence",url:"/intelligence",activePaths:["/intelligence"],Icon:xdt,isOnMastraPlatform:!0,hidden:!Tir},mSe=[{key:"primitives",title:"Primitives",items:[{name:"Agents",url:"/agents",Icon:zo,isOnMastraPlatform:!0},{name:"Prompts",url:"/prompts",Icon:jir,isOnMastraPlatform:!0},{name:"Workflows",url:"/workflows",Icon:xl,isOnMastraPlatform:!0},{name:"Processors",url:"/processors",Icon:AO,isOnMastraPlatform:!1,foldable:!0},{name:"MCP Servers",url:"/mcps",Icon:u_,isOnMastraPlatform:!0,foldable:!0},{name:"Tools",url:"/tools",Icon:of,isOnMastraPlatform:!0,foldable:!0},{name:"Workspaces",url:"/workspaces",Icon:_ir,isOnMastraPlatform:!0,foldable:!0}]},{key:"evaluation",title:"Evaluation",items:[{name:"Scorers",url:"/scorers",Icon:jx,isOnMastraPlatform:!0},{name:"Datasets",url:"/datasets",Icon:pSe,isOnMastraPlatform:!0},{name:"Experiments",url:"/experiments",Icon:Sir,isOnMastraPlatform:!0},{name:"Review Queue",url:"/experiments/review-queue",Icon:E3,isOnMastraPlatform:!0}]},{key:"observability",title:"Observability",items:[{name:"Metrics",url:"/metrics",Icon:Oir,isOnMastraPlatform:!0},{name:"Traces",url:"/traces",Icon:ox,isOnMastraPlatform:!0},Eir,{name:"Logs",url:"/logs",Icon:kir,isOnMastraPlatform:!0}]}],gSe=[{name:"Settings",url:"/settings",Icon:Cir,isOnMastraPlatform:!1},{name:"Resources",url:"/resources",Icon:ndt,isOnMastraPlatform:!0}],Iir=[...mSe.flatMap(e=>e.items),...gSe];function Nir(e){return Iir.find(t=>t.url===e)}function hs(e,t){const n=Nir(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 vSe=e=>{if(!e)return"";try{return decodeURIComponent(e)}catch{return e}},ySe=e=>{const t=vSe(e);return t.length>8?`${t.slice(0,8)}...`:t},xSe={id:"agent",Component:Asr,Switcher:$sr},Air={id:"scorer",Component:pir,Switcher:mir},Pir={id:"tool",Component:bir,Switcher:wir},$ir={id:"processor",Component:Xsr,Switcher:Jsr},z1t={id:"mcp-server",Component:Wsr,Switcher:Hsr},$7e={id:"workflow",Component:rsr,Switcher:ssr},_G={id:"dataset",Component:Vsr,Switcher:Usr},F1t={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 Aie=null;function Rir(){return Aie||(Aie=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Ii(()=>import("./core-DERPlZmN.js"),__vite__mapDeps([0,1,2,3,4]),import.meta.url),Ii(()=>import("./engine-javascript-DSQaR0Yq.js"),__vite__mapDeps([5,2,3]),import.meta.url)]);return e({themes:[Ii(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Ii(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Ii(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Ii(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Ii(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Ii(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Ii(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Ii(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Ii(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Ii(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Ii(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Ii(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Ii(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Ii(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([6,7,8]),import.meta.url),Ii(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Ii(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Aie}async function Mir(e,t){const n=F1t[t?.toLowerCase()];if(!n)return null;const r=await Rir(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function B1t(e){const t=e?.split(".").pop()?.toLowerCase();return t?F1t[t]:void 0}function Dir({children:e,tooltip:t}){const r=`${typeof e=="string"?e.replace(/\s*\([^)]*\)/g,""):"Request context"} details`;return a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(lt,{children:e}),t&&a.jsx(pc,{delay:10,children:a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("button",{type:"button","aria-label":r,className:Z(Fn,On,"rounded-sm",$i),children:a.jsx(Nt,{size:"xs",children:a.jsx(op,{})})})}),a.jsx(Nn,{side:"top",className:"max-w-60",children:t})]})})]})}let R7e;const V1t=()=>R7e??=Promise.all([Ii(()=>import("./standalone-Dfz2oS5J.js"),[],import.meta.url),Ii(()=>import("./babel-lWBcy2sH.js"),[],import.meta.url),Ii(()=>import("./estree-Dd9JfUIE.js"),[],import.meta.url)]).catch(e=>{throw R7e=void 0,e}),K4=async e=>{const[t,n,r]=await V1t();return await t.format(e,{semi:!1,parser:"json",printWidth:80,tabWidth:2,plugins:[n,r]})},U1t=async e=>{const[t,n,r]=await V1t();return await t.format(e,{parser:"babel-ts",printWidth:80,tabWidth:2,plugins:[n,r]})},Eq=e=>{try{const t=JSON.parse(e);return!!t&&typeof t=="object"}catch{return!1}},Lir=Oi(vt(),kPn());function Pie(e,t){if(!e)return"__custom__";for(const[n,r]of Object.entries(e))if(JSON.stringify(r)===t)return n;return"__custom__"}function zir(e){try{return JSON.stringify(JSON.parse(e))}catch{return null}}const q1t=({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(()=>Pie(t,l)),{handleCopy:v}=Mm({text:u}),[y,x]=g.useState(l);y!==l&&(x(l),d(c),h(c),m(Pie(t,l)));const b=g.useMemo(()=>{const N=zir(u);return N?N!==l:u!==f},[l,u,f]),S=()=>{let N;try{N=JSON.parse(u)}catch{Ge.error("Invalid JSON");return}const I=Lir.safeParse(N);if(!I.success){Ge.error(`${e} must be a JSON object`);return}r(I.data)},k=()=>{d(f),m(Pie(t,l))},j=Z(Fn,On),C=async()=>{if(!Eq(u)){Ge.error("Invalid JSON");return}const N=await K4(u);d(N)},T=async N=>{if(m(N),N==="__custom__"||!t)return;const I=t[N];if(I){const P=await K4(JSON.stringify(I));d(P)}},_=N=>{d(N),p!=="__custom__"&&m("__custom__")};return a.jsx(pc,{children:a.jsxs("div",{children:[a.jsxs(ft,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs(Dir,{tooltip:i,children:[e," (JSON)"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[o,a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("button",{type:"button",onClick:C,className:j,children:a.jsx(Nt,{children:a.jsx(al,{})})})}),a.jsxs(Nn,{children:["Format the ",e," JSON"]})]}),a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("button",{type:"button",onClick:v,className:j,children:a.jsx(Nt,{children:a.jsx($m,{})})})}),a.jsxs(Nn,{children:["Copy ",e]})]})]})]}),t&&Object.keys(t).length>0&&a.jsxs(ft,{children:[a.jsxs(lt,{className:"sr-only",children:[e," preset"]}),a.jsxs(Ur,{value:p,onValueChange:T,children:[a.jsx(Qr,{children:a.jsx(qr,{placeholder:"Select a preset..."})}),a.jsxs(Zr,{children:[a.jsx(or,{value:"__custom__",children:"Custom"}),Object.keys(t).map(N=>a.jsx(or,{value:N,children:N},N))]})]})]}),a.jsx(Cr,{value:u,onChange:_,showCopyButton:!1,className:s})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[b&&a.jsx(de,{variant:"default",size:"icon-md",type:"button",tooltip:`Revert ${e} changes`,onClick:k,children:a.jsx(Ln,{})}),a.jsx(de,{icon:a.jsx(pr,{}),type:"button",onClick:S,children:"Save"})]})]})})},Fir={align:"shift"};function Q1t({label:e,icon:t,open:n,onOpenChange:r,children:s}){return a.jsxs(bp,{open:n,onOpenChange:r,children:[a.jsx(rf,{variant:"ghost",size:"icon-md",type:"button",tooltip:e,"aria-label":e,children:t}),a.jsx(nh,{align:"start",collisionAvoidance:Fir,className:"w-[min(480px,calc(100vw-2rem))] p-0",children:a.jsx("div",{onSubmit:i=>i.stopPropagation(),children:a.jsx(Nr,{className:"w-full",maxHeight:"min(600px, calc(100dvh - 8rem))",children:a.jsx("div",{className:"space-y-4 p-4",children:s})})})})]})}function Bir(){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 bSe({entityType:e,entityId:t}){const[n,r]=g.useState(!1),[s,i]=wr(e,t),o=Bir(),l=c=>{i(c),Ge.success("Request context saved locally"),r(!1)};return a.jsx(Q1t,{label:"Request context",icon:a.jsx(Qjn,{}),open:n,onOpenChange:r,children:a.jsx(q1t,{label:"Request Context",presets:o,value:s,onSave:l,editorClassName:"h-[260px]"})})}function Z1t({entityType:e,entityId:t,extraFields:n,onSaveExtra:r,onOpenChange:s}){const[i,o]=g.useState(!1),[l,c]=eSe(e,t),u=f=>{o(f),s?.(f)},d=f=>{c(f),r?.(),Ge.success("Run options saved locally"),u(!1)};return a.jsxs(Q1t,{label:"Run options",icon:a.jsx(ox,{}),open:i,onOpenChange:u,children:[n,a.jsx(q1t,{label:"Tracing Options",value:l,onSave:d,editorClassName:"h-[260px]"})]})}function Vir({workflowId:e,resourceId:t,setResourceId:n}){const[r,s]=g.useState(t);return a.jsxs(a.Fragment,{children:[a.jsx(bSe,{entityType:"workflow",entityId:e}),a.jsx(Z1t,{entityType:"workflow",entityId:e,onOpenChange:i=>{i&&s(t)},onSaveExtra:()=>n(r),extraFields:a.jsxs(ft,{children:[a.jsx(lt,{children:"Resource ID"}),a.jsx(Sn,{value:r,onChange:i=>s(i.target.value),placeholder:"e.g. tenant-42"}),a.jsx(eo,{children:"Ignored when server auth derives the resource ID from the user."})]})})]})}function Iq({icon:e,label:t,tooltipContent:n,docsHref:r}){return a.jsxs($n,{children:[a.jsx(In,{render:a.jsx("span",{role:"button",tabIndex:0,"aria-disabled":"true","aria-label":t,className:"inline-flex",children:a.jsx(de,{variant:"ghost",size:"icon-md",disabled:!0,"aria-hidden":"true",tabIndex:-1,children:e})})}),a.jsx(Nn,{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",On),children:["Learn more",a.jsx(Vs,{className:"size-3"})]})]})})]})}const Uir=({scheduleId:e,queryOptions:t})=>{const n=Ye();return kt({queryKey:["schedule",e],queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return n.getSchedule(e)},...t})},TG=({queryOptions:e,...t}={})=>{const n=Ye();return kt({queryKey:["schedules",t],queryFn:async()=>(await n.listSchedules(t)).schedules,...e})},M7e=25,qir=({scheduleId:e,queryOptions:t})=>{const n=Ye(),{inView:r,setRef:s}=E0(),i=Am({queryKey:["schedule-triggers",e],initialPageParam:void 0,queryFn:async({pageParam:d})=>e?n.listScheduleTriggers(e,{limit:M7e,toActualFireAt:d}):{triggers:[]},getNextPageParam:d=>{if(!(!d?.triggers?.length||d.triggers.length<M7e))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}},Qir=({scheduleId:e,queryOptions:t})=>{const n=Ye(),r=yr();return kn({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 $ie({value:e,icon:t,label:n}){return a.jsxs(ls,{value:e,children:[a.jsx(Nt,{size:"xs",children:t}),a.jsx(Y,{variant:"caption",className:"text-inherit",children:n})]})}function Zir({workflowId:e,activeTab:t,showObservability:n=!1}){const{navigate:r}=hn(),{data:s,isSuccess:i}=TG({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(Hl,{value:t,defaultTab:t,onValueChange:u,className:"min-w-0",children:a.jsxs(Gl,{variant:"pill-ghost",children:[a.jsx($ie,{value:"graph",icon:a.jsx(xl,{}),label:"Graph"}),n&&a.jsx($ie,{value:"traces",icon:a.jsx(ox,{}),label:"Traces"}),!d&&a.jsx($ie,{value:"schedules",icon:a.jsx(i0,{}),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(Iq,{icon:a.jsx(ox,{}),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(Iq,{icon:a.jsx(i0,{}),label:"Schedules",tooltipContent:"Configure a schedule on this workflow to enable Schedules.",docsHref:"https://mastra.ai/docs/workflows/scheduled-workflows"})]})]})}const Wir=({children:e})=>{const{workflowId:t,runId:n}=fr();return a.jsx(Jbe,{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(Kir,{children:e})})},Hir=e=>e==="graph"||e==="traces"||e==="schedules",Gir=({workflowId:e})=>{const t=Lr();return C0({"g$+t":()=>t(`/workflows/${encodeURIComponent(e)}/traces`)}),null};function Kir({children:e}){const{workflowId:t,runId:n}=fr(),r=Dxe("/workflows/:workflowId/:tab/*"),{isLoading:s}=L3({workflowId:t,requestContext:wr("workflow",t)[0],queryOptions:{enabled:!!t}}),{hasObservability:i}=k1t(),o=Hir(r?.params.tab)?r.params.tab:"none",l=[hs("/workflows"),n?{...$7e,to:`/workflows/${encodeURIComponent(t??"")}/graph`}:$7e,...n?[{id:"workflow-run",Component:isr,Action:osr}]:[]];if(!t)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{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(St,{breadcrumbs:a.jsx(Pt,{crumbs:l}),children:[a.jsx("h1",{className:"sr-only",children:t}),a.jsx(bt,{className:"h-full"})]});const c=u=>a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:l}),headerActions:a.jsx(lsr,{}),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(Zir,{workflowId:t,activeTab:o,showObservability:i}),u]})]});return a.jsxs(gtt,{children:[a.jsx(Gir,{workflowId:t}),o==="graph"?a.jsx(Hwt,{children:a.jsx(nSe,{workflowId:t,initialRunId:n,children:a.jsx(Wwt,{children:c(a.jsx(lrr,{leftSlot:a.jsx(Yir,{workflowId:t,initialRunId:n}),children:e}))})})},t):c(e)]})}function Yir({workflowId:e,initialRunId:t}){const[n]=wr("workflow",e),{canExecute:r,canDelete:s}=Ta();return a.jsx(prr,{workflowId:e,initialRunId:t,requestContext:n,runActionsSlot:i=>a.jsx(Vir,{workflowId:e,...i}),canExecute:r("workflows"),canDelete:s("workflows")})}const W1t=dd(Z(hr,"rounded-xl transition-all duration-normal ease-out-custom motion-reduce:transition-none"),{variants:{elevation:{flat:"shadow-none",raised:""},interactive:{true:Z(AA,Ebe,"cursor-pointer active:scale-99"),false:""}},compoundVariants:[{elevation:"flat",interactive:!0,class:yx}],defaultVariants:{elevation:"raised",interactive:!1}}),hc=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(W1t({elevation:t,interactive:n}),e),...s})});hc.displayName="Card";function H1t({className:e,elevation:t,LinkComponent:n="a",...r}){return a.jsx(n,{className:Z(W1t({elevation:t,interactive:!0}),e),...r})}const Nq=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}));Nq.displayName="CardHeader";const ak=g.forwardRef(({className:e,...t},n)=>a.jsx("h3",{ref:n,className:Z("text-subheading text-foreground",e),...t}));ak.displayName="CardTitle";const vj=g.forwardRef(({className:e,...t},n)=>a.jsx("p",{ref:n,className:Z("text-caption text-muted-foreground",e),...t}));vj.displayName="CardDescription";const Xir=dd("",{variants:{density:{default:"p-3",compact:"p-2"}},defaultVariants:{density:"default"}}),dv=g.forwardRef(({className:e,density:t,...n},r)=>a.jsx("div",{ref:r,className:Z(Xir({density:t}),e),...n}));dv.displayName="CardContent";const Jir=g.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,className:Z("flex items-center p-3 pt-0",e),...t}));Jir.displayName="CardFooter";const D7e=["blue","green","orange","purple","pink","amber","cyan"];function wSe(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 iP=e=>D7e[wSe(e)%D7e.length]??"blue",Di=e=>`var(--badge-${e}-indicator)`,eor={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"},G1t=e=>eor[e],tor=e=>({background:`var(--badge-${e}-strong)`,foreground:`var(--badge-${e}-foreground)`,tint:`var(--badge-${e}-indicator)`}),L7e={goal:"green",outcome:"orange",behavior:"blue",sentiment:"purple"},z7e=["pink","amber"],nor={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"},ror={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 SSe(e){const t=e.toLowerCase();return(Object.hasOwn(L7e,t)?L7e[t]:void 0)??z7e[wSe(t)%z7e.length]??"pink"}function Cx(e){return`var(--chart-${SSe(e)})`}function K1t(e){return nor[SSe(e)]}function sor(e){return ror[SSe(e)]}const oP=[{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"}];oP.map(e=>e.name);Object.fromEntries(oP.map(e=>[e.name,e.description]));function yL(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 cp(e,t){return e.find(n=>n.name===t)?.label??ior(t)}function xS(e,t){return e.find(n=>n.name===t)?.description||void 0}function ior(e){return e.split(/[-_]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function EG(e){return`${e} ${e===1?"trace":"traces"}`}function oor(e){return`${e} ${e===1?"theme":"themes"}`}function Y1t(e,t){if(t<=0)return`${EG(e)} in this snapshot`;const n=Math.round(e/t);return`${e} of ${n} traces in this snapshot (${Math.round(t*100)}%)`}const kSe={timeZone:"UTC"};function Y4(e){return dI(e,{...kSe,now:0})??e}function IG(e){return is(e,"date-time",kSe)??e}function Fhe(e,t){return xGn(e,t,kSe)??`${e}–${t}`}const aor=[["chat.completion","1.2s"],["tool.search_docs","340ms"],["workflow.support","2.8s"]],Aq=e=>({color:Cx(e)}),F7e=()=>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 X4(e){return new Intl.NumberFormat("en-US").format(e)}function lor(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 cor({progress:e}){const t=e.signalCatalog??oP,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(hr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:$l({tone:"muted",variant:"caption"}),children:"Traces analyzed"}),a.jsx("dd",{className:Z($l({tone:"ink",variant:"heading"}),"mt-1"),children:X4(e.traceCount)})]}),a.jsxs("div",{className:Z(hr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:$l({tone:"muted",variant:"caption"}),children:"Trace signal types ready"}),a.jsxs("dd",{className:Z($l({tone:"ink",variant:"heading"}),"mt-1"),children:[e.signalCatalog?r:e.availableSignals.length," of ",n]})]}),a.jsxs("div",{className:Z(hr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:$l({tone:"muted",variant:"caption"}),children:"Status"}),a.jsx("dd",{className:Z($l({tone:"ink",variant:"heading"}),"mt-1 capitalize"),children:e.status})]})]})}function uor({progress:e}){if(!e)return null;const t=e.signalCatalog??oP;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:yL(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=cp(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:Aq(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:[X4(r.generated)," generated · ",X4(r.embedded)," embedded"]})]},n)})})}function dor({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(hr,"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:Aq(s.name),children:cp(n,s.name)}),a.jsx(Y,{font:"body",as:"span",variant:"caption",tone:"muted",className:"capitalize",children:s.status})]}),xS(n,s.name)?a.jsx(Y,{font:"body",variant:"caption",tone:"muted",className:"mt-1",children:xS(n,s.name)}):null,a.jsxs(Y,{font:"body",variant:"caption",tone:"muted",className:"mt-1",children:[X4(i.generated)," generated · ",X4(i.embedded)," embedded"]})]},s.name)})})]})}const Bhe=({actionSlot:e,LinkComponent:t="a",progress:n,signalCatalog:r,isRangeEmpty:s})=>{const i=lor(n,s),o=r??n?.signalCatalog??oP,c=yL(o,o.filter(u=>u.enabled).map(u=>u.name)).map(u=>({key:u,label:cp(o,u),description:xS(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:aor.map(([u,d])=>a.jsxs("div",{className:Z(hr,"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(F7e,{}),a.jsxs(hc,{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(MA,{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(F7e,{}),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:Aq(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:Aq(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(cor,{progress:n}):null,a.jsx(uor,{progress:n})]})]}),a.jsxs("div",{className:"mt-4 flex shrink-0 flex-wrap items-center gap-2 sm:justify-end",children:[e,a.jsxs(de,{icon:a.jsx(Vs,{}),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(de,{icon:a.jsx(ox,{}),render:a.jsx(t,{href:"/traces"}),variant:"primary",size:"sm",children:"View incoming traces"})]})]})]})})};function B7e(e){return a.jsx(Bhe,{...e})}async function hor(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 HM={cacheScope:"oss-studio",request:hor,LinkComponent:"a",getTraceHref:e=>`/traces?traceId=${encodeURIComponent(e)}`,signalCatalog:oP},OSe=g.createContext(HM);function ha(){return g.useContext(OSe)}function por(e,t){const n=new URLSearchParams({entityType:t});return e(`/api/learning/entities?${n}`)}function mor(e,t,n){const r=new URLSearchParams({entityType:n});return e(`/api/learning/entities/${encodeURIComponent(t)}/progress?${r}`)}function X1t(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 J1t(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 gor(e,t,n,r,s,i){const o=new URLSearchParams({entityType:n,signalName:r,snapshotId:s});return e(jSe(t,i,`?${o}`))}function xL(e){return e.map(t=>`${t.signalName}:${t.kind==="theme"?t.themeId:"noise"}`).join(",")}function vor(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",xL(c)),e(jSe(t,i,`/examples?${u}`))}function yor(e,t,n,r,s,i=100){const o=new URLSearchParams({entityType:n,signalName:r,limit:String(i)});return e(jSe(t,s,`/history?${o}`))}function xor(e,t,n,r,s){const i=new URLSearchParams({entityType:n,signalName:r,snapshotId:s});return e(tSt(t,`?${i}`))}function bor(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",xL(l)),e(tSt(t,`/examples?${c}`))}async function eSt(e,t,n,r,s){const i=await V7e(e,t,n,r,s,0),o=[...i.paths],l={...i.themes};let c=i.nextOffset;for(;c!==void 0;){const u=await V7e(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 V7e(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 wor(e,t){return e(`/api/learning/traces/${encodeURIComponent(t)}/summary`)}function jSe(e,t,n){return`/api/learning/entities/${encodeURIComponent(e)}/themes/${encodeURIComponent(t)}${n}`}function tSt(e,t){return`/api/learning/entities/${encodeURIComponent(e)}/noise${t}`}function nSt(e,t,n=!0){const{cacheScope:r,request:s}=ha();return kt({queryKey:["entity-learning",r,t,e,"progress"],queryFn:()=>mor(s,e??"",t),enabled:n&&!!e})}function rSt(e){const{cacheScope:t,request:n}=ha();return kt({queryKey:["entity-learning",t,"entities",e],queryFn:()=>por(n,e)})}function sSt(e,t,n,r,s){const{cacheScope:i,request:o}=ha(),l=r?.toISOString(),c=s?.toISOString();return kt({queryKey:["entity-learning",i,t,e,"theme-snapshots",n,l,c],queryFn:()=>X1t(o,e,t,n,r,s),enabled:n.length>=2,staleTime:3e4})}const Sor=.01;function kor(e,t){return String(e[t.id])}function Oor(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 jor(e,t){return Number(e[`${t.id}TraceCount`])}function Cor(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:Tor(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`]:Q7e(o.node),[`${o.signalName}Description`]:o.node.description,[`${o.signalName}TraceCount`]:o.node.traceCount,[l.signalName]:l.node.nodeId,[`${l.signalName}Label`]:Q7e(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 _or(e){return Cor(e)}function U7e(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 q7e(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(Sor,s.get(c)??l.traceCount)}});return{...e,stages:n,links:o}}function Q7e(e){return e.kind==="noise"?"Noise":e.label}function Tor(e){return`${e.slice(0,1).toUpperCase()}${e.slice(1)}`}function J4(e,t){const n=e.cutoffAt?IG(e.cutoffAt):Fhe(e.startedAt,e.endedAt);if(!t)return n;const{traceCount:r,themeCount:s}=Eor(t);return`${n} · ${EG(r)} · ${oor(s)}`}function Eor(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 jc(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 Ior=typeof Symbol=="function"&&Symbol.observable||"@@observable",Z7e=Ior,Rie=()=>Math.random().toString(36).substring(7).split("").join("."),Nor={INIT:`@@redux/INIT${Rie()}`,REPLACE:`@@redux/REPLACE${Rie()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${Rie()}`},Pq=Nor;function CSe(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 _Se(e,t,n){if(typeof e!="function")throw new Error(jc(2));if(typeof t=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(jc(0));if(typeof t=="function"&&typeof n>"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(jc(1));return n(_Se)(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(jc(3));return s}function f(y){if(typeof y!="function")throw new Error(jc(4));if(c)throw new Error(jc(5));let x=!0;u();const b=l++;return o.set(b,y),function(){if(x){if(c)throw new Error(jc(6));x=!1,u(),o.delete(b),i=null}}}function h(y){if(!CSe(y))throw new Error(jc(7));if(typeof y.type>"u")throw new Error(jc(8));if(typeof y.type!="string")throw new Error(jc(17));if(c)throw new Error(jc(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(jc(10));r=y,h({type:Pq.REPLACE})}function m(){const y=f;return{subscribe(x){if(typeof x!="object"||x===null)throw new Error(jc(11));function b(){const k=x;k.next&&k.next(d())}return b(),{unsubscribe:y(b)}},[Z7e](){return this}}}return h({type:Pq.INIT}),{dispatch:h,subscribe:f,getState:d,replaceReducer:p,[Z7e]:m}}function Aor(e){Object.keys(e).forEach(t=>{const n=e[t];if(typeof n(void 0,{type:Pq.INIT})>"u")throw new Error(jc(12));if(typeof n(void 0,{type:Pq.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(jc(13))})}function iSt(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{Aor(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(jc(14));u[f]=m,c=c||m!==p}return c=c||r.length!==Object.keys(o).length,c?u:o}}function W7e(e,t){return function(...n){return t(e.apply(this,n))}}function H7e(e,t){if(typeof e=="function")return W7e(e,t);if(typeof e!="object"||e===null)throw new Error(jc(16));const n={};for(const r in e){const s=e[r];typeof s=="function"&&(n[r]=W7e(s,t))}return n}function e5(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,n)=>(...r)=>t(n(...r)))}function oSt(...e){return t=>(n,r)=>{const s=t(n,r);let i=()=>{throw new Error(jc(15))};const o={getState:s.getState,dispatch:(c,...u)=>i(c,...u)},l=e.map(c=>c(o));return i=e5(...l)(s.dispatch),{...s,dispatch:i}}}function aSt(e){return CSe(e)&&"type"in e&&typeof e.type=="string"}var Mie={exports:{}},Die={};var G7e;function Por(){if(G7e)return Die;G7e=1;var e=gA();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 Die.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},Die}var K7e;function $or(){return K7e||(K7e=1,Mie.exports=Por()),Mie.exports}$or();var Ror=g.version.startsWith("19"),Mor=Symbol.for(Ror?"react.transitional.element":"react.element"),Dor=Symbol.for("react.portal"),Lor=Symbol.for("react.fragment"),zor=Symbol.for("react.strict_mode"),For=Symbol.for("react.profiler"),Bor=Symbol.for("react.consumer"),Vor=Symbol.for("react.context"),lSt=Symbol.for("react.forward_ref"),Uor=Symbol.for("react.suspense"),qor=Symbol.for("react.suspense_list"),TSe=Symbol.for("react.memo"),Qor=Symbol.for("react.lazy"),Zor=lSt,Wor=TSe;function Hor(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case Mor:switch(e=e.type,e){case Lor:case For:case zor:case Uor:case qor:return e;default:switch(e=e&&e.$$typeof,e){case Vor:case lSt:case Qor:case TSe:return e;case Bor:return e;default:return t}}case Dor:return t}}}function Gor(e){return Hor(e)===TSe}function Kor(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 Yor(e,{initMapStateToProps:t,initMapDispatchToProps:n,initMergeProps:r,...s}){const i=t(e,s),o=n(e,s),l=r(e,s);return Kor(i,o,l,e,s)}function Xor(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 Vhe(e){return function(n){const r=e(n);function s(){return r}return s.dependsOnOwnProps=!1,s}}function Y7e(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function cSt(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=Y7e(e);let u=i(l,c);return typeof u=="function"&&(i.mapToProps=u,i.dependsOnOwnProps=Y7e(u),u=i(l,c)),u},i}}function ESe(e,t){return(n,r)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${r.wrappedComponentName}.`)}}function Jor(e){return e&&typeof e=="object"?Vhe(t=>Xor(e,t)):e?typeof e=="function"?cSt(e):ESe(e,"mapDispatchToProps"):Vhe(t=>({dispatch:t}))}function ear(e){return e?typeof e=="function"?cSt(e):ESe(e,"mapStateToProps"):Vhe(()=>({}))}function tar(e,t,n){return{...n,...e,...t}}function nar(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 rar(e){return e?typeof e=="function"?nar(e):ESe(e,"mergeProps"):()=>tar}function sar(e){e()}function iar(){let e=null,t=null;return{clear(){e=null,t=null},notify(){sar(()=>{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 X7e={notify(){},get:()=>[]};function uSt(e,t){let n,r=X7e,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=iar())}function f(){s--,n&&s===0&&(n(),n=void 0,r.clear(),r=X7e)}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 oar=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",aar=oar(),lar=()=>typeof navigator<"u"&&navigator.product==="ReactNative",car=lar(),uar=()=>aar||car?g.useLayoutEffect:g.useEffect,$q=uar();function J7e(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function oB(e,t){if(J7e(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])||!J7e(e[n[s]],t[n[s]]))return!1;return!0}var dar={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},far={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},har={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},dSt={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},par={[Zor]:har,[Wor]:dSt};function eBe(e){return Gor(e)?dSt:par[e.$$typeof]||dar}var mar=Object.defineProperty,gar=Object.getOwnPropertyNames,tBe=Object.getOwnPropertySymbols,yar=Object.getOwnPropertyDescriptor,xar=Object.getPrototypeOf,nBe=Object.prototype;function Uhe(e,t){if(typeof t!="string"){if(nBe){const i=xar(t);i&&i!==nBe&&Uhe(e,i)}let n=gar(t);tBe&&(n=n.concat(tBe(t)));const r=eBe(e),s=eBe(t);for(let i=0;i<n.length;++i){const o=n[i];if(!far[o]&&!(s&&s[o])&&!(r&&r[o])){const l=yar(t,o);try{mar(e,o,l)}catch{}}}}return e}var bar=Symbol.for("react-redux-context"),war=typeof globalThis<"u"?globalThis:{};function Sar(){if(!g.createContext)return{};const e=war[bar]??=new Map;let t=e.get(g.createContext);return t||(t=g.createContext(null),e.set(g.createContext,t)),t}var fSt=Sar(),kar=[null,null];function Oar(e,t,n){$q(()=>e(...t),n)}function jar(e,t,n,r,s,i){e.current=r,n.current=!1,s.current&&(s.current=null,i())}function Car(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 _ar(e,t){return e===t}function Tar(e,t,n,{pure:r,areStatesEqual:s=_ar,areOwnPropsEqual:i=oB,areStatePropsEqual:o=oB,areMergedPropsEqual:l=oB,forwardRef:c=!1,context:u=fSt}={}){const d=u,f=ear(e),h=Jor(t),p=rar(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,I]=g.useMemo(()=>{const{reactReduxForwardedRef:ee,...se}=T;return[T.context,ee,se]},[T]),P=g.useMemo(()=>{let ee=d;return _?.Consumer,ee},[_,d]),A=g.useContext(P),D=!!T.store&&!!T.store.getState&&!!T.store.dispatch,z=!!A&&!!A.store,Q=D?T.store:A.store,q=z?A.getServerState:Q.getState,B=g.useMemo(()=>Yor(Q.dispatch,S),[Q]),[V,H]=g.useMemo(()=>{if(!m)return kar;const ee=uSt(Q,D?void 0:A.subscription),se=ee.notifyNestedSubs.bind(ee);return[ee,se]},[Q,D,A]),M=g.useMemo(()=>D?A:{...A,subscription:V},[D,A,V]),G=g.useRef(void 0),L=g.useRef(I),$=g.useRef(void 0),F=g.useRef(!1),U=g.useRef(!1),K=g.useRef(void 0);$q(()=>(U.current=!0,()=>{U.current=!1}),[]);const ne=g.useMemo(()=>()=>$.current&&I===L.current?$.current:B(Q.getState(),I),[Q,I]),X=g.useMemo(()=>se=>V?Car(m,Q,V,B,L,G,F,U,$,H,se):()=>{},[V]);Oar(jar,[L,G,F,I,$,H]);let te;try{te=g.useSyncExternalStore(X,ne,q?()=>B(q(),I):ne)}catch(ee){throw K.current&&(ee.message+=`
|
|
259
259
|
The error may be correlated with this previous error:
|
|
260
260
|
${K.current.stack}
|
|
@@ -667,7 +667,7 @@ window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-
|
|
|
667
667
|
|
|
668
668
|
`),i=r.filter(o=>o.type==="prompt_block"||o.type==="prompt_block_ref").map(o=>o.type==="prompt_block_ref"?Jge(o.id,o.rules):V5(hXe(o.content),o.rules));return{instructionsString:s,instructionBlocks:i}}const n=x8t(e);return{instructionsString:n,instructionBlocks:[V5(n)]}},kus=e=>{const t=e?Object.entries(e):void 0;if(t)return Object.fromEntries(t.map(([n,r])=>[n,{description:r.description,sampling:r.sampling?{type:r.sampling.type,rate:r.sampling.rate||0}:void 0,rules:r.rules}]))},Ous=e=>{if(!e)return{};let t;if(Array.isArray(e)){t={};for(const r of e)Object.assign(t,r.value)}else t=e;const n={};for(const[r,s]of Object.entries(t))n[r]={description:s.description,sampling:s.sampling?.type==="ratio"?{type:"ratio",rate:s.sampling.rate}:void 0,rules:s.rules};return n},pXe=e=>{if(!e?.enabled)return;const t=Mle(e.model),n=Mle(e.observation?.model),r=n||e.observation?.messageTokens||e.observation?.maxTokensPerBatch||e.observation?.bufferTokens!==void 0||e.observation?.bufferActivation!==void 0||e.observation?.blockAfter!==void 0?{model:n,messageTokens:e.observation?.messageTokens,maxTokensPerBatch:e.observation?.maxTokensPerBatch,bufferTokens:e.observation?.bufferTokens,bufferActivation:e.observation?.bufferActivation,blockAfter:e.observation?.blockAfter}:void 0,s=Mle(e.reflection?.model),i=s||e.reflection?.observationTokens||e.reflection?.blockAfter!==void 0||e.reflection?.bufferActivation!==void 0?{model:s,observationTokens:e.reflection?.observationTokens,blockAfter:e.reflection?.blockAfter,bufferActivation:e.reflection?.bufferActivation}:void 0;return t||e.scope||e.shareTokenBudget||r||i?{model:t,scope:e.scope,shareTokenBudget:e.shareTokenBudget,observation:r,reflection:i}:!0},jus=e=>{if(!e)return;const t=typeof e=="object"?e:{};return{enabled:!0,model:Rle(t.model),scope:t.scope,shareTokenBudget:t.shareTokenBudget,observation:t.observation?{model:Rle(t.observation.model),messageTokens:t.observation.messageTokens,maxTokensPerBatch:t.observation.maxTokensPerBatch,bufferTokens:t.observation.bufferTokens,bufferActivation:t.observation.bufferActivation,blockAfter:t.observation.blockAfter}:void 0,reflection:t.reflection?{model:Rle(t.reflection.model),observationTokens:t.reflection.observationTokens,blockAfter:t.reflection.blockAfter,bufferActivation:t.reflection.bufferActivation}:void 0}};async function mXe(e,t){const n=e.filter(s=>s.id).map(s=>s.id),r=await Promise.all(e.filter(s=>!s.id).map(s=>t.createStoredMCPClient({name:s.name,description:s.description,servers:s.servers}).then(i=>i.id)));return[...n,...r]}function b8t(e){let t;if(e.requestContextSchema)try{t=typeof e.requestContextSchema=="string"?lS(e.requestContextSchema):e.requestContextSchema}catch{}return{name:e.name,description:e.description,instructions:e.instructions,model:{provider:e.provider,name:e.modelId},tools:e.tools,workflows:e.workflows,agents:e.agents,skills:void 0,workspace:e.workspaceId?{workspaceId:e.workspaceId}:void 0,requestContextSchema:t}}function Cus(e){const t=$le(e.tools),n=_us(e.memory),r=Tus(e.memory),{instructionsString:s,instructionBlocks:i}=Sus(e.instructions);return{name:e.name||"",description:e.description||"",instructions:s,model:{provider:e.model?.provider||"",name:e.model?.name||""},tools:t,integrationTools:xus(e.integrationTools),workflows:$le(e.workflows),agents:$le(e.agents),scorers:Ous(e.scorers),memory:r?.options?{enabled:!0,lastMessages:r.options.lastMessages,semanticRecall:r.options.semanticRecall,readOnly:r.options.readOnly,vector:r.vector,embedder:r.embedder,observationalMemory:jus(r.observationalMemory)}:void 0,memoryRef:n,instructionBlocks:i,skills:bus(e.skills),workspace:wus(e.workspace),variables:e.requestContextSchema}}function w8t(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _us(e){if(!(!w8t(e)||e.type!=="id"||typeof e.memoryId!="string"))return{type:"id",memoryId:e.memoryId}}function Tus(e){if(!w8t(e))return e;if(e.type!=="id")return e.type==="inline"?e.config:e}function Eus(e,t){if(!e||e.length===0)return{type:"published"};let n=!1,r=!1;const s=[];for(const i of e){if(i.type==="prompt_block"){i.content.trim()!==""&&(r=!0);continue}const o=i.promptBlockId?.trim();if(!o)continue;n=!0;const l=t.get(o);l===void 0||l==="unknown"?s.push(o):l==="published"&&(r=!0)}return s.length>0?{type:"unknown",ids:[...new Set(s)]}:r?{type:"published"}:n?{type:"empty"}:{type:"published"}}function Ius(e){const t=e.map(n=>n.name?`"${n.name}" (${n.id})`:n.id).join(", ");return`Unable to verify referenced prompt block${e.length===1?"":"s"}: ${t}. Resolve these references or try again before continuing.`}const Nus="This agent only references unpublished prompt blocks, so it would run with an empty prompt. Publish the referenced prompt blocks or add inline instructions before continuing.";function Aus(e){return`Unable to use unpublished referenced prompt block${e.length===1?"":"s"}: ${e.join(", ")}. Publish these prompt blocks and try again.`}function Pus(e){const t=e.join(", ");return`Unable to verify publication status for prompt block${e.length===1?"":"s"}: ${t}. The block may have been deleted or is temporarily unavailable. Please check and try again.`}function nIe(e,t){const n=Ye(),r=yr(),[s,i]=g.useState(!1),[o,l]=g.useState(!1),c=e.mode==="edit",u=c?e.agentId:void 0,d=c&&!!e.isCodeAgentOverride,f=c&&!!e.hasStoredOverride,h=c?e.editorConfig:void 0,{ownsInstructions:p,ownsTools:m,ownsToolDescriptions:v}=P_(d,h),[y,x]=g.useState(!1),b=d&&!f&&!y,{createStoredAgent:S}=fC(),{updateStoredAgent:k}=fC({agentId:u}),j=g.useMemo(()=>c?Cus(e.dataSource):void 0,[c,c?e.dataSource:void 0]),{form:C}=xcs({initialValues:j,isCodeAgentOverride:d}),T=g.useEffectEvent(()=>{if(!j||e.mode!=="edit")return;C.reset(j);const H=e.dataSource.mcpClients,M=Object.keys(H??{});M.length!==0&&Promise.all(M.map(G=>n.getStoredMCPClient(G).details())).then(G=>{const L=G.map(U=>({id:U.id,name:U.name,description:U.description,servers:U.servers,selectedTools:H?.[U.id]?.tools??{}}));C.setValue("mcpClients",L,{shouldDirty:!1});const F={...C.getValues("tools")??{}};for(const U of L)for(const[K,ne]of Object.entries(U.selectedTools??{}))F[K]={description:ne.description};C.setValue("tools",F,{shouldDirty:!1})}).catch(()=>{})});g.useEffect(()=>{c&&T()},[c,c?e.dataSource:void 0]);const _=g.useCallback(async H=>{if(d){const F=new Set;for(const X of H.mcpClients??[])for(const te of Object.keys(X.selectedTools??{}))F.add(te);const U={};for(const[X,te]of Object.entries(H.tools??{}))F.has(X)||(U[X]=te);const K=await mXe(H.mcpClients??[],n),ne=Object.fromEntries(K.map((X,te)=>{const oe=H.mcpClients?.[te]?.selectedTools??{};return[X,{tools:oe}]}));return{name:H.name,model:H.model,requestContextSchema:H.variables?Object.fromEntries(Object.entries(H.variables)):void 0,instructions:p?fXe(H.instructionBlocks):[],...m||v?{tools:Object.keys(U).length>0?U:{},integrationTools:dXe(H.integrationTools),mcpClients:ne}:{}}}if(c){const F=H.mcpClientsToDelete??[];await Promise.all(F.map(U=>n.getStoredMCPClient(U).delete()))}const M=new Set;for(const F of H.mcpClients??[])for(const U of Object.keys(F.selectedTools??{}))M.add(U);const G={};for(const[F,U]of Object.entries(H.tools??{}))M.has(F)||(G[F]=U);const L=await mXe(H.mcpClients??[],n),$=Object.fromEntries(L.map((F,U)=>{const K=H.mcpClients?.[U]?.selectedTools??{};return[F,{tools:K}]}));return{name:H.name,description:H.description||void 0,instructions:fXe(H.instructionBlocks),model:H.model,tools:Object.keys(G).length>0?G:{},integrationTools:dXe(H.integrationTools),workflows:H.workflows&&Object.keys(H.workflows).length>0?H.workflows:void 0,agents:H.agents&&Object.keys(H.agents).length>0?H.agents:void 0,mcpClients:$,scorers:kus(H.scorers),skills:H.skills,workspace:H.workspace,requestContextSchema:H.variables?Object.fromEntries(Object.entries(H.variables)):void 0}},[c,d,p,m,v,n]),N=g.useCallback(H=>{const M=H.memory?.enabled?{options:{lastMessages:H.memory.lastMessages,semanticRecall:H.memory.semanticRecall,readOnly:H.memory.readOnly},observationalMemory:pXe(H.memory.observationalMemory)}:void 0;if(M)return{...M,vector:H.memory?.vector,embedder:H.memory?.embedder}},[]),I=g.useCallback(async H=>{if(d&&!p)return!1;const M=Array.from(new Set((H.instructionBlocks??[]).filter(U=>U.type==="prompt_block_ref").map(U=>U.promptBlockId.trim()).filter(Boolean)));if(M.length===0)return!1;const G=new Map,L=[];if(await Promise.all(M.map(async U=>{try{const K=await n.getStoredPromptBlock(U).details(t);if(!K){G.set(U,"unknown"),L.push({id:U,reason:"not_found"});return}G.set(U,K.activeVersionId?"published":"unpublished")}catch(K){const ne=K instanceof Hy?K.status:void 0;G.set(U,"unknown"),L.push({id:U,reason:ne===404?"not_found":ne===403?"forbidden":"request_failed"})}})),L.length>0)return Ge.error(Ius(L)),!0;const $=M.filter(U=>G.get(U)==="unpublished");if($.length>0)return Ge.error(Aus($)),!0;const F=Eus(H.instructionBlocks,G);return F.type==="unknown"?(Ge.error(Pus(F.ids)),!0):F.type==="empty"?(Ge.error(Nus),!0):!1},[n,d,p,t]),P=g.useCallback(async H=>{if(!c)return;if(!await C.trigger()){Ge.error("Please fill in all required fields");return}const G=C.getValues();l(!0);try{if(await I(G))return;const L=await _(G),$=d?void 0:G.memoryRef??N(G);if(b){const F={id:e.agentId,...L,memory:$,autoPublish:!1};await S.mutateAsync(F),x(!0)}else await k.mutateAsync({...L,memory:$,...H?{changeMessage:H}:{}});C.reset(G,{keepValues:!0}),r.invalidateQueries({queryKey:["agent-versions",u]}),d||(r.invalidateQueries({queryKey:["stored-agent",u]}),r.invalidateQueries({queryKey:["agent",u]})),Ge.success(e.mode==="edit"&&e.saveSuccessMessage?e.saveSuccessMessage:"Draft saved")}catch(L){Ge.error(`Failed to save draft: ${L instanceof Error?L.message:"Unknown error"}`)}finally{l(!1)}},[C,c,u,b,e,_,N,S,k,r,I]),A=g.useCallback(async H=>{if(!H&&!await C.trigger()){Ge.error("Please fill in all required fields");return}const M=C.getValues();i(!0);try{if(!H&&await I(M))return;if(c){if(H)await n.getStoredAgent(e.agentId).activateVersion(H);else if(b){const G=await _(M),L=d?void 0:M.memoryRef??N(M),$={id:e.agentId,...G,memory:L};await S.mutateAsync($),x(!0);const U=(await n.getStoredAgent(e.agentId).listVersions({orderBy:{field:"createdAt",direction:"DESC"},perPage:1})).versions[0];U&&await n.getStoredAgent(e.agentId).activateVersion(U.id)}else{const[G,L]=await Promise.all([n.getStoredAgent(e.agentId).details(),n.getStoredAgent(e.agentId).listVersions({orderBy:{field:"createdAt",direction:"DESC"},perPage:1})]),$=L.versions[0];if(!$||$.id===G.activeVersionId){Ge.error("No draft changes to publish. Save a draft first.");return}await n.getStoredAgent(e.agentId).activateVersion($.id)}await Promise.all([r.invalidateQueries({queryKey:["agent-versions",u]}),r.invalidateQueries({queryKey:["stored-agent",u]}),r.invalidateQueries({queryKey:["agent",u]}),r.invalidateQueries({queryKey:["agents"]}),r.invalidateQueries({queryKey:["stored-agents"]})]),Ge.success("Agent published"),e.onSuccess(e.agentId)}else{const G=await _(M),L=M.memory?.enabled?{options:{lastMessages:M.memory.lastMessages,semanticRecall:M.memory.semanticRecall,readOnly:M.memory.readOnly},observationalMemory:pXe(M.memory.observationalMemory)}:void 0,$={...G,memory:L},F=await S.mutateAsync($);Ge.success("Agent created successfully"),e.onSuccess(F.id)}}catch(G){const L=c?"publish":"create";Ge.error(`Failed to ${L} agent: ${G instanceof Error?G.message:"Unknown error"}`)}finally{i(!1)}},[C,c,b,n,S,e,u,_,N,r,I]),D=g.useCallback(async()=>{if(!c)return;if(!await C.trigger()){Ge.error("Please fill in all required fields");return}const M=await _(C.getValues());return n.getStoredAgent(e.agentId).export(M)},[_,n,C,c,e]),z=g.useCallback(async()=>{try{const H=await D();if(!H)return;const M=new Blob([H.content],{type:"application/json"}),G=URL.createObjectURL(M),L=document.createElement("a");L.href=G,L.download=H.fileName,L.click(),URL.revokeObjectURL(G),Ge.success("Agent JSON downloaded")}catch(H){Ge.error(`Failed to download JSON: ${H instanceof Error?H.message:"Unknown error"}`)}},[D]),Q=g.useCallback(async({platformApiEndpoint:H,projectId:M})=>{if(c)try{const G=await D();if(!G)return;const L=H.replace(/\/$/,""),$=await fetch(`${L}/v1/server/projects/${M}/agent-overrides/pr`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:G.agentId,fileName:G.fileName,content:G.content})});if(!$.ok){const U=await $.text();throw new Error(U||`Request failed with ${$.status}`)}const F=await $.json();window.open(F.url,"_blank","noopener,noreferrer"),Ge.success("Pull request opened")}catch(G){Ge.error(`Failed to open PR: ${G instanceof Error?G.message:"Unknown error"}`)}},[D,c]),q=Qn({control:C.control}),B=g.useMemo(()=>{if(d)return(q.instructionBlocks??[]).some(L=>L.type==="prompt_block_ref"||L.type==="prompt_block"&&typeof L.content=="string"&&L.content.trim());const H=!!q.name&&!!q.model?.provider&&!!q.model?.name,M=(q.instructionBlocks??[]).some(G=>G.type==="prompt_block_ref"||G.type==="prompt_block"&&typeof G.content=="string"&&G.content.trim());return H&&M},[d,q.name,q.model?.provider,q.model?.name,q.instructionBlocks]),V=C.formState.isDirty;return{form:C,handlePublish:A,handleSaveDraft:P,handleDownloadJson:z,handleOpenPr:Q,isSubmitting:s,isSavingDraft:o,canPublish:B,isDirty:V}}function S8t({form:e,mode:t,agentId:n,isSubmitting:r,isSavingDraft:s,handlePublish:i,handleSaveDraft:o,readOnly:l,isCodeAgentOverride:c,isCodeSourceAgent:u,editorConfig:d,basePath:f,currentPath:h,banner:p,children:m,versionId:v,rightPanel:y}){return a.jsx(yMt,{form:e,mode:t,agentId:n,isSubmitting:r,isSavingDraft:s,handlePublish:i,handleSaveDraft:o,readOnly:l,isCodeAgentOverride:c,isCodeSourceAgent:u,editorConfig:d,children:a.jsxs(Ics,{basePath:f,currentPath:h,versionId:v,rightPanel:y,children:[p,m]})})}function $us({agentId:e,selectedVersionId:t,onVersionSelect:n,activeVersionId:r}){const{data:s,isLoading:i}=mL({agentId:e,params:{orderBy:{direction:"DESC"}},queryOptions:{enabled:!!e}}),o=s?.versions??[],c=(r?o.find(u=>u.id===r):void 0)?.versionNumber;return a.jsxs("div",{className:"flex h-full flex-col",children:[a.jsx("div",{className:"border-b border-border px-3 py-3",children:a.jsx(Y,{variant:"column",tone:"ink",children:"Version history"})}),a.jsx(Nr,{className:"min-h-0 flex-1",children:i?a.jsx("div",{className:"px-3 py-4",children:a.jsx(Y,{variant:"meta",tone:"faint",children:"Loading versions..."})}):a.jsx("ul",{className:"flex flex-col",children:o.map(u=>{const d=t===u.id||!t&&u.id===o[0]?.id,f=u.id===r,h=c!==void 0&&u.versionNumber>c;return a.jsx("li",{children:a.jsxs("button",{type:"button",onClick:()=>n(u.id),className:Z("text-foreground","w-full border-l-2 px-3 py-2.5 text-left",On,d?"border-border-strong bg-fill-hover":`border-transparent hover:bg-fill-subtle ${Fn}`),children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs(Y,{variant:"caption",className:"text-inherit",children:["v",u.versionNumber]}),f&&a.jsx(Ft,{variant:"success",children:"Published"}),h&&a.jsx(Ft,{variant:"info",children:"Draft"})]}),a.jsx(Y,{variant:"meta",tone:"faint",className:"mt-0.5",children:is(u.createdAt,"date-time")??""})]})},u.id)})})})]})}function rIe({children:e,className:t}){return a.jsx("div",{"data-slot":"sidebar-panel",className:Z("ml-px flex h-full min-h-0 w-full min-w-0 flex-col overflow-hidden rounded-tr-studio-panel border-t border-r border-surface-rim bg-card",t),children:e})}function jI({title:e,icon:t,badge:n}){return a.jsxs(a.Fragment,{children:[a.jsx(Nt,{size:"xs",className:"text-inherit",children:t}),a.jsx(Y,{as:"span",variant:"caption",className:"text-inherit",children:e}),n!=null?a.jsxs(a.Fragment,{children:[" ",n]}):null]})}function k8t({name:e,prop:t,depth:n}){const r=Array.isArray(t.type)?t.type.filter(i=>i!=="null").join(" | "):t.type,s=t.type==="object"&&t.properties&&Object.keys(t.properties).length>0;return a.jsxs("div",{style:n>0?{paddingLeft:n*12}:void 0,children:[a.jsxs("div",{className:"flex items-center gap-2 py-1",children:[a.jsx(dp,{className:"text-caption text-foreground",children:e}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:r}),t.description&&a.jsxs(Y,{as:"span",variant:"caption",tone:"muted",className:"truncate italic",children:["— ",t.description]})]}),s&&a.jsx("div",{className:"ml-1 border-l border-border",children:Object.entries(t.properties).map(([i,o])=>a.jsx(k8t,{name:i,prop:o,depth:n+1},i))})]})}function gXe(e,t){const n=e.split(`
|
|
669
669
|
`),r=t.split(`
|
|
670
|
-
`),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 ave(e){return e.type==="prompt_block"&&typeof e.content=="string"?e.content:null}function Rus({promptBlockId:e}){const{data:t}=M6({blockId:e,queryOptions:{enabled:!!e}}),n=t?.content??"";return n?a.jsx(io,{content:n,tooltip:"Copy prompt block text",size:"sm"}):null}function sM({block:e}){const t=ave(e);return t?a.jsx(io,{content:t,tooltip:"Copy prompt text",size:"sm"}):e.type==="prompt_block_ref"&&(typeof e.promptBlockId=="string"||typeof e.id=="string")?a.jsx(Rus,{promptBlockId:e.promptBlockId??e.id}):null}function Mus({previousBlocks:e,currentBlocks:t}){const n=Array.isArray(e)?e:[],r=Array.isArray(t)?t:[],s=r.map(l=>ave(l)??""),i=n.map(l=>ave(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(sM,{block:u})}),a.jsx(Y,{variant:"caption",tone:"muted",font:"mono",className:"whitespace-pre-wrap",children:l||"(empty)"})]});const d=gXe(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(sM,{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(sM,{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(sM,{block:u})}),a.jsx(Y,{variant:"caption",tone:"muted",font:"mono",className:"whitespace-pre-wrap",children:f||"(empty)"})]},c);const p=gXe(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(sM,{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 Dus({promptBlockId:e}){const{data:t,isLoading:n}=M6({blockId:e,queryOptions:{enabled:!!e}});if(n)return a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(An,{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(io,{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 O8t({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(Dus,{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(io,{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 Lus({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(Ft,{variant:"destructive",className:"ml-auto",children:"removed in latest"}),c==="added"&&a.jsx(Ft,{variant:"success",className:"ml-auto",children:"added in latest"})]},i)})})}function zus({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 Fus({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(Ft,{variant:"destructive",className:"ml-auto",children:"removed in latest"}),d==="added"&&a.jsx(Ft,{variant:"success",className:"ml-auto",children:"added in latest"})]},l)})})}function Bus({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(Ft,{children:String(s.type)}):null]},r))})}function Vus({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r}=kl(),s=r.watch("tools"),i=r.watch("variables"),o=r.watch("instructionBlocks"),l=s?Object.keys(s).length:0,{data:c,isLoading:u}=ksr({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(Ft,{variant:"warning",size:"sm",children:"modified"}):null,v=h?a.jsx(Ft,{variant:"warning",size:"sm",children:"modified"}):l>0?a.jsx(Ft,{size:"sm",children:`${l}`}):null,y=p?a.jsx(Ft,{variant:"warning",size:"sm",children:"modified"}):null;return u?a.jsx("div",{className:"flex items-center justify-center py-5",children:a.jsx(An,{className:"h-5 w-5"})}):a.jsxs(Hl,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[a.jsxs(Gl,{variant:"pill-ghost",className:"shrink-0",children:[a.jsx(ls,{value:"variables",children:a.jsx(jI,{title:"Variables",icon:a.jsx(al,{}),badge:y})}),a.jsx(ls,{value:"instructions",children:a.jsx(jI,{title:"System Prompt",icon:a.jsx(MA,{}),badge:m})}),a.jsx(ls,{value:"tools",children:a.jsx(jI,{title:"Tools",icon:a.jsx(ad,{}),badge:v})})]}),a.jsx(Ls,{value:"variables",className:"px-4 py-4",children:p?a.jsx(Fus,{previousVars:p.previousValue,currentVars:p.currentValue}):a.jsx(Bus,{variables:i})}),a.jsx(Ls,{value:"instructions",className:"px-4 py-4",children:f?a.jsx(Mus,{previousBlocks:f.previousValue,currentBlocks:f.currentValue}):a.jsx(O8t,{blocks:o})}),a.jsx(Ls,{value:"tools",className:"px-4 py-4",children:h?a.jsx(Lus,{previousTools:h.previousValue,currentTools:h.currentValue}):a.jsx(zus,{tools:s})})]})}function Uus({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r,readOnly:s,isCodeAgentOverride:i,editorConfig:o}=kl(),{isInstructionsLocked:l}=P_(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(Nr,{className:"min-h-0 flex-1",children:p?a.jsx(Vus,{agentId:e,selectedVersionId:t,latestVersionId:n}):a.jsxs(Hl,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[a.jsxs(Gl,{variant:"pill-ghost",className:"shrink-0",children:[a.jsx(ls,{value:"variables",children:a.jsx(jI,{title:"Variables",icon:a.jsx(al,{})})}),a.jsx(ls,{value:"instructions",children:a.jsx(jI,{title:"System Prompt",icon:a.jsx(MA,{})})}),a.jsx(ls,{value:"tools",children:a.jsx(jI,{title:"Tools",icon:a.jsx(ad,{}),badge:f>0?a.jsx(Ft,{size:"sm",children:`${f}`}):void 0})})]}),a.jsx(Ls,{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(k8t,{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(Ls,{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($n,{children:[a.jsx(In,{className:Z("inline cursor-pointer underline decoration-dotted",Fn,On),children:"use variables"}),a.jsx(Nn,{side:"bottom",align:"start",className:"max-w-72",children:a.jsxs("span",{children:["Use ",a.jsx(dp,{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(O8t,{blocks:u}):a.jsx(KFt,{})]}),a.jsx(Ls,{value:"tools",className:"px-4 py-0 pb-4",children:a.jsx(YFt,{})})]})})]})}function Dle(e){return typeof e=="object"&&e!==null}function qus(e){if(!Dle(e))return{};const t={};return typeof e.maxSteps=="number"&&(t.maxSteps=e.maxSteps),Dle(e.modelSettings)&&(t.modelSettings=e.modelSettings),Dle(e.providerOptions)&&(t.providerOptions=e.providerOptions),t}function sIe(e){if(!e)return{modelSettings:{}};const t=qus(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 iIe({agentId:e}){return a.jsxs(a.Fragment,{children:[a.jsx(bSe,{entityType:"agent",entityId:e}),a.jsx(Z1t,{entityType:"agent",entityId:e})]})}function Qus({ctx:e}){const{isDirty:t}=g1e({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(de,{type:"button",variant:"default",size:"sm",onClick:()=>n(),disabled:r,icon:a.jsx(Rm,{}),children:r?"Saving...":i}),children:a.jsx(Wt.Message,{children:o})})}function Zus({agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s}){const i=g.useMemo(()=>wa(),[e]),o=wr("agent",e)[0],l=Object.keys(o).length>0,c=ZZr(),{data:u}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),d=g.useMemo(()=>sIe(u),[u]);return a.jsx(tMt,{agentId:e,defaultSettings:d,children:a.jsx(vY,{children:a.jsxs(yY,{agentId:e,threadId:i,enabled:!!(u?.hasBrowser??u?.browserTools?.length),children:[a.jsx(FEe,{children:a.jsx(wY,{children:a.jsx(KWr,{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(Qus,{ctx:c}),a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx(oIe,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,supportsMemory:u?.supportsMemory,threadId:i,memory:s,modelList:u?.modelList,isNewThread:!0,runOptionsSlot:a.jsx(iIe,{agentId:e})},i)})]})})},i)}),a.jsx(jRt,{})]},`session-${e}-${i}`)},`browser-${e}-${i}`)})}function Wus({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}=mL({agentId:e,params:{orderBy:{direction:"DESC"}},queryOptions:{enabled:!!e}}),T=g.useMemo(()=>C?.versions??[],[C?.versions]),_=T[0],I=(t?T.find(q=>q.id===t):void 0)?.versionNumber,P=g.useMemo(()=>T.map(q=>{const B=q.id===t,V=I!==void 0&&q.versionNumber>I;return{value:q.id,label:`${u?"Save":"v"}${q.versionNumber} - ${is(q.createdAt,"date-time")??""}`,description:q.changeMessage||void 0,end:u?a.jsx(Ft,{variant:B?"success":"info",children:B?"Current":"Saved"}):B?a.jsx(Ft,{variant:"success",children:"Published"}):V?a.jsx(Ft,{variant:"info",children:"Draft"}):void 0}}),[T,t,I,u]),A=n??_?.id??"",D=c||!s||i||o,z=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(Ca,{options:P,value:A,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"}),A&&a.jsx(io,{content:A,tooltip:"Copy version ID",size:"sm"}),a.jsxs($n,{children:[a.jsx(In,{"aria-label":"Version information",className:Z("shrink-0 rounded-sm",$i,Fn,On),children:a.jsx(Nt,{size:"xs",children:a.jsx(op,{})})}),a.jsx(Nn,{side:"bottom",align:"start",className:"max-w-56",children:z})]}),a.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[c&&a.jsx(Ft,{variant:"warning",children:"Read-only"}),!c&&l&&!u&&a.jsx(Ft,{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(de,{variant:"default",size:"md",onClick:()=>{v?.()},icon:a.jsx(ip,{}),children:"Download JSON"}),f?a.jsx(de,{variant:"primary",size:"md",onClick:()=>{y?.()},title:h,icon:a.jsx(vdt,{}),children:"Open PR"}):a.jsx(de,{variant:"primary",size:"md",onClick:()=>{p()},disabled:D,children:i?a.jsxs(a.Fragment,{children:[a.jsx(An,{className:"size-3.5"}),"Saving…"]}):a.jsxs(a.Fragment,{children:[a.jsx(Nt,{size:"xs",children:a.jsx(Rm,{})}),"Save to filesystem"]})})]}):c&&!x?null:a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[a.jsxs(Vl,{children:[a.jsx(de,{variant:"default",onClick:()=>p(),disabled:D,children:i?a.jsxs(a.Fragment,{children:[a.jsx(An,{className:"size-3.5"}),"Saving…"]}):a.jsxs(a.Fragment,{children:[a.jsx(Nt,{size:"xs",children:a.jsx(Rm,{})}),"Save New Version"]})}),a.jsxs(ut,{children:[a.jsx(ut.Trigger,{asChild:!0,children:a.jsx(de,{variant:"default",disabled:D,"aria-label":"More save options",children:a.jsx(Fl,{className:"size-3.5"})})}),a.jsx(ut.Content,{align:"end",children:a.jsxs(ut.Item,{onSelect:()=>S(!0),children:[a.jsx(Nt,{size:"xs",children:a.jsx(A3,{})}),"Save with message"]})})]})]}),a.jsx(de,{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(An,{className:"size-3.5"}),"Publishing…"]}):a.jsxs(a.Fragment,{children:[a.jsx(Nt,{size:"xs",children:a.jsx(pr,{})}),x?"Publish This Version":"Publish"]})})]}),a.jsx(rs,{open:b,onOpenChange:S,pending:i,children:a.jsxs(ss,{children:[a.jsxs(es,{children:[a.jsx(Kr,{children:"Save New Version"}),a.jsx(Mo,{children:"Add a message to describe the changes in this version."})]}),a.jsx(Gr,{children:a.jsxs(ft,{children:[a.jsx(lt,{children:"Change message"}),a.jsx(Sn,{placeholder:"Describe what changed...",value:k,onChange:q=>j(q.target.value),onKeyDown:q=>{q.key==="Enter"&&Q()},disabled:i,autoFocus:!0})]})}),a.jsxs(Ho,{children:[a.jsx(ja,{children:"Cancel"}),a.jsx(Oa,{onConfirm:Q,children:"Save Version"})]})]})})]})}}function Hus({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}=Wus({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(rIe,{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(Uus,{agentId:e,selectedVersionId:n,latestVersionId:r})}),k]})}function Gus({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(Xge,{agentId:e,leftDrawerLabel:"Open configuration",leftSlot:a.jsx(Hus,{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(Zus,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s})})}function Lle({value:e,icon:t,label:n}){return a.jsxs(ls,{value:e,children:[a.jsx(Nt,{size:"xs",children:t}),a.jsx(Y,{variant:"caption",className:"text-inherit",children:n})]})}function Kus({agentId:e,activeTab:t,showPlayground:n=!1,showObservability:r=!1}){const{navigate:s}=hn(),i={chat:`/agents/${e}/threads/new`,versions:`/agents/${e}/editor`,traces:`/agents/${e}/traces`},o=l=>{l!=="none"&&s(i[l])};return a.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 p-1.5",children:[a.jsx(Hl,{value:t,defaultTab:t,onValueChange:o,className:"min-w-0",children:a.jsxs(Gl,{variant:"pill-ghost",children:[a.jsx(Lle,{value:"chat",icon:a.jsx(A3,{}),label:"Chat"}),r&&a.jsx(Lle,{value:"traces",icon:a.jsx(ox,{}),label:"Traces"}),n&&a.jsx(Lle,{value:"versions",icon:a.jsx(eN,{}),label:"Editor"})]})}),(!r||!n)&&a.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-0.5",children:[!r&&a.jsx(Iq,{icon:a.jsx(ox,{}),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"}),!n&&a.jsx(Iq,{icon:a.jsx(eN,{}),label:"Editor",tooltipContent:"Add @mastra/editor to enable the Editor.",docsHref:"https://mastra.ai/docs/editor/overview"})]})]})}function lve(){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 j8t(){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(lve,{}),a.jsx(C8t,{})]})})}function C8t(){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 Yus(){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(C8t,{}),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 W9=({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 Xus(e,t){if(!e||VRt(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 Jus({provider:e,modelId:t,settings:n,setSettings:r}){const s=Xus(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 eds=({canEdit:e=!0})=>{const{settings:t,setSettings:n}=RCe(),[r,s]=g.useState(""),[i,o]=g.useState(!1),[l,c]=g.useState(null),{handleCopy:u}=Mm({text:r}),d=JSON.stringify(t?.modelSettings?.providerOptions??{});g.useEffect(()=>{(async()=>{if(!Eq(d)){c("Invalid JSON");return}const v=await K4(d);s(v)})()},[d]);const f=async()=>{if(c(null),!Eq(r)){c("Invalid JSON");return}const m=await K4(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(Fn,On);return a.jsx(pc,{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(ft,{children:[a.jsx(lt,{children:"Frequency Penalty"}),a.jsx(Sn,{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(ft,{children:[a.jsx(lt,{children:"Presence Penalty"}),a.jsx(Sn,{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(ft,{children:[a.jsx(lt,{children:"Top K"}),a.jsx(Sn,{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(ft,{children:[a.jsx(lt,{children:"Max Tokens"}),a.jsx(Sn,{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(ft,{children:[a.jsx(lt,{children:"Max Steps"}),a.jsx(Sn,{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(ft,{children:[a.jsx(lt,{children:"Max Retries"}),a.jsx(Sn,{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(ft,{children:[a.jsx(lt,{children:"Seed"}),a.jsx(Sn,{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(ft,{invalid:!!l,className:"gap-1",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx(lt,{children:"Provider Options"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("button",{type:"button",onClick:f,className:p,"aria-label":"Format Provider Options",children:a.jsx(Nt,{children:a.jsx(al,{})})})}),a.jsx(Nn,{children:"Format the Provider Options JSON"})]}),a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("button",{type:"button",onClick:u,className:p,"aria-label":"Copy Provider Options",children:a.jsx(Nt,{children:a.jsx($m,{})})})}),a.jsx(Nn,{children:"Copy Provider Options"})]}),e&&a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("button",{type:"button",onClick:h,className:p,"aria-label":"Save Provider Options",children:a.jsx(Nt,{children:i?a.jsx(pr,{}):a.jsx(Rm,{})})})}),a.jsx(Nn,{children:i?"Saved":"Save Provider Options"})]})]})]}),a.jsx(Cr,{value:r,onChange:s,language:"json",editable:e,showCopyButton:!1,className:"h-75"}),a.jsx(cs,{children:l})]})]})})},tds=({hasMemory:e,hasSubAgents:t,disabled:n})=>{const r=e&&t,s=n||!r,i=a.jsxs(Qg,{disabled:s,children:[a.jsx(fm,{value:"network",className:"text-foreground"}),a.jsx(lt,{children:"Network"})]});if(r)return i;const o=[];return e||o.push("memory enabled"),t||o.push("at least one sub-agent"),a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:i}),a.jsx(Nn,{children:a.jsxs("p",{children:["Network is not available. Please make sure you have ",o.join(" and "),"."]})})]})},nds=({supported:e,disabled:t})=>{const n=t||!e,r=a.jsxs(Qg,{disabled:n,children:[a.jsx(fm,{value:"streamSubscription",className:"text-foreground"}),a.jsx(lt,{children:"Stream subscription (default)"})]});return e?r:a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:r}),a.jsx(Nn,{children:a.jsx("p",{children:"Stream subscription is not supported for this agent."})})]})},rds=({agentId:e})=>{const{data:t,isLoading:n}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:r,isLoading:s}=gk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{settings:i,setSettings:o,resetAll:l}=RCe(),{canEdit:c}=Ta(),[u,d]=g.useState(!1),[f,h]=g.useState(!1),p=c("agents"),{hasSamplingRestriction:m}=Jus({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(bp,{open:f,onOpenChange:(C,T)=>{if(!C&&u){T?.cancel?.();return}h(C)},children:[a.jsx(rf,{asChild:!0,children:a.jsx(de,{variant:"ghost",size:"icon-md",type:"button",tooltip:"Model settings","data-testid":"composer-model-settings-trigger",children:a.jsx(rTn,{})})}),a.jsx(nh,{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(W9,{label:"Chat Method",children:a.jsxs(t6,{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(Qg,{disabled:!p,children:[a.jsx(fm,{value:"generateLegacy",className:"text-foreground"}),a.jsx(lt,{children:"Generate (Legacy)"})]}),b&&a.jsxs(Qg,{disabled:!p,children:[a.jsx(fm,{value:"generate",className:"text-foreground"}),a.jsx(lt,{children:"Generate"})]}),!b&&a.jsxs(Qg,{disabled:!p,children:[a.jsx(fm,{value:"streamLegacy",className:"text-foreground"}),a.jsx(lt,{children:"Stream (Legacy)"})]}),b&&a.jsx(nds,{supported:S,disabled:!p}),b&&a.jsxs(Qg,{disabled:!p,children:[a.jsx(fm,{value:"stream",className:"text-foreground"}),a.jsx(lt,{children:"Stream"})]}),b&&a.jsx(tds,{hasMemory:v,hasSubAgents:y,disabled:!p})]})}),a.jsx(W9,{label:"Require Tool Approval",children:a.jsx(Iu,{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(op,{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(W9,{label:"Temperature",children:a.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[a.jsx(_ge,{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(W9,{label:"Top P",children:a.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[a.jsx(_ge,{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(de,{icon:a.jsx(JC,{}),variant:"ghost",size:"sm",type:"button",disabled:!p,onClick:()=>p&&l(),children:"Reset"}),a.jsx(de,{icon:a.jsx(P3,{}),variant:"default",size:"sm",type:"button",disabled:!p,onClick:()=>d(!0),children:"Advanced Settings"})]})]})})]}),a.jsx(rs,{open:u,onOpenChange:d,children:a.jsxs(ss,{size:"lg",children:[a.jsx(es,{children:a.jsx(Kr,{children:"Advanced model settings"})}),a.jsx(Gr,{children:a.jsx(eds,{canEdit:p})})]})})]})},sds=()=>{const{data:e}=nP();return{isLiveKitAvailable:e?.liveKitConnectionRouteEnabled!==!1}},ids="/voice/livekit/connection-details",vXe="lk.agent.state",ods="lk.transcription",ads="lk.transcription_final";function lds(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 cds=({agentId:e,threadId:t,onCallStarted:n})=>{const{baseUrl:r,headers:s}=$3(),{isLiveKitAvailable:i}=sds(),o=yr(),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 I=()=>x.current!==_;u("connecting"),p([]);try{const P=await fetch(`${r}${ids}`,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify({agentId:e,threadId:t,resourceId:e}),signal:N.signal});if(I())return;if(!P.ok){const V=await P.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 A=await P.json();if(I())return;const{Room:D,RoomEvent:z,Track:Q}=await Ii(async()=>{const{Room:V,RoomEvent:H,Track:M}=await import("./livekit-client.esm-CKIgC2IJ.js");return{Room:V,RoomEvent:H,Track:M}},[],import.meta.url);if(I())return;const q=new D;m.current=q;const B=new Audio;if(B.autoplay=!0,v.current=B,q.on(z.TrackSubscribed,V=>{V.kind===Q.Kind.Audio&&v.current&&V.attach(v.current)}),q.on(z.ParticipantAttributesChanged,(V,H)=>{const M=V[vXe]??H.attributes[vXe];M&&H.identity!==A.participantName&&f(M)}),q.on(z.Disconnected,()=>{m.current===q&&j()}),q.registerTextStreamHandler(ods,async(V,H)=>{const M=H.identity===A.participantName?"user":"agent",G=V.info.attributes?.[ads]==="true";for await(const L of V)p($=>lds($,V.info.id,M,L,G));M==="agent"&&k()}),await q.connect(A.serverUrl,A.participantToken),I()){q.disconnect(),m.current===q&&(m.current=null);return}if(await q.localParticipant.setMicrophoneEnabled(!0),I()){q.disconnect(),m.current===q&&(m.current=null);return}u("active"),S(),await Promise.resolve(l.current?.()).catch(()=>{})}catch(P){if(N.signal.aborted||I())return;j(),hu.error(P instanceof Error?P.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}},uds=({voiceCall:e})=>{const{isLiveKitAvailable:t}=e;return e.status==="idle"?a.jsx(de,{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(d_n,{})}):e.status==="connecting"?a.jsx(de,{variant:"ghost",size:"icon-md",type:"button",tooltip:"Connecting…","data-testid":"voice-call-button",children:a.jsx(dc,{className:"animate-spin"})}):a.jsx(de,{variant:"destructive-ghost",size:"icon-md",type:"button",tooltip:"End voice call","data-testid":"voice-call-button",onClick:()=>e.stop(),children:a.jsx(c_n,{})})},dds={initializing:"Connecting…",listening:"Listening…",thinking:"Thinking…",speaking:"Speaking…"},yXe=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(e[n]?.role===t)return e[n]},fds=({voiceCall:e})=>{if(e.status==="idle")return null;const t=yXe(e.captions,"user"),n=yXe(e.captions,"agent"),r=e.status==="connecting"?"Connecting…":dds[e.agentState];return a.jsxs("div",{"data-testid":"voice-call-panel",className:Z(hr,"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})]})},hds=300,pds=[],mds=(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},gds=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,vds=({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(AWr,{turns:e,className:"pointer-events-auto sticky top-1/2 -translate-y-1/2"})}),yds=({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}=BEe(n),m=_Zr(),{isRunning:v}=LP(),[y]=wr("agent",t??""),{isSpeaking:x,readAloud:b,stop:S}=irs(t,y,{onError:B=>hu.error(B instanceof Error?B.message:"Voice generation failed.")}),{hasSession:k,viewMode:j}=YL(),C=k&&(j==="collapsed"||j==="expanded"),T=m.length===0,_=m[m.length-1],N=v&&(_?.role!=="assistant"||!gds(_)),I=mds(N,hds),P=g.useMemo(()=>QWr(m),[m]),A=g.useMemo(()=>new Set(P.map(B=>B.messageId)),[P]),D=WWr(m,{key:wge,opensTurn:B=>A.has(B.id)}),z=T&&!c,[Q,q]=g.useState(z);return g.useEffect(()=>{if(Q!==z){if(z||!v){q(z);return}fp(()=>q(!1))}},[z,Q,v]),a.jsx(frs,{controlled:h&&p?{value:h.attachments,onChange:B=>p(V=>({...V,attachments:typeof B=="function"?B(V.attachments):B}))}:void 0,children:a.jsx(jg,{className:"h-full",scroller:{autoScroll:!0,defaultScrollPosition:"last-anchor",onReachStart:u,preserveScrollOnPrepend:!!u},"data-testid":"thread-wrapper",children:a.jsx(jg.Stage,{children:a.jsxs(jg.Viewport,{style:{overflowAnchor:"none"},children:[a.jsx(vds,{turns:P}),a.jsxs(jg.Content,{className:Q?"flex-none":void 0,children:[d&&a.jsx(jg.Column,{"data-testid":"thread-history-older-skeleton","aria-busy":"true","aria-label":"Loading older messages",className:"py-3",children:a.jsx(lve,{})}),T&&c?a.jsx(jg.Column,{"data-testid":"thread-history-skeleton","aria-busy":"true",className:"flex-1 py-4",children:a.jsx(lve,{})}):Q?null:a.jsxs(jg.Column,{ref:f,"data-testid":"thread-message-column",className:"relative flex-1 gap-4 py-4",children:[a.jsx(Crs,{containerRef:f}),a.jsx(bMt,{children:D.map((B,V)=>{const H=V===D.length-1,M=H&&v&&B.opensTurn&&V>0;return a.jsxs(jg.Turn,{opensTurn:B.opensTurn,holdsRoom:M,className:"gap-4",children:[B.entries.map(G=>a.jsx(HCe,{messageId:G.id,scrollAnchor:A.has(G.id),children:a.jsx(Bge,{message:G,hasModelList:s,isSpeaking:x,onReadAloud:b,onStopSpeaking:S})},wge(G))),H&&I&&a.jsx(Kme,{})]},B.key)})}),!v&&a.jsx(JWr,{})]})]}),a.jsxs(jg.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(jg.ScrollButton,{}),a.jsxs(jg.Column,{className:Q?"gap-6 px-1 md:px-1":"gap-2 px-1 md:px-1",children:[Q?a.jsx(xds,{agentName:e}):a.jsxs(a.Fragment,{children:[C&&t&&n&&a.jsx(ORt,{agentName:e}),a.jsx(ass,{})]}),a.jsx("div",{className:Q?"starter-prompt":void 0,children:a.jsx(bds,{agentId:t,threadId:n,hasModelList:s,hideModelSwitcher:i,runOptionsSlot:o,refreshThreadList:l})}),Q?a.jsx(Prs,{prompts:r??pds}):null]})]})]})})})})},xds=({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(OS,{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?"]})]}),bds=({agentId:e,threadId:t,hasModelList:n,hideModelSwitcher:r,runOptionsSlot:s,refreshThreadList:i})=>{const{threadInput:o,setThreadInput:l,updateDraft:c,draftStatus:u}=BEe(t),d=g.useRef(null),f=g.useRef(!1),h=g.useRef(0);g.useEffect(()=>()=>{h.current++},[]);const[p,m]=g.useState(),v=DCe(),{attachments:y,toCoreUserMessages:x,clear:b,isAddingAttachments:S}=P6(),{isRunning:k,canSendWhileStreaming:j,cancelRun:C}=LP(),[T,_]=g.useState(0),{canExecute:N}=Ta(),I=N("agents"),P=!I||!!u?.restoring;Irs(d,{threadId:t,disabled:P});const A=cds({agentId:e,threadId:t,onCallStarted:i}),D=o.trim().length===0&&y.length===0,z=k&&!j,Q=async()=>{if(D||z||!I||u?.restoring||S||f.current)return;f.current=!0;const q=h.current,B=new Set(y.map(V=>V.id));m(void 0);try{const V=y.length>0?await x():void 0;if(h.current!==q)return;c?c(H=>({text:H.text===o?"":H.text,attachments:H.attachments.filter(M=>!B.has(M.id))})):(l(""),b()),_(H=>H+1),v({message:o,attachments:V})}catch{h.current===q&&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(fds,{voiceCall:A}),(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(jrs,{disabled:!I||u?.restoring,children:a.jsx(_Mt,{className:"relative",onSubmit:q=>{q.preventDefault(),Q()},children:a.jsx(EMt,{busy:k,children:a.jsxs(TMt,{sendingPulseKey:T,children:[a.jsx(wrs,{}),a.jsx(NMt,{ref:d,value:o,placeholder:I?"Enter your message...":"You don't have permission to execute agents",onChange:q=>{l(q.target.value)},onKeyDown:q=>{if(!(q.nativeEvent.isComposing||q.keyCode===229)&&q.key==="Enter"&&!q.shiftKey){if(z)return;q.preventDefault(),q.stopPropagation(),Q()}},disabled:P}),e&&!n&&!r&&a.jsx(Cas,{}),a.jsx(AMt,{children:a.jsx(Sds,{canExecute:I,agentId:e,runOptionsSlot:s,showModelSwitcher:!!(e&&!n&&!r),isEmpty:D,isRunning:k,canSendWhileStreaming:j,onCancel:()=>{C()},onSetText:q=>{l(q)},voiceCall:A})})]})})})})]})},wds=({agentId:e,onTranscript:t})=>{const[n]=wr("agent",e??""),{start:r,stop:s,isListening:i,transcript:o}=ivn({agentId:e,requestContext:n});return g.useEffect(()=>{o&&g.startTransition(()=>t(o))},[t,o]),a.jsx(de,{variant:"ghost",size:"icon-md",type:"button",tooltip:i?"Stop dictation":"Start dictation",onClick:()=>i?s():r(),children:i?a.jsx(cve,{}):a.jsx(ICn,{})})},Sds=({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(jas,{}),a.jsx(rds,{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(hrs,{}),e&&a.jsx(wds,{agentId:t,onTranscript:c}),e&&t&&u&&a.jsx(uds,{voiceCall:u})]}),a.jsx(kds,{canExecute:e,isEmpty:s,isRunning:i,canSendWhileStreaming:o,onCancel:l})]})]}),kds=({canExecute:e=!0,isEmpty:t,isRunning:n,canSendWhileStreaming:r,onCancel:s})=>{const{isAddingAttachments:i}=P6();return n&&!r?a.jsx(de,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:a.jsx(cve,{})}):a.jsxs(a.Fragment,{children:[a.jsx(de,{type:"submit",variant:"default",size:"icon-md",tooltip:e?"Send":"No permission to execute",disabled:!e||t||i,children:a.jsx(WS,{})}),n&&a.jsx(de,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:a.jsx(cve,{})})]})},cve=()=>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:Fn,children:[a.jsx("circle",{cx:"12",cy:"12",r:"10"}),a.jsx("rect",{width:"6",height:"6",x:"9",y:"9",rx:"1"})]}),oIe=({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}=RCe(),v=wr("agent",e)[0],{data:y,isLoading:x,fetchNextPage:b,hasNextPage:S,isFetchingNextPage:k}=OG({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(KZr,{agentId:e,agentName:t,modelVersion:i,agentVersionId:o,supportsMemory:l,threadId:n,initialMessages:C,refreshThreadList:s,settings:m,requestContext:v,children:a.jsx(yds,{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 EZ(){return a.jsx(tn,{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(de,{onClick:()=>window.location.reload(),children:"Reload"}),a.jsx(de,{render:a.jsx(oc,{to:"/agents"}),children:"Choose agent"})]})})}function xXe(){const{agentId:e,threadId:t}=fr(),[n]=pi(),{data:r,isLoading:s,error:i}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:o}=gk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),l=Lr(),c=t==="new",u=g.useMemo(()=>wa(),[t]),d=!!o?.result,{refetch:f}=ACe({resourceId:e,agentId:e,isMemoryEnabled:d,requestContext:wr("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(()=>sIe(r),[r]);if(i&&_s(i))return a.jsx(ci,{variant:"fill"});if(i&&Ts(i))return a.jsx(Js,{variant:"fill",resource:"agents"});if(s)return a.jsx(Ods,{});if(i&&ok(i))return a.jsx(EZ,{});if(i)return a.jsx(tn,{tone:"error",titleSlot:"Failed to load agent",descriptionSlot:i.message});if(!r)return a.jsx(EZ,{});const m=c?u:t??u,v=async()=>{await f(),c&&l(`/agents/${e}/session/${u}`)};return a.jsx(tMt,{agentId:e,defaultSettings:p,children:a.jsx(hMt,{agentId:e,threadId:m,resourceId:e,children:a.jsx(vY,{children:a.jsx(yY,{agentId:e,threadId:m,enabled:!!(r?.hasBrowser??r?.browserTools?.length),children:a.jsx(FEe,{children:a.jsx(gMt,{children:a.jsx(wY,{children:a.jsxs(St,{variant:"fit",children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(eMt,{}),a.jsx("div",{className:"relative grid h-full min-h-0",children:a.jsx(oIe,{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(iIe,{agentId:e})},m)})]})})})})},`session-${e}-${m}`)},`browser-${e}-${m}`)})})}const Ods=()=>a.jsxs(St,{variant:"fit",children:[a.jsx("h1",{className:"sr-only",children:"Agent session"}),a.jsx(eMt,{}),a.jsx("div",{className:"relative grid h-full overflow-y-auto pt-4","data-testid":"agent-session-skeleton","aria-busy":"true",children:a.jsx(j8t,{})})]}),jds={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"}},CI=e=>e?Object.keys(e).length:0,LX=e=>e>0?String(e):"Off",_8t=e=>(e?.inputProcessors?.length??0)+(e?.outputProcessors?.length??0),T8t=e=>!!e?.result,E8t=(e,t)=>!!(t&&e&&e.editor!==!1);function WP({view:e,label:t,status:n,description:r,docsHref:s,enabled:i,tone:o,icon:l}){const c=jds[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",$i,Fn,On),children:[a.jsx("span",{className:Z("mt-0.5 size-3.5 shrink-0 text-muted-foreground [&>svg]:size-3.5",On,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(Vs,{className:Z("mt-0.5 size-3 shrink-0 text-muted-foreground group-hover/capability-row:text-foreground",On)})]})}function bXe({agentId:e,view:t}){const{data:n,isLoading:r}=gk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),s=T8t(n),i=s?n?.memoryType==="gateway"?"Gateway":"On":"Off",o=r?"Checking":i;return a.jsx(WP,{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(DP,{})})}function wXe({agentId:e,view:t}){const{data:n,isLoading:r}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{isCmsAvailable:s,isLoading:i}=Ix(),o=E8t(n,s),l=n?.editor===!1,c=mL({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(WP,{view:t,label:"Editor",status:p,description:v,docsHref:"https://mastra.ai/docs/editor/overview",enabled:o,tone:"amber",icon:a.jsx(od,{})})}function SXe({agentId:e,view:t}){const{data:n,isLoading:r}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),s=CI(n?.tools);return a.jsx(WP,{view:t,label:"Tools",status:r?"Checking":LX(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(ad,{})})}function kXe({agentId:e,view:t}){const{data:n,isLoading:r}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),s=CI(n?.workflows);return a.jsx(WP,{view:t,label:"Workflows",status:r?"Checking":LX(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(GS,{})})}function OXe({agentId:e,view:t}){const{data:n,isLoading:r}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),s=CI(n?.agents);return a.jsx(WP,{view:t,label:"Sub-agents",status:r?"Checking":LX(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(rdt,{})})}function jXe({agentId:e,view:t}){const{data:n,isLoading:r}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),s=_8t(n);return a.jsx(WP,{view:t,label:"Processors",status:r?"Checking":LX(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(Ldt,{})})}function Cds({agentId:e}){const{data:t}=gk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:n}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{isCmsAvailable:r}=Ix(),s=[T8t(t),E8t(n,r),CI(n?.tools)>0,CI(n?.workflows)>0,CI(n?.agents)>0,_8t(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 _ds({agentId:e}){const[t,n]=g.useState(!1);return a.jsx(Wl,{open:t,onOpenChange:n,children:a.jsxs("div",{className:"shrink-0 border-t border-border",children:[a.jsx(wl,{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",yx,Fn,On),children:[a.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden",children:[a.jsx(bXe,{agentId:e,view:"chip"}),a.jsx(wXe,{agentId:e,view:"chip"}),a.jsx(SXe,{agentId:e,view:"chip"}),a.jsx(kXe,{agentId:e,view:"chip"}),a.jsx(OXe,{agentId:e,view:"chip"}),a.jsx(jXe,{agentId:e,view:"chip"})]}),a.jsx(Cds,{agentId:e}),a.jsx(Gs,{className:Z("size-3.5 shrink-0 text-muted-foreground transition-transform duration-normal ease-out-custom",t?"rotate-90":void 0)})]})}),a.jsx(Sl,{className:"px-2 pb-2",children:a.jsxs("div",{className:"grid gap-1",children:[a.jsx(bXe,{agentId:e,view:"row"}),a.jsx(wXe,{agentId:e,view:"row"}),a.jsx(SXe,{agentId:e,view:"row"}),a.jsx(kXe,{agentId:e,view:"row"}),a.jsx(OXe,{agentId:e,view:"row"}),a.jsx(jXe,{agentId:e,view:"row"})]})})]})})}function Tds(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 Eds(e){return typeof e=="object"&&e!==null&&"parts"in e&&Array.isArray(e.parts)}function Ids(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 Nds(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 Ads(e){const t=[];for(const n of e){const r=Tds(n.content);if(Eds(r))for(const s of r.parts)Ids(s)&&t.push(Nds(s,new Date(n.createdAt).toISOString()))}return t.sort((n,r)=>n.timestamp.localeCompare(r.timestamp)),t}function uA(e){return/[Zz+-]\d{0,4}$/.test(e.trim())?new Date(e).getTime():new Date(e.trim().replace(" ","T")+"Z").getTime()}function Pds(e){if(e.length===0)return{tMin:0,tMax:1};let t=1/0,n=-1/0;for(const r of e){const s=uA(r);s<t&&(t=s),s>n&&(n=s)}return t===n?{tMin:t,tMax:t+1}:{tMin:t,tMax:n}}function z6(e,t){return(uA(e)-t.tMin)/(t.tMax-t.tMin)}function aIe(e,t){return new Date(t.tMin+e*(t.tMax-t.tMin))}function $ds(e,t){return aIe(e,t).getTime()}function I8t(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function Rds(e){return uA(I8t(e))}function Mds(e,t){if(t==null)return null;const r=e.map(s=>({id:s.id,t:uA(I8t(s))})).toSorted((s,i)=>s.t-i.t).findLast(s=>s.t<=t);return r?r.id:null}function CXe(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function Dds(e){return[...e].sort((t,n)=>uA(CXe(t))-uA(CXe(n)))}function Lds({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=Dds(t).at(-1);return{messageTokens:s?.pendingTokens??i?.pendingMessageTokens,messageThreshold:s?.observationThreshold??n,memoryTokens:s?.observationTokens??i?.observationTokenCount,memoryThreshold:s?.reflectionThreshold??r}}function aD(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function zds(e,t,n){const r=e.map(i=>({ts:String(aD(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:z6(i.ts,n),pendingMessageTokens:i.pendingMessageTokens}))}function Fds(e,t,n){const r=[...e.map(i=>({ts:String(aD(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:z6(i.ts,n),observationTokenCount:s}))}function Bds(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:z6(s.ts,t),bufferedObservationTokenCount:r}))}function Vds(e,t){return[...e].sort((n,r)=>String(aD(n)).localeCompare(String(aD(r)))).map(n=>({t:z6(String(aD(n)),t),event:1}))}function Uds(e,t){return[...e].sort((n,r)=>new Date(n.createdAt).getTime()-new Date(r.createdAt).getTime()).map(n=>({t:z6(new Date(n.createdAt).toISOString(),t),event:1,role:n.role}))}function qds(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 Qds(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 Zds(e){return e==null?null:Number(e)}function Wds(e){return!!e?.event}const Hds="var(--chart-green)",Gds="var(--chart-amber)",_Xe="var(--chart-pink)";function Kds({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:is(aIe(n,e),"date-time-seconds",{timeZone:"UTC"})},n))})]})}function lIe({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?is(aIe(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:`${Jf} 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:`${Jf} rounded px-2 py-1`,children:i&&a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"ink",children:i})})}function Yds({label:e,data:t,dataKey:n,color:r,gradientId:s,domain:i,zoomDomain:o,threshold:l}){const c=Qds(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(CL,{width:"100%",height:32,children:a.jsxs(_Ir,{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(LL,{dataKey:"t",type:"number",domain:o,allowDataOverflow:!0,hide:!0}),a.jsx(zL,{type:"number",domain:c!=null?[0,c]:void 0,hide:!0}),a.jsx(jK,{content:a.jsx(lIe,{domain:i,showValue:!0}),cursor:{stroke:"var(--border)"}}),a.jsx(UOe,{type:"linear",dataKey:n,stroke:r,strokeWidth:1,fill:`url(#${s})`,isAnimationActive:!1}),l!=null&&a.jsx(POe,{y:l,stroke:"var(--border-strong)",strokeDasharray:"4 3"})]})})})]})}function Xds({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(CL,{width:"100%",height:r,children:a.jsxs(jIr,{margin:{top:0,right:0,bottom:0,left:0},children:[a.jsx(LL,{dataKey:"t",type:"number",domain:i,allowDataOverflow:!0,hide:!0}),a.jsx(zL,{dataKey:"event",type:"number",domain:[0,2],hide:!0}),a.jsx(jK,{content:a.jsx(lIe,{domain:s}),cursor:!1}),a.jsx(_Tt,{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 TXe({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=qds(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(CL,{width:"100%",height:u,children:a.jsxs(EIr,{margin:{top:0,right:0,bottom:0,left:0},onClick:h=>{const p=Zds(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(LL,{dataKey:"t",type:"number",domain:l,allowDataOverflow:!0,hide:!0}),a.jsx(zL,{yAxisId:"area",dataKey:n,type:"number",hide:!0,domain:[0,"dataMax"]}),a.jsx(jK,{content:a.jsx(lIe,{domain:o,showValue:!0}),cursor:!1}),a.jsx(UOe,{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=>Wds(h.payload)?a.jsx("circle",{cx:h.cx,cy:h.cy,r:4,fill:s}):a.jsx(a.Fragment,{})}),c!=null&&a.jsx(POe,{yAxisId:"area",y:c,stroke:"var(--border-strong)",strokeDasharray:"4 3"})]})})})]})}function Jds({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(de,{variant:"ghost",size:"icon-sm","aria-label":"Reset zoom",onClick:i,children:a.jsx(JC,{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 efs={tMin:0,tMax:1};function tfs({omRecords:e,markers:t,messages:n,tDomain:r,observationThreshold:s,reflectionThreshold:i,onSelectTimestamp:o,zoomRange:l,onZoomRangeChange:c}){const u=r??efs,d=g.useCallback(Q=>{o?.($ds(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(()=>Uds(n,u),[n,u]),I=g.useMemo(()=>zds(e,t,u),[e,t,u]),P=g.useMemo(()=>Fds(e,t,u),[e,t,u]),A=g.useMemo(()=>Bds(t,u),[t,u]),D=g.useMemo(()=>Vds(e,u),[e,u]);return N.length>0||I.length>0||P.length>0||D.length>0?a.jsxs("div",{className:"flex flex-col pr-2 pb-2 [&_.recharts-surface]:outline-none",children:[a.jsx(TXe,{label:"Messages",areaData:I,areaDataKey:"pendingMessageTokens",eventData:N,color:Hds,gradientId:"grad-messages",domain:u,zoomDomain:_,threshold:s,onSelectT:o?d:void 0}),a.jsx(TXe,{label:"Observations",areaData:P,areaDataKey:"observationTokenCount",eventData:D,color:Gds,gradientId:"grad-observations",domain:u,zoomDomain:_,threshold:i,onSelectT:o?d:void 0}),A.length>0&&a.jsx(Yds,{label:"Buffered obs",data:A,dataKey:"bufferedObservationTokenCount",color:_Xe,gradientId:"grad-buffered-obs",domain:u,zoomDomain:_,threshold:i}),D.length>0&&a.jsx(Xds,{label:"Events",data:D,color:_Xe,domain:u,zoomDomain:_}),a.jsx(Kds,{domain:u}),a.jsx(Jds,{tDomain:u,zoomLeft:y,zoomRight:x,onZoomLeftChange:b,onZoomRightChange:S,onReset:k})]}):null}const nfs=g.lazy(()=>Ii(async()=>{const{CodeDiff:e}=await import("./CodeDiff.es-B7T1Sq6b.js");return{CodeDiff:e}},__vite__mapDeps([9,4,1,3]),import.meta.url).then(({CodeDiff:e})=>({default:e})));function rfs(e){if(!e)return null;const t=e.match(/^(\d{1,2}):(\d{2})$/);if(!t)return e;const[,n,r]=t;return is(new Date(2e3,0,1,Number(n),Number(r)),"time")??e}function sfs(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=Pge[e];return{card:n.card,text:"text-foreground",time:n.time}}function ifs(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(Age))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 ofs(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(`
|
|
670
|
+
`),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 ave(e){return e.type==="prompt_block"&&typeof e.content=="string"?e.content:null}function Rus({promptBlockId:e}){const{data:t}=M6({blockId:e,queryOptions:{enabled:!!e}}),n=t?.content??"";return n?a.jsx(io,{content:n,tooltip:"Copy prompt block text",size:"sm"}):null}function sM({block:e}){const t=ave(e);return t?a.jsx(io,{content:t,tooltip:"Copy prompt text",size:"sm"}):e.type==="prompt_block_ref"&&(typeof e.promptBlockId=="string"||typeof e.id=="string")?a.jsx(Rus,{promptBlockId:e.promptBlockId??e.id}):null}function Mus({previousBlocks:e,currentBlocks:t}){const n=Array.isArray(e)?e:[],r=Array.isArray(t)?t:[],s=r.map(l=>ave(l)??""),i=n.map(l=>ave(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(sM,{block:u})}),a.jsx(Y,{variant:"caption",tone:"muted",font:"mono",className:"whitespace-pre-wrap",children:l||"(empty)"})]});const d=gXe(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(sM,{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(sM,{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(sM,{block:u})}),a.jsx(Y,{variant:"caption",tone:"muted",font:"mono",className:"whitespace-pre-wrap",children:f||"(empty)"})]},c);const p=gXe(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(sM,{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 Dus({promptBlockId:e}){const{data:t,isLoading:n}=M6({blockId:e,queryOptions:{enabled:!!e}});if(n)return a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(An,{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(io,{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 O8t({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(Dus,{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(io,{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 Lus({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(Ft,{variant:"destructive",className:"ml-auto",children:"removed in latest"}),c==="added"&&a.jsx(Ft,{variant:"success",className:"ml-auto",children:"added in latest"})]},i)})})}function zus({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 Fus({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(Ft,{variant:"destructive",className:"ml-auto",children:"removed in latest"}),d==="added"&&a.jsx(Ft,{variant:"success",className:"ml-auto",children:"added in latest"})]},l)})})}function Bus({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(Ft,{children:String(s.type)}):null]},r))})}function Vus({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r}=kl(),s=r.watch("tools"),i=r.watch("variables"),o=r.watch("instructionBlocks"),l=s?Object.keys(s).length:0,{data:c,isLoading:u}=ksr({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(Ft,{variant:"warning",size:"sm",children:"modified"}):null,v=h?a.jsx(Ft,{variant:"warning",size:"sm",children:"modified"}):l>0?a.jsx(Ft,{size:"sm",children:`${l}`}):null,y=p?a.jsx(Ft,{variant:"warning",size:"sm",children:"modified"}):null;return u?a.jsx("div",{className:"flex items-center justify-center py-5",children:a.jsx(An,{className:"h-5 w-5"})}):a.jsxs(Hl,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[a.jsxs(Gl,{variant:"pill-ghost",className:"shrink-0",children:[a.jsx(ls,{value:"variables",children:a.jsx(jI,{title:"Variables",icon:a.jsx(al,{}),badge:y})}),a.jsx(ls,{value:"instructions",children:a.jsx(jI,{title:"System Prompt",icon:a.jsx(MA,{}),badge:m})}),a.jsx(ls,{value:"tools",children:a.jsx(jI,{title:"Tools",icon:a.jsx(ad,{}),badge:v})})]}),a.jsx(Ls,{value:"variables",className:"px-4 py-4",children:p?a.jsx(Fus,{previousVars:p.previousValue,currentVars:p.currentValue}):a.jsx(Bus,{variables:i})}),a.jsx(Ls,{value:"instructions",className:"px-4 py-4",children:f?a.jsx(Mus,{previousBlocks:f.previousValue,currentBlocks:f.currentValue}):a.jsx(O8t,{blocks:o})}),a.jsx(Ls,{value:"tools",className:"px-4 py-4",children:h?a.jsx(Lus,{previousTools:h.previousValue,currentTools:h.currentValue}):a.jsx(zus,{tools:s})})]})}function Uus({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r,readOnly:s,isCodeAgentOverride:i,editorConfig:o}=kl(),{isInstructionsLocked:l}=P_(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(Nr,{className:"min-h-0 flex-1",children:p?a.jsx(Vus,{agentId:e,selectedVersionId:t,latestVersionId:n}):a.jsxs(Hl,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[a.jsxs(Gl,{variant:"pill-ghost",className:"shrink-0",children:[a.jsx(ls,{value:"variables",children:a.jsx(jI,{title:"Variables",icon:a.jsx(al,{})})}),a.jsx(ls,{value:"instructions",children:a.jsx(jI,{title:"System Prompt",icon:a.jsx(MA,{})})}),a.jsx(ls,{value:"tools",children:a.jsx(jI,{title:"Tools",icon:a.jsx(ad,{}),badge:f>0?a.jsx(Ft,{size:"sm",children:`${f}`}):void 0})})]}),a.jsx(Ls,{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(k8t,{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(Ls,{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($n,{children:[a.jsx(In,{className:Z("inline cursor-pointer underline decoration-dotted",Fn,On),children:"use variables"}),a.jsx(Nn,{side:"bottom",align:"start",className:"max-w-72",children:a.jsxs("span",{children:["Use ",a.jsx(dp,{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(O8t,{blocks:u}):a.jsx(KFt,{})]}),a.jsx(Ls,{value:"tools",className:"px-4 py-0 pb-4",children:a.jsx(YFt,{})})]})})]})}function Dle(e){return typeof e=="object"&&e!==null}function qus(e){if(!Dle(e))return{};const t={};return typeof e.maxSteps=="number"&&(t.maxSteps=e.maxSteps),Dle(e.modelSettings)&&(t.modelSettings=e.modelSettings),Dle(e.providerOptions)&&(t.providerOptions=e.providerOptions),t}function sIe(e){if(!e)return{modelSettings:{}};const t=qus(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 iIe({agentId:e}){return a.jsxs(a.Fragment,{children:[a.jsx(bSe,{entityType:"agent",entityId:e}),a.jsx(Z1t,{entityType:"agent",entityId:e})]})}function Qus({ctx:e}){const{isDirty:t}=g1e({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(de,{type:"button",variant:"default",size:"sm",onClick:()=>n(),disabled:r,icon:a.jsx(Rm,{}),children:r?"Saving...":i}),children:a.jsx(Wt.Message,{children:o})})}function Zus({agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s}){const i=g.useMemo(()=>wa(),[e]),o=wr("agent",e)[0],l=Object.keys(o).length>0,c=ZZr(),{data:u}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),d=g.useMemo(()=>sIe(u),[u]);return a.jsx(tMt,{agentId:e,defaultSettings:d,children:a.jsx(vY,{children:a.jsxs(yY,{agentId:e,threadId:i,enabled:!!(u?.hasBrowser??u?.browserTools?.length),children:[a.jsx(FEe,{children:a.jsx(wY,{children:a.jsx(KWr,{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(Qus,{ctx:c}),a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx(oIe,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,supportsMemory:u?.supportsMemory,threadId:i,memory:s,modelList:u?.modelList,isNewThread:!0,runOptionsSlot:a.jsx(iIe,{agentId:e})},i)})]})})},i)}),a.jsx(jRt,{})]},`session-${e}-${i}`)},`browser-${e}-${i}`)})}function Wus({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}=mL({agentId:e,params:{orderBy:{direction:"DESC"}},queryOptions:{enabled:!!e}}),T=g.useMemo(()=>C?.versions??[],[C?.versions]),_=T[0],I=(t?T.find(q=>q.id===t):void 0)?.versionNumber,P=g.useMemo(()=>T.map(q=>{const B=q.id===t,V=I!==void 0&&q.versionNumber>I;return{value:q.id,label:`${u?"Save":"v"}${q.versionNumber} - ${is(q.createdAt,"date-time")??""}`,description:q.changeMessage||void 0,end:u?a.jsx(Ft,{variant:B?"success":"info",children:B?"Current":"Saved"}):B?a.jsx(Ft,{variant:"success",children:"Published"}):V?a.jsx(Ft,{variant:"info",children:"Draft"}):void 0}}),[T,t,I,u]),A=n??_?.id??"",D=c||!s||i||o,z=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(Ca,{options:P,value:A,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"}),A&&a.jsx(io,{content:A,tooltip:"Copy version ID",size:"sm"}),a.jsxs($n,{children:[a.jsx(In,{"aria-label":"Version information",className:Z("shrink-0 rounded-sm",$i,Fn,On),children:a.jsx(Nt,{size:"xs",children:a.jsx(op,{})})}),a.jsx(Nn,{side:"bottom",align:"start",className:"max-w-56",children:z})]}),a.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[c&&a.jsx(Ft,{variant:"warning",children:"Read-only"}),!c&&l&&!u&&a.jsx(Ft,{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(de,{variant:"default",size:"md",onClick:()=>{v?.()},icon:a.jsx(ip,{}),children:"Download JSON"}),f?a.jsx(de,{variant:"primary",size:"md",onClick:()=>{y?.()},title:h,icon:a.jsx(vdt,{}),children:"Open PR"}):a.jsx(de,{variant:"primary",size:"md",onClick:()=>{p()},disabled:D,children:i?a.jsxs(a.Fragment,{children:[a.jsx(An,{className:"size-3.5"}),"Saving…"]}):a.jsxs(a.Fragment,{children:[a.jsx(Nt,{size:"xs",children:a.jsx(Rm,{})}),"Save to filesystem"]})})]}):c&&!x?null:a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[a.jsxs(Vl,{children:[a.jsx(de,{variant:"default",onClick:()=>p(),disabled:D,children:i?a.jsxs(a.Fragment,{children:[a.jsx(An,{className:"size-3.5"}),"Saving…"]}):a.jsxs(a.Fragment,{children:[a.jsx(Nt,{size:"xs",children:a.jsx(Rm,{})}),"Save New Version"]})}),a.jsxs(ut,{children:[a.jsx(ut.Trigger,{asChild:!0,children:a.jsx(de,{variant:"default",disabled:D,"aria-label":"More save options",children:a.jsx(Fl,{className:"size-3.5"})})}),a.jsx(ut.Content,{align:"end",children:a.jsxs(ut.Item,{onSelect:()=>S(!0),children:[a.jsx(Nt,{size:"xs",children:a.jsx(A3,{})}),"Save with message"]})})]})]}),a.jsx(de,{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(An,{className:"size-3.5"}),"Publishing…"]}):a.jsxs(a.Fragment,{children:[a.jsx(Nt,{size:"xs",children:a.jsx(pr,{})}),x?"Publish This Version":"Publish"]})})]}),a.jsx(rs,{open:b,onOpenChange:S,pending:i,children:a.jsxs(ss,{children:[a.jsxs(es,{children:[a.jsx(Kr,{children:"Save New Version"}),a.jsx(Mo,{children:"Add a message to describe the changes in this version."})]}),a.jsx(Gr,{children:a.jsxs(ft,{children:[a.jsx(lt,{children:"Change message"}),a.jsx(Sn,{placeholder:"Describe what changed...",value:k,onChange:q=>j(q.target.value),onKeyDown:q=>{q.key==="Enter"&&Q()},disabled:i,autoFocus:!0})]})}),a.jsxs(Ho,{children:[a.jsx(ja,{children:"Cancel"}),a.jsx(Oa,{onConfirm:Q,children:"Save Version"})]})]})})]})}}function Hus({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}=Wus({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(rIe,{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(Uus,{agentId:e,selectedVersionId:n,latestVersionId:r})}),k]})}function Gus({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(Xge,{agentId:e,leftDrawerLabel:"Open configuration",leftSlot:a.jsx(Hus,{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(Zus,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s})})}function Lle({value:e,icon:t,label:n}){return a.jsxs(ls,{value:e,children:[a.jsx(Nt,{size:"xs",children:t}),a.jsx(Y,{variant:"caption",className:"text-inherit",children:n})]})}function Kus({agentId:e,activeTab:t,showPlayground:n=!1,showObservability:r=!1}){const{navigate:s}=hn(),i={chat:`/agents/${e}/threads/new`,versions:`/agents/${e}/editor`,traces:`/agents/${e}/traces`},o=l=>{l!=="none"&&s(i[l])};return a.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 p-1.5",children:[a.jsx(Hl,{value:t,defaultTab:t,onValueChange:o,className:"min-w-0",children:a.jsxs(Gl,{variant:"pill-ghost",children:[a.jsx(Lle,{value:"chat",icon:a.jsx(A3,{}),label:"Chat"}),r&&a.jsx(Lle,{value:"traces",icon:a.jsx(ox,{}),label:"Traces"}),n&&a.jsx(Lle,{value:"versions",icon:a.jsx(eN,{}),label:"Editor"})]})}),(!r||!n)&&a.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-0.5",children:[!r&&a.jsx(Iq,{icon:a.jsx(ox,{}),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"}),!n&&a.jsx(Iq,{icon:a.jsx(eN,{}),label:"Editor",tooltipContent:"Add @mastra/editor to enable the Editor.",docsHref:"https://mastra.ai/docs/editor/overview"})]})]})}function lve(){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 j8t(){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(lve,{}),a.jsx(C8t,{})]})})}function C8t(){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 Yus(){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(C8t,{}),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 W9=({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 Xus(e,t){if(!e||VRt(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 Jus({provider:e,modelId:t,settings:n,setSettings:r}){const s=Xus(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 eds=({canEdit:e=!0})=>{const{settings:t,setSettings:n}=RCe(),[r,s]=g.useState(""),[i,o]=g.useState(!1),[l,c]=g.useState(null),{handleCopy:u}=Mm({text:r}),d=JSON.stringify(t?.modelSettings?.providerOptions??{});g.useEffect(()=>{(async()=>{if(!Eq(d)){c("Invalid JSON");return}const v=await K4(d);s(v)})()},[d]);const f=async()=>{if(c(null),!Eq(r)){c("Invalid JSON");return}const m=await K4(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(Fn,On);return a.jsx(pc,{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(ft,{children:[a.jsx(lt,{children:"Frequency Penalty"}),a.jsx(Sn,{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(ft,{children:[a.jsx(lt,{children:"Presence Penalty"}),a.jsx(Sn,{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(ft,{children:[a.jsx(lt,{children:"Top K"}),a.jsx(Sn,{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(ft,{children:[a.jsx(lt,{children:"Max Tokens"}),a.jsx(Sn,{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(ft,{children:[a.jsx(lt,{children:"Max Steps"}),a.jsx(Sn,{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(ft,{children:[a.jsx(lt,{children:"Max Retries"}),a.jsx(Sn,{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(ft,{children:[a.jsx(lt,{children:"Seed"}),a.jsx(Sn,{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(ft,{invalid:!!l,className:"gap-1",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx(lt,{children:"Provider Options"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("button",{type:"button",onClick:f,className:p,"aria-label":"Format Provider Options",children:a.jsx(Nt,{children:a.jsx(al,{})})})}),a.jsx(Nn,{children:"Format the Provider Options JSON"})]}),a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("button",{type:"button",onClick:u,className:p,"aria-label":"Copy Provider Options",children:a.jsx(Nt,{children:a.jsx($m,{})})})}),a.jsx(Nn,{children:"Copy Provider Options"})]}),e&&a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("button",{type:"button",onClick:h,className:p,"aria-label":"Save Provider Options",children:a.jsx(Nt,{children:i?a.jsx(pr,{}):a.jsx(Rm,{})})})}),a.jsx(Nn,{children:i?"Saved":"Save Provider Options"})]})]})]}),a.jsx(Cr,{value:r,onChange:s,language:"json",editable:e,showCopyButton:!1,className:"h-75"}),a.jsx(cs,{children:l})]})]})})},tds=({hasMemory:e,hasSubAgents:t,disabled:n})=>{const r=e&&t,s=n||!r,i=a.jsxs(Qg,{disabled:s,children:[a.jsx(fm,{value:"network",className:"text-foreground"}),a.jsx(lt,{children:"Network"})]});if(r)return i;const o=[];return e||o.push("memory enabled"),t||o.push("at least one sub-agent"),a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:i}),a.jsx(Nn,{children:a.jsxs("p",{children:["Network is not available. Please make sure you have ",o.join(" and "),"."]})})]})},nds=({supported:e,disabled:t})=>{const n=t||!e,r=a.jsxs(Qg,{disabled:n,children:[a.jsx(fm,{value:"streamSubscription",className:"text-foreground"}),a.jsx(lt,{children:"Stream subscription (default)"})]});return e?r:a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:r}),a.jsx(Nn,{children:a.jsx("p",{children:"Stream subscription is not supported for this agent."})})]})},rds=({agentId:e})=>{const{data:t,isLoading:n}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:r,isLoading:s}=gk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{settings:i,setSettings:o,resetAll:l}=RCe(),{canEdit:c}=Ta(),[u,d]=g.useState(!1),[f,h]=g.useState(!1),p=c("agents"),{hasSamplingRestriction:m}=Jus({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(bp,{open:f,onOpenChange:(C,T)=>{if(!C&&u){T?.cancel?.();return}h(C)},children:[a.jsx(rf,{asChild:!0,children:a.jsx(de,{variant:"ghost",size:"icon-md",type:"button",tooltip:"Model settings","data-testid":"composer-model-settings-trigger",children:a.jsx(rTn,{})})}),a.jsx(nh,{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(W9,{label:"Chat Method",children:a.jsxs(t6,{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(Qg,{disabled:!p,children:[a.jsx(fm,{value:"generateLegacy",className:"text-foreground"}),a.jsx(lt,{children:"Generate (Legacy)"})]}),b&&a.jsxs(Qg,{disabled:!p,children:[a.jsx(fm,{value:"generate",className:"text-foreground"}),a.jsx(lt,{children:"Generate"})]}),!b&&a.jsxs(Qg,{disabled:!p,children:[a.jsx(fm,{value:"streamLegacy",className:"text-foreground"}),a.jsx(lt,{children:"Stream (Legacy)"})]}),b&&a.jsx(nds,{supported:S,disabled:!p}),b&&a.jsxs(Qg,{disabled:!p,children:[a.jsx(fm,{value:"stream",className:"text-foreground"}),a.jsx(lt,{children:"Stream"})]}),b&&a.jsx(tds,{hasMemory:v,hasSubAgents:y,disabled:!p})]})}),a.jsx(W9,{label:"Require Tool Approval",children:a.jsx(Iu,{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(op,{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(W9,{label:"Temperature",children:a.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[a.jsx(_ge,{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(W9,{label:"Top P",children:a.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[a.jsx(_ge,{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(de,{icon:a.jsx(JC,{}),variant:"ghost",size:"sm",type:"button",disabled:!p,onClick:()=>p&&l(),children:"Reset"}),a.jsx(de,{icon:a.jsx(P3,{}),variant:"default",size:"sm",type:"button",disabled:!p,onClick:()=>d(!0),children:"Advanced Settings"})]})]})})]}),a.jsx(rs,{open:u,onOpenChange:d,children:a.jsxs(ss,{size:"lg",children:[a.jsx(es,{children:a.jsx(Kr,{children:"Advanced model settings"})}),a.jsx(Gr,{children:a.jsx(eds,{canEdit:p})})]})})]})},sds=()=>{const{data:e}=nP();return{isLiveKitAvailable:e?.liveKitConnectionRouteEnabled!==!1}},ids="/voice/livekit/connection-details",vXe="lk.agent.state",ods="lk.transcription",ads="lk.transcription_final";function lds(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 cds=({agentId:e,threadId:t,onCallStarted:n})=>{const{baseUrl:r,headers:s}=$3(),{isLiveKitAvailable:i}=sds(),o=yr(),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 I=()=>x.current!==_;u("connecting"),p([]);try{const P=await fetch(`${r}${ids}`,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify({agentId:e,threadId:t,resourceId:e}),signal:N.signal});if(I())return;if(!P.ok){const V=await P.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 A=await P.json();if(I())return;const{Room:D,RoomEvent:z,Track:Q}=await Ii(async()=>{const{Room:V,RoomEvent:H,Track:M}=await import("./livekit-client.esm-CKIgC2IJ.js");return{Room:V,RoomEvent:H,Track:M}},[],import.meta.url);if(I())return;const q=new D;m.current=q;const B=new Audio;if(B.autoplay=!0,v.current=B,q.on(z.TrackSubscribed,V=>{V.kind===Q.Kind.Audio&&v.current&&V.attach(v.current)}),q.on(z.ParticipantAttributesChanged,(V,H)=>{const M=V[vXe]??H.attributes[vXe];M&&H.identity!==A.participantName&&f(M)}),q.on(z.Disconnected,()=>{m.current===q&&j()}),q.registerTextStreamHandler(ods,async(V,H)=>{const M=H.identity===A.participantName?"user":"agent",G=V.info.attributes?.[ads]==="true";for await(const L of V)p($=>lds($,V.info.id,M,L,G));M==="agent"&&k()}),await q.connect(A.serverUrl,A.participantToken),I()){q.disconnect(),m.current===q&&(m.current=null);return}if(await q.localParticipant.setMicrophoneEnabled(!0),I()){q.disconnect(),m.current===q&&(m.current=null);return}u("active"),S(),await Promise.resolve(l.current?.()).catch(()=>{})}catch(P){if(N.signal.aborted||I())return;j(),hu.error(P instanceof Error?P.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}},uds=({voiceCall:e})=>{const{isLiveKitAvailable:t}=e;return e.status==="idle"?a.jsx(de,{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(d_n,{})}):e.status==="connecting"?a.jsx(de,{variant:"ghost",size:"icon-md",type:"button",tooltip:"Connecting…","data-testid":"voice-call-button",children:a.jsx(dc,{className:"animate-spin"})}):a.jsx(de,{variant:"destructive-ghost",size:"icon-md",type:"button",tooltip:"End voice call","data-testid":"voice-call-button",onClick:()=>e.stop(),children:a.jsx(c_n,{})})},dds={initializing:"Connecting…",listening:"Listening…",thinking:"Thinking…",speaking:"Speaking…"},yXe=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(e[n]?.role===t)return e[n]},fds=({voiceCall:e})=>{if(e.status==="idle")return null;const t=yXe(e.captions,"user"),n=yXe(e.captions,"agent"),r=e.status==="connecting"?"Connecting…":dds[e.agentState];return a.jsxs("div",{"data-testid":"voice-call-panel",className:Z(hr,"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})]})},hds=300,pds=[],mds=(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},gds=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,vds=({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(AWr,{turns:e,className:"pointer-events-auto sticky top-1/2 -translate-y-1/2"})}),yds=({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}=BEe(n),m=_Zr(),{isRunning:v}=LP(),[y]=wr("agent",t??""),{isSpeaking:x,readAloud:b,stop:S}=irs(t,y,{onError:B=>hu.error(B instanceof Error?B.message:"Voice generation failed.")}),{hasSession:k,viewMode:j}=YL(),C=k&&(j==="collapsed"||j==="expanded"),T=m.length===0,_=m[m.length-1],N=v&&(_?.role!=="assistant"||!gds(_)),I=mds(N,hds),P=g.useMemo(()=>QWr(m),[m]),A=g.useMemo(()=>new Set(P.map(B=>B.messageId)),[P]),D=WWr(m,{key:wge,opensTurn:B=>A.has(B.id)}),z=T&&!c,[Q,q]=g.useState(z);return g.useEffect(()=>{if(Q!==z){if(z||!v){q(z);return}fp(()=>q(!1))}},[z,Q,v]),a.jsx(frs,{controlled:h&&p?{value:h.attachments,onChange:B=>p(V=>({...V,attachments:typeof B=="function"?B(V.attachments):B}))}:void 0,children:a.jsx(jg,{className:"h-full",scroller:{autoScroll:!0,defaultScrollPosition:"last-anchor",onReachStart:u,preserveScrollOnPrepend:!!u},"data-testid":"thread-wrapper",children:a.jsx(jg.Stage,{children:a.jsxs(jg.Viewport,{style:{overflowAnchor:"none"},children:[a.jsx(vds,{turns:P}),a.jsxs(jg.Content,{className:Q?"flex-none":void 0,children:[d&&a.jsx(jg.Column,{"data-testid":"thread-history-older-skeleton","aria-busy":"true","aria-label":"Loading older messages",className:"py-3",children:a.jsx(lve,{})}),T&&c?a.jsx(jg.Column,{"data-testid":"thread-history-skeleton","aria-busy":"true",className:"flex-1 py-4",children:a.jsx(lve,{})}):Q?null:a.jsxs(jg.Column,{ref:f,"data-testid":"thread-message-column",className:"relative flex-1 gap-4 py-4",children:[a.jsx(Crs,{containerRef:f}),a.jsx(bMt,{children:D.map((B,V)=>{const H=V===D.length-1,M=H&&v&&B.opensTurn&&V>0;return a.jsxs(jg.Turn,{opensTurn:B.opensTurn,holdsRoom:M,className:"gap-4",children:[B.entries.map(G=>a.jsx(HCe,{messageId:G.id,scrollAnchor:A.has(G.id),children:a.jsx(Bge,{message:G,hasModelList:s,isSpeaking:x,onReadAloud:b,onStopSpeaking:S})},wge(G))),H&&I&&a.jsx(Kme,{})]},B.key)})}),!v&&a.jsx(JWr,{})]})]}),a.jsxs(jg.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(jg.ScrollButton,{}),a.jsxs(jg.Column,{className:Q?"gap-6 px-1 md:px-1":"gap-2 px-1 md:px-1",children:[Q?a.jsx(xds,{agentName:e}):a.jsxs(a.Fragment,{children:[C&&t&&n&&a.jsx(ORt,{agentName:e}),a.jsx(ass,{})]}),a.jsx("div",{className:Q?"starter-prompt":void 0,children:a.jsx(bds,{agentId:t,threadId:n,hasModelList:s,hideModelSwitcher:i,runOptionsSlot:o,refreshThreadList:l})}),Q?a.jsx(Prs,{prompts:r??pds}):null]})]})]})})})})},xds=({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(OS,{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?"]})]}),bds=({agentId:e,threadId:t,hasModelList:n,hideModelSwitcher:r,runOptionsSlot:s,refreshThreadList:i})=>{const{threadInput:o,setThreadInput:l,updateDraft:c,draftStatus:u}=BEe(t),d=g.useRef(null),f=g.useRef(!1),h=g.useRef(0);g.useEffect(()=>()=>{h.current++},[]);const[p,m]=g.useState(),v=DCe(),{attachments:y,toCoreUserMessages:x,clear:b,isAddingAttachments:S}=P6(),{isRunning:k,canSendWhileStreaming:j,cancelRun:C}=LP(),[T,_]=g.useState(0),{canExecute:N}=Ta(),I=N("agents"),P=!I||!!u?.restoring;Irs(d,{threadId:t,disabled:P});const A=cds({agentId:e,threadId:t,onCallStarted:i}),D=o.trim().length===0&&y.length===0,z=k&&!j,Q=async()=>{if(D||z||!I||u?.restoring||S||f.current)return;f.current=!0;const q=h.current,B=new Set(y.map(V=>V.id));m(void 0);try{const V=y.length>0?await x():void 0;if(h.current!==q)return;c?c(H=>({text:H.text===o?"":H.text,attachments:H.attachments.filter(M=>!B.has(M.id))})):(l(""),b()),_(H=>H+1),v({message:o,attachments:V})}catch{h.current===q&&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(fds,{voiceCall:A}),(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(jrs,{disabled:!I||u?.restoring,children:a.jsx(_Mt,{className:"relative",onSubmit:q=>{q.preventDefault(),Q()},children:a.jsx(EMt,{busy:k,children:a.jsxs(TMt,{sendingPulseKey:T,children:[a.jsx(wrs,{}),a.jsx(NMt,{ref:d,value:o,placeholder:I?"Enter your message...":"You don't have permission to execute agents",onChange:q=>{l(q.target.value)},onKeyDown:q=>{if(!(q.nativeEvent.isComposing||q.keyCode===229)&&q.key==="Enter"&&!q.shiftKey){if(z)return;q.preventDefault(),q.stopPropagation(),Q()}},disabled:P}),e&&!n&&!r&&a.jsx(Cas,{}),a.jsx(AMt,{children:a.jsx(Sds,{canExecute:I,agentId:e,runOptionsSlot:s,showModelSwitcher:!!(e&&!n&&!r),isEmpty:D,isRunning:k,canSendWhileStreaming:j,onCancel:()=>{C()},onSetText:q=>{l(q)},voiceCall:A})})]})})})})]})},wds=({agentId:e,onTranscript:t})=>{const[n]=wr("agent",e??""),{start:r,stop:s,isListening:i,transcript:o}=ivn({agentId:e,requestContext:n});return g.useEffect(()=>{o&&g.startTransition(()=>t(o))},[t,o]),a.jsx(de,{variant:"ghost",size:"icon-md",type:"button",tooltip:i?"Stop dictation":"Start dictation",onClick:()=>i?s():r(),children:i?a.jsx(cve,{}):a.jsx(ICn,{})})},Sds=({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(jas,{}),a.jsx(rds,{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(hrs,{}),e&&a.jsx(wds,{agentId:t,onTranscript:c}),e&&t&&u&&a.jsx(uds,{voiceCall:u})]}),a.jsx(kds,{canExecute:e,isEmpty:s,isRunning:i,canSendWhileStreaming:o,onCancel:l})]})]}),kds=({canExecute:e=!0,isEmpty:t,isRunning:n,canSendWhileStreaming:r,onCancel:s})=>{const{isAddingAttachments:i}=P6();return n&&!r?a.jsx(de,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:a.jsx(cve,{})}):a.jsxs(a.Fragment,{children:[a.jsx(de,{type:"submit",variant:"default",size:"icon-md",tooltip:e?"Send":"No permission to execute",disabled:!e||t||i,children:a.jsx(WS,{})}),n&&a.jsx(de,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:a.jsx(cve,{})})]})},cve=()=>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:Fn,children:[a.jsx("circle",{cx:"12",cy:"12",r:"10"}),a.jsx("rect",{width:"6",height:"6",x:"9",y:"9",rx:"1"})]}),oIe=({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}=RCe(),v=wr("agent",e)[0],{data:y,isLoading:x,fetchNextPage:b,hasNextPage:S,isFetchingNextPage:k}=OG({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(KZr,{agentId:e,agentName:t,modelVersion:i,agentVersionId:o,supportsMemory:l,threadId:n,initialMessages:C,refreshThreadList:s,settings:m,requestContext:v,children:a.jsx(yds,{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 EZ(){return a.jsx(tn,{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(de,{onClick:()=>window.location.reload(),children:"Reload"}),a.jsx(de,{render:a.jsx(oc,{to:"/agents"}),children:"Choose agent"})]})})}function xXe(){const{agentId:e,threadId:t}=fr(),[n]=pi(),{data:r,isLoading:s,error:i}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:o}=gk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),l=Lr(),c=t==="new",u=g.useMemo(()=>wa(),[t]),d=!!o?.result,{refetch:f}=ACe({resourceId:e,agentId:e,isMemoryEnabled:d,requestContext:wr("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(()=>sIe(r),[r]);if(i&&_s(i))return a.jsx(ci,{variant:"fill"});if(i&&Ts(i))return a.jsx(Js,{variant:"fill",resource:"agents"});if(s)return a.jsx(Ods,{});if(i&&ok(i))return a.jsx(EZ,{});if(i)return a.jsx(tn,{tone:"error",titleSlot:"Failed to load agent",descriptionSlot:i.message});if(!r)return a.jsx(EZ,{});const m=c?u:t??u,v=async()=>{await f(),c&&l(`/agents/${e}/session/${u}`)};return a.jsx(tMt,{agentId:e,defaultSettings:p,children:a.jsx(hMt,{agentId:e,threadId:m,resourceId:e,children:a.jsx(vY,{children:a.jsx(yY,{agentId:e,threadId:m,enabled:!!(r?.hasBrowser??r?.browserTools?.length),children:a.jsx(FEe,{children:a.jsx(gMt,{children:a.jsx(wY,{children:a.jsxs(St,{variant:"fit",children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(eMt,{}),a.jsx("div",{className:"relative grid h-full min-h-0",children:a.jsx(oIe,{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(iIe,{agentId:e})},m)})]})})})})},`session-${e}-${m}`)},`browser-${e}-${m}`)})})}const Ods=()=>a.jsxs(St,{variant:"fit",children:[a.jsx("h1",{className:"sr-only",children:"Agent session"}),a.jsx(eMt,{}),a.jsx("div",{className:"relative grid h-full overflow-y-auto pt-4","data-testid":"agent-session-skeleton","aria-busy":"true",children:a.jsx(j8t,{})})]}),jds={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"}},CI=e=>e?Object.keys(e).length:0,LX=e=>e>0?String(e):"Off",_8t=e=>(e?.inputProcessors?.length??0)+(e?.outputProcessors?.length??0),T8t=e=>!!e?.result,E8t=(e,t)=>!!(t&&e&&e.editor!==!1);function WP({view:e,label:t,status:n,description:r,docsHref:s,enabled:i,tone:o,icon:l}){const c=jds[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",$i,Fn,On),children:[a.jsx("span",{className:Z("mt-0.5 size-3.5 shrink-0 text-muted-foreground [&>svg]:size-3.5",On,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(Vs,{className:Z("mt-0.5 size-3 shrink-0 text-muted-foreground group-hover/capability-row:text-foreground",On)})]})}function bXe({agentId:e,view:t}){const{data:n,isLoading:r}=gk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),s=T8t(n),i=s?n?.memoryType==="gateway"?"Gateway":"On":"Off",o=r?"Checking":i;return a.jsx(WP,{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(DP,{})})}function wXe({agentId:e,view:t}){const{data:n,isLoading:r}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{isCmsAvailable:s,isLoading:i}=Ix(),o=E8t(n,s),l=n?.editor===!1,c=mL({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(WP,{view:t,label:"Editor",status:p,description:v,docsHref:"https://mastra.ai/docs/editor/overview",enabled:o,tone:"amber",icon:a.jsx(od,{})})}function SXe({agentId:e,view:t}){const{data:n,isLoading:r}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),s=CI(n?.tools);return a.jsx(WP,{view:t,label:"Tools",status:r?"Checking":LX(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(ad,{})})}function kXe({agentId:e,view:t}){const{data:n,isLoading:r}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),s=CI(n?.workflows);return a.jsx(WP,{view:t,label:"Workflows",status:r?"Checking":LX(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(GS,{})})}function OXe({agentId:e,view:t}){const{data:n,isLoading:r}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),s=CI(n?.agents);return a.jsx(WP,{view:t,label:"Sub-agents",status:r?"Checking":LX(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(rdt,{})})}function jXe({agentId:e,view:t}){const{data:n,isLoading:r}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),s=_8t(n);return a.jsx(WP,{view:t,label:"Processors",status:r?"Checking":LX(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(Ldt,{})})}function Cds({agentId:e}){const{data:t}=gk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:n}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{isCmsAvailable:r}=Ix(),s=[T8t(t),E8t(n,r),CI(n?.tools)>0,CI(n?.workflows)>0,CI(n?.agents)>0,_8t(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 _ds({agentId:e}){const[t,n]=g.useState(!1);return a.jsx(Wl,{open:t,onOpenChange:n,children:a.jsxs("div",{className:"shrink-0 border-t border-border",children:[a.jsx(wl,{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",yx,Fn,On),children:[a.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden",children:[a.jsx(bXe,{agentId:e,view:"chip"}),a.jsx(wXe,{agentId:e,view:"chip"}),a.jsx(SXe,{agentId:e,view:"chip"}),a.jsx(kXe,{agentId:e,view:"chip"}),a.jsx(OXe,{agentId:e,view:"chip"}),a.jsx(jXe,{agentId:e,view:"chip"})]}),a.jsx(Cds,{agentId:e}),a.jsx(Gs,{className:Z("size-3.5 shrink-0 text-muted-foreground transition-transform duration-normal ease-out-custom",t?"rotate-90":void 0)})]})}),a.jsx(Sl,{className:"px-2 pb-2",children:a.jsxs("div",{className:"grid gap-1",children:[a.jsx(bXe,{agentId:e,view:"row"}),a.jsx(wXe,{agentId:e,view:"row"}),a.jsx(SXe,{agentId:e,view:"row"}),a.jsx(kXe,{agentId:e,view:"row"}),a.jsx(OXe,{agentId:e,view:"row"}),a.jsx(jXe,{agentId:e,view:"row"})]})})]})})}function Tds(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 Eds(e){return typeof e=="object"&&e!==null&&"parts"in e&&Array.isArray(e.parts)}function Ids(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 Nds(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 Ads(e){const t=[];for(const n of e){const r=Tds(n.content);if(Eds(r))for(const s of r.parts)Ids(s)&&t.push(Nds(s,new Date(n.createdAt).toISOString()))}return t.sort((n,r)=>n.timestamp.localeCompare(r.timestamp)),t}function uA(e){return/[Zz+-]\d{0,4}$/.test(e.trim())?new Date(e).getTime():new Date(e.trim().replace(" ","T")+"Z").getTime()}function Pds(e){if(e.length===0)return{tMin:0,tMax:1};let t=1/0,n=-1/0;for(const r of e){const s=uA(r);s<t&&(t=s),s>n&&(n=s)}return t===n?{tMin:t,tMax:t+1}:{tMin:t,tMax:n}}function z6(e,t){return(uA(e)-t.tMin)/(t.tMax-t.tMin)}function aIe(e,t){return new Date(t.tMin+e*(t.tMax-t.tMin))}function $ds(e,t){return aIe(e,t).getTime()}function I8t(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function Rds(e){return uA(I8t(e))}function Mds(e,t){if(t==null)return null;const r=e.map(s=>({id:s.id,t:uA(I8t(s))})).toSorted((s,i)=>s.t-i.t).findLast(s=>s.t<=t);return r?r.id:null}function CXe(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function Dds(e){return[...e].sort((t,n)=>uA(CXe(t))-uA(CXe(n)))}function Lds({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=Dds(t).at(-1);return{messageTokens:s?.pendingTokens??i?.pendingMessageTokens,messageThreshold:s?.observationThreshold??n,memoryTokens:s?.observationTokens??i?.observationTokenCount,memoryThreshold:s?.reflectionThreshold??r}}function aD(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function zds(e,t,n){const r=e.map(i=>({ts:String(aD(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:z6(i.ts,n),pendingMessageTokens:i.pendingMessageTokens}))}function Fds(e,t,n){const r=[...e.map(i=>({ts:String(aD(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:z6(i.ts,n),observationTokenCount:s}))}function Bds(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:z6(s.ts,t),bufferedObservationTokenCount:r}))}function Vds(e,t){return[...e].sort((n,r)=>String(aD(n)).localeCompare(String(aD(r)))).map(n=>({t:z6(String(aD(n)),t),event:1}))}function Uds(e,t){return[...e].sort((n,r)=>new Date(n.createdAt).getTime()-new Date(r.createdAt).getTime()).map(n=>({t:z6(new Date(n.createdAt).toISOString(),t),event:1,role:n.role}))}function qds(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 Qds(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 Zds(e){return e==null?null:Number(e)}function Wds(e){return!!e?.event}const Hds="var(--chart-green)",Gds="var(--chart-amber)",_Xe="var(--chart-pink)";function Kds({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:is(aIe(n,e),"date-time-seconds",{timeZone:"UTC"})},n))})]})}function lIe({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?is(aIe(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:`${Jf} 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:`${Jf} rounded px-2 py-1`,children:i&&a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"ink",children:i})})}function Yds({label:e,data:t,dataKey:n,color:r,gradientId:s,domain:i,zoomDomain:o,threshold:l}){const c=Qds(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(CL,{width:"100%",height:32,children:a.jsxs(_Ir,{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(LL,{dataKey:"t",type:"number",domain:o,allowDataOverflow:!0,hide:!0}),a.jsx(zL,{type:"number",domain:c!=null?[0,c]:void 0,hide:!0}),a.jsx(jK,{content:a.jsx(lIe,{domain:i,showValue:!0}),cursor:{stroke:"var(--border)"}}),a.jsx(UOe,{type:"linear",dataKey:n,stroke:r,strokeWidth:1,fill:`url(#${s})`,isAnimationActive:!1}),l!=null&&a.jsx(POe,{y:l,stroke:"var(--border-strong)",strokeDasharray:"4 3"})]})})})]})}function Xds({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(CL,{width:"100%",height:r,children:a.jsxs(jIr,{margin:{top:0,right:0,bottom:0,left:0},children:[a.jsx(LL,{dataKey:"t",type:"number",domain:i,allowDataOverflow:!0,hide:!0}),a.jsx(zL,{dataKey:"event",type:"number",domain:[0,2],hide:!0}),a.jsx(jK,{content:a.jsx(lIe,{domain:s}),cursor:!1}),a.jsx(_Tt,{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 TXe({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=qds(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(CL,{width:"100%",height:u,children:a.jsxs(EIr,{margin:{top:0,right:0,bottom:0,left:0},onClick:h=>{const p=Zds(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(LL,{dataKey:"t",type:"number",domain:l,allowDataOverflow:!0,hide:!0}),a.jsx(zL,{yAxisId:"area",dataKey:n,type:"number",hide:!0,domain:[0,"dataMax"]}),a.jsx(jK,{content:a.jsx(lIe,{domain:o,showValue:!0}),cursor:!1}),a.jsx(UOe,{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=>Wds(h.payload)?a.jsx("circle",{cx:h.cx,cy:h.cy,r:4,fill:s}):a.jsx(a.Fragment,{})}),c!=null&&a.jsx(POe,{yAxisId:"area",y:c,stroke:"var(--border-strong)",strokeDasharray:"4 3"})]})})})]})}function Jds({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(de,{variant:"ghost",size:"icon-sm","aria-label":"Reset zoom",onClick:i,children:a.jsx(JC,{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 efs={tMin:0,tMax:1};function tfs({omRecords:e,markers:t,messages:n,tDomain:r,observationThreshold:s,reflectionThreshold:i,onSelectTimestamp:o,zoomRange:l,onZoomRangeChange:c}){const u=r??efs,d=g.useCallback(Q=>{o?.($ds(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(()=>Uds(n,u),[n,u]),I=g.useMemo(()=>zds(e,t,u),[e,t,u]),P=g.useMemo(()=>Fds(e,t,u),[e,t,u]),A=g.useMemo(()=>Bds(t,u),[t,u]),D=g.useMemo(()=>Vds(e,u),[e,u]);return N.length>0||I.length>0||P.length>0||D.length>0?a.jsxs("div",{className:"flex flex-col pr-2 pb-2 [&_.recharts-surface]:outline-none",children:[a.jsx(TXe,{label:"Messages",areaData:I,areaDataKey:"pendingMessageTokens",eventData:N,color:Hds,gradientId:"grad-messages",domain:u,zoomDomain:_,threshold:s,onSelectT:o?d:void 0}),a.jsx(TXe,{label:"Observations",areaData:P,areaDataKey:"observationTokenCount",eventData:D,color:Gds,gradientId:"grad-observations",domain:u,zoomDomain:_,threshold:i,onSelectT:o?d:void 0}),A.length>0&&a.jsx(Yds,{label:"Buffered obs",data:A,dataKey:"bufferedObservationTokenCount",color:_Xe,gradientId:"grad-buffered-obs",domain:u,zoomDomain:_,threshold:i}),D.length>0&&a.jsx(Xds,{label:"Events",data:D,color:_Xe,domain:u,zoomDomain:_}),a.jsx(Kds,{domain:u}),a.jsx(Jds,{tDomain:u,zoomLeft:y,zoomRight:x,onZoomLeftChange:b,onZoomRightChange:S,onReset:k})]}):null}const nfs=g.lazy(()=>Ii(async()=>{const{CodeDiff:e}=await import("./CodeDiff.es-CB_gYanJ.js");return{CodeDiff:e}},__vite__mapDeps([9,4,1,3]),import.meta.url).then(({CodeDiff:e})=>({default:e})));function rfs(e){if(!e)return null;const t=e.match(/^(\d{1,2}):(\d{2})$/);if(!t)return e;const[,n,r]=t;return is(new Date(2e3,0,1,Number(n),Number(r)),"time")??e}function sfs(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=Pge[e];return{card:n.card,text:"text-foreground",time:n.time}}function ifs(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(Age))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 ofs(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(`
|
|
671
671
|
`),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=ifs(u);if(p){if(h&&c){c.children.push(p);continue}l.items.push(p),c=p}}return o}function N8t({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=sfs(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:rfs(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(N8t,{items:n.children,nested:!0})})]})]})},`${n.text.slice(0,20)}-${r}`)})})}function afs({observations:e}){const t=g.useMemo(()=>ofs(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(N8t,{items:n.items})]},`${n.title}-${r}`))})}function lfs({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 cfs({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(tn,{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(ft,{orientation:"horizontal",className:"gap-1.5",children:[a.jsx(Iu,{checked:s,onCheckedChange:f=>i(f===!0)}),a.jsx(lt,{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(nfs,{codeA:typeof u.activeObservations=="string"?u.activeObservations:"",codeB:d,filename:"observations.md",layout:"unified",className:"rounded-xl"})}):d?a.jsx(afs,{observations:d}):a.jsx(Y,{variant:"caption",tone:"muted",className:"italic",children:l.isObserving||l.isReflecting?"Processing…":"Initialized"})})]}),a.jsx(lfs,{records:o,selectedRecordId:l.id,onSelectRecord:n})]})}function EXe(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 ufs={messages:"text-chart-blue",memory:"text-chart-purple",warning:"text-warning-foreground"};function IXe({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",ufs[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:[EXe(t),"/",EXe(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 dfs({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(IXe,{label:"Messages",value:e,max:t,tone:"messages"}):null,o?a.jsx(IXe,{label:s,value:n,max:r,tone:"memory"}):null]})})}function ffs({messages:e,omRecords:t,isLoading:n=!1,onClose:r,selectedTimestamp:s,onSelectTimestamp:i,contextWindow:o}){const[l,c]=g.useState(null),u=g.useMemo(()=>Ads(e),[e]),d=g.useMemo(()=>Pds(e.map(j=>new Date(j.createdAt).toISOString())),[e]),f=g.useMemo(()=>Lds({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=Rds(j);return C>=m.left&&C<=m.right}),[t,y,m.left,m.right]),b=g.useMemo(()=>s!=null?Mds(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(de,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"Back to memory",onClick:()=>r?.(),children:a.jsx(fd,{})}),a.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 text-foreground",children:[a.jsx(DP,{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(cfs,{records:x,selectedRecordId:k,onSelectRecord:c,isLoading:n})}),a.jsxs("div",{className:"border-t border-border",children:[a.jsx(dfs,{messageTokens:o?.messageTokens??f.messageTokens,messageThreshold:o?.messageThreshold??f.messageThreshold,memoryTokens:h,memoryThreshold:p,memoryLabel:"Observations"}),a.jsx(tfs,{omRecords:t,markers:u,messages:e,tDomain:d,onSelectTimestamp:i,zoomRange:m,onZoomRangeChange:v})]})]})]})}const hfs=2e3;function pfs({agentId:e,threadId:t}){const{isPanelOpen:n,closePanel:r,selectedTimestamp:s,setSelectedTimestamp:i}=OY(),{isObservingFromStream:o,isReflectingFromStream:l,observationsUpdatedAt:c,streamProgress:u}=kY(),d=o||l,{data:f}=NCe({threadId:t,agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!t&&t!=="new"&&!!e}}),h=f?.resourceId??e,{data:p}=vk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:m,isLoading:v,refetch:y}=YRt({agentId:n?e:void 0,threadId:n?t:void 0,resourceId:h}),{data:x,isLoading:b,refetch:S}=xZr({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()},hfs);return()=>clearInterval(T)},[n,d,y,S]),!n)return null;const k=p?.config?.observationalMemory,j=u?.threadId===t?u:null,C=zEe({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(ffs,{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 mfs(e){const{data:t}=vk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),n=t?.config;return{recentMessages:hFt(n?.lastMessages,n?.messageHistory),semanticRecallOn:!!n?.semanticRecall,workingMemoryOn:!!n?.workingMemory?.enabled,observationalOn:!!n?.observationalMemory?.enabled}}const NXe="agent-memory-sidebar-tab-v2",gfs=()=>{const[e,t]=g.useState(()=>{const r=sessionStorage.getItem(NXe)||"threads";return r==="threads"||r==="memory"?r:"threads"}),n=g.useCallback(r=>{t(r),sessionStorage.setItem(NXe,r)},[]);return{selectedTab:e,handleTabChange:n}},vfs=e=>e>=85?"bg-warning-indicator":e>=60?"bg-info-indicator":"bg-success-indicator";function H9({icon:e,tooltip:t,enabled:n,value:r}){return a.jsxs($n,{children:[a.jsx(In,{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(Nn,{children:t})]})}function yfs(){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 xfs({agentId:e,threadId:t,threads:n,onDelete:r,isThreadsLoading:s}){return a.jsx(rIe,{children:a.jsx(bfs,{agentId:e,threadId:t,threads:n,onDelete:r,isThreadsLoading:s})})}function bfs({agentId:e,threadId:t,threads:n,onDelete:r,threadsSlot:s,isThreadsLoading:i}){const{data:o,isLoading:l}=gk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),c=!!o?.result,u=o?.memoryType,{selectedTab:d,handleTabChange:f}=gfs(),{isPanelOpen:h}=OY(),{streamProgress:p}=kY(),{recentMessages:m,semanticRecallOn:v,workingMemoryOn:y,observationalOn:x}=mfs(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}=NCe({threadId:t,agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!t&&t!=="new"&&!!e}}),{data:I}=vk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:P}=YRt({agentId:x?e:void 0,threadId:x?t:void 0,resourceId:N?.resourceId??e}),A=I?.config?.observationalMemory,{messageTokens:D,messageThreshold:z}=zEe({record:P?.record,liveProgress:_,agentConfig:A}),q=(!!_||!!P?.record)&&z>0?Math.min(100,Math.round(D/z*100)):void 0;return g.useLayoutEffect(()=>{if(b||T||!c)return;const B=S.current,V=k.current;if(!B||!V)return;const H=()=>{const G=getComputedStyle(B),L=Number.parseFloat(G.borderTopWidth)||0,$=Number.parseFloat(G.borderBottomWidth)||0,F=Number.parseFloat(G.marginTop)||0,U=Number.parseFloat(G.marginBottom)||0,K=Math.ceil(V.getBoundingClientRect().height+L+$),ne=Math.ceil(K+F+U);C(X=>X.height===K&&X.offset===ne?X:{height:K,offset:ne})};if(H(),typeof ResizeObserver>"u")return;const M=new ResizeObserver(H);return M.observe(V),()=>M.disconnect()},[c,m.description,q,x,v,b,T,y]),l?a.jsx(yfs,{}):T?a.jsx("div",{"data-testid":"memory-sidebar-panel",className:"h-full min-h-0 min-w-0",children:a.jsx(pfs,{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(fFt,{resourceId:e,resourceType:"agent",threads:n??[],threadId:t,onDelete:r??(()=>{}),embedded:!0,isLoading:i},e):a.jsx(tn,{titleSlot:"Memory not enabled",descriptionSlot:"Conversations are only saved as threads when the agent has memory configured.",actionSlot:a.jsx(de,{icon:a.jsx(Vs,{}),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(hr,"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(DP,{className:"h-4 w-4 shrink-0"}),a.jsx(Y,{as:"span",variant:"column",children:"Memory"})]}),b?a.jsx(Fl,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):a.jsx(Mbe,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]}),b?null:a.jsx(pc,{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(H9,{icon:A3,tooltip:m.description,enabled:m.enabled,value:m.maxMessages}),a.jsx(H9,{icon:Hd,tooltip:v?"Semantic recall is on - retrieves relevant past messages":"Semantic recall is off",enabled:v}),a.jsx(H9,{icon:qCn,tooltip:y?"Working memory is on - persists notes across the conversation":"Working memory is off",enabled:y}),a.jsx(H9,{icon:rl,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",vfs(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(Uas,{agentId:e,threadId:t,memoryType:u})})]}):null]}),a.jsx(_ds,{agentId:e})]})}function wfs({agentId:e,threadId:t}){const n=wr("agent",e)[0],{mutateAsync:r}=bZr(n),{paths:s,navigate:i}=hn(),{data:o}=gk({agentId:e,requestContext:n,queryOptions:{enabled:!!e}}),l=!!o?.result,{data:c,isLoading:u}=ACe({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{Ge.error("Failed to delete chat");return}Ge.success("Chat deleted successfully"),h===t&&i(s.agentNewThreadLink(e))};return a.jsx(xfs,{agentId:e,threadId:t,threads:d,onDelete:f,isThreadsLoading:u})}const Sfs=()=>{const e=jY();return C0({"{":()=>e?.toggle()}),null},Td=e=>e.nullable().transform(t=>t??void 0).optional(),AXe=Dn({frequencyPenalty:Td(Ss()),presencePenalty:Td(Ss()),maxRetries:Td(Ss()),maxSteps:Td(Ss()),maxTokens:Td(Ss()),temperature:Td(Ss()),topK:Td(Ss()),topP:Td(Ss()),seed:Td(Ss()),providerOptions:Td(Oi(vt(),Oi(vt(),KPn()))),chatWithGenerateLegacy:Td(Ma()),chatWithGenerate:Td(Ma()),chatWithLegacyStream:Td(Ma()),chatWithNetwork:Td(Ma()),requireToolApproval:Td(Ma())}),kfs=Dn({provider:vt(),model:vt()}),A8t=Oi(vt(),ca());function Ofs(e){const t=A8t.safeParse(e);if(!t.success)return;const n={};for(const[r,s]of Object.entries(AXe.shape)){if(!Object.hasOwn(t.data,r))continue;const i=s.safeParse(t.data[r]);i.success&&(n[r]=i.data)}return AXe.parse(n)}const jfs=A8t.transform(e=>{const t=kfs.safeParse(e.selection);return{selection:t.success?t.data:void 0,modelSettings:Ofs(e.modelSettings)}});function Cfs(e){return JSON.stringify({...e,modelSettings:e.modelSettings&&Object.fromEntries(Object.entries(e.modelSettings).map(([t,n])=>[t,n===void 0?null:n]))})}function _fs(e){const t=`mastra-thread-preferences-${JSON.stringify([e.agentId,e.threadId])}`;return a.jsx(Tfs,{...e,storageKey:t},t)}function Tfs({children:e,defaultProvider:t,defaultModel:n,defaultSettings:r,storageKey:s}){const[i,o]=eP({initialKey:s,defaultValue:{},schema:jfs,serialize:Cfs}),{data:l,isError:c}=_0(),u=l?.modelPolicy,{models:d,isLoading:f,isError:h}=F0({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(I=>so(I.provider)===so(v?.provider??"")&&(!v?.model||I.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:{...vge.modelSettings,...r?.modelSettings,...i.modelSettings}};return a.jsx(UCe.Provider,{value:{provider:C,model:T,modelOverride:_,modelWarning:j,setProvider:I=>o(P=>({...P,selection:{provider:I,model:""}})),setModel:(I,P)=>o(A=>({...A,selection:{provider:I,model:P}}))},children:a.jsx($Ce.Provider,{value:{settings:N,setSettings:I=>o(P=>({...P,modelSettings:I.modelSettings})),resetAll:()=>o(I=>({...I,modelSettings:void 0}))},children:e})})}const Efs=6;function Ifs(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===Efs))break}return n}function Nfs(){const{agentId:e,threadId:t}=fr(),n=Ye(),{data:r,error:s}=Ul(),i=r&&mp(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]=pi(),{data:f,isLoading:h,error:p}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:m,isLoading:v}=gk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),y=Lr(),x=jY(),b=g.useRef(null),S=t==="new",k=g.useMemo(()=>wa(),[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:I}=ACe({agentId:e,isMemoryEnabled:T,resourceId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!T}}),P=d.get("messageId")??void 0,A=Ifs(f?.metadata),D=g.useMemo(()=>sIe(f),[f]);if(p&&_s(p))return a.jsx(ci,{variant:"fill"});if(p&&Ts(p))return a.jsx(Js,{variant:"fill",resource:"agents"});if(!r&&s)return a.jsx(tn,{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(Xge,{agentId:e,leftSlot:S&&!v&&!T?void 0:a.jsx(Pfs,{agentId:e}),leftDrawerLabel:"Threads",children:S?a.jsx(Yus,{}):a.jsx($fs,{})});if(p&&ok(p))return a.jsx(EZ,{});if(p)return a.jsx(tn,{tone:"error",titleSlot:"Failed to load agent",descriptionSlot:p.message});if(!f)return a.jsx(EZ,{});const z=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 I()};return a.jsx(_fs,{agentId:e,threadId:z,defaultProvider:so(f.provider??""),defaultModel:f.modelId??"",defaultSettings:D,children:a.jsx(hMt,{agentId:e,threadId:z,resourceId:e,children:a.jsx(vY,{children:a.jsx(yY,{agentId:e,threadId:z,enabled:!!(f?.hasBrowser??f?.browserTools?.length),children:a.jsx(FEe,{ref:b,persistence:l?{key:u,threadId:z}:void 0,children:a.jsx(gMt,{children:a.jsx(QZr,{children:a.jsxs(wY,{children:[a.jsx(Sfs,{}),a.jsx(Xge,{agentId:e,leftSlot:Q?void 0:a.jsx(wfs,{agentId:e,threadId:z}),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(oIe,{agentId:e,agentName:f?.name,modelVersion:f?.modelVersion,supportsMemory:f?.supportsMemory,threadId:z,memory:T,refreshThreadList:q,modelList:f?.modelList,messageId:P,suggestedPrompts:A,isNewThread:S,runOptionsSlot:a.jsx(iIe,{agentId:e})})})},z)})]},`${e}-${z}`)},`memory-timeline-${e}-${z}`)})},`${l}:${JSON.stringify([...c,z])}`)},`session-${e}-${z}`)},`browser-${e}-${z}`)})})}function Afs(){const{agentId:e}=fr();return a.jsx(HZr,{children:a.jsx(Nfs,{})},e)}const Pfs=({agentId:e})=>a.jsx(rIe,{children:a.jsx(fFt,{threads:[],threadId:"",onDelete:()=>{},resourceId:e,resourceType:"agent",embedded:!0,isLoading:!0})}),$fs=()=>a.jsx("div",{className:"relative grid h-full overflow-y-auto pt-4","data-testid":"agent-thread-skeleton","aria-busy":"true",children:a.jsx(j8t,{})}),P8t=()=>{const{data:e}=nP();return e?.editorSource==="code"?"code":"db"},F6=()=>{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 Rfs(){const{agentId:e}=fr(),[t,n]=g.useState(null),{data:r,isLoading:s,error:i}=md({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:o}=gk({agentId:e,requestContext:wr("agent",e)[0],queryOptions:{enabled:!!e}}),l=P8t(),{isMastraPlatform:c,mastraPlatformApiEndpoint:u,mastraPlatformProjectId:d}=F6(),{data:f,isLoading:h}=mL({agentId:e,params:{orderBy:{direction:"DESC"}},queryOptions:{enabled:!!e}}),p=(f?.versions?.length??0)>0,{data:m,isLoading:v}=jG({agentId:e,status:"draft",queryOptions:{enabled:!!e&&p}}),y=r?.source==="code",x=y&&l==="code",b=!P_(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:_}=O1t({agentId:e??"",versionId:t??"",queryOptions:{enabled:!!e&&!!t}}),N=m?.activeVersionId,I=f?.versions?.[0],P=!!(I&&I.id!==N),A=!!t&&!!_,D=A&&t!==I?.id,z=g.useMemo(()=>A&&_?_:m||(r?b8t(r):{}),[A,_,m,r]),{form:Q,handlePublish:q,handleSaveDraft:B,handleDownloadJson:V,handleOpenPr:H,isSubmitting:M,isSavingDraft:G,isDirty:L}=nIe({mode:"edit",agentId:e??"",dataSource:z,isCodeAgentOverride:y,hasStoredOverride:y&&!!m,editorConfig:r?.editor,saveSuccessMessage:x?"Saved to filesystem":void 0,onSuccess:()=>{}}),$=g.useCallback(async()=>{D&&t?await q(t):await q()},[q,D,t]),F=g.useCallback(async()=>{!u||!d||await H({platformApiEndpoint:u,projectId:d})},[H,u,d]),U=g.useCallback(K=>{K===I?.id?n(null):n(K)},[I?.id]);return i&&_s(i)?a.jsx(ci,{variant:"fill"}):i&&Ts(i)?a.jsx(Js,{variant:"fill",resource:"agents"}):C?a.jsx(An,{fill:!0}):i&&ok(i)?a.jsx("div",{className:"py-4 text-center",children:"Agent not found"}):i?a.jsx(tn,{tone:"error",titleSlot:"Failed to load agent",descriptionSlot:i.message}):r?a.jsx(yMt,{form:Q,mode:"edit",agentId:e,isSubmitting:M,isSavingDraft:G,handlePublish:q,handleSaveDraft:B,isCodeAgentOverride:y,isCodeSourceAgent:x,readOnly:D||!b,editorConfig:r?.editor,children:a.jsx(Gus,{agentId:e,agentName:r?.name,modelVersion:r?.modelVersion,agentVersionId:t??I?.id,hasMemory:T,activeVersionId:N,selectedVersionId:t??void 0,latestVersionId:I?.id,onVersionSelect:U,isDirty:L,isSavingDraft:G,isPublishing:M,hasDraft:P,readOnly:D||!b,isCodeSourceAgent:x,showCodeModeActions:S,canOpenPr:k,openPrTitle:j,onSaveDraft:B,onPublish:$,onDownloadJson:V,onOpenPr:F,isViewingPreviousVersion:D})}):a.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}const cIe={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 zX(e){const t=e.attributes?.processorPhase;return typeof t=="string"&&Object.hasOwn(cIe,t)?t:void 0}function $8t(e,t){const n=zX(e);if(!(!n||Object.keys(t).length===0))return{phase:n,phaseLabel:cIe[n],data:t}}function Mfs(e,t){return $8t(e,t)}function Dfs(e,t){return $8t(e,t)}const Lfs=["processorPhase","processorExecutor","processorIndex","hookDurationMs","messageListMutations","tripwireAbort"];function R8t(e){const t=zX(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(Lfs);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:cIe[t],executor:n.processorExecutor,processorIndex:n.processorIndex,hookDurationMs:n.hookDurationMs,messageListMutations:r,tripwireAbort:s,...Object.keys(o).length>0?{rest:o}:{}}}const rj=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zle=e=>e.status==="suspended"||e.status==="aborted"||e.status==="interrupted",zfs=["agent_run","model_step","model_inference"];function M8t(e){const t=e.input;if(t==null)return;if(e.spanType==="agent_run"&&e.metadata?.resumed===!0)return{type:"agent-run-resume",value:rj(t)?t:{resumeData:t}};if(zX(e)){const r=rj(t)?Mfs(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 zfs.includes(e.spanType)?{type:"messages",value:t}:{type:"json",value:t};if(!rj(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(rj(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 D8t(e){const t=e.output;if(t!=null){if(zX(e)){const n=rj(t)?Dfs(e,t):void 0;return n?{type:"processor",value:n}:{type:"json",value:t}}if(typeof t=="string")return{type:"text",value:t};if(!rj(t))return{type:"json",value:t};switch(e.spanType){case"agent_run":return zle(t)?{type:"interrupted",value:t}:{type:"agent-run-result",value:t};case"model_generation":return zle(t)?{type:"interrupted",value:t}:{type:"model-generation-result",value:t};case"model_step":return zle(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 Ffs=e=>rj(e)&&typeof e.message=="string";function Bfs(e){return Ffs(e.error)?e.error:void 0}const uve=(e,t)=>e==="number"?Number(t):e==="boolean"?t.toLowerCase()==="true":t,cl=e=>"kind"in e&&e.kind==="group",PXe=/mac|iphone|ipad|ipod/i;function Vfs(){if(typeof navigator>"u")return!1;const e=navigator,t=e.userAgentData?.platform||e.platform||"",n=e.userAgent||"";return PXe.test(t)||PXe.test(n)}function uIe(){const[e]=g.useState(Vfs);return e}function Ufs(e){const t=uIe();return g.useMemo(()=>{const n=e.trim().toUpperCase();return`${t?"⌘":"Ctrl"} ${n}`},[t,e])}const dIe="root",qfs=e=>Array.isArray(e)?{logic:"and",nodes:e}:e,Qfs=(e,t)=>t?e.nodes.filter(n=>!cl(n)):e,Fle=e=>{const t=[],n=(r,s)=>{for(const i of r)cl(i)?n(i.nodes,i.id):t.push(s?{item:i,groupId:s}:{item:i})};return n(e.nodes,void 0),t},L8t=(e,t)=>{for(const n of e){if(!cl(n))continue;if(n.id===t)return n;const r=L8t(n.nodes,t);if(r)return r}},z8t=(e,t)=>L8t(e.nodes,t),Zfs=(e,t)=>{const n=(r,s)=>{for(const i of r){if(!cl(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)},fIe=e=>e.nodes.reduce((t,n)=>t+(cl(n)?fIe(n):1),0),F8t=e=>[e.id,...e.nodes.flatMap(t=>cl(t)?F8t(t):[t.id])],FX=(e,t,n)=>e.map(r=>cl(r)?r.id===t?n(r):{...r,nodes:FX(r.nodes,t,n)}:r),B8t=(e,t)=>e.map(n=>cl(n)?{...n,nodes:B8t(n.nodes,t)}:t(n)),hIe=(e,t)=>e.filter(t).map(n=>cl(n)?{...n,nodes:hIe(n.nodes,t)}:n),Wfs=(e,t,n)=>({...e,nodes:B8t(e.nodes,r=>r.id===t?{...r,...n}:r)}),$Xe=(e,t)=>({...e,nodes:hIe(e.nodes,n=>n.id!==t)}),V8t=e=>e.flatMap(t=>{if(!cl(t))return[t];const n=V8t(t.nodes);return n.length===0?[]:[{...t,nodes:n}]}),U8t=e=>({...e,nodes:V8t(e.nodes)}),RXe=(e,t,n)=>!t||t===dIe?{...e,nodes:[...e.nodes,n]}:{...e,nodes:FX(e.nodes,t,r=>({...r,nodes:[...r.nodes,n]}))},Hfs=(e,t,n)=>t===dIe?{...e,logic:n}:{...e,nodes:FX(e.nodes,t,r=>({...r,logic:n}))},Gfs=(e,t,n)=>!t||t===dIe?{...e,nodes:[...e.nodes,n]}:{...e,nodes:FX(e.nodes,t,r=>({...r,nodes:[...r.nodes,n]}))},Kfs=(e,t)=>U8t({...e,nodes:hIe(e.nodes,n=>cl(n)||t.has(n.id))}),dve=["field","operator","value","remove"],Yfs=[...dve].reverse(),Xfs=3,pIe="data-filter-bar-scope",Ble=e=>e?.closest(`[${pIe}]`)??null,MXe=e=>e?e.operatorId?"operator":"field":"none",q8t=g.createContext(null);function Qc(){const e=g.useContext(q8t);if(!e)throw new Error("FilterBar compound components must be rendered inside <FilterBar>.");return e}let DXe=0;function LXe(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(DXe+=1,`filter-${DXe}`)}function Q8t(e){return e?.arity==="many"?[]:""}const TO=(e,t=new Set)=>{for(const n of e)t.add(n.id),cl(n)&&TO(n.nodes,t);return t},Z8t=(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(cl(l)&&cl(o)?{...l,nodes:Z8t(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 Jfs({fields:e,operators:t,value:n,onValueChange:r,createItemId:s,maxDepth:i=Xfs,ariaLabel:o,children:l}){const c=g.useRef(new Map),u=g.useRef(null),d=Array.isArray(n),f=g.useMemo(()=>qfs(n),[n]),h=g.useRef(f);h.current=f;const[p,m]=g.useState(""),[v,y]=g.useState(()=>new Set),[x,b]=g.useState(void 0),[S,k]=g.useState(null),j=g.useCallback(_e=>r(Qfs(_e,d)),[r,d]),C=g.useCallback(_e=>e.find(ce=>ce.id===_e),[e]),T=g.useCallback(_e=>t.find(ce=>ce.id===_e),[t]),_=g.useCallback(_e=>{if(!_e.operators)return t;const ce=new Set(_e.operators);return t.filter(ye=>ce.has(ye.id))},[t]),N=g.useCallback(_e=>m(_e),[]),[I,P]=g.useState(null),A=g.useRef(I);A.current=I;const[D,z]=g.useState(null),Q=g.useCallback(()=>z(_e=>_e?{..._e,glint:!1}:null),[]),[q,B]=g.useState(()=>new Set),V=g.useCallback(_e=>{B(ce=>{if(!ce.has(_e))return ce;const ye=new Set(ce);return ye.delete(_e),ye})},[]),H=g.useCallback(_e=>{const ce=[..._e];ce.length!==0&&B(ye=>new Set([...ye,...ce]))},[]),M=g.useRef(f.nodes),{rendered:G,items:L,leaving:$,rootGroupOf:F}=g.useMemo(()=>{const _e=TO(f.nodes);let ce=q.size===0?f:{...f,nodes:Z8t(M.current,f.nodes,q)};D&&!_e.has(D.item.id)&&(ce=RXe(ce,D.groupId,D.item)),M.current=ce.nodes;const ye=TO(ce.nodes),Me=new Set([...q].filter(le=>ye.has(le)&&!_e.has(le))),Ie=new Map;for(const le of ce.nodes)if(cl(le))for(const{item:xe}of Fle({nodes:[le]}))Ie.set(xe.id,le.id);return{rendered:ce,items:Fle(ce).map(le=>le.item),leaving:Me,rootGroupOf:Ie}},[f,D,q]),U=g.useCallback(_e=>s&&x===void 0?s(_e):LXe(),[s,x]),K=g.useCallback(_e=>{z(null),P(ce=>_e?{..._e,id:ce?.fieldId===_e.fieldId?ce.id:U(_e.fieldId),from:MXe(ce),groupId:x}:null)},[U,x]),ne=g.useCallback(({fieldId:_e,operatorId:ce},ye)=>{const Me=A.current?.id??U(_e),Ie=A.current?.groupId??x,le={id:Me,fieldId:_e,operatorId:ce,value:ye};j(RXe(h.current,Ie,le)),z({item:le,from:MXe(A.current),glint:!0,groupId:Ie}),P(null),N("Filter added")},[j,N,U,x]),X=g.useCallback((_e,ce)=>{j(Wfs(h.current,_e,ce))},[j]),te=g.useCallback(_e=>{H([_e]),j($Xe(h.current,_e)),z(null),N("Filter removed")},[j,N,H]),oe=g.useCallback(_e=>{b(ce=>ce&&_e.has(ce)?void 0:ce)},[]),ue=g.useCallback(_e=>{const ce=h.current,ye=z8t(ce,_e),Me=new Set(ye?F8t(ye):[_e]);H(Me),j($Xe(ce,_e)),z(null),P(null),oe(Me),k(Ie=>Ie===_e?null:Ie),N("Advanced filter removed")},[j,N,H,oe]),ee=g.useCallback((_e,ce)=>{const ye={id:LXe(),kind:"group",logic:ce,nodes:[]};return j(Gfs(h.current,_e,ye)),z(null),P(null),b(ye.id),N(_e?"Nested group added":"Advanced filter added"),ye.id},[j,N]),se=g.useCallback((_e,ce)=>{j(Hfs(h.current,_e,ce)),N(`Conditions joined with ${ce}`)},[j,N]),re=g.useCallback(_e=>Zfs(h.current,_e),[]),ae=g.useCallback(_e=>{if(k(_e),_e!==null)return;const ce=h.current,ye=U8t(ce),Me=TO(ye.nodes),Ie=new Set([...TO(ce.nodes)].filter(le=>!Me.has(le)));Ie.size>0&&(H(Ie),j(ye)),P(null),b(void 0)},[j,H]),pe=g.useCallback(()=>{u.current?.focus()},[]),ve=g.useCallback(_e=>{b(_e),P(null),_e===void 0&&pe()},[pe]),he=g.useCallback(()=>{const _e=h.current,ce=Kfs(_e,v),ye=TO(ce.nodes),Me=new Set([...TO(_e.nodes)].filter(Ie=>!ye.has(Ie)));H(Me),j(ce),z(null),P(null),b(void 0),k(null),N("All filters removed")},[j,N,v,H]),Oe=Fle(f).some(({item:_e})=>!v.has(_e.id)),Ee=g.useCallback((_e,ce)=>{y(ye=>{if(ye.has(_e)===ce)return ye;const Me=new Set(ye);return ce?Me.add(_e):Me.delete(_e),Me})},[]),Fe=g.useCallback((_e,ce,ye)=>{const Me=`${_e}:${ce}`;ye?c.current.set(Me,ye):c.current.delete(Me)},[]),qe=g.useCallback(_e=>{_e?u.current=_e:u.current?.isConnected||(u.current=null)},[]),Be=g.useRef(L);Be.current=L;const Pe=g.useRef(F);Pe.current=F;const Ve=g.useCallback((_e,ce,ye)=>{const Me=Be.current,Ie=Pe.current,le=Me[_e-ce],xe=le?[...dve].map(ze=>c.current.get(`${le.id}:${ze}`)).find(Boolean):null,Se=Ble(typeof document>"u"?null:document.activeElement)??Ble(xe)??void 0,$e=ce===-1?Yfs:dve;for(let ze=_e;ze>=0&&ze<Me.length;ze+=ce){const He=Me[ze];if(!He)break;const De=[He.id,Ie.get(He.id)].filter(tt=>tt!==void 0);for(const tt of De)for(const Ze of[ye,...$e]){const rt=c.current.get(`${tt}:${Ze}`);if(rt&&(Se===void 0||Ble(rt)===Se))return rt.focus(),!0}}return!1},[]),Ce=g.useCallback(_e=>{Ve(_e+1,1,"value")||Ve(_e-1,-1,"value")||pe()},[Ve,pe]),Te=g.useMemo(()=>({fields:e,operators:t,items:L,expression:G,groupsEnabled:!d,maxDepth:i,draft:I,setDraft:K,commitDraft:ne,lastCommit:D,settleCommit:Q,updateItem:X,removeItem:te,leaving:$,settleRemove:V,clear:he,hasRemovableItems:Oe,registerNonRemovable:Ee,addGroup:ee,removeGroup:ue,setLogic:se,getGroupDepth:re,openGroupId:S,setOpenGroup:ae,inputTarget:x,openGroupInput:ve,getField:C,getOperator:T,getFieldOperators:_,registerSegment:Fe,registerInput:qe,focusChip:Ve,focusInput:pe,focusAfterRemove:Ce,announce:N,announcement:p,ariaLabel:o}),[e,t,L,G,d,i,I,K,ne,D,Q,X,te,$,V,he,Oe,Ee,ee,ue,se,re,S,ae,x,ve,C,T,_,Fe,qe,Ve,pe,Ce,N,p,o]);return a.jsx(q8t.Provider,{value:Te,children:l})}function W8t({option:e}){return a.jsxs(a.Fragment,{children:[e.start,a.jsx("span",{className:"min-w-0 truncate",children:e.label??e.value})]})}const H8t=g.forwardRef((e,t)=>a.jsx(g1t,{ref:Eu(t),...e}));H8t.displayName="FilterBarOptionItem";function _I({getKey:e,renderOption:t,isSelected:n,isLoading:r,error:s,emptyText:i="No results.","aria-label":o,"aria-multiselectable":l}){const c=!r&&s===void 0,u=_v();return a.jsxs(a.Fragment,{children:[r&&a.jsxs(_7e,{className:as.empty,children:[a.jsx(An,{size:"sm"}),a.jsx("span",{children:"Loading…"})]}),!r&&s!==void 0&&a.jsx(_7e,{className:as.empty,children:"Couldn't load values."}),a.jsx(y1t,{className:as.empty,children:c?i:null}),a.jsx("div",{className:Z(as.listScroller,"max-h-[min(var(--spacing-dropdown),60dvh)]",u.containerClassName),...u.getContainerProps({}),children:a.jsx(Dm,{menu:u,children:a.jsx(u1t,{"aria-label":o,"aria-multiselectable":l,className:as.list,children:d=>{const f=n?.(d)??!1;return a.jsxs(H8t,{value:d,"data-selected":f||void 0,className:Z(as.item,"min-w-0"),children:[a.jsx("span",{className:"flex min-w-0 flex-1 items-center gap-1.5 truncate",children:t(d)}),a.jsx("span",{className:as.itemRightSlot,children:a.jsx("span",{className:as.checkContainer,children:n?f&&a.jsx(pr,{className:as.checkIcon}):a.jsx(v1t,{children:a.jsx(pr,{className:as.checkIcon})})})})]},e(d))}})})})]})}function G8t(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 mIe(e,t,n){return G8t(n?n(e):String(e),t)}const ehs=150,ths=[{value:"true",label:"True"},{value:"false",label:"False"}],K8t=e=>e?.suggestions??(e?.type==="boolean"?ths:void 0);function nhs({field:e,operatorId:t,query:n,enabled:r}){const s=K8t(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))})},ehs);return()=>{clearTimeout(S),b.abort()}},[v,r,n,t]),{options:g.useMemo(()=>o?o.filter(x=>G8t(x.label??x.value,n)):l,[o,l,n]),isLoading:!!i&&u,error:f,hasSuggestions:!!s}}const zXe=e=>Array.isArray(e)?e.map(String):[];function Y8t({field:e,operator:t,query:n,enabled:r,initialValue:s,onCommit:i}){const o=t?.arity==="many",[l,c]=g.useState(()=>zXe(s)),u=g.useRef(s);u.current=s,g.useEffect(()=>{c(r?zXe(u.current):[])},[r]);const d=nhs({field:e,operatorId:t?.id??"",query:n,enabled:r}),f=e?.type,h=!e?.strict&&f!=="boolean",p=g.useCallback(k=>{c(j=>j.includes(k)?j.filter(C=>C!==k):[...j,k])},[]),m=g.useCallback(k=>i(Array.isArray(k)?k.map(j=>uve(f,j)):uve(f,k)),[i,f]),v=g.useCallback(k=>{o?p(k.value):m(k.value)},[o,p,m]),y=g.useCallback(()=>l.length===0?!1:(m(l),!0),[l,m]),x=g.useCallback(k=>h&&k.length>0&&(f!=="number"||Number.isFinite(Number(k))),[h,f]),b=g.useCallback(()=>{const k=n.trim();return x(k)?(m(o?l.includes(k)?l:[...l,k]:k),!0):!1},[x,n,o,l,m]),S=g.useCallback((k,j)=>k.key!=="Enter"?!1:o&&(k.ctrlKey||k.metaKey)?(k.preventDefault(),y()||b()):j===null?(k.preventDefault(),b()):!1,[o,y,b]);return{isMany:o,selected:l,toggle:p,options:d.options,isLoading:d.isLoading,error:d.error,hasSuggestions:d.hasSuggestions,allowFreeText:h,canCommitQuery:x(n.trim()),handleSelect:v,handleKeyDown:S,commitSelection:y,commitFreeText:b}}const BX=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"),X8t="sm",J8t={autoHighlight:"always",keepHighlight:!0},e9t=Z("filter-bar-chip relative flex max-w-full items-stretch divide-x divide-border overflow-hidden rounded-full",JW,Hh[X8t]),TI=Z(BX,"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 VX({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 fve=e=>e?.color?{color:e.color}:void 0,rhs=(e,t)=>e==="none"?0:e==="field"||t?1:2,IZ=(e,t)=>{const n=K8t(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)},shs=(e,t)=>!Array.isArray(e)||e.length<2?IZ(e,t):`${IZ(e.slice(0,1),t)} +${e.length-1}`,t9t=g.createContext(null),bk=()=>{const e=g.useContext(t9t);if(!e)throw new Error("FilterBarChip segments must be rendered inside <FilterBarChip>.");return e};function ihs(e){return e instanceof Element&&!!e.closest('[data-slot="filter-bar-editor"]')}function dx({item:e,readOnly:t=!1,removable:n=!0,draft:r=!1,className:s,children:i}){const o=Qc(),[l,c]=g.useState(null),u=o.getField(e.fieldId),d=o.getOperator(e.operatorId),f=o.items.findIndex(I=>I.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 I=h.current;if(!p||!I)return;const P=typeof I.getAnimations=="function"?I.getAnimations({subtree:!0}):[];if(P.length===0){y(e.id);return}let A=!1;return Promise.all(P.map(D=>D.finished)).then(()=>{A||y(e.id)}).catch(()=>{}),()=>{A=!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?"":IZ(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=rhs(k,x),C=S?.glint??!1,T=g.useCallback(I=>{if(t||r||p||ihs(I.target))return;const P=Array.from(h.current?.querySelectorAll("[data-filter-bar-segment]")??[]),A=P.findIndex(D=>D===I.target);switch(I.key){case"ArrowRight":{I.preventDefault();const D=P[A+1];D?D.focus():o.focusChip(f+1,1,"field")||o.focusInput();return}case"ArrowLeft":{I.preventDefault();const D=P[A-1];D?D.focus():o.focusChip(f-1,-1,"remove");return}case"Delete":case"Backspace":if(!n)return;I.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(i9t,{}),a.jsx(o9t,{}),a.jsx(a9t,{}),n&&a.jsx(l9t,{})]});return a.jsx(t9t.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(e9t,p&&"pointer-events-none",s),style:{"--filter-bar-segments-settled":j,"--filter-bar-chip-shine":u?.color??"currentColor"},onKeyDown:T,onClick:I=>I.stopPropagation(),onAnimationEnd:I=>{I.animationName==="filter-bar-chip-shine"&&o.settleCommit()},children:[t&&a.jsx("span",{className:Z(BX,"pr-0 text-muted-foreground [--filter-bar-segment-padding:0.5rem_0]"),title:"This filter is locked",children:a.jsx(Su,{className:"size-[1.1em]"})}),N]})})}const n9t=g.createContext({highlighted:null});function gIe({placeholder:e,icon:t=Hd,inputMode:n,onKeyDown:r}){const{highlighted:s}=g.useContext(n9t);return a.jsxs("div",{className:as.searchContainer,children:[a.jsx(t,{className:as.searchIcon}),a.jsx(oSe,{className:as.searchInput,placeholder:e,inputMode:n,onKeyDown:i=>r?.(i,s)})]})}function vIe({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=Qc(),m=bk(),v=A0(),y=m.openSegment===e,[x,b]=g.useState(null),S=e==="field",k=S?a.jsx(VX,{field:m.field,label:t}):a.jsx("span",{className:"truncate",children:t});return m.readOnly||m.draft||m.leaving?a.jsx("span",{className:Z(BX,S&&"text-foreground"),style:S?fve(m.field):void 0,title:n,children:k}):a.jsxs(Tq,{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)},...J8t,modal:!1,children:[a.jsx(c1t,{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(TI,S&&"text-foreground"),style:S?fve(m.field):void 0}),children:k}),a.jsx(aSe,{container:v,children:a.jsx(lSe,{align:"start",sideOffset:o_,positionMethod:vv,className:as.positioner,children:a.jsx(cSe,{className:Z(as.popup,"min-w-44"),"data-slot":"filter-bar-editor",children:a.jsx(n9t.Provider,{value:{highlighted:x},children:h})})})})]})}const ohs=e=>e.label,ahs=e=>e.label,lhs=e=>e.label??e.value;function chs(){const e=Qc(),t=bk(),[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?Q8t(l):t.item.value}),t.setOpenSegment(null)},[e,t]);return a.jsxs(vIe,{segment:"field",ariaLabel:"Field",label:t.field?.label??t.item.fieldId,items:e.fields,itemToString:ohs,filter:mIe,value:t.field,query:n,onQueryChange:r,onSelect:s,children:[a.jsx(gIe,{placeholder:"Change field…"}),a.jsx(_I,{"aria-label":"Fields",getKey:i=>i.id,renderOption:i=>a.jsx(VX,{field:i}),emptyText:"No matching field."})]})}function uhs(){const e=Qc(),t=bk(),[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?Q8t(o):t.item.value}),t.setOpenSegment(null)},[e,t]);return a.jsxs(vIe,{segment:"operator",ariaLabel:"Operator",label:t.operator?.label??t.item.operatorId,items:s,itemToString:ahs,filter:mIe,value:t.operator,query:n,onQueryChange:r,onSelect:i,children:[a.jsx(gIe,{placeholder:"Change operator…"}),a.jsx(_I,{"aria-label":"Operators",getKey:o=>o.id,renderOption:o=>o.label,emptyText:"No matching operator."})]})}function dhs(){const e=Qc(),t=bk(),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=Y8t({field:t.field,operator:t.operator,query:r,enabled:n,initialValue:t.item.value,onCommit:o}),c=ghs[t.field?.type??"text"];return a.jsx(vIe,{segment:"value",ariaLabel:"Value",label:shs(t.item.value,t.field)||"…",fullLabel:IZ(t.item.value,t.field)||"…",items:l.options,itemToString:lhs,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 r9t({step:e,onCancel:t}){const n=bk(),r=uIe()?"⌘↵":"Ctrl ↵";return a.jsxs(a.Fragment,{children:[e.hasSuggestions&&a.jsx(_I,{"aria-label":"Values","aria-multiselectable":e.isMany||void 0,getKey:s=>s.value,renderOption:s=>a.jsx(W8t,{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(de,{size:"sm",variant:"ghost",onClick:t,children:"Cancel"}),a.jsxs(de,{size:"sm",variant:"default",onClick:()=>e.commitSelection()||e.commitFreeText(),children:["Done",a.jsx(Ud,{size:"xs",children:r})]})]})]})}function fhs(e,t){return e.hasSuggestions?e.allowFreeText?`Search or type a ${t}…`:`Search ${t}s…`:`Type a ${t}…`}function s9t({step:e,onCancel:t,inputMode:n,noun:r}){return a.jsxs(a.Fragment,{children:[a.jsx(gIe,{icon:e.hasSuggestions?Hd:od,inputMode:n,placeholder:fhs(e,r),onKeyDown:(s,i)=>{const o=e.hasSuggestions?i:null;(e.handleKeyDown(s,o)||s.key==="Enter"&&o===null)&&s.preventBaseUIHandler()}}),a.jsx(r9t,{step:e,onCancel:t})]})}function hhs(e){return a.jsx(s9t,{...e,noun:"value"})}function phs(e){return a.jsx(s9t,{...e,inputMode:"decimal",noun:"number"})}function mhs(e){return a.jsx(r9t,{...e})}const ghs={text:hhs,number:phs,boolean:mhs};function i9t(){return a.jsx(chs,{})}function o9t(){const e=bk();return e.operatorImplied||e.draft&&!e.operator?null:a.jsx(uhs,{})}function a9t(){const e=bk();return e.draft||(e.operator?.arity??"one")==="none"?null:a.jsx(dhs,{})}function l9t(){const e=Qc(),t=bk();if(t.readOnly||t.draft)return null;const n=Z(TI,"px-1.5 text-muted-foreground [--filter-bar-segment-padding:0.375rem]");if(t.leaving)return a.jsx("span",{className:n,children:a.jsx(Ln,{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(Ln,{className:"size-[1.1em]"})})}dx.Field=i9t;dx.Operator=o9t;dx.Value=a9t;dx.Remove=l9t;const vhs=e=>"label"in e&&e.label?e.label:"value"in e?e.value:"",yhs=[],c9t="__filter-bar-advanced__",xhs={id:c9t,label:"Advanced filter…",icon:al,operators:[]};function u9t(e){return Qc().inputTarget!==e.groupId?null:a.jsx(bhs,{...e})}function bhs({placeholder:e="Filter…",className:t,"aria-label":n="Add filter",groupId:r,onLeave:s}){const i=Qc(),o=A0(),l=g.useRef(null),[c,u]=g.useState(!1),[d,f]=g.useState(""),[h,p]=g.useState(null),[m,v]=g.useState(!1),y=uIe()?"⌘↵":"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(te=>!te.hidden);return _?[...X,xhs]:X},[i.fields,_]),I=r?z8t(i.expression,r):void 0;g.useEffect(()=>{r&&l.current?.focus()},[r]);const P=g.useCallback(X=>{bo.flushSync(()=>v(!0)),X(),v(!1)},[]),A=g.useCallback(X=>P(()=>b(X)),[P,b]),D=g.useCallback(()=>{b(null),f("")},[b]),z=g.useCallback(()=>{u(!1),D()},[D]),Q=g.useCallback((X,te,oe)=>{P(()=>S({fieldId:X,operatorId:te},oe)),f(""),l.current?.focus()},[P,S]),q=g.useCallback((X,te)=>{if(te.arity==="none"){Q(X,te.id,"");return}A({fieldId:X,operatorId:te.id}),f("")},[Q,A]),B=g.useCallback(X=>{if(X.id===c9t){const ue=i.addGroup(void 0,"or");i.setOpenGroup(ue),i.openGroupInput(ue),f(""),u(!1);return}const[te,...oe]=i.getFieldOperators(X);if(X.search&&te&&d.trim()!==""){Q(X.id,te.id,uve(X.type,d));return}if(te&&oe.length===0){q(X.id,te);return}A({fieldId:X.id}),f("")},[i,Q,d,q,A]),V=Y8t({field:j,operator:C,query:d,enabled:c&&k==="value",onCommit:X=>{x?.operatorId&&Q(x.fieldId,x.operatorId,X)}}),H=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;A(X?null:{fieldId:x.fieldId})}else k==="operator"?A(null):H()||u(!1);f("")},[k,x,j,T,A,H]),G=X=>{k==="field"?B(X):k==="operator"&&x?q(x.fieldId,X):V.handleSelect(X)},L=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(I){const te=I.nodes.findLast(oe=>!i.leaving.has(oe.id));te?i.removeItem(te.id):H()}else{const te=i.items.findLast(oe=>!i.leaving.has(oe.id));te&&i.removeItem(te.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(),G(h);return}if(k==="value"){const te=V.hasSuggestions?h:null;(V.handleKeyDown(X,te)||X.key==="Enter"&&te===null)&&X.preventBaseUIHandler()}}},$={field:N,operator:T,value:V.options},F=m?yhs:$[k],U=g.useCallback((X,te,oe)=>"search"in X&&X.search===!0||mIe(X,te,oe),[]),K=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(Tq,{items:F,itemToStringLabel:vhs,filter:k==="value"?null:U,value:null,onValueChange:(X,te)=>{te.cancel(),X&&G(X)},inputValue:d,onInputValueChange:(X,te)=>{te.reason==="input-change"&&(f(X),c||u(!0))},onItemHighlighted:X=>p(X??null),open:c,onOpenChange:(X,te)=>{!X&&te.reason==="escape-key"||!X&&te.reason==="outside-press"&&te.event.target instanceof Node&&l.current?.contains(te.event.target)||(X?u(!0):z())},...J8t,modal:!1,children:[a.jsxs("div",{"data-slot":"filter-bar-input-trigger",className:Z(x1t({variant:"default",size:X8t}),"w-auto cursor-text","focus-within:bg-fill-hover",BSn,k==="field"?"min-w-40":"min-w-28",t),children:[a.jsx(kdt,{"aria-hidden":!0,className:"-ml-[.3em] shrink-0 text-muted-foreground"}),a.jsx(oSe,{ref:X=>{l.current=X,i.registerInput(X)},"aria-label":n,spellCheck:!1,"data-slot":"filter-bar-input","data-step":k,"data-target":I?.id,inputMode:k==="value"&&j?.type==="number"?"decimal":void 0,placeholder:ne,className:Z(Nbe,"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:L})]}),a.jsx(aSe,{container:o,children:a.jsx(lSe,{align:"start",sideOffset:o_,positionMethod:vv,className:as.positioner,children:a.jsxs(cSe,{className:Z(as.popup,"min-w-56"),"data-slot":"filter-bar-editor",children:[(k!=="value"||V.hasSuggestions)&&a.jsxs("div",{className:Z(as.searchContainer,"cursor-text"),"data-slot":"filter-bar-search",onMouseDown:X=>X.preventDefault(),onClick:()=>l.current?.focus(),children:[a.jsx(Hd,{className:as.searchIcon}),a.jsx("span",{className:Z(as.searchInput,"flex items-center truncate",d===""&&as.placeholder),children:d===""?K:d})]}),k==="field"&&a.jsx(_I,{"aria-label":"Fields",getKey:X=>X.id,renderOption:X=>a.jsxs(a.Fragment,{children:[a.jsx(VX,{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(_I,{"aria-label":"Operators",getKey:X=>X.id,renderOption:X=>X.label,emptyText:"No matching operator."}),k==="value"&&V.hasSuggestions&&a.jsx(_I,{"aria-label":"Values","aria-multiselectable":V.isMany||void 0,getKey:X=>X.value,renderOption:X=>a.jsx(W8t,{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(de,{size:"sm",variant:"default",disabled:!V.canCommitQuery,onMouseDown:X=>X.preventDefault(),onClick:()=>V.commitFreeText(),children:["Apply",a.jsx(Ud,{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(de,{size:"sm",variant:"default",onMouseDown:X=>X.preventDefault(),onClick:()=>V.commitSelection()||V.commitFreeText(),children:["Done",a.jsx(Ud,{size:"xs",children:y})]})})]})})})]})})}function d9t(e,t,n){const{settleRemove:r}=Qc();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 f9t="flex h-control-sm w-14 shrink-0 items-center justify-center rounded-md text-column tracking-wide text-muted-foreground uppercase";function whs({groupId:e,logic:t,className:n}){const r=Qc(),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(f9t,"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 Shs({groupId:e,logic:t}){const n=Qc();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 h9t({group:e,depth:t,onRemove:n,removeLabel:r="Remove group",className:s}){const i=Qc(),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:f9t,children:"where"},`${h}:where`):a.jsx(whs,{groupId:e.id,logic:e.logic},`${h}:logic`);for(const h of e.nodes)d.push(a.jsxs(g.Fragment,{children:[f(h.id),cl(h)?a.jsx(khs,{group:h,depth:t+1}):a.jsx(dx,{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(dx,{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(u9t,{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(de,{ref:o,variant:"ghost",size:"sm",icon:a.jsx(bs,{}),onClick:()=>i.openGroupInput(e.id),children:"Condition"}),a.jsx(de,{variant:"ghost",size:"sm",icon:a.jsx(eS,{}),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(de,{variant:"ghost",size:"sm",icon:a.jsx(Go,{}),className:"ml-auto text-muted-foreground","aria-label":r,onClick:n,children:"Clear all"})]})]})}function khs({group:e,depth:t}){const n=Qc(),r=g.useRef(null),s=n.leaving.has(e.id);d9t(e.id,s,r);const i=fIe(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(DA,{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(Shs,{groupId:e.id,logic:e.logic}),a.jsx(de,{variant:"ghost",size:"icon-sm",tooltip:"Remove group",disabled:s,onClick:()=>n.removeGroup(e.id),children:a.jsx(Go,{})})]})]}),a.jsx(h9t,{group:e,depth:t})]})}function p9t({group:e,className:t}){const n=Qc(),r=g.useRef(null),s=g.useRef(null),i=n.leaving.has(e.id),o=n.openGroupId===e.id,l=fIe(e),c=n.items.findIndex(h=>m9t(e,h.id)),u=c===-1?n.items.length:c;d9t(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(bp,{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",e9t,i&&"pointer-events-none",t),onKeyDown:d,children:[a.jsxs(rf,{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(TI,"gap-1.5"),title:"Edit advanced filter",children:[a.jsx(al,{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(TI,"px-1.5"),children:a.jsx(Ln,{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(TI,"px-1.5"),onClick:f,children:a.jsx(Ln,{className:"size-[1.1em]"})})]}),a.jsxs(nh,{align:"start",className:"w-[min(92vw,44rem)] p-0",[pIe]:"advanced",finalFocus:s,children:[a.jsxs("div",{className:"flex items-center gap-2 border-b border-border px-3 py-2",children:[a.jsx(al,{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(de,{variant:"ghost",size:"icon-sm",className:"ml-auto",tooltip:"Close",onClick:()=>n.setOpenGroup(null),children:a.jsx(Ln,{})})]}),a.jsx(h9t,{group:e,depth:1,removeLabel:"Remove advanced filter",onRemove:()=>{n.setOpenGroup(null),f()}})]})]})}const m9t=(e,t)=>e.nodes.some(n=>n.id===t?!0:"kind"in n&&m9t(n,t));function Ohs({label:e}){const t=Qc();return t.hasRemovableItems?a.jsx(de,{variant:"ghost",size:"icon-sm","aria-label":e,tooltip:e,onClick:n=>{n.stopPropagation(),t.clear(),t.focusInput()},children:a.jsx(Ln,{})}):null}function jhs({className:e,clearLabel:t,children:n}){const r=Qc();return a.jsxs("div",{role:"group","aria-label":r.ariaLabel,"data-slot":"filter-bar",[pIe]:"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(Ohs,{label:t})}),a.jsx(x0,{"aria-live":"polite",children:r.announcement})]})}function Kg({fields:e,operators:t,value:n,onValueChange:r,createItemId:s,maxDepth:i,"aria-label":o="Filters",clearLabel:l="Clear filters",className:c,children:u}){return a.jsx(Jfs,{fields:e,operators:t,value:n,onValueChange:r,createItemId:s,maxDepth:i,ariaLabel:o,children:a.jsx(jhs,{className:c,clearLabel:l,children:u})})}function Chs({renderChip:e=_hs}){const t=Qc(),n=[];for(const r of t.expression.nodes){const s=cl(r)?a.jsx(p9t,{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(dx,{draft:!0,item:{id:r,fieldId:s,operatorId:i,value:""}})},r))}return a.jsx(a.Fragment,{children:n})}const _hs=e=>a.jsx(dx,{item:e});Kg.Chips=Chs;Kg.Chip=dx;Kg.AdvancedChip=p9t;Kg.Input=u9t;const Ths=1440*60*1e3,yIe=({queryOptions:e}={})=>{const t=Ye();return kt({queryKey:["observability-capabilities"],queryFn:()=>t.getObservabilityCapabilities(),retry:!1,staleTime:Ths,...e})},UX=()=>{const{data:e,isLoading:t}=yIe();return{isLoading:t,enabled:!t&&(e?.capabilities.traceQuery??!0)}},Ehs=()=>{const{data:e,isLoading:t}=yIe();return{isLoading:t,enabled:!t&&(e?.capabilities.feedback??!0)}};function Ihs(e){return e.startsWith("agent-")}function Nhs(e){return e.match(/^(?:mcp_)?tool:\s*'(.*?)'/)?.[1]??e}function g9t(e){return v9t(e,[])}function v9t(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=Nhs(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,...Ihs(s)?{matchArgs:"ignore"}:{}})}!r&&n.children?.length&&v9t(n.children,t)}return t}function Ahs(e){const t=(()=>{try{const r=JSON.stringify(e.input);return r?r.length>40?`${r.slice(0,40)}…`:r:""}catch{return""}})(),n=ux(e.id)??e.id;return t?`${n} — ${t}`:n}function Phs({traceId:e,isOpen:t,onClose:n,level:r=2}){const s=Ye(),{data:i,isLoading:o}=kt({queryKey:["trace-trajectory",e],queryFn:()=>s.getTraceTrajectory(e??""),enabled:t&&!!e}),l=i?.steps?g9t(i.steps):[],c=l.length>0?By(l,2):"";return a.jsxs(yo,{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(yo.Top,{children:[a.jsxs(Zd,{children:[a.jsx(rl,{})," ",ux(e)]}),"›",a.jsxs(Zd,{children:[a.jsx(ad,{})," Add Tool Mocks to Item"]})]}),a.jsxs(yo.Content,{children:[a.jsx(yo.Header,{children:a.jsxs(yo.Heading,{children:[a.jsx(ad,{})," 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($hs,{initialMocksJson:c,onClose:n},e??"no-trace")]})]})}function $hs({initialMocksJson:e,onClose:t}){const[n,r]=g.useState(""),[s,i]=g.useState(""),[o,l]=g.useState(e),{data:c,isLoading:u}=ik(),d=c?.datasets??[],{data:f=[],isLoading:h}=_N({datasetId:n,queryOptions:{enabled:!!n}}),{data:p,isFetching:m}=_1t({datasetId:n,itemId:s,queryOptions:{enabled:!!n&&!!s}}),{updateItem:v}=ul(),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){Ge.error("Please select a dataset and an item");return}let k;try{const T=o.trim()?JSON.parse(o):[];if(!Array.isArray(T)){Ge.error("Tool Mocks must be a JSON array");return}k=T}catch{Ge.error("Tool Mocks must be valid JSON");return}if(k.length===0){Ge.error("There are no tool mocks to add");return}if(!p||p.id!==s){Ge.error("Item is still loading, please try again");return}const C=[...p.toolMocks??[],...k];try{await v.mutateAsync({datasetId:n,itemId:s,toolMocks:C}),Ge.success(`Added ${k.length} tool mock(s) to the item`),t()}catch(T){Ge.error(`Failed to add tool mocks: ${T instanceof Error?T.message:"Unknown error"}`)}};return a.jsxs(Qa,{onSubmit:b,children:[a.jsxs(ft,{children:[a.jsx(lt,{required:!0,children:"Dataset"}),a.jsxs(Ur,{value:n,onValueChange:x,disabled:u,children:[a.jsx(Qr,{children:a.jsx(qr,{placeholder:u?"Loading datasets...":"Select a dataset"})}),a.jsx(Zr,{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(or,{value:S.id,children:S.name},S.id))})]})]}),a.jsxs(ft,{children:[a.jsx(lt,{required:!0,children:"Item"}),a.jsxs(Ur,{value:s,onValueChange:i,disabled:!n||h,children:[a.jsx(Qr,{children:a.jsx(qr,{placeholder:n?h?"Loading items...":"Select an item":"Select a dataset first"})}),a.jsx(Zr,{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(or,{value:S.id,children:Ahs(S)},S.id))})]})]}),a.jsxs(ft,{children:[a.jsx(lt,{children:"Tool Mocks (JSON)"}),a.jsx(Cr,{value:o,onChange:l,showCopyButton:!1,className:"min-h-40"}),a.jsx(eo,{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(de,{icon:a.jsx(Ln,{}),type:"button",onClick:t,children:"Cancel"}),a.jsx(de,{icon:a.jsx(bs,{}),type:"submit",variant:"default",disabled:v.isPending||m||!y||!n||!s||p?.id!==s,children:v.isPending?"Adding...":"Append Tool Mocks"})]})]})}const Rhs=3e4;function y9t(e){return gL(e.state.error,"feedback")||vL(e.state.error)?!1:Rhs}function HP(e,t,n){const r=e.get(t);if(r!==void 0)return r;const s=n();return e.set(t,s),s}const B6=300*1e3;function Mhs({traceId:e,spanId:t,depth:n,queryOptions:r}){return Ye(),kt({queryKey:["branch",e,t,n],queryFn:async()=>{throw new Error("traceId and spanId are required")},staleTime:0,...r})}const u2={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"};function FXe(e){return Object.values(fu).find(t=>t===e)}const xIe=({entityType:e,rootOnly:t=!1,queryOptions:n}={})=>{const r=Ye();return kt({queryKey:e?["observability-entity-names","by-type",e]:["observability-entity-names","all",t?"root-only":"all-types"],queryFn:async()=>{try{if(e){const i=FXe(e);return i?await r.getEntityNames({entityType:i}):{names:[]}}if(!t)return await r.getEntityNames();const s=await Promise.all(Object.values(u2).map(i=>{const o=FXe(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:B6,...n})},bIe=({queryOptions:e}={})=>{const t=Ye();return kt({queryKey:["observability-environments"],queryFn:async()=>{try{return await t.getEnvironments()}catch{return{environments:[]}}},select:n=>n?.environments??[],retry:!1,staleTime:B6,...e})},x9t=({queryOptions:e}={})=>{const t=Ye();return kt({queryKey:["observability-service-names"],queryFn:async()=>{try{return await t.getServiceNames()}catch{return{serviceNames:[]}}},select:n=>n?.serviceNames??[],retry:!1,staleTime:B6,...e})},Dhs=1e3*60*60*24*30;function wIe({traceId:e,spanId:t,queryOptions:n}){const r=Ye();return kt({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?Dhs:0,...n})}const b9t=({queryOptions:e}={})=>{const t=Ye();return kt({queryKey:["observability-tags"],queryFn:async()=>{try{return await t.getTags()}catch{return{tags:[]}}},select:n=>n?.tags??[],retry:!1,staleTime:B6,...e})};function Lhs({threadId:e,queryOptions:t}){const n=Ye(),{data:r}=kt({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 SIe=(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 $_({traceId:e,passive:t=!1,queryOptions:n}){const r=Ye(),{queryKey:s,queryFn:i,enabled:o,staleTime:l}=SIe(r,e);return kt({queryKey:s,queryFn:i,enabled:o,staleTime:l,refetchOnMount:!t,refetchOnWindowFocus:!t,refetchOnReconnect:!t,...n})}function zhs(){const e=Ye(),t=yr();return n=>t.fetchQuery(SIe(e,n))}function Fhs({traceId:e,anchorSpanId:t,listMode:n,depth:r,queryOptions:s}){const i=n==="branches",o=$_({traceId:e,queryOptions:{enabled:!!e,...s?.trace}});return Mhs({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 Bhs(e){return e?.page.next??void 0}function Vhs(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 Vle=e=>typeof e=="string"?e:e.toISOString();function Uhs(e){return{traceId:e.traceId,rootSpanId:e.spanId,name:e.name,entityId:e.entityId??null,parentSpanId:e.parentSpanId??null,createdAt:Vle(e.createdAt),metadata:e.metadata??null,inputPreview:e.inputPreview??null,threadId:e.threadId??null,resourceId:e.resourceId??null,startedAt:Vle(e.startedAt),endedAt:e.endedAt==null?e.endedAt:Vle(e.endedAt),entityName:e.entityName??null,entityType:e.entityType??null,environment:null,status:e.status}}function qhs(e){const t=new Set;return e.pages.flatMap(n=>n.spans.flatMap(r=>t.has(r.traceId)?[]:(t.add(r.traceId),[Uhs(r)])))}function Qhs(e){return e.pagination?.hasMore?e.pagination.page+1:void 0}function Zhs({query:e,limit:t=25,enabled:n=!0,withQueryTrace:r=!0,legacyFilters:s,queryOptions:i}){const o=Ye(),{inView:l,setRef:c}=E0(),u=Am({queryKey:["trace-query",e,t],queryFn:e?async({pageParam:I})=>{const P=await new zO({...o.options,retries:0}).queryTraces({...e,page:{limit:t,after:I??null}});if("traces"in P&&"page"in P)return P;throw new Error("Expected a cursor-paginated trace query response")}:k0,initialPageParam:void 0,getNextPageParam:Bhs,select:Vhs,retry:!1,placeholderData:Jue,enabled:n&&r,...i?.traceQuery}),d=e?.orderBy,f=d?.[0]?.direction==="asc"?"ASC":"DESC",h=Am({queryKey:["trace-query-legacy",s,t,d],queryFn:({pageParam:I})=>o.listTracesLight({filters:s,pagination:{page:I,perPage:t},orderBy:{field:"startedAt",direction:f}}),initialPageParam:0,getNextPageParam:Qhs,select:qhs,retry:!1,placeholderData:Jue,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 hve="mastra_model_total_input_tokens",w9t="mastra_model_total_output_tokens",BXe=500;function Whs(e){const t=[];for(let n=0;n<e.length;n+=BXe)t.push(e.slice(n,n+BXe));return t}function Hhs(){return{estimatedCost:0,hasEstimatedCost:!1,costUnits:new Set,hasUnknownCostUnit:!1}}function Ghs(e,t){for(const n of t.groups){const r=n.dimensions.traceId,s=n.dimensions.name;if(!r||s!==hve&&s!==w9t)continue;const i=HP(e,r,Hhs),o=s===hve?"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 Khs(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 pve({traceIds:e,enabled:t,autoRefetch:n,queryOptions:r}){const s=Ye(),i=[...new Set(e)].toSorted(),o=`${s.options.baseUrl||(typeof window>"u"?"local":window.location.origin||"local")}:${s.options.apiPrefix??"/api"}`;return kt({queryKey:["trace-usage",o,i],enabled:t&&i.length>0,queryFn:async()=>{const l=Whs(i),c=await Promise.allSettled(l.map(d=>s.getMetricBreakdown({name:[hve,w9t],aggregation:"sum",groupBy:["traceId","name"],filters:{traceIds:d},limit:d.length*2}))),u=new Map;for(const d of c)d.status==="fulfilled"&&Ghs(u,d.value);return Khs(u)},placeholderData:(l,c)=>c?.queryKey[1]===o?l:void 0,refetchInterval:t&&n?1e4:!1,...r})}const S9t=({traceId:e,spanId:t,queryOptions:n})=>{const r=Ye(),s=yr();return kn({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})},k9t=({traceId:e,spanId:t,queryOptions:n})=>{const r=Ye(),s=yr();return kn({mutationFn:({feedbackId:i})=>r.deleteFeedback({feedbackIds:[i]}),onSuccess:()=>s.invalidateQueries({queryKey:t?["span-feedback",e,t]:["trace-feedback",e]}),...n})},kIe=({traceId:e="",spanId:t="",page:n,queryOptions:r})=>{const s=Ye(),i=n??0;return kt({queryKey:["span-feedback",e,t,i],queryFn:()=>s.listFeedback({filters:{traceId:e,spanId:t},pagination:{page:i,perPage:10}}),refetchInterval:y9t,gcTime:0,staleTime:0,...r})},qX=({traceId:e="",page:t,queryOptions:n})=>{const r=Ye(),s=t??0;return kt({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:y9t,gcTime:0,staleTime:0,...n})},O9t=100,Yhs={canonicalFields:[],observedFields:[],observedFieldsTruncated:!1},Xhs="TRACE_QUERY_DISCOVERY_UNSUPPORTED",Jhs=e=>e instanceof Hy&&typeof e.body=="object"&&e.body!==null&&e.body.code===Xhs,eps=e=>["trace-query-fields",e.from,e.to],j9t=(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:O9t},{signal:i});return o.map(({value:l})=>({value:l}))},tps=({timeRange:e,queryOptions:t})=>{const n=Ye(),r=kt({queryKey:eps(e),queryFn:async({signal:i})=>{try{return await n.getTraceQueryFields({timeRange:e,predicateScope:"trace",limit:O9t},{signal:i})}catch(o){if(Jhs(o))return Yhs;throw o}},retry:!1,staleTime:B6,placeholderData:Jue,...t}),s=r.data?.observedFields;return{fields:g.useMemo(()=>(s??[]).map(i=>({path:i.path,suggestions:j9t(n,e,"trace",i.path)})),[s,n,e]),isLoading:r.isLoading,error:r.error}};function nps(){const e=Ye();return`mastra:traces:columns:${e.options.baseUrl||(typeof window>"u"?"local":window.location.origin||"local")}:${e.options.apiPrefix??"/api"}`}function rps(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 By(r,2)}function sps({traceDetails:e,rootSpanId:t,traceId:n,isOpen:r,onClose:s,level:i=2}){const o=Ye(),{data:l}=wIe({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}=kt({queryKey:["trace-trajectory",n],queryFn:()=>o.getTraceTrajectory(n??""),enabled:r&&!!n}),f=u?.steps&&u.steps.length>0?By({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?g9t(u.steps):[],p=h.length>0?By(h,2):void 0;return a.jsx($zt,{initialInput:rps(c),initialGroundTruth:c?.output!=null?By(c.output,2):"",initialTrajectory:f,trajectoryLoading:d,initialToolMocks:p,breadcrumb:a.jsxs(Zd,{children:[a.jsx(rl,{})," ",ux(n)]}),isOpen:r,onClose:s,level:i,source:n?{type:"trace",referenceId:n}:void 0})}const ips={"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"},Ule="Pick a wider time range — older traces may fall outside the current window.";function ops({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No traces for ${ips[e]}`,description:Ule}:t&&n?{title:`No traces between ${is(t,"date-time")} and ${is(n,"date-time")}`,description:Ule}:t?{title:`No traces since ${is(t,"date-time")}`,description:Ule}:{title:"No traces yet",description:"Traces will appear here once agents, workflows, or tools are executed."}}const aps=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=ops({datePreset:e,dateFrom:t,dateTo:n});return a.jsx(tn,{titleSlot:r,descriptionSlot:s,variant:"fill"})};function C9t({queryOptions:e}={}){const t=Ye(),n=yr();return kn({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 lps(e){return e==="needs-review"?"warning":e==="complete"||e==="reviewed"?"success":"neutral"}function OIe({status:e,children:t,...n}){return a.jsx(Ft,{size:"xs",...n,variant:lps(e),children:t??e})}function cps(e){const t=e.author;return t?t.name||t.email||t.id:void 0}const _9t=g.createContext(null);function R_(){const e=g.useContext(_9t);if(!e)throw new Error("Comment compounds must be rendered within Comment");return e}const ups=dd("flex flex-col",{variants:{variant:{default:"gap-2",embed:Z(hr,"gap-1 rounded-xl p-3"),thread:""}},defaultVariants:{variant:"default"}}),T9t=g.forwardRef(({className:e,variant:t="default",...n},r)=>a.jsx(_9t.Provider,{value:t,children:a.jsx("div",{ref:r,"data-slot":"comment","data-variant":t,className:Z(ups({variant:t}),e),...n})}));T9t.displayName="Comment";const dps={default:"gap-3",embed:"gap-2",thread:""},E9t=g.forwardRef(({className:e,...t},n)=>{const r=R_();return a.jsx("ul",{ref:n,"data-slot":"comment-list",className:Z("flex flex-col",dps[r],e),...t})});E9t.displayName="CommentList";const fps={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"},mve=g.forwardRef(({className:e,continued:t=!1,highlighted:n=!1,...r},s)=>{const i=R_(),o=i==="thread"?"div":"li";return a.jsx(o,{ref:s,"data-slot":"comment-item",className:Z("group/comment-item",fps[i],i==="thread"&&(t?"py-0.5":"py-1.5"),n&&"bg-info-subtle",e),...r})});mve.displayName="CommentItem";const I9t=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}));I9t.displayName="CommentItemAvatar";const N9t=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}));N9t.displayName="CommentItemContent";const hps={default:"flex items-center gap-2",embed:"flex items-center gap-2",thread:"flex items-baseline gap-1.5"},gve=g.forwardRef(({className:e,...t},n)=>{const r=R_();return a.jsx("div",{ref:n,"data-slot":"comment-item-header",className:Z(hps[r],e),...t})});gve.displayName="CommentItemHeader";const pps={default:"subheading",embed:"subheading",thread:"column"},mps={default:"text-foreground",embed:"text-foreground",thread:"truncate text-foreground"},A9t=g.forwardRef(({className:e,...t},n)=>{const r=R_();return a.jsx(Y,{ref:n,as:"span",variant:pps[r],"data-slot":"comment-item-author",className:Z(mps[r],e),...t})});A9t.displayName="CommentItemAuthor";const gps={default:"text-caption text-muted-foreground",embed:"text-caption text-muted-foreground",thread:"text-meta text-placeholder shrink-0"},P9t=g.forwardRef(({className:e,...t},n)=>{const r=R_();return a.jsx("time",{ref:n,"data-slot":"comment-item-timestamp",className:Z(gps[r],e),...t})});P9t.displayName="CommentItemTimestamp";const vps={default:"body",embed:"body",thread:"caption"},yps={default:"whitespace-pre-wrap text-foreground border-l border-border pl-3",embed:"whitespace-pre-wrap text-foreground",thread:""},$9t=g.forwardRef(({className:e,...t},n)=>{const r=R_();return qdt({defaultTagName:r==="thread"?"div":"p",props:{...t,ref:n,"data-slot":"comment-item-body",className:Z($l({variant:vps[r]}),yps[r],e)}})});$9t.displayName="CommentItemBody";const xps={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"},R9t=g.forwardRef(({className:e,...t},n)=>{const r=R_();return r==="embed"?null:a.jsx("div",{ref:n,"data-slot":"comment-item-actions",className:Z(xps[r],e),...t})});R9t.displayName="CommentItemActions";function bps({status:e}){const t=e==="reviewed"?"reviewed":"needs-review";return a.jsx(OIe,{"data-slot":"feedback-review-status",status:t,children:t==="reviewed"?"Reviewed":"Needs review"})}function wps(e){const t=e.comment||(typeof e.value=="string"?e.value:"");return t||(e.feedbackType==="thumbs"?e.value===1?"👍":"👎":String(e.value??""))}function Sps({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=cps(l),f=d?a.jsx(OS,{name:d,src:l.author?.avatarUrl,size:"sm"}):null,h=d&&a.jsx(A9t,{children:d}),p=a.jsx(P9t,{dateTime:u.toISOString(),children:is(u,"date-time")}),m=l.feedbackId,v=a.jsx(bps,{status:l.reviewStatus}),y=!!(s&&m&&l.reviewStatus!=="reviewed"),x=!!(n&&m),b=m&&(y||x)&&a.jsx(R9t,{children:a.jsxs(ut,{children:[a.jsx(ut.Trigger,{render:a.jsx(de,{size:"icon-sm",variant:"ghost","aria-label":"Feedback actions",children:a.jsx(GD,{})})}),a.jsxs(ut.Content,{align:"end",children:[y&&a.jsxs(ut.Item,{disabled:i===m,onSelect:()=>s?.(m),children:[a.jsx(Nt,{size:"xs",children:a.jsx(E3,{})}),"Mark reviewed"]}),x&&a.jsxs(ut.Item,{disabled:r,onSelect:()=>n?.(m),children:[a.jsx(Nt,{size:"xs",children:a.jsx(Go,{})}),"Delete feedback"]})]})]})}),S=a.jsx($9t,{children:wps(l)}),k=m??`${l.traceId}-${c}`;return e==="thread"?a.jsxs(mve,{children:[f&&a.jsx(I9t,{children:f}),a.jsxs(N9t,{children:[a.jsxs(gve,{children:[h,p,v,b]}),S]})]},k):a.jsxs(mve,{children:[a.jsxs(gve,{children:[f,h,p,v,b]}),S]},k)});return e==="thread"?a.jsx(a.Fragment,{children:o}):a.jsx(E9t,{children:o})}function M9t({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(T9t,{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(HEt,{size:"sm",children:[a.jsx(GEt,{"aria-label":"Leave feedback",placeholder:"Leave feedback...",value:d,onChange:S=>f(S.target.value)}),a.jsx(Ype,{align:"inline-end",children:a.jsx(KEt,{type:"submit","aria-label":"Send feedback",disabled:m,children:a.jsx(WS,{})})})]})}),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(Sps,{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(de,{icon:a.jsx($A,{}),size:"sm",variant:"ghost",disabled:y===0,onClick:()=>n?.(y-1),children:"Previous"}),a.jsx(de,{icon:a.jsx(Gs,{}),size:"sm",variant:"ghost",disabled:!x,onClick:()=>n?.(y+1),children:"Next"})]}),a.jsx(Ut,{open:h!==void 0,onOpenChange:S=>{!S&&!o&&p(void 0)},children:a.jsxs(Ut.Content,{children:[a.jsxs(Ut.Header,{children:[a.jsx(Ut.Title,{children:"Delete feedback?"}),a.jsx(Ut.Description,{children:"This permanently deletes this feedback comment. This action cannot be undone."})]}),a.jsxs(Ut.Footer,{children:[a.jsx(Ut.Cancel,{disabled:o,children:"Cancel"}),a.jsx(de,{icon:a.jsx(Go,{}),variant:"primary",disabled:o,onClick:b,children:o?"Deleting…":"Delete"})]})]})})]})}function D9t({traceId:e,spanId:t}){const[n,r]=g.useState(0),{data:s,isLoading:i}=kIe({traceId:e,spanId:t,page:n,queryOptions:{enabled:!!e&&!!t}}),{mutateAsync:o,isPending:l}=S9t({traceId:e,spanId:t}),{mutateAsync:c,isPending:u}=k9t({traceId:e,spanId:t}),d=C9t();return a.jsx(M9t,{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 kps=["type","input","duration","endTime","environment","inputTokens","outputTokens","totalTokens","estimatedCost"],L9t=["inputTokens","outputTokens","totalTokens","estimatedCost"],z9t=["traceId","threadId","resourceId","entityId"],F9t={traceId:"Trace ID",threadId:"Thread ID",resourceId:"Resource ID",entityId:"Primitive ID"},zb={visibleColumns:["type","input","duration","estimatedCost"],customColumns:[],metadataKeys:[]},B9t=3,Ops=new Set([2,B9t]),jps=new Set(kps),Cps=new Set(L9t),_ps=new Set(z9t);function Tps(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Eps(e){return typeof e=="string"&&jps.has(e)}function Ips(e){return typeof e=="string"&&_ps.has(e)}function Nps(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 Aps(e){if(!e)return zb;try{const t=JSON.parse(e);if(!Tps(t)||!Ops.has(t.version))return zb;const n=Array.isArray(t.visibleColumns)?[...new Set(t.visibleColumns.filter(Eps))]:[...zb.visibleColumns],r=Array.isArray(t.customColumns)?[...new Set(t.customColumns.filter(Ips))]:[];return{visibleColumns:n,customColumns:r,metadataKeys:Nps(t.metadataKeys)}}catch{return zb}}function Pps(e){return JSON.stringify({version:B9t,visibleColumns:e.visibleColumns,customColumns:e.customColumns,metadataKeys:e.metadataKeys})}function V9t(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 $ps=/^(?:agent|workflow|scorer) run: '(.+?)'(.*)$/;function Rps(e){return e&&e.replace($ps,"$1$2")}function Mps(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 kc(e,t){return e.visibleColumns.includes(t)}function Dps(e){return e.visibleColumns.some(U9t)}function U9t(e){return Cps.has(e)}const Lps=[],zps=["type","input","duration","endTime","environment"],VXe={type:"Primitive type",input:"Input",duration:"Duration",endTime:"End",environment:"Environment",inputTokens:"Input tokens",outputTokens:"Output tokens",totalTokens:"Total tokens",estimatedCost:"Estimated cost"};function Fps({preferences:e,availableMetadataKeys:t=Lps,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(ut,{children:[a.jsx(ut.Trigger,{render:a.jsx(de,{variant:"ghost",size:"md",icon:a.jsx(udt,{"aria-hidden":!0}),children:"Columns"})}),a.jsxs(ut.Content,{align:"end",className:"min-w-56",children:[a.jsx(ut.Label,{children:"Standard columns"}),zps.map(S=>a.jsx(ut.CheckboxItem,{checked:e.visibleColumns.includes(S),onCheckedChange:()=>s(S),children:VXe[S]},S)),a.jsx(ut.Separator,{}),a.jsx(ut.Label,{children:"Usage columns"}),L9t.map(S=>a.jsx(ut.CheckboxItem,{checked:e.visibleColumns.includes(S),disabled:!!n,onCheckedChange:()=>s(S),children:VXe[S]},S)),n&&a.jsx(Y,{variant:"meta",tone:"faint",className:"px-2 py-1",role:"note",children:n}),a.jsx(ut.Separator,{}),a.jsx(ut.Label,{children:"Custom columns"}),z9t.map(S=>{const k=e.customColumns.includes(S);return a.jsx(ut.CheckboxItem,{checked:k,onCheckedChange:()=>k?o(S):i(S),children:F9t[S]},S)}),(r||e.metadataKeys.length>0)&&a.jsxs(a.Fragment,{children:[a.jsx(ut.Separator,{}),a.jsx(ut.Label,{children:"Metadata columns"}),e.metadataKeys.map(S=>a.jsx(ut.CheckboxItem,{checked:!0,title:S,onCheckedChange:()=>c(S),children:S},S)),r&&a.jsxs(ut.Item,{onSelect:()=>f(!0),children:[a.jsx(bs,{"aria-hidden":!0}),"Add metadata column"]})]}),a.jsx(ut.Separator,{}),a.jsx(ut.Item,{onSelect:u,children:"Reset to defaults"})]})]}),r&&a.jsx(rs,{open:d,onOpenChange:x,children:a.jsx(ss,{children:a.jsxs(Qa,{onSubmit:b,className:"gap-0",children:[a.jsxs(es,{children:[a.jsx(Kr,{children:"Add metadata column"}),a.jsx(Mo,{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(Gr,{children:a.jsxs(ft,{invalid:!!m,children:[a.jsx(lt,{children:"Metadata key"}),a.jsx(Ca,{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(cs,{children:m})]})}),a.jsxs(Ho,{children:[a.jsx(ja,{children:"Cancel"}),a.jsx(Oa,{type:"submit",children:"Add column"})]})]})})})]})}function NZ({traceId:e,variant:t}){const[n,r]=g.useState(0),{data:s,isLoading:i}=qX({traceId:e,page:n,queryOptions:{enabled:!!e}}),{mutateAsync:o,isPending:l}=S9t({traceId:e}),{mutateAsync:c,isPending:u}=k9t({traceId:e}),d=C9t();return a.jsx(M9t,{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 jIe=new Set(["tags","runId","sessionId","requestId","userId","organizationId","serviceName","experimentId"]),Bps=["is","isNot","in","notIn","exists","notExists","gt","gte","lt","lte"],CIe=e=>Bps.includes(e),vve=e=>"nodes"in e,Vps={is:"eq",isNot:"ne",in:"in",notIn:"notIn",exists:"exists",notExists:"notExists",gt:"gt",gte:"gte",lt:"lt",lte:"lte"},q9t=new Set(["spans.durationMs","scores.score","feedback.value"]),Ups=new Set(["entityType","status","entityName","environment","traceId","threadId","resourceId"]),qps=new Set(["threadId","resourceId","environment"]),Q9t={isNot:"is",notIn:"in",notExists:"exists"},Qps=e=>e in Q9t,Z9t=["spans","scores","feedback"];function Zps(e){if(e==="entityId")return{scope:"spans",path:"entityId"};for(const t of Z9t)if(e.startsWith(`${t}.`)&&e.length>t.length+1)return{scope:t,path:e.slice(t.length+1)};return{path:e}}function UXe(e,t,n){const r=Vps[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;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 Wps(e){if(jIe.has(e.fieldId))return;const t=e.operatorId??"is",n=t==="exists"||t==="notExists",r=(Array.isArray(e.value)?e.value:[e.value]).filter(d=>typeof d=="string"&&!!d.trim()&&d!=="Any");if(!r.length&&!n)return;let s=e.fieldId,i=r;if(s.startsWith("metadata.")){if(s.length===9)return}else if(s==="rootEntityType"||s==="entityType")s="entityType";else if(s==="status"){if(i=r.filter(d=>d!=="running"),!i.length&&!n)return}else if(q9t.has(s)&&(i=r.map(Number).filter(d=>!Number.isNaN(d)),!i.length&&!n))return;const{scope:o,path:l}=Zps(s),c=s.startsWith("metadata.");if(!o&&!c&&!Ups.has(s))return;if(o&&Qps(t)){const d=UXe(Q9t[t],l,i);return d?{predicate:{[o]:{none:d}}}:void 0}const u=UXe(t,l,i);if(u)return o?{scope:o,predicate:u}:(t==="isNot"||t==="notIn")&&(c||qps.has(s))?{predicate:{op:"or",args:[u,{op:"notExists",path:l}]}}:{predicate:u}}function W9t(e,{mergeRelated:t}){const n=[],r={spans:[],scores:[],feedback:[]};for(const s of e){const i=Wps(s);i&&("scope"in i?t?r[i.scope].push(i.predicate):n.push({[i.scope]:{some:i.predicate}}):n.push(i.predicate))}for(const s of Z9t){const[i,...o]=r[s];if(!i)continue;const l=o.length?{op:"and",args:[i,...o]}:i;n.push({[s]:{some:l}})}return n}function H9t(e){const t=e.nodes.filter(r=>!vve(r)),n=W9t(t,{mergeRelated:e.logic==="and"});for(const r of e.nodes){if(!vve(r))continue;const s=H9t(r);s&&n.push(s)}if(n.length!==0)return n.length===1?n[0]:{op:e.logic,args:n}}function qXe({rootEntityType:e,status:t,dateFrom:n,dateTo:r,tokens:s,groups:i=[],now:o}){const l=[];e&&l.push({op:"eq",left:{path:"entityType"},right:{literal:e}}),t&&t!=="running"&&l.push({op:"eq",left:{path:"status"},right:{literal:t}}),l.push(...W9t(s,{mergeRelated:!0}));for(const c of i){const u=H9t(c);u&&l.push(u)}return{timeRange:{from:(n??new Date(o.getTime()-10080*60*1e3)).toISOString(),to:(r??o).toISOString()},...l.length?{where:{op:"and",args:l}}:{}}}const Hps=744*60*60*1e3;function Gps(e){const t=new Date(e.to).getTime(),n=new Date(e.from).getTime(),r=t-Hps;return n>=r&&n<t?e:{from:new Date(r).toISOString(),to:e.to}}const G9t=[{label:"Agent",entityType:u2.AGENT},{label:"Workflow",entityType:u2.WORKFLOW},{label:"Scorer",entityType:u2.SCORER},{label:"Ingest",entityType:u2.INGEST}],Kps=[{label:"Running",value:"running"},{label:"Success",value:"success"},{label:"Error",value:"error"}],U5="metadata.",AZ="filterMetadata.",K9t=e=>e.startsWith(U5)&&e.length>U5.length,QX=e=>e.startsWith(AZ)&&e.length>AZ.length,Yps=e=>AZ+e.slice(U5.length),Xps=e=>U5+e.slice(AZ.length),MS="rootEntityType",DS="status",p1="listMode",$B="anchorSpanId",Jps=new Set(["traces","branches"]),m1="datePreset",Hw="dateFrom",Gw="dateTo",ems=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Cc={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",traceId:"filterTraceId",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId","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"},ZX=Object.keys(Cc),Y9t=".op",PZ=e=>e+Y9t,X9t=e=>e.endsWith(Y9t),tms=e=>e==="exists"||e==="notExists",nms=e=>e==="in"||e==="notIn",WX=e=>e.operatorId??(Array.isArray(e.value)?"in":"is"),J9t=(e,t)=>{const n=e.get(PZ(t));return n!==null&&CIe(n)?n:void 0},rms=new Set(["running","success","error"]),_Ie="mastra:traces:saved-filters";function sms(e,t=_Ie){const n=xms(e),r=e.get(m1);r&&r!=="custom"&&n.set(m1,r);const s=EIe(n).filter(i=>i.nodes.length>0);n.delete(NC);for(const i of s)n.append(NC,TIe(i));if(!n.toString()){ims(t);return}try{localStorage.setItem(t,n.toString())}catch{}}function ims(e=_Ie){try{localStorage.removeItem(e)}catch{}}function oms(e=_Ie){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function ams(e){if(e.has(m1)||e.has(Hw)||e.has(Gw)||e.has(MS)||e.has(DS)||e.has(p1)||e.has(NC))return!0;for(const t of ZX)if(e.has(Cc[t]))return!0;for(const t of e.keys())if(QX(t))return!0;return!1}const lms=[{id:"is",label:"is"},{id:"isNot",label:"is not"},{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"}],G9=["is","isNot","in","notIn","exists","notExists"],QXe=["is","isNot","in","notIn"],cms=["is","isNot","gt","gte","lt","lte","exists","notExists"],ums=["exists","notExists"],ZXe=["is","in"],dms=["is"],fms={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","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"},e7t={timeRange:{icon:JI,color:Di("amber")},rootEntityType:{icon:sdt,color:Di("purple")},entityName:{icon:HS,color:Di("cyan")},entityId:{icon:gdt,color:Di("pink")},status:{icon:okn,color:Di("orange")},tags:{icon:gTn,color:Di("pink")},serviceName:{icon:q_n,color:Di("cyan")},environment:{icon:xv,color:Di("green")},traceId:{icon:Vdt,color:Di("blue")},runId:{icon:ku,color:Di("purple")},threadId:{icon:A3,color:Di("blue")},sessionId:{icon:N3,color:Di("orange")},requestId:{icon:Adt,color:Di("amber")},resourceId:{icon:LA,color:Di("green")},userId:{icon:DTn,color:Di("orange")},organizationId:{icon:Rbe,color:Di("cyan")},experimentId:{icon:oH,color:Di("pink")},"spans.name":{icon:eN,color:Di("blue")},"spans.spanType":{icon:H_n,color:Di("purple")},"spans.model":{icon:MA,color:Di("green")},"spans.provider":{icon:Ode,color:Di("cyan")},"spans.durationMs":{icon:sS,color:Di("orange")},"spans.error":{icon:Gd,color:"var(--destructive-foreground)"},"scores.scorerId":{icon:yv,color:Di("green")},"scores.score":{icon:a_n,color:Di("amber")},"feedback.feedbackType":{icon:jTn,color:Di("purple")},"feedback.value":{icon:zA,color:Di("amber")},"feedback.comment":{icon:OCn,color:Di("blue")}},t7t=e=>e7t[e]?.icon,n7t=e=>e7t[e]?.color??Di(iP(e)),iM=e=>({id:e,label:fms[e]??e,icon:t7t(e),color:n7t(e)}),hms=["entityId","traceId","runId","threadId","sessionId","requestId","resourceId","userId","organizationId","experimentId"],pms=["spans.name","spans.spanType","spans.model","spans.provider","spans.durationMs","spans.error","scores.scorerId","scores.score","feedback.feedbackType","feedback.value","feedback.comment"],mms=new Set(["spans.error","feedback.comment"]),ZT=(e,t)=>e.label.localeCompare(t.label);function gms({availableRootEntityNames:e,availableEnvironments:t,hiddenFieldIds:n=[],metadataFields:r=[],valueSuggestions:s,withQueryTrace:i=!0}){const o=(y,x,b=G9)=>({...iM(y),operators:b,strict:!0,suggestions:x}),l=y=>({...iM(y),operators:y==="traceId"?QXe:G9}),c=y=>{const[x,b]=y.split("."),S=s?.(x,b);return{...iM(y),operators:G9,...S?{strict:!0,suggestions:S}:{}}},u=y=>({...iM(y),type:"number",operators:cms}),d=y=>({...iM(y),operators:ums}),f=[o("rootEntityType",G9t.map(y=>({value:y.entityType,label:y.label})),ZXe),o("entityName",e.map(y=>({value:y})),QXe),o("status",Kps.filter(y=>y.value!=="running").map(y=>({value:y.value,label:y.label})),ZXe),o("environment",t.map(y=>({value:y})))],h=hms.map(l),p=["spans","scores","feedback"].flatMap(y=>pms.filter(x=>x.startsWith(`${y}.`)).map(x=>q9t.has(x)?u(x):mms.has(x)?d(x):c(x)).sort(ZT)),m=r.filter(({path:y})=>K9t(y)).map(({path:y,suggestions:x})=>({id:y,label:y.slice(U5.length),icon:al,color:Di(iP(y)),operators:G9,suggestions:x})),v=new Set(n);return i?[...f.sort(ZT),...h.sort(ZT),...p,...m.sort(ZT)].filter(y=>!jIe.has(y.id)).map(y=>v.has(y.id)?{...y,hidden:!0}:y):[...f.sort(ZT),...h.sort(ZT)].map(y=>({...y,operators:dms,...v.has(y.id)?{hidden:!0}:{}}))}function r7t(e){return e.map(t=>({id:t.fieldId,fieldId:t.fieldId,operatorId:WX(t),value:t.value==="Any"?"":t.value}))}function s7t(e){return e.map(i7t)}function i7t(e){const t={fieldId:e.fieldId,value:Array.isArray(e.value)?e.value.map(String):String(e.value)};return CIe(e.operatorId)&&e.operatorId!==WX(t)&&(t.operatorId=e.operatorId),t}function WXe(e,t){return{logic:"and",nodes:[...r7t(e),...t.map(o7t)]}}function o7t(e){return{id:e.id,kind:"group",logic:e.logic,nodes:e.nodes.map(t=>vve(t)?o7t(t):{id:t.id??t.fieldId,fieldId:t.fieldId,operatorId:WX(t),value:t.value==="Any"?"":t.value})}}function vms(e){const t=e.nodes.filter(r=>!cl(r)),n=e.nodes.filter(cl).map(a7t);return{tokens:s7t(t),groups:n}}function a7t(e){const t=e.nodes.map(n=>cl(n)?a7t(n):{id:n.id,...i7t(n)});return{id:e.id,logic:e.logic,nodes:t}}function yms(e){const t=[],n=new Map([[MS,"rootEntityType"],[DS,"status"]]);for(const s of ZX)n.set(Cc[s],s);const r=new Set;for(const[s]of e.entries()){if(X9t(s))continue;const i=QX(s)?Xps(s):n.get(s);if(!i||r.has(i))continue;r.add(i);const o=J9t(e,s),l=e.getAll(s);if(i==="tags"||nms(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 xms(e){const t=new URLSearchParams,n=e.get(MS);n&&t.set(MS,n);const r=e.get(DS);r&&t.set(DS,r);const s=e.get(p1);s&&t.set(p1,s);const i=l=>{const c=J9t(e,l),u=e.getAll(l).filter(d=>d||tms(c));if(u.length){for(const d of u)t.append(l,d);c&&t.set(PZ(l),c)}};for(const l of ZX){const c=Cc[l];if(l==="tags"){for(const u of e.getAll(c))t.append(c,u);continue}i(c)}const o=new Set;for(const l of e.keys())!QX(l)||X9t(l)||o.has(l)||(o.add(l),i(l));for(const l of EIe(e))t.append(NC,TIe(l));return t}function HXe(e,t,n=[]){e.delete(MS),e.delete(DS),e.delete(NC);for(const r of ZX){const s=Cc[r];e.delete(s),e.delete(PZ(s))}for(const r of Array.from(e.keys()))QX(r)&&e.delete(r);for(const r of t){if(r.fieldId==="rootEntityType"&&typeof r.value=="string"){e.set(MS,r.value);continue}if(r.fieldId==="status"&&typeof r.value=="string"){e.set(DS,r.value);continue}const s=K9t(r.fieldId)?Yps(r.fieldId):Cc[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=WX(r),o=r.fieldId==="tags"?"in":"is";i!==o&&e.set(PZ(s),i)}for(const r of n)e.append(NC,TIe(r))}const NC="filterGroup",TIe=e=>JSON.stringify(e);function EIe(e){return e.getAll(NC).map(bms).filter(t=>t!==void 0)}function bms(e){try{return c7t(JSON.parse(e))}catch{return}}const l7t=e=>typeof e=="object"&&e!==null,wms=e=>Array.isArray(e)&&e.every(t=>typeof t=="string");function c7t(e){if(!l7t(e)||typeof e.id!="string"||e.logic!=="and"&&e.logic!=="or"||!Array.isArray(e.nodes))return;const t=e.nodes.map(Sms).filter(n=>n!==void 0);return{id:e.id,logic:e.logic,nodes:t}}function Sms(e){if(!l7t(e))return;if("nodes"in e)return c7t(e);if(typeof e.id!="string"||typeof e.fieldId!="string"||typeof e.value!="string"&&!wms(e.value))return;const t={id:e.id,fieldId:e.fieldId,value:e.value};return typeof e.operatorId=="string"&&CIe(e.operatorId)&&(t.operatorId=e.operatorId),t}function kms({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}const Oj="timeRange",yve={id:Oj,label:"Time",icon:t7t(Oj),color:n7t(Oj),type:"text",operators:["is"],hidden:!0},$Z={id:Oj,fieldId:Oj,operatorId:"is",value:""},Oms=e=>e instanceof HTMLElement&&e.hasAttribute("data-filter-bar-segment");function jms(e){const t=Qc();return a.jsxs(dx,{item:$Z,removable:!1,children:[a.jsx("span",{className:Z(BX,"text-foreground"),style:fve(yve),children:a.jsx(VX,{field:yve})}),a.jsx("div",{className:"contents",onKeyDown:n=>{Oms(n.target)||n.stopPropagation()},children:a.jsx(YK,{...e,renderTrigger:({label:n,disabled:r})=>a.jsx("button",{type:"button",ref:s=>t.registerSegment($Z.id,"value",s),"data-filter-bar-segment":"",disabled:r,"aria-label":`Value: ${n}`,title:n,className:TI,children:a.jsx("span",{className:"truncate",children:n})})})})]})}function IIe({error:e,resource:t,errorTitle:n}){if(_s(e))return a.jsx(ci,{});if(Ts(e))return a.jsx(Js,{resource:t});const r=e instanceof Error?r2r(e):void 0;return a.jsx(tn,{tone:"error",titleSlot:n,descriptionSlot:r?.error??"Unknown error"})}function Cms(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 WT(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 GXe(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const _ms=(e,t)=>Math.abs(e-t)<1.01,Tms=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}};let oM;const qle=()=>{if(oM!==void 0)return oM;if(typeof navigator>"u")return oM=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return oM=!0;const e=navigator.maxTouchPoints;return oM=navigator.platform==="MacIntel"&&e!==void 0&&e>0},KXe=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Ems=e=>e,Ims=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},Nms=(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(KXe(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(KXe(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},RZ={passive:!0},Ams=typeof window>"u"?!0:"onscrollend"in window,Pms=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const s=e.targetWindow;if(!s)return;const i=e.options.useScrollendEvent&&Ams;let o=0;const l=i?null:Tms(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,RZ),i&&r.addEventListener("scrollend",d,RZ),()=>{r.removeEventListener("scroll",u),i&&r.removeEventListener("scrollend",d)}},$ms=(e,t)=>Pms(e,t,n=>{const{horizontal:r,isRtl:s}=e.options;return r?n.scrollLeft*(s&&-1||1):n.scrollTop}),Rms=(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"]},Mms=(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})},Dms=Mms;class Lms{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:Ems,rangeExtractor:Ims,onChange:()=>{},measureElement:Rms,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=WT(()=>(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,!(!qle()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};i.addEventListener("touchstart",o,RZ),i.addEventListener("touchend",l,RZ),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&&(qle()&&(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=WT(()=>[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=WT(()=>[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=Cms(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=WT(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,i)=>n.length===0||r===0?(this.range=null,null):(this.range=Fms(n,r,s,i,i===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=WT(()=>{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=WT(()=>[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=u7t(0,r.length-1,i?l=>s[l*2]:l=>GXe(r[l]).start,n);return GXe(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&&(qle()&&(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&&_ms(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 u7t=(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 zms(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 Fms(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=zms(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=u7t(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 Qle=typeof document<"u"?g.useLayoutEffect:g.useEffect;function Bms({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?bo.flushSync(s):s()),(f=r.onChange)==null||f.call(r,u,d)}},[c]=g.useState(()=>{const u=new Lms(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),Qle(()=>c._didMount(),[]),Qle(()=>c._willUpdate()),Qle(()=>{o(c)}),c}function d7t(e){return Bms({observeElementRect:Nms,observeElementOffset:$ms,scrollToFn:Dms,...e})}function MZ(e,t){const n=vS(e)?.getTime(),r=vS(t)?.getTime();if(!(n===void 0||r===void 0||r<n))return r-n}function Vms(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 Ums(e){return e?.attributes?.finishReason==="length"}function qms(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.
|
|
672
672
|
|
|
673
673
|
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 Qms=new Intl.NumberFormat("en-US",{notation:"compact",maximumSignificantDigits:3}),Zms=new Intl.NumberFormat("en-US"),Wms=new Set(Intl.supportedValuesOf("currency"));function f7t(e){return e!==void 0&&Wms.has(e.toUpperCase())}function xve(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:e,...t})}function rd(e,{currency:t}={}){if(!f7t(t))return Qms.format(e);const n=Math.abs(e);return n<100?M_(e,{currency:t}):n<1e3?xve(t,{maximumFractionDigits:0}).format(e):xve(t,{notation:"compact",maximumSignificantDigits:3}).format(e)}function M_(e,{currency:t}={}){if(!f7t(t))return Zms.format(e);const n=xve(t,{}),r=10**-(n.resolvedOptions().maximumFractionDigits??2);return e!==0&&Math.abs(e)<r?`${e<0?"-":""}<${n.format(r)}`:n.format(e)}function Om(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 Hms=36,Gms=8,Kms=20;function Yms(e,t){return e[t]}function Xms(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>=Kms)break}return[...n]}function Jms(e){if(!(e?.inputTokens===void 0&&e?.outputTokens===void 0))return(e?.inputTokens??0)+(e?.outputTokens??0)}function egs({traces:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,filtersApplied:i,featuredTraceId:o,featuredSpanId:l,isBranchesMode:c,recentlyAddedKeys:u,columnPreferences:d=zb,usageByTraceId:f,onTraceClick:h,createdSort:p,onSortChange:m,onFilterByField:v}){const y=g.useRef(null),x=V9t(d),b=d7t({count:e.length,getScrollElement:()=>y.current,estimateSize:()=>Hms,overscan:Gms}),{getRowProps:S}=Ru({count:e.length,containerRef:y,onNavigate:_=>b.scrollToIndex(_),global:!0}),k=b.getVirtualItems(),j=b.getTotalSize(),C=k[0]?.start??0,T=k.length>0?Math.max(0,j-(k[k.length-1]?.end??0)):0;return a.jsxs(Gi,{columns:x,fit:"container",scrollRef:y,className:"min-w-0",children:[a.jsxs(Gi.Top,{children:[m?a.jsx(Gi.SortableTopCell,{sortKey:"startedAt",sort:p,onSortChange:m,children:"Start"}):a.jsx(Gi.TopCell,{children:"Start"}),kc(d,"type")&&a.jsx(Gi.TopCell,{children:"Primitive type"}),a.jsx(Gi.TopCell,{children:"Primitive name"}),kc(d,"input")&&a.jsx(Gi.TopCell,{children:"Input"}),a.jsx(Gi.TopCell,{children:"Status"}),kc(d,"duration")&&a.jsx(Gi.TopCell,{className:"justify-end text-right",children:"Duration"}),kc(d,"endTime")&&a.jsx(Gi.TopCell,{children:"End"}),kc(d,"environment")&&a.jsx(Gi.TopCell,{children:"Environment"}),kc(d,"inputTokens")&&a.jsx(Gi.TopCell,{className:"justify-end text-right",children:"Input tokens"}),kc(d,"outputTokens")&&a.jsx(Gi.TopCell,{className:"justify-end text-right",children:"Output tokens"}),kc(d,"totalTokens")&&a.jsx(Gi.TopCell,{className:"justify-end text-right",children:"Total tokens"}),kc(d,"estimatedCost")&&a.jsx(Gi.TopCell,{className:"justify-end text-right",children:"Est. cost"}),d.customColumns.map(_=>{const N=F9t[_],I=v?Xms(e,_):[];return!v||I.length===0?a.jsx(Gi.TopCell,{children:N},_):a.jsx(Gi.TopCell,{className:"overflow-visible",children:a.jsxs(ut,{children:[a.jsx(ut.Trigger,{render:a.jsxs("button",{type:"button",className:Z("flex min-w-0 items-center gap-1 rounded-sm hover:text-foreground",$i),children:[a.jsx("span",{className:"min-w-0 truncate",children:N}),a.jsx(kdt,{"aria-hidden":!0,className:"size-[1.2em] shrink-0"})]})}),a.jsxs(ut.Content,{align:"start",children:[a.jsx(ut.Label,{children:"Filter by value"}),I.map(P=>a.jsx(ut.Item,{onSelect:()=>v(_,P),children:a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",className:"min-w-0 truncate",children:P})},P))]})]})},_)}),d.metadataKeys.map(_=>a.jsx(Gi.TopCellWithTooltip,{tooltip:_,children:_},_))]}),t?a.jsx(WEt,{columnCount:REt(x).length}):e.length===0?a.jsx(Gi.NoMatch,{message:i?"No traces found for applied filters":"No traces found yet"}):a.jsxs(a.Fragment,{children:[a.jsx(Gi.Spacer,{height:C}),k.map(_=>{const N=e[_.index];if(!N)return null;const I=N.traceId===o&&(l==null||N.spanId===l),P=`${N.traceId}:${N.spanId??""}`,A=u?.has(P)??!1,D=N.startedAt??N.createdAt,z=f?.get(N.traceId);return a.jsxs(Gi.RowButton,{ref:b.measureElement,"data-index":_.index,...S(_.index),onClick:()=>h(N),featured:I,className:Z(A&&"animate-row-highlight"),children:[a.jsx(Gi.CreatedCell,{timestamp:D,preset:"day-time-seconds"}),kc(d,"type")&&a.jsx(Gi.TypeCell,{entityType:N.entityType}),a.jsx(Gi.NameCell,{name:N.entityName||N.name,parentSpanId:N.parentSpanId,showLevelTooltip:c}),kc(d,"input")&&a.jsx(Gi.InputCell,{input:N.inputPreview??Vms(N.input)}),a.jsx(Gi.StatusCell,{status:N.status}),kc(d,"duration")&&a.jsx(ke.NumberCell,{font:"mono",children:nf(MZ(N.startedAt,N.endedAt))}),kc(d,"endTime")&&a.jsx(Gi.CreatedCell,{timestamp:N.endedAt??"",preset:"day-time-seconds"}),kc(d,"environment")&&a.jsx(ke.TextCell,{children:N.environment||"—"}),kc(d,"inputTokens")&&a.jsx(ke.NumberCell,{children:z?.inputTokens===void 0?void 0:rd(z.inputTokens)}),kc(d,"outputTokens")&&a.jsx(ke.NumberCell,{children:z?.outputTokens===void 0?void 0:rd(z.outputTokens)}),kc(d,"totalTokens")&&a.jsx(ke.NumberCell,{children:(()=>{const Q=Jms(z);return Q===void 0?void 0:rd(Q)})()}),kc(d,"estimatedCost")&&a.jsx(ke.NumberCell,{children:z?.estimatedCost===void 0?void 0:Om(z.estimatedCost,z.costUnit)}),d.customColumns.map(Q=>a.jsx(ke.TextCell,{font:"mono",children:Yms(N,Q)??void 0},Q)),d.metadataKeys.map(Q=>{const q=Mps(N.metadata,Q);return a.jsx(ke.TextCell,{font:"mono",children:q},Q)})]},P)}),a.jsx(Gi.Spacer,{height:T}),a.jsx(Gi.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})]})}function tgs({columnPreferences:e=zb}){const t=V9t(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(Au,{columns:t,fit:"container"})]})}function Zle(e){if(typeof window>"u")return zb;try{return Aps(window.localStorage.getItem(e)??void 0)}catch{return zb}}function ngs(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,Pps(t))}catch{}}function rgs(){const e=nps(),[t,n]=g.useState(()=>({storageKey:e,preferences:Zle(e),shouldPersist:!1})),r=t.storageKey===e?t.preferences:Zle(e);g.useEffect(()=>{t.storageKey===e&&t.shouldPersist&&ngs(e,t.preferences)},[t,e]);const s=f=>{n(h=>{const p=h.storageKey===e?h.preferences:Zle(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(()=>zb)}}function sgs(e,t,n){const{storageKey:r,skipHydration:s}=n??{},i=g.useRef(!1);return g.useEffect(()=>{if(s||i.current||(i.current=!0,ams(e)))return;const o=oms(r);o&&t(l=>{const c=new URLSearchParams(l);for(const[u,d]of o)c.append(u,d);return c},{replace:!0})},[]),g.useCallback((o,l)=>{t(c=>{const u=typeof o=="function"?o(c):o;return sms(u,r),u},l)},[t,r])}function igs(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 RB="traceId",mb="spanId",iy="tab",Wle="spanView",oy="scoreId",d2="highlightSpanIds",aM=1440*60*1e3,ogs={"last-24h":aM,"last-3d":3*aM,"last-7d":7*aM,"last-14d":14*aM,"last-30d":30*aM};function HT(e){e.delete(RB),e.delete(mb),e.delete($B),e.delete(iy),e.delete(oy),e.delete(d2)}function ags(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const F=e.get(m1);return F&&F!=="all"&&ems.has(F)?F:"last-7d"},[e]),i=e.get(Hw),o=e.get(Gw),l=g.useMemo(()=>{if(s==="custom"){if(!i)return;const U=new Date(i);return Number.isNaN(U.getTime())?void 0:U}const F=ogs[s];return F?new Date(Date.now()-F):void 0},[s,i]),c=g.useMemo(()=>{if(s!=="custom"||!o)return;const F=new Date(o);return Number.isNaN(F.getTime())?void 0:F},[s,o]),u=g.useRef(s);u.current=s;const d=e.get(RB)||void 0,f=e.get(mb)||void 0,h=e.get($B)||void 0,p=e.get(iy),m=p==="feedback"?"feedback":p==="details"?"details":void 0,v=e.get(Wle)==="timeline"?"timeline":"tree",y=e.get(oy)||void 0,x=e.get(d2),b=g.useMemo(()=>x?x.split(",").filter(Boolean):[],[x]),S=g.useMemo(()=>{const F=e.get(p1);return F&&Jps.has(F)?F:"traces"},[e]),k=g.useMemo(()=>G9t.find(F=>F.entityType===e.get(MS)),[e]),j=g.useMemo(()=>{const F=e.get(DS);return F&&rms.has(F)?F:void 0},[e]),C=g.useMemo(()=>yms(e),[e]),T=g.useMemo(()=>EIe(e),[e]),_=g.useCallback((F,U,K)=>{t(ne=>{const X=new URLSearchParams(ne);return F?X.set(RB,F):X.delete(RB),U?X.set(mb,U):X.delete(mb),K?X.set($B,K):X.delete($B),X.delete(iy),X.delete(oy),X.delete(d2),X},{replace:!0})},[t]),N=g.useCallback(()=>_(""),[_]),I=g.useCallback(F=>{const U=e.get(mb)||null;F!==U&&t(K=>{const ne=new URLSearchParams(K);return F?ne.set(mb,F):ne.delete(mb),ne.delete(iy),ne.delete(oy),ne},{replace:!0})},[e,t]),P=g.useCallback(()=>I(null),[I]),A=g.useCallback(F=>{t(U=>{const K=new URLSearchParams(U);return F==="timeline"?K.set(Wle,F):K.delete(Wle),K},{replace:!0})},[t]),D=g.useCallback(F=>{const U=e.get(iy)||null;F!==U&&t(K=>{const ne=new URLSearchParams(K);return F&&F!=="details"?ne.set(iy,F):ne.delete(iy),ne.delete(oy),ne},{replace:!0})},[e,t]),z=g.useCallback((F,U)=>{const K=U&&U!=="details"?U:null;F===(e.get(mb)||null)&&K===(e.get(iy)||null)&&!e.get(oy)||t(X=>{const te=new URLSearchParams(X);return te.set(mb,F),K?te.set(iy,K):te.delete(iy),te.delete(oy),te},{replace:!0})},[e,t]),Q=g.useCallback(F=>{const U=e.get(oy)||null;F!==U&&t(K=>{const ne=new URLSearchParams(K);return F?ne.set(oy,F):ne.delete(oy),ne},{replace:!0})},[e,t]),q=g.useCallback(F=>{t(U=>{const K=new URLSearchParams(U);return F.length===0?K.delete(d2):K.set(d2,F.join(",")),K},{replace:!0})},[t]),B=g.useCallback((F,U=[])=>{t(K=>{const ne=new URLSearchParams(K);return HXe(ne,F,U),HT(ne),ne},{replace:!0})},[t]),V=B,H=g.useCallback((F,U)=>{if(u.current!=="custom")return;const K=U==="from"?Hw:Gw;t(ne=>{const X=new URLSearchParams(ne);return F?X.set(K,F.toISOString()):X.delete(K),HT(X),X},{replace:!0})},[t]),M=g.useCallback((F,U)=>{u.current==="custom"&&t(K=>{const ne=new URLSearchParams(K);return F?ne.set(Hw,F.toISOString()):ne.delete(Hw),U?ne.set(Gw,U.toISOString()):ne.delete(Gw),HT(ne),ne},{replace:!0})},[t]),G=g.useCallback(F=>{u.current=F,t(U=>{const K=new URLSearchParams(U);return F==="last-7d"?(K.delete(m1),K.delete(Hw),K.delete(Gw)):F==="custom"?K.set(m1,"custom"):(K.set(m1,F),K.delete(Hw),K.delete(Gw)),HT(K),K},{replace:!0})},[t]),L=g.useCallback(F=>{t(U=>{const K=new URLSearchParams(U);return F==="traces"?K.delete(p1):K.set(p1,F),HT(K),K},{replace:!0})},[t]),$=g.useCallback(()=>{t(F=>{const U=new URLSearchParams(F);return U.delete(p1),HXe(U,[]),HT(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:I,handleSpanClose:P,handleSpanTabChange:D,handleSpanViewChange:A,handleSpanChangeWithTab:z,handleScoreChange:Q,handleHighlightSpans:q,handleListModeChange:L,handleFilterTokensChange:V,handleDateChange:H,handleDateRangeChange:M,handleDatePresetChange:G,handleRemoveAll:$,applyFilterTokens:B}}function lgs(e){return e.map(t=>({traceId:t.traceId,spanId:t.rootSpanId,parentSpanId:t.parentSpanId,name:Rps(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}))}function h7t({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=Zhs({queryOptions:{traceQuery:{refetchInterval:d&&!n?1e4:!1,refetchOnWindowFocus:d},legacy:{refetchInterval:d&&!n?1e4:!1,refetchOnWindowFocus:d}},query:t?{...e(c),orderBy:t}:e(c),withQueryTrace:s,legacyFilters:i,limit:o,enabled:l});return g.useEffect(()=>{if(!d||!n||h.error)return;const p=setInterval(()=>u(new Date),1e4);return()=>clearInterval(p)},[d,n,h.error]),{...h,rows:lgs(h.data??[]),autoRefetch:d,setAutoRefetch:f}}const bve="sort",wve="dir",cgs="page";function ugs(e,t,n){const r=e.get(bve);if(!r||!t.includes(r))return n;const i=e.get(wve)==="desc"?"desc":"asc";return{key:r,direction:i}}function wk({searchParams:e,setSearchParams:t,allowedKeys:n,defaultSort:r}){const s=e.get(bve),i=e.get(wve),o=g.useMemo(()=>ugs(e,n,r),[s,i,n,r]),l=g.useCallback((c,u)=>{t(d=>{const f=new URLSearchParams(d);return f.set(bve,u),f.set(wve,c),f.delete(cgs),f},{replace:!0})},[t]);return{sort:o,onSortChange:l}}const dgs=new Set(["ObservabilityStorageClickhouseVNext","ObservabilityStorageDuckDB","ObservabilityInMemory","ObservabilitySpanner","ObservabilityStoragePostgresVNext"]),V6=()=>{const{isMastraPlatform:e}=F6(),{data:t,isLoading:n,error:r}=yIe(),s=t?.observabilityStorageType,i=t?.capabilities?.metrics??(s?dgs.has(s):!1);return{supportsMetrics:e||i,isInMemory:!e&&s==="ObservabilityInMemory",isLoading:!e&&n,error:e?void 0:r}};function Ws({value:e,className:t}){return a.jsx(bl,{code:JSON.stringify(e??null,null,2),lang:"json","data-slot":"span-payload-json",className:Z(hr,"rounded-lg p-3 text-wrap break-all text-muted-foreground",t,"text-caption")})}function NIe({value:e}){if(typeof e!="object"||e===null||Array.isArray(e))return a.jsx(Ws,{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(Ws,{value:e});try{const i=new URL(n);if(i.username||i.password)return a.jsx(Ws,{value:e})}catch{return a.jsx(Ws,{value:e})}const s=typeof t.filename=="string"?t.filename:typeof t.name=="string"?t.name:void 0;return a.jsx(SI,{type:t.type==="image"||typeof r=="string"&&r.startsWith("image/")?"image":"file",contentType:typeof r=="string"?r:void 0,src:n,name:s})}const YXe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function p7t({value:e,showLabel:t=!0}){if(!YXe(e))return a.jsx(Ws,{value:e});const n=e.type==="tool-invocation"?e.toolInvocation:e;if(!YXe(n)||typeof n.toolName!="string"||!n.toolName)return a.jsx(Ws,{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}=y_(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(lD,{children:e.type==="tool-result"?"Tool result":"Tool call"}),a.jsx(GCe,{status:i?"error":"idle",header:a.jsx(aY,{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(tp,{label:"Arguments",children:a.jsx(Ws,{value:r})}),s!==void 0&&a.jsx(tp,{label:"Result",children:a.jsx(Ws,{value:s})}),o!==void 0&&a.jsx(tp,{label:"Error",children:a.jsx(Ws,{value:o})})]})})]})}function lD({children:e}){return a.jsx(Y,{as:"span",variant:"meta",tone:"faint",className:"block uppercase",children:e})}function tp({label:e,children:t}){return a.jsxs("div",{"data-slot":"span-payload-field",className:"flex flex-col gap-1.5",children:[a.jsx(lD,{children:e}),t]})}function LS({children:e}){return a.jsx("div",{"data-slot":"span-payload-markdown",className:"text-foreground",children:a.jsx(Fc,{children:e})})}function pm({label:e,children:t,defaultOpen:n=!1}){return a.jsxs(Wl,{defaultOpen:n,children:[a.jsxs(wl,{className:"flex items-center gap-1 text-meta text-placeholder uppercase [&>svg]:size-3",children:[a.jsx(Gs,{}),e]}),a.jsx(Sl,{className:"pt-1.5",children:t})]})}function AIe({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(p7t,{value:t,showLabel:!1})},n))})}const DZ=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function fgs(e){const t=e.split(`
|
|
@@ -691,7 +691,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
|
|
|
691
691
|
]`,Xxs=[{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 Jxs(){const{isCopied:e,handleCopy:t}=Mm({text:SJe,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:Xxs.map(n=>a.jsxs("div",{className:"grid grid-cols-[7rem_1fr] gap-3 px-3 py-2.5",children:[a.jsx("dt",{className:$l({tone:"ink",variant:"meta"}),children:a.jsx(dp,{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(Ft,{variant:"success",size:"xs",children:"required"}):a.jsx(Ft,{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(de,{icon:e?a.jsx(pr,{}):a.jsx($m,{}),variant:"ghost",size:"sm",onClick:t,children:e?"Copied":"Copy"})]}),a.jsx(Cr,{variant:"embedded",language:"json",editable:!1,lineNumbers:!1,showCopyButton:!1,value:SJe,className:"p-3"})]}),a.jsx(de,{variant:"ghost",render:a.jsx("a",{href:Yxs,target:"_blank",rel:"noopener noreferrer"}),className:"self-start",icon:a.jsx(Vs,{}),children:"Datasets documentation"})]})}const nce=10,ebs=`[
|
|
692
692
|
{ "input": "…", "groundTruth": "…" }
|
|
693
693
|
]`,kJe="flex min-h-0 flex-1 flex-col py-0";function tbs({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:s,pastedText:i,onPastedTextChange:o,validation:l,isImporting:c}){return a.jsxs(Hl,{value:e,defaultTab:"upload",onValueChange:t,className:"flex h-full flex-col gap-3",children:[a.jsxs(Gl,{variant:"pill",children:[a.jsx(ls,{value:"upload",children:"Upload file"}),a.jsx(ls,{value:"paste",children:"Paste JSON"})]}),a.jsx(Ls,{value:"upload",className:kJe,children:n?a.jsx(ibs,{file:n,validation:l,onReplace:s,isImporting:c}):a.jsx(nbs,{onFileSelect:r,disabled:c})}),a.jsx(Ls,{value:"paste",className:kJe,children:a.jsx(Cr,{"aria-label":"JSON items",language:"json",lineNumbers:!1,showCopyButton:!1,placeholder:ebs,value:i,onChange:o,editable:!c,className:"min-h-50 flex-1"})})]})}function nbs({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(fH,{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 ",FIe]})]})}function rbs(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function sbs(e){return typeof e=="string"?e:JSON.stringify(e)??""}function ibs({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,nce);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(sH,{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:rbs(e.size)}),a.jsx(de,{icon:a.jsx(tx,{}),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:sbs(l.input)}),l.hasInput?l.hasGroundTruth?null:a.jsx(Ft,{variant:"warning",size:"xs",children:"no groundTruth"}):a.jsx(Ft,{variant:"destructive",size:"xs",children:"no input"})]},l.index)),i>nce&&a.jsxs(Y,{as:"p",variant:"meta",tone:"muted",className:"border-t border-border px-3 py-1.5",children:["+ ",i-nce," more"]})]})}const obs=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function abs({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}=ul(),S=i==="upload"?u:p,k=g.useMemo(()=>i==="upload"&&f?{status:"error",kind:"parse",message:f}:axs(S),[i,f,S]),j=g.useCallback(async I=>{const P=++x.current;if(!I.name.toLowerCase().endsWith(".json")){h("Only .json files are supported");return}if(I.size>W7t){h(`File is larger than ${FIe}`);return}try{const A=await obs(I);if(P!==x.current)return;c({name:I.name,size:I.size}),d(A),h(null)}catch{if(P!==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}),Ge.success(`Imported ${k.total} item${k.total!==1?"s":""}`),s?.(),r(!1),setTimeout(T,150)}catch(I){Ge.error(I instanceof Error?I.message:"Failed to import items")}finally{y(!1)}}},[k,b,e,s,r,T]);return a.jsx(rs,{open:n,onOpenChange:_,pending:v,children:a.jsxs(ss,{size:"xl",children:[a.jsxs(es,{children:[a.jsx(Kr,{children:"Import into dataset"}),a.jsxs(Mo,{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(Gr,{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(tbs,{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(Jxs,{})})]})}),a.jsxs(Ho,{children:[a.jsx(lbs,{validation:k}),a.jsx(ja,{children:"Cancel"}),a.jsxs(Oa,{onConfirm:N,disabled:k.status!=="ready",children:[v&&a.jsx(An,{}),k.status==="ready"?`Import ${k.total} item${k.total!==1?"s":""}`:"Import"]})]})]})})}function lbs({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 ${FIe}`;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(dp,{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 cbs(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 J7t({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=i=>{i.defaultPrevented||cbs(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 eBt=g.createContext(null);function ubs({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=Lr(),o=Dxe("/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]);J7t({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(eBt.Provider,{value:h,children:r})}function tBt(){const e=g.useContext(eBt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}const dbs=["createdAt"];function fbs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s,belowToolbarSlot:i}){const[o,l]=pi(),{activeVersion:c}=BIe(o,l),{sort:u,onSortChange:d}=wk({searchParams:o,setSearchParams:l,allowedKeys:dbs}),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),[I,P]=g.useState([]),[A,D]=g.useState(0),[z,Q]=g.useState(""),[q]=UK(z,300),{data:B}=Tv({datasetId:e,queryOptions:{enabled:!!e}}),{data:V=[],isLoading:H,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:L}=_N({datasetId:e,search:q||void 0,version:c,orderBy:f,queryOptions:{enabled:!!e}}),{deleteItems:$}=ul(),{currentItemId:F,openItem:U,close:K}=tBt(),ne=ae=>{F===ae?K():U(ae)},X=ae=>{S(ae),x(!0)},te=ae=>{T(ae),j(!0)},oe=ae=>{j(ae),ae||(T([]),D(pe=>pe+1))},ue=ae=>{P(ae),N(!0)},ee=async()=>{await $.mutateAsync({datasetId:e,itemIds:I}),Ge.success(`Deleted ${I.length} items`),N(!1),P([]),D(ae=>ae+1)},se=ae=>{x(!1),S([]),D(pe=>pe+1),n?.(ae)},re=ae=>{x(ae),ae||(S([]),D(pe=>pe+1))};return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid h-full overflow-auto",children:a.jsx(Kxs,{items:V,leftSlot:r,rightSlot:s,belowToolbarSlot:i,isLoading:H,onItemClick:ne,featuredItemId:F,onAddClick:t??(()=>{}),onImportClick:()=>p(!0),onImportJsonClick:()=>v(!0),onBulkDeleteClick:ue,onCreateDatasetClick:X,onAddToDatasetClick:te,datasetName:B?.name,clearSelectionTrigger:A,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:L,searchQuery:z,activeSearchQuery:q,onSearchChange:Q,sort:u,onSortChange:d,currentDatasetVersion:B?.version})}),a.jsx(Uxs,{datasetId:e,open:h,onOpenChange:p}),a.jsx(abs,{datasetId:e,datasetName:B?.name,open:m,onOpenChange:v}),a.jsx(Oxs,{open:y,onOpenChange:re,items:b,onSuccess:se}),a.jsx(jxs,{open:k,onOpenChange:oe,items:C,currentDatasetId:e}),a.jsx(Ut,{open:_,onOpenChange:N,children:a.jsxs(Ut.Content,{children:[a.jsxs(Ut.Header,{children:[a.jsx(Ut.Title,{children:"Delete Items"}),a.jsxs(Ut.Description,{children:["Are you sure you want to delete ",I.length," item",I.length!==1?"s":"","? This action cannot be undone."]})]}),a.jsxs(Ut.Footer,{children:[a.jsx(Ut.Cancel,{children:"Cancel"}),a.jsx(Ut.Action,{onClick:ee,children:$.isPending?"Deleting...":"Delete"})]})]})})]})}const OJe="__create_tag__";function hbs({datasetId:e}){const{data:t}=Tv({datasetId:e,queryOptions:{enabled:!!e}}),{data:n}=ik(),{updateDataset:r}=ul(),[s,i]=g.useState(""),o=g.useMemo(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),l=g.useMemo(()=>B7t(n?.datasets??[]),[n?.datasets]),c=g.useMemo(()=>{const h=l.map(v=>({label:v,value:v,end:o.includes(v)?a.jsx(pr,{"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:OJe},...h]:h},[l,o,s]),u=h=>{r.mutate({datasetId:e,tags:h},{onError:()=>Ge.error("Failed to update tags")})},d=h=>{const p=h===OJe?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(GX,{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(Ln,{className:"size-3"})})]},h)),a.jsx(Ca,{options:c,value:void 0,onValueChange:d,onInputValueChange:i,placeholder:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(HS,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:"ghost",size:"sm",className:"w-auto min-w-0",disabled:r.isPending})]})}function nBt({overrideEnabled:e,onOverrideEnabledChange:t,selectedScorerIds:n,onSelectedScorerIdsChange:r,disabled:s=!1}){return a.jsxs("div",{className:"grid gap-3",children:[a.jsxs(ft,{orientation:"horizontal",disabled:s,className:"gap-3",children:[a.jsx(fc,{checked:e,onCheckedChange:t}),a.jsx(lt,{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(YX,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function EI({field:e,errors:t}){return t.length===0?null:a.jsx(cs,{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 pbs(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 mbs({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}=ul(),j=()=>{i("{}"),l(""),u(""),f(""),p(!1),v([]),x(""),S(null)},C=A=>{j(),n(A)},T=async A=>{A.preventDefault();let D;try{D=JSON.parse(s)}catch{Ge.error("Input must be valid JSON");return}let z;if(o.trim())try{z=JSON.parse(o)}catch{Ge.error("Ground Truth must be valid JSON");return}let Q;if(c.trim())try{Q=JSON.parse(c)}catch{Ge.error("Expected Trajectory must be valid JSON");return}let q;if(d.trim())try{const V=JSON.parse(d);if(!Array.isArray(V)){Ge.error("Tool Mocks must be a JSON array");return}q=V}catch{Ge.error("Tool Mocks must be valid JSON");return}let B;if(y.trim())try{B=JSON.parse(y)}catch{Ge.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:D,groundTruth:z,expectedTrajectory:Q,toolMocks:q,scorerIds:h?m:void 0,requestContext:B}),Ge.success("Item added successfully"),C(!1),r?.()}catch(V){const H=pbs(V);H?S(H):Ge.error(`Failed to add item: ${V instanceof Error?V.message:"Unknown error"}`)}},_=A=>{i(A),b?.field==="input"&&S(null)},N=A=>{l(A),b?.field==="groundTruth"&&S(null)},I=A=>{f(A),b?.field==="toolMocks"&&S(null)},P=()=>{C(!1)};return a.jsxs(yo,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:P,level:1,children:[a.jsx(yo.Top,{children:"Add Item"}),a.jsxs(yo.Content,{children:[a.jsx(yo.Header,{children:a.jsx(yo.Heading,{children:"Add Item"})}),a.jsxs(Qa,{onSubmit:T,children:[a.jsxs(ft,{invalid:b?.field==="input",children:[a.jsx(lt,{required:!0,children:"Input (JSON)"}),a.jsx(Cr,{value:s,onChange:_,showCopyButton:!1,className:"min-h-[240px]"}),b?.field==="input"&&a.jsx(EI,{field:"input",errors:b.errors})]}),a.jsxs(ft,{invalid:b?.field==="groundTruth",children:[a.jsx(lt,{children:"Ground Truth (JSON, optional)"}),a.jsx(Cr,{value:o,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),b?.field==="groundTruth"&&a.jsx(EI,{field:"groundTruth",errors:b.errors})]}),a.jsxs(ft,{children:[a.jsx(lt,{children:"Expected Trajectory (JSON, optional)"}),a.jsx(Cr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),a.jsxs(ft,{invalid:b?.field==="toolMocks",children:[a.jsx(lt,{children:"Tool Mocks (JSON array, optional)"}),a.jsx(Cr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),b?.field==="toolMocks"&&a.jsx(EI,{field:"toolMocks",errors:b.errors})]}),a.jsx(nBt,{overrideEnabled:h,onOverrideEnabledChange:p,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),a.jsxs(ft,{children:[a.jsx(lt,{children:"Request Context (JSON, optional)"}),a.jsx(Cr,{value:y,onChange:x,showCopyButton:!1,className:"min-h-[200px]"})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[a.jsx(de,{icon:a.jsx(Ln,{}),type:"button",onClick:P,children:"Cancel"}),a.jsx(de,{icon:a.jsx(bs,{}),type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}const fO=e=>JSON.stringify(e??null,null,2),gbs=[{key:"input",title:"Input",icon:a.jsx(KD,{}),value:e=>fO(e.input)},{key:"groundTruth",title:"Ground Truth",icon:a.jsx(j1,{}),value:e=>fO(e.groundTruth)},{key:"expectedTrajectory",title:"Expected Trajectory",icon:a.jsx(Kbe,{}),value:e=>e.expectedTrajectory!=null?fO(e.expectedTrajectory):void 0},{key:"toolMocks",title:"Tool Mocks",icon:a.jsx(ad,{}),value:e=>fO(e.toolMocks??[])},{key:"scorerIds",title:"Scorers",icon:a.jsx(Sdt,{}),value:e=>e.scorerIds===void 0?"Inherited from dataset":fO(e.scorerIds)},{key:"requestContext",title:"Request Context",icon:a.jsx(al,{}),value:e=>e.requestContext!=null?fO(e.requestContext):void 0},{key:"metadata",title:"Metadata",icon:a.jsx(HS,{}),value:e=>fO(e.metadata)}];function _ve({item:e,diff:t}){return a.jsxs(a.Fragment,{children:[a.jsxs(Lt,{children:[a.jsx(Lt.Key,{children:"Dataset Id"}),a.jsx(Lt.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:e.datasetId,children:e.datasetId}),a.jsx(Lt.Key,{children:"Version"}),a.jsxs(Lt.Value,{children:["v",e.datasetVersion]}),a.jsx(Lt.Key,{children:"Created"}),a.jsx(Lt.Value,{children:is(e.createdAt,"date-time")}),a.jsx(Lt.Key,{children:"Updated"}),a.jsx(Lt.Value,{children:e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime()?is(e.updatedAt,"date-time"):"n/a"})]}),a.jsx("div",{className:"mt-3 grid gap-3",children:gbs.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 vbs({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(od,{className:"h-5 w-5"})," Edit Item"]})}),a.jsxs("div",{className:"space-y-6",children:[a.jsxs(ft,{invalid:y?.field==="input",children:[a.jsx(lt,{required:!0,children:"Input (JSON)"}),a.jsx(Cr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&a.jsx(EI,{field:"input",errors:y.errors})]}),a.jsxs(ft,{invalid:y?.field==="groundTruth",children:[a.jsx(lt,{children:"Ground Truth (JSON, optional)"}),a.jsx(Cr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&a.jsx(EI,{field:"groundTruth",errors:y.errors})]}),a.jsxs(ft,{children:[a.jsx(lt,{children:"Expected Trajectory (JSON, optional)"}),a.jsx(Cr,{value:o,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs(ft,{invalid:y?.field==="toolMocks",children:[a.jsx(lt,{children:"Tool Mocks (JSON array, optional)"}),a.jsxs(eo,{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(Cr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&a.jsx(EI,{field:"toolMocks",errors:y.errors})]}),a.jsx(nBt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:h,onSelectedScorerIdsChange:p,disabled:S}),a.jsxs(ft,{children:[a.jsx(lt,{children:"Request Context (JSON, optional)"}),a.jsx(Cr,{value:m,onChange:v,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs(ft,{children:[a.jsx(lt,{children:"Metadata (JSON, optional)"}),a.jsx(Cr,{value:s,onChange:i,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs("div",{className:"flex gap-2 pt-4",children:[a.jsx(de,{icon:a.jsx(pr,{}),variant:"primary",onClick:x,disabled:S,children:S?"Saving...":"Save Changes"}),a.jsx(de,{icon:a.jsx(Ln,{}),onClick:b,disabled:S,children:"Cancel"})]})]})]})}const ybs=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function xbs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:i,isLoading:o}=pf(),{data:l,isLoading:c}=vp({}),{data:u,isLoading:d}=eg(),f=e==="agent"?Object.entries(i??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(l??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):[],h=e==="agent"&&o||e==="workflow"&&c||e==="scorer"&&d,p=v=>{t(v),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs(ft,{children:[a.jsx(lt,{children:"Target Type"}),a.jsx(Ca,{options:ybs,value:e,onValueChange:p,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&a.jsxs(ft,{children:[a.jsx(lt,{children:m}),a.jsx(Ca,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:h,container:s})]})]})}const bbs=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function wbs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return ix(e)}catch(r){return console.error("Failed to parse requestContextSchema:",r),null}},[e]);return n?a.jsxs(a0,{children:[a.jsx(l0,{children:"Request Context"}),a.jsx(q1e,{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 rce({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 XX({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),[f,h]=g.useState(i??""),[p,m]=g.useState(o??""),[v,y]=g.useState(e??""),[x,b]=g.useState(t??null),[S,k]=g.useState(r??""),[j,C]=g.useState(s??""),[T,_]=g.useState(n??null),[N,I]=g.useState({}),[P,A]=g.useState(""),{triggerExperiment:D}=ul(),{data:z}=Tv({datasetId:v,queryOptions:{enabled:!!v}}),{total:Q}=_N({datasetId:v,search:void 0,version:x,queryOptions:{enabled:!!v}}),q=z?.requestContextSchema,B=z?.scorerIds??[],V=T===null&&B.length>0,H=T??B,M=!!(q&&Object.keys(q).length>0),G=!!(v&&S&&j&&f.trim()),L=D.isPending,$=[!f.trim()&&"name",!v&&"dataset",!j&&"target"].filter(Boolean),F=M?Object.values(N).some(ue=>ue!==void 0&&ue!==""):P.trim().length>0,U=ue=>{y(ue),b(null),_(n??null),I({})},K=()=>{h(i??""),m(o??""),y(e??""),b(t??null),k(r??""),C(s??""),_(n??null),I({}),A("")},ne=()=>{if(M){const ue=Object.entries(N).filter(([,ee])=>ee!==void 0&&ee!=="");return ue.length>0?Object.fromEntries(ue):void 0}if(P.trim()){let ue;try{ue=JSON.parse(P)}catch{throw new Error("Request Context must be valid JSON")}if(!ue||typeof ue!="object"||Array.isArray(ue))throw new Error("Request Context must be a JSON object");return ue}},X=async()=>{if(!v||!S||!j||!f.trim())return;let ue;try{ue=ne()}catch(ee){const se=ee instanceof Error?ee.message:"Request Context must be valid JSON";hu.error(se);return}try{const ee=await D.mutateAsync({datasetId:v,name:f.trim(),description:p.trim()||void 0,targetType:S,targetId:j,scorerIds:H.length>0?H:void 0,version:x??void 0,requestContext:ue});hu.success("Experiment triggered successfully"),c(!1),u?.(ee.experimentId),K()}catch(ee){const se=ee instanceof Error?ee.message:"Failed to trigger experiment";hu.error(se)}},te=()=>{c(!1),K()},oe=ue=>{(ue.metaKey||ue.ctrlKey)&&ue.key==="Enter"&&G&&!L&&(ue.preventDefault(),X())};return a.jsx(rs,{open:l,onOpenChange:te,pending:L,children:a.jsxs(ss,{ref:d,size:"lg",onKeyDown:oe,children:[a.jsxs(es,{children:[a.jsx(Kr,{children:"Run experiment"}),a.jsx(Mo,{children:"Pick a dataset, choose what to run it against, and optionally score the results."})]}),a.jsxs(Gr,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs(ft,{children:[a.jsx(lt,{required:!0,children:"Name"}),a.jsx(Sn,{required:!0,value:f,onChange:ue=>h(ue.target.value),placeholder:"Enter experiment name",autoFocus:!0,disabled:L})]}),a.jsxs(ft,{children:[a.jsx(lt,{children:"Description"}),a.jsx(Ou,{value:p,onChange:ue=>m(ue.target.value),placeholder:"Enter experiment description (optional)",disabled:L,rows:2})]})]}),a.jsxs("ol",{className:"list-none",children:[a.jsxs(rce,{index:1,done:!!v,children:[a.jsxs("div",{className:"grid grid-cols-[1fr_140px] gap-3",children:[a.jsxs(ft,{children:[a.jsx(lt,{children:"Dataset"}),a.jsx(E1t,{value:v,onValueChange:U,container:d})]}),v&&a.jsxs(ft,{children:[a.jsx(lt,{children:"Version"}),a.jsx(X7t,{datasetId:v,value:x,onValueChange:b,container:d})]})]}),v&&Q!==void 0&&a.jsxs(Y,{variant:"meta",tone:"muted",children:[Q," ",Q===1?"item":"items"]})]}),a.jsxs(rce,{index:2,done:!!j,children:[a.jsx(xbs,{targetType:S,setTargetType:k,targetId:j,setTargetId:C,container:d}),S&&!j&&a.jsxs(Y,{variant:"meta",tone:"muted",children:["Choose ",S==="agent"?"an":"a"," ",S," to run"]})]}),a.jsx(rce,{index:3,done:H.length>0,isLast:!0,children:a.jsx(YX,{selectedScorers:H,setSelectedScorers:_,disabled:L,container:d,helperText:V?"Pre-filled from the dataset's default scorers.":"Scores are computed after each item runs."})})]}),a.jsxs(Wl,{children:[a.jsxs(wl,{className:"flex items-center gap-2 text-caption",children:[a.jsx(Gs,{className:"size-4"}),"Request Context (JSON, optional)",F&&a.jsx(Ft,{size:"xs",variant:"blue",children:"set"})]}),a.jsx(Sl,{className:"pt-3",children:M?a.jsx(wbs,{requestContextSchema:q,onChange:I}):a.jsx(Cr,{value:P,onChange:A,showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),a.jsxs(Ho,{children:[a.jsx("p",{"data-testid":"experiment-run-status","aria-live":"polite",className:"mr-auto flex items-center gap-2",children:$.length===0?a.jsxs(a.Fragment,{children:[a.jsx(Ft,{variant:"success",indicator:"dot",children:"Ready"}),a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",children:[Q??0," items · ",S," · ",H.length," scorers"]})]}):a.jsxs(Ft,{variant:"neutral",indicator:"dot",children:["Missing ",$.join(", ")]})}),a.jsx(ja,{children:"Cancel"}),a.jsx(Oa,{onConfirm:X,disabled:!G,children:L?a.jsxs(a.Fragment,{children:[a.jsx(An,{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(Ud,{size:"xs",children:bbs?"⌘":"Ctrl"}),a.jsx(Ud,{size:"xs",children:"↵"})]})]})})]})]})})}const rBt=g.createContext(null);function Sbs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:i,children:o}){const l=Lr(),u=Dxe("/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]);J7t({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(rBt.Provider,{value:v,children:o})}function sBt(){const e=g.useContext(rBt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}const kbs=new Set(["itemId","id","status","input","tags","scores","startedAt"]);function iBt({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,sort:m,onSortChange:v}){const{Link:y,paths:x}=hn(),b=!!(f&&h),S=s.filter(B=>kbs.has(B.name)||o?.includes(B.name)),k=[b?"2rem":"",...S.map(B=>B.size)].filter(Boolean).join(" "),j=B=>S.some(V=>V.name===B),C=j("itemId")||j("id"),T=j("status"),_=j("input"),N=j("tags"),I=j("scores"),P=j("startedAt"),A=f?e.filter(B=>f.has(B.id)).length:0,D=e.length>0&&A===e.length,{containerRef:z,getRowProps:Q}=Ru({count:e.length}),q=B=>o?.includes(B.name)?a.jsx(ke.TopCell,{children:a.jsxs(y,{href:x.scorerLink(B.name),className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[a.jsx(jx,{}),a.jsx("span",{className:"min-w-0 truncate",children:B.label})]})},B.name):B.name==="startedAt"&&v?a.jsx(ke.SortableTopCell,{sortKey:"startedAt",sort:m?.key==="startedAt"?m.direction:void 0,onSortChange:v,children:B.label},B.name):a.jsx(ke.TopCell,{children:B.label},B.name);return t?a.jsx(Au,{columns:k}):a.jsxs(ke,{columns:k,className:"min-w-0",scrollRef:z,fit:"container",children:[a.jsxs(ke.Top,{hasLeadingCell:b,children:[b&&(p?a.jsx(ke.TopSelectCell,{checked:D?!0:A>0?"indeterminate":!1,onToggle:p,"aria-label":"Select all"}):a.jsx(ke.TopCell,{children:" "})),b?a.jsx(ke.TopCells,{colStart:2,children:S.map(q)}):S.map(q)]}),e.length===0?a.jsx(ke.NoMatch,{message:d}):a.jsxs(a.Fragment,{children:[e.map((B,V)=>{const H=!!B.error,M=B.id===n,G=a.jsxs(a.Fragment,{children:[C&&a.jsxs(ke.Cell,{className:"flex items-center gap-1.5 text-muted-foreground",children:[a.jsx("span",{children:B.itemId?.slice(0,8)??""}),H&&a.jsxs($n,{children:[a.jsx(In,{render:a.jsx(RA,{role:"img","aria-label":"Error",className:"size-3.5 text-destructive-foreground"})}),a.jsx(Nn,{children:jbs(B.error)})]})]}),T&&a.jsx(ke.Cell,{className:"flex items-center","data-testid":`result-status-${B.id}`,children:B.status?a.jsx(OIe,{status:B.status}):a.jsx("span",{className:"text-placeholder",children:"—"})}),_&&a.jsx(ke.TextCell,{font:"mono",children:_bs(Cbs(B.input),200)}),N&&a.jsx(ke.Cell,{className:"flex items-center gap-1 overflow-hidden","data-testid":`result-tags-${B.id}`,children:B.tags?.map(L=>a.jsx(GX,{value:L,className:"shrink-0"},L))}),I&&a.jsx(ke.Cell,{children:a.jsx(Obs,{scores:B.scores})}),P&&(B.startedAt?a.jsx(ke.CreatedCell,{timestamp:B.startedAt}):a.jsx(ke.Cell,{className:"text-placeholder",children:"—"})),o?.map(L=>{const F=i?.[B.itemId]?.find(U=>U.scorerId===L);return a.jsx(ke.Cell,{className:"text-muted-foreground tabular-nums",children:F!=null?F.score.toFixed(3):"-"},L)})]});return b?a.jsxs(ke.RowWrapper,{children:[a.jsx(ke.SelectCell,{checked:f.has(B.id),onToggle:()=>h(B.id),"aria-label":`Select result ${B.itemId}`}),a.jsx(ke.RowButton,{colStart:2,featured:M,"data-selected":M||void 0,onClick:()=>r(B.id),...Q(V),children:G})]},B.id):a.jsx(ke.RowButton,{featured:M,"data-selected":M||void 0,onClick:()=>r(B.id),...Q(V),children:G},B.id)}),a.jsx(ke.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function Obs({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(Nt,{size:"xs",className:"text-muted-foreground",children:a.jsx(yv,{})}),a.jsx(Y,{variant:"meta",tone:"muted",font:"mono",children:t[0].toFixed(2)}),t.length>1&&a.jsxs(Ft,{children:["+",t.length-1]})]})}function jbs(e){return e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?e.message||"Error":typeof e=="string"&&e?e:"Error"}function Cbs(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function _bs(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function Tbs({experimentId:e,experimentStatus:t,results:n,isLoading:r,setEndOfListElement:s,isFetchingNextPage:i,hasNextPage:o,selectedIds:l,onToggleSelect:c,sort:u,onSortChange:d}){const{currentItemId:f,openItem:h,close:p}=sBt(),m=g.useMemo(()=>f?n.find(S=>S.itemId===f)?.id??null:null,[n,f]),{data:v}=yS({experimentId:e,experimentStatus:t,queryOptions:{enabled:!!e}}),y=g.useMemo(()=>{if(!v)return[];const S=new Set;for(const k of Object.values(v))for(const j of k)S.add(j.scorerId);return[...S].sort()},[v]),x=g.useCallback(S=>{const k=n.find(j=>j.id===S);k&&(k.itemId===f?p():h(k.itemId))},[n,f,p,h]),b=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"auto"},{name:"status",label:"Status",size:"auto"},{name:"input",label:"Input",size:"1fr"},{name:"tags",label:"Tags",size:"auto"},{name:"startedAt",label:"Created",size:"auto"},...y.map(S=>({name:S,label:S,size:"auto"}))],[y]);return a.jsx("div",{className:"h-full min-h-0 min-w-0 overflow-y-auto",children:a.jsx(iBt,{results:n,isLoading:r,featuredResultId:m,onResultClick:x,columns:b,scoresByItemId:v,scorerIds:y,setEndOfListElement:s,isFetchingNextPage:i,hasNextPage:o,selectedIds:l,onToggleSelect:c,sort:u,onSortChange:d})})}const jJe={pending:{icon:a.jsx(JI,{className:"size-4 text-warning-foreground"}),label:"Pending"},running:{icon:a.jsx(An,{size:"sm"}),label:"Running"},completed:{icon:a.jsx(ldt,{className:"size-4 text-muted-foreground"}),label:"Completed"},failed:{icon:a.jsx(Dbe,{className:"size-4 text-destructive-foreground"}),label:"Failed"}};function Ebs({status:e,className:t}){const n=jJe[e]??jJe.pending;return a.jsxs($n,{children:[a.jsx(In,{render:a.jsx("span",{tabIndex:0,className:Z("flex shrink-0 items-center",t),children:n.icon})}),a.jsx(Nn,{children:n.label})]})}function Ibs({children:e,className:t}){return a.jsx("div",{className:Z("grid content-start gap-4 overflow-y-auto",t),children:e})}function Nbs({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 Abs({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 oBt=Object.assign(Nbs,{Content:Ibs,Toolbar:Abs});function Pbs({children:e,className:t}){return a.jsx("div",{className:Z("grid size-full grid-cols-1 overflow-y-auto",t),children:e})}const $bs=({experimentId:e,experimentStatus:t,supportsMetrics:n,queryOptions:r})=>{const s=Ye(),i=!!e&&n,o=kt({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}},Rbs=({traceId:e,queryOptions:t})=>{const n=Ye();return kt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return n.getTraceLight(e)},...t})};function aBt({datasetId:e,target:t,queryOptions:n}){const r=Ye(),s={perPage:100};return t?.targetType&&(s.targetType=t.targetType),t?.targetId&&(s.targetId=t.targetId),kt({queryKey:["experiments",s],queryFn:()=>r.listExperiments(s),...n})}function Mbs({datasetId:e,target:t,orderBy:n,queryOptions:r}){const s=Ye(),{inView:i,setRef:o}=E0(),l=t?.targetType||void 0,c=t?.targetId||void 0,u=Am({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 Dbs={agent:"blue",workflow:"cyan",model:"purple",mcp:"green",tool:"amber",workspace:"orange"},Lbs=Object.keys(Dbs);[...Lbs];function zbs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${is(n,"date-time")}`}return`v${e}`}function Fbs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=T1t({datasetId:e,queryOptions:{enabled:!!e}}),i=(s??[]).map(o=>({value:String(o.version),label:`${zbs(o.version,o.createdAt)}${o.isCurrent?" (current)":""}`}));return a.jsxs(oBt.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[a.jsx("div",{}),a.jsxs(Ur,{value:t??"",onValueChange:o=>r?.(o,n??""),children:[a.jsx(Qr,{"aria-label":"Version A",size:"md",children:a.jsx(qr,{placeholder:"Select version"})}),a.jsx(Zr,{children:i.map(o=>a.jsx(or,{value:o.value,children:o.label},o.value))})]}),a.jsxs(Ur,{value:n??"",onValueChange:o=>r?.(t??"",o),children:[a.jsx(Qr,{"aria-label":"Version B",size:"md",children:a.jsx(qr,{placeholder:"Select an option"})}),a.jsx(Zr,{children:i.map(o=>a.jsx(or,{value:o.value,children:o.label},o.value))})]}),a.jsx("div",{})]})}const zB={added:{badgeVariant:"info",borderColor:"border-info-edge",icon:a.jsx(bs,{}),tooltip:"Added in this version"},changed:{badgeVariant:"warning",borderColor:"border-warning-edge",icon:a.jsx(s_n,{}),tooltip:"Changed in this version"},same:{badgeVariant:"success",borderColor:"border-success-edge",icon:a.jsx(ddt,{}),tooltip:"Same in both versions"}};function sce({red:e=!1,tooltip:t}){return a.jsxs($n,{children:[a.jsx(In,{render:a.jsx("span",{}),role:"img",tabIndex:0,"aria-label":t,className:Z("rounded",$i),children:a.jsx(edt,{className:Z("h-5 w-5 text-muted-foreground/40",{"text-destructive-foreground":e})})}),a.jsx(Nn,{children:t})]})}function K9({href:e,tooltip:t,className:n,children:r}){const{Link:s}=hn(),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",ro.colors,$i,n),children:r});return t===void 0?i:a.jsxs($n,{children:[a.jsx(In,{render:i}),a.jsx(Nn,{children:t})]})}function ice({variant:e,version:t}){if(!e)return a.jsxs(Y,{as:"span",tone:"muted",children:["v. ",t]});const{badgeVariant:n,icon:r,tooltip:s}=zB[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(Ft,{variant:n,size:"xs",icon:r})})]})}function Bbs(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function CJe({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function Vbs({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=Bbs(c,u),f=CJe({otherVersionExists:u!==void 0,status:d,isNewer:o}),h=CJe({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",ro.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(K9,{href:`/datasets/${e}/items/${l}`,className:"gap-2",tooltip:f?zB[f].tooltip:void 0,children:a.jsx(ice,{variant:f,version:c.datasetVersion})}):a.jsx("div",{className:"flex items-center justify-center",children:a.jsx(sce,{red:o,tooltip:o?"Deleted in this version":"Not present in this version"})}),u?.datasetVersion?a.jsx(K9,{href:`/datasets/${e}/items/${l}`,className:"gap-2",tooltip:h?zB[h].tooltip:void 0,children:a.jsx(ice,{variant:h,version:u.datasetVersion})}):a.jsx("div",{className:"flex items-center justify-center",children:a.jsx(sce,{red:!o,tooltip:o?"Not present in this version":"Deleted in this version"})})]}):a.jsx(K9,{href:`/datasets/${e}/items/${l}`,className:"col-span-2 gap-2",tooltip:zB.same.tooltip,children:a.jsx(ice,{variant:"same",version:u?.datasetVersion})}),d==="changed"?a.jsx(K9,{href:`/datasets/${e}/items/${l}/versions?version=${c?.datasetVersion}&compare=${u?.datasetVersion}`,children:"Compare"}):a.jsx("div",{children:a.jsx(sce,{tooltip:"Comparing is available only for changed items"})})]},l)})})})}function Ubs(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 qbs({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(Qbs,{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 Qbs({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:i}=hn(),{updateItem:o,deleteItem:l}=ul(),[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(""),[I,P]=g.useState(null),[A,D]=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),D(!1),P(null))},[t?.id]);const z=n.findIndex(L=>L.id===t.id),Q=z>0?()=>r(n[z-1].id):void 0,q=z>=0&&z<n.length-1?()=>r(n[z+1].id):void 0,B=async()=>{let L;try{L=JSON.parse(d)}catch{Ge.error("Input must be valid JSON");return}let $;if(h.trim())try{$=JSON.parse(h)}catch{Ge.error("Ground Truth must be valid JSON");return}let F;if(m.trim())try{F=JSON.parse(m)}catch{Ge.error("Metadata must be valid JSON");return}let U=null;if(y.trim())try{U=JSON.parse(y)}catch{Ge.error("Expected Trajectory must be valid JSON");return}let K;if(b.trim())try{const te=JSON.parse(b);if(!Array.isArray(te)){Ge.error("Tool Mocks must be a JSON array");return}K=te}catch{Ge.error("Tool Mocks must be valid JSON");return}else K=[];let ne;if(_.trim())try{ne=JSON.parse(_)}catch{Ge.error("Request Context must be valid JSON");return}let X;k?X=C:t.scorerIds!==void 0&&(X=null);try{const te=await o.mutateAsync({datasetId:e,itemId:t.id,input:L,groundTruth:$,metadata:F,expectedTrajectory:U,toolMocks:K,scorerIds:X,requestContext:ne});Ge.success("Item updated successfully"),j(te.scorerIds!==void 0),T(te.scorerIds??[]),u(!1),P(null)}catch(te){const oe=Ubs(te);oe?P(oe):Ge.error(`Failed to update item: ${te instanceof Error?te.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),P(null)},H=L=>{f(L),I?.field==="input"&&P(null)},M=L=>{p(L),I?.field==="groundTruth"&&P(null)},G=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Ge.success("Item deleted successfully"),D(!1),s()}catch(L){Ge.error(`Failed to delete item: ${L instanceof Error?L.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(de,{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(Gbe,{})}),a.jsxs(ut,{children:[a.jsx(ut.Trigger,{asChild:!0,children:a.jsx(de,{size:"sm",variant:"ghost",tooltip:"Open actions menu","aria-label":"Open actions menu",children:a.jsx(j0,{})})}),a.jsxs(ut.Content,{align:"end",className:"w-48",children:[a.jsxs(ut.Item,{onSelect:()=>u(!0),children:[a.jsx(od,{}),"Edit"]}),a.jsxs(ut.Item,{onSelect:()=>D(!0),variant:"destructive",children:[a.jsx(Go,{}),"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(vbs,{inputValue:d,setInputValue:H,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:I,onSave:B,onCancel:V,isSaving:o.isPending}):a.jsx(_ve,{item:t})}),a.jsx(Ut,{open:A,onOpenChange:D,children:a.jsxs(Ut.Content,{children:[a.jsxs(Ut.Header,{children:[a.jsx(Ut.Title,{children:"Delete Item"}),a.jsx(Ut.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),a.jsxs(Ut.Footer,{children:[a.jsx(Ut.Cancel,{children:"Cancel"}),a.jsx(Ut.Action,{onClick:G,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function Zbs(){const{datasetId:e,items:t,isLoadingItems:n,currentItemId:r,openItem:s,close:i}=tBt(),o=g.useMemo(()=>r?t.find(d=>d.id===r):void 0,[t,r]),{data:l,isLoading:c}=_1t({datasetId:o?"":e,itemId:!o&&r?r:"",queryOptions:{enabled:!!(!o&&e)&&!!(!o&&r&&r)}}),u=o??l??void 0;return a.jsx(qbs,{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 Y9({crumbs:e,children:t}){return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{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 Wbs(){const{datasetId:e,itemId:t}=fr(),n=[hs("/datasets"),{..._G,to:`/datasets/${encodeURIComponent(e)}`},...t?[{id:"dataset-items",label:"Items"},{id:"dataset-item",label:ySe(t)}]:[]],r=Lr(),[s,i]=pi(),{activeVersion:o,handleVersionChange:l}=BIe(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}=Tv({datasetId:e,queryOptions:{enabled:!!e}}),{data:S=[],isLoading:k}=_N({datasetId:e,search:void 0,version:o,queryOptions:{enabled:!!e}}),j=!k&&S.length===0;if(b)return null;if(x&&_s(x))return a.jsx(Y9,{crumbs:n,children:a.jsx(ci,{})});if(x&&Ts(x))return a.jsx(Y9,{crumbs:n,children:a.jsx(Js,{resource:"datasets"})});if(x&&ok(x)||!b&&!x&&!y)return a.jsx(Y9,{crumbs:n,children:a.jsx(tn,{titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:a.jsx(de,{render:a.jsx(oc,{to:"/datasets"}),icon:a.jsx(fd,{}),children:"Back to Datasets"})})});if(x)return a.jsx(Y9,{crumbs:n,children:a.jsx(tn,{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(ubs,{datasetId:e,items:S,isLoadingItems:k,children:[a.jsxs("div",{className:"h-full",children:[a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:n}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{children:a.jsx(fbs,{datasetId:e,onAddItemClick:()=>f(!0),belowToolbarSlot:a.jsx(hbs,{datasetId:e}),leftSlot:a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"mr-3 whitespace-nowrap",children:y?.createdAt?`Created ${is(y.createdAt,"date-time")}`:""}),rightSlot:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(de,{render:a.jsx(oc,{to:`/experiments?dataset=${e}`}),icon:a.jsx(oH,{}),children:"View experiments"}),a.jsx(X7t,{datasetId:e,value:o,onValueChange:l,currentVersion:y?.version,className:"w-36"}),j?a.jsxs($n,{children:[a.jsx(In,{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(de,{variant:"primary",icon:a.jsx(ku,{}),children:"Run Experiment"})})})}),a.jsx(Nn,{children:"Add items to the dataset before running an experiment"})]}):a.jsx(de,{variant:"primary",onClick:()=>u(!0),icon:a.jsx(ku,{}),children:"Run Experiment"}),a.jsxs(ut,{children:[a.jsx(ut.Trigger,{asChild:!0,children:a.jsx(de,{size:"lg","aria-label":"Dataset actions menu",children:a.jsx(j0,{})})}),a.jsxs(ut.Content,{align:"end",className:"w-48",children:[a.jsxs(ut.Item,{onSelect:()=>{r(`/datasets/${e}/edit`)},children:[a.jsx(od,{})," Edit Dataset"]}),a.jsxs(ut.Item,{onSelect:()=>v(!0),children:[a.jsx($m,{})," Duplicate Dataset"]}),a.jsxs(ut.Item,{onSelect:()=>p(!0),variant:"destructive",children:[a.jsx(Go,{})," Delete Dataset"]})]})]})]})})})]}),a.jsx(Zbs,{})]}),a.jsx(XX,{initialDatasetId:e,initialDatasetVersion:o??void 0,open:c,onOpenChange:u,onSuccess:C},`${e}:${o??"latest"}`),a.jsx(mbs,{datasetId:e,open:d,onOpenChange:f}),y&&a.jsx(Cxs,{open:m,onOpenChange:v,sourceDatasetId:y.id,sourceDatasetName:y.name,sourceDatasetDescription:y.description,sourceDatasetTargetType:y.targetType}),y&&a.jsx(Ixs,{open:h,onOpenChange:p,datasetId:y.id,datasetName:y.name,onSuccess:T})]})}const lBt=[hs("/datasets"),_G,{id:"dataset-edit",label:"Edit dataset"}];function oce({children:e}){return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:lBt}),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 Hbs(){const{datasetId:e}=fr(),t=Lr(),{data:n,error:r,isLoading:s}=Tv({datasetId:e,queryOptions:{enabled:!!e}}),i=()=>{t(`/datasets/${e}`)};return s?null:r&&_s(r)?a.jsx(oce,{children:a.jsx(ci,{})}):r&&Ts(r)?a.jsx(oce,{children:a.jsx(Js,{resource:"datasets"})}):r||!n?a.jsx(oce,{children:a.jsx(tn,{tone:"error",titleSlot:"Failed to load dataset",descriptionSlot:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:lBt}),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(Dh,{className:"mb-6 p-0",children:a.jsxs(Dh.Column,{children:[a.jsxs(Dh.Title,{children:[a.jsx(ex,{})," Edit dataset"]}),a.jsx(Dh.Description,{children:n.name})]})}),a.jsx(hc,{className:"p-4",children:a.jsx(Exs,{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 _Je(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 TJe(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]})," · ",is(r,"date-time")]}),n.isLatest?a.jsx(Ft,{variant:"blue",size:"xs",className:"ml-auto",children:"Latest"}):null]}),disabled:t?.has(n.datasetVersion)??!1}})}function EJe(e){const t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function Gbs(){const{datasetId:e,itemId:t}=fr(),[n,r]=pi(),s=[hs("/datasets"),_G,{id:"dataset-item",label:ySe(t),to:e&&t?`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`:void 0},{id:"dataset-item-versions",label:"Item Version History"}],i=EJe(n.get("version")),o=EJe(n.get("compare")),l=n.get("view")==="diff",{data:c,error:u}=Tv({datasetId:e??"",queryOptions:{enabled:!!e}}),{data:d,isLoading:f}=Lsr({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}=zsr({datasetId:e??"",itemId:t??"",datasetVersion:m??0,latestVersion:c?.version,queryOptions:{enabled:!!e&&!!t&&(m??0)>0}}),x=(T,_)=>r(N=>{const I=new URLSearchParams(N);return _==null?I.delete(T):I.set(T,String(_)),I},{replace:!0});if(u&&_s(u))return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx(ci,{variant:"fill"})]});if(u&&Ts(u))return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx(Js,{variant:"fill",resource:"datasets"})]});if(!e||!t)return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{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?_Je(h,e):null,j=v?_Je(v,e):null,C=(h?.datasetVersion??0)<(v?.datasetVersion??0);return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:s}),headerActions:b&&a.jsx(de,{variant:"ghost",size:"sm",onClick:()=>x("view",l?null:"diff"),children:l?a.jsxs(a.Fragment,{children:[a.jsx(zbe,{})," Default View"]}):a.jsxs(a.Fragment,{children:[a.jsx(Ijn,{})," 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(hc,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[a.jsx(Nq,{children:a.jsx(IJe,{label:"Version",value:p!=null?String(p):"",options:TJe(d??[],m!=null?new Set([m]):void 0),onValueChange:T=>x("version",Number(T))})}),a.jsx(dv,{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(_ve,{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(hc,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[a.jsx(Nq,{children:a.jsx(IJe,{label:"Compare version",value:m!=null?String(m):"",placeholder:"Select a version to compare",options:TJe(d??[],p!=null?new Set([p]):void 0),onValueChange:T=>x("compare",Number(T))})}),a.jsx(dv,{className:"grid content-start gap-5 overflow-y-auto",children:m==null?a.jsx(tn,{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(_ve,{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 IJe({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(Gbe,{className:"size-4 opacity-50"}),a.jsxs(Ur,{value:t,onValueChange:s,children:[a.jsx(Qr,{"aria-label":e,className:"w-full",children:a.jsx(qr,{placeholder:r,className:"flex-1"})}),a.jsx(Zr,{children:n.map(i=>a.jsx(or,{value:i.value,disabled:i.disabled,children:i.label},i.value))})]})]})}const X9=[hs("/datasets"),_G,{id:"dataset-versions",label:"Versions"}];function Kbs(){const{datasetId:e}=fr(),[t]=pi(),n=t.get("ids")?.split(",").map(Number).filter(m=>!isNaN(m)&&m>0)??[],r=Lr(),{data:s,error:i}=Tv({datasetId:e??"",queryOptions:{enabled:!!e}}),o=_N({datasetId:e??"",search:void 0,version:n[0]??null,queryOptions:{enabled:!!e}}),l=_N({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&&_s(i))return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:X9}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx(ci,{variant:"fill"})]});if(i&&Ts(i))return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:X9}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx(Js,{variant:"fill",resource:"datasets"})]});if(!e||n.length<2)return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:X9}),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(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:X9}),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(Dh,{children:[a.jsxs(Dh.Column,{children:[a.jsxs(Dh.Title,{children:[a.jsx(z_n,{})," Compare Dataset Versions"]}),a.jsx(Dh.Description,{children:a.jsxs(Zd,{children:[a.jsx(Gbe,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),a.jsx(Dh.Column,{children:a.jsx(de,{render:a.jsx(oc,{to:`/datasets/${e}`}),icon:a.jsx(fd,{}),children:"Back to Dataset"})})]}),a.jsx(Pbs,{children:a.jsxs(oBt,{children:[a.jsx(Fbs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:p}),a.jsx(Vbs,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:h})]})})]})})]})}const Ybs=[hs("/datasets"),{id:"dataset-new",label:"Create new dataset"}];function Xbs(){const e=Lr(),[t]=pi(),n=t.get("targetType"),r=KX(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(St,{breadcrumbs:a.jsx(Pt,{crumbs:Ybs}),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(Dh,{className:"mb-6 p-0",children:a.jsxs(Dh.Column,{children:[a.jsxs(Dh.Title,{children:[a.jsx(ex,{})," Create new dataset"]}),a.jsx(Dh.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),a.jsx(hc,{className:"p-4",children:a.jsx(wxs,{targetType:r,targetIds:i,onSuccess:o,onCancel:()=>{e(-1)}})})]})})]})}const cBt=(e,{experimentId:t,targetType:n,targetId:r,experiments:s,isLoadingExperiments:i=!1,queryOptions:o})=>{const l=Ye(),c=s!==void 0,{data:u,isLoading:d}=aBt({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=kt({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??[],createdAt:x.createdAt,status:x.status,groundTruth:x.groundTruth,toolMockReport:x.toolMockReport}))}catch{return[]}}))).flat(),enabled:!!f,refetchOnWindowFocus:!1,...o});return{...m,isLoading:m.isLoading||h}},Jbs=(e={})=>cBt("needs-review",e),e0s=(e={})=>cBt("complete",e);function t0s({queryOptions:e}={}){const t=Ye();return kt({queryKey:["experiment-review-summary"],queryFn:()=>t.getExperimentReviewSummary(),...e})}function uBt({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:s}){const{deleteExperiment:i}=ul(),o=async()=>{try{await i.mutateAsync(n),Ge.success("Experiment deleted successfully"),t(!1),s?.()}catch(l){Ge.error(`Failed to delete experiment: ${l instanceof Error?l.message:"Unknown error"}`)}};return a.jsx(Ut,{open:e,onOpenChange:t,children:a.jsxs(Ut.Content,{children:[a.jsxs(Ut.Header,{children:[a.jsx(Ut.Title,{children:"Delete Experiment"}),a.jsxs(Ut.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(Ut.Footer,{children:[a.jsx(Ut.Cancel,{children:"Cancel"}),a.jsx(de,{icon:a.jsx(Go,{}),variant:"primary",onClick:o,disabled:i.isPending,children:i.isPending?"Deleting...":"Delete"})]})]})})}const n0s="minmax(9rem,1fr)",r0s="minmax(8rem,16rem)",s0s="1fr",i0s="auto auto auto auto auto auto auto",Jv={experiment:"Experiment",description:"Description",dataset:"Dataset",target:"Target",status:"Status",items:"Items",succeeded:"Processed",failed:"Errored",review:"Review",date:"Date"},o0s={completed:"neutral",running:"warning",failed:"destructive",pending:"neutral"},a0s={completed:"Run completed",running:"Run in progress",failed:"Run failed",pending:"Run queued"};function dBt(e){const t=ux(e.id)??e.id;return e.name||`Experiment #${t}`}const l0s=60;function c0s({experiment:e}){return a.jsx("span",{className:"block min-w-0 truncate text-left text-muted-foreground",children:dBt(e)})}function u0s({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<=l0s?n:a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:n}),a.jsx(Nn,{children:t})]})}function fBt(){const{data:e}=pf(),{data:t}=vp(),{data:n}=eg(),{data:r}=c_();return{agents:e,workflows:t,scorers:n,processors:r}}const hBt={agent:zo,workflow:xl,scorer:jx,processor:AO},pBt={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},d0s="External (caller-run)";function mBt(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:i,targetId:o}=e;if(!o)return d0s;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 f0s({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(ke.Cell,{children:a.jsx(c0s,{experiment:e})}),a.jsx(ke.Cell,{children:a.jsx(u0s,{experiment:e})}),t!==void 0&&a.jsx(ke.TextCell,{children:t}),a.jsx(ke.Cell,{children:a.jsx(h0s,{experiment:e})}),a.jsx(ke.Cell,{children:a.jsx(Ft,{variant:o0s[r]??"neutral",indicator:"dot",children:a0s[r]??r})}),a.jsx(ke.TextCell,{className:"text-center",children:o}),a.jsx(ke.TextCell,{className:"text-center",children:s}),a.jsx(ke.TextCell,{className:"text-center",children:a.jsx("span",{className:i>0?"text-destructive-foreground":"",children:i})}),a.jsx(ke.Cell,{className:"text-center",children:a.jsx(p0s,{review:n})}),a.jsx(ke.TextCell,{children:is(e.createdAt,"date")??"—"})]})}function h0s({experiment:e}){const t=fBt(),n=mBt(e,t),r=e.targetId?e.targetType:null,s=r?hBt[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":pBt[r],children:a.jsx(s,{})}),a.jsx("span",{className:r?"truncate":"truncate text-placeholder",children:n})]})}function p0s({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(Ft,{size:"xs",variant:"warning",children:[e.needsReview," pending"]}):a.jsxs(Ft,{size:"xs",variant:"success",children:[e.complete,"/",t," reviewed"]})}const gBt=`${n0s} ${r0s} ${s0s} ${i0s}`,NJe=`${gBt} auto`,m0s=[{label:Jv.experiment},{label:Jv.description},{label:Jv.dataset},{label:Jv.target},{label:Jv.status,sortKey:"status"},{label:Jv.items,className:"text-center"},{label:Jv.succeeded,className:"text-center"},{label:Jv.failed,className:"text-center"},{label:Jv.review,className:"text-center"},{label:Jv.date,sortKey:"createdAt"}],vBt=e=>e.stopPropagation();function g0s({experiment:e,rowProps:t,onSelect:n,featured:r,onDelete:s,children:i}){const{paths:o,Link:l}=hn(),c=g.useRef(null);return a.jsxs(ke.RowWrapper,{...t,onSelectRow:n??(()=>c.current?.click()),children:[n?a.jsx(ke.RowButton,{colEnd:-2,featured:r,tabIndex:-1,onClick:u=>{u.stopPropagation(),n()},children:i}):a.jsx(ke.RowLink,{ref:c,colEnd:-2,to:o.experimentLink(e.id),LinkComponent:l,tabIndex:-1,onClick:vBt,children:i}),a.jsx(ke.ActionsCell,{className:"pl-2",children:a.jsx(de,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"Delete experiment","aria-label":`Delete experiment ${e.name??e.id}`,onClick:u=>{u.stopPropagation(),s()},children:a.jsx(Go,{className:"size-4"})})})]})}function v0s({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=l!==void 0,x=g.useMemo(()=>{const I=new Map;return t?.forEach(P=>I.set(P.id,P.name)),I},[t]),b=g.useMemo(()=>m?e:[...e].sort((I,P)=>{const A=I.createdAt?new Date(I.createdAt).getTime():0;return(P.createdAt?new Date(P.createdAt).getTime():0)-A}),[e,m]),S=g.useMemo(()=>{const I=s.toLowerCase();return b.filter(P=>{const A=P.datasetId?x.get(P.datasetId)??"":"",D=!I||P.id.toLowerCase().includes(I)||(P.name??"").toLowerCase().includes(I)||A.toLowerCase().includes(I)||(P.targetId??"").toLowerCase().includes(I),z=i==="all"||P.status===i,Q=o==="all"||P.datasetId===o;return D&&z&&Q})},[b,s,x,i,o]),{containerRef:k,getRowProps:j}=Ru({count:S.length,global:d}),[C,T]=g.useState(null);if(r)return a.jsx(Au,{columns:NJe});const _=y?`auto ${gBt}`:NJe,N=m0s.map(I=>I.sortKey&&v?a.jsx(ke.SortableTopCell,{className:I.className,sortKey:I.sortKey,sort:m?.key===I.sortKey?m.direction:void 0,onSortChange:v,children:I.label},I.label):a.jsx(ke.TopCell,{className:I.className,children:I.label},I.label));return a.jsxs(ke,{columns:_,scrollRef:k,children:[a.jsx(ke.Top,{hasLeadingCell:y,children:y?a.jsxs(a.Fragment,{children:[a.jsx(ke.TopCell,{children:" "}),a.jsx(ke.TopCells,{colStart:2,children:N})]}):a.jsxs(a.Fragment,{children:[N,a.jsx(ke.TopCell,{"aria-hidden":!0,children:null})]})}),S.map((I,P)=>{const A=I.datasetId?x.get(I.datasetId)??ux(I.datasetId)??I.datasetId:"—",D=a.jsx(f0s,{experiment:I,datasetName:A,review:n?.get(I.id)});if(!l)return a.jsx(g0s,{experiment:I,rowProps:j(P),onSelect:c?()=>c(I):void 0,featured:u===I.id,onDelete:()=>T(I),children:D},I.id);const z=l.selectedExperimentIds.includes(I.id),Q=()=>l.onToggleSelection(I.id);return a.jsxs(ke.RowWrapper,{...j(P),onSelectRow:Q,children:[a.jsx(ke.SelectCell,{checked:z,onToggle:Q,"aria-label":`Select experiment ${I.id}`}),a.jsx(ke.RowButton,{colStart:2,featured:z,tabIndex:-1,onClick:vBt,children:D})]},I.id)}),a.jsx(ke.NextPageLoading,{isLoading:f,hasMore:h,setEndOfListElement:p}),C&&a.jsx(uBt,{open:!0,onOpenChange:I=>{I||T(null)},experimentId:C.id,experimentName:C.name??void 0})]})}const y0s=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function x0s(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const b0s=({onRunExperiment:e})=>a.jsx(tn,{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(de,{variant:"primary",onClick:e,icon:a.jsx(ku,{}),children:"Run Experiment"}),a.jsx(de,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Vs,{}),children:"Experiments Documentation"})]}),variant:"fill"});function w0s({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:i,datasetOptions:o,targetType:l,onTargetTypeChange:c,targetId:u,onTargetIdChange:d,onReset:f,hasActiveFilters:h,onRunClick:p,runTooltip:m="Run an experiment",onCompareClick:v,selection:y}){const x=y?.selectedCount===2&&!y.compareDisabledReason;return a.jsxs(Xn,{children:[a.jsxs(Xn.Start,{children:[a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(Pu,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),a.jsxs(Ur,{value:n,onValueChange:r,children:[a.jsx(Qr,{"aria-label":"Status",size:"md",className:"whitespace-nowrap",children:a.jsx(qr,{placeholder:"Select an option"})}),a.jsx(Zr,{children:y0s.map(b=>a.jsx(or,{value:b.value,children:b.label},b.value))})]}),a.jsxs(Ur,{value:s,onValueChange:i,children:[a.jsx(Qr,{"aria-label":"Dataset",size:"md",className:"whitespace-nowrap",children:a.jsx(qr,{placeholder:"Select an option"})}),a.jsx(Zr,{children:o.map(b=>a.jsx(or,{value:b.value,children:b.label},b.value))})]}),a.jsx(q7t,{targetType:l,targetId:u,onTargetTypeChange:c,onTargetIdChange:d}),f&&h&&a.jsx(de,{onClick:f,size:"sm",variant:"default",icon:a.jsx(Ln,{}),children:"Reset"})]}),y?a.jsx(Xn.End,{children:a.jsxs(Vl,{className:"whitespace-nowrap",children:[a.jsxs(qh,{className:"gap-2",children:[a.jsxs(Ft,{size:"sm",variant:y.selectedCount<2?"destructive":"success",children:[y.selectedCount," / 2"]}),"selected",y.compareDisabledReason&&a.jsxs("span",{className:"text-destructive-foreground",children:["· ",y.compareDisabledReason]})]}),a.jsx(de,{variant:"primary",disabled:!x,onClick:y.onExecuteCompare,icon:a.jsx(_3e,{}),children:"Compare Experiments"}),a.jsx(de,{icon:a.jsx(Ln,{}),onClick:y.onCancelSelection,children:"Cancel"})]})}):a.jsxs(Xn.End,{children:[v&&a.jsx(de,{onClick:v,tooltip:"Select two experiments of the same dataset to compare",icon:a.jsx(_3e,{}),children:"Compare"}),p&&a.jsx(de,{onClick:p,tooltip:m,variant:"primary",icon:a.jsx(ku,{}),children:"Run Experiment"})]})]})}const S0s={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},AJe=e=>e?e instanceof Date?e.toISOString():e:null,PJe=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},$Je=(e,t,n)=>{if(!e)return S0s;const r=new Map;for(const s of n??[])r.set(s.scorerId,s.reason??null);return{present:!0,output:e.output,metadata:t?.metadata??null,comment:t?.comment??null,error:t?.error??null,startedAt:AJe(t?.startedAt),completedAt:AJe(t?.completedAt),scores:Object.entries(e.scores).map(([s,i])=>({scorerId:s,value:i,reason:r.get(s)??null})).sort((s,i)=>s.scorerId.localeCompare(i.scorerId))}},k0s=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:i,contenderScores:o})=>{if(!e)return[];const l=PJe(r),c=PJe(s);return e.items.map(u=>{const d=$Je(u.results[t],l.get(u.itemId),i?.[u.itemId]),f=$Je(u.results[n],c.get(u.itemId),o?.[u.itemId]),h={};for(const p of new Set([...d.scores,...f.scores].map(m=>m.scorerId))){const m=d.scores.find(y=>y.scorerId===p)?.value??null,v=f.scores.find(y=>y.scorerId===p)?.value??null;h[p]=m!=null&&v!=null?v-m:null}return{itemId:u.itemId,input:u.input,groundTruth:u.groundTruth,baseline:d,contender:f,deltas:h}})};function MO({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return a.jsxs(Wl,{defaultOpen:r,className:"grid gap-2",children:[a.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[a.jsxs(wl,{className:Z("flex items-center gap-1.5 [&>svg]:size-4",n==="negative"?"text-destructive-foreground":"text-foreground","text-subheading"),children:[a.jsx(Gs,{}),e]}),t]}),a.jsx(Sl,{role:"region","aria-label":e,children:s})]})}function RJe({label:e,value:t}){return t==null?null:a.jsx(MO,{title:e,defaultOpen:!1,children:a.jsx(bl,{className:"max-h-40 overflow-auto rounded-md bg-card p-3 text-caption whitespace-pre-wrap text-muted-foreground",code:typeof t=="string"?t:JSON.stringify(t,null,2)})})}function yBt({delta:e}){const t=e>0?"text-success-indicator":e<0?"text-destructive-foreground":"text-muted-foreground";return a.jsxs("span",{className:Z("inline-flex min-w-20 items-center gap-1 tabular-nums",t),children:[a.jsx(Y,{as:"span",className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),a.jsx(Y,{as:"span",children:Math.abs(e).toFixed(2)}),e>0?a.jsx($be,{className:"size-3.5"}):e<0?a.jsx(Yut,{className:"size-3.5"}):null]})}function xBt({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:i}=hn();return a.jsxs("div",{className:"grid gap-1 rounded-lg bg-background px-3 py-2",children:[a.jsxs("div",{className:"flex items-center justify-between gap-4",children:[a.jsxs(s,{href:i.scorerLink(e),"aria-label":`Open ${e}`,className:"flex min-w-0 items-center gap-1.5 text-foreground hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[a.jsx(jx,{}),a.jsx(Y,{as:"span",variant:"subheading",className:"min-w-0 truncate",children:e})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(Y,{as:"span",tone:"muted",className:"tabular-nums",children:t!=null?t.toFixed(2):"-"}),n!=null&&a.jsx(yBt,{delta:n})]})]}),r&&a.jsx(Y,{tone:"muted",children:r})]})}function MJe(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function O0s(e){if(!e.startedAt||!e.completedAt)return null;const t=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return nf(t)??null}const j0s=Z(hr,"max-h-[30vh] overflow-y-auto rounded-xl p-4 break-all whitespace-pre-wrap");function DJe({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],i=O0s(s);if(r)return a.jsx("div",{className:"flex h-32 items-center justify-center",children:a.jsx(An,{})});if(!s.present)return a.jsx(Y,{tone:"muted",className:"py-5 text-center",children:"Not present in this experiment"});const o=MJe(s.output);return a.jsxs("div",{className:"grid content-start gap-5",children:[i&&a.jsxs($n,{children:[a.jsx(In,{render:a.jsxs(Y,{tone:"muted",className:"flex items-center justify-end gap-1.5 [&>svg]:size-3.5",children:[a.jsx(JI,{}),a.jsx(Y,{as:"span",variant:"body",font:"mono",children:i})]})}),a.jsx(Nn,{children:"Run duration"})]}),s.error?a.jsx(MO,{title:"Error",tone:"negative",actions:a.jsx(io,{content:s.error.message}),children:a.jsx(Y,{tone:"muted",className:"rounded-xl border border-destructive-edge bg-destructive-subtle p-4 break-words",children:s.error.message})}):a.jsx(MO,{title:"Output",actions:a.jsx(io,{content:o}),children:a.jsx(bl,{className:Z(j0s,"font-mono text-body text-muted-foreground"),code:o})}),s.scores.length>0&&a.jsx(MO,{title:"Scores",children:a.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>a.jsx(xBt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&a.jsx(MO,{title:"Comment",defaultOpen:!1,children:a.jsx(Y,{tone:"muted",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&a.jsx(MO,{title:"Metadata",defaultOpen:!1,children:a.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>a.jsxs("div",{className:"flex items-start justify-between gap-4",children:[a.jsx("dt",{className:$l({tone:"muted",variant:"body"}),children:l}),a.jsx("dd",{className:Z($l({tone:"ink",variant:"body",font:"mono"}),"break-all"),children:MJe(c)})]},l))})})]})}const C0s={baseline:"Baseline",contender:"Contender"},_0s={baseline:"purple",contender:"blue"},T0s="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function LJe({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:i,paths:o}=hn(),l=C0s[e],c=t?ux(t.id)??t.id:null,u=t?.createdAt?new Date(t.createdAt):null,d=n??[];return a.jsxs("div",{className:"grid content-start gap-3",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[a.jsx(Ft,{variant:_0s[e],size:"xs",children:l}),t&&a.jsx(de,{render:a.jsx(i,{href:`/experiments/${t.id}`}),size:"sm","aria-label":`Open experiment ${t.name||c}`,children:a.jsx("span",{className:"min-w-0 truncate",children:t.name||c})})]}),t&&a.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-muted-foreground",children:[t.name&&a.jsxs(Zd,{children:[a.jsx(LA,{})," ",c]}),t.targetType==="agent"&&t.targetId?a.jsxs(i,{href:o.agentLink(t.targetId),className:T0s,children:[a.jsx(zo,{}),a.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):a.jsxs(Zd,{children:[a.jsx(Fdt,{})," ",t.targetId]}),a.jsxs(Zd,{className:Z(s&&"text-warning-foreground"),children:[a.jsx(N3,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]}),u&&a.jsxs(Zd,{children:[a.jsx(rU,{})," ",is(u,"date-time")]})]}),d.length>0&&a.jsx(MO,{title:"Overall score",children:a.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:h,delta:p})=>a.jsx(xBt,{scorerId:f,value:h,delta:r?p:null},f))})})]})}const YT="min-w-0 px-4 py-3";function E0s({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=hn(),{data:i,isLoading:o,error:l}=Dsr({datasetId:e,experimentIdA:t,experimentIdB:n,queryOptions:{enabled:!!e&&!!t&&!!n}}),{data:c,isLoading:u}=G4({datasetId:e,experimentId:t,queryOptions:{enabled:!!e&&!!t}}),{data:d,isLoading:f}=G4({datasetId:e,experimentId:n,queryOptions:{enabled:!!e&&!!n}}),h=c&&d&&c.datasetVersion!==d.datasetVersion,p=i?.baselineId??t,m=t===p?n:t,v=c?.id===p?c:d,y=c?.id===m?c:d,{data:x,isLoading:b}=zhe({datasetId:e,experimentId:p,experimentStatus:v?.status,queryOptions:{enabled:!!e&&!!p}}),{data:S,isLoading:k}=zhe({datasetId:e,experimentId:m,experimentStatus:y?.status,queryOptions:{enabled:!!e&&!!m}}),{data:j}=yS({experimentId:p,experimentStatus:v?.status,queryOptions:{enabled:!!p}}),{data:C}=yS({experimentId:m,experimentStatus:y?.status,queryOptions:{enabled:!!m}}),T=g.useMemo(()=>k0s({comparison:i,baselineId:p,contenderId:m,baselineResults:x,contenderResults:S,baselineScores:j,contenderScores:C}),[i,p,m,x,S,j,C]),_=g.useMemo(()=>[...new Set(T.flatMap(I=>Object.keys(I.deltas)))].sort(),[T]),N=g.useMemo(()=>{const I=(D,z)=>{const Q=T.map(q=>q[D].scores.find(B=>B.scorerId===z)?.value).filter(q=>q!=null);return Q.length>0?Q.reduce((q,B)=>q+B,0)/Q.length:null},P=_.map(D=>({scorerId:D,average:I("baseline",D),delta:null})),A=_.map(D=>{const z=I("baseline",D),Q=I("contender",D);return{scorerId:D,average:Q,delta:z!=null&&Q!=null?Q-z:null}});return{baseline:P,contender:A}},[T,_]);return o||u||f?a.jsx("div",{className:"flex h-64 items-center justify-center",children:a.jsx(An,{})}):l?a.jsx(Wt,{variant:"warning",title:"Error loading comparison",children:a.jsx(Wt.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!i||i.items.length===0?a.jsx(Y,{as:"p",variant:"body",tone:"muted",className:"py-5 text-center",children:"No comparison data"}):a.jsx("div",{className:"grid gap-4",children:a.jsxs("div",{role:"table","aria-label":"Experiments comparison",className:"grid",children:[a.jsxs("div",{role:"row",className:"grid border-y border-border xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-border",children:[a.jsx("div",{role:"columnheader","aria-label":"Items",className:Z("text-muted-foreground",`${YT} uppercase`),children:a.jsx(Y,{as:"span",variant:"caption",className:"block",children:"Items"})}),a.jsx("div",{role:"columnheader","aria-label":"Baseline",className:YT,children:a.jsx(LJe,{side:"baseline",experiment:v??void 0,summary:N.baseline,versionMismatch:h??void 0})}),a.jsx("div",{role:"columnheader","aria-label":"Contender",className:YT,children:a.jsx(LJe,{side:"contender",experiment:y??void 0,summary:N.contender,versionMismatch:h??void 0,showDeltas:!0})})]}),T.map(I=>{const P=Object.entries(I.deltas).flatMap(([A,D])=>D==null||D===0?[]:[{scorerId:A,delta:D}]);return a.jsxs("div",{role:"row","aria-label":I.itemId,className:"grid border-b border-border xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-border",children:[a.jsxs("div",{role:"cell",className:`${YT} grid content-start gap-1`,children:[a.jsx(r,{href:s.datasetItemLink(e,I.itemId),"aria-label":`Open item ${I.itemId}`,className:Z(I.baseline.present&&I.contender.present?"text-muted-foreground":"text-placeholder","flex items-start gap-1.5 break-all hover:underline [&>svg]:mt-0.5 [&>svg]:size-3.5 [&>svg]:shrink-0"),children:a.jsx(Y,{as:"span",variant:"caption",font:"mono",className:"min-w-0",children:I.itemId})}),P.length>0&&a.jsx("span",{className:"flex flex-wrap items-center gap-2",children:P.map(({scorerId:A,delta:D})=>a.jsx(yBt,{delta:D},A))}),a.jsxs("div",{className:"grid pt-3",children:[a.jsx(RJe,{label:"Input",value:I.input}),a.jsx(RJe,{label:"Ground truth",value:I.groundTruth})]})]}),a.jsx("div",{role:"cell","aria-label":"Baseline",className:YT,children:a.jsx(DJe,{side:"baseline",row:I,isLoading:b})}),a.jsx("div",{role:"cell","aria-label":"Contender",className:YT,children:a.jsx(DJe,{side:"contender",row:I,isLoading:k,showDeltas:!0})})]},I.itemId)})]})})}function I0s(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 XT=[hs("/experiments")],N0s=["createdAt","status"];function A0s(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,i]=g.useState(!1),[o,l]=g.useState(!1),[c,u]=g.useState([]),d=Lr(),[f,h]=pi(),{sort:p,onSortChange:m}=wk({searchParams:f,setSearchParams:h,allowedKeys:N0s}),v=g.useMemo(()=>p?{field:p.key,direction:p.direction==="asc"?"ASC":"DESC"}:void 0,[p]),y=f.get("dataset")??"all",x=g.useCallback(ue=>{h(ee=>{const se=new URLSearchParams(ee);return ue==="all"?se.delete("dataset"):se.set("dataset",ue),se},{replace:!0})},[h]),{targetType:b,targetId:S,setTargetType:k,setTargetId:j}=Q7t(),{data:C,isLoading:T,error:_}=ik(),{data:N,isLoading:I,error:P,isFetchingNextPage:A,hasNextPage:D,setEndOfListElement:z}=Mbs({datasetId:y==="all"?void 0:y,target:{targetType:b,targetId:S},orderBy:v}),{data:Q}=t0s(),q=g.useMemo(()=>C?.datasets??[],[C?.datasets]),B=g.useMemo(()=>N??[],[N]),V=g.useMemo(()=>x0s(q),[q]),H=g.useMemo(()=>I0s(Q),[Q]),M=T||I,G=P||_,L=ue=>{const ee=new Set(B.map(se=>se.id));u(se=>{const re=se.filter(ae=>ee.has(ae));return re.includes(ue)?re.filter(ae=>ae!==ue):re.length>=2?[re[0],ue]:[...re,ue]})},$=()=>{u([]),l(!1)},{selectedIds:F,selectedDatasetIds:U}=g.useMemo(()=>{const ue=new Map(B.map(se=>[se.id,se.datasetId])),ee=c.filter(se=>ue.has(se));return{selectedIds:ee,selectedDatasetIds:new Set(ee.map(se=>ue.get(se)))}},[B,c]),K=F.length===2&&U.size!==1?"not the same dataset":void 0,ne=()=>{if(F.length!==2||K)return;const[ue,ee]=F,[se]=U;if(!se)return;const re=new URLSearchParams({dataset:se,baseline:ue,contender:ee});d(`/experiments/compare?${re.toString()}`)};if(G&&_s(G))return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:XT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(ci,{variant:"fill"})]});if(P&&Ts(P))return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:XT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Js,{variant:"fill",resource:"experiments"})]});if(_&&Ts(_))return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:XT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Js,{variant:"fill",resource:"datasets"})]});if(G)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:XT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(tn,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:G.message})]});const X=a.jsx(XX,{open:s,onOpenChange:i,onSuccess:ue=>{d(`/experiments/${ue}`)}});if(B.length===0&&!M&&y==="all"&&!b)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:XT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(b0s,{onRunExperiment:()=>i(!0)}),X]});const te=n!=="all"||y!=="all"||e!==""||b!=="",oe=()=>{t(""),r("all"),h(ue=>{const ee=new URLSearchParams(ue);return ee.delete("dataset"),ee.delete(Cj),ee.delete(g1),ee},{replace:!0})};return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:XT}),actionRow:a.jsx(w0s,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:y,onDatasetFilterChange:x,datasetOptions:V,targetType:b,onTargetTypeChange:k,targetId:S,onTargetIdChange:j,onReset:oe,hasActiveFilters:te,onRunClick:()=>i(!0),onCompareClick:()=>l(!0),selection:o?{selectedCount:F.length,onExecuteCompare:ne,onCancelSelection:$,compareDisabledReason:K}:void 0}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(v0s,{experiments:B,datasets:q,reviewByExperiment:H,isLoading:M,search:e,statusFilter:n,datasetFilter:y,isFetchingNextPage:A,hasNextPage:D,setEndOfListElement:z,sort:p,onSortChange:m,selection:o?{selectedExperimentIds:F,onToggleSelection:L}:void 0}),X]})}function J9({experimentId:e}){const{Link:t,paths:n}=hn();return a.jsx(de,{render:a.jsx(t,{href:n.experimentLink(e)}),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function P0s({datasetId:e,experimentIdA:t,experimentIdB:n}){const[,r]=pi(),s=G4({datasetId:e,experimentId:t}),i=G4({datasetId:e,experimentId:n}),o=s.isLoading||i.isLoading,l=s.error??i.error;return l&&_s(l)?a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Compare"}),a.jsx(ci,{variant:"fill"})]}):l&&Ts(l)?a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Compare"}),a.jsx(Js,{variant:"fill",resource:"experiments"})]}):l&&!ok(l)?a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Compare"}),a.jsx(tn,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:l.message})]}):!o&&(l||!s.data||!i.data)?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(J9,{experimentId:t}),"and",a.jsx(J9,{experimentId:n}),"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.jsxs("div",{className:"flex items-center justify-between gap-4 px-4 py-3",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[a.jsx(Y,{as:"h1",variant:"heading",tone:"ink",children:"Experiments comparison"}),a.jsxs(Y,{variant:"caption",tone:"muted",className:"flex items-center gap-2",children:[a.jsx(J9,{experimentId:t}),"and",a.jsx(J9,{experimentId:n})]})]}),a.jsxs($n,{children:[a.jsx(In,{render:a.jsx(de,{onClick:()=>r({dataset:e,baseline:n,contender:t}),icon:a.jsx(Xut,{}),children:"Swap sides"})}),a.jsx(Nn,{children:"Switch baseline and contender"})]})]}),a.jsx(E0s,{datasetId:e,experimentIdA:t,experimentIdB:n})]})})}function $0s(){const[e]=pi(),t=e.get("dataset")??void 0,n=e.get("baseline")??void 0,r=e.get("contender")??void 0;return!t||!n||!r?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 experiments to compare."}),a.jsxs(Y,{className:"mt-2",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})]}):a.jsx(P0s,{datasetId:t,experimentIdA:n,experimentIdB:r})}const R0s=[hs("/experiments"),{id:"experiments-compare",label:"Compare"}];function M0s(){return a.jsx(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:R0s}),children:a.jsx($0s,{})})}function D0s(e){const{data:t}=$_({traceId:e,queryOptions:{enabled:!!e}}),r=t?.spans.find(o=>!o.parentSpanId)?.entityType==="agent",{supportsMetrics:s}=V6(),i=pve({traceIds:e?[e]:[],enabled:r&&s,autoRefetch:!1});return e?i.data?.get(e):void 0}const zJe="__create_tag__";function bBt({selectedResults:e,vocabulary:t,onAddTag:n,disabled:r,appearance:s="toolbar"}){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(pr,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),h=i.trim();return h.length>0&&!l.includes(h)?[{label:`Create "${h}"`,value:zJe},...f]:f},[l,c,i]),d=f=>{const h=f===zJe?i.trim():f;!h||c.has(h)||n(h)};return a.jsx(Ca,{"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(HS,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:s==="inline"?"ghost":"default",size:s==="inline"?"sm":"md",className:"w-auto min-w-0",disabled:r})}function ace(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function L0s({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(ad,{}),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(dp,{children:ace(s.args)})]}),n.length>0&&a.jsxs(Y,{as:"span",variant:"caption",className:"mt-1 block",children:["Unconsumed mocks: ",a.jsx(dp,{children:n.map(o=>ace(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:ace(o.args)})]}),a.jsx(Y,{as:"span",variant:"caption",className:`shrink-0 rounded px-2 py-0.5 ${z0s(o.outcome)}`,children:o.outcome})]},`${o.outcome}-${o.toolName}-${l}`))})]})}function z0s(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 F0s({result:e,itemId:t,fallback:n,title:r,onClose:s,...i}){const o=r??(t?`Experiment item ${t}`:`Result ${e?.id??""}`);return a.jsx($t,{open:!!(e??t),onClose:s,title:o,depth:1,size:"half",children:e?a.jsx(B0s,{result:e,onClose:s,...i}):t?a.jsxs(a.Fragment,{children:[a.jsxs($t.Header,{children:[a.jsx($t.CloseButton,{onClick:s,tooltip:"Close result panel"}),a.jsxs($t.Heading,{children:["Experiment item",a.jsx($t.CopyId,{id:t})]})]}),n]}):null})}function B0s({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=!!e?.error,y=e7(e?.input),x=e7(e?.output),b=e7(e?.groundTruth),S=c&&e.status!=="needs-review"&&e.status!=="complete",k=Array.isArray(e.tags)?e.tags:[],j=g.useMemo(()=>[e],[e]),C=!!u||k.length>0,{Link:T}=hn(),_=m&&e.traceId?e.traceId:void 0,{data:N}=qX({traceId:_,queryOptions:{enabled:!!_}}),I=D0s(e.traceId),P=a.jsxs($t.Content,{children:[a.jsxs("div",{className:"mb-6 grid gap-4",children:[a.jsxs(Lt,{children:[a.jsx(Lt.Key,{children:"Item Id"}),a.jsx(Lt.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),e.createdAt&&a.jsxs(a.Fragment,{children:[a.jsx(Lt.Key,{children:"Created"}),a.jsx(Lt.Value,{children:is(e.createdAt,"date-time")})]}),e.status&&a.jsxs(a.Fragment,{children:[a.jsx(Lt.Key,{children:"Status"}),a.jsx(Lt.Value,{children:a.jsx(OIe,{status:e.status})})]}),C&&a.jsxs(a.Fragment,{children:[a.jsx(Lt.Key,{children:"Tags"}),a.jsx(Lt.Value,{children:a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[k.map(A=>a.jsxs(GX,{value:A,className:u?"gap-1 pr-1":void 0,children:[A,u&&a.jsx("button",{type:"button","aria-label":`Remove tag ${A}`,disabled:f,onClick:()=>u(k.filter(D=>D!==A)),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:a.jsx(Ln,{className:"size-3"})})]},A)),u&&a.jsx(bBt,{appearance:"inline",selectedResults:j,vocabulary:d,onAddTag:A=>u([...k,A]),disabled:f})]})})]}),I&&a.jsxs(a.Fragment,{children:[a.jsx(Lt.Key,{children:"Input tokens"}),a.jsx(Lt.Value,{children:I.inputTokens!==void 0?rd(I.inputTokens):"—"}),a.jsx(Lt.Key,{children:"Output tokens"}),a.jsx(Lt.Value,{children:I.outputTokens!==void 0?rd(I.outputTokens):"—"}),a.jsx(Lt.Key,{children:"Cost"}),a.jsx(Lt.Value,{children:I.estimatedCost!==void 0?Om(I.estimatedCost,I.costUnit):"—"})]})]}),v&&a.jsx(Wt,{variant:"destructive",title:"Error",children:a.jsx(Wt.Message,{children:e7(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&a.jsxs(ke,{columns:"1fr 1fr",children:[a.jsxs(ke.Top,{children:[a.jsx(ke.TopCell,{children:"Scorer"}),a.jsx(ke.TopCell,{children:"Score"})]}),t.map(A=>o?a.jsxs(ke.RowButton,{featured:l===A.id,onClick:()=>o(A.id),children:[a.jsx(ke.Cell,{children:A.scorerId}),a.jsx(ke.TextCell,{font:"mono",children:A.score.toFixed(3)})]},A.id):a.jsxs(ke.RowStatic,{children:[a.jsx(ke.Cell,{children:A.scorerId}),a.jsx(ke.TextCell,{font:"mono",children:A.score.toFixed(3)})]},A.id))]}),e.toolMockReport&&a.jsx(L0s,{report:e.toolMockReport})]}),a.jsxs("div",{className:"grid gap-3",children:[a.jsx($t.CodeSection,{title:"Input",icon:a.jsx(fdt,{}),codeStr:y}),a.jsx($t.CodeSection,{title:"Output",icon:a.jsx(j1,{}),codeStr:x}),e.groundTruth!==void 0&&a.jsx($t.CodeSection,{title:"Ground Truth",icon:a.jsx(Fdt,{}),codeStr:b})]})]});return a.jsxs(a.Fragment,{children:[a.jsxs($t.Header,{children:[a.jsx($t.CloseButton,{onClick:s,tooltip:"Close result panel"}),a.jsxs($t.Heading,{children:["Result",a.jsx($t.CopyId,{id:e.id})]}),a.jsxs($t.HeaderActions,{children:[S&&a.jsx(de,{size:"sm",variant:"primary",onClick:()=>c(e.id),icon:a.jsx(E3,{}),children:"Flag for Review"}),p&&e.status==="needs-review"&&a.jsx(de,{size:"sm",variant:"primary",onClick:p,icon:a.jsx(_3,{}),children:"Mark as reviewed"}),h&&a.jsx(de,{size:"sm",variant:"ghost",render:a.jsx(T,{href:h}),tooltip:"See experiment","aria-label":"See experiment",children:a.jsx(oH,{})}),e.traceId&&i&&a.jsx(de,{size:"sm",variant:"ghost",onClick:i,tooltip:"See trace","aria-label":"See trace",children:a.jsx(ox,{})}),a.jsx($t.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Go to previous result",nextLabel:"Go to next result"})]})]}),_?a.jsxs(Hl,{defaultTab:"details",className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[a.jsx($t.Header,{children:a.jsxs(Gl,{variant:"pill-ghost",size:"sm",children:[a.jsx(ls,{value:"details",children:"Details"}),a.jsxs(ls,{value:"feedback",children:["Feedback",N?.pagination?.total!=null&&a.jsxs(a.Fragment,{children:[" (",N.pagination.total,")"]})]})]})}),a.jsx(Ls,{value:"details",flush:!0,children:P}),a.jsx(Ls,{value:"feedback",flush:!0,children:a.jsx($t.Content,{children:m({traceId:_})})})]}):P]})}function e7(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function V0s(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function U0s({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(q0s,{score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s})})}function q0s({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s}){const i=V0s(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(de,{size:"sm",variant:"ghost",onClick:s,tooltip:"See trace","aria-label":"See trace",children:a.jsx(ox,{})}),(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(yv,{}),codeStr:e.reason||o,simplified:!0}),!i&&a.jsxs(a.Fragment,{children:[a.jsx($t.CodeSection,{title:"Preprocess Prompt",icon:a.jsx(Hp,{}),codeStr:e.preprocessPrompt||o,simplified:!0}),a.jsx($t.CodeSection,{title:"Analyze Prompt",icon:a.jsx(Hp,{}),codeStr:e.analyzePrompt||o,simplified:!0}),a.jsx($t.CodeSection,{title:"Generate Score Prompt",icon:a.jsx(Hp,{}),codeStr:e.generateScorePrompt||o,simplified:!0}),a.jsx($t.CodeSection,{title:"Generate Reason Prompt",icon:a.jsx(Hp,{}),codeStr:e.generateReasonPrompt||o,simplified:!0})]})]})})]})}function wBt(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 SBt({result:e,scores:t,state:n,withQueryTrace:r,withFeedback:s,...i}){const o=wBt(t,e?.id),{navigate:l}=hn(),{featuredTraceId:c,setFeaturedTraceId:u,featuredSpanId:d,setFeaturedSpanId:f,featuredScoreId:h,setFeaturedScoreId:p,featuredScore:m}=n??o,v=I=>{p(P=>I===P?null:I),u(null),f(void 0)},y=I=>{I&&(u(I),f(void 0),p(null))},x=()=>{if(!h||!t)return;const I=t.findIndex(P=>P.id===h);if(I>=0&&I<t.length-1)return()=>p(t[I+1].id)},b=()=>{if(!h||!t)return;const I=t.findIndex(P=>P.id===h);if(I>0)return()=>p(t[I-1].id)},{data:S,isLoading:k}=Rbs({traceId:c,queryOptions:{enabled:!!c}}),j=S?.spans,C=j?.find(I=>!I.parentSpanId),{data:T}=qX({traceId:c??void 0,queryOptions:{enabled:s&&!!c}}),{data:_}=kIe({traceId:c??void 0,spanId:d,queryOptions:{enabled:s&&!!c&&!!d}}),{data:N}=hSe({traceId:c??void 0,spanId:C?.spanId,page:0,queryOptions:{enabled:!!c&&!!C?.spanId}});return a.jsxs(a.Fragment,{children:[a.jsx(F0s,{...i,result:e,scores:t,onScoreClick:v,featuredScoreId:h,onShowTrace:e?.traceId?()=>y(e.traceId):void 0,feedbackTabSlot:s?({traceId:I})=>a.jsx(NZ,{traceId:I},I):void 0}),a.jsx(U0s,{score:m??void 0,onNext:x(),onPrevious:b(),onClose:()=>p(null),onShowTrace:m?()=>y(m.traceId):void 0}),a.jsx(MIe,{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:(I,P)=>l(Tje(I,P)),feedbackTabBadge:s?T?.pagination?.total??void 0:void 0,feedbackTabSlot:s?({traceId:I})=>a.jsx(NZ,{traceId:I}):void 0,scoresTabBadge:N?.pagination?.total??void 0,scoresTabSlot:({traceId:I,rootSpanId:P})=>P?a.jsx(kEe,{traceId:I,spanId:P,onScoreSelect:A=>{t?.some(D=>D.id===A)&&(u(null),f(void 0),p(A))}}):null,spanFeedbackTabBadge:s?_?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:s?({traceId:I,spanId:P})=>I&&P?a.jsx(D9t,{traceId:I,spanId:P},`${I}:${P}`):null:void 0})]})}function kBt(e,t){const{data:n}=Tv({datasetId:e,queryOptions:{enabled:!!e}});return g.useMemo(()=>[...new Set([...n?.tags??[],...t.flatMap(r=>r.tags??[])])].sort(),[n?.tags,t])}function Q0s({withQueryTrace:e,withFeedback:t}){const{currentItemId:n,experimentId:r,datasetId:s,experimentStatus:i,results:o,isLoadingResults:l,hasNextPage:c,close:u,goToPreviousItem:d,goToNextItem:f}=sBt(),h=g.useMemo(()=>n?o.find(j=>j.itemId===n):void 0,[o,n]),{data:p}=yS({experimentId:r,experimentStatus:i,queryOptions:{enabled:!!r}}),{updateExperimentResult:m}=ul(),v=g.useCallback(async j=>{try{await m.mutateAsync({datasetId:s,experimentId:r,resultId:j,status:"needs-review"}),Ge("Result flagged for review")}catch{Ge.error("Failed to flag result for review")}},[s,r,m]),y=kBt(s,o),x=g.useCallback(async(j,C)=>{try{await m.mutateAsync({datasetId:s,experimentId:r,resultId:j,tags:C})}catch{Ge.error("Failed to update tags")}},[s,r,m]),b=g.useCallback(async j=>{try{await m.mutateAsync({datasetId:s,experimentId:r,resultId:j,status:"complete"}),Ge("Result marked as reviewed")}catch{Ge.error("Failed to complete result")}},[s,r,m]),S=h?p?.[h.itemId]:void 0,k=wBt(S,h?.id);return a.jsx(SBt,{result:h,itemId:n,fallback:l||c?a.jsx($t.LoadingData,{}):a.jsxs($t.NoData,{children:['No loaded result for item "',n,'".']}),scores:S,state:k,withQueryTrace:e,withFeedback:t,onPrevious:d,onNext:f,onClose:u,onComplete:h?()=>b(h.id):void 0,onFlagForReview:h?()=>{v(h.id)}:void 0,onTagsChange:h?j=>{x(h.id,j)}:void 0,tagVocabulary:y,isUpdatingTags:m.isPending})}function Z0s({selection:e}){const{selectedIds:t,selectedResults:n,tagVocabulary:r,isFlagging:s,isTagging:i}=e;if(t.size===0)return null;const o=s||i;return a.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap",children:[a.jsxs(de,{disabled:o,onClick:e.flagSelectedForReview,icon:a.jsx(E3,{}),children:["Flag ",t.size," to review"]}),a.jsx(bBt,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:o}),a.jsx(de,{icon:a.jsx(Ln,{}),variant:"ghost",onClick:e.clearSelection,children:"Clear"})]})}function OBt(e){const{data:t}=yS({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])}function lce({icon:e,typeLabel:t,subject:n,description:r,isLast:s=!1}){return a.jsxs("li",{className:"relative grid grid-cols-[auto_1fr] gap-x-2.5 pb-4 last:pb-0",children:[a.jsxs("div",{className:"flex flex-col items-center",children:[a.jsxs($n,{children:[a.jsx(In,{render:a.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground [&_svg]:size-3.5",role:"img","aria-label":t}),children:e}),a.jsx(Nn,{children:t})]}),!s&&a.jsx("span",{"aria-hidden":!0,className:"mt-1 w-px flex-1 bg-border"})]}),a.jsxs("div",{className:"grid min-w-0 gap-0.5",children:[a.jsx("div",{className:"flex min-h-5 items-center",children:a.jsx(Y,{tone:"ink",as:"span",variant:"caption",className:"block",children:n})}),a.jsx(Y,{variant:"meta",tone:"faint",children:r})]})]})}const cce="text-foreground inline-flex min-w-0 items-center gap-1.5 hover:underline";function W0s({experiment:e,className:t}){const{Link:n,paths:r}=hn(),s=fBt(),{scorers:i}=s,{data:o,isLoading:l}=Tv({datasetId:e.datasetId??"",queryOptions:{enabled:!!e.datasetId}}),c=OBt(e),u=e.targetType,d=e.targetId,f=mBt(e,s),h=(()=>{if(!d)return null;switch(u){case"agent":return r.agentLink(d);case"workflow":return r.workflowLink(d);case"scorer":return r.scorerLink(d);default:return null}})(),p=u&&hBt[u]||zo,m=u&&pBt[u]||"Evaluation target";return a.jsxs("ol",{className:Z("grid",t),children:[a.jsx(lce,{icon:a.jsx(pSe,{}),typeLabel:"Dataset",description:`Each item will be passed to the ${m.toLowerCase()}`,subject:e.datasetId?a.jsxs(n,{href:r.datasetLink(e.datasetId),className:cce,children:[a.jsx("span",{className:"truncate",children:l?a.jsx(bt,{className:"h-4 w-28"}):o?.name??e.datasetId}),e.datasetVersion!=null&&a.jsxs("span",{className:"shrink-0 text-muted-foreground",children:["(v",e.datasetVersion,")"]})]}):a.jsx("span",{className:"text-muted-foreground",children:"No dataset"})}),a.jsx(lce,{icon:a.jsx(p,{}),typeLabel:m,description:"Its output is then scored",subject:h?a.jsx(n,{href:h,className:cce,children:a.jsx("span",{className:"truncate",children:f})}):a.jsx("span",{className:"truncate text-muted-foreground",children:f})}),a.jsx(lce,{icon:a.jsx(jx,{}),typeLabel:"Scorers",description:"It gives a score by comparing ground truth",isLast:!0,subject:c.length===0?a.jsx("span",{className:"text-muted-foreground",children:"No scorer has produced a score yet"}):a.jsx("ul",{className:"grid min-w-0 gap-0.5",children:c.map(v=>{const y=i?.[v]?.scorer?.config?.name??v;return a.jsx("li",{className:"min-w-0",children:a.jsx(n,{href:r.scorerLink(v),className:cce,children:a.jsx("span",{className:"truncate",children:y})})},v)})})})]})}function JT({label:e,children:t}){return a.jsxs(a.Fragment,{children:[a.jsx(Lt.Key,{children:e}),a.jsx(Lt.Value,{className:"flex flex-wrap items-baseline justify-end gap-x-1.5 text-right",children:t})]})}function H0s({experiment:e,metrics:t}){const{data:n}=yS({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}}),r=e.status==="running"||e.status==="pending",s=g.useMemo(()=>{if(!n)return;const c=Object.values(n).flat();if(c.length!==0)return c.reduce((u,d)=>u+d.score,0)/c.length},[n]),i=e.startedAt??e.createdAt,o=i?new Date(i):null,l=(()=>{if(e.status==="running")return"Running…";if(!e.startedAt||!e.completedAt)return"—";const c=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return nf(c)??"—"})();return a.jsxs(Lt,{children:[a.jsx(JT,{label:"Avg score",children:s===void 0?a.jsx("span",{className:"text-muted-foreground",children:"—"}):a.jsxs(a.Fragment,{children:[a.jsx("span",{children:s.toFixed(3)}),r&&a.jsx("span",{className:"text-muted-foreground",children:"· so far"})]})}),a.jsx(JT,{label:"Items",children:r?a.jsxs("span",{className:"text-muted-foreground",children:[(e.succeededCount??0)+(e.failedCount??0),"/",e.totalItems," items processed"]}):a.jsxs(a.Fragment,{children:[a.jsxs("span",{children:[e.totalItems," item",e.totalItems===1?"":"s"]}),(e.failedCount??0)>0&&a.jsxs("span",{className:"text-destructive-foreground",children:["· ",e.failedCount," errored"]})]})}),a.jsx(JT,{label:"Started",children:o?a.jsx("span",{title:i1e(o),children:is(o,"date-time")}):a.jsx("span",{children:"—"})}),a.jsx(JT,{label:"Duration",children:a.jsx("span",{children:l})}),t?.isEnabled&&a.jsxs(a.Fragment,{children:[a.jsx(JT,{label:"Tokens",children:t.data?.totalTokens==null?a.jsx("span",{className:"text-muted-foreground",children:"—"}):a.jsxs(a.Fragment,{children:[a.jsx("span",{children:rd(t.data.totalTokens)}),t.data.estimatedCost!=null&&a.jsxs("span",{className:"text-muted-foreground",children:["· ",Om(t.data.estimatedCost,t.data.costUnit)]}),r&&a.jsx("span",{className:"text-muted-foreground",children:"· so far"})]})}),a.jsx(JT,{label:"Latency (avg)",children:t.data?.avgAgentDurationMs==null?a.jsx("span",{className:"text-muted-foreground",children:"—"}):a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",children:nf(Math.round(t.data.avgAgentDurationMs))})})]})]})}function G0s({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=hn(),{data:s}=eg(),i=g.useMemo(()=>{if(!e)return[];const o={};for(const l of Object.values(e))for(const c of l)o[c.scorerId]||(o[c.scorerId]={sum:0,count:0}),o[c.scorerId].sum+=c.score,o[c.scorerId].count++;return Object.entries(o).map(([l,{sum:c,count:u}])=>({scorerId:l,avg:c/u})).sort((l,c)=>l.scorerId.localeCompare(c.scorerId))},[e]);if(i.length===0){const o=t==="running"||t==="pending",l=e!==void 0;let c,u;return o?(c="Experiment in progress",u="Summary metrics will appear here once the experiment completes."):l?(c="No scorers configured",u="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(c="Loading scores",u="Fetching scorer results…"),a.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[a.jsx(yv,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:c}),a.jsx(Y,{as:"span",variant:"caption",className:"truncate",children:u})]})}return a.jsx("div",{className:"flex flex-col gap-2",children:i.map(({scorerId:o,avg:l})=>{const c=s?.[o]?.scorer?.config?.name??o;return a.jsxs(Md,{className:"min-w-0 p-3",children:[a.jsxs(n,{href:r.scorerLink(o),className:"flex min-w-0 items-center gap-1.5 text-muted-foreground hover:underline [&>svg]:size-3 [&>svg]:shrink-0 [&>svg]:text-muted-foreground",children:[a.jsxs($n,{children:[a.jsx(In,{render:a.jsx(jx,{role:"img","aria-label":"Scorer"})}),a.jsx(Nn,{children:"Scorer"})]}),a.jsx(Y,{as:"span",variant:"caption",className:"truncate",children:c})]}),a.jsxs(Y,{as:"strong",variant:"subheading",tone:"muted",children:[l.toFixed(3),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"ml-1.5",children:"avg score"})]})]},o)})})}function uce({title:e,children:t}){return a.jsxs("section",{className:"grid gap-3",children:[a.jsx(Y,{as:"h2",variant:"subheading",tone:"ink",children:e}),t]})}function K0s({experiment:e,metrics:t,className:n}){const{Link:r,paths:s}=hn(),{data:i}=yS({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}}),o=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${s.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return a.jsxs(hc,{as:"aside","aria-label":"Experiment details",className:Z("grid content-start gap-5 p-5",n),children:[a.jsxs(uce,{title:"Pipeline",children:[a.jsx(W0s,{experiment:e}),e.agentVersion&&a.jsxs(Lt,{children:[a.jsx(Lt.Key,{children:"Version"}),o?a.jsx(Lt.ValueLink,{href:o,as:r,children:e.agentVersion}):a.jsx(Lt.Value,{children:e.agentVersion})]})]}),a.jsx(uce,{title:"Run",children:a.jsx(H0s,{experiment:e,metrics:t})}),a.jsx(uce,{title:"Scorers",children:a.jsx(G0s,{scoresByItemId:i,experimentStatus:e.status})})]})}function Y0s({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[i,o]=g.useState(e.description??""),{updateExperiment:l}=ul(),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()}),Ge.success("Experiment renamed"),n(!1)}catch(f){Ge.error(`Failed to rename experiment: ${f instanceof Error?f.message:"Unknown error"}`)}};return a.jsx(rs,{open:t,onOpenChange:n,pending:l.isPending,children:a.jsxs(ss,{children:[a.jsx(es,{children:a.jsx(Kr,{children:"Rename Experiment"})}),a.jsxs(Qa,{onSubmit:u,children:[a.jsxs(Gr,{children:[a.jsxs(ft,{children:[a.jsx(lt,{required:!0,children:"Name"}),a.jsx(Sn,{required:!0,value:r,onChange:d=>s(d.target.value),placeholder:"Enter experiment name",autoFocus:!0})]}),a.jsxs(ft,{children:[a.jsx(lt,{children:"Description"}),a.jsx(Sn,{value:i,onChange:d=>o(d.target.value),placeholder:"Enter experiment description (optional)"})]})]}),a.jsxs(Ho,{children:[a.jsx(ja,{children:"Cancel"}),a.jsx(Oa,{type:"submit",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})]})})}const X0s=["agent","workflow","scorer"];function J0s({experiment:e}){const[t,n]=g.useState(!1),r=Lr(),{paths:s}=hn(),i=OBt(e),o=X0s.find(l=>l===e.targetType);return!e.datasetId||!o||!e.targetId?null:a.jsxs(a.Fragment,{children:[a.jsx(de,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",icon:a.jsx(ku,{}),children:"Rerun"}),t&&a.jsx(XX,{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:l=>{r(s.experimentLink(l))}},i.join(","))]})}function ews({experiment:e,onDeleteClick:t,children:n}){const{Link:r}=hn(),[s,i]=g.useState(!1),o=!!e.datasetId,l=o||!!t;return a.jsxs(a.Fragment,{children:[a.jsxs(Xn,{children:[a.jsxs(Xn.Start,{className:"whitespace-nowrap",children:[a.jsx(J0s,{experiment:e}),a.jsx(de,{render:a.jsx(r,{href:ZMr(e.id)}),icon:a.jsx(E3,{}),children:"Review queue"}),l&&a.jsxs(ut,{children:[a.jsx(ut.Trigger,{asChild:!0,children:a.jsx(de,{size:"lg","aria-label":"Experiment actions menu",children:a.jsx(j0,{})})}),a.jsxs(ut.Content,{align:"start",className:"w-48",children:[o&&a.jsxs(ut.Item,{onSelect:()=>i(!0),children:[a.jsx(od,{})," Rename Experiment"]}),t&&a.jsxs(ut.Item,{onSelect:t,variant:"destructive",children:[a.jsx(Go,{})," Delete Experiment"]})]})]})]}),n&&a.jsx(Xn.End,{children:n})]}),s&&a.jsx(Y0s,{experiment:e,open:!0,onOpenChange:i})]})}const jBt=()=>{const{experimentId:e}=fr(),{data:t}=dSe();return{experimentId:e,experiment:t?.experiments?.find(n=>n.id===e)}};function tws(){const{experimentId:e,experiment:t}=jBt();if(!e)return null;const n=e.length>8?`${e.slice(0,8)}...`:e;return t?.name||n}function nws(){const{experiment:e}=jBt();return e?a.jsx(Ebs,{status:e.status}):null}function rws({datasetId:e,experimentId:t}){const[n,r]=g.useState(!1),{updateExperimentResult:s}=ul();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?Ge(`Tag "${o}" added to ${u} result${u>1?"s":""}`):Ge.error("Failed to add tag")},[e,t,n,s]),isPending:n}}function sws({datasetId:e,experimentId:t,results:n}){const[r,s]=g.useState(new Set),[i,o]=g.useState(!1),{updateExperimentResult:l}=ul(),{addTag:c,isPending:u}=rws({datasetId:e,experimentId:t}),d=kBt(e,n),f=g.useMemo(()=>n.filter(y=>r.has(y.id)),[n,r]),h=g.useCallback(y=>{s(x=>{const b=new Set(x);return b.has(y)?b.delete(y):b.add(y),b})},[]),p=g.useCallback(()=>s(new Set),[]),m=g.useCallback(async()=>{if(i||r.size===0)return;o(!0);const y=new Set;try{for(const x of r)try{await l.mutateAsync({datasetId:e,experimentId:t,resultId:x,status:"needs-review"}),y.add(x)}catch{}}finally{o(!1)}y.size>0&&(s(x=>{const b=new Set(x);for(const S of y)b.delete(S);return b}),Ge(`${y.size} result${y.size>1?"s":""} flagged for review`))},[e,t,i,r,l]),v=g.useCallback(y=>c(y,f),[c,f]);return{selectedIds:r,selectedResults:f,toggleSelect:h,clearSelection:p,flagSelectedForReview:m,isFlagging:i,addTagToSelected:v,isTagging:u,tagVocabulary:d}}const iws=[],ows=["startedAt"];function t7({crumbs:e,children:t}){return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{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 aws(){const{experimentId:e,itemId:t}=fr(),n=[hs("/experiments"),{id:"experiment",Component:tws,icon:nws,to:e?`/experiments/${encodeURIComponent(e)}`:void 0},...t?[{id:"experiment-items",label:"Items"},{id:"experiment-item",label:ySe(t)}]:[]],r=Lr(),[s,i]=g.useState(!1),o=UX(),[l,c]=pi(),{sort:u,onSortChange:d}=wk({searchParams:l,setSearchParams:c,allowedKeys:ows}),f=g.useMemo(()=>u?{field:u.key,direction:u.direction==="asc"?"ASC":"DESC"}:void 0,[u]),{data:h,isLoading:p}=dSe(),v=h?.experiments?.find(A=>A.id===e)?.datasetId??"",{data:y,isLoading:x,error:b}=G4({datasetId:v,experimentId:e??"",queryOptions:{enabled:!!v&&!!e}}),{data:S,isLoading:k,setEndOfListElement:j,isFetchingNextPage:C,hasNextPage:T}=zhe({datasetId:v,experimentId:e??"",experimentStatus:y?.status,orderBy:f,queryOptions:{enabled:!!v&&!!e}}),{supportsMetrics:_}=V6(),N=$bs({experimentId:e,experimentStatus:y?.status,supportsMetrics:_,queryOptions:{enabled:!!e&&_}}),I=sws({datasetId:v,experimentId:e??"",results:S??iws});if(!e||p||x)return null;if(b&&_s(b))return a.jsx(t7,{crumbs:n,children:a.jsx(ci,{})});if(b&&Ts(b))return a.jsx(t7,{crumbs:n,children:a.jsx(Js,{resource:"datasets"})});const P=a.jsx(t7,{crumbs:n,children:a.jsx(tn,{titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:a.jsx(de,{render:a.jsx(oc,{to:"/experiments"}),icon:a.jsx(fd,{}),children:"Back to Experiments"})})});return b&&ok(b)?P:b?a.jsx(t7,{crumbs:n,children:a.jsx(tn,{tone:"error",titleSlot:"Failed to load experiment",descriptionSlot:b instanceof Error?b.message:"An unexpected error occurred. Please try again."})}):!v||!y?P:a.jsx(Sbs,{experimentId:e,datasetId:v,experimentStatus:y.status,results:S??[],isLoadingResults:k,hasNextPage:T,children:a.jsxs("div",{className:"h-full",children:[a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:n}),actionRow:a.jsx(ews,{experiment:y,onDeleteClick:()=>i(!0),children:a.jsx(Z0s,{selection:I})}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-4 overflow-visible",children:[a.jsx(Tbs,{experimentId:e,experimentStatus:y.status,results:S??[],isLoading:k,setEndOfListElement:j,isFetchingNextPage:C,hasNextPage:T,selectedIds:I.selectedIds,onToggleSelect:I.toggleSelect,sort:u,onSortChange:d}),a.jsx(K0s,{experiment:y,metrics:N,className:"w-80 overflow-y-auto"})]})]}),a.jsx(Q0s,{withQueryTrace:o.enabled,withFeedback:o.enabled}),a.jsx(uBt,{open:s,onOpenChange:i,experimentId:e,experimentName:y.name??void 0,onSuccess:()=>r("/experiments")})]})})}function lws({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(Sn,{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(Fn,"p-0.5"),children:a.jsx(pr,{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(Fn,"p-0.5 opacity-0 transition-opacity group-hover:opacity-100"),title:"Edit tag",children:a.jsx(od,{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(Ln,{className:"h-3 w-3"})})]})}function cws({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(bp,{open:o,onOpenChange:l,children:[a.jsx(rf,{asChild:!0,children:a.jsxs(de,{size:i,icon:a.jsx(HS,{}),children:["Tag ",e," items"]})}),a.jsxs(nh,{className:"w-56 p-2",align:"end",children:[a.jsx(Sn,{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(Ln,{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 uws=[{name:"itemId",label:"Item ID",size:"auto"},{name:"input",label:"Input",size:"minmax(0,1fr)"},{name:"tags",label:"Tags",size:"auto"},{name:"scores",label:"Scores",size:"6rem"}],dce="__untagged__",n7="all",dws=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}];function fws({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=Ye(),{paths:v}=hn(),{data:y}=Tv({datasetId:e??"",queryOptions:{enabled:!!e}}),{data:x,isLoading:b}=Jbs({experimentId:t,targetType:s,targetId:i,experiments:n,isLoadingExperiments:r}),{data:S,isLoading:k}=e0s({experimentId:t,targetType:s,targetId:i,experiments:n,isLoadingExperiments:r}),{updateExperimentResult:j}=ul(),[C,T]=g.useState(o??null);g.useEffect(()=>{o!==void 0&&T(o)},[o]);const[_,N]=g.useState(null),[I,P]=g.useState(new Set),[A,D]=g.useState(!1),[z,Q]=g.useState(!1),[q,B]=g.useState(!1),[V,H]=g.useState(""),[M,G]=g.useState(""),[L,$]=g.useState(""),[F,U]=g.useState([]),[K,ne]=g.useState(!1),X=g.useMemo(()=>x??[],[x]),te=g.useMemo(()=>{const me=new Set;if(y?.tags)for(const Le of y.tags)me.add(Le);for(const Le of X)for(const et of Le.tags)me.add(et);return[...me].sort()},[y,X]),oe=g.useCallback(me=>{!y||!e||(y.tags??[]).includes(me)},[y,e]),ue=g.useMemo(()=>_?_===dce?X.filter(me=>me.tags.length===0):X.filter(me=>me.tags.includes(_)):X,[X,_]),ee=g.useMemo(()=>{const me=new Map;let Le=0;for(const Ot of X){Ot.tags.length===0&&Le++;for(const Bt of Ot.tags)me.set(Bt,(me.get(Bt)??0)+1)}const et=[...me.entries()].sort((Ot,Bt)=>Bt[1]-Ot[1]).map(([Ot])=>({value:Ot,label:Ot}));return[{value:n7,label:"All tags"},...Le>0?[{value:dce,label:"Untagged"}]:[],...et]},[X]),se=!!_||A,re=g.useCallback(()=>{N(null),D(!1),T(null)},[]),ae=g.useCallback((me,Le)=>{const et=X.find(Ot=>Ot.id===me);et?.experimentId&&et?.datasetId&&j.mutate({datasetId:et.datasetId,experimentId:et.experimentId,resultId:et.id,tags:Le})},[X,j]),pe=g.useCallback(me=>{const Le=X.find(et=>et.id===me);P(et=>{const Ot=new Set(et);return Ot.delete(me),Ot}),C===me&&T(null),Le?.experimentId&&Le?.datasetId&&j.mutate({datasetId:Le.datasetId,experimentId:Le.experimentId,resultId:Le.id,status:null})},[X,j,C]),ve=g.useCallback(me=>{const Le=X.find(et=>et.id===me);P(et=>{const Ot=new Set(et);return Ot.delete(me),Ot}),C===me&&T(null),Le?.experimentId&&Le?.datasetId&&j.mutate({datasetId:Le.datasetId,experimentId:Le.experimentId,resultId:Le.id,status:"complete"})},[X,j,C]),he=g.useMemo(()=>{const me=A?S??[]:ue;return!A||!_?me:_===dce?me.filter(Le=>Le.tags.length===0):me.filter(Le=>Le.tags.includes(_))},[A,S,ue,_]),Oe=A?k:!1,Ee=g.useMemo(()=>new Set(he.map(me=>me.id)),[he]),Fe=g.useMemo(()=>[...I].filter(me=>Ee.has(me)).length,[I,Ee]),qe=he.length>0&&Fe===he.length,Be=g.useCallback(me=>{P(Le=>{const et=new Set(Le);return et.has(me)?et.delete(me):et.add(me),et})},[]),Pe=g.useCallback(()=>{P(qe?new Set:new Set(he.map(me=>me.id)))},[qe,he]),Ve=g.useCallback(me=>{for(const Le of I){const et=X.find(Ot=>Ot.id===Le);et&&!et.tags.includes(me)&&ae(Le,[...et.tags,me])}},[X,I,ae]),Ce=g.useCallback(me=>{for(const Le of I){const et=X.find(Ot=>Ot.id===Le);et&&et.tags.includes(me)&&ae(Le,et.tags.filter(Ot=>Ot!==me))}},[X,I,ae]),Te=g.useCallback(()=>{for(const me of I)ve(me);P(new Set)},[I,ve]),_e=g.useCallback(()=>{for(const me of I)pe(me);P(new Set)},[I,pe]),ce=g.useCallback(()=>{H(""),B(!0)},[]),ye=g.useCallback(async()=>{if(!(!M||!L)){Q(!0),B(!1);try{const me=X.filter(et=>I.has(et.id));if(me.length===0){Q(!1);return}const Le=await m.clusterFailures({modelId:`${M}/${L}`,items:me.map(et=>({id:et.id,input:et.input,output:et.output??void 0,error:typeof et.error=="string"?et.error:et.error?String(et.error):void 0,scores:et.scores,existingTags:et.tags.length>0?et.tags:void 0})),availableTags:te.length>0?te:void 0,prompt:V||void 0});Le.proposedTags&&Le.proposedTags.length>0&&(U(Le.proposedTags.map(et=>({...et,accepted:!0}))),ne(!0))}catch(me){console.error("Analysis failed:",me)}finally{Q(!1)}}},[M,L,X,I,m,te,V]),Me=g.useCallback(()=>{for(const me of F){if(!me.accepted)continue;const Le=X.find(et=>et.id===me.itemId);if(Le){const et=[...new Set([...Le.tags,...me.tags])];ae(Le.id,et)}}ne(!1)},[F,X,ae]),Ie=g.useCallback(me=>{T(Le=>Le===me?null:me)},[]),le=g.useMemo(()=>C?he.find(me=>me.id===C)??null:null,[C,he]),{data:xe}=yS({experimentId:le?.experimentId??"",queryOptions:{enabled:!!le?.experimentId}}),Se=C?he.findIndex(me=>me.id===C):-1,$e=Se>0?()=>T(he[Se-1].id):void 0,ze=Se>=0&&Se<he.length-1?()=>T(he[Se+1].id):void 0,He=!A&&I.size>0,De=!!d&&!A&&ue.length>0,tt=A?"completed":"review",Ze=me=>{D(me==="completed"),T(null)},rt=a.jsxs(Xn,{children:[a.jsx(Xn.Start,{children:c?a.jsxs(a.Fragment,{children:[l,c({status:tt,onStatusChange:Ze,tag:_,onTagChange:N,tagOptions:ee.filter(me=>me.value!==n7)})]}):a.jsxs(a.Fragment,{children:[l,a.jsxs(Ur,{value:tt,onValueChange:me=>Ze(me==="completed"?"completed":"review"),children:[a.jsx(Qr,{"aria-label":"Status",size:"md",className:"whitespace-nowrap",children:a.jsx(qr,{placeholder:"Select an option"})}),a.jsx(Zr,{children:dws.map(me=>a.jsx(or,{value:me.value,children:me.label},me.value))})]}),ee.length>1&&a.jsxs(Ur,{value:_??n7,onValueChange:me=>N(me===n7?null:me),children:[a.jsx(Qr,{"aria-label":"Tags",size:"md",className:"whitespace-nowrap",children:a.jsx(qr,{placeholder:"Select an option"})}),a.jsx(Zr,{children:ee.map(me=>a.jsx(or,{value:me.value,children:me.label},me.value))})]}),se&&a.jsx(de,{onClick:re,size:"sm",variant:"default",icon:a.jsx(Ln,{}),children:"Reset"})]})}),(He||u||De)&&a.jsxs(Xn.End,{children:[u,De&&a.jsxs(de,{size:"md",onClick:()=>d?.(ue.map(me=>({input:me.input,output:me.output}))),children:[a.jsx(Nt,{size:"xs",children:a.jsx(yv,{})}),"Create Scorer"]}),He&&a.jsxs(a.Fragment,{children:[a.jsx(cws,{size:"md",selectedCount:I.size,vocabulary:te,onApplyTag:Ve,onRemoveTag:Ce,onNewTag:me=>Ve(me)}),a.jsx(de,{variant:"primary",onClick:Te,icon:a.jsx(_3,{}),children:"Mark as reviewed"}),a.jsxs(ut,{children:[a.jsx(ut.Trigger,{asChild:!0,children:a.jsx(de,{disabled:z,"aria-label":"More actions",children:z?a.jsx(An,{className:"h-4 w-4"}):a.jsx(GD,{})})}),a.jsxs(ut.Content,{align:"end",children:[a.jsxs(ut.Item,{onSelect:ce,children:[a.jsx(Nt,{size:"xs",children:a.jsx(dH,{})}),"Analyze"]}),a.jsx(ut.Separator,{}),a.jsxs(ut.Item,{onSelect:_e,children:[a.jsx(Nt,{size:"xs",children:a.jsx(Go,{})}),"Remove from queue"]})]})]})]})]})]});if(b)return a.jsxs(St,{breadcrumbs:f,actionRow:rt,children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(An,{fill:!0})]});const At=a.jsx(SBt,{withQueryTrace:h,withFeedback:p,result:le??void 0,title:`Review item ${le?.id??""}`,scores:le?xe?.[le.itemId]:void 0,experimentLink:le?.experimentId?v.experimentItemLink(le.experimentId,le.itemId):void 0,tagVocabulary:te,onTagsChange:A||!le?void 0:me=>{ae(le.id,me);for(const Le of me)te.includes(Le)||oe(Le)},onComplete:A||!le?void 0:()=>ve(le.id),onPrevious:$e,onNext:ze,onClose:()=>T(null)});return a.jsxs(St,{breadcrumbs:f,actionRow:rt,children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(rs,{open:q,onOpenChange:B,children:a.jsxs(ss,{children:[a.jsxs(es,{children:[a.jsx(Kr,{children:"Analyze Items"}),a.jsx(Mo,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),a.jsxs(Gr,{children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs(ft,{className:"gap-1",children:[a.jsx(lt,{children:"Provider"}),a.jsx(dk,{value:M,onValueChange:G})]}),a.jsxs(ft,{className:"gap-1",children:[a.jsx(lt,{children:"Model"}),a.jsx(fk,{llmId:M,value:L,onValueChange:$})]})]}),a.jsxs(Y,{variant:"meta",tone:"muted",children:[I.size," item",I.size!==1?"s":""," will be analyzed"]}),a.jsxs(ft,{className:"gap-1",children:[a.jsx(lt,{children:"Instructions (optional)"}),a.jsx(Ou,{className:"text-caption",value:V,onChange:me=>H(me.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3})]})]}),a.jsxs(Ho,{children:[a.jsx(ja,{children:"Cancel"}),a.jsx(Oa,{onConfirm:ye,disabled:!M||!L||z,children:"Analyze"})]})]})}),a.jsx(rs,{open:K,onOpenChange:ne,children:a.jsxs(ss,{size:"lg",children:[a.jsxs(es,{children:[a.jsx(Kr,{children:"Review Proposed Tags"}),a.jsxs(Mo,{children:[F.filter(me=>me.accepted).length," of ",F.length," proposals selected"]})]}),a.jsx(Gr,{children:F.map((me,Le)=>{const et=X.find(Ot=>Ot.id===me.itemId);return a.jsx("div",{className:Z("rounded-lg border p-3",!me.accepted&&"opacity-50"),children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Iu,{checked:me.accepted,onCheckedChange:Ot=>U(Bt=>Bt.map((Qt,yt)=>yt===Le?{...Qt,accepted:!!Ot}:Qt))}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"block truncate",children:et?typeof et.input=="string"?et.input.slice(0,100):JSON.stringify(et.input).slice(0,100):me.itemId}),a.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:me.tags.map((Ot,Bt)=>a.jsx(lws,{tag:Ot,onRename:Qt=>U(yt=>yt.map((bn,yn)=>yn===Le?{...bn,tags:bn.tags.map((we,Ne)=>Ne===Bt?Qt:we)}:bn)),onRemove:()=>U(Qt=>Qt.map((yt,bn)=>bn===Le?{...yt,tags:yt.tags.filter((yn,we)=>we!==Bt)}:yt))},`${Ot}-${Bt}`))}),me.reason&&a.jsx(Y,{variant:"meta",tone:"muted",className:"mt-1 block italic",children:me.reason})]})]})},me.itemId)})}),a.jsxs(Ho,{children:[a.jsx(ja,{children:"Cancel"}),a.jsxs(Oa,{onConfirm:Me,disabled:F.filter(me=>me.accepted).length===0,children:["Accept ",F.filter(me=>me.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:Oe?a.jsx(An,{fill:!0}):he.length===0?a.jsx(tn,{titleSlot:A?"No completed reviews yet":"No items to review",descriptionSlot:A?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here.",variant:"fill"}):a.jsx(iBt,{results:he,isLoading:!1,featuredResultId:C,onResultClick:Ie,columns:uws,selectedIds:A?void 0:I,onToggleSelect:A?void 0:Be,onToggleSelectAll:A?void 0:Pe})}),At]})]})}const JX="targetType",eJ="targetId",tJ="experiment",nJ="status",rJ="tag",FJe={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},hws=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}],BJe={[JX]:{icon:sdt,hue:"purple"},[eJ]:{icon:gdt,hue:"pink"},[tJ]:{icon:oH,hue:"pink"},[nJ]:{icon:_3,hue:"orange"},[rJ]:{icon:HS,hue:"pink"}},uM=(e,t)=>({id:e,label:t,icon:BJe[e].icon,color:Di(BJe[e].hue),strict:!0}),pws=[{id:"is",label:"is"}],dM=(e,t)=>({id:e,fieldId:e,operatorId:"is",value:t}),mws=({targetType:e,targetId:t,experimentId:n,status:r,tag:s})=>{const i=[];return e&&i.push(dM(JX,e)),t&&i.push(dM(eJ,t)),n&&i.push(dM(tJ,n)),r!=="review"&&i.push(dM(nJ,r)),s&&i.push(dM(rJ,s)),i},gws=e=>{const t=s=>{const i=e.find(o=>o.fieldId===s);return typeof i?.value=="string"?i.value:""},n=t(JX),r=KX(n)?n:"";return{targetType:r,targetId:r?t(eJ):"",experimentId:t(tJ),status:t(nJ)==="completed"?"completed":"review",tag:t(rJ)||null}};function vws({targetType:e,targetId:t,experimentId:n,status:r,tag:s,experiments:i,tagOptions:o,onChange:l}){const{data:c}=pf({queryOptions:{enabled:e==="agent"}}),{data:u}=vp({queryOptions:{enabled:e==="workflow"}}),{data:d}=eg({enabled:e==="scorer"}),{data:f}=c_({queryOptions:{enabled:e==="processor"}}),h=g.useMemo(()=>{const m=e==="agent"?Object.entries(c??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(d??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):e==="processor"?Object.entries(f??{}).map(([v,y])=>({value:v,label:y.name??v})):[];return[{...uM(JX,"Target type"),suggestions:zIe.map(v=>({value:v,label:FJe[v]}))},{...uM(eJ,e?FJe[e]:"Target"),hidden:!e,suggestions:m},{...uM(tJ,"Experiment"),suggestions:i.map(v=>({value:v.id,label:dBt(v)}))},{...uM(nJ,"Status"),suggestions:hws},{...uM(rJ,"Tag"),hidden:o.length===0,suggestions:o}]},[e,c,u,d,f,i,o]),p=g.useMemo(()=>mws({targetType:e,targetId:t,experimentId:n,status:r,tag:s}),[e,t,n,r,s]);return a.jsxs(Kg,{fields:h,operators:pws,value:p,onValueChange:m=>l(gws(m)),createItemId:m=>m,"aria-label":"Review queue filters",className:"min-w-64 flex-1",children:[a.jsx(Kg.Chips,{}),a.jsx(Kg.Input,{placeholder:"Filter review queue…"})]})}const r7=[hs("/experiments"),hs("/experiments/review-queue")],fce="experiment",VJe="review";function yws(){const[e,t]=pi(),n=e.get(Cj),r=KX(n)?n:"",s=r?e.get(g1)??"":"",i=e.get(fce),o=e.get(VJe),{Link:l,paths:c}=hn(),u=UX(),{data:d,error:f}=aBt({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(Cj,m.targetType):x.delete(Cj),j?x.set(g1,j):x.delete(g1),k?x.set(fce,k):x.delete(fce),x.delete(VJe),x},{replace:!0})};return f&&_s(f)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:r7}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(ci,{variant:"fill"})]}):f&&Ts(f)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:r7}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(Js,{variant:"fill",resource:"experiments"})]}):f?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:r7}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(tn,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:f.message})]}):a.jsx(fws,{withQueryTrace:u.enabled,withFeedback:u.enabled,breadcrumbs:a.jsx(Pt,{crumbs:r7}),datasetId:h?.datasetId??void 0,experimentId:i??void 0,targetType:r,targetId:s,featuredItemId:o,renderFilters:m=>a.jsx(vws,{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(de,{render:a.jsx(l,{href:c.experimentLink(i)}),icon:a.jsx($be,{}),children:"See experiment"}):void 0})}function xws({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 CBt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return a.jsx("ul",{className:"space-y-1",children:e.map(s=>a.jsx(xws,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function bws({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(CBt,{connections:i,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function wws({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(bws,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):a.jsx(CBt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?a.jsx("p",{className:"text-destructive-foreground",children:String(c)}):null]})}function Sws({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(ft,{invalid:!!o,disabled:i,children:[a.jsx(lt,{children:"Provider"}),a.jsxs(Ur,{value:n,onValueChange:h,children:[a.jsx(Qr,{children:a.jsx(qr,{placeholder:i?"Loading providers…":"Select provider"})}),a.jsx(Zr,{children:e.map(y=>a.jsx(or,{value:y.id,children:`${y.displayName??y.name} (${y.id})`},y.id))})]}),a.jsx(cs,{children:o?String(o):void 0})]}),a.jsxs(ft,{invalid:!!c,disabled:!n||l,children:[a.jsx(lt,{children:"Toolkit"}),a.jsxs(Ur,{value:r,onValueChange:p,children:[a.jsx(Qr,{children:a.jsx(qr,{placeholder:l?"Loading toolkits…":"Select toolkit"})}),a.jsx(Zr,{children:t.map(y=>a.jsx(or,{value:y.slug,children:`${y.name} (${y.slug})`},y.slug))})]}),a.jsx(cs,{children:c?String(c):void 0})]}),a.jsxs(ft,{disabled:!n||!r,children:[a.jsx(lt,{children:"Label (optional)"}),a.jsx(Sn,{placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value)})]}),a.jsx(de,{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 UJe=e=>e.authorId?.trim()||"shared",kws=(e,t)=>{if(!t||new Set(e.map(UJe)).size<=1)return null;const r=new Map;for(const i of e){const o=UJe(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},Ows=["*","tool-providers:*","tool-providers:admin"];function jws(){const{data:e}=qm();return e?.permissions?.some(t=>Ows.includes(t))??!1}const Cws=[{id:"integrations",label:"Integrations"}];function _ws(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,i]=g.useState(""),o=EP(),l=tY({providerId:e||null,queryOptions:{enabled:!!e}}),c=GNt({providerId:e||null,toolkit:n||null}),u=WNt(),d=HNt(),f=jws(),h=o.data?.providers??[],p=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>kws(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(St,{breadcrumbs:a.jsx(Pt,{crumbs:Cws}),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(Sws,{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(wws,{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 Tws({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(v0,{className:"h-10 w-10"}),a.jsx(Y,{as:"h1",variant:"heading",tone:"ink",children:e})]}),t,n,r]})}function _Bt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:i}=Ul(),{mutate:o,isPending:l,error:c}=Gvn(),{mutate:u,isPending:d,error:f}=Yvn(),{mutate:h,isPending:p}=Tlt(),[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,I=C.signUpEnabled!==!1,P=m==="signin"||!I,A=P?l:d,D=P?c:f,z=()=>{t?t():e?window.location.href=e:window.location.href=SY("/")},Q=M=>{M.preventDefault(),P?o({email:b,password:k},{onSuccess:z}):u({email:b,password:k,name:y||void 0},{onSuccess:z})},q=()=>{h({redirectUri:e},{onSuccess:M=>{window.location.href=M.url}})},B=()=>{v(P?"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(Su,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),a.jsx(Y,{tone:"muted",children:C.description})]}):null,H=r?a.jsx("div",{role:"alert",children:a.jsx(Wt,{variant:"destructive",children:r})}):null;return a.jsxs(Tws,{title:P?"Sign in to Mastra Studio":"Create your account",description:V,errorBanner:H,children:[_&&a.jsxs(Qa,{onSubmit:Q,children:[!P&&a.jsxs(ft,{children:[a.jsx(lt,{children:"Name"}),a.jsx(Sn,{name:"name",type:"text",value:y,onChange:M=>x(M.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),a.jsxs(ft,{children:[a.jsx(lt,{required:!0,children:"Email"}),a.jsx(Sn,{name:"email",type:"email",value:b,onChange:M=>S(M.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"}),a.jsx(cs,{})]}),a.jsxs(ft,{children:[a.jsx(lt,{required:!0,children:"Password"}),a.jsx(Sn,{name:"password",type:"password",value:k,onChange:M=>j(M.target.value),placeholder:P?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"}),a.jsx(cs,{})]}),D?a.jsx("div",{role:"alert",children:a.jsx(Wt,{variant:"destructive",children:D.message})}):null,a.jsx(de,{icon:a.jsx(qbe,{}),type:"submit",disabled:A,className:"w-full",size:"lg",children:A?P?"Signing in...":"Creating account...":P?"Sign in":"Create account"}),I&&a.jsxs("div",{className:"text-center",children:[a.jsx(Y,{as:"span",variant:"body",tone:"muted",children:P?"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:P?"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(de,{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 Ews(){const[e]=pi(),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(_Bt,{redirectUri:n,onSuccess:o,initialMode:s,errorMessage:i})}function TBt({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(de,{disabled:e,size:"md",onClick:t,icon:a.jsx(Ln,{}),children:"Clear"}),i&&a.jsxs(ut,{children:[a.jsx(ut.Trigger,{asChild:!0,children:a.jsx(de,{disabled:e,size:"md","aria-label":"More filter actions",children:a.jsx(j0,{})})}),a.jsxs(ut.Content,{align:"end",children:[n&&a.jsxs(ut.Item,{onSelect:()=>n(),children:[a.jsx(Ln,{}),"Remove all filters"]}),n&&(r||s)&&a.jsx(ut.Separator,{}),r&&a.jsxs(ut.Item,{onSelect:()=>r(),children:[a.jsx(Rm,{}),"Save filters for next time"]}),s&&a.jsxs(ut.Item,{onSelect:()=>s(),children:[a.jsx(Go,{}),"Remove saved filters"]})]})]})]})}const Iws=Z(Xm,"min-w-0 focus:text-foreground");function hce({role:e,checked:t,label:n,onClick:r}){return a.jsxs("button",{ref:Eu(),type:"button",role:e,"aria-checked":t,"data-selected":t||void 0,"data-pick-multi-item":"",title:n,className:Iws,onClick:r,children:[a.jsx("span",{className:"min-w-0 flex-1 truncate",children:n}),t&&a.jsx("span",{className:i_,children:a.jsx(pr,{})})]})}function EBt({field:e,tokens:t,onChange:n}){const[r,s]=g.useState(""),i=_v(),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:uI.container,children:[a.jsx(Hd,{className:uI.icon}),a.jsx("input",{type:"text",value:r,onChange:f=>s(f.target.value),placeholder:`Search ${e.label.toLowerCase()}...`,className:uI.input,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(vq,"m-1"),children:[a.jsx(An,{size:"sm",className:"size-3 text-muted-foreground"}),"Loading options…"]}):l.length===0?a.jsx("div",{className:Z(vq,"m-1"),children:e.emptyText??"No option found."}):e.multi?a.jsx("div",{...o,children:a.jsx(Dm,{menu:i,children:l.map(f=>{const h=d.includes(f.value);return a.jsx(hce,{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(Dm,{menu:i,children:[l.map(f=>a.jsx(hce,{role:"radio",checked:u===f.value,label:f.label,onClick:()=>n(e.id,f.value)},f.value)),!e.omitAnyOption&&a.jsx(hce,{role:"radio",checked:u==="Any",label:"Any",onClick:()=>n(e.id,"Any")})]})})]})}function VIe(e){return Array.isArray(e)?e.length===0?"Any":e.join(", "):e}const Nws="This filter is set by the current context and cannot be removed here.";function Aws(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:VIe(t)}function Pws({field:e,value:t,tooltipContent:n}){const r=Aws(e,t),s=`${e.label} filter is locked by context`;return a.jsx(pc,{delayDuration:150,children:a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsxs(Vl,{"data-locked-field-id":e.id,"data-property-filter-pill":"locked",tabIndex:0,"aria-label":s,children:[a.jsx(qh,{children:e.label}),a.jsx(qh,{children:"is"}),a.jsx(qh,{children:r}),a.jsx(qh,{children:a.jsx(Su,{})})]})}),a.jsx(Nn,{children:n})]})})}function $ws({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(Vl,{children:[a.jsx(qh,{children:e.label}),a.jsx(qh,{children:"is"}),a.jsx(Sn,{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(de,{type:"button",disabled:s,"aria-label":`Remove ${e.label} filter`,onMouseDown:u=>u.preventDefault(),onClick:r,children:a.jsx(Ln,{})})]})}function Rws({field:e,token:t,tokens:n,onChange:r,onRemove:s,disabled:i}){const[o,l]=g.useState(!1);return a.jsxs(Vl,{children:[a.jsx(qh,{children:e.label}),a.jsx(qh,{children:"is"}),a.jsxs(bp,{open:o,onOpenChange:l,children:[a.jsx(rf,{asChild:!0,children:a.jsx(de,{type:"button",disabled:i,children:VIe(t.value)})}),a.jsx(nh,{align:"start",sideOffset:o_,className:"w-64 p-0","data-pick-multi-panel":!0,children:a.jsx(EBt,{field:e,tokens:n,onChange:r})})]}),a.jsx(de,{type:"button",disabled:i,"aria-label":`Remove ${e.label} filter`,onClick:s,children:a.jsx(Ln,{})})]})}function IBt({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:s,lockedFieldIds:i,lockedTooltipContent:o=Nws}){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(Pws,{field:h,value:d.value,tooltipContent:o},`${d.fieldId}-${f}`):h.kind==="text"&&!Array.isArray(d.value)?a.jsx($ws,{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(Rws,{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(Vl,{children:[a.jsx(qh,{children:h.label}),a.jsx(qh,{children:"is"}),a.jsx(qh,{children:VIe(d.value)}),a.jsx(de,{type:"button",disabled:r,"aria-label":`Remove ${h.label} filter`,onClick:()=>u(f),children:a.jsx(Ln,{})})]},`${d.fieldId}-${f}`):null})})}const NBt=Z(Xm,"focus:text-foreground"),UIe=g.forwardRef((e,t)=>a.jsx("button",{type:"button",role:"menuitem","data-filter-item":"",ref:Eu(t),...e}));UIe.displayName="FilterMenuButton";function ABt({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 A=new Set(l);return e.filter(D=>!A.has(D.id))},[e,l]),[u,d]=g.useState(!1),f=_v(),[h,p]=g.useState(),[m,v]=g.useState([]),[y,x]=g.useState(),[b,S]=g.useState(),k=g.useRef(!1),j=g.useCallback(A=>{S(D=>D===A?void 0:A)},[]),C=g.useCallback(()=>S(void 0),[]);g.useEffect(()=>{u||S(void 0)},[u]);const T=g.useMemo(()=>c.find(A=>A.id===h),[c,h]),_=g.useMemo(()=>{const A=new Set;for(const D of t){const z=e.find(Q=>Q.id===D.fieldId);z&&z.kind!=="pick-multi"&&A.add(D.fieldId)}return A},[t,e]),N=g.useCallback(()=>{p(void 0),v([]),x(void 0)},[]);g.useEffect(()=>{u||N()},[u,N]);const I=g.useCallback((A,D)=>{const z=t.findIndex(q=>q.fieldId===A);if(Array.isArray(D)&&D.length===0){if(z===-1)return;n(t.filter((q,B)=>B!==z));return}if(z===-1){n([...t,{fieldId:A,value:D}]);return}const Q=[...t];Q[z]={fieldId:A,value:D},n(Q)},[n,t]),P=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(bp,{open:u,onOpenChange:d,children:[a.jsx(rf,{asChild:!0,children:a.jsx(de,{size:i,disabled:s,icon:a.jsx(T3e,{}),children:r})}),a.jsx(nh,{align:"end",sideOffset:o_,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(Fn,On),onClick:N,children:a.jsx(fd,{className:"size-4"})}),a.jsx(Cjn,{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:A=>{if(A.key!=="ArrowDown"&&A.key!=="ArrowUp"&&A.key!=="Home"&&A.key!=="End")return;const D=Array.from(A.currentTarget.querySelectorAll("[data-filter-item]:not([disabled])"));if(D.length===0)return;A.preventDefault();const z=document.activeElement,Q=D.findIndex(B=>B===z);let q;A.key==="Home"?q=0:A.key==="End"?q=D.length-1:A.key==="ArrowDown"?q=Q<0?0:(Q+1)%D.length:q=Q<=0?D.length-1:Q-1,D[q]?.focus()},children:a.jsx(Dm,{menu:f,children:c.length>0?c.map(A=>{const D=_.has(A.id);return A.kind==="pick-multi"?a.jsx(Mws,{field:A,tokens:t,onChange:I,open:b===A.id,onToggle:j,onClose:C},A.id):a.jsxs(UIe,{className:Z(NBt,"group"),disabled:D,onClick:()=>{if(x(void 0),A.kind==="text"){n([...t,{fieldId:A.id,value:""}]),o?.(A.id),k.current=!0,d(!1);return}p(A.id)},children:[a.jsx("span",{className:"truncate",children:A.label}),D?a.jsx("span",{className:"ml-auto text-muted-foreground",children:"In use"}):a.jsx("span",{className:Z(iL,"text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 group-focus:opacity-100"),children:a.jsx(bs,{})})]},A.id)}):a.jsx("div",{className:vq,children:"No matching property."})})}),T&&a.jsxs(ft,{invalid:!!y,children:[a.jsx(Ca,{multiple:!0,options:T.options??[],value:m,onValueChange:A=>{v(A),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(cs,{children:y})]}),T&&a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.jsx(de,{icon:a.jsx(Ln,{}),variant:"ghost",size:"md",onClick:()=>d(!1),children:"Cancel"}),a.jsx(de,{icon:a.jsx(T3e,{}),size:"md",onClick:P,children:"Add filter"})]})]})})]})}function Mws({field:e,tokens:t,onChange:n,open:r,onToggle:s,onClose:i}){const o=g.useRef(null);return a.jsxs(bp,{open:r,onOpenChange:l=>{l?s(e.id):i()},children:[a.jsx(rf,{asChild:!0,children:a.jsxs(UIe,{className:NBt,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(Gs,{className:"text-muted-foreground"}),a.jsx("span",{className:"truncate",children:e.label}),!r&&a.jsx("span",{className:Z(iL,"text-muted-foreground"),children:a.jsx(Gs,{})})]})}),a.jsx(nh,{ref:o,side:"right",align:"start",sideOffset:o_,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(EBt,{field:e,tokens:t,onChange:n})})]})}function Dws({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:i,depth:o}){const l=e?oC(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(Lt,{children:[e.entityType&&a.jsxs(a.Fragment,{children:[a.jsx(Lt.Key,{children:"Entity Type"}),a.jsx(Lt.Value,{children:e.entityType})]}),e.entityName&&a.jsxs(a.Fragment,{children:[a.jsx(Lt.Key,{children:"Entity Name"}),a.jsx(Lt.Value,{children:e.entityName})]}),e.serviceName&&a.jsxs(a.Fragment,{children:[a.jsx(Lt.Key,{children:"Service"}),a.jsx(Lt.Value,{children:e.serviceName})]}),e.environment&&a.jsxs(a.Fragment,{children:[a.jsx(Lt.Key,{children:"Environment"}),a.jsx(Lt.Value,{children:e.environment})]}),e.source&&a.jsxs(a.Fragment,{children:[a.jsx(Lt.Key,{children:"Source"}),a.jsx(Lt.Value,{children:e.source})]}),e.metadata&&Object.entries(e.metadata).map(([c,u])=>a.jsxs(g.Fragment,{children:[a.jsx(Lt.Key,{children:c}),a.jsx(Lt.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(Vl,{className:"w-full min-w-0",children:[a.jsxs(de,{className:"min-w-0 flex-1 justify-between overflow-hidden",icon:a.jsx(sp,{}),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(io,{content:e.traceId,tooltip:"Copy Trace ID to clipboard"})]}),e.spanId&&a.jsxs(Vl,{className:"w-full min-w-0",children:[a.jsxs(de,{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(sp,{}),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(io,{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 Lws({error:e,resource:t,errorTitle:n}){if(_s(e))return a.jsx(ci,{});if(Ts(e))return a.jsx(Js,{resource:t});if(vL(e))return a.jsx(tn,{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(gL(e,"logs"))return a.jsx(tn,{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(tn,{tone:"error",titleSlot:n,descriptionSlot:r??"Unknown error"})}const zws={debug:"neutral",info:"info",warn:"warning",error:"destructive",fatal:"destructive"};function Fws({level:e}){return a.jsx(pa,{children:a.jsx(Ft,{variant:zws[e],children:e})})}function Bws({entityType:e,className:t}){const n=Z("size-3.5 shrink-0 text-placeholder",t);switch(e.toLowerCase()){case"agent":return a.jsx(zo,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return a.jsx(xl,{className:n,"aria-hidden":!0});case"tool":return a.jsx(of,{className:n,"aria-hidden":!0});default:return null}}function Vws({entityType:e,entityName:t}){const n=e??"";return a.jsxs(pa,{className:"flex min-w-0 items-center gap-2",children:[a.jsx(Bws,{entityType:n}),t?a.jsx(Y,{as:"span",variant:"body-sm",className:"min-w-0 truncate",children:t}):"-"]})}function Uws({message:e}){return a.jsx(pa,{className:"min-w-0 truncate font-mono text-body-sm text-muted-foreground",children:e})}function qws({data:e}){if(!e||Object.keys(e).length===0)return a.jsx(pa,{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(sje,{font:"mono",children:t})}const El=Object.assign(BL,{Top:VL,TopCell:z0,SortableTopCell:KK,TopCellWithTooltip:WK,TopCellSmart:FEt,RowWrapper:aje,RowButton:UL,RowLink:oje,Spacer:lje,NoMatch:GK,DateCell:DEt,TimeCell:zEt,LevelCell:Fws,EntityCell:Vws,MessageCell:Uws,DataCell:qws,NextPageLoading:HK}),qJe="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",Qws=36,Zws=8;function Wws({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=d7t({count:e.length,getScrollElement:()=>d.current,estimateSize:()=>Qws,overscan:Zws}),{getRowProps:h}=Ru({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(Au,{columns:qJe,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(El,{columns:qJe,scrollRef:d,className:"min-w-0",fit:"container",children:[a.jsxs(El.Top,{children:[u?a.jsx(El.SortableTopCell,{sortKey:"timestamp",sort:c,onSortChange:u,children:"Date"}):a.jsx(El.TopCell,{children:"Date"}),a.jsx(El.TopCell,{children:"Time"}),a.jsx(El.TopCell,{children:"Level"}),a.jsx(El.TopCell,{children:"Entity"}),a.jsx(El.TopCell,{children:"Message"}),a.jsx(El.TopCell,{children:"Data"})]}),e.length===0?a.jsx(El.NoMatch,{message:"No logs match your search"}):a.jsxs(a.Fragment,{children:[a.jsx(El.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(El.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(El.DateCell,{timestamp:S.timestamp}),a.jsx(El.TimeCell,{timestamp:S.timestamp}),a.jsx(El.LevelCell,{level:S.level}),a.jsx(El.EntityCell,{entityType:S.entityType,entityName:S.entityName}),a.jsx(El.MessageCell,{message:S.message}),a.jsx(El.DataCell,{data:S.data})]},k)}),a.jsx(El.Spacer,{height:x})]}),a.jsx(El.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function Hws({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=>Gws(f,i));return u?a.jsxs("div",{className:Z("grid grid-cols-[1fr_auto] items-start gap-3"),children:[a.jsx(IBt,{fields:i,tokens:o,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&a.jsx(TBt,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function Gws(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 Kws={"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"},pce="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function Yws({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${Kws[e]}`,description:pce}:t&&n?{title:`No logs between ${is(t,"date-time")} and ${is(n,"date-time")}`,description:pce}:t?{title:`No logs since ${is(t,"date-time")}`,description:pce}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const Xws=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=Yws({datePreset:e,dateFrom:t,dateTo:n});return a.jsx(tn,{titleSlot:r,descriptionSlot:s,actionSlot:a.jsx(de,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Vs,{}),children:"Logging Documentation"}),variant:"fill"})},s7={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},PBt=[{label:"Agent",entityType:s7.AGENT},{label:"Workflow",entityType:s7.WORKFLOW},{label:"Scorer",entityType:s7.SCORER},{label:"Ingest",entityType:s7.INGEST}],Jws=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],w0="rootEntityType",Eb="datePreset",Ib="dateFrom",Nb="dateTo",e1s=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Nl={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"},q6=Object.keys(Nl),qIe=new Set(["tags"]),QIe="mastra:logs:saved-filters";function t1s(e,t=QIe){const n=o1s(e),r=e.get(Eb);r&&n.set(Eb,r);const s=e.get(Ib);s&&n.set(Ib,s);const i=e.get(Nb);i&&n.set(Nb,i);try{localStorage.setItem(t,n.toString())}catch{}}function n1s(e=QIe){try{localStorage.removeItem(e)}catch{}}function QJe(e=QIe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function r1s(e){if(e.has(Eb)||e.has(Ib)||e.has(Nb)||e.has(w0))return!0;for(const t of q6)if(e.has(Nl[t]))return!0;return!1}function s1s({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const i=[{id:"rootEntityType",label:"Primitive type",kind:"pick-multi",searchable:!1,options:PBt.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:Jws.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 i1s(e){const t=[],n=new Map([[w0,"rootEntityType"]]);for(const s of q6)n.set(Nl[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),qIe.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 o1s(e){const t=new URLSearchParams,n=e.get(w0);n&&t.set(w0,n);for(const r of q6){const s=Nl[r];if(qIe.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 a1s(e,t){e.delete(w0);for(const n of q6)e.delete(Nl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(w0,n.value);continue}const r=Nl[n.fieldId];if(r){if(qIe.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 l1s({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 c1s(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 u1s="Filters setting for Logs saved",d1s="Filters setting for Logs cleared up";function f1s(e,t,n){const{storageKey:r,messages:s,skipHydration:i}={},[o,l]=g.useState(()=>QJe(r)!==null),c=g.useCallback(()=>{t1s(e,r),l(!0);const f=s?.saved??u1s;f!==!1&&Ge.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{n1s(r),l(!1);const f=s?.cleared??d1s;f!==!1&&Ge.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(i||d.current||(d.current=!0,r1s(e)))return;const f=QJe(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 h1s(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 p1s(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,h1s(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function m1s(e,t,n,r){const s=g.useMemo(()=>p1s(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 Tve="logId",Eve="traceId",Ive="spanId",fM=1440*60*1e3,g1s={"last-24h":fM,"last-3d":3*fM,"last-7d":7*fM,"last-14d":14*fM,"last-30d":30*fM};function i7(e){e.delete(Tve),e.delete(Eve),e.delete(Ive)}function v1s(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const j=e.get(Eb);return j&&e1s.has(j)?j:"last-24h"},[e]),i=e.get(Ib),o=e.get(Nb),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=g1s[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(Tve),f=e.get(Eve),h=e.get(Ive),p=g.useMemo(()=>PBt.find(j=>j.entityType===e.get(w0)),[e]),m=g.useMemo(()=>i1s(e),[e]),v=g.useCallback(j=>{t(C=>{const T=new URLSearchParams(C);for(const[_,N]of Object.entries(j)){const I=_==="logId"?Tve:_==="traceId"?Eve:Ive;N?T.set(I,N):T.delete(I)}return T},{replace:!0})},[t]),y=g.useCallback(j=>{t(C=>{const T=new URLSearchParams(C);return a1s(T,j),i7(T),T},{replace:!0})},[t]),x=y,b=g.useCallback((j,C)=>{if(u.current!=="custom")return;const T=C==="from"?Ib:Nb;t(_=>{const N=new URLSearchParams(_);return j?N.set(T,j.toISOString()):N.delete(T),i7(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(Eb),T.delete(Ib),T.delete(Nb)):j==="custom"?T.set(Eb,"custom"):(T.set(Eb,j),T.delete(Ib),T.delete(Nb)),i7(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(j=>{const C=new URLSearchParams(j);C.delete(w0);for(const T of q6)C.delete(Nl[T]);return C.delete(Eb),C.delete(Ib),C.delete(Nb),i7(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 y1s=20,x1s=1e4,b1s={field:"timestamp",direction:"DESC"};function w1s(e,t,n){if(e?.pagination?.hasMore)return n+1}function S1s(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 k1s(e){return gL(e.state.error,"logs")||vL(e.state.error)?!1:x1s}const O1s=({filters:e,orderBy:t=b1s,queryOptions:n}={})=>{const r=Ye(),{inView:s,setRef:i}=E0(),{hasNextPage:o,isFetchingNextPage:l,fetchNextPage:c,data:u,isLoading:d,isError:f,error:h}=Am({queryKey:["logs",e,t],queryFn:({pageParam:p})=>r.listLogsVNext({pagination:{page:p,perPage:y1s},filters:e,orderBy:t}),initialPageParam:0,getNextPageParam:w1s,select:S1s,retry:!1,refetchInterval:k1s,...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}},mce=[hs("/logs")],j1s=["timestamp"],C1s={key:"timestamp",direction:"desc"};function _1s(){const[e,t]=pi(),n=Lr(),r=v1s(e,t),s=UX(),{sort:i,onSortChange:o}=wk({searchParams:e,setSearchParams:t,allowedKeys:j1s,defaultSort:C1s}),l=g.useMemo(()=>({field:"timestamp",direction:i?.direction==="asc"?"ASC":"DESC"}),[i?.direction]),c=f1s(e,t),[u,d]=g.useState(),{data:f=[],isPending:h}=b9t(),{data:p=[],isPending:m}=xIe({entityType:r.selectedEntityOption?.entityType,rootOnly:!0}),{data:v=[],isPending:y}=bIe(),{data:x=[],isPending:b}=x9t(),S=g.useMemo(()=>s1s({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(()=>l1s({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:I}=O1s({filters:k,orderBy:l}),{logIdMap:P,featuredLog:A,handleLogClick:D,handlePreviousLog:z,handleNextLog:Q}=m1s(j,r.featuredLogId,r.handleFeaturedChange,r.featuredTraceId),{data:q,isLoading:B}=$_({traceId:r.featuredTraceId??null,queryOptions:{enabled:!!r.featuredTraceId}}),V=g.useCallback(()=>r.applyFilterTokens(c1s(S,r.filterTokens)),[S,r]),H=g.useCallback(()=>r.handleFeaturedChange({logId:null}),[r]),M=g.useCallback(K=>r.handleFeaturedChange({traceId:K,spanId:null}),[r]),G=g.useCallback((K,ne)=>r.handleFeaturedChange({traceId:K,spanId:ne}),[r]),L=g.useCallback(()=>r.handleFeaturedChange({traceId:null,spanId:null}),[r]),$=g.useCallback(K=>r.handleFeaturedChange({spanId:K??null}),[r]),F=a.jsxs(a.Fragment,{children:[a.jsx(Xn,{children:a.jsxs(Xn.Start,{children:[a.jsx(YK,{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(ABt,{fields:S,tokens:r.filterTokens,onTokensChange:r.handleFilterTokensChange,disabled:C,onStartTextFilter:d})]})}),a.jsx(Hws,{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(St,{breadcrumbs:a.jsx(Pt,{crumbs:mce}),actionRow:F,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsx(Lws,{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(St,{breadcrumbs:a.jsx(Pt,{crumbs:mce}),actionRow:F,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx(Xws,{datePreset:r.datePreset,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo})]}):a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:mce}),actionRow:F,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx(Wws,{logs:j,isLoading:C,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:I,logIdMap:P,featuredLogId:r.featuredLogId,onLogClick:D,timestampSort:i?.direction,onSortChange:o}),a.jsx(Dws,{log:A??void 0,onClose:H,onTraceClick:M,onSpanClick:G,onPrevious:z,onNext:Q}),a.jsx(MIe,{depth:2,traceId:A?r.featuredTraceId??void 0:void 0,spans:q?.spans,isLoadingSpans:B,selectedSpanId:r.featuredSpanId??null,onSpanSelect:$,onClose:L,withQueryTrace:s.enabled,withFeedback:s.enabled,onOpenScore:(K,ne)=>n(Tje(K,ne))})]})}const T1s={name:e=>e.name||e.id};function E1s({server:e,rowProps:t}){const{paths:n,Link:r}=hn(),i=Ye().options.baseUrl,l=e.transports?.includes("sse")??!0?"sse":"mcp",c=i?`${i}/api/mcp/${e.id}/${l}`:"",{data:u}=N1t({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(ke.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[a.jsx(ke.NameCell,{children:m}),a.jsx(ke.DescriptionCell,{children:c}),a.jsx(ke.TextCell,{className:"text-center",children:h||""}),a.jsx(ke.TextCell,{className:"text-center",children:f||""}),a.jsx(ke.TextCell,{className:"text-center",children:p||""})]})}function I1s({mcpServers:e,isLoading:t,search:n="",sort:r,onSortChange:s}){const i=g.useMemo(()=>{const c=n.toLowerCase();return mk(e.filter(u=>u.name?.toLowerCase().includes(c)||u.id?.toLowerCase().includes(c)),r,T1s)},[e,n,r]),{containerRef:o,getRowProps:l}=Ru({count:i.length,global:!0});return t?a.jsx(Au,{columns:"auto 1fr auto auto auto"}):a.jsxs(ke,{columns:"auto 1fr auto auto auto",scrollRef:o,children:[a.jsxs(ke.Top,{children:[s?a.jsx(ke.SortableTopCell,{sortKey:"name",sort:r?.key==="name"?r.direction:void 0,onSortChange:s,children:"Name"}):a.jsx(ke.TopCell,{children:"Name"}),a.jsx(ke.TopCell,{children:"URL"}),a.jsx(ke.TopCellSmart,{long:"Agents",short:a.jsx(zo,{}),tooltip:"Agent Tools",className:"text-center"}),a.jsx(ke.TopCellSmart,{long:"Tools",short:a.jsx(of,{}),tooltip:"Tools",className:"text-center"}),a.jsx(ke.TopCellSmart,{long:"Workflows",short:a.jsx(xl,{}),tooltip:"Workflow Tools",className:"text-center"})]}),i.length===0&&n?a.jsx(ke.NoMatch,{message:"No MCP Servers match your search"}):null,i.map((c,u)=>a.jsx(E1s,{server:c,rowProps:l(u)},c.id))]})}const N1s=()=>a.jsx(tn,{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(de,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Vs,{}),children:"MCP Documentation"}),variant:"fill"}),hM=[hs("/mcps")],A1s=()=>{const{data:e=[],isLoading:t,error:n}=rP(),[r,s]=g.useState(""),[i,o]=g.useState();return n&&_s(n)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:hM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(ci,{variant:"fill"})]}):n&&Ts(n)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:hM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(Js,{variant:"fill",resource:"MCP servers"})]}):n?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:hM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(tn,{tone:"error",variant:"fill",titleSlot:"Failed to load MCP servers",descriptionSlot:n.message})]}):e.length===0&&!t?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:hM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(N1s,{})]}):a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:hM}),actionRow:a.jsx(Xn,{children:a.jsx(Xn.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(Pu,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})})}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(I1s,{mcpServers:e,isLoading:t,search:r,sort:i,onSortChange:(l,c)=>o({key:c,direction:l})})]})},ZJe="auto 1fr auto",P1s={tool:"Tool",agent:"Agent",workflow:"Workflow"};function $1s(e){return e in DEe}function R1s({type:e}){const t=$1s(e)?e:"tool",n=DEe[t],r=P1s[t];return a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("span",{"aria-label":t,className:"inline-flex text-muted-foreground [&>svg]:size-4",children:a.jsx(n,{})})}),a.jsx(Nn,{children:r})]})}const M1s=vr({ui:vr({resourceUri:Cn().optional()}).optional(),"ui/resourceUri":Cn().optional()});function D1s(e){const t=M1s.safeParse(e);return t.success?!!(t.data.ui?.resourceUri?.startsWith("ui://")||t.data["ui/resourceUri"]?.startsWith("ui://")):!1}function L1s({server:e}){const[t,n]=g.useState(""),{data:r={},isLoading:s}=N1t({selectedServer:e}),{Link:i,paths:o}=hn(),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}=Ru({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(Pu,{onSearch:n,label:"Filter tools",placeholder:"Filter by name",shortcutDisabled:!0})})]}),s?a.jsx(Au,{columns:ZJe}):a.jsxs(ke,{columns:ZJe,scrollRef:c,children:[a.jsxs(ke.Top,{children:[a.jsx(ke.TopCell,{children:"Name"}),a.jsx(ke.TopCell,{children:"Description"}),a.jsx(ke.TopCell,{className:"justify-center text-center",children:"Type"})]}),l.length===0&&t?a.jsx(ke.NoMatch,{message:"No tools match your search"}):null,l.map((d,f)=>a.jsxs(ke.RowLink,{to:o.mcpServerToolLink(e.id,d.name),LinkComponent:i,...u(f),children:[a.jsx(ke.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-2",children:[d.name,D1s(d._meta)&&a.jsx(Ft,{size:"xs",children:"App"})]})}),a.jsx(ke.DescriptionCell,{children:d.description}),a.jsx(ke.TextCell,{className:"justify-center text-center",children:a.jsx(R1s,{type:d.toolType??"tool"})})]},d.name))]})]})}const z1s=({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(hc,{children:a.jsxs(Hl,{defaultTab:"http",children:[a.jsxs(Nq,{className:"flex-row items-center justify-between gap-3 space-y-0 border-b border-border",children:[a.jsx(ak,{className:"shrink-0",children:"Connect"}),a.jsx("div",{className:"min-w-0",children:a.jsx(Gl,{variant:"pill-ghost",size:"sm",children:l.map(c=>a.jsx(ls,{value:c.value,children:c.label},c.value))})})]}),l.map(c=>a.jsx(Ls,{value:c.value,flush:!0,children:a.jsxs(dv,{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(io,{tooltip:c.tooltip,content:c.content})]})]})},c.value))]})}),a.jsx(L1s,{server:t})]})},F1s=()=>{const{serverId:e}=fr(),t=[hs("/mcps"),z1t],{data:n=[],isLoading:r}=rP(),s=n.find(l=>l.id===e),i=s?.transports?.includes("sse")??!0,o=r||s?a.jsxs($c,{children:[a.jsx($c.Title,{isLoading:r,children:s?.name}),s&&a.jsx($c.Meta,{beside:!0,children:a.jsxs(Ft,{size:"sm",children:["v",s.version_detail.version]})}),s&&a.jsx($c.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.jsx(St,{variant:"narrow",breadcrumbs:a.jsx(Pt,{crumbs:t}),header:o,children:a.jsx(z1s,{isLoading:r,server:s})})};function B1s(e){if(!e)return;const t=e.ui;if(t?.resourceUri)return t.resourceUri;const n=e["ui/resourceUri"];if(typeof n=="string")return n}function V1s(e){return typeof e=="object"&&e!==null&&e.status==="suspended"}function U1s(e){return JSON.stringify({error:e instanceof Error?e.message:String(e)},null,2)}const q1s=({toolId:e,serverId:t})=>{const{canExecute:n}=Ta(),r=n("tools"),s=Ye(),{data:i,isLoading:o,error:l}=fSe({serverId:t,toolId:e,queryOptions:{enabled:!!t&&!!e}}),{mutateAsync:c,isPending:u,data:d,error:f}=qsr({serverId:t,toolId:e}),h=i?B1s(i._meta):void 0,{data:p}=kt({queryKey:["mcp-app-resource",t,h],queryFn:async()=>h?(await s.readMcpServerResource(t,h)).contents[0]?.text??null:null,enabled:!!h}),m=g.useCallback(async(x,b)=>await c({data:b}),[c]);g.useEffect(()=>{if(l){const x=l instanceof Error?l.message:"Failed to load tool";Ge.error(`Error loading tool: ${x}`)}},[l]);const v=async(x,b)=>{if(i)return await c({data:x,requestContext:b}).catch(()=>{})};if(o)return a.jsxs("div",{className:"p-4",children:[a.jsx(bt,{className:"mb-4 h-8 w-48"}),a.jsx(bt,{className:"h-32 w-full"})]});if(l)return null;if(!i)return a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(Y,{variant:"heading",tone:"muted",children:"Tool not found"})});if(!r)return a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(Y,{variant:"caption",tone:"muted",children:"You don't have permission to execute tools."})});let y;try{y=ix(i.inputSchema)}catch(x){console.error("Error processing input schema:",x),Ge.error("Failed to process tool input schema."),y=vr({})}return a.jsxs("div",{className:"flex flex-col gap-4",children:[p&&a.jsx("div",{className:"border-b border-border p-4",children:a.jsx(bzt,{html:p,toolName:i.name,onToolCall:m})}),V1s(d)&&a.jsx("div",{className:"px-4 pt-4",children: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("code",{children:"inputRequests"})," handler to finish the request."]})}),a.jsx(LEe,{executionResult:d,errorString:f?U1s(f):void 0,isExecutingTool:u,zodInputSchema:y,handleExecuteTool:v,toolDescription:i.description||"",toolId:i.name,requestContextEntityType:"mcp-tool",requestContextEntityId:`${t}:${i.name}`})]})},Q1s=()=>{const{serverId:e,toolId:t}=fr(),n=[hs("/mcps"),{...z1t,to:e?`/mcps/${encodeURIComponent(e)}`:void 0},{id:"mcp-server-tool",Component:Gsr}],{data:r,isLoading:s}=fSe({serverId:e,toolId:t,queryOptions:{enabled:!!e&&!!t}});return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:n}),children:[a.jsx("h1",{className:"sr-only",children:t}),!s&&r&&a.jsx("div",{className:"h-full w-full overflow-y-auto",children:a.jsx(q1s,{toolId:t,serverId:e})})]})},Z1s={default:YW,inset:Z(hr,"*:bg-background! *:shadow-rim!")};function W1s({children:e,variant:t="default",className:n}){return a.jsx("div",{className:Z("grid grid-cols-1 gap-1 rounded-xl p-1 *:min-w-0! md:grid-cols-2 lg:flex lg:*:flex-1",Z1s[t],n),children:e})}function H1s({children:e,className:t}){return a.jsx("div",{className:Z("flex flex-wrap gap-4",t),children:e})}const $Bt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],dA="rootEntityType",fA={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"},sJ=Object.keys(fA),ZIe="mastra:metrics:saved-filters";function G1s(e){const t=J1s(e);try{localStorage.setItem(ZIe,t.toString())}catch{}}function K1s(){try{localStorage.removeItem(ZIe)}catch{}}function RBt(){try{const e=localStorage.getItem(ZIe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function Y1s(e){if(e.has(dA))return!0;for(const t of sJ)if(e.has(fA[t]))return!0;return!1}function MBt({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const i=[{id:"rootEntityType",label:"Primitive type",kind:"pick-multi",searchable:!1,options:$Bt.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:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"threadId",label:"Thread ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],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 X1s(e){const t=[],n=new Map([[dA,"rootEntityType"]]);for(const s of sJ)n.set(fA[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 J1s(e){const t=new URLSearchParams,n=e.getAll(dA);for(const r of n)t.append(dA,r);for(const r of sJ){const s=fA[r],i=e.getAll(s);for(const o of i)t.append(s,o)}return t}function eSs(e,t){e.delete(dA);for(const n of sJ)e.delete(fA[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?dA:fA[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 tSs="Any";function WJe(e){const t=e.trim();return t===""||t===tSs}const nSs=new Set($Bt.map(e=>e.entityType));function HJe(e){const t=e.trim();return nSs.has(t)?t:void 0}function rSs(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=>!WJe(i));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const i=s[0],o=i!==void 0?HJe(i):void 0;o&&(t.rootEntityType=o)}else t[r]=s[0]}else if(typeof n.value=="string"){if(WJe(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const i=HJe(s);i&&(t.rootEntityType=i)}else t[r]=s}}return t}const DBt=[{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"}],sSs=new Set(DBt.map(e=>e.value));function iSs(e){return typeof e=="string"&&(sSs.has(e)||e==="custom")}const LBt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",comparisonLabel:"vs previous 24h",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function Q6(){return g.useContext(LBt)}function oSs(e,t){return e!=="custom"?DBt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${dI(t.from)} – ${dI(t.to)}`:dI(t.from)??"":"Custom range"}const GJe=3600*1e3;function aSs(e,t){if(e!=="custom")return`vs previous ${e}`;const n=t?.to?.getTime()??Date.now(),r=t?.from?.getTime()??n-24*GJe,s=Math.round((n-r)/GJe);return`vs previous ${s>24&&s%24===0?`${s/24}d`:`${s}h`}`}function lSs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:i,onCustomRangeChange:o,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>rSs(d),[d]),h=g.useMemo(()=>JSON.stringify(f),[f]),p=oSs(t,i),m=aSs(t,i),v=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:i,setCustomRange:o??(()=>{}),dateRangeLabel:p,comparisonLabel:m,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:h,tracesBasePath:l,logsBasePath:c}),[t,r,i,o,p,m,d,s,f,h,l,c]);return a.jsx(LBt.Provider,{value:v,children:e})}const Nve=1440*60*1e3,cSs={"24h":Nve,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function uSs(e,t,n){if(e!=="custom"){const r=cSs[e]??Nve;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-Nve),end:t?.to??new Date(n)}}function dSs({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(()=>uSs(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 zBt(e){if(e==null)return;const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?void 0:t}const fSs={time:{hour:"numeric",minute:"2-digit"},"time-seconds":{hour:"numeric",minute:"2-digit",second:"2-digit"},"date-time":{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"},"date-time-seconds":{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit"},"day-time-seconds":{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit"},calendar:{year:"numeric",month:"numeric",day:"numeric",calendar:"gregory",numberingSystem:"latn"},dayMonth:{month:"short",day:"numeric"},dayMonthYear:{month:"short",day:"numeric",year:"numeric"},precise:{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3},timePrecise:{hour:"numeric",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3}},KJe=new Map;function WIe(e,t,n){const r=`${t??""}|${n??""}|${e}`;let s=KJe.get(r);return s||(s=new Intl.DateTimeFormat(t,{...fSs[e],timeZone:n}),KJe.set(r,s)),s}function YJe(e,t){const n=WIe("calendar","en-US",t).formatToParts(e);return{year:n.find(r=>r.type==="year")?.value,month:n.find(r=>r.type==="month")?.value,day:n.find(r=>r.type==="day")?.value}}function hSs(e,{locale:t,now:n,timeZone:r}={}){const s=zBt(e);if(!s)return;const i=new Date(n??Date.now());return WIe(YJe(s,r).year===YJe(i,r).year?"dayMonth":"dayMonthYear",t,r).format(s)}function pSs(e,t,n={}){const r=zBt(e);if(!r)return;const{locale:s,now:i,timeZone:o}=n;return WIe(t,s,o).format(r)}const mSs=2880*60*1e3;function FBt({start:e,end:t}){return t.getTime()-e.getTime()<=mSs?"1h":"1d"}function BBt(e,t){return t==="1h"?pSs(e,"time")??"":hSs(e)??""}function gSs(e){const t=Ye(),{filters:n,filterKey:r,queryOptions:s}=e;return kt({queryKey:["metrics","active-resources-kpi",r],queryFn:()=>t.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:n,comparePeriod:"previous_period"}),...s})}function vSs(e){const t=Ye(),{filters:n,filterKey:r,queryOptions:s}=e;return kt({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 VBt(e){const t=Ye(),{filters:n,filterKey:r,queryOptions:s}=e;return kt({queryKey:["metrics","agent-runs-kpi",r],queryFn:()=>t.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:n,comparePeriod:"previous_period"}),...s})}async function gce(e,t,n,r){const s=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:r,filters:n}),i=s.series.find(c=>c.percentile===.5),o=s.series.find(c=>c.percentile===.95);if(!i||!o)return[];const l=new Map(o.points.map(c=>[new Date(c.timestamp).getTime(),c.value]));return i.points.map(c=>{const u=new Date(c.timestamp),d=u.getTime();return{time:BBt(u,r),tsMs:d,p50:Math.round(c.value),p95:Math.round(l.get(d)??0)}})}function ySs(e){const t=Ye(),{timestamp:n,filters:r,filterKey:s,queryOptions:i}=e,o=FBt(n);return kt({queryKey:["metrics","latency",s,o],queryFn:async()=>{const[l,c,u]=await Promise.all([gce(t,"mastra_agent_duration_ms",r,o),gce(t,"mastra_workflow_duration_ms",r,o),gce(t,"mastra_tool_duration_ms",r,o)]);return{agentData:l,workflowData:c,toolData:u,interval:o}},...i})}function xSs(e){const t=Ye(),{filters:n,filterKey:r,queryOptions:s}=e;return kt({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})}const bSs=new Intl.NumberFormat("en-US",{notation:"compact",maximumSignificantDigits:3}),wSs=new Intl.NumberFormat("en-US"),SSs=new Set(Intl.supportedValuesOf("currency"));function UBt(e){return e!==void 0&&SSs.has(e.toUpperCase())}function Ave(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:e,...t})}function o7(e,{currency:t}={}){if(!UBt(t))return bSs.format(e);const n=Math.abs(e);return n<100?kSs(e,{currency:t}):n<1e3?Ave(t,{maximumFractionDigits:0}).format(e):Ave(t,{notation:"compact",maximumSignificantDigits:3}).format(e)}function kSs(e,{currency:t}={}){if(!UBt(t))return wSs.format(e);const n=Ave(t,{}),r=10**-(n.resolvedOptions().maximumFractionDigits??2);return e!==0&&Math.abs(e)<r?`${e<0?"-":""}<${n.format(r)}`:n.format(e)}function OSs(e){const t=Ye(),{filters:n,filterKey:r,queryOptions:s}=e;return kt({queryKey:["metrics","model-usage-cost",r],queryFn:async()=>{const[i,o,l,c]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(h=>t.getMetricBreakdown({name:[h],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:n})));if(!i||!o||!l||!c)return[];const u=new Map,d=h=>HP(u,h,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),f=(h,p)=>{p.estimatedCost!=null&&(h.cost=(h.cost??0)+p.estimatedCost,p.costUnit&&(h.costUnit=p.costUnit))};for(const h of i.groups){const p=d(h.dimensions.model??"unknown");p.input=h.value,f(p,h)}for(const h of o.groups){const p=d(h.dimensions.model??"unknown");p.output=h.value,f(p,h)}for(const h of l.groups){const p=d(h.dimensions.model??"unknown");p.cacheRead=h.value}for(const h of c.groups){const p=d(h.dimensions.model??"unknown");p.cacheWrite=h.value}return Array.from(u.entries()).map(([h,p])=>({model:h,input:o7(p.input),output:o7(p.output),cacheRead:o7(p.cacheRead),cacheWrite:o7(p.cacheWrite),cost:p.cost,costUnit:p.costUnit})).sort((h,p)=>h.model.localeCompare(p.model))},...s})}function jSs(e){const t=Ye(),{filters:n,filterKey:r,queryOptions:s}=e;return kt({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=>HP(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 XJe(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const i=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};i[n]+=r.value,r.estimatedCost!=null&&(i.cost=(i.cost??0)+r.estimatedCost,t?.costUnit?i.costUnits.add(t.costUnit):i.hasUnknownCostUnit=!0),e.set(s,i)}}function CSs(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function _Ss(e){const t=Ye(),{timestamp:n,filters:r,filterKey:s,queryOptions:i}=e,o=FBt(n);return kt({queryKey:["metrics","token-usage-timeseries",s,o],queryFn:async()=>{const[l,c]=await Promise.all([t.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:o,aggregation:"sum",filters:r}),t.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:o,aggregation:"sum",filters:r})]),u=new Map;return XJe(u,l.series[0],"input"),XJe(u,c.series[0],"output"),{data:Array.from(u.values()).sort((d,f)=>d.tsMs-f.tsMs).map(d=>({time:BBt(new Date(d.tsMs),o),tsMs:d.tsMs,input:d.input,output:d.output,total:d.input+d.output,cost:d.cost,costUnit:CSs(d)})),interval:o}},...i})}const vce=20;function TSs(e){const t=Ye(),{filters:n,filterKey:r,queryOptions:s}=e;return kt({queryKey:["metrics","top-active-threads",r],queryFn:async()=>{const i={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:n},[o,l,c]=await Promise.all([t.getMetricBreakdown({...i,name:["mastra_agent_duration_ms"],aggregation:"count",limit:vce}),t.getMetricBreakdown({...i,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:vce}),t.getMetricBreakdown({...i,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:vce})]),u=new Map,d=h=>HP(u,h,()=>({tokens:0,cost:null,costUnit:null})),f=h=>{for(const p of h){const m=p.dimensions.threadId;if(!m)continue;const v=d(m);v.tokens+=p.value,p.estimatedCost!=null&&(v.cost=(v.cost??0)+p.estimatedCost,p.costUnit&&(v.costUnit=p.costUnit))}};return f(l.groups),f(c.groups),o.groups.filter(h=>!!h.dimensions.threadId).map(h=>{const p=h.dimensions.threadId,m=u.get(p);return{threadId:p,resourceId:h.dimensions.resourceId??null,runs:h.value,tokens:m?.tokens??0,cost:m?.cost??null,costUnit:m?.costUnit??null}})},...s})}const yce=20;function ESs(e){const t=Ye(),{filters:n,filterKey:r,queryOptions:s}=e;return kt({queryKey:["metrics","top-resources-by-threads",r],queryFn:async()=>{const i={groupBy:["resourceId"],orderDirection:"DESC",filters:n},[o,l,c]=await Promise.all([t.getMetricBreakdown({...i,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:yce}),t.getMetricBreakdown({...i,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:yce}),t.getMetricBreakdown({...i,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:yce})]),u=new Map,d=h=>HP(u,h,()=>({tokens:0,cost:null,costUnit:null})),f=h=>{for(const p of h){const m=p.dimensions.resourceId;if(!m)continue;const v=d(m);v.tokens+=p.value,p.estimatedCost!=null&&(v.cost=(v.cost??0)+p.estimatedCost,p.costUnit&&(v.costUnit=p.costUnit))}};return f(l.groups),f(c.groups),o.groups.filter(h=>!!h.dimensions.resourceId).map(h=>{const p=h.dimensions.resourceId,m=u.get(p);return{resourceId:p,threadCount:h.value,tokens:m?.tokens??0,cost:m?.cost??null,costUnit:m?.costUnit??null}})},...s})}function ISs(e){const t=Ye(),{filters:n,filterKey:r,queryOptions:s}=e;return kt({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 xce(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=HP(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 NSs(e){const t=Ye(),{filters:n,filterKey:r,queryOptions:s}=e;return kt({queryKey:["metrics","trace-volume",r],queryFn:async()=>{const[i,o,l]=await Promise.all([xce(t,"mastra_agent_duration_ms",n),xce(t,"mastra_workflow_duration_ms",n),xce(t,"mastra_tool_duration_ms",n)]);return{agentData:i,workflowData:o,toolData:l}},...s})}function hp(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=Q6();return dSs({datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r})}function Z6({href:e,LinkComponent:t="a"}){return a.jsx(de,{render:a.jsx(t,{href:e}),variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:a.jsx(rl,{})})}function ASs({href:e,LinkComponent:t="a"}){return a.jsx(de,{render:a.jsx(t,{href:e}),variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:a.jsx(vCn,{})})}function PSs({children:e,className:t}){return a.jsx("div",{className:Z("flex shrink-0 items-center gap-1",t),children:e})}function $Ss({children:e,className:t}){return a.jsx("div",{className:Z("overflow-x-auto",t),children:e})}function qBt({children:e,className:t}){return a.jsx(Y,{tone:"faint",className:Z("mt-0.5",t),children:e})}function RSs({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 MSs({className:e}){return a.jsx("div",{className:Z("flex items-center justify-center",e),children:a.jsx(An,{size:"md",variant:"pulse",className:"text-placeholder"})})}function DSs({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 JJe({children:e,className:t}){return a.jsx(hc,{className:Z("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 LSs({value:e,label:t,className:n}){return a.jsxs("div",{className:Z("text-right",n),children:[a.jsx(Y,{tone:"muted",className:"tabular-nums",children:e}),t&&a.jsx(Y,{tone:"faint",className:"mt-0.5",children:t})]})}function QBt({children:e,className:t,as:n="h2"}){return a.jsx(n,{className:Z("text-body text-foreground",t),children:e})}function zSs(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(QBt,{as:r,children:t}),n&&a.jsx(qBt,{children:n})]})}function FSs({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 er=Object.assign(JJe,{Root:JJe,Kpi:Md,TopBar:FSs,Actions:PSs,TitleAndDescription:zSs,Title:QBt,Description:qBt,Summary:LSs,Loading:MSs,Error:RSs,Content:$Ss,NoData:DSs});function zZ({data:e,series:t,className:n}){return a.jsx("div",{className:Z("flex flex-wrap items-center gap-4 gap-y-1",n),children:t.map(r=>{const s=r.aggregate?.(e);return a.jsxs("div",{className:"inline-flex items-center gap-2",children:[a.jsx("div",{className:"size-2 shrink-0 rounded-full",style:{backgroundColor:r.color}}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"max-w-24 truncate",children:r.label}),s&&a.jsxs(Y,{as:"span",variant:"caption",tone:"muted",children:[s.value,s.suffix&&a.jsxs(Y,{as:"span",variant:"caption",tone:"faint",children:[" ",s.suffix]})]})]},r.dataKey)})})}function BSs({active:e,payload:t,label:n,suffix:r,formatValue:s=i=>i.toLocaleString("en-US")}){return!e||!t?.length?null:a.jsxs(WOe,{children:[a.jsx(Y,{variant:"column",tone:"ink",className:"mb-1",children:n}),t.map(i=>a.jsxs("p",{className:"text-foreground",children:[a.jsx("span",{className:"mr-2 inline-block size-2 rounded-full",style:{backgroundColor:i.color}}),i.name,":"," ",a.jsxs("span",{className:"font-mono",children:[typeof i.value=="number"?s(i.value):i.value,r]})]},i.name))]})}const VSs=new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1});function USs({points:e}){const[t,n]=e??[];return!t||!n?null:a.jsx("line",{x1:0,x2:0,y1:t.y,y2:n.y,stroke:"currentColor",strokeOpacity:.2,strokeWidth:1,className:"pointer-events-none text-black transition-transform duration-150 ease-out dark:text-white",style:{transform:`translateX(${t.x}px)`}})}function Pve({data:e,series:t,height:n=210,yDomain:r,onPointClick:s,xAxisInterval:i="preserveStartEnd",xAxisMinTickGap:o=28,showDots:l=!1,showLegend:c=!0}){const u=typeof s=="function";return a.jsxs("div",{children:[c&&a.jsx(zZ,{data:e,series:t,className:"mb-4"}),a.jsx("div",{style:{height:n},children:a.jsx(CL,{width:"100%",height:"100%",children:a.jsxs(MEr,{data:e,margin:{top:5,right:5,bottom:5,left:0},children:[a.jsx(lTt,{stroke:"currentColor",strokeOpacity:.08,strokeDasharray:"4 4",vertical:!1,className:"text-black dark:text-white"}),a.jsx(LL,{dataKey:"time",tick:{fontSize:pde,fill:O5e,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,interval:i,minTickGap:o}),a.jsx(zL,{tick:{fontSize:pde,fill:O5e,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,width:"auto",tickFormatter:d=>VSs.format(d),domain:r,tickCount:3}),a.jsx(jK,{content:a.jsx(BSs,{}),cursor:a.jsx(USs,{})}),t.map(d=>a.jsx(vTt,{type:"linear",dataKey:d.dataKey,stroke:d.color,strokeWidth:2,dot:l?{r:3,fill:d.color,strokeWidth:0}:!1,activeDot:u?{r:4,stroke:d.color,strokeOpacity:.3,strokeWidth:4,style:{cursor:"pointer"},onClick:(f,h)=>{const p=h?.payload;p&&s(p,d.dataKey)}}:{r:4,stroke:d.color,strokeOpacity:.3,strokeWidth:4},name:d.label},d.dataKey))]})})})]})}function qSs(e){return e==="agents"||e==="workflows"||e==="tools"}function eet(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const i=s[t];return r+(typeof i=="number"&&Number.isFinite(i)?i:0)},0);return`${Math.round(n/e.length)}`}function QSs(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const $ve={className:"max-h-80",mask:{left:!1}},Qy={pink:"var(--chart-pink)",purple:"var(--chart-purple)",blue:"var(--chart-blue)",blueDark:"var(--chart-blue-deep)",amber:"var(--chart-amber)"},ZBt=[{dataKey:"p50",label:"p50",color:Qy.blue,aggregate:e=>({value:eet(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Qy.amber,aggregate:e=>({value:eet(e,"p95"),suffix:"avg ms"})}];function bce({data:e,onPointClick:t}){return e.length===0?a.jsx(er.NoData,{message:"No latency data yet"}):a.jsx(Pve,{data:e,series:ZBt,showLegend:!1,onPointClick:t?n=>QSs(n)?t(n):void 0:void 0})}function ZSs({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const i=(e?.agentData.length??0)>0,o=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:i,workflows:o,tools:l},u=i?"agents":o?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),h=c[d]?d:u,p=typeof s=="function"?s(h):s,m=e?.interval??"1h",v=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),y=e?{agents:e.agentData,workflows:e.workflowData,tools:e.toolData}[h]:[];return a.jsxs(er,{children:[a.jsxs(er.TopBar,{children:[a.jsx(er.TitleAndDescription,{title:"Latency",description:m==="1h"?"Hourly p50 and p95 latency.":"Daily p50 and p95 latency."}),p?a.jsx(er.Actions,{children:p}):null]}),t?a.jsx(er.Loading,{}):n?a.jsx(er.Error,{message:"Failed to load latency data"}):a.jsx(er.Content,{children:v?a.jsxs(Hl,{value:h,onValueChange:x=>{qSs(x)&&c[x]&&f(x)},defaultTab:u,className:"overflow-visible",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 [&>:first-child]:w-auto",children:[a.jsxs(Gl,{children:[a.jsx(ls,{value:"agents",disabled:!i,disabledTooltip:"No agent latency data for this period",children:"Agents"}),a.jsx(ls,{value:"workflows",disabled:!o,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),a.jsx(ls,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),y.length>0&&a.jsx(zZ,{data:y,series:ZBt})]}),a.jsx(Ls,{value:"agents",className:"pt-3",children:a.jsx(bce,{data:e.agentData,onPointClick:r?x=>r("agents",x,m):void 0})}),a.jsx(Ls,{value:"workflows",className:"pt-3",children:a.jsx(bce,{data:e.workflowData,onPointClick:r?x=>r("workflows",x,m):void 0})}),a.jsx(Ls,{value:"tools",className:"pt-3",children:a.jsx(bce,{data:e.toolData,onPointClick:r?x=>r("tools",x,m):void 0})})]}):a.jsx(er.NoData,{message:"No latency data yet"})})]})}function WSs(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 HSs(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const i=new Date(s.getTime()+3600*1e3);return{from:s,to:i}}const n=new Date(e);n.setUTCHours(0,0,0,0);const r=new Date(n.getTime()+1440*60*1e3);return{from:n,to:r}}function WBt(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=WSs(s);l&&e.set(t,l)}function Ja(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function HBt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function tet({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const i=new URLSearchParams;i.set(p1,"branches"),WBt(i,m1,Hw,Gw,e,t,r.window);const o=r.rootEntityType??n.rootEntityType;o&&i.set(MS,o),r.status&&i.set(DS,r.status),Ja(i,Cc.entityName,r.entityName??n.entityName),Ja(i,Cc.threadId,r.threadId??n.threadId),Ja(i,Cc.resourceId,r.resourceId??n.resourceId),Ja(i,Cc.runId,n.runId),Ja(i,Cc.sessionId,n.sessionId),Ja(i,Cc.requestId,n.requestId),Ja(i,Cc.userId,n.userId),Ja(i,Cc.organizationId,n.organizationId),Ja(i,Cc.experimentId,n.experimentId),Ja(i,Cc.serviceName,n.serviceName),Ja(i,Cc.environment,n.environment),HBt(i,Cc.tags,n.tags);const l=i.toString();return l?`${s}?${l}`:s}function GSs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const i=new URLSearchParams;WBt(i,Eb,Ib,Nb,e,t,r.window);const o=r.rootEntityType??n.rootEntityType;o&&i.set(w0,o),Ja(i,Nl.entityName,r.entityName??n.entityName),Ja(i,Nl.threadId,r.threadId??n.threadId),Ja(i,Nl.resourceId,r.resourceId??n.resourceId),Ja(i,Nl.runId,n.runId),Ja(i,Nl.sessionId,n.sessionId),Ja(i,Nl.requestId,n.requestId),Ja(i,Nl.userId,n.userId),Ja(i,Nl.organizationId,n.organizationId),Ja(i,Nl.experimentId,n.experimentId),Ja(i,Nl.serviceName,n.serviceName),Ja(i,Nl.environment,n.environment),HBt(i,Nl.tags,n.tags),r.status==="error"&&i.append(Nl.level,"error");const l=i.toString();return l?`${s}?${l}`:s}function KP(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=Q6(),i=g.useCallback((c={})=>tet({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),o=g.useCallback((c={})=>GSs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=HSs(u,d);return tet({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:i,getLogsHref:o,getBucketTracesHref:l}}const net={agents:fu.AGENT,workflows:fu.WORKFLOW_RUN,tools:fu.TOOL};function KSs(){const{data:e,isLoading:t,isError:n}=ySs(hp()),{getTracesHref:r,getBucketTracesHref:s}=KP(),{Link:i}=hn(),o=Lr();return a.jsx(ZSs,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&o(s({rootEntityType:net[l]},c.tsMs,"1h"))},actions:l=>a.jsx(Z6,{href:r({rootEntityType:net[l]}),LinkComponent:i})})}function YSs(e){return e==="threads"||e==="resources"}function wce(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function XSs({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:i}){const[o,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,h=e.data?.reduce((y,x)=>y+x.runs,0)??0,p=t.data?.reduce((y,x)=>y+x.threadCount,0)??0,m=o==="threads"?e:t,v=typeof s=="function"?s(o):s;return a.jsxs(er,{children:[a.jsxs(er.TopBar,{children:[a.jsx(er.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),o==="threads"&&d&&a.jsx(er.Summary,{value:h.toLocaleString(),label:"Total runs"}),o==="resources"&&f&&a.jsx(er.Summary,{value:p.toLocaleString(),label:"Total threads"}),v?a.jsx(er.Actions,{children:v}):null]}),m.isLoading?a.jsx(er.Loading,{}):m.isError?a.jsx(er.Error,{message:"Failed to load memory data"}):a.jsx(er.Content,{children:a.jsxs(Hl,{defaultTab:"threads",value:o,onValueChange:y=>{YSs(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[a.jsxs(Gl,{children:[a.jsx(ls,{value:"threads",children:"Threads"}),a.jsx(ls,{value:"resources",children:"Resources"})]}),a.jsx(Ls,{value:"threads",className:"pt-3",children:d?a.jsxs(ke,{columns:"auto auto auto auto auto",...$ve,children:[a.jsxs(ke.Top,{children:[a.jsx(ke.TopCell,{sticky:"start",children:"Thread ID"}),a.jsx(ke.TopCell,{className:"justify-end text-right",children:"Resource ID"}),a.jsx(ke.TopCell,{className:"justify-end text-right",children:"Runs"}),a.jsx(ke.TopCell,{className:"justify-end text-right",children:"Tokens"}),a.jsx(ke.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const x=n?.(y),b=a.jsxs(a.Fragment,{children:[a.jsx(ke.RowHeaderCell,{className:"text-caption",children:wce(y.threadId)}),a.jsx(ke.NumberCell,{children:y.resourceId?wce(y.resourceId):"—"}),a.jsx(ke.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),a.jsx(ke.NumberCell,{children:y.tokens>0?rd(y.tokens):"—"}),a.jsx(ke.NumberCell,{children:y.cost!=null?Om(y.cost,y.costUnit):"—"})]});return x?a.jsx(ke.RowLink,{to:x,LinkComponent:i,children:b},y.key):a.jsx(ke.RowStatic,{children:b},y.key)})]}):a.jsx(er.NoData,{message:"No thread activity yet"})}),a.jsx(Ls,{value:"resources",className:"pt-3",children:f?a.jsxs(ke,{columns:"auto auto auto auto",...$ve,children:[a.jsxs(ke.Top,{children:[a.jsx(ke.TopCell,{sticky:"start",children:"Resource ID"}),a.jsx(ke.TopCell,{className:"justify-end text-right",children:"Threads"}),a.jsx(ke.TopCell,{className:"justify-end text-right",children:"Tokens"}),a.jsx(ke.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const x=r?.(y),b=a.jsxs(a.Fragment,{children:[a.jsx(ke.RowHeaderCell,{className:"text-caption",children:wce(y.resourceId)}),a.jsx(ke.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),a.jsx(ke.NumberCell,{children:y.tokens>0?rd(y.tokens):"—"}),a.jsx(ke.NumberCell,{children:y.cost!=null?Om(y.cost,y.costUnit):"—"})]});return x?a.jsx(ke.RowLink,{to:x,LinkComponent:i,children:b},y.key):a.jsx(ke.RowStatic,{children:b},y.key)})]}):a.jsx(er.NoData,{message:"No resource activity yet"})})]})})]})}function JSs(){const e=TSs(hp()),t=ESs(hp()),{getTracesHref:n}=KP(),{Link:r}=hn();return a.jsx(XSs,{threads:{data:e.data,isLoading:e.isLoading,isError:e.isError},resources:{data:t.data,isLoading:t.isLoading,isError:t.isError},LinkComponent:r,getThreadRowHref:s=>n({threadId:s.threadId,...s.resourceId?{resourceId:s.resourceId}:{}}),getResourceRowHref:s=>n({resourceId:s.resourceId})})}function W6({value:e,currency:t,className:n}){const r=rd(e,{currency:t}),s=M_(e,{currency:t});return r===s?a.jsx("span",{className:Z("tabular-nums",n),children:r}):a.jsxs($n,{children:[a.jsxs(In,{render:a.jsx("span",{tabIndex:0,className:Z("tabular-nums",n)}),children:[a.jsx("span",{"aria-hidden":"true",children:r}),a.jsx("span",{className:"sr-only",children:s})]}),a.jsx(Nn,{side:"right",children:s})]})}function H6({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:i,lowerIsBetter:o}){const{comparisonLabel:l}=Q6(),c=t!=null,u=c&&!s&&!i&&r!=null&&r!==0;return a.jsxs(Md,{children:[a.jsxs(Md.Header,{children:[a.jsx(Md.Label,{children:e}),u?a.jsx(Md.Change,{changePct:r,comparison:l,prevValue:n,lowerIsBetter:o}):null]}),a.jsxs(Md.ValueRow,{children:[c?a.jsx(Md.Value,{children:t}):null,i?a.jsx(Md.Error,{}):s?a.jsx(Md.Loading,{}):c?u?null:a.jsx(Md.NoChange,{}):a.jsx(Md.NoData,{})]})]})}function eks(){const{data:e,isLoading:t,isError:n}=VBt(hp());return a.jsx(H6,{label:"Agent runs",value:e?.value!=null?a.jsx(W6,{value:e.value}):null,prevValue:e?.previousValue!=null?M_(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function tks(){const{data:e,isLoading:t,isError:n}=xSs(hp()),r=e?.costUnit??void 0;return a.jsx(H6,{label:"Model cost",value:e?.cost!=null?a.jsx(W6,{value:e.cost,currency:r}):null,prevValue:e?.previousCost!=null?M_(e.previousCost,{currency:r}):void 0,changePct:e?.costChangePercent??null,lowerIsBetter:!0,isLoading:t,isError:n})}function nks(){const{data:e,isLoading:t,isError:n}=ISs(hp());return a.jsx(H6,{label:"Tokens",value:e?.value!=null?a.jsx(W6,{value:e.value}):null,prevValue:e?.previousValue!=null?M_(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function rks(){const{data:e,isLoading:t,isError:n}=vSs(hp());return a.jsx(H6,{label:"Threads",value:e?.value!=null?a.jsx(W6,{value:e.value}):null,prevValue:e?.previousValue!=null?M_(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function sks(){const{data:e,isLoading:t,isError:n}=gSs(hp());return a.jsx(H6,{label:"Resources",value:e?.value!=null?a.jsx(W6,{value:e.value}):null,prevValue:e?.previousValue!=null?M_(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}const iks=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function oks(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 aks(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 lks(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=Q6(),s=g.useRef(e);s.current=e;const i=g.useRef(n);return i.current=n,a.jsx(YK,{preset:oks(e),onPresetChange:o=>{const l=aks(o);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(o,l)=>{if(s.current!=="custom")return;const c={...i.current,[l]:o};i.current=c,r(c)},presets:iks})}const cD=[hs("/metrics")];function cks({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=>uks(f,i));return u?a.jsxs("div",{className:Z("grid grid-cols-[1fr_auto] items-start gap-3"),children:[a.jsx(IBt,{fields:i,tokens:o,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&a.jsx(TBt,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function uks(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}function Rve({children:e,filterFields:t,isLoading:n=!1}){const[r]=pi(),{filterTokens:s,setFilterTokens:i}=Q6(),[o,l]=g.useState(),[c,u]=g.useState(()=>!!RBt()),d=()=>{G1s(r),u(!0),Ge.success("Filters setting for Metrics saved")},f=()=>{K1s(),u(!1),Ge.success("Filters setting for Metrics cleared up")},h=()=>{const p=s.map(m=>{const v=t.find(y=>y.id===m.fieldId);return v?v.kind==="text"?{fieldId:m.fieldId,value:""}:v.kind==="pick-multi"?v.multi?{fieldId:m.fieldId,value:[]}:{fieldId:m.fieldId,value:"Any"}:v.kind==="multi-select"?{fieldId:m.fieldId,value:[]}:m:m});i(p)};return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:cD}),actionRow:a.jsxs(a.Fragment,{children:[a.jsx(Xn,{children:a.jsxs(Xn.Start,{children:[a.jsx(lks,{}),a.jsx(ABt,{fields:t,tokens:s,onTokensChange:i,disabled:n,onStartTextFilter:l})]})}),a.jsx(cks,{isLoading:n,filterFields:t,filterTokens:s,onFilterTokensChange:i,onClear:h,onRemoveAll:()=>i([]),onSave:d,onRemoveSaved:c?f:void 0,autoFocusFilterFieldId:o})]}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),e]})}function dks({error:e}){return _s(e)?a.jsx(ci,{}):Ts(e)?a.jsx(Js,{resource:"metrics"}):a.jsx(tn,{tone:"error",titleSlot:"Failed to load storage capabilities",descriptionSlot:e.message})}const ret=MBt({availableTags:[],availableEntityNames:[],availableServiceNames:[],availableEnvironments:[]});function fks({children:e}){const{supportsMetrics:t,isLoading:n,error:r}=V6();return n?a.jsx(Rve,{filterFields:ret,isLoading:!0,children:a.jsxs("div",{className:"flex h-full items-center justify-center gap-2",children:[a.jsx(An,{"aria-label":"Loading storage capabilities"}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:"Loading storage capabilities"})]})}):r?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:cD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsx(dks,{error:r})})]}):t?e:a.jsx(Rve,{filterFields:ret,children:a.jsx(tn,{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(de,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Vs,{}),children:"Metrics Documentation"}),variant:"fill"})})}function hks({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:i}){const o=!!e&&e.length>0;return a.jsxs(er,{children:[a.jsxs(er.TopBar,{children:[a.jsx(er.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),o&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Om(l):"—":c.size===1?u=l>0?Om(l,[...c][0]):"—":u="Mixed",a.jsx(er.Summary,{value:u,label:"Total cost"})})(),s?a.jsx(er.Actions,{children:s}):null]}),t?a.jsx(er.Loading,{}):n?a.jsx(er.Error,{message:"Failed to load model usage data"}):a.jsx(er.Content,{children:o?a.jsxs(ke,{columns:"auto auto auto auto auto auto",...$ve,children:[a.jsxs(ke.Top,{children:[a.jsx(ke.TopCell,{sticky:"start",children:"Model"}),a.jsx(ke.TopCell,{className:"justify-end text-right",children:"Input"}),a.jsx(ke.TopCell,{className:"justify-end text-right",children:"Output"}),a.jsx(ke.TopCell,{className:"justify-end text-right",children:"Cache Read"}),a.jsx(ke.TopCell,{className:"justify-end text-right",children:"Cache Write"}),a.jsx(ke.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=a.jsxs(a.Fragment,{children:[a.jsx(ke.RowHeaderCell,{className:"text-caption",children:l.model}),a.jsx(ke.NumberCell,{children:l.input}),a.jsx(ke.NumberCell,{children:l.output}),a.jsx(ke.NumberCell,{children:l.cacheRead}),a.jsx(ke.NumberCell,{children:l.cacheWrite}),a.jsx(ke.NumberCell,{highlight:!0,children:l.cost!=null?Om(l.cost,l.costUnit):"—"})]});return c?a.jsx(ke.RowLink,{to:c,LinkComponent:i,children:u},l.model):a.jsx(ke.RowStatic,{children:u},l.model)})]}):a.jsx(er.NoData,{message:"No model usage data yet"})})]})}function pks(){const{data:e,isLoading:t,isError:n}=OSs(hp()),{getTracesHref:r}=KP(),{Link:s}=hn();return a.jsx(hks,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:fu.AGENT}),actions:a.jsx(Z6,{href:r({rootEntityType:fu.AGENT}),LinkComponent:s})})}function mks(e){const t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim())?.[1];if(!t)return;const n=t.length===3?[...t].map(s=>s+s).join(""):t,r=s=>{const i=parseInt(n.slice(s,s+2),16)/255;return i<=.03928?i/12.92:((i+.055)/1.055)**2.4};return .2126*r(0)+.7152*r(2)+.0722*r(4)}function gks(e){const t=e?mks(e):void 0;return t!==void 0&&t>.25}function Mve({data:e,segments:t,maxVal:n,fmt:r,className:s,LinkComponent:i="a"}){const o=[...e].sort((c,u)=>{const d=u.values.reduce((h,p)=>h+p,0),f=c.values.reduce((h,p)=>h+p,0);return d-f}),l=t.length>1;return a.jsxs(Nr,{className:Z("size-full",s),children:[a.jsxs("div",{className:"mt-2 mb-4 flex items-center gap-3",children:[a.jsx("div",{className:"flex flex-1 items-center gap-4",children:t.map(c=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"size-2 rounded-full",style:{backgroundColor:c.color}}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:c.label})]},c.label))}),a.jsx(Y,{as:"span",variant:"caption",tone:"faint",className:"shrink-0 pr-2",children:"Total"})]}),a.jsx("div",{className:"grid gap-3.5",children:o.map(c=>{const u=c.values.reduce((p,m)=>p+m,0),d=`${n>0?u/n*100:0}%`,f=gks(t[c.values.findIndex(p=>p>0)]?.color),h=a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"relative h-full min-w-0 flex-1",style:{"--bar-width":d},children:[a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("div",{className:Z("absolute inset-y-0 left-0",c.href?"cursor-pointer":"cursor-default"),style:{width:d},children:t.map((p,m)=>{const v=c.values[m]??0,y=u>0?v/u*100:0,x=c.values.slice(0,m).reduce((j,C)=>j+(u>0?C/u*100:0),0),b=c.values.slice(m+1).every(j=>!j),S=c.href?void 0:c.hrefs?.[m],k=a.jsx("div",{className:Z("absolute inset-y-0 opacity-40 dark:opacity-100",l&&m===0&&"rounded-l",l&&b&&"rounded-r",!l&&"rounded",S&&"cursor-pointer transition-opacity hover:opacity-70"),style:{left:l?`${x}%`:0,width:l?`${y}%`:`${y}%`,backgroundColor:p.color}});return S?a.jsx(i,{href:S,"aria-label":`${c.name} — ${p.label}`,className:"contents",children:k},p.label):a.jsx(vks,{children:k},p.label)})})}),a.jsx(Nn,{side:"top",className:"font-mono",children:a.jsx("div",{className:"grid gap-1",children:t.map((p,m)=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{children:p.label}),a.jsx("span",{className:"ml-auto pl-3",children:r(c.values[m]??0)})]},p.label))})})]}),a.jsx("div",{className:Z("pointer-events-none absolute inset-0 z-10",f&&"dark:[clip-path:inset(0_0_0_var(--bar-width))]"),children:a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"absolute inset-y-0 left-2.5 flex items-center truncate",children:c.name})}),f&&a.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute inset-y-0 left-0 z-10 hidden w-(--bar-width) overflow-hidden dark:block",children:a.jsx(Y,{as:"span",variant:"caption",tone:"faint",className:"absolute inset-y-0 left-2.5 flex items-center whitespace-nowrap",children:c.name})})]}),a.jsx(Y,{as:"span",tone:"muted",className:"shrink-0 pr-3 tabular-nums",children:r(u)})]});return c.href?a.jsx(i,{href:c.href,className:"flex h-6 cursor-pointer items-center gap-14 rounded transition-colors outline-none hover:bg-fill-subtle focus-visible:bg-fill-subtle",children:h},c.name):a.jsx("div",{className:"flex h-6 items-center gap-14",children:h},c.name)})})]})}function vks({children:e}){return a.jsx(a.Fragment,{children:e})}function yks(e){return e==="tokens"||e==="cost"}function xks({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:i}){const[o,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((x,b)=>x+b.total,0),f=c.filter(x=>x.cost!=null&&x.cost>0),h=new Set(f.map(x=>x.costUnit??"usd")),p=h.size<=1,m=p?[...h][0]??"usd":null,v=p?f.reduce((x,b)=>x+(b.cost??0),0):0,y=p&&v>0;return a.jsxs(er,{children:[a.jsxs(er.TopBar,{children:[a.jsx(er.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(o==="cost"&&y?a.jsx(er.Summary,{value:Om(v,m),label:"Total cost"}):a.jsx(er.Summary,{value:rd(d),label:"Total tokens"})),u&&s?a.jsx(er.Actions,{children:s}):null]}),t?a.jsx(er.Loading,{}):n?a.jsx(er.Error,{message:"Failed to load token usage data"}):a.jsx(er.Content,{children:u?a.jsxs(Hl,{defaultTab:"tokens",value:o,onValueChange:x=>{yks(x)&&l(x)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[a.jsxs(Gl,{children:[a.jsx(ls,{value:"tokens",children:"Tokens"}),a.jsx(ls,{value:"cost",children:"Cost"})]}),a.jsx(Ls,{value:"tokens",className:"pt-3",children:a.jsx(Mve,{LinkComponent:i,data:c.map(x=>({name:x.name,values:[x.input,x.output],href:r?.(x)})),segments:[{label:"Input",color:Qy.blueDark},{label:"Output",color:Qy.blue}],maxVal:Math.max(...c.map(x=>x.input+x.output)),fmt:rd})}),a.jsx(Ls,{value:"cost",className:"pt-3",children:y?a.jsx(Mve,{LinkComponent:i,data:f.slice().sort((x,b)=>(b.cost??0)-(x.cost??0)).map(x=>({name:x.name,values:[x.cost],href:r?.(x)})),segments:[{label:"Cost",color:Qy.purple}],maxVal:Math.max(...f.map(x=>x.cost??0)),fmt:x=>Om(x,m)}):a.jsx(er.NoData,{message:"No cost data yet"})})]}):a.jsx(er.NoData,{message:"No token usage data yet"})})]})}function bks(){const{data:e,isLoading:t,isError:n}=jSs(hp()),{getTracesHref:r}=KP(),{Link:s}=hn();return a.jsx(xks,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:i=>r({rootEntityType:fu.AGENT,entityName:i.name}),actions:a.jsx(Z6,{href:r({rootEntityType:fu.AGENT}),LinkComponent:s})})}function Dve(e,t=rd){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const set=[{dataKey:"input",label:"Input tokens",color:Qy.blue,aggregate:Dve("input")},{dataKey:"output",label:"Output tokens",color:Qy.amber,aggregate:Dve("output")}];function wks(e){return e==="tokens"||e==="cost"}function Sks({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[i,o]=g.useState("tokens"),l=e??[],c=l.map(S=>({...S})),u=l.length>0,d=l.filter(S=>S.cost!=null&&S.cost>0),f=d.map(S=>({...S})),h=new Set(d.map(S=>S.costUnit).filter(S=>!!S)),p=h.size===1&&d.every(S=>S.costUnit!=null),m=p?[...h][0]??null:null,v=p?d.reduce((S,k)=>S+(k.cost??0),0):0,y=p&&v>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",b=[{dataKey:"cost",label:"Cost",color:Qy.purple,aggregate:Dve("cost",S=>Om(S,m))}];return a.jsxs(er,{children:[a.jsxs(er.TopBar,{children:[a.jsx(er.TitleAndDescription,{title:"Token usage over time",description:x}),u&&s?a.jsx(er.Actions,{children:s}):null]}),n?a.jsx(er.Loading,{}):r?a.jsx(er.Error,{message:"Failed to load token usage timeline"}):a.jsx(er.Content,{children:u?a.jsxs(Hl,{defaultTab:"tokens",value:i,onValueChange:S=>{wks(S)&&o(S)},className:"overflow-visible",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 [&>:first-child]:w-auto",children:[a.jsxs(Gl,{children:[a.jsx(ls,{value:"tokens",children:"Tokens"}),a.jsx(ls,{value:"cost",children:"Cost"})]}),i==="tokens"?a.jsx(zZ,{data:c,series:set}):y?a.jsx(zZ,{data:f,series:b}):null]}),a.jsx(Ls,{value:"tokens",className:"pt-3",children:a.jsx(Pve,{data:c,series:set,showLegend:!1})}),a.jsx(Ls,{value:"cost",className:"pt-3",children:y?a.jsx(Pve,{data:f,series:b,showLegend:!1}):a.jsx(er.NoData,{message:"No cost data yet"})})]}):a.jsx(er.NoData,{message:"No token usage data yet"})})]})}function kks(){const{data:e,isLoading:t,isError:n}=_Ss(hp()),{getTracesHref:r}=KP(),{Link:s}=hn();return a.jsx(Sks,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:a.jsx(Z6,{href:r(),LinkComponent:s})})}function Sce({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return a.jsx(Mve,{LinkComponent:r,data:e.map(s=>{const i=n?.(s),o=t?.(s);return i?{name:s.name,values:[s.completed,s.errors],hrefs:[o,i]}:{name:s.name,values:[s.completed,s.errors],href:o}}),segments:[{label:"Completed",color:Qy.blueDark},{label:"Errors",color:Qy.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:rd})}function Oks({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:i,LinkComponent:o}){const[l,c]=g.useState("agents"),u=typeof i=="function"?i(l):i,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,h=m=>r?v=>r(m,v):void 0,p=m=>s?v=>s(m,v):void 0;return a.jsxs(er,{children:[a.jsxs(er.TopBar,{children:[a.jsx(er.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&a.jsx(er.Summary,{value:rd(f),label:"Total runs"}),u?a.jsx(er.Actions,{children:u}):null]}),t?a.jsx(er.Loading,{}):n?a.jsx(er.Error,{message:"Failed to load trace volume data"}):a.jsx(er.Content,{children:d?a.jsxs(Hl,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[a.jsxs(Gl,{children:[a.jsx(ls,{value:"agents",children:"Agents"}),a.jsx(ls,{value:"workflows",children:"Workflows"}),a.jsx(ls,{value:"tools",children:"Tools"})]}),a.jsx(Ls,{value:"agents",className:"pt-3",children:e.agentData.length>0?a.jsx(Sce,{data:e.agentData,rowHrefs:h("agents"),errorHrefs:p("agents"),LinkComponent:o}):a.jsx(er.NoData,{message:"No agent data yet"})}),a.jsx(Ls,{value:"workflows",className:"pt-3",children:e.workflowData.length>0?a.jsx(Sce,{data:e.workflowData,rowHrefs:h("workflows"),errorHrefs:p("workflows"),LinkComponent:o}):a.jsx(er.NoData,{message:"No workflow data yet"})}),a.jsx(Ls,{value:"tools",className:"pt-3",children:e.toolData.length>0?a.jsx(Sce,{data:e.toolData,rowHrefs:h("tools"),errorHrefs:p("tools"),LinkComponent:o}):a.jsx(er.NoData,{message:"No tool data yet"})})]}):a.jsx(er.NoData,{message:"No trace volume data yet"})})]})}const a7={agents:fu.AGENT,workflows:fu.WORKFLOW_RUN,tools:fu.TOOL};function jks(){const{data:e,isLoading:t,isError:n}=NSs(hp()),{getTracesHref:r,getLogsHref:s}=KP(),{Link:i}=hn();return a.jsx(Oks,{data:e,isLoading:t,isError:n,LinkComponent:i,getRowHref:(o,l)=>r({rootEntityType:a7[o],entityName:l.name}),getErrorSegmentHref:(o,l)=>l.errors>0?s({rootEntityType:a7[o],entityName:l.name,status:"error"}):void 0,actions:o=>a.jsxs(a.Fragment,{children:[a.jsx(Z6,{href:r({rootEntityType:a7[o]}),LinkComponent:i}),a.jsx(ASs,{href:s({rootEntityType:a7[o],status:"error"}),LinkComponent:i})]})})}const kce="period",l7="dateFrom",c7="dateTo";function Cks(){const[e,t]=pi(),n=e.get(kce),r=iSs(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(l7)),h=d(e.get(c7));if(!(!f&&!h))return{from:f,to:h}},[r,e.toString()]),i=g.useMemo(()=>X1s(e),[e.toString()]),o=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d==="24h"?h.delete(kce):h.set(kce,d),d!=="custom"&&(h.delete(l7),h.delete(c7)),h},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d?.from?h.set(l7,d.from.toISOString()):h.delete(l7),d?.to?h.set(c7,d.to.toISOString()):h.delete(c7),h},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return eSs(h,d),h},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,Y1s(e)))return;const d=RBt();d&&t(f=>{const h=new URLSearchParams(f);for(const[p,m]of d)h.append(p,m);return h},{replace:!0})},[]),a.jsx(lSs,{preset:r,filterTokens:i,onPresetChange:o,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:a.jsx(fks,{children:a.jsx(_ks,{})})})}function _ks(){const{error:e,isLoading:t}=VBt(hp()),{isInMemory:n}=V6(),{data:r,isLoading:s}=b9t(),{data:i,isLoading:o}=xIe(),{data:l,isLoading:c}=x9t(),{data:u,isLoading:d}=bIe(),f=g.useMemo(()=>MBt({availableTags:r??[],availableEntityNames:i??[],availableServiceNames:l??[],availableEnvironments:u??[],loading:{tags:s,entityNames:o,serviceNames:c,environments:d}}),[r,i,l,u,s,o,c,d]);return e&&_s(e)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:cD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(ci,{variant:"fill"})]}):e&&Ts(e)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:cD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(Js,{variant:"fill",resource:"metrics"})]}):e?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:cD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(tn,{tone:"error",variant:"fill",titleSlot:"Failed to load metrics",descriptionSlot:e.message})]}):a.jsx(Rve,{filterFields:f,isLoading:t,children:a.jsxs("div",{className:"grid content-start gap-4 pb-6",children:[n&&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.jsxs(W1s,{children:[a.jsx(eks,{}),a.jsx(tks,{}),a.jsx(nks,{}),a.jsx(rks,{}),a.jsx(sks,{})]}),a.jsxs(H1s,{children:[a.jsx(pks,{}),a.jsx(bks,{}),a.jsx(kks,{}),a.jsx(JSs,{}),a.jsx(jks,{}),a.jsx(KSs,{})]})]})})}function Tks(){const{isCmsAvailable:e}=Ix(),{paths:t}=hn();return e?a.jsx(bY,{href:t.cmsPromptBlockCreateLink(),tooltip:"Create a prompt",children:"New prompt"}):null}const pM=[hs("/prompts")],Eks=50,Iks=["updatedAt"];function Nks(){const[e,t]=g.useState(""),[n,r]=g.useState(0),[s,i]=pi(),{sort:o,onSortChange:l}=wk({searchParams:s,setSearchParams:i,allowedKeys:Iks}),c=g.useMemo(()=>o?{field:o.key,direction:o.direction==="asc"?"ASC":"DESC"}:void 0,[o]),{data:u,isLoading:d,error:f,isPlaceholderData:h}=$Ft({page:n,perPage:Eks,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&&_s(f)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:pM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(ci,{variant:"fill"})]}):f&&Ts(f)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:pM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(Js,{variant:"fill",resource:"prompt blocks"})]}):f?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:pM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(tn,{tone:"error",variant:"fill",titleSlot:"Failed to load prompt blocks",descriptionSlot:f.message})]}):p.length===0&&!d&&n===0?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:pM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(ccs,{})]}):a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:pM}),headerActions:a.jsx(Tks,{}),actionRow:a.jsx(Xn,{children:a.jsx(Xn.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(Pu,{onSearch:x,label:"Filter prompts",placeholder:"Filter by name or description"})})})}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(lcs,{promptBlocks:p,isLoading:d,search:e,currentPage:n,hasMore:m,onNextPage:v,onPrevPage:y,updatedSort:o?.direction,onSortChange:b})]})}const Aks=[hs("/resources")],Pks=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:BOn,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:ndt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Vs,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:A3,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:Lbe,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:Rbe,href:"https://mastra.ai/contact?ref=studio",external:!0}];function $ks(){return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Aks}),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:Pks.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",On)}),a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",children:e.title}),e.external&&a.jsx(Vs,{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 iet(){const{isCmsAvailable:e}=Ix(),{paths:t}=hn();return e?a.jsx(bY,{href:t.cmsScorersCreateLink(),tooltip:"Create a scorer",children:"New scorer"}):null}const mM=[hs("/scorers")];function Rks(){const{data:e={},isLoading:t,error:n}=eg(),[r,s]=g.useState(""),[i,o]=g.useState("all"),[l,c]=g.useState();if(n&&_s(n))return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:mM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(ci,{variant:"fill"})]});if(n&&Ts(n))return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:mM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Js,{variant:"fill",resource:"scorers"})]});if(n)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:mM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(tn,{tone:"error",variant:"fill",titleSlot:"Failed to load scorers",descriptionSlot:n.message})]});if(Object.keys(e).length===0&&!t)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:mM}),headerActions:a.jsx(iet,{}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(His,{})]});const u=i!=="all"||r!=="",d=()=>{s(""),o("all")};return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:mM}),headerActions:a.jsx(iet,{}),actionRow:a.jsx(Kis,{search:r,onSearchChange:s,sourceFilter:i,onSourceFilterChange:o,onReset:d,hasActiveFilters:u}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Wis,{scorers:e,isLoading:t,search:r,sourceFilter:i,sort:l,onSortChange:(f,h)=>c({key:h,direction:f})})]})}const GBt=["input","entity"],Mks={input:"Input",entity:"Entity"};function Dks(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 Lks(){const[e,t]=g.useState(new Set),n=g.useMemo(()=>new Set(GBt.filter(i=>!e.has(i))),[e]),r=g.useMemo(()=>Dks(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 zks({visibleColumns:e,toggleColumn:t}){return a.jsxs(ut,{children:[a.jsx(ut.Trigger,{asChild:!0,children:a.jsx(de,{icon:a.jsx(udt,{}),children:"Columns"})}),a.jsxs(ut.Content,{align:"end",children:[a.jsx(ut.Label,{children:"Toggle columns"}),GBt.map(n=>a.jsx(ut.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:Mks[n]},n))]})]})}const oet=[hs("/scorers"),Air],Fks=["date","score"];function Bks(){const{scorerId:e}=fr(),[t,n]=pi(),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}=lir(e),p=Lks(),{data:m={},isLoading:v,error:y}=pf(),{isLoading:x,error:b}=vp({}),{sort:S,onSortChange:k}=wk({searchParams:t,setSearchParams:n,allowedKeys:Fks}),{data:j=[],isLoading:C,error:T,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:I}=air({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),P=g.useMemo(()=>mk(j,S,{date:X=>X.createdAt,score:X=>typeof X.score=="number"?X.score:void 0}),[j,S]),A=g.useMemo(()=>f?.agentIds?.filter(X=>m[X]).map(X=>({value:X,label:m[X].name,type:"AGENT"}))||[],[f?.agentIds,m]),D=g.useMemo(()=>f?.workflowIds?.map(X=>({value:X,label:X,type:"WORKFLOW"}))||[],[f?.workflowIds]),z=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...A,...D],[A,D]),Q=t.get("entity")??"all",q=z.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";Ge.error(`Error loading scorer: ${X}`)}},[h]),g.useEffect(()=>{if(y){const X=y instanceof Error?y.message:"Failed to load agents";Ge.error(`Error loading agents: ${X}`)}},[y]),g.useEffect(()=>{if(b){const X=b instanceof Error?b.message:"Failed to load workflows";Ge.error(`Error loading workflows: ${X}`)}},[b]);const B=X=>{X?.value&&n(te=>{const oe=new URLSearchParams(te);return oe.set("entity",X.value),oe})};g.useEffect(()=>{const X=t.get("scoreId")??void 0;if(X===s)return;if(!X){i(void 0);return}P.find(oe=>oe.id===X)&&i(X)},[t,P]);const V=g.useCallback(X=>{i(X||void 0),n(te=>{const oe=new URLSearchParams(te);return X?oe.set("scoreId",X):oe.delete("scoreId"),oe})},[n]);if(!f)return null;const H=_s(h)||_s(y)||_s(b),M=h&&Ts(h),G=!H&&!M&&(h||y||b),L=!C&&P.length===0,$=u?.value!=="all",F=f?.source==="stored",U=e?a.jsx(XX,{open:o,onOpenChange:l,initialScorerIds:[e],onSuccess:X=>{c(`/experiments/${X}`)}}):null,K=F?a.jsxs(ut,{children:[a.jsx(ut.Trigger,{asChild:!0,children:a.jsx(de,{size:"lg","aria-label":"Scorer actions menu",children:a.jsx(j0,{})})}),a.jsx(ut.Content,{align:"end",className:"w-48",children:a.jsxs(ut.Item,{onSelect:()=>{c(`/cms/scorers/${e}/edit`)},children:[a.jsx(od,{})," Edit Scorer"]})})]}):null;if(H||M||G||L&&!$){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",te=H||M||G;return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:oet}),actionRow:!te&&K?a.jsx(Xn,{children:a.jsx(Xn.End,{children:K})}):void 0,children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:"flex h-full items-center justify-center",children:H?a.jsx(ci,{}):M?a.jsx(Js,{resource:"scorers"}):G?a.jsx(tn,{tone:"error",titleSlot:"Failed to load scorer",descriptionSlot:X}):a.jsx(Ais,{onRunExperiment:()=>l(!0)})}),U]})}return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:oet}),actionRow:a.jsxs(Xn,{children:[a.jsx(Xn.Start,{children:a.jsx(Qis,{selectedEntity:u,entityOptions:z,onEntityChange:B,onReset:()=>{n(X=>{const te=new URLSearchParams(X);return te.set("entity","all"),te})},isLoading:C||v||x})}),a.jsxs(Xn.End,{children:[a.jsx(zks,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),a.jsx(de,{variant:"primary",onClick:()=>l(!0),icon:a.jsx(ku,{}),children:"Run Experiment"}),K]})]}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Nis,{scores:P,isLoading:C,selectedScoreId:s,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:I,onScoreClick:V,errorMsg:T?.message,columnsState:p,sort:S,onSortChange:k}),U]})}const KBt=g.createContext(void 0);function Vks({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(KBt.Provider,{value:d,children:a.jsxs(J2t,{...l,value:e,onValueChange:h=>{f(h)&&t(h)},"aria-label":n,...wx({"aria-label":n,"aria-labelledby":l["aria-labelledby"]}),"data-slot":"segmented-control","data-size":r,className:Z(hr,"relative inline-flex w-fit shrink-0 items-stretch rounded-full p-0.5",s&&"gap-0.5",Hh[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 Uks({value:e,disabled:t,className:n,children:r,ref:s,...i}){const o=g.useContext(KBt);if(!o)throw new Error("SegmentedControlItem must be used inside a SegmentedControl");const{iconOnly:l,registerItem:c,unregisterItem:u}=o,d=KS(s,f=>(f&&c(e,f),()=>u(e)));return a.jsx(X2t,{...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",On,n),children:r})}const qks=[{value:"system",label:"System",icon:a.jsx(Tdt,{})},{value:"light",label:"Light",icon:a.jsx(hTn,{})},{value:"dark",label:"Dark",icon:a.jsx(RCn,{})}];function Qks(e,t){if(e.some(r=>r.value===t))return t;const[n]=e;return n?n.value:"system"}const Zks=({value:e,onChange:t,options:n=qks,size:r="md","aria-label":s="Theme",...i})=>{const{theme:o,setTheme:l}=Vwe(),c=e??o,u=t??l,d=Qks(n,c);return a.jsx(Vks,{...i,"aria-label":s,iconOnly:!0,size:r==="xs"?"sm":r,value:d,onValueChange:u,children:n.map(f=>a.jsx(Uks,{value:f.value,"aria-label":f.label,children:f.icon},f.value))})},Wks=[hs("/settings")],Hks=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=$3();return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:Wks}),children:[a.jsx("h1",{className:"sr-only",children:"Settings"}),a.jsx(yos,{children:a.jsxs("div",{className:"mx-auto flex max-w-4xl flex-col gap-8",children:[a.jsxs(LKe,{children:[a.jsxs(zKe,{children:[a.jsx(FKe,{children:"General"}),a.jsx(BKe,{children:"Stored in this browser."})]}),a.jsx(Ezt,{children:a.jsx(Azt,{label:"Theme",description:"Customize the appearance of the studio.",children:a.jsx(Zks,{})})})]}),a.jsxs(LKe,{children:[a.jsxs(zKe,{children:[a.jsx(FKe,{children:"Mastra Connection"}),a.jsx(BKe,{children:"Configure the Mastra instance URL, API prefix, and request headers used by the studio."})]}),a.jsx(sFt,{variant:"factory",initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})]})]})})]})};function Gks(){const[e]=pi(),t=Lr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return a.jsx(_Bt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}async function YBt(){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 Kks({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 Yks({repoOrSlug:e,owner:t}){const{templates:n}=await YBt(),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 Kks({repo:e,owner:t});if(s)return s;throw new Error(`Template ${e} not found`)}return r}async function Xks({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(`
|
|
694
|
-
`).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 Jks=({queryOptions:e}={})=>kt({queryKey:["mastra-templates"],queryFn:YBt,...e}),eOs=({repoOrSlug:e,owner:t,queryOptions:n})=>kt({queryKey:["template-repo",e,t],queryFn:()=>Yks({repoOrSlug:e,owner:t}),...n}),tOs=({repo:e,owner:t,branch:n,queryOptions:r})=>kt({queryKey:["template-repo-env-vars",e,t,n],queryFn:()=>Xks({repo:e,owner:t,branch:n}),...r}),nOs=({queryOptions:e}={})=>{const t=Ye();return kt({queryKey:["agent-builder-workflow"],queryFn:async()=>await t.getAgentBuilderAction("merge-template").details(),...e})},rOs=({queryOptions:e}={})=>{const t=Ye();return kn({mutationFn:async({runId:n})=>await t.getAgentBuilderAction("merge-template").createRun({runId:n}),...e})},sOs=({queryOptions:e}={})=>{const t=Ye();return kn({mutationFn:async({runId:n})=>await t.getAgentBuilderAction("merge-template").runById(n),...e})},aet=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)},cet=(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=aet(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=aet(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}},iOs=(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)}},XBt=(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}=cet(h,d,e);if(d=p,r(p),h.runId||c||t){const m=h.runId||c||t;iOs(m,p)}}}catch(f){console.error("💥 [processStream] Error processing template installation stream:",f);const{newState:h}=cet({type:"error",payload:{error:f instanceof Error?f.message:"Unknown error"}},d,e);r(h)}finally{i(!1),u.releaseLock()}}}},oOs=({workflowInfo:e,queryOptions:t}={})=>{const n=Ye(),{streamResult:r,isStreaming:s,processStream:i}=XBt(e);return{streamInstall:kn({mutationFn:async({inputData:o,selectedModel:l,runId:c})=>{for(let d=1;d<=3;d++)try{const f=n.getAgentBuilderAction("merge-template"),h=new RC;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}},aOs=({workflowInfo:e,queryOptions:t}={})=>{const n=Ye(),{streamResult:r,isStreaming:s,processStream:i}=XBt(e);return{observeInstall:kn({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 lOs(e){return e.replace(/\/$/,"").split("/").pop()}function cOs({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(hr,"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(nx,On),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(zo,{})," ",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(of,{})," ",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(Edt,{})," ",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(GS,{})," ",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(u_,{})," ",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",Fut,nx,On),children:[a.jsx(xY,{})," ",lOs(i.githubUrl)]})})})]},i.slug)})})}function uOs({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(Ur,{value:t,onValueChange:s,children:[a.jsx(Qr,{"aria-label":"Filter by tag",size:"md",children:a.jsx(qr,{placeholder:"Select an option"})}),a.jsx(Zr,{children:e.map(f=>a.jsx(or,{value:f.value,children:f.label},f.value))})]}),a.jsxs(Ur,{value:r,onValueChange:i,children:[a.jsx(Qr,{"aria-label":"Filter by provider",size:"md",children:a.jsx(qr,{placeholder:"Select an option"})}),a.jsx(Zr,{children:n.map(f=>a.jsx(or,{value:f.value,children:f.label},f.value))})]}),c&&a.jsx(de,{onClick:c,icon:a.jsx(Ln,{}),children:"Reset"})]})}const dOs=[{id:"templates",label:"Templates"}];function fOs(){const{data:e,isLoading:t}=Jks(),{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(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:dOs}),children:[a.jsx("h1",{className:"sr-only",children:"Templates"}),a.jsx(R3,{children:a.jsxs(Gdt,{children:[a.jsx(Nt,{children:a.jsx(C1,{})}),"Templates"]})}),a.jsxs("div",{className:Z("z-10 h-full w-full overflow-y-auto px-5 pb-12"),children:[a.jsx(uOs,{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(cOs,{templates:y,linkComponent:oc,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const hOs="1.75.0-alpha.8";function iJ({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 pOs({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(Gd,{className:"text-warning-foreground"}),title:"Template Installed with Warnings"}:{icon:a.jsx(ejn,{}),title:"Template Installation Failed"},{icon:l,title:c}=o();return a.jsxs(iJ,{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(Fn,"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(bl,{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(Fn,"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(bl,{className:"text-caption wrap-break-word whitespace-pre-wrap",code:n})})]})]})}const mOs=g.createContext(null);function gOs(){const e=g.useContext(mOs);return e||{registerResetFn:()=>{},triggerReset:()=>{}}}const JBt=({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}=qL(),b=T0(),{models:S}=F0(),k=g.useMemo(()=>y?.providers||[],[y]);g.useEffect(()=>{l(t),u(e||"")},[t,e]);const j=so(c),T=bI(k,j)?.id||j,_=async z=>{if(l(z),z&&T){f(!0);try{const Q=await n({provider:T,modelId:z});console.info("Model updated:",Q)}catch(Q){console.error("Failed to update model:",Q)}finally{f(!1)}}},N=z=>{const Q=so(z);u(Q),Q!==j&&(l(""),v(!0))},{registerResetFn:I}=gOs();if(g.useEffect(()=>(I(()=>{if(h||m)return;if(j&&j!==s&&(!o||o==="")){u(so(s)),l(i);const V=bI(k,s)?.id||s;V&&i&&n({provider:V,modelId:i}).catch(H=>{console.error("Failed to reset model:",H)})}}),()=>{I(null)}),[I,j,o,s,i,n,h,m,k]),x)return a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(An,{}),a.jsx(Y,{as:"span",tone:"muted",children:"Loading providers..."})]});const P=async()=>{if(!r){console.warn("Reset model function not provided");return}try{f(!0),await r()}catch(z){console.error("Failed to reset model:",z)}finally{f(!1)}},A=bI(k,j);if(b.active&&b.pickerVisible===!1){const z=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(hr,"flex items-center gap-2 rounded-md px-3 py-2"),"data-testid":"agent-metadata-model-locked",children:[a.jsx(Su,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"caption",tone:"ink",className:"truncate",children:z}),a.jsx(Y,{as:"span",variant:"meta",tone:"muted",className:"ml-auto shrink-0",children:"Set by admin"})]})}const D=!!(j&&o)&&b.active&&b.allowed!==void 0&&!S.some(z=>so(z.provider)===j&&z.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(dk,{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(de,{variant:"default",size:"md",onClick:P,disabled:d,className:"flex items-center gap-1.5 border-0! whitespace-nowrap",title:"Reset to original model",children:a.jsx(JC,{className:"h-3.5 w-3.5"})})]}),D&&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."]})})}),A&&!A.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(A.envVar)?A.envVar.join(", "):A.envVar})," ","environment"," ",Array.isArray(A.envVar)&&A.envVar.length>1?"variables":"variable"," to use this provider."]})})})]})};function vOs({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(iJ,{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(Idt,{})]}),a.jsxs(ft,{orientation:"horizontal",children:[a.jsx(lt,{children:"Template AI Model Provider"}),a.jsx(fmt,{className:"flex-1",children:a.jsxs(Ur,{name:"template-provider",value:t,onValueChange:n,children:[a.jsx(Qr,{size:"md",children:a.jsx(qr,{placeholder:"Select"})}),a.jsx(Zr,{children:e.map(h=>a.jsx(or,{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(An,{}),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(ft,{className:"w-full",children:[a.jsx(lt,{className:"sr-only",children:"Key"}),a.jsx(Sn,{name:`env-${h}`,value:h,disabled:!0,className:"w-full"})]}),a.jsxs(ft,{invalid:s.includes(h),className:"w-full",children:[a.jsx(lt,{className:"sr-only",children:"Value"}),a.jsx(Sn,{name:h,value:p,onChange:o,autoComplete:"off",className:"w-full"}),a.jsx(cs,{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(JBt,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&a.jsx(de,{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(An,{className:"h-4 w-4"})," Installing..."]}):a.jsxs(a.Fragment,{children:["Install ",a.jsx(sp,{})]})})]})})}function yOs({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(C1,{}),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(op,{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(eN,{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(dp,{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(Fn,"mt-auto flex items-center gap-2"),children:[a.jsx(xY,{}),a.jsx(Y,{as:"span",variant:"body",className:"block",children:n?.split("/")?.pop()})]})]}),s&&a.jsx(TEe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function uet(e){switch(e){case"running":return a.jsx(An,{size:"sm","aria-hidden":!0});case"success":return a.jsx(pr,{"aria-hidden":!0});case"failed":return a.jsx(Ln,{"aria-hidden":!0});default:return null}}function xOs(){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 bOs({status:e,variant:t}){return t==="plain"?a.jsx("span",{className:Z("flex size-4 items-center justify-center self-center [&>svg]:size-4",ro.colors,{"[&>svg]:text-success-indicator":e==="success","[&>svg]:text-destructive-foreground":e==="failed"}),children:e==="pending"?a.jsx(xOs,{}):uet(e)}):a.jsx("span",{className:Z("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",ro.colors,ro.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:uet(e)})}function wOs({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",ro.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",ro.colors),children:[n,"."]}),a.jsxs("div",{className:"min-w-0",children:[a.jsx(Y,{as:"h4",tone:s,className:ro.colors,children:e.title}),e.description&&a.jsx(Y,{tone:"faint",className:Z("-mt-0.5",{truncate:r==="plain"}),children:e.description})]})]}),a.jsx(bOs,{status:e.status,variant:r})]})}function SOs({currentStep:e,steps:t=[],className:n}){return a.jsx("div",{className:Z(n),children:t.map((r,s)=>a.jsx(wOs,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function kOs({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",ro.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",ro.colors,ro.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(An,{}):s+1})},r.id))}),a.jsxs("div",{className:Z("text-center text-caption text-muted-foreground",ro.colors),children:[n," of ",t," steps completed"]})]})}function OOs({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(iJ,{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(kOs,{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(HCn,{}),a.jsx(Y,{as:"span",variant:"body",className:"block",children:l||"Something went wrong"})]}),u&&a.jsx(SOs,{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(An,{}),a.jsx(Y,{as:"p",variant:"body",children:"This may take some time..."})]})]})}function jOs({name:e,installedEntities:t}){return a.jsxs(iJ,{className:Z("grid content-center items-center justify-items-center gap-4","[&>svg]:h-8 [&>svg]:w-8"),children:[a.jsx(Idt,{}),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(TEe,{data:t})]})}function COs(){const{templateSlug:e}=fr(),t=[{id:"templates",label:"Templates",to:"/templates"},{id:"template",label:vSe(e)}],[n,r]=pi(),[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:I,isLoading:P}=eOs({repoOrSlug:e,owner:"mastra-ai"}),D=hOs?.includes("beta")??!1?"beta":"main",{data:z,isLoading:Q}=tOs({repo:I?.githubUrl?new URL(I.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:D}),{data:q,isLoading:B}=nOs(),{mutateAsync:V,isPending:H}=rOs(),{mutateAsync:M}=sOs(),{streamInstall:G,streamResult:L,isStreaming:$}=oOs({workflowInfo:q}),{observeInstall:F,streamResult:U,isStreaming:K}=aOs({workflowInfo:q});g.useEffect(()=>{const re=n.get("runId");re&&!y&&!m&&!$&&!K&&(console.info("🔄 Checking completed run after hot reload:",{runId:re}),S(re),M({runId:re}).then(ae=>{const pe=ae.snapshot;if(pe?.status==="success"&&pe?.result?.success)x(!0);else if(pe?.result?.success===!1)if(pe?.result?.validationResults&&!pe?.result?.validationResults?.valid&&pe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:he,errors:Oe}=pe.result.validationResults,Ee=`Template installation completed but ${he} validation issue${he>1?"s":""} remain unresolved.`;v(Ee),N(Oe||[])}else{const he=pe?.result?.message||pe?.result?.error||"Template installation failed";v(typeof he=="string"?he:String(he))}}).catch(ae=>{console.error("❌ Failed to fetch run details:",ae),v("Failed to retrieve installation status after reload")}))},[n,y,m,$,K,M]),g.useEffect(()=>{const re=n.get("runId"),ae=n.get("resume"),pe=n.get("provider");if(re&&ae==="true"&&pe&&!$&&!K&&!k&&!C&&q){S(re),j(!0);try{M({runId:re}).then(ve=>{if(ve.snapshot?.status==="running")return F.mutateAsync({runId:re})}).then(()=>{r(ve=>{const he=new URLSearchParams(ve);return he.delete("resume"),he})}).catch(ve=>{console.error("❌ Failed to resume template installation:",ve),ve.message?.includes("404")||ve.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(ve){console.error("❌ Auto-resume failed with error:",ve),v("Failed to resume template installation. Please refresh and try again.")}}},[n,e,$,K,k,C,q,M,F,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:I?.tools?.length?I.tools.map(re=>re).join(", "):"n/a",icon:a.jsx(of,{})},{key:"agents",label:"Agents",value:I?.agents?.length?I.agents.map(re=>re).join(", "):"n/a",icon:a.jsx(zo,{})},{key:"workflows",label:"Workflows",value:I?.workflows?.length?I.workflows.map(re=>re).join(", "):"n/a",icon:a.jsx(GS,{})},{key:"providers",label:"Providers",value:I?.supportedProviders?.length?I.supportedProviders.join(", "):"n/a",icon:a.jsx(s0,{})},{key:"tags",label:"Tags",value:I?.tags?.length?I.tags.join(", "):"n/a",icon:a.jsx(HS,{})}],te=[{...X[0]},{...X[1]},{...X[2]}].filter(re=>re.value!=="n/a");g.useEffect(()=>{z&&f(z)},[z]),g.useEffect(()=>{const re=L||U;re?.phase==="error"&&re?.error&&v(typeof re.error=="string"?re.error:String(re.error))},[L?.phase,L?.error,U?.phase,U?.error]);const oe=re=>{i(re)},ue=async re=>(l(re.provider),u(re.modelId),{message:"Model updated successfully"}),ee=async()=>{const re=Object.entries(d).reduce((ae,[pe,ve])=>(ve===""&&ae.push(pe),ae),[]);if(re.length>0){p(re);return}if(I){v(null),x(!1),S(""),T(!0);try{const pe={repo:I.githubUrl||`https://github.com/mastra-ai/template-${I.slug}`,ref:D,slug:I.slug,variables:d},{runId:ve}=await V({});S(ve),r(he=>{const Oe=new URLSearchParams(he);return Oe.set("runId",ve),Oe.set("resume","true"),Oe.set("provider",s||"openai"),Oe}),await G.mutateAsync({inputData:pe,selectedModel:{provider:o,modelId:c},runId:ve})}catch(ae){T(!1),v(ae?.message||"Template installation failed"),console.error("Template installation failed",ae)}}},se=re=>{const{name:ae,value:pe}=re.target;pe.trim()===""?p(ve=>[...ve,ae]):p(ve=>ve.filter(he=>he!==ae)),f(ve=>({...ve,[ae]:pe}))};return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{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(yOs,{isLoading:P,title:I?.title,description:I?.longDescription,imageURL:I?.imageURL,githubUrl:I?.githubUrl,infoData:X,templateSlug:e}),I&&a.jsxs(a.Fragment,{children:[($||K)&&a.jsx(OOs,{name:I.title,streamResult:K?U:L,runId:b,workflowInfo:q}),y&&a.jsx(jOs,{name:I.title,installedEntities:te,linkComponent:oc}),m&&a.jsx(pOs,{errorMsg:m,validationErrors:_.length>0?_:L?.validationResults?.errors||U?.validationResults?.errors}),!$&&!K&&!y&&!m&&a.jsx(vOs,{providerOptions:ne,selectedProvider:s,onProviderChange:oe,variables:d,setVariables:f,errors:h,setErrors:p,handleInstallTemplate:ee,handleVariableChange:se,isLoadingEnvVars:Q||B,isInstalling:H,defaultModelProvider:o,defaultModelId:c,onModelUpdate:ue})]})]})})]})}const _Os=()=>{const{toolId:e,agentId:t}=fr(),n=[hs("/agents"),{...xSe,to:t?`/agents/${encodeURIComponent(t)}`:void 0},{id:"agent-tool",Component:Psr}];return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:n}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:"h-full w-full overflow-y-auto",children:a.jsx(Aas,{toolId:e,agentId:t})})]})},TOs=({toolId:e})=>{const{canExecute:t}=Ta(),n=t("tools"),{data:r={}}=pf(),s=g.useMemo(()=>{for(const m of Object.values(r))if(m.tools){const v=Object.values(m.tools).find(y=>y.id===e);if(v)return v}return null},[r,e]),{data:i,isLoading:o,error:l}=vir({toolId:e,queryOptions:{enabled:!s}}),c=s||i,{mutateAsync:u,isPending:d,data:f}=yir();g.useEffect(()=>{if(l){const m=l instanceof Error?l.message:"Failed to load tool";Ge.error(`Error loading tool: ${m}`)}},[l]);const h=async(m,v)=>{if(c)try{return await u({toolId:c.id,input:m,requestContext:v})}catch(y){throw Ge.error("Error executing dev tool"),console.error("Error executing dev tool:",y),y}},p=c?.inputSchema?ix(lS(c?.inputSchema)):vr({});return o?a.jsxs("div",{className:"p-4",children:[a.jsx(bt,{className:"mb-4 h-8 w-48"}),a.jsx(bt,{className:"h-32 w-full"})]}):l?null:c?n?a.jsx(LEe,{executionResult:f,isExecutingTool:d,zodInputSchema:p,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextEntityType:"tool",requestContextEntityId:c.id}):a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(Y,{variant:"caption",tone:"muted",children:"You don't have permission to execute tools."})}):a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(Y,{variant:"heading",tone:"muted",children:"Tool not found"})})},EOs=()=>{const{toolId:e}=fr(),t=[hs("/tools"),Pir];return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:"h-full w-full overflow-y-hidden",children:a.jsx(TOs,{toolId:e})})]})},IOs=()=>a.jsx(tn,{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(de,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/workflows/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Vs,{}),children:"Workflows Documentation"}),variant:"fill"});function NOs(e,t,n){return mk(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 AOs(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function POs(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 $Os(e,t,n){const r=POs(t),s=[],i=(o,l,c,u,d,f)=>{const h=AOs(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 det="auto 24rem minmax(0, 1fr) auto auto auto";function eVt({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 tVt({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(Fn,"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(Gs,{className:Z("size-4 transition-transform",t&&"rotate-90")})}):a.jsx("span",{className:"size-5 shrink-0","aria-hidden":!0})})}const ROs=e=>e.stopPropagation();function u7({sortKey:e,sort:t,onSortChange:n,children:r}){return n?a.jsx(ke.SortableTopCell,{sortKey:e,sort:t?.key===e?t.direction:void 0,onSortChange:s=>n(s,e),children:r}):a.jsx(ke.TopCell,{children:r})}function MOs({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:s}){const{paths:i,Link:o}=hn(),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(ke.RowWrapper,{...s,onSelectRow:()=>l.current?.click(),children:[a.jsx(tVt,{row:e,isExpanded:t,onToggle:n}),a.jsxs(ke.RowLink,{ref:l,colStart:2,to:i.workflowLink(c.id),LinkComponent:o,tabIndex:-1,onClick:ROs,children:[a.jsx(ke.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-1.5",children:[e.depth>0?a.jsx(eVt,{guides:e.guides,isLastChild:e.isLastChild}):null,a.jsx("span",{className:"truncate",children:d}),c.origin==="dynamic"?a.jsx(Ft,{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(GS,{"aria-hidden":!0,className:"size-3.5"}),u.length]}):null]})}),a.jsx(ke.DescriptionCell,{children:f}),a.jsx(ke.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(ke.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(nS,{"aria-hidden":!0,className:"size-3.5"}),m]}):""}),a.jsx(ke.TextCell,{className:"text-center",children:h||""})]})]})}function DOs({workflows:e,isLoading:t,search:n="",sort:r,onSortChange:s,requestContext:i}){const[o,l]=g.useState(new Set),c=f$n({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(()=>NOs(d,r,c),[d,r,c]),h=g.useMemo(()=>$Os(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}=Ru({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(Au,{columns:det,fit:"container"}):a.jsxs(ke,{columns:det,fit:"container",scrollRef:m,children:[a.jsxs(ke.Top,{children:[a.jsx(ke.TopCell,{children:a.jsx("span",{className:"sr-only",children:"Expand"})}),a.jsx(u7,{sortKey:"name",sort:r,onSortChange:s,children:"Name"}),a.jsx(ke.TopCell,{children:"Description"}),a.jsx(u7,{sortKey:"running",sort:r,onSortChange:s,children:"Running"}),a.jsx(u7,{sortKey:"suspended",sort:r,onSortChange:s,children:"Pending input"}),a.jsx(u7,{sortKey:"steps",sort:r,onSortChange:s,children:"Number of steps"})]}),h.length===0&&n?a.jsx(ke.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(ke.RowStatic,{className:"gap-0 px-0",children:[a.jsx(tVt,{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(ke.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(eVt,{guides:x.guides,isLastChild:x.isLastChild}),a.jsx("span",{className:"truncate",children:cf(x.stepId,50)}),a.jsxs($n,{children:[a.jsx(In,{render:a.jsx(Y,{as:"span",variant:"body-sm",tone:"muted"}),role:"note",tabIndex:0,className:Z("shrink-0 rounded-sm",$i),children:"not registered"}),a.jsx(Nn,{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(ke.DescriptionCell,{children:cf(x.description??"",200)}),a.jsx(ke.TextCell,{className:"text-center",children:""}),a.jsx(ke.TextCell,{className:"text-center",children:""}),a.jsx(ke.TextCell,{className:"text-center",children:""})]})]},`workflow-${x.pathKey}`):a.jsx(MOs,{row:x,isExpanded:b,onToggle:S,runCount:c[x.workflow.id],rowProps:v(p.get(x.pathKey)??-1)},`workflow-${x.pathKey}`)})]})}const gM=[hs("/workflows")];function LOs(){const{data:e,isLoading:t,error:n}=vp(),[r,s]=g.useState(""),[i,o]=g.useState();return n&&_s(n)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:gM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(ci,{variant:"fill"})]}):n&&Ts(n)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:gM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Js,{variant:"fill",resource:"workflows"})]}):n?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:gM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(tn,{tone:"error",variant:"fill",titleSlot:"Failed to load workflows",descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:gM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(IOs,{})]}):a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:gM}),actionRow:a.jsxs(Xn,{children:[a.jsx(Xn.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(Pu,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})})}),a.jsx(Xn.End,{children:a.jsx(de,{render:a.jsx(oc,{to:"/workflows/schedules"}),variant:"primary",icon:a.jsx(i0,{}),children:"Schedules"})})]}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(DOs,{workflows:e||{},isLoading:t,search:r,sort:i,onSortChange:(l,c)=>o({key:c,direction:l})})]})}const zOs={active:"bg-success-indicator",paused:"bg-info-indicator",completed:"bg-muted-foreground"},FOs={active:"text-success-indicator",paused:"text-info-indicator",completed:"text-muted-foreground"},nVt=({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 ${zOs[e]}`,"aria-hidden":!0}),a.jsx(Y,{as:"span",variant:"caption",className:FOs[e],children:e})]});function rVt({status:e}){const{icon:t,color:n}=BOs(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 BOs(e){switch(e){case"success":return{icon:a.jsx(pr,{size:14}),color:"text-success-indicator"};case"failed":return{icon:a.jsx(Ln,{size:14}),color:"text-destructive-foreground"};case"running":return{icon:a.jsx(An,{}),color:"text-muted-foreground"};case"suspended":return{icon:a.jsx(rH,{size:14}),color:"text-info-indicator"};case"canceled":return{icon:a.jsx(T3,{size:14}),color:"text-muted-foreground"};case"pending":case"waiting":return{icon:a.jsx(JI,{size:14}),color:"text-muted-foreground"};default:return{icon:null,color:"text-muted-foreground"}}}const fet="auto auto auto auto 1fr",VOs=3e4,UOs=5*6e4;function qOs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:i}){const{Link:o,paths:l}=hn(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=Ru({count:u});let h=-1;return t?a.jsx(Au,{columns:fet}):e.length===0?a.jsx(Y,{variant:"body",tone:"muted",className:"p-4",children:"No trigger history yet."}):a.jsxs(ke,{columns:fet,className:"min-w-0",scrollRef:d,children:[a.jsxs(ke.Top,{children:[a.jsx(ke.TopCell,{children:"Run"}),a.jsx(ke.TopCell,{children:"Status"}),a.jsx(ke.TopCell,{children:"Started"}),a.jsx(ke.TopCell,{children:"Duration"}),a.jsx(ke.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=nf(m,{signed:!0}),y=p.outcome==="failed",x=y?p.error:p.run?.error,b=Math.abs(m),S=!y&&b>VOs&&b<=UOs,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(ke.Cell,{children:C}),a.jsx(ke.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(Gd,{size:14}),"publish failed"]}):p.run?a.jsx(rVt,{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($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-destructive-foreground",children:a.jsx(Gd,{size:14})})}),a.jsx(Nn,{children:x})]}):null]})}),a.jsx(ke.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[p.actualFireAt?a.jsx(fI,{value:p.actualFireAt}):"—",S?a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-info-indicator",children:a.jsx(Gd,{size:14})})}),a.jsxs(Nn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),a.jsx(ke.Cell,{children:p.run?a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",children:nf(p.run.durationMs)||"—"}):a.jsx("span",{className:"text-muted-foreground",children:"—"})}),a.jsx(ke.Cell,{children:" "})]});return j?a.jsx(ke.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:o,...f(h),children:T},k):a.jsx(ke.RowStatic,{children:T},k)}),a.jsx(ke.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:i})]})}const sVt={id:"workflow-schedules",label:"Schedules",icon:i0,to:"/workflows/schedules"};function d7({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 QOs(){const{scheduleId:e}=fr(),t=[hs("/workflows"),sVt,{id:"schedule",label:vSe(e),icon:i0}],{paths:n}=hn(),{data:r,error:s}=Uir({scheduleId:e,queryOptions:{enabled:!!e}}),{data:i,isLoading:o,error:l,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d}=qir({scheduleId:e,queryOptions:{enabled:!!e}}),f=Qir({scheduleId:e});if(s&&_s(s))return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(ci,{variant:"fill"})]});if(s&&Ts(s))return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Js,{variant:"fill",resource:"schedules"})]});if(s)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(tn,{tone:"error",variant:"fill",titleSlot:"Failed to load schedule",descriptionSlot:s.message})]});const h=r?.workflowId,p=r?.agentId;return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:t}),actionRow:a.jsx(Xn,{children:a.jsxs(Xn.End,{children:[a.jsx(de,{render:a.jsx(oc,{to:n.schedulesLink()}),variant:"ghost",icon:a.jsx(fd,{}),children:"Back to schedules"}),h?a.jsx(de,{icon:a.jsx(xl,{}),render:a.jsx(oc,{to:n.workflowLink(h)}),variant:"ghost",children:"Open workflow"}):null,r?a.jsx(de,{onClick:()=>{const m=r.status==="active"?"pause":"resume";f.mutate(m,{onSuccess:()=>Ge.success(m==="pause"?"Schedule paused":"Schedule resumed"),onError:v=>Ge.error(v.message)})},disabled:f.isPending,"data-testid":"schedule-toggle-button",children:r.status==="active"?a.jsxs(a.Fragment,{children:[a.jsx(nS,{}),"Pause"]}):a.jsxs(a.Fragment,{children:[a.jsx(ku,{}),"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(d7,{label:p?"Agent":"Workflow",children:h?a.jsx(oc,{to:n.workflowLink(h),className:"text-foreground hover:underline",children:h}):p?a.jsx(oc,{to:n.agentLink(p),className:"text-foreground hover:underline",children:p}):"—"}),a.jsxs(d7,{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(d7,{label:"Status",children:a.jsx(nVt,{status:r.status})}),a.jsx(d7,{label:"Next fire",children:r.nextFireAt?a.jsx(fI,{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(tn,{tone:"error",titleSlot:"Failed to load trigger history",descriptionSlot:l.message}):a.jsx(qOs,{triggers:i??[],isLoading:o,workflowId:h,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d})]})]}):null]})}const ZOs={target:e=>e.workflowId??e.agentId??"",status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},het="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function WOs({schedules:e,isLoading:t,search:n="",sort:r,onSortChange:s}){const{paths:i,Link:o}=hn(),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 mk(h,r,ZOs)},[e,n,r]),{containerRef:c,getRowProps:u}=Ru({count:l.length,global:!0});if(t)return a.jsx(Au,{columns:het});const d=(f,h)=>s?a.jsx(ke.SortableTopCell,{sortKey:f,sort:r?.key===f?r.direction:void 0,onSortChange:s,children:h}):a.jsx(ke.TopCell,{children:h});return a.jsxs(ke,{columns:het,className:"min-w-0",scrollRef:c,children:[a.jsxs(ke.Top,{children:[d("target","Target"),a.jsx(ke.TopCell,{children:"Schedule ID"}),a.jsx(ke.TopCell,{children:"Cron"}),d("status","Status"),d("nextFireAt","Next fire"),d("lastFireAt","Last run")]}),l.length===0&&n?a.jsx(ke.NoMatch,{message:"No schedules match your search"}):null,l.length===0&&!n?a.jsx(ke.NoMatch,{message:"No schedules configured"}):null,l.map((f,h)=>a.jsxs(ke.RowLink,{to:i.scheduleLink(f.id),LinkComponent:o,...u(h),children:[a.jsx(ke.NameCell,{children:f.workflowId??f.agentId}),a.jsx(ke.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(ke.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(ke.Cell,{children:a.jsx(nVt,{status:f.status})}),a.jsx(ke.Cell,{children:f.nextFireAt?a.jsx(fI,{value:f.nextFireAt}):"—"}),a.jsx(ke.Cell,{children:f.lastRun?a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx(rVt,{status:f.lastRun.status}),f.lastFireAt?a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:a.jsx(fI,{value:f.lastFireAt})}):null]}):f.lastFireAt?a.jsx(fI,{value:f.lastFireAt}):a.jsx("span",{className:"text-muted-foreground",children:"Never"})})]},f.id))]})}function iVt({workflowId:e}={}){const{data:t,isLoading:n,error:r}=TG(e?{workflowId:e}:{}),[s,i]=g.useState(""),[o,l]=g.useState();return r?a.jsx(tn,{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(Pu,{onSearch:i,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),a.jsx("div",{className:"overflow-y-auto",children:a.jsx(WOs,{schedules:t??[],isLoading:n,search:s,sort:o,onSortChange:(c,u)=>l({key:u,direction:c})})})]})}const Oce=[hs("/workflows"),sVt];function HOs(){const[e]=pi(),t=e.get("workflowId")??void 0,{error:n}=TG(t?{workflowId:t}:{});return n&&_s(n)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Oce}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(ci,{variant:"fill"})]}):n&&Ts(n)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Oce}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(Js,{variant:"fill",resource:"schedules"})]}):a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Oce}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx("div",{className:"h-full",children:a.jsx(iVt,{workflowId:t})})]})}const GOs={"--belt-hue":"var(--warning-indicator)"};function KOs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function YOs(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 XOs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:a.jsxs("section",{className:Z(J1e,"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(Nt,{children:a.jsx(rH,{})}),"Step suspended"]}),a.jsx(Ft,{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?ix(lS(i.resumeSchema)):If(Cn(),Ff());return a.jsx(JOs,{step:s,stepSchema:o,description:i.description,onResume:r},`${s.runId}-${s.stepId}`)})]}),a.jsx(m2t,{status:"ready",label:"Needs input",className:"before:hidden",style:GOs})]})}function JOs({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){Ge.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(Nt,{children:a.jsx(DCn,{})}),"The step is asking"]}),a.jsxs(Wl,{open:s,onOpenChange:i,children:[a.jsxs(wl,{className:Z(hr,"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(Nt,{children:a.jsx(Gs,{className:Z("text-muted-foreground transition-transform",{"rotate-90 transform":s})})}),a.jsx(Y,{as:"span",variant:"body",tone:"ink",className:"truncate",children:YOs(e.suspendPayload,e.stepId)})]}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"shrink-0",children:KOs(e.suspendPayload)})]}),a.jsx(Sl,{children:a.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:a.jsx(Cr,{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(Nt,{children:a.jsx(BCn,{})}),"Your response"]}),a.jsx("div",{className:"-mx-5",children:a.jsx(Q1e,{schema:t,isSubmitLoading:o,submitButtonLabel:"Resume",submitButtonVariant:"primary",submitButtonIcon:a.jsx(ku,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:c})})]})]})}function ejs({hidden:e,requestContext:t,canResume:n}){const{result:r,workflow:s,runId:i,isStreamingWorkflow:o}=g.useContext(Ql),l=Kpt(r,i),c=A6n(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(XOs,{suspendedSteps:l,workflow:s,isStreaming:o,onResume:c})},i)}const pet={success:{label:"Completed",icon:pr},failed:{label:"Failed",icon:Dbe},suspended:{label:"Needs input",icon:nS},waiting:{label:"Waiting",icon:sS},paused:{label:"Paused",icon:nS},skipped:{label:"Skipped",icon:eTn},running:{label:"Running",icon:dc},canceled:{label:"Canceled",icon:T3}},tjs={label:"Status unavailable",icon:xOn};function njs({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:s,onOpenInput:i,onOpenOutput:o}){const l=Object.hasOwn(pet,e.status)?pet[e.status]:tjs,c=l.icon,u=r1e(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",$i),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",Gbt[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(Fbe,{"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",hGn[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:nf(e.timing.durationMs)}):a.jsx("span",{"aria-label":"Timing unavailable",children:"—"})}),a.jsxs("div",{className:"flex items-center",children:[a.jsx(de,{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(eH,{})}),a.jsx(de,{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(nH,{})})]})]})}const rjs=e=>e.includes("."),sjs=e=>e==="input"||e.endsWith(".input"),met=1;function ijs(e,t){const n=s1e(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 ojs(e,t){const n=Object.entries(e).filter(([l])=>!sjs(l)).map(([l,c])=>({stepId:l,step:c,...ijs(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-met),v=Math.min(Math.max(p/o*100,met),100-m);h={durationMs:p,offsetPct:m,widthPct:v}}return{stepId:l,step:c,status:lG(c)?"suspended":c.status,timing:h,spansSuspension:f,isRunning:d,isNestedEntry:rjs(l)}})}function ajs(){const{steps:e}=BP(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=wH(),[i,o]=g.useState(()=>Date.now()),[l,c]=g.useState(!0),[u,d]=g.useState(!1),{showData:f}=rk(),h=g.useRef(null),p=ojs(e,i),m=p.some(v=>v.isRunning);return _wt(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(Wl,{open:!l,onOpenChange:v=>c(!v),className:Z(hr,"@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl"),children:[a.jsxs("div",{className:"flex items-center",children:[a.jsxs(wl,{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(idt,{"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(Fl,{"aria-hidden":!0,className:Z("size-4 transition-transform motion-reduce:transition-none",l&&"-rotate-90")})})]}),!l&&a.jsx(de,{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(rOn,{}):a.jsx(adt,{})})]}),a.jsx(Sl,{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(njs,{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 ljs=({workflowId:e,workflow:t,isLoading:n})=>{const[r]=wr("workflow",e),{canExecute:s,isLoading:i}=Ta(),{stepDetail:o}=rk(),l=tP(),c=o?.type==="data",u=a.jsxs("div",{className:"[container-type:size] relative h-full min-h-0",children:[a.jsx(A2t,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),a.jsx(ejs,{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(IB,{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(ajs,{})})]});return l&&o&&!c?a.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:a.jsx(IB,{requestContext:r})}):a.jsxs("div",{className:"relative h-full min-h-0",children:[u,a.jsxs(QP,{className:"pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2",children:[a.jsx(ep,{id:"workflow-graph",className:"pointer-events-none min-w-0"}),o&&!c&&a.jsxs(a.Fragment,{children:[a.jsx(RS,{className:"pointer-events-auto"}),a.jsx(ep,{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(IB,{requestContext:r})})})]})]})]})},get=()=>{const{workflowId:e}=fr(),{data:t,isLoading:n,error:r}=L3({workflowId:e,requestContext:wr("workflow",e)[0],queryOptions:{enabled:!!e}});return r&&_s(r)?a.jsx(ci,{variant:"fill"}):r&&Ts(r)?a.jsx(Js,{variant:"fill",resource:"workflows"}):a.jsx(ljs,{workflowId:e,workflow:t??void 0,isLoading:n})};function cjs(){const{workflowId:e}=fr(),{error:t}=TG(e?{workflowId:e}:{});if(!e)return null;let n;return t&&_s(t)?n=a.jsx(ci,{variant:"fill"}):t&&Ts(t)?n=a.jsx(Js,{variant:"fill",resource:"schedules"}):n=a.jsx("div",{className:"h-full",children:a.jsx(iVt,{workflowId:e})}),a.jsxs(St,{children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),n]})}function ujs(){const{workflowId:e}=fr();return e?a.jsx(DIe,{scopedEntityId:e,scopedEntityType:fu.WORKFLOW_RUN}):null}const oVt=g.createContext(null);function Zc(){const e=g.useContext(oVt);if(!e)throw new Error("Workspace components must be rendered inside <Workspace.Root>");return e}const djs=e=>e?.status;function fjs(e,t){return _s(e)?"Your session has expired. Sign in again to continue.":Ts(e)?"You don't have permission to access this.":ok(e)?"This path no longer exists.":djs(e)===501?"This workspace does not support this operation.":t}function oJ({error:e,fallback:t,className:n}){return a.jsx(Wt,{variant:"destructive",className:n,children:a.jsx(Wt.Message,{children:fjs(e,t)})})}const hjs=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function pjs(e){const t=hjs.exec(e);return t?{frontmatter:t[1]??"",body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function mjs({content:e}){const{frontmatter:t,body:n}=pjs(e);return a.jsxs(a.Fragment,{children:[t!==null&&a.jsx("div",{"data-testid":"workspace-frontmatter",className:"border-b border-border",children:a.jsx(PP,{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(Fc,{children:n})})]})}function gjs(){const{activeFilePath:e}=Zc();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 vjs({path:e,content:t,mimeType:n}){return vAt(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"})}):yAt(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:${xWe(e,n)};base64,${t}`,type:xWe(e,n)})})}):_Dr(e)?a.jsx(mjs,{content:t}):a.jsx(PP,{code:t,lang:B1t(e),overflow:"scroll",className:"rounded-none border-0 bg-transparent [&_pre]:p-4"})}function yjs({renderPreview:e}){const{workspaceId:t,activeFilePath:n}=Zc(),{data:r,isLoading:s,error:i}=MDr({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(oJ,{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(vjs,{...o})}const hA=".",aVt=(e,t)=>e===hA?t:`${e}/${t}`,vet=e=>e.split("/").slice(0,-1).map((t,n,r)=>r.slice(0,n+1).join("/")),lVt=e=>{const t=e.lastIndexOf("/");return t===-1?hA:e.slice(0,t)};function cVt({labeled:e=!1}={}){const{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=Zc(),s=yr(),[i,o]=g.useState(!1),[l,c]=g.useState(""),[u,d]=g.useState(!1);if(!n||r(hA))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",lVt(f)]}),o(!1),c("")}catch{}finally{d(!1)}}};return a.jsxs(a.Fragment,{children:[e?a.jsx(de,{variant:"ghost",icon:a.jsx(eS,{}),onClick:()=>o(!0),children:"New folder"}):a.jsx(de,{variant:"ghost",size:"icon-sm",tooltip:"New folder",onClick:()=>o(!0),children:a.jsx(eS,{})}),a.jsx(rs,{open:i,onOpenChange:o,pending:u,children:a.jsx(ss,{size:"sm",children:a.jsxs("form",{onSubmit:p=>{p.preventDefault(),h()},children:[a.jsx(es,{children:a.jsx(Kr,{children:"New folder"})}),a.jsx(Gr,{children:a.jsx(Sn,{autoFocus:!0,"aria-label":"Folder path",placeholder:"docs/guides",value:l,onChange:p=>c(p.target.value)})}),a.jsxs(Ho,{children:[a.jsx(ja,{children:"Cancel"}),a.jsx(de,{type:"submit",variant:"primary",disabled:!f||u,children:"Create"})]})]})})})]})}function yet(e){return`${e.topSource}/${e.name}`}function xet(e){const t=xAt(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function xjs({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}=EDr({workspaceId:n,queryOptions:{enabled:!!n}}),b=TDr({workspaceId:n}),S=g.useMemo(()=>f?.topSource?xAt(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}=IDr({workspaceId:n,owner:S?.owner,repo:S?.repo,skillPath:f?.name,queryOptions:{enabled:!!n&&!!S&&!!f}}),T=L0(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]),I=b.isPending,P=u.trim().length>=2,A=g.useMemo(()=>{if(!f)return!1;const Q=xet(f);return!!(Q&&i.includes(Q)||o.includes(f.name))},[f,i,o]),D=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]),z=g.useCallback(Q=>{Q||(d(""),h(null),m(void 0)),t(Q)},[t]);return a.jsx(rs,{open:e,onOpenChange:z,pending:s,children:a.jsxs(ss,{size:"xl",className:"h-[80vh]",children:[a.jsxs(es,{children:[a.jsx(Kr,{children:"Add Skill"}),a.jsx(Mo,{children:"Search and install skills from the community registry"})]}),a.jsxs(Gr,{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:P?"Search Results":"Popular Skills"}),a.jsx(Nr,{className:"flex-1 rounded-lg border border-border",children:a.jsx(sf,{className:!x&&!I&&N.length===0?"flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col":void 0,children:x||I?a.jsx("div",{className:"flex items-center justify-center py-5",children:a.jsx(dc,{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(T3,{className:"mb-2 size-8"}),a.jsx(Y,{children:P?"No skills found":"No skills available"})]}):a.jsx("div",{className:"space-y-1 p-2",children:N.map(Q=>{const q=yet(Q),B=xet(Q),V=B&&i.includes(B)||o.includes(Q.name),H=f?yet(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",H===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(pr,{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(ip,{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(XL,{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(xY,{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(ip,{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(Fn,On),title:"View on GitHub",children:a.jsx(Vs,{className:"size-4"})})]})}),C?a.jsx("div",{className:"flex flex-1 items-center justify-center",children:a.jsx(dc,{className:"size-6 animate-spin text-muted-foreground"})}):j?a.jsx(Nr,{className:"flex-1",children:a.jsx("div",{className:"p-4",children:a.jsx(Fc,{children:j})})}):a.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-muted-foreground",children:[a.jsx(C1,{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(Vs,{className:"size-3"})]})]})]}):a.jsxs("div",{className:"flex h-full flex-col items-center justify-center text-muted-foreground",children:[a.jsx(C1,{className:"mb-2 size-8"}),a.jsx(Y,{children:"Select a skill to preview"})]})})]})]}),f&&l&&l.length>1&&a.jsxs(ft,{orientation:"horizontal",className:Z(hr,"gap-3 rounded-lg p-3"),children:[a.jsx(DA,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx(lt,{className:"whitespace-nowrap",children:"Install to"}),a.jsxs(Ur,{value:v,onValueChange:m,children:[a.jsx(Qr,{className:"flex-1",children:a.jsx(qr,{})}),a.jsx(Zr,{children:l.map(Q=>{const q=Q.displayName??Q.name??Q.provider??"unknown";return a.jsxs(or,{value:Q.path,children:[q," (",Q.path,")"]},Q.path)})})]})]})]}),f&&a.jsxs(Ho,{children:[A&&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(ja,{children:"Cancel"}),a.jsx(Oa,{onConfirm:D,disabled:!S||A,"data-testid":"install-skill-button",children:s?"Installing...":A?"Already Installed":"Install"})]})]})})}function uVt({labeled:e=!1}){const{workspaceId:t,addSkill:n}=Zc(),[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(de,{variant:"ghost",onClick:()=>s(!0),children:[a.jsx(Cde,{}),"Add skill"]}):a.jsx(de,{variant:"ghost",size:"icon-sm","aria-label":"Add skill",tooltip:"Add skill",onClick:()=>s(!0),children:a.jsx(Cde,{})}),a.jsx(xjs,{...c,open:r,onOpenChange:s,workspaceId:t,onInstall:d=>{u(d)},isInstalling:i})]})}function bjs({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(vet(t??""))),[b,S]=g.useState(t);if(t!==b){S(t);const C=vet(t??"").filter(T=>!y.has(T));C.length>0&&x(new Set([...y,...C]))}const k=i?.join(`
|
|
694
|
+
`).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 Jks=({queryOptions:e}={})=>kt({queryKey:["mastra-templates"],queryFn:YBt,...e}),eOs=({repoOrSlug:e,owner:t,queryOptions:n})=>kt({queryKey:["template-repo",e,t],queryFn:()=>Yks({repoOrSlug:e,owner:t}),...n}),tOs=({repo:e,owner:t,branch:n,queryOptions:r})=>kt({queryKey:["template-repo-env-vars",e,t,n],queryFn:()=>Xks({repo:e,owner:t,branch:n}),...r}),nOs=({queryOptions:e}={})=>{const t=Ye();return kt({queryKey:["agent-builder-workflow"],queryFn:async()=>await t.getAgentBuilderAction("merge-template").details(),...e})},rOs=({queryOptions:e}={})=>{const t=Ye();return kn({mutationFn:async({runId:n})=>await t.getAgentBuilderAction("merge-template").createRun({runId:n}),...e})},sOs=({queryOptions:e}={})=>{const t=Ye();return kn({mutationFn:async({runId:n})=>await t.getAgentBuilderAction("merge-template").runById(n),...e})},aet=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)},cet=(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=aet(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=aet(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}},iOs=(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)}},XBt=(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}=cet(h,d,e);if(d=p,r(p),h.runId||c||t){const m=h.runId||c||t;iOs(m,p)}}}catch(f){console.error("💥 [processStream] Error processing template installation stream:",f);const{newState:h}=cet({type:"error",payload:{error:f instanceof Error?f.message:"Unknown error"}},d,e);r(h)}finally{i(!1),u.releaseLock()}}}},oOs=({workflowInfo:e,queryOptions:t}={})=>{const n=Ye(),{streamResult:r,isStreaming:s,processStream:i}=XBt(e);return{streamInstall:kn({mutationFn:async({inputData:o,selectedModel:l,runId:c})=>{for(let d=1;d<=3;d++)try{const f=n.getAgentBuilderAction("merge-template"),h=new RC;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}},aOs=({workflowInfo:e,queryOptions:t}={})=>{const n=Ye(),{streamResult:r,isStreaming:s,processStream:i}=XBt(e);return{observeInstall:kn({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 lOs(e){return e.replace(/\/$/,"").split("/").pop()}function cOs({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(hr,"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(nx,On),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(zo,{})," ",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(of,{})," ",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(Edt,{})," ",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(GS,{})," ",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(u_,{})," ",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",Fut,nx,On),children:[a.jsx(xY,{})," ",lOs(i.githubUrl)]})})})]},i.slug)})})}function uOs({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(Ur,{value:t,onValueChange:s,children:[a.jsx(Qr,{"aria-label":"Filter by tag",size:"md",children:a.jsx(qr,{placeholder:"Select an option"})}),a.jsx(Zr,{children:e.map(f=>a.jsx(or,{value:f.value,children:f.label},f.value))})]}),a.jsxs(Ur,{value:r,onValueChange:i,children:[a.jsx(Qr,{"aria-label":"Filter by provider",size:"md",children:a.jsx(qr,{placeholder:"Select an option"})}),a.jsx(Zr,{children:n.map(f=>a.jsx(or,{value:f.value,children:f.label},f.value))})]}),c&&a.jsx(de,{onClick:c,icon:a.jsx(Ln,{}),children:"Reset"})]})}const dOs=[{id:"templates",label:"Templates"}];function fOs(){const{data:e,isLoading:t}=Jks(),{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(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:dOs}),children:[a.jsx("h1",{className:"sr-only",children:"Templates"}),a.jsx(R3,{children:a.jsxs(Gdt,{children:[a.jsx(Nt,{children:a.jsx(C1,{})}),"Templates"]})}),a.jsxs("div",{className:Z("z-10 h-full w-full overflow-y-auto px-5 pb-12"),children:[a.jsx(uOs,{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(cOs,{templates:y,linkComponent:oc,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const hOs="1.75.0";function iJ({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 pOs({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(Gd,{className:"text-warning-foreground"}),title:"Template Installed with Warnings"}:{icon:a.jsx(ejn,{}),title:"Template Installation Failed"},{icon:l,title:c}=o();return a.jsxs(iJ,{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(Fn,"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(bl,{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(Fn,"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(bl,{className:"text-caption wrap-break-word whitespace-pre-wrap",code:n})})]})]})}const mOs=g.createContext(null);function gOs(){const e=g.useContext(mOs);return e||{registerResetFn:()=>{},triggerReset:()=>{}}}const JBt=({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}=qL(),b=T0(),{models:S}=F0(),k=g.useMemo(()=>y?.providers||[],[y]);g.useEffect(()=>{l(t),u(e||"")},[t,e]);const j=so(c),T=bI(k,j)?.id||j,_=async z=>{if(l(z),z&&T){f(!0);try{const Q=await n({provider:T,modelId:z});console.info("Model updated:",Q)}catch(Q){console.error("Failed to update model:",Q)}finally{f(!1)}}},N=z=>{const Q=so(z);u(Q),Q!==j&&(l(""),v(!0))},{registerResetFn:I}=gOs();if(g.useEffect(()=>(I(()=>{if(h||m)return;if(j&&j!==s&&(!o||o==="")){u(so(s)),l(i);const V=bI(k,s)?.id||s;V&&i&&n({provider:V,modelId:i}).catch(H=>{console.error("Failed to reset model:",H)})}}),()=>{I(null)}),[I,j,o,s,i,n,h,m,k]),x)return a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(An,{}),a.jsx(Y,{as:"span",tone:"muted",children:"Loading providers..."})]});const P=async()=>{if(!r){console.warn("Reset model function not provided");return}try{f(!0),await r()}catch(z){console.error("Failed to reset model:",z)}finally{f(!1)}},A=bI(k,j);if(b.active&&b.pickerVisible===!1){const z=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(hr,"flex items-center gap-2 rounded-md px-3 py-2"),"data-testid":"agent-metadata-model-locked",children:[a.jsx(Su,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"caption",tone:"ink",className:"truncate",children:z}),a.jsx(Y,{as:"span",variant:"meta",tone:"muted",className:"ml-auto shrink-0",children:"Set by admin"})]})}const D=!!(j&&o)&&b.active&&b.allowed!==void 0&&!S.some(z=>so(z.provider)===j&&z.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(dk,{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(de,{variant:"default",size:"md",onClick:P,disabled:d,className:"flex items-center gap-1.5 border-0! whitespace-nowrap",title:"Reset to original model",children:a.jsx(JC,{className:"h-3.5 w-3.5"})})]}),D&&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."]})})}),A&&!A.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(A.envVar)?A.envVar.join(", "):A.envVar})," ","environment"," ",Array.isArray(A.envVar)&&A.envVar.length>1?"variables":"variable"," to use this provider."]})})})]})};function vOs({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(iJ,{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(Idt,{})]}),a.jsxs(ft,{orientation:"horizontal",children:[a.jsx(lt,{children:"Template AI Model Provider"}),a.jsx(fmt,{className:"flex-1",children:a.jsxs(Ur,{name:"template-provider",value:t,onValueChange:n,children:[a.jsx(Qr,{size:"md",children:a.jsx(qr,{placeholder:"Select"})}),a.jsx(Zr,{children:e.map(h=>a.jsx(or,{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(An,{}),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(ft,{className:"w-full",children:[a.jsx(lt,{className:"sr-only",children:"Key"}),a.jsx(Sn,{name:`env-${h}`,value:h,disabled:!0,className:"w-full"})]}),a.jsxs(ft,{invalid:s.includes(h),className:"w-full",children:[a.jsx(lt,{className:"sr-only",children:"Value"}),a.jsx(Sn,{name:h,value:p,onChange:o,autoComplete:"off",className:"w-full"}),a.jsx(cs,{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(JBt,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&a.jsx(de,{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(An,{className:"h-4 w-4"})," Installing..."]}):a.jsxs(a.Fragment,{children:["Install ",a.jsx(sp,{})]})})]})})}function yOs({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(C1,{}),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(op,{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(eN,{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(dp,{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(Fn,"mt-auto flex items-center gap-2"),children:[a.jsx(xY,{}),a.jsx(Y,{as:"span",variant:"body",className:"block",children:n?.split("/")?.pop()})]})]}),s&&a.jsx(TEe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function uet(e){switch(e){case"running":return a.jsx(An,{size:"sm","aria-hidden":!0});case"success":return a.jsx(pr,{"aria-hidden":!0});case"failed":return a.jsx(Ln,{"aria-hidden":!0});default:return null}}function xOs(){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 bOs({status:e,variant:t}){return t==="plain"?a.jsx("span",{className:Z("flex size-4 items-center justify-center self-center [&>svg]:size-4",ro.colors,{"[&>svg]:text-success-indicator":e==="success","[&>svg]:text-destructive-foreground":e==="failed"}),children:e==="pending"?a.jsx(xOs,{}):uet(e)}):a.jsx("span",{className:Z("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",ro.colors,ro.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:uet(e)})}function wOs({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",ro.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",ro.colors),children:[n,"."]}),a.jsxs("div",{className:"min-w-0",children:[a.jsx(Y,{as:"h4",tone:s,className:ro.colors,children:e.title}),e.description&&a.jsx(Y,{tone:"faint",className:Z("-mt-0.5",{truncate:r==="plain"}),children:e.description})]})]}),a.jsx(bOs,{status:e.status,variant:r})]})}function SOs({currentStep:e,steps:t=[],className:n}){return a.jsx("div",{className:Z(n),children:t.map((r,s)=>a.jsx(wOs,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function kOs({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",ro.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",ro.colors,ro.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(An,{}):s+1})},r.id))}),a.jsxs("div",{className:Z("text-center text-caption text-muted-foreground",ro.colors),children:[n," of ",t," steps completed"]})]})}function OOs({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(iJ,{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(kOs,{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(HCn,{}),a.jsx(Y,{as:"span",variant:"body",className:"block",children:l||"Something went wrong"})]}),u&&a.jsx(SOs,{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(An,{}),a.jsx(Y,{as:"p",variant:"body",children:"This may take some time..."})]})]})}function jOs({name:e,installedEntities:t}){return a.jsxs(iJ,{className:Z("grid content-center items-center justify-items-center gap-4","[&>svg]:h-8 [&>svg]:w-8"),children:[a.jsx(Idt,{}),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(TEe,{data:t})]})}function COs(){const{templateSlug:e}=fr(),t=[{id:"templates",label:"Templates",to:"/templates"},{id:"template",label:vSe(e)}],[n,r]=pi(),[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:I,isLoading:P}=eOs({repoOrSlug:e,owner:"mastra-ai"}),D=hOs?.includes("beta")??!1?"beta":"main",{data:z,isLoading:Q}=tOs({repo:I?.githubUrl?new URL(I.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:D}),{data:q,isLoading:B}=nOs(),{mutateAsync:V,isPending:H}=rOs(),{mutateAsync:M}=sOs(),{streamInstall:G,streamResult:L,isStreaming:$}=oOs({workflowInfo:q}),{observeInstall:F,streamResult:U,isStreaming:K}=aOs({workflowInfo:q});g.useEffect(()=>{const re=n.get("runId");re&&!y&&!m&&!$&&!K&&(console.info("🔄 Checking completed run after hot reload:",{runId:re}),S(re),M({runId:re}).then(ae=>{const pe=ae.snapshot;if(pe?.status==="success"&&pe?.result?.success)x(!0);else if(pe?.result?.success===!1)if(pe?.result?.validationResults&&!pe?.result?.validationResults?.valid&&pe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:he,errors:Oe}=pe.result.validationResults,Ee=`Template installation completed but ${he} validation issue${he>1?"s":""} remain unresolved.`;v(Ee),N(Oe||[])}else{const he=pe?.result?.message||pe?.result?.error||"Template installation failed";v(typeof he=="string"?he:String(he))}}).catch(ae=>{console.error("❌ Failed to fetch run details:",ae),v("Failed to retrieve installation status after reload")}))},[n,y,m,$,K,M]),g.useEffect(()=>{const re=n.get("runId"),ae=n.get("resume"),pe=n.get("provider");if(re&&ae==="true"&&pe&&!$&&!K&&!k&&!C&&q){S(re),j(!0);try{M({runId:re}).then(ve=>{if(ve.snapshot?.status==="running")return F.mutateAsync({runId:re})}).then(()=>{r(ve=>{const he=new URLSearchParams(ve);return he.delete("resume"),he})}).catch(ve=>{console.error("❌ Failed to resume template installation:",ve),ve.message?.includes("404")||ve.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(ve){console.error("❌ Auto-resume failed with error:",ve),v("Failed to resume template installation. Please refresh and try again.")}}},[n,e,$,K,k,C,q,M,F,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:I?.tools?.length?I.tools.map(re=>re).join(", "):"n/a",icon:a.jsx(of,{})},{key:"agents",label:"Agents",value:I?.agents?.length?I.agents.map(re=>re).join(", "):"n/a",icon:a.jsx(zo,{})},{key:"workflows",label:"Workflows",value:I?.workflows?.length?I.workflows.map(re=>re).join(", "):"n/a",icon:a.jsx(GS,{})},{key:"providers",label:"Providers",value:I?.supportedProviders?.length?I.supportedProviders.join(", "):"n/a",icon:a.jsx(s0,{})},{key:"tags",label:"Tags",value:I?.tags?.length?I.tags.join(", "):"n/a",icon:a.jsx(HS,{})}],te=[{...X[0]},{...X[1]},{...X[2]}].filter(re=>re.value!=="n/a");g.useEffect(()=>{z&&f(z)},[z]),g.useEffect(()=>{const re=L||U;re?.phase==="error"&&re?.error&&v(typeof re.error=="string"?re.error:String(re.error))},[L?.phase,L?.error,U?.phase,U?.error]);const oe=re=>{i(re)},ue=async re=>(l(re.provider),u(re.modelId),{message:"Model updated successfully"}),ee=async()=>{const re=Object.entries(d).reduce((ae,[pe,ve])=>(ve===""&&ae.push(pe),ae),[]);if(re.length>0){p(re);return}if(I){v(null),x(!1),S(""),T(!0);try{const pe={repo:I.githubUrl||`https://github.com/mastra-ai/template-${I.slug}`,ref:D,slug:I.slug,variables:d},{runId:ve}=await V({});S(ve),r(he=>{const Oe=new URLSearchParams(he);return Oe.set("runId",ve),Oe.set("resume","true"),Oe.set("provider",s||"openai"),Oe}),await G.mutateAsync({inputData:pe,selectedModel:{provider:o,modelId:c},runId:ve})}catch(ae){T(!1),v(ae?.message||"Template installation failed"),console.error("Template installation failed",ae)}}},se=re=>{const{name:ae,value:pe}=re.target;pe.trim()===""?p(ve=>[...ve,ae]):p(ve=>ve.filter(he=>he!==ae)),f(ve=>({...ve,[ae]:pe}))};return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{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(yOs,{isLoading:P,title:I?.title,description:I?.longDescription,imageURL:I?.imageURL,githubUrl:I?.githubUrl,infoData:X,templateSlug:e}),I&&a.jsxs(a.Fragment,{children:[($||K)&&a.jsx(OOs,{name:I.title,streamResult:K?U:L,runId:b,workflowInfo:q}),y&&a.jsx(jOs,{name:I.title,installedEntities:te,linkComponent:oc}),m&&a.jsx(pOs,{errorMsg:m,validationErrors:_.length>0?_:L?.validationResults?.errors||U?.validationResults?.errors}),!$&&!K&&!y&&!m&&a.jsx(vOs,{providerOptions:ne,selectedProvider:s,onProviderChange:oe,variables:d,setVariables:f,errors:h,setErrors:p,handleInstallTemplate:ee,handleVariableChange:se,isLoadingEnvVars:Q||B,isInstalling:H,defaultModelProvider:o,defaultModelId:c,onModelUpdate:ue})]})]})})]})}const _Os=()=>{const{toolId:e,agentId:t}=fr(),n=[hs("/agents"),{...xSe,to:t?`/agents/${encodeURIComponent(t)}`:void 0},{id:"agent-tool",Component:Psr}];return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:n}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:"h-full w-full overflow-y-auto",children:a.jsx(Aas,{toolId:e,agentId:t})})]})},TOs=({toolId:e})=>{const{canExecute:t}=Ta(),n=t("tools"),{data:r={}}=pf(),s=g.useMemo(()=>{for(const m of Object.values(r))if(m.tools){const v=Object.values(m.tools).find(y=>y.id===e);if(v)return v}return null},[r,e]),{data:i,isLoading:o,error:l}=vir({toolId:e,queryOptions:{enabled:!s}}),c=s||i,{mutateAsync:u,isPending:d,data:f}=yir();g.useEffect(()=>{if(l){const m=l instanceof Error?l.message:"Failed to load tool";Ge.error(`Error loading tool: ${m}`)}},[l]);const h=async(m,v)=>{if(c)try{return await u({toolId:c.id,input:m,requestContext:v})}catch(y){throw Ge.error("Error executing dev tool"),console.error("Error executing dev tool:",y),y}},p=c?.inputSchema?ix(lS(c?.inputSchema)):vr({});return o?a.jsxs("div",{className:"p-4",children:[a.jsx(bt,{className:"mb-4 h-8 w-48"}),a.jsx(bt,{className:"h-32 w-full"})]}):l?null:c?n?a.jsx(LEe,{executionResult:f,isExecutingTool:d,zodInputSchema:p,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextEntityType:"tool",requestContextEntityId:c.id}):a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(Y,{variant:"caption",tone:"muted",children:"You don't have permission to execute tools."})}):a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(Y,{variant:"heading",tone:"muted",children:"Tool not found"})})},EOs=()=>{const{toolId:e}=fr(),t=[hs("/tools"),Pir];return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:"h-full w-full overflow-y-hidden",children:a.jsx(TOs,{toolId:e})})]})},IOs=()=>a.jsx(tn,{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(de,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/workflows/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Vs,{}),children:"Workflows Documentation"}),variant:"fill"});function NOs(e,t,n){return mk(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 AOs(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function POs(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 $Os(e,t,n){const r=POs(t),s=[],i=(o,l,c,u,d,f)=>{const h=AOs(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 det="auto 24rem minmax(0, 1fr) auto auto auto";function eVt({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 tVt({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(Fn,"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(Gs,{className:Z("size-4 transition-transform",t&&"rotate-90")})}):a.jsx("span",{className:"size-5 shrink-0","aria-hidden":!0})})}const ROs=e=>e.stopPropagation();function u7({sortKey:e,sort:t,onSortChange:n,children:r}){return n?a.jsx(ke.SortableTopCell,{sortKey:e,sort:t?.key===e?t.direction:void 0,onSortChange:s=>n(s,e),children:r}):a.jsx(ke.TopCell,{children:r})}function MOs({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:s}){const{paths:i,Link:o}=hn(),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(ke.RowWrapper,{...s,onSelectRow:()=>l.current?.click(),children:[a.jsx(tVt,{row:e,isExpanded:t,onToggle:n}),a.jsxs(ke.RowLink,{ref:l,colStart:2,to:i.workflowLink(c.id),LinkComponent:o,tabIndex:-1,onClick:ROs,children:[a.jsx(ke.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-1.5",children:[e.depth>0?a.jsx(eVt,{guides:e.guides,isLastChild:e.isLastChild}):null,a.jsx("span",{className:"truncate",children:d}),c.origin==="dynamic"?a.jsx(Ft,{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(GS,{"aria-hidden":!0,className:"size-3.5"}),u.length]}):null]})}),a.jsx(ke.DescriptionCell,{children:f}),a.jsx(ke.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(ke.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(nS,{"aria-hidden":!0,className:"size-3.5"}),m]}):""}),a.jsx(ke.TextCell,{className:"text-center",children:h||""})]})]})}function DOs({workflows:e,isLoading:t,search:n="",sort:r,onSortChange:s,requestContext:i}){const[o,l]=g.useState(new Set),c=f$n({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(()=>NOs(d,r,c),[d,r,c]),h=g.useMemo(()=>$Os(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}=Ru({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(Au,{columns:det,fit:"container"}):a.jsxs(ke,{columns:det,fit:"container",scrollRef:m,children:[a.jsxs(ke.Top,{children:[a.jsx(ke.TopCell,{children:a.jsx("span",{className:"sr-only",children:"Expand"})}),a.jsx(u7,{sortKey:"name",sort:r,onSortChange:s,children:"Name"}),a.jsx(ke.TopCell,{children:"Description"}),a.jsx(u7,{sortKey:"running",sort:r,onSortChange:s,children:"Running"}),a.jsx(u7,{sortKey:"suspended",sort:r,onSortChange:s,children:"Pending input"}),a.jsx(u7,{sortKey:"steps",sort:r,onSortChange:s,children:"Number of steps"})]}),h.length===0&&n?a.jsx(ke.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(ke.RowStatic,{className:"gap-0 px-0",children:[a.jsx(tVt,{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(ke.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(eVt,{guides:x.guides,isLastChild:x.isLastChild}),a.jsx("span",{className:"truncate",children:cf(x.stepId,50)}),a.jsxs($n,{children:[a.jsx(In,{render:a.jsx(Y,{as:"span",variant:"body-sm",tone:"muted"}),role:"note",tabIndex:0,className:Z("shrink-0 rounded-sm",$i),children:"not registered"}),a.jsx(Nn,{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(ke.DescriptionCell,{children:cf(x.description??"",200)}),a.jsx(ke.TextCell,{className:"text-center",children:""}),a.jsx(ke.TextCell,{className:"text-center",children:""}),a.jsx(ke.TextCell,{className:"text-center",children:""})]})]},`workflow-${x.pathKey}`):a.jsx(MOs,{row:x,isExpanded:b,onToggle:S,runCount:c[x.workflow.id],rowProps:v(p.get(x.pathKey)??-1)},`workflow-${x.pathKey}`)})]})}const gM=[hs("/workflows")];function LOs(){const{data:e,isLoading:t,error:n}=vp(),[r,s]=g.useState(""),[i,o]=g.useState();return n&&_s(n)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:gM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(ci,{variant:"fill"})]}):n&&Ts(n)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:gM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Js,{variant:"fill",resource:"workflows"})]}):n?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:gM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(tn,{tone:"error",variant:"fill",titleSlot:"Failed to load workflows",descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:gM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(IOs,{})]}):a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:gM}),actionRow:a.jsxs(Xn,{children:[a.jsx(Xn.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(Pu,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})})}),a.jsx(Xn.End,{children:a.jsx(de,{render:a.jsx(oc,{to:"/workflows/schedules"}),variant:"primary",icon:a.jsx(i0,{}),children:"Schedules"})})]}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(DOs,{workflows:e||{},isLoading:t,search:r,sort:i,onSortChange:(l,c)=>o({key:c,direction:l})})]})}const zOs={active:"bg-success-indicator",paused:"bg-info-indicator",completed:"bg-muted-foreground"},FOs={active:"text-success-indicator",paused:"text-info-indicator",completed:"text-muted-foreground"},nVt=({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 ${zOs[e]}`,"aria-hidden":!0}),a.jsx(Y,{as:"span",variant:"caption",className:FOs[e],children:e})]});function rVt({status:e}){const{icon:t,color:n}=BOs(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 BOs(e){switch(e){case"success":return{icon:a.jsx(pr,{size:14}),color:"text-success-indicator"};case"failed":return{icon:a.jsx(Ln,{size:14}),color:"text-destructive-foreground"};case"running":return{icon:a.jsx(An,{}),color:"text-muted-foreground"};case"suspended":return{icon:a.jsx(rH,{size:14}),color:"text-info-indicator"};case"canceled":return{icon:a.jsx(T3,{size:14}),color:"text-muted-foreground"};case"pending":case"waiting":return{icon:a.jsx(JI,{size:14}),color:"text-muted-foreground"};default:return{icon:null,color:"text-muted-foreground"}}}const fet="auto auto auto auto 1fr",VOs=3e4,UOs=5*6e4;function qOs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:i}){const{Link:o,paths:l}=hn(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=Ru({count:u});let h=-1;return t?a.jsx(Au,{columns:fet}):e.length===0?a.jsx(Y,{variant:"body",tone:"muted",className:"p-4",children:"No trigger history yet."}):a.jsxs(ke,{columns:fet,className:"min-w-0",scrollRef:d,children:[a.jsxs(ke.Top,{children:[a.jsx(ke.TopCell,{children:"Run"}),a.jsx(ke.TopCell,{children:"Status"}),a.jsx(ke.TopCell,{children:"Started"}),a.jsx(ke.TopCell,{children:"Duration"}),a.jsx(ke.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=nf(m,{signed:!0}),y=p.outcome==="failed",x=y?p.error:p.run?.error,b=Math.abs(m),S=!y&&b>VOs&&b<=UOs,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(ke.Cell,{children:C}),a.jsx(ke.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(Gd,{size:14}),"publish failed"]}):p.run?a.jsx(rVt,{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($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-destructive-foreground",children:a.jsx(Gd,{size:14})})}),a.jsx(Nn,{children:x})]}):null]})}),a.jsx(ke.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[p.actualFireAt?a.jsx(fI,{value:p.actualFireAt}):"—",S?a.jsxs($n,{children:[a.jsx(In,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-info-indicator",children:a.jsx(Gd,{size:14})})}),a.jsxs(Nn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),a.jsx(ke.Cell,{children:p.run?a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",children:nf(p.run.durationMs)||"—"}):a.jsx("span",{className:"text-muted-foreground",children:"—"})}),a.jsx(ke.Cell,{children:" "})]});return j?a.jsx(ke.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:o,...f(h),children:T},k):a.jsx(ke.RowStatic,{children:T},k)}),a.jsx(ke.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:i})]})}const sVt={id:"workflow-schedules",label:"Schedules",icon:i0,to:"/workflows/schedules"};function d7({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 QOs(){const{scheduleId:e}=fr(),t=[hs("/workflows"),sVt,{id:"schedule",label:vSe(e),icon:i0}],{paths:n}=hn(),{data:r,error:s}=Uir({scheduleId:e,queryOptions:{enabled:!!e}}),{data:i,isLoading:o,error:l,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d}=qir({scheduleId:e,queryOptions:{enabled:!!e}}),f=Qir({scheduleId:e});if(s&&_s(s))return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(ci,{variant:"fill"})]});if(s&&Ts(s))return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Js,{variant:"fill",resource:"schedules"})]});if(s)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(tn,{tone:"error",variant:"fill",titleSlot:"Failed to load schedule",descriptionSlot:s.message})]});const h=r?.workflowId,p=r?.agentId;return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:t}),actionRow:a.jsx(Xn,{children:a.jsxs(Xn.End,{children:[a.jsx(de,{render:a.jsx(oc,{to:n.schedulesLink()}),variant:"ghost",icon:a.jsx(fd,{}),children:"Back to schedules"}),h?a.jsx(de,{icon:a.jsx(xl,{}),render:a.jsx(oc,{to:n.workflowLink(h)}),variant:"ghost",children:"Open workflow"}):null,r?a.jsx(de,{onClick:()=>{const m=r.status==="active"?"pause":"resume";f.mutate(m,{onSuccess:()=>Ge.success(m==="pause"?"Schedule paused":"Schedule resumed"),onError:v=>Ge.error(v.message)})},disabled:f.isPending,"data-testid":"schedule-toggle-button",children:r.status==="active"?a.jsxs(a.Fragment,{children:[a.jsx(nS,{}),"Pause"]}):a.jsxs(a.Fragment,{children:[a.jsx(ku,{}),"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(d7,{label:p?"Agent":"Workflow",children:h?a.jsx(oc,{to:n.workflowLink(h),className:"text-foreground hover:underline",children:h}):p?a.jsx(oc,{to:n.agentLink(p),className:"text-foreground hover:underline",children:p}):"—"}),a.jsxs(d7,{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(d7,{label:"Status",children:a.jsx(nVt,{status:r.status})}),a.jsx(d7,{label:"Next fire",children:r.nextFireAt?a.jsx(fI,{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(tn,{tone:"error",titleSlot:"Failed to load trigger history",descriptionSlot:l.message}):a.jsx(qOs,{triggers:i??[],isLoading:o,workflowId:h,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d})]})]}):null]})}const ZOs={target:e=>e.workflowId??e.agentId??"",status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},het="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function WOs({schedules:e,isLoading:t,search:n="",sort:r,onSortChange:s}){const{paths:i,Link:o}=hn(),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 mk(h,r,ZOs)},[e,n,r]),{containerRef:c,getRowProps:u}=Ru({count:l.length,global:!0});if(t)return a.jsx(Au,{columns:het});const d=(f,h)=>s?a.jsx(ke.SortableTopCell,{sortKey:f,sort:r?.key===f?r.direction:void 0,onSortChange:s,children:h}):a.jsx(ke.TopCell,{children:h});return a.jsxs(ke,{columns:het,className:"min-w-0",scrollRef:c,children:[a.jsxs(ke.Top,{children:[d("target","Target"),a.jsx(ke.TopCell,{children:"Schedule ID"}),a.jsx(ke.TopCell,{children:"Cron"}),d("status","Status"),d("nextFireAt","Next fire"),d("lastFireAt","Last run")]}),l.length===0&&n?a.jsx(ke.NoMatch,{message:"No schedules match your search"}):null,l.length===0&&!n?a.jsx(ke.NoMatch,{message:"No schedules configured"}):null,l.map((f,h)=>a.jsxs(ke.RowLink,{to:i.scheduleLink(f.id),LinkComponent:o,...u(h),children:[a.jsx(ke.NameCell,{children:f.workflowId??f.agentId}),a.jsx(ke.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(ke.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(ke.Cell,{children:a.jsx(nVt,{status:f.status})}),a.jsx(ke.Cell,{children:f.nextFireAt?a.jsx(fI,{value:f.nextFireAt}):"—"}),a.jsx(ke.Cell,{children:f.lastRun?a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx(rVt,{status:f.lastRun.status}),f.lastFireAt?a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:a.jsx(fI,{value:f.lastFireAt})}):null]}):f.lastFireAt?a.jsx(fI,{value:f.lastFireAt}):a.jsx("span",{className:"text-muted-foreground",children:"Never"})})]},f.id))]})}function iVt({workflowId:e}={}){const{data:t,isLoading:n,error:r}=TG(e?{workflowId:e}:{}),[s,i]=g.useState(""),[o,l]=g.useState();return r?a.jsx(tn,{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(Pu,{onSearch:i,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),a.jsx("div",{className:"overflow-y-auto",children:a.jsx(WOs,{schedules:t??[],isLoading:n,search:s,sort:o,onSortChange:(c,u)=>l({key:u,direction:c})})})]})}const Oce=[hs("/workflows"),sVt];function HOs(){const[e]=pi(),t=e.get("workflowId")??void 0,{error:n}=TG(t?{workflowId:t}:{});return n&&_s(n)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Oce}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(ci,{variant:"fill"})]}):n&&Ts(n)?a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Oce}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(Js,{variant:"fill",resource:"schedules"})]}):a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Oce}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx("div",{className:"h-full",children:a.jsx(iVt,{workflowId:t})})]})}const GOs={"--belt-hue":"var(--warning-indicator)"};function KOs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function YOs(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 XOs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:a.jsxs("section",{className:Z(J1e,"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(Nt,{children:a.jsx(rH,{})}),"Step suspended"]}),a.jsx(Ft,{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?ix(lS(i.resumeSchema)):If(Cn(),Ff());return a.jsx(JOs,{step:s,stepSchema:o,description:i.description,onResume:r},`${s.runId}-${s.stepId}`)})]}),a.jsx(m2t,{status:"ready",label:"Needs input",className:"before:hidden",style:GOs})]})}function JOs({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){Ge.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(Nt,{children:a.jsx(DCn,{})}),"The step is asking"]}),a.jsxs(Wl,{open:s,onOpenChange:i,children:[a.jsxs(wl,{className:Z(hr,"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(Nt,{children:a.jsx(Gs,{className:Z("text-muted-foreground transition-transform",{"rotate-90 transform":s})})}),a.jsx(Y,{as:"span",variant:"body",tone:"ink",className:"truncate",children:YOs(e.suspendPayload,e.stepId)})]}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"shrink-0",children:KOs(e.suspendPayload)})]}),a.jsx(Sl,{children:a.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:a.jsx(Cr,{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(Nt,{children:a.jsx(BCn,{})}),"Your response"]}),a.jsx("div",{className:"-mx-5",children:a.jsx(Q1e,{schema:t,isSubmitLoading:o,submitButtonLabel:"Resume",submitButtonVariant:"primary",submitButtonIcon:a.jsx(ku,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:c})})]})]})}function ejs({hidden:e,requestContext:t,canResume:n}){const{result:r,workflow:s,runId:i,isStreamingWorkflow:o}=g.useContext(Ql),l=Kpt(r,i),c=A6n(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(XOs,{suspendedSteps:l,workflow:s,isStreaming:o,onResume:c})},i)}const pet={success:{label:"Completed",icon:pr},failed:{label:"Failed",icon:Dbe},suspended:{label:"Needs input",icon:nS},waiting:{label:"Waiting",icon:sS},paused:{label:"Paused",icon:nS},skipped:{label:"Skipped",icon:eTn},running:{label:"Running",icon:dc},canceled:{label:"Canceled",icon:T3}},tjs={label:"Status unavailable",icon:xOn};function njs({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:s,onOpenInput:i,onOpenOutput:o}){const l=Object.hasOwn(pet,e.status)?pet[e.status]:tjs,c=l.icon,u=r1e(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",$i),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",Gbt[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(Fbe,{"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",hGn[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:nf(e.timing.durationMs)}):a.jsx("span",{"aria-label":"Timing unavailable",children:"—"})}),a.jsxs("div",{className:"flex items-center",children:[a.jsx(de,{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(eH,{})}),a.jsx(de,{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(nH,{})})]})]})}const rjs=e=>e.includes("."),sjs=e=>e==="input"||e.endsWith(".input"),met=1;function ijs(e,t){const n=s1e(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 ojs(e,t){const n=Object.entries(e).filter(([l])=>!sjs(l)).map(([l,c])=>({stepId:l,step:c,...ijs(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-met),v=Math.min(Math.max(p/o*100,met),100-m);h={durationMs:p,offsetPct:m,widthPct:v}}return{stepId:l,step:c,status:lG(c)?"suspended":c.status,timing:h,spansSuspension:f,isRunning:d,isNestedEntry:rjs(l)}})}function ajs(){const{steps:e}=BP(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=wH(),[i,o]=g.useState(()=>Date.now()),[l,c]=g.useState(!0),[u,d]=g.useState(!1),{showData:f}=rk(),h=g.useRef(null),p=ojs(e,i),m=p.some(v=>v.isRunning);return _wt(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(Wl,{open:!l,onOpenChange:v=>c(!v),className:Z(hr,"@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl"),children:[a.jsxs("div",{className:"flex items-center",children:[a.jsxs(wl,{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(idt,{"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(Fl,{"aria-hidden":!0,className:Z("size-4 transition-transform motion-reduce:transition-none",l&&"-rotate-90")})})]}),!l&&a.jsx(de,{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(rOn,{}):a.jsx(adt,{})})]}),a.jsx(Sl,{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(njs,{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 ljs=({workflowId:e,workflow:t,isLoading:n})=>{const[r]=wr("workflow",e),{canExecute:s,isLoading:i}=Ta(),{stepDetail:o}=rk(),l=tP(),c=o?.type==="data",u=a.jsxs("div",{className:"[container-type:size] relative h-full min-h-0",children:[a.jsx(A2t,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),a.jsx(ejs,{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(IB,{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(ajs,{})})]});return l&&o&&!c?a.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:a.jsx(IB,{requestContext:r})}):a.jsxs("div",{className:"relative h-full min-h-0",children:[u,a.jsxs(QP,{className:"pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2",children:[a.jsx(ep,{id:"workflow-graph",className:"pointer-events-none min-w-0"}),o&&!c&&a.jsxs(a.Fragment,{children:[a.jsx(RS,{className:"pointer-events-auto"}),a.jsx(ep,{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(IB,{requestContext:r})})})]})]})]})},get=()=>{const{workflowId:e}=fr(),{data:t,isLoading:n,error:r}=L3({workflowId:e,requestContext:wr("workflow",e)[0],queryOptions:{enabled:!!e}});return r&&_s(r)?a.jsx(ci,{variant:"fill"}):r&&Ts(r)?a.jsx(Js,{variant:"fill",resource:"workflows"}):a.jsx(ljs,{workflowId:e,workflow:t??void 0,isLoading:n})};function cjs(){const{workflowId:e}=fr(),{error:t}=TG(e?{workflowId:e}:{});if(!e)return null;let n;return t&&_s(t)?n=a.jsx(ci,{variant:"fill"}):t&&Ts(t)?n=a.jsx(Js,{variant:"fill",resource:"schedules"}):n=a.jsx("div",{className:"h-full",children:a.jsx(iVt,{workflowId:e})}),a.jsxs(St,{children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),n]})}function ujs(){const{workflowId:e}=fr();return e?a.jsx(DIe,{scopedEntityId:e,scopedEntityType:fu.WORKFLOW_RUN}):null}const oVt=g.createContext(null);function Zc(){const e=g.useContext(oVt);if(!e)throw new Error("Workspace components must be rendered inside <Workspace.Root>");return e}const djs=e=>e?.status;function fjs(e,t){return _s(e)?"Your session has expired. Sign in again to continue.":Ts(e)?"You don't have permission to access this.":ok(e)?"This path no longer exists.":djs(e)===501?"This workspace does not support this operation.":t}function oJ({error:e,fallback:t,className:n}){return a.jsx(Wt,{variant:"destructive",className:n,children:a.jsx(Wt.Message,{children:fjs(e,t)})})}const hjs=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function pjs(e){const t=hjs.exec(e);return t?{frontmatter:t[1]??"",body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function mjs({content:e}){const{frontmatter:t,body:n}=pjs(e);return a.jsxs(a.Fragment,{children:[t!==null&&a.jsx("div",{"data-testid":"workspace-frontmatter",className:"border-b border-border",children:a.jsx(PP,{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(Fc,{children:n})})]})}function gjs(){const{activeFilePath:e}=Zc();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 vjs({path:e,content:t,mimeType:n}){return vAt(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"})}):yAt(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:${xWe(e,n)};base64,${t}`,type:xWe(e,n)})})}):_Dr(e)?a.jsx(mjs,{content:t}):a.jsx(PP,{code:t,lang:B1t(e),overflow:"scroll",className:"rounded-none border-0 bg-transparent [&_pre]:p-4"})}function yjs({renderPreview:e}){const{workspaceId:t,activeFilePath:n}=Zc(),{data:r,isLoading:s,error:i}=MDr({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(oJ,{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(vjs,{...o})}const hA=".",aVt=(e,t)=>e===hA?t:`${e}/${t}`,vet=e=>e.split("/").slice(0,-1).map((t,n,r)=>r.slice(0,n+1).join("/")),lVt=e=>{const t=e.lastIndexOf("/");return t===-1?hA:e.slice(0,t)};function cVt({labeled:e=!1}={}){const{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=Zc(),s=yr(),[i,o]=g.useState(!1),[l,c]=g.useState(""),[u,d]=g.useState(!1);if(!n||r(hA))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",lVt(f)]}),o(!1),c("")}catch{}finally{d(!1)}}};return a.jsxs(a.Fragment,{children:[e?a.jsx(de,{variant:"ghost",icon:a.jsx(eS,{}),onClick:()=>o(!0),children:"New folder"}):a.jsx(de,{variant:"ghost",size:"icon-sm",tooltip:"New folder",onClick:()=>o(!0),children:a.jsx(eS,{})}),a.jsx(rs,{open:i,onOpenChange:o,pending:u,children:a.jsx(ss,{size:"sm",children:a.jsxs("form",{onSubmit:p=>{p.preventDefault(),h()},children:[a.jsx(es,{children:a.jsx(Kr,{children:"New folder"})}),a.jsx(Gr,{children:a.jsx(Sn,{autoFocus:!0,"aria-label":"Folder path",placeholder:"docs/guides",value:l,onChange:p=>c(p.target.value)})}),a.jsxs(Ho,{children:[a.jsx(ja,{children:"Cancel"}),a.jsx(de,{type:"submit",variant:"primary",disabled:!f||u,children:"Create"})]})]})})})]})}function yet(e){return`${e.topSource}/${e.name}`}function xet(e){const t=xAt(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function xjs({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}=EDr({workspaceId:n,queryOptions:{enabled:!!n}}),b=TDr({workspaceId:n}),S=g.useMemo(()=>f?.topSource?xAt(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}=IDr({workspaceId:n,owner:S?.owner,repo:S?.repo,skillPath:f?.name,queryOptions:{enabled:!!n&&!!S&&!!f}}),T=L0(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]),I=b.isPending,P=u.trim().length>=2,A=g.useMemo(()=>{if(!f)return!1;const Q=xet(f);return!!(Q&&i.includes(Q)||o.includes(f.name))},[f,i,o]),D=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]),z=g.useCallback(Q=>{Q||(d(""),h(null),m(void 0)),t(Q)},[t]);return a.jsx(rs,{open:e,onOpenChange:z,pending:s,children:a.jsxs(ss,{size:"xl",className:"h-[80vh]",children:[a.jsxs(es,{children:[a.jsx(Kr,{children:"Add Skill"}),a.jsx(Mo,{children:"Search and install skills from the community registry"})]}),a.jsxs(Gr,{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:P?"Search Results":"Popular Skills"}),a.jsx(Nr,{className:"flex-1 rounded-lg border border-border",children:a.jsx(sf,{className:!x&&!I&&N.length===0?"flex flex-col [&>div]:flex [&>div]:flex-1 [&>div]:flex-col":void 0,children:x||I?a.jsx("div",{className:"flex items-center justify-center py-5",children:a.jsx(dc,{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(T3,{className:"mb-2 size-8"}),a.jsx(Y,{children:P?"No skills found":"No skills available"})]}):a.jsx("div",{className:"space-y-1 p-2",children:N.map(Q=>{const q=yet(Q),B=xet(Q),V=B&&i.includes(B)||o.includes(Q.name),H=f?yet(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",H===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(pr,{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(ip,{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(XL,{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(xY,{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(ip,{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(Fn,On),title:"View on GitHub",children:a.jsx(Vs,{className:"size-4"})})]})}),C?a.jsx("div",{className:"flex flex-1 items-center justify-center",children:a.jsx(dc,{className:"size-6 animate-spin text-muted-foreground"})}):j?a.jsx(Nr,{className:"flex-1",children:a.jsx("div",{className:"p-4",children:a.jsx(Fc,{children:j})})}):a.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-muted-foreground",children:[a.jsx(C1,{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(Vs,{className:"size-3"})]})]})]}):a.jsxs("div",{className:"flex h-full flex-col items-center justify-center text-muted-foreground",children:[a.jsx(C1,{className:"mb-2 size-8"}),a.jsx(Y,{children:"Select a skill to preview"})]})})]})]}),f&&l&&l.length>1&&a.jsxs(ft,{orientation:"horizontal",className:Z(hr,"gap-3 rounded-lg p-3"),children:[a.jsx(DA,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx(lt,{className:"whitespace-nowrap",children:"Install to"}),a.jsxs(Ur,{value:v,onValueChange:m,children:[a.jsx(Qr,{className:"flex-1",children:a.jsx(qr,{})}),a.jsx(Zr,{children:l.map(Q=>{const q=Q.displayName??Q.name??Q.provider??"unknown";return a.jsxs(or,{value:Q.path,children:[q," (",Q.path,")"]},Q.path)})})]})]})]}),f&&a.jsxs(Ho,{children:[A&&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(ja,{children:"Cancel"}),a.jsx(Oa,{onConfirm:D,disabled:!S||A,"data-testid":"install-skill-button",children:s?"Installing...":A?"Already Installed":"Install"})]})]})})}function uVt({labeled:e=!1}){const{workspaceId:t,addSkill:n}=Zc(),[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(de,{variant:"ghost",onClick:()=>s(!0),children:[a.jsx(Cde,{}),"Add skill"]}):a.jsx(de,{variant:"ghost",size:"icon-sm","aria-label":"Add skill",tooltip:"Add skill",onClick:()=>s(!0),children:a.jsx(Cde,{})}),a.jsx(xjs,{...c,open:r,onOpenChange:s,workspaceId:t,onInstall:d=>{u(d)},isInstalling:i})]})}function bjs({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(vet(t??""))),[b,S]=g.useState(t);if(t!==b){S(t);const C=vet(t??"").filter(T=>!y.has(T));C.length>0&&x(new Set([...y,...C]))}const k=i?.join(`
|
|
695
695
|
`)??"",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(`
|
|
696
696
|
`):[]).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(oVt.Provider,{value:j,children:f})}const dVt=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"})}),wjs=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 Sjs(){const{isSearching:e,setSearching:t,searchFiles:n,searchSkills:r}=Zc();return!n&&!r?null:a.jsx(de,{variant:"ghost",size:"icon-sm",tooltip:"Search files and skills","aria-pressed":e,onClick:()=>t(!e),children:a.jsx(wjs,{})})}function kjs(){const{isSearching:e}=Zc();return e?a.jsx(jjs,{}):a.jsx(Ojs,{})}const bet=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function Ojs(){const{fileCount:e,skillCount:t}=Zc();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":bet(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:bet(t,"Skill")})]})]})}function jjs(){const{setSearching:e,setQuery:t}=Zc(),[n,r]=g.useState(""),[,s]=g.useTransition();return a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(Sn,{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(de,{variant:"ghost",size:"icon-sm",tooltip:"Close search",onClick:()=>e(!1),children:a.jsx(Ln,{})})]})}function Cjs(){const{workspaceId:e,query:t,activeFilePath:n,setActiveFilePath:r,searchFiles:s,searchSkills:i}=Zc(),{data:o,isLoading:l,isError:c,error:u}=FDr({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(oJ,{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(Nt,{size:"sm",children:d.kind==="skill"?a.jsx(XL,{}):a.jsx(dVt,{})}),a.jsx(Y,{as:"span",variant:"body-sm",className:"truncate",children:d.label})]})},d.path))}):a.jsx(tn,{titleSlot:"No results"}):a.jsx(tn,{titleSlot:"Search files and skills",descriptionSlot:"Type to find matching content."})}function _js({mount:e}){switch(e.icon||e.provider){case"aws-s3":case"s3":return a.jsx(FNt,{className:"text-foreground"});case"google-cloud":case"google-cloud-storage":case"gcs":return a.jsx(VNt,{});case"azure-blob":case"azure":return a.jsx(BNt,{className:"text-badge-blue-indicator"});case"cloudflare":case"cloudflare-r2":case"r2":return a.jsx(Ode,{className:"text-badge-orange-indicator"});case"minio":return a.jsx(jde,{className:"text-badge-red-indicator"});case"database":return a.jsx(ex,{className:"text-badge-green-indicator"});case"local":case"folder":return a.jsx(DA,{className:"text-badge-amber-indicator"});case"hard-drive":return a.jsx(jde,{className:"text-muted-foreground"});default:return a.jsx(Ode,{className:"text-muted-foreground"})}}const Tjs=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"})}),Ejs=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 Ijs(){const{workspaceId:e,activeFilePath:t,setActiveFilePath:n}=Zc(),{data:r,isLoading:s,error:i}=WL({workspaceId:e,path:hA}),[o,l]=g.useState(null);return s?a.jsx(Rjs,{}):r?a.jsxs(a.Fragment,{children:[a.jsx(jr,{"aria-label":"Workspace files",selectedId:t,onSelect:n,className:"py-1",children:a.jsx(fVt,{entries:r,parent:hA,onRequestDelete:l})}),a.jsx($js,{entry:o,onClose:()=>l(null)})]}):a.jsx(oJ,{error:i,fallback:"Could not load files.",className:"m-2"})}function fVt({entries:e,parent:t,onRequestDelete:n}){return e.map(r=>{const s=aVt(t,r.name);return r.type==="directory"?a.jsx(Njs,{name:r.name,path:s,mount:r.mount,onRequestDelete:n},r.name):a.jsx(Pjs,{name:r.name,size:r.size,path:s,onRequestDelete:n},r.name)})}function hVt({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 pVt({name:e,onClick:t}){return a.jsx(de,{variant:"destructive-ghost",size:"icon-sm",tooltip:`Delete ${e}`,onClick:n=>{n.stopPropagation(),t()},onKeyDown:n=>n.stopPropagation(),children:a.jsx(Tjs,{})})}function Njs({name:e,path:t,mount:n,onRequestDelete:r}){const{workspaceId:s,onDelete:i,onCreateDirectory:o,isReadOnly:l,openFolders:c,setFolderOpen:u}=Zc(),d=c.has(t),{isLoading:f}=WL({workspaceId:s,path:t,queryOptions:{enabled:d}}),[h,p]=g.useState(!1),m=i&&!l(t),v=o&&!l(t);return a.jsxs(jr.Folder,{id:t,open:d,onOpenChange:y=>u(t,y),children:[a.jsxs(jr.FolderTrigger,{actions:m||v?a.jsxs(hVt,{children:[v?a.jsx(de,{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(eS,{})}):null,m?a.jsx(pVt,{name:e,onClick:()=>r({path:t,type:"directory"})}):null]}):void 0,children:[a.jsx(jr.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(_js,{mount:n})}):a.jsx(w7t,{})}),a.jsx(jr.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(RA,{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(Su,{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(An,{size:"sm","aria-label":`Loading ${e}`,className:"size-3 text-muted-foreground"})}):null]}),a.jsx(jr.FolderContent,{children:d?a.jsx(Ajs,{path:t,creating:h,onCreated:()=>p(!1),onRequestDelete:r}):null})]})}function Ajs({path:e,creating:t,onCreated:n,onRequestDelete:r}){const{workspaceId:s,onCreateDirectory:i}=Zc(),o=yr(),{data:l,isLoading:c,error:u}=WL({workspaceId:s,path:e}),d=async f=>{try{await i?.(aVt(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(jr.Input,{type:"folder",placeholder:"Folder name",onSubmit:f=>{d(f)},onCancel:n}):null,c?null:l?a.jsx(fVt,{entries:l,parent:e,onRequestDelete:r}):a.jsx(oJ,{error:u,fallback:"Could not load folder.",className:"my-1 mr-1"})]})}function Pjs({name:e,size:t,path:n,onRequestDelete:r}){const{onDelete:s,isReadOnly:i,activeFilePath:o}=Zc(),l=s&&!i(n),c=n===o,u=g.useRef(null);return g.useEffect(()=>{c&&u.current?.scrollIntoView?.({block:"nearest"})},[c]),a.jsxs(jr.File,{ref:u,id:n,children:[a.jsx(jr.Icon,{children:a.jsx(dVt,{})}),a.jsx(jr.Label,{children:e}),a.jsxs(hVt,{children:[t!==void 0?a.jsx(Y,{as:"span",variant:"caption",tone:"faint",font:"mono",children:Ejs(t)}):null,l?a.jsx(pVt,{name:e,onClick:()=>r({path:n,type:"file"})}):null]})]})}function $js({entry:e,onClose:t}){const{workspaceId:n,activeFilePath:r,setActiveFilePath:s,onDelete:i}=Zc(),o=yr(),[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",lVt(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(Ut,{open:e!==null,onOpenChange:h=>{!h&&!l&&t()},children:a.jsxs(Ut.Content,{children:[a.jsxs(Ut.Header,{children:[a.jsxs(Ut.Title,{children:["Delete ",e?.type==="directory"?"folder":"file","?"]}),a.jsxs(Ut.Description,{children:[f," This action cannot be undone."]})]}),a.jsxs(Ut.Footer,{children:[a.jsx(Ut.Cancel,{disabled:l,children:"Cancel"}),a.jsx(de,{variant:"destructive",disabled:l,onClick:()=>{d()},children:l?"Deleting…":"Delete"})]})]})})}function Rjs(){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 Mjs({children:e,...t}){return a.jsx(bjs,{...t,children:a.jsx(Djs,{children:e})})}function Djs({children:e}){const{workspaceId:t}=Zc(),{data:n,error:r}=WL({workspaceId:t,path:hA});return(n?n.length===0:ok(r))?a.jsx(tn,{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(cVt,{labeled:!0}),a.jsx(uVt,{labeled:!0})]})}):a.jsx("div",{className:"size-full overflow-hidden",children:a.jsx(QP,{className:"size-full min-h-0 min-w-0",orientation:"horizontal",children:e})})}function Ljs({children:e}){return a.jsxs(a.Fragment,{children:[a.jsx(KEe,{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(RS,{className:"w-px bg-border"})]})}function zjs({children:e,actions:t}){const{isSearching:n}=Zc();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 Fjs(){const{isSearching:e}=Zc();return a.jsx(Nr,{className:"min-h-0 flex-1 px-2 py-1",children:e?a.jsx(Cjs,{}):a.jsx(Ijs,{})})}function Bjs({children:e}){return a.jsx(ep,{id:"workspace-active-file",className:"flex min-w-0 flex-col",minSize:30,children:e})}function Vjs({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 Ujs({renderPreview:e}){const{activeFilePath:t}=Zc();return t?a.jsx(Nr,{className:"min-h-0 flex-1",children:a.jsx(yjs,{renderPreview:e})}):a.jsx(tn,{variant:"fill",titleSlot:"Select a file"})}const Cg={Root:Mjs,Aside:Ljs,AsideHeader:zjs,Search:kjs,SearchToggle:Sjs,CreateDirectory:cVt,Tree:Fjs,ActiveFile:Bjs,ActiveFileHeader:Vjs,FilePath:gjs,ActiveFileContent:Ujs};function qjs({asideActions:e,renderPreview:t,...n}){return a.jsxs(Cg.Root,{...n,children:[a.jsxs(Cg.Aside,{children:[a.jsx(Cg.AsideHeader,{actions:a.jsxs(a.Fragment,{children:[a.jsx(Cg.SearchToggle,{}),a.jsx(Cg.CreateDirectory,{}),a.jsx(uVt,{}),e]}),children:a.jsx(Cg.Search,{})}),a.jsx(Cg.Tree,{})]}),a.jsxs(Cg.ActiveFile,{children:[a.jsx(Cg.ActiveFileHeader,{children:a.jsx(Cg.FilePath,{})}),a.jsx(Cg.ActiveFileContent,{renderPreview:t})]})]})}const Qjs=()=>a.jsx(tn,{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(de,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/workspace/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Vs,{}),children:"Workspaces Documentation"}),variant:"fill"}),Zjs=()=>a.jsx(tn,{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(de,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/workspace/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Vs,{}),children:"Workspaces Documentation"}),variant:"fill"}),Wjs=()=>a.jsx(tn,{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(de,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/workspace/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Vs,{}),children:"Workspaces Documentation"}),variant:"fill"}),jce=".agents/skills",Hjs=e=>e.replace(/^\.?\/+|\/+$/g,"");function Gjs({workspaceId:e,showInitWarning:t,skills:n}){const{data:r}=WL({workspaceId:e,path:jce,queryOptions:{enabled:!!n}}),s=n&&r?r.filter(i=>i.type==="directory"&&!n.some(o=>o.name===i.name||Hjs(o.path)===`${jce}/${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:jce})," but not discovered. Add this path to your workspace skills configuration to see ",s.length===1?"it":"them","."]})})]})}const Mw=[hs("/workspaces")],wet=e=>Ts(e)?"you don't have permission to modify this workspace":e instanceof Error?e.message:"Unknown error";function ket(){const{workspaceId:e}=fr(),[t,n]=pi(),r=Lr(),s=yr(),i=t.get("file"),{data:o,error:l,isLoading:c}=wAt(),u=o?.workspaces??[],d=e??u[0]?.id,{data:f,isLoading:h,error:p}=bAt({workspaceId:d,queryOptions:{enabled:!!d}}),m=_s(l)||_s(p),v=Ts(l)||Ts(p),y=Ume(l)||Ume(p),x=d?u.find(he=>he.id===d):void 0,b=he=>{const Oe=new URLSearchParams(t);for(const[Ee,Fe]of Object.entries(he))Fe===null?Oe.delete(Ee):Oe.set(Ee,Fe);n(Oe)},S=he=>{r(`/workspaces/${he}`)},k=he=>{b({file:he??null})},j=i??void 0,C=$Dr(),T=RDr(),{data:_,refetch:N}=BDr({workspaceId:d,queryOptions:{enabled:!!d}}),I=NDr(),P=ADr(),A=PDr(),D=he=>{const Oe=/^\.agents\/skills\/([^/]+)$/.exec(he);return Oe?ue.find(Fe=>Fe.path?.replace(/^\.?\/+|\/+$/g,"")===he)?.name??Oe[1]:void 0},z=async()=>{if(d)try{const he=await P.mutateAsync({workspaceId:d}),Oe=he.updated.filter(Ee=>!Ee.success);Oe.length>0?Ge.error(`Failed to update ${Oe.map(Ee=>Ee.skillName).join(", ")}`):Ge.success(`${he.updated.length} skill(s) updated`),s.invalidateQueries({queryKey:["workspace",d,"fs"]})}catch(he){Ge.error(`Failed to update skills: ${he instanceof Error?he.message:"Unknown error"}`)}},Q=async({path:he,type:Oe})=>{if(!d)return;const Ee=Oe==="directory"?D(he):void 0;if(!Ee){try{await C.mutateAsync({path:he,recursive:!0,force:!0,workspaceId:d})}catch(Fe){throw Ge.error(`Failed to delete ${he}: ${wet(Fe)}`),Fe}return}try{if(!(await A.mutateAsync({workspaceId:d,skillName:Ee})).success)throw new Error(`Failed to remove skill "${Ee}"`);Ge.success(`Skill "${Ee}" removed`),N()}catch(Fe){throw Ge.error(Fe instanceof Error?Fe.message:"Failed to remove skill"),Fe}},q=f?.isWorkspaceConfigured??!1,B=f?.capabilities?.hasFilesystem??!1,V=f?.capabilities?.hasSkills??!1,H=x?.safety?.readOnly??!1,{canEdit:M,canDelete:G,canExecute:L,isLoading:$}=Ta(),F=!$&&M("workspaces")&&!H,U=!$&&G("workspaces")&&!H,K=!$&&L("workspaces"),ne=B&&V&&F,X=f?.mounts,te=X?.filter(he=>!he.readOnly).map(he=>({path:he.path,displayName:he.displayName,icon:he.icon,provider:he.provider,name:he.name})),oe=async he=>{if(d)try{const Oe=await I.mutateAsync({...he,workspaceId:d});if(!Oe.success)throw new Error("Unknown error");s.invalidateQueries({queryKey:["workspace",d,"fs"]}),N(),Ge.success(`Skill "${Oe.skillName}" installed successfully (${Oe.filesWritten} files)`)}catch(Oe){throw Ge.error(`Failed to install skill: ${Oe instanceof Error?Oe.message:"Unknown error"}`),Oe}},ue=_?.skills??[],ee=_?.isSkillsConfigured??!1,se=K&&B&&!!(f?.capabilities?.canBM25||f?.capabilities?.canVector),re=K&&V&&ee&&ue.length>0,ae=H?["."]:(X??[]).filter(he=>he.readOnly).map(he=>he.path.replace(/^\/+|\/+$/g,"")||".");if(c)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Mw}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(An,{fill:!0})]});if(m)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Mw}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(ci,{variant:"fill"})]});if(v)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Mw}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(Js,{variant:"fill",resource:"workspaces"})]});if(y)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Mw}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(Wjs,{})]});const pe=l||p;if(pe)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Mw}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(tn,{tone:"error",variant:"fill",titleSlot:"Failed to load workspace",descriptionSlot:pe.message})]});if(!c&&u.length===0)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Mw}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(Qjs,{})]});if(!h&&!c&&!q)return a.jsxs(St,{breadcrumbs:a.jsx(Pt,{crumbs:Mw}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(Zjs,{})]});const ve=u.map(he=>({value:he.id,label:he.name,description:he.source==="agent"?`Agent: ${he.agentName}`:"Global workspace",end:a.jsxs("span",{className:"flex shrink-0 gap-1",children:[he.safety?.readOnly&&a.jsx(Ft,{size:"xs",variant:"warning",children:"Read-only"}),he.capabilities.hasFilesystem&&a.jsx(Ft,{size:"xs",children:"FS"}),he.capabilities.hasSandbox&&a.jsx(Ft,{size:"xs",children:"Sandbox"}),he.capabilities.hasSkills&&a.jsx(Ft,{size:"xs",children:"Skills"})]})}));return a.jsxs(St,{variant:"fit",breadcrumbs:a.jsx(Pt,{crumbs:Mw}),headerActions:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ca,{"aria-label":"Workspace",variant:"ghost",className:"w-auto",options:ve,value:x?.id,onValueChange:S,placeholder:"Select workspace",searchPlaceholder:"Search workspaces...",emptyText:"No workspaces found."}),H&&a.jsx(Ft,{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(Gjs,{workspaceId:d,showInitWarning:se&&!h&&f?.status!=="ready",skills:V&&_?ue:void 0}),B&&d&&a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx(qjs,{workspaceId:d,activeFilePath:j,onActiveFileChange:k,readOnlyPaths:ae,skillCount:V&&_?ue.length:void 0,searchFiles:se,searchSkills:re,onCreateDirectory:F?async he=>{try{await T.mutateAsync({path:he,recursive:!0,workspaceId:d})}catch(Oe){throw Ge.error(`Failed to create ${he}: ${wet(Oe)}`),Oe}}:void 0,asideActions:ne&&ue.some(he=>he.path?.includes(".agents/skills/"))?a.jsx(de,{variant:"ghost",size:"icon-sm",tooltip:"Update skills",disabled:P.isPending,onClick:()=>{z()},children:a.jsx(tx,{className:P.isPending?"animate-spin":void 0})}):void 0,addSkill:ne?{onInstall:oe,installedSkillIds:ue.filter(he=>he.skillsShSource).map(he=>`${he.skillsShSource.owner}/${he.skillsShSource.repo}/${he.name}`),installedSkillNames:ue.filter(he=>!he.skillsShSource).map(he=>he.name),writableMounts:te,installedSkillPaths:Object.fromEntries(ue.filter(he=>he.path).map(he=>[he.name,he.path]))}:void 0,onDelete:U?Q:void 0},d)}),!B&&!h&&a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx(tn,{variant:"fill",titleSlot:"No filesystem or skills configured",descriptionSlot:"Add a filesystem or skills to this workspace to browse its files here."})})]})]})}function mVt({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","max-lg:p-1.5 lg:py-2 lg:pr-2",s?"lg:pl-0":"lg:pl-2"),children:e})]})]})}function gVt({children:e,className:t}){return a.jsx("div",{"data-slot":"main-card",className:Z("relative min-h-0 flex-1 overflow-hidden rounded-studio-frame p-px",YW,t),children:e})}function Kjs(){return a.jsxs("div",{className:"h-screen bg-sidebar",children:[a.jsx(pH,{position:"bottom-right"}),a.jsx(Bwe,{defaultTheme:"system",children:a.jsx(pc,{delayDuration:0,children:a.jsx(mVt,{children:a.jsx(gVt,{className:"flex items-center justify-center overflow-y-auto",children:a.jsx(Jy,{})})})})})]})}function Yjs(e){const[t,n]=g.useState({getBoundingClientRect(){return DOMRect.fromRect({width:0,height:0,x:0,y:0})}}),r=g.useRef(null),s=g.useRef(null),i=g.useRef(null),o=g.useRef(null),l=g.useRef(!0),c=g.useRef(null),u=J1(),d=g.useMemo(()=>({anchor:t,setAnchor:n,actionsRef:i,backdropRef:r,internalBackdropRef:s,positionerRef:o,allowMouseUpTriggerRef:l,initialCursorPointRef:c,rootId:u}),[t,u]);return a.jsx(obt.Provider,{value:d,children:a.jsx(Gwe.Provider,{value:void 0,children:a.jsx(e1e,{...e})})})}const Oet=500,Xjs=g.forwardRef(function(t,n){const{render:r,className:s,style:i,...o}=t,{setAnchor:l,actionsRef:c,internalBackdropRef:u,backdropRef:d,positionerRef:f,allowMouseUpTriggerRef:h,initialCursorPointRef:p,rootId:m}=tG(!1),{store:v}=Cv(!1),y=v.useState("open"),x=v.useState("disabled"),b=g.useRef(null),S=g.useRef(null),k=No(),j=No(),C=g.useRef(!1),T=g.useRef(null);function _(Q,q,B){const V=B.type.startsWith("touch");p.current={x:Q,y:q},l({getBoundingClientRect(){return DOMRect.fromRect({width:V?10:0,height:V?10:0,x:Q,y:q})}}),C.current=!1,c.current?.setOpen(!0,Yt(iv,B)),j.start(Oet,()=>{C.current=!0})}function N(Q){if(x)return;h.current=!0,sc(Q),_(Q.clientX,Q.clientY,Q.nativeEvent);const q=kr(b.current);T.current?.abort();const B=new AbortController;T.current=B,q.addEventListener("mouseup",V=>{if(h.current=!1,!C.current)return;j.clear(),C.current=!1;const H=Ui(V);ln(f.current,H)||m&&H&&n1e(H)===m||c.current?.setOpen(!1,Yt(DW,V))},{once:!0,signal:B.signal})}function I(){k.clear(),S.current=null}function P(Q){if(x){I();return}if(h.current=!1,Q.touches.length!==1){I();return}Q.stopPropagation();const q=Q.touches[0],B={x:q.clientX,y:q.clientY};S.current=B,k.start(Oet,()=>{_(B.x,B.y,Q.nativeEvent)})}function A(Q){if(Q.touches.length!==1){I();return}if(k.isStarted()&&S.current){const q=Q.touches[0],B=10,V=Math.abs(q.clientX-S.current.x),H=Math.abs(q.clientY-S.current.y);(V>B||H>B)&&I()}}return g.useEffect(()=>()=>{T.current?.abort()},[]),g.useEffect(()=>{function Q(B){if(x)return;const H=Ui(B);(ln(b.current,H)||ln(u.current,H)||ln(d.current,H))&&B.preventDefault()}const q=kr(b.current);return Br(q,"contextmenu",Q)},[d,x,u]),pn("div",t,{state:{open:y},ref:[b,n],props:[{onContextMenu:N,onTouchStart:P,onTouchMove:A,onTouchEnd:I,onTouchCancel:I,style:{WebkitTouchCallout:"none"}},o],stateAttributesMapping:XI})}),Jjs=Yjs,eCs=dbt,tCs=GA,nCs=kbt,rCs=gbt,sCs=Xjs,vVt=g.forwardRef(({className:e,align:t="start",alignOffset:n=4,side:r,sideOffset:s=0,container:i,anchor:o,positionMethod:l=vv,collisionBoundary:c,collisionPadding:u,sticky:d,arrowPadding:f,disableAnchorTracking:h,collisionAvoidance:p,children:m,...v},y)=>{const x={align:t,alignOffset:n,side:r,sideOffset:s,anchor:o,positionMethod:l,collisionBoundary:c,collisionPadding:u,sticky:d,arrowPadding:f,disableAnchorTracking:h,collisionAvoidance:p},b=A0(i),S=_v();return a.jsx(GA,{container:b,children:a.jsx(aG,{className:YA,...x,children:a.jsx(sG,{"data-slot":"context-menu-content",className:Z(XA,S.containerClassName,e),...v,...S.getContainerProps(v,y),children:a.jsx(Dm,{menu:S,children:m})})})})});vVt.displayName="ContextMenuContent";const yVt=g.forwardRef(({className:e,inset:t,variant:n="default",onSelect:r,onClick:s,...i},o)=>a.jsx(fbt,{ref:Eu(o),"data-inset":t?"":void 0,"data-variant":n,onClick:l=>{s?.(l),r?.(l)},className:Z(n==="destructive"?Abt:Xm,t&&KA,e),...i}));yVt.displayName="ContextMenuItem";const xVt=g.forwardRef(({className:e,children:t,checked:n,...r},s)=>a.jsxs(lbt,{ref:Eu(s),checked:n,className:Z(Xm,e),...r,children:[t,a.jsx(cbt,{className:i_,children:a.jsx(pr,{})})]}));xVt.displayName="ContextMenuCheckboxItem";const bVt=g.forwardRef(({className:e,children:t,...n},r)=>a.jsxs(ybt,{ref:Eu(r),className:Z(Xm,e),...n,children:[t,a.jsx(xbt,{className:i_,children:a.jsx(pr,{})})]}));bVt.displayName="ContextMenuRadioItem";const wVt=g.forwardRef(({className:e,inset:t,...n},r)=>a.jsx("div",{ref:r,className:Z(Pbt,t&&KA,e),...n}));wVt.displayName="ContextMenuLabel";const SVt=g.forwardRef(({className:e,...t},n)=>a.jsx(Cbt,{ref:n,className:Z($bt,e),...t}));SVt.displayName="ContextMenuSeparator";const kVt=({className:e,...t})=>a.jsx("span",{className:Z(Rbt,e),...t});kVt.displayName="ContextMenuShortcut";const OVt=g.forwardRef(({className:e,inset:t,children:n,...r},s)=>a.jsxs(_bt,{ref:Eu(s),className:Z(Xm,"data-[popup-open]:text-foreground",t&&KA,e),...r,children:[n,a.jsx("span",{className:Z(iL,"opacity-50"),children:a.jsx(Fl,{className:"-rotate-90"})})]}));OVt.displayName="ContextMenuSubTrigger";const jVt=g.forwardRef(({className:e,align:t="start",alignOffset:n=-4,side:r="right",sideOffset:s=-4,anchor:i,positionMethod:o=vv,collisionBoundary:l,collisionPadding:c,sticky:u,arrowPadding:d,disableAnchorTracking:f,collisionAvoidance:h,children:p,...m},v)=>{const y={align:t,alignOffset:n,side:r,sideOffset:s,anchor:i,positionMethod:o,collisionBoundary:l,collisionPadding:c,sticky:u,arrowPadding:d,disableAnchorTracking:f,collisionAvoidance:h},x=A0(),b=_v();return a.jsx(GA,{container:x,children:a.jsx(aG,{className:YA,...y,children:a.jsx(sG,{"data-slot":"context-menu-sub-content",className:Z(XA,b.containerClassName,e),...m,...b.getContainerProps(m,v),children:a.jsx(Dm,{menu:b,children:p})})})})});jVt.displayName="ContextMenuSubContent";function gl({open:e,defaultOpen:t,onOpenChange:n,children:r}){return a.jsx(Jjs,{open:e,defaultOpen:t,onOpenChange:n,children:r})}gl.Trigger=sCs;gl.Content=vVt;gl.Group=eCs;gl.Portal=tCs;gl.Item=yVt;gl.CheckboxItem=xVt;gl.RadioItem=bVt;gl.Label=wVt;gl.Separator=SVt;gl.Shortcut=kVt;gl.Sub=nCs;gl.SubContent=jVt;gl.SubTrigger=OVt;gl.RadioGroup=rCs;function iCs({className:e,children:t,...n}){return a.jsx("footer",{"data-slot":"sidebar-footer",className:Z("mt-auto shrink-0 space-y-1.5 pb-2",e),...n,children:t})}const HIe=Re.createContext(null),CVt=Re.createContext(null);function K0(){return Re.useContext(HIe)}function ag(){const e=Re.useContext(HIe),t=Re.useContext(CVt);if(!e||!t)throw new Error("useSidebar must be used within a SidebarProvider.");return{...e,...t}}const oCs=g.forwardRef(function({className:t,children:n,action:r,...s},i){const{state:o}=ag();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})]})}),aCs=`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")`,lCs=76,cCs=100,uCs=60,dCs=22.5,fCs=.18,jet=110,_Vt=[0,.08,.16,.25,.34,.44,.55,.66,.78,.89,1],TVt={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 EVt(e){const t=1-e;return t*t*t}function hCs(e,t){return`linear-gradient(to right, ${_Vt.map(r=>{const s=(t*EVt(r)*100).toFixed(2);return`color-mix(in oklch, var(${e}) ${s}%, transparent) ${(r*100).toFixed(0)}%`}).join(", ")})`}function Cet(e,t){const n=_Vt.map(r=>{const s=(t+(100-t)*r).toFixed(2);return`rgb(0 0 0 / ${EVt(r).toFixed(3)}) ${s}%`});return`linear-gradient(${e}, rgb(0 0 0 / 1) 0%, ${n.join(", ")})`}const pCs=`${Cet("to bottom",uCs)}, ${Cet("to right",dCs)}`;function _et({tone:e}){const t=TVt[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:cCs,backgroundImage:hCs(t.colorVar,t.peak),maskImage:pCs,maskComposite:"intersect"},children:t.grain?a.jsx("span",{"aria-hidden":!0,className:"absolute inset-0",style:{backgroundImage:aCs,backgroundRepeat:"repeat",backgroundSize:`${jet}px ${jet}px`,opacity:fCs}}):null})}const mCs=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=K0(),v=d??m?.state??"default",y=u??m?.LinkComponent??"a",x=v==="collapsed",b=TVt[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(_et,{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&&AA,f),style:{height:lCs},...h,children:[a.jsx(_et,{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 gCs({logo:e,title:t,className:n,...r}){const{state:s}=ag();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(x0,{children:t}):a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",className:"truncate font-body tracking-tight",children:t})]})}const vCs=g.forwardRef(function({className:t,children:n,...r},s){const{state:i,isMobile:o}=ag();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 IVt({className:e,onClick:t,...n}){const{desktopState:r,isMobile:s,toggleSidebar:i}=ag(),o=r==="collapsed";return s?null:a.jsxs($n,{children:[a.jsx(In,{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",$i,"[&_svg]:size-4 [&_svg]:text-muted-foreground [&:hover_svg]:text-foreground",e),children:a.jsx(Ndt,{})})}),a.jsx(Nn,{children:a.jsxs("span",{className:"inline-flex items-center gap-1.5",children:["Toggle Sidebar",a.jsx(Ud,{size:"xs",className:"bg-muted text-muted-foreground",children:"["})]})})]})}const Tet="animate-[sidebar-hold_var(--resize-dur)] motion-reduce:animate-none";function yCs({className:e,children:t,collapsedLogo:n,actions:r,...s}){const i=K0(),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(Tet,"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(Tet,"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(IVt,{})})]}):t,r]})}const xCs=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",Fn,On,$i,"[&_svg]:size-4 [&_svg]:shrink-0",r&&"w-auto px-2",t),...i,children:[n,r?a.jsx(Ud,{size:"xs",className:Z("bg-surface-overlay-soft active:scale-100",nx),children:r}):null]})});function bCs({"aria-label":e="Main",children:t,className:n,...r}){const s=K0()?.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(Nr,{className:"min-h-0 flex-1",mask:{top:"3rem",bottom:"5rem"},children:a.jsx(sf,{className:"px-0.5",children:a.jsx("div",{className:"pr-1.5",children:t})})})})}function NVt({children:e,icon:t,action:n,className:r,state:s,href:i,isActive:o,LinkComponent:l,...c}){const u=K0(),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(x0,{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(x0,{children:n}):null]})})}function GIe({children:e,className:t,state:n,...r}){const s=K0();return(n??s?.state??"default")==="collapsed"?a.jsx(x0,{children:e}):a.jsx("span",{...r,className:Z("min-w-0 flex-1 truncate text-left",t),children:e})}const wCs=dd("flex min-w-0 cursor-pointer items-center rounded-lg text-label whitespace-nowrap",{variants:{size:{sm:Hh.sm,md:Hh.md,lg:Hh.lg}},defaultVariants:{size:"md"}}),SCs=e=>e<=0?"gap-2 py-1 px-3":e===1?`gap-2 py-1 pr-3 pl-8 ${Hh.md}`:e===2?`gap-2 py-1 pr-3 pl-10 ${Hh.md}`:`gap-2 py-1 pr-3 pl-12 ${Hh.md}`,kCs=Z("rounded-lg text-muted-foreground hover:text-foreground",AA),OCs="bg-fill text-foreground",jCs=Z("my-2 border border-transparent bg-brand-green text-black hover:text-black hover:brightness-95"),AVt=({isActive:e,isFeatured:t})=>Z(kCs,e&&OCs,t&&jCs),PVt=({isCollapsed:e,level:t=0,size:n})=>Z(wCs({size:n}),"w-full justify-start",On,"[&_svg]:size-4 [&_svg]:shrink-0",$i,!e&&SCs(t),e&&"gap-0 px-[13.5px] py-0"),$Vt=({isActive:e,isCollapsed:t,isFeatured:n,level:r,size:s}={})=>Z(PVt({isCollapsed:t,level:r,size:s}),AVt({isActive:e,isFeatured:n}));function KIe({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=K0(),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(PVt({level:b,size:s}),"flex-1 pr-1"):Z($Vt({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(ECs,{action:S,surfaceClassName:AVt({isActive:r,isFeatured:x}),children:a.jsx(TCs,{label:_Cs(e,y),children:CCs({render:i,asChild:f,children:n,link:e,state:m,Link:v,isActive:r,className:k})})}),!y&&d]})}function CCs({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(Gs,{"aria-hidden":"true",className:"!size-3.5"}):null;if(e||t){const f=e??n;if(!Re.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 Re.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(GIe,{state:s,children:r.name}),n,u]})}function _Cs(e,t){if(e)return e.tooltipMsg?t?`${e.name} | ${e.tooltipMsg}`:e.tooltipMsg:t?e.name:void 0}function TCs({label:e,children:t}){return Re.isValidElement(t)?a.jsxs($n,{disabled:!e,children:[a.jsx(In,{render:t}),e?a.jsx(Nn,{side:"right",align:"center",sideOffset:16,children:e}):null]}):t}function ECs({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 YIe({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 RVt({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 MVt({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})}const DVt=Re.createContext(void 0);function LVt(){const e=Re.useContext(DVt);if(!e)throw new Error("Sidebar.NavStack components must be used within Sidebar.NavStack.");return e}function ICs({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(DVt.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 zVt(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 NCs({children:e,className:t,...n}){const{state:r}=ag(),{activeValue:s,rootValue:i}=LVt(),o=r==="collapsed"||s===i;return a.jsx("div",{...n,"data-slot":"sidebar-nav-stack-root","aria-hidden":!o,inert:!o,className:zVt(o,"root",t),children:e})}function ACs({value:e,title:t,backLabel:n="Back to main navigation",returnFocusRef:r,onBack:s,children:i,className:o,...l}){const{state:c}=ag(),{activeValue:u,closeView:d}=LVt(),f=c!=="collapsed"&&u===e,h=Re.useRef(null),p=Re.useRef(f);Re.useEffect(()=>{f&&!p.current&&h.current?.focus(),p.current=f},[f]),Re.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:zVt(f,"view",o),children:[a.jsxs("button",{ref:h,type:"button","aria-label":`${n}: ${t}`,onClick:m,className:Z($Vt(),"mb-2 grid grid-cols-[2rem_1fr_2rem] px-1"),children:[a.jsx(fd,{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 PCs=Object.assign(ICs,{Root:NCs,View:ACs});function $Cs({className:e,icon:t,"aria-label":n="Open navigation menu",onClick:r,...s}){const{isMobile:i,mobileTriggerRef:o,setOpenMobile:l}=ag();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",Fn,"hover:bg-fill-subtle",$i,e),children:t??a.jsx(Odt,{className:"size-5"})})}const Eet="sidebar:state",Iet="sidebar:width",Net="--sidebar-width",Cce=(e,t,n)=>Math.min(n,Math.max(t,e)),RCs=typeof window<"u"?Re.useLayoutEffect:Re.useEffect;function FVt({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=Cce(n,h,p),y=i??h,x=c?`${c}:${Eet}`:Eet,b=c?`${c}:${Iet}`:Iet,S=()=>{if(typeof window>"u")return{state:t,width:v};try{let re=t,ae=v;const pe=window.localStorage.getItem(x);(pe==="collapsed"||pe==="default")&&(re=pe);const ve=window.localStorage.getItem(b);if(ve!==null){const he=Number(ve);Number.isFinite(he)&&(ae=Cce(he,h,p))}return{state:re,width:ae}}catch{return{state:t,width:v}}},k=Re.useRef(null);k.current===null&&(k.current=S());const j=k.current,[C,T]=Re.useState(j.state),[_,N]=Re.useState(j.width),[I,P]=Re.useState(!1),[A,D]=Re.useState(!1),[z,Q]=Re.useState(!1),q=Re.useRef(!1),B=Re.useRef(null),V=Re.useRef(j.width),H=Re.useRef(j.state);H.current=C;const M=Re.useRef(null);Re.useEffect(()=>{if(typeof window>"u")return;const re=window.matchMedia(`(max-width: ${u-1}px)`),ae=()=>P(re.matches);return ae(),re.addEventListener("change",ae),()=>re.removeEventListener("change",ae)},[u]);const G=Re.useCallback(re=>{q.current=re,re&&Q(!0),D(re)},[]);Re.useEffect(()=>{!I&&A&&(G(!1),Q(!1))},[I,A,G]);const L=Re.useCallback(re=>{const ae=M.current;ae&&ae.style.setProperty(Net,`${re}px`)},[]);RCs(()=>{L(C==="collapsed"?m:V.current)},[C,m,L]);const $=Re.useCallback(re=>{try{window.localStorage.setItem(x,re)}catch{}},[x]),F=Re.useCallback(()=>{if(I){G(!q.current);return}T(re=>{const ae=re==="default"?"collapsed":"default";return H.current=ae,$(ae),ae})},[I,$,G]),U=Re.useCallback(re=>{const ae=Cce(re,h,p);V.current=ae,L(ae)},[h,p,L]),K=Re.useCallback(()=>{H.current="collapsed",$("collapsed"),T("collapsed")},[$]),ne=Re.useCallback(()=>{H.current="default",$("default"),T("default")},[$]),X=Re.useCallback(()=>{N(V.current);try{window.localStorage.setItem(x,H.current),window.localStorage.setItem(b,String(V.current))}catch{}},[x,b]),te=Re.useCallback(re=>{const ae=M.current;ae&&(re?ae.setAttribute("data-sidebar-gesture","active"):ae.removeAttribute("data-sidebar-gesture"))},[]);Re.useEffect(()=>{if(l)return;const re=ae=>{if(ae.code==="KeyB"&&(ae.metaKey||ae.ctrlKey)&&!(ae.altKey||ae.shiftKey)){if(ae.target instanceof HTMLElement){const pe=ae.target.tagName;if(pe==="INPUT"||pe==="TEXTAREA"||pe==="SELECT"||ae.target.isContentEditable)return}ae.preventDefault(),F()}};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[l,F]);const oe=I?"default":C,ue=Re.useMemo(()=>({state:oe,desktopState:C,width:_,minWidth:h,maxWidth:p,collapseBelow:y,collapsedWidth:m,isMobile:I,toggleSidebar:F,setWidth:U,collapse:K,expand:ne,commit:X,setGestureActive:te,LinkComponent:f}),[oe,C,_,h,p,y,m,I,F,U,K,ne,X,te,f]),ee=Re.useMemo(()=>({openMobile:A,mobileTriggerRef:B,setOpenMobile:G,setMobileDrawerPresent:Q}),[A,G]),se={[Net]:`${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":I?"true":"false","data-sidebar-mobile-present":z?"true":"false",style:se,suppressHydrationWarning:!0,children:a.jsx(HIe.Provider,{value:ue,children:a.jsx(CVt.Provider,{value:ee,children:e})})})}const Aet=10,MCs=5;function DCs({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}=ag(),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(D=>{if(D.button!==0)return;D.preventDefault(),C.current=!1,S(!0);const z=D.clientX,Q=D.currentTarget,q=D.pointerId;try{Q.setPointerCapture(q)}catch{}const B=Q.parentElement,V=B?B.getBoundingClientRect().left:0,H=document.body.style.cursor,M=document.body.style.userSelect,G=$=>{if($.pointerId!==q)return;const F=$.clientX-z;if(!C.current){if(Math.abs(F)<=MCs)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)},L=$=>{$&&$.pointerId!==q||(window.removeEventListener("pointermove",G),window.removeEventListener("pointerup",L),window.removeEventListener("pointercancel",L),document.body.style.cursor=H,document.body.style.userSelect=M,S(!1),x(),T.current=null)};T.current=()=>L(),window.addEventListener("pointermove",G),window.addEventListener("pointerup",L),window.addEventListener("pointercancel",L)},[l,m,y,v,x,S]),N=g.useCallback(()=>{if(C.current){C.current=!1;return}b()},[b]),I=g.useCallback(D=>{switch(D.key){case"Enter":case" ":{D.preventDefault(),b();return}case"ArrowLeft":{if(D.preventDefault(),k)return;m(s-Aet),x();return}case"ArrowRight":{if(D.preventDefault(),k){y(),x();return}m(s+Aet),x();return}case"Home":{D.preventDefault(),y(),m(i),x();return}case"End":{D.preventDefault(),y(),m(o),x();return}}},[k,s,i,o,m,y,x,b]),P=g.useCallback(D=>{if(!(D.target instanceof Element))return;const z=D.target.closest("a");!z||!z.hasAttribute("href")||D.button!==0||D.metaKey||D.ctrlKey||D.shiftKey||D.altKey||z.target==="_blank"||z.hasAttribute("download")||h(!1)},[h]);if(u)return a.jsx(CP,{side:"left",open:d,onOpenChange:h,onOpenChangeComplete:D=>{D||p(!1)},children:a.jsxs(VK,{"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(LK,{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(Jf,nx,Fut,"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(Odt,{className:"size-4"})})})}):null,a.jsx(x0,{asChild:!0,children:a.jsx(_P,{children:"Navigation"})}),a.jsx(x0,{asChild:!0,children:a.jsx(FL,{children:"Primary site navigation drawer"})}),a.jsx("div",{onClick:P,className:Z("flex h-full min-h-0 flex-col overflow-hidden py-2",n==="takeover"?"px-4":"px-3"),children:e})]})});const A=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","px-2",j&&"pointer-events-none px-0 opacity-0"),children:e}),a.jsx("div",{role:"separator","aria-orientation":"vertical","aria-valuenow":k?void 0:A,"aria-valuemin":k?void 0:i,"aria-valuemax":k?void 0:o,"aria-valuetext":k?"collapsed":`${A} pixels`,"aria-label":`Resize sidebar. Arrow keys to resize, Enter to ${k?"expand":"collapse"}.`,tabIndex:0,onPointerDown:_,onClick:N,onKeyDown:I,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(Y1e,{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 LCs({"aria-label":e="Sidebar",mobileMode:t="takeover",variant:n="default",children:r,...s}){const i=K0(),o=n==="raised"&&!i?.isMobile;return a.jsx("aside",{"aria-label":e,className:"contents",children:a.jsx(DCs,{mobileMode:t,...s,children:o?a.jsx("div",{"data-slot":"sidebar-surface",className:Z("my-2 -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",YW),children:r}):r})})}const aJ=["sidebar","more","hidden"],BVt={sidebar:"Always show",more:"Hide in More menu",hidden:"Never show"},zCs=Oi(vt(),ff(aJ)),FCs="mastra:sidebar:link-visibility";function q5(e){return`${e.url}:${e.name}`}function Pet(e,t){return`${e}:${t.name}`}function VVt(e,t){return e.defaultVisible??t<2?"sidebar":"more"}function UVt(e){return aJ.some(t=>t===e)}function BCs({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(rs,{open:e,onOpenChange:t,children:a.jsxs(ss,{size:"md",finalFocus:n,children:[a.jsxs(es,{children:[a.jsx(Kr,{children:"Customize sidebar"}),a.jsx(Mo,{children:"Choose where each optional link appears. Changes save automatically in this browser."})]}),a.jsx(Gr,{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(Ur,{value:s(c.key,f,u.length),onValueChange:h=>{UVt(h)&&i(c.key,f,h)},children:[a.jsx(Qr,{size:"sm",variant:"ghost",className:"w-44 shrink-0","aria-label":`${f.name} placement`,children:a.jsx(qr,{})}),a.jsx(Zr,{children:aJ.map(h=>a.jsx(or,{value:h,children:BVt[h]},h))})]})]},q5(f)))})]},c.key)})})]})})}function XIe({link:e,activeCandidates:t,level:n=0,isActive:r,...s}){const i=e.children??[];return a.jsx(KIe,{...s,link:e,isActive:r?.(e,t)??e.isActive,level:n,subItems:i.length>0?a.jsx(YIe,{className:"mt-0.5",children:i.map(o=>a.jsx(XIe,{link:o,activeCandidates:t,level:n+1,isActive:r},q5(o)))}):null})}function VCs({link:e,activeCandidates:t,isActive:n,placement:r,onPlacementChange:s,onCustomize:i}){const o=g.useRef(null);return a.jsxs(gl,{children:[a.jsx(gl.Trigger,{ref:l=>{o.current=l},render:a.jsx(XIe,{link:e,activeCandidates:t,isActive:n})}),a.jsxs(gl.Content,{"aria-label":`${e.name} options`,children:[a.jsx(gl.RadioGroup,{value:r,onValueChange:l=>{UVt(l)&&s(l)},children:aJ.map(l=>a.jsx(gl.RadioItem,{value:l,children:BVt[l]},l))}),a.jsx(gl.Separator,{}),a.jsx(gl.Item,{onClick:()=>i(o.current?.querySelector("a")??null),children:"Customize sidebar…"})]})]})}function UCs({links:e,activeCandidates:t,isActive:n,placementOf:r,onPlacementChange:s,onCustomize:i}){const l=K0()?.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)!==VVt(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(ut.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))]},q5(v))}return a.jsxs(a.Fragment,{children:[u.map(v=>a.jsx(VCs,{link:v,activeCandidates:t,isActive:n,placement:r(v),onPlacementChange:y=>s(v,y),onCustomize:y=>i(y,()=>p.current)},q5(v))),h?a.jsxs(ut,{modal:!1,children:[a.jsx(KIe,{link:{name:"More",url:"",icon:a.jsx(GD,{})},render:a.jsxs(ut.Trigger,{ref:p,render:a.jsx("button",{type:"button"}),"aria-label":"More",children:[a.jsx(GD,{"aria-hidden":"true"}),a.jsx(GIe,{children:"More"})]})}),a.jsxs(ut.Content,{align:"start","aria-label":"More navigation",className:"min-w-44",children:[d.map(v=>m(v)),d.length>0&&a.jsx(ut.Separator,{}),a.jsxs(ut.Item,{onClick:()=>i(p.current,()=>p.current),children:[a.jsx(P3,{}),"Customize sidebar"]})]})]}):null]})}function qCs({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]=eP({initialKey:r,defaultValue:{},schema:zCs});function f(v,y,x){return u[Pet(v,y)]??VVt(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,[Pet(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(RVt,{className:n,"aria-labelledby":x,"aria-label":x?void 0:v.key,children:[y?a.jsx(MVt,{className:"[&:after]:border-border"}):null,v.title?a.jsx(NVt,{id:x,href:v.href,isActive:v.isHeaderActive,children:v.title}):null,a.jsxs(YIe,{children:[v.links.map(k=>a.jsx(XIe,{link:k,activeCandidates:S,isActive:t},q5(k))),b.length>0?a.jsx(UCs,{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(BCs,{open:i,onOpenChange:p,returnFocusRef:l,sections:e,placementOf:f,onPlacementChange:m})]})}function QCs({visibilityStorageKey:e=FCs,...t}){return a.jsx(qCs,{...t,visibilityStorageKey:e},e)}const po=Object.assign(LCs,{Brand:gCs,CommandHeader:vCs,Footer:iCs,FooterMeta:oCs,Header:yCs,Meter:mCs,MobileTrigger:$Cs,Nav:bCs,NavHeader:NVt,NavLabel:GIe,NavLink:KIe,NavList:YIe,NavSection:RVt,NavSeparator:MVt,NavStack:PCs,Provider:FVt,SearchTrigger:xCs,Sections:QCs,Trigger:IVt});function ZCs(){const{data:e,isLoading:t}=Ul(),{isLoading:n,canAccessAgentBuilder:r}=xx();return t||n?{isVisible:!1}:e?!!e.enabled&&!mp(e)?{isVisible:!1}:{isVisible:r}:{isVisible:!1}}function qVt(){const{isImpersonating:e,impersonatedRole:t,stopImpersonation:n}=gH();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(rl,{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(Ln,{className:"h-3 w-3"})})]})}var $et=1,WCs=.9,HCs=.8,GCs=.17,_ce=.1,Tce=.999,KCs=.9999,YCs=.99,XCs=/[\\\/_+.#"@\[\(\{&]/,JCs=/[\\\/_+.#"@\[\(\{&]/g,e_s=/[\s-]/,QVt=/[\s-]/g;function Lve(e,t,n,r,s,i,o){if(i===t.length)return s===e.length?$et:YCs;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=Lve(e,t,n,r,u+1,i+1,o),f>d&&(u===s?f*=$et:XCs.test(e.charAt(u-1))?(f*=HCs,p=e.slice(s,u-1).match(JCs),p&&s>0&&(f*=Math.pow(Tce,p.length))):e_s.test(e.charAt(u-1))?(f*=WCs,m=e.slice(s,u-1).match(QVt),m&&s>0&&(f*=Math.pow(Tce,m.length))):(f*=GCs,s>0&&(f*=Math.pow(Tce,u-s))),e.charAt(u)!==t.charAt(i)&&(f*=KCs)),(f<_ce&&n.charAt(u-1)===r.charAt(i+1)||r.charAt(i+1)===r.charAt(i)&&n.charAt(u-1)!==r.charAt(i))&&(h=Lve(e,t,n,r,u+1,i+2,o),h*_ce>f&&(f=h*_ce)),f>d&&(d=f),u=n.indexOf(c,u+1);return o[l]=d,d}function Ret(e){return e.toLowerCase().replace(QVt," ")}function t_s(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Lve(e,t,Ret(e),Ret(t),0,0,{})}function $1(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e?.(s),n===!1||!s||!s.defaultPrevented)return t?.(s)}}function Met(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pA(...e){return t=>{let n=!1;const r=e.map(s=>{const i=Met(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():Met(e[s],null)}}}}function D_(...e){return g.useCallback(pA(...e),e)}function n_s(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,r_s(s,...t)]}function r_s(...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 Q5=globalThis?.document?g.useLayoutEffect:()=>{},s_s=vA[" useId ".trim().toString()]||(()=>{}),i_s=0;function Jb(e){const[t,n]=g.useState(s_s());return Q5(()=>{n(r=>r??String(i_s++))},[e]),t?`radix-${t}`:""}var o_s=vA[" useInsertionEffect ".trim().toString()]||Q5;function a_s({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[s,i,o]=l_s({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=c_s(d)?d(e):d;f!==e&&o.current?.(f)}else i(d)},[l,e,i,o]);return[c,u]}function l_s({defaultProp:e,onChange:t}){const[n,r]=g.useState(e),s=g.useRef(n),i=g.useRef(t);return o_s(()=>{i.current=t},[t]),g.useEffect(()=>{s.current!==n&&(i.current?.(n),s.current=n)},[n,s]),[n,r,i]}function c_s(e){return typeof e=="function"}function ZVt(e){const t=g.forwardRef((n,r)=>{let{children:s,...i}=n,o=null,l=!1;const c=[];Det(s)&&typeof f7=="function"&&(s=f7(s._payload)),g.Children.forEach(s,h=>{if(p_s(h)){l=!0;const p=h;let m="child"in p.props?p.props.child:p.props.children;Det(m)&&typeof f7=="function"&&(m=f7(m._payload)),o=d_s(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?h_s(o):void 0,d=D_(r,u);if(!o){if(s||s===0)throw new Error(l?y_s(e):v_s(e));return s}const f=f_s(i,o.props??{});return o.type!==g.Fragment&&(f.ref=r?d:u),g.cloneElement(o,f)});return t.displayName=`${e}.Slot`,t}var u_s=Symbol.for("radix.slottable"),d_s=(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 f_s(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 h_s(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 p_s(e){return g.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===u_s}var m_s=Symbol.for("react.lazy");function Det(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===m_s&&"_payload"in e&&g_s(e._payload)}function g_s(e){return typeof e=="object"&&e!==null&&"then"in e}var v_s=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,y_s=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,f7=vA[" use ".trim().toString()],x_s=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Lu=x_s.reduce((e,t)=>{const n=ZVt(`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 b_s(e,t){e&&bo.flushSync(()=>e.dispatchEvent(t))}function Z5(e){const t=g.useRef(e);return g.useEffect(()=>{t.current=e}),g.useMemo(()=>((...n)=>t.current?.(...n)),[])}var w_s="DismissableLayer",zve="dismissableLayer.update",S_s="dismissableLayer.pointerDownOutside",k_s="dismissableLayer.focusOutside",Let,JIe=g.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),WVt=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(JIe),[f,h]=g.useState(null),p=f?.ownerDocument??globalThis?.document,[,m]=g.useState({}),v=D_(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=T_s(P=>{i?.(P),l?.(P),P.defaultPrevented||c?.()},{ownerDocument:p,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:C,dismissableSurfaces:d.dismissableSurfaces,shouldHandlePointerDownOutside:g.useCallback(P=>{if(!(P instanceof Node))return!1;const A=[...d.branches].some(D=>D.contains(P));return j&&!A},[d.branches,j])}),_=E_s(P=>{if(r&&C.current)return;const A=P.target;[...d.branches].some(z=>z.contains(A))||(o?.(P),l?.(P),P.defaultPrevented||c?.())},p),N=f?S===y.length-1:!1,I=Z5(P=>{P.key==="Escape"&&(s?.(P),!P.defaultPrevented&&c&&(P.preventDefault(),c()))});return g.useEffect(()=>{if(N)return p.addEventListener("keydown",I,{capture:!0}),()=>p.removeEventListener("keydown",I,{capture:!0})},[p,N,I]),g.useEffect(()=>{if(f)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Let=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(f)),d.layers.add(f),zet(),()=>{n&&(d.layersWithOutsidePointerEventsDisabled.delete(f),d.layersWithOutsidePointerEventsDisabled.size===0&&(p.body.style.pointerEvents=Let))}},[f,p,n,d]),g.useEffect(()=>()=>{f&&(d.layers.delete(f),d.layersWithOutsidePointerEventsDisabled.delete(f),zet())},[f,d]),g.useEffect(()=>{const P=()=>m({});return document.addEventListener(zve,P),()=>document.removeEventListener(zve,P)},[]),a.jsx(Lu.div,{...u,ref:v,style:{pointerEvents:k?j?"auto":"none":void 0,...e.style},onFocusCapture:$1(e.onFocusCapture,_.onFocusCapture),onBlurCapture:$1(e.onBlurCapture,_.onBlurCapture),onPointerDownCapture:$1(e.onPointerDownCapture,T.onPointerDownCapture)})});WVt.displayName=w_s;var O_s="DismissableLayerBranch",j_s=g.forwardRef((e,t)=>{const n=g.useContext(JIe),r=g.useRef(null),s=D_(t,r);return g.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),a.jsx(Lu.div,{...e,ref:s})});j_s.displayName=O_s;function C_s(){const e=g.useContext(JIe),[t,n]=g.useState(null);return g.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var __s=()=>!0;function T_s(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:s,dismissableSurfaces:i,shouldHandlePointerDownOutside:o=__s}=t,l=Z5(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||HVt(S_s,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 E_s(e,t=globalThis?.document){const n=Z5(e),r=g.useRef(!1);return g.useEffect(()=>{const s=i=>{i.target&&!r.current&&HVt(k_s,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 zet(){const e=new CustomEvent(zve);document.dispatchEvent(e)}function HVt(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?b_s(s,i):s.dispatchEvent(i)}var Ece="focusScope.autoFocusOnMount",Ice="focusScope.autoFocusOnUnmount",Fet={bubbles:!1,cancelable:!0},I_s="FocusScope",GVt=g.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:i,...o}=e,[l,c]=g.useState(null),u=Z5(s),d=Z5(i),f=g.useRef(null),h=D_(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:Fw(f.current,{select:!0})},y=function(S){if(p.paused||!l)return;const k=S.relatedTarget;k!==null&&(l.contains(k)||Fw(f.current,{select:!0}))},x=function(S){if(document.activeElement===document.body)for(const j of S)j.removedNodes.length>0&&Fw(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){Vet.add(p);const v=document.activeElement;if(!l.contains(v)){const x=new CustomEvent(Ece,Fet);l.addEventListener(Ece,u),l.dispatchEvent(x),x.defaultPrevented||(N_s(M_s(KVt(l)),{select:!0}),document.activeElement===v&&Fw(l))}return()=>{l.removeEventListener(Ece,u),setTimeout(()=>{const x=new CustomEvent(Ice,Fet);l.addEventListener(Ice,d),l.dispatchEvent(x),x.defaultPrevented||Fw(v??document.body,{select:!0}),l.removeEventListener(Ice,d),Vet.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]=A_s(b);S&&k?!v.shiftKey&&x===k?(v.preventDefault(),n&&Fw(S,{select:!0})):v.shiftKey&&x===S&&(v.preventDefault(),n&&Fw(k,{select:!0})):x===b&&v.preventDefault()}},[n,r,p.paused]);return a.jsx(Lu.div,{tabIndex:-1,...o,ref:h,onKeyDown:m})});GVt.displayName=I_s;function N_s(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Fw(r,{select:t}),document.activeElement!==n)return}function A_s(e){const t=KVt(e),n=Bet(t,e),r=Bet(t.reverse(),e);return[n,r]}function KVt(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 Bet(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):P_s(r,{upTo:t})))return r}function P_s(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 $_s(e){return e instanceof HTMLInputElement&&"select"in e}function Fw(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&$_s(e)&&t&&e.select()}}var Vet=R_s();function R_s(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Uet(e,t),e.unshift(t)},remove(t){e=Uet(e,t),e[0]?.resume()}}}function Uet(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function M_s(e){return e.filter(t=>t.tagName!=="A")}var D_s="Portal",YVt=g.forwardRef((e,t)=>{const{container:n,...r}=e,[s,i]=g.useState(!1);Q5(()=>i(!0),[]);const o=n||s&&globalThis?.document?.body;return o?bo.createPortal(a.jsx(Lu.div,{...r,ref:t}),o):null});YVt.displayName=D_s;function L_s(e,t){return g.useReducer((n,r)=>t[n][r]??n,e)}var lJ=e=>{const{present:t,children:n}=e,r=z_s(t),s=typeof n=="function"?n({present:r.isPresent}):g.Children.only(n),i=F_s(r.ref,B_s(s));return typeof n=="function"||r.isPresent?g.cloneElement(s,{ref:i}):null};lJ.displayName="Presence";function z_s(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]=L_s(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??vM(r.current),o.current=void 0):i.current="none"},[c]),Q5(()=>{const d=r.current,f=s.current;if(f!==e){const p=i.current,m=vM(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]),Q5(()=>{if(t){let d;const f=t.ownerDocument.defaultView??window,h=m=>{const y=vM(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=vM(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=vM(f)}else r.current=null;n(d)},[])}}function qet(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function F_s(...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=qet(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():qet(r[o],null)}}},[])}function vM(e){return e?.animationName||"none"}function B_s(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 h7=0,eE=null;function V_s(){g.useEffect(()=>{eE||(eE={start:Qet(),end:Qet()});const{start:e,end:t}=eE;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),h7++,()=>{h7===1&&(eE?.start.remove(),eE?.end.remove(),eE=null),h7=Math.max(0,h7-1)}},[])}function Qet(){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 ky=function(){return ky=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},ky.apply(this,arguments)};function XVt(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 U_s(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 FB="right-scroll-bar-position",BB="width-before-scroll-bar",q_s="with-scroll-bars-hidden",Q_s="--removed-body-scroll-bar-size";function Nce(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Z_s(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 W_s=typeof window<"u"?g.useLayoutEffect:g.useEffect,Zet=new WeakMap;function H_s(e,t){var n=Z_s(null,function(r){return e.forEach(function(s){return Nce(s,r)})});return W_s(function(){var r=Zet.get(n);if(r){var s=new Set(r),i=new Set(e),o=n.current;s.forEach(function(l){i.has(l)||Nce(l,null)}),i.forEach(function(l){s.has(l)||Nce(l,o)})}Zet.set(n,e)},[e]),n}function G_s(e){return e}function K_s(e,t){t===void 0&&(t=G_s);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 Y_s(e){e===void 0&&(e={});var t=K_s(null);return t.options=ky({async:!0,ssr:!1},e),t}var JVt=function(e){var t=e.sideCar,n=XVt(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,ky({},n))};JVt.isSideCarExport=!0;function X_s(e,t){return e.useMedium(t),JVt}var eUt=Y_s(),Ace=function(){},cJ=g.forwardRef(function(e,t){var n=g.useRef(null),r=g.useState({onScrollCapture:Ace,onWheelCapture:Ace,onTouchMoveCapture:Ace}),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=XVt(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),j=h,C=H_s([n,t]),T=ky(ky({},k),s);return g.createElement(g.Fragment,null,d&&g.createElement(j,{sideCar:eUt,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),ky(ky({},T),{ref:C})):g.createElement(b,ky({},T,{className:c,ref:C}),l))});cJ.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};cJ.classNames={fullWidth:BB,zeroRight:FB};var J_s=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function eTs(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=J_s();return t&&e.setAttribute("nonce",t),e}function tTs(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function nTs(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var rTs=function(){var e=0,t=null;return{add:function(n){e==0&&(t=eTs())&&(tTs(t,n),nTs(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},sTs=function(){var e=rTs();return function(t,n){g.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},tUt=function(){var e=sTs(),t=function(n){var r=n.styles,s=n.dynamic;return e(r,s),null};return t},iTs={left:0,top:0,right:0,gap:0},Pce=function(e){return parseInt(e||"",10)||0},oTs=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[Pce(n),Pce(r),Pce(s)]},aTs=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return iTs;var t=oTs(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])}},lTs=tUt(),II="data-scroll-locked",cTs=function(e,t,n,r){var s=e.left,i=e.top,o=e.right,l=e.gap;return n===void 0&&(n="margin"),`
|
|
697
697
|
.`.concat(q_s,` {
|