@mastra/deployer-sandbox 0.3.21 → 0.3.22-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/studio/assets/{CodeDiff.es-D-3pK78A.js → CodeDiff.es-hnMamK_l.js} +1 -1
- package/dist/studio/assets/{core-QQAS7ifM.js → core-VuCQVt-s.js} +1 -1
- package/dist/studio/assets/{index-mdIMRdQn.js → index-SN6EsXk6.js} +2 -2
- package/dist/studio/assets/{index-C7U0QkuV.js → index-TU8EIsjo.js} +1 -1
- package/dist/studio/assets/{main-CS8gBi_K.js → main-B2KiawZF.js} +4 -4
- package/dist/studio/index.html +1 -1
- package/package.json +4 -4
|
@@ -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-VuCQVt-s.js","./index-TU8EIsjo.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-hnMamK_l.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{_ as Ai}from"./preload-helper-PPVm8Dsz.js";function GHt(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 Ev(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var yne={exports:{}},vR={};var IMe;function KHt(){if(IMe)return vR;IMe=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 vR.Fragment=t,vR.jsx=n,vR.jsxs=n,vR}var NMe;function YHt(){return NMe||(NMe=1,yne.exports=KHt()),yne.exports}var a=YHt(),xne={exports:{}},Gr={},AMe;function XHt(){if(AMe)return Gr;AMe=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(M){return M===null||typeof M!="object"?null:(M=p&&M[p]||M["@@iterator"],typeof M=="function"?M:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,x={};function b(M,$,z){this.props=M,this.context=$,this.refs=x,this.updater=z||v}b.prototype.isReactComponent={},b.prototype.setState=function(M,$){if(typeof M!="object"&&typeof M!="function"&&M!=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,M,$,"setState")},b.prototype.forceUpdate=function(M){this.updater.enqueueForceUpdate(this,M,"forceUpdate")};function S(){}S.prototype=b.prototype;function k(M,$,z){this.props=M,this.context=$,this.refs=x,this.updater=z||v}var j=k.prototype=new S;j.constructor=k,y(j,b.prototype),j.isPureReactComponent=!0;var C=Array.isArray;function T(){}var _={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function I(M,$,z){var U=z.ref;return{$$typeof:t,type:M,key:$,ref:U!==void 0?U:null,props:z}}function A(M,$){return I(M.type,$,M.props)}function P(M){return typeof M=="object"&&M!==null&&M.$$typeof===t}function L(M){var $={"=":"=0",":":"=2"};return"$"+M.replace(/[=:]/g,function(z){return $[z]})}var F=/\/+/g;function Q(M,$){return typeof M=="object"&&M!==null&&M.key!=null?L(""+M.key):$.toString(36)}function q(M){switch(M.status){case"fulfilled":return M.value;case"rejected":throw M.reason;default:switch(typeof M.status=="string"?M.then(T,T):(M.status="pending",M.then(function($){M.status==="pending"&&(M.status="fulfilled",M.value=$)},function($){M.status==="pending"&&(M.status="rejected",M.reason=$)})),M.status){case"fulfilled":return M.value;case"rejected":throw M.reason}}throw M}function B(M,$,z,U,G){var ne=typeof M;(ne==="undefined"||ne==="boolean")&&(M=null);var X=!1;if(M===null)X=!0;else switch(ne){case"bigint":case"string":case"number":X=!0;break;case"object":switch(M.$$typeof){case t:case n:X=!0;break;case f:return X=M._init,B(X(M._payload),$,z,U,G)}}if(X)return G=G(M),X=U===""?"."+Q(M,0):U,C(G)?(z="",X!=null&&(z=X.replace(F,"$&/")+"/"),B(G,$,z,"",function(fe){return fe})):G!=null&&(P(G)&&(G=A(G,z+(G.key==null||M&&M.key===G.key?"":(""+G.key).replace(F,"$&/")+"/")+X)),$.push(G)),1;X=0;var ee=U===""?".":U+":";if(C(M))for(var ie=0;ie<M.length;ie++)U=M[ie],ne=ee+Q(U,ie),X+=B(U,$,z,ne,G);else if(ie=m(M),typeof ie=="function")for(M=ie.call(M),ie=0;!(U=M.next()).done;)U=U.value,ne=ee+Q(U,ie++),X+=B(U,$,z,ne,G);else if(ne==="object"){if(typeof M.then=="function")return B(q(M),$,z,U,G);throw $=String(M),Error("Objects are not valid as a React child (found: "+($==="[object Object]"?"object with keys {"+Object.keys(M).join(", ")+"}":$)+"). If you meant to render a collection of children, use an array instead.")}return X}function V(M,$,z){if(M==null)return M;var U=[],G=0;return B(M,U,"","",function(ne){return $.call(z,ne,G++)}),U}function H(M){if(M._status===-1){var $=M._result;$=$(),$.then(function(z){(M._status===0||M._status===-1)&&(M._status=1,M._result=z)},function(z){(M._status===0||M._status===-1)&&(M._status=2,M._result=z)}),M._status===-1&&(M._status=0,M._result=$)}if(M._status===1)return M._result.default;throw M._result}var D=typeof reportError=="function"?reportError:function(M){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var $=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof M=="object"&&M!==null&&typeof M.message=="string"?String(M.message):String(M),error:M});if(!window.dispatchEvent($))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",M);return}console.error(M)},K={map:V,forEach:function(M,$,z){V(M,function(){$.apply(this,arguments)},z)},count:function(M){var $=0;return V(M,function(){$++}),$},toArray:function(M){return V(M,function($){return $})||[]},only:function(M){if(!P(M))throw Error("React.Children.only expected to receive a single React element child.");return M}};return Gr.Activity=h,Gr.Children=K,Gr.Component=b,Gr.Fragment=r,Gr.Profiler=i,Gr.PureComponent=k,Gr.StrictMode=s,Gr.Suspense=u,Gr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=_,Gr.__COMPILER_RUNTIME={__proto__:null,c:function(M){return _.H.useMemoCache(M)}},Gr.cache=function(M){return function(){return M.apply(null,arguments)}},Gr.cacheSignal=function(){return null},Gr.cloneElement=function(M,$,z){if(M==null)throw Error("The argument must be a React element, but you passed "+M+".");var U=y({},M.props),G=M.key;if($!=null)for(ne in $.key!==void 0&&(G=""+$.key),$)!N.call($,ne)||ne==="key"||ne==="__self"||ne==="__source"||ne==="ref"&&$.ref===void 0||(U[ne]=$[ne]);var ne=arguments.length-2;if(ne===1)U.children=z;else if(1<ne){for(var X=Array(ne),ee=0;ee<ne;ee++)X[ee]=arguments[ee+2];U.children=X}return I(M.type,G,U)},Gr.createContext=function(M){return M={$$typeof:l,_currentValue:M,_currentValue2:M,_threadCount:0,Provider:null,Consumer:null},M.Provider=M,M.Consumer={$$typeof:o,_context:M},M},Gr.createElement=function(M,$,z){var U,G={},ne=null;if($!=null)for(U in $.key!==void 0&&(ne=""+$.key),$)N.call($,U)&&U!=="key"&&U!=="__self"&&U!=="__source"&&(G[U]=$[U]);var X=arguments.length-2;if(X===1)G.children=z;else if(1<X){for(var ee=Array(X),ie=0;ie<X;ie++)ee[ie]=arguments[ie+2];G.children=ee}if(M&&M.defaultProps)for(U in X=M.defaultProps,X)G[U]===void 0&&(G[U]=X[U]);return I(M,ne,G)},Gr.createRef=function(){return{current:null}},Gr.forwardRef=function(M){return{$$typeof:c,render:M}},Gr.isValidElement=P,Gr.lazy=function(M){return{$$typeof:f,_payload:{_status:-1,_result:M},_init:H}},Gr.memo=function(M,$){return{$$typeof:d,type:M,compare:$===void 0?null:$}},Gr.startTransition=function(M){var $=_.T,z={};_.T=z;try{var U=M(),G=_.S;G!==null&&G(z,U),typeof U=="object"&&U!==null&&typeof U.then=="function"&&U.then(T,D)}catch(ne){D(ne)}finally{$!==null&&z.types!==null&&($.types=z.types),_.T=$}},Gr.unstable_useCacheRefresh=function(){return _.H.useCacheRefresh()},Gr.use=function(M){return _.H.use(M)},Gr.useActionState=function(M,$,z){return _.H.useActionState(M,$,z)},Gr.useCallback=function(M,$){return _.H.useCallback(M,$)},Gr.useContext=function(M){return _.H.useContext(M)},Gr.useDebugValue=function(){},Gr.useDeferredValue=function(M,$){return _.H.useDeferredValue(M,$)},Gr.useEffect=function(M,$){return _.H.useEffect(M,$)},Gr.useEffectEvent=function(M){return _.H.useEffectEvent(M)},Gr.useId=function(){return _.H.useId()},Gr.useImperativeHandle=function(M,$,z){return _.H.useImperativeHandle(M,$,z)},Gr.useInsertionEffect=function(M,$){return _.H.useInsertionEffect(M,$)},Gr.useLayoutEffect=function(M,$){return _.H.useLayoutEffect(M,$)},Gr.useMemo=function(M,$){return _.H.useMemo(M,$)},Gr.useOptimistic=function(M,$){return _.H.useOptimistic(M,$)},Gr.useReducer=function(M,$,z){return _.H.useReducer(M,$,z)},Gr.useRef=function(M){return _.H.useRef(M)},Gr.useState=function(M){return _.H.useState(M)},Gr.useSyncExternalStore=function(M,$,z){return _.H.useSyncExternalStore(M,$,z)},Gr.useTransition=function(){return _.H.useTransition()},Gr.version="19.2.7",Gr}var PMe;function YA(){return PMe||(PMe=1,xne.exports=XHt()),xne.exports}var g=YA();const Me=Ev(g),XA=GHt({__proto__:null,default:Me},[g]);var bne={exports:{}},yR={},wne={exports:{}},Sne={};var $Me;function JHt(){return $Me||($Me=1,(function(e){function t(q,B){var V=q.length;q.push(B);e:for(;0<V;){var H=V-1>>>1,D=q[H];if(0<s(D,B))q[H]=B,q[V]=D,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,D=q.length,K=D>>>1;H<K;){var M=2*(H+1)-1,$=q[M],z=M+1,U=q[z];if(0>s($,V))z<D&&0>s(U,$)?(q[H]=U,q[z]=V,H=z):(q[H]=$,q[M]=V,H=M);else if(z<D&&0>s(U,V))q[H]=U,q[z]=V,H=z;else break e}}return B}function s(q,B){var V=q.sortIndex-B.sortIndex;return V!==0?V:q.id-B.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var o=Date,l=o.now();e.unstable_now=function(){return o.now()-l}}var c=[],u=[],d=1,f=null,h=3,p=!1,m=!1,v=!1,y=!1,x=typeof setTimeout=="function"?setTimeout:null,b=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;function k(q){for(var B=n(u);B!==null;){if(B.callback===null)r(u);else if(B.startTime<=q)r(u),B.sortIndex=B.expirationTime,t(c,B);else break;B=n(u)}}function j(q){if(v=!1,k(q),!m)if(n(c)!==null)m=!0,C||(C=!0,P());else{var B=n(u);B!==null&&Q(j,B.startTime-q)}}var C=!1,T=-1,_=5,N=-1;function I(){return y?!0:!(e.unstable_now()-N<_)}function A(){if(y=!1,C){var q=e.unstable_now();N=q;var B=!0;try{e:{m=!1,v&&(v=!1,b(T),T=-1),p=!0;var V=h;try{t:{for(k(q),f=n(c);f!==null&&!(f.expirationTime>q&&I());){var H=f.callback;if(typeof H=="function"){f.callback=null,h=f.priorityLevel;var D=H(f.expirationTime<=q);if(q=e.unstable_now(),typeof D=="function"){f.callback=D,k(q),B=!0;break t}f===n(c)&&r(c),k(q)}else r(c);f=n(c)}if(f!==null)B=!0;else{var K=n(u);K!==null&&Q(j,K.startTime-q),B=!1}}break e}finally{f=null,h=V,p=!1}B=void 0}}finally{B?P():C=!1}}}var P;if(typeof S=="function")P=function(){S(A)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,F=L.port2;L.port1.onmessage=A,P=function(){F.postMessage(null)}}else P=function(){x(A,0)};function Q(q,B){T=x(function(){q(e.unstable_now())},B)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(q){q.callback=null},e.unstable_forceFrameRate=function(q){0>q||125<q?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):_=0<q?Math.floor(1e3/q):5},e.unstable_getCurrentPriorityLevel=function(){return h},e.unstable_next=function(q){switch(h){case 1:case 2:case 3:var B=3;break;default:B=h}var V=h;h=B;try{return q()}finally{h=V}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(q,B){switch(q){case 1:case 2:case 3:case 4:case 5:break;default:q=3}var V=h;h=q;try{return B()}finally{h=V}},e.unstable_scheduleCallback=function(q,B,V){var 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 D=-1;break;case 2:D=250;break;case 5:D=1073741823;break;case 4:D=1e4;break;default:D=5e3}return D=V+D,q={id:d++,callback:B,priorityLevel:q,startTime:V,expirationTime:D,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=D,t(c,q),m||p||(m=!0,C||(C=!0,P()))),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}}}})(Sne)),Sne}var RMe;function eGt(){return RMe||(RMe=1,wne.exports=JHt()),wne.exports}var kne={exports:{}},qu={};var MMe;function tGt(){if(MMe)return qu;MMe=1;var e=YA();function t(c){var u="https://react.dev/errors/"+c;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var d=2;d<arguments.length;d++)u+="&args[]="+encodeURIComponent(arguments[d])}return"Minified React error #"+c+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(t(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},s=Symbol.for("react.portal");function i(c,u,d){var f=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:f==null?null:""+f,children:c,containerInfo:u,implementation:d}}var o=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,u){if(c==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return qu.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,qu.createPortal=function(c,u){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(t(299));return i(c,u,null,d)},qu.flushSync=function(c){var u=o.T,d=r.p;try{if(o.T=null,r.p=2,c)return c()}finally{o.T=u,r.p=d,r.d.f()}},qu.preconnect=function(c,u){typeof c=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,r.d.C(c,u))},qu.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},qu.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin),h=typeof u.integrity=="string"?u.integrity:void 0,p=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;d==="style"?r.d.S(c,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:f,integrity:h,fetchPriority:p}):d==="script"&&r.d.X(c,{crossOrigin:f,integrity:h,fetchPriority:p,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},qu.preinitModule=function(c,u){if(typeof c=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var d=l(u.as,u.crossOrigin);r.d.M(c,{crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&r.d.M(c)},qu.preload=function(c,u){if(typeof c=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin);r.d.L(c,d,{crossOrigin:f,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0,type:typeof u.type=="string"?u.type:void 0,fetchPriority:typeof u.fetchPriority=="string"?u.fetchPriority:void 0,referrerPolicy:typeof u.referrerPolicy=="string"?u.referrerPolicy:void 0,imageSrcSet:typeof u.imageSrcSet=="string"?u.imageSrcSet:void 0,imageSizes:typeof u.imageSizes=="string"?u.imageSizes:void 0,media:typeof u.media=="string"?u.media:void 0})}},qu.preloadModule=function(c,u){if(typeof c=="string")if(u){var d=l(u.as,u.crossOrigin);r.d.m(c,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else r.d.m(c)},qu.requestFormReset=function(c){r.d.r(c)},qu.unstable_batchedUpdates=function(c,u){return c(u)},qu.useFormState=function(c,u,d){return o.H.useFormState(c,u,d)},qu.useFormStatus=function(){return o.H.useHostTransitionStatus()},qu.version="19.2.7",qu}var DMe;function Trt(){if(DMe)return kne.exports;DMe=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(),kne.exports=tGt(),kne.exports}var LMe;function nGt(){if(LMe)return yR;LMe=1;var e={env:{}};var t=eGt(),n=YA(),r=Trt();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 oe=!1,be=W.child;be;){if(be===E){oe=!0,E=W,R=J;break}if(be===R){oe=!0,R=W,E=J;break}be=be.sibling}if(!oe){for(be=J.child;be;){if(be===E){oe=!0,E=J,R=W;break}if(be===R){oe=!0,R=J,E=W;break}be=be.sibling}if(!oe)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"),A=Symbol.for("react.memo_cache_sentinel"),P=Symbol.iterator;function L(w){return w===null||typeof w!="object"?null:(w=P&&w[P]||w["@@iterator"],typeof w=="function"?w:null)}var F=Symbol.for("react.client.reference");function Q(w){if(w==null)return null;if(typeof w=="function")return w.$$typeof===F?null:w.displayName||w.name||null;if(typeof w=="string")return w;switch(w){case y:return"Fragment";case b:return"Profiler";case x:return"StrictMode";case C:return"Suspense";case T:return"SuspenseList";case 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},D=[],K=-1;function M(w){return{current:w}}function $(w){0>K||(w.current=D[K],D[K]=null,K--)}function z(w,O){K++,D[K]=w.current,w.current=O}var U=M(null),G=M(null),ne=M(null),X=M(null);function ee(w,O){switch(z(ne,O),z(G,w),z(U,null),O.nodeType){case 9:case 11:w=(w=O.documentElement)&&(w=w.namespaceURI)?JRe(w):0;break;default:if(w=O.tagName,O=O.namespaceURI)O=JRe(O),w=eMe(O,w);else switch(w){case"svg":w=1;break;case"math":w=2;break;default:w=0}}$(U),z(U,w)}function ie(){$(U),$(G),$(ne)}function fe(w){w.memoizedState!==null&&z(X,w);var O=U.current,E=eMe(O,w.type);O!==E&&(z(G,w),z(U,E))}function te(w){G.current===w&&($(U),$(G)),X.current===w&&($(X),hR._currentValue=H)}var se,re;function le(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 Lt=function(){throw Error()};if(Object.defineProperty(Lt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Lt,[])}catch(bt){var pt=bt}Reflect.construct(w,[],Lt)}else{try{Lt.call()}catch(bt){pt=bt}w.call(Lt.prototype)}}else{try{throw Error()}catch(bt){pt=bt}(Lt=w())&&typeof Lt.catch=="function"&&Lt.catch(function(){})}}catch(bt){if(bt&&pt&&typeof bt.stack=="string")return[bt.stack,pt.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(),oe=J[0],be=J[1];if(oe&&be){var qe=oe.split(`
|
|
@@ -254,7 +254,7 @@ Error message: ${_ct(n)}`,cause:n}),this[Mct]=!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)=>{nm.isError(c)&&(c.value=u),l(c)},(c,u)=>{c.length?l(new nm(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 nm.isError(l)&&(l.value=c),l},(l,c)=>{if(l.length)throw new nm(l,t,void 0,void 0,o);i=c}),i}isValid(t,n){return this.validate(t,n).then(()=>!0,r=>{if(nm.isError(r))return!1;throw r})}isValidSync(t,n){try{return this.validateSync(t,n),!0}catch(r){if(nm.isError(r))return!1;throw r}}_getDefault(t){let n=this.spec.default;return n==null?n:typeof n=="function"?n.call(this,t):nI(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=XT({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=XT({message:n,name:"optionality",test(s){return s===void 0?this.schema.spec.optional:!0}}),r}optional(){return this.optionality(!0)}defined(t=Mb.defined){return this.optionality(!1,t)}nullable(){return this.nullability(!0)}nonNullable(t=Mb.notNull){return this.nullability(!1,t)}required(t=Mb.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=Mb.default),typeof n.test!="function")throw new TypeError("`test` is a required parameters");let r=this.clone(),s=XT(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=J1t(t).map(i=>new UL(i));return s.forEach(i=>{i.isSibling&&r.deps.push(i.key)}),r.conditions.push(typeof n=="function"?new YBe(s,n):YBe.fromOptions(s,n)),r}typeError(t){let n=this.clone();return n.internalTests.typeError=XT({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=Mb.oneOf){let r=this.clone();return t.forEach(s=>{r._whitelist.add(s),r._blacklist.delete(s)}),r.internalTests.whiteList=XT({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=Mb.notOneOf){let r=this.clone();return t.forEach(s=>{r._blacklist.add(s),r._whitelist.delete(s)}),r.internalTests.blacklist=XT({message:n,name:"notOneOf",test(s){let i=this.schema._blacklist,o=i.resolveAll(this.resolve);return o.includes(s)?this.createError({params:{values:Array.from(i).join(", "),resolved:o}}):!0}}),r}strip(t=!0){let n=this.clone();return n.spec.strip=t,n}describe(t){const n=(t?this.resolve(t):this).clone(),{label:r,meta:s,optional:i,nullable:o}=n.spec;return{meta:s,label:r,optional:i,nullable:o,default:n.getDefault(t),type:n.type,oneOf:n._whitelist.describe(),notOneOf:n._blacklist.describe(),tests:n.tests.map(c=>({name:c.OPTIONS.name,params:c.OPTIONS.params})).filter((c,u,d)=>d.findIndex(f=>f.name===c.name)===u)}}};LC.prototype.__isYupSchema__=!0;for(const e of["validate","validateSync"])LC.prototype[`${e}At`]=function(t,n,r={}){const{parent:s,parentPath:i,schema:o}=ttr(this,t,n,r.context);return o[e](s&&s[i],Object.assign({},r,{parent:s,path:t}))};for(const e of["equals","is"])LC.prototype[e]=LC.prototype.oneOf;for(const e of["not","nope"])LC.prototype[e]=LC.prototype.notOneOf;var ntr=/^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/;function rtr(e){const t=str(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 str(e){var t,n;const r=ntr.exec(e);return r?{year:vb(r[1]),month:vb(r[2],1)-1,day:vb(r[3],1),hour:vb(r[4]),minute:vb(r[5]),second:vb(r[6]),millisecond:r[7]?vb(r[7].substring(0,3)):0,precision:(t=(n=r[7])==null?void 0:n.length)!=null?t:void 0,z:r[8]||void 0,plusMinus:r[9]||void 0,hourOffset:vb(r[10]),minuteOffset:vb(r[11])}:null}function vb(e,t=0){return Number(e)||t}var itr=new Date(""),otr=e=>Object.prototype.toString.call(e)==="[object Date]",atr=class lSt extends LC{constructor(){super({type:"date",check(t){return otr(t)&&!isNaN(t.getTime())}}),this.withMutation(()=>{this.transform((t,n,r)=>!r.spec.coerce||r.isType(t)||t===null?t:(t=rtr(t),isNaN(t)?lSt.INVALID_DATE:new Date(t)))})}prepareParam(t,n){let r;if(UL.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=Tpe.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=Tpe.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)}})}};atr.INVALID_DATE=itr;function JBe(e,t){let n=e;for(const r of t)if(n=n[r],n===void 0)return;return n}function pD(e){if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}const FSe=6048e5,ltr=864e5,ctr=6e4,utr=36e5,dtr=1e3,eUe=Symbol.for("constructDateFrom");function Do(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&eUe in e?e[eUe](t):e instanceof Date?new e.constructor(t):new Date(t)}function Hs(e,t){return Do(t||e,e)}function du(e,t,n){const r=Hs(e,n?.in);return isNaN(t)?Do(n?.in||e,NaN):(t&&r.setDate(r.getDate()+t),r)}function Sv(e,t,n){const r=Hs(e,n?.in);if(isNaN(t))return Do(n?.in||e,NaN);if(!t)return r;const s=r.getDate(),i=Do(n?.in||e,r.getTime());i.setMonth(r.getMonth()+t+1,0);const o=i.getDate();return s>=o?i:(r.setFullYear(i.getFullYear(),i.getMonth(),s),r)}let ftr={};function M_(){return ftr}function gp(e,t){const n=M_(),r=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,s=Hs(e,t?.in),i=s.getDay(),o=(i<r?7:0)+i-r;return s.setDate(s.getDate()-o),s.setHours(0,0,0,0),s}function A0(e,t){return gp(e,{...t,weekStartsOn:1})}function cSt(e,t){const n=Hs(e,t?.in),r=n.getFullYear(),s=Do(n,0);s.setFullYear(r+1,0,4),s.setHours(0,0,0,0);const i=A0(s),o=Do(n,0);o.setFullYear(r,0,4),o.setHours(0,0,0,0);const l=A0(o);return n.getTime()>=i.getTime()?r+1:n.getTime()>=l.getTime()?r:r-1}function eA(e){const t=Hs(e),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+e-+n}function PP(e,...t){const n=Do.bind(null,e||t.find(r=>typeof r=="object"));return t.map(n)}function tA(e,t){const n=Hs(e,t?.in);return n.setHours(0,0,0,0),n}function qy(e,t,n){const[r,s]=PP(n?.in,e,t),i=tA(r),o=tA(s),l=+i-eA(i),c=+o-eA(o);return Math.round((l-c)/ltr)}function htr(e,t){const n=cSt(e,t),r=Do(e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),A0(r)}function Epe(e,t,n){return du(e,t*7,n)}function ptr(e,t,n){return Sv(e,t*12,n)}function mtr(e,t){let n,r=t?.in;return e.forEach(s=>{!r&&typeof s=="object"&&(r=Do.bind(null,s));const i=Hs(s,r);(!n||n<i||isNaN(+i))&&(n=i)}),Do(r,n||NaN)}function gtr(e,t){let n,r=t?.in;return e.forEach(s=>{!r&&typeof s=="object"&&(r=Do.bind(null,s));const i=Hs(s,r);(!n||n>i||isNaN(+i))&&(n=i)}),Do(r,n||NaN)}function Qf(e,t,n){const[r,s]=PP(n?.in,e,t);return+tA(r)==+tA(s)}function BSe(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function USe(e){return!(!BSe(e)&&typeof e!="number"||isNaN(+Hs(e)))}function k5(e,t,n){const[r,s]=PP(n?.in,e,t),i=r.getFullYear()-s.getFullYear(),o=r.getMonth()-s.getMonth();return i*12+o}function vtr(e,t,n){const[r,s]=PP(n?.in,e,t),i=gp(r,n),o=gp(s,n),l=+i-eA(i),c=+o-eA(o);return Math.round((l-c)/FSe)}function VSe(e,t){const n=Hs(e,t?.in),r=n.getMonth();return n.setFullYear(n.getFullYear(),r+1,0),n.setHours(23,59,59,999),n}function Yf(e,t){const n=Hs(e,t?.in);return n.setDate(1),n.setHours(0,0,0,0),n}function uSt(e,t){const n=Hs(e,t?.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}function qSe(e,t){const n=M_(),r=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,s=Hs(e,t?.in),i=s.getDay(),o=(i<r?-7:0)+6-(i-r);return s.setDate(s.getDate()+o),s.setHours(23,59,59,999),s}function dSt(e,t){return qSe(e,{...t,weekStartsOn:1})}const ytr={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"}},xtr=(e,t,n)=>{let r;const s=ytr[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 _oe(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}const btr={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},wtr={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Str={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},ktr={date:_oe({formats:btr,defaultWidth:"full"}),time:_oe({formats:wtr,defaultWidth:"full"}),dateTime:_oe({formats:Str,defaultWidth:"full"})},Otr={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},jtr=(e,t,n,r)=>Otr[e];function ZR(e){return(t,n)=>{const r=n?.context?String(n.context):"standalone";let s;if(r==="formatting"&&e.formattingValues){const o=e.defaultFormattingWidth||e.defaultWidth,l=n?.width?String(n.width):o;s=e.formattingValues[l]||e.formattingValues[o]}else{const o=e.defaultWidth,l=n?.width?String(n.width):e.defaultWidth;s=e.values[l]||e.values[o]}const i=e.argumentCallback?e.argumentCallback(t):t;return s[i]}}const Ctr={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},_tr={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Ttr={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"]},Etr={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"]},Itr={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"}},Ntr={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"}},Atr=(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"},Ptr={ordinalNumber:Atr,era:ZR({values:Ctr,defaultWidth:"wide"}),quarter:ZR({values:_tr,defaultWidth:"wide",argumentCallback:e=>e-1}),month:ZR({values:Ttr,defaultWidth:"wide"}),day:ZR({values:Etr,defaultWidth:"wide"}),dayPeriod:ZR({values:Itr,defaultWidth:"wide",formattingValues:Ntr,defaultFormattingWidth:"wide"})};function WR(e){return(t,n={})=>{const r=n.width,s=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],i=t.match(s);if(!i)return null;const o=i[0],l=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?Rtr(l,f=>f.test(o)):$tr(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 $tr(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function Rtr(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function Mtr(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 Dtr=/^(\d+)(th|st|nd|rd)?/i,Ltr=/\d+/i,ztr={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},Ftr={any:[/^b/i,/^(a|c)/i]},Btr={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},Utr={any:[/1/i,/2/i,/3/i,/4/i]},Vtr={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},qtr={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]},Qtr={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},Ztr={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]},Wtr={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},Htr={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}},Gtr={ordinalNumber:Mtr({matchPattern:Dtr,parsePattern:Ltr,valueCallback:e=>parseInt(e,10)}),era:WR({matchPatterns:ztr,defaultMatchWidth:"wide",parsePatterns:Ftr,defaultParseWidth:"any"}),quarter:WR({matchPatterns:Btr,defaultMatchWidth:"wide",parsePatterns:Utr,defaultParseWidth:"any",valueCallback:e=>e+1}),month:WR({matchPatterns:Vtr,defaultMatchWidth:"wide",parsePatterns:qtr,defaultParseWidth:"any"}),day:WR({matchPatterns:Qtr,defaultMatchWidth:"wide",parsePatterns:Ztr,defaultParseWidth:"any"}),dayPeriod:WR({matchPatterns:Wtr,defaultMatchWidth:"any",parsePatterns:Htr,defaultParseWidth:"any"})},QSe={code:"en-US",formatDistance:xtr,formatLong:ktr,formatRelative:jtr,localize:Ptr,match:Gtr,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Ktr(e,t){const n=Hs(e,t?.in);return qy(n,uSt(n))+1}function ZSe(e,t){const n=Hs(e,t?.in),r=+A0(n)-+htr(n);return Math.round(r/FSe)+1}function WSe(e,t){const n=Hs(e,t?.in),r=n.getFullYear(),s=M_(),i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,o=Do(t?.in||e,0);o.setFullYear(r+1,0,i),o.setHours(0,0,0,0);const l=gp(o,t),c=Do(t?.in||e,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const u=gp(c,t);return+n>=+l?r+1:+n>=+u?r:r-1}function Ytr(e,t){const n=M_(),r=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,s=WSe(e,t),i=Do(t?.in||e,0);return i.setFullYear(s,0,r),i.setHours(0,0,0,0),gp(i,t)}function HSe(e,t){const n=Hs(e,t?.in),r=+gp(n,t)-+Ytr(n,t);return Math.round(r/FSe)+1}function Xi(e,t){const n=e<0?"-":"",r=Math.abs(e).toString().padStart(t,"0");return n+r}const Xw={y(e,t){const n=e.getFullYear(),r=n>0?n:1-n;return Xi(t==="yy"?r%100:r,t.length)},M(e,t){const n=e.getMonth();return t==="M"?String(n+1):Xi(n+1,2)},d(e,t){return Xi(e.getDate(),t.length)},a(e,t){const n=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];default:return n==="am"?"a.m.":"p.m."}},h(e,t){return Xi(e.getHours()%12||12,t.length)},H(e,t){return Xi(e.getHours(),t.length)},m(e,t){return Xi(e.getMinutes(),t.length)},s(e,t){return Xi(e.getSeconds(),t.length)},S(e,t){const n=t.length,r=e.getMilliseconds(),s=Math.trunc(r*Math.pow(10,n-3));return Xi(s,t.length)}},JT={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},tUe={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 Xw.y(e,t)},Y:function(e,t,n,r){const s=WSe(e,r),i=s>0?s:1-s;if(t==="YY"){const o=i%100;return Xi(o,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):Xi(i,t.length)},R:function(e,t){const n=cSt(e);return Xi(n,t.length)},u:function(e,t){const n=e.getFullYear();return Xi(n,t.length)},Q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(r);case"QQ":return Xi(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(r);case"qq":return Xi(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,t,n){const r=e.getMonth();switch(t){case"M":case"MM":return Xw.M(e,t);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(e,t,n){const r=e.getMonth();switch(t){case"L":return String(r+1);case"LL":return Xi(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(e,t,n,r){const s=HSe(e,r);return t==="wo"?n.ordinalNumber(s,{unit:"week"}):Xi(s,t.length)},I:function(e,t,n){const r=ZSe(e);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):Xi(r,t.length)},d:function(e,t,n){return t==="do"?n.ordinalNumber(e.getDate(),{unit:"date"}):Xw.d(e,t)},D:function(e,t,n){const r=Ktr(e);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Xi(r,t.length)},E:function(e,t,n){const r=e.getDay();switch(t){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(e,t,n,r){const s=e.getDay(),i=(s-r.weekStartsOn+8)%7||7;switch(t){case"e":return String(i);case"ee":return Xi(i,2);case"eo":return n.ordinalNumber(i,{unit:"day"});case"eee":return n.day(s,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(s,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(s,{width:"short",context:"formatting"});default:return n.day(s,{width:"wide",context:"formatting"})}},c:function(e,t,n,r){const s=e.getDay(),i=(s-r.weekStartsOn+8)%7||7;switch(t){case"c":return String(i);case"cc":return Xi(i,t.length);case"co":return n.ordinalNumber(i,{unit:"day"});case"ccc":return n.day(s,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(s,{width:"narrow",context:"standalone"});case"cccccc":return n.day(s,{width:"short",context:"standalone"});default:return n.day(s,{width:"wide",context:"standalone"})}},i:function(e,t,n){const r=e.getDay(),s=r===0?7:r;switch(t){case"i":return String(s);case"ii":return Xi(s,t.length);case"io":return n.ordinalNumber(s,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(e,t,n){const s=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(s,{width:"narrow",context:"formatting"});default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(e,t,n){const r=e.getHours();let s;switch(r===12?s=JT.noon:r===0?s=JT.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=JT.evening:r>=12?s=JT.afternoon:r>=4?s=JT.morning:s=JT.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 Xw.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getHours(),{unit:"hour"}):Xw.H(e,t)},K:function(e,t,n){const r=e.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Xi(r,t.length)},k:function(e,t,n){let r=e.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):Xi(r,t.length)},m:function(e,t,n){return t==="mo"?n.ordinalNumber(e.getMinutes(),{unit:"minute"}):Xw.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getSeconds(),{unit:"second"}):Xw.s(e,t)},S:function(e,t){return Xw.S(e,t)},X:function(e,t,n){const r=e.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return rUe(r);case"XXXX":case"XX":return QO(r);default:return QO(r,":")}},x:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"x":return rUe(r);case"xxxx":case"xx":return QO(r);default:return QO(r,":")}},O:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+nUe(r,":");default:return"GMT"+QO(r,":")}},z:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+nUe(r,":");default:return"GMT"+QO(r,":")}},t:function(e,t,n){const r=Math.trunc(+e/1e3);return Xi(r,t.length)},T:function(e,t,n){return Xi(+e,t.length)}};function nUe(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),s=Math.trunc(r/60),i=r%60;return i===0?n+String(s):n+String(s)+t+Xi(i,2)}function rUe(e,t){return e%60===0?(e>0?"-":"+")+Xi(Math.abs(e)/60,2):QO(e,t)}function QO(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),s=Xi(Math.trunc(r/60),2),i=Xi(r%60,2);return n+s+t+i}const sUe=(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"})}},fSt=(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"})}},Xtr=(e,t)=>{const n=e.match(/(P+)(p+)?/)||[],r=n[1],s=n[2];if(!s)return sUe(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}}",sUe(r,t)).replace("{{time}}",fSt(s,t))},Ipe={p:fSt,P:Xtr},Jtr=/^D+$/,enr=/^Y+$/,tnr=["D","DD","YY","YYYY"];function hSt(e){return Jtr.test(e)}function pSt(e){return enr.test(e)}function Npe(e,t,n){const r=nnr(e,t,n);if(console.warn(r),tnr.includes(e))throw new RangeError(r)}function nnr(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 rnr=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,snr=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,inr=/^'([^]*?)'?$/,onr=/''/g,anr=/[a-zA-Z]/;function Ok(e,t,n){const r=M_(),s=n?.locale??r.locale??QSe,i=n?.firstWeekContainsDate??n?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=n?.weekStartsOn??n?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,l=Hs(e,n?.in);if(!USe(l))throw new RangeError("Invalid time value");let c=t.match(snr).map(d=>{const f=d[0];if(f==="p"||f==="P"){const h=Ipe[f];return h(d,s.formatLong)}return d}).join("").match(rnr).map(d=>{if(d==="''")return{isToken:!1,value:"'"};const f=d[0];if(f==="'")return{isToken:!1,value:lnr(d)};if(tUe[f])return{isToken:!0,value:d};if(f.match(anr))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&&pSt(f)||!n?.useAdditionalDayOfYearTokens&&hSt(f))&&Npe(f,t,String(e));const h=tUe[f[0]];return h(l,f,s.localize,u)}).join("")}function lnr(e){const t=e.match(inr);return t?t[1].replace(onr,"'"):e}function cnr(e,t){const n=Hs(e,t?.in),r=n.getFullYear(),s=n.getMonth(),i=Do(n,0);return i.setFullYear(r,s+1,0),i.setHours(0,0,0,0),i.getDate()}function unr(){return Object.assign({},M_())}function dnr(e,t){const n=Hs(e,t?.in).getDay();return n===0?7:n}function fnr(e){return Math.trunc(+Hs(e)/1e3)}function hnr(e,t){const n=Hs(e,t?.in),r=n.getMonth();return n.setFullYear(n.getFullYear(),r+1,0),n.setHours(0,0,0,0),Hs(n,t?.in)}function pnr(e,t){const n=Hs(e,t?.in);return vtr(hnr(n,t),Yf(n,t),t)+1}function Ape(e,t){return+Hs(e)>+Hs(t)}function mSt(e,t){return+Hs(e)<+Hs(t)}function mnr(e,t){const n=gnr(t)?new t(0):Do(t,0);return n.setFullYear(e.getFullYear(),e.getMonth(),e.getDate()),n.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()),n}function gnr(e){return typeof e=="function"&&e.prototype?.constructor===e}const vnr=10;class gSt{subPriority=0;validate(t,n){return!0}}class ynr extends gSt{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 xnr extends gSt{priority=vnr;subPriority=-1;constructor(t,n){super(),this.context=t||(r=>Do(n,r))}set(t,n){return n.timestampIsSet?t:Do(t,mnr(t,this.context))}}class Di{run(t,n,r,s){const i=this.parse(t,n,r,s);return i?{setter:new ynr(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class bnr extends Di{priority=140;parse(t,n,r){switch(n){case"G":case"GG":case"GGG":return r.era(t,{width:"abbreviated"})||r.era(t,{width:"narrow"});case"GGGGG":return r.era(t,{width:"narrow"});default:return r.era(t,{width:"wide"})||r.era(t,{width:"abbreviated"})||r.era(t,{width:"narrow"})}}set(t,n,r){return n.era=r,t.setFullYear(r,0,1),t.setHours(0,0,0,0),t}incompatibleTokens=["R","u","t","T"]}const wl={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},Py={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function Sl(e,t){return e&&{value:t(e.value),rest:e.rest}}function za(e,t){const n=t.match(e);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function $y(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*utr+i*ctr+o*dtr),rest:t.slice(n[0].length)}}function vSt(e){return za(wl.anyDigitsSigned,e)}function dl(e,t){switch(e){case 1:return za(wl.singleDigit,t);case 2:return za(wl.twoDigits,t);case 3:return za(wl.threeDigits,t);case 4:return za(wl.fourDigits,t);default:return za(new RegExp("^\\d{1,"+e+"}"),t)}}function pQ(e,t){switch(e){case 1:return za(wl.singleDigitSigned,t);case 2:return za(wl.twoDigitsSigned,t);case 3:return za(wl.threeDigitsSigned,t);case 4:return za(wl.fourDigitsSigned,t);default:return za(new RegExp("^-?\\d{1,"+e+"}"),t)}}function GSe(e){switch(e){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;default:return 0}}function ySt(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 xSt(e){return e%400===0||e%4===0&&e%100!==0}class wnr extends Di{priority=130;incompatibleTokens=["Y","R","u","w","I","i","e","c","t","T"];parse(t,n,r){const s=i=>({year:i,isTwoDigitYear:n==="yy"});switch(n){case"y":return Sl(dl(4,t),s);case"yo":return Sl(r.ordinalNumber(t,{unit:"year"}),s);default:return Sl(dl(n.length,t),s)}}validate(t,n){return n.isTwoDigitYear||n.year>0}set(t,n,r){const s=t.getFullYear();if(r.isTwoDigitYear){const o=ySt(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 Snr extends Di{priority=130;parse(t,n,r){const s=i=>({year:i,isTwoDigitYear:n==="YY"});switch(n){case"Y":return Sl(dl(4,t),s);case"Yo":return Sl(r.ordinalNumber(t,{unit:"year"}),s);default:return Sl(dl(n.length,t),s)}}validate(t,n){return n.isTwoDigitYear||n.year>0}set(t,n,r,s){const i=WSe(t,s);if(r.isTwoDigitYear){const l=ySt(r.year,i);return t.setFullYear(l,0,s.firstWeekContainsDate),t.setHours(0,0,0,0),gp(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),gp(t,s)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]}class knr extends Di{priority=130;parse(t,n){return pQ(n==="R"?4:n.length,t)}set(t,n,r){const s=Do(t,0);return s.setFullYear(r,0,4),s.setHours(0,0,0,0),A0(s)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]}class Onr extends Di{priority=130;parse(t,n){return pQ(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 jnr extends Di{priority=120;parse(t,n,r){switch(n){case"Q":case"QQ":return dl(n.length,t);case"Qo":return r.ordinalNumber(t,{unit:"quarter"});case"QQQ":return r.quarter(t,{width:"abbreviated",context:"formatting"})||r.quarter(t,{width:"narrow",context:"formatting"});case"QQQQQ":return r.quarter(t,{width:"narrow",context:"formatting"});default:return r.quarter(t,{width:"wide",context:"formatting"})||r.quarter(t,{width:"abbreviated",context:"formatting"})||r.quarter(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=1&&n<=4}set(t,n,r){return t.setMonth((r-1)*3,1),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]}class Cnr extends Di{priority=120;parse(t,n,r){switch(n){case"q":case"qq":return dl(n.length,t);case"qo":return r.ordinalNumber(t,{unit:"quarter"});case"qqq":return r.quarter(t,{width:"abbreviated",context:"standalone"})||r.quarter(t,{width:"narrow",context:"standalone"});case"qqqqq":return r.quarter(t,{width:"narrow",context:"standalone"});default:return r.quarter(t,{width:"wide",context:"standalone"})||r.quarter(t,{width:"abbreviated",context:"standalone"})||r.quarter(t,{width:"narrow",context:"standalone"})}}validate(t,n){return n>=1&&n<=4}set(t,n,r){return t.setMonth((r-1)*3,1),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]}class _nr extends Di{incompatibleTokens=["Y","R","q","Q","L","w","I","D","i","e","c","t","T"];priority=110;parse(t,n,r){const s=i=>i-1;switch(n){case"M":return Sl(za(wl.month,t),s);case"MM":return Sl(dl(2,t),s);case"Mo":return Sl(r.ordinalNumber(t,{unit:"month"}),s);case"MMM":return r.month(t,{width:"abbreviated",context:"formatting"})||r.month(t,{width:"narrow",context:"formatting"});case"MMMMM":return r.month(t,{width:"narrow",context:"formatting"});default:return r.month(t,{width:"wide",context:"formatting"})||r.month(t,{width:"abbreviated",context:"formatting"})||r.month(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=0&&n<=11}set(t,n,r){return t.setMonth(r,1),t.setHours(0,0,0,0),t}}class Tnr extends Di{priority=110;parse(t,n,r){const s=i=>i-1;switch(n){case"L":return Sl(za(wl.month,t),s);case"LL":return Sl(dl(2,t),s);case"Lo":return Sl(r.ordinalNumber(t,{unit:"month"}),s);case"LLL":return r.month(t,{width:"abbreviated",context:"standalone"})||r.month(t,{width:"narrow",context:"standalone"});case"LLLLL":return r.month(t,{width:"narrow",context:"standalone"});default:return r.month(t,{width:"wide",context:"standalone"})||r.month(t,{width:"abbreviated",context:"standalone"})||r.month(t,{width:"narrow",context:"standalone"})}}validate(t,n){return n>=0&&n<=11}set(t,n,r){return t.setMonth(r,1),t.setHours(0,0,0,0),t}incompatibleTokens=["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]}function Enr(e,t,n){const r=Hs(e,n?.in),s=HSe(r,n)-t;return r.setDate(r.getDate()-s*7),Hs(r,n?.in)}class Inr extends Di{priority=100;parse(t,n,r){switch(n){case"w":return za(wl.week,t);case"wo":return r.ordinalNumber(t,{unit:"week"});default:return dl(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,r,s){return gp(Enr(t,r,s),s)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]}function Nnr(e,t,n){const r=Hs(e,n?.in),s=ZSe(r,n)-t;return r.setDate(r.getDate()-s*7),r}class Anr extends Di{priority=100;parse(t,n,r){switch(n){case"I":return za(wl.week,t);case"Io":return r.ordinalNumber(t,{unit:"week"});default:return dl(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,r){return A0(Nnr(t,r))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]}const Pnr=[31,28,31,30,31,30,31,31,30,31,30,31],$nr=[31,29,31,30,31,30,31,31,30,31,30,31];class Rnr extends Di{priority=90;subPriority=1;parse(t,n,r){switch(n){case"d":return za(wl.date,t);case"do":return r.ordinalNumber(t,{unit:"date"});default:return dl(n.length,t)}}validate(t,n){const r=t.getFullYear(),s=xSt(r),i=t.getMonth();return s?n>=1&&n<=$nr[i]:n>=1&&n<=Pnr[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 Mnr extends Di{priority=90;subpriority=1;parse(t,n,r){switch(n){case"D":case"DD":return za(wl.dayOfYear,t);case"Do":return r.ordinalNumber(t,{unit:"date"});default:return dl(n.length,t)}}validate(t,n){const r=t.getFullYear();return xSt(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 KSe(e,t,n){const r=M_(),s=n?.weekStartsOn??n?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,i=Hs(e,n?.in),o=i.getDay(),c=(t%7+7)%7,u=7-s,d=t<0||t>6?t-(o+u)%7:(c+u)%7-(o+u)%7;return du(i,d,n)}class Dnr extends Di{priority=90;parse(t,n,r){switch(n){case"E":case"EE":case"EEE":return r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"});case"EEEEE":return r.day(t,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"});default:return r.day(t,{width:"wide",context:"formatting"})||r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=0&&n<=6}set(t,n,r,s){return t=KSe(t,r,s),t.setHours(0,0,0,0),t}incompatibleTokens=["D","i","e","c","t","T"]}class Lnr extends Di{priority=90;parse(t,n,r,s){const i=o=>{const l=Math.floor((o-1)/7)*7;return(o+s.weekStartsOn+6)%7+l};switch(n){case"e":case"ee":return Sl(dl(n.length,t),i);case"eo":return Sl(r.ordinalNumber(t,{unit:"day"}),i);case"eee":return r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"});case"eeeee":return r.day(t,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"});default:return r.day(t,{width:"wide",context:"formatting"})||r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=0&&n<=6}set(t,n,r,s){return t=KSe(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 znr extends Di{priority=90;parse(t,n,r,s){const i=o=>{const l=Math.floor((o-1)/7)*7;return(o+s.weekStartsOn+6)%7+l};switch(n){case"c":case"cc":return Sl(dl(n.length,t),i);case"co":return Sl(r.ordinalNumber(t,{unit:"day"}),i);case"ccc":return r.day(t,{width:"abbreviated",context:"standalone"})||r.day(t,{width:"short",context:"standalone"})||r.day(t,{width:"narrow",context:"standalone"});case"ccccc":return r.day(t,{width:"narrow",context:"standalone"});case"cccccc":return r.day(t,{width:"short",context:"standalone"})||r.day(t,{width:"narrow",context:"standalone"});default:return r.day(t,{width:"wide",context:"standalone"})||r.day(t,{width:"abbreviated",context:"standalone"})||r.day(t,{width:"short",context:"standalone"})||r.day(t,{width:"narrow",context:"standalone"})}}validate(t,n){return n>=0&&n<=6}set(t,n,r,s){return t=KSe(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 Fnr(e,t,n){const r=Hs(e,n?.in),s=dnr(r,n),i=t-s;return du(r,i,n)}class Bnr extends Di{priority=90;parse(t,n,r){const s=i=>i===0?7:i;switch(n){case"i":case"ii":return dl(n.length,t);case"io":return r.ordinalNumber(t,{unit:"day"});case"iii":return Sl(r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"}),s);case"iiiii":return Sl(r.day(t,{width:"narrow",context:"formatting"}),s);case"iiiiii":return Sl(r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"}),s);default:return Sl(r.day(t,{width:"wide",context:"formatting"})||r.day(t,{width:"abbreviated",context:"formatting"})||r.day(t,{width:"short",context:"formatting"})||r.day(t,{width:"narrow",context:"formatting"}),s)}}validate(t,n){return n>=1&&n<=7}set(t,n,r){return t=Fnr(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 Unr extends Di{priority=80;parse(t,n,r){switch(n){case"a":case"aa":case"aaa":return r.dayPeriod(t,{width:"abbreviated",context:"formatting"})||r.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaaa":return r.dayPeriod(t,{width:"narrow",context:"formatting"});default:return r.dayPeriod(t,{width:"wide",context:"formatting"})||r.dayPeriod(t,{width:"abbreviated",context:"formatting"})||r.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,n,r){return t.setHours(GSe(r),0,0,0),t}incompatibleTokens=["b","B","H","k","t","T"]}class Vnr extends Di{priority=80;parse(t,n,r){switch(n){case"b":case"bb":case"bbb":return r.dayPeriod(t,{width:"abbreviated",context:"formatting"})||r.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbbb":return r.dayPeriod(t,{width:"narrow",context:"formatting"});default:return r.dayPeriod(t,{width:"wide",context:"formatting"})||r.dayPeriod(t,{width:"abbreviated",context:"formatting"})||r.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,n,r){return t.setHours(GSe(r),0,0,0),t}incompatibleTokens=["a","B","H","k","t","T"]}class qnr extends Di{priority=80;parse(t,n,r){switch(n){case"B":case"BB":case"BBB":return r.dayPeriod(t,{width:"abbreviated",context:"formatting"})||r.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBBB":return r.dayPeriod(t,{width:"narrow",context:"formatting"});default:return r.dayPeriod(t,{width:"wide",context:"formatting"})||r.dayPeriod(t,{width:"abbreviated",context:"formatting"})||r.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,n,r){return t.setHours(GSe(r),0,0,0),t}incompatibleTokens=["a","b","t","T"]}class Qnr extends Di{priority=70;parse(t,n,r){switch(n){case"h":return za(wl.hour12h,t);case"ho":return r.ordinalNumber(t,{unit:"hour"});default:return dl(n.length,t)}}validate(t,n){return n>=1&&n<=12}set(t,n,r){const s=t.getHours()>=12;return s&&r<12?t.setHours(r+12,0,0,0):!s&&r===12?t.setHours(0,0,0,0):t.setHours(r,0,0,0),t}incompatibleTokens=["H","K","k","t","T"]}class Znr extends Di{priority=70;parse(t,n,r){switch(n){case"H":return za(wl.hour23h,t);case"Ho":return r.ordinalNumber(t,{unit:"hour"});default:return dl(n.length,t)}}validate(t,n){return n>=0&&n<=23}set(t,n,r){return t.setHours(r,0,0,0),t}incompatibleTokens=["a","b","h","K","k","t","T"]}class Wnr extends Di{priority=70;parse(t,n,r){switch(n){case"K":return za(wl.hour11h,t);case"Ko":return r.ordinalNumber(t,{unit:"hour"});default:return dl(n.length,t)}}validate(t,n){return n>=0&&n<=11}set(t,n,r){return t.getHours()>=12&&r<12?t.setHours(r+12,0,0,0):t.setHours(r,0,0,0),t}incompatibleTokens=["h","H","k","t","T"]}class Hnr extends Di{priority=70;parse(t,n,r){switch(n){case"k":return za(wl.hour24h,t);case"ko":return r.ordinalNumber(t,{unit:"hour"});default:return dl(n.length,t)}}validate(t,n){return n>=1&&n<=24}set(t,n,r){const s=r<=24?r%24:r;return t.setHours(s,0,0,0),t}incompatibleTokens=["a","b","h","H","K","t","T"]}class Gnr extends Di{priority=60;parse(t,n,r){switch(n){case"m":return za(wl.minute,t);case"mo":return r.ordinalNumber(t,{unit:"minute"});default:return dl(n.length,t)}}validate(t,n){return n>=0&&n<=59}set(t,n,r){return t.setMinutes(r,0,0),t}incompatibleTokens=["t","T"]}class Knr extends Di{priority=50;parse(t,n,r){switch(n){case"s":return za(wl.second,t);case"so":return r.ordinalNumber(t,{unit:"second"});default:return dl(n.length,t)}}validate(t,n){return n>=0&&n<=59}set(t,n,r){return t.setSeconds(r,0),t}incompatibleTokens=["t","T"]}class Ynr extends Di{priority=30;parse(t,n){const r=s=>Math.trunc(s*Math.pow(10,-n.length+3));return Sl(dl(n.length,t),r)}set(t,n,r){return t.setMilliseconds(r),t}incompatibleTokens=["t","T"]}class Xnr extends Di{priority=10;parse(t,n){switch(n){case"X":return $y(Py.basicOptionalMinutes,t);case"XX":return $y(Py.basic,t);case"XXXX":return $y(Py.basicOptionalSeconds,t);case"XXXXX":return $y(Py.extendedOptionalSeconds,t);default:return $y(Py.extended,t)}}set(t,n,r){return n.timestampIsSet?t:Do(t,t.getTime()-eA(t)-r)}incompatibleTokens=["t","T","x"]}class Jnr extends Di{priority=10;parse(t,n){switch(n){case"x":return $y(Py.basicOptionalMinutes,t);case"xx":return $y(Py.basic,t);case"xxxx":return $y(Py.basicOptionalSeconds,t);case"xxxxx":return $y(Py.extendedOptionalSeconds,t);default:return $y(Py.extended,t)}}set(t,n,r){return n.timestampIsSet?t:Do(t,t.getTime()-eA(t)-r)}incompatibleTokens=["t","T","X"]}class err extends Di{priority=40;parse(t){return vSt(t)}set(t,n,r){return[Do(t,r*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"}class trr extends Di{priority=20;parse(t){return vSt(t)}set(t,n,r){return[Do(t,r),{timestampIsSet:!0}]}incompatibleTokens="*"}const nrr={G:new bnr,y:new wnr,Y:new Snr,R:new knr,u:new Onr,Q:new jnr,q:new Cnr,M:new _nr,L:new Tnr,w:new Inr,I:new Anr,d:new Rnr,D:new Mnr,E:new Dnr,e:new Lnr,c:new znr,i:new Bnr,a:new Unr,b:new Vnr,B:new qnr,h:new Qnr,H:new Znr,K:new Wnr,k:new Hnr,m:new Gnr,s:new Knr,S:new Ynr,X:new Xnr,x:new Jnr,t:new err,T:new trr},rrr=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,srr=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,irr=/^'([^]*?)'?$/,orr=/''/g,arr=/\S/,lrr=/[a-zA-Z]/;function crr(e,t,n,r){const s=()=>Do(n,NaN),i=unr(),o=i.locale??QSe,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 xnr(r?.in,n)],f=t.match(srr).map(y=>{const x=y[0];if(x in Ipe){const b=Ipe[x];return b(y,o.formatLong)}return y}).join("").match(rrr),h=[];for(let y of f){pSt(y)&&Npe(y,t,e),hSt(y)&&Npe(y,t,e);const x=y[0],b=nrr[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(lrr))throw new RangeError("Format string contains an unescaped latin alphabet character `"+x+"`");if(y==="''"?y="'":x==="'"&&(y=urr(y)),e.indexOf(y)===0)e=e.slice(y.length);else return s()}}if(e.length>0&&arr.test(e))return s();const p=d.map(y=>y.priority).sort((y,x)=>x-y).filter((y,x,b)=>b.indexOf(y)===x).map(y=>d.filter(x=>x.priority===y).sort((x,b)=>b.subPriority-x.subPriority)).map(y=>y[0]);let m=Hs(n,r?.in);if(isNaN(+m))return s();const v={};for(const y of p){if(!y.validate(m,u))return s();const x=y.set(m,v,u);Array.isArray(x)?(m=x[0],Object.assign(v,x[1])):m=x}return m}function urr(e){return e.match(irr)[1].replace(orr,"'")}function YSe(e,t,n){const[r,s]=PP(n?.in,e,t);return r.getFullYear()===s.getFullYear()&&r.getMonth()===s.getMonth()}function drr(e,t,n){const[r,s]=PP(n?.in,e,t);return r.getFullYear()===s.getFullYear()}function Toe(e,t,n){return du(e,-t,n)}function Eoe(e,t,n){const r=Hs(e,n?.in),s=r.getFullYear(),i=r.getDate(),o=Do(e,0);o.setFullYear(s,t,15),o.setHours(0,0,0,0);const l=cnr(o);return r.setMonth(t,Math.min(i,l)),r}function iUe(e,t,n){const r=Hs(e,n?.in);return isNaN(+r)?Do(e,NaN):(r.setFullYear(t),r)}function bSt(e,t){const{getFieldState:n,formState:r}=Lr(),[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 frr=["title","name","label"];function oUe(e){return e.find(t=>typeof t=="string"&&t.trim().length>0)}function hrr(e){if(typeof e=="string")return e.trim();if(typeof e=="number"||typeof e=="boolean")return String(e);if(pD(e))return oUe(frr.map(t=>e[t]))??oUe(Object.values(e))}function prr({children:e,onRemove:t,index:n}){const r=g.useContext(oK),s=g.useContext(MSe),i=g.useContext(Z1t),{control:o}=Lr(),l=Zn({control:o,name:r}),c=hrr(l),u=g.useRef(null),{expanded:d,invalid:f,setExpanded:h}=bSt(r,!c),p=`Item ${n+1}${c?`: ${c}`:""}`;return a.jsxs(gc,{open:d,onOpenChange:h,className:"overflow-hidden rounded-lg border border-border bg-background motion-reduce:[&_[data-slot=collapsible-content]]:transition-none motion-reduce:[&_svg]:transition-none",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-1 pr-1",children:[a.jsxs(Hl,{ref:u,"aria-label":f?`${p}, Needs input`:p,className:"flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-lg px-3 text-left text-caption focus-visible:-outline-offset-1",children:[a.jsx(Ha,{direction:"right",className:"size-3.5 text-muted-foreground"}),a.jsxs("span",{className:"shrink-0 text-muted-foreground",children:["Item ",n+1]}),c&&a.jsx("span",{className:"truncate text-foreground",title:c,children:c}),f&&a.jsx(Y,{as:"span",variant:"meta",className:"ml-auto shrink-0 text-destructive-foreground",children:"Needs input"})]}),!s&&a.jsx(ue,{type:"button",variant:"ghost",size:"icon-md",className:"size-11","aria-label":`Remove item ${n+1}`,onClick:()=>{t(),i?.current?.focus()},children:a.jsx(Xo,{})})]}),a.jsxs(Gl,{keepMounted:!0,className:"border-t border-border p-3",children:[e,!s&&a.jsx("div",{className:"flex justify-end pt-2",children:a.jsx(ue,{type:"button",className:"min-h-11","aria-label":`Done editing item ${n+1}`,onClick:()=>{h(!1),u.current?.focus()},icon:a.jsx(ur,{}),children:"Done"})})]})]})}function mrr({label:e,children:t,onAddItem:n}){const r=g.useContext(MSe),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(c_n,{"aria-hidden":!0,className:"size-3.5"}),e," ",a.jsx("span",{className:"tabular-nums",children:s})]}),!r&&a.jsxs(ue,{ref:i,type:"button",variant:"ghost",size:"sm","aria-label":`Add ${e} item`,onClick:n,children:[a.jsx(ys,{}),"Add item"]})]}),s===0?a.jsx(Y,{as:"p",variant:"caption",tone:"muted",className:"py-2",children:"No items added"}):a.jsx(Z1t,{value:i,children:a.jsx("div",{className:"flex flex-col gap-2",children:t})})]})}function grr(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 wSt(e){return{checked(t){return e.indeterminate?{}:t?{"data-checked":""}:{"data-unchecked":""}},...kp}}const vrr=g.createContext(void 0);function yrr(){return g.useContext(vrr)}const SSt=g.createContext(void 0);function xrr(){const e=g.useContext(SSt);if(e===void 0)throw new Error(Nr(14));return e}const brr="data-parent",wrr=g.forwardRef(function(t,n){const{checked:r,className:s,defaultChecked:i=!1,"aria-labelledby":o,disabled:l=!1,form:c,id:u,indeterminate:d=!1,inputRef:f,name:h,onCheckedChange:p,parent:m=!1,readOnly:v=!1,render:y,required:x=!1,uncheckedValue:b,value:S,nativeButton:k=!1,style:j,...C}=t,{clearErrors:T}=Rv(),{disabled:_,name:N,setDirty:I,setFilled:A,setFocused:P,setTouched:L,state:F,validationMode:Q,validityData:q,validation:B}=Ru(),V=CG(),{labelId:H,controlId:D,registerControlId:K,getDescriptionProps:M}=yd(),$=yrr(),z=$?.allValues===void 0?void 0:$.parent,U=z!==void 0,G=_||V.disabled||$?.disabled||l,ne=N??h,X=S??ne,ee=Zi(),ie=Zi();let fe=u||D;U&&(m?fe=ie:X!==void 0?fe=`${z.id}-${X}`:fe||=ie);let te={};U&&(m?te=z.getParentProps():X!==void 0&&(te=z.getChildProps(X)));const{checked:se=r,indeterminate:re=d,onCheckedChange:le,...pe}=te,ve=$?.value,he=g.useRef(null),ke=ul(()=>Symbol()),Ee=g.useRef(!1),{getButtonProps:Ve,buttonRef:Ze}=gd({disabled:G,native:k}),Fe=$?.validation??B,[Ae,ze]=Xd({controlled:X!==void 0&&ve!==void 0&&!m?ve.includes(X):se,default:i,name:"Checkbox",state:"checked"}),je=U?!!se:Ae,Ce=U&&re||d;jt(()=>{K!==ti&&(Ee.current=!0,K(ke.current,fe))},[fe,K,ke]),g.useEffect(()=>{const Qe=ke.current;return()=>{!Ee.current||K===ti||(Ee.current=!1,K(Qe,void 0))}},[K,ke]),I_(he,ee,Ae,void 0,!$&&!G,h);const Ue=g.useRef(null),ae=Fe.registerInput,me=$?X:void 0,Ne=g.useCallback(Qe=>ae(Qe,{controlRef:he,value:me}),[ae,me]),Te=tf(f,Ue,m?void 0:Ne),ce=Kwe(o,H,Ue,!k,fe??void 0);jt(()=>{Ue.current&&(Ue.current.indeterminate=Ce,Ae&&A(!0))},[Ae,Ce,A]),ev(Ae,()=>{$||(T(ne),A(Ae),I(Ae!==q.initialValue),Fe.change(Ae))});const ye=kl({checked:Ae,disabled:G,form:c,name:m?void 0:ne,id:k?void 0:fe??void 0,required:x,ref:Te,style:ne?aP:bS,tabIndex:-1,type:"checkbox","aria-hidden":!0,onChange(Qe){if(Qe.nativeEvent.defaultPrevented)return;if(v){Qe.preventDefault();return}const tt=Qe.currentTarget.checked,st=Yt(Io,Qe.nativeEvent);if(p?.(tt,st),!st.isCanceled&&(le?.(tt,st),!st.isCanceled&&(ze(tt),X!==void 0&&$!==void 0&&!m&&!U))){const He=tt?[...$.value,X]:$.value.filter(Le=>Le!==X);$.setValue(He,st)}},onClick(Qe){Qe.stopPropagation()},onFocus(){he.current?.focus()}},S!==void 0?{value:($?Ae&&S:S)||""}:ai,M,Qe=>Fe.getValidationProps(G,Qe));g.useEffect(()=>{if(!z||X===void 0)return;const Qe=z.disabledStatesRef.current;return Qe.set(X,G),()=>{Qe.delete(X)}},[z,G,X]);const Se=g.useMemo(()=>({...F,checked:je,disabled:G,readOnly:v,required:x,indeterminate:Ce}),[F,je,G,v,x,Ce]),$e=wSt(Se),De=cn("span",t,{state:Se,ref:[Ze,he,n],props:[{id:k?fe??void 0:ee,role:"checkbox","aria-checked":Ce?"mixed":je,"aria-readonly":v||void 0,"aria-required":x||void 0,"aria-labelledby":ce,[brr]:m?"":void 0,onFocus(){G||P(!0)},onBlur(){const Qe=Ue.current;Qe&&(L(!0),P(!1),Q==="onBlur"&&Fe.commit($?ve:Qe.checked))},onKeyDown(Qe){if(Qe.key!=="Enter"||(Qe.preventBaseUIHandler(),Qe.defaultPrevented))return;const tt=Ue.current?.form??null,st=Qe.currentTarget,He=Qe.nativeEvent,Le=Qe.preventDefault,wt=He.preventDefault;let ge=!1;Qe.preventDefault=()=>{ge=!0,Le.call(Qe)},He.preventDefault=()=>{ge=!0,wt.call(He)},wt.call(He),bi(st).queueMicrotask(()=>{Qe.preventDefault=Le,He.preventDefault=wt,ge||grr(tt)?.click()})},onClick(Qe){if(v||G)return;Qe.preventDefault();const tt=Ue.current;tt&&Rj(tt,Qe)}},C,pe,Ve,M,Qe=>Fe.getValidationProps(G,Qe)],stateAttributesMapping:$e});return a.jsxs(SSt.Provider,{value:Se,children:[De,!Ae&&!$&&ne&&!m&&b!==void 0&&a.jsx("input",{type:"hidden",form:c,name:ne,value:b,disabled:G}),a.jsx("input",{...ye,suppressHydrationWarning:!0})]})}),Srr=g.forwardRef(function(t,n){const{render:r,className:s,style:i,keepMounted:o=!1,...l}=t,c=xrr(),u=c.checked||c.indeterminate,{mounted:d,transitionStatus:f,setMounted:h}=Sp(u),p=g.useRef(null),m={...c,transitionStatus:f};Cl({open:u,ref:p,onComplete(){u||h(!1)}});const y={...wSt(c),...oh},x=o||d,b=cn("span",t,{ref:[n,p],state:m,stateAttributesMapping:y,props:l});return x?b:null}),kSt=["flex size-4 shrink-0 cursor-pointer items-center justify-center","border border-border bg-fill-hover text-background",Mi.all,"hover:border-border-strong hover:bg-fill-active","active:scale-95 active:border-border-hover active:bg-fill-strong",eD,"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(" "),Gc=g.forwardRef(({className:e,checked:t,indeterminate:n,...r},s)=>{const i=t==="indeterminate";return a.jsx(wrr,{ref:s,checked:i?!1:t,indeterminate:n??i,"data-slot":"checkbox",render:a.jsx("span",{...$x(r)}),className:Z("peer rounded-[0.3125rem]",kSt,"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(Srr,{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(krr,{})})})});Gc.displayName="Checkbox";function krr(){return a.jsxs(a.Fragment,{children:[a.jsx(ur,{className:Z("stroke-3.25 size-3 scale-95 transition-[stroke-dashoffset,transform] duration-200 ease-out-custom","[stroke-dasharray:28] [stroke-dashoffset:28]","group-data-[checked]/checkbox-indicator:[stroke-dashoffset:0]","group-data-[checked]/checkbox-indicator:scale-100","group-data-[indeterminate]/checkbox-indicator:hidden")}),a.jsx(Zht,{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 Orr=({field:e,label:t,inputProps:n})=>a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx(Gc,{onCheckedChange:r=>{const s={target:{name:n.name,value:r}};n.onChange(s)},defaultChecked:e.default,disabled:n.disabled||n.readOnly}),a.jsx(ut,{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 jrr(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 OSt(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 VL(e){return e.mode==="multiple"}function qL(e){return e.mode==="range"}function lK(e){return e.mode==="single"}var Crr={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 _rr(e,t){return Ok(e,"LLLL y",t)}function Trr(e,t){return Ok(e,"d",t)}function Err(e,t){return Ok(e,"LLLL",t)}function Irr(e){return"".concat(e)}function Nrr(e,t){return Ok(e,"cccccc",t)}function Arr(e,t){return Ok(e,"yyyy",t)}var Prr=Object.freeze({__proto__:null,formatCaption:_rr,formatDay:Trr,formatMonthCaption:Err,formatWeekNumber:Irr,formatWeekdayName:Nrr,formatYearCaption:Arr}),$rr=function(e,t,n){return Ok(e,"do MMMM (EEEE)",n)},Rrr=function(){return"Month: "},Mrr=function(){return"Go to next month"},Drr=function(){return"Go to previous month"},Lrr=function(e,t){return Ok(e,"cccc",t)},zrr=function(e){return"Week n. ".concat(e)},Frr=function(){return"Year: "},Brr=Object.freeze({__proto__:null,labelDay:$rr,labelMonthDropdown:Rrr,labelNext:Mrr,labelPrevious:Drr,labelWeekNumber:zrr,labelWeekday:Lrr,labelYearDropdown:Frr});function Urr(){var e="buttons",t=Crr,n=QSe,r={},s={},i=1,o={},l=new Date;return{captionLayout:e,classNames:t,formatters:Prr,labels:Brr,locale:n,modifiersClassNames:r,modifiers:s,numberOfMonths:i,styles:o,today:l,mode:"default"}}function Vrr(e){var t=e.fromYear,n=e.toYear,r=e.fromMonth,s=e.toMonth,i=e.fromDate,o=e.toDate;return r?i=Yf(r):t&&(i=new Date(t,0,1)),s?o=VSe(s):n&&(o=new Date(n,11,31)),{fromDate:i?tA(i):void 0,toDate:o?tA(o):void 0}}var jSt=g.createContext(void 0);function qrr(e){var t,n=e.initialProps,r=Urr(),s=Vrr(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;(lK(n)||VL(n)||qL(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(jSt.Provider,{value:u,children:e.children})}function ea(){var e=g.useContext(jSt);if(!e)throw new Error("useDayPicker must be used within a DayPickerProvider.");return e}function CSt(e){var t=ea(),n=t.locale,r=t.classNames,s=t.styles,i=t.formatters.formatCaption;return a.jsx("div",{className:r.caption_label,style:s.caption_label,"aria-live":"polite",role:"presentation",id:e.id,children:i(e.displayMonth,{locale:n})})}function Qrr(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 _St(e){var t,n,r=e.onChange,s=e.value,i=e.children,o=e.caption,l=e.className,c=e.style,u=ea(),d=(n=(t=u.components)===null||t===void 0?void 0:t.IconDropdown)!==null&&n!==void 0?n:Qrr;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 Zrr(e){var t,n=ea(),r=n.fromDate,s=n.toDate,i=n.styles,o=n.locale,l=n.formatters.formatMonthCaption,c=n.classNames,u=n.components,d=n.labels.labelMonthDropdown;if(!r)return a.jsx(a.Fragment,{});if(!s)return a.jsx(a.Fragment,{});var f=[];if(drr(r,s))for(var h=Yf(r),p=r.getMonth();p<=s.getMonth();p++)f.push(Eoe(h,p));else for(var h=Yf(new Date),p=0;p<=11;p++)f.push(Eoe(h,p));var m=function(y){var x=Number(y.target.value),b=Eoe(Yf(e.displayMonth),x);e.onChange(b)},v=(t=u?.Dropdown)!==null&&t!==void 0?t:_St;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 Wrr(e){var t,n=e.displayMonth,r=ea(),s=r.fromDate,i=r.toDate,o=r.locale,l=r.styles,c=r.classNames,u=r.components,d=r.formatters.formatYearCaption,f=r.labels.labelYearDropdown,h=[];if(!s)return a.jsx(a.Fragment,{});if(!i)return a.jsx(a.Fragment,{});for(var p=s.getFullYear(),m=i.getFullYear(),v=p;v<=m;v++)h.push(iUe(uSt(new Date),v));var y=function(b){var S=iUe(Yf(n),Number(b.target.value));e.onChange(S)},x=(t=u?.Dropdown)!==null&&t!==void 0?t:_St;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 Hrr(e,t){var n=g.useState(e),r=n[0],s=n[1],i=t===void 0?r:t;return[i,s]}function Grr(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&&k5(i,s)<0){var u=-1*(c-1);s=Sv(i,u)}return o&&k5(s,o)<0&&(s=o),Yf(s)}function Krr(){var e=ea(),t=Grr(e),n=Hrr(t,e.month),r=n[0],s=n[1],i=function(o){var l;if(!e.disableNavigation){var c=Yf(o);s(c),(l=e.onMonthChange)===null||l===void 0||l.call(e,c)}};return[r,i]}function Yrr(e,t){for(var n=t.reverseMonths,r=t.numberOfMonths,s=Yf(e),i=Yf(Sv(s,r)),o=k5(i,s),l=[],c=0;c<o;c++){var u=Sv(s,c);l.push(u)}return n&&(l=l.reverse()),l}function Xrr(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=Yf(e);if(!n)return Sv(l,o);var c=k5(n,e);if(!(c<i))return Sv(l,o)}}function Jrr(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=Yf(e);if(!n)return Sv(l,-o);var c=k5(l,n);if(!(c<=0))return Sv(l,-o)}}var TSt=g.createContext(void 0);function esr(e){var t=ea(),n=Krr(),r=n[0],s=n[1],i=Yrr(r,t),o=Xrr(r,t),l=Jrr(r,t),c=function(f){return i.some(function(h){return YSe(f,h)})},u=function(f,h){c(f)||(h&&mSt(f,h)?s(Sv(f,1+t.numberOfMonths*-1)):s(f))},d={currentMonth:r,displayMonths:i,goToMonth:s,goToDate:u,previousMonth:l,nextMonth:o,isDateDisplayed:c};return a.jsx(TSt.Provider,{value:d,children:e.children})}function QL(){var e=g.useContext(TSt);if(!e)throw new Error("useNavigation must be used within a NavigationProvider");return e}function aUe(e){var t,n=ea(),r=n.classNames,s=n.styles,i=n.components,o=QL().goToMonth,l=function(d){o(Sv(d,e.displayIndex?-e.displayIndex:0))},c=(t=i?.CaptionLabel)!==null&&t!==void 0?t:CSt,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(Zrr,{onChange:l,displayMonth:e.displayMonth}),a.jsx(Wrr,{onChange:l,displayMonth:e.displayMonth})]})}function tsr(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 nsr(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 mQ=g.forwardRef(function(e,t){var n=ea(),r=n.classNames,s=n.styles,i=[r.button_reset,r.button];e.className&&i.push(e.className);var o=i.join(" "),l=Ar(Ar({},s.button_reset),s.button);return e.style&&Object.assign(l,e.style),a.jsx("button",Ar({},e,{ref:t,type:"button",className:o,style:l}))});function rsr(e){var t,n,r=ea(),s=r.dir,i=r.locale,o=r.classNames,l=r.styles,c=r.labels,u=c.labelPrevious,d=c.labelNext,f=r.components;if(!e.nextMonth&&!e.previousMonth)return a.jsx(a.Fragment,{});var h=u(e.previousMonth,{locale:i}),p=[o.nav_button,o.nav_button_previous].join(" "),m=d(e.nextMonth,{locale:i}),v=[o.nav_button,o.nav_button_next].join(" "),y=(t=f?.IconRight)!==null&&t!==void 0?t:nsr,x=(n=f?.IconLeft)!==null&&n!==void 0?n:tsr;return a.jsxs("div",{className:o.nav,style:l.nav,children:[!e.hidePrevious&&a.jsx(mQ,{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(mQ,{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 lUe(e){var t=ea().numberOfMonths,n=QL(),r=n.previousMonth,s=n.nextMonth,i=n.goToMonth,o=n.displayMonths,l=o.findIndex(function(m){return YSe(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(rsr,{displayMonth:e.displayMonth,hideNext:d,hidePrevious:f,nextMonth:s,previousMonth:r,onPreviousClick:h,onNextClick:p})}function ssr(e){var t,n=ea(),r=n.classNames,s=n.disableNavigation,i=n.styles,o=n.captionLayout,l=n.components,c=(t=l?.CaptionLabel)!==null&&t!==void 0?t:CSt,u;return s?u=a.jsx(c,{id:e.id,displayMonth:e.displayMonth}):o==="dropdown"?u=a.jsx(aUe,{displayMonth:e.displayMonth,id:e.id}):o==="dropdown-buttons"?u=a.jsxs(a.Fragment,{children:[a.jsx(aUe,{displayMonth:e.displayMonth,displayIndex:e.displayIndex,id:e.id}),a.jsx(lUe,{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(lUe,{displayMonth:e.displayMonth,id:e.id})]}),a.jsx("div",{className:r.caption,style:i.caption,children:u})}function isr(e){var t=ea(),n=t.footer,r=t.styles,s=t.classNames.tfoot;return n?a.jsx("tfoot",{className:s,style:r.tfoot,children:a.jsx("tr",{children:a.jsx("td",{colSpan:8,children:n})})}):a.jsx(a.Fragment,{})}function osr(e,t,n){for(var r=n?A0(new Date):gp(new Date,{locale:e,weekStartsOn:t}),s=[],i=0;i<7;i++){var o=du(r,i);s.push(o)}return s}function asr(){var e=ea(),t=e.classNames,n=e.styles,r=e.showWeekNumber,s=e.locale,i=e.weekStartsOn,o=e.ISOWeek,l=e.formatters.formatWeekdayName,c=e.labels.labelWeekday,u=osr(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 lsr(){var e,t=ea(),n=t.classNames,r=t.styles,s=t.components,i=(e=s?.HeadRow)!==null&&e!==void 0?e:asr;return a.jsx("thead",{style:r.head,className:n.head,children:a.jsx(i,{})})}function csr(e){var t=ea(),n=t.locale,r=t.formatters.formatDay;return a.jsx(a.Fragment,{children:r(e.date,{locale:n})})}var XSe=g.createContext(void 0);function usr(e){if(!VL(e.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return a.jsx(XSe.Provider,{value:t,children:e.children})}return a.jsx(dsr,{initialProps:e.initialProps,children:e.children})}function dsr(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?OSt([],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(XSe.Provider,{value:c,children:n})}function JSe(){var e=g.useContext(XSe);if(!e)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return e}function fsr(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:Ape(r,e)?{from:e,to:s}:{from:r,to:e}:s?Ape(e,s)?{from:s,to:e}:{from:e,to:s}:r?mSt(e,r)?{from:e,to:r}:{from:r,to:e}:{from:e,to:void 0}}var eke=g.createContext(void 0);function hsr(e){if(!qL(e.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return a.jsx(eke.Provider,{value:t,children:e.children})}return a.jsx(psr,{initialProps:e.initialProps,children:e.children})}function psr(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=fsr(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:Toe(i,l-1),before:du(i,l-1)}),i&&o&&d.disabled.push({after:i,before:du(i,l-1)}),!i&&o&&d.disabled.push({after:Toe(o,l-1),before:du(o,l-1)})),c){if(i&&!o&&(d.disabled.push({before:du(i,-c+1)}),d.disabled.push({after:du(i,c-1)})),i&&o){var f=qy(o,i)+1,h=c-f;d.disabled.push({before:Toe(i,h)}),d.disabled.push({after:du(o,h)})}!i&&o&&(d.disabled.push({before:du(o,-c+1)}),d.disabled.push({after:du(o,c-1)}))}return a.jsx(eke.Provider,{value:{selected:r,onDayClick:u,modifiers:d},children:n})}function tke(){var e=g.useContext(eke);if(!e)throw new Error("useSelectRange must be used within a SelectRangeProvider");return e}function HB(e){return Array.isArray(e)?OSt([],e):e!==void 0?[e]:[]}function msr(e){var t={};return Object.entries(e).forEach(function(n){var r=n[0],s=n[1];t[r]=HB(s)}),t}var kv;(function(e){e.Outside="outside",e.Disabled="disabled",e.Selected="selected",e.Hidden="hidden",e.Today="today",e.RangeStart="range_start",e.RangeEnd="range_end",e.RangeMiddle="range_middle"})(kv||(kv={}));var gsr=kv.Selected,yb=kv.Disabled,vsr=kv.Hidden,ysr=kv.Today,Ioe=kv.RangeEnd,Noe=kv.RangeMiddle,Aoe=kv.RangeStart,xsr=kv.Outside;function bsr(e,t,n){var r,s=(r={},r[gsr]=HB(e.selected),r[yb]=HB(e.disabled),r[vsr]=HB(e.hidden),r[ysr]=[e.today],r[Ioe]=[],r[Noe]=[],r[Aoe]=[],r[xsr]=[],r);return e.fromDate&&s[yb].push({before:e.fromDate}),e.toDate&&s[yb].push({after:e.toDate}),VL(e)?s[yb]=s[yb].concat(t.modifiers[yb]):qL(e)&&(s[yb]=s[yb].concat(n.modifiers[yb]),s[Aoe]=n.modifiers[Aoe],s[Noe]=n.modifiers[Noe],s[Ioe]=n.modifiers[Ioe]),s}var ESt=g.createContext(void 0);function wsr(e){var t=ea(),n=JSe(),r=tke(),s=bsr(t,n,r),i=msr(t.modifiers),o=Ar(Ar({},s),i);return a.jsx(ESt.Provider,{value:o,children:e.children})}function ISt(){var e=g.useContext(ESt);if(!e)throw new Error("useModifiers must be used within a ModifiersProvider");return e}function Ssr(e){return!!(e&&typeof e=="object"&&"before"in e&&"after"in e)}function ksr(e){return!!(e&&typeof e=="object"&&"from"in e)}function Osr(e){return!!(e&&typeof e=="object"&&"after"in e)}function jsr(e){return!!(e&&typeof e=="object"&&"before"in e)}function Csr(e){return!!(e&&typeof e=="object"&&"dayOfWeek"in e)}function _sr(e,t){var n,r=t.from,s=t.to;if(r&&s){var i=qy(s,r)<0;i&&(n=[s,r],r=n[0],s=n[1]);var o=qy(e,r)>=0&&qy(s,e)>=0;return o}return s?Qf(s,e):r?Qf(r,e):!1}function Tsr(e){return BSe(e)}function Esr(e){return Array.isArray(e)&&e.every(BSe)}function Isr(e,t){return t.some(function(n){if(typeof n=="boolean")return n;if(Tsr(n))return Qf(e,n);if(Esr(n))return n.includes(e);if(ksr(n))return _sr(e,n);if(Csr(n))return n.dayOfWeek.includes(e.getDay());if(Ssr(n)){var r=qy(n.before,e),s=qy(n.after,e),i=r>0,o=s<0,l=Ape(n.before,n.after);return l?o&&i:i||o}return Osr(n)?qy(e,n.after)>0:jsr(n)?qy(n.before,e)>0:typeof n=="function"?n(e):!1})}function nke(e,t,n){var r=Object.keys(t).reduce(function(i,o){var l=t[o];return Isr(e,l)&&i.push(o),i},[]),s={};return r.forEach(function(i){return s[i]=!0}),n&&!YSe(e,n)&&(s.outside=!0),s}function Nsr(e,t){for(var n=Yf(e[0]),r=VSe(e[e.length-1]),s,i,o=n;o<=r;){var l=nke(o,t),c=!l.disabled&&!l.hidden;if(!c){o=du(o,1);continue}if(l.selected)return o;l.today&&!i&&(i=o),s||(s=o),o=du(o,1)}return i||s}var Asr=365;function NSt(e,t){var n=t.moveBy,r=t.direction,s=t.context,i=t.modifiers,o=t.retry,l=o===void 0?{count:0,lastFocused:e}:o,c=s.weekStartsOn,u=s.fromDate,d=s.toDate,f=s.locale,h={day:du,week:Epe,month:Sv,year:ptr,startOfWeek:function(y){return s.ISOWeek?A0(y):gp(y,{locale:f,weekStartsOn:c})},endOfWeek:function(y){return s.ISOWeek?dSt(y):qSe(y,{locale:f,weekStartsOn:c})}},p=h[n](e,r==="after"?1:-1);r==="before"&&u?p=mtr([u,p]):r==="after"&&d&&(p=gtr([d,p]));var m=!0;if(i){var v=nke(p,i);m=!v.disabled&&!v.hidden}return m?p:l.count>Asr?l.lastFocused:NSt(p,{moveBy:n,direction:r,context:s,modifiers:i,retry:Ar(Ar({},l),{count:l.count+1})})}var ASt=g.createContext(void 0);function Psr(e){var t=QL(),n=ISt(),r=g.useState(),s=r[0],i=r[1],o=g.useState(),l=o[0],c=o[1],u=Nsr(t.displayMonths,n),d=s??(l&&t.isDateDisplayed(l))?l:u,f=function(){c(s),i(void 0)},h=function(y){i(y)},p=ea(),m=function(y,x){if(s){var b=NSt(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(ASt.Provider,{value:v,children:e.children})}function rke(){var e=g.useContext(ASt);if(!e)throw new Error("useFocusContext must be used within a FocusProvider");return e}function $sr(e,t){var n=ISt(),r=nke(e,n,t);return r}var ske=g.createContext(void 0);function Rsr(e){if(!lK(e.initialProps)){var t={selected:void 0};return a.jsx(ske.Provider,{value:t,children:e.children})}return a.jsx(Msr,{initialProps:e.initialProps,children:e.children})}function Msr(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(ske.Provider,{value:s,children:n})}function PSt(){var e=g.useContext(ske);if(!e)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return e}function Dsr(e,t){var n=ea(),r=PSt(),s=JSe(),i=tke(),o=rke(),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,D,K;lK(n)?(V=r.onDayClick)===null||V===void 0||V.call(r,e,t,B):VL(n)?(H=s.onDayClick)===null||H===void 0||H.call(s,e,t,B):qL(n)?(D=i.onDayClick)===null||D===void 0||D.call(i,e,t,B):(K=n.onDayClick)===null||K===void 0||K.call(n,e,t,B)},k=function(B){var V;h(e),(V=n.onDayFocus)===null||V===void 0||V.call(n,e,t,B)},j=function(B){var V;f(),(V=n.onDayBlur)===null||V===void 0||V.call(n,e,t,B)},C=function(B){var V;(V=n.onDayMouseEnter)===null||V===void 0||V.call(n,e,t,B)},T=function(B){var V;(V=n.onDayMouseLeave)===null||V===void 0||V.call(n,e,t,B)},_=function(B){var V;(V=n.onDayPointerEnter)===null||V===void 0||V.call(n,e,t,B)},N=function(B){var V;(V=n.onDayPointerLeave)===null||V===void 0||V.call(n,e,t,B)},I=function(B){var V;(V=n.onDayTouchCancel)===null||V===void 0||V.call(n,e,t,B)},A=function(B){var V;(V=n.onDayTouchEnd)===null||V===void 0||V.call(n,e,t,B)},P=function(B){var V;(V=n.onDayTouchMove)===null||V===void 0||V.call(n,e,t,B)},L=function(B){var V;(V=n.onDayTouchStart)===null||V===void 0||V.call(n,e,t,B)},F=function(B){var V;(V=n.onDayKeyUp)===null||V===void 0||V.call(n,e,t,B)},Q=function(B){var V;switch(B.key){case"ArrowLeft":B.preventDefault(),B.stopPropagation(),n.dir==="rtl"?l():c();break;case"ArrowRight":B.preventDefault(),B.stopPropagation(),n.dir==="rtl"?c():l();break;case"ArrowDown":B.preventDefault(),B.stopPropagation(),u();break;case"ArrowUp":B.preventDefault(),B.stopPropagation(),d();break;case"PageUp":B.preventDefault(),B.stopPropagation(),B.shiftKey?v():p();break;case"PageDown":B.preventDefault(),B.stopPropagation(),B.shiftKey?y():m();break;case"Home":B.preventDefault(),B.stopPropagation(),x();break;case"End":B.preventDefault(),B.stopPropagation(),b();break}(V=n.onDayKeyDown)===null||V===void 0||V.call(n,e,t,B)},q={onClick:S,onFocus:k,onBlur:j,onKeyDown:Q,onKeyUp:F,onMouseEnter:C,onMouseLeave:T,onPointerEnter:_,onPointerLeave:N,onTouchCancel:I,onTouchEnd:A,onTouchMove:P,onTouchStart:L};return q}function Lsr(){var e=ea(),t=PSt(),n=JSe(),r=tke(),s=lK(e)?t.selected:VL(e)?n.selected:qL(e)?r.selected:void 0;return s}function zsr(e){return Object.values(kv).includes(e)}function Fsr(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(zsr(r)){var i=e.classNames["day_".concat(r)];i&&n.push(i)}}),n}function Bsr(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 Usr(e,t,n){var r,s,i,o=ea(),l=rke(),c=$sr(e,t),u=Dsr(e,c),d=Lsr(),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=Fsr(o,c).join(" "),p=Bsr(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:csr,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 Vsr(e){var t=g.useRef(null),n=Usr(e.date,e.displayMonth,t);return n.isHidden?a.jsx("div",{role:"gridcell"}):n.isButton?a.jsx(mQ,Ar({name:"day",ref:t},n.buttonProps)):a.jsx("div",Ar({},n.divProps))}function qsr(e){var t=e.number,n=e.dates,r=ea(),s=r.onWeekNumberClick,i=r.styles,o=r.classNames,l=r.locale,c=r.labels.labelWeekNumber,u=r.formatters.formatWeekNumber,d=u(Number(t),{locale:l});if(!s)return a.jsx("span",{className:o.weeknumber,style:i.weeknumber,children:d});var f=c(Number(t),{locale:l}),h=function(p){s(t,n,p)};return a.jsx(mQ,{name:"week-number","aria-label":f,className:o.weeknumber,style:i.weeknumber,onClick:h,children:d})}function Qsr(e){var t,n,r=ea(),s=r.styles,i=r.classNames,o=r.showWeekNumber,l=r.components,c=(t=l?.Day)!==null&&t!==void 0?t:Vsr,u=(n=l?.WeekNumber)!==null&&n!==void 0?n:qsr,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})},fnr(f))})]})}function cUe(e,t,n){for(var r=n?.ISOWeek?dSt(t):qSe(t,n),s=n?.ISOWeek?A0(e):gp(e,n),i=qy(r,s),o=[],l=0;l<=i;l++)o.push(du(s,l));var c=o.reduce(function(u,d){var f=n?.ISOWeek?ZSe(d):HSe(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 Zsr(e,t){var n=cUe(Yf(e),VSe(e),t);if(t?.useFixedWeeks){var r=pnr(e,t);if(r<6){var s=n[n.length-1],i=s.dates[s.dates.length-1],o=Epe(i,6-r),l=cUe(Epe(i,1),o,t);n.push.apply(n,l)}}return n}function Wsr(e){var t,n,r,s=ea(),i=s.locale,o=s.classNames,l=s.styles,c=s.hideHead,u=s.fixedWeeks,d=s.components,f=s.weekStartsOn,h=s.firstWeekContainsDate,p=s.ISOWeek,m=Zsr(e.displayMonth,{useFixedWeeks:!!u,ISOWeek:p,locale:i,weekStartsOn:f,firstWeekContainsDate:h}),v=(t=d?.Head)!==null&&t!==void 0?t:lsr,y=(n=d?.Row)!==null&&n!==void 0?n:Qsr,x=(r=d?.Footer)!==null&&r!==void 0?r:isr;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 Hsr(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Gsr=Hsr()?g.useLayoutEffect:g.useEffect,Poe=!1,Ksr=0;function uUe(){return"react-day-picker-".concat(++Ksr)}function Ysr(e){var t,n=e??(Poe?uUe():null),r=g.useState(n),s=r[0],i=r[1];return Gsr(function(){s===null&&i(uUe())},[]),g.useEffect(function(){Poe===!1&&(Poe=!0)},[]),(t=e??s)!==null&&t!==void 0?t:void 0}function Xsr(e){var t,n,r=ea(),s=r.dir,i=r.classNames,o=r.styles,l=r.components,c=QL().displayMonths,u=Ysr(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:ssr;return a.jsxs("div",{className:f.join(" "),style:h,children:[a.jsx(y,{id:u,displayMonth:e.displayMonth,displayIndex:e.displayIndex}),a.jsx(Wsr,{id:d,"aria-labelledby":u,displayMonth:e.displayMonth})]},e.displayIndex)}function Jsr(e){var t=ea(),n=t.classNames,r=t.styles;return a.jsx("div",{className:n.months,style:r.months,children:e.children})}function eir(e){var t,n,r=e.initialProps,s=ea(),i=rke(),o=QL(),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:Jsr;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(Xsr,{displayIndex:v,displayMonth:m},v)})})}))}function tir(e){var t=e.children,n=jrr(e,["children"]);return a.jsx(qrr,{initialProps:n,children:a.jsx(esr,{children:a.jsx(Rsr,{initialProps:n,children:a.jsx(usr,{initialProps:n,children:a.jsx(hsr,{initialProps:n,children:a.jsx(wsr,{children:a.jsx(Psr,{children:t})})})})})})})}function nir(e){return a.jsx(tir,Ar({},e,{children:a.jsx(eir,{initialProps:e})}))}function Ppe({className:e,classNames:t,showOutsideDays:n=!0,...r}){return a.jsx(nir,{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(Ln,"flex size-7 items-center justify-center rounded-md bg-transparent p-0 hover:bg-fill-subtle"),nav_button_next:Z(Ln,"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 $St=g.createContext(void 0);function ZL(e){const t=g.useContext($St);if(t===void 0&&!e)throw new Error(Nr(47));return t}const rir={...rL,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 sir extends k_{constructor(t,n,r){const s=new O_;super(iir(t,s,n,r),oir(s),rir)}setOpen=(t,n)=>{const r=n.reason===Ra,s=n.reason===vv&&n.event.detail===0,i=!t&&(n.reason===b_||n.reason==null),o=R0e(n),l=this.select("activeTriggerId");if(!t&&n.reason===b0e&&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};DH(d,t,n.trigger,o()),this.update(d)};r?(this.set("stickIfOpen",!0),this.context.stickIfOpenTimeout.start(Sft,()=>{this.set("stickIfOpen",!1)}),So.flushSync(c)):c();let u;s?u="click":i?u="dismiss":n.reason===O0&&(u="focus"),this.set("instantType",u)}}function iir(e,t,n,r=!1){const s={...nL(),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=LH(t,n,r),s}function oir(e){return{popupRef:g.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:g.createRef(),beforeContentFocusGuardRef:g.createRef(),stickIfOpenTimeout:new Lm,triggerElements:e}}function dUe({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=lir(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),Zft(d,f),J3(d);const{forceUnmount:m}=eL(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(H3))}),[m,d]);const v=f||h;return a.jsxs($St.Provider,{value:d,children:[l&&a.jsx(Y3,{handle:l,store:d}),v&&a.jsx(cir,{store:d,modal:o}),typeof t=="function"?t({payload:p}):t]})}function air(e){return ZL(!0)?a.jsx(dUe,{props:e}):a.jsx(N0e,{children:a.jsx(dUe,{props:e})})}function lir(e,t){const n=MH((r,s)=>new sir(t,r,s));return g.useEffect(()=>n.context.stickIfOpenTimeout.disposeEffect(),[n]),n}function cir({store:e,modal:t}){const n=e.useState("floatingRootContext"),r=S_(n,{outsidePressEvent:{mouse:t==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}}),s=r.reference,i=r.floating;return tL(e,{activeTriggerProps:s,inactiveTriggerProps:s,popupProps:i}),null}const uir=300,dir=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=uir,closeDelay:h=0,id:p,...m}=t,v=ZL(!0),x=sL(c)??v;if(!x)throw new Error(Nr(74));const b=Zi(p),S=x.useState("isTriggerActive",b),k=x.useState("floatingRootContext"),j=x.useState("isOpenedByTrigger",b),C=x.useState("triggerPopupId",b),T=g.useRef(null),{registerTrigger:_,isMountedByThisTrigger:N}=X3(b,T,x,{payload:u,disabled:o,openOnHover:d,closeDelay:h}),I=x.useState("openChangeReason"),A=x.useState("stickIfOpen"),P=x.useState("openMethod"),L=x.useState("focusManagerModal"),F=iL(k,{enabled:!o&&d&&(P!=="touch"||I!==vv),mouseOnly:!0,move:!1,handleClose:oL(),restMs:f,delay:{close:h},triggerElementRef:T,isActiveTrigger:S,isClosing:()=>x.select("transitionStatus")==="ending"}),Q=w_(k,{stickIfOpen:A}),q=gSe(()=>x.select("open"),ne=>{x.set("openMethod",ne)}),B=x.useState("triggerProps",N),{getButtonProps:V,buttonRef:H}=gd({disabled:o,native:l}),D={open(ne){return ne&&I===vv?_N.open(ne):cP.open(ne)}},{preFocusGuardRef:K,handlePreFocusGuardFocus:M,handleFocusTargetFocus:$}=qwt(x,T),U=cn("button",t,{state:{disabled:o,open:j},ref:[H,n,_,T],props:[Q.reference,F,B,q,{[_0e]:"",id:b,"aria-haspopup":"dialog","aria-expanded":j,"aria-controls":C},m,V],stateAttributesMapping:D}),G=a.jsx(g.Fragment,{children:U},b);return N&&!L?a.jsxs(g.Fragment,{children:[a.jsx(wS,{ref:K,onFocus:M}),G,a.jsx(wS,{ref:x.context.triggerFocusTargetRef,onFocus:$})]}):G}),RSt=g.createContext(void 0);function fir(){const e=g.useContext(RSt);if(e===void 0)throw new Error(Nr(45));return e}const hir=g.forwardRef(function(t,n){const{keepMounted:r=!1,...s}=t;return ZL().useState("mounted")||r?a.jsx(RSt.Provider,{value:r,children:a.jsx(K3,{ref:n,...s})}):null}),MSt=g.createContext(void 0);function pir(){const e=g.useContext(MSt);if(!e)throw new Error(Nr(46));return e}const mir=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=IH,...b}=t,S=ZL(),k=fir(),j=NH(),C=S.useState("floatingRootContext"),T=S.useState("mounted"),_=S.useState("open"),N=S.useState("openChangeReason"),I=S.useState("activeTriggerElement"),A=S.useState("modal"),P=S.useState("openMethod"),L=S.useState("positionerElement"),F=S.useState("instantType"),Q=S.useState("transitionStatus"),q=S.useState("adaptiveOrigin"),B=g.useRef(null),V=RH(L),H=uP({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}),D=C.useState("domReferenceElement");jt(()=>{const U=D,G=B.current;if(U&&(B.current=U),G&&U&&U!==G){S.set("instantType",void 0);const ne=new AbortController;return V(()=>{S.set("instantType","trigger-change")},ne.signal),()=>{ne.abort()}}},[D,V,S]);const K=A===!0&&N!==Ra;KG(_&&K,P==="touch",L,I);const M=S.useStateSetter("positionerElement"),$={open:_,side:H.side,align:H.align,anchorHidden:H.anchorHidden,instant:F},z=dP(t,$,{styles:H.positionerStyles,transitionStatus:Q,props:b,refs:[n,M],hidden:!T,inert:!_});return a.jsxs(MSt.Provider,{value:H,children:[T&&K&&a.jsx(LL,{inert:fP(!_),cutout:I}),a.jsx(I0e,{id:j,children:z})]})}),gir=g.createContext(void 0);function vir(){const[e,t]=g.useState(0),n=ft(()=>(t(s=>s+1),()=>{t(s=>Math.max(0,s-1))}));return{context:g.useMemo(()=>({register:n}),[n]),hasClosePart:e>0}}const yir=g.forwardRef(function(t,n){const{render:r,className:s,style:i,initialFocus:o,finalFocus:l,...c}=t,u=ZL(),d=pir(),f=mSe()!=null,{context:h,hasClosePart:p}=vir(),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"),A=u.useState("disabled"),P=u.useState("openOnHover"),L=u.useState("closeDelay");Cl({open:m,ref:u.context.popupRef,onComplete(){m&&u.context.onOpenChangeComplete?.(!0)}}),zH(N,{enabled:P&&!A,closeDelay:L});const F=o===void 0?Vft(u.context.popupRef):o,Q=j!==!1&&p;u.useSyncedValue("focusManagerModal",Q);const q=u.useStateSetter("popupElement"),B={open:m,side:d.side,align:d.align,instant:y,transitionStatus:x},V=cn("div",t,{state:B,ref:[n,u.context.popupRef,q],props:[b,{id:I,role:"dialog",...gk,"aria-labelledby":S,"aria-describedby":k,onKeyDown(H){f&&kk.has(H.key)&&H.stopPropagation()}},__(x),c],stateAttributesMapping:C_});return a.jsx(lP,{context:N,openInteractionType:v,modal:Q,disabled:!C||T===Ra,initialFocus:F,returnFocus:l,restoreFocus:"popup",previousFocusableElement:ni(_)?_:void 0,nextFocusableElement:u.context.triggerFocusTargetRef,beforeContentFocusGuardRef:u.context.beforeContentFocusGuardRef,children:a.jsx(gir.Provider,{value:h,children:V})})}),jp=air,sf=g.forwardRef(({className:e,asChild:t,render:n,children:r,variant:s,size:i,tooltip:o,...l},c)=>{const u=r1t({render:n,asChild:t,children:r,variant:s,size:i,tooltip:o,className:e});return a.jsx(dir,{ref:c,className:u.className,render:u.render,...l,children:u.children})});sf.displayName="PopoverTrigger";const lh=g.forwardRef(({className:e,container:t,align:n="center",alignOffset:r=0,side:s="bottom",sideOffset:i=4,anchor:o,positionMethod:l=Av,collisionBoundary:c,collisionPadding:u,sticky:d,arrowPadding:f,disableAnchorTracking:h,collisionAvoidance:p,...m},v)=>{const y=typeof e=="string"?e:void 0,x=J0(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(hir,{container:x,children:a.jsx(mir,{className:"z-50 outline-none",...b,children:a.jsx(yir,{ref:v,"data-slot":"popover-content",className:Z("z-50 w-72 origin-[var(--transform-origin)] rounded-xl text-foreground focus-visible:outline-hidden",nh,"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})})})});lh.displayName="PopoverContent";const xir=({inputProps:e,field:t})=>{const{key:n,...r}=e,[s,i]=g.useState(void 0),[o,l]=g.useState(!1),c=Ivt();g.useEffect(()=>{if(t.default){const f=new Date(t.default);USe(f)&&i(f)}},[t]);const u=f=>{i(f),f&&r.onChange({target:{value:f.toISOString(),name:e.name}}),l(!1)},d=()=>{i(void 0),r.onChange({target:{value:"",name:e.name}}),l(!1)};return a.jsxs(jp,{open:o,onOpenChange:l,children:[a.jsx(sf,{asChild:!0,children:a.jsx(ue,{...c,variant:"default",size:"lg",className:Z("w-full",Q0e),icon:a.jsx(C4,{}),children:s?a.jsx("span",{className:"text-foreground",children:Ok(s,"PPP")}):a.jsx("span",{className:"text-muted-foreground",children:"Pick a date"})})}),a.jsxs(lh,{className:"w-auto bg-muted p-0",align:"start",children:[a.jsx(Ppe,{mode:"single",selected:s,onSelect:u,month:s,onMonthChange:i}),s&&a.jsx("div",{className:"p-3 pt-0",children:a.jsx(ue,{icon:a.jsx(zn,{}),variant:"default",size:"lg",className:"w-full",onClick:d,children:"Clear"})})]})]})},bir=({field:e,path:t})=>{const{uiComponents:n}=zSe(),{control:r}=Lr(),{fields:s,append:i,remove:o}=mer({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:w5(e),field:e,onAddItem:()=>i(c),children:s.map((d,f)=>a.jsx(oK,{value:[...t,f.toString()].join("."),children:a.jsx(n.ArrayElementWrapper,{onRemove:()=>o(f),index:f,children:a.jsx(Qj,{field:u,path:[...t,f.toString()]})})},d.id))}):a.jsx(n.ErrorMessage,{error:`[AutoForm] Unable to determine array element schema for "${w5(e)}"`})},wir=({field:e,path:t})=>{const{uiComponents:n}=zSe();return a.jsx(oK,{value:t.join("."),children:a.jsx(n.ObjectWrapper,{label:w5(e),field:e,children:Object.entries(e.schema??[]).map(([r,s])=>a.jsx(Qj,{field:s,path:[...t,s.key]},`${t.join(".")}.${s.key}`))})})},Qj=({field:e,path:t})=>{const{formComponents:n,uiComponents:r}=zSe(),{register:s,formState:{errors:i,defaultValues:o},getValues:l,control:c}=Lr(),u=t.join("."),d=JBe(i,t)?.message,f=Zn({control:c,name:u}),h=f===void 0?l(u):f,p=g.useMemo(()=>{if(!o)return e.default;const x=JBe(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=bir:e.type==="object"?v=wir: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:w5(e),error:d,id:u,field:y,children:a.jsx(v,{label:w5(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)})},Sir=({field:e,path:t})=>{const{watch:n}=Lr(),r=t.join("."),s=n(r),o=(e.schema?.flatMap(h=>h.schema||[])||[])?.filter(h=>h.fieldConfig?.customData?.isLiteral)||[],l=o[0];if(!l)return null;const c=o?.reduce((h,p)=>{const m=(p.fieldConfig?.customData?.literalValues??[]).map(v=>[v,v]);return h.options?.push(...m),h},{key:l.key,required:l.required,type:"select",default:l.default,description:l.description,options:[],fieldConfig:l.fieldConfig}),u=e.schema?.reduce((h,p)=>{const m=p.schema?.find(x=>x.fieldConfig?.customData?.isLiteral),v=m?.fieldConfig?.customData?.literalValues?.[0],y=p.schema?.filter(x=>x.key!==m?.key)??[];return v&&(h[v]=y),h},{}),d=e.schema?.filter(h=>!h.schema?.find(m=>m.fieldConfig?.customData?.isLiteral)),f=s?.[c.key];return a.jsxs("div",{children:[a.jsx(Qj,{field:c,path:[...t,c.key]},`${r}.${c.key}`),f&&u?.[f]&&u[f].map(h=>a.jsx(Qj,{field:h,path:[...t,h.key]},`${r}.${h.key}`)),d&&d.map(h=>a.jsx(Qj,{field:h,path:[...t,h.key]},`${r}.${h.key}`))]},e.key)},kir=({error:e})=>a.jsx(Wt,{variant:"destructive",title:e}),Oir=["object","array"];function fUe({description:e,error:t}){return!e&&!t?null:a.jsxs(ht,{invalid:!!t,children:[e&&a.jsx(no,{children:e}),a.jsx(ns,{children:t})]})}const jir=({label:e,children:t,field:n,error:r})=>{const s=n.fieldConfig?.description;if(n.type==="record")return a.jsxs(T0,{className:"gap-2 pb-4 last:pb-0",children:[a.jsx(OC,{required:n.required,children:e}),t,a.jsx(fUe,{description:s,error:r})]});if(Oir.includes(n.type))return a.jsxs("div",{className:"pb-4 last:pb-0",children:[t,a.jsx(fUe,{description:s,error:r})]});const i=n.type==="boolean";return a.jsxs(ht,{invalid:!!r,className:"pb-4 last:pb-0",children:[!i&&a.jsx(ut,{required:n.required,className:"block",children:e}),t,s&&a.jsx(no,{children:s}),a.jsx(ns,{children:r})]})};function Cir({className:e,...t}){return a.jsx("form",{"data-slot":"form",className:Z("flex flex-col gap-4",e),...t})}const DSt=g.forwardRef(function(t,n){return a.jsx(Tvt,{ref:n,...t})}),_ir=md(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(pht,"rounded-full",V0e),unstyled:Z0e},size:{sm:Z(ov.sm,"px-[.75em]"),md:Z(ov.md,"px-[.75em]"),lg:Z(ov.lg,"px-[.85em]")}},defaultVariants:{variant:"default",size:"md"}});function wn({className:e,size:t,testId:n,variant:r,error:s,autoComplete:i,...o}){return a.jsx(DSt,{className:Z(_ir({variant:mht(r),size:t}),uht,e),"data-testid":n,...BH(s),...o,...tK(i),...$x(o)})}const $pe=Symbol("invalid");function hUe(e){if(e==="")return;const t=Number(e);return isNaN(t)?$pe:t}const Tir=({inputProps:e,field:t})=>{const{key:n,...r}=e;return a.jsx(wn,{type:"number",step:"any",...r,defaultValue:t.default!==void 0?Number(t.default):void 0,onChange:s=>{const i=hUe(s.target.value);i!==$pe&&r.onChange({target:{value:i,name:e.name}})},onBlur:s=>{const i=hUe(s.target.value);i!==$pe&&r.onChange({target:{value:i,name:e.name}})}})};function Eir({label:e,children:t}){return e===aK||e===""?a.jsx("div",{className:"flex flex-col gap-2",children:t}):a.jsx(Iir,{label:e,children:t})}function Iir({label:e,children:t}){const n=g.useContext(oK),{expanded:r,invalid:s,setExpanded:i}=bSt(n,!1);return a.jsxs(gc,{open:r,onOpenChange:i,className:"motion-reduce:[&_[data-slot=collapsible-content]]:transition-none motion-reduce:[&_svg]:transition-none",children:[a.jsxs(Hl,{className:"flex min-h-11 w-full items-center gap-2 text-left text-caption text-muted-foreground",children:[a.jsx(Ha,{direction:"right",className:"size-3.5"}),a.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[a.jsx(Ua,{"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(Gl,{keepMounted:!0,className:"border-l border-border pt-2 pl-4",children:t})]})}const Nir=({inputProps:e,field:t})=>{const{onChange:n}=e,[r,s]=g.useState(()=>Object.entries(t.default||{}).map(([d,f])=>({id:d||Sa(),key:d,value:f})));g.useEffect(()=>{r.length===0&&s([{id:Sa(),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:Sa(),key:"",value:""}];s(d),i(d)},u=d=>{const f=r.filter(h=>h.id!==d);f.length===0&&f.push({id:Sa(),key:"",value:""}),s(f),i(f)};return a.jsxs("div",{className:"grid gap-2",children:[r.map(d=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(wn,{placeholder:"Key",className:"flex-1","aria-label":"Key",value:d.key,onChange:f=>o(d.id,"key",f.target.value),onBlur:l}),a.jsx(wn,{placeholder:"Value",className:"flex-1","aria-label":"Value",value:d.value,onChange:f=>o(d.id,"value",f.target.value),onBlur:l}),a.jsx(ue,{type:"button",variant:"ghost",size:"icon-md",tooltip:"Remove pair","aria-label":"Remove pair",onClick:()=>u(d.id),children:a.jsx(opt,{})})]},d.id)),a.jsx(ue,{type:"button",variant:"ghost",size:"sm",className:"justify-self-start",onClick:c,icon:a.jsx(ys,{}),children:"Add pair"})]})},Air=({field:e,inputProps:t,value:n})=>{const{key:r,...s}=t;return a.jsxs(ps,{...s,value:n,onValueChange:i=>{const o={target:{value:i,name:t.name}};s.onChange(o)},children:[a.jsx(gs,{children:a.jsx(ms,{placeholder:"Select an option"})}),a.jsx(vs,{children:(e.options||[]).map(([i,o])=>a.jsx(hr,{value:i,children:o},i))})]})},Pir=({inputProps:e,field:t})=>{const{key:n,className:r,...s}=e;return a.jsx(Pu,{...s,rows:1,className:Z("field-sizing-content max-h-48 min-h-control-md resize-none overflow-y-auto",r),defaultValue:t.default})},$ir=({children:e})=>a.jsx(ue,{type:"submit",children:e}),Rir=({field:e,inputProps:t})=>{const n=t.name?.split(".")??[];return e.schema?.map((r,s)=>a.jsxs("div",{children:[a.jsx(Qj,{field:r,path:n},n.join(".")),s<(e.schema?.length??0)-1&&a.jsx(Y,{variant:"meta",className:"text-center",children:"OR"})]},r.key))};function Mir({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(()=>Ner(e),[e]),f=Dx({defaultValues:{...Aer(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(b5,{...f,children:a.jsx(Ber,{value:p,children:a.jsxs(i.Form,{onSubmit:f.handleSubmit(h),...u,children:[d.fields.map(m=>a.jsx(Qj,{field:m,path:[m.key]},m.key)),s,l&&a.jsx(i.SubmitButton,{children:"Submit"})]})})})}const Dir={Form:Cir,FieldWrapper:jir,ErrorMessage:kir,SubmitButton:$ir,ObjectWrapper:Eir,ArrayWrapper:mrr,ArrayElementWrapper:prr};function Lir({uiComponents:e,formComponents:t,readOnly:n,...r}){const s=g.useMemo(()=>({...Dir,...e}),[e]),i=g.useMemo(()=>{const o=l=>n===void 0?l:{...l,readOnly:n};return{string:l=>a.jsx(Pir,{...l,inputProps:o(l.inputProps)}),number:l=>a.jsx(Tir,{...l,inputProps:o(l.inputProps)}),boolean:l=>a.jsx(Orr,{...l,inputProps:o(l.inputProps)}),date:l=>a.jsx(xir,{...l,inputProps:o(l.inputProps)}),select:l=>a.jsx(Air,{...l,inputProps:o(l.inputProps)}),record:l=>a.jsx(Nir,{...l,inputProps:o(l.inputProps)}),union:l=>a.jsx(Rir,{...l,inputProps:o(l.inputProps)}),"discriminated-union":l=>a.jsx(Sir,{...l,inputProps:o(l.inputProps)}),...t}},[n,t]);return a.jsx(MSe,{value:n===!0,children:a.jsx(Mir,{...r,uiComponents:s,formComponents:i})})}function LSt(e){return e!=null&&typeof e=="object"&&"_zod"in e}function $u(e){if(!(e==null||typeof e!="object"))return LSt(e)?e._zod.def:e._def}function zir(e){return typeof e.isOptional=="function"?e.isOptional():typeof e.safeParse=="function"?e.safeParse(void 0).success:!1}function Om(e){if(e.shape&&typeof e.shape=="object")return e.shape;const t=$u(e);if(t?.shape)return typeof t.shape=="function"?t.shape():t.shape}function O5(e){const t=$u(e);return t?"innerType"in t?O5(t.innerType):"schema"in t?O5(t.schema):e:e}function Fir(e){const t=$u(e);if(t?.entries)return t.entries;if(t?.values)return t.values}function zSt(e){const t=$u(e);return t?.element??t?.type}function Bir(e){return $u(e)?.valueType}function FSt(e){const t=$u(e);if(t?.values!==void 0)return Array.isArray(t.values)?t.values[0]:t.values;if(t?.value!==void 0)return t.value}function Uir(e){const t=$u(e);if(t?.values!==void 0)return t.values;if(t?.value!==void 0)return[t.value]}function Vir(e){const t=$u(e);if(t?.defaultValue!==void 0)return typeof t.defaultValue=="function"?t.defaultValue():t.defaultValue}function ike(e){return $u(e)?.options}function gQ(e){const t=$u(e);if(t?.left&&t?.right)return{left:t.left,right:t.right};if(e.def?.left&&e.def?.right)return{left:e.def.left,right:e.def.right}}function qir(e){return $u(e)?.checks??[]}function Qir(e){return e.some(t=>{if(LSt(t)){const n=$u(t);return n?.check==="string_format"&&n?.format==="datetime"}return t.kind==="datetime"})}function vQ(e){const t=Om(e);if(t)return Object.keys(t).length===0;const n=gQ(e);return n?vQ(n.left)&&vQ(n.right):!1}function Sj(e){const t=$u(e);if(!t)return;const n=Vir(e);if(n!==void 0)return n;const r=FSt(e);if(r!==void 0&&(t.typeName==="ZodLiteral"||t.type==="literal"||e?.constructor?.name?.slice(1)==="ZodLiteral"))return r;if("innerType"in t)return Sj(t.innerType);if("schema"in t)return Sj(t.schema);if(Om(e)&&!("left"in t))return GB(e);if("left"in t&&"right"in t){const i=Om(t.left),o=Om(t.right),l=i?GB(t.left):Sj(t.left),c=o?GB(t.right):Sj(t.right);return{...l,...c}}}function GB(e){const t=Om(e);if(!t)return{};const n={};for(const[r,s]of Object.entries(t)){const i=Sj(s);i!==void 0&&(n[r]=i)}return n}function BSt(e,t){if(t?.fieldType)return t.fieldType;const n=e?.constructor?.name?.slice(1),r=$u(e),s=typeof r?.type=="string"?`Zod${r.type.charAt(0).toUpperCase()}${r.type.slice(1)}`:void 0,i=r?.typeName??s??n;if(i==="ZodObject"||i==="ZodIntersection")return"object";if(i==="ZodNumber")return"number";if(i==="ZodBoolean")return"boolean";if(i==="ZodString"){const o=qir(e);return Qir(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=ike(e);return o&&o.every(c=>{const u=Om(c);return u?Object.values(u).some(d=>{const f=d?.constructor?.name?.slice(1),h=$u(d);return f==="ZodLiteral"||h?.typeName==="ZodLiteral"||h?.type==="literal"}):!1})?"discriminated-union":"union"}if(i==="ZodDiscriminatedUnion")return"discriminated-union";if(i==="ZodLiteral"){const o=FSt(e);return typeof o=="number"?"number":typeof o=="boolean"?"boolean":"string"}return"string"}function Rpe(e){const t=$u(e);if(t){if(t.typeName==="ZodEffects"&&t.effect?.type==="refinement"){const n=t.effect?.refinement;if(n){const r=Object.getOwnPropertySymbols(n);for(const s of r){const i=n[s];if(i&&typeof i=="object")return i}}}if("innerType"in t)return Rpe(t.innerType);if("schema"in t)return Rpe(t.schema)}}function l1(e,t){const n=O5(t),r=Rpe(t);let s=BSt(n,r);const i=Sj(t),o=Fir(n);let l=[];o&&(Array.isArray(o)?l=o.map(b=>[b,b]):l=Object.entries(o));let c=[];const u=Om(n);u&&!gQ(n)&&(c=Object.entries(u).map(([b,S])=>l1(b,S)));const d=ike(n),f=n?.constructor?.name?.slice(1),h=$u(n),p=typeof h?.type=="string"?`Zod${h.type.charAt(0).toUpperCase()}${h.type.slice(1)}`:void 0,m=h?.typeName??p??f;(m==="ZodUnion"||m==="ZodDiscriminatedUnion")&&d&&(c=Object.entries(d).map(([b,S])=>l1(b,S)));const v=gQ(n);if(v){const{left:b,right:S}=v;let k=[],j=[];const C=Om(b);if(C)k=Object.entries(C).map(([_,N])=>l1(_,N));else{const _=l1(e,b);k=_.schema??[_],s=_.type}const T=Om(S);if(T)j=Object.entries(T).map(([_,N])=>l1(_,N));else{const _=l1(e,S);j=_.schema??[_],s=_.type}c=[...k,...j]}if(m==="ZodArray"){const b=zSt(n);b&&(c=[l1("0",b)])}const y=m==="ZodLiteral",x=y?Uir(n):void 0;return{key:e,type:s,required:!zir(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 Zir(e){const t=Om(e);return t?{fields:Object.entries(t).map(([r,s])=>l1(r,s))}:{fields:[]}}function Wir(e){const t=gQ(e);return t?[t.left,t.right]:ike(e)}function pUe(e,t){const n={};for(const[r,s]of Object.entries(e)){const i=t(r),o=i?yQ(s,i):s;o!==void 0&&(n[r]=o)}return n}function mUe(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 yQ(e,t){const n=O5(t),r=Wir(n);if(r){const l=r.reduce((c,u)=>yQ(c,u),e);return pD(l)&&mUe(t,l)?void 0:l}const s=Om(n);if(s&&pD(e)){const l=pUe(e,c=>s[c]);return mUe(t,l)?void 0:l}const i=Bir(n);if(i&&pD(e))return pUe(e,()=>i);if(Array.isArray(e)){const l=zSt(n);return l&&typeof l=="object"?e.map(c=>yQ(c,l)):e}if(!((e===""||e===null&&!t.safeParse(null).success)&&Sj(t)===void 0))return e}class Hir{_schema;constructor(t){if(!t)throw new Error("CustomZodProvider: schema is required");this._schema=t}getDefaultValues(){return GB(this._schema)}validateSchema(t){const n=yQ(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 Zir(this._schema)}}function $oe(e,t){return t?e[aK]:e}function Gir(e,t){return vQ(e)?yr({}):t?yr({[aK]:e.description?e:e.describe("Input")}):e}const USt=g.createContext(null),Kir=({children:e})=>{const t=g.useContext(USt);return t?a.jsx(JG,{...t,children:e}):null},Yir={SubmitButton:Kir};function oke({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=Om(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?.($oe(_,m))),y.current?.($oe(T.getValues(),m)))},[x,m]),S=g.useMemo(()=>e?new Hir(Gir(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:{[aK]:r}:r,[m,r]),C=g.useCallback(async T=>{await t?.($oe(T,m))},[t,m]);return S?a.jsx(USt.Provider,{value:k,children:a.jsx(Lir,{schema:S,onSubmit:C,onFormInit:b,defaultValues:j,formProps:{className:u,noValidate:!0},uiComponents:Yir,withSubmit:!0,readOnly:d,children:f})}):(console.error("no form schema found"),null)}function ake(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 VSt(e,t){const n=BSt(O5(e));if(n==="object"&&!pD(t))return"Form input requires a JSON object. Correct the JSON first.";if(n==="array"&&!Array.isArray(t))return"Form input requires a JSON array. Correct the JSON first."}function qSt(e,t){const n=ake(t);if(!n.ok)return{ok:!1,errors:[n.error]};const r=e.safeParse(n.value);return r.success?{ok:!0,value:r.data}:{ok:!1,errors:r.error.issues.map(s=>`${s.path.join(".")||"Input"}: ${s.message}`)}}const Xir=a.jsx(At,{children:a.jsx(Uc,{})});function Jir(e,t){if(!t)return{type:"form",value:e};const n=e??EJn(),r=x1t(n);return r?{type:"simple",value:r}:{type:"json",value:JSON.stringify(n,null,2)}}const lke=({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=Xir,submitButtonVariant:h="primary",submitButtonFullWidth:p,hideInputTypeLabel:m,inputTypeLabel:v="Run input",hideHeading:y})=>{const[x,b]=g.useState(()=>Jir(t,o)),S=g.useRef(t),[k,j]=g.useState([]);function C(){return x.type==="json"?ake(x.value):{ok:!0,value:x.type==="form"?S.current:x.value}}function T(F){const Q=qSt(e,F);Q.ok?s(Q.value):j(Q.errors)}function _(F){if(F===x.type)return;j([]);const Q=C();if(!Q.ok)return j([Q.error]);if(F==="json")return b({type:F,value:JSON.stringify(Q.value===void 0?{}:Q.value,null,2)});if(F==="simple"){const B=x1t(Q.value);return B?b({type:F,value:B}):j(["Simple input requires a messages array with text parts and a string phase. Correct the JSON first."])}const q=VSt(e,Q.value);return q?j([q]):b({type:F,value:Q.value})}const N=a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",children:"Trigger a run"}),I=!d&&!y,A=d||y||m,P=a.jsx(ier,{value:x.type,onChange:_,disabled:n,includeSimple:o,compact:I}),L=a.jsxs(a.Fragment,{children:[!m&&a.jsxs("div",{className:"flex justify-between gap-3 px-5 py-3",children:[a.jsx(Y,{as:"p",variant:"caption",tone:"muted",children:v}),I&&a.jsx("div",{className:"shrink-0",children:P})]}),a.jsxs("div",{className:"px-5",children:[A&&a.jsx("div",{className:"pb-4",children:P}),a.jsx("div",{className:Z("pb-4",{"pointer-events-none opacity-50":n}),children:x.type==="json"?a.jsx(AJn,{value:x.value,onChange:F=>{b({type:"json",value:F}),j([])},errors:k,isSubmitLoading:n,submitButtonLabel:r,submitButtonIcon:f,submitButtonVariant:h,submitButtonFullWidth:p,onSubmit:()=>T(x.value),submitActions:l,leftActions:c,children:i}):x.type==="simple"&&o?a.jsx(ser,{schema:e,value:x.value,onChange:F=>b({type:"simple",value:F}),isSubmitLoading:n,submitButtonLabel:r,submitButtonIcon:f,submitButtonVariant:h,submitButtonFullWidth:p,onSubmit:s,submitActions:l,leftActions:c,children:i}):a.jsx(eor,{schema:e,onValuesChange:F=>{S.current=F},defaultValues:x.value,isSubmitLoading:n,submitButtonLabel:r,submitButtonIcon:f,submitButtonVariant:h,submitButtonFullWidth:p,onSubmit:s,submitActions:l,leftActions:c,children:i})})]})]});return d?a.jsxs(gc,{defaultOpen:!0,children:[a.jsxs(Hl,{className:"flex w-full items-center gap-2 pb-3 text-left",children:[a.jsx(Ha,{direction:"right",className:"size-4 text-muted-foreground"}),u??N]}),a.jsx(Gl,{keepMounted:!0,children:L})]}):a.jsxs(a.Fragment,{children:[!y&&a.jsx("div",{className:"border-b border-border pb-3",children:u??N}),a.jsx("div",{children:L})]})},eor=({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(oke,{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 tor({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(lke,{schema:e,defaultValues:r,isSubmitLoading:t,submitButtonLabel:d,inputTypeLabel:"Next run input",submitButtonVariant:"primary",submitButtonIcon:a.jsx(At,{children:a.jsx(Uc,{})}),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(ue,{variant:"primary",disabled:t,onClick:()=>n(null),children:[t?a.jsx(At,{children:a.jsx(fc,{className:"animate-spin"})}):a.jsx(At,{children:a.jsx(Uc,{})}),d]})]})]})]})}const Ol=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 nor({workflow:e,workflowId:t}){const n=Object.keys(e.steps??{}).length;return a.jsxs("div",{className:"flex w-full items-center gap-2 px-5",children:[a.jsx(At,{className:"shrink-0 text-muted-foreground",children:a.jsx(Ol,{})}),a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",className:"truncate",children:e.name??t}),a.jsx(ii,{content:e.name??t,variant:"ghost",className:"shrink-0"}),a.jsxs(Mt,{className:"ml-auto shrink-0",children:[n," step",n===1?"":"s"]})]})}const QSt=g.createContext(void 0);function WL(){const e=g.useContext(QSt);if(e===void 0)throw new Error(Nr(53));return e}const ror=500,Mpe=16;function R1(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 eE=e=>t=>t?{[e]:""}:null,cK={hasOverflowX:eE("data-has-overflow-x"),hasOverflowY:eE("data-has-overflow-y"),overflowXStart:eE("data-overflow-x-start"),overflowXEnd:eE("data-overflow-x-end"),overflowYStart:eE("data-overflow-y-start"),overflowYEnd:eE("data-overflow-y-end"),cornerHidden:()=>null},sor={x:0,y:0},gUe={width:0,height:0},ior={xStart:!1,xEnd:!1,yStart:!1,yEnd:!1},oor={x:!0,y:!0,corner:!0},aor=g.forwardRef(function(t,n){const{render:r,className:s,overflowEdgeThreshold:i,style:o,...l}=t,{xStart:c,xEnd:u,yStart:d,yEnd:f}=lor(i),h=Zi(),p=bo(),m=bo(),{nonce:v,disableStyleElements:y}=dSe(),[x,b]=g.useState(!1),[S,k]=g.useState(!1),[j,C]=g.useState(!1),[T,_]=g.useState(!1),[N,I]=g.useState(!1),[A,P]=g.useState(gUe),[L,F]=g.useState(gUe),[Q,q]=g.useState(ior),[B,V]=g.useState(oor),H=g.useRef(null),D=g.useRef(null),K=g.useRef(null),M=g.useRef(null),$=g.useRef(null),z=g.useRef(null),U=g.useRef(null),G=g.useRef(null),ne=g.useRef(0),X=g.useRef(0),ee=g.useRef(0),ie=g.useRef(0),fe=g.useRef("vertical"),te=g.useRef(sor),se=g.useRef(null);function re(je){const Ce=je?C:k,Ue=je?p:m;Ce(!0),Ue.start(ror,()=>{Ce(!1)})}const le=ft(je=>{const Ce=je.x-te.current.x,Ue=je.y-te.current.y;te.current=je,Ue!==0&&re(!0),Ce!==0&&re(!1)}),pe=ft(()=>{const je=D.current;je&&se.current===null&&(se.current=je.style.scrollSnapType,je.style.scrollSnapType="none")}),ve=ft(je=>{if(je.button!==0||G.current!==null&&(fe.current==="vertical"?$.current:z.current)?.hasPointerCapture(G.current))return;G.current=je.pointerId,ne.current=je.clientY,X.current=je.clientX,fe.current=je.currentTarget.getAttribute("data-orientation");const Ce=D.current;Ce&&(ee.current=Ce.scrollTop,ie.current=Ce.scrollLeft,pe()),(fe.current==="vertical"?$.current:z.current)?.setPointerCapture(je.pointerId)}),he=ft(je=>{if(je.pointerId!==G.current)return;G.current=null,(fe.current==="vertical"?C:k)(!1),se.current!==null&&(D.current&&(D.current.style.scrollSnapType=se.current),se.current=null);const Ce=fe.current==="vertical"?$.current:z.current;Ce?.hasPointerCapture(je.pointerId)&&Ce.releasePointerCapture(je.pointerId)}),ke=ft(je=>{if(je.pointerId!==G.current)return;if(je.buttons%2===0){he(je);return}const Ce=D.current;if(!Ce)return;const Ue=fe.current==="vertical",ae=Ue?$.current:z.current,me=Ue?K.current:M.current;if(!ae||!me)return;const Ne=Ue?"y":"x",Te=R1(me,"padding",Ne),ce=R1(ae,"margin",Ne),ye=Ue?ae.offsetHeight:ae.offsetWidth,$e=(Ue?me.offsetHeight:me.offsetWidth)-ye-Te-ce,De=Ue?je.clientY-ne.current:je.clientX-X.current,Qe=$e<=0?0:De/$e,tt=Ue?Ce.scrollHeight:Ce.scrollWidth,st=Ue?Ce.clientHeight:Ce.clientWidth,Le=(Ue?ee.current:ie.current)+Qe*(tt-st);Ue?Ce.scrollTop=Le:Ce.scrollLeft=Le,je.preventDefault(),re(Ue)});function Ee(je){_(je.pointerType==="touch")}function Ve(je){if(Ee(je),je.pointerType!=="touch"){const Ce=ln(H.current,je.target);b(Ce)}}const Ze=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]),Fe={role:"presentation",onPointerEnter:Ve,onPointerMove:Ve,onPointerDown:Ee,onPointerLeave(){b(!1)},style:{position:"relative","--scroll-area-corner-height":`${A.height}px`,"--scroll-area-corner-width":`${A.width}px`}},Ae=cn("div",t,{state:Ze,ref:[n,H],props:[Fe,l],stateAttributesMapping:cK}),ze=g.useMemo(()=>({handlePointerDown:ve,handlePointerMove:ke,handlePointerUp:he,handleScroll:le,disableViewportSnap:pe,cornerSize:A,setCornerSize:P,thumbSize:L,setThumbSize:F,hasMeasuredScrollbar:N,setHasMeasuredScrollbar:I,touchModality:T,cornerRef:U,scrollingX:S,scrollingY:j,hovering:x,setHovering:b,viewportRef:D,scrollbarYRef:K,scrollbarXRef:M,thumbYRef:$,thumbXRef:z,rootId:h,hiddenState:B,setHiddenState:V,overflowEdges:Q,setOverflowEdges:q,viewportState:Ze,overflowEdgeThreshold:{xStart:c,xEnd:u,yStart:d,yEnd:f}}),[ve,ke,he,le,pe,A,L,N,T,S,j,x,h,B,Q,Ze,c,u,d,f]);return a.jsxs(QSt.Provider,{value:ze,children:[!y&&x5.getElement(v),Ae]})});function lor(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 ZSt=g.createContext(void 0);function cor(){const e=g.useContext(ZSt);if(e===void 0)throw new Error(Nr(55));return e}const WSt=["--scroll-area-overflow-x-start","--scroll-area-overflow-x-end","--scroll-area-overflow-y-start","--scroll-area-overflow-y-end"];let vUe=!1;function uor(){vUe||Tx||(typeof CSS<"u"&&"registerProperty"in CSS&&WSt.forEach(e=>{try{CSS.registerProperty({name:e,syntax:"<length>",inherits:!1,initialValue:"0px"})}catch{}}),vUe=!0)}const dor=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}=WL(),I=Ex(),A=g.useRef(!0),P=g.useRef([NaN,NaN,NaN,NaN]),L=bo(),F=bo(),Q=ft(()=>{const D=l.current,K=c.current,M=u.current,$=d.current,z=f.current,U=h.current;if(!D)return;const G=D.scrollHeight,ne=D.scrollWidth,X=D.clientHeight,ee=D.clientWidth,ie=D.scrollTop,fe=D.scrollLeft,te=P.current,se=Number.isNaN(te[0]);if(te[0]=X,te[1]=G,te[2]=ee,te[3]=ne,se&&S(!0),G===0||ne===0)return;const re=hor(D),le=re.y,pe=re.x,ve=ee/ne,he=X/G,ke=Math.max(0,ne-ee),Ee=Math.max(0,G-X);let Ve=0,Ze=0;pe||(Ve=wpe(I==="rtl"?-fe:fe,ke),Ze=ke-Ve);const Fe=le?0:wpe(ie,Ee),Ae=le?0:Ee-Fe,ze=pe?0:ee,je=le?0:X;let Ce=0,Ue=0;!pe&&!le&&(Ce=K?.offsetWidth||0,Ue=M?.offsetHeight||0);const ae=p.width===0&&p.height===0,me=ae?Ce:0,Ne=ae?Ue:0,Te=R1(M,"padding","x"),ce=R1(K,"padding","y"),ye=R1(z,"margin","x"),Se=R1($,"margin","y"),$e=ze-Te-ye,De=je-ce-Se,Qe=M?Math.min(M.offsetWidth-me,$e):$e,tt=K?Math.min(K.offsetHeight-Ne,De):De,st=Math.max(Mpe,Qe*ve),He=Math.max(Mpe,tt*he);if(v(ge=>j9(ge,{width:st,height:He})),K&&$){const ge=K.offsetHeight-He-ce-Se,Pe=yUe($,"--scroll-area-thumb-height",ie,Ee,G,He,ge);$.style.transform=`translate3d(0,${Pe}px,0)`}if(M&&z){const ge=M.offsetWidth-st-Te-ye,Pe=I==="rtl"?-fe:fe,Xe=yUe(z,"--scroll-area-thumb-width",Pe,ke,ne,st,ge);z.style.transform=`translate3d(${I==="rtl"?-Xe:Xe}px,0,0)`}const Le=[Ve,Ze,Fe,Ae];WSt.forEach((ge,Pe)=>{D.style.setProperty(ge,`${Le[Pe]}px`)}),U&&m(ge=>j9(ge,{width:Ce,height:Ue})),x(ge=>j9(ge,re));const wt={xStart:!pe&&Ve>_.xStart,xEnd:!pe&&Ze>_.xEnd,yStart:!le&&Fe>_.yStart,yEnd:!le&&Ae>_.yEnd};T(ge=>j9(ge,wt))});jt(()=>{uor()},[]),jt(()=>{queueMicrotask(Q)},[Q,b,I,_.xStart,_.xEnd,_.yStart,_.yEnd]),jt(()=>{l.current?.matches(":hover")&&C(!0)},[l,C]),jt(()=>{const D=l.current;if(typeof ResizeObserver>"u"||!D)return;let K=!1;const M=new ResizeObserver(()=>{if(!K){K=!0;const $=P.current;if($[0]===D.clientHeight&&$[1]===D.scrollHeight&&$[2]===D.clientWidth&&$[3]===D.scrollWidth)return}Q()});return M.observe(D),F.start(0,()=>{const $=D.getAnimations({subtree:!0});$.length!==0&&Promise.allSettled($.map(z=>z.finished)).then(Q).catch(()=>{})}),()=>{M.disconnect(),F.clear()}},[Q,l,F]);function q(){A.current=!1}const B={role:"presentation",...y&&{"data-id":`${y}-viewport`},tabIndex:b.x&&b.y?-1:0,className:x5.className,style:{overflow:"scroll"},onScroll(){l.current&&(Q(),(j||!A.current)&&k({x:l.current.scrollLeft,y:l.current.scrollTop}),L.start(100,()=>{A.current=!0}))},onWheel:q,onPointerMove:q,onPointerEnter:q,onKeyDown:q},V=cn("div",t,{ref:[n,l],state:N,props:[B,o],stateAttributesMapping:cK}),H=g.useMemo(()=>({computeThumbPosition:Q}),[Q]);return a.jsx(ZSt.Provider,{value:H,children:V})});function hor(e){const t=e.clientHeight>=e.scrollHeight,n=e.clientWidth>=e.scrollWidth;return{y:t,x:n,corner:t||n}}function j9(e,t){for(const n in t)if(e[n]!==t[n])return t;return e}function yUe(e,t,n,r,s,i,o){const l=Pi(n,0,r),c=n-l,u=Math.max(Mpe,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 HSt=g.createContext(void 0);function por(){const e=g.useContext(HSt);if(e===void 0)throw new Error(Nr(54));return e}const mor=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}=WL(),I=i==="vertical",A={...N,hovering:u,scrolling:I?f:d,orientation:i},P=Ex(),L=!_&&!o,F=I?h.y:h.x,Q=o||!F;g.useEffect(()=>{if(!Q)return;const V=v.current,H=I?p.current:m.current;if(!H)return;function D(K){if(!V||K.ctrlKey)return;const M=!I,$=M?"scrollLeft":"scrollTop",z=M?K.deltaX:K.deltaY;if(z===0)return;const U=M?V.scrollWidth-V.clientWidth:V.scrollHeight-V.clientHeight,G=M&&P==="rtl"?-U:0,ne=M&&P==="rtl"?0:U,X=V[$];X<=G&&z<0||X>=ne&&z>0||(K.preventDefault(),V[$]=Math.min(ne,Math.max(G,X+z)),k({x:V.scrollLeft,y:V.scrollTop}))}return Fr(H,"wheel",D,{passive:!1})},[P,k,I,m,p,Q,v]);const q={...C&&{"data-id":`${C}-scrollbar`},onPointerDown(V){if(V.button!==0)return;const H=qi(V.nativeEvent),D=I?y.current:x.current;if(D&&ln(D,H))return;const K=v.current;if(!K)return;const M=I?p.current:m.current;if(!D||!M)return;const $=I?"y":"x",z=R1(D,"margin",$),U=R1(M,"padding",$),G=I?D.offsetHeight:D.offsetWidth,ne=M.getBoundingClientRect(),X=I?V.clientY-ne.top-G/2-U+z/2:V.clientX-ne.left-G/2-U+z/2,ee=I?K.scrollHeight:K.scrollWidth,ie=I?K.clientHeight:K.clientWidth,te=(I?M.offsetHeight:M.offsetWidth)-G-U-z;if(te<=0)return;const se=X/te,re=ee-ie;j(),I?K.scrollTop=se*re:P==="rtl"?K.scrollLeft=-(1-se)*re:K.scrollLeft=se*re,k({x:K.scrollLeft,y:K.scrollTop}),b(V)},onPointerUp:S,onPointerCancel:S,style:{position:"absolute",touchAction:"none",WebkitUserSelect:"none",userSelect:"none",visibility:L?"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=cn("div",t,{ref:[n,I?p:m],state:A,props:[q,c],stateAttributesMapping:cK});return Q?a.jsx(HSt.Provider,{value:i,children:B}):null}),gor=g.forwardRef(function(t,n){const{render:r,className:s,style:i,...o}=t,{computeThumbPosition:l}=cor(),{hasMeasuredScrollbar:c,viewportState:u}=WL(),d=g.useRef(null),f=g.useRef(c);return jt(()=>{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]),cn("div",t,{ref:[n,d],state:u,stateAttributesMapping:cK,props:[{role:"presentation",style:{minWidth:"fit-content"}},o]})}),vor=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}=WL(),v=por(),y=v==="vertical";return cn("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]})}),yor=g.forwardRef(function(t,n){const{render:r,className:s,style:i,...o}=t,{cornerRef:l,cornerSize:c,hiddenState:u}=WL(),d=cn("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}),xor=8,GSt=(e,{enabled:t=!0})=>{const n=g.useRef(t),r=g.useRef(null),s=g.useRef(!1),i=g.useRef(null);Me.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-xor){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])},bor=100,wor=20,Sor=1,kor=16,Dpe="2rem",C9="0px",Oor=["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(" "),Jw=e=>e===!0?Dpe:e;function jor(e,t){if(e===!1)return{top:!1,bottom:!1,left:!1,right:!1};const n=(t==="vertical"||t==="both")&&Dpe,r=(t==="horizontal"||t==="both")&&Dpe,s={top:n,bottom:n,left:r,right:r};return e===!0||e===void 0||(e.y!==void 0&&(s.top=Jw(e.y),s.bottom=Jw(e.y)),e.x!==void 0&&(s.left=Jw(e.x),s.right=Jw(e.x)),e.top!==void 0&&(s.top=Jw(e.top)),e.bottom!==void 0&&(s.bottom=Jw(e.bottom)),e.left!==void 0&&(s.left=Jw(e.left)),e.right!==void 0&&(s.right=Jw(e.right))),s}const Cor=e=>({"--scroll-area-fade-top":e.top||C9,"--scroll-area-fade-bottom":e.bottom||C9,"--scroll-area-fade-left":e.left||C9,"--scroll-area-fade-right":e.right||C9});function xUe(e,t,n){const r=e??t;return Number.isFinite(r)?Math.max(n,r):Math.max(n,t)}const bUe=({direction:e,label:t,onStartScrolling:n,onStopScrolling:r,onKeyboardScroll:s})=>{const i=e==="left"?mP:Dc;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",Ln,On,ji,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"})})},_or=({areaRef:e,scrollButtons:t})=>{const n=g.useRef(null),r=typeof t=="object"?t:void 0,s=xUe(r?.scrollSpeed,bor,Sor),i=xUe(r?.scrollIntervalTime,wor,kor),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(bUe,{direction:"left",label:o,onStartScrolling:d,onStopScrolling:c,onKeyboardScroll:f=>u(f,2)}),a.jsx(bUe,{direction:"right",label:l,onStartScrolling:d,onStopScrolling:c,onKeyboardScroll:f=>u(f,2)})]})},cke=g.createContext(null);function Tor(){const e=g.use(cke);if(!e)throw new Error("ScrollAreaViewport must be a direct child of ScrollArea");return e}function of({className:e,children:t,ref:n}){const r=Tor(),{areaRef:s}=r,i=g.useMemo(()=>xk(s,n),[s,n]);return a.jsx(dor,{ref:i,className:Z(r.className,e),style:r.style,children:a.jsx(gor,{style:r.contentStyle,children:a.jsx(cke,{value:null,children:t})})})}function Ir({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);GSt(u,{enabled:r});const d=jor(o,s),f=Object.values(d).some(Boolean),h=Cor(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&&Oor),style:h,contentStyle:p},v=g.Children.toArray(t).filter(x=>g.isValidElement(x)&&x.type===of).length;if(v>1)throw new Error("ScrollArea takes at most one ScrollAreaViewport");const y=v===1;return a.jsxs(aor,{className:Z("group/scroll-area relative overflow-hidden",e),...c,children:[a.jsx(cke,{value:m,children:y?t:a.jsx(of,{children:t})}),i&&s!=="vertical"&&a.jsx(_or,{areaRef:u,scrollButtons:i}),(s==="vertical"||s==="both")&&a.jsx(wUe,{orientation:"vertical",revealOnHover:l}),(s==="horizontal"||s==="both")&&a.jsx(wUe,{orientation:"horizontal",revealOnHover:l}),s==="both"&&a.jsx(yor,{})]})}function wUe({className:e,orientation:t="vertical",revealOnHover:n=!0,...r}){return a.jsx(mor,{"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(vor,{className:"relative flex-1 rounded-full bg-muted-foreground/30 hover:bg-muted-foreground/60"})})}function jk({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 KSt({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(Zl),[C,T]=g.useState(!1),_=g.useRef(null),N=g.useRef(null),[I,A]=g.useState(),[P,L]=jk({initialKey:`workflow-run-resource-id:${e}`,defaultValue:"",schema:gt()}),F=t||S,Q=I?.runId===F?I:void 0,q=F?m:null,B=mvt(q,F),{zodSchemaToUse:V,hasStateSchema:H}=u9n(r),D=fG(q?.status),K=q?.status==="paused";g.useEffect(()=>()=>_.current?.abort(),[]);const M=async ie=>{if(!r||C)return;_.current?.abort();const fe=new AbortController;_.current=fe,T(!0);try{A(void 0),v(null);const te=P.trim()||void 0,se=await i({workflowId:e,resourceId:te});if(fe.signal.aborted)return;b(se.runId),T(!1);const{initialState:re,inputData:le}=ie??{},pe=H?le:ie;await o({workflowId:e,runId:se.runId,inputData:pe,initialState:re,requestContext:f,resourceId:te})}catch(te){fe.signal.aborted||Ye.error(te instanceof Error?te.message:"Error executing workflow")}finally{fe.signal.aborted||T(!1)}},$=async()=>{if(!F)return;const ie=m?.status==="paused"||m?.status==="suspended"?m:void 0;try{const fe=await d({workflowId:e,runId:F});A({...fe,runId:F}),ie&&v({...ie,status:"canceled"})}catch{Ye.error("Error cancelling workflow run")}};if(g.useEffect(()=>{if(!t||!l)return;const ie=`${e}:${t}`;N.current!==ie&&(N.current=ie,l({workflowId:e,runId:t}))},[t,l,e]),s)return a.jsx(Ir,{className:"h-[calc(100vh-126px)] px-4 pt-2 pb-4",children:a.jsxs("div",{className:"space-y-4",children:[a.jsx(xt,{className:"h-10"}),a.jsx(xt,{className:"h-10"})]})});if(!r)return null;const z=B.length>0,U=q?.status==="running"||q?.status==="suspended",G=!!F,ne=q?.status??n??(c?"running":"pending"),X=a.jsx(p9n,{status:q?.status,cancelMessage:Q?.message??null,isCancelling:u,onCancel:$,disabled:!p}),ee=G?a.jsx(xJn,{runId:F,status:ne,result:q,timestamp:k?.timestamp,resourceId:Xpt(k)}):a.jsx(nor,{workflow:r,workflowId:e});return a.jsx("div",{className:"pt-3",children:a.jsxs("div",{children:[z&&c&&a.jsxs("div",{className:"-mt-5 flex items-center gap-2 border-b border-border bg-card px-5 py-2",children:[a.jsx(At,{children:a.jsx(fc,{className:"animate-spin text-foreground"})}),a.jsx(Y,{children:"Resuming workflow"})]}),p&&a.jsx(tor,{zodSchema:V,defaultValues:y,isStreaming:C||c,onExecute:ie=>{x(ie),M(ie)},isViewingRun:G,isProcessorWorkflow:r?.isProcessorWorkflow,collapsible:!1,headingSlot:ee,leftActions:t?void 0:a.jsx($9n,{}),submitButtonLabel:C?"Starting…":"Run",submitActions:h?.({resourceId:P,setResourceId:L})},`${e}:${F||"new"}`),!p&&a.jsx(Y,{variant:"caption",tone:"muted",className:"px-5 py-2",children:"You don't have permission to execute workflows."}),D&&q&&a.jsx(nJn,{result:q,workflowError:j,className:"mx-5 mb-4"}),K&&p&&a.jsx("div",{className:"px-5 pt-3 pb-4",children:a.jsx(z9n,{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(VXn,{input:y,result:q},F)]})})}const Eor=({workflowId:e,runId:t,observeWorkflowStream:n,...r})=>{const{runSnapshot:s,isLoadingRunExecutionResult:i}=g.useContext(Zl),o=g.useCallback(()=>{!t||!s||fG(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(xt,{className:"size-5 shrink-0 rounded-full"}),a.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[a.jsx(xt,{className:"h-4 w-24"}),a.jsx(xt,{className:"h-3 w-40"})]}),a.jsxs("div",{className:"shrink-0 space-y-2",children:[a.jsx(xt,{className:"ml-auto h-3 w-12"}),a.jsx(xt,{className:"ml-auto h-3 w-16"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx(xt,{className:"h-4 w-24"}),a.jsx(xt,{className:"h-7 w-28 rounded-md"})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx(xt,{className:"h-9 w-full rounded-md"}),a.jsx(xt,{className:"h-9 w-full rounded-md"}),a.jsx(xt,{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(KSt,{...r,paramsRunId:t,paramsRunStatus:s.status,workflowId:e,observeWorkflowStream:o},`${e}:${t}`)},YSt=g.createContext(void 0);function hf(e){const t=g.useContext(YSt);if(!e&&t===void 0)throw new Error(Nr(27));return t}const Ior=g.forwardRef(function(t,n){const{render:r,className:s,style:i,forceRender:o=!1,...l}=t,c=hf(),u=c.useState("open"),d=c.useState("nested"),f=c.useState("mounted"),h=c.useState("transitionStatus");return cn("div",t,{state:{open:u,transitionStatus:h},ref:[c.context.backdropRef,n],stateAttributesMapping:C_,props:[{role:"presentation",hidden:!f,style:{userSelect:"none",WebkitUserSelect:"none"}},l],enabled:o||!d})}),uK=g.forwardRef(function(t,n){const{render:r,className:s,style:i,disabled:o=!1,nativeButton:l=!0,...c}=t,u=hf(),d=u.useState("open"),{getButtonProps:f,buttonRef:h}=gd({disabled:o,native:l}),p={disabled:o};function m(v){d&&u.setOpen(!1,Yt(b0e,v.nativeEvent))}return cn("button",t,{state:p,ref:[n,h],props:[{onClick:m},c,f]})}),XSt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,id:o,...l}=t,c=hf(),u=Zi(o);return c.useSyncedValueWithCleanup("descriptionElementId",u),cn("p",t,{ref:n,props:[{id:u},l]})}),JSt=g.createContext(void 0);function uke(){const e=g.useContext(JSt);if(e===void 0)throw new Error(Nr(26));return e}const ekt={...j_,...oh,nestedDialogOpen(e){return e?{"data-nested-dialog-open":""}:null}},Nor=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");uke(),Cl({open:b,ref:u.context.popupRef,onComplete(){b&&u.context.onOpenChangeComplete?.(!0)}});const _=l===void 0?Vft(u.context.popupRef):l,N=x>0,I=u.useStateSetter("popupElement"),P=cn("div",t,{state:{open:b,nested:y,transitionStatus:j,nestedDialogOpen:N},props:[p,{id:T,"aria-labelledby":k,"aria-describedby":d,role:C,...gk,hidden:!v,onKeyDown(L){kk.has(L.key)&&L.stopPropagation()},style:{"--nested-dialogs":x}},c],ref:[n,u.context.popupRef,I],stateAttributesMapping:ekt});return a.jsx(lP,{context:h,openInteractionType:S,disabled:!v,closeOnFocusOut:!f,initialFocus:_,returnFocus:o,modal:m!==!1,restoreFocus:"popup",children:P})}),tkt=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(JSt.Provider,{value:r,children:a.jsxs(K3,{ref:n,...s,children:[o&&l===!0&&a.jsx(LL,{ref:i.context.internalBackdropRef,inert:fP(!c)}),t.children]})}):null});function Aor({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=S_(l,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?"intentional":{mouse:i==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}},outsidePress(m){if(!e.context.outsidePressEnabledRef.current||"button"in m&&m.button!==0)return!1;if("touches"in m){if(m.type==="touchend"){if(m.changedTouches.length!==1||m.touches.length!==0)return!1}else if(m.touches.length!==1)return!1}const v=qi(m);if(h&&!s){if(i){const y=e.context.internalBackdropRef.current,x=e.context.backdropRef.current;return y||x?y===v||x===v||ln(v,o)&&!v?.hasAttribute("data-base-ui-portal"):!0}return!0}return!1},escapeKey:h});return Pwt(r&&i===!0,o),e.useContextCallback("onNestedDialogOpen",(m,v)=>{u(m),f(v)}),jt(()=>(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]),tL(e,{activeTriggerProps:p.reference,inactiveTriggerProps:p.trigger,popupProps:p.floating,nestedOpenDialogCount:c,nestedOpenDrawerCount:d}),null}const Por={...rL,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 $or extends k_{constructor(t,n,r){const s=new O_,i=Ror(t,s,n,r);super(i,Mor(s),Por)}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};DH(r,t,n.trigger),this.update(r)}}function Ror(e,t,n,r=!1){const s={...nL(),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=LH(t,n,r),s}function Mor(e){return{popupRef:g.createRef(),backdropRef:g.createRef(),internalBackdropRef:g.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:e,onOpenChange:void 0,onOpenChangeComplete:void 0}}function nkt(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=MH((A,P)=>new $or({open:s,openProp:r,activeTriggerId:h,triggerIdProp:f,...k},A,P),!0);j.useControlledProp("openProp",r),j.useControlledProp("triggerIdProp",f),j.useSyncedValues(k),j.useContextCallback("onOpenChange",i),j.useContextCallback("onOpenChangeComplete",o);const C=j.useState("open"),T=j.useState("mounted"),_=j.useState("payload");Zft(j,C),J3(j);const{forceUnmount:N}=eL(C,j);g.useImperativeHandle(u,()=>({unmount:N,close:()=>j.setOpen(!1,Yt(H3))}),[N,j]);const I=C||T;return a.jsxs(YSt.Provider,{value:j,children:[d&&a.jsx(Y3,{handle:d,store:j}),I&&a.jsx(Aor,{store:j,parentContext:b?.context,isDrawer:p}),typeof n=="function"?n({payload:_}):n]})}function Dor(e){return nkt("dialog",e)}const Lor=g.forwardRef(function(t,n){const{render:r,className:s,style:i,children:o,...l}=t,c=uke(),u=hf(),d=u.useState("open"),f=u.useState("nested"),h=u.useState("transitionStatus"),p=u.useState("nestedOpenDialogCount"),m=u.useState("mounted"),v=u.useStateSetter("viewportElement"),y=p>0;return cn("div",t,{enabled:c||m,state:{open:d,nested:f,transitionStatus:h,nestedDialogOpen:y},ref:[n,v],stateAttributesMapping:ekt,props:[{role:"presentation",hidden:!m,style:{pointerEvents:d?void 0:"none"},children:o},l]})}),rkt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,id:o,...l}=t,c=hf(),u=Zi(o);return c.useSyncedValueWithCleanup("titleElementId",u),cn("h2",t,{ref:n,props:[{id:u},l]})}),skt=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=sL(d)??h;if(!m)throw new Error(Nr(79));const v=Zi(c),y=m.useState("floatingRootContext"),x=m.useState("isOpenedByTrigger",v),b=m.useState("triggerPopupId",v),S=g.useRef(null),{registerTrigger:k,isMountedByThisTrigger:j}=X3(v,S,m,{payload:u}),{getButtonProps:C,buttonRef:T}=gd({disabled:o,native:l}),_=w_(y),N=gSe(()=>m.select("open"),P=>{m.set("openMethod",P)}),I={disabled:o,open:x},A=m.useState("triggerProps",j);return cn("button",t,{state:I,ref:[T,n,k,S],props:[_.reference,A,N,{[_0e]:"",id:v,"aria-haspopup":"dialog","aria-expanded":x,"aria-controls":b},f,C],stateAttributesMapping:cP})});let Pc=(function(e){return e.nestedDrawers="--nested-drawers",e.height="--drawer-height",e.frontmostHeight="--drawer-frontmost-height",e.swipeMovementX="--drawer-swipe-movement-x",e.swipeMovementY="--drawer-swipe-movement-y",e.snapPointOffset="--drawer-snap-point-offset",e.swipeStrength="--drawer-swipe-strength",e})({}),M1=(function(e){return e.swipeProgress="--drawer-swipe-progress",e})({});const ikt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,forceRender:o=!1,...l}=t,c=hf(),u=c.useState("open"),d=c.useState("nested"),f=c.useState("mounted"),h=c.useState("transitionStatus");return cn("div",t,{state:{open:u,transitionStatus:h},ref:[c.context.backdropRef,n],stateAttributesMapping:C_,props:[{role:"presentation",hidden:!f,style:{pointerEvents:u?void 0:"none",userSelect:"none",WebkitUserSelect:"none",[M1.swipeProgress]:"0",[Pc.swipeStrength]:"1"}},l],enabled:o||!d})}),zor=uK,okt="data-drawer-content",xQ=g.forwardRef(function(t,n){const{render:r,className:s,style:i,...o}=t;return hf(),cn("div",t,{ref:n,props:[{[okt]:""},o]})}),akt=XSt,For=g.createContext(void 0);function lkt(){return g.useContext(For)}let T1=(function(e){return e[e.open=C8.open]="open",e[e.closed=C8.closed]="closed",e[e.startingStyle=C8.startingStyle]="startingStyle",e[e.endingStyle=C8.endingStyle]="endingStyle",e.expanded="data-expanded",e.nestedDrawerOpen="data-nested-drawer-open",e.nestedDrawerSwiping="data-nested-drawer-swiping",e.swipeDismiss="data-swipe-dismiss",e.swipeDirection="data-swipe-direction",e.swiping="data-swiping",e})({});const ckt=g.createContext(void 0);function dK(e){const t=g.useContext(ckt);if(e!==!0&&t===void 0)throw new Error(Nr(90));return t}function ukt(e,t){const n=e+t;return n>=0?t:-Math.sqrt(-n)-e}function SUe(e,t,n){if(!Number.isFinite(t)||t<=0)return null;if(typeof e=="number")return Number.isFinite(e)?e<=1?Pi(e,0,1)*t:e:null;const r=e.trim();if(r.endsWith("px")){const s=Number.parseFloat(r);return Number.isFinite(s)?s:null}if(r.endsWith("rem")){const s=Number.parseFloat(r);return Number.isFinite(s)?s*n:null}return null}function KB(e,t){let n=-1,r=1/0;for(let s=0;s<e.length;s+=1){const i=Math.abs(e[s]-t);i<r&&(r=i,n=s)}return n}function dkt(){const e=hf(),{snapPoints:t,activeSnapPoint:n,setActiveSnapPoint:r,popupHeight:s}=dK(),i=e.useState("viewportElement"),[o,l]=g.useState(0),[c,u]=g.useState(16),d=ft(()=>{const m=wr(i).documentElement;l(i?i.offsetHeight:m.clientHeight);const v=parseFloat(getComputedStyle(m).fontSize);Number.isFinite(v)&&u(v)});jt(()=>{if(d(),!i||typeof ResizeObserver!="function")return;const p=new ResizeObserver(d);return p.observe(i),()=>{p.disconnect()}},[d,i]);const f=g.useMemo(()=>{if(!t||t.length===0||o<=0||s<=0)return[];const p=Math.min(s,o),m=t.map(x=>{const b=SUe(x,o,c);if(b===null)return null;const S=Pi(b,0,p);return{value:x,height:S,offset:Math.max(0,s-S)}}).filter(x=>!!x);if(m.length<=1)return m;const v=[],y=[];for(let x=m.length-1;x>=0;x-=1){const b=m[x];y.some(k=>Math.abs(k-b.height)<=1)||(y.push(b.height),v.push(b))}return v.reverse(),v},[s,c,t,o]),h=g.useMemo(()=>{if(n===null)return;const p=f.find(x=>Object.is(x.value,n));if(p)return p;const m=Math.min(s,o),v=SUe(n,o,c);if(v===null)return;const y=Pi(v,0,m);return f[KB(f.map(x=>x.height),y)]},[n,s,f,c,o]);return{snapPoints:t,activeSnapPoint:n,setActiveSnapPoint:r,popupHeight:s,viewportHeight:o,resolvedSnapPoints:f,activeSnapPointOffset:h?.offset??null}}const fkt=g.createContext(null);function Bor(){return g.useContext(fkt)}let kUe=!1;function Uor(){kUe||(typeof CSS<"u"&&"registerProperty"in CSS&&([Pc.swipeMovementX,Pc.swipeMovementY,Pc.snapPointOffset].forEach(e=>{try{CSS.registerProperty({name:e,syntax:"<length>",inherits:!1,initialValue:"0px"})}catch{}}),[{name:M1.swipeProgress,initialValue:"0"},{name:Pc.swipeStrength,initialValue:"1"}].forEach(({name:e,initialValue:t})=>{try{CSS.registerProperty({name:e,syntax:"<number>",inherits:!1,initialValue:t})}catch{}})),kUe=!0)}const Vor={...C_,expanded(e){return e?{[T1.expanded]:""}:null},nestedDrawerOpen(e){return e?{[T1.nestedDrawerOpen]:""}:null},nestedDrawerSwiping(e){return e?{[T1.nestedDrawerSwiping]:""}:null},swipeDirection(e){return{[T1.swipeDirection]:e}},swiping(e){return e?{[T1.swiping]:""}:null}},hkt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,finalFocus:o,initialFocus:l,...c}=t,u=hf(),d=u.context.popupRef,{swipeDirection:f,frontmostHeight:h,hasNestedDrawer:p,nestedSwiping:m,nestedSwipeProgressStore:v,onPopupHeightChange:y,notifyParentFrontmostHeight:x,notifyParentHasNestedDrawer:b}=dK(),S=u.useState("descriptionElementId"),k=u.useState("disablePointerDismissal"),j=u.useState("floatingRootContext"),C=u.useState("popupProps"),T=u.useState("modal"),_=u.useState("mounted"),N=u.useState("nested"),I=u.useState("nestedOpenDrawerCount"),A=u.useState("transitionStatus"),P=u.useState("open"),L=u.useState("openMethod"),F=u.useState("titleElementId"),Q=u.useState("role"),q=j.useState("floatingId"),B=c.id??q,V=Bor();uke();const{snapPoints:H,activeSnapPoint:D,activeSnapPointOffset:K}=dkt(),M=I>0,$=V?.swiping??!1,z=V?.swipeStrength??null,[U,G]=g.useState(0),ne=g.useRef(0),X=ft(()=>{const he=d.current;if(!he)return;const ke=he.offsetHeight;if(ne.current>0&&h>ne.current&&ke>ne.current)return;if(ne.current>0&&p){const Ze=ne.current;G(Ze),y(Ze);return}const Ve=ke;Ve!==ne.current&&(ne.current=Ve,G(Ve),y(Ve))});jt(()=>{if(!_){ne.current=0,G(0),y(0);return}const he=d.current;if(!he||(Uor(),X(),typeof ResizeObserver!="function"))return;const ke=new ResizeObserver(X);return ke.observe(he),()=>{ke.disconnect()}},[X,_,M,y,d]),jt(()=>{const he=()=>{const Ve=d.current;if(!Ve)return;const Ze=v.getSnapshot();Ze>0?Ve.style.setProperty(M1.swipeProgress,`${Ze}`):Ve.style.setProperty(M1.swipeProgress,"0")};he();const ke=v.subscribe(he),Ee=d.current;return()=>{ke(),Ee&&Ee.style.setProperty(M1.swipeProgress,"0")}},[v,d]),jt(()=>{if(P)return x?.(h),()=>{x?.(0)}},[h,P,x]),jt(()=>b?(b(P||A==="ending"),()=>{b(!1)}):void 0,[b,P,A]),Cl({open:P,ref:d,onComplete(){P&&u.context.onOpenChangeComplete?.(!0)}});const ee=l===void 0?d:l,ie=u.useStateSetter("popupElement"),fe={open:P,nested:N,transitionStatus:A,expanded:D===1,nestedDrawerOpen:M,nestedDrawerSwiping:m,swipeDirection:f,swiping:$};let te;U&&!(!p&&A!=="ending")&&(te=`${U}px`);const re=H&&H.length>0&&(f==="down"||f==="up");let le=null;re&&K!==null&&(le=f==="up"?-K:K);let pe=V?V.getDragStyles():ai;if(re&&f==="down"){const he=K??0,ke=Number.parseFloat(String(pe[Pc.swipeMovementY]));$&&Number.isFinite(ke)?pe={...pe,transform:void 0,[Pc.swipeMovementY]:`${ukt(he,ke)}px`}:pe={...pe,transform:void 0}}const ve=cn("div",t,{state:fe,props:[C,{id:B,"aria-labelledby":F,"aria-describedby":S,role:Q,...gk,hidden:!_,onKeyDown(he){kk.has(he.key)&&he.stopPropagation()},style:{...pe,[M1.swipeProgress]:"0",[Pc.nestedDrawers]:I,[Pc.height]:te,[Pc.snapPointOffset]:typeof le=="number"?`${le}px`:"0px",[Pc.frontmostHeight]:h?`${h}px`:void 0,[Pc.swipeStrength]:typeof z=="number"&&Number.isFinite(z)&&z>0?`${z}`:"1"}},c],ref:[n,d,ie],stateAttributesMapping:Vor});return a.jsx(lP,{context:j,openInteractionType:L,disabled:!_,closeOnFocusOut:!k,initialFocus:ee,returnFocus:o,modal:T!==!1,restoreFocus:"popup",children:ve})}),pkt=tkt;var OUe,jUe;function mkt(e){const{children:t,open:n,defaultOpen:r=!1,onOpenChange:s,onOpenChangeComplete:i,disablePointerDismissal:o=!1,modal:l=!0,actionsRef:c,handle:u,triggerId:d,defaultTriggerId:f=null,swipeDirection:h="down",snapToSequentialPoints:p=!1,snapPoints:m,snapPoint:v,defaultSnapPoint:y,onSnapPointChange:x}=e,b=dK(!0),S=b?.onNestedSwipeProgressChange,k=b?.onNestedFrontmostHeightChange,j=b?.onNestedSwipingChange,C=b?.onNestedDrawerPresenceChange,[T,_]=g.useState(0),[N,I]=g.useState(0),[A,P]=g.useState(!1),[L,F]=g.useState(!1),[Q]=g.useState(qor),q=y!==void 0?y:m?.[0]??null,B=v!==void 0,[V,H]=Xd({controlled:v,default:q,name:"Drawer",state:"snapPoint"}),D=g.useRef(!1),K=g.useRef(!1),M=ft((se,re)=>{const le=re??Yt(Io);x?.(se,le),!le.isCanceled&&H(se)}),$=g.useMemo(()=>B||!m||m.length===0?V:V===null||!m.some(se=>Object.is(se,V))?q:V,[V,B,q,m]),z=ft(se=>{_(se),!D.current&&se>0&&I(se)}),U=ft(se=>{if(se>0){D.current=!0,I(se);return}D.current=!1,T>0&&I(T)}),G=ft(se=>{P(se)}),ne=ft(se=>{Q.set(se),S?.(se)}),X=ft(se=>{F(se),j?.(se)}),ee=ft((se,re)=>{s?.(se,re),!re.isCanceled&&!se&&m&&m.length>0&&M(q,Yt(re.reason,re.event,re.trigger))}),ie=g.useMemo(()=>({swipeDirection:h,swipeAreaActiveRef:K,snapToSequentialPoints:p,snapPoints:m,activeSnapPoint:$,setActiveSnapPoint:M,frontmostHeight:N,popupHeight:T,hasNestedDrawer:A,nestedSwiping:L,nestedSwipeProgressStore:Q,onNestedDrawerPresenceChange:G,onPopupHeightChange:z,onNestedFrontmostHeightChange:U,onNestedSwipingChange:X,onNestedSwipeProgressChange:ne,notifyParentFrontmostHeight:k,notifyParentSwipingChange:j,notifyParentSwipeProgressChange:S,notifyParentHasNestedDrawer:C}),[$,N,A,L,Q,C,S,j,k,G,U,ne,X,z,T,M,m,p,K,h]),fe=typeof t=="function"?se=>a.jsxs(g.Fragment,{children:[OUe||(OUe=a.jsx(CUe,{})),t(se)]}):a.jsxs(g.Fragment,{children:[jUe||(jUe=a.jsx(CUe,{})),t]}),te=nkt("drawer",{open:n,defaultOpen:r,onOpenChange:ee,onOpenChangeComplete:i,disablePointerDismissal:o,modal:l,actionsRef:c,handle:u,triggerId:d,defaultTriggerId:f,children:fe});return a.jsx(ckt.Provider,{value:ie,children:te})}function qor(){let e=0;const t=new Set;return{getSnapshot:()=>e,set(n){const r=Number.isFinite(n)?n:0;r!==e&&(e=r,t.forEach(s=>{s()}))},subscribe(n){return t.add(n),()=>{t.delete(n)}}}}function CUe(){const e=lkt(),t=hf(!1),n=e?.setDrawerOpen,r=e?.removeDrawer,s=t.useState("open"),i=t.useState("nestedOpenDialogCount"),o=t.useState("popupElement"),l=i===0;return jt(()=>{if(r)return()=>{r(t)}},[r,t]),jt(()=>{n?.(t,s)},[s,n,t]),g.useEffect(()=>{if(!s||!l||!S4)return;const u=bi(o).CloseWatcher;if(!u)return;function d(p){t.select("open")&&t.setOpen(!1,Yt(Ekn,p))}const f=new u,h=Fr(f,"close",d);return()=>{h(),f.destroy()}},[t,l,s,o]),null}function gkt(e,t=!1){const{overflowY:n}=ud(e);return n!=="auto"&&n!=="scroll"?!1:t?e.clientHeight>0:e.scrollHeight>e.clientHeight}function Qor(e,t=!1){const{overflowX:n}=ud(e);return n!=="auto"&&n!=="scroll"?!1:t?e.clientWidth>0:e.scrollWidth>e.clientWidth}function Lpe(e,t,n=!1){return t==="vertical"?gkt(e,n):Qor(e,n)}function Zor(e,t,n){let r=e;for(;ni(r)&&r!==t&&!iv(r);){for(const s of n)if(Lpe(r,s))return!0;r=gv(r)}return!1}function rI(e,t,n="vertical",r=!1){let s=ni(e)?e:null;for(;ni(s)&&s!==t&&!iv(s);){if(Lpe(s,n,r))return s;s=gv(s)}return Lpe(t,n,r)?t:null}function YB(e,t,n){return typeof e?.elementFromPoint=="function"?e.elementFromPoint(t,n):null}const Wor=40,Hor=10,Gor=1,Kor=50,_Ue=16,Yor=80,Xor='button,a,input,select,textarea,label,[role="button"]';function Cy(e,t,n){switch(e){case"up":return-n;case"down":return n;case"left":return-t;case"right":return t;default:return 0}}function Jor(e){const n=bi(e).getComputedStyle(e).transform;let r=0,s=0,i=1;if(n&&n!=="none"){const o=n.match(/matrix(?:3d)?\(([^)]+)\)/);if(o){const l=o[1].split(", ").map(parseFloat);l.length===6?(r=l[4],s=l[5],i=Math.sqrt(l[0]*l[0]+l[1]*l[1])):l.length===16&&(r=l[12],s=l[13],i=l[0])}}return{x:r,y:s,scale:i}}function _9(e){return Number.isFinite(e)&&e>0?e:null}function TUe(e,t){return`translate3d(${e.x}px,${e.y}px,0) scale(${t})`}function ear(e){return e%2===1}function Roe(e,t,n){const r=e[n];if(typeof r=="function")try{r.call(e,t)}catch(s){if(s&&typeof s=="object"&&"name"in s&&s.name==="NotFoundError")return;throw s}}function tar(e){const{enabled:t,directions:n,elementRef:r,movementCssVars:s,canStart:i,ignoreSelectorWhenTouch:o=!0,ignoreScrollableAncestors:l=!1,swipeThreshold:c,onDismiss:u,onProgress:d,onCancel:f,onSwipeStart:h,onRelease:p,onSwipingChange:m,trackDrag:v=!0}=e,y=Xor,x=n.length===1?n[0]:void 0,b=Math.max(0,typeof c=="number"?c:Wor),S=n.includes("left"),k=n.includes("right"),j=n.includes("up"),C=n.includes("down"),T=S||k,_=j||C,N=g.useMemo(()=>{const ge=[];return _&&ge.push("vertical"),T&&ge.push("horizontal"),ge},[T,_]),[I,A]=g.useState(void 0),[P,L]=g.useState(!1),[F,Q]=g.useState(!1),q=g.useRef({x:0,y:0}),B=g.useRef({x:0,y:0}),V=g.useRef(null),H=g.useRef({x:0,y:0,scale:1}),D=g.useRef(void 0),K=g.useRef(0),M=g.useRef(!1),$=g.useRef({x:0,y:0}),z=g.useRef(null),U=g.useRef(!1),G=g.useRef(!1),ne=g.useRef(null),X=g.useRef(!1),ee=g.useRef(!1),ie=g.useRef({width:0,height:0}),fe=g.useRef(0),te=g.useRef(b),se=g.useRef(null),re=g.useRef(null),le=g.useRef(null),pe=g.useRef({x:0,y:0}),ve=g.useRef(null),he=g.useRef(!1),ke=g.useRef(null),Ee=ft(ge=>{he.current!==ge&&(he.current=ge,L(ge),m?.(ge))});function Ve(ge){if(!ge)return;const Pe=r.current,Xe=se.current;if(!Pe||!Xe)return;const St=Xe({element:Pe,direction:ge});te.current=Math.max(0,St)}const Ze=ft((ge,Pe)=>{const Xe=Number.isFinite(ge)?Pi(ge,0,1):0,St=Xe!==fe.current;let Ft=!1;if(Pe){const qt=ve.current;Ft=!qt||qt.deltaX!==Pe.deltaX||qt.deltaY!==Pe.deltaY||qt.direction!==Pe.direction}!St&&!Ft||(fe.current=Xe,Pe?ve.current=Pe:St&&(ve.current=null),d?.(Xe,Pe))}),Fe=ft(ge=>{const Pe=r.current;if(!v||!Pe){ge||(ke.current=null);return}const Xe=Pe.style,St=ke.current;ge?(St||(ke.current=[Xe.transition,Xe.transform]),Xe.transition="none"):St&&([Xe.transition,Xe.transform]=St,ke.current=null);const Ft=B.current,qt=H.current,yt=Ft.x-qt.x,xn=Ft.y-qt.y;ge&&(Xe.transform=TUe(Ft,qt.scale)),Xe.setProperty(s.x,`${yt}px`),Xe.setProperty(s.y,`${xn}px`)});function Ae(ge,Pe){if(Pe===null)return;const Xe=le.current;if(Xe&&Pe>Xe.time){const St=Math.max(Pe-Xe.time,_Ue);pe.current={x:(ge.x-Xe.x)/St,y:(ge.y-Xe.y)/St}}le.current={x:ge.x,y:ge.y,time:Pe}}const ze=g.useCallback(()=>{A(void 0),Ee(!1),Q(!1),Ze(0),te.current=b,se.current=null,q.current={x:0,y:0},B.current={x:0,y:0},H.current={x:0,y:0,scale:1},D.current=void 0,K.current=0,M.current=!1,$.current={x:0,y:0},z.current=null,U.current=!1,V.current=null,G.current=!1,ne.current=null,X.current=!1,ee.current=!1,ie.current={width:0,height:0},re.current=null,le.current=null,pe.current={x:0,y:0},ve.current=null,Fe(!1)},[Ee,b,Fe,Ze]);function je(ge){if("touches"in ge){const Pe=ge.touches[0];return Pe?{x:Pe.clientX,y:Pe.clientY}:null}return{x:ge.clientX,y:ge.clientY}}function Ce(ge){return"touches"in ge?!0:ge.pointerType==="touch"}function Ue(ge,Pe){const Xe=r.current?.getRootNode();return YB(Xe,ge.x,ge.y)??qi(Pe)}function ae(ge,Pe){return T&&!_?rI(ge,Pe,"horizontal"):_&&!T?rI(ge,Pe,"vertical"):rI(ge,Pe,"vertical")??rI(ge,Pe,"horizontal")}function me(ge,Pe,Xe){X.current=!1;const St=Ce(ge),Ft=Ue(Pe,ge.nativeEvent),yt=wr(r.current).body,xn=St&&yt?ae(Ft,yt):null,vn=Xe?.ignoreScrollableTarget??!1;if(xn&&!vn||(X.current=!!(xn&&vn),(Ft?Ft.closest(y):!1)&&(!St||o)))return!1;const Ie=r.current;if(l&&Ie&&Ft&&N.length>0&&!(Xe?.ignoreScrollableAncestors??!1)&&Zor(Ft,Ie,N))return!1;if(M.current=!1,D.current=void 0,K.current=0,q.current=Pe,re.current=_9(ge.timeStamp),$.current=Pe,V.current=Pe,te.current=b,se.current=typeof c=="function"?c:null,Ie){ie.current={width:Ie.offsetWidth,height:Ie.offsetHeight},Ve(x);const We=Jor(Ie);H.current=We,B.current={x:We.x,y:We.y},Ae({x:We.x,y:We.y},re.current),"touches"in ge||Roe(Ie,ge.pointerId,"setPointerCapture")}return h?.(ge.nativeEvent),Ee(!0),z.current=null,U.current=!0,Ze(0),Fe(!0),!0}function Ne(){Te(),X.current=!1,V.current=null}function Te(){G.current=!1,ne.current=null}function ce(ge){if(Ne(),!he.current)return;Ee(!1),z.current=null;const Pe=H.current;B.current={x:Pe.x,y:Pe.y},A(void 0),ee.current=!1,Fe(!1);const Xe=r.current;Xe&&Roe(Xe,ge.pointerId,"releasePointerCapture"),Ze(0,{deltaX:0,deltaY:0,direction:void 0}),f?.(ge.nativeEvent)}function ye(ge,Pe){const Xe=yt=>Math.sign(yt)*Math.abs(yt)**.5,St=(yt,xn,vn)=>!xn&&yt<0||!vn&&yt>0?Xe(yt):yt,Ft=T?St(ge,S,k):Xe(ge),qt=_?St(Pe,j,C):Xe(Pe);return{x:Ft,y:qt}}function Se(ge,Pe,Xe){const St=(yt,xn,vn,we,Ie)=>yt>0&&xn<=0&&we||yt<0&&xn>=Math.max(0,vn)&&Ie,Ft=Math.abs(Pe),qt=Math.abs(Xe);return _&&Xe!==0&&(!T||qt>=Ft)?St(Xe,ge.scrollTop,ge.scrollHeight-ge.clientHeight,C,j):T&&Pe!==0&&(!_||Ft>qt)?St(Pe,ge.scrollLeft,ge.scrollWidth-ge.clientWidth,k,S):null}const $e=ft(ge=>{if(!t||ge.defaultPrevented||ge.nativeEvent.defaultPrevented||!("touches"in ge)&&ge.button!==0)return;const Pe=je(ge);!Pe||(G.current=!0,ne.current=Pe,X.current=!1,ee.current=!("touches"in ge),!(i?i(Pe,{nativeEvent:ge.nativeEvent,direction:x}):!0))||me(ge,Pe)&&Te()});function De(ge,Pe,Xe){if(!t||!he.current)return;const St=qi(ge.nativeEvent);if(Ce(ge)&&!X.current){const Ur=ge.currentTarget;if(ae(St,Ur))return}if("touches"in ge||ge.preventDefault(),U.current&&(U.current=!1,v)){q.current=Pe;const Ur=_9(ge.timeStamp);Ur!==null&&(re.current=Ur)}const Ft=Pe.x,qt=Pe.y,yt=Xe.x,xn=Xe.y;(xn<0&&qt>$.current.y||xn>0&&qt<$.current.y)&&($.current={x:$.current.x,y:qt}),(yt<0&&Ft>$.current.x||yt>0&&Ft<$.current.x)&&($.current={x:Ft,y:$.current.y});const vn=Ft-q.current.x,we=qt-q.current.y,Ie=qt-$.current.y,We=Ft-$.current.x;let ot=z.current;ot===null&&T&&_&&Math.sqrt(vn*vn+we*we)>=Gor&&(ot=Math.abs(vn)>Math.abs(we)?"horizontal":"vertical",z.current=ot);let dt;if(!D.current)ot==="vertical"?we>0?dt="down":we<0&&(dt="up"):ot==="horizontal"?vn>0?dt="right":vn<0&&(dt="left"):Math.abs(vn)>=Math.abs(we)?dt=vn>0?"right":"left":dt=we>0?"down":"up",dt&&(dt==="left"&&S||dt==="right"&&k||dt==="up"&&j||dt==="down"&&C)&&(D.current=dt,K.current=Cy(dt,vn,we),A(dt),Ve(dt));else{const Ur=D.current,dr=Cy(Ur,We,Ie);dr>te.current?(M.current=!1,A(Ur)):!(S&&k)&&!(j&&C)&&K.current-dr>=Hor&&(M.current=!0)}const Zt=ye(vn,we);let Bt=H.current.x,Et=H.current.y;ot==="horizontal"?T&&(Bt+=Zt.x):(ot==="vertical"||T&&(Bt+=Zt.x),_&&(Et+=Zt.y));const mt=B.current,gn=Bt!==mt.x||Et!==mt.y;B.current={x:Bt,y:Et},gn&&Fe(!0),Ae({x:Bt,y:Et},_9(ge.timeStamp));const dn=Bt-H.current.x,Pn=Et-H.current.y,gr={deltaX:dn,deltaY:Pn,direction:D.current};let xs=0;const zr=x??D.current;if(zr){const Ur=zr==="left"||zr==="right"?ie.current.width:ie.current.height,dr=H.current.scale||1,Ti=Cy(zr,dn,Pn);Ur>0&&dr>0&&Ti>0&&(xs=Ti/(Ur*dr))}Ze(xs,gr)}const Qe=ft(ge=>{if(!t)return;const Pe=B.current,Xe=H.current,St=Pe.x-Xe.x,Ft=Pe.y-Xe.y,qt={deltaX:St,deltaY:Ft,direction:D.current};if(!he.current){Ne(),Ze(0,qt);return}Ee(!1),z.current=null,Ne(),ee.current=!1;const yt=r.current;yt&&("touches"in ge||Roe(yt,ge.pointerId,"releasePointerCapture"));const xn=St,vn=Ft,we=re.current,Ie=_9(ge.timeStamp),We=we!==null&&Ie!==null&&Ie>we?Ie-we:0,ot=We>0?Math.max(We,Kor):0,dt=ot>0?xn/ot:0,Zt=ot>0?vn/ot:0;let Bt=pe.current.x,Et=pe.current.y;const mt=le.current;if(mt&&Ie!==null&&Ie>=mt.time){const xs=Ie-mt.time;if(xs<=Yor){const zr=Math.max(xs,_Ue),Ur=Pe.x-mt.x,dr=Pe.y-mt.y,Ti=Ur/zr,Ei=dr/zr;Ti!==0&&(Bt=Ti),Ei!==0&&(Et=Ei)}else Bt=0,Et=0}const gn=p?.({event:ge.nativeEvent,direction:D.current,deltaX:xn,deltaY:vn,velocityX:dt,velocityY:Zt,releaseVelocityX:Bt,releaseVelocityY:Et}),dn=typeof gn=="boolean";if(M.current&&!dn){B.current={x:Xe.x,y:Xe.y},A(void 0),Fe(!1),Ze(0,qt);return}let Pn=!1,gr;if(dn)Pn=gn,gr=D.current??x;else for(const xs of n)if(Cy(xs,xn,vn)>te.current){Pn=!0,gr=xs;break}Pn&&gr?(A(gr),Q(!0),Fe(!1),u?.(ge.nativeEvent,{direction:gr})):(B.current={x:Xe.x,y:Xe.y},A(void 0),Fe(!1),Ze(0,qt))}),tt=ft(ge=>{const Pe=je(ge);if(!Pe)return;let Xe=!1;if(!("touches"in ge)){const qt=ear(ge.buttons);if(qt&&(ee.current=!0),ge.buttons!==0&&!qt){ce(ge);return}if(ge.buttons===0&&ee.current){if(!he.current){Qe(ge);return}Xe=!0}}if(!P&&G.current){if(!Ce(ge)&&(ge.defaultPrevented||ge.nativeEvent.defaultPrevented)){Ne();return}if(i?i(Pe,{nativeEvent:ge.nativeEvent,direction:x}):!0){const yt=ne.current;let xn=!1;if(Ce(ge)){const we=r.current;if(yt&&we){const Ie=Ue(Pe,ge.nativeEvent),ot=wr(we).body,dt=ot?ae(Ie,ot):null;if(dt&&(ln(we,dt)||ln(dt,we))){const Zt=Pe.x-yt.x,Bt=Pe.y-yt.y,Et=Se(dt,Zt,Bt);if(Et===!1)return;Et===!0&&(xn=!0)}}}me(ge,Pe,{ignoreScrollableTarget:xn,ignoreScrollableAncestors:xn})&&(yt&&xn?(Te(),q.current=yt,$.current=yt,V.current=yt,U.current=!1):(Te(),X.current=!1))}}const St=V.current,Ft=St===null?{x:0,y:0}:{x:Pe.x-St.x,y:Pe.y-St.y};V.current=Pe,De(ge,Pe,Ft),Xe&&!("touches"in ge)&&Qe(ge)}),st=ft((ge,Pe)=>{tt({touches:ge.touches,currentTarget:Pe,nativeEvent:ge,defaultPrevented:ge.defaultPrevented,timeStamp:ge.timeStamp})}),He=g.useCallback(()=>{const ge=he.current,Pe=B.current,Xe=H.current,St=Pe.x-Xe.x,Ft=Pe.y-Xe.y;return!ge&&St===0&&Ft===0&&!F?{[s.x]:"0px",[s.y]:"0px"}:{transition:ge?"none":void 0,transform:ge?TUe(Pe,Xe.scale):void 0,[s.x]:`${St}px`,[s.y]:`${Ft}px`}},[F,s]),Le=g.useCallback(()=>t?{onPointerDown:$e,onPointerMove:tt,onPointerUp:Qe,onPointerCancel:Qe}:{},[t,Qe,tt,$e]),wt=g.useCallback(()=>t?{onTouchStart:$e,onTouchMove:tt,onTouchEnd:Qe,onTouchCancel:Qe}:{},[t,Qe,tt,$e]);return{swiping:P,swipeDirection:I,dragDismissed:F,getPointerProps:Le,getTouchProps:wt,moveNative:st,getDragStyles:He,reset:ze}}const vkt=rkt,nar=skt,rar=g.createContext(void 0);function sar(){return g.useContext(rar)}const zpe=10,EUe=.5,IUe=.5,iar=300,NUe=4,AUe=.2,oar=4,Moe=80,PUe=360,$Ue=.1,aar=1,RUe=6,lar=2,car=`[${okt}]`,ykt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,children:o,...l}=t,c=hf(),u=c.context.popupRef,d=c.context.backdropRef,{swipeDirection:f,notifyParentSwipingChange:h,notifyParentSwipeProgressChange:p,frontmostHeight:m,snapToSequentialPoints:v,swipeAreaActiveRef:y}=dK(),x=lkt(),{snapPoints:b,resolvedSnapPoints:S,activeSnapPoint:k,activeSnapPointOffset:j,setActiveSnapPoint:C,popupHeight:T}=dkt(),_=c.useState("open"),N=c.useState("mounted"),I=c.useState("nested"),A=c.useState("nestedOpenDrawerCount"),P=c.useState("viewportElement"),L=c.useState("popupElement"),F=x?.visualStateStore,Q=A>0,q=f==="left"||f==="right"?"horizontal":"vertical",B=q==="vertical",V=B?"horizontal":"vertical",[H,D]=g.useState(null),K=g.useRef(void 0),M=g.useRef(null),$=xS(),z=g.useRef(!1),U=g.useRef(!1),G=g.useRef(""),ne=g.useRef(!1),X=g.useRef(!1),ee=g.useRef(null),ie=sar(),fe=g.useMemo(()=>{if(!b||b.length<2||S.length<2||f!=="down"&&f!=="up")return null;const ae=S.map(ce=>ce.offset).sort((ce,ye)=>ce-ye),me=ae[0],Te=ae[1]-me;return{minOffset:me,range:Te}},[S,b,f]),te=g.useMemo(()=>!fe||j===null?null:Pi((j-fe.minOffset)/fe.range,0,1),[j,fe]),se=g.useMemo(()=>b&&b.length>0&&(f==="down"||f==="up")?f==="down"?["down","up"]:["up","down"]:[f],[b,f]),re=ft(ae=>{u.current?.toggleAttribute(T1.swipeDismiss,ae),d.current?.toggleAttribute(T1.swipeDismiss,ae)}),le=ft(()=>{re(!1),u.current?.removeAttribute(CN.endingStyle),D(null)}),pe=ft(()=>{U.current&&(U.current=!1,h?.(!1))}),ve=ft((ae,me,Ne)=>{const Te=_&&!I&&me,ce=Te?ae:0,ye=_&&me?ae:0;Ne&&p&&(p(ye),ye<=0&&pe()),F?.set({swipeProgress:ce,frontmostHeight:ce>0?m:0});const Se=d.current;if(!Se)return;const $e=Te&&ce>0;Se.style.setProperty(M1.swipeProgress,$e?`${ce}`:"0"),$e&&m>0?Se.style.setProperty(Pc.height,`${m}px`):Se.style.removeProperty(Pc.height)});function he(ae,me,Ne,Te,ce,ye,Se,$e){const De=xkt(ae,me);if(De<=0)return null;const tt=((me==="down"||me==="up")&&b&&b.length>0?j??0:0)+Cy(me,Ne,Te),st=Math.max(0,De-tt);if(st<=0)return null;const He=Cy(me,Se,$e),Le=Math.abs(He)>0?He:Cy(me,ce,ye);if(Le<=AUe)return null;const wt=Pi(Le,AUe,oar),Pe=(Pi(st/wt,Moe,PUe)-Moe)/(PUe-Moe);return $Ue+Pe*(aar-$Ue)}function ke(ae){if(U.current||!ae)return;const me=ae.direction??f,Ne=Cy(me,ae.deltaX,ae.deltaY);Math.abs(Ne)<zpe||(U.current=!0,h?.(!0))}const Ee=tar({enabled:N&&!Q,directions:se,elementRef:c.context.popupRef,ignoreSelectorWhenTouch:!1,ignoreScrollableAncestors:!0,movementCssVars:{x:Pc.swipeMovementX,y:Pc.swipeMovementY},onSwipeStart(ae){if("touches"in ae||ae.pointerType==="touch")return;const me=u.current,Te=wr(me).getSelection?.();if(!Te||Te.isCollapsed)return;const ce=Cr(Te.anchorNode)?Te.anchorNode:Te.anchorNode?.parentElement,ye=Cr(Te.focusNode)?Te.focusNode:Te.focusNode?.parentElement;!ln(me,ce)&&!ln(me,ye)||Te.removeAllRanges()},onSwipingChange(ae){z.current=ae,Doe(c.context.backdropRef.current,ae),!ae&&!p&&pe()},swipeThreshold({element:ae,direction:me}){return DUe(ae,me)},canStart(ae,me){const Ne=c.context.popupRef.current;if(!Ne)return!1;const Te=Ne.ownerDocument,ce=YB(Ne.getRootNode(),ae.x,ae.y);if(!ce||!ln(Ne,ce))return!1;const ye=me.nativeEvent;return!(("touches"in ye||ye.pointerType==="touch")&&LUe(Te,Ne))},onProgress(ae,me){ke(me);const Ne=!!(b&&b.length>0);if(z.current&&f==="down"&&Ne&&me){const ce=c.context.popupRef.current;ce&&(ce.style.removeProperty("transform"),ce.style.setProperty(Pc.swipeMovementY,`${ukt(j??0,me.deltaY)}px`))}let Te=ae;if(fe&&T>0){const ce=j??fe.minOffset,ye=Se=>Pi((Se-fe.minOffset)/fe.range,0,1);me&&Number.isFinite(me.deltaY)?Te=ye(Pi(ce+me.deltaY,0,T)):te!==null&&(Te=te)}ve(Te,!0,!0)},onRelease({event:ae,deltaX:me,deltaY:Ne,direction:Te,velocityX:ce,velocityY:ye,releaseVelocityX:Se,releaseVelocityY:$e}){const De=c.context.popupRef.current;if(!De){le();return}const Qe=De;function tt(we){pe(),re(!0),Qe.style.removeProperty("transition"),Qe.setAttribute(CN.endingStyle,""),So.flushSync(()=>{D(he(Qe,we,me,Ne,ce,ye,Se,$e))})}if(!b||b.length===0){if(!Te){le();return}const we=Cy(Te,me,Ne);if(we<=0)return le(),!1;if(Cy(Te,ce,ye)>=EUe)return tt(Te),!0;const Ie=we>DUe(Qe,Te);return Ie?tt(Te):le(),Ie}if(f!=="down"&&f!=="up"){le();return}if(!T)return le(),!1;if(S.length===0){le();return}const st=f==="down"?Ne:-Ne,He=Math.sign(st),Le=f==="down"?$e:-$e,wt=f==="down"?ye:-ye;let ge=Le;if(He!==0&&Math.abs(st)>=zpe){const we=Math.sign(ge);we!==0&&we!==He&&(ge=wt)}const Pe=j??0,Xe=Pi(Pe+st,0,T),St=Math.abs(ge)>=IUe?Pi(ge,-NUe,NUe)*iar:0,Ft=v?Xe:Pi(Xe+St,0,T),qt=Yt(v8,ae),yt=()=>(K.current=k,C(null,qt),tt(f),!0);if(v){const we=[...S].sort((gn,dn)=>gn.offset-dn.offset),Ie=we.map(gn=>gn.offset),We=KB(Ie,Pe);let ot=we[KB(Ie,Ft)];const dt=Math.sign(ge),Zt=He!==0&&dt!==0&&dt===He&&Math.abs(ge)>=IUe;let Bt=Ft;if(Zt){const gn=Pi(We+He,0,we.length-1);if(gn!==We){const dn=we[gn];(He>0?Ft<dn.offset:Ft>dn.offset)&&(ot=dn,Bt=dn.offset)}else if(He>0)return yt()}const Et=Math.abs(Bt-T),mt=Math.abs(Bt-ot.offset);return Et<mt?yt():(C(ot.value,qt),le(),!1)}if(ge>=EUe&&st>0)return yt();const xn=S[KB(S.map(we=>we.offset),Ft)];return Math.abs(Ft-T)<Math.abs(Ft-xn.offset)?yt():(C(xn.value,qt),le(),!1)},onDismiss(ae){F?.set({swipeProgress:0,frontmostHeight:0});const me=c.context.backdropRef.current;me&&(me.style.setProperty(M1.swipeProgress,"0"),me.style.removeProperty(Pc.height));const Ne=Yt(v8,ae);if(c.setOpen(!1,Ne),Ne.isCanceled){const Te=K.current;Te!==void 0&&C(Te,Yt(v8,ae)),K.current=void 0,M.current?.(),le();return}if(c.select("open")){const Te=ae;$.request(()=>{if(c.select("open")){const ce=K.current;ce!==void 0&&C(ce,Yt(v8,Te)),K.current=void 0,le(),M.current?.()}else K.current=void 0});return}K.current=void 0,re(!0)}}),Ve=Ee.getPointerProps(),Ze=Ee.getTouchProps(),{moveNative:Fe,reset:Ae}=Ee;M.current=Ae,g.useEffect(()=>{const ae=P??L;if(!ae)return;const me=ae,Ne=wr(me);function Te(ye,Se,$e){const De=B?$e.clientY-Se.lastY:$e.clientX-Se.lastX;if(ye.touches.length===2||LUe(Ne,me)||!_||!N||Q||yar(Se,ye,$e,B))return;const tt=Se.scrollTarget;if(!tt||tt===Ne.documentElement||tt===Ne.body){ye.cancelable&&ye.preventDefault(),ye.stopPropagation(),Fe(ye,me);return}if(!xar(tt,q)){ye.cancelable&&ye.preventDefault(),ye.stopPropagation();return}if(De!==0){const st=bar(tt,q,f,De);Se.allowSwipe?ye.cancelable&&ye.preventDefault():ye.cancelable&&st?(Se.allowSwipe=!0,ye.preventDefault()):Se.allowSwipe=!1}Se.allowSwipe===!0&&(ye.stopPropagation(),Fe(ye,me))}function ce(ye){if(ie?.onTouchMove(ye),X.current)return;const Se=ee.current,$e=ye.touches[0];!$e||!Se||(Te(ye,Se,$e),gar(Se,$e))}return Fr(Ne,"touchmove",ce,{passive:!1,capture:!0})},[N,Q,_,L,B,q,f,Fe,P,ie]),jt(()=>{!fe||Ee.swiping||ve(!_||I?0:te??0,!0,!1)},[ve,m,I,p,_,te,fe,Ee.swiping,c,F]),jt(()=>{if(p)return _||p(0),()=>{p(0)}},[p,_]),jt(()=>{_&&(y.current||Ae(),le())},[le,_,Ae,y]),jt(()=>{const ae=d.current;return()=>{F?.set({swipeProgress:0,frontmostHeight:0}),Doe(ae,!1);const me=d.current;me!==ae&&Doe(me,!1),pe()}},[d,pe,F]);const ze=g.useMemo(()=>({swiping:Ee.swiping,getDragStyles:Ee.getDragStyles,swipeStrength:H??null,setSwipeDismissed:re}),[re,Ee.getDragStyles,Ee.swiping,H]);function je(ae){X.current=ae,ee.current=null}function Ce(){je(!1),G.current="",ne.current=!1}function Ue(ae){return G.current="",ae.pointerType!=="touch"}return a.jsx(Lor,{ref:n,className:s,style:i,render:r,...kl(l,{onPointerDown(ae){if(G.current=ae.pointerType,ne.current=ae.pointerType==="pen",!_||!N||Q)return;const me=YB(ae.currentTarget.getRootNode(),ae.clientX,ae.clientY);MUe(me)||uar(me)||ae.pointerType!=="touch"&&Ve.onPointerDown?.(ae)},onPointerMove(ae){ae.pointerType!=="touch"&&Ve.onPointerMove?.(ae)},onPointerUp(ae){Ue(ae)&&Ve.onPointerUp?.(ae)},onPointerCancel(ae){Ue(ae)&&Ve.onPointerCancel?.(ae)},onTouchStart(ae){if(G.current==="pen"&&ne.current){ne.current=!1,je(!1);return}if(!_||!N||Q){je(!1);return}const Ne=ae.touches[0];if(!Ne)return;if(mar(ae)){je(!1);return}const Te=ae.currentTarget,ce=YB(Te.getRootNode(),Ne.clientX,Ne.clientY),ye=qi(ae.nativeEvent),Se=Cr(ye)?ye:Te;if(!ln(Te,Se)){je(!0);return}if(ie?.onTouchStart(ae),MUe(ce)){je(!0);return}X.current=!1;const $e=rI(Se,Te,q),De=rI(Se,Te,V)!=null;let Qe=null;$e&&(Qe=wkt($e,q,f)?null:!1),ee.current={startX:Ne.clientX,startY:Ne.clientY,lastX:Ne.clientX,lastY:Ne.clientY,scrollTarget:$e,hasCrossAxisScrollableContent:De,allowSwipe:Qe,preserveNativeCrossAxisScroll:!1,drawerAxisAttributed:!1},Ze.onTouchStart?.(ae)},onTouchEnd(ae){ie?.onTouchEnd(ae),Ce(),Ze.onTouchEnd?.(ae)},onTouchCancel(ae){ie?.onTouchCancel(),Ce(),Ze.onTouchCancel?.(ae)},"data-nested-dialog-open":void 0}),children:a.jsx(fkt.Provider,{value:ze,children:o})})});function Doe(e,t){e?.toggleAttribute(T1.swiping,t)}function MUe(e){return!!e?.closest(aOn)}function uar(e){return!!e?.closest(car)}function xkt(e,t){return t==="left"||t==="right"?e.offsetWidth:e.offsetHeight}function DUe(e,t){return Math.max(xkt(e,t)*.5,zpe)}function dar(e,t){return e instanceof t.HTMLInputElement&&e.type==="range"}function far(e){return e.tagName==="INPUT"||e.tagName==="TEXTAREA"}function har(e,t){const n=Cr(e.anchorNode)?e.anchorNode:e.anchorNode?.parentElement,r=Cr(e.focusNode)?e.focusNode:e.focusNode?.parentElement;return e.containsNode(t,!0)||ln(t,n)||ln(t,r)}function LUe(e,t){const n=sc(e);if(n&&ln(t,n)&&far(n)){const{selectionStart:s,selectionEnd:i}=n;if(s!=null&&i!=null&&s<i)return!0}const r=e.getSelection?.();return!r||r.isCollapsed?!1:har(r,t)}function par(e,t){return e.composedPath().some(n=>dar(n,t))}function mar(e){return par(e.nativeEvent,bi(e.currentTarget))}function gar(e,t){e.lastX=t.clientX,e.lastY=t.clientY}function yar(e,t,n,r){if(e.preserveNativeCrossAxisScroll)return!0;if(e.drawerAxisAttributed||e.allowSwipe===!0||!e.hasCrossAxisScrollableContent)return!1;if(!t.cancelable)return e.preserveNativeCrossAxisScroll=!0,!0;const s=r?n.clientY-e.startY:n.clientX-e.startX,i=r?n.clientX-e.startX:n.clientY-e.startY,o=Math.abs(s),l=Math.abs(i);return l>=RUe&&l>o+lar?(e.preserveNativeCrossAxisScroll=!0,!0):o>=RUe?(e.drawerAxisAttributed=!0,!1):!0}function xar(e,t){return bkt(e,t).max>0}function bkt(e,t){if(t==="vertical"){const r=Math.max(0,e.scrollHeight-e.clientHeight);return{offset:e.scrollTop,max:r}}const n=Math.max(0,e.scrollWidth-e.clientWidth);return{offset:e.scrollLeft,max:n}}function wkt(e,t,n){const r=Skt(n,t),{offset:s,max:i}=bkt(e,t);return r?s<=0:s>=i}function bar(e,t,n,r){return(Skt(n,t)?r>0:r<0)?wkt(e,t,n):!1}function Skt(e,t){return t==="vertical"?e==="down":e==="right"}const war=md("drawer-backdrop fixed inset-0 z-50",{variants:{overlay:{visible:"bg-scrim backdrop-blur-xs",transparent:"bg-transparent",none:"hidden"}},defaultVariants:{overlay:"visible"}}),Sar=md("fixed z-50 flex",{variants:{side:{top:"items-start justify-center",bottom:"items-end justify-center",left:"items-stretch justify-start",right:"items-stretch justify-end"},layout:{default:"inset-0",floating:"p-2 sm:p-3",floatingOverlay:"inset-0 p-2 sm:p-3"}},compoundVariants:[{side:"right",layout:"floating",className:"inset-y-0 right-0 w-[calc(32rem+1.5rem)] max-w-full sm:w-[calc(32rem+2rem)]"},{side:"left",layout:"floating",className:"inset-y-0 left-0 w-[calc(32rem+1.5rem)] max-w-full sm:w-[calc(32rem+2rem)]"},{side:"bottom",layout:"floating",className:"inset-x-0 bottom-0 h-[calc(85dvh+1.5rem)] max-h-full sm:h-[calc(85dvh+2rem)]"},{side:"top",layout:"floating",className:"inset-x-0 top-0 h-[calc(85dvh+1.5rem)] max-h-full sm:h-[calc(85dvh+2rem)]"}],defaultVariants:{side:"bottom",layout:"default"}}),kar=md(Z("drawer-popup group/popup relative z-50 box-border flex [touch-action:auto] flex-col overflow-y-auto overscroll-contain will-change-transform outline-none","text-foreground",iht,"data-[swiping]:select-none","after:pointer-events-none after:absolute after:inset-0 after:bg-transparent after:transition-[background-color] after:duration-[450ms] after:content-['']","data-[nested-drawer-open]:after:bg-black/25"),{variants:{side:{bottom:"",top:"",left:"",right:""},variant:{default:"",floating:"drawer-popup-floating pointer-events-auto rounded-lg"}},compoundVariants:[{side:"bottom",variant:"default",className:"-mb-12 h-[var(--drawer-height,auto)] max-h-[calc(85vh_+_3rem)] w-full rounded-t-xl pb-12"},{side:"top",variant:"default",className:"-mt-12 h-[var(--drawer-height,auto)] max-h-[calc(85vh_+_3rem)] w-full rounded-b-xl pt-12"},{side:"left",variant:"default",className:"h-full w-[20rem] max-w-[85vw] rounded-r-xl"},{side:"right",variant:"default",className:"h-full w-[20rem] max-w-[85vw] rounded-l-xl"},{side:["left","right"],variant:"floating",className:"h-[calc(100dvh-1.5rem)] w-[32rem] max-w-[calc(100vw-1.5rem)] sm:h-[calc(100dvh-2rem)] sm:max-w-[calc(100vw-2rem)]"},{side:["top","bottom"],variant:"floating",className:"max-h-[calc(85dvh-1.5rem)] w-[calc(100vw-1.5rem)] sm:max-h-[calc(85dvh-2rem)] sm:w-[calc(100vw-2rem)]"}],defaultVariants:{side:"bottom",variant:"default"}}),Oar={top:"up",bottom:"down",left:"left",right:"right"},jar=(e,t)=>e!=="auto"?e:t==="floating"?"none":"visible",kkt=g.createContext({side:"bottom",variant:"default",resolvedOverlay:"visible"}),fK=()=>g.useContext(kkt),Car=(e,t)=>e!=="floating"?"default":t==="none"?"floating":"floatingOverlay";function D_({side:e="bottom",variant:t="default",overlay:n="auto",modal:r,disablePointerDismissal:s,children:i,...o}){const l=jar(n,t),c=r??(l==="none"?!1:void 0),u=s??(l==="none"?!0:void 0),d=g.useMemo(()=>({side:e,variant:t,resolvedOverlay:l}),[e,t,l]);return a.jsx(kkt.Provider,{value:d,children:a.jsx(mkt,{swipeDirection:Oar[e],modal:c,disablePointerDismissal:u,...o,children:i})})}D_.displayName="Drawer";function Okt({asChild:e,children:t,...n}){const r=e&&g.isValidElement(t)?{render:t}:{};return a.jsx(nar,{...r,...n,children:e?void 0:t})}Okt.displayName="DrawerTrigger";const hK=g.forwardRef(({asChild:e,children:t,...n},r)=>{const s=e&&g.isValidElement(t)?{render:t}:{};return a.jsx(zor,{ref:r,...s,...n,children:e?void 0:t})});hK.displayName="DrawerClose";const dke=pkt,jkt=xQ,pK=g.forwardRef(({className:e,overlay:t,...n},r)=>{const{resolvedOverlay:s}=fK(),i=t??s;return a.jsx(ikt,{ref:r,"data-slot":"drawer-backdrop","data-overlay":i,className:Z(war({overlay:i}),e),...n})});pK.displayName="DrawerBackdrop";const mK=g.forwardRef(({className:e,side:t,variant:n,...r},s)=>{const i=fK(),o=t??i.side,l=n??i.variant,c=Car(l,i.resolvedOverlay);return a.jsx(ykt,{ref:s,"data-slot":"drawer-viewport","data-variant":l,className:Z(Sar({side:o,layout:c}),e),...r})});mK.displayName="DrawerViewport";const gK=g.forwardRef(({className:e,side:t,variant:n,...r},s)=>{const i=fK(),o=t??i.side,l=n??i.variant;return a.jsx(hkt,{ref:s,"data-slot":"drawer-popup","data-variant":l,className:Z(kar({side:o,variant:l}),e),...r})});gK.displayName="DrawerPopup";const Ckt=Z("transition-opacity duration-300 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:duration-0","group-data-[nested-drawer-open]/popup:opacity-0"),Fpe=()=>a.jsx("div",{"aria-hidden":!0,"data-slot":"drawer-handle",className:Z("mx-auto my-2 h-1 w-12 shrink-0 rounded-full bg-muted",Ckt)});Fpe.displayName="DrawerHandleBar";const _kt=({side:e,variant:t})=>t!=="floating"||e!=="left"&&e!=="right"?null:a.jsx("div",{"aria-hidden":!0,"data-slot":"drawer-side-handle",className:Z("absolute top-1/2 z-10 flex h-20 w-5 -translate-y-1/2 cursor-ew-resize touch-none items-center justify-center select-none lg:hidden",e==="right"?"-left-2":"-right-2"),children:a.jsx("div",{className:"h-10 w-1 rounded-full bg-border-strong"})});_kt.displayName="DrawerFloatingSideHandle";const HL=g.forwardRef(({className:e,children:t,variant:n,showCloseButton:r=!0,...s},i)=>{const{side:o,variant:l,resolvedOverlay:c}=fK(),u=n??l,d=o==="top"||o==="bottom";return a.jsxs(dke,{children:[c!=="none"&&a.jsx(pK,{}),a.jsx(mK,{variant:u,children:a.jsxs(gK,{ref:i,variant:u,className:e,...s,children:[d&&o==="bottom"&&a.jsx(Fpe,{}),a.jsx(_kt,{side:o,variant:u}),a.jsxs("div",{"data-slot":"drawer-content",className:Z("relative flex min-h-0 flex-1 flex-col","[&>form]:flex [&>form]:min-h-0 [&>form]:flex-1 [&>form]:flex-col [&>form]:gap-0",Ckt),children:[r&&a.jsx(Tkt,{}),t]}),d&&o==="top"&&a.jsx(Fpe,{})]})})]})});HL.displayName="DrawerContent";const Tkt=()=>a.jsx(hK,{asChild:!0,children:a.jsx(ue,{type:"button",variant:"ghost",size:"icon-sm",className:"absolute top-3 right-3 z-10","aria-label":"Close",children:a.jsx(zn,{})})});Tkt.displayName="DrawerDefaultCloseButton";const fke=({className:e,...t})=>a.jsx("div",{"data-slot":"drawer-header",className:Z("flex flex-col gap-0.5 px-3 py-2.5 pr-12 text-left",e),...t});fke.displayName="DrawerHeader";const hke=({className:e,...t})=>a.jsx("div",{"data-slot":"drawer-body",className:Z("flex-1 px-3 py-2.5",e),...t});hke.displayName="DrawerBody";const $P=g.forwardRef(({className:e,...t},n)=>a.jsx(vkt,{ref:n,className:Z("text-subheading text-foreground",e),...t}));$P.displayName="DrawerTitle";const GL=g.forwardRef(({className:e,...t},n)=>a.jsx(akt,{ref:n,className:Z("text-caption text-muted-foreground",e),...t}));GL.displayName="DrawerDescription";const Ck=(e=1024)=>{const t=`(max-width: ${e-1}px)`,n=g.useCallback(r=>{const s=window.matchMedia(t);return s.addEventListener("change",r),()=>s.removeEventListener("change",r)},[t]);return g.useSyncExternalStore(n,()=>window.matchMedia(t).matches,()=>!1)},Ekt=g.createContext({intent:"default",pending:!1});function vK(){return g.useContext(Ekt)}const yK={sm:"min-h-control-sm",md:"min-h-control-md",lg:"min-h-control-lg"},xK="h-auto min-w-0 max-w-full whitespace-normal wrap-anywhere max-[22rem]:w-full",_ar=640,Tar="[&>form]:flex [&>form]:min-h-0 [&>form]:flex-1 [&>form]:flex-col [&>form]:gap-0",Ear=["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",Tar,iht].join(" "),Iar={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)]"},Ikt=()=>Ck(_ar);function Kr({intent:e="default",pending:t=!1,open:n,defaultOpen:r=!1,onOpenChange:s,disablePointerDismissal:i,...o}){const l=Ikt(),[c,u]=g.useState(r),d={...o,open:n??c,disablePointerDismissal:i??e==="destructive"};function f(h,p){if(!h&&t){p.cancel();return}u(h),s?.(h,p)}return a.jsx(Ekt.Provider,{value:{intent:e,pending:t},children:l?a.jsx(D_,{...d,onOpenChange:f}):a.jsx(Dor,{...d,onOpenChange:f})})}const pke=skt,Nar=tkt,Aar=uK;function Par({className:e,...t}){return a.jsx(Ior,{"data-slot":"dialog-overlay",className:Z("dialog-backdrop-motion fixed inset-0 z-50 bg-scrim backdrop-blur-xs",e),...t})}function Yr({className:e,children:t,size:n="md",showOverlay:r=!0,showCloseButton:s=!0,overlayClassName:i,initialFocus:o,...l}){const{intent:c,pending:u}=vK(),d=Ikt(),f=g.useRef(null),h=c==="destructive",p={"data-slot":"dialog-content","data-size":n,"data-intent":c,role:h?"alertdialog":"dialog",initialFocus:o??(h&&s?f:!0),"aria-busy":u||void 0,...l},m=s&&a.jsx(uK,{ref:f,disabled:u,"data-slot":"dialog-close",className:Z("absolute right-4",d?"top-1.5":"top-4"),render:a.jsx(ue,{variant:"ghost",size:"icon-sm","aria-label":"Close",children:a.jsx(zn,{})})});return d?a.jsxs(HL,{...p,showCloseButton:!1,className:Z("pb-3",n==="full"&&"h-[calc(85vh+3rem)]",s&&"[&_[data-slot=dialog-header]]:pr-12",e),children:[t,m,a.jsx("div",{"aria-hidden":!0,className:"h-12 shrink-0"})]}):a.jsxs(Nar,{children:[r&&a.jsx(Par,{className:i}),a.jsxs(Nor,{...p,className:Z(Ear,Iar[n],s&&"[&_[data-slot=dialog-header]]:pr-12",e),children:[t,m]})]})}function Xr({className:e,...t}){return a.jsx("div",{"data-slot":"dialog-header",className:Z("flex min-w-0 shrink-0 flex-col gap-1 px-5 py-2",e),...t})}function Yo({className:e,...t}){return a.jsx("div",{"data-slot":"dialog-footer",className:Z("flex shrink-0 flex-wrap items-center justify-end gap-2 px-5 py-2",e),...t})}function qr({className:e,layout:t="scroll",flush:n=!1,children:r,...s}){const i=Z("flex min-w-0 flex-col gap-4 text-body wrap-break-word text-muted-foreground",!n&&"px-5 py-2",e);return t==="fill"?a.jsx("div",{"data-slot":"dialog-body",className:Z("min-h-0 flex-1",i),...s,children:r}):a.jsx(Ir,{className:"flex min-h-0 min-w-0 flex-1 flex-col",mask:!0,children:a.jsx(of,{className:"h-auto min-h-0",children:a.jsx("div",{"data-slot":"dialog-body",className:i,...s,children:r})})})}function Qr({className:e,...t}){return a.jsx(rkt,{className:Z("text-heading wrap-break-word text-foreground",e),...t})}function Lo({className:e,...t}){return a.jsx(XSt,{className:Z("text-body wrap-break-word text-muted-foreground",e),...t})}function Ca({disabled:e,size:t="md",...n}){const{pending:r}=vK();return a.jsx(uK,{render:a.jsx(ue,{size:t,variant:"ghost",className:Z(xK,yK[t]),children:n.children}),...n,disabled:e||r})}function Ut(e){return a.jsx(Kr,{...e,modal:!0,disablePointerDismissal:!0})}function $ar({size:e="sm",...t}){return a.jsx(Yr,{"data-slot":"alert-dialog-content",size:e,showCloseButton:!1,...t,role:"alertdialog"})}function Rar({children:e,...t}){return a.jsx(Aar,{render:a.jsx(ue,{variant:"primary",size:"md",className:Z(xK,yK.md),children:e}),...t})}Ut.Trigger=pke;Ut.Content=$ar;Ut.Header=Xr;Ut.Footer=Yo;Ut.Body=qr;Ut.Title=Qr;Ut.Description=Lo;Ut.Action=Rar;Ut.Cancel=Ca;const Nkt=({children:e,"aria-label":t="Threads",embedded:n=!1})=>a.jsx("div",{className:Z("size-full",!n&&"pb-2 pl-2"),children:a.jsx("nav",{"aria-label":t,className:Z("flex h-full flex-col gap-1 overflow-y-auto p-1",!n&&Z(pr,"rounded-studio-panel")),children:e})}),Mar=({render:e,children:t})=>a.jsx(ue,{render:e,variant:"ghost",className:"w-full justify-start rounded-xl px-3",children:t}),Dar=()=>a.jsx("div",{role:"separator","aria-orientation":"horizontal",className:"-mx-1 h-px shrink-0 bg-border/40"}),Bpe=({children:e})=>a.jsx("ol",{className:"flex flex-col gap-1","data-testid":"thread-list",children:e}),Upe=({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(ue,{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(ue,{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(zn,{})}),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})]}),Akt=({children:e})=>a.jsx(Y,{as:"p",variant:"caption",tone:"muted",className:"px-3 py-2",children:e}),Lar=yr({status:sg(["running","failed","canceled","pending","waiting","paused","suspended","success"]),timestamp:rc().optional()}),zar=yr({output:M4()});function Far(e){const t=Lar.safeParse(e);return t.success?t.data:void 0}function Bar(e){if(e==null)return null;const t=Cn().safeParse(e);if(t.success)return t.data;const n=zar.safeParse(e),r=n.success?n.data.output:e;try{return JSON.stringify(r)}catch{return null}}function Uar({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:Jr(e,"date-time")}),t&&a.jsx("span",{className:"min-w-0 truncate",title:`Resource ${t}`,children:e===void 0?t:`· ${t}`})]})}const Var=({workflowId:e,runId:t,canDelete:n})=>{const[r,s]=g.useState(!0),[i,o]=g.useState(null),{Link:l,paths:c,navigate:u}=Tn(),{isLoading:d,error:f,data:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v}=z2n({workflowId:e,summary:!0}),{data:y}=Gpt({workflowId:e,runId:t??"",queryOptions:{enabled:!!(e&&t)}}),x=Bar(y?.payload),{mutateAsync:b}=F2n({workflowId:e}),S=async j=>{try{await b({runId:j}),Ye.success("Workflow run deleted successfully"),o(null),u(c.workflowLink(e))}catch{Ye.error("Failed to delete workflow run"),o(null)}},k=h||[];return a.jsxs(a.Fragment,{children:[a.jsxs(gc,{open:r,onOpenChange:s,className:"flex min-h-0 flex-col",children:[a.jsxs(Hl,{className:"flex shrink-0 items-center gap-2 px-4 py-3 text-left text-caption text-muted-foreground",children:[a.jsx(Ha,{direction:"right",className:"size-4 text-muted-foreground"}),a.jsx("span",{children:"Recent runs"}),!d&&!f&&a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",children:[k.length,v?"+":""]})]}),a.jsx(Gl,{keepMounted:!0,fill:!0,className:"flex min-h-0 flex-col",children:a.jsx(Ir,{className:"min-h-0 w-full flex-1",mask:{top:!1},children:d?a.jsx("div",{className:"p-4",children:a.jsx(xt,{className:"h-32"})}):a.jsx(Nkt,{"aria-label":"Workflow runs",embedded:!0,children:k.length===0?a.jsx(Akt,{children:f?"Unable to load workflow runs.":"Your run history will appear here once you run the workflow"}):a.jsxs(Bpe,{children:[k.map(j=>{const C=j.runId===t,T=Far(j.snapshot),_=C?x:null;return a.jsx(Upe,{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(m1t,{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(Uar,{timestamp:Dfe(T?.timestamp),resourceId:Xpt(j)}),_&&a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"block w-full min-w-0 truncate",children:_})]})]})},`run-${j.runId}`)}),m&&a.jsx("li",{className:"flex items-center justify-center py-2",children:a.jsx(At,{children:a.jsx(_n,{})})}),a.jsx("li",{children:a.jsx("div",{ref:p})})]})})})})]}),a.jsx(qar,{open:!!i,onOpenChange:()=>o(null),onDelete:()=>{i&&S(i)}})]})},qar=({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"})]})]})}),Pkt=g.createContext(0);function T9(e,t=!1){return{maxZoom:1,padding:t?"20px":{left:`${e+40}px`,right:"40px",top:"40px",bottom:"64px"}}}const Qar=md("pointer-events-none block transition-all duration-150 ease-out motion-reduce:transition-none",{variants:{variant:{line:"h-3/4 w-px bg-linear-to-b from-transparent via-foreground/30 to-transparent opacity-0",pill:"h-10 w-0.5 rounded-full bg-foreground/30"}},defaultVariants:{variant:"line"}}),mke=({variant:e,className:t})=>a.jsx("span",{"aria-hidden":!0,className:Z(Qar({variant:e}),t)}),gke=380,Zar="workflow-canvas-left-panel-width",War=8,zUe=16,vke=`${pr} rounded-studio-panel`,$kt=g.createContext(void 0);function Loe(e,t){return Math.max(gke,Math.min(e,t))}function Har(){const e=g.useContext($kt);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"?zUe:-zUe))};return a.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panel","aria-valuenow":e.width,"aria-valuemin":gke,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(mke,{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 Gar=({children:e,leftSlot:t})=>{const n=Ck(),r=g.useRef(null),[s,i]=jk({initialKey:Zar,defaultValue:gke,schema:us()}),[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=Loe(s,o),u=p=>{const m=r.current;m&&i(Loe(p-m.getBoundingClientRect().left,o))},d=p=>i(Loe(c+p,o)),f=t?c-War: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(Pkt,{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($kt,{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})})]})},Rkt=Z(vke,"pointer-events-auto");function Mkt({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(Har,{})]})}function Kar({workflowId:e,onClick:t}){const{Link:n,paths:r}=Tn();return a.jsx(ue,{render:a.jsx(n,{href:`${r.workflowLink(e)}/graph`}),variant:"ghost",size:"icon-md",tooltip:"New workflow run",onClick:t,children:a.jsx(ys,{})})}function Yar({children:e,workflowId:t,showNewRunButton:n,onNewRun:r}){const{result:s}=g.useContext(Zl),[i,o]=g.useState(!0);return a.jsx(Mkt,{className:"max-h-[75%] flex-initial",children:a.jsxs(gc,{render:a.jsx("section",{}),open:i,onOpenChange:o,"data-testid":"workflow-information-top-section",className:Z(Rkt,"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(Hl,{className:"flex min-w-0 flex-1 items-center gap-2 px-4 py-3 text-column text-muted-foreground",children:[a.jsx(Ha,{direction:"right",className:"size-4 text-muted-foreground"}),a.jsx("span",{children:"Workflow run"}),!i&&s?.status&&a.jsx(y1t,{status:s.status})]}),n&&a.jsx(Kar,{workflowId:t,onClick:()=>{o(!0),r()}})]}),a.jsx(Gl,{keepMounted:!0,fill:!0,className:"flex min-h-0 flex-col",children:a.jsx(Ir,{"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(of,{className:"h-full",children:e})})})]})})}function Xar(e){return a.jsx(KSt,{...e})}function Jar({runId:e,observeWorkflowStream:t,...n}){return a.jsx(Eor,{...n,runId:e,observeWorkflowStream:t})}function elr({workflowId:e,activeRunId:t,canDelete:n}){return a.jsx(Mkt,{className:"mt-auto max-h-[min(35%,280px)] shrink-0",children:a.jsx("section",{className:Z(Rkt,"flex min-h-0 min-w-0 flex-col overflow-hidden"),children:a.jsx(Var,{workflowId:e,runId:t,canDelete:n})})})}function tlr({workflowId:e,initialRunId:t,requestContext:n,runActionsSlot:r,canExecute:s,canDelete:i}){const{data:o,isLoading:l,error:c}=yL({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(Zl),{setSelectedStepId:b}=dG(),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";Ye.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(Yar,{workflowId:e,showNewRunButton:!!S,onNewRun:j,children:t?a.jsx(Jar,{...k,runId:t,observeWorkflowStream:h}):a.jsx(Xar,{...k})}),a.jsx(elr,{workflowId:e,activeRunId:S,canDelete:i})]})}function yke(e,t){return Wpt(`mastra-tracing-options:${e}:${t}`)}const FUe={runId:"",payload:null,override:null};function nlr(e){const[t,n]=g.useState(FUe),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(FUe),[]);return{runId:r,payload:t.payload,override:s,setRunId:i,setPayload:o,setResult:l,dropOverride:c,reset:u}}const rlr=5e3,slr=e=>fG(e.state.data?.status)?!1:rlr;function ilr(e){return{...e,timestamp:Dfe(e.updatedAt)??Dfe(e.createdAt)}}function olr(e,t,{poll:n}){const{data:r,isLoading:s}=Gpt({workflowId:e,runId:t,queryOptions:{enabled:!!(e&&t),refetchInterval:n?slr:void 0}});return{persistedRun:g.useMemo(()=>r&&ilr(r),[r]),isLoading:s}}function alr({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}=b0n({debugMode:t,tracingOptions:n,onError:b=>Ye.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 xke=g.createContext(null);function _k(){const e=g.useContext(xke);if(!e)throw new Error("useWorkflowStepDetail must be used within WorkflowStepDetailProvider");return e}const llr={};function clr({children:e,snapshot:t,workflowId:n,initialRunId:r,withoutTimeTravel:s=!1,requestContext:i=llr,tracingOptions:o}){const l=g.useContext(xke)?.resetStepDetail,[c,u]=g.useState(!1),{data:d,isLoading:f,error:h}=yL({workflowId:n,requestContext:i,queryOptions:{enabled:!!n}}),p=mr(),m=w0n(),v=S0n(),{runId:y,payload:x,override:b,setRunId:S,setPayload:k,setResult:j,dropOverride:C,reset:T}=nlr(r),{result:_,isOpen:N,isObserving:I,select:A,close:P,streamWorkflow:L,resumeWorkflowStream:F,observeWorkflowStream:Q,timeTravelWorkflowStream:q}=alr({runId:y,debugMode:c,tracingOptions:o}),B=b??_,V=!r&&fG(B?.status),H=r||(V?y:""),{persistedRun:D,isLoading:K}=olr(n,H,{poll:!N}),M=D??t,$=g.useMemo(()=>M?eDn(M):null,[M]),z=g.useMemo(()=>nDn(B,$),[B,$]),U=r?M:void 0,G=I&&iDn(z?.status),ne=N&&!G,X=g.useMemo(()=>U?sDn(U,$?.input):x,[U,$,x]),ee=g.useCallback(he=>{l?.(),S(he)},[l,S]),ie=g.useCallback(()=>{l?.(),P(),T()},[l,P,T]);g.useEffect(()=>ie,[n,r,ie]);const fe=g.useCallback((he,ke)=>{A(he,ke),C(he)},[A,C]),te=g.useCallback((he,ke)=>p.invalidateQueries({queryKey:Hpt(he,ke),exact:!0}),[p]),se=g.useCallback(async he=>{fe(he.runId),await L(he)},[fe,L]),re=g.useCallback(async he=>{fe(he.runId);try{await F(he)}finally{await te(he.workflowId,he.runId)}},[te,fe,F]),le=g.useCallback(he=>{if(he.storedStatus==="suspended"){P();return}fe(he.runId,"observe"),Q({workflowId:he.workflowId,runId:he.runId,storeRunResult:null})},[P,fe,Q]),pe=g.useCallback(async he=>{fe(he.runId);try{await q(he)}finally{await te(he.workflowId,he.runId)}},[te,fe,q]),ve=g.useMemo(()=>({workflowId:n,workflow:d??void 0,workflowError:h??null,isLoading:f,runId:y,setRunId:ee,result:z,setResult:j,streamResult:_,payload:X,setPayload:k,clearData:ie,snapshot:t,runSnapshot:U,isLoadingRunExecutionResult:K,isStreamingWorkflow:ne,isCancellingWorkflowRun:v.isPending,createWorkflowRun:m.mutateAsync,streamWorkflow:se,resumeWorkflow:re,observeWorkflowStream:le,timeTravelWorkflowStream:pe,cancelWorkflowRun:v.mutateAsync,closeStreamsAndReset:P,withoutTimeTravel:s,debugMode:c,setDebugMode:u}),[n,d,h,f,y,ee,z,j,_,X,k,ie,t,U,K,ne,v.isPending,m.mutateAsync,se,re,le,pe,v.mutateAsync,P,s,c]);return a.jsx(Zl.Provider,{value:ve,children:e})}function bke(e){return a.jsx(clr,{...e,requestContext:xr("workflow",e.workflowId)[0],tracingOptions:yke("workflow",e.workflowId)[0]})}function Dkt({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(Kpt.Provider,{value:i,children:e})}function Lkt({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(xke.Provider,{value:u,children:e})}const ulr=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"})}),wke=({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})}),Lx=e=>a.jsx(xt,{className:"h-3 w-24",...e}),j5=({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]",ov.sm,On,n?"max-w-xs cursor-default text-foreground":Z(Ln,"max-w-48 cursor-pointer hover:bg-fill-subtle active:bg-fill"),e),...c,children:[i&&a.jsx(At,{className:Z("-ml-[.3em] shrink-0 opacity-50 group-hover:opacity-100","transition-opacity duration-normal ease-out-custom"),children:i}),o?a.jsx(Lx,{}):a.jsx("span",{className:"min-w-0 flex-1 truncate",children:l})]}),s&&a.jsx("span",{"data-slot":"crumb-switcher",className:Z("-ml-1 flex h-control-sm shrink-0 items-center",d&&"[&_button]:bg-transparent! [&_button:enabled]:after:absolute [&_button:enabled]:after:inset-0 [&_button:enabled]:after:rounded-full"),children:s}),r&&a.jsx("span",{className:"-ml-1 flex h-control-sm shrink-0 items-center",children:r})]}),!n&&a.jsx("li",{role:"separator",className:"flex h-full items-center",children:a.jsx(At,{className:"text-placeholder",children:a.jsx(ulr,{})})})]})},RP={variant:"ghost",size:"icon-sm",align:"end"};function dlr(e,t,n,r,s,i,o,l,c,u=2){const d=Qkn(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 G1(n.current,d)?void 0:d}const zkt=g.createContext(void 0),Fkt=g.createContext(void 0),Bkt=g.createContext(void 0),Ukt=g.createContext(!1),Vkt=g.createContext("");function lg(){const e=g.useContext(zkt);if(!e)throw new Error(Nr(22));return e}function bK(){const e=g.useContext(Fkt);if(!e)throw new Error(Nr(23));return e}function KL(){const e=g.useContext(Bkt);if(!e)throw new Error(Nr(24));return e}function qkt(){return g.useContext(Vkt)}function flr(){return g.useContext(Ukt)}const fn={id:e=>e.id,labelId:e=>e.labelId,items:e=>e.items,selectedValue:e=>e.selectedValue,hasSelectedValue:e=>{const{selectedValue:t,selectionMode:n}=e;return t==null?!1:n==="multiple"&&Array.isArray(t)?t.length>0:!0},hasNullItemLabel:(e,t)=>t?j1t(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=>Vm(t,s,n)):Vm(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 Qkt(e){return e==null?void 0:`${e}-popup`}function hlr(e,t){return(n,r)=>n==null?!1:e.contains(n,r,t)}function Ske(e){return Array.isArray(e)?e.map(t=>Ske(t)).join(","):e==null?"":String(e)}const BUe=new Map;function plr(e={}){const t={usage:"search",sensitivity:"base",ignorePunctuation:!0,...e},n=`${Ske(e.locale)}|${JSON.stringify(t)}`,r=BUe.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=tm(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=tm(o,c);return s.compare(u.slice(0,l.length),l)===0},endsWith(o,l,c){if(!l)return!0;const u=tm(o,c),d=l.length;return u.length>=d&&s.compare(u.slice(u.length-d),l)===0}};return BUe.set(n,i),i}const mlr=plr,Zkt=Symbol("none"),zoe={value:Zkt,index:-1};function glr(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:A,itemToStringValue:P,isItemEqualToValue:L=k1t,virtualized:F=!1,inline:Q=!1,fillInputOnItemPress:q=!0,modal:B=!1,limit:V=-1,autoComplete:H="list",formAutoComplete:D,locale:K,submitOnItemClick:M=!1}=e,{clearErrors:$}=Rv(),{setDirty:z,validityData:U,setFilled:G,name:ne,disabled:X,setTouched:ee,setFocused:ie,validationMode:fe,validation:te}=Ru(),se=Ex(),re=bk({id:t}),le=mlr({locale:K}),[pe,ve]=g.useState(!1),[he,ke]=g.useState(null),Ee=g.useRef([]),Ve=g.useRef([]),Ze=g.useRef(null),Fe=g.useRef(null),Ae=g.useRef(null),ze=g.useRef(null),je=g.useRef(null),Ce=g.useRef(!0),Ue=g.useRef(!1),ae=g.useRef(null),me=g.useRef(null),Ne=g.useRef(null),Te=g.useRef(zoe),ce=g.useRef(null),ye=g.useRef([]),Se=g.useRef(null),$e=X||m,De=ne??h,Qe=d==="multiple",tt=d==="single",st=l!==void 0||o!==void 0,He=S!==void 0,Le=k!==void 0;let wt;T==="always"?wt="always":wt=T?"input-change":!1;const[ge,Pe]=Xd({controlled:s,default:Qe?r??zf:r,name:"Combobox",state:"selectedValue"}),Xe=g.useMemo(()=>j===null?()=>!0:j!==void 0?j:hlr(le,A),[j,le,A]),St=ul(()=>st?o??"":tt?tm(ge,A):"").current,[Ft,qt]=Xd({controlled:l,default:St,name:"Combobox",state:"inputValue"}),[yt,xn]=Xd({controlled:c,default:u,name:"Combobox",state:"open"}),vn=OSe(S),we=he??String(Ft).trim(),Ie=tt?tm(ge,A):"",We=tt&&!pe&&we!==""&&Ie.length===we.length&&le.contains(Ie,we),ot=We?"":we,dt=He&&Le&&We,Zt=g.useMemo(()=>S?vn?S.flatMap(mn=>mn.items):S:zf,[S,vn]),Bt=g.useMemo(()=>{if(k&&!dt)return k;if(!S)return zf;if(vn){const In=S,Ns=[];let Ii=0;for(const ta of In){if(V>-1&&Ii>=V)break;const Pa=V>-1?V-Ii:1/0,Oo=ot===""?ta.items.slice(0,Pa):[];if(ot!=="")for(const Kl of ta.items){if(Oo.length>=Pa)break;Xe(Kl,ot,A)&&Oo.push(Kl)}if(Oo.length>0){const Kl={...ta,items:Oo};Ns.push(Kl),Ii+=Oo.length}}return Ns}if(ot==="")return V>-1?Zt.slice(0,V):Zt;const mn=[];for(const In of Zt){if(V>-1&&mn.length>=V)break;Xe(In,ot,A)&&mn.push(In)}return mn},[k,dt,S,vn,ot,V,Xe,A,Zt]),Et=g.useMemo(()=>vn?Bt.flatMap(In=>In.items):Bt,[Bt,vn]),mt=ul(()=>{let mn=null;return Q&&yt&&He&&d!=="none"&&(mn=voe(Et,ge,L,Qe)),new Bft({id:re,labelId:void 0,selectedValue:ge,open:yt,items:S,selectionMode:d,listRef:Ee,labelsRef:Ve,popupRef:Ze,emptyRef:je,inputRef:Fe,startDismissRef:Ae,endDismissRef:ze,keyboardActiveRef:Ce,chipsContainerRef:ae,clearRef:me,valuesRef:ye,pointerDownItemRef:Se,selectionEventRef:Ne,name:De,form:p,disabled:$e,readOnly:v,required:y,grid:b,virtualized:F,openOnInputClick:C,itemToStringLabel:A,isItemEqualToValue:L,modal:B,autoHighlight:wt,submitOnItemClick:M,hasInputValue:st,mounted:!1,forceMounted:!1,transitionStatus:"idle",inline:Q,activeIndex:null,selectedIndex:mn,popupProps:{},listProps:{},inputProps:{},triggerProps:{},itemProps:ai,positionerElement:null,listElement:null,popupId:void 0,triggerElement:null,inputElement:null,inputGroupElement:null,popupSide:null,openMethod:null,inputInsidePopup:!0,inputOwnsFormValue:d==="none",onOpenChangeComplete:ti,setOpen:ti,setInputValue:ti,setSelectedValue:ti,setIndices:ti,handleSelection:ti,forceMount:ti,requestSubmit:ti})}).current,gn=d==="none"?Ft:ge,dn=g.useMemo(()=>d==="none"?gn:Array.isArray(ge)?ge.map(mn=>Hg(mn,P)):Hg(ge,P),[gn,P,d,ge]),Pn=ft(f),gr=ft(n),xs=kt(mt,fn.activeIndex),zr=kt(mt,fn.selectedIndex),Ur=kt(mt,fn.positionerElement),dr=kt(mt,fn.listElement),Ti=kt(mt,fn.triggerElement),Ei=kt(mt,fn.inputElement),Aa=kt(mt,fn.inputGroupElement),Wr=kt(mt,fn.inline),Ka=kt(mt,fn.inputInsidePopup),gg=kt(mt,fn.inputOwnsFormValue),ga=aa(Ti),{mounted:bc,setMounted:hh,transitionStatus:Cd}=Sp(yt),{openMethod:Pp,triggerProps:$p}=vSe(yt),ph=ft(()=>dn);I_(Ka?ga:Fe,re,gn,ph,!$e,h);const Hr=ft(()=>{S?Ve.current=Et.map(mn=>tm(mn,A)):mt.set("forceMounted",!0)}),Is=ft((mn,In,Ns)=>{if(In===-1){if(Te.current===zoe)return;Te.current=zoe}else Te.current={value:mn,index:In};Pn(mn,TH(Ns,void 0,{index:In}))}),Ks=ft(mn=>{mt.update(mn);const In=mn.activeIndex;if(In===void 0)return;const Ns=mn.type||Io;In===null?Is(void 0,-1,Ns):Is(ye.current[In],In,Ns)}),Ya=ft((mn,In)=>{if(Ue.current=In.reason===wy,e.onInputValueChange?.(mn,In),!In.isCanceled){if(In.reason===bI){yt&&he!==null&&ke(null);const Ns=In.event,Ii=Ns.inputType;if(Ns.type==="compositionend"||Ii!=null&&Ii!==""&&Ii!=="insertReplacementText"){const Pa=mn.trim()!=="";Pa&&ve(!0),ce.current={hasQuery:Pa};const Oo=mt.state.listElement;if(!mt.state.virtualized&&Oo){const Kl=Ze.current;for(const vf of SN(Oo.firstElementChild??Oo)){if(!ni(vf)||(Kl?!ln(Kl,vf):vf.getAttribute("role")==="dialog"))break;if(gkt(vf)){vf.scrollTop=0;break}}}Pa&&wt&&mt.state.activeIndex==null&&(yt||Wr)&&mt.set("activeIndex",0)}}else In.reason===wy&&mn===""&&mt.state.inputInsidePopup&&(ce.current={hasQuery:!1,selection:!0});qt(mn)}}),gf=ft((mn,In)=>{if(yt!==mn&&(In.reason===b_&&He&&Et.length===0&&!je.current&&In.allowPropagation(),e.onOpenChange?.(mn,In),!In.isCanceled&&(mn&&Ka&&!Wr&&he!==null&&(ve(!1),ke(null),Ft!==""&&In.reason!==bI&&Ya("",Yt(wy,In.event))),!mn&&pe&&(tt?(Wr||ke(we),we===""&&ve(!1)):Qe&&(Wr||ke(we),Ka&&Ks({activeIndex:null}),(!Ka||Wr)&&Ya("",Yt(wy,In.event)))),xn(mn),!mn&&Ka&&(In.reason===O0||In.reason===W3)&&(ee(!0),ie(!1),fe==="onBlur")))){const Ns=d==="none"?Ft:ge;te.commit(Ns)}}),pi=ft((mn,In)=>{if(i?.(mn,In),In.isCanceled)return;Pe(mn),(d==="none"&&Ze.current&&q||tt&&!mt.state.inputInsidePopup)&&Ya(tm(mn,A),Yt(In.reason,In.event))}),_d=ft((mn,In)=>{const Ns=qi(mn),Ii=Ne.current??mn;Ne.current=null;const ta=Yt(H1,Ii),Pa=Ns?.closest("a")?.getAttribute("href");if(Pa){Pa.startsWith("#")&&gf(!1,ta);return}if(Qe){const Oo=Array.isArray(ge)?ge:[],vf=PJn(Oo,In,L)?O1t(Oo,In,L):[...Oo,In];if(pi(vf,ta),ta.isCanceled||!(Fe.current?Fe.current.value.trim()!=="":!1))return;mt.state.inputInsidePopup?Ya("",Yt(wy,ta.event)):gf(!1,ta)}else{if(pi(In,ta),ta.isCanceled)return;gf(!1,ta)}}),vg=ft(()=>{const mn=te.inputRef.current?.form??mt.state.inputElement?.form;mn&&typeof mn.requestSubmit=="function"&&mn.requestSubmit()}),Hx=ft(()=>{if(hh(!1),gr?.(!1),ve(!1),ke(null),Ks(d==="none"?{activeIndex:null,selectedIndex:null}:{activeIndex:null}),Qe&&Fe.current&&Fe.current.value!==""&&!Ue.current&&Ya("",Yt(wy)),tt)if(mt.state.inputInsidePopup)Fe.current&&Fe.current.value!==""&&Ya("",Yt(wy));else{const mn=tm(ge,A);Fe.current&&Fe.current.value!==mn&&Ya(mn,Yt(mn===""?wy:Io))}}),wc=g.useMemo(()=>Wr&&Ur?{current:Ur.closest('[role="dialog"]')}:Ze,[Wr,Ur]);Cl({enabled:!e.actionsRef,open:yt,ref:wc,onComplete(){yt||Hx()}}),g.useImperativeHandle(e.actionsRef,()=>({unmount:Hx}),[Hx]),jt(function(){if(yt||(Se.current=null,d==="none"))return;const In=He?Zt:ye.current;Ks({selectedIndex:voe(In,ge,L,Qe)})},[yt,ge,d,Qe,He,Zt,L,Ks]),jt(()=>{S&&(ye.current=Et,Ee.current.length=Et.length)},[S,Et]),jt(()=>{const mn=ce.current;if(mn){const Kl=yt||Wr||mt.state.positionerElement?.hidden===!1;if(mn.hasQuery)wt&&Kl&&mt.set("activeIndex",0),ce.current=null;else if(String(Ft).trim()===""&&(ce.current=null,Kl)){const vf=mn.selection;wt==="always"&&!vf&&mt.state.selectionMode==="none"&&mt.set("activeIndex",0),queueMicrotask(()=>{if(!mt.state.open&&!mt.state.inline||Fe.current&&Fe.current.value.trim()!=="")return;const mh=mt.state.selectedValue,Kv=mt.state.selectionMode==="multiple",Bz=Kv&&Array.isArray(mh)?mh[mh.length-1]:mh,nu=mt.state.selectionMode!=="none"&&Bz!=null;if(nu||vf){const Yx=He||Le?Et:ye.current;mt.set("activeIndex",nu?voe(Yx,mh,mt.state.isItemEqualToValue,Kv):null)}else wt==="always"&&mt.set("activeIndex",0)})}}if(!yt&&!Wr)return;const Ns=He||Le?Et:ye.current,Ii=mt.state.activeIndex;if(Ii==null){if(wt==="always"&&Ns.length>0){mt.set("activeIndex",0);return}Is(void 0,-1,Io);return}if(Ii>=Ns.length){Is(void 0,-1,Io),mt.set("activeIndex",null);return}const ta=Ns[Ii],Pa=Te.current.value,Oo=Pa!==Zkt&&Vm(ta,Pa,mt.state.isItemEqualToValue);(Te.current.index!==Ii||!Oo)&&Is(ta,Ii,Io)},[xs,wt,Is,Le,He,Et,Wr,yt,mt,Ft]),jt(()=>{if(d==="none"){G(String(Ft)!=="");return}G(Qe?Array.isArray(ge)&&ge.length>0:ge!=null)},[G,d,Ft,ge,Qe]),g.useEffect(()=>{He&&wt&&Et.length===0&&Ks({activeIndex:null})},[He,wt,Et.length,Ks]);function Kk(mn){const In=U.initialValue;return Array.isArray(mn)&&Array.isArray(In)?!eK(mn,In,(Ns,Ii)=>Vm(Ns,Ii,L)):mn!==In}ev(we,()=>{!yt||we===""||we===String(St)||ve(!0)});function Yk(){const mn=tm(ge,A);Ft!==mn&&Ya(mn,Yt(Io))}ev(ge,()=>{d!=="none"&&($(De),z(Kk(ge)),te.change(ge),tt&&!st&&!Ka&&Yk())}),ev(Ft,()=>{d==="none"&&($(De),z(Ft!==U.initialValue),te.change(Ft))}),ev(S,()=>{!tt||st||Ka||pe||Yk()});const yg=Hft({open:Wr?!0:yt,onOpenChange:gf,elements:{reference:Ka?Ti:Ei,floating:Ur}}),Gx=b?"grid":"listbox",Xk=yt||Wr,C$=Xk?"true":"false",xg=g.useMemo(()=>{const mn=Ei?.tagName==="INPUT",In=Ei==null||mn,Ns=In||Xk,Ii=In?{autoComplete:"off",spellCheck:"false",autoCorrect:"off",autoCapitalize:"none"}:{};return Ns&&(Ii.role="combobox",Ii["aria-expanded"]=C$,Ii["aria-haspopup"]=Gx,Ii["aria-controls"]=Xk?dr?.id:void 0,Ii["aria-autocomplete"]=H),{reference:Ii,floating:{role:"presentation"}}},[Ei,Xk,C$,Gx,dr?.id,H]),zz=w_(yg,{enabled:!v&&!$e&&C,event:"mousedown-only",toggle:!1,touchOpenDelay:Ka?0:100,reason:Tkn}),Jk=S_(yg,{enabled:!v&&!$e&&!Wr,outsidePressEvent:{mouse:"sloppy",touch:"intentional"},bubbles:Wr?!0:void 0,outsidePress(mn){const In=qi(mn);return!ln(Ti,In)&&!ln(me.current,In)&&!ln(ae.current,In)&&!ln(Aa,In)}}),Kx=F0e(yg,{enabled:!v&&!$e,id:re,listRef:Ee,activeIndex:xs,selectedIndex:zr,virtual:!0,loopFocus:I,allowEscape:I&&!wt,focusItemOnOpen:pe||d==="none"&&!wt?!1:"auto",focusItemOnHover:N,resetOnPointerLeave:!_,orientation:b?"horizontal":void 0,rtl:se==="rtl",disabledIndices:zf,grid:b?dlr:void 0,onNavigate(mn,In){!In&&!yt||Cd==="ending"||Ks(In?{activeIndex:mn,type:Ce.current?w0e:sft}:{activeIndex:mn})}}),eO=g.useMemo(()=>kl(Kx.reference,{onKeyDown(mn){b&&mt.state.activeIndex==null&&(mn.key==="ArrowLeft"||mn.key==="ArrowRight")&&mn.preventBaseUIHandler()}},Jk.reference,zz.reference,xg.reference),[Kx.reference,Jk.reference,zz.reference,xg.reference,b,mt]),_$=g.useMemo(()=>kl(gk,Jk.floating),[Jk.floating]),T$=g.useMemo(()=>kl(Kx.floating,xg.floating),[Kx.floating,xg.floating]),ww=g.useMemo(()=>{const mn=Kx.item;return mn?{...mn,onFocus:void 0}:ai},[Kx.item]);w1t(()=>{mt.update({inline:Q,popupProps:_$,listProps:T$,inputProps:eO,triggerProps:$p,itemProps:ww,setOpen:gf,setInputValue:Ya,setSelectedValue:pi,setIndices:Ks,handleSelection:_d,forceMount:Hr,requestSubmit:vg,onOpenChangeComplete:gr})}),jt(()=>{mt.update({id:re,selectedValue:ge,open:yt,mounted:bc,transitionStatus:Cd,items:S,inline:Q,popupProps:_$,listProps:T$,inputProps:eO,triggerProps:$p,openMethod:Pp,itemProps:ww,selectionMode:d,name:De,form:p,disabled:$e,readOnly:v,required:y,grid:b,virtualized:F,openOnInputClick:C,itemToStringLabel:A,modal:B,autoHighlight:wt,isItemEqualToValue:L,submitOnItemClick:M,hasInputValue:st,inputOwnsFormValue:d==="none"&&(Q||!mt.state.inputInsidePopup)})},[mt,re,ge,yt,bc,Cd,S,_$,T$,eO,ww,Pp,$p,d,De,$e,v,y,b,F,C,A,B,L,M,st,Q,wt,p]);const bg=tf(x,te.inputRef),E$=g.useMemo(()=>({query:we,hasItems:He,filteredItems:Bt,flatFilteredItems:Et}),[we,He,Bt,Et]),I$=g.useMemo(()=>Array.isArray(gn)?"":Hg(gn,P),[gn,P]),Sw=Qe&&Array.isArray(ge)&&ge.length>0,Gv=Qe||d==="none"&&gg?void 0:De,Fz=g.useMemo(()=>!Qe||!Array.isArray(ge)||!De?null:ge.map(mn=>{const In=Hg(mn,P);return a.jsx("input",{type:"hidden",form:p,name:De,value:In,disabled:$e},In)}),[Qe,ge,p,De,P,$e]),N$=a.jsxs(g.Fragment,{children:[e.children,a.jsx("input",{...te.getValidationProps($e,{onFocus(){if(Ka){Ti?.focus();return}(Fe.current||Ti)?.focus()},onChange(mn){if(mn.nativeEvent.defaultPrevented||$e||v)return;const In=mn.currentTarget.value,Ns=In.toLowerCase(),Ii=Yt(Io,mn.nativeEvent),ta=()=>ye.current.findIndex(Oo=>Hg(Oo,P).toLowerCase()===Ns||tm(Oo,A).toLowerCase()===Ns);function Pa(){if(Qe)return;if(d==="none"){Ya(In,Ii);return}let Oo=ta();Oo===-1&&(Oo=ye.current.findIndex((vf,mh)=>{const Kv=Ve.current[mh];return Kv!=null&&Kv.toLowerCase()===Ns}));const Kl=Oo===-1?void 0:ye.current[Oo];Kl!=null&&pi?.(Kl,Ii)}tt&&(Hr(),S&&ta()===-1&&mt.set("forceMounted",!0)),queueMicrotask(Pa)}}),id:re&&Gv==null?`${re}-hidden-input`:void 0,form:p,name:Gv,autoComplete:D,disabled:$e,required:y&&!Sw,readOnly:v,value:I$,ref:bg,style:Gv?aP:bS,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),Fz]});return a.jsx(zkt.Provider,{value:mt,children:a.jsx(Fkt.Provider,{value:yg,children:a.jsx(Ukt.Provider,{value:He,children:a.jsx(Bkt.Provider,{value:E$,children:a.jsx(Vkt.Provider,{value:Ft,children:N$})})})})})}function bQ(e){const{multiple:t=!1,defaultValue:n,value:r,onValueChange:s,autoComplete:i,...o}=e;return a.jsx(glr,{...o,selectionMode:t?"multiple":"single",selectedValue:r,defaultSelectedValue:n,onSelectedValueChange:s,formAutoComplete:i})}function UUe(e){const{children:t,placeholder:n}=e,r=lg(),s=kt(r,fn.itemToStringLabel),i=kt(r,fn.selectedValue),o=kt(r,fn.items),l=kt(r,fn.selectionMode)==="multiple",c=kt(r,fn.hasSelectedValue),u=!c&&n!=null&&t==null,d=kt(r,fn.hasNullItemLabel,u);let f=null;return typeof t=="function"?f=t(i):t!=null?f=t:!c&&n!=null&&!d?f=n:l&&Array.isArray(i)?f=C1t(i,o,s):f=jSe(i,o,s),a.jsx(g.Fragment,{children:f})}const Wkt={..._N,...kp,popupSide:e=>e?{"data-popup-side":e}:null,listEmpty:e=>e?{"data-list-empty":""}:null},vlr=g.createContext(void 0);function ylr(){return g.useContext(vlr)}const Hkt=g.createContext(void 0);function kke(e){const t=g.useContext(Hkt);if(t===void 0&&!e)throw new Error(Nr(21));return t}const Gkt=g.forwardRef(function(t,n){const r=lg(),{buttonRef:s,getButtonProps:i}=gd({native:!1}),o=tf(n,s);function l(u){r.state.setOpen(!1,Yt(b0e,u.nativeEvent,u.currentTarget))}const c=i({onClick:l});return a.jsx("span",{ref:o,...c,"aria-label":"Dismiss",tabIndex:void 0,style:aP})});function Kkt(e){const t=kt(e,fn.mounted),n=kt(e,fn.popupSide),r=kt(e,fn.positionerElement);return t&&r?n:null}function wK(){return KL().filteredItems.length===0}function xlr(e){return e==="rtl"?["ArrowRight","ArrowLeft"]:["ArrowLeft","ArrowRight"]}function blr(e,t){const n=e>=t-1?t-2:e;return n>=0?n:void 0}function Ykt(e,t,n){const r=e.state.listRef.current[t];r&&(e.state.selectionEventRef.current=n,r.click(),e.state.selectionEventRef.current=null)}const Oke=g.forwardRef(function(t,n){const{render:r,className:s,disabled:i=!1,id:o,style:l,...c}=t,{state:u,disabled:d,setTouched:f,setFocused:h,validationMode:p,validation:m}=Ru(),{labelId:v}=yd(),y=ylr(),b=!!kke(!0),S=lg(),k=qkt(),j=Ex(),C=kt(S,fn.required),T=kt(S,fn.disabled),_=kt(S,fn.readOnly),N=kt(S,fn.name),I=kt(S,fn.form),A=kt(S,fn.selectionMode),P=kt(S,fn.autoHighlight),L=kt(S,fn.inputProps),F=kt(S,fn.triggerProps),Q=kt(S,fn.open),q=kt(S,fn.mounted),B=kt(S,fn.selectedValue),V=kt(S,fn.id),H=kt(S,fn.inline),D=kt(S,fn.modal),K=!!P,M=Kkt(S),$=d||T||i,z=wK(),U=b||H,G=!U||D,ne=Zi(o??(U?void 0:V)),X=b?yvt:u,[ee,ie]=g.useState(null),fe=g.useRef(!1),te=g.useRef(null),se=g.useRef(!1),re=A==="none"&&!b,le=ft(Fe=>{const Ae=b||S.state.inline;Ae&&!S.state.hasInputValue&&S.state.setInputValue("",Yt(Io)),S.update({inputElement:Fe,inputInsidePopup:Ae,inputOwnsFormValue:re})}),pe=b?c:m.getValidationProps($,c);function ve(){S.state.setIndices({activeIndex:null,selectedIndex:null,type:S.state.keyboardActiveRef.current?w0e:sft})}function he(){S.state.keyboardActiveRef.current=!1}const ke={...X,open:Q,disabled:$,readOnly:_,popupSide:M,listEmpty:z};function Ee(Fe){if(!y)return;let Ae;const{highlightedChipIndex:ze}=y,je=y.chipsRef.current.length,[Ce,Ue]=xlr(j);return ze!==void 0?(Fe.key===Ce?(Fe.preventDefault(),ze>0?Ae=ze-1:Ae=void 0):Fe.key===Ue?(Fe.preventDefault(),ze<je-1?Ae=ze+1:Ae=void 0):(Fe.key==="Backspace"||Fe.key==="Delete")&&(Fe.preventDefault(),Ae=blr(ze,B.length),ve()),Ae):(Fe.key===Ce&&(Fe.currentTarget.selectionStart??0)===0&&B.length>0&&(Fe.preventDefault(),Ae=je>0?je-1:void 0),Ae)}const Ve=cn("input",t,{state:ke,ref:[n,S.state.inputRef,le],props:[L,F,{value:ee??k,"aria-readonly":_||void 0,"aria-required":C||void 0,"aria-labelledby":v,disabled:$,readOnly:_,required:A==="none"?C:void 0,form:I,...re&&N&&{name:N},id:ne,onFocus(){if(h(!0),!H||!se.current)return;se.current=!1;const Fe=te.current;Fe==null||!Object.hasOwn(S.state.valuesRef.current,Fe)||S.state.setIndices({activeIndex:Fe})},onBlur(){f(!0),h(!1);const Fe=S.state.activeIndex;if(H&&Fe!==null&&P!=="always"&&(te.current=Fe,se.current=!0,S.state.setIndices({activeIndex:null})),p==="onBlur"){const Ae=A==="none"?k:B;m.commit(Ae)}},onCompositionStart(Fe){S4||(fe.current=!0,ie(Fe.currentTarget.value))},onCompositionEnd(Fe){fe.current=!1;const Ae=Fe.currentTarget.value;ie(null),S.state.setInputValue(Ae,Yt(bI,Fe.nativeEvent))},onChange(Fe){const Ae=Fe.nativeEvent,ze=Ae.inputType,je=!ze||ze==="insertReplacementText",Ce=fe.current||!je;function Ue(Te){_||$||!Te||!Ce||(S.state.setOpen(!0,Yt(bI,Ae)),K||ve())}if(fe.current){const Te=Fe.currentTarget.value;ie(Te),Te===""&&!S.state.openOnInputClick&&!S.state.inputInsidePopup&&S.state.setOpen(!1,Yt(wy,Ae));const ce=Te.trim(),ye=K&&ce!=="";Ue(ce),Q&&S.state.activeIndex!==null&&!ye&&ve();return}const ae=Yt(bI,Ae);if(S.state.setInputValue(Fe.currentTarget.value,ae),ae.isCanceled)return;const me=Fe.currentTarget.value==="",Ne=Yt(wy,Ae);me&&!S.state.inputInsidePopup&&(A==="single"&&S.state.setSelectedValue(null,Ne),S.state.openOnInputClick||S.state.setOpen(!1,Ne)),Ue(Fe.currentTarget.value.trim()),Q&&S.state.activeIndex!==null&&!K&&ve()},onKeyDown(Fe){if($||_||Fe.ctrlKey||Fe.shiftKey||Fe.altKey||Fe.metaKey)return;S.state.keyboardActiveRef.current=!0;const Ae=Fe.currentTarget,ze=Ae.scrollWidth-Ae.clientWidth,je=j==="rtl";if(Fe.key==="Home"){ic(Fe);const ae=RLe&&je?Ae.value.length:0;Ae.setSelectionRange(ae,ae),Ae.scrollLeft=0;return}if(Fe.key==="End"){ic(Fe);const ae=RLe&&je?0:Ae.value.length;Ae.setSelectionRange(ae,ae),Ae.scrollLeft=je?-ze:ze;return}if(!q&&Fe.key==="Escape"){const ae=A==="multiple"&&Array.isArray(B)?B.length===0:B===null,me=Yt(b_,Fe.nativeEvent),Ne=A==="multiple"?[]:null;S.state.setInputValue("",me),S.state.setSelectedValue(Ne,me),!ae&&!S.state.inline&&!me.isPropagationAllowed&&Fe.stopPropagation();return}if(y&&Fe.key==="Backspace"&&Ae.value===""&&y.highlightedChipIndex===void 0&&Array.isArray(B)&&B.length>0){const ae=y.chipsRef.current.length,me=ae>0?ae-1:B.length-1,Ne=B.filter((Te,ce)=>ce!==me);ve(),S.state.setSelectedValue(Ne,Yt(Io,Fe.nativeEvent));return}const Ce=y?.highlightedChipIndex!==void 0,Ue=Ee(Fe);if(y?.setHighlightedChipIndex(Ue),Ue!==void 0?y?.chipsRef.current[Ue]?.focus():Ce&&S.state.inputRef.current?.focus(),Fe.which!==229&&Fe.key==="Enter"&&Q){const ae=S.state.activeIndex,me=Fe.nativeEvent;if(ae===null){if(H)return;S.state.setOpen(!1,Yt(Io,me));return}ic(Fe),Ykt(S,ae,me)}},onPointerMove:he,onPointerDown:he},pe],stateAttributesMapping:Wkt}),Ze=b?a.jsx(Gwe.Provider,{value:xvt,children:Ve}):Ve;return a.jsxs(g.Fragment,{children:[Q&&G&&a.jsx(Gkt,{ref:S.state.startDismissRef}),Ze]})}),Xkt=g.forwardRef(function(t,n){const{render:r,className:s,nativeButton:i=!0,disabled:o=!1,id:l,style:c,...u}=t,{state:d,disabled:f,setTouched:h,setFocused:p,validationMode:m,validation:v}=Ru(),{labelId:y}=yd(),x=lg(),b=kt(x,fn.selectionMode),S=kt(x,fn.disabled),k=kt(x,fn.readOnly),j=kt(x,fn.required),C=kt(x,fn.positionerElement),T=kt(x,fn.listElement),_=kt(x,fn.popupId),N=kt(x,fn.triggerProps),I=kt(x,fn.inputInsidePopup),A=kt(x,fn.id),P=kt(x,fn.labelId),L=kt(x,fn.open),F=kt(x,fn.selectedValue),Q=kt(x,fn.activeIndex),q=kt(x,fn.selectedIndex),B=kt(x,fn.hasSelectedValue),V=bK(),H=qkt(),D=bo(),K=f||S||o,M=wK(),$=Kkt(x);bk({id:I?l:void 0});const z=I?l??A:l,U=CSe(y,P);let G;L&&I?G=_??Qkt(A):L&&(G=T?.id);const ne=g.useRef("");function X(pe){ne.current=pe.pointerType}const{reference:ee}=B0e(V,{enabled:!L&&!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(Io))}}),{reference:ie}=w_(V,{enabled:!k&&!S,event:"mousedown"}),{buttonRef:fe,getButtonProps:te}=gd({native:i,disabled:K}),se={...d,open:L,disabled:K,popupSide:$,listEmpty:M,placeholder:b==="none"?!1:!B},re=ft(pe=>{x.set("triggerElement",pe)});return cn("button",t,{ref:[n,fe,re],state:se,props:[N,ie,ee,{id:z,tabIndex:I?0:-1,role:I?"combobox":void 0,"aria-expanded":L,"aria-haspopup":I?"dialog":"listbox","aria-controls":G,"aria-required":I&&j||void 0,"aria-labelledby":U,onPointerDown:X,onPointerEnter:X,onFocus(){p(!0),!(K||k)&&D.start(0,x.state.forceMount)},onBlur(pe){if(!ln(C,pe.relatedTarget)&&(h(!0),p(!1),m==="onBlur")){const ve=b==="none"?H:F;v.commit(ve)}},onMouseDown(pe){if(K||k||(I||V.set("domReferenceElement",pe.currentTarget),x.state.forceMount(),ne.current!=="touch"&&(x.state.inputRef.current?.focus(),I||pe.preventDefault()),L))return;const ve=wr(pe.currentTarget);function he(ke){const Ee=x.state.triggerElement;if(!Ee)return;const Ve=qi(ke),Ze=x.state.positionerElement,Fe=x.state.listElement;ln(Ee,Ve)||ln(Ze,Ve)||ln(Fe,Ve)||xSe(ke,Ee)||x.state.setOpen(!1,Yt(_H,ke))}I&&ve.addEventListener("mouseup",he,{once:!0})},onKeyDown(pe){k||(pe.key==="ArrowDown"||pe.key==="ArrowUp")&&(ic(pe),x.state.setOpen(!0,Yt(k4,pe.nativeEvent)),x.state.inputRef.current?.focus())}},v.getValidationProps(K,u),te],stateAttributesMapping:Wkt})}),wlr=g.createContext(null);function Slr(){return g.useContext(wlr)}function klr(e){const{children:t}=e,{filteredItems:n}=KL(),r=Slr(),s=r?r.items:n;return a.jsx(g.Fragment,{children:s.map(t)})}const Jkt=g.forwardRef(function(t,n){var r;const{render:s,className:i,style:o,children:l,...c}=t,u=lg(),d=bK(),f=!!kke(!0),{filteredItems:h,hasItems:p}=KL(),m=kt(u,fn.selectionMode),v=kt(u,fn.grid),y=kt(u,fn.listProps),x=kt(u,fn.virtualized),b=kt(u,fn.forceMounted),S=m==="multiple",k=h.length===0,j=ft(P=>{u.set("positionerElement",P)}),C=ft(P=>{u.set("listElement",P)}),T=g.useMemo(()=>typeof l=="function"?r||(r=a.jsx(klr,{children:l})):l,[l]),_={empty:k},N=d.useState("floatingId"),I=cn("div",t,{state:_,ref:[n,C,f?null:j],props:[y,{children:T,tabIndex:-1,id:N,role:v?"grid":"listbox","aria-multiselectable":S?"true":void 0,onKeyDown(P){if(!(u.state.disabled||u.state.readOnly)&&P.key==="Enter"){const L=u.state.activeIndex;if(L==null)return;ic(P),Ykt(u,L,P.nativeEvent)}},onKeyDownCapture(){u.state.keyboardActiveRef.current=!0},onPointerMoveCapture(){u.state.keyboardActiveRef.current=!1}},c]});if(x)return I;const A=p&&!b?void 0:u.state.labelsRef;return a.jsx(TP,{elementsRef:u.state.listRef,labelsRef:A,children:I})}),Olr="",jlr=200;function Clr(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 eOt(){const e=bo(),t=g.useRef(null);return g.useEffect(()=>{if(Z3)return;const n=t.current;if(n==null)return;const r=Clr(n);if(r==null)return;const s=r.data,i=`${s}${Olr}`;return r.nodeValue=i,e.start(jlr,()=>{r.nodeValue===i&&(r.nodeValue=s)}),()=>{e.clear(),r.nodeValue===i&&(r.nodeValue=s)}},[t,e]),t}const VUe=g.forwardRef(function(t,n){const{render:r,className:s,style:i,children:o,...l}=t,c=eOt();return cn("div",t,{ref:[n,c],props:[{children:o,role:"status","aria-live":"polite","aria-atomic":!0},l]})}),tOt=g.createContext(void 0);function _lr(){const e=g.useContext(tOt);if(e===void 0)throw new Error(Nr(20));return e}const jke=g.forwardRef(function(t,n){const{keepMounted:r=!1,...s}=t,i=lg(),o=kt(i,fn.mounted),l=kt(i,fn.forceMounted);return o||r||l?a.jsx(tOt.Provider,{value:r,children:a.jsx(K3,{ref:n,...s})}):null}),Cke=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=T0e,style:x,...b}=t,S=lg(),k=bK(),j=_lr(),C=kt(S,fn.modal),T=kt(S,fn.open),_=kt(S,fn.mounted),N=kt(S,fn.openMethod),I=kt(S,fn.positionerElement),A=kt(S,fn.triggerElement),P=kt(S,fn.inputElement),L=kt(S,fn.inputGroupElement),F=kt(S,fn.inputInsidePopup),Q=kt(S,fn.transitionStatus),q=wK(),V=uP({anchor:i??(F?A:L??P),floatingRootContext:k,positionMethod:o,mounted:_,side:l,sideOffset:u,align:c,alignOffset:d,arrowPadding:p,collisionBoundary:f,collisionPadding:h,sticky:m,disableAnchorTracking:v,keepMounted:j,collisionAvoidance:y,lazyFlip:!0});KG(T&&C,N==="touch",I,A);const H={open:T,side:V.side,align:V.align,anchorHidden:V.anchorHidden,empty:q};jt(()=>{S.set("popupSide",V.side)},[S,V.side]);const D=ft(M=>{S.set("positionerElement",M)}),K=dP(t,H,{styles:V.positionerStyles,transitionStatus:Q,props:b,refs:[n,D],hidden:!_,inert:!T});return a.jsxs(Hkt.Provider,{value:V,children:[_&&C&&a.jsx(LL,{inert:fP(!T),cutout:L??P??A}),K]})}),Tlr={...j_,...oh},_ke=g.forwardRef(function(t,n){const{render:r,className:s,style:i,initialFocus:o,finalFocus:l,...c}=t,u=lg(),d=kke(),f=bK(),h=kt(u,fn.mounted),p=kt(u,fn.open),m=kt(u,fn.openMethod),v=kt(u,fn.popupProps),y=kt(u,fn.transitionStatus),x=kt(u,fn.inputInsidePopup),b=kt(u,fn.inputElement),S=kt(u,fn.modal),k=kt(u,fn.id),j=wK(),C=c.id??(x?Qkt(k):void 0);jt(()=>(u.set("popupId",u.state.popupRef.current?.id||C),()=>{u.set("popupId",void 0)}),[u,C]),Cl({open:p,ref:u.state.popupRef,onComplete(){p&&u.state.onOpenChangeComplete(!0)}});const T={open:p,side:d.side,align:d.align,anchorHidden:d.anchorHidden,transitionStatus:y,empty:j},_=cn("div",t,{state:T,ref:[n,u.state.popupRef],props:[v,{id:C,role:x?"dialog":"presentation",onFocus(L){const F=qi(L.nativeEvent);m!=="touch"&&(ln(u.state.listElement,F)||F===L.currentTarget)&&u.state.inputRef.current?.focus()}},__(y),c],stateAttributesMapping:Tlr}),I=o===void 0?x?L=>L==="touch"?u.state.popupRef.current:b:!1:o;let A;l!=null?A=l:A=x?void 0:!1;const P=!x||S;return a.jsx(lP,{context:f,disabled:!h,modal:P,openInteractionType:m,initialFocus:I,returnFocus:A,getInsideElements:()=>[u.state.startDismissRef.current,u.state.endDismissRef.current],children:a.jsxs(g.Fragment,{children:[_,P&&a.jsx(Gkt,{ref:u.state.endDismissRef})]})})}),nOt=g.createContext(void 0);function rOt(){const e=g.useContext(nOt);if(!e)throw new Error(Nr(19));return e}const Elr=g.createContext(!1);function Ilr(){return g.useContext(Elr)}function sOt(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=X0({guess:!0,index:u,textRef:p}),v=lg(),y=Ilr(),x=flr(),b=kt(v,fn.selectionMode),S=kt(v,fn.disabled),k=kt(v,fn.readOnly),j=kt(v,fn.isItemEqualToValue),C=S||d,T=b!=="none",_=u??s??m.index,N=_!==-1,I=kt(v,fn.id),A=kt(v,fn.isActive,_),P=kt(v,fn.isSelected,c),L=kt(v,fn.itemProps),F=g.useRef(null),Q=I!=null&&N?`${I}-${_}`:void 0,q=P&&T;jt(()=>{if(!(N&&(r||u!=null)))return;const U=v.state.listRef.current;return U[_]=F.current,()=>{delete U[_]}},[N,r,_,u,v]),jt(()=>{if(!N||x)return;const z=v.state.valuesRef.current;return z[_]=c,()=>{delete z[_]}},[N,x,_,c,v]),jt(()=>{if(!N||x)return;const z=v.state.selectedValue,U=Array.isArray(z)?z[z.length-1]:z;Vm(c,U,j)&&v.set("selectedIndex",_)},[N,x,v,_,c,j]);const{getButtonProps:B,buttonRef:V}=gd({disabled:C,focusableWhenDisabled:!0,native:f,composite:!0}),H={disabled:C,selected:q,highlighted:A};function D(z){function U(){v.state.handleSelection(z,c)}v.state.submitOnItemClick?(So.flushSync(U),v.state.requestSubmit()):U()}const K={id:Q,role:y?"gridcell":"option","aria-selected":T?q:void 0,tabIndex:void 0,onPointerDownCapture(z){z.isPrimary&&(v.state.pointerDownItemRef.current=z.currentTarget),z.preventDefault()},onMouseDown(z){z.preventDefault()},onClick(z){C||k||D(z.nativeEvent)},onMouseUp(z){const U=v.state.pointerDownItemRef.current===z.currentTarget;v.state.pointerDownItemRef.current=null,!(C||k||z.button!==0||U||!A)&&D(z.nativeEvent)}},M=cn("div",t,{ref:[V,n,m.ref,F],state:H,props:[L,K,h,B]}),$=g.useMemo(()=>({selected:q,textRef:p}),[q,p]);return a.jsx(nOt.Provider,{value:$,children:M})}function Nlr(e){const{componentProps:t,forwardedRef:n}=e,r=lg(),s=kt(r,fn.isItemEqualToValue),{flatFilteredItems:i}=KL(),o=LI(i,t.value??null,s);return a.jsx(sOt,{componentProps:t,forwardedRef:n,virtualized:!0,indexFromFilter:o})}const iOt=g.memo(g.forwardRef(function(t,n){const r=lg(),s=kt(r,fn.virtualized);return s&&t.index==null?a.jsx(Nlr,{componentProps:t,forwardedRef:n}):a.jsx(sOt,{componentProps:t,forwardedRef:n,virtualized:s,indexFromFilter:void 0})})),oOt=g.forwardRef(function(t,n){const{selected:r}=rOt();return t.keepMounted||r?a.jsx(Alr,{...t,ref:n}):null}),Alr=g.memo(g.forwardRef((e,t)=>{const{render:n,className:r,style:s,keepMounted:i,...o}=e,{selected:l}=rOt(),c=g.useRef(null),{transitionStatus:u,setMounted:d}=Sp(l),h=cn("span",e,{ref:[t,c],state:{selected:l,transitionStatus:u},props:[{"aria-hidden":!0,children:"✔️"},o],stateAttributesMapping:oh});return Cl({open:l,ref:c,onComplete(){l||d(!1)}}),h})),aOt=g.forwardRef(function(t,n){const{render:r,className:s,style:i,children:o,...l}=t,{filteredItems:c}=KL(),u=lg(),d=eOt(),f=c.length===0?o:null;return cn("div",t,{ref:[n,u.state.emptyRef,d],props:[{children:f,role:"status","aria-live":"polite","aria-atomic":!0},l]})});function Plr(e){return e==="link"?"ghost":e}function lOt({variant:e,size:t,className:n}){const r=Plr(e);return Z(pP({variant:r,size:t}),r==="default"&&fht,!H0e(t)&&Z(hht,"justify-between"),U0e[r],"data-[placeholder]:text-muted-foreground",Q0e,n)}const Vpe=md(ag,{variants:{multiple:{false:"",true:""}},defaultVariants:{multiple:!1}}),ss={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(AP,"max-h-none overflow-hidden p-0"),positioner:Z(NP,"pointer-events-auto"),searchContainer:RI.container,searchIcon:RI.icon,searchInput:Z(RI.input,"disabled:cursor-not-allowed disabled:opacity-50"),empty:Z(lQ,"empty:hidden"),list:"p-1 empty:p-0",listScroller:"max-h-dropdown overflow-y-auto overflow-x-hidden",item:Vpe({multiple:!1}),itemMulti:Vpe({multiple:!0}),itemRightSlot:"ml-auto flex items-center gap-2 shrink-0",checkContainer:Z($_,"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 $lr({children:e,className:t}){return a.jsx("div",{className:Z("grid gap-2 text-foreground",t),children:e})}function cOt({children:e,name:t,className:n}){return a.jsxs(Y,{variant:"body-sm",role:"alert",id:t!==void 0?`error-${t}`:void 0,className:Z("flex gap-1 text-destructive-foreground",n),children:[a.jsx(At,{size:"xs",className:"mt-1 shrink-0","aria-hidden":!0,children:a.jsx(gP,{})}),a.jsx("span",{children:e})]})}function uOt({children:e}){return a.jsx(Y,{variant:"caption",tone:"muted",children:e})}function Rlr({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 Mlr({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 Dlr({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(cOt,{name:e,className:"truncate",children:n}):t?a.jsx(uOt,{children:t}):null})}const Llr=Object.assign({},{Layout:Mlr,Column:$lr,Label:Rlr,HelpText:uOt,ErrorMsg:cOt,Message:Dlr}),zlr=e=>`error-${e}`,qUe=[],Flr=[];function Foe(e){return e.multiple===!0}const dOt=g.forwardRef((e,t)=>a.jsx(iOt,{ref:Du(t),...e}));dOt.displayName="ComboboxItem";function QUe({option:e}){return a.jsxs("span",{className:ss.optionText,children:[a.jsx("span",{className:ss.optionLabel,children:e.label}),e.description&&a.jsx("span",{className:ss.optionDescription,children:e.description})]})}function fl(e){const{options:t,placeholder:n=Foe(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=Foe(e),T=C?e.clearLabel:void 0,_=wP(),N=g.useId(),I=j??N,A=[m,k?zlr(I):void 0].filter(Boolean).join(" ")||void 0,[P,L]=g.useState(""),F=P.trim(),Q=!C&&b&&F&&!t.some(X=>X.value===F)?{label:`Use “${F}”`,value:F}:void 0,q=Q?[Q,...t]:t,B=C?e.value??qUe:qUe,V=g.useMemo(()=>new Set(B),[B]),H=C?null:t.find(X=>X.value===e.value)??null,D=C?t.filter(X=>V.has(X.value)):Flr,K=D.length===0?n:`${D.length} selected`,M=()=>{Foe(e)&&e.onValueChange?.([])},$=J0(f),z=Bv(),U=H0e(c),G=a.jsxs(a.Fragment,{children:[a.jsxs(Xkt,{id:h,"aria-label":p??(h||_?void 0:C?"Select options":"Select option"),...$x({"aria-label":p}),...BH(!!k),"aria-describedby":A,"data-shape":U?"icon":void 0,className:lOt({variant:l,size:c,className:Z(x&&"w-auto px-2.5",i)}),children:[U?a.jsx("span",{className:"sr-only",children:C?K:a.jsx(UUe,{placeholder:n})}):C?a.jsx("span",{className:Z("truncate",D.length===0&&ss.placeholder),children:K}):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(UUe,{placeholder:n})})]}),y?a.jsx("span",{className:"flex shrink-0 items-center",children:a.jsx(_ht,{className:Z(ss.chevron,(U||x)&&"ml-0")})}):null]}),a.jsx(jke,{container:$,children:a.jsx(Cke,{align:v,sideOffset:4,positionMethod:Av,className:ss.positioner,children:a.jsxs(_ke,{className:ss.popup,children:[a.jsxs("div",{className:ss.searchContainer,children:[a.jsx(Su,{className:ss.searchIcon}),a.jsx(Oke,{className:ss.searchInput,placeholder:r,...mp})]}),a.jsx(aOt,{className:ss.empty,children:s}),a.jsx(Ir,{maxHeight:"var(--spacing-dropdown)",children:a.jsx(of,{className:"scroll-py-8",children:a.jsx("div",{className:z.containerClassName,...z.getContainerProps({}),children:a.jsx(Um,{menu:z,children:a.jsx(Jkt,{className:ss.list,children:X=>{const ee=V.has(X.value);return a.jsx(dOt,{value:X,className:Vpe({multiple:C}),children:C?a.jsxs(a.Fragment,{children:[X.start,a.jsx(QUe,{option:X}),a.jsxs("span",{className:ss.itemRightSlot,children:[X.end?a.jsx("div",{className:ss.optionEnd,children:X.end}):null,a.jsx("span",{className:ss.checkContainer,children:ee?a.jsx(ur,{className:ss.checkIcon}):null})]})]}):a.jsxs(a.Fragment,{children:[X.start,a.jsx(QUe,{option:X}),a.jsxs("span",{className:ss.itemRightSlot,children:[X.end?a.jsx("div",{className:ss.optionEnd,children:X.end}):null,a.jsx("span",{className:ss.checkContainer,children:a.jsx(oOt,{children:a.jsx(ur,{className:ss.checkIcon})})})]})]})},X.value)}})})})})}),B.length>0&&T?a.jsx("div",{className:Z("border-t","border-border","p-1"),children:a.jsx(ue,{type:"button",variant:"destructive-ghost",size:"sm",className:"w-full justify-start",onClick:M,icon:a.jsx(zn,{}),children:T})}):null]})})})]}),ne=C?a.jsx(bQ,{multiple:!0,autoHighlight:!0,items:q,value:D,onValueChange:X=>e.onValueChange?.((X??[]).map(ee=>ee.value)),disabled:o,open:u,onOpenChange:d,children:G}):a.jsx(bQ,{autoHighlight:!0,items:q,value:H,inputValue:P,onInputValueChange:X=>{L(X),S?.(X)},onValueChange:X=>{X&&(e.onValueChange?.(X.value),L(""),S?.(""))},disabled:o,open:u,onOpenChange:d,children:G});return k?a.jsxs("div",{className:ss.root,children:[ne,a.jsx(Llr.ErrorMsg,{name:I,children:k})]}):ne}function Blr({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}=ng({requestContext:f}),{navigate:y,paths:x}=Tn();g.useEffect(()=>{if(m){const k=v instanceof Error?v.message:"Failed to load workflows";Ye.error(`Error loading workflows: ${k}`)}},[m,v]);const b=Object.keys(h).map(k=>({label:h[k]?.name||k,value:k})),S=k=>{t?t(k):k&&k!==e&&y(x.workflowLink(k))};return a.jsx(fl,{options:b,value:e,onValueChange:S,placeholder:p?"Loading workflows...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||p||m,variant:l,size:c,"aria-label":u,align:d})}function Ulr(){const{workflowId:e}=jr(),{data:t,isLoading:n}=ng();return e?n?a.jsx(Lx,{}):t?.[e]?.name||e:null}function Vlr(){const{workflowId:e}=jr();return e?a.jsx(Blr,{value:e,...RP,"aria-label":"Switch workflow"}):null}function qlr(){const{runId:e}=jr();return e?e.split("-")[0]:null}function Qlr(){const{runId:e}=jr();return e?a.jsx(ii,{content:e,tooltip:"Copy run id",variant:"ghost",size:"icon-sm"}):null}const Zlr=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 Wlr(){return a.jsx(ue,{render:a.jsx("a",{target:"_blank",rel:"noopener noreferrer",href:"/swagger-ui"}),variant:"ghost",size:"sm",icon:a.jsx(Zlr,{}),children:"API endpoints"})}function Hlr(e){if("Component"in e&&e.Component){const t=e.Component;return a.jsx(t,{})}return"node"in e?e.node:e.label}function Dt({crumbs:e}){if(e.length===0)return null;const t=e.length-1;return a.jsx(wke,{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(j5,{as:i?ac:"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:Hlr(n)},n.id)})})}const MP=({queryOptions:e}={})=>{const t=Ge();return _t({queryKey:["mastra-packages"],queryFn:()=>t.getSystemPackages(),...e})},fOt=()=>{const{data:e,isLoading:t}=MP();return{hasObservability:!!(e?.observabilityEnabled??e?.packages?.some(r=>r.name==="@mastra/observability")),isLoading:t}},Glr=40,Klr="",qpe=e=>new Date(e.createdAt).getTime(),Ylr=(e,t)=>qpe(e)-qpe(t),SK=({threadId:e,agentId:t,memory:n,requestContext:r,queryOptions:s})=>{const i=Ge();return Dm({queryKey:["memory","messages",e,t,r],initialPageParam:Klr,queryFn:n&&e?({pageParam:o})=>i.listThreadMessages(e,{agentId:t,requestContext:r,includeSystemReminders:!0,perPage:Glr,orderBy:{field:"createdAt",direction:"DESC"},filter:o?{dateRange:{end:new Date(o)}}:void 0}):V0,getNextPageParam:(o,l,c)=>{if(!o.hasMore||o.messages.length===0)return;const u=new Date(Math.min(...o.messages.map(qpe))).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(Ylr);return{...o,messages:c}},staleTime:0,gcTime:0,retry:!1,refetchOnWindowFocus:!1,...s})};function Xlr({agentId:e,path:t,agentVersionId:n,requestContext:r,queryOptions:s}){const i=Ge();return _t({queryKey:["agent-plan",e,n,t,r],queryFn:()=>(n?i.getAgent(e,{versionId:n}):i.getAgent(e)).readPlan(t,r),retry:!1,...s})}const Jlr={"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 ecr(e={}){const{enabled:t=!0,agentId:n,runId:r,threadId:s,resourceId:i,taskId:o}=e,l=Ge(),[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 A=await l.streamBackgroundTasks({agentId:n,runId:r,threadId:s,resourceId:i,taskId:o});if(!A){p(new Error("Stream connection failed"));return}N===y.current&&f(!0);const P=A.getReader();for(v.current=P;!I.signal.aborted;){const{done:L,value:F}=await P.read();if(L)break;const Q=F;Q.type!=="background-task-output"&&u(q=>({...q,[Q.payload.taskId]:{...q[Q.payload.taskId],...Q.payload,status:Jlr[Q.type],args:("args"in Q.payload?Q.payload.args:void 0)??q[Q.payload.taskId]?.args??{}}}))}}catch(A){A?.name!=="AbortError"&&N===y.current&&p(A instanceof Error?A:new Error(String(A)))}finally{N===y.current&&f(!1)}},[l,n,r,s,i,o,k]);g.useEffect(()=>{if(!t){k();return}return j(),k},[t,j,k]);const C=g.useCallback(()=>{k()},[k]),T=g.useCallback(()=>{j()},[j]);return{tasks:c,isConnected:d,error:h,disconnect:C,reconnect:T,runningTasks:x,completedTasks:b,failedTasks:S,clearCompletedAndFailedTasks:()=>{u(N=>{const I={...N};return Object.values(I).forEach(A=>{(A.status==="completed"||A.status==="failed"||A.status==="cancelled"||A.status==="timed_out")&&delete I[A.taskId]}),I})}}}const tcr=({backgroundTaskId:e,queryOptions:t})=>{const n=Ge();return _t({queryKey:["background-task",e],queryFn:()=>n.getBackgroundTask(e),...t})},ncr=(e,t)=>["browser-session-probe",e,t],rcr={hasSession:!0,screencastAvailable:!0},scr=e=>!e||typeof e!="object"?!1:"status"in e&&e.status===404||"statusCode"in e&&e.statusCode===404;function icr({agentId:e,threadId:t,queryOptions:n}){const r=Ge();return _t({queryKey:ncr(e,t),queryFn:async()=>{if(!e)return{hasSession:!1,screencastAvailable:!1};try{return await r.getAgent(e).browserSession(t)}catch(s){if(scr(s))return rcr;throw s}},refetchOnWindowFocus:!0,staleTime:0,retry:1,...n})}const ocr="MODEL_NOT_ALLOWED";function acr(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!==ocr)return null;const r=n.error;return{message:r.message||t.message||"Model not allowed by admin policy",attempted:r.attempted,offendingLabel:r.offendingLabel}}const zC=({queryOptions:e,...t}={})=>{const n=Ge(),r=Object.keys(t).length>0?t:void 0;return _t({queryKey:["stored-agents",r],queryFn:()=>n.listStoredAgents(r),...e})},kK=({agentId:e,status:t,requestContext:n,queryOptions:r}={})=>{const s=Ge();return _t({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})},Tke=({agentId:e,requestContext:t,queryOptions:n}={})=>{const r=Ge();return _t({queryKey:["stored-agent-dependents",e,t],queryFn:()=>r.getStoredAgent(e).dependents(t),retry:!1,...n})},FC=({agentId:e,requestContext:t,queryOptions:n}={})=>{const r=Ge(),s=mr(),i=o=>{acr(o)&&s.invalidateQueries({queryKey:["builder-settings"]})};return{createStoredAgent:Sn({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:Sn({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:Sn({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})}},YL=({agentId:e,params:t,requestContext:n,queryOptions:r})=>{const s=Ge();return _t({queryKey:["agent-versions",e,t,n],queryFn:e?()=>s.getStoredAgent(e).listVersions(t,n):V0,...r})},hOt=({agentId:e,versionId:t,requestContext:n,queryOptions:r})=>{const s=Ge();return _t({queryKey:["agent-version",e,t,n],queryFn:()=>s.getStoredAgent(e).getVersion(t,n),...r})},lcr=({agentId:e,fromVersionId:t,toVersionId:n,requestContext:r,queryOptions:s})=>{const i=Ge();return _t({queryKey:["agent-versions-compare",e,t,n,r],queryFn:()=>i.getStoredAgent(e).compareVersions(t,n,r),...s})};function ZUe(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function ccr(e,t,n,r){const s=Ge(),[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=ZUe(C):_?.content?I=ZUe(_.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 bd=({agentId:e,requestContext:t,queryOptions:n}={})=>{const r=Ge();return _t({queryKey:["agent",e,t],queryFn:()=>e?r.getAgent(e).details(t):null,retry:!1,...n})},Cp=({requestContext:e,queryOptions:t}={})=>{const n=Ge();return _t({queryKey:["agents",e],queryFn:()=>n.listAgents(e),...t})},ucr=({agentId:e,queryOptions:t})=>{const n=Ge(),r=mr();return Sn({mutationFn:async s=>n.getAgent(e).reorderModelList(s),onSuccess:()=>{r.invalidateQueries({queryKey:["agent",e]})},onError:s=>{console.error("Error reordering model list",s)},...t})},dcr=({agentId:e,queryOptions:t})=>{const n=Ge(),r=mr();return Sn({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 fcr({queryOptions:e}={}){const t=Ge();return Sn({mutationFn:({agentId:n,threadId:r})=>t.getAgent(n).closeBrowser(r),onError:n=>{console.error("[useCloseBrowser] Error closing browser:",n)},...e})}function Tk({queryOptions:e}={}){const t=Ge();return _t({queryKey:["stored-skills"],queryFn:()=>t.listStoredSkills(),...e})}const XL=({queryOptions:e}={})=>{const t=Ge();return _t({queryKey:["channels","platforms"],queryFn:()=>t.channels.listPlatforms(),staleTime:60*1e3,retry:!1,...e})},pOt=({platform:e,agentId:t,queryOptions:n})=>{const r=Ge();return _t({queryKey:["channels","installations",e,t],queryFn:()=>r.channels.listInstallations(e,t),staleTime:10*1e3,retry:!1,...n})},hcr=({platform:e,queryOptions:t})=>{const n=Ge(),r=mr();return Sn({mutationFn:s=>n.channels.reconcileInstallation(e,s),onSuccess:()=>{r.invalidateQueries({queryKey:["channels","installations",e]})},...t})},pcr=({platform:e,queryOptions:t})=>{const n=Ge(),r=mr();return Sn({mutationFn:({agentId:s,options:i})=>n.channels.connect(e,s,{...i,redirectUrl:window.location.href}),onSuccess:()=>{r.invalidateQueries({queryKey:["channels","installations",e]})},...t})},mOt=({platform:e,queryOptions:t})=>{const n=Ge(),r=mr();return Sn({mutationFn:s=>n.channels.disconnect(e,s),onSuccess:()=>{r.invalidateQueries({queryKey:["channels","installations",e]})},...t})},mcr=({queryOptions:e}={})=>{const t=Ge();return Sn({mutationFn:async({agentId:n,toolId:r,input:s,playgroundRequestContext:i})=>{const o=new d_;return Object.entries(i??{}).forEach(([l,c])=>{o.set(l,c)}),t.getAgent(n).executeTool(r,{data:s,requestContext:o})},...e})};function gcr({value:e,onValueChange:t,placeholder:n="Select an agent...",searchPlaceholder:r="Search agents...",emptyText:s="No agents found.",className:i,disabled:o=!1,variant:l,size:c,"aria-label":u,align:d}){const{data:f={},isLoading:h,isError:p,error:m}=Cp(),{navigate:v,paths:y}=Tn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load agents";Ye.error(`Error loading agents: ${S}`)}},[p,m]);const x=Object.keys(f).map(S=>({label:f[S]?.name||S,value:S})),b=S=>{t?t(S):S&&S!==e&&v(y.agentLink(S))};return a.jsx(fl,{options:x,value:e,onValueChange:b,placeholder:h?"Loading agents...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||h||p,variant:l,size:c,"aria-label":u,align:d})}function vcr(){const{agentId:e}=jr(),{data:t,isLoading:n}=Cp();return e?n?a.jsx(Lx,{}):t?.[e]?.name||e:null}function ycr(){const{agentId:e}=jr();return e?a.jsx(gcr,{value:e,...RP,"aria-label":"Switch agent"}):null}const OK=e=>{const t=JSON.stringify(e);return g.useCallback(n=>{const r={};return JSON.parse(t).forEach((s,i)=>{r[s]=n[i]?.data}),{data:r,isLoading:n.some(s=>s.isLoading),error:n.find(s=>s.error)?.error??null}},[t])},gOt=({datasetId:e,itemId:t,queryOptions:n})=>{const r=Ge();return _t({queryKey:["dataset-item",e,t],queryFn:()=>r.getDatasetItem(e,t),retry:!1,...n})},WUe=10,nA=({datasetId:e,search:t,version:n,orderBy:r,queryOptions:s})=>{const i=Ge(),{inView:o,setRef:l}=K0(),c=Dm({queryKey:["dataset-items",e,t,n,r],queryFn:async({pageParam:f})=>await i.listDatasetItems(e,{page:f,perPage:WUe,search:t||void 0,version:n||void 0,orderBy:r}),initialPageParam:0,getNextPageParam:(f,h,p)=>{if(f?.items?.length&&!((p+1)*WUe>=(f?.pagination?.total??0)))return p+1},retry:!1,...s}),u=c.data?.pages.flatMap(f=>f?.items??[])??[],d=c.data?.pages[0]?.pagination?.total;return g.useEffect(()=>{o&&c.hasNextPage&&!c.isFetchingNextPage&&c.fetchNextPage()},[o,c]),{...c,data:u,total:d,setEndOfListElement:l}},pl=({queryOptions:e}={})=>{const t=Ge(),n=mr(),r=Sn({mutationFn:h=>t.createDataset(h),onSuccess:()=>{n.invalidateQueries({queryKey:["datasets"]})},...e?.createDataset}),s=Sn({mutationFn:h=>t.updateDataset(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["datasets"]}),n.invalidateQueries({queryKey:["dataset",p.datasetId]})},...e?.updateDataset}),i=Sn({mutationFn:h=>t.deleteDataset(h),onSuccess:()=>{n.invalidateQueries({queryKey:["datasets"]})},...e?.deleteDataset}),o=Sn({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=Sn({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=Sn({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=Sn({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=Sn({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=Sn({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:Sn({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:Sn({mutationFn:h=>t.triggerDatasetExperiment(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["dataset-experiments",p.datasetId]})},...e?.triggerExperiment}),deleteExperiment:Sn({mutationFn:h=>t.deleteExperiment(h),onSuccess:()=>{n.invalidateQueries({queryKey:["experiments"]}),n.invalidateQueries({queryKey:["experiment"]}),n.invalidateQueries({queryKey:["dataset-experiments"]}),n.invalidateQueries({queryKey:["dataset-experiment"]}),n.invalidateQueries({queryKey:["dataset-experiment-results"]}),n.invalidateQueries({queryKey:["review-items"]}),n.invalidateQueries({queryKey:["completed-items"]}),n.invalidateQueries({queryKey:["experiment-review-summary"]})},...e?.deleteExperiment}),updateExperiment:Sn({mutationFn:h=>t.updateDatasetExperiment(h),onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["experiments"]}),n.invalidateQueries({queryKey:["experiment",p.experimentId]}),n.invalidateQueries({queryKey:["dataset-experiments",p.datasetId]}),n.invalidateQueries({queryKey:["dataset-experiment",p.datasetId,p.experimentId]})},...e?.updateExperiment}),updateExperimentResult:Sn({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})}},Ek=({pagination:e,queryOptions:t}={})=>{const n=Ge();return _t({queryKey:["datasets",e],queryFn:()=>n.listDatasets(e),placeholderData:r=>r,...t})},xcr=20,bcr=({filter:e,orderBy:t,queryOptions:n}={})=>{const r=Ge(),{inView:s,setRef:i}=K0(),o=e?.targetType||void 0,l=e?.targetId?[e.targetId]:void 0,c=Dm({queryKey:["datasets","infinite",{targetType:o,targetIds:l,orderBy:t}],queryFn:({pageParam:u})=>r.listDatasets({page:u,perPage:xcr,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}},zx=({datasetId:e,queryOptions:t})=>{const n=Ge();return _t({queryKey:["dataset",e],queryFn:()=>n.getDataset(e),...t})},wcr=({datasetId:e,experimentIds:t,baselineId:n,queryOptions:r})=>{const s=Ge();return _t({queryKey:["compare-experiments",e,t,n],queryFn:()=>s.compareExperiments({datasetId:e,experimentIds:t,baselineId:n}),...r})},jK=2e3,Qpe=100,Scr=100,CK=e=>e==="running"||e==="pending",vOt=(e,t,n)=>({queryKey:["dataset-experiment",t,n],queryFn:()=>e.getDatasetExperiment(t,n),gcTime:0,staleTime:0,refetchInterval:r=>CK(r.state.data?.status)?jK:!1}),yOt=(e,t,n)=>({queryKey:["dataset-experiment-scores",t,n],queryFn:async()=>{const r=[];let s=0;for(;;){const o=await e.listScoresByRunId({runId:t,page:s,perPage:Scr});if(r.push(...o.scores),!o.pagination.hasMore)break;s++}const i={};for(const o of r)(i[o.entityId]??=[]).push(o);return i},refetchInterval:CK(n)?jK:!1}),kcr=(e,t,n,r)=>({queryKey:["dataset-experiment-results-all",t,n,r],queryFn:async()=>{const s=[];let i=0;for(;;){const o=await e.listDatasetExperimentResults(t,n,{page:i,perPage:Qpe});if(s.push(...o.results),!o.pagination.hasMore||o.results.length===0)break;i++}return s},refetchInterval:CK(r)?jK:!1}),xOt=({datasetId:e,experimentId:t,queryOptions:n})=>{const r=Ge(),{queryKey:s,queryFn:i,gcTime:o,staleTime:l,refetchInterval:c}=vOt(r,e,t);return _t({queryKey:s,queryFn:i,gcTime:o,staleTime:l,refetchInterval:c,...n})},Eke=({datasetId:e,experimentIds:t})=>{const n=Ge(),r=OK(t);return Mm({queries:t.map(s=>vOt(n,e,s)),combine:r})},Ocr=({datasetId:e,experimentId:t,experimentStatus:n,orderBy:r,queryOptions:s})=>{const i=Ge(),{inView:o,setRef:l}=K0(),c=Dm({queryKey:["dataset-experiment-results",e,t,n,r],queryFn:async({pageParam:u})=>i.listDatasetExperimentResults(e,t,{page:u,perPage:Qpe,orderBy:r}),initialPageParam:0,getNextPageParam:(u,d,f)=>{if(u?.results?.length&&!((f+1)*Qpe>=(u?.pagination?.total??0)))return f+1},refetchInterval:CK(n)?jK:!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}},jcr=({datasetId:e,experiments:t})=>{const n=Ge(),r=OK(t.map(s=>s.id));return Mm({queries:t.map(s=>kcr(n,e,s.id,s.status)),combine:r})},JL=({experimentId:e,experimentStatus:t,queryOptions:n})=>{const r=Ge(),{queryKey:s,queryFn:i,refetchInterval:o}=yOt(r,e,t);return _t({queryKey:s,queryFn:i,refetchInterval:o,...n})},Ccr=({experiments:e})=>{const t=Ge(),n=OK(e.map(r=>r.id));return Mm({queries:e.map(r=>yOt(t,r.id,r.status)),combine:n})},_cr=({datasetId:e,itemId:t,queryOptions:n})=>{const r=Ge();return _t({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})},Tcr=({datasetId:e,itemId:t,datasetVersion:n,latestVersion:r,queryOptions:s})=>{const i=Ge();return _t({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})},Ecr=10,bOt=({datasetId:e,queryOptions:t})=>{const n=Ge();return Dm({queryKey:["dataset-versions",e],queryFn:async({pageParam:r})=>n.listDatasetVersions(e,{page:r,perPage:Ecr}),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})},Icr=({pagination:e,queryOptions:t}={})=>{const n=Ge();return _t({queryKey:["experiments",e],queryFn:()=>n.listExperiments(e),...t})},wOt=({experimentId:e,queryOptions:t})=>{const n=Ge();return _t({queryKey:["experiment",e],queryFn:()=>n.getExperiment(e),...t})};function Ncr({workflowId:e,queryOptions:t}){const n=Ge();return _t({queryKey:["workflow-schema",e],queryFn:async()=>{if(!e)throw new Error("No workflow selected");return n.getWorkflow(e).getSchema()},staleTime:300*1e3,...t})}function SOt({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}=Ek(),{navigate:y,paths:x}=Tn();g.useEffect(()=>{if(m){const j=v instanceof Error?v.message:"Failed to load datasets";Ye.error(`Error loading datasets: ${j}`)}},[m,v]);const S=(h?.datasets??[]).map(j=>({label:j.name,value:j.id})),k=j=>{t?t(j):j&&j!==e&&y(x.datasetLink(j))};return a.jsx(fl,{options:S,value:e,onValueChange:k,placeholder:p?"Loading datasets...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||p||m,variant:l,size:c,"aria-label":u,align:d,container:f})}function Acr(){const{datasetId:e}=jr(),{data:t,isLoading:n}=Ek();return e?n?a.jsx(Lx,{}):t?.datasets?.find(r=>r.id===e)?.name??e:null}function Pcr(){const{datasetId:e}=jr();return e?a.jsx(SOt,{value:e,...RP,"aria-label":"Switch dataset"}):null}const $cr=({serverId:e,appResourceUri:t,queryOptions:n})=>{const r=Ge();return _t({queryKey:["mcp-app-resource",e,t],queryFn:async()=>t?(await r.readMcpServerResource(e,t)).contents[0]?.text??null:null,enabled:t!==void 0,...n})};function kOt({queryOptions:e}={}){const t=Ge();return _t({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 Rcr=({serverId:e,toolId:t,requestContext:n,queryOptions:r})=>{const s=Ge();return _t({queryKey:["mcp-server-tool",e,t],queryFn:()=>s.getMcpServerTool(e,t).details(n),...r})},Mcr=({serverId:e,toolId:t,queryOptions:n})=>{const r=Ge();return Sn({mutationFn:({data:s,requestContext:i})=>r.getMcpServerTool(e,t).execute({data:s,requestContext:i}),...n})},OOt=({selectedServer:e,queryOptions:t})=>{const n=Ge();return _t({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})},DP=({requestContext:e,queryOptions:t}={})=>{const n=Ge();return _t({queryKey:["mcp-servers"],queryFn:async()=>(await n.getMcpServers(e)).servers,...t})};async function HUe(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 Dcr(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 HUe(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 HUe(o)).result?.tools??[]}}const Lcr=({queryOptions:e}={})=>{const t=Ge().options?.headers??{};return Sn({mutationFn:n=>Dcr(n,t),...e})};function jOt({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}=DP(),{navigate:y,paths:x}=Tn();g.useEffect(()=>{if(m){const k=v instanceof Error?v.message:"Failed to load MCP servers";Ye.error(`Error loading MCP servers: ${k}`)}},[m,v]);const b=h.map(k=>({label:k.name,value:k.id})),S=k=>{t?t(k):k&&k!==e&&y(x.mcpServerLink(k))};return a.jsx(fl,{options:b,value:e,onValueChange:S,placeholder:p?"Loading MCP servers...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||p||m,variant:l,size:c,"aria-label":u,align:d,container:f})}function zcr(){const{serverId:e}=jr(),{data:t,isLoading:n}=DP();return e?n?a.jsx(Lx,{}):t?.find(r=>r.id===e)?.name||e:null}function Fcr(){const{serverId:e}=jr();return e?a.jsx(jOt,{value:e,...RP,"aria-label":"Switch MCP server"}):null}const LP=({requestContext:e,queryOptions:t}={})=>{const n=Ge();return _t({queryKey:["processors"],queryFn:()=>n.listProcessors(e),...t})},COt=({processorId:e,requestContext:t,queryOptions:n})=>{const r=Ge();return _t({queryKey:["processor",e],queryFn:()=>r.getProcessor(e).details(t),...n})},Bcr=({requestContext:e,queryOptions:t}={})=>{const n=Ge();return Sn({mutationFn:async({processorId:r,phase:s,messages:i,agentId:o})=>n.getProcessor(r).execute({phase:s,messages:i,agentId:o,requestContext:e}),...t})};function Ucr({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}=LP(),{navigate:v,paths:y}=Tn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load processors";Ye.error(`Error loading processors: ${S}`)}},[p,m]);const x=Object.keys(f).filter(S=>{const k=f[S];return k?.phases&&k.phases.length>0}).map(S=>({label:f[S]?.name||S,value:S})),b=S=>{t?t(S):S&&S!==e&&(f[S]?.isWorkflow?v(y.workflowLink(S)+"/graph"):v(y.processorLink(S)))};return a.jsx(fl,{options:x,value:e,onValueChange:b,placeholder:h?"Loading processors...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||h||p,variant:l,size:c,"aria-label":u,align:d})}function Vcr(){const{processorId:e}=jr(),{data:t,isLoading:n}=LP();return e?n?a.jsx(Lx,{}):t?.[e]?.name||e:null}function qcr(){const{processorId:e}=jr();return e?a.jsx(Ucr,{value:e,...RP,"aria-label":"Switch processor"}):null}const Boe=[400,401,403,404,501];function Cs(e){if(!e||typeof e!="object")return!1;if("status"in e&&e.status===401||"statusCode"in e&&e.statusCode===401)return!0;if("message"in e){const t=e.message;if(typeof t=="string")return/\bstatus:\s*401\b/.test(t)}return!1}function _s(e){if(!e||typeof e!="object")return!1;if("status"in e&&e.status===403||"statusCode"in e&&e.statusCode===403)return!0;if("message"in e){const t=e.message;if(typeof t=="string")return/\bstatus:\s*403\b/.test(t)}return!1}function Ik(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 e6(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 Qcr=["Observability storage domain is not available","Scores storage domain is not available"];function t6(e){if(!e||typeof e!="object"||!("message"in e))return!1;const t=e.message;return typeof t!="string"?!1:Qcr.some(n=>t.includes(n))}function _Ot(e){if(!e||typeof e!="object")return!1;if("status"in e){const t=e.status;return Boe.includes(t)}if("statusCode"in e){const t=e.statusCode;return Boe.includes(t)}if("message"in e){const t=e.message;if(typeof t=="string")return Boe.some(n=>new RegExp(`\\bstatus:\\s*${n}\\b`).test(t))}return!1}function Zcr(e,t){return _Ot(t)?!1:e<3}const Wcr=25,Hcr=15e3;function Gcr(e){return e6(e.state.error,"scores")||t6(e.state.error)?!1:Hcr}function Kcr(e,t,n){if(e?.pagination?.hasMore)return n+1}function Ycr(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 Xcr=({scorerId:e,entityId:t,entityType:n,queryOptions:r})=>{const s=Ge(),{inView:i,setRef:o}=K0(),l=Dm({queryKey:["scores",e,t,n],queryFn:({pageParam:f})=>s.listScoresByScorerId({scorerId:e,page:f,perPage:Wcr,entityId:t,entityType:n}),initialPageParam:0,getNextPageParam:Kcr,select:f=>Ycr(f),refetchInterval:Gcr,...r}),{hasNextPage:c,isFetchingNextPage:u,fetchNextPage:d}=l;return g.useEffect(()=>{i&&c&&!u&&d()},[i,c,u,d]),{...l,setEndOfListElement:o}},Jcr=e=>{const t=Ge(),[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}},TOt=({requestContext:e,queryOptions:t}={})=>{const n=Ge();return _t({queryKey:["scorers",e],queryFn:()=>n.listScorers(e),staleTime:0,gcTime:0,...t})},eur=15e3;function tur(e){return e6(e.state.error,"scores")||t6(e.state.error)?!1:eur}const Ike=({traceId:e="",spanId:t="",page:n,queryOptions:r})=>{const s=Ge();return _t({queryKey:["trace-span-scores",e,t,n],queryFn:()=>s.listScoresBySpan({traceId:e,spanId:t,page:n||0,perPage:10}),refetchInterval:tur,gcTime:0,staleTime:0,...r})},nur=({queryOptions:e}={})=>{const t=Ge();return Sn({mutationFn:async({scorerName:n,traceId:r,spanId:s})=>await t.score({scorerName:n,targets:[{traceId:r,spanId:s}]}),...e})},EOt=({scorerId:e,status:t,requestContext:n,queryOptions:r}={})=>{const s=Ge();return _t({queryKey:["stored-scorer",e,t,n],queryFn:()=>e?s.getStoredScorer(e).details(n,{status:t}):null,...r})},IOt=({scorerId:e,requestContext:t,queryOptions:n}={})=>{const r=Ge(),s=mr();return{createStoredScorer:Sn({mutationFn:i=>r.createStoredScorer(i),onSuccess:()=>{s.invalidateQueries({queryKey:["stored-scorers"]}),s.invalidateQueries({queryKey:["scorers"]})},...n?.createStoredScorer}),updateStoredScorer:Sn({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:Sn({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})}},NOt=({scorerId:e,params:t,requestContext:n,queryOptions:r})=>{const s=Ge();return _t({queryKey:["scorer-versions",e,t,n],queryFn:()=>s.getStoredScorer(e).listVersions(t,n),...r})},rur=({scorerId:e,versionId:t,requestContext:n,queryOptions:r})=>{const s=Ge();return _t({queryKey:["scorer-version",e,t,n],queryFn:()=>s.getStoredScorer(e).getVersion(t,n),...r})},Fx=(e,t)=>TOt({...e,requestContext:t});function sur({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}=Fx(),{navigate:v,paths:y}=Tn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load scorers";Ye.error(`Error loading scorers: ${S}`)}},[p,m]);const x=Object.keys(f).map(S=>({label:f[S]?.scorer.config.name||S,value:S})),b=S=>{t?t(S):S&&S!==e&&v(y.scorerLink(S))};return a.jsx(fl,{options:x,value:e,onValueChange:b,placeholder:h?"Loading scorers...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||h||p,variant:l,size:c,"aria-label":u,align:d})}function iur(){const{scorerId:e}=jr(),{data:t,isLoading:n}=Fx();return e?n?a.jsx(Lx,{}):t?.[e]?.scorer.config.name||e:null}function our(){const{scorerId:e}=jr();return e?a.jsx(sur,{value:e,...RP,"aria-label":"Switch scorer"}):null}function aur(){const{scorerId:e}=jr(),{data:t,isLoading:n}=EOt({scorerId:e,status:"draft",queryOptions:{enabled:!!e}});return e?n?a.jsx(Lx,{}):t?.name??"Scorer not found":null}const Uo=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"})]}),AOt=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"})}),lur=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"})}),cur=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"})]}),L_=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"})]}),uur=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 8.98824 8.33142",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M5.70011e-05 6.409V0H1.04865V6.409C1.04875 6.89152 1.43994 7.28283 1.92248 7.28283H8.3581V8.33142H1.92248C0.860814 8.33142 0.000149953 7.47065 5.70011e-05 6.409Z",fill:"currentColor"}),a.jsx("path",{d:"M8.08006 0.945713C8.27714 0.733828 8.6087 0.72151 8.82077 0.918405C9.03289 1.11551 9.04518 1.44767 8.84808 1.6598L6.08595 4.63218C5.90127 4.83085 5.59525 4.85557 5.38074 4.68953L4.03177 3.64571L2.74765 5.07183C2.55386 5.28688 2.22206 5.30441 2.00694 5.11074C1.79189 4.91695 1.77435 4.58515 1.96803 4.37003L3.57915 2.58278L3.65357 2.51451C3.83887 2.37494 4.09997 2.37165 4.28982 2.51861L5.64358 3.56652L8.08006 0.945713Z",fill:"currentColor"})]});function aj(e){return a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 10.123 10.123",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M4.50195 1.53809H5.62109V0H6.75098V1.53809H7.5293L7.64258 1.54395C8.19939 1.60066 8.63379 2.0708 8.63379 2.64258V3.37305H10.123V4.50195H8.63379V5.62109H10.123V6.75H8.63379V7.57812L8.62891 7.69141C8.57589 8.2109 8.16211 8.62387 7.64258 8.67676L7.5293 8.68262H6.75098V10.123H5.62109V8.68262H4.50195V10.123H3.37305V8.68262H2.59375L2.48047 8.67676C1.96102 8.62383 1.54817 8.21082 1.49512 7.69141L1.48926 7.57812V6.75H0V5.62109H1.48926V4.50195H0V3.37305H1.48926V2.64258C1.48926 2.07084 1.92371 1.60071 2.48047 1.54395L2.59375 1.53809H3.37305V0H4.50195V1.53809ZM2.61914 7.55273H7.50488V2.66699H2.61914V7.55273Z",fill:"currentColor"})})}const dur=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"})}),tw=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"})]}),fur=e=>a.jsx("svg",{width:"17",height:"18",viewBox:"0 0 17 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M8.40864 11.9983C7.58064 11.9733 6.84164 11.6153 6.31564 11.0563C6.31464 11.0563 6.31464 11.0553 6.31464 11.0553C5.78864 10.4963 5.47564 9.73633 5.50064 8.90833C5.52564 8.08033 5.88464 7.34133 6.44364 6.81533C7.00264 6.28833 7.76264 5.97633 8.59064 6.00133C9.41864 6.02633 10.1576 6.38433 10.6836 6.94333H10.6846C11.2106 7.50333 11.5236 8.26233 11.4986 9.09033C11.4726 9.91833 11.1146 10.6583 10.5556 11.1843C9.99664 11.7103 9.23664 12.0233 8.40864 11.9983ZM16.1266 8.15033L14.3606 7.74033C14.2316 7.14133 14.0146 6.57633 13.7216 6.05733L14.7726 4.57933C14.9116 4.38533 14.8926 4.12033 14.7296 3.94633L13.9206 3.08733C13.7576 2.91333 13.4946 2.87933 13.2916 3.00533L11.7526 3.96533C11.2526 3.64133 10.7016 3.39033 10.1116 3.22633L9.80964 1.43833C9.76964 1.20333 9.56964 1.02833 9.33164 1.02133L8.15264 0.985326C7.91364 0.978326 7.70364 1.14033 7.64964 1.37233L7.24064 3.13933C6.64164 3.26733 6.07664 3.48433 5.55664 3.77733L4.07864 2.72633C3.88464 2.58833 3.61964 2.60633 3.44664 2.76933L2.58664 3.57833C2.41364 3.74133 2.37964 4.00533 2.50564 4.20733L3.46564 5.74633C3.14164 6.24633 2.89064 6.79833 2.72564 7.38833L0.937635 7.68933C0.702635 7.72933 0.528635 7.92933 0.520635 8.16733L0.485635 9.34733C0.477635 9.58533 0.639635 9.79533 0.872635 9.84933L2.63864 10.2583C2.76764 10.8573 2.98464 11.4233 3.27764 11.9423L2.22564 13.4203C2.08764 13.6143 2.10564 13.8793 2.26964 14.0523L3.07864 14.9123C3.24164 15.0853 3.50464 15.1203 3.70664 14.9933L5.24564 14.0333C5.74663 14.3583 6.29764 14.6093 6.88764 14.7733L7.18964 16.5613C7.22864 16.7963 7.42864 16.9713 7.66764 16.9783L8.84663 17.0143C9.08564 17.0213 9.29564 16.8593 9.34964 16.6273L9.75864 14.8603C10.3576 14.7323 10.9226 14.5153 11.4416 14.2213L12.9206 15.2733C13.1146 15.4113 13.3786 15.3933 13.5526 15.2293L14.4116 14.4213C14.5856 14.2573 14.6196 13.9943 14.4936 13.7923L13.5336 12.2533C13.8576 11.7523 14.1086 11.2013 14.2726 10.6113L16.0616 10.3103C16.2966 10.2703 16.4706 10.0703 16.4776 9.83233L16.5136 8.65233C16.5206 8.41433 16.3586 8.20433 16.1266 8.15033Z",fill:"currentColor"})}),fd=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 11.185 11.185",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.0293 1.16491L4.81958 0.801671L4.81955 0.801686L5.0293 1.16491ZM5.75391 1.16491L5.96365 0.801686L5.96363 0.801671L5.75391 1.16491ZM9.04492 3.06531L9.25474 2.70212L9.25467 2.70208L9.04492 3.06531ZM9.40723 7.49304L9.82666 7.49332V7.49304H9.40723ZM9.04492 8.11999L8.8352 7.75675L8.83518 7.75676L9.04492 8.11999ZM5.75391 10.0204L5.96363 10.3836L5.96365 10.3836L5.75391 10.0204ZM5.0293 10.0204L4.81955 10.3836L4.81963 10.3837L5.0293 10.0204ZM1.73828 8.11999L1.94803 7.75676L1.948 7.75675L1.73828 8.11999ZM1.37598 7.49304H0.956538L0.956538 7.49332L1.37598 7.49304ZM1.73828 3.06531L1.94802 3.42854L1.94803 3.42853L1.73828 3.06531ZM5.59277 3.38366L5.59283 2.96423H5.59277V3.38366ZM3.38379 5.59167L2.96435 5.59159V5.59167H3.38379ZM5.59277 7.80066V8.2201H5.59283L5.59277 7.80066ZM7.80078 5.59167H8.22022V5.59159L7.80078 5.59167ZM5.0293 1.16491L5.23902 1.52816C5.33331 1.47372 5.44989 1.47372 5.54419 1.52816L5.75391 1.16491L5.96363 0.801671C5.60978 0.59738 5.17342 0.59738 4.81958 0.801671L5.0293 1.16491ZM5.75391 1.16491L5.54416 1.52814L8.83518 3.42853L9.04492 3.06531L9.25467 2.70208L5.96365 0.801686L5.75391 1.16491ZM9.04492 3.06531L8.83511 3.42849C8.92979 3.48319 8.98779 3.5839 8.98779 3.69226H9.40723H9.82666C9.82666 3.28328 9.60799 2.90619 9.25474 2.70212L9.04492 3.06531ZM9.40723 3.69226H8.98779V7.49304H9.40723H9.82666V3.69226H9.40723ZM9.40723 7.49304L8.98779 7.49276C8.98772 7.6015 8.92949 7.70231 8.8352 7.75675L9.04492 8.11999L9.25464 8.48324C9.60821 8.2791 9.82639 7.90167 9.82666 7.49332L9.40723 7.49304ZM9.04492 8.11999L8.83518 7.75676L5.54416 9.65715L5.75391 10.0204L5.96365 10.3836L9.25467 8.48322L9.04492 8.11999ZM5.75391 10.0204L5.54419 9.65714C5.44996 9.71154 5.33331 9.71156 5.23897 9.65711L5.0293 10.0204L4.81963 10.3837C5.17339 10.5878 5.60977 10.5879 5.96363 10.3836L5.75391 10.0204ZM5.0293 10.0204L5.23904 9.65715L1.94803 7.75676L1.73828 8.11999L1.52854 8.48322L4.81955 10.3836L5.0293 10.0204ZM1.73828 8.11999L1.948 7.75675C1.85371 7.70231 1.79549 7.6015 1.79541 7.49276L1.37598 7.49304L0.956538 7.49332C0.956809 7.90167 1.17499 8.2791 1.52856 8.48324L1.73828 8.11999ZM1.37598 7.49304H1.79542V3.69226H1.37598H0.956538V7.49304H1.37598ZM1.37598 3.69226H1.79542C1.79542 3.58378 1.85339 3.48318 1.94802 3.42854L1.73828 3.06531L1.52854 2.70207C1.17507 2.90617 0.956538 3.2833 0.956538 3.69226H1.37598ZM1.73828 3.06531L1.94803 3.42853L5.23904 1.52814L5.0293 1.16491L4.81955 0.801686L1.52854 2.70208L1.73828 3.06531ZM5.59277 3.38366V2.96423C4.14162 2.96423 2.96463 4.14015 2.96435 5.59159L3.38379 5.59167L3.80323 5.59175C3.80342 4.60382 4.60458 3.8031 5.59277 3.8031V3.38366ZM3.38379 5.59167H2.96435C2.96435 7.04322 4.14132 8.2201 5.59277 8.2201V7.80066V7.38122C4.6046 7.38122 3.80323 6.57991 3.80323 5.59167H3.38379ZM5.59277 7.80066L5.59283 8.2201C7.04429 8.2199 8.22022 7.04294 8.22022 5.59167H7.80078H7.38134C7.38134 6.57999 6.58061 7.38108 5.59272 7.38122L5.59277 7.80066ZM7.80078 5.59167L8.22022 5.59159C8.21994 4.14043 7.04398 2.96443 5.59283 2.96423L5.59277 3.38366L5.59272 3.8031C6.58062 3.80324 7.38115 4.60374 7.38134 5.59175L7.80078 5.59167Z",fill:"currentColor"})}),bx=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"})]}),hur=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"})}),pur=typeof window<"u"&&window.MASTRA_SIGNALS_UI==="true",mur={name:"Intelligence",url:"/intelligence",activePaths:["/intelligence"],Icon:zht,isOnMastraPlatform:!0,hidden:!pur},Nke=[{key:"primitives",title:"Primitives",items:[{name:"Agents",url:"/agents",Icon:Uo,isOnMastraPlatform:!0},{name:"Prompts",url:"/prompts",Icon:dur,isOnMastraPlatform:!0},{name:"Workflows",url:"/workflows",Icon:Ol,isOnMastraPlatform:!0},{name:"Processors",url:"/processors",Icon:aj,isOnMastraPlatform:!1,foldable:!0},{name:"MCP Servers",url:"/mcps",Icon:L_,isOnMastraPlatform:!0,foldable:!0},{name:"Tools",url:"/tools",Icon:fd,isOnMastraPlatform:!0,foldable:!0},{name:"Workspaces",url:"/workspaces",Icon:hur,isOnMastraPlatform:!0,foldable:!0}]},{key:"evaluation",title:"Evaluation",items:[{name:"Scorers",url:"/scorers",Icon:tw,isOnMastraPlatform:!0},{name:"Datasets",url:"/datasets",Icon:AOt,isOnMastraPlatform:!0},{name:"Experiments",url:"/experiments",Icon:lur,isOnMastraPlatform:!0},{name:"Review Queue",url:"/experiments/review-queue",Icon:Iht,isOnMastraPlatform:!0}]},{key:"observability",title:"Observability",items:[{name:"Metrics",url:"/metrics",Icon:uur,isOnMastraPlatform:!0},{name:"Traces",url:"/traces",Icon:bx,isOnMastraPlatform:!0},mur,{name:"Logs",url:"/logs",Icon:cur,isOnMastraPlatform:!0}]}],Ake=[{name:"Settings",url:"/settings",Icon:fur,isOnMastraPlatform:!1},{name:"Resources",url:"/resources",Icon:kht,isOnMastraPlatform:!0}],gur=[...Nke.flatMap(e=>e.items),...Ake];function vur(e){return gur.find(t=>t.url===e)}function Ts(e,t){const n=vur(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 Pke=e=>{if(!e)return"";try{return decodeURIComponent(e)}catch{return e}},POt=e=>{const t=Pke(e);return t.length>8?`${t.slice(0,8)}...`:t},$Ot={id:"agent",Component:vcr,Switcher:ycr},yur={id:"scorer",Component:iur,Switcher:our},xur={id:"processor",Component:Vcr,Switcher:qcr},bur={id:"mcp-server",Component:zcr,Switcher:Fcr},GUe={id:"workflow",Component:Ulr,Switcher:Vlr},_K={id:"dataset",Component:Acr,Switcher:Pcr},ROt={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 Uoe=null;function wur(){return Uoe||(Uoe=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Ai(()=>import("./core-QQAS7ifM.js"),__vite__mapDeps([0,1,2,3,4]),import.meta.url),Ai(()=>import("./engine-javascript-DSQaR0Yq.js"),__vite__mapDeps([5,2,3]),import.meta.url)]);return e({themes:[Ai(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Ai(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Ai(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Ai(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Ai(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Ai(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Ai(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Ai(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Ai(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Ai(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Ai(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Ai(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Ai(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Ai(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([6,7,8]),import.meta.url),Ai(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Ai(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Uoe}async function Sur(e,t){const n=ROt[t?.toLowerCase()];if(!n)return null;const r=await wur(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function MOt(e){const t=e?.split(".").pop()?.toLowerCase();return t?ROt[t]:void 0}function kur({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(ut,{children:e}),t&&a.jsx(mc,{delay:10,children:a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("button",{type:"button","aria-label":r,className:Z(Ln,On,"rounded-sm",ji),children:a.jsx(At,{size:"xs",children:a.jsx(hp,{})})})}),a.jsx(Dn,{side:"top",className:"max-w-60",children:t})]})})]})}let KUe;const DOt=()=>KUe??=Promise.all([Ai(()=>import("./standalone-Dfz2oS5J.js"),[],import.meta.url),Ai(()=>import("./babel-lWBcy2sH.js"),[],import.meta.url),Ai(()=>import("./estree-Dd9JfUIE.js"),[],import.meta.url)]).catch(e=>{throw KUe=void 0,e}),C5=async e=>{const[t,n,r]=await DOt();return await t.format(e,{semi:!1,parser:"json",printWidth:80,tabWidth:2,plugins:[n,r]})},LOt=async e=>{const[t,n,r]=await DOt();return await t.format(e,{parser:"babel-ts",printWidth:80,tabWidth:2,plugins:[n,r]})},wQ=e=>{try{const t=JSON.parse(e);return!!t&&typeof t=="object"}catch{return!1}},Our=Oi(gt(),n2n());function Voe(e,t){if(!e)return"__custom__";for(const[n,r]of Object.entries(e))if(JSON.stringify(r)===t)return n;return"__custom__"}function jur(e){try{return JSON.stringify(JSON.parse(e))}catch{return null}}const zOt=({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(()=>Voe(t,l)),{handleCopy:v}=Bm({text:u}),[y,x]=g.useState(l);y!==l&&(x(l),d(c),h(c),m(Voe(t,l)));const b=g.useMemo(()=>{const N=jur(u);return N?N!==l:u!==f},[l,u,f]),S=()=>{let N;try{N=JSON.parse(u)}catch{Ye.error("Invalid JSON");return}const I=Our.safeParse(N);if(!I.success){Ye.error(`${e} must be a JSON object`);return}r(I.data)},k=()=>{d(f),m(Voe(t,l))},j=Z(Ln,On),C=async()=>{if(!wQ(u)){Ye.error("Invalid JSON");return}const N=await C5(u);d(N)},T=async N=>{if(m(N),N==="__custom__"||!t)return;const I=t[N];if(I){const A=await C5(JSON.stringify(I));d(A)}},_=N=>{d(N),p!=="__custom__"&&m("__custom__")};return a.jsx(mc,{children:a.jsxs("div",{children:[a.jsxs(ht,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs(kur,{tooltip:i,children:[e," (JSON)"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[o,a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:C,className:j,children:a.jsx(At,{children:a.jsx(Ua,{})})})}),a.jsxs(Dn,{children:["Format the ",e," JSON"]})]}),a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:v,className:j,children:a.jsx(At,{children:a.jsx(zm,{})})})}),a.jsxs(Dn,{children:["Copy ",e]})]})]})]}),t&&Object.keys(t).length>0&&a.jsxs(ht,{children:[a.jsxs(ut,{className:"sr-only",children:[e," preset"]}),a.jsxs(ps,{value:p,onValueChange:T,children:[a.jsx(gs,{children:a.jsx(ms,{placeholder:"Select a preset..."})}),a.jsxs(vs,{children:[a.jsx(hr,{value:"__custom__",children:"Custom"}),Object.keys(t).map(N=>a.jsx(hr,{value:N,children:N},N))]})]})]}),a.jsx(Or,{value:u,onChange:_,showCopyButton:!1,className:s})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[b&&a.jsx(ue,{variant:"default",size:"icon-md",type:"button",tooltip:`Revert ${e} changes`,onClick:k,children:a.jsx(zn,{})}),a.jsx(ue,{icon:a.jsx(ur,{}),type:"button",onClick:S,children:"Save"})]})]})})},Cur={align:"shift"};function FOt({label:e,icon:t,open:n,onOpenChange:r,children:s}){return a.jsxs(jp,{open:n,onOpenChange:r,children:[a.jsx(sf,{variant:"ghost",size:"icon-md",type:"button",tooltip:e,"aria-label":e,children:t}),a.jsx(lh,{align:"start",collisionAvoidance:Cur,className:"w-[min(480px,calc(100vw-2rem))] p-0",children:a.jsx("div",{onSubmit:i=>i.stopPropagation(),children:a.jsx(Ir,{className:"w-full",maxHeight:"min(600px, calc(100dvh - 8rem))",children:a.jsx("div",{className:"space-y-4 p-4",children:s})})})})]})}function _ur(){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 $ke({entityType:e,entityId:t}){const[n,r]=g.useState(!1),[s,i]=xr(e,t),o=_ur(),l=c=>{i(c),Ye.success("Request context saved locally"),r(!1)};return a.jsx(FOt,{label:"Request context",icon:a.jsx(bEn,{}),open:n,onOpenChange:r,children:a.jsx(zOt,{label:"Request Context",presets:o,value:s,onSave:l,editorClassName:"h-[260px]"})})}function BOt({entityType:e,entityId:t,extraFields:n,onSaveExtra:r,onOpenChange:s}){const[i,o]=g.useState(!1),[l,c]=yke(e,t),u=f=>{o(f),s?.(f)},d=f=>{c(f),r?.(),Ye.success("Run options saved locally"),u(!1)};return a.jsxs(FOt,{label:"Run options",icon:a.jsx(bx,{}),open:i,onOpenChange:u,children:[n,a.jsx(zOt,{label:"Tracing Options",value:l,onSave:d,editorClassName:"h-[260px]"})]})}function Tur({workflowId:e,resourceId:t,setResourceId:n}){const[r,s]=g.useState(t);return a.jsxs(a.Fragment,{children:[a.jsx($ke,{entityType:"workflow",entityId:e}),a.jsx(BOt,{entityType:"workflow",entityId:e,onOpenChange:i=>{i&&s(t)},onSaveExtra:()=>n(r),extraFields:a.jsxs(ht,{children:[a.jsx(ut,{children:"Resource ID"}),a.jsx(wn,{value:r,onChange:i=>s(i.target.value),placeholder:"e.g. tenant-42"}),a.jsx(no,{children:"Ignored when server auth derives the resource ID from the user."})]})})]})}function SQ({icon:e,label:t,tooltipContent:n,docsHref:r}){return a.jsxs(Fn,{children:[a.jsx(Mn,{render:a.jsx("span",{role:"button",tabIndex:0,"aria-disabled":"true","aria-label":t,className:"inline-flex",children:a.jsx(ue,{variant:"ghost",size:"icon-md",disabled:!0,"aria-hidden":"true",tabIndex:-1,children:e})})}),a.jsx(Dn,{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(Zs,{className:"size-3"})]})]})})]})}const Eur=({scheduleId:e,queryOptions:t})=>{const n=Ge();return _t({queryKey:["schedule",e],queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return n.getSchedule(e)},...t})},TK=({queryOptions:e,...t}={})=>{const n=Ge();return _t({queryKey:["schedules",t],queryFn:async()=>(await n.listSchedules(t)).schedules,...e})},YUe=25,Iur=({scheduleId:e,queryOptions:t})=>{const n=Ge(),{inView:r,setRef:s}=K0(),i=Dm({queryKey:["schedule-triggers",e],initialPageParam:void 0,queryFn:async({pageParam:d})=>e?n.listScheduleTriggers(e,{limit:YUe,toActualFireAt:d}):{triggers:[]},getNextPageParam:d=>{if(!(!d?.triggers?.length||d.triggers.length<YUe))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}},Nur=({scheduleId:e,queryOptions:t})=>{const n=Ge(),r=mr();return Sn({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 qoe({value:e,icon:t,label:n}){return a.jsxs(si,{value:e,children:[a.jsx(At,{size:"xs",children:t}),a.jsx(Y,{variant:"caption",className:"text-inherit",children:n})]})}function Aur({workflowId:e,activeTab:t,showObservability:n=!1}){const{navigate:r}=Tn(),{data:s,isSuccess:i}=TK({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(Wc,{value:t,defaultTab:t,onValueChange:u,className:"min-w-0",children:a.jsxs(Hc,{variant:"pill-ghost",children:[a.jsx(qoe,{value:"graph",icon:a.jsx(Ol,{}),label:"Graph"}),n&&a.jsx(qoe,{value:"traces",icon:a.jsx(bx,{}),label:"Traces"}),!d&&a.jsx(qoe,{value:"schedules",icon:a.jsx(C0,{}),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(SQ,{icon:a.jsx(bx,{}),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(SQ,{icon:a.jsx(C0,{}),label:"Schedules",tooltipContent:"Configure a schedule on this workflow to enable Schedules.",docsHref:"https://mastra.ai/docs/workflows/scheduled-workflows"})]})]})}const Pur=({children:e})=>{const{workflowId:t,runId:n}=jr();return a.jsx(vwe,{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(Mur,{children:e})})},$ur=e=>e==="graph"||e==="traces"||e==="schedules",Rur=({workflowId:e})=>{const t=Dr();return W0({"g$+t":()=>t(`/workflows/${encodeURIComponent(e)}/traces`)}),null};function Mur({children:e}){const{workflowId:t,runId:n}=jr(),r=e0e("/workflows/:workflowId/:tab/*"),{isLoading:s}=yL({workflowId:t,requestContext:xr("workflow",t)[0],queryOptions:{enabled:!!t}}),{hasObservability:i}=fOt(),o=$ur(r?.params.tab)?r.params.tab:"none",l=[Ts("/workflows"),n?{...GUe,to:`/workflows/${encodeURIComponent(t??"")}/graph`}:GUe,...n?[{id:"workflow-run",Component:qlr,Action:Qlr}]:[]];if(!t)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:l}),children:[a.jsx("h1",{className:"sr-only",children:t}),a.jsx("div",{className:"flex h-full flex-col items-center justify-center",children:a.jsx(Y,{variant:"body",tone:"ink",className:"text-center",children:"No workflow ID provided"})})]});if(s&&o==="graph")return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:l}),children:[a.jsx("h1",{className:"sr-only",children:t}),a.jsx(xt,{className:"h-full"})]});const c=u=>a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:l}),headerActions:a.jsx(Wlr,{}),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(Aur,{workflowId:t,activeTab:o,showObservability:i}),u]})]});return a.jsxs(Krt,{children:[a.jsx(Rur,{workflowId:t}),o==="graph"?a.jsx(Lkt,{children:a.jsx(bke,{workflowId:t,initialRunId:n,children:a.jsx(Dkt,{children:c(a.jsx(Gar,{leftSlot:a.jsx(Dur,{workflowId:t,initialRunId:n}),children:e}))})})},t):c(e)]})}function Dur({workflowId:e,initialRunId:t}){const[n]=xr("workflow",e),{canExecute:r,canDelete:s}=Za();return a.jsx(tlr,{workflowId:e,initialRunId:t,requestContext:n,runActionsSlot:i=>a.jsx(Tur,{workflowId:e,...i}),canExecute:r("workflows"),canDelete:s("workflows")})}const UOt=md(Z(pr,"rounded-xl transition-all duration-normal ease-out-custom motion-reduce:transition-none"),{variants:{elevation:{flat:"shadow-none",raised:""},interactive:{true:Z(hP,q0e,"cursor-pointer active:scale-99"),false:""}},compoundVariants:[{elevation:"flat",interactive:!0,class:Ix}],defaultVariants:{elevation:"raised",interactive:!1}}),hl=g.forwardRef(({className:e,elevation:t,interactive:n,as:r,...s},i)=>{const o=r||(n?"button":"div");return a.jsx(o,{ref:i,type:o==="button"?"button":void 0,className:Z(UOt({elevation:t,interactive:n}),e),...s})});hl.displayName="Card";function VOt({className:e,elevation:t,LinkComponent:n="a",...r}){return a.jsx(n,{className:Z(UOt({elevation:t,interactive:!0}),e),...r})}const kQ=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}));kQ.displayName="CardHeader";const nw=g.forwardRef(({className:e,...t},n)=>a.jsx("h3",{ref:n,className:Z("text-subheading text-foreground",e),...t}));nw.displayName="CardTitle";const Zj=g.forwardRef(({className:e,...t},n)=>a.jsx("p",{ref:n,className:Z("text-caption text-muted-foreground",e),...t}));Zj.displayName="CardDescription";const Lur=md("",{variants:{density:{default:"p-3",compact:"p-2"}},defaultVariants:{density:"default"}}),qm=g.forwardRef(({className:e,density:t,...n},r)=>a.jsx("div",{ref:r,className:Z(Lur({density:t}),e),...n}));qm.displayName="CardContent";const zur=g.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,className:Z("flex items-center p-3 pt-0",e),...t}));zur.displayName="CardFooter";const XUe=["blue","green","orange","purple","pink","amber","cyan"];function Rke(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 EK=e=>XUe[Rke(e)%XUe.length]??"blue",m0=e=>`var(--badge-${e}-indicator)`,Fur={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"},qOt=e=>Fur[e],Bur=e=>({background:`var(--badge-${e}-strong)`,foreground:`var(--badge-${e}-foreground)`,tint:`var(--badge-${e}-indicator)`}),JUe={goal:"green",outcome:"orange",behavior:"blue",sentiment:"purple"},eVe=["pink","amber"],Uur={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"},Vur={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 Mke(e){const t=e.toLowerCase();return(Object.hasOwn(JUe,t)?JUe[t]:void 0)??eVe[Rke(t)%eVe.length]??"pink"}function Bx(e){return`var(--chart-${Mke(e)})`}function QOt(e){return Uur[Mke(e)]}function qur(e){return Vur[Mke(e)]}const zP=[{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"}];zP.map(e=>e.name);Object.fromEntries(zP.map(e=>[e.name,e.description]));function n6(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 vp(e,t){return e.find(n=>n.name===t)?.label??Qur(t)}function US(e,t){return e.find(n=>n.name===t)?.description||void 0}function Qur(e){return e.split(/[-_]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function IK(e){return`${e} ${e===1?"trace":"traces"}`}function Zur(e){return`${e} ${e===1?"theme":"themes"}`}function ZOt(e,t){if(t<=0)return`${IK(e)} in this snapshot`;const n=Math.round(e/t);return`${e} of ${n} traces in this snapshot (${Math.round(t*100)}%)`}const Dke={timeZone:"UTC"};function _5(e){return MI(e,{...Dke,now:0})??e}function NK(e){return Jr(e,"date-time",Dke)??e}function Zpe(e,t){return cJn(e,t,Dke)??`${e}–${t}`}const Wur=[["chat.completion","1.2s"],["tool.search_docs","340ms"],["workflow.support","2.8s"]],OQ=e=>({color:Bx(e)}),tVe=()=>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 T5(e){return new Intl.NumberFormat("en-US").format(e)}function Hur(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 Gur({progress:e}){const t=e.signalCatalog??zP,n=t.filter(s=>s.enabled).length,r=t.filter(s=>s.enabled&&s.status==="ready").length;return a.jsxs("dl",{className:"mt-4 grid gap-2 sm:grid-cols-3",children:[a.jsxs("div",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:Ma({tone:"muted",variant:"caption"}),children:"Traces analyzed"}),a.jsx("dd",{className:Z(Ma({tone:"ink",variant:"heading"}),"mt-1"),children:T5(e.traceCount)})]}),a.jsxs("div",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:Ma({tone:"muted",variant:"caption"}),children:"Trace signal types ready"}),a.jsxs("dd",{className:Z(Ma({tone:"ink",variant:"heading"}),"mt-1"),children:[e.signalCatalog?r:e.availableSignals.length," of ",n]})]}),a.jsxs("div",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:Ma({tone:"muted",variant:"caption"}),children:"Status"}),a.jsx("dd",{className:Z(Ma({tone:"ink",variant:"heading"}),"mt-1 capitalize"),children:e.status})]})]})}function Kur({progress:e}){if(!e)return null;const t=e.signalCatalog??zP;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:n6(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=vp(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:OQ(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:[T5(r.generated)," generated · ",T5(r.embedded)," embedded"]})]},n)})})}function Yur({progress:e,signalCatalog:t}){const n=e?.signalCatalog??t,r=n.filter(s=>s.enabled&&s.status!=="ready");return r.length===0?null:a.jsxs("section",{className:"rounded-lg border border-border bg-background p-4","aria-labelledby":"pending-signals-heading",children:[a.jsx(Y,{as:"h2",variant:"subheading",tone:"ink",id:"pending-signals-heading",children:"Signals building themes"}),a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-1",children:"Themes appear once enough new traces are analyzed, embedded, and clustered."}),a.jsx("ul",{"aria-label":"Pending trace signals",className:"mt-3 grid gap-2 sm:grid-cols-2",children:r.map(s=>{const i=e?.signals[s.name]??{generated:0,embedded:0};return a.jsxs("li",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx(Y,{font:"body",as:"span",variant:"subheading",style:OQ(s.name),children:vp(n,s.name)}),a.jsx(Y,{font:"body",as:"span",variant:"caption",tone:"muted",className:"capitalize",children:s.status})]}),US(n,s.name)?a.jsx(Y,{font:"body",variant:"caption",tone:"muted",className:"mt-1",children:US(n,s.name)}):null,a.jsxs(Y,{font:"body",variant:"caption",tone:"muted",className:"mt-1",children:[T5(i.generated)," generated · ",T5(i.embedded)," embedded"]})]},s.name)})})]})}const Wpe=({actionSlot:e,LinkComponent:t="a",progress:n,signalCatalog:r,isRangeEmpty:s})=>{const i=Hur(n,s),o=r??n?.signalCatalog??zP,c=n6(o,o.filter(u=>u.enabled).map(u=>u.name)).map(u=>({key:u,label:vp(o,u),description:US(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:Wur.map(([u,d])=>a.jsxs("div",{className:Z(pr,"flex items-center justify-between rounded px-3 py-1.5"),children:[a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"muted",children:u}),a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"muted",children:d})]},u))})]}),a.jsx(tVe,{}),a.jsxs(hl,{as:"div",role:"listitem",className:"flex min-h-50 flex-col items-center p-5 text-center",elevation:"raised",children:[a.jsx(Y,{as:"h2",variant:"heading",tone:"ink",children:"Trace Intelligence"}),a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-0.5",children:"Finds recurring themes"}),a.jsx("div",{"aria-hidden":"true",className:"mt-5 flex size-14 items-center justify-center rounded-full border border-brand-green-indicator bg-fill-subtle",children:a.jsx(yP,{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(tVe,{}),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:OQ(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:OQ(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(Gur,{progress:n}):null,a.jsx(Kur,{progress:n})]})]}),a.jsxs("div",{className:"mt-4 flex shrink-0 flex-wrap items-center gap-2 sm:justify-end",children:[e,a.jsxs(ue,{icon:a.jsx(Zs,{}),render:a.jsx("a",{href:"https://mastra.ai/en/docs/mastra-platform/trace-intelligence",target:"_blank",rel:"noopener noreferrer"}),size:"sm",children:["Read the docs",a.jsx("span",{className:"sr-only",children:" (opens in new tab)"})]}),a.jsx(ue,{icon:a.jsx(bx,{}),render:a.jsx(t,{href:"/traces"}),variant:"primary",size:"sm",children:"View incoming traces"})]})]})]})})};function nVe(e){return a.jsx(Wpe,{...e})}async function Xur(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 w2={cacheScope:"oss-studio",request:Xur,LinkComponent:"a",getTraceHref:e=>`/traces?traceId=${encodeURIComponent(e)}`,signalCatalog:zP},Lke=g.createContext(w2);function pa(){return g.useContext(Lke)}function Jur(e,t){const n=new URLSearchParams({entityType:t});return e(`/api/learning/entities?${n}`)}function edr(e,t,n){const r=new URLSearchParams({entityType:n});return e(`/api/learning/entities/${encodeURIComponent(t)}/progress?${r}`)}function WOt(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 HOt(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 tdr(e,t,n,r,s,i){const o=new URLSearchParams({entityType:n,signalName:r,snapshotId:s});return e(zke(t,i,`?${o}`))}function r6(e){return e.map(t=>`${t.signalName}:${t.kind==="theme"?t.themeId:"noise"}`).join(",")}function ndr(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",r6(c)),e(zke(t,i,`/examples?${u}`))}function rdr(e,t,n,r,s,i=100){const o=new URLSearchParams({entityType:n,signalName:r,limit:String(i)});return e(zke(t,s,`/history?${o}`))}function sdr(e,t,n,r,s){const i=new URLSearchParams({entityType:n,signalName:r,snapshotId:s});return e(KOt(t,`?${i}`))}function idr(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",r6(l)),e(KOt(t,`/examples?${c}`))}async function GOt(e,t,n,r,s){const i=await rVe(e,t,n,r,s,0),o=[...i.paths],l={...i.themes};let c=i.nextOffset;for(;c!==void 0;){const u=await rVe(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 rVe(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 odr(e,t){return e(`/api/learning/traces/${encodeURIComponent(t)}/summary`)}function zke(e,t,n){return`/api/learning/entities/${encodeURIComponent(e)}/themes/${encodeURIComponent(t)}${n}`}function KOt(e,t){return`/api/learning/entities/${encodeURIComponent(e)}/noise${t}`}function YOt(e,t,n=!0){const{cacheScope:r,request:s}=pa();return _t({queryKey:["entity-learning",r,t,e,"progress"],queryFn:()=>edr(s,e??"",t),enabled:n&&!!e})}function XOt(e){const{cacheScope:t,request:n}=pa();return _t({queryKey:["entity-learning",t,"entities",e],queryFn:()=>Jur(n,e)})}function JOt(e,t,n,r,s){const{cacheScope:i,request:o}=pa(),l=r?.toISOString(),c=s?.toISOString();return _t({queryKey:["entity-learning",i,t,e,"theme-snapshots",n,l,c],queryFn:()=>WOt(o,e,t,n,r,s),enabled:n.length>=2,staleTime:3e4})}const adr=.01;function ldr(e,t){return String(e[t.id])}function cdr(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 Dcr(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 HUe(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 HUe(o)).result?.tools??[]}}const Lcr=({queryOptions:e}={})=>{const t=Ge().options?.headers??{};return Sn({mutationFn:n=>Dcr(n,t),...e})};function jOt({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}=DP(),{navigate:y,paths:x}=Tn();g.useEffect(()=>{if(m){const k=v instanceof Error?v.message:"Failed to load MCP servers";Ye.error(`Error loading MCP servers: ${k}`)}},[m,v]);const b=h.map(k=>({label:k.name,value:k.id})),S=k=>{t?t(k):k&&k!==e&&y(x.mcpServerLink(k))};return a.jsx(fl,{options:b,value:e,onValueChange:S,placeholder:p?"Loading MCP servers...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||p||m,variant:l,size:c,"aria-label":u,align:d,container:f})}function zcr(){const{serverId:e}=jr(),{data:t,isLoading:n}=DP();return e?n?a.jsx(Lx,{}):t?.find(r=>r.id===e)?.name||e:null}function Fcr(){const{serverId:e}=jr();return e?a.jsx(jOt,{value:e,...RP,"aria-label":"Switch MCP server"}):null}const LP=({requestContext:e,queryOptions:t}={})=>{const n=Ge();return _t({queryKey:["processors"],queryFn:()=>n.listProcessors(e),...t})},COt=({processorId:e,requestContext:t,queryOptions:n})=>{const r=Ge();return _t({queryKey:["processor",e],queryFn:()=>r.getProcessor(e).details(t),...n})},Bcr=({requestContext:e,queryOptions:t}={})=>{const n=Ge();return Sn({mutationFn:async({processorId:r,phase:s,messages:i,agentId:o})=>n.getProcessor(r).execute({phase:s,messages:i,agentId:o,requestContext:e}),...t})};function Ucr({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}=LP(),{navigate:v,paths:y}=Tn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load processors";Ye.error(`Error loading processors: ${S}`)}},[p,m]);const x=Object.keys(f).filter(S=>{const k=f[S];return k?.phases&&k.phases.length>0}).map(S=>({label:f[S]?.name||S,value:S})),b=S=>{t?t(S):S&&S!==e&&(f[S]?.isWorkflow?v(y.workflowLink(S)+"/graph"):v(y.processorLink(S)))};return a.jsx(fl,{options:x,value:e,onValueChange:b,placeholder:h?"Loading processors...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||h||p,variant:l,size:c,"aria-label":u,align:d})}function Vcr(){const{processorId:e}=jr(),{data:t,isLoading:n}=LP();return e?n?a.jsx(Lx,{}):t?.[e]?.name||e:null}function qcr(){const{processorId:e}=jr();return e?a.jsx(Ucr,{value:e,...RP,"aria-label":"Switch processor"}):null}const Boe=[400,401,403,404,501];function Cs(e){if(!e||typeof e!="object")return!1;if("status"in e&&e.status===401||"statusCode"in e&&e.statusCode===401)return!0;if("message"in e){const t=e.message;if(typeof t=="string")return/\bstatus:\s*401\b/.test(t)}return!1}function _s(e){if(!e||typeof e!="object")return!1;if("status"in e&&e.status===403||"statusCode"in e&&e.statusCode===403)return!0;if("message"in e){const t=e.message;if(typeof t=="string")return/\bstatus:\s*403\b/.test(t)}return!1}function Ik(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 e6(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 Qcr=["Observability storage domain is not available","Scores storage domain is not available"];function t6(e){if(!e||typeof e!="object"||!("message"in e))return!1;const t=e.message;return typeof t!="string"?!1:Qcr.some(n=>t.includes(n))}function _Ot(e){if(!e||typeof e!="object")return!1;if("status"in e){const t=e.status;return Boe.includes(t)}if("statusCode"in e){const t=e.statusCode;return Boe.includes(t)}if("message"in e){const t=e.message;if(typeof t=="string")return Boe.some(n=>new RegExp(`\\bstatus:\\s*${n}\\b`).test(t))}return!1}function Zcr(e,t){return _Ot(t)?!1:e<3}const Wcr=25,Hcr=15e3;function Gcr(e){return e6(e.state.error,"scores")||t6(e.state.error)?!1:Hcr}function Kcr(e,t,n){if(e?.pagination?.hasMore)return n+1}function Ycr(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 Xcr=({scorerId:e,entityId:t,entityType:n,queryOptions:r})=>{const s=Ge(),{inView:i,setRef:o}=K0(),l=Dm({queryKey:["scores",e,t,n],queryFn:({pageParam:f})=>s.listScoresByScorerId({scorerId:e,page:f,perPage:Wcr,entityId:t,entityType:n}),initialPageParam:0,getNextPageParam:Kcr,select:f=>Ycr(f),refetchInterval:Gcr,...r}),{hasNextPage:c,isFetchingNextPage:u,fetchNextPage:d}=l;return g.useEffect(()=>{i&&c&&!u&&d()},[i,c,u,d]),{...l,setEndOfListElement:o}},Jcr=e=>{const t=Ge(),[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}},TOt=({requestContext:e,queryOptions:t}={})=>{const n=Ge();return _t({queryKey:["scorers",e],queryFn:()=>n.listScorers(e),staleTime:0,gcTime:0,...t})},eur=15e3;function tur(e){return e6(e.state.error,"scores")||t6(e.state.error)?!1:eur}const Ike=({traceId:e="",spanId:t="",page:n,queryOptions:r})=>{const s=Ge();return _t({queryKey:["trace-span-scores",e,t,n],queryFn:()=>s.listScoresBySpan({traceId:e,spanId:t,page:n||0,perPage:10}),refetchInterval:tur,gcTime:0,staleTime:0,...r})},nur=({queryOptions:e}={})=>{const t=Ge();return Sn({mutationFn:async({scorerName:n,traceId:r,spanId:s})=>await t.score({scorerName:n,targets:[{traceId:r,spanId:s}]}),...e})},EOt=({scorerId:e,status:t,requestContext:n,queryOptions:r}={})=>{const s=Ge();return _t({queryKey:["stored-scorer",e,t,n],queryFn:()=>e?s.getStoredScorer(e).details(n,{status:t}):null,...r})},IOt=({scorerId:e,requestContext:t,queryOptions:n}={})=>{const r=Ge(),s=mr();return{createStoredScorer:Sn({mutationFn:i=>r.createStoredScorer(i),onSuccess:()=>{s.invalidateQueries({queryKey:["stored-scorers"]}),s.invalidateQueries({queryKey:["scorers"]})},...n?.createStoredScorer}),updateStoredScorer:Sn({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:Sn({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})}},NOt=({scorerId:e,params:t,requestContext:n,queryOptions:r})=>{const s=Ge();return _t({queryKey:["scorer-versions",e,t,n],queryFn:()=>s.getStoredScorer(e).listVersions(t,n),...r})},rur=({scorerId:e,versionId:t,requestContext:n,queryOptions:r})=>{const s=Ge();return _t({queryKey:["scorer-version",e,t,n],queryFn:()=>s.getStoredScorer(e).getVersion(t,n),...r})},Fx=(e,t)=>TOt({...e,requestContext:t});function sur({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}=Fx(),{navigate:v,paths:y}=Tn();g.useEffect(()=>{if(p){const S=m instanceof Error?m.message:"Failed to load scorers";Ye.error(`Error loading scorers: ${S}`)}},[p,m]);const x=Object.keys(f).map(S=>({label:f[S]?.scorer.config.name||S,value:S})),b=S=>{t?t(S):S&&S!==e&&v(y.scorerLink(S))};return a.jsx(fl,{options:x,value:e,onValueChange:b,placeholder:h?"Loading scorers...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:o||h||p,variant:l,size:c,"aria-label":u,align:d})}function iur(){const{scorerId:e}=jr(),{data:t,isLoading:n}=Fx();return e?n?a.jsx(Lx,{}):t?.[e]?.scorer.config.name||e:null}function our(){const{scorerId:e}=jr();return e?a.jsx(sur,{value:e,...RP,"aria-label":"Switch scorer"}):null}function aur(){const{scorerId:e}=jr(),{data:t,isLoading:n}=EOt({scorerId:e,status:"draft",queryOptions:{enabled:!!e}});return e?n?a.jsx(Lx,{}):t?.name??"Scorer not found":null}const Uo=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"})]}),AOt=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"})}),lur=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"})}),cur=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"})]}),L_=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"})]}),uur=e=>a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 8.98824 8.33142",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[a.jsx("path",{d:"M5.70011e-05 6.409V0H1.04865V6.409C1.04875 6.89152 1.43994 7.28283 1.92248 7.28283H8.3581V8.33142H1.92248C0.860814 8.33142 0.000149953 7.47065 5.70011e-05 6.409Z",fill:"currentColor"}),a.jsx("path",{d:"M8.08006 0.945713C8.27714 0.733828 8.6087 0.72151 8.82077 0.918405C9.03289 1.11551 9.04518 1.44767 8.84808 1.6598L6.08595 4.63218C5.90127 4.83085 5.59525 4.85557 5.38074 4.68953L4.03177 3.64571L2.74765 5.07183C2.55386 5.28688 2.22206 5.30441 2.00694 5.11074C1.79189 4.91695 1.77435 4.58515 1.96803 4.37003L3.57915 2.58278L3.65357 2.51451C3.83887 2.37494 4.09997 2.37165 4.28982 2.51861L5.64358 3.56652L8.08006 0.945713Z",fill:"currentColor"})]});function aj(e){return a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 10.123 10.123",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M4.50195 1.53809H5.62109V0H6.75098V1.53809H7.5293L7.64258 1.54395C8.19939 1.60066 8.63379 2.0708 8.63379 2.64258V3.37305H10.123V4.50195H8.63379V5.62109H10.123V6.75H8.63379V7.57812L8.62891 7.69141C8.57589 8.2109 8.16211 8.62387 7.64258 8.67676L7.5293 8.68262H6.75098V10.123H5.62109V8.68262H4.50195V10.123H3.37305V8.68262H2.59375L2.48047 8.67676C1.96102 8.62383 1.54817 8.21082 1.49512 7.69141L1.48926 7.57812V6.75H0V5.62109H1.48926V4.50195H0V3.37305H1.48926V2.64258C1.48926 2.07084 1.92371 1.60071 2.48047 1.54395L2.59375 1.53809H3.37305V0H4.50195V1.53809ZM2.61914 7.55273H7.50488V2.66699H2.61914V7.55273Z",fill:"currentColor"})})}const dur=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"})}),tw=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"})]}),fur=e=>a.jsx("svg",{width:"17",height:"18",viewBox:"0 0 17 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M8.40864 11.9983C7.58064 11.9733 6.84164 11.6153 6.31564 11.0563C6.31464 11.0563 6.31464 11.0553 6.31464 11.0553C5.78864 10.4963 5.47564 9.73633 5.50064 8.90833C5.52564 8.08033 5.88464 7.34133 6.44364 6.81533C7.00264 6.28833 7.76264 5.97633 8.59064 6.00133C9.41864 6.02633 10.1576 6.38433 10.6836 6.94333H10.6846C11.2106 7.50333 11.5236 8.26233 11.4986 9.09033C11.4726 9.91833 11.1146 10.6583 10.5556 11.1843C9.99664 11.7103 9.23664 12.0233 8.40864 11.9983ZM16.1266 8.15033L14.3606 7.74033C14.2316 7.14133 14.0146 6.57633 13.7216 6.05733L14.7726 4.57933C14.9116 4.38533 14.8926 4.12033 14.7296 3.94633L13.9206 3.08733C13.7576 2.91333 13.4946 2.87933 13.2916 3.00533L11.7526 3.96533C11.2526 3.64133 10.7016 3.39033 10.1116 3.22633L9.80964 1.43833C9.76964 1.20333 9.56964 1.02833 9.33164 1.02133L8.15264 0.985326C7.91364 0.978326 7.70364 1.14033 7.64964 1.37233L7.24064 3.13933C6.64164 3.26733 6.07664 3.48433 5.55664 3.77733L4.07864 2.72633C3.88464 2.58833 3.61964 2.60633 3.44664 2.76933L2.58664 3.57833C2.41364 3.74133 2.37964 4.00533 2.50564 4.20733L3.46564 5.74633C3.14164 6.24633 2.89064 6.79833 2.72564 7.38833L0.937635 7.68933C0.702635 7.72933 0.528635 7.92933 0.520635 8.16733L0.485635 9.34733C0.477635 9.58533 0.639635 9.79533 0.872635 9.84933L2.63864 10.2583C2.76764 10.8573 2.98464 11.4233 3.27764 11.9423L2.22564 13.4203C2.08764 13.6143 2.10564 13.8793 2.26964 14.0523L3.07864 14.9123C3.24164 15.0853 3.50464 15.1203 3.70664 14.9933L5.24564 14.0333C5.74663 14.3583 6.29764 14.6093 6.88764 14.7733L7.18964 16.5613C7.22864 16.7963 7.42864 16.9713 7.66764 16.9783L8.84663 17.0143C9.08564 17.0213 9.29564 16.8593 9.34964 16.6273L9.75864 14.8603C10.3576 14.7323 10.9226 14.5153 11.4416 14.2213L12.9206 15.2733C13.1146 15.4113 13.3786 15.3933 13.5526 15.2293L14.4116 14.4213C14.5856 14.2573 14.6196 13.9943 14.4936 13.7923L13.5336 12.2533C13.8576 11.7523 14.1086 11.2013 14.2726 10.6113L16.0616 10.3103C16.2966 10.2703 16.4706 10.0703 16.4776 9.83233L16.5136 8.65233C16.5206 8.41433 16.3586 8.20433 16.1266 8.15033Z",fill:"currentColor"})}),fd=e=>a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 11.185 11.185",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:a.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.0293 1.16491L4.81958 0.801671L4.81955 0.801686L5.0293 1.16491ZM5.75391 1.16491L5.96365 0.801686L5.96363 0.801671L5.75391 1.16491ZM9.04492 3.06531L9.25474 2.70212L9.25467 2.70208L9.04492 3.06531ZM9.40723 7.49304L9.82666 7.49332V7.49304H9.40723ZM9.04492 8.11999L8.8352 7.75675L8.83518 7.75676L9.04492 8.11999ZM5.75391 10.0204L5.96363 10.3836L5.96365 10.3836L5.75391 10.0204ZM5.0293 10.0204L4.81955 10.3836L4.81963 10.3837L5.0293 10.0204ZM1.73828 8.11999L1.94803 7.75676L1.948 7.75675L1.73828 8.11999ZM1.37598 7.49304H0.956538L0.956538 7.49332L1.37598 7.49304ZM1.73828 3.06531L1.94802 3.42854L1.94803 3.42853L1.73828 3.06531ZM5.59277 3.38366L5.59283 2.96423H5.59277V3.38366ZM3.38379 5.59167L2.96435 5.59159V5.59167H3.38379ZM5.59277 7.80066V8.2201H5.59283L5.59277 7.80066ZM7.80078 5.59167H8.22022V5.59159L7.80078 5.59167ZM5.0293 1.16491L5.23902 1.52816C5.33331 1.47372 5.44989 1.47372 5.54419 1.52816L5.75391 1.16491L5.96363 0.801671C5.60978 0.59738 5.17342 0.59738 4.81958 0.801671L5.0293 1.16491ZM5.75391 1.16491L5.54416 1.52814L8.83518 3.42853L9.04492 3.06531L9.25467 2.70208L5.96365 0.801686L5.75391 1.16491ZM9.04492 3.06531L8.83511 3.42849C8.92979 3.48319 8.98779 3.5839 8.98779 3.69226H9.40723H9.82666C9.82666 3.28328 9.60799 2.90619 9.25474 2.70212L9.04492 3.06531ZM9.40723 3.69226H8.98779V7.49304H9.40723H9.82666V3.69226H9.40723ZM9.40723 7.49304L8.98779 7.49276C8.98772 7.6015 8.92949 7.70231 8.8352 7.75675L9.04492 8.11999L9.25464 8.48324C9.60821 8.2791 9.82639 7.90167 9.82666 7.49332L9.40723 7.49304ZM9.04492 8.11999L8.83518 7.75676L5.54416 9.65715L5.75391 10.0204L5.96365 10.3836L9.25467 8.48322L9.04492 8.11999ZM5.75391 10.0204L5.54419 9.65714C5.44996 9.71154 5.33331 9.71156 5.23897 9.65711L5.0293 10.0204L4.81963 10.3837C5.17339 10.5878 5.60977 10.5879 5.96363 10.3836L5.75391 10.0204ZM5.0293 10.0204L5.23904 9.65715L1.94803 7.75676L1.73828 8.11999L1.52854 8.48322L4.81955 10.3836L5.0293 10.0204ZM1.73828 8.11999L1.948 7.75675C1.85371 7.70231 1.79549 7.6015 1.79541 7.49276L1.37598 7.49304L0.956538 7.49332C0.956809 7.90167 1.17499 8.2791 1.52856 8.48324L1.73828 8.11999ZM1.37598 7.49304H1.79542V3.69226H1.37598H0.956538V7.49304H1.37598ZM1.37598 3.69226H1.79542C1.79542 3.58378 1.85339 3.48318 1.94802 3.42854L1.73828 3.06531L1.52854 2.70207C1.17507 2.90617 0.956538 3.2833 0.956538 3.69226H1.37598ZM1.73828 3.06531L1.94803 3.42853L5.23904 1.52814L5.0293 1.16491L4.81955 0.801686L1.52854 2.70208L1.73828 3.06531ZM5.59277 3.38366V2.96423C4.14162 2.96423 2.96463 4.14015 2.96435 5.59159L3.38379 5.59167L3.80323 5.59175C3.80342 4.60382 4.60458 3.8031 5.59277 3.8031V3.38366ZM3.38379 5.59167H2.96435C2.96435 7.04322 4.14132 8.2201 5.59277 8.2201V7.80066V7.38122C4.6046 7.38122 3.80323 6.57991 3.80323 5.59167H3.38379ZM5.59277 7.80066L5.59283 8.2201C7.04429 8.2199 8.22022 7.04294 8.22022 5.59167H7.80078H7.38134C7.38134 6.57999 6.58061 7.38108 5.59272 7.38122L5.59277 7.80066ZM7.80078 5.59167L8.22022 5.59159C8.21994 4.14043 7.04398 2.96443 5.59283 2.96423L5.59277 3.38366L5.59272 3.8031C6.58062 3.80324 7.38115 4.60374 7.38134 5.59175L7.80078 5.59167Z",fill:"currentColor"})}),bx=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"})]}),hur=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"})}),pur=typeof window<"u"&&window.MASTRA_SIGNALS_UI==="true",mur={name:"Intelligence",url:"/intelligence",activePaths:["/intelligence"],Icon:zht,isOnMastraPlatform:!0,hidden:!pur},Nke=[{key:"primitives",title:"Primitives",items:[{name:"Agents",url:"/agents",Icon:Uo,isOnMastraPlatform:!0},{name:"Prompts",url:"/prompts",Icon:dur,isOnMastraPlatform:!0},{name:"Workflows",url:"/workflows",Icon:Ol,isOnMastraPlatform:!0},{name:"Processors",url:"/processors",Icon:aj,isOnMastraPlatform:!1,foldable:!0},{name:"MCP Servers",url:"/mcps",Icon:L_,isOnMastraPlatform:!0,foldable:!0},{name:"Tools",url:"/tools",Icon:fd,isOnMastraPlatform:!0,foldable:!0},{name:"Workspaces",url:"/workspaces",Icon:hur,isOnMastraPlatform:!0,foldable:!0}]},{key:"evaluation",title:"Evaluation",items:[{name:"Scorers",url:"/scorers",Icon:tw,isOnMastraPlatform:!0},{name:"Datasets",url:"/datasets",Icon:AOt,isOnMastraPlatform:!0},{name:"Experiments",url:"/experiments",Icon:lur,isOnMastraPlatform:!0},{name:"Review Queue",url:"/experiments/review-queue",Icon:Iht,isOnMastraPlatform:!0}]},{key:"observability",title:"Observability",items:[{name:"Metrics",url:"/metrics",Icon:uur,isOnMastraPlatform:!0},{name:"Traces",url:"/traces",Icon:bx,isOnMastraPlatform:!0},mur,{name:"Logs",url:"/logs",Icon:cur,isOnMastraPlatform:!0}]}],Ake=[{name:"Settings",url:"/settings",Icon:fur,isOnMastraPlatform:!1},{name:"Resources",url:"/resources",Icon:kht,isOnMastraPlatform:!0}],gur=[...Nke.flatMap(e=>e.items),...Ake];function vur(e){return gur.find(t=>t.url===e)}function Ts(e,t){const n=vur(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 Pke=e=>{if(!e)return"";try{return decodeURIComponent(e)}catch{return e}},POt=e=>{const t=Pke(e);return t.length>8?`${t.slice(0,8)}...`:t},$Ot={id:"agent",Component:vcr,Switcher:ycr},yur={id:"scorer",Component:iur,Switcher:our},xur={id:"processor",Component:Vcr,Switcher:qcr},bur={id:"mcp-server",Component:zcr,Switcher:Fcr},GUe={id:"workflow",Component:Ulr,Switcher:Vlr},_K={id:"dataset",Component:Acr,Switcher:Pcr},ROt={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 Uoe=null;function wur(){return Uoe||(Uoe=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Ai(()=>import("./core-VuCQVt-s.js"),__vite__mapDeps([0,1,2,3,4]),import.meta.url),Ai(()=>import("./engine-javascript-DSQaR0Yq.js"),__vite__mapDeps([5,2,3]),import.meta.url)]);return e({themes:[Ai(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Ai(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Ai(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Ai(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Ai(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Ai(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Ai(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Ai(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Ai(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Ai(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Ai(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Ai(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Ai(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Ai(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([6,7,8]),import.meta.url),Ai(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Ai(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Uoe}async function Sur(e,t){const n=ROt[t?.toLowerCase()];if(!n)return null;const r=await wur(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function MOt(e){const t=e?.split(".").pop()?.toLowerCase();return t?ROt[t]:void 0}function kur({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(ut,{children:e}),t&&a.jsx(mc,{delay:10,children:a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("button",{type:"button","aria-label":r,className:Z(Ln,On,"rounded-sm",ji),children:a.jsx(At,{size:"xs",children:a.jsx(hp,{})})})}),a.jsx(Dn,{side:"top",className:"max-w-60",children:t})]})})]})}let KUe;const DOt=()=>KUe??=Promise.all([Ai(()=>import("./standalone-Dfz2oS5J.js"),[],import.meta.url),Ai(()=>import("./babel-lWBcy2sH.js"),[],import.meta.url),Ai(()=>import("./estree-Dd9JfUIE.js"),[],import.meta.url)]).catch(e=>{throw KUe=void 0,e}),C5=async e=>{const[t,n,r]=await DOt();return await t.format(e,{semi:!1,parser:"json",printWidth:80,tabWidth:2,plugins:[n,r]})},LOt=async e=>{const[t,n,r]=await DOt();return await t.format(e,{parser:"babel-ts",printWidth:80,tabWidth:2,plugins:[n,r]})},wQ=e=>{try{const t=JSON.parse(e);return!!t&&typeof t=="object"}catch{return!1}},Our=Oi(gt(),n2n());function Voe(e,t){if(!e)return"__custom__";for(const[n,r]of Object.entries(e))if(JSON.stringify(r)===t)return n;return"__custom__"}function jur(e){try{return JSON.stringify(JSON.parse(e))}catch{return null}}const zOt=({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(()=>Voe(t,l)),{handleCopy:v}=Bm({text:u}),[y,x]=g.useState(l);y!==l&&(x(l),d(c),h(c),m(Voe(t,l)));const b=g.useMemo(()=>{const N=jur(u);return N?N!==l:u!==f},[l,u,f]),S=()=>{let N;try{N=JSON.parse(u)}catch{Ye.error("Invalid JSON");return}const I=Our.safeParse(N);if(!I.success){Ye.error(`${e} must be a JSON object`);return}r(I.data)},k=()=>{d(f),m(Voe(t,l))},j=Z(Ln,On),C=async()=>{if(!wQ(u)){Ye.error("Invalid JSON");return}const N=await C5(u);d(N)},T=async N=>{if(m(N),N==="__custom__"||!t)return;const I=t[N];if(I){const A=await C5(JSON.stringify(I));d(A)}},_=N=>{d(N),p!=="__custom__"&&m("__custom__")};return a.jsx(mc,{children:a.jsxs("div",{children:[a.jsxs(ht,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs(kur,{tooltip:i,children:[e," (JSON)"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[o,a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:C,className:j,children:a.jsx(At,{children:a.jsx(Ua,{})})})}),a.jsxs(Dn,{children:["Format the ",e," JSON"]})]}),a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:v,className:j,children:a.jsx(At,{children:a.jsx(zm,{})})})}),a.jsxs(Dn,{children:["Copy ",e]})]})]})]}),t&&Object.keys(t).length>0&&a.jsxs(ht,{children:[a.jsxs(ut,{className:"sr-only",children:[e," preset"]}),a.jsxs(ps,{value:p,onValueChange:T,children:[a.jsx(gs,{children:a.jsx(ms,{placeholder:"Select a preset..."})}),a.jsxs(vs,{children:[a.jsx(hr,{value:"__custom__",children:"Custom"}),Object.keys(t).map(N=>a.jsx(hr,{value:N,children:N},N))]})]})]}),a.jsx(Or,{value:u,onChange:_,showCopyButton:!1,className:s})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[b&&a.jsx(ue,{variant:"default",size:"icon-md",type:"button",tooltip:`Revert ${e} changes`,onClick:k,children:a.jsx(zn,{})}),a.jsx(ue,{icon:a.jsx(ur,{}),type:"button",onClick:S,children:"Save"})]})]})})},Cur={align:"shift"};function FOt({label:e,icon:t,open:n,onOpenChange:r,children:s}){return a.jsxs(jp,{open:n,onOpenChange:r,children:[a.jsx(sf,{variant:"ghost",size:"icon-md",type:"button",tooltip:e,"aria-label":e,children:t}),a.jsx(lh,{align:"start",collisionAvoidance:Cur,className:"w-[min(480px,calc(100vw-2rem))] p-0",children:a.jsx("div",{onSubmit:i=>i.stopPropagation(),children:a.jsx(Ir,{className:"w-full",maxHeight:"min(600px, calc(100dvh - 8rem))",children:a.jsx("div",{className:"space-y-4 p-4",children:s})})})})]})}function _ur(){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 $ke({entityType:e,entityId:t}){const[n,r]=g.useState(!1),[s,i]=xr(e,t),o=_ur(),l=c=>{i(c),Ye.success("Request context saved locally"),r(!1)};return a.jsx(FOt,{label:"Request context",icon:a.jsx(bEn,{}),open:n,onOpenChange:r,children:a.jsx(zOt,{label:"Request Context",presets:o,value:s,onSave:l,editorClassName:"h-[260px]"})})}function BOt({entityType:e,entityId:t,extraFields:n,onSaveExtra:r,onOpenChange:s}){const[i,o]=g.useState(!1),[l,c]=yke(e,t),u=f=>{o(f),s?.(f)},d=f=>{c(f),r?.(),Ye.success("Run options saved locally"),u(!1)};return a.jsxs(FOt,{label:"Run options",icon:a.jsx(bx,{}),open:i,onOpenChange:u,children:[n,a.jsx(zOt,{label:"Tracing Options",value:l,onSave:d,editorClassName:"h-[260px]"})]})}function Tur({workflowId:e,resourceId:t,setResourceId:n}){const[r,s]=g.useState(t);return a.jsxs(a.Fragment,{children:[a.jsx($ke,{entityType:"workflow",entityId:e}),a.jsx(BOt,{entityType:"workflow",entityId:e,onOpenChange:i=>{i&&s(t)},onSaveExtra:()=>n(r),extraFields:a.jsxs(ht,{children:[a.jsx(ut,{children:"Resource ID"}),a.jsx(wn,{value:r,onChange:i=>s(i.target.value),placeholder:"e.g. tenant-42"}),a.jsx(no,{children:"Ignored when server auth derives the resource ID from the user."})]})})]})}function SQ({icon:e,label:t,tooltipContent:n,docsHref:r}){return a.jsxs(Fn,{children:[a.jsx(Mn,{render:a.jsx("span",{role:"button",tabIndex:0,"aria-disabled":"true","aria-label":t,className:"inline-flex",children:a.jsx(ue,{variant:"ghost",size:"icon-md",disabled:!0,"aria-hidden":"true",tabIndex:-1,children:e})})}),a.jsx(Dn,{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(Zs,{className:"size-3"})]})]})})]})}const Eur=({scheduleId:e,queryOptions:t})=>{const n=Ge();return _t({queryKey:["schedule",e],queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return n.getSchedule(e)},...t})},TK=({queryOptions:e,...t}={})=>{const n=Ge();return _t({queryKey:["schedules",t],queryFn:async()=>(await n.listSchedules(t)).schedules,...e})},YUe=25,Iur=({scheduleId:e,queryOptions:t})=>{const n=Ge(),{inView:r,setRef:s}=K0(),i=Dm({queryKey:["schedule-triggers",e],initialPageParam:void 0,queryFn:async({pageParam:d})=>e?n.listScheduleTriggers(e,{limit:YUe,toActualFireAt:d}):{triggers:[]},getNextPageParam:d=>{if(!(!d?.triggers?.length||d.triggers.length<YUe))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}},Nur=({scheduleId:e,queryOptions:t})=>{const n=Ge(),r=mr();return Sn({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 qoe({value:e,icon:t,label:n}){return a.jsxs(si,{value:e,children:[a.jsx(At,{size:"xs",children:t}),a.jsx(Y,{variant:"caption",className:"text-inherit",children:n})]})}function Aur({workflowId:e,activeTab:t,showObservability:n=!1}){const{navigate:r}=Tn(),{data:s,isSuccess:i}=TK({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(Wc,{value:t,defaultTab:t,onValueChange:u,className:"min-w-0",children:a.jsxs(Hc,{variant:"pill-ghost",children:[a.jsx(qoe,{value:"graph",icon:a.jsx(Ol,{}),label:"Graph"}),n&&a.jsx(qoe,{value:"traces",icon:a.jsx(bx,{}),label:"Traces"}),!d&&a.jsx(qoe,{value:"schedules",icon:a.jsx(C0,{}),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(SQ,{icon:a.jsx(bx,{}),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(SQ,{icon:a.jsx(C0,{}),label:"Schedules",tooltipContent:"Configure a schedule on this workflow to enable Schedules.",docsHref:"https://mastra.ai/docs/workflows/scheduled-workflows"})]})]})}const Pur=({children:e})=>{const{workflowId:t,runId:n}=jr();return a.jsx(vwe,{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(Mur,{children:e})})},$ur=e=>e==="graph"||e==="traces"||e==="schedules",Rur=({workflowId:e})=>{const t=Dr();return W0({"g$+t":()=>t(`/workflows/${encodeURIComponent(e)}/traces`)}),null};function Mur({children:e}){const{workflowId:t,runId:n}=jr(),r=e0e("/workflows/:workflowId/:tab/*"),{isLoading:s}=yL({workflowId:t,requestContext:xr("workflow",t)[0],queryOptions:{enabled:!!t}}),{hasObservability:i}=fOt(),o=$ur(r?.params.tab)?r.params.tab:"none",l=[Ts("/workflows"),n?{...GUe,to:`/workflows/${encodeURIComponent(t??"")}/graph`}:GUe,...n?[{id:"workflow-run",Component:qlr,Action:Qlr}]:[]];if(!t)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:l}),children:[a.jsx("h1",{className:"sr-only",children:t}),a.jsx("div",{className:"flex h-full flex-col items-center justify-center",children:a.jsx(Y,{variant:"body",tone:"ink",className:"text-center",children:"No workflow ID provided"})})]});if(s&&o==="graph")return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:l}),children:[a.jsx("h1",{className:"sr-only",children:t}),a.jsx(xt,{className:"h-full"})]});const c=u=>a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:l}),headerActions:a.jsx(Wlr,{}),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(Aur,{workflowId:t,activeTab:o,showObservability:i}),u]})]});return a.jsxs(Krt,{children:[a.jsx(Rur,{workflowId:t}),o==="graph"?a.jsx(Lkt,{children:a.jsx(bke,{workflowId:t,initialRunId:n,children:a.jsx(Dkt,{children:c(a.jsx(Gar,{leftSlot:a.jsx(Dur,{workflowId:t,initialRunId:n}),children:e}))})})},t):c(e)]})}function Dur({workflowId:e,initialRunId:t}){const[n]=xr("workflow",e),{canExecute:r,canDelete:s}=Za();return a.jsx(tlr,{workflowId:e,initialRunId:t,requestContext:n,runActionsSlot:i=>a.jsx(Tur,{workflowId:e,...i}),canExecute:r("workflows"),canDelete:s("workflows")})}const UOt=md(Z(pr,"rounded-xl transition-all duration-normal ease-out-custom motion-reduce:transition-none"),{variants:{elevation:{flat:"shadow-none",raised:""},interactive:{true:Z(hP,q0e,"cursor-pointer active:scale-99"),false:""}},compoundVariants:[{elevation:"flat",interactive:!0,class:Ix}],defaultVariants:{elevation:"raised",interactive:!1}}),hl=g.forwardRef(({className:e,elevation:t,interactive:n,as:r,...s},i)=>{const o=r||(n?"button":"div");return a.jsx(o,{ref:i,type:o==="button"?"button":void 0,className:Z(UOt({elevation:t,interactive:n}),e),...s})});hl.displayName="Card";function VOt({className:e,elevation:t,LinkComponent:n="a",...r}){return a.jsx(n,{className:Z(UOt({elevation:t,interactive:!0}),e),...r})}const kQ=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}));kQ.displayName="CardHeader";const nw=g.forwardRef(({className:e,...t},n)=>a.jsx("h3",{ref:n,className:Z("text-subheading text-foreground",e),...t}));nw.displayName="CardTitle";const Zj=g.forwardRef(({className:e,...t},n)=>a.jsx("p",{ref:n,className:Z("text-caption text-muted-foreground",e),...t}));Zj.displayName="CardDescription";const Lur=md("",{variants:{density:{default:"p-3",compact:"p-2"}},defaultVariants:{density:"default"}}),qm=g.forwardRef(({className:e,density:t,...n},r)=>a.jsx("div",{ref:r,className:Z(Lur({density:t}),e),...n}));qm.displayName="CardContent";const zur=g.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,className:Z("flex items-center p-3 pt-0",e),...t}));zur.displayName="CardFooter";const XUe=["blue","green","orange","purple","pink","amber","cyan"];function Rke(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 EK=e=>XUe[Rke(e)%XUe.length]??"blue",m0=e=>`var(--badge-${e}-indicator)`,Fur={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"},qOt=e=>Fur[e],Bur=e=>({background:`var(--badge-${e}-strong)`,foreground:`var(--badge-${e}-foreground)`,tint:`var(--badge-${e}-indicator)`}),JUe={goal:"green",outcome:"orange",behavior:"blue",sentiment:"purple"},eVe=["pink","amber"],Uur={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"},Vur={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 Mke(e){const t=e.toLowerCase();return(Object.hasOwn(JUe,t)?JUe[t]:void 0)??eVe[Rke(t)%eVe.length]??"pink"}function Bx(e){return`var(--chart-${Mke(e)})`}function QOt(e){return Uur[Mke(e)]}function qur(e){return Vur[Mke(e)]}const zP=[{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"}];zP.map(e=>e.name);Object.fromEntries(zP.map(e=>[e.name,e.description]));function n6(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 vp(e,t){return e.find(n=>n.name===t)?.label??Qur(t)}function US(e,t){return e.find(n=>n.name===t)?.description||void 0}function Qur(e){return e.split(/[-_]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function IK(e){return`${e} ${e===1?"trace":"traces"}`}function Zur(e){return`${e} ${e===1?"theme":"themes"}`}function ZOt(e,t){if(t<=0)return`${IK(e)} in this snapshot`;const n=Math.round(e/t);return`${e} of ${n} traces in this snapshot (${Math.round(t*100)}%)`}const Dke={timeZone:"UTC"};function _5(e){return MI(e,{...Dke,now:0})??e}function NK(e){return Jr(e,"date-time",Dke)??e}function Zpe(e,t){return cJn(e,t,Dke)??`${e}–${t}`}const Wur=[["chat.completion","1.2s"],["tool.search_docs","340ms"],["workflow.support","2.8s"]],OQ=e=>({color:Bx(e)}),tVe=()=>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 T5(e){return new Intl.NumberFormat("en-US").format(e)}function Hur(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 Gur({progress:e}){const t=e.signalCatalog??zP,n=t.filter(s=>s.enabled).length,r=t.filter(s=>s.enabled&&s.status==="ready").length;return a.jsxs("dl",{className:"mt-4 grid gap-2 sm:grid-cols-3",children:[a.jsxs("div",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:Ma({tone:"muted",variant:"caption"}),children:"Traces analyzed"}),a.jsx("dd",{className:Z(Ma({tone:"ink",variant:"heading"}),"mt-1"),children:T5(e.traceCount)})]}),a.jsxs("div",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:Ma({tone:"muted",variant:"caption"}),children:"Trace signal types ready"}),a.jsxs("dd",{className:Z(Ma({tone:"ink",variant:"heading"}),"mt-1"),children:[e.signalCatalog?r:e.availableSignals.length," of ",n]})]}),a.jsxs("div",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsx("dt",{className:Ma({tone:"muted",variant:"caption"}),children:"Status"}),a.jsx("dd",{className:Z(Ma({tone:"ink",variant:"heading"}),"mt-1 capitalize"),children:e.status})]})]})}function Kur({progress:e}){if(!e)return null;const t=e.signalCatalog??zP;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:n6(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=vp(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:OQ(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:[T5(r.generated)," generated · ",T5(r.embedded)," embedded"]})]},n)})})}function Yur({progress:e,signalCatalog:t}){const n=e?.signalCatalog??t,r=n.filter(s=>s.enabled&&s.status!=="ready");return r.length===0?null:a.jsxs("section",{className:"rounded-lg border border-border bg-background p-4","aria-labelledby":"pending-signals-heading",children:[a.jsx(Y,{as:"h2",variant:"subheading",tone:"ink",id:"pending-signals-heading",children:"Signals building themes"}),a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-1",children:"Themes appear once enough new traces are analyzed, embedded, and clustered."}),a.jsx("ul",{"aria-label":"Pending trace signals",className:"mt-3 grid gap-2 sm:grid-cols-2",children:r.map(s=>{const i=e?.signals[s.name]??{generated:0,embedded:0};return a.jsxs("li",{className:Z(pr,"rounded-md px-3 py-2"),children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx(Y,{font:"body",as:"span",variant:"subheading",style:OQ(s.name),children:vp(n,s.name)}),a.jsx(Y,{font:"body",as:"span",variant:"caption",tone:"muted",className:"capitalize",children:s.status})]}),US(n,s.name)?a.jsx(Y,{font:"body",variant:"caption",tone:"muted",className:"mt-1",children:US(n,s.name)}):null,a.jsxs(Y,{font:"body",variant:"caption",tone:"muted",className:"mt-1",children:[T5(i.generated)," generated · ",T5(i.embedded)," embedded"]})]},s.name)})})]})}const Wpe=({actionSlot:e,LinkComponent:t="a",progress:n,signalCatalog:r,isRangeEmpty:s})=>{const i=Hur(n,s),o=r??n?.signalCatalog??zP,c=n6(o,o.filter(u=>u.enabled).map(u=>u.name)).map(u=>({key:u,label:vp(o,u),description:US(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:Wur.map(([u,d])=>a.jsxs("div",{className:Z(pr,"flex items-center justify-between rounded px-3 py-1.5"),children:[a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"muted",children:u}),a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"muted",children:d})]},u))})]}),a.jsx(tVe,{}),a.jsxs(hl,{as:"div",role:"listitem",className:"flex min-h-50 flex-col items-center p-5 text-center",elevation:"raised",children:[a.jsx(Y,{as:"h2",variant:"heading",tone:"ink",children:"Trace Intelligence"}),a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-0.5",children:"Finds recurring themes"}),a.jsx("div",{"aria-hidden":"true",className:"mt-5 flex size-14 items-center justify-center rounded-full border border-brand-green-indicator bg-fill-subtle",children:a.jsx(yP,{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(tVe,{}),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:OQ(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:OQ(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(Gur,{progress:n}):null,a.jsx(Kur,{progress:n})]})]}),a.jsxs("div",{className:"mt-4 flex shrink-0 flex-wrap items-center gap-2 sm:justify-end",children:[e,a.jsxs(ue,{icon:a.jsx(Zs,{}),render:a.jsx("a",{href:"https://mastra.ai/en/docs/mastra-platform/trace-intelligence",target:"_blank",rel:"noopener noreferrer"}),size:"sm",children:["Read the docs",a.jsx("span",{className:"sr-only",children:" (opens in new tab)"})]}),a.jsx(ue,{icon:a.jsx(bx,{}),render:a.jsx(t,{href:"/traces"}),variant:"primary",size:"sm",children:"View incoming traces"})]})]})]})})};function nVe(e){return a.jsx(Wpe,{...e})}async function Xur(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 w2={cacheScope:"oss-studio",request:Xur,LinkComponent:"a",getTraceHref:e=>`/traces?traceId=${encodeURIComponent(e)}`,signalCatalog:zP},Lke=g.createContext(w2);function pa(){return g.useContext(Lke)}function Jur(e,t){const n=new URLSearchParams({entityType:t});return e(`/api/learning/entities?${n}`)}function edr(e,t,n){const r=new URLSearchParams({entityType:n});return e(`/api/learning/entities/${encodeURIComponent(t)}/progress?${r}`)}function WOt(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 HOt(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 tdr(e,t,n,r,s,i){const o=new URLSearchParams({entityType:n,signalName:r,snapshotId:s});return e(zke(t,i,`?${o}`))}function r6(e){return e.map(t=>`${t.signalName}:${t.kind==="theme"?t.themeId:"noise"}`).join(",")}function ndr(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",r6(c)),e(zke(t,i,`/examples?${u}`))}function rdr(e,t,n,r,s,i=100){const o=new URLSearchParams({entityType:n,signalName:r,limit:String(i)});return e(zke(t,s,`/history?${o}`))}function sdr(e,t,n,r,s){const i=new URLSearchParams({entityType:n,signalName:r,snapshotId:s});return e(KOt(t,`?${i}`))}function idr(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",r6(l)),e(KOt(t,`/examples?${c}`))}async function GOt(e,t,n,r,s){const i=await rVe(e,t,n,r,s,0),o=[...i.paths],l={...i.themes};let c=i.nextOffset;for(;c!==void 0;){const u=await rVe(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 rVe(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 odr(e,t){return e(`/api/learning/traces/${encodeURIComponent(t)}/summary`)}function zke(e,t,n){return`/api/learning/entities/${encodeURIComponent(e)}/themes/${encodeURIComponent(t)}${n}`}function KOt(e,t){return`/api/learning/entities/${encodeURIComponent(e)}/noise${t}`}function YOt(e,t,n=!0){const{cacheScope:r,request:s}=pa();return _t({queryKey:["entity-learning",r,t,e,"progress"],queryFn:()=>edr(s,e??"",t),enabled:n&&!!e})}function XOt(e){const{cacheScope:t,request:n}=pa();return _t({queryKey:["entity-learning",t,"entities",e],queryFn:()=>Jur(n,e)})}function JOt(e,t,n,r,s){const{cacheScope:i,request:o}=pa(),l=r?.toISOString(),c=s?.toISOString();return _t({queryKey:["entity-learning",i,t,e,"theme-snapshots",n,l,c],queryFn:()=>WOt(o,e,t,n,r,s),enabled:n.length>=2,staleTime:3e4})}const adr=.01;function ldr(e,t){return String(e[t.id])}function cdr(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 udr(e,t){return Number(e[`${t.id}TraceCount`])}function ddr(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:hdr(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`]:oVe(o.node),[`${o.signalName}Description`]:o.node.description,[`${o.signalName}TraceCount`]:o.node.traceCount,[l.signalName]:l.node.nodeId,[`${l.signalName}Label`]:oVe(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 fdr(e){return ddr(e)}function sVe(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 iVe(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(adr,s.get(c)??l.traceCount)}});return{...e,stages:n,links:o}}function oVe(e){return e.kind==="noise"?"Noise":e.label}function hdr(e){return`${e.slice(0,1).toUpperCase()}${e.slice(1)}`}function E5(e,t){const n=e.cutoffAt?NK(e.cutoffAt):Zpe(e.startedAt,e.endedAt);if(!t)return n;const{traceCount:r,themeCount:s}=pdr(t);return`${n} · ${IK(r)} · ${Zur(s)}`}function pdr(e){return{traceCount:e.stages[0]?.traceCount??e.snapshot.traceCount,themeCount:e.stages.reduce((t,n)=>t+n.nodes.filter(r=>r.kind==="theme").length,0)}}function _c(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 mdr=typeof Symbol=="function"&&Symbol.observable||"@@observable",aVe=mdr,Qoe=()=>Math.random().toString(36).substring(7).split("").join("."),gdr={INIT:`@@redux/INIT${Qoe()}`,REPLACE:`@@redux/REPLACE${Qoe()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${Qoe()}`},jQ=gdr;function Fke(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 Bke(e,t,n){if(typeof e!="function")throw new Error(_c(2));if(typeof t=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(_c(0));if(typeof t=="function"&&typeof n>"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(_c(1));return n(Bke)(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(_c(3));return s}function f(y){if(typeof y!="function")throw new Error(_c(4));if(c)throw new Error(_c(5));let x=!0;u();const b=l++;return o.set(b,y),function(){if(x){if(c)throw new Error(_c(6));x=!1,u(),o.delete(b),i=null}}}function h(y){if(!Fke(y))throw new Error(_c(7));if(typeof y.type>"u")throw new Error(_c(8));if(typeof y.type!="string")throw new Error(_c(17));if(c)throw new Error(_c(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(_c(10));r=y,h({type:jQ.REPLACE})}function m(){const y=f;return{subscribe(x){if(typeof x!="object"||x===null)throw new Error(_c(11));function b(){const k=x;k.next&&k.next(d())}return b(),{unsubscribe:y(b)}},[aVe](){return this}}}return h({type:jQ.INIT}),{dispatch:h,subscribe:f,getState:d,replaceReducer:p,[aVe]:m}}function vdr(e){Object.keys(e).forEach(t=>{const n=e[t];if(typeof n(void 0,{type:jQ.INIT})>"u")throw new Error(_c(12));if(typeof n(void 0,{type:jQ.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(_c(13))})}function ejt(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{vdr(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(_c(14));u[f]=m,c=c||m!==p}return c=c||r.length!==Object.keys(o).length,c?u:o}}function lVe(e,t){return function(...n){return t(e.apply(this,n))}}function cVe(e,t){if(typeof e=="function")return lVe(e,t);if(typeof e!="object"||e===null)throw new Error(_c(16));const n={};for(const r in e){const s=e[r];typeof s=="function"&&(n[r]=lVe(s,t))}return n}function I5(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,n)=>(...r)=>t(n(...r)))}function tjt(...e){return t=>(n,r)=>{const s=t(n,r);let i=()=>{throw new Error(_c(15))};const o={getState:s.getState,dispatch:(c,...u)=>i(c,...u)},l=e.map(c=>c(o));return i=I5(...l)(s.dispatch),{...s,dispatch:i}}}function njt(e){return Fke(e)&&"type"in e&&typeof e.type=="string"}var Zoe={exports:{}},Woe={};var uVe;function ydr(){if(uVe)return Woe;uVe=1;var e=YA();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 Woe.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},Woe}var dVe;function xdr(){return dVe||(dVe=1,Zoe.exports=ydr()),Zoe.exports}xdr();var bdr=g.version.startsWith("19"),wdr=Symbol.for(bdr?"react.transitional.element":"react.element"),Sdr=Symbol.for("react.portal"),kdr=Symbol.for("react.fragment"),Odr=Symbol.for("react.strict_mode"),jdr=Symbol.for("react.profiler"),Cdr=Symbol.for("react.consumer"),_dr=Symbol.for("react.context"),rjt=Symbol.for("react.forward_ref"),Tdr=Symbol.for("react.suspense"),Edr=Symbol.for("react.suspense_list"),Uke=Symbol.for("react.memo"),Idr=Symbol.for("react.lazy"),Ndr=rjt,Adr=Uke;function Pdr(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case wdr:switch(e=e.type,e){case kdr:case jdr:case Odr:case Tdr:case Edr:return e;default:switch(e=e&&e.$$typeof,e){case _dr:case rjt:case Idr:case Uke:return e;case Cdr:return e;default:return t}}case Sdr:return t}}}function $dr(e){return Pdr(e)===Uke}function Rdr(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 Mdr(e,{initMapStateToProps:t,initMapDispatchToProps:n,initMergeProps:r,...s}){const i=t(e,s),o=n(e,s),l=r(e,s);return Rdr(i,o,l,e,s)}function Ddr(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 Hpe(e){return function(n){const r=e(n);function s(){return r}return s.dependsOnOwnProps=!1,s}}function fVe(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function sjt(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=fVe(e);let u=i(l,c);return typeof u=="function"&&(i.mapToProps=u,i.dependsOnOwnProps=fVe(u),u=i(l,c)),u},i}}function Vke(e,t){return(n,r)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${r.wrappedComponentName}.`)}}function Ldr(e){return e&&typeof e=="object"?Hpe(t=>Ddr(e,t)):e?typeof e=="function"?sjt(e):Vke(e,"mapDispatchToProps"):Hpe(t=>({dispatch:t}))}function zdr(e){return e?typeof e=="function"?sjt(e):Vke(e,"mapStateToProps"):Hpe(()=>({}))}function Fdr(e,t,n){return{...n,...e,...t}}function Bdr(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 Udr(e){return e?typeof e=="function"?Bdr(e):Vke(e,"mergeProps"):()=>Fdr}function Vdr(e){e()}function qdr(){let e=null,t=null;return{clear(){e=null,t=null},notify(){Vdr(()=>{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 hVe={notify(){},get:()=>[]};function ijt(e,t){let n,r=hVe,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=qdr())}function f(){s--,n&&s===0&&(n(),n=void 0,r.clear(),r=hVe)}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 Qdr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Zdr=Qdr(),Wdr=()=>typeof navigator<"u"&&navigator.product==="ReactNative",Hdr=Wdr(),Gdr=()=>Zdr||Hdr?g.useLayoutEffect:g.useEffect,CQ=Gdr();function pVe(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function XB(e,t){if(pVe(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])||!pVe(e[n[s]],t[n[s]]))return!1;return!0}var Kdr={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},Ydr={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},Xdr={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},ojt={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},Jdr={[Ndr]:Xdr,[Adr]:ojt};function mVe(e){return $dr(e)?ojt:Jdr[e.$$typeof]||Kdr}var efr=Object.defineProperty,tfr=Object.getOwnPropertyNames,gVe=Object.getOwnPropertySymbols,nfr=Object.getOwnPropertyDescriptor,rfr=Object.getPrototypeOf,vVe=Object.prototype;function Gpe(e,t){if(typeof t!="string"){if(vVe){const i=rfr(t);i&&i!==vVe&&Gpe(e,i)}let n=tfr(t);gVe&&(n=n.concat(gVe(t)));const r=mVe(e),s=mVe(t);for(let i=0;i<n.length;++i){const o=n[i];if(!Ydr[o]&&!(s&&s[o])&&!(r&&r[o])){const l=nfr(t,o);try{efr(e,o,l)}catch{}}}}return e}var sfr=Symbol.for("react-redux-context"),ifr=typeof globalThis<"u"?globalThis:{};function ofr(){if(!g.createContext)return{};const e=ifr[sfr]??=new Map;let t=e.get(g.createContext);return t||(t=g.createContext(null),e.set(g.createContext,t)),t}var ajt=ofr(),afr=[null,null];function lfr(e,t,n){CQ(()=>e(...t),n)}function cfr(e,t,n,r,s,i){e.current=r,n.current=!1,s.current&&(s.current=null,i())}function ufr(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 dfr(e,t){return e===t}function ffr(e,t,n,{pure:r,areStatesEqual:s=dfr,areOwnPropsEqual:i=XB,areStatePropsEqual:o=XB,areMergedPropsEqual:l=XB,forwardRef:c=!1,context:u=ajt}={}){const d=u,f=zdr(e),h=Ldr(t),p=Udr(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:te,...se}=T;return[T.context,te,se]},[T]),A=g.useMemo(()=>{let te=d;return _?.Consumer,te},[_,d]),P=g.useContext(A),L=!!T.store&&!!T.store.getState&&!!T.store.dispatch,F=!!P&&!!P.store,Q=L?T.store:P.store,q=F?P.getServerState:Q.getState,B=g.useMemo(()=>Mdr(Q.dispatch,S),[Q]),[V,H]=g.useMemo(()=>{if(!m)return afr;const te=ijt(Q,L?void 0:P.subscription),se=te.notifyNestedSubs.bind(te);return[te,se]},[Q,L,P]),D=g.useMemo(()=>L?P:{...P,subscription:V},[L,P,V]),K=g.useRef(void 0),M=g.useRef(I),$=g.useRef(void 0),z=g.useRef(!1),U=g.useRef(!1),G=g.useRef(void 0);CQ(()=>(U.current=!0,()=>{U.current=!1}),[]);const ne=g.useMemo(()=>()=>$.current&&I===M.current?$.current:B(Q.getState(),I),[Q,I]),X=g.useMemo(()=>se=>V?ufr(m,Q,V,B,M,K,z,U,$,H,se):()=>{},[V]);lfr(cfr,[M,K,z,I,$,H]);let ee;try{ee=g.useSyncExternalStore(X,ne,q?()=>B(q(),I):ne)}catch(te){throw G.current&&(te.message+=`
|
|
259
259
|
The error may be correlated with this previous error:
|
|
260
260
|
${G.current.stack}
|
|
@@ -672,7 +672,7 @@ window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-
|
|
|
672
672
|
`),r=t.split(`
|
|
673
673
|
`),s=n.length,i=r.length,o=Array.from({length:s+1},()=>new Array(i+1).fill(0));for(let d=1;d<=s;d++)for(let f=1;f<=i;f++)n[d-1]===r[f-1]?o[d][f]=o[d-1][f-1]+1:o[d][f]=Math.max(o[d-1][f],o[d][f-1]);const l=[];let c=s,u=i;for(;c>0||u>0;)c>0&&u>0&&n[c-1]===r[u-1]?(l.push({type:"equal",text:n[c-1]}),c--,u--):u>0&&(c===0||o[c][u-1]>=o[c-1][u])?(l.push({type:"added",text:r[u-1]}),u--):(l.push({type:"removed",text:n[c-1]}),c--);return l.reverse()}function gye(e){return e.type==="prompt_block"&&typeof e.content=="string"?e.content:null}function Rgs({promptBlockId:e}){const{data:t}=_z({blockId:e,queryOptions:{enabled:!!e}}),n=t?.content??"";return n?a.jsx(ii,{content:n,tooltip:"Copy prompt block text",size:"sm"}):null}function PM({block:e}){const t=gye(e);return t?a.jsx(ii,{content:t,tooltip:"Copy prompt text",size:"sm"}):e.type==="prompt_block_ref"&&(typeof e.promptBlockId=="string"||typeof e.id=="string")?a.jsx(Rgs,{promptBlockId:e.promptBlockId??e.id}):null}function Mgs({previousBlocks:e,currentBlocks:t}){const n=Array.isArray(e)?e:[],r=Array.isArray(t)?t:[],s=r.map(l=>gye(l)??""),i=n.map(l=>gye(l)??"");if(n.length<=1&&r.length<=1){const l=i[0]??"",c=s[0]??"",u=n[0];if(l===c)return a.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[u&&a.jsx("div",{className:"absolute top-2 right-2",children:a.jsx(PM,{block:u})}),a.jsx(Y,{variant:"caption",tone:"muted",font:"mono",className:"whitespace-pre-wrap",children:l||"(empty)"})]});const d=bet(l,c);return a.jsxs("div",{className:"relative overflow-hidden rounded-md border border-border",children:[u&&a.jsx("div",{className:"absolute top-2 right-2 z-10",children:a.jsx(PM,{block:u})}),d.map((f,h)=>a.jsxs(Y,{as:"p",variant:"body",tone:"muted",className:Z("px-3 py-0.5 wrap-break-word whitespace-pre-wrap",f.type==="removed"&&"bg-destructive-subtle text-destructive-subtle-foreground",f.type==="added"&&"bg-success-subtle text-success-subtle-foreground"),children:[a.jsx("span",{className:"mr-2 inline-block w-4 shrink-0 text-muted-foreground/50 select-none",children:f.type==="removed"?"−":f.type==="added"?"+":" "}),f.text||" "]},h))]})}const o=Math.max(n.length,r.length);return a.jsx("div",{className:"flex flex-col gap-2",children:Array.from({length:o},(l,c)=>{const u=n[c],d=r[c],f=i[c]??"",h=s[c]??"";if(!u&&d)return a.jsxs("div",{className:"rounded-md border border-success-edge bg-success-subtle p-3",children:[a.jsx(Y,{variant:"meta",className:"mb-1 text-success-subtle-foreground",children:"+ Added block"}),a.jsx(Y,{variant:"caption",className:"whitespace-pre-wrap text-success-subtle-foreground",children:h})]},c);if(u&&!d)return a.jsxs("div",{className:"relative rounded-md border border-destructive-edge bg-destructive-subtle p-3",children:[a.jsx("div",{className:"absolute top-2 right-2",children:a.jsx(PM,{block:u})}),a.jsx(Y,{variant:"meta",className:"mb-1 text-destructive-subtle-foreground",children:"− Removed in latest"}),a.jsx(Y,{variant:"caption",className:"whitespace-pre-wrap text-destructive-subtle-foreground",children:f})]},c);if(f===h)return a.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[u&&a.jsx("div",{className:"absolute top-2 right-2",children:a.jsx(PM,{block:u})}),a.jsx(Y,{variant:"caption",tone:"muted",font:"mono",className:"whitespace-pre-wrap",children:f||"(empty)"})]},c);const p=bet(f,h);return a.jsxs("div",{className:"relative overflow-hidden rounded-md border border-border",children:[u&&a.jsx("div",{className:"absolute top-2 right-2 z-10",children:a.jsx(PM,{block:u})}),p.map((m,v)=>a.jsxs(Y,{as:"p",variant:"body",tone:"muted",className:Z("px-3 py-0.5 wrap-break-word whitespace-pre-wrap",m.type==="removed"&&"bg-destructive-subtle text-destructive-subtle-foreground",m.type==="added"&&"bg-success-subtle text-success-subtle-foreground"),children:[a.jsx("span",{className:"mr-2 inline-block w-4 shrink-0 text-muted-foreground/50 select-none",children:m.type==="removed"?"−":m.type==="added"?"+":" "}),m.text||" "]},v))]},c)})})}function Dgs({promptBlockId:e}){const{data:t,isLoading:n}=_z({blockId:e,queryOptions:{enabled:!!e}});if(n)return a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(_n,{className:"h-4 w-4"})});const r=t?.content??"";return a.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[r&&a.jsx("div",{className:"absolute top-2 right-2",children:a.jsx(ii,{content:r,tooltip:"Copy prompt block text",size:"sm"})}),t?.name&&a.jsx(Y,{variant:"meta",tone:"muted",className:"mb-1",children:t.name}),a.jsx(Y,{variant:"caption",tone:"muted",font:"mono",className:"whitespace-pre-wrap",children:r||"(empty)"})]})}function gBt({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(Dgs,{promptBlockId:i},i??r)}const s=typeof n.content=="string"?n.content:"";return a.jsxs("div",{className:"relative rounded-md border border-border bg-background p-3",children:[s&&a.jsx("div",{className:"absolute top-2 right-2",children:a.jsx(ii,{content:s,tooltip:"Copy prompt text",size:"sm"})}),a.jsx(Y,{variant:"caption",tone:"muted",font:"mono",className:"whitespace-pre-wrap",children:s||"(empty)"})]},n.id??r)})})}function Lgs({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(Mt,{variant:"destructive",className:"ml-auto",children:"removed in latest"}),c==="added"&&a.jsx(Mt,{variant:"success",className:"ml-auto",children:"added in latest"})]},i)})})}function zgs({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 Fgs({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(Mt,{variant:"destructive",className:"ml-auto",children:"removed in latest"}),d==="added"&&a.jsx(Mt,{variant:"success",className:"ml-auto",children:"added in latest"})]},l)})})}function Bgs({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(Mt,{children:String(s.type)}):null]},r))})}function Ugs({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r}=Tl(),s=r.watch("tools"),i=r.watch("variables"),o=r.watch("instructionBlocks"),l=s?Object.keys(s).length:0,{data:c,isLoading:u}=lcr({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(Mt,{variant:"warning",size:"sm",children:"modified"}):null,v=h?a.jsx(Mt,{variant:"warning",size:"sm",children:"modified"}):l>0?a.jsx(Mt,{size:"sm",children:`${l}`}):null,y=p?a.jsx(Mt,{variant:"warning",size:"sm",children:"modified"}):null;return u?a.jsx("div",{className:"flex items-center justify-center py-5",children:a.jsx(_n,{className:"h-5 w-5"})}):a.jsxs(Wc,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[a.jsxs(Hc,{variant:"pill-ghost",className:"shrink-0",children:[a.jsx(si,{value:"variables",children:a.jsx(YI,{title:"Variables",icon:a.jsx(Ua,{}),badge:y})}),a.jsx(si,{value:"instructions",children:a.jsx(YI,{title:"System Prompt",icon:a.jsx(yP,{}),badge:m})}),a.jsx(si,{value:"tools",children:a.jsx(YI,{title:"Tools",icon:a.jsx(dd,{}),badge:v})})]}),a.jsx(No,{value:"variables",className:"px-4 py-4",children:p?a.jsx(Fgs,{previousVars:p.previousValue,currentVars:p.currentValue}):a.jsx(Bgs,{variables:i})}),a.jsx(No,{value:"instructions",className:"px-4 py-4",children:f?a.jsx(Mgs,{previousBlocks:f.previousValue,currentBlocks:f.currentValue}):a.jsx(gBt,{blocks:o})}),a.jsx(No,{value:"tools",className:"px-4 py-4",children:h?a.jsx(Lgs,{previousTools:h.previousValue,currentTools:h.currentValue}):a.jsx(zgs,{tools:s})})]})}function Vgs({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r,readOnly:s,isCodeAgentOverride:i,editorConfig:o}=Tl(),{isInstructionsLocked:l}=iT(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(Ir,{className:"min-h-0 flex-1",children:p?a.jsx(Ugs,{agentId:e,selectedVersionId:t,latestVersionId:n}):a.jsxs(Wc,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[a.jsxs(Hc,{variant:"pill-ghost",className:"shrink-0",children:[a.jsx(si,{value:"variables",children:a.jsx(YI,{title:"Variables",icon:a.jsx(Ua,{})})}),a.jsx(si,{value:"instructions",children:a.jsx(YI,{title:"System Prompt",icon:a.jsx(yP,{})})}),a.jsx(si,{value:"tools",children:a.jsx(YI,{title:"Tools",icon:a.jsx(dd,{}),badge:f>0?a.jsx(Mt,{size:"sm",children:`${f}`}):void 0})})]}),a.jsx(No,{value:"variables",className:"py-0",children:a.jsxs("div",{className:"flex flex-col gap-1 px-4 py-4",children:[h.length>0?a.jsx("div",{className:"flex flex-col",children:h.map(([m,v])=>a.jsx(mBt,{name:m,prop:v,depth:0},m))}):null,a.jsx(Y,{variant:"meta",tone:"muted",className:"mt-1",children:h.length>0?"Defined via requestContextSchema in code.":"No variables defined. Add a requestContextSchema to your agent to define variables."})]})}),a.jsxs(No,{value:"instructions",className:"px-4 py-0 pb-4",children:[a.jsx("div",{className:"flex flex-col gap-3 pt-4 pb-2",children:a.jsxs(Y,{variant:"caption",tone:"muted",children:["Add instruction blocks to your agent. Blocks are combined in order to form the system prompt. You can"," ",a.jsxs(Fn,{children:[a.jsx(Mn,{className:Z("inline cursor-pointer underline decoration-dotted",Ln,On),children:"use variables"}),a.jsx(Dn,{side:"bottom",align:"start",className:"max-w-72",children:a.jsxs("span",{children:["Use ",a.jsx(sh,{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(gBt,{blocks:u}):a.jsx(U7t,{})]}),a.jsx(No,{value:"tools",className:"px-4 py-0 pb-4",children:a.jsx(V7t,{})})]})})]})}function Qce(e){return typeof e=="object"&&e!==null}function qgs(e){if(!Qce(e))return{};const t={};return typeof e.maxSteps=="number"&&(t.maxSteps=e.maxSteps),Qce(e.modelSettings)&&(t.modelSettings=e.modelSettings),Qce(e.providerOptions)&&(t.providerOptions=e.providerOptions),t}function wNe(e){if(!e)return{modelSettings:{}};const t=qgs(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 SNe({agentId:e}){return a.jsxs(a.Fragment,{children:[a.jsx($ke,{entityType:"agent",entityId:e}),a.jsx(BOt,{entityType:"agent",entityId:e})]})}function Qgs({ctx:e}){const{isDirty:t}=ASe({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(ue,{type:"button",variant:"default",size:"sm",onClick:()=>n(),disabled:r,icon:a.jsx(Fm,{}),children:r?"Saving...":i}),children:a.jsx(Wt.Message,{children:o})})}function Zgs({agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s}){const i=g.useMemo(()=>Sa(),[e]),o=xr("agent",e)[0],l=Object.keys(o).length>0,c=OXr(),{data:u}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),d=g.useMemo(()=>wNe(u),[u]);return a.jsx(zDt,{agentId:e,defaultSettings:d,children:a.jsx(yX,{children:a.jsxs(xX,{agentId:e,threadId:i,enabled:!!(u?.hasBrowser??u?.browserTools?.length),children:[a.jsx(nNe,{children:a.jsx(SX,{children:a.jsx(TJr,{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(Qgs,{ctx:c}),a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx(MNe,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,supportsMemory:u?.supportsMemory,threadId:i,memory:s,modelList:u?.modelList,isNewThread:!0,runOptionsSlot:a.jsx(SNe,{agentId:e})},i)})]})})},i)}),a.jsx(cDt,{})]},`session-${e}-${i}`)},`browser-${e}-${i}`)})}function Wgs({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}=YL({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,A=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} - ${Jr(q.createdAt,"date-time")??""}`,description:q.changeMessage||void 0,end:u?a.jsx(Mt,{variant:B?"success":"info",children:B?"Current":"Saved"}):B?a.jsx(Mt,{variant:"success",children:"Published"}):V?a.jsx(Mt,{variant:"info",children:"Draft"}):void 0}}),[T,t,I,u]),P=n??_?.id??"",L=c||!s||i||o,F=u?"Code mode saves write override JSON to filesystem-backed editor storage. This dropdown shows saved override snapshots for this agent.":"Changes are saved as draft versions. When you're ready, publish a version to make it the active configuration used in production.",Q=g.useCallback(async()=>{if(i)return;const q=k.trim();await p(q||void 0),S(!1),j("")},[k,p,i]);return{versionSelector:a.jsxs("div",{className:"flex items-center gap-2 border-b border-border bg-card px-4 py-3",children:[T.length>0?a.jsx(fl,{options:A,value:P,onValueChange:r,placeholder:"Select version...",variant:"ghost",className:"min-w-0 flex-1"}):a.jsx(Y,{variant:"meta",tone:"muted",children:u?"No filesystem saves yet":"No versions yet"}),P&&a.jsx(ii,{content:P,tooltip:"Copy version ID",size:"sm"}),a.jsxs(Fn,{children:[a.jsx(Mn,{"aria-label":"Version information",className:Z("shrink-0 rounded-sm",ji,Ln,On),children:a.jsx(At,{size:"xs",children:a.jsx(hp,{})})}),a.jsx(Dn,{side:"bottom",align:"start",className:"max-w-56",children:F})]}),a.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[c&&a.jsx(Mt,{variant:"warning",children:"Read-only"}),!c&&l&&!u&&a.jsx(Mt,{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(ue,{variant:"default",size:"md",onClick:()=>{v?.()},icon:a.jsx(fp,{}),children:"Download JSON"}),f?a.jsx(ue,{variant:"primary",size:"md",onClick:()=>{y?.()},title:h,icon:a.jsx(Dht,{}),children:"Open PR"}):a.jsx(ue,{variant:"primary",size:"md",onClick:()=>{p()},disabled:L,children:i?a.jsxs(a.Fragment,{children:[a.jsx(_n,{className:"size-3.5"}),"Saving…"]}):a.jsxs(a.Fragment,{children:[a.jsx(At,{size:"xs",children:a.jsx(Fm,{})}),"Save to filesystem"]})})]}):c&&!x?null:a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[a.jsxs(pc,{children:[a.jsx(ue,{variant:"default",onClick:()=>p(),disabled:L,children:i?a.jsxs(a.Fragment,{children:[a.jsx(_n,{className:"size-3.5"}),"Saving…"]}):a.jsxs(a.Fragment,{children:[a.jsx(At,{size:"xs",children:a.jsx(Fm,{})}),"Save New Version"]})}),a.jsxs(ct,{children:[a.jsx(ct.Trigger,{asChild:!0,children:a.jsx(ue,{variant:"default",disabled:L,"aria-label":"More save options",children:a.jsx(dc,{className:"size-3.5"})})}),a.jsx(ct.Content,{align:"end",children:a.jsxs(ct.Item,{onSelect:()=>S(!0),children:[a.jsx(At,{size:"xs",children:a.jsx(dL,{})}),"Save with message"]})})]})]}),a.jsx(ue,{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(_n,{className:"size-3.5"}),"Publishing…"]}):a.jsxs(a.Fragment,{children:[a.jsx(At,{size:"xs",children:a.jsx(ur,{})}),x?"Publish This Version":"Publish"]})})]}),a.jsx(Kr,{open:b,onOpenChange:S,pending:i,children:a.jsxs(Yr,{children:[a.jsxs(Xr,{children:[a.jsx(Qr,{children:"Save New Version"}),a.jsx(Lo,{children:"Add a message to describe the changes in this version."})]}),a.jsx(qr,{children:a.jsxs(ht,{children:[a.jsx(ut,{children:"Change message"}),a.jsx(wn,{placeholder:"Describe what changed...",value:k,onChange:q=>j(q.target.value),onKeyDown:q=>{q.key==="Enter"&&Q()},disabled:i,autoFocus:!0})]})}),a.jsxs(Yo,{children:[a.jsx(Ca,{children:"Cancel"}),a.jsx(ja,{onConfirm:Q,children:"Save Version"})]})]})})]})}}function Hgs({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}=Wgs({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(bNe,{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(Vgs,{agentId:e,selectedVersionId:n,latestVersionId:r})}),k]})}function Ggs({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(aye,{agentId:e,leftDrawerLabel:"Open configuration",leftSlot:a.jsx(Hgs,{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(Zgs,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s})})}function FJ(e,t,n){const r=e.get(t);if(r!==void 0)return r;const s=n();return e.set(t,s),s}const Kgs=3e4;function vBt(e){return e6(e.state.error,"feedback")||t6(e.state.error)?!1:Kgs}const kNe={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 BJ(e){const t=e.attributes?.processorPhase;return typeof t=="string"&&Object.hasOwn(kNe,t)?t:void 0}function yBt(e,t){const n=BJ(e);if(!(!n||Object.keys(t).length===0))return{phase:n,phaseLabel:kNe[n],data:t}}function Ygs(e,t){return yBt(e,t)}function Xgs(e,t){return yBt(e,t)}const Jgs=["processorPhase","processorExecutor","processorIndex","hookDurationMs","messageListMutations","tripwireAbort"];function xBt(e){const t=BJ(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(Jgs);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:kNe[t],executor:n.processorExecutor,processorIndex:n.processorIndex,hookDurationMs:n.hookDurationMs,messageListMutations:r,tripwireAbort:s,...Object.keys(o).length>0?{rest:o}:{}}}const Nj=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zce=e=>e.status==="suspended"||e.status==="aborted"||e.status==="interrupted",evs=["agent_run","model_step","model_inference"];function bBt(e){const t=e.input;if(t==null)return;if(e.spanType==="agent_run"&&e.metadata?.resumed===!0)return{type:"agent-run-resume",value:Nj(t)?t:{resumeData:t}};if(BJ(e)){const r=Nj(t)?Ygs(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 evs.includes(e.spanType)?{type:"messages",value:t}:{type:"json",value:t};if(!Nj(t))return{type:"json",value:t};const n=e.spanType==="agent_run";if((n||e.spanType==="model_generation")&&"messages"in t){const{messages:r}=t;if(typeof r=="string")return{type:"text",value:r};if(Array.isArray(r))return{type:"messages",value:r};if(Nj(r))return{type:"messages",value:[r]}}if(n){if(typeof t.role=="string")return{type:"messages",value:[t]};if("toolCallId"in t||"toolName"in t||"resumeData"in t)return{type:"agent-run-resume",value:t}}return{type:"json",value:t}}function wBt(e){const t=e.output;if(t!=null){if(BJ(e)){const n=Nj(t)?Xgs(e,t):void 0;return n?{type:"processor",value:n}:{type:"json",value:t}}if(typeof t=="string")return{type:"text",value:t};if(!Nj(t))return{type:"json",value:t};switch(e.spanType){case"agent_run":return Zce(t)?{type:"interrupted",value:t}:{type:"agent-run-result",value:t};case"model_generation":return Zce(t)?{type:"interrupted",value:t}:{type:"model-generation-result",value:t};case"model_step":return Zce(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 tvs=e=>Nj(e)&&typeof e.message=="string";function nvs(e){return tvs(e.error)?e.error:void 0}const Iz=300*1e3;function rvs({traceId:e,spanId:t,depth:n,queryOptions:r}){return Ge(),_t({queryKey:["branch",e,t,n],queryFn:async()=>{throw new Error("traceId and spanId are required")},staleTime:0,...r})}const D2={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"};function wet(e){return Object.values(od).find(t=>t===e)}const ONe=({entityType:e,rootOnly:t=!1,queryOptions:n}={})=>{const r=Ge();return _t({queryKey:e?["observability-entity-names","by-type",e]:["observability-entity-names","all",t?"root-only":"all-types"],queryFn:async()=>{try{if(e){const i=wet(e);return i?await r.getEntityNames({entityType:i}):{names:[]}}if(!t)return await r.getEntityNames();const s=await Promise.all(Object.values(D2).map(i=>{const o=wet(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:Iz,...n})},jNe=({queryOptions:e}={})=>{const t=Ge();return _t({queryKey:["observability-environments"],queryFn:async()=>{try{return await t.getEnvironments()}catch{return{environments:[]}}},select:n=>n?.environments??[],retry:!1,staleTime:Iz,...e})},SBt=({queryOptions:e}={})=>{const t=Ge();return _t({queryKey:["observability-service-names"],queryFn:async()=>{try{return await t.getServiceNames()}catch{return{serviceNames:[]}}},select:n=>n?.serviceNames??[],retry:!1,staleTime:Iz,...e})},svs=1e3*60*60*24*30;function CNe({traceId:e,spanId:t,queryOptions:n}){const r=Ge();return _t({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?svs:0,...n})}const kBt=({queryOptions:e}={})=>{const t=Ge();return _t({queryKey:["observability-tags"],queryFn:async()=>{try{return await t.getTags()}catch{return{tags:[]}}},select:n=>n?.tags??[],retry:!1,staleTime:Iz,...e})};function ivs({threadId:e,queryOptions:t}){const n=Ge(),{data:r}=_t({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 _Ne=(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 oT({traceId:e,passive:t=!1,queryOptions:n}){const r=Ge(),{queryKey:s,queryFn:i,enabled:o,staleTime:l}=_Ne(r,e);return _t({queryKey:s,queryFn:i,enabled:o,staleTime:l,refetchOnMount:!t,refetchOnWindowFocus:!t,refetchOnReconnect:!t,...n})}function ovs(){const e=Ge(),t=mr();return n=>t.fetchQuery(_Ne(e,n))}function avs({traceId:e,anchorSpanId:t,listMode:n,depth:r,queryOptions:s}){const i=n==="branches",o=oT({traceId:e,queryOptions:{enabled:!!e,...s?.trace}});return rvs({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 lvs(e){return e?.page.next??void 0}function cvs(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 Wce=e=>typeof e=="string"?e:e.toISOString();function uvs(e){return{traceId:e.traceId,rootSpanId:e.spanId,name:e.name,entityId:e.entityId??null,parentSpanId:e.parentSpanId??null,createdAt:Wce(e.createdAt),metadata:e.metadata??null,inputPreview:e.inputPreview??null,threadId:e.threadId??null,resourceId:e.resourceId??null,startedAt:Wce(e.startedAt),endedAt:e.endedAt==null?e.endedAt:Wce(e.endedAt),entityName:e.entityName??null,entityType:e.entityType??null,environment:null,status:e.status}}function dvs(e){const t=new Set;return e.pages.flatMap(n=>n.spans.flatMap(r=>t.has(r.traceId)?[]:(t.add(r.traceId),[uvs(r)])))}function fvs(e){return e.pagination?.hasMore?e.pagination.page+1:void 0}function hvs({query:e,limit:t=25,enabled:n=!0,withQueryTrace:r=!0,legacyFilters:s,queryOptions:i}){const o=Ge(),{inView:l,setRef:c}=K0(),u=Dm({queryKey:["trace-query",e,t],queryFn:e?async({pageParam:I})=>{const A=await new hj({...o.options,retries:0}).queryTraces({...e,page:{limit:t,after:I??null}});if("traces"in A&&"page"in A)return A;throw new Error("Expected a cursor-paginated trace query response")}:V0,initialPageParam:void 0,getNextPageParam:lvs,select:cvs,retry:!1,placeholderData:fx,enabled:n&&r,...i?.traceQuery}),d=e?.orderBy,f=d?.[0]?.direction==="asc"?"ASC":"DESC",h=Dm({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:fvs,select:dvs,retry:!1,placeholderData:fx,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 vye="mastra_model_total_input_tokens",OBt="mastra_model_total_output_tokens",ket=500;function pvs(e){const t=[];for(let n=0;n<e.length;n+=ket)t.push(e.slice(n,n+ket));return t}function mvs(){return{estimatedCost:0,hasEstimatedCost:!1,costUnits:new Set,hasUnknownCostUnit:!1}}function gvs(e,t){for(const n of t.groups){const r=n.dimensions.traceId,s=n.dimensions.name;if(!r||s!==vye&&s!==OBt)continue;const i=FJ(e,r,mvs),o=s===vye?"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 vvs(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 yye({traceIds:e,enabled:t,autoRefetch:n,queryOptions:r}){const s=Ge(),i=[...new Set(e)].toSorted(),o=`${s.options.baseUrl||(typeof window>"u"?"local":window.location.origin||"local")}:${s.options.apiPrefix??"/api"}`;return _t({queryKey:["trace-usage",o,i],enabled:t&&i.length>0,queryFn:async()=>{const l=pvs(i),c=await Promise.allSettled(l.map(d=>s.getMetricBreakdown({name:[vye,OBt],aggregation:"sum",groupBy:["traceId","name"],filters:{traceIds:d},limit:d.length*2}))),u=new Map;for(const d of c)d.status==="fulfilled"&&gvs(u,d.value);return vvs(u)},placeholderData:(l,c)=>c?.queryKey[1]===o?l:void 0,refetchInterval:t&&n?1e4:!1,...r})}const jBt=({traceId:e,spanId:t,queryOptions:n})=>{const r=Ge(),s=mr();return Sn({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})},CBt=({traceId:e,spanId:t,queryOptions:n})=>{const r=Ge(),s=mr();return Sn({mutationFn:({feedbackId:i})=>r.deleteFeedback({feedbackIds:[i]}),onSuccess:()=>s.invalidateQueries({queryKey:t?["span-feedback",e,t]:["trace-feedback",e]}),...n})},TNe=({traceId:e="",spanId:t="",page:n,queryOptions:r})=>{const s=Ge(),i=n??0;return _t({queryKey:["span-feedback",e,t,i],queryFn:()=>s.listFeedback({filters:{traceId:e,spanId:t},pagination:{page:i,perPage:10}}),refetchInterval:vBt,gcTime:0,staleTime:0,...r})},UJ=({traceId:e="",page:t,queryOptions:n})=>{const r=Ge(),s=t??0;return _t({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:vBt,gcTime:0,staleTime:0,...n})},_Bt=100,Oet={canonicalFields:[],observedFields:[],observedFieldsTruncated:!1},yvs="TRACE_QUERY_DISCOVERY_UNSUPPORTED",xvs=e=>e instanceof lx&&typeof e.body=="object"&&e.body!==null&&e.body.code===yvs,bvs=e=>["trace-query-fields",e.from,e.to],TBt=(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:_Bt},{signal:i});return o.map(({value:l})=>({value:l}))},wvs=({timeRange:e,queryOptions:t})=>{const n=Ge(),r=_t({queryKey:bvs(e),queryFn:async({signal:o})=>{try{return await n.getTraceQueryFields({timeRange:e,predicateScope:"trace",limit:_Bt},{signal:o})}catch(l){if(xvs(l))return Oet;throw l}},retry:!1,staleTime:Iz,placeholderData:fx,...t}),s=r.data?.observedFields,i=r.data?.canonicalFields??Oet.canonicalFields;return{fields:g.useMemo(()=>(s??[]).map(o=>({path:o.path,suggestions:TBt(n,e,"trace",o.path)})),[s,n,e]),canonicalFields:i,isLoading:r.isLoading,error:r.error}};function Svs(){const e=Ge();return`mastra:traces:columns:${e.options.baseUrl||(typeof window>"u"?"local":window.location.origin||"local")}:${e.options.apiPrefix??"/api"}`}const xye=(e,t)=>e==="number"?Number(t):e==="boolean"?t.toLowerCase()==="true":t,qa=e=>"kind"in e&&e.kind==="group",ENe=new Set(["runId","sessionId","requestId","userId","organizationId","serviceName","experimentId"]),kvs=["is","isNot","in","notIn","exists","notExists","gt","gte","lt","lte","matches","notMatches"],INe=e=>kvs.includes(e),bye=e=>"nodes"in e,Ovs={is:"eq",isNot:"ne",in:"in",notIn:"notIn",exists:"exists",notExists:"notExists",gt:"gt",gte:"gte",lt:"lt",lte:"lte",matches:"matches",notMatches:"notMatches"},EBt=new Set(["durationMs","spans.durationMs","scores.score","feedback.value"]),jvs=new Set(["entityType","status","entityName","environment","traceId","threadId","resourceId","durationMs"]),Cvs=new Set(["threadId","resourceId","environment","durationMs"]),IBt={isNot:"is",notIn:"in",notExists:"exists",notMatches:"matches"},_vs=e=>e in IBt,NBt=["spans","scores","feedback"];function Tvs(e){if(e==="entityId")return{scope:"spans",path:"entityId"};for(const t of NBt)if(e.startsWith(`${t}.`)&&e.length>t.length+1)return{scope:t,path:e.slice(t.length+1)};return{path:e}}function jet(e,t,n){const r=Ovs[e];switch(r){case"exists":case"notExists":return{op:r,path:t};case"in":case"notIn":return n.length?{op:r,value:{path:t},set:n}:void 0;case"matches":case"notMatches":{const[s]=n;return typeof s=="string"?{op:r,left:{path:t},right:{literal:s}}:void 0}default:{if(!n.length)return;if(n.length>1){if(r==="eq")return{op:"in",value:{path:t},set:n};if(r==="ne")return{op:"notIn",value:{path:t},set:n}}const[s]=n;return s===void 0?void 0:{op:r,left:{path:t},right:{literal:s}}}}}function Evs(e,t){if(e==="exists"||e==="notExists")return{op:e,path:"tags"};const n=e==="notIn"||e==="isNot",r=t.map(i=>({op:n?"notIncludes":"includes",path:"tags",value:i})),s=r.length<=1?r[0]:{op:n?"and":"or",args:r};return!s||!n?s:{op:"or",args:[s,{op:"notExists",path:"tags"}]}}const Ivs=new Set(["spans.error"]);function Nvs(e,t){if(ENe.has(e.fieldId)||t.has(e.fieldId))return;const n=e.operatorId??(e.fieldId==="tags"?"in":"is"),r=n==="exists"||n==="notExists";if(Ivs.has(e.fieldId)&&!r)return;const s=(Array.isArray(e.value)?e.value:[e.value]).filter(f=>typeof f=="string"&&!!f.trim()&&!NNe(f,n));if(!s.length&&!r)return;if(e.fieldId==="tags"){const f=Evs(n,s);return f?{predicate:f}:void 0}let i=e.fieldId,o=s;if(i.startsWith("metadata.")){if(i.length===9)return}else if(i==="rootEntityType"||i==="entityType")i="entityType";else if(i==="status"){if(o=s.filter(f=>f!=="running"),!o.length&&!r)return}else if(EBt.has(i)&&(o=s.map(Number).filter(f=>!Number.isNaN(f)),!o.length&&!r))return;if((n==="matches"||n==="notMatches")&&(o=o.filter(f=>/[\p{L}\p{M}\p{N}]/u.test(String(f))),!o.length))return;const{scope:l,path:c}=Tvs(i),u=i.startsWith("metadata.");if(!l&&!u&&!jvs.has(i))return;if(l&&_vs(n)){const f=jet(IBt[n],c,o);return f?{predicate:{[l]:{none:f}}}:void 0}const d=jet(n,c,o);if(d)return l?{scope:l,predicate:d}:(n==="isNot"||n==="notIn")&&(u||Cvs.has(i))?{predicate:{op:"or",args:[d,{op:"notExists",path:c}]}}:{predicate:d}}function ABt(e,{mergeRelated:t,excludedFieldIds:n}){const r=[],s={spans:[],scores:[],feedback:[]};for(const i of e){const o=Nvs(i,n);o&&("scope"in o?t?s[o.scope].push(o.predicate):r.push({[o.scope]:{some:o.predicate}}):r.push(o.predicate))}for(const i of NBt){const[o,...l]=s[i];if(!o)continue;const c=l.length?{op:"and",args:[o,...l]}:o;r.push({[i]:{some:c}})}return r}function PBt(e,t){const n=e.nodes.filter(s=>!bye(s)),r=ABt(n,{mergeRelated:e.logic==="and",excludedFieldIds:t});for(const s of e.nodes){if(!bye(s))continue;const i=PBt(s,t);i&&r.push(i)}if(r.length!==0)return r.length===1?r[0]:{op:e.logic,args:r}}function Cet({rootEntityType:e,status:t,dateFrom:n,dateTo:r,tokens:s,groups:i=[],excludedFieldIds:o=new Set,now:l}){const c=[];e&&c.push({op:"eq",left:{path:"entityType"},right:{literal:e}}),t&&t!=="running"&&c.push({op:"eq",left:{path:"status"},right:{literal:t}}),c.push(...ABt(s,{mergeRelated:!0,excludedFieldIds:o}));for(const u of i){const d=PBt(u,o);d&&c.push(d)}return{timeRange:{from:(n??new Date(l.getTime()-10080*60*1e3)).toISOString(),to:(r??l).toISOString()},...c.length?{where:{op:"and",args:c}}:{}}}const Avs=744*60*60*1e3;function Pvs(e){const t=new Date(e.to).getTime(),n=new Date(e.from).getTime(),r=t-Avs;return n>=r&&n<t?e:{from:new Date(r).toISOString(),to:e.to}}const $Bt=[{label:"Agent",entityType:D2.AGENT},{label:"Workflow",entityType:D2.WORKFLOW},{label:"Scorer",entityType:D2.SCORER},{label:"Ingest",entityType:D2.INGEST}],$vs=[{label:"Running",value:"running"},{label:"Success",value:"success"},{label:"Error",value:"error"}],b3="metadata.",wW="filterMetadata.",RBt=e=>e.startsWith(b3)&&e.length>b3.length,VJ=e=>e.startsWith(wW)&&e.length>wW.length,Rvs=e=>wW+e.slice(b3.length),Mvs=e=>b3+e.slice(wW.length),w$="rootEntityType",S$="status",_et={rootEntityType:w$,status:S$},z1="listMode",OU="anchorSpanId",Dvs=new Set(["traces","branches"]),F1="datePreset",x1="dateFrom",b1="dateTo",Lvs=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),yl={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",traceId:"filterTraceId",durationMs:"filterDurationMs",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId","spans.name":"filterSpanName","spans.spanType":"filterSpanType","spans.model":"filterSpanModel","spans.provider":"filterSpanProvider","spans.durationMs":"filterSpanDurationMs","spans.error":"filterSpanError","scores.scorerId":"filterScorerId","scores.score":"filterScore","feedback.feedbackType":"filterFeedbackType","feedback.value":"filterFeedbackValue","feedback.comment":"filterFeedbackComment"},qJ=Object.keys(yl),MBt=".op",sS=e=>e+MBt,DBt=e=>e.endsWith(MBt),LBt=e=>e==="exists"||e==="notExists",zvs=e=>e==="in"||e==="notIn",FA=e=>e.operatorId??(Array.isArray(e.value)?"in":"is"),NNe=(e,t)=>e==="Any"&&t!=="matches"&&t!=="notMatches",wye=(e,t)=>{const n=e.get(sS(t));return n!==null&&INe(n)?n:void 0},Fvs=new Set(["running","success","error"]),ANe="mastra:traces:saved-filters";function Bvs(e,t=ANe){const n=cys(e),r=e.get(F1);r&&r!=="custom"&&n.set(F1,r);const s=RNe(n).filter(i=>i.nodes.length>0);n.delete(i_);for(const i of s)n.append(i_,$Ne(i));if(!n.toString()){Uvs(t);return}try{localStorage.setItem(t,n.toString())}catch{}}function Uvs(e=ANe){try{localStorage.removeItem(e)}catch{}}function Vvs(e=ANe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function qvs(e){if(e.has(F1)||e.has(x1)||e.has(b1)||e.has(w$)||e.has(S$)||e.has(z1)||e.has(i_))return!0;for(const t of qJ)if(e.has(yl[t]))return!0;for(const t of e.keys())if(VJ(t))return!0;return!1}const Qvs=[{id:"is",label:"is",widensTo:"in"},{id:"isNot",label:"is not",widensTo:"notIn"},{id:"in",label:"is any of",arity:"many"},{id:"notIn",label:"is none of",arity:"many"},{id:"exists",label:"exists",arity:"none"},{id:"notExists",label:"does not exist",arity:"none"},{id:"gt",label:"greater than"},{id:"gte",label:"at least"},{id:"lt",label:"less than"},{id:"lte",label:"at most"},{id:"matches",label:"matches",freeText:!0},{id:"notMatches",label:"does not match",freeText:!0}],L2=["is","isNot","in","notIn","exists","notExists"],Zvs=[...L2,"matches","notMatches"],Tet=["is","isNot","in","notIn"],Wvs=["is","isNot","gt","gte","lt","lte","exists","notExists"],Hvs=["gt","gte","lt","lte"],Gvs=["exists","notExists"],Kvs=["in","notIn","exists","notExists"],Yvs={in:"includes",notIn:"notIncludes",exists:"exists",notExists:"notExists"},Eet=["is","in"],Xvs=["is"],Jvs={rootEntityType:"Primitive type",entityName:"Primitive name",entityId:"Primitive ID",status:"Status",tags:"Tags",serviceName:"Service Name",environment:"Environment",traceId:"Trace ID",runId:"Run ID",threadId:"Thread ID",sessionId:"Session ID",requestId:"Request ID",resourceId:"Resource ID",userId:"User ID",organizationId:"Organization ID",experimentId:"Experiment ID","spans.name":"Span name","spans.spanType":"Span type","spans.model":"Model","spans.provider":"Provider",durationMs:"Duration (ms)","spans.durationMs":"Span duration (ms)","spans.error":"Span error","scores.scorerId":"Scorer","scores.score":"Score","feedback.feedbackType":"Feedback type","feedback.value":"Feedback value","feedback.comment":"Feedback comment"},eys={timeRange:fC,rootEntityType:Oht,entityName:Nx,entityId:nwe,status:ECn,tags:ZNn,serviceName:bNn,environment:Pv,traceId:apt,runId:Uc,threadId:dL,sessionId:uL,requestId:Yht,resourceId:Z0,userId:pAn,organizationId:Y0e,experimentId:lL,"spans.name":EN,"spans.spanType":ONn,"spans.model":yP,"spans.provider":_fe,durationMs:gx,"spans.durationMs":gx,"spans.error":Yd,"scores.scorerId":tg,"scores.score":MIn,"feedback.feedbackType":nAn,"feedback.value":ex,"feedback.comment":JEn},zBt=e=>eys[e],PNe=e=>"var(--muted-foreground)",qE=e=>({id:e,label:Jvs[e]??e,icon:zBt(e),color:PNe()}),tys=["entityId","traceId","runId","threadId","sessionId","requestId","resourceId","userId","organizationId","experimentId"],nys=["spans.name","spans.spanType","spans.model","spans.provider","spans.durationMs","spans.error","scores.scorerId","scores.score","feedback.feedbackType","feedback.value","feedback.comment"],FBt=new Set(["spans.error"]),rys=new Set(["spans.name","feedback.comment"]),sys=new Set(["feedback.comment"]),xE=(e,t)=>e.label.localeCompare(t.label);function iys(e,t){const n=e.find(i=>i.path==="tags");if(!n)return;const r=Kvs.filter(i=>n.operators.includes(Yvs[i]??""));if(r.length===0)return;const s=n.valueSuggestions?t?.("trace","tags"):void 0;return{...qE("tags"),operators:r,...s?{suggestions:s}:{}}}function oys({availableRootEntityNames:e,availableEnvironments:t,hiddenFieldIds:n=[],metadataFields:r=[],canonicalTraceFields:s=[],valueSuggestions:i,withQueryTrace:o=!0,withRootDuration:l=!1}){const c=(k,j,C=L2)=>({...qE(k),operators:C,strict:!0,suggestions:j}),u=k=>({...qE(k),operators:k==="traceId"?Tet:L2}),d=k=>{const[j,C]=k.split("."),T=sys.has(k)?void 0:i?.(j,C);return{...qE(k),operators:rys.has(k)?Zvs:L2,...T?{strict:!0,suggestions:T}:{}}},f=k=>({...qE(k),type:"number",operators:Wvs}),h=k=>({...qE(k),operators:Gvs}),p=[c("rootEntityType",$Bt.map(k=>({value:k.entityType,label:k.label})),Eet),c("entityName",e.map(k=>({value:k})),Tet),c("status",$vs.filter(k=>k.value!=="running").map(k=>({value:k.value,label:k.label})),Eet),c("environment",t.map(k=>({value:k})))],m=tys.map(u),v=["spans","scores","feedback"].flatMap(k=>nys.filter(j=>j.startsWith(`${k}.`)).map(j=>EBt.has(j)?f(j):FBt.has(j)?h(j):d(j)).sort(xE)),y=r.filter(({path:k})=>RBt(k)).map(({path:k,suggestions:j})=>({id:k,label:k.slice(b3.length),icon:Ua,color:PNe(),operators:L2,suggestions:j})),x=iys(s,i),b=x?[x]:[],S=new Set(n);return o?[...[...p,...b].sort(xE),...[...m,...l?[{...f("durationMs"),operators:Hvs}]:[]].sort(xE),...v,...y.sort(xE)].filter(k=>!ENe.has(k.id)).map(k=>S.has(k.id)?{...k,hidden:!0}:k):[...p.sort(xE),...m.sort(xE)].map(k=>({...k,operators:Xvs,...S.has(k.id)?{hidden:!0}:{}}))}function BBt(e){return e.map(t=>({id:t.fieldId,fieldId:t.fieldId,operatorId:FA(t),value:NNe(t.value,FA(t))?"":t.value}))}function UBt(e){return e.map(VBt)}function VBt(e){const t={fieldId:e.fieldId,value:Array.isArray(e.value)?e.value.map(String):String(e.value)};return INe(e.operatorId)&&e.operatorId!==FA(t)&&(t.operatorId=e.operatorId),t}function Iet(e,t){return{logic:"and",nodes:[...BBt(e),...t.map(qBt)]}}function qBt(e){return{id:e.id,kind:"group",logic:e.logic,nodes:e.nodes.map(t=>bye(t)?qBt(t):{id:t.id??t.fieldId,fieldId:t.fieldId,operatorId:FA(t),value:NNe(t.value,FA(t))?"":t.value})}}function ays(e){const t=e.nodes.filter(r=>!qa(r)),n=e.nodes.filter(qa).map(QBt);return{tokens:UBt(t),groups:n}}function QBt(e){const t=e.nodes.map(n=>qa(n)?QBt(n):{id:n.id,...VBt(n)});return{id:e.id,logic:e.logic,nodes:t}}function lys(e){const t=[],n=new Map([[w$,"rootEntityType"],[S$,"status"]]);for(const s of qJ)n.set(yl[s],s);const r=new Set;for(const[s]of e.entries()){if(DBt(s))continue;const i=VJ(s)?Mvs(s):n.get(s);if(!i||r.has(i))continue;r.add(i);const o=wye(e,s),l=e.getAll(s);if(FBt.has(i)&&(o?!LBt(o):l[0]))continue;if(i==="tags"||zvs(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 cys(e){const t=new URLSearchParams,n=i=>{const o=wye(e,i),l=e.getAll(i).filter(c=>c||LBt(o));if(l.length){for(const c of l)t.append(i,c);o&&t.set(sS(i),o)}};n(w$),n(S$);const r=e.get(z1);r&&t.set(z1,r);for(const i of qJ){const o=yl[i];if(i==="tags"){for(const c of e.getAll(o))t.append(o,c);const l=wye(e,o);l&&e.has(o)&&t.set(sS(o),l);continue}n(o)}const s=new Set;for(const i of e.keys())!VJ(i)||DBt(i)||s.has(i)||(s.add(i),n(i));for(const i of RNe(e))t.append(i_,$Ne(i));return t}function Net(e,t,n=[]){for(const r of Object.values(_et))e.delete(r),e.delete(sS(r));e.delete(i_);for(const r of qJ){const s=yl[r];e.delete(s),e.delete(sS(s))}for(const r of Array.from(e.keys()))VJ(r)&&e.delete(r);for(const r of t){const s=RBt(r.fieldId)?Rvs(r.fieldId):_et[r.fieldId]??yl[r.fieldId];if(!s)continue;if(Array.isArray(r.value))if(r.value.length===0)e.append(s,"");else for(const l of r.value)e.append(s,l);else e.set(s,r.value.trim());const i=FA(r),o=r.fieldId==="tags"?"in":"is";i!==o&&e.set(sS(s),i)}for(const r of n)e.append(i_,$Ne(r))}const i_="filterGroup",$Ne=e=>JSON.stringify(e);function RNe(e){return e.getAll(i_).map(uys).filter(t=>t!==void 0)}function uys(e){try{return WBt(JSON.parse(e))}catch{return}}const ZBt=e=>typeof e=="object"&&e!==null,dys=e=>Array.isArray(e)&&e.every(t=>typeof t=="string");function WBt(e){if(!ZBt(e)||typeof e.id!="string"||e.logic!=="and"&&e.logic!=="or"||!Array.isArray(e.nodes))return;const t=e.nodes.map(fys).filter(n=>n!==void 0);return{id:e.id,logic:e.logic,nodes:t}}function fys(e){if(!ZBt(e))return;if("nodes"in e)return WBt(e);if(typeof e.id!="string"||typeof e.fieldId!="string"||typeof e.value!="string"&&!dys(e.value))return;const t={id:e.id,fieldId:e.fieldId,value:e.value};return typeof e.operatorId=="string"&&INe(e.operatorId)&&(t.operatorId=e.operatorId),t}function hys({rootEntityType:e,status:t,dateFrom:n,dateTo:r,tokens:s}){const i={};e&&(i.entityType=e),t&&(i.status=t),n&&(i.startedAt={start:n}),r&&(i.endedAt={end:r});for(const o of s){if(o.fieldId==="tags"){Array.isArray(o.value)&&o.value.length>0?i.tags=o.value:typeof o.value=="string"&&o.value.trim()&&(i.tags=[o.value.trim()]);continue}if(typeof o.value=="string"&&o.value.trim()&&o.value!=="Any")switch(o.fieldId){case"entityId":i.entityId=o.value;break;case"entityName":i.entityName=o.value;break;case"traceId":i.traceId=o.value;break;case"runId":i.runId=o.value;break;case"threadId":i.threadId=o.value;break;case"sessionId":i.sessionId=o.value;break;case"requestId":i.requestId=o.value;break;case"resourceId":i.resourceId=o.value;break;case"userId":i.userId=o.value;break;case"organizationId":i.organizationId=o.value;break;case"serviceName":i.serviceName=o.value;break;case"environment":i.environment=o.value;break;case"experimentId":i.experimentId=o.value;break}}return i}function Hce({value:e,icon:t,label:n}){return a.jsxs(si,{value:e,children:[a.jsx(At,{size:"xs",children:t}),a.jsx(Y,{variant:"caption",className:"text-inherit",children:n})]})}function pys({agentId:e,activeTab:t,threadId:n,showPlayground:r=!1,showObservability:s=!1}){const{navigate:i}=Tn(),o={chat:`/agents/${e}/threads/${n??"new"}`,versions:`/agents/${e}/editor`,traces:n?`/agents/${e}/traces?${new URLSearchParams({[yl.threadId]:n})}`:`/agents/${e}/traces`},l=c=>{c!=="none"&&i(o[c])};return a.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 p-1.5",children:[a.jsx(Wc,{value:t,defaultTab:t,onValueChange:l,className:"min-w-0",children:a.jsxs(Hc,{variant:"pill-ghost",children:[a.jsx(Hce,{value:"chat",icon:a.jsx(dL,{}),label:"Chat"}),s&&a.jsx(Hce,{value:"traces",icon:a.jsx(bx,{}),label:"Traces"}),r&&a.jsx(Hce,{value:"versions",icon:a.jsx(EN,{}),label:"Editor"})]})}),(!s||!r)&&a.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-0.5",children:[!s&&a.jsx(SQ,{icon:a.jsx(bx,{}),label:"Traces",tooltipContent:a.jsxs(a.Fragment,{children:["Add ",a.jsx("code",{children:"@mastra/observability"})," to enable Traces."]}),docsHref:"https://mastra.ai/docs/observability/overview"}),!r&&a.jsx(SQ,{icon:a.jsx(EN,{}),label:"Editor",tooltipContent:"Add @mastra/editor to enable the Editor.",docsHref:"https://mastra.ai/docs/editor/overview"})]})]})}const mys=({agentId:e})=>{const t=Ge(),{data:n=[]}=XL(),r=n.filter(l=>l.isConfigured),s=Mm({queries:r.map(l=>({queryKey:["channels","installations",l.id,e],queryFn:()=>t.channels.listInstallations(l.id,e),staleTime:10*1e3,retry:!1}))}),i=r.flatMap((l,c)=>{const u=s[c]?.data;return!u||u.some(d=>d.status==="active")?[]:[{platform:l,isPending:u.some(d=>d.status==="pending")}]});if(i.length===0)return null;const o=s.some(l=>l.data?.length);return a.jsx(hl,{elevation:"flat","data-testid":"agent-channels-card",children:a.jsxs(qm,{className:"flex flex-col gap-1",children:[a.jsx(nw,{children:o?"Finish connecting your channels":"Connect your channels"}),a.jsx("ul",{className:"divide-y divide-border",children:i.map(({platform:l,isPending:c})=>a.jsx(gys,{platform:l,agentId:e,isPending:c},l.id))})]})})};function gys({platform:e,agentId:t,isPending:n}){const{connect:r,isConnecting:s}=vX(e.id);return z_e({platform:e.id,agentId:t,hasPendingInstall:n}),a.jsxs("li",{className:"flex items-center gap-3 py-2.5",children:[a.jsx(gX,{platform:e.id,className:"h-5 w-5 shrink-0"}),a.jsx(Y,{as:"span",variant:"body",tone:"ink",className:"min-w-0 flex-1 truncate",children:e.name}),n?a.jsx(Mt,{variant:"warning",size:"sm",indicator:"dot",children:"Pending"}):null,a.jsx(ue,{icon:a.jsx(JH,{}),size:"sm",variant:"default",onClick:()=>r(t),disabled:s,children:s?"Connecting...":"Connect"})]})}function Sye(){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(xt,{className:"h-10 w-2/3 rounded-2xl"})}),a.jsx("div",{className:"flex justify-end",children:a.jsx(xt,{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(xt,{className:"h-4 w-full rounded-full"}),a.jsx(xt,{className:"h-4 w-5/6 rounded-full"}),a.jsx(xt,{className:"h-4 w-2/3 rounded-full"})]})})]})}function HBt(){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(Sye,{}),a.jsx(GBt,{})]})})}function GBt(){return a.jsxs("div",{className:"rounded-3xl border border-border bg-background px-3 py-2.5",children:[a.jsx(xt,{className:"h-5 w-1/2 rounded-full"}),a.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[a.jsx(xt,{className:"h-control-md w-24 rounded-full"}),a.jsx(xt,{className:"h-control-md w-control-md rounded-full"})]})]})}function vys(){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(xt,{className:"h-avatar-lg w-avatar-lg rounded-full"}),a.jsx(xt,{className:"h-7 w-2/3 rounded-full"})]}),a.jsx(GBt,{}),a.jsxs("div",{className:"flex flex-col gap-1 px-3",children:[a.jsx(xt,{className:"h-control-md w-2/3 rounded-full"}),a.jsx(xt,{className:"h-control-md w-1/2 rounded-full"}),a.jsx(xt,{className:"h-control-md w-3/5 rounded-full"})]})]})})}const D7=({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 yys(e,t){if(!e||CDt(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 xys({provider:e,modelId:t,settings:n,setSettings:r}){const s=yys(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 bys=({canEdit:e=!0})=>{const{settings:t,setSettings:n}=K_e(),[r,s]=g.useState(""),[i,o]=g.useState(!1),[l,c]=g.useState(null),{handleCopy:u}=Bm({text:r}),d=JSON.stringify(t?.modelSettings?.providerOptions??{});g.useEffect(()=>{(async()=>{if(!wQ(d)){c("Invalid JSON");return}const v=await C5(d);s(v)})()},[d]);const f=async()=>{if(c(null),!wQ(r)){c("Invalid JSON");return}const m=await C5(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(Ln,On);return a.jsx(mc,{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(ht,{children:[a.jsx(ut,{children:"Frequency Penalty"}),a.jsx(wn,{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(ht,{children:[a.jsx(ut,{children:"Presence Penalty"}),a.jsx(wn,{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(ht,{children:[a.jsx(ut,{children:"Top K"}),a.jsx(wn,{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(ht,{children:[a.jsx(ut,{children:"Max Tokens"}),a.jsx(wn,{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(ht,{children:[a.jsx(ut,{children:"Max Steps"}),a.jsx(wn,{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(ht,{children:[a.jsx(ut,{children:"Max Retries"}),a.jsx(wn,{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(ht,{children:[a.jsx(ut,{children:"Seed"}),a.jsx(wn,{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(ht,{invalid:!!l,className:"gap-1",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx(ut,{children:"Provider Options"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:f,className:p,"aria-label":"Format Provider Options",children:a.jsx(At,{children:a.jsx(Ua,{})})})}),a.jsx(Dn,{children:"Format the Provider Options JSON"})]}),a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:u,className:p,"aria-label":"Copy Provider Options",children:a.jsx(At,{children:a.jsx(zm,{})})})}),a.jsx(Dn,{children:"Copy Provider Options"})]}),e&&a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("button",{type:"button",onClick:h,className:p,"aria-label":"Save Provider Options",children:a.jsx(At,{children:i?a.jsx(ur,{}):a.jsx(Fm,{})})})}),a.jsx(Dn,{children:i?"Saved":"Save Provider Options"})]})]})]}),a.jsx(Or,{value:r,onChange:s,language:"json",editable:e,showCopyButton:!1,className:"h-75"}),a.jsx(ns,{children:l})]})]})})},wys=({hasMemory:e,hasSubAgents:t,disabled:n})=>{const r=e&&t,s=n||!r,i=a.jsxs(cm,{disabled:s,children:[a.jsx(Yh,{value:"network",className:"text-foreground"}),a.jsx(ut,{children:"Network"})]});if(r)return i;const o=[];return e||o.push("memory enabled"),t||o.push("at least one sub-agent"),a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:i}),a.jsx(Dn,{children:a.jsxs("p",{children:["Network is not available. Please make sure you have ",o.join(" and "),"."]})})]})},Sys=({supported:e,disabled:t})=>{const n=t||!e,r=a.jsxs(cm,{disabled:n,children:[a.jsx(Yh,{value:"streamSubscription",className:"text-foreground"}),a.jsx(ut,{children:"Stream subscription (default)"})]});return e?r:a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:r}),a.jsx(Dn,{children:a.jsx("p",{children:"Stream subscription is not supported for this agent."})})]})},kys=({agentId:e})=>{const{data:t,isLoading:n}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:r,isLoading:s}=Vk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{settings:i,setSettings:o,resetAll:l}=K_e(),{canEdit:c}=Za(),[u,d]=g.useState(!1),[f,h]=g.useState(!1),p=c("agents"),{hasSamplingRestriction:m}=xys({provider:t?.provider,modelId:t?.modelId,settings:i,setSettings:o});if(!n&&!t)return null;const v=!!r?.result,y=!!(t&&Object.keys(t.agents||{}).length>0),x=t?.modelVersion,b=x==="v2"||x==="v3",S=t?.supportsMemory!==!1;let k;t&&(b?i?.modelSettings?.chatWithNetwork?k="network":i?.modelSettings?.chatWithGenerate?k="generate":i?.modelSettings?.chatWithLegacyStream||!S?k="stream":k="streamSubscription":k=i?.modelSettings?.chatWithGenerateLegacy?"generateLegacy":"streamLegacy");const j=m&&(i?.modelSettings?.temperature!==void 0||i?.modelSettings?.topP!==void 0);return a.jsxs(a.Fragment,{children:[a.jsxs(jp,{open:f,onOpenChange:(C,T)=>{if(!C&&u){T?.cancel?.();return}h(C)},children:[a.jsx(sf,{asChild:!0,children:a.jsx(ue,{variant:"ghost",size:"icon-md",type:"button",tooltip:"Model settings","data-testid":"composer-model-settings-trigger",children:a.jsx(PNn,{})})}),a.jsx(lh,{align:"start",className:"w-80 p-4",children:n||s?a.jsx(xt,{className:"h-40 w-full","data-testid":"composer-model-settings-skeleton"}):a.jsxs("section",{className:"@container space-y-5",children:[a.jsx(D7,{label:"Chat Method",children:a.jsxs(q6,{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(cm,{disabled:!p,children:[a.jsx(Yh,{value:"generateLegacy",className:"text-foreground"}),a.jsx(ut,{children:"Generate (Legacy)"})]}),b&&a.jsxs(cm,{disabled:!p,children:[a.jsx(Yh,{value:"generate",className:"text-foreground"}),a.jsx(ut,{children:"Generate"})]}),!b&&a.jsxs(cm,{disabled:!p,children:[a.jsx(Yh,{value:"streamLegacy",className:"text-foreground"}),a.jsx(ut,{children:"Stream (Legacy)"})]}),b&&a.jsx(Sys,{supported:S,disabled:!p}),b&&a.jsxs(cm,{disabled:!p,children:[a.jsx(Yh,{value:"stream",className:"text-foreground"}),a.jsx(ut,{children:"Stream"})]}),b&&a.jsx(wys,{hasMemory:v,hasSubAgents:y,disabled:!p})]})}),a.jsx(D7,{label:"Require Tool Approval",children:a.jsx(Gc,{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(hp,{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(D7,{label:"Temperature",children:a.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[a.jsx(Pve,{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(D7,{label:"Top P",children:a.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[a.jsx(Pve,{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(ue,{icon:a.jsx(T_,{}),variant:"ghost",size:"sm",type:"button",disabled:!p,onClick:()=>p&&l(),children:"Reset"}),a.jsx(ue,{icon:a.jsx(hL,{}),variant:"default",size:"sm",type:"button",disabled:!p,onClick:()=>d(!0),children:"Advanced Settings"})]})]})})]}),a.jsx(Kr,{open:u,onOpenChange:d,children:a.jsxs(Yr,{size:"lg",children:[a.jsx(Xr,{children:a.jsx(Qr,{children:"Advanced model settings"})}),a.jsx(qr,{children:a.jsx(bys,{canEdit:p})})]})})]})},Oys=()=>{const{data:e}=MP();return{isLiveKitAvailable:e?.liveKitConnectionRouteEnabled!==!1}},jys="/voice/livekit/connection-details",Aet="lk.agent.state",Cys="lk.transcription",_ys="lk.transcription_final";function Tys(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 Eys=({agentId:e,threadId:t,onCallStarted:n})=>{const{baseUrl:r,headers:s}=pL(),{isLiveKitAvailable:i}=Oys(),o=mr(),l=g.useRef(n);g.useEffect(()=>{l.current=n},[n]);const[c,u]=g.useState("idle"),[d,f]=g.useState("initializing"),[h,p]=g.useState([]),m=g.useRef(null),v=g.useRef(null),y=g.useRef(null),x=g.useRef(0),b=g.useRef(null),S=g.useCallback(()=>{t&&o.invalidateQueries({queryKey:["memory","messages",t]}),e&&o.invalidateQueries({queryKey:["memory","threads",e,e]})},[e,o,t]),k=g.useCallback(()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{y.current=null,S()},600)},[S]),j=g.useCallback(()=>{x.current+=1,b.current?.abort(),b.current=null;const _=m.current;m.current=null,_&&_.disconnect(),y.current&&(clearTimeout(y.current),y.current=null),v.current=null,u("idle"),f("initializing")},[]);g.useEffect(()=>j,[j]);const C=g.useCallback(()=>{j(),p([]),S()},[j,S]),T=g.useCallback(async()=>{if(c!=="idle"||!i)return;const _=x.current+=1,N=new AbortController;b.current=N;const I=()=>x.current!==_;u("connecting"),p([]);try{const A=await fetch(`${r}${jys}`,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify({agentId:e,threadId:t,resourceId:e}),signal:N.signal});if(I())return;if(!A.ok){const V=await A.json().catch(()=>({}));throw new Error(V.error??"LiveKit voice is not configured for this server. Add liveKitConnectionRoute() to server.apiRoutes and run a voice worker.")}const P=await A.json();if(I())return;const{Room:L,RoomEvent:F,Track:Q}=await Ai(async()=>{const{Room:V,RoomEvent:H,Track:D}=await import("./livekit-client.esm-CKIgC2IJ.js");return{Room:V,RoomEvent:H,Track:D}},[],import.meta.url);if(I())return;const q=new L;m.current=q;const B=new Audio;if(B.autoplay=!0,v.current=B,q.on(F.TrackSubscribed,V=>{V.kind===Q.Kind.Audio&&v.current&&V.attach(v.current)}),q.on(F.ParticipantAttributesChanged,(V,H)=>{const D=V[Aet]??H.attributes[Aet];D&&H.identity!==P.participantName&&f(D)}),q.on(F.Disconnected,()=>{m.current===q&&j()}),q.registerTextStreamHandler(Cys,async(V,H)=>{const D=H.identity===P.participantName?"user":"agent",K=V.info.attributes?.[_ys]==="true";for await(const M of V)p($=>Tys($,V.info.id,D,M,K));D==="agent"&&k()}),await q.connect(P.serverUrl,P.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(A){if(N.signal.aborted||I())return;j(),ku.error(A instanceof Error?A.message:"Failed to start the voice call.")}},[e,r,j,s,i,S,k,c,t]);return{status:c,agentState:d,captions:h,isLiveKitAvailable:i,start:()=>{T()},stop:C}},Iys=({voiceCall:e})=>{const{isLiveKitAvailable:t}=e;return e.status==="idle"?a.jsx(ue,{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(FIn,{})}):e.status==="connecting"?a.jsx(ue,{variant:"ghost",size:"icon-md",type:"button",tooltip:"Connecting…","data-testid":"voice-call-button",children:a.jsx(fc,{className:"animate-spin"})}):a.jsx(ue,{variant:"destructive-ghost",size:"icon-md",type:"button",tooltip:"End voice call","data-testid":"voice-call-button",onClick:()=>e.stop(),children:a.jsx(LIn,{})})},Nys={initializing:"Connecting…",listening:"Listening…",thinking:"Thinking…",speaking:"Speaking…"},Pet=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(e[n]?.role===t)return e[n]},Ays=({voiceCall:e})=>{if(e.status==="idle")return null;const t=Pet(e.captions,"user"),n=Pet(e.captions,"agent"),r=e.status==="connecting"?"Connecting…":Nys[e.agentState];return a.jsxs("div",{"data-testid":"voice-call-panel",className:Z(pr,"mx-auto mb-2 w-full max-w-3xl rounded-[16px] px-4 py-3"),children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:Z("h-2 w-2 rounded-full",e.status==="connecting"&&"bg-muted-foreground",e.status==="active"&&e.agentState==="speaking"&&"animate-pulse bg-success-indicator",e.status==="active"&&e.agentState!=="speaking"&&"bg-success-indicator")}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:r})]}),t&&a.jsx(Y,{variant:"caption",tone:"muted",className:"mt-2 truncate","data-testid":"voice-caption-user",children:t.text}),n&&a.jsx(Y,{variant:"caption",tone:"ink",className:"mt-1","data-testid":"voice-caption-agent",children:n.text})]})},Pys=300,$ys=[],Rys=(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},Mys=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,Dys=({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(uJr,{turns:e,className:"pointer-events-auto sticky top-1/2 -translate-y-1/2"})}),Lys=({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}=rNe(n),m=sXr(),{isRunning:v}=d$(),[y]=xr("agent",t??""),{isSpeaking:x,readAloud:b,stop:S}=Kls(t,y,{onError:B=>ku.error(B instanceof Error?B.message:"Voice generation failed.")}),{hasSession:k,viewMode:j}=z6(),C=k&&(j==="collapsed"||j==="expanded"),T=m.length===0,_=m[m.length-1],N=v&&(_?.role!=="assistant"||!Mys(_)),I=Rys(N,Pys),A=g.useMemo(()=>kJr(m),[m]),P=g.useMemo(()=>new Set(A.map(B=>B.messageId)),[A]),L=jJr(m,{key:_ve,opensTurn:B=>P.has(B.id)}),F=T&&!c,[Q,q]=g.useState(F);return g.useEffect(()=>{if(Q!==F){if(F||!v){q(F);return}xp(()=>q(!1))}},[F,Q,v]),a.jsx(rcs,{controlled:h&&p?{value:h.attachments,onChange:B=>p(V=>({...V,attachments:typeof B=="function"?B(V.attachments):B}))}:void 0,children:a.jsx(Pg,{className:"h-full",scroller:{autoScroll:!0,defaultScrollPosition:"last-anchor",onReachStart:u,preserveScrollOnPrepend:!!u},"data-testid":"thread-wrapper",children:a.jsx(Pg.Stage,{children:a.jsxs(Pg.Viewport,{style:{overflowAnchor:"none"},children:[a.jsx(Dys,{turns:A}),a.jsxs(Pg.Content,{className:Q?"flex-none":void 0,children:[d&&a.jsx(Pg.Column,{"data-testid":"thread-history-older-skeleton","aria-busy":"true","aria-label":"Loading older messages",className:"py-3",children:a.jsx(Sye,{})}),T&&c?a.jsx(Pg.Column,{"data-testid":"thread-history-skeleton","aria-busy":"true",className:"flex-1 py-4",children:a.jsx(Sye,{})}):Q?null:a.jsxs(Pg.Column,{ref:f,"data-testid":"thread-message-column",className:"relative flex-1 gap-4 py-4",children:[a.jsx(Ccs,{containerRef:f}),a.jsx(s4t,{children:L.map((B,V)=>{const H=V===L.length-1,D=H&&v&&B.opensTurn&&V>0;return a.jsxs(Pg.Turn,{opensTurn:B.opensTurn,holdsRoom:D,className:"gap-4",children:[B.entries.map(K=>a.jsx(cTe,{messageId:K.id,scrollAnchor:P.has(K.id),children:a.jsx(Gve,{message:K,hasModelList:s,isSpeaking:x,onReadAloud:b,onStopSpeaking:S})},_ve(K))),H&&I&&a.jsx(nve,{})]},B.key)})}),!v&&a.jsx(NJr,{})]})]}),a.jsxs(Pg.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(Pg.ScrollButton,{}),a.jsxs(Pg.Column,{className:Q?"gap-6 px-1 md:px-1":"gap-2 px-1 md:px-1",children:[Q?a.jsxs(a.Fragment,{children:[a.jsx(zys,{agentName:e}),t?a.jsx(mys,{agentId:t}):null]}):a.jsxs(a.Fragment,{children:[C&&t&&n&&a.jsx(lDt,{agentName:e}),a.jsx(aus,{})]}),a.jsx("div",{className:Q?"starter-prompt":void 0,children:a.jsx(Fys,{agentId:t,threadId:n,hasModelList:s,hideModelSwitcher:i,runOptionsSlot:o,refreshThreadList:l})}),Q?a.jsx(Pcs,{prompts:r??$ys}):null]})]})]})})})})},zys=({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(KS,{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?"]})]}),Fys=({agentId:e,threadId:t,hasModelList:n,hideModelSwitcher:r,runOptionsSlot:s,refreshThreadList:i})=>{const{threadInput:o,setThreadInput:l,updateDraft:c,draftStatus:u}=rNe(t),d=g.useRef(null),f=g.useRef(!1),h=g.useRef(0);g.useEffect(()=>()=>{h.current++},[]);const[p,m]=g.useState(),v=X_e(),{attachments:y,toCoreUserMessages:x,clear:b,restore:S,isAddingAttachments:k}=kz(),{isRunning:j,canSendWhileStreaming:C,cancelRun:T}=d$(),[_,N]=g.useState(0),{canExecute:I}=Za(),A=I("agents"),P=!A||!!u?.restoring;Ics(d,{threadId:t,disabled:P});const L=Eys({agentId:e,threadId:t,onCallStarted:i}),F=o.trim().length===0&&y.length===0,Q=j&&!C,q=async()=>{if(F||Q||!A||u?.restoring||k||f.current)return;f.current=!0;const B=h.current,V=y,H=new Set(V.map(M=>M.id)),D=M=>M?`${o}
|
|
674
674
|
|
|
675
|
-
${M}`:o,K=()=>{h.current===B&&(c?c(M=>({text:D(M.text),attachments:[...V,...M.attachments]})):(l(D),S(V)),m("Your message could not be sent. Your draft has been restored."))};m(void 0);try{const M=y.length>0?await x():void 0;if(h.current!==B)return;c?c($=>({text:$.text===o?"":$.text,attachments:$.attachments.filter(z=>!H.has(z.id))})):(l(""),b()),N($=>$+1),Promise.resolve(v({message:o,attachments:M})).then($=>{$===!1&&K()})}catch{h.current===B&&m("Attachments could not be prepared. Your draft has been kept.")}finally{f.current=!1}};return a.jsxs("div",{className:"relative",style:{viewTransitionName:"agent-chat-composer"},children:[a.jsx(Ays,{voiceCall:L}),(p||u?.error)&&a.jsx(Y,{variant:"caption",role:"alert",children:p||u?.error}),u?.restoring&&a.jsx(Y,{variant:"caption",role:"status",className:"sr-only",children:"Restoring draft…"}),a.jsx(jcs,{disabled:!A||u?.restoring,children:a.jsx(d4t,{className:"relative",onSubmit:B=>{B.preventDefault(),q()},children:a.jsx(h4t,{busy:j,children:a.jsxs(f4t,{sendingPulseKey:_,children:[a.jsx(wcs,{}),a.jsx(m4t,{ref:d,value:o,placeholder:A?"Enter your message...":"You don't have permission to execute agents",onChange:B=>{l(B.target.value)},onKeyDown:B=>{if(!(B.nativeEvent.isComposing||B.keyCode===229)&&B.key==="Enter"&&!B.shiftKey){if(Q)return;B.preventDefault(),B.stopPropagation(),q()}},disabled:P}),e&&!n&&!r&&a.jsx(Ahs,{}),a.jsx(g4t,{children:a.jsx(Uys,{canExecute:A,agentId:e,runOptionsSlot:s,showModelSwitcher:!!(e&&!n&&!r),isEmpty:F,isRunning:j,canSendWhileStreaming:C,onCancel:()=>{T()},onSetText:B=>{l(B)},voiceCall:L})})]})})})})]})},Bys=({agentId:e,onTranscript:t})=>{const[n]=xr("agent",e??""),{start:r,stop:s,isListening:i,transcript:o}=j0n({agentId:e,requestContext:n});return g.useEffect(()=>{o&&g.startTransition(()=>t(o))},[t,o]),a.jsx(ue,{variant:"ghost",size:"icon-md",type:"button",tooltip:i?"Stop dictation":"Start dictation",onClick:()=>i?s():r(),children:i?a.jsx(kye,{}):a.jsx(iIn,{})})},Uys=({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(Nhs,{}),a.jsx(kys,{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(scs,{}),e&&a.jsx(Bys,{agentId:t,onTranscript:c}),e&&t&&u&&a.jsx(Iys,{voiceCall:u})]}),a.jsx(Vys,{canExecute:e,isEmpty:s,isRunning:i,canSendWhileStreaming:o,onCancel:l})]})]}),Vys=({canExecute:e=!0,isEmpty:t,isRunning:n,canSendWhileStreaming:r,onCancel:s})=>{const{isAddingAttachments:i}=kz();return n&&!r?a.jsx(ue,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:a.jsx(kye,{})}):a.jsxs(a.Fragment,{children:[a.jsx(ue,{type:"submit",variant:"default",size:"icon-md",tooltip:e?"Send":"No permission to execute",disabled:!e||t||i,children:a.jsx(vk,{})}),n&&a.jsx(ue,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:a.jsx(kye,{})})]})},kye=()=>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:Ln,children:[a.jsx("circle",{cx:"12",cy:"12",r:"10"}),a.jsx("rect",{width:"6",height:"6",x:"9",y:"9",rx:"1"})]}),MNe=({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}=K_e(),v=xr("agent",e)[0],{data:y,isLoading:x,fetchNextPage:b,hasNextPage:S,isFetchingNextPage:k}=SK({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(TXr,{agentId:e,agentName:t,modelVersion:i,agentVersionId:o,supportsMemory:l,threadId:n,initialMessages:C,refreshThreadList:s,settings:m,requestContext:v,children:a.jsx(Lys,{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 SW(){return a.jsx(Xt,{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(ue,{onClick:()=>window.location.reload(),children:"Reload"}),a.jsx(ue,{render:a.jsx(ac,{to:"/agents"}),children:"Choose agent"})]})})}function $et(){const{agentId:e,threadId:t}=jr(),[n]=ci(),{data:r,isLoading:s,error:i}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:o}=Vk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),l=Dr(),c=t==="new",u=g.useMemo(()=>Sa(),[t]),d=!!o?.result,{refetch:f}=W_e({resourceId:e,agentId:e,isMemoryEnabled:d,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!d}});g.useEffect(()=>{d&&(t||l(`/agents/${e}/session/new`))},[d,t,e,l]);const h=n.get("messageId")??void 0,p=g.useMemo(()=>wNe(r),[r]);if(i&&Cs(i))return a.jsx(ui,{variant:"fill"});if(i&&_s(i))return a.jsx(Gs,{variant:"fill",resource:"agents"});if(s)return a.jsx(qys,{});if(i&&Ik(i))return a.jsx(SW,{});if(i)return a.jsx(Xt,{tone:"error",titleSlot:"Failed to load agent",descriptionSlot:i.message});if(!r)return a.jsx(SW,{});const m=c?u:t??u,v=async()=>{await f(),c&&l(`/agents/${e}/session/${u}`)};return a.jsx(zDt,{agentId:e,defaultSettings:p,children:a.jsx(YDt,{agentId:e,threadId:m,resourceId:e,children:a.jsx(yX,{children:a.jsx(xX,{agentId:e,threadId:m,enabled:!!(r?.hasBrowser??r?.browserTools?.length),children:a.jsx(nNe,{children:a.jsx(e4t,{children:a.jsx(SX,{children:a.jsxs(It,{variant:"fit",children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(LDt,{}),a.jsx("div",{className:"relative grid h-full min-h-0",children:a.jsx(MNe,{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(SNe,{agentId:e})},m)})]})})})})},`session-${e}-${m}`)},`browser-${e}-${m}`)})})}const qys=()=>a.jsxs(It,{variant:"fit",children:[a.jsx("h1",{className:"sr-only",children:"Agent session"}),a.jsx(LDt,{}),a.jsx("div",{className:"relative grid h-full overflow-y-auto pt-4","data-testid":"agent-session-skeleton","aria-busy":"true",children:a.jsx(HBt,{})})]}),Qys={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"}},XI=e=>e?Object.keys(e).length:0,QJ=e=>e>0?String(e):"Off",KBt=e=>(e?.inputProcessors?.length??0)+(e?.outputProcessors?.length??0),YBt=e=>!!e?.result,XBt=(e,t)=>!!(t&&e&&e.editor!==!1);function k$({view:e,label:t,status:n,description:r,docsHref:s,enabled:i,tone:o,icon:l}){const c=Qys[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",ji,Ln,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(Zs,{className:Z("mt-0.5 size-3 shrink-0 text-muted-foreground group-hover/capability-row:text-foreground",On)})]})}function Ret({agentId:e,view:t}){const{data:n,isLoading:r}=Vk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=YBt(n),i=s?n?.memoryType==="gateway"?"Gateway":"On":"Off",o=r?"Checking":i;return a.jsx(k$,{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(u$,{})})}function Met({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{isCmsAvailable:s,isLoading:i}=Wx(),o=XBt(n,s),l=n?.editor===!1,c=YL({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(k$,{view:t,label:"Editor",status:p,description:v,docsHref:"https://mastra.ai/docs/editor/overview",enabled:o,tone:"amber",icon:a.jsx(Bc,{})})}function Det({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=XI(n?.tools);return a.jsx(k$,{view:t,label:"Tools",status:r?"Checking":QJ(s),description:s>0?`${s} tool${s===1?"":"s"} available.`:"No tools are configured.",docsHref:"https://mastra.ai/docs/agents/using-tools-and-mcp",enabled:s>0,tone:"emerald",icon:a.jsx(dd,{})})}function Let({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=XI(n?.workflows);return a.jsx(k$,{view:t,label:"Workflows",status:r?"Checking":QJ(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(yk,{})})}function zet({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=XI(n?.agents);return a.jsx(k$,{view:t,label:"Sub-agents",status:r?"Checking":QJ(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(K0e,{})})}function Fet({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=KBt(n);return a.jsx(k$,{view:t,label:"Processors",status:r?"Checking":QJ(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(spt,{})})}function Zys({agentId:e}){const{data:t}=Vk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:n}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{isCmsAvailable:r}=Wx(),s=[YBt(t),XBt(n,r),XI(n?.tools)>0,XI(n?.workflows)>0,XI(n?.agents)>0,KBt(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 Wys({agentId:e}){const[t,n]=g.useState(!1);return a.jsx(gc,{open:t,onOpenChange:n,children:a.jsxs("div",{className:"shrink-0 border-t border-border",children:[a.jsx(Hl,{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",Ix,Ln,On),children:[a.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden",children:[a.jsx(Ret,{agentId:e,view:"chip"}),a.jsx(Met,{agentId:e,view:"chip"}),a.jsx(Det,{agentId:e,view:"chip"}),a.jsx(Let,{agentId:e,view:"chip"}),a.jsx(zet,{agentId:e,view:"chip"}),a.jsx(Fet,{agentId:e,view:"chip"})]}),a.jsx(Zys,{agentId:e}),a.jsx(Ha,{direction:"right",className:"size-3.5 text-muted-foreground"})]})}),a.jsx(Gl,{className:"px-2 pb-2",children:a.jsxs("div",{className:"grid gap-1",children:[a.jsx(Ret,{agentId:e,view:"row"}),a.jsx(Met,{agentId:e,view:"row"}),a.jsx(Det,{agentId:e,view:"row"}),a.jsx(Let,{agentId:e,view:"row"}),a.jsx(zet,{agentId:e,view:"row"}),a.jsx(Fet,{agentId:e,view:"row"})]})})]})})}function Hys(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 Gys(e){return typeof e=="object"&&e!==null&&"parts"in e&&Array.isArray(e.parts)}function Kys(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 Yys(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 Xys(e){const t=[];for(const n of e){const r=Hys(n.content);if(Gys(r))for(const s of r.parts)Kys(s)&&t.push(Yys(s,new Date(n.createdAt).toISOString()))}return t.sort((n,r)=>n.timestamp.localeCompare(r.timestamp)),t}function BA(e){return/[Zz+-]\d{0,4}$/.test(e.trim())?new Date(e).getTime():new Date(e.trim().replace(" ","T")+"Z").getTime()}function Jys(e){if(e.length===0)return{tMin:0,tMax:1};let t=1/0,n=-1/0;for(const r of e){const s=BA(r);s<t&&(t=s),s>n&&(n=s)}return t===n?{tMin:t,tMax:t+1}:{tMin:t,tMax:n}}function Nz(e,t){return(BA(e)-t.tMin)/(t.tMax-t.tMin)}function DNe(e,t){return new Date(t.tMin+e*(t.tMax-t.tMin))}function exs(e,t){return DNe(e,t).getTime()}function JBt(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function txs(e){return BA(JBt(e))}function nxs(e,t){if(t==null)return null;const r=e.map(s=>({id:s.id,t:BA(JBt(s))})).toSorted((s,i)=>s.t-i.t).findLast(s=>s.t<=t);return r?r.id:null}function Bet(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function rxs(e){return[...e].sort((t,n)=>BA(Bet(t))-BA(Bet(n)))}function sxs({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=rxs(t).at(-1);return{messageTokens:s?.pendingTokens??i?.pendingMessageTokens,messageThreshold:s?.observationThreshold??n,memoryTokens:s?.observationTokens??i?.observationTokenCount,memoryThreshold:s?.reflectionThreshold??r}}function LD(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function ixs(e,t,n){const r=e.map(i=>({ts:String(LD(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:Nz(i.ts,n),pendingMessageTokens:i.pendingMessageTokens}))}function oxs(e,t,n){const r=[...e.map(i=>({ts:String(LD(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:Nz(i.ts,n),observationTokenCount:s}))}function axs(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:Nz(s.ts,t),bufferedObservationTokenCount:r}))}function lxs(e,t){return[...e].sort((n,r)=>String(LD(n)).localeCompare(String(LD(r)))).map(n=>({t:Nz(String(LD(n)),t),event:1}))}function cxs(e,t){return[...e].sort((n,r)=>new Date(n.createdAt).getTime()-new Date(r.createdAt).getTime()).map(n=>({t:Nz(new Date(n.createdAt).toISOString(),t),event:1,role:n.role}))}function uxs(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 dxs(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 fxs(e){return e==null?null:Number(e)}function hxs(e){return!!e?.event}const pxs="var(--chart-green)",mxs="var(--chart-amber)",Uet="var(--chart-pink)";function gxs({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:Jr(DNe(n,e),"date-time-seconds",{timeZone:"UTC"})},n))})]})}function LNe({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?Jr(DNe(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:`${nh} 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:`${nh} rounded px-2 py-1`,children:i&&a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"ink",children:i})})}function vxs({label:e,data:t,dataKey:n,color:r,gradientId:s,domain:i,zoomDomain:o,threshold:l}){const c=dxs(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(cA,{width:"100%",height:32,children:a.jsxs(vMr,{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(C6,{dataKey:"t",type:"number",domain:o,allowDataOverflow:!0,hide:!0}),a.jsx(_6,{type:"number",domain:c!=null?[0,c]:void 0,hide:!0}),a.jsx(w6,{content:a.jsx(LNe,{domain:i,showValue:!0}),cursor:{stroke:"var(--border)"}}),a.jsx(zY,{type:"linear",dataKey:n,stroke:r,strokeWidth:1,fill:`url(#${s})`,isAnimationActive:!1}),l!=null&&a.jsx(DY,{y:l,stroke:"var(--border-strong)",strokeDasharray:"4 3"})]})})})]})}function yxs({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(cA,{width:"100%",height:r,children:a.jsxs(mMr,{margin:{top:0,right:0,bottom:0,left:0},children:[a.jsx(C6,{dataKey:"t",type:"number",domain:i,allowDataOverflow:!0,hide:!0}),a.jsx(_6,{dataKey:"event",type:"number",domain:[0,2],hide:!0}),a.jsx(w6,{content:a.jsx(LNe,{domain:s}),cursor:!1}),a.jsx(_Nt,{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 Vet({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=uxs(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(cA,{width:"100%",height:u,children:a.jsxs(aCe,{margin:{top:0,right:0,bottom:0,left:0},onClick:h=>{const p=fxs(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(C6,{dataKey:"t",type:"number",domain:l,allowDataOverflow:!0,hide:!0}),a.jsx(_6,{yAxisId:"area",dataKey:n,type:"number",hide:!0,domain:[0,"dataMax"]}),a.jsx(w6,{content:a.jsx(LNe,{domain:o,showValue:!0}),cursor:!1}),a.jsx(zY,{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=>hxs(h.payload)?a.jsx("circle",{cx:h.cx,cy:h.cy,r:4,fill:s}):a.jsx(a.Fragment,{})}),c!=null&&a.jsx(DY,{yAxisId:"area",y:c,stroke:"var(--border-strong)",strokeDasharray:"4 3"})]})})})]})}function xxs({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(ue,{variant:"ghost",size:"icon-sm","aria-label":"Reset zoom",onClick:i,children:a.jsx(T_,{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 bxs={tMin:0,tMax:1};function wxs({omRecords:e,markers:t,messages:n,tDomain:r,observationThreshold:s,reflectionThreshold:i,onSelectTimestamp:o,zoomRange:l,onZoomRangeChange:c}){const u=r??bxs,d=g.useCallback(Q=>{o?.(exs(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(()=>cxs(n,u),[n,u]),I=g.useMemo(()=>ixs(e,t,u),[e,t,u]),A=g.useMemo(()=>oxs(e,t,u),[e,t,u]),P=g.useMemo(()=>axs(t,u),[t,u]),L=g.useMemo(()=>lxs(e,u),[e,u]);return N.length>0||I.length>0||A.length>0||L.length>0?a.jsxs("div",{className:"flex flex-col pr-2 pb-2 [&_.recharts-surface]:outline-none",children:[a.jsx(Vet,{label:"Messages",areaData:I,areaDataKey:"pendingMessageTokens",eventData:N,color:pxs,gradientId:"grad-messages",domain:u,zoomDomain:_,threshold:s,onSelectT:o?d:void 0}),a.jsx(Vet,{label:"Observations",areaData:A,areaDataKey:"observationTokenCount",eventData:L,color:mxs,gradientId:"grad-observations",domain:u,zoomDomain:_,threshold:i,onSelectT:o?d:void 0}),P.length>0&&a.jsx(vxs,{label:"Buffered obs",data:P,dataKey:"bufferedObservationTokenCount",color:Uet,gradientId:"grad-buffered-obs",domain:u,zoomDomain:_,threshold:i}),L.length>0&&a.jsx(yxs,{label:"Events",data:L,color:Uet,domain:u,zoomDomain:_}),a.jsx(gxs,{domain:u}),a.jsx(xxs,{tDomain:u,zoomLeft:y,zoomRight:x,onZoomLeftChange:b,onZoomRightChange:S,onReset:k})]}):null}const Sxs=g.lazy(()=>Ai(async()=>{const{CodeDiff:e}=await import("./CodeDiff.es-D-3pK78A.js");return{CodeDiff:e}},__vite__mapDeps([9,4,1,3]),import.meta.url).then(({CodeDiff:e})=>({default:e})));function kxs(e){if(!e)return null;const t=e.match(/^(\d{1,2}):(\d{2})$/);if(!t)return e;const[,n,r]=t;return Jr(new Date(2e3,0,1,Number(n),Number(r)),"time")??e}function Oxs(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=Bve[e];return{card:n.card,text:"text-foreground",time:n.time}}function jxs(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(Fve))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 Cxs(e){const t="<observations>",n=e.indexOf(t),r=n===-1?-1:e.indexOf("</observations>",n+t.length),s=(r===-1?e:e.slice(n+t.length,r)).trim();if(!s)return[];const i=s.split(`
|
|
675
|
+
${M}`:o,K=()=>{h.current===B&&(c?c(M=>({text:D(M.text),attachments:[...V,...M.attachments]})):(l(D),S(V)),m("Your message could not be sent. Your draft has been restored."))};m(void 0);try{const M=y.length>0?await x():void 0;if(h.current!==B)return;c?c($=>({text:$.text===o?"":$.text,attachments:$.attachments.filter(z=>!H.has(z.id))})):(l(""),b()),N($=>$+1),Promise.resolve(v({message:o,attachments:M})).then($=>{$===!1&&K()})}catch{h.current===B&&m("Attachments could not be prepared. Your draft has been kept.")}finally{f.current=!1}};return a.jsxs("div",{className:"relative",style:{viewTransitionName:"agent-chat-composer"},children:[a.jsx(Ays,{voiceCall:L}),(p||u?.error)&&a.jsx(Y,{variant:"caption",role:"alert",children:p||u?.error}),u?.restoring&&a.jsx(Y,{variant:"caption",role:"status",className:"sr-only",children:"Restoring draft…"}),a.jsx(jcs,{disabled:!A||u?.restoring,children:a.jsx(d4t,{className:"relative",onSubmit:B=>{B.preventDefault(),q()},children:a.jsx(h4t,{busy:j,children:a.jsxs(f4t,{sendingPulseKey:_,children:[a.jsx(wcs,{}),a.jsx(m4t,{ref:d,value:o,placeholder:A?"Enter your message...":"You don't have permission to execute agents",onChange:B=>{l(B.target.value)},onKeyDown:B=>{if(!(B.nativeEvent.isComposing||B.keyCode===229)&&B.key==="Enter"&&!B.shiftKey){if(Q)return;B.preventDefault(),B.stopPropagation(),q()}},disabled:P}),e&&!n&&!r&&a.jsx(Ahs,{}),a.jsx(g4t,{children:a.jsx(Uys,{canExecute:A,agentId:e,runOptionsSlot:s,showModelSwitcher:!!(e&&!n&&!r),isEmpty:F,isRunning:j,canSendWhileStreaming:C,onCancel:()=>{T()},onSetText:B=>{l(B)},voiceCall:L})})]})})})})]})},Bys=({agentId:e,onTranscript:t})=>{const[n]=xr("agent",e??""),{start:r,stop:s,isListening:i,transcript:o}=j0n({agentId:e,requestContext:n});return g.useEffect(()=>{o&&g.startTransition(()=>t(o))},[t,o]),a.jsx(ue,{variant:"ghost",size:"icon-md",type:"button",tooltip:i?"Stop dictation":"Start dictation",onClick:()=>i?s():r(),children:i?a.jsx(kye,{}):a.jsx(iIn,{})})},Uys=({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(Nhs,{}),a.jsx(kys,{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(scs,{}),e&&a.jsx(Bys,{agentId:t,onTranscript:c}),e&&t&&u&&a.jsx(Iys,{voiceCall:u})]}),a.jsx(Vys,{canExecute:e,isEmpty:s,isRunning:i,canSendWhileStreaming:o,onCancel:l})]})]}),Vys=({canExecute:e=!0,isEmpty:t,isRunning:n,canSendWhileStreaming:r,onCancel:s})=>{const{isAddingAttachments:i}=kz();return n&&!r?a.jsx(ue,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:a.jsx(kye,{})}):a.jsxs(a.Fragment,{children:[a.jsx(ue,{type:"submit",variant:"default",size:"icon-md",tooltip:e?"Send":"No permission to execute",disabled:!e||t||i,children:a.jsx(vk,{})}),n&&a.jsx(ue,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:a.jsx(kye,{})})]})},kye=()=>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:Ln,children:[a.jsx("circle",{cx:"12",cy:"12",r:"10"}),a.jsx("rect",{width:"6",height:"6",x:"9",y:"9",rx:"1"})]}),MNe=({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}=K_e(),v=xr("agent",e)[0],{data:y,isLoading:x,fetchNextPage:b,hasNextPage:S,isFetchingNextPage:k}=SK({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(TXr,{agentId:e,agentName:t,modelVersion:i,agentVersionId:o,supportsMemory:l,threadId:n,initialMessages:C,refreshThreadList:s,settings:m,requestContext:v,children:a.jsx(Lys,{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 SW(){return a.jsx(Xt,{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(ue,{onClick:()=>window.location.reload(),children:"Reload"}),a.jsx(ue,{render:a.jsx(ac,{to:"/agents"}),children:"Choose agent"})]})})}function $et(){const{agentId:e,threadId:t}=jr(),[n]=ci(),{data:r,isLoading:s,error:i}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:o}=Vk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),l=Dr(),c=t==="new",u=g.useMemo(()=>Sa(),[t]),d=!!o?.result,{refetch:f}=W_e({resourceId:e,agentId:e,isMemoryEnabled:d,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!d}});g.useEffect(()=>{d&&(t||l(`/agents/${e}/session/new`))},[d,t,e,l]);const h=n.get("messageId")??void 0,p=g.useMemo(()=>wNe(r),[r]);if(i&&Cs(i))return a.jsx(ui,{variant:"fill"});if(i&&_s(i))return a.jsx(Gs,{variant:"fill",resource:"agents"});if(s)return a.jsx(qys,{});if(i&&Ik(i))return a.jsx(SW,{});if(i)return a.jsx(Xt,{tone:"error",titleSlot:"Failed to load agent",descriptionSlot:i.message});if(!r)return a.jsx(SW,{});const m=c?u:t??u,v=async()=>{await f(),c&&l(`/agents/${e}/session/${u}`)};return a.jsx(zDt,{agentId:e,defaultSettings:p,children:a.jsx(YDt,{agentId:e,threadId:m,resourceId:e,children:a.jsx(yX,{children:a.jsx(xX,{agentId:e,threadId:m,enabled:!!(r?.hasBrowser??r?.browserTools?.length),children:a.jsx(nNe,{children:a.jsx(e4t,{children:a.jsx(SX,{children:a.jsxs(It,{variant:"fit",children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(LDt,{}),a.jsx("div",{className:"relative grid h-full min-h-0",children:a.jsx(MNe,{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(SNe,{agentId:e})},m)})]})})})})},`session-${e}-${m}`)},`browser-${e}-${m}`)})})}const qys=()=>a.jsxs(It,{variant:"fit",children:[a.jsx("h1",{className:"sr-only",children:"Agent session"}),a.jsx(LDt,{}),a.jsx("div",{className:"relative grid h-full overflow-y-auto pt-4","data-testid":"agent-session-skeleton","aria-busy":"true",children:a.jsx(HBt,{})})]}),Qys={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"}},XI=e=>e?Object.keys(e).length:0,QJ=e=>e>0?String(e):"Off",KBt=e=>(e?.inputProcessors?.length??0)+(e?.outputProcessors?.length??0),YBt=e=>!!e?.result,XBt=(e,t)=>!!(t&&e&&e.editor!==!1);function k$({view:e,label:t,status:n,description:r,docsHref:s,enabled:i,tone:o,icon:l}){const c=Qys[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",ji,Ln,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(Zs,{className:Z("mt-0.5 size-3 shrink-0 text-muted-foreground group-hover/capability-row:text-foreground",On)})]})}function Ret({agentId:e,view:t}){const{data:n,isLoading:r}=Vk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=YBt(n),i=s?n?.memoryType==="gateway"?"Gateway":"On":"Off",o=r?"Checking":i;return a.jsx(k$,{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(u$,{})})}function Met({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{isCmsAvailable:s,isLoading:i}=Wx(),o=XBt(n,s),l=n?.editor===!1,c=YL({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(k$,{view:t,label:"Editor",status:p,description:v,docsHref:"https://mastra.ai/docs/editor/overview",enabled:o,tone:"amber",icon:a.jsx(Bc,{})})}function Det({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=XI(n?.tools);return a.jsx(k$,{view:t,label:"Tools",status:r?"Checking":QJ(s),description:s>0?`${s} tool${s===1?"":"s"} available.`:"No tools are configured.",docsHref:"https://mastra.ai/docs/agents/using-tools-and-mcp",enabled:s>0,tone:"emerald",icon:a.jsx(dd,{})})}function Let({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=XI(n?.workflows);return a.jsx(k$,{view:t,label:"Workflows",status:r?"Checking":QJ(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(yk,{})})}function zet({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=XI(n?.agents);return a.jsx(k$,{view:t,label:"Sub-agents",status:r?"Checking":QJ(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(K0e,{})})}function Fet({agentId:e,view:t}){const{data:n,isLoading:r}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),s=KBt(n);return a.jsx(k$,{view:t,label:"Processors",status:r?"Checking":QJ(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(spt,{})})}function Zys({agentId:e}){const{data:t}=Vk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:n}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{isCmsAvailable:r}=Wx(),s=[YBt(t),XBt(n,r),XI(n?.tools)>0,XI(n?.workflows)>0,XI(n?.agents)>0,KBt(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 Wys({agentId:e}){const[t,n]=g.useState(!1);return a.jsx(gc,{open:t,onOpenChange:n,children:a.jsxs("div",{className:"shrink-0 border-t border-border",children:[a.jsx(Hl,{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",Ix,Ln,On),children:[a.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden",children:[a.jsx(Ret,{agentId:e,view:"chip"}),a.jsx(Met,{agentId:e,view:"chip"}),a.jsx(Det,{agentId:e,view:"chip"}),a.jsx(Let,{agentId:e,view:"chip"}),a.jsx(zet,{agentId:e,view:"chip"}),a.jsx(Fet,{agentId:e,view:"chip"})]}),a.jsx(Zys,{agentId:e}),a.jsx(Ha,{direction:"right",className:"size-3.5 text-muted-foreground"})]})}),a.jsx(Gl,{className:"px-2 pb-2",children:a.jsxs("div",{className:"grid gap-1",children:[a.jsx(Ret,{agentId:e,view:"row"}),a.jsx(Met,{agentId:e,view:"row"}),a.jsx(Det,{agentId:e,view:"row"}),a.jsx(Let,{agentId:e,view:"row"}),a.jsx(zet,{agentId:e,view:"row"}),a.jsx(Fet,{agentId:e,view:"row"})]})})]})})}function Hys(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 Gys(e){return typeof e=="object"&&e!==null&&"parts"in e&&Array.isArray(e.parts)}function Kys(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 Yys(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 Xys(e){const t=[];for(const n of e){const r=Hys(n.content);if(Gys(r))for(const s of r.parts)Kys(s)&&t.push(Yys(s,new Date(n.createdAt).toISOString()))}return t.sort((n,r)=>n.timestamp.localeCompare(r.timestamp)),t}function BA(e){return/[Zz+-]\d{0,4}$/.test(e.trim())?new Date(e).getTime():new Date(e.trim().replace(" ","T")+"Z").getTime()}function Jys(e){if(e.length===0)return{tMin:0,tMax:1};let t=1/0,n=-1/0;for(const r of e){const s=BA(r);s<t&&(t=s),s>n&&(n=s)}return t===n?{tMin:t,tMax:t+1}:{tMin:t,tMax:n}}function Nz(e,t){return(BA(e)-t.tMin)/(t.tMax-t.tMin)}function DNe(e,t){return new Date(t.tMin+e*(t.tMax-t.tMin))}function exs(e,t){return DNe(e,t).getTime()}function JBt(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function txs(e){return BA(JBt(e))}function nxs(e,t){if(t==null)return null;const r=e.map(s=>({id:s.id,t:BA(JBt(s))})).toSorted((s,i)=>s.t-i.t).findLast(s=>s.t<=t);return r?r.id:null}function Bet(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function rxs(e){return[...e].sort((t,n)=>BA(Bet(t))-BA(Bet(n)))}function sxs({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=rxs(t).at(-1);return{messageTokens:s?.pendingTokens??i?.pendingMessageTokens,messageThreshold:s?.observationThreshold??n,memoryTokens:s?.observationTokens??i?.observationTokenCount,memoryThreshold:s?.reflectionThreshold??r}}function LD(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function ixs(e,t,n){const r=e.map(i=>({ts:String(LD(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:Nz(i.ts,n),pendingMessageTokens:i.pendingMessageTokens}))}function oxs(e,t,n){const r=[...e.map(i=>({ts:String(LD(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:Nz(i.ts,n),observationTokenCount:s}))}function axs(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:Nz(s.ts,t),bufferedObservationTokenCount:r}))}function lxs(e,t){return[...e].sort((n,r)=>String(LD(n)).localeCompare(String(LD(r)))).map(n=>({t:Nz(String(LD(n)),t),event:1}))}function cxs(e,t){return[...e].sort((n,r)=>new Date(n.createdAt).getTime()-new Date(r.createdAt).getTime()).map(n=>({t:Nz(new Date(n.createdAt).toISOString(),t),event:1,role:n.role}))}function uxs(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 dxs(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 fxs(e){return e==null?null:Number(e)}function hxs(e){return!!e?.event}const pxs="var(--chart-green)",mxs="var(--chart-amber)",Uet="var(--chart-pink)";function gxs({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:Jr(DNe(n,e),"date-time-seconds",{timeZone:"UTC"})},n))})]})}function LNe({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?Jr(DNe(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:`${nh} 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:`${nh} rounded px-2 py-1`,children:i&&a.jsx(Y,{as:"span",variant:"meta",font:"mono",tone:"ink",children:i})})}function vxs({label:e,data:t,dataKey:n,color:r,gradientId:s,domain:i,zoomDomain:o,threshold:l}){const c=dxs(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(cA,{width:"100%",height:32,children:a.jsxs(vMr,{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(C6,{dataKey:"t",type:"number",domain:o,allowDataOverflow:!0,hide:!0}),a.jsx(_6,{type:"number",domain:c!=null?[0,c]:void 0,hide:!0}),a.jsx(w6,{content:a.jsx(LNe,{domain:i,showValue:!0}),cursor:{stroke:"var(--border)"}}),a.jsx(zY,{type:"linear",dataKey:n,stroke:r,strokeWidth:1,fill:`url(#${s})`,isAnimationActive:!1}),l!=null&&a.jsx(DY,{y:l,stroke:"var(--border-strong)",strokeDasharray:"4 3"})]})})})]})}function yxs({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(cA,{width:"100%",height:r,children:a.jsxs(mMr,{margin:{top:0,right:0,bottom:0,left:0},children:[a.jsx(C6,{dataKey:"t",type:"number",domain:i,allowDataOverflow:!0,hide:!0}),a.jsx(_6,{dataKey:"event",type:"number",domain:[0,2],hide:!0}),a.jsx(w6,{content:a.jsx(LNe,{domain:s}),cursor:!1}),a.jsx(_Nt,{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 Vet({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=uxs(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(cA,{width:"100%",height:u,children:a.jsxs(aCe,{margin:{top:0,right:0,bottom:0,left:0},onClick:h=>{const p=fxs(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(C6,{dataKey:"t",type:"number",domain:l,allowDataOverflow:!0,hide:!0}),a.jsx(_6,{yAxisId:"area",dataKey:n,type:"number",hide:!0,domain:[0,"dataMax"]}),a.jsx(w6,{content:a.jsx(LNe,{domain:o,showValue:!0}),cursor:!1}),a.jsx(zY,{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=>hxs(h.payload)?a.jsx("circle",{cx:h.cx,cy:h.cy,r:4,fill:s}):a.jsx(a.Fragment,{})}),c!=null&&a.jsx(DY,{yAxisId:"area",y:c,stroke:"var(--border-strong)",strokeDasharray:"4 3"})]})})})]})}function xxs({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(ue,{variant:"ghost",size:"icon-sm","aria-label":"Reset zoom",onClick:i,children:a.jsx(T_,{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 bxs={tMin:0,tMax:1};function wxs({omRecords:e,markers:t,messages:n,tDomain:r,observationThreshold:s,reflectionThreshold:i,onSelectTimestamp:o,zoomRange:l,onZoomRangeChange:c}){const u=r??bxs,d=g.useCallback(Q=>{o?.(exs(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(()=>cxs(n,u),[n,u]),I=g.useMemo(()=>ixs(e,t,u),[e,t,u]),A=g.useMemo(()=>oxs(e,t,u),[e,t,u]),P=g.useMemo(()=>axs(t,u),[t,u]),L=g.useMemo(()=>lxs(e,u),[e,u]);return N.length>0||I.length>0||A.length>0||L.length>0?a.jsxs("div",{className:"flex flex-col pr-2 pb-2 [&_.recharts-surface]:outline-none",children:[a.jsx(Vet,{label:"Messages",areaData:I,areaDataKey:"pendingMessageTokens",eventData:N,color:pxs,gradientId:"grad-messages",domain:u,zoomDomain:_,threshold:s,onSelectT:o?d:void 0}),a.jsx(Vet,{label:"Observations",areaData:A,areaDataKey:"observationTokenCount",eventData:L,color:mxs,gradientId:"grad-observations",domain:u,zoomDomain:_,threshold:i,onSelectT:o?d:void 0}),P.length>0&&a.jsx(vxs,{label:"Buffered obs",data:P,dataKey:"bufferedObservationTokenCount",color:Uet,gradientId:"grad-buffered-obs",domain:u,zoomDomain:_,threshold:i}),L.length>0&&a.jsx(yxs,{label:"Events",data:L,color:Uet,domain:u,zoomDomain:_}),a.jsx(gxs,{domain:u}),a.jsx(xxs,{tDomain:u,zoomLeft:y,zoomRight:x,onZoomLeftChange:b,onZoomRightChange:S,onReset:k})]}):null}const Sxs=g.lazy(()=>Ai(async()=>{const{CodeDiff:e}=await import("./CodeDiff.es-hnMamK_l.js");return{CodeDiff:e}},__vite__mapDeps([9,4,1,3]),import.meta.url).then(({CodeDiff:e})=>({default:e})));function kxs(e){if(!e)return null;const t=e.match(/^(\d{1,2}):(\d{2})$/);if(!t)return e;const[,n,r]=t;return Jr(new Date(2e3,0,1,Number(n),Number(r)),"time")??e}function Oxs(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=Bve[e];return{card:n.card,text:"text-foreground",time:n.time}}function jxs(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(Fve))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 Cxs(e){const t="<observations>",n=e.indexOf(t),r=n===-1?-1:e.indexOf("</observations>",n+t.length),s=(r===-1?e:e.slice(n+t.length,r)).trim();if(!s)return[];const i=s.split(`
|
|
676
676
|
`),o=[];let l=null,c=null;for(const u of i){const d=u.trim();if(!d)continue;if(d.startsWith("Date:")){let m=d.slice(5).trim(),v=null;if(m.endsWith(")")){const y=m.lastIndexOf("("),x=y===-1?"":m.slice(y+1,-1);y>0&&x&&!x.includes(")")&&(v=x.trim(),m=m.slice(0,y).trim())}if(m){l={title:m,relativeTime:v,items:[]},o.push(l),c=null;continue}}l||(l={title:"Recent",relativeTime:null,items:[]},o.push(l));const h=(u.match(/^(\s*)/)?.[1]?.length??0)>=2&&(d.startsWith("* ->")||d.startsWith("->")||d.startsWith("-")),p=jxs(u);if(p){if(h&&c){c.children.push(p);continue}l.items.push(p),c=p}}return o}function eUt({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=Oxs(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:kxs(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(eUt,{items:n.children,nested:!0})})]})]})},`${n.text.slice(0,20)}-${r}`)})})}function _xs({observations:e}){const t=g.useMemo(()=>Cxs(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(eUt,{items:n.items})]},`${n.title}-${r}`))})}function Txs({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 Exs({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(xt,{className:"h-6 w-40"}),a.jsx(xt,{className:"h-32 w-full"}),a.jsx(xt,{className:"h-32 w-full"})]});if(!l)return a.jsx(Xt,{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(ht,{orientation:"horizontal",className:"gap-1.5",children:[a.jsx(Gc,{checked:s,onCheckedChange:f=>i(f===!0)}),a.jsx(ut,{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(xt,{className:"h-32"}),children:a.jsx(Sxs,{codeA:typeof u.activeObservations=="string"?u.activeObservations:"",codeB:d,filename:"observations.md",layout:"unified",className:"rounded-xl"})}):d?a.jsx(_xs,{observations:d}):a.jsx(Y,{variant:"caption",tone:"muted",className:"italic",children:l.isObserving||l.isReflecting?"Processing…":"Initialized"})})]}),a.jsx(Txs,{records:o,selectedRecordId:l.id,onSelectRecord:n})]})}function qet(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 Ixs={messages:"text-chart-blue",memory:"text-chart-purple",warning:"text-warning-foreground"};function Qet({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",Ixs[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:[qet(t),"/",qet(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 Nxs({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(Qet,{label:"Messages",value:e,max:t,tone:"messages"}):null,o?a.jsx(Qet,{label:s,value:n,max:r,tone:"memory"}):null]})})}function Axs({messages:e,omRecords:t,isLoading:n=!1,onClose:r,selectedTimestamp:s,onSelectTimestamp:i,contextWindow:o}){const[l,c]=g.useState(null),u=g.useMemo(()=>Xys(e),[e]),d=g.useMemo(()=>Jys(e.map(j=>new Date(j.createdAt).toISOString())),[e]),f=g.useMemo(()=>sxs({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=txs(j);return C>=m.left&&C<=m.right}),[t,y,m.left,m.right]),b=g.useMemo(()=>s!=null?nxs(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(ue,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"Back to memory",onClick:()=>r?.(),children:a.jsx(vd,{})}),a.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 text-foreground",children:[a.jsx(u$,{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(xt,{className:"h-6 w-40"}),a.jsx(xt,{className:"h-32 w-full"}),a.jsx(xt,{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(Exs,{records:x,selectedRecordId:k,onSelectRecord:c,isLoading:n})}),a.jsxs("div",{className:"border-t border-border",children:[a.jsx(Nxs,{messageTokens:o?.messageTokens??f.messageTokens,messageThreshold:o?.messageThreshold??f.messageThreshold,memoryTokens:h,memoryThreshold:p,memoryLabel:"Observations"}),a.jsx(wxs,{omRecords:t,markers:u,messages:e,tDomain:d,onSelectTimestamp:i,zoomRange:m,onZoomRangeChange:v})]})]})]})}const Pxs=2e3;function $xs({agentId:e,threadId:t}){const{isPanelOpen:n,closePanel:r,selectedTimestamp:s,setSelectedTimestamp:i}=jX(),{isObservingFromStream:o,isReflectingFromStream:l,observationsUpdatedAt:c,streamProgress:u}=OX(),d=o||l,{data:f}=Z_e({threadId:t,agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!t&&t!=="new"&&!!e}}),h=f?.resourceId??e,{data:p}=qk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:m,isLoading:v,refetch:y}=RDt({agentId:n?e:void 0,threadId:n?t:void 0,resourceId:h}),{data:x,isLoading:b,refetch:S}=KYr({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()},Pxs);return()=>clearInterval(T)},[n,d,y,S]),!n)return null;const k=p?.config?.observationalMemory,j=u?.threadId===t?u:null,C=tNe({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(Axs,{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 Rxs(e){const{data:t}=qk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),n=t?.config;return{recentMessages:o7t(n?.lastMessages,n?.messageHistory),semanticRecallOn:!!n?.semanticRecall,workingMemoryOn:!!n?.workingMemory?.enabled,observationalOn:!!n?.observationalMemory?.enabled}}const Zet="agent-memory-sidebar-tab-v2",Mxs=()=>{const[e,t]=g.useState(()=>{const r=sessionStorage.getItem(Zet)||"threads";return r==="threads"||r==="memory"?r:"threads"}),n=g.useCallback(r=>{t(r),sessionStorage.setItem(Zet,r)},[]);return{selectedTab:e,handleTabChange:n}},Dxs=e=>e>=85?"bg-warning-indicator":e>=60?"bg-info-indicator":"bg-success-indicator";function L7({icon:e,tooltip:t,enabled:n,value:r}){return a.jsxs(Fn,{children:[a.jsx(Mn,{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(Dn,{children:t})]})}function Lxs(){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(xt,{className:"h-3 w-28"}),a.jsx(xt,{className:"h-3 w-20"}),a.jsx(xt,{className:"h-3 w-24"}),a.jsx(xt,{className:"h-3 w-16"})]})}function zxs({agentId:e,threadId:t,threads:n,onDelete:r,isThreadsLoading:s}){return a.jsx(bNe,{children:a.jsx(Fxs,{agentId:e,threadId:t,threads:n,onDelete:r,isThreadsLoading:s})})}function Fxs({agentId:e,threadId:t,threads:n,onDelete:r,threadsSlot:s,isThreadsLoading:i}){const{data:o,isLoading:l}=Vk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),c=!!o?.result,u=o?.memoryType,{selectedTab:d,handleTabChange:f}=Mxs(),{isPanelOpen:h}=jX(),{streamProgress:p}=OX(),{recentMessages:m,semanticRecallOn:v,workingMemoryOn:y,observationalOn:x}=Rxs(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}=Z_e({threadId:t,agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!t&&t!=="new"&&!!e}}),{data:I}=qk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:A}=RDt({agentId:x?e:void 0,threadId:x?t:void 0,resourceId:N?.resourceId??e}),P=I?.config?.observationalMemory,{messageTokens:L,messageThreshold:F}=tNe({record:A?.record,liveProgress:_,agentConfig:P}),q=(!!_||!!A?.record)&&F>0?Math.min(100,Math.round(L/F*100)):void 0;return g.useLayoutEffect(()=>{if(b||T||!c)return;const B=S.current,V=k.current;if(!B||!V)return;const H=()=>{const K=getComputedStyle(B),M=Number.parseFloat(K.borderTopWidth)||0,$=Number.parseFloat(K.borderBottomWidth)||0,z=Number.parseFloat(K.marginTop)||0,U=Number.parseFloat(K.marginBottom)||0,G=Math.ceil(V.getBoundingClientRect().height+M+$),ne=Math.ceil(G+z+U);C(X=>X.height===G&&X.offset===ne?X:{height:G,offset:ne})};if(H(),typeof ResizeObserver>"u")return;const D=new ResizeObserver(H);return D.observe(V),()=>D.disconnect()},[c,m.description,q,x,v,b,T,y]),l?a.jsx(Lxs,{}):T?a.jsx("div",{"data-testid":"memory-sidebar-panel",className:"h-full min-h-0 min-w-0",children:a.jsx($xs,{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(i7t,{resourceId:e,resourceType:"agent",threads:n??[],threadId:t,onDelete:r??(()=>{}),embedded:!0,isLoading:i},e):a.jsx(Xt,{titleSlot:"Memory not enabled",descriptionSlot:"Conversations are only saved as threads when the agent has memory configured.",actionSlot:a.jsx(ue,{icon:a.jsx(Zs,{}),render:a.jsx("a",{href:"https://mastra.ai/docs/memory/overview",target:"_blank",rel:"noopener noreferrer"}),children:"View documentation"})}))})}),c?a.jsxs("div",{ref:S,"data-testid":"memory-sidebar-overlay",className:Z("memory-sidebar-overlay absolute inset-x-0 bottom-0 z-10 box-border flex min-h-0 flex-col overflow-hidden",b?Z(pr,"top-1 m-1 rounded-xl"):"state-layer m-1 rounded-xl border border-surface-rim bg-muted"),style:{height:b?void 0:j.height||void 0},children:[a.jsxs("button",{ref:k,type:"button",onClick:()=>f(b?"threads":"memory"),"aria-pressed":b,"data-testid":"memory-sidebar-card",className:"group/memory-card w-full shrink-0 cursor-pointer bg-transparent px-3 py-2.5 text-left",children:[a.jsxs("span",{className:"flex items-center justify-between gap-2",children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 text-foreground",children:[a.jsx(u$,{className:"h-4 w-4 shrink-0"}),a.jsx(Y,{as:"span",variant:"column",children:"Memory"})]}),b?a.jsx(dc,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):a.jsx(ZH,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]}),b?null:a.jsx(mc,{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(L7,{icon:dL,tooltip:m.description,enabled:m.enabled,value:m.maxMessages}),a.jsx(L7,{icon:Su,tooltip:v?"Semantic recall is on - retrieves relevant past messages":"Semantic recall is off",enabled:v}),a.jsx(L7,{icon:xIn,tooltip:y?"Working memory is on - persists notes across the conversation":"Working memory is off",enabled:y}),a.jsx(L7,{icon:Fa,tooltip:x?"Observational memory is on - learns from the conversation":"Observational memory is off",enabled:x})]})}),q!==void 0?a.jsx("span",{"data-testid":"memory-card-observation-bar","data-percent":q,className:"mt-2 block h-1 w-full overflow-hidden rounded-full bg-fill",children:a.jsx("span",{className:Z("block h-full rounded-full transition-all duration-normal",Dxs(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(Vhs,{agentId:e,threadId:t,memoryType:u})})]}):null]}),a.jsx(Wys,{agentId:e})]})}function Bxs({agentId:e,threadId:t}){const n=xr("agent",e)[0],{mutateAsync:r}=YYr(n),{paths:s,navigate:i}=Tn(),{data:o}=Vk({agentId:e,requestContext:n,queryOptions:{enabled:!!e}}),l=!!o?.result,{data:c,isLoading:u}=W_e({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{Ye.error("Failed to delete chat");return}Ye.success("Chat deleted successfully"),h===t&&i(s.agentNewThreadLink(e))};return a.jsx(zxs,{agentId:e,threadId:t,threads:d,onDelete:f,isThreadsLoading:u})}const Uxs=()=>{const e=CX();return W0({"{":()=>e?.toggle()}),null},$d=e=>e.nullable().transform(t=>t??void 0).optional(),Wet=Rn({frequencyPenalty:$d(us()),presencePenalty:$d(us()),maxRetries:$d(us()),maxSteps:$d(us()),maxTokens:$d(us()),temperature:$d(us()),topK:$d(us()),topP:$d(us()),seed:$d(us()),providerOptions:$d(Oi(gt(),Oi(gt(),E2n()))),chatWithGenerateLegacy:$d(Da()),chatWithGenerate:$d(Da()),chatWithLegacyStream:$d(Da()),chatWithNetwork:$d(Da()),requireToolApproval:$d(Da())}),Vxs=Rn({provider:gt(),model:gt()}),tUt=Oi(gt(),ua());function qxs(e){const t=tUt.safeParse(e);if(!t.success)return;const n={};for(const[r,s]of Object.entries(Wet.shape)){if(!Object.hasOwn(t.data,r))continue;const i=s.safeParse(t.data[r]);i.success&&(n[r]=i.data)}return Wet.parse(n)}const Qxs=tUt.transform(e=>{const t=Vxs.safeParse(e.selection);return{selection:t.success?t.data:void 0,modelSettings:qxs(e.modelSettings)}});function Zxs(e){return JSON.stringify({...e,modelSettings:e.modelSettings&&Object.fromEntries(Object.entries(e.modelSettings).map(([t,n])=>[t,n===void 0?null:n]))})}function Wxs(e){const t=`mastra-thread-preferences-${JSON.stringify([e.agentId,e.threadId])}`;return a.jsx(Hxs,{...e,storageKey:t},t)}function Hxs({children:e,defaultProvider:t,defaultModel:n,defaultSettings:r,storageKey:s}){const[i,o]=jk({initialKey:s,defaultValue:{},schema:Qxs,serialize:Zxs}),{data:l,isError:c}=H0(),u=l?.modelPolicy,{models:d,isLoading:f,isError:h}=uw({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=>io(I.provider)===io(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:{...kve.modelSettings,...r?.modelSettings,...i.modelSettings}};return a.jsx(sTe.Provider,{value:{provider:C,model:T,modelOverride:_,modelWarning:j,setProvider:I=>o(A=>({...A,selection:{provider:I,model:""}})),setModel:(I,A)=>o(P=>({...P,selection:{provider:I,model:A}}))},children:a.jsx(G_e.Provider,{value:{settings:N,setSettings:I=>o(A=>({...A,modelSettings:I.modelSettings})),resetAll:()=>o(I=>({...I,modelSettings:void 0}))},children:e})})}const Gxs=6;function Kxs(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===Gxs))break}return n}function Yxs(){const{agentId:e,threadId:t}=jr(),n=Ge(),{data:r,error:s}=Ql(),i=r&&wp(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]=ci(),{data:f,isLoading:h,error:p}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:m,isLoading:v}=Vk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),y=Dr(),x=CX(),b=g.useRef(null),S=t==="new",k=g.useMemo(()=>Sa(),[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}=W_e({agentId:e,isMemoryEnabled:T,resourceId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!T}}),A=d.get("messageId")??void 0,P=Kxs(f?.metadata),L=g.useMemo(()=>wNe(f),[f]);if(p&&Cs(p))return a.jsx(ui,{variant:"fill"});if(p&&_s(p))return a.jsx(Gs,{variant:"fill",resource:"agents"});if(!r&&s)return a.jsx(Xt,{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(aye,{agentId:e,leftSlot:S&&!v&&!T?void 0:a.jsx(Jxs,{agentId:e}),leftDrawerLabel:"Threads",children:S?a.jsx(vys,{}):a.jsx(ebs,{})});if(p&&Ik(p))return a.jsx(SW,{});if(p)return a.jsx(Xt,{tone:"error",titleSlot:"Failed to load agent",descriptionSlot:p.message});if(!f)return a.jsx(SW,{});const F=S?k:t??k,Q=S&&!T&&(N||!_?.length),q=async()=>{if(S&&C.current===j){const B=b.current;l&&await B?.move(j),C.current===j&&B===b.current&&y(`/agents/${e}/threads/${k}`,{replace:!0})}x?.expandIfAutoCollapsed(),await I()};return a.jsx(Wxs,{agentId:e,threadId:F,defaultProvider:io(f.provider??""),defaultModel:f.modelId??"",defaultSettings:L,children:a.jsx(YDt,{agentId:e,threadId:F,resourceId:e,children:a.jsx(yX,{children:a.jsx(xX,{agentId:e,threadId:F,enabled:!!(f?.hasBrowser??f?.browserTools?.length),children:a.jsx(nNe,{ref:b,persistence:l?{key:u,threadId:F}:void 0,children:a.jsx(e4t,{children:a.jsx(kXr,{children:a.jsxs(SX,{children:[a.jsx(Uxs,{}),a.jsx(aye,{agentId:e,leftSlot:Q?void 0:a.jsx(Bxs,{agentId:e,threadId:F}),leftDrawerLabel:"Threads",children:a.jsx("div",{className:"relative flex h-full min-h-0 flex-col",children:a.jsx("div",{className:"relative grid min-h-0 flex-1",children:a.jsx(MNe,{agentId:e,agentName:f?.name,modelVersion:f?.modelVersion,supportsMemory:f?.supportsMemory,threadId:F,memory:T,refreshThreadList:q,modelList:f?.modelList,messageId:A,suggestedPrompts:P,isNewThread:S,runOptionsSlot:a.jsx(SNe,{agentId:e})})})},F)})]},`${e}-${F}`)},`memory-timeline-${e}-${F}`)})},`${l}:${JSON.stringify([...c,F])}`)},`session-${e}-${F}`)},`browser-${e}-${F}`)})})}function Xxs(){const{agentId:e}=jr();return a.jsx(CXr,{children:a.jsx(Yxs,{})},e)}const Jxs=({agentId:e})=>a.jsx(bNe,{children:a.jsx(i7t,{threads:[],threadId:"",onDelete:()=>{},resourceId:e,resourceType:"agent",embedded:!0,isLoading:!0})}),ebs=()=>a.jsx("div",{className:"relative grid h-full overflow-y-auto pt-4","data-testid":"agent-thread-skeleton","aria-busy":"true",children:a.jsx(HBt,{})}),nUt=()=>{const{data:e}=MP();return e?.editorSource==="code"?"code":"db"},Az=()=>{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 tbs(){const{agentId:e}=jr(),[t,n]=g.useState(null),{data:r,isLoading:s,error:i}=bd({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),{data:o}=Vk({agentId:e,requestContext:xr("agent",e)[0],queryOptions:{enabled:!!e}}),l=nUt(),{isMastraPlatform:c,mastraPlatformApiEndpoint:u,mastraPlatformProjectId:d}=Az(),{data:f,isLoading:h}=YL({agentId:e,params:{orderBy:{direction:"DESC"}},queryOptions:{enabled:!!e}}),p=(f?.versions?.length??0)>0,{data:m,isLoading:v}=kK({agentId:e,status:"draft",queryOptions:{enabled:!!e&&p}}),y=r?.source==="code",x=y&&l==="code",b=!iT(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:_}=hOt({agentId:e??"",versionId:t??"",queryOptions:{enabled:!!e&&!!t}}),N=m?.activeVersionId,I=f?.versions?.[0],A=!!(I&&I.id!==N),P=!!t&&!!_,L=P&&t!==I?.id,F=g.useMemo(()=>P&&_?_:m||(r?fBt(r):{}),[P,_,m,r]),{form:Q,handlePublish:q,handleSaveDraft:B,handleDownloadJson:V,handleOpenPr:H,isSubmitting:D,isSavingDraft:K,isDirty:M}=xNe({mode:"edit",agentId:e??"",dataSource:F,isCodeAgentOverride:y,hasStoredOverride:y&&!!m,editorConfig:r?.editor,saveSuccessMessage:x?"Saved to filesystem":void 0,onSuccess:()=>{}}),$=g.useCallback(async()=>{L&&t?await q(t):await q()},[q,L,t]),z=g.useCallback(async()=>{!u||!d||await H({platformApiEndpoint:u,projectId:d})},[H,u,d]),U=g.useCallback(G=>{G===I?.id?n(null):n(G)},[I?.id]);return i&&Cs(i)?a.jsx(ui,{variant:"fill"}):i&&_s(i)?a.jsx(Gs,{variant:"fill",resource:"agents"}):C?a.jsx(_n,{fill:!0}):i&&Ik(i)?a.jsx("div",{className:"py-4 text-center",children:"Agent not found"}):i?a.jsx(Xt,{tone:"error",titleSlot:"Failed to load agent",descriptionSlot:i.message}):r?a.jsx(n4t,{form:Q,mode:"edit",agentId:e,isSubmitting:D,isSavingDraft:K,handlePublish:q,handleSaveDraft:B,isCodeAgentOverride:y,isCodeSourceAgent:x,readOnly:L||!b,editorConfig:r?.editor,children:a.jsx(Ggs,{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:M,isSavingDraft:K,isPublishing:D,hasDraft:A,readOnly:L||!b,isCodeSourceAgent:x,showCodeModeActions:S,canOpenPr:k,openPrTitle:j,onSaveDraft:B,onPublish:$,onDownloadJson:V,onOpenPr:z,isViewingPreviousVersion:L})}):a.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}const Het=/mac|iphone|ipad|ipod/i;function nbs(){if(typeof navigator>"u")return!1;const e=navigator,t=e.userAgentData?.platform||e.platform||"",n=e.userAgent||"";return Het.test(t)||Het.test(n)}function zNe(){const[e]=g.useState(nbs);return e}function rbs(e){const t=zNe();return g.useMemo(()=>{const n=e.trim().toUpperCase();return`${t?"⌘":"Ctrl"} ${n}`},[t,e])}const FNe="root",sbs=e=>Array.isArray(e)?{logic:"and",nodes:e}:e,ibs=(e,t)=>t?e.nodes.filter(n=>!qa(n)):e,Gce=e=>{const t=[],n=(r,s)=>{for(const i of r)qa(i)?n(i.nodes,i.id):t.push(s?{item:i,groupId:s}:{item:i})};return n(e.nodes,void 0),t},rUt=(e,t)=>{for(const n of e){if(!qa(n))continue;if(n.id===t)return n;const r=rUt(n.nodes,t);if(r)return r}},sUt=(e,t)=>rUt(e.nodes,t),obs=(e,t)=>{const n=(r,s)=>{for(const i of r){if(!qa(i))continue;if(i.id===t)return s;const o=n(i.nodes,s+1);if(o)return o}return 0};return n(e.nodes,1)},BNe=e=>e.nodes.reduce((t,n)=>t+(qa(n)?BNe(n):1),0),iUt=e=>[e.id,...e.nodes.flatMap(t=>qa(t)?iUt(t):[t.id])],ZJ=(e,t,n)=>e.map(r=>qa(r)?r.id===t?n(r):{...r,nodes:ZJ(r.nodes,t,n)}:r),oUt=(e,t)=>e.map(n=>qa(n)?{...n,nodes:oUt(n.nodes,t)}:t(n)),UNe=(e,t)=>e.filter(t).map(n=>qa(n)?{...n,nodes:UNe(n.nodes,t)}:n),Get=(e,t,n)=>({...e,nodes:oUt(e.nodes,r=>r.id===t?{...r,...n}:r)}),Ket=(e,t)=>({...e,nodes:UNe(e.nodes,n=>n.id!==t)}),aUt=e=>e.flatMap(t=>{if(!qa(t))return[t];const n=aUt(t.nodes);return n.length===0?[]:[{...t,nodes:n}]}),lUt=e=>({...e,nodes:aUt(e.nodes)}),Yet=(e,t,n)=>!t||t===FNe?{...e,nodes:[...e.nodes,n]}:{...e,nodes:ZJ(e.nodes,t,r=>({...r,nodes:[...r.nodes,n]}))},abs=(e,t,n)=>{const r=o=>{const l=n.find(c=>c.id===o);return l?.arity==="many"?l.id:l?.widensTo},s=r(e.operatorId);if(!s||s!==r(t.operatorId)||!n.some(o=>o.id===s))return t;const i=[e.value,t.value].flat().filter(o=>o!=="");return{operatorId:s,value:i.filter((o,l)=>i.indexOf(o)===l)}},lbs=(e,t,n)=>t===FNe?{...e,logic:n}:{...e,nodes:ZJ(e.nodes,t,r=>({...r,logic:n}))},cbs=(e,t,n)=>!t||t===FNe?{...e,nodes:[...e.nodes,n]}:{...e,nodes:ZJ(e.nodes,t,r=>({...r,nodes:[...r.nodes,n]}))},ubs=(e,t)=>lUt({...e,nodes:UNe(e.nodes,n=>qa(n)||t.has(n.id))}),Oye=["field","operator","value","remove"],dbs=[...Oye].reverse(),fbs=3,VNe="data-filter-bar-scope",Kce=e=>e?.closest(`[${VNe}]`)??null,Xet=e=>e?e.operatorId?"operator":"field":"none",cUt=g.createContext(null);function eu(){const e=g.useContext(cUt);if(!e)throw new Error("FilterBar compound components must be rendered inside <FilterBar>.");return e}let Jet=0;function ett(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Jet+=1,`filter-${Jet}`)}function uUt(e){return e?.arity==="many"?[]:""}const rj=(e,t=new Set)=>{for(const n of e)t.add(n.id),qa(n)&&rj(n.nodes,t);return t},dUt=(e,t,n)=>{const r=new Map(t.map(o=>[o.id,o])),s=new Set,i=[];for(const o of e){const l=r.get(o.id);l?(s.add(o.id),i.push(qa(l)&&qa(o)?{...l,nodes:dUt(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 hbs({fields:e,operators:t,value:n,onValueChange:r,createItemId:s,maxDepth:i=fbs,ariaLabel:o,children:l}){const c=g.useRef(new Map),u=g.useRef(null),d=Array.isArray(n),f=g.useMemo(()=>sbs(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(ae=>r(ibs(ae,d)),[r,d]),C=g.useCallback(ae=>e.find(me=>me.id===ae),[e]),T=g.useCallback(ae=>t.find(me=>me.id===ae),[t]),_=g.useCallback(ae=>{if(!ae.operators)return t;const me=new Set(ae.operators);return t.filter(Ne=>me.has(Ne.id))},[t]),N=g.useCallback(ae=>m(ae),[]),[I,A]=g.useState(null),P=g.useRef(I);P.current=I;const[L,F]=g.useState(null),Q=g.useCallback(()=>F(ae=>ae?{...ae,glint:!1}:null),[]),[q,B]=g.useState(()=>new Set),V=g.useCallback(ae=>{B(me=>{if(!me.has(ae))return me;const Ne=new Set(me);return Ne.delete(ae),Ne})},[]),H=g.useCallback(ae=>{const me=[...ae];me.length!==0&&B(Ne=>new Set([...Ne,...me]))},[]),D=g.useRef(f.nodes),{rendered:K,items:M,leaving:$,rootGroupOf:z}=g.useMemo(()=>{const ae=rj(f.nodes);let me=q.size===0?f:{...f,nodes:dUt(D.current,f.nodes,q)};L&&!ae.has(L.item.id)&&(me=Yet(me,L.groupId,L.item)),D.current=me.nodes;const Ne=rj(me.nodes),Te=new Set([...q].filter(ye=>Ne.has(ye)&&!ae.has(ye))),ce=new Map;for(const ye of me.nodes)if(qa(ye))for(const{item:Se}of Gce({nodes:[ye]}))ce.set(Se.id,ye.id);return{rendered:me,items:Gce(me).map(ye=>ye.item),leaving:Te,rootGroupOf:ce}},[f,L,q]),U=g.useCallback((ae,me)=>{if(!s||me!==void 0)return;const Ne=s(ae);return h.current.nodes.find(Te=>!qa(Te)&&Te.id===Ne)},[s]),G=g.useCallback(ae=>s&&x===void 0&&!U(ae,void 0)?s(ae):ett(),[s,x,U]),ne=g.useCallback(ae=>{F(null),A(me=>ae?{...ae,id:me?.fieldId===ae.fieldId?me.id:G(ae.fieldId),from:Xet(me),groupId:x}:null)},[G,x]),X=g.useCallback(({fieldId:ae,operatorId:me},Ne)=>{const Te=P.current?.id??G(ae),ce=P.current?.groupId??x,ye=Xet(P.current);A(null);const Se=U(ae,ce);if(Se){const De=C(ae),Qe=abs(Se,{operatorId:me,value:Ne},De?_(De):[]),tt={...Se,...Qe};j(Get(h.current,Se.id,Qe)),F({item:tt,from:ye,glint:!0}),N("Filter updated");return}const $e={id:Te,fieldId:ae,operatorId:me,value:Ne};j(Yet(h.current,ce,$e)),F({item:$e,from:ye,glint:!0,groupId:ce}),N("Filter added")},[j,N,G,x,U,C,_]),ee=g.useCallback((ae,me)=>{j(Get(h.current,ae,me))},[j]),ie=g.useCallback(ae=>{H([ae]),j(Ket(h.current,ae)),F(null),N("Filter removed")},[j,N,H]),fe=g.useCallback(ae=>{b(me=>me&&ae.has(me)?void 0:me)},[]),te=g.useCallback(ae=>{const me=h.current,Ne=sUt(me,ae),Te=new Set(Ne?iUt(Ne):[ae]);H(Te),j(Ket(me,ae)),F(null),A(null),fe(Te),k(ce=>ce===ae?null:ce),N("Advanced filter removed")},[j,N,H,fe]),se=g.useCallback((ae,me)=>{const Ne={id:ett(),kind:"group",logic:me,nodes:[]};return j(cbs(h.current,ae,Ne)),F(null),A(null),b(Ne.id),N(ae?"Nested group added":"Advanced filter added"),Ne.id},[j,N]),re=g.useCallback((ae,me)=>{j(lbs(h.current,ae,me)),N(`Conditions joined with ${me}`)},[j,N]),le=g.useCallback(ae=>obs(h.current,ae),[]),pe=g.useCallback(ae=>{if(k(ae),ae!==null)return;const me=h.current,Ne=lUt(me),Te=rj(Ne.nodes),ce=new Set([...rj(me.nodes)].filter(ye=>!Te.has(ye)));ce.size>0&&(H(ce),j(Ne)),A(null),b(void 0)},[j,H]),ve=g.useCallback(()=>{u.current?.focus()},[]),he=g.useCallback(ae=>{b(ae),A(null),ae===void 0&&ve()},[ve]),ke=g.useCallback(()=>{const ae=h.current,me=ubs(ae,v),Ne=rj(me.nodes),Te=new Set([...rj(ae.nodes)].filter(ce=>!Ne.has(ce)));H(Te),j(me),F(null),A(null),b(void 0),k(null),N("All filters removed")},[j,N,v,H]),Ee=Gce(f).some(({item:ae})=>!v.has(ae.id)),Ve=g.useCallback((ae,me)=>{y(Ne=>{if(Ne.has(ae)===me)return Ne;const Te=new Set(Ne);return me?Te.add(ae):Te.delete(ae),Te})},[]),Ze=g.useCallback((ae,me,Ne)=>{const Te=`${ae}:${me}`;Ne?c.current.set(Te,Ne):c.current.delete(Te)},[]),Fe=g.useCallback(ae=>{ae?u.current=ae:u.current?.isConnected||(u.current=null)},[]),Ae=g.useRef(M);Ae.current=M;const ze=g.useRef(z);ze.current=z;const je=g.useCallback((ae,me,Ne)=>{const Te=Ae.current,ce=ze.current,ye=Te[ae-me],Se=ye?[...Oye].map(Qe=>c.current.get(`${ye.id}:${Qe}`)).find(Boolean):null,$e=Kce(typeof document>"u"?null:document.activeElement)??Kce(Se)??void 0,De=me===-1?dbs:Oye;for(let Qe=ae;Qe>=0&&Qe<Te.length;Qe+=me){const tt=Te[Qe];if(!tt)break;const st=[tt.id,ce.get(tt.id)].filter(He=>He!==void 0);for(const He of st)for(const Le of[Ne,...De]){const wt=c.current.get(`${He}:${Le}`);if(wt&&($e===void 0||Kce(wt)===$e))return wt.focus(),!0}}return!1},[]),Ce=g.useCallback(ae=>{je(ae+1,1,"value")||je(ae-1,-1,"value")||ve()},[je,ve]),Ue=g.useMemo(()=>({fields:e,operators:t,items:M,expression:K,groupsEnabled:!d,maxDepth:i,draft:I,setDraft:ne,commitDraft:X,lastCommit:L,settleCommit:Q,updateItem:ee,removeItem:ie,leaving:$,settleRemove:V,clear:ke,hasRemovableItems:Ee,registerNonRemovable:Ve,addGroup:se,removeGroup:te,setLogic:re,getGroupDepth:le,openGroupId:S,setOpenGroup:pe,inputTarget:x,openGroupInput:he,getField:C,getOperator:T,getFieldOperators:_,registerSegment:Ze,registerInput:Fe,focusChip:je,focusInput:ve,focusAfterRemove:Ce,announce:N,announcement:p,ariaLabel:o}),[e,t,M,K,d,i,I,ne,X,L,Q,ee,ie,$,V,ke,Ee,Ve,se,te,re,le,S,pe,x,he,C,T,_,Ze,Fe,je,ve,Ce,N,p,o]);return a.jsx(cUt.Provider,{value:Ue,children:l})}function fUt({option:e}){return a.jsxs(a.Fragment,{children:[e.start,a.jsx("span",{className:"min-w-0 truncate",children:e.label??e.value})]})}const hUt=g.forwardRef((e,t)=>a.jsx(iOt,{ref:Du(t),...e}));hUt.displayName="FilterBarOptionItem";function JI({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=Bv();return a.jsxs(a.Fragment,{children:[r&&a.jsxs(VUe,{className:ss.empty,children:[a.jsx(_n,{size:"sm"}),a.jsx("span",{children:"Loading…"})]}),!r&&s!==void 0&&a.jsx(VUe,{className:ss.empty,children:"Couldn't load values."}),a.jsx(aOt,{className:ss.empty,children:c?i:null}),a.jsx("div",{className:Z(ss.listScroller,"max-h-[min(var(--spacing-dropdown),60dvh)]",u.containerClassName),...u.getContainerProps({}),children:a.jsx(Um,{menu:u,children:a.jsx(Jkt,{"aria-label":o,"aria-multiselectable":l,className:ss.list,children:d=>{const f=n?.(d)??!1;return a.jsxs(hUt,{value:d,"data-selected":f||void 0,className:Z(ss.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:ss.itemRightSlot,children:a.jsx("span",{className:ss.checkContainer,children:n?f&&a.jsx(ur,{className:ss.checkIcon}):a.jsx(oOt,{children:a.jsx(ur,{className:ss.checkIcon})})})})]},e(d))}})})})]})}function qNe(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 QNe(e,t,n){return qNe(n?n(e):String(e),t)}const pbs=150,mbs=[{value:"true",label:"True"},{value:"false",label:"False"}],pUt=e=>e?.suggestions??(e?.type==="boolean"?mbs:void 0);function gbs({field:e,operatorId:t,query:n,enabled:r}){const s=pUt(e),i=typeof s=="function"?s:void 0,o=Array.isArray(s)?s:void 0,[l,c]=g.useState([]),[u,d]=g.useState(!1),[f,h]=g.useState(void 0),p=g.useRef(0),m=g.useRef(i);m.current=i;const v=!!i;return g.useEffect(()=>{if(!v||!r){c([]),d(!1),h(void 0);return}const x=++p.current,b=new AbortController;d(!0);const S=setTimeout(()=>{Promise.resolve().then(()=>m.current?.({query:n,operatorId:t,signal:b.signal})??[]).then(k=>{x===p.current&&(c(k),h(void 0),d(!1))}).catch(k=>{x!==p.current||b.signal.aborted||(h(k),d(!1))})},pbs);return()=>{clearTimeout(S),b.abort()}},[v,r,n,t]),{options:g.useMemo(()=>o?o.filter(x=>qNe(x.label??x.value,n)):l,[o,l,n]),isLoading:!!i&&u,error:f,hasSuggestions:!!s}}const ttt=e=>Array.isArray(e)?e.map(String):[];function mUt({field:e,operator:t,query:n,enabled:r,initialValue:s,setQuery:i,onCommit:o}){const l=t?.arity==="many",[c,u]=g.useState(()=>ttt(s)),d=g.useRef(s);d.current=s,g.useEffect(()=>{u(r?ttt(d.current):[])},[r]);const f=t?.freeText===!0,h=gbs({field:f?void 0:e,operatorId:t?.id??"",query:n,enabled:r}),p=e?.type,m=(!e?.strict||f)&&p!=="boolean",v=g.useMemo(()=>{if(!l)return h.options;const I=vbs(c,h.options,h.hasSuggestions,n);return I.length===0?h.options:[...h.options,...I]},[l,c,h.options,h.hasSuggestions,n]),y=g.useCallback(I=>{u(A=>A.includes(I)?A.filter(P=>P!==I):[...A,I])},[]),x=g.useCallback(I=>o(Array.isArray(I)?I.map(A=>xye(p,A)):xye(p,I)),[o,p]),b=g.useCallback(I=>{l?y(I.value):x(I.value)},[l,y,x]),S=g.useCallback(()=>c.length===0?!1:(x(c),!0),[c,x]),k=g.useCallback(I=>m&&I.length>0&&(p!=="number"||Number.isFinite(Number(I)))&&(!f||/[\p{L}\p{M}\p{N}]/u.test(I)),[m,f,p]);function j(){const I=n.trim();return k(I)?(u(A=>A.includes(I)?A:[...A,I]),i(""),!0):!1}const C=g.useCallback(()=>{const I=n.trim();return k(I)?(x(l?c.includes(I)?c:[...c,I]:I),!0):!1},[k,n,l,c,x]);function T(){return l?j():C()}function _(){return h.options.length===0?C()||S():S()||C()}function N(I,A){return I.key!=="Enter"?!1:l&&(I.ctrlKey||I.metaKey)?(I.preventDefault(),_()):A===null?(I.preventDefault(),T()):!1}return{isMany:l,selected:c,toggle:y,options:v,isLoading:h.isLoading,error:h.error,hasSuggestions:h.hasSuggestions,hasOptions:h.hasSuggestions||v.length>0,allowFreeText:m,canCommitQuery:k(n.trim()),handleSelect:b,handleKeyDown:N,submitFreeText:T,commitDone:_}}function vbs(e,t,n,r){const s=new Set(t.map(o=>o.value)),i=o=>!n||qNe(o,r);return e.filter(o=>!s.has(o)&&i(o)).map(o=>({value:o}))}const WJ=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"),gUt="sm",vUt={autoHighlight:"always",keepHighlight:!0},yUt=Z("filter-bar-chip relative flex max-w-full items-stretch divide-x divide-border overflow-hidden rounded-full py-px",UH,tp[gUt]),eN=Z(WJ,"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 HJ({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 jye=e=>e?.color?{color:e.color}:void 0,ybs=(e,t)=>e==="none"?0:e==="field"||t?1:2,kW=(e,t)=>{const n=pUt(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)},xbs=(e,t)=>!Array.isArray(e)||e.length<2?kW(e,t):`${kW(e.slice(0,1),t)} +${e.length-1}`,xUt=g.createContext(null),Wk=()=>{const e=g.useContext(xUt);if(!e)throw new Error("FilterBarChip segments must be rendered inside <FilterBarChip>.");return e};function bbs(e){return e instanceof Element&&!!e.closest('[data-slot="filter-bar-editor"]')}function kx({item:e,readOnly:t=!1,removable:n=!0,draft:r=!1,className:s,children:i}){const o=eu(),[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 A=typeof I.getAnimations=="function"?I.getAnimations({subtree:!0}):[];if(A.length===0){y(e.id);return}let P=!1;return Promise.all(A.map(L=>L.finished)).then(()=>{P||y(e.id)}).catch(()=>{}),()=>{P=!0}},[p,e.id,y]);const x=u?o.getFieldOperators(u).length===1:!1,b=[u?.label??e.fieldId,x?"":d?.label??e.operatorId,r?"":kW(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=ybs(k,x),C=S?.glint??!1,T=g.useCallback(I=>{if(t||r||p||bbs(I.target))return;const A=Array.from(h.current?.querySelectorAll("[data-filter-bar-segment]")??[]),P=A.findIndex(L=>L===I.target);switch(I.key){case"ArrowRight":{I.preventDefault();const L=A[P+1];L?L.focus():o.focusChip(f+1,1,"field")||o.focusInput();return}case"ArrowLeft":{I.preventDefault();const L=A[P-1];L?L.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(kUt,{}),a.jsx(OUt,{}),a.jsx(jUt,{}),n&&a.jsx(CUt,{})]});return a.jsx(xUt.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(yUt,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(WJ,"pr-0 text-muted-foreground [--filter-bar-segment-padding:0.5rem_0]"),title:"This filter is locked",children:a.jsx(Au,{className:"size-[1.1em]"})}),N]})})}const bUt=g.createContext({highlighted:null});function ZNe({placeholder:e,icon:t=Su,inputMode:n,onKeyDown:r}){const{highlighted:s}=g.useContext(bUt);return a.jsxs("div",{className:ss.searchContainer,children:[a.jsx(t,{className:ss.searchIcon}),a.jsx(Oke,{className:ss.searchInput,placeholder:e,inputMode:n,...mp,onKeyDown:i=>r?.(i,s)})]})}function WNe({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=eu(),m=Wk(),v=J0(),y=m.openSegment===e,[x,b]=g.useState(null),S=e==="field",k=S?a.jsx(HJ,{field:m.field,label:t}):a.jsx("span",{className:"truncate",children:t});return m.readOnly||m.draft||m.leaving?a.jsx("span",{className:Z(WJ,S&&"text-foreground"),style:S?jye(m.field):void 0,title:n,children:k}):a.jsxs(bQ,{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)},...vUt,modal:!1,children:[a.jsx(Xkt,{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(eN,S&&"text-foreground"),style:S?jye(m.field):void 0}),children:k}),a.jsx(jke,{container:v,children:a.jsx(Cke,{align:"start",sideOffset:R_,positionMethod:Av,className:ss.positioner,children:a.jsx(_ke,{className:Z(ss.popup,"min-w-44"),"data-slot":"filter-bar-editor",children:a.jsx(bUt.Provider,{value:{highlighted:x},children:h})})})})]})}const wbs=e=>e.label,Sbs=e=>e.label,kbs=e=>e.label??e.value;function Obs(){const e=eu(),t=Wk(),[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?uUt(l):t.item.value}),t.setOpenSegment(null)},[e,t]);return a.jsxs(WNe,{segment:"field",ariaLabel:"Field",label:t.field?.label??t.item.fieldId,items:e.fields,itemToString:wbs,filter:QNe,value:t.field,query:n,onQueryChange:r,onSelect:s,children:[a.jsx(ZNe,{placeholder:"Change field…"}),a.jsx(JI,{"aria-label":"Fields",getKey:i=>i.id,renderOption:i=>a.jsx(HJ,{field:i}),emptyText:"No matching field."})]})}function jbs(){const e=eu(),t=Wk(),[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?uUt(o):t.item.value}),t.setOpenSegment(null)},[e,t]);return a.jsxs(WNe,{segment:"operator",ariaLabel:"Operator",label:t.operator?.label??t.item.operatorId,items:s,itemToString:Sbs,filter:QNe,value:t.operator,query:n,onQueryChange:r,onSelect:i,children:[a.jsx(ZNe,{placeholder:"Change operator…"}),a.jsx(JI,{"aria-label":"Operators",getKey:o=>o.id,renderOption:o=>o.label,emptyText:"No matching operator."})]})}function Cbs(){const e=eu(),t=Wk(),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=mUt({field:t.field,operator:t.operator,query:r,enabled:n,initialValue:t.item.value,setQuery:s,onCommit:o}),c=Nbs[t.field?.type??"text"];return a.jsx(WNe,{segment:"value",ariaLabel:"Value",label:xbs(t.item.value,t.field)||"…",fullLabel:kW(t.item.value,t.field)||"…",items:l.options,itemToString:kbs,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 wUt({step:e,onCancel:t}){const n=Wk(),r=zNe()?"⌘↵":"Ctrl ↵";return a.jsxs(a.Fragment,{children:[e.hasOptions&&a.jsx(JI,{"aria-label":"Values","aria-multiselectable":e.isMany||void 0,getKey:s=>s.value,renderOption:s=>a.jsx(fUt,{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(ue,{size:"sm",variant:"ghost",onClick:t,children:"Cancel"}),a.jsxs(ue,{size:"sm",variant:"default",onClick:()=>e.commitDone(),children:["Done",a.jsx(Wd,{size:"xs",children:r})]})]})]})}function _bs(e,t){return e.hasSuggestions?e.allowFreeText?`Search or type a ${t}…`:`Search ${t}s…`:`Type a ${t}…`}function SUt({step:e,onCancel:t,inputMode:n,noun:r}){return a.jsxs(a.Fragment,{children:[a.jsx(ZNe,{icon:e.hasSuggestions?Su:Bc,inputMode:n,placeholder:_bs(e,r),onKeyDown:(s,i)=>{const o=e.hasSuggestions?i:null;(e.handleKeyDown(s,o)||s.key==="Enter"&&o===null)&&s.preventBaseUIHandler()}}),a.jsx(wUt,{step:e,onCancel:t})]})}function Tbs(e){return a.jsx(SUt,{...e,noun:"value"})}function Ebs(e){return a.jsx(SUt,{...e,inputMode:"decimal",noun:"number"})}function Ibs(e){return a.jsx(wUt,{...e})}const Nbs={text:Tbs,number:Ebs,boolean:Ibs};function kUt(){return a.jsx(Obs,{})}function OUt(){const e=Wk();return e.operatorImplied||e.draft&&!e.operator?null:a.jsx(jbs,{})}function jUt(){const e=Wk();return e.draft||(e.operator?.arity??"one")==="none"?null:a.jsx(Cbs,{})}function CUt(){const e=eu(),t=Wk();if(t.readOnly||t.draft)return null;const n=Z(eN,"px-1.5 text-muted-foreground [--filter-bar-segment-padding:0.375rem]");if(t.leaving)return a.jsx("span",{className:n,children:a.jsx(zn,{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(zn,{className:"size-[1.1em]"})})}kx.Field=kUt;kx.Operator=OUt;kx.Value=jUt;kx.Remove=CUt;const Abs=e=>"label"in e&&e.label?e.label:"value"in e?e.value:"",Pbs=[],_Ut="__filter-bar-advanced__",$bs={id:_Ut,label:"Advanced filter…",icon:Ua,operators:[]};function TUt(e){return eu().inputTarget!==e.groupId?null:a.jsx(Rbs,{...e})}function Rbs({placeholder:e="Filter…",className:t,"aria-label":n="Add filter",groupId:r,onLeave:s}){const i=eu(),o=J0(),l=g.useRef(null),[c,u]=g.useState(!1),[d,f]=g.useState(""),[h,p]=g.useState(null),[m,v]=g.useState(!1),y=zNe()?"⌘↵":"Ctrl ↵",{draft:x,setDraft:b,commitDraft:S}=i,k=x?x.operatorId?"value":"operator":"field",j=x?i.getField(x.fieldId):void 0,C=x?.operatorId?i.getOperator(x.operatorId):void 0,T=g.useMemo(()=>j?i.getFieldOperators(j):[],[i,j]),_=i.groupsEnabled&&r===void 0,N=g.useMemo(()=>{const X=i.fields.filter(ee=>!ee.hidden);return _?[...X,$bs]:X},[i.fields,_]),I=r?sUt(i.expression,r):void 0;g.useEffect(()=>{r&&l.current?.focus()},[r]);const A=g.useCallback(X=>{So.flushSync(()=>v(!0)),X(),v(!1)},[]),P=g.useCallback(X=>A(()=>b(X)),[A,b]),L=g.useCallback(()=>{b(null),f("")},[b]),F=g.useCallback(()=>{u(!1),L()},[L]),Q=g.useCallback((X,ee,ie)=>{A(()=>S({fieldId:X,operatorId:ee},ie)),f(""),l.current?.focus()},[A,S]),q=g.useCallback((X,ee)=>{if(ee.arity==="none"){Q(X,ee.id,"");return}P({fieldId:X,operatorId:ee.id}),f("")},[Q,P]),B=g.useCallback(X=>{if(X.id===_Ut){const fe=i.addGroup(void 0,"or");i.setOpenGroup(fe),i.openGroupInput(fe),f(""),u(!1);return}const[ee,...ie]=i.getFieldOperators(X);if(X.search&&ee&&d.trim()!==""){Q(X.id,ee.id,xye(X.type,d));return}if(ee&&ie.length===0){q(X.id,ee);return}P({fieldId:X.id}),f("")},[i,Q,d,q,P]),V=mUt({field:j,operator:C,query:d,enabled:c&&k==="value",setQuery:f,onCommit:X=>{x?.operatorId&&Q(x.fieldId,x.operatorId,X)}}),H=g.useCallback(()=>r?(i.openGroupInput(void 0),s?.(),!0):!1,[i,r,s]),D=g.useCallback(()=>{if(k==="value"&&x){const X=j?T.length===1:!1;P(X?null:{fieldId:x.fieldId})}else k==="operator"?P(null):H()||u(!1);f("")},[k,x,j,T,P,H]),K=X=>{k==="field"?B(X):k==="operator"&&x?q(x.fieldId,X):V.handleSelect(X)},M=X=>{if(X.key==="Escape"){X.preventDefault(),X.stopPropagation(),X.preventBaseUIHandler(),D();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")D();else if(I){const ee=I.nodes.findLast(ie=>!i.leaving.has(ie.id));ee?i.removeItem(ee.id):H()}else{const ee=i.items.findLast(ie=>!i.leaving.has(ie.id));ee&&i.removeItem(ee.id)}return}if(X.key==="ArrowLeft"&&k==="field"){i.focusChip(i.items.length-1,-1,"remove")&&X.preventDefault();return}}if(c){if(X.key==="Tab"&&h&&k!=="value"&&(k==="operator"||d!=="")){X.preventDefault(),X.preventBaseUIHandler(),K(h);return}if(k==="value"){const ee=V.hasSuggestions?h:null;(V.handleKeyDown(X,ee)||X.key==="Enter"&&ee===null)&&X.preventBaseUIHandler()}}},$={field:N,operator:T,value:V.options},z=m?Pbs:$[k],U=g.useCallback((X,ee,ie)=>"search"in X&&X.search===!0||QNe(X,ee,ie),[]),G=k==="field"?"Search fields…":k==="operator"?"Search operators…":"Search values…",ne=k==="field"?e:k==="operator"?"Operator…":V.hasSuggestions&&V.allowFreeText?"Search or type a value…":j?.type==="number"?"Number…":"Value…";return a.jsx(a.Fragment,{children:a.jsxs(bQ,{items:z,itemToStringLabel:Abs,filter:k==="value"?null:U,value:null,onValueChange:(X,ee)=>{ee.cancel(),X&&K(X)},inputValue:d,onInputValueChange:(X,ee)=>{ee.reason==="input-change"&&(f(X),c||u(!0))},onItemHighlighted:X=>p(X??null),open:c,onOpenChange:(X,ee)=>{!X&&ee.reason==="escape-key"||!X&&ee.reason==="outside-press"&&ee.event.target instanceof Node&&l.current?.contains(ee.event.target)||(X?u(!0):F())},...vUt,modal:!1,children:[a.jsxs("div",{"data-slot":"filter-bar-input-trigger",className:Z(lOt({variant:"default",size:gUt}),"w-auto cursor-text","focus-within:bg-fill-hover",oCn,k==="field"?"min-w-40":"min-w-28",t),children:[a.jsx(Vht,{"aria-hidden":!0,className:"-ml-[.3em] shrink-0 text-muted-foreground"}),a.jsx(Oke,{ref:X=>{l.current=X,i.registerInput(X)},"aria-label":n,spellCheck:!1,...mp,"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(Z0e,"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:M})]}),a.jsx(jke,{container:o,children:a.jsx(Cke,{align:"start",sideOffset:R_,positionMethod:Av,className:ss.positioner,children:a.jsxs(_ke,{className:Z(ss.popup,"min-w-56"),"data-slot":"filter-bar-editor",children:[(k!=="value"||V.hasSuggestions)&&a.jsxs("div",{className:Z(ss.searchContainer,"cursor-text"),"data-slot":"filter-bar-search",onMouseDown:X=>X.preventDefault(),onClick:()=>l.current?.focus(),children:[a.jsx(Su,{className:ss.searchIcon}),a.jsx("span",{className:Z(ss.searchInput,"flex items-center truncate",d===""&&ss.placeholder),children:d===""?G:d})]}),k==="field"&&a.jsx(JI,{"aria-label":"Fields",getKey:X=>X.id,renderOption:X=>a.jsxs(a.Fragment,{children:[a.jsx(HJ,{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(JI,{"aria-label":"Operators",getKey:X=>X.id,renderOption:X=>X.label,emptyText:"No matching operator."}),k==="value"&&V.hasOptions&&a.jsx(JI,{"aria-label":"Values","aria-multiselectable":V.isMany||void 0,getKey:X=>X.value,renderOption:X=>a.jsx(fUt,{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(ue,{size:"sm",variant:"default",disabled:!V.canCommitQuery,onMouseDown:X=>X.preventDefault(),onClick:()=>V.submitFreeText(),children:["Apply",a.jsx(Wd,{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(ue,{size:"sm",variant:"default",onMouseDown:X=>X.preventDefault(),onClick:()=>V.commitDone(),children:["Done",a.jsx(Wd,{size:"xs",children:y})]})})]})})})]})})}function EUt(e,t,n){const{settleRemove:r}=eu();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 IUt="flex h-control-sm w-14 shrink-0 items-center justify-center rounded-md text-column tracking-wide text-muted-foreground uppercase";function Mbs({groupId:e,logic:t,className:n}){const r=eu(),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(IUt,"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 Dbs({groupId:e,logic:t}){const n=eu();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 NUt({group:e,depth:t,onRemove:n,removeLabel:r="Remove group",className:s}){const i=eu(),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:IUt,children:"where"},`${h}:where`):a.jsx(Mbs,{groupId:e.id,logic:e.logic},`${h}:logic`);for(const h of e.nodes)d.push(a.jsxs(g.Fragment,{children:[f(h.id),qa(h)?a.jsx(Lbs,{group:h,depth:t+1}):a.jsx(kx,{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(kx,{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(TUt,{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(ue,{ref:o,variant:"ghost",size:"sm",icon:a.jsx(ys,{}),onClick:()=>i.openGroupInput(e.id),children:"Condition"}),a.jsx(ue,{variant:"ghost",size:"sm",icon:a.jsx(jS,{}),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(ue,{variant:"ghost",size:"sm",icon:a.jsx(Xo,{}),className:"ml-auto text-muted-foreground","aria-label":r,onClick:n,children:"Clear all"})]})]})}function Lbs({group:e,depth:t}){const n=eu(),r=g.useRef(null),s=n.leaving.has(e.id);EUt(e.id,s,r);const i=BNe(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(xP,{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(Dbs,{groupId:e.id,logic:e.logic}),a.jsx(ue,{variant:"ghost",size:"icon-sm",tooltip:"Remove group",disabled:s,onClick:()=>n.removeGroup(e.id),children:a.jsx(Xo,{})})]})]}),a.jsx(NUt,{group:e,depth:t})]})}function AUt({group:e,className:t}){const n=eu(),r=g.useRef(null),s=g.useRef(null),i=n.leaving.has(e.id),o=n.openGroupId===e.id,l=BNe(e),c=n.items.findIndex(h=>PUt(e,h.id)),u=c===-1?n.items.length:c;EUt(e.id,i,r);const d=h=>{if(i)return;const p=Array.from(r.current?.querySelectorAll("[data-filter-bar-segment]")??[]),m=p.findIndex(v=>v===h.target);if(m!==-1)switch(h.key){case"ArrowRight":{h.preventDefault();const v=p[m+1];v?v.focus():n.focusChip(u+l,1,"field")||n.focusInput();return}case"ArrowLeft":{h.preventDefault();const v=p[m-1];v?v.focus():n.focusChip(u-1,-1,"remove");return}case"Delete":case"Backspace":h.preventDefault(),f();return}},f=()=>{n.removeGroup(e.id),n.focusAfterRemove(u)};return a.jsxs(jp,{open:o,onOpenChange:h=>n.setOpenGroup(h?e.id:null),children:[a.jsxs("div",{ref:r,role:"group","aria-label":`Advanced filter, ${l} ${l===1?"condition":"conditions"}`,"aria-hidden":i||void 0,"data-slot":"filter-bar-advanced","data-leaving":i||void 0,className:Z("filter-bar-advanced",yUt,i&&"pointer-events-none",t),onKeyDown:d,children:[a.jsxs(sf,{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(eN,"gap-1.5"),title:"Edit advanced filter",children:[a.jsx(Ua,{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(eN,"px-1.5"),children:a.jsx(zn,{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(eN,"px-1.5"),onClick:f,children:a.jsx(zn,{className:"size-[1.1em]"})})]}),a.jsxs(lh,{align:"start",className:"w-[min(92vw,44rem)] p-0",[VNe]:"advanced",finalFocus:s,children:[a.jsxs("div",{className:"flex items-center gap-2 border-b border-border px-3 py-2",children:[a.jsx(Ua,{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(ue,{variant:"ghost",size:"icon-sm",className:"ml-auto",tooltip:"Close",onClick:()=>n.setOpenGroup(null),children:a.jsx(zn,{})})]}),a.jsx(NUt,{group:e,depth:1,removeLabel:"Remove advanced filter",onRemove:()=>{n.setOpenGroup(null),f()}})]})]})}const PUt=(e,t)=>e.nodes.some(n=>n.id===t?!0:"kind"in n&&PUt(n,t));function zbs({label:e}){const t=eu();return t.hasRemovableItems?a.jsx(ue,{variant:"ghost",size:"icon-sm","aria-label":e,tooltip:e,onClick:n=>{n.stopPropagation(),t.clear(),t.focusInput()},children:a.jsx(zn,{})}):null}function Fbs({className:e,clearLabel:t,children:n}){const r=eu();return a.jsxs("div",{role:"group","aria-label":r.ariaLabel,"data-slot":"filter-bar",[VNe]:"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(zbs,{label:t})}),a.jsx(z0,{"aria-live":"polite",children:r.announcement})]})}function wu({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(hbs,{fields:e,operators:t,value:n,onValueChange:r,createItemId:s,maxDepth:i,ariaLabel:o,children:a.jsx(Fbs,{className:c,clearLabel:l,children:u})})}function Bbs({renderChip:e=Ubs}){const t=eu(),n=[];for(const r of t.expression.nodes){const s=qa(r)?a.jsx(AUt,{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(kx,{draft:!0,item:{id:r,fieldId:s,operatorId:i,value:""}})},r))}return a.jsx(a.Fragment,{children:n})}const Ubs=e=>a.jsx(kx,{item:e});wu.Chips=Bbs;wu.Chip=kx;wu.AdvancedChip=AUt;wu.Input=TUt;const Vbs=1440*60*1e3,Pz=({queryOptions:e}={})=>{const t=Ge();return _t({queryKey:["observability-capabilities"],queryFn:()=>t.getObservabilityCapabilities(),retry:!1,staleTime:Vbs,...e})},GJ=()=>{const{data:e,isLoading:t}=Pz();return{isLoading:t,enabled:!t&&(e?.capabilities.traceQuery??!0)}},qbs=()=>{const{data:e,isLoading:t}=Pz();return{isLoading:t,enabled:!t&&(e?.capabilities.traceQueryDiscovery??!0)}},Qbs=()=>{const{data:e,isLoading:t}=Pz();return{isLoading:t,enabled:!t&&(e?.capabilities.traceQueryRootDuration??!1)}},Zbs=()=>{const{data:e,isLoading:t}=Pz();return{isLoading:t,enabled:!t&&(e?.capabilities.feedback??!0)}};function Wbs(e){return e.startsWith("agent-")}function Hbs(e){return e.match(/^(?:mcp_)?tool:\s*'(.*?)'/)?.[1]??e}function $Ut(e){return RUt(e,[])}function RUt(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=Hbs(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,...Wbs(s)?{matchArgs:"ignore"}:{}})}!r&&n.children?.length&&RUt(n.children,t)}return t}function Gbs(e){const t=(()=>{try{const r=JSON.stringify(e.input);return r?r.length>40?`${r.slice(0,40)}…`:r:""}catch{return""}})(),n=Tv(e.id)??e.id;return t?`${n} — ${t}`:n}function Kbs({traceId:e,isOpen:t,onClose:n,level:r=2}){const s=Ge(),{data:i,isLoading:o}=_t({queryKey:["trace-trajectory",e],queryFn:()=>s.getTraceTrajectory(e??""),enabled:t&&!!e}),l=i?.steps?$Ut(i.steps):[],c=l.length>0?sv(l,2):"";return a.jsxs(xo,{dialogTitle:"Add Tool Mocks to Item",dialogDescription:"Append trace-derived tool mocks to an existing dataset item",isOpen:t,onClose:n,level:r,children:[a.jsxs(xo.Top,{children:[a.jsxs(cv,{children:[a.jsx(Fa,{})," ",Tv(e)]}),"›",a.jsxs(cv,{children:[a.jsx(dd,{})," Add Tool Mocks to Item"]})]}),a.jsxs(xo.Content,{children:[a.jsx(xo.Header,{children:a.jsxs(xo.Heading,{children:[a.jsx(dd,{})," Add Tool Mocks to Item"]})}),o?a.jsx(Y,{as:"p",variant:"body",tone:"muted",className:"px-2 py-4",children:"Loading tool calls from trace..."}):a.jsx(Ybs,{initialMocksJson:c,onClose:n},e??"no-trace")]})]})}function Ybs({initialMocksJson:e,onClose:t}){const[n,r]=g.useState(""),[s,i]=g.useState(""),[o,l]=g.useState(e),{data:c,isLoading:u}=Ek(),d=c?.datasets??[],{data:f=[],isLoading:h}=nA({datasetId:n,queryOptions:{enabled:!!n}}),{data:p,isFetching:m}=gOt({datasetId:n,itemId:s,queryOptions:{enabled:!!n&&!!s}}),{updateItem:v}=pl(),y=(()=>{if(!o.trim())return!1;try{const S=JSON.parse(o);return Array.isArray(S)&&S.length>0}catch{return!1}})(),x=S=>{r(S),i("")},b=async S=>{if(S.preventDefault(),!n||!s){Ye.error("Please select a dataset and an item");return}let k;try{const T=o.trim()?JSON.parse(o):[];if(!Array.isArray(T)){Ye.error("Tool Mocks must be a JSON array");return}k=T}catch{Ye.error("Tool Mocks must be valid JSON");return}if(k.length===0){Ye.error("There are no tool mocks to add");return}if(!p||p.id!==s){Ye.error("Item is still loading, please try again");return}const C=[...p.toolMocks??[],...k];try{await v.mutateAsync({datasetId:n,itemId:s,toolMocks:C}),Ye.success(`Added ${k.length} tool mock(s) to the item`),t()}catch(T){Ye.error(`Failed to add tool mocks: ${T instanceof Error?T.message:"Unknown error"}`)}};return a.jsxs(Ga,{onSubmit:b,children:[a.jsxs(ht,{children:[a.jsx(ut,{required:!0,children:"Dataset"}),a.jsxs(ps,{value:n,onValueChange:x,disabled:u,children:[a.jsx(gs,{children:a.jsx(ms,{placeholder:u?"Loading datasets...":"Select a dataset"})}),a.jsx(vs,{children:d.length===0?a.jsx(Y,{as:"p",variant:"body",tone:"muted",className:"px-2 py-4 text-center",children:"No datasets available"}):d.map(S=>a.jsx(hr,{value:S.id,children:S.name},S.id))})]})]}),a.jsxs(ht,{children:[a.jsx(ut,{required:!0,children:"Item"}),a.jsxs(ps,{value:s,onValueChange:i,disabled:!n||h,children:[a.jsx(gs,{children:a.jsx(ms,{placeholder:n?h?"Loading items...":"Select an item":"Select a dataset first"})}),a.jsx(vs,{children:f.length===0?a.jsx(Y,{as:"p",variant:"body",tone:"muted",className:"px-2 py-4 text-center",children:"No items available"}):f.map(S=>a.jsx(hr,{value:S.id,children:Gbs(S)},S.id))})]})]}),a.jsxs(ht,{children:[a.jsx(ut,{children:"Tool Mocks (JSON)"}),a.jsx(Or,{value:o,onChange:l,showCopyButton:!1,className:"min-h-40"}),a.jsx(no,{children:"Seeded from the trace's tool calls. Edit or remove entries before appending."})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[a.jsx(ue,{icon:a.jsx(zn,{}),type:"button",onClick:t,children:"Cancel"}),a.jsx(ue,{icon:a.jsx(ys,{}),type:"submit",variant:"default",disabled:v.isPending||m||!y||!n||!s||p?.id!==s,children:v.isPending?"Adding...":"Append Tool Mocks"})]})]})}function Xbs(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 sv(r,2)}function Jbs({traceDetails:e,rootSpanId:t,traceId:n,isOpen:r,onClose:s,level:i=2}){const o=Ge(),{data:l}=CNe({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}=_t({queryKey:["trace-trajectory",n],queryFn:()=>o.getTraceTrajectory(n??""),enabled:r&&!!n}),f=u?.steps&&u.steps.length>0?sv({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?$Ut(u.steps):[],p=h.length>0?sv(h,2):void 0;return a.jsx(C9t,{initialInput:Xbs(c),initialGroundTruth:c?.output!=null?sv(c.output,2):"",initialTrajectory:f,trajectoryLoading:d,initialToolMocks:p,breadcrumb:a.jsxs(cv,{children:[a.jsx(Fa,{})," ",Tv(n)]}),isOpen:r,onClose:s,level:i,source:n?{type:"trace",referenceId:n}:void 0})}const e0s={"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"},Yce="Pick a wider time range — older traces may fall outside the current window.";function t0s({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No traces for ${e0s[e]}`,description:Yce}:t&&n?{title:`No traces between ${Jr(t,"date-time")} and ${Jr(n,"date-time")}`,description:Yce}:t?{title:`No traces since ${Jr(t,"date-time")}`,description:Yce}:{title:"No traces yet",description:"Traces will appear here once agents, workflows, or tools are executed."}}const n0s=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=t0s({datePreset:e,dateFrom:t,dateTo:n});return a.jsx(Xt,{titleSlot:r,descriptionSlot:s,variant:"fill"})};function MUt({queryOptions:e}={}){const t=Ge(),n=mr();return Sn({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 r0s(e){return e==="needs-review"?"warning":e==="complete"||e==="reviewed"?"success":"neutral"}function HNe({status:e,children:t,...n}){return a.jsx(Mt,{size:"xs",...n,variant:r0s(e),children:t??e})}function s0s(e){const t=e.author;return t?t.name||t.email||t.id:void 0}const DUt=g.createContext(null);function aT(){const e=g.useContext(DUt);if(!e)throw new Error("Comment compounds must be rendered within Comment");return e}const i0s=md("flex flex-col",{variants:{variant:{default:"gap-2",embed:Z(pr,"gap-1 rounded-xl p-3"),thread:""}},defaultVariants:{variant:"default"}}),LUt=g.forwardRef(({className:e,variant:t="default",...n},r)=>a.jsx(DUt.Provider,{value:t,children:a.jsx("div",{ref:r,"data-slot":"comment","data-variant":t,className:Z(i0s({variant:t}),e),...n})}));LUt.displayName="Comment";const o0s={default:"gap-3",embed:"gap-2",thread:""},zUt=g.forwardRef(({className:e,...t},n)=>{const r=aT();return a.jsx("ul",{ref:n,"data-slot":"comment-list",className:Z("flex flex-col",o0s[r],e),...t})});zUt.displayName="CommentList";const a0s={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"},Cye=g.forwardRef(({className:e,continued:t=!1,highlighted:n=!1,...r},s)=>{const i=aT(),o=i==="thread"?"div":"li";return a.jsx(o,{ref:s,"data-slot":"comment-item",className:Z("group/comment-item",a0s[i],i==="thread"&&(t?"py-0.5":"py-1.5"),n&&"bg-info-subtle",e),...r})});Cye.displayName="CommentItem";const FUt=g.forwardRef(({className:e,...t},n)=>a.jsx("div",{ref:n,"data-slot":"comment-item-avatar",className:Z("w-6 shrink-0 pt-0.5",e),...t}));FUt.displayName="CommentItemAvatar";const BUt=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}));BUt.displayName="CommentItemContent";const l0s={default:"flex items-center gap-2",embed:"flex items-center gap-2",thread:"flex items-baseline gap-1.5"},_ye=g.forwardRef(({className:e,...t},n)=>{const r=aT();return a.jsx("div",{ref:n,"data-slot":"comment-item-header",className:Z(l0s[r],e),...t})});_ye.displayName="CommentItemHeader";const c0s={default:"subheading",embed:"subheading",thread:"column"},u0s={default:"text-foreground",embed:"text-foreground",thread:"truncate text-foreground"},UUt=g.forwardRef(({className:e,...t},n)=>{const r=aT();return a.jsx(Y,{ref:n,as:"span",variant:c0s[r],"data-slot":"comment-item-author",className:Z(u0s[r],e),...t})});UUt.displayName="CommentItemAuthor";const d0s={default:"text-caption text-muted-foreground",embed:"text-caption text-muted-foreground",thread:"text-meta text-placeholder shrink-0"},VUt=g.forwardRef(({className:e,...t},n)=>{const r=aT();return a.jsx("time",{ref:n,"data-slot":"comment-item-timestamp",className:Z(d0s[r],e),...t})});VUt.displayName="CommentItemTimestamp";const f0s={default:"body",embed:"body",thread:"caption"},h0s={default:"whitespace-pre-wrap text-foreground border-l border-border pl-3",embed:"whitespace-pre-wrap text-foreground",thread:""},qUt=g.forwardRef(({className:e,...t},n)=>{const r=aT();return mwe({defaultTagName:r==="thread"?"div":"p",props:{...t,ref:n,"data-slot":"comment-item-body",className:Z(Ma({variant:f0s[r]}),h0s[r],e)}})});qUt.displayName="CommentItemBody";const p0s={default:"flex items-center gap-1 opacity-0 group-focus-within/comment-item:opacity-100 group-hover/comment-item:opacity-100 motion-safe:transition-opacity",embed:"",thread:"ml-auto flex shrink-0 items-center gap-0.5 self-center transition-opacity duration-200 ease-out motion-reduce:transition-none pointer-fine:opacity-0 pointer-fine:group-focus-within/comment-item:opacity-100 pointer-fine:group-hover/comment-item:opacity-100"},QUt=g.forwardRef(({className:e,...t},n)=>{const r=aT();return r==="embed"?null:a.jsx("div",{ref:n,"data-slot":"comment-item-actions",className:Z(p0s[r],e),...t})});QUt.displayName="CommentItemActions";function m0s({status:e}){const t=e==="reviewed"?"reviewed":"needs-review";return a.jsx(HNe,{"data-slot":"feedback-review-status",status:t,children:t==="reviewed"?"Reviewed":"Needs review"})}function g0s(e){const t=e.comment||(typeof e.value=="string"?e.value:"");return t||(e.feedbackType==="thumbs"?e.value===1?"👍":"👎":String(e.value??""))}function v0s({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=s0s(l),f=d?a.jsx(KS,{name:d,src:l.author?.avatarUrl,size:"sm"}):null,h=d&&a.jsx(UUt,{children:d}),p=a.jsx(VUt,{dateTime:u.toISOString(),children:Jr(u,"date-time")}),m=l.feedbackId,v=a.jsx(m0s,{status:l.reviewStatus}),y=!!(s&&m&&l.reviewStatus!=="reviewed"),x=!!(n&&m),b=m&&(y||x)&&a.jsx(QUt,{children:a.jsxs(ct,{children:[a.jsx(ct.Trigger,{render:a.jsx(ue,{size:"icon-sm",variant:"ghost","aria-label":"Feedback actions",children:a.jsx(TN,{})})}),a.jsxs(ct.Content,{align:"end",children:[y&&a.jsxs(ct.Item,{disabled:i===m,onSelect:()=>s?.(m),children:[a.jsx(At,{size:"xs",children:a.jsx(Iht,{})}),"Mark reviewed"]}),x&&a.jsxs(ct.Item,{disabled:r,onSelect:()=>n?.(m),children:[a.jsx(At,{size:"xs",children:a.jsx(Xo,{})}),"Delete feedback"]})]})]})}),S=a.jsx(qUt,{children:g0s(l)}),k=m??`${l.traceId}-${c}`;return e==="thread"?a.jsxs(Cye,{children:[f&&a.jsx(FUt,{children:f}),a.jsxs(BUt,{children:[a.jsxs(_ye,{children:[h,p,v,b]}),S]})]},k):a.jsxs(Cye,{children:[a.jsxs(_ye,{children:[f,h,p,v,b]}),S]},k)});return e==="thread"?a.jsx(a.Fragment,{children:o}):a.jsx(zUt,{children:o})}function ZUt({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(LUt,{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(EAt,{size:"sm",children:[a.jsx(IAt,{"aria-label":"Leave feedback",placeholder:"Leave feedback...",value:d,onChange:S=>f(S.target.value)}),a.jsx(rge,{align:"inline-end",children:a.jsx(NAt,{type:"submit","aria-label":"Send feedback",disabled:m,children:a.jsx(vk,{})})})]})}),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(v0s,{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(ue,{icon:a.jsx(mP,{}),size:"sm",variant:"ghost",disabled:y===0,onClick:()=>n?.(y-1),children:"Previous"}),a.jsx(ue,{icon:a.jsx(Dc,{}),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(ue,{icon:a.jsx(Xo,{}),variant:"primary",disabled:o,onClick:b,children:o?"Deleting…":"Delete"})]})]})})]})}function WUt({traceId:e,spanId:t}){const[n,r]=g.useState(0),{data:s,isLoading:i}=TNe({traceId:e,spanId:t,page:n,queryOptions:{enabled:!!e&&!!t}}),{mutateAsync:o,isPending:l}=jBt({traceId:e,spanId:t}),{mutateAsync:c,isPending:u}=CBt({traceId:e,spanId:t}),d=MUt();return a.jsx(ZUt,{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 y0s=["type","input","duration","endTime","environment","inputTokens","outputTokens","totalTokens","estimatedCost"],GNe=["inputTokens","outputTokens","totalTokens","estimatedCost"],HUt=["traceId","threadId","resourceId","entityId"],GUt={traceId:"Trace ID",threadId:"Thread ID",resourceId:"Resource ID",entityId:"Primitive ID"},n0={visibleColumns:["type","input","duration","estimatedCost"],customColumns:[],metadataKeys:[]},KUt=3,x0s=new Set([2,KUt]),b0s=new Set(y0s),w0s=new Set(GNe),S0s=new Set(HUt);function k0s(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function O0s(e){return typeof e=="string"&&b0s.has(e)}function j0s(e){return typeof e=="string"&&S0s.has(e)}function C0s(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 _0s(e){if(!e)return n0;try{const t=JSON.parse(e);if(!k0s(t)||!x0s.has(t.version))return n0;const n=Array.isArray(t.visibleColumns)?[...new Set(t.visibleColumns.filter(O0s))]:[...n0.visibleColumns],r=Array.isArray(t.customColumns)?[...new Set(t.customColumns.filter(j0s))]:[];return{visibleColumns:n,customColumns:r,metadataKeys:C0s(t.metadataKeys)}}catch{return n0}}function T0s(e){return JSON.stringify({version:KUt,visibleColumns:e.visibleColumns,customColumns:e.customColumns,metadataKeys:e.metadataKeys})}function E0s(e){const t=new Set(e.visibleColumns),n=["startTime"];t.has("type")&&n.push("type"),n.push("name"),t.has("input")&&n.push("input"),n.push("status");for(const r of["duration","endTime","environment",...GNe])t.has(r)&&n.push(r);return n.push(...e.customColumns.map(r=>`custom:${r}`)),n.push(...e.metadataKeys.map(r=>`metadata:${r}`)),n}function YUt(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 I0s=/^(?:agent|workflow|scorer) run: '(.+?)'(.*)$/;function N0s(e){return e&&e.replace(I0s,"$1$2")}function A0s(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 jc(e,t){return e.visibleColumns.includes(t)}function P0s(e){return e.visibleColumns.some(XUt)}function XUt(e){return w0s.has(e)}const $0s=[],R0s=["type","input","duration","endTime","environment"],ntt={type:"Primitive type",input:"Input",duration:"Duration",endTime:"End",environment:"Environment",inputTokens:"Input tokens",outputTokens:"Output tokens",totalTokens:"Total tokens",estimatedCost:"Estimated cost"};function M0s({preferences:e,availableMetadataKeys:t=$0s,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(ct,{children:[a.jsx(ct.Trigger,{render:a.jsx(ue,{variant:"ghost",size:"md",icon:a.jsx(Aht,{"aria-hidden":!0}),children:"Columns"})}),a.jsxs(ct.Content,{align:"end",className:"min-w-56",children:[a.jsx(ct.Label,{children:"Standard columns"}),R0s.map(S=>a.jsx(ct.CheckboxItem,{checked:e.visibleColumns.includes(S),onCheckedChange:()=>s(S),children:ntt[S]},S)),a.jsx(ct.Separator,{}),a.jsx(ct.Label,{children:"Usage columns"}),GNe.map(S=>a.jsx(ct.CheckboxItem,{checked:e.visibleColumns.includes(S),disabled:!!n,onCheckedChange:()=>s(S),children:ntt[S]},S)),n&&a.jsx(Y,{variant:"meta",tone:"faint",className:"px-2 py-1",role:"note",children:n}),a.jsx(ct.Separator,{}),a.jsx(ct.Label,{children:"Custom columns"}),HUt.map(S=>{const k=e.customColumns.includes(S);return a.jsx(ct.CheckboxItem,{checked:k,onCheckedChange:()=>k?o(S):i(S),children:GUt[S]},S)}),(r||e.metadataKeys.length>0)&&a.jsxs(a.Fragment,{children:[a.jsx(ct.Separator,{}),a.jsx(ct.Label,{children:"Metadata columns"}),e.metadataKeys.map(S=>a.jsx(ct.CheckboxItem,{checked:!0,title:S,onCheckedChange:()=>c(S),children:S},S)),r&&a.jsxs(ct.Item,{onSelect:()=>f(!0),children:[a.jsx(ys,{"aria-hidden":!0}),"Add metadata column"]})]}),a.jsx(ct.Separator,{}),a.jsx(ct.Item,{onSelect:u,children:"Reset to defaults"})]})]}),r&&a.jsx(Kr,{open:d,onOpenChange:x,children:a.jsx(Yr,{children:a.jsxs(Ga,{onSubmit:b,className:"gap-0",children:[a.jsxs(Xr,{children:[a.jsx(Qr,{children:"Add metadata column"}),a.jsx(Lo,{children:"Pick a top-level trace metadata key observed in the current time range, or type one. Only the key is saved, never its values."})]}),a.jsx(qr,{children:a.jsxs(ht,{invalid:!!m,children:[a.jsx(ut,{children:"Metadata key"}),a.jsx(fl,{options:y,value:h,onValueChange:S=>{p(S),v(void 0)},allowCustomValue:!0,placeholder:"Select a metadata key…",searchPlaceholder:"Search metadata keys…",emptyText:"No metadata keys observed. Type one to add it."}),a.jsx(ns,{children:m})]})}),a.jsxs(Yo,{children:[a.jsx(Ca,{children:"Cancel"}),a.jsx(ja,{type:"submit",children:"Add column"})]})]})})})]})}function OW({traceId:e,variant:t}){const[n,r]=g.useState(0),{data:s,isLoading:i}=UJ({traceId:e,page:n,queryOptions:{enabled:!!e}}),{mutateAsync:o,isPending:l}=jBt({traceId:e}),{mutateAsync:c,isPending:u}=CBt({traceId:e}),d=MUt();return a.jsx(ZUt,{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 UA="timeRange",Tye={id:UA,label:"Time",icon:zBt(UA),color:PNe(),type:"text",operators:["is"],hidden:!0},jW={id:UA,fieldId:UA,operatorId:"is",value:""},D0s=e=>e instanceof HTMLElement&&e.hasAttribute("data-filter-bar-segment");function L0s(e){const t=eu();return a.jsxs(kx,{item:jW,removable:!1,children:[a.jsx("span",{className:Z(WJ,"text-foreground"),style:jye(Tye),children:a.jsx(HJ,{field:Tye})}),a.jsx("div",{className:"contents",onKeyDown:n=>{D0s(n.target)||n.stopPropagation()},children:a.jsx(KY,{...e,renderTrigger:({label:n,disabled:r})=>a.jsx("button",{type:"button",ref:s=>t.registerSegment(jW.id,"value",s),"data-filter-bar-segment":"",disabled:r,"aria-label":`Value: ${n}`,title:n,className:eN,children:a.jsx("span",{className:"truncate",children:n})})})})]})}function KNe({error:e,resource:t,errorTitle:n}){if(Cs(e))return a.jsx(ui,{});if(_s(e))return a.jsx(Gs,{resource:t});const r=e instanceof Error?gLr(e):void 0;return a.jsx(Xt,{tone:"error",titleSlot:n,descriptionSlot:r?.error??"Unknown error"})}function z0s(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 bE(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 rtt(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const F0s=(e,t)=>Math.abs(e-t)<1.01,B0s=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}};let $M;const Xce=()=>{if($M!==void 0)return $M;if(typeof navigator>"u")return $M=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return $M=!0;const e=navigator.maxTouchPoints;return $M=navigator.platform==="MacIntel"&&e!==void 0&&e>0},stt=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},U0s=e=>e,V0s=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},q0s=(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(stt(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(stt(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return i.observe(n,{box:"border-box"}),()=>{i.unobserve(n)}},CW={passive:!0},Q0s=typeof window>"u"?!0:"onscrollend"in window,Z0s=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const s=e.targetWindow;if(!s)return;const i=e.options.useScrollendEvent&&Q0s;let o=0;const l=i?null:B0s(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,CW),i&&r.addEventListener("scrollend",d,CW),()=>{r.removeEventListener("scroll",u),i&&r.removeEventListener("scrollend",d)}},W0s=(e,t)=>Z0s(e,t,n=>{const{horizontal:r,isRtl:s}=e.options;return r?n.scrollLeft*(s&&-1||1):n.scrollTop}),H0s=(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"]},G0s=(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})},K0s=G0s;class Y0s{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:U0s,rangeExtractor:V0s,onChange:()=>{},measureElement:H0s,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=bE(()=>(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,!(!Xce()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};i.addEventListener("touchstart",o,CW),i.addEventListener("touchend",l,CW),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&&(Xce()&&(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=bE(()=>[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=bE(()=>[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=z0s(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=bE(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,i)=>n.length===0||r===0?(this.range=null,null):(this.range=J0s(n,r,s,i,i===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=bE(()=>{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=bE(()=>[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=JUt(0,r.length-1,i?l=>s[l*2]:l=>rtt(r[l]).start,n);return rtt(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&&(Xce()&&(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&&F0s(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 JUt=(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 X0s(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 J0s(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=X0s(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=JUt(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 Jce=typeof document<"u"?g.useLayoutEffect:g.useEffect;function ews({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const s=g.useReducer(u=>u+1,0)[1],i=g.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});i.current.enabled=t,i.current.mode=n;const o=u=>{const d=i.current;if(!d.enabled||!d.container)return;const f=u.getTotalSize();if(f!==d.lastSize){d.lastSize=f;const x=u.options.horizontal?"width":"height";d.container.style[x]=`${f}px`}const h=!!u.options.horizontal,p=d.mode==="transform",m=h?"left":"top",v=u.options.scrollMargin,y=u.getVirtualItems();for(const x of y){const b=x.start-v,S=u.elementsCache.get(x.key);S&&d.lastPositions.get(S)!==b&&(d.lastPositions.set(S,b),p?S.style.transform=h?`translate3d(${b}px, 0, 0)`:`translate3d(0, ${b}px, 0)`:S.style[m]=`${b}px`)}},l={...r,onChange:(u,d)=>{var f;const h=i.current;let p=!0;if(h.enabled){o(u);const m=u.range,v=h.prevRange;p=!v||v.isScrolling!==u.isScrolling||v.startIndex!==m?.startIndex||v.endIndex!==m?.endIndex,p&&(h.prevRange=m?{startIndex:m.startIndex,endIndex:m.endIndex,isScrolling:u.isScrolling}:null)}p&&(e&&d?So.flushSync(s):s()),(f=r.onChange)==null||f.call(r,u,d)}},[c]=g.useState(()=>{const u=new Y0s(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),Jce(()=>c._didMount(),[]),Jce(()=>c._willUpdate()),Jce(()=>{o(c)}),c}function eVt(e){return ews({observeElementRect:q0s,observeElementOffset:W0s,scrollToFn:K0s,...e})}function _W(e,t){const n=BS(e)?.getTime(),r=BS(t)?.getTime();if(!(n===void 0||r===void 0||r<n))return r-n}function tws(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 nws(e){return e?.attributes?.finishReason==="length"}function rws(e){const t=e?.attributes?.usage;if(!t)return"The model stopped generating because it reached the maximum token limit. The response was truncated and may be incomplete.";const n=t.inputTokens??0,r=t.outputTokens??0,s=t.totalTokens??n+r;return n>0||r>0?`The model stopped generating because it reached the maximum token limit. The response was truncated and may be incomplete.
|
|
677
677
|
|
|
678
678
|
Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generating because it reached the maximum token limit (${s} tokens). The response was truncated and may be incomplete.`}const sws=new Intl.NumberFormat("en-US",{notation:"compact",maximumSignificantDigits:3}),iws=new Intl.NumberFormat("en-US"),ows=new Set(Intl.supportedValuesOf("currency"));function tVt(e){return e!==void 0&&ows.has(e.toUpperCase())}function Eye(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:e,...t})}function zD(e,{currency:t}={}){if(!tVt(t))return sws.format(e);const n=Math.abs(e);return n<100?aws(e,{currency:t}):n<1e3?Eye(t,{maximumFractionDigits:0}).format(e):Eye(t,{notation:"compact",maximumSignificantDigits:3}).format(e)}function aws(e,{currency:t}={}){if(!tVt(t))return iws.format(e);const n=Eye(t,{}),r=10**-(n.resolvedOptions().maximumFractionDigits??2);return e!==0&&Math.abs(e)<r?`${e<0?"-":""}<${n.format(r)}`:n.format(e)}function nVt(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 lws=36,cws=8,uws=20;function dws(e,t){return e[t]}function fws(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>=uws)break}return[...n]}function hws(e){if(!(e?.inputTokens===void 0&&e?.outputTokens===void 0))return(e?.inputTokens??0)+(e?.outputTokens??0)}function pws({traces:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,filtersApplied:i,featuredTraceId:o,featuredSpanId:l,isBranchesMode:c,recentlyAddedKeys:u,columnPreferences:d=n0,usageByTraceId:f,onTraceClick:h,createdSort:p,onSortChange:m,onFilterByField:v,listId:y="all-traces"}){const x=g.useRef(null),b=YUt(d),S=E0s(d),k=eVt({count:e.length,getScrollElement:()=>x.current,estimateSize:()=>lws,overscan:cws}),{getRowProps:j}=Fu({count:e.length,containerRef:x,onNavigate:I=>k.scrollToIndex(I),global:!0}),C=k.getVirtualItems(),T=k.getTotalSize(),_=C[0]?.start??0,N=C.length>0?Math.max(0,T-(C[C.length-1]?.end??0)):0;return a.jsxs(Yi,{reorderable:!0,id:y,columns:b,columnKeys:S,fit:"container",scrollRef:x,className:"min-w-0",children:[a.jsxs(Yi.Top,{children:[m?a.jsx(Yi.SortableTopCell,{sortKey:"startedAt",sort:p,onSortChange:m,children:"Start"}):a.jsx(Yi.TopCell,{children:"Start"}),jc(d,"type")&&a.jsx(Yi.TopCell,{children:"Primitive type"}),a.jsx(Yi.TopCell,{children:"Primitive name"}),jc(d,"input")&&a.jsx(Yi.TopCell,{children:"Input"}),a.jsx(Yi.TopCell,{children:"Status"}),jc(d,"duration")&&a.jsx(Yi.TopCell,{className:"justify-end text-right",children:"Duration"}),jc(d,"endTime")&&a.jsx(Yi.TopCell,{children:"End"}),jc(d,"environment")&&a.jsx(Yi.TopCell,{children:"Environment"}),jc(d,"inputTokens")&&a.jsx(Yi.TopCell,{className:"justify-end text-right",children:"Input tokens"}),jc(d,"outputTokens")&&a.jsx(Yi.TopCell,{className:"justify-end text-right",children:"Output tokens"}),jc(d,"totalTokens")&&a.jsx(Yi.TopCell,{className:"justify-end text-right",children:"Total tokens"}),jc(d,"estimatedCost")&&a.jsx(Yi.TopCell,{className:"justify-end text-right",children:"Est. cost"}),d.customColumns.map(I=>{const A=GUt[I],P=v?fws(e,I):[];return!v||P.length===0?a.jsx(Yi.TopCell,{children:A},I):a.jsx(Yi.TopCell,{className:"overflow-visible",children:a.jsxs(ct,{children:[a.jsx(ct.Trigger,{render:a.jsxs("button",{type:"button",className:Z("flex min-w-0 items-center gap-1 rounded-sm hover:text-foreground",ji),children:[a.jsx("span",{className:"min-w-0 truncate",children:A}),a.jsx(Vht,{"aria-hidden":!0,className:"size-[1.2em] shrink-0"})]})}),a.jsxs(ct.Content,{align:"start",children:[a.jsx(ct.Label,{children:"Filter by value"}),P.map(L=>a.jsx(ct.Item,{onSelect:()=>v(I,L),children:a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",className:"min-w-0 truncate",children:L})},L))]})]})},I)}),d.metadataKeys.map(I=>a.jsx(Yi.TopCellWithTooltip,{tooltip:I,children:I},I))]}),t?a.jsx(TAt,{columnCount:gCe(b).length}):e.length===0?a.jsx(Yi.NoMatch,{message:i?"No traces found for applied filters":"No traces found yet"}):a.jsxs(a.Fragment,{children:[a.jsx(Yi.Spacer,{height:_}),C.map(I=>{const A=e[I.index];if(!A)return null;const P=A.traceId===o&&(l==null||A.spanId===l),L=`${A.traceId}:${A.spanId??""}`,F=u?.has(L)??!1,Q=A.startedAt??A.createdAt,q=f?.get(A.traceId);return a.jsxs(Yi.RowButton,{ref:k.measureElement,"data-index":I.index,...j(I.index),onClick:()=>h(A),featured:P,className:Z(F&&"animate-row-highlight"),children:[a.jsx(Yi.CreatedCell,{timestamp:Q,preset:"day-time-seconds"}),jc(d,"type")&&a.jsx(Yi.TypeCell,{entityType:A.entityType}),a.jsx(Yi.NameCell,{name:A.entityName||A.name,parentSpanId:A.parentSpanId,showLevelTooltip:c}),jc(d,"input")&&a.jsx(Yi.InputCell,{input:A.inputPreview??tws(A.input)}),a.jsx(Yi.StatusCell,{status:A.status}),jc(d,"duration")&&a.jsx(_e.NumberCell,{font:"mono",children:Vc(_W(A.startedAt,A.endedAt))}),jc(d,"endTime")&&a.jsx(Yi.CreatedCell,{timestamp:A.endedAt??"",preset:"day-time-seconds"}),jc(d,"environment")&&a.jsx(_e.TextCell,{children:A.environment||"—"}),jc(d,"inputTokens")&&a.jsx(_e.NumberCell,{children:q?.inputTokens===void 0?void 0:zD(q.inputTokens)}),jc(d,"outputTokens")&&a.jsx(_e.NumberCell,{children:q?.outputTokens===void 0?void 0:zD(q.outputTokens)}),jc(d,"totalTokens")&&a.jsx(_e.NumberCell,{children:(()=>{const B=hws(q);return B===void 0?void 0:zD(B)})()}),jc(d,"estimatedCost")&&a.jsx(_e.NumberCell,{children:q?.estimatedCost===void 0?void 0:nVt(q.estimatedCost,q.costUnit)}),d.customColumns.map(B=>a.jsx(_e.TextCell,{font:"mono",children:dws(A,B)??void 0},B)),d.metadataKeys.map(B=>{const V=A0s(A.metadata,B);return a.jsx(_e.TextCell,{font:"mono",children:V},B)})]},L)}),a.jsx(Yi.Spacer,{height:N}),a.jsx(Yi.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})]})}function mws({columnPreferences:e=n0}){const t=YUt(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(xt,{className:"h-control-md min-w-64 flex-1"}),a.jsx(xt,{className:"h-control-md w-28"})]}),a.jsx(Lu,{columns:t,fit:"container"})]})}function eue(e){if(typeof window>"u")return n0;try{return _0s(window.localStorage.getItem(e)??void 0)}catch{return n0}}function gws(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,T0s(t))}catch{}}function vws(){const e=Svs(),[t,n]=g.useState(()=>({storageKey:e,preferences:eue(e),shouldPersist:!1})),r=t.storageKey===e?t.preferences:eue(e);g.useEffect(()=>{t.storageKey===e&&t.shouldPersist&&gws(e,t.preferences)},[t,e]);const s=f=>{n(h=>{const p=h.storageKey===e?h.preferences:eue(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(()=>n0)}}function itt(e,t){if(!t?.length)return e;const n=new URLSearchParams(e);for(const r of t)n.delete(r),n.delete(sS(r));return n}function yws(e,t,n){const{storageKey:r,skipHydration:s,excludeParams:i}=n??{},o=g.useRef(!1);return g.useEffect(()=>{if(s||o.current||(o.current=!0,qvs(e)))return;const l=Vvs(r),c=l&&itt(l,i);c?.toString()&&t(u=>{const d=new URLSearchParams(u);for(const[f,h]of c)d.append(f,h);return d},{replace:!0})},[]),g.useCallback((l,c)=>{t(u=>{const d=typeof l=="function"?l(u):l;return Bvs(itt(d,i),r),d},c)},[t,r,i])}function xws(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 jU="traceId",Ab="spanId",yy="tab",tue="spanView",xy="scoreId",z2="highlightSpanIds",RM=1440*60*1e3,bws={"last-24h":RM,"last-3d":3*RM,"last-7d":7*RM,"last-14d":14*RM,"last-30d":30*RM};function wE(e){e.delete(jU),e.delete(Ab),e.delete(OU),e.delete(yy),e.delete(xy),e.delete(z2)}function wws(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const z=e.get(F1);return z&&z!=="all"&&Lvs.has(z)?z:"last-7d"},[e]),i=e.get(x1),o=e.get(b1),l=g.useMemo(()=>{if(s==="custom"){if(!i)return;const U=new Date(i);return Number.isNaN(U.getTime())?void 0:U}const z=bws[s];return z?new Date(Date.now()-z):void 0},[s,i]),c=g.useMemo(()=>{if(s!=="custom"||!o)return;const z=new Date(o);return Number.isNaN(z.getTime())?void 0:z},[s,o]),u=g.useRef(s);u.current=s;const d=e.get(jU)||void 0,f=e.get(Ab)||void 0,h=e.get(OU)||void 0,p=e.get(yy),m=p==="feedback"?"feedback":p==="details"?"details":void 0,v=e.get(tue)==="timeline"?"timeline":"tree",y=e.get(xy)||void 0,x=e.get(z2),b=g.useMemo(()=>x?x.split(",").filter(Boolean):[],[x]),S=g.useMemo(()=>{const z=e.get(z1);return z&&Dvs.has(z)?z:"traces"},[e]),k=g.useMemo(()=>$Bt.find(z=>z.entityType===e.get(w$)),[e]),j=g.useMemo(()=>{const z=e.get(S$);return z&&Fvs.has(z)?z:void 0},[e]),C=g.useMemo(()=>lys(e),[e]),T=g.useMemo(()=>RNe(e),[e]),_=g.useCallback((z,U,G)=>{t(ne=>{const X=new URLSearchParams(ne);return z?X.set(jU,z):X.delete(jU),U?X.set(Ab,U):X.delete(Ab),G?X.set(OU,G):X.delete(OU),X.delete(yy),X.delete(xy),X.delete(z2),X},{replace:!0})},[t]),N=g.useCallback(()=>_(""),[_]),I=g.useCallback(z=>{const U=e.get(Ab)||null;z!==U&&t(G=>{const ne=new URLSearchParams(G);return z?ne.set(Ab,z):ne.delete(Ab),ne.delete(yy),ne.delete(xy),ne},{replace:!0})},[e,t]),A=g.useCallback(()=>I(null),[I]),P=g.useCallback(z=>{t(U=>{const G=new URLSearchParams(U);return z==="timeline"?G.set(tue,z):G.delete(tue),G},{replace:!0})},[t]),L=g.useCallback(z=>{const U=e.get(yy)||null;z!==U&&t(G=>{const ne=new URLSearchParams(G);return z&&z!=="details"?ne.set(yy,z):ne.delete(yy),ne.delete(xy),ne},{replace:!0})},[e,t]),F=g.useCallback((z,U)=>{const G=U&&U!=="details"?U:null;z===(e.get(Ab)||null)&&G===(e.get(yy)||null)&&!e.get(xy)||t(X=>{const ee=new URLSearchParams(X);return ee.set(Ab,z),G?ee.set(yy,G):ee.delete(yy),ee.delete(xy),ee},{replace:!0})},[e,t]),Q=g.useCallback(z=>{const U=e.get(xy)||null;z!==U&&t(G=>{const ne=new URLSearchParams(G);return z?ne.set(xy,z):ne.delete(xy),ne},{replace:!0})},[e,t]),q=g.useCallback(z=>{t(U=>{const G=new URLSearchParams(U);return z.length===0?G.delete(z2):G.set(z2,z.join(",")),G},{replace:!0})},[t]),B=g.useCallback((z,U=[])=>{t(G=>{const ne=new URLSearchParams(G);return Net(ne,z,U),wE(ne),ne},{replace:!0})},[t]),V=B,H=g.useCallback((z,U)=>{if(u.current!=="custom")return;const G=U==="from"?x1:b1;t(ne=>{const X=new URLSearchParams(ne);return z?X.set(G,z.toISOString()):X.delete(G),wE(X),X},{replace:!0})},[t]),D=g.useCallback((z,U)=>{u.current==="custom"&&t(G=>{const ne=new URLSearchParams(G);return z?ne.set(x1,z.toISOString()):ne.delete(x1),U?ne.set(b1,U.toISOString()):ne.delete(b1),wE(ne),ne},{replace:!0})},[t]),K=g.useCallback(z=>{u.current=z,t(U=>{const G=new URLSearchParams(U);return z==="last-7d"?(G.delete(F1),G.delete(x1),G.delete(b1)):z==="custom"?G.set(F1,"custom"):(G.set(F1,z),G.delete(x1),G.delete(b1)),wE(G),G},{replace:!0})},[t]),M=g.useCallback(z=>{t(U=>{const G=new URLSearchParams(U);return z==="traces"?G.delete(z1):G.set(z1,z),wE(G),G},{replace:!0})},[t]),$=g.useCallback(()=>{t(z=>{const U=new URLSearchParams(z);return U.delete(z1),Net(U,[]),wE(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:A,handleSpanTabChange:L,handleSpanViewChange:P,handleSpanChangeWithTab:F,handleScoreChange:Q,handleHighlightSpans:q,handleListModeChange:M,handleFilterTokensChange:V,handleDateChange:H,handleDateRangeChange:D,handleDatePresetChange:K,handleRemoveAll:$,applyFilterTokens:B}}function Sws(e){return e.map(t=>({traceId:t.traceId,spanId:t.rootSpanId,parentSpanId:t.parentSpanId,name:N0s(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 rVt({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=hvs({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:Sws(h.data??[]),autoRefetch:d,setAutoRefetch:f}}const Iye="sort",Nye="dir",kws="page";function Ows(e,t,n){const r=e.get(Iye);if(!r||!t.includes(r))return n;const i=e.get(Nye)==="desc"?"desc":"asc";return{key:r,direction:i}}function Hk({searchParams:e,setSearchParams:t,allowedKeys:n,defaultSort:r}){const s=e.get(Iye),i=e.get(Nye),o=g.useMemo(()=>Ows(e,n,r),[s,i,n,r]),l=g.useCallback((c,u)=>{t(d=>{const f=new URLSearchParams(d);return f.set(Iye,u),f.set(Nye,c),f.delete(kws),f},{replace:!0})},[t]);return{sort:o,onSortChange:l}}const jws=new Set(["ObservabilityStorageClickhouseVNext","ObservabilityStorageDuckDB","ObservabilityInMemory","ObservabilitySpanner","ObservabilityStoragePostgresVNext"]),O$=()=>{const{isMastraPlatform:e}=Az(),{data:t,isLoading:n,error:r}=Pz(),s=t?.observabilityStorageType,i=t?.capabilities?.metrics??(s?jws.has(s):!1);return{supportsMetrics:e||i,isInMemory:!e&&s==="ObservabilityInMemory",isLoading:!e&&n,error:e?void 0:r}};function Vs({value:e,className:t}){return a.jsx(jl,{code:JSON.stringify(e??null,null,2),lang:"json","data-slot":"span-payload-json",className:Z(pr,"rounded-lg p-3 text-wrap break-all text-muted-foreground",t,"text-caption")})}function YNe({value:e}){if(typeof e!="object"||e===null||Array.isArray(e))return a.jsx(Vs,{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(Vs,{value:e});try{const i=new URL(n);if(i.username||i.password)return a.jsx(Vs,{value:e})}catch{return a.jsx(Vs,{value:e})}const s=typeof t.filename=="string"?t.filename:typeof t.name=="string"?t.name:void 0;return a.jsx(HI,{type:t.type==="image"||typeof r=="string"&&r.startsWith("image/")?"image":"file",contentType:typeof r=="string"?r:void 0,src:n,name:s})}const ott=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function sVt({value:e,showLabel:t=!0}){if(!ott(e))return a.jsx(Vs,{value:e});const n=e.type==="tool-invocation"?e.toolInvocation:e;if(!ott(n)||typeof n.toolName!="string"||!n.toolName)return a.jsx(Vs,{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}=Q_(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(FD,{children:e.type==="tool-result"?"Tool result":"Tool call"}),a.jsx(dTe,{status:i?"error":"idle",header:a.jsx(oX,{icon:a.jsx(l,{"aria-hidden":!0}),label:c,detail:u,description:d}),children:f&&a.jsxs("div",{className:"flex flex-col gap-3",children:[r!==void 0&&a.jsx(lp,{label:"Arguments",children:a.jsx(Vs,{value:r})}),s!==void 0&&a.jsx(lp,{label:"Result",children:a.jsx(Vs,{value:s})}),o!==void 0&&a.jsx(lp,{label:"Error",children:a.jsx(Vs,{value:o})})]})})]})}function FD({children:e}){return a.jsx(Y,{as:"span",variant:"meta",tone:"faint",className:"block uppercase",children:e})}function lp({label:e,children:t}){return a.jsxs("div",{"data-slot":"span-payload-field",className:"flex flex-col gap-1.5",children:[a.jsx(FD,{children:e}),t]})}function lk({children:e}){return a.jsx("div",{"data-slot":"span-payload-markdown",className:"text-foreground",children:a.jsx(ql,{children:e})})}function xm({label:e,children:t,defaultOpen:n=!1}){return a.jsxs(gc,{defaultOpen:n,children:[a.jsxs(Hl,{className:"flex items-center gap-1 text-meta text-placeholder uppercase",children:[a.jsx(Ha,{direction:"right",className:"size-3"}),e]}),a.jsx(Gl,{className:"pt-1.5",children:t})]})}function XNe({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(sVt,{value:t,showLabel:!1})},n))})}const TW=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Cws(e){const t=e.split(`
|
|
@@ -696,7 +696,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
|
|
|
696
696
|
]`,xOs=[{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 bOs(){const{isCopied:e,handleCopy:t}=Bm({text:Att,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:xOs.map(n=>a.jsxs("div",{className:"grid grid-cols-[7rem_1fr] gap-3 px-3 py-2.5",children:[a.jsx("dt",{className:Ma({tone:"ink",variant:"meta"}),children:a.jsx(sh,{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(Mt,{variant:"success",size:"xs",children:"required"}):a.jsx(Mt,{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(ue,{icon:e?a.jsx(ur,{}):a.jsx(zm,{}),variant:"ghost",size:"sm",onClick:t,children:e?"Copied":"Copy"})]}),a.jsx(Or,{variant:"embedded",language:"json",editable:!1,lineNumbers:!1,showCopyButton:!1,value:Att,className:"p-3"})]}),a.jsx(ue,{variant:"ghost",render:a.jsx("a",{href:yOs,target:"_blank",rel:"noopener noreferrer"}),className:"self-start",icon:a.jsx(Zs,{}),children:"Datasets documentation"})]})}const uue=10,wOs=`[
|
|
697
697
|
{ "input": "…", "groundTruth": "…" }
|
|
698
698
|
]`,Ptt="flex min-h-0 flex-1 flex-col py-0";function SOs({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:s,pastedText:i,onPastedTextChange:o,validation:l,isImporting:c}){return a.jsxs(Wc,{value:e,defaultTab:"upload",onValueChange:t,className:"flex h-full flex-col gap-3",children:[a.jsxs(Hc,{variant:"pill",children:[a.jsx(si,{value:"upload",children:"Upload file"}),a.jsx(si,{value:"paste",children:"Paste JSON"})]}),a.jsx(No,{value:"upload",className:Ptt,children:n?a.jsx(COs,{file:n,validation:l,onReplace:s,isImporting:c}):a.jsx(kOs,{onFileSelect:r,disabled:c})}),a.jsx(No,{value:"paste",className:Ptt,children:a.jsx(Or,{"aria-label":"JSON items",language:"json",lineNumbers:!1,showCopyButton:!1,placeholder:wOs,value:i,onChange:o,editable:!c,className:"min-h-50 flex-1"})})]})}function kOs({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(nG,{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 ",hAe]})]})}function OOs(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function jOs(e){return typeof e=="string"?e:JSON.stringify(e)??""}function COs({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,uue);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(GH,{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:OOs(e.size)}),a.jsx(ue,{icon:a.jsx(mx,{}),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:jOs(l.input)}),l.hasInput?l.hasGroundTruth?null:a.jsx(Mt,{variant:"warning",size:"xs",children:"no groundTruth"}):a.jsx(Mt,{variant:"destructive",size:"xs",children:"no input"})]},l.index)),i>uue&&a.jsxs(Y,{as:"p",variant:"meta",tone:"muted",className:"border-t border-border px-3 py-1.5",children:["+ ",i-uue," more"]})]})}const _Os=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function TOs({datasetId:e,datasetName:t,open:n,onOpenChange:r,onSuccess:s}){const[i,o]=g.useState("upload"),[l,c]=g.useState(null),[u,d]=g.useState(""),[f,h]=g.useState(null),[p,m]=g.useState(""),[v,y]=g.useState(!1),x=g.useRef(0),{batchInsertItems:b}=pl(),S=i==="upload"?u:p,k=g.useMemo(()=>i==="upload"&&f?{status:"error",kind:"parse",message:f}:_ks(S),[i,f,S]),j=g.useCallback(async I=>{const A=++x.current;if(!I.name.toLowerCase().endsWith(".json")){h("Only .json files are supported");return}if(I.size>DVt){h(`File is larger than ${hAe}`);return}try{const P=await _Os(I);if(A!==x.current)return;c({name:I.name,size:I.size}),d(P),h(null)}catch{if(A!==x.current)return;h("Could not read the file")}},[]),C=g.useCallback(()=>{x.current++,c(null),d(""),h(null)},[]),T=g.useCallback(()=>{x.current++,o("upload"),c(null),d(""),h(null),m("")},[]),_=g.useCallback(()=>{r(!1),setTimeout(T,150)},[r,T]),N=g.useCallback(async()=>{if(k.status==="ready"){y(!0);try{await b.mutateAsync({datasetId:e,items:k.items}),Ye.success(`Imported ${k.total} item${k.total!==1?"s":""}`),s?.(),r(!1),setTimeout(T,150)}catch(I){Ye.error(I instanceof Error?I.message:"Failed to import items")}finally{y(!1)}}},[k,b,e,s,r,T]);return a.jsx(Kr,{open:n,onOpenChange:_,pending:v,children:a.jsxs(Yr,{size:"xl",children:[a.jsxs(Xr,{children:[a.jsx(Qr,{children:"Import into dataset"}),a.jsxs(Lo,{children:["Add items to ",t?a.jsx("span",{className:"text-foreground",children:t}):"this dataset"," from a JSON file or paste them directly."]})]}),a.jsx(qr,{flush:!0,children:a.jsxs("div",{className:"grid divide-y divide-border md:grid-cols-[1.15fr_1fr] md:divide-x md:divide-y-0",children:[a.jsx("div",{className:"flex min-h-[360px] flex-col p-4",children:a.jsx(SOs,{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(bOs,{})})]})}),a.jsxs(Yo,{children:[a.jsx(EOs,{validation:k}),a.jsx(Ca,{children:"Cancel"}),a.jsxs(ja,{onConfirm:N,disabled:k.status!=="ready",children:[v&&a.jsx(_n,{}),k.status==="ready"?`Import ${k.total} item${k.total!==1?"s":""}`:"Import"]})]})]})})}function EOs({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 ${hAe}`;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(sh,{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 IOs(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 qVt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=i=>{i.defaultPrevented||IOs(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 QVt=g.createContext(null);function NOs({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=Dr(),o=e0e("/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]);qVt({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(QVt.Provider,{value:h,children:r})}function ZVt(){const e=g.useContext(QVt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}const AOs=["createdAt"];function POs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s,belowToolbarSlot:i}){const[o,l]=ci(),{activeVersion:c}=pAe(o,l),{sort:u,onSortChange:d}=Hk({searchParams:o,setSearchParams:l,allowedKeys:AOs}),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,A]=g.useState([]),[P,L]=g.useState(0),[F,Q]=g.useState(""),[q]=UY(F,300),{data:B}=zx({datasetId:e,queryOptions:{enabled:!!e}}),{data:V=[],isLoading:H,setEndOfListElement:D,isFetchingNextPage:K,hasNextPage:M}=nA({datasetId:e,search:q||void 0,version:c,orderBy:f,queryOptions:{enabled:!!e}}),{deleteItems:$}=pl(),{currentItemId:z,openItem:U,close:G}=ZVt(),ne=le=>{z===le?G():U(le)},X=le=>{S(le),x(!0)},ee=le=>{T(le),j(!0)},ie=le=>{j(le),le||(T([]),L(pe=>pe+1))},fe=le=>{A(le),N(!0)},te=async()=>{await $.mutateAsync({datasetId:e,itemIds:I}),Ye.success(`Deleted ${I.length} items`),N(!1),A([]),L(le=>le+1)},se=le=>{x(!1),S([]),L(pe=>pe+1),n?.(le)},re=le=>{x(le),le||(S([]),L(pe=>pe+1))};return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid h-full overflow-auto",children:a.jsx(vOs,{items:V,leftSlot:r,rightSlot:s,belowToolbarSlot:i,isLoading:H,onItemClick:ne,featuredItemId:z,onAddClick:t??(()=>{}),onImportClick:()=>p(!0),onImportJsonClick:()=>v(!0),onBulkDeleteClick:fe,onCreateDatasetClick:X,onAddToDatasetClick:ee,datasetName:B?.name,clearSelectionTrigger:P,setEndOfListElement:D,isFetchingNextPage:K,hasNextPage:M,searchQuery:F,activeSearchQuery:q,onSearchChange:Q,sort:u,onSortChange:d,currentDatasetVersion:B?.version})}),a.jsx(uOs,{datasetId:e,open:h,onOpenChange:p}),a.jsx(TOs,{datasetId:e,datasetName:B?.name,open:m,onOpenChange:v}),a.jsx(Qks,{open:y,onOpenChange:re,items:b,onSuccess:se}),a.jsx(Zks,{open:k,onOpenChange:ie,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:te,children:$.isPending?"Deleting...":"Delete"})]})]})})]})}const $tt="__create_tag__";function $Os({datasetId:e}){const{data:t}=zx({datasetId:e,queryOptions:{enabled:!!e}}),{data:n}=Ek(),{updateDataset:r}=pl(),[s,i]=g.useState(""),o=g.useMemo(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),l=g.useMemo(()=>NVt(n?.datasets??[]),[n?.datasets]),c=g.useMemo(()=>{const h=l.map(v=>({label:v,value:v,end:o.includes(v)?a.jsx(ur,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),p=s.trim();return p.length>0&&!l.includes(p)&&!o.includes(p)?[{label:`Create "${p}"`,value:$tt},...h]:h},[l,o,s]),u=h=>{r.mutate({datasetId:e,tags:h},{onError:()=>Ye.error("Failed to update tags")})},d=h=>{const p=h===$tt?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(YJ,{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(zn,{className:"size-3"})})]},h)),a.jsx(fl,{options:c,value:void 0,onValueChange:d,onInputValueChange:i,placeholder:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(Nx,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",size:"sm",className:"w-auto min-w-0",disabled:r.isPending})]})}function WVt({overrideEnabled:e,onOverrideEnabledChange:t,selectedScorerIds:n,onSelectedScorerIdsChange:r,disabled:s=!1}){return a.jsxs("div",{className:"grid gap-3",children:[a.jsxs(ht,{orientation:"horizontal",disabled:s,className:"gap-3",children:[a.jsx(hc,{checked:e,onCheckedChange:t}),a.jsx(ut,{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(JJ,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function tN({field:e,errors:t}){return t.length===0?null:a.jsx(ns,{children:a.jsx("span",{className:"space-y-1",children:t.map(n=>a.jsxs("span",{className:"block",children:[a.jsxs("code",{className:"rounded bg-destructive-subtle px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},`${n.path}:${n.message}`))})})}function ROs(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 MOs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,i]=g.useState("{}"),[o,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[h,p]=g.useState(!1),[m,v]=g.useState([]),[y,x]=g.useState(""),[b,S]=g.useState(null),{addItem:k}=pl(),j=()=>{i("{}"),l(""),u(""),f(""),p(!1),v([]),x(""),S(null)},C=P=>{j(),n(P)},T=async P=>{P.preventDefault();let L;try{L=JSON.parse(s)}catch{Ye.error("Input must be valid JSON");return}let F;if(o.trim())try{F=JSON.parse(o)}catch{Ye.error("Ground Truth must be valid JSON");return}let Q;if(c.trim())try{Q=JSON.parse(c)}catch{Ye.error("Expected Trajectory must be valid JSON");return}let q;if(d.trim())try{const V=JSON.parse(d);if(!Array.isArray(V)){Ye.error("Tool Mocks must be a JSON array");return}q=V}catch{Ye.error("Tool Mocks must be valid JSON");return}let B;if(y.trim())try{B=JSON.parse(y)}catch{Ye.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:L,groundTruth:F,expectedTrajectory:Q,toolMocks:q,scorerIds:h?m:void 0,requestContext:B}),Ye.success("Item added successfully"),C(!1),r?.()}catch(V){const H=ROs(V);H?S(H):Ye.error(`Failed to add item: ${V instanceof Error?V.message:"Unknown error"}`)}},_=P=>{i(P),b?.field==="input"&&S(null)},N=P=>{l(P),b?.field==="groundTruth"&&S(null)},I=P=>{f(P),b?.field==="toolMocks"&&S(null)},A=()=>{C(!1)};return a.jsxs(xo,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[a.jsx(xo.Top,{children:"Add Item"}),a.jsxs(xo.Content,{children:[a.jsx(xo.Header,{children:a.jsx(xo.Heading,{children:"Add Item"})}),a.jsxs(Ga,{onSubmit:T,children:[a.jsxs(ht,{invalid:b?.field==="input",children:[a.jsx(ut,{required:!0,children:"Input (JSON)"}),a.jsx(Or,{value:s,onChange:_,showCopyButton:!1,className:"min-h-[240px]"}),b?.field==="input"&&a.jsx(tN,{field:"input",errors:b.errors})]}),a.jsxs(ht,{invalid:b?.field==="groundTruth",children:[a.jsx(ut,{children:"Ground Truth (JSON, optional)"}),a.jsx(Or,{value:o,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),b?.field==="groundTruth"&&a.jsx(tN,{field:"groundTruth",errors:b.errors})]}),a.jsxs(ht,{children:[a.jsx(ut,{children:"Expected Trajectory (JSON, optional)"}),a.jsx(Or,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),a.jsxs(ht,{invalid:b?.field==="toolMocks",children:[a.jsx(ut,{children:"Tool Mocks (JSON array, optional)"}),a.jsx(Or,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),b?.field==="toolMocks"&&a.jsx(tN,{field:"toolMocks",errors:b.errors})]}),a.jsx(WVt,{overrideEnabled:h,onOverrideEnabledChange:p,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),a.jsxs(ht,{children:[a.jsx(ut,{children:"Request Context (JSON, optional)"}),a.jsx(Or,{value:y,onChange:x,showCopyButton:!1,className:"min-h-[200px]"})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[a.jsx(ue,{icon:a.jsx(zn,{}),type:"button",onClick:A,children:"Cancel"}),a.jsx(ue,{icon:a.jsx(ys,{}),type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}const BO=e=>JSON.stringify(e??null,null,2),DOs=[{key:"input",title:"Input",icon:a.jsx(_4,{}),value:e=>BO(e.input)},{key:"groundTruth",title:"Ground Truth",icon:a.jsx(Lj,{}),value:e=>BO(e.groundTruth)},{key:"expectedTrajectory",title:"Expected Trajectory",icon:a.jsx(fwe,{}),value:e=>e.expectedTrajectory!=null?BO(e.expectedTrajectory):void 0},{key:"toolMocks",title:"Tool Mocks",icon:a.jsx(dd,{}),value:e=>BO(e.toolMocks??[])},{key:"scorerIds",title:"Scorers",icon:a.jsx(Uht,{}),value:e=>e.scorerIds===void 0?"Inherited from dataset":BO(e.scorerIds)},{key:"requestContext",title:"Request Context",icon:a.jsx(Ua,{}),value:e=>e.requestContext!=null?BO(e.requestContext):void 0},{key:"metadata",title:"Metadata",icon:a.jsx(Nx,{}),value:e=>BO(e.metadata)}];function Dye({item:e,diff:t}){return a.jsxs(a.Fragment,{children:[a.jsxs(Kt,{children:[a.jsx(Kt.Key,{children:"Dataset Id"}),a.jsx(Kt.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:e.datasetId,children:e.datasetId}),a.jsx(Kt.Key,{children:"Version"}),a.jsxs(Kt.Value,{children:["v",e.datasetVersion]}),a.jsx(Kt.Key,{children:"Created"}),a.jsx(Kt.Value,{children:Jr(e.createdAt,"date-time")}),a.jsx(Kt.Key,{children:"Updated"}),a.jsx(Kt.Value,{children:e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime()?Jr(e.updatedAt,"date-time"):"n/a"})]}),a.jsx("div",{className:"mt-3 grid gap-3",children:DOs.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(Tt.CodeSection,{title:n.title,icon:n.icon,codeStr:r??"",diff:t?{against:s??"",side:t.side}:void 0},n.key)})})]})}function LOs({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(Bc,{className:"h-5 w-5"})," Edit Item"]})}),a.jsxs("div",{className:"space-y-6",children:[a.jsxs(ht,{invalid:y?.field==="input",children:[a.jsx(ut,{required:!0,children:"Input (JSON)"}),a.jsx(Or,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&a.jsx(tN,{field:"input",errors:y.errors})]}),a.jsxs(ht,{invalid:y?.field==="groundTruth",children:[a.jsx(ut,{children:"Ground Truth (JSON, optional)"}),a.jsx(Or,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&a.jsx(tN,{field:"groundTruth",errors:y.errors})]}),a.jsxs(ht,{children:[a.jsx(ut,{children:"Expected Trajectory (JSON, optional)"}),a.jsx(Or,{value:o,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs(ht,{invalid:y?.field==="toolMocks",children:[a.jsx(ut,{children:"Tool Mocks (JSON array, optional)"}),a.jsxs(no,{children:["Ordered static mocks served in place of executing the tool. Each entry is"," ",a.jsx("code",{children:'{ "toolName", "args", "output" }'}),". Calling a mocked tool with non-matching args fails the item; unmocked tools run live."]}),a.jsx(Or,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&a.jsx(tN,{field:"toolMocks",errors:y.errors})]}),a.jsx(WVt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:h,onSelectedScorerIdsChange:p,disabled:S}),a.jsxs(ht,{children:[a.jsx(ut,{children:"Request Context (JSON, optional)"}),a.jsx(Or,{value:m,onChange:v,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs(ht,{children:[a.jsx(ut,{children:"Metadata (JSON, optional)"}),a.jsx(Or,{value:s,onChange:i,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs("div",{className:"flex gap-2 pt-4",children:[a.jsx(ue,{icon:a.jsx(ur,{}),variant:"primary",onClick:x,disabled:S,children:S?"Saving...":"Save Changes"}),a.jsx(ue,{icon:a.jsx(zn,{}),onClick:b,disabled:S,children:"Cancel"})]})]})]})}const zOs=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function FOs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,onTargetNameChange:s,container:i}){const{data:o,isLoading:l}=Cp(),{data:c,isLoading:u}=ng({}),{data:d,isLoading:f}=Fx(),h=e==="agent"?Object.entries(o??{}).map(([x,b])=>({value:x,label:b.name??x})):e==="workflow"?Object.entries(c??{}).map(([x,b])=>({value:x,label:b.name??x})):e==="scorer"?Object.entries(d??{}).map(([x,b])=>({value:x,label:b.scorer?.config?.name??x})):[],p=e==="agent"&&l||e==="workflow"&&u||e==="scorer"&&f,m=x=>{t(x),r(""),s?.(void 0)},v=x=>{r(x),s?.(h.find(b=>b.value===x)?.label||x)},y=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs(ht,{children:[a.jsx(ut,{children:"Target Type"}),a.jsx(fl,{options:zOs,value:e,onValueChange:m,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:i})]}),e&&a.jsxs(ht,{children:[a.jsx(ut,{children:y}),a.jsx(fl,{options:h,value:n,onValueChange:v,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:i})]})]})}function HVt(e){return e?Nks(e,LVt()):""}function Rtt(e){return{name:e.name??HVt(e.targetId),description:e.description??"",datasetId:e.datasetId??"",version:e.version,targetType:e.targetType??"",targetId:e.targetId??"",scorerIds:e.scorerIds,requestContextValues:{},requestContextRaw:""}}function BOs(e){const t=Dx({defaultValues:Rtt(e)});return{form:t,changeTargetName:s=>{e.name!==void 0||t.getValues("name")!==t.formState.defaultValues?.name||t.resetField("name",{defaultValue:HVt(s)})},resetForm:()=>t.reset(Rtt(e))}}const UOs=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function VOs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return $S(e)}catch(r){return console.error("Failed to parse requestContextSchema:",r),null}},[e]);return n?a.jsxs(T0,{children:[a.jsx(OC,{children:"Request Context"}),a.jsx(oke,{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 due({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 eee({initialDatasetId:e,initialDatasetVersion:t,initialScorerIds:n,initialTargetType:r,initialTargetId:s,initialName:i,initialDescription:o,open:l,onOpenChange:c,onSuccess:u}){const d=g.useRef(null),{form:f,changeTargetName:h,resetForm:p}=BOs({name:i,description:o,datasetId:e,version:t,targetType:r,targetId:s,scorerIds:n}),{register:m,setValue:v,watch:y}=f,[x,b,S,k,j,C,T,_]=y(["name","datasetId","version","targetType","targetId","scorerIds","requestContextValues","requestContextRaw"]),{triggerExperiment:N}=pl(),{data:I}=zx({datasetId:b,queryOptions:{enabled:!!b}}),{total:A}=nA({datasetId:b,search:void 0,version:S,queryOptions:{enabled:!!b}}),P=I?.requestContextSchema,L=I?.scorerIds??[],F=C===void 0&&L.length>0,Q=C??L,q=!!(P&&Object.keys(P).length>0),B=x.trim(),V=!!(b&&k&&j&&B),H=N.isPending,D=[!b&&"dataset",!j&&"target",j&&!B&&"name"].filter(Boolean),K=q?Object.values(T).some(ne=>ne!==void 0&&ne!==""):_.trim().length>0,M=ne=>{v("datasetId",ne),v("version",void 0),v("scorerIds",n),v("requestContextValues",{})},$=()=>{if(q){const ne=Object.entries(T).filter(([,X])=>X!==void 0&&X!=="");return ne.length>0?Object.fromEntries(ne):void 0}if(_.trim()){let ne;try{ne=JSON.parse(_)}catch{throw new Error("Request Context must be valid JSON")}if(!ne||typeof ne!="object"||Array.isArray(ne))throw new Error("Request Context must be a JSON object");return ne}},z=f.handleSubmit(async({description:ne})=>{if(!b||!k||!j||!B)return;let X;try{X=$()}catch(ee){const ie=ee instanceof Error?ee.message:"Request Context must be valid JSON";ku.error(ie);return}try{const ee=await N.mutateAsync({datasetId:b,name:B,description:ne.trim()||void 0,targetType:k,targetId:j,scorerIds:Q.length>0?Q:void 0,version:S,requestContext:X});ku.success("Experiment triggered successfully"),c(!1),u?.(ee.experimentId),p()}catch(ee){const ie=ee instanceof Error?ee.message:"Failed to trigger experiment";ku.error(ie)}}),U=()=>{c(!1),p()},G=ne=>{(ne.metaKey||ne.ctrlKey)&&ne.key==="Enter"&&V&&!H&&(ne.preventDefault(),z())};return a.jsx(Kr,{open:l,onOpenChange:U,pending:H,children:a.jsxs(Yr,{ref:d,size:"lg",onKeyDown:G,children:[a.jsxs(Xr,{children:[a.jsx(Qr,{children:"Run experiment"}),a.jsx(Lo,{children:"Pick a dataset, choose what to run it against, and optionally score the results."})]}),a.jsxs(qr,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs(ht,{children:[a.jsx(ut,{children:"Name"}),a.jsx(wn,{...m("name"),placeholder:"Enter experiment name",autoFocus:!0,disabled:H})]}),a.jsxs(ht,{children:[a.jsx(ut,{children:"Description"}),a.jsx(Pu,{...m("description"),placeholder:"Enter experiment description (optional)",disabled:H,rows:2})]})]}),a.jsxs("ol",{className:"list-none",children:[a.jsxs(due,{index:1,done:!!b,children:[a.jsxs("div",{className:"grid grid-cols-[1fr_140px] gap-3",children:[a.jsxs(ht,{children:[a.jsx(ut,{children:"Dataset"}),a.jsx(SOt,{value:b,onValueChange:M,container:d})]}),b&&a.jsxs(ht,{children:[a.jsx(ut,{children:"Version"}),a.jsx(VVt,{datasetId:b,value:S??null,onValueChange:ne=>v("version",ne??void 0),container:d})]})]}),b&&A!==void 0&&a.jsxs(Y,{variant:"meta",tone:"muted",children:[A," ",A===1?"item":"items"]})]}),a.jsxs(due,{index:2,done:!!j,children:[a.jsx(FOs,{targetType:k,setTargetType:ne=>v("targetType",ne),targetId:j,setTargetId:ne=>v("targetId",ne),onTargetNameChange:h,container:d}),k&&!j&&a.jsxs(Y,{variant:"meta",tone:"muted",children:["Choose ",k==="agent"?"an":"a"," ",k," to run"]})]}),a.jsx(due,{index:3,done:Q.length>0,isLast:!0,children:a.jsx(JJ,{selectedScorers:Q,setSelectedScorers:ne=>v("scorerIds",ne),disabled:H,container:d,helperText:F?"Pre-filled from the dataset's default scorers.":"Scores are computed after each item runs."})})]}),a.jsxs(gc,{children:[a.jsxs(Hl,{className:"flex items-center gap-2 text-caption",children:[a.jsx(Ha,{direction:"right",className:"size-4"}),"Request Context (JSON, optional)",K&&a.jsx(Mt,{size:"xs",variant:"blue",children:"set"})]}),a.jsx(Gl,{className:"pt-3",children:q?a.jsx(VOs,{requestContextSchema:P,onChange:ne=>v("requestContextValues",ne)}):a.jsx(Or,{value:_,onChange:ne=>v("requestContextRaw",ne),showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),a.jsxs(Yo,{children:[a.jsx("p",{"data-testid":"experiment-run-status","aria-live":"polite",className:"mr-auto flex items-center gap-2",children:D.length===0?a.jsxs(a.Fragment,{children:[a.jsx(Mt,{variant:"success",indicator:"dot",children:"Ready"}),a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",children:[A??0," items · ",k," · ",Q.length," scorers"]})]}):a.jsxs(Mt,{variant:"neutral",indicator:"dot",children:["Missing ",D.join(", ")]})}),a.jsx(Ca,{children:"Cancel"}),a.jsx(ja,{onConfirm:z,disabled:!V,children:H?a.jsxs(a.Fragment,{children:[a.jsx(_n,{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(Wd,{size:"xs",children:UOs?"⌘":"Ctrl"}),a.jsx(Wd,{size:"xs",children:"↵"})]})]})})]})]})})}const Lye="mastra_model_total_input_tokens",GVt="mastra_model_total_output_tokens",qOs=2e3,Mtt=()=>({estimatedCost:0,costUnits:new Set,hasUnknownCostUnit:!1});function Dtt(e,t,n){e[t]=(e[t]??0)+n.value,n.estimatedCost!=null&&(e.estimatedCost+=n.estimatedCost,n.costUnit?e.costUnits.add(n.costUnit.toLowerCase()):e.hasUnknownCostUnit=!0)}function Ltt(e){const t=!e.hasUnknownCostUnit&&e.costUnits.size===1;return{inputTokens:e.inputTokens,outputTokens:e.outputTokens,estimatedCost:t?e.estimatedCost:void 0,costUnit:t?[...e.costUnits][0]:void 0}}function QOs(e){const t=Mtt(),n=new Map;for(const s of e.groups){const i=s.dimensions.name;if(i!==Lye&&i!==GVt)continue;const o=i===Lye?"inputTokens":"outputTokens";Dtt(t,o,s);const l=s.dimensions.traceId;l&&Dtt(FJ(n,l,Mtt),o,s)}const r={};for(const[s,i]of n)r[s]=Ltt(i);return{summary:Ltt(t),traces:r}}const mAe=({experiments:e,supportsMetrics:t})=>{const n=Ge(),r=OK(e.map(s=>s.id));return Mm({queries:e.map(({id:s,status:i})=>({queryKey:["experiment-item-usage",s],queryFn:async()=>QOs(await n.getMetricBreakdown({name:[Lye,GVt],aggregation:"sum",groupBy:["traceId","name"],filters:{experimentId:s}})),enabled:t,refetchInterval:i==="running"||i==="pending"?qOs:!1})),combine:r})},ZOs=({experimentId:e,experimentStatus:t,supportsMetrics:n,queryOptions:r})=>{const s=Ge(),i=!!e&&n,o=_t({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}},WOs=({traceId:e,queryOptions:t})=>{const n=Ge();return _t({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return n.getTraceLight(e)},...t})};function KVt({datasetId:e,target:t,queryOptions:n}){const r=Ge(),s={perPage:100};return t?.targetType&&(s.targetType=t.targetType),t?.targetId&&(s.targetId=t.targetId),_t({queryKey:["experiments",s],queryFn:()=>r.listExperiments(s),...n})}function HOs({datasetId:e,target:t,orderBy:n,queryOptions:r}){const s=Ge(),{inView:i,setRef:o}=K0(),l=t?.targetType||void 0,c=t?.targetId||void 0,u=Dm({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 YVt=g.createContext(null);function GOs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:i,children:o}){const l=Dr(),u=e0e("/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]);qVt({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(YVt.Provider,{value:v,children:o})}function gAe(){const e=g.useContext(YVt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}function zye(e,t){if(!e||typeof e!="object"||!(t in e))return;const n=e[t];return typeof n=="string"&&n?n:void 0}function vAe(e){if(e.targetType==="agent")return zye(e.output,"text")}function XVt(e){if(e.targetType)return vAe(e);const{output:t}=e;if(!(t==null||t===""))return typeof t=="string"?t:JSON.stringify(t)}function KOs(e){const t=[];return e.some(n=>XVt(n))&&t.push({name:"output",label:"Output",size:"1fr"}),e.some(n=>tee(n))&&t.push({name:"error",label:"Error",size:"1fr"}),t}function tee(e){const t=zye(e.error,"message");if(t)return t;if(!(e.targetType!=="agent"||!e.output||typeof e.output!="object"))return zye(e.output.error,"message")}const Fye=e=>e!=null?e.toFixed(2):"-",JVt=e=>Vc(e)??"-",YOs=(e,t)=>e!=null&&t!=null?e-t:null,XOs=new Set(Intl.supportedValuesOf("currency")),Rz=(e,t)=>{if(e===void 0)return"-";const n=e!==0&&Math.abs(e)<1?{maximumSignificantDigits:3}:{minimumFractionDigits:2,maximumFractionDigits:2},r=(t??"usd").toUpperCase();return XOs.has(r)?new Intl.NumberFormat("en-US",{style:"currency",currency:r,...n}).format(e):`${new Intl.NumberFormat("en-US",n).format(e)} ${t}`},eqt=e=>t=>Rz(t,e),JOs=new Intl.NumberFormat("en-US"),iS=e=>e!==void 0?JOs.format(e):"-",qA=e=>{if(!(e?.inputTokens===void 0&&e?.outputTokens===void 0))return(e.inputTokens??0)+(e.outputTokens??0)},ejs=new Set(["itemId","id","status","input","output","error","tags","scores","startedAt","cost","tokens","duration"]);function tqt({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}=Tn(),b=!!(f&&h),S=s.filter(M=>ejs.has(M.name)||o?.includes(M.name)),k=[b?"2rem":"",...S.map(M=>M.size)].filter(Boolean).join(" "),j=M=>S.some($=>$.name===M),C=j("itemId")||j("id"),T=j("status"),_=j("input"),N=j("output"),I=j("error"),A=j("tags"),P=j("scores"),L=j("startedAt"),F=j("cost"),Q=j("tokens"),q=j("duration"),B=f?e.filter(M=>f.has(M.id)).length:0,V=e.length>0&&B===e.length,{containerRef:H,getRowProps:D}=Fu({count:e.length}),K=M=>o?.includes(M.name)?a.jsx(_e.TopCell,{children:a.jsxs(y,{href:x.scorerLink(M.name),className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[a.jsx(tw,{}),a.jsx("span",{className:"min-w-0 truncate",children:M.label})]})},M.name):M.name==="startedAt"&&v?a.jsx(_e.SortableTopCell,{sortKey:"startedAt",sort:m?.key==="startedAt"?m.direction:void 0,onSortChange:v,children:M.label},M.name):a.jsx(_e.TopCell,{children:M.label},M.name);return t?a.jsx(Lu,{columns:k}):a.jsxs(_e,{columns:k,className:"min-w-0",scrollRef:H,fit:"container",children:[a.jsxs(_e.Top,{hasLeadingCell:b,children:[b&&(p?a.jsx(_e.TopSelectCell,{checked:V?!0:B>0?"indeterminate":!1,onToggle:p,"aria-label":"Select all"}):a.jsx(_e.TopCell,{children:" "})),b?a.jsx(_e.TopCells,{colStart:2,children:S.map(K)}):S.map(K)]}),e.length===0?a.jsx(_e.NoMatch,{message:d}):a.jsxs(a.Fragment,{children:[e.map((M,$)=>{const z=!!M.error,U=M.id===n,G=a.jsxs(a.Fragment,{children:[C&&a.jsx(_e.Cell,{className:"text-muted-foreground",children:M.itemId?.slice(0,8)??""}),T&&a.jsx(_e.Cell,{className:"flex items-center","data-testid":`result-status-${M.id}`,children:M.status?a.jsx(HNe,{status:M.status}):a.jsx("span",{className:"text-placeholder",children:"—"})}),_&&a.jsx(_e.TextCell,{font:"mono",children:sjs(rjs(M.input),200)}),N&&a.jsx(_e.Cell,{className:"truncate font-mono","data-testid":`result-output-${M.id}`,children:XVt(M)??""}),I&&a.jsx(_e.Cell,{className:"truncate text-destructive-foreground","data-testid":`result-error-${M.id}`,children:tee(M)??""}),A&&a.jsx(_e.Cell,{className:"flex items-center gap-1 overflow-hidden","data-testid":`result-tags-${M.id}`,children:M.tags?.map(ne=>a.jsx(YJ,{value:ne,className:"shrink-0"},ne))}),P&&a.jsx(_e.Cell,{children:a.jsx(tjs,{scores:M.scores})}),L&&(M.startedAt?a.jsx(_e.TextCell,{"data-testid":`result-created-${M.id}`,children:Jr(M.startedAt,"date-time")}):a.jsx(_e.Cell,{className:"text-placeholder",children:"—"})),F&&a.jsx(_e.Cell,{className:"text-muted-foreground tabular-nums","data-testid":`result-cost-${M.id}`,children:Rz(M.usage?.estimatedCost,M.usage?.costUnit)}),Q&&a.jsx(_e.Cell,{className:"text-muted-foreground tabular-nums","data-testid":`result-tokens-${M.id}`,children:iS(qA(M.usage))}),q&&a.jsx(_e.Cell,{className:"text-muted-foreground tabular-nums","data-testid":`result-duration-${M.id}`,children:Vc(njs(M))??"-"}),o?.map(ne=>{const ee=i?.[M.itemId]?.find(ie=>ie.scorerId===ne);return a.jsx(_e.Cell,{className:"text-muted-foreground tabular-nums",children:ee!=null?ee.score.toFixed(3):"-"},ne)})]});return b?a.jsxs(_e.RowWrapper,{children:[a.jsx(_e.SelectCell,{checked:f.has(M.id),onToggle:()=>h(M.id),"aria-label":`Select result ${M.itemId}`}),a.jsx(_e.RowButton,{colStart:2,featured:U,variant:z?"error":"default","data-selected":U||void 0,onClick:()=>r(M.id),...D($),children:G})]},M.id):a.jsx(_e.RowButton,{featured:U,variant:z?"error":"default","data-selected":U||void 0,onClick:()=>r(M.id),...D($),children:G},M.id)}),a.jsx(_e.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function tjs({scores:e}){const t=Array.isArray(e)?e.map(n=>n.score).filter(n=>n!=null):Object.values(e??{});return t.length===0?a.jsx(Y,{variant:"meta",tone:"faint",children:"—"}):a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(At,{size:"xs",className:"text-muted-foreground",children:a.jsx(tg,{})}),a.jsx(Y,{variant:"meta",tone:"muted",font:"mono",children:t[0].toFixed(2)}),t.length>1&&a.jsxs(Mt,{children:["+",t.length-1]})]})}function njs({startedAt:e,completedAt:t}){if(!(!e||!t))return new Date(t).getTime()-new Date(e).getTime()}function rjs(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function sjs(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}const ijs={pending:"Run queued — waiting to start…",running:"Run in progress — results appear as items complete"};function ojs({experimentId:e,experimentStatus:t,results:n,isLoading:r,setEndOfListElement:s,isFetchingNextPage:i,hasNextPage:o,selectedIds:l,onToggleSelect:c,onToggleSelectAll:u,sort:d,onSortChange:f,supportsMetrics:h=!1}){const{currentItemId:p,openItem:m,close:v}=gAe(),y=g.useMemo(()=>p?n.find(N=>N.itemId===p)?.id??null:null,[n,p]),{data:x}=JL({experimentId:e,experimentStatus:t,queryOptions:{enabled:!!e}}),b=g.useMemo(()=>[{id:e,status:t}],[e,t]),{data:S}=mAe({experiments:b,supportsMetrics:h}),k=S[e]?.traces,j=g.useMemo(()=>k?n.map(N=>({...N,usage:N.traceId?k[N.traceId]:void 0})):n,[n,k]),C=g.useMemo(()=>{if(!x)return[];const N=new Set;for(const I of Object.values(x))for(const A of I)N.add(A.scorerId);return[...N].sort()},[x]),T=g.useCallback(N=>{const I=n.find(A=>A.id===N);I&&(I.itemId===p?v():m(I.itemId))},[n,p,v,m]),_=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"auto"},{name:"input",label:"Input",size:"1fr"},...KOs(n),{name:"tags",label:"Tags",size:"auto"},{name:"startedAt",label:"Created",size:"auto"},...h?[{name:"cost",label:"Cost",size:"auto"},{name:"tokens",label:"Tokens",size:"auto"}]:[],{name:"duration",label:"Duration",size:"auto"},...C.map(N=>({name:N,label:N,size:"auto"}))],[n,C,h]);return a.jsx("div",{className:"h-full min-h-0 min-w-0 overflow-y-auto",children:a.jsx(tqt,{results:j,isLoading:r,featuredResultId:y,onResultClick:T,columns:_,scoresByItemId:x,scorerIds:C,setEndOfListElement:s,isFetchingNextPage:i,hasNextPage:o,emptyMessage:ijs[t??""]??"No results yet",selectedIds:l,onToggleSelect:c,onToggleSelectAll:u,sort:d,onSortChange:f})})}const ajs="minmax(9rem,1fr)",ljs="minmax(8rem,16rem)",cjs="1fr",ujs="auto auto auto auto auto auto auto",fy={experiment:"Experiment",description:"Description",dataset:"Dataset",target:"Target",status:"Status",items:"Items",succeeded:"Processed",failed:"Errored",review:"Review",date:"Date"},djs={completed:"neutral",running:"warning",failed:"destructive",pending:"neutral"},F2={completed:"Run completed",running:"Run in progress",failed:"Run failed",pending:"Run queued"},ztt={pending:{icon:a.jsx(fC,{className:"size-4 text-warning-foreground"}),label:F2.pending},running:{icon:a.jsx(_n,{size:"sm"}),label:F2.running},completed:{icon:a.jsx(Tht,{className:"size-4 text-muted-foreground"}),label:F2.completed},failed:{icon:a.jsx(X0e,{className:"size-4 text-destructive-foreground"}),label:F2.failed}};function fjs({status:e,className:t}){const n=ztt[e]??ztt.pending;return a.jsxs(Fn,{children:[a.jsx(Mn,{render:a.jsx("span",{tabIndex:0,className:Z("flex shrink-0 items-center",t),children:n.icon})}),a.jsx(Dn,{children:n.label})]})}function hjs({children:e,className:t}){return a.jsx("div",{className:Z("grid content-start gap-4 overflow-y-auto",t),children:e})}function pjs({children:e,className:t}){return a.jsx("div",{className:"flex w-full overflow-y-auto",children:a.jsx("div",{className:Z("grid w-full content-start gap-4 overflow-y-auto",t),children:e})})}function mjs({children:e,className:t}){return a.jsx("div",{className:Z("flex w-full flex-wrap items-center justify-between gap-3 gap-x-4",t),children:e})}const nqt=Object.assign(pjs,{Content:hjs,Toolbar:mjs});function gjs({children:e,className:t}){return a.jsx("div",{className:Z("grid size-full grid-cols-1 overflow-y-auto",t),children:e})}const vjs={agent:"blue",workflow:"cyan",model:"purple",mcp:"green",tool:"amber",workspace:"orange"},yjs=Object.keys(vjs);[...yjs];function xjs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${Jr(n,"date-time")}`}return`v${e}`}function bjs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=bOt({datasetId:e,queryOptions:{enabled:!!e}}),i=(s??[]).map(o=>({value:String(o.version),label:`${xjs(o.version,o.createdAt)}${o.isCurrent?" (current)":""}`}));return a.jsxs(nqt.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[a.jsx("div",{}),a.jsxs(ps,{value:t??"",onValueChange:o=>r?.(o,n??""),children:[a.jsx(gs,{"aria-label":"Version A",size:"md",children:a.jsx(ms,{placeholder:"Select version"})}),a.jsx(vs,{children:i.map(o=>a.jsx(hr,{value:o.value,children:o.label},o.value))})]}),a.jsxs(ps,{value:n??"",onValueChange:o=>r?.(t??"",o),children:[a.jsx(gs,{"aria-label":"Version B",size:"md",children:a.jsx(ms,{placeholder:"Select an option"})}),a.jsx(vs,{children:i.map(o=>a.jsx(hr,{value:o.value,children:o.label},o.value))})]}),a.jsx("div",{})]})}const EU={added:{badgeVariant:"info",borderColor:"border-info-edge",icon:a.jsx(ys,{}),tooltip:"Added in this version"},changed:{badgeVariant:"warning",borderColor:"border-warning-edge",icon:a.jsx(PIn,{}),tooltip:"Changed in this version"},same:{badgeVariant:"success",borderColor:"border-success-edge",icon:a.jsx(Pht,{}),tooltip:"Same in both versions"}};function fue({red:e=!1,tooltip:t}){return a.jsxs(Fn,{children:[a.jsx(Mn,{render:a.jsx("span",{}),role:"img",tabIndex:0,"aria-label":t,className:Z("rounded",ji),children:a.jsx(wht,{className:Z("h-5 w-5 text-muted-foreground/40",{"text-destructive-foreground":e})})}),a.jsx(Dn,{children:t})]})}function z7({href:e,tooltip:t,className:n,children:r}){const{Link:s}=Tn(),i=a.jsx(s,{href:e,className:Z("flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left hover:bg-fill-subtle",Mi.colors,ji,n),children:r});return t===void 0?i:a.jsxs(Fn,{children:[a.jsx(Mn,{render:i}),a.jsx(Dn,{children:t})]})}function hue({variant:e,version:t}){if(!e)return a.jsxs(Y,{as:"span",tone:"muted",children:["v. ",t]});const{badgeVariant:n,icon:r,tooltip:s}=EU[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(Mt,{variant:n,size:"xs",icon:r})})]})}function wjs(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function Ftt({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function Sjs({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=wjs(c,u),f=Ftt({otherVersionExists:u!==void 0,status:d,isNewer:o}),h=Ftt({otherVersionExists:c!==void 0,status:d,isNewer:!o});return a.jsxs("li",{className:Z("text-foreground","grid grid-cols-[1fr_1fr_1fr_10rem] gap-3 overflow-hidden rounded-lg border border-transparent border-t-border px-3 py-[3px] pb-[2px] first:border-t-transparent",Mi.colors),children:[a.jsx(Y,{as:"p",variant:"body",tone:"faint",className:"truncate py-[0.6rem]",children:l}),d!=="same"?a.jsxs(a.Fragment,{children:[c?.datasetVersion?a.jsx(z7,{href:`/datasets/${e}/items/${l}`,className:"gap-2",tooltip:f?EU[f].tooltip:void 0,children:a.jsx(hue,{variant:f,version:c.datasetVersion})}):a.jsx("div",{className:"flex items-center justify-center",children:a.jsx(fue,{red:o,tooltip:o?"Deleted in this version":"Not present in this version"})}),u?.datasetVersion?a.jsx(z7,{href:`/datasets/${e}/items/${l}`,className:"gap-2",tooltip:h?EU[h].tooltip:void 0,children:a.jsx(hue,{variant:h,version:u.datasetVersion})}):a.jsx("div",{className:"flex items-center justify-center",children:a.jsx(fue,{red:!o,tooltip:o?"Not present in this version":"Deleted in this version"})})]}):a.jsx(z7,{href:`/datasets/${e}/items/${l}`,className:"col-span-2 gap-2",tooltip:EU.same.tooltip,children:a.jsx(hue,{variant:"same",version:u?.datasetVersion})}),d==="changed"?a.jsx(z7,{href:`/datasets/${e}/items/${l}/versions?version=${c?.datasetVersion}&compare=${u?.datasetVersion}`,children:"Compare"}):a.jsx("div",{children:a.jsx(fue,{tooltip:"Comparing is available only for changed items"})})]},l)})})})}function kjs(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 Ojs({item:e,itemId:t,fallback:n,onClose:r,...s}){const i=e?.id??t;return a.jsx(Tt,{open:!!i,onClose:r,title:`Dataset item ${i??""}`,children:e?a.jsx(jjs,{item:e,onClose:r,...s},e.id):t?a.jsxs(a.Fragment,{children:[a.jsxs(Tt.Header,{children:[a.jsx(Tt.CloseButton,{onClick:r,tooltip:"Close detail panel"}),a.jsxs(Tt.Heading,{children:["Item",a.jsx(Tt.CopyId,{id:t})]})]}),n]}):null})}function jjs({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:i}=Tn(),{updateItem:o,deleteItem:l}=pl(),[c,u]=g.useState(!1),[d,f]=g.useState(""),[h,p]=g.useState(""),[m,v]=g.useState(""),[y,x]=g.useState(""),[b,S]=g.useState(""),[k,j]=g.useState(t.scorerIds!==void 0),[C,T]=g.useState(t.scorerIds??[]),[_,N]=g.useState(""),[I,A]=g.useState(null),[P,L]=g.useState(!1);g.useEffect(()=>{t&&(f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),x(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),S(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),j(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),L(!1),A(null))},[t?.id]);const F=n.findIndex(M=>M.id===t.id),Q=F>0?()=>r(n[F-1].id):void 0,q=F>=0&&F<n.length-1?()=>r(n[F+1].id):void 0,B=async()=>{let M;try{M=JSON.parse(d)}catch{Ye.error("Input must be valid JSON");return}let $;if(h.trim())try{$=JSON.parse(h)}catch{Ye.error("Ground Truth must be valid JSON");return}let z;if(m.trim())try{z=JSON.parse(m)}catch{Ye.error("Metadata must be valid JSON");return}let U=null;if(y.trim())try{U=JSON.parse(y)}catch{Ye.error("Expected Trajectory must be valid JSON");return}let G;if(b.trim())try{const ee=JSON.parse(b);if(!Array.isArray(ee)){Ye.error("Tool Mocks must be a JSON array");return}G=ee}catch{Ye.error("Tool Mocks must be valid JSON");return}else G=[];let ne;if(_.trim())try{ne=JSON.parse(_)}catch{Ye.error("Request Context must be valid JSON");return}let X;k?X=C:t.scorerIds!==void 0&&(X=null);try{const ee=await o.mutateAsync({datasetId:e,itemId:t.id,input:M,groundTruth:$,metadata:z,expectedTrajectory:U,toolMocks:G,scorerIds:X,requestContext:ne});Ye.success("Item updated successfully"),j(ee.scorerIds!==void 0),T(ee.scorerIds??[]),u(!1),A(null)}catch(ee){const ie=kjs(ee);ie?A(ie):Ye.error(`Failed to update item: ${ee instanceof Error?ee.message:"Unknown error"}`)}},V=()=>{f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),x(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),S(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),j(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},H=M=>{f(M),I?.field==="input"&&A(null)},D=M=>{p(M),I?.field==="groundTruth"&&A(null)},K=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Ye.success("Item deleted successfully"),L(!1),s()}catch(M){Ye.error(`Failed to delete item: ${M instanceof Error?M.message:"Unknown error"}`)}};return a.jsxs(a.Fragment,{children:[a.jsxs(Tt.Header,{children:[a.jsx(Tt.CloseButton,{onClick:s,tooltip:"Close detail panel"}),a.jsxs(Tt.Heading,{children:["Item",a.jsx(Tt.CopyId,{id:t.id})]}),a.jsxs(Tt.HeaderActions,{children:[!c&&a.jsxs(a.Fragment,{children:[a.jsx(ue,{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(dwe,{})}),a.jsxs(ct,{children:[a.jsx(ct.Trigger,{asChild:!0,children:a.jsx(ue,{size:"sm",variant:"ghost",tooltip:"Open actions menu","aria-label":"Open actions menu",children:a.jsx(Q0,{})})}),a.jsxs(ct.Content,{align:"end",className:"w-48",children:[a.jsxs(ct.Item,{onSelect:()=>u(!0),children:[a.jsx(Bc,{}),"Edit"]}),a.jsxs(ct.Item,{onSelect:()=>L(!0),variant:"destructive",children:[a.jsx(Xo,{}),"Delete Item"]})]})]})]}),a.jsx(Tt.NextPrevNav,{onPrevious:Q,onNext:q,previousLabel:"Go to previous item",nextLabel:"Go to next item"})]})]}),a.jsx(Tt.Content,{children:c?a.jsx(LOs,{inputValue:d,setInputValue:H,groundTruthValue:h,setGroundTruthValue:D,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(Dye,{item:t})}),a.jsx(Ut,{open:P,onOpenChange:L,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:K,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function Cjs(){const{datasetId:e,items:t,isLoadingItems:n,currentItemId:r,openItem:s,close:i}=ZVt(),o=g.useMemo(()=>r?t.find(d=>d.id===r):void 0,[t,r]),{data:l,isLoading:c}=gOt({datasetId:o?"":e,itemId:!o&&r?r:"",queryOptions:{enabled:!!(!o&&e)&&!!(!o&&r&&r)}}),u=o??l??void 0;return a.jsx(Ojs,{datasetId:e,item:u,itemId:r,fallback:n||c?a.jsx(Tt.LoadingData,{}):a.jsxs(Tt.NoData,{children:['No loaded item "',r,'".']}),items:t,onItemChange:s,onClose:i})}function F7({crumbs:e,children:t}){return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:e}),children:[a.jsx("h1",{className:"sr-only",children:"Dataset"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:t})]})}function _js(){const{datasetId:e,itemId:t}=jr(),n=[Ts("/datasets"),{..._K,to:`/datasets/${encodeURIComponent(e)}`},...t?[{id:"dataset-items",label:"Items"},{id:"dataset-item",label:POt(t)}]:[]],r=Dr(),[s,i]=ci(),{activeVersion:o,handleVersionChange:l}=pAe(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}=zx({datasetId:e,queryOptions:{enabled:!!e}}),{data:S=[],isLoading:k}=nA({datasetId:e,search:void 0,version:o,queryOptions:{enabled:!!e}}),j=!k&&S.length===0;if(b)return null;if(x&&Cs(x))return a.jsx(F7,{crumbs:n,children:a.jsx(ui,{})});if(x&&_s(x))return a.jsx(F7,{crumbs:n,children:a.jsx(Gs,{resource:"datasets"})});if(x&&Ik(x)||!b&&!x&&!y)return a.jsx(F7,{crumbs:n,children:a.jsx(Xt,{titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:a.jsx(ue,{render:a.jsx(ac,{to:"/datasets"}),icon:a.jsx(vd,{}),children:"Back to Datasets"})})});if(x)return a.jsx(F7,{crumbs:n,children:a.jsx(Xt,{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(NOs,{datasetId:e,items:S,isLoadingItems:k,children:[a.jsxs("div",{className:"h-full",children:[a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:n}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{children:a.jsx(POs,{datasetId:e,onAddItemClick:()=>f(!0),belowToolbarSlot:a.jsx($Os,{datasetId:e}),leftSlot:a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"mr-3 whitespace-nowrap",children:y?.createdAt?`Created ${Jr(y.createdAt,"date-time")}`:""}),rightSlot:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ue,{render:a.jsx(ac,{to:`/experiments?dataset=${e}`}),icon:a.jsx(lL,{}),children:"View experiments"}),a.jsx(VVt,{datasetId:e,value:o,onValueChange:l,currentVersion:y?.version,className:"w-36"}),j?a.jsxs(Fn,{children:[a.jsx(Mn,{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(ue,{variant:"primary",icon:a.jsx(Uc,{}),children:"Run Experiment"})})})}),a.jsx(Dn,{children:"Add items to the dataset before running an experiment"})]}):a.jsx(ue,{variant:"primary",onClick:()=>u(!0),icon:a.jsx(Uc,{}),children:"Run Experiment"}),a.jsxs(ct,{children:[a.jsx(ct.Trigger,{asChild:!0,children:a.jsx(ue,{size:"lg","aria-label":"Dataset actions menu",children:a.jsx(Q0,{})})}),a.jsxs(ct.Content,{align:"end",className:"w-48",children:[a.jsxs(ct.Item,{onSelect:()=>{r(`/datasets/${e}/edit`)},children:[a.jsx(Bc,{})," Edit Dataset"]}),a.jsxs(ct.Item,{onSelect:()=>v(!0),children:[a.jsx(zm,{})," Duplicate Dataset"]}),a.jsxs(ct.Item,{onSelect:()=>p(!0),variant:"destructive",children:[a.jsx(Xo,{})," Delete Dataset"]})]})]})]})})})]}),a.jsx(Cjs,{})]}),a.jsx(eee,{initialDatasetId:e,initialDatasetVersion:o??void 0,open:c,onOpenChange:u,onSuccess:C},`${e}:${o??"latest"}`),a.jsx(MOs,{datasetId:e,open:d,onOpenChange:f}),y&&a.jsx(Wks,{open:m,onOpenChange:v,sourceDatasetId:y.id,sourceDatasetName:y.name,sourceDatasetDescription:y.description,sourceDatasetTargetType:y.targetType}),y&&a.jsx(Yks,{open:h,onOpenChange:p,datasetId:y.id,datasetName:y.name,onSuccess:T})]})}const rqt=[Ts("/datasets"),_K,{id:"dataset-edit",label:"Edit dataset"}];function pue({children:e}){return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:rqt}),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 Tjs(){const{datasetId:e}=jr(),t=Dr(),{data:n,error:r,isLoading:s}=zx({datasetId:e,queryOptions:{enabled:!!e}}),i=()=>{t(`/datasets/${e}`)};return s?null:r&&Cs(r)?a.jsx(pue,{children:a.jsx(ui,{})}):r&&_s(r)?a.jsx(pue,{children:a.jsx(Gs,{resource:"datasets"})}):r||!n?a.jsx(pue,{children:a.jsx(Xt,{tone:"error",titleSlot:"Failed to load dataset",descriptionSlot:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:rqt}),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(Vh,{className:"mb-6 p-0",children:a.jsxs(Vh.Column,{children:[a.jsxs(Vh.Title,{children:[a.jsx(yv,{})," Edit dataset"]}),a.jsx(Vh.Description,{children:n.name})]})}),a.jsx(hl,{className:"p-4",children:a.jsx(Kks,{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 Btt(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 Utt(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]})," · ",Jr(r,"date-time")]}),n.isLatest?a.jsx(Mt,{variant:"blue",size:"xs",className:"ml-auto",children:"Latest"}):null]}),disabled:t?.has(n.datasetVersion)??!1}})}function Vtt(e){const t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function Ejs(){const{datasetId:e,itemId:t}=jr(),[n,r]=ci(),s=[Ts("/datasets"),_K,{id:"dataset-item",label:POt(t),to:e&&t?`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`:void 0},{id:"dataset-item-versions",label:"Item Version History"}],i=Vtt(n.get("version")),o=Vtt(n.get("compare")),l=n.get("view")==="diff",{data:c,error:u}=zx({datasetId:e??"",queryOptions:{enabled:!!e}}),{data:d,isLoading:f}=_cr({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}=Tcr({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&&Cs(u))return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx(ui,{variant:"fill"})]});if(u&&_s(u))return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx(Gs,{variant:"fill",resource:"datasets"})]});if(!e||!t)return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsx("div",{className:"py-5 text-center text-muted-foreground",children:a.jsx("p",{children:"Item not found."})})})]});const b=!!(h&&v),S=l&&b,k=h?Btt(h,e):null,j=v?Btt(v,e):null,C=(h?.datasetVersion??0)<(v?.datasetVersion??0);return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:s}),headerActions:b&&a.jsx(ue,{variant:"ghost",size:"sm",onClick:()=>x("view",l?null:"diff"),children:l?a.jsxs(a.Fragment,{children:[a.jsx(ewe,{})," Default View"]}):a.jsxs(a.Fragment,{children:[a.jsx(iEn,{})," Diff View"]})}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsxs("div",{className:"grid min-h-0 grid-cols-1 gap-4 md:grid-cols-2",children:[a.jsxs(hl,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[a.jsx(kQ,{children:a.jsx(qtt,{label:"Version",value:p!=null?String(p):"",options:Utt(d??[],m!=null?new Set([m]):void 0),onValueChange:T=>x("version",Number(T))})}),a.jsx(qm,{className:"grid content-start gap-5 overflow-y-auto",children:f?a.jsx(Y,{as:"p",variant:"body",tone:"muted",children:"Loading..."}):k?a.jsx(Dye,{item:k,diff:S&&j?{against:j,side:C?"a":"b"}:void 0}):a.jsx(Y,{as:"p",variant:"body",tone:"muted",children:"Item data not available"})})]}),a.jsxs(hl,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[a.jsx(kQ,{children:a.jsx(qtt,{label:"Compare version",value:m!=null?String(m):"",placeholder:"Select a version to compare",options:Utt(d??[],p!=null?new Set([p]):void 0),onValueChange:T=>x("compare",Number(T))})}),a.jsx(qm,{className:"grid content-start gap-5 overflow-y-auto",children:m==null?a.jsx(Xt,{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(Dye,{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 qtt({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(dwe,{className:"size-4 opacity-50"}),a.jsxs(ps,{value:t,onValueChange:s,children:[a.jsx(gs,{"aria-label":e,className:"w-full",children:a.jsx(ms,{placeholder:r,className:"flex-1"})}),a.jsx(vs,{children:n.map(i=>a.jsx(hr,{value:i.value,disabled:i.disabled,children:i.label},i.value))})]})]})}const B7=[Ts("/datasets"),_K,{id:"dataset-versions",label:"Versions"}];function Ijs(){const{datasetId:e}=jr(),[t]=ci(),n=t.get("ids")?.split(",").map(Number).filter(m=>!isNaN(m)&&m>0)??[],r=Dr(),{data:s,error:i}=zx({datasetId:e??"",queryOptions:{enabled:!!e}}),o=nA({datasetId:e??"",search:void 0,version:n[0]??null,queryOptions:{enabled:!!e}}),l=nA({datasetId:e??"",search:void 0,version:n[1]??null,queryOptions:{enabled:!!e}}),c=g.useMemo(()=>o.data??[],[o.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const m=new Map;for(const v of[...c,...u])m.has(v.id)||m.set(v.id,{id:v.id,createdAt:new Date(v.createdAt)});return[...m.values()].sort((v,y)=>y.createdAt.getTime()-v.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(m=>[m.id,m])),[c]),h=g.useMemo(()=>new Map(u.map(m=>[m.id,m])),[u]);if(i&&Cs(i))return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:B7}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx(ui,{variant:"fill"})]});if(i&&_s(i))return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:B7}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx(Gs,{variant:"fill",resource:"datasets"})]});if(!e||n.length<2)return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:B7}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsx("div",{className:"py-5 text-center text-muted-foreground",children:a.jsx("p",{children:"Select at least two versions to compare."})})})]});const p=(m,v)=>{r(`/datasets/${e}/versions?ids=${m},${v}`,{replace:!0})};return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:B7}),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(Vh,{children:[a.jsxs(Vh.Column,{children:[a.jsxs(Vh.Title,{children:[a.jsx(hNn,{})," Compare Dataset Versions"]}),a.jsx(Vh.Description,{children:a.jsxs(cv,{children:[a.jsx(dwe,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),a.jsx(Vh.Column,{children:a.jsx(ue,{render:a.jsx(ac,{to:`/datasets/${e}`}),icon:a.jsx(vd,{}),children:"Back to Dataset"})})]}),a.jsx(gjs,{children:a.jsxs(nqt,{children:[a.jsx(bjs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:p}),a.jsx(Sjs,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:h})]})})]})})]})}const Njs=[Ts("/datasets"),{id:"dataset-new",label:"Create new dataset"}];function Ajs(){const e=Dr(),[t]=ci(),n=t.get("targetType"),r=XJ(n)?n:void 0,s=t.get("targetIds"),i=r&&s?s.split(",").map(l=>l.trim()).filter(Boolean):void 0,o=l=>{e(`/datasets/${l}`)};return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Njs}),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(Vh,{className:"mb-6 p-0",children:a.jsxs(Vh.Column,{children:[a.jsxs(Vh.Title,{children:[a.jsx(yv,{})," Create new dataset"]}),a.jsx(Vh.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),a.jsx(hl,{className:"p-4",children:a.jsx(Uks,{targetType:r,targetIds:i,onSuccess:o,onCancel:()=>{e(-1)}})})]})})]})}const sqt=(e,{experimentId:t,targetType:n,targetId:r,experiments:s,isLoadingExperiments:i=!1,queryOptions:o})=>{const l=Ge(),c=s!==void 0,{data:u,isLoading:d}=KVt({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=_t({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}},Pjs=(e={})=>sqt("needs-review",e),$js=(e={})=>sqt("complete",e);function Rjs({queryOptions:e}={}){const t=Ge();return _t({queryKey:["experiment-review-summary"],queryFn:()=>t.getExperimentReviewSummary(),...e})}function iqt({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:s}){const{deleteExperiment:i}=pl(),o=async()=>{try{await i.mutateAsync(n),Ye.success("Experiment deleted successfully"),t(!1),s?.()}catch(l){Ye.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(ue,{icon:a.jsx(Xo,{}),variant:"primary",onClick:o,disabled:i.isPending,children:i.isPending?"Deleting...":"Delete"})]})]})})}function oqt(e){const t=Tv(e.id)??e.id;return e.name||`Experiment #${t}`}const Mjs=60;function Djs({experiment:e}){return a.jsx("span",{className:"block min-w-0 truncate text-left text-muted-foreground",children:oqt(e)})}function Ljs({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<=Mjs?n:a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:n}),a.jsx(Dn,{children:t})]})}function zjs(){const{data:e}=Cp(),{data:t}=ng(),{data:n}=Fx(),{data:r}=LP();return{agents:e,workflows:t,scorers:n,processors:r}}const Fjs={agent:Uo,workflow:Ol,scorer:tw,processor:aj},Bjs={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},Ujs="External (caller-run)";function Vjs(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:i,targetId:o}=e;if(!o)return Ujs;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 qjs({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(_e.Cell,{children:a.jsx(Djs,{experiment:e})}),a.jsx(_e.Cell,{children:a.jsx(Ljs,{experiment:e})}),t!==void 0&&a.jsx(_e.TextCell,{children:t}),a.jsx(_e.Cell,{children:a.jsx(Qjs,{experiment:e})}),a.jsx(_e.Cell,{children:a.jsx(Mt,{variant:djs[r]??"neutral",indicator:"dot",children:F2[r]??r})}),a.jsx(_e.TextCell,{className:"text-center",children:o}),a.jsx(_e.TextCell,{className:"text-center",children:s}),a.jsx(_e.TextCell,{className:"text-center",children:a.jsx("span",{className:i>0?"text-destructive-foreground":"",children:i})}),a.jsx(_e.Cell,{className:"text-center",children:a.jsx(Zjs,{review:n})}),a.jsx(_e.TextCell,{children:Jr(e.createdAt,"date")??"—"})]})}function Qjs({experiment:e}){const t=zjs(),n=Vjs(e,t),r=e.targetId?e.targetType:null,s=r?Fjs[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":Bjs[r],children:a.jsx(s,{})}),a.jsx("span",{className:r?"truncate":"truncate text-placeholder",children:n})]})}function Zjs({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(Mt,{size:"xs",variant:"warning",children:[e.needsReview," pending"]}):a.jsxs(Mt,{size:"xs",variant:"success",children:[e.complete,"/",t," reviewed"]})}const Wjs=`${ajs} ${ljs} ${cjs} ${ujs}`,mue=`${Wjs} auto`,Hjs=[{label:fy.experiment},{label:fy.description},{label:fy.dataset},{label:fy.target},{label:fy.status,sortKey:"status"},{label:fy.items,className:"text-center"},{label:fy.succeeded,className:"text-center"},{label:fy.failed,className:"text-center"},{label:fy.review,className:"text-center"},{label:fy.date,sortKey:"createdAt"}],Gjs=e=>e.stopPropagation();function Kjs({experiment:e,rowProps:t,onSelect:n,featured:r,onDelete:s,leadingCell:i,children:o}){const l=i?2:void 0,{paths:c,Link:u}=Tn(),d=g.useRef(null);return a.jsxs(_e.RowWrapper,{...t,onSelectRow:n??(()=>d.current?.click()),children:[i,n?a.jsx(_e.RowButton,{colStart:l,colEnd:-2,featured:r,tabIndex:-1,onClick:f=>{f.stopPropagation(),n()},children:o}):a.jsx(_e.RowLink,{ref:d,colStart:l,colEnd:-2,featured:r,to:c.experimentLink(e.id),LinkComponent:u,tabIndex:-1,onClick:Gjs,children:o}),a.jsx(_e.ActionsCell,{className:"pl-2",children:a.jsx(ue,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"Delete experiment","aria-label":`Delete experiment ${e.name??e.id}`,onClick:f=>{f.stopPropagation(),s()},children:a.jsx(Xo,{className:"size-4"})})})]})}function Yjs({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:i="all",datasetFilter:o="all",selection:l,onSelectExperiment:c,selectedExperimentId:u,keyboardGlobal:d=!0,isFetchingNextPage:f,hasNextPage:h,setEndOfListElement:p,sort:m,onSortChange:v}){const y=g.useMemo(()=>{const A=new Map;return t?.forEach(P=>A.set(P.id,P.name)),A},[t]),x=g.useMemo(()=>m?e:[...e].sort((A,P)=>{const L=A.createdAt?new Date(A.createdAt).getTime():0;return(P.createdAt?new Date(P.createdAt).getTime():0)-L}),[e,m]),b=g.useMemo(()=>{const A=s.toLowerCase();return x.filter(P=>{const L=P.datasetId?y.get(P.datasetId)??"":"",F=!A||P.id.toLowerCase().includes(A)||(P.name??"").toLowerCase().includes(A)||L.toLowerCase().includes(A)||(P.targetId??"").toLowerCase().includes(A),Q=i==="all"||P.status===i,q=o==="all"||P.datasetId===o;return F&&Q&&q})},[x,s,y,i,o]),{containerRef:S,getRowProps:k}=Fu({count:b.length,global:d}),[j,C]=g.useState(null);if(r)return a.jsx(Lu,{columns:mue});const _=(l?.selectedExperimentIds.length??0)===0||b.length===0?!1:b.every(A=>l?.selectedExperimentIds.includes(A.id))?!0:"indeterminate",N=l?`auto ${mue}`:mue,I=Hjs.map(A=>A.sortKey&&v?a.jsx(_e.SortableTopCell,{className:A.className,sortKey:A.sortKey,sort:m?.key===A.sortKey?m.direction:void 0,onSortChange:v,children:A.label},A.label):a.jsx(_e.TopCell,{className:A.className,children:A.label},A.label));return a.jsxs(_e,{columns:N,scrollRef:S,children:[a.jsx(_e.Top,{hasLeadingCell:l!==void 0,children:l?a.jsxs(a.Fragment,{children:[a.jsx(_e.TopSelectCell,{checked:_,onToggle:()=>l.onToggleAll(b.map(A=>A.id)),"aria-label":"Select all experiments"}),a.jsxs(_e.TopCells,{colStart:2,children:[I,a.jsx(_e.TopCell,{"aria-hidden":!0,children:null})]})]}):a.jsxs(a.Fragment,{children:[I,a.jsx(_e.TopCell,{"aria-hidden":!0,children:null})]})}),b.length===0&&!h?a.jsx(_e.NoMatch,{message:"No experiments match your filters"}):null,b.map((A,P)=>{const L=A.datasetId?y.get(A.datasetId)??Tv(A.datasetId)??A.datasetId:"—",F=a.jsx(qjs,{experiment:A,datasetName:L,review:n?.get(A.id)}),Q=l?.selectedExperimentIds.includes(A.id)??!1;return a.jsx(Kjs,{experiment:A,rowProps:k(P),onSelect:c?()=>c(A):void 0,featured:Q||u===A.id,onDelete:()=>C(A),leadingCell:l&&a.jsx(_e.SelectCell,{checked:Q,onToggle:()=>l.onToggleSelection(A.id),"aria-label":`Select experiment ${A.id}`}),children:F},A.id)}),a.jsx(_e.NextPageLoading,{isLoading:f,hasMore:h,setEndOfListElement:p}),j&&a.jsx(iqt,{open:!0,onOpenChange:A=>{A||C(null)},experimentId:j.id,experimentName:j.name??void 0})]})}const Xjs=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function Jjs(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const eCs=({onRunExperiment:e})=>a.jsx(Xt,{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(ue,{variant:"primary",onClick:e,icon:a.jsx(Uc,{}),children:"Run Experiment"}),a.jsx(ue,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Experiments Documentation"})]}),variant:"fill"});function tCs({selectedCount:e,onClearSelection:t,onCompare:n,compareDisabledReason:r}){const s=e===0;return a.jsxs("div",{className:"flex min-h-8 items-center gap-1 whitespace-nowrap",children:[a.jsxs(ue,{variant:"ghost",size:"sm",disabled:s,iconEnd:s?void 0:a.jsx(zn,{}),onClick:t,tooltip:s?void 0:"Clear selection",className:"mr-2 tabular-nums",children:[e," selected"]}),r?a.jsxs(Fn,{children:[a.jsx(Mn,{render:a.jsx("span",{className:"cursor-not-allowed",tabIndex:0}),children:a.jsx(ue,{size:"sm",disabled:!0,tabIndex:-1,icon:a.jsx(C6e,{}),children:"Compare"})}),a.jsx(Dn,{children:r})]}):a.jsx(ue,{size:"sm",onClick:n,icon:a.jsx(C6e,{}),children:"Compare"})]})}const yAe="search",xAe="status",bAe="dataset",QA="all",nCs=[{id:"contains",label:"contains"},{id:"is",label:"is"}],rCs=Xjs.filter(e=>e.value!==QA),sCs=({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:s})=>{const i=[];return e&&i.push(uv(yAe,e,"contains")),i.push(...aAe({targetType:r,targetId:s})),t!==QA&&i.push(uv(xAe,t)),n!==QA&&i.push(uv(bAe,n)),i},iCs=e=>({...lAe(e),search:dv(e,yAe),statusFilter:dv(e,xAe)||QA,datasetFilter:dv(e,bAe)||QA});function oCs({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:s,datasetOptions:i,onChange:o}){const l=cAe(r),c=g.useMemo(()=>[{id:yAe,label:"Search",icon:Su,search:!0,operators:["contains"]},...l,{id:xAe,label:"Status",icon:vP,color:m0("orange"),operators:["is"],strict:!0,suggestions:rCs},{id:bAe,label:"Dataset",icon:yv,color:m0("blue"),operators:["is"],strict:!0,suggestions:i.filter(d=>d.value!==QA)}],[l,i]),u=g.useMemo(()=>sCs({search:e,statusFilter:t,datasetFilter:n,targetType:r,targetId:s}),[e,t,n,r,s]);return a.jsxs(wu,{fields:c,operators:nCs,value:u,onValueChange:d=>o(iCs(d)),createItemId:d=>d,"aria-label":"Experiments filters",className:"min-w-64 flex-1",children:[a.jsx(wu.Chips,{}),a.jsx(wu.Input,{placeholder:"Filter experiments…"})]})}function aCs({search:e,statusFilter:t,datasetFilter:n,datasetOptions:r,targetType:s,targetId:i,onFiltersChange:o,selection:l}){return a.jsxs(ar,{children:[a.jsx(ar.Start,{children:a.jsx(oCs,{search:e,statusFilter:t,datasetFilter:n,datasetOptions:r,targetType:s,targetId:i,onChange:o})}),a.jsx(ar.End,{children:a.jsx(tCs,{...l})})]})}const lCs={present:!1,targetType:null,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Qtt=e=>e?e instanceof Date?e.toISOString():e:null,cCs=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},uCs=(e,t,n,r)=>{if(!e)return lCs;const s=new Map;for(const i of n??[])s.set(i.scorerId,i.reason??null);return{present:!0,targetType:t?.targetType??null,output:e.output,metadata:t?.metadata??null,comment:t?.comment??null,error:t?.error??null,startedAt:Qtt(t?.startedAt),completedAt:Qtt(t?.completedAt),scores:Object.entries(e.scores).map(([i,o])=>({scorerId:i,value:o,reason:s.get(i)??null})).sort((i,o)=>i.scorerId.localeCompare(o.scorerId)),usage:t?.traceId?r?.[t.traceId]:void 0}},dCs=(e,t)=>{const n={};for(const r of new Set([...e.scores,...t.scores].map(s=>s.scorerId))){const s=e.scores.find(o=>o.scorerId===r)?.value??null,i=t.scores.find(o=>o.scorerId===r)?.value??null;n[r]=s!=null&&i!=null?i-s:null}return n};function w3(e){return!e.startedAt||!e.completedAt?null:new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime()}const fCs=(e,t)=>{const n=w3(e),r=w3(t);return n!=null&&r!=null?r-n:null},hCs=(e,t)=>{const n=e.usage?.estimatedCost,r=t.usage?.estimatedCost;if(!(n===void 0||r===void 0))return e.usage?.costUnit===t.usage?.costUnit?r-n:void 0},pCs=(e,t)=>{const n=qA(e.usage),r=qA(t.usage);return n!==void 0&&r!==void 0?r-n:void 0},mCs=({comparison:e,experimentIds:t,resultsById:n,scoresById:r,usageById:s})=>{if(!e)return[];const i=new Map(t.map(o=>[o,cCs(n?.[o])]));return e.items.map(o=>{const l=t.map(u=>uCs(o.results[u],i.get(u)?.get(o.itemId),r?.[u]?.[o.itemId],s?.[u]?.traces)),[c]=l;return{itemId:o.itemId,input:o.input,groundTruth:o.groundTruth,sides:l.map((u,d)=>({...u,experimentId:t[d],role:d===0?"baseline":"contender",deltas:d===0?null:dCs(c,u),durationDeltaMs:d===0?null:fCs(c,u),costDelta:d===0?void 0:hCs(c,u),tokenDelta:d===0?void 0:pCs(c,u)}))}})};function nN({value:e}){return a.jsx("div",{className:"min-w-0 p-3 text-foreground",children:typeof e=="string"?a.jsx(ql,{children:e}):a.jsx(jl,{code:JSON.stringify(e??null,null,2),lang:"json",className:"text-caption text-wrap break-all text-muted-foreground"})})}const nee="grid content-start gap-5";function Kg({title:e,actions:t,tone:n="default",collapsible:r=!0,framed:s=!1,children:i}){const o=AX({collapsedHeight:160}),l=r?a.jsx(V6,{state:o,expandLabel:"Expand",children:i}):i;return a.jsxs("section",{className:"grid min-w-0 gap-2",children:[a.jsxs("div",{className:"flex h-7 items-center justify-between gap-2",children:[a.jsx(Tt.SectionHeading,{className:Z(n==="negative"&&"text-destructive-foreground"),children:e}),a.jsx("div",{className:"ml-auto flex items-center gap-1",children:t})]}),a.jsxs("div",{role:"region","aria-label":e,className:"min-w-0",children:[s?n==="negative"?a.jsx("div",{className:"min-w-0 overflow-hidden rounded-lg border border-destructive-edge bg-destructive-subtle",children:l}):a.jsx(hl,{className:"min-w-0 overflow-hidden",children:l}):l,r&&o.isExpanded&&o.isClipped&&a.jsx("div",{className:"flex justify-center pt-1",children:a.jsx(ue,{size:"sm",variant:"ghost",icon:a.jsx(fL,{}),onClick:()=>o.setExpanded(!1),children:"Collapse"})})]})]})}function Ztt({label:e,value:t}){return t==null?null:a.jsx(Kg,{title:e,framed:!0,children:a.jsx(nN,{value:t})})}const gCs=e=>e.toFixed(2);function vCs({delta:e,format:t=gCs,higherIsBetter:n=!0}){const r=n?e>0:e<0,s=e===0?"text-muted-foreground":r?"text-success-indicator":"text-destructive-foreground",i=e>0?"+":e<0?"-":"";return a.jsxs("span",{className:Z("inline-flex items-center gap-1 tabular-nums",s),children:[i,t(Math.abs(e)),a.jsx("span",{"aria-hidden":!0,className:"inline-flex size-3.5 shrink-0 [&>svg]:size-3.5",children:e>0?a.jsx(G0e,{}):e<0?a.jsx(xht,{}):null})]})}function aqt({scorerId:e}){const{Link:t,paths:n}=Tn();return a.jsx(t,{href:n.scorerLink(e),"aria-label":`Open ${e}`,className:"min-w-0 truncate hover:text-foreground hover:underline",children:e})}function wAe({metrics:e}){if(e.length===0)return null;const t=e.some(n=>n.delta!=null);return a.jsx("dl",{className:Z("grid auto-rows-[minmax(1.5rem,auto)] items-center gap-x-4 gap-y-1",t?"grid-cols-[minmax(0,1fr)_auto_auto]":"grid-cols-[minmax(0,1fr)_auto]"),children:e.map(({id:n,icon:r,label:s,value:i,delta:o,formatDelta:l,higherIsBetter:c,emphasis:u})=>a.jsxs(g.Fragment,{children:[a.jsxs("dt",{className:"flex min-w-0 items-center gap-1.5 text-body-sm text-muted-foreground [&>svg]:size-3.5 [&>svg]:shrink-0",children:[r,s]}),a.jsx("dd",{className:Z("flex min-w-0 justify-end text-right text-foreground tabular-nums",u?"text-heading font-semibold":"text-body-sm"),children:i}),t&&a.jsx("dd",{className:"flex justify-end text-body-sm",children:o!=null&&a.jsx(vCs,{delta:o,format:l,higherIsBetter:c})})]},n))})}function Bye({usage:e,showUsage:t,durationMs:n,costDelta:r,tokenDelta:s,durationDeltaMs:i,scores:o}){const l=e?.costUnit,c=t?[{id:"cost",icon:a.jsx(HH,{}),label:"Cost",value:Rz(e?.estimatedCost,l),delta:r??null,formatDelta:eqt(l),higherIsBetter:!1}]:[],u=t?[{id:"tokens",icon:a.jsx(Z0,{}),label:"Tokens",value:iS(qA(e)),delta:s??null,formatDelta:iS,higherIsBetter:!1}]:[],d=n==null?[]:[{id:"duration",icon:a.jsx(fC,{}),label:"Duration",value:Vc(n)??"-",delta:i??null,formatDelta:JVt,higherIsBetter:!1}];return[...c,...d,...u,...o.map(f=>({id:`scorer:${f.scorerId}`,icon:a.jsx(tw,{}),label:f.label??a.jsx(aqt,{scorerId:f.scorerId}),value:Fye(f.value),delta:f.delta??null}))]}function Wtt(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function yCs(e,t){return Bye({usage:e.usage,showUsage:t,durationMs:w3(e),costDelta:e.costDelta,tokenDelta:e.tokenDelta,durationDeltaMs:e.durationDeltaMs,scores:e.scores.map(n=>({scorerId:n.scorerId,value:n.value,delta:e.deltas?.[n.scorerId]??null}))})}function xCs({column:e,isLoading:t,showUsage:n=!1}){if(t)return a.jsx("div",{className:"flex h-32 items-center justify-center",children:a.jsx(_n,{})});if(!e.present)return a.jsx(Y,{tone:"muted",className:"py-5 text-center",children:"Not present in this experiment"});const r=Wtt(e.output),s=vAe(e),i=tee(e),o=yCs(e,n);return a.jsxs("div",{className:nee,children:[o.length>0&&a.jsx(Kg,{title:"Metrics",collapsible:!1,children:a.jsx(wAe,{metrics:o})}),i?a.jsx(Kg,{title:"Error",tone:"negative",framed:!0,actions:a.jsx(ii,{content:i}),children:a.jsx(Y,{tone:"muted",className:"p-3 break-words",children:i})}):a.jsx(Kg,{title:"Output",framed:!0,actions:a.jsx(ii,{content:r}),children:a.jsx(nN,{value:s??e.output})}),e.comment&&a.jsx(Kg,{title:"Comment",framed:!0,children:a.jsx(nN,{value:e.comment})}),e.metadata&&Object.keys(e.metadata).length>0&&a.jsx(Kg,{title:"Metadata",children:a.jsx("dl",{className:"grid gap-1",children:Object.entries(e.metadata).map(([l,c])=>a.jsxs("div",{className:"flex items-start justify-between gap-4",children:[a.jsx("dt",{className:Ma({tone:"muted",variant:"body"}),children:l}),a.jsx("dd",{className:Z(Ma({tone:"ink",variant:"body",font:"mono"}),"break-all"),children:Wtt(c)})]},l))})})]})}const Htt={baseline:"purple",contender:"blue"};function bCs({role:e,label:t,experiment:n,summary:r,metrics:s,baselineMetrics:i,versionMismatch:o,onSetBaseline:l,showUsage:c=!1}){const{Link:u,paths:d}=Tn(),f=n?Tv(n.id)??n.id:null,h=n?.createdAt?new Date(n.createdAt):null,p=e==="contender",m=(b,S)=>p?YOs(b,S):null,v=n?[...n.targetId?[{id:"target",icon:n.targetType==="agent"?a.jsx(Uo,{}):a.jsx(HNn,{}),label:n.targetType==="agent"?"Agent":"Target",value:n.targetType==="agent"?a.jsx(u,{href:d.agentLink(n.targetId),className:"min-w-0 truncate hover:underline",children:n.targetId}):a.jsx("span",{className:"min-w-0 truncate",children:n.targetId}),delta:null}]:[],...o?[{id:"dataset-version",icon:a.jsx(uL,{}),label:"Dataset",value:a.jsx("span",{className:"text-warning-foreground",children:"different dataset version"}),delta:null}]:[],...h?[{id:"created-at",icon:a.jsx(C4,{}),label:"Created",value:Jr(h,"date"),delta:null}]:[]]:[],y=c?s:void 0,x=[...y?[{id:"total-cost",icon:a.jsx(HH,{}),label:"Total cost",value:Rz(y.cost,y.costUnit),delta:y.costUnit===i?.costUnit?m(y.cost,i?.cost):null,formatDelta:eqt(y.costUnit),higherIsBetter:!1,emphasis:!0}]:[],...s?[{id:"avg-duration",icon:a.jsx(fC,{}),label:"Avg duration",value:Vc(s.averageDurationMs)??"-",delta:m(s.averageDurationMs,i?.averageDurationMs),formatDelta:JVt,higherIsBetter:!1,emphasis:!0}]:[],...y?[{id:"total-tokens",icon:a.jsx(Z0,{}),label:"Total tokens",value:iS(y.tokens),delta:m(y.tokens,i?.tokens),formatDelta:iS,higherIsBetter:!1}]:[],...v,...s?[{id:"errors",icon:a.jsx(gP,{}),label:"Errors",value:String(s.errorCount),delta:m(s.errorCount,i?.errorCount),formatDelta:String,higherIsBetter:!1}]:[],...s&&r&&r.length>0?[{id:"avg-score",icon:a.jsx(tg,{}),label:"Avg score",value:Fye(s.averageScore),delta:m(s.averageScore,i?.averageScore)}]:[],...(r??[]).map(({scorerId:b,average:S,delta:k})=>({id:`scorer:${b}`,icon:a.jsx(tw,{}),label:a.jsx(aqt,{scorerId:b}),value:Fye(S),delta:p?k:null}))];return a.jsxs("div",{className:nee,children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n&&a.jsx(ue,{render:a.jsx(u,{href:`/experiments/${n.id}`}),size:"sm",className:"max-w-full min-w-0","aria-label":`Open experiment ${n.name||f}`,children:a.jsx("span",{className:"min-w-0 truncate",children:n.name||f})}),a.jsx("div",{className:"ml-auto shrink-0",children:l?a.jsxs(Fn,{children:[a.jsx(Mn,{render:a.jsx("button",{type:"button","aria-label":"Set as baseline",onClick:l,className:Z("cursor-pointer rounded-[7px] hover:brightness-110",ji)}),children:a.jsx(Mt,{variant:Htt[e],size:"md",icon:a.jsx(ex,{}),children:t})}),a.jsx(Dn,{children:"Set as baseline"})]}):a.jsx(Mt,{variant:Htt[e],size:"md",icon:e==="baseline"?a.jsx(ex,{className:"fill-current"}):a.jsx(ex,{}),children:t})})]}),x.length>0&&a.jsx(Kg,{title:"Summary",collapsible:!1,children:a.jsx(wAe,{metrics:x})})]})}const U7="min-w-0 px-4 py-3",Gtt="grid border-border xl:grid-cols-[minmax(22rem,26rem)_repeat(var(--compare-cols),minmax(32rem,1fr))] xl:divide-x xl:divide-border",gue=e=>e===0?"Baseline":`Contender ${e}`,Uye=e=>e!=null,Vye=e=>e.length>0?e.reduce((t,n)=>t+n,0)/e.length:null,Ktt=(e,t,n)=>Vye(e.map(r=>r.sides[t]?.scores.find(s=>s.scorerId===n)?.value??null).filter(Uye)),wCs=(e,t)=>{const n=e.map(r=>r.sides[t]).filter(r=>r?.present);return{errorCount:n.filter(r=>r.error).length,averageScore:Vye(n.flatMap(r=>r.scores.map(s=>s.value)).filter(Uye)),averageDurationMs:Vye(n.map(w3).filter(Uye))}};function SCs({datasetId:e,baselineId:t,contenderIds:n,onSetBaseline:r}){const s=g.useMemo(()=>[t,...n],[t,n]),{data:i,isLoading:o,error:l}=wcr({datasetId:e,experimentIds:s,baselineId:t,queryOptions:{enabled:!!e&&!!t&&n.length>0}}),{data:c,isLoading:u}=Eke({datasetId:e,experimentIds:s}),d=g.useMemo(()=>s.map(C=>({id:C,status:c[C]?.status})),[s,c]),{data:f,isLoading:h}=jcr({datasetId:e,experiments:d}),{data:p}=Ccr({experiments:d}),{supportsMetrics:m,isLoading:v}=O$(),{data:y,isLoading:x}=mAe({experiments:d,supportsMetrics:m}),b=g.useMemo(()=>mCs({comparison:i,experimentIds:s,resultsById:f,scoresById:p,usageById:y}),[i,s,f,p,y]),S=g.useMemo(()=>{const C=[...new Set(b.flatMap(T=>T.sides.flatMap(_=>_.scores.map(N=>N.scorerId))))].sort();return s.map((T,_)=>C.map(N=>{const I=Ktt(b,_,N),A=Ktt(b,0,N),P=_>0&&I!=null&&A!=null?I-A:null;return{scorerId:N,average:I,delta:P}}))},[b,s]),k=g.useMemo(()=>s.map((C,T)=>{const _=y[C]?.summary;return{...wCs(b,T),cost:_?.estimatedCost,costUnit:_?.costUnit,tokens:qA(_)}}),[b,s,y]);if(o||u||v||x)return a.jsx("div",{className:"pointer-events-none fixed inset-0 flex items-center justify-center",children:a.jsx(_n,{})});if(l)return a.jsx(Wt,{variant:"warning",title:"Error loading comparison",children:a.jsx(Wt.Message,{children:l instanceof Error?l.message:"Unknown error"})});if(!i||i.items.length===0)return a.jsx(Y,{as:"p",variant:"body",tone:"muted",className:"py-5 text-center",children:"No comparison data"});const j=c[t];return a.jsx(Ir,{orientation:"horizontal",mask:{x:"6rem"},children:a.jsxs("div",{role:"table","aria-label":"Experiments comparison",className:"grid",style:{"--compare-cols":s.length},children:[a.jsxs("div",{role:"row",className:Z(Gtt,"border-b"),children:[a.jsx("div",{role:"columnheader","aria-label":"Items",className:Z("text-muted-foreground",`${U7} uppercase`),children:a.jsx(Y,{as:"span",variant:"caption",className:"block",children:"Items"})}),s.map((C,T)=>{const _=c[C]??void 0;return a.jsx("div",{role:"columnheader","aria-label":gue(T),className:U7,children:a.jsx(bCs,{role:T===0?"baseline":"contender",label:gue(T),experiment:_,summary:S[T],metrics:h?void 0:k[T],baselineMetrics:h?void 0:k[0],versionMismatch:T>0&&_&&j?_?.datasetVersion!==j?.datasetVersion:void 0,onSetBaseline:T>0&&r?()=>r(C):void 0,showUsage:m})},C)})]}),b.map(C=>a.jsxs("div",{role:"row","aria-label":C.itemId,className:Z(Gtt,"border-b"),children:[a.jsxs("div",{role:"cell",className:Z(U7,nee),children:[a.jsx(Ztt,{label:"Input",value:C.input}),a.jsx(Ztt,{label:"Ground truth",value:C.groundTruth})]}),C.sides.map((T,_)=>a.jsx("div",{role:"cell","aria-label":gue(_),className:U7,children:a.jsx(xCs,{column:T,isLoading:h,showUsage:m})},T.experimentId))]},C.itemId))]})})}const IU=10;function kCs(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 OE=[Ts("/experiments")],OCs=["createdAt","status"];function jCs(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,i]=g.useState(!1),[o,l]=g.useState([]),c=Dr(),[u,d]=ci(),{sort:f,onSortChange:h}=Hk({searchParams:u,setSearchParams:d,allowedKeys:OCs}),p=g.useMemo(()=>f?{field:f.key,direction:f.direction==="asc"?"ASC":"DESC"}:void 0,[f]),m=u.get("dataset")??"all",{targetType:v,targetId:y}=RVt(),x=U=>{t(U.search),r(U.statusFilter),d(G=>{const ne=new URLSearchParams(G),X=(ee,ie)=>{ie?ne.set(ee,ie):ne.delete(ee)};return X("dataset",U.datasetFilter==="all"?"":U.datasetFilter),X(x0,U.targetType),X(Yy,U.targetType===v?U.targetId:""),ne},{replace:!0})},{data:b,isLoading:S,error:k}=Ek(),{data:j,isLoading:C,error:T,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:I}=HOs({datasetId:m==="all"?void 0:m,target:{targetType:v,targetId:y},orderBy:p}),{data:A}=Rjs(),P=g.useMemo(()=>b?.datasets??[],[b?.datasets]),L=g.useMemo(()=>j??[],[j]),F=g.useMemo(()=>Jjs(P),[P]),Q=g.useMemo(()=>kCs(A),[A]),q=S||C,B=T||k,V=U=>{const G=new Set(L.map(ne=>ne.id));l(ne=>{const X=ne.filter(ee=>G.has(ee));return X.includes(U)?X.filter(ee=>ee!==U):X.length>=IU?[...X.slice(0,IU-1),U]:[...X,U]})},H=U=>{l(G=>G.length>0?[]:U.slice(0,IU))},{selectedIds:D,selectedDatasetIds:K}=g.useMemo(()=>{const U=new Map(L.map(ne=>[ne.id,ne.datasetId])),G=o.filter(ne=>U.has(ne));return{selectedIds:G,selectedDatasetIds:new Set(G.map(ne=>U.get(ne)))}},[L,o]),M=D.length<2?"Select at least two experiments to compare":K.size!==1?"Select experiments from the same dataset to compare":void 0,$=()=>{if(D.length<2||M)return;const[U,...G]=D,[ne]=K;if(!ne)return;const X=new URLSearchParams({dataset:ne,baseline:U});for(const ee of G)X.append("contender",ee);c(`/experiments/compare?${X.toString()}`)};if(B&&Cs(B))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:OE}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(ui,{variant:"fill"})]});if(T&&_s(T))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:OE}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Gs,{variant:"fill",resource:"experiments"})]});if(k&&_s(k))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:OE}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Gs,{variant:"fill",resource:"datasets"})]});if(B)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:OE}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Xt,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:B.message})]});const z=a.jsx(eee,{open:s,onOpenChange:i,onSuccess:U=>{c(`/experiments/${U}`)}});return L.length===0&&!q&&m==="all"&&!v?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:OE}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(eCs,{onRunExperiment:()=>i(!0)}),z]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:OE}),headerActions:a.jsx(ue,{variant:"primary",size:"sm",icon:a.jsx(Uc,{}),tooltip:"Run an experiment",onClick:()=>i(!0),children:"Run Experiment"}),actionRow:a.jsx(aCs,{search:e,statusFilter:n,datasetFilter:m,datasetOptions:F,targetType:v,targetId:y,onFiltersChange:x,selection:{selectedCount:D.length,onClearSelection:()=>l([]),onCompare:$,compareDisabledReason:M}}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Yjs,{experiments:L,datasets:P,reviewByExperiment:Q,isLoading:q,search:e,statusFilter:n,datasetFilter:m,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:I,sort:f,onSortChange:h,selection:{selectedExperimentIds:D,onToggleSelection:V,onToggleAll:H}}),z]})}const CCs={baseline:"bg-badge-purple-indicator",contender:"bg-badge-blue-indicator"};function lqt({experimentId:e,name:t,role:n,className:r,trailing:s}){const{Link:i,paths:o}=Tn(),l=t||e.slice(0,8);return a.jsxs(ue,{render:a.jsx(i,{href:o.experimentLink(e)}),variant:"ghost",size:"sm",className:Z("max-w-48 min-w-0",r),"aria-label":`Open experiment ${l}`,children:[n&&a.jsx("span",{"aria-hidden":"true",className:Z("size-1.5 shrink-0 rounded-full",CCs[n])}),a.jsx("span",{className:"min-w-0 truncate",children:l}),s&&a.jsx("span",{className:"ml-auto flex shrink-0",children:s})]})}function cqt(){const[e]=ci(),t=e.get("dataset")??void 0,n=e.get("baseline")??void 0,r=g.useMemo(()=>[...new Set(e.getAll("contender"))].filter(s=>s&&s!==n).slice(0,IU-1),[e,n]);return{datasetId:t,baselineId:n,contenderIds:r}}function uqt(){const{datasetId:e,baselineId:t,contenderIds:n}=cqt(),r=!!(e&&t&&n.length>0);return{datasetId:e,experimentIds:r&&t?[t,...n]:[]}}function _Cs(){const{experimentIds:e}=uqt();return e.length>0?`Comparing ${e.length} experiments`:"Comparing"}function TCs(){const{datasetId:e,experimentIds:t}=uqt(),{data:n}=Eke({datasetId:e??"",experimentIds:t});return t.length===0?null:a.jsxs(G_,{children:[a.jsx(Fk,{delay:0,closeDelay:100,render:a.jsx(ue,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"Show compared experiments",children:a.jsx(dc,{})})}),a.jsx(Bk,{side:"bottom",align:"end",sideOffset:4,showArrow:!1,className:"w-72 p-1.5",children:a.jsx("ul",{"aria-label":"Compared experiments",className:"grid gap-0.5",children:t.map((r,s)=>a.jsx("li",{className:"grid",children:a.jsx(lqt,{className:"w-full max-w-none justify-start",experimentId:r,name:n[r]?.name,role:s===0?"baseline":"contender",trailing:s===0&&a.jsx(Mt,{variant:"purple",size:"sm",icon:a.jsx(ex,{className:"fill-current"}),children:"Baseline"})})},r))})})]})}function ECs({experimentIds:e}){return e.map((t,n)=>a.jsxs("span",{className:"flex items-center gap-2",children:[n>0&&n===e.length-1&&"and",a.jsxs("span",{className:"flex items-center",children:[a.jsx(lqt,{experimentId:t}),n<e.length-2&&","]})]},t))}function ICs({datasetId:e,baselineId:t,contenderIds:n}){const[,r]=ci(),s=g.useMemo(()=>[t,...n],[t,n]),{data:i,isLoading:o,error:l}=Eke({datasetId:e,experimentIds:s}),c=u=>{const d=new URLSearchParams({dataset:e,baseline:u});for(const f of s)f!==u&&d.append("contender",f);r(d)};return l&&Cs(l)?a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Compare"}),a.jsx(ui,{variant:"fill"})]}):l&&_s(l)?a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Compare"}),a.jsx(Gs,{variant:"fill",resource:"experiments"})]}):l&&!Ik(l)?a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Compare"}),a.jsx(Xt,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:l.message})]}):!o&&(l||s.some(u=>!i[u]))?a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Compare"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsxs("div",{className:"py-5 text-center text-muted-foreground",children:[a.jsxs(Y,{as:"p",children:["Experiments must belong to the same dataset (",e,") to be compared."]}),a.jsxs(Y,{className:"mt-2 flex items-center justify-center gap-2",children:["One of",a.jsx(ECs,{experimentIds:s}),"was not found in it."]})]})})]}):a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsxs("div",{className:"grid w-full content-start",children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Experiments comparison"}),a.jsx(SCs,{datasetId:e,baselineId:t,contenderIds:n,onSetBaseline:c})]})})}function NCs(){const{datasetId:e,baselineId:t,contenderIds:n}=cqt();return!e||!t||n.length===0?a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h1",variant:"heading",className:"sr-only",children:"Compare"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsxs("div",{className:"py-5 text-center text-muted-foreground",children:[a.jsx(Y,{as:"p",children:"Select two to ten experiments to compare."}),a.jsxs(Y,{className:"mt-2",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentId}","&contender=","{experimentId}","&contender=","{experimentId}"]})]})})]}):a.jsx(ICs,{datasetId:e,baselineId:t,contenderIds:n})}const ACs=[Ts("/experiments"),{id:"experiments-compare",Component:_Cs,Switcher:TCs}];function PCs(){return a.jsx(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:ACs}),children:a.jsx(NCs,{})})}function $Cs({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[i,o]=g.useState(e.description??""),{updateExperiment:l}=pl(),c=!!r.trim(),u=async d=>{if(d.preventDefault(),!(!c||l.isPending||!e.datasetId))try{await l.mutateAsync({datasetId:e.datasetId,experimentId:e.id,name:r.trim(),description:i.trim()}),Ye.success("Experiment renamed"),n(!1)}catch(f){Ye.error(`Failed to rename experiment: ${f instanceof Error?f.message:"Unknown error"}`)}};return a.jsx(Kr,{open:t,onOpenChange:n,pending:l.isPending,children:a.jsxs(Yr,{children:[a.jsx(Xr,{children:a.jsx(Qr,{children:"Rename Experiment"})}),a.jsxs(Ga,{onSubmit:u,children:[a.jsxs(qr,{children:[a.jsxs(ht,{children:[a.jsx(ut,{required:!0,children:"Name"}),a.jsx(wn,{required:!0,value:r,onChange:d=>s(d.target.value),placeholder:"Enter experiment name",autoFocus:!0})]}),a.jsxs(ht,{children:[a.jsx(ut,{children:"Description"}),a.jsx(wn,{value:i,onChange:d=>o(d.target.value),placeholder:"Enter experiment description (optional)"})]})]}),a.jsxs(Yo,{children:[a.jsx(Ca,{children:"Cancel"}),a.jsx(ja,{type:"submit",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})]})})}function RCs(e){const{data:t}=JL({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}});return g.useMemo(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!t)return[];const n=new Set;for(const r of Object.values(t))for(const s of r)n.add(s.scorerId);return[...n].sort()},[e.scorerIds,t])}const MCs=["agent","workflow","scorer"];function DCs({experiment:e}){const[t,n]=g.useState(!1),r=Dr(),{paths:s}=Tn(),i=RCs(e),o=MCs.find(l=>l===e.targetType);return!e.datasetId||!o||!e.targetId?null:a.jsxs(a.Fragment,{children:[a.jsx(ue,{variant:"primary",size:"sm",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",icon:a.jsx(Uc,{}),children:"Rerun"}),t&&a.jsx(eee,{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 LCs({experiment:e,onDeleteClick:t}){const[n,r]=g.useState(!1),s=!!e.datasetId,i=s||!!t;return a.jsxs(a.Fragment,{children:[a.jsx(DCs,{experiment:e}),i&&a.jsxs(ct,{children:[a.jsx(ct.Trigger,{asChild:!0,children:a.jsx(ue,{variant:"ghost",size:"icon-sm","aria-label":"Experiment actions menu",children:a.jsx(Q0,{})})}),a.jsxs(ct.Content,{align:"end",className:"w-48",children:[s&&a.jsxs(ct.Item,{onSelect:()=>r(!0),children:[a.jsx(Bc,{})," Rename Experiment"]}),t&&a.jsxs(ct.Item,{onSelect:t,variant:"destructive",children:[a.jsx(Xo,{})," Delete Experiment"]})]})]}),n&&a.jsx($Cs,{experiment:e,open:!0,onOpenChange:r})]})}function zCs(e){const{data:t,isLoading:n}=oT({traceId:e,queryOptions:{enabled:!!e}}),s=t?.spans.find(d=>!d.parentSpanId)?.entityType==="agent",{supportsMetrics:i,isLoading:o}=O$(),l=s&&i,c=yye({traceIds:e?[e]:[],enabled:l,autoRefetch:!1}),u=l&&(c.isLoading||c.isPlaceholderData);return{usage:e?c.data?.get(e):void 0,isLoading:!!e&&(n||o||u)}}const Ytt="__create_tag__";function dqt({selectedResults:e,vocabulary:t,onAddTag:n,disabled:r,variant:s}){const[i,o]=g.useState(""),l=g.useMemo(()=>[...t].sort(),[t]),c=g.useMemo(()=>{if(e.length===0)return new Set;const[f,...h]=e;return new Set((f.tags??[]).filter(p=>h.every(m=>(m.tags??[]).includes(p))))},[e]),u=g.useMemo(()=>{const f=l.map(m=>({label:m,value:m,end:c.has(m)?a.jsx(ur,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),h=i.trim();return h.length>0&&!l.includes(h)?[{label:`Create "${h}"`,value:Ytt},...f]:f},[l,c,i]),d=f=>{const h=f===Ytt?i.trim():f;!h||c.has(h)||n(h)};return a.jsx(fl,{"data-testid":"experiment-results-tag-picker",options:u,value:void 0,onValueChange:d,onInputValueChange:o,placeholder:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(Nx,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:s,size:"sm",className:"w-auto min-w-0",disabled:r})}function vue(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function FCs({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(Tt.SectionHeading,{icon:a.jsx(dd,{}),children:"Tool Mocks"}),s&&a.jsx(Wt,{variant:"destructive",title:"Mock mismatch",children:a.jsxs(Wt.Message,{children:[a.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),a.jsxs(Y,{as:"span",variant:"caption",className:"mt-1 block",children:["Called with: ",a.jsx(sh,{children:vue(s.args)})]}),n.length>0&&a.jsxs(Y,{as:"span",variant:"caption",className:"mt-1 block",children:["Unconsumed mocks: ",a.jsx(sh,{children:n.map(o=>vue(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:vue(o.args)})]}),a.jsx(Y,{as:"span",variant:"caption",className:`shrink-0 rounded px-2 py-0.5 ${BCs(o.outcome)}`,children:o.outcome})]},`${o.outcome}-${o.toolName}-${l}`))})]})}function BCs(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 UCs({result:e,itemId:t,fallback:n,title:r,onClose:s,variant:i="drawer",...o}){const l=r??(t?`Experiment item ${t}`:`Experiment result ${e?.id??""}`),c=e?a.jsx(VCs,{result:e,onClose:s,...o}):t?a.jsxs(a.Fragment,{children:[a.jsxs(Tt.Header,{children:[a.jsxs(Tt.Heading,{children:["Experiment item",a.jsx(Tt.CopyId,{id:t})]}),a.jsx(Tt.HeaderActions,{children:a.jsx(Tt.CloseButton,{icon:"x",onClick:s})})]}),n]}):null;return i==="inline"?c?a.jsx(Tt,{variant:"inline",title:l,children:c}):null:a.jsx(Tt,{open:!!(e??t),onClose:s,title:l,depth:1,children:c})}function VCs({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=yue(e.input),y=yue(e.output),x=vAe(e),b=c&&e.status!=="needs-review"&&e.status!=="complete",S=Array.isArray(e.tags)?e.tags:[],k=g.useMemo(()=>[e],[e]),j=!!u||S.length>0,{Link:C}=Tn(),T=m&&e.traceId?e.traceId:void 0,{data:_}=UJ({traceId:T,queryOptions:{enabled:!!T}}),{usage:N,isLoading:I}=zCs(e.traceId),A=I&&(e.targetType==null||e.targetType==="agent"),P=Bye({usage:N,showUsage:!!N||A,durationMs:w3(e),scores:[]}).map(q=>A&&(q.id==="cost"||q.id==="tokens")?{...q,value:a.jsx(xt,{"aria-hidden":!0,className:"h-4 w-14"})}:q),L=typeof e.error=="string"&&e.error?e.error:tee(e),F=[...P,{id:"item-id",icon:a.jsx(nwe,{}),label:"Item Id",value:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"font-mono",title:e.itemId,children:Tv(e.itemId)}),a.jsx(ii,{content:e.itemId,tooltip:"Copy Item Id to clipboard",variant:"link"})]}),delta:null},...e.createdAt?[{id:"created",icon:a.jsx(C4,{}),label:"Created",value:Jr(e.createdAt,"date-time"),delta:null}]:[],...e.status?[{id:"status",icon:a.jsx(L_n,{}),label:"Status",value:a.jsx(HNe,{status:e.status}),delta:null}]:[],...j?[{id:"tags",icon:a.jsx(Nx,{}),label:"Tags",value:a.jsx(QCs,{tags:S,selectedResults:k,onTagsChange:u,tagVocabulary:d,isUpdatingTags:f}),delta:null}]:[],...Bye({showUsage:!1,durationMs:null,scores:(t??[]).map(q=>({scorerId:q.scorerId,value:q.score,label:o?a.jsx(qCs,{scorerId:q.scorerId,featured:l===q.id,onClick:()=>o(q.id)}):void 0}))})],Q=a.jsx(Tt.Content,{children:a.jsxs("div",{className:nee,children:[a.jsx(wAe,{metrics:F}),a.jsx(Kg,{title:"Input",framed:!0,actions:a.jsx(ii,{content:v}),children:a.jsx(nN,{value:e.input})}),e.groundTruth!=null&&a.jsx(Kg,{title:"Ground Truth",framed:!0,actions:a.jsx(ii,{content:yue(e.groundTruth)}),children:a.jsx(nN,{value:e.groundTruth})}),L?a.jsx(Kg,{title:"Error",tone:"negative",framed:!0,actions:a.jsx(ii,{content:L}),children:a.jsx(Y,{tone:"muted",className:"p-3 break-words",children:L})}):a.jsx(Kg,{title:"Output",framed:!0,actions:a.jsx(ii,{content:y}),children:a.jsx(nN,{value:x??e.output})}),e.toolMockReport&&a.jsx(FCs,{report:e.toolMockReport})]})});return a.jsxs(a.Fragment,{children:[a.jsxs(Tt.Header,{children:[a.jsx(Tt.Heading,{children:"Experiment result"}),a.jsxs(Tt.HeaderActions,{children:[b&&a.jsx(ue,{size:"sm",variant:"primary",onClick:()=>c(e.id),icon:a.jsx(Nht,{}),children:"Request review"}),p&&e.status==="needs-review"&&a.jsx(ue,{size:"sm",variant:"primary",onClick:p,icon:a.jsx(vP,{}),children:"Mark as reviewed"}),h&&a.jsx(ue,{size:"sm",variant:"ghost",render:a.jsx(C,{href:h}),tooltip:"See experiment","aria-label":"See experiment",children:a.jsx(lL,{})}),e.traceId&&i&&a.jsx(ue,{size:"sm",variant:"ghost",onClick:i,tooltip:"See trace","aria-label":"See trace",children:a.jsx(bx,{})}),a.jsx(Tt.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Go to previous result",nextLabel:"Go to next result"}),a.jsx(Tt.CloseButton,{icon:"x",onClick:s})]})]}),T?a.jsxs(Wc,{defaultTab:"details",className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[a.jsx(Tt.Header,{children:a.jsxs(Hc,{variant:"pill-ghost",size:"sm",children:[a.jsx(si,{value:"details",children:"Details"}),a.jsxs(si,{value:"feedback",children:["Feedback",_?.pagination?.total!=null&&a.jsxs(a.Fragment,{children:[" (",_.pagination.total,")"]})]})]})}),a.jsx(No,{value:"details",flush:!0,children:Q}),a.jsx(No,{value:"feedback",flush:!0,children:a.jsx(Tt.Content,{children:m({traceId:T})})})]}):Q]})}function qCs({scorerId:e,featured:t,onClick:n}){return a.jsx("button",{type:"button","aria-pressed":t,onClick:n,className:Z("min-w-0 cursor-pointer truncate hover:text-foreground hover:underline",t&&"text-foreground"),children:e})}function QCs({tags:e,selectedResults:t,onTagsChange:n,tagVocabulary:r,isUpdatingTags:s}){return a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-1.5",children:[e.map(i=>a.jsxs(YJ,{value:i,className:n?"gap-1 pr-1":void 0,children:[i,n&&a.jsx("button",{type:"button","aria-label":`Remove tag ${i}`,disabled:s,onClick:()=>n(e.filter(o=>o!==i)),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:a.jsx(zn,{className:"size-3"})})]},i)),n&&a.jsx(dqt,{selectedResults:t,vocabulary:r,onAddTag:i=>n([...e,i]),disabled:s,variant:"ghost"})]})}function yue(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function ZCs(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function WCs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s}){return a.jsx(Tt,{open:!!e,onClose:r,title:e?`Score ${e.scorerId}`:"Score",depth:2,children:e&&a.jsx(HCs,{score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s})})}function HCs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s}){const i=ZCs(e),o=i?"N/A — code-based scorer":"N/A — step not configured";return a.jsxs(a.Fragment,{children:[a.jsxs(Tt.Header,{children:[a.jsx(Tt.CloseButton,{onClick:r,tooltip:"Close score panel"}),a.jsxs(Tt.Heading,{children:["Score",a.jsx(Tt.CopyId,{id:e.scorerId})]}),a.jsxs(Tt.HeaderActions,{children:[s&&e.traceId&&a.jsx(ue,{size:"sm",variant:"ghost",onClick:s,tooltip:"See trace","aria-label":"See trace",children:a.jsx(bx,{})}),(n||t)&&a.jsx(Tt.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Go to previous score",nextLabel:"Go to next score"})]})]}),a.jsx(Tt.Content,{children:a.jsxs("div",{className:"grid gap-3",children:[a.jsx(Tt.CodeSection,{title:`Score: ${e.score}`,icon:a.jsx(tg,{}),codeStr:e.reason||o,simplified:!0}),!i&&a.jsxs(a.Fragment,{children:[a.jsx(Tt.CodeSection,{title:"Preprocess Prompt",icon:a.jsx(Jp,{}),codeStr:e.preprocessPrompt||o,simplified:!0}),a.jsx(Tt.CodeSection,{title:"Analyze Prompt",icon:a.jsx(Jp,{}),codeStr:e.analyzePrompt||o,simplified:!0}),a.jsx(Tt.CodeSection,{title:"Generate Score Prompt",icon:a.jsx(Jp,{}),codeStr:e.generateScorePrompt||o,simplified:!0}),a.jsx(Tt.CodeSection,{title:"Generate Reason Prompt",icon:a.jsx(Jp,{}),codeStr:e.generateReasonPrompt||o,simplified:!0})]})]})})]})}function fqt(e,t){const[n,r]=g.useState(null),[s,i]=g.useState(void 0),[o,l]=g.useState(null),[c,u]=g.useState(t);t!==c&&(u(t),r(null),i(void 0),l(null));const d=e?.find(f=>f.id===o)??null;return{featuredTraceId:n,setFeaturedTraceId:r,featuredSpanId:s,setFeaturedSpanId:i,featuredScoreId:o,setFeaturedScoreId:l,featuredScore:d}}function hqt({result:e,scores:t,state:n,withQueryTrace:r,withFeedback:s,...i}){const o=fqt(t,e?.id),{navigate:l}=Tn(),{featuredTraceId:c,setFeaturedTraceId:u,featuredSpanId:d,setFeaturedSpanId:f,featuredScoreId:h,setFeaturedScoreId:p,featuredScore:m}=n??o,v=I=>{p(A=>I===A?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(A=>A.id===h);if(I>=0&&I<t.length-1)return()=>p(t[I+1].id)},b=()=>{if(!h||!t)return;const I=t.findIndex(A=>A.id===h);if(I>0)return()=>p(t[I-1].id)},{data:S,isLoading:k}=WOs({traceId:c,queryOptions:{enabled:!!c}}),j=S?.spans,C=j?.find(I=>!I.parentSpanId),{data:T}=UJ({traceId:c??void 0,queryOptions:{enabled:s&&!!c}}),{data:_}=TNe({traceId:c??void 0,spanId:d,queryOptions:{enabled:s&&!!c&&!!d}}),{data:N}=Ike({traceId:c??void 0,spanId:C?.spanId,page:0,queryOptions:{enabled:!!c&&!!C?.spanId}});return a.jsxs(a.Fragment,{children:[a.jsx(UCs,{...i,result:e,scores:t,onScoreClick:v,featuredScoreId:h,onShowTrace:e?.traceId?()=>y(e.traceId):void 0,feedbackTabSlot:s?({traceId:I})=>a.jsx(OW,{traceId:I},I):void 0}),a.jsx(WCs,{score:m??void 0,onNext:x(),onPrevious:b(),onClose:()=>p(null),onShowTrace:m?()=>y(m.traceId):void 0}),a.jsx(nAe,{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,A)=>l(UCe(I,A)),feedbackTabBadge:s?T?.pagination?.total??void 0:void 0,feedbackTabSlot:s?({traceId:I})=>a.jsx(OW,{traceId:I}):void 0,scoresTabBadge:N?.pagination?.total??void 0,scoresTabSlot:({traceId:I,rootSpanId:A})=>A?a.jsx(FIe,{traceId:I,spanId:A,onScoreSelect:P=>{t?.some(L=>L.id===P)&&(u(null),f(void 0),p(P))}}):null,spanFeedbackTabBadge:s?_?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:s?({traceId:I,spanId:A})=>I&&A?a.jsx(WUt,{traceId:I,spanId:A},`${I}:${A}`):null:void 0})]})}function pqt(e,t){const{data:n}=zx({datasetId:e,queryOptions:{enabled:!!e}});return g.useMemo(()=>[...new Set([...n?.tags??[],...t.flatMap(r=>r.tags??[])])].sort(),[n?.tags,t])}function Xtt({withQueryTrace:e,withFeedback:t,variant:n}){const{currentItemId:r,experimentId:s,datasetId:i,experimentStatus:o,results:l,isLoadingResults:c,hasNextPage:u,close:d,goToPreviousItem:f,goToNextItem:h}=gAe(),p=g.useMemo(()=>r?l.find(C=>C.itemId===r):void 0,[l,r]),{data:m}=JL({experimentId:s,experimentStatus:o,queryOptions:{enabled:!!s}}),{updateExperimentResult:v}=pl(),y=g.useCallback(async C=>{try{await v.mutateAsync({datasetId:i,experimentId:s,resultId:C,status:"needs-review"}),Ye("Result flagged for review")}catch{Ye.error("Failed to flag result for review")}},[i,s,v]),x=pqt(i,l),b=g.useCallback(async(C,T)=>{try{await v.mutateAsync({datasetId:i,experimentId:s,resultId:C,tags:T})}catch{Ye.error("Failed to update tags")}},[i,s,v]),S=g.useCallback(async C=>{try{await v.mutateAsync({datasetId:i,experimentId:s,resultId:C,status:"complete"}),Ye("Result marked as reviewed")}catch{Ye.error("Failed to complete result")}},[i,s,v]),k=p?m?.[p.itemId]:void 0,j=fqt(k,p?.id);return a.jsx(hqt,{variant:n,result:p,itemId:r,fallback:c||u?a.jsx(Tt.LoadingData,{}):a.jsxs(Tt.NoData,{children:['No loaded result for item "',r,'".']}),scores:k,state:j,withQueryTrace:e,withFeedback:t,onPrevious:f,onNext:h,onClose:d,onComplete:p?()=>S(p.id):void 0,onFlagForReview:p?()=>{y(p.id)}:void 0,onTagsChange:p?C=>{b(p.id,C)}:void 0,tagVocabulary:x,isUpdatingTags:v.isPending})}const ree=g.createContext(null);function GCs({children:e}){const[t,n]=g.useState(null),[r,s]=g.useState([]),[i,o]=g.useState(!0),c=!Ck()&&i,u=g.useRef(null),d=g.useRef(0),f=g.useCallback((y,x)=>{const b=d.current+1;return d.current=b,s(S=>[...S.filter(k=>k.owner!==y),{owner:y,priority:x,order:b}]),()=>{s(S=>S.filter(k=>!(k.owner===y&&k.order===b)))}},[]),h=g.useMemo(()=>{let y;for(const x of r)(!y||x.priority>y.priority||x.priority===y.priority&&x.order>y.order)&&(y=x);return y?.owner??null},[r]),p=g.useCallback(()=>u.current?.toggle(),[]),m=g.useCallback(y=>o(y<=0),[]),v=g.useMemo(()=>({el:t,setEl:n,activeOwner:h,register:f,panelHandle:u,isCollapsed:c,onPanelResize:m,toggle:p}),[h,t,c,m,f,p]);return a.jsx(ree.Provider,{value:v,children:e})}function Jtt(e){const t=g.use(ree);return a.jsx("div",{ref:t?.setEl??void 0,...e})}function mqt({owner:e,priority:t=0,children:n}){const r=g.use(ree),s=r?.register;return g.useEffect(()=>{if(s)return s(e,t)},[e,t,s]),!r?.el||r.activeOwner!==e?null:So.createPortal(n,r.el)}const ent=()=>{},KCs={current:null};function Mz(){const e=g.use(ree);if(!e)return{hasPanel:!1,isCollapsed:!0,onPanelResize:ent,panelHandle:KCs,toggle:ent};const{activeOwner:t,isCollapsed:n,onPanelResize:r,panelHandle:s,toggle:i}=e;return{hasPanel:t!==null,isCollapsed:n,onPanelResize:r,panelHandle:s,toggle:i}}function YCs(e){const{currentItemId:t,close:n}=gAe(),{hasPanel:r,isCollapsed:s,panelHandle:i}=Mz(),o=Ck(),l=g.useRef(!1);g.useEffect(()=>{if(!t||!r)return;const u=requestAnimationFrame(()=>i.current?.expand());return()=>cancelAnimationFrame(u)},[t,r,i]);const c=g.useEffectEvent(()=>n());return g.useEffect(()=>{if(!r){l.current=!1;return}if(!s){l.current=!0;return}if(!(!l.current||!t)){if(l.current=!1,!document.querySelector('[data-separator="active"]')){c();return}return window.addEventListener("pointerup",c,{once:!0}),()=>window.removeEventListener("pointerup",c)}},[r,s,t]),o?a.jsx(Xtt,{...e}):t?a.jsx(mqt,{owner:"experiment-item",children:a.jsx(Xtt,{...e,variant:"inline"})}):null}function gqt({children:e,className:t}){return a.jsx("div",{className:"@container",children:a.jsx("div",{className:Z("grid gap-4 *:min-w-0! @xl:grid-cols-2 @3xl:has-[>:nth-child(5)]:grid-cols-3 @4xl:grid-cols-[repeat(auto-fit,minmax(12rem,1fr))] @6xl:has-[>:nth-child(5)]:grid-cols-[repeat(auto-fit,minmax(12rem,1fr))]!",t),children:e})})}const vqt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],ZA="rootEntityType",WA={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"},see=Object.keys(WA),SAe="mastra:metrics:saved-filters";function XCs(e){const t=n_s(e);try{localStorage.setItem(SAe,t.toString())}catch{}}function JCs(){try{localStorage.removeItem(SAe)}catch{}}function yqt(){try{const e=localStorage.getItem(SAe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function e_s(e){if(e.has(ZA))return!0;for(const t of see)if(e.has(WA[t]))return!0;return!1}function xqt({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const i=[{id:"rootEntityType",label:"Primitive type",kind:"pick-multi",searchable:!1,options:vqt.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 t_s(e){const t=[],n=new Map([[ZA,"rootEntityType"]]);for(const s of see)n.set(WA[s],s);const r=new Set;for(const[s]of e.entries()){const i=n.get(s);if(!i||r.has(i))continue;if(r.add(i),i==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:i,value:l.filter(Boolean)});continue}if(i==="rootEntityType"||i==="entityName"||i==="serviceName"||i==="environment"||i==="provider"||i==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:i,value:l});continue}}const o=e.get(s);o!==null&&t.push({fieldId:i,value:o})}return t}function n_s(e){const t=new URLSearchParams,n=e.getAll(ZA);for(const r of n)t.append(ZA,r);for(const r of see){const s=WA[r],i=e.getAll(s);for(const o of i)t.append(s,o)}return t}function r_s(e,t){e.delete(ZA);for(const n of see)e.delete(WA[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?ZA:WA[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 s_s="Any";function tnt(e){const t=e.trim();return t===""||t===s_s}const i_s=new Set(vqt.map(e=>e.entityType));function nnt(e){const t=e.trim();return i_s.has(t)?t:void 0}function o_s(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(i=>typeof i=="string").map(i=>i.trim()).filter(i=>!tnt(i));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const i=s[0],o=i!==void 0?nnt(i):void 0;o&&(t.rootEntityType=o)}else t[r]=s[0]}else if(typeof n.value=="string"){if(tnt(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const i=nnt(s);i&&(t.rootEntityType=i)}else t[r]=s}}return t}const bqt=[{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"}],a_s=new Set(bqt.map(e=>e.value));function l_s(e){return typeof e=="string"&&(a_s.has(e)||e==="custom")}const wqt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",comparisonLabel:"vs previous 24h",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}"});function Gk(){return g.useContext(wqt)}function c_s(e,t){return e!=="custom"?bqt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${MI(t.from)} – ${MI(t.to)}`:MI(t.from)??"":"Custom range"}const rnt=3600*1e3;function u_s(e,t){if(e!=="custom")return`vs previous ${e}`;const n=t?.to?.getTime()??Date.now(),r=t?.from?.getTime()??n-24*rnt,s=Math.round((n-r)/rnt);return`vs previous ${s>24&&s%24===0?`${s/24}d`:`${s}h`}`}function d_s({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:i,onCustomRangeChange:o}){const l=g.useMemo(()=>JSON.stringify(n),[n]),c=g.useMemo(()=>n,[l]),u=g.useMemo(()=>o_s(c),[c]),d=g.useMemo(()=>JSON.stringify(u),[u]),f=c_s(t,i),h=u_s(t,i),p=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:i,setCustomRange:o??(()=>{}),dateRangeLabel:f,comparisonLabel:h,filterTokens:c,setFilterTokens:s,dimensionalFilter:u,dimensionalFilterKey:d}),[t,r,i,o,f,h,c,s,u,d]);return a.jsx(wqt.Provider,{value:p,children:e})}const f_s=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function h_s(e){switch(e){case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return"last-24h"}}function p_s(e){switch(e){case"last-3d":return"3d";case"last-7d":return"7d";case"last-14d":return"14d";case"last-30d":return"30d";case"custom":return"custom";default:return"24h"}}function m_s(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=Gk(),s=g.useRef(e);s.current=e;const i=g.useRef(n);return i.current=n,a.jsx(KY,{preset:h_s(e),onPresetChange:o=>{const l=p_s(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:f_s})}function iee({onClick:e}){return a.jsx(ue,{onClick:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:a.jsx(Fa,{})})}function Sqt({onClick:e}){return a.jsx(ue,{onClick:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:a.jsx(ZEn,{})})}function g_s({children:e,reveal:t="always",className:n}){return a.jsx("div",{className:Z("flex shrink-0 items-center gap-1 self-center",t==="hover"&&"opacity-0 transition-opacity duration-150 group-hover/metrics-card:opacity-100 focus-within:opacity-100",n),children:e})}function v_s({children:e,className:t}){return a.jsx("div",{className:Z("overflow-x-auto overflow-y-hidden [&_tbody>tr:last-child]:border-b-0",t),children:e})}function kqt({children:e,className:t}){return a.jsx(Y,{tone:"faint",className:Z("mt-0.5",t),children:e})}function y_s({message:e="Failed to load data",className:t}){return a.jsx("div",{className:Z("flex flex-col items-center justify-center gap-3",t),children:a.jsx(Y,{variant:"caption",className:"text-destructive-foreground",children:e})})}function x_s({className:e}){return a.jsx("div",{className:Z("flex items-center justify-center",e),children:a.jsx(_n,{size:"md",variant:"pulse",className:"text-placeholder"})})}function b_s({message:e="No data yet",className:t}){return a.jsx("div",{className:Z("flex h-full items-center justify-center",t),children:a.jsx(Y,{tone:"faint",children:e})})}function snt({children:e,className:t}){return a.jsx(hl,{className:Z("group/metrics-card grid min-h-72 min-w-80 flex-1 grid-rows-[auto_1fr] gap-4 px-4 py-3 2xl:min-w-120 md:min-w-88 lg:min-w-sm xl:min-w-104",t),children:e})}function w_s({value:e,label:t,isLoading:n=!1,className:r}){return n?a.jsxs("div",{className:Z("order-last flex shrink-0 flex-col items-end",r),children:[a.jsx(XV,{line:"text-body",className:"h-4 w-14"}),t&&a.jsx(XV,{line:"text-body mt-0.5",className:"w-10"})]}):a.jsxs("div",{className:Z("order-last text-right",r),children:[a.jsx(Y,{tone:"muted",className:"tabular-nums",children:e}),t&&a.jsx(Y,{tone:"faint",className:"mt-0.5",children:t})]})}function S_s({value:e,onValueChange:t,children:n}){return a.jsx(Wc,{value:e,onValueChange:t,defaultTab:e,children:a.jsx(Hc,{variant:"pill-ghost",size:"sm",children:n})})}function k_s({className:e,...t}){return a.jsx(si,{...t,className:Z("h-6 px-2.5 text-column",e)})}function Oqt({children:e,className:t,as:n="h2"}){return a.jsx(n,{className:Z("text-body text-foreground",t),children:e})}function O_s(e){if("children"in e)return a.jsx("div",{className:e.className,children:e.children});const{title:t,description:n,titleAs:r}=e;return a.jsxs("div",{className:e.className,children:[a.jsx(Oqt,{as:r,children:t}),n&&a.jsx(kqt,{children:n})]})}function j_s({children:e,className:t}){return a.jsx("div",{className:Z("flex min-w-0 flex-wrap items-center justify-between gap-x-4 gap-y-2 [&>*:first-child]:min-w-0 [&>*:last-child:not(:first-child)]:ml-auto",t),children:e})}function C_s({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 yi=Object.assign(snt,{Root:snt,Kpi:Jh,TopBar:C_s,Toolbar:j_s,Tabs:S_s,Tab:k_s,Actions:g_s,TitleAndDescription:O_s,Title:Oqt,Description:kqt,Summary:w_s,Loading:x_s,Error:y_s,Content:v_s,NoData:b_s});function lT({isEmpty:e=!1,emptyMessage:t="No data in this range.",children:n}){return a.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[n,e&&a.jsx(yi.NoData,{message:t,className:"absolute inset-0"})]})}function ih({title:e,description:t,summary:n,actions:r,toolbar:s,isUpdating:i=!1,className:o,children:l}){const c=Z("transition-opacity duration-200",i&&"opacity-50");return a.jsxs(yi,{className:Z("min-h-0! min-w-0!",o),children:[a.jsxs(yi.TopBar,{children:[a.jsx(yi.TitleAndDescription,{title:e,description:t}),r&&a.jsx(yi.Actions,{reveal:"hover",children:r}),n&&a.jsx("div",{className:Z("order-last flex w-24 shrink-0 justify-end",c),children:n})]}),a.jsxs(yi.Content,{className:"flex flex-col gap-4 overflow-visible",children:[s,a.jsx("div",{className:Z("relative flex h-60 min-h-0 min-w-0 flex-col",c),children:l})]})]})}function cT(){return a.jsx(yi.Error,{message:"Couldn't load this data. Try again in a moment.",className:"h-full"})}function B1({label:e,icon:t,isError:n=!1,...r}){return a.jsxs(Jh,{children:[a.jsx(Jh.Label,{icon:a.jsx(t,{}),children:e}),n?a.jsx(__s,{}):a.jsx(T_s,{...r})]})}function __s(){return a.jsxs(a.Fragment,{children:[a.jsx(Jh.ValueRow,{className:"mt-1",children:a.jsx(Jh.Value,{children:"—"})}),a.jsx(Jh.Footer,{detail:a.jsx("span",{className:"text-destructive-foreground",children:"Couldn't load"})})]})}function T_s({value:e,change:t,lowerIsBetter:n,detail:r,previous:s,comparison:i,isLoading:o=!1,isUpdating:l=!1}){const c=Z("transition-opacity duration-200",l&&"opacity-50");return a.jsxs(a.Fragment,{children:[a.jsxs(Jh.ValueRow,{className:Z("mt-1",c),isLoading:o,children:[a.jsx(Jh.Value,{children:e}),t!==void 0&&a.jsx(Jh.Change,{changePct:t,comparison:i,lowerIsBetter:n,prevValue:s})]}),a.jsx(Jh.Footer,{detail:r,prevValue:t===void 0?void 0:s,isLoading:o,className:c})]})}const E_s={2:"@3xl:grid-cols-2",3:"@3xl:grid-cols-2 @7xl:grid-cols-3"},I_s={1:"",2:"@3xl:col-span-2",full:"col-span-full"};function u1({children:e,columns:t=3,className:n}){return a.jsx("div",{className:Z("@container",n),children:a.jsx("div",{className:Z("grid gap-4",E_s[t]),children:e})})}function N_s({children:e,span:t=1,className:n}){return a.jsx("div",{className:Z("min-w-0 *:w-full *:min-w-0!",I_s[t],n),children:e})}u1.Item=N_s;const qye=1440*60*1e3,A_s={"24h":qye,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function P_s(e,t,n){if(e!=="custom"){const r=A_s[e]??qye;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-qye),end:t?.to??new Date(n)}}function $_s({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(()=>P_s(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 R_s(e){const t=Ge(),{filters:n,filterKey:r,queryOptions:s}=e;return _t({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 jqt(e){const t=Ge(),{filters:n,filterKey:r,queryOptions:s}=e;return _t({queryKey:["metrics","agent-runs-kpi",r],queryFn:()=>t.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:n,comparePeriod:"previous_period"}),...s})}function M_s(e){const t=Ge(),{filters:n,filterKey:r,queryOptions:s}=e;return _t({queryKey:["metrics","model-cost-kpi",r],queryFn:async()=>{const i=await t.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:n,comparePeriod:"previous_period"});return{cost:i.estimatedCost??null,costUnit:i.costUnit??null,previousCost:i.previousEstimatedCost??null,costChangePercent:i.costChangePercent??null}},...s})}new Set(Intl.supportedValuesOf("currency"));function D_s(e){const t=Ge(),{filters:n,filterKey:r,queryOptions:s}=e;return _t({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=>FJ(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 L_s(e){const t=Ge(),{filters:n,filterKey:r,queryOptions:s}=e;return _t({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 xue(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=FJ(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 z_s(e){const t=Ge(),{filters:n,filterKey:r,queryOptions:s}=e;return _t({queryKey:["metrics","trace-volume",r],queryFn:async()=>{const[i,o,l]=await Promise.all([xue(t,"mastra_agent_duration_ms",n),xue(t,"mastra_workflow_duration_ms",n),xue(t,"mastra_tool_duration_ms",n)]);return{agentData:i,workflowData:o,toolData:l}},...s})}function mf(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=Gk();return $_s({datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r})}function fv(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}K`:e>=1e3?`${(e/1e3).toFixed(2)}K`:String(Math.round(e))}function int(e){return e>=1e4?`${(e/1e3).toFixed(1)}s`:e>=1e3?`${(e/1e3).toFixed(2)}s`:`${Math.round(e)}ms`}function Qye(e){const t=e*100;return t===0?"0%":t<.1?"<0.1%":`${t<10?t.toFixed(2):t.toFixed(1)}%`}function eC(e){return e>0&&e<.01?"<$0.01":`$${e.toFixed(2)}`}function F_s(e){return e>=1e6?`${+(e/1e6).toFixed(1)}M`:e>=1e3?`${+(e/1e3).toFixed(1)}K`:String(Math.round(e))}function B_s(e){return e>=1e3?`${+(e/1e3).toFixed(1)}s`:`${Math.round(e)}ms`}const oee={placeholderData:fx},kAe=e=>e==null?"—":fv(e),U_s=e=>e==null?"—":eC(e),aee=e=>e==null||!Number.isFinite(e)?void 0:e,OAe=e=>e==null?void 0:fv(e),V_s=e=>e==null?void 0:eC(e);function q_s(){return a.jsxs(gqt,{children:[a.jsx(Q_s,{}),a.jsx(Z_s,{}),a.jsx(W_s,{}),a.jsx(H_s,{})]})}function Q_s(){const{comparisonLabel:e}=Gk(),{data:t,isLoading:n,isPlaceholderData:r,isError:s}=jqt({...mf(),queryOptions:oee});return a.jsx(B1,{label:"Agent runs",icon:K0e,value:kAe(t?.value),change:aee(t?.changePercent),detail:"in this range",previous:OAe(t?.previousValue),comparison:e,isLoading:n,isUpdating:r,isError:s})}function Z_s(){const{comparisonLabel:e}=Gk(),{data:t,isLoading:n,isPlaceholderData:r,isError:s}=M_s({...mf(),queryOptions:oee});return a.jsx(B1,{label:"Model cost",icon:HH,value:U_s(t?.cost),change:aee(t?.costChangePercent),lowerIsBetter:!0,detail:"estimated",previous:V_s(t?.previousCost),comparison:e,isLoading:n,isUpdating:r,isError:s})}function W_s(){const{comparisonLabel:e}=Gk(),{data:t,isLoading:n,isPlaceholderData:r,isError:s}=L_s({...mf(),queryOptions:oee});return a.jsx(B1,{label:"Tokens",icon:Z0,value:kAe(t?.value),change:aee(t?.changePercent),detail:"input and output",previous:OAe(t?.previousValue),comparison:e,isLoading:n,isUpdating:r,isError:s})}function H_s(){const{comparisonLabel:e}=Gk(),{data:t,isLoading:n,isPlaceholderData:r,isError:s}=R_s({...mf(),queryOptions:oee});return a.jsx(B1,{label:"Threads",icon:cwe,value:kAe(t?.value),change:aee(t?.changePercent),detail:"with agent runs",previous:OAe(t?.previousValue),comparison:e,isLoading:n,isUpdating:r,isError:s})}const Cqt=36e5,G_s=24*Cqt,K_s=(e,t)=>t.getTime()-e.getTime()>G_s+Cqt,V7=e=>e.toLocaleDateString("en-US",{month:"short",day:"numeric"}),ont=e=>e.toLocaleTimeString("en-US",{hour:"numeric"});function Y_s(e,t,n){const r=new Date(e);if(t>=24)return{ts:e,label:V7(r),edgeLabel:V7(r),time:r.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})};const s=r.toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric"}),i=`${V7(r)}, ${ont(r)}`;return n?{ts:e,label:r.getHours()===0?V7(r):i,edgeLabel:i,time:s}:{ts:e,label:ont(r),edgeLabel:i,time:s}}const _qt=36e5,q7=24*_qt,Q7=_qt;function uT(e,t){const n=t.getTime()-e.getTime();return n<=q7+Q7?{interval:"1h",stepHours:1}:n<=3*q7+Q7?{interval:"1h",stepHours:3}:n<=7*q7+Q7?{interval:"1h",stepHours:6}:n<=14*q7+Q7?{interval:"1h",stepHours:12}:{interval:"1d",stepHours:24}}const jAe=e=>e==="1h"?1:24;function CAe(e,t){const n=new Date(e);if(t>=24)return new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime();const r=Math.floor(n.getHours()/t)*t;return new Date(n.getFullYear(),n.getMonth(),n.getDate(),r).getTime()}function Tqt(e,t){const n=new Date(e);return t>=24?new Date(n.getFullYear(),n.getMonth(),n.getDate()+1).getTime():CAe(new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()+t).getTime(),t)}function _Ae(e,t,n){const r=K_s(e,t),s=[];for(let i=CAe(e.getTime(),n);i<=t.getTime();i=Tqt(i,n))s.push(Y_s(i,n,r));return s}function TAe(e,t){const n=new Map(e.map((r,s)=>[r.ts,s]));return r=>n.get(CAe(new Date(r.timestamp).getTime(),t))}function lee(e,t){return{from:new Date(e),to:new Date(Tqt(e,t))}}const bue={input:"mastra_model_total_input_tokens",output:"mastra_model_total_output_tokens",cacheRead:"mastra_model_input_cache_read_tokens"},X_s="mastra_agent_duration_ms";function EAe(){const e=Ge(),{filters:t,filterKey:n,timestamp:r}=mf(),{interval:s,stepHours:i}=uT(r.start,r.end);return _t({queryKey:["metrics","activity",n,s],placeholderData:fx,queryFn:async()=>{const o=v=>e.getMetricTimeSeries({name:[v],interval:s,aggregation:"sum",filters:t}),[l,c,u,d]=await Promise.all([o(bue.input),o(bue.output),o(bue.cacheRead),e.getMetricTimeSeries({name:[X_s],interval:s,aggregation:"count",groupBy:["status"],filters:t})]),f=_Ae(r.start,r.end,i).map(v=>({...v,input:0,cacheRead:0,output:0,cost:0,completed:0,failed:0,failureRate:0})),h=TAe(f,i),p=v=>{const y=h(v);return y===void 0?void 0:f[y]},m=(v,y)=>{for(const x of v){const b=p(x);b&&(b[y]+=x.value,y!=="cacheRead"&&(b.cost+=x.estimatedCost??0))}};for(const v of l.series)m(v.points,"input");for(const v of c.series)m(v.points,"output");for(const v of u.series)m(v.points,"cacheRead");for(const v of d.series){const y=/error|fail/i.test(v.name)?"failed":"completed";for(const x of v.points){const b=p(x);b&&(b[y]+=x.value)}}for(const v of f){v.input=Math.max(v.input-v.cacheRead,0);const y=v.completed+v.failed;v.failureRate=y>0?v.failed/y:0}return f}})}const IAe={xKey:"label",timestampKey:"ts",tooltipLabelKey:"time"},NAe={...IAe,xKey:"edgeLabel"},mu={green:"var(--chart-share-1)",sky:"var(--chart-share-2)",violet:"var(--chart-share-3)",teal:"var(--chart-share-4)",indigo:"var(--chart-share-5)",error:"var(--chart-red)",neutral:"var(--muted-foreground)"};function cee({data:e,series:t,className:n}){return a.jsx("div",{className:Z("flex flex-wrap items-center gap-x-4 gap-y-1",n),children:t.map(r=>{const s=e?r.aggregate?.(e):void 0;return a.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[r.dashed?a.jsx("span",{className:"h-0 w-3 shrink-0 border-t-2 border-dashed",style:{borderColor:r.color}}):a.jsx("div",{className:"size-2 shrink-0 rounded-[2px]",style:{backgroundColor:r.color}}),a.jsx(Y,{as:"span",variant:"body-sm",tone:"muted",className:"max-w-48 truncate",children:r.label}),s&&a.jsxs(Y,{as:"span",variant:"body-sm",tone:"muted",className:"-ml-1 tabular-nums",children:[s.value,s.suffix&&a.jsxs(Y,{as:"span",variant:"body-sm",tone:"faint",children:[" ",s.suffix]})]})]},r.dataKey)})})}function Eqt({active:e,payload:t,label:n,suffix:r,formatValue:s=c=>c.toLocaleString("en-US"),showTotal:i=!1,labelKey:o,formatByKey:l}){if(!e||!t?.length)return null;const c=p=>typeof p=="number"&&Number.isFinite(p),u=t.reduce((p,m)=>p+(c(m.value)?m.value:0),0),d=o?String(t[0]?.payload?.[o]??n??""):n,f=p=>l?.[String(p.dataKey)]??s,h=p=>c(p.value)?f(p)(p.value):typeof p.value=="number"||p.value==null?"—":p.value;return a.jsxs(lCe,{children:[a.jsx(Y,{variant:"column",tone:"ink",className:"mb-1",children:d}),a.jsxs("div",{className:"grid grid-cols-[auto_1fr_auto] items-center gap-x-2 gap-y-1",children:[t.map(p=>a.jsxs("div",{className:"contents",children:[a.jsx("span",{className:"size-2 rounded-[2px]",style:{backgroundColor:p.color}}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"max-w-40 truncate",children:p.name}),a.jsxs("span",{className:"text-right font-mono text-foreground tabular-nums",children:[h(p),c(p.value)&&r]})]},p.name)),i&&a.jsxs("div",{className:"col-span-3 grid grid-cols-subgrid items-center border-t border-border pt-1",children:[a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"col-span-2",children:"Total"}),a.jsxs("span",{className:"text-right font-mono text-foreground tabular-nums",children:[s(u),r]})]})]})]})}const uee={top:8,right:0,bottom:0,left:0},AAe=22,PAe=11;function J_s(e,t){let n=t;const r=()=>(n=(n*9301+49297)%233280,n/233280);let s=.45;return Array.from({length:e},()=>(s=Math.min(.85,Math.max(.25,s+(r()-.5)*.3)),s))}function Iqt({kind:e,height:t=210,className:n}){const r=`ghost${g.useId().replace(/:/g,"")}`,s=ppt(),i=J_s(e==="bar"?24:16,e==="bar"?7:11),{ghost:o,mask:l,peak:c}=e==="bar"?eTs(i):tTs(i),u=a.jsxs(a.Fragment,{children:[a.jsxs("defs",{children:[a.jsxs("linearGradient",{id:`${r}-band`,x1:"0",y1:"0",x2:"1",y2:"0",children:[a.jsx("stop",{offset:"0",stopColor:"var(--foreground)",stopOpacity:0}),a.jsx("stop",{offset:"0.5",stopColor:"var(--foreground)",stopOpacity:c}),a.jsx("stop",{offset:"1",stopColor:"var(--foreground)",stopOpacity:0})]}),a.jsx("mask",{id:`${r}-mask`,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"100",height:"100",children:l})]}),o,a.jsx("g",{mask:`url(#${r}-mask)`,children:a.jsx("rect",{width:40,height:100,fill:`url(#${r}-band)`,className:"animate-[chart-ghost-sweep_2s_infinite]",style:{animationDelay:s}})})]}),d=a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"min-h-0 flex-1",style:{paddingTop:uee.top},children:a.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none",className:"block size-full","aria-hidden":!0,children:u})}),a.jsx("div",{style:{height:AAe}})]});return t==="fill"?a.jsx("div",{role:"status","aria-label":"Loading chart",className:Z("relative min-h-45 w-full flex-1",n),children:a.jsx("div",{className:"absolute inset-0 flex flex-col",children:d})}):a.jsx("div",{role:"status","aria-label":"Loading chart",className:Z("flex w-full flex-col",n),style:{height:t},children:d})}function eTs(e){const t=100/e.length,n=e.map((r,s)=>a.jsx("rect",{x:s*t+t*.15,width:t*.7,y:100-r*100,height:r*100,rx:.4},s));return{ghost:a.jsx("g",{fill:"var(--foreground)",fillOpacity:.07,children:n}),mask:a.jsx("g",{fill:"white",children:n}),peak:.09}}function tTs(e){const t=100/(e.length-1),n=e.map((i,o)=>[o*t,100-i*100]),r=n.map(([i,o],l)=>{const c=n[l-1];if(!c)return`M${i},${o}`;const[u,d]=c,f=(u+i)/2;return`C${f},${d} ${f},${o} ${i},${o}`}).join(" "),s=`${r} L100,100 L0,100 Z`;return{ghost:a.jsxs(a.Fragment,{children:[a.jsx("path",{d:s,fill:"var(--foreground)",fillOpacity:.025}),a.jsx("path",{d:r,fill:"none",stroke:"var(--foreground)",strokeOpacity:.12,strokeWidth:1.75,vectorEffect:"non-scaling-stroke"})]}),mask:a.jsxs(a.Fragment,{children:[a.jsx("path",{d:s,fill:"white",fillOpacity:.2}),a.jsx("path",{d:r,fill:"none",stroke:"white",strokeWidth:1.75,vectorEffect:"non-scaling-stroke"})]}),peak:.18}}const Nqt={vertical:!1,stroke:"var(--border)",strokeDasharray:"3 3",strokeOpacity:.5},nTs={stroke:"var(--border)",strokeDasharray:"3 3",strokeWidth:.8};function Aqt(){const e=g.useRef(null),[t,n]=g.useState({width:0,height:0});return g.useLayoutEffect(()=>{const s=e.current?.getBoundingClientRect();s&&n({width:s.width,height:s.height})},[]),{size:t,onResize:(s,i)=>n(o=>o.width===s&&o.height===i?o:{width:s,height:i}),ref:e}}function rTs(e){if(!e)return 3;const t=e-AAe-uee.top;return Math.min(5,Math.max(3,Math.round(t/48)+1))}const NU=6e4,ant=1440*NU,sTs=[5,10,15,30,60,120,180,240,360,720,1440,2880,10080],iTs=48,Pqt=e=>e.length*PAe*.58;function oTs(e,t,n,r="auto"){const s=t.length-1;if(s<0)return new Set;const i=new Set([0,s]);if(r==="edges"||t.length<3)return i;const o=Math.max(...t.map(p=>Pqt(p))),l=Math.floor(n/(o+iTs));if(l<3)return i;const c=e.every(aTs)?e:void 0,u=c?(c[1]??0)-(c[0]??0):0,d=c?((c[s]??0)-(c[0]??0)+u)/NU:0,f=c?sTs.find(p=>p*NU>=u&&p*NU%u===0&&d/p<=l):void 0;if(!c||!(u>0)||f===void 0){const p=Math.ceil(t.length/l),m=new Set;for(let v=0;v<=s;v+=p)m.add(v);return m.has(s)||(s%p<p/2&&m.delete(s-s%p),m.add(s)),m.size<3?i:m}const h=new Set;return c.forEach((p,m)=>{const v=new Date(p),y=new Date(v.getFullYear(),v.getMonth(),v.getDate()).getTime(),x=u>=ant||v.getHours()===0&&v.getMinutes()===0;(f<1440?v.getSeconds()===0&&(v.getHours()*60+v.getMinutes())%f===0:x&&Math.round(y/ant)%(f/1440)===0)&&h.add(m)}),h.size<3?i:h}function aTs(e){return typeof e=="number"&&Number.isFinite(e)}const $qt=3,Rqt=e=>e!==void 0&&Number.isFinite(e)&&e>0?e:0;function lTs(e,t,n,{gap:r=0,minSize:s=$qt}={}){const i=e.map(Rqt),o=i[t]??0;if(!(o>0)||!Number.isFinite(n.y)||!Number.isFinite(n.height))return;const l=n.height/o,c=i.slice(0,t).reduce((k,j)=>k+j,0),u=n.y+n.height+c*l,d=i.flatMap((k,j)=>k>0?[j]:[]),f=i.reduce((k,j)=>k+j,0)*l,h=r*(d.length-1),p=k=>m[k]??0,m=i.map(k=>k>0&&f>0?Math.max(k*l*(f-h)/f,0):0),v=d.filter(k=>p(k)<s),y=d.filter(k=>p(k)>=s),x=v.reduce((k,j)=>k+s-p(j),0),b=y.reduce((k,j)=>k+p(j)-s,0);for(const k of v)m[k]=s;for(const k of y)m[k]=b>=x?p(k)-(b>0?(p(k)-s)/b*x:0):s;let S=u;for(const k of d){if(S-=p(k),k===t)return{y:S,height:p(k)};S-=r}}function cTs(e,t,{minSize:n=$qt}={}){if(!(!(Rqt(e)>0)||!Number.isFinite(t.y)||!Number.isFinite(t.height)))return t.height>=n?t:{y:t.y+t.height-n,height:n}}function uTs({x:e=0,y:t=0,payload:n,picked:r,count:s,plotWidth:i}){if(!n||!i||!r.has(n.index))return null;const o=String(n.value),l=n.offset??0,c=l>0?e-l*(2*n.index+1):e-n.index*i/Math.max(s-1,1),u=Pqt(o)/2,d=Math.min(Math.max(e,c+u),c+i-u);return a.jsx("text",{x:d,y:t,dy:"0.71em",textAnchor:"middle",fontSize:PAe,fill:Ert,children:o})}const Zye=new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}),Mqt={fontSize:PAe,fill:Ert};function Dqt({data:e,xKey:t,timestampKey:n,xLabels:r,plotWidth:s}){const i=e.map(c=>String(c[t]??"")),o=e.map(c=>{const u=c[n];return typeof u=="number"?u:void 0}),l=oTs(o,i,s,r);return a.jsx(C6,{dataKey:t,height:AAe,tick:c=>a.jsx(uTs,{...c,picked:l,count:e.length,plotWidth:s}),tickLine:!1,axisLine:!1,tickMargin:6,interval:0})}const Lqt=44;function Wye({id:e=0,show:t,size:n,formatter:r,domain:s,right:i=!1}){return a.jsx(_6,{yAxisId:e,hide:!t,orientation:i?"right":"left",tick:Mqt,tickLine:!1,axisLine:!1,width:"auto",tickMargin:4,tickFormatter:r,domain:s,tickCount:rTs(n.height)})}function zqt({height:e,plotRef:t,onResize:n,clickable:r,children:s}){const i=Z("w-full [&_.recharts-surface]:overflow-visible [&_.recharts-surface]:outline-none","[&_*:focus:not(:focus-visible)]:outline-none",r&&"[&_.recharts-surface]:cursor-pointer");return e==="fill"?a.jsx("div",{className:"relative min-h-45 flex-1",children:a.jsx("div",{ref:t,className:Z("absolute inset-0",i),children:a.jsx(cA,{width:"100%",height:"100%",onResize:n,children:s})})}):a.jsx("div",{ref:t,className:i,style:{height:e},children:a.jsx(cA,{width:"100%",height:"100%",onResize:n,children:s})})}function Fqt(){return`chart${g.useId().replace(/:/g,"")}`}const dTs=2,fTs=2,hTs=.75,pTs=.55,mTs=3,gTs=.3;function vTs({fill:e,color:t,capped:n,keys:r,dataKey:s}){return function({x:o=0,width:l=0,index:c,payload:u,...d}){const f=r.map(S=>Number(u?.[S])||0),h=r.indexOf(s),p={y:d.y??0,height:Math.max(d.height??0,0)},m=r.length>1?lTs(f,h,p,{gap:fTs}):cTs(f[h]??0,p);if(!m)return a.jsx("g",{});const{y:v,height:y}=m,x=Math.min(dTs,Math.floor(y/3)),b={"data-bucket":c,style:{transition:"opacity 150ms ease-out"}};return n?a.jsxs("g",{...b,children:[a.jsx(UI,{x:o,y:v,width:l,height:y,radius:x,fill:t,fillOpacity:pTs}),a.jsx(UI,{x:o,y:v,width:l,height:Math.min(mTs,y),radius:x,fill:t})]}):a.jsx("g",{...b,children:a.jsx(UI,{x:o,y:v,width:l,height:y,radius:x,fill:e})})}}function yTs({scope:e,setter:t}){const[n,r]=g.useState();return g.useLayoutEffect(()=>{t.current=r},[t]),n===void 0?null:a.jsx("style",{children:`[data-chart-scope="${e}"] [data-bucket]:not([data-bucket="${n}"]){opacity:${gTs}}`})}function Bqt(e){const{data:t,series:n,overlay:r,height:s=210,showLegend:i=!0,isLoading:o=!1,className:l}=e,c=Fqt(),u=Z(s==="fill"&&"flex min-h-0 flex-1 flex-col",l),d=r?[...n,{...r,dashed:!0}]:n;return a.jsxs("div",{className:u,"data-chart-scope":c,children:[i&&a.jsx(cee,{data:o?void 0:t,series:d,className:"mb-4"}),o?a.jsx(Iqt,{kind:"bar",height:s}):a.jsx(xTs,{...e,id:c})]})}function xTs({data:e,series:t,height:n=210,yDomain:r,valueFormatter:s,axisFormatter:i,referenceLine:o,variant:l="gradient",showYAxis:c=!0,showTotal:u=t.length>1,xKey:d="time",timestampKey:f="tsMs",xLabels:h="auto",tooltipLabelKey:p,onBucketClick:m,overlay:v,id:y}){const x=g.useRef(()=>{}),{size:b,onResize:S,ref:k}=Aqt(),j=t.map(I=>I.dataKey).join("\0"),C=t.map(I=>I.color).join("\0"),T=g.useMemo(()=>{const I=j.split("\0"),A=C.split("\0");return I.map((P,L)=>vTs({fill:`url(#${y}-bar-${L})`,color:A[L]??"",capped:l==="capped",keys:I,dataKey:P}))},[j,C,l,y]),_=s??Zye.format,N=b.width-(c?Lqt:0);return a.jsxs(a.Fragment,{children:[a.jsx(yTs,{scope:y,setter:x}),a.jsx(zqt,{height:n,plotRef:k,onResize:S,clickable:!!m,children:a.jsxs(aCe,{data:e,margin:uee,onMouseMove:I=>{const A=I?.activeTooltipIndex;x.current(A==null?void 0:Number(A))},onMouseLeave:()=>x.current(void 0),onClick:I=>{const A=I?.activeTooltipIndex,P=A==null?void 0:e[Number(A)];m&&P&&m(P,Number(A))},children:[a.jsx("defs",{children:t.map((I,A)=>a.jsxs("linearGradient",{id:`${y}-bar-${A}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"0%",stopColor:I.color,stopOpacity:1}),a.jsx("stop",{offset:"100%",stopColor:I.color,stopOpacity:hTs})]},I.dataKey))}),a.jsx(Hje,{...Nqt}),Dqt({data:e,xKey:d,timestampKey:f,xLabels:h,plotWidth:N}),Wye({show:c,size:b,formatter:i??_,domain:r}),v&&Wye({id:"overlay",show:!1,size:b,formatter:v.valueFormatter??Zye.format,right:!0}),a.jsx(w6,{cursor:!1,content:a.jsx(Eqt,{formatValue:_,showTotal:u&&!v,labelKey:p,formatByKey:v?.valueFormatter?{[v.dataKey]:v.valueFormatter}:void 0})}),t.map((I,A)=>a.jsx(jNt,{dataKey:I.dataKey,name:I.label,stackId:"1",fill:I.color,maxBarSize:28,isAnimationActive:!1,shape:T[A]},I.dataKey)),v&&a.jsx(Jje,{yAxisId:"overlay",type:"monotone",dataKey:v.dataKey,name:v.label,stroke:v.color,strokeWidth:1.75,strokeDasharray:"4 3",dot:!1,activeDot:{r:3.5,fill:v.color,stroke:"var(--background)",strokeWidth:2},isAnimationActive:!1,connectNulls:!0}),o&&a.jsx(DY,{y:o.value,ifOverflow:"extendDomain",stroke:o.color,strokeDasharray:"4 4",label:{value:o.label,position:"insideTopLeft",...Mqt}})]})})]})}const bTs=[{dataKey:"input",label:"Input",color:mu.green},{dataKey:"cacheRead",label:"Cache read",color:mu.violet},{dataKey:"output",label:"Output",color:mu.sky}],wTs=[{dataKey:"cost",label:"Cost",color:mu.green}],STs=e=>`$${e.toFixed(e<10?1:0)}`;function kTs({onViewTraces:e,onTimeRangeClick:t}){const[n,r]=g.useState("tokens"),{data:s=[],isLoading:i,isError:o,isPlaceholderData:l}=EAe(),{timestamp:c}=mf(),{stepHours:u}=uT(c.start,c.end),d=s.reduce((v,y)=>v+y.input+y.cacheRead+y.output,0),f=s.reduce((v,y)=>v+y.cost,0),h=n==="tokens",p=h?bTs:wTs,m={title:"Token usage",description:h?"Input, cache reads and output.":"Estimated model spend.",actions:e&&a.jsx(iee,{onClick:e}),toolbar:a.jsxs(yi.Toolbar,{children:[a.jsx(cee,{series:p}),a.jsxs(yi.Tabs,{value:n,onValueChange:r,children:[a.jsx(yi.Tab,{value:"tokens",children:"Tokens"}),a.jsx(yi.Tab,{value:"cost",children:"Cost"})]})]})};return o?a.jsx(ih,{...m,children:a.jsx(cT,{})}):a.jsx(ih,{...m,summary:a.jsx(yi.Summary,{value:h?fv(d):eC(f),label:h?"tokens":"cost",isLoading:i}),isUpdating:l,children:a.jsx(lT,{isEmpty:!i&&d===0&&f===0,emptyMessage:"No model calls in this range.",children:a.jsx(Bqt,{data:s,series:p,height:"fill",showLegend:!1,valueFormatter:h?fv:eC,axisFormatter:h?F_s:STs,onBucketClick:t&&(v=>t(lee(Number(v.ts),u))),isLoading:i,...IAe})})})}const OTs=[{dataKey:"completed",label:"Completed",color:mu.green},{dataKey:"failed",label:"Failed",color:mu.error}];function jTs({onTimeRangeClick:e}){const{data:t=[],isLoading:n,isError:r,isPlaceholderData:s}=EAe(),{timestamp:i}=mf(),{stepHours:o}=uT(i.start,i.end),l=t.reduce((u,d)=>u+d.completed+d.failed,0),c={title:"Agent runs",description:"Completed and failed runs."};return r?a.jsx(ih,{...c,children:a.jsx(cT,{})}):a.jsx(ih,{...c,summary:a.jsx(yi.Summary,{value:fv(l),label:"runs",isLoading:n}),isUpdating:s,children:a.jsx(lT,{isEmpty:!n&&l===0,emptyMessage:"No agent runs in this range.",children:a.jsx(Bqt,{data:t,series:OTs,height:"fill",xLabels:"edges",valueFormatter:fv,onBucketClick:e&&(u=>e(lee(Number(u.ts),o))),isLoading:n,...NAe})})})}const lnt=1.75,CTs=.12,_Ts=12;function TTs({points:e}){const[t,n]=e??[];return!t||!n?null:a.jsx("line",{x1:0,x2:0,y1:t.y,y2:n.y,...nTs,className:"pointer-events-none transition-transform duration-150 ease-out",style:{transform:`translateX(${t.x}px)`}})}function $Ae(e){const{data:t,series:n,height:r=210,showLegend:s=!0,isLoading:i=!1,className:o}=e,l=Z(r==="fill"&&"flex min-h-0 flex-1 flex-col",o);return a.jsxs("div",{className:l,children:[s&&a.jsx(cee,{data:i?void 0:t,series:n,className:"mb-4"}),i?a.jsx(Iqt,{kind:"line",height:r}):a.jsx(ETs,{...e})]})}function ETs({data:e,series:t,height:n=210,yDomain:r,onPointClick:s,onBucketClick:i,xKey:o="time",timestampKey:l="tsMs",xLabels:c="auto",tooltipLabelKey:u,showDots:d=!1,valueFormatter:f,axisFormatter:h,showYAxis:p=!0}){const m=Fqt(),{size:v,onResize:y,ref:x}=Aqt(),b=f??Zye.format,S=C=>e.filter(T=>typeof T[C]=="number").length<=_Ts,k=v.width-(p?Lqt:0),j=C=>({r:3.5,fill:C.color,stroke:"var(--background)",strokeWidth:2,...s&&{style:{cursor:"pointer"},onClick:(T,_)=>{cnt(_)&&cnt(_.payload)&&s(_.payload,C.dataKey)}}});return a.jsx(zqt,{height:n,plotRef:x,onResize:y,clickable:!!i,children:a.jsxs(aCe,{data:e,margin:uee,onClick:C=>{const T=C?.activeTooltipIndex,_=T==null?void 0:e[Number(T)];i&&_&&i(_,Number(T))},children:[a.jsx("defs",{children:t.map((C,T)=>a.jsxs("linearGradient",{id:`${m}-area-${T}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"0%",stopColor:C.color,stopOpacity:CTs}),a.jsx("stop",{offset:"95%",stopColor:C.color,stopOpacity:0})]},C.dataKey))}),a.jsx(Hje,{...Nqt}),Dqt({data:e,xKey:o,timestampKey:l,xLabels:c,plotWidth:k}),Wye({show:p,size:v,formatter:h??b,domain:r}),a.jsx(w6,{content:a.jsx(Eqt,{formatValue:b,labelKey:u}),cursor:a.jsx(TTs,{})}),t.map((C,T)=>{const _={type:"monotone",dataKey:C.dataKey,name:C.label,stroke:C.color,strokeWidth:C.emphasis?lnt+.5:lnt,strokeDasharray:C.dashed?"4 3":void 0,dot:d||S(C.dataKey)?{r:3,fill:C.color,strokeWidth:0}:!1,activeDot:j(C),isAnimationActive:!1,connectNulls:!0};return C.dashed?a.jsx(Jje,{..._},C.dataKey):a.jsx(zY,{..._,fill:`url(#${m}-area-${T})`,fillOpacity:1},C.dataKey)})]})})}function cnt(e){return typeof e=="object"&&e!==null}const ITs=[{dataKey:"failureRate",label:"Failed runs",color:mu.error}],NTs=e=>`${Math.round(e*100)}%`;function ATs({onViewErrors:e,onTimeRangeClick:t}){const{data:n=[],isLoading:r,isError:s,isPlaceholderData:i}=EAe(),{timestamp:o}=mf(),{stepHours:l}=uT(o.start,o.end),c=n.reduce((h,p)=>h+p.completed+p.failed,0),u=n.reduce((h,p)=>h+p.failed,0),d=u===0?[0,1]:void 0,f={title:"Failure rate",description:"Share of agent runs that failed.",actions:e&&a.jsx(Sqt,{onClick:e})};return s?a.jsx(ih,{...f,children:a.jsx(cT,{})}):a.jsx(ih,{...f,summary:a.jsx(yi.Summary,{value:Qye(c>0?u/c:0),label:"failed",isLoading:r}),isUpdating:i,children:a.jsx(lT,{isEmpty:!r&&c===0,emptyMessage:"No agent runs in this range.",children:a.jsx($Ae,{data:n,series:ITs,height:"fill",xLabels:"edges",valueFormatter:Qye,axisFormatter:NTs,yDomain:d,onBucketClick:t&&(h=>t(lee(Number(h.ts),l))),isLoading:r,...NAe})})})}const PTs={agents:"mastra_agent_duration_ms",workflows:"mastra_workflow_duration_ms",tools:"mastra_tool_duration_ms"},unt=["agents","workflows","tools"];function $Ts(){const e=Ge(),{filters:t,filterKey:n,timestamp:r}=mf(),{interval:s}=uT(r.start,r.end),i=jAe(s);return _t({queryKey:["metrics","latency-percentiles",n,s],placeholderData:fx,queryFn:async()=>{const o=await Promise.all(unt.map(u=>e.getMetricPercentiles({name:PTs[u],percentiles:[.5,.95],interval:s,filters:t}))),l=_Ae(r.start,r.end,i),c=TAe(l,i);return o.forEach((u,d)=>{const f=unt[d];if(f)for(const h of u.series){const p=RTs(f,h.percentile);if(p)for(const m of h.points){const v=l[c(m)??-1];v&&(v[p]=Math.round(m.value))}}}),l}})}function RTs(e,t){if(t===.5)return`${e}P50`;if(t===.95)return`${e}P95`}const MTs={agents:od.AGENT,workflows:od.WORKFLOW_RUN,tools:od.TOOL};function DTs(e){return[{dataKey:`${e}P50`,label:"P50",color:mu.sky},{dataKey:`${e}P95`,label:"P95",color:mu.green,emphasis:!0}]}const LTs={agents:"agent runs",workflows:"workflow runs",tools:"tool calls"};function zTs({onViewTraces:e,onTimeRangeClick:t}){const[n,r]=g.useState("agents"),{data:s=[],isLoading:i,isError:o,isPlaceholderData:l}=$Ts(),{timestamp:c}=mf(),u=jAe(uT(c.start,c.end).interval),d=DTs(n),f=Math.max(0,...s.map(p=>p[`${n}P95`]??0)),h={title:"Latency",description:"Duration percentiles.",actions:e&&a.jsx(iee,{onClick:()=>e(MTs[n])}),toolbar:a.jsxs(yi.Toolbar,{children:[a.jsx(cee,{series:d}),a.jsxs(yi.Tabs,{value:n,onValueChange:r,children:[a.jsx(yi.Tab,{value:"agents",children:"Agents"}),a.jsx(yi.Tab,{value:"workflows",children:"Workflows"}),a.jsx(yi.Tab,{value:"tools",children:"Tools"})]})]})};return o?a.jsx(ih,{...h,children:a.jsx(cT,{})}):a.jsx(ih,{...h,summary:a.jsx(yi.Summary,{value:f>0?int(f):"—",label:"peak P95",isLoading:i}),isUpdating:l,children:a.jsx(lT,{isEmpty:!i&&f===0,emptyMessage:`No ${LTs[n]} in this range.`,children:a.jsx($Ae,{data:s,series:d,height:"fill",xLabels:"edges",showLegend:!1,valueFormatter:int,axisFormatter:B_s,onBucketClick:t&&(p=>t(lee(Number(p.ts),u))),isLoading:i,...NAe})})})}function Uqt({columns:e=[],valueLabel:t,valueWidth:n="w-14",className:r}){return a.jsxs("div",{"aria-hidden":!0,className:Z("flex shrink-0 items-center gap-3 text-column text-placeholder",r),children:[e.map(s=>a.jsx("span",{className:Z("shrink-0 text-right",s.width??"w-16"),children:s.label},s.label)),a.jsx("span",{className:"w-12 shrink-0 text-right",children:"Share"}),a.jsx("span",{className:Z("shrink-0 text-right",n),children:t})]})}const Vqt="-mx-2 flex w-[calc(100%+1rem)] items-center gap-3 rounded-md px-2 py-1 text-left",rN="shrink-0 text-right text-body-sm tabular-nums";function FTs({row:e,columns:t,valueWidth:n,share:r,highlighted:s,dimmed:i,onHover:o,LinkComponent:l}){const c=Z(Vqt,"transition-[background-color,opacity] duration-150",s&&"bg-fill-subtle",(e.href||e.onClick)&&"hover:bg-fill-subtle");return a.jsx("li",{children:a.jsxs(BTs,{row:e,LinkComponent:l,className:c,style:{opacity:i?.5:1},onMouseEnter:o,children:[a.jsx("span",{className:"size-2 shrink-0 rounded-[2px]",style:{backgroundColor:e.paint.color,opacity:e.paint.alpha}}),a.jsx(UTs,{row:e}),t.map((u,d)=>a.jsx("span",{className:Z(rN,"text-muted-foreground",u.width??"w-16"),children:e.cells?.[d]},u.label)),a.jsx("span",{className:Z(rN,"w-12 text-muted-foreground"),children:r}),a.jsx("span",{className:Z(rN,"text-foreground",n),children:e.value})]})})}function BTs({row:e,LinkComponent:t,...n}){if(e.href){const r=t??"a";return a.jsx(r,{href:e.href,...n})}return e.onClick?a.jsx("button",{type:"button",onClick:e.onClick,...n}):a.jsx("div",{...n})}function UTs({row:e}){return typeof e.label!="string"?a.jsx("span",{className:"flex min-w-0 flex-1",title:e.title,children:e.label}):a.jsx("span",{className:"min-w-0 flex-1 truncate",title:e.title??e.label,children:a.jsx(Y,{as:"span",variant:"body-sm",tone:"ink",children:e.label})})}const VTs="var(--chart-share-1)",dnt=[1,2,3,4,5].map(e=>`var(--chart-share-${e})`),qTs=[3,4,2,5,1].map(e=>`var(--chart-share-${e})`),QTs=[1,.7,.48,.32,.2,.14],dee={color:"var(--chart-share-rest)",alpha:1},ZTs=50,a_="__rest";function qqt(e,t,n){if(n==="hues"){const r=dnt.includes(e)?[e,...dnt.filter(s=>s!==e)]:[e,...qTs];return Array.from({length:t},(s,i)=>({color:r[i%r.length]??e,alpha:[1,.55,.3][Math.floor(i/r.length)]??.2}))}return Array.from({length:t},(r,s)=>({color:e,alpha:QTs[s]??.1}))}const RAe=e=>e.reduce((t,n)=>t+Math.max(n.share,0),0);function WTs(e){return e.map(t=>Number.isFinite(t.share)&&t.share>0?t:{...t,share:0}).toSorted((t,n)=>n.share-t.share)}function HTs(e,{limit:t,other:n,color:r,palette:s}){if(e.length<=t+1)return{shown:fnt(e,r,s),rest:[]};const i=e.slice(t),o=n?.(i),l={key:a_,label:`Other (${i.length})`,share:RAe(i),value:o?.value,cells:o?.cells,paint:dee,segment:a_};return{shown:[...fnt(e.slice(0,t),r,s),l],rest:i}}function fnt(e,t,n){const r=qqt(t,e.length,n);return e.map((s,i)=>({...s,paint:r[i]??dee,segment:s.key}))}function GTs(e,{count:t,activeKey:n,color:r,palette:s}){const i=Math.min(t,e.length,ZTs),o=qqt(r,i,s),l=new Map(e.map((u,d)=>[u.key,d]));return{shown:KTs(e,t,n).map(u=>{const d=l.get(u.key)??e.length;return{...u,paint:o[d]??dee,segment:d<i?u.key:a_}}),rest:e.slice(i)}}function KTs(e,t,n){const r=e.slice(0,t),s=n?e.findIndex(o=>o.key===n):-1,i=s>=t?e[s]:void 0;return i?[...r,i]:r}function YTs(e,t){const n=e.filter(o=>o.segment!==a_).map(o=>({key:o.key,share:o.share,paint:o.paint})),r=t.length?[{key:a_,share:RAe(t),paint:dee}]:[],s=[...n,...r].filter(o=>o.share>0),i=s.reduce((o,l)=>o+l.share,0);return s.map(o=>({key:o.key,paint:o.paint,grow:o.share/i*100}))}function XTs(e,t){if(t!==void 0)return e.find(n=>n.key===t)?.segment??t}const JTs=(e,t)=>t!==void 0&&t!==e;function eEs(e,t){return t===void 0||t===e.key?!1:!(t===a_&&e.segment===a_)}const tEs=(e,t)=>{const n=e/(t||1);return n>0?n<.001?"<0.1%":`${(n*100).toFixed(n<.1?1:0)}%`:"0%"};function nEs({shown:e,total:t,limit:n,pageSize:r,onMore:s,onLess:i}){if(t<=n)return null;const o=t-e,l="flex items-center gap-1.5 rounded-md px-2 py-1 text-body-sm font-medium text-muted-foreground transition-colors duration-150 hover:bg-fill-subtle hover:text-foreground",c=new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1});return a.jsxs("li",{className:"-mx-2 flex items-center gap-1",children:[o>0&&a.jsxs("button",{type:"button",onClick:s,className:l,children:[a.jsx(dc,{className:"size-3.5 shrink-0"}),"Show ",Math.min(o,r)," more"]}),e>n&&a.jsxs("button",{type:"button",onClick:i,className:l,children:[a.jsx(ZH,{className:"size-3.5 shrink-0"}),"Show top ",n]}),o>0&&a.jsxs("span",{className:"ml-auto pr-2 text-body-sm text-placeholder tabular-nums",children:[c.format(e)," of ",c.format(t)]})]})}const hnt=["w-32","w-24","w-36","w-20","w-28"];function Z7({className:e}){return a.jsxs(a.Fragment,{children:["",a.jsx(xt,{className:Z("absolute top-1/2 h-3.5 -translate-y-1/2",e)})]})}function rEs({rows:e,columns:t,valueWidth:n}){return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"flex h-2",children:a.jsx(xt,{className:"size-full rounded-full"})}),a.jsx("ul",{className:"grid min-w-0 grid-cols-1 gap-0.5","aria-busy":!0,children:Array.from({length:e},(r,s)=>a.jsxs("li",{className:Vqt,children:[a.jsx(xt,{className:"size-2 shrink-0 rounded-[2px]"}),a.jsx("span",{className:"min-w-0 flex-1",children:a.jsx(Y,{as:"span",variant:"body-sm",className:"relative",children:a.jsx(Z7,{className:Z("left-0",hnt[s%hnt.length])})})}),t.map(i=>a.jsx("span",{className:Z(rN,"relative",i.width??"w-16"),children:a.jsx(Z7,{className:"right-0 w-10"})},i.label)),a.jsx("span",{className:Z(rN,"relative w-12"),children:a.jsx(Z7,{className:"right-0 w-9"})}),a.jsx("span",{className:Z(rN,"relative",n),children:a.jsx(Z7,{className:"right-0 w-12"})})]},s))})]})}function S3({showHeader:e=!0,className:t,...n}){const{columns:r=[],valueLabel:s,valueWidth:i="w-14"}=n;return a.jsxs("div",{className:Z("grid grid-cols-1 gap-4",t),children:[e&&a.jsx("div",{className:"flex justify-end",children:a.jsx(Uqt,{columns:r,valueLabel:s,valueWidth:i})}),a.jsx(sEs,{...n})]})}function sEs({rows:e,columns:t=[],valueLabel:n,valueWidth:r="w-14",palette:s="shades",color:i=VTs,limit:o=5,overflow:l="other",pageSize:c=50,other:u,activeKey:d,emptyState:f="No data in this range.",isLoading:h=!1,LinkComponent:p}){const[m,v]=g.useState(),[y,x]=g.useState(0),b=o+y*c;if(h)return a.jsx(rEs,{rows:l==="other"?o+1:o,columns:t,valueWidth:r});const S=WTs(e);if(S.length===0)return a.jsx(Y,{variant:"body-sm",tone:"muted",className:"py-6 text-center",children:f});const k=RAe(S),j=l==="more",{shown:C,rest:T}=j?GTs(S,{count:b,activeKey:d,color:i,palette:s}):HTs(S,{limit:o,other:u,color:i,palette:s}),_=YTs(C,T),N=XTs(C,m),I=()=>v(void 0);return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"flex h-2 gap-0.5",onMouseLeave:I,children:_.map(A=>a.jsx("span",{"data-testid":"metrics-share-segment",onMouseEnter:()=>v(A.key),className:"h-full min-w-[3px] transition-opacity duration-150 first:rounded-l-full last:rounded-r-full",style:{flex:`${A.grow} 1 0`,backgroundColor:A.paint.color,opacity:A.paint.alpha*(JTs(A.key,N)?.3:1)}},A.key))}),a.jsxs("ul",{className:"grid min-w-0 grid-cols-1 gap-0.5",onMouseLeave:I,children:[C.map(A=>a.jsx(FTs,{row:A,columns:t,valueWidth:r,share:tEs(A.share,k),highlighted:m===A.key||d===A.key,dimmed:eEs(A,m),onHover:()=>v(A.key),LinkComponent:p},A.key)),j&&a.jsx(nEs,{shown:Math.min(b,S.length),total:S.length,limit:o,pageSize:c,onMore:()=>x(A=>A+1),onLess:()=>x(0)})]})]})}S3.Header=Uqt;const iEs={agents:od.AGENT,workflows:od.WORKFLOW_RUN,tools:od.TOOL},pnt=[{label:"Error rate"}],mnt=(e,t)=>Qye(t>0?e/t:0);function oEs({onViewTraces:e,onViewErrors:t,onEntityClick:n}){const[r,s]=g.useState("agents"),i=iEs[r],o=z_s({...mf(),queryOptions:{placeholderData:fx}}),l={agents:o.data?.agentData??[],workflows:o.data?.workflowData??[],tools:o.data?.toolData??[]},c=l[r],u=c.map(p=>({key:p.name,label:p.name,share:p.completed+p.errors,value:fv(p.completed+p.errors),cells:[mnt(p.errors,p.completed+p.errors)],onClick:n&&(()=>n(i,p.name))})),d=new Map(c.map(p=>[p.name,p.errors])),f=[...l.agents,...l.workflows,...l.tools].reduce((p,m)=>p+m.completed+m.errors,0),h={title:"Trace volume",description:"Runs and calls, with error rate.",actions:(e||t)&&a.jsxs(a.Fragment,{children:[e&&a.jsx(iee,{onClick:()=>e(i)}),t&&a.jsx(Sqt,{onClick:()=>t(i)})]}),toolbar:a.jsxs(yi.Toolbar,{children:[a.jsxs(yi.Tabs,{value:r,onValueChange:s,children:[a.jsx(yi.Tab,{value:"agents",children:"Agents"}),a.jsx(yi.Tab,{value:"workflows",children:"Workflows"}),a.jsx(yi.Tab,{value:"tools",children:"Tools"})]}),a.jsx(S3.Header,{columns:pnt,valueLabel:"Runs"})]})};return o.isError?a.jsx(ih,{...h,children:a.jsx(cT,{})}):a.jsx(ih,{...h,summary:a.jsx(yi.Summary,{value:fv(f),label:"runs and calls",isLoading:o.isLoading}),isUpdating:o.isPlaceholderData,children:a.jsx(lT,{children:a.jsx(S3,{rows:u,columns:pnt,valueLabel:"Runs",showHeader:!1,color:mu.sky,other:p=>{const m=p.reduce((y,x)=>y+(d.get(x.key)??0),0),v=p.reduce((y,x)=>y+x.share,0);return{value:fv(v),cells:[mnt(m,v)]}},emptyState:"No runs in this range.",isLoading:o.isLoading},r)})})}const aEs=["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],lEs=100;function Qqt(e){const t=Ge(),{filters:n,filterKey:r}=mf();return _t({queryKey:["metrics","token-spend",e,r],placeholderData:fx,queryFn:async()=>{const{groups:s}=await t.getMetricBreakdown({name:aEs,groupBy:[e],aggregation:"sum",orderDirection:"DESC",limit:lEs,filters:n});return s.map(i=>({key:String(i.dimensions[e]??"unknown"),tokens:i.value,cost:i.estimatedCost??0}))}})}const cEs={placeholderData:fx},gnt=[{label:"Tokens"}];function uEs(e){const[t,n]=g.useState("agents");return t==="models"?a.jsx(fEs,{...e,onViewChange:n}):t==="threads"?a.jsx(hEs,{...e,onViewChange:n}):a.jsx(dEs,{...e,onViewChange:n})}function dEs(e){const{onAgentClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:s,isError:i}=D_s({...mf(),queryOptions:cEs}),o=n.map(l=>({key:l.name,cost:l.cost??0,tokens:l.total,onClick:t&&(()=>t(l.name))}));return a.jsx(MAe,{view:"agents",...e,rows:o,isLoading:r,isUpdating:s,isError:i})}function fEs(e){const{onModelClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:s,isError:i}=Qqt("model"),o=n.map(l=>({...l,onClick:t&&(()=>t(l.key))}));return a.jsx(MAe,{view:"models",...e,rows:o,isLoading:r,isUpdating:s,isError:i})}function hEs(e){const{onThreadClick:t}=e,{data:n=[],isLoading:r,isPlaceholderData:s,isError:i}=Qqt("threadId"),o=n.map(l=>({...l,onClick:t&&(()=>t(l.key))}));return a.jsx(MAe,{view:"threads",...e,rows:o,isLoading:r,isUpdating:s,isError:i})}function MAe({view:e,onViewChange:t,onViewTraces:n,rows:r,isLoading:s,isUpdating:i,isError:o}){const l=new Map(r.map(d=>[d.key,d.tokens])),c=r.map(d=>({key:d.key,label:d.key,share:d.cost,value:eC(d.cost),cells:[fv(d.tokens)],onClick:d.onClick})),u={title:"Usage",description:"Who is spending: cost share, with tokens.",actions:n&&a.jsx(iee,{onClick:n}),toolbar:a.jsxs(yi.Toolbar,{children:[a.jsxs(yi.Tabs,{value:e,onValueChange:t,children:[a.jsx(yi.Tab,{value:"agents",children:"Agents"}),a.jsx(yi.Tab,{value:"models",children:"Models"}),a.jsx(yi.Tab,{value:"threads",children:"Threads"})]}),a.jsx(S3.Header,{columns:gnt,valueLabel:"Cost"})]})};return o?a.jsx(ih,{...u,children:a.jsx(cT,{})}):a.jsx(ih,{...u,summary:a.jsx(yi.Summary,{value:eC(r.reduce((d,f)=>d+f.cost,0)),label:"cost",isLoading:s}),isUpdating:i,children:a.jsx(lT,{children:a.jsx(S3,{rows:c,columns:gnt,valueLabel:"Cost",showHeader:!1,color:mu.green,other:d=>({value:eC(d.reduce((f,h)=>f+h.share,0)),cells:[fv(d.reduce((f,h)=>f+(l.get(h.key)??0),0))]}),emptyState:"No model usage in this range.",isLoading:s})})})}const pEs=100;function mEs(){const e=Ge(),{filters:t,filterKey:n,timestamp:r}=mf(),{interval:s}=uT(r.start,r.end),i=jAe(s);return _t({queryKey:["metrics","scores",n,s],placeholderData:fx,queryFn:async()=>{const o=await e.listScores({filters:t,pagination:{page:0,perPage:pEs}}),l=new Map(o.scores.map(p=>[p.scorerId,p.scorerName??p.scorerId])),c=[...l.keys()].toSorted(),u=await Promise.all(c.map(p=>Promise.all([e.getScoreAggregate({scorerId:p,aggregation:"avg",filters:t}),e.getScoreTimeSeries({scorerId:p,aggregation:"avg",interval:s,filters:t})]))),d=_Ae(r.start,r.end,i),f=TAe(d,i),h=[];return u.forEach(([p,m],v)=>{const y=c[v];if(y){h.push({scorerId:y,name:l.get(y)??y,average:p.value??0});for(const x of m.series)for(const b of x.points){const S=d[f(b)??-1];S&&(S[y]=b.value)}}}),{scorers:h,buckets:d}}})}const vnt=[mu.green,mu.sky,mu.violet,mu.teal,mu.indigo],Zqt=e=>e.toFixed(2),gEs=e=>e.toFixed(1);function vEs(e){return e.map(({scorerId:t,name:n,average:r},s)=>({dataKey:t,label:n,color:vnt[s%vnt.length]??mu.neutral,aggregate:()=>({value:Zqt(r)})}))}function yEs(){const{data:e,isLoading:t,isError:n,isPlaceholderData:r}=mEs(),s=e?.scorers??[],i={title:"Scores",description:"Average scorer result, 0 to 1."};return n?a.jsx(ih,{...i,children:a.jsx(cT,{})}):a.jsx(ih,{...i,summary:a.jsx(yi.Summary,{value:String(s.length),label:s.length===1?"scorer":"scorers",isLoading:t}),isUpdating:r,children:a.jsx(lT,{isEmpty:!t&&s.length===0,emptyMessage:"No scores in this range.",children:a.jsx($Ae,{data:e?.buckets??[],series:vEs(s),height:"fill",yDomain:[0,1],valueFormatter:Zqt,axisFormatter:gEs,isLoading:t,...IAe})})})}function xEs({experiment:e,metrics:t}){const{data:n}=JL({experimentId:e.id,experimentStatus:e.status,queryOptions:{enabled:!!e.id}}),r=e.status==="running"||e.status==="pending",s=g.useMemo(()=>[{id:e.id,status:e.status}],[e.id,e.status]),{data:i,isLoading:o}=mAe({experiments:s,supportsMetrics:t?.isEnabled??!1}),l=g.useMemo(()=>{if(!n)return;const x=Object.values(n).flat();return x.length===0?null:x.reduce((b,S)=>b+S.score,0)/x.length},[n]),c=e.startedAt??e.createdAt,u=(()=>{if(r)return"Running…";if(!e.startedAt||!e.completedAt)return"—";const x=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return Vc(x)??"—"})(),d=r?" so far":"",f=i[e.id]?.summary,h=qA(f),p=f?.inputTokens===void 0&&f?.outputTokens===void 0?`input + output${d}`:`${iS(f.inputTokens??0)} in · ${iS(f.outputTokens??0)} out${d}`,m=t?.isEnabled?t.data?.avgAgentDurationMs:void 0,v=m==null?void 0:Vc(Math.round(m)),y=v?`${v} avg per item${d}`:c?`started ${Jr(new Date(c),"date-time")}`:"not started";return a.jsxs(gqt,{children:[t?.isEnabled&&a.jsx(B1,{label:"Total cost",icon:HH,value:f?.estimatedCost===void 0?"—":Rz(f.estimatedCost,f.costUnit),detail:`estimated${d}`,isLoading:o}),a.jsx(B1,{label:"Run duration",icon:gx,value:u,detail:y}),t?.isEnabled&&a.jsx(B1,{label:"Total tokens",icon:Z0,value:h===void 0?"—":iS(h),detail:p,isLoading:o}),a.jsx(B1,{label:"Avg score",icon:tg,value:l==null?"—":l.toFixed(3),detail:l!=null?`across all scorers${d}`:r?"waiting for scores":"no scores",isLoading:l===void 0&&!r})]})}function bEs({selection:e}){const{selectedIds:t,selectedResults:n,tagVocabulary:r,isFlagging:s,isTagging:i}=e,o=s||i,l=t.size===0;return a.jsxs("div",{className:"flex min-h-8 items-center gap-2 whitespace-nowrap",children:[a.jsxs(ue,{variant:"ghost",size:"sm",disabled:l,iconEnd:l?void 0:a.jsx(zn,{}),onClick:e.clearSelection,tooltip:l?void 0:"Clear selection",className:"tabular-nums",children:[t.size," selected"]}),!l&&a.jsxs(a.Fragment,{children:[a.jsx(ue,{size:"sm",disabled:o,onClick:e.flagSelectedForReview,icon:a.jsx(Nht,{}),children:"Request review"}),a.jsx(dqt,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:o})]})]})}const Wqt=()=>{const{experimentId:e}=jr(),{data:t}=wOt({experimentId:e??"",queryOptions:{enabled:!!e,retryOnMount:!1}});return{experimentId:e,experiment:t}},Hqt=()=>{const{experimentId:e,experiment:t}=Wqt(),n=t?.datasetId??"",{data:r}=xOt({datasetId:n,experimentId:e??"",queryOptions:{enabled:!!(n&&e),retryOnMount:!1}});return r??t};function wEs(){const{experimentId:e,experiment:t}=Wqt();if(!e)return null;const n=e.length>8?`${e.slice(0,8)}...`:e;return t?.name||n}function SEs(){const e=Hqt();return e?.status?a.jsx(fjs,{status:e.status}):null}function kEs(){const e=Hqt();if(!e)return null;const{totalItems:t,succeededCount:n,failedCount:r,status:s}=e,i=s==="running"||s==="pending",o=t===1?"item":"items",l=i?`${n+r}/${t} ${o}`:`${t} ${o}`;return a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"whitespace-nowrap tabular-nums",children:r>0?`${l} · ${r} errored`:l})}function OEs({datasetId:e,experimentId:t}){const[n,r]=g.useState(!1),{updateExperimentResult:s}=pl();return{addTag:g.useCallback(async(o,l)=>{const c=l.filter(d=>!(d.tags??[]).includes(o));if(n||c.length===0)return;r(!0);let u=0;try{u=(await Promise.allSettled(c.map(f=>s.mutateAsync({datasetId:e,experimentId:t,resultId:f.id,tags:[...f.tags??[],o]})))).filter(f=>f.status==="fulfilled").length}finally{r(!1)}u>0?Ye(`Tag "${o}" added to ${u} result${u>1?"s":""}`):Ye.error("Failed to add tag")},[e,t,n,s]),isPending:n}}function jEs({datasetId:e,experimentId:t,results:n}){const[r,s]=g.useState(new Set),[i,o]=g.useState(!1),{updateExperimentResult:l}=pl(),{addTag:c,isPending:u}=OEs({datasetId:e,experimentId:t}),d=pqt(e,n),f=g.useMemo(()=>n.filter(x=>r.has(x.id)),[n,r]),h=g.useCallback(x=>{s(b=>{const S=new Set(b);return S.has(x)?S.delete(x):S.add(x),S})},[]),p=g.useCallback(()=>s(new Set),[]),m=g.useCallback(()=>{s(x=>n.length>0&&n.every(b=>x.has(b.id))?new Set:new Set(n.map(b=>b.id)))},[n]),v=g.useCallback(async()=>{if(i||r.size===0)return;o(!0);const x=new Set;try{for(const b of r)try{await l.mutateAsync({datasetId:e,experimentId:t,resultId:b,status:"needs-review"}),x.add(b)}catch{}}finally{o(!1)}x.size>0&&(s(b=>{const S=new Set(b);for(const k of x)S.delete(k);return S}),Ye(`${x.size} result${x.size>1?"s":""} flagged for review`))},[e,t,i,r,l]),y=g.useCallback(x=>c(x,f),[c,f]);return{selectedIds:r,selectedResults:f,toggleSelect:h,toggleSelectAll:m,clearSelection:p,flagSelectedForReview:v,isFlagging:i,addTagToSelected:y,isTagging:u,tagVocabulary:d}}const CEs=[],_Es=["startedAt"];function W7({crumbs:e,children:t}){return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:e}),children:[a.jsx("h1",{className:"sr-only",children:"Experiment"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:t})]})}function TEs(){const{experimentId:e}=jr(),t=[Ts("/experiments"),{id:"experiment",Component:wEs,icon:SEs,Action:kEs}],n=Dr(),[r,s]=g.useState(!1),i=GJ(),[o,l]=ci(),{sort:c,onSortChange:u}=Hk({searchParams:o,setSearchParams:l,allowedKeys:_Es}),d=g.useMemo(()=>c?{field:c.key,direction:c.direction==="asc"?"ASC":"DESC"}:void 0,[c]),{data:f,isLoading:h,error:p}=wOt({experimentId:e??"",queryOptions:{enabled:!!e}}),m=f?.datasetId??"",{data:v,isLoading:y,error:x}=xOt({datasetId:m,experimentId:e??"",queryOptions:{enabled:!!m&&!!e}}),{data:b,isLoading:S,setEndOfListElement:k,isFetchingNextPage:j,hasNextPage:C}=Ocr({datasetId:m,experimentId:e??"",experimentStatus:v?.status,orderBy:d,queryOptions:{enabled:!!m&&!!e}}),{supportsMetrics:T}=O$(),_=ZOs({experimentId:e,experimentStatus:v?.status,supportsMetrics:T,queryOptions:{enabled:!!e&&T}}),N=jEs({datasetId:m,experimentId:e??"",results:b??CEs}),I=p??x;if(!e||h||y)return null;if(I&&Cs(I))return a.jsx(W7,{crumbs:t,children:a.jsx(ui,{})});if(I&&_s(I))return a.jsx(W7,{crumbs:t,children:a.jsx(Gs,{resource:"datasets"})});const A=a.jsx(W7,{crumbs:t,children:a.jsx(Xt,{titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:a.jsx(ue,{render:a.jsx(ac,{to:"/experiments"}),icon:a.jsx(vd,{}),children:"Back to Experiments"})})});return I&&Ik(I)?A:I?a.jsx(W7,{crumbs:t,children:a.jsx(Xt,{tone:"error",titleSlot:"Failed to load experiment",descriptionSlot:I instanceof Error?I.message:"An unexpected error occurred. Please try again."})}):!m||!v?A:a.jsx(GOs,{experimentId:e,datasetId:m,experimentStatus:v.status,results:b??[],isLoadingResults:S,hasNextPage:C,children:a.jsxs("div",{className:"h-full",children:[a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),headerActions:a.jsx(LCs,{experiment:v,onDeleteClick:()=>s(!0)}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsxs("div",{className:"grid content-start gap-4",children:[a.jsx(xEs,{experiment:v,metrics:_}),a.jsxs("div",{className:"grid content-start gap-1",children:[a.jsx(bEs,{selection:N}),a.jsx(ojs,{experimentId:e,experimentStatus:v.status,results:b??[],isLoading:S,setEndOfListElement:k,isFetchingNextPage:j,hasNextPage:C,selectedIds:N.selectedIds,onToggleSelect:N.toggleSelect,onToggleSelectAll:N.toggleSelectAll,sort:c,onSortChange:u,supportsMetrics:T})]})]})]}),a.jsx(YCs,{withQueryTrace:i.enabled,withFeedback:i.enabled}),a.jsx(iqt,{open:r,onOpenChange:s,experimentId:e,experimentName:v.name??void 0,onSuccess:()=>n("/experiments")})]})})}function EEs({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(wn,{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(Ln,"p-0.5"),children:a.jsx(ur,{className:"h-3 w-3"})})]}):a.jsxs("span",{className:"group inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1.5 py-0.5 text-muted-foreground",children:[a.jsx(Y,{as:"span",variant:"caption",children:e}),a.jsx("button",{type:"button",onClick:()=>{o(e),s(!0)},className:Z(Ln,"p-0.5 opacity-0 transition-opacity group-hover:opacity-100"),title:"Edit tag",children:a.jsx(Bc,{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(zn,{className:"h-3 w-3"})})]})}function IEs({selectedCount:e,vocabulary:t,onApplyTag:n,onRemoveTag:r,onNewTag:s,size:i="sm"}){const[o,l]=g.useState(!1),[c,u]=g.useState(""),d=t.filter(h=>h.toLowerCase().includes(c.toLowerCase())),f=c.trim()&&!t.includes(c.trim());return a.jsxs(jp,{open:o,onOpenChange:l,children:[a.jsx(sf,{asChild:!0,children:a.jsxs(ue,{size:i,icon:a.jsx(Nx,{}),children:["Tag ",e," items"]})}),a.jsxs(lh,{className:"w-56 p-2",align:"end",children:[a.jsx(wn,{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(zn,{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 NEs=[{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"}],wue="__untagged__",H7="all",AEs=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}];function PEs({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=Ge(),{paths:v}=Tn(),{data:y}=zx({datasetId:e??"",queryOptions:{enabled:!!e}}),{data:x,isLoading:b}=Pjs({experimentId:t,targetType:s,targetId:i,experiments:n,isLoadingExperiments:r}),{data:S,isLoading:k}=$js({experimentId:t,targetType:s,targetId:i,experiments:n,isLoadingExperiments:r}),{updateExperimentResult:j}=pl(),[C,T]=g.useState(o??null);g.useEffect(()=>{o!==void 0&&T(o)},[o]);const[_,N]=g.useState(null),[I,A]=g.useState(new Set),[P,L]=g.useState(!1),[F,Q]=g.useState(!1),[q,B]=g.useState(!1),[V,H]=g.useState(""),[D,K]=g.useState(""),[M,$]=g.useState(""),[z,U]=g.useState([]),[G,ne]=g.useState(!1),X=g.useMemo(()=>x??[],[x]),ee=g.useMemo(()=>{const ge=new Set;if(y?.tags)for(const Pe of y.tags)ge.add(Pe);for(const Pe of X)for(const Xe of Pe.tags)ge.add(Xe);return[...ge].sort()},[y,X]),ie=g.useCallback(ge=>{!y||!e||(y.tags??[]).includes(ge)},[y,e]),fe=g.useMemo(()=>_?_===wue?X.filter(ge=>ge.tags.length===0):X.filter(ge=>ge.tags.includes(_)):X,[X,_]),te=g.useMemo(()=>{const ge=new Map;let Pe=0;for(const St of X){St.tags.length===0&&Pe++;for(const Ft of St.tags)ge.set(Ft,(ge.get(Ft)??0)+1)}const Xe=[...ge.entries()].sort((St,Ft)=>Ft[1]-St[1]).map(([St])=>({value:St,label:St}));return[{value:H7,label:"All tags"},...Pe>0?[{value:wue,label:"Untagged"}]:[],...Xe]},[X]),se=!!_||P,re=g.useCallback(()=>{N(null),L(!1),T(null)},[]),le=g.useCallback((ge,Pe)=>{const Xe=X.find(St=>St.id===ge);Xe?.experimentId&&Xe?.datasetId&&j.mutate({datasetId:Xe.datasetId,experimentId:Xe.experimentId,resultId:Xe.id,tags:Pe})},[X,j]),pe=g.useCallback(ge=>{const Pe=X.find(Xe=>Xe.id===ge);A(Xe=>{const St=new Set(Xe);return St.delete(ge),St}),C===ge&&T(null),Pe?.experimentId&&Pe?.datasetId&&j.mutate({datasetId:Pe.datasetId,experimentId:Pe.experimentId,resultId:Pe.id,status:null})},[X,j,C]),ve=g.useCallback(ge=>{const Pe=X.find(Xe=>Xe.id===ge);A(Xe=>{const St=new Set(Xe);return St.delete(ge),St}),C===ge&&T(null),Pe?.experimentId&&Pe?.datasetId&&j.mutate({datasetId:Pe.datasetId,experimentId:Pe.experimentId,resultId:Pe.id,status:"complete"})},[X,j,C]),he=g.useMemo(()=>{const ge=P?S??[]:fe;return!P||!_?ge:_===wue?ge.filter(Pe=>Pe.tags.length===0):ge.filter(Pe=>Pe.tags.includes(_))},[P,S,fe,_]),ke=P?k:!1,Ee=g.useMemo(()=>new Set(he.map(ge=>ge.id)),[he]),Ve=g.useMemo(()=>[...I].filter(ge=>Ee.has(ge)).length,[I,Ee]),Ze=he.length>0&&Ve===he.length,Fe=g.useCallback(ge=>{A(Pe=>{const Xe=new Set(Pe);return Xe.has(ge)?Xe.delete(ge):Xe.add(ge),Xe})},[]),Ae=g.useCallback(()=>{A(Ze?new Set:new Set(he.map(ge=>ge.id)))},[Ze,he]),ze=g.useCallback(ge=>{for(const Pe of I){const Xe=X.find(St=>St.id===Pe);Xe&&!Xe.tags.includes(ge)&&le(Pe,[...Xe.tags,ge])}},[X,I,le]),je=g.useCallback(ge=>{for(const Pe of I){const Xe=X.find(St=>St.id===Pe);Xe&&Xe.tags.includes(ge)&&le(Pe,Xe.tags.filter(St=>St!==ge))}},[X,I,le]),Ce=g.useCallback(()=>{for(const ge of I)ve(ge);A(new Set)},[I,ve]),Ue=g.useCallback(()=>{for(const ge of I)pe(ge);A(new Set)},[I,pe]),ae=g.useCallback(()=>{H(""),B(!0)},[]),me=g.useCallback(async()=>{if(!(!D||!M)){Q(!0),B(!1);try{const ge=X.filter(Xe=>I.has(Xe.id));if(ge.length===0){Q(!1);return}const Pe=await m.clusterFailures({modelId:`${D}/${M}`,items:ge.map(Xe=>({id:Xe.id,input:Xe.input,output:Xe.output??void 0,error:typeof Xe.error=="string"?Xe.error:Xe.error?String(Xe.error):void 0,scores:Xe.scores,existingTags:Xe.tags.length>0?Xe.tags:void 0})),availableTags:ee.length>0?ee:void 0,prompt:V||void 0});Pe.proposedTags&&Pe.proposedTags.length>0&&(U(Pe.proposedTags.map(Xe=>({...Xe,accepted:!0}))),ne(!0))}catch(ge){console.error("Analysis failed:",ge)}finally{Q(!1)}}},[D,M,X,I,m,ee,V]),Ne=g.useCallback(()=>{for(const ge of z){if(!ge.accepted)continue;const Pe=X.find(Xe=>Xe.id===ge.itemId);if(Pe){const Xe=[...new Set([...Pe.tags,...ge.tags])];le(Pe.id,Xe)}}ne(!1)},[z,X,le]),Te=g.useCallback(ge=>{T(Pe=>Pe===ge?null:ge)},[]),ce=g.useMemo(()=>C?he.find(ge=>ge.id===C)??null:null,[C,he]),{data:ye}=JL({experimentId:ce?.experimentId??"",queryOptions:{enabled:!!ce?.experimentId}}),Se=C?he.findIndex(ge=>ge.id===C):-1,$e=Se>0?()=>T(he[Se-1].id):void 0,De=Se>=0&&Se<he.length-1?()=>T(he[Se+1].id):void 0,Qe=!P&&I.size>0,tt=!!d&&!P&&fe.length>0,st=P?"completed":"review",He=ge=>{L(ge==="completed"),T(null)},Le=a.jsxs(ar,{children:[a.jsx(ar.Start,{children:c?a.jsxs(a.Fragment,{children:[l,c({status:st,onStatusChange:He,tag:_,onTagChange:N,tagOptions:te.filter(ge=>ge.value!==H7)})]}):a.jsxs(a.Fragment,{children:[l,a.jsxs(ps,{value:st,onValueChange:ge=>He(ge==="completed"?"completed":"review"),children:[a.jsx(gs,{"aria-label":"Status",size:"md",className:"whitespace-nowrap",children:a.jsx(ms,{placeholder:"Select an option"})}),a.jsx(vs,{children:AEs.map(ge=>a.jsx(hr,{value:ge.value,children:ge.label},ge.value))})]}),te.length>1&&a.jsxs(ps,{value:_??H7,onValueChange:ge=>N(ge===H7?null:ge),children:[a.jsx(gs,{"aria-label":"Tags",size:"md",className:"whitespace-nowrap",children:a.jsx(ms,{placeholder:"Select an option"})}),a.jsx(vs,{children:te.map(ge=>a.jsx(hr,{value:ge.value,children:ge.label},ge.value))})]}),se&&a.jsx(ue,{onClick:re,size:"sm",variant:"default",icon:a.jsx(zn,{}),children:"Reset"})]})}),(Qe||u||tt)&&a.jsxs(ar.End,{children:[u,tt&&a.jsxs(ue,{size:"md",onClick:()=>d?.(fe.map(ge=>({input:ge.input,output:ge.output}))),children:[a.jsx(At,{size:"xs",children:a.jsx(tg,{})}),"Create Scorer"]}),Qe&&a.jsxs(a.Fragment,{children:[a.jsx(IEs,{size:"md",selectedCount:I.size,vocabulary:ee,onApplyTag:ze,onRemoveTag:je,onNewTag:ge=>ze(ge)}),a.jsx(ue,{variant:"primary",onClick:Ce,icon:a.jsx(vP,{}),children:"Mark as reviewed"}),a.jsxs(ct,{children:[a.jsx(ct.Trigger,{asChild:!0,children:a.jsx(ue,{disabled:F,"aria-label":"More actions",children:F?a.jsx(_n,{className:"h-4 w-4"}):a.jsx(TN,{})})}),a.jsxs(ct.Content,{align:"end",children:[a.jsxs(ct.Item,{onSelect:ae,children:[a.jsx(At,{size:"xs",children:a.jsx(tG,{})}),"Analyze"]}),a.jsx(ct.Separator,{}),a.jsxs(ct.Item,{onSelect:Ue,children:[a.jsx(At,{size:"xs",children:a.jsx(Xo,{})}),"Remove from queue"]})]})]})]})]})]});if(b)return a.jsxs(It,{breadcrumbs:f,actionRow:Le,children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(_n,{fill:!0})]});const wt=a.jsx(hqt,{withQueryTrace:h,withFeedback:p,result:ce??void 0,title:`Review item ${ce?.id??""}`,scores:ce?ye?.[ce.itemId]:void 0,experimentLink:ce?.experimentId?v.experimentItemLink(ce.experimentId,ce.itemId):void 0,tagVocabulary:ee,onTagsChange:P||!ce?void 0:ge=>{le(ce.id,ge);for(const Pe of ge)ee.includes(Pe)||ie(Pe)},onComplete:P||!ce?void 0:()=>ve(ce.id),onPrevious:$e,onNext:De,onClose:()=>T(null)});return a.jsxs(It,{breadcrumbs:f,actionRow:Le,children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(Kr,{open:q,onOpenChange:B,children:a.jsxs(Yr,{children:[a.jsxs(Xr,{children:[a.jsx(Qr,{children:"Analyze Items"}),a.jsx(Lo,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),a.jsxs(qr,{children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs(ht,{className:"gap-1",children:[a.jsx(ut,{children:"Provider"}),a.jsx(Mk,{value:D,onValueChange:K})]}),a.jsxs(ht,{className:"gap-1",children:[a.jsx(ut,{children:"Model"}),a.jsx(Dk,{llmId:D,value:M,onValueChange:$})]})]}),a.jsxs(Y,{variant:"meta",tone:"muted",children:[I.size," item",I.size!==1?"s":""," will be analyzed"]}),a.jsxs(ht,{className:"gap-1",children:[a.jsx(ut,{children:"Instructions (optional)"}),a.jsx(Pu,{className:"text-caption",value:V,onChange:ge=>H(ge.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3})]})]}),a.jsxs(Yo,{children:[a.jsx(Ca,{children:"Cancel"}),a.jsx(ja,{onConfirm:me,disabled:!D||!M||F,children:"Analyze"})]})]})}),a.jsx(Kr,{open:G,onOpenChange:ne,children:a.jsxs(Yr,{size:"lg",children:[a.jsxs(Xr,{children:[a.jsx(Qr,{children:"Review Proposed Tags"}),a.jsxs(Lo,{children:[z.filter(ge=>ge.accepted).length," of ",z.length," proposals selected"]})]}),a.jsx(qr,{children:z.map((ge,Pe)=>{const Xe=X.find(St=>St.id===ge.itemId);return a.jsx("div",{className:Z("rounded-lg border p-3",!ge.accepted&&"opacity-50"),children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Gc,{checked:ge.accepted,onCheckedChange:St=>U(Ft=>Ft.map((qt,yt)=>yt===Pe?{...qt,accepted:!!St}:qt))}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"block truncate",children:Xe?typeof Xe.input=="string"?Xe.input.slice(0,100):JSON.stringify(Xe.input).slice(0,100):ge.itemId}),a.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:ge.tags.map((St,Ft)=>a.jsx(EEs,{tag:St,onRename:qt=>U(yt=>yt.map((xn,vn)=>vn===Pe?{...xn,tags:xn.tags.map((we,Ie)=>Ie===Ft?qt:we)}:xn)),onRemove:()=>U(qt=>qt.map((yt,xn)=>xn===Pe?{...yt,tags:yt.tags.filter((vn,we)=>we!==Ft)}:yt))},`${St}-${Ft}`))}),ge.reason&&a.jsx(Y,{variant:"meta",tone:"muted",className:"mt-1 block italic",children:ge.reason})]})]})},ge.itemId)})}),a.jsxs(Yo,{children:[a.jsx(Ca,{children:"Cancel"}),a.jsxs(ja,{onConfirm:Ne,disabled:z.filter(ge=>ge.accepted).length===0,children:["Accept ",z.filter(ge=>ge.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:ke?a.jsx(_n,{fill:!0}):he.length===0?a.jsx(Xt,{titleSlot:P?"No completed reviews yet":"No items to review",descriptionSlot:P?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here.",variant:"fill"}):a.jsx(tqt,{results:he,isLoading:!1,featuredResultId:C,onResultClick:Te,columns:NEs,selectedIds:P?void 0:I,onToggleSelect:P?void 0:Fe,onToggleSelectAll:P?void 0:Ae})}),wt]})]})}const DAe="experiment",LAe="status",zAe="tag",$Es=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}],REs=[{id:"is",label:"is"}],MEs=({targetType:e,targetId:t,experimentId:n,status:r,tag:s})=>{const i=aAe({targetType:e,targetId:t});return n&&i.push(uv(DAe,n)),r!=="review"&&i.push(uv(LAe,r)),s&&i.push(uv(zAe,s)),i},DEs=e=>({...lAe(e),experimentId:dv(e,DAe),status:dv(e,LAe)==="completed"?"completed":"review",tag:dv(e,zAe)||null});function LEs({targetType:e,targetId:t,experimentId:n,status:r,tag:s,experiments:i,tagOptions:o,onChange:l}){const c=cAe(e),u=g.useMemo(()=>[...c,{id:DAe,label:"Experiment",icon:lL,color:m0("pink"),strict:!0,suggestions:i.map(f=>({value:f.id,label:oqt(f)}))},{id:LAe,label:"Status",icon:vP,color:m0("orange"),strict:!0,suggestions:$Es},{id:zAe,label:"Tag",icon:Nx,color:m0("pink"),strict:!0,hidden:o.length===0,suggestions:o}],[c,i,o]),d=g.useMemo(()=>MEs({targetType:e,targetId:t,experimentId:n,status:r,tag:s}),[e,t,n,r,s]);return a.jsxs(wu,{fields:u,operators:REs,value:d,onValueChange:f=>l(DEs(f)),createItemId:f=>f,"aria-label":"Review queue filters",className:"min-w-64 flex-1",children:[a.jsx(wu.Chips,{}),a.jsx(wu.Input,{placeholder:"Filter review queue…"})]})}const G7=[Ts("/experiments"),Ts("/experiments/review-queue")],Sue="experiment",ynt="review";function zEs(){const[e,t]=ci(),n=e.get(x0),r=XJ(n)?n:"",s=r?e.get(Yy)??"":"",i=e.get(Sue),o=e.get(ynt),{Link:l,paths:c}=Tn(),u=GJ(),{data:d,error:f}=KVt({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(x0,m.targetType):x.delete(x0),j?x.set(Yy,j):x.delete(Yy),k?x.set(Sue,k):x.delete(Sue),x.delete(ynt),x},{replace:!0})};return f&&Cs(f)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:G7}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(ui,{variant:"fill"})]}):f&&_s(f)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:G7}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(Gs,{variant:"fill",resource:"experiments"})]}):f?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:G7}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(Xt,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:f.message})]}):a.jsx(PEs,{withQueryTrace:u.enabled,withFeedback:u.enabled,breadcrumbs:a.jsx(Dt,{crumbs:G7}),datasetId:h?.datasetId??void 0,experimentId:i??void 0,targetType:r,targetId:s,featuredItemId:o,renderFilters:m=>a.jsx(LEs,{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(ue,{render:a.jsx(l,{href:c.experimentLink(i)}),icon:a.jsx(G0e,{}),children:"See experiment"}):void 0})}function FEs({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 Gqt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return a.jsx("ul",{className:"space-y-1",children:e.map(s=>a.jsx(FEs,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function BEs({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(Gqt,{connections:i,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function UEs({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(BEs,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):a.jsx(Gqt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?a.jsx("p",{className:"text-destructive-foreground",children:String(c)}):null]})}function VEs({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(ht,{invalid:!!o,disabled:i,children:[a.jsx(ut,{children:"Provider"}),a.jsxs(ps,{value:n,onValueChange:h,children:[a.jsx(gs,{children:a.jsx(ms,{placeholder:i?"Loading providers…":"Select provider"})}),a.jsx(vs,{children:e.map(y=>a.jsx(hr,{value:y.id,children:`${y.displayName??y.name} (${y.id})`},y.id))})]}),a.jsx(ns,{children:o?String(o):void 0})]}),a.jsxs(ht,{invalid:!!c,disabled:!n||l,children:[a.jsx(ut,{children:"Toolkit"}),a.jsxs(ps,{value:r,onValueChange:p,children:[a.jsx(gs,{children:a.jsx(ms,{placeholder:l?"Loading toolkits…":"Select toolkit"})}),a.jsx(vs,{children:t.map(y=>a.jsx(hr,{value:y.slug,children:`${y.name} (${y.slug})`},y.slug))})]}),a.jsx(ns,{children:c?String(c):void 0})]}),a.jsxs(ht,{disabled:!n||!r,children:[a.jsx(ut,{children:"Label (optional)"}),a.jsx(wn,{placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value)})]}),a.jsx(ue,{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 xnt=e=>e.authorId?.trim()||"shared",qEs=(e,t)=>{if(!t||new Set(e.map(xnt)).size<=1)return null;const r=new Map;for(const i of e){const o=xnt(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},QEs=["*","tool-providers:*","tool-providers:admin"];function ZEs(){const{data:e}=Xm();return e?.permissions?.some(t=>QEs.includes(t))??!1}const WEs=[{id:"integrations",label:"Integrations"}];function HEs(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,i]=g.useState(""),o=r$(),l=eX({providerId:e||null,queryOptions:{enabled:!!e}}),c=$$t({providerId:e||null,toolkit:n||null}),u=A$t(),d=P$t(),f=ZEs(),h=o.data?.providers??[],p=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>qEs(m,f),[m,f]),y=S=>{t(S),r("")},x=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{i(""),c.refetch()}})},b=S=>{d.mutate({providerId:e,connectionId:S})};return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:WEs}),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(VEs,{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(UEs,{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 GEs({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(D0,{className:"h-10 w-10"}),a.jsx(Y,{as:"h1",variant:"heading",tone:"ink",children:e})]}),t,n,r]})}function Kqt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:i}=Ql(),{mutate:o,isPending:l,error:c}=mwn(),{mutate:u,isPending:d,error:f}=vwn(),{mutate:h,isPending:p}=udt(),[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,A=m==="signin"||!I,P=A?l:d,L=A?c:f,F=()=>{t?t():e?window.location.href=e:window.location.href=kX("/")},Q=D=>{D.preventDefault(),A?o({email:b,password:k},{onSuccess:F}):u({email:b,password:k,name:y||void 0},{onSuccess:F})},q=()=>{h({redirectUri:e},{onSuccess:D=>{window.location.href=D.url}})},B=()=>{v(A?"signup":"signin")},V=C.description?a.jsxs("div",{className:"flex items-start gap-2.5 rounded-md border border-border bg-sidebar p-3",children:[a.jsx(Au,{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(GEs,{title:A?"Sign in to Mastra Studio":"Create your account",description:V,errorBanner:H,children:[_&&a.jsxs(Ga,{onSubmit:Q,children:[!A&&a.jsxs(ht,{children:[a.jsx(ut,{children:"Name"}),a.jsx(wn,{name:"name",type:"text",autoComplete:"name",value:y,onChange:D=>x(D.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),a.jsxs(ht,{children:[a.jsx(ut,{required:!0,children:"Email"}),a.jsx(wn,{name:"email",type:"email",autoComplete:"email",value:b,onChange:D=>S(D.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"}),a.jsx(ns,{})]}),a.jsxs(ht,{children:[a.jsx(ut,{required:!0,children:"Password"}),a.jsx(wn,{name:"password",type:"password",autoComplete:A?"current-password":"new-password",value:k,onChange:D=>j(D.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"}),a.jsx(ns,{})]}),L?a.jsx("div",{role:"alert",children:a.jsx(Wt,{variant:"destructive",children:L.message})}):null,a.jsx(ue,{icon:a.jsx(owe,{}),type:"submit",disabled:P,className:"w-full",size:"lg",children:P?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),I&&a.jsxs("div",{className:"text-center",children:[a.jsx(Y,{as:"span",variant:"body",tone:"muted",children:A?"Don't have an account? ":"Already have an account? "}),a.jsx("button",{type:"button",onClick:B,className:"text-foreground hover:underline",children:a.jsx(Y,{as:"span",variant:"body",className:"block",children:A?"Sign up":"Sign in"})})]})]}),T&&_&&a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"absolute inset-0 flex items-center",children:a.jsx("div",{className:"w-full border-t border-border"})}),a.jsx("div",{className:"relative flex justify-center",children:a.jsx(Y,{as:"span",variant:"body",tone:"muted",className:"bg-sidebar px-2",children:"or continue with"})})]}),T&&N&&a.jsxs(ue,{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 KEs(){const[e]=ci(),t=Dr(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",i=e.get("error_description")||e.get("error")||null,o=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return a.jsx(Kqt,{redirectUri:n,onSuccess:o,initialMode:s,errorMessage:i})}function Yqt({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(ue,{disabled:e,size:"md",onClick:t,icon:a.jsx(zn,{}),children:"Clear"}),i&&a.jsxs(ct,{children:[a.jsx(ct.Trigger,{asChild:!0,children:a.jsx(ue,{disabled:e,size:"md","aria-label":"More filter actions",children:a.jsx(Q0,{})})}),a.jsxs(ct.Content,{align:"end",children:[n&&a.jsxs(ct.Item,{onSelect:()=>n(),children:[a.jsx(zn,{}),"Remove all filters"]}),n&&(r||s)&&a.jsx(ct.Separator,{}),r&&a.jsxs(ct.Item,{onSelect:()=>r(),children:[a.jsx(Fm,{}),"Save filters for next time"]}),s&&a.jsxs(ct.Item,{onSelect:()=>s(),children:[a.jsx(Xo,{}),"Remove saved filters"]})]})]})]})}const YEs=Z(ag,"min-w-0 focus:text-foreground");function kue({role:e,checked:t,label:n,onClick:r}){return a.jsxs("button",{ref:Du(),type:"button",role:e,"aria-checked":t,"data-selected":t||void 0,"data-pick-multi-item":"",title:n,className:YEs,onClick:r,children:[a.jsx("span",{className:"min-w-0 flex-1 truncate",children:n}),t&&a.jsx("span",{className:$_,children:a.jsx(ur,{})})]})}function Xqt({field:e,tokens:t,onChange:n}){const[r,s]=g.useState(""),i=Bv(),o={className:Z("max-h-[80dvh] overflow-auto p-1",i.containerClassName),...i.getContainerProps({})},l=g.useMemo(()=>{const f=r.trim().toLowerCase();return f?e.options.filter(h=>h.label.toLowerCase().includes(f)):e.options},[e.options,r]),c=g.useMemo(()=>t.find(f=>f.fieldId===e.id),[t,e.id]),u=typeof c?.value=="string"?c.value:e.multi?void 0:e.defaultValue,d=g.useMemo(()=>{const f=c?.value;return Array.isArray(f)?f:typeof f=="string"?[f]:[]},[c]);return a.jsxs(a.Fragment,{children:[e.searchable!==!1&&a.jsxs("div",{className:RI.container,children:[a.jsx(Su,{className:RI.icon}),a.jsx("input",{type:"text",value:r,onChange:f=>s(f.target.value),placeholder:`Search ${e.label.toLowerCase()}...`,className:RI.input,...mp,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(lQ,"m-1"),children:[a.jsx(_n,{size:"sm",className:"size-3 text-muted-foreground"}),"Loading options…"]}):l.length===0?a.jsx("div",{className:Z(lQ,"m-1"),children:e.emptyText??"No option found."}):e.multi?a.jsx("div",{...o,children:a.jsx(Um,{menu:i,children:l.map(f=>{const h=d.includes(f.value);return a.jsx(kue,{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(Um,{menu:i,children:[l.map(f=>a.jsx(kue,{role:"radio",checked:u===f.value,label:f.label,onClick:()=>n(e.id,f.value)},f.value)),!e.omitAnyOption&&a.jsx(kue,{role:"radio",checked:u==="Any",label:"Any",onClick:()=>n(e.id,"Any")})]})})]})}function FAe(e){return Array.isArray(e)?e.length===0?"Any":e.join(", "):e}const XEs="This filter is set by the current context and cannot be removed here.";function JEs(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:FAe(t)}function eIs({field:e,value:t,tooltipContent:n}){const r=JEs(e,t),s=`${e.label} filter is locked by context`;return a.jsx(mc,{delayDuration:150,children:a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsxs(pc,{"data-locked-field-id":e.id,"data-property-filter-pill":"locked",tabIndex:0,"aria-label":s,children:[a.jsx(vm,{children:e.label}),a.jsx(vm,{children:"is"}),a.jsx(vm,{children:r}),a.jsx(vm,{children:a.jsx(Au,{})})]})}),a.jsx(Dn,{children:n})]})})}function tIs({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(pc,{children:[a.jsx(vm,{children:e.label}),a.jsx(vm,{children:"is"}),a.jsx(wn,{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(ue,{type:"button",disabled:s,"aria-label":`Remove ${e.label} filter`,onMouseDown:u=>u.preventDefault(),onClick:r,children:a.jsx(zn,{})})]})}function nIs({field:e,token:t,tokens:n,onChange:r,onRemove:s,disabled:i}){const[o,l]=g.useState(!1);return a.jsxs(pc,{children:[a.jsx(vm,{children:e.label}),a.jsx(vm,{children:"is"}),a.jsxs(jp,{open:o,onOpenChange:l,children:[a.jsx(sf,{asChild:!0,children:a.jsx(ue,{type:"button",disabled:i,children:FAe(t.value)})}),a.jsx(lh,{align:"start",sideOffset:R_,className:"w-64 p-0","data-pick-multi-panel":!0,children:a.jsx(Xqt,{field:e,tokens:n,onChange:r})})]}),a.jsx(ue,{type:"button",disabled:i,"aria-label":`Remove ${e.label} filter`,onClick:s,children:a.jsx(zn,{})})]})}function Jqt({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:s,lockedFieldIds:i,lockedTooltipContent:o=XEs}){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(eIs,{field:h,value:d.value,tooltipContent:o},`${d.fieldId}-${f}`):h.kind==="text"&&!Array.isArray(d.value)?a.jsx(tIs,{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(nIs,{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(pc,{children:[a.jsx(vm,{children:h.label}),a.jsx(vm,{children:"is"}),a.jsx(vm,{children:FAe(d.value)}),a.jsx(ue,{type:"button",disabled:r,"aria-label":`Remove ${h.label} filter`,onClick:()=>u(f),children:a.jsx(zn,{})})]},`${d.fieldId}-${f}`):null})})}const eQt=Z(ag,"focus:text-foreground"),BAe=g.forwardRef((e,t)=>a.jsx("button",{type:"button",role:"menuitem","data-filter-item":"",ref:Du(t),...e}));BAe.displayName="FilterMenuButton";function tQt({fields:e,tokens:t,onTokensChange:n,label:r="Add Filter",disabled:s,size:i,onStartTextFilter:o,hiddenFieldIds:l}){const c=g.useMemo(()=>{if(!l||l.length===0)return e;const P=new Set(l);return e.filter(L=>!P.has(L.id))},[e,l]),[u,d]=g.useState(!1),f=Bv(),[h,p]=g.useState(),[m,v]=g.useState([]),[y,x]=g.useState(),[b,S]=g.useState(),k=g.useRef(!1),j=g.useCallback(P=>{S(L=>L===P?void 0:P)},[]),C=g.useCallback(()=>S(void 0),[]);g.useEffect(()=>{u||S(void 0)},[u]);const T=g.useMemo(()=>c.find(P=>P.id===h),[c,h]),_=g.useMemo(()=>{const P=new Set;for(const L of t){const F=e.find(Q=>Q.id===L.fieldId);F&&F.kind!=="pick-multi"&&P.add(L.fieldId)}return P},[t,e]),N=g.useCallback(()=>{p(void 0),v([]),x(void 0)},[]);g.useEffect(()=>{u||N()},[u,N]);const I=g.useCallback((P,L)=>{const F=t.findIndex(q=>q.fieldId===P);if(Array.isArray(L)&&L.length===0){if(F===-1)return;n(t.filter((q,B)=>B!==F));return}if(F===-1){n([...t,{fieldId:P,value:L}]);return}const Q=[...t];Q[F]={fieldId:P,value:L},n(Q)},[n,t]),A=g.useCallback(()=>{if(!T){x("Choose a property first.");return}if(_.has(T.id)){x(`Remove the existing ${T.label} filter before adding another.`);return}if(m.length===0){x(`Choose at least one ${T.label.toLowerCase()} value.`);return}n([...t,{fieldId:T.id,value:m}]),d(!1)},[m,n,T,_,t]);return a.jsxs(jp,{open:u,onOpenChange:d,children:[a.jsx(sf,{asChild:!0,children:a.jsx(ue,{size:i,disabled:s,icon:a.jsx(_6e,{}),children:r})}),a.jsx(lh,{align:"end",sideOffset:R_,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(Ln,On),onClick:N,children:a.jsx(vd,{className:"size-4"})}),a.jsx(tEn,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:`${T.label} · is`})]}),!T&&a.jsx("div",{role:"menu",className:Z("max-h-[80dvh] overflow-auto",f.containerClassName),...f.getContainerProps({}),onKeyDown:P=>{if(P.key!=="ArrowDown"&&P.key!=="ArrowUp"&&P.key!=="Home"&&P.key!=="End")return;const L=Array.from(P.currentTarget.querySelectorAll("[data-filter-item]:not([disabled])"));if(L.length===0)return;P.preventDefault();const F=document.activeElement,Q=L.findIndex(B=>B===F);let q;P.key==="Home"?q=0:P.key==="End"?q=L.length-1:P.key==="ArrowDown"?q=Q<0?0:(Q+1)%L.length:q=Q<=0?L.length-1:Q-1,L[q]?.focus()},children:a.jsx(Um,{menu:f,children:c.length>0?c.map(P=>{const L=_.has(P.id);return P.kind==="pick-multi"?a.jsx(rIs,{field:P,tokens:t,onChange:I,open:b===P.id,onToggle:j,onClose:C},P.id):a.jsxs(BAe,{className:Z(eQt,"group"),disabled:L,onClick:()=>{if(x(void 0),P.kind==="text"){n([...t,{fieldId:P.id,value:""}]),o?.(P.id),k.current=!0,d(!1);return}p(P.id)},children:[a.jsx("span",{className:"truncate",children:P.label}),L?a.jsx("span",{className:"ml-auto text-muted-foreground",children:"In use"}):a.jsx("span",{className:Z(zL,"text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 group-focus:opacity-100"),children:a.jsx(ys,{})})]},P.id)}):a.jsx("div",{className:lQ,children:"No matching property."})})}),T&&a.jsxs(ht,{invalid:!!y,children:[a.jsx(fl,{multiple:!0,options:T.options??[],value:m,onValueChange:P=>{v(P),x(void 0)},placeholder:T.placeholder??`Choose ${T.label}`,searchPlaceholder:`Search ${T.label.toLowerCase()}...`,emptyText:T.emptyText??"No option found.",size:"md","aria-label":T.label}),a.jsx(ns,{children:y})]}),T&&a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.jsx(ue,{icon:a.jsx(zn,{}),variant:"ghost",size:"md",onClick:()=>d(!1),children:"Cancel"}),a.jsx(ue,{icon:a.jsx(_6e,{}),size:"md",onClick:A,children:"Add filter"})]})]})})]})}function rIs({field:e,tokens:t,onChange:n,open:r,onToggle:s,onClose:i}){const o=g.useRef(null);return a.jsxs(jp,{open:r,onOpenChange:l=>{l?s(e.id):i()},children:[a.jsx(sf,{asChild:!0,children:a.jsxs(BAe,{className:eQt,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(Dc,{className:"text-muted-foreground"}),a.jsx("span",{className:"truncate",children:e.label}),!r&&a.jsx("span",{className:Z(zL,"text-muted-foreground"),children:a.jsx(Dc,{})})]})}),a.jsx(lh,{ref:o,side:"right",align:"start",sideOffset:R_,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(Xqt,{field:e,tokens:t,onChange:n})})]})}function sIs({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:i,depth:o}){const l=e?$C(e.timestamp)??"":"";return a.jsx(Tt,{open:!!e,onClose:t,title:e?`Log ${l}`:"Log",depth:o,children:e&&a.jsxs(a.Fragment,{children:[a.jsxs(Tt.Header,{children:[a.jsx(Tt.CloseButton,{onClick:t}),a.jsxs(Tt.Heading,{children:["Log · ",l]}),a.jsx(Tt.HeaderActions,{children:a.jsx(Tt.NextPrevNav,{onPrevious:s,onNext:i,previousLabel:"Go to previous log",nextLabel:"Go to next log"})})]}),a.jsx(Tt.Content,{children:a.jsxs("div",{className:"grid gap-6 p-2",children:[a.jsxs(Kt,{children:[e.entityType&&a.jsxs(a.Fragment,{children:[a.jsx(Kt.Key,{children:"Entity Type"}),a.jsx(Kt.Value,{children:e.entityType})]}),e.entityName&&a.jsxs(a.Fragment,{children:[a.jsx(Kt.Key,{children:"Entity Name"}),a.jsx(Kt.Value,{children:e.entityName})]}),e.serviceName&&a.jsxs(a.Fragment,{children:[a.jsx(Kt.Key,{children:"Service"}),a.jsx(Kt.Value,{children:e.serviceName})]}),e.environment&&a.jsxs(a.Fragment,{children:[a.jsx(Kt.Key,{children:"Environment"}),a.jsx(Kt.Value,{children:e.environment})]}),e.source&&a.jsxs(a.Fragment,{children:[a.jsx(Kt.Key,{children:"Source"}),a.jsx(Kt.Value,{children:e.source})]}),e.metadata&&Object.entries(e.metadata).map(([c,u])=>a.jsxs(g.Fragment,{children:[a.jsx(Kt.Key,{children:c}),a.jsx(Kt.Value,{children:String(u)})]},c))]}),a.jsx(Tt.CodeSection,{title:"Message",codeStr:e.message,simplified:!0}),(e.traceId||e.spanId)&&a.jsxs("div",{className:"grid gap-2",children:[e.traceId&&a.jsxs(pc,{className:"w-full min-w-0",children:[a.jsxs(ue,{className:"min-w-0 flex-1 justify-between overflow-hidden",icon:a.jsx(dp,{}),onClick:()=>e.traceId&&n?.(e.traceId),children:[a.jsx("span",{children:"Trace"}),a.jsxs(Y,{as:"span",variant:"caption",tone:"faint",className:"ml-auto min-w-0 truncate",children:["# ",e.traceId]})]}),a.jsx(ii,{content:e.traceId,tooltip:"Copy Trace ID to clipboard"})]}),e.spanId&&a.jsxs(pc,{className:"w-full min-w-0",children:[a.jsxs(ue,{className:"min-w-0 flex-1 justify-between overflow-hidden",disabled:!e.traceId||!r,onClick:()=>e.traceId&&e.spanId&&r?.(e.traceId,e.spanId),icon:a.jsx(dp,{}),children:[a.jsx("span",{children:"Span"}),a.jsxs(Y,{as:"span",variant:"caption",tone:"faint",className:"ml-auto min-w-0 truncate",children:["# ",e.spanId]})]}),a.jsx(ii,{content:e.spanId,tooltip:"Copy Span ID to clipboard"})]})]}),e.data&&Object.keys(e.data).length>0&&a.jsx(Tt.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2)})]})})]})})}function iIs({error:e,resource:t,errorTitle:n}){if(Cs(e))return a.jsx(ui,{});if(_s(e))return a.jsx(Gs,{resource:t});if(t6(e))return a.jsx(Xt,{titleSlot:"Observability storage is not available",descriptionSlot:"The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio."});if(e6(e,"logs"))return a.jsx(Xt,{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(Xt,{tone:"error",titleSlot:n,descriptionSlot:r??"Unknown error"})}const oIs={debug:"neutral",info:"info",warn:"warning",error:"destructive",fatal:"destructive"};function aIs({level:e}){return a.jsx(ma,{children:a.jsx(Mt,{variant:oIs[e],children:e})})}function lIs({entityType:e,className:t}){const n=Z("size-3.5 shrink-0 text-placeholder",t);switch(e.toLowerCase()){case"agent":return a.jsx(Uo,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return a.jsx(Ol,{className:n,"aria-hidden":!0});case"tool":return a.jsx(fd,{className:n,"aria-hidden":!0});default:return null}}function cIs({entityType:e,entityName:t}){const n=e??"";return a.jsxs(ma,{className:"flex min-w-0 items-center gap-2",children:[a.jsx(lIs,{entityType:n}),t?a.jsx(Y,{as:"span",variant:"body-sm",className:"min-w-0 truncate",children:t}):"-"]})}function uIs({message:e}){return a.jsx(ma,{className:"min-w-0 truncate font-mono text-body-sm text-muted-foreground",children:e})}function dIs({data:e}){if(!e||Object.keys(e).length===0)return a.jsx(ma,{children:null});const t=Object.entries(e).map(([n,r])=>{if(typeof r=="string")return`${n}: ${r}`;try{return`${n}: ${JSON.stringify(r)}`}catch{return`${n}: <unserializable>`}}).join(", ");return a.jsx(vCe,{font:"mono",children:t})}const $l=Object.assign(T6,{Top:I6,TopCell:cw,SortableTopCell:GY,TopCellWithTooltip:HY,TopCellSmart:OAt,RowWrapper:wCe,RowButton:E6,RowLink:bCe,Spacer:SCe,NoMatch:WY,DateCell:pAt,TimeCell:gAt,LevelCell:aIs,EntityCell:cIs,MessageCell:uIs,DataCell:dIs,NextPageLoading:ZY}),bnt="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",fIs=36,hIs=8;function pIs({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=eVt({count:e.length,getScrollElement:()=>d.current,estimateSize:()=>fIs,overscan:hIs}),{getRowProps:h}=Fu({count:e.length,containerRef:d,onNavigate:b=>f.scrollToIndex(b),global:!0}),p=g.useRef(t);if(g.useEffect(()=>{p.current&&!t&&d.current?.dispatchEvent(new Event("scroll")),p.current=t},[t]),t)return a.jsx(Lu,{columns:bnt,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($l,{columns:bnt,scrollRef:d,className:"min-w-0",fit:"container",children:[a.jsxs($l.Top,{children:[u?a.jsx($l.SortableTopCell,{sortKey:"timestamp",sort:c,onSortChange:u,children:"Date"}):a.jsx($l.TopCell,{children:"Date"}),a.jsx($l.TopCell,{children:"Time"}),a.jsx($l.TopCell,{children:"Level"}),a.jsx($l.TopCell,{children:"Entity"}),a.jsx($l.TopCell,{children:"Message"}),a.jsx($l.TopCell,{children:"Data"})]}),e.length===0?a.jsx($l.NoMatch,{message:"No logs match your search"}):a.jsxs(a.Fragment,{children:[a.jsx($l.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($l.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($l.DateCell,{timestamp:S.timestamp}),a.jsx($l.TimeCell,{timestamp:S.timestamp}),a.jsx($l.LevelCell,{level:S.level}),a.jsx($l.EntityCell,{entityType:S.entityType,entityName:S.entityName}),a.jsx($l.MessageCell,{message:S.message}),a.jsx($l.DataCell,{data:S.data})]},k)}),a.jsx($l.Spacer,{height:x})]}),a.jsx($l.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function mIs({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=>gIs(f,i));return u?a.jsxs("div",{className:Z("grid grid-cols-[1fr_auto] items-start gap-3"),children:[a.jsx(Jqt,{fields:i,tokens:o,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&a.jsx(Yqt,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function gIs(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 vIs={"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"},Oue="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function yIs({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${vIs[e]}`,description:Oue}:t&&n?{title:`No logs between ${Jr(t,"date-time")} and ${Jr(n,"date-time")}`,description:Oue}:t?{title:`No logs since ${Jr(t,"date-time")}`,description:Oue}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const xIs=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=yIs({datePreset:e,dateFrom:t,dateTo:n});return a.jsx(Xt,{titleSlot:r,descriptionSlot:s,actionSlot:a.jsx(ue,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Logging Documentation"}),variant:"fill"})},K7={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},nQt=[{label:"Agent",entityType:K7.AGENT},{label:"Workflow",entityType:K7.WORKFLOW},{label:"Scorer",entityType:K7.SCORER},{label:"Ingest",entityType:K7.INGEST}],bIs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],B0="rootEntityType",Zb="datePreset",Wb="dateFrom",Hb="dateTo",wIs=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Ml={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"},Dz=Object.keys(Ml),UAe=new Set(["tags"]),VAe="mastra:logs:saved-filters";function SIs(e,t=VAe){const n=_Is(e),r=e.get(Zb);r&&n.set(Zb,r);const s=e.get(Wb);s&&n.set(Wb,s);const i=e.get(Hb);i&&n.set(Hb,i);try{localStorage.setItem(t,n.toString())}catch{}}function kIs(e=VAe){try{localStorage.removeItem(e)}catch{}}function wnt(e=VAe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function OIs(e){if(e.has(Zb)||e.has(Wb)||e.has(Hb)||e.has(B0))return!0;for(const t of Dz)if(e.has(Ml[t]))return!0;return!1}function jIs({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const i=[{id:"rootEntityType",label:"Primitive type",kind:"pick-multi",searchable:!1,options:nQt.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:bIs.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 CIs(e){const t=[],n=new Map([[B0,"rootEntityType"]]);for(const s of Dz)n.set(Ml[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),UAe.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 _Is(e){const t=new URLSearchParams,n=e.get(B0);n&&t.set(B0,n);for(const r of Dz){const s=Ml[r];if(UAe.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 TIs(e,t){e.delete(B0);for(const n of Dz)e.delete(Ml[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(B0,n.value);continue}const r=Ml[n.fieldId];if(r){if(UAe.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 EIs({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 IIs(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 NIs="Filters setting for Logs saved",AIs="Filters setting for Logs cleared up";function PIs(e,t,n){const{storageKey:r,messages:s,skipHydration:i}={},[o,l]=g.useState(()=>wnt(r)!==null),c=g.useCallback(()=>{SIs(e,r),l(!0);const f=s?.saved??NIs;f!==!1&&Ye.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{kIs(r),l(!1);const f=s?.cleared??AIs;f!==!1&&Ye.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(i||d.current||(d.current=!0,OIs(e)))return;const f=wnt(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 $Is(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 RIs(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,$Is(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function MIs(e,t,n,r){const s=g.useMemo(()=>RIs(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 Hye="logId",Gye="traceId",Kye="spanId",LM=1440*60*1e3,DIs={"last-24h":LM,"last-3d":3*LM,"last-7d":7*LM,"last-14d":14*LM,"last-30d":30*LM};function Y7(e){e.delete(Hye),e.delete(Gye),e.delete(Kye)}function LIs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const j=e.get(Zb);return j&&wIs.has(j)?j:"last-24h"},[e]),i=e.get(Wb),o=e.get(Hb),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=DIs[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(Hye),f=e.get(Gye),h=e.get(Kye),p=g.useMemo(()=>nQt.find(j=>j.entityType===e.get(B0)),[e]),m=g.useMemo(()=>CIs(e),[e]),v=g.useCallback(j=>{t(C=>{const T=new URLSearchParams(C);for(const[_,N]of Object.entries(j)){const I=_==="logId"?Hye:_==="traceId"?Gye:Kye;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 TIs(T,j),Y7(T),T},{replace:!0})},[t]),x=y,b=g.useCallback((j,C)=>{if(u.current!=="custom")return;const T=C==="from"?Wb:Hb;t(_=>{const N=new URLSearchParams(_);return j?N.set(T,j.toISOString()):N.delete(T),Y7(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(Zb),T.delete(Wb),T.delete(Hb)):j==="custom"?T.set(Zb,"custom"):(T.set(Zb,j),T.delete(Wb),T.delete(Hb)),Y7(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(j=>{const C=new URLSearchParams(j);C.delete(B0);for(const T of Dz)C.delete(Ml[T]);return C.delete(Zb),C.delete(Wb),C.delete(Hb),Y7(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 zIs=20,FIs=1e4,BIs={field:"timestamp",direction:"DESC"};function UIs(e,t,n){if(e?.pagination?.hasMore)return n+1}function VIs(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 qIs(e){return e6(e.state.error,"logs")||t6(e.state.error)?!1:FIs}const QIs=({filters:e,orderBy:t=BIs,queryOptions:n}={})=>{const r=Ge(),{inView:s,setRef:i}=K0(),{hasNextPage:o,isFetchingNextPage:l,fetchNextPage:c,data:u,isLoading:d,isError:f,error:h}=Dm({queryKey:["logs",e,t],queryFn:({pageParam:p})=>r.listLogsVNext({pagination:{page:p,perPage:zIs},filters:e,orderBy:t}),initialPageParam:0,getNextPageParam:UIs,select:VIs,retry:!1,refetchInterval:qIs,...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}},jue=[Ts("/logs")],ZIs=["timestamp"],WIs={key:"timestamp",direction:"desc"};function HIs(){const[e,t]=ci(),n=Dr(),r=LIs(e,t),s=GJ(),{sort:i,onSortChange:o}=Hk({searchParams:e,setSearchParams:t,allowedKeys:ZIs,defaultSort:WIs}),l=g.useMemo(()=>({field:"timestamp",direction:i?.direction==="asc"?"ASC":"DESC"}),[i?.direction]),c=PIs(e,t),[u,d]=g.useState(),{data:f=[],isPending:h}=kBt(),{data:p=[],isPending:m}=ONe({entityType:r.selectedEntityOption?.entityType,rootOnly:!0}),{data:v=[],isPending:y}=jNe(),{data:x=[],isPending:b}=SBt(),S=g.useMemo(()=>jIs({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(()=>EIs({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}=QIs({filters:k,orderBy:l}),{logIdMap:A,featuredLog:P,handleLogClick:L,handlePreviousLog:F,handleNextLog:Q}=MIs(j,r.featuredLogId,r.handleFeaturedChange,r.featuredTraceId),{data:q,isLoading:B}=oT({traceId:r.featuredTraceId??null,queryOptions:{enabled:!!r.featuredTraceId}}),V=g.useCallback(()=>r.applyFilterTokens(IIs(S,r.filterTokens)),[S,r]),H=g.useCallback(()=>r.handleFeaturedChange({logId:null}),[r]),D=g.useCallback(G=>r.handleFeaturedChange({traceId:G,spanId:null}),[r]),K=g.useCallback((G,ne)=>r.handleFeaturedChange({traceId:G,spanId:ne}),[r]),M=g.useCallback(()=>r.handleFeaturedChange({traceId:null,spanId:null}),[r]),$=g.useCallback(G=>r.handleFeaturedChange({spanId:G??null}),[r]),z=a.jsxs(a.Fragment,{children:[a.jsx(ar,{children:a.jsxs(ar.Start,{children:[a.jsx(KY,{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(tQt,{fields:S,tokens:r.filterTokens,onTokensChange:r.handleFilterTokensChange,disabled:C,onStartTextFilter:d})]})}),a.jsx(mIs,{isLoading:C,filterFields:S,filterTokens:r.filterTokens,onFilterTokensChange:r.handleFilterTokensChange,onClear:V,onRemoveAll:r.handleRemoveAll,onSave:c.handleSave,onRemoveSaved:c.hasSavedFilters?c.handleRemoveSaved:void 0,autoFocusFilterFieldId:u})]});if(T)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:jue}),actionRow:z,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsx(iIs,{error:T,resource:"logs",errorTitle:"Failed to load logs"})})]});const U=!!r.selectedEntityOption||r.filterTokens.length>0;return j.length===0&&!C&&!U?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:jue}),actionRow:z,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx(xIs,{datePreset:r.datePreset,dateFrom:r.selectedDateFrom,dateTo:r.selectedDateTo})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:jue}),actionRow:z,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx(pIs,{logs:j,isLoading:C,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:I,logIdMap:A,featuredLogId:r.featuredLogId,onLogClick:L,timestampSort:i?.direction,onSortChange:o}),a.jsx(sIs,{log:P??void 0,onClose:H,onTraceClick:D,onSpanClick:K,onPrevious:F,onNext:Q}),a.jsx(nAe,{depth:2,traceId:P?r.featuredTraceId??void 0:void 0,spans:q?.spans,isLoadingSpans:B,selectedSpanId:r.featuredSpanId??null,onSpanSelect:$,onClose:M,withQueryTrace:s.enabled,withFeedback:s.enabled,onOpenScore:(G,ne)=>n(UCe(G,ne))})]})}const GIs={name:e=>e.name||e.id};function KIs({server:e,rowProps:t}){const{paths:n,Link:r}=Tn(),i=Ge().options.baseUrl,l=e.transports?.includes("sse")??!0?"sse":"mcp",c=i?`${i}/api/mcp/${e.id}/${l}`:"",{data:u}=OOt({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(_e.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[a.jsx(_e.NameCell,{children:m}),a.jsx(_e.DescriptionCell,{children:c}),a.jsx(_e.TextCell,{className:"text-center",children:h||""}),a.jsx(_e.TextCell,{className:"text-center",children:f||""}),a.jsx(_e.TextCell,{className:"text-center",children:p||""})]})}function YIs({mcpServers:e,isLoading:t,search:n="",sort:r,onSortChange:s}){const i=g.useMemo(()=>{const c=n.toLowerCase();return Uk(e.filter(u=>u.name?.toLowerCase().includes(c)||u.id?.toLowerCase().includes(c)),r,GIs)},[e,n,r]),{containerRef:o,getRowProps:l}=Fu({count:i.length,global:!0});return t?a.jsx(Lu,{columns:"auto 1fr auto auto auto"}):a.jsxs(_e,{columns:"auto 1fr auto auto auto",scrollRef:o,children:[a.jsxs(_e.Top,{children:[s?a.jsx(_e.SortableTopCell,{sortKey:"name",sort:r?.key==="name"?r.direction:void 0,onSortChange:s,children:"Name"}):a.jsx(_e.TopCell,{children:"Name"}),a.jsx(_e.TopCell,{children:"URL"}),a.jsx(_e.TopCellSmart,{long:"Agents",short:a.jsx(Uo,{}),tooltip:"Agent Tools",className:"text-center"}),a.jsx(_e.TopCellSmart,{long:"Tools",short:a.jsx(fd,{}),tooltip:"Tools",className:"text-center"}),a.jsx(_e.TopCellSmart,{long:"Workflows",short:a.jsx(Ol,{}),tooltip:"Workflow Tools",className:"text-center"})]}),i.length===0&&n?a.jsx(_e.NoMatch,{message:"No MCP Servers match your search"}):null,i.map((c,u)=>a.jsx(KIs,{server:c,rowProps:l(u)},c.id))]})}const XIs=()=>a.jsx(Xt,{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(ue,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"MCP Documentation"}),variant:"fill"}),zM=[Ts("/mcps")],JIs=()=>{const{data:e=[],isLoading:t,error:n}=DP(),[r,s]=g.useState(""),[i,o]=g.useState();return n&&Cs(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:zM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(ui,{variant:"fill"})]}):n&&_s(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:zM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(Gs,{variant:"fill",resource:"MCP servers"})]}):n?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:zM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(Xt,{tone:"error",variant:"fill",titleSlot:"Failed to load MCP servers",descriptionSlot:n.message})]}):e.length===0&&!t?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:zM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(XIs,{})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:zM}),actionRow:a.jsx(ar,{children:a.jsx(ar.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(pf,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})})}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(YIs,{mcpServers:e,isLoading:t,search:r,sort:i,onSortChange:(l,c)=>o({key:c,direction:l})})]})};function Xf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eNs(e){if(!Xf(e))return;if(Xf(e.ui)&&typeof e.ui.resourceUri=="string")return e.ui.resourceUri;const t=e["ui/resourceUri"];return typeof t=="string"?t:void 0}function tNs(e){return Xf(e)&&e.status==="suspended"}function nNs(e){return e<1e3?`${Math.round(e)} ms`:`${(e/1e3).toFixed(2)} s`}function rNs(e){return e===void 0?"undefined":JSON.stringify(e,null,2)}function rQt(e){return e.status==="error"?e.error:rNs(e.output)}function sNs({status:e,output:t,error:n},r){if(r!==void 0){if(e==="success")return{status:"success",output:t,durationMs:r};if(e==="error")return{status:"error",error:iNs(n),durationMs:r}}}function iNs(e){return e instanceof Error?JSON.stringify({error:e.message},null,2):JSON.stringify({error:String(e)},null,2)}function fee(e){return a.jsx(rye,{className:"min-h-control-md",...e})}function oNs({zodInputSchema:e,isRunning:t,onRun:n,requestContextEntityType:r,requestContextEntityId:s}){const i=!vQ(e),[o,l]=g.useState({view:"form",value:void 0}),c=g.useRef(void 0),[u,d]=g.useState([]);function f(m){if(m===o.view)return;if(d([]),o.view==="form")return l({view:"json",value:JSON.stringify(c.current??{},null,2)});const v=ake(o.value);if(!v.ok)return d([v.error]);const y=VSt(e,v.value);if(y)return d([y]);c.current=v.value,l({view:"form",value:v.value})}function h(m){const v=qSt(e,m);v.ok?n(v.value):d(v.errors)}const p={isSubmitLoading:t,submitButtonLabel:"Run",submitButtonIcon:a.jsx(Uc,{}),submitButtonVariant:"primary"};return a.jsxs(DA,{children:[a.jsx(fee,{action:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx($ke,{entityType:r,entityId:s}),a.jsx(Wc,{defaultTab:"form",value:o.view,onValueChange:f,children:a.jsxs(Hc,{size:"md",children:[a.jsxs(si,{value:"form",disabled:t,children:[a.jsx(At,{size:"sm",children:a.jsx(Xht,{})}),"Form"]}),a.jsxs(si,{value:"json",disabled:t,children:[a.jsx(At,{size:"sm",children:a.jsx(Ua,{})}),"JSON"]})]})})]}),children:a.jsx(LA,{children:"Request"})}),a.jsx(y$,{children:a.jsx("div",{className:"p-4",children:o.view==="json"?a.jsxs("div",{className:"grid gap-4",children:[a.jsxs(ht,{invalid:u.length>0,children:[a.jsx(Or,{variant:"embedded",language:"json",value:o.value,onChange:m=>{l({view:"json",value:m}),d([])},editable:!t,"aria-label":"Request JSON"}),u.length>0&&a.jsx(ns,{children:u.map(m=>a.jsx("span",{className:"block",children:m},m))})]}),a.jsx(JG,{...p,onSubmit:()=>h(o.value)})]}):a.jsx(oke,{...p,schema:e,defaultValues:o.value,onValuesChange:m=>{c.current=m},onSubmit:n,className:"gap-0",children:!i&&a.jsx(Y,{variant:"body-sm",tone:"muted",className:"pb-4",children:"This tool takes no input. Run it as is."})})})})]})}function aNs({isRunning:e,lastRun:t}){return e?a.jsx(Xt,{iconSlot:a.jsx(_n,{}),titleSlot:"Running…",descriptionSlot:"Waiting for the tool to respond."}):t?a.jsx(jl,{code:rQt(t),lang:"json",className:"overflow-x-auto p-4 text-caption whitespace-pre"}):a.jsx(Xt,{iconSlot:a.jsx(vNn,{}),titleSlot:"No response yet",descriptionSlot:"Run the tool to see its output here."})}function lNs({run:e}){return a.jsxs("div",{className:"flex items-center gap-2",children:[e.status==="success"?a.jsx(Mt,{variant:"success",emphasis:"subtle",indicator:"dot",children:"Success"}):a.jsx(Mt,{variant:"destructive",emphasis:"subtle",indicator:"dot",children:"Error"}),a.jsx(Y,{as:"span",variant:"caption",font:"mono",tone:"muted",children:nNs(e.durationMs)}),a.jsx(ii,{content:rQt(e),copyMessage:"Response copied",tooltip:"Copy response",size:"icon-sm"})]})}function cNs({isRunning:e,lastRun:t}){return a.jsxs(DA,{className:"h-full",children:[a.jsx(fee,{action:!e&&t&&a.jsx(lNs,{run:t}),children:a.jsx(LA,{children:"Response"})}),a.jsx(y$,{className:"grid min-h-48 flex-1 content-center",children:a.jsx(aNs,{isRunning:e,lastRun:t})})]})}function sQt({zodInputSchema:e,execution:t,requestContextEntityType:n,requestContextEntityId:r}){const[s]=xr(n,r),[i,o]=g.useState(),l=async u=>{const d=performance.now();await t.execute(u,s).catch(()=>{}),o(performance.now()-d)},c=t.status==="pending";return a.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-6",children:[a.jsx(oNs,{zodInputSchema:e,isRunning:c,onRun:l,requestContextEntityType:n,requestContextEntityId:r}),a.jsx(cNs,{isRunning:c,lastRun:sNs(t,i)})]})}function iQt(e){return Xf(e)?$S(e):yr({})}function uNs({serverId:e,tool:t}){const{mutateAsync:n,status:r,data:s,error:i}=Mcr({serverId:e,toolId:t.name}),{data:o}=$cr({serverId:e,appResourceUri:eNs(t._meta)}),l=iQt(t.inputSchema),c={execute:(u,d)=>n({data:u,requestContext:d}),status:r,output:s,error:i};return a.jsxs("div",{className:"grid content-start gap-6",children:[o&&a.jsx(o9t,{html:o,toolName:t.name,onToolCall:(u,d)=>n({data:d})}),tNs(s)&&a.jsxs(Wt,{variant:"warning",children:["This tool asked for more input, which Studio cannot provide. The suspend payload below shows what it needs. Call it from an MCP client with an ",a.jsx(sh,{children:"inputRequests"})," handler to finish the request."]}),a.jsx(sQt,{zodInputSchema:l,execution:c,requestContextEntityType:"mcp-tool",requestContextEntityId:`${e}:${t.name}`})]})}const oQt=g.createContext(void 0),dNs=oQt.Provider;function qAe(){const e=g.useContext(oQt);if(e===void 0)throw new Error("useOpenToolId must be used inside ToolDrawer");return e}function fNs({description:e}){const t=AX({collapsedHeight:140});return a.jsx(V6,{state:t,expandLabel:"Read more",children:a.jsx(ql,{children:e})})}function aQt({description:e,overview:t,playground:n,canRun:r}){return a.jsx(a.Fragment,{children:a.jsxs(Wc,{defaultTab:"overview",className:"grid flex-1 grid-rows-[auto_1fr] gap-4 overflow-visible",children:[a.jsxs(Hc,{variant:"pill",size:"sm",children:[a.jsx(si,{value:"overview",children:"Overview"}),a.jsx(si,{value:"playground",disabled:!r,disabledTooltip:"You don't have permission to execute tools.",children:"Playground"})]}),a.jsxs(No,{value:"overview",flush:!0,className:"content-start gap-6",children:[e&&a.jsx(hl,{className:"p-4",children:a.jsx(fNs,{description:e})}),t]}),a.jsx(No,{value:"playground",flush:!0,keepMounted:!0,className:"h-full",children:r&&n})]})})}function hNs(e){return e.map(t=>JSON.stringify(t)).join(" | ")}function Snt(e){return e.map(k3).join(" | ")}function k3(e){return Xf(e)?Array.isArray(e.enum)?hNs(e.enum):"const"in e?JSON.stringify(e.const):Array.isArray(e.anyOf)?Snt(e.anyOf):Array.isArray(e.oneOf)?Snt(e.oneOf):Array.isArray(e.type)?e.type.join(" | "):e.type==="array"?`${k3(e.items)}[]`:lQt(e)?`Record<string, ${k3(e.additionalProperties)}>`:typeof e.type=="string"?e.type:"unknown":"unknown"}function pNs(e,t,n,{defaultsAreOptional:r=!1}){const s=Xf(t)?t:{},i="default"in s;return{name:e,type:k3(s),required:n.has(e)&&!(r&&i),description:typeof s.description=="string"?s.description:void 0,defaultValue:i?JSON.stringify(s.default):void 0}}function mNs(e,t={}){if(!Xf(e)||!Xf(e.properties))return[];const n=new Set(Array.isArray(e.required)?e.required.filter(r=>typeof r=="string"):[]);return Object.entries(e.properties).map(([r,s])=>pNs(r,s,n,t))}function lQt(e){return Xf(e)&&e.type==="object"&&!Xf(e.properties)&&Xf(e.additionalProperties)}function gNs(e){return Xf(e)&&(e.type==="object"||Xf(e.properties))}const vNs=["type","properties","items","enum","const","anyOf","oneOf","allOf","$ref"];function yNs(e){return!Xf(e)||!vNs.some(t=>t in e)}function xNs(){return a.jsxs(a.Fragment,{children:[a.jsx("span",{"aria-hidden":!0,className:"ml-0.5 text-destructive-indicator",children:"*"}),a.jsx("span",{className:"sr-only",children:" (required)"})]})}function bNs({field:e}){return a.jsxs(a.Fragment,{children:[e.description,e.defaultValue!==void 0&&a.jsxs("span",{className:"block",children:["Default ",e.defaultValue]})]})}function wNs({field:e}){const t=!!e.description||e.defaultValue!==void 0;return a.jsx(Oz,{label:a.jsxs(Y,{as:"span",variant:"body-sm",font:"mono",tone:"ink",children:[e.name,e.required&&a.jsx(xNs,{})]}),description:t&&a.jsx(bNs,{field:e}),children:a.jsx(Y,{as:"span",variant:"caption",font:"mono",tone:"muted",children:e.type})})}function Yye({message:e}){return a.jsx(Oz,{label:a.jsx(Y,{as:"span",variant:"body-sm",tone:"muted",children:e})})}function SNs({schema:e,emptyMessage:t,defaultsAreOptional:n}){if(yNs(e))return a.jsx(Yye,{message:t});if(!gNs(e)||lQt(e))return a.jsx(Oz,{label:"Type",children:a.jsx(Y,{as:"span",variant:"caption",font:"mono",tone:"muted",children:k3(e)})});const r=mNs(e,{defaultsAreOptional:n});return r.length===0?a.jsx(Yye,{message:t}):r.map(s=>a.jsx(wNs,{field:s},s.name))}function Cue({title:e,...t}){return a.jsxs(DA,{children:[a.jsx(fee,{children:a.jsx(LA,{children:e})}),a.jsx(y$,{children:a.jsx(SNs,{...t})})]})}function cQt({inputSchema:e,outputSchema:t,requestContextSchema:n,footer:r}){return a.jsxs("div",{className:"grid gap-6",children:[a.jsx(Cue,{title:"Input",schema:e,emptyMessage:"This tool takes no input.",defaultsAreOptional:!0}),a.jsx(Cue,{title:"Output",schema:t,emptyMessage:"No output schema defined."}),n!==void 0&&a.jsx(Cue,{title:"Request context",schema:n,emptyMessage:"No request context fields.",defaultsAreOptional:!0}),r]})}function kNs({serverId:e}){const t=qAe(),{canExecute:n}=Za(),{data:r,isLoading:s}=Rcr({serverId:e,toolId:t});return s?a.jsx(Tt.LoadingData,{}):r?a.jsx(aQt,{description:r.description,overview:a.jsx(cQt,{inputSchema:r.inputSchema}),canRun:n("tools"),playground:a.jsx(uNs,{serverId:e,tool:r})}):a.jsxs(Tt.NoData,{children:['This server has no tool "',t,'".']})}const uQt={agent:Uo,workflow:Ol,tool:fd},knt="auto 1fr auto",ONs={tool:"Tool",agent:"Agent",workflow:"Workflow"};function jNs(e){return e in uQt}function CNs({type:e}){const t=jNs(e)?e:"tool",n=uQt[t],r=ONs[t];return a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("span",{"aria-label":t,className:"inline-flex text-muted-foreground [&>svg]:size-4",children:a.jsx(n,{})})}),a.jsx(Dn,{children:r})]})}const _Ns=yr({ui:yr({resourceUri:Cn().optional()}).optional(),"ui/resourceUri":Cn().optional()});function TNs(e){const t=_Ns.safeParse(e);return t.success?!!(t.data.ui?.resourceUri?.startsWith("ui://")||t.data["ui/resourceUri"]?.startsWith("ui://")):!1}function ENs({server:e}){const[t,n]=g.useState(""),{data:r={},isLoading:s}=OOt({selectedServer:e}),{Link:i,paths:o}=Tn(),l=g.useMemo(()=>{const d=t.toLowerCase();return Object.values(r).filter(f=>f.name.toLowerCase().includes(d)||f.description?.toLowerCase().includes(d))},[r,t]),{containerRef:c,getRowProps:u}=Fu({count:l.length});return a.jsxs("section",{className:"flex flex-col gap-3",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[a.jsx(Y,{as:"h2",variant:"heading",children:"Available tools"}),a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(pf,{onSearch:n,label:"Filter tools",placeholder:"Filter by name",shortcutDisabled:!0})})]}),s?a.jsx(Lu,{columns:knt}):a.jsxs(_e,{columns:knt,scrollRef:c,children:[a.jsxs(_e.Top,{children:[a.jsx(_e.TopCell,{children:"Name"}),a.jsx(_e.TopCell,{children:"Description"}),a.jsx(_e.TopCell,{className:"justify-center text-center",children:"Type"})]}),l.length===0&&t?a.jsx(_e.NoMatch,{message:"No tools match your search"}):null,l.map((d,f)=>a.jsxs(_e.RowLink,{to:o.mcpServerToolLink(e.id,d.name),LinkComponent:i,...u(f),children:[a.jsx(_e.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-2",children:[d.name,TNs(d._meta)&&a.jsx(Mt,{size:"xs",children:"App"})]})}),a.jsx(_e.DescriptionCell,{children:d.description}),a.jsx(_e.TextCell,{className:"justify-center text-center",children:a.jsx(CNs,{type:d.toolType??"tool"})})]},d.name))]})]})}const INs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const c=window.MASTRA_SERVER_HOST,u=window.MASTRA_SERVER_PORT;let d=null;c&&u&&(d=`http://${c}:${u}`);const f=d||"http://localhost:4111",h=`${f}/api/mcp/${t.id}/sse`,p=`${f}/api/mcp/${t.id}/mcp`;s({sseUrl:h,httpStreamUrl:p})},[t]),e)return null;if(!t)return a.jsx(Y,{as:"h1",variant:"heading",tone:"muted",className:"py-20 text-center",children:"Server not found"});const i=t.transports?.includes("sse")??!0,o=`npx -y mcp-remote ${i?n:r}`,l=[{value:"http",label:"HTTP",description:"Use for stateless HTTP transport with streamable responses.",content:r,tooltip:"Copy HTTP Stream URL"},...i?[{value:"sse",label:"SSE",description:"Use for real-time communication via SSE.",content:n,tooltip:"Copy SSE URL"}]:[],{value:"cli",label:"CLI",description:"Use for local command-line access via npx and mcp-remote.",content:o,tooltip:"Copy Command Line Config"}];return a.jsxs("div",{className:"flex flex-col gap-6 pt-4",children:[a.jsx(hl,{children:a.jsxs(Wc,{defaultTab:"http",children:[a.jsxs(kQ,{className:"flex-row items-center justify-between gap-3 space-y-0 border-b border-border",children:[a.jsx(nw,{className:"shrink-0",children:"Connect"}),a.jsx("div",{className:"min-w-0",children:a.jsx(Hc,{variant:"pill-ghost",size:"sm",children:l.map(c=>a.jsx(si,{value:c.value,children:c.label},c.value))})})]}),l.map(c=>a.jsx(No,{value:c.value,flush:!0,children:a.jsxs(qm,{className:"flex flex-col gap-3",children:[a.jsx(Y,{tone:"muted",children:c.description}),a.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg bg-muted py-2 pr-2 pl-3",children:[a.jsx(Y,{as:"span",font:"mono",className:"min-w-0 break-all",children:c.content}),a.jsx(ii,{tooltip:c.tooltip,content:c.content})]})]})},c.value))]})}),a.jsx(ENs,{server:t})]})};function dQt(){const[e,t]=ci();return{toolId:e.get("tool")??void 0,close:()=>t(s=>{const i=new URLSearchParams(s);return i.delete("tool"),i},{replace:!0})}}function QAe({children:e}){const{toolId:t,close:n}=dQt();return a.jsxs(Tt,{open:t!==void 0,onClose:n,title:t??"",children:[a.jsxs(Tt.Header,{children:[a.jsxs(Tt.Heading,{children:[a.jsx(At,{size:"sm",className:"text-muted-foreground",children:a.jsx(fd,{})}),a.jsx("span",{className:"truncate",children:t})]}),a.jsx(Tt.HeaderActions,{children:a.jsx(Tt.CloseButton,{icon:"x",tooltip:"Close tool",onClick:n})})]}),a.jsx(Tt.Content,{className:"flex flex-col gap-4 px-3",children:t&&a.jsx(dNs,{value:t,children:e},t)})]})}const NNs=()=>{const{serverId:e}=jr(),t=[Ts("/mcps"),bur],{data:n=[],isLoading:r}=DP(),s=n.find(l=>l.id===e),i=s?.transports?.includes("sse")??!0,o=r||s?a.jsxs(Mc,{children:[a.jsx(Mc.Title,{isLoading:r,children:s?.name}),s&&a.jsx(Mc.Meta,{beside:!0,children:a.jsxs(Mt,{size:"sm",children:["v",s.version_detail.version]})}),s&&a.jsx(Mc.Description,{children:i?"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case.":"This MCP server speaks Streamable HTTP only (protocol 2026-07-28)."})]}):void 0;return a.jsxs(It,{variant:"narrow",breadcrumbs:a.jsx(Dt,{crumbs:t}),header:o,children:[a.jsx(INs,{isLoading:r,server:s}),e&&a.jsx(QAe,{children:a.jsx(kNs,{serverId:e})})]})},BD=[Ts("/metrics")];function ANs({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=>PNs(f,i));return u?a.jsxs("div",{className:Z("grid grid-cols-[1fr_auto] items-start gap-3"),children:[a.jsx(Jqt,{fields:i,tokens:o,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&a.jsx(Yqt,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function PNs(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 Xye({children:e,filterFields:t,isLoading:n=!1}){const[r]=ci(),{filterTokens:s,setFilterTokens:i}=Gk(),[o,l]=g.useState(),[c,u]=g.useState(()=>!!yqt()),d=()=>{XCs(r),u(!0),Ye.success("Filters setting for Metrics saved")},f=()=>{JCs(),u(!1),Ye.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(It,{breadcrumbs:a.jsx(Dt,{crumbs:BD}),actionRow:a.jsxs(a.Fragment,{children:[a.jsx(ar,{children:a.jsxs(ar.Start,{children:[a.jsx(m_s,{}),a.jsx(tQt,{fields:t,tokens:s,onTokensChange:i,disabled:n,onStartTextFilter:l})]})}),a.jsx(ANs,{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 $Ns({error:e}){return Cs(e)?a.jsx(ui,{}):_s(e)?a.jsx(Gs,{resource:"metrics"}):a.jsx(Xt,{tone:"error",titleSlot:"Failed to load storage capabilities",descriptionSlot:e.message})}const Ont=xqt({availableTags:[],availableEntityNames:[],availableServiceNames:[],availableEnvironments:[]});function RNs({children:e}){const{supportsMetrics:t,isLoading:n,error:r}=O$();return n?a.jsx(Xye,{filterFields:Ont,isLoading:!0,children:a.jsxs("div",{className:"flex h-full items-center justify-center gap-2",children:[a.jsx(_n,{"aria-label":"Loading storage capabilities"}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:"Loading storage capabilities"})]})}):r?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsx($Ns,{error:r})})]}):t?e:a.jsx(Xye,{filterFields:Ont,children:a.jsx(Xt,{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(ue,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Metrics Documentation"}),variant:"fill"})})}function MNs(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 fQt(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=MNs(s);l&&e.set(t,l)}function rl(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function hQt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function DNs({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const i=new URLSearchParams;i.set(z1,"branches"),fQt(i,F1,x1,b1,e,t,r.window);const o=r.rootEntityType??n.rootEntityType;o&&i.set(w$,o),r.status&&i.set(S$,r.status),rl(i,yl.entityName,r.entityName??n.entityName),rl(i,yl.threadId,r.threadId??n.threadId),rl(i,yl.resourceId,r.resourceId??n.resourceId),rl(i,yl.runId,n.runId),rl(i,yl.sessionId,n.sessionId),rl(i,yl.requestId,n.requestId),rl(i,yl.userId,n.userId),rl(i,yl.organizationId,n.organizationId),rl(i,yl.experimentId,n.experimentId),rl(i,yl.serviceName,n.serviceName),rl(i,yl.environment,n.environment),hQt(i,yl.tags,n.tags);const l=i.toString();return l?`${s}?${l}`:s}function LNs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const i=new URLSearchParams;fQt(i,Zb,Wb,Hb,e,t,r.window);const o=r.rootEntityType??n.rootEntityType;o&&i.set(B0,o),rl(i,Ml.entityName,r.entityName??n.entityName),rl(i,Ml.threadId,r.threadId??n.threadId),rl(i,Ml.resourceId,r.resourceId??n.resourceId),rl(i,Ml.runId,n.runId),rl(i,Ml.sessionId,n.sessionId),rl(i,Ml.requestId,n.requestId),rl(i,Ml.userId,n.userId),rl(i,Ml.organizationId,n.organizationId),rl(i,Ml.experimentId,n.experimentId),rl(i,Ml.serviceName,n.serviceName),rl(i,Ml.environment,n.environment),hQt(i,Ml.tags,n.tags),r.status==="error"&&i.append(Ml.level,"error");const l=i.toString();return l?`${s}?${l}`:s}function zNs(){const{datePreset:e,customRange:t,dimensionalFilter:n}=Gk(),r=Dr(),s={preset:e,customRange:t,dashboardFilter:n};return{openTraces:(l={})=>{r(DNs({...s,scope:l}))},openLogs:(l={})=>{r(LNs({...s,scope:l}))}}}const _ue="period",X7="dateFrom",J7="dateTo";function FNs(){const[e,t]=ci(),n=e.get(_ue),r=l_s(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=p=>{if(!p)return;const m=new Date(p);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(X7)),h=d(e.get(J7));if(!(!f&&!h))return{from:f,to:h}},[r,e.toString()]),i=g.useMemo(()=>t_s(e),[e.toString()]),o=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d==="24h"?h.delete(_ue):h.set(_ue,d),d!=="custom"&&(h.delete(X7),h.delete(J7)),h},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d?.from?h.set(X7,d.from.toISOString()):h.delete(X7),d?.to?h.set(J7,d.to.toISOString()):h.delete(J7),h},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return r_s(h,d),h},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,e_s(e)))return;const d=yqt();d&&t(f=>{const h=new URLSearchParams(f);for(const[p,m]of d)h.append(p,m);return h},{replace:!0})},[]),a.jsx(d_s,{preset:r,filterTokens:i,onPresetChange:o,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:a.jsx(RNs,{children:a.jsx(BNs,{})})})}function BNs(){const{error:e,isLoading:t}=jqt(mf()),{isInMemory:n}=O$(),{data:r,isLoading:s}=kBt(),{data:i,isLoading:o}=ONe(),{data:l,isLoading:c}=SBt(),{data:u,isLoading:d}=jNe(),f=g.useMemo(()=>xqt({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&&Cs(e)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(ui,{variant:"fill"})]}):e&&_s(e)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(Gs,{variant:"fill",resource:"metrics"})]}):e?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(Xt,{tone:"error",variant:"fill",titleSlot:"Failed to load metrics",descriptionSlot:e.message})]}):a.jsx(Xye,{filterFields:f,isLoading:t,children:a.jsxs("div",{className:"grid content-start gap-4",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.jsx(UNs,{})]})})}function UNs(){const{openTraces:e,openLogs:t}=zNs(),n=od.AGENT;return a.jsxs("div",{className:"grid content-start gap-4 pb-6",children:[a.jsx(q_s,{}),a.jsx(kTs,{onViewTraces:()=>e(),onTimeRangeClick:r=>e({window:r})}),a.jsxs(u1,{columns:3,children:[a.jsx(u1.Item,{children:a.jsx(jTs,{onTimeRangeClick:r=>e({rootEntityType:n,window:r})})}),a.jsx(u1.Item,{children:a.jsx(ATs,{onViewErrors:()=>t({rootEntityType:n,status:"error"}),onTimeRangeClick:r=>e({rootEntityType:n,status:"error",window:r})})}),a.jsx(u1.Item,{span:2,className:"@7xl:col-span-1",children:a.jsx(zTs,{onViewTraces:r=>e({rootEntityType:r}),onTimeRangeClick:r=>e({window:r})})})]}),a.jsxs(u1,{columns:2,children:[a.jsx(u1.Item,{children:a.jsx(oEs,{onViewTraces:r=>e({rootEntityType:r}),onViewErrors:r=>t({rootEntityType:r,status:"error"}),onEntityClick:(r,s)=>e({rootEntityType:r,entityName:s})})}),a.jsx(u1.Item,{children:a.jsx(uEs,{onViewTraces:()=>e(),onAgentClick:r=>e({rootEntityType:n,entityName:r}),onModelClick:r=>e({model:r}),onThreadClick:r=>e({threadId:r})})})]}),a.jsx(yEs,{})]})}function VNs(){const{isCmsAvailable:e}=Wx(),{paths:t}=Tn();return e?a.jsx(wX,{href:t.cmsPromptBlockCreateLink(),tooltip:"Create a prompt",children:"New prompt"}):null}const FM=[Ts("/prompts")],qNs=50,QNs=["updatedAt"];function ZNs(){const[e,t]=g.useState(""),[n,r]=g.useState(0),[s,i]=ci(),{sort:o,onSortChange:l}=Hk({searchParams:s,setSearchParams:i,allowedKeys:QNs}),c=g.useMemo(()=>o?{field:o.key,direction:o.direction==="asc"?"ASC":"DESC"}:void 0,[o]),{data:u,isLoading:d,error:f,isPlaceholderData:h}=C7t({page:n,perPage:qNs,orderBy:c}),p=u?.promptBlocks??[],m=u?.hasMore??!1,v=g.useCallback(()=>{h||r(S=>S+1)},[h]),y=g.useCallback(()=>{h||r(S=>Math.max(0,S-1))},[h]),x=g.useCallback(S=>{t(S),r(0)},[]),b=g.useCallback((S,k)=>{l(S,k),r(0)},[l]);return f&&Cs(f)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:FM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(ui,{variant:"fill"})]}):f&&_s(f)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:FM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(Gs,{variant:"fill",resource:"prompt blocks"})]}):f?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:FM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(Xt,{tone:"error",variant:"fill",titleSlot:"Failed to load prompt blocks",descriptionSlot:f.message})]}):p.length===0&&!d&&n===0?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:FM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(cms,{})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:FM}),headerActions:a.jsx(VNs,{}),actionRow:a.jsx(ar,{children:a.jsx(ar.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(pf,{onSearch:x,label:"Filter prompts",placeholder:"Filter by name or description"})})})}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(lms,{promptBlocks:p,isLoading:d,search:e,currentPage:n,hasMore:m,onNextPage:v,onPrevPage:y,updatedSort:o?.direction,onSortChange:b})]})}const WNs=[Ts("/resources")],HNs=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:mTn,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:kht,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Zs,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:dL,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:J0e,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:Y0e,href:"https://mastra.ai/contact?ref=studio",external:!0}];function GNs(){return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:WNs}),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:HNs.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(Zs,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})]}),a.jsx(Y,{variant:"caption",tone:"muted",children:e.description})]},e.href))})})]})}function jnt(){const{isCmsAvailable:e}=Wx(),{paths:t}=Tn();return e?a.jsx(wX,{href:t.cmsScorersCreateLink(),tooltip:"Create a scorer",children:"New scorer"}):null}const BM=[Ts("/scorers")];function KNs(){const{data:e={},isLoading:t,error:n}=Fx(),[r,s]=g.useState(""),[i,o]=g.useState("all"),[l,c]=g.useState();if(n&&Cs(n))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(ui,{variant:"fill"})]});if(n&&_s(n))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Gs,{variant:"fill",resource:"scorers"})]});if(n)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Xt,{tone:"error",variant:"fill",titleSlot:"Failed to load scorers",descriptionSlot:n.message})]});if(Object.keys(e).length===0&&!t)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BM}),headerActions:a.jsx(jnt,{}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(efs,{})]});const u=i!=="all"||r!=="",d=()=>{s(""),o("all")};return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:BM}),headerActions:a.jsx(jnt,{}),actionRow:a.jsx(nfs,{search:r,onSearchChange:s,sourceFilter:i,onSourceFilterChange:o,onReset:d,hasActiveFilters:u}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Jds,{scorers:e,isLoading:t,search:r,sourceFilter:i,sort:l,onSortChange:(f,h)=>c({key:h,direction:f})})]})}const pQt=["input","entity"],YNs={input:"Input",entity:"Entity"};function XNs(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 JNs(){const[e,t]=g.useState(new Set),n=g.useMemo(()=>new Set(pQt.filter(i=>!e.has(i))),[e]),r=g.useMemo(()=>XNs(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 eAs({visibleColumns:e,toggleColumn:t}){return a.jsxs(ct,{children:[a.jsx(ct.Trigger,{asChild:!0,children:a.jsx(ue,{icon:a.jsx(Aht,{}),children:"Columns"})}),a.jsxs(ct.Content,{align:"end",children:[a.jsx(ct.Label,{children:"Toggle columns"}),pQt.map(n=>a.jsx(ct.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:YNs[n]},n))]})]})}const Cnt=[Ts("/scorers"),yur],tAs=["date","score"];function nAs(){const{scorerId:e}=jr(),[t,n]=ci(),r=t.get("scoreId")??void 0,[s,i]=g.useState(r),[o,l]=g.useState(!1),c=Dr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:h}=Jcr(e),p=JNs(),{data:m={},isLoading:v,error:y}=Cp(),{isLoading:x,error:b}=ng({}),{sort:S,onSortChange:k}=Hk({searchParams:t,setSearchParams:n,allowedKeys:tAs}),{data:j=[],isLoading:C,error:T,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:I}=Xcr({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),A=g.useMemo(()=>Uk(j,S,{date:X=>X.createdAt,score:X=>typeof X.score=="number"?X.score:void 0}),[j,S]),P=g.useMemo(()=>f?.agentIds?.filter(X=>m[X]).map(X=>({value:X,label:m[X].name,type:"AGENT"}))||[],[f?.agentIds,m]),L=g.useMemo(()=>f?.workflowIds?.map(X=>({value:X,label:X,type:"WORKFLOW"}))||[],[f?.workflowIds]),F=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...P,...L],[P,L]),Q=t.get("entity")??"all",q=F.find(X=>X.value===Q);q&&q.value!==u?.value&&d(q),g.useEffect(()=>{if(h){const X=h instanceof Error?h.message:"Failed to load scorer";Ye.error(`Error loading scorer: ${X}`)}},[h]),g.useEffect(()=>{if(y){const X=y instanceof Error?y.message:"Failed to load agents";Ye.error(`Error loading agents: ${X}`)}},[y]),g.useEffect(()=>{if(b){const X=b instanceof Error?b.message:"Failed to load workflows";Ye.error(`Error loading workflows: ${X}`)}},[b]);const B=X=>{X?.value&&n(ee=>{const ie=new URLSearchParams(ee);return ie.set("entity",X.value),ie})};g.useEffect(()=>{const X=t.get("scoreId")??void 0;if(X===s)return;if(!X){i(void 0);return}A.find(ie=>ie.id===X)&&i(X)},[t,A]);const V=g.useCallback(X=>{i(X||void 0),n(ee=>{const ie=new URLSearchParams(ee);return X?ie.set("scoreId",X):ie.delete("scoreId"),ie})},[n]);if(!f)return null;const H=Cs(h)||Cs(y)||Cs(b),D=h&&_s(h),K=!H&&!D&&(h||y||b),M=!C&&A.length===0,$=u?.value!=="all",z=f?.source==="stored",U=e?a.jsx(eee,{open:o,onOpenChange:l,initialScorerIds:[e],onSuccess:X=>{c(`/experiments/${X}`)}}):null,G=z?a.jsxs(ct,{children:[a.jsx(ct.Trigger,{asChild:!0,children:a.jsx(ue,{size:"lg","aria-label":"Scorer actions menu",children:a.jsx(Q0,{})})}),a.jsx(ct.Content,{align:"end",className:"w-48",children:a.jsxs(ct.Item,{onSelect:()=>{c(`/cms/scorers/${e}/edit`)},children:[a.jsx(Bc,{})," Edit Scorer"]})})]}):null;if(H||D||K||M&&!$){const X=(h instanceof Error?h.message:void 0)??(y instanceof Error?y.message:void 0)??(b instanceof Error?b.message:void 0)??"An unexpected error occurred",ee=H||D||K;return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Cnt}),actionRow:!ee&&G?a.jsx(ar,{children:a.jsx(ar.End,{children:G})}):void 0,children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:"flex h-full items-center justify-center",children:H?a.jsx(ui,{}):D?a.jsx(Gs,{resource:"scorers"}):K?a.jsx(Xt,{tone:"error",titleSlot:"Failed to load scorer",descriptionSlot:X}):a.jsx(Lds,{onRunExperiment:()=>l(!0)})}),U]})}return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Cnt}),actionRow:a.jsxs(ar,{children:[a.jsx(ar.Start,{children:a.jsx(Yds,{selectedEntity:u,entityOptions:F,onEntityChange:B,onReset:()=>{n(X=>{const ee=new URLSearchParams(X);return ee.set("entity","all"),ee})},isLoading:C||v||x})}),a.jsxs(ar.End,{children:[a.jsx(eAs,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),a.jsx(ue,{variant:"primary",onClick:()=>l(!0),icon:a.jsx(Uc,{}),children:"Run Experiment"}),G]})]}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Dds,{scores:A,isLoading:C,selectedScoreId:s,isFetchingNextPage:_,hasNextPage:N,setEndOfListElement:I,onScoreClick:V,errorMsg:T?.message,columnsState:p,sort:S,onSortChange:k}),U]})}const mQt=g.createContext(void 0);function rAs({value:e,onValueChange:t,"aria-label":n,size:r="md",iconOnly:s=!1,className:i,children:o,...l}){const c=g.useRef(new Map),u=g.useRef(null),d={iconOnly:s,registerItem:(h,p)=>c.current.set(h,p),unregisterItem:h=>c.current.delete(h)},f=h=>typeof h=="string"&&c.current.has(h);return g.useLayoutEffect(()=>{const h=u.current,p=c.current.get(e);if(!h)return;if(!p){h.hidden=!0;return}const m=()=>{h.style.width=`${p.offsetWidth}px`,h.style.transform=`translateX(${p.offsetLeft}px)`};m();let v;h.hidden&&(h.hidden=!1,v=requestAnimationFrame(()=>h.setAttribute("data-ready","")));const y=typeof ResizeObserver>"u"?void 0:new ResizeObserver(m);return c.current.forEach(x=>y?.observe(x)),()=>{v!==void 0&&cancelAnimationFrame(v),y?.disconnect()}},[e,o]),a.jsx(mQt.Provider,{value:d,children:a.jsxs(M5t,{...l,value:e,onValueChange:h=>{f(h)&&t(h)},"aria-label":n,...$x({"aria-label":n,"aria-labelledby":l["aria-labelledby"]}),"data-slot":"segmented-control","data-size":r,className:Z(pr,"relative inline-flex w-fit shrink-0 items-stretch rounded-full p-0.5",s&&"gap-0.5",tp[r],"data-[disabled]:opacity-50",i),children:[a.jsx("span",{ref:u,hidden:!0,"aria-hidden":"true","data-slot":"segmented-control-thumb",className:Z("pointer-events-none absolute inset-y-0.5 left-0 rounded-full bg-fill-hover ring-1 ring-border ring-inset","motion-safe:data-[ready]:transition-[transform,width] motion-safe:data-[ready]:duration-normal motion-safe:data-[ready]:ease-out-custom")}),o]})})}function sAs({value:e,disabled:t,className:n,children:r,ref:s,...i}){const o=g.useContext(mQt);if(!o)throw new Error("SegmentedControlItem must be used inside a SegmentedControl");const{iconOnly:l,registerItem:c,unregisterItem:u}=o,d=xk(s,f=>(f&&c(e,f),()=>u(e)));return a.jsx(R5t,{...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 iAs=[{value:"system",label:"System",icon:a.jsx(Wht,{})},{value:"light",label:"Light",icon:a.jsx(VNn,{})},{value:"dark",label:"Dark",icon:a.jsx(uIn,{})}];function oAs(e,t){if(e.some(r=>r.value===t))return t;const[n]=e;return n?n.value:"system"}const aAs=({value:e,onChange:t,options:n=iAs,size:r="md","aria-label":s="Theme",...i})=>{const{theme:o,setTheme:l}=oSe(),c=e??o,u=t??l,d=oAs(n,c);return a.jsx(rAs,{...i,"aria-label":s,iconOnly:!0,size:r==="xs"?"sm":r,value:d,onValueChange:u,children:n.map(f=>a.jsx(sAs,{value:f.value,"aria-label":f.label,children:f.icon},f.value))})},lAs=[Ts("/settings")],cAs=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=pL();return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:lAs}),children:[a.jsx("h1",{className:"sr-only",children:"Settings"}),a.jsx(Ofs,{children:a.jsxs("div",{className:"mx-auto flex max-w-4xl flex-col gap-8",children:[a.jsxs(DA,{children:[a.jsxs(rye,{children:[a.jsx(LA,{children:"General"}),a.jsx(qXe,{children:"Stored in this browser."})]}),a.jsx(y$,{children:a.jsx(Oz,{label:"Theme",description:"Customize the appearance of the studio.",children:a.jsx(aAs,{})})})]}),a.jsxs(DA,{children:[a.jsxs(rye,{children:[a.jsx(LA,{children:"Mastra Connection"}),a.jsx(qXe,{children:"Configure the Mastra instance URL, API prefix, and request headers used by the studio."})]}),a.jsx(Y9t,{variant:"factory",initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})]})]})})]})};function uAs(){const[e]=ci(),t=Dr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return a.jsx(Kqt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}async function gQt(){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 dAs({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 fAs({repoOrSlug:e,owner:t}){const{templates:n}=await gQt(),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 dAs({repo:e,owner:t});if(s)return s;throw new Error(`Template ${e} not found`)}return r}async function hAs({repo:e,owner:t,branch:n}){const r=`https://raw.githubusercontent.com/${t}/${e}/${n}/.env.example`,s=await fetch(r);return s.ok?(await s.text()).split(`
|
|
699
|
-
`).reduce((i,o)=>{if(!o||o.startsWith("#"))return i;const[l,c]=o.split("=");return l&&(i[l]=c?.split("")?.every(u=>u==="*")?"":c?.replaceAll('"',"")),i},{}):{}}const pAs=({queryOptions:e}={})=>_t({queryKey:["mastra-templates"],queryFn:gQt,...e}),mAs=({repoOrSlug:e,owner:t,queryOptions:n})=>_t({queryKey:["template-repo",e,t],queryFn:()=>fAs({repoOrSlug:e,owner:t}),...n}),gAs=({repo:e,owner:t,branch:n,queryOptions:r})=>_t({queryKey:["template-repo-env-vars",e,t,n],queryFn:()=>hAs({repo:e,owner:t,branch:n}),...r}),vAs=({queryOptions:e}={})=>{const t=Ge();return _t({queryKey:["agent-builder-workflow"],queryFn:async()=>await t.getAgentBuilderAction("merge-template").details(),...e})},yAs=({queryOptions:e}={})=>{const t=Ge();return Sn({mutationFn:async({runId:n})=>await t.getAgentBuilderAction("merge-template").createRun({runId:n}),...e})},xAs=({queryOptions:e}={})=>{const t=Ge();return Sn({mutationFn:async({runId:n})=>await t.getAgentBuilderAction("merge-template").runById(n),...e})},_nt=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)},Tnt=(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=_nt(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=_nt(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}},bAs=(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)}},vQt=(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}=Tnt(h,d,e);if(d=p,r(p),h.runId||c||t){const m=h.runId||c||t;bAs(m,p)}}}catch(f){console.error("💥 [processStream] Error processing template installation stream:",f);const{newState:h}=Tnt({type:"error",payload:{error:f instanceof Error?f.message:"Unknown error"}},d,e);r(h)}finally{i(!1),u.releaseLock()}}}},wAs=({workflowInfo:e,queryOptions:t}={})=>{const n=Ge(),{streamResult:r,isStreaming:s,processStream:i}=vQt(e);return{streamInstall:Sn({mutationFn:async({inputData:o,selectedModel:l,runId:c})=>{for(let d=1;d<=3;d++)try{const f=n.getAgentBuilderAction("merge-template"),h=new d_;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}},SAs=({workflowInfo:e,queryOptions:t}={})=>{const n=Ge(),{streamResult:r,isStreaming:s,processStream:i}=vQt(e);return{observeInstall:Sn({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 kAs(e){return e.replace(/\/$/,"").split("/").pop()}function OAs({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?a.jsx("div",{className:Z("grid gap-y-4",n),children:Array.from({length:5}).map((i,o)=>a.jsx("div",{className:"h-16 animate-pulse rounded-lg bg-card"},o))}):a.jsx("div",{className:Z("grid gap-y-4",n),children:e.map(i=>{const o=i?.agents||i?.tools||i?.networks||i?.workflows||i?.mcp;return a.jsxs("article",{className:Z(pr,"state-layer grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg"),children:[a.jsxs(s,{to:`/templates/${i.slug}`,className:Z("group grid",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":i.imageURL}),children:[i.imageURL&&a.jsx("div",{className:"overflow-hidden",children:a.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${i.imageURL})`}})}),a.jsxs("div",{className:Z("grid w-full gap-0.5 px-4 py-3","[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground"),children:[a.jsx(Y,{as:"h2",tone:"ink",children:i.title}),a.jsx(Y,{className:Z(vx,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(Uo,{})," ",i.agents.length]})}),i?.tools&&i.tools.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(fd,{})," ",i.tools.length]})}),i?.networks&&i.networks.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(Hht,{})," ",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(yk,{})," ",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(L_,{})," ",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",aht,vx,On),children:[a.jsx(bX,{})," ",kAs(i.githubUrl)]})})})]},i.slug)})})}function jAs({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(ps,{value:t,onValueChange:s,children:[a.jsx(gs,{"aria-label":"Filter by tag",size:"md",children:a.jsx(ms,{placeholder:"Select an option"})}),a.jsx(vs,{children:e.map(f=>a.jsx(hr,{value:f.value,children:f.label},f.value))})]}),a.jsxs(ps,{value:r,onValueChange:i,children:[a.jsx(gs,{"aria-label":"Filter by provider",size:"md",children:a.jsx(ms,{placeholder:"Select an option"})}),a.jsx(vs,{children:n.map(f=>a.jsx(hr,{value:f.value,children:f.label},f.value))})]}),c&&a.jsx(ue,{onClick:c,icon:a.jsx(zn,{}),children:"Reset"})]})}const CAs=[{id:"templates",label:"Templates"}];function _As(){const{data:e,isLoading:t}=pAs(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[i,o]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(b=>{f.push({value:b,label:b})});const h=[{value:"all",label:"Any provider"}];(s||[]).forEach(b=>{h.push({value:b,label:b})});const p=(b,S)=>{S==="tag"?o(b):S==="provider"&&c(b)},m=b=>{d(b)},v=()=>{o("all"),c("all"),d("")},y=n.filter(b=>!(u&&!b.title.toLowerCase().includes(u)&&!b.description.toLowerCase().includes(u)||i!=="all"&&!b.tags.includes(i)||l!=="all"&&!b.supportedProviders.includes(l))),x=u||i!=="all"||l!=="all";return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:CAs}),children:[a.jsx("h1",{className:"sr-only",children:"Templates"}),a.jsx(mL,{children:a.jsxs(hpt,{children:[a.jsx(At,{children:a.jsx(K1,{})}),"Templates"]})}),a.jsxs("div",{className:Z("z-10 h-full w-full overflow-y-auto px-5 pb-12"),children:[a.jsx(jAs,{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(OAs,{templates:y,linkComponent:ac,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const TAs="1.77.0";function hee({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 EAs({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(Yd,{className:"text-warning-foreground"}),title:"Template Installed with Warnings"}:{icon:a.jsx(TTn,{}),title:"Template Installation Failed"},{icon:l,title:c}=o();return a.jsxs(hee,{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(Ln,"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(jl,{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(Ln,"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(jl,{className:"text-caption wrap-break-word whitespace-pre-wrap",code:n})})]})]})}const IAs=g.createContext(null);function NAs(){const e=g.useContext(IAs);return e||{registerResetFn:()=>{},triggerReset:()=>{}}}const yQt=({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}=N6(),b=G0(),{models:S}=uw(),k=g.useMemo(()=>y?.providers||[],[y]);g.useEffect(()=>{l(t),u(e||"")},[t,e]);const j=io(c),T=ZI(k,j)?.id||j,_=async F=>{if(l(F),F&&T){f(!0);try{const Q=await n({provider:T,modelId:F});console.info("Model updated:",Q)}catch(Q){console.error("Failed to update model:",Q)}finally{f(!1)}}},N=F=>{const Q=io(F);u(Q),Q!==j&&(l(""),v(!0))},{registerResetFn:I}=NAs();if(g.useEffect(()=>(I(()=>{if(h||m)return;if(j&&j!==s&&(!o||o==="")){u(io(s)),l(i);const V=ZI(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(_n,{}),a.jsx(Y,{as:"span",tone:"muted",children:"Loading providers..."})]});const A=async()=>{if(!r){console.warn("Reset model function not provided");return}try{f(!0),await r()}catch(F){console.error("Failed to reset model:",F)}finally{f(!1)}},P=ZI(k,j);if(b.active&&b.pickerVisible===!1){const F=b.default&&b.default.provider&&b.default.modelId?`${b.default.provider}/${b.default.modelId}`:c&&o?`${c}/${o}`:"Locked by admin";return a.jsxs("div",{className:Z(pr,"flex items-center gap-2 rounded-md px-3 py-2"),"data-testid":"agent-metadata-model-locked",children:[a.jsx(Au,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"caption",tone:"ink",className:"truncate",children:F}),a.jsx(Y,{as:"span",variant:"meta",tone:"muted",className:"ml-auto shrink-0",children:"Set by admin"})]})}const L=!!(j&&o)&&b.active&&b.allowed!==void 0&&!S.some(F=>io(F.provider)===j&&F.model===o);return a.jsxs("div",{className:"@container",children:[a.jsxs("div",{className:"flex w-full flex-col items-stretch gap-2 @xs:flex-row @xs:items-center",children:[a.jsx("div",{className:"w-full @xs:w-2/5",children:a.jsx(Mk,{value:j,onValueChange:N,open:h,onOpenChange:p})}),a.jsx("div",{className:"w-full @xs:w-3/5",children:a.jsx(Dk,{llmId:j,value:o,onValueChange:_,open:m,onOpenChange:v})}),a.jsx(ue,{variant:"default",size:"md",onClick:A,disabled:d,className:"flex items-center gap-1.5 border-0! whitespace-nowrap",title:"Reset to original model",children:a.jsx(T_,{className:"h-3.5 w-3.5"})})]}),L&&a.jsx("div",{className:"p-2 pt-2","data-testid":"agent-metadata-model-stale-warning",children:a.jsx(Wt,{variant:"warning",title:"Model not allowed",children:a.jsxs(Wt.Message,{children:[a.jsxs("code",{className:"rounded bg-fill-hover px-1 py-0.5",children:[c,"/",o]})," ","is no longer allowed by the admin policy. Pick a different model to save changes."]})})}),P&&!P.connected&&a.jsx("div",{className:"p-2 pt-2",children:a.jsx(Wt,{variant:"warning",title:"Provider not connected",children:a.jsxs(Wt.Message,{children:["Set the"," ",a.jsx("code",{className:"rounded bg-fill-hover px-1 py-0.5",children:Array.isArray(P.envVar)?P.envVar.join(", "):P.envVar})," ","environment"," ",Array.isArray(P.envVar)&&P.envVar.length>1?"variables":"variable"," to use this provider."]})})})]})};function AAs({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(hee,{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(Ght,{})]}),a.jsxs(ht,{orientation:"horizontal",children:[a.jsx(ut,{children:"Template AI Model Provider"}),a.jsx(Nvt,{className:"flex-1",children:a.jsxs(ps,{name:"template-provider",value:t,onValueChange:n,children:[a.jsx(gs,{size:"md",children:a.jsx(ms,{placeholder:"Select"})}),a.jsx(vs,{children:e.map(h=>a.jsx(hr,{value:h.value,children:h.label},h.value))})]})})]}),t&&Object.entries(r||{}).length>0&&a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h3",tone:"muted",children:"Set required Environmental Variables"}),a.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?a.jsxs("div",{className:Z("text-muted-foreground","col-span-2 flex items-center justify-center gap-4","[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50","animate-in duration-300 fade-in"),children:[a.jsx(_n,{}),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(ht,{className:"w-full",children:[a.jsx(ut,{className:"sr-only",children:"Key"}),a.jsx(wn,{name:`env-${h}`,value:h,disabled:!0,className:"w-full"})]}),a.jsxs(ht,{invalid:s.includes(h),className:"w-full",children:[a.jsx(ut,{className:"sr-only",children:"Value"}),a.jsx(wn,{name:h,value:p,onChange:o,autoComplete:"off",className:"w-full"}),a.jsx(ns,{children:s.includes(h)?"Value is required.":void 0})]})]},h))}),a.jsxs("div",{className:"relative mt-3.5 border-t border-border pt-12",children:[a.jsx("div",{className:"absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full bg-background",children:a.jsx(Y,{tone:"muted",as:"span",variant:"caption",className:"block",children:"And"})}),a.jsx(Y,{as:"h3",tone:"muted",children:"Set AI Model for Template Installation"}),a.jsx(Y,{tone:"muted",className:"mt-2 mb-5",children:"This model will be used by the workflow to process and install the template"}),a.jsx(yQt,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&a.jsx(ue,{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(_n,{className:"h-4 w-4"})," Installing..."]}):a.jsxs(a.Fragment,{children:["Install ",a.jsx(dp,{})]})})]})})}function PAs({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(K1,{}),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(hp,{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(sh,{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(Ln,"mt-auto flex items-center gap-2"),children:[a.jsx(bX,{}),a.jsx(Y,{as:"span",variant:"body",className:"block",children:n?.split("/")?.pop()})]})]}),s&&a.jsx(ZIe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Ent(e){switch(e){case"running":return a.jsx(_n,{size:"sm","aria-hidden":!0});case"success":return a.jsx(ur,{"aria-hidden":!0});case"failed":return a.jsx(zn,{"aria-hidden":!0});default:return null}}function $As(){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 RAs({status:e,variant:t}){return t==="plain"?a.jsx("span",{className:Z("flex size-4 items-center justify-center self-center [&>svg]:size-4",Mi.colors,{"[&>svg]:text-success-indicator":e==="success","[&>svg]:text-destructive-foreground":e==="failed"}),children:e==="pending"?a.jsx($As,{}):Ent(e)}):a.jsx("span",{className:Z("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Mi.colors,Mi.transform,{"[&>svg]:text-success-indicator":e==="success","[&>svg]:text-destructive-foreground":e==="failed","border border-dashed border-placeholder":e==="pending","[&>svg]:size-4":e!=="running","bg-success-subtle":e==="success","bg-destructive-subtle":e==="failed","scale-110":e==="success"||e==="failed"}),children:Ent(e)})}function MAs({step:e,isActive:t,position:n,variant:r="default"}){const s=t||e.status==="success"?"ink":"muted";return a.jsxs("div",{className:Z("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",Mi.colors,{"border border-transparent":r==="default","border-dashed border-placeholder bg-card":t&&r==="default"}),children:[a.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[a.jsxs(Y,{as:"span",tone:s,className:Z("flex min-w-6 justify-end",Mi.colors),children:[n,"."]}),a.jsxs("div",{className:"min-w-0",children:[a.jsx(Y,{as:"h4",tone:s,className:Mi.colors,children:e.title}),e.description&&a.jsx(Y,{tone:"faint",className:Z("-mt-0.5",{truncate:r==="plain"}),children:e.description})]})]}),a.jsx(RAs,{status:e.status,variant:r})]})}function DAs({currentStep:e,steps:t=[],className:n}){return a.jsx("div",{className:Z(n),children:t.map((r,s)=>a.jsx(MAs,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function LAs({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return a.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[a.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>a.jsx("div",{className:Z("relative flex h-8 items-center justify-end",Mi.colors,{"bg-success-subtle":r.status==="success"&&e?.[s-1]?.status==="success"}),children:a.jsx("div",{className:Z("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-fill text-column text-muted-foreground motion-reduce:transition-none",Mi.colors,Mi.transform,{"border border-dashed border-placeholder":r.status==="pending","scale-110 bg-success-subtle text-success-subtle-foreground":r.status==="success","scale-110 bg-destructive-subtle text-destructive-subtle-foreground":r.status==="failed"}),children:r.status==="running"?a.jsx(_n,{}):s+1})},r.id))}),a.jsxs("div",{className:Z("text-center text-caption text-muted-foreground",Mi.colors),children:[n," of ",t," steps completed"]})]})}function zAs({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(hee,{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(LAs,{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(kIn,{}),a.jsx(Y,{as:"span",variant:"body",className:"block",children:l||"Something went wrong"})]}),u&&a.jsx(DAs,{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(_n,{}),a.jsx(Y,{as:"p",variant:"body",children:"This may take some time..."})]})]})}function FAs({name:e,installedEntities:t}){return a.jsxs(hee,{className:Z("grid content-center items-center justify-items-center gap-4","[&>svg]:h-8 [&>svg]:w-8"),children:[a.jsx(Ght,{}),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(ZIe,{data:t})]})}function BAs(){const{templateSlug:e}=jr(),t=[{id:"templates",label:"Templates",to:"/templates"},{id:"template",label:Pke(e)}],[n,r]=ci(),[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:A}=mAs({repoOrSlug:e,owner:"mastra-ai"}),L=TAs?.includes("beta")??!1?"beta":"main",{data:F,isLoading:Q}=gAs({repo:I?.githubUrl?new URL(I.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:L}),{data:q,isLoading:B}=vAs(),{mutateAsync:V,isPending:H}=yAs(),{mutateAsync:D}=xAs(),{streamInstall:K,streamResult:M,isStreaming:$}=wAs({workflowInfo:q}),{observeInstall:z,streamResult:U,isStreaming:G}=SAs({workflowInfo:q});g.useEffect(()=>{const re=n.get("runId");re&&!y&&!m&&!$&&!G&&(console.info("🔄 Checking completed run after hot reload:",{runId:re}),S(re),D({runId:re}).then(le=>{const pe=le.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:ke}=pe.result.validationResults,Ee=`Template installation completed but ${he} validation issue${he>1?"s":""} remain unresolved.`;v(Ee),N(ke||[])}else{const he=pe?.result?.message||pe?.result?.error||"Template installation failed";v(typeof he=="string"?he:String(he))}}).catch(le=>{console.error("❌ Failed to fetch run details:",le),v("Failed to retrieve installation status after reload")}))},[n,y,m,$,G,D]),g.useEffect(()=>{const re=n.get("runId"),le=n.get("resume"),pe=n.get("provider");if(re&&le==="true"&&pe&&!$&&!G&&!k&&!C&&q){S(re),j(!0);try{D({runId:re}).then(ve=>{if(ve.snapshot?.status==="running")return z.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,$,G,k,C,q,D,z,r]);const ne=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],X=[{key:"tools",label:"Tools",value:I?.tools?.length?I.tools.map(re=>re).join(", "):"n/a",icon:a.jsx(fd,{})},{key:"agents",label:"Agents",value:I?.agents?.length?I.agents.map(re=>re).join(", "):"n/a",icon:a.jsx(Uo,{})},{key:"workflows",label:"Workflows",value:I?.workflows?.length?I.workflows.map(re=>re).join(", "):"n/a",icon:a.jsx(yk,{})},{key:"providers",label:"Providers",value:I?.supportedProviders?.length?I.supportedProviders.join(", "):"n/a",icon:a.jsx(j0,{})},{key:"tags",label:"Tags",value:I?.tags?.length?I.tags.join(", "):"n/a",icon:a.jsx(Nx,{})}],ee=[{...X[0]},{...X[1]},{...X[2]}].filter(re=>re.value!=="n/a");g.useEffect(()=>{F&&f(F)},[F]),g.useEffect(()=>{const re=M||U;re?.phase==="error"&&re?.error&&v(typeof re.error=="string"?re.error:String(re.error))},[M?.phase,M?.error,U?.phase,U?.error]);const ie=re=>{i(re)},fe=async re=>(l(re.provider),u(re.modelId),{message:"Model updated successfully"}),te=async()=>{const re=Object.entries(d).reduce((le,[pe,ve])=>(ve===""&&le.push(pe),le),[]);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:L,slug:I.slug,variables:d},{runId:ve}=await V({});S(ve),r(he=>{const ke=new URLSearchParams(he);return ke.set("runId",ve),ke.set("resume","true"),ke.set("provider",s||"openai"),ke}),await K.mutateAsync({inputData:pe,selectedModel:{provider:o,modelId:c},runId:ve})}catch(le){T(!1),v(le?.message||"Template installation failed"),console.error("Template installation failed",le)}}},se=re=>{const{name:le,value:pe}=re.target;pe.trim()===""?p(ve=>[...ve,le]):p(ve=>ve.filter(he=>he!==le)),f(ve=>({...ve,[le]:pe}))};return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:Z("h-full w-full overflow-y-scroll lg:px-12"),children:a.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-4",children:[a.jsx(PAs,{isLoading:A,title:I?.title,description:I?.longDescription,imageURL:I?.imageURL,githubUrl:I?.githubUrl,infoData:X,templateSlug:e}),I&&a.jsxs(a.Fragment,{children:[($||G)&&a.jsx(zAs,{name:I.title,streamResult:G?U:M,runId:b,workflowInfo:q}),y&&a.jsx(FAs,{name:I.title,installedEntities:ee,linkComponent:ac}),m&&a.jsx(EAs,{errorMsg:m,validationErrors:_.length>0?_:M?.validationResults?.errors||U?.validationResults?.errors}),!$&&!G&&!y&&!m&&a.jsx(AAs,{providerOptions:ne,selectedProvider:s,onProviderChange:ie,variables:d,setVariables:f,errors:h,setErrors:p,handleInstallTemplate:te,handleVariableChange:se,isLoadingEnvVars:Q||B,isInstalling:H,defaultModelProvider:o,defaultModelId:c,onModelUpdate:fe})]})]})})]})}const UAs=()=>a.jsx(Xt,{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(ue,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/workflows/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Workflows Documentation"}),variant:"fill"});function VAs(e,t,n){return Uk(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 qAs(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function QAs(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 ZAs(e,t,n){const r=QAs(t),s=[],i=(o,l,c,u,d,f)=>{const h=qAs(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 Int="auto 24rem minmax(0, 1fr) auto auto auto";function xQt({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 bQt({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(Ln,"relative grid size-5 shrink-0 place-items-center before:absolute before:-inset-1.5 before:content-['']"),onClick:i=>{i.stopPropagation(),n()},children:a.jsx(Ha,{direction:"right",className:"size-4"})}):a.jsx("span",{className:"size-5 shrink-0","aria-hidden":!0})})}const WAs=e=>e.stopPropagation();function eB({sortKey:e,sort:t,onSortChange:n,children:r}){return n?a.jsx(_e.SortableTopCell,{sortKey:e,sort:t?.key===e?t.direction:void 0,onSortChange:s=>n(s,e),children:r}):a.jsx(_e.TopCell,{children:r})}function HAs({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:s}){const{paths:i,Link:o}=Tn(),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(_e.RowWrapper,{...s,onSelectRow:()=>l.current?.click(),children:[a.jsx(bQt,{row:e,isExpanded:t,onToggle:n}),a.jsxs(_e.RowLink,{ref:l,colStart:2,to:i.workflowLink(c.id),LinkComponent:o,tabIndex:-1,onClick:WAs,children:[a.jsx(_e.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-1.5",children:[e.depth>0?a.jsx(xQt,{guides:e.guides,isLastChild:e.isLastChild}):null,a.jsx("span",{className:"truncate",children:d}),c.origin==="dynamic"?a.jsx(Mt,{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(yk,{"aria-hidden":!0,className:"size-3.5"}),u.length]}):null]})}),a.jsx(_e.DescriptionCell,{children:f}),a.jsx(_e.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(_e.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(_S,{"aria-hidden":!0,className:"size-3.5"}),m]}):""}),a.jsx(_e.TextCell,{className:"text-center",children:h||""})]})]})}function GAs({workflows:e,isLoading:t,search:n="",sort:r,onSortChange:s,requestContext:i}){const[o,l]=g.useState(new Set),c=Q2n({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(()=>VAs(d,r,c),[d,r,c]),h=g.useMemo(()=>ZAs(f,e,o),[f,e,o]),p=g.useMemo(()=>{const x=new Map;for(const b of h)b.kind==="workflow"&&x.set(b.pathKey,x.size);return x},[h]),{containerRef:m,getRowProps:v}=Fu({count:p.size,global:!0}),y=x=>{l(b=>{const S=new Set(b);return S.has(x)?S.delete(x):S.add(x),S})};return t?a.jsx(Lu,{columns:Int,fit:"container"}):a.jsxs(_e,{columns:Int,fit:"container",scrollRef:m,children:[a.jsxs(_e.Top,{children:[a.jsx(_e.TopCell,{children:a.jsx("span",{className:"sr-only",children:"Expand"})}),a.jsx(eB,{sortKey:"name",sort:r,onSortChange:s,children:"Name"}),a.jsx(_e.TopCell,{children:"Description"}),a.jsx(eB,{sortKey:"running",sort:r,onSortChange:s,children:"Running"}),a.jsx(eB,{sortKey:"suspended",sort:r,onSortChange:s,children:"Pending input"}),a.jsx(eB,{sortKey:"steps",sort:r,onSortChange:s,children:"Number of steps"})]}),h.length===0&&n?a.jsx(_e.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(_e.RowStatic,{className:"gap-0 px-0",children:[a.jsx(bQt,{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(_e.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(xQt,{guides:x.guides,isLastChild:x.isLastChild}),a.jsx("span",{className:"truncate",children:cf(x.stepId,50)}),a.jsxs(Fn,{children:[a.jsx(Mn,{render:a.jsx(Y,{as:"span",variant:"body-sm",tone:"muted"}),role:"note",tabIndex:0,className:Z("shrink-0 rounded-sm",ji),children:"not registered"}),a.jsx(Dn,{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(_e.DescriptionCell,{children:cf(x.description??"",200)}),a.jsx(_e.TextCell,{className:"text-center",children:""}),a.jsx(_e.TextCell,{className:"text-center",children:""}),a.jsx(_e.TextCell,{className:"text-center",children:""})]})]},`workflow-${x.pathKey}`):a.jsx(HAs,{row:x,isExpanded:b,onToggle:S,runCount:c[x.workflow.id],rowProps:v(p.get(x.pathKey)??-1)},`workflow-${x.pathKey}`)})]})}const UM=[Ts("/workflows")];function KAs(){const{data:e,isLoading:t,error:n}=ng(),[r,s]=g.useState(""),[i,o]=g.useState();return n&&Cs(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(ui,{variant:"fill"})]}):n&&_s(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Gs,{variant:"fill",resource:"workflows"})]}):n?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Xt,{tone:"error",variant:"fill",titleSlot:"Failed to load workflows",descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(UAs,{})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UM}),actionRow:a.jsxs(ar,{children:[a.jsx(ar.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(pf,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})})}),a.jsx(ar.End,{children:a.jsx(ue,{render:a.jsx(ac,{to:"/workflows/schedules"}),variant:"primary",icon:a.jsx(C0,{}),children:"Schedules"})})]}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(GAs,{workflows:e||{},isLoading:t,search:r,sort:i,onSortChange:(l,c)=>o({key:c,direction:l})})]})}const YAs={active:"bg-success-indicator",paused:"bg-info-indicator",completed:"bg-muted-foreground"},XAs={active:"text-success-indicator",paused:"text-info-indicator",completed:"text-muted-foreground"},wQt=({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 ${YAs[e]}`,"aria-hidden":!0}),a.jsx(Y,{as:"span",variant:"caption",className:XAs[e],children:e})]});function SQt({status:e}){const{icon:t,color:n}=JAs(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 JAs(e){switch(e){case"success":return{icon:a.jsx(ur,{size:14}),color:"text-success-indicator"};case"failed":return{icon:a.jsx(zn,{size:14}),color:"text-destructive-foreground"};case"running":return{icon:a.jsx(_n,{}),color:"text-muted-foreground"};case"suspended":return{icon:a.jsx(WH,{size:14}),color:"text-info-indicator"};case"canceled":return{icon:a.jsx(aL,{size:14}),color:"text-muted-foreground"};case"pending":case"waiting":return{icon:a.jsx(fC,{size:14}),color:"text-muted-foreground"};default:return{icon:null,color:"text-muted-foreground"}}}const Nnt="auto auto auto auto 1fr",ePs=3e4,tPs=5*6e4;function nPs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:i}){const{Link:o,paths:l}=Tn(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=Fu({count:u});let h=-1;return t?a.jsx(Lu,{columns:Nnt}):e.length===0?a.jsx(Y,{variant:"body",tone:"muted",className:"p-4",children:"No trigger history yet."}):a.jsxs(_e,{columns:Nnt,className:"min-w-0",scrollRef:d,children:[a.jsxs(_e.Top,{children:[a.jsx(_e.TopCell,{children:"Run"}),a.jsx(_e.TopCell,{children:"Status"}),a.jsx(_e.TopCell,{children:"Started"}),a.jsx(_e.TopCell,{children:"Duration"}),a.jsx(_e.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=Vc(m,{signed:!0}),y=p.outcome==="failed",x=y?p.error:p.run?.error,b=Math.abs(m),S=!y&&b>ePs&&b<=tPs,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(_e.Cell,{children:C}),a.jsx(_e.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(Yd,{size:14}),"publish failed"]}):p.run?a.jsx(SQt,{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(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-destructive-foreground",children:a.jsx(Yd,{size:14})})}),a.jsx(Dn,{children:x})]}):null]})}),a.jsx(_e.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[p.actualFireAt?a.jsx(DI,{value:p.actualFireAt}):"—",S?a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-info-indicator",children:a.jsx(Yd,{size:14})})}),a.jsxs(Dn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),a.jsx(_e.Cell,{children:p.run?a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",children:Vc(p.run.durationMs)||"—"}):a.jsx("span",{className:"text-muted-foreground",children:"—"})}),a.jsx(_e.Cell,{children:" "})]});return j?a.jsx(_e.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:o,...f(h),children:T},k):a.jsx(_e.RowStatic,{children:T},k)}),a.jsx(_e.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:i})]})}const kQt={id:"workflow-schedules",label:"Schedules",icon:C0,to:"/workflows/schedules"};function tB({label:e,children:t}){return a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"uppercase",children:e}),a.jsx("div",{children:a.jsx(Y,{as:"span",variant:"body",className:"block",children:t})})]})}function rPs(){const{scheduleId:e}=jr(),t=[Ts("/workflows"),kQt,{id:"schedule",label:Pke(e),icon:C0}],{paths:n}=Tn(),{data:r,error:s}=Eur({scheduleId:e,queryOptions:{enabled:!!e}}),{data:i,isLoading:o,error:l,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d}=Iur({scheduleId:e,queryOptions:{enabled:!!e}}),f=Nur({scheduleId:e});if(s&&Cs(s))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(ui,{variant:"fill"})]});if(s&&_s(s))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Gs,{variant:"fill",resource:"schedules"})]});if(s)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Xt,{tone:"error",variant:"fill",titleSlot:"Failed to load schedule",descriptionSlot:s.message})]});const h=r?.workflowId,p=r?.agentId;return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),actionRow:a.jsx(ar,{children:a.jsxs(ar.End,{children:[a.jsx(ue,{render:a.jsx(ac,{to:n.schedulesLink()}),variant:"ghost",icon:a.jsx(vd,{}),children:"Back to schedules"}),h?a.jsx(ue,{icon:a.jsx(Ol,{}),render:a.jsx(ac,{to:n.workflowLink(h)}),variant:"ghost",children:"Open workflow"}):null,r?a.jsx(ue,{onClick:()=>{const m=r.status==="active"?"pause":"resume";f.mutate(m,{onSuccess:()=>Ye.success(m==="pause"?"Schedule paused":"Schedule resumed"),onError:v=>Ye.error(v.message)})},disabled:f.isPending,"data-testid":"schedule-toggle-button",children:r.status==="active"?a.jsxs(a.Fragment,{children:[a.jsx(_S,{}),"Pause"]}):a.jsxs(a.Fragment,{children:[a.jsx(Uc,{}),"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(tB,{label:p?"Agent":"Workflow",children:h?a.jsx(ac,{to:n.workflowLink(h),className:"text-foreground hover:underline",children:h}):p?a.jsx(ac,{to:n.agentLink(p),className:"text-foreground hover:underline",children:p}):"—"}),a.jsxs(tB,{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(tB,{label:"Status",children:a.jsx(wQt,{status:r.status})}),a.jsx(tB,{label:"Next fire",children:r.nextFireAt?a.jsx(DI,{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(Xt,{tone:"error",titleSlot:"Failed to load trigger history",descriptionSlot:l.message}):a.jsx(nPs,{triggers:i??[],isLoading:o,workflowId:h,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d})]})]}):null]})}const sPs={target:e=>e.workflowId??e.agentId??"",status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},Ant="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function iPs({schedules:e,isLoading:t,search:n="",sort:r,onSortChange:s}){const{paths:i,Link:o}=Tn(),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 Uk(h,r,sPs)},[e,n,r]),{containerRef:c,getRowProps:u}=Fu({count:l.length,global:!0});if(t)return a.jsx(Lu,{columns:Ant});const d=(f,h)=>s?a.jsx(_e.SortableTopCell,{sortKey:f,sort:r?.key===f?r.direction:void 0,onSortChange:s,children:h}):a.jsx(_e.TopCell,{children:h});return a.jsxs(_e,{columns:Ant,className:"min-w-0",scrollRef:c,children:[a.jsxs(_e.Top,{children:[d("target","Target"),a.jsx(_e.TopCell,{children:"Schedule ID"}),a.jsx(_e.TopCell,{children:"Cron"}),d("status","Status"),d("nextFireAt","Next fire"),d("lastFireAt","Last run")]}),l.length===0&&n?a.jsx(_e.NoMatch,{message:"No schedules match your search"}):null,l.length===0&&!n?a.jsx(_e.NoMatch,{message:"No schedules configured"}):null,l.map((f,h)=>a.jsxs(_e.RowLink,{to:i.scheduleLink(f.id),LinkComponent:o,...u(h),children:[a.jsx(_e.NameCell,{children:f.workflowId??f.agentId}),a.jsx(_e.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(_e.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(_e.Cell,{children:a.jsx(wQt,{status:f.status})}),a.jsx(_e.Cell,{children:f.nextFireAt?a.jsx(DI,{value:f.nextFireAt}):"—"}),a.jsx(_e.Cell,{children:f.lastRun?a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx(SQt,{status:f.lastRun.status}),f.lastFireAt?a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:a.jsx(DI,{value:f.lastFireAt})}):null]}):f.lastFireAt?a.jsx(DI,{value:f.lastFireAt}):a.jsx("span",{className:"text-muted-foreground",children:"Never"})})]},f.id))]})}function OQt({workflowId:e}={}){const{data:t,isLoading:n,error:r}=TK(e?{workflowId:e}:{}),[s,i]=g.useState(""),[o,l]=g.useState();return r?a.jsx(Xt,{tone:"error",titleSlot:"Failed to load schedules",descriptionSlot:r.message}):a.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[a.jsx("div",{className:"max-w-120",children:a.jsx(pf,{onSearch:i,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),a.jsx("div",{className:"overflow-y-auto",children:a.jsx(iPs,{schedules:t??[],isLoading:n,search:s,sort:o,onSortChange:(c,u)=>l({key:u,direction:c})})})]})}const Tue=[Ts("/workflows"),kQt];function oPs(){const[e]=ci(),t=e.get("workflowId")??void 0,{error:n}=TK(t?{workflowId:t}:{});return n&&Cs(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Tue}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(ui,{variant:"fill"})]}):n&&_s(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Tue}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(Gs,{variant:"fill",resource:"schedules"})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Tue}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx("div",{className:"h-full",children:a.jsx(OQt,{workflowId:t})})]})}const aPs={"--belt-hue":"var(--warning-indicator)"};function lPs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function cPs(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 uPs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:a.jsxs("section",{className:Z(vke,"pointer-events-auto relative isolate"),"data-testid":"workflow-suspended-steps","aria-label":"Step suspended",children:[a.jsxs("div",{className:"max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]",children:[a.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border bg-background px-5 py-4",children:[a.jsxs(Y,{as:"h2",variant:"column",tone:"ink",className:"flex items-center gap-2",children:[a.jsx(At,{children:a.jsx(WH,{})}),"Step suspended"]}),a.jsx(Mt,{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?$S(hC(i.resumeSchema)):Nf(Cn(),Bf());return a.jsx(dPs,{step:s,stepSchema:o,description:i.description,onResume:r},`${s.runId}-${s.stepId}`)})]}),a.jsx(J4t,{status:"ready",label:"Needs input",className:"before:hidden",style:aPs})]})}function dPs({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){Ye.error(d instanceof Error?d.message:"Error resuming workflow")}finally{l(!1)}};return a.jsxs("div",{className:"space-y-5 p-5 [&+&]:border-t [&+&]:border-border",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(Y,{as:"p",variant:"subheading",tone:"ink",className:"break-words",children:e.stepId}),n&&a.jsx(Y,{as:"p",variant:"caption",tone:"muted",children:n})]}),e.suspendPayload!==void 0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs(Y,{as:"p",variant:"caption",tone:"muted",className:"flex items-center gap-2",children:[a.jsx(At,{children:a.jsx(fIn,{})}),"The step is asking"]}),a.jsxs(gc,{open:s,onOpenChange:i,children:[a.jsxs(Hl,{className:Z(pr,"flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5"),children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[a.jsx(At,{children:a.jsx(Ha,{direction:"right",className:"text-muted-foreground"})}),a.jsx(Y,{as:"span",variant:"body",tone:"ink",className:"truncate",children:cPs(e.suspendPayload,e.stepId)})]}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"shrink-0",children:lPs(e.suspendPayload)})]}),a.jsx(Gl,{children:a.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:a.jsx(Or,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs(Y,{as:"p",variant:"caption",tone:"muted",className:"flex items-center gap-2",children:[a.jsx(At,{children:a.jsx(gIn,{})}),"Your response"]}),a.jsx("div",{className:"-mx-5",children:a.jsx(lke,{schema:t,isSubmitLoading:o,submitButtonLabel:"Resume",submitButtonVariant:"primary",submitButtonIcon:a.jsx(Uc,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:c})})]})]})}function fPs({hidden:e,requestContext:t,canResume:n}){const{result:r,workflow:s,runId:i,isStreamingWorkflow:o}=g.useContext(Zl),l=mvt(r,i),c=f9n(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(uPs,{suspendedSteps:l,workflow:s,isStreaming:o,onResume:c})},i)}const Pnt={success:{label:"Completed",icon:ur},failed:{label:"Failed",icon:X0e},suspended:{label:"Needs input",icon:_S},waiting:{label:"Waiting",icon:gx},paused:{label:"Paused",icon:_S},skipped:{label:"Skipped",icon:INn},running:{label:"Running",icon:fc},canceled:{label:"Canceled",icon:aL}},hPs={label:"Status unavailable",icon:Q_n};function pPs({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:s,onOpenInput:i,onOpenOutput:o}){const l=Object.hasOwn(Pnt,e.status)?Pnt[e.status]:hPs,c=l.icon,u=wSe(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",ji),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",p1t[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(twe,{"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",rJn[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:Vc(e.timing.durationMs)}):a.jsx("span",{"aria-label":"Timing unavailable",children:"—"})}),a.jsxs("div",{className:"flex items-center",children:[a.jsx(ue,{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(VH,{})}),a.jsx(ue,{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(QH,{})})]})]})}const mPs=e=>e.includes("."),gPs=e=>e==="input"||e.endsWith(".input"),$nt=1;function vPs(e,t){const n=SSe(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 yPs(e,t){const n=Object.entries(e).filter(([l])=>!gPs(l)).map(([l,c])=>({stepId:l,step:c,...vPs(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-$nt),v=Math.min(Math.max(p/o*100,$nt),100-m);h={durationMs:p,offsetPct:m,widthPct:v}}return{stepId:l,step:c,status:XG(c)?"suspended":c.status,timing:h,spansSuspension:f,isRunning:d,isNestedEntry:mPs(l)}})}function xPs(){const{steps:e}=p$(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=dG(),[i,o]=g.useState(()=>Date.now()),[l,c]=g.useState(!0),[u,d]=g.useState(!1),{showData:f}=_k(),h=g.useRef(null),p=yPs(e,i),m=p.some(v=>v.isRunning);return GSt(h,{enabled:m&&!l}),g.useEffect(()=>{if(!m||l)return;const v=setInterval(()=>o(Date.now()),100);return()=>clearInterval(v)},[m,l]),p.length===0?null:a.jsx("div",{"data-testid":"workflow-timeline",className:"relative z-20 shrink-0 px-2 pb-2",children:a.jsxs(gc,{open:!l,onOpenChange:v=>c(!v),className:Z(pr,"@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl"),children:[a.jsxs("div",{className:"flex items-center",children:[a.jsxs(Hl,{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(jht,{"aria-hidden":!0,className:"size-4 text-muted-foreground"})}),a.jsx("span",{children:"Timeline"}),a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",children:[p.length," events"]}),a.jsx("span",{className:"ml-auto",children:a.jsx(Ha,{direction:"right",className:"size-4"})})]}),!l&&a.jsx(ue,{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(__n,{}):a.jsx(_ht,{})})]}),a.jsx(Gl,{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(pPs,{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 bPs=({workflowId:e,workflow:t,isLoading:n})=>{const[r]=xr("workflow",e),{canExecute:s,isLoading:i}=Za(),{stepDetail:o}=_k(),l=Ck(),c=o?.type==="data",u=a.jsxs("div",{className:"[container-type:size] relative h-full min-h-0",children:[a.jsx(g5t,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),a.jsx(fPs,{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(bU,{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(xPs,{})})]});return l&&o&&!c?a.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:a.jsx(bU,{requestContext:r})}):a.jsxs("div",{className:"relative h-full min-h-0",children:[u,a.jsxs(x$,{className:"pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2",children:[a.jsx(ap,{id:"workflow-graph",className:"pointer-events-none min-w-0"}),o&&!c&&a.jsxs(a.Fragment,{children:[a.jsx(ak,{className:"pointer-events-auto"}),a.jsx(ap,{id:"workflow-step-detail",minSize:300,maxSize:"60%",defaultSize:420,className:"min-w-0",children:a.jsx("div",{className:"pointer-events-auto h-full min-h-0 overflow-hidden rounded-studio-panel border border-border bg-background",children:a.jsx(bU,{requestContext:r})})})]})]})]})},Rnt=()=>{const{workflowId:e}=jr(),{data:t,isLoading:n,error:r}=yL({workflowId:e,requestContext:xr("workflow",e)[0],queryOptions:{enabled:!!e}});return r&&Cs(r)?a.jsx(ui,{variant:"fill"}):r&&_s(r)?a.jsx(Gs,{variant:"fill",resource:"workflows"}):a.jsx(bPs,{workflowId:e,workflow:t??void 0,isLoading:n})};function wPs(){const{workflowId:e}=jr(),{error:t}=TK(e?{workflowId:e}:{});if(!e)return null;let n;return t&&Cs(t)?n=a.jsx(ui,{variant:"fill"}):t&&_s(t)?n=a.jsx(Gs,{variant:"fill",resource:"schedules"}):n=a.jsx("div",{className:"h-full",children:a.jsx(OQt,{workflowId:e})}),a.jsxs(It,{children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),n]})}function SPs(){const{workflowId:e}=jr();return e?a.jsx(rAe,{scopedEntityId:e,scopedEntityType:od.WORKFLOW_RUN}):null}const jQt=g.createContext(null);function tu(){const e=g.useContext(jQt);if(!e)throw new Error("Workspace components must be rendered inside <Workspace.Root>");return e}const kPs=e=>e?.status;function OPs(e,t){return Cs(e)?"Your session has expired. Sign in again to continue.":_s(e)?"You don't have permission to access this.":Ik(e)?"This path no longer exists.":kPs(e)===501?"This workspace does not support this operation.":t}function pee({error:e,fallback:t,className:n}){return a.jsx(Wt,{variant:"destructive",className:n,children:a.jsx(Wt.Message,{children:OPs(e,t)})})}const jPs=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function CPs(e){const t=jPs.exec(e);return t?{frontmatter:t[1]??"",body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function _Ps({content:e}){const{frontmatter:t,body:n}=CPs(e);return a.jsxs(a.Fragment,{children:[t!==null&&a.jsx("div",{"data-testid":"workspace-frontmatter",className:"border-b border-border",children:a.jsx(a$,{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(ql,{children:n})})]})}function TPs(){const{activeFilePath:e}=tu();return e?a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",tone:"muted",className:"truncate","data-testid":"workspace-file-path",children:e}):null}function EPs({path:e,content:t,mimeType:n}){return nRt(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"})}):rRt(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:${jGe(e,n)};base64,${t}`,type:jGe(e,n)})})}):szr(e)?a.jsx(_Ps,{content:t}):a.jsx(a$,{code:t,lang:MOt(e),overflow:"scroll",className:"rounded-none border-0 bg-transparent [&_pre]:p-4"})}function IPs({renderPreview:e}){const{workspaceId:t,activeFilePath:n}=tu(),{data:r,isLoading:s,error:i}=hzr({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(xt,{className:"h-4 w-1/2"}),a.jsx(xt,{className:"h-4 w-5/6"}),a.jsx(xt,{className:"h-4 w-2/3"})]});if(!r)return a.jsx(pee,{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(EPs,{...o})}const HA=".",CQt=(e,t)=>e===HA?t:`${e}/${t}`,Mnt=e=>e.split("/").slice(0,-1).map((t,n,r)=>r.slice(0,n+1).join("/")),_Qt=e=>{const t=e.lastIndexOf("/");return t===-1?HA:e.slice(0,t)};function TQt({labeled:e=!1}={}){const{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=tu(),s=mr(),[i,o]=g.useState(!1),[l,c]=g.useState(""),[u,d]=g.useState(!1);if(!n||r(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",_Qt(f)]}),o(!1),c("")}catch{}finally{d(!1)}}};return a.jsxs(a.Fragment,{children:[e?a.jsx(ue,{variant:"ghost",icon:a.jsx(jS,{}),onClick:()=>o(!0),children:"New folder"}):a.jsx(ue,{variant:"ghost",size:"icon-sm",tooltip:"New folder",onClick:()=>o(!0),children:a.jsx(jS,{})}),a.jsx(Kr,{open:i,onOpenChange:o,pending:u,children:a.jsx(Yr,{size:"sm",children:a.jsxs("form",{onSubmit:p=>{p.preventDefault(),h()},children:[a.jsx(Xr,{children:a.jsx(Qr,{children:"New folder"})}),a.jsx(qr,{children:a.jsx(wn,{autoFocus:!0,"aria-label":"Folder path",placeholder:"docs/guides",value:l,onChange:p=>c(p.target.value)})}),a.jsxs(Yo,{children:[a.jsx(Ca,{children:"Cancel"}),a.jsx(ue,{type:"submit",variant:"primary",disabled:!f||u,children:"Create"})]})]})})})]})}function Dnt(e){return`${e.topSource}/${e.name}`}function Lnt(e){const t=sRt(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function NPs({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}=ozr({workspaceId:n,queryOptions:{enabled:!!n}}),b=izr({workspaceId:n}),S=g.useMemo(()=>f?.topSource?sRt(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}=azr({workspaceId:n,owner:S?.owner,repo:S?.repo,skillPath:f?.name,queryOptions:{enabled:!!n&&!!S&&!!f}}),T=lw(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,A=u.trim().length>=2,P=g.useMemo(()=>{if(!f)return!1;const Q=Lnt(f);return!!(Q&&i.includes(Q)||o.includes(f.name))},[f,i,o]),L=g.useCallback(()=>{!f||!S||r({repository:`${S.owner}/${S.repo}`,skillName:f.name,mount:l&&l.length>1?v:void 0})},[f,S,r,l,v]),F=g.useCallback(Q=>{Q||(d(""),h(null),m(void 0)),t(Q)},[t]);return a.jsx(Kr,{open:e,onOpenChange:F,pending:s,children:a.jsxs(Yr,{size:"xl",className:"h-[80vh]",children:[a.jsxs(Xr,{children:[a.jsx(Qr,{children:"Add Skill"}),a.jsx(Lo,{children:"Search and install skills from the community registry"})]}),a.jsxs(qr,{layout:"fill",children:[a.jsx(Zc,{label:"Search skills",placeholder:"Search skills...",value:u,onValueChange:_}),a.jsxs("div",{className:"flex min-h-0 flex-1 gap-4",children:[a.jsxs("div",{className:"flex min-h-0 w-1/2 flex-col",children:[a.jsx(Y,{as:"p",variant:"eyebrow",tone:"muted",className:"mb-2",children:A?"Search Results":"Popular Skills"}),a.jsx(Ir,{className:"flex-1 rounded-lg border border-border",children:a.jsx(of,{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(fc,{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(aL,{className:"mb-2 size-8"}),a.jsx(Y,{children:A?"No skills found":"No skills available"})]}):a.jsx("div",{className:"space-y-1 p-2",children:N.map(Q=>{const q=Dnt(Q),B=Lnt(Q),V=B&&i.includes(B)||o.includes(Q.name),H=f?Dnt(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(ur,{className:"size-2.5"}),"Installed"]})]}),a.jsx(Y,{as:"p",variant:"caption",tone:"muted",className:"truncate",children:Q.topSource})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-1 text-muted-foreground",children:[a.jsx(fp,{className:"size-3"}),a.jsx(Y,{as:"span",variant:"caption",children:Q.installs.toLocaleString()})]})]})},q)})})})})]}),a.jsxs("div",{className:"flex min-h-0 w-1/2 flex-col",children:[a.jsx(Y,{as:"p",variant:"eyebrow",tone:"muted",className:"mb-2",children:"Preview"}),a.jsx("div",{className:"flex flex-1 flex-col overflow-hidden rounded-lg border border-border",children:f?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"border-b border-border bg-card p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"rounded-lg bg-muted p-2",children:a.jsx(F6,{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(bX,{className:"size-3"}),a.jsx(Y,{as:"span",variant:"caption",className:"block",children:f.topSource})]}),a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(fp,{className:"size-3"}),a.jsxs(Y,{as:"span",variant:"caption",className:"block",children:[f.installs.toLocaleString()," installs"]})]})]})]}),S&&a.jsx("a",{href:`https://github.com/${S.owner}/${S.repo}`,target:"_blank",rel:"noopener noreferrer",className:Z(Ln,On),title:"View on GitHub",children:a.jsx(Zs,{className:"size-4"})})]})}),C?a.jsx("div",{className:"flex flex-1 items-center justify-center",children:a.jsx(fc,{className:"size-6 animate-spin text-muted-foreground"})}):j?a.jsx(Ir,{className:"flex-1",children:a.jsx("div",{className:"p-4",children:a.jsx(ql,{children:j})})}):a.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-muted-foreground",children:[a.jsx(K1,{className:"mb-2 size-8"}),a.jsx(Y,{children:"Preview unavailable"}),k&&a.jsxs("a",{href:k,target:"_blank",rel:"noopener noreferrer",className:"mt-2 flex items-center gap-1 text-info-indicator hover:underline",children:[a.jsxs(Y,{as:"span",variant:"caption",className:"block",children:["View on skills.sh"," "]}),a.jsx(Zs,{className:"size-3"})]})]})]}):a.jsxs("div",{className:"flex h-full flex-col items-center justify-center text-muted-foreground",children:[a.jsx(K1,{className:"mb-2 size-8"}),a.jsx(Y,{children:"Select a skill to preview"})]})})]})]}),f&&l&&l.length>1&&a.jsxs(ht,{orientation:"horizontal",className:Z(pr,"gap-3 rounded-lg p-3"),children:[a.jsx(xP,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx(ut,{className:"whitespace-nowrap",children:"Install to"}),a.jsxs(ps,{value:v,onValueChange:m,children:[a.jsx(gs,{className:"flex-1",children:a.jsx(ms,{})}),a.jsx(vs,{children:l.map(Q=>{const q=Q.displayName??Q.name??Q.provider??"unknown";return a.jsxs(hr,{value:Q.path,children:[q," (",Q.path,")"]},Q.path)})})]})]})]}),f&&a.jsxs(Yo,{children:[P&&l&&l.length>1&&(()=>{const Q=c?.[f.name];if(!Q)return null;const q=l.find(B=>Q.startsWith(B.path+"/")||Q===B.path);return q?a.jsxs(Y,{as:"span",variant:"caption",tone:"muted",className:"mr-auto",children:["Installed at ",q.path]}):null})(),a.jsx(Ca,{children:"Cancel"}),a.jsx(ja,{onConfirm:L,disabled:!S||P,"data-testid":"install-skill-button",children:s?"Installing...":P?"Already Installed":"Install"})]})]})})}function EQt({labeled:e=!1}){const{workspaceId:t,addSkill:n}=tu(),[r,s]=g.useState(!1),[i,o]=g.useState(!1);if(!n)return null;const{onInstall:l,...c}=n,u=async d=>{o(!0);try{await l(d),s(!1)}catch{}finally{o(!1)}};return a.jsxs(a.Fragment,{children:[e?a.jsxs(ue,{variant:"ghost",onClick:()=>s(!0),children:[a.jsx(Efe,{}),"Add skill"]}):a.jsx(ue,{variant:"ghost",size:"icon-sm","aria-label":"Add skill",tooltip:"Add skill",onClick:()=>s(!0),children:a.jsx(Efe,{})}),a.jsx(NPs,{...c,open:r,onOpenChange:s,workspaceId:t,onInstall:d=>{u(d)},isInstalling:i})]})}function APs({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(Mnt(t??""))),[b,S]=g.useState(t);if(t!==b){S(t);const C=Mnt(t??"").filter(T=>!y.has(T));C.length>0&&x(new Set([...y,...C]))}const k=i?.join(`
|
|
699
|
+
`).reduce((i,o)=>{if(!o||o.startsWith("#"))return i;const[l,c]=o.split("=");return l&&(i[l]=c?.split("")?.every(u=>u==="*")?"":c?.replaceAll('"',"")),i},{}):{}}const pAs=({queryOptions:e}={})=>_t({queryKey:["mastra-templates"],queryFn:gQt,...e}),mAs=({repoOrSlug:e,owner:t,queryOptions:n})=>_t({queryKey:["template-repo",e,t],queryFn:()=>fAs({repoOrSlug:e,owner:t}),...n}),gAs=({repo:e,owner:t,branch:n,queryOptions:r})=>_t({queryKey:["template-repo-env-vars",e,t,n],queryFn:()=>hAs({repo:e,owner:t,branch:n}),...r}),vAs=({queryOptions:e}={})=>{const t=Ge();return _t({queryKey:["agent-builder-workflow"],queryFn:async()=>await t.getAgentBuilderAction("merge-template").details(),...e})},yAs=({queryOptions:e}={})=>{const t=Ge();return Sn({mutationFn:async({runId:n})=>await t.getAgentBuilderAction("merge-template").createRun({runId:n}),...e})},xAs=({queryOptions:e}={})=>{const t=Ge();return Sn({mutationFn:async({runId:n})=>await t.getAgentBuilderAction("merge-template").runById(n),...e})},_nt=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)},Tnt=(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=_nt(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=_nt(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}},bAs=(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)}},vQt=(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}=Tnt(h,d,e);if(d=p,r(p),h.runId||c||t){const m=h.runId||c||t;bAs(m,p)}}}catch(f){console.error("💥 [processStream] Error processing template installation stream:",f);const{newState:h}=Tnt({type:"error",payload:{error:f instanceof Error?f.message:"Unknown error"}},d,e);r(h)}finally{i(!1),u.releaseLock()}}}},wAs=({workflowInfo:e,queryOptions:t}={})=>{const n=Ge(),{streamResult:r,isStreaming:s,processStream:i}=vQt(e);return{streamInstall:Sn({mutationFn:async({inputData:o,selectedModel:l,runId:c})=>{for(let d=1;d<=3;d++)try{const f=n.getAgentBuilderAction("merge-template"),h=new d_;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}},SAs=({workflowInfo:e,queryOptions:t}={})=>{const n=Ge(),{streamResult:r,isStreaming:s,processStream:i}=vQt(e);return{observeInstall:Sn({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 kAs(e){return e.replace(/\/$/,"").split("/").pop()}function OAs({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?a.jsx("div",{className:Z("grid gap-y-4",n),children:Array.from({length:5}).map((i,o)=>a.jsx("div",{className:"h-16 animate-pulse rounded-lg bg-card"},o))}):a.jsx("div",{className:Z("grid gap-y-4",n),children:e.map(i=>{const o=i?.agents||i?.tools||i?.networks||i?.workflows||i?.mcp;return a.jsxs("article",{className:Z(pr,"state-layer grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg"),children:[a.jsxs(s,{to:`/templates/${i.slug}`,className:Z("group grid",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":i.imageURL}),children:[i.imageURL&&a.jsx("div",{className:"overflow-hidden",children:a.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${i.imageURL})`}})}),a.jsxs("div",{className:Z("grid w-full gap-0.5 px-4 py-3","[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground"),children:[a.jsx(Y,{as:"h2",tone:"ink",children:i.title}),a.jsx(Y,{className:Z(vx,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(Uo,{})," ",i.agents.length]})}),i?.tools&&i.tools.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(fd,{})," ",i.tools.length]})}),i?.networks&&i.networks.length>0&&a.jsx("li",{children:a.jsxs(Y,{as:"span",variant:"body",className:"block",children:[a.jsx(Hht,{})," ",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(yk,{})," ",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(L_,{})," ",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",aht,vx,On),children:[a.jsx(bX,{})," ",kAs(i.githubUrl)]})})})]},i.slug)})})}function jAs({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(ps,{value:t,onValueChange:s,children:[a.jsx(gs,{"aria-label":"Filter by tag",size:"md",children:a.jsx(ms,{placeholder:"Select an option"})}),a.jsx(vs,{children:e.map(f=>a.jsx(hr,{value:f.value,children:f.label},f.value))})]}),a.jsxs(ps,{value:r,onValueChange:i,children:[a.jsx(gs,{"aria-label":"Filter by provider",size:"md",children:a.jsx(ms,{placeholder:"Select an option"})}),a.jsx(vs,{children:n.map(f=>a.jsx(hr,{value:f.value,children:f.label},f.value))})]}),c&&a.jsx(ue,{onClick:c,icon:a.jsx(zn,{}),children:"Reset"})]})}const CAs=[{id:"templates",label:"Templates"}];function _As(){const{data:e,isLoading:t}=pAs(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[i,o]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(b=>{f.push({value:b,label:b})});const h=[{value:"all",label:"Any provider"}];(s||[]).forEach(b=>{h.push({value:b,label:b})});const p=(b,S)=>{S==="tag"?o(b):S==="provider"&&c(b)},m=b=>{d(b)},v=()=>{o("all"),c("all"),d("")},y=n.filter(b=>!(u&&!b.title.toLowerCase().includes(u)&&!b.description.toLowerCase().includes(u)||i!=="all"&&!b.tags.includes(i)||l!=="all"&&!b.supportedProviders.includes(l))),x=u||i!=="all"||l!=="all";return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:CAs}),children:[a.jsx("h1",{className:"sr-only",children:"Templates"}),a.jsx(mL,{children:a.jsxs(hpt,{children:[a.jsx(At,{children:a.jsx(K1,{})}),"Templates"]})}),a.jsxs("div",{className:Z("z-10 h-full w-full overflow-y-auto px-5 pb-12"),children:[a.jsx(jAs,{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(OAs,{templates:y,linkComponent:ac,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const TAs="1.78.0-alpha.0";function hee({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 EAs({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(Yd,{className:"text-warning-foreground"}),title:"Template Installed with Warnings"}:{icon:a.jsx(TTn,{}),title:"Template Installation Failed"},{icon:l,title:c}=o();return a.jsxs(hee,{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(Ln,"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(jl,{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(Ln,"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(jl,{className:"text-caption wrap-break-word whitespace-pre-wrap",code:n})})]})]})}const IAs=g.createContext(null);function NAs(){const e=g.useContext(IAs);return e||{registerResetFn:()=>{},triggerReset:()=>{}}}const yQt=({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}=N6(),b=G0(),{models:S}=uw(),k=g.useMemo(()=>y?.providers||[],[y]);g.useEffect(()=>{l(t),u(e||"")},[t,e]);const j=io(c),T=ZI(k,j)?.id||j,_=async F=>{if(l(F),F&&T){f(!0);try{const Q=await n({provider:T,modelId:F});console.info("Model updated:",Q)}catch(Q){console.error("Failed to update model:",Q)}finally{f(!1)}}},N=F=>{const Q=io(F);u(Q),Q!==j&&(l(""),v(!0))},{registerResetFn:I}=NAs();if(g.useEffect(()=>(I(()=>{if(h||m)return;if(j&&j!==s&&(!o||o==="")){u(io(s)),l(i);const V=ZI(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(_n,{}),a.jsx(Y,{as:"span",tone:"muted",children:"Loading providers..."})]});const A=async()=>{if(!r){console.warn("Reset model function not provided");return}try{f(!0),await r()}catch(F){console.error("Failed to reset model:",F)}finally{f(!1)}},P=ZI(k,j);if(b.active&&b.pickerVisible===!1){const F=b.default&&b.default.provider&&b.default.modelId?`${b.default.provider}/${b.default.modelId}`:c&&o?`${c}/${o}`:"Locked by admin";return a.jsxs("div",{className:Z(pr,"flex items-center gap-2 rounded-md px-3 py-2"),"data-testid":"agent-metadata-model-locked",children:[a.jsx(Au,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),a.jsx(Y,{as:"span",variant:"caption",tone:"ink",className:"truncate",children:F}),a.jsx(Y,{as:"span",variant:"meta",tone:"muted",className:"ml-auto shrink-0",children:"Set by admin"})]})}const L=!!(j&&o)&&b.active&&b.allowed!==void 0&&!S.some(F=>io(F.provider)===j&&F.model===o);return a.jsxs("div",{className:"@container",children:[a.jsxs("div",{className:"flex w-full flex-col items-stretch gap-2 @xs:flex-row @xs:items-center",children:[a.jsx("div",{className:"w-full @xs:w-2/5",children:a.jsx(Mk,{value:j,onValueChange:N,open:h,onOpenChange:p})}),a.jsx("div",{className:"w-full @xs:w-3/5",children:a.jsx(Dk,{llmId:j,value:o,onValueChange:_,open:m,onOpenChange:v})}),a.jsx(ue,{variant:"default",size:"md",onClick:A,disabled:d,className:"flex items-center gap-1.5 border-0! whitespace-nowrap",title:"Reset to original model",children:a.jsx(T_,{className:"h-3.5 w-3.5"})})]}),L&&a.jsx("div",{className:"p-2 pt-2","data-testid":"agent-metadata-model-stale-warning",children:a.jsx(Wt,{variant:"warning",title:"Model not allowed",children:a.jsxs(Wt.Message,{children:[a.jsxs("code",{className:"rounded bg-fill-hover px-1 py-0.5",children:[c,"/",o]})," ","is no longer allowed by the admin policy. Pick a different model to save changes."]})})}),P&&!P.connected&&a.jsx("div",{className:"p-2 pt-2",children:a.jsx(Wt,{variant:"warning",title:"Provider not connected",children:a.jsxs(Wt.Message,{children:["Set the"," ",a.jsx("code",{className:"rounded bg-fill-hover px-1 py-0.5",children:Array.isArray(P.envVar)?P.envVar.join(", "):P.envVar})," ","environment"," ",Array.isArray(P.envVar)&&P.envVar.length>1?"variables":"variable"," to use this provider."]})})})]})};function AAs({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(hee,{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(Ght,{})]}),a.jsxs(ht,{orientation:"horizontal",children:[a.jsx(ut,{children:"Template AI Model Provider"}),a.jsx(Nvt,{className:"flex-1",children:a.jsxs(ps,{name:"template-provider",value:t,onValueChange:n,children:[a.jsx(gs,{size:"md",children:a.jsx(ms,{placeholder:"Select"})}),a.jsx(vs,{children:e.map(h=>a.jsx(hr,{value:h.value,children:h.label},h.value))})]})})]}),t&&Object.entries(r||{}).length>0&&a.jsxs(a.Fragment,{children:[a.jsx(Y,{as:"h3",tone:"muted",children:"Set required Environmental Variables"}),a.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?a.jsxs("div",{className:Z("text-muted-foreground","col-span-2 flex items-center justify-center gap-4","[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50","animate-in duration-300 fade-in"),children:[a.jsx(_n,{}),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(ht,{className:"w-full",children:[a.jsx(ut,{className:"sr-only",children:"Key"}),a.jsx(wn,{name:`env-${h}`,value:h,disabled:!0,className:"w-full"})]}),a.jsxs(ht,{invalid:s.includes(h),className:"w-full",children:[a.jsx(ut,{className:"sr-only",children:"Value"}),a.jsx(wn,{name:h,value:p,onChange:o,autoComplete:"off",className:"w-full"}),a.jsx(ns,{children:s.includes(h)?"Value is required.":void 0})]})]},h))}),a.jsxs("div",{className:"relative mt-3.5 border-t border-border pt-12",children:[a.jsx("div",{className:"absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full bg-background",children:a.jsx(Y,{tone:"muted",as:"span",variant:"caption",className:"block",children:"And"})}),a.jsx(Y,{as:"h3",tone:"muted",children:"Set AI Model for Template Installation"}),a.jsx(Y,{tone:"muted",className:"mt-2 mb-5",children:"This model will be used by the workflow to process and install the template"}),a.jsx(yQt,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&a.jsx(ue,{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(_n,{className:"h-4 w-4"})," Installing..."]}):a.jsxs(a.Fragment,{children:["Install ",a.jsx(dp,{})]})})]})})}function PAs({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(K1,{}),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(hp,{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(sh,{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(Ln,"mt-auto flex items-center gap-2"),children:[a.jsx(bX,{}),a.jsx(Y,{as:"span",variant:"body",className:"block",children:n?.split("/")?.pop()})]})]}),s&&a.jsx(ZIe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Ent(e){switch(e){case"running":return a.jsx(_n,{size:"sm","aria-hidden":!0});case"success":return a.jsx(ur,{"aria-hidden":!0});case"failed":return a.jsx(zn,{"aria-hidden":!0});default:return null}}function $As(){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 RAs({status:e,variant:t}){return t==="plain"?a.jsx("span",{className:Z("flex size-4 items-center justify-center self-center [&>svg]:size-4",Mi.colors,{"[&>svg]:text-success-indicator":e==="success","[&>svg]:text-destructive-foreground":e==="failed"}),children:e==="pending"?a.jsx($As,{}):Ent(e)}):a.jsx("span",{className:Z("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Mi.colors,Mi.transform,{"[&>svg]:text-success-indicator":e==="success","[&>svg]:text-destructive-foreground":e==="failed","border border-dashed border-placeholder":e==="pending","[&>svg]:size-4":e!=="running","bg-success-subtle":e==="success","bg-destructive-subtle":e==="failed","scale-110":e==="success"||e==="failed"}),children:Ent(e)})}function MAs({step:e,isActive:t,position:n,variant:r="default"}){const s=t||e.status==="success"?"ink":"muted";return a.jsxs("div",{className:Z("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",Mi.colors,{"border border-transparent":r==="default","border-dashed border-placeholder bg-card":t&&r==="default"}),children:[a.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[a.jsxs(Y,{as:"span",tone:s,className:Z("flex min-w-6 justify-end",Mi.colors),children:[n,"."]}),a.jsxs("div",{className:"min-w-0",children:[a.jsx(Y,{as:"h4",tone:s,className:Mi.colors,children:e.title}),e.description&&a.jsx(Y,{tone:"faint",className:Z("-mt-0.5",{truncate:r==="plain"}),children:e.description})]})]}),a.jsx(RAs,{status:e.status,variant:r})]})}function DAs({currentStep:e,steps:t=[],className:n}){return a.jsx("div",{className:Z(n),children:t.map((r,s)=>a.jsx(MAs,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function LAs({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return a.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[a.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>a.jsx("div",{className:Z("relative flex h-8 items-center justify-end",Mi.colors,{"bg-success-subtle":r.status==="success"&&e?.[s-1]?.status==="success"}),children:a.jsx("div",{className:Z("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-fill text-column text-muted-foreground motion-reduce:transition-none",Mi.colors,Mi.transform,{"border border-dashed border-placeholder":r.status==="pending","scale-110 bg-success-subtle text-success-subtle-foreground":r.status==="success","scale-110 bg-destructive-subtle text-destructive-subtle-foreground":r.status==="failed"}),children:r.status==="running"?a.jsx(_n,{}):s+1})},r.id))}),a.jsxs("div",{className:Z("text-center text-caption text-muted-foreground",Mi.colors),children:[n," of ",t," steps completed"]})]})}function zAs({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(hee,{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(LAs,{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(kIn,{}),a.jsx(Y,{as:"span",variant:"body",className:"block",children:l||"Something went wrong"})]}),u&&a.jsx(DAs,{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(_n,{}),a.jsx(Y,{as:"p",variant:"body",children:"This may take some time..."})]})]})}function FAs({name:e,installedEntities:t}){return a.jsxs(hee,{className:Z("grid content-center items-center justify-items-center gap-4","[&>svg]:h-8 [&>svg]:w-8"),children:[a.jsx(Ght,{}),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(ZIe,{data:t})]})}function BAs(){const{templateSlug:e}=jr(),t=[{id:"templates",label:"Templates",to:"/templates"},{id:"template",label:Pke(e)}],[n,r]=ci(),[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:A}=mAs({repoOrSlug:e,owner:"mastra-ai"}),L=TAs?.includes("beta")??!1?"beta":"main",{data:F,isLoading:Q}=gAs({repo:I?.githubUrl?new URL(I.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:L}),{data:q,isLoading:B}=vAs(),{mutateAsync:V,isPending:H}=yAs(),{mutateAsync:D}=xAs(),{streamInstall:K,streamResult:M,isStreaming:$}=wAs({workflowInfo:q}),{observeInstall:z,streamResult:U,isStreaming:G}=SAs({workflowInfo:q});g.useEffect(()=>{const re=n.get("runId");re&&!y&&!m&&!$&&!G&&(console.info("🔄 Checking completed run after hot reload:",{runId:re}),S(re),D({runId:re}).then(le=>{const pe=le.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:ke}=pe.result.validationResults,Ee=`Template installation completed but ${he} validation issue${he>1?"s":""} remain unresolved.`;v(Ee),N(ke||[])}else{const he=pe?.result?.message||pe?.result?.error||"Template installation failed";v(typeof he=="string"?he:String(he))}}).catch(le=>{console.error("❌ Failed to fetch run details:",le),v("Failed to retrieve installation status after reload")}))},[n,y,m,$,G,D]),g.useEffect(()=>{const re=n.get("runId"),le=n.get("resume"),pe=n.get("provider");if(re&&le==="true"&&pe&&!$&&!G&&!k&&!C&&q){S(re),j(!0);try{D({runId:re}).then(ve=>{if(ve.snapshot?.status==="running")return z.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,$,G,k,C,q,D,z,r]);const ne=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],X=[{key:"tools",label:"Tools",value:I?.tools?.length?I.tools.map(re=>re).join(", "):"n/a",icon:a.jsx(fd,{})},{key:"agents",label:"Agents",value:I?.agents?.length?I.agents.map(re=>re).join(", "):"n/a",icon:a.jsx(Uo,{})},{key:"workflows",label:"Workflows",value:I?.workflows?.length?I.workflows.map(re=>re).join(", "):"n/a",icon:a.jsx(yk,{})},{key:"providers",label:"Providers",value:I?.supportedProviders?.length?I.supportedProviders.join(", "):"n/a",icon:a.jsx(j0,{})},{key:"tags",label:"Tags",value:I?.tags?.length?I.tags.join(", "):"n/a",icon:a.jsx(Nx,{})}],ee=[{...X[0]},{...X[1]},{...X[2]}].filter(re=>re.value!=="n/a");g.useEffect(()=>{F&&f(F)},[F]),g.useEffect(()=>{const re=M||U;re?.phase==="error"&&re?.error&&v(typeof re.error=="string"?re.error:String(re.error))},[M?.phase,M?.error,U?.phase,U?.error]);const ie=re=>{i(re)},fe=async re=>(l(re.provider),u(re.modelId),{message:"Model updated successfully"}),te=async()=>{const re=Object.entries(d).reduce((le,[pe,ve])=>(ve===""&&le.push(pe),le),[]);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:L,slug:I.slug,variables:d},{runId:ve}=await V({});S(ve),r(he=>{const ke=new URLSearchParams(he);return ke.set("runId",ve),ke.set("resume","true"),ke.set("provider",s||"openai"),ke}),await K.mutateAsync({inputData:pe,selectedModel:{provider:o,modelId:c},runId:ve})}catch(le){T(!1),v(le?.message||"Template installation failed"),console.error("Template installation failed",le)}}},se=re=>{const{name:le,value:pe}=re.target;pe.trim()===""?p(ve=>[...ve,le]):p(ve=>ve.filter(he=>he!==le)),f(ve=>({...ve,[le]:pe}))};return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:Z("h-full w-full overflow-y-scroll lg:px-12"),children:a.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-4",children:[a.jsx(PAs,{isLoading:A,title:I?.title,description:I?.longDescription,imageURL:I?.imageURL,githubUrl:I?.githubUrl,infoData:X,templateSlug:e}),I&&a.jsxs(a.Fragment,{children:[($||G)&&a.jsx(zAs,{name:I.title,streamResult:G?U:M,runId:b,workflowInfo:q}),y&&a.jsx(FAs,{name:I.title,installedEntities:ee,linkComponent:ac}),m&&a.jsx(EAs,{errorMsg:m,validationErrors:_.length>0?_:M?.validationResults?.errors||U?.validationResults?.errors}),!$&&!G&&!y&&!m&&a.jsx(AAs,{providerOptions:ne,selectedProvider:s,onProviderChange:ie,variables:d,setVariables:f,errors:h,setErrors:p,handleInstallTemplate:te,handleVariableChange:se,isLoadingEnvVars:Q||B,isInstalling:H,defaultModelProvider:o,defaultModelId:c,onModelUpdate:fe})]})]})})]})}const UAs=()=>a.jsx(Xt,{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(ue,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/workflows/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Workflows Documentation"}),variant:"fill"});function VAs(e,t,n){return Uk(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 qAs(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function QAs(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 ZAs(e,t,n){const r=QAs(t),s=[],i=(o,l,c,u,d,f)=>{const h=qAs(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 Int="auto 24rem minmax(0, 1fr) auto auto auto";function xQt({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 bQt({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(Ln,"relative grid size-5 shrink-0 place-items-center before:absolute before:-inset-1.5 before:content-['']"),onClick:i=>{i.stopPropagation(),n()},children:a.jsx(Ha,{direction:"right",className:"size-4"})}):a.jsx("span",{className:"size-5 shrink-0","aria-hidden":!0})})}const WAs=e=>e.stopPropagation();function eB({sortKey:e,sort:t,onSortChange:n,children:r}){return n?a.jsx(_e.SortableTopCell,{sortKey:e,sort:t?.key===e?t.direction:void 0,onSortChange:s=>n(s,e),children:r}):a.jsx(_e.TopCell,{children:r})}function HAs({row:e,isExpanded:t,onToggle:n,runCount:r,rowProps:s}){const{paths:i,Link:o}=Tn(),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(_e.RowWrapper,{...s,onSelectRow:()=>l.current?.click(),children:[a.jsx(bQt,{row:e,isExpanded:t,onToggle:n}),a.jsxs(_e.RowLink,{ref:l,colStart:2,to:i.workflowLink(c.id),LinkComponent:o,tabIndex:-1,onClick:WAs,children:[a.jsx(_e.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-1.5",children:[e.depth>0?a.jsx(xQt,{guides:e.guides,isLastChild:e.isLastChild}):null,a.jsx("span",{className:"truncate",children:d}),c.origin==="dynamic"?a.jsx(Mt,{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(yk,{"aria-hidden":!0,className:"size-3.5"}),u.length]}):null]})}),a.jsx(_e.DescriptionCell,{children:f}),a.jsx(_e.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(_e.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(_S,{"aria-hidden":!0,className:"size-3.5"}),m]}):""}),a.jsx(_e.TextCell,{className:"text-center",children:h||""})]})]})}function GAs({workflows:e,isLoading:t,search:n="",sort:r,onSortChange:s,requestContext:i}){const[o,l]=g.useState(new Set),c=Q2n({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(()=>VAs(d,r,c),[d,r,c]),h=g.useMemo(()=>ZAs(f,e,o),[f,e,o]),p=g.useMemo(()=>{const x=new Map;for(const b of h)b.kind==="workflow"&&x.set(b.pathKey,x.size);return x},[h]),{containerRef:m,getRowProps:v}=Fu({count:p.size,global:!0}),y=x=>{l(b=>{const S=new Set(b);return S.has(x)?S.delete(x):S.add(x),S})};return t?a.jsx(Lu,{columns:Int,fit:"container"}):a.jsxs(_e,{columns:Int,fit:"container",scrollRef:m,children:[a.jsxs(_e.Top,{children:[a.jsx(_e.TopCell,{children:a.jsx("span",{className:"sr-only",children:"Expand"})}),a.jsx(eB,{sortKey:"name",sort:r,onSortChange:s,children:"Name"}),a.jsx(_e.TopCell,{children:"Description"}),a.jsx(eB,{sortKey:"running",sort:r,onSortChange:s,children:"Running"}),a.jsx(eB,{sortKey:"suspended",sort:r,onSortChange:s,children:"Pending input"}),a.jsx(eB,{sortKey:"steps",sort:r,onSortChange:s,children:"Number of steps"})]}),h.length===0&&n?a.jsx(_e.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(_e.RowStatic,{className:"gap-0 px-0",children:[a.jsx(bQt,{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(_e.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(xQt,{guides:x.guides,isLastChild:x.isLastChild}),a.jsx("span",{className:"truncate",children:cf(x.stepId,50)}),a.jsxs(Fn,{children:[a.jsx(Mn,{render:a.jsx(Y,{as:"span",variant:"body-sm",tone:"muted"}),role:"note",tabIndex:0,className:Z("shrink-0 rounded-sm",ji),children:"not registered"}),a.jsx(Dn,{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(_e.DescriptionCell,{children:cf(x.description??"",200)}),a.jsx(_e.TextCell,{className:"text-center",children:""}),a.jsx(_e.TextCell,{className:"text-center",children:""}),a.jsx(_e.TextCell,{className:"text-center",children:""})]})]},`workflow-${x.pathKey}`):a.jsx(HAs,{row:x,isExpanded:b,onToggle:S,runCount:c[x.workflow.id],rowProps:v(p.get(x.pathKey)??-1)},`workflow-${x.pathKey}`)})]})}const UM=[Ts("/workflows")];function KAs(){const{data:e,isLoading:t,error:n}=ng(),[r,s]=g.useState(""),[i,o]=g.useState();return n&&Cs(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(ui,{variant:"fill"})]}):n&&_s(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Gs,{variant:"fill",resource:"workflows"})]}):n?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Xt,{tone:"error",variant:"fill",titleSlot:"Failed to load workflows",descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(UAs,{})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:UM}),actionRow:a.jsxs(ar,{children:[a.jsx(ar.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(pf,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})})}),a.jsx(ar.End,{children:a.jsx(ue,{render:a.jsx(ac,{to:"/workflows/schedules"}),variant:"primary",icon:a.jsx(C0,{}),children:"Schedules"})})]}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(GAs,{workflows:e||{},isLoading:t,search:r,sort:i,onSortChange:(l,c)=>o({key:c,direction:l})})]})}const YAs={active:"bg-success-indicator",paused:"bg-info-indicator",completed:"bg-muted-foreground"},XAs={active:"text-success-indicator",paused:"text-info-indicator",completed:"text-muted-foreground"},wQt=({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 ${YAs[e]}`,"aria-hidden":!0}),a.jsx(Y,{as:"span",variant:"caption",className:XAs[e],children:e})]});function SQt({status:e}){const{icon:t,color:n}=JAs(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 JAs(e){switch(e){case"success":return{icon:a.jsx(ur,{size:14}),color:"text-success-indicator"};case"failed":return{icon:a.jsx(zn,{size:14}),color:"text-destructive-foreground"};case"running":return{icon:a.jsx(_n,{}),color:"text-muted-foreground"};case"suspended":return{icon:a.jsx(WH,{size:14}),color:"text-info-indicator"};case"canceled":return{icon:a.jsx(aL,{size:14}),color:"text-muted-foreground"};case"pending":case"waiting":return{icon:a.jsx(fC,{size:14}),color:"text-muted-foreground"};default:return{icon:null,color:"text-muted-foreground"}}}const Nnt="auto auto auto auto 1fr",ePs=3e4,tPs=5*6e4;function nPs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:i}){const{Link:o,paths:l}=Tn(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=Fu({count:u});let h=-1;return t?a.jsx(Lu,{columns:Nnt}):e.length===0?a.jsx(Y,{variant:"body",tone:"muted",className:"p-4",children:"No trigger history yet."}):a.jsxs(_e,{columns:Nnt,className:"min-w-0",scrollRef:d,children:[a.jsxs(_e.Top,{children:[a.jsx(_e.TopCell,{children:"Run"}),a.jsx(_e.TopCell,{children:"Status"}),a.jsx(_e.TopCell,{children:"Started"}),a.jsx(_e.TopCell,{children:"Duration"}),a.jsx(_e.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=Vc(m,{signed:!0}),y=p.outcome==="failed",x=y?p.error:p.run?.error,b=Math.abs(m),S=!y&&b>ePs&&b<=tPs,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(_e.Cell,{children:C}),a.jsx(_e.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(Yd,{size:14}),"publish failed"]}):p.run?a.jsx(SQt,{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(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-destructive-foreground",children:a.jsx(Yd,{size:14})})}),a.jsx(Dn,{children:x})]}):null]})}),a.jsx(_e.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[p.actualFireAt?a.jsx(DI,{value:p.actualFireAt}):"—",S?a.jsxs(Fn,{children:[a.jsx(Mn,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-info-indicator",children:a.jsx(Yd,{size:14})})}),a.jsxs(Dn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),a.jsx(_e.Cell,{children:p.run?a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",children:Vc(p.run.durationMs)||"—"}):a.jsx("span",{className:"text-muted-foreground",children:"—"})}),a.jsx(_e.Cell,{children:" "})]});return j?a.jsx(_e.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:o,...f(h),children:T},k):a.jsx(_e.RowStatic,{children:T},k)}),a.jsx(_e.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:i})]})}const kQt={id:"workflow-schedules",label:"Schedules",icon:C0,to:"/workflows/schedules"};function tB({label:e,children:t}){return a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx(Y,{variant:"meta",tone:"muted",className:"uppercase",children:e}),a.jsx("div",{children:a.jsx(Y,{as:"span",variant:"body",className:"block",children:t})})]})}function rPs(){const{scheduleId:e}=jr(),t=[Ts("/workflows"),kQt,{id:"schedule",label:Pke(e),icon:C0}],{paths:n}=Tn(),{data:r,error:s}=Eur({scheduleId:e,queryOptions:{enabled:!!e}}),{data:i,isLoading:o,error:l,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d}=Iur({scheduleId:e,queryOptions:{enabled:!!e}}),f=Nur({scheduleId:e});if(s&&Cs(s))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(ui,{variant:"fill"})]});if(s&&_s(s))return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Gs,{variant:"fill",resource:"schedules"})]});if(s)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Xt,{tone:"error",variant:"fill",titleSlot:"Failed to load schedule",descriptionSlot:s.message})]});const h=r?.workflowId,p=r?.agentId;return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:t}),actionRow:a.jsx(ar,{children:a.jsxs(ar.End,{children:[a.jsx(ue,{render:a.jsx(ac,{to:n.schedulesLink()}),variant:"ghost",icon:a.jsx(vd,{}),children:"Back to schedules"}),h?a.jsx(ue,{icon:a.jsx(Ol,{}),render:a.jsx(ac,{to:n.workflowLink(h)}),variant:"ghost",children:"Open workflow"}):null,r?a.jsx(ue,{onClick:()=>{const m=r.status==="active"?"pause":"resume";f.mutate(m,{onSuccess:()=>Ye.success(m==="pause"?"Schedule paused":"Schedule resumed"),onError:v=>Ye.error(v.message)})},disabled:f.isPending,"data-testid":"schedule-toggle-button",children:r.status==="active"?a.jsxs(a.Fragment,{children:[a.jsx(_S,{}),"Pause"]}):a.jsxs(a.Fragment,{children:[a.jsx(Uc,{}),"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(tB,{label:p?"Agent":"Workflow",children:h?a.jsx(ac,{to:n.workflowLink(h),className:"text-foreground hover:underline",children:h}):p?a.jsx(ac,{to:n.agentLink(p),className:"text-foreground hover:underline",children:p}):"—"}),a.jsxs(tB,{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(tB,{label:"Status",children:a.jsx(wQt,{status:r.status})}),a.jsx(tB,{label:"Next fire",children:r.nextFireAt?a.jsx(DI,{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(Xt,{tone:"error",titleSlot:"Failed to load trigger history",descriptionSlot:l.message}):a.jsx(nPs,{triggers:i??[],isLoading:o,workflowId:h,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d})]})]}):null]})}const sPs={target:e=>e.workflowId??e.agentId??"",status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},Ant="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function iPs({schedules:e,isLoading:t,search:n="",sort:r,onSortChange:s}){const{paths:i,Link:o}=Tn(),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 Uk(h,r,sPs)},[e,n,r]),{containerRef:c,getRowProps:u}=Fu({count:l.length,global:!0});if(t)return a.jsx(Lu,{columns:Ant});const d=(f,h)=>s?a.jsx(_e.SortableTopCell,{sortKey:f,sort:r?.key===f?r.direction:void 0,onSortChange:s,children:h}):a.jsx(_e.TopCell,{children:h});return a.jsxs(_e,{columns:Ant,className:"min-w-0",scrollRef:c,children:[a.jsxs(_e.Top,{children:[d("target","Target"),a.jsx(_e.TopCell,{children:"Schedule ID"}),a.jsx(_e.TopCell,{children:"Cron"}),d("status","Status"),d("nextFireAt","Next fire"),d("lastFireAt","Last run")]}),l.length===0&&n?a.jsx(_e.NoMatch,{message:"No schedules match your search"}):null,l.length===0&&!n?a.jsx(_e.NoMatch,{message:"No schedules configured"}):null,l.map((f,h)=>a.jsxs(_e.RowLink,{to:i.scheduleLink(f.id),LinkComponent:o,...u(h),children:[a.jsx(_e.NameCell,{children:f.workflowId??f.agentId}),a.jsx(_e.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(_e.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(_e.Cell,{children:a.jsx(wQt,{status:f.status})}),a.jsx(_e.Cell,{children:f.nextFireAt?a.jsx(DI,{value:f.nextFireAt}):"—"}),a.jsx(_e.Cell,{children:f.lastRun?a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx(SQt,{status:f.lastRun.status}),f.lastFireAt?a.jsx(Y,{as:"span",variant:"caption",tone:"muted",children:a.jsx(DI,{value:f.lastFireAt})}):null]}):f.lastFireAt?a.jsx(DI,{value:f.lastFireAt}):a.jsx("span",{className:"text-muted-foreground",children:"Never"})})]},f.id))]})}function OQt({workflowId:e}={}){const{data:t,isLoading:n,error:r}=TK(e?{workflowId:e}:{}),[s,i]=g.useState(""),[o,l]=g.useState();return r?a.jsx(Xt,{tone:"error",titleSlot:"Failed to load schedules",descriptionSlot:r.message}):a.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[a.jsx("div",{className:"max-w-120",children:a.jsx(pf,{onSearch:i,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),a.jsx("div",{className:"overflow-y-auto",children:a.jsx(iPs,{schedules:t??[],isLoading:n,search:s,sort:o,onSortChange:(c,u)=>l({key:u,direction:c})})})]})}const Tue=[Ts("/workflows"),kQt];function oPs(){const[e]=ci(),t=e.get("workflowId")??void 0,{error:n}=TK(t?{workflowId:t}:{});return n&&Cs(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Tue}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(ui,{variant:"fill"})]}):n&&_s(n)?a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Tue}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(Gs,{variant:"fill",resource:"schedules"})]}):a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:Tue}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx("div",{className:"h-full",children:a.jsx(OQt,{workflowId:t})})]})}const aPs={"--belt-hue":"var(--warning-indicator)"};function lPs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function cPs(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 uPs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:a.jsxs("section",{className:Z(vke,"pointer-events-auto relative isolate"),"data-testid":"workflow-suspended-steps","aria-label":"Step suspended",children:[a.jsxs("div",{className:"max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]",children:[a.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border bg-background px-5 py-4",children:[a.jsxs(Y,{as:"h2",variant:"column",tone:"ink",className:"flex items-center gap-2",children:[a.jsx(At,{children:a.jsx(WH,{})}),"Step suspended"]}),a.jsx(Mt,{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?$S(hC(i.resumeSchema)):Nf(Cn(),Bf());return a.jsx(dPs,{step:s,stepSchema:o,description:i.description,onResume:r},`${s.runId}-${s.stepId}`)})]}),a.jsx(J4t,{status:"ready",label:"Needs input",className:"before:hidden",style:aPs})]})}function dPs({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){Ye.error(d instanceof Error?d.message:"Error resuming workflow")}finally{l(!1)}};return a.jsxs("div",{className:"space-y-5 p-5 [&+&]:border-t [&+&]:border-border",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(Y,{as:"p",variant:"subheading",tone:"ink",className:"break-words",children:e.stepId}),n&&a.jsx(Y,{as:"p",variant:"caption",tone:"muted",children:n})]}),e.suspendPayload!==void 0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs(Y,{as:"p",variant:"caption",tone:"muted",className:"flex items-center gap-2",children:[a.jsx(At,{children:a.jsx(fIn,{})}),"The step is asking"]}),a.jsxs(gc,{open:s,onOpenChange:i,children:[a.jsxs(Hl,{className:Z(pr,"flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5"),children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[a.jsx(At,{children:a.jsx(Ha,{direction:"right",className:"text-muted-foreground"})}),a.jsx(Y,{as:"span",variant:"body",tone:"ink",className:"truncate",children:cPs(e.suspendPayload,e.stepId)})]}),a.jsx(Y,{as:"span",variant:"caption",tone:"muted",className:"shrink-0",children:lPs(e.suspendPayload)})]}),a.jsx(Gl,{children:a.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:a.jsx(Or,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs(Y,{as:"p",variant:"caption",tone:"muted",className:"flex items-center gap-2",children:[a.jsx(At,{children:a.jsx(gIn,{})}),"Your response"]}),a.jsx("div",{className:"-mx-5",children:a.jsx(lke,{schema:t,isSubmitLoading:o,submitButtonLabel:"Resume",submitButtonVariant:"primary",submitButtonIcon:a.jsx(Uc,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:c})})]})]})}function fPs({hidden:e,requestContext:t,canResume:n}){const{result:r,workflow:s,runId:i,isStreamingWorkflow:o}=g.useContext(Zl),l=mvt(r,i),c=f9n(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(uPs,{suspendedSteps:l,workflow:s,isStreaming:o,onResume:c})},i)}const Pnt={success:{label:"Completed",icon:ur},failed:{label:"Failed",icon:X0e},suspended:{label:"Needs input",icon:_S},waiting:{label:"Waiting",icon:gx},paused:{label:"Paused",icon:_S},skipped:{label:"Skipped",icon:INn},running:{label:"Running",icon:fc},canceled:{label:"Canceled",icon:aL}},hPs={label:"Status unavailable",icon:Q_n};function pPs({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:s,onOpenInput:i,onOpenOutput:o}){const l=Object.hasOwn(Pnt,e.status)?Pnt[e.status]:hPs,c=l.icon,u=wSe(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",ji),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",p1t[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(twe,{"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",rJn[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:Vc(e.timing.durationMs)}):a.jsx("span",{"aria-label":"Timing unavailable",children:"—"})}),a.jsxs("div",{className:"flex items-center",children:[a.jsx(ue,{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(VH,{})}),a.jsx(ue,{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(QH,{})})]})]})}const mPs=e=>e.includes("."),gPs=e=>e==="input"||e.endsWith(".input"),$nt=1;function vPs(e,t){const n=SSe(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 yPs(e,t){const n=Object.entries(e).filter(([l])=>!gPs(l)).map(([l,c])=>({stepId:l,step:c,...vPs(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-$nt),v=Math.min(Math.max(p/o*100,$nt),100-m);h={durationMs:p,offsetPct:m,widthPct:v}}return{stepId:l,step:c,status:XG(c)?"suspended":c.status,timing:h,spansSuspension:f,isRunning:d,isNestedEntry:mPs(l)}})}function xPs(){const{steps:e}=p$(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=dG(),[i,o]=g.useState(()=>Date.now()),[l,c]=g.useState(!0),[u,d]=g.useState(!1),{showData:f}=_k(),h=g.useRef(null),p=yPs(e,i),m=p.some(v=>v.isRunning);return GSt(h,{enabled:m&&!l}),g.useEffect(()=>{if(!m||l)return;const v=setInterval(()=>o(Date.now()),100);return()=>clearInterval(v)},[m,l]),p.length===0?null:a.jsx("div",{"data-testid":"workflow-timeline",className:"relative z-20 shrink-0 px-2 pb-2",children:a.jsxs(gc,{open:!l,onOpenChange:v=>c(!v),className:Z(pr,"@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl"),children:[a.jsxs("div",{className:"flex items-center",children:[a.jsxs(Hl,{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(jht,{"aria-hidden":!0,className:"size-4 text-muted-foreground"})}),a.jsx("span",{children:"Timeline"}),a.jsxs(Y,{as:"span",variant:"meta",tone:"muted",children:[p.length," events"]}),a.jsx("span",{className:"ml-auto",children:a.jsx(Ha,{direction:"right",className:"size-4"})})]}),!l&&a.jsx(ue,{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(__n,{}):a.jsx(_ht,{})})]}),a.jsx(Gl,{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(pPs,{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 bPs=({workflowId:e,workflow:t,isLoading:n})=>{const[r]=xr("workflow",e),{canExecute:s,isLoading:i}=Za(),{stepDetail:o}=_k(),l=Ck(),c=o?.type==="data",u=a.jsxs("div",{className:"[container-type:size] relative h-full min-h-0",children:[a.jsx(g5t,{workflowId:e,workflow:t,isLoading:n,requestContext:r}),a.jsx(fPs,{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(bU,{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(xPs,{})})]});return l&&o&&!c?a.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:a.jsx(bU,{requestContext:r})}):a.jsxs("div",{className:"relative h-full min-h-0",children:[u,a.jsxs(x$,{className:"pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2",children:[a.jsx(ap,{id:"workflow-graph",className:"pointer-events-none min-w-0"}),o&&!c&&a.jsxs(a.Fragment,{children:[a.jsx(ak,{className:"pointer-events-auto"}),a.jsx(ap,{id:"workflow-step-detail",minSize:300,maxSize:"60%",defaultSize:420,className:"min-w-0",children:a.jsx("div",{className:"pointer-events-auto h-full min-h-0 overflow-hidden rounded-studio-panel border border-border bg-background",children:a.jsx(bU,{requestContext:r})})})]})]})]})},Rnt=()=>{const{workflowId:e}=jr(),{data:t,isLoading:n,error:r}=yL({workflowId:e,requestContext:xr("workflow",e)[0],queryOptions:{enabled:!!e}});return r&&Cs(r)?a.jsx(ui,{variant:"fill"}):r&&_s(r)?a.jsx(Gs,{variant:"fill",resource:"workflows"}):a.jsx(bPs,{workflowId:e,workflow:t??void 0,isLoading:n})};function wPs(){const{workflowId:e}=jr(),{error:t}=TK(e?{workflowId:e}:{});if(!e)return null;let n;return t&&Cs(t)?n=a.jsx(ui,{variant:"fill"}):t&&_s(t)?n=a.jsx(Gs,{variant:"fill",resource:"schedules"}):n=a.jsx("div",{className:"h-full",children:a.jsx(OQt,{workflowId:e})}),a.jsxs(It,{children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),n]})}function SPs(){const{workflowId:e}=jr();return e?a.jsx(rAe,{scopedEntityId:e,scopedEntityType:od.WORKFLOW_RUN}):null}const jQt=g.createContext(null);function tu(){const e=g.useContext(jQt);if(!e)throw new Error("Workspace components must be rendered inside <Workspace.Root>");return e}const kPs=e=>e?.status;function OPs(e,t){return Cs(e)?"Your session has expired. Sign in again to continue.":_s(e)?"You don't have permission to access this.":Ik(e)?"This path no longer exists.":kPs(e)===501?"This workspace does not support this operation.":t}function pee({error:e,fallback:t,className:n}){return a.jsx(Wt,{variant:"destructive",className:n,children:a.jsx(Wt.Message,{children:OPs(e,t)})})}const jPs=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function CPs(e){const t=jPs.exec(e);return t?{frontmatter:t[1]??"",body:e.slice(t[0].length)}:{frontmatter:null,body:e}}function _Ps({content:e}){const{frontmatter:t,body:n}=CPs(e);return a.jsxs(a.Fragment,{children:[t!==null&&a.jsx("div",{"data-testid":"workspace-frontmatter",className:"border-b border-border",children:a.jsx(a$,{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(ql,{children:n})})]})}function TPs(){const{activeFilePath:e}=tu();return e?a.jsx(Y,{as:"span",variant:"body-sm",font:"mono",tone:"muted",className:"truncate","data-testid":"workspace-file-path",children:e}):null}function EPs({path:e,content:t,mimeType:n}){return nRt(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"})}):rRt(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:${jGe(e,n)};base64,${t}`,type:jGe(e,n)})})}):szr(e)?a.jsx(_Ps,{content:t}):a.jsx(a$,{code:t,lang:MOt(e),overflow:"scroll",className:"rounded-none border-0 bg-transparent [&_pre]:p-4"})}function IPs({renderPreview:e}){const{workspaceId:t,activeFilePath:n}=tu(),{data:r,isLoading:s,error:i}=hzr({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(xt,{className:"h-4 w-1/2"}),a.jsx(xt,{className:"h-4 w-5/6"}),a.jsx(xt,{className:"h-4 w-2/3"})]});if(!r)return a.jsx(pee,{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(EPs,{...o})}const HA=".",CQt=(e,t)=>e===HA?t:`${e}/${t}`,Mnt=e=>e.split("/").slice(0,-1).map((t,n,r)=>r.slice(0,n+1).join("/")),_Qt=e=>{const t=e.lastIndexOf("/");return t===-1?HA:e.slice(0,t)};function TQt({labeled:e=!1}={}){const{workspaceId:t,onCreateDirectory:n,isReadOnly:r}=tu(),s=mr(),[i,o]=g.useState(!1),[l,c]=g.useState(""),[u,d]=g.useState(!1);if(!n||r(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",_Qt(f)]}),o(!1),c("")}catch{}finally{d(!1)}}};return a.jsxs(a.Fragment,{children:[e?a.jsx(ue,{variant:"ghost",icon:a.jsx(jS,{}),onClick:()=>o(!0),children:"New folder"}):a.jsx(ue,{variant:"ghost",size:"icon-sm",tooltip:"New folder",onClick:()=>o(!0),children:a.jsx(jS,{})}),a.jsx(Kr,{open:i,onOpenChange:o,pending:u,children:a.jsx(Yr,{size:"sm",children:a.jsxs("form",{onSubmit:p=>{p.preventDefault(),h()},children:[a.jsx(Xr,{children:a.jsx(Qr,{children:"New folder"})}),a.jsx(qr,{children:a.jsx(wn,{autoFocus:!0,"aria-label":"Folder path",placeholder:"docs/guides",value:l,onChange:p=>c(p.target.value)})}),a.jsxs(Yo,{children:[a.jsx(Ca,{children:"Cancel"}),a.jsx(ue,{type:"submit",variant:"primary",disabled:!f||u,children:"Create"})]})]})})})]})}function Dnt(e){return`${e.topSource}/${e.name}`}function Lnt(e){const t=sRt(e.topSource,e.name);return t?`${t.owner}/${t.repo}/${e.name}`:null}function NPs({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}=ozr({workspaceId:n,queryOptions:{enabled:!!n}}),b=izr({workspaceId:n}),S=g.useMemo(()=>f?.topSource?sRt(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}=azr({workspaceId:n,owner:S?.owner,repo:S?.repo,skillPath:f?.name,queryOptions:{enabled:!!n&&!!S&&!!f}}),T=lw(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,A=u.trim().length>=2,P=g.useMemo(()=>{if(!f)return!1;const Q=Lnt(f);return!!(Q&&i.includes(Q)||o.includes(f.name))},[f,i,o]),L=g.useCallback(()=>{!f||!S||r({repository:`${S.owner}/${S.repo}`,skillName:f.name,mount:l&&l.length>1?v:void 0})},[f,S,r,l,v]),F=g.useCallback(Q=>{Q||(d(""),h(null),m(void 0)),t(Q)},[t]);return a.jsx(Kr,{open:e,onOpenChange:F,pending:s,children:a.jsxs(Yr,{size:"xl",className:"h-[80vh]",children:[a.jsxs(Xr,{children:[a.jsx(Qr,{children:"Add Skill"}),a.jsx(Lo,{children:"Search and install skills from the community registry"})]}),a.jsxs(qr,{layout:"fill",children:[a.jsx(Zc,{label:"Search skills",placeholder:"Search skills...",value:u,onValueChange:_}),a.jsxs("div",{className:"flex min-h-0 flex-1 gap-4",children:[a.jsxs("div",{className:"flex min-h-0 w-1/2 flex-col",children:[a.jsx(Y,{as:"p",variant:"eyebrow",tone:"muted",className:"mb-2",children:A?"Search Results":"Popular Skills"}),a.jsx(Ir,{className:"flex-1 rounded-lg border border-border",children:a.jsx(of,{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(fc,{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(aL,{className:"mb-2 size-8"}),a.jsx(Y,{children:A?"No skills found":"No skills available"})]}):a.jsx("div",{className:"space-y-1 p-2",children:N.map(Q=>{const q=Dnt(Q),B=Lnt(Q),V=B&&i.includes(B)||o.includes(Q.name),H=f?Dnt(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(ur,{className:"size-2.5"}),"Installed"]})]}),a.jsx(Y,{as:"p",variant:"caption",tone:"muted",className:"truncate",children:Q.topSource})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-1 text-muted-foreground",children:[a.jsx(fp,{className:"size-3"}),a.jsx(Y,{as:"span",variant:"caption",children:Q.installs.toLocaleString()})]})]})},q)})})})})]}),a.jsxs("div",{className:"flex min-h-0 w-1/2 flex-col",children:[a.jsx(Y,{as:"p",variant:"eyebrow",tone:"muted",className:"mb-2",children:"Preview"}),a.jsx("div",{className:"flex flex-1 flex-col overflow-hidden rounded-lg border border-border",children:f?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"border-b border-border bg-card p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"rounded-lg bg-muted p-2",children:a.jsx(F6,{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(bX,{className:"size-3"}),a.jsx(Y,{as:"span",variant:"caption",className:"block",children:f.topSource})]}),a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(fp,{className:"size-3"}),a.jsxs(Y,{as:"span",variant:"caption",className:"block",children:[f.installs.toLocaleString()," installs"]})]})]})]}),S&&a.jsx("a",{href:`https://github.com/${S.owner}/${S.repo}`,target:"_blank",rel:"noopener noreferrer",className:Z(Ln,On),title:"View on GitHub",children:a.jsx(Zs,{className:"size-4"})})]})}),C?a.jsx("div",{className:"flex flex-1 items-center justify-center",children:a.jsx(fc,{className:"size-6 animate-spin text-muted-foreground"})}):j?a.jsx(Ir,{className:"flex-1",children:a.jsx("div",{className:"p-4",children:a.jsx(ql,{children:j})})}):a.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-muted-foreground",children:[a.jsx(K1,{className:"mb-2 size-8"}),a.jsx(Y,{children:"Preview unavailable"}),k&&a.jsxs("a",{href:k,target:"_blank",rel:"noopener noreferrer",className:"mt-2 flex items-center gap-1 text-info-indicator hover:underline",children:[a.jsxs(Y,{as:"span",variant:"caption",className:"block",children:["View on skills.sh"," "]}),a.jsx(Zs,{className:"size-3"})]})]})]}):a.jsxs("div",{className:"flex h-full flex-col items-center justify-center text-muted-foreground",children:[a.jsx(K1,{className:"mb-2 size-8"}),a.jsx(Y,{children:"Select a skill to preview"})]})})]})]}),f&&l&&l.length>1&&a.jsxs(ht,{orientation:"horizontal",className:Z(pr,"gap-3 rounded-lg p-3"),children:[a.jsx(xP,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx(ut,{className:"whitespace-nowrap",children:"Install to"}),a.jsxs(ps,{value:v,onValueChange:m,children:[a.jsx(gs,{className:"flex-1",children:a.jsx(ms,{})}),a.jsx(vs,{children:l.map(Q=>{const q=Q.displayName??Q.name??Q.provider??"unknown";return a.jsxs(hr,{value:Q.path,children:[q," (",Q.path,")"]},Q.path)})})]})]})]}),f&&a.jsxs(Yo,{children:[P&&l&&l.length>1&&(()=>{const Q=c?.[f.name];if(!Q)return null;const q=l.find(B=>Q.startsWith(B.path+"/")||Q===B.path);return q?a.jsxs(Y,{as:"span",variant:"caption",tone:"muted",className:"mr-auto",children:["Installed at ",q.path]}):null})(),a.jsx(Ca,{children:"Cancel"}),a.jsx(ja,{onConfirm:L,disabled:!S||P,"data-testid":"install-skill-button",children:s?"Installing...":P?"Already Installed":"Install"})]})]})})}function EQt({labeled:e=!1}){const{workspaceId:t,addSkill:n}=tu(),[r,s]=g.useState(!1),[i,o]=g.useState(!1);if(!n)return null;const{onInstall:l,...c}=n,u=async d=>{o(!0);try{await l(d),s(!1)}catch{}finally{o(!1)}};return a.jsxs(a.Fragment,{children:[e?a.jsxs(ue,{variant:"ghost",onClick:()=>s(!0),children:[a.jsx(Efe,{}),"Add skill"]}):a.jsx(ue,{variant:"ghost",size:"icon-sm","aria-label":"Add skill",tooltip:"Add skill",onClick:()=>s(!0),children:a.jsx(Efe,{})}),a.jsx(NPs,{...c,open:r,onOpenChange:s,workspaceId:t,onInstall:d=>{u(d)},isInstalling:i})]})}function APs({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(Mnt(t??""))),[b,S]=g.useState(t);if(t!==b){S(t);const C=Mnt(t??"").filter(T=>!y.has(T));C.length>0&&x(new Set([...y,...C]))}const k=i?.join(`
|
|
700
700
|
`)??"",j=g.useMemo(()=>({workspaceId:e,activeFilePath:t,setActiveFilePath:s,isSearching:h,setSearching:C=>{p(C),C||v("")},query:m,setQuery:v,onDelete:n,onCreateDirectory:r,isReadOnly:C=>(k?k.split(`
|
|
701
701
|
`):[]).some(_=>_==="."||C===_||C.startsWith(`${_}/`)),searchFiles:o,searchSkills:l,fileCount:c,skillCount:u,addSkill:d,openFolders:y,setFolderOpen:(C,T)=>x(_=>{if(_.has(C)===T)return _;const N=new Set(_);return T?N.add(C):N.delete(C),N})}),[e,t,h,m,n,r,s,k,o,l,c,u,d,y]);return a.jsx(jQt.Provider,{value:j,children:f})}const IQt=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"})}),PPs=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 $Ps(){const{isSearching:e,setSearching:t,searchFiles:n,searchSkills:r}=tu();return!n&&!r?null:a.jsx(ue,{variant:"ghost",size:"icon-sm",tooltip:"Search files and skills","aria-pressed":e,onClick:()=>t(!e),children:a.jsx(PPs,{})})}function RPs(){const{isSearching:e}=tu();return e?a.jsx(DPs,{}):a.jsx(MPs,{})}const znt=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function MPs(){const{fileCount:e,skillCount:t}=tu();return a.jsxs(Y,{as:"span",variant:"label",tone:"muted",className:"block min-w-0 truncate",children:[a.jsx("span",{children:e===void 0?"Files":znt(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:znt(t,"Skill")})]})]})}function DPs(){const{setSearching:e,setQuery:t}=tu(),[n,r]=g.useState(""),[,s]=g.useTransition();return a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(wn,{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(ue,{variant:"ghost",size:"icon-sm",tooltip:"Close search",onClick:()=>e(!1),children:a.jsx(zn,{})})]})}function LPs(){const{workspaceId:e,query:t,activeFilePath:n,setActiveFilePath:r,searchFiles:s,searchSkills:i}=tu(),{data:o,isLoading:l,isError:c,error:u}=vzr({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(xt,{className:"h-4 w-3/4"}),a.jsx(xt,{className:"h-4 w-2/3"})]}):c?a.jsx(pee,{error:u,fallback:"Search failed.",className:"m-2"}):o?.length?a.jsx("ul",{"aria-label":"Search results",className:"flex flex-col py-1",children:o.map(d=>a.jsx("li",{children:a.jsxs("button",{type:"button",title:d.path,onClick:()=>r(d.path),className:Z("text-foreground","flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left hover:bg-fill-subtle",n===d.path&&"bg-fill"),children:[a.jsx(At,{size:"sm",children:d.kind==="skill"?a.jsx(F6,{}):a.jsx(IQt,{})}),a.jsx(Y,{as:"span",variant:"body-sm",className:"truncate",children:d.label})]})},d.path))}):a.jsx(Xt,{titleSlot:"No results"}):a.jsx(Xt,{titleSlot:"Search files and skills",descriptionSlot:"Type to find matching content."})}function zPs({mount:e}){switch(e.icon||e.provider){case"aws-s3":case"s3":return a.jsx(j$t,{className:"text-foreground"});case"google-cloud":case"google-cloud-storage":case"gcs":return a.jsx(_$t,{});case"azure-blob":case"azure":return a.jsx(C$t,{className:"text-badge-blue-indicator"});case"cloudflare":case"cloudflare-r2":case"r2":return a.jsx(_fe,{className:"text-badge-orange-indicator"});case"minio":return a.jsx(Tfe,{className:"text-badge-red-indicator"});case"database":return a.jsx(yv,{className:"text-badge-green-indicator"});case"local":case"folder":return a.jsx(xP,{className:"text-badge-amber-indicator"});case"hard-drive":return a.jsx(Tfe,{className:"text-muted-foreground"});default:return a.jsx(_fe,{className:"text-muted-foreground"})}}const FPs=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"})}),BPs=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 UPs(){const{workspaceId:e,activeFilePath:t,setActiveFilePath:n}=tu(),{data:r,isLoading:s,error:i}=R6({workspaceId:e,path:HA}),[o,l]=g.useState(null);return s?a.jsx(WPs,{}):r?a.jsxs(a.Fragment,{children:[a.jsx(kr,{"aria-label":"Workspace files",selectedId:t,onSelect:n,className:"py-1",children:a.jsx(NQt,{entries:r,parent:HA,onRequestDelete:l})}),a.jsx(ZPs,{entry:o,onClose:()=>l(null)})]}):a.jsx(pee,{error:i,fallback:"Could not load files.",className:"m-2"})}function NQt({entries:e,parent:t,onRequestDelete:n}){return e.map(r=>{const s=CQt(t,r.name);return r.type==="directory"?a.jsx(VPs,{name:r.name,path:s,mount:r.mount,onRequestDelete:n},r.name):a.jsx(QPs,{name:r.name,size:r.size,path:s,onRequestDelete:n},r.name)})}function AQt({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 PQt({name:e,onClick:t}){return a.jsx(ue,{variant:"destructive-ghost",size:"icon-sm",tooltip:`Delete ${e}`,onClick:n=>{n.stopPropagation(),t()},onKeyDown:n=>n.stopPropagation(),children:a.jsx(FPs,{})})}function VPs({name:e,path:t,mount:n,onRequestDelete:r}){const{workspaceId:s,onDelete:i,onCreateDirectory:o,isReadOnly:l,openFolders:c,setFolderOpen:u}=tu(),d=c.has(t),{isLoading:f}=R6({workspaceId:s,path:t,queryOptions:{enabled:d}}),[h,p]=g.useState(!1),m=i&&!l(t),v=o&&!l(t);return a.jsxs(kr.Folder,{id:t,open:d,onOpenChange:y=>u(t,y),children:[a.jsxs(kr.FolderTrigger,{actions:m||v?a.jsxs(AQt,{children:[v?a.jsx(ue,{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(jS,{})}):null,m?a.jsx(PQt,{name:e,onClick:()=>r({path:t,type:"directory"})}):null]}):void 0,children:[a.jsx(kr.Icon,{children:n?a.jsx("span",{role:"img","aria-label":`Mount: ${n.displayName??n.provider}`,title:[n.displayName??n.provider,n.description].filter(Boolean).join(" — "),className:"flex",children:a.jsx(zPs,{mount:n})}):a.jsx(dVt,{})}),a.jsx(kr.Label,{children:e}),n?.status==="error"?a.jsx("span",{role:"img","aria-label":`Mount error: ${n.error??"unavailable"}`,title:n.error,className:"flex shrink-0",children:a.jsx(gP,{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(Au,{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(_n,{size:"sm","aria-label":`Loading ${e}`,className:"size-3 text-muted-foreground"})}):null]}),a.jsx(kr.FolderContent,{children:d?a.jsx(qPs,{path:t,creating:h,onCreated:()=>p(!1),onRequestDelete:r}):null})]})}function qPs({path:e,creating:t,onCreated:n,onRequestDelete:r}){const{workspaceId:s,onCreateDirectory:i}=tu(),o=mr(),{data:l,isLoading:c,error:u}=R6({workspaceId:s,path:e}),d=async f=>{try{await i?.(CQt(e,f.replace(/^\/+|\/+$/g,"")))}catch{return}n(),await o.invalidateQueries({queryKey:["workspace",s,"fs","list",e]})};return a.jsxs(a.Fragment,{children:[t?a.jsx(kr.Input,{type:"folder",placeholder:"Folder name",onSubmit:f=>{d(f)},onCancel:n}):null,c?null:l?a.jsx(NQt,{entries:l,parent:e,onRequestDelete:r}):a.jsx(pee,{error:u,fallback:"Could not load folder.",className:"my-1 mr-1"})]})}function QPs({name:e,size:t,path:n,onRequestDelete:r}){const{onDelete:s,isReadOnly:i,activeFilePath:o}=tu(),l=s&&!i(n),c=n===o,u=g.useRef(null);return g.useEffect(()=>{c&&u.current?.scrollIntoView?.({block:"nearest"})},[c]),a.jsxs(kr.File,{ref:u,id:n,children:[a.jsx(kr.Icon,{children:a.jsx(IQt,{})}),a.jsx(kr.Label,{children:e}),a.jsxs(AQt,{children:[t!==void 0?a.jsx(Y,{as:"span",variant:"caption",tone:"faint",font:"mono",children:BPs(t)}):null,l?a.jsx(PQt,{name:e,onClick:()=>r({path:n,type:"file"})}):null]})]})}function ZPs({entry:e,onClose:t}){const{workspaceId:n,activeFilePath:r,setActiveFilePath:s,onDelete:i}=tu(),o=mr(),[l,c]=g.useState(!1),u=e?.path.split("/").pop(),d=async()=>{if(!(!e||!i)){c(!0);try{await i(e)}catch{return}finally{c(!1)}(r===e.path||r?.startsWith(`${e.path}/`))&&s(void 0),o.removeQueries({queryKey:["workspace",n,"fs","list",e.path]}),await o.invalidateQueries({queryKey:["workspace",n,"fs","list",_Qt(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(ue,{variant:"destructive",disabled:l,onClick:()=>{d()},children:l?"Deleting…":"Delete"})]})]})})}function WPs(){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(xt,{className:"h-4 w-3/4"}),a.jsx(xt,{className:"h-4 w-1/2"}),a.jsx(xt,{className:"h-4 w-2/3"})]})}function HPs({children:e,...t}){return a.jsx(APs,{...t,children:a.jsx(GPs,{children:e})})}function GPs({children:e}){const{workspaceId:t}=tu(),{data:n,error:r}=R6({workspaceId:t,path:HA});return(n?n.length===0:Ik(r))?a.jsx(Xt,{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(TQt,{labeled:!0}),a.jsx(EQt,{labeled:!0})]})}):a.jsx("div",{className:"size-full overflow-hidden",children:a.jsx(x$,{className:"size-full min-h-0 min-w-0",orientation:"horizontal",children:e})})}function KPs({children:e}){return a.jsxs(a.Fragment,{children:[a.jsx(hNe,{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(ak,{className:"w-px bg-border"})]})}function YPs({children:e,actions:t}){const{isSearching:n}=tu();return a.jsxs("div",{className:"flex h-11 shrink-0 items-center gap-2 border-b border-border px-3",children:[a.jsx("div",{className:"min-w-0 flex-1",children:e}),t&&!n?a.jsx("div",{className:"flex shrink-0 items-center gap-1",children:t}):null]})}function XPs(){const{isSearching:e}=tu();return a.jsx(Ir,{className:"min-h-0 flex-1 px-2 py-1",children:e?a.jsx(LPs,{}):a.jsx(UPs,{})})}function JPs({children:e}){return a.jsx(ap,{id:"workspace-active-file",className:"flex min-w-0 flex-col",minSize:30,children:e})}function e$s({children:e}){return a.jsx("div",{className:"flex h-11 shrink-0 items-center gap-2 border-b border-border px-4",children:e})}function t$s({renderPreview:e}){const{activeFilePath:t}=tu();return t?a.jsx(Ir,{className:"min-h-0 flex-1",children:a.jsx(IPs,{renderPreview:e})}):a.jsx(Xt,{variant:"fill",titleSlot:"Select a file"})}const $g={Root:HPs,Aside:KPs,AsideHeader:YPs,Search:RPs,SearchToggle:$Ps,CreateDirectory:TQt,Tree:XPs,ActiveFile:JPs,ActiveFileHeader:e$s,FilePath:TPs,ActiveFileContent:t$s};function n$s({asideActions:e,renderPreview:t,...n}){return a.jsxs($g.Root,{...n,children:[a.jsxs($g.Aside,{children:[a.jsx($g.AsideHeader,{actions:a.jsxs(a.Fragment,{children:[a.jsx($g.SearchToggle,{}),a.jsx($g.CreateDirectory,{}),a.jsx(EQt,{}),e]}),children:a.jsx($g.Search,{})}),a.jsx($g.Tree,{})]}),a.jsxs($g.ActiveFile,{children:[a.jsx($g.ActiveFileHeader,{children:a.jsx($g.FilePath,{})}),a.jsx($g.ActiveFileContent,{renderPreview:t})]})]})}const r$s=()=>a.jsx(Xt,{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(ue,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/workspace/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Workspaces Documentation"}),variant:"fill"}),s$s=()=>a.jsx(Xt,{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(ue,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/workspace/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Workspaces Documentation"}),variant:"fill"}),i$s=()=>a.jsx(Xt,{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(ue,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/workspace/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Zs,{}),children:"Workspaces Documentation"}),variant:"fill"}),Eue=".agents/skills",o$s=e=>e.replace(/^\.?\/+|\/+$/g,"");function a$s({workspaceId:e,showInitWarning:t,skills:n}){const{data:r}=R6({workspaceId:e,path:Eue,queryOptions:{enabled:!!n}}),s=n&&r?r.filter(i=>i.type==="directory"&&!n.some(o=>o.name===i.name||o$s(o.path)===`${Eue}/${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:Eue})," but not discovered. Add this path to your workspace skills configuration to see ",s.length===1?"it":"them","."]})})]})}const o1=[Ts("/workspaces")],Fnt=e=>_s(e)?"you don't have permission to modify this workspace":e instanceof Error?e.message:"Unknown error";function Bnt(){const{workspaceId:e}=jr(),[t,n]=ci(),r=Dr(),s=mr(),i=t.get("file"),{data:o,error:l,isLoading:c}=oRt(),u=o?.workspaces??[],d=e??u[0]?.id,{data:f,isLoading:h,error:p}=iRt({workspaceId:d,queryOptions:{enabled:!!d}}),m=Cs(l)||Cs(p),v=_s(l)||_s(p),y=Gge(l)||Gge(p),x=d?u.find(he=>he.id===d):void 0,b=he=>{const ke=new URLSearchParams(t);for(const[Ee,Ve]of Object.entries(he))Ve===null?ke.delete(Ee):ke.set(Ee,Ve);n(ke)},S=he=>{r(`/workspaces/${he}`)},k=he=>{b({file:he??null})},j=i??void 0,C=dzr(),T=fzr(),{data:_,refetch:N}=yzr({workspaceId:d,queryOptions:{enabled:!!d}}),I=lzr(),A=czr(),P=uzr(),L=he=>{const ke=/^\.agents\/skills\/([^/]+)$/.exec(he);return ke?fe.find(Ve=>Ve.path?.replace(/^\.?\/+|\/+$/g,"")===he)?.name??ke[1]:void 0},F=async()=>{if(d)try{const he=await A.mutateAsync({workspaceId:d}),ke=he.updated.filter(Ee=>!Ee.success);ke.length>0?Ye.error(`Failed to update ${ke.map(Ee=>Ee.skillName).join(", ")}`):Ye.success(`${he.updated.length} skill(s) updated`),s.invalidateQueries({queryKey:["workspace",d,"fs"]})}catch(he){Ye.error(`Failed to update skills: ${he instanceof Error?he.message:"Unknown error"}`)}},Q=async({path:he,type:ke})=>{if(!d)return;const Ee=ke==="directory"?L(he):void 0;if(!Ee){try{await C.mutateAsync({path:he,recursive:!0,force:!0,workspaceId:d})}catch(Ve){throw Ye.error(`Failed to delete ${he}: ${Fnt(Ve)}`),Ve}return}try{if(!(await P.mutateAsync({workspaceId:d,skillName:Ee})).success)throw new Error(`Failed to remove skill "${Ee}"`);Ye.success(`Skill "${Ee}" removed`),N()}catch(Ve){throw Ye.error(Ve instanceof Error?Ve.message:"Failed to remove skill"),Ve}},q=f?.isWorkspaceConfigured??!1,B=f?.capabilities?.hasFilesystem??!1,V=f?.capabilities?.hasSkills??!1,H=x?.safety?.readOnly??!1,{canEdit:D,canDelete:K,canExecute:M,isLoading:$}=Za(),z=!$&&D("workspaces")&&!H,U=!$&&K("workspaces")&&!H,G=!$&&M("workspaces"),ne=B&&V&&z,X=f?.mounts,ee=X?.filter(he=>!he.readOnly).map(he=>({path:he.path,displayName:he.displayName,icon:he.icon,provider:he.provider,name:he.name})),ie=async he=>{if(d)try{const ke=await I.mutateAsync({...he,workspaceId:d});if(!ke.success)throw new Error("Unknown error");s.invalidateQueries({queryKey:["workspace",d,"fs"]}),N(),Ye.success(`Skill "${ke.skillName}" installed successfully (${ke.filesWritten} files)`)}catch(ke){throw Ye.error(`Failed to install skill: ${ke instanceof Error?ke.message:"Unknown error"}`),ke}},fe=_?.skills??[],te=_?.isSkillsConfigured??!1,se=G&&B&&!!(f?.capabilities?.canBM25||f?.capabilities?.canVector),re=G&&V&&te&&fe.length>0,le=H?["."]:(X??[]).filter(he=>he.readOnly).map(he=>he.path.replace(/^\/+|\/+$/g,"")||".");if(c)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:o1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(_n,{fill:!0})]});if(m)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:o1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(ui,{variant:"fill"})]});if(v)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:o1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(Gs,{variant:"fill",resource:"workspaces"})]});if(y)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:o1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(i$s,{})]});const pe=l||p;if(pe)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:o1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(Xt,{tone:"error",variant:"fill",titleSlot:"Failed to load workspace",descriptionSlot:pe.message})]});if(!c&&u.length===0)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:o1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(r$s,{})]});if(!h&&!c&&!q)return a.jsxs(It,{breadcrumbs:a.jsx(Dt,{crumbs:o1}),children:[a.jsx("h1",{className:"sr-only",children:"Workspaces"}),a.jsx(s$s,{})]});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(Mt,{size:"xs",variant:"warning",children:"Read-only"}),he.capabilities.hasFilesystem&&a.jsx(Mt,{size:"xs",children:"FS"}),he.capabilities.hasSandbox&&a.jsx(Mt,{size:"xs",children:"Sandbox"}),he.capabilities.hasSkills&&a.jsx(Mt,{size:"xs",children:"Skills"})]})}));return a.jsxs(It,{variant:"fit",breadcrumbs:a.jsx(Dt,{crumbs:o1}),headerActions:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(fl,{"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(Mt,{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(a$s,{workspaceId:d,showInitWarning:se&&!h&&f?.status!=="ready",skills:V&&_?fe:void 0}),B&&d&&a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx(n$s,{workspaceId:d,activeFilePath:j,onActiveFileChange:k,readOnlyPaths:le,skillCount:V&&_?fe.length:void 0,searchFiles:se,searchSkills:re,onCreateDirectory:z?async he=>{try{await T.mutateAsync({path:he,recursive:!0,workspaceId:d})}catch(ke){throw Ye.error(`Failed to create ${he}: ${Fnt(ke)}`),ke}}:void 0,asideActions:ne&&fe.some(he=>he.path?.includes(".agents/skills/"))?a.jsx(ue,{variant:"ghost",size:"icon-sm",tooltip:"Update skills",disabled:A.isPending,onClick:()=>{F()},children:a.jsx(mx,{className:A.isPending?"animate-spin":void 0})}):void 0,addSkill:ne?{onInstall:ie,installedSkillIds:fe.filter(he=>he.skillsShSource).map(he=>`${he.skillsShSource.owner}/${he.skillsShSource.repo}/${he.name}`),installedSkillNames:fe.filter(he=>!he.skillsShSource).map(he=>he.name),writableMounts:ee,installedSkillPaths:Object.fromEntries(fe.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(Xt,{variant:"fill",titleSlot:"No filesystem or skills configured",descriptionSlot:"Add a filesystem or skills to this workspace to browse its files here."})})]})]})}function $Qt({children:e,className:t,mobileHeader:n,ref:r,sidebar:s,...i}){return a.jsxs("div",{ref:r,"data-slot":"app-shell",className:Z("h-full min-h-0",s&&"lg:grid lg:grid-cols-[auto_minmax(0,1fr)] lg:grid-rows-[1fr]",t),...i,children:[s,a.jsxs("div",{"data-slot":"app-shell-content",className:"flex h-full min-h-0 min-w-0 flex-col",children:[n,a.jsx("div",{"data-slot":"app-shell-body",className:Z("flex min-h-0 flex-1 flex-col","lg:py-2 lg:pr-2",s?"lg:pl-0":"lg:pl-2"),children:e})]})]})}function RQt({children:e,className:t}){return a.jsx("div",{"data-slot":"main-card",className:Z("relative min-h-0 flex-1 overflow-hidden lg:rounded-studio-frame lg:p-px lg:shadow-raised",nCn,t),children:e})}function l$s(){return a.jsxs("div",{className:"h-screen bg-sidebar",children:[a.jsx(sG,{position:"bottom-right"}),a.jsx(iSe,{defaultTheme:"system",children:a.jsx(mc,{delayDuration:0,children:a.jsx($Qt,{children:a.jsx(RQt,{className:"flex items-center justify-center overflow-y-auto",children:a.jsx(px,{})})})})})]})}function c$s({className:e,children:t,...n}){return a.jsx("footer",{"data-slot":"sidebar-footer",className:Z("mt-auto shrink-0 space-y-1.5",e),...n,children:t})}const ZAe=Me.createContext(null),MQt=Me.createContext(null);function bw(){return Me.useContext(ZAe)}function mg(){const e=Me.useContext(ZAe),t=Me.useContext(MQt);if(!e||!t)throw new Error("useSidebar must be used within a SidebarProvider.");return{...e,...t}}const u$s=g.forwardRef(function({className:t,children:n,action:r,...s},i){const{state:o}=mg();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})]})}),d$s=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`,f$s=76,h$s=100,p$s=60,m$s=22.5,g$s=.18,Unt=110,DQt=[0,.08,.16,.25,.34,.44,.55,.66,.78,.89,1],LQt={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 zQt(e){const t=1-e;return t*t*t}function v$s(e,t){return`linear-gradient(to right, ${DQt.map(r=>{const s=(t*zQt(r)*100).toFixed(2);return`color-mix(in oklch, var(${e}) ${s}%, transparent) ${(r*100).toFixed(0)}%`}).join(", ")})`}function Vnt(e,t){const n=DQt.map(r=>{const s=(t+(100-t)*r).toFixed(2);return`rgb(0 0 0 / ${zQt(r).toFixed(3)}) ${s}%`});return`linear-gradient(${e}, rgb(0 0 0 / 1) 0%, ${n.join(", ")})`}const y$s=`${Vnt("to bottom",p$s)}, ${Vnt("to right",m$s)}`;function qnt({tone:e}){const t=LQt[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:h$s,backgroundImage:v$s(t.colorVar,t.peak),maskImage:y$s,maskComposite:"intersect"},children:t.grain?a.jsx("span",{"aria-hidden":!0,className:"absolute inset-0",style:{backgroundImage:d$s,backgroundRepeat:"repeat",backgroundSize:`${Unt}px ${Unt}px`,opacity:g$s}}):null})}const x$s=g.forwardRef(function({label:t,value:n,status:r,tone:s="neutral",icon:i,action:o,href:l,linkLabel:c,LinkComponent:u,state:d,className:f,...h},p){const m=bw(),v=d??m?.state??"default",y=u??m?.LinkComponent??"a",x=v==="collapsed",b=LQt[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(qnt,{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&&hP,f),style:{height:f$s},...h,children:[a.jsx(qnt,{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 b$s({logo:e,title:t,className:n,...r}){const{state:s}=mg();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(z0,{children:t}):a.jsx(Y,{as:"span",variant:"subheading",tone:"ink",className:"truncate font-body tracking-tight",children:t})]})}const w$s=g.forwardRef(function({className:t,children:n,...r},s){const{state:i,isMobile:o}=mg();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 FQt({className:e,onClick:t,...n}){const{desktopState:r,isMobile:s,toggleSidebar:i}=mg(),o=r==="collapsed";return s?null:a.jsxs(Fn,{children:[a.jsx(Mn,{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",ji,"[&_svg]:size-4 [&_svg]:text-muted-foreground [&:hover_svg]:text-foreground",e),children:a.jsx(Kht,{})})}),a.jsx(Dn,{children:a.jsxs("span",{className:"inline-flex items-center gap-1.5",children:["Toggle Sidebar",a.jsx(Wd,{size:"xs",className:"bg-muted text-muted-foreground",children:"["})]})})]})}const Qnt="animate-[sidebar-hold_var(--resize-dur)] motion-reduce:animate-none";function S$s({className:e,children:t,collapsedLogo:n,actions:r,...s}){const i=bw(),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(Qnt,"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(Qnt,"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(FQt,{})})]}):t,r]})}const k$s=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",Ln,On,ji,"[&_svg]:size-4 [&_svg]:shrink-0",r&&"w-auto px-2",t),...i,children:[n,r?a.jsx(Wd,{size:"xs",className:Z("bg-surface-overlay-soft active:scale-100",vx),children:r}):null]})});function O$s({"aria-label":e="Main",children:t,className:n,...r}){const s=bw()?.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(Ir,{className:"min-h-0 flex-1",mask:{top:"3rem",bottom:"5rem"},children:a.jsx(of,{className:"px-0.5",children:a.jsx("div",{className:"pr-1.5",children:t})})})})}function BQt({children:e,icon:t,action:n,className:r,state:s,href:i,isActive:o,LinkComponent:l,...c}){const u=bw(),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(z0,{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(z0,{children:n}):null]})})}function WAe({children:e,className:t,state:n,...r}){const s=bw();return(n??s?.state??"default")==="collapsed"?a.jsx(z0,{children:e}):a.jsx("span",{...r,className:Z("min-w-0 flex-1 truncate text-left",t),children:e})}const j$s=md("flex min-w-0 cursor-pointer items-center rounded-lg text-label whitespace-nowrap",{variants:{size:{sm:tp.sm,md:tp.md,lg:tp.lg}},defaultVariants:{size:"md"}}),C$s=e=>e<=0?"gap-2 py-1 px-3":e===1?`gap-2 py-1 pr-3 pl-8 ${tp.md}`:e===2?`gap-2 py-1 pr-3 pl-10 ${tp.md}`:`gap-2 py-1 pr-3 pl-12 ${tp.md}`,_$s=Z("rounded-lg text-muted-foreground hover:text-foreground",hP),T$s="bg-fill text-foreground",E$s=Z("my-2 border border-transparent bg-brand-green text-black hover:text-black hover:brightness-95"),UQt=({isActive:e,isFeatured:t})=>Z(_$s,e&&T$s,t&&E$s),VQt=({isCollapsed:e,level:t=0,size:n})=>Z(j$s({size:n}),"w-full justify-start",On,"[&_svg]:size-4 [&_svg]:shrink-0",ji,!e&&C$s(t),e&&"gap-0 px-[13.5px] py-0"),qQt=({isActive:e,isCollapsed:t,isFeatured:n,level:r,size:s}={})=>Z(VQt({isCollapsed:t,level:r,size:s}),UQt({isActive:e,isFeatured:n}));function HAe({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=bw(),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(VQt({level:b,size:s}),"flex-1 pr-1"):Z(qQt({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(P$s,{action:S,surfaceClassName:UQt({isActive:r,isFeatured:x}),children:a.jsx(A$s,{label:N$s(e,y),children:I$s({render:i,asChild:f,children:n,link:e,state:m,Link:v,isActive:r,className:k})})}),!y&&d]})}function I$s({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(Dc,{"aria-hidden":"true",className:"!size-3.5"}):null;if(e||t){const f=e??n;if(!Me.isValidElement(f))throw new Error("SidebarNavLink requires a valid React element child when `asChild` is true so it can apply `SlottedNavChildProps` and merge `itemClassName`.");return Me.cloneElement(f,{className:Z(l,f.props.className),"aria-current":c,children:a.jsxs(a.Fragment,{children:[f.props.children,u]})})}if(!r)return n;const d=/^(https?:)?\/\//.test(r.url)?{target:"_blank",rel:"noreferrer"}:{};return a.jsxs(i,{href:r.url,...d,"aria-current":c,className:l,children:[r.icon,a.jsx(WAe,{state:s,children:r.name}),n,u]})}function N$s(e,t){if(e)return e.tooltipMsg?t?`${e.name} | ${e.tooltipMsg}`:e.tooltipMsg:t?e.name:void 0}function A$s({label:e,children:t}){return Me.isValidElement(t)?a.jsxs(Fn,{disabled:!e,children:[a.jsx(Mn,{render:t}),e?a.jsx(Dn,{side:"right",align:"center",sideOffset:16,children:e}):null]}):t}function P$s({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 GAe({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 QQt({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 ZQt({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 WQt=Me.createContext(void 0);function HQt(){const e=Me.useContext(WQt);if(!e)throw new Error("Sidebar.NavStack components must be used within Sidebar.NavStack.");return e}function $$s({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(WQt.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 GQt(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 R$s({children:e,className:t,...n}){const{state:r}=mg(),{activeValue:s,rootValue:i}=HQt(),o=r==="collapsed"||s===i;return a.jsx("div",{...n,"data-slot":"sidebar-nav-stack-root","aria-hidden":!o,inert:!o,className:GQt(o,"root",t),children:e})}function M$s({value:e,title:t,backLabel:n="Back to main navigation",returnFocusRef:r,onBack:s,children:i,className:o,...l}){const{state:c}=mg(),{activeValue:u,closeView:d}=HQt(),f=c!=="collapsed"&&u===e,h=Me.useRef(null),p=Me.useRef(f);Me.useEffect(()=>{f&&!p.current&&h.current?.focus(),p.current=f},[f]),Me.useEffect(()=>{if(!f)return;function v(y){y.key!=="Escape"||y.defaultPrevented||(y.preventDefault(),d(r),s?.())}return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[f,d,s,r]);function m(){d(r),s?.()}return a.jsxs("div",{...l,"data-slot":"sidebar-nav-stack-view","data-value":e,"aria-hidden":!f,inert:!f,className:GQt(f,"view",o),children:[a.jsxs("button",{ref:h,type:"button","aria-label":`${n}: ${t}`,onClick:m,className:Z(qQt(),"mb-2 grid grid-cols-[2rem_1fr_2rem] px-1"),children:[a.jsx(vd,{className:"justify-self-center","aria-hidden":"true"}),a.jsx("span",{className:"min-w-0 truncate text-center",children:t}),a.jsx("span",{"aria-hidden":"true"})]}),i]})}const D$s=Object.assign($$s,{Root:R$s,View:M$s});function L$s({className:e,icon:t,"aria-label":n="Open navigation menu",onClick:r,...s}){const{isMobile:i,mobileTriggerRef:o,setOpenMobile:l}=mg();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",Ln,"hover:bg-fill-subtle",ji,e),children:t??a.jsx(qht,{className:"size-5"})})}const Znt="sidebar:state",Wnt="sidebar:width",Hnt="--sidebar-width",Iue=(e,t,n)=>Math.min(n,Math.max(t,e)),z$s=typeof window<"u"?Me.useLayoutEffect:Me.useEffect;function KQt({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=Iue(n,h,p),y=i??h,x=c?`${c}:${Znt}`:Znt,b=c?`${c}:${Wnt}`:Wnt,S=()=>{if(typeof window>"u")return{state:t,width:v};try{let re=t,le=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)&&(le=Iue(he,h,p))}return{state:re,width:le}}catch{return{state:t,width:v}}},k=Me.useRef(null);k.current===null&&(k.current=S());const j=k.current,[C,T]=Me.useState(j.state),[_,N]=Me.useState(j.width),[I,A]=Me.useState(!1),[P,L]=Me.useState(!1),[F,Q]=Me.useState(!1),q=Me.useRef(!1),B=Me.useRef(null),V=Me.useRef(j.width),H=Me.useRef(j.state);H.current=C;const D=Me.useRef(null);Me.useEffect(()=>{if(typeof window>"u")return;const re=window.matchMedia(`(max-width: ${u-1}px)`),le=()=>A(re.matches);return le(),re.addEventListener("change",le),()=>re.removeEventListener("change",le)},[u]);const K=Me.useCallback(re=>{q.current=re,re&&Q(!0),L(re)},[]);Me.useEffect(()=>{!I&&P&&(K(!1),Q(!1))},[I,P,K]);const M=Me.useCallback(re=>{const le=D.current;le&&le.style.setProperty(Hnt,`${re}px`)},[]);z$s(()=>{M(C==="collapsed"?m:V.current)},[C,m,M]);const $=Me.useCallback(re=>{try{window.localStorage.setItem(x,re)}catch{}},[x]),z=Me.useCallback(()=>{if(I){K(!q.current);return}T(re=>{const le=re==="default"?"collapsed":"default";return H.current=le,$(le),le})},[I,$,K]),U=Me.useCallback(re=>{const le=Iue(re,h,p);V.current=le,M(le)},[h,p,M]),G=Me.useCallback(()=>{H.current="collapsed",$("collapsed"),T("collapsed")},[$]),ne=Me.useCallback(()=>{H.current="default",$("default"),T("default")},[$]),X=Me.useCallback(()=>{N(V.current);try{window.localStorage.setItem(x,H.current),window.localStorage.setItem(b,String(V.current))}catch{}},[x,b]),ee=Me.useCallback(re=>{const le=D.current;le&&(re?le.setAttribute("data-sidebar-gesture","active"):le.removeAttribute("data-sidebar-gesture"))},[]);Me.useEffect(()=>{if(l)return;const re=le=>{if(le.code==="KeyB"&&(le.metaKey||le.ctrlKey)&&!(le.altKey||le.shiftKey)){if(le.target instanceof HTMLElement){const pe=le.target.tagName;if(pe==="INPUT"||pe==="TEXTAREA"||pe==="SELECT"||le.target.isContentEditable)return}le.preventDefault(),z()}};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[l,z]);const ie=I?"default":C,fe=Me.useMemo(()=>({state:ie,desktopState:C,width:_,minWidth:h,maxWidth:p,collapseBelow:y,collapsedWidth:m,isMobile:I,toggleSidebar:z,setWidth:U,collapse:G,expand:ne,commit:X,setGestureActive:ee,LinkComponent:f}),[ie,C,_,h,p,y,m,I,z,U,G,ne,X,ee,f]),te=Me.useMemo(()=>({openMobile:P,mobileTriggerRef:B,setOpenMobile:K,setMobileDrawerPresent:Q}),[P,K]),se={[Hnt]:`${j.state==="collapsed"?m:j.width}px`,"--sidebar-width-mobile":`${d}px`,display:"contents"};return a.jsx("div",{ref:D,"data-sidebar-scope":!0,"data-sidebar-state":C,"data-sidebar-mobile":I?"true":"false","data-sidebar-mobile-present":F?"true":"false",style:se,suppressHydrationWarning:!0,children:a.jsx(ZAe.Provider,{value:fe,children:a.jsx(MQt.Provider,{value:te,children:e})})})}const Gnt=10,F$s=5;function B$s({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}=mg(),k=r==="collapsed",j=k&&c===0,C=g.useRef(!1),T=g.useRef(null);g.useEffect(()=>()=>{T.current?.(),T.current=null},[]);const _=g.useCallback(L=>{if(L.button!==0)return;L.preventDefault(),C.current=!1,S(!0);const F=L.clientX,Q=L.currentTarget,q=L.pointerId;try{Q.setPointerCapture(q)}catch{}const B=Q.parentElement,V=B?B.getBoundingClientRect().left:0,H=document.body.style.cursor,D=document.body.style.userSelect,K=$=>{if($.pointerId!==q)return;const z=$.clientX-F;if(!C.current){if(Math.abs(z)<=F$s)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)},M=$=>{$&&$.pointerId!==q||(window.removeEventListener("pointermove",K),window.removeEventListener("pointerup",M),window.removeEventListener("pointercancel",M),document.body.style.cursor=H,document.body.style.userSelect=D,S(!1),x(),T.current=null)};T.current=()=>M(),window.addEventListener("pointermove",K),window.addEventListener("pointerup",M),window.addEventListener("pointercancel",M)},[l,m,y,v,x,S]),N=g.useCallback(()=>{if(C.current){C.current=!1;return}b()},[b]),I=g.useCallback(L=>{switch(L.key){case"Enter":case" ":{L.preventDefault(),b();return}case"ArrowLeft":{if(L.preventDefault(),k)return;m(s-Gnt),x();return}case"ArrowRight":{if(L.preventDefault(),k){y(),x();return}m(s+Gnt),x();return}case"Home":{L.preventDefault(),y(),m(i),x();return}case"End":{L.preventDefault(),y(),m(o),x();return}}},[k,s,i,o,m,y,x,b]),A=g.useCallback(L=>{if(!(L.target instanceof Element))return;const F=L.target.closest("a");!F||!F.hasAttribute("href")||L.button!==0||L.metaKey||L.ctrlKey||L.shiftKey||L.altKey||F.target==="_blank"||F.hasAttribute("download")||h(!1)},[h]);if(u)return a.jsx(D_,{side:"left",open:d,onOpenChange:h,onOpenChangeComplete:L=>{L||p(!1)},children:a.jsxs(HL,{"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(hK,{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(nh,vx,aht,"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(qht,{className:"size-4"})})})}):null,a.jsx(z0,{asChild:!0,children:a.jsx($P,{children:"Navigation"})}),a.jsx(z0,{asChild:!0,children:a.jsx(GL,{children:"Primary site navigation drawer"})}),a.jsx("div",{onClick:A,className:Z("flex h-full min-h-0 flex-col overflow-hidden py-2",n==="takeover"?"px-4":"px-3"),children:e})]})});const P=k?c:s;return a.jsxs("div",{className:Z("sidebar-layout group/sidebar t-resize relative min-h-0 shrink-0 self-stretch bg-sidebar text-foreground","w-(--sidebar-width)","in-data-[sidebar-gesture=active]:transition-none",t,j&&"border-r-0 border-transparent"),children:[a.jsx("div",{className:Z("flex h-full min-h-0 flex-col overflow-hidden","transition-opacity duration-200 motion-reduce:transition-none","p-2",j&&"pointer-events-none p-0 opacity-0"),children:e}),a.jsx("div",{role:"separator","aria-orientation":"vertical","aria-valuenow":k?void 0:P,"aria-valuemin":k?void 0:i,"aria-valuemax":k?void 0:o,"aria-valuetext":k?"collapsed":`${P} pixels`,"aria-label":`Resize sidebar. Arrow keys to resize, Enter to ${k?"expand":"collapse"}.`,tabIndex:0,onPointerDown:_,onClick:N,onKeyDown: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(mke,{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 U$s({"aria-label":e="Sidebar",mobileMode:t="takeover",variant:n="default",children:r,...s}){const i=bw(),o=n==="raised"&&!i?.isMobile;return a.jsx("aside",{"aria-label":e,className:"contents",children:a.jsx(B$s,{mobileMode:t,...s,children:o?a.jsx("div",{"data-slot":"sidebar-surface",className:Z("-mr-2 -ml-4 flex min-h-0 flex-1 flex-col overflow-hidden rounded-r-xl py-1.5",i?.state==="collapsed"?"pr-2 pl-4":"pr-3.5 pl-5.5",oht),children:r}):r})})}const mee=["sidebar","more","hidden"],YQt={sidebar:"Always show",more:"Hide in More menu",hidden:"Never show"},V$s=Oi(gt(),ff(mee)),q$s="mastra:sidebar:link-visibility";function O3(e){return`${e.url}:${e.name}`}function Knt(e,t){return`${e}:${t.name}`}function XQt(e,t){return e.defaultVisible??t<2?"sidebar":"more"}function JQt(e){return mee.some(t=>t===e)}function Q$s({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(Kr,{open:e,onOpenChange:t,children:a.jsxs(Yr,{size:"md",finalFocus:n,children:[a.jsxs(Xr,{children:[a.jsx(Qr,{children:"Customize sidebar"}),a.jsx(Lo,{children:"Choose where each optional link appears. Changes save automatically in this browser."})]}),a.jsx(qr,{className:"space-y-5",children:l.map(c=>{const u=c.moreLinks??[],d=c.title?`${o}-${c.key}`:void 0;return a.jsxs("section",{"aria-labelledby":d,"aria-label":d?void 0:c.key,className:"space-y-2",children:[c.title?a.jsx(Y,{as:"h3",id:d,variant:"label",tone:"muted",children:c.title}):null,a.jsx("ul",{className:"divide-y divide-border rounded-lg border border-border",children:u.map(f=>a.jsxs("li",{className:"flex min-h-11 items-center gap-2.5 py-1.5 pr-1.5 pl-3",children:[a.jsx("span",{"aria-hidden":"true",className:"flex shrink-0 text-muted-foreground [&_svg]:size-4",children:f.icon}),a.jsx(Y,{as:"span",variant:"body-sm",className:"min-w-0 flex-1 truncate",children:f.name}),a.jsxs(ps,{value:s(c.key,f,u.length),onValueChange:h=>{JQt(h)&&i(c.key,f,h)},children:[a.jsx(gs,{size:"sm",variant:"ghost",className:"w-44 shrink-0","aria-label":`${f.name} placement`,children:a.jsx(ms,{})}),a.jsx(vs,{children:mee.map(h=>a.jsx(hr,{value:h,children:YQt[h]},h))})]})]},O3(f)))})]},c.key)})})]})})}function KAe({link:e,activeCandidates:t,level:n=0,isActive:r,...s}){const i=e.children??[];return a.jsx(HAe,{...s,link:e,isActive:r?.(e,t)??e.isActive,level:n,subItems:i.length>0?a.jsx(GAe,{className:"mt-0.5",children:i.map(o=>a.jsx(KAe,{link:o,activeCandidates:t,level:n+1,isActive:r},O3(o)))}):null})}function Z$s({link:e,activeCandidates:t,isActive:n,placement:r,onPlacementChange:s,onCustomize:i}){const o=g.useRef(null);return a.jsxs(yo,{children:[a.jsx(yo.Trigger,{ref:l=>{o.current=l},render:a.jsx(KAe,{link:e,activeCandidates:t,isActive:n})}),a.jsxs(yo.Content,{"aria-label":`${e.name} options`,children:[a.jsx(yo.RadioGroup,{value:r,onValueChange:l=>{JQt(l)&&s(l)},children:mee.map(l=>a.jsx(yo.RadioItem,{value:l,children:YQt[l]},l))}),a.jsx(yo.Separator,{}),a.jsx(yo.Item,{onClick:()=>i(o.current?.querySelector("a")??null),children:"Customize sidebar…"})]})]})}function W$s({links:e,activeCandidates:t,isActive:n,placementOf:r,onPlacementChange:s,onCustomize:i}){const l=bw()?.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)!==XQt(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(ct.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))]},O3(v))}return a.jsxs(a.Fragment,{children:[u.map(v=>a.jsx(Z$s,{link:v,activeCandidates:t,isActive:n,placement:r(v),onPlacementChange:y=>s(v,y),onCustomize:y=>i(y,()=>p.current)},O3(v))),h?a.jsxs(ct,{modal:!1,children:[a.jsx(HAe,{link:{name:"More",url:"",icon:a.jsx(TN,{})},render:a.jsxs(ct.Trigger,{ref:p,render:a.jsx("button",{type:"button"}),"aria-label":"More",children:[a.jsx(TN,{"aria-hidden":"true"}),a.jsx(WAe,{children:"More"})]})}),a.jsxs(ct.Content,{align:"start","aria-label":"More navigation",className:"min-w-44",children:[d.map(v=>m(v)),d.length>0&&a.jsx(ct.Separator,{}),a.jsxs(ct.Item,{onClick:()=>i(p.current,()=>p.current),children:[a.jsx(hL,{}),"Customize sidebar"]})]})]}):null]})}function H$s({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]=jk({initialKey:r,defaultValue:{},schema:V$s});function f(v,y,x){return u[Knt(v,y)]??XQt(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,[Knt(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(QQt,{className:n,"aria-labelledby":x,"aria-label":x?void 0:v.key,children:[y?a.jsx(ZQt,{className:"[&:after]:border-border"}):null,v.title?a.jsx(BQt,{id:x,href:v.href,isActive:v.isHeaderActive,children:v.title}):null,a.jsxs(GAe,{children:[v.links.map(k=>a.jsx(KAe,{link:k,activeCandidates:S,isActive:t},O3(k))),b.length>0?a.jsx(W$s,{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(Q$s,{open:i,onOpenChange:p,returnFocusRef:l,sections:e,placementOf:f,onPlacementChange:m})]})}function G$s({visibilityStorageKey:e=q$s,...t}){return a.jsx(H$s,{...t,visibilityStorageKey:e},e)}const ho=Object.assign(U$s,{Brand:b$s,CommandHeader:w$s,Footer:c$s,FooterMeta:u$s,Header:S$s,Meter:x$s,MobileTrigger:L$s,Nav:O$s,NavHeader:BQt,NavLabel:WAe,NavLink:HAe,NavList:GAe,NavSection:QQt,NavSeparator:ZQt,NavStack:D$s,Provider:KQt,SearchTrigger:k$s,Sections:G$s,Trigger:FQt});function K$s(){const{data:e,isLoading:t}=Ql(),{isLoading:n,canAccessAgentBuilder:r}=Ax();return t||n?{isVisible:!1}:e?!!e.enabled&&!wp(e)?{isVisible:!1}:{isVisible:r}:{isVisible:!1}}function eZt(){const{isImpersonating:e,impersonatedRole:t,stopImpersonation:n}=oG();return!e||!t?null:a.jsxs("div",{className:"mx-3 mb-2 flex items-center gap-2 rounded-md border border-info-edge bg-info-subtle px-3 py-1.5",children:[a.jsx(Fa,{className:"h-3.5 w-3.5 shrink-0 text-info-subtle-foreground"}),a.jsxs(Y,{variant:"meta",className:"truncate text-info-subtle-foreground",children:["Previewing ",a.jsx("span",{className:"font-medium capitalize",children:t.name})," experience"]}),a.jsx("button",{type:"button",onClick:n,className:"ml-auto shrink-0 rounded p-0.5 text-info-subtle-foreground hover:bg-info-edge",title:"Exit role preview",children:a.jsx(zn,{className:"h-3 w-3"})})]})}var Ynt=1,Y$s=.9,X$s=.8,J$s=.17,Nue=.1,Aue=.999,eRs=.9999,tRs=.99,nRs=/[\\\/_+.#"@\[\(\{&]/,rRs=/[\\\/_+.#"@\[\(\{&]/g,sRs=/[\s-]/,tZt=/[\s-]/g;function Jye(e,t,n,r,s,i,o){if(i===t.length)return s===e.length?Ynt:tRs;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=Jye(e,t,n,r,u+1,i+1,o),f>d&&(u===s?f*=Ynt:nRs.test(e.charAt(u-1))?(f*=X$s,p=e.slice(s,u-1).match(rRs),p&&s>0&&(f*=Math.pow(Aue,p.length))):sRs.test(e.charAt(u-1))?(f*=Y$s,m=e.slice(s,u-1).match(tZt),m&&s>0&&(f*=Math.pow(Aue,m.length))):(f*=J$s,s>0&&(f*=Math.pow(Aue,u-s))),e.charAt(u)!==t.charAt(i)&&(f*=eRs)),(f<Nue&&n.charAt(u-1)===r.charAt(i+1)||r.charAt(i+1)===r.charAt(i)&&n.charAt(u-1)!==r.charAt(i))&&(h=Jye(e,t,n,r,u+1,i+2,o),h*Nue>f&&(f=h*Nue)),f>d&&(d=f),u=n.indexOf(c,u+1);return o[l]=d,d}function Xnt(e){return e.toLowerCase().replace(tZt," ")}function iRs(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Jye(e,t,Xnt(e),Xnt(t),0,0,{})}function oS(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e?.(s),n===!1||!s||!s.defaultPrevented)return t?.(s)}}function Jnt(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function GA(...e){return t=>{let n=!1;const r=e.map(s=>{const i=Jnt(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():Jnt(e[s],null)}}}}function dT(...e){return g.useCallback(GA(...e),e)}function oRs(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,aRs(s,...t)]}function aRs(...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 j3=globalThis?.document?g.useLayoutEffect:()=>{},lRs=XA[" useId ".trim().toString()]||(()=>{}),cRs=0;function b0(e){const[t,n]=g.useState(lRs());return j3(()=>{n(r=>r??String(cRs++))},[e]),t?`radix-${t}`:""}var uRs=XA[" useInsertionEffect ".trim().toString()]||j3;function dRs({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[s,i,o]=fRs({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=hRs(d)?d(e):d;f!==e&&o.current?.(f)}else i(d)},[l,e,i,o]);return[c,u]}function fRs({defaultProp:e,onChange:t}){const[n,r]=g.useState(e),s=g.useRef(n),i=g.useRef(t);return uRs(()=>{i.current=t},[t]),g.useEffect(()=>{s.current!==n&&(i.current?.(n),s.current=n)},[n,s]),[n,r,i]}function hRs(e){return typeof e=="function"}function nZt(e){const t=g.forwardRef((n,r)=>{let{children:s,...i}=n,o=null,l=!1;const c=[];ert(s)&&typeof nB=="function"&&(s=nB(s._payload)),g.Children.forEach(s,h=>{if(yRs(h)){l=!0;const p=h;let m="child"in p.props?p.props.child:p.props.children;ert(m)&&typeof nB=="function"&&(m=nB(m._payload)),o=mRs(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?vRs(o):void 0,d=dT(r,u);if(!o){if(s||s===0)throw new Error(l?SRs(e):wRs(e));return s}const f=gRs(i,o.props??{});return o.type!==g.Fragment&&(f.ref=r?d:u),g.cloneElement(o,f)});return t.displayName=`${e}.Slot`,t}var pRs=Symbol.for("radix.slottable"),mRs=(e,t)=>{if("child"in e.props){const n=e.props.child;return g.isValidElement(n)?g.cloneElement(n,void 0,e.props.children(n.props.children)):null}return g.isValidElement(t)?t:null};function gRs(e,t){const n={...t};for(const r in t){const s=e[r],i=t[r];/^on[A-Z]/.test(r)?s&&i?n[r]=(...l)=>{const c=i(...l);return s(...l),c}:s&&(n[r]=s):r==="style"?n[r]={...s,...i}:r==="className"&&(n[r]=[s,i].filter(Boolean).join(" "))}return{...e,...n}}function vRs(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function yRs(e){return g.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===pRs}var xRs=Symbol.for("react.lazy");function ert(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===xRs&&"_payload"in e&&bRs(e._payload)}function bRs(e){return typeof e=="object"&&e!==null&&"then"in e}var wRs=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,SRs=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,nB=XA[" use ".trim().toString()],kRs=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Vu=kRs.reduce((e,t)=>{const n=nZt(`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 ORs(e,t){e&&So.flushSync(()=>e.dispatchEvent(t))}function C3(e){const t=g.useRef(e);return g.useEffect(()=>{t.current=e}),g.useMemo(()=>((...n)=>t.current?.(...n)),[])}var jRs="DismissableLayer",exe="dismissableLayer.update",CRs="dismissableLayer.pointerDownOutside",_Rs="dismissableLayer.focusOutside",trt,YAe=g.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),rZt=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(YAe),[f,h]=g.useState(null),p=f?.ownerDocument??globalThis?.document,[,m]=g.useState({}),v=dT(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=ARs(A=>{i?.(A),l?.(A),A.defaultPrevented||c?.()},{ownerDocument:p,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:C,dismissableSurfaces:d.dismissableSurfaces,shouldHandlePointerDownOutside:g.useCallback(A=>{if(!(A instanceof Node))return!1;const P=[...d.branches].some(L=>L.contains(A));return j&&!P},[d.branches,j])}),_=PRs(A=>{if(r&&C.current)return;const P=A.target;[...d.branches].some(F=>F.contains(P))||(o?.(A),l?.(A),A.defaultPrevented||c?.())},p),N=f?S===y.length-1:!1,I=C3(A=>{A.key==="Escape"&&(s?.(A),!A.defaultPrevented&&c&&(A.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&&(trt=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(f)),d.layers.add(f),nrt(),()=>{n&&(d.layersWithOutsidePointerEventsDisabled.delete(f),d.layersWithOutsidePointerEventsDisabled.size===0&&(p.body.style.pointerEvents=trt))}},[f,p,n,d]),g.useEffect(()=>()=>{f&&(d.layers.delete(f),d.layersWithOutsidePointerEventsDisabled.delete(f),nrt())},[f,d]),g.useEffect(()=>{const A=()=>m({});return document.addEventListener(exe,A),()=>document.removeEventListener(exe,A)},[]),a.jsx(Vu.div,{...u,ref:v,style:{pointerEvents:k?j?"auto":"none":void 0,...e.style},onFocusCapture:oS(e.onFocusCapture,_.onFocusCapture),onBlurCapture:oS(e.onBlurCapture,_.onBlurCapture),onPointerDownCapture:oS(e.onPointerDownCapture,T.onPointerDownCapture)})});rZt.displayName=jRs;var TRs="DismissableLayerBranch",ERs=g.forwardRef((e,t)=>{const n=g.useContext(YAe),r=g.useRef(null),s=dT(t,r);return g.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),a.jsx(Vu.div,{...e,ref:s})});ERs.displayName=TRs;function IRs(){const e=g.useContext(YAe),[t,n]=g.useState(null);return g.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}var NRs=()=>!0;function ARs(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:s,dismissableSurfaces:i,shouldHandlePointerDownOutside:o=NRs}=t,l=C3(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||sZt(CRs,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 PRs(e,t=globalThis?.document){const n=C3(e),r=g.useRef(!1);return g.useEffect(()=>{const s=i=>{i.target&&!r.current&&sZt(_Rs,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 nrt(){const e=new CustomEvent(exe);document.dispatchEvent(e)}function sZt(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?ORs(s,i):s.dispatchEvent(i)}var Pue="focusScope.autoFocusOnMount",$ue="focusScope.autoFocusOnUnmount",rrt={bubbles:!1,cancelable:!0},$Rs="FocusScope",iZt=g.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:i,...o}=e,[l,c]=g.useState(null),u=C3(s),d=C3(i),f=g.useRef(null),h=dT(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:d1(f.current,{select:!0})},y=function(S){if(p.paused||!l)return;const k=S.relatedTarget;k!==null&&(l.contains(k)||d1(f.current,{select:!0}))},x=function(S){if(document.activeElement===document.body)for(const j of S)j.removedNodes.length>0&&d1(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){irt.add(p);const v=document.activeElement;if(!l.contains(v)){const x=new CustomEvent(Pue,rrt);l.addEventListener(Pue,u),l.dispatchEvent(x),x.defaultPrevented||(RRs(FRs(oZt(l)),{select:!0}),document.activeElement===v&&d1(l))}return()=>{l.removeEventListener(Pue,u),setTimeout(()=>{const x=new CustomEvent($ue,rrt);l.addEventListener($ue,d),l.dispatchEvent(x),x.defaultPrevented||d1(v??document.body,{select:!0}),l.removeEventListener($ue,d),irt.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]=MRs(b);S&&k?!v.shiftKey&&x===k?(v.preventDefault(),n&&d1(S,{select:!0})):v.shiftKey&&x===S&&(v.preventDefault(),n&&d1(k,{select:!0})):x===b&&v.preventDefault()}},[n,r,p.paused]);return a.jsx(Vu.div,{tabIndex:-1,...o,ref:h,onKeyDown:m})});iZt.displayName=$Rs;function RRs(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(d1(r,{select:t}),document.activeElement!==n)return}function MRs(e){const t=oZt(e),n=srt(t,e),r=srt(t.reverse(),e);return[n,r]}function oZt(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 srt(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):DRs(r,{upTo:t})))return r}function DRs(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 LRs(e){return e instanceof HTMLInputElement&&"select"in e}function d1(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&LRs(e)&&t&&e.select()}}var irt=zRs();function zRs(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=ort(e,t),e.unshift(t)},remove(t){e=ort(e,t),e[0]?.resume()}}}function ort(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function FRs(e){return e.filter(t=>t.tagName!=="A")}var BRs="Portal",aZt=g.forwardRef((e,t)=>{const{container:n,...r}=e,[s,i]=g.useState(!1);j3(()=>i(!0),[]);const o=n||s&&globalThis?.document?.body;return o?So.createPortal(a.jsx(Vu.div,{...r,ref:t}),o):null});aZt.displayName=BRs;function URs(e,t){return g.useReducer((n,r)=>t[n][r]??n,e)}var gee=e=>{const{present:t,children:n}=e,r=VRs(t),s=typeof n=="function"?n({present:r.isPresent}):g.Children.only(n),i=qRs(r.ref,QRs(s));return typeof n=="function"||r.isPresent?g.cloneElement(s,{ref:i}):null};gee.displayName="Presence";function VRs(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]=URs(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]),j3(()=>{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]),j3(()=>{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 art(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function qRs(...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=art(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():art(r[o],null)}}},[])}function VM(e){return e?.animationName||"none"}function QRs(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 rB=0,jE=null;function ZRs(){g.useEffect(()=>{jE||(jE={start:lrt(),end:lrt()});const{start:e,end:t}=jE;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),rB++,()=>{rB===1&&(jE?.start.remove(),jE?.end.remove(),jE=null),rB=Math.max(0,rB-1)}},[])}function lrt(){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 My=function(){return My=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},My.apply(this,arguments)};function lZt(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 WRs(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 AU="right-scroll-bar-position",PU="width-before-scroll-bar",HRs="with-scroll-bars-hidden",GRs="--removed-body-scroll-bar-size";function Rue(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function KRs(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 YRs=typeof window<"u"?g.useLayoutEffect:g.useEffect,crt=new WeakMap;function XRs(e,t){var n=KRs(null,function(r){return e.forEach(function(s){return Rue(s,r)})});return YRs(function(){var r=crt.get(n);if(r){var s=new Set(r),i=new Set(e),o=n.current;s.forEach(function(l){i.has(l)||Rue(l,null)}),i.forEach(function(l){s.has(l)||Rue(l,o)})}crt.set(n,e)},[e]),n}function JRs(e){return e}function eMs(e,t){t===void 0&&(t=JRs);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 tMs(e){e===void 0&&(e={});var t=eMs(null);return t.options=My({async:!0,ssr:!1},e),t}var cZt=function(e){var t=e.sideCar,n=lZt(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,My({},n))};cZt.isSideCarExport=!0;function nMs(e,t){return e.useMedium(t),cZt}var uZt=tMs(),Mue=function(){},vee=g.forwardRef(function(e,t){var n=g.useRef(null),r=g.useState({onScrollCapture:Mue,onWheelCapture:Mue,onTouchMoveCapture:Mue}),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=lZt(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),j=h,C=XRs([n,t]),T=My(My({},k),s);return g.createElement(g.Fragment,null,d&&g.createElement(j,{sideCar:uZt,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),My(My({},T),{ref:C})):g.createElement(b,My({},T,{className:c,ref:C}),l))});vee.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};vee.classNames={fullWidth:PU,zeroRight:AU};var rMs=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function sMs(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=rMs();return t&&e.setAttribute("nonce",t),e}function iMs(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function oMs(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var aMs=function(){var e=0,t=null;return{add:function(n){e==0&&(t=sMs())&&(iMs(t,n),oMs(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},lMs=function(){var e=aMs();return function(t,n){g.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},dZt=function(){var e=lMs(),t=function(n){var r=n.styles,s=n.dynamic;return e(r,s),null};return t},cMs={left:0,top:0,right:0,gap:0},Due=function(e){return parseInt(e||"",10)||0},uMs=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],s=t[e==="padding"?"paddingRight":"marginRight"];return[Due(n),Due(r),Due(s)]},dMs=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return cMs;var t=uMs(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},fMs=dZt(),sN="data-scroll-locked",hMs=function(e,t,n,r){var s=e.left,i=e.top,o=e.right,l=e.gap;return n===void 0&&(n="margin"),`
|
|
702
702
|
.`.concat(HRs,` {
|