@mastra/deployer-sandbox 0.1.1-alpha.0 → 0.1.2-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/CHANGELOG.md +16 -0
- package/dist/studio/assets/{core-BsSeUVq8.js → core-DHSn7H8K.js} +1 -1
- package/dist/studio/assets/{index-Dzf6_JAA.js → index-C8MeFRS0.js} +2 -2
- package/dist/studio/assets/{main-N75HX_Fj.js → main-CSpadNDw.js} +4 -4
- package/dist/studio/index.html +1 -1
- package/package.json +6 -6
|
@@ -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-DHSn7H8K.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{_ as go}from"./preload-helper-PPVm8Dsz.js";function XVt(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in e)){const a=Object.getOwnPropertyDescriptor(r,s);a&&Object.defineProperty(e,s,a.get?a:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var lT=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var nK={exports:{}},BA={};var oPe;function JVt(){if(oPe)return BA;oPe=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,s,a){var i=null;if(a!==void 0&&(i=""+a),s.key!==void 0&&(i=""+s.key),"key"in s){a={};for(var l in s)l!=="key"&&(a[l]=s[l])}else a=s;return s=a.ref,{$$typeof:e,type:r,key:i,ref:s!==void 0?s:null,props:a}}return BA.Fragment=t,BA.jsx=n,BA.jsxs=n,BA}var lPe;function eqt(){return lPe||(lPe=1,nK.exports=JVt()),nK.exports}var o=eqt(),rK={exports:{}},qr={},cPe;function tqt(){if(cPe)return qr;cPe=1;var e={env:{}};var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),i=Symbol.for("react.consumer"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),p=Symbol.for("react.activity"),h=Symbol.iterator;function m(V){return V===null||typeof V!="object"?null:(V=h&&V[h]||V["@@iterator"],typeof V=="function"?V:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function S(V,$,U){this.props=V,this.context=$,this.refs=b,this.updater=U||v}S.prototype.isReactComponent={},S.prototype.setState=function(V,$){if(typeof V!="object"&&typeof V!="function"&&V!=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,V,$,"setState")},S.prototype.forceUpdate=function(V){this.updater.enqueueForceUpdate(this,V,"forceUpdate")};function x(){}x.prototype=S.prototype;function k(V,$,U){this.props=V,this.context=$,this.refs=b,this.updater=U||v}var _=k.prototype=new x;_.constructor=k,y(_,S.prototype),_.isPureReactComponent=!0;var C=Array.isArray;function E(){}var j={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function I(V,$,U){var Z=U.ref;return{$$typeof:t,type:V,key:$,ref:Z!==void 0?Z:null,props:U}}function A(V,$){return I(V.type,$,V.props)}function R(V){return typeof V=="object"&&V!==null&&V.$$typeof===t}function L(V){var $={"=":"=0",":":"=2"};return"$"+V.replace(/[=:]/g,function(U){return $[U]})}var M=/\/+/g;function z(V,$){return typeof V=="object"&&V!==null&&V.key!=null?L(""+V.key):$.toString(36)}function H(V){switch(V.status){case"fulfilled":return V.value;case"rejected":throw V.reason;default:switch(typeof V.status=="string"?V.then(E,E):(V.status="pending",V.then(function($){V.status==="pending"&&(V.status="fulfilled",V.value=$)},function($){V.status==="pending"&&(V.status="rejected",V.reason=$)})),V.status){case"fulfilled":return V.value;case"rejected":throw V.reason}}throw V}function F(V,$,U,Z,K){var ne=typeof V;(ne==="undefined"||ne==="boolean")&&(V=null);var te=!1;if(V===null)te=!0;else switch(ne){case"bigint":case"string":case"number":te=!0;break;case"object":switch(V.$$typeof){case t:case n:te=!0;break;case f:return te=V._init,F(te(V._payload),$,U,Z,K)}}if(te)return K=K(V),te=Z===""?"."+z(V,0):Z,C(K)?(U="",te!=null&&(U=te.replace(M,"$&/")+"/"),F(K,$,U,"",function(pe){return pe})):K!=null&&(R(K)&&(K=A(K,U+(K.key==null||V&&V.key===K.key?"":(""+K.key).replace(M,"$&/")+"/")+te)),$.push(K)),1;te=0;var J=Z===""?".":Z+":";if(C(V))for(var ae=0;ae<V.length;ae++)Z=V[ae],ne=J+z(Z,ae),te+=F(Z,$,U,ne,K);else if(ae=m(V),typeof ae=="function")for(V=ae.call(V),ae=0;!(Z=V.next()).done;)Z=Z.value,ne=J+z(Z,ae++),te+=F(Z,$,U,ne,K);else if(ne==="object"){if(typeof V.then=="function")return F(H(V),$,U,Z,K);throw $=String(V),Error("Objects are not valid as a React child (found: "+($==="[object Object]"?"object with keys {"+Object.keys(V).join(", ")+"}":$)+"). If you meant to render a collection of children, use an array instead.")}return te}function B(V,$,U){if(V==null)return V;var Z=[],K=0;return F(V,Z,"","",function(ne){return $.call(U,ne,K++)}),Z}function q(V){if(V._status===-1){var $=V._result;$=$(),$.then(function(U){(V._status===0||V._status===-1)&&(V._status=1,V._result=U)},function(U){(V._status===0||V._status===-1)&&(V._status=2,V._result=U)}),V._status===-1&&(V._status=0,V._result=$)}if(V._status===1)return V._result.default;throw V._result}var D=typeof reportError=="function"?reportError:function(V){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var $=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof V=="object"&&V!==null&&typeof V.message=="string"?String(V.message):String(V),error:V});if(!window.dispatchEvent($))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",V);return}console.error(V)},G={map:B,forEach:function(V,$,U){B(V,function(){$.apply(this,arguments)},U)},count:function(V){var $=0;return B(V,function(){$++}),$},toArray:function(V){return B(V,function($){return $})||[]},only:function(V){if(!R(V))throw Error("React.Children.only expected to receive a single React element child.");return V}};return qr.Activity=p,qr.Children=G,qr.Component=S,qr.Fragment=r,qr.Profiler=a,qr.PureComponent=k,qr.StrictMode=s,qr.Suspense=u,qr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=j,qr.__COMPILER_RUNTIME={__proto__:null,c:function(V){return j.H.useMemoCache(V)}},qr.cache=function(V){return function(){return V.apply(null,arguments)}},qr.cacheSignal=function(){return null},qr.cloneElement=function(V,$,U){if(V==null)throw Error("The argument must be a React element, but you passed "+V+".");var Z=y({},V.props),K=V.key;if($!=null)for(ne in $.key!==void 0&&(K=""+$.key),$)!T.call($,ne)||ne==="key"||ne==="__self"||ne==="__source"||ne==="ref"&&$.ref===void 0||(Z[ne]=$[ne]);var ne=arguments.length-2;if(ne===1)Z.children=U;else if(1<ne){for(var te=Array(ne),J=0;J<ne;J++)te[J]=arguments[J+2];Z.children=te}return I(V.type,K,Z)},qr.createContext=function(V){return V={$$typeof:l,_currentValue:V,_currentValue2:V,_threadCount:0,Provider:null,Consumer:null},V.Provider=V,V.Consumer={$$typeof:i,_context:V},V},qr.createElement=function(V,$,U){var Z,K={},ne=null;if($!=null)for(Z in $.key!==void 0&&(ne=""+$.key),$)T.call($,Z)&&Z!=="key"&&Z!=="__self"&&Z!=="__source"&&(K[Z]=$[Z]);var te=arguments.length-2;if(te===1)K.children=U;else if(1<te){for(var J=Array(te),ae=0;ae<te;ae++)J[ae]=arguments[ae+2];K.children=J}if(V&&V.defaultProps)for(Z in te=V.defaultProps,te)K[Z]===void 0&&(K[Z]=te[Z]);return I(V,ne,K)},qr.createRef=function(){return{current:null}},qr.forwardRef=function(V){return{$$typeof:c,render:V}},qr.isValidElement=R,qr.lazy=function(V){return{$$typeof:f,_payload:{_status:-1,_result:V},_init:q}},qr.memo=function(V,$){return{$$typeof:d,type:V,compare:$===void 0?null:$}},qr.startTransition=function(V){var $=j.T,U={};j.T=U;try{var Z=V(),K=j.S;K!==null&&K(U,Z),typeof Z=="object"&&Z!==null&&typeof Z.then=="function"&&Z.then(E,D)}catch(ne){D(ne)}finally{$!==null&&U.types!==null&&($.types=U.types),j.T=$}},qr.unstable_useCacheRefresh=function(){return j.H.useCacheRefresh()},qr.use=function(V){return j.H.use(V)},qr.useActionState=function(V,$,U){return j.H.useActionState(V,$,U)},qr.useCallback=function(V,$){return j.H.useCallback(V,$)},qr.useContext=function(V){return j.H.useContext(V)},qr.useDebugValue=function(){},qr.useDeferredValue=function(V,$){return j.H.useDeferredValue(V,$)},qr.useEffect=function(V,$){return j.H.useEffect(V,$)},qr.useEffectEvent=function(V){return j.H.useEffectEvent(V)},qr.useId=function(){return j.H.useId()},qr.useImperativeHandle=function(V,$,U){return j.H.useImperativeHandle(V,$,U)},qr.useInsertionEffect=function(V,$){return j.H.useInsertionEffect(V,$)},qr.useLayoutEffect=function(V,$){return j.H.useLayoutEffect(V,$)},qr.useMemo=function(V,$){return j.H.useMemo(V,$)},qr.useOptimistic=function(V,$){return j.H.useOptimistic(V,$)},qr.useReducer=function(V,$,U){return j.H.useReducer(V,$,U)},qr.useRef=function(V){return j.H.useRef(V)},qr.useState=function(V){return j.H.useState(V)},qr.useSyncExternalStore=function(V,$,U){return j.H.useSyncExternalStore(V,$,U)},qr.useTransition=function(){return j.H.useTransition()},qr.version="19.2.7",qr}var uPe;function $N(){return uPe||(uPe=1,rK.exports=tqt()),rK.exports}var g=$N();const Le=zl(g),x_=XVt({__proto__:null,default:Le},[g]);var sK={exports:{}},UA={},aK={exports:{}},iK={};var dPe;function nqt(){return dPe||(dPe=1,(function(e){function t(H,F){var B=H.length;H.push(F);e:for(;0<B;){var q=B-1>>>1,D=H[q];if(0<s(D,F))H[q]=F,H[B]=D,B=q;else break e}}function n(H){return H.length===0?null:H[0]}function r(H){if(H.length===0)return null;var F=H[0],B=H.pop();if(B!==F){H[0]=B;e:for(var q=0,D=H.length,G=D>>>1;q<G;){var V=2*(q+1)-1,$=H[V],U=V+1,Z=H[U];if(0>s($,B))U<D&&0>s(Z,$)?(H[q]=Z,H[U]=B,q=U):(H[q]=$,H[V]=B,q=V);else if(U<D&&0>s(Z,B))H[q]=Z,H[U]=B,q=U;else break e}}return F}function s(H,F){var B=H.sortIndex-F.sortIndex;return B!==0?B:H.id-F.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var a=performance;e.unstable_now=function(){return a.now()}}else{var i=Date,l=i.now();e.unstable_now=function(){return i.now()-l}}var c=[],u=[],d=1,f=null,p=3,h=!1,m=!1,v=!1,y=!1,b=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,x=typeof setImmediate<"u"?setImmediate:null;function k(H){for(var F=n(u);F!==null;){if(F.callback===null)r(u);else if(F.startTime<=H)r(u),F.sortIndex=F.expirationTime,t(c,F);else break;F=n(u)}}function _(H){if(v=!1,k(H),!m)if(n(c)!==null)m=!0,C||(C=!0,R());else{var F=n(u);F!==null&&z(_,F.startTime-H)}}var C=!1,E=-1,j=5,T=-1;function I(){return y?!0:!(e.unstable_now()-T<j)}function A(){if(y=!1,C){var H=e.unstable_now();T=H;var F=!0;try{e:{m=!1,v&&(v=!1,S(E),E=-1),h=!0;var B=p;try{t:{for(k(H),f=n(c);f!==null&&!(f.expirationTime>H&&I());){var q=f.callback;if(typeof q=="function"){f.callback=null,p=f.priorityLevel;var D=q(f.expirationTime<=H);if(H=e.unstable_now(),typeof D=="function"){f.callback=D,k(H),F=!0;break t}f===n(c)&&r(c),k(H)}else r(c);f=n(c)}if(f!==null)F=!0;else{var G=n(u);G!==null&&z(_,G.startTime-H),F=!1}}break e}finally{f=null,p=B,h=!1}F=void 0}}finally{F?R():C=!1}}}var R;if(typeof x=="function")R=function(){x(A)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,M=L.port2;L.port1.onmessage=A,R=function(){M.postMessage(null)}}else R=function(){b(A,0)};function z(H,F){E=b(function(){H(e.unstable_now())},F)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(H){H.callback=null},e.unstable_forceFrameRate=function(H){0>H||125<H?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):j=0<H?Math.floor(1e3/H):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_next=function(H){switch(p){case 1:case 2:case 3:var F=3;break;default:F=p}var B=p;p=F;try{return H()}finally{p=B}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(H,F){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var B=p;p=H;try{return F()}finally{p=B}},e.unstable_scheduleCallback=function(H,F,B){var q=e.unstable_now();switch(typeof B=="object"&&B!==null?(B=B.delay,B=typeof B=="number"&&0<B?q+B:q):B=q,H){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=B+D,H={id:d++,callback:F,priorityLevel:H,startTime:B,expirationTime:D,sortIndex:-1},B>q?(H.sortIndex=B,t(u,H),n(c)===null&&H===n(u)&&(v?(S(E),E=-1):v=!0,z(_,B-q))):(H.sortIndex=D,t(c,H),m||h||(m=!0,C||(C=!0,R()))),H},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(H){var F=p;return function(){var B=p;p=F;try{return H.apply(this,arguments)}finally{p=B}}}})(iK)),iK}var fPe;function rqt(){return fPe||(fPe=1,aK.exports=nqt()),aK.exports}var oK={exports:{}},vu={};var pPe;function sqt(){if(pPe)return vu;pPe=1;var e=$N();function t(c){var u="https://react.dev/errors/"+c;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var d=2;d<arguments.length;d++)u+="&args[]="+encodeURIComponent(arguments[d])}return"Minified React error #"+c+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(t(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},s=Symbol.for("react.portal");function a(c,u,d){var f=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:f==null?null:""+f,children:c,containerInfo:u,implementation:d}}var i=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,u){if(c==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return vu.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,vu.createPortal=function(c,u){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(t(299));return a(c,u,null,d)},vu.flushSync=function(c){var u=i.T,d=r.p;try{if(i.T=null,r.p=2,c)return c()}finally{i.T=u,r.p=d,r.d.f()}},vu.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))},vu.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},vu.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin),p=typeof u.integrity=="string"?u.integrity:void 0,h=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;d==="style"?r.d.S(c,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:f,integrity:p,fetchPriority:h}):d==="script"&&r.d.X(c,{crossOrigin:f,integrity:p,fetchPriority:h,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},vu.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)},vu.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})}},vu.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)},vu.requestFormReset=function(c){r.d.r(c)},vu.unstable_batchedUpdates=function(c,u){return c(u)},vu.useFormState=function(c,u,d){return i.H.useFormState(c,u,d)},vu.useFormStatus=function(){return i.H.useHostTransitionStatus()},vu.version="19.2.7",vu}var hPe;function Dat(){if(hPe)return oK.exports;hPe=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(),oK.exports=sqt(),oK.exports}var mPe;function aqt(){if(mPe)return UA;mPe=1;var e={env:{}};var t=rqt(),n=$N(),r=Dat();function s(w){var O="https://react.dev/errors/"+w;if(1<arguments.length){O+="?args[]="+encodeURIComponent(arguments[1]);for(var N=2;N<arguments.length;N++)O+="&args[]="+encodeURIComponent(arguments[N])}return"Minified React error #"+w+"; visit "+O+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function a(w){return!(!w||w.nodeType!==1&&w.nodeType!==9&&w.nodeType!==11)}function i(w){var O=w,N=w;if(w.alternate)for(;O.return;)O=O.return;else{w=O;do O=w,(O.flags&4098)!==0&&(N=O.return),w=O.return;while(w)}return O.tag===3?N:null}function l(w){if(w.tag===13){var O=w.memoizedState;if(O===null&&(w=w.alternate,w!==null&&(O=w.memoizedState)),O!==null)return O.dehydrated}return null}function c(w){if(w.tag===31){var O=w.memoizedState;if(O===null&&(w=w.alternate,w!==null&&(O=w.memoizedState)),O!==null)return O.dehydrated}return null}function u(w){if(i(w)!==w)throw Error(s(188))}function d(w){var O=w.alternate;if(!O){if(O=i(w),O===null)throw Error(s(188));return O!==w?null:w}for(var N=w,P=O;;){var W=N.return;if(W===null)break;var Q=W.alternate;if(Q===null){if(P=W.return,P!==null){N=P;continue}break}if(W.child===Q.child){for(Q=W.child;Q;){if(Q===N)return u(W),w;if(Q===P)return u(W),O;Q=Q.sibling}throw Error(s(188))}if(N.return!==P.return)N=W,P=Q;else{for(var ie=!1,Se=W.child;Se;){if(Se===N){ie=!0,N=W,P=Q;break}if(Se===P){ie=!0,P=W,N=Q;break}Se=Se.sibling}if(!ie){for(Se=Q.child;Se;){if(Se===N){ie=!0,N=Q,P=W;break}if(Se===P){ie=!0,P=Q,N=W;break}Se=Se.sibling}if(!ie)throw Error(s(189))}}if(N.alternate!==P)throw Error(s(190))}if(N.tag!==3)throw Error(s(188));return N.stateNode.current===N?w:O}function f(w){var O=w.tag;if(O===5||O===26||O===27||O===6)return w;for(w=w.child;w!==null;){if(O=f(w),O!==null)return O;w=w.sibling}return null}var p=Object.assign,h=Symbol.for("react.element"),m=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),S=Symbol.for("react.profiler"),x=Symbol.for("react.consumer"),k=Symbol.for("react.context"),_=Symbol.for("react.forward_ref"),C=Symbol.for("react.suspense"),E=Symbol.for("react.suspense_list"),j=Symbol.for("react.memo"),T=Symbol.for("react.lazy"),I=Symbol.for("react.activity"),A=Symbol.for("react.memo_cache_sentinel"),R=Symbol.iterator;function L(w){return w===null||typeof w!="object"?null:(w=R&&w[R]||w["@@iterator"],typeof w=="function"?w:null)}var M=Symbol.for("react.client.reference");function z(w){if(w==null)return null;if(typeof w=="function")return w.$$typeof===M?null:w.displayName||w.name||null;if(typeof w=="string")return w;switch(w){case y:return"Fragment";case S:return"Profiler";case b:return"StrictMode";case C:return"Suspense";case E:return"SuspenseList";case I:return"Activity"}if(typeof w=="object")switch(w.$$typeof){case v:return"Portal";case k:return w.displayName||"Context";case x:return(w._context.displayName||"Context")+".Consumer";case _:var O=w.render;return w=w.displayName,w||(w=O.displayName||O.name||"",w=w!==""?"ForwardRef("+w+")":"ForwardRef"),w;case j:return O=w.displayName||null,O!==null?O:z(w.type)||"Memo";case T:O=w._payload,w=w._init;try{return z(w(O))}catch{}}return null}var H=Array.isArray,F=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,B=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,q={pending:!1,data:null,method:null,action:null},D=[],G=-1;function V(w){return{current:w}}function $(w){0>G||(w.current=D[G],D[G]=null,G--)}function U(w,O){G++,D[G]=w.current,w.current=O}var Z=V(null),K=V(null),ne=V(null),te=V(null);function J(w,O){switch(U(ne,O),U(K,w),U(Z,null),O.nodeType){case 9:case 11:w=(w=O.documentElement)&&(w=w.namespaceURI)?N2e(w):0;break;default:if(w=O.tagName,O=O.namespaceURI)O=N2e(O),w=I2e(O,w);else switch(w){case"svg":w=1;break;case"math":w=2;break;default:w=0}}$(Z),U(Z,w)}function ae(){$(Z),$(K),$(ne)}function pe(w){w.memoizedState!==null&&U(te,w);var O=Z.current,N=I2e(O,w.type);O!==N&&(U(K,w),U(Z,N))}function Y(w){K.current===w&&($(Z),$(K)),te.current===w&&($(te),DA._currentValue=q)}var ee,ce;function de(w){if(ee===void 0)try{throw Error()}catch(N){var O=N.stack.trim().match(/\n( *(at )?)/);ee=O&&O[1]||"",ce=-1<N.stack.indexOf(`
|
|
3
3
|
at`)?" (<anonymous>)":-1<N.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
4
4
|
`+ee+w+ce}var oe=!1;function me(w,O){if(!w||oe)return"";oe=!0;var N=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var P={DetermineComponentFrameRoot:function(){try{if(O){var jt=function(){throw Error()};if(Object.defineProperty(jt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(jt,[])}catch(ft){var ot=ft}Reflect.construct(w,[],jt)}else{try{jt.call()}catch(ft){ot=ft}w.call(jt.prototype)}}else{try{throw Error()}catch(ft){ot=ft}(jt=w())&&typeof jt.catch=="function"&&jt.catch(function(){})}}catch(ft){if(ft&&ot&&typeof ft.stack=="string")return[ft.stack,ot.stack]}return[null,null]}};P.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var W=Object.getOwnPropertyDescriptor(P.DetermineComponentFrameRoot,"name");W&&W.configurable&&Object.defineProperty(P.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Q=P.DetermineComponentFrameRoot(),ie=Q[0],Se=Q[1];if(ie&&Se){var Be=ie.split(`
|
|
@@ -334,7 +334,7 @@ attempted value: ${i}
|
|
|
334
334
|
\${}
|
|
335
335
|
}
|
|
336
336
|
}`,{label:"class",detail:"definition",type:"keyword"}),Xd('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),Xd('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],L0t=uSe.concat([Xd("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),Xd("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),Xd("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),UFe=new Uyt,F0t=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function mR(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const _7n=["FunctionDeclaration"],C7n={FunctionDeclaration:mR("function"),ClassDeclaration:mR("class"),ClassExpression:()=>!0,EnumDeclaration:mR("constant"),TypeAliasDeclaration:mR("type"),NamespaceDeclaration:mR("namespace"),VariableDefinition(e,t){e.matchContext(_7n)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function z0t(e,t){let n=UFe.get(t);if(n)return n;let r=[],s=!0;function a(i,l){let c=e.sliceString(i.from,i.to);r.push({label:c,type:l})}return t.cursor(Fa.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=C7n[i.name];if(l&&l(i,a)||F0t.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of z0t(e,i.node))r.push(l);return!1}}),UFe.set(t,r),r}const nB=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,dSe=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function B0t(e){let t=mi(e.state).resolveInner(e.pos,-1);if(dSe.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&nB.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)F0t.has(s.name)&&(r=r.concat(z0t(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:nB}}function IJ(e,t,n){var r;let s=[];for(;;){let a=t.firstChild,i;if(a?.name=="VariableName")return s.push(e(a)),{path:s.reverse(),name:n};if(a?.name=="MemberExpression"&&((r=i=a.lastChild)===null||r===void 0?void 0:r.name)=="PropertyName")s.push(e(i)),t=a;else return null}}function U0t(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=mi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?IJ(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?IJ(t,n.parent,""):dSe.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&nB.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?IJ(t,n,""):e.explicit?{path:[],name:""}:null}function E7n(e,t){let n=e,r=[],s=new Set;for(let a=0;;a++){for(let l of(Object.getOwnPropertyNames||Object.keys)(e)){if(!/^[a-zA-Z_$\xaa-\uffdc][\w$\xaa-\uffdc]*$/.test(l)||s.has(l))continue;s.add(l);let c;try{c=n[l]}catch{continue}r.push({label:l,type:typeof c=="function"?/^[A-Z]/.test(l)?"class":t?"function":"method":t?"variable":"property",boost:-a})}let i=Object.getPrototypeOf(e);if(!i)return r;e=i}}function j7n(e){let t=new Map;return n=>{let r=U0t(n);if(!r)return null;let s=e;for(let i of r.path)if(s=s[i],!s)return null;let a=t.get(s);return a||t.set(s,a=E7n(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:nB}}}const Qh=FO.define({name:"javascript",parser:O7n.configure({props:[Z_.add({IfStatement:Uj({except:/^\s*({|else\b)/}),TryStatement:Uj({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:SFn,SwitchBody:e=>{let t=e.textAfter,n=/^\s*\}/.test(t),r=/^\s*(case|default)\b/.test(t);return e.baseIndent+(n?0:r?1:2)*e.unit},Block:wFn({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":Uj({except:/^\s*{/}),JSXElement(e){let t=/^\s*<\//.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},JSXEscape(e){let t=/\s*\}/.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},"JSXOpenTag JSXSelfClosingTag"(e){return e.column(e.node.from)+e.unit}}),G_.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":q1e,BlockComment(e){return{from:e.from+2,to:e.to-2}},JSXElement(e){let t=e.firstChild;if(!t||t.name=="JSXSelfClosingTag")return null;let n=e.lastChild;return{from:t.to,to:n.type.isError?e.to:n.from}},"JSXSelfClosingTag JSXOpenTag"(e){var t;let n=(t=e.firstChild)===null||t===void 0?void 0:t.nextSibling,r=e.lastChild;return!n||n.type.isError?null:{from:n.to,to:r.type.isError?e.to:r.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),V0t={test:e=>/^JSX/.test(e.name),facet:oH({commentTokens:{block:{open:"{/*",close:"*/}"}}})},fSe=Qh.configure({dialect:"ts"},"typescript"),pSe=Qh.configure({dialect:"jsx",props:[B1e.add(e=>e.isTop?[V0t]:void 0)]}),hSe=Qh.configure({dialect:"jsx ts",props:[B1e.add(e=>e.isTop?[V0t]:void 0)]},"typescript");let q0t=e=>({label:e,type:"keyword"});const H0t="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(q0t),T7n=H0t.concat(["declare","implements","private","protected","public"].map(q0t));function rB(e={}){let t=e.jsx?e.typescript?hSe:pSe:e.typescript?fSe:Qh,n=e.typescript?L0t.concat(T7n):uSe.concat(H0t);return new BO(t,[Qh.data.of({autocomplete:ozn(dSe,Vxt(n))}),Qh.data.of({autocomplete:B0t}),e.jsx?W0t:[]])}function N7n(e){for(;;){if(e.name=="JSXOpenTag"||e.name=="JSXSelfClosingTag"||e.name=="JSXFragmentTag")return e;if(e.name=="JSXEscape"||!e.parent)return null;e=e.parent}}function VFe(e,t,n=e.length){for(let r=t?.firstChild;r;r=r.nextSibling)if(r.name=="JSXIdentifier"||r.name=="JSXBuiltin"||r.name=="JSXNamespacedName"||r.name=="JSXMemberExpression")return e.sliceString(r.from,Math.min(r.to,n));return""}const I7n=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),W0t=Nt.inputHandler.of((e,t,n,r,s)=>{if((I7n?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!Qh.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u;let{head:d}=c,f=mi(i).resolveInner(d-1,-1),p;if(f.name=="JSXStartTag"&&(f=f.parent),!(i.doc.sliceString(d-1,d)!=r||f.name=="JSXAttributeValue"&&f.to>d)){if(r==">"&&f.name=="JSXFragmentTag")return{range:c,changes:{from:d,insert:"</>"}};if(r=="/"&&f.name=="JSXStartCloseTag"){let h=f.parent,m=h.parent;if(m&&h.from==d-2&&((p=VFe(i.doc,m.firstChild,d))||((u=m.firstChild)===null||u===void 0?void 0:u.name)=="JSXFragmentTag")){let v=`${p}>`;return{range:gt.cursor(d+v.length,-1),changes:{from:d,insert:v}}}}else if(r==">"){let h=N7n(f);if(h&&h.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(p=VFe(i.doc,h,d)))return{range:c,changes:{from:d,insert:`</${p}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function A7n(e,t){return t||(t={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:!0,node:!0,es6:!0,es2015:!0,es2017:!0,es2020:!0},rules:{}},e.getRules().forEach((n,r)=>{var s;!((s=n.meta.docs)===null||s===void 0)&&s.recommended&&(t.rules[r]=2)})),n=>{let{state:r}=n,s=[];for(let{from:a,to:i}of Qh.findRegions(r)){let l=r.doc.lineAt(a),c={line:l.number-1,col:a-l.from,pos:a};for(let u of e.verify(r.sliceDoc(a,i),t))s.push(R7n(u,r.doc,c))}return s}}function qFe(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function R7n(e,t,n){let r=qFe(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?qFe(e.endLine,e.endColumn,t,n):r,message:e.message,source:e.ruleId?"eslint:"+e.ruleId:"eslint",severity:e.severity==1?"warning":"error"};if(e.fix){let{range:a,text:i}=e.fix,l=a[0]+n.pos-r,c=a[1]+n.pos-r;s.actions=[{name:"fix",apply(u,d){u.dispatch({changes:{from:d+l,to:d+c,insert:i},scrollIntoView:!0})}}]}return s}const H6=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:W0t,completionPath:U0t,esLint:A7n,javascript:rB,javascriptLanguage:Qh,jsxLanguage:pSe,localCompletionSource:B0t,scopeCompletionSource:j7n,snippets:uSe,tsxLanguage:hSe,typescriptLanguage:fSe,typescriptSnippets:L0t},Symbol.toStringTag,{value:"Module"})),gR=["_blank","_self","_top","_parent"],AJ=["ascii","utf-8","utf-16","latin1","latin1"],RJ=["get","post","put","delete"],PJ=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],tp=["true","false"],er={},P7n={a:{attrs:{href:null,ping:null,type:null,media:null,target:gR,hreflang:null}},abbr:er,address:er,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:er,aside:er,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:er,base:{attrs:{href:null,target:gR}},bdi:er,bdo:er,blockquote:{attrs:{cite:null}},body:er,br:er,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:PJ,formmethod:RJ,formnovalidate:["novalidate"],formtarget:gR,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:er,center:er,cite:er,code:er,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:er,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:er,div:er,dl:er,dt:er,em:er,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:er,figure:er,footer:er,form:{attrs:{action:null,name:null,"accept-charset":AJ,autocomplete:["on","off"],enctype:PJ,method:RJ,novalidate:["novalidate"],target:gR}},h1:er,h2:er,h3:er,h4:er,h5:er,h6:er,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:er,hgroup:er,hr:er,html:{attrs:{manifest:null}},i:er,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:PJ,formmethod:RJ,formnovalidate:["novalidate"],formtarget:gR,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:er,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:er,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:er,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:AJ,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:er,noscript:er,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:er,param:{attrs:{name:null,value:null}},pre:er,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:er,rt:er,ruby:er,samp:er,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:AJ}},section:er,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:er,source:{attrs:{src:null,type:null,media:null}},span:er,strong:er,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:er,summary:er,sup:er,table:er,tbody:er,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:er,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:er,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:er,time:{attrs:{datetime:null}},title:er,tr:er,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:er,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:er},Z0t={accesskey:null,class:null,contenteditable:tp,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:tp,autocorrect:tp,autocapitalize:tp,style:null,tabindex:null,title:null,translate:["yes","no"],rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":tp,"aria-autocomplete":["inline","list","both","none"],"aria-busy":tp,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":tp,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":tp,"aria-hidden":tp,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":tp,"aria-multiselectable":tp,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":tp,"aria-relevant":null,"aria-required":tp,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null},G0t="beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map(e=>"on"+e);for(let e of G0t)Z0t[e]=null;class yM{constructor(t,n){this.tags={...P7n,...t},this.globalAttrs={...Z0t,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}yM.default=new yM;function DT(e,t,n=e.length){if(!t)return"";let r=t.firstChild,s=r&&r.getChild("TagName");return s?e.sliceString(s.from,Math.min(s.to,n)):""}function LT(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function Q0t(e,t,n){let r=n.tags[DT(e,LT(t))];return r?.children||n.allTags}function mSe(e,t){let n=[];for(let r=LT(t);r&&!r.type.isTop;r=LT(r.parent)){let s=DT(e,r);if(s&&r.lastChild.name=="CloseTag")break;s&&n.indexOf(s)<0&&(t.name=="EndTag"||t.from>=r.firstChild.to)&&n.push(s)}return n}const Y0t=/^[:\-\.\w\u00b7-\uffff]*$/;function HFe(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=LT(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:Q0t(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(mSe(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function WFe(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:mSe(e.doc,t).map((a,i)=>({label:a,apply:a+s,type:"type",boost:99-i})),validFor:Y0t}}function $7n(e,t,n,r){let s=[],a=0;for(let i of Q0t(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of mSe(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function M7n(e,t,n,r,s){let a=LT(n),i=a?t.tags[DT(e.doc,a)]:null,l=i&&i.attrs?Object.keys(i.attrs):[],c=i&&i.globalAttrs===!1?l:l.length?l.concat(t.globalAttrNames):t.globalAttrNames;return{from:r,to:s,options:c.map(u=>({label:u,type:"property"})),validFor:Y0t}}function D7n(e,t,n,r,s){var a;let i=(a=n.parent)===null||a===void 0?void 0:a.getChild("AttributeName"),l=[],c;if(i){let u=e.sliceDoc(i.from,i.to),d=t.globalAttrs[u];if(!d){let f=LT(n),p=f?t.tags[DT(e.doc,f)]:null;d=p?.attrs&&p.attrs[u]}if(d){let f=e.sliceDoc(r,s).toLowerCase(),p='"',h='"';/^['"]/.test(f)?(c=f[0]=='"'?/^[^"]*$/:/^[^']*$/,p="",h=e.sliceDoc(s,s+1)==f[0]?"":f[0],f=f.slice(1),r++):c=/^[^\s<>='"]*$/;for(let m of d)l.push({label:m,apply:p+m+h,type:"constant"})}}return{from:r,to:s,options:l,validFor:c}}function K0t(e,t){let{state:n,pos:r}=t,s=mi(n).resolveInner(r,-1),a=s.resolve(r);for(let i=r,l;a==s&&(l=s.childBefore(i));){let c=l.lastChild;if(!c||!c.type.isError||c.from<c.to)break;a=s=l,i=c.from}return s.name=="TagName"?s.parent&&/CloseTag$/.test(s.parent.name)?WFe(n,s,s.from,r):HFe(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?HFe(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?WFe(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?M7n(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?D7n(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?$7n(n,e,s,r):null}function L7n(e){return K0t(yM.default,e)}function F7n(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new yM(t,n):yM.default;return s=>K0t(r,s)}const z7n=Qh.parser.configure({top:"SingleExpression"}),X0t=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:fSe.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:pSe.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:hSe.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:z7n},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:Qh.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:tB.parser}],J0t=[{name:"style",parser:tB.parser.configure({top:"Styles"})}].concat(G0t.map(e=>({name:e,parser:Qh.parser}))),ewt=FO.define({name:"html",parser:d9n.configure({props:[Z_.add({Element(e){let t=/^(\s*)(<\/)?/.exec(e.textAfter);return e.node.to<=e.pos+t[0].length?e.continue():e.lineIndent(e.node.from)+(t[2]?0:e.unit)},"OpenTag CloseTag SelfClosingTag"(e){return e.column(e.node.from)+e.unit},Document(e){if(e.pos+/\s*/.exec(e.textAfter)[0].length<e.node.to)return e.continue();let t=null,n;for(let r=e.node;;){let s=r.lastChild;if(!s||s.name!="Element"||s.to!=r.to)break;t=r=s}return t&&!((n=t.lastChild)&&(n.name=="CloseTag"||n.name=="SelfClosingTag"))?e.lineIndent(t.from)+e.unit:null}}),G_.add({Element(e){let t=e.firstChild,n=e.lastChild;return!t||t.name!="OpenTag"?null:{from:t.to,to:n.name=="CloseTag"?n.from:e.to}}}),Mxt.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),_8=ewt.configure({wrap:I0t(X0t,J0t)});function B7n(e={}){let t="",n;e.matchClosingTags===!1&&(t="noMatch"),e.selfClosingTags===!0&&(t=(t?t+" ":"")+"selfClosing"),(e.nestedLanguages&&e.nestedLanguages.length||e.nestedAttributes&&e.nestedAttributes.length)&&(n=I0t((e.nestedLanguages||[]).concat(X0t),(e.nestedAttributes||[]).concat(J0t)));let r=n?ewt.configure({wrap:n,dialect:t}):t?_8.configure({dialect:t}):_8;return new BO(r,[_8.data.of({autocomplete:F7n(e)}),e.autoCloseTags!==!1?U7n:[],rB().support,Z9n().support])}const ZFe=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),U7n=Nt.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!_8.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u,d,f;let p=i.doc.sliceString(c.from-1,c.to)==r,{head:h}=c,m=mi(i).resolveInner(h,-1),v;if(p&&r==">"&&m.name=="EndTag"){let y=m.parent;if(((d=(u=y.parent)===null||u===void 0?void 0:u.lastChild)===null||d===void 0?void 0:d.name)!="CloseTag"&&(v=DT(i.doc,y.parent,h))&&!ZFe.has(v)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),S=`</${v}>`;return{range:c,changes:{from:h,to:b,insert:S}}}}else if(p&&r=="/"&&m.name=="IncompleteCloseTag"){let y=m.parent;if(m.from==h-2&&((f=y.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(v=DT(i.doc,y,h))&&!ZFe.has(v)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),S=`${v}>`;return{range:gt.cursor(h+S.length,-1),changes:{from:h,to:b,insert:S}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),twt=oH({commentTokens:{block:{open:"<!--",close:"-->"}}}),nwt=new Dr,rwt=p8n.configure({props:[G_.add(e=>!e.is("Block")||e.is("Document")||Cme(e)!=null||V7n(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),nwt.add(Cme),Z_.add({Document:()=>null}),ww.add({Document:twt})]});function Cme(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function V7n(e){return e.name=="OrderedList"||e.name=="BulletList"}function q7n(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=Cme(r.type))!=null&&s<=t)break;n=r}return n.to}const H7n=Oxt.of((e,t,n)=>{for(let r=mi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(nwt);if(s==null)continue;let a=q7n(r,s);if(a>n)return{from:n,to:a}}return null});function gSe(e){return new _p(twt,e,[],"markdown")}const swt=gSe(rwt),W7n=rwt.configure([O8n,C8n,_8n,E8n,{props:[G_.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),qO=gSe(W7n);function Z7n(e,t){return n=>{if(n&&e){let r=null;if(n=/\S*/.exec(n)[0],typeof e=="function"?r=e(n):r=ng.matchLanguageName(e,n,!0),r instanceof ng)return r.support?r.support.language.parser:zO.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class $J{constructor(t,n,r,s,a,i,l){this.node=t,this.from=n,this.to=r,this.spaceBefore=s,this.spaceAfter=a,this.type=i,this.item=l}blank(t,n=!0){let r=this.spaceBefore+(this.node.name=="Blockquote"?">":"");if(t!=null){for(;r.length<t;)r+=" ";return r}else{for(let s=this.to-this.from-r.length-this.spaceAfter.length;s>0;s--)r+=" ";return r+(n?this.spaceAfter:"")}}marker(t,n){let r=this.node.name=="OrderedList"?String(+iwt(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function awt(e,t){let n=[],r=[];for(let s=e;s;s=s.parent){if(s.name=="FencedCode")return r;(s.name=="ListItem"||s.name=="Blockquote")&&n.push(s)}for(let s=n.length-1;s>=0;s--){let a=n[s],i,l=t.lineAt(a.from),c=a.from-l.from;if(a.name=="Blockquote"&&(i=/^ *>( ?)/.exec(l.text.slice(c))))r.push(new $J(a,c,c+i[0].length,"",i[1],">",null));else if(a.name=="ListItem"&&a.parent.name=="OrderedList"&&(i=/^( *)\d+([.)])( *)/.exec(l.text.slice(c)))){let u=i[3],d=i[0].length;u.length>=4&&(u=u.slice(0,u.length-4),d-=4),r.push(new $J(a.parent,c,c+d,i[1],u,i[2],a))}else if(a.name=="ListItem"&&a.parent.name=="BulletList"&&(i=/^( *)([-+*])( {1,4}\[[ xX]\])?( +)/.exec(l.text.slice(c)))){let u=i[4],d=i[0].length;u.length>4&&(u=u.slice(0,u.length-4),d-=4);let f=i[2];i[3]&&(f+=i[3].replace(/[xX]/," ")),r.push(new $J(a.parent,c,c+d,i[1],u,f,a))}}return r}function iwt(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function MJ(e,t,n,r=0){for(let s=-1,a=e;;){if(a.name=="ListItem"){let l=iwt(a,t),c=+l[2];if(s>=0){if(c!=s+1)return;n.push({from:a.from+l[1].length,to:a.from+l[0].length,insert:String(s+2+r)})}s=c}let i=a.nextSibling;if(!i)break;a=i}}function vSe(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(iI)!=" ")return e;let r=Pg(e,4,n),s="";for(let a=r;a>0;)a>=4?(s+=" ",a-=4):(s+=" ",a--);return s+e.slice(n)}const owt=(e={})=>({state:t,dispatch:n})=>{let r=mi(t),{doc:s}=t,a=null,i=t.changeByRange(l=>{if(!l.empty||!qO.isActiveAt(t,l.from,-1)&&!qO.isActiveAt(t,l.from,1))return a={range:l};let c=l.from,u=s.lineAt(c),d=awt(r.resolveInner(c,-1),s);for(;d.length&&d[d.length-1].from>c-u.from;)d.pop();if(!d.length)return a={range:l};let f=d[d.length-1];if(f.to-f.spaceAfter.length>c-u.from)return a={range:l};let p=c>=f.to-f.spaceAfter.length&&!/\S/.test(u.text.slice(f.to));if(f.item&&p){let b=f.node.firstChild,S=f.node.getChild("ListItem","ListItem");if(b.to>=c||S&&S.to<c||u.from>0&&!/[^\s>]/.test(s.lineAt(u.from-1).text)||e.nonTightLists===!1){let x=d.length>1?d[d.length-2]:null,k,_="";x&&x.item?(k=u.from+x.from,_=x.marker(s,1)):k=u.from+(x?x.to:0);let C=[{from:k,to:c,insert:_}];return f.node.name=="OrderedList"&&MJ(f.item,s,C,-2),x&&x.node.name=="OrderedList"&&MJ(x.item,s,C),{range:gt.cursor(k+_.length),changes:C}}else{let x=QFe(d,t,u);return{range:gt.cursor(c+x.length+1),changes:{from:u.from,insert:x+t.lineBreak}}}}if(f.node.name=="Blockquote"&&p&&u.from){let b=s.lineAt(u.from-1),S=/>\s*$/.exec(b.text);if(S&&S.index==f.from){let x=t.changes([{from:b.from+S.index,to:b.to},{from:u.from+f.from,to:u.to}]);return{range:l.map(x),changes:x}}}let h=[];f.node.name=="OrderedList"&&MJ(f.item,s,h);let m=f.item&&f.item.from<u.from,v="";if(!m||/^[\s\d.)\-+*>]*/.exec(u.text)[0].length>=f.to)for(let b=0,S=d.length-1;b<=S;b++)v+=b==S&&!m?d[b].marker(s,1):d[b].blank(b<S?Pg(u.text,4,d[b+1].from)-v.length:null);let y=c;for(;y>u.from&&/\s/.test(u.text.charAt(y-u.from-1));)y--;return v=vSe(v,t),G7n(f.node,t.doc)&&(v=QFe(d,t,u)+t.lineBreak+v),h.push({from:y,to:c,insert:t.lineBreak+v}),{range:gt.cursor(y+v.length+1),changes:h}});return a?!1:(n(t.update(i,{scrollIntoView:!0,userEvent:"input"})),!0)},lwt=owt();function GFe(e){return e.name=="QuoteMark"||e.name=="ListMark"}function G7n(e,t){if(e.name!="OrderedList"&&e.name!="BulletList")return!1;let n=e.firstChild,r=e.getChild("ListItem","ListItem");if(!r)return!1;let s=t.lineAt(n.to),a=t.lineAt(r.from),i=/^[\s>]*$/.test(s.text);return s.number+(i?0:1)<a.number}function QFe(e,t,n){let r="";for(let s=0,a=e.length-2;s<=a;s++)r+=e[s].blank(s<a?Pg(n.text,4,e[s+1].from)-r.length:null,s<a);return vSe(r,t)}function Q7n(e,t){let n=e.resolveInner(t,-1),r=t;GFe(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(GFe(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const cwt=({state:e,dispatch:t})=>{let n=mi(e),r=null,s=e.changeByRange(a=>{let i=a.from,{doc:l}=e;if(a.empty&&qO.isActiveAt(e,a.from)){let c=l.lineAt(i),u=awt(Q7n(n,i),l);if(u.length){let d=u[u.length-1],f=d.to-d.spaceAfter.length+(d.spaceAfter?1:0);if(i-c.from>f&&!/\S/.test(c.text.slice(f,i-c.from)))return{range:gt.cursor(c.from+f),changes:{from:c.from+f,to:i}};if(i-c.from==f&&(!d.item||c.from<=d.item.from||!/\S/.test(c.text.slice(0,d.to)))){let p=c.from+d.from;if(d.item&&d.node.from<d.item.from&&/\S/.test(c.text.slice(d.from,d.to))){let h=d.blank(Pg(c.text,4,d.to)-Pg(c.text,4,d.from));return p==c.from&&(h=vSe(h,e)),{range:gt.cursor(p+h.length),changes:{from:p,to:c.from+d.to,insert:h}}}if(p<i)return{range:gt.cursor(p),changes:{from:p,to:i}}}}}return r={range:a}});return r?!1:(t(e.update(s,{scrollIntoView:!0,userEvent:"delete"})),!0)},uwt=[{key:"Enter",run:lwt},{key:"Backspace",run:cwt}],dwt=B7n({matchClosingTags:!1});function ySe(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=swt,completeHTMLTags:a=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=dwt}=e;if(!(s instanceof dH))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,H7n],d;i&&u.push(fwt),n instanceof BO?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?Z7n(t,d):void 0;c.push(m8n({codeParser:f,htmlParser:l.language.parser})),r&&u.push(Xp.high(aI.of(uwt)));let p=gSe(s.configure(c));return a&&u.push(p.data.of({autocomplete:Y7n})),new BO(p,u)}function Y7n(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=mi(t).resolveInner(n,-1);for(;s&&!s.type.isTop;){if(s.name=="CodeBlock"||s.name=="FencedCode"||s.name=="ProcessingInstructionBlock"||s.name=="CommentBlock"||s.name=="Link"||s.name=="Image")return null;s=s.parent}return{from:n-r[0].length,to:n,options:K7n(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let DJ=null;function K7n(){if(DJ)return DJ;let e=L7n(new G1e(cs.create({extensions:dwt}),0,!0));return DJ=e?e.options:[]}const X7n=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,fwt=Nt.domEventHandlers({paste:(e,t)=>{var n;let{main:r}=t.state.selection;if(r.empty)return!1;let s=(n=e.clipboardData)===null||n===void 0?void 0:n.getData("text/plain");if(!s||!/^(https?:\/\/|mailto:|xmpp:|www\.)/.test(s)||(/^www\./.test(s)&&(s="https://"+s),!qO.isActiveAt(t.state,r.from,1)))return!1;let a=mi(t.state),i=!1;return a.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||X7n.test(l.name))&&(i=!0)},leave:l=>{l.to<r.to&&(i=!0)}}),i?!1:(t.dispatch({changes:[{from:r.from,insert:"["},{from:r.to,insert:`](${s})`}],userEvent:"input.paste",scrollIntoView:!0}),!0)}}),J7n=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:swt,deleteMarkupBackward:cwt,insertNewlineContinueMarkup:lwt,insertNewlineContinueMarkupCommand:owt,markdown:ySe,markdownKeymap:uwt,markdownLanguage:qO,pasteURLAsLink:fwt},Symbol.toStringTag,{value:"Module"}));function HO(){return HO=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},HO.apply(null,arguments)}var eBn=e=>{var t=e.theme,n=e.settings,r=n===void 0?{}:n,s=e.styles,a=s===void 0?[]:s,i={".cm-gutters":{}},l={};r.background&&(l.backgroundColor=r.background),r.backgroundImage&&(l.backgroundImage=r.backgroundImage),r.foreground&&(l.color=r.foreground),r.fontSize&&(l.fontSize=r.fontSize),(r.background||r.foreground)&&(i["&"]=l),r.fontFamily&&(i["&.cm-editor .cm-scroller"]={fontFamily:r.fontFamily}),r.gutterBackground&&(i[".cm-gutters"].backgroundColor=r.gutterBackground),r.gutterForeground&&(i[".cm-gutters"].color=r.gutterForeground),r.gutterBorder&&(i[".cm-gutters"].borderRightColor=r.gutterBorder),r.caret&&(i[".cm-content"]={caretColor:r.caret},i[".cm-cursor, .cm-dropCursor"]={borderLeftColor:r.caret});var c={};r.gutterActiveForeground&&(c.color=r.gutterActiveForeground),r.lineHighlight&&(i[".cm-activeLine"]={backgroundColor:r.lineHighlight},c.backgroundColor=r.lineHighlight),i[".cm-activeLineGutter"]=c,r.selection&&(i["&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection"]={background:r.selection+" !important"}),r.selectionMatch&&(i["& .cm-selectionMatch"]={backgroundColor:r.selectionMatch});var u=Nt.theme(i,{dark:t==="dark"}),d=Ug.define(a),f=[u,H1(d)];return f},tBn={background:"#282a36",foreground:"#f8f8f2",caret:"#f8f8f0",selection:"rgba(255, 255, 255, 0.1)",selectionMatch:"rgba(255, 255, 255, 0.2)",gutterBackground:"#282a36",gutterForeground:"#6D8A88",gutterBorder:"transparent",lineHighlight:"rgba(255, 255, 255, 0.1)"},nBn=[{tag:fe.comment,color:"#6272a4"},{tag:fe.string,color:"#f1fa8c"},{tag:fe.atom,color:"#bd93f9"},{tag:fe.meta,color:"#f8f8f2"},{tag:[fe.keyword,fe.operator,fe.tagName],color:"#ff79c6"},{tag:[fe.function(fe.propertyName),fe.propertyName],color:"#66d9ef"},{tag:[fe.definition(fe.variableName),fe.function(fe.variableName),fe.className,fe.attributeName],color:"#50fa7b"},{tag:fe.atom,color:"#bd93f9"}],lI=e=>{var t=e||{},n=t.theme,r=n===void 0?"dark":n,s=t.settings,a=s===void 0?{}:s,i=t.styles,l=i===void 0?[]:i;return eBn({theme:r,settings:HO({},tBn,a),styles:[...nBn,...l]})};lI();function pwt(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}const rBn=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=xSe(e.state,n.from);return r.line?sBn(e):r.block?iBn(e):!1};function bSe(e,t){return({state:n,dispatch:r})=>{if(n.readOnly)return!1;let s=e(t,n);return s?(r(n.update(s)),!0):!1}}const sBn=bSe(cBn,0),aBn=bSe(hwt,0),iBn=bSe((e,t)=>hwt(e,t,lBn(t)),0);function xSe(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const vR=50;function oBn(e,{open:t,close:n},r,s){let a=e.sliceDoc(r-vR,r),i=e.sliceDoc(s,s+vR),l=/\s*$/.exec(a)[0].length,c=/^\s*/.exec(i)[0].length,u=a.length-l;if(a.slice(u-t.length,u)==t&&i.slice(c,c+n.length)==n)return{open:{pos:r-l,margin:l&&1},close:{pos:s+c,margin:c&&1}};let d,f;s-r<=2*vR?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+vR),f=e.sliceDoc(s-vR,s));let p=/^\s*/.exec(d)[0].length,h=/\s*$/.exec(f)[0].length,m=f.length-h-n.length;return d.slice(p,p+t.length)==t&&f.slice(m,m+n.length)==n?{open:{pos:r+p+t.length,margin:/\s/.test(d.charAt(p+t.length))?1:0},close:{pos:s-h-n.length,margin:/\s/.test(f.charAt(m-1))?1:0}}:null}function lBn(e){let t=[];for(let n of e.selection.ranges){let r=e.doc.lineAt(n.from),s=n.to<=r.to?r:e.doc.lineAt(n.to);s.from>r.from&&s.from==n.to&&(s=n.to==r.to+1?r:e.doc.lineAt(n.to-1));let a=t.length-1;a>=0&&t[a].to>r.from?t[a].to=s.to:t.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:s.to})}return t}function hwt(e,t,n=t.selection.ranges){let r=n.map(a=>xSe(t,a.from).block);if(!r.every(a=>a))return null;let s=n.map((a,i)=>oBn(t,r[i],a.from,a.to));if(e!=2&&!s.every(a=>a))return{changes:t.changes(n.map((a,i)=>s[i]?[]:[{from:a.from,insert:r[i].open+" "},{from:a.to,insert:" "+r[i].close}]))};if(e!=1&&s.some(a=>a)){let a=[];for(let i=0,l;i<s.length;i++)if(l=s[i]){let c=r[i],{open:u,close:d}=l;a.push({from:u.pos-c.open.length,to:u.pos+u.margin},{from:d.pos-d.margin,to:d.pos+c.close.length})}return{changes:a}}return null}function cBn(e,t,n=t.selection.ranges){let r=[],s=-1;e:for(let{from:a,to:i}of n){let l=r.length,c=1e9,u;for(let d=a;d<=i;){let f=t.doc.lineAt(d);if(u==null&&(u=xSe(t,f.from).line,!u))continue e;if(f.from>s&&(a==i||i>f.from)){s=f.from;let p=/^\s*/.exec(f.text)[0].length,h=p==f.length,m=f.text.slice(p,p+u.length)==u?p:-1;p<f.text.length&&p<c&&(c=p),r.push({line:f,comment:m,token:u,indent:p,empty:h,single:!1})}d=f.to+1}if(c<1e9)for(let d=l;d<r.length;d++)r[d].indent<r[d].line.text.length&&(r[d].indent=c);r.length==l+1&&(r[l].single=!0)}if(e!=2&&r.some(a=>a.comment<0&&(!a.empty||a.single))){let a=[];for(let{line:l,token:c,indent:u,empty:d,single:f}of r)(f||!d)&&a.push({from:l.from+u,insert:c+" "});let i=t.changes(a);return{changes:i,selection:t.selection.map(i,1)}}else if(e!=1&&r.some(a=>a.comment>=0)){let a=[];for(let{line:i,comment:l,token:c}of r)if(l>=0){let u=i.from+l,d=u+c.length;i.text[d-i.from]==" "&&d++,a.push({from:u,to:d})}return{changes:a}}return null}const Eme=Ly.define(),uBn=Ly.define(),dBn=On.define(),mwt=On.define({combine(e){return Fy(e,{minDepth:100,newGroupDelay:500,joinToEvent:(t,n)=>n},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(t,n)=>(r,s)=>t(r,s)||n(r,s)})}}),gwt=Sl.define({create(){return qv.empty},update(e,t){let n=t.state.facet(mwt),r=t.annotation(Eme);if(r){let c=ff.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=sB(d,d.length,n.minDepth,c):d=bwt(d,t.startState.selection),new qv(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(uBn);if((s=="full"||s=="before")&&(e=e.isolate()),t.annotation($l.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=ff.fromTransaction(t),i=t.annotation($l.time),l=t.annotation($l.userEvent);return a?e=e.addChanges(a,i,l,n,t):t.selection&&(e=e.addSelection(t.startState.selection,i,l,n.newGroupDelay)),(s=="full"||s=="after")&&(e=e.isolate()),e},toJSON(e){return{done:e.done.map(t=>t.toJSON()),undone:e.undone.map(t=>t.toJSON())}},fromJSON(e){return new qv(e.done.map(ff.fromJSON),e.undone.map(ff.fromJSON))}});function fBn(e={}){return[gwt,mwt.of(e),Nt.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?vwt:t.inputType=="historyRedo"?jme:null;return r?(t.preventDefault(),r(n)):!1}})]}function fH(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(gwt,!1);if(!s)return!1;let a=s.pop(e,n,t);return a?(r(a),!0):!1}}const vwt=fH(0,!1),jme=fH(1,!1),pBn=fH(0,!0),hBn=fH(1,!0);class ff{constructor(t,n,r,s,a){this.changes=t,this.effects=n,this.mapped=r,this.startSelection=s,this.selectionsAfter=a}setSelAfter(t){return new ff(this.changes,this.effects,this.mapped,this.startSelection,t)}toJSON(){var t,n,r;return{changes:(t=this.changes)===null||t===void 0?void 0:t.toJSON(),mapped:(n=this.mapped)===null||n===void 0?void 0:n.toJSON(),startSelection:(r=this.startSelection)===null||r===void 0?void 0:r.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(t){return new ff(t.changes&&Rl.fromJSON(t.changes),[],t.mapped&&ny.fromJSON(t.mapped),t.startSelection&>.fromJSON(t.startSelection),t.selectionsAfter.map(gt.fromJSON))}static fromTransaction(t,n){let r=zh;for(let s of t.startState.facet(dBn)){let a=s(t);a.length&&(r=r.concat(a))}return!r.length&&t.changes.empty?null:new ff(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,zh)}static selection(t){return new ff(void 0,zh,void 0,void 0,t)}}function sB(e,t,n,r){let s=t+1>n+20?t-n-1:0,a=e.slice(s,t);return a.push(r),a}function mBn(e,t){let n=[],r=!1;return e.iterChangedRanges((s,a)=>n.push(s,a)),t.iterChangedRanges((s,a,i,l)=>{for(let c=0;c<n.length;){let u=n[c++],d=n[c++];l>=u&&i<=d&&(r=!0)}}),r}function gBn(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function ywt(e,t){return e.length?t.length?e.concat(t):e:t}const zh=[],vBn=200;function bwt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-vBn));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),sB(e,e.length-1,1e9,n.setSelAfter(r)))}else return[ff.selection([t])]}function yBn(e){let t=e[e.length-1],n=e.slice();return n[e.length-1]=t.setSelAfter(t.selectionsAfter.slice(0,t.selectionsAfter.length-1)),n}function LJ(e,t){if(!e.length)return e;let n=e.length,r=zh;for(;n;){let s=bBn(e[n-1],t,r);if(s.changes&&!s.changes.empty||s.effects.length){let a=e.slice(0,n);return a[n-1]=s,a}else t=s.mapped,n--,r=s.selectionsAfter}return r.length?[ff.selection(r)]:zh}function bBn(e,t,n){let r=ywt(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):zh,n);if(!e.changes)return ff.selection(r);let s=e.changes.map(t),a=t.mapDesc(e.changes,!0),i=e.mapped?e.mapped.composeDesc(a):a;return new ff(s,vr.mapEffects(e.effects,t),i,e.startSelection.map(a),r)}const xBn=/^(input\.type|delete)($|\.)/;class qv{constructor(t,n,r=0,s=void 0){this.done=t,this.undone=n,this.prevTime=r,this.prevUserEvent=s}isolate(){return this.prevTime?new qv(this.done,this.undone):this}addChanges(t,n,r,s,a){let i=this.done,l=i[i.length-1];return l&&l.changes&&!l.changes.empty&&t.changes&&(!r||xBn.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(a,mBn(l.changes,t.changes))||r=="input.type.compose")?i=sB(i,i.length-1,s.minDepth,new ff(t.changes.compose(l.changes),ywt(vr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,zh)):i=sB(i,i.length,s.minDepth,t),new qv(i,zh,n,r)}addSelection(t,n,r,s){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:zh;return a.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&gBn(a[a.length-1],t)?this:new qv(bwt(this.done,t),this.undone,n,r)}addMapping(t){return new qv(LJ(this.done,t),LJ(this.undone,t),this.prevTime,this.prevUserEvent)}pop(t,n,r){let s=t==0?this.done:this.undone;if(s.length==0)return null;let a=s[s.length-1],i=a.selectionsAfter[0]||(a.startSelection?a.startSelection.map(a.changes.invertedDesc,1):n.selection);if(r&&a.selectionsAfter.length)return n.update({selection:a.selectionsAfter[a.selectionsAfter.length-1],annotations:Eme.of({side:t,rest:yBn(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(a.changes){let l=s.length==1?zh:s.slice(0,s.length-1);return a.mapped&&(l=LJ(l,a.mapped)),n.update({changes:a.changes,selection:a.startSelection,effects:a.effects,annotations:Eme.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}qv.empty=new qv(zh,zh);const wBn=[{key:"Mod-z",run:vwt,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:jme,preventDefault:!0},{linux:"Ctrl-Shift-z",run:jme,preventDefault:!0},{key:"Mod-u",run:pBn,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:hBn,preventDefault:!0}];function cI(e,t){return gt.create(e.ranges.map(t),e.mainIndex)}function Vg(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function qg({state:e,dispatch:t},n){let r=cI(e.selection,n);return r.eq(e.selection,!0)?!1:(t(Vg(e,r)),!0)}function pH(e,t){return gt.cursor(t?e.to:e.from)}function xwt(e,t){return qg(e,n=>n.empty?e.moveByChar(n,t):pH(n,t))}function Ju(e){return e.textDirectionAt(e.state.selection.main.head)==_i.LTR}const wwt=e=>xwt(e,!Ju(e)),Swt=e=>xwt(e,Ju(e));function kwt(e,t){return qg(e,n=>n.empty?e.moveByGroup(n,t):pH(n,t))}const SBn=e=>kwt(e,!Ju(e)),kBn=e=>kwt(e,Ju(e));function OBn(e,t,n){if(t.type.prop(n))return!0;let r=t.to-t.from;return r&&(r>2||/[^\s,.;:]/.test(e.sliceDoc(t.from,t.to)))||t.firstChild}function hH(e,t,n){let r=mi(e).resolveInner(t.head),s=n?Dr.closedBy:Dr.openedBy;for(let c=t.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;OBn(e,u,s)?r=u:c=n?u.to:u.from}let a=r.type.prop(s),i,l;return a&&(i=n?Vv(e,r.from,1):Vv(e,r.to,-1))&&i.matched?l=n?i.end.to:i.end.from:l=n?r.to:r.from,gt.cursor(l,n?-1:1)}const _Bn=e=>qg(e,t=>hH(e.state,t,!Ju(e))),CBn=e=>qg(e,t=>hH(e.state,t,Ju(e)));function Owt(e,t){return qg(e,n=>{if(!n.empty)return pH(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const _wt=e=>Owt(e,!1),Cwt=e=>Owt(e,!0);function Ewt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let a of e.state.facet(Nt.scrollMargins)){let i=a(e);i?.top&&(n=Math.max(i?.top,n)),i?.bottom&&(r=Math.max(i?.bottom,r))}s=e.scrollDOM.clientHeight-n-r}else s=(e.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:n,marginBottom:r,selfScroll:t,height:Math.max(e.defaultLineHeight,s-5)}}function jwt(e,t){let n=Ewt(e),{state:r}=e,s=cI(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):pH(i,t));if(s.eq(r.selection))return!1;let a;if(n.selfScroll){let i=e.coordsAtPos(r.selection.main.head),l=e.scrollDOM.getBoundingClientRect(),c=l.top+n.marginTop,u=l.bottom-n.marginBottom;i&&i.top>c&&i.bottom<u&&(a=Nt.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(Vg(r,s),{effects:a}),!0}const YFe=e=>jwt(e,!1),Tme=e=>jwt(e,!0);function W1(e,t,n){let r=e.lineBlockAt(t.head),s=e.moveToLineBoundary(t,n);if(s.head==t.head&&s.head!=(n?r.to:r.from)&&(s=e.moveToLineBoundary(t,n,!1)),!n&&s.head==r.from&&r.length){let a=/^\s*/.exec(e.state.sliceDoc(r.from,Math.min(r.from+100,r.to)))[0].length;a&&t.head!=r.from+a&&(s=gt.cursor(r.from+a))}return s}const EBn=e=>qg(e,t=>W1(e,t,!0)),jBn=e=>qg(e,t=>W1(e,t,!1)),TBn=e=>qg(e,t=>W1(e,t,!Ju(e))),NBn=e=>qg(e,t=>W1(e,t,Ju(e))),IBn=e=>qg(e,t=>gt.cursor(e.lineBlockAt(t.head).from,1)),ABn=e=>qg(e,t=>gt.cursor(e.lineBlockAt(t.head).to,-1));function RBn(e,t,n){let r=!1,s=cI(e.selection,a=>{let i=Vv(e,a.head,-1)||Vv(e,a.head,1)||a.head>0&&Vv(e,a.head-1,1)||a.head<e.doc.length&&Vv(e,a.head+1,-1);if(!i||!i.end)return a;r=!0;let l=i.start.from==a.head?i.end.to:i.end.from;return gt.cursor(l)});return r?(t(Vg(e,s)),!0):!1}const PBn=({state:e,dispatch:t})=>RBn(e,t);function Om(e,t,n){let r=cI(e.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=t&&(s=gt.range(s.head,s.anchor));let a=n(s);return gt.range(s.anchor,a.head,a.goalColumn,a.bidiLevel||void 0,a.assoc)});return r.eq(e.state.selection)?!1:(e.dispatch(Vg(e.state,r)),!0)}function Twt(e,t){return Om(e,t,n=>e.moveByChar(n,t))}const Nwt=e=>Twt(e,!Ju(e)),Iwt=e=>Twt(e,Ju(e));function Awt(e,t){return Om(e,t,n=>e.moveByGroup(n,t))}const $Bn=e=>Awt(e,!Ju(e)),MBn=e=>Awt(e,Ju(e)),DBn=e=>{let t=!Ju(e);return Om(e,t,n=>hH(e.state,n,t))},LBn=e=>{let t=Ju(e);return Om(e,t,n=>hH(e.state,n,t))};function Rwt(e,t){return Om(e,t,n=>e.moveVertically(n,t))}const Pwt=e=>Rwt(e,!1),$wt=e=>Rwt(e,!0);function Mwt(e,t){return Om(e,t,n=>e.moveVertically(n,t,Ewt(e).height))}const KFe=e=>Mwt(e,!1),XFe=e=>Mwt(e,!0),FBn=e=>Om(e,!0,t=>W1(e,t,!0)),zBn=e=>Om(e,!1,t=>W1(e,t,!1)),BBn=e=>{let t=!Ju(e);return Om(e,t,n=>W1(e,n,t))},UBn=e=>{let t=Ju(e);return Om(e,t,n=>W1(e,n,t))},VBn=e=>Om(e,!1,t=>gt.cursor(e.lineBlockAt(t.head).from)),qBn=e=>Om(e,!0,t=>gt.cursor(e.lineBlockAt(t.head).to)),JFe=({state:e,dispatch:t})=>(t(Vg(e,{anchor:0})),!0),eze=({state:e,dispatch:t})=>(t(Vg(e,{anchor:e.doc.length})),!0),tze=({state:e,dispatch:t})=>(t(Vg(e,{anchor:e.selection.main.anchor,head:0})),!0),nze=({state:e,dispatch:t})=>(t(Vg(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),HBn=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),WBn=({state:e,dispatch:t})=>{let n=mH(e).map(({from:r,to:s})=>gt.range(r,Math.min(s+1,e.doc.length)));return t(e.update({selection:gt.create(n),userEvent:"select"})),!0},ZBn=({state:e,dispatch:t})=>{let n=cI(e.selection,r=>{let s=mi(e),a=s.resolveStack(r.from,1);if(r.empty){let i=s.resolveStack(r.from,-1);i.node.from>=a.node.from&&i.node.to<=a.node.to&&(a=i)}for(let i=a;i;i=i.next){let{node:l}=i;if((l.from<r.from&&l.to>=r.to||l.to>r.to&&l.from<=r.from)&&i.next)return gt.range(l.to,l.from)}return r});return n.eq(e.selection)?!1:(t(Vg(e,n)),!0)};function Dwt(e,t){let{state:n}=e,r=n.selection,s=n.selection.ranges.slice();for(let a of n.selection.ranges){let i=n.doc.lineAt(a.head);if(t?i.to<e.state.doc.length:i.from>0)for(let l=a;;){let c=e.moveVertically(l,t);if(c.head<i.from||c.head>i.to){s.some(u=>u.head==c.head)||s.push(c);break}else{if(c.head==l.head)break;l=c}}}return s.length==r.ranges.length?!1:(e.dispatch(Vg(n,gt.create(s,s.length-1))),!0)}const GBn=e=>Dwt(e,!1),QBn=e=>Dwt(e,!0),YBn=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=gt.create([n.main]):n.main.empty||(r=gt.create([gt.cursor(n.main.head)])),r?(t(Vg(e,r)),!0):!1};function R4(e,t){if(e.state.readOnly)return!1;let n="delete.selection",{state:r}=e,s=r.changeByRange(a=>{let{from:i,to:l}=a;if(i==l){let c=t(a);c<i?(n="delete.backward",c=W6(e,c,!1)):c>i&&(n="delete.forward",c=W6(e,c,!0)),i=Math.min(i,c),l=Math.max(l,c)}else i=W6(e,i,!1),l=W6(e,l,!0);return i==l?{range:a}:{changes:{from:i,to:l},range:gt.cursor(i,i<a.head?-1:1)}});return s.changes.empty?!1:(e.dispatch(r.update(s,{scrollIntoView:!0,userEvent:n,effects:n=="delete.selection"?Nt.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function W6(e,t,n){if(e instanceof Nt)for(let r of e.state.facet(Nt.atomicRanges).map(s=>s(e)))r.between(t,t,(s,a)=>{s<t&&a>t&&(t=n?a:s)});return t}const Lwt=(e,t,n)=>R4(e,r=>{let s=r.from,{state:a}=e,i=a.doc.lineAt(s),l,c;if(n&&!t&&s>i.from&&s<i.from+200&&!/[^ \t]/.test(l=i.text.slice(0,s-i.from))){if(l[l.length-1]==" ")return s-1;let u=Pg(l,a.tabSize),d=u%UO(a)||UO(a);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=Oc(i.text,s-i.from,t,t)+i.from,c==s&&i.number!=(t?a.doc.lines:1)?c+=t?1:-1:!t&&/[\ufe00-\ufe0f]/.test(i.text.slice(c-i.from,s-i.from))&&(c=Oc(i.text,c-i.from,!1,!1)+i.from);return c}),Nme=e=>Lwt(e,!1,!0),Fwt=e=>Lwt(e,!0,!1),zwt=(e,t)=>R4(e,n=>{let r=n.head,{state:s}=e,a=s.doc.lineAt(r),i=s.charCategorizer(r);for(let l=null;;){if(r==(t?a.to:a.from)){r==n.head&&a.number!=(t?s.doc.lines:1)&&(r+=t?1:-1);break}let c=Oc(a.text,r-a.from,t)+a.from,u=a.text.slice(Math.min(r,c)-a.from,Math.max(r,c)-a.from),d=i(u);if(l!=null&&d!=l)break;(u!=" "||r!=n.head)&&(l=d),r=c}return r}),Bwt=e=>zwt(e,!1),KBn=e=>zwt(e,!0),XBn=e=>R4(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),JBn=e=>R4(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),eUn=e=>R4(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),tUn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:Sa.of(["",""])},range:gt.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},nUn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>{if(!r.empty||r.from==0||r.from==e.doc.length)return{range:r};let s=r.from,a=e.doc.lineAt(s),i=s==a.from?s-1:Oc(a.text,s-a.from,!1)+a.from,l=s==a.to?s+1:Oc(a.text,s-a.from,!0)+a.from;return{changes:{from:i,to:l,insert:e.doc.slice(s,l).append(e.doc.slice(i,s))},range:gt.cursor(l)}});return n.changes.empty?!1:(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function mH(e){let t=[],n=-1;for(let r of e.selection.ranges){let s=e.doc.lineAt(r.from),a=e.doc.lineAt(r.to);if(!r.empty&&r.to==a.from&&(a=e.doc.lineAt(r.to-1)),n>=s.number){let i=t[t.length-1];i.to=a.to,i.ranges.push(r)}else t.push({from:s.from,to:a.to,ranges:[r]});n=a.number+1}return t}function Uwt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let a of mH(e)){if(n?a.to==e.doc.length:a.from==0)continue;let i=e.doc.lineAt(n?a.to+1:a.from-1),l=i.length+1;if(n){r.push({from:a.to,to:i.to},{from:a.from,insert:i.text+e.lineBreak});for(let c of a.ranges)s.push(gt.range(Math.min(e.doc.length,c.anchor+l),Math.min(e.doc.length,c.head+l)))}else{r.push({from:i.from,to:a.from},{from:a.to,insert:e.lineBreak+i.text});for(let c of a.ranges)s.push(gt.range(c.anchor-l,c.head-l))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:gt.create(s,e.selection.mainIndex),userEvent:"move.line"})),!0):!1}const rUn=({state:e,dispatch:t})=>Uwt(e,t,!1),sUn=({state:e,dispatch:t})=>Uwt(e,t,!0);function Vwt(e,t,n){if(e.readOnly)return!1;let r=[];for(let a of mH(e))n?r.push({from:a.from,insert:e.doc.slice(a.from,a.to)+e.lineBreak}):r.push({from:a.to,insert:e.lineBreak+e.doc.slice(a.from,a.to)});let s=e.changes(r);return t(e.update({changes:s,selection:e.selection.map(s,n?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const aUn=({state:e,dispatch:t})=>Vwt(e,t,!1),iUn=({state:e,dispatch:t})=>Vwt(e,t,!0),oUn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(mH(t).map(({from:s,to:a})=>(s>0?s--:a<t.doc.length&&a++,{from:s,to:a}))),r=cI(t.selection,s=>{let a;if(e.lineWrapping){let i=e.lineBlockAt(s.head),l=e.coordsAtPos(s.head,s.assoc||1);l&&(a=i.bottom+e.documentTop-l.bottom+e.defaultLineHeight/2)}return e.moveVertically(s,!0,a)}).map(n);return e.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:"delete.line"}),!0};function lUn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=mi(e).resolveInner(t),r=n.childBefore(t),s=n.childAfter(t),a;return r&&s&&r.to<=t&&s.from>=t&&(a=r.type.prop(Dr.closedBy))&&a.indexOf(s.name)>-1&&e.doc.lineAt(r.to).from==e.doc.lineAt(s.from).from&&!/\S/.test(e.sliceDoc(r.to,s.from))?{from:r.to,to:s.from}:null}const rze=qwt(!1),cUn=qwt(!0);function qwt(e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let r=t.changeByRange(s=>{let{from:a,to:i}=s,l=t.doc.lineAt(a),c=!e&&a==i&&lUn(t,a);e&&(a=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new lH(t,{simulateBreak:a,simulateDoubleBreak:!!c}),d=U1e(u,a);for(d==null&&(d=Pg(/^\s*/.exec(t.doc.lineAt(a).text)[0],t.tabSize));i<l.to&&/\s/.test(l.text[i-l.from]);)i++;c?{from:a,to:i}=c:a>l.from&&a<l.from+100&&!/\S/.test(l.text.slice(0,a))&&(a=l.from);let f=["",uM(t,d)];return c&&f.push(uM(t,u.lineIndent(l.from,-1))),{changes:{from:a,to:i,insert:Sa.of(f)},range:gt.cursor(a+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function wSe(e,t){let n=-1;return e.changeByRange(r=>{let s=[];for(let i=r.from;i<=r.to;){let l=e.doc.lineAt(i);l.number>n&&(r.empty||r.to>l.from)&&(t(l,s,r),n=l.number),i=l.to+1}let a=e.changes(s);return{changes:s,range:gt.range(a.mapPos(r.anchor,1),a.mapPos(r.head,1))}})}const uUn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new lH(e,{overrideIndentation:a=>{let i=n[a];return i??-1}}),s=wSe(e,(a,i,l)=>{let c=U1e(r,a.from);if(c==null)return;/\S/.test(a.text)||(c=0);let u=/^\s*/.exec(a.text)[0],d=uM(e,c);(u!=d||l.from<a.from+u.length)&&(n[a.from]=c,i.push({from:a.from,to:a.from+u.length,insert:d}))});return s.changes.empty||t(e.update(s,{userEvent:"indent"})),!0},Hwt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(wSe(e,(n,r)=>{r.push({from:n.from,insert:e.facet(iI)})}),{userEvent:"input.indent"})),!0),Wwt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(wSe(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let a=Pg(s,e.tabSize),i=0,l=uM(e,Math.max(0,a-UO(e)));for(;i<s.length&&i<l.length&&s.charCodeAt(i)==l.charCodeAt(i);)i++;r.push({from:n.from+i,to:n.from+s.length,insert:l.slice(i)})}),{userEvent:"delete.dedent"})),!0),dUn=e=>(e.setTabFocusMode(),!0),fUn=[{key:"Ctrl-b",run:wwt,shift:Nwt,preventDefault:!0},{key:"Ctrl-f",run:Swt,shift:Iwt},{key:"Ctrl-p",run:_wt,shift:Pwt},{key:"Ctrl-n",run:Cwt,shift:$wt},{key:"Ctrl-a",run:IBn,shift:VBn},{key:"Ctrl-e",run:ABn,shift:qBn},{key:"Ctrl-d",run:Fwt},{key:"Ctrl-h",run:Nme},{key:"Ctrl-k",run:XBn},{key:"Ctrl-Alt-h",run:Bwt},{key:"Ctrl-o",run:tUn},{key:"Ctrl-t",run:nUn},{key:"Ctrl-v",run:Tme}],pUn=[{key:"ArrowLeft",run:wwt,shift:Nwt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:SBn,shift:$Bn,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:TBn,shift:BBn,preventDefault:!0},{key:"ArrowRight",run:Swt,shift:Iwt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:kBn,shift:MBn,preventDefault:!0},{mac:"Cmd-ArrowRight",run:NBn,shift:UBn,preventDefault:!0},{key:"ArrowUp",run:_wt,shift:Pwt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:JFe,shift:tze},{mac:"Ctrl-ArrowUp",run:YFe,shift:KFe},{key:"ArrowDown",run:Cwt,shift:$wt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:eze,shift:nze},{mac:"Ctrl-ArrowDown",run:Tme,shift:XFe},{key:"PageUp",run:YFe,shift:KFe},{key:"PageDown",run:Tme,shift:XFe},{key:"Home",run:jBn,shift:zBn,preventDefault:!0},{key:"Mod-Home",run:JFe,shift:tze},{key:"End",run:EBn,shift:FBn,preventDefault:!0},{key:"Mod-End",run:eze,shift:nze},{key:"Enter",run:rze,shift:rze},{key:"Mod-a",run:HBn},{key:"Backspace",run:Nme,shift:Nme,preventDefault:!0},{key:"Delete",run:Fwt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:Bwt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:KBn,preventDefault:!0},{mac:"Mod-Backspace",run:JBn,preventDefault:!0},{mac:"Mod-Delete",run:eUn,preventDefault:!0}].concat(fUn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),hUn=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:_Bn,shift:DBn},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:CBn,shift:LBn},{key:"Alt-ArrowUp",run:rUn},{key:"Shift-Alt-ArrowUp",run:aUn},{key:"Alt-ArrowDown",run:sUn},{key:"Shift-Alt-ArrowDown",run:iUn},{key:"Mod-Alt-ArrowUp",run:GBn},{key:"Mod-Alt-ArrowDown",run:QBn},{key:"Escape",run:YBn},{key:"Mod-Enter",run:cUn},{key:"Alt-l",mac:"Ctrl-l",run:WBn},{key:"Mod-i",run:ZBn,preventDefault:!0},{key:"Mod-[",run:Wwt},{key:"Mod-]",run:Hwt},{key:"Mod-Alt-\\",run:uUn},{key:"Shift-Mod-k",run:oUn},{key:"Shift-Mod-\\",run:PBn},{key:"Mod-/",run:rBn},{key:"Alt-A",run:aBn},{key:"Ctrl-m",mac:"Shift-Alt-m",run:dUn}].concat(pUn),mUn={key:"Tab",run:Hwt,shift:Wwt},sze=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class jx{constructor(t,n,r=0,s=t.length,a,i){this.test=i,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=t.iterRange(r,s),this.bufferStart=r,this.normalize=a?l=>a(sze(l)):sze,this.query=this.normalize(n)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return rf(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let t=this.peek();if(t<0)return this.done=!0,this;let n=k1e(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=Av(t);let s=this.normalize(n);if(s.length)for(let a=0,i=r,l=!0;;a++){let c=s.charCodeAt(a),u=this.match(c,i,l,this.bufferPos+this.bufferStart,a==s.length-1);if(u)return this.value=u,this;if(a==s.length-1)break;l&&a<n.length&&n.charCodeAt(a)==c?i++:l=!1}}}match(t,n,r,s,a){let i=null;for(let l=0;l<this.matches.length;){let c=this.matches[l],u=!1;this.query.charCodeAt(c.index)==t&&(c.index==this.query.length-1?i={from:c.from,to:s,precise:a&&c.precise}:(c.index++,u=!0)),u?l++:this.matches.splice(l,1)}return this.query.charCodeAt(0)==t&&(this.query.length==1?i={from:n,to:s,precise:r&&a}:this.matches.push({from:n,index:1,precise:r})),i&&this.test&&!this.test(i.from,i.to,this.buffer,this.bufferStart)&&(i=null),i}}typeof Symbol<"u"&&(jx.prototype[Symbol.iterator]=function(){return this});const Zwt={from:-1,to:-1,match:/.*/.exec(""),precise:!0},SSe="gm"+(/x/.unicode==null?"":"u");class Gwt{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=Zwt,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new Qwt(t,n,r,s,a);this.re=new RegExp(n,SSe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=aB(t,s),this.getLine(this.curLineStart)}getLine(t){this.iter.next(t),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let t=this.matchPos-this.curLineStart;;){this.re.lastIndex=t;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,s=r+n[0].length;if(this.matchPos=aB(this.text,s+(r==s?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<s||r>this.value.to)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,precise:!0,match:n},this;t=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),t=0;else return this.done=!0,this}}}const FJ=new WeakMap;class qj{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=FJ.get(t);if(!s||s.from>=r||s.to<=n){let l=new qj(n,t.sliceString(n,r));return FJ.set(t,l),l}if(s.from==n&&s.to==r)return s;let{text:a,from:i}=s;return i>n&&(a=t.sliceString(n,i)+a,i=n),s.to<r&&(a+=t.sliceString(s.to,r)),FJ.set(t,new qj(i,a)),new qj(n,a.slice(n-i,r-i))}}class Qwt{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=Zwt,this.matchPos=aB(t,s),this.re=new RegExp(n,SSe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=qj.get(t,s,this.chunkEnd(s+5e3))}chunkEnd(t){return t>=this.to?this.to:this.text.lineAt(t).to}next(){for(;;){let t=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==t&&(this.re.lastIndex=t+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,s=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,precise:!0,match:n},this.matchPos=aB(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=qj.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(Gwt.prototype[Symbol.iterator]=Qwt.prototype[Symbol.iterator]=function(){return this});function gUn(e){try{return new RegExp(e,SSe),!0}catch{return!1}}function aB(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}const vUn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=X6n(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(a=>{let i=a&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(a.elements.line.value);if(!i){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,u,d,f]=i,p=d?+d.slice(1):0,h=u?+u:l.number;if(u&&f){let y=h/100;c&&(y=y*(c=="-"?-1:1)+l.number/t.doc.lines),h=Math.round(t.doc.lines*y)}else u&&c&&(h=h*(c=="-"?-1:1)+l.number);let m=t.doc.line(Math.max(1,Math.min(t.doc.lines,h))),v=gt.cursor(m.from+Math.max(0,Math.min(p,m.length)));e.dispatch({effects:[r,Nt.scrollIntoView(v.from,{y:"center"})],selection:v})}),!0},yUn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},bUn=On.define({combine(e){return Fy(e,yUn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function xUn(e){return[_Un,OUn]}const wUn=jn.mark({class:"cm-selectionMatch"}),SUn=jn.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function aze(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=So.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=So.Word)}function kUn(e,t,n,r){return e(t.sliceDoc(n,n+1))==So.Word&&e(t.sliceDoc(r-1,r))==So.Word}const OUn=Co.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(bUn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return jn.none;let s=r.main,a,i=null;if(s.empty){if(!t.highlightWordAroundCursor)return jn.none;let c=n.wordAt(s.head);if(!c)return jn.none;i=n.charCategorizer(s.head),a=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<t.minSelectionLength||c>200)return jn.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),i=n.charCategorizer(s.head),!(aze(i,n,s.from,s.to)&&kUn(i,n,s.from,s.to)))return jn.none}else if(a=n.sliceDoc(s.from,s.to),!a)return jn.none}let l=[];for(let c of e.visibleRanges){let u=new jx(n.doc,a,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||aze(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(SUn.range(d,f)):(d>=s.to||f<=s.from)&&l.push(wUn.range(d,f)),l.length>t.maxMatches))return jn.none}}return jn.set(l)}},{decorations:e=>e.decorations}),_Un=Nt.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),CUn=({state:e,dispatch:t})=>{let{selection:n}=e,r=gt.create(n.ranges.map(s=>e.wordAt(s.head)||gt.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function EUn(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),a=s&&s.from==n.from&&s.to==n.to;for(let i=!1,l=new jx(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new jx(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),i=!0}else{if(i&&r.some(c=>c.from==l.value.from))continue;if(a){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const jUn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return CUn({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(a=>e.sliceDoc(a.from,a.to)!=r))return!1;let s=EUn(e,r);return s?(t(e.update({selection:e.selection.addRange(gt.range(s.from,s.to),!1),effects:Nt.scrollIntoView(s.to)})),!0):!1},uI=On.define({combine(e){return Fy(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new UUn(t),scrollToMatch:t=>Nt.scrollIntoView(t)})}});class Ywt{constructor(t){this.search=t.search,this.caseSensitive=!!t.caseSensitive,this.literal=!!t.literal,this.regexp=!!t.regexp,this.replace=t.replace||"",this.valid=!!this.search&&(!this.regexp||gUn(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
|
|
337
|
-
`:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new PUn(this):new IUn(this)}getCursor(t,n=0,r){let s=t.doc?t:cs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?qE(this,s,n,r):VE(this,s,n,r)}}class Kwt{constructor(t){this.spec=t}}function TUn(e,t,n){return(r,s,a,i)=>{if(n&&!n(r,s,a,i))return!1;let l=r>=i&&s<=i+a.length?a.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function VE(e,t,n,r){let s;return e.wholeWord&&(s=NUn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=TUn(e.test,t,s)),new jx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function NUn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(iB(s,n-a))!=So.Word||t(oB(s,n-a))!=So.Word)&&(t(oB(s,r-a))!=So.Word||t(iB(s,r-a))!=So.Word))}class IUn extends Kwt{constructor(t){super(t)}nextMatch(t,n,r){let s=VE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=VE(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),i=VE(this.spec,t,a,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=VE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=VE(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function AUn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function qE(e,t,n,r){let s;return e.wholeWord&&(s=RUn(t.charCategorizer(t.selection.main.head))),e.test&&(s=AUn(e.test,t,s)),new Gwt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function iB(e,t){return e.slice(Oc(e,t,!1),t)}function oB(e,t){return e.slice(t,Oc(e,t))}function RUn(e){return(t,n,r)=>!r[0].length||(e(iB(r.input,r.index))!=So.Word||e(oB(r.input,r.index))!=So.Word)&&(e(oB(r.input,r.index+r[0].length))!=So.Word||e(iB(r.input,r.index+r[0].length))!=So.Word)}class PUn extends Kwt{nextMatch(t,n,r){let s=qE(this.spec,t,r,t.doc.length).next();return s.done&&(s=qE(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=qE(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=qE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=qE(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const bM=vr.define(),kSe=vr.define(),Fw=Sl.define({create(e){return new zJ(Ime(e).create(),null)},update(e,t){for(let n of t.effects)n.is(bM)?e=new zJ(n.value.create(),e.panel):n.is(kSe)&&(e=new zJ(e.query,n.value?OSe:null));return e},provide:e=>cM.from(e,t=>t.panel)});class zJ{constructor(t,n){this.query=t,this.panel=n}}const $Un=jn.mark({class:"cm-searchMatch"}),MUn=jn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),DUn=Co.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Fw))}update(e){let t=e.state.field(Fw);(t!=e.startState.field(Fw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return jn.none;let{view:n}=this,r=new Rd;for(let s=0,a=n.visibleRanges,i=a.length;s<i;s++){let{from:l,to:c}=a[s];for(;s<i-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(p=>p.from==u&&p.to==d);r.add(u,d,f?MUn:$Un)})}return r.finish()}},{decorations:e=>e.decorations});function P4(e){return t=>{let n=t.state.field(Fw,!1);return n&&n.query.spec.valid?e(t,n):e1t(t)}}const lB=P4((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=gt.single(r.from,r.to),a=e.state.facet(uI);return e.dispatch({selection:s,effects:[_Se(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),Jwt(e),!0}),cB=P4((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=gt.single(s.from,s.to),i=e.state.facet(uI);return e.dispatch({selection:a,effects:[_Se(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),Jwt(e),!0}),LUn=P4((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:gt.create(n.map(r=>gt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),FUn=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],i=0;for(let l=new jx(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(gt.range(l.value.from,l.value.to))}return t(e.update({selection:gt.create(a,i),userEvent:"select.search.matches"})),!0},ize=P4((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let i=a,l=[],c,u,d=[];i.precise?i.from==r&&i.to==s&&(u=n.toText(t.getReplacement(i)),l.push({from:i.from,to:i.to,insert:u}),i=t.nextMatch(n,i.from,i.to),d.push(Nt.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=gt.single(i.from,i.to).map(f),d.push(_Se(e,i)),d.push(n.facet(uI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),zUn=P4((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Nt.announce.of(r),userEvent:"input.replace.all"}),!0});function OSe(e){return e.state.facet(uI).createPanel(e)}function Ime(e,t){var n,r,s,a,i;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let u=e.facet(uI);return new Ywt({search:((n=t?.literal)!==null&&n!==void 0?n:u.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t?.caseSensitive)!==null&&r!==void 0?r:u.caseSensitive,literal:(s=t?.literal)!==null&&s!==void 0?s:u.literal,regexp:(a=t?.regexp)!==null&&a!==void 0?a:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function Xwt(e){let t=z1e(e,OSe);return t&&t.dom.querySelector("[main-field]")}function Jwt(e){let t=Xwt(e);t&&t==e.root.activeElement&&t.select()}const e1t=e=>{let t=e.state.field(Fw,!1);if(t&&t.panel){let n=Xwt(e);if(n&&n!=e.root.activeElement){let r=Ime(e.state,t.query.spec);r.valid&&e.dispatch({effects:bM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[kSe.of(!0),t?bM.of(Ime(e.state,t.query.spec)):vr.appendConfig.of(qUn)]});return!0},t1t=e=>{let t=e.state.field(Fw,!1);if(!t||!t.panel)return!1;let n=z1e(e,OSe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:kSe.of(!1)}),!0},BUn=[{key:"Mod-f",run:e1t,scope:"editor search-panel"},{key:"F3",run:lB,shift:cB,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:lB,shift:cB,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:t1t,scope:"editor search-panel"},{key:"Mod-Shift-l",run:FUn},{key:"Mod-Alt-g",run:vUn},{key:"Mod-d",run:jUn,preventDefault:!0}];class UUn{constructor(t){this.view=t;let n=this.query=t.state.field(Fw).query.spec;this.commit=this.commit.bind(this),this.searchField=ui("input",{value:n.search,placeholder:np(t,"Find"),"aria-label":np(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=ui("input",{value:n.replace,placeholder:np(t,"Replace"),"aria-label":np(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=ui("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=ui("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=ui("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return ui("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=ui("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>lB(t),[np(t,"next")]),r("prev",()=>cB(t),[np(t,"previous")]),r("select",()=>LUn(t),[np(t,"all")]),ui("label",null,[this.caseField,np(t,"match case")]),ui("label",null,[this.reField,np(t,"regexp")]),ui("label",null,[this.wordField,np(t,"by word")]),...t.state.readOnly?[]:[ui("br"),this.replaceField,r("replace",()=>ize(t),[np(t,"replace")]),r("replaceAll",()=>zUn(t),[np(t,"replace all")])],ui("button",{name:"close",onclick:()=>t1t(t),"aria-label":np(t,"close"),type:"button"},["×"])])}commit(){let t=new Ywt({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});t.eq(this.query)||(this.query=t,this.view.dispatch({effects:bM.of(t)}))}keydown(t){l6n(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?cB:lB)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),ize(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(bM)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(t){this.query=t,this.searchField.value=t.search,this.replaceField.value=t.replace,this.caseField.checked=t.caseSensitive,this.reField.checked=t.regexp,this.wordField.checked=t.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(uI).top}}function np(e,t){return e.state.phrase(t)}const Z6=30,G6=/[\s\.,:;?!]/;function _Se(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-Z6),i=Math.min(s,n+Z6),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<Z6;c++)if(!G6.test(l[c+1])&&G6.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-Z6;c--)if(!G6.test(l[c-1])&&G6.test(l[c])){l=l.slice(0,c);break}}return Nt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const VUn=Nt.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),qUn=[Fw,Xp.low(DUn),VUn];class oze{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class wk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(xM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Rd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==p&&(v.to>v.from||v.to==p))l.push(v),d++,h=Math.min(v.to,h);else{h=Math.min(v.from,h);break}}let m=rVn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(p,p,jn.widget({widget:new JUn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,jn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new wk(u,n,FT(u))}}function FT(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new oze(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new oze(r.from,a,r.diagnostic)}}),r}function HUn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(xM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(n1t))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function WUn(e,t){return e.field(Cp,!1)?t:t.concat(vr.appendConfig.of(sVn))}const n1t=vr.define(),CSe=vr.define(),r1t=vr.define(),Cp=Sl.define({create(){return new wk(jn.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=FT(n,e.selected.diagnostic,a)||FT(n,null,a)}!n.size&&s&&t.state.facet(xM).autoPanel&&(s=null),e=new wk(n,s,r)}for(let n of t.effects)if(n.is(n1t)){let r=t.state.facet(xM).autoPanel?n.value.length?wM.open:null:e.panel;e=wk.init(n.value,r,t.state)}else n.is(CSe)?e=new wk(e.diagnostics,n.value?wM.open:null,e.selected):n.is(r1t)&&(e=new wk(e.diagnostics,e.panel,n.value));return e},provide:e=>[cM.from(e,t=>t.panel),Nt.decorations.from(e,t=>t.diagnostics)]}),ZUn=jn.mark({class:"cm-lintRange cm-lintRange-active"});function GUn(e,t,n){let{diagnostics:r}=e.state.field(Cp),s,a=-1,i=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,u,{spec:d})=>{if(t>=c&&t<=u&&(c==u||(t>c||n>0)&&(t<u||n<0)))return s=d.diagnostics,a=c,i=u,!1});let l=e.state.facet(xM).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:i,above:e.state.doc.lineAt(a).to<i,create(){return{dom:QUn(e,s)}}}:null}function QUn(e,t){return ui("ul",{class:"cm-tooltip-lint"},t.map(n=>a1t(e,n,!1)))}const YUn=e=>{let t=e.state.field(Cp,!1);(!t||!t.panel)&&e.dispatch({effects:WUn(e.state,[CSe.of(!0)])});let n=z1e(e,wM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},lze=e=>{let t=e.state.field(Cp,!1);return!t||!t.panel?!1:(e.dispatch({effects:CSe.of(!1)}),!0)},KUn=e=>{let t=e.state.field(Cp,!1);if(!t)return!1;let n=e.state.selection.main,r=t.diagnostics.iter(n.to+1);return!r.value&&(r=t.diagnostics.iter(0),!r.value||r.from==n.from&&r.to==n.to)?!1:(e.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0}),!0)},XUn=[{key:"Mod-Shift-m",run:YUn,preventDefault:!0},{key:"F8",run:KUn}],xM=On.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Fy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:cze,tooltipFilter:cze,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function cze(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function s1t(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function a1t(e,t,n){var r;let s=n?s1t(t.actions):[];return ui("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},ui("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,i)=>{let l=!1,c=h=>{if(h.preventDefault(),l)return;l=!0;let m=FT(e.state.field(Cp).diagnostics,t);m&&a.apply(e,m.from,m.to)},{name:u}=a,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),ui("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return ui("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&ui("div",{class:"cm-diagnosticSource"},t.source))}class JUn extends Jp{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return ui("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class uze{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=a1t(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class wM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)lze(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],i=s1t(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=FT(this.view.state.field(Cp).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=ui("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=ui("div",{class:"cm-panel-lint"},this.list,ui("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>lze(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Cp).selected;if(!t)return-1;for(let n=0;n<this.items.length;n++)if(this.items[n].diagnostic==t.diagnostic)return n;return-1}update(){let{diagnostics:t,selected:n}=this.view.state.field(Cp),r=0,s=!1,a=null,i=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(i.has(d))continue;i.add(d);let f=-1,p;for(let h=r;h<this.items.length;h++)if(this.items[h].diagnostic==d){f=h;break}f<0?(p=new uze(this.view,d),this.items.splice(r,0,p),s=!0):(p=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&p.diagnostic==n.diagnostic?p.dom.hasAttribute("aria-selected")||(p.dom.setAttribute("aria-selected","true"),a=p):p.dom.hasAttribute("aria-selected")&&p.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new uze(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let u=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/u:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/u)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Cp),r=FT(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:r1t.of(r)})}static open(t){return new wM(t)}}function eVn(e,t='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${t}>${encodeURIComponent(e)}</svg>')`}function Q6(e){return eVn(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${e}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const tVn=Nt.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:Q6("#d11")},".cm-lintRange-warning":{backgroundImage:Q6("orange")},".cm-lintRange-info":{backgroundImage:Q6("#999")},".cm-lintRange-hint":{backgroundImage:Q6("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});function nVn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function rVn(e){let t="hint",n=1;for(let r of e){let s=nVn(r.severity);s>n&&(n=s,t=r.severity)}return t}const sVn=[Cp,Nt.decorations.compute([Cp],e=>{let{selected:t,panel:n}=e.field(Cp);return!t||!n||t.from==t.to?jn.none:jn.set([ZUn.range(t.from,t.to)])}),Y6n(GUn,{hideOn:HUn}),tVn];var dze=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,a=[];t.closeBracketsKeymap!==!1&&(a=a.concat(Zzn)),t.defaultKeymap!==!1&&(a=a.concat(hUn)),t.searchKeymap!==!1&&(a=a.concat(BUn)),t.historyKeymap!==!1&&(a=a.concat(wBn)),t.foldKeymap!==!1&&(a=a.concat(AFn)),t.completionKeymap!==!1&&(a=a.concat(Jxt)),t.lintKeymap!==!1&&(a=a.concat(XUn));var i=[];return t.lineNumbers!==!1&&i.push(lFn()),t.highlightActiveLineGutter!==!1&&i.push(dFn()),t.highlightSpecialChars!==!1&&i.push(O6n()),t.history!==!1&&i.push(fBn()),t.foldGutter!==!1&&i.push(MFn()),t.drawSelection!==!1&&i.push(h6n()),t.dropCursor!==!1&&i.push(b6n()),t.allowMultipleSelections!==!1&&i.push(cs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(OFn()),t.syntaxHighlighting!==!1&&i.push(H1(zFn,{fallback:!0})),t.bracketMatching!==!1&&i.push(ZFn()),t.closeBrackets!==!1&&i.push(Vzn()),t.autocompletion!==!1&&i.push(Xxt()),t.rectangularSelection!==!1&&i.push(L6n()),s!==!1&&i.push(B6n()),t.highlightActiveLine!==!1&&i.push(N6n()),t.highlightSelectionMatches!==!1&&i.push(xUn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(iI.of(" ".repeat(t.tabSize))),i.concat([aI.of(a.flat())]).filter(Boolean)};const aVn="#e5c07b",fze="#e06c75",iVn="#56b6c2",oVn="#ffffff",C8="#abb2bf",Ame="#7d8799",lVn="#61afef",cVn="#98c379",pze="#d19a66",uVn="#c678dd",dVn="#21252b",hze="#2c313a",mze="#282c34",BJ="#353a42",fVn="#3E4451",gze="#528bff",pVn=Nt.theme({"&":{color:C8,backgroundColor:mze},".cm-content":{caretColor:gze},".cm-cursor, .cm-dropCursor":{borderLeftColor:gze},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:fVn},".cm-panels":{backgroundColor:dVn,color:C8},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#6699ff0b"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847"},".cm-gutters":{backgroundColor:mze,color:Ame,border:"none"},".cm-activeLineGutter":{backgroundColor:hze},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:BJ},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:BJ,borderBottomColor:BJ},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:hze,color:C8}}},{dark:!0}),hVn=Ug.define([{tag:fe.keyword,color:uVn},{tag:[fe.name,fe.deleted,fe.character,fe.propertyName,fe.macroName],color:fze},{tag:[fe.function(fe.variableName),fe.labelName],color:lVn},{tag:[fe.color,fe.constant(fe.name),fe.standard(fe.name)],color:pze},{tag:[fe.definition(fe.name),fe.separator],color:C8},{tag:[fe.typeName,fe.className,fe.number,fe.changed,fe.annotation,fe.modifier,fe.self,fe.namespace],color:aVn},{tag:[fe.operator,fe.operatorKeyword,fe.url,fe.escape,fe.regexp,fe.link,fe.special(fe.string)],color:iVn},{tag:[fe.meta,fe.comment],color:Ame},{tag:fe.strong,fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.link,color:Ame,textDecoration:"underline"},{tag:fe.heading,fontWeight:"bold",color:fze},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:pze},{tag:[fe.processingInstruction,fe.string,fe.inserted],color:cVn},{tag:fe.invalid,color:oVn}]),mVn=[pVn,H1(hVn)];var gVn=Nt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),vVn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,v=[];switch(s&&v.unshift(aI.of([mUn])),m&&(typeof m=="boolean"?v.unshift(dze()):v.unshift(dze(m))),p&&v.unshift(P6n(p)),d){case"light":v.push(gVn);break;case"dark":v.push(mVn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(Nt.editable.of(!1)),c&&v.push(cs.readOnly.of(!0)),[...v]},yVn=e=>({line:e.state.doc.lineAt(e.state.selection.main.from),lineCount:e.state.doc.lines,lineBreak:e.state.lineBreak,length:e.state.doc.length,readOnly:e.state.readOnly,tabSize:e.state.tabSize,selection:e.state.selection,selectionAsSingle:e.state.selection.asSingle().main,ranges:e.state.selection.ranges,selectionCode:e.state.sliceDoc(e.state.selection.main.from,e.state.selection.main.to),selections:e.state.selection.ranges.map(t=>e.state.sliceDoc(t.from,t.to)),selectedText:e.state.selection.ranges.some(t=>!t.empty)});class bVn{constructor(t,n){this.timeLeftMS=void 0,this.timeoutMS=void 0,this.isCancelled=!1,this.isTimeExhausted=!1,this.callbacks=[],this.timeLeftMS=n,this.timeoutMS=n,this.callbacks.push(t)}tick(){if(!this.isCancelled&&!this.isTimeExhausted&&(this.timeLeftMS--,this.timeLeftMS<=0)){this.isTimeExhausted=!0;var t=this.callbacks.slice();this.callbacks.length=0,t.forEach(n=>{try{n()}catch(r){console.error("TimeoutLatch callback error:",r)}})}}cancel(){this.isCancelled=!0,this.callbacks.length=0}reset(){this.timeLeftMS=this.timeoutMS,this.isCancelled=!1,this.isTimeExhausted=!1}get isDone(){return this.isCancelled||this.isTimeExhausted}}class vze{constructor(){this.interval=null,this.latches=new Set}add(t){this.latches.add(t),this.start()}remove(t){this.latches.delete(t),this.latches.size===0&&this.stop()}start(){this.interval===null&&(this.interval=setInterval(()=>{this.latches.forEach(t=>{t.tick(),t.isDone&&this.remove(t)})},1))}stop(){this.interval!==null&&(clearInterval(this.interval),this.interval=null)}}var UJ=null,xVn=()=>typeof window>"u"?new vze:(UJ||(UJ=new vze),UJ),wVn=Nt.theme({"& .cm-scroller":{height:"100% !important"}}),yze=null,VJ=null;function SVn(e,t,n,r,s,a){if(!e&&!t&&!n&&!r&&!s&&!a)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a});return i===yze||(yze=i,VJ=Nt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),VJ}var bze=Ly.define(),kVn=200,OVn=[];function _Vn(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,a=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?OVn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,S=e.width,x=S===void 0?null:S,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,E=C===void 0?null:C,j=e.placeholder,T=j===void 0?"":j,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,M=e.indentWithTab,z=M===void 0?!0:M,H=e.basicSetup,F=H===void 0?!0:H,B=e.root,q=e.initialState,D=g.useState(),G=D[0],V=D[1],$=g.useState(),U=$[0],Z=$[1],K=g.useState(),ne=K[0],te=K[1],J=g.useState(()=>({current:null}))[0],ae=g.useState(()=>({current:null}))[0],pe=SVn(h,v,b,x,_,E),Y=Nt.updateListener.of(de=>{if(de.docChanged&&typeof r=="function"&&!de.transactions.some(be=>be.annotation(bze))){J.current?J.current.reset():(J.current=new bVn(()=>{if(ae.current){var be=ae.current;ae.current=null,be()}J.current=null},kVn),xVn().add(J.current));var oe=de.state.doc,me=oe.toString();r(me,de)}s&&s(yVn(de))}),ee=vVn({theme:f,editable:A,readOnly:L,placeholder:T,indentWithTab:z,basicSetup:F}),ce=[Y,...pe?[pe]:[],wVn,...ee];return i&&typeof i=="function"&&ce.push(Nt.updateListener.of(i)),ce=ce.concat(c),g.useLayoutEffect(()=>{if(G&&!ne){var de={doc:t,selection:n,extensions:ce},oe=q?cs.fromJSON(q.json,de,q.fields):cs.create(de);if(te(oe),!U){var me=new Nt({state:oe,parent:G,root:B});Z(me),a&&a(me,oe)}}return()=>{U&&(te(void 0),Z(void 0))}},[G,ne]),g.useEffect(()=>{e.container&&V(e.container)},[e.container]),g.useEffect(()=>()=>{U&&(U.destroy(),Z(void 0)),J.current&&(J.current.cancel(),J.current=null)},[U]),g.useEffect(()=>{u&&U&&U.focus()},[u,U]),g.useEffect(()=>{U&&U.dispatch({effects:vr.reconfigure.of(ce)})},[f,c,h,v,b,x,_,E,T,A,L,z,F,r,i]),g.useEffect(()=>{if(t!==void 0){var de=U?U.state.doc.toString():"";if(U&&t!==de){var oe=J.current&&!J.current.isDone,me=()=>{U&&t!==U.state.doc.toString()&&U.dispatch({changes:{from:0,to:U.state.doc.toString().length,insert:t||""},annotations:[bze.of(!0)]})};oe?ae.current=me:me()}}},[t,U]),{state:ne,setState:te,view:U,setView:Z,container:G,setContainer:V}}var CVn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],Gu=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,v=e.height,y=e.minHeight,b=e.maxHeight,S=e.width,x=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,E=e.indentWithTab,j=e.editable,T=e.readOnly,I=e.root,A=e.initialState,R=pwt(e,CVn),L=g.useRef(null),M=_Vn({root:I,value:s,autoFocus:p,theme:m,height:v,minHeight:y,maxHeight:b,width:S,minWidth:x,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:E,editable:j,readOnly:T,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),z=M.state,H=M.view,F=M.container,B=M.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:z,view:H}),[L,F,z,H]);var q=g.useCallback(G=>{L.current=G,B(G)},[B]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var D=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",HO({ref:q,className:""+D+(n?" "+n:"")},R))});Gu.displayName="CodeMirror";const EVn={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash"};let qJ=null;function jVn(){return qJ||(qJ=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([go(()=>import("./core-BsSeUVq8.js"),__vite__mapDeps([0,1,2]),import.meta.url),go(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[go(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),go(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[go(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),go(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),go(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),go(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),go(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),go(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),go(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),go(()=>import("./python-DhUJRlN_.js"),[],import.meta.url)],engine:t()})})()),qJ}async function TVn(e,t){const n=EVn[t?.toLowerCase()];if(!n)return null;const r=await jVn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function NVn(e){return new BO(H1e.define(e))}const i1t=[ng.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return go(()=>Promise.resolve().then(()=>H6),void 0,import.meta.url).then(e=>e.javascript())}}),ng.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return go(()=>Promise.resolve().then(()=>azn),void 0,import.meta.url).then(e=>e.json())}}),ng.of({name:"JSX",extensions:["jsx"],load(){return go(()=>Promise.resolve().then(()=>H6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),ng.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return go(()=>Promise.resolve().then(()=>J7n),void 0,import.meta.url).then(e=>e.markdown())}}),ng.of({name:"TSX",extensions:["tsx"],load(){return go(()=>Promise.resolve().then(()=>H6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),ng.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return go(()=>Promise.resolve().then(()=>H6),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),ng.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return go(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>NVn(e.shell))}})];function IVn(e,t=5){if(!e?.properties)return[];const n=[];function r(s,a,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:a,label:a,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${a}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${a}[].${c}`,i+1)}for(const[s,a]of Object.entries(e.properties))r(a,s,1);return n}function AVn(e){const t=IVn(e);return Xxt({override:[RVn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function RVn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,p)=>{const v=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const PVn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,$Vn=jn.mark({class:"cm-variable-highlight"}),xze=new fxt({regexp:PVn,decoration:()=>$Vn}),MVn=Co.fromClass(class{decorations;constructor(e){this.decorations=xze.createDeco(e)}update(e){this.decorations=xze.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),DVn=MVn;function LVn(){const e=lI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[fe.className,fe.propertyName],color:"var(--neutral6)"},{tag:fe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.heading1,fe.heading2,fe.heading3,fe.heading4,fe.heading5,fe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:fe.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:fe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:fe.url,color:"var(--accent3)"},{tag:fe.monospace,color:"var(--neutral6)"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=Nt.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function FVn(){const e=Nt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=Ug.define([{tag:[fe.comment,fe.bracket],color:"var(--neutral2)"},{tag:[fe.string,fe.meta,fe.regexp],color:"var(--accent1)"},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:"var(--accent6)"},{tag:[fe.keyword,fe.operator,fe.tagName],color:"var(--accent2)"},{tag:[fe.function(fe.propertyName),fe.propertyName],color:"var(--accent5)"},{tag:[fe.definition(fe.variableName),fe.function(fe.variableName),fe.className,fe.attributeName],color:"var(--accent3)"},{tag:[fe.variableName,fe.number],color:"var(--accent5)"},{tag:[fe.name,fe.quote],color:"var(--accent1)"},{tag:fe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.heading1,fe.heading2,fe.heading3,fe.heading4,fe.heading5,fe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[fe.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:fe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:fe.url,color:"var(--accent3)"},{tag:fe.monospace,color:"var(--neutral6)"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:[fe.deleted],color:"var(--accent2)"},{tag:fe.invalid,color:"var(--error)"},{tag:[fe.standard(fe.tagName)],color:"var(--accent1)"}]);return[e,H1(t)]}const Kx=()=>{const e=q_().resolvedTheme==="dark";return g.useMemo(()=>e?LVn():FVn(),[e])},zVn=uo(X("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","duration-normal transition-colors ease-out-custom"),{variants:{variant:{default:"rounded-md border border-border1 bg-surface3 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),BVn=Xp.highest(Nt.editorAttributes.of({style:"outline: none"})),UVn=Xp.highest(Nt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),VVn=[BVn,UVn],Wr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,...m},v)=>{const y=Kx(),b=e?JSON.stringify(e,null,2):t??"",S=g.useMemo(()=>{const x=[...VVn];return f&&x.push(Nt.lineWrapping),a==="json"?x.push(Rp):a==="markdown"&&x.push(ySe({base:qO,codeLanguages:i1t})),i&&a==="markdown"&&x.push(DVn),c&&a==="markdown"&&x.push(AVn(c)),p===!1&&x.push(cs.readOnly.of(!0)),x},[a,i,c,p,f]);return o.jsxs("div",{className:X(zVn({variant:h}),s),...m,children:[r&&o.jsx($a,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(Gu,{ref:v,value:b,theme:y,extensions:S,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),qVn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},HVn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=Kx(),{settings:r,setSettings:s}=Uq(),a=r?.tracingOptions,i=g.useMemo(()=>qVn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=p=>{u.current=!0,c(p)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const p=JSON.parse(l);typeof p=="object"&&p!==null&&s({...r,tracingOptions:p})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(Gu,{value:l,onChange:d,theme:n,extensions:[Rp],className:X("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(le,{type:"button",onClick:f,children:"Save"})})]})},WVn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(qe,{children:o.jsx(tq,{})})})}),o.jsx($n,{children:"Run Options"})]}),o.jsx(br,{open:e,onOpenChange:t,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Run Options"}),o.jsx(Ks,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx($r,{children:o.jsx(HVn,{onSaved:()=>t(!1)})})]})})]})};function ZVn({status:e}){switch(e){case"running":return o.jsx(Kt,{});case"failed":return o.jsx(bs,{className:"text-accent2"});case"canceled":return o.jsx(If,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(hT,{className:"text-neutral3"});case"suspended":return o.jsx(YV,{className:"text-accent3"});case"success":return o.jsx(pa,{className:"text-accent1"});default:return o.jsx(hT,{className:"text-neutral3"})}}function o1t({status:e}){return o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx(qe,{"aria-label":e,className:"shrink-0",children:o.jsx(ZVn,{status:e})})}),o.jsx($n,{children:e})]})}var HJ,wze;function ESe(){if(wze)return HJ;wze=1;var e="\0",t="\0",n="";class r{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(d){d&&(this._isDirected=Object.hasOwn(d,"directed")?d.directed:!0,this._isMultigraph=Object.hasOwn(d,"multigraph")?d.multigraph:!1,this._isCompound=Object.hasOwn(d,"compound")?d.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(d){return this._label=d,this}graph(){return this._label}setDefaultNodeLabel(d){return this._defaultNodeLabelFn=d,typeof d!="function"&&(this._defaultNodeLabelFn=()=>d),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var d=this;return this.nodes().filter(f=>Object.keys(d._in[f]).length===0)}sinks(){var d=this;return this.nodes().filter(f=>Object.keys(d._out[f]).length===0)}setNodes(d,f){var p=arguments,h=this;return d.forEach(function(m){p.length>1?h.setNode(m,f):h.setNode(m)}),this}setNode(d,f){return Object.hasOwn(this._nodes,d)?(arguments.length>1&&(this._nodes[d]=f),this):(this._nodes[d]=arguments.length>1?f:this._defaultNodeLabelFn(d),this._isCompound&&(this._parent[d]=t,this._children[d]={},this._children[t][d]=!0),this._in[d]={},this._preds[d]={},this._out[d]={},this._sucs[d]={},++this._nodeCount,this)}node(d){return this._nodes[d]}hasNode(d){return Object.hasOwn(this._nodes,d)}removeNode(d){var f=this;if(Object.hasOwn(this._nodes,d)){var p=h=>f.removeEdge(f._edgeObjs[h]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(h){f.setParent(h)}),delete this._children[d]),Object.keys(this._in[d]).forEach(p),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(p),delete this._out[d],delete this._sucs[d],--this._nodeCount}return this}setParent(d,f){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(f===void 0)f=t;else{f+="";for(var p=f;p!==void 0;p=this.parent(p))if(p===d)throw new Error("Setting "+f+" as parent of "+d+" would create a cycle");this.setNode(f)}return this.setNode(d),this._removeFromParentsChildList(d),this._parent[d]=f,this._children[f][d]=!0,this}_removeFromParentsChildList(d){delete this._children[this._parent[d]][d]}parent(d){if(this._isCompound){var f=this._parent[d];if(f!==t)return f}}children(d=t){if(this._isCompound){var f=this._children[d];if(f)return Object.keys(f)}else{if(d===t)return this.nodes();if(this.hasNode(d))return[]}}predecessors(d){var f=this._preds[d];if(f)return Object.keys(f)}successors(d){var f=this._sucs[d];if(f)return Object.keys(f)}neighbors(d){var f=this.predecessors(d);if(f){const h=new Set(f);for(var p of this.successors(d))h.add(p);return Array.from(h.values())}}isLeaf(d){var f;return this.isDirected()?f=this.successors(d):f=this.neighbors(d),f.length===0}filterNodes(d){var f=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});f.setGraph(this.graph());var p=this;Object.entries(this._nodes).forEach(function([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,p.edge(v))});var h={};function m(v){var y=p.parent(v);return y===void 0||f.hasNode(y)?(h[v]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var p=this,h=arguments;return d.reduce(function(m,v){return h.length>1?p.setEdge(m,v,f):p.setEdge(m,v),v}),this}setEdge(){var d,f,p,h,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,p=v.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=v,f=arguments[1],p=arguments[3],arguments.length>2&&(h=arguments[2],m=!0)),d=""+d,f=""+f,p!==void 0&&(p=""+p);var y=i(this._isDirected,d,f,p);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=h),this;if(p!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(d),this.setNode(f),this._edgeLabels[y]=m?h:this._defaultEdgeLabelFn(d,f,p);var b=l(this._isDirected,d,f,p);return d=b.v,f=b.w,Object.freeze(b),this._edgeObjs[y]=b,s(this._preds[f],d),s(this._sucs[d],f),this._in[f][y]=b,this._out[d][y]=b,this._edgeCount++,this}edge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return this._edgeLabels[h]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return Object.hasOwn(this._edgeLabels,h)}removeEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p),m=this._edgeObjs[h];return m&&(d=m.v,f=m.w,delete this._edgeLabels[h],delete this._edgeObjs[h],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][h],delete this._out[d][h],this._edgeCount--),this}inEdges(d,f){var p=this._in[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.v===f):h}}outEdges(d,f){var p=this._out[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.w===f):h}}nodeEdges(d,f){var p=this.inEdges(d,f);if(p)return p.concat(this.outEdges(d,f))}}function s(u,d){u[d]?u[d]++:u[d]=1}function a(u,d){--u[d]||delete u[d]}function i(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}return h+n+m+n+(p===void 0?e:p)}function l(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}var y={v:h,w:m};return p&&(y.name=p),y}function c(u,d){return i(u,d.v,d.w,d.name)}return HJ=r,HJ}var WJ,Sze;function GVn(){return Sze||(Sze=1,WJ="2.2.4"),WJ}var ZJ,kze;function QVn(){return kze||(kze=1,ZJ={Graph:ESe(),version:GVn()}),ZJ}var GJ,Oze;function YVn(){if(Oze)return GJ;Oze=1;var e=ESe();GJ={write:t,read:s};function t(a){var i={options:{directed:a.isDirected(),multigraph:a.isMultigraph(),compound:a.isCompound()},nodes:n(a),edges:r(a)};return a.graph()!==void 0&&(i.value=structuredClone(a.graph())),i}function n(a){return a.nodes().map(function(i){var l=a.node(i),c=a.parent(i),u={v:i};return l!==void 0&&(u.value=l),c!==void 0&&(u.parent=c),u})}function r(a){return a.edges().map(function(i){var l=a.edge(i),c={v:i.v,w:i.w};return i.name!==void 0&&(c.name=i.name),l!==void 0&&(c.value=l),c})}function s(a){var i=new e(a.options).setGraph(a.value);return a.nodes.forEach(function(l){i.setNode(l.v,l.value),l.parent&&i.setParent(l.v,l.parent)}),a.edges.forEach(function(l){i.setEdge({v:l.v,w:l.w,name:l.name},l.value)}),i}return GJ}var QJ,_ze;function KVn(){if(_ze)return QJ;_ze=1,QJ=e;function e(t){var n={},r=[],s;function a(i){Object.hasOwn(n,i)||(n[i]=!0,s.push(i),t.successors(i).forEach(a),t.predecessors(i).forEach(a))}return t.nodes().forEach(function(i){s=[],a(i),s.length&&r.push(s)}),r}return QJ}var YJ,Cze;function l1t(){if(Cze)return YJ;Cze=1;class e{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(n){return n.key})}has(n){return Object.hasOwn(this._keyIndices,n)}priority(n){var r=this._keyIndices[n];if(r!==void 0)return this._arr[r].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(n,r){var s=this._keyIndices;if(n=String(n),!Object.hasOwn(s,n)){var a=this._arr,i=a.length;return s[n]=i,a.push({key:n,priority:r}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var n=this._arr.pop();return delete this._keyIndices[n.key],this._heapify(0),n.key}decrease(n,r){var s=this._keyIndices[n];if(r>this._arr[s].priority)throw new Error("New priority is greater than current priority. Key: "+n+" Old: "+this._arr[s].priority+" New: "+r);this._arr[s].priority=r,this._decrease(s)}_heapify(n){var r=this._arr,s=2*n,a=s+1,i=n;s<r.length&&(i=r[s].priority<r[i].priority?s:i,a<r.length&&(i=r[a].priority<r[i].priority?a:i),i!==n&&(this._swap(n,i),this._heapify(i)))}_decrease(n){for(var r=this._arr,s=r[n].priority,a;n!==0&&(a=n>>1,!(r[a].priority<s));)this._swap(n,a),n=a}_swap(n,r){var s=this._arr,a=this._keyIndices,i=s[n],l=s[r];s[n]=l,s[r]=i,a[l.key]=n,a[i.key]=r}}return YJ=e,YJ}var KJ,Eze;function c1t(){if(Eze)return KJ;Eze=1;var e=l1t();KJ=n;var t=()=>1;function n(s,a,i,l){return r(s,String(a),i||t,l||function(c){return s.outEdges(c)})}function r(s,a,i,l){var c={},u=new e,d,f,p=function(h){var m=h.v!==d?h.v:h.w,v=c[m],y=i(h),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+h+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(h){var m=h===a?0:Number.POSITIVE_INFINITY;c[h]={distance:m},u.add(h,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(p);return c}return KJ}var XJ,jze;function XVn(){if(jze)return XJ;jze=1;var e=c1t();XJ=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return XJ}var JJ,Tze;function u1t(){if(Tze)return JJ;Tze=1,JJ=e;function e(t){var n=0,r=[],s={},a=[];function i(l){var c=s[l]={onStack:!0,lowlink:n,index:n++};if(r.push(l),t.successors(l).forEach(function(f){Object.hasOwn(s,f)?s[f].onStack&&(c.lowlink=Math.min(c.lowlink,s[f].index)):(i(f),c.lowlink=Math.min(c.lowlink,s[f].lowlink))}),c.lowlink===c.index){var u=[],d;do d=r.pop(),s[d].onStack=!1,u.push(d);while(l!==d);a.push(u)}}return t.nodes().forEach(function(l){Object.hasOwn(s,l)||i(l)}),a}return JJ}var eee,Nze;function JVn(){if(Nze)return eee;Nze=1;var e=u1t();eee=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return eee}var tee,Ize;function eqn(){if(Ize)return tee;Ize=1,tee=t;var e=()=>1;function t(r,s,a){return n(r,s||e,a||function(i){return r.outEdges(i)})}function n(r,s,a){var i={},l=r.nodes();return l.forEach(function(c){i[c]={},i[c][c]={distance:0},l.forEach(function(u){c!==u&&(i[c][u]={distance:Number.POSITIVE_INFINITY})}),a(c).forEach(function(u){var d=u.v===c?u.w:u.v,f=s(u);i[c][d]={distance:f,predecessor:c}})}),l.forEach(function(c){var u=i[c];l.forEach(function(d){var f=i[d];l.forEach(function(p){var h=f[c],m=u[p],v=f[p],y=h.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return tee}var nee,Aze;function d1t(){if(Aze)return nee;Aze=1;function e(n){var r={},s={},a=[];function i(l){if(Object.hasOwn(s,l))throw new t;Object.hasOwn(r,l)||(s[l]=!0,r[l]=!0,n.predecessors(l).forEach(i),delete s[l],a.push(l))}if(n.sinks().forEach(i),Object.keys(r).length!==n.nodeCount())throw new t;return a}class t extends Error{constructor(){super(...arguments)}}return nee=e,e.CycleException=t,nee}var ree,Rze;function tqn(){if(Rze)return ree;Rze=1;var e=d1t();ree=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return ree}var see,Pze;function f1t(){if(Pze)return see;Pze=1,see=e;function e(s,a,i){Array.isArray(a)||(a=[a]);var l=s.isDirected()?f=>s.successors(f):f=>s.neighbors(f),c=i==="post"?t:n,u=[],d={};return a.forEach(f=>{if(!s.hasNode(f))throw new Error("Graph does not have node: "+f);c(f,l,d,u)}),u}function t(s,a,i,l){for(var c=[[s,!1]];c.length>0;){var u=c.pop();u[1]?l.push(u[0]):Object.hasOwn(i,u[0])||(i[u[0]]=!0,c.push([u[0],!0]),r(a(u[0]),d=>c.push([d,!1])))}}function n(s,a,i,l){for(var c=[s];c.length>0;){var u=c.pop();Object.hasOwn(i,u)||(i[u]=!0,l.push(u),r(a(u),d=>c.push(d)))}}function r(s,a){for(var i=s.length;i--;)a(s[i],i,s);return s}return see}var aee,$ze;function nqn(){if($ze)return aee;$ze=1;var e=f1t();aee=t;function t(n,r){return e(n,r,"post")}return aee}var iee,Mze;function rqn(){if(Mze)return iee;Mze=1;var e=f1t();iee=t;function t(n,r){return e(n,r,"pre")}return iee}var oee,Dze;function sqn(){if(Dze)return oee;Dze=1;var e=ESe(),t=l1t();oee=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var p=f.v===c?f.w:f.v,h=l.priority(p);if(h!==void 0){var m=s(f);m<h&&(i[p]=c,l.decrease(p,m))}}if(r.nodeCount()===0)return a;r.nodes().forEach(function(f){l.add(f,Number.POSITIVE_INFINITY),a.setNode(f)}),l.decrease(r.nodes()[0],0);for(var d=!1;l.size()>0;){if(c=l.removeMin(),Object.hasOwn(i,c))a.setEdge(c,i[c]);else{if(d)throw new Error("Input graph is not connected: "+r);d=!0}r.nodeEdges(c).forEach(u)}return a}return oee}var lee,Lze;function aqn(){return Lze||(Lze=1,lee={components:KVn(),dijkstra:c1t(),dijkstraAll:XVn(),findCycles:JVn(),floydWarshall:eqn(),isAcyclic:tqn(),postorder:nqn(),preorder:rqn(),prim:sqn(),tarjan:u1t(),topsort:d1t()}),lee}var cee,Fze;function Mg(){if(Fze)return cee;Fze=1;var e=QVn();return cee={Graph:e.Graph,json:YVn(),alg:aqn(),version:e.version},cee}var uee,zze;function iqn(){if(zze)return uee;zze=1;class e{constructor(){let s={};s._next=s._prev=s,this._sentinel=s}dequeue(){let s=this._sentinel,a=s._prev;if(a!==s)return t(a),a}enqueue(s){let a=this._sentinel;s._prev&&s._next&&t(s),s._next=a._next,a._next._prev=s,a._next=s,s._prev=a}toString(){let s=[],a=this._sentinel,i=a._prev;for(;i!==a;)s.push(JSON.stringify(i,n)),i=i._prev;return"["+s.join(", ")+"]"}}function t(r){r._prev._next=r._next,r._next._prev=r._prev,delete r._next,delete r._prev}function n(r,s){if(r!=="_next"&&r!=="_prev")return s}return uee=e,uee}var dee,Bze;function oqn(){if(Bze)return dee;Bze=1;let e=Mg().Graph,t=iqn();dee=r;let n=()=>1;function r(u,d){if(u.nodeCount()<=1)return[];let f=i(u,d||n);return s(f.graph,f.buckets,f.zeroIdx).flatMap(h=>u.outEdges(h.v,h.w))}function s(u,d,f){let p=[],h=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=h.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){p=p.concat(a(u,d,f,v,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);h&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(v=>{let y=u.edge(v),b=v.w,S=u.node(b);S.in-=y,l(d,f,S)}),u.removeNode(p.v),m}function i(u,d){let f=new e,p=0,h=0;u.nodes().forEach(y=>{f.setNode(y,{v:y,in:0,out:0})}),u.edges().forEach(y=>{let b=f.edge(y.v,y.w)||0,S=d(y),x=b+S;f.setEdge(y.v,y.w,x),h=Math.max(h,f.node(y.v).out+=S),p=Math.max(p,f.node(y.w).in+=S)});let m=c(h+p+3).map(()=>new t),v=p+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return dee}var fee,Uze;function Dl(){if(Uze)return fee;Uze=1;let e=Mg().Graph;fee={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:C,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:_,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:x,zipObject:E};function t(j,T,I,A){for(var R=A;j.hasNode(R);)R=x(A);return I.dummy=T,j.setNode(R,I),R}function n(j){let T=new e().setGraph(j.graph());return j.nodes().forEach(I=>T.setNode(I,j.node(I))),j.edges().forEach(I=>{let A=T.edge(I.v,I.w)||{weight:0,minlen:1},R=j.edge(I);T.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),T}function r(j){let T=new e({multigraph:j.isMultigraph()}).setGraph(j.graph());return j.nodes().forEach(I=>{j.children(I).length||T.setNode(I,j.node(I))}),j.edges().forEach(I=>{T.setEdge(I,j.edge(I))}),T}function s(j){let T=j.nodes().map(I=>{let A={};return j.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+j.edge(R).weight}),A});return E(j.nodes(),T)}function a(j){let T=j.nodes().map(I=>{let A={};return j.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+j.edge(R).weight}),A});return E(j.nodes(),T)}function i(j,T){let I=j.x,A=j.y,R=T.x-I,L=T.y-A,M=j.width/2,z=j.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,F;return Math.abs(L)*M>Math.abs(R)*z?(L<0&&(z=-z),H=z*R/L,F=z):(R<0&&(M=-M),H=M,F=M*L/R),{x:I+H,y:A+F}}function l(j){let T=k(m(j)+1).map(()=>[]);return j.nodes().forEach(I=>{let A=j.node(I),R=A.rank;R!==void 0&&(T[R][A.order]=I)}),T}function c(j){let T=j.nodes().map(A=>{let R=j.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,T);j.nodes().forEach(A=>{let R=j.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(j){let T=j.nodes().map(M=>j.node(M).rank),I=h(Math.min,T),A=[];j.nodes().forEach(M=>{let z=j.node(M).rank-I;A[z]||(A[z]=[]),A[z].push(M)});let R=0,L=j.graph().nodeRankFactor;Array.from(A).forEach((M,z)=>{M===void 0&&z%L!==0?--R:M!==void 0&&R&&M.forEach(H=>j.node(H).rank+=R)})}function d(j,T,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(j,"border",R,T)}function f(j,T=p){const I=[];for(let A=0;A<j.length;A+=T){const R=j.slice(A,A+T);I.push(R)}return I}const p=65535;function h(j,T){if(T.length>p){const I=f(T);return j.apply(null,I.map(A=>j.apply(null,A)))}else return j.apply(null,T)}function m(j){const I=j.nodes().map(A=>{let R=j.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function v(j,T){let I={lhs:[],rhs:[]};return j.forEach(A=>{T(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(j,T){let I=Date.now();try{return T()}finally{console.log(j+" time: "+(Date.now()-I)+"ms")}}function b(j,T){return T()}let S=0;function x(j){var T=++S;return j+(""+T)}function k(j,T,I=1){T==null&&(T=j,j=0);let A=L=>L<T;I<0&&(A=L=>T<L);const R=[];for(let L=j;A(L);L+=I)R.push(L);return R}function _(j,T){const I={};for(const A of T)j[A]!==void 0&&(I[A]=j[A]);return I}function C(j,T){let I=T;return typeof T=="string"&&(I=A=>A[T]),Object.entries(j).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function E(j,T){return j.reduce((I,A,R)=>(I[A]=T[R],I),{})}return fee}var pee,Vze;function lqn(){if(Vze)return pee;Vze=1;let e=oqn(),t=Dl().uniqueId;pee={run:n,undo:s};function n(a){(a.graph().acyclicer==="greedy"?e(a,l(a)):r(a)).forEach(c=>{let u=a.edge(c);a.removeEdge(c),u.forwardName=c.name,u.reversed=!0,a.setEdge(c.w,c.v,u,t("rev"))});function l(c){return u=>c.edge(u).weight}}function r(a){let i=[],l={},c={};function u(d){Object.hasOwn(c,d)||(c[d]=!0,l[d]=!0,a.outEdges(d).forEach(f=>{Object.hasOwn(l,f.w)?i.push(f):u(f.w)}),delete l[d])}return a.nodes().forEach(u),i}function s(a){a.edges().forEach(i=>{let l=a.edge(i);if(l.reversed){a.removeEdge(i);let c=l.forwardName;delete l.reversed,delete l.forwardName,a.setEdge(i.w,i.v,l,c)}})}return pee}var hee,qze;function cqn(){if(qze)return hee;qze=1;let e=Dl();hee={run:t,undo:r};function t(s){s.graph().dummyChains=[],s.edges().forEach(a=>n(s,a))}function n(s,a){let i=a.v,l=s.node(i).rank,c=a.w,u=s.node(c).rank,d=a.name,f=s.edge(a),p=f.labelRank;if(u===l+1)return;s.removeEdge(a);let h,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},h=e.addDummyNode(s,"edge",m,"_d"),l===p&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,h,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(h),i=h;s.setEdge(i,c,{weight:f.weight},d)}function r(s){s.graph().dummyChains.forEach(a=>{let i=s.node(a),l=i.edgeLabel,c;for(s.setEdge(i.edgeObj,l);i.dummy;)c=s.successors(a)[0],s.removeNode(a),l.points.push({x:i.x,y:i.y}),i.dummy==="edge-label"&&(l.x=i.x,l.y=i.y,l.width=i.width,l.height=i.height),a=c,i=s.node(a)})}return hee}var mee,Hze;function uB(){if(Hze)return mee;Hze=1;const{applyWithChunking:e}=Dl();mee={longestPath:t,slack:n};function t(r){var s={};function a(i){var l=r.node(i);if(Object.hasOwn(s,i))return l.rank;s[i]=!0;let c=r.outEdges(i).map(d=>d==null?Number.POSITIVE_INFINITY:a(d.w)-r.edge(d).minlen);var u=e(Math.min,c);return u===Number.POSITIVE_INFINITY&&(u=0),l.rank=u}r.sources().forEach(a)}function n(r,s){return r.node(s.w).rank-r.node(s.v).rank-r.edge(s).minlen}return mee}var gee,Wze;function p1t(){if(Wze)return gee;Wze=1;var e=Mg().Graph,t=uB().slack;gee=n;function n(i){var l=new e({directed:!1}),c=i.nodes()[0],u=i.nodeCount();l.setNode(c,{});for(var d,f;r(l,i)<u;)d=s(l,i),f=l.hasNode(d.v)?t(i,d):-t(i,d),a(l,i,f);return l}function r(i,l){function c(u){l.nodeEdges(u).forEach(d=>{var f=d.v,p=u===f?d.w:f;!i.hasNode(p)&&!t(l,d)&&(i.setNode(p,{}),i.setEdge(u,p,{}),c(p))})}return i.nodes().forEach(c),i.nodeCount()}function s(i,l){return l.edges().reduce((u,d)=>{let f=Number.POSITIVE_INFINITY;return i.hasNode(d.v)!==i.hasNode(d.w)&&(f=t(l,d)),f<u[0]?[f,d]:u},[Number.POSITIVE_INFINITY,null])[1]}function a(i,l,c){i.nodes().forEach(u=>l.node(u).rank+=c)}return gee}var vee,Zze;function uqn(){if(Zze)return vee;Zze=1;var e=p1t(),t=uB().slack,n=uB().longestPath,r=Mg().alg.preorder,s=Mg().alg.postorder,a=Dl().simplify;vee=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(S){S=a(S),n(S);var x=e(S);d(x),l(x,S);for(var k,_;k=p(x);)_=h(x,S,k),m(x,S,k,_)}function l(S,x){var k=s(S,S.nodes());k=k.slice(0,k.length-1),k.forEach(_=>c(S,x,_))}function c(S,x,k){var _=S.node(k),C=_.parent;S.edge(k,C).cutvalue=u(S,x,k)}function u(S,x,k){var _=S.node(k),C=_.parent,E=!0,j=x.edge(k,C),T=0;return j||(E=!1,j=x.edge(C,k)),T=j.weight,x.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==C){var L=A===E,M=x.edge(I).weight;if(T+=L?M:-M,y(S,k,R)){var z=S.edge(k,R).cutvalue;T+=L?-z:z}}}),T}function d(S,x){arguments.length<2&&(x=S.nodes()[0]),f(S,{},1,x)}function f(S,x,k,_,C){var E=k,j=S.node(_);return x[_]=!0,S.neighbors(_).forEach(T=>{Object.hasOwn(x,T)||(k=f(S,x,k,T,_))}),j.low=E,j.lim=k++,C?j.parent=C:delete j.parent,k}function p(S){return S.edges().find(x=>S.edge(x).cutvalue<0)}function h(S,x,k){var _=k.v,C=k.w;x.hasEdge(_,C)||(_=k.w,C=k.v);var E=S.node(_),j=S.node(C),T=E,I=!1;E.lim>j.lim&&(T=j,I=!0);var A=x.edges().filter(R=>I===b(S,S.node(R.v),T)&&I!==b(S,S.node(R.w),T));return A.reduce((R,L)=>t(x,L)<t(x,R)?L:R)}function m(S,x,k,_){var C=k.v,E=k.w;S.removeEdge(C,E),S.setEdge(_.v,_.w,{}),d(S),l(S,x),v(S,x)}function v(S,x){var k=S.nodes().find(C=>!x.node(C).parent),_=r(S,k);_=_.slice(1),_.forEach(C=>{var E=S.node(C).parent,j=x.edge(C,E),T=!1;j||(j=x.edge(E,C),T=!0),x.node(C).rank=x.node(E).rank+(T?j.minlen:-j.minlen)})}function y(S,x,k){return S.hasEdge(x,k)}function b(S,x,k){return k.low<=x.lim&&x.lim<=k.lim}return vee}var yee,Gze;function dqn(){if(Gze)return yee;Gze=1;var e=uB(),t=e.longestPath,n=p1t(),r=uqn();yee=s;function s(c){var u=c.graph().ranker;if(u instanceof Function)return u(c);switch(c.graph().ranker){case"network-simplex":l(c);break;case"tight-tree":i(c);break;case"longest-path":a(c);break;case"none":break;default:l(c)}}var a=t;function i(c){t(c),n(c)}function l(c){r(c)}return yee}var bee,Qze;function fqn(){if(Qze)return bee;Qze=1,bee=e;function e(r){let s=n(r);r.graph().dummyChains.forEach(a=>{let i=r.node(a),l=i.edgeObj,c=t(r,s,l.v,l.w),u=c.path,d=c.lca,f=0,p=u[f],h=!0;for(;a!==l.w;){if(i=r.node(a),h){for(;(p=u[f])!==d&&r.node(p).maxRank<i.rank;)f++;p===d&&(h=!1)}if(!h){for(;f<u.length-1&&r.node(p=u[f+1]).minRank<=i.rank;)f++;p=u[f]}r.setParent(a,p),a=r.successors(a)[0]}})}function t(r,s,a,i){let l=[],c=[],u=Math.min(s[a].low,s[i].low),d=Math.max(s[a].lim,s[i].lim),f,p;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(p=f,f=i;(f=r.parent(f))!==p;)c.push(f);return{path:l.concat(c.reverse()),lca:p}}function n(r){let s={},a=0;function i(l){let c=a;r.children(l).forEach(i),s[l]={low:c,lim:a++}}return r.children().forEach(i),s}return bee}var xee,Yze;function pqn(){if(Yze)return xee;Yze=1;let e=Dl();xee={run:t,cleanup:a};function t(i){let l=e.addDummyNode(i,"root",{},"_root"),c=r(i),u=Object.values(c),d=e.applyWithChunking(Math.max,u)-1,f=2*d+1;i.graph().nestingRoot=l,i.edges().forEach(h=>i.edge(h).minlen*=f);let p=s(i)+1;i.children().forEach(h=>n(i,l,f,p,d,c,h)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,p){let h=i.children(p);if(!h.length){p!==l&&i.setEdge(l,p,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(v,p),y.borderBottom=v,h.forEach(b=>{n(i,l,c,u,d,f,b);let S=i.node(b),x=S.borderTop?S.borderTop:b,k=S.borderBottom?S.borderBottom:b,_=S.borderTop?u:2*u,C=x!==k?1:d-f[p]+1;i.setEdge(m,x,{weight:_,minlen:C,nestingEdge:!0}),i.setEdge(k,v,{weight:_,minlen:C,nestingEdge:!0})}),i.parent(p)||i.setEdge(l,m,{weight:0,minlen:d+f[p]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(p=>c(p,d+1)),l[u]=d}return i.children().forEach(u=>c(u,1)),l}function s(i){return i.edges().reduce((l,c)=>l+i.edge(c).weight,0)}function a(i){var l=i.graph();i.removeNode(l.nestingRoot),delete l.nestingRoot,i.edges().forEach(c=>{var u=i.edge(c);u.nestingEdge&&i.removeEdge(c)})}return xee}var wee,Kze;function hqn(){if(Kze)return wee;Kze=1;let e=Dl();wee=t;function t(r){function s(a){let i=r.children(a),l=r.node(a);if(i.length&&i.forEach(s),Object.hasOwn(l,"minRank")){l.borderLeft=[],l.borderRight=[];for(let c=l.minRank,u=l.maxRank+1;c<u;++c)n(r,"borderLeft","_bl",a,l,c),n(r,"borderRight","_br",a,l,c)}}r.children().forEach(s)}function n(r,s,a,i,l,c){let u={width:0,height:0,rank:c,borderType:s},d=l[s][c-1],f=e.addDummyNode(r,"border",u,a);l[s][c]=f,r.setParent(f,i),d&&r.setEdge(d,f,{weight:1})}return wee}var See,Xze;function mqn(){if(Xze)return See;Xze=1,See={adjust:e,undo:t};function e(c){let u=c.graph().rankdir.toLowerCase();(u==="lr"||u==="rl")&&n(c)}function t(c){let u=c.graph().rankdir.toLowerCase();(u==="bt"||u==="rl")&&s(c),(u==="lr"||u==="rl")&&(i(c),n(c))}function n(c){c.nodes().forEach(u=>r(c.node(u))),c.edges().forEach(u=>r(c.edge(u)))}function r(c){let u=c.width;c.width=c.height,c.height=u}function s(c){c.nodes().forEach(u=>a(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(a),Object.hasOwn(d,"y")&&a(d)})}function a(c){c.y=-c.y}function i(c){c.nodes().forEach(u=>l(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(l),Object.hasOwn(d,"x")&&l(d)})}function l(c){let u=c.x;c.x=c.y,c.y=u}return See}var kee,Jze;function gqn(){if(Jze)return kee;Jze=1;let e=Dl();kee=t;function t(n){let r={},s=n.nodes().filter(d=>!n.children(d).length),a=s.map(d=>n.node(d).rank),i=e.applyWithChunking(Math.max,a),l=e.range(i+1).map(()=>[]);function c(d){if(r[d])return;r[d]=!0;let f=n.node(d);l[f.rank].push(d),n.successors(d).forEach(c)}return s.sort((d,f)=>n.node(d).rank-n.node(f).rank).forEach(c),l}return kee}var Oee,e8e;function vqn(){if(e8e)return Oee;e8e=1;let e=Dl().zipObject;Oee=t;function t(r,s){let a=0;for(let i=1;i<s.length;++i)a+=n(r,s[i-1],s[i]);return a}function n(r,s,a){let i=e(a,a.map((p,h)=>h)),l=s.flatMap(p=>r.outEdges(p).map(h=>({pos:i[h.w],weight:r.edge(h).weight})).sort((h,m)=>h.pos-m.pos)),c=1;for(;c<a.length;)c<<=1;let u=2*c-1;c-=1;let d=new Array(u).fill(0),f=0;return l.forEach(p=>{let h=p.pos+c;d[h]+=p.weight;let m=0;for(;h>0;)h%2&&(m+=d[h+1]),h=h-1>>1,d[h]+=p.weight;f+=p.weight*m}),f}return Oee}var _ee,t8e;function yqn(){if(t8e)return _ee;t8e=1,_ee=e;function e(t,n=[]){return n.map(r=>{let s=t.inEdges(r);if(s.length){let a=s.reduce((i,l)=>{let c=t.edge(l),u=t.node(l.v);return{sum:i.sum+c.weight*u.order,weight:i.weight+c.weight}},{sum:0,weight:0});return{v:r,barycenter:a.sum/a.weight,weight:a.weight}}else return{v:r}})}return _ee}var Cee,n8e;function bqn(){if(n8e)return Cee;n8e=1;let e=Dl();Cee=t;function t(s,a){let i={};s.forEach((c,u)=>{let d=i[c.v]={indegree:0,in:[],out:[],vs:[c.v],i:u};c.barycenter!==void 0&&(d.barycenter=c.barycenter,d.weight=c.weight)}),a.edges().forEach(c=>{let u=i[c.v],d=i[c.w];u!==void 0&&d!==void 0&&(d.indegree++,u.out.push(i[c.w]))});let l=Object.values(i).filter(c=>!c.indegree);return n(l)}function n(s){let a=[];function i(c){return u=>{u.merged||(u.barycenter===void 0||c.barycenter===void 0||u.barycenter>=c.barycenter)&&r(c,u)}}function l(c){return u=>{u.in.push(c),--u.indegree===0&&s.push(u)}}for(;s.length;){let c=s.pop();a.push(c),c.in.reverse().forEach(i(c)),c.out.forEach(l(c))}return a.filter(c=>!c.merged).map(c=>e.pick(c,["vs","i","barycenter","weight"]))}function r(s,a){let i=0,l=0;s.weight&&(i+=s.barycenter*s.weight,l+=s.weight),a.weight&&(i+=a.barycenter*a.weight,l+=a.weight),s.vs=a.vs.concat(s.vs),s.barycenter=i/l,s.weight=l,s.i=Math.min(a.i,s.i),a.merged=!0}return Cee}var Eee,r8e;function xqn(){if(r8e)return Eee;r8e=1;let e=Dl();Eee=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,p=0;l.sort(r(!!a)),p=n(u,c,p),l.forEach(m=>{p+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,p=n(u,c,p)});let h={vs:u.flat(!0)};return f&&(h.barycenter=d/f,h.weight=f),h}function n(s,a,i){let l;for(;a.length&&(l=a[a.length-1]).i<=i;)a.pop(),s.push(l.vs),i++;return i}function r(s){return(a,i)=>a.barycenter<i.barycenter?-1:a.barycenter>i.barycenter?1:s?i.i-a.i:a.i-i.i}return Eee}var jee,s8e;function wqn(){if(s8e)return jee;s8e=1;let e=yqn(),t=bqn(),n=xqn();jee=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),p=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,m={};p&&(d=d.filter(S=>S!==p&&S!==h));let v=e(i,d);v.forEach(S=>{if(i.children(S.v).length){let x=r(i,S.v,c,u);m[S.v]=x,Object.hasOwn(x,"barycenter")&&a(S,x)}});let y=t(v,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let S=i.node(i.predecessors(p)[0]),x=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+S.order+x.order)/(b.weight+2),b.weight+=2}return b}function s(i,l){i.forEach(c=>{c.vs=c.vs.flatMap(u=>l[u]?l[u].vs:u)})}function a(i,l){i.barycenter!==void 0?(i.barycenter=(i.barycenter*i.weight+l.barycenter*l.weight)/(i.weight+l.weight),i.weight+=l.weight):(i.barycenter=l.barycenter,i.weight=l.weight)}return jee}var Tee,a8e;function Sqn(){if(a8e)return Tee;a8e=1;let e=Mg().Graph,t=Dl();Tee=n;function n(s,a,i,l){l||(l=s.nodes());let c=r(s),u=new e({compound:!0}).setGraph({root:c}).setDefaultNodeLabel(d=>s.node(d));return l.forEach(d=>{let f=s.node(d),p=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,p||c),s[i](d).forEach(h=>{let m=h.v===d?h.w:h.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(h).weight+y})}),Object.hasOwn(f,"minRank")&&u.setNode(d,{borderLeft:f.borderLeft[a],borderRight:f.borderRight[a]}))}),u}function r(s){for(var a;s.hasNode(a=t.uniqueId("_root")););return a}return Tee}var Nee,i8e;function kqn(){if(i8e)return Nee;i8e=1,Nee=e;function e(t,n,r){let s={},a;r.forEach(i=>{let l=t.parent(i),c,u;for(;l;){if(c=t.parent(l),c?(u=s[c],s[c]=l):(u=a,a=l),u&&u!==l){n.setEdge(u,l);return}l=c}})}return Nee}var Iee,o8e;function Oqn(){if(o8e)return Iee;o8e=1;let e=gqn(),t=vqn(),n=wqn(),r=Sqn(),s=kqn(),a=Mg().Graph,i=Dl();Iee=l;function l(f,p){if(p&&typeof p.customOrder=="function"){p.customOrder(f,l);return}let h=i.maxRank(f),m=c(f,i.range(1,h+1),"inEdges"),v=c(f,i.range(h-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),p&&p.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,S;for(let x=0,k=0;k<4;++x,++k){u(x%2?m:v,x%4>=2),y=i.buildLayerMatrix(f);let _=t(f,y);_<b&&(k=0,S=Object.assign({},y),b=_)}d(f,S)}function c(f,p,h){const m=new Map,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let S=b.minRank;S<=b.maxRank;S++)S!==b.rank&&v(S,y)}return p.map(function(y){return r(f,y,h,m.get(y)||[])})}function u(f,p){let h=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,h,p);y.vs.forEach((b,S)=>m.node(b).order=S),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,v)=>f.node(m).order=v))}return Iee}var Aee,l8e;function _qn(){if(l8e)return Aee;l8e=1;let e=Mg().Graph,t=Dl();Aee={positionX:h,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:p};function n(y,b){let S={};function x(k,_){let C=0,E=0,j=k.length,T=_[_.length-1];return _.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:j;(R||I===T)&&(_.slice(E,A+1).forEach(M=>{y.predecessors(M).forEach(z=>{let H=y.node(z),F=H.order;(F<C||L<F)&&!(H.dummy&&y.node(M).dummy)&&a(S,z,M)})}),E=A+1,C=L)}),_}return b.length&&b.reduce(x),S}function r(y,b){let S={};function x(_,C,E,j,T){let I;t.range(C,E).forEach(A=>{I=_[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<j||L.order>T)&&a(S,R,I)})})}function k(_,C){let E=-1,j,T=0;return C.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(j=y.node(R[0]).order,x(C,T,A,E,j),T=A,E=j)}x(C,T,C.length,j,_.length)}),C}return b.length&&b.reduce(k),S}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(S=>y.node(S).dummy)}function a(y,b,S){if(b>S){let k=b;b=S,S=k}let x=y[b];x||(y[b]=x={}),x[S]=!0}function i(y,b,S){if(b>S){let x=b;b=S,S=x}return!!y[b]&&Object.hasOwn(y[b],S)}function l(y,b,S,x){let k={},_={},C={};return b.forEach(E=>{E.forEach((j,T)=>{k[j]=j,_[j]=j,C[j]=T})}),b.forEach(E=>{let j=-1;E.forEach(T=>{let I=x(T);if(I.length){I=I.sort((R,L)=>C[R]-C[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let M=I[R];_[T]===T&&j<C[M]&&!i(S,T,M)&&(_[M]=T,_[T]=k[T]=k[M],j=C[M])}}})}),{root:k,align:_}}function c(y,b,S,x,k){let _={},C=u(y,b,S,k),E=k?"borderLeft":"borderRight";function j(A,R){let L=C.nodes(),M=L.pop(),z={};for(;M;)z[M]?A(M):(z[M]=!0,L.push(M),L=L.concat(R(M))),M=L.pop()}function T(A){_[A]=C.inEdges(A).reduce((R,L)=>Math.max(R,_[L.v]+C.edge(L)),0)}function I(A){let R=C.outEdges(A).reduce((M,z)=>Math.min(M,_[z.w]-C.edge(z)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==E&&(_[A]=Math.max(_[A],R))}return j(T,C.predecessors.bind(C)),j(I,C.successors.bind(C)),Object.keys(x).forEach(A=>_[A]=_[S[A]]),_}function u(y,b,S,x){let k=new e,_=y.graph(),C=m(_.nodesep,_.edgesep,x);return b.forEach(E=>{let j;E.forEach(T=>{let I=S[T];if(k.setNode(I),j){var A=S[j],R=k.edge(A,I);k.setEdge(A,I,Math.max(C(y,T,j),R||0))}j=T})}),k}function d(y,b){return Object.values(b).reduce((S,x)=>{let k=Number.NEGATIVE_INFINITY,_=Number.POSITIVE_INFINITY;Object.entries(x).forEach(([E,j])=>{let T=v(y,E)/2;k=Math.max(j+T,k),_=Math.min(j-T,_)});const C=k-_;return C<S[0]&&(S=[C,x]),S},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let S=Object.values(b),x=t.applyWithChunking(Math.min,S),k=t.applyWithChunking(Math.max,S);["u","d"].forEach(_=>{["l","r"].forEach(C=>{let E=_+C,j=y[E];if(j===b)return;let T=Object.values(j),I=x-t.applyWithChunking(Math.min,T);C!=="l"&&(I=k-t.applyWithChunking(Math.max,T)),I&&(y[E]=t.mapValues(j,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(S,x)=>{if(b)return y[b.toLowerCase()][x];{let k=Object.values(y).map(_=>_[x]).sort((_,C)=>_-C);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),S=Object.assign(n(y,b),r(y,b)),x={},k;["u","d"].forEach(C=>{k=C==="u"?b:Object.values(b).reverse(),["l","r"].forEach(E=>{E==="r"&&(k=k.map(A=>Object.values(A).reverse()));let j=(C==="u"?y.predecessors:y.successors).bind(y),T=l(y,k,S,j),I=c(y,k,T.root,T.align,E==="r");E==="r"&&(I=t.mapValues(I,A=>-A)),x[C+E]=I})});let _=d(y,x);return f(x,_),p(x,y.graph().align)}function m(y,b,S){return(x,k,_)=>{let C=x.node(k),E=x.node(_),j=0,T;if(j+=C.width/2,Object.hasOwn(C,"labelpos"))switch(C.labelpos.toLowerCase()){case"l":T=-C.width/2;break;case"r":T=C.width/2;break}if(T&&(j+=S?T:-T),T=0,j+=(C.dummy?b:y)/2,j+=(E.dummy?b:y)/2,j+=E.width/2,Object.hasOwn(E,"labelpos"))switch(E.labelpos.toLowerCase()){case"l":T=E.width/2;break;case"r":T=-E.width/2;break}return T&&(j+=S?T:-T),T=0,j}}function v(y,b){return y.node(b).width}return Aee}var Ree,c8e;function Cqn(){if(c8e)return Ree;c8e=1;let e=Dl(),t=_qn().positionX;Ree=n;function n(s){s=e.asNonCompoundGraph(s),r(s),Object.entries(t(s)).forEach(([a,i])=>s.node(a).x=i)}function r(s){let a=e.buildLayerMatrix(s),i=s.graph().ranksep,l=0;a.forEach(c=>{const u=c.reduce((d,f)=>{const p=s.node(f).height;return d>p?d:p},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return Ree}var Pee,u8e;function Eqn(){if(u8e)return Pee;u8e=1;let e=lqn(),t=cqn(),n=dqn(),r=Dl().normalizeRanks,s=fqn(),a=Dl().removeEmptyRanks,i=pqn(),l=hqn(),c=mqn(),u=Oqn(),d=Cqn(),f=Dl(),p=Mg().Graph;Pee=h;function h($,U){let Z=U&&U.debugTiming?f.time:f.notime;Z("layout",()=>{let K=Z(" buildLayoutGraph",()=>j($));Z(" runLayout",()=>m(K,Z,U)),Z(" updateInputGraph",()=>v($,K))})}function m($,U,Z){U(" makeSpaceForEdgeLabels",()=>T($)),U(" removeSelfEdges",()=>B($)),U(" acyclic",()=>e.run($)),U(" nestingGraph.run",()=>i.run($)),U(" rank",()=>n(f.asNonCompoundGraph($))),U(" injectEdgeLabelProxies",()=>I($)),U(" removeEmptyRanks",()=>a($)),U(" nestingGraph.cleanup",()=>i.cleanup($)),U(" normalizeRanks",()=>r($)),U(" assignRankMinMax",()=>A($)),U(" removeEdgeLabelProxies",()=>R($)),U(" normalize.run",()=>t.run($)),U(" parentDummyChains",()=>s($)),U(" addBorderSegments",()=>l($)),U(" order",()=>u($,Z)),U(" insertSelfEdges",()=>q($)),U(" adjustCoordinateSystem",()=>c.adjust($)),U(" position",()=>d($)),U(" positionSelfEdges",()=>D($)),U(" removeBorderNodes",()=>F($)),U(" normalize.undo",()=>t.undo($)),U(" fixupEdgeLabelCoords",()=>z($)),U(" undoCoordinateSystem",()=>c.undo($)),U(" translateGraph",()=>L($)),U(" assignNodeIntersects",()=>M($)),U(" reversePoints",()=>H($)),U(" acyclic.undo",()=>e.undo($))}function v($,U){$.nodes().forEach(Z=>{let K=$.node(Z),ne=U.node(Z);K&&(K.x=ne.x,K.y=ne.y,K.rank=ne.rank,U.children(Z).length&&(K.width=ne.width,K.height=ne.height))}),$.edges().forEach(Z=>{let K=$.edge(Z),ne=U.edge(Z);K.points=ne.points,Object.hasOwn(ne,"x")&&(K.x=ne.x,K.y=ne.y)}),$.graph().width=U.graph().width,$.graph().height=U.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},S=["acyclicer","ranker","rankdir","align"],x=["width","height","rank"],k={width:0,height:0},_=["minlen","weight","width","height","labeloffset"],C={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},E=["labelpos"];function j($){let U=new p({multigraph:!0,compound:!0}),Z=V($.graph());return U.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,S))),$.nodes().forEach(K=>{let ne=V($.node(K));const te=G(ne,x);Object.keys(k).forEach(J=>{te[J]===void 0&&(te[J]=k[J])}),U.setNode(K,te),U.setParent(K,$.parent(K))}),$.edges().forEach(K=>{let ne=V($.edge(K));U.setEdge(K,Object.assign({},C,G(ne,_),f.pick(ne,E)))}),U}function T($){let U=$.graph();U.ranksep/=2,$.edges().forEach(Z=>{let K=$.edge(Z);K.minlen*=2,K.labelpos.toLowerCase()!=="c"&&(U.rankdir==="TB"||U.rankdir==="BT"?K.width+=K.labeloffset:K.height+=K.labeloffset)})}function I($){$.edges().forEach(U=>{let Z=$.edge(U);if(Z.width&&Z.height){let K=$.node(U.v),te={rank:($.node(U.w).rank-K.rank)/2+K.rank,e:U};f.addDummyNode($,"edge-proxy",te,"_ep")}})}function A($){let U=0;$.nodes().forEach(Z=>{let K=$.node(Z);K.borderTop&&(K.minRank=$.node(K.borderTop).rank,K.maxRank=$.node(K.borderBottom).rank,U=Math.max(U,K.maxRank))}),$.graph().maxRank=U}function R($){$.nodes().forEach(U=>{let Z=$.node(U);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(U))})}function L($){let U=Number.POSITIVE_INFINITY,Z=0,K=Number.POSITIVE_INFINITY,ne=0,te=$.graph(),J=te.marginx||0,ae=te.marginy||0;function pe(Y){let ee=Y.x,ce=Y.y,de=Y.width,oe=Y.height;U=Math.min(U,ee-de/2),Z=Math.max(Z,ee+de/2),K=Math.min(K,ce-oe/2),ne=Math.max(ne,ce+oe/2)}$.nodes().forEach(Y=>pe($.node(Y))),$.edges().forEach(Y=>{let ee=$.edge(Y);Object.hasOwn(ee,"x")&&pe(ee)}),U-=J,K-=ae,$.nodes().forEach(Y=>{let ee=$.node(Y);ee.x-=U,ee.y-=K}),$.edges().forEach(Y=>{let ee=$.edge(Y);ee.points.forEach(ce=>{ce.x-=U,ce.y-=K}),Object.hasOwn(ee,"x")&&(ee.x-=U),Object.hasOwn(ee,"y")&&(ee.y-=K)}),te.width=Z-U+J,te.height=ne-K+ae}function M($){$.edges().forEach(U=>{let Z=$.edge(U),K=$.node(U.v),ne=$.node(U.w),te,J;Z.points?(te=Z.points[0],J=Z.points[Z.points.length-1]):(Z.points=[],te=ne,J=K),Z.points.unshift(f.intersectRect(K,te)),Z.points.push(f.intersectRect(ne,J))})}function z($){$.edges().forEach(U=>{let Z=$.edge(U);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H($){$.edges().forEach(U=>{let Z=$.edge(U);Z.reversed&&Z.points.reverse()})}function F($){$.nodes().forEach(U=>{if($.children(U).length){let Z=$.node(U),K=$.node(Z.borderTop),ne=$.node(Z.borderBottom),te=$.node(Z.borderLeft[Z.borderLeft.length-1]),J=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(J.x-te.x),Z.height=Math.abs(ne.y-K.y),Z.x=te.x+Z.width/2,Z.y=K.y+Z.height/2}}),$.nodes().forEach(U=>{$.node(U).dummy==="border"&&$.removeNode(U)})}function B($){$.edges().forEach(U=>{if(U.v===U.w){var Z=$.node(U.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:U,label:$.edge(U)}),$.removeEdge(U)}})}function q($){var U=f.buildLayerMatrix($);U.forEach(Z=>{var K=0;Z.forEach((ne,te)=>{var J=$.node(ne);J.order=te+K,(J.selfEdges||[]).forEach(ae=>{f.addDummyNode($,"selfedge",{width:ae.label.width,height:ae.label.height,rank:J.rank,order:te+ ++K,e:ae.e,label:ae.label},"_se")}),delete J.selfEdges})})}function D($){$.nodes().forEach(U=>{var Z=$.node(U);if(Z.dummy==="selfedge"){var K=$.node(Z.e.v),ne=K.x+K.width/2,te=K.y,J=Z.x-ne,ae=K.height/2;$.setEdge(Z.e,Z.label),$.removeNode(U),Z.label.points=[{x:ne+2*J/3,y:te-ae},{x:ne+5*J/6,y:te-ae},{x:ne+J,y:te},{x:ne+5*J/6,y:te+ae},{x:ne+2*J/3,y:te+ae}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,U){return f.mapValues(f.pick($,U),Number)}function V($){var U={};return $&&Object.entries($).forEach(([Z,K])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),U[Z]=K}),U}return Pee}var $ee,d8e;function jqn(){if(d8e)return $ee;d8e=1;let e=Dl(),t=Mg().Graph;$ee={debugOrdering:n};function n(r){let s=e.buildLayerMatrix(r),a=new t({compound:!0,multigraph:!0}).setGraph({});return r.nodes().forEach(i=>{a.setNode(i,{label:i}),a.setParent(i,"layer"+r.node(i).rank)}),r.edges().forEach(i=>a.setEdge(i.v,i.w,{},i.name)),s.forEach((i,l)=>{let c="layer"+l;a.setNode(c,{rank:"same"}),i.reduce((u,d)=>(a.setEdge(u,d,{style:"invis"}),d))}),a}return $ee}var Mee,f8e;function Tqn(){return f8e||(f8e=1,Mee="1.1.8"),Mee}var Dee,p8e;function Nqn(){return p8e||(p8e=1,Dee={graphlib:Mg(),layout:Eqn(),debug:jqn(),util:{time:Dl().time,notime:Dl().notime},version:Tqn()}),Dee}var Iqn=Nqn();const h8e=zl(Iqn);function Vl(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=Vl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var Aqn={value:()=>{}};function gH(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new E8(n)}function E8(e){this._=e}function Rqn(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",s=n.indexOf(".");if(s>=0&&(r=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}E8.prototype=gH.prototype={constructor:E8,on:function(e,t){var n=this._,r=Rqn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=Pqn(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=r[a]).type)n[s]=m8e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=m8e(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new E8(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++r)a[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function Pqn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function m8e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=Aqn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Rme="http://www.w3.org/1999/xhtml";const g8e={svg:"http://www.w3.org/2000/svg",xhtml:Rme,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function vH(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),g8e.hasOwnProperty(t)?{space:g8e[t],local:e}:e}function $qn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Rme&&t.documentElement.namespaceURI===Rme?t.createElement(e):t.createElementNS(n,e)}}function Mqn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function h1t(e){var t=vH(e);return(t.local?Mqn:$qn)(t)}function Dqn(){}function jSe(e){return e==null?Dqn:function(){return this.querySelector(e)}}function Lqn(e){typeof e!="function"&&(e=jSe(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=a[d])&&(u=e.call(c,c.__data__,d,a))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new Hp(r,this._parents)}function Fqn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function zqn(){return[]}function m1t(e){return e==null?zqn:function(){return this.querySelectorAll(e)}}function Bqn(e){return function(){return Fqn(e.apply(this,arguments))}}function Uqn(e){typeof e=="function"?e=Bqn(e):e=m1t(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new Hp(r,s)}function g1t(e){return function(){return this.matches(e)}}function v1t(e){return function(t){return t.matches(e)}}var Vqn=Array.prototype.find;function qqn(e){return function(){return Vqn.call(this.children,e)}}function Hqn(){return this.firstElementChild}function Wqn(e){return this.select(e==null?Hqn:qqn(typeof e=="function"?e:v1t(e)))}var Zqn=Array.prototype.filter;function Gqn(){return Array.from(this.children)}function Qqn(e){return function(){return Zqn.call(this.children,e)}}function Yqn(e){return this.selectAll(e==null?Gqn:Qqn(typeof e=="function"?e:v1t(e)))}function Kqn(e){typeof e!="function"&&(e=g1t(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Hp(r,this._parents)}function y1t(e){return new Array(e.length)}function Xqn(){return new Hp(this._enter||this._groups.map(y1t),this._parents)}function dB(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}dB.prototype={constructor:dB,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function Jqn(e){return function(){return e}}function eHn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new dB(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function tHn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,p=new Array(d),h;for(l=0;l<d;++l)(c=t[l])&&(p[l]=h=i.call(c,c.__data__,l,t)+"",u.has(h)?s[l]=c:u.set(h,c));for(l=0;l<f;++l)h=i.call(e,a[l],l,a)+"",(c=u.get(h))?(r[l]=c,c.__data__=a[l],u.delete(h)):n[l]=new dB(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function nHn(e){return e.__data__}function rHn(e,t){if(!arguments.length)return Array.from(this,nHn);var n=t?tHn:eHn,r=this._parents,s=this._groups;typeof e!="function"&&(e=Jqn(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),u=0;u<a;++u){var d=r[u],f=s[u],p=f.length,h=sHn(e.call(d,d&&d.__data__,u,r)),m=h.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,v,y,b,h,t);for(var S=0,x=0,k,_;S<m;++S)if(k=v[S]){for(S>=x&&(x=S+1);!(_=y[x])&&++x<m;);k._next=_||null}}return i=new Hp(i,r),i._enter=l,i._exit=c,i}function sHn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function aHn(){return new Hp(this._exit||this._groups.map(y1t),this._parents)}function iHn(e,t,n){var r=this.enter(),s=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),r&&s?r.merge(s).order():s}function oHn(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,a=r.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var u=n[c],d=r[c],f=u.length,p=l[c]=new Array(f),h,m=0;m<f;++m)(h=u[m]||d[m])&&(p[m]=h);for(;c<s;++c)l[c]=n[c];return new Hp(l,this._parents)}function lHn(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,a=r[s],i;--s>=0;)(i=r[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function cHn(e){e||(e=uHn);function t(f,p){return f&&p?e(f.__data__,p.__data__):!f-!p}for(var n=this._groups,r=n.length,s=new Array(r),a=0;a<r;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new Hp(s,this._parents).order()}function uHn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function dHn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function fHn(){return Array.from(this)}function pHn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length;s<a;++s){var i=r[s];if(i)return i}return null}function hHn(){let e=0;for(const t of this)++e;return e}function mHn(){return!this.node()}function gHn(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function vHn(e){return function(){this.removeAttribute(e)}}function yHn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function bHn(e,t){return function(){this.setAttribute(e,t)}}function xHn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function wHn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function SHn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function kHn(e,t){var n=vH(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?yHn:vHn:typeof t=="function"?n.local?SHn:wHn:n.local?xHn:bHn)(n,t))}function b1t(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function OHn(e){return function(){this.style.removeProperty(e)}}function _Hn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function CHn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function EHn(e,t,n){return arguments.length>1?this.each((t==null?OHn:typeof t=="function"?CHn:_Hn)(e,t,n??"")):zT(this.node(),e)}function zT(e,t){return e.style.getPropertyValue(t)||b1t(e).getComputedStyle(e,null).getPropertyValue(t)}function jHn(e){return function(){delete this[e]}}function THn(e,t){return function(){this[e]=t}}function NHn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function IHn(e,t){return arguments.length>1?this.each((t==null?jHn:typeof t=="function"?NHn:THn)(e,t)):this.node()[e]}function x1t(e){return e.trim().split(/^|\s+/)}function TSe(e){return e.classList||new w1t(e)}function w1t(e){this._node=e,this._names=x1t(e.getAttribute("class")||"")}w1t.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function S1t(e,t){for(var n=TSe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function k1t(e,t){for(var n=TSe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function AHn(e){return function(){S1t(this,e)}}function RHn(e){return function(){k1t(this,e)}}function PHn(e,t){return function(){(t.apply(this,arguments)?S1t:k1t)(this,e)}}function $Hn(e,t){var n=x1t(e+"");if(arguments.length<2){for(var r=TSe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?PHn:t?AHn:RHn)(n,t))}function MHn(){this.textContent=""}function DHn(e){return function(){this.textContent=e}}function LHn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function FHn(e){return arguments.length?this.each(e==null?MHn:(typeof e=="function"?LHn:DHn)(e)):this.node().textContent}function zHn(){this.innerHTML=""}function BHn(e){return function(){this.innerHTML=e}}function UHn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function VHn(e){return arguments.length?this.each(e==null?zHn:(typeof e=="function"?UHn:BHn)(e)):this.node().innerHTML}function qHn(){this.nextSibling&&this.parentNode.appendChild(this)}function HHn(){return this.each(qHn)}function WHn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function ZHn(){return this.each(WHn)}function GHn(e){var t=typeof e=="function"?e:h1t(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function QHn(){return null}function YHn(e,t){var n=typeof e=="function"?e:h1t(e),r=t==null?QHn:typeof t=="function"?t:jSe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function KHn(){var e=this.parentNode;e&&e.removeChild(this)}function XHn(){return this.each(KHn)}function JHn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function eWn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function tWn(e){return this.select(e?eWn:JHn)}function nWn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function rWn(e){return function(t){e.call(this,t,this.__data__)}}function sWn(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function aWn(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,a;n<s;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++r]=a;++r?t.length=r:delete this.__on}}}function iWn(e,t,n){return function(){var r=this.__on,s,a=rWn(t);if(r){for(var i=0,l=r.length;i<l;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(s):this.__on=[s]}}function oWn(e,t,n){var r=sWn(e+""),s,a=r.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,u=l.length,d;c<u;++c)for(s=0,d=l[c];s<a;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?iWn:aWn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function O1t(e,t,n){var r=b1t(e),s=r.CustomEvent;typeof s=="function"?s=new s(t,n):(s=r.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function lWn(e,t){return function(){return O1t(this,e,t)}}function cWn(e,t){return function(){return O1t(this,e,t.apply(this,arguments))}}function uWn(e,t){return this.each((typeof t=="function"?cWn:lWn)(e,t))}function*dWn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length,i;s<a;++s)(i=r[s])&&(yield i)}var _1t=[null];function Hp(e,t){this._groups=e,this._parents=t}function $4(){return new Hp([[document.documentElement]],_1t)}function fWn(){return this}Hp.prototype=$4.prototype={constructor:Hp,select:Lqn,selectAll:Uqn,selectChild:Wqn,selectChildren:Yqn,filter:Kqn,data:rHn,enter:Xqn,exit:aHn,join:iHn,merge:oHn,selection:fWn,order:lHn,sort:cHn,call:dHn,nodes:fHn,node:pHn,size:hHn,empty:mHn,each:gHn,attr:kHn,style:EHn,property:IHn,classed:$Hn,text:FHn,html:VHn,raise:HHn,lower:ZHn,append:GHn,insert:YHn,remove:XHn,clone:tWn,datum:nWn,on:oWn,dispatch:uWn,[Symbol.iterator]:dWn};function Sp(e){return typeof e=="string"?new Hp([[document.querySelector(e)]],[document.documentElement]):new Hp([[e]],_1t)}function pWn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function rg(e,t){if(e=pWn(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}const hWn={passive:!1},SM={capture:!0,passive:!1};function Lee(e){e.stopImmediatePropagation()}function Hj(e){e.preventDefault(),e.stopImmediatePropagation()}function C1t(e){var t=e.document.documentElement,n=Sp(e).on("dragstart.drag",Hj,SM);"onselectstart"in t?n.on("selectstart.drag",Hj,SM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function E1t(e,t){var n=e.document.documentElement,r=Sp(e).on("dragstart.drag",null);t&&(r.on("click.drag",Hj,SM),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const Y6=e=>()=>e;function Pme(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:a,x:i,y:l,dx:c,dy:u,dispatch:d}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:d}})}Pme.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function mWn(e){return!e.ctrlKey&&!e.button}function gWn(){return this.parentNode}function vWn(e,t){return t??{x:e.x,y:e.y}}function yWn(){return navigator.maxTouchPoints||"ontouchstart"in this}function j1t(){var e=mWn,t=gWn,n=vWn,r=yWn,s={},a=gH("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,hWn).on("touchend.drag touchcancel.drag",S).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,_){if(!(d||!e.call(this,k,_))){var C=x(this,t.call(this,k,_),k,_,"mouse");C&&(Sp(k.view).on("mousemove.drag",m,SM).on("mouseup.drag",v,SM),C1t(k.view),Lee(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(Hj(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function v(k){Sp(k.view).on("mousemove.drag mouseup.drag",null),E1t(k.view,u),Hj(k),s.mouse("end",k)}function y(k,_){if(e.call(this,k,_)){var C=k.changedTouches,E=t.call(this,k,_),j=C.length,T,I;for(T=0;T<j;++T)(I=x(this,E,k,_,C[T].identifier,C[T]))&&(Lee(k),I("start",k,C[T]))}}function b(k){var _=k.changedTouches,C=_.length,E,j;for(E=0;E<C;++E)(j=s[_[E].identifier])&&(Hj(k),j("drag",k,_[E]))}function S(k){var _=k.changedTouches,C=_.length,E,j;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),E=0;E<C;++E)(j=s[_[E].identifier])&&(Lee(k),j("end",k,_[E]))}function x(k,_,C,E,j,T){var I=a.copy(),A=rg(T||C,_),R,L,M;if((M=n.call(k,new Pme("beforestart",{sourceEvent:C,target:p,identifier:j,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),E))!=null)return R=M.x-A[0]||0,L=M.y-A[1]||0,function z(H,F,B){var q=A,D;switch(H){case"start":s[j]=z,D=i++;break;case"end":delete s[j],--i;case"drag":A=rg(B||F,_),D=i;break}I.call(H,k,new Pme(H,{sourceEvent:F,subject:M,target:p,identifier:j,active:D,x:A[0]+R,y:A[1]+L,dx:A[0]-q[0],dy:A[1]-q[1],dispatch:I}),E)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:Y6(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:Y6(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:Y6(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:Y6(!!k),p):r},p.on=function(){var k=a.on.apply(a,arguments);return k===a?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function NSe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function T1t(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function M4(){}var kM=.7,fB=1/kM,Wj="\\s*([+-]?\\d+)\\s*",OM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ry="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",bWn=/^#([0-9a-f]{3,8})$/,xWn=new RegExp(`^rgb\\(${Wj},${Wj},${Wj}\\)$`),wWn=new RegExp(`^rgb\\(${ry},${ry},${ry}\\)$`),SWn=new RegExp(`^rgba\\(${Wj},${Wj},${Wj},${OM}\\)$`),kWn=new RegExp(`^rgba\\(${ry},${ry},${ry},${OM}\\)$`),OWn=new RegExp(`^hsl\\(${OM},${ry},${ry}\\)$`),_Wn=new RegExp(`^hsla\\(${OM},${ry},${ry},${OM}\\)$`),v8e={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};NSe(M4,WO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:y8e,formatHex:y8e,formatHex8:CWn,formatHsl:EWn,formatRgb:b8e,toString:b8e});function y8e(){return this.rgb().formatHex()}function CWn(){return this.rgb().formatHex8()}function EWn(){return N1t(this).formatHsl()}function b8e(){return this.rgb().formatRgb()}function WO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=bWn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?x8e(t):n===3?new pf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?K6(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?K6(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=xWn.exec(e))?new pf(t[1],t[2],t[3],1):(t=wWn.exec(e))?new pf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=SWn.exec(e))?K6(t[1],t[2],t[3],t[4]):(t=kWn.exec(e))?K6(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=OWn.exec(e))?k8e(t[1],t[2]/100,t[3]/100,1):(t=_Wn.exec(e))?k8e(t[1],t[2]/100,t[3]/100,t[4]):v8e.hasOwnProperty(e)?x8e(v8e[e]):e==="transparent"?new pf(NaN,NaN,NaN,0):null}function x8e(e){return new pf(e>>16&255,e>>8&255,e&255,1)}function K6(e,t,n,r){return r<=0&&(e=t=n=NaN),new pf(e,t,n,r)}function jWn(e){return e instanceof M4||(e=WO(e)),e?(e=e.rgb(),new pf(e.r,e.g,e.b,e.opacity)):new pf}function $me(e,t,n,r){return arguments.length===1?jWn(e):new pf(e,t,n,r??1)}function pf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}NSe(pf,$me,T1t(M4,{brighter(e){return e=e==null?fB:Math.pow(fB,e),new pf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?kM:Math.pow(kM,e),new pf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new pf(nO(this.r),nO(this.g),nO(this.b),pB(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:w8e,formatHex:w8e,formatHex8:TWn,formatRgb:S8e,toString:S8e}));function w8e(){return`#${Dk(this.r)}${Dk(this.g)}${Dk(this.b)}`}function TWn(){return`#${Dk(this.r)}${Dk(this.g)}${Dk(this.b)}${Dk((isNaN(this.opacity)?1:this.opacity)*255)}`}function S8e(){const e=pB(this.opacity);return`${e===1?"rgb(":"rgba("}${nO(this.r)}, ${nO(this.g)}, ${nO(this.b)}${e===1?")":`, ${e})`}`}function pB(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function nO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Dk(e){return e=nO(e),(e<16?"0":"")+e.toString(16)}function k8e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new ug(e,t,n,r)}function N1t(e){if(e instanceof ug)return new ug(e.h,e.s,e.l,e.opacity);if(e instanceof M4||(e=WO(e)),!e)return new ug;if(e instanceof ug)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),a=Math.max(t,n,r),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-r)/l+(n<r)*6:n===a?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new ug(i,l,c,e.opacity)}function NWn(e,t,n,r){return arguments.length===1?N1t(e):new ug(e,t,n,r??1)}function ug(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}NSe(ug,NWn,T1t(M4,{brighter(e){return e=e==null?fB:Math.pow(fB,e),new ug(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?kM:Math.pow(kM,e),new ug(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,s=2*n-r;return new pf(Fee(e>=240?e-240:e+120,s,r),Fee(e,s,r),Fee(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new ug(O8e(this.h),X6(this.s),X6(this.l),pB(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=pB(this.opacity);return`${e===1?"hsl(":"hsla("}${O8e(this.h)}, ${X6(this.s)*100}%, ${X6(this.l)*100}%${e===1?")":`, ${e})`}`}}));function O8e(e){return e=(e||0)%360,e<0?e+360:e}function X6(e){return Math.max(0,Math.min(1,e||0))}function Fee(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const ISe=e=>()=>e;function IWn(e,t){return function(n){return e+n*t}}function AWn(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function RWn(e){return(e=+e)==1?I1t:function(t,n){return n-t?AWn(t,n,e):ISe(isNaN(t)?n:t)}}function I1t(e,t){var n=t-e;return n?IWn(e,n):ISe(isNaN(e)?t:e)}const hB=(function e(t){var n=RWn(t);function r(s,a){var i=n((s=$me(s)).r,(a=$me(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=I1t(s.opacity,a.opacity);return function(d){return s.r=i(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function PWn(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(a){for(s=0;s<n;++s)r[s]=e[s]*(1-a)+t[s]*a;return r}}function $Wn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function MWn(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),a=new Array(n),i;for(i=0;i<r;++i)s[i]=cx(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<r;++i)a[i]=s[i](l);return a}}function DWn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function ag(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function LWn(e,t){var n={},r={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=cx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Mme=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,zee=new RegExp(Mme.source,"g");function FWn(e){return function(){return e}}function zWn(e){return function(t){return e(t)+""}}function A1t(e,t){var n=Mme.lastIndex=zee.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Mme.exec(e))&&(s=zee.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:ag(r,s)})),n=zee.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?zWn(c[0].x):FWn(t):(t=c.length,function(u){for(var d=0,f;d<t;++d)l[(f=c[d]).i]=f.x(u);return l.join("")})}function cx(e,t){var n=typeof t,r;return t==null||n==="boolean"?ISe(t):(n==="number"?ag:n==="string"?(r=WO(t))?(t=r,hB):A1t:t instanceof WO?hB:t instanceof Date?DWn:$Wn(t)?PWn:Array.isArray(t)?MWn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?LWn:ag)(e,t)}function ASe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var _8e=180/Math.PI,Dme={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function R1t(e,t,n,r,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*_8e,skewX:Math.atan(c)*_8e,scaleX:i,scaleY:l}}var J6;function BWn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Dme:R1t(t.a,t.b,t.c,t.d,t.e,t.f)}function UWn(e){return e==null||(J6||(J6=document.createElementNS("http://www.w3.org/2000/svg","g")),J6.setAttribute("transform",e),!(e=J6.transform.baseVal.consolidate()))?Dme:(e=e.matrix,R1t(e.a,e.b,e.c,e.d,e.e,e.f))}function P1t(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push("translate(",null,t,null,n);m.push({i:v-4,x:ag(u,f)},{i:v-2,x:ag(d,p)})}else(f||p)&&h.push("translate("+f+t+p+n)}function i(u,d,f,p){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),p.push({i:f.push(s(f)+"rotate(",null,r)-2,x:ag(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,p){u!==d?p.push({i:f.push(s(f)+"skewX(",null,r)-2,x:ag(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push(s(h)+"scale(",null,",",null,")");m.push({i:v-4,x:ag(u,f)},{i:v-2,x:ag(d,p)})}else(f!==1||p!==1)&&h.push(s(h)+"scale("+f+","+p+")")}return function(u,d){var f=[],p=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,p),i(u.rotate,d.rotate,f,p),l(u.skewX,d.skewX,f,p),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,p),u=d=null,function(h){for(var m=-1,v=p.length,y;++m<v;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var VWn=P1t(BWn,"px, ","px)","deg)"),qWn=P1t(UWn,", ",")",")"),HWn=1e-12;function C8e(e){return((e=Math.exp(e))+1/e)/2}function WWn(e){return((e=Math.exp(e))-1/e)/2}function ZWn(e){return((e=Math.exp(2*e))-1)/(e+1)}const j8=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],p=i[2],h=d-l,m=f-c,v=h*h+m*m,y,b;if(v<HWn)b=Math.log(p/u)/t,y=function(E){return[l+E*h,c+E*m,u*Math.exp(t*E*b)]};else{var S=Math.sqrt(v),x=(p*p-u*u+r*v)/(2*u*n*S),k=(p*p-u*u-r*v)/(2*p*n*S),_=Math.log(Math.sqrt(x*x+1)-x),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,y=function(E){var j=E*b,T=C8e(_),I=u/(n*S)*(T*ZWn(t*j+_)-WWn(_));return[l+I*h,c+I*m,u*T/C8e(t*j+_)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function GWn(e,t){t===void 0&&(t=e,e=cx);for(var n=0,r=t.length-1,s=t[0],a=new Array(r<0?0:r);n<r;)a[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return a[l](i-l)}}var BT=0,P2=0,yR=0,$1t=1e3,mB,$2,gB=0,ZO=0,yH=0,_M=typeof performance=="object"&&performance.now?performance:Date,M1t=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function RSe(){return ZO||(M1t(QWn),ZO=_M.now()+yH)}function QWn(){ZO=0}function vB(){this._call=this._time=this._next=null}vB.prototype=D1t.prototype={constructor:vB,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?RSe():+n)+(t==null?0:+t),!this._next&&$2!==this&&($2?$2._next=this:mB=this,$2=this),this._call=e,this._time=n,Lme()},stop:function(){this._call&&(this._call=null,this._time=1/0,Lme())}};function D1t(e,t,n){var r=new vB;return r.restart(e,t,n),r}function YWn(){RSe(),++BT;for(var e=mB,t;e;)(t=ZO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--BT}function E8e(){ZO=(gB=_M.now())+yH,BT=P2=0;try{YWn()}finally{BT=0,XWn(),ZO=0}}function KWn(){var e=_M.now(),t=e-gB;t>$1t&&(yH-=t,gB=e)}function XWn(){for(var e,t=mB,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:mB=n);$2=e,Lme(r)}function Lme(e){if(!BT){P2&&(P2=clearTimeout(P2));var t=e-ZO;t>24?(e<1/0&&(P2=setTimeout(E8e,e-_M.now()-yH)),yR&&(yR=clearInterval(yR))):(yR||(gB=_M.now(),yR=setInterval(KWn,$1t)),BT=1,M1t(E8e))}}function j8e(e,t,n){var r=new vB;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var JWn=gH("start","end","cancel","interrupt"),eZn=[],L1t=0,T8e=1,Fme=2,T8=3,N8e=4,zme=5,N8=6;function bH(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;tZn(e,n,{name:t,index:r,group:s,on:JWn,tween:eZn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:L1t})}function PSe(e,t){var n=Hg(e,t);if(n.state>L1t)throw new Error("too late; already scheduled");return n}function zy(e,t){var n=Hg(e,t);if(n.state>T8)throw new Error("too late; already running");return n}function Hg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function tZn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=D1t(a,0,n.time);function a(u){n.state=T8e,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,p,h;if(n.state!==T8e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===T8)return j8e(i);h.state===N8e?(h.state=N8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=N8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(j8e(function(){n.state===T8&&(n.state=N8e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Fme,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Fme){for(n.state=T8,s=new Array(p=n.tween.length),d=0,f=-1;d<p;++d)(h=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=h);s.length=f+1}}function l(u){for(var d=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(c),n.state=zme,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===zme&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=N8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function I8(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>Fme&&r.state<zme,r.state=N8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function nZn(e){return this.each(function(){I8(this,e)})}function rZn(e,t){var n,r;return function(){var s=zy(this,e),a=s.tween;if(a!==n){r=n=a;for(var i=0,l=r.length;i<l;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function sZn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=zy(this,e),i=a.tween;if(i!==r){s=(r=i).slice();for(var l={name:t,value:n},c=0,u=s.length;c<u;++c)if(s[c].name===t){s[c]=l;break}c===u&&s.push(l)}a.tween=s}}function aZn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Hg(this.node(),n).tween,s=0,a=r.length,i;s<a;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?rZn:sZn)(n,e,t))}function $Se(e,t,n){var r=e._id;return e.each(function(){var s=zy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Hg(s,r).value[t]}}function F1t(e,t){var n;return(typeof t=="number"?ag:t instanceof WO?hB:(n=WO(t))?(t=n,hB):A1t)(e,t)}function iZn(e){return function(){this.removeAttribute(e)}}function oZn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function lZn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===r?a:a=t(r=i,n)}}function cZn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?a:a=t(r=i,n)}}function uZn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function dZn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function fZn(e,t){var n=vH(e),r=n==="transform"?qWn:F1t;return this.attrTween(e,typeof t=="function"?(n.local?dZn:uZn)(n,r,$Se(this,"attr."+e,t)):t==null?(n.local?oZn:iZn)(n):(n.local?cZn:lZn)(n,r,t))}function pZn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function hZn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function mZn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&hZn(e,a)),n}return s._value=t,s}function gZn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&pZn(e,a)),n}return s._value=t,s}function vZn(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=vH(e);return this.tween(n,(r.local?mZn:gZn)(r,t))}function yZn(e,t){return function(){PSe(this,e).delay=+t.apply(this,arguments)}}function bZn(e,t){return t=+t,function(){PSe(this,e).delay=t}}function xZn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?yZn:bZn)(t,e)):Hg(this.node(),t).delay}function wZn(e,t){return function(){zy(this,e).duration=+t.apply(this,arguments)}}function SZn(e,t){return t=+t,function(){zy(this,e).duration=t}}function kZn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?wZn:SZn)(t,e)):Hg(this.node(),t).duration}function OZn(e,t){if(typeof t!="function")throw new Error;return function(){zy(this,e).ease=t}}function _Zn(e){var t=this._id;return arguments.length?this.each(OZn(t,e)):Hg(this.node(),t).ease}function CZn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;zy(this,e).ease=n}}function EZn(e){if(typeof e!="function")throw new Error;return this.each(CZn(this._id,e))}function jZn(e){typeof e!="function"&&(e=g1t(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Tx(r,this._parents,this._name,this._id)}function TZn(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,a=Math.min(r,s),i=new Array(r),l=0;l<a;++l)for(var c=t[l],u=n[l],d=c.length,f=i[l]=new Array(d),p,h=0;h<d;++h)(p=c[h]||u[h])&&(f[h]=p);for(;l<r;++l)i[l]=t[l];return new Tx(i,this._parents,this._name,this._id)}function NZn(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function IZn(e,t,n){var r,s,a=NZn(t)?PSe:zy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function AZn(e,t){var n=this._id;return arguments.length<2?Hg(this.node(),n).on.on(e):this.each(IZn(n,e,t))}function RZn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function PZn(){return this.on("end.remove",RZn(this._id))}function $Zn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=jSe(e));for(var r=this._groups,s=r.length,a=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=a[i]=new Array(c),d,f,p=0;p<c;++p)(d=l[p])&&(f=e.call(d,d.__data__,p,l))&&("__data__"in d&&(f.__data__=d.__data__),u[p]=f,bH(u[p],t,n,p,u,Hg(d,n)));return new Tx(a,this._parents,t,n)}function MZn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=m1t(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var p=e.call(d,d.__data__,f,c),h,m=Hg(d,n),v=0,y=p.length;v<y;++v)(h=p[v])&&bH(h,t,n,v,p,m);a.push(p),i.push(d)}return new Tx(a,i,t,n)}var DZn=$4.prototype.constructor;function LZn(){return new DZn(this._groups,this._parents)}function FZn(e,t){var n,r,s;return function(){var a=zT(this,e),i=(this.style.removeProperty(e),zT(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function z1t(e){return function(){this.style.removeProperty(e)}}function zZn(e,t,n){var r,s=n+"",a;return function(){var i=zT(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function BZn(e,t,n){var r,s,a;return function(){var i=zT(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),zT(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function UZn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=zy(this,e),u=c.on,d=c.value[a]==null?l||(l=z1t(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function VZn(e,t,n){var r=(e+="")=="transform"?VWn:F1t;return t==null?this.styleTween(e,FZn(e,r)).on("end.style."+e,z1t(e)):typeof t=="function"?this.styleTween(e,BZn(e,r,$Se(this,"style."+e,t))).each(UZn(this._id,e)):this.styleTween(e,zZn(e,r,t),n).on("end.style."+e,null)}function qZn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function HZn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&qZn(e,i,n)),r}return a._value=t,a}function WZn(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(t==null)return this.tween(r,null);if(typeof t!="function")throw new Error;return this.tween(r,HZn(e,t,n??""))}function ZZn(e){return function(){this.textContent=e}}function GZn(e){return function(){var t=e(this);this.textContent=t??""}}function QZn(e){return this.tween("text",typeof e=="function"?GZn($Se(this,"text",e)):ZZn(e==null?"":e+""))}function YZn(e){return function(t){this.textContent=e.call(this,t)}}function KZn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&YZn(s)),t}return r._value=e,r}function XZn(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,KZn(e))}function JZn(){for(var e=this._name,t=this._id,n=B1t(),r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=Hg(c,t);bH(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Tx(r,this._parents,e,n)}function eGn(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var u=zy(this,r),d=u.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),u.on=t}),s===0&&a()})}var tGn=0;function Tx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function B1t(){return++tGn}var yb=$4.prototype;Tx.prototype={constructor:Tx,select:$Zn,selectAll:MZn,selectChild:yb.selectChild,selectChildren:yb.selectChildren,filter:jZn,merge:TZn,selection:LZn,transition:JZn,call:yb.call,nodes:yb.nodes,node:yb.node,size:yb.size,empty:yb.empty,each:yb.each,on:AZn,attr:fZn,attrTween:vZn,style:VZn,styleTween:WZn,text:QZn,textTween:XZn,remove:PZn,tween:aZn,delay:xZn,duration:kZn,ease:_Zn,easeVarying:EZn,end:eGn,[Symbol.iterator]:yb[Symbol.iterator]};function nGn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var rGn={time:null,delay:0,duration:250,ease:nGn};function sGn(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function aGn(e){var t,n;e instanceof Tx?(t=e._id,e=e._name):(t=B1t(),(n=rGn).time=RSe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&bH(c,e,t,u,i,n||sGn(c,t));return new Tx(r,this._parents,e,t)}$4.prototype.interrupt=nZn;$4.prototype.transition=aGn;const eF=e=>()=>e;function iGn(e,{sourceEvent:t,target:n,transform:r,dispatch:s}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:s}})}function Kb(e,t,n){this.k=e,this.x=t,this.y=n}Kb.prototype={constructor:Kb,scale:function(e){return e===1?this:new Kb(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Kb(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var xH=new Kb(1,0,0);U1t.prototype=Kb.prototype;function U1t(e){for(;!e.__zoom;)if(!(e=e.parentNode))return xH;return e.__zoom}function Bee(e){e.stopImmediatePropagation()}function bR(e){e.preventDefault(),e.stopImmediatePropagation()}function oGn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function lGn(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function I8e(){return this.__zoom||xH}function cGn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function uGn(){return navigator.maxTouchPoints||"ontouchstart"in this}function dGn(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function V1t(){var e=oGn,t=lGn,n=dGn,r=cGn,s=uGn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=j8,u=gH("start","zoom","end"),d,f,p,h=500,m=150,v=0,y=10;function b(M){M.property("__zoom",I8e).on("wheel.zoom",j,{passive:!1}).on("mousedown.zoom",T).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(M,z,H,F){var B=M.selection?M.selection():M;B.property("__zoom",I8e),M!==B?_(M,z,H,F):B.interrupt().each(function(){C(this,arguments).event(F).start().zoom(null,typeof z=="function"?z.apply(this,arguments):z).end()})},b.scaleBy=function(M,z,H,F){b.scaleTo(M,function(){var B=this.__zoom.k,q=typeof z=="function"?z.apply(this,arguments):z;return B*q},H,F)},b.scaleTo=function(M,z,H,F){b.transform(M,function(){var B=t.apply(this,arguments),q=this.__zoom,D=H==null?k(B):typeof H=="function"?H.apply(this,arguments):H,G=q.invert(D),V=typeof z=="function"?z.apply(this,arguments):z;return n(x(S(q,V),D,G),B,i)},H,F)},b.translateBy=function(M,z,H,F){b.transform(M,function(){return n(this.__zoom.translate(typeof z=="function"?z.apply(this,arguments):z,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,F)},b.translateTo=function(M,z,H,F,B){b.transform(M,function(){var q=t.apply(this,arguments),D=this.__zoom,G=F==null?k(q):typeof F=="function"?F.apply(this,arguments):F;return n(xH.translate(G[0],G[1]).scale(D.k).translate(typeof z=="function"?-z.apply(this,arguments):-z,typeof H=="function"?-H.apply(this,arguments):-H),q,i)},F,B)};function S(M,z){return z=Math.max(a[0],Math.min(a[1],z)),z===M.k?M:new Kb(z,M.x,M.y)}function x(M,z,H){var F=z[0]-H[0]*M.k,B=z[1]-H[1]*M.k;return F===M.x&&B===M.y?M:new Kb(M.k,F,B)}function k(M){return[(+M[0][0]+ +M[1][0])/2,(+M[0][1]+ +M[1][1])/2]}function _(M,z,H,F){M.on("start.zoom",function(){C(this,arguments).event(F).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(F).end()}).tween("zoom",function(){var B=this,q=arguments,D=C(B,q).event(F),G=t.apply(B,q),V=H==null?k(G):typeof H=="function"?H.apply(B,q):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),U=B.__zoom,Z=typeof z=="function"?z.apply(B,q):z,K=c(U.invert(V).concat($/U.k),Z.invert(V).concat($/Z.k));return function(ne){if(ne===1)ne=Z;else{var te=K(ne),J=$/te[2];ne=new Kb(J,V[0]-te[0]*J,V[1]-te[1]*J)}D.zoom(null,ne)}})}function C(M,z,H){return!H&&M.__zooming||new E(M,z)}function E(M,z){this.that=M,this.args=z,this.active=0,this.sourceEvent=null,this.extent=t.apply(M,z),this.taps=0}E.prototype={event:function(M){return M&&(this.sourceEvent=M),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(M,z){return this.mouse&&M!=="mouse"&&(this.mouse[1]=z.invert(this.mouse[0])),this.touch0&&M!=="touch"&&(this.touch0[1]=z.invert(this.touch0[0])),this.touch1&&M!=="touch"&&(this.touch1[1]=z.invert(this.touch1[0])),this.that.__zoom=z,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(M){var z=Sp(this.that).datum();u.call(M,this.that,new iGn(M,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),z)}};function j(M,...z){if(!e.apply(this,arguments))return;var H=C(this,z).event(M),F=this.__zoom,B=Math.max(a[0],Math.min(a[1],F.k*Math.pow(2,r.apply(this,arguments)))),q=rg(M);if(H.wheel)(H.mouse[0][0]!==q[0]||H.mouse[0][1]!==q[1])&&(H.mouse[1]=F.invert(H.mouse[0]=q)),clearTimeout(H.wheel);else{if(F.k===B)return;H.mouse=[q,F.invert(q)],I8(this),H.start()}bR(M),H.wheel=setTimeout(D,m),H.zoom("mouse",n(x(S(F,B),H.mouse[0],H.mouse[1]),H.extent,i));function D(){H.wheel=null,H.end()}}function T(M,...z){if(p||!e.apply(this,arguments))return;var H=M.currentTarget,F=C(this,z,!0).event(M),B=Sp(M.view).on("mousemove.zoom",V,!0).on("mouseup.zoom",$,!0),q=rg(M,H),D=M.clientX,G=M.clientY;C1t(M.view),Bee(M),F.mouse=[q,this.__zoom.invert(q)],I8(this),F.start();function V(U){if(bR(U),!F.moved){var Z=U.clientX-D,K=U.clientY-G;F.moved=Z*Z+K*K>v}F.event(U).zoom("mouse",n(x(F.that.__zoom,F.mouse[0]=rg(U,H),F.mouse[1]),F.extent,i))}function $(U){B.on("mousemove.zoom mouseup.zoom",null),E1t(U.view,F.moved),bR(U),F.event(U).end()}}function I(M,...z){if(e.apply(this,arguments)){var H=this.__zoom,F=rg(M.changedTouches?M.changedTouches[0]:M,this),B=H.invert(F),q=H.k*(M.shiftKey?.5:2),D=n(x(S(H,q),F,B),t.apply(this,z),i);bR(M),l>0?Sp(this).transition().duration(l).call(_,D,F,M):Sp(this).call(b.transform,D,F,M)}}function A(M,...z){if(e.apply(this,arguments)){var H=M.touches,F=H.length,B=C(this,z,M.changedTouches.length===F).event(M),q,D,G,V;for(Bee(M),D=0;D<F;++D)G=H[D],V=rg(G,this),V=[V,this.__zoom.invert(V),G.identifier],B.touch0?!B.touch1&&B.touch0[2]!==V[2]&&(B.touch1=V,B.taps=0):(B.touch0=V,q=!0,B.taps=1+!!d);d&&(d=clearTimeout(d)),q&&(B.taps<2&&(f=V[0],d=setTimeout(function(){d=null},h)),I8(this),B.start())}}function R(M,...z){if(this.__zooming){var H=C(this,z).event(M),F=M.changedTouches,B=F.length,q,D,G,V;for(bR(M),q=0;q<B;++q)D=F[q],G=rg(D,this),H.touch0&&H.touch0[2]===D.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===D.identifier&&(H.touch1[0]=G);if(D=H.that.__zoom,H.touch1){var $=H.touch0[0],U=H.touch0[1],Z=H.touch1[0],K=H.touch1[1],ne=(ne=Z[0]-$[0])*ne+(ne=Z[1]-$[1])*ne,te=(te=K[0]-U[0])*te+(te=K[1]-U[1])*te;D=S(D,Math.sqrt(ne/te)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],V=[(U[0]+K[0])/2,(U[1]+K[1])/2]}else if(H.touch0)G=H.touch0[0],V=H.touch0[1];else return;H.zoom("touch",n(x(D,G,V),H.extent,i))}}function L(M,...z){if(this.__zooming){var H=C(this,z).event(M),F=M.changedTouches,B=F.length,q,D;for(Bee(M),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),q=0;q<B;++q)D=F[q],H.touch0&&H.touch0[2]===D.identifier?delete H.touch0:H.touch1&&H.touch1[2]===D.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(D=rg(D,this),Math.hypot(f[0]-D[0],f[1]-D[1])<y)){var G=Sp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(M){return arguments.length?(r=typeof M=="function"?M:eF(+M),b):r},b.filter=function(M){return arguments.length?(e=typeof M=="function"?M:eF(!!M),b):e},b.touchable=function(M){return arguments.length?(s=typeof M=="function"?M:eF(!!M),b):s},b.extent=function(M){return arguments.length?(t=typeof M=="function"?M:eF([[+M[0][0],+M[0][1]],[+M[1][0],+M[1][1]]]),b):t},b.scaleExtent=function(M){return arguments.length?(a[0]=+M[0],a[1]=+M[1],b):[a[0],a[1]]},b.translateExtent=function(M){return arguments.length?(i[0][0]=+M[0][0],i[1][0]=+M[1][0],i[0][1]=+M[0][1],i[1][1]=+M[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(M){return arguments.length?(n=M,b):n},b.duration=function(M){return arguments.length?(l=+M,b):l},b.interpolate=function(M){return arguments.length?(c=M,b):c},b.on=function(){var M=u.on.apply(u,arguments);return M===u?b:M},b.clickDistance=function(M){return arguments.length?(v=(M=+M)*M,b):Math.sqrt(v)},b.tapDistance=function(M){return arguments.length?(y=+M,b):y},b}const by={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},CM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],q1t=["Enter"," ","Escape"],H1t={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var UT;(function(e){e.Strict="strict",e.Loose="loose"})(UT||(UT={}));var rO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(rO||(rO={}));var EM;(function(e){e.Partial="partial",e.Full="full"})(EM||(EM={}));const W1t={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var dw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(dw||(dw={}));var jM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(jM||(jM={}));var sr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(sr||(sr={}));const A8e={[sr.Left]:sr.Right,[sr.Right]:sr.Left,[sr.Top]:sr.Bottom,[sr.Bottom]:sr.Top};function Z1t(e){return e===null?null:e?"valid":"invalid"}const G1t=e=>"id"in e&&"source"in e&&"target"in e,fGn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),MSe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),D4=(e,t=[0,0])=>{const{width:n,height:r}=Xx(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},pGn=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):MSe(s)?s:t.nodeLookup.get(s.id));const l=i?yB(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return wH(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return SH(n)},L4=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=wH(n,yB(s)),r=!0)}),r?SH(n):{x:0,y:0,width:0,height:0}},DSe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...z4(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:p=!1}=u;if(i&&!f||p)continue;const h=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=TM(l,qT(u)),y=(h??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},hGn=(e,t)=>{const n=new Set;return e.forEach(r=>{n.add(r.id)}),t.filter(r=>n.has(r.source)||n.has(r.target))};function mGn(e,t){const n=new Map,r=t?.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{s.measured.width&&s.measured.height&&(t?.includeHiddenNodes||!s.hidden)&&(!r||r.has(s.id))&&n.set(s.id,s)}),n}async function gGn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=mGn(e,i),c=L4(l),u=LSe(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function Q1t({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=i.origin??r;let f=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",by.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&HT(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const p=HT(f)?GO(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",by.error015()),{position:{x:p.x-c+(i.measured.width??0)*d[0],y:p.y-u+(i.measured.height??0)*d[1]},positionAbsolute:p}}async function vGn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=a.has(p.id),m=!h&&p.parentId&&i.find(v=>v.id===p.parentId);(h||m)&&i.push(p)}const l=new Set(t.map(p=>p.id)),c=r.filter(p=>p.deletable!==!1),d=hGn(i,c);for(const p of c)l.has(p.id)&&!d.find(m=>m.id===p.id)&&d.push(p);if(!s)return{edges:d,nodes:i};const f=await s({nodes:i,edges:d});return typeof f=="boolean"?f?{edges:d,nodes:i}:{edges:[],nodes:[]}:f}const VT=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),GO=(e={x:0,y:0},t,n)=>({x:VT(e.x,t[0][0],t[1][0]-(n?.width??0)),y:VT(e.y,t[0][1],t[1][1]-(n?.height??0))});function Y1t(e,t,n){const{width:r,height:s}=Xx(n),{x:a,y:i}=n.internals.positionAbsolute;return GO(e,[[a,i],[a+r,i+s]],t)}const R8e=(e,t,n)=>e<t?VT(Math.abs(e-t),1,t)/t:e>n?-VT(Math.abs(e-n),1,t)/t:0,K1t=(e,t,n=15,r=40)=>{const s=R8e(e.x,r,t.width-r)*n,a=R8e(e.y,r,t.height-r)*n;return[s,a]},wH=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Bme=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),SH=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),qT=(e,t=[0,0])=>{const{x:n,y:r}=MSe(e)?e.internals.positionAbsolute:D4(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},yB=(e,t=[0,0])=>{const{x:n,y:r}=MSe(e)?e.internals.positionAbsolute:D4(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},X1t=(e,t)=>SH(wH(Bme(e),Bme(t))),TM=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},P8e=e=>gg(e.width)&&gg(e.height)&&gg(e.x)&&gg(e.y),gg=e=>!isNaN(e)&&isFinite(e),yGn=(e,t)=>{},F4=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),z4=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?F4(l,i):l},bB=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function cE(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function bGn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=cE(e,n),s=cE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=cE(e.top??e.y??0,n),s=cE(e.bottom??e.y??0,n),a=cE(e.left??e.x??0,t),i=cE(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:a,x:a+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function xGn(e,t,n,r,s,a){const{x:i,y:l}=bB(e,[t,n,r]),{x:c,y:u}=bB({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const LSe=(e,t,n,r,s,a)=>{const i=bGn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=VT(u,r,s),f=e.x+e.width/2,p=e.y+e.height/2,h=t/2-f*d,m=n/2-p*d,v=xGn(e,h,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},NM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function HT(e){return e!=null&&e!=="parent"}function Xx(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function J1t(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function eSt(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function $8e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function wGn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function SGn(e){return{...H1t,...e||{}}}function pP(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=vg(e),l=z4({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?F4(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const FSe=e=>({width:e.offsetWidth,height:e.offsetHeight}),tSt=e=>e?.getRootNode?.()||window?.document,kGn=["INPUT","SELECT","TEXTAREA"];function nSt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:kGn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const rSt=e=>"clientX"in e,vg=(e,t)=>{const n=rSt(e),r=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:s-(t?.top??0)}},M8e=(e,t,n,r,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...FSe(i)}})};function sSt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function tF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function D8e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case sr.Left:return[t-tF(t-r,a),n];case sr.Right:return[t+tF(r-t,a),n];case sr.Top:return[t,n-tF(n-s,a)];case sr.Bottom:return[t,n+tF(s-n,a)]}}function zSe({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,curvature:i=.25}){const[l,c]=D8e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=D8e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=sSt({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,p,h,m]}function aSt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function OGn({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return r;const i=s&&n?r+1e3:r,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function _Gn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=wH(yB(e),yB(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return TM(i,SH(a))>0}const CGn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,EGn=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),jGn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||CGn;let s;return G1t(e)?s={...e}:s={...e,id:r(e)},EGn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function iSt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=aSt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const L8e={[sr.Left]:{x:-1,y:0},[sr.Right]:{x:1,y:0},[sr.Top]:{x:0,y:-1},[sr.Bottom]:{x:0,y:1}},TGn=({source:e,sourcePosition:t=sr.Bottom,target:n})=>t===sr.Left||t===sr.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},F8e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function NGn({source:e,sourcePosition:t=sr.Bottom,target:n,targetPosition:r=sr.Top,center:s,offset:a,stepPosition:i}){const l=L8e[t],c=L8e[r],u={x:e.x+l.x*a,y:e.y+l.y*a},d={x:n.x+c.x*a,y:n.y+c.y*a},f=TGn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],v,y;const b={x:0,y:0},S={x:0,y:0},[,,x,k]=aSt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const j=[{x:v,y:u.y},{x:v,y:d.y}],T=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?j:T:m=p==="x"?T:j}else{const j=[{x:u.x,y:d.y}],T=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?T:j:m=l.y===h?j:T,t===r){const M=Math.abs(e[p]-n[p]);if(M<=a){const z=Math.min(a-1,a-M);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*z:S[p]=(d[p]>n[p]?-1:1)*z}}if(t!==r){const M=p==="x"?"y":"x",z=l[p]===c[M],H=u[M]>d[M],F=u[M]<d[M];(l[p]===1&&(!z&&H||z&&F)||l[p]!==1&&(!z&&F||z&&H))&&(m=p==="x"?j:T)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+S.x,y:d.y+S.y},R=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));R>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const _={x:u.x+b.x,y:u.y+b.y},C={x:d.x+S.x,y:d.y+S.y};return[[e,..._.x!==m[0].x||_.y!==m[0].y?[_]:[],...m,...C.x!==m[m.length-1].x||C.y!==m[m.length-1].y?[C]:[],n],v,y,x,k]}function IGn(e,t,n,r){const s=Math.min(F8e(e,t)/2,F8e(t,n)/2,r),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${a+s*u},${i}Q ${a},${i} ${a},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function Ume({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,v]=NGn({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:a,center:{x:l,y:c},offset:u,stepPosition:d});let y=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)y+=IGn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,p,h,m,v]}function z8e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function AGn(e){const{sourceNode:t,targetNode:n}=e;if(!z8e(t)||!z8e(n))return null;const r=t.internals.handleBounds||B8e(t.handles),s=n.internals.handleBounds||B8e(n.handles),a=U8e(r?.source??[],e.sourceHandle),i=U8e(e.connectionMode===UT.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",by.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||sr.Bottom,c=i?.position||sr.Top,u=QO(t,a,l),d=QO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function B8e(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,r.type==="source"?t.push(r):r.type==="target"&&n.push(r);return{source:t,target:n}}function QO(e,t,n=sr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??Xx(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case sr.Top:return{x:s+i/2,y:a};case sr.Right:return{x:s+i,y:a+l/2};case sr.Bottom:return{x:s+i/2,y:a+l};case sr.Left:return{x:s,y:a+l/2}}}function U8e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Vme(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function RGn(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=Vme(c,t);a.has(u)||(i.push({id:u,color:c.color||n,...c}),a.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const oSt=1e3,PGn=10,BSe={nodeOrigin:[0,0],nodeExtent:CM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},$Gn={...BSe,checkEquality:!0};function USe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function MGn(e,t,n){const r=USe(BSe,n);for(const s of e.values())if(s.parentId)qSe(s,e,t,r);else{const a=D4(s,r.nodeOrigin),i=HT(s.extent)?s.extent:r.nodeExtent,l=GO(a,i,Xx(s));s.internals.positionAbsolute=l}}function DGn(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&r.push(a)}return{source:n,target:r}}function VSe(e){return e==="manual"}function qme(e,t,n,r={}){const s=USe($Gn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!VSe(s.zIndexMode)?oSt:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=i.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const p=D4(d,s.nodeOrigin),h=HT(d.extent)?d.extent:s.nodeExtent,m=GO(p,h,Xx(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:DGn(d,f),z:lSt(d,l,s.zIndexMode),userNode:d}},t.set(d.id,f)}(f.measured===void 0||f.measured.width===void 0||f.measured.height===void 0)&&!f.hidden&&(c=!1),d.parentId&&qSe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function LGn(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function qSe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=USe(BSe,r),u=e.parentId,d=t.get(u);if(!d){console.warn(`Parent node ${u} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}LGn(e,n),s&&!d.parentId&&d.internals.rootParentIndex===void 0&&c==="auto"&&(d.internals.rootParentIndex=++s.i,d.internals.z=d.internals.z+s.i*PGn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!VSe(c)?oSt:0,{x:p,y:h,z:m}=FGn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=p!==v.x||h!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:v,z:m}})}function lSt(e,t,n){const r=gg(e.zIndex)?e.zIndex:0;return VSe(n)?r:r+(e.selected?t:0)}function FGn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=Xx(e),u=D4(e,n),d=HT(e.extent)?GO(u,e.extent,c):u;let f=GO({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=Y1t(f,c,t));const p=lSt(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function HSe(e,t,n,r=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??qT(l),u=X1t(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=Xx(l),f=l.origin??r,p=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,h=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(p>0||h>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+y,y:l.position.y-h+b}}),n.get(c)?.forEach(S=>{e.some(x=>x.id===S.id)||s.push({id:S.id,type:"position",position:{x:S.position.x+p,y:S.position.y+h}})})),(d.width<i.width||d.height<i.height||p||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(p?f[0]*p-y:0),height:v+(h?f[1]*h-b:0)}})}),s}function zGn(e,t,n,r,s,a,i){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),p=[];for(const h of e.values()){const m=t.get(h.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=FSe(h.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||h.force))){const S=h.nodeElement.getBoundingClientRect(),x=HT(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=Y1t(k,v,t.get(m.parentId)):x&&(k=GO(k,x,v));const _={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:M8e("source",h.nodeElement,S,f,m.id),target:M8e("target",h.nodeElement,S,f,m.id)}}};t.set(m.id,_),m.parentId&&qSe(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:qT(_,s)}))}}if(p.length>0){const h=HSe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function BGn({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function V8e(e,t,n,r,s,a){let i=s;const l=r.get(i)||new Map;r.set(i,l.set(n,t)),i=`${s}-${e}`;const c=r.get(i)||new Map;if(r.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function cSt(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;V8e("source",c,d,e,s,i),V8e("target",c,u,e,a,l),t.set(r.id,r)}}function uSt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:uSt(n,t):!1}function q8e(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function UGn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!uSt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function Uee({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:s[0],s]}function VGn({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:r-s.distance.y},i=F4(a,t);return{x:i.x-a.x,y:i.y-a.y}}function qGn({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,p=null,h=!1,m=!1,v=null;function y({noDragClassName:S,handleSelector:x,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:E=0}){p=Sp(k);function j({x:R,y:L}){const{nodeLookup:M,nodeExtent:z,snapGrid:H,snapToGrid:F,nodeOrigin:B,onNodeDrag:q,onSelectionDrag:D,onError:G,updateNodePositions:V}=t();a={x:R,y:L};let $=!1;const U=l.size>1,Z=U&&z?Bme(L4(l)):null,K=U&&F?VGn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[ne,te]of l){if(!M.has(ne))continue;let J={x:R-te.distance.x,y:L-te.distance.y};F&&(J=K?{x:Math.round(J.x+K.x),y:Math.round(J.y+K.y)}:F4(J,H));let ae=null;if(U&&z&&!te.extent&&Z){const{positionAbsolute:ee}=te.internals,ce=ee.x-Z.x+z[0][0],de=ee.x+te.measured.width-Z.x2+z[1][0],oe=ee.y-Z.y+z[0][1],me=ee.y+te.measured.height-Z.y2+z[1][1];ae=[[ce,oe],[de,me]]}const{position:pe,positionAbsolute:Y}=Q1t({nodeId:ne,nextPosition:J,nodeLookup:M,nodeExtent:ae||z,nodeOrigin:B,onError:G});$=$||te.position.x!==pe.x||te.position.y!==pe.y,te.position=pe,te.internals.positionAbsolute=Y}if(m=m||$,!!$&&(V(l,!0),v&&(r||q||!C&&D))){const[ne,te]=Uee({nodeId:C,dragItems:l,nodeLookup:M});r?.(v,l,ne,te),q?.(v,ne,te),C||D?.(v,te)}}async function T(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:M,autoPanOnNodeDrag:z}=t();if(!z){c=!1,cancelAnimationFrame(i);return}const[H,F]=K1t(u,d,M);(H!==0||F!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-F/R[2],await L({x:H,y:F})&&j(a)),i=requestAnimationFrame(T)}function I(R){const{nodeLookup:L,multiSelectionActive:M,nodesDraggable:z,transform:H,snapGrid:F,snapToGrid:B,selectNodesOnDrag:q,onNodeDragStart:D,onSelectionDragStart:G,unselectNodesAndEdges:V}=t();f=!0,(!q||!_)&&!M&&C&&(L.get(C)?.selected||V()),_&&q&&C&&e?.(C);const $=pP(R.sourceEvent,{transform:H,snapGrid:F,snapToGrid:B,containerBounds:d});if(a=$,l=UGn(L,z,$,C),l.size>0&&(n||D||!C&&G)){const[U,Z]=Uee({nodeId:C,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,U,Z),D?.(R.sourceEvent,U,Z),C||G?.(R.sourceEvent,Z)}}const A=j1t().clickDistance(E).on("start",R=>{const{domNode:L,nodeDragThreshold:M,transform:z,snapGrid:H,snapToGrid:F}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,v=R.sourceEvent,M===0&&I(R),a=pP(R.sourceEvent,{transform:z,snapGrid:H,snapToGrid:F,containerBounds:d}),u=vg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:M,snapGrid:z,snapToGrid:H,nodeDragThreshold:F,nodeLookup:B}=t(),q=pP(R.sourceEvent,{transform:M,snapGrid:z,snapToGrid:H,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||C&&!B.has(C))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,T()),!f){const D=vg(R.sourceEvent,d),G=D.x-u.x,V=D.y-u.y;Math.sqrt(G*G+V*V)>F&&I(R)}(a.x!==q.xSnapped||a.y!==q.ySnapped)&&l&&f&&(u=vg(R.sourceEvent,d),j(q))}}).on("end",R=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:M,onNodeDragStop:z,onSelectionDragStop:H}=t();if(m&&(M(l,!1),m=!1),s||z||!C&&H){const[F,B]=Uee({nodeId:C,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,F,B),z?.(R.sourceEvent,F,B),C||H?.(R.sourceEvent,B)}}}).filter(R=>{const L=R.target;return!R.button&&(!S||!q8e(L,`.${S}`,k))&&(!x||q8e(L,x,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function HGn(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())TM(s,qT(a))>0&&r.push(a);return r}const WGn=250;function ZGn(e,t,n,r){let s=[],a=1/0;const i=HGn(e,n,t+WGn);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const u of c){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:d,y:f}=QO(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<a?(s=[{...u,x:d,y:f}],a=p):p===a&&s.push({...u,x:d,y:f}))}}if(!s.length)return null;if(s.length>1){const l=r.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function dSt(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...QO(i,c,c.position,!0)}:c}function fSt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function GGn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const pSt=()=>!0;function QGn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=pSt,onReconnectEnd:S,updateConnection:x,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:E=1,handleDomNode:j}){const T=tSt(e.target);let I=0,A;const{x:R,y:L}=vg(e),M=fSt(a,j),z=l?.getBoundingClientRect();let H=!1;if(!z||!M)return;const F=dSt(s,M,r,c,t);if(!F)return;let B=vg(e,z),q=!1,D=null,G=!1,V=null;function $(){if(!d||!z)return;const[pe,Y]=K1t(B,z,C);p({x:pe,y:Y}),I=requestAnimationFrame($)}const U={...F,nodeId:s,type:M,position:F.position},Z=c.get(s);let ne={inProgress:!0,isValid:null,from:QO(Z,U,sr.Left,!0),fromHandle:U,fromPosition:U.position,fromNode:Z,to:B,toHandle:null,toPosition:A8e[U.position],toNode:null,pointer:B};function te(){H=!0,x(ne),m?.(e,{nodeId:s,handleId:r,handleType:M})}E===0&&te();function J(pe){if(!H){const{x:me,y:be}=vg(pe),we=me-R,Te=be-L;if(!(we*we+Te*Te>E*E))return;te()}if(!_()||!U){ae(pe);return}const Y=k();B=vg(pe,z),A=ZGn(z4(B,Y,!1,[1,1]),n,c,U),q||($(),q=!0);const ee=hSt(pe,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:T,lib:u,flowId:f,nodeLookup:c});V=ee.handleDomNode,D=ee.connection,G=GGn(!!A,ee.isValid);const ce=c.get(s),de=ce?QO(ce,U,sr.Left,!0):ne.from,oe={...ne,from:de,isValid:G,to:ee.toHandle&&G?bB({x:ee.toHandle.x,y:ee.toHandle.y},Y):B,toHandle:ee.toHandle,toPosition:G&&ee.toHandle?ee.toHandle.position:A8e[U.position],toNode:ee.toHandle?c.get(ee.toHandle.nodeId):null,pointer:B};x(oe),ne=oe}function ae(pe){if(!("touches"in pe&&pe.touches.length>0)){if(H){(A||V)&&D&&G&&v?.(D);const{inProgress:Y,...ee}=ne,ce={...ee,toPosition:ne.toHandle?ne.toPosition:null};y?.(pe,ce),a&&S?.(pe,ce)}h(),cancelAnimationFrame(I),q=!1,G=!1,D=null,V=null,T.removeEventListener("mousemove",J),T.removeEventListener("mouseup",ae),T.removeEventListener("touchmove",J),T.removeEventListener("touchend",ae)}}T.addEventListener("mousemove",J),T.addEventListener("mouseup",ae),T.addEventListener("touchmove",J),T.addEventListener("touchend",ae)}function hSt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=pSt,nodeLookup:d}){const f=a==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=vg(e),v=i.elementFromPoint(h,m),y=v?.classList.contains(`${l}-flow__handle`)?v:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const S=fSt(void 0,y),x=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),_=y.classList.contains("connectable"),C=y.classList.contains("connectableend");if(!x||!S)return b;const E={source:f?x:r,sourceHandle:f?k:s,target:f?r:x,targetHandle:f?s:k};b.connection=E;const T=_&&C&&(n===UT.Strict?f&&S==="source"||!f&&S==="target":x!==r||k!==s);b.isValid=T&&u(E),b.toHandle=dSt(x,S,k,d,n,!0)}return b}const Hme={onPointerDown:QGn,isValid:hSt};function YGn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Sp(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=x=>{if(x.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=x.sourceEvent.ctrlKey&&NM()?10:1,C=-x.sourceEvent.deltaY*(x.sourceEvent.deltaMode===1?.05:x.sourceEvent.deltaMode?1:.002)*d,E=k[2]*Math.pow(2,C*_);t.scaleTo(E)};let v=[0,0];const y=x=>{(x.sourceEvent.type==="mousedown"||x.sourceEvent.type==="touchstart")&&(v=[x.sourceEvent.clientX??x.sourceEvent.touches[0].clientX,x.sourceEvent.clientY??x.sourceEvent.touches[0].clientY])},b=x=>{const k=n();if(x.sourceEvent.type!=="mousemove"&&x.sourceEvent.type!=="touchmove"||!t)return;const _=[x.sourceEvent.clientX??x.sourceEvent.touches[0].clientX,x.sourceEvent.clientY??x.sourceEvent.touches[0].clientY],C=[_[0]-v[0],_[1]-v[1]];v=_;const E=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),j={x:k[0]-C[0]*E,y:k[1]-C[1]*E},T=[[0,0],[c,u]];t.setViewportConstrained({x:j.x,y:j.y,zoom:k[2]},T,l)},S=V1t().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(S,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:rg}}const kH=e=>({x:e.x,y:e.y,zoom:e.k}),Vee=({x:e,y:t,zoom:n})=>xH.translate(e,t).scale(n),fj=(e,t)=>e.target.closest(`.${t}`),mSt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),KGn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,qee=(e,t=0,n=KGn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},gSt=e=>{const t=e.ctrlKey&&NM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function XGn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(fj(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const y=rg(d),b=gSt(d),S=f*Math.pow(2,b);r.scaleTo(n,S,y,d);return}const p=d.deltaMode===1?20:1;let h=s===rO.Vertical?0:d.deltaX*p,m=s===rO.Horizontal?0:d.deltaY*p;!NM()&&d.shiftKey&&s!==rO.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const v=kH(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,v),e.panScrollTimeout=setTimeout(()=>{u?.(d,v),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,v))}}function JGn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=fj(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function eQn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=kH(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=s,r.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(r.sourceEvent,s)}}function tQn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&mSt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,kH(a.transform))}}function nQn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&mSt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=kH(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function rQn({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const p=e||t,h=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(fj(f,`${u}-flow__node`)||fj(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||fj(f,l)&&m||fj(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!p&&!s&&!h&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function sQn({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),f=V1t().scaleExtent([t,n]).translateExtent(r),p=Sp(e).call(f);S({x:s.x,y:s.y,zoom:VT(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(gSt);function v(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?cx:j8).transform(qee(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:M,panOnScroll:z,panOnDrag:H,panOnScrollMode:F,panOnScrollSpeed:B,preventScrolling:q,zoomOnPinch:D,zoomOnScroll:G,zoomOnDoubleClick:V,zoomActivationKeyPressed:$,lib:U,onTransformChange:Z,connectionInProgress:K,paneClickDistance:ne,selectionOnDrag:te}){M&&!u.isZoomingOrPanning&&b();const J=z&&!$&&!M;f.clickDistance(te?1/0:!gg(ne)||ne<0?0:ne);const ae=J?XGn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:F,panOnScrollSpeed:B,zoomOnPinch:D,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):JGn({noWheelClassName:A,preventScrolling:q,d3ZoomHandler:h});if(p.on("wheel.zoom",ae,{passive:!1}),!M){const Y=eQn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",Y);const ee=tQn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",ee);const ce=nQn({zoomPanValues:u,panOnDrag:H,panOnScroll:z,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",ce)}const pe=rQn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:z,zoomOnDoubleClick:V,zoomOnPinch:D,userSelectionActive:M,noPanClassName:R,noWheelClassName:A,lib:U,connectionInProgress:K});f.filter(pe),V?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function S(A,R,L){const M=Vee(A),z=f?.constrain()(M,R,L);return z&&await v(z),new Promise(H=>H(z))}async function x(A,R){const L=Vee(A);return await v(L,R),new Promise(M=>M(L))}function k(A){if(p){const R=Vee(A),L=p.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(p,R,null,{sync:!0})}}function _(){const A=p?U1t(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?cx:j8).scaleTo(qee(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?cx:j8).scaleBy(qee(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function j(A){f?.scaleExtent(A)}function T(A){f?.translateExtent(A)}function I(A){const R=!gg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:x,setViewportConstrained:S,getViewport:_,scaleTo:C,scaleBy:E,setScaleExtent:j,setTranslateExtent:T,syncViewport:k,setClickDistance:I}}var WT;(function(e){e.Line="line",e.Handle="handle"})(WT||(WT={}));function aQn({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:a}){const i=e-t,l=n-r,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function H8e(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:s}}function q0(e,t){return Math.max(0,t-e)}function H0(e,t){return Math.max(0,e-t)}function nF(e,t,n){return Math.max(0,t-e,e-n)}function W8e(e,t){return e?!t:t}function iQn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:S}=r,{x,y:k,width:_,height:C,aspectRatio:E}=e;let j=Math.floor(d?h-e.pointerX:0),T=Math.floor(f?m-e.pointerY:0);const I=_+(c?-j:j),A=C+(u?-T:T),R=-a[0]*_,L=-a[1]*C;let M=nF(I,v,y),z=nF(A,b,S);if(i){let B=0,q=0;c&&j<0?B=q0(x+j+R,i[0][0]):!c&&j>0&&(B=H0(x+I+R,i[1][0])),u&&T<0?q=q0(k+T+L,i[0][1]):!u&&T>0&&(q=H0(k+A+L,i[1][1])),M=Math.max(M,B),z=Math.max(z,q)}if(l){let B=0,q=0;c&&j>0?B=H0(x+j,l[0][0]):!c&&j<0&&(B=q0(x+I,l[1][0])),u&&T>0?q=H0(k+T,l[0][1]):!u&&T<0&&(q=q0(k+A,l[1][1])),M=Math.max(M,B),z=Math.max(z,q)}if(s){if(d){const B=nF(I/E,b,S)*E;if(M=Math.max(M,B),i){let q=0;!c&&!u||c&&!u&&p?q=H0(k+L+I/E,i[1][1])*E:q=q0(k+L+(c?j:-j)/E,i[0][1])*E,M=Math.max(M,q)}if(l){let q=0;!c&&!u||c&&!u&&p?q=q0(k+I/E,l[1][1])*E:q=H0(k+(c?j:-j)/E,l[0][1])*E,M=Math.max(M,q)}}if(f){const B=nF(A*E,v,y)/E;if(z=Math.max(z,B),i){let q=0;!c&&!u||u&&!c&&p?q=H0(x+A*E+R,i[1][0])/E:q=q0(x+(u?T:-T)*E+R,i[0][0])/E,z=Math.max(z,q)}if(l){let q=0;!c&&!u||u&&!c&&p?q=q0(x+A*E,l[1][0])/E:q=H0(x+(u?T:-T)*E,l[0][0])/E,z=Math.max(z,q)}}}T=T+(T<0?z:-z),j=j+(j<0?M:-M),s&&(p?I>A*E?T=(W8e(c,u)?-j:j)/E:j=(W8e(c,u)?-T:T)*E:d?(T=j/E,u=c):(j=T*E,c=u));const H=c?x+j:x,F=u?k+T:k;return{width:_+(c?-j:j),height:C+(u?-T:T),x:a[0]*j*(c?-1:1)+H,y:a[1]*T*(u?-1:1)+F}}const vSt={width:0,height:0,x:0,y:0},oQn={...vSt,pointerX:0,pointerY:0,aspectRatio:1};function lQn(e){return[[0,0],[e.measured.width,e.measured.height]]}function cQn(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[r-l,s-c],[r+a-l,s+i-c]]}function uQn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Sp(e);let i={controlDirection:H8e("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:p,onResizeStart:h,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...vSt},S={...oQn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:H8e(u)};let x,k=null,_=[],C,E,j,T=!1;const I=j1t().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:M,snapToGrid:z,nodeOrigin:H,paneDomNode:F}=n();if(x=R.get(t),!x)return;k=F?.getBoundingClientRect()??null;const{xSnapped:B,ySnapped:q}=pP(A.sourceEvent,{transform:L,snapGrid:M,snapToGrid:z,containerBounds:k});b={width:x.measured.width??0,height:x.measured.height??0,x:x.position.x??0,y:x.position.y??0},S={...b,pointerX:B,pointerY:q,aspectRatio:b.width/b.height},C=void 0,x.parentId&&(x.extent==="parent"||x.expandParent)&&(C=R.get(x.parentId),E=C&&x.extent==="parent"?lQn(C):void 0),_=[],j=void 0;for(const[D,G]of R)if(G.parentId===t&&(_.push({id:D,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const V=cQn(G,x,G.origin??H);j?j=[[Math.min(V[0][0],j[0][0]),Math.min(V[0][1],j[0][1])],[Math.max(V[1][0],j[1][0]),Math.max(V[1][1],j[1][1])]]:j=V}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:M,nodeOrigin:z}=n(),H=pP(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:M,containerBounds:k}),F=[];if(!x)return;const{x:B,y:q,width:D,height:G}=b,V={},$=x.origin??z,{width:U,height:Z,x:K,y:ne}=iQn(S,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,E,j),te=U!==D,J=Z!==G,ae=K!==B&&te,pe=ne!==q&&J;if(!ae&&!pe&&!te&&!J)return;if((ae||pe||$[0]===1||$[1]===1)&&(V.x=ae?K:b.x,V.y=pe?ne:b.y,b.x=V.x,b.y=V.y,_.length>0)){const de=K-B,oe=ne-q;for(const me of _)me.position={x:me.position.x-de+$[0]*(U-D),y:me.position.y-oe+$[1]*(Z-G)},F.push(me)}if((te||J)&&(V.width=te&&(!i.resizeDirection||i.resizeDirection==="horizontal")?U:b.width,V.height=J&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=V.width,b.height=V.height),C&&x.expandParent){const de=$[0]*(V.width??0);V.x&&V.x<de&&(b.x=de,S.x=S.x-(V.x-de));const oe=$[1]*(V.height??0);V.y&&V.y<oe&&(b.y=oe,S.y=S.y-(V.y-oe))}const Y=aQn({width:b.width,prevWidth:D,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),ee={...b,direction:Y};y?.(A,ee)!==!1&&(T=!0,m?.(A,ee),r(V,F))}).on("end",A=>{T&&(v?.(A,{...b}),s?.({...b}),T=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const dQn={},Z8e=e=>{let t;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const h=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(m=>m(t,h))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(dQn?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},u=t=e(r,s,c);return c},fQn=e=>e?Z8e(e):Z8e,{useDebugValue:pQn}=Le,{useSyncExternalStoreWithSelector:hQn}=IOn,mQn=e=>e;function ySt(e,t=mQn,n){const r=hQn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return pQn(r),r}const G8e=(e,t)=>{const n=fQn(e),r=(s,a=t)=>ySt(n,s,a);return Object.assign(r,n),r},gQn=(e,t)=>e?G8e(e,t):G8e;function oo(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,s]of e)if(!Object.is(s,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const OH=g.createContext(null),vQn=OH.Provider,bSt=by.error001();function Us(e,t){const n=g.useContext(OH);if(n===null)throw new Error(bSt);return ySt(n,e,t)}function jo(){const e=g.useContext(OH);if(e===null)throw new Error(bSt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const Q8e={display:"none"},yQn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},xSt="react-flow__node-desc",wSt="react-flow__edge-desc",bQn="react-flow__aria-live",xQn=e=>e.ariaLiveMessage,wQn=e=>e.ariaLabelConfig;function SQn({rfId:e}){const t=Us(xQn);return o.jsx("div",{id:`${bQn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:yQn,children:t})}function kQn({rfId:e,disableKeyboardA11y:t}){const n=Us(wQn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${xSt}-${e}`,style:Q8e,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${wSt}-${e}`,style:Q8e,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(SQn,{rfId:e})]})}const B4=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Vl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});B4.displayName="Panel";function OQn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(B4,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:o.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const _Qn=e=>{const t=[],n=[];for(const[,r]of e.nodeLookup)r.selected&&t.push(r.internals.userNode);for(const[,r]of e.edgeLookup)r.selected&&n.push(r);return{selectedNodes:t,selectedEdges:n}},rF=e=>e.id;function CQn(e,t){return oo(e.selectedNodes.map(rF),t.selectedNodes.map(rF))&&oo(e.selectedEdges.map(rF),t.selectedEdges.map(rF))}function EQn({onSelectionChange:e}){const t=jo(),{selectedNodes:n,selectedEdges:r}=Us(_Qn,CQn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const jQn=e=>!!e.onSelectionChangeHandlers;function TQn({onSelectionChange:e}){const t=Us(jQn);return e||t?o.jsx(EQn,{onSelectionChange:e}):null}const Wme=typeof window<"u"?g.useLayoutEffect:g.useEffect,SSt=[0,0],NQn={x:0,y:0,zoom:1},IQn=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode"],Y8e=[...IQn,"rfId"],AQn=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),K8e={translateExtent:CM,nodeOrigin:SSt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function RQn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Us(AQn,oo),u=jo();Wme(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=K8e,l()}),[]);const d=g.useRef(K8e);return Wme(()=>{for(const f of Y8e){const p=e[f],h=d.current[f];p!==h&&(typeof e[f]>"u"||(f==="nodes"?t(p):f==="edges"?n(p):f==="minZoom"?r(p):f==="maxZoom"?s(p):f==="translateExtent"?a(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:SGn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},Y8e.map(f=>e[f])),null}function X8e(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function PQn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=X8e(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:X8e()?.matches?"dark":"light"}const J8e=typeof document<"u"?document:null;function IM(e=null,t={target:J8e,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
|
|
337
|
+
`:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new PUn(this):new IUn(this)}getCursor(t,n=0,r){let s=t.doc?t:cs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?qE(this,s,n,r):VE(this,s,n,r)}}class Kwt{constructor(t){this.spec=t}}function TUn(e,t,n){return(r,s,a,i)=>{if(n&&!n(r,s,a,i))return!1;let l=r>=i&&s<=i+a.length?a.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function VE(e,t,n,r){let s;return e.wholeWord&&(s=NUn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=TUn(e.test,t,s)),new jx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function NUn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(iB(s,n-a))!=So.Word||t(oB(s,n-a))!=So.Word)&&(t(oB(s,r-a))!=So.Word||t(iB(s,r-a))!=So.Word))}class IUn extends Kwt{constructor(t){super(t)}nextMatch(t,n,r){let s=VE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=VE(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),i=VE(this.spec,t,a,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=VE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=VE(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function AUn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function qE(e,t,n,r){let s;return e.wholeWord&&(s=RUn(t.charCategorizer(t.selection.main.head))),e.test&&(s=AUn(e.test,t,s)),new Gwt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function iB(e,t){return e.slice(Oc(e,t,!1),t)}function oB(e,t){return e.slice(t,Oc(e,t))}function RUn(e){return(t,n,r)=>!r[0].length||(e(iB(r.input,r.index))!=So.Word||e(oB(r.input,r.index))!=So.Word)&&(e(oB(r.input,r.index+r[0].length))!=So.Word||e(iB(r.input,r.index+r[0].length))!=So.Word)}class PUn extends Kwt{nextMatch(t,n,r){let s=qE(this.spec,t,r,t.doc.length).next();return s.done&&(s=qE(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=qE(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=qE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=qE(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const bM=vr.define(),kSe=vr.define(),Fw=Sl.define({create(e){return new zJ(Ime(e).create(),null)},update(e,t){for(let n of t.effects)n.is(bM)?e=new zJ(n.value.create(),e.panel):n.is(kSe)&&(e=new zJ(e.query,n.value?OSe:null));return e},provide:e=>cM.from(e,t=>t.panel)});class zJ{constructor(t,n){this.query=t,this.panel=n}}const $Un=jn.mark({class:"cm-searchMatch"}),MUn=jn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),DUn=Co.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Fw))}update(e){let t=e.state.field(Fw);(t!=e.startState.field(Fw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return jn.none;let{view:n}=this,r=new Rd;for(let s=0,a=n.visibleRanges,i=a.length;s<i;s++){let{from:l,to:c}=a[s];for(;s<i-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(p=>p.from==u&&p.to==d);r.add(u,d,f?MUn:$Un)})}return r.finish()}},{decorations:e=>e.decorations});function P4(e){return t=>{let n=t.state.field(Fw,!1);return n&&n.query.spec.valid?e(t,n):e1t(t)}}const lB=P4((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=gt.single(r.from,r.to),a=e.state.facet(uI);return e.dispatch({selection:s,effects:[_Se(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),Jwt(e),!0}),cB=P4((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=gt.single(s.from,s.to),i=e.state.facet(uI);return e.dispatch({selection:a,effects:[_Se(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),Jwt(e),!0}),LUn=P4((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:gt.create(n.map(r=>gt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),FUn=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],i=0;for(let l=new jx(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(gt.range(l.value.from,l.value.to))}return t(e.update({selection:gt.create(a,i),userEvent:"select.search.matches"})),!0},ize=P4((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let i=a,l=[],c,u,d=[];i.precise?i.from==r&&i.to==s&&(u=n.toText(t.getReplacement(i)),l.push({from:i.from,to:i.to,insert:u}),i=t.nextMatch(n,i.from,i.to),d.push(Nt.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=gt.single(i.from,i.to).map(f),d.push(_Se(e,i)),d.push(n.facet(uI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),zUn=P4((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Nt.announce.of(r),userEvent:"input.replace.all"}),!0});function OSe(e){return e.state.facet(uI).createPanel(e)}function Ime(e,t){var n,r,s,a,i;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let u=e.facet(uI);return new Ywt({search:((n=t?.literal)!==null&&n!==void 0?n:u.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t?.caseSensitive)!==null&&r!==void 0?r:u.caseSensitive,literal:(s=t?.literal)!==null&&s!==void 0?s:u.literal,regexp:(a=t?.regexp)!==null&&a!==void 0?a:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function Xwt(e){let t=z1e(e,OSe);return t&&t.dom.querySelector("[main-field]")}function Jwt(e){let t=Xwt(e);t&&t==e.root.activeElement&&t.select()}const e1t=e=>{let t=e.state.field(Fw,!1);if(t&&t.panel){let n=Xwt(e);if(n&&n!=e.root.activeElement){let r=Ime(e.state,t.query.spec);r.valid&&e.dispatch({effects:bM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[kSe.of(!0),t?bM.of(Ime(e.state,t.query.spec)):vr.appendConfig.of(qUn)]});return!0},t1t=e=>{let t=e.state.field(Fw,!1);if(!t||!t.panel)return!1;let n=z1e(e,OSe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:kSe.of(!1)}),!0},BUn=[{key:"Mod-f",run:e1t,scope:"editor search-panel"},{key:"F3",run:lB,shift:cB,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:lB,shift:cB,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:t1t,scope:"editor search-panel"},{key:"Mod-Shift-l",run:FUn},{key:"Mod-Alt-g",run:vUn},{key:"Mod-d",run:jUn,preventDefault:!0}];class UUn{constructor(t){this.view=t;let n=this.query=t.state.field(Fw).query.spec;this.commit=this.commit.bind(this),this.searchField=ui("input",{value:n.search,placeholder:np(t,"Find"),"aria-label":np(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=ui("input",{value:n.replace,placeholder:np(t,"Replace"),"aria-label":np(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=ui("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=ui("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=ui("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return ui("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=ui("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>lB(t),[np(t,"next")]),r("prev",()=>cB(t),[np(t,"previous")]),r("select",()=>LUn(t),[np(t,"all")]),ui("label",null,[this.caseField,np(t,"match case")]),ui("label",null,[this.reField,np(t,"regexp")]),ui("label",null,[this.wordField,np(t,"by word")]),...t.state.readOnly?[]:[ui("br"),this.replaceField,r("replace",()=>ize(t),[np(t,"replace")]),r("replaceAll",()=>zUn(t),[np(t,"replace all")])],ui("button",{name:"close",onclick:()=>t1t(t),"aria-label":np(t,"close"),type:"button"},["×"])])}commit(){let t=new Ywt({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});t.eq(this.query)||(this.query=t,this.view.dispatch({effects:bM.of(t)}))}keydown(t){l6n(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?cB:lB)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),ize(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(bM)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(t){this.query=t,this.searchField.value=t.search,this.replaceField.value=t.replace,this.caseField.checked=t.caseSensitive,this.reField.checked=t.regexp,this.wordField.checked=t.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(uI).top}}function np(e,t){return e.state.phrase(t)}const Z6=30,G6=/[\s\.,:;?!]/;function _Se(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-Z6),i=Math.min(s,n+Z6),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<Z6;c++)if(!G6.test(l[c+1])&&G6.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-Z6;c--)if(!G6.test(l[c-1])&&G6.test(l[c])){l=l.slice(0,c);break}}return Nt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const VUn=Nt.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),qUn=[Fw,Xp.low(DUn),VUn];class oze{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class wk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(xM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Rd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==p&&(v.to>v.from||v.to==p))l.push(v),d++,h=Math.min(v.to,h);else{h=Math.min(v.from,h);break}}let m=rVn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(p,p,jn.widget({widget:new JUn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,jn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new wk(u,n,FT(u))}}function FT(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new oze(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new oze(r.from,a,r.diagnostic)}}),r}function HUn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(xM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(n1t))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function WUn(e,t){return e.field(Cp,!1)?t:t.concat(vr.appendConfig.of(sVn))}const n1t=vr.define(),CSe=vr.define(),r1t=vr.define(),Cp=Sl.define({create(){return new wk(jn.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=FT(n,e.selected.diagnostic,a)||FT(n,null,a)}!n.size&&s&&t.state.facet(xM).autoPanel&&(s=null),e=new wk(n,s,r)}for(let n of t.effects)if(n.is(n1t)){let r=t.state.facet(xM).autoPanel?n.value.length?wM.open:null:e.panel;e=wk.init(n.value,r,t.state)}else n.is(CSe)?e=new wk(e.diagnostics,n.value?wM.open:null,e.selected):n.is(r1t)&&(e=new wk(e.diagnostics,e.panel,n.value));return e},provide:e=>[cM.from(e,t=>t.panel),Nt.decorations.from(e,t=>t.diagnostics)]}),ZUn=jn.mark({class:"cm-lintRange cm-lintRange-active"});function GUn(e,t,n){let{diagnostics:r}=e.state.field(Cp),s,a=-1,i=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,u,{spec:d})=>{if(t>=c&&t<=u&&(c==u||(t>c||n>0)&&(t<u||n<0)))return s=d.diagnostics,a=c,i=u,!1});let l=e.state.facet(xM).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:i,above:e.state.doc.lineAt(a).to<i,create(){return{dom:QUn(e,s)}}}:null}function QUn(e,t){return ui("ul",{class:"cm-tooltip-lint"},t.map(n=>a1t(e,n,!1)))}const YUn=e=>{let t=e.state.field(Cp,!1);(!t||!t.panel)&&e.dispatch({effects:WUn(e.state,[CSe.of(!0)])});let n=z1e(e,wM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},lze=e=>{let t=e.state.field(Cp,!1);return!t||!t.panel?!1:(e.dispatch({effects:CSe.of(!1)}),!0)},KUn=e=>{let t=e.state.field(Cp,!1);if(!t)return!1;let n=e.state.selection.main,r=t.diagnostics.iter(n.to+1);return!r.value&&(r=t.diagnostics.iter(0),!r.value||r.from==n.from&&r.to==n.to)?!1:(e.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0}),!0)},XUn=[{key:"Mod-Shift-m",run:YUn,preventDefault:!0},{key:"F8",run:KUn}],xM=On.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Fy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:cze,tooltipFilter:cze,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function cze(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function s1t(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function a1t(e,t,n){var r;let s=n?s1t(t.actions):[];return ui("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},ui("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,i)=>{let l=!1,c=h=>{if(h.preventDefault(),l)return;l=!0;let m=FT(e.state.field(Cp).diagnostics,t);m&&a.apply(e,m.from,m.to)},{name:u}=a,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),ui("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return ui("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&ui("div",{class:"cm-diagnosticSource"},t.source))}class JUn extends Jp{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return ui("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class uze{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=a1t(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class wM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)lze(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],i=s1t(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=FT(this.view.state.field(Cp).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=ui("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=ui("div",{class:"cm-panel-lint"},this.list,ui("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>lze(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Cp).selected;if(!t)return-1;for(let n=0;n<this.items.length;n++)if(this.items[n].diagnostic==t.diagnostic)return n;return-1}update(){let{diagnostics:t,selected:n}=this.view.state.field(Cp),r=0,s=!1,a=null,i=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(i.has(d))continue;i.add(d);let f=-1,p;for(let h=r;h<this.items.length;h++)if(this.items[h].diagnostic==d){f=h;break}f<0?(p=new uze(this.view,d),this.items.splice(r,0,p),s=!0):(p=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&p.diagnostic==n.diagnostic?p.dom.hasAttribute("aria-selected")||(p.dom.setAttribute("aria-selected","true"),a=p):p.dom.hasAttribute("aria-selected")&&p.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new uze(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let u=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/u:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/u)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Cp),r=FT(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:r1t.of(r)})}static open(t){return new wM(t)}}function eVn(e,t='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${t}>${encodeURIComponent(e)}</svg>')`}function Q6(e){return eVn(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${e}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const tVn=Nt.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:Q6("#d11")},".cm-lintRange-warning":{backgroundImage:Q6("orange")},".cm-lintRange-info":{backgroundImage:Q6("#999")},".cm-lintRange-hint":{backgroundImage:Q6("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});function nVn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function rVn(e){let t="hint",n=1;for(let r of e){let s=nVn(r.severity);s>n&&(n=s,t=r.severity)}return t}const sVn=[Cp,Nt.decorations.compute([Cp],e=>{let{selected:t,panel:n}=e.field(Cp);return!t||!n||t.from==t.to?jn.none:jn.set([ZUn.range(t.from,t.to)])}),Y6n(GUn,{hideOn:HUn}),tVn];var dze=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,a=[];t.closeBracketsKeymap!==!1&&(a=a.concat(Zzn)),t.defaultKeymap!==!1&&(a=a.concat(hUn)),t.searchKeymap!==!1&&(a=a.concat(BUn)),t.historyKeymap!==!1&&(a=a.concat(wBn)),t.foldKeymap!==!1&&(a=a.concat(AFn)),t.completionKeymap!==!1&&(a=a.concat(Jxt)),t.lintKeymap!==!1&&(a=a.concat(XUn));var i=[];return t.lineNumbers!==!1&&i.push(lFn()),t.highlightActiveLineGutter!==!1&&i.push(dFn()),t.highlightSpecialChars!==!1&&i.push(O6n()),t.history!==!1&&i.push(fBn()),t.foldGutter!==!1&&i.push(MFn()),t.drawSelection!==!1&&i.push(h6n()),t.dropCursor!==!1&&i.push(b6n()),t.allowMultipleSelections!==!1&&i.push(cs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(OFn()),t.syntaxHighlighting!==!1&&i.push(H1(zFn,{fallback:!0})),t.bracketMatching!==!1&&i.push(ZFn()),t.closeBrackets!==!1&&i.push(Vzn()),t.autocompletion!==!1&&i.push(Xxt()),t.rectangularSelection!==!1&&i.push(L6n()),s!==!1&&i.push(B6n()),t.highlightActiveLine!==!1&&i.push(N6n()),t.highlightSelectionMatches!==!1&&i.push(xUn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(iI.of(" ".repeat(t.tabSize))),i.concat([aI.of(a.flat())]).filter(Boolean)};const aVn="#e5c07b",fze="#e06c75",iVn="#56b6c2",oVn="#ffffff",C8="#abb2bf",Ame="#7d8799",lVn="#61afef",cVn="#98c379",pze="#d19a66",uVn="#c678dd",dVn="#21252b",hze="#2c313a",mze="#282c34",BJ="#353a42",fVn="#3E4451",gze="#528bff",pVn=Nt.theme({"&":{color:C8,backgroundColor:mze},".cm-content":{caretColor:gze},".cm-cursor, .cm-dropCursor":{borderLeftColor:gze},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:fVn},".cm-panels":{backgroundColor:dVn,color:C8},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#6699ff0b"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847"},".cm-gutters":{backgroundColor:mze,color:Ame,border:"none"},".cm-activeLineGutter":{backgroundColor:hze},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:BJ},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:BJ,borderBottomColor:BJ},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:hze,color:C8}}},{dark:!0}),hVn=Ug.define([{tag:fe.keyword,color:uVn},{tag:[fe.name,fe.deleted,fe.character,fe.propertyName,fe.macroName],color:fze},{tag:[fe.function(fe.variableName),fe.labelName],color:lVn},{tag:[fe.color,fe.constant(fe.name),fe.standard(fe.name)],color:pze},{tag:[fe.definition(fe.name),fe.separator],color:C8},{tag:[fe.typeName,fe.className,fe.number,fe.changed,fe.annotation,fe.modifier,fe.self,fe.namespace],color:aVn},{tag:[fe.operator,fe.operatorKeyword,fe.url,fe.escape,fe.regexp,fe.link,fe.special(fe.string)],color:iVn},{tag:[fe.meta,fe.comment],color:Ame},{tag:fe.strong,fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.link,color:Ame,textDecoration:"underline"},{tag:fe.heading,fontWeight:"bold",color:fze},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:pze},{tag:[fe.processingInstruction,fe.string,fe.inserted],color:cVn},{tag:fe.invalid,color:oVn}]),mVn=[pVn,H1(hVn)];var gVn=Nt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),vVn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,v=[];switch(s&&v.unshift(aI.of([mUn])),m&&(typeof m=="boolean"?v.unshift(dze()):v.unshift(dze(m))),p&&v.unshift(P6n(p)),d){case"light":v.push(gVn);break;case"dark":v.push(mVn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(Nt.editable.of(!1)),c&&v.push(cs.readOnly.of(!0)),[...v]},yVn=e=>({line:e.state.doc.lineAt(e.state.selection.main.from),lineCount:e.state.doc.lines,lineBreak:e.state.lineBreak,length:e.state.doc.length,readOnly:e.state.readOnly,tabSize:e.state.tabSize,selection:e.state.selection,selectionAsSingle:e.state.selection.asSingle().main,ranges:e.state.selection.ranges,selectionCode:e.state.sliceDoc(e.state.selection.main.from,e.state.selection.main.to),selections:e.state.selection.ranges.map(t=>e.state.sliceDoc(t.from,t.to)),selectedText:e.state.selection.ranges.some(t=>!t.empty)});class bVn{constructor(t,n){this.timeLeftMS=void 0,this.timeoutMS=void 0,this.isCancelled=!1,this.isTimeExhausted=!1,this.callbacks=[],this.timeLeftMS=n,this.timeoutMS=n,this.callbacks.push(t)}tick(){if(!this.isCancelled&&!this.isTimeExhausted&&(this.timeLeftMS--,this.timeLeftMS<=0)){this.isTimeExhausted=!0;var t=this.callbacks.slice();this.callbacks.length=0,t.forEach(n=>{try{n()}catch(r){console.error("TimeoutLatch callback error:",r)}})}}cancel(){this.isCancelled=!0,this.callbacks.length=0}reset(){this.timeLeftMS=this.timeoutMS,this.isCancelled=!1,this.isTimeExhausted=!1}get isDone(){return this.isCancelled||this.isTimeExhausted}}class vze{constructor(){this.interval=null,this.latches=new Set}add(t){this.latches.add(t),this.start()}remove(t){this.latches.delete(t),this.latches.size===0&&this.stop()}start(){this.interval===null&&(this.interval=setInterval(()=>{this.latches.forEach(t=>{t.tick(),t.isDone&&this.remove(t)})},1))}stop(){this.interval!==null&&(clearInterval(this.interval),this.interval=null)}}var UJ=null,xVn=()=>typeof window>"u"?new vze:(UJ||(UJ=new vze),UJ),wVn=Nt.theme({"& .cm-scroller":{height:"100% !important"}}),yze=null,VJ=null;function SVn(e,t,n,r,s,a){if(!e&&!t&&!n&&!r&&!s&&!a)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a});return i===yze||(yze=i,VJ=Nt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),VJ}var bze=Ly.define(),kVn=200,OVn=[];function _Vn(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,a=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?OVn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,S=e.width,x=S===void 0?null:S,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,E=C===void 0?null:C,j=e.placeholder,T=j===void 0?"":j,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,M=e.indentWithTab,z=M===void 0?!0:M,H=e.basicSetup,F=H===void 0?!0:H,B=e.root,q=e.initialState,D=g.useState(),G=D[0],V=D[1],$=g.useState(),U=$[0],Z=$[1],K=g.useState(),ne=K[0],te=K[1],J=g.useState(()=>({current:null}))[0],ae=g.useState(()=>({current:null}))[0],pe=SVn(h,v,b,x,_,E),Y=Nt.updateListener.of(de=>{if(de.docChanged&&typeof r=="function"&&!de.transactions.some(be=>be.annotation(bze))){J.current?J.current.reset():(J.current=new bVn(()=>{if(ae.current){var be=ae.current;ae.current=null,be()}J.current=null},kVn),xVn().add(J.current));var oe=de.state.doc,me=oe.toString();r(me,de)}s&&s(yVn(de))}),ee=vVn({theme:f,editable:A,readOnly:L,placeholder:T,indentWithTab:z,basicSetup:F}),ce=[Y,...pe?[pe]:[],wVn,...ee];return i&&typeof i=="function"&&ce.push(Nt.updateListener.of(i)),ce=ce.concat(c),g.useLayoutEffect(()=>{if(G&&!ne){var de={doc:t,selection:n,extensions:ce},oe=q?cs.fromJSON(q.json,de,q.fields):cs.create(de);if(te(oe),!U){var me=new Nt({state:oe,parent:G,root:B});Z(me),a&&a(me,oe)}}return()=>{U&&(te(void 0),Z(void 0))}},[G,ne]),g.useEffect(()=>{e.container&&V(e.container)},[e.container]),g.useEffect(()=>()=>{U&&(U.destroy(),Z(void 0)),J.current&&(J.current.cancel(),J.current=null)},[U]),g.useEffect(()=>{u&&U&&U.focus()},[u,U]),g.useEffect(()=>{U&&U.dispatch({effects:vr.reconfigure.of(ce)})},[f,c,h,v,b,x,_,E,T,A,L,z,F,r,i]),g.useEffect(()=>{if(t!==void 0){var de=U?U.state.doc.toString():"";if(U&&t!==de){var oe=J.current&&!J.current.isDone,me=()=>{U&&t!==U.state.doc.toString()&&U.dispatch({changes:{from:0,to:U.state.doc.toString().length,insert:t||""},annotations:[bze.of(!0)]})};oe?ae.current=me:me()}}},[t,U]),{state:ne,setState:te,view:U,setView:Z,container:G,setContainer:V}}var CVn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],Gu=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,v=e.height,y=e.minHeight,b=e.maxHeight,S=e.width,x=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,E=e.indentWithTab,j=e.editable,T=e.readOnly,I=e.root,A=e.initialState,R=pwt(e,CVn),L=g.useRef(null),M=_Vn({root:I,value:s,autoFocus:p,theme:m,height:v,minHeight:y,maxHeight:b,width:S,minWidth:x,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:E,editable:j,readOnly:T,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),z=M.state,H=M.view,F=M.container,B=M.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:z,view:H}),[L,F,z,H]);var q=g.useCallback(G=>{L.current=G,B(G)},[B]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var D=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",HO({ref:q,className:""+D+(n?" "+n:"")},R))});Gu.displayName="CodeMirror";const EVn={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash"};let qJ=null;function jVn(){return qJ||(qJ=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([go(()=>import("./core-DHSn7H8K.js"),__vite__mapDeps([0,1,2]),import.meta.url),go(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[go(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),go(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[go(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),go(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),go(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),go(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),go(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),go(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),go(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),go(()=>import("./python-DhUJRlN_.js"),[],import.meta.url)],engine:t()})})()),qJ}async function TVn(e,t){const n=EVn[t?.toLowerCase()];if(!n)return null;const r=await jVn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function NVn(e){return new BO(H1e.define(e))}const i1t=[ng.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return go(()=>Promise.resolve().then(()=>H6),void 0,import.meta.url).then(e=>e.javascript())}}),ng.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return go(()=>Promise.resolve().then(()=>azn),void 0,import.meta.url).then(e=>e.json())}}),ng.of({name:"JSX",extensions:["jsx"],load(){return go(()=>Promise.resolve().then(()=>H6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),ng.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return go(()=>Promise.resolve().then(()=>J7n),void 0,import.meta.url).then(e=>e.markdown())}}),ng.of({name:"TSX",extensions:["tsx"],load(){return go(()=>Promise.resolve().then(()=>H6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),ng.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return go(()=>Promise.resolve().then(()=>H6),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),ng.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return go(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>NVn(e.shell))}})];function IVn(e,t=5){if(!e?.properties)return[];const n=[];function r(s,a,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:a,label:a,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${a}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${a}[].${c}`,i+1)}for(const[s,a]of Object.entries(e.properties))r(a,s,1);return n}function AVn(e){const t=IVn(e);return Xxt({override:[RVn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function RVn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,p)=>{const v=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const PVn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,$Vn=jn.mark({class:"cm-variable-highlight"}),xze=new fxt({regexp:PVn,decoration:()=>$Vn}),MVn=Co.fromClass(class{decorations;constructor(e){this.decorations=xze.createDeco(e)}update(e){this.decorations=xze.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),DVn=MVn;function LVn(){const e=lI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[fe.className,fe.propertyName],color:"var(--neutral6)"},{tag:fe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.heading1,fe.heading2,fe.heading3,fe.heading4,fe.heading5,fe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:fe.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:fe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:fe.url,color:"var(--accent3)"},{tag:fe.monospace,color:"var(--neutral6)"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=Nt.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function FVn(){const e=Nt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=Ug.define([{tag:[fe.comment,fe.bracket],color:"var(--neutral2)"},{tag:[fe.string,fe.meta,fe.regexp],color:"var(--accent1)"},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:"var(--accent6)"},{tag:[fe.keyword,fe.operator,fe.tagName],color:"var(--accent2)"},{tag:[fe.function(fe.propertyName),fe.propertyName],color:"var(--accent5)"},{tag:[fe.definition(fe.variableName),fe.function(fe.variableName),fe.className,fe.attributeName],color:"var(--accent3)"},{tag:[fe.variableName,fe.number],color:"var(--accent5)"},{tag:[fe.name,fe.quote],color:"var(--accent1)"},{tag:fe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.heading1,fe.heading2,fe.heading3,fe.heading4,fe.heading5,fe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[fe.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:fe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:fe.url,color:"var(--accent3)"},{tag:fe.monospace,color:"var(--neutral6)"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:[fe.deleted],color:"var(--accent2)"},{tag:fe.invalid,color:"var(--error)"},{tag:[fe.standard(fe.tagName)],color:"var(--accent1)"}]);return[e,H1(t)]}const Kx=()=>{const e=q_().resolvedTheme==="dark";return g.useMemo(()=>e?LVn():FVn(),[e])},zVn=uo(X("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","duration-normal transition-colors ease-out-custom"),{variants:{variant:{default:"rounded-md border border-border1 bg-surface3 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),BVn=Xp.highest(Nt.editorAttributes.of({style:"outline: none"})),UVn=Xp.highest(Nt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),VVn=[BVn,UVn],Wr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,...m},v)=>{const y=Kx(),b=e?JSON.stringify(e,null,2):t??"",S=g.useMemo(()=>{const x=[...VVn];return f&&x.push(Nt.lineWrapping),a==="json"?x.push(Rp):a==="markdown"&&x.push(ySe({base:qO,codeLanguages:i1t})),i&&a==="markdown"&&x.push(DVn),c&&a==="markdown"&&x.push(AVn(c)),p===!1&&x.push(cs.readOnly.of(!0)),x},[a,i,c,p,f]);return o.jsxs("div",{className:X(zVn({variant:h}),s),...m,children:[r&&o.jsx($a,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(Gu,{ref:v,value:b,theme:y,extensions:S,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),qVn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},HVn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=Kx(),{settings:r,setSettings:s}=Uq(),a=r?.tracingOptions,i=g.useMemo(()=>qVn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=p=>{u.current=!0,c(p)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const p=JSON.parse(l);typeof p=="object"&&p!==null&&s({...r,tracingOptions:p})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(Gu,{value:l,onChange:d,theme:n,extensions:[Rp],className:X("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(le,{type:"button",onClick:f,children:"Save"})})]})},WVn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(qe,{children:o.jsx(tq,{})})})}),o.jsx($n,{children:"Run Options"})]}),o.jsx(br,{open:e,onOpenChange:t,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Run Options"}),o.jsx(Ks,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx($r,{children:o.jsx(HVn,{onSaved:()=>t(!1)})})]})})]})};function ZVn({status:e}){switch(e){case"running":return o.jsx(Kt,{});case"failed":return o.jsx(bs,{className:"text-accent2"});case"canceled":return o.jsx(If,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(hT,{className:"text-neutral3"});case"suspended":return o.jsx(YV,{className:"text-accent3"});case"success":return o.jsx(pa,{className:"text-accent1"});default:return o.jsx(hT,{className:"text-neutral3"})}}function o1t({status:e}){return o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx(qe,{"aria-label":e,className:"shrink-0",children:o.jsx(ZVn,{status:e})})}),o.jsx($n,{children:e})]})}var HJ,wze;function ESe(){if(wze)return HJ;wze=1;var e="\0",t="\0",n="";class r{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(d){d&&(this._isDirected=Object.hasOwn(d,"directed")?d.directed:!0,this._isMultigraph=Object.hasOwn(d,"multigraph")?d.multigraph:!1,this._isCompound=Object.hasOwn(d,"compound")?d.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(d){return this._label=d,this}graph(){return this._label}setDefaultNodeLabel(d){return this._defaultNodeLabelFn=d,typeof d!="function"&&(this._defaultNodeLabelFn=()=>d),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var d=this;return this.nodes().filter(f=>Object.keys(d._in[f]).length===0)}sinks(){var d=this;return this.nodes().filter(f=>Object.keys(d._out[f]).length===0)}setNodes(d,f){var p=arguments,h=this;return d.forEach(function(m){p.length>1?h.setNode(m,f):h.setNode(m)}),this}setNode(d,f){return Object.hasOwn(this._nodes,d)?(arguments.length>1&&(this._nodes[d]=f),this):(this._nodes[d]=arguments.length>1?f:this._defaultNodeLabelFn(d),this._isCompound&&(this._parent[d]=t,this._children[d]={},this._children[t][d]=!0),this._in[d]={},this._preds[d]={},this._out[d]={},this._sucs[d]={},++this._nodeCount,this)}node(d){return this._nodes[d]}hasNode(d){return Object.hasOwn(this._nodes,d)}removeNode(d){var f=this;if(Object.hasOwn(this._nodes,d)){var p=h=>f.removeEdge(f._edgeObjs[h]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(h){f.setParent(h)}),delete this._children[d]),Object.keys(this._in[d]).forEach(p),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(p),delete this._out[d],delete this._sucs[d],--this._nodeCount}return this}setParent(d,f){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(f===void 0)f=t;else{f+="";for(var p=f;p!==void 0;p=this.parent(p))if(p===d)throw new Error("Setting "+f+" as parent of "+d+" would create a cycle");this.setNode(f)}return this.setNode(d),this._removeFromParentsChildList(d),this._parent[d]=f,this._children[f][d]=!0,this}_removeFromParentsChildList(d){delete this._children[this._parent[d]][d]}parent(d){if(this._isCompound){var f=this._parent[d];if(f!==t)return f}}children(d=t){if(this._isCompound){var f=this._children[d];if(f)return Object.keys(f)}else{if(d===t)return this.nodes();if(this.hasNode(d))return[]}}predecessors(d){var f=this._preds[d];if(f)return Object.keys(f)}successors(d){var f=this._sucs[d];if(f)return Object.keys(f)}neighbors(d){var f=this.predecessors(d);if(f){const h=new Set(f);for(var p of this.successors(d))h.add(p);return Array.from(h.values())}}isLeaf(d){var f;return this.isDirected()?f=this.successors(d):f=this.neighbors(d),f.length===0}filterNodes(d){var f=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});f.setGraph(this.graph());var p=this;Object.entries(this._nodes).forEach(function([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,p.edge(v))});var h={};function m(v){var y=p.parent(v);return y===void 0||f.hasNode(y)?(h[v]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var p=this,h=arguments;return d.reduce(function(m,v){return h.length>1?p.setEdge(m,v,f):p.setEdge(m,v),v}),this}setEdge(){var d,f,p,h,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,p=v.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=v,f=arguments[1],p=arguments[3],arguments.length>2&&(h=arguments[2],m=!0)),d=""+d,f=""+f,p!==void 0&&(p=""+p);var y=i(this._isDirected,d,f,p);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=h),this;if(p!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(d),this.setNode(f),this._edgeLabels[y]=m?h:this._defaultEdgeLabelFn(d,f,p);var b=l(this._isDirected,d,f,p);return d=b.v,f=b.w,Object.freeze(b),this._edgeObjs[y]=b,s(this._preds[f],d),s(this._sucs[d],f),this._in[f][y]=b,this._out[d][y]=b,this._edgeCount++,this}edge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return this._edgeLabels[h]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return Object.hasOwn(this._edgeLabels,h)}removeEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p),m=this._edgeObjs[h];return m&&(d=m.v,f=m.w,delete this._edgeLabels[h],delete this._edgeObjs[h],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][h],delete this._out[d][h],this._edgeCount--),this}inEdges(d,f){var p=this._in[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.v===f):h}}outEdges(d,f){var p=this._out[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.w===f):h}}nodeEdges(d,f){var p=this.inEdges(d,f);if(p)return p.concat(this.outEdges(d,f))}}function s(u,d){u[d]?u[d]++:u[d]=1}function a(u,d){--u[d]||delete u[d]}function i(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}return h+n+m+n+(p===void 0?e:p)}function l(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}var y={v:h,w:m};return p&&(y.name=p),y}function c(u,d){return i(u,d.v,d.w,d.name)}return HJ=r,HJ}var WJ,Sze;function GVn(){return Sze||(Sze=1,WJ="2.2.4"),WJ}var ZJ,kze;function QVn(){return kze||(kze=1,ZJ={Graph:ESe(),version:GVn()}),ZJ}var GJ,Oze;function YVn(){if(Oze)return GJ;Oze=1;var e=ESe();GJ={write:t,read:s};function t(a){var i={options:{directed:a.isDirected(),multigraph:a.isMultigraph(),compound:a.isCompound()},nodes:n(a),edges:r(a)};return a.graph()!==void 0&&(i.value=structuredClone(a.graph())),i}function n(a){return a.nodes().map(function(i){var l=a.node(i),c=a.parent(i),u={v:i};return l!==void 0&&(u.value=l),c!==void 0&&(u.parent=c),u})}function r(a){return a.edges().map(function(i){var l=a.edge(i),c={v:i.v,w:i.w};return i.name!==void 0&&(c.name=i.name),l!==void 0&&(c.value=l),c})}function s(a){var i=new e(a.options).setGraph(a.value);return a.nodes.forEach(function(l){i.setNode(l.v,l.value),l.parent&&i.setParent(l.v,l.parent)}),a.edges.forEach(function(l){i.setEdge({v:l.v,w:l.w,name:l.name},l.value)}),i}return GJ}var QJ,_ze;function KVn(){if(_ze)return QJ;_ze=1,QJ=e;function e(t){var n={},r=[],s;function a(i){Object.hasOwn(n,i)||(n[i]=!0,s.push(i),t.successors(i).forEach(a),t.predecessors(i).forEach(a))}return t.nodes().forEach(function(i){s=[],a(i),s.length&&r.push(s)}),r}return QJ}var YJ,Cze;function l1t(){if(Cze)return YJ;Cze=1;class e{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(n){return n.key})}has(n){return Object.hasOwn(this._keyIndices,n)}priority(n){var r=this._keyIndices[n];if(r!==void 0)return this._arr[r].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(n,r){var s=this._keyIndices;if(n=String(n),!Object.hasOwn(s,n)){var a=this._arr,i=a.length;return s[n]=i,a.push({key:n,priority:r}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var n=this._arr.pop();return delete this._keyIndices[n.key],this._heapify(0),n.key}decrease(n,r){var s=this._keyIndices[n];if(r>this._arr[s].priority)throw new Error("New priority is greater than current priority. Key: "+n+" Old: "+this._arr[s].priority+" New: "+r);this._arr[s].priority=r,this._decrease(s)}_heapify(n){var r=this._arr,s=2*n,a=s+1,i=n;s<r.length&&(i=r[s].priority<r[i].priority?s:i,a<r.length&&(i=r[a].priority<r[i].priority?a:i),i!==n&&(this._swap(n,i),this._heapify(i)))}_decrease(n){for(var r=this._arr,s=r[n].priority,a;n!==0&&(a=n>>1,!(r[a].priority<s));)this._swap(n,a),n=a}_swap(n,r){var s=this._arr,a=this._keyIndices,i=s[n],l=s[r];s[n]=l,s[r]=i,a[l.key]=n,a[i.key]=r}}return YJ=e,YJ}var KJ,Eze;function c1t(){if(Eze)return KJ;Eze=1;var e=l1t();KJ=n;var t=()=>1;function n(s,a,i,l){return r(s,String(a),i||t,l||function(c){return s.outEdges(c)})}function r(s,a,i,l){var c={},u=new e,d,f,p=function(h){var m=h.v!==d?h.v:h.w,v=c[m],y=i(h),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+h+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(h){var m=h===a?0:Number.POSITIVE_INFINITY;c[h]={distance:m},u.add(h,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(p);return c}return KJ}var XJ,jze;function XVn(){if(jze)return XJ;jze=1;var e=c1t();XJ=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return XJ}var JJ,Tze;function u1t(){if(Tze)return JJ;Tze=1,JJ=e;function e(t){var n=0,r=[],s={},a=[];function i(l){var c=s[l]={onStack:!0,lowlink:n,index:n++};if(r.push(l),t.successors(l).forEach(function(f){Object.hasOwn(s,f)?s[f].onStack&&(c.lowlink=Math.min(c.lowlink,s[f].index)):(i(f),c.lowlink=Math.min(c.lowlink,s[f].lowlink))}),c.lowlink===c.index){var u=[],d;do d=r.pop(),s[d].onStack=!1,u.push(d);while(l!==d);a.push(u)}}return t.nodes().forEach(function(l){Object.hasOwn(s,l)||i(l)}),a}return JJ}var eee,Nze;function JVn(){if(Nze)return eee;Nze=1;var e=u1t();eee=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return eee}var tee,Ize;function eqn(){if(Ize)return tee;Ize=1,tee=t;var e=()=>1;function t(r,s,a){return n(r,s||e,a||function(i){return r.outEdges(i)})}function n(r,s,a){var i={},l=r.nodes();return l.forEach(function(c){i[c]={},i[c][c]={distance:0},l.forEach(function(u){c!==u&&(i[c][u]={distance:Number.POSITIVE_INFINITY})}),a(c).forEach(function(u){var d=u.v===c?u.w:u.v,f=s(u);i[c][d]={distance:f,predecessor:c}})}),l.forEach(function(c){var u=i[c];l.forEach(function(d){var f=i[d];l.forEach(function(p){var h=f[c],m=u[p],v=f[p],y=h.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return tee}var nee,Aze;function d1t(){if(Aze)return nee;Aze=1;function e(n){var r={},s={},a=[];function i(l){if(Object.hasOwn(s,l))throw new t;Object.hasOwn(r,l)||(s[l]=!0,r[l]=!0,n.predecessors(l).forEach(i),delete s[l],a.push(l))}if(n.sinks().forEach(i),Object.keys(r).length!==n.nodeCount())throw new t;return a}class t extends Error{constructor(){super(...arguments)}}return nee=e,e.CycleException=t,nee}var ree,Rze;function tqn(){if(Rze)return ree;Rze=1;var e=d1t();ree=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return ree}var see,Pze;function f1t(){if(Pze)return see;Pze=1,see=e;function e(s,a,i){Array.isArray(a)||(a=[a]);var l=s.isDirected()?f=>s.successors(f):f=>s.neighbors(f),c=i==="post"?t:n,u=[],d={};return a.forEach(f=>{if(!s.hasNode(f))throw new Error("Graph does not have node: "+f);c(f,l,d,u)}),u}function t(s,a,i,l){for(var c=[[s,!1]];c.length>0;){var u=c.pop();u[1]?l.push(u[0]):Object.hasOwn(i,u[0])||(i[u[0]]=!0,c.push([u[0],!0]),r(a(u[0]),d=>c.push([d,!1])))}}function n(s,a,i,l){for(var c=[s];c.length>0;){var u=c.pop();Object.hasOwn(i,u)||(i[u]=!0,l.push(u),r(a(u),d=>c.push(d)))}}function r(s,a){for(var i=s.length;i--;)a(s[i],i,s);return s}return see}var aee,$ze;function nqn(){if($ze)return aee;$ze=1;var e=f1t();aee=t;function t(n,r){return e(n,r,"post")}return aee}var iee,Mze;function rqn(){if(Mze)return iee;Mze=1;var e=f1t();iee=t;function t(n,r){return e(n,r,"pre")}return iee}var oee,Dze;function sqn(){if(Dze)return oee;Dze=1;var e=ESe(),t=l1t();oee=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var p=f.v===c?f.w:f.v,h=l.priority(p);if(h!==void 0){var m=s(f);m<h&&(i[p]=c,l.decrease(p,m))}}if(r.nodeCount()===0)return a;r.nodes().forEach(function(f){l.add(f,Number.POSITIVE_INFINITY),a.setNode(f)}),l.decrease(r.nodes()[0],0);for(var d=!1;l.size()>0;){if(c=l.removeMin(),Object.hasOwn(i,c))a.setEdge(c,i[c]);else{if(d)throw new Error("Input graph is not connected: "+r);d=!0}r.nodeEdges(c).forEach(u)}return a}return oee}var lee,Lze;function aqn(){return Lze||(Lze=1,lee={components:KVn(),dijkstra:c1t(),dijkstraAll:XVn(),findCycles:JVn(),floydWarshall:eqn(),isAcyclic:tqn(),postorder:nqn(),preorder:rqn(),prim:sqn(),tarjan:u1t(),topsort:d1t()}),lee}var cee,Fze;function Mg(){if(Fze)return cee;Fze=1;var e=QVn();return cee={Graph:e.Graph,json:YVn(),alg:aqn(),version:e.version},cee}var uee,zze;function iqn(){if(zze)return uee;zze=1;class e{constructor(){let s={};s._next=s._prev=s,this._sentinel=s}dequeue(){let s=this._sentinel,a=s._prev;if(a!==s)return t(a),a}enqueue(s){let a=this._sentinel;s._prev&&s._next&&t(s),s._next=a._next,a._next._prev=s,a._next=s,s._prev=a}toString(){let s=[],a=this._sentinel,i=a._prev;for(;i!==a;)s.push(JSON.stringify(i,n)),i=i._prev;return"["+s.join(", ")+"]"}}function t(r){r._prev._next=r._next,r._next._prev=r._prev,delete r._next,delete r._prev}function n(r,s){if(r!=="_next"&&r!=="_prev")return s}return uee=e,uee}var dee,Bze;function oqn(){if(Bze)return dee;Bze=1;let e=Mg().Graph,t=iqn();dee=r;let n=()=>1;function r(u,d){if(u.nodeCount()<=1)return[];let f=i(u,d||n);return s(f.graph,f.buckets,f.zeroIdx).flatMap(h=>u.outEdges(h.v,h.w))}function s(u,d,f){let p=[],h=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=h.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){p=p.concat(a(u,d,f,v,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);h&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(v=>{let y=u.edge(v),b=v.w,S=u.node(b);S.in-=y,l(d,f,S)}),u.removeNode(p.v),m}function i(u,d){let f=new e,p=0,h=0;u.nodes().forEach(y=>{f.setNode(y,{v:y,in:0,out:0})}),u.edges().forEach(y=>{let b=f.edge(y.v,y.w)||0,S=d(y),x=b+S;f.setEdge(y.v,y.w,x),h=Math.max(h,f.node(y.v).out+=S),p=Math.max(p,f.node(y.w).in+=S)});let m=c(h+p+3).map(()=>new t),v=p+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return dee}var fee,Uze;function Dl(){if(Uze)return fee;Uze=1;let e=Mg().Graph;fee={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:C,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:_,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:x,zipObject:E};function t(j,T,I,A){for(var R=A;j.hasNode(R);)R=x(A);return I.dummy=T,j.setNode(R,I),R}function n(j){let T=new e().setGraph(j.graph());return j.nodes().forEach(I=>T.setNode(I,j.node(I))),j.edges().forEach(I=>{let A=T.edge(I.v,I.w)||{weight:0,minlen:1},R=j.edge(I);T.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),T}function r(j){let T=new e({multigraph:j.isMultigraph()}).setGraph(j.graph());return j.nodes().forEach(I=>{j.children(I).length||T.setNode(I,j.node(I))}),j.edges().forEach(I=>{T.setEdge(I,j.edge(I))}),T}function s(j){let T=j.nodes().map(I=>{let A={};return j.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+j.edge(R).weight}),A});return E(j.nodes(),T)}function a(j){let T=j.nodes().map(I=>{let A={};return j.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+j.edge(R).weight}),A});return E(j.nodes(),T)}function i(j,T){let I=j.x,A=j.y,R=T.x-I,L=T.y-A,M=j.width/2,z=j.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,F;return Math.abs(L)*M>Math.abs(R)*z?(L<0&&(z=-z),H=z*R/L,F=z):(R<0&&(M=-M),H=M,F=M*L/R),{x:I+H,y:A+F}}function l(j){let T=k(m(j)+1).map(()=>[]);return j.nodes().forEach(I=>{let A=j.node(I),R=A.rank;R!==void 0&&(T[R][A.order]=I)}),T}function c(j){let T=j.nodes().map(A=>{let R=j.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,T);j.nodes().forEach(A=>{let R=j.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(j){let T=j.nodes().map(M=>j.node(M).rank),I=h(Math.min,T),A=[];j.nodes().forEach(M=>{let z=j.node(M).rank-I;A[z]||(A[z]=[]),A[z].push(M)});let R=0,L=j.graph().nodeRankFactor;Array.from(A).forEach((M,z)=>{M===void 0&&z%L!==0?--R:M!==void 0&&R&&M.forEach(H=>j.node(H).rank+=R)})}function d(j,T,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(j,"border",R,T)}function f(j,T=p){const I=[];for(let A=0;A<j.length;A+=T){const R=j.slice(A,A+T);I.push(R)}return I}const p=65535;function h(j,T){if(T.length>p){const I=f(T);return j.apply(null,I.map(A=>j.apply(null,A)))}else return j.apply(null,T)}function m(j){const I=j.nodes().map(A=>{let R=j.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function v(j,T){let I={lhs:[],rhs:[]};return j.forEach(A=>{T(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(j,T){let I=Date.now();try{return T()}finally{console.log(j+" time: "+(Date.now()-I)+"ms")}}function b(j,T){return T()}let S=0;function x(j){var T=++S;return j+(""+T)}function k(j,T,I=1){T==null&&(T=j,j=0);let A=L=>L<T;I<0&&(A=L=>T<L);const R=[];for(let L=j;A(L);L+=I)R.push(L);return R}function _(j,T){const I={};for(const A of T)j[A]!==void 0&&(I[A]=j[A]);return I}function C(j,T){let I=T;return typeof T=="string"&&(I=A=>A[T]),Object.entries(j).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function E(j,T){return j.reduce((I,A,R)=>(I[A]=T[R],I),{})}return fee}var pee,Vze;function lqn(){if(Vze)return pee;Vze=1;let e=oqn(),t=Dl().uniqueId;pee={run:n,undo:s};function n(a){(a.graph().acyclicer==="greedy"?e(a,l(a)):r(a)).forEach(c=>{let u=a.edge(c);a.removeEdge(c),u.forwardName=c.name,u.reversed=!0,a.setEdge(c.w,c.v,u,t("rev"))});function l(c){return u=>c.edge(u).weight}}function r(a){let i=[],l={},c={};function u(d){Object.hasOwn(c,d)||(c[d]=!0,l[d]=!0,a.outEdges(d).forEach(f=>{Object.hasOwn(l,f.w)?i.push(f):u(f.w)}),delete l[d])}return a.nodes().forEach(u),i}function s(a){a.edges().forEach(i=>{let l=a.edge(i);if(l.reversed){a.removeEdge(i);let c=l.forwardName;delete l.reversed,delete l.forwardName,a.setEdge(i.w,i.v,l,c)}})}return pee}var hee,qze;function cqn(){if(qze)return hee;qze=1;let e=Dl();hee={run:t,undo:r};function t(s){s.graph().dummyChains=[],s.edges().forEach(a=>n(s,a))}function n(s,a){let i=a.v,l=s.node(i).rank,c=a.w,u=s.node(c).rank,d=a.name,f=s.edge(a),p=f.labelRank;if(u===l+1)return;s.removeEdge(a);let h,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},h=e.addDummyNode(s,"edge",m,"_d"),l===p&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,h,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(h),i=h;s.setEdge(i,c,{weight:f.weight},d)}function r(s){s.graph().dummyChains.forEach(a=>{let i=s.node(a),l=i.edgeLabel,c;for(s.setEdge(i.edgeObj,l);i.dummy;)c=s.successors(a)[0],s.removeNode(a),l.points.push({x:i.x,y:i.y}),i.dummy==="edge-label"&&(l.x=i.x,l.y=i.y,l.width=i.width,l.height=i.height),a=c,i=s.node(a)})}return hee}var mee,Hze;function uB(){if(Hze)return mee;Hze=1;const{applyWithChunking:e}=Dl();mee={longestPath:t,slack:n};function t(r){var s={};function a(i){var l=r.node(i);if(Object.hasOwn(s,i))return l.rank;s[i]=!0;let c=r.outEdges(i).map(d=>d==null?Number.POSITIVE_INFINITY:a(d.w)-r.edge(d).minlen);var u=e(Math.min,c);return u===Number.POSITIVE_INFINITY&&(u=0),l.rank=u}r.sources().forEach(a)}function n(r,s){return r.node(s.w).rank-r.node(s.v).rank-r.edge(s).minlen}return mee}var gee,Wze;function p1t(){if(Wze)return gee;Wze=1;var e=Mg().Graph,t=uB().slack;gee=n;function n(i){var l=new e({directed:!1}),c=i.nodes()[0],u=i.nodeCount();l.setNode(c,{});for(var d,f;r(l,i)<u;)d=s(l,i),f=l.hasNode(d.v)?t(i,d):-t(i,d),a(l,i,f);return l}function r(i,l){function c(u){l.nodeEdges(u).forEach(d=>{var f=d.v,p=u===f?d.w:f;!i.hasNode(p)&&!t(l,d)&&(i.setNode(p,{}),i.setEdge(u,p,{}),c(p))})}return i.nodes().forEach(c),i.nodeCount()}function s(i,l){return l.edges().reduce((u,d)=>{let f=Number.POSITIVE_INFINITY;return i.hasNode(d.v)!==i.hasNode(d.w)&&(f=t(l,d)),f<u[0]?[f,d]:u},[Number.POSITIVE_INFINITY,null])[1]}function a(i,l,c){i.nodes().forEach(u=>l.node(u).rank+=c)}return gee}var vee,Zze;function uqn(){if(Zze)return vee;Zze=1;var e=p1t(),t=uB().slack,n=uB().longestPath,r=Mg().alg.preorder,s=Mg().alg.postorder,a=Dl().simplify;vee=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(S){S=a(S),n(S);var x=e(S);d(x),l(x,S);for(var k,_;k=p(x);)_=h(x,S,k),m(x,S,k,_)}function l(S,x){var k=s(S,S.nodes());k=k.slice(0,k.length-1),k.forEach(_=>c(S,x,_))}function c(S,x,k){var _=S.node(k),C=_.parent;S.edge(k,C).cutvalue=u(S,x,k)}function u(S,x,k){var _=S.node(k),C=_.parent,E=!0,j=x.edge(k,C),T=0;return j||(E=!1,j=x.edge(C,k)),T=j.weight,x.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==C){var L=A===E,M=x.edge(I).weight;if(T+=L?M:-M,y(S,k,R)){var z=S.edge(k,R).cutvalue;T+=L?-z:z}}}),T}function d(S,x){arguments.length<2&&(x=S.nodes()[0]),f(S,{},1,x)}function f(S,x,k,_,C){var E=k,j=S.node(_);return x[_]=!0,S.neighbors(_).forEach(T=>{Object.hasOwn(x,T)||(k=f(S,x,k,T,_))}),j.low=E,j.lim=k++,C?j.parent=C:delete j.parent,k}function p(S){return S.edges().find(x=>S.edge(x).cutvalue<0)}function h(S,x,k){var _=k.v,C=k.w;x.hasEdge(_,C)||(_=k.w,C=k.v);var E=S.node(_),j=S.node(C),T=E,I=!1;E.lim>j.lim&&(T=j,I=!0);var A=x.edges().filter(R=>I===b(S,S.node(R.v),T)&&I!==b(S,S.node(R.w),T));return A.reduce((R,L)=>t(x,L)<t(x,R)?L:R)}function m(S,x,k,_){var C=k.v,E=k.w;S.removeEdge(C,E),S.setEdge(_.v,_.w,{}),d(S),l(S,x),v(S,x)}function v(S,x){var k=S.nodes().find(C=>!x.node(C).parent),_=r(S,k);_=_.slice(1),_.forEach(C=>{var E=S.node(C).parent,j=x.edge(C,E),T=!1;j||(j=x.edge(E,C),T=!0),x.node(C).rank=x.node(E).rank+(T?j.minlen:-j.minlen)})}function y(S,x,k){return S.hasEdge(x,k)}function b(S,x,k){return k.low<=x.lim&&x.lim<=k.lim}return vee}var yee,Gze;function dqn(){if(Gze)return yee;Gze=1;var e=uB(),t=e.longestPath,n=p1t(),r=uqn();yee=s;function s(c){var u=c.graph().ranker;if(u instanceof Function)return u(c);switch(c.graph().ranker){case"network-simplex":l(c);break;case"tight-tree":i(c);break;case"longest-path":a(c);break;case"none":break;default:l(c)}}var a=t;function i(c){t(c),n(c)}function l(c){r(c)}return yee}var bee,Qze;function fqn(){if(Qze)return bee;Qze=1,bee=e;function e(r){let s=n(r);r.graph().dummyChains.forEach(a=>{let i=r.node(a),l=i.edgeObj,c=t(r,s,l.v,l.w),u=c.path,d=c.lca,f=0,p=u[f],h=!0;for(;a!==l.w;){if(i=r.node(a),h){for(;(p=u[f])!==d&&r.node(p).maxRank<i.rank;)f++;p===d&&(h=!1)}if(!h){for(;f<u.length-1&&r.node(p=u[f+1]).minRank<=i.rank;)f++;p=u[f]}r.setParent(a,p),a=r.successors(a)[0]}})}function t(r,s,a,i){let l=[],c=[],u=Math.min(s[a].low,s[i].low),d=Math.max(s[a].lim,s[i].lim),f,p;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(p=f,f=i;(f=r.parent(f))!==p;)c.push(f);return{path:l.concat(c.reverse()),lca:p}}function n(r){let s={},a=0;function i(l){let c=a;r.children(l).forEach(i),s[l]={low:c,lim:a++}}return r.children().forEach(i),s}return bee}var xee,Yze;function pqn(){if(Yze)return xee;Yze=1;let e=Dl();xee={run:t,cleanup:a};function t(i){let l=e.addDummyNode(i,"root",{},"_root"),c=r(i),u=Object.values(c),d=e.applyWithChunking(Math.max,u)-1,f=2*d+1;i.graph().nestingRoot=l,i.edges().forEach(h=>i.edge(h).minlen*=f);let p=s(i)+1;i.children().forEach(h=>n(i,l,f,p,d,c,h)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,p){let h=i.children(p);if(!h.length){p!==l&&i.setEdge(l,p,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(v,p),y.borderBottom=v,h.forEach(b=>{n(i,l,c,u,d,f,b);let S=i.node(b),x=S.borderTop?S.borderTop:b,k=S.borderBottom?S.borderBottom:b,_=S.borderTop?u:2*u,C=x!==k?1:d-f[p]+1;i.setEdge(m,x,{weight:_,minlen:C,nestingEdge:!0}),i.setEdge(k,v,{weight:_,minlen:C,nestingEdge:!0})}),i.parent(p)||i.setEdge(l,m,{weight:0,minlen:d+f[p]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(p=>c(p,d+1)),l[u]=d}return i.children().forEach(u=>c(u,1)),l}function s(i){return i.edges().reduce((l,c)=>l+i.edge(c).weight,0)}function a(i){var l=i.graph();i.removeNode(l.nestingRoot),delete l.nestingRoot,i.edges().forEach(c=>{var u=i.edge(c);u.nestingEdge&&i.removeEdge(c)})}return xee}var wee,Kze;function hqn(){if(Kze)return wee;Kze=1;let e=Dl();wee=t;function t(r){function s(a){let i=r.children(a),l=r.node(a);if(i.length&&i.forEach(s),Object.hasOwn(l,"minRank")){l.borderLeft=[],l.borderRight=[];for(let c=l.minRank,u=l.maxRank+1;c<u;++c)n(r,"borderLeft","_bl",a,l,c),n(r,"borderRight","_br",a,l,c)}}r.children().forEach(s)}function n(r,s,a,i,l,c){let u={width:0,height:0,rank:c,borderType:s},d=l[s][c-1],f=e.addDummyNode(r,"border",u,a);l[s][c]=f,r.setParent(f,i),d&&r.setEdge(d,f,{weight:1})}return wee}var See,Xze;function mqn(){if(Xze)return See;Xze=1,See={adjust:e,undo:t};function e(c){let u=c.graph().rankdir.toLowerCase();(u==="lr"||u==="rl")&&n(c)}function t(c){let u=c.graph().rankdir.toLowerCase();(u==="bt"||u==="rl")&&s(c),(u==="lr"||u==="rl")&&(i(c),n(c))}function n(c){c.nodes().forEach(u=>r(c.node(u))),c.edges().forEach(u=>r(c.edge(u)))}function r(c){let u=c.width;c.width=c.height,c.height=u}function s(c){c.nodes().forEach(u=>a(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(a),Object.hasOwn(d,"y")&&a(d)})}function a(c){c.y=-c.y}function i(c){c.nodes().forEach(u=>l(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(l),Object.hasOwn(d,"x")&&l(d)})}function l(c){let u=c.x;c.x=c.y,c.y=u}return See}var kee,Jze;function gqn(){if(Jze)return kee;Jze=1;let e=Dl();kee=t;function t(n){let r={},s=n.nodes().filter(d=>!n.children(d).length),a=s.map(d=>n.node(d).rank),i=e.applyWithChunking(Math.max,a),l=e.range(i+1).map(()=>[]);function c(d){if(r[d])return;r[d]=!0;let f=n.node(d);l[f.rank].push(d),n.successors(d).forEach(c)}return s.sort((d,f)=>n.node(d).rank-n.node(f).rank).forEach(c),l}return kee}var Oee,e8e;function vqn(){if(e8e)return Oee;e8e=1;let e=Dl().zipObject;Oee=t;function t(r,s){let a=0;for(let i=1;i<s.length;++i)a+=n(r,s[i-1],s[i]);return a}function n(r,s,a){let i=e(a,a.map((p,h)=>h)),l=s.flatMap(p=>r.outEdges(p).map(h=>({pos:i[h.w],weight:r.edge(h).weight})).sort((h,m)=>h.pos-m.pos)),c=1;for(;c<a.length;)c<<=1;let u=2*c-1;c-=1;let d=new Array(u).fill(0),f=0;return l.forEach(p=>{let h=p.pos+c;d[h]+=p.weight;let m=0;for(;h>0;)h%2&&(m+=d[h+1]),h=h-1>>1,d[h]+=p.weight;f+=p.weight*m}),f}return Oee}var _ee,t8e;function yqn(){if(t8e)return _ee;t8e=1,_ee=e;function e(t,n=[]){return n.map(r=>{let s=t.inEdges(r);if(s.length){let a=s.reduce((i,l)=>{let c=t.edge(l),u=t.node(l.v);return{sum:i.sum+c.weight*u.order,weight:i.weight+c.weight}},{sum:0,weight:0});return{v:r,barycenter:a.sum/a.weight,weight:a.weight}}else return{v:r}})}return _ee}var Cee,n8e;function bqn(){if(n8e)return Cee;n8e=1;let e=Dl();Cee=t;function t(s,a){let i={};s.forEach((c,u)=>{let d=i[c.v]={indegree:0,in:[],out:[],vs:[c.v],i:u};c.barycenter!==void 0&&(d.barycenter=c.barycenter,d.weight=c.weight)}),a.edges().forEach(c=>{let u=i[c.v],d=i[c.w];u!==void 0&&d!==void 0&&(d.indegree++,u.out.push(i[c.w]))});let l=Object.values(i).filter(c=>!c.indegree);return n(l)}function n(s){let a=[];function i(c){return u=>{u.merged||(u.barycenter===void 0||c.barycenter===void 0||u.barycenter>=c.barycenter)&&r(c,u)}}function l(c){return u=>{u.in.push(c),--u.indegree===0&&s.push(u)}}for(;s.length;){let c=s.pop();a.push(c),c.in.reverse().forEach(i(c)),c.out.forEach(l(c))}return a.filter(c=>!c.merged).map(c=>e.pick(c,["vs","i","barycenter","weight"]))}function r(s,a){let i=0,l=0;s.weight&&(i+=s.barycenter*s.weight,l+=s.weight),a.weight&&(i+=a.barycenter*a.weight,l+=a.weight),s.vs=a.vs.concat(s.vs),s.barycenter=i/l,s.weight=l,s.i=Math.min(a.i,s.i),a.merged=!0}return Cee}var Eee,r8e;function xqn(){if(r8e)return Eee;r8e=1;let e=Dl();Eee=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,p=0;l.sort(r(!!a)),p=n(u,c,p),l.forEach(m=>{p+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,p=n(u,c,p)});let h={vs:u.flat(!0)};return f&&(h.barycenter=d/f,h.weight=f),h}function n(s,a,i){let l;for(;a.length&&(l=a[a.length-1]).i<=i;)a.pop(),s.push(l.vs),i++;return i}function r(s){return(a,i)=>a.barycenter<i.barycenter?-1:a.barycenter>i.barycenter?1:s?i.i-a.i:a.i-i.i}return Eee}var jee,s8e;function wqn(){if(s8e)return jee;s8e=1;let e=yqn(),t=bqn(),n=xqn();jee=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),p=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,m={};p&&(d=d.filter(S=>S!==p&&S!==h));let v=e(i,d);v.forEach(S=>{if(i.children(S.v).length){let x=r(i,S.v,c,u);m[S.v]=x,Object.hasOwn(x,"barycenter")&&a(S,x)}});let y=t(v,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let S=i.node(i.predecessors(p)[0]),x=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+S.order+x.order)/(b.weight+2),b.weight+=2}return b}function s(i,l){i.forEach(c=>{c.vs=c.vs.flatMap(u=>l[u]?l[u].vs:u)})}function a(i,l){i.barycenter!==void 0?(i.barycenter=(i.barycenter*i.weight+l.barycenter*l.weight)/(i.weight+l.weight),i.weight+=l.weight):(i.barycenter=l.barycenter,i.weight=l.weight)}return jee}var Tee,a8e;function Sqn(){if(a8e)return Tee;a8e=1;let e=Mg().Graph,t=Dl();Tee=n;function n(s,a,i,l){l||(l=s.nodes());let c=r(s),u=new e({compound:!0}).setGraph({root:c}).setDefaultNodeLabel(d=>s.node(d));return l.forEach(d=>{let f=s.node(d),p=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,p||c),s[i](d).forEach(h=>{let m=h.v===d?h.w:h.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(h).weight+y})}),Object.hasOwn(f,"minRank")&&u.setNode(d,{borderLeft:f.borderLeft[a],borderRight:f.borderRight[a]}))}),u}function r(s){for(var a;s.hasNode(a=t.uniqueId("_root")););return a}return Tee}var Nee,i8e;function kqn(){if(i8e)return Nee;i8e=1,Nee=e;function e(t,n,r){let s={},a;r.forEach(i=>{let l=t.parent(i),c,u;for(;l;){if(c=t.parent(l),c?(u=s[c],s[c]=l):(u=a,a=l),u&&u!==l){n.setEdge(u,l);return}l=c}})}return Nee}var Iee,o8e;function Oqn(){if(o8e)return Iee;o8e=1;let e=gqn(),t=vqn(),n=wqn(),r=Sqn(),s=kqn(),a=Mg().Graph,i=Dl();Iee=l;function l(f,p){if(p&&typeof p.customOrder=="function"){p.customOrder(f,l);return}let h=i.maxRank(f),m=c(f,i.range(1,h+1),"inEdges"),v=c(f,i.range(h-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),p&&p.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,S;for(let x=0,k=0;k<4;++x,++k){u(x%2?m:v,x%4>=2),y=i.buildLayerMatrix(f);let _=t(f,y);_<b&&(k=0,S=Object.assign({},y),b=_)}d(f,S)}function c(f,p,h){const m=new Map,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let S=b.minRank;S<=b.maxRank;S++)S!==b.rank&&v(S,y)}return p.map(function(y){return r(f,y,h,m.get(y)||[])})}function u(f,p){let h=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,h,p);y.vs.forEach((b,S)=>m.node(b).order=S),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,v)=>f.node(m).order=v))}return Iee}var Aee,l8e;function _qn(){if(l8e)return Aee;l8e=1;let e=Mg().Graph,t=Dl();Aee={positionX:h,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:p};function n(y,b){let S={};function x(k,_){let C=0,E=0,j=k.length,T=_[_.length-1];return _.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:j;(R||I===T)&&(_.slice(E,A+1).forEach(M=>{y.predecessors(M).forEach(z=>{let H=y.node(z),F=H.order;(F<C||L<F)&&!(H.dummy&&y.node(M).dummy)&&a(S,z,M)})}),E=A+1,C=L)}),_}return b.length&&b.reduce(x),S}function r(y,b){let S={};function x(_,C,E,j,T){let I;t.range(C,E).forEach(A=>{I=_[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<j||L.order>T)&&a(S,R,I)})})}function k(_,C){let E=-1,j,T=0;return C.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(j=y.node(R[0]).order,x(C,T,A,E,j),T=A,E=j)}x(C,T,C.length,j,_.length)}),C}return b.length&&b.reduce(k),S}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(S=>y.node(S).dummy)}function a(y,b,S){if(b>S){let k=b;b=S,S=k}let x=y[b];x||(y[b]=x={}),x[S]=!0}function i(y,b,S){if(b>S){let x=b;b=S,S=x}return!!y[b]&&Object.hasOwn(y[b],S)}function l(y,b,S,x){let k={},_={},C={};return b.forEach(E=>{E.forEach((j,T)=>{k[j]=j,_[j]=j,C[j]=T})}),b.forEach(E=>{let j=-1;E.forEach(T=>{let I=x(T);if(I.length){I=I.sort((R,L)=>C[R]-C[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let M=I[R];_[T]===T&&j<C[M]&&!i(S,T,M)&&(_[M]=T,_[T]=k[T]=k[M],j=C[M])}}})}),{root:k,align:_}}function c(y,b,S,x,k){let _={},C=u(y,b,S,k),E=k?"borderLeft":"borderRight";function j(A,R){let L=C.nodes(),M=L.pop(),z={};for(;M;)z[M]?A(M):(z[M]=!0,L.push(M),L=L.concat(R(M))),M=L.pop()}function T(A){_[A]=C.inEdges(A).reduce((R,L)=>Math.max(R,_[L.v]+C.edge(L)),0)}function I(A){let R=C.outEdges(A).reduce((M,z)=>Math.min(M,_[z.w]-C.edge(z)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==E&&(_[A]=Math.max(_[A],R))}return j(T,C.predecessors.bind(C)),j(I,C.successors.bind(C)),Object.keys(x).forEach(A=>_[A]=_[S[A]]),_}function u(y,b,S,x){let k=new e,_=y.graph(),C=m(_.nodesep,_.edgesep,x);return b.forEach(E=>{let j;E.forEach(T=>{let I=S[T];if(k.setNode(I),j){var A=S[j],R=k.edge(A,I);k.setEdge(A,I,Math.max(C(y,T,j),R||0))}j=T})}),k}function d(y,b){return Object.values(b).reduce((S,x)=>{let k=Number.NEGATIVE_INFINITY,_=Number.POSITIVE_INFINITY;Object.entries(x).forEach(([E,j])=>{let T=v(y,E)/2;k=Math.max(j+T,k),_=Math.min(j-T,_)});const C=k-_;return C<S[0]&&(S=[C,x]),S},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let S=Object.values(b),x=t.applyWithChunking(Math.min,S),k=t.applyWithChunking(Math.max,S);["u","d"].forEach(_=>{["l","r"].forEach(C=>{let E=_+C,j=y[E];if(j===b)return;let T=Object.values(j),I=x-t.applyWithChunking(Math.min,T);C!=="l"&&(I=k-t.applyWithChunking(Math.max,T)),I&&(y[E]=t.mapValues(j,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(S,x)=>{if(b)return y[b.toLowerCase()][x];{let k=Object.values(y).map(_=>_[x]).sort((_,C)=>_-C);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),S=Object.assign(n(y,b),r(y,b)),x={},k;["u","d"].forEach(C=>{k=C==="u"?b:Object.values(b).reverse(),["l","r"].forEach(E=>{E==="r"&&(k=k.map(A=>Object.values(A).reverse()));let j=(C==="u"?y.predecessors:y.successors).bind(y),T=l(y,k,S,j),I=c(y,k,T.root,T.align,E==="r");E==="r"&&(I=t.mapValues(I,A=>-A)),x[C+E]=I})});let _=d(y,x);return f(x,_),p(x,y.graph().align)}function m(y,b,S){return(x,k,_)=>{let C=x.node(k),E=x.node(_),j=0,T;if(j+=C.width/2,Object.hasOwn(C,"labelpos"))switch(C.labelpos.toLowerCase()){case"l":T=-C.width/2;break;case"r":T=C.width/2;break}if(T&&(j+=S?T:-T),T=0,j+=(C.dummy?b:y)/2,j+=(E.dummy?b:y)/2,j+=E.width/2,Object.hasOwn(E,"labelpos"))switch(E.labelpos.toLowerCase()){case"l":T=E.width/2;break;case"r":T=-E.width/2;break}return T&&(j+=S?T:-T),T=0,j}}function v(y,b){return y.node(b).width}return Aee}var Ree,c8e;function Cqn(){if(c8e)return Ree;c8e=1;let e=Dl(),t=_qn().positionX;Ree=n;function n(s){s=e.asNonCompoundGraph(s),r(s),Object.entries(t(s)).forEach(([a,i])=>s.node(a).x=i)}function r(s){let a=e.buildLayerMatrix(s),i=s.graph().ranksep,l=0;a.forEach(c=>{const u=c.reduce((d,f)=>{const p=s.node(f).height;return d>p?d:p},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return Ree}var Pee,u8e;function Eqn(){if(u8e)return Pee;u8e=1;let e=lqn(),t=cqn(),n=dqn(),r=Dl().normalizeRanks,s=fqn(),a=Dl().removeEmptyRanks,i=pqn(),l=hqn(),c=mqn(),u=Oqn(),d=Cqn(),f=Dl(),p=Mg().Graph;Pee=h;function h($,U){let Z=U&&U.debugTiming?f.time:f.notime;Z("layout",()=>{let K=Z(" buildLayoutGraph",()=>j($));Z(" runLayout",()=>m(K,Z,U)),Z(" updateInputGraph",()=>v($,K))})}function m($,U,Z){U(" makeSpaceForEdgeLabels",()=>T($)),U(" removeSelfEdges",()=>B($)),U(" acyclic",()=>e.run($)),U(" nestingGraph.run",()=>i.run($)),U(" rank",()=>n(f.asNonCompoundGraph($))),U(" injectEdgeLabelProxies",()=>I($)),U(" removeEmptyRanks",()=>a($)),U(" nestingGraph.cleanup",()=>i.cleanup($)),U(" normalizeRanks",()=>r($)),U(" assignRankMinMax",()=>A($)),U(" removeEdgeLabelProxies",()=>R($)),U(" normalize.run",()=>t.run($)),U(" parentDummyChains",()=>s($)),U(" addBorderSegments",()=>l($)),U(" order",()=>u($,Z)),U(" insertSelfEdges",()=>q($)),U(" adjustCoordinateSystem",()=>c.adjust($)),U(" position",()=>d($)),U(" positionSelfEdges",()=>D($)),U(" removeBorderNodes",()=>F($)),U(" normalize.undo",()=>t.undo($)),U(" fixupEdgeLabelCoords",()=>z($)),U(" undoCoordinateSystem",()=>c.undo($)),U(" translateGraph",()=>L($)),U(" assignNodeIntersects",()=>M($)),U(" reversePoints",()=>H($)),U(" acyclic.undo",()=>e.undo($))}function v($,U){$.nodes().forEach(Z=>{let K=$.node(Z),ne=U.node(Z);K&&(K.x=ne.x,K.y=ne.y,K.rank=ne.rank,U.children(Z).length&&(K.width=ne.width,K.height=ne.height))}),$.edges().forEach(Z=>{let K=$.edge(Z),ne=U.edge(Z);K.points=ne.points,Object.hasOwn(ne,"x")&&(K.x=ne.x,K.y=ne.y)}),$.graph().width=U.graph().width,$.graph().height=U.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},S=["acyclicer","ranker","rankdir","align"],x=["width","height","rank"],k={width:0,height:0},_=["minlen","weight","width","height","labeloffset"],C={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},E=["labelpos"];function j($){let U=new p({multigraph:!0,compound:!0}),Z=V($.graph());return U.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,S))),$.nodes().forEach(K=>{let ne=V($.node(K));const te=G(ne,x);Object.keys(k).forEach(J=>{te[J]===void 0&&(te[J]=k[J])}),U.setNode(K,te),U.setParent(K,$.parent(K))}),$.edges().forEach(K=>{let ne=V($.edge(K));U.setEdge(K,Object.assign({},C,G(ne,_),f.pick(ne,E)))}),U}function T($){let U=$.graph();U.ranksep/=2,$.edges().forEach(Z=>{let K=$.edge(Z);K.minlen*=2,K.labelpos.toLowerCase()!=="c"&&(U.rankdir==="TB"||U.rankdir==="BT"?K.width+=K.labeloffset:K.height+=K.labeloffset)})}function I($){$.edges().forEach(U=>{let Z=$.edge(U);if(Z.width&&Z.height){let K=$.node(U.v),te={rank:($.node(U.w).rank-K.rank)/2+K.rank,e:U};f.addDummyNode($,"edge-proxy",te,"_ep")}})}function A($){let U=0;$.nodes().forEach(Z=>{let K=$.node(Z);K.borderTop&&(K.minRank=$.node(K.borderTop).rank,K.maxRank=$.node(K.borderBottom).rank,U=Math.max(U,K.maxRank))}),$.graph().maxRank=U}function R($){$.nodes().forEach(U=>{let Z=$.node(U);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(U))})}function L($){let U=Number.POSITIVE_INFINITY,Z=0,K=Number.POSITIVE_INFINITY,ne=0,te=$.graph(),J=te.marginx||0,ae=te.marginy||0;function pe(Y){let ee=Y.x,ce=Y.y,de=Y.width,oe=Y.height;U=Math.min(U,ee-de/2),Z=Math.max(Z,ee+de/2),K=Math.min(K,ce-oe/2),ne=Math.max(ne,ce+oe/2)}$.nodes().forEach(Y=>pe($.node(Y))),$.edges().forEach(Y=>{let ee=$.edge(Y);Object.hasOwn(ee,"x")&&pe(ee)}),U-=J,K-=ae,$.nodes().forEach(Y=>{let ee=$.node(Y);ee.x-=U,ee.y-=K}),$.edges().forEach(Y=>{let ee=$.edge(Y);ee.points.forEach(ce=>{ce.x-=U,ce.y-=K}),Object.hasOwn(ee,"x")&&(ee.x-=U),Object.hasOwn(ee,"y")&&(ee.y-=K)}),te.width=Z-U+J,te.height=ne-K+ae}function M($){$.edges().forEach(U=>{let Z=$.edge(U),K=$.node(U.v),ne=$.node(U.w),te,J;Z.points?(te=Z.points[0],J=Z.points[Z.points.length-1]):(Z.points=[],te=ne,J=K),Z.points.unshift(f.intersectRect(K,te)),Z.points.push(f.intersectRect(ne,J))})}function z($){$.edges().forEach(U=>{let Z=$.edge(U);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H($){$.edges().forEach(U=>{let Z=$.edge(U);Z.reversed&&Z.points.reverse()})}function F($){$.nodes().forEach(U=>{if($.children(U).length){let Z=$.node(U),K=$.node(Z.borderTop),ne=$.node(Z.borderBottom),te=$.node(Z.borderLeft[Z.borderLeft.length-1]),J=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(J.x-te.x),Z.height=Math.abs(ne.y-K.y),Z.x=te.x+Z.width/2,Z.y=K.y+Z.height/2}}),$.nodes().forEach(U=>{$.node(U).dummy==="border"&&$.removeNode(U)})}function B($){$.edges().forEach(U=>{if(U.v===U.w){var Z=$.node(U.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:U,label:$.edge(U)}),$.removeEdge(U)}})}function q($){var U=f.buildLayerMatrix($);U.forEach(Z=>{var K=0;Z.forEach((ne,te)=>{var J=$.node(ne);J.order=te+K,(J.selfEdges||[]).forEach(ae=>{f.addDummyNode($,"selfedge",{width:ae.label.width,height:ae.label.height,rank:J.rank,order:te+ ++K,e:ae.e,label:ae.label},"_se")}),delete J.selfEdges})})}function D($){$.nodes().forEach(U=>{var Z=$.node(U);if(Z.dummy==="selfedge"){var K=$.node(Z.e.v),ne=K.x+K.width/2,te=K.y,J=Z.x-ne,ae=K.height/2;$.setEdge(Z.e,Z.label),$.removeNode(U),Z.label.points=[{x:ne+2*J/3,y:te-ae},{x:ne+5*J/6,y:te-ae},{x:ne+J,y:te},{x:ne+5*J/6,y:te+ae},{x:ne+2*J/3,y:te+ae}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,U){return f.mapValues(f.pick($,U),Number)}function V($){var U={};return $&&Object.entries($).forEach(([Z,K])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),U[Z]=K}),U}return Pee}var $ee,d8e;function jqn(){if(d8e)return $ee;d8e=1;let e=Dl(),t=Mg().Graph;$ee={debugOrdering:n};function n(r){let s=e.buildLayerMatrix(r),a=new t({compound:!0,multigraph:!0}).setGraph({});return r.nodes().forEach(i=>{a.setNode(i,{label:i}),a.setParent(i,"layer"+r.node(i).rank)}),r.edges().forEach(i=>a.setEdge(i.v,i.w,{},i.name)),s.forEach((i,l)=>{let c="layer"+l;a.setNode(c,{rank:"same"}),i.reduce((u,d)=>(a.setEdge(u,d,{style:"invis"}),d))}),a}return $ee}var Mee,f8e;function Tqn(){return f8e||(f8e=1,Mee="1.1.8"),Mee}var Dee,p8e;function Nqn(){return p8e||(p8e=1,Dee={graphlib:Mg(),layout:Eqn(),debug:jqn(),util:{time:Dl().time,notime:Dl().notime},version:Tqn()}),Dee}var Iqn=Nqn();const h8e=zl(Iqn);function Vl(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=Vl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var Aqn={value:()=>{}};function gH(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new E8(n)}function E8(e){this._=e}function Rqn(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",s=n.indexOf(".");if(s>=0&&(r=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}E8.prototype=gH.prototype={constructor:E8,on:function(e,t){var n=this._,r=Rqn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=Pqn(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=r[a]).type)n[s]=m8e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=m8e(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new E8(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++r)a[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function Pqn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function m8e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=Aqn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Rme="http://www.w3.org/1999/xhtml";const g8e={svg:"http://www.w3.org/2000/svg",xhtml:Rme,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function vH(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),g8e.hasOwnProperty(t)?{space:g8e[t],local:e}:e}function $qn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Rme&&t.documentElement.namespaceURI===Rme?t.createElement(e):t.createElementNS(n,e)}}function Mqn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function h1t(e){var t=vH(e);return(t.local?Mqn:$qn)(t)}function Dqn(){}function jSe(e){return e==null?Dqn:function(){return this.querySelector(e)}}function Lqn(e){typeof e!="function"&&(e=jSe(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=a[d])&&(u=e.call(c,c.__data__,d,a))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new Hp(r,this._parents)}function Fqn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function zqn(){return[]}function m1t(e){return e==null?zqn:function(){return this.querySelectorAll(e)}}function Bqn(e){return function(){return Fqn(e.apply(this,arguments))}}function Uqn(e){typeof e=="function"?e=Bqn(e):e=m1t(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new Hp(r,s)}function g1t(e){return function(){return this.matches(e)}}function v1t(e){return function(t){return t.matches(e)}}var Vqn=Array.prototype.find;function qqn(e){return function(){return Vqn.call(this.children,e)}}function Hqn(){return this.firstElementChild}function Wqn(e){return this.select(e==null?Hqn:qqn(typeof e=="function"?e:v1t(e)))}var Zqn=Array.prototype.filter;function Gqn(){return Array.from(this.children)}function Qqn(e){return function(){return Zqn.call(this.children,e)}}function Yqn(e){return this.selectAll(e==null?Gqn:Qqn(typeof e=="function"?e:v1t(e)))}function Kqn(e){typeof e!="function"&&(e=g1t(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Hp(r,this._parents)}function y1t(e){return new Array(e.length)}function Xqn(){return new Hp(this._enter||this._groups.map(y1t),this._parents)}function dB(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}dB.prototype={constructor:dB,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function Jqn(e){return function(){return e}}function eHn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new dB(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function tHn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,p=new Array(d),h;for(l=0;l<d;++l)(c=t[l])&&(p[l]=h=i.call(c,c.__data__,l,t)+"",u.has(h)?s[l]=c:u.set(h,c));for(l=0;l<f;++l)h=i.call(e,a[l],l,a)+"",(c=u.get(h))?(r[l]=c,c.__data__=a[l],u.delete(h)):n[l]=new dB(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function nHn(e){return e.__data__}function rHn(e,t){if(!arguments.length)return Array.from(this,nHn);var n=t?tHn:eHn,r=this._parents,s=this._groups;typeof e!="function"&&(e=Jqn(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),u=0;u<a;++u){var d=r[u],f=s[u],p=f.length,h=sHn(e.call(d,d&&d.__data__,u,r)),m=h.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,v,y,b,h,t);for(var S=0,x=0,k,_;S<m;++S)if(k=v[S]){for(S>=x&&(x=S+1);!(_=y[x])&&++x<m;);k._next=_||null}}return i=new Hp(i,r),i._enter=l,i._exit=c,i}function sHn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function aHn(){return new Hp(this._exit||this._groups.map(y1t),this._parents)}function iHn(e,t,n){var r=this.enter(),s=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),r&&s?r.merge(s).order():s}function oHn(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,a=r.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var u=n[c],d=r[c],f=u.length,p=l[c]=new Array(f),h,m=0;m<f;++m)(h=u[m]||d[m])&&(p[m]=h);for(;c<s;++c)l[c]=n[c];return new Hp(l,this._parents)}function lHn(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,a=r[s],i;--s>=0;)(i=r[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function cHn(e){e||(e=uHn);function t(f,p){return f&&p?e(f.__data__,p.__data__):!f-!p}for(var n=this._groups,r=n.length,s=new Array(r),a=0;a<r;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new Hp(s,this._parents).order()}function uHn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function dHn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function fHn(){return Array.from(this)}function pHn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length;s<a;++s){var i=r[s];if(i)return i}return null}function hHn(){let e=0;for(const t of this)++e;return e}function mHn(){return!this.node()}function gHn(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function vHn(e){return function(){this.removeAttribute(e)}}function yHn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function bHn(e,t){return function(){this.setAttribute(e,t)}}function xHn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function wHn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function SHn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function kHn(e,t){var n=vH(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?yHn:vHn:typeof t=="function"?n.local?SHn:wHn:n.local?xHn:bHn)(n,t))}function b1t(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function OHn(e){return function(){this.style.removeProperty(e)}}function _Hn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function CHn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function EHn(e,t,n){return arguments.length>1?this.each((t==null?OHn:typeof t=="function"?CHn:_Hn)(e,t,n??"")):zT(this.node(),e)}function zT(e,t){return e.style.getPropertyValue(t)||b1t(e).getComputedStyle(e,null).getPropertyValue(t)}function jHn(e){return function(){delete this[e]}}function THn(e,t){return function(){this[e]=t}}function NHn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function IHn(e,t){return arguments.length>1?this.each((t==null?jHn:typeof t=="function"?NHn:THn)(e,t)):this.node()[e]}function x1t(e){return e.trim().split(/^|\s+/)}function TSe(e){return e.classList||new w1t(e)}function w1t(e){this._node=e,this._names=x1t(e.getAttribute("class")||"")}w1t.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function S1t(e,t){for(var n=TSe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function k1t(e,t){for(var n=TSe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function AHn(e){return function(){S1t(this,e)}}function RHn(e){return function(){k1t(this,e)}}function PHn(e,t){return function(){(t.apply(this,arguments)?S1t:k1t)(this,e)}}function $Hn(e,t){var n=x1t(e+"");if(arguments.length<2){for(var r=TSe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?PHn:t?AHn:RHn)(n,t))}function MHn(){this.textContent=""}function DHn(e){return function(){this.textContent=e}}function LHn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function FHn(e){return arguments.length?this.each(e==null?MHn:(typeof e=="function"?LHn:DHn)(e)):this.node().textContent}function zHn(){this.innerHTML=""}function BHn(e){return function(){this.innerHTML=e}}function UHn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function VHn(e){return arguments.length?this.each(e==null?zHn:(typeof e=="function"?UHn:BHn)(e)):this.node().innerHTML}function qHn(){this.nextSibling&&this.parentNode.appendChild(this)}function HHn(){return this.each(qHn)}function WHn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function ZHn(){return this.each(WHn)}function GHn(e){var t=typeof e=="function"?e:h1t(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function QHn(){return null}function YHn(e,t){var n=typeof e=="function"?e:h1t(e),r=t==null?QHn:typeof t=="function"?t:jSe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function KHn(){var e=this.parentNode;e&&e.removeChild(this)}function XHn(){return this.each(KHn)}function JHn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function eWn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function tWn(e){return this.select(e?eWn:JHn)}function nWn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function rWn(e){return function(t){e.call(this,t,this.__data__)}}function sWn(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function aWn(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,a;n<s;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++r]=a;++r?t.length=r:delete this.__on}}}function iWn(e,t,n){return function(){var r=this.__on,s,a=rWn(t);if(r){for(var i=0,l=r.length;i<l;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(s):this.__on=[s]}}function oWn(e,t,n){var r=sWn(e+""),s,a=r.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,u=l.length,d;c<u;++c)for(s=0,d=l[c];s<a;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?iWn:aWn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function O1t(e,t,n){var r=b1t(e),s=r.CustomEvent;typeof s=="function"?s=new s(t,n):(s=r.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function lWn(e,t){return function(){return O1t(this,e,t)}}function cWn(e,t){return function(){return O1t(this,e,t.apply(this,arguments))}}function uWn(e,t){return this.each((typeof t=="function"?cWn:lWn)(e,t))}function*dWn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length,i;s<a;++s)(i=r[s])&&(yield i)}var _1t=[null];function Hp(e,t){this._groups=e,this._parents=t}function $4(){return new Hp([[document.documentElement]],_1t)}function fWn(){return this}Hp.prototype=$4.prototype={constructor:Hp,select:Lqn,selectAll:Uqn,selectChild:Wqn,selectChildren:Yqn,filter:Kqn,data:rHn,enter:Xqn,exit:aHn,join:iHn,merge:oHn,selection:fWn,order:lHn,sort:cHn,call:dHn,nodes:fHn,node:pHn,size:hHn,empty:mHn,each:gHn,attr:kHn,style:EHn,property:IHn,classed:$Hn,text:FHn,html:VHn,raise:HHn,lower:ZHn,append:GHn,insert:YHn,remove:XHn,clone:tWn,datum:nWn,on:oWn,dispatch:uWn,[Symbol.iterator]:dWn};function Sp(e){return typeof e=="string"?new Hp([[document.querySelector(e)]],[document.documentElement]):new Hp([[e]],_1t)}function pWn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function rg(e,t){if(e=pWn(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}const hWn={passive:!1},SM={capture:!0,passive:!1};function Lee(e){e.stopImmediatePropagation()}function Hj(e){e.preventDefault(),e.stopImmediatePropagation()}function C1t(e){var t=e.document.documentElement,n=Sp(e).on("dragstart.drag",Hj,SM);"onselectstart"in t?n.on("selectstart.drag",Hj,SM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function E1t(e,t){var n=e.document.documentElement,r=Sp(e).on("dragstart.drag",null);t&&(r.on("click.drag",Hj,SM),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const Y6=e=>()=>e;function Pme(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:a,x:i,y:l,dx:c,dy:u,dispatch:d}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:d}})}Pme.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function mWn(e){return!e.ctrlKey&&!e.button}function gWn(){return this.parentNode}function vWn(e,t){return t??{x:e.x,y:e.y}}function yWn(){return navigator.maxTouchPoints||"ontouchstart"in this}function j1t(){var e=mWn,t=gWn,n=vWn,r=yWn,s={},a=gH("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,hWn).on("touchend.drag touchcancel.drag",S).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,_){if(!(d||!e.call(this,k,_))){var C=x(this,t.call(this,k,_),k,_,"mouse");C&&(Sp(k.view).on("mousemove.drag",m,SM).on("mouseup.drag",v,SM),C1t(k.view),Lee(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(Hj(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function v(k){Sp(k.view).on("mousemove.drag mouseup.drag",null),E1t(k.view,u),Hj(k),s.mouse("end",k)}function y(k,_){if(e.call(this,k,_)){var C=k.changedTouches,E=t.call(this,k,_),j=C.length,T,I;for(T=0;T<j;++T)(I=x(this,E,k,_,C[T].identifier,C[T]))&&(Lee(k),I("start",k,C[T]))}}function b(k){var _=k.changedTouches,C=_.length,E,j;for(E=0;E<C;++E)(j=s[_[E].identifier])&&(Hj(k),j("drag",k,_[E]))}function S(k){var _=k.changedTouches,C=_.length,E,j;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),E=0;E<C;++E)(j=s[_[E].identifier])&&(Lee(k),j("end",k,_[E]))}function x(k,_,C,E,j,T){var I=a.copy(),A=rg(T||C,_),R,L,M;if((M=n.call(k,new Pme("beforestart",{sourceEvent:C,target:p,identifier:j,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),E))!=null)return R=M.x-A[0]||0,L=M.y-A[1]||0,function z(H,F,B){var q=A,D;switch(H){case"start":s[j]=z,D=i++;break;case"end":delete s[j],--i;case"drag":A=rg(B||F,_),D=i;break}I.call(H,k,new Pme(H,{sourceEvent:F,subject:M,target:p,identifier:j,active:D,x:A[0]+R,y:A[1]+L,dx:A[0]-q[0],dy:A[1]-q[1],dispatch:I}),E)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:Y6(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:Y6(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:Y6(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:Y6(!!k),p):r},p.on=function(){var k=a.on.apply(a,arguments);return k===a?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function NSe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function T1t(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function M4(){}var kM=.7,fB=1/kM,Wj="\\s*([+-]?\\d+)\\s*",OM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ry="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",bWn=/^#([0-9a-f]{3,8})$/,xWn=new RegExp(`^rgb\\(${Wj},${Wj},${Wj}\\)$`),wWn=new RegExp(`^rgb\\(${ry},${ry},${ry}\\)$`),SWn=new RegExp(`^rgba\\(${Wj},${Wj},${Wj},${OM}\\)$`),kWn=new RegExp(`^rgba\\(${ry},${ry},${ry},${OM}\\)$`),OWn=new RegExp(`^hsl\\(${OM},${ry},${ry}\\)$`),_Wn=new RegExp(`^hsla\\(${OM},${ry},${ry},${OM}\\)$`),v8e={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};NSe(M4,WO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:y8e,formatHex:y8e,formatHex8:CWn,formatHsl:EWn,formatRgb:b8e,toString:b8e});function y8e(){return this.rgb().formatHex()}function CWn(){return this.rgb().formatHex8()}function EWn(){return N1t(this).formatHsl()}function b8e(){return this.rgb().formatRgb()}function WO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=bWn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?x8e(t):n===3?new pf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?K6(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?K6(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=xWn.exec(e))?new pf(t[1],t[2],t[3],1):(t=wWn.exec(e))?new pf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=SWn.exec(e))?K6(t[1],t[2],t[3],t[4]):(t=kWn.exec(e))?K6(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=OWn.exec(e))?k8e(t[1],t[2]/100,t[3]/100,1):(t=_Wn.exec(e))?k8e(t[1],t[2]/100,t[3]/100,t[4]):v8e.hasOwnProperty(e)?x8e(v8e[e]):e==="transparent"?new pf(NaN,NaN,NaN,0):null}function x8e(e){return new pf(e>>16&255,e>>8&255,e&255,1)}function K6(e,t,n,r){return r<=0&&(e=t=n=NaN),new pf(e,t,n,r)}function jWn(e){return e instanceof M4||(e=WO(e)),e?(e=e.rgb(),new pf(e.r,e.g,e.b,e.opacity)):new pf}function $me(e,t,n,r){return arguments.length===1?jWn(e):new pf(e,t,n,r??1)}function pf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}NSe(pf,$me,T1t(M4,{brighter(e){return e=e==null?fB:Math.pow(fB,e),new pf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?kM:Math.pow(kM,e),new pf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new pf(nO(this.r),nO(this.g),nO(this.b),pB(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:w8e,formatHex:w8e,formatHex8:TWn,formatRgb:S8e,toString:S8e}));function w8e(){return`#${Dk(this.r)}${Dk(this.g)}${Dk(this.b)}`}function TWn(){return`#${Dk(this.r)}${Dk(this.g)}${Dk(this.b)}${Dk((isNaN(this.opacity)?1:this.opacity)*255)}`}function S8e(){const e=pB(this.opacity);return`${e===1?"rgb(":"rgba("}${nO(this.r)}, ${nO(this.g)}, ${nO(this.b)}${e===1?")":`, ${e})`}`}function pB(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function nO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Dk(e){return e=nO(e),(e<16?"0":"")+e.toString(16)}function k8e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new ug(e,t,n,r)}function N1t(e){if(e instanceof ug)return new ug(e.h,e.s,e.l,e.opacity);if(e instanceof M4||(e=WO(e)),!e)return new ug;if(e instanceof ug)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),a=Math.max(t,n,r),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-r)/l+(n<r)*6:n===a?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new ug(i,l,c,e.opacity)}function NWn(e,t,n,r){return arguments.length===1?N1t(e):new ug(e,t,n,r??1)}function ug(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}NSe(ug,NWn,T1t(M4,{brighter(e){return e=e==null?fB:Math.pow(fB,e),new ug(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?kM:Math.pow(kM,e),new ug(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,s=2*n-r;return new pf(Fee(e>=240?e-240:e+120,s,r),Fee(e,s,r),Fee(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new ug(O8e(this.h),X6(this.s),X6(this.l),pB(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=pB(this.opacity);return`${e===1?"hsl(":"hsla("}${O8e(this.h)}, ${X6(this.s)*100}%, ${X6(this.l)*100}%${e===1?")":`, ${e})`}`}}));function O8e(e){return e=(e||0)%360,e<0?e+360:e}function X6(e){return Math.max(0,Math.min(1,e||0))}function Fee(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const ISe=e=>()=>e;function IWn(e,t){return function(n){return e+n*t}}function AWn(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function RWn(e){return(e=+e)==1?I1t:function(t,n){return n-t?AWn(t,n,e):ISe(isNaN(t)?n:t)}}function I1t(e,t){var n=t-e;return n?IWn(e,n):ISe(isNaN(e)?t:e)}const hB=(function e(t){var n=RWn(t);function r(s,a){var i=n((s=$me(s)).r,(a=$me(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=I1t(s.opacity,a.opacity);return function(d){return s.r=i(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function PWn(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(a){for(s=0;s<n;++s)r[s]=e[s]*(1-a)+t[s]*a;return r}}function $Wn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function MWn(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),a=new Array(n),i;for(i=0;i<r;++i)s[i]=cx(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<r;++i)a[i]=s[i](l);return a}}function DWn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function ag(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function LWn(e,t){var n={},r={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=cx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Mme=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,zee=new RegExp(Mme.source,"g");function FWn(e){return function(){return e}}function zWn(e){return function(t){return e(t)+""}}function A1t(e,t){var n=Mme.lastIndex=zee.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Mme.exec(e))&&(s=zee.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:ag(r,s)})),n=zee.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?zWn(c[0].x):FWn(t):(t=c.length,function(u){for(var d=0,f;d<t;++d)l[(f=c[d]).i]=f.x(u);return l.join("")})}function cx(e,t){var n=typeof t,r;return t==null||n==="boolean"?ISe(t):(n==="number"?ag:n==="string"?(r=WO(t))?(t=r,hB):A1t:t instanceof WO?hB:t instanceof Date?DWn:$Wn(t)?PWn:Array.isArray(t)?MWn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?LWn:ag)(e,t)}function ASe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var _8e=180/Math.PI,Dme={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function R1t(e,t,n,r,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*_8e,skewX:Math.atan(c)*_8e,scaleX:i,scaleY:l}}var J6;function BWn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Dme:R1t(t.a,t.b,t.c,t.d,t.e,t.f)}function UWn(e){return e==null||(J6||(J6=document.createElementNS("http://www.w3.org/2000/svg","g")),J6.setAttribute("transform",e),!(e=J6.transform.baseVal.consolidate()))?Dme:(e=e.matrix,R1t(e.a,e.b,e.c,e.d,e.e,e.f))}function P1t(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push("translate(",null,t,null,n);m.push({i:v-4,x:ag(u,f)},{i:v-2,x:ag(d,p)})}else(f||p)&&h.push("translate("+f+t+p+n)}function i(u,d,f,p){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),p.push({i:f.push(s(f)+"rotate(",null,r)-2,x:ag(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,p){u!==d?p.push({i:f.push(s(f)+"skewX(",null,r)-2,x:ag(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push(s(h)+"scale(",null,",",null,")");m.push({i:v-4,x:ag(u,f)},{i:v-2,x:ag(d,p)})}else(f!==1||p!==1)&&h.push(s(h)+"scale("+f+","+p+")")}return function(u,d){var f=[],p=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,p),i(u.rotate,d.rotate,f,p),l(u.skewX,d.skewX,f,p),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,p),u=d=null,function(h){for(var m=-1,v=p.length,y;++m<v;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var VWn=P1t(BWn,"px, ","px)","deg)"),qWn=P1t(UWn,", ",")",")"),HWn=1e-12;function C8e(e){return((e=Math.exp(e))+1/e)/2}function WWn(e){return((e=Math.exp(e))-1/e)/2}function ZWn(e){return((e=Math.exp(2*e))-1)/(e+1)}const j8=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],p=i[2],h=d-l,m=f-c,v=h*h+m*m,y,b;if(v<HWn)b=Math.log(p/u)/t,y=function(E){return[l+E*h,c+E*m,u*Math.exp(t*E*b)]};else{var S=Math.sqrt(v),x=(p*p-u*u+r*v)/(2*u*n*S),k=(p*p-u*u-r*v)/(2*p*n*S),_=Math.log(Math.sqrt(x*x+1)-x),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,y=function(E){var j=E*b,T=C8e(_),I=u/(n*S)*(T*ZWn(t*j+_)-WWn(_));return[l+I*h,c+I*m,u*T/C8e(t*j+_)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function GWn(e,t){t===void 0&&(t=e,e=cx);for(var n=0,r=t.length-1,s=t[0],a=new Array(r<0?0:r);n<r;)a[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return a[l](i-l)}}var BT=0,P2=0,yR=0,$1t=1e3,mB,$2,gB=0,ZO=0,yH=0,_M=typeof performance=="object"&&performance.now?performance:Date,M1t=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function RSe(){return ZO||(M1t(QWn),ZO=_M.now()+yH)}function QWn(){ZO=0}function vB(){this._call=this._time=this._next=null}vB.prototype=D1t.prototype={constructor:vB,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?RSe():+n)+(t==null?0:+t),!this._next&&$2!==this&&($2?$2._next=this:mB=this,$2=this),this._call=e,this._time=n,Lme()},stop:function(){this._call&&(this._call=null,this._time=1/0,Lme())}};function D1t(e,t,n){var r=new vB;return r.restart(e,t,n),r}function YWn(){RSe(),++BT;for(var e=mB,t;e;)(t=ZO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--BT}function E8e(){ZO=(gB=_M.now())+yH,BT=P2=0;try{YWn()}finally{BT=0,XWn(),ZO=0}}function KWn(){var e=_M.now(),t=e-gB;t>$1t&&(yH-=t,gB=e)}function XWn(){for(var e,t=mB,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:mB=n);$2=e,Lme(r)}function Lme(e){if(!BT){P2&&(P2=clearTimeout(P2));var t=e-ZO;t>24?(e<1/0&&(P2=setTimeout(E8e,e-_M.now()-yH)),yR&&(yR=clearInterval(yR))):(yR||(gB=_M.now(),yR=setInterval(KWn,$1t)),BT=1,M1t(E8e))}}function j8e(e,t,n){var r=new vB;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var JWn=gH("start","end","cancel","interrupt"),eZn=[],L1t=0,T8e=1,Fme=2,T8=3,N8e=4,zme=5,N8=6;function bH(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;tZn(e,n,{name:t,index:r,group:s,on:JWn,tween:eZn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:L1t})}function PSe(e,t){var n=Hg(e,t);if(n.state>L1t)throw new Error("too late; already scheduled");return n}function zy(e,t){var n=Hg(e,t);if(n.state>T8)throw new Error("too late; already running");return n}function Hg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function tZn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=D1t(a,0,n.time);function a(u){n.state=T8e,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,p,h;if(n.state!==T8e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===T8)return j8e(i);h.state===N8e?(h.state=N8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=N8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(j8e(function(){n.state===T8&&(n.state=N8e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Fme,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Fme){for(n.state=T8,s=new Array(p=n.tween.length),d=0,f=-1;d<p;++d)(h=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=h);s.length=f+1}}function l(u){for(var d=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(c),n.state=zme,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===zme&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=N8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function I8(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>Fme&&r.state<zme,r.state=N8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function nZn(e){return this.each(function(){I8(this,e)})}function rZn(e,t){var n,r;return function(){var s=zy(this,e),a=s.tween;if(a!==n){r=n=a;for(var i=0,l=r.length;i<l;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function sZn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=zy(this,e),i=a.tween;if(i!==r){s=(r=i).slice();for(var l={name:t,value:n},c=0,u=s.length;c<u;++c)if(s[c].name===t){s[c]=l;break}c===u&&s.push(l)}a.tween=s}}function aZn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Hg(this.node(),n).tween,s=0,a=r.length,i;s<a;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?rZn:sZn)(n,e,t))}function $Se(e,t,n){var r=e._id;return e.each(function(){var s=zy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Hg(s,r).value[t]}}function F1t(e,t){var n;return(typeof t=="number"?ag:t instanceof WO?hB:(n=WO(t))?(t=n,hB):A1t)(e,t)}function iZn(e){return function(){this.removeAttribute(e)}}function oZn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function lZn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===r?a:a=t(r=i,n)}}function cZn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?a:a=t(r=i,n)}}function uZn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function dZn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function fZn(e,t){var n=vH(e),r=n==="transform"?qWn:F1t;return this.attrTween(e,typeof t=="function"?(n.local?dZn:uZn)(n,r,$Se(this,"attr."+e,t)):t==null?(n.local?oZn:iZn)(n):(n.local?cZn:lZn)(n,r,t))}function pZn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function hZn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function mZn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&hZn(e,a)),n}return s._value=t,s}function gZn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&pZn(e,a)),n}return s._value=t,s}function vZn(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=vH(e);return this.tween(n,(r.local?mZn:gZn)(r,t))}function yZn(e,t){return function(){PSe(this,e).delay=+t.apply(this,arguments)}}function bZn(e,t){return t=+t,function(){PSe(this,e).delay=t}}function xZn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?yZn:bZn)(t,e)):Hg(this.node(),t).delay}function wZn(e,t){return function(){zy(this,e).duration=+t.apply(this,arguments)}}function SZn(e,t){return t=+t,function(){zy(this,e).duration=t}}function kZn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?wZn:SZn)(t,e)):Hg(this.node(),t).duration}function OZn(e,t){if(typeof t!="function")throw new Error;return function(){zy(this,e).ease=t}}function _Zn(e){var t=this._id;return arguments.length?this.each(OZn(t,e)):Hg(this.node(),t).ease}function CZn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;zy(this,e).ease=n}}function EZn(e){if(typeof e!="function")throw new Error;return this.each(CZn(this._id,e))}function jZn(e){typeof e!="function"&&(e=g1t(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Tx(r,this._parents,this._name,this._id)}function TZn(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,a=Math.min(r,s),i=new Array(r),l=0;l<a;++l)for(var c=t[l],u=n[l],d=c.length,f=i[l]=new Array(d),p,h=0;h<d;++h)(p=c[h]||u[h])&&(f[h]=p);for(;l<r;++l)i[l]=t[l];return new Tx(i,this._parents,this._name,this._id)}function NZn(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function IZn(e,t,n){var r,s,a=NZn(t)?PSe:zy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function AZn(e,t){var n=this._id;return arguments.length<2?Hg(this.node(),n).on.on(e):this.each(IZn(n,e,t))}function RZn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function PZn(){return this.on("end.remove",RZn(this._id))}function $Zn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=jSe(e));for(var r=this._groups,s=r.length,a=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=a[i]=new Array(c),d,f,p=0;p<c;++p)(d=l[p])&&(f=e.call(d,d.__data__,p,l))&&("__data__"in d&&(f.__data__=d.__data__),u[p]=f,bH(u[p],t,n,p,u,Hg(d,n)));return new Tx(a,this._parents,t,n)}function MZn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=m1t(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var p=e.call(d,d.__data__,f,c),h,m=Hg(d,n),v=0,y=p.length;v<y;++v)(h=p[v])&&bH(h,t,n,v,p,m);a.push(p),i.push(d)}return new Tx(a,i,t,n)}var DZn=$4.prototype.constructor;function LZn(){return new DZn(this._groups,this._parents)}function FZn(e,t){var n,r,s;return function(){var a=zT(this,e),i=(this.style.removeProperty(e),zT(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function z1t(e){return function(){this.style.removeProperty(e)}}function zZn(e,t,n){var r,s=n+"",a;return function(){var i=zT(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function BZn(e,t,n){var r,s,a;return function(){var i=zT(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),zT(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function UZn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=zy(this,e),u=c.on,d=c.value[a]==null?l||(l=z1t(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function VZn(e,t,n){var r=(e+="")=="transform"?VWn:F1t;return t==null?this.styleTween(e,FZn(e,r)).on("end.style."+e,z1t(e)):typeof t=="function"?this.styleTween(e,BZn(e,r,$Se(this,"style."+e,t))).each(UZn(this._id,e)):this.styleTween(e,zZn(e,r,t),n).on("end.style."+e,null)}function qZn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function HZn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&qZn(e,i,n)),r}return a._value=t,a}function WZn(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(t==null)return this.tween(r,null);if(typeof t!="function")throw new Error;return this.tween(r,HZn(e,t,n??""))}function ZZn(e){return function(){this.textContent=e}}function GZn(e){return function(){var t=e(this);this.textContent=t??""}}function QZn(e){return this.tween("text",typeof e=="function"?GZn($Se(this,"text",e)):ZZn(e==null?"":e+""))}function YZn(e){return function(t){this.textContent=e.call(this,t)}}function KZn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&YZn(s)),t}return r._value=e,r}function XZn(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,KZn(e))}function JZn(){for(var e=this._name,t=this._id,n=B1t(),r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=Hg(c,t);bH(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Tx(r,this._parents,e,n)}function eGn(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var u=zy(this,r),d=u.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),u.on=t}),s===0&&a()})}var tGn=0;function Tx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function B1t(){return++tGn}var yb=$4.prototype;Tx.prototype={constructor:Tx,select:$Zn,selectAll:MZn,selectChild:yb.selectChild,selectChildren:yb.selectChildren,filter:jZn,merge:TZn,selection:LZn,transition:JZn,call:yb.call,nodes:yb.nodes,node:yb.node,size:yb.size,empty:yb.empty,each:yb.each,on:AZn,attr:fZn,attrTween:vZn,style:VZn,styleTween:WZn,text:QZn,textTween:XZn,remove:PZn,tween:aZn,delay:xZn,duration:kZn,ease:_Zn,easeVarying:EZn,end:eGn,[Symbol.iterator]:yb[Symbol.iterator]};function nGn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var rGn={time:null,delay:0,duration:250,ease:nGn};function sGn(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function aGn(e){var t,n;e instanceof Tx?(t=e._id,e=e._name):(t=B1t(),(n=rGn).time=RSe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&bH(c,e,t,u,i,n||sGn(c,t));return new Tx(r,this._parents,e,t)}$4.prototype.interrupt=nZn;$4.prototype.transition=aGn;const eF=e=>()=>e;function iGn(e,{sourceEvent:t,target:n,transform:r,dispatch:s}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:s}})}function Kb(e,t,n){this.k=e,this.x=t,this.y=n}Kb.prototype={constructor:Kb,scale:function(e){return e===1?this:new Kb(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Kb(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var xH=new Kb(1,0,0);U1t.prototype=Kb.prototype;function U1t(e){for(;!e.__zoom;)if(!(e=e.parentNode))return xH;return e.__zoom}function Bee(e){e.stopImmediatePropagation()}function bR(e){e.preventDefault(),e.stopImmediatePropagation()}function oGn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function lGn(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function I8e(){return this.__zoom||xH}function cGn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function uGn(){return navigator.maxTouchPoints||"ontouchstart"in this}function dGn(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function V1t(){var e=oGn,t=lGn,n=dGn,r=cGn,s=uGn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=j8,u=gH("start","zoom","end"),d,f,p,h=500,m=150,v=0,y=10;function b(M){M.property("__zoom",I8e).on("wheel.zoom",j,{passive:!1}).on("mousedown.zoom",T).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(M,z,H,F){var B=M.selection?M.selection():M;B.property("__zoom",I8e),M!==B?_(M,z,H,F):B.interrupt().each(function(){C(this,arguments).event(F).start().zoom(null,typeof z=="function"?z.apply(this,arguments):z).end()})},b.scaleBy=function(M,z,H,F){b.scaleTo(M,function(){var B=this.__zoom.k,q=typeof z=="function"?z.apply(this,arguments):z;return B*q},H,F)},b.scaleTo=function(M,z,H,F){b.transform(M,function(){var B=t.apply(this,arguments),q=this.__zoom,D=H==null?k(B):typeof H=="function"?H.apply(this,arguments):H,G=q.invert(D),V=typeof z=="function"?z.apply(this,arguments):z;return n(x(S(q,V),D,G),B,i)},H,F)},b.translateBy=function(M,z,H,F){b.transform(M,function(){return n(this.__zoom.translate(typeof z=="function"?z.apply(this,arguments):z,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,F)},b.translateTo=function(M,z,H,F,B){b.transform(M,function(){var q=t.apply(this,arguments),D=this.__zoom,G=F==null?k(q):typeof F=="function"?F.apply(this,arguments):F;return n(xH.translate(G[0],G[1]).scale(D.k).translate(typeof z=="function"?-z.apply(this,arguments):-z,typeof H=="function"?-H.apply(this,arguments):-H),q,i)},F,B)};function S(M,z){return z=Math.max(a[0],Math.min(a[1],z)),z===M.k?M:new Kb(z,M.x,M.y)}function x(M,z,H){var F=z[0]-H[0]*M.k,B=z[1]-H[1]*M.k;return F===M.x&&B===M.y?M:new Kb(M.k,F,B)}function k(M){return[(+M[0][0]+ +M[1][0])/2,(+M[0][1]+ +M[1][1])/2]}function _(M,z,H,F){M.on("start.zoom",function(){C(this,arguments).event(F).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(F).end()}).tween("zoom",function(){var B=this,q=arguments,D=C(B,q).event(F),G=t.apply(B,q),V=H==null?k(G):typeof H=="function"?H.apply(B,q):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),U=B.__zoom,Z=typeof z=="function"?z.apply(B,q):z,K=c(U.invert(V).concat($/U.k),Z.invert(V).concat($/Z.k));return function(ne){if(ne===1)ne=Z;else{var te=K(ne),J=$/te[2];ne=new Kb(J,V[0]-te[0]*J,V[1]-te[1]*J)}D.zoom(null,ne)}})}function C(M,z,H){return!H&&M.__zooming||new E(M,z)}function E(M,z){this.that=M,this.args=z,this.active=0,this.sourceEvent=null,this.extent=t.apply(M,z),this.taps=0}E.prototype={event:function(M){return M&&(this.sourceEvent=M),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(M,z){return this.mouse&&M!=="mouse"&&(this.mouse[1]=z.invert(this.mouse[0])),this.touch0&&M!=="touch"&&(this.touch0[1]=z.invert(this.touch0[0])),this.touch1&&M!=="touch"&&(this.touch1[1]=z.invert(this.touch1[0])),this.that.__zoom=z,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(M){var z=Sp(this.that).datum();u.call(M,this.that,new iGn(M,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),z)}};function j(M,...z){if(!e.apply(this,arguments))return;var H=C(this,z).event(M),F=this.__zoom,B=Math.max(a[0],Math.min(a[1],F.k*Math.pow(2,r.apply(this,arguments)))),q=rg(M);if(H.wheel)(H.mouse[0][0]!==q[0]||H.mouse[0][1]!==q[1])&&(H.mouse[1]=F.invert(H.mouse[0]=q)),clearTimeout(H.wheel);else{if(F.k===B)return;H.mouse=[q,F.invert(q)],I8(this),H.start()}bR(M),H.wheel=setTimeout(D,m),H.zoom("mouse",n(x(S(F,B),H.mouse[0],H.mouse[1]),H.extent,i));function D(){H.wheel=null,H.end()}}function T(M,...z){if(p||!e.apply(this,arguments))return;var H=M.currentTarget,F=C(this,z,!0).event(M),B=Sp(M.view).on("mousemove.zoom",V,!0).on("mouseup.zoom",$,!0),q=rg(M,H),D=M.clientX,G=M.clientY;C1t(M.view),Bee(M),F.mouse=[q,this.__zoom.invert(q)],I8(this),F.start();function V(U){if(bR(U),!F.moved){var Z=U.clientX-D,K=U.clientY-G;F.moved=Z*Z+K*K>v}F.event(U).zoom("mouse",n(x(F.that.__zoom,F.mouse[0]=rg(U,H),F.mouse[1]),F.extent,i))}function $(U){B.on("mousemove.zoom mouseup.zoom",null),E1t(U.view,F.moved),bR(U),F.event(U).end()}}function I(M,...z){if(e.apply(this,arguments)){var H=this.__zoom,F=rg(M.changedTouches?M.changedTouches[0]:M,this),B=H.invert(F),q=H.k*(M.shiftKey?.5:2),D=n(x(S(H,q),F,B),t.apply(this,z),i);bR(M),l>0?Sp(this).transition().duration(l).call(_,D,F,M):Sp(this).call(b.transform,D,F,M)}}function A(M,...z){if(e.apply(this,arguments)){var H=M.touches,F=H.length,B=C(this,z,M.changedTouches.length===F).event(M),q,D,G,V;for(Bee(M),D=0;D<F;++D)G=H[D],V=rg(G,this),V=[V,this.__zoom.invert(V),G.identifier],B.touch0?!B.touch1&&B.touch0[2]!==V[2]&&(B.touch1=V,B.taps=0):(B.touch0=V,q=!0,B.taps=1+!!d);d&&(d=clearTimeout(d)),q&&(B.taps<2&&(f=V[0],d=setTimeout(function(){d=null},h)),I8(this),B.start())}}function R(M,...z){if(this.__zooming){var H=C(this,z).event(M),F=M.changedTouches,B=F.length,q,D,G,V;for(bR(M),q=0;q<B;++q)D=F[q],G=rg(D,this),H.touch0&&H.touch0[2]===D.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===D.identifier&&(H.touch1[0]=G);if(D=H.that.__zoom,H.touch1){var $=H.touch0[0],U=H.touch0[1],Z=H.touch1[0],K=H.touch1[1],ne=(ne=Z[0]-$[0])*ne+(ne=Z[1]-$[1])*ne,te=(te=K[0]-U[0])*te+(te=K[1]-U[1])*te;D=S(D,Math.sqrt(ne/te)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],V=[(U[0]+K[0])/2,(U[1]+K[1])/2]}else if(H.touch0)G=H.touch0[0],V=H.touch0[1];else return;H.zoom("touch",n(x(D,G,V),H.extent,i))}}function L(M,...z){if(this.__zooming){var H=C(this,z).event(M),F=M.changedTouches,B=F.length,q,D;for(Bee(M),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),q=0;q<B;++q)D=F[q],H.touch0&&H.touch0[2]===D.identifier?delete H.touch0:H.touch1&&H.touch1[2]===D.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(D=rg(D,this),Math.hypot(f[0]-D[0],f[1]-D[1])<y)){var G=Sp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(M){return arguments.length?(r=typeof M=="function"?M:eF(+M),b):r},b.filter=function(M){return arguments.length?(e=typeof M=="function"?M:eF(!!M),b):e},b.touchable=function(M){return arguments.length?(s=typeof M=="function"?M:eF(!!M),b):s},b.extent=function(M){return arguments.length?(t=typeof M=="function"?M:eF([[+M[0][0],+M[0][1]],[+M[1][0],+M[1][1]]]),b):t},b.scaleExtent=function(M){return arguments.length?(a[0]=+M[0],a[1]=+M[1],b):[a[0],a[1]]},b.translateExtent=function(M){return arguments.length?(i[0][0]=+M[0][0],i[1][0]=+M[1][0],i[0][1]=+M[0][1],i[1][1]=+M[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(M){return arguments.length?(n=M,b):n},b.duration=function(M){return arguments.length?(l=+M,b):l},b.interpolate=function(M){return arguments.length?(c=M,b):c},b.on=function(){var M=u.on.apply(u,arguments);return M===u?b:M},b.clickDistance=function(M){return arguments.length?(v=(M=+M)*M,b):Math.sqrt(v)},b.tapDistance=function(M){return arguments.length?(y=+M,b):y},b}const by={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},CM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],q1t=["Enter"," ","Escape"],H1t={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var UT;(function(e){e.Strict="strict",e.Loose="loose"})(UT||(UT={}));var rO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(rO||(rO={}));var EM;(function(e){e.Partial="partial",e.Full="full"})(EM||(EM={}));const W1t={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var dw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(dw||(dw={}));var jM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(jM||(jM={}));var sr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(sr||(sr={}));const A8e={[sr.Left]:sr.Right,[sr.Right]:sr.Left,[sr.Top]:sr.Bottom,[sr.Bottom]:sr.Top};function Z1t(e){return e===null?null:e?"valid":"invalid"}const G1t=e=>"id"in e&&"source"in e&&"target"in e,fGn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),MSe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),D4=(e,t=[0,0])=>{const{width:n,height:r}=Xx(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},pGn=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):MSe(s)?s:t.nodeLookup.get(s.id));const l=i?yB(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return wH(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return SH(n)},L4=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=wH(n,yB(s)),r=!0)}),r?SH(n):{x:0,y:0,width:0,height:0}},DSe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...z4(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:p=!1}=u;if(i&&!f||p)continue;const h=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=TM(l,qT(u)),y=(h??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},hGn=(e,t)=>{const n=new Set;return e.forEach(r=>{n.add(r.id)}),t.filter(r=>n.has(r.source)||n.has(r.target))};function mGn(e,t){const n=new Map,r=t?.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{s.measured.width&&s.measured.height&&(t?.includeHiddenNodes||!s.hidden)&&(!r||r.has(s.id))&&n.set(s.id,s)}),n}async function gGn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=mGn(e,i),c=L4(l),u=LSe(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function Q1t({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=i.origin??r;let f=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",by.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&HT(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const p=HT(f)?GO(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",by.error015()),{position:{x:p.x-c+(i.measured.width??0)*d[0],y:p.y-u+(i.measured.height??0)*d[1]},positionAbsolute:p}}async function vGn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=a.has(p.id),m=!h&&p.parentId&&i.find(v=>v.id===p.parentId);(h||m)&&i.push(p)}const l=new Set(t.map(p=>p.id)),c=r.filter(p=>p.deletable!==!1),d=hGn(i,c);for(const p of c)l.has(p.id)&&!d.find(m=>m.id===p.id)&&d.push(p);if(!s)return{edges:d,nodes:i};const f=await s({nodes:i,edges:d});return typeof f=="boolean"?f?{edges:d,nodes:i}:{edges:[],nodes:[]}:f}const VT=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),GO=(e={x:0,y:0},t,n)=>({x:VT(e.x,t[0][0],t[1][0]-(n?.width??0)),y:VT(e.y,t[0][1],t[1][1]-(n?.height??0))});function Y1t(e,t,n){const{width:r,height:s}=Xx(n),{x:a,y:i}=n.internals.positionAbsolute;return GO(e,[[a,i],[a+r,i+s]],t)}const R8e=(e,t,n)=>e<t?VT(Math.abs(e-t),1,t)/t:e>n?-VT(Math.abs(e-n),1,t)/t:0,K1t=(e,t,n=15,r=40)=>{const s=R8e(e.x,r,t.width-r)*n,a=R8e(e.y,r,t.height-r)*n;return[s,a]},wH=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Bme=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),SH=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),qT=(e,t=[0,0])=>{const{x:n,y:r}=MSe(e)?e.internals.positionAbsolute:D4(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},yB=(e,t=[0,0])=>{const{x:n,y:r}=MSe(e)?e.internals.positionAbsolute:D4(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},X1t=(e,t)=>SH(wH(Bme(e),Bme(t))),TM=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},P8e=e=>gg(e.width)&&gg(e.height)&&gg(e.x)&&gg(e.y),gg=e=>!isNaN(e)&&isFinite(e),yGn=(e,t)=>{},F4=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),z4=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?F4(l,i):l},bB=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function cE(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function bGn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=cE(e,n),s=cE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=cE(e.top??e.y??0,n),s=cE(e.bottom??e.y??0,n),a=cE(e.left??e.x??0,t),i=cE(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:a,x:a+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function xGn(e,t,n,r,s,a){const{x:i,y:l}=bB(e,[t,n,r]),{x:c,y:u}=bB({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const LSe=(e,t,n,r,s,a)=>{const i=bGn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=VT(u,r,s),f=e.x+e.width/2,p=e.y+e.height/2,h=t/2-f*d,m=n/2-p*d,v=xGn(e,h,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},NM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function HT(e){return e!=null&&e!=="parent"}function Xx(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function J1t(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function eSt(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function $8e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function wGn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function SGn(e){return{...H1t,...e||{}}}function pP(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=vg(e),l=z4({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?F4(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const FSe=e=>({width:e.offsetWidth,height:e.offsetHeight}),tSt=e=>e?.getRootNode?.()||window?.document,kGn=["INPUT","SELECT","TEXTAREA"];function nSt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:kGn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const rSt=e=>"clientX"in e,vg=(e,t)=>{const n=rSt(e),r=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:s-(t?.top??0)}},M8e=(e,t,n,r,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...FSe(i)}})};function sSt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function tF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function D8e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case sr.Left:return[t-tF(t-r,a),n];case sr.Right:return[t+tF(r-t,a),n];case sr.Top:return[t,n-tF(n-s,a)];case sr.Bottom:return[t,n+tF(s-n,a)]}}function zSe({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,curvature:i=.25}){const[l,c]=D8e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=D8e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=sSt({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,p,h,m]}function aSt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function OGn({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return r;const i=s&&n?r+1e3:r,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function _Gn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=wH(yB(e),yB(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return TM(i,SH(a))>0}const CGn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,EGn=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),jGn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||CGn;let s;return G1t(e)?s={...e}:s={...e,id:r(e)},EGn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function iSt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=aSt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const L8e={[sr.Left]:{x:-1,y:0},[sr.Right]:{x:1,y:0},[sr.Top]:{x:0,y:-1},[sr.Bottom]:{x:0,y:1}},TGn=({source:e,sourcePosition:t=sr.Bottom,target:n})=>t===sr.Left||t===sr.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},F8e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function NGn({source:e,sourcePosition:t=sr.Bottom,target:n,targetPosition:r=sr.Top,center:s,offset:a,stepPosition:i}){const l=L8e[t],c=L8e[r],u={x:e.x+l.x*a,y:e.y+l.y*a},d={x:n.x+c.x*a,y:n.y+c.y*a},f=TGn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],v,y;const b={x:0,y:0},S={x:0,y:0},[,,x,k]=aSt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const j=[{x:v,y:u.y},{x:v,y:d.y}],T=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?j:T:m=p==="x"?T:j}else{const j=[{x:u.x,y:d.y}],T=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?T:j:m=l.y===h?j:T,t===r){const M=Math.abs(e[p]-n[p]);if(M<=a){const z=Math.min(a-1,a-M);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*z:S[p]=(d[p]>n[p]?-1:1)*z}}if(t!==r){const M=p==="x"?"y":"x",z=l[p]===c[M],H=u[M]>d[M],F=u[M]<d[M];(l[p]===1&&(!z&&H||z&&F)||l[p]!==1&&(!z&&F||z&&H))&&(m=p==="x"?j:T)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+S.x,y:d.y+S.y},R=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));R>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const _={x:u.x+b.x,y:u.y+b.y},C={x:d.x+S.x,y:d.y+S.y};return[[e,..._.x!==m[0].x||_.y!==m[0].y?[_]:[],...m,...C.x!==m[m.length-1].x||C.y!==m[m.length-1].y?[C]:[],n],v,y,x,k]}function IGn(e,t,n,r){const s=Math.min(F8e(e,t)/2,F8e(t,n)/2,r),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${a+s*u},${i}Q ${a},${i} ${a},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function Ume({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,v]=NGn({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:a,center:{x:l,y:c},offset:u,stepPosition:d});let y=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)y+=IGn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,p,h,m,v]}function z8e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function AGn(e){const{sourceNode:t,targetNode:n}=e;if(!z8e(t)||!z8e(n))return null;const r=t.internals.handleBounds||B8e(t.handles),s=n.internals.handleBounds||B8e(n.handles),a=U8e(r?.source??[],e.sourceHandle),i=U8e(e.connectionMode===UT.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",by.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||sr.Bottom,c=i?.position||sr.Top,u=QO(t,a,l),d=QO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function B8e(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,r.type==="source"?t.push(r):r.type==="target"&&n.push(r);return{source:t,target:n}}function QO(e,t,n=sr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??Xx(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case sr.Top:return{x:s+i/2,y:a};case sr.Right:return{x:s+i,y:a+l/2};case sr.Bottom:return{x:s+i/2,y:a+l};case sr.Left:return{x:s,y:a+l/2}}}function U8e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Vme(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function RGn(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=Vme(c,t);a.has(u)||(i.push({id:u,color:c.color||n,...c}),a.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const oSt=1e3,PGn=10,BSe={nodeOrigin:[0,0],nodeExtent:CM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},$Gn={...BSe,checkEquality:!0};function USe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function MGn(e,t,n){const r=USe(BSe,n);for(const s of e.values())if(s.parentId)qSe(s,e,t,r);else{const a=D4(s,r.nodeOrigin),i=HT(s.extent)?s.extent:r.nodeExtent,l=GO(a,i,Xx(s));s.internals.positionAbsolute=l}}function DGn(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&r.push(a)}return{source:n,target:r}}function VSe(e){return e==="manual"}function qme(e,t,n,r={}){const s=USe($Gn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!VSe(s.zIndexMode)?oSt:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=i.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const p=D4(d,s.nodeOrigin),h=HT(d.extent)?d.extent:s.nodeExtent,m=GO(p,h,Xx(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:DGn(d,f),z:lSt(d,l,s.zIndexMode),userNode:d}},t.set(d.id,f)}(f.measured===void 0||f.measured.width===void 0||f.measured.height===void 0)&&!f.hidden&&(c=!1),d.parentId&&qSe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function LGn(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function qSe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=USe(BSe,r),u=e.parentId,d=t.get(u);if(!d){console.warn(`Parent node ${u} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}LGn(e,n),s&&!d.parentId&&d.internals.rootParentIndex===void 0&&c==="auto"&&(d.internals.rootParentIndex=++s.i,d.internals.z=d.internals.z+s.i*PGn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!VSe(c)?oSt:0,{x:p,y:h,z:m}=FGn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=p!==v.x||h!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:v,z:m}})}function lSt(e,t,n){const r=gg(e.zIndex)?e.zIndex:0;return VSe(n)?r:r+(e.selected?t:0)}function FGn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=Xx(e),u=D4(e,n),d=HT(e.extent)?GO(u,e.extent,c):u;let f=GO({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=Y1t(f,c,t));const p=lSt(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function HSe(e,t,n,r=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??qT(l),u=X1t(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=Xx(l),f=l.origin??r,p=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,h=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(p>0||h>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+y,y:l.position.y-h+b}}),n.get(c)?.forEach(S=>{e.some(x=>x.id===S.id)||s.push({id:S.id,type:"position",position:{x:S.position.x+p,y:S.position.y+h}})})),(d.width<i.width||d.height<i.height||p||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(p?f[0]*p-y:0),height:v+(h?f[1]*h-b:0)}})}),s}function zGn(e,t,n,r,s,a,i){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),p=[];for(const h of e.values()){const m=t.get(h.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=FSe(h.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||h.force))){const S=h.nodeElement.getBoundingClientRect(),x=HT(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=Y1t(k,v,t.get(m.parentId)):x&&(k=GO(k,x,v));const _={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:M8e("source",h.nodeElement,S,f,m.id),target:M8e("target",h.nodeElement,S,f,m.id)}}};t.set(m.id,_),m.parentId&&qSe(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:qT(_,s)}))}}if(p.length>0){const h=HSe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function BGn({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function V8e(e,t,n,r,s,a){let i=s;const l=r.get(i)||new Map;r.set(i,l.set(n,t)),i=`${s}-${e}`;const c=r.get(i)||new Map;if(r.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function cSt(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;V8e("source",c,d,e,s,i),V8e("target",c,u,e,a,l),t.set(r.id,r)}}function uSt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:uSt(n,t):!1}function q8e(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function UGn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!uSt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function Uee({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:s[0],s]}function VGn({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:r-s.distance.y},i=F4(a,t);return{x:i.x-a.x,y:i.y-a.y}}function qGn({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,p=null,h=!1,m=!1,v=null;function y({noDragClassName:S,handleSelector:x,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:E=0}){p=Sp(k);function j({x:R,y:L}){const{nodeLookup:M,nodeExtent:z,snapGrid:H,snapToGrid:F,nodeOrigin:B,onNodeDrag:q,onSelectionDrag:D,onError:G,updateNodePositions:V}=t();a={x:R,y:L};let $=!1;const U=l.size>1,Z=U&&z?Bme(L4(l)):null,K=U&&F?VGn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[ne,te]of l){if(!M.has(ne))continue;let J={x:R-te.distance.x,y:L-te.distance.y};F&&(J=K?{x:Math.round(J.x+K.x),y:Math.round(J.y+K.y)}:F4(J,H));let ae=null;if(U&&z&&!te.extent&&Z){const{positionAbsolute:ee}=te.internals,ce=ee.x-Z.x+z[0][0],de=ee.x+te.measured.width-Z.x2+z[1][0],oe=ee.y-Z.y+z[0][1],me=ee.y+te.measured.height-Z.y2+z[1][1];ae=[[ce,oe],[de,me]]}const{position:pe,positionAbsolute:Y}=Q1t({nodeId:ne,nextPosition:J,nodeLookup:M,nodeExtent:ae||z,nodeOrigin:B,onError:G});$=$||te.position.x!==pe.x||te.position.y!==pe.y,te.position=pe,te.internals.positionAbsolute=Y}if(m=m||$,!!$&&(V(l,!0),v&&(r||q||!C&&D))){const[ne,te]=Uee({nodeId:C,dragItems:l,nodeLookup:M});r?.(v,l,ne,te),q?.(v,ne,te),C||D?.(v,te)}}async function T(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:M,autoPanOnNodeDrag:z}=t();if(!z){c=!1,cancelAnimationFrame(i);return}const[H,F]=K1t(u,d,M);(H!==0||F!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-F/R[2],await L({x:H,y:F})&&j(a)),i=requestAnimationFrame(T)}function I(R){const{nodeLookup:L,multiSelectionActive:M,nodesDraggable:z,transform:H,snapGrid:F,snapToGrid:B,selectNodesOnDrag:q,onNodeDragStart:D,onSelectionDragStart:G,unselectNodesAndEdges:V}=t();f=!0,(!q||!_)&&!M&&C&&(L.get(C)?.selected||V()),_&&q&&C&&e?.(C);const $=pP(R.sourceEvent,{transform:H,snapGrid:F,snapToGrid:B,containerBounds:d});if(a=$,l=UGn(L,z,$,C),l.size>0&&(n||D||!C&&G)){const[U,Z]=Uee({nodeId:C,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,U,Z),D?.(R.sourceEvent,U,Z),C||G?.(R.sourceEvent,Z)}}const A=j1t().clickDistance(E).on("start",R=>{const{domNode:L,nodeDragThreshold:M,transform:z,snapGrid:H,snapToGrid:F}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,v=R.sourceEvent,M===0&&I(R),a=pP(R.sourceEvent,{transform:z,snapGrid:H,snapToGrid:F,containerBounds:d}),u=vg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:M,snapGrid:z,snapToGrid:H,nodeDragThreshold:F,nodeLookup:B}=t(),q=pP(R.sourceEvent,{transform:M,snapGrid:z,snapToGrid:H,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||C&&!B.has(C))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,T()),!f){const D=vg(R.sourceEvent,d),G=D.x-u.x,V=D.y-u.y;Math.sqrt(G*G+V*V)>F&&I(R)}(a.x!==q.xSnapped||a.y!==q.ySnapped)&&l&&f&&(u=vg(R.sourceEvent,d),j(q))}}).on("end",R=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:M,onNodeDragStop:z,onSelectionDragStop:H}=t();if(m&&(M(l,!1),m=!1),s||z||!C&&H){const[F,B]=Uee({nodeId:C,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,F,B),z?.(R.sourceEvent,F,B),C||H?.(R.sourceEvent,B)}}}).filter(R=>{const L=R.target;return!R.button&&(!S||!q8e(L,`.${S}`,k))&&(!x||q8e(L,x,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function HGn(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())TM(s,qT(a))>0&&r.push(a);return r}const WGn=250;function ZGn(e,t,n,r){let s=[],a=1/0;const i=HGn(e,n,t+WGn);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const u of c){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:d,y:f}=QO(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<a?(s=[{...u,x:d,y:f}],a=p):p===a&&s.push({...u,x:d,y:f}))}}if(!s.length)return null;if(s.length>1){const l=r.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function dSt(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...QO(i,c,c.position,!0)}:c}function fSt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function GGn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const pSt=()=>!0;function QGn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=pSt,onReconnectEnd:S,updateConnection:x,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:E=1,handleDomNode:j}){const T=tSt(e.target);let I=0,A;const{x:R,y:L}=vg(e),M=fSt(a,j),z=l?.getBoundingClientRect();let H=!1;if(!z||!M)return;const F=dSt(s,M,r,c,t);if(!F)return;let B=vg(e,z),q=!1,D=null,G=!1,V=null;function $(){if(!d||!z)return;const[pe,Y]=K1t(B,z,C);p({x:pe,y:Y}),I=requestAnimationFrame($)}const U={...F,nodeId:s,type:M,position:F.position},Z=c.get(s);let ne={inProgress:!0,isValid:null,from:QO(Z,U,sr.Left,!0),fromHandle:U,fromPosition:U.position,fromNode:Z,to:B,toHandle:null,toPosition:A8e[U.position],toNode:null,pointer:B};function te(){H=!0,x(ne),m?.(e,{nodeId:s,handleId:r,handleType:M})}E===0&&te();function J(pe){if(!H){const{x:me,y:be}=vg(pe),we=me-R,Te=be-L;if(!(we*we+Te*Te>E*E))return;te()}if(!_()||!U){ae(pe);return}const Y=k();B=vg(pe,z),A=ZGn(z4(B,Y,!1,[1,1]),n,c,U),q||($(),q=!0);const ee=hSt(pe,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:T,lib:u,flowId:f,nodeLookup:c});V=ee.handleDomNode,D=ee.connection,G=GGn(!!A,ee.isValid);const ce=c.get(s),de=ce?QO(ce,U,sr.Left,!0):ne.from,oe={...ne,from:de,isValid:G,to:ee.toHandle&&G?bB({x:ee.toHandle.x,y:ee.toHandle.y},Y):B,toHandle:ee.toHandle,toPosition:G&&ee.toHandle?ee.toHandle.position:A8e[U.position],toNode:ee.toHandle?c.get(ee.toHandle.nodeId):null,pointer:B};x(oe),ne=oe}function ae(pe){if(!("touches"in pe&&pe.touches.length>0)){if(H){(A||V)&&D&&G&&v?.(D);const{inProgress:Y,...ee}=ne,ce={...ee,toPosition:ne.toHandle?ne.toPosition:null};y?.(pe,ce),a&&S?.(pe,ce)}h(),cancelAnimationFrame(I),q=!1,G=!1,D=null,V=null,T.removeEventListener("mousemove",J),T.removeEventListener("mouseup",ae),T.removeEventListener("touchmove",J),T.removeEventListener("touchend",ae)}}T.addEventListener("mousemove",J),T.addEventListener("mouseup",ae),T.addEventListener("touchmove",J),T.addEventListener("touchend",ae)}function hSt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=pSt,nodeLookup:d}){const f=a==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=vg(e),v=i.elementFromPoint(h,m),y=v?.classList.contains(`${l}-flow__handle`)?v:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const S=fSt(void 0,y),x=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),_=y.classList.contains("connectable"),C=y.classList.contains("connectableend");if(!x||!S)return b;const E={source:f?x:r,sourceHandle:f?k:s,target:f?r:x,targetHandle:f?s:k};b.connection=E;const T=_&&C&&(n===UT.Strict?f&&S==="source"||!f&&S==="target":x!==r||k!==s);b.isValid=T&&u(E),b.toHandle=dSt(x,S,k,d,n,!0)}return b}const Hme={onPointerDown:QGn,isValid:hSt};function YGn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Sp(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=x=>{if(x.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=x.sourceEvent.ctrlKey&&NM()?10:1,C=-x.sourceEvent.deltaY*(x.sourceEvent.deltaMode===1?.05:x.sourceEvent.deltaMode?1:.002)*d,E=k[2]*Math.pow(2,C*_);t.scaleTo(E)};let v=[0,0];const y=x=>{(x.sourceEvent.type==="mousedown"||x.sourceEvent.type==="touchstart")&&(v=[x.sourceEvent.clientX??x.sourceEvent.touches[0].clientX,x.sourceEvent.clientY??x.sourceEvent.touches[0].clientY])},b=x=>{const k=n();if(x.sourceEvent.type!=="mousemove"&&x.sourceEvent.type!=="touchmove"||!t)return;const _=[x.sourceEvent.clientX??x.sourceEvent.touches[0].clientX,x.sourceEvent.clientY??x.sourceEvent.touches[0].clientY],C=[_[0]-v[0],_[1]-v[1]];v=_;const E=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),j={x:k[0]-C[0]*E,y:k[1]-C[1]*E},T=[[0,0],[c,u]];t.setViewportConstrained({x:j.x,y:j.y,zoom:k[2]},T,l)},S=V1t().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(S,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:rg}}const kH=e=>({x:e.x,y:e.y,zoom:e.k}),Vee=({x:e,y:t,zoom:n})=>xH.translate(e,t).scale(n),fj=(e,t)=>e.target.closest(`.${t}`),mSt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),KGn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,qee=(e,t=0,n=KGn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},gSt=e=>{const t=e.ctrlKey&&NM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function XGn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(fj(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const y=rg(d),b=gSt(d),S=f*Math.pow(2,b);r.scaleTo(n,S,y,d);return}const p=d.deltaMode===1?20:1;let h=s===rO.Vertical?0:d.deltaX*p,m=s===rO.Horizontal?0:d.deltaY*p;!NM()&&d.shiftKey&&s!==rO.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const v=kH(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,v),e.panScrollTimeout=setTimeout(()=>{u?.(d,v),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,v))}}function JGn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=fj(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function eQn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=kH(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=s,r.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(r.sourceEvent,s)}}function tQn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&mSt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,kH(a.transform))}}function nQn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&mSt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=kH(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function rQn({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const p=e||t,h=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(fj(f,`${u}-flow__node`)||fj(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||fj(f,l)&&m||fj(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!p&&!s&&!h&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function sQn({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),f=V1t().scaleExtent([t,n]).translateExtent(r),p=Sp(e).call(f);S({x:s.x,y:s.y,zoom:VT(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(gSt);function v(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?cx:j8).transform(qee(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:M,panOnScroll:z,panOnDrag:H,panOnScrollMode:F,panOnScrollSpeed:B,preventScrolling:q,zoomOnPinch:D,zoomOnScroll:G,zoomOnDoubleClick:V,zoomActivationKeyPressed:$,lib:U,onTransformChange:Z,connectionInProgress:K,paneClickDistance:ne,selectionOnDrag:te}){M&&!u.isZoomingOrPanning&&b();const J=z&&!$&&!M;f.clickDistance(te?1/0:!gg(ne)||ne<0?0:ne);const ae=J?XGn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:F,panOnScrollSpeed:B,zoomOnPinch:D,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):JGn({noWheelClassName:A,preventScrolling:q,d3ZoomHandler:h});if(p.on("wheel.zoom",ae,{passive:!1}),!M){const Y=eQn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",Y);const ee=tQn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",ee);const ce=nQn({zoomPanValues:u,panOnDrag:H,panOnScroll:z,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",ce)}const pe=rQn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:z,zoomOnDoubleClick:V,zoomOnPinch:D,userSelectionActive:M,noPanClassName:R,noWheelClassName:A,lib:U,connectionInProgress:K});f.filter(pe),V?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function S(A,R,L){const M=Vee(A),z=f?.constrain()(M,R,L);return z&&await v(z),new Promise(H=>H(z))}async function x(A,R){const L=Vee(A);return await v(L,R),new Promise(M=>M(L))}function k(A){if(p){const R=Vee(A),L=p.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(p,R,null,{sync:!0})}}function _(){const A=p?U1t(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?cx:j8).scaleTo(qee(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?cx:j8).scaleBy(qee(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function j(A){f?.scaleExtent(A)}function T(A){f?.translateExtent(A)}function I(A){const R=!gg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:x,setViewportConstrained:S,getViewport:_,scaleTo:C,scaleBy:E,setScaleExtent:j,setTranslateExtent:T,syncViewport:k,setClickDistance:I}}var WT;(function(e){e.Line="line",e.Handle="handle"})(WT||(WT={}));function aQn({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:a}){const i=e-t,l=n-r,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function H8e(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:s}}function q0(e,t){return Math.max(0,t-e)}function H0(e,t){return Math.max(0,e-t)}function nF(e,t,n){return Math.max(0,t-e,e-n)}function W8e(e,t){return e?!t:t}function iQn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:S}=r,{x,y:k,width:_,height:C,aspectRatio:E}=e;let j=Math.floor(d?h-e.pointerX:0),T=Math.floor(f?m-e.pointerY:0);const I=_+(c?-j:j),A=C+(u?-T:T),R=-a[0]*_,L=-a[1]*C;let M=nF(I,v,y),z=nF(A,b,S);if(i){let B=0,q=0;c&&j<0?B=q0(x+j+R,i[0][0]):!c&&j>0&&(B=H0(x+I+R,i[1][0])),u&&T<0?q=q0(k+T+L,i[0][1]):!u&&T>0&&(q=H0(k+A+L,i[1][1])),M=Math.max(M,B),z=Math.max(z,q)}if(l){let B=0,q=0;c&&j>0?B=H0(x+j,l[0][0]):!c&&j<0&&(B=q0(x+I,l[1][0])),u&&T>0?q=H0(k+T,l[0][1]):!u&&T<0&&(q=q0(k+A,l[1][1])),M=Math.max(M,B),z=Math.max(z,q)}if(s){if(d){const B=nF(I/E,b,S)*E;if(M=Math.max(M,B),i){let q=0;!c&&!u||c&&!u&&p?q=H0(k+L+I/E,i[1][1])*E:q=q0(k+L+(c?j:-j)/E,i[0][1])*E,M=Math.max(M,q)}if(l){let q=0;!c&&!u||c&&!u&&p?q=q0(k+I/E,l[1][1])*E:q=H0(k+(c?j:-j)/E,l[0][1])*E,M=Math.max(M,q)}}if(f){const B=nF(A*E,v,y)/E;if(z=Math.max(z,B),i){let q=0;!c&&!u||u&&!c&&p?q=H0(x+A*E+R,i[1][0])/E:q=q0(x+(u?T:-T)*E+R,i[0][0])/E,z=Math.max(z,q)}if(l){let q=0;!c&&!u||u&&!c&&p?q=q0(x+A*E,l[1][0])/E:q=H0(x+(u?T:-T)*E,l[0][0])/E,z=Math.max(z,q)}}}T=T+(T<0?z:-z),j=j+(j<0?M:-M),s&&(p?I>A*E?T=(W8e(c,u)?-j:j)/E:j=(W8e(c,u)?-T:T)*E:d?(T=j/E,u=c):(j=T*E,c=u));const H=c?x+j:x,F=u?k+T:k;return{width:_+(c?-j:j),height:C+(u?-T:T),x:a[0]*j*(c?-1:1)+H,y:a[1]*T*(u?-1:1)+F}}const vSt={width:0,height:0,x:0,y:0},oQn={...vSt,pointerX:0,pointerY:0,aspectRatio:1};function lQn(e){return[[0,0],[e.measured.width,e.measured.height]]}function cQn(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[r-l,s-c],[r+a-l,s+i-c]]}function uQn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Sp(e);let i={controlDirection:H8e("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:p,onResizeStart:h,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...vSt},S={...oQn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:H8e(u)};let x,k=null,_=[],C,E,j,T=!1;const I=j1t().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:M,snapToGrid:z,nodeOrigin:H,paneDomNode:F}=n();if(x=R.get(t),!x)return;k=F?.getBoundingClientRect()??null;const{xSnapped:B,ySnapped:q}=pP(A.sourceEvent,{transform:L,snapGrid:M,snapToGrid:z,containerBounds:k});b={width:x.measured.width??0,height:x.measured.height??0,x:x.position.x??0,y:x.position.y??0},S={...b,pointerX:B,pointerY:q,aspectRatio:b.width/b.height},C=void 0,x.parentId&&(x.extent==="parent"||x.expandParent)&&(C=R.get(x.parentId),E=C&&x.extent==="parent"?lQn(C):void 0),_=[],j=void 0;for(const[D,G]of R)if(G.parentId===t&&(_.push({id:D,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const V=cQn(G,x,G.origin??H);j?j=[[Math.min(V[0][0],j[0][0]),Math.min(V[0][1],j[0][1])],[Math.max(V[1][0],j[1][0]),Math.max(V[1][1],j[1][1])]]:j=V}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:M,nodeOrigin:z}=n(),H=pP(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:M,containerBounds:k}),F=[];if(!x)return;const{x:B,y:q,width:D,height:G}=b,V={},$=x.origin??z,{width:U,height:Z,x:K,y:ne}=iQn(S,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,E,j),te=U!==D,J=Z!==G,ae=K!==B&&te,pe=ne!==q&&J;if(!ae&&!pe&&!te&&!J)return;if((ae||pe||$[0]===1||$[1]===1)&&(V.x=ae?K:b.x,V.y=pe?ne:b.y,b.x=V.x,b.y=V.y,_.length>0)){const de=K-B,oe=ne-q;for(const me of _)me.position={x:me.position.x-de+$[0]*(U-D),y:me.position.y-oe+$[1]*(Z-G)},F.push(me)}if((te||J)&&(V.width=te&&(!i.resizeDirection||i.resizeDirection==="horizontal")?U:b.width,V.height=J&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=V.width,b.height=V.height),C&&x.expandParent){const de=$[0]*(V.width??0);V.x&&V.x<de&&(b.x=de,S.x=S.x-(V.x-de));const oe=$[1]*(V.height??0);V.y&&V.y<oe&&(b.y=oe,S.y=S.y-(V.y-oe))}const Y=aQn({width:b.width,prevWidth:D,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),ee={...b,direction:Y};y?.(A,ee)!==!1&&(T=!0,m?.(A,ee),r(V,F))}).on("end",A=>{T&&(v?.(A,{...b}),s?.({...b}),T=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const dQn={},Z8e=e=>{let t;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const h=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(m=>m(t,h))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(dQn?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},u=t=e(r,s,c);return c},fQn=e=>e?Z8e(e):Z8e,{useDebugValue:pQn}=Le,{useSyncExternalStoreWithSelector:hQn}=IOn,mQn=e=>e;function ySt(e,t=mQn,n){const r=hQn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return pQn(r),r}const G8e=(e,t)=>{const n=fQn(e),r=(s,a=t)=>ySt(n,s,a);return Object.assign(r,n),r},gQn=(e,t)=>e?G8e(e,t):G8e;function oo(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,s]of e)if(!Object.is(s,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const OH=g.createContext(null),vQn=OH.Provider,bSt=by.error001();function Us(e,t){const n=g.useContext(OH);if(n===null)throw new Error(bSt);return ySt(n,e,t)}function jo(){const e=g.useContext(OH);if(e===null)throw new Error(bSt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const Q8e={display:"none"},yQn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},xSt="react-flow__node-desc",wSt="react-flow__edge-desc",bQn="react-flow__aria-live",xQn=e=>e.ariaLiveMessage,wQn=e=>e.ariaLabelConfig;function SQn({rfId:e}){const t=Us(xQn);return o.jsx("div",{id:`${bQn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:yQn,children:t})}function kQn({rfId:e,disableKeyboardA11y:t}){const n=Us(wQn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${xSt}-${e}`,style:Q8e,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${wSt}-${e}`,style:Q8e,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(SQn,{rfId:e})]})}const B4=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Vl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});B4.displayName="Panel";function OQn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(B4,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:o.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const _Qn=e=>{const t=[],n=[];for(const[,r]of e.nodeLookup)r.selected&&t.push(r.internals.userNode);for(const[,r]of e.edgeLookup)r.selected&&n.push(r);return{selectedNodes:t,selectedEdges:n}},rF=e=>e.id;function CQn(e,t){return oo(e.selectedNodes.map(rF),t.selectedNodes.map(rF))&&oo(e.selectedEdges.map(rF),t.selectedEdges.map(rF))}function EQn({onSelectionChange:e}){const t=jo(),{selectedNodes:n,selectedEdges:r}=Us(_Qn,CQn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const jQn=e=>!!e.onSelectionChangeHandlers;function TQn({onSelectionChange:e}){const t=Us(jQn);return e||t?o.jsx(EQn,{onSelectionChange:e}):null}const Wme=typeof window<"u"?g.useLayoutEffect:g.useEffect,SSt=[0,0],NQn={x:0,y:0,zoom:1},IQn=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode"],Y8e=[...IQn,"rfId"],AQn=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),K8e={translateExtent:CM,nodeOrigin:SSt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function RQn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Us(AQn,oo),u=jo();Wme(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=K8e,l()}),[]);const d=g.useRef(K8e);return Wme(()=>{for(const f of Y8e){const p=e[f],h=d.current[f];p!==h&&(typeof e[f]>"u"||(f==="nodes"?t(p):f==="edges"?n(p):f==="minZoom"?r(p):f==="maxZoom"?s(p):f==="translateExtent"?a(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:SGn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},Y8e.map(f=>e[f])),null}function X8e(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function PQn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=X8e(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:X8e()?.matches?"dark":"light"}const J8e=typeof document<"u"?document:null;function IM(e=null,t={target:J8e,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
|
|
338
338
|
`).replace(`
|
|
339
339
|
|
|
340
340
|
`,`
|
|
@@ -493,7 +493,7 @@ ${e.map(u=>`- ${u.id}: ${u.name}`).join(`
|
|
|
493
493
|
`]},u)})})})});function Gp({children:e}){const t=e.replace(/\\n/g,`
|
|
494
494
|
`);return o.jsx(F2t,{remarkPlugins:[vPr],components:xPr,className:"space-y-3",children:t})}const bPr=({children:e,className:t,language:n,...r})=>{const s=typeof e=="string"?e:aye(e),a=X("overflow-x-scroll rounded-md border bg-surface1/50 p-4 font-mono text-sm [scrollbar-width:none]",t);return o.jsxs("div",{className:"group/code relative mb-4",children:[o.jsx(cPt,{code:s,lang:n,className:a,...r}),o.jsx("div",{className:"invisible absolute top-2 right-2 flex gap-1 rounded-lg p-1 opacity-0 transition-all duration-200 group-hover/code:visible group-hover/code:opacity-100",children:o.jsx($a,{content:s,copyMessage:"Copied code to clipboard"})})]})};function aye(e){if(typeof e=="string")return e;if(e?.props?.children){let t=e.props.children;return Array.isArray(t)?t.map(n=>aye(n)).join(""):aye(t)}return""}const xPr={h1:({children:e,...t})=>o.jsx("h1",{className:"text-2xl font-semibold",...t,children:e}),h2:({children:e,...t})=>o.jsx("h2",{className:"text-xl font-semibold",...t,children:e}),h3:({children:e,...t})=>o.jsx("h3",{className:"text-lg font-semibold",...t,children:e}),h4:({children:e,...t})=>o.jsx("h4",{className:"text-base font-semibold",...t,children:e}),h5:({children:e,...t})=>o.jsx("h5",{className:"font-medium",...t,children:e}),strong:({children:e,...t})=>o.jsx("strong",{className:"font-semibold",...t,children:e}),a:({children:e,...t})=>o.jsx("a",{className:"underline underline-offset-2",...t,children:e}),blockquote:({children:e,...t})=>o.jsx("blockquote",{className:"border-l-2 border-neutral6 pl-4",...t,children:e}),code:({children:e,className:t,...n})=>{const r=/language-(\w+)/.exec(t||"");return r?o.jsx(bPr,{className:t,language:r[1],...n,children:e}):o.jsx("code",{className:X("font-mono [:not(pre)>&]:rounded-md [:not(pre)>&]:bg-surface1/50 [:not(pre)>&]:px-1 [:not(pre)>&]:py-0.5"),...n,children:e})},pre:({children:e})=>e,ol:({children:e,...t})=>o.jsx("ol",{className:"list-decimal space-y-2 pl-6",...t,children:e}),ul:({children:e,...t})=>o.jsx("ul",{className:"list-disc space-y-2 pl-6",...t,children:e}),li:({children:e,...t})=>o.jsx("li",{className:"my-1.5",...t,children:e}),table:({children:e,...t})=>o.jsx("table",{className:"w-full border-collapse overflow-y-auto rounded-md border border-neutral6/20",...t,children:e}),th:({children:e,...t})=>o.jsx("th",{className:"border border-neutral6/20 px-4 py-2 text-left font-bold [[align=center]]:text-center [[align=right]]:text-right",...t,children:e}),td:({children:e,...t})=>o.jsx("td",{className:"border border-neutral6/20 px-4 py-2 text-left [[align=center]]:text-center [[align=right]]:text-right",...t,children:e}),tr:({children:e,...t})=>o.jsx("tr",{className:"m-0 border-t p-0 even:bg-surface4",...t,children:e}),p:({children:e,...t})=>o.jsx("p",{className:"leading-relaxed whitespace-pre-wrap",...t,children:e}),hr:({...e})=>o.jsx("hr",{className:"border-neutral6/20",...e})},uPt=({reason:e,tripwire:t})=>{const[n,r]=g.useState(!1),s=t&&(t.retry!==void 0||t.metadata||t.processorId);return o.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-amber-950/20 overflow-hidden",children:[o.jsxs("div",{className:"flex items-start gap-3 p-4",children:[o.jsx(Exe,{className:"w-5 h-5 text-amber-400 mt-0.5 shrink-0"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-sm font-medium text-amber-200 mb-1",children:"Content Blocked"}),o.jsx("p",{className:"text-sm text-amber-300/90",children:e})]})]}),s&&o.jsxs(o.Fragment,{children:[o.jsxs("button",{onClick:()=>r(!n),className:"w-full flex items-center gap-2 px-4 py-2 text-xs text-amber-400/70 hover:text-amber-400 hover:bg-amber-900/20 transition-colors border-t border-amber-500/20",children:[n?o.jsx(Ia,{className:"w-3.5 h-3.5"}):o.jsx(ha,{className:"w-3.5 h-3.5"}),o.jsx("span",{children:"Details"})]}),n&&o.jsxs("div",{className:"px-4 pb-4 space-y-3 border-t border-amber-500/20 bg-amber-950/10",children:[t.retry!==void 0&&o.jsxs("div",{className:"flex items-center gap-2 pt-3",children:[o.jsx(n1,{className:"w-3.5 h-3.5 text-amber-400/60"}),o.jsxs("span",{className:"text-xs text-amber-300/70",children:["Retry:"," ",t.retry?o.jsx("span",{className:"text-green-400",children:"Allowed"}):o.jsx("span",{className:"text-red-400",children:"Not allowed"})]})]}),t.processorId&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(BN,{className:"w-3.5 h-3.5 text-amber-400/60"}),o.jsxs("span",{className:"text-xs text-amber-300/70",children:["Processor:"," ",o.jsx("code",{className:"px-1.5 py-0.5 rounded bg-amber-900/30 text-amber-200 font-mono",children:t.processorId})]})]}),t.metadata!==void 0&&t.metadata!==null&&o.jsxs("div",{className:"pt-1",children:[o.jsx("p",{className:"text-xs text-amber-400/60 mb-1.5",children:"Metadata:"}),o.jsx("pre",{className:"text-xs text-amber-200/80 bg-amber-900/30 rounded p-2 overflow-x-auto font-mono",children:String(JSON.stringify(t.metadata,null,2))})]})]})]})]})},RCe=({text:e,metadata:t})=>{const[n,r]=g.useState(!1);if(t?.status==="tripwire")return o.jsx(uPt,{reason:e,tripwire:t.tripwire});if(t?.status==="warning")return o.jsx(En,{variant:"warning",title:"Warning",children:o.jsx(En.Message,{children:e})});if(t?.status==="error")return o.jsx(En,{variant:"destructive",title:"Error",children:o.jsx(En.Message,{children:e})});const s=t?.completionResult;if(s)return o.jsxs("div",{className:"mb-2 space-y-2",children:[o.jsxs("button",{onClick:()=>r(i=>!i),className:"flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(C_,{className:X("transition-all",n?"rotate-90":"rotate-180")})}),o.jsxs(un,{variant:"info",icon:o.jsx(SO,{}),children:[n?"Show":"Hide"," completion check"]})]}),!n&&o.jsx(En,{variant:"info",title:s?.passed?"Complete":"Not Complete",children:o.jsx(Gp,{children:e})})]});const a=e.trim();return a.startsWith("__ERROR__:")?o.jsx(En,{variant:"destructive",title:"Error",children:o.jsx(En.Message,{children:a.substring(10)})}):a.startsWith("Error:")?o.jsx(En,{variant:"destructive",title:"Error",children:o.jsx(En.Message,{children:a.substring(6).trim()})}):o.jsx(Gp,{children:e})},wPr=({text:e})=>o.jsx(En,{variant:"destructive",title:"Error",children:o.jsx(En.Message,{children:e})}),dPt=({text:e})=>o.jsx(En,{variant:"warning",title:"Warning",children:o.jsx(En.Message,{children:e})}),fPt=({text:e,tripwire:t})=>o.jsx(uPt,{reason:e,tripwire:t}),IZe={Error:wPr,Warning:dPt,Tripwire:fPt},pPt=()=>{const e=Ho(),t=Hs(),[n]=g.useState(()=>e.state?.userMessage);return g.useEffect(()=>{n!==void 0&&t(".",{replace:!0,state:null})},[n,t]),n},hPt=g.createContext(null),SPr=({agentId:e,children:t})=>{const n=Mf(),{canWrite:r}=Ry(),s=pPt(),{data:a,isLoading:i}=g3(e,{status:"draft"}),{data:l,isPending:c}=AI({enabled:n.tools}),{data:u,isPending:d}=Em({enabled:n.agents}),{data:f,isPending:p}=Hy({enabled:n.workflows}),{data:h,isPending:m}=K1({enabled:n.skills}),{data:v}=WW(),{data:y,isLoading:b}=Cm(),S=!a?.authorId||y?.id===a.authorId,x=!!a?.authorId&&b,k=!!e&&!i&&!x&&(!n.tools||!c)&&(!n.skills||!m)&&(!n.agents||!d)&&(!n.workflows||!p),_=g.useMemo(()=>(v?.workspaces??[]).filter(j=>j.status!=="archived").sort((j,T)=>(T.runtimeRegistered?1:0)-(j.runtimeRegistered?1:0)).map(j=>({id:j.id,name:j.name})),[v]),C=g.useMemo(()=>h?.skills??[],[h]),E=g.useMemo(()=>({agentId:e,storedAgent:a??void 0,toolsData:l??{},agentsData:u??{},workflowsData:f??{},availableSkills:C,availableWorkspaces:_,initialUserMessage:s,isOwner:S,canWrite:r,isReady:k}),[e,a,l,u,f,C,_,s,S,r,k]);return o.jsx(hPt.Provider,{value:E,children:t})},aC=()=>{const e=g.useContext(hPt);if(!e)throw new Error("useAgentPrimitives must be used inside <AgentPrimitivesProvider>");return e},PI=()=>{const e=We();return yt({queryKey:["tool-providers"],queryFn:()=>e.listToolProviders()})},kPr=3e4,OPr=e=>{const t=We(),n=PI(),r=g.useMemo(()=>n.data?.providers??[],[n.data?.providers]),s=Cm(),a=s.data?.id,i=s.isSuccess||iRt(s.error),l=xT({queries:r.map(m=>({queryKey:["tool-integration-services",m.id],queryFn:()=>t.getToolProvider(m.id).listToolkits()}))}),c=g.useMemo(()=>{const m=[];return r.forEach((v,y)=>{const b=l[y]?.data?.data??[];for(const S of b)m.push({providerId:v.id,toolkit:S.slug})}),m},[r,l]),u=xT({queries:c.map(m=>({queryKey:["tool-integration-connections-all",m.providerId,m.toolkit,a],queryFn:()=>t.getToolProvider(m.providerId).listConnections({toolkit:m.toolkit,...a?{authorId:a}:{}}),enabled:i,staleTime:kPr}))}),d=n.isLoading||s.isLoading||l.some(m=>m.isLoading)||u.some(m=>m.isLoading),f=g.useMemo(()=>{const m=new Map;return c.forEach((v,y)=>{const b=u[y]?.data?.items??[];m.set(`${v.providerId}:${v.toolkit}`,b)}),m},[c,u]),p=g.useCallback((m,v)=>(f.get(`${m}:${v}`)??[]).some(y=>y.status==="active"),[f]),h=g.useCallback((m,v)=>f.get(`${m}:${v}`)??[],[f]);return{hasConnection:p,getConnections:h,isLoading:d}},_Pr=500,S3=()=>{const e=We(),t=PI(),n=g.useMemo(()=>t.data?.providers??[],[t.data?.providers]),r=xT({queries:n.map(c=>({queryKey:["tool-integration-services",c.id],queryFn:()=>e.getToolProvider(c.id).listToolkits()}))}),s=g.useMemo(()=>{const c=[];return n.forEach((u,d)=>{const f=r[d]?.data?.data??[];for(const p of f)c.push({providerId:u.id,toolkit:p.slug})}),c},[n,r]),a=xT({queries:s.map(c=>({queryKey:["tool-integration-tools-all",c.providerId,c.toolkit],queryFn:()=>e.getToolProvider(c.providerId).listTools({toolkit:c.toolkit,perPage:_Pr})}))}),i=t.isLoading||r.some(c=>c.isLoading)||a.some(c=>c.isLoading);return{tools:g.useMemo(()=>{const c=[];return s.forEach((u,d)=>{const f=a[d]?.data?.data??[];for(const p of f){const h=p.toolkit??u.toolkit;c.push({providerId:u.providerId,slug:p.slug,toolkit:h,name:p.name,description:p.description})}}),c},[s,a]),isLoading:i}};function CPr(e,t,n={},r){const s=Object.fromEntries(Object.entries(e).map(([l,c])=>[l,{description:c.description}])),a=Object.fromEntries(Object.entries(t).filter(([l])=>l!==r).map(([l,c])=>[l,{id:l,name:c.name??l,description:c.description}])),i=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,{id:l,name:c.name??l,description:c.description}]));return{tools:s,agents:a,workflows:i}}const EPr=({tools:e,agents:t,workflows:n={},selected:r})=>{const s=r?.tools??{},a=r?.agents??{},i=r?.workflows??{},l=[],c=new Set;for(const[u,d]of Object.entries(t))c.add(u),l.push({id:u,name:d?.name??u,description:d?.description,isChecked:!!a[u],type:"agent"});for(const[u,d]of Object.entries(n)){if(c.has(u)){console.warn(`[buildAgentTools] id collision for "${u}": agent and workflow share the same id; agent takes precedence.`);continue}c.add(u),l.push({id:u,name:d?.name??u,description:d?.description,isChecked:!!i[u],type:"workflow"})}for(const[u,d]of Object.entries(e)){if(c.has(u)){console.warn(`[buildAgentTools] id collision for "${u}": agent or workflow and tool share the same id; agent/workflow takes precedence.`);continue}c.add(u),l.push({id:u,name:u,description:d?.description,isChecked:!!s[u],type:"tool"})}return l},jPr={};function Lre(e,t){const n={};for(const[r,s]of Object.entries(e))t.has(r)&&(n[r]=s);return n}function mPt({toolsData:e,agentsData:t,workflowsData:n,selectedTools:r,selectedAgents:s,selectedWorkflows:a,excludeAgentId:i}){const l=n??jPr,c=PCn(),{tools:u}=S3(),{hasConnection:d,getConnections:f}=OPr(),p=Mn({name:"toolProviders"});return g.useMemo(()=>{const h=c.visibleTools===null?e:Lre(e,c.visibleTools),m=c.visibleAgents===null?t:Lre(t,c.visibleAgents),v=c.visibleWorkflows===null?l:Lre(l,c.visibleWorkflows),y=CPr(h,m,v,i),b=EPr({tools:y.tools,agents:y.agents,workflows:y.workflows,selected:{tools:r,agents:s,workflows:a}}),S=u.map(x=>({id:`${x.providerId}:${x.slug}`,name:x.slug,description:x.description,isChecked:!!p?.[x.providerId]?.tools?.[x.slug],type:"integration",providerId:x.providerId,toolkit:x.toolkit,hasConnection:d(x.providerId,x.toolkit),connectionLabels:f(x.providerId,x.toolkit).filter(k=>k.status==="active").map(k=>k.label||k.connectionId)}));return[...b,...S]},[e,t,l,r,s,a,i,c,u,p,d,f])}const TPr=e=>{const t=e.trim();if(t.length===0)return{summary:"Something went wrong while building the agent."};if(t.startsWith("{")||t.startsWith("["))try{const i=JSON.parse(t),l=NPr(i);if(l)return{summary:APr(l),details:t}}catch{}const n=t.split(`
|
|
495
495
|
`)[0],r=n.length>200,s=r?`${n.slice(0,200)}…`:n,a=r||t.length>n.length?t:void 0;return{summary:s,details:a}},NPr=e=>{const t=typeof e.message=="string"?e.message:void 0;if(t){const r=IPr(t);return r||t}const n=e.error;if(n&&typeof n=="object"){const r=n.message;if(typeof r=="string")return r}},IPr=e=>{const t=e.trim();if(t.startsWith("{"))try{const n=JSON.parse(t),r=n.error;if(r&&typeof r=="object"){const s=r.message;if(typeof s=="string")return s}if(typeof n.message=="string")return n.message}catch{return}},APr=e=>{const n=e.toLowerCase().indexOf("please include the request id");if(n===-1)return e.trim();const s=e.slice(n).indexOf("."),a=s===-1?e.length:n+s+1;return(e.slice(0,n)+e.slice(a)).trim()},RPr=({children:e,className:t})=>o.jsx("span",{className:X("inline-block text-transparent",t),style:{backgroundImage:"linear-gradient(to right, var(--neutral3), var(--neutral6), var(--neutral3))",backgroundSize:"200% 100%",backgroundClip:"text",WebkitBackgroundClip:"text",animation:"shimmer-text 2s linear infinite"},children:e}),gPt=({text:e})=>o.jsxs(ye,{variant:"ui-md",className:"whitespace-pre-wrap leading-relaxed text-neutral4 max-w-[80%] flex items-center gap-2",as:"div",children:[o.jsx(oa,{className:"animate-spin size-4 text-neutral3"}),o.jsx(RPr,{children:e})]}),PPr=e=>{switch(e){case"urgent":return"destructive";case"high":return"warning";case"medium":return"info";default:return"note"}},$x=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vPt=e=>typeof e=="string"?e:Array.isArray(e)?e.flatMap(t=>$x(t)?t.type==="text"&&typeof t.text=="string"&&t.text.length>0?[t.text]:[]:[]).join(`
|
|
496
|
-
`):"",Qv=e=>{if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)},k3=e=>$x(e)?e.type==="notification"||e.type==="state"||e.type==="reactive":!1,yPt=e=>{const t=e.content.metadata?.signal;return $x(t)?t:void 0},PCe=e=>{const t=yPt(e)?.type;return typeof t=="string"?t:e.type},bPt=e=>e==="user"||e==="user-message",$Pr=e=>{const t=[];for(const n of e){const r=n;if(r.type==="text"&&typeof r.text=="string"){t.push({type:"text",text:r.text});continue}if(r.type==="file"&&typeof r.data=="string"){const s=(typeof r.mediaType=="string"?r.mediaType:void 0)??(typeof r.mimeType=="string"?r.mimeType:void 0)??"application/octet-stream";t.push({type:"file",data:r.data,mediaType:s})}}return t.length===1&&t[0]?.type==="text"?t[0].text:t},xPt=e=>{const t=yPt(e)??{};return{id:typeof t.id=="string"?t.id:e.id,type:PCe(e),tagName:typeof t.tagName=="string"?t.tagName:e.type,contents:$Pr(e.content.parts),...$x(t.attributes)?{attributes:t.attributes}:{},...$x(t.metadata)?{metadata:t.metadata}:{}}},wPt=e=>{const t=$x(e.metadata?.notification)?e.metadata.notification:void 0;if(t)return{signal:t.signal==="notification"||t.signal==="summary"?t.signal:void 0,recordId:typeof t.recordId=="string"?t.recordId:void 0,source:typeof t.source=="string"?t.source:void 0,kind:typeof t.kind=="string"?t.kind:void 0,priority:typeof t.priority=="string"?t.priority:void 0,status:typeof t.status=="string"?t.status:void 0,pending:typeof t.pending=="number"?t.pending:void 0}},MPr=e=>{const t=wPt(e);if(t?.signal==="summary"||e.tagName==="notification-summary")return"Notification summary";const n=t?.source??Qv(e.attributes?.source),r=t?.kind??Qv(e.attributes?.kind);return n&&r?`${n} / ${r}`:n??r??"Notification"},DPr=({signal:e})=>{const t=wPt(e),n=t?.priority??Qv(e.attributes?.priority),r=Qv(t?.pending)??Qv(e.attributes?.pending),s=t?.status??Qv(e.attributes?.status),a=vPt(e.contents),i=r?`${r} pending`:void 0,l=!!(n||s||i),c=a.length>0;return o.jsx(En,{variant:PPr(n),title:MPr(e),icon:o.jsx(Pfn,{}),className:"my-2 max-w-[80%]",children:l||c?o.jsxs("div",{className:"flex flex-col gap-2",children:[l?o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n?o.jsx(un,{size:"xs",children:n}):null,s?o.jsx(un,{size:"xs",children:s}):null,i?o.jsx(un,{size:"xs",children:i}):null]}):null,c?o.jsx(En.Message,{className:"whitespace-pre-wrap break-words",children:a}):null]}):null})},LPr=e=>{const t=$x(e.metadata?.state)?e.metadata.state:void 0;return{id:Qv(t?.id)??Qv(e.attributes?.id)??"State signal",mode:Qv(t?.mode)??Qv(e.attributes?.mode)}},FPr=({children:e})=>o.jsx("span",{className:"inline-flex items-center rounded-full border border-border1 px-1.5 py-0.5 text-xs leading-none text-neutral4",children:e});function zPr(e){return Array.isArray(e)&&e.every(t=>$x(t)&&typeof t.id=="string"&&typeof t.content=="string"&&(t.status==="pending"||t.status==="in_progress"||t.status==="completed")&&typeof t.activeForm=="string")}function BPr(e){if(!(e.id==="tasks"||e.tagName==="current-task-list"||e.tagName==="task-list-update"))return;const n=e.metadata,s=($x(n?.value)?n.value:void 0)?.tasks;if(zPr(s))return s}const SPt=({signal:e})=>{if(!k3(e))return null;const t=vPt(e.contents);if(e.type==="state"){if(BPr(e))return null;const r=LPr(e);return o.jsx("div",{className:"my-2 max-w-[80%] rounded-lg border border-border1 bg-surface2 px-4 py-3 text-neutral5",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(uy,{className:"mt-0.5 h-4 w-4 shrink-0 text-icon3"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("p",{className:"text-ui-sm leading-ui-sm font-medium text-neutral6",children:r.id}),r.mode?o.jsx(FPr,{children:r.mode}):null]}),t?o.jsx("p",{className:"mt-2 whitespace-pre-wrap break-words text-ui-sm leading-ui-md",children:t}):null]})]})})}return e.type==="notification"?o.jsx(DPr,{signal:e}):e.type==="reactive"?o.jsx("div",{className:"my-2 max-w-[80%] rounded-lg border border-border1 bg-surface2 px-4 py-3 text-neutral5",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(jdt,{className:"mt-0.5 h-4 w-4 shrink-0 text-icon3"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("p",{className:"text-ui-sm leading-ui-sm font-medium text-neutral6",children:e.tagName??"Signal"}),t?o.jsx("p",{className:"mt-2 whitespace-pre-wrap break-words text-ui-sm leading-ui-md",children:t}):null]})]})}):null},AZe=({toolCallId:e,toolName:t})=>{const{approveToolCall:n,declineToolCall:r}=Gjr(),[s,a]=g.useState(null),i=s!==null,l=()=>{a("approve"),n(e)},c=()=>{a("decline"),r(e)};return o.jsxs(OPt,{testId:"agent-builder-chat-tool-approval",className:"bg-surface4 border-transparent",children:[o.jsxs(ye,{variant:"ui-sm",className:"text-neutral5 pb-2",as:"div",children:["Approval required for ",o.jsx("span",{className:"font-mono text-neutral6",children:t})]}),o.jsxs("div",{className:"flex gap-2 items-center",children:[o.jsxs(le,{variant:"default",onClick:l,disabled:i,"data-testid":"agent-builder-chat-tool-approve","aria-label":`Approve ${t}`,children:[o.jsx(qe,{children:s==="approve"?o.jsx(oa,{className:"animate-spin"}):o.jsx(pa,{})}),"Approve"]}),o.jsxs(le,{variant:"ghost",onClick:c,disabled:i,"data-testid":"agent-builder-chat-tool-decline","aria-label":`Decline ${t}`,children:[s==="decline"&&o.jsx(qe,{children:o.jsx(oa,{className:"animate-spin"})}),"Decline"]})]})]})},kPt=e=>e.role==="assistant"||e.role==="user"||e.role==="system"?e.role:e.role==="signal"?bPt(PCe(e))?"user":"assistant":null,UPr=e=>{const t=xPt(e);return k3(t)?{...e,role:"assistant",content:{...e.content,parts:[{type:"data-signal",data:t}]}}:null},VPr=e=>{const t=e.content.metadata;if(!t||typeof t!="object")return;const{mode:n}=t;if(!(n!=="stream"&&n!=="network"&&n!=="generate"))return t.requireApprovalMetadata},qPr=e=>!e||typeof e!="object"||!("name"in e)?"unknown":typeof e.name=="string"?e.name:"unknown",RZe=(e,t,n)=>{if(e)return(t?e[t]:void 0)??(n?e[n]:void 0)},HPr=e=>{const t=kPt(e);return t===null?null:e.role==="signal"&&t==="assistant"?UPr(e):t===e.role?e:{...e,role:t}},PZe=(e,t,n)=>{switch(e){case mCe:return o.jsx(KPr,{});case fCe:return o.jsx(XPr,{});case pCe:return o.jsx(JPr,{});case vCe:return o.jsx(e$r,{});case gCe:return o.jsx(t$r,{});case hCe:return o.jsx(n$r,{});case dCe:return o.jsx(r$r,{});case yCe:return o.jsx(s$r,{});case"skill":return o.jsx(a$r,{name:qPr(t)});default:return o.jsx(YPr,{toolName:e,input:t,output:n})}},WPr=({message:e})=>{const t=VPr(e),n=Qjr(),r=kPt(e),s=HPr(e);if(s===null)return null;const a=e.content.metadata,i={Text:c=>o.jsx(ZPr,{txt:c.text??"",role:r,metadata:a}),Reasoning:c=>("state"in c?c.state:void 0)!=="streaming"?null:o.jsx(gPt,{text:"Reasoning..."}),Data:c=>c.type==="data-signal"&&k3(c.data)?o.jsx(SPt,{signal:c.data}):null,ToolInvocation:c=>{const u=c.toolInvocation,d=RZe(t,u.toolName,u.toolCallId);if(d&&u.state!=="result")return o.jsx(AZe,{toolCallId:d.toolCallId,toolName:d.toolName});if(u.state!=="result")return null;const f="args"in u?u.args:void 0,p="result"in u?u.result:void 0;return PZe(u.toolName,f,p)},DynamicTool:c=>{const u=c.toolName??c.type.replace(/^tool-/,""),d=RZe(t,u,c.toolCallId);return d&&c.state!=="output-available"?o.jsx(AZe,{toolCallId:d.toolCallId,toolName:d.toolName}):c.state!=="output-available"?null:PZe(u,c.input,c.output)}},l={Error:({text:c})=>o.jsx(GPr,{error:TPr(c),onRetry:n}),Warning:dPt,Tripwire:fPt};return o.jsx(G9,{message:s,...i,status:l})},ZPr=({txt:e,role:t,metadata:n})=>t==="user"?o.jsx("div",{className:"flex justify-end",children:o.jsx(ye,{variant:"ui-md",className:"bg-white text-black rounded-2xl px-4 py-2.5 max-w-[80%] [&_ul]:!space-y-1 [&_ol]:!space-y-1 [&_li]:!my-0 [&_p]:!leading-normal [&_p]:!whitespace-normal [&_li]:!leading-normal",as:"div",children:o.jsx(Gp,{children:e})})}):t==="assistant"||t==="system"?o.jsx(ye,{variant:"ui-md",className:"text-neutral4 max-w-[80%] [&_ul]:!space-y-1 [&_ol]:!space-y-1 [&_li]:!my-0 [&_p]:!leading-normal [&_p]:!whitespace-normal [&_li]:!leading-normal",as:"div",children:o.jsx(RCe,{text:e,metadata:n})}):null,GPr=({error:e,onRetry:t})=>o.jsxs(X_,{className:"border-accent6/40 bg-accent6/5 max-w-[80%] p-4 flex flex-col gap-3",role:"alert","data-testid":"agent-builder-chat-error",children:[o.jsxs("div",{className:"flex items-start gap-2.5",children:[o.jsx(yf,{className:"size-4 mt-0.5 shrink-0 text-accent6","aria-hidden":!0}),o.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[o.jsx(ye,{variant:"ui-md",className:"text-icon6 font-medium",as:"div",children:"Something went wrong while building the agent."}),o.jsx(ye,{variant:"ui-sm",className:"text-neutral4 break-words",as:"div","data-testid":"agent-builder-chat-error-summary",children:e.summary})]})]}),e.details&&e.details!==e.summary?o.jsxs(jf,{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[t!==null&&o.jsxs(le,{variant:"default",onClick:t,className:"gap-1.5","data-testid":"agent-builder-chat-error-retry",children:[o.jsx(n1,{className:"size-3.5","aria-hidden":!0}),"Try again"]}),o.jsx($d,{className:"text-neutral4 hover:text-neutral6 text-sm underline-offset-2 hover:underline","data-testid":"agent-builder-chat-error-details-trigger",children:"Details"})]}),o.jsx(Md,{children:o.jsx("pre",{className:"text-xs text-neutral4 whitespace-pre-wrap break-all bg-surface1 rounded-md p-2 max-h-48 overflow-auto","data-testid":"agent-builder-chat-error-details",children:e.details})})]}):t!==null&&o.jsx("div",{className:"flex items-center gap-3",children:o.jsxs(le,{variant:"default",onClick:t,className:"gap-1.5","data-testid":"agent-builder-chat-error-retry",children:[o.jsx(n1,{className:"size-3.5","aria-hidden":!0}),"Try again"]})})]}),QPr=({testId:e})=>o.jsxs("div",{className:"flex flex-col gap-6","data-testid":e,children:[o.jsx("div",{className:"flex justify-end",children:o.jsx(xt,{className:"h-10 w-56 rounded-2xl"})}),o.jsx(xt,{className:"h-6 w-[70%] rounded-full"}),o.jsx(xt,{className:"h-6 w-[55%] rounded-full"}),o.jsx("div",{className:"flex justify-end",children:o.jsx(xt,{className:"h-10 w-40 rounded-2xl"})}),o.jsx(xt,{className:"h-6 w-[65%] rounded-full"})]}),$Ze=e=>{if(e===void 0)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}},YPr=({toolName:e,input:t,output:n})=>{const r=$Ze(t),s=$Ze(n),a=s.length>0;return o.jsx(OPt,{testId:"agent-builder-chat-generic-tool",children:o.jsxs(jf,{children:[o.jsxs($d,{className:"flex w-full items-center gap-2 text-left group","data-testid":"agent-builder-chat-generic-tool-trigger",children:[o.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-border1/60 bg-surface1 px-2 py-0.5",children:[o.jsx(Up,{className:"size-3.5 shrink-0 text-neutral4","aria-hidden":!0}),o.jsxs(ye,{variant:"ui-sm",className:"text-neutral5",as:"span",children:["Executing ",o.jsx("span",{className:"font-mono text-neutral6",children:e})]})]}),o.jsx(ha,{className:"size-4 shrink-0 text-neutral4 transition-transform group-data-[state=open]:rotate-90","aria-hidden":!0})]}),o.jsx(Md,{children:o.jsxs("div",{className:"mt-3 flex flex-col gap-2","data-testid":"agent-builder-chat-generic-tool-content",children:[o.jsxs("div",{className:"rounded-md border border-border1/60 bg-surface1 overflow-hidden",children:[o.jsx("div",{className:"px-2 py-1 border-b border-border1/60",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",as:"div",children:"Input"})}),o.jsx("pre",{className:"m-0 max-h-[320px] overflow-auto p-3 text-xs leading-relaxed text-neutral5 whitespace-pre-wrap break-words",children:r||"{}"})]}),a?o.jsxs("div",{className:"rounded-md border border-border1/60 bg-surface1 overflow-hidden",children:[o.jsx("div",{className:"px-2 py-1 border-b border-border1/60",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",as:"div",children:"Output"})}),o.jsx("pre",{className:"m-0 max-h-[320px] overflow-auto p-3 text-xs leading-relaxed text-neutral5 whitespace-pre-wrap break-words",children:s})]}):null]})})]})})},OPt=({children:e,testId:t,className:n})=>o.jsx(X_,{"data-testid":t,className:X("max-w-[80%] p-3 bg-surface2/60 border-border1/60 animate-in fade-in slide-in-from-left-2 duration-300",n),children:e}),i0=({icon:e,label:t,value:n})=>o.jsxs("div",{className:"flex items-start gap-2 min-w-0 max-w-full animate-in fade-in slide-in-from-right-4 duration-500 ease-out",children:[o.jsx("div",{className:"pt-0.5",children:o.jsx(qe,{children:e})}),o.jsxs(ye,{variant:"ui-md",className:"text-neutral3 min-w-0 flex-1 truncate",as:"div",children:[t," ",o.jsx("strong",{className:"font-semibold text-neutral6",children:n})]})]}),KPr=()=>{const{watch:e}=Vr(),t=e("name");return t?o.jsx(i0,{icon:o.jsx(adt,{}),label:"Setting the agent name:",value:t}):null},XPr=()=>{const{watch:e}=Vr(),t=e("description");return t?o.jsx(i0,{icon:o.jsx(adt,{}),label:"Setting the agent description:",value:t}):null},JPr=()=>{const{watch:e}=Vr(),t=e("instructions");return t?o.jsx(i0,{icon:o.jsx(jc,{}),label:"Setting the agent instructions:",value:t}):null},e$r=()=>{const{agentId:e,toolsData:t,agentsData:n,workflowsData:r}=aC(),{watch:s}=Vr(),a=s("tools"),i=s("agents"),l=s("workflows"),u=mPt({toolsData:t,agentsData:n,workflowsData:r,selectedTools:a,selectedAgents:i,selectedWorkflows:l,excludeAgentId:e}).filter(f=>f.isChecked),d=u.length===0?"none":u.map(f=>f.name).join(", ");return o.jsx(i0,{icon:o.jsx(Up,{}),label:"Enabling tools:",value:d})},t$r=()=>{const{availableSkills:e}=aC(),{watch:t}=Vr(),n=t("skills"),r=n?e.filter(a=>n[a.id]===!0):[],s=r.length===0?"none":r.map(a=>a.name).join(", ");return o.jsx(i0,{icon:o.jsx(Axe,{}),label:"Enabling skills:",value:s})},n$r=()=>{const{watch:e}=Vr(),t=e("model");return t?o.jsx(i0,{icon:o.jsx(II,{providerId:t.provider,size:16}),label:"Setting agent model to",value:`${t.provider}/${t.name}`}):null},r$r=()=>{const{watch:e}=Vr(),t=e("browserEnabled");return o.jsx(i0,{icon:t?o.jsx(Ux,{}):o.jsx(Thn,{}),label:"Browser access",value:t?"enabled":"disabled"})},s$r=()=>{const{watch:e}=Vr(),t=e("workspaceId");return t?o.jsx(i0,{icon:o.jsx(udt,{}),label:"Setting workspace to",value:t}):null},a$r=({name:e})=>o.jsx(i0,{icon:o.jsx(Axe,{}),label:"Using super-powers:",value:e}),i$r=e=>{const t=g.useRef(null);return g.useEffect(()=>{const n=t.current;n&&n.scrollTo({top:n.scrollHeight,behavior:"smooth"})},[e]),t},o$r=(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},l$r=300,c$r=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,$Ce=({messages:e,isLoading:t=!1,isRunning:n=!1,emptyState:r,skeletonTestId:s})=>{const a=i$r(e),i=t&&e.length===0,l=o$r(i,l$r),c=!t&&e.length===0&&r!==void 0,u=e[e.length-1],d=n&&!i&&(u?.role!=="assistant"||!c$r(u));return o.jsx("div",{ref:a,className:"flex-1 min-h-0 overflow-y-auto py-6 px-6",style:{viewTransitionName:"agent-builder-messages"},children:l?o.jsx(QPr,{testId:s}):c?r:o.jsxs("div",{className:"flex flex-col gap-6",children:[e.map(f=>o.jsx(WPr,{message:f},f.id)),d&&o.jsx(m2t,{testId:"agent-builder-chat-pending"})]})})},MZe="builder-agent",u$r=e=>`agent-builder-${e}`,d$r=({initialUserMessage:e,isFreshThread:t=!1,features:n,availableAgentTools:r=[],availableWorkspaces:s=[],availableSkills:a=[],toolsReady:i=!0,agentId:l,children:c})=>{const u=u$r(l),{data:d,isLoading:f}=AH({agentId:MZe,threadId:u,memory:!t}),p=g.useMemo(()=>[],[l]),h=d?.messages??p,m=(d?.messages?.length??0)>0,{models:v,isLoading:y}=Y1(),b=n.model?v:[],{isLoading:S}=S3(),x=i&&(!n.model||!y)&&!S,k=uTr({features:n,availableAgentTools:r,availableWorkspaces:s,availableSkills:a,availableModels:b,integrationToolsLoading:S}),{control:_}=Vr(),C=Mn({control:_}),E=DTr({availableWorkspaces:s}),j=g.useMemo(()=>({...k,...n.skills?{[p2t]:E}:{}}),[k,E,n.skills]),T=g.useMemo(()=>({isLoading:f,agentId:l}),[f,l]),I=x&&!f&&!m?e:void 0,A=nTr(C,{availableAgentTools:r,availableSkills:a,availableWorkspaces:s,availableModels:b,features:n,starterUserMessage:e});return o.jsx(t2t,{agentId:MZe,threadId:u,initialMessages:h,initialUserMessage:I,clientTools:j,extraInstructions:A,debounceTime:1e3,children:o.jsx(_Pt.Provider,{value:T,children:c})})},_Pt=g.createContext({isLoading:!1,agentId:""}),f$r=()=>o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[o.jsx(p$r,{}),o.jsx(h$r,{})]}),p$r=()=>{const e=cCe(),t=fu(),{isLoading:n}=g.useContext(_Pt);return o.jsx($Ce,{messages:e,isLoading:n,isRunning:t,skeletonTestId:"agent-builder-conversation-messages-skeleton"})},h$r=()=>{const e=e2t(),t=uCe(),{draft:n,setDraft:r,trimmed:s,handleFormSubmit:a,handleKeyDown:i}=n2t({onSubmit:t});return o.jsx(wCe,{draft:n,onDraftChange:r,onSubmit:a,onKeyDown:i,disabled:e,isRunning:e,canSubmit:s.length>0&&!e,placeholder:"Tell the builder what to change…",inputTestId:"agent-builder-conversation-input",submitTestId:"agent-builder-conversation-submit",containerTestId:"agent-builder-conversation-composer"})};function m$r(e){if(!e)return;const t={};for(const[n,r]of Object.entries(e)){const s={};for(const[i,l]of Object.entries(r.tools??{}))s[i]=l;const a={};for(const[i,l]of Object.entries(r.connections??{}))a[i]=l.map(c=>({kind:"author",toolkit:c.toolkit,connectionId:c.connectionId,...c.label?.trim()?{label:c.label.trim()}:{},...c.scope?{scope:c.scope}:{}}));t[n]={tools:s,connections:a}}return Object.keys(t).length>0?t:void 0}function g$r(e){if(!e||Array.isArray(e))return;const t=e,n={};for(const[r,s]of Object.entries(t)){if(typeof s!="object"||s===null)continue;const a=s.connections??{},i=Object.keys(a),l=d=>{const f=d.toLowerCase(),p=i.find(h=>f.startsWith(`${h.toLowerCase()}_`)||f===h.toLowerCase());if(p)return p;if(i.length===1)return i[0]},c={};for(const[d,f]of Object.entries(s.tools??{})){const p=f?.toolkit??l(d);p&&(c[d]={toolkit:p,...f?.description?{description:f.description}:{}})}const u={};for(const[d,f]of Object.entries(a))u[d]=f.map(p=>({kind:"author",toolkit:d,connectionId:p.connectionId,...p.label?.trim()?{label:p.label.trim()}:{},...p.scope?{scope:p.scope}:{}}));n[r]={tools:c,connections:u}}return Object.keys(n).length>0?n:void 0}function WF(e,t){return Object.fromEntries(Object.entries(e??{}).filter(([,n])=>n).map(([n])=>{const r=t.get(n);return[n,r?{description:r}:{}]}))}function v$r(e,t,n=[]){const r=new Map,s=new Map,a=new Map;for(const y of t)y.type==="tool"?r.set(y.id,y.description):y.type==="agent"?s.set(y.id,y.description):a.set(y.id,y.description);const i=new Map;for(const y of n)i.set(y.id,y.description);const l=WF(e.tools,r),c=WF(e.agents,s),u=WF(e.workflows,a),d=WF(e.skills,i),f=typeof e.workspaceId=="string"&&e.workspaceId.length>0?{type:"id",workspaceId:e.workspaceId}:void 0,p=e.description?.trim()?e.description.trim():void 0,h=e.avatarUrl?{avatarUrl:e.avatarUrl}:void 0,m=e.browserEnabled===!0,v=m$r(e.toolProviders);return{name:e.name,description:p,instructions:e.instructions,tools:l,agents:c,workflows:u,skills:d,workspace:f,browser:m,visibility:e.visibility,model:e.model,metadata:h,toolProviders:v}}function y$r(e){return e&&typeof e=="object"&&"code"in e&&e.code==="MODEL_NOT_ALLOWED"?{message:e instanceof Error?e.message:"Model is not allowed"}:null}function b$r({agentId:e,availableAgentTools:t=[],availableSkills:n=[],onSuccess:r,silent:s=!1}){const{updateStoredAgent:a}=O1(e),i=y3();return{save:g.useCallback(async c=>{const u=v$r(c,t,n),d=u.visibility??i,f=u.workspace?{workspace:u.workspace}:{},p={browser:u.browser},h=u.metadata?{metadata:u.metadata}:{},m=u.toolProviders?{toolProviders:u.toolProviders}:{};try{const v=await a.mutateAsync({name:u.name,description:u.description,instructions:u.instructions,tools:u.tools,agents:u.agents,workflows:u.workflows,skills:u.skills,visibility:d,model:u.model,...f,...p,...h,...m});return s||De.success("Agent updated"),r?.(e),v}catch(v){const y=y$r(v);throw y?De.error(y.message):De.error(`Failed to save agent: ${v instanceof Error?v.message:"Unknown error"}`),v}},[e,t,n,a,r,i,s]),isSaving:a.isPending}}const x$r=600,w$r=2e3;function S$r({agentId:e,availableAgentTools:t=[],availableSkills:n=[],debounceMs:r=x$r,savedDisplayMs:s=w$r}){const a=Vr(),{save:i}=b$r({agentId:e,availableAgentTools:t,availableSkills:n,silent:!0}),[l,c]=g.useState("idle"),[u,d]=g.useState(null),f=g.useRef(a.getValues()),p=g.useRef(0),h=g.useRef(null),m=g.useCallback(()=>{h.current&&(clearTimeout(h.current),h.current=null)},[]),v=g.useCallback(async()=>{const x=++p.current,k=f.current;m(),c("saving"),d(null);try{if(await i(k),x!==p.current)return;c("saved"),h.current=setTimeout(()=>{h.current=null,c("idle")},s)}catch(_){if(x!==p.current)return;c("error"),d(_ instanceof Error?_:new Error(String(_)))}},[m,i,s]),y=My(()=>{v()},r);g.useEffect(()=>{const x=a.watch(k=>{f.current=k,y()});return()=>{x.unsubscribe()}},[a,y]),g.useEffect(()=>()=>{y.flush(),m()},[m,y]);const b=g.useCallback(()=>{v()},[v]),S=g.useCallback(()=>{y.flush()},[y]);return{status:l,lastError:u,retry:b,flushNow:S}}const CPt=g.createContext(null),k$r=({storedAgent:e,availableAgentTools:t,onModeToggle:n,children:r})=>{const{agentId:s,availableSkills:a,availableWorkspaces:i,initialUserMessage:l,isOwner:c}=aC(),u=Mf(),d=c&&e.visibility==="public",f=l!==void 0,p=S$r({agentId:s,availableAgentTools:t,availableSkills:a}),h=g.useMemo(()=>({agentId:s,isOwner:c,canPublishToChannel:d,features:u,availableAgentTools:t,availableSkills:a,availableWorkspaces:i,autosave:p,onModeToggle:n}),[s,c,d,u,t,a,i,p,n]);return o.jsx(CPt.Provider,{value:h,children:o.jsx(d$r,{agentId:s,features:u,availableAgentTools:t,availableWorkspaces:i,availableSkills:a,initialUserMessage:l,isFreshThread:f,toolsReady:!0,children:r})})},o0=()=>{const e=g.useContext(CPt);if(!e)throw new Error("useEditPage must be used inside <EditPageProvider>");return e};function O$r({platform:e,agentId:t,onCancel:n,onClose:r}){const{mutateAsync:s,isPending:a}=WRt(e.id),i=async()=>{try{await s(t),De.success(`${e.name} disconnected`),r()}catch(l){const c=l;De.error(c.body?.error||c.message||"Failed to disconnect channel")}};return o.jsxs(o.Fragment,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Are you sure?"}),o.jsxs(Ks,{children:["Your agent will be removed from ",o.jsx("span",{className:"text-neutral6",children:e.name}),"."]})]}),o.jsxs(Nc,{children:[o.jsx(le,{variant:"ghost",onClick:n,disabled:a,children:"Cancel"}),o.jsx(le,{variant:"default",onClick:i,disabled:a,"data-testid":`publish-channel-dialog-${e.id}-disconnect-confirm`,children:a?"Disconnecting…":"Confirm"})]})]})}const _$r=({className:e})=>o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[o.jsx("path",{d:"M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zm1.271 0a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313z",fill:"#E01E5A"}),o.jsx("path",{d:"M8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zm0 1.271a2.527 2.527 0 0 1 2.521 2.521 2.527 2.527 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312z",fill:"#36C5F0"}),o.jsx("path",{d:"M18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zm-1.27 0a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312z",fill:"#2EB67D"}),o.jsx("path",{d:"M15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zm0-1.27a2.527 2.527 0 0 1-2.52-2.523 2.527 2.527 0 0 1 2.52-2.52h6.313A2.528 2.528 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z",fill:"#ECB22E"})]}),C$r=({className:e})=>o.jsx("svg",{className:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:o.jsx("path",{d:"M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z",fill:"#5865F2"})}),E$r=({className:e})=>o.jsx("svg",{className:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:o.jsx("path",{d:"M11.944 0A12 12 0 1 0 24 12 12.01 12.01 0 0 0 11.944 0Zm5.625 8.244-1.95 9.2c-.146.658-.537.818-1.084.508l-3-2.211-1.447 1.394c-.16.16-.295.295-.605.295l.215-3.053 5.56-5.023c.242-.213-.054-.334-.375-.12l-6.871 4.326-2.962-.924c-.643-.204-.657-.643.135-.953l11.567-4.46c.537-.194 1.006.131.817.95v.07Z",fill:"#26A5E4"})}),j$r=({className:e})=>o.jsx("svg",{className:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:o.jsx("path",{d:"M9.5 2A1.5 1.5 0 0 0 8 3.5v2A1.5 1.5 0 0 0 9.5 7h5A1.5 1.5 0 0 0 16 5.5v-2A1.5 1.5 0 0 0 14.5 2h-5zM4 8.5A1.5 1.5 0 0 1 5.5 7H7v1.5A1.5 1.5 0 0 0 8.5 10h7a1.5 1.5 0 0 0 1.5-1.5V7h1.5A1.5 1.5 0 0 1 20 8.5v11a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 4 19.5v-11z",fill:"currentColor",opacity:"0.5"})}),T$r={slack:_$r,discord:C$r,telegram:E$r};function MCe({platform:e,className:t}){const n=T$r[e.toLowerCase()]??j$r;return o.jsx(n,{className:t})}const N$r={description:e=>`Manage the ${e} connection for this agent.`,notConfigured:()=>"This platform is not configured on the server.",notConnected:e=>`Publish this agent to ${e}.`,connectLabel:"Connect"},I$r={slack:{description:()=>"Manage the Slack connection for this agent.",notConfigured:()=>"Slack is not configured on the server.",notConnected:()=>"You will be redirected to Slack to choose a workspace and approve permissions.",connectLabel:"Continue with Slack",requireActiveInstallation:!0}};function A$r(e){return{...N$r,...I$r[e]??{}}}function R$r({platform:e,agentId:t,installation:n,onClose:r,onDisconnectRequest:s}){const{connect:a,isConnecting:i}=lCe(e.id,{onClose:r}),l=A$r(e.id),c=l.requireActiveInstallation&&n?.status!=="active"?void 0:n,u=()=>{a(t)};return o.jsxs(o.Fragment,{children:[o.jsxs(wr,{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(MCe,{platform:e.id,className:"h-8 w-8 shrink-0"}),o.jsxs(gr,{children:[e.name," integration"]})]}),o.jsx(Ks,{children:l.description(e.name)})]}),o.jsx($r,{children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:e.isConfigured?c?o.jsxs(o.Fragment,{children:["Connected ",o.jsx("span",{className:"text-neutral6",children:e.name})," to"," ",o.jsx("span",{className:"text-neutral6",children:"Mastra"})]}):l.notConnected(e.name):l.notConfigured(e.name)})}),o.jsx(Nc,{children:e.isConfigured&&c?o.jsx(le,{variant:"default",onClick:s,"data-testid":`publish-channel-dialog-${e.id}-disconnect`,children:"Disconnect"}):e.isConfigured?o.jsx(le,{variant:"default",onClick:u,disabled:i,"data-testid":`publish-channel-dialog-${e.id}-connect`,children:i?"Connecting…":l.connectLabel}):o.jsx(le,{variant:"default",onClick:r,children:"Close"})})]})}function P$r({platform:e,agentId:t,installation:n,open:r,onOpenChange:s,initialView:a="publish"}){const[i,l]=g.useState(a);g.useEffect(()=>{r&&l(a)},[r,a]);const c=()=>s(!1);return o.jsx(br,{open:r,onOpenChange:s,children:o.jsx(xr,{"data-testid":`publish-channel-dialog-${e.id}`,children:i==="publish"?o.jsx(R$r,{platform:e,agentId:t,installation:n,onClose:c,onDisconnectRequest:()=>l("confirm-disconnect")}):o.jsx(O$r,{platform:e,agentId:t,onCancel:()=>l("publish"),onClose:c})})})}function $$r(e){const{canPublishToChannel:t}=o0(),n=Vr(),{updateStoredAgent:r}=O1(e),[s,a]=g.useState(null),[i,l]=g.useState(!1),[c,u]=g.useState(null),d=lCe("slack"),f=g.useCallback(S=>{const{platform:x,installation:k}=S;if(x.id==="slack"&&x.isConfigured&&!k){d.connect(e);return}u(S)},[e,d]),p=g.useCallback((S,x)=>{const k={platform:S,installation:x};if(t){f(k);return}a(k),l(!0)},[t,f]),h=g.useCallback(()=>{l(!1),a(null)},[]),m=g.useCallback(async()=>{if(s)try{await r.mutateAsync({visibility:"public"}),n.setValue("visibility","public",{shouldDirty:!1}),De.success("Agent added to the library");const S=s;l(!1),a(null),f(S)}catch(S){De.error(`Failed to add to library: ${S instanceof Error?S.message:"Unknown error"}`)}},[s,r,n,f]),v=s?.platform.name??"this channel",y=g.useMemo(()=>o.jsx(br,{open:i,onOpenChange:S=>!S&&h(),children:o.jsxs(xr,{"data-testid":"agent-builder-publish-before-connect-dialog",children:[o.jsxs(wr,{children:[o.jsxs(gr,{children:["Add this agent to your library to connect ",v,"?"]}),o.jsxs(Ks,{children:["Connecting to ",v," requires this agent to be in the library so your teammates can use the bot. We'll add it to the library and then continue to ",v,"."]})]}),o.jsxs(Nc,{children:[o.jsx(le,{variant:"ghost",onClick:h,disabled:r.isPending,"data-testid":"agent-builder-publish-before-connect-dialog-cancel",children:"Cancel"}),o.jsx(le,{variant:"default",onClick:m,disabled:r.isPending,"data-testid":"agent-builder-publish-before-connect-dialog-confirm",children:"Add to library & continue"})]})]})}),[i,h,m,v,r.isPending]),b=c?o.jsx(P$r,{platform:c.platform,agentId:e,installation:c.installation,open:!0,onOpenChange:S=>{S||u(null)}}):null;return{requestPublishAndConnect:p,dialog:y,channelDialog:b}}const M$r={slack:"Creates a Slack bot powered by this agent."},EPt=({agentId:e,editable:t=!0})=>{const{data:n=[],isLoading:r}=HW(),{canPublishToChannel:s}=o0(),{requestPublishAndConnect:a,dialog:i,channelDialog:l}=$$r(e);return r?o.jsx("div",{className:"flex justify-center px-6 py-8","data-testid":"integrations-detail-picker-loading",children:o.jsxs("div",{className:"flex w-full max-w-[48rem] flex-col items-center gap-6 text-center",children:[o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx(xt,{className:"h-6 w-48"}),o.jsx(xt,{className:"h-4 w-80"})]}),o.jsxs("div",{className:"flex flex-wrap items-stretch justify-center gap-4",children:[o.jsxs("div",{className:"flex w-48 flex-col items-center gap-3 rounded-xl border border-border1 bg-surface3 px-4 py-6",children:[o.jsx(xt,{className:"size-14 rounded-xl"}),o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsx(xt,{className:"h-4 w-24"}),o.jsx(xt,{className:"h-3 w-32"})]}),o.jsx(xt,{className:"h-badge-default w-20 rounded-full"})]}),o.jsxs("div",{className:"flex w-48 flex-col items-center gap-3 rounded-xl border border-border1 bg-surface3 px-4 py-6",children:[o.jsx(xt,{className:"size-14 rounded-xl"}),o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsx(xt,{className:"h-4 w-24"}),o.jsx(xt,{className:"h-3 w-32"})]}),o.jsx(xt,{className:"h-badge-default w-20 rounded-full"})]})]})]})}):n.length===0?o.jsx("div",{className:"flex justify-center px-6 py-8","data-testid":"integrations-detail-picker",children:o.jsx(ye,{variant:"ui-md",className:"text-neutral3",children:"No integrations configured for this project"})}):o.jsxs("div",{className:"flex justify-center px-6 py-8","data-testid":"integrations-detail-picker",children:[o.jsxs("div",{className:"flex w-full max-w-[48rem] flex-col items-center gap-6 text-center",children:[o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx(ye,{variant:"header-sm",className:"font-semibold text-neutral6",children:"Channel integrations"}),o.jsx(ye,{variant:"ui-md",className:"text-neutral3",children:"Publish this agent to external platforms. Each connection installs a bot in the platform that runs this agent."})]}),o.jsx("div",{className:"flex flex-wrap items-stretch justify-center gap-4",children:n.map(c=>o.jsx(D$r,{platform:c,agentId:e,disabled:!t,requiresLibrary:!s,onSelect:u=>a(c,u)},c.id))})]}),i,l]})},D$r=({platform:e,agentId:t,disabled:n,requiresLibrary:r,onSelect:s})=>{const{data:a=[]}=HRt(e.id,t),i=a.find(u=>u.status==="active"),l=M$r[e.id],c=e.isConfigured&&r;return o.jsxs("button",{type:"button",onClick:()=>s(i),disabled:n,"data-testid":`integration-card-${e.id}`,className:"flex w-48 flex-col items-center gap-3 rounded-xl border border-border1 bg-surface3 px-4 py-6 text-center transition-colors hover:bg-surface4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent1 disabled:cursor-not-allowed disabled:opacity-60",children:[o.jsx("div",{className:"grid size-14 place-items-center rounded-xl bg-surface4",children:o.jsx(MCe,{platform:e.id,className:"h-7 w-7"})}),o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsx(ye,{variant:"ui-md",className:"font-semibold text-neutral6",children:e.name}),l?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:l}):null]}),e.isConfigured?i?o.jsx(bg,{variant:"success",size:"sm",withDot:!0,children:"Connected"}):o.jsx(bg,{variant:"neutral",size:"sm",withDot:!0,children:"Not connected"}):o.jsx(bg,{variant:"warning",size:"sm",withDot:!0,children:"Not configured"}),c?o.jsx(bg,{variant:"warning",size:"sm",withDot:!0,children:"Add to library to connect"}):null]})},L$r=X("group/input-group relative flex w-full flex-1 items-center","border border-border1 text-neutral6",vs.all,"has-[:disabled]:cursor-not-allowed has-[:disabled]:opacity-50","has-[[aria-invalid=true]]:border-error","has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col","has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col","has-[textarea]:h-auto","has-[>[data-align=inline-start]]:[&>[data-slot=input-group-control]]:pl-0","has-[>[data-align=inline-end]]:[&>[data-slot=input-group-control]]:pr-0","has-[>[data-align=block-start]]:[&>[data-slot=input-group-control]]:w-full has-[>[data-align=block-start]]:[&>[data-slot=input-group-control]]:flex-none","has-[>[data-align=block-end]]:[&>[data-slot=input-group-control]]:w-full has-[>[data-align=block-end]]:[&>[data-slot=input-group-control]]:flex-none"),jPt=X("has-[>[data-align=block-start]]:rounded-xl","has-[>[data-align=block-end]]:rounded-xl","has-[textarea]:rounded-xl"),DZe=X("rounded-full bg-surface-overlay-soft","hover:bg-surface-overlay-strong",umt,"outline-hidden focus-within:bg-surface-overlay-strong focus-within:outline-hidden",lmt,jPt),F$r=uo(L$r,{variants:{variant:{default:DZe,filled:DZe,outline:X("rounded-full bg-transparent",umt,"outline-hidden focus-within:outline-hidden",lmt,jPt)}},defaultVariants:{variant:"default"}}),Pu=g.forwardRef(({className:e,size:t="md",variant:n,...r},s)=>o.jsx("div",{ref:s,role:"group","data-slot":"input-group","data-size":t,className:X(F$r({variant:n}),O2[t],e),...r}));Pu.displayName="InputGroup";const z$r=uo(X("flex items-center justify-center gap-2 text-neutral3 select-none","group-has-[:disabled]/input-group:opacity-50","[&>svg:not([class*='size-'])]:size-4"),{variants:{align:{"inline-start":"order-first pr-1 pl-3 has-[>button]:pl-1","inline-end":"order-last pr-3 pl-1 has-[>button]:pr-1","block-start":"order-first w-full justify-start border-b border-border1 px-3 pt-2 pb-1","block-end":"order-last w-full justify-start border-t border-border1 px-3 pt-1 pb-2"}},defaultVariants:{align:"inline-start"}}),Xc=g.forwardRef(({className:e,align:t="inline-start",onClick:n,...r},s)=>o.jsx("div",{ref:s,role:"group","data-slot":"input-group-addon","data-align":t,className:X(z$r({align:t}),e),onClick:a=>{a.target.closest('button, input, textarea, [role="button"]')||a.currentTarget.parentElement?.querySelector("[data-slot=input-group-control]")?.focus(),n?.(a)},...r}));Xc.displayName="InputGroupAddon";const B$r=X("group-data-[size=xs]/input-group:h-form-xs","group-data-[size=sm]/input-group:h-form-sm","group-data-[size=md]/input-group:h-form-md","group-data-[size=default]/input-group:h-form-default","group-data-[size=lg]/input-group:h-form-lg"),TPt=X("group-data-[size=xs]/input-group:text-ui-xs","group-data-[size=sm]/input-group:text-ui-sm","group-data-[size=md]/input-group:text-ui-md","group-data-[size=default]/input-group:text-ui-md","group-data-[size=lg]/input-group:text-ui-lg"),$u=g.forwardRef(({className:e,testId:t,error:n,type:r="text",...s},a)=>o.jsx("input",{ref:a,type:r,"data-slot":"input-group-control","data-testid":t,"aria-invalid":n,className:X("min-w-0 flex-1 bg-transparent px-3 text-neutral6 outline-hidden",B$r,TPt,"placeholder:duration-normal placeholder:text-neutral2 placeholder:transition-opacity","focus:placeholder:opacity-70","disabled:cursor-not-allowed","[&::-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",e),...s}));$u.displayName="InputGroupInput";const U$r=g.forwardRef(({className:e,testId:t,error:n,...r},s)=>o.jsx("textarea",{ref:s,"data-slot":"input-group-control","data-testid":t,"aria-invalid":n,className:X("min-h-15 min-w-0 flex-1 resize-y bg-transparent px-3 py-2 text-neutral6 outline-hidden",TPt,"placeholder:duration-normal placeholder:text-neutral2 placeholder:transition-opacity","focus:placeholder:opacity-70","disabled:cursor-not-allowed",e),...r}));U$r.displayName="InputGroupTextarea";const V$r=g.forwardRef(({className:e,...t},n)=>o.jsx("span",{ref:n,className:X("flex items-center gap-2 text-ui-sm text-neutral3 [&_svg]:pointer-events-none","[&_svg:not([class*='size-'])]:size-4",e),...t}));V$r.displayName="InputGroupText";const NPt=g.forwardRef(({size:e="icon-sm",variant:t="ghost",type:n="button",...r},s)=>o.jsx(le,{ref:s,type:n,size:e,variant:t,...r}));NPt.displayName="InputGroupButton";const IPt=({title:e,subtitle:t,icon:n,isSelected:r,disabled:s=!1,onClick:a,ariaLabel:i,testId:l,checkTestId:c,footer:u})=>{const d=s0(),f={"--agent-color-bg":d.background,...r?{borderColor:d.background}:null},p=r?{borderColor:d.background,backgroundColor:d.background,color:d.foreground}:void 0;return o.jsxs("div",{"data-testid":l,style:f,className:X("flex w-full flex-col gap-2 rounded-lg border bg-surface3 p-4 transition-colors","focus-visible:!border-[var(--agent-color-bg)] focus-within:!border-[var(--agent-color-bg)]",r?"bg-surface4":"border-border1",s&&"opacity-60"),children:[o.jsxs("button",{type:"button",onClick:a,disabled:s,"aria-pressed":r,"aria-label":i,className:X("flex w-full items-center gap-3 text-left outline-none",!s&&"cursor-pointer hover:opacity-90 active:opacity-80",s&&"cursor-not-allowed"),children:[n,o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[o.jsx(ye,{variant:"ui-md",className:"truncate font-medium text-neutral6",children:e}),t&&o.jsx(ye,{variant:"ui-sm",className:"truncate text-neutral3",children:t})]}),o.jsx("span",{"aria-hidden":"true","data-testid":c,style:p,className:X("flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors",!r&&"border-border1 bg-transparent"),children:r&&o.jsx(pa,{className:"h-3 w-3"})})]}),u]})},q$r=({title:e,items:t,isChecked:n,onToggle:r,onSelectAll:s,onClearAll:a,disabled:i=!1,testIdPrefix:l})=>{const c=s0(),[u,d]=g.useState(""),f=g.useMemo(()=>{const p=u.trim().toLowerCase();return p?t.filter(h=>h.label.toLowerCase().includes(p)):t},[t,u]);return o.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border1 py-6 px-6","data-testid":`${l}-filter`,children:[o.jsx("div",{className:"shrink-0 rounded-full bg-surface3","data-testid":`${l}-filter-search`,children:o.jsxs(Pu,{variant:"outline",size:"lg",children:[o.jsx(Xc,{align:"inline-start",children:o.jsx(Ka,{})}),o.jsx($u,{type:"search","aria-label":`Filter ${e.toLowerCase()}`,placeholder:`Filter ${e.toLowerCase()}...`,onChange:p=>d(p.target.value)})]})}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2 text-ui-xs",children:[o.jsx("button",{type:"button",onClick:s,disabled:i,"data-testid":`${l}-filter-select-all`,className:"text-neutral3 transition-colors hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-60",children:"Select all"}),o.jsx("span",{className:"text-neutral2","aria-hidden":!0,children:"·"}),o.jsx("button",{type:"button",onClick:a,disabled:i,"data-testid":`${l}-filter-clear-all`,className:"text-neutral3 transition-colors hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-60",children:"Clear all"})]}),o.jsx(Br,{className:"min-h-0 flex-1",viewPortClassName:"pr-2",children:f.length===0?o.jsx(ye,{variant:"ui-xs",className:"px-1 py-2 text-neutral3",children:"No matches"}):o.jsx("ul",{className:"flex flex-col gap-0.5",children:f.map(p=>{const h=n(p.id),m=h?{backgroundColor:c.background,borderColor:c.background,color:c.foreground}:void 0;return o.jsx("li",{children:o.jsxs("label",{"data-testid":`${l}-filter-item-${p.id}`,"data-checked":h?"true":"false",className:X("flex cursor-pointer select-none items-center gap-2 rounded-md px-2 py-1.5 text-ui-sm text-neutral6 transition-colors hover:bg-surface4",i&&"cursor-not-allowed opacity-60"),children:[o.jsx(Bo,{checked:h,disabled:i,onCheckedChange:()=>r(p.id),style:m,"data-testid":`${l}-filter-checkbox-${p.id}`,className:"h-3.5 w-3.5 shrink-0 shadow-none [&_svg]:h-2.5 [&_svg]:w-2.5 data-[state=checked]:shadow-none"}),p.icon&&o.jsx("span",{className:"flex shrink-0 items-center",children:p.icon}),o.jsx("span",{className:"truncate",children:p.label})]})},p.id)})})})]})},APt=({testId:e})=>o.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:o.jsxs("div",{className:"grid h-full min-h-0 grid-cols-[280px_minmax(0,1fr)] overflow-hidden","data-testid":e,children:[o.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border1 py-6 px-6",children:[o.jsx(xt,{className:"h-10 w-full rounded-md"}),o.jsx(xt,{className:"h-4 w-28"}),o.jsx(xt,{className:"h-7 w-full rounded-md"}),o.jsx(xt,{className:"h-7 w-full rounded-md"}),o.jsx(xt,{className:"h-7 w-full rounded-md"}),o.jsx(xt,{className:"h-7 w-full rounded-md"})]}),o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-6 px-6 py-6",children:[o.jsx("div",{className:"shrink-0 max-w-[30ch]",children:o.jsx(xt,{className:"h-10 w-full rounded-md"})}),o.jsx("div",{className:"flex min-h-0 flex-col gap-6 overflow-y-auto",children:o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsx(xt,{className:"h-4 w-24"}),o.jsxs("div",{className:"grid grid-cols-1 content-start gap-2 lg:gap-6 sm:grid-cols-2 2xl:grid-cols-3",children:[o.jsx(xt,{className:"h-20 rounded-lg"}),o.jsx(xt,{className:"h-20 rounded-lg"}),o.jsx(xt,{className:"h-20 rounded-lg"}),o.jsx(xt,{className:"h-20 rounded-lg"}),o.jsx(xt,{className:"h-20 rounded-lg"}),o.jsx(xt,{className:"h-20 rounded-lg"})]})]})})]})]})}),RPt=({editable:e=!0})=>{const t=Wx();if(t.active&&t.pickerVisible===!1){const r=t.default?.provider,s=t.default?.modelId;return o.jsx("div",{className:"px-6 py-6",children:o.jsx(G$r,{provider:r,modelId:s})})}return o.jsx("div",{className:"h-full min-h-0 overflow-hidden","data-testid":"model-detail-picker",children:o.jsx(H$r,{disabled:!e})})},H$r=({disabled:e=!1})=>{const{setValue:t,control:n}=Vr(),r=Mn({control:n,name:"model"}),s=Wx(),{models:a,isLoading:i}=Y1(),[l,c]=g.useState(""),[u,d]=g.useState(null),f=g.useMemo(()=>{const j=new Map;for(const T of a){const I=pi(T.provider);j.has(I)||j.set(I,T.providerName)}return Array.from(j.entries()).map(([T,I])=>({providerId:T,providerName:I})).sort((T,I)=>T.providerName.localeCompare(I.providerName))},[a]),p=j=>u===null||u.has(j),h=j=>{d(T=>{const I=T??new Set(f.map(R=>R.providerId)),A=new Set(I);return A.has(j)?A.delete(j):A.add(j),A})},m=()=>{d(new Set(f.map(j=>j.providerId)))},v=()=>{d(new Set)},y=g.useMemo(()=>f.map(({providerId:j,providerName:T})=>({id:j,label:T,icon:o.jsx(II,{providerId:j,size:18})})),[f]);if(i)return o.jsx(APt,{testId:"model-card-picker-loading"});const b=pi(r?.provider??""),S=r?.name??"",x=!!(b&&S),k=a.some(j=>pi(j.provider)===b&&j.model===S),_=x&&s.active&&!k,C=Q$r(a,u,l,b),E=u!==null&&u.size===0;return o.jsxs("div",{className:"h-full min-h-0 overflow-hidden",children:[o.jsxs("div",{className:"grid h-full min-h-0 grid-cols-[280px_minmax(0,1fr)] overflow-hidden","data-testid":"model-card-picker",children:[f.length>0&&o.jsx(q$r,{title:"Providers",items:y,isChecked:p,onToggle:h,onSelectAll:m,onClearAll:v,disabled:e,testIdPrefix:"models-provider"}),o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-6 px-6 py-6",children:[o.jsx("div",{"data-testid":"model-card-picker-search",className:"shrink-0 max-w-[30ch] rounded-full bg-surface3",children:o.jsxs(Pu,{variant:"outline",size:"lg",children:[o.jsx(Xc,{align:"inline-start",children:o.jsx(Ka,{})}),o.jsx($u,{type:"search","aria-label":"Search models",placeholder:"Search models or providers...",onChange:j=>c(j.target.value)})]})}),C.length===0?o.jsx("div",{className:"flex min-h-0 items-center justify-center",children:o.jsx(ye,{variant:"ui-md",className:"text-neutral3",children:l.trim()?`No models match "${l.trim()}"`:E?"Select at least one provider to see models":"No models available"})}):o.jsx(W$r,{groups:C,selectedProvider:b,selectedModel:S,disabled:e,onChange:(j,T)=>t("model",{provider:j,name:T},{shouldDirty:!0})})]})]}),_&&o.jsx(Z$r,{provider:b,modelId:S})]})},W$r=({groups:e,selectedProvider:t,selectedModel:n,disabled:r,onChange:s})=>o.jsx("div",{className:"flex min-h-0 flex-col gap-6 overflow-y-auto",children:e.map(a=>o.jsxs("section",{"data-testid":`model-provider-section-${a.providerId}`,className:"flex flex-col gap-3",children:[o.jsx(ye,{variant:"ui-sm",as:"h3",className:"text-neutral3 uppercase tracking-wide","data-testid":`model-provider-section-title-${a.providerId}`,children:a.providerName}),o.jsx("div",{className:"grid grid-cols-1 content-start gap-2 lg:gap-6 sm:grid-cols-2 2xl:grid-cols-3",children:a.models.map(i=>{const c=pi(i.provider)===t&&i.model===n;return o.jsx(IPt,{icon:o.jsx(II,{providerId:i.provider,size:32}),title:i.model,subtitle:i.providerName,isSelected:c,disabled:r,onClick:()=>s(i.provider,i.model),testId:`model-card-${i.provider}-${i.model}`,checkTestId:`model-card-check-${i.provider}-${i.model}`},`${i.provider}__${i.model}`)})})]},a.providerId))}),Z$r=({provider:e,modelId:t})=>o.jsxs("div",{className:"mx-6 mb-6 flex items-start gap-2 rounded-md border border-accent6 bg-accent6Dark/40 px-3 py-2 text-accent6","data-testid":"model-detail-stale-warning",role:"alert",children:[o.jsx(yf,{className:"h-4 w-4 shrink-0 mt-0.5"}),o.jsxs(ye,{variant:"ui-xs",children:[o.jsxs("span",{className:"font-medium",children:[e,"/",t]})," ","is no longer allowed by the admin policy. Pick a different model to save changes."]})]}),G$r=({provider:e,modelId:t})=>o.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border1 bg-surface3 px-3 py-2","data-testid":"model-detail-locked-chip",children:[o.jsx(Cf,{className:"h-4 w-4 shrink-0 text-neutral3"}),o.jsx(ye,{variant:"ui-sm",className:"font-medium text-neutral6 truncate",children:e&&t?`${e}/${t}`:"Locked by admin"}),o.jsx(ye,{variant:"ui-xs",className:"ml-auto shrink-0 text-neutral3",children:"Set by admin"})]});function Q$r(e,t,n,r){const s=n.toLowerCase(),a=e.filter(l=>{const c=pi(l.provider);return t!==null&&!t.has(c)?!1:!!(!s||l.provider.toLowerCase().includes(s)||l.model.toLowerCase().includes(s))}),i=new Map;for(const l of a){const c=pi(l.provider);let u=i.get(c);u||(u={providerId:c,providerName:l.providerName,models:[]},i.set(c,u)),u.models.push(l)}for(const l of i.values())l.models.sort((c,u)=>c.model.localeCompare(u.model));return Array.from(i.values()).sort((l,c)=>{const u=l.providerId===r?0:1,d=c.providerId===r?0:1;return u!==d?u-d:l.providerName.localeCompare(c.providerName)})}const PPt=({editable:e=!0,availableSkills:t=[]})=>{const{setValue:n,getValues:r,watch:s}=Vr(),a=s("skills")??{},i=(l,c)=>{const u=r("skills")??{};n("skills",{...u,[l]:c},{shouldDirty:!0})};return o.jsx("div",{className:"h-full min-h-0 overflow-y-auto py-2",children:t.length===0?o.jsx(K$r,{}):o.jsx("ul",{className:"flex flex-col",children:t.map(l=>{const c=!!a[l.id];return o.jsx("li",{children:o.jsx(Y$r,{skill:l,editable:e,onToggle:i,isChecked:c})},l.id)})})})},Y$r=({skill:e,editable:t,onToggle:n,isChecked:r})=>o.jsxs("label",{className:"flex cursor-pointer items-start gap-3 px-6 py-4 transition-colors hover:bg-surface2","aria-disabled":!t,children:[o.jsx("div",{className:"mt-0.5",children:o.jsx(Bo,{checked:r,onCheckedChange:s=>n(e.id,s===!0),disabled:!t})}),o.jsxs("div",{className:"flex min-w-0 flex-col",children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium text-neutral6",children:e.name}),e.description&&o.jsx(ye,{variant:"ui-xs",className:"mt-0.5 truncate text-neutral3",title:e.description,children:e.description})]})]}),K$r=()=>o.jsx("div",{className:"flex items-center justify-center py-12",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"No skills available in this project."})}),X$r=({item:e,editable:t,onToggle:n})=>{const r=e.type==="integration"&&!!e.providerId&&!!e.toolkit,s=r&&e.hasConnection===!1,a=e.connectionLabels??[],i=r&&!s&&a.length>0;return o.jsx(IPt,{title:e.name,subtitle:e.description||"No description provided",isSelected:e.isChecked,disabled:!t,onClick:()=>n(e,!e.isChecked),ariaLabel:e.name,testId:`tool-card-${e.type}-${e.id}`,checkTestId:`tool-card-check-${e.type}-${e.id}`,footer:r?s?o.jsx(ye,{variant:"ui-xs",className:"flex h-7 items-center text-neutral3","data-testid":`tool-card-requires-connection-${e.type}-${e.id}`,children:"Requires connection"}):i?o.jsx("div",{className:"flex min-h-7 flex-wrap items-center gap-2","data-testid":`tool-card-connections-${e.type}-${e.id}`,children:a.map(l=>o.jsx(un,{className:"h-auto py-0.5 text-[10px]",children:l},l))}):o.jsx("div",{className:"h-7"}):void 0})},J$r=({tools:e,editable:t,onlySelected:n,onOnlySelectedChange:r,onSearch:s,emptyStateDetails:a,onToggle:i})=>{const l=s0(),c=n?{backgroundColor:l.background,borderColor:l.background,color:l.foreground}:void 0;return o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-6 px-6 py-6",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-4",children:[o.jsx("div",{"data-testid":"tools-card-picker-search",className:"max-w-[30ch] flex-1 rounded-full bg-surface3",children:o.jsxs(Pu,{variant:"outline",size:"lg",children:[o.jsx(Xc,{align:"inline-start",children:o.jsx(Ka,{})}),o.jsx($u,{type:"search","aria-label":"Search tools",placeholder:"Search tools...",onChange:u=>s(u.target.value)})]})}),o.jsxs("label",{"data-testid":"tools-only-selected-filter",className:X("inline-flex items-center gap-2 text-ui-xs text-neutral3 select-none cursor-pointer",!t&&"cursor-not-allowed opacity-60"),children:[o.jsx(Bo,{checked:n,onCheckedChange:u=>r(u===!0),disabled:!t,"data-testid":"tools-only-selected-filter-checkbox",style:c,className:"h-3 w-3 shadow-none [&_svg]:h-2.5 [&_svg]:w-2.5 data-[state=checked]:shadow-none"}),o.jsx("span",{children:"Show only selected"})]})]}),e.length===0?o.jsx($Pt,{details:a}):o.jsx("div",{className:"grid min-h-0 grid-cols-1 content-start gap-2 lg:gap-6 overflow-y-auto sm:grid-cols-2 2xl:grid-cols-3",children:e.map(u=>o.jsx(X$r,{item:u,editable:t,onToggle:i},`${u.type}__${u.id}`))})]})},$Pt=({details:e})=>o.jsx("div",{className:"flex min-h-0 items-center justify-center px-3 py-6",children:o.jsx(ye,{variant:"ui-md",className:"text-neutral3",children:e})}),MPt="__built-in__",eMr=e=>{const t=PI(),n=t.data?.providers;return g.useMemo(()=>{const r=new Map;let s=!1;for(const c of e)if(c.type==="integration"&&c.providerId&&c.toolkit){const u=r.get(c.providerId)??new Set;u.add(c.toolkit),r.set(c.providerId,u)}else s=!0;const a=s?[{id:MPt,label:"Built-in"}]:[],i=(n??[]).filter(c=>r.has(c.id)).map(c=>({providerId:c.id,providerName:c.name,presentSlugs:Array.from(r.get(c.id)??new Set)})),l=[...a.map(c=>c.id),...i.flatMap(c=>c.presentSlugs)];return{builtIn:a,providers:i,allToolkitIds:l,isProvidersLoading:t.isLoading}},[e,n,t.isLoading])},tMr=e=>e.type==="integration"&&e.toolkit?e.toolkit:MPt;function nMr(e,t,n,r){const s=t.trim().toLowerCase();return e.filter(a=>r!==null&&!r.has(tMr(a))||n&&!a.isChecked?!1:s?a.name.toLowerCase().includes(s)||(a.description?.toLowerCase().includes(s)??!1):!0)}function rMr(e){const t=e.search.trim();return e.allToolkitsUnchecked?"Select at least one toolkit to see tools":e.onlySelected&&t===""?"No tools selected yet":e.onlySelected?o.jsxs(o.Fragment,{children:["No selected tools match ",t]}):o.jsxs(o.Fragment,{children:["No tools match ",o.jsx("strong",{children:t})]})}const XW=e=>{const t=We();return yt({queryKey:["tool-provider-toolkits",e],queryFn:()=>t.getToolProvider(e).listToolkits(),enabled:!!e})},DPt=()=>{const e=We(),t=Ur();return Rn({mutationFn:async({providerId:n,connectionId:r,force:s})=>e.getToolProvider(n).disconnectConnection(r,s?{force:s}:void 0),onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["tool-integration-connections",r.providerId]})}})},LPt=e=>e.split(/[-_\s]+/).filter(Boolean).map(t=>`${t.charAt(0).toUpperCase()}${t.slice(1)}`).join(" "),sMr=()=>{const e=We(),t=Ur();return Rn({mutationFn:async({providerId:n,connectionId:r,label:s})=>e.getToolProvider(n).updateConnection(r,{label:s}),onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["tool-integration-connections",r.providerId]}),t.invalidateQueries({queryKey:["tool-integration-connections-all",r.providerId]})}})},aMr=400,LZe=e=>{const t=e.trim();return t.length>0?t:null},iMr=({providerId:e,connectionId:t,initialLabel:n})=>{const r=sMr(),s=g.useRef(LZe(n)),a=My(l=>{l!==s.current&&r.mutate({providerId:e,connectionId:t,label:l},{onSuccess:()=>{s.current=l,De.success("Connection renamed")}})},aMr);return g.useEffect(()=>()=>{a.flush()},[a]),{scheduleRename:l=>{const c=LZe(l);if(c===s.current){a.cancel();return}a(c)},isPending:r.isPending,error:r.error}},oMr=({providerId:e,connectionId:t,initialLabel:n,iconUrl:r,disabled:s,testIdPrefix:a,showBack:i,onBack:l,onDisconnected:c})=>{const u=iMr({providerId:e,connectionId:t,initialLabel:n}),d=DPt(),[f,p]=g.useState(n),[h,m]=g.useState(!1),v=LPt(e),y=()=>{d.mutate({providerId:e,connectionId:t,force:!0},{onSuccess:()=>{De.success("Connection disconnected"),c(t)}})};return o.jsxs(o.Fragment,{children:[o.jsxs($r,{className:"flex flex-col gap-3",children:[i&&o.jsxs(le,{type:"button",variant:"ghost",size:"sm",onClick:l,"aria-label":"Back to connections","data-testid":`${a}-back`,className:"-mt-1 -ml-1.5 w-fit text-neutral3",children:[o.jsx(qe,{children:o.jsx(pdt,{})}),"Connections"]}),o.jsxs("div",{className:"flex flex-col items-center gap-4 text-center",children:[o.jsx("div",{className:"grid size-14 place-items-center overflow-hidden rounded-xl bg-surface4","aria-hidden":!0,children:r?o.jsx("img",{src:r,alt:"",className:"size-8 object-contain"}):o.jsx(qe,{size:"lg",className:"text-neutral3",children:o.jsx(Khn,{})})}),o.jsxs("div",{className:"flex w-full flex-col items-center gap-1.5",children:[o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3",children:[v," connection"]}),o.jsxs("div",{className:"relative w-full",children:[o.jsx(Cn,{id:`${a}-input`,variant:"filled",size:"sm",value:f,onChange:b=>{p(b.target.value),u.scheduleRename(b.target.value)},disabled:s||u.isPending,placeholder:"Unnamed connection",autoFocus:!0,"aria-label":"Connection name",testId:`${a}-input`,className:"text-center"}),u.isPending&&o.jsx("span",{className:"absolute top-1/2 right-2 -translate-y-1/2",children:o.jsx(Kt,{size:"sm","aria-label":"Saving","data-testid":`${a}-saving`})})]}),u.error?o.jsx(ye,{variant:"ui-xs",className:"text-red-500",children:String(u.error)}):null]}),o.jsx(le,{type:"button",variant:"ghost",onClick:()=>m(!0),disabled:s||d.isPending,"data-testid":`${a}-disconnect`,children:"Disconnect"})]})]}),o.jsx(At,{open:h,onOpenChange:m,children:o.jsxs(At.Content,{"data-testid":`${a}-disconnect-dialog`,children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Disconnect connection?"}),o.jsx(At.Description,{children:"Disconnecting revokes this authorized account and removes it from Mastra. Agents using this connection will lose access. This can’t be undone."})]}),d.error?o.jsx(ye,{variant:"ui-xs",className:"text-red-500",children:String(d.error)}):null,o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{"data-testid":`${a}-disconnect-cancel`,disabled:d.isPending,children:"Cancel"}),o.jsx(le,{type:"button",variant:"primary",onClick:y,disabled:s||d.isPending,"data-testid":`${a}-disconnect-confirm`,children:d.isPending?"Disconnecting…":"Disconnect"})]})]})})]})},Df=({children:e,className:t,onClick:n})=>o.jsx("div",{tabIndex:n?0:void 0,onKeyDown:r=>{n&&(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n?.())},className:X("group/entity flex gap-3 rounded-xl border border-border1 bg-surface3 px-4 py-3",n&&"cursor-pointer transition-all hover:bg-surface4",t),onClick:n,children:e}),FPt=({children:e,className:t,style:n})=>o.jsx(qe,{size:"lg",className:X("mt-1 shrink-0 text-neutral3",t),style:n,children:e}),Lf=({children:e,className:t})=>o.jsx(ye,{as:"p",variant:"ui-lg",className:X("font-medium text-neutral6",t),children:e}),th=({children:e,className:t})=>o.jsx(ye,{as:"div",variant:"ui-sm",className:X("text-neutral3",t),children:e}),Ff=({children:e,className:t})=>o.jsx("div",{className:X("w-full flex-1",t),children:e}),lMr=({connections:e,testIdPrefix:t,onSelect:n,onAddConnection:r,addingConnection:s=!1,disabled:a=!1})=>o.jsxs(o.Fragment,{children:[o.jsx($r,{"data-testid":`${t}-list`,children:o.jsx("div",{className:"flex flex-col gap-2",role:"list",children:e.map(i=>o.jsx(Df,{className:"relative items-center rounded-lg px-2 py-2 transition-colors hover:bg-surface4",children:o.jsx(Ff,{className:"min-w-0",children:o.jsxs("button",{type:"button",disabled:a,onClick:()=>n(i.connectionId),"data-testid":`${t}-list-item-${i.connectionId}`,className:"flex w-full items-center justify-between gap-2 text-left outline-none after:absolute after:inset-0 after:rounded-lg focus-visible:after:ring-2 focus-visible:after:ring-accent1",children:[o.jsx(Lf,{className:"truncate",children:i.label?.trim()||"Unnamed connection"}),o.jsx(qe,{className:"shrink-0 text-neutral3",children:o.jsx(ha,{})})]})})},i.connectionId))})}),r&&o.jsx(Nc,{children:o.jsxs(le,{type:"button",variant:"outline",size:"sm",onClick:r,disabled:a||s,"data-testid":`${t}-add`,children:[s?o.jsx(Kt,{size:"sm"}):o.jsx(qe,{children:o.jsx(Zr,{})}),"Add connection"]})})]}),cMr=({open:e,onOpenChange:t,providerId:n,connections:r,disabled:s=!1,testIdPrefix:a,onDisconnected:i,iconUrl:l,onAddConnection:c,addingConnection:u=!1})=>{const[d,f]=g.useState(null),p=d===null,h=r.find(v=>v.connectionId===d)??null,m=v=>{v||f(null),t(v)};return o.jsx(br,{open:e,onOpenChange:m,children:o.jsxs(xr,{"data-testid":`${a}-dialog`,className:"sm:max-w-md",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:p?`${LPt(n)} connections`:"Manage connection"}),o.jsx(Ks,{children:"Rename or disconnect this authorized account."})]}),e&&(p?o.jsx(lMr,{connections:r,testIdPrefix:a,onSelect:f,onAddConnection:c,addingConnection:u,disabled:s}):h&&o.jsx(oMr,{providerId:n,connectionId:h.connectionId,initialLabel:h.label??"",iconUrl:l,disabled:s,testIdPrefix:a,showBack:!0,onBack:()=>f(null),onDisconnected:v=>{i(v),r.length<=1?m(!1):f(null)}},h.connectionId))]})})},uMr=2e3,dMr=5*6e4,zPt=(e={})=>{const t=We(),n=e.pollIntervalMs??uMr,r=e.timeoutMs??dMr,s=e.openPopup??(a=>window.open(a,"_blank","popup,width=600,height=700"));return Rn({mutationFn:async({providerId:a,toolkit:i,connectionId:l,config:c,label:u,scope:d})=>{const f=t.getToolProvider(a),p=l?.trim(),{url:h,authId:m}=await f.authorize({toolkit:i,...p?{connectionId:p}:{},...c?{config:c}:{},...u!==void 0?{label:u}:{},...d?{scope:d}:{}}),v=s(h);if(!v)throw new Error("Popup blocked. Please allow popups for this site.");const y=Date.now();for(;Date.now()-y<r;){await new Promise(S=>setTimeout(S,n));const{status:b}=await f.getAuthStatus(m);if(b==="completed"||b==="failed"){try{v.close()}catch{}return{status:b,connectionId:m}}}try{v.close()}catch{}throw new Error("Authorization timed out")}})},BPt=(e,t,n)=>{const r=We(),s=n?.scopeToSelf??!1,a=Cm(),i=a.data?.id,l=!s||a.isSuccess||iRt(a.error);return yt({queryKey:s?["tool-integration-connections",e,t,i]:["tool-integration-connections",e,t],queryFn:()=>r.getToolProvider(e).listConnections({toolkit:t,...s&&i?{authorId:i}:{}}),enabled:!!e&&!!t&&l})},iye=32,fMr=e=>{const t=e.replace(/[^A-Za-z0-9 _-]+/g,"-").replace(/^[-\s]+|[-\s]+$/g,""),n=t.length>0?t:"connection";return n.length>iye?n.slice(0,iye):n},pMr=e=>{const t=new Set;return e.map(n=>{let r=n.label??"";const s=()=>r.toLocaleLowerCase();let a=2;for(;t.has(s());){const i=` ${a++}`;r=`${r.slice(0,iye-i.length)}${i}`}return t.add(s()),r===n.label?n:{...n,label:r}})},hMr=(e,t)=>e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.connectionId===s.connectionId&&n.toolkit===s.toolkit&&n.scope===s.scope&&(n.label??void 0)===(s.label??void 0)}),mMr=({activeConnections:e,pinned:t,toolkit:n})=>{const r=new Map(t.map(a=>[a.connectionId,a])),s=e.map(a=>{const i=r.get(a.connectionId);return{kind:"author",toolkit:n,connectionId:a.connectionId,scope:i?.scope??"per-author",label:i?.label?.trim()||a.label?.trim()||void 0}});return s.length<2?s:pMr(s.map(a=>({...a,label:a.label||fMr(a.connectionId)})))},gMr=({hasSelectedTool:e,currentPins:t,desiredPins:n,connectionsField:r,setValue:s})=>{g.useEffect(()=>{!e||hMr(t,n)||s(r,n,{shouldDirty:!0})},[e,n,t,r,s])},vMr=({providerId:e,toolkit:t,disabled:n=!1,multipleAllowed:r=!1})=>{const{setValue:s}=Vr(),a=Ur(),i=zPt(),l=BPt(e,t,{scopeToSelf:!0}),[c,u]=g.useState(!1),d=XW(c?e:null),f=g.useMemo(()=>d.data?.data?.find(E=>E.slug===t)?.icon,[d.data?.data,t]),p=g.useMemo(()=>`toolProviders.${e}.connections.${t}`,[e,t]),h=Mn({name:p}),m=g.useMemo(()=>h??[],[h]),v=Mn({name:`toolProviders.${e}`}),y=g.useMemo(()=>Object.values(v?.tools??{}).some(E=>E?.toolkit===t),[v?.tools,t]),b=g.useMemo(()=>(l.data?.items??[]).filter(E=>E.status==="active"),[l.data?.items]),S=g.useMemo(()=>mMr({activeConnections:b,pinned:m,toolkit:t}),[b,m,t]),x=g.useMemo(()=>b.map(E=>({connectionId:E.connectionId,label:E.label})),[b]);gMr({hasSelectedTool:y,currentPins:m,desiredPins:S,connectionsField:p,setValue:s});const k=E=>{m.some(j=>j.connectionId===E)&&s(p,m.filter(j=>j.connectionId!==E),{shouldDirty:!0})},_=()=>{i.mutate({providerId:e,toolkit:t,scope:"per-author"},{onSuccess:()=>{a.invalidateQueries({queryKey:["tool-integration-connections",e,t]}),a.invalidateQueries({queryKey:["tool-integration-connections-all",e,t]})}})},C=`${e}-${t}`;return l.isPending?o.jsx(xt,{className:"h-7 w-20","data-testid":`toolkit-connection-loading-${C}`}):b.length===0?o.jsx(le,{type:"button",variant:"outline",size:"sm",onClick:_,disabled:n||i.isPending,"data-testid":`toolkit-connect-${C}`,children:i.isPending?"Connecting…":"Connect"}):o.jsxs("div",{className:"flex items-center gap-1","data-testid":`toolkit-connection-${C}`,children:[o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"Manage connection","aria-label":`Manage ${t} connection`,onClick:()=>u(!0),disabled:n,"data-testid":`toolkit-manage-${C}`,children:o.jsx(z9,{})}),c&&o.jsx(cMr,{open:!0,onOpenChange:u,providerId:e,connections:x,disabled:n,testIdPrefix:`toolkit-manage-${C}`,onDisconnected:k,iconUrl:f,onAddConnection:r?_:void 0,addingConnection:i.isPending})]})},Vk="tools-toolkit",DCe=g.memo(({item:e,checked:t,disabled:n,onToggle:r,providerId:s,multipleAllowed:a})=>{const i=s0(),l=t?{backgroundColor:i.background,borderColor:i.background,color:i.foreground}:void 0;return o.jsxs("li",{className:"flex items-center gap-1",children:[o.jsxs("label",{"data-testid":`${Vk}-filter-item-${e.id}`,"data-checked":t?"true":"false",className:X("flex min-w-0 flex-1 cursor-pointer select-none items-center gap-2 rounded-md px-2 py-1.5 text-ui-sm text-neutral6 transition-colors hover:bg-surface4",n&&"cursor-not-allowed opacity-60"),children:[o.jsx(Bo,{checked:t,disabled:n,onCheckedChange:()=>r(e.id),style:l,"data-testid":`${Vk}-filter-checkbox-${e.id}`,className:"h-3.5 w-3.5 shrink-0 shadow-none [&_svg]:h-2.5 [&_svg]:w-2.5 data-[state=checked]:shadow-none"}),e.icon&&o.jsx("img",{src:e.icon,alt:"","aria-hidden":!0,"data-testid":`${Vk}-filter-icon-${e.id}`,className:"h-4 w-4 shrink-0 rounded object-contain"}),o.jsx("span",{className:"truncate",children:e.label})]}),s&&o.jsx("div",{className:"shrink-0",children:o.jsx(vMr,{providerId:s,toolkit:e.id,disabled:n,multipleAllowed:a})})]})});DCe.displayName="ToolkitFilterRow";const yMr=({provider:e,term:t,isChecked:n,onToggle:r,disabled:s,multipleAllowed:a})=>{const{data:i,isLoading:l}=XW(e.providerId),c=g.useMemo(()=>{const u=new Map,d=new Map;for(const p of i?.data??[])u.set(p.slug,p.name??p.slug),p.icon&&d.set(p.slug,p.icon);const f=e.presentSlugs.map(p=>({id:p,label:u.get(p)??p,icon:d.get(p)})).sort((p,h)=>p.label.localeCompare(h.label));return t?f.filter(p=>p.label.toLowerCase().includes(t)):f},[i,e.presentSlugs,t]);return l?o.jsxs("div",{className:"flex flex-col gap-1 px-2",children:[o.jsx(xt,{className:"h-4 w-20"}),Array.from({length:Math.min(e.presentSlugs.length,3)}).map((u,d)=>o.jsx(xt,{className:"h-7 w-full"},d))]}):c.length===0?null:o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx(ye,{variant:"ui-xs","data-testid":`tools-provider-section-${e.providerId}`,className:"px-2 pt-1 text-neutral3 uppercase tracking-wide",children:e.providerName}),o.jsx("ul",{className:"flex flex-col gap-0.5",children:c.map(u=>o.jsx(DCe,{item:u,checked:n(u.id),disabled:s,onToggle:r,providerId:e.providerId,multipleAllowed:a},u.id))})]})},bMr=({builtIn:e,providers:t,isProvidersLoading:n,isChecked:r,onToggle:s,onSelectAll:a,onClearAll:i,disabled:l=!1,multipleAllowedByProvider:c})=>{const[u,d]=g.useState(""),f=u.trim().toLowerCase(),p=g.useMemo(()=>f?e.filter(h=>h.label.toLowerCase().includes(f)):e,[e,f]);return o.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border1 py-6 px-6","data-testid":`${Vk}-filter`,children:[o.jsx("div",{className:"shrink-0 rounded-full bg-surface3","data-testid":`${Vk}-filter-search`,children:o.jsxs(Pu,{variant:"outline",size:"lg",children:[o.jsx(Xc,{align:"inline-start",children:o.jsx(Ka,{})}),o.jsx($u,{type:"search","aria-label":"Filter toolkits",placeholder:"Filter toolkits...",onChange:h=>d(h.target.value)})]})}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2 text-ui-xs",children:[o.jsx("button",{type:"button",onClick:a,disabled:l,"data-testid":`${Vk}-filter-select-all`,className:"text-neutral3 transition-colors hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-60",children:"Select all"}),o.jsx("span",{className:"text-neutral2","aria-hidden":!0,children:"·"}),o.jsx("button",{type:"button",onClick:i,disabled:l,"data-testid":`${Vk}-filter-clear-all`,className:"text-neutral3 transition-colors hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-60",children:"Clear all"})]}),o.jsx(Br,{className:"min-h-0 flex-1",viewPortClassName:"pr-2",children:o.jsxs("div",{className:"flex flex-col gap-3",children:[p.length>0&&o.jsx("ul",{className:"flex flex-col gap-0.5",children:p.map(h=>o.jsx(DCe,{item:h,checked:r(h.id),disabled:l,onToggle:s},h.id))}),t.map(h=>o.jsx(yMr,{provider:h,term:f,isChecked:r,onToggle:s,disabled:l,multipleAllowed:c.get(h.providerId)??!1},h.providerId)),n&&o.jsx("div",{className:"flex flex-col gap-1 px-2",children:Array.from({length:3}).map((h,m)=>o.jsx(xt,{className:"h-7 w-full"},m))})]})})]})},xMr=()=>{const{setValue:e,getValues:t}=Vr(),n=g.useCallback((a,i)=>{const l=t("toolProviders")??{},c=l[a]??{tools:{},connections:{}};e("toolProviders",{...l,[a]:i(c)},{shouldDirty:!0})},[t,e]),r=g.useCallback((a,i)=>{if(a.type==="integration"&&a.providerId&&a.toolkit){const u=a.name,d=a.toolkit,f=a.description;n(a.providerId,p=>{const h={...p.tools??{}};return i?h[u]={toolkit:d,...f?{description:f}:{}}:delete h[u],{...p,tools:h,connections:{...p.connections??{}}}});return}const l=a.type==="agent"?"agents":a.type==="workflow"?"workflows":"tools",c=t(l)??{};e(l,{...c,[a.id]:i},{shouldDirty:!0})},[t,e,n]),s=g.useCallback((a,i)=>{if(!a.providerId||!a.toolkit)return;const l=a.toolkit,c=a.name,u=a.description;n(a.providerId,d=>{const f={...d.tools??{}};f[c]||(f[c]={toolkit:l,...u?{description:u}:{}});const p=d.connections?.[l]??[],h=p.some(v=>v.connectionId===i),m={...d.connections??{},[l]:h?p:[...p,{kind:"author",toolkit:l,connectionId:i,scope:"per-author"}]};return{...d,tools:f,connections:m}})},[n]);return{toggle:r,pinConnection:s}},wMr=e=>{const[t,n]=g.useState(null),r=g.useCallback(c=>t===null||t.has(c),[t]),s=g.useCallback(c=>{n(u=>{const d=new Set(u??e);return d.has(c)?d.delete(c):d.add(c),d})},[e]),a=g.useCallback(()=>n(null),[]),i=g.useCallback(()=>n(new Set),[]),l=g.useMemo(()=>t!==null&&t.size===0,[t]);return{selected:t,isChecked:r,toggle:s,selectAll:a,clearAll:i,allUnchecked:l}},UPt=({editable:e=!0,availableAgentTools:t=[]})=>{const[n,r]=g.useState(""),[s,a]=g.useState(!1),{builtIn:i,providers:l,allToolkitIds:c,isProvidersLoading:u}=eMr(t),d=wMr(c),{toggle:f}=xMr(),p=PI(),h=g.useMemo(()=>{const b=new Map;for(const S of p.data?.providers??[])b.set(S.id,S.capabilities?.multipleConnectionsPerToolkit??!1);return b},[p.data?.providers]),{isLoading:m}=S3();if(t.length===0)return m?o.jsx(APt,{testId:"tools-card-picker-loading"}):o.jsx("div",{className:"px-6 py-6","data-testid":"tools-empty-state",children:o.jsx($Pt,{details:"No tools available in this project"})});const v=nMr(t,n,s,d.selected),y=rMr({allToolkitsUnchecked:d.allUnchecked,onlySelected:s,search:n});return o.jsxs("div",{className:"grid h-full min-h-0 grid-cols-[280px_minmax(0,1fr)]","data-testid":"tools-card-picker",children:[(u||c.length>0)&&o.jsx(bMr,{builtIn:i,providers:l,isProvidersLoading:u,isChecked:d.isChecked,onToggle:d.toggle,onSelectAll:d.selectAll,onClearAll:d.clearAll,disabled:!e,multipleAllowedByProvider:h}),o.jsx(J$r,{tools:v,editable:e,onlySelected:s,onOnlySelectedChange:a,onSearch:r,emptyStateDetails:y,onToggle:f})]})},SMr=({agentId:e,availableAgentTools:t,availableSkills:n,disabled:r=!1,fallbackInstructions:s})=>{const i={"--tab-indicator-color":s0().background},{isLoading:l}=S3(),c=ZRt({hasAgentTools:t.length>0||l,hasSkills:n.length>0}),u=c.model,d=c.tools,f=c.skills,p=c.browser,h=c.integrations,m="h-full min-h-0 pb-6 pt-6",v="h-full min-h-0 !py-0",y=!r,b=u?"model":d?"tools":"instructions";return o.jsx("div",{className:"h-full min-h-0 overflow-hidden","data-testid":"agent-profile-tabs",children:o.jsxs(Lc,{defaultTab:b,className:"grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] overflow-hidden",children:[o.jsxs(Dc,{variant:"line",sticky:!0,className:"!bg-surface3 px-6",style:i,children:[u&&o.jsx(Rr,{value:"model",children:"Model"}),d&&o.jsx(Rr,{value:"tools",children:"Tools"}),o.jsx(Rr,{value:"instructions",children:"Instructions"}),f&&o.jsx(Rr,{value:"skills",children:"Skills"}),p&&o.jsx(Rr,{value:"browser",children:"Browser"}),h&&o.jsx(Rr,{value:"integrations",children:"Integrations"})]}),o.jsxs("div",{className:"min-h-0 overflow-y-auto h-full",children:[u&&o.jsx(Xr,{value:"model",className:v,children:o.jsx(RPt,{editable:y})}),d&&o.jsx(Xr,{value:"tools",className:v,children:o.jsx(UPt,{availableAgentTools:t,editable:y})}),o.jsx(Xr,{value:"instructions",className:m,children:o.jsx(QRt,{editable:y,fallbackPrompt:s})}),f&&o.jsx(Xr,{value:"skills",className:m,children:o.jsx(PPt,{availableSkills:n,editable:y})}),p&&o.jsx(Xr,{value:"browser",className:m,children:o.jsx(GRt,{editable:y})}),h&&o.jsx(Xr,{value:"integrations",className:m,children:o.jsx(EPt,{agentId:e,editable:y})})]})]})})},oye=["ready","identity","model","tools","instructions","skills","browser","library","integrations","end"],kMr=({gates:e,includeInitial:t})=>{const n=[];for(const r of oye)switch(r){case"ready":case"identity":case"library":t&&n.push(r);break;case"instructions":case"end":n.push(r);break;default:e[r]&&n.push(r);break}return n},OMr=(e,t)=>{if(t.includes(e))return e;const n=oye.indexOf(e);return oye.slice(n+1).find(r=>t.includes(r))??"end"},VPt=g.createContext(null),_Mr=({initialStep:e="end",hasAgentTools:t=!0,children:n})=>{const{availableSkills:r}=aC(),s=ZRt({hasAgentTools:t,hasSkills:r.length>0}),a=g.useMemo(()=>kMr({gates:s,includeInitial:e==="ready"}),[s,e]),[i,l]=g.useState(()=>a.includes(e)?e:a[0]??"end");g.useEffect(()=>{l(p=>OMr(p,a))},[a]);const c=g.useCallback(()=>{l(p=>{const h=a.indexOf(p);return h===-1?p:a[h+1]??p})},[a]),u=g.useCallback(()=>{l(p=>{const h=a.indexOf(p);return h<=0?p:a[h-1]})},[a]),d=a.length>=2&&a[a.length-2]===i,f=g.useMemo(()=>({step:i,next:c,prev:u,steps:a,isLast:d}),[i,c,u,a,d]);return o.jsx(VPt.Provider,{value:f,children:n})},zf=()=>g.useContext(VPt)??{step:"end",next:()=>{},prev:()=>{},steps:[],isLast:!1},gm=e=>{"startViewTransition"in document?document.startViewTransition(()=>{Ni.flushSync(()=>{e()})}):e()},l0=({children:e,cta:t,title:n,description:r,contentClassName:s,panelClassName:a,panelOverlay:i})=>{const l=s0(),c=fu(),{isLast:u,next:d,prev:f,step:p,steps:h}=zf(),m=Hs(),{id:v}=Sr(),y={backgroundImage:`conic-gradient(from 0deg at 50% 50%, ${l.background}, ${l.foreground}, ${l.background})`},b=u&&v,x=h.indexOf(p)>0?o.jsxs(le,{variant:"ghost",onClick:()=>gm(()=>f()),disabled:c,"data-testid":"agent-builder-step-back",children:[o.jsx(qe,{children:o.jsx(Rc,{})})," ","Back"]}):null;return o.jsxs("div",{className:"relative w-full h-full min-h-0 border border-border1 rounded-3xl overflow-hidden p-4",children:[o.jsx("div",{"aria-hidden":!0,className:X("agent-step-banner pointer-events-none",c&&"agent-step-banner-rotating"),style:y}),o.jsxs("div",{className:X("relative h-full overflow-hidden bg-surface3 rounded-2xl grid min-h-0",n?"grid-rows-[auto_minmax(0,1fr)_auto]":"grid-rows-[minmax(0,1fr)_auto]",a),children:[i,n&&o.jsxs("div",{className:"border-b border-border1 px-6 pt-6 pb-4","data-testid":"agent-step-title-section",children:[o.jsx("h2",{className:"text-3xl font-semibold text-neutral6 pb-1",children:n}),r&&o.jsx("div",{className:"w-1/2 text-neutral3",children:r})]}),o.jsx("div",{className:X("min-h-0 overflow-y-auto",s),"data-testid":"agent-step-content",children:e}),b?o.jsxs("div",{className:"flex justify-center items-center gap-2 shrink-0 border-t border-border1 pt-6 pb-6","data-testid":"agent-step-footer",children:[x,o.jsx(le,{variant:"outline",onClick:()=>gm(()=>d()),disabled:c,children:"See agent configuration"}),o.jsx(le,{variant:"primary",onClick:()=>m(`/agent-builder/agents/${v}/view`,{viewTransition:!0}),disabled:c,children:"Try agent"})]}):o.jsxs("div",{className:"flex justify-center items-center gap-2 shrink-0 border-t border-border1 pt-6 pb-6","data-testid":"agent-step-footer",children:[x,t]})]})]})},CMr=()=>{const{next:e}=zf(),t=Hs(),{id:n}=Sr(),r=g.useRef(null);g.useEffect(()=>{const i=r.current;!i||typeof i.animate!="function"||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches||i.animate([{backgroundPosition:"180% 0",opacity:0},{opacity:1,offset:.12},{opacity:1,offset:.88},{backgroundPosition:"-80% 0",opacity:0}],{duration:2400,delay:120,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",fill:"both"})},[]);const s=()=>{gm(()=>{e()})},a=()=>{t(`/agent-builder/agents/${n}/view`,{viewTransition:!0})};return o.jsx(l0,{panelClassName:"ready-stage",panelOverlay:o.jsx("span",{ref:r,className:"ready-stage-sweep","aria-hidden":"true"}),cta:o.jsxs("div",{className:"relative z-[2] flex items-center justify-center gap-3",children:[o.jsx(le,{variant:"outline",onClick:s,"data-testid":"agent-builder-ready-review",children:"Review my agent"}),o.jsx(le,{variant:"primary",onClick:a,"data-testid":"agent-builder-ready-try",children:"Try my agent"})]}),children:o.jsx("div",{className:"w-full h-full flex flex-col items-center justify-center py-6 px-6 text-center",children:o.jsxs("div",{className:"ready-stage-content flex flex-col items-center gap-4",children:[o.jsx("h2",{className:"text-4xl font-semibold text-neutral6","data-testid":"agent-builder-ready-heading",children:"Your agent is ready"}),o.jsx("p",{className:"text-neutral3 text-lg max-w-md",children:"You can review and fine-tune everything, or jump straight in and try it out."})]})})})},EMr=({avatar:e,details:t})=>{const{next:n}=zf(),r=fu(),s=()=>{gm(()=>{n()})};return o.jsx(l0,{cta:o.jsxs(le,{onClick:s,disabled:r,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsxs("div",{className:"relative w-full h-full flex flex-col items-center justify-center gap-4 py-6 px-6 text-center",children:[e,t]})})},jMr=({agentId:e})=>{const{next:t}=zf(),n=fu(),{requestChange:r,dialog:s}=iCe(e),{control:a}=Vr(),l=Mn({control:a,name:"visibility"})==="public",c=()=>{gm(()=>{t()})};return o.jsx(l0,{title:"Add to your library",description:"Adding your agent to the library makes it visible to everyone in your workspace, so teammates can discover it, try it out, and copy it as a starting point for their own agents.",cta:o.jsxs(le,{onClick:c,disabled:n,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsxs("div",{className:"relative w-full h-full flex flex-col items-center justify-center gap-4 py-6 px-6 text-center","data-testid":"agent-builder-library-step",children:[o.jsx(qe,{size:"lg",className:"text-neutral4",children:o.jsx(f$,{})}),l?o.jsxs("p",{className:"flex items-center gap-2 text-neutral2","data-testid":"agent-builder-library-added",children:[o.jsx(qe,{children:o.jsx(pa,{})}),"Added to your library"]}):o.jsx(le,{variant:"primary",onClick:()=>r("public"),disabled:n,"data-testid":"agent-builder-library-add",children:"Add to library"}),o.jsx("p",{className:"text-neutral3 max-w-md",children:"You can change this at any time from the agent's visibility settings — adding to the library now is optional."}),s]})})},TMr=({provider:e,name:t})=>{const n=pi(e);return o.jsxs(un,{variant:"default",children:[o.jsx(II,{providerId:n,size:16})," ",n,"/",t]})},NMr=()=>{const{next:e}=zf(),t=fu(),n=Mn({name:"model"}),r=()=>{gm(()=>{e()})};return o.jsx(l0,{title:"Available models",description:n?o.jsxs("div",{className:"flex items-center gap-2",children:["Selected model: ",o.jsx(TMr,{provider:n.provider,name:n.name})]}):void 0,contentClassName:"overflow-hidden",cta:o.jsxs(le,{onClick:r,disabled:t,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsx(RPt,{editable:!t})})},IMr=()=>{const{availableAgentTools:e}=o0(),{next:t}=zf(),n=fu(),r=e.filter(a=>a.isChecked).length,s=()=>{gm(()=>{t()})};return o.jsx(l0,{title:"Available tools",description:o.jsxs("div",{className:"flex items-center gap-2",children:["Selected tools:"," ",o.jsx(un,{variant:"default",children:o.jsx("strong",{className:"font-semibold text-neutral6",children:r})})]}),contentClassName:"overflow-hidden",cta:o.jsxs(le,{onClick:s,disabled:n,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsx(UPt,{availableAgentTools:e,editable:!n})})},AMr=()=>{const{next:e}=zf(),t=fu(),n=()=>{gm(()=>{e()})};return o.jsx(l0,{title:"Instructions",cta:o.jsxs(le,{onClick:n,disabled:t,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsx(QRt,{editable:!t})})},RMr=()=>{const{availableSkills:e}=o0(),{next:t}=zf(),n=fu(),r=()=>{gm(()=>{t()})};return o.jsx(l0,{title:"Skills",cta:o.jsxs(le,{onClick:r,disabled:n,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsx(PPt,{availableSkills:e,editable:!n})})},PMr=()=>{const{next:e}=zf(),t=fu(),n=()=>{gm(()=>{e()})};return o.jsx(l0,{title:"Browser",cta:o.jsxs(le,{onClick:n,disabled:t,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsx(GRt,{editable:!t})})},$Mr=()=>{const{agentId:e}=o0(),{next:t}=zf(),n=fu(),r=()=>{gm(()=>{t()})};return o.jsx(l0,{title:"Integrations",cta:o.jsxs(le,{onClick:r,disabled:n,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsx(EPt,{agentId:e,editable:!n})})},qPt=({status:e,lastError:t,onRetry:n})=>e==="saving"?o.jsxs("span",{className:"flex items-center gap-1.5 text-ui-sm text-neutral3","data-testid":"agent-builder-autosave-saving",children:[o.jsx(Kt,{size:"sm"}),"Saving…"]}):e==="saved"?o.jsxs("span",{className:"flex items-center gap-1.5 text-ui-sm text-neutral3","data-testid":"agent-builder-autosave-saved",children:[o.jsx(pa,{className:"h-3.5 w-3.5"}),"Saved"]}):e==="error"?o.jsxs("span",{className:"flex items-center gap-1.5 text-ui-sm text-neutral3","data-testid":"agent-builder-autosave-error",children:[o.jsx("span",{title:t?.message,children:"Failed to save"}),o.jsx("button",{type:"button",onClick:n,"data-testid":"agent-builder-autosave-retry",className:"underline underline-offset-2 hover:text-neutral4",children:"Retry"})]}):null,HPt=({className:e,isLoading:t=!1})=>{const{control:n}=Vr(),r=Mn({control:n,name:"name"}),s=r&&r.trim()?r:"Untitled";return o.jsx("div",{className:e,"data-testid":"agent-builder-title",children:o.jsx("div",{className:"flex items-center gap-2 min-w-0",children:o.jsx("span",{className:"block text-ui-md leading-ui-md text-white truncate","data-testid":"agent-builder-title-name",children:t?o.jsx(xt,{className:"inline-block h-4 w-24 align-middle","data-testid":"agent-builder-title-skeleton"}):s})})})},MMr=({isLoading:e,mode:t,onModeToggle:n,modeToggleDisabled:r=!1,rightAside:s,primaryAction:a,mobileExtra:i})=>{const l=t==="test"?"Switch to Edit mode":"Switch to View mode";return o.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-center gap-2 px-4 pt-4 md:px-10",children:[o.jsxs(vwe,{label:"Agent navigation",className:"min-w-0",listClassName:"min-w-0",children:[o.jsx(j$,{as:ti,to:"/agent-builder/agents","data-testid":"agent-builder-back-to-list",children:"Agent list"}),o.jsx(j$,{as:"span",isCurrent:!0,children:o.jsx(HPt,{isLoading:e})})]}),o.jsxs("div",{className:"justify-self-end flex items-center gap-2 shrink-0",children:[s&&o.jsx("div",{className:"shrink-0 mr-1",children:s}),a&&o.jsx("div",{className:"shrink-0 flex",children:a}),i&&o.jsx("div",{className:"shrink-0 lg:hidden",children:i}),t&&n&&o.jsxs(le,{variant:"ghost",size:"sm",onClick:n,disabled:r,className:"hidden lg:inline-flex shrink-0","data-testid":"agent-builder-mode-toggle","aria-label":l,children:[o.jsx(n1,{}),l]})]})]})};function DMr({agentId:e}){const t=Vr(),n=Mn({control:t.control,name:"visibility"}),{requestChange:r,dialog:s}=iCe(e),a=n??"private";return o.jsxs(o.Fragment,{children:[a==="private"?o.jsxs(le,{size:"sm",variant:"default",onClick:()=>r("public"),"data-testid":"agent-builder-visibility-add",children:[o.jsx(Ux,{className:"h-3.5 w-3.5"}),"Add to library"]}):o.jsxs(le,{size:"sm",variant:"ghost",onClick:()=>r("private"),"data-testid":"agent-builder-visibility-remove",children:[o.jsx(Cf,{className:"h-3.5 w-3.5"}),"Remove from library"]}),s]})}const LMr={slack:"Slack"},FMr=e=>e?LMr[e]??e.charAt(0).toUpperCase()+e.slice(1):"channel",WPt=()=>{const[e]=Pi(),t=g.useRef(null),n=e.get("channel_connected"),r=e.get("channel_error"),s=e.get("platform"),a=e.get("team");g.useEffect(()=>{if(n!=="true"&&!r)return;const i=r?`error:${s}:${r}`:`success:${s}:${a}`;if(t.current===i)return;t.current=i;const l=FMr(s);if(n==="true"){const c=a?` workspace "${a}"`:"";De.success(`Connected to ${l}${c}`)}else De.error(`Failed to connect ${l}: ${r}`)},[n,r,s,e,a])},zMr=({topBar:e,chat:t,chatFooter:n,profile:r,variant:s="split",hideMobileChat:a=!1})=>{const i=s==="centered",l=a&&!i;return o.jsxs("div",{className:"h-full grid grid-rows-[auto_1fr]",children:[e,o.jsxs("div",{className:X("flex flex-1 min-h-0 min-w-0 flex-col pt-4 pb-4 md:pb-10",!i&&"lg:grid lg:grid-rows-1 lg:grid-cols-[1fr_2fr]"),children:[o.jsx("div",{className:X("h-full w-full min-w-0 overflow-hidden px-4 md:px-10",i&&"lg:mx-auto lg:max-w-[80ch]",l&&"hidden lg:block"),"data-testid":"agent-builder-panel-chat",style:{viewTransitionName:"agent-builder-chat-panel"},children:o.jsxs("div",{className:"min-h-0 min-w-0 h-full overflow-hidden md:max-w-[80ch] md:mx-auto w-full grid grid-rows-[1fr_auto]",children:[o.jsx("div",{className:"min-h-0 min-w-0 h-full overflow-hidden",children:t}),n?o.jsx("div",{"data-testid":"agent-builder-chat-footer",className:"w-full pt-3 lg:hidden",children:n}):null]})}),!i&&o.jsx("div",{className:X("min-w-0 overflow-hidden","flex-1 px-4 md:px-10","lg:flex-none lg:h-full lg:min-h-0 lg:pl-0 lg:pr-10"),"data-testid":"agent-builder-panel-profile",style:{viewTransitionName:"agent-builder-profile-panel"},children:o.jsx("div",{className:"h-full min-h-0 w-full min-w-0 overflow-hidden",children:r})})]})]})};function BMr(e){if(e&&typeof e=="object"&&"type"in e&&e.type==="id"){const t=e.workspaceId;return typeof t=="string"?t:void 0}}function UMr(e){if(!e)return{};if(Array.isArray(e)){const t={};for(const n of e)Object.assign(t,n.value);return t}return e}function VMr(e){if(!e||Array.isArray(e))return;const t=e.provider,n=e.name;if(typeof t=="string"&&t.length>0&&typeof n=="string"&&n.length>0)return{provider:t,name:n}}function ZPt(e){const t=e?.metadata&&typeof e.metadata=="object"&&"avatarUrl"in e.metadata?e.metadata.avatarUrl:void 0;return{name:e?.name??"",description:e?.description??"",instructions:typeof e?.instructions=="string"?e.instructions:"",tools:Object.fromEntries(Object.keys(e?.tools??{}).map(n=>[n,!0])),agents:Object.fromEntries(Object.keys(e?.agents??{}).map(n=>[n,!0])),workflows:Object.fromEntries(Object.keys(e?.workflows??{}).map(n=>[n,!0])),skills:Object.fromEntries(Object.keys(UMr(e?.skills)).map(n=>[n,!0])),workspaceId:BMr(e?.workspace),browserEnabled:e?.browser!=null,visibility:e?.visibility,avatarUrl:t,model:VMr(e?.model),toolProviders:g$r(e?.toolProviders)}}function qMr(){const{id:e}=Sr();return WPt(),o.jsx(SPr,{agentId:e,children:o.jsx(HMr,{})})}const HMr=()=>{const{agentId:e,storedAgent:t,isReady:n,isOwner:r,canWrite:s}=aC();return n?t?!s||!r?o.jsx(Vu,{to:`/agent-builder/agents/${e}/view`,replace:!0}):o.jsx(WMr,{}):o.jsx(Vu,{to:"/agent-builder/agents",replace:!0}):o.jsx(JMr,{})},WMr=()=>{const{agentId:e,storedAgent:t}=aC(),[n]=g.useState(()=>ZPt(t)),r=q1({defaultValues:n});return o.jsx(M$,{...r,children:o.jsx(lD,{agentId:e,children:o.jsx(ZMr,{})})})},ZMr=()=>{const{agentId:e,storedAgent:t,toolsData:n,agentsData:r,workflowsData:s,isOwner:a,initialUserMessage:i}=aC(),l=Hs(),{control:c}=Vr(),u=Mn({control:c,name:"tools"}),d=Mn({control:c,name:"agents"}),f=Mn({control:c,name:"workflows"}),p=mPt({toolsData:n,agentsData:r,workflowsData:s,selectedTools:u,selectedAgents:d,selectedWorkflows:f,excludeAgentId:e}),{isLoading:h}=S3(),m=a?()=>l(`/agent-builder/agents/${e}/view`,{viewTransition:!0}):void 0;return o.jsx(_Mr,{initialStep:i?"ready":"end",hasAgentTools:p.length>0||h,children:o.jsx(k$r,{storedAgent:t,availableAgentTools:p,onModeToggle:m,children:o.jsx(GMr,{})})})},GMr=()=>{const{step:e}=zf(),t=Mf(),n=e2t(),{control:r}=Vr(),{dirtyFields:s}=u1e({control:r}),a=Mn({control:r,name:"name"})??"",i=Mn({control:r,name:"description"})??"",l=Mn({control:r,name:"instructions"})??"",c=Mn({control:r,name:"model.name"})??"",u=(y,b)=>!!y||b.trim().length>0,d=u(s.name,a)&&u(s.description,i)&&u(s.instructions,l)&&(!t.model||u(s.model?.name,c)),p=e==="ready"&&!(d&&!n)||e==="identity"&&!d,h=p?"centered":"split",m=p,v=e==="identity"&&d&&!n;return o.jsx(zMr,{topBar:o.jsx(YMr,{}),chat:o.jsx(f$r,{}),chatFooter:v?o.jsx(QMr,{}):void 0,profile:m?null:o.jsx(XMr,{}),variant:h,hideMobileChat:e==="end"})},QMr=()=>{const{next:e}=zf(),t=Hs(),{agentId:n}=o0();return o.jsxs("div",{className:"flex flex-col gap-2 lg:hidden","data-testid":"agent-builder-mobile-initial-ctas",children:[o.jsx(le,{variant:"primary",onClick:()=>t(`/agent-builder/agents/${n}/view`,{viewTransition:!0}),"data-testid":"agent-builder-mobile-initial-cta-chat",children:"Chat with my agent"}),o.jsx(le,{variant:"outline",onClick:()=>gm(()=>e()),"data-testid":"agent-builder-mobile-initial-cta-config",children:"See configuration"})]})},YMr=()=>{const{autosave:e,onModeToggle:t}=o0(),n=fu(),{step:r}=zf(),s=r!=="end";return o.jsx(MMr,{isLoading:!1,mode:"build",onModeToggle:s?void 0:t,modeToggleDisabled:n,rightAside:o.jsx(qPt,{status:e.status,lastError:e.lastError,onRetry:e.retry}),mobileExtra:o.jsx(KMr,{})})},KMr=()=>{const{agentId:e}=o0(),t=fu(),{data:n}=dc(),{control:r}=Vr(),s=Mn({control:r,name:"name"})??"";return o.jsx(FRt,{agentId:e,showSetVisibility:!!n?.enabled,showDelete:!0,showViewAgent:!0,agentName:s,disabled:t})},XMr=()=>{const{agentId:e,availableAgentTools:t,availableSkills:n,isOwner:r}=o0(),s=fu(),{data:a}=dc(),{control:i}=Vr(),l=Mn({control:i,name:"name"})??"",{step:c}=zf(),u=o.jsxs("div",{className:"hidden lg:flex items-center gap-2","data-testid":"agent-builder-hero-actions-desktop",children:[a?.enabled&&o.jsx("span",{style:{viewTransitionName:"agent-visibility-select"},children:o.jsx(DMr,{agentId:e})}),r&&o.jsx(xjr,{agentId:e,agentName:l,disabled:s})]});return c==="ready"?o.jsx(CMr,{}):c==="identity"?o.jsx(EMr,{avatar:o.jsx(GWe,{disabled:s}),details:o.jsx(QWe,{mode:"highlighted",disabled:s})}):c==="library"?o.jsx(jMr,{agentId:e}):c==="model"?o.jsx(NMr,{}):c==="tools"?o.jsx(IMr,{}):c==="instructions"?o.jsx(AMr,{}):c==="skills"?o.jsx(RMr,{}):c==="browser"?o.jsx(PMr,{}):c==="integrations"?o.jsx($Mr,{}):o.jsxs(kjr,{children:[o.jsx(Ojr,{avatar:o.jsx(GWe,{disabled:s}),details:o.jsx(QWe,{disabled:s}),actions:u}),o.jsx(SMr,{agentId:e,availableAgentTools:t,availableSkills:n,disabled:s})]})},JMr=()=>o.jsx("div",{className:"h-screen w-screen flex items-center justify-center",children:o.jsx(Kt,{})}),GPt=g.createContext(null);function O3(){const e=g.useContext(GPt);if(!e)throw new Error("useBrowserSession must be used within a BrowserSessionProvider");return e}const QPt=g.createContext(null);function YPt(){const e=g.useContext(QPt);if(!e)throw new Error("useBrowserFrame must be used within a BrowserSessionProvider");return{latestFrame:g.useSyncExternalStore(e.subscribe,e.getSnapshot)}}const eDr=["browser_","stagehand_"];function tDr(e){return eDr.some(t=>e.startsWith(t))}function nDr(e){if(!e||typeof e!="object")return!1;const t=e;return t.success===!1&&typeof t.code=="string"}const LCe=g.createContext(null);function JW({children:e}){const[t,n]=g.useState(new Map),r=g.useCallback(i=>{n(l=>{const c=l.get(i.toolCallId);if(c&&c.result===i.result&&c.status===i.status)return l;const u=new Map(l);return u.set(i.toolCallId,c?{...i,timestamp:c.timestamp}:i),u})},[]),s=g.useMemo(()=>Array.from(t.values()).sort((i,l)=>i.timestamp-l.timestamp),[t]),a=g.useMemo(()=>({toolCalls:s,registerToolCall:r}),[s,r]);return o.jsx(LCe.Provider,{value:a,children:e})}function FCe(){const e=g.useContext(LCe);if(!e)throw new Error("useBrowserToolCalls must be used within a BrowserToolCallsProvider");return e}function rDr(){return g.useContext(LCe)}const FZe={browser_goto:"Go to",browser_click:"Click",browser_type:"Type",browser_scroll:"Scroll",browser_snapshot:"Snapshot",browser_close:"Close",browser_select:"Select",browser_press:"Press",browser_hover:"Hover",browser_back:"Back",browser_dialog:"Dialog",browser_wait:"Wait",browser_tabs:"Tabs",browser_drag:"Drag",browser_evaluate:"Evaluate",stagehand_navigate:"Navigate",stagehand_act:"Act",stagehand_extract:"Extract",stagehand_observe:"Observe",stagehand_close:"Close",stagehand_tabs:"Tabs"},sDr={browser_goto:"url",browser_click:"ref",browser_type:"text",browser_scroll:"direction",browser_close:"reason",browser_select:"value",browser_press:"key",browser_hover:"ref",browser_dialog:"action",browser_wait:"time",browser_tabs:"action",browser_drag:"sourceRef",browser_evaluate:"expression",stagehand_navigate:"url",stagehand_act:"action",stagehand_extract:"instruction",stagehand_observe:"instruction",stagehand_tabs:"action"};function aDr(e){return FZe[e]?FZe[e]:e.replace(/^(browser_|stagehand_)/,"")}function iDr(e,t){const n=sDr[e];if(!n)return null;const r=t[n];if(r==null)return null;const s=String(r);return s.length>50?`${s.slice(0,47)}...`:s}function KPt({entry:e}){const[t,n]=g.useState(!1),r=aDr(e.toolName),s=iDr(e.toolName,e.args),{__mastraMetadata:a,...i}=e.args;return o.jsxs("div",{className:"border-b border-border1 last:border-b-0",children:[o.jsxs("button",{type:"button",onClick:()=>n(l=>!l),"aria-expanded":t,className:"flex items-center gap-2 w-full px-3 py-0.5 text-left hover:bg-surface3 transition-colors",children:[o.jsx(ha,{className:X("h-3 w-3 text-neutral3 transition-transform shrink-0",t&&"rotate-90")}),o.jsx(oDr,{status:e.status}),o.jsx("span",{className:"text-xs font-medium text-neutral6 shrink-0",children:r}),s&&o.jsx("span",{className:"text-xs text-neutral3 truncate",children:s})]}),t&&o.jsxs("div",{className:"px-3 pb-2 space-y-2",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-xs font-medium text-neutral4 pb-1",children:"Arguments"}),o.jsx(Wr,{data:i,"data-testid":"browser-tool-args"})]}),e.result!==void 0&&e.result!==null&&o.jsxs("div",{children:[o.jsx("p",{className:"text-xs font-medium text-neutral4 pb-1",children:"Result"}),typeof e.result=="string"?o.jsx("pre",{className:"whitespace-pre text-xs bg-surface4 p-2 rounded-md overflow-x-auto max-h-40 overflow-y-auto",children:e.result}):o.jsx(Wr,{data:e.result,"data-testid":"browser-tool-result"})]})]})]})}function oDr({status:e}){switch(e){case"pending":return o.jsx(oa,{className:"h-3 w-3 text-neutral4 animate-spin shrink-0"});case"complete":return o.jsx(pa,{className:"h-3 w-3 text-green-500 shrink-0"});case"error":return o.jsx(bs,{className:"h-3 w-3 text-red-500 shrink-0"})}}const lDr=10;function cDr(e){const[t,n]=g.useState([]),r=g.useRef(0),s=g.useRef(e.viewport);g.useEffect(()=>{s.current=e.viewport},[e.viewport]);const a=g.useCallback(i=>{n(l=>l.filter(c=>c.id!==i))},[]);return g.useEffect(()=>{if(!e.enabled||!e.imgRef.current)return;const i=e.imgRef.current;function l(c){if(c.button!==0)return;const u=s.current;if(!u)return;const d=i.getBoundingClientRect(),f=c.clientX-d.left,p=c.clientY-d.top,h=Math.min(d.width/u.width,d.height/u.height),m=u.width*h,v=u.height*h,y=(d.width-m)/2,b=(d.height-v)/2,S=f-y,x=p-b;S<0||x<0||S>m||x>v||n(k=>{if(k.length>=lDr)return k;const _=++r.current;return[...k,{id:_,x:f,y:p}]})}return i.addEventListener("mousedown",l),()=>{i.removeEventListener("mousedown",l)}},[e.enabled,e.imgRef]),{ripples:t,removeRipple:a}}function uDr(){const{toolCalls:e}=FCe();return g.useMemo(()=>{const t=e.filter(s=>s.status==="pending"),n=t.length>0,r=n?t[0].toolName:null;return{isAgentBusy:n,activeToolName:r,pendingCount:t.length}},[e])}const dDr=16,zZe=500;function ZF(e,t,n,r){const s=e-n.left,a=t-n.top,i=Math.min(n.width/r.width,n.height/r.height),l=r.width*i,c=r.height*i,u=(n.width-l)/2,d=(n.height-c)/2,f=s-u,p=a-d;return f<0||p<0||f>l||p>c?null:{x:f/i,y:p/i}}function BZe(e,t,n){let r;switch(t){case 0:r=e;break;case 1:r=e*dDr;break;case 2:r=e*(n??800);break;default:r=e}return Math.max(-zZe,Math.min(zZe,r))}function Sj(e){let t=0;return e.altKey&&(t|=1),e.ctrlKey&&(t|=2),e.metaKey&&(t|=4),e.shiftKey&&(t|=8),t}function fDr(e){return e.length===1}function pDr(e){const t=g.useRef(e.sendMessage),n=g.useRef(e.onEscape);g.useEffect(()=>{t.current=e.sendMessage},[e.sendMessage]),g.useEffect(()=>{n.current=e.onEscape},[e.onEscape]),g.useEffect(()=>{if(!e.enabled)return;function r(l,c,u,d,f){const p={type:"keyboard",eventType:l};c!==void 0&&(p.key=c),u!==void 0&&(p.code=u),d!==void 0&&(p.text=d),f&&(p.modifiers=f),t.current(JSON.stringify(p))}function s(l){if(l.isComposing||l.keyCode===229)return;if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),n.current();return}l.preventDefault(),l.stopPropagation();const c=Sj(l),u=fDr(l.key);r("keyDown",l.key,l.code,void 0,c),u&&r("char",l.key,void 0,l.key,c)}function a(l){l.isComposing||l.keyCode===229||l.key!=="Escape"&&(l.preventDefault(),l.stopPropagation(),r("keyUp",l.key,l.code,void 0,Sj(l)))}function i(l){const c=l.data;if(c)for(const u of c)r("keyDown",u,void 0,void 0,0),r("char",u,void 0,u,0),r("keyUp",u,void 0,void 0,0)}return document.addEventListener("keydown",s,{capture:!0}),document.addEventListener("keyup",a,{capture:!0}),document.addEventListener("compositionend",i),()=>{document.removeEventListener("keydown",s,{capture:!0}),document.removeEventListener("keyup",a,{capture:!0}),document.removeEventListener("compositionend",i)}},[e.enabled])}function hDr(e){const t=g.useRef(e.viewport),n=g.useRef(e.sendMessage);g.useEffect(()=>{t.current=e.viewport},[e.viewport]),g.useEffect(()=>{n.current=e.sendMessage},[e.sendMessage]),g.useEffect(()=>{if(!e.enabled||!e.imgRef.current)return;const r=e.imgRef.current;function s(v,y,b,S,x,k,_,C){const E={type:"mouse",eventType:v,x:y,y:b};S!==void 0&&(E.button=S),x!==void 0&&(E.clickCount=x),k!==void 0&&(E.modifiers=k),_!==void 0&&(E.deltaX=_),C!==void 0&&(E.deltaY=C),n.current(JSON.stringify(E))}function a(v){return v===2?"right":v===1?"middle":"left"}function i(v){const y=t.current;if(!y)return;const b=r.getBoundingClientRect(),S=ZF(v.clientX,v.clientY,b,y);if(!S)return;const x=a(v.button),k=Sj(v);s("mouseMoved",S.x,S.y,void 0,void 0,k),s("mousePressed",S.x,S.y,x,1,k)}function l(v){const y=t.current;if(!y)return;const b=r.getBoundingClientRect(),S=ZF(v.clientX,v.clientY,b,y);if(!S)return;const x=a(v.button);s("mouseReleased",S.x,S.y,x,1,Sj(v))}function c(v){v.preventDefault()}function u(v){v.preventDefault();const y=t.current;if(!y)return;const b=r.getBoundingClientRect(),S=ZF(v.clientX,v.clientY,b,y);if(!S)return;const x=BZe(v.deltaX,v.deltaMode,y.height),k=BZe(v.deltaY,v.deltaMode,y.height);s("mouseWheel",S.x,S.y,void 0,void 0,Sj(v),x,k)}let d=null,f=0,p=null;const h=1e3/30;function m(v){p=v,d===null&&(d=requestAnimationFrame(y=>{if(d=null,!p||y-f<h)return;f=y;const S=t.current;if(!S){p=null;return}const x=p;p=null;const k=r.getBoundingClientRect(),_=ZF(x.clientX,x.clientY,k,S);_&&s("mouseMoved",_.x,_.y,void 0,void 0,Sj(x))}))}return r.addEventListener("mousedown",i),r.addEventListener("mouseup",l),r.addEventListener("contextmenu",c),r.addEventListener("wheel",u,{passive:!1}),r.addEventListener("mousemove",m),()=>{r.removeEventListener("mousedown",i),r.removeEventListener("mouseup",l),r.removeEventListener("contextmenu",c),r.removeEventListener("wheel",u),r.removeEventListener("mousemove",m),d!==null&&cancelAnimationFrame(d)}},[e.enabled,e.imgRef])}const mDr={browser_navigate:"Navigating",browser_goto:"Navigating",browser_click:"Clicking",browser_type:"Typing",browser_scroll:"Scrolling",browser_screenshot:"Capturing",browser_snapshot:"Reading page",browser_close:"Closing",browser_select:"Selecting",stagehand_navigate:"Navigating",stagehand_act:"Acting",stagehand_extract:"Extracting",stagehand_observe:"Observing",stagehand_screenshot:"Capturing",stagehand_close:"Closing"};function gDr({toolName:e}){const t=e?mDr[e]??e.replace(/^(browser_|stagehand_)/,""):"Working";return o.jsx("div",{className:"absolute inset-0 bg-surface1/40 flex items-center justify-center z-10 cursor-not-allowed",children:o.jsxs("div",{className:"flex items-center gap-2 bg-surface2 px-3 py-1.5 rounded-md border border-border1 shadow-sm",children:[o.jsx(oa,{className:"h-3.5 w-3.5 text-accent1 animate-spin"}),o.jsxs("span",{className:"text-xs font-medium text-neutral4",children:["Agent: ",t]})]})})}const lye=32,UZe=lye/2;function vDr({ripples:e,onAnimationEnd:t}){return e.length===0?null:o.jsx(o.Fragment,{children:e.map(n=>o.jsx("span",{className:"absolute rounded-full pointer-events-none animate-click-ripple bg-accent1/40",style:{left:n.x-UZe,top:n.y-UZe,width:lye,height:lye},onAnimationEnd:()=>t(n.id)},n.id))})}function XPt({className:e,onStatusChange:t,onUrlChange:n,onFirstFrame:r}){const s=g.useRef(null),a=g.useRef(null),i=g.useRef(!1),[l,c]=g.useState(!1),[u,d]=g.useState(!1),{status:f,currentUrl:p,viewport:h,sendMessage:m}=O3(),{latestFrame:v}=YPt();g.useEffect(()=>{v&&s.current&&(s.current.src=`data:image/jpeg;base64,${v}`,i.current||(i.current=!0,c(!0)))},[v]);const y=g.useCallback(()=>{d(!1)},[]),b=g.useCallback(()=>{f==="streaming"&&d(!0)},[f]),{isAgentBusy:S,activeToolName:x}=uDr();hDr({imgRef:s,viewport:h,sendMessage:m,enabled:f==="streaming"&&!S}),pDr({sendMessage:m,enabled:u&&f==="streaming"&&l&&!S,onEscape:y});const{ripples:k,removeRipple:_}=cDr({imgRef:s,viewport:h,enabled:f==="streaming"&&l&&!S});g.useEffect(()=>{t?.(f)},[f,t]),g.useEffect(()=>{n?.(p)},[p,n]),g.useEffect(()=>{l&&r?.()},[l,r]),g.useEffect(()=>{if(!u)return;function T(A){a.current&&!a.current.contains(A.target)&&d(!1)}function I(){d(!1)}return document.addEventListener("mousedown",T),window.addEventListener("blur",I),()=>{document.removeEventListener("mousedown",T),window.removeEventListener("blur",I)}},[u]),g.useEffect(()=>{f!=="streaming"&&d(!1)},[f]);const C=(f==="connecting"||f==="browser_starting"||f==="streaming")&&!l,E=f==="disconnected"&&l,j=f==="error";return o.jsxs("div",{ref:a,className:X("relative w-full aspect-video bg-surface2 rounded-md overflow-hidden",u&&!S&&"ring-2 ring-accent1",u&&S&&"ring-2 ring-amber-400",e),children:[o.jsx("img",{ref:s,alt:"Browser screencast",onClick:b,onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),b())},tabIndex:f==="streaming"?0:-1,role:"button",className:X("absolute inset-0 w-full h-full object-contain",l?"opacity-100":"opacity-0",f==="streaming"&&(u?"cursor-text":"cursor-pointer"))}),o.jsx(vDr,{ripples:k,onAnimationEnd:_}),S&&o.jsx(gDr,{toolName:x}),C&&o.jsx(xt,{className:"absolute inset-0"}),E&&o.jsx("div",{className:"absolute inset-0 bg-surface1/80 flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx("div",{className:"w-4 h-4 border-2 border-neutral4 border-t-transparent rounded-full animate-spin"}),o.jsx("span",{className:"text-sm text-neutral4",children:"Reconnecting..."})]})}),j&&o.jsx("div",{className:"absolute inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 px-6 py-4 text-center",children:[o.jsx("div",{className:"w-14 h-14 rounded-full bg-red-500/20 flex items-center justify-center",children:o.jsx("svg",{className:"w-7 h-7 text-red-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"})})}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-lg font-medium text-white",children:"Connection Error"}),o.jsx("span",{className:"text-sm text-white/70",children:"Failed to connect to browser"})]})]})})]})}function JPt({agentName:e="Agent"}){const{hasSession:t,viewMode:n,status:r,currentUrl:s,setViewMode:a,closeBrowser:i}=O3(),{latestFrame:l}=YPt(),{toolCalls:c}=FCe(),u=g.useRef(null),[d,f]=g.useState(!1),p=g.useRef(null),h=n==="expanded";g.useEffect(()=>{if(l){const x=`data:image/jpeg;base64,${l}`;u.current&&(u.current.src=x),d||f(!0)}},[l,d]),g.useEffect(()=>{t||(f(!1),u.current&&(u.current.src=""))},[t]),g.useEffect(()=>{h&&p.current&&(p.current.scrollTop=p.current.scrollHeight)},[c.length,h]);const m=g.useCallback(()=>{a(h?"collapsed":"expanded")},[h,a]),v=g.useCallback(()=>{a("modal")},[a]),y=g.useCallback(async()=>{await i()},[i]),b=g.useMemo(()=>{if(!s)return"Browser";try{return new URL(s).hostname}catch{return s}},[s]);if(!t||n==="modal")return null;const S=r==="streaming";return o.jsxs("div",{className:X("bg-surface2 border border-border1 rounded-3xl overflow-hidden transition-all duration-200","hover:border-border2"),children:[o.jsxs("button",{type:"button",onClick:m,className:X("group flex items-center gap-3 w-full px-4 py-3","hover:bg-surface3 transition-colors","focus:outline-none focus:ring-2 focus:ring-accent1 focus:ring-inset"),children:[o.jsxs("div",{className:"relative shrink-0 w-24 h-14 bg-surface3 rounded-md overflow-hidden border border-border1",children:[d?o.jsx("img",{ref:u,alt:"Browser preview",className:"w-full h-full object-cover"}):o.jsx("div",{className:"flex items-center justify-center w-full h-full",children:o.jsx(Odt,{className:"h-5 w-5 text-neutral3"})}),S&&o.jsx("div",{className:"absolute top-1 right-1 w-2 h-2 bg-success rounded-full animate-pulse"})]}),o.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("span",{className:"text-sm font-medium text-neutral6 truncate",children:[e,"'s browser"]}),o.jsx(bg,{variant:S?"success":"neutral",size:"sm",withDot:!0,pulse:S,children:S?"Live":"Idle"})]}),o.jsx("p",{className:"text-xs text-neutral4 truncate mt-0.5",children:b})]}),o.jsx("div",{className:"shrink-0 text-neutral4 group-hover:text-neutral5 transition-colors",children:h?o.jsx(Ia,{className:"h-5 w-5"}):o.jsx(C_,{className:"h-5 w-5"})})]}),h&&o.jsxs("div",{className:"border-t border-border1",children:[o.jsx("div",{className:"p-3",children:o.jsxs("div",{className:"relative",children:[o.jsx(XPt,{className:"w-full"}),o.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[o.jsx(le,{variant:"default",size:"icon-sm",tooltip:"Center view",onClick:v,className:"bg-surface1/80 backdrop-blur-sm",children:o.jsx(omn,{className:"h-3.5 w-3.5"})}),o.jsx(le,{variant:"default",size:"icon-sm",tooltip:"Close browser",onClick:y,className:"bg-surface1/80 backdrop-blur-sm",children:o.jsx(bs,{className:"h-3.5 w-3.5"})})]})]})}),c.length>0&&o.jsx("div",{ref:p,className:"border-t border-border1 max-h-40 overflow-y-auto",children:o.jsxs("div",{className:"px-3 py-2",children:[o.jsx("h4",{className:"text-xs font-medium text-neutral4 mb-2",children:"Browser Actions"}),o.jsx("div",{className:"space-y-1",children:c.slice(-5).map(x=>o.jsx(KPt,{entry:x},x.toolCallId))})]})})]})]})}function yDr({className:e}){const{toolCalls:t}=FCe(),[n,r]=g.useState(!0),s=g.useRef(null);return g.useEffect(()=>{n&&s.current&&(s.current.scrollTop=s.current.scrollHeight)},[t.length,n]),t.length===0?null:o.jsxs("div",{className:X("flex flex-col overflow-hidden",e),children:[o.jsxs("button",{type:"button",onClick:()=>r(a=>!a),"aria-expanded":n,className:"flex items-center gap-2 w-full px-3 py-1 text-left hover:bg-surface3 transition-colors shrink-0",children:[o.jsx(Ia,{className:X("h-3.5 w-3.5 text-neutral3 transition-transform",n?"rotate-180":"")}),o.jsxs("span",{className:"text-xs font-medium text-neutral4",children:["Browser Actions (",t.length,")"]})]}),n&&o.jsx("div",{ref:s,className:"flex-1 overflow-y-auto bg-surface1",children:t.map(a=>o.jsx(KPt,{entry:a},a.toolCallId))})]})}const bDr=(e,t)=>{const n=g.useRef(null);g.useEffect(()=>{e?(n.current=document.activeElement,t?.current?.focus()):n.current&&(n.current.focus(),n.current=null)},[e,t])};function xDr(e){switch(e){case"idle":return{variant:"neutral",pulse:!1,label:"Idle"};case"connecting":return{variant:"warning",pulse:!0,label:"Connecting"};case"connected":return{variant:"warning",pulse:!0,label:"Connected"};case"browser_starting":return{variant:"warning",pulse:!0,label:"Starting"};case"streaming":return{variant:"success",pulse:!1,label:"Live"};case"browser_closed":return{variant:"neutral",pulse:!1,label:"Closed"};case"disconnected":return{variant:"error",pulse:!0,label:"Disconnected"};case"error":return{variant:"error",pulse:!1,label:"Error"};default:return{variant:"neutral",pulse:!1,label:"Unknown"}}}function zCe(){const{viewMode:e,status:t,currentUrl:n,hide:r,closeBrowser:s}=O3(),a=e==="modal",i=g.useRef(null);bDr(a,i);const l=()=>{if(n)try{const d=new URL(n);(d.protocol==="http:"||d.protocol==="https:")&&window.open(d.href,"_blank","noopener,noreferrer")}catch{}};g.useEffect(()=>{if(!a)return;const d=f=>{f.key==="Escape"&&(f.preventDefault(),r())};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[a,r]);const c=d=>{d.target===d.currentTarget&&r()},u=xDr(t);return o.jsx("div",{className:X("fixed inset-0 z-50 flex items-center justify-center p-8","bg-black/60 backdrop-blur-sm transition-opacity duration-200",a?"opacity-100":"opacity-0 pointer-events-none"),onClick:c,"aria-hidden":!a,children:o.jsxs("div",{ref:i,role:"dialog","aria-modal":"true","aria-label":"Browser view",tabIndex:-1,className:X("flex flex-col w-full max-w-5xl max-h-full","bg-surface2 rounded-xl border border-border1 shadow-2xl overflow-hidden","transition-transform duration-200 outline-none",a?"scale-100":"scale-95"),onClick:d=>d.stopPropagation(),children:[o.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-border1 shrink-0",children:[o.jsx(Ux,{className:"h-4 w-4 text-neutral4 shrink-0"}),o.jsx("div",{className:"flex-1 min-w-0 px-3 py-1.5 bg-surface3 rounded-md border border-border1",children:o.jsx("span",{className:X("text-sm truncate block",n?"text-neutral5":"text-neutral3 italic"),children:n||"No URL"})}),o.jsx(bg,{variant:u.variant,size:"sm",withDot:!0,pulse:u.pulse,children:u.label}),o.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[o.jsx(le,{variant:"ghost",size:"icon-sm",tooltip:"Minimize to chat",onClick:r,children:o.jsx(gmn,{className:"h-4 w-4"})}),n&&o.jsx(le,{variant:"ghost",size:"icon-sm",tooltip:"Open in new tab",onClick:l,children:o.jsx(ka,{className:"h-4 w-4"})}),o.jsx(le,{variant:"ghost",size:"icon-sm",tooltip:"Close browser",onClick:s,children:o.jsx(bs,{className:"h-4 w-4"})})]})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto",children:[o.jsx("div",{className:"p-4",children:o.jsx(XPt,{className:"w-full max-h-[60vh]"})}),o.jsx("div",{className:"px-4 pb-4",children:o.jsx(yDr,{})})]})]})})}const e$t=g.createContext({isConversationLoading:!1}),wDr=[],SDr=[{title:"What can you do?",description:"Get an overview of capabilities",prompt:"What can you do? Give me a quick overview of your capabilities.",Icon:emn},{title:"Show available tools",description:"See what this agent can call",prompt:"Show me the available tools you can call and explain when you would use each one.",Icon:Up},{title:"Suggest a task",description:"Get an example prompt to try",prompt:"Suggest a useful task I can try with you, including an example prompt.",Icon:Qhn},{title:"Run a self-check",description:"Verify tools are reachable",prompt:"Run a self-check and verify whether your tools are reachable. Tell me what works and what does not.",Icon:gxe}],kDr=({agentId:e,agentName:t,agentDescription:n,agentAvatarUrl:r,children:s})=>{const{data:a}=Cm(),i=a?.id?`${a.id}-${e}`:e,{data:l,isLoading:c}=AH({agentId:e,threadId:i,memory:!0}),u=l?.messages??wDr,d=g.useMemo(()=>({isConversationLoading:c,agentName:t,agentDescription:n,agentAvatarUrl:r}),[c,t,n,r]);return o.jsx(t2t,{agentId:e,threadId:i,initialMessages:u,children:o.jsx(e$t.Provider,{value:d,children:s})},i)},ODr=({hasBrowser:e=!1})=>{const t=fu(),n=uCe(),{draft:r,setDraft:s,trimmed:a,handleFormSubmit:i,handleKeyDown:l}=n2t({onSubmit:n});return o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[o.jsx(CDr,{onStarterPromptSelect:s}),e&&o.jsx(_Dr,{}),o.jsx(wCe,{draft:r,onDraftChange:s,onSubmit:i,onKeyDown:l,disabled:t,isRunning:t,canSubmit:a.length>0&&!t,placeholder:"Message your agent…",inputTestId:"agent-builder-agent-chat-input",submitTestId:"agent-builder-agent-chat-submit",containerTestId:"agent-builder-agent-chat-composer"})]})},_Dr=()=>{const{hasSession:e,viewMode:t}=O3();return!e||t==="modal"?null:o.jsx("div",{className:"mx-auto mb-2 w-full max-w-3xl",children:o.jsx(JPt,{})})},CDr=({onStarterPromptSelect:e})=>{const t=cCe(),n=fu(),{isConversationLoading:r,agentName:s,agentDescription:a,agentAvatarUrl:i}=g.useContext(e$t);return o.jsx($Ce,{messages:t,isLoading:r,isRunning:n,skeletonTestId:"agent-builder-agent-chat-messages-skeleton",emptyState:o.jsxs("div",{className:"flex flex-col items-center gap-6 py-6 text-center lg:h-full lg:justify-center lg:py-0","data-testid":"agent-builder-agent-chat-empty-state",children:[o.jsxs("div",{className:"flex flex-col items-center gap-3",children:[o.jsx("div",{className:"starter-chip",style:{animationDelay:"0ms",viewTransitionName:"agent-avatar"},children:o.jsx(p_,{name:s??"Agent",src:i,size:"lg"})}),o.jsx("div",{className:"starter-chip",style:{animationDelay:"150ms"},children:o.jsx(ye,{variant:"ui-lg",className:"text-neutral6 font-semibold",style:{viewTransitionName:"agent-name"},children:s??"your agent"})}),a?o.jsx("div",{className:"starter-chip",style:{animationDelay:"220ms"},children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral4 max-w-[40ch]",style:{viewTransitionName:"agent-description"},children:a})}):null]}),o.jsx("div",{className:"grid w-full max-w-2xl grid-cols-1 gap-5 sm:grid-cols-2",children:SDr.map((l,c)=>o.jsxs("button",{type:"button",onClick:()=>e(l.prompt),"data-testid":`agent-builder-agent-chat-starter-${l.title.toLowerCase().replace(/\s+/g,"-")}`,style:{animationDelay:`${280+c*40}ms`},className:"starter-chip group flex gap-3 rounded-3xl border border-border1 bg-surface2 p-4 text-left transition-colors duration-normal ease-out-custom hover:border-border2 hover:bg-surface3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent1",children:[o.jsx("span",{className:"mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md bg-surface3 text-neutral4 transition-colors group-hover:text-neutral6",children:o.jsx(l.Icon,{className:"size-4","aria-hidden":"true"})}),o.jsxs("span",{className:"min-w-0",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral6 font-medium transition-colors group-hover:text-neutral6",children:l.title}),o.jsx(ye,{variant:"ui-xs",className:"mt-1 text-neutral4 transition-colors group-hover:text-neutral5",children:l.description})]})]},l.title))})]})})},EDr=({mode:e,onModeToggle:t,modeToggleDisabled:n=!1,ownerActions:r,mobileMenu:s})=>{const a=e==="test"?"Switch to Edit mode":"Switch to View mode";return o.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-center gap-2 px-4 pt-4 md:px-10","data-testid":"agent-builder-view-top-bar",children:[o.jsxs(vwe,{label:"Agent navigation",className:"min-w-0",listClassName:"min-w-0",children:[o.jsx(j$,{as:ti,to:"/agent-builder/agents","data-testid":"agent-builder-back-to-list",children:"Agent list"}),o.jsx(j$,{as:"span",isCurrent:!0,children:o.jsx(HPt,{isLoading:!1})})]}),o.jsxs("div",{className:"justify-self-end flex items-center gap-2 shrink-0",children:[r&&o.jsx("div",{className:"shrink-0 hidden lg:flex items-center gap-2",children:r}),s&&o.jsx("div",{className:"shrink-0 lg:hidden",children:s}),e&&t&&o.jsxs(le,{variant:"ghost",size:"sm",onClick:t,disabled:n,className:"hidden lg:inline-flex shrink-0","data-testid":"agent-builder-mode-toggle","aria-label":a,children:[o.jsx(n1,{}),a]})]})]})};function jDr(e,t){const n=e?.metadata&&typeof e.metadata=="object"&&"avatarUrl"in e.metadata?e.metadata.avatarUrl:void 0;return{id:e?.id??t,name:e?.name??"",description:e?.description??"",avatarUrl:n,systemPrompt:typeof e?.instructions=="string"?e.instructions:"",visibility:e?.visibility??"private",authorId:e?.authorId}}const t$t=g.createContext(null),TDr=({agentId:e,storedAgent:t,currentUserId:n,canWrite:r,children:s})=>{const a=Mf(),i=Hs(),l=g.useMemo(()=>jDr(t,e),[t,e]),c=!t.authorId||n===t.authorId,u=t.visibility==="public",d=r&&c,f=a.browser&&t.browser!=null,p=n?`${n}-${e}`:e,h=g.useMemo(()=>c?()=>i(`/agent-builder/agents/${e}/edit`,{viewTransition:!0}):void 0,[c,e,i]),m=g.useMemo(()=>({agentId:e,isOwner:c,canModify:d,isPublishable:u,hasBrowser:f,agent:l,threadId:p,onModeToggle:h}),[e,c,d,u,f,l,p,h]);return o.jsx(t$t.Provider,{value:m,children:o.jsx(kDr,{agentId:e,agentName:t.name,agentDescription:t.description,agentAvatarUrl:l.avatarUrl,children:s})})},n$t=()=>{const e=g.useContext(t$t);if(!e)throw new Error("useViewPage must be used inside <ViewPageProvider>");return e},NDr=({topBar:e,chat:t,browserOverlay:n})=>o.jsxs("div",{className:"flex flex-1 min-w-0 flex-col h-full min-h-0",children:[e,o.jsx("div",{className:"flex-1 min-h-0 w-full min-w-0 overflow-hidden px-4 md:px-10 md:max-w-[80ch] md:mx-auto pt-10 md:pt-4 pb-4 md:pb-10","data-testid":"agent-builder-panel-chat",children:t}),n]}),IDr=(e,t)=>["browser-session-probe",e,t],ADr={hasSession:!0,screencastAvailable:!0},RDr=e=>!e||typeof e!="object"?!1:"status"in e&&e.status===404||"statusCode"in e&&e.statusCode===404;function PDr({agentId:e,threadId:t,enabled:n=!0}){const r=We();return yt({queryKey:IDr(e,t),queryFn:async()=>{if(!e)return{hasSession:!1,screencastAvailable:!1};try{return await r.getAgent(e).browserSession(t)}catch(s){if(RDr(s))return ADr;throw s}},enabled:n&&!!e,refetchOnWindowFocus:!0,staleTime:0,retry:1})}function $Dr(){const e=We();return Rn({mutationFn:({agentId:t,threadId:n})=>e.getAgent(t).closeBrowser(n),onError:t=>{console.error("[useCloseBrowser] Error closing browser:",t)}})}function MDr(){let e=null;const t=new Set;return{getSnapshot:()=>e,subscribe:n=>(t.add(n),()=>{t.delete(n)}),setFrame:n=>{e!==n&&(e=n,t.forEach(r=>r()))}}}function eZ({children:e,agentId:t,threadId:n,enabled:r=!0}){const[s,a]=g.useState(!1),[i,l]=g.useState("collapsed"),{data:c}=PDr({agentId:t,threadId:n,enabled:r}),u=c?.screencastAvailable??!1,d=c?.hasSession??!1,p=r&&u&&(d||i!=="collapsed"),h=g.useRef(p),m=g.useRef(t),v=g.useRef(n);g.useEffect(()=>{h.current=p,m.current=t,v.current=n});const[y,b]=g.useState("idle"),[S,x]=g.useState(null),[k,_]=g.useState(null),C=g.useRef(MDr()),E=g.useRef(null),j=g.useRef(0),T=g.useRef(null),I=g.useRef(null),A=5,R=g.useCallback(()=>{T.current&&(clearTimeout(T.current),T.current=null)},[]),L=g.useCallback(()=>{R(),I.current=null,E.current&&(E.current.close(),E.current=null),j.current=0,a(!1),b("idle"),x(null),C.current.setFrame(null),_(null)},[R]),M=g.useCallback(Z=>{E.current?.readyState===WebSocket.OPEN&&E.current.send(Z)},[]),z=g.useRef(!1),H=g.useCallback(()=>{if(!h.current)return;const Z=m.current,K=v.current;if(!Z||!K||I.current?.agentId===Z&&I.current?.threadId===K&&E.current?.readyState===WebSocket.OPEN)return;R(),E.current&&(z.current=!0,E.current.close(),E.current=null),I.current={agentId:Z,threadId:K},b("connecting");const te=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/browser/${Z}/stream?threadId=${encodeURIComponent(K)}`;try{const J=new WebSocket(te);z.current=!1,E.current=J,J.onopen=()=>{b("connected"),j.current=0},J.onmessage=ae=>{const pe=ae.data;if(pe.startsWith("{"))try{const Y=JSON.parse(pe);if(Y.status)switch(Y.status){case"browser_starting":b("browser_starting");break;case"streaming":b("streaming"),a(!0);break;case"browser_closed":b("browser_closed"),a(!1),l("collapsed");break;case"stopped":b("disconnected");break;case"error":b("error"),a(!1);break}Y.url&&x(Y.url),Y.viewport&&_(Y.viewport)}catch{C.current.setFrame(pe)}else C.current.setFrame(pe),b(Y=>Y!=="streaming"?"streaming":Y),a(!0)},J.onerror=()=>{},J.onclose=ae=>{if(E.current===J&&(E.current=null,!z.current))if(a(!1),!ae.wasClean&&j.current<A){j.current+=1;const pe=Math.min(1e3*Math.pow(2,j.current-1),1e4);b("disconnected"),T.current=setTimeout(()=>{H()},pe)}else j.current>=A?b("error"):b("disconnected")}}catch{b("error")}},[R]);g.useEffect(()=>(p&&t&&n&&H(),()=>{L()}),[p,t,n,H,L]),g.useEffect(()=>{if(!p)return;const Z=()=>{document.visibilityState==="visible"&&y==="disconnected"&&t&&n&&(j.current=0,H())};return document.addEventListener("visibilitychange",Z),()=>{document.removeEventListener("visibilitychange",Z)}},[p,y,t,n,H]);const F=g.useCallback(Z=>{l(Z)},[]),B=g.useCallback(()=>{l("modal")},[]),q=g.useCallback(()=>{l("collapsed")},[]),D=g.useCallback(()=>{a(!1),l("collapsed"),C.current.setFrame(null)},[]),G=$Dr(),V=g.useCallback(async()=>{if(!(G.isPending||!t))try{await G.mutateAsync({agentId:t,threadId:n}),D()}catch{}},[t,n,G,D]),$=G.isPending,U=g.useMemo(()=>({hasSession:s,viewMode:i,isPanelOpen:i==="modal",isActive:s,status:y,currentUrl:S,viewport:k,isClosing:$,setViewMode:F,show:B,hide:q,endSession:D,closeBrowser:V,sendMessage:M,connect:H,disconnect:L}),[s,i,y,S,k,$,F,B,q,D,V,M,H,L]);return o.jsx(GPt.Provider,{value:U,children:o.jsx(QPt.Provider,{value:C.current,children:e})})}function DDr(){const{id:e}=Sr(),{data:t,isLoading:n}=g3(e,{status:"draft"}),{data:r,isLoading:s}=Cm(),{canWrite:a}=Ry();return WPt(),e?n||s?o.jsx(BDr,{}):t?o.jsx(TDr,{agentId:e,storedAgent:t,currentUserId:r?.id,canWrite:a,children:o.jsx(LDr,{storedAgent:t})}):o.jsx(Vu,{to:"/agent-builder/agents",replace:!0}):null}const LDr=({storedAgent:e})=>{const{hasBrowser:t,agentId:n,threadId:r}=n$t(),[s]=g.useState(()=>ZPt(e)),a=q1({defaultValues:s}),i=o.jsx(FDr,{hasBrowser:t});return t?o.jsx(M$,{...a,children:o.jsx(lD,{agentId:n,children:o.jsx(JW,{children:o.jsx(eZ,{agentId:n,threadId:r,children:i})})})}):o.jsx(M$,{...a,children:o.jsx(lD,{agentId:n,children:i})})},FDr=g.memo(function({hasBrowser:t}){const n=g.useMemo(()=>o.jsx(zDr,{}),[]),r=g.useMemo(()=>o.jsx(ODr,{hasBrowser:t}),[t]),s=g.useMemo(()=>t?o.jsx(zCe,{}):void 0,[t]);return o.jsx(NDr,{topBar:n,chat:r,browserOverlay:s})}),zDr=()=>{const{canModify:e,onModeToggle:t,isOwner:n,agentId:r,agent:s}=n$t(),a=fu();return o.jsx(EDr,{mode:e?"test":void 0,onModeToggle:t,modeToggleDisabled:a,mobileMenu:n&&o.jsx(FRt,{agentId:r,showEditAgent:!0,showDelete:!0,agentName:s.name,disabled:a})})},BDr=()=>o.jsx("div",{className:"h-screen w-screen flex items-center justify-center",children:o.jsx(Kt,{})}),VZe=(e,t)=>{const n=e.favoriteCount??0,r=t?n+(e.isFavorited?0:1):Math.max(0,n-(e.isFavorited?1:0));return{...e,isFavorited:t,favoriteCount:r}},UDr=e=>{const t=We(),n=Ur(),{requestContext:r}=Cs();return Rn({mutationFn:async({favorited:s})=>{if(!e)throw new Error("skillId is required to toggle favorite");const a=t.getStoredSkill(e);return s?a.favorite(r):a.unfavorite(r)},onMutate:async({favorited:s})=>{if(!e)return{previousLists:[]};await n.cancelQueries({queryKey:["stored-skills"]}),await n.cancelQueries({queryKey:["stored-skill",e]});const a=n.getQueryData(["stored-skill",e]),i=n.getQueriesData({queryKey:["stored-skills"]}),l=[];for(const[c,u]of i)l.push([c,u]),u?.skills&&n.setQueryData(c,{...u,skills:u.skills.map(d=>d.id===e?VZe(d,s):d)});return a&&n.setQueryData(["stored-skill",e],VZe(a,s)),{previousDetail:a,previousLists:l}},onError:(s,a,i)=>{if(i){e&&i.previousDetail!==void 0&&n.setQueryData(["stored-skill",e],i.previousDetail);for(const[l,c]of i.previousLists)n.setQueryData(l,c)}},onSettled:()=>{n.invalidateQueries({queryKey:["stored-skills"]}),e&&n.invalidateQueries({queryKey:["stored-skill",e]})}})},VDr={sm:14,md:16},cye=({skillId:e,isFavorited:t=!1,favoriteCount:n,size:r="md",className:s,showCount:a=!0})=>{const i=Mf(),l=UDr(e),{data:c}=dc();if(!i.favorites)return null;const u=c?wm(c):!1,d=t?"Unstar skill":"Star skill",f="Sign in to star this skill",p=typeof n=="number"&&n>0,h=n===1?"Star":"Stars",m=l.isPending||!u;return o.jsxs(le,{type:"button",variant:"default",size:r,"aria-pressed":t,"aria-label":u?d:f,title:u?d:f,disabled:m,onClick:v=>{v.preventDefault(),v.stopPropagation(),u&&l.mutate({favorited:!t})},className:X("shrink-0",u?"cursor-pointer":"cursor-not-allowed",s),children:[o.jsx(gT,{size:VDr[r],className:X("shrink-0",t&&"fill-current text-yellow-300"),"aria-hidden":!0}),a&&o.jsx("span",{className:"leading-none whitespace-nowrap",children:p?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"tabular-nums",children:n})," ",h]}):"Star"})]})};function qDr(e){if(!e||typeof e!="object")return null;const t=e.origin;if(!t||typeof t!="object")return null;const n=t;return n.type==="skills-sh"&&typeof n.owner=="string"&&typeof n.repo=="string"&&typeof n.skillName=="string"?{type:"skills-sh",owner:n.owner,repo:n.repo,skillName:n.skillName}:n.type==="library-copy"&&typeof n.sourceSkillId=="string"&&typeof n.sourceSkillName=="string"?{type:"library-copy",sourceSkillId:n.sourceSkillId,sourceSkillName:n.sourceSkillName,sourceAuthorId:typeof n.sourceAuthorId=="string"?n.sourceAuthorId:void 0}:null}function BCe({skills:e,search:t,onSkillClick:n,showFavorites:r=!0}){const s=g.useMemo(()=>{const a=(t??"").trim().toLowerCase();return a?e.filter(i=>{const l=i.name?.toLowerCase()??"",c=i.description?.toLowerCase()??"";return l.includes(a)||c.includes(a)}):e},[e,t]);return s.length===0?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(zr,{iconSlot:o.jsx(Ka,{className:"h-8 w-8 text-neutral3"}),titleSlot:"No skills match your search",descriptionSlot:"Try a different name or description."})}):o.jsx("div",{className:"bg-surface2 border border-border1 rounded-xl divide-y divide-border1 overflow-hidden",children:s.map(a=>{const i=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("div",{className:"text-ui-md text-neutral6 truncate",children:a.name}),a.visibility==="private"&&o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx("span",{className:"text-neutral3 shrink-0","aria-label":"Private skill","data-testid":"skill-builder-private-visibility-icon",children:o.jsx(qe,{size:"sm",children:o.jsx(Cf,{})})})}),o.jsx($n,{children:"Only visible to you"})]}),(()=>{const l=qDr(a.metadata);if(!l)return null;const c=l.type==="library-copy";return o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-surface5 text-neutral4 shrink-0","aria-label":c?"Copied skill":"Imported skill","data-testid":"skill-builder-origin-badge",children:[c?o.jsx(am,{className:"h-2.5 w-2.5"}):o.jsx(vf,{className:"h-2.5 w-2.5"}),l.type==="skills-sh"?"skills.sh":c?"copied":"imported"]})}),o.jsx($n,{children:l.type==="skills-sh"?`Imported from ${l.owner}/${l.repo}`:c?`Copied from "${l.sourceSkillName}"`:"Imported from external registry"})]})})()]}),o.jsx("div",{className:"flex items-center gap-2 mt-0.5",children:o.jsx("span",{className:"text-ui-sm text-neutral3 line-clamp-1",children:a.description||"No description"})}),r&&o.jsx("div",{className:"mt-2 md:hidden",children:o.jsx(cye,{skillId:a.id,isFavorited:a.isFavorited,favoriteCount:a.favoriteCount,size:"sm"})})]}),r&&o.jsx(cye,{skillId:a.id,isFavorited:a.isFavorited,favoriteCount:a.favoriteCount,size:"sm",className:"shrink-0 hidden md:inline-flex"})]});return n?o.jsx("button",{className:"px-6 py-5 flex items-start gap-4 w-full text-left hover:bg-surface3/50 transition-colors md:items-center",onClick:()=>n(a),children:i},a.id):o.jsx("div",{className:"px-6 py-5 flex items-start gap-4 md:items-center",children:i},a.id)})})}function UCe({rows:e=4}){return o.jsx("div",{className:"bg-surface2 border border-border1 rounded-xl divide-y divide-border1 overflow-hidden",children:Array.from({length:e}).map((t,n)=>o.jsxs("div",{className:"px-6 py-5 flex items-center gap-4",children:[o.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[o.jsx("div",{className:"h-3.5 w-48 bg-surface3 rounded animate-pulse"}),o.jsx("div",{className:"h-3 w-72 max-w-full bg-surface3 rounded animate-pulse"})]}),o.jsx("div",{className:"h-3 w-16 bg-surface3 rounded animate-pulse"})]},n))})}function HDr(){const e=Hs(),[t,n]=g.useState(""),[r,s]=g.useState("agents"),a=Mf(),{data:i}=Cm(),l=x=>{const _=!x.authorId||i?.id===x.authorId?"edit":"view";e(`/agent-builder/skills/${x.id}/${_}`,{viewTransition:!0})},c=g.useMemo(()=>({favoritedOnly:!0,orderBy:{field:"updatedAt",direction:"DESC"}}),[]),{data:u,isLoading:d,error:f}=f_(c),{data:p,isLoading:h,error:m}=K1({enabled:r==="skills"&&a.skills}),v=u?.agents??[],y=p?.skills??[],b=(x,k)=>ys(x)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ws,{})}):xs(x)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ds,{resource:k})}):o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Hi,{title:`Failed to load favorite ${k}`,message:x.message})}),S=r==="agents"?d?o.jsx(tCe,{rowTestId:"favorite-skeleton-row"}):f?b(f,"agents"):v.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(zr,{iconSlot:o.jsx(gT,{className:"h-8 w-8 text-neutral3"}),titleSlot:"No favorite agents yet",descriptionSlot:"Star agents to keep them here for quick access."})}):o.jsx(eCe,{agents:v,search:t,rowTestId:"favorite-agent-row"}):h?o.jsx(UCe,{}):m?b(m,"skills"):y.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(zr,{iconSlot:o.jsx(jg,{className:"h-8 w-8 text-neutral3"}),titleSlot:"No favorite skills yet",descriptionSlot:"Star skills to keep them here for quick access."})}):o.jsx(BCe,{skills:y,search:t,onSkillClick:l});return o.jsx(o.Fragment,{children:o.jsxs(Ft,{className:"px-4 md:px-10",children:[o.jsxs(Ft.TopArea,{children:[o.jsx("div",{className:"flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4",children:o.jsxs(Sf,{children:[o.jsxs(Sf.Title,{children:[o.jsx(gT,{})," Favorites"]}),o.jsx(Sf.Description,{children:r==="agents"?"Agents you've starred in Agent Builder.":"Skills you've starred in Agent Builder."})]})}),o.jsxs("div",{className:"flex items-center gap-4",children:[a.skills&&o.jsxs("div",{className:"flex rounded-lg border border-border1 overflow-hidden",children:[o.jsx("button",{onClick:()=>s("agents"),className:`px-3 py-1.5 text-xs font-medium transition-colors ${r==="agents"?"bg-surface4 text-neutral6":"bg-surface2 text-neutral3 hover:text-neutral5"}`,children:"Agents"}),o.jsx("button",{onClick:()=>s("skills"),className:`px-3 py-1.5 text-xs font-medium transition-colors ${r==="skills"?"bg-surface4 text-neutral6":"bg-surface2 text-neutral3 hover:text-neutral5"}`,children:"Skills"})]}),o.jsx("div",{className:"flex-1 max-w-120",children:o.jsx($f,{onSearch:n,label:"Filter favorites",placeholder:"Filter by name or description"})})]})]}),S]})})}function WDr({title:e,description:t,tone:n="default",id:r,className:s,descriptionClassName:a}){const i=n==="danger";return o.jsxs(o.Fragment,{children:[o.jsx("h3",{id:r,className:X("font-display text-header-md leading-tight font-normal tracking-normal",i?"text-accent2":"text-neutral4",s),children:e}),t!=null&&o.jsx("p",{className:X("mt-2 max-w-[62ch] font-sans text-[13.5px] leading-ui-xs",i?"text-accent2/70":"text-neutral3",a),children:t})]})}function uye({title:e,description:t,action:n,variant:r="default",fillHeight:s=!1,className:a,contentClassName:i,children:l}){const c=r==="danger";return o.jsxs("section",{"data-variant":r,className:X("overflow-hidden rounded-2xl border",s&&"flex h-full flex-col",c?"border-accent2/25":"border-border1",a),children:[o.jsxs("div",{className:X("flex flex-col gap-3 px-7 pt-7 pb-6 sm:flex-row sm:items-start sm:justify-between sm:gap-6",c?"bg-accent2/8":"bg-surface-overlay-soft"),children:[o.jsx("div",{className:"min-w-0",children:o.jsx(WDr,{title:e,description:t,tone:c?"danger":"default"})}),n!=null?o.jsx("div",{className:"shrink-0",children:n}):null]}),o.jsx("div",{className:X("min-w-0 px-7 pt-6 pb-7",s&&"flex-1",c?"bg-accent2/4":null,i),children:l})]})}const ZDr=e=>{const t=We();return yt({queryKey:["infrastructure-status"],queryFn:()=>t.getInfrastructureStatus(),enabled:e?.enabled??!0,retry:!1})},GR=({ok:e,label:t})=>o.jsxs("span",{className:`inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-xs ${e?"bg-accent3/10 text-accent3":"bg-surface2 text-neutral3"}`,"data-slot":"infrastructure-status-badge","data-ok":e?"true":"false",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${e?"bg-accent3":"bg-neutral3"}`,"aria-hidden":"true"}),t]}),Fre=({message:e})=>o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:e}),hk=e=>e==null?e:String(e).split(/([\s-]+)/).map(t=>/^[\s-]+$/.test(t)?t:t.charAt(0).toUpperCase()+t.slice(1)).join(""),Ib=({label:e,value:t})=>o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4",children:e}),o.jsx(ye,{variant:"ui-sm",className:"text-icon6",children:t??"Not set"})]}),qZe=({entries:e})=>e.length===0?null:o.jsx("div",{className:"grid grid-cols-1 gap-3 border-t border-border1 pt-3 sm:grid-cols-2",children:e.map(t=>o.jsx(Ib,{label:`Config: ${t.key}`,value:hk(t.value)},t.key))}),GDr=()=>{const{hasPermission:e}=dl(),t=e("infrastructure:read"),{data:n,isLoading:r,error:s}=ZDr({enabled:t}),a=n;return o.jsxs(Ft,{width:"narrow",children:[o.jsx(Ft.TopArea,{children:o.jsx(Sf,{children:o.jsx(Sf.Title,{children:"Infrastructure"})})}),o.jsx(Ft.MainArea,{className:"flex flex-col gap-5 mt-6",children:o.jsx(uye,{title:"Agent Builder Infrastructure",description:"Deployment-level defaults Agent Builder applies when users create or run builder agents.",children:t?r?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"Loading infrastructure configuration…"}):s||!a?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"Infrastructure configuration unavailable."}):o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-md",className:"font-medium",children:"Channels"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"Configured channel providers available to Agent Builder publish/share flows. Unconfigured providers are omitted until their required environment/config is present."})]}),a.channels.providers.length===0?o.jsx(Fre,{message:"No configured channel providers for Agent Builder."}):o.jsx("ul",{className:"flex flex-col gap-2",children:a.channels.providers.map(i=>o.jsxs("li",{className:"rounded-md border border-border1 px-3 py-3",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:hk(i.name)}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3",children:["Provider ID: ",i.id]})]}),o.jsx(GR,{ok:i.isConfigured,label:i.isConfigured?"Configured":"Not configured"})]}),o.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 border-t border-border1 pt-3 sm:grid-cols-2",children:[o.jsx(Ib,{label:"Registered by",value:`${hk(i.name)} provider`}),o.jsx(Ib,{label:"Provider routes",value:i.routeCount})]})]},i.id))})]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-md",className:"font-medium",children:"Browser"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"Browser automation provider configured for builder agents. The card shows the selected provider and only non-default options explicitly passed in configuration."})]}),a.browser.provider?o.jsxs("div",{className:"rounded-md border border-border1 px-3 py-3",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsx("div",{className:"flex flex-col gap-1",children:o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:hk(a.browser.provider)})}),o.jsx(GR,{ok:a.browser.registered,label:a.browser.registered?"Provider available":"Provider missing"})]}),a.browser.env?o.jsx("div",{className:"mt-3 grid grid-cols-1 gap-3 border-t border-border1 pt-3 sm:grid-cols-2",children:o.jsx(Ib,{label:"Environment",value:hk(a.browser.env)})}):null,o.jsx(qZe,{entries:a.browser.config})]}):o.jsx(Fre,{message:"No browser configured."})]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-md",className:"font-medium",children:"Registries"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"External skill registries available to import skills into the workspace."})]}),o.jsx("div",{className:"rounded-md border border-border1 px-3 py-3",children:o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:"skills.sh"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"GitHub-backed public skills registry."})]}),o.jsx(GR,{ok:a.registries?.skillsSh?.enabled??!1,label:a.registries?.skillsSh?.enabled?"Enabled":"Disabled"})]})})]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-md",className:"font-medium",children:"Workspace"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"Workspace config used for generated files and sandbox execution. This reports the builder workspace only, not agent-specific runtime workspaces."})]}),a.workspace.type?o.jsxs("div",{className:"rounded-md border border-border1 px-3 py-3",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:a.workspace.workspaceId??a.workspace.name??"Inline workspace"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(GR,{ok:a.workspace.hasFilesystem,label:"Filesystem"}),o.jsx(GR,{ok:a.workspace.hasSandbox,label:"Sandbox"})]})]}),o.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 border-t border-border1 pt-3 sm:grid-cols-2",children:[o.jsx(Ib,{label:"Config type",value:a.workspace.type==="id"?"Registered workspace":"Inline config"}),a.workspace.workspaceId?o.jsx(Ib,{label:"Workspace ID",value:a.workspace.workspaceId}):null,o.jsx(Ib,{label:"Name",value:a.workspace.name}),o.jsx(Ib,{label:"Filesystem provider",value:hk(a.workspace.filesystemProvider)}),o.jsx(Ib,{label:"Sandbox provider",value:hk(a.workspace.sandboxProvider)})]}),o.jsx(qZe,{entries:a.workspace.config})]}):o.jsx(Fre,{message:"No workspace configured."})]})]}):o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You do not have permission to view Agent Builder infrastructure."})})})]})};function QDr(){const e=Hs(),[t,n]=g.useState(""),[r,s]=g.useState("agents"),a=Mf(),{canUseFavorites:i}=Ry(),l=g.useMemo(()=>({visibility:"public"}),[]),{data:c,isLoading:u,error:d}=f_(l),{data:f,isLoading:p,error:h}=K1({enabled:r==="skills"&&a.skills}),m=c?.agents??[],v=f?.skills??[],y=S=>ys(S)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ws,{})}):xs(S)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ds,{resource:r})}):o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Hi,{title:"Failed to load the library",message:S.message})}),b=r==="agents"?u?o.jsx(tCe,{rowTestId:"library-skeleton-row"}):d?y(d):m.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(zr,{iconSlot:o.jsx(f$,{className:"h-8 w-8 text-neutral3"}),titleSlot:"No public agents yet",descriptionSlot:"Mark an agent as Public to share it with the team library."})}):o.jsx(eCe,{agents:m,search:t,rowTestId:"library-agent-row",showFavorites:i}):p?o.jsx(UCe,{}):h?y(h):v.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(zr,{iconSlot:o.jsx(jg,{className:"h-8 w-8 text-neutral3"}),titleSlot:"No public skills yet",descriptionSlot:"Mark a skill as Public to share it with the team library."})}):o.jsx(BCe,{skills:v,search:t,onSkillClick:S=>e(`/agent-builder/skills/${S.id}/view`,{viewTransition:!0}),showFavorites:i});return o.jsx(o.Fragment,{children:o.jsxs(Ft,{className:"px-4 md:px-10",children:[o.jsxs(Ft.TopArea,{children:[o.jsx("div",{className:"flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4",children:o.jsxs(Sf,{children:[o.jsxs(Sf.Title,{children:[o.jsx(f$,{})," Library"]}),o.jsx(Sf.Description,{children:r==="agents"?"Agents shared with the team library.":"Skills shared with the team library."})]})}),o.jsxs("div",{className:"flex items-center gap-4",children:[a.skills&&o.jsxs("div",{className:"flex rounded-lg border border-border1 overflow-hidden",children:[o.jsx("button",{onClick:()=>s("agents"),className:`px-3 py-1.5 text-xs font-medium transition-colors ${r==="agents"?"bg-surface4 text-neutral6":"bg-surface2 text-neutral3 hover:text-neutral5"}`,children:"Agents"}),o.jsx("button",{onClick:()=>s("skills"),className:`px-3 py-1.5 text-xs font-medium transition-colors ${r==="skills"?"bg-surface4 text-neutral6":"bg-surface2 text-neutral3 hover:text-neutral5"}`,children:"Skills"})]}),o.jsx("div",{className:"flex-1 max-w-120",children:o.jsx($f,{onSearch:n,label:"Filter library",placeholder:"Filter by name or description"})})]})]}),b]})})}const $I=e=>o.jsx(lTn,{...e}),YDr=300*1e3;function KDr(e){const t=We();return yt({queryKey:["builder-registries"],queryFn:()=>t.listBuilderRegistries(),enabled:e?.enabled??!0,retry:!1})}function XDr(e){const t=We();return Rn({mutationFn:async n=>{if(!e)throw new Error("Registry ID is required");return t.searchBuilderRegistry(e,{q:n,limit:10})}})}function JDr(e){const t=We();return yt({queryKey:["builder-registry",e,"popular"],queryFn:()=>{if(!e)throw new Error("Registry ID is required");return t.getBuilderRegistryPopular(e,{limit:10,offset:0})},enabled:!!e,staleTime:YDr,retry:!1})}function e4r(e,t,n,r,s){const a=We();return yt({queryKey:["builder-registry",e,"preview",t,n,r],queryFn:async()=>{if(!e||!t||!n||!r)throw new Error("registryId, owner, repo, and skillPath are required");return(await a.getBuilderRegistryPreview(e,{owner:t,repo:n,path:r})).content},enabled:s?.enabled!==!1&&!!e&&!!t&&!!n&&!!r,retry:!1})}function t4r(e){const t=We(),n=Ur();return Rn({mutationFn:async r=>{if(!e)throw new Error("Registry ID is required");return t.installBuilderRegistrySkill(e,r)},onSuccess:()=>{n.invalidateQueries({queryKey:["stored-skills"]})}})}function n4r(e){if(!e)return null;const n=e.replace(/^https?:\/\//,"").replace(/^github\.com\//,"").split("/").filter(Boolean);return n.length<2?null:{owner:n[0],repo:n[1]}}function HZe(e){return`${e.topSource}/${e.name}`}function r4r({open:e,onOpenChange:t,registryId:n,registryLabel:r,installedSkillIds:s=[],onInstalled:a,onCollision:i}){const[l,c]=g.useState(""),[u,d]=g.useState(null),[f,p]=g.useState(null),{data:h,isLoading:m}=JDr(e?n:void 0),v=XDr(n),y=t4r(n),b=g.useMemo(()=>u?.topSource?n4r(u.topSource):null,[u]),{data:S,isLoading:x}=e4r(n,b?.owner,b?.repo,u?.name,{enabled:!!b&&!!u&&e}),k=My(L=>{L.trim().length>=2&&v.mutate(L)},300),_=g.useCallback(L=>{c(L),k(L)},[k]),C=g.useMemo(()=>l.trim().length>=2?v.data?.skills??[]:h?.skills??[],[l,v.data,h]),E=v.isPending,j=l.trim().length>=2,T=g.useMemo(()=>u?s.includes(u.name):!1,[u,s]),I=g.useMemo(()=>b?`https://github.com/${b.owner}/${b.repo}`:null,[b]),A=g.useCallback(async()=>{if(!(!u||!b)){p(null);try{const L=await y.mutateAsync({owner:b.owner,repo:b.repo,skillName:u.name});a?.(L.storedSkillId),t(!1)}catch(L){const M=L?.message??"Install failed";/409/.test(M)||/already exists/i.test(M)?(i?.(u.name),p("A skill with this name already exists. Open the existing skill instead.")):p(M)}}},[u,b,y,a,t,i]),R=g.useCallback(L=>{L||(c(""),d(null),p(null)),t(L)},[t]);return o.jsx(br,{open:e,onOpenChange:R,children:o.jsxs(xr,{className:"max-w-4xl h-[80vh] flex flex-col",children:[o.jsxs(wr,{children:[o.jsxs(gr,{children:["Browse ",r]}),o.jsxs(Ks,{children:["Find a public skill from ",r," and import it into your Builder skill library."]})]}),o.jsxs($r,{className:"flex-1 flex flex-col gap-4 overflow-hidden max-h-none",children:[o.jsxs("div",{className:"relative",children:[o.jsx(Ka,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-neutral3"}),o.jsx(Cn,{placeholder:`Search ${r}...`,value:l,onChange:L=>_(L.target.value),className:"pl-9","data-testid":"builder-add-skill-search"})]}),o.jsxs("div",{className:"flex flex-1 gap-4 min-h-0",children:[o.jsxs("div",{className:"w-1/2 flex flex-col min-h-0",children:[o.jsx("div",{className:"text-xs font-medium text-neutral4 uppercase tracking-wide mb-2",children:j?"Search results":"Popular skills"}),o.jsx(Br,{className:"flex-1 border border-border1 rounded-lg",children:m||E?o.jsx("div",{className:"flex items-center justify-center py-8",children:o.jsx(oa,{className:"h-6 w-6 animate-spin text-neutral3"})}):C.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-neutral4",children:[o.jsx(Kv,{className:"h-8 w-8 mb-2"}),o.jsx("p",{className:"text-sm",children:j?"No skills found":"No skills available"})]}):o.jsx("div",{className:"p-2 space-y-1",children:C.map(L=>{const M=HZe(L),z=s.includes(L.name),H=u?HZe(u):null;return o.jsx("button",{onClick:()=>d(L),className:X("w-full text-left px-3 py-2 rounded-md transition-colors","hover:bg-surface4",H===M&&"bg-surface5 border border-accent1"),children:o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"font-medium text-sm text-neutral6 truncate",children:L.name}),z&&o.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-accent1/20 text-accent1",children:[o.jsx(pa,{className:"h-2.5 w-2.5"}),"Installed"]})]}),o.jsx("div",{className:"text-xs text-neutral4 truncate",children:L.topSource})]}),o.jsxs("div",{className:"flex items-center gap-1 text-xs text-neutral3 shrink-0",children:[o.jsx(vf,{className:"h-3 w-3"}),o.jsx("span",{children:L.installs.toLocaleString()})]})]})},M)})})})]}),o.jsx("div",{className:"w-1/2 flex flex-col min-h-0 border border-border1 rounded-lg overflow-hidden",children:u?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"p-4 border-b border-border1 bg-surface3",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"p-2 rounded-lg bg-surface5",children:o.jsx($I,{className:"h-5 w-5 text-neutral4"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h3",{className:"font-semibold text-neutral6 truncate",children:u.name}),o.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-neutral4",children:[o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(wdt,{className:"h-3 w-3"}),u.topSource]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(vf,{className:"h-3 w-3"}),u.installs.toLocaleString()," installs"]})]})]}),I&&o.jsx("a",{href:I,target:"_blank",rel:"noopener noreferrer",className:"text-neutral4 hover:text-neutral5 transition-colors",title:"View on GitHub",children:o.jsx(ka,{className:"h-4 w-4"})})]})}),x?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(oa,{className:"h-6 w-6 animate-spin text-neutral3"})}):S?o.jsx(Br,{className:"flex-1",children:o.jsx("div",{className:"p-4",children:o.jsx(Gp,{children:S})})}):o.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-neutral4",children:[o.jsx(Kv,{className:"h-8 w-8 mb-2"}),o.jsx("p",{className:"text-sm",children:"Preview unavailable"})]})]}):o.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-neutral4",children:[o.jsx(Kv,{className:"h-8 w-8 mb-2"}),o.jsx("p",{className:"text-sm",children:"Select a skill to preview"})]})})]}),u&&o.jsxs("div",{className:"flex flex-col gap-3 pt-4 border-t border-border1",children:[f&&o.jsx("div",{className:"text-sm text-red-400 px-3 py-2 rounded-md bg-red-500/10 border border-red-500/20",children:f}),o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[o.jsx(le,{variant:"default",onClick:()=>R(!1),children:"Cancel"}),o.jsx(le,{variant:"primary",onClick:A,disabled:!b||y.isPending||T,"data-testid":"builder-install-skill-button",children:y.isPending?o.jsxs(o.Fragment,{children:[o.jsx(oa,{className:"h-4 w-4 mr-2 animate-spin"}),"Installing..."]}):T?o.jsxs(o.Fragment,{children:[o.jsx(pa,{className:"h-4 w-4 mr-2"}),"Already installed"]}):o.jsxs(o.Fragment,{children:[o.jsx(vf,{className:"h-4 w-4 mr-2"}),"Install"]})})]})]})]})]})})}function s4r(){const e=Hs(),{isLoading:t}=Cm(),{hasPermission:n,rbacEnabled:r}=dl(),s=!r||n("stored-skills:write"),a=!r||n("stored-skills:read"),[i,l]=g.useState(null),c=()=>e("/agent-builder/skills/create",{viewTransition:!0}),u=_=>e(`/agent-builder/skills/${_}/edit`,{viewTransition:!0}),{data:d,isLoading:f,error:p}=K1({enabled:!t}),[h,m]=g.useState(""),v=g.useMemo(()=>d?.skills??[],[d?.skills]),y=g.useMemo(()=>v.map(_=>_.id),[v]),{data:b}=KDr({enabled:a&&s}),S=g.useMemo(()=>b?.registries.find(_=>_.enabled)??null,[b]),x=_=>{u(_.id)},k=t||f?o.jsx(UCe,{}):p?ys(p)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ws,{})}):xs(p)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ds,{resource:"skills"})}):o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Hi,{title:"Failed to load skills",message:p.message})}):v.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(zr,{iconSlot:o.jsx(jg,{className:"h-8 w-8 text-neutral3"}),titleSlot:"No skills yet",descriptionSlot:"Create your first skill to give agents new capabilities.",actionSlot:s?o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(le,{variant:"primary",onClick:c,children:[o.jsx(Zr,{})," New skill"]}),S&&o.jsxs(le,{variant:"default",onClick:()=>l({id:S.id,label:S.label}),children:[o.jsx(vf,{})," Browse registry"]})]}):void 0})}):o.jsx(BCe,{skills:v,search:h,onSkillClick:x});return o.jsxs(o.Fragment,{children:[o.jsxs(Ft,{className:"px-4 md:px-10",children:[o.jsxs(Ft.TopArea,{children:[o.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4",children:[o.jsxs(Sf,{children:[o.jsxs(Sf.Title,{children:[o.jsx(jg,{})," My skills"]}),o.jsx(Sf.Description,{children:"Skills you've created."})]}),v.length>0&&s&&o.jsxs("div",{className:"w-full shrink-0 flex flex-col items-stretch gap-2 md:w-auto md:flex-row md:items-center",children:[S&&o.jsxs(le,{variant:"default",className:"w-full justify-center md:w-auto",onClick:()=>l({id:S.id,label:S.label}),children:[o.jsx(vf,{})," Browse registry"]}),o.jsxs(le,{variant:"primary",className:"w-full justify-center md:w-auto",onClick:c,children:[o.jsx(Zr,{})," New skill"]})]})]}),o.jsx("div",{className:"max-w-120",children:o.jsx($f,{onSearch:m,label:"Filter skills",placeholder:"Filter by name or description"})})]}),k]}),i&&o.jsx(r4r,{open:!!i,onOpenChange:_=>{_||l(null)},registryId:i.id,registryLabel:i.label,installedSkillIds:y,onInstalled:_=>{const C=v.find(E=>E.id===_);ru.success(C?`Imported "${C.name}"`:"Skill imported")},onCollision:_=>{const C=v.find(E=>E.id===_||E.name===_);C?ru.error(`"${C.name}" is already in your library`,{action:{label:"Open existing",onClick:()=>u(C.id)}}):ru.error(`A skill named "${_}" already exists.`)}})]})}const a4r=[{title:"Code reviewer",icon:Up,prompt:"Build a skill that reviews TypeScript code for type-safety issues, missing tests, and inconsistent patterns. Leave concrete suggestions with examples."},{title:"Doc summarizer",icon:jc,prompt:"Build a skill that summarizes long technical documents into a one-page brief with the key points, action items, and open questions."},{title:"Onboarding tutor",icon:Sdt,prompt:"Build a skill that onboards new engineers to a codebase. Explain the architecture, point to the right docs, and answer questions in plain English with code examples."},{title:"Research notes",icon:ldt,prompt:"Build a skill that turns messy research notes into structured findings with sources, methodology, and a tl;dr at the top."}],i4r=e=>e.length<=20?e:e.slice(0,20)+"…",o4r=()=>{const[e,t]=g.useState(""),n=Hs(),r=g.useRef(null),s=xCe(),a=y3(),{data:i}=WW(),{data:l}=z1(),c=g.useMemo(()=>(i?.workspaces??[]).filter(v=>v.status!=="archived").sort((v,y)=>(y.runtimeRegistered?1:0)-(v.runtimeRegistered?1:0)).map(v=>({value:v.id,label:v.name})),[i]),u=g.useMemo(()=>{const v=l?.configuration?.agent?.workspace;return v?.type==="id"?v.workspaceId:void 0},[l]),d=e.trim(),f=s.isPending,p=async v=>{if(v.preventDefault(),d.length===0||f)return;const y=QU(),b=u??(c.length===1?c[0].value:void 0);try{await s.mutateAsync({id:y,name:i4r(d),description:"",instructions:"",visibility:a,workspaceId:b,files:[]})}catch{De.error("Failed to start a new skill");return}n(`/agent-builder/skills/${y}/edit`,{state:{userMessage:d},viewTransition:!0})},h=v=>{f||v.key==="Enter"&&!v.shiftKey&&!v.nativeEvent.isComposing&&(v.preventDefault(),v.currentTarget.form?.requestSubmit())},m=v=>{t(v),r.current?.focus()};return o.jsx("div",{className:"starter-aurora flex min-h-full flex-col items-center justify-center bg-surface1 px-6 py-24",children:o.jsxs("div",{className:"relative z-10 flex w-full max-w-3xl flex-col gap-12",children:[o.jsx("h1",{className:"starter-heading text-center font-serif text-neutral6",style:{fontSize:"clamp(1.875rem, 3.5vw, 2.5rem)",lineHeight:1.1,letterSpacing:"-0.015em"},children:"What skill do you want to build?"}),o.jsx("form",{onSubmit:p,children:o.jsxs("div",{className:"starter-prompt rounded-2xl border border-border1 bg-surface2 transition-colors duration-normal ease-out-custom focus-within:border-neutral3",style:{viewTransitionName:"skill-chat-composer"},children:[o.jsx(Ml,{ref:r,testId:"skill-builder-starter-input",size:"default",variant:"unstyled",placeholder:"Describe the skill you want to build…",value:e,onChange:v=>t(v.target.value),onKeyDown:h,disabled:f,className:"min-h-[112px] resize-none px-5 py-4 text-ui-md outline-none placeholder:text-neutral3 focus:outline-none focus-visible:outline-none",rows:3}),o.jsx("div",{className:"flex items-center justify-end px-3 pb-2.5",children:o.jsx(le,{type:"submit",variant:"default",size:"icon-md",tooltip:"Start building",disabled:d.length===0||f,"data-testid":"skill-builder-starter-submit",className:"rounded-full",children:f?o.jsx("span",{"data-testid":"skill-builder-starter-submit-spinner",children:o.jsx(Kt,{})}):o.jsx($D,{})})})]})}),o.jsx("div",{className:"flex flex-wrap justify-center gap-2",children:a4r.map((v,y)=>{const b=v.icon;return o.jsxs("button",{type:"button",onClick:()=>m(v.prompt),"data-testid":`skill-builder-starter-example-${v.title.toLowerCase().replace(/\s+/g,"-")}`,style:{animationDelay:`${280+y*40}ms`},className:"starter-chip group inline-flex items-center gap-2 rounded-full border border-border1 bg-transparent px-4 py-2 text-ui-sm text-neutral4 transition-colors duration-normal ease-out-custom hover:border-border2 hover:bg-surface2 hover:text-neutral6",children:[o.jsx(b,{className:"h-3.5 w-3.5 text-neutral3 transition-colors group-hover:text-neutral5"}),v.title]},v.title)})})]})})};function l4r(){const{hasPermission:e,rbacEnabled:t}=dl(),n=!t||e("stored-skills:write");K1({enabled:n}),WW(),z1();const r=Hs();return n?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"absolute top-3 left-3 md:top-6 md:left-6 z-10",children:o.jsx(le,{size:"icon-sm",variant:"ghost",onClick:()=>r("/agent-builder/skills",{viewTransition:!0}),className:"rounded-full",tooltip:"Skills list",children:o.jsx(Rc,{})})}),o.jsx(o4r,{})]}):o.jsx(Vu,{to:"/agent-builder/skills",replace:!0})}function c4r(e){const t=We(),n=Ur();return Rn({mutationFn:()=>{if(!e)throw new Error("skillId is required for delete");return t.getStoredSkill(e).delete()},onSuccess:()=>{n.invalidateQueries({queryKey:["stored-skills"]}),e&&n.removeQueries({queryKey:["stored-skill",e]})}})}const r$t=({skillId:e})=>{const[t,n]=g.useState(!1),r=Hs(),s=c4r(e),a=async()=>{try{await s.mutateAsync(),De.success("Skill deleted"),n(!1),r("/agent-builder/skills",{viewTransition:!0})}catch(i){De.error(i instanceof Error?i.message:"Failed to delete skill")}};return{open:t,setOpen:n,isPending:s.isPending,confirm:a}},s$t=({open:e,onOpenChange:t,skillName:n,isPending:r,onConfirm:s})=>o.jsx(At,{open:e,onOpenChange:t,children:o.jsxs(At.Content,{"data-testid":"skill-builder-delete-skill-dialog",children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete skill?"}),o.jsxs(At.Description,{children:['This permanently deletes "',n,'". This cannot be undone.']})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{"data-testid":"skill-builder-delete-skill-cancel",disabled:r,children:"Cancel"}),o.jsx(le,{variant:"primary","data-testid":"skill-builder-delete-skill-confirm",disabled:r,onClick:()=>{s()},children:r?"Deleting…":"Delete skill"})]})]})}),u4r=({skillId:e,skillName:t,disabled:n=!1})=>{const{open:r,setOpen:s,isPending:a,confirm:i}=r$t({skillId:e});return o.jsxs(o.Fragment,{children:[o.jsxs(le,{size:"lg",variant:"default",onClick:()=>s(!0),disabled:n||a,className:"w-full","data-testid":"skill-builder-delete-skill",children:[o.jsx(uu,{}),o.jsx("span",{children:"Delete skill"})]}),o.jsx(s$t,{open:r,onOpenChange:s,skillName:t,isPending:a,onConfirm:i})]})},d4r=({skillId:e,skillName:t,disabled:n=!1})=>{const{open:r,setOpen:s,isPending:a,confirm:i}=r$t({skillId:e});return o.jsxs(o.Fragment,{children:[o.jsxs(dt.Item,{"data-testid":"skill-builder-mobile-menu-delete",disabled:n,className:"text-red-500 focus:text-red-400",onSelect:l=>{l.preventDefault(),s(!0)},children:[o.jsx(uu,{}),o.jsx("span",{children:"Delete skill"})]}),o.jsx(s$t,{open:r,onOpenChange:s,skillName:t,isPending:a,onConfirm:i})]})};function a$t(e,t){const n=[];for(const r of e){const s=t?`${t}/${r.name}`:r.name;r.type==="file"&&r.content!==void 0?n.push({path:s,content:r.content}):r.type==="folder"&&r.children&&n.push(...a$t(r.children,s))}return n}function VCe(e={}){const t=We(),n=Ur(),r=u2t(),{hasPermission:s}=dl(),a=s("workspaces:write"),{silent:i=!1}=e;return Rn({mutationFn:async l=>{const{id:c,name:u,description:d,visibility:f,instructions:p,files:h,workspaceId:m}=l;if(h?.length&&m&&a){const S=a$t(h,"");try{await Promise.all(S.map(x=>r.mutateAsync({workspaceId:m,path:`skills/${x.path}`,content:x.content,recursive:!0})))}catch(x){console.warn("[skill] Workspace file write failed, saving to DB only:",x)}}const v=p??(h?YU(h):void 0),y=h?a2t(h):void 0,b={};return u!==void 0&&(b.name=u),d!==void 0&&(b.description=d),f!==void 0&&(b.visibility=f),v!==void 0&&(b.instructions=v),y!==void 0&&(b.license=y),h!==void 0&&(b.files=h),t.getStoredSkill(c).update(b)},onSuccess:()=>{n.invalidateQueries({queryKey:["stored-skills"]}),n.invalidateQueries({queryKey:["stored-skill"]}),i||De.success("Skill updated")},onError:l=>{i||De.error(`Failed to update skill: ${l instanceof Error?l.message:"Unknown error"}`)}})}const f4r={public:{title:"Add this skill to your library?",description:"Adding this skill to the library means your teammates will be able to discover and use it.",toast:"Skill added to the library"},private:{title:"Remove this skill from your library?",description:"Removing this skill from the library means your teammates will no longer be able to discover or use it. You will be the only person with access.",toast:"Skill removed from the library"}};function i$t(e){const t=Vr(),n=VCe({silent:!0});return MRt({copy:f4r,isPending:n.isPending,mutate:r=>n.mutateAsync({id:e,visibility:r}),onSuccess:r=>{t.setValue("visibility",r,{shouldDirty:!1})},testIds:{dialog:"skill-builder-visibility-confirm-dialog",cancel:"skill-builder-visibility-confirm-cancel",confirm:"skill-builder-visibility-confirm-yes"}})}function p4r({skillId:e,showSetVisibility:t=!1,showDelete:n=!1,skillName:r="",disabled:s=!1}){return!t&&!n?null:o.jsx("div",{className:"lg:hidden","data-testid":"skill-builder-mobile-menu",children:o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsx(le,{size:"icon-sm",variant:"ghost",tooltip:"More actions","data-testid":"skill-builder-mobile-menu-trigger",children:o.jsx(DD,{})})}),o.jsxs(dt.Content,{align:"end",children:[t&&o.jsx(h4r,{skillId:e,disabled:s}),t&&n&&o.jsx(dt.Separator,{}),n&&o.jsx(d4r,{skillId:e,skillName:r,disabled:s})]})]})})}function h4r({skillId:e,disabled:t}){const n=Vr(),r=Mn({control:n.control,name:"visibility"})??"private",{requestChange:s,dialog:a}=i$t(e);return o.jsxs(o.Fragment,{children:[r==="private"?o.jsxs(dt.Item,{"data-testid":"skill-builder-mobile-menu-visibility-add",disabled:t,closeOnClick:!1,onSelect:()=>{s("public")},children:[o.jsx(Ux,{}),o.jsx("span",{children:"Add to library"})]}):o.jsxs(dt.Item,{"data-testid":"skill-builder-mobile-menu-visibility-remove",disabled:t,closeOnClick:!1,onSelect:()=>{s("private")},children:[o.jsx(Cf,{}),o.jsx("span",{children:"Remove from library"})]}),a]})}function m4r({skillId:e}){const t=Vr(),n=Mn({control:t.control,name:"visibility"})??"private",{requestChange:r,dialog:s}=i$t(e);return o.jsxs(o.Fragment,{children:[n==="private"?o.jsxs(le,{size:"sm",variant:"default",onClick:()=>r("public"),"data-testid":"skill-builder-visibility-add",children:[o.jsx(Ux,{className:"h-3.5 w-3.5"}),"Add to library"]}):o.jsxs(le,{size:"sm",variant:"ghost",onClick:()=>r("private"),"data-testid":"skill-builder-visibility-remove",children:[o.jsx(Cf,{className:"h-3.5 w-3.5"}),"Remove from library"]}),s]})}const g4r=600,v4r=2e3;function y4r({skillId:e,debounceMs:t=g4r,savedDisplayMs:n=v4r}){const r=Vr(),s=VCe({silent:!0}),[a,i]=g.useState("idle"),[l,c]=g.useState(null),u=g.useRef(r.getValues()),d=g.useRef(0),f=g.useRef(null),p=()=>{f.current&&(clearTimeout(f.current),f.current=null)},h=g.useCallback(async()=>{const b=++d.current,S=u.current;p(),i("saving"),c(null);try{const x=kk(S.name||"untitled"),k=S.name?s2t(x,S.name):x,_=Ev(k,"skill-md",S.instructions??"");if(await s.mutateAsync({id:e,name:S.name,description:S.description,instructions:S.instructions,visibility:S.visibility,workspaceId:S.workspaceId,files:_}),b!==d.current)return;i("saved"),f.current=setTimeout(()=>{f.current=null,i("idle")},n)}catch(x){if(b!==d.current)return;i("error"),c(x instanceof Error?x:new Error(String(x)))}},[e,s,n]),m=My(()=>{h()},t);g.useEffect(()=>{const b=r.watch(S=>{u.current=S,m()});return()=>{b.unsubscribe()}},[r,m]),g.useEffect(()=>()=>{m.flush(),p()},[m]);const v=g.useCallback(()=>{h()},[h]),y=g.useCallback(()=>{m.flush()},[m]);return{status:a,lastError:l,retry:v,flushNow:y}}function o$t(e){const t=We();return yt({queryKey:["stored-skill",e],queryFn:()=>t.getStoredSkill(e).details(),enabled:!!e})}const b4r=({title:e,rightAside:t,primaryAction:n,mobileExtra:r,showForm:s=!0,chat:a,form:i,deleteAction:l})=>{const c=Hs(),[u,d]=g.useState("chat");return o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2 bg-surface1 px-3 py-2 md:px-6 md:py-3",children:[o.jsx(le,{size:"icon-sm",variant:"ghost",onClick:()=>c("/agent-builder/skills",{viewTransition:!0}),className:"rounded-full",tooltip:"Skills list","data-testid":"skill-edit-back-button",children:o.jsx(Rc,{})}),o.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[o.jsx("div",{className:"min-w-0 truncate text-ui-md text-neutral6",children:e}),t&&o.jsx("div",{className:"shrink-0",children:t})]}),n&&o.jsx("div",{className:"shrink-0",children:n}),r&&o.jsx("div",{className:"shrink-0 lg:hidden",children:r})]}),s&&o.jsx("div",{className:"md:hidden px-4 pt-4 pb-2",children:o.jsxs("div",{role:"tablist","aria-label":"Workspace view",className:"relative mx-auto flex h-9 w-full max-w-sm items-center rounded-full border border-border1 bg-surface3 p-0.5",children:[o.jsx("span",{"aria-hidden":"true",className:X("absolute inset-y-0.5 left-0.5 w-[calc(50%-2px)] rounded-full bg-surface4","transition-transform duration-200 ease-out",u==="configure"&&"translate-x-full")}),o.jsx("button",{type:"button",role:"tab","aria-selected":u==="chat","data-testid":"skill-edit-tab-chat",onClick:()=>d("chat"),className:X("relative z-10 flex-1 rounded-full text-ui-md font-medium outline-none","transition-colors duration-200",u==="chat"?"text-neutral5":"text-neutral3 hover:text-neutral4"),children:"Chat"}),o.jsx("button",{type:"button",role:"tab","aria-selected":u==="configure","data-testid":"skill-edit-tab-configure",onClick:()=>d("configure"),className:X("relative z-10 flex-1 rounded-full text-ui-md font-medium outline-none","transition-colors duration-200",u==="configure"?"text-neutral5":"text-neutral3 hover:text-neutral4"),children:"Configuration"})]})}),o.jsxs("div",{className:X("grid min-h-0 flex-1 grid-cols-1",s&&"md:grid-cols-[1fr_minmax(360px,40%)]"),children:[o.jsx("div",{className:X("min-w-0 min-h-0 overflow-hidden bg-surface1",s&&u!=="chat"?"hidden":"block","md:block","md:transition-[grid-column] md:duration-300 md:ease-out"),children:o.jsx("div",{className:"flex h-full min-h-0 flex-col px-4 pt-4 pb-6 md:px-10",children:o.jsx("div",{className:"flex min-h-0 flex-1 flex-col md:max-w-[80ch] md:mx-auto w-full",children:a})})}),s&&o.jsx("div",{className:X("min-w-0 min-h-0 overflow-hidden bg-surface1",u==="configure"?"block":"hidden","md:block","px-4 pb-6 md:p-4 md:bg-transparent"),"data-testid":"skill-edit-configure-panel",children:o.jsxs("div",{className:X("skill-panel-slide-in flex h-full min-h-0 flex-col overflow-hidden","md:rounded-3xl md:border md:border-border1 md:bg-surface2"),children:[o.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:i}),l&&o.jsx("div",{className:"border-t border-border1 px-4 pb-4 pt-4 md:px-6","data-testid":"skill-edit-delete-action",children:l})]})})]})]})},l$t="skillBuilderTool",c$t="readSkillForm",WZe=`# Role
|
|
496
|
+
`):"",Qv=e=>{if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)},k3=e=>$x(e)?e.type==="notification"||e.type==="state"||e.type==="reactive":!1,yPt=e=>{const t=e.content.metadata?.signal;return $x(t)?t:void 0},PCe=e=>{const t=yPt(e)?.type;return typeof t=="string"?t:e.type},bPt=e=>e==="user"||e==="user-message",$Pr=e=>{const t=[];for(const n of e){const r=n;if(r.type==="text"&&typeof r.text=="string"){t.push({type:"text",text:r.text});continue}if(r.type==="file"&&typeof r.data=="string"){const s=(typeof r.mediaType=="string"?r.mediaType:void 0)??(typeof r.mimeType=="string"?r.mimeType:void 0)??"application/octet-stream";t.push({type:"file",data:r.data,mediaType:s})}}return t.length===1&&t[0]?.type==="text"?t[0].text:t},xPt=e=>{const t=yPt(e)??{};return{id:typeof t.id=="string"?t.id:e.id,type:PCe(e),tagName:typeof t.tagName=="string"?t.tagName:e.type,contents:$Pr(e.content.parts),...$x(t.attributes)?{attributes:t.attributes}:{},...$x(t.metadata)?{metadata:t.metadata}:{}}},wPt=e=>{const t=$x(e.metadata?.notification)?e.metadata.notification:void 0;if(t)return{signal:t.signal==="notification"||t.signal==="summary"?t.signal:void 0,recordId:typeof t.recordId=="string"?t.recordId:void 0,source:typeof t.source=="string"?t.source:void 0,kind:typeof t.kind=="string"?t.kind:void 0,priority:typeof t.priority=="string"?t.priority:void 0,status:typeof t.status=="string"?t.status:void 0,pending:typeof t.pending=="number"?t.pending:void 0}},MPr=e=>{const t=wPt(e);if(t?.signal==="summary"||e.tagName==="notification-summary")return"Notification summary";const n=t?.source??Qv(e.attributes?.source),r=t?.kind??Qv(e.attributes?.kind);return n&&r?`${n} / ${r}`:n??r??"Notification"},DPr=({signal:e})=>{const t=wPt(e),n=t?.priority??Qv(e.attributes?.priority),r=Qv(t?.pending)??Qv(e.attributes?.pending),s=t?.status??Qv(e.attributes?.status),a=vPt(e.contents),i=r?`${r} pending`:void 0,l=!!(n||s||i),c=a.length>0;return o.jsx(En,{variant:PPr(n),title:MPr(e),icon:o.jsx(Pfn,{}),className:"my-2 max-w-[80%]",children:l||c?o.jsxs("div",{className:"flex flex-col gap-2",children:[l?o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n?o.jsx(un,{size:"xs",children:n}):null,s?o.jsx(un,{size:"xs",children:s}):null,i?o.jsx(un,{size:"xs",children:i}):null]}):null,c?o.jsx(En.Message,{className:"whitespace-pre-wrap break-words",children:a}):null]}):null})},LPr=e=>{const t=$x(e.metadata?.state)?e.metadata.state:void 0;return{id:Qv(t?.id)??Qv(e.attributes?.id)??"State signal",mode:Qv(t?.mode)??Qv(e.attributes?.mode)}},FPr=({children:e})=>o.jsx("span",{className:"inline-flex items-center rounded-full border border-border1 px-1.5 py-0.5 text-xs leading-none text-neutral4",children:e});function zPr(e){return Array.isArray(e)&&e.every(t=>$x(t)&&typeof t.id=="string"&&typeof t.content=="string"&&(t.status==="pending"||t.status==="in_progress"||t.status==="completed")&&typeof t.activeForm=="string")}function BPr(e){if(!(e.id==="tasks"||e.tagName==="current-task-list"||e.tagName==="task-list-update"))return;const n=e.metadata,s=($x(n?.value)?n.value:void 0)?.tasks;if(zPr(s))return s}const SPt=({signal:e})=>{if(!k3(e))return null;const t=vPt(e.contents);if(e.type==="state"){if(BPr(e))return null;const r=LPr(e);return o.jsx("div",{className:"my-2 max-w-[80%] rounded-lg border border-border1 bg-surface2 px-4 py-3 text-neutral5",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(uy,{className:"mt-0.5 h-4 w-4 shrink-0 text-icon3"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("p",{className:"text-ui-sm leading-ui-sm font-medium text-neutral6",children:r.id}),r.mode?o.jsx(FPr,{children:r.mode}):null]}),t?o.jsx("p",{className:"mt-2 whitespace-pre-wrap break-words text-ui-sm leading-ui-md",children:t}):null]})]})})}return e.type==="notification"?o.jsx(DPr,{signal:e}):e.type==="reactive"?o.jsx("div",{className:"my-2 max-w-[80%] rounded-lg border border-border1 bg-surface2 px-4 py-3 text-neutral5",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(jdt,{className:"mt-0.5 h-4 w-4 shrink-0 text-icon3"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("p",{className:"text-ui-sm leading-ui-sm font-medium text-neutral6",children:e.tagName??"Signal"}),t?o.jsx("p",{className:"mt-2 whitespace-pre-wrap break-words text-ui-sm leading-ui-md",children:t}):null]})]})}):null},AZe=({toolCallId:e,toolName:t})=>{const{approveToolCall:n,declineToolCall:r}=Gjr(),[s,a]=g.useState(null),i=s!==null,l=()=>{a("approve"),n(e)},c=()=>{a("decline"),r(e)};return o.jsxs(OPt,{testId:"agent-builder-chat-tool-approval",className:"bg-surface4 border-transparent",children:[o.jsxs(ye,{variant:"ui-sm",className:"text-neutral5 pb-2",as:"div",children:["Approval required for ",o.jsx("span",{className:"font-mono text-neutral6",children:t})]}),o.jsxs("div",{className:"flex gap-2 items-center",children:[o.jsxs(le,{variant:"default",onClick:l,disabled:i,"data-testid":"agent-builder-chat-tool-approve","aria-label":`Approve ${t}`,children:[o.jsx(qe,{children:s==="approve"?o.jsx(oa,{className:"animate-spin"}):o.jsx(pa,{})}),"Approve"]}),o.jsxs(le,{variant:"ghost",onClick:c,disabled:i,"data-testid":"agent-builder-chat-tool-decline","aria-label":`Decline ${t}`,children:[s==="decline"&&o.jsx(qe,{children:o.jsx(oa,{className:"animate-spin"})}),"Decline"]})]})]})},kPt=e=>e.role==="assistant"||e.role==="user"||e.role==="system"?e.role:e.role==="signal"?bPt(PCe(e))?"user":"assistant":null,UPr=e=>{const t=xPt(e);return k3(t)?{...e,role:"assistant",content:{...e.content,parts:[{type:"data-signal",data:t}]}}:null},VPr=e=>{const t=e.content.metadata;if(!t||typeof t!="object")return;const{mode:n}=t;if(!(n!=="stream"&&n!=="network"&&n!=="generate"))return t.requireApprovalMetadata},qPr=e=>!e||typeof e!="object"||!("name"in e)?"unknown":typeof e.name=="string"?e.name:"unknown",RZe=(e,t,n)=>{if(e)return(t?e[t]:void 0)??(n?e[n]:void 0)},HPr=e=>{const t=kPt(e);return t===null?null:e.role==="signal"&&t==="assistant"?UPr(e):t===e.role?e:{...e,role:t}},PZe=(e,t,n)=>{switch(e){case mCe:return o.jsx(KPr,{});case fCe:return o.jsx(XPr,{});case pCe:return o.jsx(JPr,{});case vCe:return o.jsx(e$r,{});case gCe:return o.jsx(t$r,{});case hCe:return o.jsx(n$r,{});case dCe:return o.jsx(r$r,{});case yCe:return o.jsx(s$r,{});case"skill":return o.jsx(a$r,{name:qPr(t)});default:return o.jsx(YPr,{toolName:e,input:t,output:n})}},WPr=({message:e})=>{const t=VPr(e),n=Qjr(),r=kPt(e),s=HPr(e);if(s===null)return null;const a=e.content.metadata,i={Text:c=>o.jsx(ZPr,{txt:c.text??"",role:r,metadata:a}),Reasoning:c=>("state"in c?c.state:void 0)!=="streaming"?null:o.jsx(gPt,{text:"Reasoning..."}),Data:c=>c.type==="data-signal"&&k3(c.data)?o.jsx(SPt,{signal:c.data}):null,ToolInvocation:c=>{const u=c.toolInvocation,d=RZe(t,u.toolName,u.toolCallId);if(d&&u.state!=="result")return o.jsx(AZe,{toolCallId:d.toolCallId,toolName:d.toolName});if(u.state!=="result")return null;const f="args"in u?u.args:void 0,p="result"in u?u.result:void 0;return PZe(u.toolName,f,p)},DynamicTool:c=>{const u=c.toolName??c.type.replace(/^tool-/,""),d=RZe(t,u,c.toolCallId);return d&&c.state!=="output-available"?o.jsx(AZe,{toolCallId:d.toolCallId,toolName:d.toolName}):c.state!=="output-available"?null:PZe(u,c.input,c.output)}},l={Error:({text:c})=>o.jsx(GPr,{error:TPr(c),onRetry:n}),Warning:dPt,Tripwire:fPt};return o.jsx(G9,{message:s,...i,status:l})},ZPr=({txt:e,role:t,metadata:n})=>t==="user"?o.jsx("div",{className:"flex justify-end",children:o.jsx(ye,{variant:"ui-md",className:"bg-white text-black rounded-2xl px-4 py-2.5 max-w-[80%] [&_ul]:!space-y-1 [&_ol]:!space-y-1 [&_li]:!my-0 [&_p]:!leading-normal [&_p]:!whitespace-normal [&_li]:!leading-normal",as:"div",children:o.jsx(Gp,{children:e})})}):t==="assistant"||t==="system"?o.jsx(ye,{variant:"ui-md",className:"text-neutral4 max-w-[80%] [&_ul]:!space-y-1 [&_ol]:!space-y-1 [&_li]:!my-0 [&_p]:!leading-normal [&_p]:!whitespace-normal [&_li]:!leading-normal",as:"div",children:o.jsx(RCe,{text:e,metadata:n})}):null,GPr=({error:e,onRetry:t})=>o.jsxs(X_,{className:"border-accent6/40 bg-accent6/5 max-w-[80%] p-4 flex flex-col gap-3",role:"alert","data-testid":"agent-builder-chat-error",children:[o.jsxs("div",{className:"flex items-start gap-2.5",children:[o.jsx(yf,{className:"size-4 mt-0.5 shrink-0 text-accent6","aria-hidden":!0}),o.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[o.jsx(ye,{variant:"ui-md",className:"text-icon6 font-medium",as:"div",children:"Something went wrong while building the agent."}),o.jsx(ye,{variant:"ui-sm",className:"text-neutral4 break-words",as:"div","data-testid":"agent-builder-chat-error-summary",children:e.summary})]})]}),e.details&&e.details!==e.summary?o.jsxs(jf,{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[t!==null&&o.jsxs(le,{variant:"default",onClick:t,className:"gap-1.5","data-testid":"agent-builder-chat-error-retry",children:[o.jsx(n1,{className:"size-3.5","aria-hidden":!0}),"Try again"]}),o.jsx($d,{className:"text-neutral4 hover:text-neutral6 text-sm underline-offset-2 hover:underline","data-testid":"agent-builder-chat-error-details-trigger",children:"Details"})]}),o.jsx(Md,{children:o.jsx("pre",{className:"text-xs text-neutral4 whitespace-pre-wrap break-all bg-surface1 rounded-md p-2 max-h-48 overflow-auto","data-testid":"agent-builder-chat-error-details",children:e.details})})]}):t!==null&&o.jsx("div",{className:"flex items-center gap-3",children:o.jsxs(le,{variant:"default",onClick:t,className:"gap-1.5","data-testid":"agent-builder-chat-error-retry",children:[o.jsx(n1,{className:"size-3.5","aria-hidden":!0}),"Try again"]})})]}),QPr=({testId:e})=>o.jsxs("div",{className:"flex flex-col gap-6","data-testid":e,children:[o.jsx("div",{className:"flex justify-end",children:o.jsx(xt,{className:"h-10 w-56 rounded-2xl"})}),o.jsx(xt,{className:"h-6 w-[70%] rounded-full"}),o.jsx(xt,{className:"h-6 w-[55%] rounded-full"}),o.jsx("div",{className:"flex justify-end",children:o.jsx(xt,{className:"h-10 w-40 rounded-2xl"})}),o.jsx(xt,{className:"h-6 w-[65%] rounded-full"})]}),$Ze=e=>{if(e===void 0)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}},YPr=({toolName:e,input:t,output:n})=>{const r=$Ze(t),s=$Ze(n),a=s.length>0;return o.jsx(OPt,{testId:"agent-builder-chat-generic-tool",children:o.jsxs(jf,{children:[o.jsxs($d,{className:"flex w-full items-center gap-2 text-left group","data-testid":"agent-builder-chat-generic-tool-trigger",children:[o.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-border1/60 bg-surface1 px-2 py-0.5",children:[o.jsx(Up,{className:"size-3.5 shrink-0 text-neutral4","aria-hidden":!0}),o.jsxs(ye,{variant:"ui-sm",className:"text-neutral5",as:"span",children:["Executing ",o.jsx("span",{className:"font-mono text-neutral6",children:e})]})]}),o.jsx(ha,{className:"size-4 shrink-0 text-neutral4 transition-transform group-data-[state=open]:rotate-90","aria-hidden":!0})]}),o.jsx(Md,{children:o.jsxs("div",{className:"mt-3 flex flex-col gap-2","data-testid":"agent-builder-chat-generic-tool-content",children:[o.jsxs("div",{className:"rounded-md border border-border1/60 bg-surface1 overflow-hidden",children:[o.jsx("div",{className:"px-2 py-1 border-b border-border1/60",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",as:"div",children:"Input"})}),o.jsx("pre",{className:"m-0 max-h-[320px] overflow-auto p-3 text-xs leading-relaxed text-neutral5 whitespace-pre-wrap break-words",children:r||"{}"})]}),a?o.jsxs("div",{className:"rounded-md border border-border1/60 bg-surface1 overflow-hidden",children:[o.jsx("div",{className:"px-2 py-1 border-b border-border1/60",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",as:"div",children:"Output"})}),o.jsx("pre",{className:"m-0 max-h-[320px] overflow-auto p-3 text-xs leading-relaxed text-neutral5 whitespace-pre-wrap break-words",children:s})]}):null]})})]})})},OPt=({children:e,testId:t,className:n})=>o.jsx(X_,{"data-testid":t,className:X("max-w-[80%] p-3 bg-surface2/60 border-border1/60 animate-in fade-in slide-in-from-left-2 duration-300",n),children:e}),i0=({icon:e,label:t,value:n})=>o.jsxs("div",{className:"flex items-start gap-2 min-w-0 max-w-full animate-in fade-in slide-in-from-right-4 duration-500 ease-out",children:[o.jsx("div",{className:"pt-0.5",children:o.jsx(qe,{children:e})}),o.jsxs(ye,{variant:"ui-md",className:"text-neutral3 min-w-0 flex-1 truncate",as:"div",children:[t," ",o.jsx("strong",{className:"font-semibold text-neutral6",children:n})]})]}),KPr=()=>{const{watch:e}=Vr(),t=e("name");return t?o.jsx(i0,{icon:o.jsx(adt,{}),label:"Setting the agent name:",value:t}):null},XPr=()=>{const{watch:e}=Vr(),t=e("description");return t?o.jsx(i0,{icon:o.jsx(adt,{}),label:"Setting the agent description:",value:t}):null},JPr=()=>{const{watch:e}=Vr(),t=e("instructions");return t?o.jsx(i0,{icon:o.jsx(jc,{}),label:"Setting the agent instructions:",value:t}):null},e$r=()=>{const{agentId:e,toolsData:t,agentsData:n,workflowsData:r}=aC(),{watch:s}=Vr(),a=s("tools"),i=s("agents"),l=s("workflows"),u=mPt({toolsData:t,agentsData:n,workflowsData:r,selectedTools:a,selectedAgents:i,selectedWorkflows:l,excludeAgentId:e}).filter(f=>f.isChecked),d=u.length===0?"none":u.map(f=>f.name).join(", ");return o.jsx(i0,{icon:o.jsx(Up,{}),label:"Enabling tools:",value:d})},t$r=()=>{const{availableSkills:e}=aC(),{watch:t}=Vr(),n=t("skills"),r=n?e.filter(a=>n[a.id]===!0):[],s=r.length===0?"none":r.map(a=>a.name).join(", ");return o.jsx(i0,{icon:o.jsx(Axe,{}),label:"Enabling skills:",value:s})},n$r=()=>{const{watch:e}=Vr(),t=e("model");return t?o.jsx(i0,{icon:o.jsx(II,{providerId:t.provider,size:16}),label:"Setting agent model to",value:`${t.provider}/${t.name}`}):null},r$r=()=>{const{watch:e}=Vr(),t=e("browserEnabled");return o.jsx(i0,{icon:t?o.jsx(Ux,{}):o.jsx(Thn,{}),label:"Browser access",value:t?"enabled":"disabled"})},s$r=()=>{const{watch:e}=Vr(),t=e("workspaceId");return t?o.jsx(i0,{icon:o.jsx(udt,{}),label:"Setting workspace to",value:t}):null},a$r=({name:e})=>o.jsx(i0,{icon:o.jsx(Axe,{}),label:"Using super-powers:",value:e}),i$r=e=>{const t=g.useRef(null);return g.useEffect(()=>{const n=t.current;n&&n.scrollTo({top:n.scrollHeight,behavior:"smooth"})},[e]),t},o$r=(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},l$r=300,c$r=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,$Ce=({messages:e,isLoading:t=!1,isRunning:n=!1,emptyState:r,skeletonTestId:s})=>{const a=i$r(e),i=t&&e.length===0,l=o$r(i,l$r),c=!t&&e.length===0&&r!==void 0,u=e[e.length-1],d=n&&!i&&(u?.role!=="assistant"||!c$r(u));return o.jsx("div",{ref:a,className:"flex-1 min-h-0 overflow-y-auto py-6 px-6",style:{viewTransitionName:"agent-builder-messages"},children:l?o.jsx(QPr,{testId:s}):c?r:o.jsxs("div",{className:"flex flex-col gap-6",children:[e.map(f=>o.jsx(WPr,{message:f},f.id)),d&&o.jsx(m2t,{testId:"agent-builder-chat-pending"})]})})},MZe="builder-agent",u$r=e=>`agent-builder-${e}`,d$r=({initialUserMessage:e,isFreshThread:t=!1,features:n,availableAgentTools:r=[],availableWorkspaces:s=[],availableSkills:a=[],toolsReady:i=!0,agentId:l,children:c})=>{const u=u$r(l),{data:d,isLoading:f}=AH({agentId:MZe,threadId:u,memory:!t}),p=g.useMemo(()=>[],[l]),h=d?.messages??p,m=(d?.messages?.length??0)>0,{models:v,isLoading:y}=Y1(),b=n.model?v:[],{isLoading:S}=S3(),x=i&&(!n.model||!y)&&!S,k=uTr({features:n,availableAgentTools:r,availableWorkspaces:s,availableSkills:a,availableModels:b,integrationToolsLoading:S}),{control:_}=Vr(),C=Mn({control:_}),E=DTr({availableWorkspaces:s}),j=g.useMemo(()=>({...k,...n.skills?{[p2t]:E}:{}}),[k,E,n.skills]),T=g.useMemo(()=>({isLoading:f,agentId:l}),[f,l]),I=x&&!f&&!m?e:void 0,A=nTr(C,{availableAgentTools:r,availableSkills:a,availableWorkspaces:s,availableModels:b,features:n,starterUserMessage:e});return o.jsx(t2t,{agentId:MZe,threadId:u,initialMessages:h,initialUserMessage:I,clientTools:j,extraInstructions:A,debounceTime:1e3,children:o.jsx(_Pt.Provider,{value:T,children:c})})},_Pt=g.createContext({isLoading:!1,agentId:""}),f$r=()=>o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[o.jsx(p$r,{}),o.jsx(h$r,{})]}),p$r=()=>{const e=cCe(),t=fu(),{isLoading:n}=g.useContext(_Pt);return o.jsx($Ce,{messages:e,isLoading:n,isRunning:t,skeletonTestId:"agent-builder-conversation-messages-skeleton"})},h$r=()=>{const e=e2t(),t=uCe(),{draft:n,setDraft:r,trimmed:s,handleFormSubmit:a,handleKeyDown:i}=n2t({onSubmit:t});return o.jsx(wCe,{draft:n,onDraftChange:r,onSubmit:a,onKeyDown:i,disabled:e,isRunning:e,canSubmit:s.length>0&&!e,placeholder:"Tell the builder what to change…",inputTestId:"agent-builder-conversation-input",submitTestId:"agent-builder-conversation-submit",containerTestId:"agent-builder-conversation-composer"})};function m$r(e){if(!e)return;const t={};for(const[n,r]of Object.entries(e)){const s={};for(const[i,l]of Object.entries(r.tools??{}))s[i]=l;const a={};for(const[i,l]of Object.entries(r.connections??{}))a[i]=l.map(c=>({kind:"author",toolkit:c.toolkit,connectionId:c.connectionId,...c.label?.trim()?{label:c.label.trim()}:{},...c.scope?{scope:c.scope}:{}}));t[n]={tools:s,connections:a}}return Object.keys(t).length>0?t:void 0}function g$r(e){if(!e||Array.isArray(e))return;const t=e,n={};for(const[r,s]of Object.entries(t)){if(typeof s!="object"||s===null)continue;const a=s.connections??{},i=Object.keys(a),l=d=>{const f=d.toLowerCase(),p=i.find(h=>f.startsWith(`${h.toLowerCase()}_`)||f===h.toLowerCase());if(p)return p;if(i.length===1)return i[0]},c={};for(const[d,f]of Object.entries(s.tools??{})){const p=f?.toolkit??l(d);p&&(c[d]={toolkit:p,...f?.description?{description:f.description}:{}})}const u={};for(const[d,f]of Object.entries(a))u[d]=f.map(p=>({kind:"author",toolkit:d,connectionId:p.connectionId,...p.label?.trim()?{label:p.label.trim()}:{},...p.scope?{scope:p.scope}:{}}));n[r]={tools:c,connections:u}}return Object.keys(n).length>0?n:void 0}function WF(e,t){return Object.fromEntries(Object.entries(e??{}).filter(([,n])=>n).map(([n])=>{const r=t.get(n);return[n,r?{description:r}:{}]}))}function v$r(e,t,n=[]){const r=new Map,s=new Map,a=new Map;for(const y of t)y.type==="tool"?r.set(y.id,y.description):y.type==="agent"?s.set(y.id,y.description):a.set(y.id,y.description);const i=new Map;for(const y of n)i.set(y.id,y.description);const l=WF(e.tools,r),c=WF(e.agents,s),u=WF(e.workflows,a),d=WF(e.skills,i),f=typeof e.workspaceId=="string"&&e.workspaceId.length>0?{type:"id",workspaceId:e.workspaceId}:void 0,p=e.description?.trim()?e.description.trim():void 0,h=e.avatarUrl?{avatarUrl:e.avatarUrl}:void 0,m=e.browserEnabled===!0,v=m$r(e.toolProviders);return{name:e.name,description:p,instructions:e.instructions,tools:l,agents:c,workflows:u,skills:d,workspace:f,browser:m,visibility:e.visibility,model:e.model,metadata:h,toolProviders:v}}function y$r(e){return e&&typeof e=="object"&&"code"in e&&e.code==="MODEL_NOT_ALLOWED"?{message:e instanceof Error?e.message:"Model is not allowed"}:null}function b$r({agentId:e,availableAgentTools:t=[],availableSkills:n=[],onSuccess:r,silent:s=!1}){const{updateStoredAgent:a}=O1(e),i=y3();return{save:g.useCallback(async c=>{const u=v$r(c,t,n),d=u.visibility??i,f=u.workspace?{workspace:u.workspace}:{},p={browser:u.browser},h=u.metadata?{metadata:u.metadata}:{},m=u.toolProviders?{toolProviders:u.toolProviders}:{};try{const v=await a.mutateAsync({autoPublish:!0,name:u.name,description:u.description,instructions:u.instructions,tools:u.tools,agents:u.agents,workflows:u.workflows,skills:u.skills,visibility:d,model:u.model,...f,...p,...h,...m});return s||De.success("Agent updated"),r?.(e),v}catch(v){const y=y$r(v);throw y?De.error(y.message):De.error(`Failed to save agent: ${v instanceof Error?v.message:"Unknown error"}`),v}},[e,t,n,a,r,i,s]),isSaving:a.isPending}}const x$r=600,w$r=2e3;function S$r({agentId:e,availableAgentTools:t=[],availableSkills:n=[],debounceMs:r=x$r,savedDisplayMs:s=w$r}){const a=Vr(),{save:i}=b$r({agentId:e,availableAgentTools:t,availableSkills:n,silent:!0}),[l,c]=g.useState("idle"),[u,d]=g.useState(null),f=g.useRef(a.getValues()),p=g.useRef(0),h=g.useRef(null),m=g.useCallback(()=>{h.current&&(clearTimeout(h.current),h.current=null)},[]),v=g.useCallback(async()=>{const x=++p.current,k=f.current;m(),c("saving"),d(null);try{if(await i(k),x!==p.current)return;c("saved"),h.current=setTimeout(()=>{h.current=null,c("idle")},s)}catch(_){if(x!==p.current)return;c("error"),d(_ instanceof Error?_:new Error(String(_)))}},[m,i,s]),y=My(()=>{v()},r);g.useEffect(()=>{const x=a.watch(k=>{f.current=k,y()});return()=>{x.unsubscribe()}},[a,y]),g.useEffect(()=>()=>{y.flush(),m()},[m,y]);const b=g.useCallback(()=>{v()},[v]),S=g.useCallback(()=>{y.flush()},[y]);return{status:l,lastError:u,retry:b,flushNow:S}}const CPt=g.createContext(null),k$r=({storedAgent:e,availableAgentTools:t,onModeToggle:n,children:r})=>{const{agentId:s,availableSkills:a,availableWorkspaces:i,initialUserMessage:l,isOwner:c}=aC(),u=Mf(),d=c&&e.visibility==="public",f=l!==void 0,p=S$r({agentId:s,availableAgentTools:t,availableSkills:a}),h=g.useMemo(()=>({agentId:s,isOwner:c,canPublishToChannel:d,features:u,availableAgentTools:t,availableSkills:a,availableWorkspaces:i,autosave:p,onModeToggle:n}),[s,c,d,u,t,a,i,p,n]);return o.jsx(CPt.Provider,{value:h,children:o.jsx(d$r,{agentId:s,features:u,availableAgentTools:t,availableWorkspaces:i,availableSkills:a,initialUserMessage:l,isFreshThread:f,toolsReady:!0,children:r})})},o0=()=>{const e=g.useContext(CPt);if(!e)throw new Error("useEditPage must be used inside <EditPageProvider>");return e};function O$r({platform:e,agentId:t,onCancel:n,onClose:r}){const{mutateAsync:s,isPending:a}=WRt(e.id),i=async()=>{try{await s(t),De.success(`${e.name} disconnected`),r()}catch(l){const c=l;De.error(c.body?.error||c.message||"Failed to disconnect channel")}};return o.jsxs(o.Fragment,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Are you sure?"}),o.jsxs(Ks,{children:["Your agent will be removed from ",o.jsx("span",{className:"text-neutral6",children:e.name}),"."]})]}),o.jsxs(Nc,{children:[o.jsx(le,{variant:"ghost",onClick:n,disabled:a,children:"Cancel"}),o.jsx(le,{variant:"default",onClick:i,disabled:a,"data-testid":`publish-channel-dialog-${e.id}-disconnect-confirm`,children:a?"Disconnecting…":"Confirm"})]})]})}const _$r=({className:e})=>o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[o.jsx("path",{d:"M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zm1.271 0a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313z",fill:"#E01E5A"}),o.jsx("path",{d:"M8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zm0 1.271a2.527 2.527 0 0 1 2.521 2.521 2.527 2.527 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312z",fill:"#36C5F0"}),o.jsx("path",{d:"M18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zm-1.27 0a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312z",fill:"#2EB67D"}),o.jsx("path",{d:"M15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zm0-1.27a2.527 2.527 0 0 1-2.52-2.523 2.527 2.527 0 0 1 2.52-2.52h6.313A2.528 2.528 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z",fill:"#ECB22E"})]}),C$r=({className:e})=>o.jsx("svg",{className:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:o.jsx("path",{d:"M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z",fill:"#5865F2"})}),E$r=({className:e})=>o.jsx("svg",{className:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:o.jsx("path",{d:"M11.944 0A12 12 0 1 0 24 12 12.01 12.01 0 0 0 11.944 0Zm5.625 8.244-1.95 9.2c-.146.658-.537.818-1.084.508l-3-2.211-1.447 1.394c-.16.16-.295.295-.605.295l.215-3.053 5.56-5.023c.242-.213-.054-.334-.375-.12l-6.871 4.326-2.962-.924c-.643-.204-.657-.643.135-.953l11.567-4.46c.537-.194 1.006.131.817.95v.07Z",fill:"#26A5E4"})}),j$r=({className:e})=>o.jsx("svg",{className:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:o.jsx("path",{d:"M9.5 2A1.5 1.5 0 0 0 8 3.5v2A1.5 1.5 0 0 0 9.5 7h5A1.5 1.5 0 0 0 16 5.5v-2A1.5 1.5 0 0 0 14.5 2h-5zM4 8.5A1.5 1.5 0 0 1 5.5 7H7v1.5A1.5 1.5 0 0 0 8.5 10h7a1.5 1.5 0 0 0 1.5-1.5V7h1.5A1.5 1.5 0 0 1 20 8.5v11a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 4 19.5v-11z",fill:"currentColor",opacity:"0.5"})}),T$r={slack:_$r,discord:C$r,telegram:E$r};function MCe({platform:e,className:t}){const n=T$r[e.toLowerCase()]??j$r;return o.jsx(n,{className:t})}const N$r={description:e=>`Manage the ${e} connection for this agent.`,notConfigured:()=>"This platform is not configured on the server.",notConnected:e=>`Publish this agent to ${e}.`,connectLabel:"Connect"},I$r={slack:{description:()=>"Manage the Slack connection for this agent.",notConfigured:()=>"Slack is not configured on the server.",notConnected:()=>"You will be redirected to Slack to choose a workspace and approve permissions.",connectLabel:"Continue with Slack",requireActiveInstallation:!0}};function A$r(e){return{...N$r,...I$r[e]??{}}}function R$r({platform:e,agentId:t,installation:n,onClose:r,onDisconnectRequest:s}){const{connect:a,isConnecting:i}=lCe(e.id,{onClose:r}),l=A$r(e.id),c=l.requireActiveInstallation&&n?.status!=="active"?void 0:n,u=()=>{a(t)};return o.jsxs(o.Fragment,{children:[o.jsxs(wr,{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(MCe,{platform:e.id,className:"h-8 w-8 shrink-0"}),o.jsxs(gr,{children:[e.name," integration"]})]}),o.jsx(Ks,{children:l.description(e.name)})]}),o.jsx($r,{children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:e.isConfigured?c?o.jsxs(o.Fragment,{children:["Connected ",o.jsx("span",{className:"text-neutral6",children:e.name})," to"," ",o.jsx("span",{className:"text-neutral6",children:"Mastra"})]}):l.notConnected(e.name):l.notConfigured(e.name)})}),o.jsx(Nc,{children:e.isConfigured&&c?o.jsx(le,{variant:"default",onClick:s,"data-testid":`publish-channel-dialog-${e.id}-disconnect`,children:"Disconnect"}):e.isConfigured?o.jsx(le,{variant:"default",onClick:u,disabled:i,"data-testid":`publish-channel-dialog-${e.id}-connect`,children:i?"Connecting…":l.connectLabel}):o.jsx(le,{variant:"default",onClick:r,children:"Close"})})]})}function P$r({platform:e,agentId:t,installation:n,open:r,onOpenChange:s,initialView:a="publish"}){const[i,l]=g.useState(a);g.useEffect(()=>{r&&l(a)},[r,a]);const c=()=>s(!1);return o.jsx(br,{open:r,onOpenChange:s,children:o.jsx(xr,{"data-testid":`publish-channel-dialog-${e.id}`,children:i==="publish"?o.jsx(R$r,{platform:e,agentId:t,installation:n,onClose:c,onDisconnectRequest:()=>l("confirm-disconnect")}):o.jsx(O$r,{platform:e,agentId:t,onCancel:()=>l("publish"),onClose:c})})})}function $$r(e){const{canPublishToChannel:t}=o0(),n=Vr(),{updateStoredAgent:r}=O1(e),[s,a]=g.useState(null),[i,l]=g.useState(!1),[c,u]=g.useState(null),d=lCe("slack"),f=g.useCallback(S=>{const{platform:x,installation:k}=S;if(x.id==="slack"&&x.isConfigured&&!k){d.connect(e);return}u(S)},[e,d]),p=g.useCallback((S,x)=>{const k={platform:S,installation:x};if(t){f(k);return}a(k),l(!0)},[t,f]),h=g.useCallback(()=>{l(!1),a(null)},[]),m=g.useCallback(async()=>{if(s)try{await r.mutateAsync({visibility:"public"}),n.setValue("visibility","public",{shouldDirty:!1}),De.success("Agent added to the library");const S=s;l(!1),a(null),f(S)}catch(S){De.error(`Failed to add to library: ${S instanceof Error?S.message:"Unknown error"}`)}},[s,r,n,f]),v=s?.platform.name??"this channel",y=g.useMemo(()=>o.jsx(br,{open:i,onOpenChange:S=>!S&&h(),children:o.jsxs(xr,{"data-testid":"agent-builder-publish-before-connect-dialog",children:[o.jsxs(wr,{children:[o.jsxs(gr,{children:["Add this agent to your library to connect ",v,"?"]}),o.jsxs(Ks,{children:["Connecting to ",v," requires this agent to be in the library so your teammates can use the bot. We'll add it to the library and then continue to ",v,"."]})]}),o.jsxs(Nc,{children:[o.jsx(le,{variant:"ghost",onClick:h,disabled:r.isPending,"data-testid":"agent-builder-publish-before-connect-dialog-cancel",children:"Cancel"}),o.jsx(le,{variant:"default",onClick:m,disabled:r.isPending,"data-testid":"agent-builder-publish-before-connect-dialog-confirm",children:"Add to library & continue"})]})]})}),[i,h,m,v,r.isPending]),b=c?o.jsx(P$r,{platform:c.platform,agentId:e,installation:c.installation,open:!0,onOpenChange:S=>{S||u(null)}}):null;return{requestPublishAndConnect:p,dialog:y,channelDialog:b}}const M$r={slack:"Creates a Slack bot powered by this agent."},EPt=({agentId:e,editable:t=!0})=>{const{data:n=[],isLoading:r}=HW(),{canPublishToChannel:s}=o0(),{requestPublishAndConnect:a,dialog:i,channelDialog:l}=$$r(e);return r?o.jsx("div",{className:"flex justify-center px-6 py-8","data-testid":"integrations-detail-picker-loading",children:o.jsxs("div",{className:"flex w-full max-w-[48rem] flex-col items-center gap-6 text-center",children:[o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx(xt,{className:"h-6 w-48"}),o.jsx(xt,{className:"h-4 w-80"})]}),o.jsxs("div",{className:"flex flex-wrap items-stretch justify-center gap-4",children:[o.jsxs("div",{className:"flex w-48 flex-col items-center gap-3 rounded-xl border border-border1 bg-surface3 px-4 py-6",children:[o.jsx(xt,{className:"size-14 rounded-xl"}),o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsx(xt,{className:"h-4 w-24"}),o.jsx(xt,{className:"h-3 w-32"})]}),o.jsx(xt,{className:"h-badge-default w-20 rounded-full"})]}),o.jsxs("div",{className:"flex w-48 flex-col items-center gap-3 rounded-xl border border-border1 bg-surface3 px-4 py-6",children:[o.jsx(xt,{className:"size-14 rounded-xl"}),o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsx(xt,{className:"h-4 w-24"}),o.jsx(xt,{className:"h-3 w-32"})]}),o.jsx(xt,{className:"h-badge-default w-20 rounded-full"})]})]})]})}):n.length===0?o.jsx("div",{className:"flex justify-center px-6 py-8","data-testid":"integrations-detail-picker",children:o.jsx(ye,{variant:"ui-md",className:"text-neutral3",children:"No integrations configured for this project"})}):o.jsxs("div",{className:"flex justify-center px-6 py-8","data-testid":"integrations-detail-picker",children:[o.jsxs("div",{className:"flex w-full max-w-[48rem] flex-col items-center gap-6 text-center",children:[o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx(ye,{variant:"header-sm",className:"font-semibold text-neutral6",children:"Channel integrations"}),o.jsx(ye,{variant:"ui-md",className:"text-neutral3",children:"Publish this agent to external platforms. Each connection installs a bot in the platform that runs this agent."})]}),o.jsx("div",{className:"flex flex-wrap items-stretch justify-center gap-4",children:n.map(c=>o.jsx(D$r,{platform:c,agentId:e,disabled:!t,requiresLibrary:!s,onSelect:u=>a(c,u)},c.id))})]}),i,l]})},D$r=({platform:e,agentId:t,disabled:n,requiresLibrary:r,onSelect:s})=>{const{data:a=[]}=HRt(e.id,t),i=a.find(u=>u.status==="active"),l=M$r[e.id],c=e.isConfigured&&r;return o.jsxs("button",{type:"button",onClick:()=>s(i),disabled:n,"data-testid":`integration-card-${e.id}`,className:"flex w-48 flex-col items-center gap-3 rounded-xl border border-border1 bg-surface3 px-4 py-6 text-center transition-colors hover:bg-surface4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent1 disabled:cursor-not-allowed disabled:opacity-60",children:[o.jsx("div",{className:"grid size-14 place-items-center rounded-xl bg-surface4",children:o.jsx(MCe,{platform:e.id,className:"h-7 w-7"})}),o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsx(ye,{variant:"ui-md",className:"font-semibold text-neutral6",children:e.name}),l?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:l}):null]}),e.isConfigured?i?o.jsx(bg,{variant:"success",size:"sm",withDot:!0,children:"Connected"}):o.jsx(bg,{variant:"neutral",size:"sm",withDot:!0,children:"Not connected"}):o.jsx(bg,{variant:"warning",size:"sm",withDot:!0,children:"Not configured"}),c?o.jsx(bg,{variant:"warning",size:"sm",withDot:!0,children:"Add to library to connect"}):null]})},L$r=X("group/input-group relative flex w-full flex-1 items-center","border border-border1 text-neutral6",vs.all,"has-[:disabled]:cursor-not-allowed has-[:disabled]:opacity-50","has-[[aria-invalid=true]]:border-error","has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col","has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col","has-[textarea]:h-auto","has-[>[data-align=inline-start]]:[&>[data-slot=input-group-control]]:pl-0","has-[>[data-align=inline-end]]:[&>[data-slot=input-group-control]]:pr-0","has-[>[data-align=block-start]]:[&>[data-slot=input-group-control]]:w-full has-[>[data-align=block-start]]:[&>[data-slot=input-group-control]]:flex-none","has-[>[data-align=block-end]]:[&>[data-slot=input-group-control]]:w-full has-[>[data-align=block-end]]:[&>[data-slot=input-group-control]]:flex-none"),jPt=X("has-[>[data-align=block-start]]:rounded-xl","has-[>[data-align=block-end]]:rounded-xl","has-[textarea]:rounded-xl"),DZe=X("rounded-full bg-surface-overlay-soft","hover:bg-surface-overlay-strong",umt,"outline-hidden focus-within:bg-surface-overlay-strong focus-within:outline-hidden",lmt,jPt),F$r=uo(L$r,{variants:{variant:{default:DZe,filled:DZe,outline:X("rounded-full bg-transparent",umt,"outline-hidden focus-within:outline-hidden",lmt,jPt)}},defaultVariants:{variant:"default"}}),Pu=g.forwardRef(({className:e,size:t="md",variant:n,...r},s)=>o.jsx("div",{ref:s,role:"group","data-slot":"input-group","data-size":t,className:X(F$r({variant:n}),O2[t],e),...r}));Pu.displayName="InputGroup";const z$r=uo(X("flex items-center justify-center gap-2 text-neutral3 select-none","group-has-[:disabled]/input-group:opacity-50","[&>svg:not([class*='size-'])]:size-4"),{variants:{align:{"inline-start":"order-first pr-1 pl-3 has-[>button]:pl-1","inline-end":"order-last pr-3 pl-1 has-[>button]:pr-1","block-start":"order-first w-full justify-start border-b border-border1 px-3 pt-2 pb-1","block-end":"order-last w-full justify-start border-t border-border1 px-3 pt-1 pb-2"}},defaultVariants:{align:"inline-start"}}),Xc=g.forwardRef(({className:e,align:t="inline-start",onClick:n,...r},s)=>o.jsx("div",{ref:s,role:"group","data-slot":"input-group-addon","data-align":t,className:X(z$r({align:t}),e),onClick:a=>{a.target.closest('button, input, textarea, [role="button"]')||a.currentTarget.parentElement?.querySelector("[data-slot=input-group-control]")?.focus(),n?.(a)},...r}));Xc.displayName="InputGroupAddon";const B$r=X("group-data-[size=xs]/input-group:h-form-xs","group-data-[size=sm]/input-group:h-form-sm","group-data-[size=md]/input-group:h-form-md","group-data-[size=default]/input-group:h-form-default","group-data-[size=lg]/input-group:h-form-lg"),TPt=X("group-data-[size=xs]/input-group:text-ui-xs","group-data-[size=sm]/input-group:text-ui-sm","group-data-[size=md]/input-group:text-ui-md","group-data-[size=default]/input-group:text-ui-md","group-data-[size=lg]/input-group:text-ui-lg"),$u=g.forwardRef(({className:e,testId:t,error:n,type:r="text",...s},a)=>o.jsx("input",{ref:a,type:r,"data-slot":"input-group-control","data-testid":t,"aria-invalid":n,className:X("min-w-0 flex-1 bg-transparent px-3 text-neutral6 outline-hidden",B$r,TPt,"placeholder:duration-normal placeholder:text-neutral2 placeholder:transition-opacity","focus:placeholder:opacity-70","disabled:cursor-not-allowed","[&::-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",e),...s}));$u.displayName="InputGroupInput";const U$r=g.forwardRef(({className:e,testId:t,error:n,...r},s)=>o.jsx("textarea",{ref:s,"data-slot":"input-group-control","data-testid":t,"aria-invalid":n,className:X("min-h-15 min-w-0 flex-1 resize-y bg-transparent px-3 py-2 text-neutral6 outline-hidden",TPt,"placeholder:duration-normal placeholder:text-neutral2 placeholder:transition-opacity","focus:placeholder:opacity-70","disabled:cursor-not-allowed",e),...r}));U$r.displayName="InputGroupTextarea";const V$r=g.forwardRef(({className:e,...t},n)=>o.jsx("span",{ref:n,className:X("flex items-center gap-2 text-ui-sm text-neutral3 [&_svg]:pointer-events-none","[&_svg:not([class*='size-'])]:size-4",e),...t}));V$r.displayName="InputGroupText";const NPt=g.forwardRef(({size:e="icon-sm",variant:t="ghost",type:n="button",...r},s)=>o.jsx(le,{ref:s,type:n,size:e,variant:t,...r}));NPt.displayName="InputGroupButton";const IPt=({title:e,subtitle:t,icon:n,isSelected:r,disabled:s=!1,onClick:a,ariaLabel:i,testId:l,checkTestId:c,footer:u})=>{const d=s0(),f={"--agent-color-bg":d.background,...r?{borderColor:d.background}:null},p=r?{borderColor:d.background,backgroundColor:d.background,color:d.foreground}:void 0;return o.jsxs("div",{"data-testid":l,style:f,className:X("flex w-full flex-col gap-2 rounded-lg border bg-surface3 p-4 transition-colors","focus-visible:!border-[var(--agent-color-bg)] focus-within:!border-[var(--agent-color-bg)]",r?"bg-surface4":"border-border1",s&&"opacity-60"),children:[o.jsxs("button",{type:"button",onClick:a,disabled:s,"aria-pressed":r,"aria-label":i,className:X("flex w-full items-center gap-3 text-left outline-none",!s&&"cursor-pointer hover:opacity-90 active:opacity-80",s&&"cursor-not-allowed"),children:[n,o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[o.jsx(ye,{variant:"ui-md",className:"truncate font-medium text-neutral6",children:e}),t&&o.jsx(ye,{variant:"ui-sm",className:"truncate text-neutral3",children:t})]}),o.jsx("span",{"aria-hidden":"true","data-testid":c,style:p,className:X("flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors",!r&&"border-border1 bg-transparent"),children:r&&o.jsx(pa,{className:"h-3 w-3"})})]}),u]})},q$r=({title:e,items:t,isChecked:n,onToggle:r,onSelectAll:s,onClearAll:a,disabled:i=!1,testIdPrefix:l})=>{const c=s0(),[u,d]=g.useState(""),f=g.useMemo(()=>{const p=u.trim().toLowerCase();return p?t.filter(h=>h.label.toLowerCase().includes(p)):t},[t,u]);return o.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border1 py-6 px-6","data-testid":`${l}-filter`,children:[o.jsx("div",{className:"shrink-0 rounded-full bg-surface3","data-testid":`${l}-filter-search`,children:o.jsxs(Pu,{variant:"outline",size:"lg",children:[o.jsx(Xc,{align:"inline-start",children:o.jsx(Ka,{})}),o.jsx($u,{type:"search","aria-label":`Filter ${e.toLowerCase()}`,placeholder:`Filter ${e.toLowerCase()}...`,onChange:p=>d(p.target.value)})]})}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2 text-ui-xs",children:[o.jsx("button",{type:"button",onClick:s,disabled:i,"data-testid":`${l}-filter-select-all`,className:"text-neutral3 transition-colors hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-60",children:"Select all"}),o.jsx("span",{className:"text-neutral2","aria-hidden":!0,children:"·"}),o.jsx("button",{type:"button",onClick:a,disabled:i,"data-testid":`${l}-filter-clear-all`,className:"text-neutral3 transition-colors hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-60",children:"Clear all"})]}),o.jsx(Br,{className:"min-h-0 flex-1",viewPortClassName:"pr-2",children:f.length===0?o.jsx(ye,{variant:"ui-xs",className:"px-1 py-2 text-neutral3",children:"No matches"}):o.jsx("ul",{className:"flex flex-col gap-0.5",children:f.map(p=>{const h=n(p.id),m=h?{backgroundColor:c.background,borderColor:c.background,color:c.foreground}:void 0;return o.jsx("li",{children:o.jsxs("label",{"data-testid":`${l}-filter-item-${p.id}`,"data-checked":h?"true":"false",className:X("flex cursor-pointer select-none items-center gap-2 rounded-md px-2 py-1.5 text-ui-sm text-neutral6 transition-colors hover:bg-surface4",i&&"cursor-not-allowed opacity-60"),children:[o.jsx(Bo,{checked:h,disabled:i,onCheckedChange:()=>r(p.id),style:m,"data-testid":`${l}-filter-checkbox-${p.id}`,className:"h-3.5 w-3.5 shrink-0 shadow-none [&_svg]:h-2.5 [&_svg]:w-2.5 data-[state=checked]:shadow-none"}),p.icon&&o.jsx("span",{className:"flex shrink-0 items-center",children:p.icon}),o.jsx("span",{className:"truncate",children:p.label})]})},p.id)})})})]})},APt=({testId:e})=>o.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:o.jsxs("div",{className:"grid h-full min-h-0 grid-cols-[280px_minmax(0,1fr)] overflow-hidden","data-testid":e,children:[o.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border1 py-6 px-6",children:[o.jsx(xt,{className:"h-10 w-full rounded-md"}),o.jsx(xt,{className:"h-4 w-28"}),o.jsx(xt,{className:"h-7 w-full rounded-md"}),o.jsx(xt,{className:"h-7 w-full rounded-md"}),o.jsx(xt,{className:"h-7 w-full rounded-md"}),o.jsx(xt,{className:"h-7 w-full rounded-md"})]}),o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-6 px-6 py-6",children:[o.jsx("div",{className:"shrink-0 max-w-[30ch]",children:o.jsx(xt,{className:"h-10 w-full rounded-md"})}),o.jsx("div",{className:"flex min-h-0 flex-col gap-6 overflow-y-auto",children:o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsx(xt,{className:"h-4 w-24"}),o.jsxs("div",{className:"grid grid-cols-1 content-start gap-2 lg:gap-6 sm:grid-cols-2 2xl:grid-cols-3",children:[o.jsx(xt,{className:"h-20 rounded-lg"}),o.jsx(xt,{className:"h-20 rounded-lg"}),o.jsx(xt,{className:"h-20 rounded-lg"}),o.jsx(xt,{className:"h-20 rounded-lg"}),o.jsx(xt,{className:"h-20 rounded-lg"}),o.jsx(xt,{className:"h-20 rounded-lg"})]})]})})]})]})}),RPt=({editable:e=!0})=>{const t=Wx();if(t.active&&t.pickerVisible===!1){const r=t.default?.provider,s=t.default?.modelId;return o.jsx("div",{className:"px-6 py-6",children:o.jsx(G$r,{provider:r,modelId:s})})}return o.jsx("div",{className:"h-full min-h-0 overflow-hidden","data-testid":"model-detail-picker",children:o.jsx(H$r,{disabled:!e})})},H$r=({disabled:e=!1})=>{const{setValue:t,control:n}=Vr(),r=Mn({control:n,name:"model"}),s=Wx(),{models:a,isLoading:i}=Y1(),[l,c]=g.useState(""),[u,d]=g.useState(null),f=g.useMemo(()=>{const j=new Map;for(const T of a){const I=pi(T.provider);j.has(I)||j.set(I,T.providerName)}return Array.from(j.entries()).map(([T,I])=>({providerId:T,providerName:I})).sort((T,I)=>T.providerName.localeCompare(I.providerName))},[a]),p=j=>u===null||u.has(j),h=j=>{d(T=>{const I=T??new Set(f.map(R=>R.providerId)),A=new Set(I);return A.has(j)?A.delete(j):A.add(j),A})},m=()=>{d(new Set(f.map(j=>j.providerId)))},v=()=>{d(new Set)},y=g.useMemo(()=>f.map(({providerId:j,providerName:T})=>({id:j,label:T,icon:o.jsx(II,{providerId:j,size:18})})),[f]);if(i)return o.jsx(APt,{testId:"model-card-picker-loading"});const b=pi(r?.provider??""),S=r?.name??"",x=!!(b&&S),k=a.some(j=>pi(j.provider)===b&&j.model===S),_=x&&s.active&&!k,C=Q$r(a,u,l,b),E=u!==null&&u.size===0;return o.jsxs("div",{className:"h-full min-h-0 overflow-hidden",children:[o.jsxs("div",{className:"grid h-full min-h-0 grid-cols-[280px_minmax(0,1fr)] overflow-hidden","data-testid":"model-card-picker",children:[f.length>0&&o.jsx(q$r,{title:"Providers",items:y,isChecked:p,onToggle:h,onSelectAll:m,onClearAll:v,disabled:e,testIdPrefix:"models-provider"}),o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-6 px-6 py-6",children:[o.jsx("div",{"data-testid":"model-card-picker-search",className:"shrink-0 max-w-[30ch] rounded-full bg-surface3",children:o.jsxs(Pu,{variant:"outline",size:"lg",children:[o.jsx(Xc,{align:"inline-start",children:o.jsx(Ka,{})}),o.jsx($u,{type:"search","aria-label":"Search models",placeholder:"Search models or providers...",onChange:j=>c(j.target.value)})]})}),C.length===0?o.jsx("div",{className:"flex min-h-0 items-center justify-center",children:o.jsx(ye,{variant:"ui-md",className:"text-neutral3",children:l.trim()?`No models match "${l.trim()}"`:E?"Select at least one provider to see models":"No models available"})}):o.jsx(W$r,{groups:C,selectedProvider:b,selectedModel:S,disabled:e,onChange:(j,T)=>t("model",{provider:j,name:T},{shouldDirty:!0})})]})]}),_&&o.jsx(Z$r,{provider:b,modelId:S})]})},W$r=({groups:e,selectedProvider:t,selectedModel:n,disabled:r,onChange:s})=>o.jsx("div",{className:"flex min-h-0 flex-col gap-6 overflow-y-auto",children:e.map(a=>o.jsxs("section",{"data-testid":`model-provider-section-${a.providerId}`,className:"flex flex-col gap-3",children:[o.jsx(ye,{variant:"ui-sm",as:"h3",className:"text-neutral3 uppercase tracking-wide","data-testid":`model-provider-section-title-${a.providerId}`,children:a.providerName}),o.jsx("div",{className:"grid grid-cols-1 content-start gap-2 lg:gap-6 sm:grid-cols-2 2xl:grid-cols-3",children:a.models.map(i=>{const c=pi(i.provider)===t&&i.model===n;return o.jsx(IPt,{icon:o.jsx(II,{providerId:i.provider,size:32}),title:i.model,subtitle:i.providerName,isSelected:c,disabled:r,onClick:()=>s(i.provider,i.model),testId:`model-card-${i.provider}-${i.model}`,checkTestId:`model-card-check-${i.provider}-${i.model}`},`${i.provider}__${i.model}`)})})]},a.providerId))}),Z$r=({provider:e,modelId:t})=>o.jsxs("div",{className:"mx-6 mb-6 flex items-start gap-2 rounded-md border border-accent6 bg-accent6Dark/40 px-3 py-2 text-accent6","data-testid":"model-detail-stale-warning",role:"alert",children:[o.jsx(yf,{className:"h-4 w-4 shrink-0 mt-0.5"}),o.jsxs(ye,{variant:"ui-xs",children:[o.jsxs("span",{className:"font-medium",children:[e,"/",t]})," ","is no longer allowed by the admin policy. Pick a different model to save changes."]})]}),G$r=({provider:e,modelId:t})=>o.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border1 bg-surface3 px-3 py-2","data-testid":"model-detail-locked-chip",children:[o.jsx(Cf,{className:"h-4 w-4 shrink-0 text-neutral3"}),o.jsx(ye,{variant:"ui-sm",className:"font-medium text-neutral6 truncate",children:e&&t?`${e}/${t}`:"Locked by admin"}),o.jsx(ye,{variant:"ui-xs",className:"ml-auto shrink-0 text-neutral3",children:"Set by admin"})]});function Q$r(e,t,n,r){const s=n.toLowerCase(),a=e.filter(l=>{const c=pi(l.provider);return t!==null&&!t.has(c)?!1:!!(!s||l.provider.toLowerCase().includes(s)||l.model.toLowerCase().includes(s))}),i=new Map;for(const l of a){const c=pi(l.provider);let u=i.get(c);u||(u={providerId:c,providerName:l.providerName,models:[]},i.set(c,u)),u.models.push(l)}for(const l of i.values())l.models.sort((c,u)=>c.model.localeCompare(u.model));return Array.from(i.values()).sort((l,c)=>{const u=l.providerId===r?0:1,d=c.providerId===r?0:1;return u!==d?u-d:l.providerName.localeCompare(c.providerName)})}const PPt=({editable:e=!0,availableSkills:t=[]})=>{const{setValue:n,getValues:r,watch:s}=Vr(),a=s("skills")??{},i=(l,c)=>{const u=r("skills")??{};n("skills",{...u,[l]:c},{shouldDirty:!0})};return o.jsx("div",{className:"h-full min-h-0 overflow-y-auto py-2",children:t.length===0?o.jsx(K$r,{}):o.jsx("ul",{className:"flex flex-col",children:t.map(l=>{const c=!!a[l.id];return o.jsx("li",{children:o.jsx(Y$r,{skill:l,editable:e,onToggle:i,isChecked:c})},l.id)})})})},Y$r=({skill:e,editable:t,onToggle:n,isChecked:r})=>o.jsxs("label",{className:"flex cursor-pointer items-start gap-3 px-6 py-4 transition-colors hover:bg-surface2","aria-disabled":!t,children:[o.jsx("div",{className:"mt-0.5",children:o.jsx(Bo,{checked:r,onCheckedChange:s=>n(e.id,s===!0),disabled:!t})}),o.jsxs("div",{className:"flex min-w-0 flex-col",children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium text-neutral6",children:e.name}),e.description&&o.jsx(ye,{variant:"ui-xs",className:"mt-0.5 truncate text-neutral3",title:e.description,children:e.description})]})]}),K$r=()=>o.jsx("div",{className:"flex items-center justify-center py-12",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"No skills available in this project."})}),X$r=({item:e,editable:t,onToggle:n})=>{const r=e.type==="integration"&&!!e.providerId&&!!e.toolkit,s=r&&e.hasConnection===!1,a=e.connectionLabels??[],i=r&&!s&&a.length>0;return o.jsx(IPt,{title:e.name,subtitle:e.description||"No description provided",isSelected:e.isChecked,disabled:!t,onClick:()=>n(e,!e.isChecked),ariaLabel:e.name,testId:`tool-card-${e.type}-${e.id}`,checkTestId:`tool-card-check-${e.type}-${e.id}`,footer:r?s?o.jsx(ye,{variant:"ui-xs",className:"flex h-7 items-center text-neutral3","data-testid":`tool-card-requires-connection-${e.type}-${e.id}`,children:"Requires connection"}):i?o.jsx("div",{className:"flex min-h-7 flex-wrap items-center gap-2","data-testid":`tool-card-connections-${e.type}-${e.id}`,children:a.map(l=>o.jsx(un,{className:"h-auto py-0.5 text-[10px]",children:l},l))}):o.jsx("div",{className:"h-7"}):void 0})},J$r=({tools:e,editable:t,onlySelected:n,onOnlySelectedChange:r,onSearch:s,emptyStateDetails:a,onToggle:i})=>{const l=s0(),c=n?{backgroundColor:l.background,borderColor:l.background,color:l.foreground}:void 0;return o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-6 px-6 py-6",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-4",children:[o.jsx("div",{"data-testid":"tools-card-picker-search",className:"max-w-[30ch] flex-1 rounded-full bg-surface3",children:o.jsxs(Pu,{variant:"outline",size:"lg",children:[o.jsx(Xc,{align:"inline-start",children:o.jsx(Ka,{})}),o.jsx($u,{type:"search","aria-label":"Search tools",placeholder:"Search tools...",onChange:u=>s(u.target.value)})]})}),o.jsxs("label",{"data-testid":"tools-only-selected-filter",className:X("inline-flex items-center gap-2 text-ui-xs text-neutral3 select-none cursor-pointer",!t&&"cursor-not-allowed opacity-60"),children:[o.jsx(Bo,{checked:n,onCheckedChange:u=>r(u===!0),disabled:!t,"data-testid":"tools-only-selected-filter-checkbox",style:c,className:"h-3 w-3 shadow-none [&_svg]:h-2.5 [&_svg]:w-2.5 data-[state=checked]:shadow-none"}),o.jsx("span",{children:"Show only selected"})]})]}),e.length===0?o.jsx($Pt,{details:a}):o.jsx("div",{className:"grid min-h-0 grid-cols-1 content-start gap-2 lg:gap-6 overflow-y-auto sm:grid-cols-2 2xl:grid-cols-3",children:e.map(u=>o.jsx(X$r,{item:u,editable:t,onToggle:i},`${u.type}__${u.id}`))})]})},$Pt=({details:e})=>o.jsx("div",{className:"flex min-h-0 items-center justify-center px-3 py-6",children:o.jsx(ye,{variant:"ui-md",className:"text-neutral3",children:e})}),MPt="__built-in__",eMr=e=>{const t=PI(),n=t.data?.providers;return g.useMemo(()=>{const r=new Map;let s=!1;for(const c of e)if(c.type==="integration"&&c.providerId&&c.toolkit){const u=r.get(c.providerId)??new Set;u.add(c.toolkit),r.set(c.providerId,u)}else s=!0;const a=s?[{id:MPt,label:"Built-in"}]:[],i=(n??[]).filter(c=>r.has(c.id)).map(c=>({providerId:c.id,providerName:c.name,presentSlugs:Array.from(r.get(c.id)??new Set)})),l=[...a.map(c=>c.id),...i.flatMap(c=>c.presentSlugs)];return{builtIn:a,providers:i,allToolkitIds:l,isProvidersLoading:t.isLoading}},[e,n,t.isLoading])},tMr=e=>e.type==="integration"&&e.toolkit?e.toolkit:MPt;function nMr(e,t,n,r){const s=t.trim().toLowerCase();return e.filter(a=>r!==null&&!r.has(tMr(a))||n&&!a.isChecked?!1:s?a.name.toLowerCase().includes(s)||(a.description?.toLowerCase().includes(s)??!1):!0)}function rMr(e){const t=e.search.trim();return e.allToolkitsUnchecked?"Select at least one toolkit to see tools":e.onlySelected&&t===""?"No tools selected yet":e.onlySelected?o.jsxs(o.Fragment,{children:["No selected tools match ",t]}):o.jsxs(o.Fragment,{children:["No tools match ",o.jsx("strong",{children:t})]})}const XW=e=>{const t=We();return yt({queryKey:["tool-provider-toolkits",e],queryFn:()=>t.getToolProvider(e).listToolkits(),enabled:!!e})},DPt=()=>{const e=We(),t=Ur();return Rn({mutationFn:async({providerId:n,connectionId:r,force:s})=>e.getToolProvider(n).disconnectConnection(r,s?{force:s}:void 0),onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["tool-integration-connections",r.providerId]})}})},LPt=e=>e.split(/[-_\s]+/).filter(Boolean).map(t=>`${t.charAt(0).toUpperCase()}${t.slice(1)}`).join(" "),sMr=()=>{const e=We(),t=Ur();return Rn({mutationFn:async({providerId:n,connectionId:r,label:s})=>e.getToolProvider(n).updateConnection(r,{label:s}),onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["tool-integration-connections",r.providerId]}),t.invalidateQueries({queryKey:["tool-integration-connections-all",r.providerId]})}})},aMr=400,LZe=e=>{const t=e.trim();return t.length>0?t:null},iMr=({providerId:e,connectionId:t,initialLabel:n})=>{const r=sMr(),s=g.useRef(LZe(n)),a=My(l=>{l!==s.current&&r.mutate({providerId:e,connectionId:t,label:l},{onSuccess:()=>{s.current=l,De.success("Connection renamed")}})},aMr);return g.useEffect(()=>()=>{a.flush()},[a]),{scheduleRename:l=>{const c=LZe(l);if(c===s.current){a.cancel();return}a(c)},isPending:r.isPending,error:r.error}},oMr=({providerId:e,connectionId:t,initialLabel:n,iconUrl:r,disabled:s,testIdPrefix:a,showBack:i,onBack:l,onDisconnected:c})=>{const u=iMr({providerId:e,connectionId:t,initialLabel:n}),d=DPt(),[f,p]=g.useState(n),[h,m]=g.useState(!1),v=LPt(e),y=()=>{d.mutate({providerId:e,connectionId:t,force:!0},{onSuccess:()=>{De.success("Connection disconnected"),c(t)}})};return o.jsxs(o.Fragment,{children:[o.jsxs($r,{className:"flex flex-col gap-3",children:[i&&o.jsxs(le,{type:"button",variant:"ghost",size:"sm",onClick:l,"aria-label":"Back to connections","data-testid":`${a}-back`,className:"-mt-1 -ml-1.5 w-fit text-neutral3",children:[o.jsx(qe,{children:o.jsx(pdt,{})}),"Connections"]}),o.jsxs("div",{className:"flex flex-col items-center gap-4 text-center",children:[o.jsx("div",{className:"grid size-14 place-items-center overflow-hidden rounded-xl bg-surface4","aria-hidden":!0,children:r?o.jsx("img",{src:r,alt:"",className:"size-8 object-contain"}):o.jsx(qe,{size:"lg",className:"text-neutral3",children:o.jsx(Khn,{})})}),o.jsxs("div",{className:"flex w-full flex-col items-center gap-1.5",children:[o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3",children:[v," connection"]}),o.jsxs("div",{className:"relative w-full",children:[o.jsx(Cn,{id:`${a}-input`,variant:"filled",size:"sm",value:f,onChange:b=>{p(b.target.value),u.scheduleRename(b.target.value)},disabled:s||u.isPending,placeholder:"Unnamed connection",autoFocus:!0,"aria-label":"Connection name",testId:`${a}-input`,className:"text-center"}),u.isPending&&o.jsx("span",{className:"absolute top-1/2 right-2 -translate-y-1/2",children:o.jsx(Kt,{size:"sm","aria-label":"Saving","data-testid":`${a}-saving`})})]}),u.error?o.jsx(ye,{variant:"ui-xs",className:"text-red-500",children:String(u.error)}):null]}),o.jsx(le,{type:"button",variant:"ghost",onClick:()=>m(!0),disabled:s||d.isPending,"data-testid":`${a}-disconnect`,children:"Disconnect"})]})]}),o.jsx(At,{open:h,onOpenChange:m,children:o.jsxs(At.Content,{"data-testid":`${a}-disconnect-dialog`,children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Disconnect connection?"}),o.jsx(At.Description,{children:"Disconnecting revokes this authorized account and removes it from Mastra. Agents using this connection will lose access. This can’t be undone."})]}),d.error?o.jsx(ye,{variant:"ui-xs",className:"text-red-500",children:String(d.error)}):null,o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{"data-testid":`${a}-disconnect-cancel`,disabled:d.isPending,children:"Cancel"}),o.jsx(le,{type:"button",variant:"primary",onClick:y,disabled:s||d.isPending,"data-testid":`${a}-disconnect-confirm`,children:d.isPending?"Disconnecting…":"Disconnect"})]})]})})]})},Df=({children:e,className:t,onClick:n})=>o.jsx("div",{tabIndex:n?0:void 0,onKeyDown:r=>{n&&(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n?.())},className:X("group/entity flex gap-3 rounded-xl border border-border1 bg-surface3 px-4 py-3",n&&"cursor-pointer transition-all hover:bg-surface4",t),onClick:n,children:e}),FPt=({children:e,className:t,style:n})=>o.jsx(qe,{size:"lg",className:X("mt-1 shrink-0 text-neutral3",t),style:n,children:e}),Lf=({children:e,className:t})=>o.jsx(ye,{as:"p",variant:"ui-lg",className:X("font-medium text-neutral6",t),children:e}),th=({children:e,className:t})=>o.jsx(ye,{as:"div",variant:"ui-sm",className:X("text-neutral3",t),children:e}),Ff=({children:e,className:t})=>o.jsx("div",{className:X("w-full flex-1",t),children:e}),lMr=({connections:e,testIdPrefix:t,onSelect:n,onAddConnection:r,addingConnection:s=!1,disabled:a=!1})=>o.jsxs(o.Fragment,{children:[o.jsx($r,{"data-testid":`${t}-list`,children:o.jsx("div",{className:"flex flex-col gap-2",role:"list",children:e.map(i=>o.jsx(Df,{className:"relative items-center rounded-lg px-2 py-2 transition-colors hover:bg-surface4",children:o.jsx(Ff,{className:"min-w-0",children:o.jsxs("button",{type:"button",disabled:a,onClick:()=>n(i.connectionId),"data-testid":`${t}-list-item-${i.connectionId}`,className:"flex w-full items-center justify-between gap-2 text-left outline-none after:absolute after:inset-0 after:rounded-lg focus-visible:after:ring-2 focus-visible:after:ring-accent1",children:[o.jsx(Lf,{className:"truncate",children:i.label?.trim()||"Unnamed connection"}),o.jsx(qe,{className:"shrink-0 text-neutral3",children:o.jsx(ha,{})})]})})},i.connectionId))})}),r&&o.jsx(Nc,{children:o.jsxs(le,{type:"button",variant:"outline",size:"sm",onClick:r,disabled:a||s,"data-testid":`${t}-add`,children:[s?o.jsx(Kt,{size:"sm"}):o.jsx(qe,{children:o.jsx(Zr,{})}),"Add connection"]})})]}),cMr=({open:e,onOpenChange:t,providerId:n,connections:r,disabled:s=!1,testIdPrefix:a,onDisconnected:i,iconUrl:l,onAddConnection:c,addingConnection:u=!1})=>{const[d,f]=g.useState(null),p=d===null,h=r.find(v=>v.connectionId===d)??null,m=v=>{v||f(null),t(v)};return o.jsx(br,{open:e,onOpenChange:m,children:o.jsxs(xr,{"data-testid":`${a}-dialog`,className:"sm:max-w-md",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:p?`${LPt(n)} connections`:"Manage connection"}),o.jsx(Ks,{children:"Rename or disconnect this authorized account."})]}),e&&(p?o.jsx(lMr,{connections:r,testIdPrefix:a,onSelect:f,onAddConnection:c,addingConnection:u,disabled:s}):h&&o.jsx(oMr,{providerId:n,connectionId:h.connectionId,initialLabel:h.label??"",iconUrl:l,disabled:s,testIdPrefix:a,showBack:!0,onBack:()=>f(null),onDisconnected:v=>{i(v),r.length<=1?m(!1):f(null)}},h.connectionId))]})})},uMr=2e3,dMr=5*6e4,zPt=(e={})=>{const t=We(),n=e.pollIntervalMs??uMr,r=e.timeoutMs??dMr,s=e.openPopup??(a=>window.open(a,"_blank","popup,width=600,height=700"));return Rn({mutationFn:async({providerId:a,toolkit:i,connectionId:l,config:c,label:u,scope:d})=>{const f=t.getToolProvider(a),p=l?.trim(),{url:h,authId:m}=await f.authorize({toolkit:i,...p?{connectionId:p}:{},...c?{config:c}:{},...u!==void 0?{label:u}:{},...d?{scope:d}:{}}),v=s(h);if(!v)throw new Error("Popup blocked. Please allow popups for this site.");const y=Date.now();for(;Date.now()-y<r;){await new Promise(S=>setTimeout(S,n));const{status:b}=await f.getAuthStatus(m);if(b==="completed"||b==="failed"){try{v.close()}catch{}return{status:b,connectionId:m}}}try{v.close()}catch{}throw new Error("Authorization timed out")}})},BPt=(e,t,n)=>{const r=We(),s=n?.scopeToSelf??!1,a=Cm(),i=a.data?.id,l=!s||a.isSuccess||iRt(a.error);return yt({queryKey:s?["tool-integration-connections",e,t,i]:["tool-integration-connections",e,t],queryFn:()=>r.getToolProvider(e).listConnections({toolkit:t,...s&&i?{authorId:i}:{}}),enabled:!!e&&!!t&&l})},iye=32,fMr=e=>{const t=e.replace(/[^A-Za-z0-9 _-]+/g,"-").replace(/^[-\s]+|[-\s]+$/g,""),n=t.length>0?t:"connection";return n.length>iye?n.slice(0,iye):n},pMr=e=>{const t=new Set;return e.map(n=>{let r=n.label??"";const s=()=>r.toLocaleLowerCase();let a=2;for(;t.has(s());){const i=` ${a++}`;r=`${r.slice(0,iye-i.length)}${i}`}return t.add(s()),r===n.label?n:{...n,label:r}})},hMr=(e,t)=>e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.connectionId===s.connectionId&&n.toolkit===s.toolkit&&n.scope===s.scope&&(n.label??void 0)===(s.label??void 0)}),mMr=({activeConnections:e,pinned:t,toolkit:n})=>{const r=new Map(t.map(a=>[a.connectionId,a])),s=e.map(a=>{const i=r.get(a.connectionId);return{kind:"author",toolkit:n,connectionId:a.connectionId,scope:i?.scope??"per-author",label:i?.label?.trim()||a.label?.trim()||void 0}});return s.length<2?s:pMr(s.map(a=>({...a,label:a.label||fMr(a.connectionId)})))},gMr=({hasSelectedTool:e,currentPins:t,desiredPins:n,connectionsField:r,setValue:s})=>{g.useEffect(()=>{!e||hMr(t,n)||s(r,n,{shouldDirty:!0})},[e,n,t,r,s])},vMr=({providerId:e,toolkit:t,disabled:n=!1,multipleAllowed:r=!1})=>{const{setValue:s}=Vr(),a=Ur(),i=zPt(),l=BPt(e,t,{scopeToSelf:!0}),[c,u]=g.useState(!1),d=XW(c?e:null),f=g.useMemo(()=>d.data?.data?.find(E=>E.slug===t)?.icon,[d.data?.data,t]),p=g.useMemo(()=>`toolProviders.${e}.connections.${t}`,[e,t]),h=Mn({name:p}),m=g.useMemo(()=>h??[],[h]),v=Mn({name:`toolProviders.${e}`}),y=g.useMemo(()=>Object.values(v?.tools??{}).some(E=>E?.toolkit===t),[v?.tools,t]),b=g.useMemo(()=>(l.data?.items??[]).filter(E=>E.status==="active"),[l.data?.items]),S=g.useMemo(()=>mMr({activeConnections:b,pinned:m,toolkit:t}),[b,m,t]),x=g.useMemo(()=>b.map(E=>({connectionId:E.connectionId,label:E.label})),[b]);gMr({hasSelectedTool:y,currentPins:m,desiredPins:S,connectionsField:p,setValue:s});const k=E=>{m.some(j=>j.connectionId===E)&&s(p,m.filter(j=>j.connectionId!==E),{shouldDirty:!0})},_=()=>{i.mutate({providerId:e,toolkit:t,scope:"per-author"},{onSuccess:()=>{a.invalidateQueries({queryKey:["tool-integration-connections",e,t]}),a.invalidateQueries({queryKey:["tool-integration-connections-all",e,t]})}})},C=`${e}-${t}`;return l.isPending?o.jsx(xt,{className:"h-7 w-20","data-testid":`toolkit-connection-loading-${C}`}):b.length===0?o.jsx(le,{type:"button",variant:"outline",size:"sm",onClick:_,disabled:n||i.isPending,"data-testid":`toolkit-connect-${C}`,children:i.isPending?"Connecting…":"Connect"}):o.jsxs("div",{className:"flex items-center gap-1","data-testid":`toolkit-connection-${C}`,children:[o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"Manage connection","aria-label":`Manage ${t} connection`,onClick:()=>u(!0),disabled:n,"data-testid":`toolkit-manage-${C}`,children:o.jsx(z9,{})}),c&&o.jsx(cMr,{open:!0,onOpenChange:u,providerId:e,connections:x,disabled:n,testIdPrefix:`toolkit-manage-${C}`,onDisconnected:k,iconUrl:f,onAddConnection:r?_:void 0,addingConnection:i.isPending})]})},Vk="tools-toolkit",DCe=g.memo(({item:e,checked:t,disabled:n,onToggle:r,providerId:s,multipleAllowed:a})=>{const i=s0(),l=t?{backgroundColor:i.background,borderColor:i.background,color:i.foreground}:void 0;return o.jsxs("li",{className:"flex items-center gap-1",children:[o.jsxs("label",{"data-testid":`${Vk}-filter-item-${e.id}`,"data-checked":t?"true":"false",className:X("flex min-w-0 flex-1 cursor-pointer select-none items-center gap-2 rounded-md px-2 py-1.5 text-ui-sm text-neutral6 transition-colors hover:bg-surface4",n&&"cursor-not-allowed opacity-60"),children:[o.jsx(Bo,{checked:t,disabled:n,onCheckedChange:()=>r(e.id),style:l,"data-testid":`${Vk}-filter-checkbox-${e.id}`,className:"h-3.5 w-3.5 shrink-0 shadow-none [&_svg]:h-2.5 [&_svg]:w-2.5 data-[state=checked]:shadow-none"}),e.icon&&o.jsx("img",{src:e.icon,alt:"","aria-hidden":!0,"data-testid":`${Vk}-filter-icon-${e.id}`,className:"h-4 w-4 shrink-0 rounded object-contain"}),o.jsx("span",{className:"truncate",children:e.label})]}),s&&o.jsx("div",{className:"shrink-0",children:o.jsx(vMr,{providerId:s,toolkit:e.id,disabled:n,multipleAllowed:a})})]})});DCe.displayName="ToolkitFilterRow";const yMr=({provider:e,term:t,isChecked:n,onToggle:r,disabled:s,multipleAllowed:a})=>{const{data:i,isLoading:l}=XW(e.providerId),c=g.useMemo(()=>{const u=new Map,d=new Map;for(const p of i?.data??[])u.set(p.slug,p.name??p.slug),p.icon&&d.set(p.slug,p.icon);const f=e.presentSlugs.map(p=>({id:p,label:u.get(p)??p,icon:d.get(p)})).sort((p,h)=>p.label.localeCompare(h.label));return t?f.filter(p=>p.label.toLowerCase().includes(t)):f},[i,e.presentSlugs,t]);return l?o.jsxs("div",{className:"flex flex-col gap-1 px-2",children:[o.jsx(xt,{className:"h-4 w-20"}),Array.from({length:Math.min(e.presentSlugs.length,3)}).map((u,d)=>o.jsx(xt,{className:"h-7 w-full"},d))]}):c.length===0?null:o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx(ye,{variant:"ui-xs","data-testid":`tools-provider-section-${e.providerId}`,className:"px-2 pt-1 text-neutral3 uppercase tracking-wide",children:e.providerName}),o.jsx("ul",{className:"flex flex-col gap-0.5",children:c.map(u=>o.jsx(DCe,{item:u,checked:n(u.id),disabled:s,onToggle:r,providerId:e.providerId,multipleAllowed:a},u.id))})]})},bMr=({builtIn:e,providers:t,isProvidersLoading:n,isChecked:r,onToggle:s,onSelectAll:a,onClearAll:i,disabled:l=!1,multipleAllowedByProvider:c})=>{const[u,d]=g.useState(""),f=u.trim().toLowerCase(),p=g.useMemo(()=>f?e.filter(h=>h.label.toLowerCase().includes(f)):e,[e,f]);return o.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border1 py-6 px-6","data-testid":`${Vk}-filter`,children:[o.jsx("div",{className:"shrink-0 rounded-full bg-surface3","data-testid":`${Vk}-filter-search`,children:o.jsxs(Pu,{variant:"outline",size:"lg",children:[o.jsx(Xc,{align:"inline-start",children:o.jsx(Ka,{})}),o.jsx($u,{type:"search","aria-label":"Filter toolkits",placeholder:"Filter toolkits...",onChange:h=>d(h.target.value)})]})}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2 text-ui-xs",children:[o.jsx("button",{type:"button",onClick:a,disabled:l,"data-testid":`${Vk}-filter-select-all`,className:"text-neutral3 transition-colors hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-60",children:"Select all"}),o.jsx("span",{className:"text-neutral2","aria-hidden":!0,children:"·"}),o.jsx("button",{type:"button",onClick:i,disabled:l,"data-testid":`${Vk}-filter-clear-all`,className:"text-neutral3 transition-colors hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-60",children:"Clear all"})]}),o.jsx(Br,{className:"min-h-0 flex-1",viewPortClassName:"pr-2",children:o.jsxs("div",{className:"flex flex-col gap-3",children:[p.length>0&&o.jsx("ul",{className:"flex flex-col gap-0.5",children:p.map(h=>o.jsx(DCe,{item:h,checked:r(h.id),disabled:l,onToggle:s},h.id))}),t.map(h=>o.jsx(yMr,{provider:h,term:f,isChecked:r,onToggle:s,disabled:l,multipleAllowed:c.get(h.providerId)??!1},h.providerId)),n&&o.jsx("div",{className:"flex flex-col gap-1 px-2",children:Array.from({length:3}).map((h,m)=>o.jsx(xt,{className:"h-7 w-full"},m))})]})})]})},xMr=()=>{const{setValue:e,getValues:t}=Vr(),n=g.useCallback((a,i)=>{const l=t("toolProviders")??{},c=l[a]??{tools:{},connections:{}};e("toolProviders",{...l,[a]:i(c)},{shouldDirty:!0})},[t,e]),r=g.useCallback((a,i)=>{if(a.type==="integration"&&a.providerId&&a.toolkit){const u=a.name,d=a.toolkit,f=a.description;n(a.providerId,p=>{const h={...p.tools??{}};return i?h[u]={toolkit:d,...f?{description:f}:{}}:delete h[u],{...p,tools:h,connections:{...p.connections??{}}}});return}const l=a.type==="agent"?"agents":a.type==="workflow"?"workflows":"tools",c=t(l)??{};e(l,{...c,[a.id]:i},{shouldDirty:!0})},[t,e,n]),s=g.useCallback((a,i)=>{if(!a.providerId||!a.toolkit)return;const l=a.toolkit,c=a.name,u=a.description;n(a.providerId,d=>{const f={...d.tools??{}};f[c]||(f[c]={toolkit:l,...u?{description:u}:{}});const p=d.connections?.[l]??[],h=p.some(v=>v.connectionId===i),m={...d.connections??{},[l]:h?p:[...p,{kind:"author",toolkit:l,connectionId:i,scope:"per-author"}]};return{...d,tools:f,connections:m}})},[n]);return{toggle:r,pinConnection:s}},wMr=e=>{const[t,n]=g.useState(null),r=g.useCallback(c=>t===null||t.has(c),[t]),s=g.useCallback(c=>{n(u=>{const d=new Set(u??e);return d.has(c)?d.delete(c):d.add(c),d})},[e]),a=g.useCallback(()=>n(null),[]),i=g.useCallback(()=>n(new Set),[]),l=g.useMemo(()=>t!==null&&t.size===0,[t]);return{selected:t,isChecked:r,toggle:s,selectAll:a,clearAll:i,allUnchecked:l}},UPt=({editable:e=!0,availableAgentTools:t=[]})=>{const[n,r]=g.useState(""),[s,a]=g.useState(!1),{builtIn:i,providers:l,allToolkitIds:c,isProvidersLoading:u}=eMr(t),d=wMr(c),{toggle:f}=xMr(),p=PI(),h=g.useMemo(()=>{const b=new Map;for(const S of p.data?.providers??[])b.set(S.id,S.capabilities?.multipleConnectionsPerToolkit??!1);return b},[p.data?.providers]),{isLoading:m}=S3();if(t.length===0)return m?o.jsx(APt,{testId:"tools-card-picker-loading"}):o.jsx("div",{className:"px-6 py-6","data-testid":"tools-empty-state",children:o.jsx($Pt,{details:"No tools available in this project"})});const v=nMr(t,n,s,d.selected),y=rMr({allToolkitsUnchecked:d.allUnchecked,onlySelected:s,search:n});return o.jsxs("div",{className:"grid h-full min-h-0 grid-cols-[280px_minmax(0,1fr)]","data-testid":"tools-card-picker",children:[(u||c.length>0)&&o.jsx(bMr,{builtIn:i,providers:l,isProvidersLoading:u,isChecked:d.isChecked,onToggle:d.toggle,onSelectAll:d.selectAll,onClearAll:d.clearAll,disabled:!e,multipleAllowedByProvider:h}),o.jsx(J$r,{tools:v,editable:e,onlySelected:s,onOnlySelectedChange:a,onSearch:r,emptyStateDetails:y,onToggle:f})]})},SMr=({agentId:e,availableAgentTools:t,availableSkills:n,disabled:r=!1,fallbackInstructions:s})=>{const i={"--tab-indicator-color":s0().background},{isLoading:l}=S3(),c=ZRt({hasAgentTools:t.length>0||l,hasSkills:n.length>0}),u=c.model,d=c.tools,f=c.skills,p=c.browser,h=c.integrations,m="h-full min-h-0 pb-6 pt-6",v="h-full min-h-0 !py-0",y=!r,b=u?"model":d?"tools":"instructions";return o.jsx("div",{className:"h-full min-h-0 overflow-hidden","data-testid":"agent-profile-tabs",children:o.jsxs(Lc,{defaultTab:b,className:"grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] overflow-hidden",children:[o.jsxs(Dc,{variant:"line",sticky:!0,className:"!bg-surface3 px-6",style:i,children:[u&&o.jsx(Rr,{value:"model",children:"Model"}),d&&o.jsx(Rr,{value:"tools",children:"Tools"}),o.jsx(Rr,{value:"instructions",children:"Instructions"}),f&&o.jsx(Rr,{value:"skills",children:"Skills"}),p&&o.jsx(Rr,{value:"browser",children:"Browser"}),h&&o.jsx(Rr,{value:"integrations",children:"Integrations"})]}),o.jsxs("div",{className:"min-h-0 overflow-y-auto h-full",children:[u&&o.jsx(Xr,{value:"model",className:v,children:o.jsx(RPt,{editable:y})}),d&&o.jsx(Xr,{value:"tools",className:v,children:o.jsx(UPt,{availableAgentTools:t,editable:y})}),o.jsx(Xr,{value:"instructions",className:m,children:o.jsx(QRt,{editable:y,fallbackPrompt:s})}),f&&o.jsx(Xr,{value:"skills",className:m,children:o.jsx(PPt,{availableSkills:n,editable:y})}),p&&o.jsx(Xr,{value:"browser",className:m,children:o.jsx(GRt,{editable:y})}),h&&o.jsx(Xr,{value:"integrations",className:m,children:o.jsx(EPt,{agentId:e,editable:y})})]})]})})},oye=["ready","identity","model","tools","instructions","skills","browser","library","integrations","end"],kMr=({gates:e,includeInitial:t})=>{const n=[];for(const r of oye)switch(r){case"ready":case"identity":case"library":t&&n.push(r);break;case"instructions":case"end":n.push(r);break;default:e[r]&&n.push(r);break}return n},OMr=(e,t)=>{if(t.includes(e))return e;const n=oye.indexOf(e);return oye.slice(n+1).find(r=>t.includes(r))??"end"},VPt=g.createContext(null),_Mr=({initialStep:e="end",hasAgentTools:t=!0,children:n})=>{const{availableSkills:r}=aC(),s=ZRt({hasAgentTools:t,hasSkills:r.length>0}),a=g.useMemo(()=>kMr({gates:s,includeInitial:e==="ready"}),[s,e]),[i,l]=g.useState(()=>a.includes(e)?e:a[0]??"end");g.useEffect(()=>{l(p=>OMr(p,a))},[a]);const c=g.useCallback(()=>{l(p=>{const h=a.indexOf(p);return h===-1?p:a[h+1]??p})},[a]),u=g.useCallback(()=>{l(p=>{const h=a.indexOf(p);return h<=0?p:a[h-1]})},[a]),d=a.length>=2&&a[a.length-2]===i,f=g.useMemo(()=>({step:i,next:c,prev:u,steps:a,isLast:d}),[i,c,u,a,d]);return o.jsx(VPt.Provider,{value:f,children:n})},zf=()=>g.useContext(VPt)??{step:"end",next:()=>{},prev:()=>{},steps:[],isLast:!1},gm=e=>{"startViewTransition"in document?document.startViewTransition(()=>{Ni.flushSync(()=>{e()})}):e()},l0=({children:e,cta:t,title:n,description:r,contentClassName:s,panelClassName:a,panelOverlay:i})=>{const l=s0(),c=fu(),{isLast:u,next:d,prev:f,step:p,steps:h}=zf(),m=Hs(),{id:v}=Sr(),y={backgroundImage:`conic-gradient(from 0deg at 50% 50%, ${l.background}, ${l.foreground}, ${l.background})`},b=u&&v,x=h.indexOf(p)>0?o.jsxs(le,{variant:"ghost",onClick:()=>gm(()=>f()),disabled:c,"data-testid":"agent-builder-step-back",children:[o.jsx(qe,{children:o.jsx(Rc,{})})," ","Back"]}):null;return o.jsxs("div",{className:"relative w-full h-full min-h-0 border border-border1 rounded-3xl overflow-hidden p-4",children:[o.jsx("div",{"aria-hidden":!0,className:X("agent-step-banner pointer-events-none",c&&"agent-step-banner-rotating"),style:y}),o.jsxs("div",{className:X("relative h-full overflow-hidden bg-surface3 rounded-2xl grid min-h-0",n?"grid-rows-[auto_minmax(0,1fr)_auto]":"grid-rows-[minmax(0,1fr)_auto]",a),children:[i,n&&o.jsxs("div",{className:"border-b border-border1 px-6 pt-6 pb-4","data-testid":"agent-step-title-section",children:[o.jsx("h2",{className:"text-3xl font-semibold text-neutral6 pb-1",children:n}),r&&o.jsx("div",{className:"w-1/2 text-neutral3",children:r})]}),o.jsx("div",{className:X("min-h-0 overflow-y-auto",s),"data-testid":"agent-step-content",children:e}),b?o.jsxs("div",{className:"flex justify-center items-center gap-2 shrink-0 border-t border-border1 pt-6 pb-6","data-testid":"agent-step-footer",children:[x,o.jsx(le,{variant:"outline",onClick:()=>gm(()=>d()),disabled:c,children:"See agent configuration"}),o.jsx(le,{variant:"primary",onClick:()=>m(`/agent-builder/agents/${v}/view`,{viewTransition:!0}),disabled:c,children:"Try agent"})]}):o.jsxs("div",{className:"flex justify-center items-center gap-2 shrink-0 border-t border-border1 pt-6 pb-6","data-testid":"agent-step-footer",children:[x,t]})]})]})},CMr=()=>{const{next:e}=zf(),t=Hs(),{id:n}=Sr(),r=g.useRef(null);g.useEffect(()=>{const i=r.current;!i||typeof i.animate!="function"||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches||i.animate([{backgroundPosition:"180% 0",opacity:0},{opacity:1,offset:.12},{opacity:1,offset:.88},{backgroundPosition:"-80% 0",opacity:0}],{duration:2400,delay:120,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",fill:"both"})},[]);const s=()=>{gm(()=>{e()})},a=()=>{t(`/agent-builder/agents/${n}/view`,{viewTransition:!0})};return o.jsx(l0,{panelClassName:"ready-stage",panelOverlay:o.jsx("span",{ref:r,className:"ready-stage-sweep","aria-hidden":"true"}),cta:o.jsxs("div",{className:"relative z-[2] flex items-center justify-center gap-3",children:[o.jsx(le,{variant:"outline",onClick:s,"data-testid":"agent-builder-ready-review",children:"Review my agent"}),o.jsx(le,{variant:"primary",onClick:a,"data-testid":"agent-builder-ready-try",children:"Try my agent"})]}),children:o.jsx("div",{className:"w-full h-full flex flex-col items-center justify-center py-6 px-6 text-center",children:o.jsxs("div",{className:"ready-stage-content flex flex-col items-center gap-4",children:[o.jsx("h2",{className:"text-4xl font-semibold text-neutral6","data-testid":"agent-builder-ready-heading",children:"Your agent is ready"}),o.jsx("p",{className:"text-neutral3 text-lg max-w-md",children:"You can review and fine-tune everything, or jump straight in and try it out."})]})})})},EMr=({avatar:e,details:t})=>{const{next:n}=zf(),r=fu(),s=()=>{gm(()=>{n()})};return o.jsx(l0,{cta:o.jsxs(le,{onClick:s,disabled:r,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsxs("div",{className:"relative w-full h-full flex flex-col items-center justify-center gap-4 py-6 px-6 text-center",children:[e,t]})})},jMr=({agentId:e})=>{const{next:t}=zf(),n=fu(),{requestChange:r,dialog:s}=iCe(e),{control:a}=Vr(),l=Mn({control:a,name:"visibility"})==="public",c=()=>{gm(()=>{t()})};return o.jsx(l0,{title:"Add to your library",description:"Adding your agent to the library makes it visible to everyone in your workspace, so teammates can discover it, try it out, and copy it as a starting point for their own agents.",cta:o.jsxs(le,{onClick:c,disabled:n,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsxs("div",{className:"relative w-full h-full flex flex-col items-center justify-center gap-4 py-6 px-6 text-center","data-testid":"agent-builder-library-step",children:[o.jsx(qe,{size:"lg",className:"text-neutral4",children:o.jsx(f$,{})}),l?o.jsxs("p",{className:"flex items-center gap-2 text-neutral2","data-testid":"agent-builder-library-added",children:[o.jsx(qe,{children:o.jsx(pa,{})}),"Added to your library"]}):o.jsx(le,{variant:"primary",onClick:()=>r("public"),disabled:n,"data-testid":"agent-builder-library-add",children:"Add to library"}),o.jsx("p",{className:"text-neutral3 max-w-md",children:"You can change this at any time from the agent's visibility settings — adding to the library now is optional."}),s]})})},TMr=({provider:e,name:t})=>{const n=pi(e);return o.jsxs(un,{variant:"default",children:[o.jsx(II,{providerId:n,size:16})," ",n,"/",t]})},NMr=()=>{const{next:e}=zf(),t=fu(),n=Mn({name:"model"}),r=()=>{gm(()=>{e()})};return o.jsx(l0,{title:"Available models",description:n?o.jsxs("div",{className:"flex items-center gap-2",children:["Selected model: ",o.jsx(TMr,{provider:n.provider,name:n.name})]}):void 0,contentClassName:"overflow-hidden",cta:o.jsxs(le,{onClick:r,disabled:t,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsx(RPt,{editable:!t})})},IMr=()=>{const{availableAgentTools:e}=o0(),{next:t}=zf(),n=fu(),r=e.filter(a=>a.isChecked).length,s=()=>{gm(()=>{t()})};return o.jsx(l0,{title:"Available tools",description:o.jsxs("div",{className:"flex items-center gap-2",children:["Selected tools:"," ",o.jsx(un,{variant:"default",children:o.jsx("strong",{className:"font-semibold text-neutral6",children:r})})]}),contentClassName:"overflow-hidden",cta:o.jsxs(le,{onClick:s,disabled:n,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsx(UPt,{availableAgentTools:e,editable:!n})})},AMr=()=>{const{next:e}=zf(),t=fu(),n=()=>{gm(()=>{e()})};return o.jsx(l0,{title:"Instructions",cta:o.jsxs(le,{onClick:n,disabled:t,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsx(QRt,{editable:!t})})},RMr=()=>{const{availableSkills:e}=o0(),{next:t}=zf(),n=fu(),r=()=>{gm(()=>{t()})};return o.jsx(l0,{title:"Skills",cta:o.jsxs(le,{onClick:r,disabled:n,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsx(PPt,{availableSkills:e,editable:!n})})},PMr=()=>{const{next:e}=zf(),t=fu(),n=()=>{gm(()=>{e()})};return o.jsx(l0,{title:"Browser",cta:o.jsxs(le,{onClick:n,disabled:t,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsx(GRt,{editable:!t})})},$Mr=()=>{const{agentId:e}=o0(),{next:t}=zf(),n=fu(),r=()=>{gm(()=>{t()})};return o.jsx(l0,{title:"Integrations",cta:o.jsxs(le,{onClick:r,disabled:n,children:["Continue"," ",o.jsx(qe,{children:o.jsx(bm,{})})]}),children:o.jsx(EPt,{agentId:e,editable:!n})})},qPt=({status:e,lastError:t,onRetry:n})=>e==="saving"?o.jsxs("span",{className:"flex items-center gap-1.5 text-ui-sm text-neutral3","data-testid":"agent-builder-autosave-saving",children:[o.jsx(Kt,{size:"sm"}),"Saving…"]}):e==="saved"?o.jsxs("span",{className:"flex items-center gap-1.5 text-ui-sm text-neutral3","data-testid":"agent-builder-autosave-saved",children:[o.jsx(pa,{className:"h-3.5 w-3.5"}),"Saved"]}):e==="error"?o.jsxs("span",{className:"flex items-center gap-1.5 text-ui-sm text-neutral3","data-testid":"agent-builder-autosave-error",children:[o.jsx("span",{title:t?.message,children:"Failed to save"}),o.jsx("button",{type:"button",onClick:n,"data-testid":"agent-builder-autosave-retry",className:"underline underline-offset-2 hover:text-neutral4",children:"Retry"})]}):null,HPt=({className:e,isLoading:t=!1})=>{const{control:n}=Vr(),r=Mn({control:n,name:"name"}),s=r&&r.trim()?r:"Untitled";return o.jsx("div",{className:e,"data-testid":"agent-builder-title",children:o.jsx("div",{className:"flex items-center gap-2 min-w-0",children:o.jsx("span",{className:"block text-ui-md leading-ui-md text-white truncate","data-testid":"agent-builder-title-name",children:t?o.jsx(xt,{className:"inline-block h-4 w-24 align-middle","data-testid":"agent-builder-title-skeleton"}):s})})})},MMr=({isLoading:e,mode:t,onModeToggle:n,modeToggleDisabled:r=!1,rightAside:s,primaryAction:a,mobileExtra:i})=>{const l=t==="test"?"Switch to Edit mode":"Switch to View mode";return o.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-center gap-2 px-4 pt-4 md:px-10",children:[o.jsxs(vwe,{label:"Agent navigation",className:"min-w-0",listClassName:"min-w-0",children:[o.jsx(j$,{as:ti,to:"/agent-builder/agents","data-testid":"agent-builder-back-to-list",children:"Agent list"}),o.jsx(j$,{as:"span",isCurrent:!0,children:o.jsx(HPt,{isLoading:e})})]}),o.jsxs("div",{className:"justify-self-end flex items-center gap-2 shrink-0",children:[s&&o.jsx("div",{className:"shrink-0 mr-1",children:s}),a&&o.jsx("div",{className:"shrink-0 flex",children:a}),i&&o.jsx("div",{className:"shrink-0 lg:hidden",children:i}),t&&n&&o.jsxs(le,{variant:"ghost",size:"sm",onClick:n,disabled:r,className:"hidden lg:inline-flex shrink-0","data-testid":"agent-builder-mode-toggle","aria-label":l,children:[o.jsx(n1,{}),l]})]})]})};function DMr({agentId:e}){const t=Vr(),n=Mn({control:t.control,name:"visibility"}),{requestChange:r,dialog:s}=iCe(e),a=n??"private";return o.jsxs(o.Fragment,{children:[a==="private"?o.jsxs(le,{size:"sm",variant:"default",onClick:()=>r("public"),"data-testid":"agent-builder-visibility-add",children:[o.jsx(Ux,{className:"h-3.5 w-3.5"}),"Add to library"]}):o.jsxs(le,{size:"sm",variant:"ghost",onClick:()=>r("private"),"data-testid":"agent-builder-visibility-remove",children:[o.jsx(Cf,{className:"h-3.5 w-3.5"}),"Remove from library"]}),s]})}const LMr={slack:"Slack"},FMr=e=>e?LMr[e]??e.charAt(0).toUpperCase()+e.slice(1):"channel",WPt=()=>{const[e]=Pi(),t=g.useRef(null),n=e.get("channel_connected"),r=e.get("channel_error"),s=e.get("platform"),a=e.get("team");g.useEffect(()=>{if(n!=="true"&&!r)return;const i=r?`error:${s}:${r}`:`success:${s}:${a}`;if(t.current===i)return;t.current=i;const l=FMr(s);if(n==="true"){const c=a?` workspace "${a}"`:"";De.success(`Connected to ${l}${c}`)}else De.error(`Failed to connect ${l}: ${r}`)},[n,r,s,e,a])},zMr=({topBar:e,chat:t,chatFooter:n,profile:r,variant:s="split",hideMobileChat:a=!1})=>{const i=s==="centered",l=a&&!i;return o.jsxs("div",{className:"h-full grid grid-rows-[auto_1fr]",children:[e,o.jsxs("div",{className:X("flex flex-1 min-h-0 min-w-0 flex-col pt-4 pb-4 md:pb-10",!i&&"lg:grid lg:grid-rows-1 lg:grid-cols-[1fr_2fr]"),children:[o.jsx("div",{className:X("h-full w-full min-w-0 overflow-hidden px-4 md:px-10",i&&"lg:mx-auto lg:max-w-[80ch]",l&&"hidden lg:block"),"data-testid":"agent-builder-panel-chat",style:{viewTransitionName:"agent-builder-chat-panel"},children:o.jsxs("div",{className:"min-h-0 min-w-0 h-full overflow-hidden md:max-w-[80ch] md:mx-auto w-full grid grid-rows-[1fr_auto]",children:[o.jsx("div",{className:"min-h-0 min-w-0 h-full overflow-hidden",children:t}),n?o.jsx("div",{"data-testid":"agent-builder-chat-footer",className:"w-full pt-3 lg:hidden",children:n}):null]})}),!i&&o.jsx("div",{className:X("min-w-0 overflow-hidden","flex-1 px-4 md:px-10","lg:flex-none lg:h-full lg:min-h-0 lg:pl-0 lg:pr-10"),"data-testid":"agent-builder-panel-profile",style:{viewTransitionName:"agent-builder-profile-panel"},children:o.jsx("div",{className:"h-full min-h-0 w-full min-w-0 overflow-hidden",children:r})})]})]})};function BMr(e){if(e&&typeof e=="object"&&"type"in e&&e.type==="id"){const t=e.workspaceId;return typeof t=="string"?t:void 0}}function UMr(e){if(!e)return{};if(Array.isArray(e)){const t={};for(const n of e)Object.assign(t,n.value);return t}return e}function VMr(e){if(!e||Array.isArray(e))return;const t=e.provider,n=e.name;if(typeof t=="string"&&t.length>0&&typeof n=="string"&&n.length>0)return{provider:t,name:n}}function ZPt(e){const t=e?.metadata&&typeof e.metadata=="object"&&"avatarUrl"in e.metadata?e.metadata.avatarUrl:void 0;return{name:e?.name??"",description:e?.description??"",instructions:typeof e?.instructions=="string"?e.instructions:"",tools:Object.fromEntries(Object.keys(e?.tools??{}).map(n=>[n,!0])),agents:Object.fromEntries(Object.keys(e?.agents??{}).map(n=>[n,!0])),workflows:Object.fromEntries(Object.keys(e?.workflows??{}).map(n=>[n,!0])),skills:Object.fromEntries(Object.keys(UMr(e?.skills)).map(n=>[n,!0])),workspaceId:BMr(e?.workspace),browserEnabled:e?.browser!=null,visibility:e?.visibility,avatarUrl:t,model:VMr(e?.model),toolProviders:g$r(e?.toolProviders)}}function qMr(){const{id:e}=Sr();return WPt(),o.jsx(SPr,{agentId:e,children:o.jsx(HMr,{})})}const HMr=()=>{const{agentId:e,storedAgent:t,isReady:n,isOwner:r,canWrite:s}=aC();return n?t?!s||!r?o.jsx(Vu,{to:`/agent-builder/agents/${e}/view`,replace:!0}):o.jsx(WMr,{}):o.jsx(Vu,{to:"/agent-builder/agents",replace:!0}):o.jsx(JMr,{})},WMr=()=>{const{agentId:e,storedAgent:t}=aC(),[n]=g.useState(()=>ZPt(t)),r=q1({defaultValues:n});return o.jsx(M$,{...r,children:o.jsx(lD,{agentId:e,children:o.jsx(ZMr,{})})})},ZMr=()=>{const{agentId:e,storedAgent:t,toolsData:n,agentsData:r,workflowsData:s,isOwner:a,initialUserMessage:i}=aC(),l=Hs(),{control:c}=Vr(),u=Mn({control:c,name:"tools"}),d=Mn({control:c,name:"agents"}),f=Mn({control:c,name:"workflows"}),p=mPt({toolsData:n,agentsData:r,workflowsData:s,selectedTools:u,selectedAgents:d,selectedWorkflows:f,excludeAgentId:e}),{isLoading:h}=S3(),m=a?()=>l(`/agent-builder/agents/${e}/view`,{viewTransition:!0}):void 0;return o.jsx(_Mr,{initialStep:i?"ready":"end",hasAgentTools:p.length>0||h,children:o.jsx(k$r,{storedAgent:t,availableAgentTools:p,onModeToggle:m,children:o.jsx(GMr,{})})})},GMr=()=>{const{step:e}=zf(),t=Mf(),n=e2t(),{control:r}=Vr(),{dirtyFields:s}=u1e({control:r}),a=Mn({control:r,name:"name"})??"",i=Mn({control:r,name:"description"})??"",l=Mn({control:r,name:"instructions"})??"",c=Mn({control:r,name:"model.name"})??"",u=(y,b)=>!!y||b.trim().length>0,d=u(s.name,a)&&u(s.description,i)&&u(s.instructions,l)&&(!t.model||u(s.model?.name,c)),p=e==="ready"&&!(d&&!n)||e==="identity"&&!d,h=p?"centered":"split",m=p,v=e==="identity"&&d&&!n;return o.jsx(zMr,{topBar:o.jsx(YMr,{}),chat:o.jsx(f$r,{}),chatFooter:v?o.jsx(QMr,{}):void 0,profile:m?null:o.jsx(XMr,{}),variant:h,hideMobileChat:e==="end"})},QMr=()=>{const{next:e}=zf(),t=Hs(),{agentId:n}=o0();return o.jsxs("div",{className:"flex flex-col gap-2 lg:hidden","data-testid":"agent-builder-mobile-initial-ctas",children:[o.jsx(le,{variant:"primary",onClick:()=>t(`/agent-builder/agents/${n}/view`,{viewTransition:!0}),"data-testid":"agent-builder-mobile-initial-cta-chat",children:"Chat with my agent"}),o.jsx(le,{variant:"outline",onClick:()=>gm(()=>e()),"data-testid":"agent-builder-mobile-initial-cta-config",children:"See configuration"})]})},YMr=()=>{const{autosave:e,onModeToggle:t}=o0(),n=fu(),{step:r}=zf(),s=r!=="end";return o.jsx(MMr,{isLoading:!1,mode:"build",onModeToggle:s?void 0:t,modeToggleDisabled:n,rightAside:o.jsx(qPt,{status:e.status,lastError:e.lastError,onRetry:e.retry}),mobileExtra:o.jsx(KMr,{})})},KMr=()=>{const{agentId:e}=o0(),t=fu(),{data:n}=dc(),{control:r}=Vr(),s=Mn({control:r,name:"name"})??"";return o.jsx(FRt,{agentId:e,showSetVisibility:!!n?.enabled,showDelete:!0,showViewAgent:!0,agentName:s,disabled:t})},XMr=()=>{const{agentId:e,availableAgentTools:t,availableSkills:n,isOwner:r}=o0(),s=fu(),{data:a}=dc(),{control:i}=Vr(),l=Mn({control:i,name:"name"})??"",{step:c}=zf(),u=o.jsxs("div",{className:"hidden lg:flex items-center gap-2","data-testid":"agent-builder-hero-actions-desktop",children:[a?.enabled&&o.jsx("span",{style:{viewTransitionName:"agent-visibility-select"},children:o.jsx(DMr,{agentId:e})}),r&&o.jsx(xjr,{agentId:e,agentName:l,disabled:s})]});return c==="ready"?o.jsx(CMr,{}):c==="identity"?o.jsx(EMr,{avatar:o.jsx(GWe,{disabled:s}),details:o.jsx(QWe,{mode:"highlighted",disabled:s})}):c==="library"?o.jsx(jMr,{agentId:e}):c==="model"?o.jsx(NMr,{}):c==="tools"?o.jsx(IMr,{}):c==="instructions"?o.jsx(AMr,{}):c==="skills"?o.jsx(RMr,{}):c==="browser"?o.jsx(PMr,{}):c==="integrations"?o.jsx($Mr,{}):o.jsxs(kjr,{children:[o.jsx(Ojr,{avatar:o.jsx(GWe,{disabled:s}),details:o.jsx(QWe,{disabled:s}),actions:u}),o.jsx(SMr,{agentId:e,availableAgentTools:t,availableSkills:n,disabled:s})]})},JMr=()=>o.jsx("div",{className:"h-screen w-screen flex items-center justify-center",children:o.jsx(Kt,{})}),GPt=g.createContext(null);function O3(){const e=g.useContext(GPt);if(!e)throw new Error("useBrowserSession must be used within a BrowserSessionProvider");return e}const QPt=g.createContext(null);function YPt(){const e=g.useContext(QPt);if(!e)throw new Error("useBrowserFrame must be used within a BrowserSessionProvider");return{latestFrame:g.useSyncExternalStore(e.subscribe,e.getSnapshot)}}const eDr=["browser_","stagehand_"];function tDr(e){return eDr.some(t=>e.startsWith(t))}function nDr(e){if(!e||typeof e!="object")return!1;const t=e;return t.success===!1&&typeof t.code=="string"}const LCe=g.createContext(null);function JW({children:e}){const[t,n]=g.useState(new Map),r=g.useCallback(i=>{n(l=>{const c=l.get(i.toolCallId);if(c&&c.result===i.result&&c.status===i.status)return l;const u=new Map(l);return u.set(i.toolCallId,c?{...i,timestamp:c.timestamp}:i),u})},[]),s=g.useMemo(()=>Array.from(t.values()).sort((i,l)=>i.timestamp-l.timestamp),[t]),a=g.useMemo(()=>({toolCalls:s,registerToolCall:r}),[s,r]);return o.jsx(LCe.Provider,{value:a,children:e})}function FCe(){const e=g.useContext(LCe);if(!e)throw new Error("useBrowserToolCalls must be used within a BrowserToolCallsProvider");return e}function rDr(){return g.useContext(LCe)}const FZe={browser_goto:"Go to",browser_click:"Click",browser_type:"Type",browser_scroll:"Scroll",browser_snapshot:"Snapshot",browser_close:"Close",browser_select:"Select",browser_press:"Press",browser_hover:"Hover",browser_back:"Back",browser_dialog:"Dialog",browser_wait:"Wait",browser_tabs:"Tabs",browser_drag:"Drag",browser_evaluate:"Evaluate",stagehand_navigate:"Navigate",stagehand_act:"Act",stagehand_extract:"Extract",stagehand_observe:"Observe",stagehand_close:"Close",stagehand_tabs:"Tabs"},sDr={browser_goto:"url",browser_click:"ref",browser_type:"text",browser_scroll:"direction",browser_close:"reason",browser_select:"value",browser_press:"key",browser_hover:"ref",browser_dialog:"action",browser_wait:"time",browser_tabs:"action",browser_drag:"sourceRef",browser_evaluate:"expression",stagehand_navigate:"url",stagehand_act:"action",stagehand_extract:"instruction",stagehand_observe:"instruction",stagehand_tabs:"action"};function aDr(e){return FZe[e]?FZe[e]:e.replace(/^(browser_|stagehand_)/,"")}function iDr(e,t){const n=sDr[e];if(!n)return null;const r=t[n];if(r==null)return null;const s=String(r);return s.length>50?`${s.slice(0,47)}...`:s}function KPt({entry:e}){const[t,n]=g.useState(!1),r=aDr(e.toolName),s=iDr(e.toolName,e.args),{__mastraMetadata:a,...i}=e.args;return o.jsxs("div",{className:"border-b border-border1 last:border-b-0",children:[o.jsxs("button",{type:"button",onClick:()=>n(l=>!l),"aria-expanded":t,className:"flex items-center gap-2 w-full px-3 py-0.5 text-left hover:bg-surface3 transition-colors",children:[o.jsx(ha,{className:X("h-3 w-3 text-neutral3 transition-transform shrink-0",t&&"rotate-90")}),o.jsx(oDr,{status:e.status}),o.jsx("span",{className:"text-xs font-medium text-neutral6 shrink-0",children:r}),s&&o.jsx("span",{className:"text-xs text-neutral3 truncate",children:s})]}),t&&o.jsxs("div",{className:"px-3 pb-2 space-y-2",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-xs font-medium text-neutral4 pb-1",children:"Arguments"}),o.jsx(Wr,{data:i,"data-testid":"browser-tool-args"})]}),e.result!==void 0&&e.result!==null&&o.jsxs("div",{children:[o.jsx("p",{className:"text-xs font-medium text-neutral4 pb-1",children:"Result"}),typeof e.result=="string"?o.jsx("pre",{className:"whitespace-pre text-xs bg-surface4 p-2 rounded-md overflow-x-auto max-h-40 overflow-y-auto",children:e.result}):o.jsx(Wr,{data:e.result,"data-testid":"browser-tool-result"})]})]})]})}function oDr({status:e}){switch(e){case"pending":return o.jsx(oa,{className:"h-3 w-3 text-neutral4 animate-spin shrink-0"});case"complete":return o.jsx(pa,{className:"h-3 w-3 text-green-500 shrink-0"});case"error":return o.jsx(bs,{className:"h-3 w-3 text-red-500 shrink-0"})}}const lDr=10;function cDr(e){const[t,n]=g.useState([]),r=g.useRef(0),s=g.useRef(e.viewport);g.useEffect(()=>{s.current=e.viewport},[e.viewport]);const a=g.useCallback(i=>{n(l=>l.filter(c=>c.id!==i))},[]);return g.useEffect(()=>{if(!e.enabled||!e.imgRef.current)return;const i=e.imgRef.current;function l(c){if(c.button!==0)return;const u=s.current;if(!u)return;const d=i.getBoundingClientRect(),f=c.clientX-d.left,p=c.clientY-d.top,h=Math.min(d.width/u.width,d.height/u.height),m=u.width*h,v=u.height*h,y=(d.width-m)/2,b=(d.height-v)/2,S=f-y,x=p-b;S<0||x<0||S>m||x>v||n(k=>{if(k.length>=lDr)return k;const _=++r.current;return[...k,{id:_,x:f,y:p}]})}return i.addEventListener("mousedown",l),()=>{i.removeEventListener("mousedown",l)}},[e.enabled,e.imgRef]),{ripples:t,removeRipple:a}}function uDr(){const{toolCalls:e}=FCe();return g.useMemo(()=>{const t=e.filter(s=>s.status==="pending"),n=t.length>0,r=n?t[0].toolName:null;return{isAgentBusy:n,activeToolName:r,pendingCount:t.length}},[e])}const dDr=16,zZe=500;function ZF(e,t,n,r){const s=e-n.left,a=t-n.top,i=Math.min(n.width/r.width,n.height/r.height),l=r.width*i,c=r.height*i,u=(n.width-l)/2,d=(n.height-c)/2,f=s-u,p=a-d;return f<0||p<0||f>l||p>c?null:{x:f/i,y:p/i}}function BZe(e,t,n){let r;switch(t){case 0:r=e;break;case 1:r=e*dDr;break;case 2:r=e*(n??800);break;default:r=e}return Math.max(-zZe,Math.min(zZe,r))}function Sj(e){let t=0;return e.altKey&&(t|=1),e.ctrlKey&&(t|=2),e.metaKey&&(t|=4),e.shiftKey&&(t|=8),t}function fDr(e){return e.length===1}function pDr(e){const t=g.useRef(e.sendMessage),n=g.useRef(e.onEscape);g.useEffect(()=>{t.current=e.sendMessage},[e.sendMessage]),g.useEffect(()=>{n.current=e.onEscape},[e.onEscape]),g.useEffect(()=>{if(!e.enabled)return;function r(l,c,u,d,f){const p={type:"keyboard",eventType:l};c!==void 0&&(p.key=c),u!==void 0&&(p.code=u),d!==void 0&&(p.text=d),f&&(p.modifiers=f),t.current(JSON.stringify(p))}function s(l){if(l.isComposing||l.keyCode===229)return;if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),n.current();return}l.preventDefault(),l.stopPropagation();const c=Sj(l),u=fDr(l.key);r("keyDown",l.key,l.code,void 0,c),u&&r("char",l.key,void 0,l.key,c)}function a(l){l.isComposing||l.keyCode===229||l.key!=="Escape"&&(l.preventDefault(),l.stopPropagation(),r("keyUp",l.key,l.code,void 0,Sj(l)))}function i(l){const c=l.data;if(c)for(const u of c)r("keyDown",u,void 0,void 0,0),r("char",u,void 0,u,0),r("keyUp",u,void 0,void 0,0)}return document.addEventListener("keydown",s,{capture:!0}),document.addEventListener("keyup",a,{capture:!0}),document.addEventListener("compositionend",i),()=>{document.removeEventListener("keydown",s,{capture:!0}),document.removeEventListener("keyup",a,{capture:!0}),document.removeEventListener("compositionend",i)}},[e.enabled])}function hDr(e){const t=g.useRef(e.viewport),n=g.useRef(e.sendMessage);g.useEffect(()=>{t.current=e.viewport},[e.viewport]),g.useEffect(()=>{n.current=e.sendMessage},[e.sendMessage]),g.useEffect(()=>{if(!e.enabled||!e.imgRef.current)return;const r=e.imgRef.current;function s(v,y,b,S,x,k,_,C){const E={type:"mouse",eventType:v,x:y,y:b};S!==void 0&&(E.button=S),x!==void 0&&(E.clickCount=x),k!==void 0&&(E.modifiers=k),_!==void 0&&(E.deltaX=_),C!==void 0&&(E.deltaY=C),n.current(JSON.stringify(E))}function a(v){return v===2?"right":v===1?"middle":"left"}function i(v){const y=t.current;if(!y)return;const b=r.getBoundingClientRect(),S=ZF(v.clientX,v.clientY,b,y);if(!S)return;const x=a(v.button),k=Sj(v);s("mouseMoved",S.x,S.y,void 0,void 0,k),s("mousePressed",S.x,S.y,x,1,k)}function l(v){const y=t.current;if(!y)return;const b=r.getBoundingClientRect(),S=ZF(v.clientX,v.clientY,b,y);if(!S)return;const x=a(v.button);s("mouseReleased",S.x,S.y,x,1,Sj(v))}function c(v){v.preventDefault()}function u(v){v.preventDefault();const y=t.current;if(!y)return;const b=r.getBoundingClientRect(),S=ZF(v.clientX,v.clientY,b,y);if(!S)return;const x=BZe(v.deltaX,v.deltaMode,y.height),k=BZe(v.deltaY,v.deltaMode,y.height);s("mouseWheel",S.x,S.y,void 0,void 0,Sj(v),x,k)}let d=null,f=0,p=null;const h=1e3/30;function m(v){p=v,d===null&&(d=requestAnimationFrame(y=>{if(d=null,!p||y-f<h)return;f=y;const S=t.current;if(!S){p=null;return}const x=p;p=null;const k=r.getBoundingClientRect(),_=ZF(x.clientX,x.clientY,k,S);_&&s("mouseMoved",_.x,_.y,void 0,void 0,Sj(x))}))}return r.addEventListener("mousedown",i),r.addEventListener("mouseup",l),r.addEventListener("contextmenu",c),r.addEventListener("wheel",u,{passive:!1}),r.addEventListener("mousemove",m),()=>{r.removeEventListener("mousedown",i),r.removeEventListener("mouseup",l),r.removeEventListener("contextmenu",c),r.removeEventListener("wheel",u),r.removeEventListener("mousemove",m),d!==null&&cancelAnimationFrame(d)}},[e.enabled,e.imgRef])}const mDr={browser_navigate:"Navigating",browser_goto:"Navigating",browser_click:"Clicking",browser_type:"Typing",browser_scroll:"Scrolling",browser_screenshot:"Capturing",browser_snapshot:"Reading page",browser_close:"Closing",browser_select:"Selecting",stagehand_navigate:"Navigating",stagehand_act:"Acting",stagehand_extract:"Extracting",stagehand_observe:"Observing",stagehand_screenshot:"Capturing",stagehand_close:"Closing"};function gDr({toolName:e}){const t=e?mDr[e]??e.replace(/^(browser_|stagehand_)/,""):"Working";return o.jsx("div",{className:"absolute inset-0 bg-surface1/40 flex items-center justify-center z-10 cursor-not-allowed",children:o.jsxs("div",{className:"flex items-center gap-2 bg-surface2 px-3 py-1.5 rounded-md border border-border1 shadow-sm",children:[o.jsx(oa,{className:"h-3.5 w-3.5 text-accent1 animate-spin"}),o.jsxs("span",{className:"text-xs font-medium text-neutral4",children:["Agent: ",t]})]})})}const lye=32,UZe=lye/2;function vDr({ripples:e,onAnimationEnd:t}){return e.length===0?null:o.jsx(o.Fragment,{children:e.map(n=>o.jsx("span",{className:"absolute rounded-full pointer-events-none animate-click-ripple bg-accent1/40",style:{left:n.x-UZe,top:n.y-UZe,width:lye,height:lye},onAnimationEnd:()=>t(n.id)},n.id))})}function XPt({className:e,onStatusChange:t,onUrlChange:n,onFirstFrame:r}){const s=g.useRef(null),a=g.useRef(null),i=g.useRef(!1),[l,c]=g.useState(!1),[u,d]=g.useState(!1),{status:f,currentUrl:p,viewport:h,sendMessage:m}=O3(),{latestFrame:v}=YPt();g.useEffect(()=>{v&&s.current&&(s.current.src=`data:image/jpeg;base64,${v}`,i.current||(i.current=!0,c(!0)))},[v]);const y=g.useCallback(()=>{d(!1)},[]),b=g.useCallback(()=>{f==="streaming"&&d(!0)},[f]),{isAgentBusy:S,activeToolName:x}=uDr();hDr({imgRef:s,viewport:h,sendMessage:m,enabled:f==="streaming"&&!S}),pDr({sendMessage:m,enabled:u&&f==="streaming"&&l&&!S,onEscape:y});const{ripples:k,removeRipple:_}=cDr({imgRef:s,viewport:h,enabled:f==="streaming"&&l&&!S});g.useEffect(()=>{t?.(f)},[f,t]),g.useEffect(()=>{n?.(p)},[p,n]),g.useEffect(()=>{l&&r?.()},[l,r]),g.useEffect(()=>{if(!u)return;function T(A){a.current&&!a.current.contains(A.target)&&d(!1)}function I(){d(!1)}return document.addEventListener("mousedown",T),window.addEventListener("blur",I),()=>{document.removeEventListener("mousedown",T),window.removeEventListener("blur",I)}},[u]),g.useEffect(()=>{f!=="streaming"&&d(!1)},[f]);const C=(f==="connecting"||f==="browser_starting"||f==="streaming")&&!l,E=f==="disconnected"&&l,j=f==="error";return o.jsxs("div",{ref:a,className:X("relative w-full aspect-video bg-surface2 rounded-md overflow-hidden",u&&!S&&"ring-2 ring-accent1",u&&S&&"ring-2 ring-amber-400",e),children:[o.jsx("img",{ref:s,alt:"Browser screencast",onClick:b,onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),b())},tabIndex:f==="streaming"?0:-1,role:"button",className:X("absolute inset-0 w-full h-full object-contain",l?"opacity-100":"opacity-0",f==="streaming"&&(u?"cursor-text":"cursor-pointer"))}),o.jsx(vDr,{ripples:k,onAnimationEnd:_}),S&&o.jsx(gDr,{toolName:x}),C&&o.jsx(xt,{className:"absolute inset-0"}),E&&o.jsx("div",{className:"absolute inset-0 bg-surface1/80 flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx("div",{className:"w-4 h-4 border-2 border-neutral4 border-t-transparent rounded-full animate-spin"}),o.jsx("span",{className:"text-sm text-neutral4",children:"Reconnecting..."})]})}),j&&o.jsx("div",{className:"absolute inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 px-6 py-4 text-center",children:[o.jsx("div",{className:"w-14 h-14 rounded-full bg-red-500/20 flex items-center justify-center",children:o.jsx("svg",{className:"w-7 h-7 text-red-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"})})}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("span",{className:"text-lg font-medium text-white",children:"Connection Error"}),o.jsx("span",{className:"text-sm text-white/70",children:"Failed to connect to browser"})]})]})})]})}function JPt({agentName:e="Agent"}){const{hasSession:t,viewMode:n,status:r,currentUrl:s,setViewMode:a,closeBrowser:i}=O3(),{latestFrame:l}=YPt(),{toolCalls:c}=FCe(),u=g.useRef(null),[d,f]=g.useState(!1),p=g.useRef(null),h=n==="expanded";g.useEffect(()=>{if(l){const x=`data:image/jpeg;base64,${l}`;u.current&&(u.current.src=x),d||f(!0)}},[l,d]),g.useEffect(()=>{t||(f(!1),u.current&&(u.current.src=""))},[t]),g.useEffect(()=>{h&&p.current&&(p.current.scrollTop=p.current.scrollHeight)},[c.length,h]);const m=g.useCallback(()=>{a(h?"collapsed":"expanded")},[h,a]),v=g.useCallback(()=>{a("modal")},[a]),y=g.useCallback(async()=>{await i()},[i]),b=g.useMemo(()=>{if(!s)return"Browser";try{return new URL(s).hostname}catch{return s}},[s]);if(!t||n==="modal")return null;const S=r==="streaming";return o.jsxs("div",{className:X("bg-surface2 border border-border1 rounded-3xl overflow-hidden transition-all duration-200","hover:border-border2"),children:[o.jsxs("button",{type:"button",onClick:m,className:X("group flex items-center gap-3 w-full px-4 py-3","hover:bg-surface3 transition-colors","focus:outline-none focus:ring-2 focus:ring-accent1 focus:ring-inset"),children:[o.jsxs("div",{className:"relative shrink-0 w-24 h-14 bg-surface3 rounded-md overflow-hidden border border-border1",children:[d?o.jsx("img",{ref:u,alt:"Browser preview",className:"w-full h-full object-cover"}):o.jsx("div",{className:"flex items-center justify-center w-full h-full",children:o.jsx(Odt,{className:"h-5 w-5 text-neutral3"})}),S&&o.jsx("div",{className:"absolute top-1 right-1 w-2 h-2 bg-success rounded-full animate-pulse"})]}),o.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("span",{className:"text-sm font-medium text-neutral6 truncate",children:[e,"'s browser"]}),o.jsx(bg,{variant:S?"success":"neutral",size:"sm",withDot:!0,pulse:S,children:S?"Live":"Idle"})]}),o.jsx("p",{className:"text-xs text-neutral4 truncate mt-0.5",children:b})]}),o.jsx("div",{className:"shrink-0 text-neutral4 group-hover:text-neutral5 transition-colors",children:h?o.jsx(Ia,{className:"h-5 w-5"}):o.jsx(C_,{className:"h-5 w-5"})})]}),h&&o.jsxs("div",{className:"border-t border-border1",children:[o.jsx("div",{className:"p-3",children:o.jsxs("div",{className:"relative",children:[o.jsx(XPt,{className:"w-full"}),o.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[o.jsx(le,{variant:"default",size:"icon-sm",tooltip:"Center view",onClick:v,className:"bg-surface1/80 backdrop-blur-sm",children:o.jsx(omn,{className:"h-3.5 w-3.5"})}),o.jsx(le,{variant:"default",size:"icon-sm",tooltip:"Close browser",onClick:y,className:"bg-surface1/80 backdrop-blur-sm",children:o.jsx(bs,{className:"h-3.5 w-3.5"})})]})]})}),c.length>0&&o.jsx("div",{ref:p,className:"border-t border-border1 max-h-40 overflow-y-auto",children:o.jsxs("div",{className:"px-3 py-2",children:[o.jsx("h4",{className:"text-xs font-medium text-neutral4 mb-2",children:"Browser Actions"}),o.jsx("div",{className:"space-y-1",children:c.slice(-5).map(x=>o.jsx(KPt,{entry:x},x.toolCallId))})]})})]})]})}function yDr({className:e}){const{toolCalls:t}=FCe(),[n,r]=g.useState(!0),s=g.useRef(null);return g.useEffect(()=>{n&&s.current&&(s.current.scrollTop=s.current.scrollHeight)},[t.length,n]),t.length===0?null:o.jsxs("div",{className:X("flex flex-col overflow-hidden",e),children:[o.jsxs("button",{type:"button",onClick:()=>r(a=>!a),"aria-expanded":n,className:"flex items-center gap-2 w-full px-3 py-1 text-left hover:bg-surface3 transition-colors shrink-0",children:[o.jsx(Ia,{className:X("h-3.5 w-3.5 text-neutral3 transition-transform",n?"rotate-180":"")}),o.jsxs("span",{className:"text-xs font-medium text-neutral4",children:["Browser Actions (",t.length,")"]})]}),n&&o.jsx("div",{ref:s,className:"flex-1 overflow-y-auto bg-surface1",children:t.map(a=>o.jsx(KPt,{entry:a},a.toolCallId))})]})}const bDr=(e,t)=>{const n=g.useRef(null);g.useEffect(()=>{e?(n.current=document.activeElement,t?.current?.focus()):n.current&&(n.current.focus(),n.current=null)},[e,t])};function xDr(e){switch(e){case"idle":return{variant:"neutral",pulse:!1,label:"Idle"};case"connecting":return{variant:"warning",pulse:!0,label:"Connecting"};case"connected":return{variant:"warning",pulse:!0,label:"Connected"};case"browser_starting":return{variant:"warning",pulse:!0,label:"Starting"};case"streaming":return{variant:"success",pulse:!1,label:"Live"};case"browser_closed":return{variant:"neutral",pulse:!1,label:"Closed"};case"disconnected":return{variant:"error",pulse:!0,label:"Disconnected"};case"error":return{variant:"error",pulse:!1,label:"Error"};default:return{variant:"neutral",pulse:!1,label:"Unknown"}}}function zCe(){const{viewMode:e,status:t,currentUrl:n,hide:r,closeBrowser:s}=O3(),a=e==="modal",i=g.useRef(null);bDr(a,i);const l=()=>{if(n)try{const d=new URL(n);(d.protocol==="http:"||d.protocol==="https:")&&window.open(d.href,"_blank","noopener,noreferrer")}catch{}};g.useEffect(()=>{if(!a)return;const d=f=>{f.key==="Escape"&&(f.preventDefault(),r())};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[a,r]);const c=d=>{d.target===d.currentTarget&&r()},u=xDr(t);return o.jsx("div",{className:X("fixed inset-0 z-50 flex items-center justify-center p-8","bg-black/60 backdrop-blur-sm transition-opacity duration-200",a?"opacity-100":"opacity-0 pointer-events-none"),onClick:c,"aria-hidden":!a,children:o.jsxs("div",{ref:i,role:"dialog","aria-modal":"true","aria-label":"Browser view",tabIndex:-1,className:X("flex flex-col w-full max-w-5xl max-h-full","bg-surface2 rounded-xl border border-border1 shadow-2xl overflow-hidden","transition-transform duration-200 outline-none",a?"scale-100":"scale-95"),onClick:d=>d.stopPropagation(),children:[o.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-border1 shrink-0",children:[o.jsx(Ux,{className:"h-4 w-4 text-neutral4 shrink-0"}),o.jsx("div",{className:"flex-1 min-w-0 px-3 py-1.5 bg-surface3 rounded-md border border-border1",children:o.jsx("span",{className:X("text-sm truncate block",n?"text-neutral5":"text-neutral3 italic"),children:n||"No URL"})}),o.jsx(bg,{variant:u.variant,size:"sm",withDot:!0,pulse:u.pulse,children:u.label}),o.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[o.jsx(le,{variant:"ghost",size:"icon-sm",tooltip:"Minimize to chat",onClick:r,children:o.jsx(gmn,{className:"h-4 w-4"})}),n&&o.jsx(le,{variant:"ghost",size:"icon-sm",tooltip:"Open in new tab",onClick:l,children:o.jsx(ka,{className:"h-4 w-4"})}),o.jsx(le,{variant:"ghost",size:"icon-sm",tooltip:"Close browser",onClick:s,children:o.jsx(bs,{className:"h-4 w-4"})})]})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto",children:[o.jsx("div",{className:"p-4",children:o.jsx(XPt,{className:"w-full max-h-[60vh]"})}),o.jsx("div",{className:"px-4 pb-4",children:o.jsx(yDr,{})})]})]})})}const e$t=g.createContext({isConversationLoading:!1}),wDr=[],SDr=[{title:"What can you do?",description:"Get an overview of capabilities",prompt:"What can you do? Give me a quick overview of your capabilities.",Icon:emn},{title:"Show available tools",description:"See what this agent can call",prompt:"Show me the available tools you can call and explain when you would use each one.",Icon:Up},{title:"Suggest a task",description:"Get an example prompt to try",prompt:"Suggest a useful task I can try with you, including an example prompt.",Icon:Qhn},{title:"Run a self-check",description:"Verify tools are reachable",prompt:"Run a self-check and verify whether your tools are reachable. Tell me what works and what does not.",Icon:gxe}],kDr=({agentId:e,agentName:t,agentDescription:n,agentAvatarUrl:r,children:s})=>{const{data:a}=Cm(),i=a?.id?`${a.id}-${e}`:e,{data:l,isLoading:c}=AH({agentId:e,threadId:i,memory:!0}),u=l?.messages??wDr,d=g.useMemo(()=>({isConversationLoading:c,agentName:t,agentDescription:n,agentAvatarUrl:r}),[c,t,n,r]);return o.jsx(t2t,{agentId:e,threadId:i,initialMessages:u,children:o.jsx(e$t.Provider,{value:d,children:s})},i)},ODr=({hasBrowser:e=!1})=>{const t=fu(),n=uCe(),{draft:r,setDraft:s,trimmed:a,handleFormSubmit:i,handleKeyDown:l}=n2t({onSubmit:n});return o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[o.jsx(CDr,{onStarterPromptSelect:s}),e&&o.jsx(_Dr,{}),o.jsx(wCe,{draft:r,onDraftChange:s,onSubmit:i,onKeyDown:l,disabled:t,isRunning:t,canSubmit:a.length>0&&!t,placeholder:"Message your agent…",inputTestId:"agent-builder-agent-chat-input",submitTestId:"agent-builder-agent-chat-submit",containerTestId:"agent-builder-agent-chat-composer"})]})},_Dr=()=>{const{hasSession:e,viewMode:t}=O3();return!e||t==="modal"?null:o.jsx("div",{className:"mx-auto mb-2 w-full max-w-3xl",children:o.jsx(JPt,{})})},CDr=({onStarterPromptSelect:e})=>{const t=cCe(),n=fu(),{isConversationLoading:r,agentName:s,agentDescription:a,agentAvatarUrl:i}=g.useContext(e$t);return o.jsx($Ce,{messages:t,isLoading:r,isRunning:n,skeletonTestId:"agent-builder-agent-chat-messages-skeleton",emptyState:o.jsxs("div",{className:"flex flex-col items-center gap-6 py-6 text-center lg:h-full lg:justify-center lg:py-0","data-testid":"agent-builder-agent-chat-empty-state",children:[o.jsxs("div",{className:"flex flex-col items-center gap-3",children:[o.jsx("div",{className:"starter-chip",style:{animationDelay:"0ms",viewTransitionName:"agent-avatar"},children:o.jsx(p_,{name:s??"Agent",src:i,size:"lg"})}),o.jsx("div",{className:"starter-chip",style:{animationDelay:"150ms"},children:o.jsx(ye,{variant:"ui-lg",className:"text-neutral6 font-semibold",style:{viewTransitionName:"agent-name"},children:s??"your agent"})}),a?o.jsx("div",{className:"starter-chip",style:{animationDelay:"220ms"},children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral4 max-w-[40ch]",style:{viewTransitionName:"agent-description"},children:a})}):null]}),o.jsx("div",{className:"grid w-full max-w-2xl grid-cols-1 gap-5 sm:grid-cols-2",children:SDr.map((l,c)=>o.jsxs("button",{type:"button",onClick:()=>e(l.prompt),"data-testid":`agent-builder-agent-chat-starter-${l.title.toLowerCase().replace(/\s+/g,"-")}`,style:{animationDelay:`${280+c*40}ms`},className:"starter-chip group flex gap-3 rounded-3xl border border-border1 bg-surface2 p-4 text-left transition-colors duration-normal ease-out-custom hover:border-border2 hover:bg-surface3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent1",children:[o.jsx("span",{className:"mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md bg-surface3 text-neutral4 transition-colors group-hover:text-neutral6",children:o.jsx(l.Icon,{className:"size-4","aria-hidden":"true"})}),o.jsxs("span",{className:"min-w-0",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral6 font-medium transition-colors group-hover:text-neutral6",children:l.title}),o.jsx(ye,{variant:"ui-xs",className:"mt-1 text-neutral4 transition-colors group-hover:text-neutral5",children:l.description})]})]},l.title))})]})})},EDr=({mode:e,onModeToggle:t,modeToggleDisabled:n=!1,ownerActions:r,mobileMenu:s})=>{const a=e==="test"?"Switch to Edit mode":"Switch to View mode";return o.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-center gap-2 px-4 pt-4 md:px-10","data-testid":"agent-builder-view-top-bar",children:[o.jsxs(vwe,{label:"Agent navigation",className:"min-w-0",listClassName:"min-w-0",children:[o.jsx(j$,{as:ti,to:"/agent-builder/agents","data-testid":"agent-builder-back-to-list",children:"Agent list"}),o.jsx(j$,{as:"span",isCurrent:!0,children:o.jsx(HPt,{isLoading:!1})})]}),o.jsxs("div",{className:"justify-self-end flex items-center gap-2 shrink-0",children:[r&&o.jsx("div",{className:"shrink-0 hidden lg:flex items-center gap-2",children:r}),s&&o.jsx("div",{className:"shrink-0 lg:hidden",children:s}),e&&t&&o.jsxs(le,{variant:"ghost",size:"sm",onClick:t,disabled:n,className:"hidden lg:inline-flex shrink-0","data-testid":"agent-builder-mode-toggle","aria-label":a,children:[o.jsx(n1,{}),a]})]})]})};function jDr(e,t){const n=e?.metadata&&typeof e.metadata=="object"&&"avatarUrl"in e.metadata?e.metadata.avatarUrl:void 0;return{id:e?.id??t,name:e?.name??"",description:e?.description??"",avatarUrl:n,systemPrompt:typeof e?.instructions=="string"?e.instructions:"",visibility:e?.visibility??"private",authorId:e?.authorId}}const t$t=g.createContext(null),TDr=({agentId:e,storedAgent:t,currentUserId:n,canWrite:r,children:s})=>{const a=Mf(),i=Hs(),l=g.useMemo(()=>jDr(t,e),[t,e]),c=!t.authorId||n===t.authorId,u=t.visibility==="public",d=r&&c,f=a.browser&&t.browser!=null,p=n?`${n}-${e}`:e,h=g.useMemo(()=>c?()=>i(`/agent-builder/agents/${e}/edit`,{viewTransition:!0}):void 0,[c,e,i]),m=g.useMemo(()=>({agentId:e,isOwner:c,canModify:d,isPublishable:u,hasBrowser:f,agent:l,threadId:p,onModeToggle:h}),[e,c,d,u,f,l,p,h]);return o.jsx(t$t.Provider,{value:m,children:o.jsx(kDr,{agentId:e,agentName:t.name,agentDescription:t.description,agentAvatarUrl:l.avatarUrl,children:s})})},n$t=()=>{const e=g.useContext(t$t);if(!e)throw new Error("useViewPage must be used inside <ViewPageProvider>");return e},NDr=({topBar:e,chat:t,browserOverlay:n})=>o.jsxs("div",{className:"flex flex-1 min-w-0 flex-col h-full min-h-0",children:[e,o.jsx("div",{className:"flex-1 min-h-0 w-full min-w-0 overflow-hidden px-4 md:px-10 md:max-w-[80ch] md:mx-auto pt-10 md:pt-4 pb-4 md:pb-10","data-testid":"agent-builder-panel-chat",children:t}),n]}),IDr=(e,t)=>["browser-session-probe",e,t],ADr={hasSession:!0,screencastAvailable:!0},RDr=e=>!e||typeof e!="object"?!1:"status"in e&&e.status===404||"statusCode"in e&&e.statusCode===404;function PDr({agentId:e,threadId:t,enabled:n=!0}){const r=We();return yt({queryKey:IDr(e,t),queryFn:async()=>{if(!e)return{hasSession:!1,screencastAvailable:!1};try{return await r.getAgent(e).browserSession(t)}catch(s){if(RDr(s))return ADr;throw s}},enabled:n&&!!e,refetchOnWindowFocus:!0,staleTime:0,retry:1})}function $Dr(){const e=We();return Rn({mutationFn:({agentId:t,threadId:n})=>e.getAgent(t).closeBrowser(n),onError:t=>{console.error("[useCloseBrowser] Error closing browser:",t)}})}function MDr(){let e=null;const t=new Set;return{getSnapshot:()=>e,subscribe:n=>(t.add(n),()=>{t.delete(n)}),setFrame:n=>{e!==n&&(e=n,t.forEach(r=>r()))}}}function eZ({children:e,agentId:t,threadId:n,enabled:r=!0}){const[s,a]=g.useState(!1),[i,l]=g.useState("collapsed"),{data:c}=PDr({agentId:t,threadId:n,enabled:r}),u=c?.screencastAvailable??!1,d=c?.hasSession??!1,p=r&&u&&(d||i!=="collapsed"),h=g.useRef(p),m=g.useRef(t),v=g.useRef(n);g.useEffect(()=>{h.current=p,m.current=t,v.current=n});const[y,b]=g.useState("idle"),[S,x]=g.useState(null),[k,_]=g.useState(null),C=g.useRef(MDr()),E=g.useRef(null),j=g.useRef(0),T=g.useRef(null),I=g.useRef(null),A=5,R=g.useCallback(()=>{T.current&&(clearTimeout(T.current),T.current=null)},[]),L=g.useCallback(()=>{R(),I.current=null,E.current&&(E.current.close(),E.current=null),j.current=0,a(!1),b("idle"),x(null),C.current.setFrame(null),_(null)},[R]),M=g.useCallback(Z=>{E.current?.readyState===WebSocket.OPEN&&E.current.send(Z)},[]),z=g.useRef(!1),H=g.useCallback(()=>{if(!h.current)return;const Z=m.current,K=v.current;if(!Z||!K||I.current?.agentId===Z&&I.current?.threadId===K&&E.current?.readyState===WebSocket.OPEN)return;R(),E.current&&(z.current=!0,E.current.close(),E.current=null),I.current={agentId:Z,threadId:K},b("connecting");const te=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/browser/${Z}/stream?threadId=${encodeURIComponent(K)}`;try{const J=new WebSocket(te);z.current=!1,E.current=J,J.onopen=()=>{b("connected"),j.current=0},J.onmessage=ae=>{const pe=ae.data;if(pe.startsWith("{"))try{const Y=JSON.parse(pe);if(Y.status)switch(Y.status){case"browser_starting":b("browser_starting");break;case"streaming":b("streaming"),a(!0);break;case"browser_closed":b("browser_closed"),a(!1),l("collapsed");break;case"stopped":b("disconnected");break;case"error":b("error"),a(!1);break}Y.url&&x(Y.url),Y.viewport&&_(Y.viewport)}catch{C.current.setFrame(pe)}else C.current.setFrame(pe),b(Y=>Y!=="streaming"?"streaming":Y),a(!0)},J.onerror=()=>{},J.onclose=ae=>{if(E.current===J&&(E.current=null,!z.current))if(a(!1),!ae.wasClean&&j.current<A){j.current+=1;const pe=Math.min(1e3*Math.pow(2,j.current-1),1e4);b("disconnected"),T.current=setTimeout(()=>{H()},pe)}else j.current>=A?b("error"):b("disconnected")}}catch{b("error")}},[R]);g.useEffect(()=>(p&&t&&n&&H(),()=>{L()}),[p,t,n,H,L]),g.useEffect(()=>{if(!p)return;const Z=()=>{document.visibilityState==="visible"&&y==="disconnected"&&t&&n&&(j.current=0,H())};return document.addEventListener("visibilitychange",Z),()=>{document.removeEventListener("visibilitychange",Z)}},[p,y,t,n,H]);const F=g.useCallback(Z=>{l(Z)},[]),B=g.useCallback(()=>{l("modal")},[]),q=g.useCallback(()=>{l("collapsed")},[]),D=g.useCallback(()=>{a(!1),l("collapsed"),C.current.setFrame(null)},[]),G=$Dr(),V=g.useCallback(async()=>{if(!(G.isPending||!t))try{await G.mutateAsync({agentId:t,threadId:n}),D()}catch{}},[t,n,G,D]),$=G.isPending,U=g.useMemo(()=>({hasSession:s,viewMode:i,isPanelOpen:i==="modal",isActive:s,status:y,currentUrl:S,viewport:k,isClosing:$,setViewMode:F,show:B,hide:q,endSession:D,closeBrowser:V,sendMessage:M,connect:H,disconnect:L}),[s,i,y,S,k,$,F,B,q,D,V,M,H,L]);return o.jsx(GPt.Provider,{value:U,children:o.jsx(QPt.Provider,{value:C.current,children:e})})}function DDr(){const{id:e}=Sr(),{data:t,isLoading:n}=g3(e,{status:"draft"}),{data:r,isLoading:s}=Cm(),{canWrite:a}=Ry();return WPt(),e?n||s?o.jsx(BDr,{}):t?o.jsx(TDr,{agentId:e,storedAgent:t,currentUserId:r?.id,canWrite:a,children:o.jsx(LDr,{storedAgent:t})}):o.jsx(Vu,{to:"/agent-builder/agents",replace:!0}):null}const LDr=({storedAgent:e})=>{const{hasBrowser:t,agentId:n,threadId:r}=n$t(),[s]=g.useState(()=>ZPt(e)),a=q1({defaultValues:s}),i=o.jsx(FDr,{hasBrowser:t});return t?o.jsx(M$,{...a,children:o.jsx(lD,{agentId:n,children:o.jsx(JW,{children:o.jsx(eZ,{agentId:n,threadId:r,children:i})})})}):o.jsx(M$,{...a,children:o.jsx(lD,{agentId:n,children:i})})},FDr=g.memo(function({hasBrowser:t}){const n=g.useMemo(()=>o.jsx(zDr,{}),[]),r=g.useMemo(()=>o.jsx(ODr,{hasBrowser:t}),[t]),s=g.useMemo(()=>t?o.jsx(zCe,{}):void 0,[t]);return o.jsx(NDr,{topBar:n,chat:r,browserOverlay:s})}),zDr=()=>{const{canModify:e,onModeToggle:t,isOwner:n,agentId:r,agent:s}=n$t(),a=fu();return o.jsx(EDr,{mode:e?"test":void 0,onModeToggle:t,modeToggleDisabled:a,mobileMenu:n&&o.jsx(FRt,{agentId:r,showEditAgent:!0,showDelete:!0,agentName:s.name,disabled:a})})},BDr=()=>o.jsx("div",{className:"h-screen w-screen flex items-center justify-center",children:o.jsx(Kt,{})}),VZe=(e,t)=>{const n=e.favoriteCount??0,r=t?n+(e.isFavorited?0:1):Math.max(0,n-(e.isFavorited?1:0));return{...e,isFavorited:t,favoriteCount:r}},UDr=e=>{const t=We(),n=Ur(),{requestContext:r}=Cs();return Rn({mutationFn:async({favorited:s})=>{if(!e)throw new Error("skillId is required to toggle favorite");const a=t.getStoredSkill(e);return s?a.favorite(r):a.unfavorite(r)},onMutate:async({favorited:s})=>{if(!e)return{previousLists:[]};await n.cancelQueries({queryKey:["stored-skills"]}),await n.cancelQueries({queryKey:["stored-skill",e]});const a=n.getQueryData(["stored-skill",e]),i=n.getQueriesData({queryKey:["stored-skills"]}),l=[];for(const[c,u]of i)l.push([c,u]),u?.skills&&n.setQueryData(c,{...u,skills:u.skills.map(d=>d.id===e?VZe(d,s):d)});return a&&n.setQueryData(["stored-skill",e],VZe(a,s)),{previousDetail:a,previousLists:l}},onError:(s,a,i)=>{if(i){e&&i.previousDetail!==void 0&&n.setQueryData(["stored-skill",e],i.previousDetail);for(const[l,c]of i.previousLists)n.setQueryData(l,c)}},onSettled:()=>{n.invalidateQueries({queryKey:["stored-skills"]}),e&&n.invalidateQueries({queryKey:["stored-skill",e]})}})},VDr={sm:14,md:16},cye=({skillId:e,isFavorited:t=!1,favoriteCount:n,size:r="md",className:s,showCount:a=!0})=>{const i=Mf(),l=UDr(e),{data:c}=dc();if(!i.favorites)return null;const u=c?wm(c):!1,d=t?"Unstar skill":"Star skill",f="Sign in to star this skill",p=typeof n=="number"&&n>0,h=n===1?"Star":"Stars",m=l.isPending||!u;return o.jsxs(le,{type:"button",variant:"default",size:r,"aria-pressed":t,"aria-label":u?d:f,title:u?d:f,disabled:m,onClick:v=>{v.preventDefault(),v.stopPropagation(),u&&l.mutate({favorited:!t})},className:X("shrink-0",u?"cursor-pointer":"cursor-not-allowed",s),children:[o.jsx(gT,{size:VDr[r],className:X("shrink-0",t&&"fill-current text-yellow-300"),"aria-hidden":!0}),a&&o.jsx("span",{className:"leading-none whitespace-nowrap",children:p?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"tabular-nums",children:n})," ",h]}):"Star"})]})};function qDr(e){if(!e||typeof e!="object")return null;const t=e.origin;if(!t||typeof t!="object")return null;const n=t;return n.type==="skills-sh"&&typeof n.owner=="string"&&typeof n.repo=="string"&&typeof n.skillName=="string"?{type:"skills-sh",owner:n.owner,repo:n.repo,skillName:n.skillName}:n.type==="library-copy"&&typeof n.sourceSkillId=="string"&&typeof n.sourceSkillName=="string"?{type:"library-copy",sourceSkillId:n.sourceSkillId,sourceSkillName:n.sourceSkillName,sourceAuthorId:typeof n.sourceAuthorId=="string"?n.sourceAuthorId:void 0}:null}function BCe({skills:e,search:t,onSkillClick:n,showFavorites:r=!0}){const s=g.useMemo(()=>{const a=(t??"").trim().toLowerCase();return a?e.filter(i=>{const l=i.name?.toLowerCase()??"",c=i.description?.toLowerCase()??"";return l.includes(a)||c.includes(a)}):e},[e,t]);return s.length===0?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(zr,{iconSlot:o.jsx(Ka,{className:"h-8 w-8 text-neutral3"}),titleSlot:"No skills match your search",descriptionSlot:"Try a different name or description."})}):o.jsx("div",{className:"bg-surface2 border border-border1 rounded-xl divide-y divide-border1 overflow-hidden",children:s.map(a=>{const i=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("div",{className:"text-ui-md text-neutral6 truncate",children:a.name}),a.visibility==="private"&&o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx("span",{className:"text-neutral3 shrink-0","aria-label":"Private skill","data-testid":"skill-builder-private-visibility-icon",children:o.jsx(qe,{size:"sm",children:o.jsx(Cf,{})})})}),o.jsx($n,{children:"Only visible to you"})]}),(()=>{const l=qDr(a.metadata);if(!l)return null;const c=l.type==="library-copy";return o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-surface5 text-neutral4 shrink-0","aria-label":c?"Copied skill":"Imported skill","data-testid":"skill-builder-origin-badge",children:[c?o.jsx(am,{className:"h-2.5 w-2.5"}):o.jsx(vf,{className:"h-2.5 w-2.5"}),l.type==="skills-sh"?"skills.sh":c?"copied":"imported"]})}),o.jsx($n,{children:l.type==="skills-sh"?`Imported from ${l.owner}/${l.repo}`:c?`Copied from "${l.sourceSkillName}"`:"Imported from external registry"})]})})()]}),o.jsx("div",{className:"flex items-center gap-2 mt-0.5",children:o.jsx("span",{className:"text-ui-sm text-neutral3 line-clamp-1",children:a.description||"No description"})}),r&&o.jsx("div",{className:"mt-2 md:hidden",children:o.jsx(cye,{skillId:a.id,isFavorited:a.isFavorited,favoriteCount:a.favoriteCount,size:"sm"})})]}),r&&o.jsx(cye,{skillId:a.id,isFavorited:a.isFavorited,favoriteCount:a.favoriteCount,size:"sm",className:"shrink-0 hidden md:inline-flex"})]});return n?o.jsx("button",{className:"px-6 py-5 flex items-start gap-4 w-full text-left hover:bg-surface3/50 transition-colors md:items-center",onClick:()=>n(a),children:i},a.id):o.jsx("div",{className:"px-6 py-5 flex items-start gap-4 md:items-center",children:i},a.id)})})}function UCe({rows:e=4}){return o.jsx("div",{className:"bg-surface2 border border-border1 rounded-xl divide-y divide-border1 overflow-hidden",children:Array.from({length:e}).map((t,n)=>o.jsxs("div",{className:"px-6 py-5 flex items-center gap-4",children:[o.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[o.jsx("div",{className:"h-3.5 w-48 bg-surface3 rounded animate-pulse"}),o.jsx("div",{className:"h-3 w-72 max-w-full bg-surface3 rounded animate-pulse"})]}),o.jsx("div",{className:"h-3 w-16 bg-surface3 rounded animate-pulse"})]},n))})}function HDr(){const e=Hs(),[t,n]=g.useState(""),[r,s]=g.useState("agents"),a=Mf(),{data:i}=Cm(),l=x=>{const _=!x.authorId||i?.id===x.authorId?"edit":"view";e(`/agent-builder/skills/${x.id}/${_}`,{viewTransition:!0})},c=g.useMemo(()=>({favoritedOnly:!0,orderBy:{field:"updatedAt",direction:"DESC"}}),[]),{data:u,isLoading:d,error:f}=f_(c),{data:p,isLoading:h,error:m}=K1({enabled:r==="skills"&&a.skills}),v=u?.agents??[],y=p?.skills??[],b=(x,k)=>ys(x)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ws,{})}):xs(x)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ds,{resource:k})}):o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Hi,{title:`Failed to load favorite ${k}`,message:x.message})}),S=r==="agents"?d?o.jsx(tCe,{rowTestId:"favorite-skeleton-row"}):f?b(f,"agents"):v.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(zr,{iconSlot:o.jsx(gT,{className:"h-8 w-8 text-neutral3"}),titleSlot:"No favorite agents yet",descriptionSlot:"Star agents to keep them here for quick access."})}):o.jsx(eCe,{agents:v,search:t,rowTestId:"favorite-agent-row"}):h?o.jsx(UCe,{}):m?b(m,"skills"):y.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(zr,{iconSlot:o.jsx(jg,{className:"h-8 w-8 text-neutral3"}),titleSlot:"No favorite skills yet",descriptionSlot:"Star skills to keep them here for quick access."})}):o.jsx(BCe,{skills:y,search:t,onSkillClick:l});return o.jsx(o.Fragment,{children:o.jsxs(Ft,{className:"px-4 md:px-10",children:[o.jsxs(Ft.TopArea,{children:[o.jsx("div",{className:"flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4",children:o.jsxs(Sf,{children:[o.jsxs(Sf.Title,{children:[o.jsx(gT,{})," Favorites"]}),o.jsx(Sf.Description,{children:r==="agents"?"Agents you've starred in Agent Builder.":"Skills you've starred in Agent Builder."})]})}),o.jsxs("div",{className:"flex items-center gap-4",children:[a.skills&&o.jsxs("div",{className:"flex rounded-lg border border-border1 overflow-hidden",children:[o.jsx("button",{onClick:()=>s("agents"),className:`px-3 py-1.5 text-xs font-medium transition-colors ${r==="agents"?"bg-surface4 text-neutral6":"bg-surface2 text-neutral3 hover:text-neutral5"}`,children:"Agents"}),o.jsx("button",{onClick:()=>s("skills"),className:`px-3 py-1.5 text-xs font-medium transition-colors ${r==="skills"?"bg-surface4 text-neutral6":"bg-surface2 text-neutral3 hover:text-neutral5"}`,children:"Skills"})]}),o.jsx("div",{className:"flex-1 max-w-120",children:o.jsx($f,{onSearch:n,label:"Filter favorites",placeholder:"Filter by name or description"})})]})]}),S]})})}function WDr({title:e,description:t,tone:n="default",id:r,className:s,descriptionClassName:a}){const i=n==="danger";return o.jsxs(o.Fragment,{children:[o.jsx("h3",{id:r,className:X("font-display text-header-md leading-tight font-normal tracking-normal",i?"text-accent2":"text-neutral4",s),children:e}),t!=null&&o.jsx("p",{className:X("mt-2 max-w-[62ch] font-sans text-[13.5px] leading-ui-xs",i?"text-accent2/70":"text-neutral3",a),children:t})]})}function uye({title:e,description:t,action:n,variant:r="default",fillHeight:s=!1,className:a,contentClassName:i,children:l}){const c=r==="danger";return o.jsxs("section",{"data-variant":r,className:X("overflow-hidden rounded-2xl border",s&&"flex h-full flex-col",c?"border-accent2/25":"border-border1",a),children:[o.jsxs("div",{className:X("flex flex-col gap-3 px-7 pt-7 pb-6 sm:flex-row sm:items-start sm:justify-between sm:gap-6",c?"bg-accent2/8":"bg-surface-overlay-soft"),children:[o.jsx("div",{className:"min-w-0",children:o.jsx(WDr,{title:e,description:t,tone:c?"danger":"default"})}),n!=null?o.jsx("div",{className:"shrink-0",children:n}):null]}),o.jsx("div",{className:X("min-w-0 px-7 pt-6 pb-7",s&&"flex-1",c?"bg-accent2/4":null,i),children:l})]})}const ZDr=e=>{const t=We();return yt({queryKey:["infrastructure-status"],queryFn:()=>t.getInfrastructureStatus(),enabled:e?.enabled??!0,retry:!1})},GR=({ok:e,label:t})=>o.jsxs("span",{className:`inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-xs ${e?"bg-accent3/10 text-accent3":"bg-surface2 text-neutral3"}`,"data-slot":"infrastructure-status-badge","data-ok":e?"true":"false",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${e?"bg-accent3":"bg-neutral3"}`,"aria-hidden":"true"}),t]}),Fre=({message:e})=>o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:e}),hk=e=>e==null?e:String(e).split(/([\s-]+)/).map(t=>/^[\s-]+$/.test(t)?t:t.charAt(0).toUpperCase()+t.slice(1)).join(""),Ib=({label:e,value:t})=>o.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4",children:e}),o.jsx(ye,{variant:"ui-sm",className:"text-icon6",children:t??"Not set"})]}),qZe=({entries:e})=>e.length===0?null:o.jsx("div",{className:"grid grid-cols-1 gap-3 border-t border-border1 pt-3 sm:grid-cols-2",children:e.map(t=>o.jsx(Ib,{label:`Config: ${t.key}`,value:hk(t.value)},t.key))}),GDr=()=>{const{hasPermission:e}=dl(),t=e("infrastructure:read"),{data:n,isLoading:r,error:s}=ZDr({enabled:t}),a=n;return o.jsxs(Ft,{width:"narrow",children:[o.jsx(Ft.TopArea,{children:o.jsx(Sf,{children:o.jsx(Sf.Title,{children:"Infrastructure"})})}),o.jsx(Ft.MainArea,{className:"flex flex-col gap-5 mt-6",children:o.jsx(uye,{title:"Agent Builder Infrastructure",description:"Deployment-level defaults Agent Builder applies when users create or run builder agents.",children:t?r?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"Loading infrastructure configuration…"}):s||!a?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"Infrastructure configuration unavailable."}):o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-md",className:"font-medium",children:"Channels"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"Configured channel providers available to Agent Builder publish/share flows. Unconfigured providers are omitted until their required environment/config is present."})]}),a.channels.providers.length===0?o.jsx(Fre,{message:"No configured channel providers for Agent Builder."}):o.jsx("ul",{className:"flex flex-col gap-2",children:a.channels.providers.map(i=>o.jsxs("li",{className:"rounded-md border border-border1 px-3 py-3",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:hk(i.name)}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3",children:["Provider ID: ",i.id]})]}),o.jsx(GR,{ok:i.isConfigured,label:i.isConfigured?"Configured":"Not configured"})]}),o.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 border-t border-border1 pt-3 sm:grid-cols-2",children:[o.jsx(Ib,{label:"Registered by",value:`${hk(i.name)} provider`}),o.jsx(Ib,{label:"Provider routes",value:i.routeCount})]})]},i.id))})]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-md",className:"font-medium",children:"Browser"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"Browser automation provider configured for builder agents. The card shows the selected provider and only non-default options explicitly passed in configuration."})]}),a.browser.provider?o.jsxs("div",{className:"rounded-md border border-border1 px-3 py-3",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsx("div",{className:"flex flex-col gap-1",children:o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:hk(a.browser.provider)})}),o.jsx(GR,{ok:a.browser.registered,label:a.browser.registered?"Provider available":"Provider missing"})]}),a.browser.env?o.jsx("div",{className:"mt-3 grid grid-cols-1 gap-3 border-t border-border1 pt-3 sm:grid-cols-2",children:o.jsx(Ib,{label:"Environment",value:hk(a.browser.env)})}):null,o.jsx(qZe,{entries:a.browser.config})]}):o.jsx(Fre,{message:"No browser configured."})]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-md",className:"font-medium",children:"Registries"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"External skill registries available to import skills into the workspace."})]}),o.jsx("div",{className:"rounded-md border border-border1 px-3 py-3",children:o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:"skills.sh"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"GitHub-backed public skills registry."})]}),o.jsx(GR,{ok:a.registries?.skillsSh?.enabled??!1,label:a.registries?.skillsSh?.enabled?"Enabled":"Disabled"})]})})]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-md",className:"font-medium",children:"Workspace"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"Workspace config used for generated files and sandbox execution. This reports the builder workspace only, not agent-specific runtime workspaces."})]}),a.workspace.type?o.jsxs("div",{className:"rounded-md border border-border1 px-3 py-3",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:a.workspace.workspaceId??a.workspace.name??"Inline workspace"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(GR,{ok:a.workspace.hasFilesystem,label:"Filesystem"}),o.jsx(GR,{ok:a.workspace.hasSandbox,label:"Sandbox"})]})]}),o.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 border-t border-border1 pt-3 sm:grid-cols-2",children:[o.jsx(Ib,{label:"Config type",value:a.workspace.type==="id"?"Registered workspace":"Inline config"}),a.workspace.workspaceId?o.jsx(Ib,{label:"Workspace ID",value:a.workspace.workspaceId}):null,o.jsx(Ib,{label:"Name",value:a.workspace.name}),o.jsx(Ib,{label:"Filesystem provider",value:hk(a.workspace.filesystemProvider)}),o.jsx(Ib,{label:"Sandbox provider",value:hk(a.workspace.sandboxProvider)})]}),o.jsx(qZe,{entries:a.workspace.config})]}):o.jsx(Fre,{message:"No workspace configured."})]})]}):o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You do not have permission to view Agent Builder infrastructure."})})})]})};function QDr(){const e=Hs(),[t,n]=g.useState(""),[r,s]=g.useState("agents"),a=Mf(),{canUseFavorites:i}=Ry(),l=g.useMemo(()=>({visibility:"public"}),[]),{data:c,isLoading:u,error:d}=f_(l),{data:f,isLoading:p,error:h}=K1({enabled:r==="skills"&&a.skills}),m=c?.agents??[],v=f?.skills??[],y=S=>ys(S)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ws,{})}):xs(S)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ds,{resource:r})}):o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Hi,{title:"Failed to load the library",message:S.message})}),b=r==="agents"?u?o.jsx(tCe,{rowTestId:"library-skeleton-row"}):d?y(d):m.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(zr,{iconSlot:o.jsx(f$,{className:"h-8 w-8 text-neutral3"}),titleSlot:"No public agents yet",descriptionSlot:"Mark an agent as Public to share it with the team library."})}):o.jsx(eCe,{agents:m,search:t,rowTestId:"library-agent-row",showFavorites:i}):p?o.jsx(UCe,{}):h?y(h):v.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(zr,{iconSlot:o.jsx(jg,{className:"h-8 w-8 text-neutral3"}),titleSlot:"No public skills yet",descriptionSlot:"Mark a skill as Public to share it with the team library."})}):o.jsx(BCe,{skills:v,search:t,onSkillClick:S=>e(`/agent-builder/skills/${S.id}/view`,{viewTransition:!0}),showFavorites:i});return o.jsx(o.Fragment,{children:o.jsxs(Ft,{className:"px-4 md:px-10",children:[o.jsxs(Ft.TopArea,{children:[o.jsx("div",{className:"flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4",children:o.jsxs(Sf,{children:[o.jsxs(Sf.Title,{children:[o.jsx(f$,{})," Library"]}),o.jsx(Sf.Description,{children:r==="agents"?"Agents shared with the team library.":"Skills shared with the team library."})]})}),o.jsxs("div",{className:"flex items-center gap-4",children:[a.skills&&o.jsxs("div",{className:"flex rounded-lg border border-border1 overflow-hidden",children:[o.jsx("button",{onClick:()=>s("agents"),className:`px-3 py-1.5 text-xs font-medium transition-colors ${r==="agents"?"bg-surface4 text-neutral6":"bg-surface2 text-neutral3 hover:text-neutral5"}`,children:"Agents"}),o.jsx("button",{onClick:()=>s("skills"),className:`px-3 py-1.5 text-xs font-medium transition-colors ${r==="skills"?"bg-surface4 text-neutral6":"bg-surface2 text-neutral3 hover:text-neutral5"}`,children:"Skills"})]}),o.jsx("div",{className:"flex-1 max-w-120",children:o.jsx($f,{onSearch:n,label:"Filter library",placeholder:"Filter by name or description"})})]})]}),b]})})}const $I=e=>o.jsx(lTn,{...e}),YDr=300*1e3;function KDr(e){const t=We();return yt({queryKey:["builder-registries"],queryFn:()=>t.listBuilderRegistries(),enabled:e?.enabled??!0,retry:!1})}function XDr(e){const t=We();return Rn({mutationFn:async n=>{if(!e)throw new Error("Registry ID is required");return t.searchBuilderRegistry(e,{q:n,limit:10})}})}function JDr(e){const t=We();return yt({queryKey:["builder-registry",e,"popular"],queryFn:()=>{if(!e)throw new Error("Registry ID is required");return t.getBuilderRegistryPopular(e,{limit:10,offset:0})},enabled:!!e,staleTime:YDr,retry:!1})}function e4r(e,t,n,r,s){const a=We();return yt({queryKey:["builder-registry",e,"preview",t,n,r],queryFn:async()=>{if(!e||!t||!n||!r)throw new Error("registryId, owner, repo, and skillPath are required");return(await a.getBuilderRegistryPreview(e,{owner:t,repo:n,path:r})).content},enabled:s?.enabled!==!1&&!!e&&!!t&&!!n&&!!r,retry:!1})}function t4r(e){const t=We(),n=Ur();return Rn({mutationFn:async r=>{if(!e)throw new Error("Registry ID is required");return t.installBuilderRegistrySkill(e,r)},onSuccess:()=>{n.invalidateQueries({queryKey:["stored-skills"]})}})}function n4r(e){if(!e)return null;const n=e.replace(/^https?:\/\//,"").replace(/^github\.com\//,"").split("/").filter(Boolean);return n.length<2?null:{owner:n[0],repo:n[1]}}function HZe(e){return`${e.topSource}/${e.name}`}function r4r({open:e,onOpenChange:t,registryId:n,registryLabel:r,installedSkillIds:s=[],onInstalled:a,onCollision:i}){const[l,c]=g.useState(""),[u,d]=g.useState(null),[f,p]=g.useState(null),{data:h,isLoading:m}=JDr(e?n:void 0),v=XDr(n),y=t4r(n),b=g.useMemo(()=>u?.topSource?n4r(u.topSource):null,[u]),{data:S,isLoading:x}=e4r(n,b?.owner,b?.repo,u?.name,{enabled:!!b&&!!u&&e}),k=My(L=>{L.trim().length>=2&&v.mutate(L)},300),_=g.useCallback(L=>{c(L),k(L)},[k]),C=g.useMemo(()=>l.trim().length>=2?v.data?.skills??[]:h?.skills??[],[l,v.data,h]),E=v.isPending,j=l.trim().length>=2,T=g.useMemo(()=>u?s.includes(u.name):!1,[u,s]),I=g.useMemo(()=>b?`https://github.com/${b.owner}/${b.repo}`:null,[b]),A=g.useCallback(async()=>{if(!(!u||!b)){p(null);try{const L=await y.mutateAsync({owner:b.owner,repo:b.repo,skillName:u.name});a?.(L.storedSkillId),t(!1)}catch(L){const M=L?.message??"Install failed";/409/.test(M)||/already exists/i.test(M)?(i?.(u.name),p("A skill with this name already exists. Open the existing skill instead.")):p(M)}}},[u,b,y,a,t,i]),R=g.useCallback(L=>{L||(c(""),d(null),p(null)),t(L)},[t]);return o.jsx(br,{open:e,onOpenChange:R,children:o.jsxs(xr,{className:"max-w-4xl h-[80vh] flex flex-col",children:[o.jsxs(wr,{children:[o.jsxs(gr,{children:["Browse ",r]}),o.jsxs(Ks,{children:["Find a public skill from ",r," and import it into your Builder skill library."]})]}),o.jsxs($r,{className:"flex-1 flex flex-col gap-4 overflow-hidden max-h-none",children:[o.jsxs("div",{className:"relative",children:[o.jsx(Ka,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-neutral3"}),o.jsx(Cn,{placeholder:`Search ${r}...`,value:l,onChange:L=>_(L.target.value),className:"pl-9","data-testid":"builder-add-skill-search"})]}),o.jsxs("div",{className:"flex flex-1 gap-4 min-h-0",children:[o.jsxs("div",{className:"w-1/2 flex flex-col min-h-0",children:[o.jsx("div",{className:"text-xs font-medium text-neutral4 uppercase tracking-wide mb-2",children:j?"Search results":"Popular skills"}),o.jsx(Br,{className:"flex-1 border border-border1 rounded-lg",children:m||E?o.jsx("div",{className:"flex items-center justify-center py-8",children:o.jsx(oa,{className:"h-6 w-6 animate-spin text-neutral3"})}):C.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-neutral4",children:[o.jsx(Kv,{className:"h-8 w-8 mb-2"}),o.jsx("p",{className:"text-sm",children:j?"No skills found":"No skills available"})]}):o.jsx("div",{className:"p-2 space-y-1",children:C.map(L=>{const M=HZe(L),z=s.includes(L.name),H=u?HZe(u):null;return o.jsx("button",{onClick:()=>d(L),className:X("w-full text-left px-3 py-2 rounded-md transition-colors","hover:bg-surface4",H===M&&"bg-surface5 border border-accent1"),children:o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"font-medium text-sm text-neutral6 truncate",children:L.name}),z&&o.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-accent1/20 text-accent1",children:[o.jsx(pa,{className:"h-2.5 w-2.5"}),"Installed"]})]}),o.jsx("div",{className:"text-xs text-neutral4 truncate",children:L.topSource})]}),o.jsxs("div",{className:"flex items-center gap-1 text-xs text-neutral3 shrink-0",children:[o.jsx(vf,{className:"h-3 w-3"}),o.jsx("span",{children:L.installs.toLocaleString()})]})]})},M)})})})]}),o.jsx("div",{className:"w-1/2 flex flex-col min-h-0 border border-border1 rounded-lg overflow-hidden",children:u?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"p-4 border-b border-border1 bg-surface3",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"p-2 rounded-lg bg-surface5",children:o.jsx($I,{className:"h-5 w-5 text-neutral4"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h3",{className:"font-semibold text-neutral6 truncate",children:u.name}),o.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-neutral4",children:[o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(wdt,{className:"h-3 w-3"}),u.topSource]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(vf,{className:"h-3 w-3"}),u.installs.toLocaleString()," installs"]})]})]}),I&&o.jsx("a",{href:I,target:"_blank",rel:"noopener noreferrer",className:"text-neutral4 hover:text-neutral5 transition-colors",title:"View on GitHub",children:o.jsx(ka,{className:"h-4 w-4"})})]})}),x?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(oa,{className:"h-6 w-6 animate-spin text-neutral3"})}):S?o.jsx(Br,{className:"flex-1",children:o.jsx("div",{className:"p-4",children:o.jsx(Gp,{children:S})})}):o.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-neutral4",children:[o.jsx(Kv,{className:"h-8 w-8 mb-2"}),o.jsx("p",{className:"text-sm",children:"Preview unavailable"})]})]}):o.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-neutral4",children:[o.jsx(Kv,{className:"h-8 w-8 mb-2"}),o.jsx("p",{className:"text-sm",children:"Select a skill to preview"})]})})]}),u&&o.jsxs("div",{className:"flex flex-col gap-3 pt-4 border-t border-border1",children:[f&&o.jsx("div",{className:"text-sm text-red-400 px-3 py-2 rounded-md bg-red-500/10 border border-red-500/20",children:f}),o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[o.jsx(le,{variant:"default",onClick:()=>R(!1),children:"Cancel"}),o.jsx(le,{variant:"primary",onClick:A,disabled:!b||y.isPending||T,"data-testid":"builder-install-skill-button",children:y.isPending?o.jsxs(o.Fragment,{children:[o.jsx(oa,{className:"h-4 w-4 mr-2 animate-spin"}),"Installing..."]}):T?o.jsxs(o.Fragment,{children:[o.jsx(pa,{className:"h-4 w-4 mr-2"}),"Already installed"]}):o.jsxs(o.Fragment,{children:[o.jsx(vf,{className:"h-4 w-4 mr-2"}),"Install"]})})]})]})]})]})})}function s4r(){const e=Hs(),{isLoading:t}=Cm(),{hasPermission:n,rbacEnabled:r}=dl(),s=!r||n("stored-skills:write"),a=!r||n("stored-skills:read"),[i,l]=g.useState(null),c=()=>e("/agent-builder/skills/create",{viewTransition:!0}),u=_=>e(`/agent-builder/skills/${_}/edit`,{viewTransition:!0}),{data:d,isLoading:f,error:p}=K1({enabled:!t}),[h,m]=g.useState(""),v=g.useMemo(()=>d?.skills??[],[d?.skills]),y=g.useMemo(()=>v.map(_=>_.id),[v]),{data:b}=KDr({enabled:a&&s}),S=g.useMemo(()=>b?.registries.find(_=>_.enabled)??null,[b]),x=_=>{u(_.id)},k=t||f?o.jsx(UCe,{}):p?ys(p)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ws,{})}):xs(p)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ds,{resource:"skills"})}):o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Hi,{title:"Failed to load skills",message:p.message})}):v.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(zr,{iconSlot:o.jsx(jg,{className:"h-8 w-8 text-neutral3"}),titleSlot:"No skills yet",descriptionSlot:"Create your first skill to give agents new capabilities.",actionSlot:s?o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(le,{variant:"primary",onClick:c,children:[o.jsx(Zr,{})," New skill"]}),S&&o.jsxs(le,{variant:"default",onClick:()=>l({id:S.id,label:S.label}),children:[o.jsx(vf,{})," Browse registry"]})]}):void 0})}):o.jsx(BCe,{skills:v,search:h,onSkillClick:x});return o.jsxs(o.Fragment,{children:[o.jsxs(Ft,{className:"px-4 md:px-10",children:[o.jsxs(Ft.TopArea,{children:[o.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4",children:[o.jsxs(Sf,{children:[o.jsxs(Sf.Title,{children:[o.jsx(jg,{})," My skills"]}),o.jsx(Sf.Description,{children:"Skills you've created."})]}),v.length>0&&s&&o.jsxs("div",{className:"w-full shrink-0 flex flex-col items-stretch gap-2 md:w-auto md:flex-row md:items-center",children:[S&&o.jsxs(le,{variant:"default",className:"w-full justify-center md:w-auto",onClick:()=>l({id:S.id,label:S.label}),children:[o.jsx(vf,{})," Browse registry"]}),o.jsxs(le,{variant:"primary",className:"w-full justify-center md:w-auto",onClick:c,children:[o.jsx(Zr,{})," New skill"]})]})]}),o.jsx("div",{className:"max-w-120",children:o.jsx($f,{onSearch:m,label:"Filter skills",placeholder:"Filter by name or description"})})]}),k]}),i&&o.jsx(r4r,{open:!!i,onOpenChange:_=>{_||l(null)},registryId:i.id,registryLabel:i.label,installedSkillIds:y,onInstalled:_=>{const C=v.find(E=>E.id===_);ru.success(C?`Imported "${C.name}"`:"Skill imported")},onCollision:_=>{const C=v.find(E=>E.id===_||E.name===_);C?ru.error(`"${C.name}" is already in your library`,{action:{label:"Open existing",onClick:()=>u(C.id)}}):ru.error(`A skill named "${_}" already exists.`)}})]})}const a4r=[{title:"Code reviewer",icon:Up,prompt:"Build a skill that reviews TypeScript code for type-safety issues, missing tests, and inconsistent patterns. Leave concrete suggestions with examples."},{title:"Doc summarizer",icon:jc,prompt:"Build a skill that summarizes long technical documents into a one-page brief with the key points, action items, and open questions."},{title:"Onboarding tutor",icon:Sdt,prompt:"Build a skill that onboards new engineers to a codebase. Explain the architecture, point to the right docs, and answer questions in plain English with code examples."},{title:"Research notes",icon:ldt,prompt:"Build a skill that turns messy research notes into structured findings with sources, methodology, and a tl;dr at the top."}],i4r=e=>e.length<=20?e:e.slice(0,20)+"…",o4r=()=>{const[e,t]=g.useState(""),n=Hs(),r=g.useRef(null),s=xCe(),a=y3(),{data:i}=WW(),{data:l}=z1(),c=g.useMemo(()=>(i?.workspaces??[]).filter(v=>v.status!=="archived").sort((v,y)=>(y.runtimeRegistered?1:0)-(v.runtimeRegistered?1:0)).map(v=>({value:v.id,label:v.name})),[i]),u=g.useMemo(()=>{const v=l?.configuration?.agent?.workspace;return v?.type==="id"?v.workspaceId:void 0},[l]),d=e.trim(),f=s.isPending,p=async v=>{if(v.preventDefault(),d.length===0||f)return;const y=QU(),b=u??(c.length===1?c[0].value:void 0);try{await s.mutateAsync({id:y,name:i4r(d),description:"",instructions:"",visibility:a,workspaceId:b,files:[]})}catch{De.error("Failed to start a new skill");return}n(`/agent-builder/skills/${y}/edit`,{state:{userMessage:d},viewTransition:!0})},h=v=>{f||v.key==="Enter"&&!v.shiftKey&&!v.nativeEvent.isComposing&&(v.preventDefault(),v.currentTarget.form?.requestSubmit())},m=v=>{t(v),r.current?.focus()};return o.jsx("div",{className:"starter-aurora flex min-h-full flex-col items-center justify-center bg-surface1 px-6 py-24",children:o.jsxs("div",{className:"relative z-10 flex w-full max-w-3xl flex-col gap-12",children:[o.jsx("h1",{className:"starter-heading text-center font-serif text-neutral6",style:{fontSize:"clamp(1.875rem, 3.5vw, 2.5rem)",lineHeight:1.1,letterSpacing:"-0.015em"},children:"What skill do you want to build?"}),o.jsx("form",{onSubmit:p,children:o.jsxs("div",{className:"starter-prompt rounded-2xl border border-border1 bg-surface2 transition-colors duration-normal ease-out-custom focus-within:border-neutral3",style:{viewTransitionName:"skill-chat-composer"},children:[o.jsx(Ml,{ref:r,testId:"skill-builder-starter-input",size:"default",variant:"unstyled",placeholder:"Describe the skill you want to build…",value:e,onChange:v=>t(v.target.value),onKeyDown:h,disabled:f,className:"min-h-[112px] resize-none px-5 py-4 text-ui-md outline-none placeholder:text-neutral3 focus:outline-none focus-visible:outline-none",rows:3}),o.jsx("div",{className:"flex items-center justify-end px-3 pb-2.5",children:o.jsx(le,{type:"submit",variant:"default",size:"icon-md",tooltip:"Start building",disabled:d.length===0||f,"data-testid":"skill-builder-starter-submit",className:"rounded-full",children:f?o.jsx("span",{"data-testid":"skill-builder-starter-submit-spinner",children:o.jsx(Kt,{})}):o.jsx($D,{})})})]})}),o.jsx("div",{className:"flex flex-wrap justify-center gap-2",children:a4r.map((v,y)=>{const b=v.icon;return o.jsxs("button",{type:"button",onClick:()=>m(v.prompt),"data-testid":`skill-builder-starter-example-${v.title.toLowerCase().replace(/\s+/g,"-")}`,style:{animationDelay:`${280+y*40}ms`},className:"starter-chip group inline-flex items-center gap-2 rounded-full border border-border1 bg-transparent px-4 py-2 text-ui-sm text-neutral4 transition-colors duration-normal ease-out-custom hover:border-border2 hover:bg-surface2 hover:text-neutral6",children:[o.jsx(b,{className:"h-3.5 w-3.5 text-neutral3 transition-colors group-hover:text-neutral5"}),v.title]},v.title)})})]})})};function l4r(){const{hasPermission:e,rbacEnabled:t}=dl(),n=!t||e("stored-skills:write");K1({enabled:n}),WW(),z1();const r=Hs();return n?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"absolute top-3 left-3 md:top-6 md:left-6 z-10",children:o.jsx(le,{size:"icon-sm",variant:"ghost",onClick:()=>r("/agent-builder/skills",{viewTransition:!0}),className:"rounded-full",tooltip:"Skills list",children:o.jsx(Rc,{})})}),o.jsx(o4r,{})]}):o.jsx(Vu,{to:"/agent-builder/skills",replace:!0})}function c4r(e){const t=We(),n=Ur();return Rn({mutationFn:()=>{if(!e)throw new Error("skillId is required for delete");return t.getStoredSkill(e).delete()},onSuccess:()=>{n.invalidateQueries({queryKey:["stored-skills"]}),e&&n.removeQueries({queryKey:["stored-skill",e]})}})}const r$t=({skillId:e})=>{const[t,n]=g.useState(!1),r=Hs(),s=c4r(e),a=async()=>{try{await s.mutateAsync(),De.success("Skill deleted"),n(!1),r("/agent-builder/skills",{viewTransition:!0})}catch(i){De.error(i instanceof Error?i.message:"Failed to delete skill")}};return{open:t,setOpen:n,isPending:s.isPending,confirm:a}},s$t=({open:e,onOpenChange:t,skillName:n,isPending:r,onConfirm:s})=>o.jsx(At,{open:e,onOpenChange:t,children:o.jsxs(At.Content,{"data-testid":"skill-builder-delete-skill-dialog",children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete skill?"}),o.jsxs(At.Description,{children:['This permanently deletes "',n,'". This cannot be undone.']})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{"data-testid":"skill-builder-delete-skill-cancel",disabled:r,children:"Cancel"}),o.jsx(le,{variant:"primary","data-testid":"skill-builder-delete-skill-confirm",disabled:r,onClick:()=>{s()},children:r?"Deleting…":"Delete skill"})]})]})}),u4r=({skillId:e,skillName:t,disabled:n=!1})=>{const{open:r,setOpen:s,isPending:a,confirm:i}=r$t({skillId:e});return o.jsxs(o.Fragment,{children:[o.jsxs(le,{size:"lg",variant:"default",onClick:()=>s(!0),disabled:n||a,className:"w-full","data-testid":"skill-builder-delete-skill",children:[o.jsx(uu,{}),o.jsx("span",{children:"Delete skill"})]}),o.jsx(s$t,{open:r,onOpenChange:s,skillName:t,isPending:a,onConfirm:i})]})},d4r=({skillId:e,skillName:t,disabled:n=!1})=>{const{open:r,setOpen:s,isPending:a,confirm:i}=r$t({skillId:e});return o.jsxs(o.Fragment,{children:[o.jsxs(dt.Item,{"data-testid":"skill-builder-mobile-menu-delete",disabled:n,className:"text-red-500 focus:text-red-400",onSelect:l=>{l.preventDefault(),s(!0)},children:[o.jsx(uu,{}),o.jsx("span",{children:"Delete skill"})]}),o.jsx(s$t,{open:r,onOpenChange:s,skillName:t,isPending:a,onConfirm:i})]})};function a$t(e,t){const n=[];for(const r of e){const s=t?`${t}/${r.name}`:r.name;r.type==="file"&&r.content!==void 0?n.push({path:s,content:r.content}):r.type==="folder"&&r.children&&n.push(...a$t(r.children,s))}return n}function VCe(e={}){const t=We(),n=Ur(),r=u2t(),{hasPermission:s}=dl(),a=s("workspaces:write"),{silent:i=!1}=e;return Rn({mutationFn:async l=>{const{id:c,name:u,description:d,visibility:f,instructions:p,files:h,workspaceId:m}=l;if(h?.length&&m&&a){const S=a$t(h,"");try{await Promise.all(S.map(x=>r.mutateAsync({workspaceId:m,path:`skills/${x.path}`,content:x.content,recursive:!0})))}catch(x){console.warn("[skill] Workspace file write failed, saving to DB only:",x)}}const v=p??(h?YU(h):void 0),y=h?a2t(h):void 0,b={};return u!==void 0&&(b.name=u),d!==void 0&&(b.description=d),f!==void 0&&(b.visibility=f),v!==void 0&&(b.instructions=v),y!==void 0&&(b.license=y),h!==void 0&&(b.files=h),t.getStoredSkill(c).update(b)},onSuccess:()=>{n.invalidateQueries({queryKey:["stored-skills"]}),n.invalidateQueries({queryKey:["stored-skill"]}),i||De.success("Skill updated")},onError:l=>{i||De.error(`Failed to update skill: ${l instanceof Error?l.message:"Unknown error"}`)}})}const f4r={public:{title:"Add this skill to your library?",description:"Adding this skill to the library means your teammates will be able to discover and use it.",toast:"Skill added to the library"},private:{title:"Remove this skill from your library?",description:"Removing this skill from the library means your teammates will no longer be able to discover or use it. You will be the only person with access.",toast:"Skill removed from the library"}};function i$t(e){const t=Vr(),n=VCe({silent:!0});return MRt({copy:f4r,isPending:n.isPending,mutate:r=>n.mutateAsync({id:e,visibility:r}),onSuccess:r=>{t.setValue("visibility",r,{shouldDirty:!1})},testIds:{dialog:"skill-builder-visibility-confirm-dialog",cancel:"skill-builder-visibility-confirm-cancel",confirm:"skill-builder-visibility-confirm-yes"}})}function p4r({skillId:e,showSetVisibility:t=!1,showDelete:n=!1,skillName:r="",disabled:s=!1}){return!t&&!n?null:o.jsx("div",{className:"lg:hidden","data-testid":"skill-builder-mobile-menu",children:o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsx(le,{size:"icon-sm",variant:"ghost",tooltip:"More actions","data-testid":"skill-builder-mobile-menu-trigger",children:o.jsx(DD,{})})}),o.jsxs(dt.Content,{align:"end",children:[t&&o.jsx(h4r,{skillId:e,disabled:s}),t&&n&&o.jsx(dt.Separator,{}),n&&o.jsx(d4r,{skillId:e,skillName:r,disabled:s})]})]})})}function h4r({skillId:e,disabled:t}){const n=Vr(),r=Mn({control:n.control,name:"visibility"})??"private",{requestChange:s,dialog:a}=i$t(e);return o.jsxs(o.Fragment,{children:[r==="private"?o.jsxs(dt.Item,{"data-testid":"skill-builder-mobile-menu-visibility-add",disabled:t,closeOnClick:!1,onSelect:()=>{s("public")},children:[o.jsx(Ux,{}),o.jsx("span",{children:"Add to library"})]}):o.jsxs(dt.Item,{"data-testid":"skill-builder-mobile-menu-visibility-remove",disabled:t,closeOnClick:!1,onSelect:()=>{s("private")},children:[o.jsx(Cf,{}),o.jsx("span",{children:"Remove from library"})]}),a]})}function m4r({skillId:e}){const t=Vr(),n=Mn({control:t.control,name:"visibility"})??"private",{requestChange:r,dialog:s}=i$t(e);return o.jsxs(o.Fragment,{children:[n==="private"?o.jsxs(le,{size:"sm",variant:"default",onClick:()=>r("public"),"data-testid":"skill-builder-visibility-add",children:[o.jsx(Ux,{className:"h-3.5 w-3.5"}),"Add to library"]}):o.jsxs(le,{size:"sm",variant:"ghost",onClick:()=>r("private"),"data-testid":"skill-builder-visibility-remove",children:[o.jsx(Cf,{className:"h-3.5 w-3.5"}),"Remove from library"]}),s]})}const g4r=600,v4r=2e3;function y4r({skillId:e,debounceMs:t=g4r,savedDisplayMs:n=v4r}){const r=Vr(),s=VCe({silent:!0}),[a,i]=g.useState("idle"),[l,c]=g.useState(null),u=g.useRef(r.getValues()),d=g.useRef(0),f=g.useRef(null),p=()=>{f.current&&(clearTimeout(f.current),f.current=null)},h=g.useCallback(async()=>{const b=++d.current,S=u.current;p(),i("saving"),c(null);try{const x=kk(S.name||"untitled"),k=S.name?s2t(x,S.name):x,_=Ev(k,"skill-md",S.instructions??"");if(await s.mutateAsync({id:e,name:S.name,description:S.description,instructions:S.instructions,visibility:S.visibility,workspaceId:S.workspaceId,files:_}),b!==d.current)return;i("saved"),f.current=setTimeout(()=>{f.current=null,i("idle")},n)}catch(x){if(b!==d.current)return;i("error"),c(x instanceof Error?x:new Error(String(x)))}},[e,s,n]),m=My(()=>{h()},t);g.useEffect(()=>{const b=r.watch(S=>{u.current=S,m()});return()=>{b.unsubscribe()}},[r,m]),g.useEffect(()=>()=>{m.flush(),p()},[m]);const v=g.useCallback(()=>{h()},[h]),y=g.useCallback(()=>{m.flush()},[m]);return{status:a,lastError:l,retry:v,flushNow:y}}function o$t(e){const t=We();return yt({queryKey:["stored-skill",e],queryFn:()=>t.getStoredSkill(e).details(),enabled:!!e})}const b4r=({title:e,rightAside:t,primaryAction:n,mobileExtra:r,showForm:s=!0,chat:a,form:i,deleteAction:l})=>{const c=Hs(),[u,d]=g.useState("chat");return o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2 bg-surface1 px-3 py-2 md:px-6 md:py-3",children:[o.jsx(le,{size:"icon-sm",variant:"ghost",onClick:()=>c("/agent-builder/skills",{viewTransition:!0}),className:"rounded-full",tooltip:"Skills list","data-testid":"skill-edit-back-button",children:o.jsx(Rc,{})}),o.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[o.jsx("div",{className:"min-w-0 truncate text-ui-md text-neutral6",children:e}),t&&o.jsx("div",{className:"shrink-0",children:t})]}),n&&o.jsx("div",{className:"shrink-0",children:n}),r&&o.jsx("div",{className:"shrink-0 lg:hidden",children:r})]}),s&&o.jsx("div",{className:"md:hidden px-4 pt-4 pb-2",children:o.jsxs("div",{role:"tablist","aria-label":"Workspace view",className:"relative mx-auto flex h-9 w-full max-w-sm items-center rounded-full border border-border1 bg-surface3 p-0.5",children:[o.jsx("span",{"aria-hidden":"true",className:X("absolute inset-y-0.5 left-0.5 w-[calc(50%-2px)] rounded-full bg-surface4","transition-transform duration-200 ease-out",u==="configure"&&"translate-x-full")}),o.jsx("button",{type:"button",role:"tab","aria-selected":u==="chat","data-testid":"skill-edit-tab-chat",onClick:()=>d("chat"),className:X("relative z-10 flex-1 rounded-full text-ui-md font-medium outline-none","transition-colors duration-200",u==="chat"?"text-neutral5":"text-neutral3 hover:text-neutral4"),children:"Chat"}),o.jsx("button",{type:"button",role:"tab","aria-selected":u==="configure","data-testid":"skill-edit-tab-configure",onClick:()=>d("configure"),className:X("relative z-10 flex-1 rounded-full text-ui-md font-medium outline-none","transition-colors duration-200",u==="configure"?"text-neutral5":"text-neutral3 hover:text-neutral4"),children:"Configuration"})]})}),o.jsxs("div",{className:X("grid min-h-0 flex-1 grid-cols-1",s&&"md:grid-cols-[1fr_minmax(360px,40%)]"),children:[o.jsx("div",{className:X("min-w-0 min-h-0 overflow-hidden bg-surface1",s&&u!=="chat"?"hidden":"block","md:block","md:transition-[grid-column] md:duration-300 md:ease-out"),children:o.jsx("div",{className:"flex h-full min-h-0 flex-col px-4 pt-4 pb-6 md:px-10",children:o.jsx("div",{className:"flex min-h-0 flex-1 flex-col md:max-w-[80ch] md:mx-auto w-full",children:a})})}),s&&o.jsx("div",{className:X("min-w-0 min-h-0 overflow-hidden bg-surface1",u==="configure"?"block":"hidden","md:block","px-4 pb-6 md:p-4 md:bg-transparent"),"data-testid":"skill-edit-configure-panel",children:o.jsxs("div",{className:X("skill-panel-slide-in flex h-full min-h-0 flex-col overflow-hidden","md:rounded-3xl md:border md:border-border1 md:bg-surface2"),children:[o.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:i}),l&&o.jsx("div",{className:"border-t border-border1 px-4 pb-4 pt-4 md:px-6","data-testid":"skill-edit-delete-action",children:l})]})})]})]})},l$t="skillBuilderTool",c$t="readSkillForm",WZe=`# Role
|
|
497
497
|
You help a user build a skill: a focused set of instructions that gives an agent expertise in a specific area.
|
|
498
498
|
|
|
499
499
|
Use simple, kind words. Avoid jargon.
|
|
@@ -730,7 +730,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
|
|
|
730
730
|
}
|
|
731
731
|
]`})]})]})}function Fis({errors:e,maxErrors:t=5}){if(e.length===0)return null;const n=e.slice(0,t),r=e.length-t;return o.jsxs("div",{className:"bg-accent2/10 border border-accent2/30 rounded-md p-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-accent2 mb-2",children:[o.jsx(qe,{children:o.jsx(yf,{className:"w-4 h-4"})}),o.jsxs("span",{className:"font-medium text-sm",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-sm text-accent2/80 space-y-1",children:n.map((s,a)=>o.jsxs("li",{className:"flex gap-2",children:[o.jsx("span",{className:"shrink-0",children:"•"}),o.jsx("span",{children:s.message})]},a))}),r>0&&o.jsxs("div",{className:"text-xs text-accent2/60 mt-2",children:["+",r," more error",r!==1?"s":""]})]})}function zis({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("upload"),[i,l]=g.useState(null),[c,u]=g.useState({current:0,total:0}),[d,f]=g.useState(null),[p,h]=g.useState(!1),{parseFile:m,isParsing:v,error:y}=fas(),{batchInsertItems:b}=Ii(),S=g.useCallback(async I=>{try{const A=await m(I);l(A),a("preview")}catch{}},[m]),x=g.useCallback(async()=>{if(!i||i.items.length===0)return;a("importing"),h(!0);const{items:I}=i;u({current:0,total:I.length});try{await b.mutateAsync({datasetId:e,items:I.map(A=>({input:A.input,groundTruth:A.groundTruth,metadata:A.metadata}))}),f({success:I.length,errors:0})}catch{f({success:0,errors:I.length})}u({current:I.length,total:I.length}),h(!1),a("complete")},[i,b,e]),k=g.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&De.success(`Imported ${d.success} item${d.success!==1?"s":""}`),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150)},[n,r,d]),_=g.useCallback(()=>{p||(n(!1),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150))},[p,n]),C=i&&i.items.length>0&&i.errors.length===0,E=()=>{switch(s){case"upload":return o.jsx(Lis,{onFileSelect:S,isParsing:v,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(Fis,{errors:i.errors}),o.jsx("div",{className:"text-sm text-neutral4",children:"Please fix the errors in your JSON file and try again."})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-sm text-neutral4",children:["Found ",i.items.length," valid item",i.items.length!==1?"s":""," to import."]}),o.jsx(Dis,{items:i.items,maxRows:5})]})}):null;case"importing":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx(Kt,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-lg font-medium text-neutral1",children:"Importing items..."}),o.jsxs("div",{className:"text-sm text-neutral4 mt-1",children:[c.current," of ",c.total]})]})]});case"complete":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx("div",{className:"text-4xl",children:d&&d.errors===0?"✓":"⚠"}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-lg font-medium text-neutral1",children:"Import Complete"}),o.jsxs("div",{className:"text-sm text-neutral4 mt-1",children:[d?.success??0," item",d?.success!==1?"s":""," imported",d&&d.errors>0&&o.jsxs("span",{className:"text-accent2",children:[" ","(",d.errors," error",d.errors!==1?"s":"",")"]})]})]})]})}},j=()=>{switch(s){case"upload":return o.jsx(le,{onClick:_,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(le,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(le,{variant:"primary",onClick:x,disabled:!C,children:["Import ",i?.items.length??0," Item",i?.items.length!==1?"s":""]})]});case"importing":return null;case"complete":return o.jsx(le,{variant:"primary",onClick:k,children:"Done"})}},T={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(br,{open:t,onOpenChange:_,children:o.jsxs(xr,{className:"max-w-2xl max-h-[90vh]",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:T[s]}),o.jsx(Ks,{children:"Import dataset items from a JSON file."})]}),o.jsx($r,{className:"min-h-[200px] max-h-[50vh] overflow-y-auto",children:E()}),o.jsx(Nc,{className:"px-6 pt-4 flex justify-end gap-2",children:j()})]})})}const JNe=e=>{const t=We(),{data:n}=SD(e),r=n?.experiments;return yt({queryKey:["dataset-review-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="needs-review").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})},Bis=e=>{const t=We(),{data:n}=SD(e),r=n?.experiments;return yt({queryKey:["dataset-completed-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="complete").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})};function Uis(e,t){if(typeof e=="string")return e.length>t?e.slice(0,t)+"...":e;try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"...":n}catch{return String(e)}}function s7t({datasetId:e,experimentId:t,featuredItemId:n}){const r=We(),{data:s}=Qx(e),{data:a,isLoading:i}=JNe(e),{data:l,isLoading:c}=Bis(e),u=g.useMemo(()=>t?(a??[]).filter(je=>je.experimentId===t):a,[a,t]),d=g.useMemo(()=>t?(l??[]).filter(je=>je.experimentId===t):l,[l,t]),{updateExperimentResult:f}=Ii(),[p,h]=g.useState(n??null);g.useEffect(()=>{n!==void 0&&h(n)},[n]);const[m,v]=g.useState(null),[y,b]=g.useState(new Set),[S,x]=g.useState(!1),[k,_]=g.useState(!1),[C,E]=g.useState(!1),[j,T]=g.useState(""),[I,A]=g.useState(""),[R,L]=g.useState(""),[M,z]=g.useState([]),[H,F]=g.useState(!1),[B,q]=g.useState(null),D=g.useMemo(()=>B??u??[],[B,u]);g.useEffect(()=>{q(null)},[e,t]),g.useEffect(()=>{u&&B===null&&q(u)},[u,B]);const G=g.useMemo(()=>{const je=new Set;if(s?.tags)for(const Ce of s.tags)je.add(Ce);for(const Ce of D)for(const Ee of Ce.tags)je.add(Ee);return[...je].sort()},[s,D]),V=g.useCallback(je=>{!s||!e||(s.tags??[]).includes(je)},[s,e]),$=g.useMemo(()=>m?m==="__untagged__"?D.filter(je=>je.tags.length===0):D.filter(je=>je.tags.includes(m)):D,[D,m]),U=g.useMemo(()=>{const je=new Map;for(const Ce of D)for(const Ee of Ce.tags)je.set(Ee,(je.get(Ee)??0)+1);return[...je.entries()].sort((Ce,Ee)=>Ee[1]-Ce[1])},[D]),Z=g.useMemo(()=>D.filter(je=>je.tags.length===0).length,[D]),K=g.useMemo(()=>{let je=0;return m&&je++,S&&je++,je},[m,S]),ne=g.useCallback((je,Ce)=>{q(Oe=>(Oe??[]).map(Re=>Re.id===je?{...Re,tags:Ce}:Re));const Ee=D.find(Oe=>Oe.id===je);Ee?.experimentId&&Ee?.datasetId&&f.mutate({datasetId:Ee.datasetId,experimentId:Ee.experimentId,resultId:Ee.id,tags:Ce})},[D,f]),te=g.useCallback((je,Ce)=>{const Ee=D.find(Oe=>Oe.id===je);Ee?.traceId&&Ce!==void 0&&r.createFeedback({feedback:{traceId:Ee.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:Ce==="positive"?1:-1,experimentId:Ee.experimentId??void 0,sourceId:Ee.id}}).catch(()=>{}),q(Oe=>(Oe??[]).map(Re=>Re.id===je?{...Re,rating:Ce}:Re))},[D,r]),J=g.useCallback((je,Ce)=>{const Ee=D.find(Oe=>Oe.id===je);Ee?.traceId&&r.createFeedback({feedback:{traceId:Ee.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:Ce,comment:Ce,experimentId:Ee.experimentId??void 0,sourceId:Ee.id}}).catch(()=>{}),q(Oe=>(Oe??[]).map(Re=>Re.id===je?{...Re,comment:Ce}:Re))},[D,r]),ae=g.useCallback(je=>{const Ce=D.find(Ee=>Ee.id===je);q(Ee=>(Ee??[]).filter(Oe=>Oe.id!==je)),b(Ee=>{const Oe=new Set(Ee);return Oe.delete(je),Oe}),p===je&&h(null),Ce?.experimentId&&Ce?.datasetId&&f.mutate({datasetId:Ce.datasetId,experimentId:Ce.experimentId,resultId:Ce.id,status:null})},[D,f,p]),pe=g.useCallback(je=>{const Ce=D.find(Ee=>Ee.id===je);q(Ee=>(Ee??[]).filter(Oe=>Oe.id!==je)),b(Ee=>{const Oe=new Set(Ee);return Oe.delete(je),Oe}),p===je&&h(null),Ce?.experimentId&&Ce?.datasetId&&f.mutate({datasetId:Ce.datasetId,experimentId:Ce.experimentId,resultId:Ce.id,status:"complete"})},[D,f,p]),Y=g.useMemo(()=>{const je=S?d??[]:$;return!S||!m?je:m==="__untagged__"?je.filter(Ce=>Ce.tags.length===0):je.filter(Ce=>Ce.tags.includes(m))},[S,d,$,m]),ee=S?c:!1,ce=g.useMemo(()=>new Set(Y.map(je=>je.id)),[Y]),de=g.useMemo(()=>[...y].filter(je=>ce.has(je)).length,[y,ce]),oe=Y.length>0&&de===Y.length,me=de>0&&!oe,be=g.useCallback(je=>{b(Ce=>{const Ee=new Set(Ce);return Ee.has(je)?Ee.delete(je):Ee.add(je),Ee})},[]),we=g.useCallback(()=>{b(oe?new Set:new Set(Y.map(je=>je.id)))},[oe,Y]),Te=g.useCallback(je=>{for(const Ce of y){const Ee=D.find(Oe=>Oe.id===Ce);Ee&&!Ee.tags.includes(je)&&ne(Ce,[...Ee.tags,je])}},[D,y,ne]),ke=g.useCallback(je=>{for(const Ce of y){const Ee=D.find(Oe=>Oe.id===Ce);Ee&&Ee.tags.includes(je)&&ne(Ce,Ee.tags.filter(Oe=>Oe!==je))}},[D,y,ne]),Ae=g.useCallback(()=>{for(const je of y)pe(je);b(new Set)},[y,pe]),ze=g.useCallback(()=>{for(const je of y)ae(je);b(new Set)},[y,ae]),ue=g.useCallback(()=>{T(""),E(!0)},[]),re=g.useCallback(async()=>{if(!(!I||!R)){_(!0),E(!1);try{const je=D.filter(Ee=>y.has(Ee.id));if(je.length===0){_(!1);return}const Ce=await r.clusterFailures({modelId:`${I}/${R}`,items:je.map(Ee=>({id:Ee.id,input:Ee.input,output:Ee.output??void 0,error:typeof Ee.error=="string"?Ee.error:Ee.error?String(Ee.error):void 0,scores:Ee.scores,existingTags:Ee.tags.length>0?Ee.tags:void 0})),availableTags:G.length>0?G:void 0,prompt:j||void 0});Ce.proposedTags&&Ce.proposedTags.length>0&&(z(Ce.proposedTags.map(Ee=>({...Ee,accepted:!0}))),F(!0))}catch(je){console.error("Analysis failed:",je)}finally{_(!1)}}},[I,R,D,y,r,G,j]),se=g.useCallback(()=>{for(const je of M){if(!je.accepted)continue;const Ce=D.find(Ee=>Ee.id===je.itemId);if(Ce){const Ee=[...new Set([...Ce.tags,...je.tags])];ne(Ce.id,Ee)}}F(!1)},[M,D,ne]),he=g.useCallback(je=>{h(Ce=>Ce===je?null:je)},[]),xe=g.useMemo(()=>p?Y.find(je=>je.id===p)??null:null,[p,Y]),Ne=p?Y.findIndex(je=>je.id===p):-1,Pe=Ne>0?()=>h(Y[Ne-1].id):void 0,Qe=Ne>=0&&Ne<Y.length-1?()=>h(Y[Ne+1].id):void 0,Ze="auto minmax(15rem,1fr) 10rem 8rem 6rem 6rem";return i?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(Kt,{className:"w-6 h-6"})}):o.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[o.jsx(br,{open:C,onOpenChange:E,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Analyze Items"}),o.jsx(Ks,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx(Dt,{className:"text-xs mb-1 block",children:"Provider"}),o.jsx(Vy,{value:I,onValueChange:A})]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"text-xs mb-1 block",children:"Model"}),o.jsx(qy,{llmId:I,value:R,onValueChange:L})]})]}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3",children:[y.size," item",y.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx(Ml,{value:j,onChange:je=>T(je.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"text-xs mt-1"})]})]}),o.jsxs(Nc,{children:[o.jsx(le,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),o.jsxs(le,{onClick:re,disabled:!I||!R||k,children:[k?o.jsx(Kt,{className:"w-4 h-4 mr-1"}):null,"Analyze"]})]})]})}),o.jsx(br,{open:H,onOpenChange:F,children:o.jsxs(xr,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Review Proposed Tags"}),o.jsxs(Ks,{children:[M.filter(je=>je.accepted).length," of ",M.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:M.map((je,Ce)=>{const Ee=D.find(Oe=>Oe.id===je.itemId);return o.jsx("div",{className:X("p-3 border rounded-lg",!je.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(Bo,{checked:je.accepted,onCheckedChange:Oe=>z(Re=>Re.map((Ue,Ye)=>Ye===Ce?{...Ue,accepted:!!Oe}:Ue))}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 truncate block",children:Ee?typeof Ee.input=="string"?Ee.input.slice(0,100):JSON.stringify(Ee.input).slice(0,100):je.itemId}),o.jsx("div",{className:"flex gap-1 flex-wrap mt-1.5",children:je.tags.map((Oe,Re)=>o.jsx(I9t,{tag:Oe,onRename:Ue=>z(Ye=>Ye.map((et,Mt)=>Mt===Ce?{...et,tags:et.tags.map((Rt,wt)=>wt===Re?Ue:Rt)}:et)),onRemove:()=>z(Ue=>Ue.map((Ye,et)=>et===Ce?{...Ye,tags:Ye.tags.filter((Mt,Rt)=>Rt!==Re)}:Ye))},`${Oe}-${Re}`))}),je.reason&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:je.reason})]})]})},je.itemId)})}),o.jsxs(Nc,{children:[o.jsx(le,{variant:"outline",onClick:()=>F(!1),children:"Cancel"}),o.jsxs(le,{onClick:se,disabled:M.filter(je=>je.accepted).length===0,children:["Accept ",M.filter(je=>je.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:X("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",xe&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid gap-8 content-start w-full overflow-y-auto",children:[o.jsxs("div",{className:"flex items-center justify-between w-full flex-wrap gap-4 gap-x-6",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsxs(le,{variant:"outline",size:"md",children:[o.jsx(bdt,{}),"Filter",K>0&&o.jsx("span",{className:X("ml-0.5 inline-flex items-center justify-center rounded-full bg-accent1/50 text-neutral5 text-ui-sm w-5 h-5"),children:K})]})}),o.jsxs(dt.Content,{align:"start",className:X("min-w-48"),children:[o.jsxs(dt.Sub,{children:[o.jsxs(dt.SubTrigger,{children:["Status",S&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(dt.SubContent,{children:[o.jsx(dt.CheckboxItem,{checked:!S,onCheckedChange:()=>{x(!1),h(null)},onSelect:je=>je.preventDefault(),children:"Review Queue"}),o.jsx(dt.CheckboxItem,{checked:S,onCheckedChange:()=>{x(!0),h(null)},onSelect:je=>je.preventDefault(),children:"Completed"})]})]}),o.jsxs(dt.Sub,{children:[o.jsxs(dt.SubTrigger,{children:["Tags",m&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(dt.SubContent,{children:[o.jsx(dt.CheckboxItem,{checked:!m,onCheckedChange:()=>v(null),onSelect:je=>je.preventDefault(),children:"All"}),Z>0&&o.jsx(dt.CheckboxItem,{checked:m==="__untagged__",onCheckedChange:()=>v(m==="__untagged__"?null:"__untagged__"),onSelect:je=>je.preventDefault(),children:"Untagged"}),U.length>0&&o.jsx(dt.Separator,{}),U.map(([je])=>o.jsx(dt.CheckboxItem,{checked:m===je,onCheckedChange:()=>v(m===je?null:je),onSelect:Ce=>Ce.preventDefault(),children:je},je))]})]}),K>0&&o.jsxs(o.Fragment,{children:[o.jsx(dt.Separator,{}),o.jsxs(dt.Item,{onSelect:()=>{v(null),x(!1),h(null)},children:[o.jsx(bs,{}),"Clear all filters"]})]})]})]}),K>0&&o.jsxs(le,{variant:"outline",size:"md",onClick:()=>{v(null),x(!1),h(null)},children:[o.jsx(bs,{}),"Reset"]})]}),!S&&y.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(N9t,{selectedCount:y.size,vocabulary:G,onApplyTag:Te,onRemoveTag:ke,onNewTag:je=>Te(je)}),o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsxs(le,{disabled:k,children:[k?o.jsx(Kt,{className:"w-4 h-4"}):o.jsx(qe,{size:"sm",children:o.jsx(Ia,{})}),"Actions"]})}),o.jsxs(dt.Content,{align:"end",children:[o.jsxs(dt.Item,{onSelect:Ae,children:[o.jsx(qe,{size:"sm",children:o.jsx(SO,{})}),"Complete"]}),o.jsxs(dt.Item,{onSelect:ze,children:[o.jsx(qe,{size:"sm",children:o.jsx(uu,{})}),"Remove"]}),o.jsx(dt.Separator,{}),o.jsxs(dt.Item,{onSelect:ue,children:[o.jsx(qe,{size:"sm",children:o.jsx(jg,{})}),"Analyze"]})]})]})]})]}),ee?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(Kt,{className:"w-6 h-6"})}):Y.length===0?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsxs("div",{className:"text-center px-8",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 block",children:S?"No completed reviews yet":"No items to review"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-2 block",children:S?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})]})}):o.jsxs(ve,{columns:Ze,className:"min-w-0",children:[o.jsxs(ve.Top,{hasLeadingCell:!0,children:[S?o.jsx(ve.TopCell,{children:" "}):o.jsx(ve.TopSelectCell,{checked:oe?!0:me?"indeterminate":!1,onToggle:()=>we(),"aria-label":"Select all"}),o.jsxs(ve.TopCells,{colStart:2,children:[o.jsx(ve.TopCell,{children:"Input"}),o.jsx(ve.TopCell,{children:"Comment"}),o.jsx(ve.TopCell,{children:"Tags"}),o.jsx(ve.TopCell,{children:"Rating"}),o.jsx(ve.TopCell,{children:"Scores"})]})]}),Y.map(je=>{const Ce=je.scores?Object.entries(je.scores):[],Ee=p===je.id,Oe=o.jsxs(o.Fragment,{children:[o.jsx(ve.Cell,{height:"compact",className:"min-w-0 text-neutral4",children:o.jsx("span",{className:"block truncate",children:Uis(je.input,200)})}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:je.comment?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 truncate",children:je.comment}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:je.tags.length>0?o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 truncate",children:je.tags.join(", ")}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(ve.Cell,{height:"compact",children:[je.rating==="positive"&&o.jsx(qe,{size:"sm",className:"text-positive1",children:o.jsx(Nxe,{})}),je.rating==="negative"&&o.jsx(qe,{size:"sm",className:"text-negative1",children:o.jsx(Txe,{})}),!je.rating&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(ve.Cell,{height:"compact",children:Ce.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:o.jsx(im,{})}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 font-mono",children:Ce[0][1].toFixed(2)}),Ce.length>1&&o.jsxs(un,{variant:"default",children:["+",Ce.length-1]})]}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(ve.RowWrapper,{children:[S?o.jsx(ve.Cell,{height:"compact",className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":je.error?"Error":"Success",title:je.error?"Error":"Success",className:X("w-2 h-2 rounded-full",je.error?"bg-red-700":"bg-green-600")})}):o.jsx(ve.SelectCell,{checked:y.has(je.id),onToggle:()=>be(je.id),"aria-label":`Select item ${je.id}`}),o.jsx(ve.RowButton,{flushLeft:!0,colStart:2,featured:Ee,onClick:()=>he(je.id),children:Oe})]},je.id)})]})]}),xe&&o.jsx(T9t,{item:xe,isCompleted:S,tagVocabulary:G,onRate:je=>te(xe.id,je),onSetTags:je=>{ne(xe.id,je);for(const Ce of je)G.includes(Ce)||V(Ce)},onComment:je=>J(xe.id,je),onRemove:()=>ae(xe.id),onComplete:S?void 0:()=>pe(xe.id),onPrevious:Pe,onNext:Qe,onClose:()=>h(null)})]})]})}function Vis({datasetId:e,onAddItemClick:t,onNavigateToDataset:n}){const{navigate:r}=bn(),[s,a]=Pi(),{tab:i,activeVersion:l,handleTabChange:c}=KNe(s,a),[u,d]=g.useState(!1),[f,p]=g.useState(!1),[h,m]=g.useState(!1),[v,y]=g.useState([]),[b,S]=g.useState(!1),[x,k]=g.useState([]),[_,C]=g.useState(!1),[E,j]=g.useState([]),[T,I]=g.useState(0),[A,R]=g.useState(null),[L,M]=g.useState(""),[z]=Ywe(L,300),{data:H}=Qx(e),{data:F=[],total:B,isLoading:q,setEndOfListElement:D,isFetchingNextPage:G,hasNextPage:V}=I1(e,z||void 0,l),{total:$}=I1(e,void 0,l),[U,Z]=g.useState({}),{data:K,isLoading:ne}=SD(e,void 0,U),{data:te}=SD(e),{deleteItems:J}=Ii(),ae=K?.experiments??[],pe=te?.experiments??[],Y=qas({hasSearchQuery:!!z,filteredItemsLength:F.length,unfilteredItemsTotal:$,itemsTotal:B}),{data:ee}=JNe(e),ce=ee?.length??0,de=se=>{R(se)},oe=()=>{R(null)},me=se=>{y(se),m(!0)},be=se=>{k(se),S(!0)},we=se=>{S(se),se||(k([]),I(he=>he+1))},Te=se=>{r(`/datasets/${e}/items?items=${se.join(",")}`)},ke=se=>{r(`/datasets/${e}/versions?ids=${se.join(",")}`)},Ae=se=>{j(se),C(!0)},ze=async()=>{await J.mutateAsync({datasetId:e,itemIds:E}),De.success(`Deleted ${E.length} items`),C(!1),j([]),I(se=>se+1)},ue=se=>{m(!1),y([]),I(he=>he+1),n?.(se)},re=se=>{m(se),se||(y([]),I(he=>he+1))};return o.jsxs(o.Fragment,{children:[o.jsxs(Lc,{defaultTab:"items",value:i,onValueChange:c,className:"grid grid-rows-[auto_1fr] h-full",children:[o.jsxs(Dc,{children:[o.jsxs(Rr,{value:"items",children:["Items ",o.jsx(ea,{color:"gray",children:Y})]}),o.jsxs(Rr,{value:"experiments",children:["Experiments",o.jsx(ea,{color:"gray",children:ae.length})]}),o.jsxs(Rr,{value:"review",children:["Review",ce>0&&o.jsx(ea,{color:"orange",children:ce})]})]}),o.jsx(Xr,{value:"items",className:"grid overflow-auto mt-5 pb-0",children:o.jsx(Mis,{datasetId:e,items:F,isLoading:q,featuredItemId:A,onItemSelect:de,onItemClose:oe,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>p(!0),onBulkDeleteClick:Ae,onCreateDatasetClick:me,onAddToDatasetClick:be,onCompareItemsClick:Te,datasetName:H?.name,clearSelectionTrigger:T,setEndOfListElement:D,isFetchingNextPage:G,hasNextPage:V,searchQuery:L,activeSearchQuery:z,onSearchChange:M,currentDatasetVersion:H?.version,onCompareVersionsClick:ke})}),o.jsx(Xr,{value:"experiments",className:"grid overflow-auto mt-5 pb-0",children:o.jsx(ois,{experiments:ae,allExperiments:pe,isLoading:ne,datasetId:e,filters:U,onFiltersChange:Z})}),o.jsx(Xr,{value:"review",className:"overflow-auto mt-2 pb-0",children:o.jsx(s7t,{datasetId:e})})]}),o.jsx(Jas,{datasetId:e,open:u,onOpenChange:d}),o.jsx(zis,{datasetId:e,open:f,onOpenChange:p}),o.jsx(Tas,{open:h,onOpenChange:re,items:v,onSuccess:ue}),o.jsx(Nas,{open:b,onOpenChange:we,items:x,currentDatasetId:e}),o.jsx(At,{open:_,onOpenChange:C,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Items"}),o.jsxs(At.Description,{children:["Are you sure you want to delete ",E.length," item",E.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:ze,children:J.isPending?"Deleting...":"Delete"})]})]})})]})}function qis(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 cae({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-xs text-destructive",children:[o.jsxs("code",{className:"bg-destructive/10 px-1 rounded",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function His({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("{}"),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[p,h]=g.useState(""),[m,v]=g.useState(null),{addItem:y}=Ii(),b=async C=>{C.preventDefault();let E;try{E=JSON.parse(s)}catch{De.error("Input must be valid JSON");return}let j;if(i.trim())try{j=JSON.parse(i)}catch{De.error("Ground Truth must be valid JSON");return}let T;if(c.trim())try{T=JSON.parse(c)}catch{De.error("Expected Trajectory must be valid JSON");return}let I;if(d.trim())try{const R=JSON.parse(d);if(!Array.isArray(R)){De.error("Tool Mocks must be a JSON array");return}I=R}catch{De.error("Tool Mocks must be valid JSON");return}let A;if(p.trim())try{A=JSON.parse(p)}catch{De.error("Request Context must be valid JSON");return}try{await y.mutateAsync({datasetId:e,input:E,groundTruth:j,expectedTrajectory:T,toolMocks:I,requestContext:A}),De.success("Item added successfully"),v(null),a("{}"),l(""),u(""),f(""),h(""),n(!1),r?.()}catch(R){const L=qis(R);L?v(L):De.error(`Failed to add item: ${R instanceof Error?R.message:"Unknown error"}`)}},S=C=>{a(C),m?.field==="input"&&v(null)},x=C=>{l(C),m?.field==="groundTruth"&&v(null)},k=C=>{f(C),m?.field==="toolMocks"&&v(null)},_=()=>{a("{}"),l(""),u(""),f(""),h(""),v(null),n(!1)};return o.jsx(br,{open:t,onOpenChange:n,children:o.jsxs(xr,{className:"max-w-lg",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Add Item"})}),o.jsx($r,{children:o.jsxs("form",{onSubmit:b,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Wr,{value:s,onChange:S,showCopyButton:!1,className:"min-h-[120px]"}),m?.field==="input"&&o.jsx(cae,{field:"input",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Wr,{value:i,onChange:x,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="groundTruth"&&o.jsx(cae,{field:"groundTruth",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Wr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Wr,{value:d,onChange:k,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="toolMocks"&&o.jsx(cae,{field:"toolMocks",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Wr,{value:p,onChange:h,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(le,{type:"button",onClick:_,children:"Cancel"}),o.jsx(le,{type:"submit",variant:"primary",disabled:y.isPending,children:y.isPending?"Adding...":"Add Item"})]})]})})]})})}function Wis({item:e}){return o.jsx(ga,{withMargins:!1,children:o.jsxs(ga.Column,{children:[o.jsxs(ga.Title,{size:"smaller",children:[o.jsx(LN,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx($a,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(ga.Description,{children:[o.jsxs(Fo,{children:[o.jsx(ddt,{})," Created ",nr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(Fo,{children:[o.jsx(E_,{})," Version v",e.datasetVersion]})]})]})})}function eIe({item:e}){const t=e?.input?JSON.stringify(e.input,null,2):"null",n=e?.groundTruth?JSON.stringify(e.groundTruth,null,2):"null",r=e?.metadata?JSON.stringify(e.metadata,null,2):"null",s=e?.expectedTrajectory?JSON.stringify(e.expectedTrajectory,null,2):null;return o.jsxs(vNe,{children:[o.jsx(Rs.CodeSection,{title:"Input",icon:o.jsx(kO,{}),codeStr:t}),o.jsx(Rs.CodeSection,{title:"Ground Truth",icon:o.jsx(Sg,{}),codeStr:n}),s&&o.jsx(Rs.CodeSection,{title:"Expected Trajectory",icon:o.jsx(Cxe,{}),codeStr:s}),o.jsx(Rs.CodeSection,{title:"Metadata",icon:o.jsx(BN,{}),codeStr:r})]})}function Zis({selectedScorers:e,setSelectedScorers:t,disabled:n=!1,container:r}){const{data:s,isLoading:a}=ih(),i=g.useMemo(()=>s?Object.entries(s).map(([l,c])=>({value:l,label:c.scorer?.config?.name||l,description:c.scorer?.config?.description||""})):[],[s]);return o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Scorers (Optional)"}),o.jsx(ic,{multiple:!0,options:i,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||a,container:r})]})}const Gis=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Qis({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=Em(),{data:l,isLoading:c}=Hy(),{data:u,isLoading:d}=ih(),f=e==="agent"?Object.entries(a??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(l??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=v=>{t(v),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Target Type"}),o.jsx(ic,{options:Gis,value:e,onValueChange:h,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:m}),o.jsx(ic,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}function Yis({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return fm(um(e))}catch(r){return console.error("Failed to parse requestContextSchema:",r),null}},[e]);return n?o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Request Context"}),o.jsx(E4,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-sm text-destructive",children:"Failed to parse request context schema"})}function Kis({datasetId:e,version:t,requestContextSchema:n,open:r,onOpenChange:s,onSuccess:a}){const i=g.useRef(null),[l,c]=g.useState(""),[u,d]=g.useState(""),[f,p]=g.useState([]),[h,m]=g.useState({}),[v,y]=g.useState(""),{triggerExperiment:b}=Ii(),S=!!(n&&Object.keys(n).length>0),x=l&&u,k=b.isPending,_=()=>{c(""),d(""),p([]),m({}),y("")},C=()=>{if(S){const T=Object.entries(h).filter(([,I])=>I!==void 0&&I!=="");return T.length>0?Object.fromEntries(T):void 0}if(v.trim()){let T;try{T=JSON.parse(v)}catch{throw new Error("Request Context must be valid JSON")}if(!T||typeof T!="object"||Array.isArray(T))throw new Error("Request Context must be a JSON object");return T}},E=async()=>{if(!x)return;let T;try{T=C()}catch(I){const A=I instanceof Error?I.message:"Request Context must be valid JSON";ru.error(A);return}try{const I=await b.mutateAsync({datasetId:e,targetType:l,targetId:u,scorerIds:f.length>0?f:void 0,version:t,requestContext:T});ru.success("Experiment triggered successfully"),s(!1),a?.(I.experimentId),_()}catch(I){const A=I instanceof Error?I.message:"Failed to trigger experiment";ru.error(A)}},j=()=>{k||(s(!1),_())};return o.jsx(br,{open:r,onOpenChange:j,children:o.jsxs(xr,{ref:i,children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Run Experiment"}),o.jsx(Ks,{children:t?`Execute items from ${nr(new Date(t),"MMM d, yyyy")} version against a target.`:"Execute all items in this dataset against a target."})]}),o.jsxs($r,{className:"grid gap-6",children:[o.jsx(Qis,{targetType:l,setTargetType:c,targetId:u,setTargetId:d,container:i}),l&&l!=="scorer"&&o.jsx(Zis,{selectedScorers:f,setSelectedScorers:p,disabled:k,container:i}),S?o.jsx(Yis,{requestContextSchema:n,onChange:m}):o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Request Context (JSON, optional)"}),o.jsx(Wr,{value:v,onChange:y,showCopyButton:!1,className:"min-h-[80px]"})]})]}),o.jsxs(Nc,{className:"px-6 pt-4",children:[o.jsx(le,{onClick:j,disabled:k,children:"Cancel"}),o.jsx(le,{variant:"primary",onClick:E,disabled:!x||k,children:k?o.jsxs(o.Fragment,{children:[o.jsx(Kt,{className:"w-4 h-4"}),"Running..."]}):"Run"})]})]})})}const Xis=e=>{const t=We();return yt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},enabled:!!e})},tIe=e=>o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 9.45892 8.88606",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{d:"M8.53702 7.36403C8.98547 7.36403 9.34918 7.70502 9.34918 8.12535C9.34906 8.54559 8.9854 8.88606 8.53702 8.88606H5.6839C5.23552 8.88606 4.87186 8.54559 4.87174 8.12535C4.87174 7.70502 5.23545 7.36403 5.6839 7.36403H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.53702 3.67209C8.98547 3.67209 9.34918 4.01309 9.34918 4.43342C9.34911 4.8537 8.98543 5.19413 8.53702 5.19413H5.6839C5.23549 5.19413 4.87181 4.8537 4.87174 4.43342C4.87174 4.01309 5.23545 3.67209 5.6839 3.67209H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.67155 0C9.10635 2.06584e-05 9.45892 0.341006 9.45892 0.761326C9.45878 1.18153 9.10627 1.52201 8.67155 1.52203H2.88163C2.4469 1.52203 2.0944 1.18154 2.09427 0.761326C2.09427 0.340993 2.44681 3.80132e-08 2.88163 0H8.67155Z",fill:"currentColor"}),o.jsx("path",{d:"M0.757606 0.760086V4.01122H3.50594V4.76883H0.759466L0.762566 5.4291C0.76837 6.70703 1.8058 7.73972 3.08374 7.73973H3.67953V8.49796H3.08374C1.38863 8.49795 0.0120204 7.1273 0.00433981 5.4322L0 4.39188V0.760086H0.757606Z",fill:"currentColor"})]});function uae(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function Jis({report:e}){const{served:t,unconsumed:n,liveCalls:r,failure:s}=e,a=[...t.map(i=>({outcome:"served",toolName:i.toolName,args:i.args})),...r.map(i=>({outcome:"live",toolName:i.toolName,args:i.args})),...n.map(i=>({outcome:"unconsumed",toolName:i.toolName,args:i.args}))];return o.jsxs("div",{className:"grid gap-2","data-testid":"tool-mock-report",children:[o.jsx(xn.SectionHeading,{icon:o.jsx(Up,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(En,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(En.Message,{children:[o.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Called with: ",uae(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>uae(i.args)).join(", ")]})]})}),o.jsx("div",{className:"rounded border border-border1 divide-y divide-border1 text-sm",children:a.map((i,l)=>o.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-1.5",children:[o.jsxs("span",{className:"min-w-0 truncate",children:[o.jsx("span",{className:"font-mono text-neutral4",children:i.toolName}),o.jsx("span",{className:"ml-2 font-mono text-xs text-neutral3",children:uae(i.args)})]}),o.jsx("span",{className:`shrink-0 text-xs px-2 py-0.5 rounded ${eos(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function eos(e){switch(e){case"served":return"bg-accent1/10 text-accent1";case"live":return"bg-orange-500/10 text-orange-400";case"unconsumed":return"bg-neutral3/10 text-neutral4"}}function tos({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d,onCollapsedChange:f}){const[p,h]=g.useState(!1),m=d??p,v=f??h,y=!!e?.error,b=jz(e?.input),S=jz(e?.output),x=jz(e?.groundTruth),k=u&&e.status!=="needs-review"&&e.status!=="complete",_=Array.isArray(e.tags)?e.tags:[];return o.jsxs(xn,{collapsed:m,children:[o.jsxs(xn.Header,{children:[o.jsxs(xn.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[f&&o.jsx(le,{size:"md",tooltip:m?"Expand panel":"Collapse panel",onClick:()=>v(!m),children:m?o.jsx(mdt,{}):o.jsx(hdt,{})}),o.jsx(xn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),o.jsxs(le,{size:"md",onClick:a,disabled:!e.traceId,children:[o.jsx(tIe,{}),"Trace"]}),o.jsx(xn.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!m&&o.jsxs(xn.Content,{children:[o.jsxs("div",{className:"grid gap-4 mb-6",children:[o.jsxs(Ht,{children:[o.jsx(Ht.Key,{children:"Item Id"}),o.jsx(Ht.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(Ht.Key,{children:"Created"}),o.jsx(Ht.Value,{children:nr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),y&&o.jsx(En,{variant:"destructive",title:"Error",children:o.jsx(En.Message,{children:jz(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(ve,{columns:"1fr 1fr",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Scorer"}),o.jsx(ve.TopCell,{children:"Score"})]}),t.map(C=>o.jsxs(ve.RowButton,{featured:c===C.id,onClick:()=>l?.(C.id),children:[o.jsx(ve.Cell,{height:"compact",children:C.scorerId}),o.jsx(ve.MonoCell,{children:C.score.toFixed(3)})]},C.id))]}),e.toolMockReport&&o.jsx(Jis,{report:e.toolMockReport}),(e.status||_.length>0||k)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(xn.SectionHeading,{icon:o.jsx(BN,{}),className:"mb-2",children:"Review"}),(e.status||_.length>0)&&o.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.status&&o.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${e.status==="needs-review"?"bg-orange-500/10 text-orange-400":e.status==="complete"?"bg-accent1/10 text-accent1":"bg-neutral3/10 text-neutral4"}`,children:e.status}),_.map(C=>o.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-surface4 text-neutral4",children:C},C))]}),k&&o.jsx("div",{children:o.jsxs(le,{size:"sm",onClick:()=>u(e.id),children:[o.jsx(KV,{}),"Flag for Review"]})}),e.status==="needs-review"&&i&&o.jsx("div",{children:o.jsxs(le,{size:"sm",onClick:i,children:[o.jsx(ka,{}),"Review"]})})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(xn.CodeSection,{title:"Input",icon:o.jsx(LN,{}),codeStr:b}),o.jsx(xn.CodeSection,{title:"Output",icon:o.jsx(Sg,{}),codeStr:S}),o.jsx(xn.CodeSection,{title:"Ground Truth",icon:o.jsx(jxe,{}),codeStr:x})]})]})]})}function jz(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function nos({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:a,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,selectedIds:d,onToggleSelect:f}){const p=!!(d&&f),h=[p?"auto":"",...s.map(v=>v.size)].filter(Boolean).join(" "),m=s.some(v=>v.name==="input");return t?o.jsx(ll,{columns:h}):o.jsxs(ve,{columns:h,className:"min-w-0",children:[o.jsxs(ve.Top,{hasLeadingCell:p,children:[p&&o.jsx(ve.TopCell,{children:" "}),p?o.jsx(ve.TopCells,{colStart:2,children:s.map(v=>o.jsx(ve.TopCell,{children:v.label},v.name))}):s.map(v=>o.jsx(ve.TopCell,{children:v.label},v.name))]}),e.length===0?o.jsx(ve.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map(v=>{const y=!!v.error,b=v.id===n,S=o.jsxs(o.Fragment,{children:[o.jsx(ve.IdCell,{id:v.itemId}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx("div",{className:"flex items-center justify-center w-10 relative bg-transparent h-full",children:o.jsx("div",{role:"img","aria-label":y?"Error":"Success",className:X("w-2 h-2 rounded-full",y?"bg-red-700":"bg-green-600")})})}),o.jsx($n,{children:y?"Error":"Success"})]})}),m&&o.jsx(ve.MonoCell,{children:sos(ros(v.input),200)}),i?.map(x=>{const _=a?.[v.itemId]?.find(C=>C.scorerId===x);return o.jsx(ve.Cell,{height:"compact",className:"font-mono text-neutral3 text-ui-smd",children:_!=null?_.score.toFixed(3):"-"},x)})]});return p?o.jsxs(ve.RowWrapper,{children:[o.jsx(ve.SelectCell,{checked:d.has(v.id),onToggle:()=>f(v.id),"aria-label":`Select result ${v.itemId}`}),o.jsx(ve.RowButton,{flushLeft:!0,colStart:2,featured:b,onClick:()=>r(v.id),children:S})]},v.id):o.jsx(ve.RowButton,{featured:b,onClick:()=>r(v.id),children:S},v.id)}),o.jsx(ve.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function ros(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function sos(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function aos(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function ios({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i}){const[l,c]=g.useState(!1),u=a??l,d=i??c,f=aos(e),p=f?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(xn,{collapsed:u,children:[o.jsxs(xn.Header,{children:[o.jsxs(xn.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[i&&o.jsx(le,{size:"md",tooltip:u?"Expand panel":"Collapse panel",onClick:()=>d(!u),children:u?o.jsx(mdt,{}):o.jsx(hdt,{})}),(n||t)&&o.jsx(xn.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&o.jsxs(le,{size:"md",onClick:s,disabled:!e.traceId,children:[o.jsx(tIe,{}),"Trace"]}),o.jsx(xn.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!u&&o.jsx(xn.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(xn.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(im,{}),codeStr:e.reason||p,simplified:!0}),!f&&o.jsxs(o.Fragment,{children:[o.jsx(xn.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(_h,{}),codeStr:e.preprocessPrompt||p,simplified:!0}),o.jsx(xn.CodeSection,{title:"Analyze Prompt",icon:o.jsx(_h,{}),codeStr:e.analyzePrompt||p,simplified:!0}),o.jsx(xn.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(_h,{}),codeStr:e.generateScorePrompt||p,simplified:!0}),o.jsx(xn.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(_h,{}),codeStr:e.generateReasonPrompt||p,simplified:!0})]})]})})]})}const JKe=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"avg",label:"Avg Score",size:"1fr"},{name:"count",label:"Items Scored",size:"1fr"}];function oos({scoresByItemId:e,experimentStatus:t}){const n=g.useMemo(()=>{if(!e)return[];const r={};for(const s of Object.values(e))for(const a of s)r[a.scorerId]||(r[a.scorerId]={sum:0,count:0}),r[a.scorerId].sum+=a.score,r[a.scorerId].count++;return Object.entries(r).map(([s,{sum:a,count:i}])=>({scorerId:s,avg:a/i,count:i})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))},[e]);if(n.length===0){const r=t==="running"||t==="pending",s=e!==void 0;let a,i;return r?(a="Experiment in progress",i="Summary metrics will appear here once the experiment completes."):s?(a="No scorers configured",i="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(a="Loading scores",i="Fetching scorer results…"),o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(zr,{iconSlot:o.jsx(im,{className:"w-8 h-8 text-neutral3"}),titleSlot:a,descriptionSlot:i})})}return o.jsxs(yn,{children:[o.jsxs(yn.Header,{columns:JKe,children:[o.jsx(yn.HeaderCol,{children:"Scorer"}),o.jsx(yn.HeaderCol,{children:"Avg Score"}),o.jsx(yn.HeaderCol,{children:"Items Scored"})]}),o.jsx(yn.Scroller,{children:o.jsx(yn.Items,{children:n.map(({scorerId:r,avg:s,count:a})=>o.jsxs(yn.Row,{columns:JKe,children:[o.jsx(yn.TextCell,{children:r}),o.jsx(yn.TextCell,{className:"font-mono",children:s.toFixed(3)}),o.jsx(yn.TextCell,{className:"font-mono",children:a})]},r))})})]})}function a7t({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const[c,u]=g.useState(null),[d,f]=g.useState(null),[p,h]=g.useState(void 0),[m,v]=g.useState(null),[y,b]=g.useState(new Set),[S,x]=g.useState(!1),[k,_]=g.useState(!1),[C,E]=g.useState(!1),[j,T]=g.useState(!1),{updateExperimentResult:I}=Ii(),A=g.useCallback(re=>{b(se=>{const he=new Set(se);return he.has(re)?he.delete(re):he.add(re),he})},[]),R=g.useCallback(()=>b(new Set),[]),L=g.useCallback(()=>{const re=r.filter(se=>!!se.error).map(se=>se.id);b(new Set(re))},[r]),M=g.useCallback(async re=>{if(S||re.length===0)return;x(!0);let se=0;const he=new Set;try{for(const xe of re)try{await I.mutateAsync({datasetId:t,experimentId:e,resultId:xe,status:"needs-review"}),se++,he.add(xe)}catch{}}finally{x(!1)}he.size>0&&b(xe=>{const Ne=new Set(xe);for(const Pe of he)Ne.delete(Pe);return Ne}),se>0&&De(`${se} result${se>1?"s":""} flagged for review`)},[t,e,S,I]),z=r.find(re=>re.id===c)??null,[H,F]=g.useState("summary"),[B,q]=g.useState(null),D=re=>{F(re),re!=="reviews"&&q(null)},{data:G}=JNe(t),V=(G??[]).filter(re=>re.experimentId===e).length,{data:$}=_9t(e,n),U=g.useMemo(()=>{if(!$)return[];const re=new Set;for(const se of Object.values($))for(const he of se)re.add(he.scorerId);return[...re].sort()},[$]),Z=re=>{u(re),f(null),h(void 0),v(null)},K=re=>{Z(re===c?null:re)},ne=()=>{Z(null)},te=()=>{if(!z)return;const re=r.findIndex(se=>se.id===z.id);if(re>=0&&re<r.length-1)return()=>Z(r[re+1].id)},J=()=>{if(!z)return;const re=r.findIndex(se=>se.id===z.id);if(re>0)return()=>Z(r[re-1].id)},ae=z?$?.[z.itemId]:void 0,pe=ae?.find(re=>re.id===m)??null,Y=re=>{v(re===m?null:re),f(null),h(void 0)},ee=()=>{if(!m||!ae)return;const re=ae.findIndex(se=>se.id===m);if(re>=0&&re<ae.length-1)return()=>v(ae[re+1].id)},ce=()=>{if(!m||!ae)return;const re=ae.findIndex(se=>se.id===m);if(re>0)return()=>v(ae[re-1].id)},{data:de,isLoading:oe}=Xis(d),me=de?.spans,{data:be,isLoading:we}=k5(d,p),Te=be?.span,{handlePreviousSpan:ke,handleNextSpan:Ae}=QNe(me,p??null,h),ze=(()=>{const re=[],se=!!pe,he=!!d;return re.push(k?"auto":se||he?"2fr":"1fr"),se&&re.push(j?"auto":"3fr"),he&&re.push(C?"auto":"3fr"),he&&p&&re.push("3fr"),re.join(" ")})(),ue=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"status",label:"Status",size:"5rem"},{name:"input",label:"Input",size:"minmax(15rem,1fr)"},...U.map(re=>({name:re,label:re,size:"12rem"}))],[U]);return o.jsxs(Lc,{defaultTab:"summary",value:H,onValueChange:D,className:"grid grid-rows-[auto_1fr] h-full overflow-hidden",children:[o.jsxs(Dc,{children:[o.jsx(Rr,{value:"summary",children:"Summary"}),o.jsx(Rr,{value:"results",children:"Results"}),o.jsxs(Rr,{value:"reviews",children:["Reviews",V>0&&o.jsx(ea,{color:"orange",children:V})]})]}),o.jsx(Xr,{value:"summary",className:"overflow-y-auto mt-5",children:o.jsx(oos,{scoresByItemId:$,experimentStatus:n})}),o.jsx(Xr,{value:"reviews",className:"overflow-auto mt-2 pb-0",children:o.jsx(s7t,{datasetId:t,experimentId:e,featuredItemId:B})}),o.jsxs(Xr,{value:"results",className:"grid grid-rows-[auto_1fr] overflow-hidden mt-2",children:[o.jsxs("div",{className:"mb-4",children:[y.size>0&&o.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-surface3",children:[o.jsxs(ye,{variant:"ui-xs",className:"text-neutral5 font-medium",children:[y.size," selected"]}),o.jsx("div",{className:"flex-1"}),o.jsxs(le,{variant:"outline",size:"sm",disabled:S,onClick:()=>M([...y]),children:[o.jsx(qe,{size:"sm",children:o.jsx(KV,{})}),"Flag for Review"]}),o.jsx(le,{variant:"ghost",size:"sm",onClick:R,children:"Clear"})]}),r.length>0&&y.size===0&&!s&&o.jsx("div",{className:"flex items-center gap-2 px-4 py-2",children:o.jsx(le,{variant:"ghost",size:"sm",onClick:L,children:"Select loaded failures"})})]}),o.jsxs("div",{className:X("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",z&&"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"flex overflow-y-auto w-full",children:o.jsx("div",{className:"grid gap-8 content-start w-full overflow-y-auto",children:o.jsx(nos,{results:r,isLoading:s,featuredResultId:c,onResultClick:K,columns:ue,scoresByItemId:$,scorerIds:U,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:y,onToggleSelect:A})})}),z&&o.jsxs("div",{className:"grid gap-4 max-h-full min-h-0 overflow-auto content-start",style:{gridTemplateRows:ze},children:[o.jsx(tos,{result:z,scores:ae,onPrevious:J(),onNext:te(),onClose:ne,onScoreClick:Y,featuredScoreId:m,onShowTrace:()=>{z.traceId&&(f(z.traceId),h(void 0),v(null),_(!0),E(!1))},onOpenInReview:()=>{q(z.id),F("reviews")},onFlagForReview:re=>M([re]),collapsed:k,onCollapsedChange:_}),pe&&o.jsx(ios,{score:pe,onNext:ee(),onPrevious:ce(),onClose:()=>v(null),onShowTrace:()=>{pe.traceId&&(f(pe.traceId),h(void 0),_(!0),T(!0),E(!1))},collapsed:j,onCollapsedChange:T}),d&&o.jsxs(o.Fragment,{children:[o.jsx(BNe,{traceId:d,spans:me,isLoading:oe,onClose:()=>{f(null),h(void 0),_(!1),T(!1)},onSpanSelect:h,initialSpanId:p??null,placement:"traces-list",showUnavailableFeaturesMsg:!1,collapsed:C,onCollapsedChange:E,LinkComponent:c1,traceHref:`/traces/${d}`}),p&&o.jsx(LNe,{traceId:d,spanId:p,span:Te,isLoading:we,onPrevious:ke,onNext:Ae,onClose:()=>h(void 0)})]})]})]})]})]})}const los={pending:o.jsx(hT,{}),running:o.jsx(fpe,{}),completed:o.jsx(pa,{}),failed:o.jsx(bs,{})};function cos({experiment:e,className:t}){const n=e.status,r=e.totalItems-e.succeededCount-e.failedCount;return o.jsxs("div",{className:X("grid justify-items-end gap-3",t),children:[o.jsxs("div",{className:"flex p-1 px-3 text-ui-lg capitalize text-neutral4 gap-2 items-center bg-surface5 rounded-lg ",children:[o.jsx("span",{className:X("w-5 h-5 flex items-center justify-center rounded-full text-black","[&>svg]:w-4 [&>svg]:h-4",{"bg-green-700":n==="completed","bg-red-700":n==="failed","bg-cyan-600":n==="running","bg-yellow-600":n==="pending"}),children:los[n]}),e.status]}),o.jsxs("div",{className:X("flex items-center gap-3 text-neutral3 text-ui-md ","[&>span]:flex [&>span]:gap-1 [&>span]:items-center ","[&_b]:text-neutral4 [&_b]:font-semibold"),children:[o.jsxs("span",{children:["Total: ",o.jsx("b",{children:e.totalItems})]}),o.jsxs("span",{children:["Succeeded: ",o.jsx("b",{children:e.succeededCount})]}),o.jsxs("span",{children:["Failed: ",o.jsx("b",{children:e.failedCount})]}),(n==="pending"||n==="running")&&o.jsxs("span",{children:["Pending: ",o.jsx("b",{children:r})]})]})]})}function uos({onPrevious:e,onNext:t,previousAriaLabel:n="Previous",nextAriaLabel:r="Next"}){return o.jsxs(Mr,{spacing:"close",children:[o.jsxs(le,{onClick:e,disabled:!e,"aria-label":n,children:[o.jsx($q,{})," Prev"]}),o.jsxs(le,{onClick:t,disabled:!t,"aria-label":r,children:["Next",o.jsx(c4,{})]})]})}function nIe({delta:e}){const t=e>0?o.jsx(ea,{size:"small",color:"green",intensity:"muted",children:o.jsx($D,{})}):e<0?o.jsx(ea,{size:"small",color:"red",intensity:"muted",children:o.jsx(Sfn,{})}):null;return o.jsxs("span",{className:X("font-mono text-sm text-neutral4 min-w-20"),children:[o.jsx("span",{className:"w-3 inline-block",children:e>0?"+ ":e<0?"- ":""}),Math.abs(e).toFixed(2)," ",t]})}function Tz(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function dos({item:e,baselineId:t,contenderId:n,baselineVersion:r,contenderVersion:s,onPrevious:a,onNext:i,onClose:l}){const c=e.results[t],u=e.results[n],d=!!(c&&u),f=new Set;if(c)for(const h of Object.keys(c.scores))f.add(h);if(u)for(const h of Object.keys(u.scores))f.add(h);const p=[...f].sort();return o.jsxs(Yr,{withLeftSeparator:!0,children:[o.jsxs(Yr.Toolbar,{children:[o.jsx(uos,{onPrevious:a,onNext:i,previousAriaLabel:"Previous comparison item",nextAriaLabel:"Next comparison item"}),o.jsx(Mr,{children:o.jsx(le,{onClick:l,"aria-label":"Close comparison detail panel",children:o.jsx(bs,{})})})]}),o.jsxs(Yr.Content,{className:"pb-6",children:[o.jsx(ga,{withMargins:!1,children:o.jsx(ga.Column,{children:o.jsxs(ga.Title,{size:"smaller",children:[o.jsx(LN,{})," ",e.itemId]})})}),d?o.jsx(o.Fragment,{children:o.jsxs(vNe,{children:[p.length>0&&o.jsxs("div",{className:"grid gap-3",children:[o.jsx("h4",{className:"text-sm font-medium text-neutral5",children:"Scores"}),o.jsx("div",{className:"grid gap-2",children:p.map(h=>{const m=c?.scores[h]??null,v=u?.scores[h]??null,y=m!=null&&v!=null?v-m:null;return o.jsxs("div",{className:"flex items-center justify-between gap-4 px-3 py-2 rounded-lg bg-surface2",children:[o.jsx("span",{className:"text-sm text-neutral5 font-medium",children:h}),o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("span",{className:"text-sm text-neutral3",children:[m!=null?m.toFixed(3):"-"," →"," ",v!=null?v.toFixed(3):"-"]}),y!=null&&o.jsx(nIe,{delta:y})]})]},h)})})]}),o.jsx(Rs.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(ea,{color:"purple",children:"Baseline "})," Experiment Output"]}),icon:o.jsx(Sg,{}),codeStr:Tz(c?.output)}),o.jsx(Rs.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(ea,{color:"cyan",children:"Contender "})," Experiment Output"]}),icon:o.jsx(Sg,{}),codeStr:Tz(u?.output)}),o.jsx(Rs.CodeSection,{title:"Item Input",icon:o.jsx(kO,{}),codeStr:Tz(e.input)}),o.jsx(Rs.CodeSection,{title:"Item Ground Truth",icon:o.jsx(jxe,{}),codeStr:Tz(e.groundTruth)})]})}):o.jsx(En,{variant:"warning",title:"Comparison not available",children:o.jsx(En.Message,{children:(()=>{const h=c?"Contender":"Baseline",m=c?s:r;return o.jsxs(o.Fragment,{children:["The ",h," experiment was run against dataset",m!=null?` v. ${m}`:"",", which does not contain this item."]})})()})})]})]})}function fos({items:e,baselineId:t,contenderId:n,scorerIds:r,featuredItemId:s,columns:a,onItemClick:i}){return o.jsx(Yr,{children:o.jsxs(yn,{children:[o.jsxs(yn.Header,{columns:a,children:[o.jsx(yn.HeaderCol,{children:"Item ID"}),!s&&r.map(l=>o.jsx(yn.HeaderCol,{className:"flex justify-center",children:l},l))]}),o.jsx(yn.Scroller,{children:o.jsx(yn.Items,{children:e.map(l=>{const c=l.results[t],u=l.results[n],d=!!(c&&u);return o.jsx(yn.Row,{children:o.jsxs(yn.RowButton,{item:{id:l.itemId},columns:a,isFeatured:s===l.itemId,onClick:i,children:[o.jsx(yn.IdCell,{id:l.itemId,className:d?"":"text-neutral1"}),!s&&o.jsx(o.Fragment,{children:r.map(f=>{const p=c?.scores[f]??null,h=u?.scores[f]??null,m=p!=null&&h!=null?h-p:null;return o.jsx(yn.Cell,{className:"flex items-center gap-5 justify-center font-mono",children:m!=null?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"flex items-center text-neutral2 min-w-24",children:[p?.toFixed(2)," → ",h?.toFixed(2)]}),o.jsx(nIe,{delta:m})]}):o.jsx("span",{className:"text-neutral1",children:"-"})},f)})})]})},l.itemId)})})})]})})}const pos={baseline:{label:"Baseline",color:"purple",customStyle:"items-end justify-items-end [&>div]:justify-end border-r-0 rounded-r-none"},contender:{label:"Contender",color:"cyan",customStyle:"items-start justify-items-start [&>div]:justify-start border-l-0 rounded-l-none"}};function eXe({datasetId:e,experiment:t,type:n}){const{Link:r}=bn(),{label:s,color:a,customStyle:i}=pos[n];if(!t)return null;const l=t.createdAt?new Date(t.createdAt):null;return o.jsxs("div",{className:`grid border-2 border-border1 rounded-lg p-5 gap-3 ${i}`,children:[o.jsxs("div",{className:"flex items-center gap-3 w-full overflow-clip",children:[n==="contender"&&o.jsxs(ea,{size:"small",color:a,children:[s,o.jsx(bm,{})]}),o.jsx(le,{as:r,href:`/datasets/${e}/experiments/${t.id}`,children:o.jsx("span",{className:"truncate min-w-0",children:t.id})}),n==="baseline"&&o.jsxs(ea,{size:"small",color:a,children:[o.jsx(Rc,{})," ",s]})]}),o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-ui-sm text-neutral3",children:[o.jsxs(Fo,{children:[o.jsx(jxe,{})," ",t.targetType," / ",t.targetId]}),o.jsxs(Fo,{children:[o.jsx(JV,{})," v",t.datasetVersion??"—"]}),l&&o.jsxs(Fo,{children:[o.jsx(fdt,{})," ",nr(l,"MMM d, yyyy HH:mm")]})]})]})}function hos({datasetId:e,experimentIdA:t,experimentIdB:n,onSwap:r}){const[s,a]=g.useState(null),{data:i,isLoading:l,error:c}=nas(e,t,n),{data:u}=_V(e,t),{data:d}=_V(e,n),f=u&&d&&u.datasetVersion!==d.datasetVersion,p=g.useMemo(()=>{if(!i)return[];const E=new Set;for(const j of i.items)for(const T of Object.values(j.results))if(T)for(const I of Object.keys(T.scores))E.add(I);return[...E].sort()},[i]),h=g.useMemo(()=>{if(!i||p.length===0)return[];const E=i.baselineId,j=t===E?n:t;return p.map(T=>{let I=0,A=0,R=0,L=0;for(const F of i.items){const B=F.results[E]?.scores[T],q=F.results[j]?.scores[T];B!=null&&(I+=B,R++),q!=null&&(A+=q,L++)}const M=R>0?I/R:null,z=L>0?A/L:null,H=M!=null&&z!=null?z-M:null;return{scorerId:T,avgA:M,avgB:z,delta:H}})},[i,p,t,n]),m=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"baselineAvg",label:"Baseline Avg",size:"1fr"},{name:"comparisonAvg",label:"Comparison Avg",size:"1fr"},{name:"delta",label:"Delta",size:"1fr"}],v=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"8rem"},...s?[]:p.map(E=>({name:E,label:E,size:"1fr"}))],[p,s]),y=i?.items.find(E=>E.itemId===s)??null,b=E=>{a(E===s?null:E)},S=()=>{a(null)},x=()=>{if(!i||!s)return;const E=i.items.findIndex(j=>j.itemId===s);if(E>=0&&E<i.items.length-1)return()=>a(i.items[E+1].itemId)},k=()=>{if(!i||!s)return;const E=i.items.findIndex(j=>j.itemId===s);if(E>0)return()=>a(i.items[E-1].itemId)};if(l)return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx(Kt,{})});if(c)return o.jsx(En,{variant:"warning",title:"Error loading comparison",children:o.jsx(En.Message,{children:c instanceof Error?c.message:"Unknown error"})});if(!i||i.items.length===0)return o.jsx("div",{className:"text-neutral4 text-sm text-center py-8",children:"No comparison data"});const _=i.baselineId,C=t===_?n:t;return o.jsxs("div",{className:"grid gap-10",children:[u&&d&&o.jsxs("div",{className:X("relative grid xl:grid-cols-[1fr_auto_1fr] gap-4 xl:gap-0"),children:[o.jsx(eXe,{datasetId:e,experiment:u,type:"baseline"}),o.jsx("div",{className:"relative flex items-center justify-center px-[2vw] before:absolute before:inset-y-0 before:left-1/2 before:-translate-x-1/2 before:w-[2px] before:bg-border1",children:o.jsx("div",{className:"relative z-1 bg-surface2 rounded-lg p-2",children:o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx(le,{onClick:r,children:"VS"})}),o.jsx($n,{children:"Switch the order"})]})})}),o.jsx(eXe,{datasetId:e,experiment:d,type:"contender"})]}),f&&o.jsx(En,{variant:"warning",title:"Version mismatch",children:o.jsxs(En.Message,{children:["These experiments used different dataset versions (v",u.datasetVersion," vs v",d.datasetVersion,"). Results may not be directly comparable."]})}),h.length>0&&o.jsxs(yn,{children:[o.jsxs(yn.Header,{columns:m,children:[o.jsx(yn.HeaderCol,{children:"Scorer"}),o.jsx(yn.HeaderCol,{className:"flex justify-center",children:o.jsxs(XYe,{children:[o.jsx(ea,{color:"purple",size:"small",intensity:"muted",children:"Baseline"}),o.jsx(ea,{color:"purple",size:"small",children:"Avg"})]})}),o.jsx(yn.HeaderCol,{className:"flex justify-center",children:o.jsxs(XYe,{children:[o.jsx(ea,{color:"cyan",size:"small",intensity:"muted",children:"Contender"}),o.jsx(ea,{color:"cyan",size:"small",children:"Avg"})]})}),o.jsx(yn.HeaderCol,{className:"flex justify-center",children:"Delta"})]}),o.jsx(yn.Scroller,{children:o.jsx(yn.Items,{children:h.map(({scorerId:E,avgA:j,avgB:T,delta:I})=>o.jsxs(yn.Row,{columns:m,children:[o.jsx(yn.TextCell,{children:E}),o.jsx(yn.TextCell,{className:"text-center font-mono",children:j!=null?j.toFixed(3):"-"}),o.jsx(yn.TextCell,{className:"text-center font-mono",children:T!=null?T.toFixed(3):"-"}),o.jsx(yn.TextCell,{className:"flex justify-center",children:I!=null?o.jsx(nIe,{delta:I}):"-"})]},E))})})]}),o.jsxs(ly,{className:X({"grid-cols-[1fr_2fr]":!!y}),children:[o.jsx(fos,{items:i.items,baselineId:_,contenderId:C,scorerIds:p,featuredItemId:s,columns:v,onItemClick:b}),!!y&&o.jsx(dos,{item:y,baselineId:_,contenderId:C,baselineVersion:u?.datasetVersion,contenderVersion:d?.datasetVersion,onPrevious:k(),onNext:x(),onClose:S})]})]})}function mos({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=YNe(e,t),[l,c]=g.useState(!1),[u,d]=g.useState(new Set),f=b=>{n?.(b)},p=b=>s==null?b.isLatest:b.datasetVersion===s,h=b=>{d(S=>{const x=new Set(S);if(x.has(b))x.delete(b);else if(x.size>=2){const[k]=Array.from(x);return new Set([k,b])}else x.add(b);return x})},m=()=>{c(!1),d(new Set)},v=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(Yr,{className:"min-w-56",children:[l?o.jsx(Yr.Toolbar,{className:"grid justify-stretch gap-3 w-full",children:o.jsxs(Mr,{children:[o.jsx(le,{onClick:m,children:"Cancel"}),o.jsx(le,{variant:"primary",disabled:u.size!==2,onClick:y,tooltip:u.size!==2?"Check 2 versions to compare":void 0,className:"grow",children:"Compare"})]})}):o.jsx(o.Fragment,{children:(a||[]).length>1&&o.jsx(Yr.Toolbar,{children:o.jsxs(le,{onClick:v,className:"w-full",children:[o.jsx(t1,{})," Compare Ver."]})})}),i?o.jsx(gos,{}):o.jsxs(yn,{children:[o.jsx(yn.Header,{children:o.jsx(yn.HeaderCol,{children:"Item Version History"})}),o.jsx(yn.Scroller,{children:o.jsx(yn.Items,{children:a?.map(b=>{const S=String(b.datasetVersion),x=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(yn.Row,{isSelected:l&&u.has(S),children:[l&&o.jsx(yn.LabelCell,{children:o.jsx(Bo,{checked:u.has(S),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||h(S)},"aria-label":`Select version ${b.datasetVersion}`})}),o.jsx(yn.RowButton,{item:b,columns:[{name:"version",label:"Item Version History",size:"1fr"}],isFeatured:p(b),onClick:()=>f(b),className:"py-2",children:o.jsx(yn.VersionCell,{version:b.datasetVersion,date:x,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function gos(){return o.jsxs(yn,{children:[o.jsx(yn.Header,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(yn.HeaderCol,{children:"Item Version History"})}),o.jsx(yn.Items,{children:Array.from({length:3}).map((e,t)=>o.jsx(yn.Row,{children:o.jsx(yn.RowButton,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(yn.TextCell,{isLoading:!0,children:"Loading..."})})},t))})]})}function vos(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${nr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function yos({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=INe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${vos(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(Yr.Toolbar,{className:"grid grid-cols-[1fr_1fr_1fr_10rem] gap-4 w-full",children:[o.jsx("div",{}),o.jsx(Ec,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(Ec,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const bos=[{name:"id",label:"ID",size:"1fr"},{name:"versionA",label:"Version A",size:"1fr"},{name:"versionB",label:"Version B",size:"1fr"},{name:"compare",label:"Compare",size:"10rem"}],xos={added:{color:"blue",borderColor:"border-blue-900",icon:o.jsx(Zr,{}),tooltip:"Added in this version"},changed:{color:"orange",borderColor:"border-yellow-900",icon:o.jsx(Edt,{}),tooltip:"Changed in this version"},same:{color:"green",borderColor:"border-green-900",icon:o.jsx(Hpn,{}),tooltip:"Same in both versions"}};function dae({red:e=!1,tooltip:t}){return o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx(Afn,{className:X("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),t&&o.jsx($n,{children:t})]})}function tk({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{color:n,icon:r,tooltip:s}=xos[e];return o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"pr-3 text-ui-md text-neutral4 min-w-16 flex justify-end",children:["v. ",t]}),o.jsx(ea,{color:n,size:"small",children:r})]})}),o.jsx($n,{children:s})]})}function wos(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function Sos({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=bn(),l=t>n;return o.jsx(yn,{children:o.jsx(yn.Scroller,{children:o.jsx(yn.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=wos(u,d);return o.jsxs(yn.Row,{columns:bos,children:[o.jsx(yn.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(yn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!d&&l?o.jsx(tk,{variant:"added",version:u.datasetVersion}):f==="changed"&&l?o.jsx(tk,{variant:"changed",version:u.datasetVersion}):o.jsx(tk,{version:u.datasetVersion})}):o.jsx(yn.Cell,{className:"justify-center flex items-center",children:o.jsx(dae,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(yn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!u&&!l?o.jsx(tk,{variant:"added",version:d.datasetVersion}):f==="changed"&&!l?o.jsx(tk,{variant:"changed",version:d.datasetVersion}):o.jsx(tk,{version:d.datasetVersion})}):o.jsx(yn.Cell,{className:"justify-center flex items-center",children:o.jsx(dae,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(yn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",children:o.jsx(tk,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(yn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?ids=${u?.datasetVersion},${d?.datasetVersion}`,children:"Compare"}):o.jsx(yn.Cell,{children:o.jsx(dae,{tooltip:o.jsxs(o.Fragment,{children:["Comparing is available",o.jsx("br",{})," only for changed items"]})})})]},c)})})})})}const tXe={needsReview:"#facc15",complete:"#22c55e"},kos=[{label:"Needs Review",color:tXe.needsReview},{label:"Reviewed",color:tXe.complete}];function Oos({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=g.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,p=0;const h=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;p+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,S=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);h.push({name:S,values:[m.needsReview,m.complete]})}return{data:h,maxVal:f,totalInPipeline:p}},[e,t,n]),c=a.length>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Wt.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Wt.Loading,{}):s?o.jsx(Wt.Error,{message:"Failed to load review data"}):o.jsx(Wt.Content,{children:c?o.jsx(NN,{data:a,segments:kos,maxVal:i,fmt:u=>String(u)}):o.jsx(Wt.NoData,{message:"No items have been sent to review yet"})})]})}function rIe(){const e=We();return yt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function i7t(e){const t=new Map;if(!e?.counts)return t;for(const n of e.counts)t.set(n.experimentId,{needsReview:n.needsReview,complete:n.complete,total:n.total});return t}function _os(e,t){const n=new Map,r=i7t(e);if(!r.size||!t)return n;for(const s of t){const a=r.get(s.id);if(!a||!s.datasetId||a.needsReview+a.complete===0)continue;const l=n.get(s.datasetId)??{needsReview:0,complete:0};l.needsReview+=a.needsReview,l.complete+=a.complete,n.set(s.datasetId,l)}return n}function Cos(e){return e?.counts?e.counts.reduce((t,n)=>({needsReview:t.needsReview+n.needsReview,complete:t.complete+n.complete,inPipeline:t.inPipeline+n.needsReview+n.complete}),{needsReview:0,complete:0,inPipeline:0}):{needsReview:0,complete:0,inPipeline:0}}const Eos=10;function jos(){const[e,t]=g.useState(!1),[n,r]=g.useState(""),[s,a]=g.useState("all"),[i,l]=g.useState("all"),[c,u]=g.useState("all"),[d,f]=g.useState(0),{data:p,isLoading:h,error:m}=Bg({page:d,perPage:Eos}),{data:v,isLoading:y,error:b}=VG(),{data:S}=rIe(),x=g.useMemo(()=>p?.datasets??[],[p?.datasets]),k=p?.pagination?.hasMore??!1,_=g.useMemo(()=>v?.experiments??[],[v?.experiments]),C=g.useMemo(()=>xas(x),[x]),E=g.useMemo(()=>_os(S,_),[S,_]),j=h||y,T=m||b,I=()=>t(!0),A=g.useCallback(()=>f(q=>q+1),[]),R=g.useCallback(()=>f(q=>Math.max(0,q-1)),[]),L=g.useCallback(q=>{r(q),f(0)},[]),M=g.useCallback(q=>{a(q),f(0)},[]),z=g.useCallback(q=>{l(q),f(0)},[]),H=g.useCallback(q=>{u(q),f(0)},[]);if(T&&ys(T))return o.jsx(lr,{children:o.jsx(Ws,{})});if(T&&xs(T))return o.jsx(lr,{children:o.jsx(Ds,{resource:"datasets"})});if(T)return o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load datasets",message:T.message})});if(x.length===0&&!j&&d===0)return o.jsxs(o.Fragment,{children:[o.jsx(lr,{children:o.jsx(_as,{onCreateClick:I})}),o.jsx(Zye,{open:e,onOpenChange:t})]});const F=s!=="all"||i!=="all"||c!=="all"||n!=="",B=()=>{r(""),a("all"),l("all"),u("all"),f(0)};return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(jas,{search:n,onSearchChange:L,targetFilter:s,onTargetFilterChange:M,experimentFilter:i,onExperimentFilterChange:z,tagFilter:c,onTagFilterChange:H,tagOptions:C,onReset:B,hasActiveFilters:F,onCreateClick:I})}),o.jsx(Oas,{datasets:x,experiments:_,reviewByDataset:E,isLoading:j,search:n,targetFilter:s,experimentFilter:i,tagFilter:c,currentPage:d,hasMore:k,onNextPage:A,onPrevPage:R}),o.jsx(Zye,{open:e,onOpenChange:t})]})}function Nz({children:e}){return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:e})]})}function Tos(){const{datasetId:e}=Sr(),t=Hs(),[n,r]=Pi(),{activeVersion:s}=KNe(n,r),[a,i]=g.useState(!1),[l,c]=g.useState(!1),[u,d]=g.useState(!1),[f,p]=g.useState(!1),[h,m]=g.useState(!1),{data:v,error:y,isLoading:b}=Qx(e),{data:S=[],isLoading:x}=I1(e,void 0,s),k=!x&&S.length===0;if(b)return null;if(y&&ys(y))return o.jsx(Nz,{children:o.jsx(Ws,{})});if(y&&xs(y))return o.jsx(Nz,{children:o.jsx(Ds,{resource:"datasets"})});if(y&&J_e(y)||!b&&!y&&!v)return o.jsx(Nz,{children:o.jsx(zr,{iconSlot:o.jsx(uy,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(le,{as:ti,to:"/datasets",children:[o.jsx(Rc,{}),"Back to Datasets"]})})});if(y)return o.jsx(Nz,{children:o.jsx(Hi,{title:"Failed to load dataset",message:y instanceof Error?y.message:"An unexpected error occurred. Please try again."})});const _=E=>{t(`/datasets/${e}/experiments/${E}`)},C=()=>{t("/datasets")};return o.jsxs(o.Fragment,{children:[o.jsxs(Ft,{height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{children:[o.jsxs(Ft.Column,{children:[v?.description&&o.jsx("p",{className:"text-ui-smd text-neutral3 mb-1",children:v.description}),o.jsxs(Ht,{numOfCol:2,children:[o.jsx(Ht.Key,{children:"Created at"}),o.jsx(Ht.Value,{children:v?.createdAt?nr(new Date(v.createdAt),"MMM d, yyyy"):""}),o.jsx(Ht.Key,{children:"Latest version"}),o.jsxs(Ht.Value,{children:["v",v?.version??""]})]})]}),o.jsx(Ft.Column,{children:o.jsxs(Mr,{children:[k?o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx("span",{className:"cursor-not-allowed",children:o.jsx("div",{className:"pointer-events-none opacity-50",inert:!0,"aria-disabled":"true",children:o.jsxs(le,{variant:"primary",children:[o.jsx(Ef,{}),s!=null?`Run on v${s}`:"Run Experiment"]})})})}),o.jsx($n,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(le,{variant:"primary",onClick:()=>i(!0),children:[o.jsx(Ef,{}),s!=null?`Run on v${s}`:"Run Experiment"]}),o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsx(le,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(DD,{})})}),o.jsxs(dt.Content,{align:"end",className:"w-48",children:[o.jsxs(dt.Item,{onSelect:()=>d(!0),children:[o.jsx(om,{})," Edit Dataset"]}),o.jsxs(dt.Item,{onSelect:()=>m(!0),children:[o.jsx(am,{})," Duplicate Dataset"]}),o.jsxs(dt.Item,{onSelect:()=>p(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(uu,{})," Delete Dataset"]})]})]})]})})]})}),o.jsx(Ft.MainArea,{children:o.jsx(Vis,{datasetId:e,onAddItemClick:()=>c(!0)})})]}),o.jsx(Kis,{datasetId:e,version:s??void 0,requestContextSchema:v?.requestContextSchema,open:a,onOpenChange:i,onSuccess:_}),o.jsx(His,{datasetId:e,open:l,onOpenChange:c}),v&&o.jsx(Pas,{open:u,onOpenChange:d,dataset:{id:v.id,name:v.name,description:v?.description||"",targetType:v.targetType,inputSchema:v.inputSchema,groundTruthSchema:v.groundTruthSchema,requestContextSchema:v.requestContextSchema}}),v&&o.jsx(Ias,{open:h,onOpenChange:m,sourceDatasetId:v.id,sourceDatasetName:v.name,sourceDatasetDescription:v.description,sourceDatasetTargetType:v.targetType}),v&&o.jsx(Mas,{open:f,onOpenChange:p,datasetId:v.id,datasetName:v.name,onSuccess:C})]})}function o7t({experiment:e}){const{Link:t,paths:n}=bn(),{data:r}=Em(),{data:s}=Hy(),{data:a}=ih(),i=()=>{switch(e.targetType){case"agent":return n.agentLink(e.targetId);case"workflow":return n.workflowLink(e.targetId);case"scorer":return n.scorerLink(e.targetId);default:return"#"}},l=()=>{const u=e.targetId;if(!u)return u;switch(e.targetType){case"agent":return r?.[u]?.name??u;case"workflow":return s?.[u]?.name??u;case"scorer":return a?.[u]?.scorer?.config?.name??u;default:return u}},c=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${n.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{children:[o.jsx(Ft.Column,{children:o.jsxs(Ht,{numOfCol:2,children:[o.jsx(Ht.Key,{children:"Created at"}),o.jsx(Ht.Value,{children:nr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")}),e.completedAt&&o.jsxs(o.Fragment,{children:[o.jsx(Ht.Key,{children:"Completed at"}),o.jsx(Ht.Value,{children:nr(new Date(e.completedAt),"MMM d, yyyy 'at' h:mm a")})]}),o.jsx(Ht.Key,{children:"Target"}),o.jsx(Ht.ValueLink,{href:i(),as:t,children:l()}),e.agentVersion&&o.jsxs(o.Fragment,{children:[o.jsx(Ht.Key,{children:"Version"}),c?o.jsx(Ht.ValueLink,{href:c,as:t,children:e.agentVersion}):o.jsx(Ht.Value,{children:e.agentVersion})]})]})}),o.jsx(Ft.Column,{children:o.jsx(cos,{experiment:e})})]})})}function Iz({children:e}){return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:e})]})}function Nos(){const{datasetId:e,experimentId:t}=Sr(),{data:n,isLoading:r,error:s}=_V(e,t),{data:a,isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u}=FG({datasetId:e,experimentId:t,experimentStatus:n?.status});return!e||!t||r?null:s&&ys(s)?o.jsx(Iz,{children:o.jsx(Ws,{})}):s&&xs(s)?o.jsx(Iz,{children:o.jsx(Ds,{resource:"datasets"})}):s&&J_e(s)||!r&&!s&&!n?o.jsx(Iz,{children:o.jsx(zr,{iconSlot:o.jsx(vxe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${t}".`,actionSlot:o.jsxs(le,{as:ti,to:`/datasets/${e}?tab=experiments`,children:[o.jsx(Rc,{}),"Back to Dataset"]})})}):s?o.jsx(Iz,{children:o.jsx(Hi,{title:"Failed to load experiment",message:s instanceof Error?s.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Ft,{height:"full",children:[o.jsx(o7t,{experiment:n}),o.jsx(Ft.MainArea,{children:o.jsx(a7t,{experimentId:t,datasetId:e,experimentStatus:n.status,results:a??[],isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u})})]})}function Ios(){const{datasetId:e}=Sr(),[t,n]=Pi(),{error:r}=Qx(e??""),s=t.get("baseline")??"",a=t.get("contender")??"";return r&&ys(r)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ws,{})})}):r&&xs(r)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||!s||!a?o.jsx(ds,{children:o.jsx(Cy,{children:o.jsxs("div",{className:"text-neutral4 text-center py-8",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"text-sm mt-2",children:["Use the URL format: /datasets/","{datasetId}","/experiments?baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):o.jsx(ds,{children:o.jsx(Cy,{children:o.jsxs("div",{className:"max-w-[100rem] w-full px-12 mx-auto grid content-start ",children:[o.jsxs(ga,{children:[o.jsxs(ga.Column,{children:[o.jsxs(ga.Title,{children:[o.jsx(t1,{})," Dataset Experiments Comparison"]}),o.jsxs(ga.Description,{children:["Comparing"," ",o.jsx(ti,{to:`/datasets/${e}/experiments/${s}`,children:s.slice(0,8)})," vs"," ",o.jsx(ti,{to:`/datasets/${e}/experiments/${a}`,children:a.slice(0,8)})]})]}),o.jsx(ga.Column,{children:o.jsxs(le,{as:ti,to:`/datasets/${e}`,children:[o.jsx(Rc,{}),"Back to Dataset"]})})]}),o.jsx(hos,{datasetId:e,experimentIdA:s,experimentIdB:a,onSwap:()=>{n({baseline:a,contender:s})}})]})})})}function Aos(){const{datasetId:e,itemId:t}=Sr(),{Link:n}=bn(),r=Hs(),{data:s,isLoading:a,error:i}=YNe(e??"",t??""),{updateItem:l,deleteItem:c}=Ii(),{data:u}=Qx(e??""),d=s?.[0]??null,f=d?.isDeleted??!1,[p,h]=g.useState(null),m=g.useMemo(()=>!d||f?{input:"",groundTruth:"",metadata:"",trajectory:"",toolMocks:"",requestContext:""}:{input:JSON.stringify(d.input,null,2),groundTruth:d.groundTruth?JSON.stringify(d.groundTruth,null,2):"",metadata:d.metadata?JSON.stringify(d.metadata,null,2):"",trajectory:d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):"",toolMocks:d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):"",requestContext:d.requestContext?JSON.stringify(d.requestContext,null,2):""},[d,f]),v=d?.datasetVersion??0,[y,b]=g.useState(!1),[S,x]=g.useState(m.input),[k,_]=g.useState(m.groundTruth),[C,E]=g.useState(m.metadata),[j,T]=g.useState(m.trajectory),[I,A]=g.useState(m.toolMocks),[R,L]=g.useState(m.requestContext),[M,z]=g.useState(v);v!==M&&(z(v),x(m.input),_(m.groundTruth),E(m.metadata),T(m.trajectory),A(m.toolMocks),L(m.requestContext));const[H,F]=g.useState(!1),B=te=>{h(f?te:te.isLatest?null:te)},q=()=>{h(null)},D=!f&&p!=null,G=()=>{D||b(!0)},V=()=>{D||F(!0)},$=async()=>{if(!e||!t)return;let te;try{te=JSON.parse(S)}catch{De.error("Input must be valid JSON");return}let J;if(k.trim())try{J=JSON.parse(k)}catch{De.error("Ground Truth must be valid JSON");return}let ae;if(C.trim())try{ae=JSON.parse(C)}catch{De.error("Metadata must be valid JSON");return}let pe;const Y=j!==m.trajectory;if(Y&&j.trim())try{pe=JSON.parse(j)}catch{De.error("Expected Trajectory must be valid JSON");return}let ee;const ce=I!==m.toolMocks;if(ce&&I.trim())try{const me=JSON.parse(I);if(!Array.isArray(me)){De.error("Tool Mocks must be a JSON array");return}ee=me}catch{De.error("Tool Mocks must be valid JSON");return}let de;const oe=R!==m.requestContext;if(oe&&R.trim())try{de=JSON.parse(R)}catch{De.error("Request Context must be valid JSON");return}try{await l.mutateAsync({datasetId:e,itemId:t,input:te,groundTruth:J,metadata:ae,...Y?{expectedTrajectory:pe??null}:{},...ce?{toolMocks:ee??[]}:{},...oe?{requestContext:de}:{}}),De.success("Item updated successfully"),b(!1)}catch(me){De.error(`Failed to update item: ${me instanceof Error?me.message:"Unknown error"}`)}},U=()=>{d&&(x(JSON.stringify(d.input,null,2)),_(d.groundTruth?JSON.stringify(d.groundTruth,null,2):""),E(d.metadata?JSON.stringify(d.metadata,null,2):""),T(d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):""),A(d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):""),L(d.requestContext?JSON.stringify(d.requestContext,null,2):"")),b(!1)},Z=async()=>{if(!(!e||!t))try{await c.mutateAsync({datasetId:e,itemId:t}),De.success("Item deleted successfully"),F(!1),r(`/datasets/${e}`)}catch(te){De.error(`Failed to delete item: ${te instanceof Error?te.message:"Unknown error"}`)}},K=p??d,ne=K?{id:t??"",datasetId:e??"",datasetVersion:K.datasetVersion,input:K.input,groundTruth:K.groundTruth,expectedTrajectory:K.expectedTrajectory,metadata:K.metadata,createdAt:K.createdAt,updatedAt:K.updatedAt}:null;return i&&ys(i)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ws,{})})}):i&&xs(i)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):a?null:!e||!t||!s||s.length===0?o.jsx(ds,{children:o.jsx(Cy,{children:o.jsx("div",{className:"text-neutral3 p-4",children:"Item not found"})})}):o.jsxs(o.Fragment,{children:[o.jsx(ds,{children:o.jsx("div",{className:"h-full overflow-hidden px-6 pb-4",children:o.jsxs("div",{className:"grid gap-6 max-w-[60rem] mx-auto grid-rows-[auto_1fr] h-full",children:[o.jsxs(ga,{children:[o.jsxs(ga.Column,{children:[o.jsxs(ga.Title,{children:[o.jsx(LN,{}),t," ",o.jsx($a,{content:t})]}),o.jsx(ga.Description,{children:o.jsxs(Fo,{children:["Item of ",o.jsx(uy,{})," ",u?.name]})}),o.jsxs(ga.Description,{children:[o.jsxs(Fo,{children:[o.jsx(ddt,{})," Created at"," ",d?.createdAt?nr(new Date(d.createdAt),"MMM d, yyyy"):""]}),o.jsxs(Fo,{children:[o.jsx(E_,{})," Latest version v",d?.datasetVersion??""]})]})]}),o.jsx(ga.Column,{children:!y&&!f&&o.jsxs(Mr,{children:[o.jsxs(le,{onClick:G,disabled:D,title:D?"Return to latest version to edit":void 0,children:[o.jsx(Edt,{})," Edit"]}),o.jsxs(le,{onClick:V,disabled:D,title:D?"Return to latest version to delete":void 0,children:[o.jsx(uu,{})," Delete"]})]})})]}),o.jsxs(ly,{className:y?"grid-cols-1":"grid-cols-[1fr_auto]",children:[o.jsxs(Yr,{withRightSeparator:!y,children:[f&&d&&o.jsx(En,{variant:"destructive",title:"Item deleted",children:o.jsxs(En.Message,{children:["This item was deleted at version v",d.datasetVersion]})}),!f&&D&&p&&o.jsx(En,{variant:"warning",title:"Previous version",action:o.jsxs(En.Button,{onClick:q,children:[o.jsx(idt,{})," Return to the latest version"]}),children:o.jsxs(En.Message,{children:["Viewing version v",p.datasetVersion]})}),y?o.jsx(n7t,{inputValue:S,setInputValue:x,groundTruthValue:k,setGroundTruthValue:_,metadataValue:C,setMetadataValue:E,trajectoryValue:j,setTrajectoryValue:T,toolMocksValue:I,setToolMocksValue:A,requestContextValue:R,setRequestContextValue:L,validationErrors:null,onSave:$,onCancel:U,isSaving:l.isPending}):ne?o.jsx(eIe,{item:ne,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})]}),!y&&o.jsx(Yr,{children:o.jsx(mos,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:B,onCompareVersionsClick:te=>{r(`/datasets/${e}/items/${t}/versions?ids=${te.join(",")}`)},activeVersion:p?.datasetVersion??null})})]})]})})}),o.jsx(At,{open:H,onOpenChange:F,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Item"}),o.jsx(At.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:Z,children:c.isPending?"Deleting...":"Delete"})]})]})})]})}function nXe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function Ros(){const{datasetId:e}=Sr(),[t,n]=Pi(),r=t.get("items")?.split(",").filter(Boolean)??[],{data:s,error:a}=Qx(e??""),{Link:i}=bn(),[l,c]=g.useState(!1),{data:u}=CV(e??"",r[0]??""),{data:d}=CV(e??"",r[1]??"");return a&&ys(a)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ws,{})})}):a&&xs(a)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||r.length<2?o.jsx(ds,{children:o.jsx(Cy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two items to compare."})})})}):o.jsxs(ds,{children:[o.jsx($y,{owner:"dataset-items-compare",children:o.jsxs(le,{as:ti,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(Rc,{}),"Back to Dataset"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:X("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":l}),children:[o.jsxs(ga,{children:[o.jsxs(ga.Column,{children:[o.jsxs(ga.Title,{children:[o.jsx(t1,{}),"Compare Dataset Items"]}),o.jsx(ga.Description,{children:o.jsxs(Fo,{children:["Comparing ",r.length," items of"," ",o.jsx(ti,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:s?.name||e?.slice(0,8)})]})})]}),o.jsx(ga.Column,{children:o.jsx(Mr,{children:o.jsx(le,{variant:"primary",onClick:()=>c(f=>!f),children:l?o.jsxs(o.Fragment,{children:[o.jsx(yxe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(Dpn,{})," Diff View"]})})})})]}),o.jsx(ly,{className:"grid-cols-[1fr_3vw_1fr]",children:r.map((f,p)=>o.jsxs(g.Fragment,{children:[o.jsx(Pos,{datasetId:e,itemId:f,Link:i,idx:p,itemIds:r,showContent:!l,onItemChange:h=>{const m=[...r];m[p]=h,n({items:m.join(",")})}}),p==0&&o.jsx("div",{className:X("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},f))}),l&&u&&d&&o.jsx(IEe,{codeA:nXe(u),codeB:nXe(d)})]})})]})}function Pos({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=CV(e,t),{data:u}=I1(e),d=new Set(s.filter((p,h)=>h!==r)),f=(u??[]).map(p=>({value:p.id,label:p.id,disabled:d.has(p.id)}));return o.jsxs(Yr,{children:[o.jsxs(Yr.Toolbar,{className:"flex gap-4",children:[o.jsxs(la,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(ua,{"aria-label":"Item",children:o.jsx(ca,{placeholder:"Select item"})}),o.jsx(da,{children:f.map(p=>o.jsx(Ar,{value:p.value,disabled:p.disabled,children:p.label},p.value))})]}),o.jsxs(le,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(E_,{}),"Versions"]})]}),i&&o.jsx(Yr.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(Wis,{item:l}),o.jsx(eIe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function rXe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function $os(){const{datasetId:e,itemId:t}=Sr(),[n,r]=Pi(),[s,a]=g.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(h=>!isNaN(h)&&h>0)??[],{data:l,error:c}=Qx(e??""),{Link:u}=bn(),{data:d}=YNe(e??"",t??""),{data:f}=Qye(e??"",t??"",i[0]??0,l?.version),{data:p}=Qye(e??"",t??"",i[1]??0,l?.version);return c&&ys(c)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ws,{})})}):c&&xs(c)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||!t||i.length<2?o.jsx(ds,{children:o.jsx(Cy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two versions to compare."})})})}):o.jsxs(ds,{children:[o.jsx($y,{owner:"dataset-item-versions-compare",children:o.jsxs(le,{as:ti,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(Rc,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:X("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":s}),children:[o.jsxs(ga,{children:[o.jsxs(ga.Column,{children:[o.jsxs(ga.Title,{children:[o.jsx(t1,{}),"Compare Dataset Item Versions"]}),o.jsx(ga.Description,{children:o.jsxs(Fo,{children:["Comparing ",i.length," versions of"," ",o.jsx(ti,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(ga.Column,{children:o.jsx(Mr,{children:o.jsx(le,{variant:"primary",onClick:()=>a(h=>!h),children:s?o.jsxs(o.Fragment,{children:[o.jsx(yxe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(Shn,{})," Diff View"]})})})})]}),o.jsx(ly,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((h,m)=>o.jsxs(g.Fragment,{children:[o.jsx(Mos,{datasetId:e,itemId:t,datasetVersion:h,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:v=>{const y=[...i];y[m]=v,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:X("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),s&&f&&p&&o.jsx(IEe,{codeA:rXe(f),codeB:rXe(p)})]})})]})}function Mos({datasetId:e,itemId:t,datasetVersion:n,latestVersion:r,allVersions:s,versionNumbers:a,Link:i,idx:l,showContent:c=!0,onVersionChange:u}){const{data:d,isLoading:f}=Qye(e,t,n,r),p=new Set(a.filter((v,y)=>y!==l)),h=s.map(v=>{const y=typeof v.updatedAt=="string"?new Date(v.updatedAt):v.updatedAt;return{value:String(v.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",v.datasetVersion]})," - ",nr(y,"MMM d, yyyy h:mm a"),v.isLatest?o.jsx(ea,{color:"blue",size:"small",children:"Latest"}):null]}),disabled:p.has(v.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(Yr,{children:[o.jsxs(Yr.Toolbar,{className:"grid gap-4 grid-cols-[auto_1fr]",children:[o.jsx(E_,{className:"w-6 h-6 opacity-50"}),o.jsxs(la,{name:`compare-version-${l}`,value:String(n),onValueChange:v=>u(Number(v)),children:[o.jsx(ua,{"aria-label":"Version",className:"w-full",children:o.jsx(ca,{placeholder:"Select version"})}),o.jsx(da,{children:h.map(v=>o.jsx(Ar,{value:v.value,disabled:v.disabled,children:v.label},v.value))})]})]}),c&&o.jsx(Yr.Content,{children:f?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):!d||!m?o.jsxs("div",{className:"text-neutral4 text-sm",children:["Version ",n," not found"]}):o.jsx(eIe,{item:m,Link:i})})]})}function Dos(){const{datasetId:e}=Sr(),[t]=Pi(),n=t.get("ids")?.split(",").map(Number).filter(v=>!isNaN(v)&&v>0)??[],r=Hs(),{data:s,error:a}=Qx(e??""),i=I1(e??"",void 0,n[0]??null),l=I1(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const v=new Map;for(const y of[...c,...u])v.has(y.id)||v.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...v.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(v=>[v.id,v])),[c]),p=g.useMemo(()=>new Map(u.map(v=>[v.id,v])),[u]);if(a&&ys(a))return o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ws,{})})});if(a&&xs(a))return o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(ds,{children:o.jsx(Cy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const h=(v,y,b)=>{r(`/datasets/${e}/items/${v}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(v,y)=>{r(`/datasets/${e}/versions?ids=${v},${y}`,{replace:!0})};return o.jsx(ds,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",children:[o.jsxs(ga,{children:[o.jsxs(ga.Column,{children:[o.jsxs(ga.Title,{children:[o.jsx(fgn,{})," Compare Dataset Versions"]}),o.jsx(ga.Description,{children:o.jsxs(Fo,{children:[o.jsx(E_,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(ga.Column,{children:o.jsxs(le,{as:ti,to:`/datasets/${e}`,children:[o.jsx(Rc,{}),"Back to Dataset"]})})]}),o.jsx(ly,{children:o.jsxs(Yr,{children:[o.jsx(yos,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(Sos,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p,onItemClick:h})]})})]})})})}function Kye({children:e,className:t}){return o.jsx("div",{className:X("flex flex-wrap gap-8",t),children:e})}function Los(e){if(!e||e.length<2)return null;const t=[...e].sort((i,l)=>new Date(i.createdAt).getTime()-new Date(l.createdAt).getTime()),n=Math.floor(t.length/2),r=n,s=t.length-n;if(r===0)return null;const a=(s-r)/r*100;return{changePct:Math.round(a*10)/10,prevValue:String(r)}}function Fos({scorers:e,datasets:t,experiments:n,avgScore:r,prevAvgScore:s,totalNeedsReview:a,isLoadingScorers:i,isLoadingDatasets:l,isLoadingExperiments:c,isLoadingScores:u,isLoadingReview:d}){const f=e?Object.keys(e).length:void 0,p=t?.length,h=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,v=Los(n);return o.jsxs(o.Fragment,{children:[o.jsxs(es,{children:[o.jsx(es.Label,{children:"Total Scorers"}),i?o.jsx(es.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(f)}),o.jsx(es.NoChange,{message:"Static count"})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Total Datasets"}),l?o.jsx(es.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(p)}),o.jsx(es.NoChange,{message:"Static count"})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Avg Score"}),u?o.jsx(es.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(r)}),m?o.jsx(es.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(es.NoChange,{})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Total Experiments"}),c?o.jsx(es.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(h)}),v?o.jsx(es.Change,{changePct:v.changePct,prevValue:v.prevValue}):o.jsx(es.NoChange,{})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Needs Review"}),d?o.jsx(es.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(a)}),a>0?o.jsx(es.NoChange,{message:"items pending review"}):o.jsx(es.NoChange,{message:"All caught up"})]}):o.jsx(es.NoData,{})]})]})}const sXe="auto 1fr auto auto auto auto auto auto auto";function zos(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}const Bos={completed:"success",running:"warning",failed:"error",pending:"neutral"};function Uos({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all"}){const{paths:l,Link:c}=bn(),u=g.useMemo(()=>{const p=new Map;return t?.forEach(h=>p.set(h.id,h.name)),p},[t]),d=g.useMemo(()=>[...e].sort((p,h)=>{const m=p.createdAt?new Date(p.createdAt).getTime():0;return(h.createdAt?new Date(h.createdAt).getTime():0)-m}),[e]),f=g.useMemo(()=>{const p=s.toLowerCase();return d.filter(h=>{const m=h.datasetId?u.get(h.datasetId)??"":"",v=!p||h.id.toLowerCase().includes(p)||m.toLowerCase().includes(p)||(h.targetId??"").toLowerCase().includes(p),y=a==="all"||h.status===a,b=i==="all"||h.datasetId===i;return v&&y&&b})},[d,s,u,a,i]);return r?o.jsx(ll,{columns:sXe}):o.jsxs(ve,{columns:sXe,variant:"striped",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Experiment"}),o.jsx(ve.TopCell,{children:"Dataset"}),o.jsx(ve.TopCell,{children:"Target"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{className:"text-center",children:"Items"}),o.jsx(ve.TopCell,{className:"text-center",children:"Succeeded"}),o.jsx(ve.TopCell,{className:"text-center",children:"Failed"}),o.jsx(ve.TopCell,{className:"text-center",children:"Review"}),o.jsx(ve.TopCell,{children:"Date"})]}),f.map(p=>{const h=p.datasetId?u.get(p.datasetId)??p.datasetId.slice(0,8):"—",m=p.status??"pending",v=p.succeededCount??0,y=p.failedCount??0,b=p.totalItems??0,S=b>0?Math.round(v/b*100):0;return o.jsxs(ve.RowLink,{to:l.experimentLink(p.id),LinkComponent:c,children:[o.jsx(ve.NameCell,{className:"font-mono",children:p.id.slice(0,8)}),o.jsx(ve.TextCell,{children:h}),o.jsx(ve.Cell,{children:o.jsxs("span",{className:"truncate",children:[p.targetType," ",p.targetId]})}),o.jsx(ve.Cell,{children:o.jsx(bg,{variant:Bos[m]??"neutral",withDot:!0,children:m})}),o.jsx(ve.TextCell,{className:"text-center",children:b}),o.jsx(ve.TextCell,{className:"text-center",children:o.jsxs("span",{className:v>0?"text-accent1":"",children:[v," (",S,"%)"]})}),o.jsx(ve.TextCell,{className:"text-center",children:o.jsx("span",{className:y>0?"text-accent2":"",children:y})}),o.jsx(ve.Cell,{className:"text-center",children:(()=>{const x=n?.get(p.id);if(!x)return o.jsx("span",{className:"text-neutral2",children:"—"});const k=x.needsReview+x.complete;return k===0?o.jsx("span",{className:"text-neutral2",children:"—"}):x.needsReview>0?o.jsxs(ea,{size:"small",color:"yellow",children:[x.needsReview," pending"]}):o.jsxs(ea,{size:"small",color:"green",children:[x.complete,"/",k," reviewed"]})})()}),o.jsx(ve.TextCell,{children:zos(p.createdAt)})]},p.id)})]})}const Vos=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function qos(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const Az={completed:"#22c55e",running:"#facc15",pending:"#fb923c",failed:"#f87171"},Hos=[{label:"Completed",color:Az.completed},{label:"Running",color:Az.running},{label:"Pending",color:Az.pending},{label:"Failed",color:Az.failed}];function Wos({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=g.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const p=f.datasetId??"unknown";c.has(p)||c.set(p,{completed:0,running:0,pending:0,failed:0});const h=c.get(p),m=f.status;m in h&&h[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,p])=>{const h=p.completed+p.running+p.pending+p.failed;return h>u&&(u=h),{name:l.get(f)??f.slice(0,12),values:[p.completed,p.running,p.pending,p.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Wt.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Wt.Loading,{}):r?o.jsx(Wt.Error,{message:"Failed to load experiments data"}):o.jsx(Wt.Content,{children:i?o.jsx(NN,{data:s,segments:Hos,maxVal:a,fmt:l=>String(l)}):o.jsx(Wt.NoData,{message:"No experiments have been run yet"})})]})}const Zos=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zr,{iconSlot:o.jsx(If,{}),titleSlot:"No Experiments yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Run an experiment from a dataset to evaluate ",o.jsx("br",{}),"your agents and workflows."]}),actionSlot:o.jsx("div",{className:"flex flex-col items-center gap-2",children:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/evals/datasets/running-experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(ka,{})]})})})});function Gos({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c}){return o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx($f,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t}),o.jsxs(Mr,{children:[o.jsx(Ec,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...Vos],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(Ec,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(le,{onClick:l,size:"sm",variant:"default",children:[o.jsx(bs,{className:"size-3"})," Reset"]})]})]})}function Qos(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=ih(),{data:l,isLoading:c,error:u}=Bg(),{data:d,isLoading:f,error:p}=VG(),{data:h,isLoading:m,isError:v,error:y}=jXr(n),{data:b,isLoading:S,isError:x,error:k}=rIe(),_=l?.datasets,C=d?.experiments,E=g.useMemo(()=>Cos(b),[b]),j=i||u||p||y||k;return j&&ys(j)?o.jsx(lr,{children:o.jsx(Ws,{})}):j&&xs(j)?o.jsx(lr,{children:o.jsx(Ds,{resource:"evaluation"})}):j?o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load evaluation data",message:j.message})}):o.jsxs(Ft,{width:"wide",height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsx(Ft.Row,{children:o.jsx(Ft.Column,{children:o.jsx(UG,{preset:e,onPresetChange:t,dateFrom:n.start,dateTo:n.end,onDateChange:(T,I)=>r(A=>I==="from"?{...A,start:T}:{...A,end:T})})})})}),o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsx(Kye,{children:o.jsx(Fos,{scorers:s,datasets:_,experiments:C,avgScore:h?.avgScore??null,prevAvgScore:h?.prevAvgScore??null,totalNeedsReview:E.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:S})}),o.jsx(zKr,{summaryData:h?.summaryData??[],overTimeData:h?.overTimeData??[],scorerNames:h?.scorerNames??[],avgScore:h?.avgScore??null,isLoading:m,isError:v}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(Eas,{experiments:C,isLoading:f,isError:!!p}),o.jsx(Wos,{experiments:C,datasets:_,isLoading:f,isError:!!p})]}),o.jsx(Oos,{reviewSummary:b,experiments:C,datasets:_,isLoading:S,isError:!!x})]})]})}function Yos(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,a]=g.useState("all"),{data:i,isLoading:l,error:c}=Bg(),{data:u,isLoading:d,error:f}=VG(),{data:p}=rIe(),h=g.useMemo(()=>i?.datasets??[],[i?.datasets]),m=g.useMemo(()=>u?.experiments??[],[u?.experiments]),v=g.useMemo(()=>qos(h),[h]),y=g.useMemo(()=>i7t(p),[p]),b=l||d,S=f||c;if(S&&ys(S))return o.jsx(lr,{children:o.jsx(Ws,{})});if(f&&xs(f))return o.jsx(lr,{children:o.jsx(Ds,{resource:"experiments"})});if(c&&xs(c))return o.jsx(lr,{children:o.jsx(Ds,{resource:"datasets"})});if(S)return o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load experiments",message:S.message})});if(m.length===0&&!b)return o.jsx(lr,{children:o.jsx(Zos,{})});const x=n!=="all"||s!=="all"||e!=="",k=()=>{t(""),r("all"),a("all")};return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(Gos,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:v,onReset:k,hasActiveFilters:x})}),o.jsx(Uos,{experiments:m,datasets:h,reviewByExperiment:y,isLoading:b,search:e,statusFilter:n,datasetFilter:s})]})}function Rz({children:e}){return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:e})]})}function Kos(){const{experimentId:e}=Sr(),{data:t,isLoading:n}=VG(),s=t?.experiments?.find(h=>h.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=_V(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p}=FG({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&ys(l)?o.jsx(Rz,{children:o.jsx(Ws,{})}):l&&xs(l)?o.jsx(Rz,{children:o.jsx(Ds,{resource:"datasets"})}):l&&J_e(l)||!n&&!s||!i&&!l&&!a?o.jsx(Rz,{children:o.jsx(zr,{iconSlot:o.jsx(vxe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(le,{as:ti,to:"/experiments",children:[o.jsx(Rc,{}),"Back to Experiments"]})})}):l?o.jsx(Rz,{children:o.jsx(Hi,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Ft,{height:"full",children:[o.jsx(o7t,{experiment:a}),o.jsx(Ft.MainArea,{children:o.jsx(a7t,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p})})]})}function Xos({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsxs("li",{className:"flex items-center justify-between border-b py-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"font-mono text-xs",children:e.connectionId}),o.jsxs("div",{className:"text-xs text-gray-500",children:[e.label??"(no label)"," · ",e.status,e.scope?` · ${e.scope}`:"",t&&e.authorId?` · author: ${e.authorId}`:""]})]}),o.jsx("button",{type:"button",className:"text-red-600 underline disabled:opacity-50",onClick:r,disabled:n,children:"Disconnect"})]})}function l7t({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(Xos,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function Jos({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("div",{className:"space-y-4",children:e.map(([s,a])=>o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-semibold text-gray-700","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),o.jsx(l7t,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function els({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:s,isLoading:a,error:i,disconnectPending:l,disconnectError:c,onDisconnect:u}){return o.jsxs("div",{className:"space-y-2 border rounded p-4",children:[o.jsx("h2",{className:"text-lg font-semibold",children:"Existing connections"}),!e||!t?o.jsx("p",{className:"text-gray-500",children:"Pick a provider and toolkit to list connections."}):a?o.jsx("p",{className:"text-gray-500",children:"Loading…"}):i?o.jsx("p",{className:"text-red-600",children:String(i)}):n.length===0?o.jsx("p",{className:"text-gray-500",children:"No connections."}):r?o.jsx(Jos,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(l7t,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function tls({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:a,providersError:i,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:p,onToolkitChange:h,onLabelChange:m,onConnect:v}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>p(y.target.value),disabled:a,children:[o.jsx("option",{value:"",children:"— select provider —"}),e.map(y=>o.jsxs("option",{value:y.id,children:[y.displayName??y.name," (",y.id,")"]},y.id))]}),a&&o.jsx("span",{className:"text-gray-500",children:"Loading providers…"}),i?o.jsx("span",{className:"text-red-600",children:String(i)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"toolkit-select",children:"Toolkit"}),o.jsxs("select",{id:"toolkit-select",className:"border rounded px-2 py-1 w-full",value:r,onChange:y=>h(y.target.value),disabled:!n||l,children:[o.jsx("option",{value:"",children:"— select toolkit —"}),t.map(y=>o.jsxs("option",{value:y.slug,children:[y.name," (",y.slug,")"]},y.slug))]}),l&&o.jsx("span",{className:"text-gray-500",children:"Loading toolkits…"}),c?o.jsx("span",{className:"text-red-600",children:String(c)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"label-input",children:"Label (optional)"}),o.jsx("input",{id:"label-input",type:"text",className:"border rounded px-2 py-1 w-full",placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value),disabled:!n||!r})]}),o.jsx("button",{type:"button",className:"bg-blue-600 text-white rounded px-4 py-2 disabled:opacity-50",onClick:v,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const aXe=e=>e.authorId?.trim()||"shared",nls=(e,t)=>{if(!t||new Set(e.map(aXe)).size<=1)return null;const r=new Map;for(const a of e){const i=aXe(a);r.set(i,[...r.get(i)??[],a])}const s=Array.from(r.entries());return s.sort(([a],[i])=>a==="shared"?1:i==="shared"?-1:a.localeCompare(i)),s},rls=["*","tool-providers:*","tool-providers:admin"];function sls(){const{data:e}=Cm();return e?.permissions?.some(t=>rls.includes(t))??!1}function als(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=PI(),l=XW(e||null),c=BPt(e||null,n||null),u=zPt(),d=DPt(),f=sls(),p=i.data?.providers??[],h=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>nls(m,f),[m,f]),y=x=>{t(x),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{a(""),c.refetch()}})},S=x=>{d.mutate({providerId:e,connectionId:x})};return o.jsxs("div",{className:"p-6 max-w-3xl space-y-6 text-sm",children:[o.jsx("h1",{className:"text-2xl font-semibold",children:"Integrations"}),o.jsx("p",{className:"text-gray-500",children:"Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect."}),o.jsx(tls,{providers:p,toolkits:h,providerId:e,toolkit:n,label:s,providersLoading:i.isLoading,providersError:i.error,toolkitsLoading:l.isLoading,toolkitsError:l.error,authorizePending:u.isPending,authorizeError:u.error,authorizedConnection:u.data,onProviderChange:y,onToolkitChange:r,onLabelChange:a,onConnect:b}),o.jsx(els,{providerId:e,toolkit:n,connections:m,groupedByAuthor:v,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:S})]})}function ils({title:e,description:t,errorBanner:n,children:r}){return o.jsx("div",{"data-testid":"login-page",className:"flex min-h-screen items-center justify-center bg-surface1",children:o.jsxs("div",{className:"w-full max-w-sm space-y-6",children:[o.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[o.jsx(Xh,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-xl font-semibold text-neutral6",children:e})]}),t,n,r]})})}function c7t({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=dc(),{mutate:i,isPending:l,error:c}=gTr(),{mutate:u,isPending:d,error:f}=yTr(),{mutate:p,isPending:h}=i2t(),[m,v]=g.useState(n),[y,b]=g.useState(""),[S,x]=g.useState(""),[k,_]=g.useState("");if(a)return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-surface1",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-surface1",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:C}=s,E=C.type==="sso"||C.type==="both",j=C.type==="credentials"||C.type==="both",T=C.sso,I=C.signUpEnabled!==!1,A=m==="signin"||!I,R=A?l:d,L=A?c:f,M=()=>{t?t():e?window.location.href=e:window.location.href="/"},z=D=>{D.preventDefault(),A?i({email:S,password:k},{onSuccess:M}):u({email:S,password:k,name:y||void 0},{onSuccess:M})},H=()=>{p({redirectUri:e},{onSuccess:D=>{window.location.href=D.url}})},F=()=>{v(A?"signup":"signin")},B=C.description?o.jsxs("div",{className:"flex items-start gap-2.5 rounded-md border border-border1 bg-surface1 p-3",children:[o.jsx(Cf,{className:"mt-0.5 h-4 w-4 shrink-0 text-neutral4"}),o.jsx("p",{className:"text-sm text-neutral3",children:C.description})]}):null,q=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(ils,{title:A?"Sign in to Mastra Studio":"Create your account",description:B,errorBanner:q,children:[j&&o.jsxs("form",{onSubmit:z,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"block text-sm text-neutral4",children:"Name"}),o.jsx(Cn,{id:"name",type:"text",value:y,onChange:D=>b(D.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"email",className:"block text-sm text-neutral4",children:"Email"}),o.jsx(Cn,{id:"email",type:"email",value:S,onChange:D=>x(D.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"password",className:"block text-sm text-neutral4",children:"Password"}),o.jsx(Cn,{id:"password",type:"password",value:k,onChange:D=>_(D.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),L&&o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:L.message}),o.jsx(le,{type:"submit",disabled:R,className:"w-full",size:"lg",children:R?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-center text-sm",children:[o.jsx("span",{className:"text-neutral3",children:A?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:F,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),E&&j&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"w-full border-t border-border1"})}),o.jsx("div",{className:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 px-2 text-neutral3",children:"or continue with"})})]}),E&&T&&o.jsxs(le,{onClick:H,disabled:h,className:"w-full",size:"lg",variant:"outline",children:[T.icon&&o.jsx("span",{className:"mr-2",children:T.icon}),h?"Redirecting...":T.text||"Sign in"]})]})}function ols(){const[e]=Pi(),t=Hs(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",a=e.get("error_description")||e.get("error")||null,i=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(c7t,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}function lls({collapsed:e,children:t}){return o.jsx("section",{className:X("flex flex-col overflow-hidden rounded-xl border border-border1 bg-surface2",e?"h-auto":"h-full"),children:t})}function cls({onClick:e,tooltip:t="Close panel",className:n}){return o.jsx(le,{size:"md",onClick:e,"aria-label":"Close Panel",tooltip:t,className:n,children:o.jsx(Hu,{})})}function uls(){return lI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"#939393",background:"transparent"},styles:[{tag:[fe.className,fe.propertyName]}]})}function dls(){const e=Nt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.75rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-activeLineGutter":{backgroundColor:"transparent"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"}}),t=Ug.define([{tag:[fe.comment,fe.bracket],color:"var(--neutral2)"},{tag:[fe.string,fe.meta,fe.regexp],color:"var(--accent1)"},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:"var(--accent6)"},{tag:[fe.keyword,fe.operator,fe.tagName],color:"var(--accent2)"},{tag:[fe.function(fe.propertyName),fe.propertyName],color:"var(--accent5)"},{tag:[fe.definition(fe.variableName),fe.function(fe.variableName),fe.className,fe.attributeName],color:"var(--accent3)"},{tag:[fe.variableName,fe.number],color:"var(--accent5)"},{tag:[fe.name,fe.quote],color:"var(--accent1)"}]);return[e,H1(t)]}const fls=()=>{const e=q_().resolvedTheme==="dark";return g.useMemo(()=>e?uls():dls(),[e])};function pls({codeStr:e="",title:t,icon:n,simplified:r=!1,className:s}){const a=fls(),[i,l]=g.useState(!1),c=g.useMemo(()=>{try{const f=JSON.parse(e);return Xye(f||"")}catch{return!1}},[e]),u=i?e?.replace(/\\n/g,`
|
|
732
732
|
`):e,d=r||i;return!e||e==="null"?null:o.jsxs("div",{className:X("flex flex-col gap-2",s),children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:X("flex items-center gap-1.5 text-ui-xs tracking-widest text-neutral2 uppercase","[&>svg]:size-3.5"),children:[n,t]}),o.jsxs(Mr,{children:[o.jsx($a,{content:e||"No content",size:"sm"}),c&&o.jsx(le,{size:"sm","aria-label":i?"Show escaped newlines":"Show multiline text",onClick:()=>l(f=>!f),children:i?o.jsx(E$,{}):o.jsx(p7,{})})]})]}),o.jsx("div",{className:"max-h-[30vh] overflow-hidden overflow-y-auto rounded-lg border border-border1 bg-surface3 p-3 text-ui-sm break-all text-neutral4 dark:border-white/10 dark:bg-black/20",children:d?o.jsx("div",{className:"font-mono break-all text-neutral4",children:o.jsx("pre",{className:"text-wrap",children:u})}):o.jsx(Gu,{extensions:[$T(),Nt.lineWrapping],theme:a,value:e,editable:!1})})]})}function Xye(e){if(typeof e=="string"){const t=e.indexOf(`
|
|
733
|
-
`);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>Xye(t));if(e&&typeof e=="object")return Object.values(e).some(t=>Xye(t))}return!1}function hls({children:e}){return o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e})}function mls({className:e,children:t}){return o.jsx("div",{className:X("mx-4 flex items-center justify-between gap-2 border-b border-border1 py-3",e),children:t})}function gls({className:e,children:t}){return o.jsx("h3",{className:X("flex gap-2 text-ui-md text-neutral3 [&>b]:font-normal [&>b]:text-neutral2",e),children:t})}function vls({className:e,children:t}){return o.jsx("dl",{className:X("grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5",e),children:t})}function yls({className:e,children:t}){return o.jsx("dt",{className:X("shrink-0 py-0.5 text-ui-smd text-neutral2",e),children:t})}function bls({className:e,children:t}){return o.jsx("dd",{className:X("min-w-0 truncate py-0.5 text-ui-smd text-neutral3",e),children:t})}function xls({className:e,children:t}){return o.jsx("dt",{className:X("col-span-2 py-3 text-ui-sm tracking-widest text-neutral2 uppercase",e),children:t})}const wls=Object.assign(vls,{Key:yls,Value:bls,Header:xls});function Sls({children:e}){return o.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-6 text-ui-sm text-neutral3",children:[o.jsx(Kt,{size:"sm",variant:"pulse",className:"text-neutral3"})," ",e??"Loading..."]})}function kls({children:e}){return o.jsx("p",{className:"px-4 py-6 text-ui-sm text-neutral2",children:e??"No data found."})}const Bi=Object.assign(lls,{Header:mls,Heading:gls,CloseButton:cls,LoadingData:Sls,NoData:kls,Content:hls,KeyValueList:wls,CodeSection:pls}),ap=Bi.KeyValueList;function Ols(e){return e instanceof Date?e:new Date(e)}function _ls({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,p=Ols(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(Bi,{collapsed:d,children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Log ",o.jsx("b",{children:nr(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[l&&o.jsx(le,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(Mq,{}):o.jsx(ewe,{})}),o.jsxs(Mr,{spacing:"close",children:[o.jsx(le,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx($q,{})}),o.jsx(le,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(c4,{})})]}),o.jsx(Bi.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Bi.Content,{children:[o.jsx("p",{className:"font-mono text-ui-md wrap-break-word whitespace-pre-wrap text-neutral4",children:e.message}),(h||m)&&o.jsxs("div",{className:X("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(h7,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:" ml-auto min-w-0 truncate text-ui-sm text-neutral2",children:["# ",h]})]}),o.jsx($a,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(h7,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:" ml-auto min-w-0 truncate text-ui-sm text-neutral2",children:["# ",m]})]}),o.jsx($a,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(ap,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Entity Type"}),o.jsx(ap.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Entity Name"}),o.jsx(ap.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Service"}),o.jsx(ap.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Environment"}),o.jsx(ap.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Source"}),o.jsx(ap.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([v,y])=>o.jsxs(g.Fragment,{children:[o.jsx(ap.Key,{children:v}),o.jsx(ap.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Bi.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function Cls({error:e,resource:t,errorTitle:n}){if(ys(e))return o.jsx(Ws,{});if(xs(e))return o.jsx(Ds,{resource:t});if(QAt(e,"logs"))return o.jsx(zr,{iconSlot:o.jsx(twe,{}),titleSlot:"Logs are not available with your current storage",descriptionSlot:"The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio."});const r=e instanceof Error?e.message:void 0;return o.jsx(Hi,{title:n,message:r??"Unknown error"})}function Els({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:X("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:X("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const jls={debug:{label:"DEBUG",color:"#71717a"},info:{label:"INFO",color:"#60a5fa"},warn:{label:"WARN",color:"#facc15"},error:{label:"ERROR",color:"#f87171"},fatal:{label:"FATAL",color:"#dc2626"}};function Tls({level:e}){const t=jls[e];return o.jsx(To,{height:"compact",children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function Nls({entityType:e,className:t}){const n=X("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case _s.AGENT:return o.jsx(Vo,{className:n,"aria-hidden":!0});case"workflow":case _s.WORKFLOW_RUN:return o.jsx(Xu,{className:n,"aria-hidden":!0});case _s.TOOL:return o.jsx(Ld,{className:n,"aria-hidden":!0});default:return null}}function Ils({entityType:e,entityName:t}){const n=e??"";return o.jsxs(To,{height:"compact",className:"flex min-w-0 items-center gap-2",children:[o.jsx(Nls,{entityType:n}),t?o.jsx("span",{className:"min-w-0 truncate text-ui-smd",children:t}):"-"]})}function Als({message:e}){return o.jsx(To,{height:"compact",className:"min-w-0 truncate font-mono text-ui-smd text-neutral4",children:e})}function Rls({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(To,{height:"compact",children:null});const t=Object.entries(e).map(([n,r])=>{if(typeof r=="string")return`${n}: ${r}`;try{return`${n}: ${JSON.stringify(r)}`}catch{return`${n}: <unserializable>`}}).join(", ");return o.jsx(GCe,{children:t})}const Ql=Object.assign(E3,{Top:aZ,TopCell:lC,TopCellWithTooltip:iZ,TopCellSmart:E$t,RowWrapper:JCe,RowButton:j3,RowLink:j$t,Spacer:XCe,NoMatch:sZ,DateCell:QCe,TimeCell:YCe,LevelCell:Tls,EntityCell:Ils,MessageCell:Als,DataCell:Rls,NextPageLoading:rZ}),iXe="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",Pls=36,$ls=8;function Mls({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=q9t({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>Pls,overscan:$ls}),d=g.useRef(t);if(g.useEffect(()=>{d.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),d.current=t},[t]),t)return o.jsx(ll,{columns:iXe});const f=u.getVirtualItems(),p=u.getTotalSize(),h=f[0]?.start??0,m=f.length>0?Math.max(0,p-(f[f.length-1]?.end??0)):0;return o.jsxs(Ql,{columns:iXe,variant:"striped",scrollRef:c,className:"min-w-0",children:[o.jsxs(Ql.Top,{children:[o.jsx(Ql.TopCell,{children:"Date"}),o.jsx(Ql.TopCell,{children:"Time"}),o.jsx(Ql.TopCell,{children:"Level"}),o.jsx(Ql.TopCell,{children:"Entity"}),o.jsx(Ql.TopCell,{children:"Message"}),o.jsx(Ql.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Ql.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Ql.Spacer,{height:h}),f.map(v=>{const y=e[v.index];if(!y)return null;const b=a.get(y);if(!b)return null;const S=b===i;return o.jsxs(Ql.RowButton,{ref:u.measureElement,"data-index":v.index,onClick:()=>l(y),featured:S,variant:y.level==="error"||y.level==="fatal"?"error":"default",children:[o.jsx(Ql.DateCell,{timestamp:y.timestamp}),o.jsx(Ql.TimeCell,{timestamp:y.timestamp}),o.jsx(Ql.LevelCell,{level:y.level}),o.jsx(Ql.EntityCell,{entityType:y.entityType,entityName:y.entityName}),o.jsx(Ql.MessageCell,{message:y.message}),o.jsx(Ql.DataCell,{data:y.data})]},b)}),o.jsx(Ql.Spacer,{height:m})]}),o.jsx(Ql.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function Dls({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>Lls(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(MNe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(PNe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Lls(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 Fls={"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"},fae="MMM d, yyyy HH:mm",pae="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function zls({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${Fls[e]}`,description:pae}:t&&n?{title:`No logs between ${nr(t,fae)} and ${nr(n,fae)}`,description:pae}:t?{title:`No logs since ${nr(t,fae)}`,description:pae}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const Bls=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=zls({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zr,{iconSlot:o.jsx(twe,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(nwe,{})]})})})},Uls=20,Vls=1e4;function qls(e,t,n){if(e?.pagination?.hasMore)return n+1}function Hls(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const a=s.logId??JSON.stringify(s);t.has(a)||(t.add(a),n.push(s))}return n}function Wls(e){return QAt(e.state.error,"logs")?!1:Vls}const Zls=({filters:e}={})=>{const t=We(),{inView:n,setRef:r}=Q_(),s=F1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:Uls},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:qls,select:Hls,retry:!1,refetchInterval:Wls}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},Pz={AGENT:_s.AGENT,WORKFLOW:_s.WORKFLOW_RUN,SCORER:_s.SCORER,INGEST:_s.RAG_INGESTION},u7t=[{label:"Agent",entityType:Pz.AGENT},{label:"Workflow",entityType:Pz.WORKFLOW},{label:"Scorer",entityType:Pz.SCORER},{label:"Ingest",entityType:Pz.INGEST}],Gls=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],zx="rootEntityType",Gb="datePreset",Qb="dateFrom",Yb="dateTo",Qls=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Il={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"},O5=Object.keys(Il),sIe=new Set(["tags"]),aIe="mastra:logs:saved-filters";function Yls(e,t=aIe){const n=tcs(e),r=e.get(Gb);r&&n.set(Gb,r);const s=e.get(Qb);s&&n.set(Qb,s);const a=e.get(Yb);a&&n.set(Yb,a);try{localStorage.setItem(t,n.toString())}catch{}}function Kls(e=aIe){try{localStorage.removeItem(e)}catch{}}function oXe(e=aIe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Xls(e){if(e.has(Gb)||e.has(Qb)||e.has(Yb)||e.has(zx))return!0;for(const t of O5)if(e.has(Il[t]))return!0;return!1}function Jls({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:u7t.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:Gls.map(u=>({label:u.label,value:u.value})),placeholder:"Choose level",emptyText:"No levels."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"spanId",label:"Span ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function ecs(e){const t=[],n=new Map([[zx,"rootEntityType"]]);for(const s of O5)n.set(Il[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),sIe.has(a)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function tcs(e){const t=new URLSearchParams,n=e.get(zx);n&&t.set(zx,n);for(const r of O5){const s=Il[r];if(sIe.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const a=e.get(s);a&&t.set(s,a)}return t}function ncs(e,t){e.delete(zx);for(const n of O5)e.delete(Il[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(zx,n.value);continue}const r=Il[n.fieldId];if(r){if(sIe.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 rcs({rootEntityType:e,dateFrom:t,dateTo:n,tokens:r}){const s={};e&&(s.rootEntityType=e),(t||n)&&(s.timestamp={...t?{start:t}:{},...n?{end:n}:{}});for(const a of r){if(a.fieldId==="tags"){Array.isArray(a.value)&&a.value.length>0?s.tags=a.value:typeof a.value=="string"&&a.value.trim()&&(s.tags=[a.value.trim()]);continue}if(a.fieldId==="level"){typeof a.value=="string"&&a.value.trim()&&a.value!=="Any"&&(s.level=a.value);continue}if(typeof a.value=="string"&&a.value.trim()&&a.value!=="Any")switch(a.fieldId){case"entityName":s.rootEntityName=a.value;break;case"traceId":s.traceId=a.value;break;case"spanId":s.spanId=a.value;break;case"runId":s.runId=a.value;break;case"threadId":s.threadId=a.value;break;case"sessionId":s.sessionId=a.value;break;case"requestId":s.requestId=a.value;break;case"resourceId":s.resourceId=a.value;break;case"userId":s.userId=a.value;break;case"organizationId":s.organizationId=a.value;break;case"serviceName":s.serviceName=a.value;break;case"environment":s.environment=a.value;break;case"experimentId":s.experimentId=a.value;break}}return s}function scs(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 acs="Filters setting for Logs saved",ics="Filters setting for Logs cleared up";function ocs(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>oXe(r)!==null),c=g.useCallback(()=>{Yls(e,r),l(!0);const f=s?.saved??acs;f!==!1&&De.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{Kls(r),l(!1);const f=s?.cleared??ics;f!==!1&&De.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,Xls(e)))return;const f=oXe(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function lcs(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 ccs(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,lcs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function ucs(e,t,n,r){const s=g.useMemo(()=>ccs(e),[e]),a=g.useMemo(()=>{const h=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&h.set(y,{log:v,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(h=>s.get(h),[s]),d=g.useCallback(h=>{const m=s.get(h);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const h=e[l-1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0,p=l>=0&&l<e.length-1?()=>{const h=e[l+1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:p}}const Jye="logId",ebe="traceId",tbe="spanId",i2=1440*60*1e3,dcs={"last-24h":i2,"last-3d":3*i2,"last-7d":7*i2,"last-14d":14*i2,"last-30d":30*i2};function $z(e){e.delete(Jye),e.delete(ebe),e.delete(tbe)}function fcs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(Gb);return _&&Qls.has(_)?_:"last-24h"},[e]),a=e.get(Qb),i=e.get(Yb),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const C=new Date(a);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=dcs[s];return _?new Date(Date.now()-_):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const _=new Date(i);return Number.isNaN(_.getTime())?void 0:_},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(Jye),f=e.get(ebe),p=e.get(tbe),h=g.useMemo(()=>u7t.find(_=>_.entityType===e.get(zx)),[e]),m=g.useMemo(()=>ecs(e),[e]),v=g.useCallback(_=>{t(C=>{const E=new URLSearchParams(C);for(const[j,T]of Object.entries(_)){const I=j==="logId"?Jye:j==="traceId"?ebe:tbe;T?E.set(I,T):E.delete(I)}return E},{replace:!0})},[t]),y=g.useCallback(_=>{t(C=>{const E=new URLSearchParams(C);return ncs(E,_),$z(E),E},{replace:!0})},[t]),b=y,S=g.useCallback((_,C)=>{if(u.current!=="custom")return;const E=C==="from"?Qb:Yb;t(j=>{const T=new URLSearchParams(j);return _?T.set(E,_.toISOString()):T.delete(E),$z(T),T},{replace:!0})},[t]),x=g.useCallback(_=>{u.current=_,t(C=>{const E=new URLSearchParams(C);return _==="last-24h"?(E.delete(Gb),E.delete(Qb),E.delete(Yb)):_==="custom"?E.set(Gb,"custom"):(E.set(Gb,_),E.delete(Qb),E.delete(Yb)),$z(E),E},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(zx);for(const E of O5)C.delete(Il[E]);return C.delete(Gb),C.delete(Qb),C.delete(Yb),$z(C),C},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:S,handleDatePresetChange:x,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,v,b,S,x,k,y])}const kb=Bi.KeyValueList;function pcs({spanId:e,span:t,isLoading:n,onClose:r}){const s=t?.startedAt&&t?.endedAt?new Date(t.endedAt).getTime()-new Date(t.startedAt).getTime():null;return o.jsxs(Bi,{children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Bi.CloseButton,{onClick:r})]}),n?o.jsx(Bi.LoadingData,{children:"Loading span..."}):t?o.jsxs(Bi.Content,{children:[o.jsxs(kb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Type"}),o.jsx(kb.Value,{children:t.spanType})]}),t.startedAt&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Started"}),o.jsx(kb.Value,{children:nr(new Date(t.startedAt),"MMM dd, HH:mm:ss.SSS")})]}),t.endedAt&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Ended"}),o.jsx(kb.Value,{children:nr(new Date(t.endedAt),"MMM dd, HH:mm:ss.SSS")})]}),s!=null&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Duration"}),o.jsx(kb.Value,{children:s<1e3?`${s}ms`:`${(s/1e3).toFixed(2)}s`})]})]}),o.jsx("br",{}),o.jsx(Bi.CodeSection,{title:"Input",icon:o.jsx(Gpe,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Output",icon:o.jsx(Qpe,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Metadata",icon:o.jsx(yw,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Attributes",icon:o.jsx(yw,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Bi.NoData,{children:"Span not found."})]})}function hcs({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>zNe(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(FNe(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Bi,{children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Bi.CloseButton,{onClick:r})]}),n?o.jsx(Bi.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Bi.NoData,{children:"No spans found for this trace."}):o.jsx(Bi.Content,{children:o.jsx(B9t,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function mcs(){const[e,t]=Pi(),n=fcs(e,t),r=ocs(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=ZNe(),{data:d=[],isPending:f}=qNe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=HNe(),{data:m=[],isPending:v}=WNe(),y=g.useMemo(()=>Jls({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:v,environments:h}}),[c,d,m,p,u,f,v,h]),b=g.useMemo(()=>rcs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:S=[],isLoading:x,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E}=Zls({filters:b}),{logIdMap:j,featuredLog:T,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=ucs(S,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:M}=GNe(n.featuredTraceId??null),{data:z,isLoading:H}=k5(n.featuredTraceId??"",n.featuredSpanId??""),F=g.useCallback(()=>n.applyFilterTokens(scs(y,n.filterTokens)),[y,n]),B=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),q=g.useCallback(K=>n.handleFeaturedChange({traceId:K,spanId:null}),[n]),D=g.useCallback((K,ne)=>n.handleFeaturedChange({traceId:K,spanId:ne}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),V=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=g.useCallback(K=>n.handleFeaturedChange({spanId:K??null}),[n]),U=o.jsxs(Ft.TopArea,{children:[o.jsx(Ft.Row,{children:o.jsxs(Ft.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(UG,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:x,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(DNe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:x,onStartTextFilter:a})]})}),o.jsx(Dls,{isLoading:x,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:F,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Ft,{width:"wide",height:"full",children:[U,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(Cls,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return S.length===0&&!x&&!Z?o.jsxs(Ft,{width:"wide",height:"full",children:[U,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(Bls,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Ft,{width:"wide",height:"full",children:[U,o.jsx(Els,{logCollapsed:i,listSlot:o.jsx(Mls,{logs:S,isLoading:x,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E,logIdMap:j,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:T?o.jsx(_ls,{log:T,onClose:B,onTraceClick:q,onSpanClick:D,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(hcs,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:M,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(pcs,{spanId:n.featuredSpanId,span:z?.span,isLoading:H,onClose:V}):null})]})}function gcs({server:e}){const{paths:t,Link:n}=bn(),s=We().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=r8t(e),l=Object.values(i||{}),c=l.length,u=l.filter(p=>p.toolType==="agent").length,d=l.filter(p=>p.toolType==="workflow").length,f=_y(e.name,50);return o.jsxs(ve.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(ve.NameCell,{children:f}),o.jsx(ve.DescriptionCell,{children:a}),o.jsx(ve.TextCell,{className:"text-center",children:u||""}),o.jsx(ve.TextCell,{className:"text-center",children:c||""}),o.jsx(ve.TextCell,{className:"text-center",children:d||""})]})}function vcs({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(ll,{columns:"auto 1fr auto auto auto"}):o.jsxs(ve,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"URL"}),o.jsx(ve.TopCellSmart,{long:"Agents",short:o.jsx(Vo,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(ve.TopCellSmart,{long:"Tools",short:o.jsx(Ld,{}),tooltip:"Tools",className:"text-center"}),o.jsx(ve.TopCellSmart,{long:"Workflows",short:o.jsx(Xu,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(ve.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(gcs,{server:s},s.id))]})}const ycs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zr,{iconSlot:o.jsx(If,{}),titleSlot:"No MCP Servers yet",descriptionSlot:o.jsxs(o.Fragment,{children:["MCP servers are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(ka,{})]})})}),bcs=()=>{const{data:e=[],isLoading:t,error:n}=AG(),[r,s]=g.useState("");return n&&ys(n)?o.jsx(lr,{children:o.jsx(Ws,{})}):n&&xs(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"MCP servers"})}):n?o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(lr,{children:o.jsx(ycs,{})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx($f,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(vcs,{mcpServers:e,isLoading:t,search:r})]})},xcs=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const a=t[s],i=a.tools,l=Object.keys(i);for(const c of l){const u=i[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...a,id:s})}}for(const[s,a]of Object.entries(e))n.has(a.id)||n.set(a.id,{...a,agents:[]});return Array.from(n.values())};function wcs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=bn(),i=g.useMemo(()=>xcs(e,t),[e,t]),l=g.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(ll,{columns:"auto 1fr auto"}):o.jsxs(ve,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"Description"}),o.jsx(ve.TopCellSmart,{long:"Agents",short:o.jsx(Vo,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(ve.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=_y(c.id,50),d=_y(c.description??"",200),f=c.agents.length;return o.jsxs(ve.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(ve.NameCell,{children:u}),o.jsx(ve.DescriptionCell,{children:d}),o.jsx(ve.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const Scs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zr,{iconSlot:o.jsx(If,{}),titleSlot:"No Tools yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra tools are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(ka,{})]})})}),kcs=()=>{const e=We();return Rn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new k_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw De.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},Ocs=({toolId:e})=>{const{canExecute:t}=dl(),n=t("tools"),{data:r={}}=Em(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=zEr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=kcs(),{requestContext:p}=Cs();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";De.error(`Error loading tool: ${v}`)}},[l]);const h=async(v,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?fm(um(Sx(c?.inputSchema))):ks({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(xt,{className:"h-8 w-48 mb-4"}),o.jsx(xt,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(xNe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function _cs({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l}){const{data:c={},isLoading:u,isError:d,error:f}=AI(),{data:p={},isLoading:h,isError:m,error:v}=Em(),{navigate:y,paths:b}=bn();g.useEffect(()=>{if(d){const _=f instanceof Error?f.message:"Failed to load tools";De.error(`Error loading tools: ${_}`)}},[d,f]),g.useEffect(()=>{if(m){const _=v instanceof Error?v.message:"Failed to load agents";De.error(`Error loading agents: ${_}`)}},[m,v]);const S=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(C=>{S.has(C.id)||S.set(C.id,C)})}),Object.values(c).forEach(_=>{S.has(_.id)||S.set(_.id,_)});const x=Array.from(S.values()).map(_=>({label:_.id,value:_.id})),k=_=>{t?t(_):_&&_!==e&&y(b.toolLink(_))};return o.jsx(ic,{options:x,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const Ccs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(Cy,{children:o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral3 font-medium py-20 text-center",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(Cy,{isDivided:!0,children:[o.jsxs("div",{className:"px-8 py-12 mx-auto max-w-2xl w-full",children:[o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral6 font-medium pb-4",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(un,{icon:o.jsx(L9t,{className:"text-neutral6"}),className:"rounded-r-sm text-neutral4!",children:"Version"}),o.jsx(un,{className:"rounded-l-sm text-neutral4!",children:t.version_detail.version})]}),o.jsx(ye,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(un,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"px-2 py-1 bg-surface4 rounded-lg",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx($a,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(un,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"px-2 py-1 bg-surface4 rounded-lg",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx($a,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(un,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",children:"CLI"}),children:"Command Line"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"px-2 py-1 bg-surface4 rounded-lg",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx($a,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"h-full overflow-y-scroll border-l border-border1",children:o.jsx(Ecs,{server:t})})]})},Ecs=({server:e})=>{const{data:t={},isLoading:n}=r8t(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"p-5 overflow-y-scroll",children:[o.jsxs("div",{className:"text-neutral6 flex gap-2 items-center",children:[o.jsx(qe,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(bC,{})}),o.jsx(ye,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(Tcs,{tool:a,serverId:e.id},s)})})]})};function jcs(e){if(!e)return!1;const t=e.ui;return!!(typeof t?.resourceUri=="string"&&t.resourceUri.startsWith("ui://")||typeof e["ui/resourceUri"]=="string"&&e["ui/resourceUri"].startsWith("ui://"))}const Tcs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=bn(),a=T8t[e.toolType||"tool"],i=jcs(e._meta);return o.jsxs(Df,{onClick:()=>n.current?.click(),children:[o.jsx(FPt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Ff,{children:[o.jsx(Lf,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.id),children:e.id}),i&&o.jsx(un,{className:"text-[10px] py-0",children:"App"})]})}),o.jsx(th,{children:e.description})]})]})},Ncs=()=>{const{serverId:e}=Sr(),{data:t=[],isLoading:n}=AG(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(Ccs,{isLoading:n,server:r})})};function Ics(e){if(!e)return;const t=e.ui;if(t?.resourceUri)return t.resourceUri;const n=e["ui/resourceUri"];if(typeof n=="string")return n}const Acs=({toolId:e,serverId:t})=>{const{canExecute:n}=dl(),r=n("tools"),s=We(),{data:a,isLoading:i,error:l}=pNe(t,e),{mutateAsync:c,isPending:u,data:d}=PQr(t,e),f=a?Ics(a._meta):void 0,{data:p}=yt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";De.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(xt,{className:"h-8 w-48 mb-4"}),o.jsx(xt,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=fm(um(a.inputSchema))}catch(y){console.error("Error processing input schema:",y),De.error("Failed to process tool input schema."),v=ks({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-b border-border1 p-4",children:o.jsx(n8t,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(xNe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},Rcs=()=>{const{serverId:e,toolId:t}=Sr(),{data:n,isLoading:r}=pNe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Acs,{toolId:t,serverId:e})})},d7t=[{label:"Agent",entityType:_s.AGENT},{label:"Workflow",entityType:_s.WORKFLOW_RUN},{label:"Scorer",entityType:_s.SCORER},{label:"Ingest",entityType:_s.RAG_INGESTION}],IN="rootEntityType",AN={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId",provider:"filterProvider",model:"filterModel"},qG=Object.keys(AN),iIe="mastra:metrics:saved-filters";function Pcs(e){const t=Fcs(e);try{localStorage.setItem(iIe,t.toString())}catch{}}function $cs(){try{localStorage.removeItem(iIe)}catch{}}function f7t(){try{const e=localStorage.getItem(iIe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function Mcs(e){if(e.has(IN))return!0;for(const t of qG)if(e.has(AN[t]))return!0;return!1}function Dcs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:d7t.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"threadId",label:"Thread ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function Lcs(e){const t=[],n=new Map([[IN,"rootEntityType"]]);for(const s of qG)n.set(AN[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}if(a==="rootEntityType"||a==="entityName"||a==="serviceName"||a==="environment"||a==="provider"||a==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:a,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function Fcs(e){const t=new URLSearchParams,n=e.getAll(IN);for(const r of n)t.append(IN,r);for(const r of qG){const s=AN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function zcs(e,t){e.delete(IN);for(const n of qG)e.delete(AN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?IN:AN[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string"&&a!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const a of s)e.append(r,a)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const Bcs="Any";function lXe(e){const t=e.trim();return t===""||t===Bcs}const Ucs=new Set(d7t.map(e=>e.entityType));function cXe(e){const t=e.trim();return Ucs.has(t)?t:void 0}function Vcs(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>!lXe(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?cXe(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(lXe(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=cXe(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const p7t=[{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"}],qcs=new Set(p7t.map(e=>e.value));function Hcs(e){return typeof e=="string"&&(qcs.has(e)||e==="custom")}const h7t=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function HG(){return g.useContext(h7t)}function Wcs(e,t){return e!=="custom"?p7t.find(n=>n.value===e)?.label??e:t?.from?t.to?`${nr(t.from,"MMM d, yyyy")} – ${nr(t.to,"MMM d, yyyy")}`:nr(t.from,"MMM d, yyyy"):"Custom range"}function Zcs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>Vcs(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=Wcs(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,h,d,s,f,p,l,c]);return o.jsx(h7t.Provider,{value:m,children:e})}const Gcs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function Qcs(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 Ycs(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 Kcs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=HG(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(UG,{preset:Qcs(e),onPresetChange:i=>{const l=Ycs(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...a.current,[l]:i};a.current=c,r(c)},presets:Gcs})}const nbe=1440*60*1e3,Xcs={"24h":nbe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function Jcs(e,t,n){if(e!=="custom"){const r=Xcs[e]??nbe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-nbe),end:t?.to??new Date(n)}}function Im(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=HG(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>Jcs(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function m7t(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}const eus=new Set(["ObservabilityStorageClickhouseVNext","ObservabilityStorageDuckDB","ObservabilityInMemory","ObservabilitySpanner","ObservabilityStoragePostgresVNext"]),tus=()=>{const{data:e,isLoading:t}=R3(),n=e?.observabilityStorageType;return{supportsMetrics:e?.observabilityStorageCapabilities?.metrics??(n?eus.has(n):!1),isInMemory:n==="ObservabilityInMemory",isLoading:t}};function _5({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(QEn,{})})}function nus({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(Ijn,{})})}const rus=[{dataKey:"p50",label:"p50",color:Fp.blue,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p50,0)/e.length)}`:"0",suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Fp.yellow,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p95,0)/e.length)}`:"0",suffix:"avg ms"})}];function sus(e){return e==="agents"||e==="workflows"||e==="tools"}function hae({data:e,onPointClick:t}){return e.length===0?o.jsx(Wt.NoData,{message:"No latency data yet"}):o.jsx(kV,{data:e,series:rus,onPointClick:t?n=>{const r=n;typeof r?.tsMs=="number"&&Number.isFinite(r.tsMs)&&t(r)}:void 0})}function aus({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),p=c[d]?d:u,h=typeof s=="function"?s(p):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,S)=>b+S,0)/v.length)}ms`:"—";return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Wt.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Wt.Actions,{children:h}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load latency data"}):o.jsx(Wt.Content,{children:m?o.jsxs(Lc,{value:p,onValueChange:b=>{sus(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(Dc,{children:[o.jsx(Rr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Rr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Rr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:o.jsx(hae,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Xr,{value:"workflows",children:o.jsx(hae,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Xr,{value:"tools",children:o.jsx(hae,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Wt.NoData,{message:"No latency data yet"})})]})}function ius(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 ous(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const a=new Date(s.getTime()+3600*1e3);return{from:s,to:a}}const n=new Date(e);n.setUTCHours(0,0,0,0);const r=new Date(n.getTime()+1440*60*1e3);return{from:n,to:r}}function g7t(e,t,n,r,s,a,i){if(i){e.set(t,"custom"),e.set(n,i.from.toISOString()),e.set(r,i.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),a?.from&&e.set(n,a.from.toISOString()),a?.to&&e.set(r,a.to.toISOString());return}const l=ius(s);l&&e.set(t,l)}function Po(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function v7t(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function uXe({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/observability"}){const a=new URLSearchParams;a.set(Ow,"branches"),g7t(a,_w,Cw,Ew,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Lx,i),r.status&&a.set(Fx,r.status),Po(a,Nl.entityName,r.entityName??n.entityName),Po(a,Nl.threadId,r.threadId??n.threadId),Po(a,Nl.resourceId,r.resourceId??n.resourceId),Po(a,Nl.entityId,n.entityId),Po(a,Nl.runId,n.runId),Po(a,Nl.sessionId,n.sessionId),Po(a,Nl.requestId,n.requestId),Po(a,Nl.userId,n.userId),Po(a,Nl.organizationId,n.organizationId),Po(a,Nl.experimentId,n.experimentId),Po(a,Nl.serviceName,n.serviceName),Po(a,Nl.environment,n.environment),v7t(a,Nl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function lus({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;g7t(a,Gb,Qb,Yb,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(zx,i),Po(a,Il.entityName,r.entityName??n.entityName),Po(a,Il.threadId,r.threadId??n.threadId),Po(a,Il.resourceId,r.resourceId??n.resourceId),Po(a,Il.runId,n.runId),Po(a,Il.sessionId,n.sessionId),Po(a,Il.requestId,n.requestId),Po(a,Il.userId,n.userId),Po(a,Il.organizationId,n.organizationId),Po(a,Il.experimentId,n.experimentId),Po(a,Il.serviceName,n.serviceName),Po(a,Il.environment,n.environment),v7t(a,Il.tags,n.tags),r.status==="error"&&a.append(Il.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function YI(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=HG(),a=g.useCallback((c={})=>uXe({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>lus({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=ous(u,d);return uXe({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const y7t="1h";async function mae(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:y7t,filters:n}),s=r.series.find(l=>l.percentile===.5),a=r.series.find(l=>l.percentile===.95);if(!s||!a)return[];const i=new Map(a.points.map(l=>[new Date(l.timestamp).getTime(),l.value]));return s.points.map(l=>{const c=new Date(l.timestamp),u=c.getTime();return{time:c.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),tsMs:u,p50:Math.round(l.value),p95:Math.round(i.get(u)??0)}})}function cus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([mae(e,"mastra_agent_duration_ms",t),mae(e,"mastra_workflow_duration_ms",t),mae(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:y7t}}})}const dXe={agents:_s.AGENT,workflows:_s.WORKFLOW_RUN,tools:_s.TOOL};function uus(){const{data:e,isLoading:t,isError:n}=cus(),{getTracesHref:r,getBucketTracesHref:s}=YI(),{Link:a}=bn(),i=Hs();return o.jsx(aus,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:dXe[l]},c.tsMs,"1h"))},actions:l=>o.jsx(_5,{href:r({rootEntityType:dXe[l]}),LinkComponent:a})})}function dus(e){return e==="threads"||e==="resources"}function gae(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function fus({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,p=e.data?.reduce((y,b)=>y+b.runs,0)??0,h=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,v=typeof s=="function"?s(i):s;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Wt.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Wt.Summary,{value:h.toLocaleString(),label:"Total threads"}),v?o.jsx(Wt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Wt.Loading,{}):m.isError?o.jsx(Wt.Error,{message:"Failed to load memory data"}):o.jsx(Wt.Content,{children:o.jsxs(Lc,{defaultTab:"threads",value:i,onValueChange:y=>{dus(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Dc,{children:[o.jsx(Rr,{value:"threads",children:"Threads"}),o.jsx(Rr,{value:"resources",children:"Resources"})]}),o.jsx(Xr,{value:"threads",children:d?o.jsxs(ve,{columns:"auto auto auto auto auto",...Yye,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),S=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:gae(y.threadId)}),o.jsx(ve.NumberCell,{children:y.resourceId?gae(y.resourceId):"—"}),o.jsx(ve.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(ve.NumberCell,{children:y.tokens>0?_c(y.tokens):"—"}),o.jsx(ve.NumberCell,{children:y.cost!=null?Cg(y.cost,y.costUnit):"—"})]});return b?o.jsx(ve.RowLink,{to:b,LinkComponent:a,children:S},y.key):o.jsx(ve.RowStatic,{children:S},y.key)})]}):o.jsx(Wt.NoData,{message:"No thread activity yet"})}),o.jsx(Xr,{value:"resources",children:f?o.jsxs(ve,{columns:"auto auto auto auto",...Yye,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),S=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:gae(y.resourceId)}),o.jsx(ve.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(ve.NumberCell,{children:y.tokens>0?_c(y.tokens):"—"}),o.jsx(ve.NumberCell,{children:y.cost!=null?Cg(y.cost,y.costUnit):"—"})]});return b?o.jsx(ve.RowLink,{to:b,LinkComponent:a,children:S},y.key):o.jsx(ve.RowStatic,{children:S},y.key)})]}):o.jsx(Wt.NoData,{message:"No resource activity yet"})})]})})]})}function C5(e,t,n){const r=e.get(t);if(r!==void 0)return r;const s=n();return e.set(t,s),s}const vae=20;function pus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:vae}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:vae}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:vae})]),l=new Map,c=d=>C5(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.threadId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,p=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}const yae=20;function hus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:yae}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:yae}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:yae})]),l=new Map,c=d=>C5(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.resourceId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,p=l.get(f);return{resourceId:f,threadCount:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}function mus(){const e=pus(),t=hus(),{getTracesHref:n}=YI(),{Link:r}=bn();return o.jsx(fus,{threads:{data:e.data,isLoading:e.isLoading,isError:e.isError},resources:{data:t.data,isLoading:t.isLoading,isError:t.isError},LinkComponent:r,getThreadRowHref:s=>n({threadId:s.threadId,...s.resourceId?{resourceId:s.resourceId}:{}}),getResourceRowHref:s=>n({resourceId:s.resourceId})})}function E5({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(es,{children:[o.jsx(es.Label,{children:e}),o.jsx(es.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(es.Error,{}):s?o.jsx(es.Loading,{}):i?r!=null?o.jsx(es.Change,{changePct:r,prevValue:n}):o.jsx(es.NoChange,{}):o.jsx(es.NoData,{})]})}function gus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function vus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function yus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function bus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function xus(){const{data:e,isLoading:t,isError:n}=m7t();return o.jsx(E5,{label:"Total Agent Runs",value:e?.value!=null?e.value.toLocaleString():null,prevValue:e?.previousValue!=null?e.previousValue.toLocaleString():void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function wus(){const{data:e,isLoading:t,isError:n}=yus();return o.jsx(E5,{label:"Total Model Cost",value:e?.cost!=null?Cg(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Cg(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function Sus(){const{data:e,isLoading:t,isError:n}=bus();return o.jsx(E5,{label:"Total Tokens",value:e?.value!=null?_c(e.value):null,prevValue:e?.previousValue!=null?_c(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function kus(){const{data:e,isLoading:t,isError:n}=vus();return o.jsx(E5,{label:"Total Threads",value:e?.value!=null?_c(e.value):null,prevValue:e?.previousValue!=null?_c(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Ous(){const{data:e,isLoading:t,isError:n}=gus();return o.jsx(E5,{label:"Total Resources",value:e?.value!=null?_c(e.value):null,prevValue:e?.previousValue!=null?_c(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function _us({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>Cus(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(MNe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(PNe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Cus(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 Eus({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Cg(l):"—":c.size===1?u=l>0?Cg(l,[...c][0]):"—":u="Mixed",o.jsx(Wt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Wt.Actions,{children:s}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load model usage data"}):o.jsx(Wt.Content,{children:i?o.jsxs(ve,{columns:"auto auto auto auto auto auto",...Yye,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Model"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:l.model}),o.jsx(ve.NumberCell,{children:l.input}),o.jsx(ve.NumberCell,{children:l.output}),o.jsx(ve.NumberCell,{children:l.cacheRead}),o.jsx(ve.NumberCell,{children:l.cacheWrite}),o.jsx(ve.NumberCell,{highlight:!0,children:l.cost!=null?Cg(l.cost,l.costUnit):"—"})]});return c?o.jsx(ve.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(ve.RowStatic,{children:u},l.model)})]}):o.jsx(Wt.NoData,{message:"No model usage data yet"})})]})}function jus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>C5(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",p=c(f);p.input=d.value,u(p,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",p=c(f);p.output=d.value,u(p,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:_c(f.input),output:_c(f.output),cacheRead:_c(f.cacheRead),cacheWrite:_c(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function Tus(){const{data:e,isLoading:t,isError:n}=jus(),{getTracesHref:r}=YI(),{Link:s}=bn();return o.jsx(Eus,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:_s.AGENT}),actions:o.jsx(_5,{href:r({rootEntityType:_s.AGENT}),LinkComponent:s})})}function Nus(e){return e==="tokens"||e==="cost"}function Ius({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,S)=>b+S.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,v=h?f.reduce((b,S)=>b+(S.cost??0),0):0,y=h&&v>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Wt.Summary,{value:Cg(v,m),label:"Total cost"}):o.jsx(Wt.Summary,{value:_c(d),label:"Total tokens"})),u&&s?o.jsx(Wt.Actions,{children:s}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load token usage data"}):o.jsx(Wt.Content,{children:u?o.jsxs(Lc,{defaultTab:"tokens",value:i,onValueChange:b=>{Nus(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Dc,{children:[o.jsx(Rr,{value:"tokens",children:"Tokens"}),o.jsx(Rr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(NN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Fp.blueDark},{label:"Output",color:Fp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:_c})}),o.jsx(Xr,{value:"cost",children:y?o.jsx(NN,{LinkComponent:a,data:f.slice().sort((b,S)=>(S.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:Fp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Cg(b,m)}):o.jsx(Wt.NoData,{message:"No cost data yet"})})]}):o.jsx(Wt.NoData,{message:"No token usage data yet"})})]})}function Aus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>C5(i,u,()=>({input:0,output:0,cost:null,costUnit:null})),c=(u,d)=>{d.estimatedCost!=null&&(u.cost=(u.cost??0)+d.estimatedCost,d.costUnit&&(u.costUnit=d.costUnit))};for(const u of s.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.input=u.value,c(f,u)}for(const u of a.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(i.entries()).map(([u,d])=>({name:u,input:d.input,output:d.output,total:d.input+d.output,cost:d.cost,costUnit:d.costUnit})).sort((u,d)=>d.total-u.total)}})}function Rus(){const{data:e,isLoading:t,isError:n}=Aus(),{getTracesHref:r}=YI(),{Link:s}=bn();return o.jsx(Ius,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:_s.AGENT,entityName:a.name}),actions:o.jsx(_5,{href:r({rootEntityType:_s.AGENT}),LinkComponent:s})})}function rbe(e,t=_c){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const Pus=[{dataKey:"input",label:"Input tokens",color:Fp.blue,aggregate:rbe("input")},{dataKey:"output",label:"Output tokens",color:Fp.yellow,aggregate:rbe("output")}];function $us(e){return e==="tokens"||e==="cost"}function Mus({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,_)=>k+_.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),p=f.map(k=>({...k})),h=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=h.size===1&&f.every(k=>k.costUnit!=null),v=m?[...h][0]??null:null,y=m?f.reduce((k,_)=>k+(_.cost??0),0):0,b=m&&y>0,S=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",x=[{dataKey:"cost",label:"Cost",color:Fp.purple,aggregate:rbe("cost",k=>Cg(k,v))}];return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Token usage over time",description:S}),u&&(a==="cost"&&b?o.jsx(Wt.Summary,{value:Cg(y,v),label:"Total cost"}):o.jsx(Wt.Summary,{value:_c(d),label:"Total tokens"})),u&&s?o.jsx(Wt.Actions,{children:s}):null]}),n?o.jsx(Wt.Loading,{}):r?o.jsx(Wt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Wt.Content,{children:u?o.jsxs(Lc,{defaultTab:"tokens",value:a,onValueChange:k=>{$us(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(Dc,{children:[o.jsx(Rr,{value:"tokens",children:"Tokens"}),o.jsx(Rr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(kV,{data:c,series:Pus})}),o.jsx(Xr,{value:"cost",children:b?o.jsx(kV,{data:p,series:x}):o.jsx(Wt.NoData,{message:"No cost data yet"})})]}):o.jsx(Wt.NoData,{message:"No token usage data yet"})})]})}function Dus(e){return e==="24h"?"1h":"1d"}function Lus(e,t){return t==="1h"?e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):e.toLocaleDateString("en-US",{month:"short",day:"2-digit"})}function fXe(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const a=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};a[n]+=r.value,r.estimatedCost!=null&&(a.cost=(a.cost??0)+r.estimatedCost,t?.costUnit?a.costUnits.add(t.costUnit):a.hasUnknownCostUnit=!0),e.set(s,a)}}function Fus(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function zus(){const e=We(),{datePreset:t,filters:n,filterKey:r}=Im(),s=Dus(t);return yt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return fXe(l,a.series[0],"input"),fXe(l,i.series[0],"output"),{data:Array.from(l.values()).sort((u,d)=>u.tsMs-d.tsMs).map(u=>{const d=new Date(u.tsMs);return{time:Lus(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:Fus(u)}}),interval:s}}})}function Bus(){const{data:e,isLoading:t,isError:n}=zus(),{getTracesHref:r}=YI(),{Link:s}=bn();return o.jsx(Mus,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(_5,{href:r(),LinkComponent:s})})}function bae({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(NN,{LinkComponent:r,data:e.map(s=>{const a=n?.(s),i=t?.(s);return a?{name:s.name,values:[s.completed,s.errors],hrefs:[i,a]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:Fp.blueDark},{label:"Errors",color:Fp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:_c})}function Uus({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,p=m=>r?v=>r(m,v):void 0,h=m=>s?v=>s(m,v):void 0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Wt.Summary,{value:_c(f),label:"Total runs"}),u?o.jsx(Wt.Actions,{children:u}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load trace volume data"}):o.jsx(Wt.Content,{children:d?o.jsxs(Lc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Dc,{children:[o.jsx(Rr,{value:"agents",children:"Agents"}),o.jsx(Rr,{value:"workflows",children:"Workflows"}),o.jsx(Rr,{value:"tools",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:e.agentData.length>0?o.jsx(bae,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No agent data yet"})}),o.jsx(Xr,{value:"workflows",children:e.workflowData.length>0?o.jsx(bae,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No workflow data yet"})}),o.jsx(Xr,{value:"tools",children:e.toolData.length>0?o.jsx(bae,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No tool data yet"})})]}):o.jsx(Wt.NoData,{message:"No trace volume data yet"})})]})}async function xae(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const a of r.groups){const i=a.dimensions.entityName??"unknown",l=a.dimensions.status??"ok",c=C5(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=a.value:c.completed+=a.value}return Array.from(s.entries()).map(([a,i])=>({name:a,...i})).sort((a,i)=>i.completed+i.errors-(a.completed+a.errors))}function Vus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([xae(e,"mastra_agent_duration_ms",t),xae(e,"mastra_workflow_duration_ms",t),xae(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const Mz={agents:_s.AGENT,workflows:_s.WORKFLOW_RUN,tools:_s.TOOL};function qus(){const{data:e,isLoading:t,isError:n}=Vus(),{getTracesHref:r,getLogsHref:s}=YI(),{Link:a}=bn();return o.jsx(Uus,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:Mz[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:Mz[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(_5,{href:r({rootEntityType:Mz[i]}),LinkComponent:a}),o.jsx(nus,{href:s({rootEntityType:Mz[i],status:"error"}),LinkComponent:a})]})})}const wae="period",Dz="dateFrom",Lz="dateTo";function Hus(){const[e,t]=Pi(),n=e.get(wae),r=Hcs(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(Dz)),p=d(e.get(Lz));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=g.useMemo(()=>Lcs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(wae):p.set(wae,d),d!=="custom"&&(p.delete(Dz),p.delete(Lz)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(Dz,d.from.toISOString()):p.delete(Dz),d?.to?p.set(Lz,d.to.toISOString()):p.delete(Lz),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return zcs(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,Mcs(e)))return;const d=f7t();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(Zcs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(Wus,{})})}function Wus(){const[e]=Pi(),{error:t,isLoading:n}=m7t(),{filterTokens:r,setFilterTokens:s}=HG(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=tus(),{data:d,isLoading:f}=ZNe(),{data:p,isLoading:h}=qNe(),{data:m,isLoading:v}=WNe(),{data:y,isLoading:b}=HNe(),S=g.useMemo(()=>Dcs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:v,environments:b}}),[d,p,m,y,f,h,v,b]),[x,k]=g.useState(()=>f7t()!==null),_=g.useCallback(()=>{Pcs(e),k(!0),De.success("Filters setting for Metrics saved")},[e]),C=g.useCallback(()=>{$cs(),k(!1),De.success("Filters setting for Metrics cleared up")},[]),E=g.useCallback(()=>{s([])},[s]),j=g.useCallback(()=>{const T=r.map(I=>{const A=S.find(R=>R.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(T)},[S,r,s]);return t&&ys(t)?o.jsx(lr,{children:o.jsx(Ws,{})}):t&&xs(t)?o.jsx(lr,{children:o.jsx(Ds,{resource:"metrics"})}):t?o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Ft,{width:"wide",height:"full",children:[o.jsxs(Ft.TopArea,{children:[o.jsx(Ft.Row,{children:o.jsxs(Ft.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Kcs,{}),o.jsx(DNe,{fields:S,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(_us,{isLoading:n,filterFields:S,filterTokens:r,onFilterTokensChange:s,onClear:j,onRemoveAll:E,onSave:_,onRemoveSaved:x?C:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid gap-8 content-start pb-10",children:[c&&o.jsx(En,{variant:"info",title:"Metrics are not persisted",children:o.jsx(En.Message,{children:"This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner."})}),o.jsxs(Kye,{children:[o.jsx(xus,{}),o.jsx(wus,{}),o.jsx(Sus,{}),o.jsx(kus,{}),o.jsx(Ous,{})]}),o.jsxs(Kye,{children:[o.jsx(Tus,{}),o.jsx(Rus,{}),o.jsx(Bus,{}),o.jsx(mus,{}),o.jsx(qus,{}),o.jsx(uus,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zr,{iconSlot:o.jsx(If,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(ka,{})]})})})]})}function Zus(){const{paths:e}=bn(),{data:t,isLoading:n,error:r}=I8t(),{isCmsAvailable:s}=tS(),[a,i]=g.useState(""),l=t?.promptBlocks??[];return r&&ys(r)?o.jsx(lr,{children:o.jsx(Ws,{})}):r&&xs(r)?o.jsx(lr,{children:o.jsx(Ds,{resource:"prompt blocks"})}):r?o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load prompt blocks",message:r.message})}):l.length===0&&!n?o.jsx(lr,{children:o.jsx(MJr,{})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx($f,{onSearch:i,label:"Filter prompts",placeholder:"Filter by name or description"})}),s&&o.jsxs(le,{as:ti,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Zr,{}),"Create Prompt"]})]})}),o.jsx($Jr,{promptBlocks:l,isLoading:n,search:a})]})}function Gus(){return o.jsx(Ft,{width:"narrow",children:o.jsx(Ft.MainArea,{children:o.jsx(yYr,{children:o.jsx(Eye,{})})})})}const Qus=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:Upn,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:cdt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:ka,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:mT,href:"https://discord.gg/BTYqqHKUrf",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:vdt,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:udt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Yus(){return o.jsx(Ft,{width:"narrow",children:o.jsx(Ft.MainArea,{children:o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 max-w-3xl",children:Qus.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group flex flex-col gap-3 rounded-lg border border-border1 bg-surface2 p-5 transition-colors hover:border-accent1 hover:bg-surface3",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"h-5 w-5 text-icon3 group-hover:text-accent1 transition-colors"}),o.jsx("span",{className:"text-ui-md font-medium text-text1",children:e.title}),e.external&&o.jsx(ka,{className:"h-3.5 w-3.5 text-icon3 ml-auto opacity-0 group-hover:opacity-100 transition-opacity"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function Kus(){const{data:e={},isLoading:t,error:n}=ih(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&ys(n))return o.jsx(lr,{children:o.jsx(Ws,{})});if(n&&xs(n))return o.jsx(lr,{children:o.jsx(Ds,{resource:"scorers"})});if(n)return o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(lr,{children:o.jsx(HKr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(ZKr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(qKr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Xus(){const{scorerId:e}=Sr(),[t,n]=Pi(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=wKr(e),{data:d={},isLoading:f,error:p}=Em(),{isLoading:h,error:m}=Hy(),{data:v=[],isLoading:y,error:b,isFetchingNextPage:S,hasNextPage:x,setEndOfListElement:k}=xKr({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),_=g.useMemo(()=>c?.agentIds?.filter(q=>d[q]).map(q=>({value:q,label:d[q].name,type:"AGENT"}))||[],[c?.agentIds,d]),C=g.useMemo(()=>c?.workflowIds?.map(q=>({value:q,label:q,type:"WORKFLOW"}))||[],[c?.workflowIds]),E=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},..._,...C],[_,C]),j=t.get("entity")??"all",T=E.find(q=>q.value===j);T&&T.value!==i?.value&&l(T),g.useEffect(()=>{if(u){const q=u instanceof Error?u.message:"Failed to load scorer";De.error(`Error loading scorer: ${q}`)}},[u]),g.useEffect(()=>{if(p){const q=p instanceof Error?p.message:"Failed to load agents";De.error(`Error loading agents: ${q}`)}},[p]),g.useEffect(()=>{if(m){const q=m instanceof Error?m.message:"Failed to load workflows";De.error(`Error loading workflows: ${q}`)}},[m]);const I=q=>{q?.value&&n(D=>{const G=new URLSearchParams(D);return G.set("entity",q.value),G})};g.useEffect(()=>{const q=t.get("scoreId")??void 0;if(q===s)return;if(!q){a(void 0);return}v.find(G=>G.id===q)&&a(q)},[t,v]);const A=g.useCallback(q=>{a(q||void 0),n(D=>{const G=new URLSearchParams(D);return q?G.set("scoreId",q):G.delete("scoreId"),G})},[n]);if(!c)return null;const R=ys(u)||ys(p)||ys(m),L=u&&xs(u),M=!R&&!L&&(u||p||m),z=!y&&v.length===0,H=i?.value!=="all",F=c?.scorer?.source==="stored"?o.jsx($y,{owner:"scorer-detail",children:o.jsxs(le,{variant:"default",as:ti,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(om,{})," Edit"]})}):null;if(R||L||M||z&&!H){const q=(u instanceof Error?u.message:void 0)??(p instanceof Error?p.message:void 0)??(m instanceof Error?m.message:void 0)??"An unexpected error occurred";return o.jsxs(Ft,{width:"wide",height:"full",children:[F,o.jsx(Ft.MainArea,{isCentered:!0,children:R?o.jsx(Ws,{}):L?o.jsx(Ds,{resource:"scorers"}):M?o.jsx(Hi,{title:"Failed to load scorer",message:q}):o.jsx(mKr,{})})]})}return o.jsxs(Ft,{width:"wide",children:[F,o.jsx(Ft.TopArea,{children:o.jsx(gKr,{selectedEntity:i,entityOptions:E,onEntityChange:I,onReset:()=>{n(q=>{const D=new URLSearchParams(q);return D.set("entity","all"),D})},isLoading:y||f||h})}),o.jsx(hKr,{scores:v,isLoading:y,selectedScoreId:s,isFetchingNextPage:S,hasNextPage:x,setEndOfListElement:k,onScoreClick:A,errorMsg:b?.message})]})}function Jus({label:e,description:t,htmlFor:n,className:r,children:s}){return o.jsxs("div",{className:X("flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",r),"data-slot":"settings-row",children:[o.jsxs("div",{children:[n?o.jsx(Dt,{htmlFor:n,className:"text-sm font-medium",children:e}):o.jsx("p",{className:"text-sm font-medium",children:e}),t&&o.jsx("p",{className:"text-sm text-neutral3",children:t})]}),s]})}const b7t=[{value:"dark",label:"Dark",Icon:wmn},{value:"light",label:"Light",Icon:Rgn},{value:"system",label:"System",Icon:Odt}],eds=e=>b7t.some(t=>t.value===e);function tds({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-2",children:[o.jsx(t,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 opacity-70"}),o.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const nds=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=Lq(),{theme:r,setTheme:s}=q_();return o.jsx(Ft,{width:"narrow",children:o.jsxs(Ft.MainArea,{className:"flex flex-col gap-5 mt-6",children:[o.jsx(uye,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(Jus,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(la,{value:r,onValueChange:a=>{eds(a)&&s(a)},children:[o.jsx(ua,{id:"theme",className:"w-full sm:w-48",children:o.jsx(ca,{className:"inline-flex min-w-0 max-w-full items-center"})}),o.jsx(da,{children:b7t.map(a=>o.jsx(Ar,{value:a.value,children:o.jsx(tds,{option:a})},a.value))})]})})}),o.jsx(uye,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(xMt,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function rds(){const[e]=Pi(),t=Hs(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(c7t,{redirectUri:n,onSuccess:r,initialMode:"signup"})}const x7t=e=>o.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("g",{clipPath:"url(#clip0_21999_22095)",children:o.jsx("path",{d:"M7.5 0.75C3.6325 0.75 0.5 3.8825 0.5 7.75C0.5 10.8475 2.50375 13.4637 5.28625 14.3912C5.63625 14.4525 5.7675 14.2425 5.7675 14.0587C5.7675 13.8925 5.75875 13.3412 5.75875 12.755C4 13.0787 3.545 12.3262 3.405 11.9325C3.32625 11.7312 2.985 11.11 2.6875 10.9437C2.4425 10.8125 2.0925 10.4887 2.67875 10.48C3.23 10.4712 3.62375 10.9875 3.755 11.1975C4.385 12.2562 5.39125 11.9587 5.79375 11.775C5.855 11.32 6.03875 11.0137 6.24 10.8387C4.6825 10.6637 3.055 10.06 3.055 7.3825C3.055 6.62125 3.32625 5.99125 3.7725 5.50125C3.7025 5.32625 3.4575 4.60875 3.8425 3.64625C3.8425 3.64625 4.42875 3.4625 5.7675 4.36375C6.3275 4.20625 6.9225 4.1275 7.5175 4.1275C8.1125 4.1275 8.7075 4.20625 9.2675 4.36375C10.6062 3.45375 11.1925 3.64625 11.1925 3.64625C11.5775 4.60875 11.3325 5.32625 11.2625 5.50125C11.7087 5.99125 11.98 6.6125 11.98 7.3825C11.98 10.0687 10.3438 10.6637 8.78625 10.8387C9.04 11.0575 9.25875 11.4775 9.25875 12.1337C9.25875 13.07 9.25 13.8225 9.25 14.0587C9.25 14.2425 9.38125 14.4612 9.73125 14.3912C11.1209 13.9221 12.3284 13.029 13.1839 11.8377C14.0393 10.6463 14.4996 9.21668 14.5 7.75C14.5 3.8825 11.3675 0.75 7.5 0.75Z",fill:"currentColor"})}),o.jsx("defs",{children:o.jsx("clipPath",{id:"clip0_21999_22095",children:o.jsx("rect",{width:"14",height:"14",fill:"currentColor",transform:"translate(0.5 0.75)"})})})]});function sds(e){return e.replace(/\/$/,"").split("/").pop()}function WG({children:e,className:t}){return o.jsx("div",{className:X("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function ads({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:X("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"h-16 bg-surface3 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:X("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:X("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:X("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:X("overflow-hidden"),children:o.jsx("div",{className:"w-full h-full bg-cover thumb transition-scale duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:X("grid py-3 px-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"hidden 2xl:flex text-neutral3 text-ui-md flex-wrap items-center gap-4 mt-3",children:[i&&o.jsxs("ul",{className:X("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Vo,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Ld,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(_dt,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(zD,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(bC,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"flex items-center text-neutral3 gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:X("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"flex items-center gap-2 px-2 py-1 rounded bg-surface1 group-hover:bg-surface2 text-neutral3 transition-colors group-hover:text-neutral5",children:[o.jsx(x7t,{})," ",sds(a.githubUrl)]})})]},a.slug)})})}function ids({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:X("h-[6.5rem] flex items-center gap-8","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:X("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(mN,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Ec,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Ec,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(le,{onClick:c,children:["Reset ",o.jsx(bs,{})]})]})}function ods(){const{data:e,isLoading:t}=ker(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(S=>{f.push({value:S,label:S})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(S=>{p.push({value:S,label:S})});const h=(S,x)=>{x==="tag"?i(S):x==="provider"&&c(S)},m=S=>{d(S)},v=()=>{i("all"),c("all"),d("")},y=n.filter(S=>!(u&&!S.title.toLowerCase().includes(u)&&!S.description.toLowerCase().includes(u)||a!=="all"&&!S.tags.includes(a)||l!=="all"&&!S.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(ds,{children:[o.jsx(ywe,{children:o.jsxs(bgt,{children:[o.jsx(qe,{children:o.jsx(Kv,{})}),"Templates"]})}),o.jsxs("div",{className:X("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(ids,{selectedTag:a,onTagChange:S=>h(S,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:S=>h(S,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(ads,{templates:y,linkComponent:ti,className:"max-w-[80rem] mx-auto",isLoading:t})]})]})}const lds="1.52.1-alpha.0";function cds({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(yf,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(vhn,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(WG,{className:"space-y-4 text-neutral3 mb-8 content-center",children:[o.jsxs("div",{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"text-center space-y-2",children:[o.jsx("p",{className:"text-ui-md font-medium text-neutral5",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-xs",children:[o.jsxs("summary",{className:"cursor-pointer text-neutral3 hover:text-neutral4 select-none text-center",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 p-3 bg-gray-100 dark:bg-gray-800 rounded text-xs overflow-auto max-h-60 text-left space-y-2",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"text-xs font-mono text-gray-700 dark:text-gray-300 mt-1 whitespace-pre-wrap wrap-break-word",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"cursor-pointer text-neutral3 hover:text-neutral4 select-none text-center",children:"Show Details"}),o.jsx("div",{className:"mt-4 p-3 bg-gray-100 dark:bg-gray-800 rounded text-xs font-mono overflow-auto max-h-60 text-left",children:o.jsx("div",{className:"whitespace-pre-wrap wrap-break-word",children:n})})]})]})}function uds({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:a,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(WG,{children:o.jsxs("div",{className:"max-w-[40rem] my-4 p-4 lg:p-8 mx-auto gap-8 grid",children:[o.jsxs("h2",{className:X("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(Cdt,{})]}),o.jsx(Ec,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] gap-4 items-start",children:l?o.jsxs("div",{className:X("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(Kt,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(g.Fragment,{children:[o.jsx(TO,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(TO,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),o.jsxs("div",{className:"border-t border-border1 pt-12 mt-3.5 relative",children:[o.jsx("div",{className:"absolute w-8 h-8 rounded-full bg-surface2 top-0 left-1/2 -translate-x-1/2 -translate-y-4 text-ui-sm text-neutral3 flex items-center justify-center",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-lg",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-8",children:"This model will be used by the workflow to process and install the template"}),o.jsx(o8t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(le,{className:X("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(Kt,{className:"w-4 h-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(bm,{})]})})]})})}function dds({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:X("grid mt-8 items-center"),children:o.jsxs("div",{className:X("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(Kv,{}),o.jsx("h2",{className:X({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid lg:grid-cols-[1fr_1fr] gap-x-24",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:X("mb-4 text-ui-md text-neutral4 mt-2 leading-7",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:X("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"shrink-0 mt-0.5",children:o.jsx(Vx,{className:"w-[1.1em] h-[1.1em] text-blue-500"})}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(wxe,{className:"w-[1em] h-[1em] text-neutral4"}),o.jsx("span",{className:"text-ui-md font-medium text-neutral5",children:"A new Git branch will be created"})]}),o.jsxs("div",{className:"text-ui-sm text-neutral4 space-y-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-medium",children:"Branch name:"})," ",o.jsx("code",{className:"bg-surface3 px-1.5 py-0.5 rounded text-ui-sm font-mono",children:i})]}),o.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&o.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 mt-auto text-neutral3 text-ui-md hover:text-neutral5",children:[o.jsx(x7t,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(gNe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function fds(e){switch(e){case"running":return o.jsx(Kt,{});case"success":return o.jsx(wx,{});case"failed":return o.jsx(Hu,{});default:return null}}function pds({stepId:e,step:t,isActive:n,position:r}){const s=a=>a.charAt(0).toUpperCase()+a.slice(1).replace(/-/g," ");return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3",vs.all,{"border border-dashed border-neutral2 bg-surface3":n}),children:[o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:X("flex min-w-6 justify-end text-ui-md",vs.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:[r,"."]}),o.jsxs("div",{children:[o.jsx("h4",{className:X("text-ui-md",vs.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:s(e)}),t.description&&o.jsx("p",{className:"-mt-0.5 text-ui-md text-neutral2",children:t.description})]})]}),o.jsx("div",{className:X("flex size-[1.75rem] items-center justify-center self-center rounded-full",vs.all,{"border border-neutral2 border-dashed":t.status==="pending","[&>svg]:text-white [&>svg]:w-4 [&>svg]:h-4":t.status!=="running","w-[1.75rem] h-[1.75rem]":t.status==="running","bg-accent1Dark shadow-glow-accent1":t.status==="success","bg-accent2Dark shadow-glow-accent2":t.status==="failed","scale-110":t.status==="success"||t.status==="failed"}),children:fds(t.status)})]})}function hds({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:X(n),children:t.map((r,s)=>o.jsx(pds,{stepId:r.id,step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function mds({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[o.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>o.jsx("div",{className:X("relative flex h-8 items-center justify-end",vs.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:X("absolute right-0 z-10 flex size-[2rem] translate-x-[50%] items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3",vs.all,{"border border-neutral2 border-dashed":r.status==="pending","[&>svg]:text-surface1 [&>svg]:w-[1.1rem] [&>svg]:h-[1.1rem]":r.status!=="running","bg-accent1Dark text-white shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-white shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Kt,{}):s+1})},r.id))}),o.jsxs("div",{className:X("text-center text-xs text-neutral3",vs.colors),children:[n," of ",t," steps completed"]})]})}function gds({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),p=f.length,h=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(WG,{className:"space-y-6 text-neutral3 mb-8 content-center",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-lg font-semibold text-neutral5",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"mt-2 text-ui-sm text-neutral3",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"max-w-[30rem] w-full mx-auto px-6",children:o.jsx(mds,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:X("rounded-lg text-neutral5 p-6 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(Imn,{}),l||"Something went wrong"]}),u&&o.jsx(hds,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-center text-sm text-neutral3 grid gap-4 justify-items-center",children:[o.jsx(Kt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function vds({name:e,installedEntities:t}){return o.jsxs(WG,{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Cdt,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-center text-neutral3 ",children:["The ",o.jsx("b",{className:"text-neutral4",children:e})," template has been successfully installed.",t&&t.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&o.jsx(gNe,{data:t})]})}function yds(){const{templateSlug:e}=Sr(),[t,n]=Pi(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,p]=g.useState([]),[h,m]=g.useState(null),[v,y]=g.useState(!1),[b,S]=g.useState(""),[x,k]=g.useState(!1),[_,C]=g.useState(!1),[E,j]=g.useState([]),{data:T,isLoading:I}=Oer({repoOrSlug:e,owner:"mastra-ai"}),R=lds?.includes("beta")??!1?"beta":"main",{data:L,isLoading:M}=_er({repo:T?.githubUrl?new URL(T.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:z,isLoading:H}=Cer(),{mutateAsync:F,isPending:B}=Eer(),{mutateAsync:q}=jer(),{streamInstall:D,streamResult:G,isStreaming:V}=Ner(z),{observeInstall:$,streamResult:U,isStreaming:Z}=Ier(z);g.useEffect(()=>{const ee=t.get("runId");ee&&!v&&!h&&!V&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:ee}),S(ee),q({runId:ee}).then(ce=>{const de=ce.snapshot;if(de?.status==="success"&&de?.result?.success)y(!0);else if(de?.result?.success===!1)if(de?.result?.validationResults&&!de?.result?.validationResults?.valid&&de?.result?.validationResults?.remainingErrors>0){const{remainingErrors:me,errors:be}=de.result.validationResults,we=`Template installation completed but ${me} validation issue${me>1?"s":""} remain unresolved.`;m(we),j(be||[])}else{const me=de?.result?.message||de?.result?.error||"Template installation failed";m(typeof me=="string"?me:String(me))}}).catch(ce=>{console.error("❌ Failed to fetch run details:",ce),m("Failed to retrieve installation status after reload")}))},[t,v,h,V,Z,q]),g.useEffect(()=>{const ee=t.get("runId"),ce=t.get("resume"),de=t.get("provider");if(ee&&ce==="true"&&de&&!V&&!Z&&!x&&!_&&z){S(ee),k(!0);try{q({runId:ee}).then(oe=>{if(oe.snapshot?.status==="running")return $.mutateAsync({runId:ee})}).then(()=>{n(oe=>{const me=new URLSearchParams(oe);return me.delete("resume"),me})}).catch(oe=>{console.error("❌ Failed to resume template installation:",oe),oe.message?.includes("404")||oe.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(oe){console.error("❌ Auto-resume failed with error:",oe),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,V,Z,x,_,z,q,$,n]);const K=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],ne=[{key:"tools",label:"Tools",value:T?.tools?.length?T.tools.map(ee=>ee).join(", "):"n/a",icon:o.jsx(Ld,{})},{key:"agents",label:"Agents",value:T?.agents?.length?T.agents.map(ee=>ee).join(", "):"n/a",icon:o.jsx(Vo,{})},{key:"workflows",label:"Workflows",value:T?.workflows?.length?T.workflows.map(ee=>ee).join(", "):"n/a",icon:o.jsx(zD,{})},{key:"providers",label:"Providers",value:T?.supportedProviders?.length?T.supportedProviders.join(", "):"n/a",icon:o.jsx(Dv,{})},{key:"tags",label:"Tags",value:T?.tags?.length?T.tags.join(", "):"n/a",icon:o.jsx(BN,{})}],te=[{...ne[0]},{...ne[1]},{...ne[2]}].filter(ee=>ee.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const ee=G||U;ee?.phase==="error"&&ee?.error&&m(typeof ee.error=="string"?ee.error:String(ee.error))},[G?.phase,G?.error,U?.phase,U?.error]);const J=ee=>{s(ee)},ae=async ee=>(i(ee.provider),c(ee.modelId),{message:"Model updated successfully"}),pe=async()=>{const ee=Object.entries(u).reduce((ce,[de,oe])=>(oe===""&&ce.push(de),ce),[]);if(ee.length>0){p(ee);return}if(T){m(null),y(!1),S(""),C(!0);try{const de={repo:T.githubUrl||`https://github.com/mastra-ai/template-${T.slug}`,ref:R,slug:T.slug,variables:u},{runId:oe}=await F({});S(oe),n(me=>{const be=new URLSearchParams(me);return be.set("runId",oe),be.set("resume","true"),be.set("provider",r||"openai"),be}),await D.mutateAsync({inputData:de,selectedModel:{provider:a,modelId:l},runId:oe})}catch(ce){C(!1),m(ce?.message||"Template installation failed"),console.error("Template installation failed",ce)}}},Y=ee=>{const{name:ce,value:de}=ee.target;de.trim()===""?p(oe=>[...oe,ce]):p(oe=>oe.filter(me=>me!==ce)),d(oe=>({...oe,[ce]:de}))};return o.jsx(ds,{children:o.jsx("div",{className:X("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"p-6 w-full max-w-[80rem] mx-auto grid gap-y-4",children:[o.jsx(dds,{isLoading:I,title:T?.title,description:T?.longDescription,imageURL:T?.imageURL,githubUrl:T?.githubUrl,infoData:ne,templateSlug:e}),T&&o.jsxs(o.Fragment,{children:[(V||Z)&&o.jsx(gds,{name:T.title,streamResult:Z?U:G,runId:b,workflowInfo:z}),v&&o.jsx(vds,{name:T.title,installedEntities:te,linkComponent:ti}),h&&o.jsx(cds,{errorMsg:h,validationErrors:E.length>0?E:G?.validationResults?.errors||U?.validationResults?.errors}),!V&&!Z&&!v&&!h&&o.jsx(uds,{providerOptions:K,selectedProvider:r,onProviderChange:J,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:pe,handleVariableChange:Y,isLoadingEnvVars:M||H,isInstalling:B,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const bds=()=>{const{toolId:e,agentId:t}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(JXr,{toolId:e,agentId:t})})},xds=()=>{const{toolId:e}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(Ocs,{toolId:e})})};function wds(){const{traceId:e}=Sr(),[t,n]=Pi(),r=Hs(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=g.useState(s??null),[d,f]=g.useState(),[p,h]=g.useState(i),[m,v]=g.useState(0),[y,b]=g.useState(!1),{data:S,isLoading:x,error:k}=GNe(e),_=g.useMemo(()=>S?.spans??[],[S?.spans]),C=g.useMemo(()=>_.find(ae=>ae.parentSpanId==null),[_]),{data:E,isLoading:j}=k5(e,c??"");g.useEffect(()=>v(0),[e,c]);const{data:T,isLoading:I}=ih(),{data:A,isLoading:R}=C8t({traceId:e,spanId:c??void 0,page:m}),[L,M]=g.useState(0);g.useEffect(()=>M(0),[e,c]);const{data:z,isLoading:H}=X9t({traceId:e,page:L});g.useEffect(()=>{if(l&&A?.scores&&!d){const ae=A.scores.find(pe=>pe.id===l);ae&&f(ae)}},[l,A?.scores,d]);const F=g.useCallback(ae=>{const pe=new URLSearchParams(t);for(const[Y,ee]of Object.entries(ae))ee===null||ee===""?pe.delete(Y):pe.set(Y,ee);n(pe,{replace:!0})},[t,n]),B=g.useCallback(ae=>{const pe=ae??null,Y=pe===c;u(pe),Y||(f(void 0),h("details"),F({spanId:pe,tab:null,scoreId:null}))},[c,F]),q=g.useCallback(()=>{u(null),f(void 0),h("details"),F({spanId:null,tab:null,scoreId:null})},[F]),D=g.useCallback(ae=>{u(ae),f(void 0),h("details"),F({spanId:ae,tab:null,scoreId:null})},[F]),{handlePreviousSpan:G,handleNextSpan:V}=QNe(_,c,D),$=g.useCallback(ae=>{const pe=ae;h(pe),f(void 0),F({tab:pe==="details"?null:pe,scoreId:null})},[F]),U=g.useCallback(ae=>{f(ae),F({scoreId:ae.id})},[F]),Z=g.useCallback(()=>{f(void 0),F({scoreId:null})},[F]),K=g.useCallback(()=>{r("/observability")},[r]),ne=g.useCallback(()=>{h("scoring"),C&&c!==C.spanId?(u(C.spanId),f(void 0),F({spanId:C.spanId,tab:"scoring",scoreId:null})):F({tab:"scoring"})},[C,c,F]),te=C?o.jsx($y,{owner:"trace-detail",children:o.jsxs(Mr,{children:[o.jsxs(le,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:ne,children:[o.jsx(upn,{}),"Evaluate"]}),o.jsxs(le,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(jd,{}),"Save"]})]})}):null,J=C?o.jsx(Ft.Row,{children:o.jsx(Ft.Column,{children:o.jsx(D9t,{rootSpan:C,numOfCol:3})})}):null;return k?o.jsxs(Ft,{height:"full",children:[te,J&&o.jsx(Ft.TopArea,{children:J}),o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(U9t,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Ft,{height:"full",className:"grid-rows-[auto_minmax(0,1fr)] content-normal",children:[te,J&&o.jsx(Ft.TopArea,{children:J}),o.jsx(Z9t,{rootSpanId:C?.spanId,traceId:e,isOpen:y,onClose:()=>b(!1)}),o.jsxs("div",{className:X("mt-4 grid min-h-0 items-stretch gap-4 overflow-hidden",c?"grid-cols-[2fr_3fr]":"grid-cols-[1fr]"),children:[o.jsx(BNe,{traceId:e,spans:_,isLoading:x,onClose:K,onSpanSelect:B,onEvaluateTrace:ne,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!x&&o.jsxs("div",{className:X("grid h-full max-h-full min-h-0 gap-4 overflow-auto",d?"grid-rows-[1fr_1fr]":"grid-rows-[1fr]"),children:[o.jsx(LNe,{traceId:e,spanId:c,span:E?.span,isLoading:j,onClose:q,onPrevious:G,onNext:V,activeTab:p,onTabChange:$,feedbackTabBadge:z?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(Q9t,{feedbackData:z,onPageChange:M,isLoadingFeedbackData:H}),scoringTabBadge:A?.pagination?.total??void 0,scoringTabSlot:({span:ae,traceId:pe,spanId:Y})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(K9t,{traceId:pe,isTopLevelSpan:!ae.parentSpanId,spanId:Y,entityType:ae.attributes?.agentId||ae.entityType===_s.AGENT?"Agent":ae.attributes?.workflowId||ae.entityType===_s.WORKFLOW_RUN?"Workflow":void 0,scorers:T,isLoadingScorers:I}),o.jsx(Y9t,{scoresData:A,onPageChange:v,isLoadingScoresData:R,onScoreSelect:U})]})}),d&&o.jsx(mNe,{score:d,onClose:Z})]})]})]})}function Sds(){const{data:e,isLoading:t,error:n}=Hy(),[r,s]=g.useState("");return n&&ys(n)?o.jsx(lr,{children:o.jsx(Ws,{})}):n&&xs(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"workflows"})}):n?o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(lr,{children:o.jsx(D9r,{})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx($f,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(le,{as:ti,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(MD,{}),"Schedules"]})]})}),o.jsx(M9r,{workflows:e||{},isLoading:t,search:r})]})}const kds={active:"bg-accent1",paused:"bg-accent3"},Ods={active:"text-accent1",paused:"text-accent3"},w7t=({status:e})=>o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${kds[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${Ods[e]}`,children:e})]}),iT=e=>!e||e<=0?"—":new Date(e).toLocaleString(),PP=e=>{if(!e||e<=0)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.floor(n/1e3);if(r<60)return t>=0?`in ${r}s`:`${r}s ago`;const s=Math.floor(r/60);if(s<60)return t>=0?`in ${s}m`:`${s}m ago`;const a=Math.floor(s/60);if(a<24)return t>=0?`in ${a}h`:`${a}h ago`;const i=Math.floor(a/24);return t>=0?`in ${i}d`:`${i}d ago`};function S7t({status:e}){const{icon:t,color:n}=_ds(e);return o.jsxs("span",{className:`inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function _ds(e){switch(e){case"success":return{icon:o.jsx(pa,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(bs,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Kt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(YV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(If,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(hT,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const pXe="auto auto auto auto 1fr";function Cds(e){if(e===void 0)return"—";if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;const t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${t}m ${n}s`}function Eds(e){const t=Math.abs(e),n=e<0?"-":"";return t<1e3?`${n}${t}ms`:t<6e4?`${n}${(t/1e3).toFixed(1)}s`:t<36e5?`${n}${(t/6e4).toFixed(1)}m`:`${n}${(t/36e5).toFixed(1)}h`}const jds=3e4,Tds=5*6e4;function Nds({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=bn();return t?o.jsx(ll,{columns:pXe}):e.length===0?o.jsx(ye,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(ve,{columns:pXe,className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Run"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Started"}),o.jsx(ve.TopCell,{children:"Duration"}),o.jsx(ve.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=Eds(u),f=`Scheduled ${iT(c.scheduledFireAt)} — published ${iT(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),v=!p&&m>jds&&m<=Tds,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),S=o.jsx("span",{className:b?"text-accent1 font-mono text-ui-sm whitespace-nowrap":"text-neutral3 font-mono text-ui-sm whitespace-nowrap",children:c.runId}),x=o.jsxs(o.Fragment,{children:[o.jsx(ve.Cell,{height:"compact",children:S}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm text-accent2",children:[o.jsx(yf,{size:14}),"publish failed"]}):c.run?o.jsx(S7t,{status:c.run.status}):o.jsx("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm text-neutral3",children:"pending"}),h?o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(yf,{size:14})})}),o.jsx($n,{children:h})]}):null]})}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:PP(c.actualFireAt)}),v?o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(yf,{size:14})})}),o.jsxs($n,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(ve.Cell,{height:"compact",children:c.run?o.jsx("span",{children:Cds(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(ve.Cell,{height:"compact",children:" "})]});return b?o.jsx(ve.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:x},y):o.jsx(ve.RowStatic,{children:x},y)}),o.jsx(ve.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const Ids=e=>{const t=We();return yt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},hXe=25,Ads=e=>{const t=We(),{inView:n,setRef:r}=Q_(),s=F1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:hXe,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<hXe))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},Rds=e=>{const t=We(),n=Ur();return Rn({mutationFn:async r=>{if(!e)throw new Error("scheduleId is required");return r==="pause"?t.pauseSchedule(e):t.resumeSchedule(e)},onSuccess:(r,s)=>{n.invalidateQueries({queryKey:["schedule",e]}),n.invalidateQueries({queryKey:["schedules"]}),De.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{De.error(r.message)}})};function Fz({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 uppercase tracking-wide",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function Pds(){const{scheduleId:e}=Sr(),{paths:t}=bn(),{data:n,error:r}=Ids(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=Ads(e),d=Rds(e);if(r&&ys(r))return o.jsx(lr,{children:o.jsx(Ws,{})});if(r&&xs(r))return o.jsx(lr,{children:o.jsx(Ds,{resource:"schedules"})});if(r)return o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(Ft.Row,{className:"justify-end",children:o.jsxs(Ft.Column,{className:"flex justify-end gap-2",children:[o.jsxs(le,{as:ti,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(Rc,{}),"Back to schedules"]}),f?o.jsx(le,{as:ti,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(le,{onClick:()=>d.mutate(n.status==="active"?"pause":"resume"),disabled:d.isPending,"data-testid":"schedule-toggle-button",children:n.status==="active"?o.jsxs(o.Fragment,{children:[o.jsx(Oxe,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Ef,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid gap-6 h-full overflow-hidden grid-cols-[minmax(0,20rem)_1fr]",children:[o.jsxs("div",{className:"flex flex-col gap-4 border border-border1 rounded-md p-4 h-fit",children:[o.jsx(Fz,{label:p?"Agent":"Workflow",children:f?o.jsx(ti,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(ti,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(Fz,{label:"Cron",children:[o.jsx("code",{className:"font-mono text-ui-md",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 ml-2 text-ui-sm",children:n.timezone}):null]}),o.jsx(Fz,{label:"Status",children:o.jsx(w7t,{status:n.status})}),o.jsx(Fz,{label:"Next fire",children:o.jsx("span",{title:iT(n.nextFireAt),children:PP(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ye,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Hi,{title:"Failed to load trigger history",message:i.message}):o.jsx(Nds,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const mXe="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function $ds({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=bn(),a=g.useMemo(()=>{const i=n.toLowerCase();return i?e.filter(l=>l.id.toLowerCase().includes(i)||(l.workflowId??l.agentId??"").toLowerCase().includes(i)):e},[e,n]);return t?o.jsx(ll,{columns:mXe}):o.jsxs(ve,{columns:mXe,variant:"striped",className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Target"}),o.jsx(ve.TopCell,{children:"Schedule ID"}),o.jsx(ve.TopCell,{children:"Cron"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Next fire"}),o.jsx(ve.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(ve.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(ve.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(ve.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(ve.NameCell,{children:i.workflowId??i.agentId}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"block truncate font-mono text-ui-smd text-neutral3",title:i.id,children:i.id})}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"font-mono text-ui-sm",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(ve.Cell,{height:"compact",children:o.jsx(w7t,{status:i.status})}),o.jsx(ve.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:iT(i.nextFireAt),children:PP(i.nextFireAt)})}),o.jsx(ve.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(S7t,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:iT(i.lastFireAt),children:i.lastFireAt?PP(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:iT(i.lastFireAt),children:PP(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function Mds({workflowId:e}={}){const{data:t,isLoading:n,error:r}=gwe(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(Hi,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid grid-rows-[auto_1fr] gap-4 h-full overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx($f,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx($ds,{schedules:t??[],isLoading:n,search:s})})]})}function Dds(){const[e]=Pi(),t=e.get("workflowId")??void 0,{error:n}=gwe(t?{workflowId:t}:{});return n&&ys(n)?o.jsx(lr,{children:o.jsx(Ws,{})}):n&&xs(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"schedules"})}):o.jsx(Ft,{children:o.jsx("div",{className:"h-full",children:o.jsx(Mds,{workflowId:t})})})}function Lds({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=GSe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=KSt(r),[d]=XSt(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=o4t({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"w-full h-full relative bg-surface1",children:a?o.jsxs(YSt,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(qEe,{position:"bottom-left"}),o.jsx(ekt,{variant:sy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"w-full h-full flex items-center justify-center",children:o.jsx(Kt,{})})})}function Fds(){const{stepDetail:e,closeStepDetail:t}=RH();return e?o.jsxs("div",{className:"flex flex-col h-full","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border1 bg-surface1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(F9,{className:"w-4 h-4",style:{color:ju.map}}),e.type==="nested-graph"&&o.jsx(Xu,{className:"w-4 h-4",style:{color:ju.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ye,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"p-1 hover:bg-surface3 rounded transition-colors","aria-label":"Close",children:o.jsx(bs,{className:"w-4 h-4 text-neutral3"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(AP,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(ZSe,{children:o.jsx(Lds,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function zds(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function Bds(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e);if(n.length===1)return n[0]}return t}function Uds({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"space-y-5 rounded-lg border border-border1 bg-surface4 p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ye,{as:"p",variant:"ui-md",className:"flex items-center gap-2 text-neutral6 font-semibold",children:[o.jsx(qe,{children:o.jsx(YV,{})}),"Step suspended"]}),o.jsx(un,{variant:"warning",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?fm(um(Sx(i.resumeSchema))):hp(ur(),jT());return o.jsx(Vds,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function Vds({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral6 font-medium truncate",children:e.stepId}),n&&o.jsx(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"flex items-center gap-2 text-neutral3",children:[o.jsx(qe,{children:o.jsx(kmn,{})}),"The step is asking"]}),o.jsxs(jf,{open:a,onOpenChange:i,children:[o.jsxs($d,{className:"flex w-full items-center justify-between gap-2 rounded-lg border border-border1 bg-surface3 px-3 py-2.5",children:[o.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[o.jsx(qe,{children:o.jsx(ha,{className:X("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ye,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:Bds(e.suspendPayload,e.stepId)})]}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:zds(e.suspendPayload)})]}),o.jsx(Md,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Wr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"flex items-center gap-2 text-neutral3",children:[o.jsx(qe,{children:o.jsx(Cmn,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(SB,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Ef,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:l=>{const c=e.stepId?.split(".");s({stepId:c,runId:e.runId,suspendPayload:e.suspendPayload,resumeData:l,isLoading:!1})}})})]})]})}function qds(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Ul),{runId:a}=Sr(),i=okt(e,r??""),l=BKn(),c=!!a,u=t?.status==="suspended",f=!!(a&&r&&a===r)&&e?.status==="suspended";return s||!n||i.length===0||c&&!u&&!f?null:o.jsx("div",{"data-testid":"workflow-suspended-overlay",className:"absolute top-2 right-2 z-20 w-[380px] max-w-[calc(100%-1rem)] max-h-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 duration-300",children:o.jsx(Uds,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const Hds=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.97865 4.57004C8.22604 4.75795 8.27426 5.11082 8.08635 5.35821L6.05486 8.03279C5.94873 8.17251 5.78348 8.25471 5.60803 8.25505C5.43257 8.2554 5.267 8.17385 5.16032 8.03454L3.80937 6.27034C3.6205 6.02369 3.66733 5.67063 3.91398 5.48176C4.16063 5.29288 4.51369 5.33972 4.70257 5.58637L5.6051 6.76498L7.19048 4.67774C7.37839 4.43036 7.73126 4.38213 7.97865 4.57004Z",fill:"currentColor"})]}),Wds=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.89741 4.10293C8.11707 4.32261 8.11706 4.67877 7.89738 4.89843L6.79517 6.00058L7.8962 7.10155C8.11588 7.32122 8.11589 7.67737 7.89623 7.89705C7.67656 8.11673 7.32041 8.11674 7.10073 7.89707L5.99965 6.79605L4.89856 7.89707C4.67889 8.11673 4.32273 8.11672 4.10307 7.89704C3.88341 7.67737 3.88342 7.32121 4.10309 7.10155L5.20413 6.00058L4.10191 4.89843C3.88224 4.67877 3.88223 4.32262 4.10189 4.10294C4.32155 3.88326 4.67771 3.88325 4.89738 4.10292L5.99965 5.20511L7.10191 4.10291C7.32159 3.88325 7.67774 3.88326 7.89741 4.10293Z",fill:"currentColor"})]}),Zds=e=>e.includes("."),Gds=e=>e==="input"||e.endsWith(".input"),Qds=1;function Yds(e){return`${Number((e/1e3).toPrecision(3))}s`}function Kds(e,t){const n=Object.entries(e).filter(([i])=>!Gds(i));if(n.length===0)return[];const r=Math.min(...n.map(([,i])=>i.startedAt)),s=Math.max(...n.map(([,i])=>i.endedAt??t)),a=Math.max(s-r,1);return n.map(([i,l])=>{const c=l.endedAt===void 0,d=(l.endedAt??t)-l.startedAt,f=(l.startedAt-r)/a*100,p=Math.max(d/a*100,Qds);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:Zds(i)}})}const Xds=({status:e})=>o.jsxs(qe,{children:[e==="success"&&o.jsx(Hds,{className:"text-accent1"}),e==="failed"&&o.jsx(Wds,{className:"text-accent2"}),e==="suspended"&&o.jsx(YV,{className:"text-accent3"}),e==="waiting"&&o.jsx(dpe,{className:"text-accent5"}),e==="skipped"&&o.jsx(dpe,{className:"text-icon3"}),e==="running"&&o.jsx(oa,{className:"text-accent6 animate-spin"})]}),Jds={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function k7t(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const gXe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},efs=e=>{const t=e;return XDt({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},tfs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=efs(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:X("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(Xds,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||i(e)},children:o.jsx(Egn,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(iV,{indicators:c,className:"shrink-0"})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"block min-w-0 max-w-full justify-self-stretch overflow-hidden text-ellipsis whitespace-nowrap text-left text-neutral6",children:k7t(e.stepId)}),o.jsx("div",{className:"relative h-2 min-w-0 rounded bg-surface4",children:o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":String(e.offsetPct),"data-width":String(e.widthPct),className:`absolute top-0 h-full rounded ${Jds[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||l(e)},children:o.jsx(_gn,{})})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"w-20 justify-self-end text-right text-neutral3 tabular-nums",children:Yds(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function nfs(){const{steps:e}=F3(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=Hq(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);Owe(f,{enabled:!l});const p=Kds(e,a),h=p.some(m=>m.isRunning);return g.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),g.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden rounded-studio-panel border border-border1/50 bg-surface3 p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"rounded-md p-1 text-neutral3 transition-colors hover:bg-surface4 hover:text-neutral6",children:o.jsx(Ia,{className:X("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:p.map((m,v)=>o.jsx(tfs,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:gXe(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:gXe(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(br,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(ckt,{data:u.data,title:`${k7t(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const rfs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=RH();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(l4t,{workflowId:e,workflow:t,isLoading:n}),o.jsx(qds,{}),o.jsx(nfs,{})]})}),r&&o.jsx("div",{className:"w-[420px] min-h-0 overflow-hidden border-l border-border1",children:o.jsx(Fds,{})})]})},vXe=()=>{const{workflowId:e}=Sr(),{data:t,isLoading:n,error:r}=q4(e);return r&&ys(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ws,{})}):r&&xs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"workflows"})}):o.jsx(fke,{children:o.jsx(rfs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function sfs(e,t){if(e==null)return{};var n,r,s=pwt(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function sbe(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function afs(e){if(Array.isArray(e))return sbe(e)}function ifs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function ofs(e,t){if(e){if(typeof e=="string")return sbe(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?sbe(e,t):void 0}}function lfs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
733
|
+
`);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>Xye(t));if(e&&typeof e=="object")return Object.values(e).some(t=>Xye(t))}return!1}function hls({children:e}){return o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e})}function mls({className:e,children:t}){return o.jsx("div",{className:X("mx-4 flex items-center justify-between gap-2 border-b border-border1 py-3",e),children:t})}function gls({className:e,children:t}){return o.jsx("h3",{className:X("flex gap-2 text-ui-md text-neutral3 [&>b]:font-normal [&>b]:text-neutral2",e),children:t})}function vls({className:e,children:t}){return o.jsx("dl",{className:X("grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5",e),children:t})}function yls({className:e,children:t}){return o.jsx("dt",{className:X("shrink-0 py-0.5 text-ui-smd text-neutral2",e),children:t})}function bls({className:e,children:t}){return o.jsx("dd",{className:X("min-w-0 truncate py-0.5 text-ui-smd text-neutral3",e),children:t})}function xls({className:e,children:t}){return o.jsx("dt",{className:X("col-span-2 py-3 text-ui-sm tracking-widest text-neutral2 uppercase",e),children:t})}const wls=Object.assign(vls,{Key:yls,Value:bls,Header:xls});function Sls({children:e}){return o.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-6 text-ui-sm text-neutral3",children:[o.jsx(Kt,{size:"sm",variant:"pulse",className:"text-neutral3"})," ",e??"Loading..."]})}function kls({children:e}){return o.jsx("p",{className:"px-4 py-6 text-ui-sm text-neutral2",children:e??"No data found."})}const Bi=Object.assign(lls,{Header:mls,Heading:gls,CloseButton:cls,LoadingData:Sls,NoData:kls,Content:hls,KeyValueList:wls,CodeSection:pls}),ap=Bi.KeyValueList;function Ols(e){return e instanceof Date?e:new Date(e)}function _ls({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,p=Ols(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(Bi,{collapsed:d,children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Log ",o.jsx("b",{children:nr(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[l&&o.jsx(le,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(Mq,{}):o.jsx(ewe,{})}),o.jsxs(Mr,{spacing:"close",children:[o.jsx(le,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx($q,{})}),o.jsx(le,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(c4,{})})]}),o.jsx(Bi.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Bi.Content,{children:[o.jsx("p",{className:"font-mono text-ui-md wrap-break-word whitespace-pre-wrap text-neutral4",children:e.message}),(h||m)&&o.jsxs("div",{className:X("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(h7,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:" ml-auto min-w-0 truncate text-ui-sm text-neutral2",children:["# ",h]})]}),o.jsx($a,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(h7,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:" ml-auto min-w-0 truncate text-ui-sm text-neutral2",children:["# ",m]})]}),o.jsx($a,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(ap,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Entity Type"}),o.jsx(ap.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Entity Name"}),o.jsx(ap.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Service"}),o.jsx(ap.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Environment"}),o.jsx(ap.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Source"}),o.jsx(ap.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([v,y])=>o.jsxs(g.Fragment,{children:[o.jsx(ap.Key,{children:v}),o.jsx(ap.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Bi.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function Cls({error:e,resource:t,errorTitle:n}){if(ys(e))return o.jsx(Ws,{});if(xs(e))return o.jsx(Ds,{resource:t});if(QAt(e,"logs"))return o.jsx(zr,{iconSlot:o.jsx(twe,{}),titleSlot:"Logs are not available with your current storage",descriptionSlot:"The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio."});const r=e instanceof Error?e.message:void 0;return o.jsx(Hi,{title:n,message:r??"Unknown error"})}function Els({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:X("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:X("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const jls={debug:{label:"DEBUG",color:"#71717a"},info:{label:"INFO",color:"#60a5fa"},warn:{label:"WARN",color:"#facc15"},error:{label:"ERROR",color:"#f87171"},fatal:{label:"FATAL",color:"#dc2626"}};function Tls({level:e}){const t=jls[e];return o.jsx(To,{height:"compact",children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function Nls({entityType:e,className:t}){const n=X("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case _s.AGENT:return o.jsx(Vo,{className:n,"aria-hidden":!0});case"workflow":case _s.WORKFLOW_RUN:return o.jsx(Xu,{className:n,"aria-hidden":!0});case _s.TOOL:return o.jsx(Ld,{className:n,"aria-hidden":!0});default:return null}}function Ils({entityType:e,entityName:t}){const n=e??"";return o.jsxs(To,{height:"compact",className:"flex min-w-0 items-center gap-2",children:[o.jsx(Nls,{entityType:n}),t?o.jsx("span",{className:"min-w-0 truncate text-ui-smd",children:t}):"-"]})}function Als({message:e}){return o.jsx(To,{height:"compact",className:"min-w-0 truncate font-mono text-ui-smd text-neutral4",children:e})}function Rls({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(To,{height:"compact",children:null});const t=Object.entries(e).map(([n,r])=>{if(typeof r=="string")return`${n}: ${r}`;try{return`${n}: ${JSON.stringify(r)}`}catch{return`${n}: <unserializable>`}}).join(", ");return o.jsx(GCe,{children:t})}const Ql=Object.assign(E3,{Top:aZ,TopCell:lC,TopCellWithTooltip:iZ,TopCellSmart:E$t,RowWrapper:JCe,RowButton:j3,RowLink:j$t,Spacer:XCe,NoMatch:sZ,DateCell:QCe,TimeCell:YCe,LevelCell:Tls,EntityCell:Ils,MessageCell:Als,DataCell:Rls,NextPageLoading:rZ}),iXe="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",Pls=36,$ls=8;function Mls({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=q9t({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>Pls,overscan:$ls}),d=g.useRef(t);if(g.useEffect(()=>{d.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),d.current=t},[t]),t)return o.jsx(ll,{columns:iXe});const f=u.getVirtualItems(),p=u.getTotalSize(),h=f[0]?.start??0,m=f.length>0?Math.max(0,p-(f[f.length-1]?.end??0)):0;return o.jsxs(Ql,{columns:iXe,variant:"striped",scrollRef:c,className:"min-w-0",children:[o.jsxs(Ql.Top,{children:[o.jsx(Ql.TopCell,{children:"Date"}),o.jsx(Ql.TopCell,{children:"Time"}),o.jsx(Ql.TopCell,{children:"Level"}),o.jsx(Ql.TopCell,{children:"Entity"}),o.jsx(Ql.TopCell,{children:"Message"}),o.jsx(Ql.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Ql.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Ql.Spacer,{height:h}),f.map(v=>{const y=e[v.index];if(!y)return null;const b=a.get(y);if(!b)return null;const S=b===i;return o.jsxs(Ql.RowButton,{ref:u.measureElement,"data-index":v.index,onClick:()=>l(y),featured:S,variant:y.level==="error"||y.level==="fatal"?"error":"default",children:[o.jsx(Ql.DateCell,{timestamp:y.timestamp}),o.jsx(Ql.TimeCell,{timestamp:y.timestamp}),o.jsx(Ql.LevelCell,{level:y.level}),o.jsx(Ql.EntityCell,{entityType:y.entityType,entityName:y.entityName}),o.jsx(Ql.MessageCell,{message:y.message}),o.jsx(Ql.DataCell,{data:y.data})]},b)}),o.jsx(Ql.Spacer,{height:m})]}),o.jsx(Ql.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function Dls({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>Lls(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(MNe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(PNe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Lls(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 Fls={"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"},fae="MMM d, yyyy HH:mm",pae="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function zls({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${Fls[e]}`,description:pae}:t&&n?{title:`No logs between ${nr(t,fae)} and ${nr(n,fae)}`,description:pae}:t?{title:`No logs since ${nr(t,fae)}`,description:pae}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const Bls=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=zls({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zr,{iconSlot:o.jsx(twe,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(nwe,{})]})})})},Uls=20,Vls=1e4;function qls(e,t,n){if(e?.pagination?.hasMore)return n+1}function Hls(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const a=s.logId??JSON.stringify(s);t.has(a)||(t.add(a),n.push(s))}return n}function Wls(e){return QAt(e.state.error,"logs")?!1:Vls}const Zls=({filters:e}={})=>{const t=We(),{inView:n,setRef:r}=Q_(),s=F1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:Uls},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:qls,select:Hls,retry:!1,refetchInterval:Wls}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},Pz={AGENT:_s.AGENT,WORKFLOW:_s.WORKFLOW_RUN,SCORER:_s.SCORER,INGEST:_s.RAG_INGESTION},u7t=[{label:"Agent",entityType:Pz.AGENT},{label:"Workflow",entityType:Pz.WORKFLOW},{label:"Scorer",entityType:Pz.SCORER},{label:"Ingest",entityType:Pz.INGEST}],Gls=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],zx="rootEntityType",Gb="datePreset",Qb="dateFrom",Yb="dateTo",Qls=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Il={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"},O5=Object.keys(Il),sIe=new Set(["tags"]),aIe="mastra:logs:saved-filters";function Yls(e,t=aIe){const n=tcs(e),r=e.get(Gb);r&&n.set(Gb,r);const s=e.get(Qb);s&&n.set(Qb,s);const a=e.get(Yb);a&&n.set(Yb,a);try{localStorage.setItem(t,n.toString())}catch{}}function Kls(e=aIe){try{localStorage.removeItem(e)}catch{}}function oXe(e=aIe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Xls(e){if(e.has(Gb)||e.has(Qb)||e.has(Yb)||e.has(zx))return!0;for(const t of O5)if(e.has(Il[t]))return!0;return!1}function Jls({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:u7t.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:Gls.map(u=>({label:u.label,value:u.value})),placeholder:"Choose level",emptyText:"No levels."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"spanId",label:"Span ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function ecs(e){const t=[],n=new Map([[zx,"rootEntityType"]]);for(const s of O5)n.set(Il[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),sIe.has(a)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function tcs(e){const t=new URLSearchParams,n=e.get(zx);n&&t.set(zx,n);for(const r of O5){const s=Il[r];if(sIe.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const a=e.get(s);a&&t.set(s,a)}return t}function ncs(e,t){e.delete(zx);for(const n of O5)e.delete(Il[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(zx,n.value);continue}const r=Il[n.fieldId];if(r){if(sIe.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 rcs({rootEntityType:e,dateFrom:t,dateTo:n,tokens:r}){const s={};e&&(s.rootEntityType=e),(t||n)&&(s.timestamp={...t?{start:t}:{},...n?{end:n}:{}});for(const a of r){if(a.fieldId==="tags"){Array.isArray(a.value)&&a.value.length>0?s.tags=a.value:typeof a.value=="string"&&a.value.trim()&&(s.tags=[a.value.trim()]);continue}if(a.fieldId==="level"){typeof a.value=="string"&&a.value.trim()&&a.value!=="Any"&&(s.level=a.value);continue}if(typeof a.value=="string"&&a.value.trim()&&a.value!=="Any")switch(a.fieldId){case"entityName":s.rootEntityName=a.value;break;case"traceId":s.traceId=a.value;break;case"spanId":s.spanId=a.value;break;case"runId":s.runId=a.value;break;case"threadId":s.threadId=a.value;break;case"sessionId":s.sessionId=a.value;break;case"requestId":s.requestId=a.value;break;case"resourceId":s.resourceId=a.value;break;case"userId":s.userId=a.value;break;case"organizationId":s.organizationId=a.value;break;case"serviceName":s.serviceName=a.value;break;case"environment":s.environment=a.value;break;case"experimentId":s.experimentId=a.value;break}}return s}function scs(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 acs="Filters setting for Logs saved",ics="Filters setting for Logs cleared up";function ocs(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>oXe(r)!==null),c=g.useCallback(()=>{Yls(e,r),l(!0);const f=s?.saved??acs;f!==!1&&De.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{Kls(r),l(!1);const f=s?.cleared??ics;f!==!1&&De.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,Xls(e)))return;const f=oXe(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function lcs(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 ccs(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,lcs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function ucs(e,t,n,r){const s=g.useMemo(()=>ccs(e),[e]),a=g.useMemo(()=>{const h=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&h.set(y,{log:v,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(h=>s.get(h),[s]),d=g.useCallback(h=>{const m=s.get(h);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const h=e[l-1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0,p=l>=0&&l<e.length-1?()=>{const h=e[l+1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:p}}const Jye="logId",ebe="traceId",tbe="spanId",i2=1440*60*1e3,dcs={"last-24h":i2,"last-3d":3*i2,"last-7d":7*i2,"last-14d":14*i2,"last-30d":30*i2};function $z(e){e.delete(Jye),e.delete(ebe),e.delete(tbe)}function fcs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(Gb);return _&&Qls.has(_)?_:"last-24h"},[e]),a=e.get(Qb),i=e.get(Yb),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const C=new Date(a);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=dcs[s];return _?new Date(Date.now()-_):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const _=new Date(i);return Number.isNaN(_.getTime())?void 0:_},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(Jye),f=e.get(ebe),p=e.get(tbe),h=g.useMemo(()=>u7t.find(_=>_.entityType===e.get(zx)),[e]),m=g.useMemo(()=>ecs(e),[e]),v=g.useCallback(_=>{t(C=>{const E=new URLSearchParams(C);for(const[j,T]of Object.entries(_)){const I=j==="logId"?Jye:j==="traceId"?ebe:tbe;T?E.set(I,T):E.delete(I)}return E},{replace:!0})},[t]),y=g.useCallback(_=>{t(C=>{const E=new URLSearchParams(C);return ncs(E,_),$z(E),E},{replace:!0})},[t]),b=y,S=g.useCallback((_,C)=>{if(u.current!=="custom")return;const E=C==="from"?Qb:Yb;t(j=>{const T=new URLSearchParams(j);return _?T.set(E,_.toISOString()):T.delete(E),$z(T),T},{replace:!0})},[t]),x=g.useCallback(_=>{u.current=_,t(C=>{const E=new URLSearchParams(C);return _==="last-24h"?(E.delete(Gb),E.delete(Qb),E.delete(Yb)):_==="custom"?E.set(Gb,"custom"):(E.set(Gb,_),E.delete(Qb),E.delete(Yb)),$z(E),E},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(zx);for(const E of O5)C.delete(Il[E]);return C.delete(Gb),C.delete(Qb),C.delete(Yb),$z(C),C},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:S,handleDatePresetChange:x,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,v,b,S,x,k,y])}const kb=Bi.KeyValueList;function pcs({spanId:e,span:t,isLoading:n,onClose:r}){const s=t?.startedAt&&t?.endedAt?new Date(t.endedAt).getTime()-new Date(t.startedAt).getTime():null;return o.jsxs(Bi,{children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Bi.CloseButton,{onClick:r})]}),n?o.jsx(Bi.LoadingData,{children:"Loading span..."}):t?o.jsxs(Bi.Content,{children:[o.jsxs(kb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Type"}),o.jsx(kb.Value,{children:t.spanType})]}),t.startedAt&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Started"}),o.jsx(kb.Value,{children:nr(new Date(t.startedAt),"MMM dd, HH:mm:ss.SSS")})]}),t.endedAt&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Ended"}),o.jsx(kb.Value,{children:nr(new Date(t.endedAt),"MMM dd, HH:mm:ss.SSS")})]}),s!=null&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Duration"}),o.jsx(kb.Value,{children:s<1e3?`${s}ms`:`${(s/1e3).toFixed(2)}s`})]})]}),o.jsx("br",{}),o.jsx(Bi.CodeSection,{title:"Input",icon:o.jsx(Gpe,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Output",icon:o.jsx(Qpe,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Metadata",icon:o.jsx(yw,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Attributes",icon:o.jsx(yw,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Bi.NoData,{children:"Span not found."})]})}function hcs({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>zNe(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(FNe(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Bi,{children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Bi.CloseButton,{onClick:r})]}),n?o.jsx(Bi.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Bi.NoData,{children:"No spans found for this trace."}):o.jsx(Bi.Content,{children:o.jsx(B9t,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function mcs(){const[e,t]=Pi(),n=fcs(e,t),r=ocs(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=ZNe(),{data:d=[],isPending:f}=qNe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=HNe(),{data:m=[],isPending:v}=WNe(),y=g.useMemo(()=>Jls({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:v,environments:h}}),[c,d,m,p,u,f,v,h]),b=g.useMemo(()=>rcs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:S=[],isLoading:x,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E}=Zls({filters:b}),{logIdMap:j,featuredLog:T,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=ucs(S,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:M}=GNe(n.featuredTraceId??null),{data:z,isLoading:H}=k5(n.featuredTraceId??"",n.featuredSpanId??""),F=g.useCallback(()=>n.applyFilterTokens(scs(y,n.filterTokens)),[y,n]),B=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),q=g.useCallback(K=>n.handleFeaturedChange({traceId:K,spanId:null}),[n]),D=g.useCallback((K,ne)=>n.handleFeaturedChange({traceId:K,spanId:ne}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),V=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=g.useCallback(K=>n.handleFeaturedChange({spanId:K??null}),[n]),U=o.jsxs(Ft.TopArea,{children:[o.jsx(Ft.Row,{children:o.jsxs(Ft.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(UG,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:x,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(DNe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:x,onStartTextFilter:a})]})}),o.jsx(Dls,{isLoading:x,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:F,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Ft,{width:"wide",height:"full",children:[U,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(Cls,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return S.length===0&&!x&&!Z?o.jsxs(Ft,{width:"wide",height:"full",children:[U,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(Bls,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Ft,{width:"wide",height:"full",children:[U,o.jsx(Els,{logCollapsed:i,listSlot:o.jsx(Mls,{logs:S,isLoading:x,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E,logIdMap:j,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:T?o.jsx(_ls,{log:T,onClose:B,onTraceClick:q,onSpanClick:D,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(hcs,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:M,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(pcs,{spanId:n.featuredSpanId,span:z?.span,isLoading:H,onClose:V}):null})]})}function gcs({server:e}){const{paths:t,Link:n}=bn(),s=We().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=r8t(e),l=Object.values(i||{}),c=l.length,u=l.filter(p=>p.toolType==="agent").length,d=l.filter(p=>p.toolType==="workflow").length,f=_y(e.name,50);return o.jsxs(ve.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(ve.NameCell,{children:f}),o.jsx(ve.DescriptionCell,{children:a}),o.jsx(ve.TextCell,{className:"text-center",children:u||""}),o.jsx(ve.TextCell,{className:"text-center",children:c||""}),o.jsx(ve.TextCell,{className:"text-center",children:d||""})]})}function vcs({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(ll,{columns:"auto 1fr auto auto auto"}):o.jsxs(ve,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"URL"}),o.jsx(ve.TopCellSmart,{long:"Agents",short:o.jsx(Vo,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(ve.TopCellSmart,{long:"Tools",short:o.jsx(Ld,{}),tooltip:"Tools",className:"text-center"}),o.jsx(ve.TopCellSmart,{long:"Workflows",short:o.jsx(Xu,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(ve.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(gcs,{server:s},s.id))]})}const ycs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zr,{iconSlot:o.jsx(If,{}),titleSlot:"No MCP Servers yet",descriptionSlot:o.jsxs(o.Fragment,{children:["MCP servers are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(ka,{})]})})}),bcs=()=>{const{data:e=[],isLoading:t,error:n}=AG(),[r,s]=g.useState("");return n&&ys(n)?o.jsx(lr,{children:o.jsx(Ws,{})}):n&&xs(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"MCP servers"})}):n?o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(lr,{children:o.jsx(ycs,{})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx($f,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(vcs,{mcpServers:e,isLoading:t,search:r})]})},xcs=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const a=t[s],i=a.tools,l=Object.keys(i);for(const c of l){const u=i[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...a,id:s})}}for(const[s,a]of Object.entries(e))n.has(a.id)||n.set(a.id,{...a,agents:[]});return Array.from(n.values())};function wcs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=bn(),i=g.useMemo(()=>xcs(e,t),[e,t]),l=g.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(ll,{columns:"auto 1fr auto"}):o.jsxs(ve,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"Description"}),o.jsx(ve.TopCellSmart,{long:"Agents",short:o.jsx(Vo,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(ve.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=_y(c.id,50),d=_y(c.description??"",200),f=c.agents.length;return o.jsxs(ve.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(ve.NameCell,{children:u}),o.jsx(ve.DescriptionCell,{children:d}),o.jsx(ve.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const Scs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zr,{iconSlot:o.jsx(If,{}),titleSlot:"No Tools yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra tools are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(ka,{})]})})}),kcs=()=>{const e=We();return Rn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new k_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw De.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},Ocs=({toolId:e})=>{const{canExecute:t}=dl(),n=t("tools"),{data:r={}}=Em(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=zEr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=kcs(),{requestContext:p}=Cs();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";De.error(`Error loading tool: ${v}`)}},[l]);const h=async(v,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?fm(um(Sx(c?.inputSchema))):ks({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(xt,{className:"h-8 w-48 mb-4"}),o.jsx(xt,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(xNe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function _cs({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l}){const{data:c={},isLoading:u,isError:d,error:f}=AI(),{data:p={},isLoading:h,isError:m,error:v}=Em(),{navigate:y,paths:b}=bn();g.useEffect(()=>{if(d){const _=f instanceof Error?f.message:"Failed to load tools";De.error(`Error loading tools: ${_}`)}},[d,f]),g.useEffect(()=>{if(m){const _=v instanceof Error?v.message:"Failed to load agents";De.error(`Error loading agents: ${_}`)}},[m,v]);const S=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(C=>{S.has(C.id)||S.set(C.id,C)})}),Object.values(c).forEach(_=>{S.has(_.id)||S.set(_.id,_)});const x=Array.from(S.values()).map(_=>({label:_.id,value:_.id})),k=_=>{t?t(_):_&&_!==e&&y(b.toolLink(_))};return o.jsx(ic,{options:x,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const Ccs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(Cy,{children:o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral3 font-medium py-20 text-center",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(Cy,{isDivided:!0,children:[o.jsxs("div",{className:"px-8 py-12 mx-auto max-w-2xl w-full",children:[o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral6 font-medium pb-4",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(un,{icon:o.jsx(L9t,{className:"text-neutral6"}),className:"rounded-r-sm text-neutral4!",children:"Version"}),o.jsx(un,{className:"rounded-l-sm text-neutral4!",children:t.version_detail.version})]}),o.jsx(ye,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(un,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"px-2 py-1 bg-surface4 rounded-lg",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx($a,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(un,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"px-2 py-1 bg-surface4 rounded-lg",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx($a,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(un,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",children:"CLI"}),children:"Command Line"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"px-2 py-1 bg-surface4 rounded-lg",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx($a,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"h-full overflow-y-scroll border-l border-border1",children:o.jsx(Ecs,{server:t})})]})},Ecs=({server:e})=>{const{data:t={},isLoading:n}=r8t(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"p-5 overflow-y-scroll",children:[o.jsxs("div",{className:"text-neutral6 flex gap-2 items-center",children:[o.jsx(qe,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(bC,{})}),o.jsx(ye,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(Tcs,{tool:a,serverId:e.id},s)})})]})};function jcs(e){if(!e)return!1;const t=e.ui;return!!(typeof t?.resourceUri=="string"&&t.resourceUri.startsWith("ui://")||typeof e["ui/resourceUri"]=="string"&&e["ui/resourceUri"].startsWith("ui://"))}const Tcs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=bn(),a=T8t[e.toolType||"tool"],i=jcs(e._meta);return o.jsxs(Df,{onClick:()=>n.current?.click(),children:[o.jsx(FPt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Ff,{children:[o.jsx(Lf,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.id),children:e.id}),i&&o.jsx(un,{className:"text-[10px] py-0",children:"App"})]})}),o.jsx(th,{children:e.description})]})]})},Ncs=()=>{const{serverId:e}=Sr(),{data:t=[],isLoading:n}=AG(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(Ccs,{isLoading:n,server:r})})};function Ics(e){if(!e)return;const t=e.ui;if(t?.resourceUri)return t.resourceUri;const n=e["ui/resourceUri"];if(typeof n=="string")return n}const Acs=({toolId:e,serverId:t})=>{const{canExecute:n}=dl(),r=n("tools"),s=We(),{data:a,isLoading:i,error:l}=pNe(t,e),{mutateAsync:c,isPending:u,data:d}=PQr(t,e),f=a?Ics(a._meta):void 0,{data:p}=yt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";De.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(xt,{className:"h-8 w-48 mb-4"}),o.jsx(xt,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=fm(um(a.inputSchema))}catch(y){console.error("Error processing input schema:",y),De.error("Failed to process tool input schema."),v=ks({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-b border-border1 p-4",children:o.jsx(n8t,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(xNe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},Rcs=()=>{const{serverId:e,toolId:t}=Sr(),{data:n,isLoading:r}=pNe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Acs,{toolId:t,serverId:e})})},d7t=[{label:"Agent",entityType:_s.AGENT},{label:"Workflow",entityType:_s.WORKFLOW_RUN},{label:"Scorer",entityType:_s.SCORER},{label:"Ingest",entityType:_s.RAG_INGESTION}],IN="rootEntityType",AN={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId",provider:"filterProvider",model:"filterModel"},qG=Object.keys(AN),iIe="mastra:metrics:saved-filters";function Pcs(e){const t=Fcs(e);try{localStorage.setItem(iIe,t.toString())}catch{}}function $cs(){try{localStorage.removeItem(iIe)}catch{}}function f7t(){try{const e=localStorage.getItem(iIe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function Mcs(e){if(e.has(IN))return!0;for(const t of qG)if(e.has(AN[t]))return!0;return!1}function Dcs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:d7t.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"threadId",label:"Thread ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function Lcs(e){const t=[],n=new Map([[IN,"rootEntityType"]]);for(const s of qG)n.set(AN[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}if(a==="rootEntityType"||a==="entityName"||a==="serviceName"||a==="environment"||a==="provider"||a==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:a,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function Fcs(e){const t=new URLSearchParams,n=e.getAll(IN);for(const r of n)t.append(IN,r);for(const r of qG){const s=AN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function zcs(e,t){e.delete(IN);for(const n of qG)e.delete(AN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?IN:AN[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string"&&a!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const a of s)e.append(r,a)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const Bcs="Any";function lXe(e){const t=e.trim();return t===""||t===Bcs}const Ucs=new Set(d7t.map(e=>e.entityType));function cXe(e){const t=e.trim();return Ucs.has(t)?t:void 0}function Vcs(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>!lXe(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?cXe(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(lXe(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=cXe(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const p7t=[{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"}],qcs=new Set(p7t.map(e=>e.value));function Hcs(e){return typeof e=="string"&&(qcs.has(e)||e==="custom")}const h7t=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function HG(){return g.useContext(h7t)}function Wcs(e,t){return e!=="custom"?p7t.find(n=>n.value===e)?.label??e:t?.from?t.to?`${nr(t.from,"MMM d, yyyy")} – ${nr(t.to,"MMM d, yyyy")}`:nr(t.from,"MMM d, yyyy"):"Custom range"}function Zcs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>Vcs(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=Wcs(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,h,d,s,f,p,l,c]);return o.jsx(h7t.Provider,{value:m,children:e})}const Gcs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function Qcs(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 Ycs(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 Kcs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=HG(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(UG,{preset:Qcs(e),onPresetChange:i=>{const l=Ycs(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...a.current,[l]:i};a.current=c,r(c)},presets:Gcs})}const nbe=1440*60*1e3,Xcs={"24h":nbe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function Jcs(e,t,n){if(e!=="custom"){const r=Xcs[e]??nbe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-nbe),end:t?.to??new Date(n)}}function Im(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=HG(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>Jcs(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function m7t(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}const eus=new Set(["ObservabilityStorageClickhouseVNext","ObservabilityStorageDuckDB","ObservabilityInMemory","ObservabilitySpanner","ObservabilityStoragePostgresVNext"]),tus=()=>{const{data:e,isLoading:t}=R3(),n=e?.observabilityStorageType;return{supportsMetrics:e?.observabilityStorageCapabilities?.metrics??(n?eus.has(n):!1),isInMemory:n==="ObservabilityInMemory",isLoading:t}};function _5({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(QEn,{})})}function nus({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(Ijn,{})})}const rus=[{dataKey:"p50",label:"p50",color:Fp.blue,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p50,0)/e.length)}`:"0",suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Fp.yellow,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p95,0)/e.length)}`:"0",suffix:"avg ms"})}];function sus(e){return e==="agents"||e==="workflows"||e==="tools"}function hae({data:e,onPointClick:t}){return e.length===0?o.jsx(Wt.NoData,{message:"No latency data yet"}):o.jsx(kV,{data:e,series:rus,onPointClick:t?n=>{const r=n;typeof r?.tsMs=="number"&&Number.isFinite(r.tsMs)&&t(r)}:void 0})}function aus({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),p=c[d]?d:u,h=typeof s=="function"?s(p):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,S)=>b+S,0)/v.length)}ms`:"—";return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Wt.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Wt.Actions,{children:h}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load latency data"}):o.jsx(Wt.Content,{children:m?o.jsxs(Lc,{value:p,onValueChange:b=>{sus(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(Dc,{children:[o.jsx(Rr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Rr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Rr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:o.jsx(hae,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Xr,{value:"workflows",children:o.jsx(hae,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Xr,{value:"tools",children:o.jsx(hae,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Wt.NoData,{message:"No latency data yet"})})]})}function ius(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 ous(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const a=new Date(s.getTime()+3600*1e3);return{from:s,to:a}}const n=new Date(e);n.setUTCHours(0,0,0,0);const r=new Date(n.getTime()+1440*60*1e3);return{from:n,to:r}}function g7t(e,t,n,r,s,a,i){if(i){e.set(t,"custom"),e.set(n,i.from.toISOString()),e.set(r,i.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),a?.from&&e.set(n,a.from.toISOString()),a?.to&&e.set(r,a.to.toISOString());return}const l=ius(s);l&&e.set(t,l)}function Po(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function v7t(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function uXe({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/observability"}){const a=new URLSearchParams;a.set(Ow,"branches"),g7t(a,_w,Cw,Ew,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Lx,i),r.status&&a.set(Fx,r.status),Po(a,Nl.entityName,r.entityName??n.entityName),Po(a,Nl.threadId,r.threadId??n.threadId),Po(a,Nl.resourceId,r.resourceId??n.resourceId),Po(a,Nl.entityId,n.entityId),Po(a,Nl.runId,n.runId),Po(a,Nl.sessionId,n.sessionId),Po(a,Nl.requestId,n.requestId),Po(a,Nl.userId,n.userId),Po(a,Nl.organizationId,n.organizationId),Po(a,Nl.experimentId,n.experimentId),Po(a,Nl.serviceName,n.serviceName),Po(a,Nl.environment,n.environment),v7t(a,Nl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function lus({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;g7t(a,Gb,Qb,Yb,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(zx,i),Po(a,Il.entityName,r.entityName??n.entityName),Po(a,Il.threadId,r.threadId??n.threadId),Po(a,Il.resourceId,r.resourceId??n.resourceId),Po(a,Il.runId,n.runId),Po(a,Il.sessionId,n.sessionId),Po(a,Il.requestId,n.requestId),Po(a,Il.userId,n.userId),Po(a,Il.organizationId,n.organizationId),Po(a,Il.experimentId,n.experimentId),Po(a,Il.serviceName,n.serviceName),Po(a,Il.environment,n.environment),v7t(a,Il.tags,n.tags),r.status==="error"&&a.append(Il.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function YI(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=HG(),a=g.useCallback((c={})=>uXe({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>lus({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=ous(u,d);return uXe({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const y7t="1h";async function mae(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:y7t,filters:n}),s=r.series.find(l=>l.percentile===.5),a=r.series.find(l=>l.percentile===.95);if(!s||!a)return[];const i=new Map(a.points.map(l=>[new Date(l.timestamp).getTime(),l.value]));return s.points.map(l=>{const c=new Date(l.timestamp),u=c.getTime();return{time:c.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),tsMs:u,p50:Math.round(l.value),p95:Math.round(i.get(u)??0)}})}function cus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([mae(e,"mastra_agent_duration_ms",t),mae(e,"mastra_workflow_duration_ms",t),mae(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:y7t}}})}const dXe={agents:_s.AGENT,workflows:_s.WORKFLOW_RUN,tools:_s.TOOL};function uus(){const{data:e,isLoading:t,isError:n}=cus(),{getTracesHref:r,getBucketTracesHref:s}=YI(),{Link:a}=bn(),i=Hs();return o.jsx(aus,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:dXe[l]},c.tsMs,"1h"))},actions:l=>o.jsx(_5,{href:r({rootEntityType:dXe[l]}),LinkComponent:a})})}function dus(e){return e==="threads"||e==="resources"}function gae(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function fus({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,p=e.data?.reduce((y,b)=>y+b.runs,0)??0,h=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,v=typeof s=="function"?s(i):s;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Wt.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Wt.Summary,{value:h.toLocaleString(),label:"Total threads"}),v?o.jsx(Wt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Wt.Loading,{}):m.isError?o.jsx(Wt.Error,{message:"Failed to load memory data"}):o.jsx(Wt.Content,{children:o.jsxs(Lc,{defaultTab:"threads",value:i,onValueChange:y=>{dus(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Dc,{children:[o.jsx(Rr,{value:"threads",children:"Threads"}),o.jsx(Rr,{value:"resources",children:"Resources"})]}),o.jsx(Xr,{value:"threads",children:d?o.jsxs(ve,{columns:"auto auto auto auto auto",...Yye,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),S=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:gae(y.threadId)}),o.jsx(ve.NumberCell,{children:y.resourceId?gae(y.resourceId):"—"}),o.jsx(ve.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(ve.NumberCell,{children:y.tokens>0?_c(y.tokens):"—"}),o.jsx(ve.NumberCell,{children:y.cost!=null?Cg(y.cost,y.costUnit):"—"})]});return b?o.jsx(ve.RowLink,{to:b,LinkComponent:a,children:S},y.key):o.jsx(ve.RowStatic,{children:S},y.key)})]}):o.jsx(Wt.NoData,{message:"No thread activity yet"})}),o.jsx(Xr,{value:"resources",children:f?o.jsxs(ve,{columns:"auto auto auto auto",...Yye,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),S=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:gae(y.resourceId)}),o.jsx(ve.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(ve.NumberCell,{children:y.tokens>0?_c(y.tokens):"—"}),o.jsx(ve.NumberCell,{children:y.cost!=null?Cg(y.cost,y.costUnit):"—"})]});return b?o.jsx(ve.RowLink,{to:b,LinkComponent:a,children:S},y.key):o.jsx(ve.RowStatic,{children:S},y.key)})]}):o.jsx(Wt.NoData,{message:"No resource activity yet"})})]})})]})}function C5(e,t,n){const r=e.get(t);if(r!==void 0)return r;const s=n();return e.set(t,s),s}const vae=20;function pus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:vae}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:vae}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:vae})]),l=new Map,c=d=>C5(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.threadId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,p=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}const yae=20;function hus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:yae}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:yae}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:yae})]),l=new Map,c=d=>C5(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.resourceId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,p=l.get(f);return{resourceId:f,threadCount:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}function mus(){const e=pus(),t=hus(),{getTracesHref:n}=YI(),{Link:r}=bn();return o.jsx(fus,{threads:{data:e.data,isLoading:e.isLoading,isError:e.isError},resources:{data:t.data,isLoading:t.isLoading,isError:t.isError},LinkComponent:r,getThreadRowHref:s=>n({threadId:s.threadId,...s.resourceId?{resourceId:s.resourceId}:{}}),getResourceRowHref:s=>n({resourceId:s.resourceId})})}function E5({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(es,{children:[o.jsx(es.Label,{children:e}),o.jsx(es.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(es.Error,{}):s?o.jsx(es.Loading,{}):i?r!=null?o.jsx(es.Change,{changePct:r,prevValue:n}):o.jsx(es.NoChange,{}):o.jsx(es.NoData,{})]})}function gus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function vus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function yus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function bus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function xus(){const{data:e,isLoading:t,isError:n}=m7t();return o.jsx(E5,{label:"Total Agent Runs",value:e?.value!=null?e.value.toLocaleString():null,prevValue:e?.previousValue!=null?e.previousValue.toLocaleString():void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function wus(){const{data:e,isLoading:t,isError:n}=yus();return o.jsx(E5,{label:"Total Model Cost",value:e?.cost!=null?Cg(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Cg(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function Sus(){const{data:e,isLoading:t,isError:n}=bus();return o.jsx(E5,{label:"Total Tokens",value:e?.value!=null?_c(e.value):null,prevValue:e?.previousValue!=null?_c(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function kus(){const{data:e,isLoading:t,isError:n}=vus();return o.jsx(E5,{label:"Total Threads",value:e?.value!=null?_c(e.value):null,prevValue:e?.previousValue!=null?_c(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Ous(){const{data:e,isLoading:t,isError:n}=gus();return o.jsx(E5,{label:"Total Resources",value:e?.value!=null?_c(e.value):null,prevValue:e?.previousValue!=null?_c(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function _us({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>Cus(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(MNe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(PNe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Cus(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 Eus({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Cg(l):"—":c.size===1?u=l>0?Cg(l,[...c][0]):"—":u="Mixed",o.jsx(Wt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Wt.Actions,{children:s}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load model usage data"}):o.jsx(Wt.Content,{children:i?o.jsxs(ve,{columns:"auto auto auto auto auto auto",...Yye,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Model"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:l.model}),o.jsx(ve.NumberCell,{children:l.input}),o.jsx(ve.NumberCell,{children:l.output}),o.jsx(ve.NumberCell,{children:l.cacheRead}),o.jsx(ve.NumberCell,{children:l.cacheWrite}),o.jsx(ve.NumberCell,{highlight:!0,children:l.cost!=null?Cg(l.cost,l.costUnit):"—"})]});return c?o.jsx(ve.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(ve.RowStatic,{children:u},l.model)})]}):o.jsx(Wt.NoData,{message:"No model usage data yet"})})]})}function jus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>C5(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",p=c(f);p.input=d.value,u(p,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",p=c(f);p.output=d.value,u(p,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:_c(f.input),output:_c(f.output),cacheRead:_c(f.cacheRead),cacheWrite:_c(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function Tus(){const{data:e,isLoading:t,isError:n}=jus(),{getTracesHref:r}=YI(),{Link:s}=bn();return o.jsx(Eus,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:_s.AGENT}),actions:o.jsx(_5,{href:r({rootEntityType:_s.AGENT}),LinkComponent:s})})}function Nus(e){return e==="tokens"||e==="cost"}function Ius({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,S)=>b+S.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,v=h?f.reduce((b,S)=>b+(S.cost??0),0):0,y=h&&v>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Wt.Summary,{value:Cg(v,m),label:"Total cost"}):o.jsx(Wt.Summary,{value:_c(d),label:"Total tokens"})),u&&s?o.jsx(Wt.Actions,{children:s}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load token usage data"}):o.jsx(Wt.Content,{children:u?o.jsxs(Lc,{defaultTab:"tokens",value:i,onValueChange:b=>{Nus(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Dc,{children:[o.jsx(Rr,{value:"tokens",children:"Tokens"}),o.jsx(Rr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(NN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Fp.blueDark},{label:"Output",color:Fp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:_c})}),o.jsx(Xr,{value:"cost",children:y?o.jsx(NN,{LinkComponent:a,data:f.slice().sort((b,S)=>(S.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:Fp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Cg(b,m)}):o.jsx(Wt.NoData,{message:"No cost data yet"})})]}):o.jsx(Wt.NoData,{message:"No token usage data yet"})})]})}function Aus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>C5(i,u,()=>({input:0,output:0,cost:null,costUnit:null})),c=(u,d)=>{d.estimatedCost!=null&&(u.cost=(u.cost??0)+d.estimatedCost,d.costUnit&&(u.costUnit=d.costUnit))};for(const u of s.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.input=u.value,c(f,u)}for(const u of a.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(i.entries()).map(([u,d])=>({name:u,input:d.input,output:d.output,total:d.input+d.output,cost:d.cost,costUnit:d.costUnit})).sort((u,d)=>d.total-u.total)}})}function Rus(){const{data:e,isLoading:t,isError:n}=Aus(),{getTracesHref:r}=YI(),{Link:s}=bn();return o.jsx(Ius,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:_s.AGENT,entityName:a.name}),actions:o.jsx(_5,{href:r({rootEntityType:_s.AGENT}),LinkComponent:s})})}function rbe(e,t=_c){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const Pus=[{dataKey:"input",label:"Input tokens",color:Fp.blue,aggregate:rbe("input")},{dataKey:"output",label:"Output tokens",color:Fp.yellow,aggregate:rbe("output")}];function $us(e){return e==="tokens"||e==="cost"}function Mus({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,_)=>k+_.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),p=f.map(k=>({...k})),h=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=h.size===1&&f.every(k=>k.costUnit!=null),v=m?[...h][0]??null:null,y=m?f.reduce((k,_)=>k+(_.cost??0),0):0,b=m&&y>0,S=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",x=[{dataKey:"cost",label:"Cost",color:Fp.purple,aggregate:rbe("cost",k=>Cg(k,v))}];return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Token usage over time",description:S}),u&&(a==="cost"&&b?o.jsx(Wt.Summary,{value:Cg(y,v),label:"Total cost"}):o.jsx(Wt.Summary,{value:_c(d),label:"Total tokens"})),u&&s?o.jsx(Wt.Actions,{children:s}):null]}),n?o.jsx(Wt.Loading,{}):r?o.jsx(Wt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Wt.Content,{children:u?o.jsxs(Lc,{defaultTab:"tokens",value:a,onValueChange:k=>{$us(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(Dc,{children:[o.jsx(Rr,{value:"tokens",children:"Tokens"}),o.jsx(Rr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(kV,{data:c,series:Pus})}),o.jsx(Xr,{value:"cost",children:b?o.jsx(kV,{data:p,series:x}):o.jsx(Wt.NoData,{message:"No cost data yet"})})]}):o.jsx(Wt.NoData,{message:"No token usage data yet"})})]})}function Dus(e){return e==="24h"?"1h":"1d"}function Lus(e,t){return t==="1h"?e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):e.toLocaleDateString("en-US",{month:"short",day:"2-digit"})}function fXe(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const a=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};a[n]+=r.value,r.estimatedCost!=null&&(a.cost=(a.cost??0)+r.estimatedCost,t?.costUnit?a.costUnits.add(t.costUnit):a.hasUnknownCostUnit=!0),e.set(s,a)}}function Fus(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function zus(){const e=We(),{datePreset:t,filters:n,filterKey:r}=Im(),s=Dus(t);return yt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return fXe(l,a.series[0],"input"),fXe(l,i.series[0],"output"),{data:Array.from(l.values()).sort((u,d)=>u.tsMs-d.tsMs).map(u=>{const d=new Date(u.tsMs);return{time:Lus(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:Fus(u)}}),interval:s}}})}function Bus(){const{data:e,isLoading:t,isError:n}=zus(),{getTracesHref:r}=YI(),{Link:s}=bn();return o.jsx(Mus,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(_5,{href:r(),LinkComponent:s})})}function bae({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(NN,{LinkComponent:r,data:e.map(s=>{const a=n?.(s),i=t?.(s);return a?{name:s.name,values:[s.completed,s.errors],hrefs:[i,a]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:Fp.blueDark},{label:"Errors",color:Fp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:_c})}function Uus({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,p=m=>r?v=>r(m,v):void 0,h=m=>s?v=>s(m,v):void 0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Wt.Summary,{value:_c(f),label:"Total runs"}),u?o.jsx(Wt.Actions,{children:u}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load trace volume data"}):o.jsx(Wt.Content,{children:d?o.jsxs(Lc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Dc,{children:[o.jsx(Rr,{value:"agents",children:"Agents"}),o.jsx(Rr,{value:"workflows",children:"Workflows"}),o.jsx(Rr,{value:"tools",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:e.agentData.length>0?o.jsx(bae,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No agent data yet"})}),o.jsx(Xr,{value:"workflows",children:e.workflowData.length>0?o.jsx(bae,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No workflow data yet"})}),o.jsx(Xr,{value:"tools",children:e.toolData.length>0?o.jsx(bae,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No tool data yet"})})]}):o.jsx(Wt.NoData,{message:"No trace volume data yet"})})]})}async function xae(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const a of r.groups){const i=a.dimensions.entityName??"unknown",l=a.dimensions.status??"ok",c=C5(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=a.value:c.completed+=a.value}return Array.from(s.entries()).map(([a,i])=>({name:a,...i})).sort((a,i)=>i.completed+i.errors-(a.completed+a.errors))}function Vus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([xae(e,"mastra_agent_duration_ms",t),xae(e,"mastra_workflow_duration_ms",t),xae(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const Mz={agents:_s.AGENT,workflows:_s.WORKFLOW_RUN,tools:_s.TOOL};function qus(){const{data:e,isLoading:t,isError:n}=Vus(),{getTracesHref:r,getLogsHref:s}=YI(),{Link:a}=bn();return o.jsx(Uus,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:Mz[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:Mz[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(_5,{href:r({rootEntityType:Mz[i]}),LinkComponent:a}),o.jsx(nus,{href:s({rootEntityType:Mz[i],status:"error"}),LinkComponent:a})]})})}const wae="period",Dz="dateFrom",Lz="dateTo";function Hus(){const[e,t]=Pi(),n=e.get(wae),r=Hcs(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(Dz)),p=d(e.get(Lz));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=g.useMemo(()=>Lcs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(wae):p.set(wae,d),d!=="custom"&&(p.delete(Dz),p.delete(Lz)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(Dz,d.from.toISOString()):p.delete(Dz),d?.to?p.set(Lz,d.to.toISOString()):p.delete(Lz),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return zcs(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,Mcs(e)))return;const d=f7t();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(Zcs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(Wus,{})})}function Wus(){const[e]=Pi(),{error:t,isLoading:n}=m7t(),{filterTokens:r,setFilterTokens:s}=HG(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=tus(),{data:d,isLoading:f}=ZNe(),{data:p,isLoading:h}=qNe(),{data:m,isLoading:v}=WNe(),{data:y,isLoading:b}=HNe(),S=g.useMemo(()=>Dcs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:v,environments:b}}),[d,p,m,y,f,h,v,b]),[x,k]=g.useState(()=>f7t()!==null),_=g.useCallback(()=>{Pcs(e),k(!0),De.success("Filters setting for Metrics saved")},[e]),C=g.useCallback(()=>{$cs(),k(!1),De.success("Filters setting for Metrics cleared up")},[]),E=g.useCallback(()=>{s([])},[s]),j=g.useCallback(()=>{const T=r.map(I=>{const A=S.find(R=>R.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(T)},[S,r,s]);return t&&ys(t)?o.jsx(lr,{children:o.jsx(Ws,{})}):t&&xs(t)?o.jsx(lr,{children:o.jsx(Ds,{resource:"metrics"})}):t?o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Ft,{width:"wide",height:"full",children:[o.jsxs(Ft.TopArea,{children:[o.jsx(Ft.Row,{children:o.jsxs(Ft.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Kcs,{}),o.jsx(DNe,{fields:S,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(_us,{isLoading:n,filterFields:S,filterTokens:r,onFilterTokensChange:s,onClear:j,onRemoveAll:E,onSave:_,onRemoveSaved:x?C:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid gap-8 content-start pb-10",children:[c&&o.jsx(En,{variant:"info",title:"Metrics are not persisted",children:o.jsx(En.Message,{children:"This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner."})}),o.jsxs(Kye,{children:[o.jsx(xus,{}),o.jsx(wus,{}),o.jsx(Sus,{}),o.jsx(kus,{}),o.jsx(Ous,{})]}),o.jsxs(Kye,{children:[o.jsx(Tus,{}),o.jsx(Rus,{}),o.jsx(Bus,{}),o.jsx(mus,{}),o.jsx(qus,{}),o.jsx(uus,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zr,{iconSlot:o.jsx(If,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(ka,{})]})})})]})}function Zus(){const{paths:e}=bn(),{data:t,isLoading:n,error:r}=I8t(),{isCmsAvailable:s}=tS(),[a,i]=g.useState(""),l=t?.promptBlocks??[];return r&&ys(r)?o.jsx(lr,{children:o.jsx(Ws,{})}):r&&xs(r)?o.jsx(lr,{children:o.jsx(Ds,{resource:"prompt blocks"})}):r?o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load prompt blocks",message:r.message})}):l.length===0&&!n?o.jsx(lr,{children:o.jsx(MJr,{})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx($f,{onSearch:i,label:"Filter prompts",placeholder:"Filter by name or description"})}),s&&o.jsxs(le,{as:ti,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Zr,{}),"Create Prompt"]})]})}),o.jsx($Jr,{promptBlocks:l,isLoading:n,search:a})]})}function Gus(){return o.jsx(Ft,{width:"narrow",children:o.jsx(Ft.MainArea,{children:o.jsx(yYr,{children:o.jsx(Eye,{})})})})}const Qus=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:Upn,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:cdt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:ka,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:mT,href:"https://discord.gg/BTYqqHKUrf",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:vdt,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:udt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Yus(){return o.jsx(Ft,{width:"narrow",children:o.jsx(Ft.MainArea,{children:o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 max-w-3xl",children:Qus.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group flex flex-col gap-3 rounded-lg border border-border1 bg-surface2 p-5 transition-colors hover:border-accent1 hover:bg-surface3",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"h-5 w-5 text-icon3 group-hover:text-accent1 transition-colors"}),o.jsx("span",{className:"text-ui-md font-medium text-text1",children:e.title}),e.external&&o.jsx(ka,{className:"h-3.5 w-3.5 text-icon3 ml-auto opacity-0 group-hover:opacity-100 transition-opacity"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function Kus(){const{data:e={},isLoading:t,error:n}=ih(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&ys(n))return o.jsx(lr,{children:o.jsx(Ws,{})});if(n&&xs(n))return o.jsx(lr,{children:o.jsx(Ds,{resource:"scorers"})});if(n)return o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(lr,{children:o.jsx(HKr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(ZKr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(qKr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Xus(){const{scorerId:e}=Sr(),[t,n]=Pi(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=wKr(e),{data:d={},isLoading:f,error:p}=Em(),{isLoading:h,error:m}=Hy(),{data:v=[],isLoading:y,error:b,isFetchingNextPage:S,hasNextPage:x,setEndOfListElement:k}=xKr({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),_=g.useMemo(()=>c?.agentIds?.filter(q=>d[q]).map(q=>({value:q,label:d[q].name,type:"AGENT"}))||[],[c?.agentIds,d]),C=g.useMemo(()=>c?.workflowIds?.map(q=>({value:q,label:q,type:"WORKFLOW"}))||[],[c?.workflowIds]),E=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},..._,...C],[_,C]),j=t.get("entity")??"all",T=E.find(q=>q.value===j);T&&T.value!==i?.value&&l(T),g.useEffect(()=>{if(u){const q=u instanceof Error?u.message:"Failed to load scorer";De.error(`Error loading scorer: ${q}`)}},[u]),g.useEffect(()=>{if(p){const q=p instanceof Error?p.message:"Failed to load agents";De.error(`Error loading agents: ${q}`)}},[p]),g.useEffect(()=>{if(m){const q=m instanceof Error?m.message:"Failed to load workflows";De.error(`Error loading workflows: ${q}`)}},[m]);const I=q=>{q?.value&&n(D=>{const G=new URLSearchParams(D);return G.set("entity",q.value),G})};g.useEffect(()=>{const q=t.get("scoreId")??void 0;if(q===s)return;if(!q){a(void 0);return}v.find(G=>G.id===q)&&a(q)},[t,v]);const A=g.useCallback(q=>{a(q||void 0),n(D=>{const G=new URLSearchParams(D);return q?G.set("scoreId",q):G.delete("scoreId"),G})},[n]);if(!c)return null;const R=ys(u)||ys(p)||ys(m),L=u&&xs(u),M=!R&&!L&&(u||p||m),z=!y&&v.length===0,H=i?.value!=="all",F=c?.scorer?.source==="stored"?o.jsx($y,{owner:"scorer-detail",children:o.jsxs(le,{variant:"default",as:ti,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(om,{})," Edit"]})}):null;if(R||L||M||z&&!H){const q=(u instanceof Error?u.message:void 0)??(p instanceof Error?p.message:void 0)??(m instanceof Error?m.message:void 0)??"An unexpected error occurred";return o.jsxs(Ft,{width:"wide",height:"full",children:[F,o.jsx(Ft.MainArea,{isCentered:!0,children:R?o.jsx(Ws,{}):L?o.jsx(Ds,{resource:"scorers"}):M?o.jsx(Hi,{title:"Failed to load scorer",message:q}):o.jsx(mKr,{})})]})}return o.jsxs(Ft,{width:"wide",children:[F,o.jsx(Ft.TopArea,{children:o.jsx(gKr,{selectedEntity:i,entityOptions:E,onEntityChange:I,onReset:()=>{n(q=>{const D=new URLSearchParams(q);return D.set("entity","all"),D})},isLoading:y||f||h})}),o.jsx(hKr,{scores:v,isLoading:y,selectedScoreId:s,isFetchingNextPage:S,hasNextPage:x,setEndOfListElement:k,onScoreClick:A,errorMsg:b?.message})]})}function Jus({label:e,description:t,htmlFor:n,className:r,children:s}){return o.jsxs("div",{className:X("flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",r),"data-slot":"settings-row",children:[o.jsxs("div",{children:[n?o.jsx(Dt,{htmlFor:n,className:"text-sm font-medium",children:e}):o.jsx("p",{className:"text-sm font-medium",children:e}),t&&o.jsx("p",{className:"text-sm text-neutral3",children:t})]}),s]})}const b7t=[{value:"dark",label:"Dark",Icon:wmn},{value:"light",label:"Light",Icon:Rgn},{value:"system",label:"System",Icon:Odt}],eds=e=>b7t.some(t=>t.value===e);function tds({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-2",children:[o.jsx(t,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 opacity-70"}),o.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const nds=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=Lq(),{theme:r,setTheme:s}=q_();return o.jsx(Ft,{width:"narrow",children:o.jsxs(Ft.MainArea,{className:"flex flex-col gap-5 mt-6",children:[o.jsx(uye,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(Jus,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(la,{value:r,onValueChange:a=>{eds(a)&&s(a)},children:[o.jsx(ua,{id:"theme",className:"w-full sm:w-48",children:o.jsx(ca,{className:"inline-flex min-w-0 max-w-full items-center"})}),o.jsx(da,{children:b7t.map(a=>o.jsx(Ar,{value:a.value,children:o.jsx(tds,{option:a})},a.value))})]})})}),o.jsx(uye,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(xMt,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function rds(){const[e]=Pi(),t=Hs(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(c7t,{redirectUri:n,onSuccess:r,initialMode:"signup"})}const x7t=e=>o.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("g",{clipPath:"url(#clip0_21999_22095)",children:o.jsx("path",{d:"M7.5 0.75C3.6325 0.75 0.5 3.8825 0.5 7.75C0.5 10.8475 2.50375 13.4637 5.28625 14.3912C5.63625 14.4525 5.7675 14.2425 5.7675 14.0587C5.7675 13.8925 5.75875 13.3412 5.75875 12.755C4 13.0787 3.545 12.3262 3.405 11.9325C3.32625 11.7312 2.985 11.11 2.6875 10.9437C2.4425 10.8125 2.0925 10.4887 2.67875 10.48C3.23 10.4712 3.62375 10.9875 3.755 11.1975C4.385 12.2562 5.39125 11.9587 5.79375 11.775C5.855 11.32 6.03875 11.0137 6.24 10.8387C4.6825 10.6637 3.055 10.06 3.055 7.3825C3.055 6.62125 3.32625 5.99125 3.7725 5.50125C3.7025 5.32625 3.4575 4.60875 3.8425 3.64625C3.8425 3.64625 4.42875 3.4625 5.7675 4.36375C6.3275 4.20625 6.9225 4.1275 7.5175 4.1275C8.1125 4.1275 8.7075 4.20625 9.2675 4.36375C10.6062 3.45375 11.1925 3.64625 11.1925 3.64625C11.5775 4.60875 11.3325 5.32625 11.2625 5.50125C11.7087 5.99125 11.98 6.6125 11.98 7.3825C11.98 10.0687 10.3438 10.6637 8.78625 10.8387C9.04 11.0575 9.25875 11.4775 9.25875 12.1337C9.25875 13.07 9.25 13.8225 9.25 14.0587C9.25 14.2425 9.38125 14.4612 9.73125 14.3912C11.1209 13.9221 12.3284 13.029 13.1839 11.8377C14.0393 10.6463 14.4996 9.21668 14.5 7.75C14.5 3.8825 11.3675 0.75 7.5 0.75Z",fill:"currentColor"})}),o.jsx("defs",{children:o.jsx("clipPath",{id:"clip0_21999_22095",children:o.jsx("rect",{width:"14",height:"14",fill:"currentColor",transform:"translate(0.5 0.75)"})})})]});function sds(e){return e.replace(/\/$/,"").split("/").pop()}function WG({children:e,className:t}){return o.jsx("div",{className:X("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function ads({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:X("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"h-16 bg-surface3 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:X("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:X("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:X("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:X("overflow-hidden"),children:o.jsx("div",{className:"w-full h-full bg-cover thumb transition-scale duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:X("grid py-3 px-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"hidden 2xl:flex text-neutral3 text-ui-md flex-wrap items-center gap-4 mt-3",children:[i&&o.jsxs("ul",{className:X("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Vo,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Ld,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(_dt,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(zD,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(bC,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"flex items-center text-neutral3 gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:X("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"flex items-center gap-2 px-2 py-1 rounded bg-surface1 group-hover:bg-surface2 text-neutral3 transition-colors group-hover:text-neutral5",children:[o.jsx(x7t,{})," ",sds(a.githubUrl)]})})]},a.slug)})})}function ids({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:X("h-[6.5rem] flex items-center gap-8","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:X("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(mN,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Ec,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Ec,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(le,{onClick:c,children:["Reset ",o.jsx(bs,{})]})]})}function ods(){const{data:e,isLoading:t}=ker(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(S=>{f.push({value:S,label:S})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(S=>{p.push({value:S,label:S})});const h=(S,x)=>{x==="tag"?i(S):x==="provider"&&c(S)},m=S=>{d(S)},v=()=>{i("all"),c("all"),d("")},y=n.filter(S=>!(u&&!S.title.toLowerCase().includes(u)&&!S.description.toLowerCase().includes(u)||a!=="all"&&!S.tags.includes(a)||l!=="all"&&!S.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(ds,{children:[o.jsx(ywe,{children:o.jsxs(bgt,{children:[o.jsx(qe,{children:o.jsx(Kv,{})}),"Templates"]})}),o.jsxs("div",{className:X("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(ids,{selectedTag:a,onTagChange:S=>h(S,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:S=>h(S,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(ads,{templates:y,linkComponent:ti,className:"max-w-[80rem] mx-auto",isLoading:t})]})]})}const lds="1.52.2-alpha.0";function cds({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(yf,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(vhn,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(WG,{className:"space-y-4 text-neutral3 mb-8 content-center",children:[o.jsxs("div",{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"text-center space-y-2",children:[o.jsx("p",{className:"text-ui-md font-medium text-neutral5",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-xs",children:[o.jsxs("summary",{className:"cursor-pointer text-neutral3 hover:text-neutral4 select-none text-center",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 p-3 bg-gray-100 dark:bg-gray-800 rounded text-xs overflow-auto max-h-60 text-left space-y-2",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"text-xs font-mono text-gray-700 dark:text-gray-300 mt-1 whitespace-pre-wrap wrap-break-word",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"cursor-pointer text-neutral3 hover:text-neutral4 select-none text-center",children:"Show Details"}),o.jsx("div",{className:"mt-4 p-3 bg-gray-100 dark:bg-gray-800 rounded text-xs font-mono overflow-auto max-h-60 text-left",children:o.jsx("div",{className:"whitespace-pre-wrap wrap-break-word",children:n})})]})]})}function uds({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:a,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(WG,{children:o.jsxs("div",{className:"max-w-[40rem] my-4 p-4 lg:p-8 mx-auto gap-8 grid",children:[o.jsxs("h2",{className:X("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(Cdt,{})]}),o.jsx(Ec,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] gap-4 items-start",children:l?o.jsxs("div",{className:X("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(Kt,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(g.Fragment,{children:[o.jsx(TO,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(TO,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),o.jsxs("div",{className:"border-t border-border1 pt-12 mt-3.5 relative",children:[o.jsx("div",{className:"absolute w-8 h-8 rounded-full bg-surface2 top-0 left-1/2 -translate-x-1/2 -translate-y-4 text-ui-sm text-neutral3 flex items-center justify-center",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-lg",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-8",children:"This model will be used by the workflow to process and install the template"}),o.jsx(o8t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(le,{className:X("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(Kt,{className:"w-4 h-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(bm,{})]})})]})})}function dds({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:X("grid mt-8 items-center"),children:o.jsxs("div",{className:X("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(Kv,{}),o.jsx("h2",{className:X({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid lg:grid-cols-[1fr_1fr] gap-x-24",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:X("mb-4 text-ui-md text-neutral4 mt-2 leading-7",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:X("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"shrink-0 mt-0.5",children:o.jsx(Vx,{className:"w-[1.1em] h-[1.1em] text-blue-500"})}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(wxe,{className:"w-[1em] h-[1em] text-neutral4"}),o.jsx("span",{className:"text-ui-md font-medium text-neutral5",children:"A new Git branch will be created"})]}),o.jsxs("div",{className:"text-ui-sm text-neutral4 space-y-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-medium",children:"Branch name:"})," ",o.jsx("code",{className:"bg-surface3 px-1.5 py-0.5 rounded text-ui-sm font-mono",children:i})]}),o.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&o.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 mt-auto text-neutral3 text-ui-md hover:text-neutral5",children:[o.jsx(x7t,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(gNe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function fds(e){switch(e){case"running":return o.jsx(Kt,{});case"success":return o.jsx(wx,{});case"failed":return o.jsx(Hu,{});default:return null}}function pds({stepId:e,step:t,isActive:n,position:r}){const s=a=>a.charAt(0).toUpperCase()+a.slice(1).replace(/-/g," ");return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3",vs.all,{"border border-dashed border-neutral2 bg-surface3":n}),children:[o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:X("flex min-w-6 justify-end text-ui-md",vs.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:[r,"."]}),o.jsxs("div",{children:[o.jsx("h4",{className:X("text-ui-md",vs.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:s(e)}),t.description&&o.jsx("p",{className:"-mt-0.5 text-ui-md text-neutral2",children:t.description})]})]}),o.jsx("div",{className:X("flex size-[1.75rem] items-center justify-center self-center rounded-full",vs.all,{"border border-neutral2 border-dashed":t.status==="pending","[&>svg]:text-white [&>svg]:w-4 [&>svg]:h-4":t.status!=="running","w-[1.75rem] h-[1.75rem]":t.status==="running","bg-accent1Dark shadow-glow-accent1":t.status==="success","bg-accent2Dark shadow-glow-accent2":t.status==="failed","scale-110":t.status==="success"||t.status==="failed"}),children:fds(t.status)})]})}function hds({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:X(n),children:t.map((r,s)=>o.jsx(pds,{stepId:r.id,step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function mds({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[o.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>o.jsx("div",{className:X("relative flex h-8 items-center justify-end",vs.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:X("absolute right-0 z-10 flex size-[2rem] translate-x-[50%] items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3",vs.all,{"border border-neutral2 border-dashed":r.status==="pending","[&>svg]:text-surface1 [&>svg]:w-[1.1rem] [&>svg]:h-[1.1rem]":r.status!=="running","bg-accent1Dark text-white shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-white shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Kt,{}):s+1})},r.id))}),o.jsxs("div",{className:X("text-center text-xs text-neutral3",vs.colors),children:[n," of ",t," steps completed"]})]})}function gds({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),p=f.length,h=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(WG,{className:"space-y-6 text-neutral3 mb-8 content-center",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-lg font-semibold text-neutral5",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"mt-2 text-ui-sm text-neutral3",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"max-w-[30rem] w-full mx-auto px-6",children:o.jsx(mds,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:X("rounded-lg text-neutral5 p-6 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(Imn,{}),l||"Something went wrong"]}),u&&o.jsx(hds,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-center text-sm text-neutral3 grid gap-4 justify-items-center",children:[o.jsx(Kt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function vds({name:e,installedEntities:t}){return o.jsxs(WG,{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Cdt,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-center text-neutral3 ",children:["The ",o.jsx("b",{className:"text-neutral4",children:e})," template has been successfully installed.",t&&t.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&o.jsx(gNe,{data:t})]})}function yds(){const{templateSlug:e}=Sr(),[t,n]=Pi(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,p]=g.useState([]),[h,m]=g.useState(null),[v,y]=g.useState(!1),[b,S]=g.useState(""),[x,k]=g.useState(!1),[_,C]=g.useState(!1),[E,j]=g.useState([]),{data:T,isLoading:I}=Oer({repoOrSlug:e,owner:"mastra-ai"}),R=lds?.includes("beta")??!1?"beta":"main",{data:L,isLoading:M}=_er({repo:T?.githubUrl?new URL(T.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:z,isLoading:H}=Cer(),{mutateAsync:F,isPending:B}=Eer(),{mutateAsync:q}=jer(),{streamInstall:D,streamResult:G,isStreaming:V}=Ner(z),{observeInstall:$,streamResult:U,isStreaming:Z}=Ier(z);g.useEffect(()=>{const ee=t.get("runId");ee&&!v&&!h&&!V&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:ee}),S(ee),q({runId:ee}).then(ce=>{const de=ce.snapshot;if(de?.status==="success"&&de?.result?.success)y(!0);else if(de?.result?.success===!1)if(de?.result?.validationResults&&!de?.result?.validationResults?.valid&&de?.result?.validationResults?.remainingErrors>0){const{remainingErrors:me,errors:be}=de.result.validationResults,we=`Template installation completed but ${me} validation issue${me>1?"s":""} remain unresolved.`;m(we),j(be||[])}else{const me=de?.result?.message||de?.result?.error||"Template installation failed";m(typeof me=="string"?me:String(me))}}).catch(ce=>{console.error("❌ Failed to fetch run details:",ce),m("Failed to retrieve installation status after reload")}))},[t,v,h,V,Z,q]),g.useEffect(()=>{const ee=t.get("runId"),ce=t.get("resume"),de=t.get("provider");if(ee&&ce==="true"&&de&&!V&&!Z&&!x&&!_&&z){S(ee),k(!0);try{q({runId:ee}).then(oe=>{if(oe.snapshot?.status==="running")return $.mutateAsync({runId:ee})}).then(()=>{n(oe=>{const me=new URLSearchParams(oe);return me.delete("resume"),me})}).catch(oe=>{console.error("❌ Failed to resume template installation:",oe),oe.message?.includes("404")||oe.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(oe){console.error("❌ Auto-resume failed with error:",oe),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,V,Z,x,_,z,q,$,n]);const K=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],ne=[{key:"tools",label:"Tools",value:T?.tools?.length?T.tools.map(ee=>ee).join(", "):"n/a",icon:o.jsx(Ld,{})},{key:"agents",label:"Agents",value:T?.agents?.length?T.agents.map(ee=>ee).join(", "):"n/a",icon:o.jsx(Vo,{})},{key:"workflows",label:"Workflows",value:T?.workflows?.length?T.workflows.map(ee=>ee).join(", "):"n/a",icon:o.jsx(zD,{})},{key:"providers",label:"Providers",value:T?.supportedProviders?.length?T.supportedProviders.join(", "):"n/a",icon:o.jsx(Dv,{})},{key:"tags",label:"Tags",value:T?.tags?.length?T.tags.join(", "):"n/a",icon:o.jsx(BN,{})}],te=[{...ne[0]},{...ne[1]},{...ne[2]}].filter(ee=>ee.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const ee=G||U;ee?.phase==="error"&&ee?.error&&m(typeof ee.error=="string"?ee.error:String(ee.error))},[G?.phase,G?.error,U?.phase,U?.error]);const J=ee=>{s(ee)},ae=async ee=>(i(ee.provider),c(ee.modelId),{message:"Model updated successfully"}),pe=async()=>{const ee=Object.entries(u).reduce((ce,[de,oe])=>(oe===""&&ce.push(de),ce),[]);if(ee.length>0){p(ee);return}if(T){m(null),y(!1),S(""),C(!0);try{const de={repo:T.githubUrl||`https://github.com/mastra-ai/template-${T.slug}`,ref:R,slug:T.slug,variables:u},{runId:oe}=await F({});S(oe),n(me=>{const be=new URLSearchParams(me);return be.set("runId",oe),be.set("resume","true"),be.set("provider",r||"openai"),be}),await D.mutateAsync({inputData:de,selectedModel:{provider:a,modelId:l},runId:oe})}catch(ce){C(!1),m(ce?.message||"Template installation failed"),console.error("Template installation failed",ce)}}},Y=ee=>{const{name:ce,value:de}=ee.target;de.trim()===""?p(oe=>[...oe,ce]):p(oe=>oe.filter(me=>me!==ce)),d(oe=>({...oe,[ce]:de}))};return o.jsx(ds,{children:o.jsx("div",{className:X("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"p-6 w-full max-w-[80rem] mx-auto grid gap-y-4",children:[o.jsx(dds,{isLoading:I,title:T?.title,description:T?.longDescription,imageURL:T?.imageURL,githubUrl:T?.githubUrl,infoData:ne,templateSlug:e}),T&&o.jsxs(o.Fragment,{children:[(V||Z)&&o.jsx(gds,{name:T.title,streamResult:Z?U:G,runId:b,workflowInfo:z}),v&&o.jsx(vds,{name:T.title,installedEntities:te,linkComponent:ti}),h&&o.jsx(cds,{errorMsg:h,validationErrors:E.length>0?E:G?.validationResults?.errors||U?.validationResults?.errors}),!V&&!Z&&!v&&!h&&o.jsx(uds,{providerOptions:K,selectedProvider:r,onProviderChange:J,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:pe,handleVariableChange:Y,isLoadingEnvVars:M||H,isInstalling:B,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const bds=()=>{const{toolId:e,agentId:t}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(JXr,{toolId:e,agentId:t})})},xds=()=>{const{toolId:e}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(Ocs,{toolId:e})})};function wds(){const{traceId:e}=Sr(),[t,n]=Pi(),r=Hs(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=g.useState(s??null),[d,f]=g.useState(),[p,h]=g.useState(i),[m,v]=g.useState(0),[y,b]=g.useState(!1),{data:S,isLoading:x,error:k}=GNe(e),_=g.useMemo(()=>S?.spans??[],[S?.spans]),C=g.useMemo(()=>_.find(ae=>ae.parentSpanId==null),[_]),{data:E,isLoading:j}=k5(e,c??"");g.useEffect(()=>v(0),[e,c]);const{data:T,isLoading:I}=ih(),{data:A,isLoading:R}=C8t({traceId:e,spanId:c??void 0,page:m}),[L,M]=g.useState(0);g.useEffect(()=>M(0),[e,c]);const{data:z,isLoading:H}=X9t({traceId:e,page:L});g.useEffect(()=>{if(l&&A?.scores&&!d){const ae=A.scores.find(pe=>pe.id===l);ae&&f(ae)}},[l,A?.scores,d]);const F=g.useCallback(ae=>{const pe=new URLSearchParams(t);for(const[Y,ee]of Object.entries(ae))ee===null||ee===""?pe.delete(Y):pe.set(Y,ee);n(pe,{replace:!0})},[t,n]),B=g.useCallback(ae=>{const pe=ae??null,Y=pe===c;u(pe),Y||(f(void 0),h("details"),F({spanId:pe,tab:null,scoreId:null}))},[c,F]),q=g.useCallback(()=>{u(null),f(void 0),h("details"),F({spanId:null,tab:null,scoreId:null})},[F]),D=g.useCallback(ae=>{u(ae),f(void 0),h("details"),F({spanId:ae,tab:null,scoreId:null})},[F]),{handlePreviousSpan:G,handleNextSpan:V}=QNe(_,c,D),$=g.useCallback(ae=>{const pe=ae;h(pe),f(void 0),F({tab:pe==="details"?null:pe,scoreId:null})},[F]),U=g.useCallback(ae=>{f(ae),F({scoreId:ae.id})},[F]),Z=g.useCallback(()=>{f(void 0),F({scoreId:null})},[F]),K=g.useCallback(()=>{r("/observability")},[r]),ne=g.useCallback(()=>{h("scoring"),C&&c!==C.spanId?(u(C.spanId),f(void 0),F({spanId:C.spanId,tab:"scoring",scoreId:null})):F({tab:"scoring"})},[C,c,F]),te=C?o.jsx($y,{owner:"trace-detail",children:o.jsxs(Mr,{children:[o.jsxs(le,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:ne,children:[o.jsx(upn,{}),"Evaluate"]}),o.jsxs(le,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(jd,{}),"Save"]})]})}):null,J=C?o.jsx(Ft.Row,{children:o.jsx(Ft.Column,{children:o.jsx(D9t,{rootSpan:C,numOfCol:3})})}):null;return k?o.jsxs(Ft,{height:"full",children:[te,J&&o.jsx(Ft.TopArea,{children:J}),o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(U9t,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Ft,{height:"full",className:"grid-rows-[auto_minmax(0,1fr)] content-normal",children:[te,J&&o.jsx(Ft.TopArea,{children:J}),o.jsx(Z9t,{rootSpanId:C?.spanId,traceId:e,isOpen:y,onClose:()=>b(!1)}),o.jsxs("div",{className:X("mt-4 grid min-h-0 items-stretch gap-4 overflow-hidden",c?"grid-cols-[2fr_3fr]":"grid-cols-[1fr]"),children:[o.jsx(BNe,{traceId:e,spans:_,isLoading:x,onClose:K,onSpanSelect:B,onEvaluateTrace:ne,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!x&&o.jsxs("div",{className:X("grid h-full max-h-full min-h-0 gap-4 overflow-auto",d?"grid-rows-[1fr_1fr]":"grid-rows-[1fr]"),children:[o.jsx(LNe,{traceId:e,spanId:c,span:E?.span,isLoading:j,onClose:q,onPrevious:G,onNext:V,activeTab:p,onTabChange:$,feedbackTabBadge:z?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(Q9t,{feedbackData:z,onPageChange:M,isLoadingFeedbackData:H}),scoringTabBadge:A?.pagination?.total??void 0,scoringTabSlot:({span:ae,traceId:pe,spanId:Y})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(K9t,{traceId:pe,isTopLevelSpan:!ae.parentSpanId,spanId:Y,entityType:ae.attributes?.agentId||ae.entityType===_s.AGENT?"Agent":ae.attributes?.workflowId||ae.entityType===_s.WORKFLOW_RUN?"Workflow":void 0,scorers:T,isLoadingScorers:I}),o.jsx(Y9t,{scoresData:A,onPageChange:v,isLoadingScoresData:R,onScoreSelect:U})]})}),d&&o.jsx(mNe,{score:d,onClose:Z})]})]})]})}function Sds(){const{data:e,isLoading:t,error:n}=Hy(),[r,s]=g.useState("");return n&&ys(n)?o.jsx(lr,{children:o.jsx(Ws,{})}):n&&xs(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"workflows"})}):n?o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(lr,{children:o.jsx(D9r,{})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx($f,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(le,{as:ti,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(MD,{}),"Schedules"]})]})}),o.jsx(M9r,{workflows:e||{},isLoading:t,search:r})]})}const kds={active:"bg-accent1",paused:"bg-accent3"},Ods={active:"text-accent1",paused:"text-accent3"},w7t=({status:e})=>o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${kds[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${Ods[e]}`,children:e})]}),iT=e=>!e||e<=0?"—":new Date(e).toLocaleString(),PP=e=>{if(!e||e<=0)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.floor(n/1e3);if(r<60)return t>=0?`in ${r}s`:`${r}s ago`;const s=Math.floor(r/60);if(s<60)return t>=0?`in ${s}m`:`${s}m ago`;const a=Math.floor(s/60);if(a<24)return t>=0?`in ${a}h`:`${a}h ago`;const i=Math.floor(a/24);return t>=0?`in ${i}d`:`${i}d ago`};function S7t({status:e}){const{icon:t,color:n}=_ds(e);return o.jsxs("span",{className:`inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function _ds(e){switch(e){case"success":return{icon:o.jsx(pa,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(bs,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Kt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(YV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(If,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(hT,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const pXe="auto auto auto auto 1fr";function Cds(e){if(e===void 0)return"—";if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;const t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${t}m ${n}s`}function Eds(e){const t=Math.abs(e),n=e<0?"-":"";return t<1e3?`${n}${t}ms`:t<6e4?`${n}${(t/1e3).toFixed(1)}s`:t<36e5?`${n}${(t/6e4).toFixed(1)}m`:`${n}${(t/36e5).toFixed(1)}h`}const jds=3e4,Tds=5*6e4;function Nds({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=bn();return t?o.jsx(ll,{columns:pXe}):e.length===0?o.jsx(ye,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(ve,{columns:pXe,className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Run"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Started"}),o.jsx(ve.TopCell,{children:"Duration"}),o.jsx(ve.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=Eds(u),f=`Scheduled ${iT(c.scheduledFireAt)} — published ${iT(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),v=!p&&m>jds&&m<=Tds,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),S=o.jsx("span",{className:b?"text-accent1 font-mono text-ui-sm whitespace-nowrap":"text-neutral3 font-mono text-ui-sm whitespace-nowrap",children:c.runId}),x=o.jsxs(o.Fragment,{children:[o.jsx(ve.Cell,{height:"compact",children:S}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm text-accent2",children:[o.jsx(yf,{size:14}),"publish failed"]}):c.run?o.jsx(S7t,{status:c.run.status}):o.jsx("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm text-neutral3",children:"pending"}),h?o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(yf,{size:14})})}),o.jsx($n,{children:h})]}):null]})}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:PP(c.actualFireAt)}),v?o.jsxs(Ln,{children:[o.jsx(Pn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(yf,{size:14})})}),o.jsxs($n,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(ve.Cell,{height:"compact",children:c.run?o.jsx("span",{children:Cds(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(ve.Cell,{height:"compact",children:" "})]});return b?o.jsx(ve.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:x},y):o.jsx(ve.RowStatic,{children:x},y)}),o.jsx(ve.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const Ids=e=>{const t=We();return yt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},hXe=25,Ads=e=>{const t=We(),{inView:n,setRef:r}=Q_(),s=F1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:hXe,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<hXe))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},Rds=e=>{const t=We(),n=Ur();return Rn({mutationFn:async r=>{if(!e)throw new Error("scheduleId is required");return r==="pause"?t.pauseSchedule(e):t.resumeSchedule(e)},onSuccess:(r,s)=>{n.invalidateQueries({queryKey:["schedule",e]}),n.invalidateQueries({queryKey:["schedules"]}),De.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{De.error(r.message)}})};function Fz({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 uppercase tracking-wide",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function Pds(){const{scheduleId:e}=Sr(),{paths:t}=bn(),{data:n,error:r}=Ids(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=Ads(e),d=Rds(e);if(r&&ys(r))return o.jsx(lr,{children:o.jsx(Ws,{})});if(r&&xs(r))return o.jsx(lr,{children:o.jsx(Ds,{resource:"schedules"})});if(r)return o.jsx(lr,{children:o.jsx(Hi,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(Ft.Row,{className:"justify-end",children:o.jsxs(Ft.Column,{className:"flex justify-end gap-2",children:[o.jsxs(le,{as:ti,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(Rc,{}),"Back to schedules"]}),f?o.jsx(le,{as:ti,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(le,{onClick:()=>d.mutate(n.status==="active"?"pause":"resume"),disabled:d.isPending,"data-testid":"schedule-toggle-button",children:n.status==="active"?o.jsxs(o.Fragment,{children:[o.jsx(Oxe,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Ef,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid gap-6 h-full overflow-hidden grid-cols-[minmax(0,20rem)_1fr]",children:[o.jsxs("div",{className:"flex flex-col gap-4 border border-border1 rounded-md p-4 h-fit",children:[o.jsx(Fz,{label:p?"Agent":"Workflow",children:f?o.jsx(ti,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(ti,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(Fz,{label:"Cron",children:[o.jsx("code",{className:"font-mono text-ui-md",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 ml-2 text-ui-sm",children:n.timezone}):null]}),o.jsx(Fz,{label:"Status",children:o.jsx(w7t,{status:n.status})}),o.jsx(Fz,{label:"Next fire",children:o.jsx("span",{title:iT(n.nextFireAt),children:PP(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ye,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Hi,{title:"Failed to load trigger history",message:i.message}):o.jsx(Nds,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const mXe="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function $ds({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=bn(),a=g.useMemo(()=>{const i=n.toLowerCase();return i?e.filter(l=>l.id.toLowerCase().includes(i)||(l.workflowId??l.agentId??"").toLowerCase().includes(i)):e},[e,n]);return t?o.jsx(ll,{columns:mXe}):o.jsxs(ve,{columns:mXe,variant:"striped",className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Target"}),o.jsx(ve.TopCell,{children:"Schedule ID"}),o.jsx(ve.TopCell,{children:"Cron"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Next fire"}),o.jsx(ve.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(ve.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(ve.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(ve.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(ve.NameCell,{children:i.workflowId??i.agentId}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"block truncate font-mono text-ui-smd text-neutral3",title:i.id,children:i.id})}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"font-mono text-ui-sm",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(ve.Cell,{height:"compact",children:o.jsx(w7t,{status:i.status})}),o.jsx(ve.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:iT(i.nextFireAt),children:PP(i.nextFireAt)})}),o.jsx(ve.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(S7t,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:iT(i.lastFireAt),children:i.lastFireAt?PP(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:iT(i.lastFireAt),children:PP(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function Mds({workflowId:e}={}){const{data:t,isLoading:n,error:r}=gwe(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(Hi,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid grid-rows-[auto_1fr] gap-4 h-full overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx($f,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx($ds,{schedules:t??[],isLoading:n,search:s})})]})}function Dds(){const[e]=Pi(),t=e.get("workflowId")??void 0,{error:n}=gwe(t?{workflowId:t}:{});return n&&ys(n)?o.jsx(lr,{children:o.jsx(Ws,{})}):n&&xs(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"schedules"})}):o.jsx(Ft,{children:o.jsx("div",{className:"h-full",children:o.jsx(Mds,{workflowId:t})})})}function Lds({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=GSe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=KSt(r),[d]=XSt(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=o4t({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"w-full h-full relative bg-surface1",children:a?o.jsxs(YSt,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(qEe,{position:"bottom-left"}),o.jsx(ekt,{variant:sy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"w-full h-full flex items-center justify-center",children:o.jsx(Kt,{})})})}function Fds(){const{stepDetail:e,closeStepDetail:t}=RH();return e?o.jsxs("div",{className:"flex flex-col h-full","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border1 bg-surface1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(F9,{className:"w-4 h-4",style:{color:ju.map}}),e.type==="nested-graph"&&o.jsx(Xu,{className:"w-4 h-4",style:{color:ju.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ye,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"p-1 hover:bg-surface3 rounded transition-colors","aria-label":"Close",children:o.jsx(bs,{className:"w-4 h-4 text-neutral3"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(AP,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(ZSe,{children:o.jsx(Lds,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function zds(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function Bds(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e);if(n.length===1)return n[0]}return t}function Uds({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"space-y-5 rounded-lg border border-border1 bg-surface4 p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ye,{as:"p",variant:"ui-md",className:"flex items-center gap-2 text-neutral6 font-semibold",children:[o.jsx(qe,{children:o.jsx(YV,{})}),"Step suspended"]}),o.jsx(un,{variant:"warning",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?fm(um(Sx(i.resumeSchema))):hp(ur(),jT());return o.jsx(Vds,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function Vds({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral6 font-medium truncate",children:e.stepId}),n&&o.jsx(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"flex items-center gap-2 text-neutral3",children:[o.jsx(qe,{children:o.jsx(kmn,{})}),"The step is asking"]}),o.jsxs(jf,{open:a,onOpenChange:i,children:[o.jsxs($d,{className:"flex w-full items-center justify-between gap-2 rounded-lg border border-border1 bg-surface3 px-3 py-2.5",children:[o.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[o.jsx(qe,{children:o.jsx(ha,{className:X("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ye,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:Bds(e.suspendPayload,e.stepId)})]}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:zds(e.suspendPayload)})]}),o.jsx(Md,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Wr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"flex items-center gap-2 text-neutral3",children:[o.jsx(qe,{children:o.jsx(Cmn,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(SB,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Ef,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:l=>{const c=e.stepId?.split(".");s({stepId:c,runId:e.runId,suspendPayload:e.suspendPayload,resumeData:l,isLoading:!1})}})})]})]})}function qds(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Ul),{runId:a}=Sr(),i=okt(e,r??""),l=BKn(),c=!!a,u=t?.status==="suspended",f=!!(a&&r&&a===r)&&e?.status==="suspended";return s||!n||i.length===0||c&&!u&&!f?null:o.jsx("div",{"data-testid":"workflow-suspended-overlay",className:"absolute top-2 right-2 z-20 w-[380px] max-w-[calc(100%-1rem)] max-h-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 duration-300",children:o.jsx(Uds,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const Hds=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.97865 4.57004C8.22604 4.75795 8.27426 5.11082 8.08635 5.35821L6.05486 8.03279C5.94873 8.17251 5.78348 8.25471 5.60803 8.25505C5.43257 8.2554 5.267 8.17385 5.16032 8.03454L3.80937 6.27034C3.6205 6.02369 3.66733 5.67063 3.91398 5.48176C4.16063 5.29288 4.51369 5.33972 4.70257 5.58637L5.6051 6.76498L7.19048 4.67774C7.37839 4.43036 7.73126 4.38213 7.97865 4.57004Z",fill:"currentColor"})]}),Wds=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.89741 4.10293C8.11707 4.32261 8.11706 4.67877 7.89738 4.89843L6.79517 6.00058L7.8962 7.10155C8.11588 7.32122 8.11589 7.67737 7.89623 7.89705C7.67656 8.11673 7.32041 8.11674 7.10073 7.89707L5.99965 6.79605L4.89856 7.89707C4.67889 8.11673 4.32273 8.11672 4.10307 7.89704C3.88341 7.67737 3.88342 7.32121 4.10309 7.10155L5.20413 6.00058L4.10191 4.89843C3.88224 4.67877 3.88223 4.32262 4.10189 4.10294C4.32155 3.88326 4.67771 3.88325 4.89738 4.10292L5.99965 5.20511L7.10191 4.10291C7.32159 3.88325 7.67774 3.88326 7.89741 4.10293Z",fill:"currentColor"})]}),Zds=e=>e.includes("."),Gds=e=>e==="input"||e.endsWith(".input"),Qds=1;function Yds(e){return`${Number((e/1e3).toPrecision(3))}s`}function Kds(e,t){const n=Object.entries(e).filter(([i])=>!Gds(i));if(n.length===0)return[];const r=Math.min(...n.map(([,i])=>i.startedAt)),s=Math.max(...n.map(([,i])=>i.endedAt??t)),a=Math.max(s-r,1);return n.map(([i,l])=>{const c=l.endedAt===void 0,d=(l.endedAt??t)-l.startedAt,f=(l.startedAt-r)/a*100,p=Math.max(d/a*100,Qds);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:Zds(i)}})}const Xds=({status:e})=>o.jsxs(qe,{children:[e==="success"&&o.jsx(Hds,{className:"text-accent1"}),e==="failed"&&o.jsx(Wds,{className:"text-accent2"}),e==="suspended"&&o.jsx(YV,{className:"text-accent3"}),e==="waiting"&&o.jsx(dpe,{className:"text-accent5"}),e==="skipped"&&o.jsx(dpe,{className:"text-icon3"}),e==="running"&&o.jsx(oa,{className:"text-accent6 animate-spin"})]}),Jds={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function k7t(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const gXe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},efs=e=>{const t=e;return XDt({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},tfs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=efs(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:X("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(Xds,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||i(e)},children:o.jsx(Egn,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(iV,{indicators:c,className:"shrink-0"})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"block min-w-0 max-w-full justify-self-stretch overflow-hidden text-ellipsis whitespace-nowrap text-left text-neutral6",children:k7t(e.stepId)}),o.jsx("div",{className:"relative h-2 min-w-0 rounded bg-surface4",children:o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":String(e.offsetPct),"data-width":String(e.widthPct),className:`absolute top-0 h-full rounded ${Jds[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||l(e)},children:o.jsx(_gn,{})})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"w-20 justify-self-end text-right text-neutral3 tabular-nums",children:Yds(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function nfs(){const{steps:e}=F3(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=Hq(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);Owe(f,{enabled:!l});const p=Kds(e,a),h=p.some(m=>m.isRunning);return g.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),g.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden rounded-studio-panel border border-border1/50 bg-surface3 p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"rounded-md p-1 text-neutral3 transition-colors hover:bg-surface4 hover:text-neutral6",children:o.jsx(Ia,{className:X("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:p.map((m,v)=>o.jsx(tfs,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:gXe(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:gXe(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(br,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(ckt,{data:u.data,title:`${k7t(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const rfs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=RH();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(l4t,{workflowId:e,workflow:t,isLoading:n}),o.jsx(qds,{}),o.jsx(nfs,{})]})}),r&&o.jsx("div",{className:"w-[420px] min-h-0 overflow-hidden border-l border-border1",children:o.jsx(Fds,{})})]})},vXe=()=>{const{workflowId:e}=Sr(),{data:t,isLoading:n,error:r}=q4(e);return r&&ys(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ws,{})}):r&&xs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"workflows"})}):o.jsx(fke,{children:o.jsx(rfs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function sfs(e,t){if(e==null)return{};var n,r,s=pwt(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function sbe(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function afs(e){if(Array.isArray(e))return sbe(e)}function ifs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function ofs(e,t){if(e){if(typeof e=="string")return sbe(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?sbe(e,t):void 0}}function lfs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
734
734
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function abe(e){return afs(e)||ifs(e)||ofs(e)||lfs()}function OD(e){"@babel/helpers - typeof";return OD=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},OD(e)}function cfs(e,t){if(OD(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(OD(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ufs(e){var t=cfs(e,"string");return OD(t)=="symbol"?t:t+""}function O7t(e,t,n){return(t=ufs(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function yXe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function Oj(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?yXe(Object(n),!0).forEach(function(r){O7t(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):yXe(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function dfs(e){var t=e.length;if(t===0||t===1)return e;if(t===2)return[e[0],e[1],"".concat(e[0],".").concat(e[1]),"".concat(e[1],".").concat(e[0])];if(t===3)return[e[0],e[1],e[2],"".concat(e[0],".").concat(e[1]),"".concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[0]),"".concat(e[1],".").concat(e[2]),"".concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[1],".").concat(e[0])];if(t>=4)return[e[0],e[1],e[2],e[3],"".concat(e[0],".").concat(e[1]),"".concat(e[0],".").concat(e[2]),"".concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[0]),"".concat(e[1],".").concat(e[2]),"".concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[1]),"".concat(e[2],".").concat(e[3]),"".concat(e[3],".").concat(e[0]),"".concat(e[3],".").concat(e[1]),"".concat(e[3],".").concat(e[2]),"".concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[1],".").concat(e[3]),"".concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[2],".").concat(e[3]),"".concat(e[0],".").concat(e[3],".").concat(e[1]),"".concat(e[0],".").concat(e[3],".").concat(e[2]),"".concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[1],".").concat(e[2],".").concat(e[3]),"".concat(e[1],".").concat(e[3],".").concat(e[0]),"".concat(e[1],".").concat(e[3],".").concat(e[2]),"".concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[0],".").concat(e[3]),"".concat(e[2],".").concat(e[1],".").concat(e[0]),"".concat(e[2],".").concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[3],".").concat(e[0]),"".concat(e[2],".").concat(e[3],".").concat(e[1]),"".concat(e[3],".").concat(e[0],".").concat(e[1]),"".concat(e[3],".").concat(e[0],".").concat(e[2]),"".concat(e[3],".").concat(e[1],".").concat(e[0]),"".concat(e[3],".").concat(e[1],".").concat(e[2]),"".concat(e[3],".").concat(e[2],".").concat(e[0]),"".concat(e[3],".").concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[1],".").concat(e[2],".").concat(e[3]),"".concat(e[0],".").concat(e[1],".").concat(e[3],".").concat(e[2]),"".concat(e[0],".").concat(e[2],".").concat(e[1],".").concat(e[3]),"".concat(e[0],".").concat(e[2],".").concat(e[3],".").concat(e[1]),"".concat(e[0],".").concat(e[3],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[3],".").concat(e[2],".").concat(e[1]),"".concat(e[1],".").concat(e[0],".").concat(e[2],".").concat(e[3]),"".concat(e[1],".").concat(e[0],".").concat(e[3],".").concat(e[2]),"".concat(e[1],".").concat(e[2],".").concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[2],".").concat(e[3],".").concat(e[0]),"".concat(e[1],".").concat(e[3],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[3],".").concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[0],".").concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[0],".").concat(e[3],".").concat(e[1]),"".concat(e[2],".").concat(e[1],".").concat(e[0],".").concat(e[3]),"".concat(e[2],".").concat(e[1],".").concat(e[3],".").concat(e[0]),"".concat(e[2],".").concat(e[3],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[3],".").concat(e[1],".").concat(e[0]),"".concat(e[3],".").concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[3],".").concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[3],".").concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[3],".").concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[3],".").concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[3],".").concat(e[2],".").concat(e[1],".").concat(e[0])]}var Sae={};function ffs(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return Sae[t]||(Sae[t]=dfs(e)),Sae[t]}function pfs(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0,r=e.filter(function(a){return a!=="token"}),s=ffs(r);return s.reduce(function(a,i){return Oj(Oj({},a),n[i])},t)}function bXe(e){return e.join(" ")}function hfs(e,t){var n=0;return function(r){return n+=1,r.map(function(s,a){return _7t({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(a)})})}}function _7t(e){var t=e.node,n=e.stylesheet,r=e.style,s=r===void 0?{}:r,a=e.useInlineStyles,i=e.key,l=t.properties,c=t.type,u=t.tagName,d=t.value;if(c==="text")return d;if(u){var f=hfs(n,a),p;if(!a)p=Oj(Oj({},l),{},{className:bXe(l.className)});else{var h=Object.keys(n).reduce(function(b,S){return S.split(".").forEach(function(x){b.includes(x)||b.push(x)}),b},[]),m=l.className&&l.className.includes("token")?["token"]:[],v=l.className&&m.concat(l.className.filter(function(b){return!h.includes(b)}));p=Oj(Oj({},l),{},{className:bXe(v)||void 0,style:pfs(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return Le.createElement(u,HO({key:i},p),y)}}const mfs=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var gfs=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function xXe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function jw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?xXe(Object(n),!0).forEach(function(r){O7t(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):xXe(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var vfs=/\n/g;function yfs(e){return e.match(vfs)}function bfs(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map(function(s,a){var i=a+n;return Le.createElement("span",{key:"line-".concat(a),className:"react-syntax-highlighter-line-number",style:typeof r=="function"?r(i):r},"".concat(i,`
|
|
735
735
|
`))})}function xfs(e){var t=e.codeString,n=e.codeStyle,r=e.containerStyle,s=r===void 0?{float:"left",paddingRight:"10px"}:r,a=e.numberStyle,i=a===void 0?{}:a,l=e.startingLineNumber;return Le.createElement("code",{style:Object.assign({},n,s)},bfs({lines:t.replace(/\n$/,"").split(`
|
|
736
736
|
`),style:i,startingLineNumber:l}))}function wfs(e){return"".concat(e.toString().length,".25em")}function C7t(e,t){return{type:"element",tagName:"span",properties:{key:"line-number--".concat(e),className:["comment","linenumber","react-syntax-highlighter-line-number"],style:t},children:[{type:"text",value:e}]}}function E7t(e,t,n){var r={display:"inline-block",minWidth:wfs(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,a=jw(jw({},r),s);return a}function a9(e){var t=e.children,n=e.lineNumber,r=e.lineNumberStyle,s=e.largestLineNumber,a=e.showInlineLineNumbers,i=e.lineProps,l=i===void 0?{}:i,c=e.className,u=c===void 0?[]:c,d=e.showLineNumbers,f=e.wrapLongLines,p=e.wrapLines,h=p===void 0?!1:p,m=h?jw({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(abe(m.className.trim().split(/\s+/)),abe(u)):u,n&&a){var v=E7t(r,n,s);t.unshift(C7t(n,v))}return f&d&&(m.style=jw({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function j7t(e){for(var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],r=0;r<e.length;r++){var s=e[r];if(s.type==="text")n.push(a9({children:[s],className:abe(new Set(t))}));else if(s.children){var a=t.concat(s.properties.className);j7t(s.children,a).forEach(function(i){return n.push(i)})}}return n}function Sfs(e,t,n,r,s,a,i,l,c){var u,d=j7t(e.value),f=[],p=-1,h=0;function m(_,C){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return a9({children:_,lineNumber:C,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:E,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function v(_,C){if(r&&C&&s){var E=E7t(l,C,i);_.unshift(C7t(C,E))}return _}function y(_,C){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||E.length>0?m(_,C,E):v(_,C)}for(var b=function(){var C=d[h],E=C.children[0].value,j=yfs(E);if(j){var T=E.split(`
|