@mastra/deployer-cloud 1.58.0-alpha.4 → 1.58.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-Dk-S7GEf.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-CTRJn-8F.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js"])))=>i.map(i=>d[i]);
2
2
  import{_ as vo}from"./preload-helper-PPVm8Dsz.js";function LHt(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 gj=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ul(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var MK={exports:{}},eR={};var x$e;function zHt(){if(x$e)return eR;x$e=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 eR.Fragment=t,eR.jsx=n,eR.jsxs=n,eR}var w$e;function FHt(){return w$e||(w$e=1,MK.exports=zHt()),MK.exports}var o=FHt(),DK={exports:{}},qr={},S$e;function BHt(){if(S$e)return qr;S$e=1;var e={env:{}};var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),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 g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function x(V,$,B){this.props=V,this.context=$,this.refs=b,this.updater=B||g}x.prototype.isReactComponent={},x.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")},x.prototype.forceUpdate=function(V){this.updater.enqueueForceUpdate(this,V,"forceUpdate")};function S(){}S.prototype=x.prototype;function k(V,$,B){this.props=V,this.context=$,this.refs=b,this.updater=B||g}var C=k.prototype=new S;C.constructor=k,y(C,x.prototype),C.isPureReactComponent=!0;var _=Array.isArray;function E(){}var T={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function I(V,$,B){var Z=B.ref;return{$$typeof:t,type:V,key:$,ref:Z!==void 0?Z:null,props:B}}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(B){return $[B]})}var D=/\/+/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,$,B,Z,K){var ne=typeof V;(ne==="undefined"||ne==="boolean")&&(V=null);var ee=!1;if(V===null)ee=!0;else switch(ne){case"bigint":case"string":case"number":ee=!0;break;case"object":switch(V.$$typeof){case t:case n:ee=!0;break;case f:return ee=V._init,F(ee(V._payload),$,B,Z,K)}}if(ee)return K=K(V),ee=Z===""?"."+z(V,0):Z,_(K)?(B="",ee!=null&&(B=ee.replace(D,"$&/")+"/"),F(K,$,B,"",function(fe){return fe})):K!=null&&(R(K)&&(K=A(K,B+(K.key==null||V&&V.key===K.key?"":(""+K.key).replace(D,"$&/")+"/")+ee)),$.push(K)),1;ee=0;var J=Z===""?".":Z+":";if(_(V))for(var ae=0;ae<V.length;ae++)Z=V[ae],ne=J+z(Z,ae),ee+=F(Z,$,B,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++),ee+=F(Z,$,B,ne,K);else if(ne==="object"){if(typeof V.then=="function")return F(H(V),$,B,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 ee}function U(V,$,B){if(V==null)return V;var Z=[],K=0;return F(V,Z,"","",function(ne){return $.call(B,ne,K++)}),Z}function q(V){if(V._status===-1){var $=V._result;$=$(),$.then(function(B){(V._status===0||V._status===-1)&&(V._status=1,V._result=B)},function(B){(V._status===0||V._status===-1)&&(V._status=2,V._result=B)}),V._status===-1&&(V._status=0,V._result=$)}if(V._status===1)return V._result.default;throw V._result}var M=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:U,forEach:function(V,$,B){U(V,function(){$.apply(this,arguments)},B)},count:function(V){var $=0;return U(V,function(){$++}),$},toArray:function(V){return U(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=x,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=T,qr.__COMPILER_RUNTIME={__proto__:null,c:function(V){return T.H.useMemoCache(V)}},qr.cache=function(V){return function(){return V.apply(null,arguments)}},qr.cacheSignal=function(){return null},qr.cloneElement=function(V,$,B){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),$)!N.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=B;else if(1<ne){for(var ee=Array(ne),J=0;J<ne;J++)ee[J]=arguments[J+2];Z.children=ee}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,$,B){var Z,K={},ne=null;if($!=null)for(Z in $.key!==void 0&&(ne=""+$.key),$)N.call($,Z)&&Z!=="key"&&Z!=="__self"&&Z!=="__source"&&(K[Z]=$[Z]);var ee=arguments.length-2;if(ee===1)K.children=B;else if(1<ee){for(var J=Array(ee),ae=0;ae<ee;ae++)J[ae]=arguments[ae+2];K.children=J}if(V&&V.defaultProps)for(Z in ee=V.defaultProps,ee)K[Z]===void 0&&(K[Z]=ee[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 $=T.T,B={};T.T=B;try{var Z=V(),K=T.S;K!==null&&K(B,Z),typeof Z=="object"&&Z!==null&&typeof Z.then=="function"&&Z.then(E,M)}catch(ne){M(ne)}finally{$!==null&&B.types!==null&&($.types=B.types),T.T=$}},qr.unstable_useCacheRefresh=function(){return T.H.useCacheRefresh()},qr.use=function(V){return T.H.use(V)},qr.useActionState=function(V,$,B){return T.H.useActionState(V,$,B)},qr.useCallback=function(V,$){return T.H.useCallback(V,$)},qr.useContext=function(V){return T.H.useContext(V)},qr.useDebugValue=function(){},qr.useDeferredValue=function(V,$){return T.H.useDeferredValue(V,$)},qr.useEffect=function(V,$){return T.H.useEffect(V,$)},qr.useEffectEvent=function(V){return T.H.useEffectEvent(V)},qr.useId=function(){return T.H.useId()},qr.useImperativeHandle=function(V,$,B){return T.H.useImperativeHandle(V,$,B)},qr.useInsertionEffect=function(V,$){return T.H.useInsertionEffect(V,$)},qr.useLayoutEffect=function(V,$){return T.H.useLayoutEffect(V,$)},qr.useMemo=function(V,$){return T.H.useMemo(V,$)},qr.useOptimistic=function(V,$){return T.H.useOptimistic(V,$)},qr.useReducer=function(V,$,B){return T.H.useReducer(V,$,B)},qr.useRef=function(V){return T.H.useRef(V)},qr.useState=function(V){return T.H.useState(V)},qr.useSyncExternalStore=function(V,$,B){return T.H.useSyncExternalStore(V,$,B)},qr.useTransition=function(){return T.H.useTransition()},qr.version="19.2.7",qr}var k$e;function WN(){return k$e||(k$e=1,DK.exports=BHt()),DK.exports}var v=WN();const ze=Ul(v),ZN=LHt({__proto__:null,default:ze},[v]);var LK={exports:{}},tR={},zK={exports:{}},FK={};var O$e;function UHt(){return O$e||(O$e=1,(function(e){function t(H,F){var U=H.length;H.push(F);e:for(;0<U;){var q=U-1>>>1,M=H[q];if(0<s(M,F))H[q]=F,H[U]=M,U=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],U=H.pop();if(U!==F){H[0]=U;e:for(var q=0,M=H.length,G=M>>>1;q<G;){var V=2*(q+1)-1,$=H[V],B=V+1,Z=H[B];if(0>s($,U))B<M&&0>s(Z,$)?(H[q]=Z,H[B]=U,q=B):(H[q]=$,H[V]=U,q=V);else if(B<M&&0>s(Z,U))H[q]=Z,H[B]=U,q=B;else break e}}return F}function s(H,F){var U=H.sortIndex-F.sortIndex;return U!==0?U: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,g=!1,y=!1,b=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,S=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 C(H){if(g=!1,k(H),!m)if(n(c)!==null)m=!0,_||(_=!0,R());else{var F=n(u);F!==null&&z(C,F.startTime-H)}}var _=!1,E=-1,T=5,N=-1;function I(){return y?!0:!(e.unstable_now()-N<T)}function A(){if(y=!1,_){var H=e.unstable_now();N=H;var F=!0;try{e:{m=!1,g&&(g=!1,x(E),E=-1),h=!0;var U=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 M=q(f.expirationTime<=H);if(H=e.unstable_now(),typeof M=="function"){f.callback=M,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(C,G.startTime-H),F=!1}}break e}finally{f=null,p=U,h=!1}F=void 0}}finally{F?R():_=!1}}}var R;if(typeof S=="function")R=function(){S(A)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,D=L.port2;L.port1.onmessage=A,R=function(){D.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"):T=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 U=p;p=F;try{return H()}finally{p=U}},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 U=p;p=H;try{return F()}finally{p=U}},e.unstable_scheduleCallback=function(H,F,U){var q=e.unstable_now();switch(typeof U=="object"&&U!==null?(U=U.delay,U=typeof U=="number"&&0<U?q+U:q):U=q,H){case 1:var M=-1;break;case 2:M=250;break;case 5:M=1073741823;break;case 4:M=1e4;break;default:M=5e3}return M=U+M,H={id:d++,callback:F,priorityLevel:H,startTime:U,expirationTime:M,sortIndex:-1},U>q?(H.sortIndex=U,t(u,H),n(c)===null&&H===n(u)&&(g?(x(E),E=-1):g=!0,z(C,U-q))):(H.sortIndex=M,t(c,H),m||h||(m=!0,_||(_=!0,R()))),H},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(H){var F=p;return function(){var U=p;p=F;try{return H.apply(this,arguments)}finally{p=U}}}})(FK)),FK}var _$e;function qHt(){return _$e||(_$e=1,zK.exports=UHt()),zK.exports}var BK={exports:{}},ku={};var C$e;function VHt(){if(C$e)return ku;C$e=1;var e=WN();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 ku.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,ku.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)},ku.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()}},ku.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))},ku.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},ku.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})}},ku.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)},ku.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})}},ku.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)},ku.requestFormReset=function(c){r.d.r(c)},ku.unstable_batchedUpdates=function(c,u){return c(u)},ku.useFormState=function(c,u,d){return i.H.useFormState(c,u,d)},ku.useFormStatus=function(){return i.H.useHostTransitionStatus()},ku.version="19.2.7",ku}var E$e;function kot(){if(E$e)return BK.exports;E$e=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),BK.exports=VHt(),BK.exports}var T$e;function HHt(){if(T$e)return tR;T$e=1;var e={env:{}};var t=qHt(),n=WN(),r=kot();function s(w){var O="https://react.dev/errors/"+w;if(1<arguments.length){O+="?args[]="+encodeURIComponent(arguments[1]);for(var j=2;j<arguments.length;j++)O+="&args[]="+encodeURIComponent(arguments[j])}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,j=w;if(w.alternate)for(;O.return;)O=O.return;else{w=O;do O=w,(O.flags&4098)!==0&&(j=O.return),w=O.return;while(w)}return O.tag===3?j: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 j=w,P=O;;){var W=j.return;if(W===null)break;var Q=W.alternate;if(Q===null){if(P=W.return,P!==null){j=P;continue}break}if(W.child===Q.child){for(Q=W.child;Q;){if(Q===j)return u(W),w;if(Q===P)return u(W),O;Q=Q.sibling}throw Error(s(188))}if(j.return!==P.return)j=W,P=Q;else{for(var ie=!1,Se=W.child;Se;){if(Se===j){ie=!0,j=W,P=Q;break}if(Se===P){ie=!0,P=W,j=Q;break}Se=Se.sibling}if(!ie){for(Se=Q.child;Se;){if(Se===j){ie=!0,j=Q,P=W;break}if(Se===P){ie=!0,P=Q,j=W;break}Se=Se.sibling}if(!ie)throw Error(s(189))}}if(j.alternate!==P)throw Error(s(190))}if(j.tag!==3)throw Error(s(188));return j.stateNode.current===j?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"),g=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),S=Symbol.for("react.consumer"),k=Symbol.for("react.context"),C=Symbol.for("react.forward_ref"),_=Symbol.for("react.suspense"),E=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),N=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 D=Symbol.for("react.client.reference");function z(w){if(w==null)return null;if(typeof w=="function")return w.$$typeof===D?null:w.displayName||w.name||null;if(typeof w=="string")return w;switch(w){case y:return"Fragment";case x:return"Profiler";case b:return"StrictMode";case _:return"Suspense";case E:return"SuspenseList";case I:return"Activity"}if(typeof w=="object")switch(w.$$typeof){case g:return"Portal";case k:return w.displayName||"Context";case S:return(w._context.displayName||"Context")+".Consumer";case C:var O=w.render;return w=w.displayName,w||(w=O.displayName||O.name||"",w=w!==""?"ForwardRef("+w+")":"ForwardRef"),w;case T:return O=w.displayName||null,O!==null?O:z(w.type)||"Memo";case N: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,U=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,q={pending:!1,data:null,method:null,action:null},M=[],G=-1;function V(w){return{current:w}}function $(w){0>G||(w.current=M[G],M[G]=null,G--)}function B(w,O){G++,M[G]=w.current,w.current=O}var Z=V(null),K=V(null),ne=V(null),ee=V(null);function J(w,O){switch(B(ne,O),B(K,w),B(Z,null),O.nodeType){case 9:case 11:w=(w=O.documentElement)&&(w=w.namespaceURI)?q2e(w):0;break;default:if(w=O.tagName,O=O.namespaceURI)O=q2e(O),w=V2e(O,w);else switch(w){case"svg":w=1;break;case"math":w=2;break;default:w=0}}$(Z),B(Z,w)}function ae(){$(Z),$(K),$(ne)}function fe(w){w.memoizedState!==null&&B(ee,w);var O=Z.current,j=V2e(O,w.type);O!==j&&(B(K,w),B(Z,j))}function Y(w){K.current===w&&($(Z),$(K)),ee.current===w&&($(ee),YA._currentValue=q)}var re,le;function ue(w){if(re===void 0)try{throw Error()}catch(j){var O=j.stack.trim().match(/\n( *(at )?)/);re=O&&O[1]||"",le=-1<j.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<j.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+re+w+le}var oe=!1;function me(w,O){if(!w||oe)return"";oe=!0;var j=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(mt){var ut=mt}Reflect.construct(w,[],jt)}else{try{jt.call()}catch(mt){ut=mt}w.call(jt.prototype)}}else{try{throw Error()}catch(mt){ut=mt}(jt=w())&&typeof jt.catch=="function"&&jt.catch(function(){})}}catch(mt){if(mt&&ut&&typeof mt.stack=="string")return[mt.stack,ut.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(`
@@ -103,7 +103,7 @@ ${n}
103
103
  `);l!=="[DONE]"&&a.enqueue(JSON.parse(l))},r=s=>{let a=vDe.exec(t);for(;a;)n(t.slice(0,a.index),s),t=t.slice(a.index+a[0].length),a=vDe.exec(t)};return new TransformStream({transform(s,a){t+=e.decode(s,{stream:!0}),r(a)},flush(s){t+=e.decode(),r(s),t&&n(t,s)}})}function i6(e){return e.status==="failed"&&e.error&&(e.error=OV(e.error,{fallbackMessage:"Unknown workflow error",supportSerialization:!1})),e}var mun=class extends qa{workflowId;runId;constructor(e,t,n){super(e),this.workflowId=t,this.runId=n}createChunkTransformStream(){return Idt()}cancelRun(){return this.request(`/workflows/${this.workflowId}/runs/${this.runId}/cancel`,{method:"POST"})}cancel(){return this.request(`/workflows/${this.workflowId}/runs/${this.runId}/cancel`,{method:"POST"})}start(e){const t=fr(e.requestContext);return this.request(`/workflows/${this.workflowId}/start?runId=${this.runId}`,{method:"POST",body:{inputData:e?.inputData,initialState:e?.initialState,requestContext:t,tracingOptions:e.tracingOptions,perStep:e.perStep}})}resume({step:e,resumeData:t,tracingOptions:n,perStep:r,forEachIndex:s,...a}){const i=fr(a.requestContext);return this.request(`/workflows/${this.workflowId}/resume?runId=${this.runId}`,{method:"POST",body:{step:e,resumeData:t,requestContext:i,tracingOptions:n,perStep:r,forEachIndex:s}})}startAsync(e){const t=new URLSearchParams;t.set("runId",this.runId);const n=fr(e.requestContext);return this.request(`/workflows/${this.workflowId}/start-async?${t.toString()}`,{method:"POST",body:{inputData:e.inputData,initialState:e.initialState,requestContext:n,tracingOptions:e.tracingOptions,resourceId:e.resourceId,perStep:e.perStep}}).then(i6)}async stream(e){const t=new URLSearchParams;t.set("runId",this.runId);const n=fr(e.requestContext),r=await this.request(`/workflows/${this.workflowId}/stream?${t.toString()}`,{method:"POST",body:{inputData:e.inputData,initialState:e.initialState,requestContext:n,tracingOptions:e.tracingOptions,resourceId:e.resourceId,perStep:e.perStep,closeOnSuspend:e.closeOnSuspend},stream:!0});if(!r.ok)throw new Error(`Failed to stream workflow: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createChunkTransformStream())}async observe(e){const t=new URLSearchParams;t.set("runId",this.runId),e?.offset!==void 0&&t.set("offset",String(e.offset));const n=await this.request(`/workflows/${this.workflowId}/observe?${t.toString()}`,{method:"POST",stream:!0});if(!n.ok)throw new Error(`Failed to observe workflow stream: ${n.statusText}`);if(!n.body)throw new Error("Response body is null");return n.body.pipeThrough(this.createChunkTransformStream())}async observeStream(){return this.observe()}resumeAsync(e){const t=fr(e.requestContext);return this.request(`/workflows/${this.workflowId}/resume-async?runId=${this.runId}`,{method:"POST",body:{step:e.step,resumeData:e.resumeData,requestContext:t,tracingOptions:e.tracingOptions,perStep:e.perStep,forEachIndex:e.forEachIndex}}).then(i6)}resumeNoWait(e){const t=fr(e.requestContext);return this.request(`/workflows/${this.workflowId}/resume-no-wait?runId=${this.runId}`,{method:"POST",body:{step:e.step,resumeData:e.resumeData,requestContext:t,tracingOptions:e.tracingOptions,perStep:e.perStep,forEachIndex:e.forEachIndex}})}async resumeStream(e){const t=new URLSearchParams;t.set("runId",this.runId);const n=fr(e.requestContext),r=await this.request(`/workflows/${this.workflowId}/resume-stream?${t.toString()}`,{method:"POST",body:{step:e.step,resumeData:e.resumeData,requestContext:n,tracingOptions:e.tracingOptions,perStep:e.perStep,forEachIndex:e.forEachIndex},stream:!0});if(!r.ok)throw new Error(`Failed to stream vNext workflow: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createChunkTransformStream())}restart(e){const t=fr(e.requestContext);return this.request(`/workflows/${this.workflowId}/restart?runId=${this.runId}`,{method:"POST",body:{requestContext:t,tracingOptions:e.tracingOptions}})}restartAsync(e){const t=fr(e?.requestContext);return this.request(`/workflows/${this.workflowId}/restart-async?runId=${this.runId}`,{method:"POST",body:{requestContext:t,tracingOptions:e?.tracingOptions}}).then(i6)}timeTravel({requestContext:e,...t}){const n=fr(e);return this.request(`/workflows/${this.workflowId}/time-travel?runId=${this.runId}`,{method:"POST",body:{...t,requestContext:n}})}timeTravelAsync({requestContext:e,...t}){const n=fr(e);return this.request(`/workflows/${this.workflowId}/time-travel-async?runId=${this.runId}`,{method:"POST",body:{...t,requestContext:n}}).then(i6)}async timeTravelStream({requestContext:e,...t}){const n=fr(e),r=await this.request(`/workflows/${this.workflowId}/time-travel-stream?runId=${this.runId}`,{method:"POST",body:{...t,requestContext:n},stream:!0});if(!r.ok)throw new Error(`Failed to time travel workflow: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createChunkTransformStream())}};const gun="";var vun=class extends qa{workflowId;constructor(t,n){super(t),this.workflowId=n}details(t){return this.request(`/workflows/${this.workflowId}${cn(t)}`)}runs(t,n){const r=yw(fr(n)),s=new URLSearchParams;return t?.fromDate&&s.set("fromDate",t.fromDate.toISOString()),t?.toDate&&s.set("toDate",t.toDate.toISOString()),t?.page!==void 0&&s.set("page",String(t.page)),t?.perPage!==void 0&&s.set("perPage",String(t.perPage)),t?.limit!==null&&t?.limit!==void 0&&(t.limit===!1?s.set("limit","false"):typeof t.limit=="number"&&t.limit>0&&Number.isInteger(t.limit)&&s.set("limit",String(t.limit))),t?.offset!==null&&t?.offset!==void 0&&!isNaN(Number(t?.offset))&&s.set("offset",String(t.offset)),t?.resourceId&&s.set("resourceId",t.resourceId),t?.status&&s.set("status",t.status),r&&s.set("requestContext",r),s.size?this.request(`/workflows/${this.workflowId}/runs?${s}`):this.request(`/workflows/${this.workflowId}/runs`)}runById(t,n){const r=new URLSearchParams;n?.fields&&n.fields.length>0&&r.set("fields",n.fields.join(",")),n?.withNestedWorkflows!==void 0&&r.set("withNestedWorkflows",String(n.withNestedWorkflows));const s=yw(fr(n?.requestContext));s&&r.set("requestContext",s);const a=r.size>0?`?${r.toString()}`:"";return this.request(`/workflows/${this.workflowId}/runs/${t}${a}`)}deleteRunById(t){return this.request(`/workflows/${this.workflowId}/runs/${t}`,{method:"DELETE"})}async getSchema(){const t=await this.details();return{inputSchema:t.inputSchema?hDe(t.inputSchema):null,outputSchema:t.outputSchema?hDe(t.outputSchema):null}}async createRun(t){const n=new URLSearchParams;t?.runId&&n.set("runId",t.runId);const r=await this.request(`/workflows/${this.workflowId}/create-run?${n.toString()}`,{method:"POST",body:{resourceId:t?.resourceId,disableScorers:t?.disableScorers}});return new mun(this.options,this.workflowId,r.runId)}static createRecordStream(t){const n=new TextEncoder;return new ReadableStream({async start(r){try{for await(const s of t){const a=JSON.stringify(s)+gun;r.enqueue(n.encode(a))}r.close()}catch(s){r.error(s)}}})}};function yun(e){const t=e.replace(/\x1E/g,`
104
104
 
105
105
  `),n=t.match(/\r?\n\r?\n/);if(!n||n.index===void 0)return{rest:t};const r=n[0].length;return{eventBlock:t.slice(0,n.index),rest:t.slice(n.index+r)}}function yDe(e){const t=e.trim();if(!t)return{};const n=t.split(/\r?\n/).filter(a=>a.startsWith("data:")).map(a=>a.slice(5).trimStart()),r=n.length>0?n.join(`
106
- `):t;if(!r||r==="[DONE]")return{done:!0};let s;try{s=JSON.parse(r)}catch(a){throw new Error(`Failed to parse A2A stream event: ${a instanceof Error?a.message:"unknown parse error"}`)}if(s&&typeof s=="object"&&"error"in s&&s.error)throw new Tx(200,"OK",`A2A stream error - ${JSON.stringify(s.error)}`,s.error);return s&&typeof s=="object"&&"result"in s?{event:s.result}:{event:s}}async function*K9(e){const t=e.getReader(),n=new TextDecoder;let r="";try{for(;;){const{done:s,value:a}=await t.read();for(s?r+=n.decode():r+=n.decode(a,{stream:!0});;){const{eventBlock:i,rest:l}=yun(r);if(r=l,!i)break;const c=yDe(i);if(c.done)return;c.event&&(yield c.event)}if(s)break}if(r.trim()){const s=yDe(r);!s.done&&s.event&&(yield s.event)}}finally{t.releaseLock()}}const bun=["ES256","ES384","ES512","RS256","RS384","RS512","PS256","PS384","PS512"];function xun(e){const t=structuredClone(e);return delete t.signatures,t}function wun(e){const t=globalThis.CryptoKey;return typeof t<"u"&&e instanceof t}function Sun(e){return e.includes("-----BEGIN ")}function kun(e){return e.includes("-----BEGIN CERTIFICATE-----")}async function Oun(e,t){if(wun(e)||e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof e=="string"){if(t.startsWith("HS"))return new TextEncoder().encode(e);if(!Sun(e))throw new Error("Expected a PEM-encoded public key or certificate string for Agent Card verification");return kun(e)?bcn(e,t):ycn(e,t)}return xcn(e,t)}async function _un(e,t){const n=e.signatures??[];if(n.length===0)return e;const r=Ucn(xun(e));if(!r)throw new Tx(200,"OK","Failed to canonicalize A2A Agent Card for signature verification");const s=t.algorithms??[...bun],a=Vln(r),i=[];for(const[l,c]of n.entries())try{const u=`${c.protected}.${a}.${c.signature}`,d=Tcn(u);if(typeof d.alg!="string")throw new Error('Agent Card signature is missing a protected "alg" header');if(!s.includes(d.alg))throw new Error(`Agent Card signature algorithm "${d.alg}" is not allowed`);const f=await t.keyProvider({agentCard:e,signature:c,protectedHeader:d,alg:d.alg,kid:typeof d.kid=="string"?d.kid:void 0,jku:typeof d.jku=="string"?d.jku:void 0,index:l});if(!f)throw new Error("No verification key was provided for Agent Card signature verification");return await Ecn(u,await Oun(f,d.alg),{algorithms:s}),e}catch(u){i.push(u instanceof Error?u.message:"Unknown verification failure")}throw new Tx(200,"OK",`A2A Agent Card signature verification failed: ${i.join("; ")}`)}function Cun(e){const t=e.error,n=t?.message??"Unknown A2A JSON-RPC error";return typeof t?.code=="number"?new Uln(t.code,n,t.data):new Tx(200,"OK",`A2A JSON-RPC error - ${n}`,t)}function UE(e){if("error"in e&&e.error)throw Cun(e);if("result"in e)return e.result;throw new Tx(200,"OK","A2A JSON-RPC response did not include a result",e)}async function X9(e,t){if(e.body)return e.body;const n=Array.from(e.headers.entries()).map(([a,i])=>`${a}: ${i}`).join(", ");let r="";try{r=await e.text()}catch{}const s=[`A2A ${t} stream response did not include a body`,`(status: ${e.status} ${e.statusText})`,n?`headers: ${n}`:"",r?`body: ${r}`:""].filter(Boolean).join(" ");throw new Tx(e.status,e.statusText,s)}var Eun=class extends qa{agentId;constructor(e,t){super(e),this.agentId=t}async getAgentCard(e){const t=await this.request(`/.well-known/${this.agentId}/agent-card.json`);return e?.verifySignature?_un(t,e.verifySignature):t}async getCard(e){return this.getAgentCard(e)}async getExtendedAgentCard(){return UE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"agent/getAuthenticatedExtendedCard"}}))}async sendMessage(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/send",params:e}})}async*sendMessageStream(e){yield*K9(await X9(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/stream",params:e},stream:!0}),"message/stream"))}async sendStreamingMessage(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/stream",params:e},stream:!0})}async getTask(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/get",params:e}})}async cancelTask(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/cancel",params:e}})}async*resubscribeTask(e){yield*K9(await X9(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/resubscribe",params:e},stream:!0}),"tasks/resubscribe"))}async setTaskPushNotificationConfig(e){return UE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/set",params:e}}))}async getTaskPushNotificationConfig(e){return UE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/get",params:e}}))}async listTaskPushNotificationConfig(e){return UE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/list",params:e}}))}async deleteTaskPushNotificationConfig(e){UE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/delete",params:e}}))}},Tun=class extends qa{agentId;constructor(e,t){super(e),this.agentId=t}async rpc(e,t){return UE(await this.request(`/a2a/${this.agentId}`,{method:"POST",headers:{"A2A-Version":"1.0"},body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:e,params:t}}))}async getAgentCard(){const e=await this.request(`/.well-known/${this.agentId}/agent-card.json`,{headers:{"A2A-Version":"1.0"}});return Icn.fromJSON(e)}async sendMessage(e){const t=await this.rpc("message/send",uDe.toJSON(e));return Dcn.fromJSON(t)}async*sendMessageStream(e){const t=await this.request(`/a2a/${this.agentId}`,{method:"POST",headers:{"A2A-Version":"1.0"},body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/stream",params:uDe.toJSON(e)},stream:!0});for await(const n of K9(await X9(t,"message/stream")))yield dDe.fromJSON(n)}async getTask(e){const t=await this.rpc("tasks/get",Acn.toJSON(e));return u1.fromJSON(t)}async listTasks(e){const t=await this.rpc("tasks/list",Rcn.toJSON(e));return Pcn.fromJSON(t)}async cancelTask(e){const t=await this.rpc("tasks/cancel",$cn.toJSON(e));return u1.fromJSON(t)}async*resubscribeTask(e){const t=await this.request(`/a2a/${this.agentId}`,{method:"POST",headers:{"A2A-Version":"1.0"},body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/resubscribe",params:Mcn.toJSON(e)},stream:!0});for await(const n of K9(await X9(t,"tasks/resubscribe")))yield dDe.fromJSON(n)}},jun=class extends qa{serverId;toolId;constructor(e,t,n){super(e),this.serverId=t,this.toolId=n}details(e){return this.request(`/mcp/${encodeURIComponent(this.serverId)}/tools/${encodeURIComponent(this.toolId)}${cn(e)}`)}execute(e){const t={};return e.data!==void 0&&(t.data=e.data),e.requestContext!==void 0&&(t.requestContext=e.requestContext),this.request(`/mcp/${encodeURIComponent(this.serverId)}/tools/${encodeURIComponent(this.toolId)}/execute`,{method:"POST",body:t})}},Nun=class extends qa{actionId;constructor(e,t){super(e),this.actionId=t}transformWorkflowResult(e){return e.status==="success"?{success:e.result.success||!1,applied:e.result.applied||!1,branchName:e.result.branchName,message:e.result.message||"Agent builder action completed",validationResults:e.result.validationResults,error:e.result.error,errors:e.result.errors,stepResults:e.result.stepResults}:e.status==="failed"?{success:!1,applied:!1,message:`Agent builder action failed: ${e.error.message}`,error:e.error.message}:{success:!1,applied:!1,message:"Agent builder action was suspended",error:"Workflow suspended - manual intervention required"}}createRecordParserTransform(){return Idt()}async createRun(e){const t=new URLSearchParams;e?.runId&&t.set("runId",e.runId);const n=`/agent-builder/${this.actionId}/create-run${t.toString()?`?${t.toString()}`:""}`;return this.request(n,{method:"POST"})}async startAsync(e,t){const n=new URLSearchParams;t&&n.set("runId",t);const r=fr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/start-async${n.toString()?`?${n.toString()}`:""}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:r}});return this.transformWorkflowResult(l)}async startActionRun(e,t){const n=new URLSearchParams;n.set("runId",t);const r=fr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/start?${n.toString()}`;return this.request(i,{method:"POST",body:{...a,requestContext:r}})}async resume(e,t){const n=new URLSearchParams;n.set("runId",t);const r=fr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/resume?${n.toString()}`;return this.request(i,{method:"POST",body:{...a,requestContext:r}})}async resumeAsync(e,t){const n=new URLSearchParams;n.set("runId",t);const r=fr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/resume-async?${n.toString()}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:r}});return this.transformWorkflowResult(l)}async stream(e,t){if(!t)throw new Error("runId is required to stream an agent builder action");const n=new URLSearchParams;n.set("runId",t);const r=fr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/stream?${n.toString()}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:r},stream:!0});if(!l.ok)throw new Error(`Failed to stream agent builder action: ${l.statusText}`);if(!l.body)throw new Error("Response body is null");return l.body.pipeThrough(this.createRecordParserTransform())}async observeStream(e){const t=new URLSearchParams;t.set("runId",e.runId);const n=`/agent-builder/${this.actionId}/observe?${t.toString()}`,r=await this.request(n,{method:"POST",stream:!0});if(!r.ok)throw new Error(`Failed to observe agent builder action stream: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createRecordParserTransform())}async observeStreamLegacy(e){const t=new URLSearchParams;t.set("runId",e.runId);const n=`/agent-builder/${this.actionId}/observe-stream-legacy?${t.toString()}`,r=await this.request(n,{method:"POST",stream:!0});if(!r.ok)throw new Error(`Failed to observe agent builder action stream legacy: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createRecordParserTransform())}async resumeStream(e){const t=new URLSearchParams;t.set("runId",e.runId);const n=fr(e.requestContext),{runId:r,requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/resume-stream?${t.toString()}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:n},stream:!0});if(!l.ok)throw new Error(`Failed to resume agent builder action stream: ${l.statusText}`);if(!l.body)throw new Error("Response body is null");return l.body.pipeThrough(this.createRecordParserTransform())}async runById(e,t){const n=new URLSearchParams;t?.fields&&t.fields.length>0&&n.set("fields",t.fields.join(",")),t?.withNestedWorkflows!==void 0&&n.set("withNestedWorkflows",String(t.withNestedWorkflows));const r=n.size>0?`?${n.toString()}`:"",s=`/agent-builder/${this.actionId}/runs/${e}${r}`;return this.request(s,{method:"GET"})}async details(){return await this.request(`/agent-builder/${this.actionId}`)}async runs(e){const t=new URLSearchParams;e?.fromDate&&t.set("fromDate",e.fromDate.toISOString()),e?.toDate&&t.set("toDate",e.toDate.toISOString()),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.page!==void 0&&t.set("page",String(e.page)),e?.limit!==null&&e?.limit!==void 0&&(e.limit===!1?t.set("limit","false"):typeof e.limit=="number"&&e.limit>0&&Number.isInteger(e.limit)&&t.set("limit",String(e.limit))),e?.offset!==null&&e?.offset!==void 0&&!isNaN(Number(e?.offset))&&t.set("offset",String(e.offset)),e?.resourceId&&t.set("resourceId",e.resourceId);const n=`/agent-builder/${this.actionId}/runs${t.toString()?`?${t.toString()}`:""}`;return this.request(n,{method:"GET"})}async cancelRun(e){const t=`/agent-builder/${this.actionId}/runs/${e}/cancel`;return this.request(t,{method:"POST"})}},Iun=class extends qa{constructor(e){super(e)}getTrace(e){return this.request(`/observability/traces/${e}`)}getTraceLight(e){return this.request(`/observability/traces/${e}/light`)}getSpan(e,t){return this.request(`/observability/traces/${e}/spans/${t}`)}getTraceTrajectory(e){return this.request(`/observability/traces/${e}/trajectory`)}getTraces(e){const{pagination:t,filters:n}=e,{page:r,perPage:s,dateRange:a}=t||{},{name:i,spanType:l,entityId:c,entityType:u}=n||{},d=new URLSearchParams;if(r!==void 0&&d.set("page",String(r)),s!==void 0&&d.set("perPage",String(s)),i&&d.set("name",i),l!==void 0&&d.set("spanType",String(l)),c&&u&&(d.set("entityId",c),d.set("entityType",u)),a){const p=JSON.stringify({start:a.start instanceof Date?a.start.toISOString():a.start,end:a.end instanceof Date?a.end.toISOString():a.end});d.set("dateRange",p)}const f=d.toString();return this.request(`/observability/traces${f?`?${f}`:""}`)}listTraces(e={}){const t=sf(e,["filters","pagination","orderBy"]);return this.request(`/observability/traces${t?`?${t}`:""}`)}listTracesLight(e={}){const t=sf(e,["filters","pagination","orderBy"]);return this.request(`/observability/traces/light${t?`?${t}`:""}`)}listBranches(e={}){const t=sf(e,["filters","pagination","orderBy"]);return this.request(`/observability/branches${t?`?${t}`:""}`)}getBranch(e){const{traceId:t,spanId:n,depth:r}=e,s=r!==void 0?`?depth=${r}`:"";return this.request(`/observability/traces/${encodeURIComponent(t)}/branches/${encodeURIComponent(n)}${s}`)}listScoresBySpan(e){const{traceId:t,spanId:n,...r}=e,s=sf(r);return this.request(`/observability/traces/${encodeURIComponent(t)}/${encodeURIComponent(n)}/scores${s?`?${s}`:""}`)}score(e){return this.request("/observability/traces/score",{method:"POST",body:{...e}})}listLogs(e={}){const t=sf(e,["filters","pagination","orderBy"]);return this.request(`/observability/logs${t?`?${t}`:""}`)}listScores(e={}){const t=sf(e,["filters","pagination","orderBy"]);return this.request(`/observability/scores${t?`?${t}`:""}`)}createScore(e){return this.request("/observability/scores",{method:"POST",body:e})}getScoreAggregate(e){return this.request("/observability/scores/aggregate",{method:"POST",body:e})}getScoreBreakdown(e){return this.request("/observability/scores/breakdown",{method:"POST",body:e})}getScoreTimeSeries(e){return this.request("/observability/scores/timeseries",{method:"POST",body:e})}getScorePercentiles(e){return this.request("/observability/scores/percentiles",{method:"POST",body:e})}listFeedback(e={}){const t=sf(e,["filters","pagination","orderBy"]);return this.request(`/observability/feedback${t?`?${t}`:""}`)}createFeedback(e){return this.request("/observability/feedback",{method:"POST",body:e})}getFeedbackAggregate(e){return this.request("/observability/feedback/aggregate",{method:"POST",body:e})}getFeedbackBreakdown(e){return this.request("/observability/feedback/breakdown",{method:"POST",body:e})}getFeedbackTimeSeries(e){return this.request("/observability/feedback/timeseries",{method:"POST",body:e})}getFeedbackPercentiles(e){return this.request("/observability/feedback/percentiles",{method:"POST",body:e})}getMetricAggregate(e){return this.request("/observability/metrics/aggregate",{method:"POST",body:e})}getMetricBreakdown(e){return this.request("/observability/metrics/breakdown",{method:"POST",body:e})}getMetricTimeSeries(e){return this.request("/observability/metrics/timeseries",{method:"POST",body:e})}getMetricPercentiles(e){return this.request("/observability/metrics/percentiles",{method:"POST",body:e})}getMetricNames(e={}){const t=sf(e);return this.request(`/observability/discovery/metric-names${t?`?${t}`:""}`)}getMetricLabelKeys(e){const t=sf(e);return this.request(`/observability/discovery/metric-label-keys${t?`?${t}`:""}`)}getMetricLabelValues(e){const t=sf(e);return this.request(`/observability/discovery/metric-label-values${t?`?${t}`:""}`)}getEntityTypes(){return this.request("/observability/discovery/entity-types")}getEntityNames(e={}){const t=sf(e);return this.request(`/observability/discovery/entity-names${t?`?${t}`:""}`)}getServiceNames(){return this.request("/observability/discovery/service-names")}getEnvironments(){return this.request("/observability/discovery/environments")}getTags(e={}){const t=sf(e);return this.request(`/observability/discovery/tags${t?`?${t}`:""}`)}},Aun=class extends qa{storedAgentId;constructor(e,t){super(e),this.storedAgentId=t}details(e,t){const n=cn(e),r=t?.status?`status=${t.status}`:"",s=`/stored/agents/${encodeURIComponent(this.storedAgentId)}${n}${r?`${n?"&":"?"}${r}`:""}`;return this.request(s)}update(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}${cn(t)}`,{method:"PATCH",body:e})}export(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/export`,{method:"POST",body:e})}openChangeRequest(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/change-request`,{method:"POST",body:e})}delete(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}${cn(e)}`,{method:"DELETE"})}dependents(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/dependents${cn(e)}`)}favorite(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/favorite${cn(e)}`,{method:"PUT"})}unfavorite(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/favorite${cn(e)}`,{method:"DELETE"})}listVersions(e,t){const n=new URLSearchParams;e?.page!==void 0&&n.set("page",String(e.page)),e?.perPage!==void 0&&n.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&n.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&n.set("orderBy[direction]",e.orderBy.direction));const r=n.toString(),s=cn(t);return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions${r?`?${r}`:""}${s?`${r?"&":"?"}${s.slice(1)}`:""}`)}createVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions${cn(t)}`,{method:"POST",body:e||{}})}getVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}${cn(t)}`)}activateVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}/activate${cn(t)}`,{method:"POST"})}restoreVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}/restore${cn(t)}`,{method:"POST"})}deleteVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}${cn(t)}`,{method:"DELETE"})}compareVersions(e,t,n){const r=new URLSearchParams;r.set("from",e),r.set("to",t);const s=cn(n);return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/compare?${r.toString()}${s?`&${s.slice(1)}`:""}`)}},Run=class extends qa{storedWorkflowId;constructor(e,t){super(e),this.storedWorkflowId=t}details(){return this.request(`/stored/workflows/${encodeURIComponent(this.storedWorkflowId)}`)}delete(){return this.request(`/stored/workflows/${encodeURIComponent(this.storedWorkflowId)}`,{method:"DELETE"})}},Pun=class extends qa{storedPromptBlockId;constructor(e,t){super(e),this.storedPromptBlockId=t}details(e,t){const n=cn(e),r=t?.status?`status=${t.status}`:"",s=`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}${n}${r?`${n?"&":"?"}${r}`:""}`;return this.request(s)}update(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}${cn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}${cn(e)}`,{method:"DELETE"})}listVersions(e,t){const n=new URLSearchParams;e?.page!==void 0&&n.set("page",String(e.page)),e?.perPage!==void 0&&n.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&n.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&n.set("orderBy[direction]",e.orderBy.direction));const r=n.toString(),s=cn(t,r?"&":"?");return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions${r?`?${r}`:""}${s}`)}createVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions${cn(t)}`,{method:"POST",body:e||{}})}getVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}${cn(t)}`)}activateVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}/activate${cn(t)}`,{method:"POST"})}restoreVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}/restore${cn(t)}`,{method:"POST"})}deleteVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}${cn(t)}`,{method:"DELETE"})}compareVersions(e,t,n){const r=new URLSearchParams;r.set("from",e),r.set("to",t);const s=cn(n,"&");return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/compare?${r.toString()}${s}`)}},$un=class extends qa{storedMCPClientId;constructor(e,t){super(e),this.storedMCPClientId=t}details(e){return this.request(`/stored/mcp-clients/${encodeURIComponent(this.storedMCPClientId)}${cn(e)}`)}update(e,t){return this.request(`/stored/mcp-clients/${encodeURIComponent(this.storedMCPClientId)}${cn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/mcp-clients/${encodeURIComponent(this.storedMCPClientId)}${cn(e)}`,{method:"DELETE"})}},Mun=class extends qa{storedScorerId;constructor(e,t){super(e),this.storedScorerId=t}details(e,t){const n=cn(e),r=t?.status?`status=${t.status}`:"",s=n?"&":"?",a=`/stored/scorers/${encodeURIComponent(this.storedScorerId)}${n}${r?`${n?s:"?"}${r}`:""}`;return this.request(a)}update(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}${cn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}${cn(e)}`,{method:"DELETE"})}listVersions(e,t){const n=new URLSearchParams;e?.page!==void 0&&n.set("page",String(e.page)),e?.perPage!==void 0&&n.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&n.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&n.set("orderBy[direction]",e.orderBy.direction));const r=n.toString(),s=cn(t);return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions${r?`?${r}`:""}${s?`${r?"&":"?"}${s.slice(1)}`:""}`)}createVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions${cn(t)}`,{method:"POST",body:e||{}})}getVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}${cn(t)}`)}activateVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}/activate${cn(t)}`,{method:"POST"})}restoreVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}/restore${cn(t)}`,{method:"POST"})}deleteVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}${cn(t)}`,{method:"DELETE"})}compareVersions(e,t,n){const r=new URLSearchParams;r.set("from",e),r.set("to",t);const s=cn(n);return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/compare?${r.toString()}${s?`&${s.slice(1)}`:""}`)}},Dun=class extends qa{providerId;constructor(e,t){super(e),this.providerId=t}listToolkits(){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/toolkits`)}listTools(e){const t=new URLSearchParams;e?.toolkit&&t.set("toolkit",e.toolkit),e?.search&&t.set("search",e.search),e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage));const n=t.toString();return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/tools${n?`?${n}`:""}`)}getToolSchema(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/tools/${encodeURIComponent(e)}/schema`)}authorize(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/authorize`,{method:"POST",body:e})}getAuthStatus(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/auth-status/${encodeURIComponent(e)}`)}getConnectionStatus(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connection-status`,{method:"POST",body:e})}listConnections(e){const t=new URLSearchParams;return t.set("toolkit",e.toolkit),e.authorId&&t.set("authorId",e.authorId),e.page!==void 0&&e.page!==null&&t.set("page",String(e.page)),e.perPage!==void 0&&e.perPage!==null&&t.set("perPage",String(e.perPage)),e.scope&&t.set("scope",e.scope),this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections?${t.toString()}`)}listConnectionFields(e){const t=new URLSearchParams;return t.set("toolkit",e.toolkit),this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connection-fields?${t.toString()}`)}disconnectConnection(e,t){const n=new URLSearchParams;t?.toolkit&&n.set("toolkit",t.toolkit),t?.force&&n.set("force","true");const r=n.toString();return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections/${encodeURIComponent(e)}${r?`?${r}`:""}`,{method:"DELETE"})}updateConnection(e,t){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections/${encodeURIComponent(e)}`,{method:"PATCH",body:t})}getConnectionUsage(e,t){const n=new URLSearchParams;t?.toolkit&&n.set("toolkit",t.toolkit);const r=n.toString();return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections/${encodeURIComponent(e)}/usage${r?`?${r}`:""}`)}getHealth(){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/health`)}},Lun=class extends qa{providerId;constructor(e,t){super(e),this.providerId=t}details(){return this.request(`/processor-providers/${encodeURIComponent(this.providerId)}`)}},zun=class extends qa{workspaceId;skillName;skillPath;basePath;pathQuery;constructor(e,t,n,r){super(e),this.workspaceId=t,this.skillName=n,this.skillPath=r,this.basePath=`/workspaces/${encodeURIComponent(this.workspaceId)}/skills/${encodeURIComponent(this.skillName)}`,this.pathQuery=this.skillPath?`?path=${encodeURIComponent(this.skillPath)}`:""}details(){return this.request(`${this.basePath}${this.pathQuery}`)}listReferences(){return this.request(`${this.basePath}/references${this.pathQuery}`)}getReference(e){return this.request(`${this.basePath}/references/${encodeURIComponent(e)}${this.pathQuery}`)}},Fun=class extends qa{workspaceId;constructor(t,n){super(t),this.workspaceId=n}get basePath(){return`/workspaces/${encodeURIComponent(this.workspaceId)}`}info(){return this.request(this.basePath)}readFile(t,n){const r=new URLSearchParams;return r.set("path",t),n&&r.set("encoding",n),this.request(`${this.basePath}/fs/read?${r.toString()}`)}writeFile(t,n,r){return this.request(`${this.basePath}/fs/write`,{method:"POST",body:{path:t,content:n,encoding:r?.encoding,recursive:r?.recursive}})}listFiles(t,n){const r=new URLSearchParams;return r.set("path",t),n!==void 0&&r.set("recursive",String(n)),this.request(`${this.basePath}/fs/list?${r.toString()}`)}delete(t,n){const r=new URLSearchParams;return r.set("path",t),n?.recursive!==void 0&&r.set("recursive",String(n.recursive)),n?.force!==void 0&&r.set("force",String(n.force)),this.request(`${this.basePath}/fs/delete?${r.toString()}`,{method:"DELETE"})}mkdir(t,n){return this.request(`${this.basePath}/fs/mkdir`,{method:"POST",body:{path:t,recursive:n}})}stat(t){const n=new URLSearchParams;return n.set("path",t),this.request(`${this.basePath}/fs/stat?${n.toString()}`)}search(t){const n=new URLSearchParams;return n.set("query",t.query),t.topK!==void 0&&n.set("topK",String(t.topK)),t.mode&&n.set("mode",t.mode),t.minScore!==void 0&&n.set("minScore",String(t.minScore)),this.request(`${this.basePath}/search?${n.toString()}`)}index(t){return this.request(`${this.basePath}/index`,{method:"POST",body:t})}listSkills(){return this.request(`${this.basePath}/skills`)}searchSkills(t){const n=new URLSearchParams;return n.set("query",t.query),t.topK!==void 0&&n.set("topK",String(t.topK)),t.minScore!==void 0&&n.set("minScore",String(t.minScore)),t.skillNames&&t.skillNames.length>0&&n.set("skillNames",t.skillNames.join(",")),t.includeReferences!==void 0&&n.set("includeReferences",String(t.includeReferences)),this.request(`${this.basePath}/skills/search?${n.toString()}`)}getSkill(t,n){return new zun(this.options,this.workspaceId,t,n)}},Bun=class extends qa{storedSkillId;constructor(e,t){super(e),this.storedSkillId=t}details(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}${cn(e)}`)}update(e,t){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}${cn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}${cn(e)}`,{method:"DELETE"})}favorite(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}/favorite${cn(e)}`,{method:"PUT"})}unfavorite(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}/favorite${cn(e)}`,{method:"DELETE"})}};function Uun(e){return e.flatMap(t=>t.type==="message"?t.content:[]).map(t=>typeof t?.text=="string"?t.text:"").filter(Boolean).join("")}function J9(e){return{...e,output_text:Uun(e.output)}}function qun(e){return e.type!=="message"?e:{...e,content:e.content??[]}}function Vun(e){return typeof e=="object"&&e!==null&&"response"in e&&(e.type==="response.created"||e.type==="response.in_progress"||e.type==="response.completed")?{...e,response:J9(e.response)}:typeof e=="object"&&e!==null&&"output"in e?J9(e):typeof e=="object"&&e!==null&&"item"in e&&(e.type==="response.output_item.added"||e.type==="response.output_item.done")?{...e,item:qun(e.item)}:e}function bDe(e){const t=e.replace(/\r\n/g,`
106
+ `):t;if(!r||r==="[DONE]")return{done:!0};let s;try{s=JSON.parse(r)}catch(a){throw new Error(`Failed to parse A2A stream event: ${a instanceof Error?a.message:"unknown parse error"}`)}if(s&&typeof s=="object"&&"error"in s&&s.error)throw new Tx(200,"OK",`A2A stream error - ${JSON.stringify(s.error)}`,s.error);return s&&typeof s=="object"&&"result"in s?{event:s.result}:{event:s}}async function*K9(e){const t=e.getReader(),n=new TextDecoder;let r="";try{for(;;){const{done:s,value:a}=await t.read();for(s?r+=n.decode():r+=n.decode(a,{stream:!0});;){const{eventBlock:i,rest:l}=yun(r);if(r=l,!i)break;const c=yDe(i);if(c.done)return;c.event&&(yield c.event)}if(s)break}if(r.trim()){const s=yDe(r);!s.done&&s.event&&(yield s.event)}}finally{t.releaseLock()}}const bun=["ES256","ES384","ES512","RS256","RS384","RS512","PS256","PS384","PS512"];function xun(e){const t=structuredClone(e);return delete t.signatures,t}function wun(e){const t=globalThis.CryptoKey;return typeof t<"u"&&e instanceof t}function Sun(e){return e.includes("-----BEGIN ")}function kun(e){return e.includes("-----BEGIN CERTIFICATE-----")}async function Oun(e,t){if(wun(e)||e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof e=="string"){if(t.startsWith("HS"))return new TextEncoder().encode(e);if(!Sun(e))throw new Error("Expected a PEM-encoded public key or certificate string for Agent Card verification");return kun(e)?bcn(e,t):ycn(e,t)}return xcn(e,t)}async function _un(e,t){const n=e.signatures??[];if(n.length===0)return e;const r=Ucn(xun(e));if(!r)throw new Tx(200,"OK","Failed to canonicalize A2A Agent Card for signature verification");const s=t.algorithms??[...bun],a=Vln(r),i=[];for(const[l,c]of n.entries())try{const u=`${c.protected}.${a}.${c.signature}`,d=Tcn(u);if(typeof d.alg!="string")throw new Error('Agent Card signature is missing a protected "alg" header');if(!s.includes(d.alg))throw new Error(`Agent Card signature algorithm "${d.alg}" is not allowed`);const f=await t.keyProvider({agentCard:e,signature:c,protectedHeader:d,alg:d.alg,kid:typeof d.kid=="string"?d.kid:void 0,jku:typeof d.jku=="string"?d.jku:void 0,index:l});if(!f)throw new Error("No verification key was provided for Agent Card signature verification");return await Ecn(u,await Oun(f,d.alg),{algorithms:s}),e}catch(u){i.push(u instanceof Error?u.message:"Unknown verification failure")}throw new Tx(200,"OK",`A2A Agent Card signature verification failed: ${i.join("; ")}`)}function Cun(e){const t=e.error,n=t?.message??"Unknown A2A JSON-RPC error";return typeof t?.code=="number"?new Uln(t.code,n,t.data):new Tx(200,"OK",`A2A JSON-RPC error - ${n}`,t)}function UE(e){if("error"in e&&e.error)throw Cun(e);if("result"in e)return e.result;throw new Tx(200,"OK","A2A JSON-RPC response did not include a result",e)}async function X9(e,t){if(e.body)return e.body;const n=Array.from(e.headers.entries()).map(([a,i])=>`${a}: ${i}`).join(", ");let r="";try{r=await e.text()}catch{}const s=[`A2A ${t} stream response did not include a body`,`(status: ${e.status} ${e.statusText})`,n?`headers: ${n}`:"",r?`body: ${r}`:""].filter(Boolean).join(" ");throw new Tx(e.status,e.statusText,s)}var Eun=class extends qa{agentId;constructor(e,t){super(e),this.agentId=t}async getAgentCard(e){const t=await this.request(`/.well-known/${this.agentId}/agent-card.json`);return e?.verifySignature?_un(t,e.verifySignature):t}async getCard(e){return this.getAgentCard(e)}async getExtendedAgentCard(){return UE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"agent/getAuthenticatedExtendedCard"}}))}async sendMessage(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/send",params:e}})}async*sendMessageStream(e){yield*K9(await X9(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/stream",params:e},stream:!0}),"message/stream"))}async sendStreamingMessage(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/stream",params:e},stream:!0})}async getTask(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/get",params:e}})}async cancelTask(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/cancel",params:e}})}async*resubscribeTask(e){yield*K9(await X9(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/resubscribe",params:e},stream:!0}),"tasks/resubscribe"))}async setTaskPushNotificationConfig(e){return UE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/set",params:e}}))}async getTaskPushNotificationConfig(e){return UE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/get",params:e}}))}async listTaskPushNotificationConfig(e){return UE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/list",params:e}}))}async deleteTaskPushNotificationConfig(e){UE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/delete",params:e}}))}},Tun=class extends qa{agentId;constructor(e,t){super(e),this.agentId=t}async rpc(e,t){return UE(await this.request(`/a2a/${this.agentId}`,{method:"POST",headers:{"A2A-Version":"1.0"},body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:e,params:t}}))}async getAgentCard(){const e=await this.request(`/.well-known/${this.agentId}/agent-card.json`,{headers:{"A2A-Version":"1.0"}});return Icn.fromJSON(e)}async sendMessage(e){const t=await this.rpc("message/send",uDe.toJSON(e));return Dcn.fromJSON(t)}async*sendMessageStream(e){const t=await this.request(`/a2a/${this.agentId}`,{method:"POST",headers:{"A2A-Version":"1.0"},body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/stream",params:uDe.toJSON(e)},stream:!0});for await(const n of K9(await X9(t,"message/stream")))yield dDe.fromJSON(n)}async getTask(e){const t=await this.rpc("tasks/get",Acn.toJSON(e));return u1.fromJSON(t)}async listTasks(e){const t=await this.rpc("tasks/list",Rcn.toJSON(e));return Pcn.fromJSON(t)}async cancelTask(e){const t=await this.rpc("tasks/cancel",$cn.toJSON(e));return u1.fromJSON(t)}async*resubscribeTask(e){const t=await this.request(`/a2a/${this.agentId}`,{method:"POST",headers:{"A2A-Version":"1.0"},body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/resubscribe",params:Mcn.toJSON(e)},stream:!0});for await(const n of K9(await X9(t,"tasks/resubscribe")))yield dDe.fromJSON(n)}},jun=class extends qa{serverId;toolId;constructor(e,t,n){super(e),this.serverId=t,this.toolId=n}details(e){return this.request(`/mcp/${encodeURIComponent(this.serverId)}/tools/${encodeURIComponent(this.toolId)}${cn(e)}`)}execute(e){const t={};return e.data!==void 0&&(t.data=e.data),e.requestContext!==void 0&&(t.requestContext=e.requestContext),this.request(`/mcp/${encodeURIComponent(this.serverId)}/tools/${encodeURIComponent(this.toolId)}/execute`,{method:"POST",body:t})}},Nun=class extends qa{actionId;constructor(e,t){super(e),this.actionId=t}transformWorkflowResult(e){return e.status==="success"?{success:e.result.success||!1,applied:e.result.applied||!1,branchName:e.result.branchName,message:e.result.message||"Agent builder action completed",validationResults:e.result.validationResults,error:e.result.error,errors:e.result.errors,stepResults:e.result.stepResults}:e.status==="failed"?{success:!1,applied:!1,message:`Agent builder action failed: ${e.error.message}`,error:e.error.message}:{success:!1,applied:!1,message:"Agent builder action was suspended",error:"Workflow suspended - manual intervention required"}}createRecordParserTransform(){return Idt()}async createRun(e){const t=new URLSearchParams;e?.runId&&t.set("runId",e.runId);const n=`/agent-builder/${this.actionId}/create-run${t.toString()?`?${t.toString()}`:""}`;return this.request(n,{method:"POST"})}async startAsync(e,t){const n=new URLSearchParams;t&&n.set("runId",t);const r=fr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/start-async${n.toString()?`?${n.toString()}`:""}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:r}});return this.transformWorkflowResult(l)}async startActionRun(e,t){const n=new URLSearchParams;n.set("runId",t);const r=fr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/start?${n.toString()}`;return this.request(i,{method:"POST",body:{...a,requestContext:r}})}async resume(e,t){const n=new URLSearchParams;n.set("runId",t);const r=fr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/resume?${n.toString()}`;return this.request(i,{method:"POST",body:{...a,requestContext:r}})}async resumeAsync(e,t){const n=new URLSearchParams;n.set("runId",t);const r=fr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/resume-async?${n.toString()}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:r}});return this.transformWorkflowResult(l)}async stream(e,t){if(!t)throw new Error("runId is required to stream an agent builder action");const n=new URLSearchParams;n.set("runId",t);const r=fr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/stream?${n.toString()}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:r},stream:!0});if(!l.ok)throw new Error(`Failed to stream agent builder action: ${l.statusText}`);if(!l.body)throw new Error("Response body is null");return l.body.pipeThrough(this.createRecordParserTransform())}async observeStream(e){const t=new URLSearchParams;t.set("runId",e.runId);const n=`/agent-builder/${this.actionId}/observe?${t.toString()}`,r=await this.request(n,{method:"POST",stream:!0});if(!r.ok)throw new Error(`Failed to observe agent builder action stream: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createRecordParserTransform())}async observeStreamLegacy(e){const t=new URLSearchParams;t.set("runId",e.runId);const n=`/agent-builder/${this.actionId}/observe-stream-legacy?${t.toString()}`,r=await this.request(n,{method:"POST",stream:!0});if(!r.ok)throw new Error(`Failed to observe agent builder action stream legacy: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createRecordParserTransform())}async resumeStream(e){const t=new URLSearchParams;t.set("runId",e.runId);const n=fr(e.requestContext),{runId:r,requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/resume-stream?${t.toString()}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:n},stream:!0});if(!l.ok)throw new Error(`Failed to resume agent builder action stream: ${l.statusText}`);if(!l.body)throw new Error("Response body is null");return l.body.pipeThrough(this.createRecordParserTransform())}async runById(e,t){const n=new URLSearchParams;t?.fields&&t.fields.length>0&&n.set("fields",t.fields.join(",")),t?.withNestedWorkflows!==void 0&&n.set("withNestedWorkflows",String(t.withNestedWorkflows));const r=n.size>0?`?${n.toString()}`:"",s=`/agent-builder/${this.actionId}/runs/${e}${r}`;return this.request(s,{method:"GET"})}async details(){return await this.request(`/agent-builder/${this.actionId}`)}async runs(e){const t=new URLSearchParams;e?.fromDate&&t.set("fromDate",e.fromDate.toISOString()),e?.toDate&&t.set("toDate",e.toDate.toISOString()),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.page!==void 0&&t.set("page",String(e.page)),e?.limit!==null&&e?.limit!==void 0&&(e.limit===!1?t.set("limit","false"):typeof e.limit=="number"&&e.limit>0&&Number.isInteger(e.limit)&&t.set("limit",String(e.limit))),e?.offset!==null&&e?.offset!==void 0&&!isNaN(Number(e?.offset))&&t.set("offset",String(e.offset)),e?.resourceId&&t.set("resourceId",e.resourceId);const n=`/agent-builder/${this.actionId}/runs${t.toString()?`?${t.toString()}`:""}`;return this.request(n,{method:"GET"})}async cancelRun(e){const t=`/agent-builder/${this.actionId}/runs/${e}/cancel`;return this.request(t,{method:"POST"})}},Iun=class extends qa{constructor(e){super(e)}getTrace(e){return this.request(`/observability/traces/${e}`)}getTraceLight(e){return this.request(`/observability/traces/${e}/light`)}getSpan(e,t){return this.request(`/observability/traces/${e}/spans/${t}`)}getTraceTrajectory(e){return this.request(`/observability/traces/${e}/trajectory`)}getTraces(e){const{pagination:t,filters:n}=e,{page:r,perPage:s,dateRange:a}=t||{},{name:i,spanType:l,entityId:c,entityType:u}=n||{},d=new URLSearchParams;if(r!==void 0&&d.set("page",String(r)),s!==void 0&&d.set("perPage",String(s)),i&&d.set("name",i),l!==void 0&&d.set("spanType",String(l)),c&&u&&(d.set("entityId",c),d.set("entityType",u)),a){const p=JSON.stringify({start:a.start instanceof Date?a.start.toISOString():a.start,end:a.end instanceof Date?a.end.toISOString():a.end});d.set("dateRange",p)}const f=d.toString();return this.request(`/observability/traces${f?`?${f}`:""}`)}listTraces(e={}){const t=sf(e,["filters","pagination","orderBy"]);return this.request(`/observability/traces${t?`?${t}`:""}`)}listTracesLight(e={}){const t=sf(e,["filters","pagination","orderBy"]);return this.request(`/observability/traces/light${t?`?${t}`:""}`)}listBranches(e={}){const t=sf(e,["filters","pagination","orderBy"]);return this.request(`/observability/branches${t?`?${t}`:""}`)}getBranch(e){const{traceId:t,spanId:n,depth:r}=e,s=r!==void 0?`?depth=${r}`:"";return this.request(`/observability/traces/${encodeURIComponent(t)}/branches/${encodeURIComponent(n)}${s}`)}listScoresBySpan(e){const{traceId:t,spanId:n,...r}=e,s=sf(r);return this.request(`/observability/traces/${encodeURIComponent(t)}/${encodeURIComponent(n)}/scores${s?`?${s}`:""}`)}score(e){return this.request("/observability/traces/score",{method:"POST",body:{...e}})}listLogs(e={}){const t=sf(e,["filters","pagination","orderBy"]);return this.request(`/observability/logs${t?`?${t}`:""}`)}listScores(e={}){const t=sf(e,["filters","pagination","orderBy"]);return this.request(`/observability/scores${t?`?${t}`:""}`)}createScore(e){return this.request("/observability/scores",{method:"POST",body:e})}getScoreAggregate(e){return this.request("/observability/scores/aggregate",{method:"POST",body:e})}getScoreBreakdown(e){return this.request("/observability/scores/breakdown",{method:"POST",body:e})}getScoreTimeSeries(e){return this.request("/observability/scores/timeseries",{method:"POST",body:e})}getScorePercentiles(e){return this.request("/observability/scores/percentiles",{method:"POST",body:e})}listFeedback(e={}){const t=sf(e,["filters","pagination","orderBy"]);return this.request(`/observability/feedback${t?`?${t}`:""}`)}createFeedback(e){return this.request("/observability/feedback",{method:"POST",body:e})}getFeedbackAggregate(e){return this.request("/observability/feedback/aggregate",{method:"POST",body:e})}getFeedbackBreakdown(e){return this.request("/observability/feedback/breakdown",{method:"POST",body:e})}getFeedbackTimeSeries(e){return this.request("/observability/feedback/timeseries",{method:"POST",body:e})}getFeedbackPercentiles(e){return this.request("/observability/feedback/percentiles",{method:"POST",body:e})}getMetricAggregate(e){return this.request("/observability/metrics/aggregate",{method:"POST",body:e})}getMetricBreakdown(e){return this.request("/observability/metrics/breakdown",{method:"POST",body:e})}getMetricTimeSeries(e){return this.request("/observability/metrics/timeseries",{method:"POST",body:e})}getMetricPercentiles(e){return this.request("/observability/metrics/percentiles",{method:"POST",body:e})}getMetricNames(e={}){const t=sf(e);return this.request(`/observability/discovery/metric-names${t?`?${t}`:""}`)}getMetricLabelKeys(e){const t=sf(e);return this.request(`/observability/discovery/metric-label-keys${t?`?${t}`:""}`)}getMetricLabelValues(e){const t=sf(e);return this.request(`/observability/discovery/metric-label-values${t?`?${t}`:""}`)}getEntityTypes(){return this.request("/observability/discovery/entity-types")}getEntityNames(e={}){const t=sf(e);return this.request(`/observability/discovery/entity-names${t?`?${t}`:""}`)}getServiceNames(){return this.request("/observability/discovery/service-names")}getEnvironments(){return this.request("/observability/discovery/environments")}getTags(e={}){const t=sf(e);return this.request(`/observability/discovery/tags${t?`?${t}`:""}`)}},Aun=class extends qa{storedAgentId;constructor(e,t){super(e),this.storedAgentId=t}details(e,t){const n=cn(e),r=t?.status?`status=${t.status}`:"",s=`/stored/agents/${encodeURIComponent(this.storedAgentId)}${n}${r?`${n?"&":"?"}${r}`:""}`;return this.request(s)}update(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}${cn(t)}`,{method:"PATCH",body:e})}export(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/export`,{method:"POST",body:e})}openChangeRequest(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/change-request`,{method:"POST",body:e})}delete(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}${cn(e)}`,{method:"DELETE"})}dependents(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/dependents${cn(e)}`)}favorite(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/favorite${cn(e)}`,{method:"PUT"})}unfavorite(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/favorite${cn(e)}`,{method:"DELETE"})}listVersions(e,t){const n=new URLSearchParams;e?.page!==void 0&&n.set("page",String(e.page)),e?.perPage!==void 0&&n.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&n.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&n.set("orderBy[direction]",e.orderBy.direction));const r=n.toString(),s=cn(t);return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions${r?`?${r}`:""}${s?`${r?"&":"?"}${s.slice(1)}`:""}`)}createVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions${cn(t)}`,{method:"POST",body:e||{}})}getVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}${cn(t)}`)}activateVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}/activate${cn(t)}`,{method:"POST"})}restoreVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}/restore${cn(t)}`,{method:"POST"})}deleteVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}${cn(t)}`,{method:"DELETE"})}compareVersions(e,t,n){const r=new URLSearchParams;r.set("from",e),r.set("to",t);const s=cn(n);return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/compare?${r.toString()}${s?`&${s.slice(1)}`:""}`)}},Run=class extends qa{dynamicWorkflowId;constructor(e,t){super(e),this.dynamicWorkflowId=t}details(){return this.request(`/stored/workflows/${encodeURIComponent(this.dynamicWorkflowId)}`)}delete(){return this.request(`/stored/workflows/${encodeURIComponent(this.dynamicWorkflowId)}`,{method:"DELETE"})}},Pun=class extends qa{storedPromptBlockId;constructor(e,t){super(e),this.storedPromptBlockId=t}details(e,t){const n=cn(e),r=t?.status?`status=${t.status}`:"",s=`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}${n}${r?`${n?"&":"?"}${r}`:""}`;return this.request(s)}update(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}${cn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}${cn(e)}`,{method:"DELETE"})}listVersions(e,t){const n=new URLSearchParams;e?.page!==void 0&&n.set("page",String(e.page)),e?.perPage!==void 0&&n.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&n.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&n.set("orderBy[direction]",e.orderBy.direction));const r=n.toString(),s=cn(t,r?"&":"?");return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions${r?`?${r}`:""}${s}`)}createVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions${cn(t)}`,{method:"POST",body:e||{}})}getVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}${cn(t)}`)}activateVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}/activate${cn(t)}`,{method:"POST"})}restoreVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}/restore${cn(t)}`,{method:"POST"})}deleteVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}${cn(t)}`,{method:"DELETE"})}compareVersions(e,t,n){const r=new URLSearchParams;r.set("from",e),r.set("to",t);const s=cn(n,"&");return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/compare?${r.toString()}${s}`)}},$un=class extends qa{storedMCPClientId;constructor(e,t){super(e),this.storedMCPClientId=t}details(e){return this.request(`/stored/mcp-clients/${encodeURIComponent(this.storedMCPClientId)}${cn(e)}`)}update(e,t){return this.request(`/stored/mcp-clients/${encodeURIComponent(this.storedMCPClientId)}${cn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/mcp-clients/${encodeURIComponent(this.storedMCPClientId)}${cn(e)}`,{method:"DELETE"})}},Mun=class extends qa{storedScorerId;constructor(e,t){super(e),this.storedScorerId=t}details(e,t){const n=cn(e),r=t?.status?`status=${t.status}`:"",s=n?"&":"?",a=`/stored/scorers/${encodeURIComponent(this.storedScorerId)}${n}${r?`${n?s:"?"}${r}`:""}`;return this.request(a)}update(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}${cn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}${cn(e)}`,{method:"DELETE"})}listVersions(e,t){const n=new URLSearchParams;e?.page!==void 0&&n.set("page",String(e.page)),e?.perPage!==void 0&&n.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&n.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&n.set("orderBy[direction]",e.orderBy.direction));const r=n.toString(),s=cn(t);return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions${r?`?${r}`:""}${s?`${r?"&":"?"}${s.slice(1)}`:""}`)}createVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions${cn(t)}`,{method:"POST",body:e||{}})}getVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}${cn(t)}`)}activateVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}/activate${cn(t)}`,{method:"POST"})}restoreVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}/restore${cn(t)}`,{method:"POST"})}deleteVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}${cn(t)}`,{method:"DELETE"})}compareVersions(e,t,n){const r=new URLSearchParams;r.set("from",e),r.set("to",t);const s=cn(n);return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/compare?${r.toString()}${s?`&${s.slice(1)}`:""}`)}},Dun=class extends qa{providerId;constructor(e,t){super(e),this.providerId=t}listToolkits(){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/toolkits`)}listTools(e){const t=new URLSearchParams;e?.toolkit&&t.set("toolkit",e.toolkit),e?.search&&t.set("search",e.search),e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage));const n=t.toString();return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/tools${n?`?${n}`:""}`)}getToolSchema(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/tools/${encodeURIComponent(e)}/schema`)}authorize(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/authorize`,{method:"POST",body:e})}getAuthStatus(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/auth-status/${encodeURIComponent(e)}`)}getConnectionStatus(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connection-status`,{method:"POST",body:e})}listConnections(e){const t=new URLSearchParams;return t.set("toolkit",e.toolkit),e.authorId&&t.set("authorId",e.authorId),e.page!==void 0&&e.page!==null&&t.set("page",String(e.page)),e.perPage!==void 0&&e.perPage!==null&&t.set("perPage",String(e.perPage)),e.scope&&t.set("scope",e.scope),this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections?${t.toString()}`)}listConnectionFields(e){const t=new URLSearchParams;return t.set("toolkit",e.toolkit),this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connection-fields?${t.toString()}`)}disconnectConnection(e,t){const n=new URLSearchParams;t?.toolkit&&n.set("toolkit",t.toolkit),t?.force&&n.set("force","true");const r=n.toString();return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections/${encodeURIComponent(e)}${r?`?${r}`:""}`,{method:"DELETE"})}updateConnection(e,t){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections/${encodeURIComponent(e)}`,{method:"PATCH",body:t})}getConnectionUsage(e,t){const n=new URLSearchParams;t?.toolkit&&n.set("toolkit",t.toolkit);const r=n.toString();return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections/${encodeURIComponent(e)}/usage${r?`?${r}`:""}`)}getHealth(){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/health`)}},Lun=class extends qa{providerId;constructor(e,t){super(e),this.providerId=t}details(){return this.request(`/processor-providers/${encodeURIComponent(this.providerId)}`)}},zun=class extends qa{workspaceId;skillName;skillPath;basePath;pathQuery;constructor(e,t,n,r){super(e),this.workspaceId=t,this.skillName=n,this.skillPath=r,this.basePath=`/workspaces/${encodeURIComponent(this.workspaceId)}/skills/${encodeURIComponent(this.skillName)}`,this.pathQuery=this.skillPath?`?path=${encodeURIComponent(this.skillPath)}`:""}details(){return this.request(`${this.basePath}${this.pathQuery}`)}listReferences(){return this.request(`${this.basePath}/references${this.pathQuery}`)}getReference(e){return this.request(`${this.basePath}/references/${encodeURIComponent(e)}${this.pathQuery}`)}},Fun=class extends qa{workspaceId;constructor(t,n){super(t),this.workspaceId=n}get basePath(){return`/workspaces/${encodeURIComponent(this.workspaceId)}`}info(){return this.request(this.basePath)}readFile(t,n){const r=new URLSearchParams;return r.set("path",t),n&&r.set("encoding",n),this.request(`${this.basePath}/fs/read?${r.toString()}`)}writeFile(t,n,r){return this.request(`${this.basePath}/fs/write`,{method:"POST",body:{path:t,content:n,encoding:r?.encoding,recursive:r?.recursive}})}listFiles(t,n){const r=new URLSearchParams;return r.set("path",t),n!==void 0&&r.set("recursive",String(n)),this.request(`${this.basePath}/fs/list?${r.toString()}`)}delete(t,n){const r=new URLSearchParams;return r.set("path",t),n?.recursive!==void 0&&r.set("recursive",String(n.recursive)),n?.force!==void 0&&r.set("force",String(n.force)),this.request(`${this.basePath}/fs/delete?${r.toString()}`,{method:"DELETE"})}mkdir(t,n){return this.request(`${this.basePath}/fs/mkdir`,{method:"POST",body:{path:t,recursive:n}})}stat(t){const n=new URLSearchParams;return n.set("path",t),this.request(`${this.basePath}/fs/stat?${n.toString()}`)}search(t){const n=new URLSearchParams;return n.set("query",t.query),t.topK!==void 0&&n.set("topK",String(t.topK)),t.mode&&n.set("mode",t.mode),t.minScore!==void 0&&n.set("minScore",String(t.minScore)),this.request(`${this.basePath}/search?${n.toString()}`)}index(t){return this.request(`${this.basePath}/index`,{method:"POST",body:t})}listSkills(){return this.request(`${this.basePath}/skills`)}searchSkills(t){const n=new URLSearchParams;return n.set("query",t.query),t.topK!==void 0&&n.set("topK",String(t.topK)),t.minScore!==void 0&&n.set("minScore",String(t.minScore)),t.skillNames&&t.skillNames.length>0&&n.set("skillNames",t.skillNames.join(",")),t.includeReferences!==void 0&&n.set("includeReferences",String(t.includeReferences)),this.request(`${this.basePath}/skills/search?${n.toString()}`)}getSkill(t,n){return new zun(this.options,this.workspaceId,t,n)}},Bun=class extends qa{storedSkillId;constructor(e,t){super(e),this.storedSkillId=t}details(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}${cn(e)}`)}update(e,t){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}${cn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}${cn(e)}`,{method:"DELETE"})}favorite(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}/favorite${cn(e)}`,{method:"PUT"})}unfavorite(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}/favorite${cn(e)}`,{method:"DELETE"})}};function Uun(e){return e.flatMap(t=>t.type==="message"?t.content:[]).map(t=>typeof t?.text=="string"?t.text:"").filter(Boolean).join("")}function J9(e){return{...e,output_text:Uun(e.output)}}function qun(e){return e.type!=="message"?e:{...e,content:e.content??[]}}function Vun(e){return typeof e=="object"&&e!==null&&"response"in e&&(e.type==="response.created"||e.type==="response.in_progress"||e.type==="response.completed")?{...e,response:J9(e.response)}:typeof e=="object"&&e!==null&&"output"in e?J9(e):typeof e=="object"&&e!==null&&"item"in e&&(e.type==="response.output_item.added"||e.type==="response.output_item.done")?{...e,item:qun(e.item)}:e}function bDe(e){const t=e.replace(/\r\n/g,`
107
107
  `).trim();if(!t)return null;const n=t.split(`
108
108
  `).filter(s=>s.startsWith("data:")).map(s=>s.slice(5).trim());if(!n.length)return null;const r=n.join(`
109
109
  `);return r==="[DONE]"?null:Vun(JSON.parse(r))}var Hun=class{response;constructor(e){this.response=e}asResponse(){return this.response}async*[Symbol.asyncIterator](){if(!this.response.body)return;const e=this.response.body.getReader(),t=new TextDecoder;let n="",r=!1;try{for(;;){const{done:a,value:i}=await e.read();n+=t.decode(i??new Uint8Array,{stream:!a});let l=n.indexOf(`
@@ -114,7 +114,7 @@ ${n}
114
114
  \r
115
115
  `),length:4},{index:k.indexOf(`
116
116
 
117
- `),length:2},{index:k.indexOf("\r\r"),length:2}].filter(_=>_.index!==-1);return C.length===0?null:C.reduce((_,E)=>E.index<_.index?E:_)},m=async k=>{const C=k.body.getReader();i=C;const _=new TextDecoder;let E="";try{for(;!a;){const{done:T,value:N}=await C.read();if(T)return a?{kind:"cancelled"}:{kind:"done"};E+=_.decode(N,{stream:!0});let I;for(;(I=h(E))!==null;){const A=E.slice(0,I.index);E=E.slice(I.index+I.length);for(const R of A.split(/\r\n|\n|\r/)){if(!R.startsWith("data:"))continue;const L=R.slice(5).trim();if(!L)continue;let D;try{D=Gun(JSON.parse(L))}catch{continue}try{e.onEvent(D)}catch(z){return a||g(z),{kind:"consumer_error"}}}}}return{kind:"cancelled"}}catch(T){return a?{kind:"cancelled"}:{kind:"transport_error",error:T}}finally{i===C&&(i=null),C.cancel().catch(()=>{})}},g=k=>{try{e.onError?.(k)}catch{}},y=k=>{g(k.kind==="transport_error"?k.error:p())},b=async k=>{try{return await m(k)}catch(C){return a?{kind:"cancelled"}:{kind:"transport_error",error:C}}},x=await f();return(async k=>{let C=k;for(;!a;){let _=await b(C);if(a||_.kind==="cancelled"||_.kind==="consumer_error")return;if(!r){y(_);return}let E=0,T;for(;!T;){if(E>=r.maxRetries){y(_);return}if(E++,await d(s(E)),a)return;try{T=await f()}catch(N){_={kind:"transport_error",error:N}}}if(a){T.body?.cancel().catch(()=>{});return}C=T;try{e.onReconnect?.()}catch{}}})(x),{unsubscribe:()=>{a=!0,u(),i?.cancel().catch(()=>{})}}}async sendMessage(e,t){const{content:n,files:r}=typeof e=="string"?{content:e,files:void 0}:e,s=fr(t?.requestContext);await this.request(this.url(`${this.base()}/messages`),{method:"POST",body:{message:n,...r?.length?{files:r}:{},...s?{requestContext:s}:{}}})}async abort(){await this.request(this.url(`${this.base()}/abort`),{method:"POST"})}async approveTool(e,t,n){const r=fr(n?.requestContext);await this.request(this.url(`${this.base()}/tool-approval`),{method:"POST",body:{toolCallId:e,approved:t,...r?{requestContext:r}:{}}})}async respondToToolSuspension(e,t,n){const r=fr(n?.requestContext);await this.request(this.url(`${this.base()}/tool-suspension`),{method:"POST",body:{toolCallId:e,resumeData:t,...r?{requestContext:r}:{}}})}async steer(e,t){const n=fr(t?.requestContext);await this.request(this.url(`${this.base()}/steer`),{method:"POST",body:{message:e,...n?{requestContext:n}:{}}})}state(){return this.request(this.url(this.base()))}async setState(e){await this.request(this.url(`${this.base()}/state`),{method:"PUT",body:{state:e}})}async switchMode(e){await this.request(this.url(`${this.base()}/mode`),{method:"POST",body:{modeId:e}})}async switchModel(e,t){await this.request(this.url(`${this.base()}/model`),{method:"POST",body:{modelId:e,scope:t?.scope,modeId:t?.modeId}})}async listThreads(e){const t=typeof e=="number"?{limit:e}:e??{},n=new URLSearchParams;t.limit!=null&&n.set("limit",String(t.limit)),t.tags&&Object.keys(t.tags).length>0&&n.set("tags",JSON.stringify(t.tags));const r=n.toString()?`?${n.toString()}`:"";return(await this.request(this.url(`${this.base()}/threads${r}`))).threads}async switchThread(e){await this.request(this.url(`${this.base()}/thread`),{method:"POST",body:{threadId:e}})}async createThread(e){return this.request(this.url(`${this.base()}/threads`),{method:"POST",body:{title:e}})}async deleteThread(e){await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(e)}`),{method:"DELETE"})}async renameThread(e,t){await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(e)}`),{method:"PUT",body:{title:t}})}async cloneThread(e){return this.request(this.url(`${this.base()}/threads/clone`),{method:"POST",body:e??{}})}async listMessages(e,t){const n=t!=null?`?limit=${t}`:"";return(await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(e)}/messages${n}`))).messages.map(Adt)}async followUp(e,t){const n=fr(t?.requestContext);await this.request(this.url(`${this.base()}/follow-up`),{method:"POST",body:{message:e,...n?{requestContext:n}:{}}})}async getOMRecord(){return(await this.request(this.url(`${this.base()}/om`))).record}async setResourceId(e){await this.request(this.url(`${this.base()}/resource`),{method:"POST",body:{newResourceId:e}})}async getResourceIds(){return(await this.request(this.url(`${this.base()}/resources`))).resourceIds}async getGoal(){return(await this.request(this.url(`${this.base()}/goal`))).goal}async setGoal(e,t){return(await this.request(this.url(`${this.base()}/goal`),{method:"POST",body:{objective:e,...t}})).goal}async updateGoal(e){return(await this.request(this.url(`${this.base()}/goal`),{method:"PUT",body:e})).goal}async clearGoal(){await this.request(this.url(`${this.base()}/goal`),{method:"DELETE"})}async getPermissions(){return this.request(this.url(`${this.base()}/permissions`))}async setPermissionForCategory(e,t){await this.request(this.url(`${this.base()}/permissions/category`),{method:"PUT",body:{category:e,policy:t}})}async setPermissionForTool(e,t){await this.request(this.url(`${this.base()}/permissions/tool`),{method:"PUT",body:{toolName:e,policy:t}})}async sendNotification(e){return this.request(this.url(`${this.base()}/notifications`),{method:"POST",body:e})}},Yun=class extends qa{controllerId;constructor(e,t){super(e),this.controllerId=t}basePath(){return`/agent-controller/${encodeURIComponent(this.controllerId)}`}async listModes(){return(await this.request(`${this.basePath()}/modes`)).modes}async listModels(){return(await this.request(`${this.basePath()}/models`)).models}async workspaceStatus(){return this.request(`${this.basePath()}/workspace`)}session(e,t){return new Qun(this.options,this.controllerId,e,t)}},CP=class extends qa{observability;conversations;responses;channels;constructor(e){super(e),this.observability=new Iun(e),this.conversations=new pun(e),this.responses=new Wun(e),this.channels=new Zun(e)}listAgents(e,t){const n=yw(fr(e)),r=new URLSearchParams;n&&r.set("requestContext",n),t&&r.set("partial","true");const s=r.toString();return this.request(`/agents${s?`?${s}`:""}`)}listAgentsModelProviders(){return this.request("/agents/providers")}getAgent(e,t){return new iun(this.options,e,t)}async listAgentControllers(){return(await this.request("/agent-controller")).agentControllers}getAgentController(e){return new Yun(this.options,e)}async listMemoryThreads(e={}){const t=new URLSearchParams;e.resourceId&&t.set("resourceId",e.resourceId),e.metadata&&t.set("metadata",JSON.stringify(e.metadata)),e.agentId&&t.set("agentId",e.agentId),e.page!==void 0&&t.set("page",e.page.toString()),e.perPage!==void 0&&t.set("perPage",e.perPage.toString()),e.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction));const n=t.toString(),r=await this.request(`/memory/threads${n?`?${n}`:""}${cn(e.requestContext,n?"&":"?")}`);return"threads"in r?r:{threads:r,total:r.length,page:e.page??0,perPage:e.perPage??100,hasMore:!1}}getMemoryConfig(e){return this.request(`/memory/config?agentId=${e.agentId}${cn(e.requestContext,"&")}`)}createMemoryThread(e){return this.request(`/memory/threads?agentId=${e.agentId}${cn(e.requestContext,"&")}`,{method:"POST",body:e})}getMemoryThread({threadId:e,agentId:t}){return new oun(this.options,e,t)}listThreadMessages(e,t={}){let n="";const r=t.includeSystemReminders===void 0?"":`includeSystemReminders=${t.includeSystemReminders}`;return t.networkId?n=`/memory/network/threads/${e}/messages?networkId=${t.networkId}${r?`&${r}`:""}${cn(t.requestContext,"&")}`:t.agentId?n=`/memory/threads/${e}/messages?agentId=${t.agentId}${r?`&${r}`:""}${cn(t.requestContext,"&")}`:n=`/memory/threads/${e}/messages${r?`?${r}`:""}${cn(t.requestContext,r?"&":"?")}`,this.request(n)}deleteThread(e,t){if(!t||!!t.agentId==!!t.networkId)throw new Error("MastraClient.deleteThread() requires exactly one of agentId or networkId. The server cannot resolve which memory store owns the thread without one, and passing both is ambiguous.");const n=t.agentId?`/memory/threads/${e}?agentId=${t.agentId}${cn(t.requestContext,"&")}`:`/memory/network/threads/${e}?networkId=${t.networkId}${cn(t.requestContext,"&")}`;return this.request(n,{method:"DELETE"})}saveMessageToMemory(e){return this.request(`/memory/save-messages?agentId=${e.agentId}${cn(e.requestContext,"&")}`,{method:"POST",body:e})}getMemoryStatus(e,t,n){const r=new URLSearchParams({agentId:e});n?.resourceId&&r.set("resourceId",n.resourceId),n?.threadId&&r.set("threadId",n.threadId);const s=r.toString();return this.request(`/memory/status?${s}${cn(t,"&")}`)}getObservationalMemory(e){const t=new URLSearchParams({agentId:e.agentId});e.resourceId&&t.set("resourceId",e.resourceId),e.threadId&&t.set("threadId",e.threadId),e.from&&t.set("from",e.from instanceof Date?e.from.toISOString():e.from),e.to&&t.set("to",e.to instanceof Date?e.to.toISOString():e.to),e.offset!=null&&t.set("offset",String(e.offset)),e.limit!=null&&t.set("limit",String(e.limit));const n=t.toString();return this.request(`/memory/observational-memory?${n}${cn(e.requestContext,"&")}`)}awaitBufferStatus(e){return this.request(`/memory/observational-memory/buffer-status${cn(e.requestContext)}`,{method:"POST",body:{agentId:e.agentId,resourceId:e.resourceId,threadId:e.threadId}})}listTools(e){const t=yw(fr(e)),n=new URLSearchParams;t&&n.set("requestContext",t);const r=n.toString();return this.request(`/tools${r?`?${r}`:""}`)}getTool(e){return new uun(this.options,e)}listProcessors(e){const t=yw(fr(e)),n=new URLSearchParams;t&&n.set("requestContext",t);const r=n.toString();return this.request(`/processors${r?`?${r}`:""}`)}getProcessor(e){return new dun(this.options,e)}listWorkflows(e,t){const n=yw(fr(e)),r=new URLSearchParams;n&&r.set("requestContext",n),t&&r.set("partial","true");const s=r.toString();return this.request(`/workflows${s?`?${s}`:""}`)}listWorkflowRunCounts(e){const t=yw(fr(e)),n=new URLSearchParams;t&&n.set("requestContext",t);const r=n.toString();return this.request(`/workflows/run-counts${r?`?${r}`:""}`)}getWorkflow(e){return new vun(this.options,e)}getAgentBuilderActions(){return this.request("/agent-builder")}getAgentBuilderAction(e){return new Nun(this.options,e)}getVector(e){return new cun(this.options,e)}listLogs(e){const{transportId:t,fromDate:n,toDate:r,logLevel:s,filters:a,page:i,perPage:l}=e,c=a?Object.entries(a).map(([d,f])=>`${d}:${f}`):[],u=new URLSearchParams;if(t&&u.set("transportId",t),n&&u.set("fromDate",n.toISOString()),r&&u.set("toDate",r.toISOString()),s&&u.set("logLevel",s),i!==void 0&&u.set("page",String(i)),l!==void 0&&u.set("perPage",String(l)),c)if(Array.isArray(c))for(const d of c)u.append("filters",d);else u.set("filters",c);return u.size?this.request(`/logs?${u}`):this.request("/logs")}getLogForRun(e){const{runId:t,transportId:n,fromDate:r,toDate:s,logLevel:a,filters:i,page:l,perPage:c}=e,u=i?Object.entries(i).map(([f,p])=>`${f}:${p}`):[],d=new URLSearchParams;if(t&&d.set("runId",t),n&&d.set("transportId",n),r&&d.set("fromDate",r.toISOString()),s&&d.set("toDate",s.toISOString()),a&&d.set("logLevel",a),l!==void 0&&d.set("page",String(l)),c!==void 0&&d.set("perPage",String(c)),u)if(Array.isArray(u))for(const f of u)d.append("filters",f);else d.set("filters",u);return d.size?this.request(`/logs/${t}?${d}`):this.request(`/logs/${t}`)}listLogTransports(){return this.request("/logs/transports")}getMcpServers(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));const n=t.toString();return this.request(`/mcp/v0/servers${n?`?${n}`:""}`)}getMcpServerDetails(e,t){const n=new URLSearchParams;t?.version&&n.set("version",t.version);const r=n.toString();return this.request(`/mcp/v0/servers/${e}${r?`?${r}`:""}`)}getMcpServerTools(e){return this.request(`/mcp/${e}/tools`)}getMcpServerTool(e,t){return new jun(this.options,e,t)}getMcpServerResources(e){return this.request(`/mcp/${encodeURIComponent(e)}/resources`)}readMcpServerResource(e,t){return this.request(`/mcp/${encodeURIComponent(e)}/resources/read`,{method:"POST",body:{uri:t}})}getA2A(e){return new Eun(this.options,e)}getA2AV1(e){return new Tun(this.options,e)}getWorkingMemory({agentId:e,threadId:t,resourceId:n,requestContext:r}){return this.request(`/memory/threads/${t}/working-memory?agentId=${e}&resourceId=${n}${cn(r,"&")}`)}searchMemory({agentId:e,resourceId:t,threadId:n,searchQuery:r,memoryConfig:s,requestContext:a}){const i=new URLSearchParams({searchQuery:r,resourceId:t,agentId:e});return n&&i.append("threadId",n),s&&i.append("memoryConfig",JSON.stringify(s)),this.request(`/memory/search?${i}${cn(a,"&")}`)}updateWorkingMemory({agentId:e,threadId:t,workingMemory:n,resourceId:r,requestContext:s}){return this.request(`/memory/threads/${t}/working-memory?agentId=${e}${cn(s,"&")}`,{method:"POST",body:{workingMemory:n,resourceId:r}})}listScorers(e){return this.request(`/scores/scorers${cn(e)}`)}getScorer(e){return this.request(`/scores/scorers/${encodeURIComponent(e)}`)}listScoresByScorerId(e){const{page:t,perPage:n,scorerId:r,entityId:s,entityType:a}=e,i=new URLSearchParams;s&&i.set("entityId",s),a&&i.set("entityType",a),t!==void 0&&i.set("page",String(t)),n!==void 0&&i.set("perPage",String(n));const l=i.toString();return this.request(`/scores/scorer/${encodeURIComponent(r)}${l?`?${l}`:""}`)}listScoresByRunId(e){const{runId:t,page:n,perPage:r}=e,s=new URLSearchParams;n!==void 0&&s.set("page",String(n)),r!==void 0&&s.set("perPage",String(r));const a=s.toString();return this.request(`/scores/run/${encodeURIComponent(t)}${a?`?${a}`:""}`)}listScoresByEntityId(e){const{entityId:t,entityType:n,page:r,perPage:s}=e,a=new URLSearchParams;r!==void 0&&a.set("page",String(r)),s!==void 0&&a.set("perPage",String(s));const i=a.toString();return this.request(`/scores/entity/${encodeURIComponent(n)}/${encodeURIComponent(t)}${i?`?${i}`:""}`)}saveScore(e){return this.request("/scores",{method:"POST",body:e})}getTrace(e){return this.observability.getTrace(e)}getTraceLight(e){return this.observability.getTraceLight(e)}getSpan(e,t){return this.observability.getSpan(e,t)}getTraceTrajectory(e){return this.observability.getTraceTrajectory(e)}getTraces(e){return this.observability.getTraces(e)}listTraces(e={}){return this.observability.listTraces(e)}listTracesLight(e={}){return this.observability.listTracesLight(e)}listBranches(e={}){return this.observability.listBranches(e)}getBranch(e){return this.observability.getBranch(e)}listScoresBySpan(e){return this.observability.listScoresBySpan(e)}score(e){return this.observability.score(e)}listLogsVNext(e={}){return this.observability.listLogs(e)}listScores(e={}){return this.observability.listScores(e)}createScore(e){return this.observability.createScore(e)}getScoreAggregate(e){return this.observability.getScoreAggregate(e)}getScoreBreakdown(e){return this.observability.getScoreBreakdown(e)}getScoreTimeSeries(e){return this.observability.getScoreTimeSeries(e)}getScorePercentiles(e){return this.observability.getScorePercentiles(e)}listFeedback(e={}){return this.observability.listFeedback(e)}createFeedback(e){return this.observability.createFeedback(e)}getFeedbackAggregate(e){return this.observability.getFeedbackAggregate(e)}getFeedbackBreakdown(e){return this.observability.getFeedbackBreakdown(e)}getFeedbackTimeSeries(e){return this.observability.getFeedbackTimeSeries(e)}getFeedbackPercentiles(e){return this.observability.getFeedbackPercentiles(e)}getMetricAggregate(e){return this.observability.getMetricAggregate(e)}getMetricBreakdown(e){return this.observability.getMetricBreakdown(e)}getMetricTimeSeries(e){return this.observability.getMetricTimeSeries(e)}getMetricPercentiles(e){return this.observability.getMetricPercentiles(e)}getMetricNames(e={}){return this.observability.getMetricNames(e)}getMetricLabelKeys(e){return this.observability.getMetricLabelKeys(e)}getMetricLabelValues(e){return this.observability.getMetricLabelValues(e)}getEntityTypes(){return this.observability.getEntityTypes()}getEntityNames(e={}){return this.observability.getEntityNames(e)}getServiceNames(){return this.observability.getServiceNames()}getEnvironments(){return this.observability.getEnvironments()}getTags(e={}){return this.observability.getTags(e)}listStoredAgents(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.status&&t.set("status",e.status),e?.authorId&&t.set("authorId",e.authorId),e?.visibility&&t.set("visibility",e.visibility),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata)),e?.favoritedOnly&&t.set("favoritedOnly","true"),e?.pinFavoritedFor&&t.set("pinFavoritedFor",e.pinFavoritedFor);const n=t.toString();return this.request(`/stored/agents${n?`?${n}`:""}`)}createStoredAgent(e){return this.request("/stored/agents",{method:"POST",body:e})}getStoredAgent(e){return new Aun(this.options,e)}listStoredWorkflows(e){const t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.authorId&&t.set("authorId",e.authorId);const n=t.toString();return this.request(`/stored/workflows${n?`?${n}`:""}`)}upsertStoredWorkflow(e){return this.request("/stored/workflows",{method:"POST",body:e})}getStoredWorkflow(e){return new Run(this.options,e)}listStoredPromptBlocks(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.status&&t.set("status",e.status),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata));const n=t.toString();return this.request(`/stored/prompt-blocks${n?`?${n}`:""}`)}createStoredPromptBlock(e){return this.request("/stored/prompt-blocks",{method:"POST",body:e})}getStoredPromptBlock(e){return new Pun(this.options,e)}listStoredScorers(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata));const n=t.toString();return this.request(`/stored/scorers${n?`?${n}`:""}`)}createStoredScorer(e){return this.request("/stored/scorers",{method:"POST",body:e})}getStoredScorer(e){return new Mun(this.options,e)}listStoredMCPClients(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata));const n=t.toString();return this.request(`/stored/mcp-clients${n?`?${n}`:""}`)}createStoredMCPClient(e){return this.request("/stored/mcp-clients",{method:"POST",body:e})}getStoredMCPClient(e){return new $un(this.options,e)}listStoredSkills(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.visibility&&t.set("visibility",e.visibility),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata)),e?.favoritedOnly&&t.set("favoritedOnly","true"),e?.pinFavoritedFor&&t.set("pinFavoritedFor",e.pinFavoritedFor);const n=t.toString();return this.request(`/stored/skills${n?`?${n}`:""}`)}createStoredSkill(e){return this.request("/stored/skills",{method:"POST",body:e})}getStoredSkill(e){return new Bun(this.options,e)}listToolProviders(){return this.request("/tool-providers")}getToolProvider(e){return new Dun(this.options,e)}getProcessorProviders(){return this.request("/processor-providers")}getProcessorProvider(e){return new Lun(this.options,e)}getSystemPackages(){return this.request("/system/packages")}getBuilderSettings(){return this.request("/editor/builder/settings")}getBuilderAvailableModels(){return this.request("/editor/builder/models/available")}getPermissionPatterns(){return this.request("/auth/permission-patterns")}getInfrastructureStatus(){return this.request("/editor/builder/infrastructure")}listBuilderRegistries(){return this.request("/editor/builder/registries")}searchBuilderRegistry(e,t){const n=new URLSearchParams({q:t.q});return t.limit!==void 0&&n.set("limit",String(t.limit)),this.request(`/editor/builder/registries/${encodeURIComponent(e)}/search?${n.toString()}`)}getBuilderRegistryPopular(e,t){const n=new URLSearchParams;t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.offset!==void 0&&n.set("offset",String(t.offset));const r=n.toString();return this.request(`/editor/builder/registries/${encodeURIComponent(e)}/popular${r?`?${r}`:""}`)}getBuilderRegistryPreview(e,t){const n=new URLSearchParams({owner:t.owner,repo:t.repo,path:t.path});return this.request(`/editor/builder/registries/${encodeURIComponent(e)}/preview?${n.toString()}`)}installBuilderRegistrySkill(e,t){return this.request(`/editor/builder/registries/${encodeURIComponent(e)}/install`,{method:"POST",body:t})}listWorkspaces(){return this.request("/workspaces")}getWorkspace(e){return new Fun(this.options,e)}listStoredWorkspaces(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.authorId&&t.set("authorId",e.authorId),e?.orderBy?.field&&t.set("orderBy[field]",e.orderBy.field),e?.orderBy?.direction&&t.set("orderBy[direction]",e.orderBy.direction);const n=t.toString();return this.request(`/stored/workspaces${n?`?${n}`:""}`)}getStoredWorkspace(e){return this.request(`/stored/workspaces/${encodeURIComponent(e)}`)}listVectors(){return this.request("/vectors")}listEmbedders(){return this.request("/embedders")}listDatasets(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage));const n=t.toString();return this.request(`/datasets${n?`?${n}`:""}`)}getDataset(e,t){const n=bX(t);return this.request(`/datasets/${encodeURIComponent(e)}${n}`)}createDataset(e){return this.request("/datasets",{method:"POST",body:e})}updateDataset(e){const{datasetId:t,organizationId:n,projectId:r,...s}=e,a=bX({organizationId:n,projectId:r});return this.request(`/datasets/${encodeURIComponent(t)}${a}`,{method:"PATCH",body:s})}deleteDataset(e,t){const n=bX(t);return this.request(`/datasets/${encodeURIComponent(e)}${n}`,{method:"DELETE"})}listDatasetItems(e,t){const n=new URLSearchParams;t?.page!==void 0&&n.set("page",String(t.page)),t?.perPage!==void 0&&n.set("perPage",String(t.perPage)),t?.search&&n.set("search",t.search),t?.version!=null&&n.set("version",String(t.version));const r=n.toString();return this.request(`/datasets/${encodeURIComponent(e)}/items${r?`?${r}`:""}`)}getDatasetItem(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`)}addDatasetItem(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items`,{method:"POST",body:n})}updateDatasetItem(e){const{datasetId:t,itemId:n,...r}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items/${encodeURIComponent(n)}`,{method:"PATCH",body:r})}deleteDatasetItem(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`,{method:"DELETE"})}batchInsertDatasetItems(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items/batch`,{method:"POST",body:n})}batchDeleteDatasetItems(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items/batch`,{method:"DELETE",body:n})}generateDatasetItems(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/generate-items`,{method:"POST",body:n})}clusterFailures(e){return this.request("/datasets/cluster-failures",{method:"POST",body:e})}getItemHistory(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}/history`)}getDatasetItemVersion(e,t,n){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}/versions/${n}`)}listDatasetVersions(e,t){const n=new URLSearchParams;t?.page!==void 0&&n.set("page",String(t.page)),t?.perPage!==void 0&&n.set("perPage",String(t.perPage));const r=n.toString();return this.request(`/datasets/${encodeURIComponent(e)}/versions${r?`?${r}`:""}`)}listExperiments(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.experimentSetId!==void 0&&t.set("experimentSetId",e.experimentSetId),e?.comparisonId!==void 0&&t.set("comparisonId",e.comparisonId),e?.variantId!==void 0&&t.set("variantId",e.variantId),e?.trialIndex!==void 0&&t.set("trialIndex",String(e.trialIndex));const n=t.toString();return this.request(`/experiments${n?`?${n}`:""}`)}getExperimentReviewSummary(){return this.request("/experiments/review-summary")}listDatasetExperiments(e,t){const n=new URLSearchParams;t?.page!==void 0&&n.set("page",String(t.page)),t?.perPage!==void 0&&n.set("perPage",String(t.perPage)),t?.experimentSetId!==void 0&&n.set("experimentSetId",t.experimentSetId),t?.comparisonId!==void 0&&n.set("comparisonId",t.comparisonId),t?.variantId!==void 0&&n.set("variantId",t.variantId),t?.trialIndex!==void 0&&n.set("trialIndex",String(t.trialIndex));const r=n.toString();return this.request(`/datasets/${encodeURIComponent(e)}/experiments${r?`?${r}`:""}`)}getDatasetExperiment(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/experiments/${encodeURIComponent(t)}`)}listDatasetExperimentResults(e,t,n){const r=new URLSearchParams;n?.page!==void 0&&r.set("page",String(n.page)),n?.perPage!==void 0&&r.set("perPage",String(n.perPage));const s=r.toString();return this.request(`/datasets/${encodeURIComponent(e)}/experiments/${encodeURIComponent(t)}/results${s?`?${s}`:""}`)}updateDatasetExperimentResult(e){const{datasetId:t,experimentId:n,resultId:r,...s}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/results/${encodeURIComponent(r)}`,{method:"PATCH",body:s})}triggerDatasetExperiment(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments`,{method:"POST",body:n})}updateExperimentResult(e){const{datasetId:t,experimentId:n,resultId:r,...s}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/results/${encodeURIComponent(r)}`,{method:"PATCH",body:s})}compareExperiments(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/compare`,{method:"POST",body:n})}listBackgroundTasks(e={}){const t=new URLSearchParams;e.agentId&&t.set("agentId",e.agentId),e.status&&t.set("status",e.status),e.runId&&t.set("runId",e.runId),e.threadId&&t.set("threadId",e.threadId),e.resourceId&&t.set("resourceId",e.resourceId),e.toolName&&t.set("toolName",e.toolName),e.toolCallId&&t.set("toolCallId",e.toolCallId),e.fromDate&&t.set("fromDate",e.fromDate.toISOString()),e.toDate&&t.set("toDate",e.toDate.toISOString()),e.dateFilterBy&&t.set("dateFilterBy",e.dateFilterBy),e.orderBy&&t.set("orderBy",e.orderBy),e.orderDirection&&t.set("orderDirection",e.orderDirection),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const n=t.toString();return this.request(`/background-tasks${n?`?${n}`:""}`)}getBackgroundTask(e){return this.request(`/background-tasks/${encodeURIComponent(e)}`)}async streamBackgroundTasks(e={}){const t=new URLSearchParams;e.agentId&&t.set("agentId",e.agentId),e.runId&&t.set("runId",e.runId),e.threadId&&t.set("threadId",e.threadId),e.resourceId&&t.set("resourceId",e.resourceId),e.taskId&&t.set("taskId",e.taskId);const n=t.toString(),r=await this.request(`/background-tasks/stream${n?`?${n}`:""}`,{stream:!0});if(!r.ok)throw new Error(`Failed to stream background tasks: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(hun())}listSchedules(e={}){const t=new URLSearchParams;e.agentId&&t.set("agentId",e.agentId),e.workflowId&&t.set("workflowId",e.workflowId),e.status&&t.set("status",e.status),e.threadId&&t.set("threadId",e.threadId),e.resourceId&&t.set("resourceId",e.resourceId),e.name&&t.set("name",e.name);const n=t.toString();return this.request(`/schedules${n?`?${n}`:""}`)}getSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`)}createSchedule(e){return this.request("/schedules",{method:"POST",body:e})}updateSchedule(e,t){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"PATCH",body:t})}deleteSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"DELETE"})}runSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}/run`,{method:"POST"})}listScheduleTriggers(e,t={}){const n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.fromActualFireAt!==void 0&&n.set("fromActualFireAt",String(t.fromActualFireAt)),t.toActualFireAt!==void 0&&n.set("toActualFireAt",String(t.toActualFireAt));const r=n.toString();return this.request(`/schedules/${encodeURIComponent(e)}/triggers${r?`?${r}`:""}`)}pauseSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}/pause`,{method:"POST"})}resumeSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}/resume`,{method:"POST"})}},Kun=class{id;description;inputSchema;outputSchema;execute;constructor(e){this.id=e.id,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.execute=e.execute}};function Ag(e){return new Kun(e)}const Xun=()=>!0;async function Jun(e,t={},n=3,r={}){let s=0,a=null;const i=r.shouldRetryResponse??Xun;for(;s<n;){let l;try{l=await fetch(e,t)}catch(u){a=u instanceof Error?u:new Error(String(u))}if(l){if(l.ok)return l;if(a=new Error(`Request failed with status: ${l.status} ${l.statusText}`),!i(l))throw a}if(s++,s>=n)break;const c=Math.min(1e3*Math.pow(2,s),1e4);await new Promise(u=>setTimeout(u,c))}throw a||new Error("Request failed after multiple retry attempts")}function ihe(e,t){if(e===t)return!0;if(e==null||t==null)return e===t;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length!==t.length?!1:e.every((n,r)=>ihe(n,t[r]));if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(typeof e=="object"&&typeof t=="object"){const n=e,r=t,s=Object.keys(n),a=Object.keys(r);return s.length!==a.length?!1:s.every(i=>Object.prototype.hasOwnProperty.call(r,i)&&ihe(n[i],r[i]))}return!1}function cg(e,t,n){const r=e?.mastra,s=r?.toolPayloadTransform?.[t]?.[n]??r?.toolPayloadProjection?.[t]?.[n];if(s&&Object.prototype.hasOwnProperty.call(s,"projected")&&!Object.prototype.hasOwnProperty.call(s,"transformed")){const{projected:a,...i}=s;return{...i,transformed:a}}return s}function Tu(e){return!!(e&&Object.prototype.hasOwnProperty.call(e,"transformed"))}var Rdt="vercel.ai.error",edn=Symbol.for(Rdt),xDe,wDe,SDe=class Pdt extends(wDe=Error,xDe=edn,wDe){constructor({name:t,message:n,cause:r}){super(n),this[xDe]=!0,this.name=t,this.cause=r}static isInstance(t){return Pdt.hasMarker(t,Rdt)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},$dt="AI_InvalidArgumentError",Mdt=`vercel.ai.error.${$dt}`,tdn=Symbol.for(Mdt),kDe,ODe,ndn=class extends(ODe=SDe,kDe=tdn,ODe){constructor({message:t,cause:n,argument:r}){super({name:$dt,message:t,cause:n}),this[kDe]=!0,this.argument=r}static isInstance(t){return SDe.hasMarker(t,Mdt)}},rdn=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const s=()=>{const a=n.length,i=new Array(t);for(let l=0;l<t;l++)i[l]=n[Math.random()*a|0];return i.join("")};if(e==null)return s;if(n.includes(r))throw new ndn({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${s()}`};rdn();function sdn({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,s])=>{const a=r.toLowerCase();return a==="*"||a==="*/*"?{mediaTypePrefix:"",regexes:s}:{mediaTypePrefix:a.replace(/\*/,""),regexes:s}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}new TextDecoder;new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:adn,atob:idn}=globalThis;function Ddt(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=idn(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function ohe(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return adn(t)}function _O(e){return typeof e=="string"?e:e instanceof ArrayBuffer?ohe(new Uint8Array(e)):ohe(e)}function Ldt(e){if(e.type==="user-message")return{type:"user",tagName:e.tagName??"user"};if(e.type==="system-reminder")return{type:"reactive",tagName:e.tagName??"system-reminder"};if(e.type==="user"||e.type==="state"||e.type==="notification")return{type:e.type,tagName:e.tagName??e.type};if(e.type==="reactive")return{type:"reactive",tagName:e.tagName??"system-reminder"};throw new Error(`Invalid signal type: ${e.type}. Use a supported signal type and set tagName for custom XML tags.`)}function odn(e){const{type:t,tagName:n}=Ldt(e);return{...e,type:t,tagName:n,id:e.id??crypto.randomUUID(),createdAt:e.createdAt instanceof Date?e.createdAt:e.createdAt?new Date(e.createdAt):new Date,acceptedAt:e.acceptedAt instanceof Date?e.acceptedAt:e.acceptedAt?new Date(e.acceptedAt):void 0}}function zdt(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function ldn(e){return zdt(e).replaceAll('"',"&quot;")}const cdn=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function Fdt(e,t){if(!cdn.test(e))throw new Error(`Invalid signal XML ${t}: ${e}`)}function udn(e){if(!e)return"";const t=Object.entries(e).filter(n=>n[1]!==null&&n[1]!==void 0).map(([n,r])=>(Fdt(n,"attribute name"),`${n}="${ldn(String(r))}"`)).join(" ");return t?` ${t}`:""}function lhe(e){const t=e.tagName??Ldt(e).tagName;Fdt(t,"tag name");const n=udn(e.attributes);return e.contents?`<${t}${n}>${zdt(e.contents)}</${t}>`:`<${t}${n} />`}function ddn(e){if(typeof e=="string")return e;if(Array.isArray(e)){const n=[];for(const r of e){if(typeof r=="string"){n.push({type:"text",text:r});continue}const s=_De(r);if(!s)return;n.push(...s)}return EDe(n)}const t=_De(e);return t?EDe(t):void 0}function _De(e){if(!e||typeof e!="object")return;const t=e;if(t.role==="user"&&"content"in t){const r=t.content;if(typeof r=="string")return[{type:"text",text:r}];if(Array.isArray(r)){const s=[];for(const a of r){const i=CDe(a);if(!i)return;s.push(i)}return s}return}const n=CDe(t);return n?[n]:void 0}function CDe(e){if(!e||typeof e!="object")return;const t=e,n=t.providerOptions&&typeof t.providerOptions=="object"&&!Array.isArray(t.providerOptions)?t.providerOptions:void 0;if(t.type==="text"&&typeof t.text=="string")return{type:"text",text:t.text,...n?{providerOptions:n}:{}};if(t.type==="file"||t.type==="image"){const r=t.type==="image"?t.image??t.data:t.data;if(typeof r!="string")return;const s=typeof t.mediaType=="string"?t.mediaType:typeof t.mimeType=="string"?t.mimeType:t.type==="image"?"image/png":"";return s?{type:"file",data:r,mediaType:s,...typeof t.filename=="string"?{filename:t.filename}:{},...n?{providerOptions:n}:{}}:void 0}}function EDe(e){if(e.length===0)return;const t=e[0];return e.length===1&&t?.type==="text"?t.text:e}function fdn(e){return typeof e=="string"?[{type:"text",text:e}]:e.map(t=>t.type==="file"?{type:"file",data:t.data instanceof URL?t.data.toString():_O(t.data),mediaType:t.mediaType,...t.filename?{filename:t.filename}:{},...t.providerOptions?{providerOptions:t.providerOptions}:{}}:{type:"text",text:t.text,...t.providerOptions?{providerOptions:t.providerOptions}:{}})}function pdn(e){const t=[];for(const n of e){const r=n.providerMetadata;if(n.type==="text")t.push({type:"text",text:n.text,...r?{providerOptions:r}:{}});else if(n.type==="file"&&typeof n.data=="string"){const s=n;t.push({type:"file",data:s.data,mediaType:typeof s.mimeType=="string"?s.mimeType:"",...typeof s.filename=="string"?{filename:s.filename}:{},...r?{providerOptions:r}:{}})}}return t}function Bdt(e){return e.length===1&&e[0]?.type==="text"&&!e[0].providerOptions?e[0].text:e.map(t=>t.type==="file"?{type:"file",data:t.data,mediaType:t.mediaType,...t.filename?{filename:t.filename}:{},...t.providerOptions?{providerOptions:t.providerOptions}:{}}:{type:"text",text:t.text,...t.providerOptions?{providerOptions:t.providerOptions}:{}})}function hdn(e){return e?Object.keys(e).some(t=>{const n=e[t];return n!=null}):!1}function mdn(e,t){let n=!1;const r=[];for(const s of t)!n&&s.type==="text"?(n=!0,r.push({...s,text:lhe({...e,contents:s.text})})):r.push(s);if(!n){const s=lhe({type:e.type,tagName:e.tagName,attributes:e.attributes});r.unshift({type:"text",text:s})}return r}function gdn(e,t){const n=e.type==="user",r=hdn(e.attributes),s=t.some(i=>i.providerOptions);let a;return n&&!r?a=t.length===1&&t[0]?.type==="text"&&!t[0].providerOptions?t[0].text:t:t.every(i=>i.type==="text")&&!s?a=lhe({...e,contents:t.map(i=>i.text).join(`
117
+ `),length:2},{index:k.indexOf("\r\r"),length:2}].filter(_=>_.index!==-1);return C.length===0?null:C.reduce((_,E)=>E.index<_.index?E:_)},m=async k=>{const C=k.body.getReader();i=C;const _=new TextDecoder;let E="";try{for(;!a;){const{done:T,value:N}=await C.read();if(T)return a?{kind:"cancelled"}:{kind:"done"};E+=_.decode(N,{stream:!0});let I;for(;(I=h(E))!==null;){const A=E.slice(0,I.index);E=E.slice(I.index+I.length);for(const R of A.split(/\r\n|\n|\r/)){if(!R.startsWith("data:"))continue;const L=R.slice(5).trim();if(!L)continue;let D;try{D=Gun(JSON.parse(L))}catch{continue}try{e.onEvent(D)}catch(z){return a||g(z),{kind:"consumer_error"}}}}}return{kind:"cancelled"}}catch(T){return a?{kind:"cancelled"}:{kind:"transport_error",error:T}}finally{i===C&&(i=null),C.cancel().catch(()=>{})}},g=k=>{try{e.onError?.(k)}catch{}},y=k=>{g(k.kind==="transport_error"?k.error:p())},b=async k=>{try{return await m(k)}catch(C){return a?{kind:"cancelled"}:{kind:"transport_error",error:C}}},x=await f();return(async k=>{let C=k;for(;!a;){let _=await b(C);if(a||_.kind==="cancelled"||_.kind==="consumer_error")return;if(!r){y(_);return}let E=0,T;for(;!T;){if(E>=r.maxRetries){y(_);return}if(E++,await d(s(E)),a)return;try{T=await f()}catch(N){_={kind:"transport_error",error:N}}}if(a){T.body?.cancel().catch(()=>{});return}C=T;try{e.onReconnect?.()}catch{}}})(x),{unsubscribe:()=>{a=!0,u(),i?.cancel().catch(()=>{})}}}async sendMessage(e,t){const{content:n,files:r}=typeof e=="string"?{content:e,files:void 0}:e,s=fr(t?.requestContext);await this.request(this.url(`${this.base()}/messages`),{method:"POST",body:{message:n,...r?.length?{files:r}:{},...s?{requestContext:s}:{}}})}async abort(){await this.request(this.url(`${this.base()}/abort`),{method:"POST"})}async approveTool(e,t,n){const r=fr(n?.requestContext);await this.request(this.url(`${this.base()}/tool-approval`),{method:"POST",body:{toolCallId:e,approved:t,...r?{requestContext:r}:{}}})}async respondToToolSuspension(e,t,n){const r=fr(n?.requestContext);await this.request(this.url(`${this.base()}/tool-suspension`),{method:"POST",body:{toolCallId:e,resumeData:t,...r?{requestContext:r}:{}}})}async steer(e,t){const n=fr(t?.requestContext);await this.request(this.url(`${this.base()}/steer`),{method:"POST",body:{message:e,...n?{requestContext:n}:{}}})}state(){return this.request(this.url(this.base()))}async setState(e){await this.request(this.url(`${this.base()}/state`),{method:"PUT",body:{state:e}})}async switchMode(e){await this.request(this.url(`${this.base()}/mode`),{method:"POST",body:{modeId:e}})}async switchModel(e,t){await this.request(this.url(`${this.base()}/model`),{method:"POST",body:{modelId:e,scope:t?.scope,modeId:t?.modeId}})}async listThreads(e){const t=typeof e=="number"?{limit:e}:e??{},n=new URLSearchParams;t.limit!=null&&n.set("limit",String(t.limit)),t.tags&&Object.keys(t.tags).length>0&&n.set("tags",JSON.stringify(t.tags));const r=n.toString()?`?${n.toString()}`:"";return(await this.request(this.url(`${this.base()}/threads${r}`))).threads}async switchThread(e){await this.request(this.url(`${this.base()}/thread`),{method:"POST",body:{threadId:e}})}async createThread(e){return this.request(this.url(`${this.base()}/threads`),{method:"POST",body:{title:e}})}async deleteThread(e){await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(e)}`),{method:"DELETE"})}async renameThread(e,t){await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(e)}`),{method:"PUT",body:{title:t}})}async cloneThread(e){return this.request(this.url(`${this.base()}/threads/clone`),{method:"POST",body:e??{}})}async listMessages(e,t){const n=t!=null?`?limit=${t}`:"";return(await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(e)}/messages${n}`))).messages.map(Adt)}async followUp(e,t){const n=fr(t?.requestContext);await this.request(this.url(`${this.base()}/follow-up`),{method:"POST",body:{message:e,...n?{requestContext:n}:{}}})}async getOMRecord(){return(await this.request(this.url(`${this.base()}/om`))).record}async setResourceId(e){await this.request(this.url(`${this.base()}/resource`),{method:"POST",body:{newResourceId:e}})}async getResourceIds(){return(await this.request(this.url(`${this.base()}/resources`))).resourceIds}async getGoal(){return(await this.request(this.url(`${this.base()}/goal`))).goal}async setGoal(e,t){return(await this.request(this.url(`${this.base()}/goal`),{method:"POST",body:{objective:e,...t}})).goal}async updateGoal(e){return(await this.request(this.url(`${this.base()}/goal`),{method:"PUT",body:e})).goal}async clearGoal(){await this.request(this.url(`${this.base()}/goal`),{method:"DELETE"})}async getPermissions(){return this.request(this.url(`${this.base()}/permissions`))}async setPermissionForCategory(e,t){await this.request(this.url(`${this.base()}/permissions/category`),{method:"PUT",body:{category:e,policy:t}})}async setPermissionForTool(e,t){await this.request(this.url(`${this.base()}/permissions/tool`),{method:"PUT",body:{toolName:e,policy:t}})}async sendNotification(e){return this.request(this.url(`${this.base()}/notifications`),{method:"POST",body:e})}},Yun=class extends qa{controllerId;constructor(e,t){super(e),this.controllerId=t}basePath(){return`/agent-controller/${encodeURIComponent(this.controllerId)}`}async listModes(){return(await this.request(`${this.basePath()}/modes`)).modes}async listModels(){return(await this.request(`${this.basePath()}/models`)).models}async workspaceStatus(){return this.request(`${this.basePath()}/workspace`)}session(e,t){return new Qun(this.options,this.controllerId,e,t)}},CP=class extends qa{observability;conversations;responses;channels;constructor(e){super(e),this.observability=new Iun(e),this.conversations=new pun(e),this.responses=new Wun(e),this.channels=new Zun(e)}listAgents(e,t){const n=yw(fr(e)),r=new URLSearchParams;n&&r.set("requestContext",n),t&&r.set("partial","true");const s=r.toString();return this.request(`/agents${s?`?${s}`:""}`)}listAgentsModelProviders(){return this.request("/agents/providers")}getAgent(e,t){return new iun(this.options,e,t)}async listAgentControllers(){return(await this.request("/agent-controller")).agentControllers}getAgentController(e){return new Yun(this.options,e)}async listMemoryThreads(e={}){const t=new URLSearchParams;e.resourceId&&t.set("resourceId",e.resourceId),e.metadata&&t.set("metadata",JSON.stringify(e.metadata)),e.agentId&&t.set("agentId",e.agentId),e.page!==void 0&&t.set("page",e.page.toString()),e.perPage!==void 0&&t.set("perPage",e.perPage.toString()),e.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction));const n=t.toString(),r=await this.request(`/memory/threads${n?`?${n}`:""}${cn(e.requestContext,n?"&":"?")}`);return"threads"in r?r:{threads:r,total:r.length,page:e.page??0,perPage:e.perPage??100,hasMore:!1}}getMemoryConfig(e){return this.request(`/memory/config?agentId=${e.agentId}${cn(e.requestContext,"&")}`)}createMemoryThread(e){return this.request(`/memory/threads?agentId=${e.agentId}${cn(e.requestContext,"&")}`,{method:"POST",body:e})}getMemoryThread({threadId:e,agentId:t}){return new oun(this.options,e,t)}listThreadMessages(e,t={}){let n="";const r=t.includeSystemReminders===void 0?"":`includeSystemReminders=${t.includeSystemReminders}`;return t.networkId?n=`/memory/network/threads/${e}/messages?networkId=${t.networkId}${r?`&${r}`:""}${cn(t.requestContext,"&")}`:t.agentId?n=`/memory/threads/${e}/messages?agentId=${t.agentId}${r?`&${r}`:""}${cn(t.requestContext,"&")}`:n=`/memory/threads/${e}/messages${r?`?${r}`:""}${cn(t.requestContext,r?"&":"?")}`,this.request(n)}deleteThread(e,t){if(!t||!!t.agentId==!!t.networkId)throw new Error("MastraClient.deleteThread() requires exactly one of agentId or networkId. The server cannot resolve which memory store owns the thread without one, and passing both is ambiguous.");const n=t.agentId?`/memory/threads/${e}?agentId=${t.agentId}${cn(t.requestContext,"&")}`:`/memory/network/threads/${e}?networkId=${t.networkId}${cn(t.requestContext,"&")}`;return this.request(n,{method:"DELETE"})}saveMessageToMemory(e){return this.request(`/memory/save-messages?agentId=${e.agentId}${cn(e.requestContext,"&")}`,{method:"POST",body:e})}getMemoryStatus(e,t,n){const r=new URLSearchParams({agentId:e});n?.resourceId&&r.set("resourceId",n.resourceId),n?.threadId&&r.set("threadId",n.threadId);const s=r.toString();return this.request(`/memory/status?${s}${cn(t,"&")}`)}getObservationalMemory(e){const t=new URLSearchParams({agentId:e.agentId});e.resourceId&&t.set("resourceId",e.resourceId),e.threadId&&t.set("threadId",e.threadId),e.from&&t.set("from",e.from instanceof Date?e.from.toISOString():e.from),e.to&&t.set("to",e.to instanceof Date?e.to.toISOString():e.to),e.offset!=null&&t.set("offset",String(e.offset)),e.limit!=null&&t.set("limit",String(e.limit));const n=t.toString();return this.request(`/memory/observational-memory?${n}${cn(e.requestContext,"&")}`)}awaitBufferStatus(e){return this.request(`/memory/observational-memory/buffer-status${cn(e.requestContext)}`,{method:"POST",body:{agentId:e.agentId,resourceId:e.resourceId,threadId:e.threadId}})}listTools(e){const t=yw(fr(e)),n=new URLSearchParams;t&&n.set("requestContext",t);const r=n.toString();return this.request(`/tools${r?`?${r}`:""}`)}getTool(e){return new uun(this.options,e)}listProcessors(e){const t=yw(fr(e)),n=new URLSearchParams;t&&n.set("requestContext",t);const r=n.toString();return this.request(`/processors${r?`?${r}`:""}`)}getProcessor(e){return new dun(this.options,e)}listWorkflows(e,t){const n=yw(fr(e)),r=new URLSearchParams;n&&r.set("requestContext",n),t&&r.set("partial","true");const s=r.toString();return this.request(`/workflows${s?`?${s}`:""}`)}listWorkflowRunCounts(e){const t=yw(fr(e)),n=new URLSearchParams;t&&n.set("requestContext",t);const r=n.toString();return this.request(`/workflows/run-counts${r?`?${r}`:""}`)}getWorkflow(e){return new vun(this.options,e)}getAgentBuilderActions(){return this.request("/agent-builder")}getAgentBuilderAction(e){return new Nun(this.options,e)}getVector(e){return new cun(this.options,e)}listLogs(e){const{transportId:t,fromDate:n,toDate:r,logLevel:s,filters:a,page:i,perPage:l}=e,c=a?Object.entries(a).map(([d,f])=>`${d}:${f}`):[],u=new URLSearchParams;if(t&&u.set("transportId",t),n&&u.set("fromDate",n.toISOString()),r&&u.set("toDate",r.toISOString()),s&&u.set("logLevel",s),i!==void 0&&u.set("page",String(i)),l!==void 0&&u.set("perPage",String(l)),c)if(Array.isArray(c))for(const d of c)u.append("filters",d);else u.set("filters",c);return u.size?this.request(`/logs?${u}`):this.request("/logs")}getLogForRun(e){const{runId:t,transportId:n,fromDate:r,toDate:s,logLevel:a,filters:i,page:l,perPage:c}=e,u=i?Object.entries(i).map(([f,p])=>`${f}:${p}`):[],d=new URLSearchParams;if(t&&d.set("runId",t),n&&d.set("transportId",n),r&&d.set("fromDate",r.toISOString()),s&&d.set("toDate",s.toISOString()),a&&d.set("logLevel",a),l!==void 0&&d.set("page",String(l)),c!==void 0&&d.set("perPage",String(c)),u)if(Array.isArray(u))for(const f of u)d.append("filters",f);else d.set("filters",u);return d.size?this.request(`/logs/${t}?${d}`):this.request(`/logs/${t}`)}listLogTransports(){return this.request("/logs/transports")}getMcpServers(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));const n=t.toString();return this.request(`/mcp/v0/servers${n?`?${n}`:""}`)}getMcpServerDetails(e,t){const n=new URLSearchParams;t?.version&&n.set("version",t.version);const r=n.toString();return this.request(`/mcp/v0/servers/${e}${r?`?${r}`:""}`)}getMcpServerTools(e){return this.request(`/mcp/${e}/tools`)}getMcpServerTool(e,t){return new jun(this.options,e,t)}getMcpServerResources(e){return this.request(`/mcp/${encodeURIComponent(e)}/resources`)}readMcpServerResource(e,t){return this.request(`/mcp/${encodeURIComponent(e)}/resources/read`,{method:"POST",body:{uri:t}})}getA2A(e){return new Eun(this.options,e)}getA2AV1(e){return new Tun(this.options,e)}getWorkingMemory({agentId:e,threadId:t,resourceId:n,requestContext:r}){return this.request(`/memory/threads/${t}/working-memory?agentId=${e}&resourceId=${n}${cn(r,"&")}`)}searchMemory({agentId:e,resourceId:t,threadId:n,searchQuery:r,memoryConfig:s,requestContext:a}){const i=new URLSearchParams({searchQuery:r,resourceId:t,agentId:e});return n&&i.append("threadId",n),s&&i.append("memoryConfig",JSON.stringify(s)),this.request(`/memory/search?${i}${cn(a,"&")}`)}updateWorkingMemory({agentId:e,threadId:t,workingMemory:n,resourceId:r,requestContext:s}){return this.request(`/memory/threads/${t}/working-memory?agentId=${e}${cn(s,"&")}`,{method:"POST",body:{workingMemory:n,resourceId:r}})}listScorers(e){return this.request(`/scores/scorers${cn(e)}`)}getScorer(e){return this.request(`/scores/scorers/${encodeURIComponent(e)}`)}listScoresByScorerId(e){const{page:t,perPage:n,scorerId:r,entityId:s,entityType:a}=e,i=new URLSearchParams;s&&i.set("entityId",s),a&&i.set("entityType",a),t!==void 0&&i.set("page",String(t)),n!==void 0&&i.set("perPage",String(n));const l=i.toString();return this.request(`/scores/scorer/${encodeURIComponent(r)}${l?`?${l}`:""}`)}listScoresByRunId(e){const{runId:t,page:n,perPage:r}=e,s=new URLSearchParams;n!==void 0&&s.set("page",String(n)),r!==void 0&&s.set("perPage",String(r));const a=s.toString();return this.request(`/scores/run/${encodeURIComponent(t)}${a?`?${a}`:""}`)}listScoresByEntityId(e){const{entityId:t,entityType:n,page:r,perPage:s}=e,a=new URLSearchParams;r!==void 0&&a.set("page",String(r)),s!==void 0&&a.set("perPage",String(s));const i=a.toString();return this.request(`/scores/entity/${encodeURIComponent(n)}/${encodeURIComponent(t)}${i?`?${i}`:""}`)}saveScore(e){return this.request("/scores",{method:"POST",body:e})}getTrace(e){return this.observability.getTrace(e)}getTraceLight(e){return this.observability.getTraceLight(e)}getSpan(e,t){return this.observability.getSpan(e,t)}getTraceTrajectory(e){return this.observability.getTraceTrajectory(e)}getTraces(e){return this.observability.getTraces(e)}listTraces(e={}){return this.observability.listTraces(e)}listTracesLight(e={}){return this.observability.listTracesLight(e)}listBranches(e={}){return this.observability.listBranches(e)}getBranch(e){return this.observability.getBranch(e)}listScoresBySpan(e){return this.observability.listScoresBySpan(e)}score(e){return this.observability.score(e)}listLogsVNext(e={}){return this.observability.listLogs(e)}listScores(e={}){return this.observability.listScores(e)}createScore(e){return this.observability.createScore(e)}getScoreAggregate(e){return this.observability.getScoreAggregate(e)}getScoreBreakdown(e){return this.observability.getScoreBreakdown(e)}getScoreTimeSeries(e){return this.observability.getScoreTimeSeries(e)}getScorePercentiles(e){return this.observability.getScorePercentiles(e)}listFeedback(e={}){return this.observability.listFeedback(e)}createFeedback(e){return this.observability.createFeedback(e)}getFeedbackAggregate(e){return this.observability.getFeedbackAggregate(e)}getFeedbackBreakdown(e){return this.observability.getFeedbackBreakdown(e)}getFeedbackTimeSeries(e){return this.observability.getFeedbackTimeSeries(e)}getFeedbackPercentiles(e){return this.observability.getFeedbackPercentiles(e)}getMetricAggregate(e){return this.observability.getMetricAggregate(e)}getMetricBreakdown(e){return this.observability.getMetricBreakdown(e)}getMetricTimeSeries(e){return this.observability.getMetricTimeSeries(e)}getMetricPercentiles(e){return this.observability.getMetricPercentiles(e)}getMetricNames(e={}){return this.observability.getMetricNames(e)}getMetricLabelKeys(e){return this.observability.getMetricLabelKeys(e)}getMetricLabelValues(e){return this.observability.getMetricLabelValues(e)}getEntityTypes(){return this.observability.getEntityTypes()}getEntityNames(e={}){return this.observability.getEntityNames(e)}getServiceNames(){return this.observability.getServiceNames()}getEnvironments(){return this.observability.getEnvironments()}getTags(e={}){return this.observability.getTags(e)}listStoredAgents(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.status&&t.set("status",e.status),e?.authorId&&t.set("authorId",e.authorId),e?.visibility&&t.set("visibility",e.visibility),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata)),e?.favoritedOnly&&t.set("favoritedOnly","true"),e?.pinFavoritedFor&&t.set("pinFavoritedFor",e.pinFavoritedFor);const n=t.toString();return this.request(`/stored/agents${n?`?${n}`:""}`)}createStoredAgent(e){return this.request("/stored/agents",{method:"POST",body:e})}getStoredAgent(e){return new Aun(this.options,e)}listDynamicWorkflows(e){const t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.authorId&&t.set("authorId",e.authorId);const n=t.toString();return this.request(`/stored/workflows${n?`?${n}`:""}`)}upsertDynamicWorkflow(e){return this.request("/stored/workflows",{method:"POST",body:e})}getDynamicWorkflow(e){return new Run(this.options,e)}listStoredPromptBlocks(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.status&&t.set("status",e.status),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata));const n=t.toString();return this.request(`/stored/prompt-blocks${n?`?${n}`:""}`)}createStoredPromptBlock(e){return this.request("/stored/prompt-blocks",{method:"POST",body:e})}getStoredPromptBlock(e){return new Pun(this.options,e)}listStoredScorers(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata));const n=t.toString();return this.request(`/stored/scorers${n?`?${n}`:""}`)}createStoredScorer(e){return this.request("/stored/scorers",{method:"POST",body:e})}getStoredScorer(e){return new Mun(this.options,e)}listStoredMCPClients(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata));const n=t.toString();return this.request(`/stored/mcp-clients${n?`?${n}`:""}`)}createStoredMCPClient(e){return this.request("/stored/mcp-clients",{method:"POST",body:e})}getStoredMCPClient(e){return new $un(this.options,e)}listStoredSkills(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.visibility&&t.set("visibility",e.visibility),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata)),e?.favoritedOnly&&t.set("favoritedOnly","true"),e?.pinFavoritedFor&&t.set("pinFavoritedFor",e.pinFavoritedFor);const n=t.toString();return this.request(`/stored/skills${n?`?${n}`:""}`)}createStoredSkill(e){return this.request("/stored/skills",{method:"POST",body:e})}getStoredSkill(e){return new Bun(this.options,e)}listToolProviders(){return this.request("/tool-providers")}getToolProvider(e){return new Dun(this.options,e)}getProcessorProviders(){return this.request("/processor-providers")}getProcessorProvider(e){return new Lun(this.options,e)}getSystemPackages(){return this.request("/system/packages")}getBuilderSettings(){return this.request("/editor/builder/settings")}getBuilderAvailableModels(){return this.request("/editor/builder/models/available")}getPermissionPatterns(){return this.request("/auth/permission-patterns")}getInfrastructureStatus(){return this.request("/editor/builder/infrastructure")}listBuilderRegistries(){return this.request("/editor/builder/registries")}searchBuilderRegistry(e,t){const n=new URLSearchParams({q:t.q});return t.limit!==void 0&&n.set("limit",String(t.limit)),this.request(`/editor/builder/registries/${encodeURIComponent(e)}/search?${n.toString()}`)}getBuilderRegistryPopular(e,t){const n=new URLSearchParams;t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.offset!==void 0&&n.set("offset",String(t.offset));const r=n.toString();return this.request(`/editor/builder/registries/${encodeURIComponent(e)}/popular${r?`?${r}`:""}`)}getBuilderRegistryPreview(e,t){const n=new URLSearchParams({owner:t.owner,repo:t.repo,path:t.path});return this.request(`/editor/builder/registries/${encodeURIComponent(e)}/preview?${n.toString()}`)}installBuilderRegistrySkill(e,t){return this.request(`/editor/builder/registries/${encodeURIComponent(e)}/install`,{method:"POST",body:t})}listWorkspaces(){return this.request("/workspaces")}getWorkspace(e){return new Fun(this.options,e)}listStoredWorkspaces(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.authorId&&t.set("authorId",e.authorId),e?.orderBy?.field&&t.set("orderBy[field]",e.orderBy.field),e?.orderBy?.direction&&t.set("orderBy[direction]",e.orderBy.direction);const n=t.toString();return this.request(`/stored/workspaces${n?`?${n}`:""}`)}getStoredWorkspace(e){return this.request(`/stored/workspaces/${encodeURIComponent(e)}`)}listVectors(){return this.request("/vectors")}listEmbedders(){return this.request("/embedders")}listDatasets(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage));const n=t.toString();return this.request(`/datasets${n?`?${n}`:""}`)}getDataset(e,t){const n=bX(t);return this.request(`/datasets/${encodeURIComponent(e)}${n}`)}createDataset(e){return this.request("/datasets",{method:"POST",body:e})}updateDataset(e){const{datasetId:t,organizationId:n,projectId:r,...s}=e,a=bX({organizationId:n,projectId:r});return this.request(`/datasets/${encodeURIComponent(t)}${a}`,{method:"PATCH",body:s})}deleteDataset(e,t){const n=bX(t);return this.request(`/datasets/${encodeURIComponent(e)}${n}`,{method:"DELETE"})}listDatasetItems(e,t){const n=new URLSearchParams;t?.page!==void 0&&n.set("page",String(t.page)),t?.perPage!==void 0&&n.set("perPage",String(t.perPage)),t?.search&&n.set("search",t.search),t?.version!=null&&n.set("version",String(t.version));const r=n.toString();return this.request(`/datasets/${encodeURIComponent(e)}/items${r?`?${r}`:""}`)}getDatasetItem(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`)}addDatasetItem(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items`,{method:"POST",body:n})}updateDatasetItem(e){const{datasetId:t,itemId:n,...r}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items/${encodeURIComponent(n)}`,{method:"PATCH",body:r})}deleteDatasetItem(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`,{method:"DELETE"})}batchInsertDatasetItems(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items/batch`,{method:"POST",body:n})}batchDeleteDatasetItems(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items/batch`,{method:"DELETE",body:n})}generateDatasetItems(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/generate-items`,{method:"POST",body:n})}clusterFailures(e){return this.request("/datasets/cluster-failures",{method:"POST",body:e})}getItemHistory(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}/history`)}getDatasetItemVersion(e,t,n){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}/versions/${n}`)}listDatasetVersions(e,t){const n=new URLSearchParams;t?.page!==void 0&&n.set("page",String(t.page)),t?.perPage!==void 0&&n.set("perPage",String(t.perPage));const r=n.toString();return this.request(`/datasets/${encodeURIComponent(e)}/versions${r?`?${r}`:""}`)}listExperiments(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.experimentSetId!==void 0&&t.set("experimentSetId",e.experimentSetId),e?.comparisonId!==void 0&&t.set("comparisonId",e.comparisonId),e?.variantId!==void 0&&t.set("variantId",e.variantId),e?.trialIndex!==void 0&&t.set("trialIndex",String(e.trialIndex));const n=t.toString();return this.request(`/experiments${n?`?${n}`:""}`)}getExperimentReviewSummary(){return this.request("/experiments/review-summary")}listDatasetExperiments(e,t){const n=new URLSearchParams;t?.page!==void 0&&n.set("page",String(t.page)),t?.perPage!==void 0&&n.set("perPage",String(t.perPage)),t?.experimentSetId!==void 0&&n.set("experimentSetId",t.experimentSetId),t?.comparisonId!==void 0&&n.set("comparisonId",t.comparisonId),t?.variantId!==void 0&&n.set("variantId",t.variantId),t?.trialIndex!==void 0&&n.set("trialIndex",String(t.trialIndex));const r=n.toString();return this.request(`/datasets/${encodeURIComponent(e)}/experiments${r?`?${r}`:""}`)}getDatasetExperiment(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/experiments/${encodeURIComponent(t)}`)}listDatasetExperimentResults(e,t,n){const r=new URLSearchParams;n?.page!==void 0&&r.set("page",String(n.page)),n?.perPage!==void 0&&r.set("perPage",String(n.perPage));const s=r.toString();return this.request(`/datasets/${encodeURIComponent(e)}/experiments/${encodeURIComponent(t)}/results${s?`?${s}`:""}`)}updateDatasetExperimentResult(e){const{datasetId:t,experimentId:n,resultId:r,...s}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/results/${encodeURIComponent(r)}`,{method:"PATCH",body:s})}triggerDatasetExperiment(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments`,{method:"POST",body:n})}updateExperimentResult(e){const{datasetId:t,experimentId:n,resultId:r,...s}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/results/${encodeURIComponent(r)}`,{method:"PATCH",body:s})}compareExperiments(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/compare`,{method:"POST",body:n})}listBackgroundTasks(e={}){const t=new URLSearchParams;e.agentId&&t.set("agentId",e.agentId),e.status&&t.set("status",e.status),e.runId&&t.set("runId",e.runId),e.threadId&&t.set("threadId",e.threadId),e.resourceId&&t.set("resourceId",e.resourceId),e.toolName&&t.set("toolName",e.toolName),e.toolCallId&&t.set("toolCallId",e.toolCallId),e.fromDate&&t.set("fromDate",e.fromDate.toISOString()),e.toDate&&t.set("toDate",e.toDate.toISOString()),e.dateFilterBy&&t.set("dateFilterBy",e.dateFilterBy),e.orderBy&&t.set("orderBy",e.orderBy),e.orderDirection&&t.set("orderDirection",e.orderDirection),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const n=t.toString();return this.request(`/background-tasks${n?`?${n}`:""}`)}getBackgroundTask(e){return this.request(`/background-tasks/${encodeURIComponent(e)}`)}async streamBackgroundTasks(e={}){const t=new URLSearchParams;e.agentId&&t.set("agentId",e.agentId),e.runId&&t.set("runId",e.runId),e.threadId&&t.set("threadId",e.threadId),e.resourceId&&t.set("resourceId",e.resourceId),e.taskId&&t.set("taskId",e.taskId);const n=t.toString(),r=await this.request(`/background-tasks/stream${n?`?${n}`:""}`,{stream:!0});if(!r.ok)throw new Error(`Failed to stream background tasks: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(hun())}listSchedules(e={}){const t=new URLSearchParams;e.agentId&&t.set("agentId",e.agentId),e.workflowId&&t.set("workflowId",e.workflowId),e.status&&t.set("status",e.status),e.threadId&&t.set("threadId",e.threadId),e.resourceId&&t.set("resourceId",e.resourceId),e.name&&t.set("name",e.name);const n=t.toString();return this.request(`/schedules${n?`?${n}`:""}`)}getSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`)}createSchedule(e){return this.request("/schedules",{method:"POST",body:e})}updateSchedule(e,t){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"PATCH",body:t})}deleteSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"DELETE"})}runSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}/run`,{method:"POST"})}listScheduleTriggers(e,t={}){const n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.fromActualFireAt!==void 0&&n.set("fromActualFireAt",String(t.fromActualFireAt)),t.toActualFireAt!==void 0&&n.set("toActualFireAt",String(t.toActualFireAt));const r=n.toString();return this.request(`/schedules/${encodeURIComponent(e)}/triggers${r?`?${r}`:""}`)}pauseSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}/pause`,{method:"POST"})}resumeSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}/resume`,{method:"POST"})}},Kun=class{id;description;inputSchema;outputSchema;execute;constructor(e){this.id=e.id,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.execute=e.execute}};function Ag(e){return new Kun(e)}const Xun=()=>!0;async function Jun(e,t={},n=3,r={}){let s=0,a=null;const i=r.shouldRetryResponse??Xun;for(;s<n;){let l;try{l=await fetch(e,t)}catch(u){a=u instanceof Error?u:new Error(String(u))}if(l){if(l.ok)return l;if(a=new Error(`Request failed with status: ${l.status} ${l.statusText}`),!i(l))throw a}if(s++,s>=n)break;const c=Math.min(1e3*Math.pow(2,s),1e4);await new Promise(u=>setTimeout(u,c))}throw a||new Error("Request failed after multiple retry attempts")}function ihe(e,t){if(e===t)return!0;if(e==null||t==null)return e===t;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length!==t.length?!1:e.every((n,r)=>ihe(n,t[r]));if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(typeof e=="object"&&typeof t=="object"){const n=e,r=t,s=Object.keys(n),a=Object.keys(r);return s.length!==a.length?!1:s.every(i=>Object.prototype.hasOwnProperty.call(r,i)&&ihe(n[i],r[i]))}return!1}function cg(e,t,n){const r=e?.mastra,s=r?.toolPayloadTransform?.[t]?.[n]??r?.toolPayloadProjection?.[t]?.[n];if(s&&Object.prototype.hasOwnProperty.call(s,"projected")&&!Object.prototype.hasOwnProperty.call(s,"transformed")){const{projected:a,...i}=s;return{...i,transformed:a}}return s}function Tu(e){return!!(e&&Object.prototype.hasOwnProperty.call(e,"transformed"))}var Rdt="vercel.ai.error",edn=Symbol.for(Rdt),xDe,wDe,SDe=class Pdt extends(wDe=Error,xDe=edn,wDe){constructor({name:t,message:n,cause:r}){super(n),this[xDe]=!0,this.name=t,this.cause=r}static isInstance(t){return Pdt.hasMarker(t,Rdt)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},$dt="AI_InvalidArgumentError",Mdt=`vercel.ai.error.${$dt}`,tdn=Symbol.for(Mdt),kDe,ODe,ndn=class extends(ODe=SDe,kDe=tdn,ODe){constructor({message:t,cause:n,argument:r}){super({name:$dt,message:t,cause:n}),this[kDe]=!0,this.argument=r}static isInstance(t){return SDe.hasMarker(t,Mdt)}},rdn=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const s=()=>{const a=n.length,i=new Array(t);for(let l=0;l<t;l++)i[l]=n[Math.random()*a|0];return i.join("")};if(e==null)return s;if(n.includes(r))throw new ndn({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${s()}`};rdn();function sdn({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,s])=>{const a=r.toLowerCase();return a==="*"||a==="*/*"?{mediaTypePrefix:"",regexes:s}:{mediaTypePrefix:a.replace(/\*/,""),regexes:s}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}new TextDecoder;new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:adn,atob:idn}=globalThis;function Ddt(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=idn(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function ohe(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return adn(t)}function _O(e){return typeof e=="string"?e:e instanceof ArrayBuffer?ohe(new Uint8Array(e)):ohe(e)}function Ldt(e){if(e.type==="user-message")return{type:"user",tagName:e.tagName??"user"};if(e.type==="system-reminder")return{type:"reactive",tagName:e.tagName??"system-reminder"};if(e.type==="user"||e.type==="state"||e.type==="notification")return{type:e.type,tagName:e.tagName??e.type};if(e.type==="reactive")return{type:"reactive",tagName:e.tagName??"system-reminder"};throw new Error(`Invalid signal type: ${e.type}. Use a supported signal type and set tagName for custom XML tags.`)}function odn(e){const{type:t,tagName:n}=Ldt(e);return{...e,type:t,tagName:n,id:e.id??crypto.randomUUID(),createdAt:e.createdAt instanceof Date?e.createdAt:e.createdAt?new Date(e.createdAt):new Date,acceptedAt:e.acceptedAt instanceof Date?e.acceptedAt:e.acceptedAt?new Date(e.acceptedAt):void 0}}function zdt(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function ldn(e){return zdt(e).replaceAll('"',"&quot;")}const cdn=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function Fdt(e,t){if(!cdn.test(e))throw new Error(`Invalid signal XML ${t}: ${e}`)}function udn(e){if(!e)return"";const t=Object.entries(e).filter(n=>n[1]!==null&&n[1]!==void 0).map(([n,r])=>(Fdt(n,"attribute name"),`${n}="${ldn(String(r))}"`)).join(" ");return t?` ${t}`:""}function lhe(e){const t=e.tagName??Ldt(e).tagName;Fdt(t,"tag name");const n=udn(e.attributes);return e.contents?`<${t}${n}>${zdt(e.contents)}</${t}>`:`<${t}${n} />`}function ddn(e){if(typeof e=="string")return e;if(Array.isArray(e)){const n=[];for(const r of e){if(typeof r=="string"){n.push({type:"text",text:r});continue}const s=_De(r);if(!s)return;n.push(...s)}return EDe(n)}const t=_De(e);return t?EDe(t):void 0}function _De(e){if(!e||typeof e!="object")return;const t=e;if(t.role==="user"&&"content"in t){const r=t.content;if(typeof r=="string")return[{type:"text",text:r}];if(Array.isArray(r)){const s=[];for(const a of r){const i=CDe(a);if(!i)return;s.push(i)}return s}return}const n=CDe(t);return n?[n]:void 0}function CDe(e){if(!e||typeof e!="object")return;const t=e,n=t.providerOptions&&typeof t.providerOptions=="object"&&!Array.isArray(t.providerOptions)?t.providerOptions:void 0;if(t.type==="text"&&typeof t.text=="string")return{type:"text",text:t.text,...n?{providerOptions:n}:{}};if(t.type==="file"||t.type==="image"){const r=t.type==="image"?t.image??t.data:t.data;if(typeof r!="string")return;const s=typeof t.mediaType=="string"?t.mediaType:typeof t.mimeType=="string"?t.mimeType:t.type==="image"?"image/png":"";return s?{type:"file",data:r,mediaType:s,...typeof t.filename=="string"?{filename:t.filename}:{},...n?{providerOptions:n}:{}}:void 0}}function EDe(e){if(e.length===0)return;const t=e[0];return e.length===1&&t?.type==="text"?t.text:e}function fdn(e){return typeof e=="string"?[{type:"text",text:e}]:e.map(t=>t.type==="file"?{type:"file",data:t.data instanceof URL?t.data.toString():_O(t.data),mediaType:t.mediaType,...t.filename?{filename:t.filename}:{},...t.providerOptions?{providerOptions:t.providerOptions}:{}}:{type:"text",text:t.text,...t.providerOptions?{providerOptions:t.providerOptions}:{}})}function pdn(e){const t=[];for(const n of e){const r=n.providerMetadata;if(n.type==="text")t.push({type:"text",text:n.text,...r?{providerOptions:r}:{}});else if(n.type==="file"&&typeof n.data=="string"){const s=n;t.push({type:"file",data:s.data,mediaType:typeof s.mimeType=="string"?s.mimeType:"",...typeof s.filename=="string"?{filename:s.filename}:{},...r?{providerOptions:r}:{}})}}return t}function Bdt(e){return e.length===1&&e[0]?.type==="text"&&!e[0].providerOptions?e[0].text:e.map(t=>t.type==="file"?{type:"file",data:t.data,mediaType:t.mediaType,...t.filename?{filename:t.filename}:{},...t.providerOptions?{providerOptions:t.providerOptions}:{}}:{type:"text",text:t.text,...t.providerOptions?{providerOptions:t.providerOptions}:{}})}function hdn(e){return e?Object.keys(e).some(t=>{const n=e[t];return n!=null}):!1}function mdn(e,t){let n=!1;const r=[];for(const s of t)!n&&s.type==="text"?(n=!0,r.push({...s,text:lhe({...e,contents:s.text})})):r.push(s);if(!n){const s=lhe({type:e.type,tagName:e.tagName,attributes:e.attributes});r.unshift({type:"text",text:s})}return r}function gdn(e,t){const n=e.type==="user",r=hdn(e.attributes),s=t.some(i=>i.providerOptions);let a;return n&&!r?a=t.length===1&&t[0]?.type==="text"&&!t[0].providerOptions?t[0].text:t:t.every(i=>i.type==="text")&&!s?a=lhe({...e,contents:t.map(i=>i.text).join(`
118
118
  `)}):a=mdn(e,t),{role:"user",content:a,...e.providerOptions?{providerOptions:e.providerOptions}:{}}}function vdn(e,t){return{type:e.type==="user"?"data-user-message":"data-signal",data:{id:e.id,type:e.type,tagName:e.tagName,contents:Bdt(t),createdAt:e.createdAt.toISOString(),...e.acceptedAt?{acceptedAt:e.acceptedAt.toISOString()}:{},...e.attributes?{attributes:e.attributes}:{},...e.metadata?{metadata:e.metadata}:{},...e.providerOptions?{providerOptions:e.providerOptions}:{},...e.transient?{transient:!0}:{}},transient:!0}}function ydn(e,t,n){const r=t.length>0?t.map(s=>s.type==="file"?{type:"file",data:s.data,mimeType:s.mediaType,...s.filename?{filename:s.filename}:{},...s.providerOptions?{providerMetadata:s.providerOptions}:{}}:{type:"text",text:s.text,...s.providerOptions?{providerMetadata:s.providerOptions}:{}}):[{type:"text",text:""}];return{id:e.id,role:"signal",createdAt:e.createdAt,threadId:n?.threadId,resourceId:n?.resourceId,type:e.tagName,content:{format:2,parts:r,...e.providerOptions?{providerMetadata:e.providerOptions}:{},metadata:{signal:{id:e.id,type:e.type,tagName:e.tagName,createdAt:e.createdAt.toISOString(),...e.acceptedAt?{acceptedAt:e.acceptedAt.toISOString()}:{},...e.attributes?{attributes:e.attributes}:{},...e.metadata?{metadata:e.metadata}:{},...e.transient?{transient:!0}:{}}}}}}function TDe(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e.__isCreatedSignal===!0}function e7(e){if(e.type==="state"&&e.transient!==void 0)throw new Error("state signals cannot be transient");const t=odn(e),n=fdn(t.contents),r={...t,__isCreatedSignal:!0,toDBMessage:s=>ydn(t,n,s),toLLMMessage:()=>gdn(t,n),toDataPart:()=>vdn(t,n)};if(r.type==="state"){const{transient:s,...a}=r;return{...a,type:r.type}}return{...r,type:r.type}}function bdn(e){const t=e.content.metadata?.signal,n=t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,r=typeof n?.type=="string"?n.type:e.type??"user-message",s=typeof n?.tagName=="string"?n.tagName:void 0,a=ddn(n&&"contents"in n?n.contents:void 0),i=Bdt(pdn(e.content.parts)),l=a??i,c=e.content.providerMetadata,u={id:typeof n?.id=="string"?n.id:e.id,createdAt:typeof n?.createdAt=="string"?n.createdAt:e.createdAt,acceptedAt:typeof n?.acceptedAt=="string"?n.acceptedAt:void 0,attributes:n?.attributes&&typeof n.attributes=="object"&&!Array.isArray(n.attributes)?n.attributes:void 0,metadata:n?.metadata&&typeof n.metadata=="object"&&!Array.isArray(n.metadata)?n.metadata:void 0,providerOptions:c&&typeof c=="object"&&!Array.isArray(c)?c:void 0};if(r==="state"&&n?.transient!==void 0)throw new Error("state signals cannot be transient");return e7(r==="state"?{...u,type:r,tagName:s,contents:l}:{...u,type:r,tagName:s,contents:l,transient:n?.transient===!0?!0:void 0})}var xdn={},che={},Udt="vercel.ai.error",wdn=Symbol.for(Udt),jDe,NDe,Zu=class qdt extends(NDe=Error,jDe=wdn,NDe){constructor({name:t,message:n,cause:r}){super(n),this[jDe]=!0,this.name=t,this.cause=r}static isInstance(t){return qdt.hasMarker(t,Udt)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},Vdt="AI_APICallError",Hdt=`vercel.ai.error.${Vdt}`,Sdn=Symbol.for(Hdt),IDe,ADe,mf=class extends(ADe=Zu,IDe=Sdn,ADe){constructor({message:t,url:n,requestBodyValues:r,statusCode:s,responseHeaders:a,responseBody:i,cause:l,isRetryable:c=s!=null&&(s===408||s===409||s===429||s>=500),data:u}){super({name:Vdt,message:t,cause:l}),this[IDe]=!0,this.url=n,this.requestBodyValues=r,this.statusCode=s,this.responseHeaders=a,this.responseBody=i,this.isRetryable=c,this.data=u}static isInstance(t){return Zu.hasMarker(t,Hdt)}},Wdt="AI_EmptyResponseBodyError",Zdt=`vercel.ai.error.${Wdt}`,kdn=Symbol.for(Zdt),RDe,PDe,Odn=class extends(PDe=Zu,RDe=kdn,PDe){constructor({message:t="Empty response body"}={}){super({name:Wdt,message:t}),this[RDe]=!0}static isInstance(t){return Zu.hasMarker(t,Zdt)}};function _0e(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Gdt="AI_InvalidArgumentError",Qdt=`vercel.ai.error.${Gdt}`,_dn=Symbol.for(Qdt),$De,MDe,Cdn=class extends(MDe=Zu,$De=_dn,MDe){constructor({message:t,cause:n,argument:r}){super({name:Gdt,message:t,cause:n}),this[$De]=!0,this.argument=r}static isInstance(t){return Zu.hasMarker(t,Qdt)}},Ydt="AI_JSONParseError",Kdt=`vercel.ai.error.${Ydt}`,Edn=Symbol.for(Kdt),DDe,LDe,t7=class extends(LDe=Zu,DDe=Edn,LDe){constructor({text:t,cause:n}){super({name:Ydt,message:`JSON parsing failed: Text: ${t}.
119
119
  Error message: ${_0e(n)}`,cause:n}),this[DDe]=!0,this.text=t}static isInstance(t){return Zu.hasMarker(t,Kdt)}},Xdt="AI_TypeValidationError",Jdt=`vercel.ai.error.${Xdt}`,Tdn=Symbol.for(Jdt),zDe,FDe,h$=class uhe extends(FDe=Zu,zDe=Tdn,FDe){constructor({value:t,cause:n}){super({name:Xdt,message:`Type validation failed: Value: ${JSON.stringify(t)}.
120
120
  Error message: ${_0e(n)}`,cause:n}),this[zDe]=!0,this.value=t}static isInstance(t){return Zu.hasMarker(t,Jdt)}static wrap({value:t,cause:n}){return uhe.isInstance(n)&&n.value===t?n:new uhe({value:t,cause:n})}},BDe=class extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}};const UDe=10,jdn=13,zS=32;function kX(e){}function Ndn(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=kX,onError:n=kX,onRetry:r=kX,onComment:s}=e,a=[];let i=!0,l,c="",u=0,d;function f(b){if(i&&(i=!1,b.charCodeAt(0)===239&&b.charCodeAt(1)===187&&b.charCodeAt(2)===191&&(b=b.slice(3))),a.length===0){const k=p(b);k!==""&&a.push(k);return}if(b.indexOf(`
@@ -333,7 +333,7 @@ attempted value: ${i}
333
333
  \${}
334
334
  }
335
335
  }`,{label:"class",detail:"definition",type:"keyword"}),af('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),af('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],y1t=bke.concat([af("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),af("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),af("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),d8e=new Sxt,b1t=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function CR(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const JBn=["FunctionDeclaration"],eUn={FunctionDeclaration:CR("function"),ClassDeclaration:CR("class"),ClassExpression:()=>!0,EnumDeclaration:CR("constant"),TypeAliasDeclaration:CR("type"),NamespaceDeclaration:CR("namespace"),VariableDefinition(e,t){e.matchContext(JBn)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function x1t(e,t){let n=d8e.get(t);if(n)return n;let r=[],s=!0;function a(i,l){let c=e.sliceString(i.from,i.to);r.push({label:c,type:l})}return t.cursor(La.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=eUn[i.name];if(l&&l(i,a)||b1t.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of x1t(e,i.node))r.push(l);return!1}}),d8e.set(t,r),r}const NB=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,xke=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function w1t(e){let t=yi(e.state).resolveInner(e.pos,-1);if(xke.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)b1t.has(s.name)&&(r=r.concat(x1t(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:NB}}function Cee(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 S1t(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=yi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?Cee(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?Cee(t,n.parent,""):xke.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&NB.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?Cee(t,n,""):e.explicit?{path:[],name:""}:null}function tUn(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 nUn(e){let t=new Map;return n=>{let r=S1t(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=tUn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:NB}}}const Jh=qO.define({name:"javascript",parser:XBn.configure({props:[Y_.add({IfStatement:QT({except:/^\s*({|else\b)/}),TryStatement:QT({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:YFn,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:QFn({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":QT({except:/^\s*{/}),JSXElement(e){let t=/^\s*<\//.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},JSXEscape(e){let t=/\s*\}/.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},"JSXOpenTag JSXSelfClosingTag"(e){return e.column(e.node.from)+e.unit}}),K_.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":JSe,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:"$"}}),k1t={test:e=>/^JSX/.test(e.name),facet:zH({commentTokens:{block:{open:"{/*",close:"*/}"}}})},wke=Jh.configure({dialect:"ts"},"typescript"),Ske=Jh.configure({dialect:"jsx",props:[YSe.add(e=>e.isTop?[k1t]:void 0)]}),kke=Jh.configure({dialect:"jsx ts",props:[YSe.add(e=>e.isTop?[k1t]:void 0)]},"typescript");let O1t=e=>({label:e,type:"keyword"});const _1t="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(O1t),rUn=_1t.concat(["declare","implements","private","protected","public"].map(O1t));function IB(e={}){let t=e.jsx?e.typescript?kke:Ske:e.typescript?wke:Jh,n=e.typescript?y1t.concat(rUn):bke.concat(_1t);return new HO(t,[Jh.data.of({autocomplete:$8n(xke,kwt(n))}),Jh.data.of({autocomplete:w1t}),e.jsx?C1t:[]])}function sUn(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 f8e(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 aUn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),C1t=It.inputHandler.of((e,t,n,r,s)=>{if((aUn?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!Jh.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u;let{head:d}=c,f=yi(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=f8e(i.doc,m.firstChild,d))||((u=m.firstChild)===null||u===void 0?void 0:u.name)=="JSXFragmentTag")){let g=`${p}>`;return{range:xt.cursor(d+g.length,-1),changes:{from:d,insert:g}}}}else if(r==">"){let h=sUn(f);if(h&&h.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(p=f8e(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 iUn(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 Jh.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(oUn(u,r.doc,c))}return s}}function p8e(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function oUn(e,t,n){let r=p8e(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?p8e(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 az=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:C1t,completionPath:S1t,esLint:iUn,javascript:IB,javascriptLanguage:Jh,jsxLanguage:Ske,localCompletionSource:w1t,scopeCompletionSource:nUn,snippets:bke,tsxLanguage:kke,typescriptLanguage:wke,typescriptSnippets:y1t},Symbol.toStringTag,{value:"Module"})),ER=["_blank","_self","_top","_parent"],Eee=["ascii","utf-8","utf-16","latin1","latin1"],Tee=["get","post","put","delete"],jee=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],op=["true","false"],tr={},lUn={a:{attrs:{href:null,ping:null,type:null,media:null,target:ER,hreflang:null}},abbr:tr,address:tr,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:tr,aside:tr,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:tr,base:{attrs:{href:null,target:ER}},bdi:tr,bdo:tr,blockquote:{attrs:{cite:null}},body:tr,br:tr,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:jee,formmethod:Tee,formnovalidate:["novalidate"],formtarget:ER,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:tr,center:tr,cite:tr,code:tr,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:tr,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:tr,div:tr,dl:tr,dt:tr,em:tr,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:tr,figure:tr,footer:tr,form:{attrs:{action:null,name:null,"accept-charset":Eee,autocomplete:["on","off"],enctype:jee,method:Tee,novalidate:["novalidate"],target:ER}},h1:tr,h2:tr,h3:tr,h4:tr,h5:tr,h6:tr,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:tr,hgroup:tr,hr:tr,html:{attrs:{manifest:null}},i:tr,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:jee,formmethod:Tee,formnovalidate:["novalidate"],formtarget:ER,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:tr,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:tr,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:tr,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:Eee,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:tr,noscript:tr,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:tr,param:{attrs:{name:null,value:null}},pre:tr,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:tr,rt:tr,ruby:tr,samp:tr,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:Eee}},section:tr,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:tr,source:{attrs:{src:null,type:null,media:null}},span:tr,strong:tr,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:tr,summary:tr,sup:tr,table:tr,tbody:tr,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:tr,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:tr,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:tr,time:{attrs:{datetime:null}},title:tr,tr,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:tr,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:tr},E1t={accesskey:null,class:null,contenteditable:op,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:op,autocorrect:op,autocapitalize:op,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":op,"aria-autocomplete":["inline","list","both","none"],"aria-busy":op,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":op,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":op,"aria-hidden":op,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":op,"aria-multiselectable":op,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":op,"aria-relevant":null,"aria-required":op,"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},T1t="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 T1t)E1t[e]=null;class IM{constructor(t,n){this.tags={...lUn,...t},this.globalAttrs={...E1t,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}IM.default=new IM;function Zj(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 Gj(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function j1t(e,t,n){let r=n.tags[Zj(e,Gj(t))];return r?.children||n.allTags}function Oke(e,t){let n=[];for(let r=Gj(t);r&&!r.type.isTop;r=Gj(r.parent)){let s=Zj(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 N1t=/^[:\-\.\w\u00b7-\uffff]*$/;function h8e(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=Gj(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:j1t(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(Oke(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function m8e(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:Oke(e.doc,t).map((a,i)=>({label:a,apply:a+s,type:"type",boost:99-i})),validFor:N1t}}function cUn(e,t,n,r){let s=[],a=0;for(let i of j1t(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of Oke(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function uUn(e,t,n,r,s){let a=Gj(n),i=a?t.tags[Zj(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:N1t}}function dUn(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=Gj(n),p=f?t.tags[Zj(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 I1t(e,t){let{state:n,pos:r}=t,s=yi(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)?m8e(n,s,s.from,r):h8e(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?h8e(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?m8e(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?uUn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?dUn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?cUn(n,e,s,r):null}function fUn(e){return I1t(IM.default,e)}function pUn(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new IM(t,n):IM.default;return s=>I1t(r,s)}const hUn=Jh.parser.configure({top:"SingleExpression"}),A1t=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:wke.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:Ske.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:kke.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:hUn},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:Jh.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:jB.parser}],R1t=[{name:"style",parser:jB.parser.configure({top:"Styles"})}].concat(T1t.map(e=>({name:e,parser:Jh.parser}))),P1t=qO.define({name:"html",parser:z7n.configure({props:[Y_.add({Element(e){let t=/^(\s*)(<\/)?/.exec(e.textAfter);return e.node.to<=e.pos+t[0].length?e.continue():e.lineIndent(e.node.from)+(t[2]?0:e.unit)},"OpenTag CloseTag SelfClosingTag"(e){return e.column(e.node.from)+e.unit},Document(e){if(e.pos+/\s*/.exec(e.textAfter)[0].length<e.node.to)return e.continue();let t=null,n;for(let r=e.node;;){let s=r.lastChild;if(!s||s.name!="Element"||s.to!=r.to)break;t=r=s}return t&&!((n=t.lastChild)&&(n.name=="CloseTag"||n.name=="SelfClosingTag"))?e.lineIndent(t.from)+e.unit:null}}),K_.add({Element(e){let t=e.firstChild,n=e.lastChild;return!t||t.name!="OpenTag"?null:{from:t.to,to:n.name=="CloseTag"?n.from:e.to}}}),gwt.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),U8=P1t.configure({wrap:d1t(A1t,R1t)});function mUn(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=d1t((e.nestedLanguages||[]).concat(A1t),(e.nestedAttributes||[]).concat(R1t)));let r=n?P1t.configure({wrap:n,dialect:t}):t?U8.configure({dialect:t}):U8;return new HO(r,[U8.data.of({autocomplete:pUn(e)}),e.autoCloseTags!==!1?gUn:[],IB().support,wBn().support])}const g8e=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),gUn=It.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!U8.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=yi(i).resolveInner(h,-1),g;if(p&&r==">"&&m.name=="EndTag"){let y=m.parent;if(((d=(u=y.parent)===null||u===void 0?void 0:u.lastChild)===null||d===void 0?void 0:d.name)!="CloseTag"&&(g=Zj(i.doc,y.parent,h))&&!g8e.has(g)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`</${g}>`;return{range:c,changes:{from:h,to:b,insert:x}}}}else if(p&&r=="/"&&m.name=="IncompleteCloseTag"){let y=m.parent;if(m.from==h-2&&((f=y.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(g=Zj(i.doc,y,h))&&!g8e.has(g)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`${g}>`;return{range:xt.cursor(h+x.length,-1),changes:{from:h,to:b,insert:x}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),$1t=zH({commentTokens:{block:{open:"<!--",close:"-->"}}}),M1t=new Dr,D1t=B9n.configure({props:[K_.add(e=>!e.is("Block")||e.is("Document")||Ige(e)!=null||vUn(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),M1t.add(Ige),Y_.add({Document:()=>null}),Iw.add({Document:$1t})]});function Ige(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function vUn(e){return e.name=="OrderedList"||e.name=="BulletList"}function yUn(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=Ige(r.type))!=null&&s<=t)break;n=r}return n.to}const bUn=swt.of((e,t,n)=>{for(let r=yi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(M1t);if(s==null)continue;let a=yUn(r,s);if(a>n)return{from:n,to:a}}return null});function _ke(e){return new jp($1t,e,[],"markdown")}const L1t=_ke(D1t),xUn=D1t.configure([X9n,e7n,J9n,t7n,{props:[K_.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),GO=_ke(xUn);function wUn(e,t){return n=>{if(n&&e){let r=null;if(n=/\S*/.exec(n)[0],typeof e=="function"?r=e(n):r=og.matchLanguageName(e,n,!0),r instanceof og)return r.support?r.support.language.parser:VO.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class Nee{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(+F1t(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function z1t(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 Nee(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 Nee(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 Nee(a.parent,c,c+d,i[1],u,f,a))}}return r}function F1t(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function Iee(e,t,n,r=0){for(let s=-1,a=e;;){if(a.name=="ListItem"){let l=F1t(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 Cke(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(yI)!=" ")return e;let r=zg(e,4,n),s="";for(let a=r;a>0;)a>=4?(s+=" ",a-=4):(s+=" ",a--);return s+e.slice(n)}const B1t=(e={})=>({state:t,dispatch:n})=>{let r=yi(t),{doc:s}=t,a=null,i=t.changeByRange(l=>{if(!l.empty||!GO.isActiveAt(t,l.from,-1)&&!GO.isActiveAt(t,l.from,1))return a={range:l};let c=l.from,u=s.lineAt(c),d=z1t(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,x=f.node.getChild("ListItem","ListItem");if(b.to>=c||x&&x.to<c||u.from>0&&!/[^\s>]/.test(s.lineAt(u.from-1).text)||e.nonTightLists===!1){let S=d.length>1?d[d.length-2]:null,k,C="";S&&S.item?(k=u.from+S.from,C=S.marker(s,1)):k=u.from+(S?S.to:0);let _=[{from:k,to:c,insert:C}];return f.node.name=="OrderedList"&&Iee(f.item,s,_,-2),S&&S.node.name=="OrderedList"&&Iee(S.item,s,_),{range:xt.cursor(k+C.length),changes:_}}else{let S=y8e(d,t,u);return{range:xt.cursor(c+S.length+1),changes:{from:u.from,insert:S+t.lineBreak}}}}if(f.node.name=="Blockquote"&&p&&u.from){let b=s.lineAt(u.from-1),x=/>\s*$/.exec(b.text);if(x&&x.index==f.from){let S=t.changes([{from:b.from+x.index,to:b.to},{from:u.from+f.from,to:u.to}]);return{range:l.map(S),changes:S}}}let h=[];f.node.name=="OrderedList"&&Iee(f.item,s,h);let m=f.item&&f.item.from<u.from,g="";if(!m||/^[\s\d.)\-+*>]*/.exec(u.text)[0].length>=f.to)for(let b=0,x=d.length-1;b<=x;b++)g+=b==x&&!m?d[b].marker(s,1):d[b].blank(b<x?zg(u.text,4,d[b+1].from)-g.length:null);let y=c;for(;y>u.from&&/\s/.test(u.text.charAt(y-u.from-1));)y--;return g=Cke(g,t),SUn(f.node,t.doc)&&(g=y8e(d,t,u)+t.lineBreak+g),h.push({from:y,to:c,insert:t.lineBreak+g}),{range:xt.cursor(y+g.length+1),changes:h}});return a?!1:(n(t.update(i,{scrollIntoView:!0,userEvent:"input"})),!0)},U1t=B1t();function v8e(e){return e.name=="QuoteMark"||e.name=="ListMark"}function SUn(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 y8e(e,t,n){let r="";for(let s=0,a=e.length-2;s<=a;s++)r+=e[s].blank(s<a?zg(n.text,4,e[s+1].from)-r.length:null,s<a);return Cke(r,t)}function kUn(e,t){let n=e.resolveInner(t,-1),r=t;v8e(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(v8e(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const q1t=({state:e,dispatch:t})=>{let n=yi(e),r=null,s=e.changeByRange(a=>{let i=a.from,{doc:l}=e;if(a.empty&&GO.isActiveAt(e,a.from)){let c=l.lineAt(i),u=z1t(kUn(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:xt.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(zg(c.text,4,d.to)-zg(c.text,4,d.from));return p==c.from&&(h=Cke(h,e)),{range:xt.cursor(p+h.length),changes:{from:p,to:c.from+d.to,insert:h}}}if(p<i)return{range:xt.cursor(p),changes:{from:p,to:i}}}}}return r={range:a}});return r?!1:(t(e.update(s,{scrollIntoView:!0,userEvent:"delete"})),!0)},V1t=[{key:"Enter",run:U1t},{key:"Backspace",run:q1t}],H1t=mUn({matchClosingTags:!1});function Eke(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=L1t,completeHTMLTags:a=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=H1t}=e;if(!(s instanceof qH))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,bUn],d;i&&u.push(W1t),n instanceof HO?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?wUn(t,d):void 0;c.push(q9n({codeParser:f,htmlParser:l.language.parser})),r&&u.push(th.high(vI.of(V1t)));let p=_ke(s.configure(c));return a&&u.push(p.data.of({autocomplete:OUn})),new HO(p,u)}function OUn(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=yi(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:_Un(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let Aee=null;function _Un(){if(Aee)return Aee;let e=fUn(new rke(cs.create({extensions:H1t}),0,!0));return Aee=e?e.options:[]}const CUn=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,W1t=It.domEventHandlers({paste:(e,t)=>{var n;let{main:r}=t.state.selection;if(r.empty)return!1;let s=(n=e.clipboardData)===null||n===void 0?void 0:n.getData("text/plain");if(!s||!/^(https?:\/\/|mailto:|xmpp:|www\.)/.test(s)||(/^www\./.test(s)&&(s="https://"+s),!GO.isActiveAt(t.state,r.from,1)))return!1;let a=yi(t.state),i=!1;return a.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||CUn.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)}}),EUn=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:L1t,deleteMarkupBackward:q1t,insertNewlineContinueMarkup:U1t,insertNewlineContinueMarkupCommand:B1t,markdown:Eke,markdownKeymap:V1t,markdownLanguage:GO,pasteURLAsLink:W1t},Symbol.toStringTag,{value:"Module"}));function QO(){return QO=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},QO.apply(null,arguments)}var TUn=e=>{var t=e.theme,n=e.settings,r=n===void 0?{}:n,s=e.styles,a=s===void 0?[]:s,i={".cm-gutters":{}},l={};r.background&&(l.backgroundColor=r.background),r.backgroundImage&&(l.backgroundImage=r.backgroundImage),r.foreground&&(l.color=r.foreground),r.fontSize&&(l.fontSize=r.fontSize),(r.background||r.foreground)&&(i["&"]=l),r.fontFamily&&(i["&.cm-editor .cm-scroller"]={fontFamily:r.fontFamily}),r.gutterBackground&&(i[".cm-gutters"].backgroundColor=r.gutterBackground),r.gutterForeground&&(i[".cm-gutters"].color=r.gutterForeground),r.gutterBorder&&(i[".cm-gutters"].borderRightColor=r.gutterBorder),r.caret&&(i[".cm-content"]={caretColor:r.caret},i[".cm-cursor, .cm-dropCursor"]={borderLeftColor:r.caret});var c={};r.gutterActiveForeground&&(c.color=r.gutterActiveForeground),r.lineHighlight&&(i[".cm-activeLine"]={backgroundColor:r.lineHighlight},c.backgroundColor=r.lineHighlight),i[".cm-activeLineGutter"]=c,r.selection&&(i["&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection"]={background:r.selection+" !important"}),r.selectionMatch&&(i["& .cm-selectionMatch"]={backgroundColor:r.selectionMatch});var u=It.theme(i,{dark:t==="dark"}),d=Zg.define(a),f=[u,tS(d)];return f},jUn={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)"},NUn=[{tag:pe.comment,color:"#6272a4"},{tag:pe.string,color:"#f1fa8c"},{tag:pe.atom,color:"#bd93f9"},{tag:pe.meta,color:"#f8f8f2"},{tag:[pe.keyword,pe.operator,pe.tagName],color:"#ff79c6"},{tag:[pe.function(pe.propertyName),pe.propertyName],color:"#66d9ef"},{tag:[pe.definition(pe.variableName),pe.function(pe.variableName),pe.className,pe.attributeName],color:"#50fa7b"},{tag:pe.atom,color:"#bd93f9"}],xI=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 TUn({theme:r,settings:QO({},jUn,a),styles:[...NUn,...l]})};xI();function Z1t(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 IUn=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=jke(e.state,n.from);return r.line?AUn(e):r.block?PUn(e):!1};function Tke(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 AUn=Tke(DUn,0),RUn=Tke(G1t,0),PUn=Tke((e,t)=>G1t(e,t,MUn(t)),0);function jke(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const TR=50;function $Un(e,{open:t,close:n},r,s){let a=e.sliceDoc(r-TR,r),i=e.sliceDoc(s,s+TR),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*TR?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+TR),f=e.sliceDoc(s-TR,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 MUn(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 G1t(e,t,n=t.selection.ranges){let r=n.map(a=>jke(t,a.from).block);if(!r.every(a=>a))return null;let s=n.map((a,i)=>$Un(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 DUn(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=jke(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 Age=Vy.define(),LUn=Vy.define(),zUn=En.define(),Q1t=En.define({combine(e){return Hy(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)})}}),Y1t=xl.define({create(){return Gv.empty},update(e,t){let n=t.state.facet(Q1t),r=t.annotation(Age);if(r){let c=yf.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=AB(d,d.length,n.minDepth,c):d=J1t(d,t.startState.selection),new Gv(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(LUn);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=yf.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 Gv(e.done.map(yf.fromJSON),e.undone.map(yf.fromJSON))}});function FUn(e={}){return[Y1t,Q1t.of(e),It.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?K1t:t.inputType=="historyRedo"?Rge:null;return r?(t.preventDefault(),r(n)):!1}})]}function VH(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(Y1t,!1);if(!s)return!1;let a=s.pop(e,n,t);return a?(r(a),!0):!1}}const K1t=VH(0,!1),Rge=VH(1,!1),BUn=VH(0,!0),UUn=VH(1,!0);class yf{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 yf(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 yf(t.changes&&Rl.fromJSON(t.changes),[],t.mapped&&iy.fromJSON(t.mapped),t.startSelection&&xt.fromJSON(t.startSelection),t.selectionsAfter.map(xt.fromJSON))}static fromTransaction(t,n){let r=qh;for(let s of t.startState.facet(zUn)){let a=s(t);a.length&&(r=r.concat(a))}return!r.length&&t.changes.empty?null:new yf(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,qh)}static selection(t){return new yf(void 0,qh,void 0,void 0,t)}}function AB(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 qUn(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 VUn(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function X1t(e,t){return e.length?t.length?e.concat(t):e:t}const qh=[],HUn=200;function J1t(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-HUn));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),AB(e,e.length-1,1e9,n.setSelAfter(r)))}else return[yf.selection([t])]}function WUn(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 Ree(e,t){if(!e.length)return e;let n=e.length,r=qh;for(;n;){let s=ZUn(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?[yf.selection(r)]:qh}function ZUn(e,t,n){let r=X1t(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):qh,n);if(!e.changes)return yf.selection(r);let s=e.changes.map(t),a=t.mapDesc(e.changes,!0),i=e.mapped?e.mapped.composeDesc(a):a;return new yf(s,xr.mapEffects(e.effects,t),i,e.startSelection.map(a),r)}const GUn=/^(input\.type|delete)($|\.)/;class Gv{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 Gv(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||GUn.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(a,qUn(l.changes,t.changes))||r=="input.type.compose")?i=AB(i,i.length-1,s.minDepth,new yf(t.changes.compose(l.changes),X1t(xr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,qh)):i=AB(i,i.length,s.minDepth,t),new Gv(i,qh,n,r)}addSelection(t,n,r,s){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:qh;return a.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&VUn(a[a.length-1],t)?this:new Gv(J1t(this.done,t),this.undone,n,r)}addMapping(t){return new Gv(Ree(this.done,t),Ree(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:Age.of({side:t,rest:WUn(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(a.changes){let l=s.length==1?qh:s.slice(0,s.length-1);return a.mapped&&(l=Ree(l,a.mapped)),n.update({changes:a.changes,selection:a.startSelection,effects:a.effects,annotations:Age.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}Gv.empty=new Gv(qh,qh);const QUn=[{key:"Mod-z",run:K1t,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:Rge,preventDefault:!0},{linux:"Ctrl-Shift-z",run:Rge,preventDefault:!0},{key:"Mod-u",run:BUn,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:UUn,preventDefault:!0}];function wI(e,t){return xt.create(e.ranges.map(t),e.mainIndex)}function Gg(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function Qg({state:e,dispatch:t},n){let r=wI(e.selection,n);return r.eq(e.selection,!0)?!1:(t(Gg(e,r)),!0)}function HH(e,t){return xt.cursor(t?e.to:e.from)}function eSt(e,t){return Qg(e,n=>n.empty?e.moveByChar(n,t):HH(n,t))}function sd(e){return e.textDirectionAt(e.state.selection.main.head)==_i.LTR}const tSt=e=>eSt(e,!sd(e)),nSt=e=>eSt(e,sd(e));function rSt(e,t){return Qg(e,n=>n.empty?e.moveByGroup(n,t):HH(n,t))}const YUn=e=>rSt(e,!sd(e)),KUn=e=>rSt(e,sd(e));function XUn(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 WH(e,t,n){let r=yi(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;XUn(e,u,s)?r=u:c=n?u.to:u.from}let a=r.type.prop(s),i,l;return a&&(i=n?Zv(e,r.from,1):Zv(e,r.to,-1))&&i.matched?l=n?i.end.to:i.end.from:l=n?r.to:r.from,xt.cursor(l,n?-1:1)}const JUn=e=>Qg(e,t=>WH(e.state,t,!sd(e))),eqn=e=>Qg(e,t=>WH(e.state,t,sd(e)));function sSt(e,t){return Qg(e,n=>{if(!n.empty)return HH(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const aSt=e=>sSt(e,!1),iSt=e=>sSt(e,!0);function oSt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let a of e.state.facet(It.scrollMargins)){let i=a(e);i?.top&&(n=Math.max(i?.top,n)),i?.bottom&&(r=Math.max(i?.bottom,r))}s=e.scrollDOM.clientHeight-n-r}else s=(e.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:n,marginBottom:r,selfScroll:t,height:Math.max(e.defaultLineHeight,s-5)}}function lSt(e,t){let n=oSt(e),{state:r}=e,s=wI(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):HH(i,t));if(s.eq(r.selection))return!1;let a;if(n.selfScroll){let i=e.coordsAtPos(r.selection.main.head),l=e.scrollDOM.getBoundingClientRect(),c=l.top+n.marginTop,u=l.bottom-n.marginBottom;i&&i.top>c&&i.bottom<u&&(a=It.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(Gg(r,s),{effects:a}),!0}const b8e=e=>lSt(e,!1),Pge=e=>lSt(e,!0);function nS(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=xt.cursor(r.from+a))}return s}const tqn=e=>Qg(e,t=>nS(e,t,!0)),nqn=e=>Qg(e,t=>nS(e,t,!1)),rqn=e=>Qg(e,t=>nS(e,t,!sd(e))),sqn=e=>Qg(e,t=>nS(e,t,sd(e))),aqn=e=>Qg(e,t=>xt.cursor(e.lineBlockAt(t.head).from,1)),iqn=e=>Qg(e,t=>xt.cursor(e.lineBlockAt(t.head).to,-1));function oqn(e,t,n){let r=!1,s=wI(e.selection,a=>{let i=Zv(e,a.head,-1)||Zv(e,a.head,1)||a.head>0&&Zv(e,a.head-1,1)||a.head<e.doc.length&&Zv(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 xt.cursor(l)});return r?(t(Gg(e,s)),!0):!1}const lqn=({state:e,dispatch:t})=>oqn(e,t);function jm(e,t,n){let r=wI(e.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=t&&(s=xt.range(s.head,s.anchor));let a=n(s);return xt.range(s.anchor,a.head,a.goalColumn,a.bidiLevel||void 0,a.assoc)});return r.eq(e.state.selection)?!1:(e.dispatch(Gg(e.state,r)),!0)}function cSt(e,t){return jm(e,t,n=>e.moveByChar(n,t))}const uSt=e=>cSt(e,!sd(e)),dSt=e=>cSt(e,sd(e));function fSt(e,t){return jm(e,t,n=>e.moveByGroup(n,t))}const cqn=e=>fSt(e,!sd(e)),uqn=e=>fSt(e,sd(e)),dqn=e=>{let t=!sd(e);return jm(e,t,n=>WH(e.state,n,t))},fqn=e=>{let t=sd(e);return jm(e,t,n=>WH(e.state,n,t))};function pSt(e,t){return jm(e,t,n=>e.moveVertically(n,t))}const hSt=e=>pSt(e,!1),mSt=e=>pSt(e,!0);function gSt(e,t){return jm(e,t,n=>e.moveVertically(n,t,oSt(e).height))}const x8e=e=>gSt(e,!1),w8e=e=>gSt(e,!0),pqn=e=>jm(e,!0,t=>nS(e,t,!0)),hqn=e=>jm(e,!1,t=>nS(e,t,!1)),mqn=e=>{let t=!sd(e);return jm(e,t,n=>nS(e,n,t))},gqn=e=>{let t=sd(e);return jm(e,t,n=>nS(e,n,t))},vqn=e=>jm(e,!1,t=>xt.cursor(e.lineBlockAt(t.head).from)),yqn=e=>jm(e,!0,t=>xt.cursor(e.lineBlockAt(t.head).to)),S8e=({state:e,dispatch:t})=>(t(Gg(e,{anchor:0})),!0),k8e=({state:e,dispatch:t})=>(t(Gg(e,{anchor:e.doc.length})),!0),O8e=({state:e,dispatch:t})=>(t(Gg(e,{anchor:e.selection.main.anchor,head:0})),!0),_8e=({state:e,dispatch:t})=>(t(Gg(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),bqn=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),xqn=({state:e,dispatch:t})=>{let n=ZH(e).map(({from:r,to:s})=>xt.range(r,Math.min(s+1,e.doc.length)));return t(e.update({selection:xt.create(n),userEvent:"select"})),!0},wqn=({state:e,dispatch:t})=>{let n=wI(e.selection,r=>{let s=yi(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 xt.range(l.to,l.from)}return r});return n.eq(e.selection)?!1:(t(Gg(e,n)),!0)};function vSt(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(Gg(n,xt.create(s,s.length-1))),!0)}const Sqn=e=>vSt(e,!1),kqn=e=>vSt(e,!0),Oqn=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=xt.create([n.main]):n.main.empty||(r=xt.create([xt.cursor(n.main.head)])),r?(t(Gg(e,r)),!0):!1};function H3(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=iz(e,c,!1)):c>i&&(n="delete.forward",c=iz(e,c,!0)),i=Math.min(i,c),l=Math.max(l,c)}else i=iz(e,i,!1),l=iz(e,l,!0);return i==l?{range:a}:{changes:{from:i,to:l},range:xt.cursor(i,i<a.head?-1:1)}});return s.changes.empty?!1:(e.dispatch(r.update(s,{scrollIntoView:!0,userEvent:n,effects:n=="delete.selection"?It.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function iz(e,t,n){if(e instanceof It)for(let r of e.state.facet(It.atomicRanges).map(s=>s(e)))r.between(t,t,(s,a)=>{s<t&&a>t&&(t=n?a:s)});return t}const ySt=(e,t,n)=>H3(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=zg(l,a.tabSize),d=u%WO(a)||WO(a);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=Ec(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=Ec(i.text,c-i.from,!1,!1)+i.from);return c}),$ge=e=>ySt(e,!1,!0),bSt=e=>ySt(e,!0,!1),xSt=(e,t)=>H3(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=Ec(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}),wSt=e=>xSt(e,!1),_qn=e=>xSt(e,!0),Cqn=e=>H3(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),Eqn=e=>H3(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),Tqn=e=>H3(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),jqn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:Oa.of(["",""])},range:xt.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},Nqn=({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:Ec(a.text,s-a.from,!1)+a.from,l=s==a.to?s+1:Ec(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:xt.cursor(l)}});return n.changes.empty?!1:(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function ZH(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 SSt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let a of ZH(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(xt.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(xt.range(c.anchor-l,c.head-l))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:xt.create(s,e.selection.mainIndex),userEvent:"move.line"})),!0):!1}const Iqn=({state:e,dispatch:t})=>SSt(e,t,!1),Aqn=({state:e,dispatch:t})=>SSt(e,t,!0);function kSt(e,t,n){if(e.readOnly)return!1;let r=[];for(let a of ZH(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 Rqn=({state:e,dispatch:t})=>kSt(e,t,!1),Pqn=({state:e,dispatch:t})=>kSt(e,t,!0),$qn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(ZH(t).map(({from:s,to:a})=>(s>0?s--:a<t.doc.length&&a++,{from:s,to:a}))),r=wI(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 Mqn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=yi(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 C8e=OSt(!1),Dqn=OSt(!0);function OSt(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&&Mqn(t,a);e&&(a=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new FH(t,{simulateBreak:a,simulateDoubleBreak:!!c}),d=KSe(u,a);for(d==null&&(d=zg(/^\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=["",kM(t,d)];return c&&f.push(kM(t,u.lineIndent(l.from,-1))),{changes:{from:a,to:i,insert:Oa.of(f)},range:xt.cursor(a+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function Nke(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:xt.range(a.mapPos(r.anchor,1),a.mapPos(r.head,1))}})}const Lqn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new FH(e,{overrideIndentation:a=>{let i=n[a];return i??-1}}),s=Nke(e,(a,i,l)=>{let c=KSe(r,a.from);if(c==null)return;/\S/.test(a.text)||(c=0);let u=/^\s*/.exec(a.text)[0],d=kM(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},_St=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(Nke(e,(n,r)=>{r.push({from:n.from,insert:e.facet(yI)})}),{userEvent:"input.indent"})),!0),CSt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(Nke(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let a=zg(s,e.tabSize),i=0,l=kM(e,Math.max(0,a-WO(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),zqn=e=>(e.setTabFocusMode(),!0),Fqn=[{key:"Ctrl-b",run:tSt,shift:uSt,preventDefault:!0},{key:"Ctrl-f",run:nSt,shift:dSt},{key:"Ctrl-p",run:aSt,shift:hSt},{key:"Ctrl-n",run:iSt,shift:mSt},{key:"Ctrl-a",run:aqn,shift:vqn},{key:"Ctrl-e",run:iqn,shift:yqn},{key:"Ctrl-d",run:bSt},{key:"Ctrl-h",run:$ge},{key:"Ctrl-k",run:Cqn},{key:"Ctrl-Alt-h",run:wSt},{key:"Ctrl-o",run:jqn},{key:"Ctrl-t",run:Nqn},{key:"Ctrl-v",run:Pge}],Bqn=[{key:"ArrowLeft",run:tSt,shift:uSt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:YUn,shift:cqn,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:rqn,shift:mqn,preventDefault:!0},{key:"ArrowRight",run:nSt,shift:dSt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:KUn,shift:uqn,preventDefault:!0},{mac:"Cmd-ArrowRight",run:sqn,shift:gqn,preventDefault:!0},{key:"ArrowUp",run:aSt,shift:hSt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:S8e,shift:O8e},{mac:"Ctrl-ArrowUp",run:b8e,shift:x8e},{key:"ArrowDown",run:iSt,shift:mSt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:k8e,shift:_8e},{mac:"Ctrl-ArrowDown",run:Pge,shift:w8e},{key:"PageUp",run:b8e,shift:x8e},{key:"PageDown",run:Pge,shift:w8e},{key:"Home",run:nqn,shift:hqn,preventDefault:!0},{key:"Mod-Home",run:S8e,shift:O8e},{key:"End",run:tqn,shift:pqn,preventDefault:!0},{key:"Mod-End",run:k8e,shift:_8e},{key:"Enter",run:C8e,shift:C8e},{key:"Mod-a",run:bqn},{key:"Backspace",run:$ge,shift:$ge,preventDefault:!0},{key:"Delete",run:bSt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:wSt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:_qn,preventDefault:!0},{mac:"Mod-Backspace",run:Eqn,preventDefault:!0},{mac:"Mod-Delete",run:Tqn,preventDefault:!0}].concat(Fqn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),Uqn=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:JUn,shift:dqn},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:eqn,shift:fqn},{key:"Alt-ArrowUp",run:Iqn},{key:"Shift-Alt-ArrowUp",run:Rqn},{key:"Alt-ArrowDown",run:Aqn},{key:"Shift-Alt-ArrowDown",run:Pqn},{key:"Mod-Alt-ArrowUp",run:Sqn},{key:"Mod-Alt-ArrowDown",run:kqn},{key:"Escape",run:Oqn},{key:"Mod-Enter",run:Dqn},{key:"Alt-l",mac:"Ctrl-l",run:xqn},{key:"Mod-i",run:wqn,preventDefault:!0},{key:"Mod-[",run:CSt},{key:"Mod-]",run:_St},{key:"Mod-Alt-\\",run:Lqn},{key:"Shift-Mod-k",run:$qn},{key:"Shift-Mod-\\",run:lqn},{key:"Mod-/",run:IUn},{key:"Alt-A",run:RUn},{key:"Ctrl-m",mac:"Shift-Alt-m",run:zqn}].concat(Bqn),qqn={key:"Tab",run:_St,shift:CSt},E8e=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class Lx{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(E8e(l)):E8e,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 uf(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=ASe(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=Mv(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"&&(Lx.prototype[Symbol.iterator]=function(){return this});const ESt={from:-1,to:-1,match:/.*/.exec(""),precise:!0},Ike="gm"+(/x/.unicode==null?"":"u");class TSt{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=ESt,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new jSt(t,n,r,s,a);this.re=new RegExp(n,Ike+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=RB(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=RB(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 Pee=new WeakMap;class KT{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=Pee.get(t);if(!s||s.from>=r||s.to<=n){let l=new KT(n,t.sliceString(n,r));return Pee.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)),Pee.set(t,new KT(i,a)),new KT(n,a.slice(n-i,r-i))}}class jSt{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=ESt,this.matchPos=RB(t,s),this.re=new RegExp(n,Ike+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=KT.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=RB(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=KT.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(TSt.prototype[Symbol.iterator]=jSt.prototype[Symbol.iterator]=function(){return this});function Vqn(e){try{return new RegExp(e,Ike),!0}catch{return!1}}function RB(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 Hqn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=CFn(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(a=>{let i=a&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(a.elements.line.value);if(!i){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,u,d,f]=i,p=d?+d.slice(1):0,h=u?+u:l.number;if(u&&f){let y=h/100;c&&(y=y*(c=="-"?-1:1)+l.number/t.doc.lines),h=Math.round(t.doc.lines*y)}else u&&c&&(h=h*(c=="-"?-1:1)+l.number);let m=t.doc.line(Math.max(1,Math.min(t.doc.lines,h))),g=xt.cursor(m.from+Math.max(0,Math.min(p,m.length)));e.dispatch({effects:[r,It.scrollIntoView(g.from,{y:"center"})],selection:g})}),!0},Wqn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Zqn=En.define({combine(e){return Hy(e,Wqn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function Gqn(e){return[Jqn,Xqn]}const Qqn=jn.mark({class:"cm-selectionMatch"}),Yqn=jn.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function T8e(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=ko.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=ko.Word)}function Kqn(e,t,n,r){return e(t.sliceDoc(n,n+1))==ko.Word&&e(t.sliceDoc(r-1,r))==ko.Word}const Xqn=To.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(Zqn),{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),!(T8e(i,n,s.from,s.to)&&Kqn(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 Lx(n.doc,a,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||T8e(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(Yqn.range(d,f)):(d>=s.to||f<=s.from)&&l.push(Qqn.range(d,f)),l.length>t.maxMatches))return jn.none}}return jn.set(l)}},{decorations:e=>e.decorations}),Jqn=It.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),eVn=({state:e,dispatch:t})=>{let{selection:n}=e,r=xt.create(n.ranges.map(s=>e.wordAt(s.head)||xt.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function tVn(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 Lx(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new Lx(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 nVn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return eVn({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=tVn(e,r);return s?(t(e.update({selection:e.selection.addRange(xt.range(s.from,s.to),!1),effects:It.scrollIntoView(s.to)})),!0):!1},SI=En.define({combine(e){return Hy(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new gVn(t),scrollToMatch:t=>It.scrollIntoView(t)})}});class NSt{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||Vqn(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"?`
336
- `: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 lVn(this):new aVn(this)}getCursor(t,n=0,r){let s=t.doc?t:cs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?GE(this,s,n,r):ZE(this,s,n,r)}}class ISt{constructor(t){this.spec=t}}function rVn(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 ZE(e,t,n,r){let s;return e.wholeWord&&(s=sVn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=rVn(e.test,t,s)),new Lx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function sVn(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(PB(s,n-a))!=ko.Word||t($B(s,n-a))!=ko.Word)&&(t($B(s,r-a))!=ko.Word||t(PB(s,r-a))!=ko.Word))}class aVn extends ISt{constructor(t){super(t)}nextMatch(t,n,r){let s=ZE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=ZE(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=ZE(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=ZE(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=ZE(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 iVn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function GE(e,t,n,r){let s;return e.wholeWord&&(s=oVn(t.charCategorizer(t.selection.main.head))),e.test&&(s=iVn(e.test,t,s)),new TSt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function PB(e,t){return e.slice(Ec(e,t,!1),t)}function $B(e,t){return e.slice(t,Ec(e,t))}function oVn(e){return(t,n,r)=>!r[0].length||(e(PB(r.input,r.index))!=ko.Word||e($B(r.input,r.index))!=ko.Word)&&(e($B(r.input,r.index+r[0].length))!=ko.Word||e(PB(r.input,r.index+r[0].length))!=ko.Word)}class lVn extends ISt{nextMatch(t,n,r){let s=GE(this.spec,t,r,t.doc.length).next();return s.done&&(s=GE(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=GE(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=GE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=GE(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const AM=xr.define(),Ake=xr.define(),Kw=xl.define({create(e){return new $ee(Mge(e).create(),null)},update(e,t){for(let n of t.effects)n.is(AM)?e=new $ee(n.value.create(),e.panel):n.is(Ake)&&(e=new $ee(e.query,n.value?Rke:null));return e},provide:e=>SM.from(e,t=>t.panel)});class $ee{constructor(t,n){this.query=t,this.panel=n}}const cVn=jn.mark({class:"cm-searchMatch"}),uVn=jn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),dVn=To.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Kw))}update(e){let t=e.state.field(Kw);(t!=e.startState.field(Kw)||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 Ld;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?uVn:cVn)})}return r.finish()}},{decorations:e=>e.decorations});function W3(e){return t=>{let n=t.state.field(Kw,!1);return n&&n.query.spec.valid?e(t,n):PSt(t)}}const MB=W3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=xt.single(r.from,r.to),a=e.state.facet(SI);return e.dispatch({selection:s,effects:[Pke(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),RSt(e),!0}),DB=W3((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=xt.single(s.from,s.to),i=e.state.facet(SI);return e.dispatch({selection:a,effects:[Pke(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),RSt(e),!0}),fVn=W3((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:xt.create(n.map(r=>xt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),pVn=({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 Lx(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(xt.range(l.value.from,l.value.to))}return t(e.update({selection:xt.create(a,i),userEvent:"select.search.matches"})),!0},j8e=W3((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(It.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=xt.single(i.from,i.to).map(f),d.push(Pke(e,i)),d.push(n.facet(SI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),hVn=W3((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:It.announce.of(r),userEvent:"input.replace.all"}),!0});function Rke(e){return e.state.facet(SI).createPanel(e)}function Mge(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(SI);return new NSt({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 ASt(e){let t=QSe(e,Rke);return t&&t.dom.querySelector("[main-field]")}function RSt(e){let t=ASt(e);t&&t==e.root.activeElement&&t.select()}const PSt=e=>{let t=e.state.field(Kw,!1);if(t&&t.panel){let n=ASt(e);if(n&&n!=e.root.activeElement){let r=Mge(e.state,t.query.spec);r.valid&&e.dispatch({effects:AM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Ake.of(!0),t?AM.of(Mge(e.state,t.query.spec)):xr.appendConfig.of(yVn)]});return!0},$St=e=>{let t=e.state.field(Kw,!1);if(!t||!t.panel)return!1;let n=QSe(e,Rke);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Ake.of(!1)}),!0},mVn=[{key:"Mod-f",run:PSt,scope:"editor search-panel"},{key:"F3",run:MB,shift:DB,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:MB,shift:DB,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:$St,scope:"editor search-panel"},{key:"Mod-Shift-l",run:pVn},{key:"Mod-Alt-g",run:Hqn},{key:"Mod-d",run:nVn,preventDefault:!0}];class gVn{constructor(t){this.view=t;let n=this.query=t.state.field(Kw).query.spec;this.commit=this.commit.bind(this),this.searchField=pi("input",{value:n.search,placeholder:lp(t,"Find"),"aria-label":lp(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=pi("input",{value:n.replace,placeholder:lp(t,"Replace"),"aria-label":lp(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=pi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=pi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=pi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return pi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=pi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>MB(t),[lp(t,"next")]),r("prev",()=>DB(t),[lp(t,"previous")]),r("select",()=>fVn(t),[lp(t,"all")]),pi("label",null,[this.caseField,lp(t,"match case")]),pi("label",null,[this.reField,lp(t,"regexp")]),pi("label",null,[this.wordField,lp(t,"by word")]),...t.state.readOnly?[]:[pi("br"),this.replaceField,r("replace",()=>j8e(t),[lp(t,"replace")]),r("replaceAll",()=>hVn(t),[lp(t,"replace all")])],pi("button",{name:"close",onclick:()=>$St(t),"aria-label":lp(t,"close"),type:"button"},["×"])])}commit(){let t=new NSt({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:AM.of(t)}))}keydown(t){Mzn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?DB:MB)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),j8e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(AM)&&!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(SI).top}}function lp(e,t){return e.state.phrase(t)}const oz=30,lz=/[\s\.,:;?!]/;function Pke(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-oz),i=Math.min(s,n+oz),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<oz;c++)if(!lz.test(l[c+1])&&lz.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-oz;c--)if(!lz.test(l[c-1])&&lz.test(l[c])){l=l.slice(0,c);break}}return It.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const vVn=It.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),yVn=[Kw,th.low(dVn),vVn];class N8e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class jk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(RM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Ld,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((g,y)=>Math.min(g,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let g=a[d];if(g.from==p&&(g.to>g.from||g.to==p))l.push(g),d++,h=Math.min(g.to,h);else{h=Math.min(g.from,h);break}}let m=IVn(l);if(l.some(g=>g.from==g.to||g.from==g.to-1&&r.doc.lineAt(g.from).to==g.from))i.add(p,p,jn.widget({widget:new EVn(m),diagnostics:l.slice()}));else{let g=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,jn.mark({class:"cm-lintRange cm-lintRange-"+m+g,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let g=0;g<l.length;g++)l[g].to<=c&&l.splice(g--,1)}let u=i.finish();return new jk(u,n,Qj(u))}}function Qj(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 N8e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new N8e(r.from,a,r.diagnostic)}}),r}function bVn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(RM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(MSt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function xVn(e,t){return e.field(Np,!1)?t:t.concat(xr.appendConfig.of(AVn))}const MSt=xr.define(),$ke=xr.define(),DSt=xr.define(),Np=xl.define({create(){return new jk(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=Qj(n,e.selected.diagnostic,a)||Qj(n,null,a)}!n.size&&s&&t.state.facet(RM).autoPanel&&(s=null),e=new jk(n,s,r)}for(let n of t.effects)if(n.is(MSt)){let r=t.state.facet(RM).autoPanel?n.value.length?PM.open:null:e.panel;e=jk.init(n.value,r,t.state)}else n.is($ke)?e=new jk(e.diagnostics,n.value?PM.open:null,e.selected):n.is(DSt)&&(e=new jk(e.diagnostics,e.panel,n.value));return e},provide:e=>[SM.from(e,t=>t.panel),It.decorations.from(e,t=>t.diagnostics)]}),wVn=jn.mark({class:"cm-lintRange cm-lintRange-active"});function SVn(e,t,n){let{diagnostics:r}=e.state.field(Np),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(RM).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:kVn(e,s)}}}:null}function kVn(e,t){return pi("ul",{class:"cm-tooltip-lint"},t.map(n=>zSt(e,n,!1)))}const OVn=e=>{let t=e.state.field(Np,!1);(!t||!t.panel)&&e.dispatch({effects:xVn(e.state,[$ke.of(!0)])});let n=QSe(e,PM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},I8e=e=>{let t=e.state.field(Np,!1);return!t||!t.panel?!1:(e.dispatch({effects:$ke.of(!1)}),!0)},_Vn=e=>{let t=e.state.field(Np,!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)},CVn=[{key:"Mod-Shift-m",run:OVn,preventDefault:!0},{key:"F8",run:_Vn}],RM=En.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Hy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:A8e,tooltipFilter:A8e,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 A8e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function LSt(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 zSt(e,t,n){var r;let s=n?LSt(t.actions):[];return pi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},pi("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=Qj(e.state.field(Np).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),pi("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return pi("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&pi("div",{class:"cm-diagnosticSource"},t.source))}class EVn extends nh{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return pi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class R8e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=zSt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class PM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)I8e(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=LSt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=Qj(this.view.state.field(Np).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=pi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=pi("div",{class:"cm-panel-lint"},this.list,pi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>I8e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Np).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(Np),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 R8e(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 R8e(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(Np),r=Qj(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:DSt.of(r)})}static open(t){return new PM(t)}}function TVn(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 cz(e){return TVn(`<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 jVn=It.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:cz("#d11")},".cm-lintRange-warning":{backgroundImage:cz("orange")},".cm-lintRange-info":{backgroundImage:cz("#999")},".cm-lintRange-hint":{backgroundImage:cz("#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 IVn(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 AVn=[Np,It.decorations.compute([Np],e=>{let{selected:t,panel:n}=e.field(Np);return!t||!n||t.from==t.to?jn.none:jn.set([wVn.range(t.from,t.to)])}),OFn(SVn,{hideOn:bVn}),jVn];var P8e=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(w9n)),t.defaultKeymap!==!1&&(a=a.concat(Uqn)),t.searchKeymap!==!1&&(a=a.concat(mVn)),t.historyKeymap!==!1&&(a=a.concat(QUn)),t.foldKeymap!==!1&&(a=a.concat(i8n)),t.completionKeymap!==!1&&(a=a.concat(Rwt)),t.lintKeymap!==!1&&(a=a.concat(CVn));var i=[];return t.lineNumbers!==!1&&i.push(MFn()),t.highlightActiveLineGutter!==!1&&i.push(zFn()),t.highlightSpecialChars!==!1&&i.push(Xzn()),t.history!==!1&&i.push(FUn()),t.foldGutter!==!1&&i.push(u8n()),t.drawSelection!==!1&&i.push(Uzn()),t.dropCursor!==!1&&i.push(Zzn()),t.allowMultipleSelections!==!1&&i.push(cs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(XFn()),t.syntaxHighlighting!==!1&&i.push(tS(h8n,{fallback:!0})),t.bracketMatching!==!1&&i.push(w8n()),t.closeBrackets!==!1&&i.push(v9n()),t.autocompletion!==!1&&i.push(Awt()),t.rectangularSelection!==!1&&i.push(fFn()),s!==!1&&i.push(mFn()),t.highlightActiveLine!==!1&&i.push(sFn()),t.highlightSelectionMatches!==!1&&i.push(Gqn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(yI.of(" ".repeat(t.tabSize))),i.concat([vI.of(a.flat())]).filter(Boolean)};const RVn="#e5c07b",$8e="#e06c75",PVn="#56b6c2",$Vn="#ffffff",q8="#abb2bf",Dge="#7d8799",MVn="#61afef",DVn="#98c379",M8e="#d19a66",LVn="#c678dd",zVn="#21252b",D8e="#2c313a",L8e="#282c34",Mee="#353a42",FVn="#3E4451",z8e="#528bff",BVn=It.theme({"&":{color:q8,backgroundColor:L8e},".cm-content":{caretColor:z8e},".cm-cursor, .cm-dropCursor":{borderLeftColor:z8e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:FVn},".cm-panels":{backgroundColor:zVn,color:q8},".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:L8e,color:Dge,border:"none"},".cm-activeLineGutter":{backgroundColor:D8e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Mee},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Mee,borderBottomColor:Mee},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:D8e,color:q8}}},{dark:!0}),UVn=Zg.define([{tag:pe.keyword,color:LVn},{tag:[pe.name,pe.deleted,pe.character,pe.propertyName,pe.macroName],color:$8e},{tag:[pe.function(pe.variableName),pe.labelName],color:MVn},{tag:[pe.color,pe.constant(pe.name),pe.standard(pe.name)],color:M8e},{tag:[pe.definition(pe.name),pe.separator],color:q8},{tag:[pe.typeName,pe.className,pe.number,pe.changed,pe.annotation,pe.modifier,pe.self,pe.namespace],color:RVn},{tag:[pe.operator,pe.operatorKeyword,pe.url,pe.escape,pe.regexp,pe.link,pe.special(pe.string)],color:PVn},{tag:[pe.meta,pe.comment],color:Dge},{tag:pe.strong,fontWeight:"bold"},{tag:pe.emphasis,fontStyle:"italic"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:pe.link,color:Dge,textDecoration:"underline"},{tag:pe.heading,fontWeight:"bold",color:$8e},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:M8e},{tag:[pe.processingInstruction,pe.string,pe.inserted],color:DVn},{tag:pe.invalid,color:$Vn}]),qVn=[BVn,tS(UVn)];var VVn=It.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),HVn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,g=[];switch(s&&g.unshift(vI.of([qqn])),m&&(typeof m=="boolean"?g.unshift(P8e()):g.unshift(P8e(m))),p&&g.unshift(lFn(p)),d){case"light":g.push(VVn);break;case"dark":g.push(qVn);break;case"none":break;default:g.push(d);break}return i===!1&&g.push(It.editable.of(!1)),c&&g.push(cs.readOnly.of(!0)),[...g]},WVn=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 ZVn{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 F8e{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 Dee=null,GVn=()=>typeof window>"u"?new F8e:(Dee||(Dee=new F8e),Dee),QVn=It.theme({"& .cm-scroller":{height:"100% !important"}}),B8e=null,Lee=null;function YVn(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===B8e||(B8e=i,Lee=It.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),Lee}var U8e=Vy.define(),KVn=200,XVn=[];function JVn(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?XVn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,g=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,S=x===void 0?null:x,k=e.minWidth,C=k===void 0?null:k,_=e.maxWidth,E=_===void 0?null:_,T=e.placeholder,N=T===void 0?"":T,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,D=e.indentWithTab,z=D===void 0?!0:D,H=e.basicSetup,F=H===void 0?!0:H,U=e.root,q=e.initialState,M=v.useState(),G=M[0],V=M[1],$=v.useState(),B=$[0],Z=$[1],K=v.useState(),ne=K[0],ee=K[1],J=v.useState(()=>({current:null}))[0],ae=v.useState(()=>({current:null}))[0],fe=YVn(h,g,b,S,C,E),Y=It.updateListener.of(ue=>{if(ue.docChanged&&typeof r=="function"&&!ue.transactions.some(be=>be.annotation(U8e))){J.current?J.current.reset():(J.current=new ZVn(()=>{if(ae.current){var be=ae.current;ae.current=null,be()}J.current=null},KVn),GVn().add(J.current));var oe=ue.state.doc,me=oe.toString();r(me,ue)}s&&s(WVn(ue))}),re=HVn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:z,basicSetup:F}),le=[Y,...fe?[fe]:[],QVn,...re];return i&&typeof i=="function"&&le.push(It.updateListener.of(i)),le=le.concat(c),v.useLayoutEffect(()=>{if(G&&!ne){var ue={doc:t,selection:n,extensions:le},oe=q?cs.fromJSON(q.json,ue,q.fields):cs.create(ue);if(ee(oe),!B){var me=new It({state:oe,parent:G,root:U});Z(me),a&&a(me,oe)}}return()=>{B&&(ee(void 0),Z(void 0))}},[G,ne]),v.useEffect(()=>{e.container&&V(e.container)},[e.container]),v.useEffect(()=>()=>{B&&(B.destroy(),Z(void 0)),J.current&&(J.current.cancel(),J.current=null)},[B]),v.useEffect(()=>{u&&B&&B.focus()},[u,B]),v.useEffect(()=>{B&&B.dispatch({effects:xr.reconfigure.of(le)})},[f,c,h,g,b,S,C,E,N,A,L,z,F,r,i]),v.useEffect(()=>{if(t!==void 0){var ue=B?B.state.doc.toString():"";if(B&&t!==ue){var oe=J.current&&!J.current.isDone,me=()=>{B&&t!==B.state.doc.toString()&&B.dispatch({changes:{from:0,to:B.state.doc.toString().length,insert:t||""},annotations:[U8e.of(!0)]})};oe?ae.current=me:me()}}},[t,B]),{state:ne,setState:ee,view:B,setView:Z,container:G,setContainer:V}}var eHn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],ed=v.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,g=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,S=e.minWidth,k=e.maxWidth,C=e.basicSetup,_=e.placeholder,E=e.indentWithTab,T=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=Z1t(e,eHn),L=v.useRef(null),D=JVn({root:I,value:s,autoFocus:p,theme:m,height:g,minHeight:y,maxHeight:b,width:x,minWidth:S,maxWidth:k,basicSetup:C,placeholder:_,indentWithTab:E,editable:T,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),z=D.state,H=D.view,F=D.container,U=D.setContainer;v.useImperativeHandle(t,()=>({editor:L.current,state:z,view:H}),[L,F,z,H]);var q=v.useCallback(G=>{L.current=G,U(G)},[U]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",QO({ref:q,className:""+M+(n?" "+n:"")},R))});ed.displayName="CodeMirror";const tHn={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 zee=null;function nHn(){return zee||(zee=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([vo(()=>import("./core-Dk-S7GEf.js"),__vite__mapDeps([0,1,2]),import.meta.url),vo(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[vo(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),vo(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[vo(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),vo(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),vo(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),vo(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),vo(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),vo(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),vo(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),vo(()=>import("./python-DhUJRlN_.js"),[],import.meta.url)],engine:t()})})()),zee}async function rHn(e,t){const n=tHn[t?.toLowerCase()];if(!n)return null;const r=await nHn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function sHn(e){return new HO(eke.define(e))}const FSt=[og.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return vo(()=>Promise.resolve().then(()=>az),void 0,import.meta.url).then(e=>e.javascript())}}),og.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return vo(()=>Promise.resolve().then(()=>R8n),void 0,import.meta.url).then(e=>e.json())}}),og.of({name:"JSX",extensions:["jsx"],load(){return vo(()=>Promise.resolve().then(()=>az),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),og.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return vo(()=>Promise.resolve().then(()=>EUn),void 0,import.meta.url).then(e=>e.markdown())}}),og.of({name:"TSX",extensions:["tsx"],load(){return vo(()=>Promise.resolve().then(()=>az),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),og.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return vo(()=>Promise.resolve().then(()=>az),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),og.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return vo(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>sHn(e.shell))}})];function aHn(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 iHn(e){const t=aHn(e);return Awt({override:[oHn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function oHn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,p)=>{const g=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:g},selection:{anchor:f+g.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const lHn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,cHn=jn.mark({class:"cm-variable-highlight"}),q8e=new W0t({regexp:lHn,decoration:()=>cHn}),uHn=To.fromClass(class{decorations;constructor(e){this.decorations=q8e.createDeco(e)}update(e){this.decorations=q8e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),dHn=uHn;function fHn(){const e=xI({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:[pe.className,pe.propertyName],color:"var(--neutral6)"},{tag:pe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.heading1,pe.heading2,pe.heading3,pe.heading4,pe.heading5,pe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:pe.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:pe.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:pe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:pe.url,color:"var(--accent3)"},{tag:pe.monospace,color:"var(--neutral6)"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:pe.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=It.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function pHn(){const e=It.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=Zg.define([{tag:[pe.comment,pe.bracket],color:"var(--neutral2)"},{tag:[pe.string,pe.meta,pe.regexp],color:"var(--accent1)"},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:"var(--accent6)"},{tag:[pe.keyword,pe.operator,pe.tagName],color:"var(--accent2)"},{tag:[pe.function(pe.propertyName),pe.propertyName],color:"var(--accent5)"},{tag:[pe.definition(pe.variableName),pe.function(pe.variableName),pe.className,pe.attributeName],color:"var(--accent3)"},{tag:[pe.variableName,pe.number],color:"var(--accent5)"},{tag:[pe.name,pe.quote],color:"var(--accent1)"},{tag:pe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.heading1,pe.heading2,pe.heading3,pe.heading4,pe.heading5,pe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[pe.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:pe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:pe.url,color:"var(--accent3)"},{tag:pe.monospace,color:"var(--neutral6)"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:[pe.deleted],color:"var(--accent2)"},{tag:pe.invalid,color:"var(--error)"},{tag:[pe.standard(pe.tagName)],color:"var(--accent1)"}]);return[e,tS(t)]}const o0=()=>{const e=Z_().resolvedTheme==="dark";return v.useMemo(()=>e?fHn():pHn(),[e])},hHn=co(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"}}),mHn=th.highest(It.editorAttributes.of({style:"outline: none"})),gHn=th.highest(It.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),vHn=[mHn,gHn],Hr=v.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,...m},g)=>{const y=o0(),b=e?JSON.stringify(e,null,2):t??"",x=v.useMemo(()=>{const S=[...vHn];return f&&S.push(It.lineWrapping),a==="json"?S.push(Dp):a==="markdown"&&S.push(Eke({base:GO,codeLanguages:FSt})),i&&a==="markdown"&&S.push(dHn),c&&a==="markdown"&&S.push(iHn(c)),p===!1&&S.push(cs.readOnly.of(!0)),S},[a,i,c,p,f]);return o.jsxs("div",{className:X(hHn({variant:h}),s),...m,children:[r&&o.jsx(Pa,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(ed,{ref:g,value:b,theme:y,extensions:x,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),yHn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},bHn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=o0(),{settings:r,setSettings:s}=xH(),a=r?.tracingOptions,i=v.useMemo(()=>yHn(a),[a]),[l,c]=v.useState(()=>i),u=v.useRef(!1);v.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(ed,{value:l,onChange:d,theme:n,extensions:[Dp],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(ce,{type:"button",onClick:f,children:"Save"})})]})},xHn=()=>{const[e,t]=v.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx(ce,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(qe,{children:o.jsx(dV,{})})})}),o.jsx(Pn,{children:"Run Options"})]}),o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Run Options"}),o.jsx(Bs,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Rr,{children:o.jsx(bHn,{onSaved:()=>t(!1)})})]})})]})};function wHn({status:e}){switch(e){case"running":return o.jsx(Jt,{});case"failed":return o.jsx(ps,{className:"text-accent2"});case"canceled":return o.jsx($f,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(yj,{className:"text-neutral3"});case"suspended":return o.jsx(aV,{className:"text-accent3"});case"success":return o.jsx(fa,{className:"text-accent1"});default:return o.jsx(yj,{className:"text-neutral3"})}}function BSt({status:e}){return o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx(qe,{"aria-label":e,className:"shrink-0",children:o.jsx(wHn,{status:e})})}),o.jsx(Pn,{children:e})]})}var Fee,V8e;function Mke(){if(V8e)return Fee;V8e=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([g,y]){d(g)&&f.setNode(g,y)}),Object.values(this._edgeObjs).forEach(function(g){f.hasNode(g.v)&&f.hasNode(g.w)&&f.setEdge(g,p.edge(g))});var h={};function m(g){var y=p.parent(g);return y===void 0||f.hasNode(y)?(h[g]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(g=>f.setParent(g,m(g))),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,g){return h.length>1?p.setEdge(m,g,f):p.setEdge(m,g),g}),this}setEdge(){var d,f,p,h,m=!1,g=arguments[0];typeof g=="object"&&g!==null&&"v"in g?(d=g.v,f=g.w,p=g.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=g,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 g=h;h=m,m=g}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 g=h;h=m,m=g}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 Fee=r,Fee}var Bee,H8e;function SHn(){return H8e||(H8e=1,Bee="2.2.4"),Bee}var Uee,W8e;function kHn(){return W8e||(W8e=1,Uee={Graph:Mke(),version:SHn()}),Uee}var qee,Z8e;function OHn(){if(Z8e)return qee;Z8e=1;var e=Mke();qee={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 qee}var Vee,G8e;function _Hn(){if(G8e)return Vee;G8e=1,Vee=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 Vee}var Hee,Q8e;function USt(){if(Q8e)return Hee;Q8e=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 Hee=e,Hee}var Wee,Y8e;function qSt(){if(Y8e)return Wee;Y8e=1;var e=USt();Wee=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,g=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<g.distance&&(g.distance=b,g.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 Wee}var Zee,K8e;function CHn(){if(K8e)return Zee;K8e=1;var e=qSt();Zee=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Zee}var Gee,X8e;function VSt(){if(X8e)return Gee;X8e=1,Gee=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 Gee}var Qee,J8e;function EHn(){if(J8e)return Qee;J8e=1;var e=VSt();Qee=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return Qee}var Yee,e9e;function THn(){if(e9e)return Yee;e9e=1,Yee=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],g=f[p],y=h.distance+m.distance;y<g.distance&&(g.distance=y,g.predecessor=m.predecessor)})})}),i}return Yee}var Kee,t9e;function HSt(){if(t9e)return Kee;t9e=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 Kee=e,e.CycleException=t,Kee}var Xee,n9e;function jHn(){if(n9e)return Xee;n9e=1;var e=HSt();Xee=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return Xee}var Jee,r9e;function WSt(){if(r9e)return Jee;r9e=1,Jee=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 Jee}var ete,s9e;function NHn(){if(s9e)return ete;s9e=1;var e=WSt();ete=t;function t(n,r){return e(n,r,"post")}return ete}var tte,a9e;function IHn(){if(a9e)return tte;a9e=1;var e=WSt();tte=t;function t(n,r){return e(n,r,"pre")}return tte}var nte,i9e;function AHn(){if(i9e)return nte;i9e=1;var e=Mke(),t=USt();nte=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 nte}var rte,o9e;function RHn(){return o9e||(o9e=1,rte={components:_Hn(),dijkstra:qSt(),dijkstraAll:CHn(),findCycles:EHn(),floydWarshall:THn(),isAcyclic:jHn(),postorder:NHn(),preorder:IHn(),prim:AHn(),tarjan:VSt(),topsort:HSt()}),rte}var ste,l9e;function Bg(){if(l9e)return ste;l9e=1;var e=kHn();return ste={Graph:e.Graph,json:OHn(),alg:RHn(),version:e.version},ste}var ate,c9e;function PHn(){if(c9e)return ate;c9e=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 ate=e,ate}var ite,u9e;function $Hn(){if(u9e)return ite;u9e=1;let e=Bg().Graph,t=PHn();ite=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],g;for(;u.nodeCount();){for(;g=m.dequeue();)a(u,d,f,g);for(;g=h.dequeue();)a(u,d,f,g);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(g=d[y].dequeue(),g){p=p.concat(a(u,d,f,g,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(g=>{let y=u.edge(g),b=u.node(g.v);h&&m.push({v:g.v,w:g.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(g=>{let y=u.edge(g),b=g.w,x=u.node(b);x.in-=y,l(d,f,x)}),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,x=d(y),S=b+x;f.setEdge(y.v,y.w,S),h=Math.max(h,f.node(y.v).out+=x),p=Math.max(p,f.node(y.w).in+=x)});let m=c(h+p+3).map(()=>new t),g=p+1;return f.nodes().forEach(y=>{l(m,g,f.node(y))}),{graph:f,buckets:m,zeroIdx:g}}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 ite}var ote,d9e;function Ll(){if(d9e)return ote;d9e=1;let e=Bg().Graph;ote={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:_,maxRank:m,normalizeRanks:c,notime:b,partition:g,pick:C,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:S,zipObject:E};function t(T,N,I,A){for(var R=A;T.hasNode(R);)R=S(A);return I.dummy=N,T.setNode(R,I),R}function n(T){let N=new e().setGraph(T.graph());return T.nodes().forEach(I=>N.setNode(I,T.node(I))),T.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=T.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(T){let N=new e({multigraph:T.isMultigraph()}).setGraph(T.graph());return T.nodes().forEach(I=>{T.children(I).length||N.setNode(I,T.node(I))}),T.edges().forEach(I=>{N.setEdge(I,T.edge(I))}),N}function s(T){let N=T.nodes().map(I=>{let A={};return T.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function a(T){let N=T.nodes().map(I=>{let A={};return T.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function i(T,N){let I=T.x,A=T.y,R=N.x-I,L=N.y-A,D=T.width/2,z=T.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,F;return Math.abs(L)*D>Math.abs(R)*z?(L<0&&(z=-z),H=z*R/L,F=z):(R<0&&(D=-D),H=D,F=D*L/R),{x:I+H,y:A+F}}function l(T){let N=k(m(T)+1).map(()=>[]);return T.nodes().forEach(I=>{let A=T.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(T){let N=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,N);T.nodes().forEach(A=>{let R=T.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(T){let N=T.nodes().map(D=>T.node(D).rank),I=h(Math.min,N),A=[];T.nodes().forEach(D=>{let z=T.node(D).rank-I;A[z]||(A[z]=[]),A[z].push(D)});let R=0,L=T.graph().nodeRankFactor;Array.from(A).forEach((D,z)=>{D===void 0&&z%L!==0?--R:D!==void 0&&R&&D.forEach(H=>T.node(H).rank+=R)})}function d(T,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(T,"border",R,N)}function f(T,N=p){const I=[];for(let A=0;A<T.length;A+=N){const R=T.slice(A,A+N);I.push(R)}return I}const p=65535;function h(T,N){if(N.length>p){const I=f(N);return T.apply(null,I.map(A=>T.apply(null,A)))}else return T.apply(null,N)}function m(T){const I=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function g(T,N){let I={lhs:[],rhs:[]};return T.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(T,N){let I=Date.now();try{return N()}finally{console.log(T+" time: "+(Date.now()-I)+"ms")}}function b(T,N){return N()}let x=0;function S(T){var N=++x;return T+(""+N)}function k(T,N,I=1){N==null&&(N=T,T=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=T;A(L);L+=I)R.push(L);return R}function C(T,N){const I={};for(const A of N)T[A]!==void 0&&(I[A]=T[A]);return I}function _(T,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(T).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function E(T,N){return T.reduce((I,A,R)=>(I[A]=N[R],I),{})}return ote}var lte,f9e;function MHn(){if(f9e)return lte;f9e=1;let e=$Hn(),t=Ll().uniqueId;lte={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 lte}var cte,p9e;function DHn(){if(p9e)return cte;p9e=1;let e=Ll();cte={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,g;for(g=0,++l;l<u;++g,++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),g===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 cte}var ute,h9e;function LB(){if(h9e)return ute;h9e=1;const{applyWithChunking:e}=Ll();ute={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 ute}var dte,m9e;function ZSt(){if(m9e)return dte;m9e=1;var e=Bg().Graph,t=LB().slack;dte=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 dte}var fte,g9e;function LHn(){if(g9e)return fte;g9e=1;var e=ZSt(),t=LB().slack,n=LB().longestPath,r=Bg().alg.preorder,s=Bg().alg.postorder,a=Ll().simplify;fte=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(x){x=a(x),n(x);var S=e(x);d(S),l(S,x);for(var k,C;k=p(S);)C=h(S,x,k),m(S,x,k,C)}function l(x,S){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(C=>c(x,S,C))}function c(x,S,k){var C=x.node(k),_=C.parent;x.edge(k,_).cutvalue=u(x,S,k)}function u(x,S,k){var C=x.node(k),_=C.parent,E=!0,T=S.edge(k,_),N=0;return T||(E=!1,T=S.edge(_,k)),N=T.weight,S.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==_){var L=A===E,D=S.edge(I).weight;if(N+=L?D:-D,y(x,k,R)){var z=x.edge(k,R).cutvalue;N+=L?-z:z}}}),N}function d(x,S){arguments.length<2&&(S=x.nodes()[0]),f(x,{},1,S)}function f(x,S,k,C,_){var E=k,T=x.node(C);return S[C]=!0,x.neighbors(C).forEach(N=>{Object.hasOwn(S,N)||(k=f(x,S,k,N,C))}),T.low=E,T.lim=k++,_?T.parent=_:delete T.parent,k}function p(x){return x.edges().find(S=>x.edge(S).cutvalue<0)}function h(x,S,k){var C=k.v,_=k.w;S.hasEdge(C,_)||(C=k.w,_=k.v);var E=x.node(C),T=x.node(_),N=E,I=!1;E.lim>T.lim&&(N=T,I=!0);var A=S.edges().filter(R=>I===b(x,x.node(R.v),N)&&I!==b(x,x.node(R.w),N));return A.reduce((R,L)=>t(S,L)<t(S,R)?L:R)}function m(x,S,k,C){var _=k.v,E=k.w;x.removeEdge(_,E),x.setEdge(C.v,C.w,{}),d(x),l(x,S),g(x,S)}function g(x,S){var k=x.nodes().find(_=>!S.node(_).parent),C=r(x,k);C=C.slice(1),C.forEach(_=>{var E=x.node(_).parent,T=S.edge(_,E),N=!1;T||(T=S.edge(E,_),N=!0),S.node(_).rank=S.node(E).rank+(N?T.minlen:-T.minlen)})}function y(x,S,k){return x.hasEdge(S,k)}function b(x,S,k){return k.low<=S.lim&&S.lim<=k.lim}return fte}var pte,v9e;function zHn(){if(v9e)return pte;v9e=1;var e=LB(),t=e.longestPath,n=ZSt(),r=LHn();pte=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 pte}var hte,y9e;function FHn(){if(y9e)return hte;y9e=1,hte=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 hte}var mte,b9e;function BHn(){if(b9e)return mte;b9e=1;let e=Ll();mte={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"),g=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(g,p),y.borderBottom=g,h.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),S=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,C=x.borderTop?u:2*u,_=S!==k?1:d-f[p]+1;i.setEdge(m,S,{weight:C,minlen:_,nestingEdge:!0}),i.setEdge(k,g,{weight:C,minlen:_,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 mte}var gte,x9e;function UHn(){if(x9e)return gte;x9e=1;let e=Ll();gte=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 gte}var vte,w9e;function qHn(){if(w9e)return vte;w9e=1,vte={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 vte}var yte,S9e;function VHn(){if(S9e)return yte;S9e=1;let e=Ll();yte=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 yte}var bte,k9e;function HHn(){if(k9e)return bte;k9e=1;let e=Ll().zipObject;bte=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 bte}var xte,O9e;function WHn(){if(O9e)return xte;O9e=1,xte=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 xte}var wte,_9e;function ZHn(){if(_9e)return wte;_9e=1;let e=Ll();wte=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 wte}var Ste,C9e;function GHn(){if(C9e)return Ste;C9e=1;let e=Ll();Ste=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,g)=>g.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 Ste}var kte,E9e;function QHn(){if(E9e)return kte;E9e=1;let e=WHn(),t=ZHn(),n=GHn();kte=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(x=>x!==p&&x!==h));let g=e(i,d);g.forEach(x=>{if(i.children(x.v).length){let S=r(i,x.v,c,u);m[x.v]=S,Object.hasOwn(S,"barycenter")&&a(x,S)}});let y=t(g,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let x=i.node(i.predecessors(p)[0]),S=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+S.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 kte}var Ote,T9e;function YHn(){if(T9e)return Ote;T9e=1;let e=Bg().Graph,t=Ll();Ote=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,g=u.edge(m,d),y=g!==void 0?g.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 Ote}var _te,j9e;function KHn(){if(j9e)return _te;j9e=1,_te=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 _te}var Cte,N9e;function XHn(){if(N9e)return Cte;N9e=1;let e=VHn(),t=HHn(),n=QHn(),r=YHn(),s=KHn(),a=Bg().Graph,i=Ll();Cte=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"),g=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,x;for(let S=0,k=0;k<4;++S,++k){u(S%2?m:g,S%4>=2),y=i.buildLayerMatrix(f);let C=t(f,y);C<b&&(k=0,x=Object.assign({},y),b=C)}d(f,x)}function c(f,p,h){const m=new Map,g=(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"&&g(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&g(x,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 g=m.graph().root,y=n(m,g,h,p);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,g)=>f.node(m).order=g))}return Cte}var Ete,I9e;function JHn(){if(I9e)return Ete;I9e=1;let e=Bg().Graph,t=Ll();Ete={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 x={};function S(k,C){let _=0,E=0,T=k.length,N=C[C.length-1];return C.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:T;(R||I===N)&&(C.slice(E,A+1).forEach(D=>{y.predecessors(D).forEach(z=>{let H=y.node(z),F=H.order;(F<_||L<F)&&!(H.dummy&&y.node(D).dummy)&&a(x,z,D)})}),E=A+1,_=L)}),C}return b.length&&b.reduce(S),x}function r(y,b){let x={};function S(C,_,E,T,N){let I;t.range(_,E).forEach(A=>{I=C[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<T||L.order>N)&&a(x,R,I)})})}function k(C,_){let E=-1,T,N=0;return _.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(T=y.node(R[0]).order,S(_,N,A,E,T),N=A,E=T)}S(_,N,_.length,T,C.length)}),_}return b.length&&b.reduce(k),x}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(x=>y.node(x).dummy)}function a(y,b,x){if(b>x){let k=b;b=x,x=k}let S=y[b];S||(y[b]=S={}),S[x]=!0}function i(y,b,x){if(b>x){let S=b;b=x,x=S}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,S){let k={},C={},_={};return b.forEach(E=>{E.forEach((T,N)=>{k[T]=T,C[T]=T,_[T]=N})}),b.forEach(E=>{let T=-1;E.forEach(N=>{let I=S(N);if(I.length){I=I.sort((R,L)=>_[R]-_[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let D=I[R];C[N]===N&&T<_[D]&&!i(x,N,D)&&(C[D]=N,C[N]=k[N]=k[D],T=_[D])}}})}),{root:k,align:C}}function c(y,b,x,S,k){let C={},_=u(y,b,x,k),E=k?"borderLeft":"borderRight";function T(A,R){let L=_.nodes(),D=L.pop(),z={};for(;D;)z[D]?A(D):(z[D]=!0,L.push(D),L=L.concat(R(D))),D=L.pop()}function N(A){C[A]=_.inEdges(A).reduce((R,L)=>Math.max(R,C[L.v]+_.edge(L)),0)}function I(A){let R=_.outEdges(A).reduce((D,z)=>Math.min(D,C[z.w]-_.edge(z)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==E&&(C[A]=Math.max(C[A],R))}return T(N,_.predecessors.bind(_)),T(I,_.successors.bind(_)),Object.keys(S).forEach(A=>C[A]=C[x[A]]),C}function u(y,b,x,S){let k=new e,C=y.graph(),_=m(C.nodesep,C.edgesep,S);return b.forEach(E=>{let T;E.forEach(N=>{let I=x[N];if(k.setNode(I),T){var A=x[T],R=k.edge(A,I);k.setEdge(A,I,Math.max(_(y,N,T),R||0))}T=N})}),k}function d(y,b){return Object.values(b).reduce((x,S)=>{let k=Number.NEGATIVE_INFINITY,C=Number.POSITIVE_INFINITY;Object.entries(S).forEach(([E,T])=>{let N=g(y,E)/2;k=Math.max(T+N,k),C=Math.min(T-N,C)});const _=k-C;return _<x[0]&&(x=[_,S]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),S=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(C=>{["l","r"].forEach(_=>{let E=C+_,T=y[E];if(T===b)return;let N=Object.values(T),I=S-t.applyWithChunking(Math.min,N);_!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[E]=t.mapValues(T,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(x,S)=>{if(b)return y[b.toLowerCase()][S];{let k=Object.values(y).map(C=>C[S]).sort((C,_)=>C-_);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),S={},k;["u","d"].forEach(_=>{k=_==="u"?b:Object.values(b).reverse(),["l","r"].forEach(E=>{E==="r"&&(k=k.map(A=>Object.values(A).reverse()));let T=(_==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,T),I=c(y,k,N.root,N.align,E==="r");E==="r"&&(I=t.mapValues(I,A=>-A)),S[_+E]=I})});let C=d(y,S);return f(S,C),p(S,y.graph().align)}function m(y,b,x){return(S,k,C)=>{let _=S.node(k),E=S.node(C),T=0,N;if(T+=_.width/2,Object.hasOwn(_,"labelpos"))switch(_.labelpos.toLowerCase()){case"l":N=-_.width/2;break;case"r":N=_.width/2;break}if(N&&(T+=x?N:-N),N=0,T+=(_.dummy?b:y)/2,T+=(E.dummy?b:y)/2,T+=E.width/2,Object.hasOwn(E,"labelpos"))switch(E.labelpos.toLowerCase()){case"l":N=E.width/2;break;case"r":N=-E.width/2;break}return N&&(T+=x?N:-N),N=0,T}}function g(y,b){return y.node(b).width}return Ete}var Tte,A9e;function eWn(){if(A9e)return Tte;A9e=1;let e=Ll(),t=JHn().positionX;Tte=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 Tte}var jte,R9e;function tWn(){if(R9e)return jte;R9e=1;let e=MHn(),t=DHn(),n=zHn(),r=Ll().normalizeRanks,s=FHn(),a=Ll().removeEmptyRanks,i=BHn(),l=UHn(),c=qHn(),u=XHn(),d=eWn(),f=Ll(),p=Bg().Graph;jte=h;function h($,B){let Z=B&&B.debugTiming?f.time:f.notime;Z("layout",()=>{let K=Z(" buildLayoutGraph",()=>T($));Z(" runLayout",()=>m(K,Z,B)),Z(" updateInputGraph",()=>g($,K))})}function m($,B,Z){B(" makeSpaceForEdgeLabels",()=>N($)),B(" removeSelfEdges",()=>U($)),B(" acyclic",()=>e.run($)),B(" nestingGraph.run",()=>i.run($)),B(" rank",()=>n(f.asNonCompoundGraph($))),B(" injectEdgeLabelProxies",()=>I($)),B(" removeEmptyRanks",()=>a($)),B(" nestingGraph.cleanup",()=>i.cleanup($)),B(" normalizeRanks",()=>r($)),B(" assignRankMinMax",()=>A($)),B(" removeEdgeLabelProxies",()=>R($)),B(" normalize.run",()=>t.run($)),B(" parentDummyChains",()=>s($)),B(" addBorderSegments",()=>l($)),B(" order",()=>u($,Z)),B(" insertSelfEdges",()=>q($)),B(" adjustCoordinateSystem",()=>c.adjust($)),B(" position",()=>d($)),B(" positionSelfEdges",()=>M($)),B(" removeBorderNodes",()=>F($)),B(" normalize.undo",()=>t.undo($)),B(" fixupEdgeLabelCoords",()=>z($)),B(" undoCoordinateSystem",()=>c.undo($)),B(" translateGraph",()=>L($)),B(" assignNodeIntersects",()=>D($)),B(" reversePoints",()=>H($)),B(" acyclic.undo",()=>e.undo($))}function g($,B){$.nodes().forEach(Z=>{let K=$.node(Z),ne=B.node(Z);K&&(K.x=ne.x,K.y=ne.y,K.rank=ne.rank,B.children(Z).length&&(K.width=ne.width,K.height=ne.height))}),$.edges().forEach(Z=>{let K=$.edge(Z),ne=B.edge(Z);K.points=ne.points,Object.hasOwn(ne,"x")&&(K.x=ne.x,K.y=ne.y)}),$.graph().width=B.graph().width,$.graph().height=B.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},x=["acyclicer","ranker","rankdir","align"],S=["width","height","rank"],k={width:0,height:0},C=["minlen","weight","width","height","labeloffset"],_={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},E=["labelpos"];function T($){let B=new p({multigraph:!0,compound:!0}),Z=V($.graph());return B.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),$.nodes().forEach(K=>{let ne=V($.node(K));const ee=G(ne,S);Object.keys(k).forEach(J=>{ee[J]===void 0&&(ee[J]=k[J])}),B.setNode(K,ee),B.setParent(K,$.parent(K))}),$.edges().forEach(K=>{let ne=V($.edge(K));B.setEdge(K,Object.assign({},_,G(ne,C),f.pick(ne,E)))}),B}function N($){let B=$.graph();B.ranksep/=2,$.edges().forEach(Z=>{let K=$.edge(Z);K.minlen*=2,K.labelpos.toLowerCase()!=="c"&&(B.rankdir==="TB"||B.rankdir==="BT"?K.width+=K.labeloffset:K.height+=K.labeloffset)})}function I($){$.edges().forEach(B=>{let Z=$.edge(B);if(Z.width&&Z.height){let K=$.node(B.v),ee={rank:($.node(B.w).rank-K.rank)/2+K.rank,e:B};f.addDummyNode($,"edge-proxy",ee,"_ep")}})}function A($){let B=0;$.nodes().forEach(Z=>{let K=$.node(Z);K.borderTop&&(K.minRank=$.node(K.borderTop).rank,K.maxRank=$.node(K.borderBottom).rank,B=Math.max(B,K.maxRank))}),$.graph().maxRank=B}function R($){$.nodes().forEach(B=>{let Z=$.node(B);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(B))})}function L($){let B=Number.POSITIVE_INFINITY,Z=0,K=Number.POSITIVE_INFINITY,ne=0,ee=$.graph(),J=ee.marginx||0,ae=ee.marginy||0;function fe(Y){let re=Y.x,le=Y.y,ue=Y.width,oe=Y.height;B=Math.min(B,re-ue/2),Z=Math.max(Z,re+ue/2),K=Math.min(K,le-oe/2),ne=Math.max(ne,le+oe/2)}$.nodes().forEach(Y=>fe($.node(Y))),$.edges().forEach(Y=>{let re=$.edge(Y);Object.hasOwn(re,"x")&&fe(re)}),B-=J,K-=ae,$.nodes().forEach(Y=>{let re=$.node(Y);re.x-=B,re.y-=K}),$.edges().forEach(Y=>{let re=$.edge(Y);re.points.forEach(le=>{le.x-=B,le.y-=K}),Object.hasOwn(re,"x")&&(re.x-=B),Object.hasOwn(re,"y")&&(re.y-=K)}),ee.width=Z-B+J,ee.height=ne-K+ae}function D($){$.edges().forEach(B=>{let Z=$.edge(B),K=$.node(B.v),ne=$.node(B.w),ee,J;Z.points?(ee=Z.points[0],J=Z.points[Z.points.length-1]):(Z.points=[],ee=ne,J=K),Z.points.unshift(f.intersectRect(K,ee)),Z.points.push(f.intersectRect(ne,J))})}function z($){$.edges().forEach(B=>{let Z=$.edge(B);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(B=>{let Z=$.edge(B);Z.reversed&&Z.points.reverse()})}function F($){$.nodes().forEach(B=>{if($.children(B).length){let Z=$.node(B),K=$.node(Z.borderTop),ne=$.node(Z.borderBottom),ee=$.node(Z.borderLeft[Z.borderLeft.length-1]),J=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(J.x-ee.x),Z.height=Math.abs(ne.y-K.y),Z.x=ee.x+Z.width/2,Z.y=K.y+Z.height/2}}),$.nodes().forEach(B=>{$.node(B).dummy==="border"&&$.removeNode(B)})}function U($){$.edges().forEach(B=>{if(B.v===B.w){var Z=$.node(B.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:B,label:$.edge(B)}),$.removeEdge(B)}})}function q($){var B=f.buildLayerMatrix($);B.forEach(Z=>{var K=0;Z.forEach((ne,ee)=>{var J=$.node(ne);J.order=ee+K,(J.selfEdges||[]).forEach(ae=>{f.addDummyNode($,"selfedge",{width:ae.label.width,height:ae.label.height,rank:J.rank,order:ee+ ++K,e:ae.e,label:ae.label},"_se")}),delete J.selfEdges})})}function M($){$.nodes().forEach(B=>{var Z=$.node(B);if(Z.dummy==="selfedge"){var K=$.node(Z.e.v),ne=K.x+K.width/2,ee=K.y,J=Z.x-ne,ae=K.height/2;$.setEdge(Z.e,Z.label),$.removeNode(B),Z.label.points=[{x:ne+2*J/3,y:ee-ae},{x:ne+5*J/6,y:ee-ae},{x:ne+J,y:ee},{x:ne+5*J/6,y:ee+ae},{x:ne+2*J/3,y:ee+ae}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,B){return f.mapValues(f.pick($,B),Number)}function V($){var B={};return $&&Object.entries($).forEach(([Z,K])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),B[Z]=K}),B}return jte}var Nte,P9e;function nWn(){if(P9e)return Nte;P9e=1;let e=Ll(),t=Bg().Graph;Nte={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 Nte}var Ite,$9e;function rWn(){return $9e||($9e=1,Ite="1.1.8"),Ite}var Ate,M9e;function sWn(){return M9e||(M9e=1,Ate={graphlib:Bg(),layout:tWn(),debug:nWn(),util:{time:Ll().time,notime:Ll().notime},version:rWn()}),Ate}var aWn=sWn();const D9e=Ul(aWn);function Hl(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=Hl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var iWn={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 V8(n)}function V8(e){this._=e}function oWn(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}})}V8.prototype=GH.prototype={constructor:V8,on:function(e,t){var n=this._,r=oWn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=lWn(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]=L9e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=L9e(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 V8(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 lWn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function L9e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=iWn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Lge="http://www.w3.org/1999/xhtml";const z9e={svg:"http://www.w3.org/2000/svg",xhtml:Lge,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function QH(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),z9e.hasOwnProperty(t)?{space:z9e[t],local:e}:e}function cWn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Lge&&t.documentElement.namespaceURI===Lge?t.createElement(e):t.createElementNS(n,e)}}function uWn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function GSt(e){var t=QH(e);return(t.local?uWn:cWn)(t)}function dWn(){}function Dke(e){return e==null?dWn:function(){return this.querySelector(e)}}function fWn(e){typeof e!="function"&&(e=Dke(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 Qp(r,this._parents)}function pWn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function hWn(){return[]}function QSt(e){return e==null?hWn:function(){return this.querySelectorAll(e)}}function mWn(e){return function(){return pWn(e.apply(this,arguments))}}function gWn(e){typeof e=="function"?e=mWn(e):e=QSt(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 Qp(r,s)}function YSt(e){return function(){return this.matches(e)}}function KSt(e){return function(t){return t.matches(e)}}var vWn=Array.prototype.find;function yWn(e){return function(){return vWn.call(this.children,e)}}function bWn(){return this.firstElementChild}function xWn(e){return this.select(e==null?bWn:yWn(typeof e=="function"?e:KSt(e)))}var wWn=Array.prototype.filter;function SWn(){return Array.from(this.children)}function kWn(e){return function(){return wWn.call(this.children,e)}}function OWn(e){return this.selectAll(e==null?SWn:kWn(typeof e=="function"?e:KSt(e)))}function _Wn(e){typeof e!="function"&&(e=YSt(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 Qp(r,this._parents)}function XSt(e){return new Array(e.length)}function CWn(){return new Qp(this._enter||this._groups.map(XSt),this._parents)}function zB(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}zB.prototype={constructor:zB,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 EWn(e){return function(){return e}}function TWn(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 zB(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function jWn(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 zB(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function NWn(e){return e.__data__}function IWn(e,t){if(!arguments.length)return Array.from(this,NWn);var n=t?jWn:TWn,r=this._parents,s=this._groups;typeof e!="function"&&(e=EWn(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=AWn(e.call(d,d&&d.__data__,u,r)),m=h.length,g=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,g,y,b,h,t);for(var x=0,S=0,k,C;x<m;++x)if(k=g[x]){for(x>=S&&(S=x+1);!(C=y[S])&&++S<m;);k._next=C||null}}return i=new Qp(i,r),i._enter=l,i._exit=c,i}function AWn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function RWn(){return new Qp(this._exit||this._groups.map(XSt),this._parents)}function PWn(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 $Wn(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 Qp(l,this._parents)}function MWn(){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 DWn(e){e||(e=LWn);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 Qp(s,this._parents).order()}function LWn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function zWn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function FWn(){return Array.from(this)}function BWn(){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 UWn(){let e=0;for(const t of this)++e;return e}function qWn(){return!this.node()}function VWn(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 HWn(e){return function(){this.removeAttribute(e)}}function WWn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function ZWn(e,t){return function(){this.setAttribute(e,t)}}function GWn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function QWn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function YWn(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 KWn(e,t){var n=QH(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?WWn:HWn:typeof t=="function"?n.local?YWn:QWn:n.local?GWn:ZWn)(n,t))}function JSt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function XWn(e){return function(){this.style.removeProperty(e)}}function JWn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function eZn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function tZn(e,t,n){return arguments.length>1?this.each((t==null?XWn:typeof t=="function"?eZn:JWn)(e,t,n??"")):Yj(this.node(),e)}function Yj(e,t){return e.style.getPropertyValue(t)||JSt(e).getComputedStyle(e,null).getPropertyValue(t)}function nZn(e){return function(){delete this[e]}}function rZn(e,t){return function(){this[e]=t}}function sZn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function aZn(e,t){return arguments.length>1?this.each((t==null?nZn:typeof t=="function"?sZn:rZn)(e,t)):this.node()[e]}function ekt(e){return e.trim().split(/^|\s+/)}function Lke(e){return e.classList||new tkt(e)}function tkt(e){this._node=e,this._names=ekt(e.getAttribute("class")||"")}tkt.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 nkt(e,t){for(var n=Lke(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function rkt(e,t){for(var n=Lke(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function iZn(e){return function(){nkt(this,e)}}function oZn(e){return function(){rkt(this,e)}}function lZn(e,t){return function(){(t.apply(this,arguments)?nkt:rkt)(this,e)}}function cZn(e,t){var n=ekt(e+"");if(arguments.length<2){for(var r=Lke(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?lZn:t?iZn:oZn)(n,t))}function uZn(){this.textContent=""}function dZn(e){return function(){this.textContent=e}}function fZn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function pZn(e){return arguments.length?this.each(e==null?uZn:(typeof e=="function"?fZn:dZn)(e)):this.node().textContent}function hZn(){this.innerHTML=""}function mZn(e){return function(){this.innerHTML=e}}function gZn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function vZn(e){return arguments.length?this.each(e==null?hZn:(typeof e=="function"?gZn:mZn)(e)):this.node().innerHTML}function yZn(){this.nextSibling&&this.parentNode.appendChild(this)}function bZn(){return this.each(yZn)}function xZn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function wZn(){return this.each(xZn)}function SZn(e){var t=typeof e=="function"?e:GSt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function kZn(){return null}function OZn(e,t){var n=typeof e=="function"?e:GSt(e),r=t==null?kZn:typeof t=="function"?t:Dke(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function _Zn(){var e=this.parentNode;e&&e.removeChild(this)}function CZn(){return this.each(_Zn)}function EZn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function TZn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function jZn(e){return this.select(e?TZn:EZn)}function NZn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function IZn(e){return function(t){e.call(this,t,this.__data__)}}function AZn(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 RZn(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 PZn(e,t,n){return function(){var r=this.__on,s,a=IZn(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 $Zn(e,t,n){var r=AZn(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?PZn:RZn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function skt(e,t,n){var r=JSt(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 MZn(e,t){return function(){return skt(this,e,t)}}function DZn(e,t){return function(){return skt(this,e,t.apply(this,arguments))}}function LZn(e,t){return this.each((typeof t=="function"?DZn:MZn)(e,t))}function*zZn(){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 akt=[null];function Qp(e,t){this._groups=e,this._parents=t}function Z3(){return new Qp([[document.documentElement]],akt)}function FZn(){return this}Qp.prototype=Z3.prototype={constructor:Qp,select:fWn,selectAll:gWn,selectChild:xWn,selectChildren:OWn,filter:_Wn,data:IWn,enter:CWn,exit:RWn,join:PWn,merge:$Wn,selection:FZn,order:MWn,sort:DWn,call:zWn,nodes:FWn,node:BWn,size:UWn,empty:qWn,each:VWn,attr:KWn,style:tZn,property:aZn,classed:cZn,text:pZn,html:vZn,raise:bZn,lower:wZn,append:SZn,insert:OZn,remove:CZn,clone:jZn,datum:NZn,on:$Zn,dispatch:LZn,[Symbol.iterator]:zZn};function Cp(e){return typeof e=="string"?new Qp([[document.querySelector(e)]],[document.documentElement]):new Qp([[e]],akt)}function BZn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function lg(e,t){if(e=BZn(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 UZn={passive:!1},$M={capture:!0,passive:!1};function Rte(e){e.stopImmediatePropagation()}function XT(e){e.preventDefault(),e.stopImmediatePropagation()}function ikt(e){var t=e.document.documentElement,n=Cp(e).on("dragstart.drag",XT,$M);"onselectstart"in t?n.on("selectstart.drag",XT,$M):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function okt(e,t){var n=e.document.documentElement,r=Cp(e).on("dragstart.drag",null);t&&(r.on("click.drag",XT,$M),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 uz=e=>()=>e;function zge(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}})}zge.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function qZn(e){return!e.ctrlKey&&!e.button}function VZn(){return this.parentNode}function HZn(e,t){return t??{x:e.x,y:e.y}}function WZn(){return navigator.maxTouchPoints||"ontouchstart"in this}function lkt(){var e=qZn,t=VZn,n=HZn,r=WZn,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,UZn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,C){if(!(d||!e.call(this,k,C))){var _=S(this,t.call(this,k,C),k,C,"mouse");_&&(Cp(k.view).on("mousemove.drag",m,$M).on("mouseup.drag",g,$M),ikt(k.view),Rte(k),u=!1,l=k.clientX,c=k.clientY,_("start",k))}}function m(k){if(XT(k),!u){var C=k.clientX-l,_=k.clientY-c;u=C*C+_*_>f}s.mouse("drag",k)}function g(k){Cp(k.view).on("mousemove.drag mouseup.drag",null),okt(k.view,u),XT(k),s.mouse("end",k)}function y(k,C){if(e.call(this,k,C)){var _=k.changedTouches,E=t.call(this,k,C),T=_.length,N,I;for(N=0;N<T;++N)(I=S(this,E,k,C,_[N].identifier,_[N]))&&(Rte(k),I("start",k,_[N]))}}function b(k){var C=k.changedTouches,_=C.length,E,T;for(E=0;E<_;++E)(T=s[C[E].identifier])&&(XT(k),T("drag",k,C[E]))}function x(k){var C=k.changedTouches,_=C.length,E,T;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),E=0;E<_;++E)(T=s[C[E].identifier])&&(Rte(k),T("end",k,C[E]))}function S(k,C,_,E,T,N){var I=a.copy(),A=lg(N||_,C),R,L,D;if((D=n.call(k,new zge("beforestart",{sourceEvent:_,target:p,identifier:T,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),E))!=null)return R=D.x-A[0]||0,L=D.y-A[1]||0,function z(H,F,U){var q=A,M;switch(H){case"start":s[T]=z,M=i++;break;case"end":delete s[T],--i;case"drag":A=lg(U||F,C),M=i;break}I.call(H,k,new zge(H,{sourceEvent:F,subject:D,target:p,identifier:T,active:M,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:uz(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:uz(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:uz(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:uz(!!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 zke(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function ckt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function G3(){}var MM=.7,FB=1/MM,JT="\\s*([+-]?\\d+)\\s*",DM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",oy="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",ZZn=/^#([0-9a-f]{3,8})$/,GZn=new RegExp(`^rgb\\(${JT},${JT},${JT}\\)$`),QZn=new RegExp(`^rgb\\(${oy},${oy},${oy}\\)$`),YZn=new RegExp(`^rgba\\(${JT},${JT},${JT},${DM}\\)$`),KZn=new RegExp(`^rgba\\(${oy},${oy},${oy},${DM}\\)$`),XZn=new RegExp(`^hsl\\(${DM},${oy},${oy}\\)$`),JZn=new RegExp(`^hsla\\(${DM},${oy},${oy},${DM}\\)$`),F9e={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};zke(G3,YO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:B9e,formatHex:B9e,formatHex8:eGn,formatHsl:tGn,formatRgb:U9e,toString:U9e});function B9e(){return this.rgb().formatHex()}function eGn(){return this.rgb().formatHex8()}function tGn(){return ukt(this).formatHsl()}function U9e(){return this.rgb().formatRgb()}function YO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=ZZn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?q9e(t):n===3?new bf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?dz(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?dz(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=GZn.exec(e))?new bf(t[1],t[2],t[3],1):(t=QZn.exec(e))?new bf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=YZn.exec(e))?dz(t[1],t[2],t[3],t[4]):(t=KZn.exec(e))?dz(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=XZn.exec(e))?W9e(t[1],t[2]/100,t[3]/100,1):(t=JZn.exec(e))?W9e(t[1],t[2]/100,t[3]/100,t[4]):F9e.hasOwnProperty(e)?q9e(F9e[e]):e==="transparent"?new bf(NaN,NaN,NaN,0):null}function q9e(e){return new bf(e>>16&255,e>>8&255,e&255,1)}function dz(e,t,n,r){return r<=0&&(e=t=n=NaN),new bf(e,t,n,r)}function nGn(e){return e instanceof G3||(e=YO(e)),e?(e=e.rgb(),new bf(e.r,e.g,e.b,e.opacity)):new bf}function Fge(e,t,n,r){return arguments.length===1?nGn(e):new bf(e,t,n,r??1)}function bf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}zke(bf,Fge,ckt(G3,{brighter(e){return e=e==null?FB:Math.pow(FB,e),new bf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?MM:Math.pow(MM,e),new bf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new bf(aO(this.r),aO(this.g),aO(this.b),BB(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:V9e,formatHex:V9e,formatHex8:rGn,formatRgb:H9e,toString:H9e}));function V9e(){return`#${Bk(this.r)}${Bk(this.g)}${Bk(this.b)}`}function rGn(){return`#${Bk(this.r)}${Bk(this.g)}${Bk(this.b)}${Bk((isNaN(this.opacity)?1:this.opacity)*255)}`}function H9e(){const e=BB(this.opacity);return`${e===1?"rgb(":"rgba("}${aO(this.r)}, ${aO(this.g)}, ${aO(this.b)}${e===1?")":`, ${e})`}`}function BB(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function aO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Bk(e){return e=aO(e),(e<16?"0":"")+e.toString(16)}function W9e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new mg(e,t,n,r)}function ukt(e){if(e instanceof mg)return new mg(e.h,e.s,e.l,e.opacity);if(e instanceof G3||(e=YO(e)),!e)return new mg;if(e instanceof mg)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 mg(i,l,c,e.opacity)}function sGn(e,t,n,r){return arguments.length===1?ukt(e):new mg(e,t,n,r??1)}function mg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}zke(mg,sGn,ckt(G3,{brighter(e){return e=e==null?FB:Math.pow(FB,e),new mg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?MM:Math.pow(MM,e),new mg(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 bf(Pte(e>=240?e-240:e+120,s,r),Pte(e,s,r),Pte(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new mg(Z9e(this.h),fz(this.s),fz(this.l),BB(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=BB(this.opacity);return`${e===1?"hsl(":"hsla("}${Z9e(this.h)}, ${fz(this.s)*100}%, ${fz(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Z9e(e){return e=(e||0)%360,e<0?e+360:e}function fz(e){return Math.max(0,Math.min(1,e||0))}function Pte(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 Fke=e=>()=>e;function aGn(e,t){return function(n){return e+n*t}}function iGn(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 oGn(e){return(e=+e)==1?dkt:function(t,n){return n-t?iGn(t,n,e):Fke(isNaN(t)?n:t)}}function dkt(e,t){var n=t-e;return n?aGn(e,n):Fke(isNaN(e)?t:e)}const UB=(function e(t){var n=oGn(t);function r(s,a){var i=n((s=Fge(s)).r,(a=Fge(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=dkt(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 lGn(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 cGn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function uGn(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]=yx(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 dGn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function ug(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function fGn(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]=yx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Bge=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,$te=new RegExp(Bge.source,"g");function pGn(e){return function(){return e}}function hGn(e){return function(t){return e(t)+""}}function fkt(e,t){var n=Bge.lastIndex=$te.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Bge.exec(e))&&(s=$te.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:ug(r,s)})),n=$te.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?hGn(c[0].x):pGn(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 yx(e,t){var n=typeof t,r;return t==null||n==="boolean"?Fke(t):(n==="number"?ug:n==="string"?(r=YO(t))?(t=r,UB):fkt:t instanceof YO?UB:t instanceof Date?dGn:cGn(t)?lGn:Array.isArray(t)?uGn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?fGn:ug)(e,t)}function Bke(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var G9e=180/Math.PI,Uge={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function pkt(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)*G9e,skewX:Math.atan(c)*G9e,scaleX:i,scaleY:l}}var pz;function mGn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Uge:pkt(t.a,t.b,t.c,t.d,t.e,t.f)}function gGn(e){return e==null||(pz||(pz=document.createElementNS("http://www.w3.org/2000/svg","g")),pz.setAttribute("transform",e),!(e=pz.transform.baseVal.consolidate()))?Uge:(e=e.matrix,pkt(e.a,e.b,e.c,e.d,e.e,e.f))}function hkt(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 g=h.push("translate(",null,t,null,n);m.push({i:g-4,x:ug(u,f)},{i:g-2,x:ug(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:ug(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:ug(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var g=h.push(s(h)+"scale(",null,",",null,")");m.push({i:g-4,x:ug(u,f)},{i:g-2,x:ug(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,g=p.length,y;++m<g;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var vGn=hkt(mGn,"px, ","px)","deg)"),yGn=hkt(gGn,", ",")",")"),bGn=1e-12;function Q9e(e){return((e=Math.exp(e))+1/e)/2}function xGn(e){return((e=Math.exp(e))-1/e)/2}function wGn(e){return((e=Math.exp(2*e))-1)/(e+1)}const H8=(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,g=h*h+m*m,y,b;if(g<bGn)b=Math.log(p/u)/t,y=function(E){return[l+E*h,c+E*m,u*Math.exp(t*E*b)]};else{var x=Math.sqrt(g),S=(p*p-u*u+r*g)/(2*u*n*x),k=(p*p-u*u-r*g)/(2*p*n*x),C=Math.log(Math.sqrt(S*S+1)-S),_=Math.log(Math.sqrt(k*k+1)-k);b=(_-C)/t,y=function(E){var T=E*b,N=Q9e(C),I=u/(n*x)*(N*wGn(t*T+C)-xGn(C));return[l+I*h,c+I*m,u*N/Q9e(t*T+C)]}}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 SGn(e,t){t===void 0&&(t=e,e=yx);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 Kj=0,VP=0,jR=0,mkt=1e3,qB,HP,VB=0,KO=0,YH=0,LM=typeof performance=="object"&&performance.now?performance:Date,gkt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Uke(){return KO||(gkt(kGn),KO=LM.now()+YH)}function kGn(){KO=0}function HB(){this._call=this._time=this._next=null}HB.prototype=vkt.prototype={constructor:HB,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Uke():+n)+(t==null?0:+t),!this._next&&HP!==this&&(HP?HP._next=this:qB=this,HP=this),this._call=e,this._time=n,qge()},stop:function(){this._call&&(this._call=null,this._time=1/0,qge())}};function vkt(e,t,n){var r=new HB;return r.restart(e,t,n),r}function OGn(){Uke(),++Kj;for(var e=qB,t;e;)(t=KO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Kj}function Y9e(){KO=(VB=LM.now())+YH,Kj=VP=0;try{OGn()}finally{Kj=0,CGn(),KO=0}}function _Gn(){var e=LM.now(),t=e-VB;t>mkt&&(YH-=t,VB=e)}function CGn(){for(var e,t=qB,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:qB=n);HP=e,qge(r)}function qge(e){if(!Kj){VP&&(VP=clearTimeout(VP));var t=e-KO;t>24?(e<1/0&&(VP=setTimeout(Y9e,e-LM.now()-YH)),jR&&(jR=clearInterval(jR))):(jR||(VB=LM.now(),jR=setInterval(_Gn,mkt)),Kj=1,gkt(Y9e))}}function K9e(e,t,n){var r=new HB;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var EGn=GH("start","end","cancel","interrupt"),TGn=[],ykt=0,X9e=1,Vge=2,W8=3,J9e=4,Hge=5,Z8=6;function KH(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;jGn(e,n,{name:t,index:r,group:s,on:EGn,tween:TGn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:ykt})}function qke(e,t){var n=Yg(e,t);if(n.state>ykt)throw new Error("too late; already scheduled");return n}function Wy(e,t){var n=Yg(e,t);if(n.state>W8)throw new Error("too late; already running");return n}function Yg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function jGn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=vkt(a,0,n.time);function a(u){n.state=X9e,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!==X9e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===W8)return K9e(i);h.state===J9e?(h.state=Z8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=Z8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(K9e(function(){n.state===W8&&(n.state=J9e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Vge,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Vge){for(n.state=W8,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=Hge,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===Hge&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=Z8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function G8(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>Vge&&r.state<Hge,r.state=Z8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function NGn(e){return this.each(function(){G8(this,e)})}function IGn(e,t){var n,r;return function(){var s=Wy(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 AGn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Wy(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 RGn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Yg(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?IGn:AGn)(n,e,t))}function Vke(e,t,n){var r=e._id;return e.each(function(){var s=Wy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Yg(s,r).value[t]}}function bkt(e,t){var n;return(typeof t=="number"?ug:t instanceof YO?UB:(n=YO(t))?(t=n,UB):fkt)(e,t)}function PGn(e){return function(){this.removeAttribute(e)}}function $Gn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function MGn(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 DGn(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 LGn(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 zGn(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 FGn(e,t){var n=QH(e),r=n==="transform"?yGn:bkt;return this.attrTween(e,typeof t=="function"?(n.local?zGn:LGn)(n,r,Vke(this,"attr."+e,t)):t==null?(n.local?$Gn:PGn)(n):(n.local?DGn:MGn)(n,r,t))}function BGn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function UGn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function qGn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&UGn(e,a)),n}return s._value=t,s}function VGn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&BGn(e,a)),n}return s._value=t,s}function HGn(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=QH(e);return this.tween(n,(r.local?qGn:VGn)(r,t))}function WGn(e,t){return function(){qke(this,e).delay=+t.apply(this,arguments)}}function ZGn(e,t){return t=+t,function(){qke(this,e).delay=t}}function GGn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?WGn:ZGn)(t,e)):Yg(this.node(),t).delay}function QGn(e,t){return function(){Wy(this,e).duration=+t.apply(this,arguments)}}function YGn(e,t){return t=+t,function(){Wy(this,e).duration=t}}function KGn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?QGn:YGn)(t,e)):Yg(this.node(),t).duration}function XGn(e,t){if(typeof t!="function")throw new Error;return function(){Wy(this,e).ease=t}}function JGn(e){var t=this._id;return arguments.length?this.each(XGn(t,e)):Yg(this.node(),t).ease}function eQn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Wy(this,e).ease=n}}function tQn(e){if(typeof e!="function")throw new Error;return this.each(eQn(this._id,e))}function nQn(e){typeof e!="function"&&(e=YSt(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 zx(r,this._parents,this._name,this._id)}function rQn(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 zx(i,this._parents,this._name,this._id)}function sQn(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 aQn(e,t,n){var r,s,a=sQn(t)?qke:Wy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function iQn(e,t){var n=this._id;return arguments.length<2?Yg(this.node(),n).on.on(e):this.each(aQn(n,e,t))}function oQn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function lQn(){return this.on("end.remove",oQn(this._id))}function cQn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Dke(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,KH(u[p],t,n,p,u,Yg(d,n)));return new zx(a,this._parents,t,n)}function uQn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=QSt(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=Yg(d,n),g=0,y=p.length;g<y;++g)(h=p[g])&&KH(h,t,n,g,p,m);a.push(p),i.push(d)}return new zx(a,i,t,n)}var dQn=Z3.prototype.constructor;function fQn(){return new dQn(this._groups,this._parents)}function pQn(e,t){var n,r,s;return function(){var a=Yj(this,e),i=(this.style.removeProperty(e),Yj(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function xkt(e){return function(){this.style.removeProperty(e)}}function hQn(e,t,n){var r,s=n+"",a;return function(){var i=Yj(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function mQn(e,t,n){var r,s,a;return function(){var i=Yj(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),Yj(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function gQn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Wy(this,e),u=c.on,d=c.value[a]==null?l||(l=xkt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function vQn(e,t,n){var r=(e+="")=="transform"?vGn:bkt;return t==null?this.styleTween(e,pQn(e,r)).on("end.style."+e,xkt(e)):typeof t=="function"?this.styleTween(e,mQn(e,r,Vke(this,"style."+e,t))).each(gQn(this._id,e)):this.styleTween(e,hQn(e,r,t),n).on("end.style."+e,null)}function yQn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function bQn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&yQn(e,i,n)),r}return a._value=t,a}function xQn(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,bQn(e,t,n??""))}function wQn(e){return function(){this.textContent=e}}function SQn(e){return function(){var t=e(this);this.textContent=t??""}}function kQn(e){return this.tween("text",typeof e=="function"?SQn(Vke(this,"text",e)):wQn(e==null?"":e+""))}function OQn(e){return function(t){this.textContent=e.call(this,t)}}function _Qn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&OQn(s)),t}return r._value=e,r}function CQn(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,_Qn(e))}function EQn(){for(var e=this._name,t=this._id,n=wkt(),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=Yg(c,t);KH(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new zx(r,this._parents,e,n)}function TQn(){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=Wy(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 jQn=0;function zx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function wkt(){return++jQn}var _b=Z3.prototype;zx.prototype={constructor:zx,select:cQn,selectAll:uQn,selectChild:_b.selectChild,selectChildren:_b.selectChildren,filter:nQn,merge:rQn,selection:fQn,transition:EQn,call:_b.call,nodes:_b.nodes,node:_b.node,size:_b.size,empty:_b.empty,each:_b.each,on:iQn,attr:FGn,attrTween:HGn,style:vQn,styleTween:xQn,text:kQn,textTween:CQn,remove:lQn,tween:RGn,delay:GGn,duration:KGn,ease:JGn,easeVarying:tQn,end:TQn,[Symbol.iterator]:_b[Symbol.iterator]};function NQn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var IQn={time:null,delay:0,duration:250,ease:NQn};function AQn(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 RQn(e){var t,n;e instanceof zx?(t=e._id,e=e._name):(t=wkt(),(n=IQn).time=Uke(),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])&&KH(c,e,t,u,i,n||AQn(c,t));return new zx(r,this._parents,e,t)}Z3.prototype.interrupt=NGn;Z3.prototype.transition=RQn;const hz=e=>()=>e;function PQn(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 ox(e,t,n){this.k=e,this.x=t,this.y=n}ox.prototype={constructor:ox,scale:function(e){return e===1?this:new ox(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new ox(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 ox(1,0,0);Skt.prototype=ox.prototype;function Skt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return XH;return e.__zoom}function Mte(e){e.stopImmediatePropagation()}function NR(e){e.preventDefault(),e.stopImmediatePropagation()}function $Qn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function MQn(){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 e7e(){return this.__zoom||XH}function DQn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function LQn(){return navigator.maxTouchPoints||"ontouchstart"in this}function zQn(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 kkt(){var e=$Qn,t=MQn,n=zQn,r=DQn,s=LQn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=H8,u=GH("start","zoom","end"),d,f,p,h=500,m=150,g=0,y=10;function b(D){D.property("__zoom",e7e).on("wheel.zoom",T,{passive:!1}).on("mousedown.zoom",N).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(D,z,H,F){var U=D.selection?D.selection():D;U.property("__zoom",e7e),D!==U?C(D,z,H,F):U.interrupt().each(function(){_(this,arguments).event(F).start().zoom(null,typeof z=="function"?z.apply(this,arguments):z).end()})},b.scaleBy=function(D,z,H,F){b.scaleTo(D,function(){var U=this.__zoom.k,q=typeof z=="function"?z.apply(this,arguments):z;return U*q},H,F)},b.scaleTo=function(D,z,H,F){b.transform(D,function(){var U=t.apply(this,arguments),q=this.__zoom,M=H==null?k(U):typeof H=="function"?H.apply(this,arguments):H,G=q.invert(M),V=typeof z=="function"?z.apply(this,arguments):z;return n(S(x(q,V),M,G),U,i)},H,F)},b.translateBy=function(D,z,H,F){b.transform(D,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(D,z,H,F,U){b.transform(D,function(){var q=t.apply(this,arguments),M=this.__zoom,G=F==null?k(q):typeof F=="function"?F.apply(this,arguments):F;return n(XH.translate(G[0],G[1]).scale(M.k).translate(typeof z=="function"?-z.apply(this,arguments):-z,typeof H=="function"?-H.apply(this,arguments):-H),q,i)},F,U)};function x(D,z){return z=Math.max(a[0],Math.min(a[1],z)),z===D.k?D:new ox(z,D.x,D.y)}function S(D,z,H){var F=z[0]-H[0]*D.k,U=z[1]-H[1]*D.k;return F===D.x&&U===D.y?D:new ox(D.k,F,U)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function C(D,z,H,F){D.on("start.zoom",function(){_(this,arguments).event(F).start()}).on("interrupt.zoom end.zoom",function(){_(this,arguments).event(F).end()}).tween("zoom",function(){var U=this,q=arguments,M=_(U,q).event(F),G=t.apply(U,q),V=H==null?k(G):typeof H=="function"?H.apply(U,q):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),B=U.__zoom,Z=typeof z=="function"?z.apply(U,q):z,K=c(B.invert(V).concat($/B.k),Z.invert(V).concat($/Z.k));return function(ne){if(ne===1)ne=Z;else{var ee=K(ne),J=$/ee[2];ne=new ox(J,V[0]-ee[0]*J,V[1]-ee[1]*J)}M.zoom(null,ne)}})}function _(D,z,H){return!H&&D.__zooming||new E(D,z)}function E(D,z){this.that=D,this.args=z,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,z),this.taps=0}E.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,z){return this.mouse&&D!=="mouse"&&(this.mouse[1]=z.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=z.invert(this.touch0[0])),this.touch1&&D!=="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(D){var z=Cp(this.that).datum();u.call(D,this.that,new PQn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),z)}};function T(D,...z){if(!e.apply(this,arguments))return;var H=_(this,z).event(D),F=this.__zoom,U=Math.max(a[0],Math.min(a[1],F.k*Math.pow(2,r.apply(this,arguments)))),q=lg(D);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===U)return;H.mouse=[q,F.invert(q)],G8(this),H.start()}NR(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(S(x(F,U),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...z){if(p||!e.apply(this,arguments))return;var H=D.currentTarget,F=_(this,z,!0).event(D),U=Cp(D.view).on("mousemove.zoom",V,!0).on("mouseup.zoom",$,!0),q=lg(D,H),M=D.clientX,G=D.clientY;ikt(D.view),Mte(D),F.mouse=[q,this.__zoom.invert(q)],G8(this),F.start();function V(B){if(NR(B),!F.moved){var Z=B.clientX-M,K=B.clientY-G;F.moved=Z*Z+K*K>g}F.event(B).zoom("mouse",n(S(F.that.__zoom,F.mouse[0]=lg(B,H),F.mouse[1]),F.extent,i))}function $(B){U.on("mousemove.zoom mouseup.zoom",null),okt(B.view,F.moved),NR(B),F.event(B).end()}}function I(D,...z){if(e.apply(this,arguments)){var H=this.__zoom,F=lg(D.changedTouches?D.changedTouches[0]:D,this),U=H.invert(F),q=H.k*(D.shiftKey?.5:2),M=n(S(x(H,q),F,U),t.apply(this,z),i);NR(D),l>0?Cp(this).transition().duration(l).call(C,M,F,D):Cp(this).call(b.transform,M,F,D)}}function A(D,...z){if(e.apply(this,arguments)){var H=D.touches,F=H.length,U=_(this,z,D.changedTouches.length===F).event(D),q,M,G,V;for(Mte(D),M=0;M<F;++M)G=H[M],V=lg(G,this),V=[V,this.__zoom.invert(V),G.identifier],U.touch0?!U.touch1&&U.touch0[2]!==V[2]&&(U.touch1=V,U.taps=0):(U.touch0=V,q=!0,U.taps=1+!!d);d&&(d=clearTimeout(d)),q&&(U.taps<2&&(f=V[0],d=setTimeout(function(){d=null},h)),G8(this),U.start())}}function R(D,...z){if(this.__zooming){var H=_(this,z).event(D),F=D.changedTouches,U=F.length,q,M,G,V;for(NR(D),q=0;q<U;++q)M=F[q],G=lg(M,this),H.touch0&&H.touch0[2]===M.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===M.identifier&&(H.touch1[0]=G);if(M=H.that.__zoom,H.touch1){var $=H.touch0[0],B=H.touch0[1],Z=H.touch1[0],K=H.touch1[1],ne=(ne=Z[0]-$[0])*ne+(ne=Z[1]-$[1])*ne,ee=(ee=K[0]-B[0])*ee+(ee=K[1]-B[1])*ee;M=x(M,Math.sqrt(ne/ee)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],V=[(B[0]+K[0])/2,(B[1]+K[1])/2]}else if(H.touch0)G=H.touch0[0],V=H.touch0[1];else return;H.zoom("touch",n(S(M,G,V),H.extent,i))}}function L(D,...z){if(this.__zooming){var H=_(this,z).event(D),F=D.changedTouches,U=F.length,q,M;for(Mte(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),q=0;q<U;++q)M=F[q],H.touch0&&H.touch0[2]===M.identifier?delete H.touch0:H.touch1&&H.touch1[2]===M.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&&(M=lg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=Cp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:hz(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:hz(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:hz(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:hz([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(g=(D=+D)*D,b):Math.sqrt(g)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const _y={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."},zM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Okt=["Enter"," ","Escape"],_kt={"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 Xj;(function(e){e.Strict="strict",e.Loose="loose"})(Xj||(Xj={}));var iO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(iO||(iO={}));var FM;(function(e){e.Partial="partial",e.Full="full"})(FM||(FM={}));const Ckt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var kw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(kw||(kw={}));var BM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(BM||(BM={}));var ar;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(ar||(ar={}));const t7e={[ar.Left]:ar.Right,[ar.Right]:ar.Left,[ar.Top]:ar.Bottom,[ar.Bottom]:ar.Top};function Ekt(e){return e===null?null:e?"valid":"invalid"}const Tkt=e=>"id"in e&&"source"in e&&"target"in e,FQn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),Hke=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),Q3=(e,t=[0,0])=>{const{width:n,height:r}=l0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},BQn=(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):Hke(s)?s:t.nodeLookup.get(s.id));const l=i?WB(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return JH(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return eW(n)},Y3=(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=JH(n,WB(s)),r=!0)}),r?eW(n):{x:0,y:0,width:0,height:0}},Wke=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...X3(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,g=UM(l,eN(u)),y=(h??0)*(m??0),b=a&&g>0;(!u.internals.handleBounds||b||g>=y||u.dragging)&&c.push(u)}return c},UQn=(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 qQn(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 VQn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=qQn(e,i),c=Y3(l),u=Zke(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 jkt({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",_y.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&tN(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=tN(f)?XO(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",_y.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 HQn({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(g=>g.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=UQn(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 Jj=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),XO=(e={x:0,y:0},t,n)=>({x:Jj(e.x,t[0][0],t[1][0]-(n?.width??0)),y:Jj(e.y,t[0][1],t[1][1]-(n?.height??0))});function Nkt(e,t,n){const{width:r,height:s}=l0(n),{x:a,y:i}=n.internals.positionAbsolute;return XO(e,[[a,i],[a+r,i+s]],t)}const n7e=(e,t,n)=>e<t?Jj(Math.abs(e-t),1,t)/t:e>n?-Jj(Math.abs(e-n),1,t)/t:0,Ikt=(e,t,n=15,r=40)=>{const s=n7e(e.x,r,t.width-r)*n,a=n7e(e.y,r,t.height-r)*n;return[s,a]},JH=(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)}),Wge=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),eW=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),eN=(e,t=[0,0])=>{const{x:n,y:r}=Hke(e)?e.internals.positionAbsolute:Q3(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}},WB=(e,t=[0,0])=>{const{x:n,y:r}=Hke(e)?e.internals.positionAbsolute:Q3(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)}},Akt=(e,t)=>eW(JH(Wge(e),Wge(t))),UM=(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)},r7e=e=>wg(e.width)&&wg(e.height)&&wg(e.x)&&wg(e.y),wg=e=>!isNaN(e)&&isFinite(e),WQn=(e,t)=>{},K3=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),X3=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?K3(l,i):l},ZB=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function hE(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 ZQn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=hE(e,n),s=hE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=hE(e.top??e.y??0,n),s=hE(e.bottom??e.y??0,n),a=hE(e.left??e.x??0,t),i=hE(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 GQn(e,t,n,r,s,a){const{x:i,y:l}=ZB(e,[t,n,r]),{x:c,y:u}=ZB({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 Zke=(e,t,n,r,s,a)=>{const i=ZQn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=Jj(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,g=GQn(e,h,m,d,t,n),y={left:Math.min(g.left-i.left,0),top:Math.min(g.top-i.top,0),right:Math.min(g.right-i.right,0),bottom:Math.min(g.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},qM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function tN(e){return e!=null&&e!=="parent"}function l0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function Rkt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function Pkt(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 s7e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function QQn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function YQn(e){return{..._kt,...e||{}}}function C2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Sg(e),l=X3({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?K3(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const Gke=e=>({width:e.offsetWidth,height:e.offsetHeight}),$kt=e=>e?.getRootNode?.()||window?.document,KQn=["INPUT","SELECT","TEXTAREA"];function Mkt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:KQn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const Dkt=e=>"clientX"in e,Sg=(e,t)=>{const n=Dkt(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)}},a7e=(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,...Gke(i)}})};function Lkt({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 mz(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function i7e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case ar.Left:return[t-mz(t-r,a),n];case ar.Right:return[t+mz(r-t,a),n];case ar.Top:return[t,n-mz(n-s,a)];case ar.Bottom:return[t,n+mz(s-n,a)]}}function Qke({sourceX:e,sourceY:t,sourcePosition:n=ar.Bottom,targetX:r,targetY:s,targetPosition:a=ar.Top,curvature:i=.25}){const[l,c]=i7e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=i7e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=Lkt({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 zkt({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 XQn({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 JQn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=JH(WB(e),WB(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 UM(i,eW(a))>0}const eYn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,tYn=(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)),nYn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||eYn;let s;return Tkt(e)?s={...e}:s={...e,id:r(e)},tYn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function Fkt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=zkt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const o7e={[ar.Left]:{x:-1,y:0},[ar.Right]:{x:1,y:0},[ar.Top]:{x:0,y:-1},[ar.Bottom]:{x:0,y:1}},rYn=({source:e,sourcePosition:t=ar.Bottom,target:n})=>t===ar.Left||t===ar.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},l7e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function sYn({source:e,sourcePosition:t=ar.Bottom,target:n,targetPosition:r=ar.Top,center:s,offset:a,stepPosition:i}){const l=o7e[t],c=o7e[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=rYn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],g,y;const b={x:0,y:0},x={x:0,y:0},[,,S,k]=zkt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(g=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(g=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const T=[{x:g,y:u.y},{x:g,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?T:N:m=p==="x"?N:T}else{const T=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:T:m=l.y===h?T:N,t===r){const D=Math.abs(e[p]-n[p]);if(D<=a){const z=Math.min(a-1,a-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*z:x[p]=(d[p]>n[p]?-1:1)*z}}if(t!==r){const D=p==="x"?"y":"x",z=l[p]===c[D],H=u[D]>d[D],F=u[D]<d[D];(l[p]===1&&(!z&&H||z&&F)||l[p]!==1&&(!z&&F||z&&H))&&(m=p==="x"?T:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.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?(g=(I.x+A.x)/2,y=m[0].y):(g=m[0].x,y=(I.y+A.y)/2)}const C={x:u.x+b.x,y:u.y+b.y},_={x:d.x+x.x,y:d.y+x.y};return[[e,...C.x!==m[0].x||C.y!==m[0].y?[C]:[],...m,..._.x!==m[m.length-1].x||_.y!==m[m.length-1].y?[_]:[],n],g,y,S,k]}function aYn(e,t,n,r){const s=Math.min(l7e(e,t)/2,l7e(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 Zge({sourceX:e,sourceY:t,sourcePosition:n=ar.Bottom,targetX:r,targetY:s,targetPosition:a=ar.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,g]=sYn({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+=aYn(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,g]}function c7e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function iYn(e){const{sourceNode:t,targetNode:n}=e;if(!c7e(t)||!c7e(n))return null;const r=t.internals.handleBounds||u7e(t.handles),s=n.internals.handleBounds||u7e(n.handles),a=d7e(r?.source??[],e.sourceHandle),i=d7e(e.connectionMode===Xj.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",_y.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||ar.Bottom,c=i?.position||ar.Top,u=JO(t,a,l),d=JO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function u7e(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 JO(e,t,n=ar.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??l0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case ar.Top:return{x:s+i/2,y:a};case ar.Right:return{x:s+i,y:a+l/2};case ar.Bottom:return{x:s+i/2,y:a+l};case ar.Left:return{x:s,y:a+l/2}}}function d7e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Gge(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function oYn(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=Gge(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 Bkt=1e3,lYn=10,Yke={nodeOrigin:[0,0],nodeExtent:zM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},cYn={...Yke,checkEquality:!0};function Kke(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function uYn(e,t,n){const r=Kke(Yke,n);for(const s of e.values())if(s.parentId)Jke(s,e,t,r);else{const a=Q3(s,r.nodeOrigin),i=tN(s.extent)?s.extent:r.nodeExtent,l=XO(a,i,l0(s));s.internals.positionAbsolute=l}}function dYn(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 Xke(e){return e==="manual"}function Qge(e,t,n,r={}){const s=Kke(cYn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!Xke(s.zIndexMode)?Bkt: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=Q3(d,s.nodeOrigin),h=tN(d.extent)?d.extent:s.nodeExtent,m=XO(p,h,l0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:dYn(d,f),z:Ukt(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&&Jke(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function fYn(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 Jke(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=Kke(Yke,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}fYn(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*lYn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!Xke(c)?Bkt:0,{x:p,y:h,z:m}=pYn(e,d,i,l,f,c),{positionAbsolute:g}=e.internals,y=p!==g.x||h!==g.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:g,z:m}})}function Ukt(e,t,n){const r=wg(e.zIndex)?e.zIndex:0;return Xke(n)?r:r+(e.selected?t:0)}function pYn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=l0(e),u=Q3(e,n),d=tN(e.extent)?XO(u,e.extent,c):u;let f=XO({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=Nkt(f,c,t));const p=Ukt(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function eOe(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??eN(l),u=Akt(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=l0(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)),g=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(g-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(x=>{e.some(S=>S.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+p,y:x.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:g+(h?f[1]*h-b:0)}})}),s}function hYn(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 g=Gke(h.nodeElement),y=m.measured.width!==g.width||m.measured.height!==g.height;if(!!(g.width&&g.height&&(y||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),S=tN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=Nkt(k,g,t.get(m.parentId)):S&&(k=XO(k,S,g));const C={...m,measured:g,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:a7e("source",h.nodeElement,x,f,m.id),target:a7e("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,C),m.parentId&&Jke(C,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:g}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:eN(C,s)}))}}if(p.length>0){const h=eOe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function mYn({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 f7e(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 qkt(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}`;f7e("source",c,d,e,s,i),f7e("target",c,u,e,a,l),t.set(r.id,r)}}function Vkt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:Vkt(n,t):!1}function p7e(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 gYn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!Vkt(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 Dte({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 vYn({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=K3(a,t);return{x:i.x-a.x,y:i.y-a.y}}function yYn({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,g=null;function y({noDragClassName:x,handleSelector:S,domNode:k,isSelectable:C,nodeId:_,nodeClickDistance:E=0}){p=Cp(k);function T({x:R,y:L}){const{nodeLookup:D,nodeExtent:z,snapGrid:H,snapToGrid:F,nodeOrigin:U,onNodeDrag:q,onSelectionDrag:M,onError:G,updateNodePositions:V}=t();a={x:R,y:L};let $=!1;const B=l.size>1,Z=B&&z?Wge(Y3(l)):null,K=B&&F?vYn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[ne,ee]of l){if(!D.has(ne))continue;let J={x:R-ee.distance.x,y:L-ee.distance.y};F&&(J=K?{x:Math.round(J.x+K.x),y:Math.round(J.y+K.y)}:K3(J,H));let ae=null;if(B&&z&&!ee.extent&&Z){const{positionAbsolute:re}=ee.internals,le=re.x-Z.x+z[0][0],ue=re.x+ee.measured.width-Z.x2+z[1][0],oe=re.y-Z.y+z[0][1],me=re.y+ee.measured.height-Z.y2+z[1][1];ae=[[le,oe],[ue,me]]}const{position:fe,positionAbsolute:Y}=jkt({nodeId:ne,nextPosition:J,nodeLookup:D,nodeExtent:ae||z,nodeOrigin:U,onError:G});$=$||ee.position.x!==fe.x||ee.position.y!==fe.y,ee.position=fe,ee.internals.positionAbsolute=Y}if(m=m||$,!!$&&(V(l,!0),g&&(r||q||!_&&M))){const[ne,ee]=Dte({nodeId:_,dragItems:l,nodeLookup:D});r?.(g,l,ne,ee),q?.(g,ne,ee),_||M?.(g,ee)}}async function N(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:D,autoPanOnNodeDrag:z}=t();if(!z){c=!1,cancelAnimationFrame(i);return}const[H,F]=Ikt(u,d,D);(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})&&T(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:z,transform:H,snapGrid:F,snapToGrid:U,selectNodesOnDrag:q,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:V}=t();f=!0,(!q||!C)&&!D&&_&&(L.get(_)?.selected||V()),C&&q&&_&&e?.(_);const $=C2(R.sourceEvent,{transform:H,snapGrid:F,snapToGrid:U,containerBounds:d});if(a=$,l=gYn(L,z,$,_),l.size>0&&(n||M||!_&&G)){const[B,Z]=Dte({nodeId:_,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,B,Z),M?.(R.sourceEvent,B,Z),_||G?.(R.sourceEvent,Z)}}const A=lkt().clickDistance(E).on("start",R=>{const{domNode:L,nodeDragThreshold:D,transform:z,snapGrid:H,snapToGrid:F}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,g=R.sourceEvent,D===0&&I(R),a=C2(R.sourceEvent,{transform:z,snapGrid:H,snapToGrid:F,containerBounds:d}),u=Sg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:z,snapToGrid:H,nodeDragThreshold:F,nodeLookup:U}=t(),q=C2(R.sourceEvent,{transform:D,snapGrid:z,snapToGrid:H,containerBounds:d});if(g=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||_&&!U.has(_))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,N()),!f){const M=Sg(R.sourceEvent,d),G=M.x-u.x,V=M.y-u.y;Math.sqrt(G*G+V*V)>F&&I(R)}(a.x!==q.xSnapped||a.y!==q.ySnapped)&&l&&f&&(u=Sg(R.sourceEvent,d),T(q))}}).on("end",R=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:D,onNodeDragStop:z,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||z||!_&&H){const[F,U]=Dte({nodeId:_,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,F,U),z?.(R.sourceEvent,F,U),_||H?.(R.sourceEvent,U)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!p7e(L,`.${x}`,k))&&(!S||p7e(L,S,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function bYn(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())UM(s,eN(a))>0&&r.push(a);return r}const xYn=250;function wYn(e,t,n,r){let s=[],a=1/0;const i=bYn(e,n,t+xYn);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}=JO(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 Hkt(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,...JO(i,c,c.position,!0)}:c}function Wkt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function SYn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const Zkt=()=>!0;function kYn(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:g,onConnectEnd:y,isValidConnection:b=Zkt,onReconnectEnd:x,updateConnection:S,getTransform:k,getFromHandle:C,autoPanSpeed:_,dragThreshold:E=1,handleDomNode:T}){const N=$kt(e.target);let I=0,A;const{x:R,y:L}=Sg(e),D=Wkt(a,T),z=l?.getBoundingClientRect();let H=!1;if(!z||!D)return;const F=Hkt(s,D,r,c,t);if(!F)return;let U=Sg(e,z),q=!1,M=null,G=!1,V=null;function $(){if(!d||!z)return;const[fe,Y]=Ikt(U,z,_);p({x:fe,y:Y}),I=requestAnimationFrame($)}const B={...F,nodeId:s,type:D,position:F.position},Z=c.get(s);let ne={inProgress:!0,isValid:null,from:JO(Z,B,ar.Left,!0),fromHandle:B,fromPosition:B.position,fromNode:Z,to:U,toHandle:null,toPosition:t7e[B.position],toNode:null,pointer:U};function ee(){H=!0,S(ne),m?.(e,{nodeId:s,handleId:r,handleType:D})}E===0&&ee();function J(fe){if(!H){const{x:me,y:be}=Sg(fe),xe=me-R,Ce=be-L;if(!(xe*xe+Ce*Ce>E*E))return;ee()}if(!C()||!B){ae(fe);return}const Y=k();U=Sg(fe,z),A=wYn(X3(U,Y,!1,[1,1]),n,c,B),q||($(),q=!0);const re=Gkt(fe,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});V=re.handleDomNode,M=re.connection,G=SYn(!!A,re.isValid);const le=c.get(s),ue=le?JO(le,B,ar.Left,!0):ne.from,oe={...ne,from:ue,isValid:G,to:re.toHandle&&G?ZB({x:re.toHandle.x,y:re.toHandle.y},Y):U,toHandle:re.toHandle,toPosition:G&&re.toHandle?re.toHandle.position:t7e[B.position],toNode:re.toHandle?c.get(re.toHandle.nodeId):null,pointer:U};S(oe),ne=oe}function ae(fe){if(!("touches"in fe&&fe.touches.length>0)){if(H){(A||V)&&M&&G&&g?.(M);const{inProgress:Y,...re}=ne,le={...re,toPosition:ne.toHandle?ne.toPosition:null};y?.(fe,le),a&&x?.(fe,le)}h(),cancelAnimationFrame(I),q=!1,G=!1,M=null,V=null,N.removeEventListener("mousemove",J),N.removeEventListener("mouseup",ae),N.removeEventListener("touchmove",J),N.removeEventListener("touchend",ae)}}N.addEventListener("mousemove",J),N.addEventListener("mouseup",ae),N.addEventListener("touchmove",J),N.addEventListener("touchend",ae)}function Gkt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=Zkt,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}=Sg(e),g=i.elementFromPoint(h,m),y=g?.classList.contains(`${l}-flow__handle`)?g:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=Wkt(void 0,y),S=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),C=y.classList.contains("connectable"),_=y.classList.contains("connectableend");if(!S||!x)return b;const E={source:f?S:r,sourceHandle:f?k:s,target:f?r:S,targetHandle:f?s:k};b.connection=E;const N=C&&_&&(n===Xj.Strict?f&&x==="source"||!f&&x==="target":S!==r||k!==s);b.isValid=N&&u(E),b.toHandle=Hkt(S,x,k,d,n,!0)}return b}const Yge={onPointerDown:kYn,isValid:Gkt};function OYn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Cp(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=S=>{if(S.sourceEvent.type!=="wheel"||!t)return;const k=n(),C=S.sourceEvent.ctrlKey&&qM()?10:1,_=-S.sourceEvent.deltaY*(S.sourceEvent.deltaMode===1?.05:S.sourceEvent.deltaMode?1:.002)*d,E=k[2]*Math.pow(2,_*C);t.scaleTo(E)};let g=[0,0];const y=S=>{(S.sourceEvent.type==="mousedown"||S.sourceEvent.type==="touchstart")&&(g=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY])},b=S=>{const k=n();if(S.sourceEvent.type!=="mousemove"&&S.sourceEvent.type!=="touchmove"||!t)return;const C=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY],_=[C[0]-g[0],C[1]-g[1]];g=C;const E=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),T={x:k[0]-_[0]*E,y:k[1]-_[1]*E},N=[[0,0],[c,u]];t.setViewportConstrained({x:T.x,y:T.y,zoom:k[2]},N,l)},x=kkt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:lg}}const tW=e=>({x:e.x,y:e.y,zoom:e.k}),Lte=({x:e,y:t,zoom:n})=>XH.translate(e,t).scale(n),mT=(e,t)=>e.target.closest(`.${t}`),Qkt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),_Yn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,zte=(e,t=0,n=_Yn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},Ykt=e=>{const t=e.ctrlKey&&qM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function CYn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(mT(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=lg(d),b=Ykt(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const p=d.deltaMode===1?20:1;let h=s===iO.Vertical?0:d.deltaX*p,m=s===iO.Horizontal?0:d.deltaY*p;!qM()&&d.shiftKey&&s!==iO.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const g=tW(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,g),e.panScrollTimeout=setTimeout(()=>{u?.(d,g),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,g))}}function EYn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=mT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function TYn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=tW(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 jYn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&Qkt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,tW(a.transform))}}function NYn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&Qkt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=tW(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function IYn({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"&&(mT(f,`${u}-flow__node`)||mT(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||mT(f,l)&&m||mT(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 g=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&g}}function AYn({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=kkt().scaleExtent([t,n]).translateExtent(r),p=Cp(e).call(f);x({x:s.x,y:s.y,zoom:Jj(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(Ykt);function g(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?yx:H8).transform(zte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:D,panOnScroll:z,panOnDrag:H,panOnScrollMode:F,panOnScrollSpeed:U,preventScrolling:q,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:V,zoomActivationKeyPressed:$,lib:B,onTransformChange:Z,connectionInProgress:K,paneClickDistance:ne,selectionOnDrag:ee}){D&&!u.isZoomingOrPanning&&b();const J=z&&!$&&!D;f.clickDistance(ee?1/0:!wg(ne)||ne<0?0:ne);const ae=J?CYn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:F,panOnScrollSpeed:U,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):EYn({noWheelClassName:A,preventScrolling:q,d3ZoomHandler:h});if(p.on("wheel.zoom",ae,{passive:!1}),!D){const Y=TYn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",Y);const re=jYn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",re);const le=NYn({zoomPanValues:u,panOnDrag:H,panOnScroll:z,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",le)}const fe=IYn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:z,zoomOnDoubleClick:V,zoomOnPinch:M,userSelectionActive:D,noPanClassName:R,noWheelClassName:A,lib:B,connectionInProgress:K});f.filter(fe),V?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const D=Lte(A),z=f?.constrain()(D,R,L);return z&&await g(z),new Promise(H=>H(z))}async function S(A,R){const L=Lte(A);return await g(L,R),new Promise(D=>D(L))}function k(A){if(p){const R=Lte(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 C(){const A=p?Skt(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function _(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?yx:H8).scaleTo(zte(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"?yx:H8).scaleBy(zte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!wg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:S,setViewportConstrained:x,getViewport:C,scaleTo:_,scaleBy:E,setScaleExtent:T,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var nN;(function(e){e.Line="line",e.Handle="handle"})(nN||(nN={}));function RYn({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 h7e(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 tw(e,t){return Math.max(0,t-e)}function nw(e,t){return Math.max(0,e-t)}function gz(e,t,n){return Math.max(0,t-e,e-n)}function m7e(e,t){return e?!t:t}function PYn(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:g,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:S,y:k,width:C,height:_,aspectRatio:E}=e;let T=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=C+(c?-T:T),A=_+(u?-N:N),R=-a[0]*C,L=-a[1]*_;let D=gz(I,g,y),z=gz(A,b,x);if(i){let U=0,q=0;c&&T<0?U=tw(S+T+R,i[0][0]):!c&&T>0&&(U=nw(S+I+R,i[1][0])),u&&N<0?q=tw(k+N+L,i[0][1]):!u&&N>0&&(q=nw(k+A+L,i[1][1])),D=Math.max(D,U),z=Math.max(z,q)}if(l){let U=0,q=0;c&&T>0?U=nw(S+T,l[0][0]):!c&&T<0&&(U=tw(S+I,l[1][0])),u&&N>0?q=nw(k+N,l[0][1]):!u&&N<0&&(q=tw(k+A,l[1][1])),D=Math.max(D,U),z=Math.max(z,q)}if(s){if(d){const U=gz(I/E,b,x)*E;if(D=Math.max(D,U),i){let q=0;!c&&!u||c&&!u&&p?q=nw(k+L+I/E,i[1][1])*E:q=tw(k+L+(c?T:-T)/E,i[0][1])*E,D=Math.max(D,q)}if(l){let q=0;!c&&!u||c&&!u&&p?q=tw(k+I/E,l[1][1])*E:q=nw(k+(c?T:-T)/E,l[0][1])*E,D=Math.max(D,q)}}if(f){const U=gz(A*E,g,y)/E;if(z=Math.max(z,U),i){let q=0;!c&&!u||u&&!c&&p?q=nw(S+A*E+R,i[1][0])/E:q=tw(S+(u?N:-N)*E+R,i[0][0])/E,z=Math.max(z,q)}if(l){let q=0;!c&&!u||u&&!c&&p?q=tw(S+A*E,l[1][0])/E:q=nw(S+(u?N:-N)*E,l[0][0])/E,z=Math.max(z,q)}}}N=N+(N<0?z:-z),T=T+(T<0?D:-D),s&&(p?I>A*E?N=(m7e(c,u)?-T:T)/E:T=(m7e(c,u)?-N:N)*E:d?(N=T/E,u=c):(T=N*E,c=u));const H=c?S+T:S,F=u?k+N:k;return{width:C+(c?-T:T),height:_+(u?-N:N),x:a[0]*T*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+F}}const Kkt={width:0,height:0,x:0,y:0},$Yn={...Kkt,pointerX:0,pointerY:0,aspectRatio:1};function MYn(e){return[[0,0],[e.measured.width,e.measured.height]]}function DYn(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 LYn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Cp(e);let i={controlDirection:h7e("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:g,shouldResize:y}){let b={...Kkt},x={...$Yn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:h7e(u)};let S,k=null,C=[],_,E,T,N=!1;const I=lkt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:D,snapToGrid:z,nodeOrigin:H,paneDomNode:F}=n();if(S=R.get(t),!S)return;k=F?.getBoundingClientRect()??null;const{xSnapped:U,ySnapped:q}=C2(A.sourceEvent,{transform:L,snapGrid:D,snapToGrid:z,containerBounds:k});b={width:S.measured.width??0,height:S.measured.height??0,x:S.position.x??0,y:S.position.y??0},x={...b,pointerX:U,pointerY:q,aspectRatio:b.width/b.height},_=void 0,S.parentId&&(S.extent==="parent"||S.expandParent)&&(_=R.get(S.parentId),E=_&&S.extent==="parent"?MYn(_):void 0),C=[],T=void 0;for(const[M,G]of R)if(G.parentId===t&&(C.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const V=DYn(G,S,G.origin??H);T?T=[[Math.min(V[0][0],T[0][0]),Math.min(V[0][1],T[0][1])],[Math.max(V[1][0],T[1][0]),Math.max(V[1][1],T[1][1])]]:T=V}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:D,nodeOrigin:z}=n(),H=C2(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:D,containerBounds:k}),F=[];if(!S)return;const{x:U,y:q,width:M,height:G}=b,V={},$=S.origin??z,{width:B,height:Z,x:K,y:ne}=PYn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,E,T),ee=B!==M,J=Z!==G,ae=K!==U&&ee,fe=ne!==q&&J;if(!ae&&!fe&&!ee&&!J)return;if((ae||fe||$[0]===1||$[1]===1)&&(V.x=ae?K:b.x,V.y=fe?ne:b.y,b.x=V.x,b.y=V.y,C.length>0)){const ue=K-U,oe=ne-q;for(const me of C)me.position={x:me.position.x-ue+$[0]*(B-M),y:me.position.y-oe+$[1]*(Z-G)},F.push(me)}if((ee||J)&&(V.width=ee&&(!i.resizeDirection||i.resizeDirection==="horizontal")?B:b.width,V.height=J&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=V.width,b.height=V.height),_&&S.expandParent){const ue=$[0]*(V.width??0);V.x&&V.x<ue&&(b.x=ue,x.x=x.x-(V.x-ue));const oe=$[1]*(V.height??0);V.y&&V.y<oe&&(b.y=oe,x.y=x.y-(V.y-oe))}const Y=RYn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),re={...b,direction:Y};y?.(A,re)!==!1&&(N=!0,m?.(A,re),r(V,F))}).on("end",A=>{N&&(g?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const zYn={},g7e=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:()=>{(zYn?"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},FYn=e=>e?g7e(e):g7e,{useDebugValue:BYn}=ze,{useSyncExternalStoreWithSelector:UYn}=rCn,qYn=e=>e;function Xkt(e,t=qYn,n){const r=UYn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return BYn(r),r}const v7e=(e,t)=>{const n=FYn(e),r=(s,a=t)=>Xkt(n,s,a);return Object.assign(r,n),r},VYn=(e,t)=>e?v7e(e,t):v7e;function io(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 nW=v.createContext(null),HYn=nW.Provider,Jkt=_y.error001();function qs(e,t){const n=v.useContext(nW);if(n===null)throw new Error(Jkt);return Xkt(n,e,t)}function No(){const e=v.useContext(nW);if(e===null)throw new Error(Jkt);return v.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const y7e={display:"none"},WYn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},eOt="react-flow__node-desc",tOt="react-flow__edge-desc",ZYn="react-flow__aria-live",GYn=e=>e.ariaLiveMessage,QYn=e=>e.ariaLabelConfig;function YYn({rfId:e}){const t=qs(GYn);return o.jsx("div",{id:`${ZYn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:WYn,children:t})}function KYn({rfId:e,disableKeyboardA11y:t}){const n=qs(QYn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${eOt}-${e}`,style:y7e,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${tOt}-${e}`,style:y7e,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(YYn,{rfId:e})]})}const J3=v.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Hl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});J3.displayName="Panel";function XYn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(J3,{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 JYn=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}},vz=e=>e.id;function eKn(e,t){return io(e.selectedNodes.map(vz),t.selectedNodes.map(vz))&&io(e.selectedEdges.map(vz),t.selectedEdges.map(vz))}function tKn({onSelectionChange:e}){const t=No(),{selectedNodes:n,selectedEdges:r}=qs(JYn,eKn);return v.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const nKn=e=>!!e.onSelectionChangeHandlers;function rKn({onSelectionChange:e}){const t=qs(nKn);return e||t?o.jsx(tKn,{onSelectionChange:e}):null}const Kge=typeof window<"u"?v.useLayoutEffect:v.useEffect,nOt=[0,0],sKn={x:0,y:0,zoom:1},aKn=["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"],b7e=[...aKn,"rfId"],iKn=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}),x7e={translateExtent:zM,nodeOrigin:nOt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function oKn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=qs(iKn,io),u=No();Kge(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=x7e,l()}),[]);const d=v.useRef(x7e);return Kge(()=>{for(const f of b7e){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:YQn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},b7e.map(f=>e[f])),null}function w7e(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function lKn(e){const[t,n]=v.useState(e==="system"?null:e);return v.useEffect(()=>{if(e!=="system"){n(e);return}const r=w7e(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:w7e()?.matches?"dark":"light"}const S7e=typeof document<"u"?document:null;function VM(e=null,t={target:S7e,actInsideInputWithModifier:!0}){const[n,r]=v.useState(!1),s=v.useRef(!1),a=v.useRef(new Set([])),[i,l]=v.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
336
+ `: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 lVn(this):new aVn(this)}getCursor(t,n=0,r){let s=t.doc?t:cs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?GE(this,s,n,r):ZE(this,s,n,r)}}class ISt{constructor(t){this.spec=t}}function rVn(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 ZE(e,t,n,r){let s;return e.wholeWord&&(s=sVn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=rVn(e.test,t,s)),new Lx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function sVn(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(PB(s,n-a))!=ko.Word||t($B(s,n-a))!=ko.Word)&&(t($B(s,r-a))!=ko.Word||t(PB(s,r-a))!=ko.Word))}class aVn extends ISt{constructor(t){super(t)}nextMatch(t,n,r){let s=ZE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=ZE(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=ZE(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=ZE(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=ZE(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 iVn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function GE(e,t,n,r){let s;return e.wholeWord&&(s=oVn(t.charCategorizer(t.selection.main.head))),e.test&&(s=iVn(e.test,t,s)),new TSt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function PB(e,t){return e.slice(Ec(e,t,!1),t)}function $B(e,t){return e.slice(t,Ec(e,t))}function oVn(e){return(t,n,r)=>!r[0].length||(e(PB(r.input,r.index))!=ko.Word||e($B(r.input,r.index))!=ko.Word)&&(e($B(r.input,r.index+r[0].length))!=ko.Word||e(PB(r.input,r.index+r[0].length))!=ko.Word)}class lVn extends ISt{nextMatch(t,n,r){let s=GE(this.spec,t,r,t.doc.length).next();return s.done&&(s=GE(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=GE(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=GE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=GE(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const AM=xr.define(),Ake=xr.define(),Kw=xl.define({create(e){return new $ee(Mge(e).create(),null)},update(e,t){for(let n of t.effects)n.is(AM)?e=new $ee(n.value.create(),e.panel):n.is(Ake)&&(e=new $ee(e.query,n.value?Rke:null));return e},provide:e=>SM.from(e,t=>t.panel)});class $ee{constructor(t,n){this.query=t,this.panel=n}}const cVn=jn.mark({class:"cm-searchMatch"}),uVn=jn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),dVn=To.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Kw))}update(e){let t=e.state.field(Kw);(t!=e.startState.field(Kw)||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 Ld;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?uVn:cVn)})}return r.finish()}},{decorations:e=>e.decorations});function W3(e){return t=>{let n=t.state.field(Kw,!1);return n&&n.query.spec.valid?e(t,n):PSt(t)}}const MB=W3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=xt.single(r.from,r.to),a=e.state.facet(SI);return e.dispatch({selection:s,effects:[Pke(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),RSt(e),!0}),DB=W3((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=xt.single(s.from,s.to),i=e.state.facet(SI);return e.dispatch({selection:a,effects:[Pke(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),RSt(e),!0}),fVn=W3((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:xt.create(n.map(r=>xt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),pVn=({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 Lx(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(xt.range(l.value.from,l.value.to))}return t(e.update({selection:xt.create(a,i),userEvent:"select.search.matches"})),!0},j8e=W3((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(It.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=xt.single(i.from,i.to).map(f),d.push(Pke(e,i)),d.push(n.facet(SI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),hVn=W3((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:It.announce.of(r),userEvent:"input.replace.all"}),!0});function Rke(e){return e.state.facet(SI).createPanel(e)}function Mge(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(SI);return new NSt({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 ASt(e){let t=QSe(e,Rke);return t&&t.dom.querySelector("[main-field]")}function RSt(e){let t=ASt(e);t&&t==e.root.activeElement&&t.select()}const PSt=e=>{let t=e.state.field(Kw,!1);if(t&&t.panel){let n=ASt(e);if(n&&n!=e.root.activeElement){let r=Mge(e.state,t.query.spec);r.valid&&e.dispatch({effects:AM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Ake.of(!0),t?AM.of(Mge(e.state,t.query.spec)):xr.appendConfig.of(yVn)]});return!0},$St=e=>{let t=e.state.field(Kw,!1);if(!t||!t.panel)return!1;let n=QSe(e,Rke);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Ake.of(!1)}),!0},mVn=[{key:"Mod-f",run:PSt,scope:"editor search-panel"},{key:"F3",run:MB,shift:DB,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:MB,shift:DB,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:$St,scope:"editor search-panel"},{key:"Mod-Shift-l",run:pVn},{key:"Mod-Alt-g",run:Hqn},{key:"Mod-d",run:nVn,preventDefault:!0}];class gVn{constructor(t){this.view=t;let n=this.query=t.state.field(Kw).query.spec;this.commit=this.commit.bind(this),this.searchField=pi("input",{value:n.search,placeholder:lp(t,"Find"),"aria-label":lp(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=pi("input",{value:n.replace,placeholder:lp(t,"Replace"),"aria-label":lp(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=pi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=pi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=pi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return pi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=pi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>MB(t),[lp(t,"next")]),r("prev",()=>DB(t),[lp(t,"previous")]),r("select",()=>fVn(t),[lp(t,"all")]),pi("label",null,[this.caseField,lp(t,"match case")]),pi("label",null,[this.reField,lp(t,"regexp")]),pi("label",null,[this.wordField,lp(t,"by word")]),...t.state.readOnly?[]:[pi("br"),this.replaceField,r("replace",()=>j8e(t),[lp(t,"replace")]),r("replaceAll",()=>hVn(t),[lp(t,"replace all")])],pi("button",{name:"close",onclick:()=>$St(t),"aria-label":lp(t,"close"),type:"button"},["×"])])}commit(){let t=new NSt({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:AM.of(t)}))}keydown(t){Mzn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?DB:MB)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),j8e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(AM)&&!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(SI).top}}function lp(e,t){return e.state.phrase(t)}const oz=30,lz=/[\s\.,:;?!]/;function Pke(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-oz),i=Math.min(s,n+oz),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<oz;c++)if(!lz.test(l[c+1])&&lz.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-oz;c--)if(!lz.test(l[c-1])&&lz.test(l[c])){l=l.slice(0,c);break}}return It.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const vVn=It.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),yVn=[Kw,th.low(dVn),vVn];class N8e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class jk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(RM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Ld,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((g,y)=>Math.min(g,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let g=a[d];if(g.from==p&&(g.to>g.from||g.to==p))l.push(g),d++,h=Math.min(g.to,h);else{h=Math.min(g.from,h);break}}let m=IVn(l);if(l.some(g=>g.from==g.to||g.from==g.to-1&&r.doc.lineAt(g.from).to==g.from))i.add(p,p,jn.widget({widget:new EVn(m),diagnostics:l.slice()}));else{let g=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,jn.mark({class:"cm-lintRange cm-lintRange-"+m+g,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let g=0;g<l.length;g++)l[g].to<=c&&l.splice(g--,1)}let u=i.finish();return new jk(u,n,Qj(u))}}function Qj(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 N8e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new N8e(r.from,a,r.diagnostic)}}),r}function bVn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(RM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(MSt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function xVn(e,t){return e.field(Np,!1)?t:t.concat(xr.appendConfig.of(AVn))}const MSt=xr.define(),$ke=xr.define(),DSt=xr.define(),Np=xl.define({create(){return new jk(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=Qj(n,e.selected.diagnostic,a)||Qj(n,null,a)}!n.size&&s&&t.state.facet(RM).autoPanel&&(s=null),e=new jk(n,s,r)}for(let n of t.effects)if(n.is(MSt)){let r=t.state.facet(RM).autoPanel?n.value.length?PM.open:null:e.panel;e=jk.init(n.value,r,t.state)}else n.is($ke)?e=new jk(e.diagnostics,n.value?PM.open:null,e.selected):n.is(DSt)&&(e=new jk(e.diagnostics,e.panel,n.value));return e},provide:e=>[SM.from(e,t=>t.panel),It.decorations.from(e,t=>t.diagnostics)]}),wVn=jn.mark({class:"cm-lintRange cm-lintRange-active"});function SVn(e,t,n){let{diagnostics:r}=e.state.field(Np),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(RM).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:kVn(e,s)}}}:null}function kVn(e,t){return pi("ul",{class:"cm-tooltip-lint"},t.map(n=>zSt(e,n,!1)))}const OVn=e=>{let t=e.state.field(Np,!1);(!t||!t.panel)&&e.dispatch({effects:xVn(e.state,[$ke.of(!0)])});let n=QSe(e,PM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},I8e=e=>{let t=e.state.field(Np,!1);return!t||!t.panel?!1:(e.dispatch({effects:$ke.of(!1)}),!0)},_Vn=e=>{let t=e.state.field(Np,!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)},CVn=[{key:"Mod-Shift-m",run:OVn,preventDefault:!0},{key:"F8",run:_Vn}],RM=En.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Hy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:A8e,tooltipFilter:A8e,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 A8e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function LSt(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 zSt(e,t,n){var r;let s=n?LSt(t.actions):[];return pi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},pi("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=Qj(e.state.field(Np).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),pi("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return pi("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&pi("div",{class:"cm-diagnosticSource"},t.source))}class EVn extends nh{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return pi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class R8e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=zSt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class PM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)I8e(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=LSt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=Qj(this.view.state.field(Np).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=pi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=pi("div",{class:"cm-panel-lint"},this.list,pi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>I8e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Np).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(Np),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 R8e(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 R8e(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(Np),r=Qj(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:DSt.of(r)})}static open(t){return new PM(t)}}function TVn(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 cz(e){return TVn(`<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 jVn=It.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:cz("#d11")},".cm-lintRange-warning":{backgroundImage:cz("orange")},".cm-lintRange-info":{backgroundImage:cz("#999")},".cm-lintRange-hint":{backgroundImage:cz("#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 IVn(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 AVn=[Np,It.decorations.compute([Np],e=>{let{selected:t,panel:n}=e.field(Np);return!t||!n||t.from==t.to?jn.none:jn.set([wVn.range(t.from,t.to)])}),OFn(SVn,{hideOn:bVn}),jVn];var P8e=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(w9n)),t.defaultKeymap!==!1&&(a=a.concat(Uqn)),t.searchKeymap!==!1&&(a=a.concat(mVn)),t.historyKeymap!==!1&&(a=a.concat(QUn)),t.foldKeymap!==!1&&(a=a.concat(i8n)),t.completionKeymap!==!1&&(a=a.concat(Rwt)),t.lintKeymap!==!1&&(a=a.concat(CVn));var i=[];return t.lineNumbers!==!1&&i.push(MFn()),t.highlightActiveLineGutter!==!1&&i.push(zFn()),t.highlightSpecialChars!==!1&&i.push(Xzn()),t.history!==!1&&i.push(FUn()),t.foldGutter!==!1&&i.push(u8n()),t.drawSelection!==!1&&i.push(Uzn()),t.dropCursor!==!1&&i.push(Zzn()),t.allowMultipleSelections!==!1&&i.push(cs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(XFn()),t.syntaxHighlighting!==!1&&i.push(tS(h8n,{fallback:!0})),t.bracketMatching!==!1&&i.push(w8n()),t.closeBrackets!==!1&&i.push(v9n()),t.autocompletion!==!1&&i.push(Awt()),t.rectangularSelection!==!1&&i.push(fFn()),s!==!1&&i.push(mFn()),t.highlightActiveLine!==!1&&i.push(sFn()),t.highlightSelectionMatches!==!1&&i.push(Gqn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(yI.of(" ".repeat(t.tabSize))),i.concat([vI.of(a.flat())]).filter(Boolean)};const RVn="#e5c07b",$8e="#e06c75",PVn="#56b6c2",$Vn="#ffffff",q8="#abb2bf",Dge="#7d8799",MVn="#61afef",DVn="#98c379",M8e="#d19a66",LVn="#c678dd",zVn="#21252b",D8e="#2c313a",L8e="#282c34",Mee="#353a42",FVn="#3E4451",z8e="#528bff",BVn=It.theme({"&":{color:q8,backgroundColor:L8e},".cm-content":{caretColor:z8e},".cm-cursor, .cm-dropCursor":{borderLeftColor:z8e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:FVn},".cm-panels":{backgroundColor:zVn,color:q8},".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:L8e,color:Dge,border:"none"},".cm-activeLineGutter":{backgroundColor:D8e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Mee},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Mee,borderBottomColor:Mee},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:D8e,color:q8}}},{dark:!0}),UVn=Zg.define([{tag:pe.keyword,color:LVn},{tag:[pe.name,pe.deleted,pe.character,pe.propertyName,pe.macroName],color:$8e},{tag:[pe.function(pe.variableName),pe.labelName],color:MVn},{tag:[pe.color,pe.constant(pe.name),pe.standard(pe.name)],color:M8e},{tag:[pe.definition(pe.name),pe.separator],color:q8},{tag:[pe.typeName,pe.className,pe.number,pe.changed,pe.annotation,pe.modifier,pe.self,pe.namespace],color:RVn},{tag:[pe.operator,pe.operatorKeyword,pe.url,pe.escape,pe.regexp,pe.link,pe.special(pe.string)],color:PVn},{tag:[pe.meta,pe.comment],color:Dge},{tag:pe.strong,fontWeight:"bold"},{tag:pe.emphasis,fontStyle:"italic"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:pe.link,color:Dge,textDecoration:"underline"},{tag:pe.heading,fontWeight:"bold",color:$8e},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:M8e},{tag:[pe.processingInstruction,pe.string,pe.inserted],color:DVn},{tag:pe.invalid,color:$Vn}]),qVn=[BVn,tS(UVn)];var VVn=It.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),HVn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,g=[];switch(s&&g.unshift(vI.of([qqn])),m&&(typeof m=="boolean"?g.unshift(P8e()):g.unshift(P8e(m))),p&&g.unshift(lFn(p)),d){case"light":g.push(VVn);break;case"dark":g.push(qVn);break;case"none":break;default:g.push(d);break}return i===!1&&g.push(It.editable.of(!1)),c&&g.push(cs.readOnly.of(!0)),[...g]},WVn=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 ZVn{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 F8e{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 Dee=null,GVn=()=>typeof window>"u"?new F8e:(Dee||(Dee=new F8e),Dee),QVn=It.theme({"& .cm-scroller":{height:"100% !important"}}),B8e=null,Lee=null;function YVn(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===B8e||(B8e=i,Lee=It.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),Lee}var U8e=Vy.define(),KVn=200,XVn=[];function JVn(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?XVn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,g=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,S=x===void 0?null:x,k=e.minWidth,C=k===void 0?null:k,_=e.maxWidth,E=_===void 0?null:_,T=e.placeholder,N=T===void 0?"":T,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,D=e.indentWithTab,z=D===void 0?!0:D,H=e.basicSetup,F=H===void 0?!0:H,U=e.root,q=e.initialState,M=v.useState(),G=M[0],V=M[1],$=v.useState(),B=$[0],Z=$[1],K=v.useState(),ne=K[0],ee=K[1],J=v.useState(()=>({current:null}))[0],ae=v.useState(()=>({current:null}))[0],fe=YVn(h,g,b,S,C,E),Y=It.updateListener.of(ue=>{if(ue.docChanged&&typeof r=="function"&&!ue.transactions.some(be=>be.annotation(U8e))){J.current?J.current.reset():(J.current=new ZVn(()=>{if(ae.current){var be=ae.current;ae.current=null,be()}J.current=null},KVn),GVn().add(J.current));var oe=ue.state.doc,me=oe.toString();r(me,ue)}s&&s(WVn(ue))}),re=HVn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:z,basicSetup:F}),le=[Y,...fe?[fe]:[],QVn,...re];return i&&typeof i=="function"&&le.push(It.updateListener.of(i)),le=le.concat(c),v.useLayoutEffect(()=>{if(G&&!ne){var ue={doc:t,selection:n,extensions:le},oe=q?cs.fromJSON(q.json,ue,q.fields):cs.create(ue);if(ee(oe),!B){var me=new It({state:oe,parent:G,root:U});Z(me),a&&a(me,oe)}}return()=>{B&&(ee(void 0),Z(void 0))}},[G,ne]),v.useEffect(()=>{e.container&&V(e.container)},[e.container]),v.useEffect(()=>()=>{B&&(B.destroy(),Z(void 0)),J.current&&(J.current.cancel(),J.current=null)},[B]),v.useEffect(()=>{u&&B&&B.focus()},[u,B]),v.useEffect(()=>{B&&B.dispatch({effects:xr.reconfigure.of(le)})},[f,c,h,g,b,S,C,E,N,A,L,z,F,r,i]),v.useEffect(()=>{if(t!==void 0){var ue=B?B.state.doc.toString():"";if(B&&t!==ue){var oe=J.current&&!J.current.isDone,me=()=>{B&&t!==B.state.doc.toString()&&B.dispatch({changes:{from:0,to:B.state.doc.toString().length,insert:t||""},annotations:[U8e.of(!0)]})};oe?ae.current=me:me()}}},[t,B]),{state:ne,setState:ee,view:B,setView:Z,container:G,setContainer:V}}var eHn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],ed=v.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,g=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,S=e.minWidth,k=e.maxWidth,C=e.basicSetup,_=e.placeholder,E=e.indentWithTab,T=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=Z1t(e,eHn),L=v.useRef(null),D=JVn({root:I,value:s,autoFocus:p,theme:m,height:g,minHeight:y,maxHeight:b,width:x,minWidth:S,maxWidth:k,basicSetup:C,placeholder:_,indentWithTab:E,editable:T,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),z=D.state,H=D.view,F=D.container,U=D.setContainer;v.useImperativeHandle(t,()=>({editor:L.current,state:z,view:H}),[L,F,z,H]);var q=v.useCallback(G=>{L.current=G,U(G)},[U]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",QO({ref:q,className:""+M+(n?" "+n:"")},R))});ed.displayName="CodeMirror";const tHn={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 zee=null;function nHn(){return zee||(zee=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([vo(()=>import("./core-CTRJn-8F.js"),__vite__mapDeps([0,1,2]),import.meta.url),vo(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[vo(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),vo(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[vo(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),vo(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),vo(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),vo(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),vo(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),vo(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),vo(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),vo(()=>import("./python-DhUJRlN_.js"),[],import.meta.url)],engine:t()})})()),zee}async function rHn(e,t){const n=tHn[t?.toLowerCase()];if(!n)return null;const r=await nHn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function sHn(e){return new HO(eke.define(e))}const FSt=[og.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return vo(()=>Promise.resolve().then(()=>az),void 0,import.meta.url).then(e=>e.javascript())}}),og.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return vo(()=>Promise.resolve().then(()=>R8n),void 0,import.meta.url).then(e=>e.json())}}),og.of({name:"JSX",extensions:["jsx"],load(){return vo(()=>Promise.resolve().then(()=>az),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),og.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return vo(()=>Promise.resolve().then(()=>EUn),void 0,import.meta.url).then(e=>e.markdown())}}),og.of({name:"TSX",extensions:["tsx"],load(){return vo(()=>Promise.resolve().then(()=>az),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),og.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return vo(()=>Promise.resolve().then(()=>az),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),og.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return vo(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>sHn(e.shell))}})];function aHn(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 iHn(e){const t=aHn(e);return Awt({override:[oHn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function oHn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,p)=>{const g=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:g},selection:{anchor:f+g.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const lHn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,cHn=jn.mark({class:"cm-variable-highlight"}),q8e=new W0t({regexp:lHn,decoration:()=>cHn}),uHn=To.fromClass(class{decorations;constructor(e){this.decorations=q8e.createDeco(e)}update(e){this.decorations=q8e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),dHn=uHn;function fHn(){const e=xI({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:[pe.className,pe.propertyName],color:"var(--neutral6)"},{tag:pe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.heading1,pe.heading2,pe.heading3,pe.heading4,pe.heading5,pe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:pe.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:pe.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:pe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:pe.url,color:"var(--accent3)"},{tag:pe.monospace,color:"var(--neutral6)"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:pe.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=It.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function pHn(){const e=It.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=Zg.define([{tag:[pe.comment,pe.bracket],color:"var(--neutral2)"},{tag:[pe.string,pe.meta,pe.regexp],color:"var(--accent1)"},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:"var(--accent6)"},{tag:[pe.keyword,pe.operator,pe.tagName],color:"var(--accent2)"},{tag:[pe.function(pe.propertyName),pe.propertyName],color:"var(--accent5)"},{tag:[pe.definition(pe.variableName),pe.function(pe.variableName),pe.className,pe.attributeName],color:"var(--accent3)"},{tag:[pe.variableName,pe.number],color:"var(--accent5)"},{tag:[pe.name,pe.quote],color:"var(--accent1)"},{tag:pe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.heading1,pe.heading2,pe.heading3,pe.heading4,pe.heading5,pe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[pe.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:pe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:pe.url,color:"var(--accent3)"},{tag:pe.monospace,color:"var(--neutral6)"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:[pe.deleted],color:"var(--accent2)"},{tag:pe.invalid,color:"var(--error)"},{tag:[pe.standard(pe.tagName)],color:"var(--accent1)"}]);return[e,tS(t)]}const o0=()=>{const e=Z_().resolvedTheme==="dark";return v.useMemo(()=>e?fHn():pHn(),[e])},hHn=co(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"}}),mHn=th.highest(It.editorAttributes.of({style:"outline: none"})),gHn=th.highest(It.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),vHn=[mHn,gHn],Hr=v.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,...m},g)=>{const y=o0(),b=e?JSON.stringify(e,null,2):t??"",x=v.useMemo(()=>{const S=[...vHn];return f&&S.push(It.lineWrapping),a==="json"?S.push(Dp):a==="markdown"&&S.push(Eke({base:GO,codeLanguages:FSt})),i&&a==="markdown"&&S.push(dHn),c&&a==="markdown"&&S.push(iHn(c)),p===!1&&S.push(cs.readOnly.of(!0)),S},[a,i,c,p,f]);return o.jsxs("div",{className:X(hHn({variant:h}),s),...m,children:[r&&o.jsx(Pa,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(ed,{ref:g,value:b,theme:y,extensions:x,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),yHn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},bHn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=o0(),{settings:r,setSettings:s}=xH(),a=r?.tracingOptions,i=v.useMemo(()=>yHn(a),[a]),[l,c]=v.useState(()=>i),u=v.useRef(!1);v.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(ed,{value:l,onChange:d,theme:n,extensions:[Dp],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(ce,{type:"button",onClick:f,children:"Save"})})]})},xHn=()=>{const[e,t]=v.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx(ce,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(qe,{children:o.jsx(dV,{})})})}),o.jsx(Pn,{children:"Run Options"})]}),o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Run Options"}),o.jsx(Bs,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Rr,{children:o.jsx(bHn,{onSaved:()=>t(!1)})})]})})]})};function wHn({status:e}){switch(e){case"running":return o.jsx(Jt,{});case"failed":return o.jsx(ps,{className:"text-accent2"});case"canceled":return o.jsx($f,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(yj,{className:"text-neutral3"});case"suspended":return o.jsx(aV,{className:"text-accent3"});case"success":return o.jsx(fa,{className:"text-accent1"});default:return o.jsx(yj,{className:"text-neutral3"})}}function BSt({status:e}){return o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx(qe,{"aria-label":e,className:"shrink-0",children:o.jsx(wHn,{status:e})})}),o.jsx(Pn,{children:e})]})}var Fee,V8e;function Mke(){if(V8e)return Fee;V8e=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([g,y]){d(g)&&f.setNode(g,y)}),Object.values(this._edgeObjs).forEach(function(g){f.hasNode(g.v)&&f.hasNode(g.w)&&f.setEdge(g,p.edge(g))});var h={};function m(g){var y=p.parent(g);return y===void 0||f.hasNode(y)?(h[g]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(g=>f.setParent(g,m(g))),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,g){return h.length>1?p.setEdge(m,g,f):p.setEdge(m,g),g}),this}setEdge(){var d,f,p,h,m=!1,g=arguments[0];typeof g=="object"&&g!==null&&"v"in g?(d=g.v,f=g.w,p=g.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=g,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 g=h;h=m,m=g}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 g=h;h=m,m=g}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 Fee=r,Fee}var Bee,H8e;function SHn(){return H8e||(H8e=1,Bee="2.2.4"),Bee}var Uee,W8e;function kHn(){return W8e||(W8e=1,Uee={Graph:Mke(),version:SHn()}),Uee}var qee,Z8e;function OHn(){if(Z8e)return qee;Z8e=1;var e=Mke();qee={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 qee}var Vee,G8e;function _Hn(){if(G8e)return Vee;G8e=1,Vee=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 Vee}var Hee,Q8e;function USt(){if(Q8e)return Hee;Q8e=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 Hee=e,Hee}var Wee,Y8e;function qSt(){if(Y8e)return Wee;Y8e=1;var e=USt();Wee=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,g=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<g.distance&&(g.distance=b,g.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 Wee}var Zee,K8e;function CHn(){if(K8e)return Zee;K8e=1;var e=qSt();Zee=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Zee}var Gee,X8e;function VSt(){if(X8e)return Gee;X8e=1,Gee=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 Gee}var Qee,J8e;function EHn(){if(J8e)return Qee;J8e=1;var e=VSt();Qee=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return Qee}var Yee,e9e;function THn(){if(e9e)return Yee;e9e=1,Yee=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],g=f[p],y=h.distance+m.distance;y<g.distance&&(g.distance=y,g.predecessor=m.predecessor)})})}),i}return Yee}var Kee,t9e;function HSt(){if(t9e)return Kee;t9e=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 Kee=e,e.CycleException=t,Kee}var Xee,n9e;function jHn(){if(n9e)return Xee;n9e=1;var e=HSt();Xee=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return Xee}var Jee,r9e;function WSt(){if(r9e)return Jee;r9e=1,Jee=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 Jee}var ete,s9e;function NHn(){if(s9e)return ete;s9e=1;var e=WSt();ete=t;function t(n,r){return e(n,r,"post")}return ete}var tte,a9e;function IHn(){if(a9e)return tte;a9e=1;var e=WSt();tte=t;function t(n,r){return e(n,r,"pre")}return tte}var nte,i9e;function AHn(){if(i9e)return nte;i9e=1;var e=Mke(),t=USt();nte=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 nte}var rte,o9e;function RHn(){return o9e||(o9e=1,rte={components:_Hn(),dijkstra:qSt(),dijkstraAll:CHn(),findCycles:EHn(),floydWarshall:THn(),isAcyclic:jHn(),postorder:NHn(),preorder:IHn(),prim:AHn(),tarjan:VSt(),topsort:HSt()}),rte}var ste,l9e;function Bg(){if(l9e)return ste;l9e=1;var e=kHn();return ste={Graph:e.Graph,json:OHn(),alg:RHn(),version:e.version},ste}var ate,c9e;function PHn(){if(c9e)return ate;c9e=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 ate=e,ate}var ite,u9e;function $Hn(){if(u9e)return ite;u9e=1;let e=Bg().Graph,t=PHn();ite=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],g;for(;u.nodeCount();){for(;g=m.dequeue();)a(u,d,f,g);for(;g=h.dequeue();)a(u,d,f,g);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(g=d[y].dequeue(),g){p=p.concat(a(u,d,f,g,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(g=>{let y=u.edge(g),b=u.node(g.v);h&&m.push({v:g.v,w:g.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(g=>{let y=u.edge(g),b=g.w,x=u.node(b);x.in-=y,l(d,f,x)}),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,x=d(y),S=b+x;f.setEdge(y.v,y.w,S),h=Math.max(h,f.node(y.v).out+=x),p=Math.max(p,f.node(y.w).in+=x)});let m=c(h+p+3).map(()=>new t),g=p+1;return f.nodes().forEach(y=>{l(m,g,f.node(y))}),{graph:f,buckets:m,zeroIdx:g}}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 ite}var ote,d9e;function Ll(){if(d9e)return ote;d9e=1;let e=Bg().Graph;ote={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:_,maxRank:m,normalizeRanks:c,notime:b,partition:g,pick:C,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:S,zipObject:E};function t(T,N,I,A){for(var R=A;T.hasNode(R);)R=S(A);return I.dummy=N,T.setNode(R,I),R}function n(T){let N=new e().setGraph(T.graph());return T.nodes().forEach(I=>N.setNode(I,T.node(I))),T.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=T.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(T){let N=new e({multigraph:T.isMultigraph()}).setGraph(T.graph());return T.nodes().forEach(I=>{T.children(I).length||N.setNode(I,T.node(I))}),T.edges().forEach(I=>{N.setEdge(I,T.edge(I))}),N}function s(T){let N=T.nodes().map(I=>{let A={};return T.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function a(T){let N=T.nodes().map(I=>{let A={};return T.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function i(T,N){let I=T.x,A=T.y,R=N.x-I,L=N.y-A,D=T.width/2,z=T.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,F;return Math.abs(L)*D>Math.abs(R)*z?(L<0&&(z=-z),H=z*R/L,F=z):(R<0&&(D=-D),H=D,F=D*L/R),{x:I+H,y:A+F}}function l(T){let N=k(m(T)+1).map(()=>[]);return T.nodes().forEach(I=>{let A=T.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(T){let N=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,N);T.nodes().forEach(A=>{let R=T.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(T){let N=T.nodes().map(D=>T.node(D).rank),I=h(Math.min,N),A=[];T.nodes().forEach(D=>{let z=T.node(D).rank-I;A[z]||(A[z]=[]),A[z].push(D)});let R=0,L=T.graph().nodeRankFactor;Array.from(A).forEach((D,z)=>{D===void 0&&z%L!==0?--R:D!==void 0&&R&&D.forEach(H=>T.node(H).rank+=R)})}function d(T,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(T,"border",R,N)}function f(T,N=p){const I=[];for(let A=0;A<T.length;A+=N){const R=T.slice(A,A+N);I.push(R)}return I}const p=65535;function h(T,N){if(N.length>p){const I=f(N);return T.apply(null,I.map(A=>T.apply(null,A)))}else return T.apply(null,N)}function m(T){const I=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function g(T,N){let I={lhs:[],rhs:[]};return T.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(T,N){let I=Date.now();try{return N()}finally{console.log(T+" time: "+(Date.now()-I)+"ms")}}function b(T,N){return N()}let x=0;function S(T){var N=++x;return T+(""+N)}function k(T,N,I=1){N==null&&(N=T,T=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=T;A(L);L+=I)R.push(L);return R}function C(T,N){const I={};for(const A of N)T[A]!==void 0&&(I[A]=T[A]);return I}function _(T,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(T).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function E(T,N){return T.reduce((I,A,R)=>(I[A]=N[R],I),{})}return ote}var lte,f9e;function MHn(){if(f9e)return lte;f9e=1;let e=$Hn(),t=Ll().uniqueId;lte={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 lte}var cte,p9e;function DHn(){if(p9e)return cte;p9e=1;let e=Ll();cte={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,g;for(g=0,++l;l<u;++g,++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),g===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 cte}var ute,h9e;function LB(){if(h9e)return ute;h9e=1;const{applyWithChunking:e}=Ll();ute={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 ute}var dte,m9e;function ZSt(){if(m9e)return dte;m9e=1;var e=Bg().Graph,t=LB().slack;dte=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 dte}var fte,g9e;function LHn(){if(g9e)return fte;g9e=1;var e=ZSt(),t=LB().slack,n=LB().longestPath,r=Bg().alg.preorder,s=Bg().alg.postorder,a=Ll().simplify;fte=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(x){x=a(x),n(x);var S=e(x);d(S),l(S,x);for(var k,C;k=p(S);)C=h(S,x,k),m(S,x,k,C)}function l(x,S){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(C=>c(x,S,C))}function c(x,S,k){var C=x.node(k),_=C.parent;x.edge(k,_).cutvalue=u(x,S,k)}function u(x,S,k){var C=x.node(k),_=C.parent,E=!0,T=S.edge(k,_),N=0;return T||(E=!1,T=S.edge(_,k)),N=T.weight,S.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==_){var L=A===E,D=S.edge(I).weight;if(N+=L?D:-D,y(x,k,R)){var z=x.edge(k,R).cutvalue;N+=L?-z:z}}}),N}function d(x,S){arguments.length<2&&(S=x.nodes()[0]),f(x,{},1,S)}function f(x,S,k,C,_){var E=k,T=x.node(C);return S[C]=!0,x.neighbors(C).forEach(N=>{Object.hasOwn(S,N)||(k=f(x,S,k,N,C))}),T.low=E,T.lim=k++,_?T.parent=_:delete T.parent,k}function p(x){return x.edges().find(S=>x.edge(S).cutvalue<0)}function h(x,S,k){var C=k.v,_=k.w;S.hasEdge(C,_)||(C=k.w,_=k.v);var E=x.node(C),T=x.node(_),N=E,I=!1;E.lim>T.lim&&(N=T,I=!0);var A=S.edges().filter(R=>I===b(x,x.node(R.v),N)&&I!==b(x,x.node(R.w),N));return A.reduce((R,L)=>t(S,L)<t(S,R)?L:R)}function m(x,S,k,C){var _=k.v,E=k.w;x.removeEdge(_,E),x.setEdge(C.v,C.w,{}),d(x),l(x,S),g(x,S)}function g(x,S){var k=x.nodes().find(_=>!S.node(_).parent),C=r(x,k);C=C.slice(1),C.forEach(_=>{var E=x.node(_).parent,T=S.edge(_,E),N=!1;T||(T=S.edge(E,_),N=!0),S.node(_).rank=S.node(E).rank+(N?T.minlen:-T.minlen)})}function y(x,S,k){return x.hasEdge(S,k)}function b(x,S,k){return k.low<=S.lim&&S.lim<=k.lim}return fte}var pte,v9e;function zHn(){if(v9e)return pte;v9e=1;var e=LB(),t=e.longestPath,n=ZSt(),r=LHn();pte=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 pte}var hte,y9e;function FHn(){if(y9e)return hte;y9e=1,hte=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 hte}var mte,b9e;function BHn(){if(b9e)return mte;b9e=1;let e=Ll();mte={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"),g=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(g,p),y.borderBottom=g,h.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),S=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,C=x.borderTop?u:2*u,_=S!==k?1:d-f[p]+1;i.setEdge(m,S,{weight:C,minlen:_,nestingEdge:!0}),i.setEdge(k,g,{weight:C,minlen:_,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 mte}var gte,x9e;function UHn(){if(x9e)return gte;x9e=1;let e=Ll();gte=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 gte}var vte,w9e;function qHn(){if(w9e)return vte;w9e=1,vte={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 vte}var yte,S9e;function VHn(){if(S9e)return yte;S9e=1;let e=Ll();yte=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 yte}var bte,k9e;function HHn(){if(k9e)return bte;k9e=1;let e=Ll().zipObject;bte=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 bte}var xte,O9e;function WHn(){if(O9e)return xte;O9e=1,xte=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 xte}var wte,_9e;function ZHn(){if(_9e)return wte;_9e=1;let e=Ll();wte=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 wte}var Ste,C9e;function GHn(){if(C9e)return Ste;C9e=1;let e=Ll();Ste=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,g)=>g.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 Ste}var kte,E9e;function QHn(){if(E9e)return kte;E9e=1;let e=WHn(),t=ZHn(),n=GHn();kte=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(x=>x!==p&&x!==h));let g=e(i,d);g.forEach(x=>{if(i.children(x.v).length){let S=r(i,x.v,c,u);m[x.v]=S,Object.hasOwn(S,"barycenter")&&a(x,S)}});let y=t(g,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let x=i.node(i.predecessors(p)[0]),S=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+S.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 kte}var Ote,T9e;function YHn(){if(T9e)return Ote;T9e=1;let e=Bg().Graph,t=Ll();Ote=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,g=u.edge(m,d),y=g!==void 0?g.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 Ote}var _te,j9e;function KHn(){if(j9e)return _te;j9e=1,_te=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 _te}var Cte,N9e;function XHn(){if(N9e)return Cte;N9e=1;let e=VHn(),t=HHn(),n=QHn(),r=YHn(),s=KHn(),a=Bg().Graph,i=Ll();Cte=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"),g=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,x;for(let S=0,k=0;k<4;++S,++k){u(S%2?m:g,S%4>=2),y=i.buildLayerMatrix(f);let C=t(f,y);C<b&&(k=0,x=Object.assign({},y),b=C)}d(f,x)}function c(f,p,h){const m=new Map,g=(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"&&g(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&g(x,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 g=m.graph().root,y=n(m,g,h,p);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,g)=>f.node(m).order=g))}return Cte}var Ete,I9e;function JHn(){if(I9e)return Ete;I9e=1;let e=Bg().Graph,t=Ll();Ete={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 x={};function S(k,C){let _=0,E=0,T=k.length,N=C[C.length-1];return C.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:T;(R||I===N)&&(C.slice(E,A+1).forEach(D=>{y.predecessors(D).forEach(z=>{let H=y.node(z),F=H.order;(F<_||L<F)&&!(H.dummy&&y.node(D).dummy)&&a(x,z,D)})}),E=A+1,_=L)}),C}return b.length&&b.reduce(S),x}function r(y,b){let x={};function S(C,_,E,T,N){let I;t.range(_,E).forEach(A=>{I=C[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<T||L.order>N)&&a(x,R,I)})})}function k(C,_){let E=-1,T,N=0;return _.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(T=y.node(R[0]).order,S(_,N,A,E,T),N=A,E=T)}S(_,N,_.length,T,C.length)}),_}return b.length&&b.reduce(k),x}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(x=>y.node(x).dummy)}function a(y,b,x){if(b>x){let k=b;b=x,x=k}let S=y[b];S||(y[b]=S={}),S[x]=!0}function i(y,b,x){if(b>x){let S=b;b=x,x=S}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,S){let k={},C={},_={};return b.forEach(E=>{E.forEach((T,N)=>{k[T]=T,C[T]=T,_[T]=N})}),b.forEach(E=>{let T=-1;E.forEach(N=>{let I=S(N);if(I.length){I=I.sort((R,L)=>_[R]-_[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let D=I[R];C[N]===N&&T<_[D]&&!i(x,N,D)&&(C[D]=N,C[N]=k[N]=k[D],T=_[D])}}})}),{root:k,align:C}}function c(y,b,x,S,k){let C={},_=u(y,b,x,k),E=k?"borderLeft":"borderRight";function T(A,R){let L=_.nodes(),D=L.pop(),z={};for(;D;)z[D]?A(D):(z[D]=!0,L.push(D),L=L.concat(R(D))),D=L.pop()}function N(A){C[A]=_.inEdges(A).reduce((R,L)=>Math.max(R,C[L.v]+_.edge(L)),0)}function I(A){let R=_.outEdges(A).reduce((D,z)=>Math.min(D,C[z.w]-_.edge(z)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==E&&(C[A]=Math.max(C[A],R))}return T(N,_.predecessors.bind(_)),T(I,_.successors.bind(_)),Object.keys(S).forEach(A=>C[A]=C[x[A]]),C}function u(y,b,x,S){let k=new e,C=y.graph(),_=m(C.nodesep,C.edgesep,S);return b.forEach(E=>{let T;E.forEach(N=>{let I=x[N];if(k.setNode(I),T){var A=x[T],R=k.edge(A,I);k.setEdge(A,I,Math.max(_(y,N,T),R||0))}T=N})}),k}function d(y,b){return Object.values(b).reduce((x,S)=>{let k=Number.NEGATIVE_INFINITY,C=Number.POSITIVE_INFINITY;Object.entries(S).forEach(([E,T])=>{let N=g(y,E)/2;k=Math.max(T+N,k),C=Math.min(T-N,C)});const _=k-C;return _<x[0]&&(x=[_,S]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),S=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(C=>{["l","r"].forEach(_=>{let E=C+_,T=y[E];if(T===b)return;let N=Object.values(T),I=S-t.applyWithChunking(Math.min,N);_!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[E]=t.mapValues(T,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(x,S)=>{if(b)return y[b.toLowerCase()][S];{let k=Object.values(y).map(C=>C[S]).sort((C,_)=>C-_);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),S={},k;["u","d"].forEach(_=>{k=_==="u"?b:Object.values(b).reverse(),["l","r"].forEach(E=>{E==="r"&&(k=k.map(A=>Object.values(A).reverse()));let T=(_==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,T),I=c(y,k,N.root,N.align,E==="r");E==="r"&&(I=t.mapValues(I,A=>-A)),S[_+E]=I})});let C=d(y,S);return f(S,C),p(S,y.graph().align)}function m(y,b,x){return(S,k,C)=>{let _=S.node(k),E=S.node(C),T=0,N;if(T+=_.width/2,Object.hasOwn(_,"labelpos"))switch(_.labelpos.toLowerCase()){case"l":N=-_.width/2;break;case"r":N=_.width/2;break}if(N&&(T+=x?N:-N),N=0,T+=(_.dummy?b:y)/2,T+=(E.dummy?b:y)/2,T+=E.width/2,Object.hasOwn(E,"labelpos"))switch(E.labelpos.toLowerCase()){case"l":N=E.width/2;break;case"r":N=-E.width/2;break}return N&&(T+=x?N:-N),N=0,T}}function g(y,b){return y.node(b).width}return Ete}var Tte,A9e;function eWn(){if(A9e)return Tte;A9e=1;let e=Ll(),t=JHn().positionX;Tte=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 Tte}var jte,R9e;function tWn(){if(R9e)return jte;R9e=1;let e=MHn(),t=DHn(),n=zHn(),r=Ll().normalizeRanks,s=FHn(),a=Ll().removeEmptyRanks,i=BHn(),l=UHn(),c=qHn(),u=XHn(),d=eWn(),f=Ll(),p=Bg().Graph;jte=h;function h($,B){let Z=B&&B.debugTiming?f.time:f.notime;Z("layout",()=>{let K=Z(" buildLayoutGraph",()=>T($));Z(" runLayout",()=>m(K,Z,B)),Z(" updateInputGraph",()=>g($,K))})}function m($,B,Z){B(" makeSpaceForEdgeLabels",()=>N($)),B(" removeSelfEdges",()=>U($)),B(" acyclic",()=>e.run($)),B(" nestingGraph.run",()=>i.run($)),B(" rank",()=>n(f.asNonCompoundGraph($))),B(" injectEdgeLabelProxies",()=>I($)),B(" removeEmptyRanks",()=>a($)),B(" nestingGraph.cleanup",()=>i.cleanup($)),B(" normalizeRanks",()=>r($)),B(" assignRankMinMax",()=>A($)),B(" removeEdgeLabelProxies",()=>R($)),B(" normalize.run",()=>t.run($)),B(" parentDummyChains",()=>s($)),B(" addBorderSegments",()=>l($)),B(" order",()=>u($,Z)),B(" insertSelfEdges",()=>q($)),B(" adjustCoordinateSystem",()=>c.adjust($)),B(" position",()=>d($)),B(" positionSelfEdges",()=>M($)),B(" removeBorderNodes",()=>F($)),B(" normalize.undo",()=>t.undo($)),B(" fixupEdgeLabelCoords",()=>z($)),B(" undoCoordinateSystem",()=>c.undo($)),B(" translateGraph",()=>L($)),B(" assignNodeIntersects",()=>D($)),B(" reversePoints",()=>H($)),B(" acyclic.undo",()=>e.undo($))}function g($,B){$.nodes().forEach(Z=>{let K=$.node(Z),ne=B.node(Z);K&&(K.x=ne.x,K.y=ne.y,K.rank=ne.rank,B.children(Z).length&&(K.width=ne.width,K.height=ne.height))}),$.edges().forEach(Z=>{let K=$.edge(Z),ne=B.edge(Z);K.points=ne.points,Object.hasOwn(ne,"x")&&(K.x=ne.x,K.y=ne.y)}),$.graph().width=B.graph().width,$.graph().height=B.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},x=["acyclicer","ranker","rankdir","align"],S=["width","height","rank"],k={width:0,height:0},C=["minlen","weight","width","height","labeloffset"],_={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},E=["labelpos"];function T($){let B=new p({multigraph:!0,compound:!0}),Z=V($.graph());return B.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),$.nodes().forEach(K=>{let ne=V($.node(K));const ee=G(ne,S);Object.keys(k).forEach(J=>{ee[J]===void 0&&(ee[J]=k[J])}),B.setNode(K,ee),B.setParent(K,$.parent(K))}),$.edges().forEach(K=>{let ne=V($.edge(K));B.setEdge(K,Object.assign({},_,G(ne,C),f.pick(ne,E)))}),B}function N($){let B=$.graph();B.ranksep/=2,$.edges().forEach(Z=>{let K=$.edge(Z);K.minlen*=2,K.labelpos.toLowerCase()!=="c"&&(B.rankdir==="TB"||B.rankdir==="BT"?K.width+=K.labeloffset:K.height+=K.labeloffset)})}function I($){$.edges().forEach(B=>{let Z=$.edge(B);if(Z.width&&Z.height){let K=$.node(B.v),ee={rank:($.node(B.w).rank-K.rank)/2+K.rank,e:B};f.addDummyNode($,"edge-proxy",ee,"_ep")}})}function A($){let B=0;$.nodes().forEach(Z=>{let K=$.node(Z);K.borderTop&&(K.minRank=$.node(K.borderTop).rank,K.maxRank=$.node(K.borderBottom).rank,B=Math.max(B,K.maxRank))}),$.graph().maxRank=B}function R($){$.nodes().forEach(B=>{let Z=$.node(B);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(B))})}function L($){let B=Number.POSITIVE_INFINITY,Z=0,K=Number.POSITIVE_INFINITY,ne=0,ee=$.graph(),J=ee.marginx||0,ae=ee.marginy||0;function fe(Y){let re=Y.x,le=Y.y,ue=Y.width,oe=Y.height;B=Math.min(B,re-ue/2),Z=Math.max(Z,re+ue/2),K=Math.min(K,le-oe/2),ne=Math.max(ne,le+oe/2)}$.nodes().forEach(Y=>fe($.node(Y))),$.edges().forEach(Y=>{let re=$.edge(Y);Object.hasOwn(re,"x")&&fe(re)}),B-=J,K-=ae,$.nodes().forEach(Y=>{let re=$.node(Y);re.x-=B,re.y-=K}),$.edges().forEach(Y=>{let re=$.edge(Y);re.points.forEach(le=>{le.x-=B,le.y-=K}),Object.hasOwn(re,"x")&&(re.x-=B),Object.hasOwn(re,"y")&&(re.y-=K)}),ee.width=Z-B+J,ee.height=ne-K+ae}function D($){$.edges().forEach(B=>{let Z=$.edge(B),K=$.node(B.v),ne=$.node(B.w),ee,J;Z.points?(ee=Z.points[0],J=Z.points[Z.points.length-1]):(Z.points=[],ee=ne,J=K),Z.points.unshift(f.intersectRect(K,ee)),Z.points.push(f.intersectRect(ne,J))})}function z($){$.edges().forEach(B=>{let Z=$.edge(B);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(B=>{let Z=$.edge(B);Z.reversed&&Z.points.reverse()})}function F($){$.nodes().forEach(B=>{if($.children(B).length){let Z=$.node(B),K=$.node(Z.borderTop),ne=$.node(Z.borderBottom),ee=$.node(Z.borderLeft[Z.borderLeft.length-1]),J=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(J.x-ee.x),Z.height=Math.abs(ne.y-K.y),Z.x=ee.x+Z.width/2,Z.y=K.y+Z.height/2}}),$.nodes().forEach(B=>{$.node(B).dummy==="border"&&$.removeNode(B)})}function U($){$.edges().forEach(B=>{if(B.v===B.w){var Z=$.node(B.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:B,label:$.edge(B)}),$.removeEdge(B)}})}function q($){var B=f.buildLayerMatrix($);B.forEach(Z=>{var K=0;Z.forEach((ne,ee)=>{var J=$.node(ne);J.order=ee+K,(J.selfEdges||[]).forEach(ae=>{f.addDummyNode($,"selfedge",{width:ae.label.width,height:ae.label.height,rank:J.rank,order:ee+ ++K,e:ae.e,label:ae.label},"_se")}),delete J.selfEdges})})}function M($){$.nodes().forEach(B=>{var Z=$.node(B);if(Z.dummy==="selfedge"){var K=$.node(Z.e.v),ne=K.x+K.width/2,ee=K.y,J=Z.x-ne,ae=K.height/2;$.setEdge(Z.e,Z.label),$.removeNode(B),Z.label.points=[{x:ne+2*J/3,y:ee-ae},{x:ne+5*J/6,y:ee-ae},{x:ne+J,y:ee},{x:ne+5*J/6,y:ee+ae},{x:ne+2*J/3,y:ee+ae}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,B){return f.mapValues(f.pick($,B),Number)}function V($){var B={};return $&&Object.entries($).forEach(([Z,K])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),B[Z]=K}),B}return jte}var Nte,P9e;function nWn(){if(P9e)return Nte;P9e=1;let e=Ll(),t=Bg().Graph;Nte={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 Nte}var Ite,$9e;function rWn(){return $9e||($9e=1,Ite="1.1.8"),Ite}var Ate,M9e;function sWn(){return M9e||(M9e=1,Ate={graphlib:Bg(),layout:tWn(),debug:nWn(),util:{time:Ll().time,notime:Ll().notime},version:rWn()}),Ate}var aWn=sWn();const D9e=Ul(aWn);function Hl(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=Hl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var iWn={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 V8(n)}function V8(e){this._=e}function oWn(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}})}V8.prototype=GH.prototype={constructor:V8,on:function(e,t){var n=this._,r=oWn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=lWn(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]=L9e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=L9e(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 V8(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 lWn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function L9e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=iWn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Lge="http://www.w3.org/1999/xhtml";const z9e={svg:"http://www.w3.org/2000/svg",xhtml:Lge,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function QH(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),z9e.hasOwnProperty(t)?{space:z9e[t],local:e}:e}function cWn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Lge&&t.documentElement.namespaceURI===Lge?t.createElement(e):t.createElementNS(n,e)}}function uWn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function GSt(e){var t=QH(e);return(t.local?uWn:cWn)(t)}function dWn(){}function Dke(e){return e==null?dWn:function(){return this.querySelector(e)}}function fWn(e){typeof e!="function"&&(e=Dke(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 Qp(r,this._parents)}function pWn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function hWn(){return[]}function QSt(e){return e==null?hWn:function(){return this.querySelectorAll(e)}}function mWn(e){return function(){return pWn(e.apply(this,arguments))}}function gWn(e){typeof e=="function"?e=mWn(e):e=QSt(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 Qp(r,s)}function YSt(e){return function(){return this.matches(e)}}function KSt(e){return function(t){return t.matches(e)}}var vWn=Array.prototype.find;function yWn(e){return function(){return vWn.call(this.children,e)}}function bWn(){return this.firstElementChild}function xWn(e){return this.select(e==null?bWn:yWn(typeof e=="function"?e:KSt(e)))}var wWn=Array.prototype.filter;function SWn(){return Array.from(this.children)}function kWn(e){return function(){return wWn.call(this.children,e)}}function OWn(e){return this.selectAll(e==null?SWn:kWn(typeof e=="function"?e:KSt(e)))}function _Wn(e){typeof e!="function"&&(e=YSt(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 Qp(r,this._parents)}function XSt(e){return new Array(e.length)}function CWn(){return new Qp(this._enter||this._groups.map(XSt),this._parents)}function zB(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}zB.prototype={constructor:zB,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 EWn(e){return function(){return e}}function TWn(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 zB(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function jWn(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 zB(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function NWn(e){return e.__data__}function IWn(e,t){if(!arguments.length)return Array.from(this,NWn);var n=t?jWn:TWn,r=this._parents,s=this._groups;typeof e!="function"&&(e=EWn(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=AWn(e.call(d,d&&d.__data__,u,r)),m=h.length,g=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,g,y,b,h,t);for(var x=0,S=0,k,C;x<m;++x)if(k=g[x]){for(x>=S&&(S=x+1);!(C=y[S])&&++S<m;);k._next=C||null}}return i=new Qp(i,r),i._enter=l,i._exit=c,i}function AWn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function RWn(){return new Qp(this._exit||this._groups.map(XSt),this._parents)}function PWn(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 $Wn(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 Qp(l,this._parents)}function MWn(){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 DWn(e){e||(e=LWn);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 Qp(s,this._parents).order()}function LWn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function zWn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function FWn(){return Array.from(this)}function BWn(){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 UWn(){let e=0;for(const t of this)++e;return e}function qWn(){return!this.node()}function VWn(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 HWn(e){return function(){this.removeAttribute(e)}}function WWn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function ZWn(e,t){return function(){this.setAttribute(e,t)}}function GWn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function QWn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function YWn(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 KWn(e,t){var n=QH(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?WWn:HWn:typeof t=="function"?n.local?YWn:QWn:n.local?GWn:ZWn)(n,t))}function JSt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function XWn(e){return function(){this.style.removeProperty(e)}}function JWn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function eZn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function tZn(e,t,n){return arguments.length>1?this.each((t==null?XWn:typeof t=="function"?eZn:JWn)(e,t,n??"")):Yj(this.node(),e)}function Yj(e,t){return e.style.getPropertyValue(t)||JSt(e).getComputedStyle(e,null).getPropertyValue(t)}function nZn(e){return function(){delete this[e]}}function rZn(e,t){return function(){this[e]=t}}function sZn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function aZn(e,t){return arguments.length>1?this.each((t==null?nZn:typeof t=="function"?sZn:rZn)(e,t)):this.node()[e]}function ekt(e){return e.trim().split(/^|\s+/)}function Lke(e){return e.classList||new tkt(e)}function tkt(e){this._node=e,this._names=ekt(e.getAttribute("class")||"")}tkt.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 nkt(e,t){for(var n=Lke(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function rkt(e,t){for(var n=Lke(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function iZn(e){return function(){nkt(this,e)}}function oZn(e){return function(){rkt(this,e)}}function lZn(e,t){return function(){(t.apply(this,arguments)?nkt:rkt)(this,e)}}function cZn(e,t){var n=ekt(e+"");if(arguments.length<2){for(var r=Lke(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?lZn:t?iZn:oZn)(n,t))}function uZn(){this.textContent=""}function dZn(e){return function(){this.textContent=e}}function fZn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function pZn(e){return arguments.length?this.each(e==null?uZn:(typeof e=="function"?fZn:dZn)(e)):this.node().textContent}function hZn(){this.innerHTML=""}function mZn(e){return function(){this.innerHTML=e}}function gZn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function vZn(e){return arguments.length?this.each(e==null?hZn:(typeof e=="function"?gZn:mZn)(e)):this.node().innerHTML}function yZn(){this.nextSibling&&this.parentNode.appendChild(this)}function bZn(){return this.each(yZn)}function xZn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function wZn(){return this.each(xZn)}function SZn(e){var t=typeof e=="function"?e:GSt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function kZn(){return null}function OZn(e,t){var n=typeof e=="function"?e:GSt(e),r=t==null?kZn:typeof t=="function"?t:Dke(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function _Zn(){var e=this.parentNode;e&&e.removeChild(this)}function CZn(){return this.each(_Zn)}function EZn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function TZn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function jZn(e){return this.select(e?TZn:EZn)}function NZn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function IZn(e){return function(t){e.call(this,t,this.__data__)}}function AZn(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 RZn(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 PZn(e,t,n){return function(){var r=this.__on,s,a=IZn(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 $Zn(e,t,n){var r=AZn(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?PZn:RZn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function skt(e,t,n){var r=JSt(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 MZn(e,t){return function(){return skt(this,e,t)}}function DZn(e,t){return function(){return skt(this,e,t.apply(this,arguments))}}function LZn(e,t){return this.each((typeof t=="function"?DZn:MZn)(e,t))}function*zZn(){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 akt=[null];function Qp(e,t){this._groups=e,this._parents=t}function Z3(){return new Qp([[document.documentElement]],akt)}function FZn(){return this}Qp.prototype=Z3.prototype={constructor:Qp,select:fWn,selectAll:gWn,selectChild:xWn,selectChildren:OWn,filter:_Wn,data:IWn,enter:CWn,exit:RWn,join:PWn,merge:$Wn,selection:FZn,order:MWn,sort:DWn,call:zWn,nodes:FWn,node:BWn,size:UWn,empty:qWn,each:VWn,attr:KWn,style:tZn,property:aZn,classed:cZn,text:pZn,html:vZn,raise:bZn,lower:wZn,append:SZn,insert:OZn,remove:CZn,clone:jZn,datum:NZn,on:$Zn,dispatch:LZn,[Symbol.iterator]:zZn};function Cp(e){return typeof e=="string"?new Qp([[document.querySelector(e)]],[document.documentElement]):new Qp([[e]],akt)}function BZn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function lg(e,t){if(e=BZn(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 UZn={passive:!1},$M={capture:!0,passive:!1};function Rte(e){e.stopImmediatePropagation()}function XT(e){e.preventDefault(),e.stopImmediatePropagation()}function ikt(e){var t=e.document.documentElement,n=Cp(e).on("dragstart.drag",XT,$M);"onselectstart"in t?n.on("selectstart.drag",XT,$M):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function okt(e,t){var n=e.document.documentElement,r=Cp(e).on("dragstart.drag",null);t&&(r.on("click.drag",XT,$M),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 uz=e=>()=>e;function zge(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}})}zge.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function qZn(e){return!e.ctrlKey&&!e.button}function VZn(){return this.parentNode}function HZn(e,t){return t??{x:e.x,y:e.y}}function WZn(){return navigator.maxTouchPoints||"ontouchstart"in this}function lkt(){var e=qZn,t=VZn,n=HZn,r=WZn,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,UZn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,C){if(!(d||!e.call(this,k,C))){var _=S(this,t.call(this,k,C),k,C,"mouse");_&&(Cp(k.view).on("mousemove.drag",m,$M).on("mouseup.drag",g,$M),ikt(k.view),Rte(k),u=!1,l=k.clientX,c=k.clientY,_("start",k))}}function m(k){if(XT(k),!u){var C=k.clientX-l,_=k.clientY-c;u=C*C+_*_>f}s.mouse("drag",k)}function g(k){Cp(k.view).on("mousemove.drag mouseup.drag",null),okt(k.view,u),XT(k),s.mouse("end",k)}function y(k,C){if(e.call(this,k,C)){var _=k.changedTouches,E=t.call(this,k,C),T=_.length,N,I;for(N=0;N<T;++N)(I=S(this,E,k,C,_[N].identifier,_[N]))&&(Rte(k),I("start",k,_[N]))}}function b(k){var C=k.changedTouches,_=C.length,E,T;for(E=0;E<_;++E)(T=s[C[E].identifier])&&(XT(k),T("drag",k,C[E]))}function x(k){var C=k.changedTouches,_=C.length,E,T;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),E=0;E<_;++E)(T=s[C[E].identifier])&&(Rte(k),T("end",k,C[E]))}function S(k,C,_,E,T,N){var I=a.copy(),A=lg(N||_,C),R,L,D;if((D=n.call(k,new zge("beforestart",{sourceEvent:_,target:p,identifier:T,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),E))!=null)return R=D.x-A[0]||0,L=D.y-A[1]||0,function z(H,F,U){var q=A,M;switch(H){case"start":s[T]=z,M=i++;break;case"end":delete s[T],--i;case"drag":A=lg(U||F,C),M=i;break}I.call(H,k,new zge(H,{sourceEvent:F,subject:D,target:p,identifier:T,active:M,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:uz(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:uz(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:uz(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:uz(!!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 zke(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function ckt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function G3(){}var MM=.7,FB=1/MM,JT="\\s*([+-]?\\d+)\\s*",DM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",oy="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",ZZn=/^#([0-9a-f]{3,8})$/,GZn=new RegExp(`^rgb\\(${JT},${JT},${JT}\\)$`),QZn=new RegExp(`^rgb\\(${oy},${oy},${oy}\\)$`),YZn=new RegExp(`^rgba\\(${JT},${JT},${JT},${DM}\\)$`),KZn=new RegExp(`^rgba\\(${oy},${oy},${oy},${DM}\\)$`),XZn=new RegExp(`^hsl\\(${DM},${oy},${oy}\\)$`),JZn=new RegExp(`^hsla\\(${DM},${oy},${oy},${DM}\\)$`),F9e={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};zke(G3,YO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:B9e,formatHex:B9e,formatHex8:eGn,formatHsl:tGn,formatRgb:U9e,toString:U9e});function B9e(){return this.rgb().formatHex()}function eGn(){return this.rgb().formatHex8()}function tGn(){return ukt(this).formatHsl()}function U9e(){return this.rgb().formatRgb()}function YO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=ZZn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?q9e(t):n===3?new bf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?dz(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?dz(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=GZn.exec(e))?new bf(t[1],t[2],t[3],1):(t=QZn.exec(e))?new bf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=YZn.exec(e))?dz(t[1],t[2],t[3],t[4]):(t=KZn.exec(e))?dz(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=XZn.exec(e))?W9e(t[1],t[2]/100,t[3]/100,1):(t=JZn.exec(e))?W9e(t[1],t[2]/100,t[3]/100,t[4]):F9e.hasOwnProperty(e)?q9e(F9e[e]):e==="transparent"?new bf(NaN,NaN,NaN,0):null}function q9e(e){return new bf(e>>16&255,e>>8&255,e&255,1)}function dz(e,t,n,r){return r<=0&&(e=t=n=NaN),new bf(e,t,n,r)}function nGn(e){return e instanceof G3||(e=YO(e)),e?(e=e.rgb(),new bf(e.r,e.g,e.b,e.opacity)):new bf}function Fge(e,t,n,r){return arguments.length===1?nGn(e):new bf(e,t,n,r??1)}function bf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}zke(bf,Fge,ckt(G3,{brighter(e){return e=e==null?FB:Math.pow(FB,e),new bf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?MM:Math.pow(MM,e),new bf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new bf(aO(this.r),aO(this.g),aO(this.b),BB(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:V9e,formatHex:V9e,formatHex8:rGn,formatRgb:H9e,toString:H9e}));function V9e(){return`#${Bk(this.r)}${Bk(this.g)}${Bk(this.b)}`}function rGn(){return`#${Bk(this.r)}${Bk(this.g)}${Bk(this.b)}${Bk((isNaN(this.opacity)?1:this.opacity)*255)}`}function H9e(){const e=BB(this.opacity);return`${e===1?"rgb(":"rgba("}${aO(this.r)}, ${aO(this.g)}, ${aO(this.b)}${e===1?")":`, ${e})`}`}function BB(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function aO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Bk(e){return e=aO(e),(e<16?"0":"")+e.toString(16)}function W9e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new mg(e,t,n,r)}function ukt(e){if(e instanceof mg)return new mg(e.h,e.s,e.l,e.opacity);if(e instanceof G3||(e=YO(e)),!e)return new mg;if(e instanceof mg)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 mg(i,l,c,e.opacity)}function sGn(e,t,n,r){return arguments.length===1?ukt(e):new mg(e,t,n,r??1)}function mg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}zke(mg,sGn,ckt(G3,{brighter(e){return e=e==null?FB:Math.pow(FB,e),new mg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?MM:Math.pow(MM,e),new mg(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 bf(Pte(e>=240?e-240:e+120,s,r),Pte(e,s,r),Pte(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new mg(Z9e(this.h),fz(this.s),fz(this.l),BB(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=BB(this.opacity);return`${e===1?"hsl(":"hsla("}${Z9e(this.h)}, ${fz(this.s)*100}%, ${fz(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Z9e(e){return e=(e||0)%360,e<0?e+360:e}function fz(e){return Math.max(0,Math.min(1,e||0))}function Pte(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 Fke=e=>()=>e;function aGn(e,t){return function(n){return e+n*t}}function iGn(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 oGn(e){return(e=+e)==1?dkt:function(t,n){return n-t?iGn(t,n,e):Fke(isNaN(t)?n:t)}}function dkt(e,t){var n=t-e;return n?aGn(e,n):Fke(isNaN(e)?t:e)}const UB=(function e(t){var n=oGn(t);function r(s,a){var i=n((s=Fge(s)).r,(a=Fge(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=dkt(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 lGn(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 cGn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function uGn(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]=yx(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 dGn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function ug(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function fGn(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]=yx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Bge=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,$te=new RegExp(Bge.source,"g");function pGn(e){return function(){return e}}function hGn(e){return function(t){return e(t)+""}}function fkt(e,t){var n=Bge.lastIndex=$te.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Bge.exec(e))&&(s=$te.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:ug(r,s)})),n=$te.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?hGn(c[0].x):pGn(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 yx(e,t){var n=typeof t,r;return t==null||n==="boolean"?Fke(t):(n==="number"?ug:n==="string"?(r=YO(t))?(t=r,UB):fkt:t instanceof YO?UB:t instanceof Date?dGn:cGn(t)?lGn:Array.isArray(t)?uGn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?fGn:ug)(e,t)}function Bke(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var G9e=180/Math.PI,Uge={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function pkt(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)*G9e,skewX:Math.atan(c)*G9e,scaleX:i,scaleY:l}}var pz;function mGn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Uge:pkt(t.a,t.b,t.c,t.d,t.e,t.f)}function gGn(e){return e==null||(pz||(pz=document.createElementNS("http://www.w3.org/2000/svg","g")),pz.setAttribute("transform",e),!(e=pz.transform.baseVal.consolidate()))?Uge:(e=e.matrix,pkt(e.a,e.b,e.c,e.d,e.e,e.f))}function hkt(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 g=h.push("translate(",null,t,null,n);m.push({i:g-4,x:ug(u,f)},{i:g-2,x:ug(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:ug(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:ug(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var g=h.push(s(h)+"scale(",null,",",null,")");m.push({i:g-4,x:ug(u,f)},{i:g-2,x:ug(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,g=p.length,y;++m<g;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var vGn=hkt(mGn,"px, ","px)","deg)"),yGn=hkt(gGn,", ",")",")"),bGn=1e-12;function Q9e(e){return((e=Math.exp(e))+1/e)/2}function xGn(e){return((e=Math.exp(e))-1/e)/2}function wGn(e){return((e=Math.exp(2*e))-1)/(e+1)}const H8=(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,g=h*h+m*m,y,b;if(g<bGn)b=Math.log(p/u)/t,y=function(E){return[l+E*h,c+E*m,u*Math.exp(t*E*b)]};else{var x=Math.sqrt(g),S=(p*p-u*u+r*g)/(2*u*n*x),k=(p*p-u*u-r*g)/(2*p*n*x),C=Math.log(Math.sqrt(S*S+1)-S),_=Math.log(Math.sqrt(k*k+1)-k);b=(_-C)/t,y=function(E){var T=E*b,N=Q9e(C),I=u/(n*x)*(N*wGn(t*T+C)-xGn(C));return[l+I*h,c+I*m,u*N/Q9e(t*T+C)]}}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 SGn(e,t){t===void 0&&(t=e,e=yx);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 Kj=0,VP=0,jR=0,mkt=1e3,qB,HP,VB=0,KO=0,YH=0,LM=typeof performance=="object"&&performance.now?performance:Date,gkt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Uke(){return KO||(gkt(kGn),KO=LM.now()+YH)}function kGn(){KO=0}function HB(){this._call=this._time=this._next=null}HB.prototype=vkt.prototype={constructor:HB,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Uke():+n)+(t==null?0:+t),!this._next&&HP!==this&&(HP?HP._next=this:qB=this,HP=this),this._call=e,this._time=n,qge()},stop:function(){this._call&&(this._call=null,this._time=1/0,qge())}};function vkt(e,t,n){var r=new HB;return r.restart(e,t,n),r}function OGn(){Uke(),++Kj;for(var e=qB,t;e;)(t=KO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Kj}function Y9e(){KO=(VB=LM.now())+YH,Kj=VP=0;try{OGn()}finally{Kj=0,CGn(),KO=0}}function _Gn(){var e=LM.now(),t=e-VB;t>mkt&&(YH-=t,VB=e)}function CGn(){for(var e,t=qB,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:qB=n);HP=e,qge(r)}function qge(e){if(!Kj){VP&&(VP=clearTimeout(VP));var t=e-KO;t>24?(e<1/0&&(VP=setTimeout(Y9e,e-LM.now()-YH)),jR&&(jR=clearInterval(jR))):(jR||(VB=LM.now(),jR=setInterval(_Gn,mkt)),Kj=1,gkt(Y9e))}}function K9e(e,t,n){var r=new HB;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var EGn=GH("start","end","cancel","interrupt"),TGn=[],ykt=0,X9e=1,Vge=2,W8=3,J9e=4,Hge=5,Z8=6;function KH(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;jGn(e,n,{name:t,index:r,group:s,on:EGn,tween:TGn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:ykt})}function qke(e,t){var n=Yg(e,t);if(n.state>ykt)throw new Error("too late; already scheduled");return n}function Wy(e,t){var n=Yg(e,t);if(n.state>W8)throw new Error("too late; already running");return n}function Yg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function jGn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=vkt(a,0,n.time);function a(u){n.state=X9e,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!==X9e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===W8)return K9e(i);h.state===J9e?(h.state=Z8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=Z8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(K9e(function(){n.state===W8&&(n.state=J9e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Vge,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Vge){for(n.state=W8,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=Hge,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===Hge&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=Z8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function G8(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>Vge&&r.state<Hge,r.state=Z8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function NGn(e){return this.each(function(){G8(this,e)})}function IGn(e,t){var n,r;return function(){var s=Wy(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 AGn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Wy(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 RGn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Yg(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?IGn:AGn)(n,e,t))}function Vke(e,t,n){var r=e._id;return e.each(function(){var s=Wy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Yg(s,r).value[t]}}function bkt(e,t){var n;return(typeof t=="number"?ug:t instanceof YO?UB:(n=YO(t))?(t=n,UB):fkt)(e,t)}function PGn(e){return function(){this.removeAttribute(e)}}function $Gn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function MGn(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 DGn(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 LGn(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 zGn(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 FGn(e,t){var n=QH(e),r=n==="transform"?yGn:bkt;return this.attrTween(e,typeof t=="function"?(n.local?zGn:LGn)(n,r,Vke(this,"attr."+e,t)):t==null?(n.local?$Gn:PGn)(n):(n.local?DGn:MGn)(n,r,t))}function BGn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function UGn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function qGn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&UGn(e,a)),n}return s._value=t,s}function VGn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&BGn(e,a)),n}return s._value=t,s}function HGn(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=QH(e);return this.tween(n,(r.local?qGn:VGn)(r,t))}function WGn(e,t){return function(){qke(this,e).delay=+t.apply(this,arguments)}}function ZGn(e,t){return t=+t,function(){qke(this,e).delay=t}}function GGn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?WGn:ZGn)(t,e)):Yg(this.node(),t).delay}function QGn(e,t){return function(){Wy(this,e).duration=+t.apply(this,arguments)}}function YGn(e,t){return t=+t,function(){Wy(this,e).duration=t}}function KGn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?QGn:YGn)(t,e)):Yg(this.node(),t).duration}function XGn(e,t){if(typeof t!="function")throw new Error;return function(){Wy(this,e).ease=t}}function JGn(e){var t=this._id;return arguments.length?this.each(XGn(t,e)):Yg(this.node(),t).ease}function eQn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Wy(this,e).ease=n}}function tQn(e){if(typeof e!="function")throw new Error;return this.each(eQn(this._id,e))}function nQn(e){typeof e!="function"&&(e=YSt(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 zx(r,this._parents,this._name,this._id)}function rQn(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 zx(i,this._parents,this._name,this._id)}function sQn(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 aQn(e,t,n){var r,s,a=sQn(t)?qke:Wy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function iQn(e,t){var n=this._id;return arguments.length<2?Yg(this.node(),n).on.on(e):this.each(aQn(n,e,t))}function oQn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function lQn(){return this.on("end.remove",oQn(this._id))}function cQn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Dke(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,KH(u[p],t,n,p,u,Yg(d,n)));return new zx(a,this._parents,t,n)}function uQn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=QSt(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=Yg(d,n),g=0,y=p.length;g<y;++g)(h=p[g])&&KH(h,t,n,g,p,m);a.push(p),i.push(d)}return new zx(a,i,t,n)}var dQn=Z3.prototype.constructor;function fQn(){return new dQn(this._groups,this._parents)}function pQn(e,t){var n,r,s;return function(){var a=Yj(this,e),i=(this.style.removeProperty(e),Yj(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function xkt(e){return function(){this.style.removeProperty(e)}}function hQn(e,t,n){var r,s=n+"",a;return function(){var i=Yj(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function mQn(e,t,n){var r,s,a;return function(){var i=Yj(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),Yj(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function gQn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Wy(this,e),u=c.on,d=c.value[a]==null?l||(l=xkt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function vQn(e,t,n){var r=(e+="")=="transform"?vGn:bkt;return t==null?this.styleTween(e,pQn(e,r)).on("end.style."+e,xkt(e)):typeof t=="function"?this.styleTween(e,mQn(e,r,Vke(this,"style."+e,t))).each(gQn(this._id,e)):this.styleTween(e,hQn(e,r,t),n).on("end.style."+e,null)}function yQn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function bQn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&yQn(e,i,n)),r}return a._value=t,a}function xQn(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,bQn(e,t,n??""))}function wQn(e){return function(){this.textContent=e}}function SQn(e){return function(){var t=e(this);this.textContent=t??""}}function kQn(e){return this.tween("text",typeof e=="function"?SQn(Vke(this,"text",e)):wQn(e==null?"":e+""))}function OQn(e){return function(t){this.textContent=e.call(this,t)}}function _Qn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&OQn(s)),t}return r._value=e,r}function CQn(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,_Qn(e))}function EQn(){for(var e=this._name,t=this._id,n=wkt(),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=Yg(c,t);KH(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new zx(r,this._parents,e,n)}function TQn(){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=Wy(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 jQn=0;function zx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function wkt(){return++jQn}var _b=Z3.prototype;zx.prototype={constructor:zx,select:cQn,selectAll:uQn,selectChild:_b.selectChild,selectChildren:_b.selectChildren,filter:nQn,merge:rQn,selection:fQn,transition:EQn,call:_b.call,nodes:_b.nodes,node:_b.node,size:_b.size,empty:_b.empty,each:_b.each,on:iQn,attr:FGn,attrTween:HGn,style:vQn,styleTween:xQn,text:kQn,textTween:CQn,remove:lQn,tween:RGn,delay:GGn,duration:KGn,ease:JGn,easeVarying:tQn,end:TQn,[Symbol.iterator]:_b[Symbol.iterator]};function NQn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var IQn={time:null,delay:0,duration:250,ease:NQn};function AQn(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 RQn(e){var t,n;e instanceof zx?(t=e._id,e=e._name):(t=wkt(),(n=IQn).time=Uke(),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])&&KH(c,e,t,u,i,n||AQn(c,t));return new zx(r,this._parents,e,t)}Z3.prototype.interrupt=NGn;Z3.prototype.transition=RQn;const hz=e=>()=>e;function PQn(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 ox(e,t,n){this.k=e,this.x=t,this.y=n}ox.prototype={constructor:ox,scale:function(e){return e===1?this:new ox(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new ox(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 ox(1,0,0);Skt.prototype=ox.prototype;function Skt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return XH;return e.__zoom}function Mte(e){e.stopImmediatePropagation()}function NR(e){e.preventDefault(),e.stopImmediatePropagation()}function $Qn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function MQn(){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 e7e(){return this.__zoom||XH}function DQn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function LQn(){return navigator.maxTouchPoints||"ontouchstart"in this}function zQn(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 kkt(){var e=$Qn,t=MQn,n=zQn,r=DQn,s=LQn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=H8,u=GH("start","zoom","end"),d,f,p,h=500,m=150,g=0,y=10;function b(D){D.property("__zoom",e7e).on("wheel.zoom",T,{passive:!1}).on("mousedown.zoom",N).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(D,z,H,F){var U=D.selection?D.selection():D;U.property("__zoom",e7e),D!==U?C(D,z,H,F):U.interrupt().each(function(){_(this,arguments).event(F).start().zoom(null,typeof z=="function"?z.apply(this,arguments):z).end()})},b.scaleBy=function(D,z,H,F){b.scaleTo(D,function(){var U=this.__zoom.k,q=typeof z=="function"?z.apply(this,arguments):z;return U*q},H,F)},b.scaleTo=function(D,z,H,F){b.transform(D,function(){var U=t.apply(this,arguments),q=this.__zoom,M=H==null?k(U):typeof H=="function"?H.apply(this,arguments):H,G=q.invert(M),V=typeof z=="function"?z.apply(this,arguments):z;return n(S(x(q,V),M,G),U,i)},H,F)},b.translateBy=function(D,z,H,F){b.transform(D,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(D,z,H,F,U){b.transform(D,function(){var q=t.apply(this,arguments),M=this.__zoom,G=F==null?k(q):typeof F=="function"?F.apply(this,arguments):F;return n(XH.translate(G[0],G[1]).scale(M.k).translate(typeof z=="function"?-z.apply(this,arguments):-z,typeof H=="function"?-H.apply(this,arguments):-H),q,i)},F,U)};function x(D,z){return z=Math.max(a[0],Math.min(a[1],z)),z===D.k?D:new ox(z,D.x,D.y)}function S(D,z,H){var F=z[0]-H[0]*D.k,U=z[1]-H[1]*D.k;return F===D.x&&U===D.y?D:new ox(D.k,F,U)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function C(D,z,H,F){D.on("start.zoom",function(){_(this,arguments).event(F).start()}).on("interrupt.zoom end.zoom",function(){_(this,arguments).event(F).end()}).tween("zoom",function(){var U=this,q=arguments,M=_(U,q).event(F),G=t.apply(U,q),V=H==null?k(G):typeof H=="function"?H.apply(U,q):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),B=U.__zoom,Z=typeof z=="function"?z.apply(U,q):z,K=c(B.invert(V).concat($/B.k),Z.invert(V).concat($/Z.k));return function(ne){if(ne===1)ne=Z;else{var ee=K(ne),J=$/ee[2];ne=new ox(J,V[0]-ee[0]*J,V[1]-ee[1]*J)}M.zoom(null,ne)}})}function _(D,z,H){return!H&&D.__zooming||new E(D,z)}function E(D,z){this.that=D,this.args=z,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,z),this.taps=0}E.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,z){return this.mouse&&D!=="mouse"&&(this.mouse[1]=z.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=z.invert(this.touch0[0])),this.touch1&&D!=="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(D){var z=Cp(this.that).datum();u.call(D,this.that,new PQn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),z)}};function T(D,...z){if(!e.apply(this,arguments))return;var H=_(this,z).event(D),F=this.__zoom,U=Math.max(a[0],Math.min(a[1],F.k*Math.pow(2,r.apply(this,arguments)))),q=lg(D);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===U)return;H.mouse=[q,F.invert(q)],G8(this),H.start()}NR(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(S(x(F,U),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...z){if(p||!e.apply(this,arguments))return;var H=D.currentTarget,F=_(this,z,!0).event(D),U=Cp(D.view).on("mousemove.zoom",V,!0).on("mouseup.zoom",$,!0),q=lg(D,H),M=D.clientX,G=D.clientY;ikt(D.view),Mte(D),F.mouse=[q,this.__zoom.invert(q)],G8(this),F.start();function V(B){if(NR(B),!F.moved){var Z=B.clientX-M,K=B.clientY-G;F.moved=Z*Z+K*K>g}F.event(B).zoom("mouse",n(S(F.that.__zoom,F.mouse[0]=lg(B,H),F.mouse[1]),F.extent,i))}function $(B){U.on("mousemove.zoom mouseup.zoom",null),okt(B.view,F.moved),NR(B),F.event(B).end()}}function I(D,...z){if(e.apply(this,arguments)){var H=this.__zoom,F=lg(D.changedTouches?D.changedTouches[0]:D,this),U=H.invert(F),q=H.k*(D.shiftKey?.5:2),M=n(S(x(H,q),F,U),t.apply(this,z),i);NR(D),l>0?Cp(this).transition().duration(l).call(C,M,F,D):Cp(this).call(b.transform,M,F,D)}}function A(D,...z){if(e.apply(this,arguments)){var H=D.touches,F=H.length,U=_(this,z,D.changedTouches.length===F).event(D),q,M,G,V;for(Mte(D),M=0;M<F;++M)G=H[M],V=lg(G,this),V=[V,this.__zoom.invert(V),G.identifier],U.touch0?!U.touch1&&U.touch0[2]!==V[2]&&(U.touch1=V,U.taps=0):(U.touch0=V,q=!0,U.taps=1+!!d);d&&(d=clearTimeout(d)),q&&(U.taps<2&&(f=V[0],d=setTimeout(function(){d=null},h)),G8(this),U.start())}}function R(D,...z){if(this.__zooming){var H=_(this,z).event(D),F=D.changedTouches,U=F.length,q,M,G,V;for(NR(D),q=0;q<U;++q)M=F[q],G=lg(M,this),H.touch0&&H.touch0[2]===M.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===M.identifier&&(H.touch1[0]=G);if(M=H.that.__zoom,H.touch1){var $=H.touch0[0],B=H.touch0[1],Z=H.touch1[0],K=H.touch1[1],ne=(ne=Z[0]-$[0])*ne+(ne=Z[1]-$[1])*ne,ee=(ee=K[0]-B[0])*ee+(ee=K[1]-B[1])*ee;M=x(M,Math.sqrt(ne/ee)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],V=[(B[0]+K[0])/2,(B[1]+K[1])/2]}else if(H.touch0)G=H.touch0[0],V=H.touch0[1];else return;H.zoom("touch",n(S(M,G,V),H.extent,i))}}function L(D,...z){if(this.__zooming){var H=_(this,z).event(D),F=D.changedTouches,U=F.length,q,M;for(Mte(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),q=0;q<U;++q)M=F[q],H.touch0&&H.touch0[2]===M.identifier?delete H.touch0:H.touch1&&H.touch1[2]===M.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&&(M=lg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=Cp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:hz(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:hz(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:hz(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:hz([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(g=(D=+D)*D,b):Math.sqrt(g)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const _y={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."},zM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Okt=["Enter"," ","Escape"],_kt={"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 Xj;(function(e){e.Strict="strict",e.Loose="loose"})(Xj||(Xj={}));var iO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(iO||(iO={}));var FM;(function(e){e.Partial="partial",e.Full="full"})(FM||(FM={}));const Ckt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var kw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(kw||(kw={}));var BM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(BM||(BM={}));var ar;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(ar||(ar={}));const t7e={[ar.Left]:ar.Right,[ar.Right]:ar.Left,[ar.Top]:ar.Bottom,[ar.Bottom]:ar.Top};function Ekt(e){return e===null?null:e?"valid":"invalid"}const Tkt=e=>"id"in e&&"source"in e&&"target"in e,FQn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),Hke=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),Q3=(e,t=[0,0])=>{const{width:n,height:r}=l0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},BQn=(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):Hke(s)?s:t.nodeLookup.get(s.id));const l=i?WB(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return JH(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return eW(n)},Y3=(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=JH(n,WB(s)),r=!0)}),r?eW(n):{x:0,y:0,width:0,height:0}},Wke=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...X3(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,g=UM(l,eN(u)),y=(h??0)*(m??0),b=a&&g>0;(!u.internals.handleBounds||b||g>=y||u.dragging)&&c.push(u)}return c},UQn=(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 qQn(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 VQn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=qQn(e,i),c=Y3(l),u=Zke(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 jkt({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",_y.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&tN(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=tN(f)?XO(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",_y.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 HQn({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(g=>g.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=UQn(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 Jj=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),XO=(e={x:0,y:0},t,n)=>({x:Jj(e.x,t[0][0],t[1][0]-(n?.width??0)),y:Jj(e.y,t[0][1],t[1][1]-(n?.height??0))});function Nkt(e,t,n){const{width:r,height:s}=l0(n),{x:a,y:i}=n.internals.positionAbsolute;return XO(e,[[a,i],[a+r,i+s]],t)}const n7e=(e,t,n)=>e<t?Jj(Math.abs(e-t),1,t)/t:e>n?-Jj(Math.abs(e-n),1,t)/t:0,Ikt=(e,t,n=15,r=40)=>{const s=n7e(e.x,r,t.width-r)*n,a=n7e(e.y,r,t.height-r)*n;return[s,a]},JH=(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)}),Wge=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),eW=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),eN=(e,t=[0,0])=>{const{x:n,y:r}=Hke(e)?e.internals.positionAbsolute:Q3(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}},WB=(e,t=[0,0])=>{const{x:n,y:r}=Hke(e)?e.internals.positionAbsolute:Q3(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)}},Akt=(e,t)=>eW(JH(Wge(e),Wge(t))),UM=(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)},r7e=e=>wg(e.width)&&wg(e.height)&&wg(e.x)&&wg(e.y),wg=e=>!isNaN(e)&&isFinite(e),WQn=(e,t)=>{},K3=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),X3=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?K3(l,i):l},ZB=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function hE(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 ZQn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=hE(e,n),s=hE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=hE(e.top??e.y??0,n),s=hE(e.bottom??e.y??0,n),a=hE(e.left??e.x??0,t),i=hE(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 GQn(e,t,n,r,s,a){const{x:i,y:l}=ZB(e,[t,n,r]),{x:c,y:u}=ZB({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 Zke=(e,t,n,r,s,a)=>{const i=ZQn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=Jj(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,g=GQn(e,h,m,d,t,n),y={left:Math.min(g.left-i.left,0),top:Math.min(g.top-i.top,0),right:Math.min(g.right-i.right,0),bottom:Math.min(g.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},qM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function tN(e){return e!=null&&e!=="parent"}function l0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function Rkt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function Pkt(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 s7e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function QQn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function YQn(e){return{..._kt,...e||{}}}function C2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Sg(e),l=X3({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?K3(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const Gke=e=>({width:e.offsetWidth,height:e.offsetHeight}),$kt=e=>e?.getRootNode?.()||window?.document,KQn=["INPUT","SELECT","TEXTAREA"];function Mkt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:KQn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const Dkt=e=>"clientX"in e,Sg=(e,t)=>{const n=Dkt(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)}},a7e=(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,...Gke(i)}})};function Lkt({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 mz(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function i7e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case ar.Left:return[t-mz(t-r,a),n];case ar.Right:return[t+mz(r-t,a),n];case ar.Top:return[t,n-mz(n-s,a)];case ar.Bottom:return[t,n+mz(s-n,a)]}}function Qke({sourceX:e,sourceY:t,sourcePosition:n=ar.Bottom,targetX:r,targetY:s,targetPosition:a=ar.Top,curvature:i=.25}){const[l,c]=i7e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=i7e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=Lkt({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 zkt({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 XQn({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 JQn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=JH(WB(e),WB(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 UM(i,eW(a))>0}const eYn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,tYn=(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)),nYn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||eYn;let s;return Tkt(e)?s={...e}:s={...e,id:r(e)},tYn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function Fkt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=zkt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const o7e={[ar.Left]:{x:-1,y:0},[ar.Right]:{x:1,y:0},[ar.Top]:{x:0,y:-1},[ar.Bottom]:{x:0,y:1}},rYn=({source:e,sourcePosition:t=ar.Bottom,target:n})=>t===ar.Left||t===ar.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},l7e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function sYn({source:e,sourcePosition:t=ar.Bottom,target:n,targetPosition:r=ar.Top,center:s,offset:a,stepPosition:i}){const l=o7e[t],c=o7e[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=rYn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],g,y;const b={x:0,y:0},x={x:0,y:0},[,,S,k]=zkt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(g=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(g=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const T=[{x:g,y:u.y},{x:g,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?T:N:m=p==="x"?N:T}else{const T=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:T:m=l.y===h?T:N,t===r){const D=Math.abs(e[p]-n[p]);if(D<=a){const z=Math.min(a-1,a-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*z:x[p]=(d[p]>n[p]?-1:1)*z}}if(t!==r){const D=p==="x"?"y":"x",z=l[p]===c[D],H=u[D]>d[D],F=u[D]<d[D];(l[p]===1&&(!z&&H||z&&F)||l[p]!==1&&(!z&&F||z&&H))&&(m=p==="x"?T:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.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?(g=(I.x+A.x)/2,y=m[0].y):(g=m[0].x,y=(I.y+A.y)/2)}const C={x:u.x+b.x,y:u.y+b.y},_={x:d.x+x.x,y:d.y+x.y};return[[e,...C.x!==m[0].x||C.y!==m[0].y?[C]:[],...m,..._.x!==m[m.length-1].x||_.y!==m[m.length-1].y?[_]:[],n],g,y,S,k]}function aYn(e,t,n,r){const s=Math.min(l7e(e,t)/2,l7e(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 Zge({sourceX:e,sourceY:t,sourcePosition:n=ar.Bottom,targetX:r,targetY:s,targetPosition:a=ar.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,g]=sYn({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+=aYn(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,g]}function c7e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function iYn(e){const{sourceNode:t,targetNode:n}=e;if(!c7e(t)||!c7e(n))return null;const r=t.internals.handleBounds||u7e(t.handles),s=n.internals.handleBounds||u7e(n.handles),a=d7e(r?.source??[],e.sourceHandle),i=d7e(e.connectionMode===Xj.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",_y.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||ar.Bottom,c=i?.position||ar.Top,u=JO(t,a,l),d=JO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function u7e(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 JO(e,t,n=ar.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??l0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case ar.Top:return{x:s+i/2,y:a};case ar.Right:return{x:s+i,y:a+l/2};case ar.Bottom:return{x:s+i/2,y:a+l};case ar.Left:return{x:s,y:a+l/2}}}function d7e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Gge(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function oYn(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=Gge(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 Bkt=1e3,lYn=10,Yke={nodeOrigin:[0,0],nodeExtent:zM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},cYn={...Yke,checkEquality:!0};function Kke(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function uYn(e,t,n){const r=Kke(Yke,n);for(const s of e.values())if(s.parentId)Jke(s,e,t,r);else{const a=Q3(s,r.nodeOrigin),i=tN(s.extent)?s.extent:r.nodeExtent,l=XO(a,i,l0(s));s.internals.positionAbsolute=l}}function dYn(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 Xke(e){return e==="manual"}function Qge(e,t,n,r={}){const s=Kke(cYn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!Xke(s.zIndexMode)?Bkt: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=Q3(d,s.nodeOrigin),h=tN(d.extent)?d.extent:s.nodeExtent,m=XO(p,h,l0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:dYn(d,f),z:Ukt(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&&Jke(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function fYn(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 Jke(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=Kke(Yke,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}fYn(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*lYn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!Xke(c)?Bkt:0,{x:p,y:h,z:m}=pYn(e,d,i,l,f,c),{positionAbsolute:g}=e.internals,y=p!==g.x||h!==g.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:g,z:m}})}function Ukt(e,t,n){const r=wg(e.zIndex)?e.zIndex:0;return Xke(n)?r:r+(e.selected?t:0)}function pYn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=l0(e),u=Q3(e,n),d=tN(e.extent)?XO(u,e.extent,c):u;let f=XO({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=Nkt(f,c,t));const p=Ukt(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function eOe(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??eN(l),u=Akt(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=l0(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)),g=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(g-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(x=>{e.some(S=>S.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+p,y:x.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:g+(h?f[1]*h-b:0)}})}),s}function hYn(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 g=Gke(h.nodeElement),y=m.measured.width!==g.width||m.measured.height!==g.height;if(!!(g.width&&g.height&&(y||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),S=tN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=Nkt(k,g,t.get(m.parentId)):S&&(k=XO(k,S,g));const C={...m,measured:g,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:a7e("source",h.nodeElement,x,f,m.id),target:a7e("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,C),m.parentId&&Jke(C,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:g}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:eN(C,s)}))}}if(p.length>0){const h=eOe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function mYn({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 f7e(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 qkt(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}`;f7e("source",c,d,e,s,i),f7e("target",c,u,e,a,l),t.set(r.id,r)}}function Vkt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:Vkt(n,t):!1}function p7e(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 gYn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!Vkt(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 Dte({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 vYn({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=K3(a,t);return{x:i.x-a.x,y:i.y-a.y}}function yYn({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,g=null;function y({noDragClassName:x,handleSelector:S,domNode:k,isSelectable:C,nodeId:_,nodeClickDistance:E=0}){p=Cp(k);function T({x:R,y:L}){const{nodeLookup:D,nodeExtent:z,snapGrid:H,snapToGrid:F,nodeOrigin:U,onNodeDrag:q,onSelectionDrag:M,onError:G,updateNodePositions:V}=t();a={x:R,y:L};let $=!1;const B=l.size>1,Z=B&&z?Wge(Y3(l)):null,K=B&&F?vYn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[ne,ee]of l){if(!D.has(ne))continue;let J={x:R-ee.distance.x,y:L-ee.distance.y};F&&(J=K?{x:Math.round(J.x+K.x),y:Math.round(J.y+K.y)}:K3(J,H));let ae=null;if(B&&z&&!ee.extent&&Z){const{positionAbsolute:re}=ee.internals,le=re.x-Z.x+z[0][0],ue=re.x+ee.measured.width-Z.x2+z[1][0],oe=re.y-Z.y+z[0][1],me=re.y+ee.measured.height-Z.y2+z[1][1];ae=[[le,oe],[ue,me]]}const{position:fe,positionAbsolute:Y}=jkt({nodeId:ne,nextPosition:J,nodeLookup:D,nodeExtent:ae||z,nodeOrigin:U,onError:G});$=$||ee.position.x!==fe.x||ee.position.y!==fe.y,ee.position=fe,ee.internals.positionAbsolute=Y}if(m=m||$,!!$&&(V(l,!0),g&&(r||q||!_&&M))){const[ne,ee]=Dte({nodeId:_,dragItems:l,nodeLookup:D});r?.(g,l,ne,ee),q?.(g,ne,ee),_||M?.(g,ee)}}async function N(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:D,autoPanOnNodeDrag:z}=t();if(!z){c=!1,cancelAnimationFrame(i);return}const[H,F]=Ikt(u,d,D);(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})&&T(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:z,transform:H,snapGrid:F,snapToGrid:U,selectNodesOnDrag:q,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:V}=t();f=!0,(!q||!C)&&!D&&_&&(L.get(_)?.selected||V()),C&&q&&_&&e?.(_);const $=C2(R.sourceEvent,{transform:H,snapGrid:F,snapToGrid:U,containerBounds:d});if(a=$,l=gYn(L,z,$,_),l.size>0&&(n||M||!_&&G)){const[B,Z]=Dte({nodeId:_,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,B,Z),M?.(R.sourceEvent,B,Z),_||G?.(R.sourceEvent,Z)}}const A=lkt().clickDistance(E).on("start",R=>{const{domNode:L,nodeDragThreshold:D,transform:z,snapGrid:H,snapToGrid:F}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,g=R.sourceEvent,D===0&&I(R),a=C2(R.sourceEvent,{transform:z,snapGrid:H,snapToGrid:F,containerBounds:d}),u=Sg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:z,snapToGrid:H,nodeDragThreshold:F,nodeLookup:U}=t(),q=C2(R.sourceEvent,{transform:D,snapGrid:z,snapToGrid:H,containerBounds:d});if(g=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||_&&!U.has(_))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,N()),!f){const M=Sg(R.sourceEvent,d),G=M.x-u.x,V=M.y-u.y;Math.sqrt(G*G+V*V)>F&&I(R)}(a.x!==q.xSnapped||a.y!==q.ySnapped)&&l&&f&&(u=Sg(R.sourceEvent,d),T(q))}}).on("end",R=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:D,onNodeDragStop:z,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||z||!_&&H){const[F,U]=Dte({nodeId:_,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,F,U),z?.(R.sourceEvent,F,U),_||H?.(R.sourceEvent,U)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!p7e(L,`.${x}`,k))&&(!S||p7e(L,S,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function bYn(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())UM(s,eN(a))>0&&r.push(a);return r}const xYn=250;function wYn(e,t,n,r){let s=[],a=1/0;const i=bYn(e,n,t+xYn);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}=JO(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 Hkt(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,...JO(i,c,c.position,!0)}:c}function Wkt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function SYn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const Zkt=()=>!0;function kYn(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:g,onConnectEnd:y,isValidConnection:b=Zkt,onReconnectEnd:x,updateConnection:S,getTransform:k,getFromHandle:C,autoPanSpeed:_,dragThreshold:E=1,handleDomNode:T}){const N=$kt(e.target);let I=0,A;const{x:R,y:L}=Sg(e),D=Wkt(a,T),z=l?.getBoundingClientRect();let H=!1;if(!z||!D)return;const F=Hkt(s,D,r,c,t);if(!F)return;let U=Sg(e,z),q=!1,M=null,G=!1,V=null;function $(){if(!d||!z)return;const[fe,Y]=Ikt(U,z,_);p({x:fe,y:Y}),I=requestAnimationFrame($)}const B={...F,nodeId:s,type:D,position:F.position},Z=c.get(s);let ne={inProgress:!0,isValid:null,from:JO(Z,B,ar.Left,!0),fromHandle:B,fromPosition:B.position,fromNode:Z,to:U,toHandle:null,toPosition:t7e[B.position],toNode:null,pointer:U};function ee(){H=!0,S(ne),m?.(e,{nodeId:s,handleId:r,handleType:D})}E===0&&ee();function J(fe){if(!H){const{x:me,y:be}=Sg(fe),xe=me-R,Ce=be-L;if(!(xe*xe+Ce*Ce>E*E))return;ee()}if(!C()||!B){ae(fe);return}const Y=k();U=Sg(fe,z),A=wYn(X3(U,Y,!1,[1,1]),n,c,B),q||($(),q=!0);const re=Gkt(fe,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});V=re.handleDomNode,M=re.connection,G=SYn(!!A,re.isValid);const le=c.get(s),ue=le?JO(le,B,ar.Left,!0):ne.from,oe={...ne,from:ue,isValid:G,to:re.toHandle&&G?ZB({x:re.toHandle.x,y:re.toHandle.y},Y):U,toHandle:re.toHandle,toPosition:G&&re.toHandle?re.toHandle.position:t7e[B.position],toNode:re.toHandle?c.get(re.toHandle.nodeId):null,pointer:U};S(oe),ne=oe}function ae(fe){if(!("touches"in fe&&fe.touches.length>0)){if(H){(A||V)&&M&&G&&g?.(M);const{inProgress:Y,...re}=ne,le={...re,toPosition:ne.toHandle?ne.toPosition:null};y?.(fe,le),a&&x?.(fe,le)}h(),cancelAnimationFrame(I),q=!1,G=!1,M=null,V=null,N.removeEventListener("mousemove",J),N.removeEventListener("mouseup",ae),N.removeEventListener("touchmove",J),N.removeEventListener("touchend",ae)}}N.addEventListener("mousemove",J),N.addEventListener("mouseup",ae),N.addEventListener("touchmove",J),N.addEventListener("touchend",ae)}function Gkt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=Zkt,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}=Sg(e),g=i.elementFromPoint(h,m),y=g?.classList.contains(`${l}-flow__handle`)?g:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=Wkt(void 0,y),S=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),C=y.classList.contains("connectable"),_=y.classList.contains("connectableend");if(!S||!x)return b;const E={source:f?S:r,sourceHandle:f?k:s,target:f?r:S,targetHandle:f?s:k};b.connection=E;const N=C&&_&&(n===Xj.Strict?f&&x==="source"||!f&&x==="target":S!==r||k!==s);b.isValid=N&&u(E),b.toHandle=Hkt(S,x,k,d,n,!0)}return b}const Yge={onPointerDown:kYn,isValid:Gkt};function OYn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Cp(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=S=>{if(S.sourceEvent.type!=="wheel"||!t)return;const k=n(),C=S.sourceEvent.ctrlKey&&qM()?10:1,_=-S.sourceEvent.deltaY*(S.sourceEvent.deltaMode===1?.05:S.sourceEvent.deltaMode?1:.002)*d,E=k[2]*Math.pow(2,_*C);t.scaleTo(E)};let g=[0,0];const y=S=>{(S.sourceEvent.type==="mousedown"||S.sourceEvent.type==="touchstart")&&(g=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY])},b=S=>{const k=n();if(S.sourceEvent.type!=="mousemove"&&S.sourceEvent.type!=="touchmove"||!t)return;const C=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY],_=[C[0]-g[0],C[1]-g[1]];g=C;const E=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),T={x:k[0]-_[0]*E,y:k[1]-_[1]*E},N=[[0,0],[c,u]];t.setViewportConstrained({x:T.x,y:T.y,zoom:k[2]},N,l)},x=kkt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:lg}}const tW=e=>({x:e.x,y:e.y,zoom:e.k}),Lte=({x:e,y:t,zoom:n})=>XH.translate(e,t).scale(n),mT=(e,t)=>e.target.closest(`.${t}`),Qkt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),_Yn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,zte=(e,t=0,n=_Yn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},Ykt=e=>{const t=e.ctrlKey&&qM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function CYn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(mT(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=lg(d),b=Ykt(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const p=d.deltaMode===1?20:1;let h=s===iO.Vertical?0:d.deltaX*p,m=s===iO.Horizontal?0:d.deltaY*p;!qM()&&d.shiftKey&&s!==iO.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const g=tW(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,g),e.panScrollTimeout=setTimeout(()=>{u?.(d,g),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,g))}}function EYn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=mT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function TYn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=tW(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 jYn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&Qkt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,tW(a.transform))}}function NYn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&Qkt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=tW(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function IYn({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"&&(mT(f,`${u}-flow__node`)||mT(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||mT(f,l)&&m||mT(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 g=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&g}}function AYn({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=kkt().scaleExtent([t,n]).translateExtent(r),p=Cp(e).call(f);x({x:s.x,y:s.y,zoom:Jj(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(Ykt);function g(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?yx:H8).transform(zte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:D,panOnScroll:z,panOnDrag:H,panOnScrollMode:F,panOnScrollSpeed:U,preventScrolling:q,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:V,zoomActivationKeyPressed:$,lib:B,onTransformChange:Z,connectionInProgress:K,paneClickDistance:ne,selectionOnDrag:ee}){D&&!u.isZoomingOrPanning&&b();const J=z&&!$&&!D;f.clickDistance(ee?1/0:!wg(ne)||ne<0?0:ne);const ae=J?CYn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:F,panOnScrollSpeed:U,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):EYn({noWheelClassName:A,preventScrolling:q,d3ZoomHandler:h});if(p.on("wheel.zoom",ae,{passive:!1}),!D){const Y=TYn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",Y);const re=jYn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",re);const le=NYn({zoomPanValues:u,panOnDrag:H,panOnScroll:z,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",le)}const fe=IYn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:z,zoomOnDoubleClick:V,zoomOnPinch:M,userSelectionActive:D,noPanClassName:R,noWheelClassName:A,lib:B,connectionInProgress:K});f.filter(fe),V?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const D=Lte(A),z=f?.constrain()(D,R,L);return z&&await g(z),new Promise(H=>H(z))}async function S(A,R){const L=Lte(A);return await g(L,R),new Promise(D=>D(L))}function k(A){if(p){const R=Lte(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 C(){const A=p?Skt(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function _(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?yx:H8).scaleTo(zte(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"?yx:H8).scaleBy(zte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!wg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:S,setViewportConstrained:x,getViewport:C,scaleTo:_,scaleBy:E,setScaleExtent:T,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var nN;(function(e){e.Line="line",e.Handle="handle"})(nN||(nN={}));function RYn({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 h7e(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 tw(e,t){return Math.max(0,t-e)}function nw(e,t){return Math.max(0,e-t)}function gz(e,t,n){return Math.max(0,t-e,e-n)}function m7e(e,t){return e?!t:t}function PYn(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:g,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:S,y:k,width:C,height:_,aspectRatio:E}=e;let T=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=C+(c?-T:T),A=_+(u?-N:N),R=-a[0]*C,L=-a[1]*_;let D=gz(I,g,y),z=gz(A,b,x);if(i){let U=0,q=0;c&&T<0?U=tw(S+T+R,i[0][0]):!c&&T>0&&(U=nw(S+I+R,i[1][0])),u&&N<0?q=tw(k+N+L,i[0][1]):!u&&N>0&&(q=nw(k+A+L,i[1][1])),D=Math.max(D,U),z=Math.max(z,q)}if(l){let U=0,q=0;c&&T>0?U=nw(S+T,l[0][0]):!c&&T<0&&(U=tw(S+I,l[1][0])),u&&N>0?q=nw(k+N,l[0][1]):!u&&N<0&&(q=tw(k+A,l[1][1])),D=Math.max(D,U),z=Math.max(z,q)}if(s){if(d){const U=gz(I/E,b,x)*E;if(D=Math.max(D,U),i){let q=0;!c&&!u||c&&!u&&p?q=nw(k+L+I/E,i[1][1])*E:q=tw(k+L+(c?T:-T)/E,i[0][1])*E,D=Math.max(D,q)}if(l){let q=0;!c&&!u||c&&!u&&p?q=tw(k+I/E,l[1][1])*E:q=nw(k+(c?T:-T)/E,l[0][1])*E,D=Math.max(D,q)}}if(f){const U=gz(A*E,g,y)/E;if(z=Math.max(z,U),i){let q=0;!c&&!u||u&&!c&&p?q=nw(S+A*E+R,i[1][0])/E:q=tw(S+(u?N:-N)*E+R,i[0][0])/E,z=Math.max(z,q)}if(l){let q=0;!c&&!u||u&&!c&&p?q=tw(S+A*E,l[1][0])/E:q=nw(S+(u?N:-N)*E,l[0][0])/E,z=Math.max(z,q)}}}N=N+(N<0?z:-z),T=T+(T<0?D:-D),s&&(p?I>A*E?N=(m7e(c,u)?-T:T)/E:T=(m7e(c,u)?-N:N)*E:d?(N=T/E,u=c):(T=N*E,c=u));const H=c?S+T:S,F=u?k+N:k;return{width:C+(c?-T:T),height:_+(u?-N:N),x:a[0]*T*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+F}}const Kkt={width:0,height:0,x:0,y:0},$Yn={...Kkt,pointerX:0,pointerY:0,aspectRatio:1};function MYn(e){return[[0,0],[e.measured.width,e.measured.height]]}function DYn(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 LYn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Cp(e);let i={controlDirection:h7e("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:g,shouldResize:y}){let b={...Kkt},x={...$Yn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:h7e(u)};let S,k=null,C=[],_,E,T,N=!1;const I=lkt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:D,snapToGrid:z,nodeOrigin:H,paneDomNode:F}=n();if(S=R.get(t),!S)return;k=F?.getBoundingClientRect()??null;const{xSnapped:U,ySnapped:q}=C2(A.sourceEvent,{transform:L,snapGrid:D,snapToGrid:z,containerBounds:k});b={width:S.measured.width??0,height:S.measured.height??0,x:S.position.x??0,y:S.position.y??0},x={...b,pointerX:U,pointerY:q,aspectRatio:b.width/b.height},_=void 0,S.parentId&&(S.extent==="parent"||S.expandParent)&&(_=R.get(S.parentId),E=_&&S.extent==="parent"?MYn(_):void 0),C=[],T=void 0;for(const[M,G]of R)if(G.parentId===t&&(C.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const V=DYn(G,S,G.origin??H);T?T=[[Math.min(V[0][0],T[0][0]),Math.min(V[0][1],T[0][1])],[Math.max(V[1][0],T[1][0]),Math.max(V[1][1],T[1][1])]]:T=V}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:D,nodeOrigin:z}=n(),H=C2(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:D,containerBounds:k}),F=[];if(!S)return;const{x:U,y:q,width:M,height:G}=b,V={},$=S.origin??z,{width:B,height:Z,x:K,y:ne}=PYn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,E,T),ee=B!==M,J=Z!==G,ae=K!==U&&ee,fe=ne!==q&&J;if(!ae&&!fe&&!ee&&!J)return;if((ae||fe||$[0]===1||$[1]===1)&&(V.x=ae?K:b.x,V.y=fe?ne:b.y,b.x=V.x,b.y=V.y,C.length>0)){const ue=K-U,oe=ne-q;for(const me of C)me.position={x:me.position.x-ue+$[0]*(B-M),y:me.position.y-oe+$[1]*(Z-G)},F.push(me)}if((ee||J)&&(V.width=ee&&(!i.resizeDirection||i.resizeDirection==="horizontal")?B:b.width,V.height=J&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=V.width,b.height=V.height),_&&S.expandParent){const ue=$[0]*(V.width??0);V.x&&V.x<ue&&(b.x=ue,x.x=x.x-(V.x-ue));const oe=$[1]*(V.height??0);V.y&&V.y<oe&&(b.y=oe,x.y=x.y-(V.y-oe))}const Y=RYn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),re={...b,direction:Y};y?.(A,re)!==!1&&(N=!0,m?.(A,re),r(V,F))}).on("end",A=>{N&&(g?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const zYn={},g7e=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:()=>{(zYn?"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},FYn=e=>e?g7e(e):g7e,{useDebugValue:BYn}=ze,{useSyncExternalStoreWithSelector:UYn}=rCn,qYn=e=>e;function Xkt(e,t=qYn,n){const r=UYn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return BYn(r),r}const v7e=(e,t)=>{const n=FYn(e),r=(s,a=t)=>Xkt(n,s,a);return Object.assign(r,n),r},VYn=(e,t)=>e?v7e(e,t):v7e;function io(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 nW=v.createContext(null),HYn=nW.Provider,Jkt=_y.error001();function qs(e,t){const n=v.useContext(nW);if(n===null)throw new Error(Jkt);return Xkt(n,e,t)}function No(){const e=v.useContext(nW);if(e===null)throw new Error(Jkt);return v.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const y7e={display:"none"},WYn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},eOt="react-flow__node-desc",tOt="react-flow__edge-desc",ZYn="react-flow__aria-live",GYn=e=>e.ariaLiveMessage,QYn=e=>e.ariaLabelConfig;function YYn({rfId:e}){const t=qs(GYn);return o.jsx("div",{id:`${ZYn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:WYn,children:t})}function KYn({rfId:e,disableKeyboardA11y:t}){const n=qs(QYn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${eOt}-${e}`,style:y7e,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${tOt}-${e}`,style:y7e,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(YYn,{rfId:e})]})}const J3=v.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Hl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});J3.displayName="Panel";function XYn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(J3,{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 JYn=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}},vz=e=>e.id;function eKn(e,t){return io(e.selectedNodes.map(vz),t.selectedNodes.map(vz))&&io(e.selectedEdges.map(vz),t.selectedEdges.map(vz))}function tKn({onSelectionChange:e}){const t=No(),{selectedNodes:n,selectedEdges:r}=qs(JYn,eKn);return v.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const nKn=e=>!!e.onSelectionChangeHandlers;function rKn({onSelectionChange:e}){const t=qs(nKn);return e||t?o.jsx(tKn,{onSelectionChange:e}):null}const Kge=typeof window<"u"?v.useLayoutEffect:v.useEffect,nOt=[0,0],sKn={x:0,y:0,zoom:1},aKn=["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"],b7e=[...aKn,"rfId"],iKn=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}),x7e={translateExtent:zM,nodeOrigin:nOt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function oKn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=qs(iKn,io),u=No();Kge(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=x7e,l()}),[]);const d=v.useRef(x7e);return Kge(()=>{for(const f of b7e){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:YQn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},b7e.map(f=>e[f])),null}function w7e(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function lKn(e){const[t,n]=v.useState(e==="system"?null:e);return v.useEffect(()=>{if(e!=="system"){n(e);return}const r=w7e(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:w7e()?.matches?"dark":"light"}const S7e=typeof document<"u"?document:null;function VM(e=null,t={target:S7e,actInsideInputWithModifier:!0}){const[n,r]=v.useState(!1),s=v.useRef(!1),a=v.useRef(new Set([])),[i,l]=v.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
337
337
  `).replace(`
338
338
 
339
339
  `,`
@@ -490,7 +490,7 @@ ${e.map(u=>`- ${u.id}: ${u.name}`).join(`
490
490
  `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:p,table:i,tableCell:c,tableRow:l}};function i(h,m,g,y){return u(d(h,g,y),h.align)}function l(h,m,g,y){const b=f(h,g,y),x=u([b]);return x.slice(0,x.indexOf(`
491
491
  `))}function c(h,m,g,y){const b=g.enter("tableCell"),x=g.enter("phrasing"),S=g.containerPhrasing(h,{...y,before:a,after:a});return x(),b(),S}function u(h,m){return z2r(h,{align:m,alignDelimiters:r,padding:n,stringLength:s})}function d(h,m,g){const y=h.children;let b=-1;const x=[],S=m.enter("table");for(;++b<y.length;)x[b]=f(y[b],m,g);return S(),x}function f(h,m,g){const y=h.children;let b=-1;const x=[],S=m.enter("tableRow");for(;++b<y.length;)x[b]=c(y[b],h,m,g);return S(),x}function p(h,m,g){let y=T$t.inlineCode(h,m,g);return g.stack.includes("tableCell")&&(y=y.replace(/\|/g,"\\$&")),y}}function C$r(){return{exit:{taskListCheckValueChecked:oQe,taskListCheckValueUnchecked:oQe,paragraph:T$r}}}function E$r(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:j$r}}}function oQe(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function T$r(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const r=n.children[0];if(r&&r.type==="text"){const s=t.children;let a=-1,i;for(;++a<s.length;){const l=s[a];if(l.type==="paragraph"){i=l;break}}i===n&&(r.value=r.value.slice(1),r.value.length===0?n.children.shift():n.position&&r.position&&typeof r.position.start.offset=="number"&&(r.position.start.column++,r.position.start.offset++,n.position.start=Object.assign({},r.position.start)))}}this.exit(e)}function j$r(e,t,n,r){const s=e.children[0],a=typeof e.checked=="boolean"&&s&&s.type==="paragraph",i="["+(e.checked?"x":" ")+"] ",l=n.createTracker(r);a&&l.move(i);let c=T$t.listItem(e,t,n,{...r,...l.current()});return a&&(c=c.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),c;function u(d){return d+i}}function N$r(){return[l2r(),j2r(),R2r(),b$r(),C$r()]}function I$r(e){return{extensions:[c2r(),N2r(e),P2r(),_$r(e),E$r()]}}const A$r={tokenize:L$r,partial:!0},j$t={tokenize:z$r,partial:!0},N$t={tokenize:F$r,partial:!0},I$t={tokenize:B$r,partial:!0},R$r={tokenize:U$r,partial:!0},A$t={name:"wwwAutolink",tokenize:M$r,previous:P$t},R$t={name:"protocolAutolink",tokenize:D$r,previous:$$t},h0={name:"emailAutolink",tokenize:$$r,previous:M$t},Xy={};function P$r(){return{text:Xy}}let ok=48;for(;ok<123;)Xy[ok]=h0,ok++,ok===58?ok=65:ok===91&&(ok=97);Xy[43]=h0;Xy[45]=h0;Xy[46]=h0;Xy[95]=h0;Xy[72]=[h0,R$t];Xy[104]=[h0,R$t];Xy[87]=[h0,A$t];Xy[119]=[h0,A$t];function $$r(e,t,n){const r=this;let s,a;return i;function i(f){return!fbe(f)||!M$t.call(r,r.previous)||VEe(r.events)?n(f):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),l(f))}function l(f){return fbe(f)?(e.consume(f),l):f===64?(e.consume(f),c):n(f)}function c(f){return f===46?e.check(R$r,d,u)(f):f===45||f===95||qu(f)?(a=!0,e.consume(f),c):d(f)}function u(f){return e.consume(f),s=!0,c}function d(f){return a&&s&&_d(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(f)):n(f)}}function M$r(e,t,n){const r=this;return s;function s(i){return i!==87&&i!==119||!P$t.call(r,r.previous)||VEe(r.events)?n(i):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(A$r,e.attempt(j$t,e.attempt(N$t,a),n),n)(i))}function a(i){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(i)}}function D$r(e,t,n){const r=this;let s="",a=!1;return i;function i(f){return(f===72||f===104)&&$$t.call(r,r.previous)&&!VEe(r.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),s+=String.fromCodePoint(f),e.consume(f),l):n(f)}function l(f){if(_d(f)&&s.length<5)return s+=String.fromCodePoint(f),e.consume(f),l;if(f===58){const p=s.toLowerCase();if(p==="http"||p==="https")return e.consume(f),c}return n(f)}function c(f){return f===47?(e.consume(f),a?u:(a=!0,c)):n(f)}function u(f){return f===null||_q(f)||ji(f)||v_(f)||_Z(f)?n(f):e.attempt(j$t,e.attempt(N$t,d),n)(f)}function d(f){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(f)}}function L$r(e,t,n){let r=0;return s;function s(i){return(i===87||i===119)&&r<3?(r++,e.consume(i),s):i===46&&r===3?(e.consume(i),a):n(i)}function a(i){return i===null?n(i):t(i)}}function z$r(e,t,n){let r,s,a;return i;function i(u){return u===46||u===95?e.check(I$t,c,l)(u):u===null||ji(u)||v_(u)||u!==45&&_Z(u)?c(u):(a=!0,e.consume(u),i)}function l(u){return u===95?r=!0:(s=r,r=void 0),e.consume(u),i}function c(u){return s||r||!a?n(u):t(u)}}function F$r(e,t){let n=0,r=0;return s;function s(i){return i===40?(n++,e.consume(i),s):i===41&&r<n?a(i):i===33||i===34||i===38||i===39||i===41||i===42||i===44||i===46||i===58||i===59||i===60||i===63||i===93||i===95||i===126?e.check(I$t,t,a)(i):i===null||ji(i)||v_(i)?t(i):(e.consume(i),s)}function a(i){return i===41&&r++,e.consume(i),s}}function B$r(e,t,n){return r;function r(l){return l===33||l===34||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===63||l===95||l===126?(e.consume(l),r):l===38?(e.consume(l),a):l===93?(e.consume(l),s):l===60||l===null||ji(l)||v_(l)?t(l):n(l)}function s(l){return l===null||l===40||l===91||ji(l)||v_(l)?t(l):r(l)}function a(l){return _d(l)?i(l):n(l)}function i(l){return l===59?(e.consume(l),r):_d(l)?(e.consume(l),i):n(l)}}function U$r(e,t,n){return r;function r(a){return e.consume(a),s}function s(a){return qu(a)?n(a):t(a)}}function P$t(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||ji(e)}function $$t(e){return!_d(e)}function M$t(e){return!(e===47||fbe(e))}function fbe(e){return e===43||e===45||e===46||e===95||qu(e)}function VEe(e){let t=e.length,n=!1;for(;t--;){const r=e[t][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const q$r={tokenize:K$r,partial:!0};function V$r(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:G$r,continuation:{tokenize:Q$r},exit:Y$r}},text:{91:{name:"gfmFootnoteCall",tokenize:Z$r},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:H$r,resolveTo:W$r}}}}function H$r(e,t,n){const r=this;let s=r.events.length;const a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i;for(;s--;){const c=r.events[s][1];if(c.type==="labelImage"){i=c;break}if(c.type==="gfmFootnoteCall"||c.type==="labelLink"||c.type==="label"||c.type==="image"||c.type==="link")break}return l;function l(c){if(!i||!i._balanced)return n(c);const u=Ng(r.sliceSerialize({start:i.end,end:r.now()}));return u.codePointAt(0)!==94||!a.includes(u.slice(1))?n(c):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),t(c))}}function W$r(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const a={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},e[e.length-1][1].start)},i={type:"chunkString",contentType:"string",start:Object.assign({},a.start),end:Object.assign({},a.end)},l=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",s,t],["exit",s,t],["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...l),e}function Z$r(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let a=0,i;return l;function l(f){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(f),e.exit("gfmFootnoteCallLabelMarker"),c}function c(f){return f!==94?n(f):(e.enter("gfmFootnoteCallMarker"),e.consume(f),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(f){if(a>999||f===93&&!i||f===null||f===91||ji(f))return n(f);if(f===93){e.exit("chunkString");const p=e.exit("gfmFootnoteCallString");return s.includes(Ng(r.sliceSerialize(p)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(f),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(f)}return ji(f)||(i=!0),a++,e.consume(f),f===92?d:u}function d(f){return f===91||f===92||f===93?(e.consume(f),a++,u):u(f)}}function G$r(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let a,i=0,l;return c;function c(m){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(m){return m===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):n(m)}function d(m){if(i>999||m===93&&!l||m===null||m===91||ji(m))return n(m);if(m===93){e.exit("chunkString");const g=e.exit("gfmFootnoteDefinitionLabelString");return a=Ng(r.sliceSerialize(g)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(m),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),p}return ji(m)||(l=!0),i++,e.consume(m),m===92?f:d}function f(m){return m===91||m===92||m===93?(e.consume(m),i++,d):d(m)}function p(m){return m===58?(e.enter("definitionMarker"),e.consume(m),e.exit("definitionMarker"),s.includes(a)||s.push(a),ca(e,h,"gfmFootnoteDefinitionWhitespace")):n(m)}function h(m){return t(m)}}function Q$r(e,t,n){return e.check(P4,t,e.attempt(q$r,t,n))}function Y$r(e){e.exit("gfmFootnoteDefinition")}function K$r(e,t,n){const r=this;return ca(e,s,"gfmFootnoteDefinitionIndent",5);function s(a){const i=r.events[r.events.length-1];return i&&i[1].type==="gfmFootnoteDefinitionIndent"&&i[2].sliceSerialize(i[1],!0).length===4?t(a):n(a)}}function X$r(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:a,resolveAll:s};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function s(i,l){let c=-1;for(;++c<i.length;)if(i[c][0]==="enter"&&i[c][1].type==="strikethroughSequenceTemporary"&&i[c][1]._close){let u=c;for(;u--;)if(i[u][0]==="exit"&&i[u][1].type==="strikethroughSequenceTemporary"&&i[u][1]._open&&i[c][1].end.offset-i[c][1].start.offset===i[u][1].end.offset-i[u][1].start.offset){i[c][1].type="strikethroughSequence",i[u][1].type="strikethroughSequence";const d={type:"strikethrough",start:Object.assign({},i[u][1].start),end:Object.assign({},i[c][1].end)},f={type:"strikethroughText",start:Object.assign({},i[u][1].end),end:Object.assign({},i[c][1].start)},p=[["enter",d,l],["enter",i[u][1],l],["exit",i[u][1],l],["enter",f,l]],h=l.parser.constructs.insideSpan.null;h&&Up(p,p.length,0,CZ(h,i.slice(u+1,c),l)),Up(p,p.length,0,[["exit",f,l],["enter",i[c][1],l],["exit",i[c][1],l],["exit",d,l]]),Up(i,u-1,c-u+3,p),c=u+p.length-2;break}}for(c=-1;++c<i.length;)i[c][1].type==="strikethroughSequenceTemporary"&&(i[c][1].type="data");return i}function a(i,l,c){const u=this.previous,d=this.events;let f=0;return p;function p(m){return u===126&&d[d.length-1][1].type!=="characterEscape"?c(m):(i.enter("strikethroughSequenceTemporary"),h(m))}function h(m){const g=EN(u);if(m===126)return f>1?c(m):(i.consume(m),f++,h);if(f<2&&!n)return c(m);const y=i.exit("strikethroughSequenceTemporary"),b=EN(m);return y._open=!b||b===2&&!!g,y._close=!g||g===2&&!!b,l(m)}}}class J$r{constructor(){this.map=[]}add(t,n,r){eMr(this,t,n,r)}consume(t){if(this.map.sort(function(a,i){return a[0]-i[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let s=r.pop();for(;s;){for(const a of s)t.push(a);s=r.pop()}this.map.length=0}}function eMr(e,t,n,r){let s=0;if(!(n===0&&r.length===0)){for(;s<e.map.length;){if(e.map[s][0]===t){e.map[s][1]+=n,e.map[s][2].push(...r);return}s+=1}e.map.push([t,n,r])}}function tMr(e,t){let n=!1;const r=[];for(;t<e.length;){const s=e[t];if(n){if(s[0]==="enter")s[1].type==="tableContent"&&r.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(s[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const a=r.length-1;r[a]=r[a]==="left"?"center":"right"}}else if(s[1].type==="tableDelimiterRow")break}else s[0]==="enter"&&s[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return r}function nMr(){return{flow:{null:{name:"table",tokenize:rMr,resolveAll:sMr}}}}function rMr(e,t,n){const r=this;let s=0,a=0,i;return l;function l(I){let A=r.events.length-1;for(;A>-1;){const D=r.events[A][1].type;if(D==="lineEnding"||D==="linePrefix")A--;else break}const R=A>-1?r.events[A][1].type:null,L=R==="tableHead"||R==="tableRow"?_:c;return L===_&&r.parser.lazy[r.now().line]?n(I):L(I)}function c(I){return e.enter("tableHead"),e.enter("tableRow"),u(I)}function u(I){return I===124||(i=!0,a+=1),d(I)}function d(I){return I===null?n(I):gr(I)?a>1?(a=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(I),e.exit("lineEnding"),h):n(I):Rs(I)?ca(e,d,"whitespace")(I):(a+=1,i&&(i=!1,s+=1),I===124?(e.enter("tableCellDivider"),e.consume(I),e.exit("tableCellDivider"),i=!0,d):(e.enter("data"),f(I)))}function f(I){return I===null||I===124||ji(I)?(e.exit("data"),d(I)):(e.consume(I),I===92?p:f)}function p(I){return I===92||I===124?(e.consume(I),f):f(I)}function h(I){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(I):(e.enter("tableDelimiterRow"),i=!1,Rs(I)?ca(e,m,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):m(I))}function m(I){return I===45||I===58?y(I):I===124?(i=!0,e.enter("tableCellDivider"),e.consume(I),e.exit("tableCellDivider"),g):C(I)}function g(I){return Rs(I)?ca(e,y,"whitespace")(I):y(I)}function y(I){return I===58?(a+=1,i=!0,e.enter("tableDelimiterMarker"),e.consume(I),e.exit("tableDelimiterMarker"),b):I===45?(a+=1,b(I)):I===null||gr(I)?k(I):C(I)}function b(I){return I===45?(e.enter("tableDelimiterFiller"),x(I)):C(I)}function x(I){return I===45?(e.consume(I),x):I===58?(i=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(I),e.exit("tableDelimiterMarker"),S):(e.exit("tableDelimiterFiller"),S(I))}function S(I){return Rs(I)?ca(e,k,"whitespace")(I):k(I)}function k(I){return I===124?m(I):I===null||gr(I)?!i||s!==a?C(I):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(I)):C(I)}function C(I){return n(I)}function _(I){return e.enter("tableRow"),E(I)}function E(I){return I===124?(e.enter("tableCellDivider"),e.consume(I),e.exit("tableCellDivider"),E):I===null||gr(I)?(e.exit("tableRow"),t(I)):Rs(I)?ca(e,E,"whitespace")(I):(e.enter("data"),T(I))}function T(I){return I===null||I===124||ji(I)?(e.exit("data"),E(I)):(e.consume(I),I===92?N:T)}function N(I){return I===92||I===124?(e.consume(I),T):T(I)}}function sMr(e,t){let n=-1,r=!0,s=0,a=[0,0,0,0],i=[0,0,0,0],l=!1,c=0,u,d,f;const p=new J$r;for(;++n<e.length;){const h=e[n],m=h[1];h[0]==="enter"?m.type==="tableHead"?(l=!1,c!==0&&(lQe(p,t,c,u,d),d=void 0,c=0),u={type:"table",start:Object.assign({},m.start),end:Object.assign({},m.end)},p.add(n,0,[["enter",u,t]])):m.type==="tableRow"||m.type==="tableDelimiterRow"?(r=!0,f=void 0,a=[0,0,0,0],i=[0,n+1,0,0],l&&(l=!1,d={type:"tableBody",start:Object.assign({},m.start),end:Object.assign({},m.end)},p.add(n,0,[["enter",d,t]])),s=m.type==="tableDelimiterRow"?2:d?3:1):s&&(m.type==="data"||m.type==="tableDelimiterMarker"||m.type==="tableDelimiterFiller")?(r=!1,i[2]===0&&(a[1]!==0&&(i[0]=i[1],f=cF(p,t,a,s,void 0,f),a=[0,0,0,0]),i[2]=n)):m.type==="tableCellDivider"&&(r?r=!1:(a[1]!==0&&(i[0]=i[1],f=cF(p,t,a,s,void 0,f)),a=i,i=[a[1],n,0,0])):m.type==="tableHead"?(l=!0,c=n):m.type==="tableRow"||m.type==="tableDelimiterRow"?(c=n,a[1]!==0?(i[0]=i[1],f=cF(p,t,a,s,n,f)):i[1]!==0&&(f=cF(p,t,i,s,n,f)),s=0):s&&(m.type==="data"||m.type==="tableDelimiterMarker"||m.type==="tableDelimiterFiller")&&(i[3]=n)}for(c!==0&&lQe(p,t,c,u,d),p.consume(t.events),n=-1;++n<t.events.length;){const h=t.events[n];h[0]==="enter"&&h[1].type==="table"&&(h[1]._align=tMr(t.events,n))}return e}function cF(e,t,n,r,s,a){const i=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",l="tableContent";n[0]!==0&&(a.end=Object.assign({},JE(t.events,n[0])),e.add(n[0],0,[["exit",a,t]]));const c=JE(t.events,n[1]);if(a={type:i,start:Object.assign({},c),end:Object.assign({},c)},e.add(n[1],0,[["enter",a,t]]),n[2]!==0){const u=JE(t.events,n[2]),d=JE(t.events,n[3]),f={type:l,start:Object.assign({},u),end:Object.assign({},d)};if(e.add(n[2],0,[["enter",f,t]]),r!==2){const p=t.events[n[2]],h=t.events[n[3]];if(p[1].end=Object.assign({},h[1].end),p[1].type="chunkText",p[1].contentType="text",n[3]>n[2]+1){const m=n[2]+1,g=n[3]-n[2]-1;e.add(m,g,[])}}e.add(n[3]+1,0,[["exit",f,t]])}return s!==void 0&&(a.end=Object.assign({},JE(t.events,s)),e.add(s,0,[["exit",a,t]]),a=void 0),a}function lQe(e,t,n,r,s){const a=[],i=JE(t.events,n);s&&(s.end=Object.assign({},i),a.push(["exit",s,t])),r.end=Object.assign({},i),a.push(["exit",r,t]),e.add(n+1,0,a)}function JE(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const aMr={name:"tasklistCheck",tokenize:oMr};function iMr(){return{text:{91:aMr}}}function oMr(e,t,n){const r=this;return s;function s(c){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(c):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),a)}function a(c){return ji(c)?(e.enter("taskListCheckValueUnchecked"),e.consume(c),e.exit("taskListCheckValueUnchecked"),i):c===88||c===120?(e.enter("taskListCheckValueChecked"),e.consume(c),e.exit("taskListCheckValueChecked"),i):n(c)}function i(c){return c===93?(e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),l):n(c)}function l(c){return gr(c)?t(c):Rs(c)?e.check({tokenize:lMr},t,n)(c):n(c)}}function lMr(e,t,n){return ca(e,r,"whitespace");function r(s){return s===null?n(s):t(s)}}function cMr(e){return V2t([P$r(),V$r(),X$r(e),nMr(),iMr()])}const uMr={};function dMr(e){const t=this,n=e||uMr,r=t.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),a=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),i=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(cMr(n)),a.push(N$r()),i.push(I$r(n))}function fMr(e){return e.htmlStyle&&typeof e.htmlStyle=="object"?e.htmlStyle:e.color?{color:e.color}:void 0}const D$t=v.memo(function({code:t,lang:n,...r}){const[s,a]=v.useState(null);if(v.useEffect(()=>{if(a(null),!n)return;let l=!1;return rHn(t,n).then(c=>{l||a(c)}).catch(()=>{l||a(null)}),()=>{l=!0}},[t,n]),!s?.length)return o.jsx("pre",{...r,children:t});let i=0;return o.jsx("pre",{...r,children:o.jsx("code",{children:s.map((l,c)=>{const u=i;let d=u;const f=l.map(p=>{const h=d;return d+=p.content.length,o.jsx("span",{className:"shiki-token",style:fMr(p),children:p.content},h)});return i=d+1,o.jsxs(v.Fragment,{children:[o.jsx("span",{children:f}),c!==s.length-1&&`
492
492
  `]},u)})})})});function Xp({children:e}){const t=e.replace(/\\n/g,`
493
- `);return o.jsx(p$t,{remarkPlugins:[dMr],components:hMr,className:"space-y-3",children:t})}const pMr=({children:e,className:t,language:n,...r})=>{const s=typeof e=="string"?e:pbe(e),a=X("[scrollbar-width:none] overflow-x-scroll rounded-md border bg-surface1/50 p-4 font-mono text-sm",t);return o.jsxs("div",{className:"group/code relative mb-4",children:[o.jsx(D$t,{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(Pa,{content:s,copyMessage:"Copied code to clipboard"})})]})};function pbe(e){if(typeof e=="string")return e;if(e?.props?.children){let t=e.props.children;return Array.isArray(t)?t.map(n=>pbe(n)).join(""):pbe(t)}return""}const hMr={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-neutral6 border-l-2 pl-4",...t,children:e}),code:({children:e,className:t,...n})=>{const r=/language-(\w+)/.exec(t||"");return r?o.jsx(pMr,{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:"border-neutral6/20 w-full border-collapse overflow-y-auto rounded-md border",...t,children:e}),th:({children:e,...t})=>o.jsx("th",{className:"border-neutral6/20 border 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-neutral6/20 border 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:"even:bg-surface4 m-0 border-t p-0",...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})},L$t=({reason:e,tripwire:t})=>{const[n,r]=v.useState(!1),s=!!(t&&(t.retry!==void 0||t.metadata!==void 0||t.processorId!==void 0));return o.jsx(Sn,{variant:"warning",title:"Content Blocked",icon:o.jsx($xe,{}),children:o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsx(Sn.Message,{className:"break-words whitespace-pre-wrap",children:e}),s&&t&&o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsxs("button",{type:"button",onClick:()=>r(!n),className:"text-ui-sm flex w-fit items-center gap-1.5 opacity-70 transition-opacity hover:opacity-100",children:[n?o.jsx(ka,{className:"size-3.5"}):o.jsx(aa,{className:"size-3.5"}),o.jsx("span",{children:"Details"})]}),n&&o.jsxs("div",{className:"text-ui-sm flex flex-col gap-2",children:[t.retry!==void 0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(a1,{className:"size-3.5 shrink-0 opacity-70"}),o.jsx("span",{children:"Retry"}),o.jsx(on,{size:"xs",variant:t.retry?"success":"error",children:t.retry?"Allowed":"Not allowed"})]}),t.processorId&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(KN,{className:"size-3.5 shrink-0 opacity-70"}),o.jsx("span",{children:"Processor"}),o.jsx(on,{size:"xs",variant:"warning",children:t.processorId})]}),t.metadata!==void 0&&t.metadata!==null&&o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsx("span",{className:"opacity-70",children:"Metadata"}),o.jsx("pre",{className:"overflow-x-auto rounded-lg bg-current/10 p-2 font-mono",children:JSON.stringify(t.metadata,null,2)})]})]})]})]})})},HEe=({text:e,metadata:t})=>{const[n,r]=v.useState(!1);if(t?.status==="tripwire")return o.jsx(L$t,{reason:e,tripwire:t.tripwire});if(t?.status==="warning")return o.jsx(Sn,{variant:"warning",title:"Warning",children:o.jsx(Sn.Message,{children:e})});if(t?.status==="error")return o.jsx(Sn,{variant:"destructive",title:"Error",children:o.jsx(Sn.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(k_,{className:X("transition-all",n?"rotate-90":"rotate-180")})}),o.jsxs(on,{variant:"info",icon:o.jsx(gO,{}),children:[n?"Show":"Hide"," completion check"]})]}),!n&&o.jsx(Sn,{variant:"info",title:s?.passed?"Complete":"Not Complete",children:o.jsx(Xp,{children:e})})]});const a=e.trim();return a.startsWith("__ERROR__:")?o.jsx(Sn,{variant:"destructive",title:"Error",children:o.jsx(Sn.Message,{children:a.substring(10)})}):a.startsWith("Error:")?o.jsx(Sn,{variant:"destructive",title:"Error",children:o.jsx(Sn.Message,{children:a.substring(6).trim()})}):o.jsx(Xp,{children:e})},mMr=({text:e})=>o.jsx(Sn,{variant:"destructive",title:"Error",children:o.jsx(Sn.Message,{children:e})}),z$t=({text:e})=>o.jsx(Sn,{variant:"warning",title:"Warning",children:o.jsx(Sn.Message,{children:e})}),F$t=({text:e,tripwire:t})=>o.jsx(L$t,{reason:e,tripwire:t}),cQe={Error:mMr,Warning:z$t,Tripwire:F$t},B$t=()=>{const e=Zo(),t=Ws(),[n]=v.useState(()=>e.state?.userMessage);return v.useEffect(()=>{n!==void 0&&t(".",{replace:!0,state:null})},[n,t]),n},U$t=v.createContext(null),gMr=({agentId:e,children:t})=>{const n=Bf(),{canWrite:r}=zy(),s=B$t(),{data:a,isLoading:i}=j4(e,{status:"draft"}),{data:l,isPending:c}=VI({enabled:n.tools}),{data:u,isPending:d}=Am({enabled:n.agents}),{data:f,isPending:p}=Ky({enabled:n.workflows}),{data:h,isPending:m}=oS({enabled:n.skills}),{data:g}=OZ(),{data:y,isLoading:b}=Im(),x=!a?.authorId||y?.id===a.authorId,S=!!a?.authorId&&b,k=!!e&&!i&&!S&&(!n.tools||!c)&&(!n.skills||!m)&&(!n.agents||!d)&&(!n.workflows||!p),C=v.useMemo(()=>(g?.workspaces??[]).filter(T=>T.status!=="archived").sort((T,N)=>(N.runtimeRegistered?1:0)-(T.runtimeRegistered?1:0)).map(T=>({id:T.id,name:T.name})),[g]),_=v.useMemo(()=>h?.skills??[],[h]),E=v.useMemo(()=>({agentId:e,storedAgent:a??void 0,toolsData:l??{},agentsData:u??{},workflowsData:f??{},availableSkills:_,availableWorkspaces:C,initialUserMessage:s,isOwner:x,canWrite:r,isReady:k}),[e,a,l,u,f,_,C,s,x,r,k]);return o.jsx(U$t.Provider,{value:E,children:t})},cC=()=>{const e=v.useContext(U$t);if(!e)throw new Error("useAgentPrimitives must be used inside <AgentPrimitivesProvider>");return e},WI=()=>{const e=We();return yt({queryKey:["tool-providers"],queryFn:()=>e.listToolProviders()})},vMr=3e4,yMr=e=>{const t=We(),n=WI(),r=v.useMemo(()=>n.data?.providers??[],[n.data?.providers]),s=Im(),a=s.data?.id,i=s.isSuccess||u2t(s.error),l=Nj({queries:r.map(m=>({queryKey:["tool-integration-services",m.id],queryFn:()=>t.getToolProvider(m.id).listToolkits()}))}),c=v.useMemo(()=>{const m=[];return r.forEach((g,y)=>{const b=l[y]?.data?.data??[];for(const x of b)m.push({providerId:g.id,toolkit:x.slug})}),m},[r,l]),u=Nj({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:vMr}))}),d=n.isLoading||s.isLoading||l.some(m=>m.isLoading)||u.some(m=>m.isLoading),f=v.useMemo(()=>{const m=new Map;return c.forEach((g,y)=>{const b=u[y]?.data?.items??[];m.set(`${g.providerId}:${g.toolkit}`,b)}),m},[c,u]),p=v.useCallback((m,g)=>(f.get(`${m}:${g}`)??[]).some(y=>y.status==="active"),[f]),h=v.useCallback((m,g)=>f.get(`${m}:${g}`)??[],[f]);return{hasConnection:p,getConnections:h,isLoading:d}},bMr=500,M4=()=>{const e=We(),t=WI(),n=v.useMemo(()=>t.data?.providers??[],[t.data?.providers]),r=Nj({queries:n.map(c=>({queryKey:["tool-integration-services",c.id],queryFn:()=>e.getToolProvider(c.id).listToolkits()}))}),s=v.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=Nj({queries:s.map(c=>({queryKey:["tool-integration-tools-all",c.providerId,c.toolkit],queryFn:()=>e.getToolProvider(c.providerId).listTools({toolkit:c.toolkit,perPage:bMr})}))}),i=t.isLoading||r.some(c=>c.isLoading)||a.some(c=>c.isLoading);return{tools:v.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 xMr(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 wMr=({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},SMr={};function Mse(e,t){const n={};for(const[r,s]of Object.entries(e))t.has(r)&&(n[r]=s);return n}function q$t({toolsData:e,agentsData:t,workflowsData:n,selectedTools:r,selectedAgents:s,selectedWorkflows:a,excludeAgentId:i}){const l=n??SMr,c=iTn(),{tools:u}=M4(),{hasConnection:d,getConnections:f}=yMr(),p=zn({name:"toolProviders"});return v.useMemo(()=>{const h=c.visibleTools===null?e:Mse(e,c.visibleTools),m=c.visibleAgents===null?t:Mse(t,c.visibleAgents),g=c.visibleWorkflows===null?l:Mse(l,c.visibleWorkflows),y=xMr(h,m,g,i),b=wMr({tools:y.tools,agents:y.agents,workflows:y.workflows,selected:{tools:r,agents:s,workflows:a}}),x=u.map(S=>({id:`${S.providerId}:${S.slug}`,name:S.slug,description:S.description,isChecked:!!p?.[S.providerId]?.tools?.[S.slug],type:"integration",providerId:S.providerId,toolkit:S.toolkit,hasConnection:d(S.providerId,S.toolkit),connectionLabels:f(S.providerId,S.toolkit).filter(k=>k.status==="active").map(k=>k.label||k.connectionId)}));return[...b,...x]},[e,t,l,r,s,a,i,c,u,p,d,f])}const kMr=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=OMr(i);if(l)return{summary:CMr(l),details:t}}catch{}const n=t.split(`
493
+ `);return o.jsx(p$t,{remarkPlugins:[dMr],components:hMr,className:"space-y-3",children:t})}const pMr=({children:e,className:t,language:n,...r})=>{const s=typeof e=="string"?e:pbe(e),a=X("[scrollbar-width:none] overflow-x-scroll rounded-md border bg-surface1/50 p-4 font-mono text-sm",t);return o.jsxs("div",{className:"group/code relative mb-4",children:[o.jsx(D$t,{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(Pa,{content:s,copyMessage:"Copied code to clipboard"})})]})};function pbe(e){if(typeof e=="string")return e;if(e?.props?.children){let t=e.props.children;return Array.isArray(t)?t.map(n=>pbe(n)).join(""):pbe(t)}return""}const hMr={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,href:t,...n})=>{const r=/^https?:\/\//i.test(t??"");return o.jsx("a",{className:"underline underline-offset-2",href:t,...n,target:r?"_blank":void 0,rel:r?"noopener noreferrer":void 0,children:e})},blockquote:({children:e,...t})=>o.jsx("blockquote",{className:"border-neutral6 border-l-2 pl-4",...t,children:e}),code:({children:e,className:t,...n})=>{const r=/language-(\w+)/.exec(t||"");return r?o.jsx(pMr,{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:"border-neutral6/20 w-full border-collapse overflow-y-auto rounded-md border",...t,children:e}),th:({children:e,...t})=>o.jsx("th",{className:"border-neutral6/20 border 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-neutral6/20 border 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:"even:bg-surface4 m-0 border-t p-0",...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})},L$t=({reason:e,tripwire:t})=>{const[n,r]=v.useState(!1),s=!!(t&&(t.retry!==void 0||t.metadata!==void 0||t.processorId!==void 0));return o.jsx(Sn,{variant:"warning",title:"Content Blocked",icon:o.jsx($xe,{}),children:o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsx(Sn.Message,{className:"break-words whitespace-pre-wrap",children:e}),s&&t&&o.jsxs("div",{className:"flex flex-col gap-3",children:[o.jsxs("button",{type:"button",onClick:()=>r(!n),className:"text-ui-sm flex w-fit items-center gap-1.5 opacity-70 transition-opacity hover:opacity-100",children:[n?o.jsx(ka,{className:"size-3.5"}):o.jsx(aa,{className:"size-3.5"}),o.jsx("span",{children:"Details"})]}),n&&o.jsxs("div",{className:"text-ui-sm flex flex-col gap-2",children:[t.retry!==void 0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(a1,{className:"size-3.5 shrink-0 opacity-70"}),o.jsx("span",{children:"Retry"}),o.jsx(on,{size:"xs",variant:t.retry?"success":"error",children:t.retry?"Allowed":"Not allowed"})]}),t.processorId&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(KN,{className:"size-3.5 shrink-0 opacity-70"}),o.jsx("span",{children:"Processor"}),o.jsx(on,{size:"xs",variant:"warning",children:t.processorId})]}),t.metadata!==void 0&&t.metadata!==null&&o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsx("span",{className:"opacity-70",children:"Metadata"}),o.jsx("pre",{className:"overflow-x-auto rounded-lg bg-current/10 p-2 font-mono",children:JSON.stringify(t.metadata,null,2)})]})]})]})]})})},HEe=({text:e,metadata:t})=>{const[n,r]=v.useState(!1);if(t?.status==="tripwire")return o.jsx(L$t,{reason:e,tripwire:t.tripwire});if(t?.status==="warning")return o.jsx(Sn,{variant:"warning",title:"Warning",children:o.jsx(Sn.Message,{children:e})});if(t?.status==="error")return o.jsx(Sn,{variant:"destructive",title:"Error",children:o.jsx(Sn.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(k_,{className:X("transition-all",n?"rotate-90":"rotate-180")})}),o.jsxs(on,{variant:"info",icon:o.jsx(gO,{}),children:[n?"Show":"Hide"," completion check"]})]}),!n&&o.jsx(Sn,{variant:"info",title:s?.passed?"Complete":"Not Complete",children:o.jsx(Xp,{children:e})})]});const a=e.trim();return a.startsWith("__ERROR__:")?o.jsx(Sn,{variant:"destructive",title:"Error",children:o.jsx(Sn.Message,{children:a.substring(10)})}):a.startsWith("Error:")?o.jsx(Sn,{variant:"destructive",title:"Error",children:o.jsx(Sn.Message,{children:a.substring(6).trim()})}):o.jsx(Xp,{children:e})},mMr=({text:e})=>o.jsx(Sn,{variant:"destructive",title:"Error",children:o.jsx(Sn.Message,{children:e})}),z$t=({text:e})=>o.jsx(Sn,{variant:"warning",title:"Warning",children:o.jsx(Sn.Message,{children:e})}),F$t=({text:e,tripwire:t})=>o.jsx(L$t,{reason:e,tripwire:t}),cQe={Error:mMr,Warning:z$t,Tripwire:F$t},B$t=()=>{const e=Zo(),t=Ws(),[n]=v.useState(()=>e.state?.userMessage);return v.useEffect(()=>{n!==void 0&&t(".",{replace:!0,state:null})},[n,t]),n},U$t=v.createContext(null),gMr=({agentId:e,children:t})=>{const n=Bf(),{canWrite:r}=zy(),s=B$t(),{data:a,isLoading:i}=j4(e,{status:"draft"}),{data:l,isPending:c}=VI({enabled:n.tools}),{data:u,isPending:d}=Am({enabled:n.agents}),{data:f,isPending:p}=Ky({enabled:n.workflows}),{data:h,isPending:m}=oS({enabled:n.skills}),{data:g}=OZ(),{data:y,isLoading:b}=Im(),x=!a?.authorId||y?.id===a.authorId,S=!!a?.authorId&&b,k=!!e&&!i&&!S&&(!n.tools||!c)&&(!n.skills||!m)&&(!n.agents||!d)&&(!n.workflows||!p),C=v.useMemo(()=>(g?.workspaces??[]).filter(T=>T.status!=="archived").sort((T,N)=>(N.runtimeRegistered?1:0)-(T.runtimeRegistered?1:0)).map(T=>({id:T.id,name:T.name})),[g]),_=v.useMemo(()=>h?.skills??[],[h]),E=v.useMemo(()=>({agentId:e,storedAgent:a??void 0,toolsData:l??{},agentsData:u??{},workflowsData:f??{},availableSkills:_,availableWorkspaces:C,initialUserMessage:s,isOwner:x,canWrite:r,isReady:k}),[e,a,l,u,f,_,C,s,x,r,k]);return o.jsx(U$t.Provider,{value:E,children:t})},cC=()=>{const e=v.useContext(U$t);if(!e)throw new Error("useAgentPrimitives must be used inside <AgentPrimitivesProvider>");return e},WI=()=>{const e=We();return yt({queryKey:["tool-providers"],queryFn:()=>e.listToolProviders()})},vMr=3e4,yMr=e=>{const t=We(),n=WI(),r=v.useMemo(()=>n.data?.providers??[],[n.data?.providers]),s=Im(),a=s.data?.id,i=s.isSuccess||u2t(s.error),l=Nj({queries:r.map(m=>({queryKey:["tool-integration-services",m.id],queryFn:()=>t.getToolProvider(m.id).listToolkits()}))}),c=v.useMemo(()=>{const m=[];return r.forEach((g,y)=>{const b=l[y]?.data?.data??[];for(const x of b)m.push({providerId:g.id,toolkit:x.slug})}),m},[r,l]),u=Nj({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:vMr}))}),d=n.isLoading||s.isLoading||l.some(m=>m.isLoading)||u.some(m=>m.isLoading),f=v.useMemo(()=>{const m=new Map;return c.forEach((g,y)=>{const b=u[y]?.data?.items??[];m.set(`${g.providerId}:${g.toolkit}`,b)}),m},[c,u]),p=v.useCallback((m,g)=>(f.get(`${m}:${g}`)??[]).some(y=>y.status==="active"),[f]),h=v.useCallback((m,g)=>f.get(`${m}:${g}`)??[],[f]);return{hasConnection:p,getConnections:h,isLoading:d}},bMr=500,M4=()=>{const e=We(),t=WI(),n=v.useMemo(()=>t.data?.providers??[],[t.data?.providers]),r=Nj({queries:n.map(c=>({queryKey:["tool-integration-services",c.id],queryFn:()=>e.getToolProvider(c.id).listToolkits()}))}),s=v.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=Nj({queries:s.map(c=>({queryKey:["tool-integration-tools-all",c.providerId,c.toolkit],queryFn:()=>e.getToolProvider(c.providerId).listTools({toolkit:c.toolkit,perPage:bMr})}))}),i=t.isLoading||r.some(c=>c.isLoading)||a.some(c=>c.isLoading);return{tools:v.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 xMr(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 wMr=({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},SMr={};function Mse(e,t){const n={};for(const[r,s]of Object.entries(e))t.has(r)&&(n[r]=s);return n}function q$t({toolsData:e,agentsData:t,workflowsData:n,selectedTools:r,selectedAgents:s,selectedWorkflows:a,excludeAgentId:i}){const l=n??SMr,c=iTn(),{tools:u}=M4(),{hasConnection:d,getConnections:f}=yMr(),p=zn({name:"toolProviders"});return v.useMemo(()=>{const h=c.visibleTools===null?e:Mse(e,c.visibleTools),m=c.visibleAgents===null?t:Mse(t,c.visibleAgents),g=c.visibleWorkflows===null?l:Mse(l,c.visibleWorkflows),y=xMr(h,m,g,i),b=wMr({tools:y.tools,agents:y.agents,workflows:y.workflows,selected:{tools:r,agents:s,workflows:a}}),x=u.map(S=>({id:`${S.providerId}:${S.slug}`,name:S.slug,description:S.description,isChecked:!!p?.[S.providerId]?.tools?.[S.slug],type:"integration",providerId:S.providerId,toolkit:S.toolkit,hasConnection:d(S.providerId,S.toolkit),connectionLabels:f(S.providerId,S.toolkit).filter(k=>k.status==="active").map(k=>k.label||k.connectionId)}));return[...b,...x]},[e,t,l,r,s,a,i,c,u,p,d,f])}const kMr=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=OMr(i);if(l)return{summary:CMr(l),details:t}}catch{}const n=t.split(`
494
494
  `)[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}},OMr=e=>{const t=typeof e.message=="string"?e.message:void 0;if(t){const r=_Mr(t);return r||t}const n=e.error;if(n&&typeof n=="object"){const r=n.message;if(typeof r=="string")return r}},_Mr=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}},CMr=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()},EMr=({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}),V$t=({text:e})=>o.jsxs(ye,{variant:"ui-md",className:"text-neutral4 flex max-w-[80%] items-center gap-2 leading-relaxed whitespace-pre-wrap",as:"div",children:[o.jsx(ua,{className:"text-neutral3 size-4 animate-spin"}),o.jsx(EMr,{children:e})]}),TMr=e=>{switch(e){case"urgent":return"destructive";case"high":return"warning";case"medium":return"info";default:return"note"}},Hx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),H$t=e=>typeof e=="string"?e:Array.isArray(e)?e.flatMap(t=>Hx(t)?t.type==="text"&&typeof t.text=="string"&&t.text.length>0?[t.text]:[]:[]).join(`
495
495
  `):"",Jv=e=>{if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)},D4=e=>Hx(e)?e.type==="notification"||e.type==="state"||e.type==="reactive":!1,W$t=e=>{const t=e.content.metadata?.signal;return Hx(t)?t:void 0},WEe=e=>{const t=W$t(e)?.type;return typeof t=="string"?t:e.type},Z$t=e=>e==="user"||e==="user-message",jMr=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},G$t=e=>{const t=W$t(e)??{};return{id:typeof t.id=="string"?t.id:e.id,type:WEe(e),tagName:typeof t.tagName=="string"?t.tagName:e.type,contents:jMr(e.content.parts),...Hx(t.attributes)?{attributes:t.attributes}:{},...Hx(t.metadata)?{metadata:t.metadata}:{}}},Q$t=e=>{const t=Hx(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}},NMr=e=>{const t=Q$t(e);if(t?.signal==="summary"||e.tagName==="notification-summary")return"Notification summary";const n=t?.source??Jv(e.attributes?.source),r=t?.kind??Jv(e.attributes?.kind);return n&&r?`${n} / ${r}`:n??r??"Notification"},IMr=({signal:e})=>{const t=Q$t(e),n=t?.priority??Jv(e.attributes?.priority),r=Jv(t?.pending)??Jv(e.attributes?.pending),s=t?.status??Jv(e.attributes?.status),a=H$t(e.contents),i=r?`${r} pending`:void 0,l=!!(n||s||i),c=a.length>0;return o.jsx(Sn,{variant:TMr(n),title:NMr(e),icon:o.jsx(vWt,{}),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(on,{size:"xs",children:n}):null,s?o.jsx(on,{size:"xs",children:s}):null,i?o.jsx(on,{size:"xs",children:i}):null]}):null,c?o.jsx(Sn.Message,{className:"break-words whitespace-pre-wrap",children:a}):null]}):null})},AMr=e=>{const t=Hx(e.metadata?.state)?e.metadata.state:void 0;return{id:Jv(t?.id)??Jv(e.attributes?.id)??"State signal",mode:Jv(t?.mode)??Jv(e.attributes?.mode)}},RMr=({children:e})=>o.jsx("span",{className:"border-border1 text-neutral4 inline-flex items-center rounded-full border px-1.5 py-0.5 text-xs leading-none",children:e});function PMr(e){return Array.isArray(e)&&e.every(t=>Hx(t)&&typeof t.id=="string"&&typeof t.content=="string"&&(t.status==="pending"||t.status==="in_progress"||t.status==="completed")&&typeof t.activeForm=="string")}function $Mr(e){if(!(e.id==="tasks"||e.tagName==="current-task-list"||e.tagName==="task-list-update"))return;const n=e.metadata,s=(Hx(n?.value)?n.value:void 0)?.tasks;if(PMr(s))return s}const Y$t=({signal:e})=>{if(!D4(e))return null;const t=H$t(e.contents);if(e.type==="state"){if($Mr(e))return null;const r=AMr(e);return o.jsx("div",{className:"border-border1 bg-surface2 text-neutral5 my-2 max-w-[80%] rounded-lg border px-4 py-3",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(py,{className:"text-icon3 mt-0.5 h-4 w-4 shrink-0"}),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 text-neutral6 font-medium",children:r.id}),r.mode?o.jsx(RMr,{children:r.mode}):null]}),t?o.jsx("p",{className:"text-ui-sm leading-ui-md mt-2 break-words whitespace-pre-wrap",children:t}):null]})]})})}return e.type==="notification"?o.jsx(IMr,{signal:e}):e.type==="reactive"?o.jsx("div",{className:"border-border1 bg-surface2 text-neutral5 my-2 max-w-[80%] rounded-lg border px-4 py-3",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(Got,{className:"text-icon3 mt-0.5 h-4 w-4 shrink-0"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("p",{className:"text-ui-sm leading-ui-sm text-neutral6 font-medium",children:e.tagName??"Signal"}),t?o.jsx("p",{className:"text-ui-sm leading-ui-md mt-2 break-words whitespace-pre-wrap",children:t}):null]})]})}):null},uQe=({toolCallId:e,toolName:t})=>{const{approveToolCall:n,declineToolCall:r}=UNr(),[s,a]=v.useState(null),i=s!==null,l=()=>{a("approve"),n(e)},c=()=>{a("decline"),r(e)};return o.jsxs(X$t,{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:"text-neutral6 font-mono",children:t})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ce,{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(ua,{className:"animate-spin"}):o.jsx(fa,{})}),"Approve"]}),o.jsxs(ce,{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(ua,{className:"animate-spin"})}),"Decline"]})]})]})},K$t=e=>e.role==="assistant"||e.role==="user"||e.role==="system"?e.role:e.role==="signal"?Z$t(WEe(e))?"user":"assistant":null,MMr=e=>{const t=G$t(e);return D4(t)?{...e,role:"assistant",content:{...e.content,parts:[{type:"data-signal",data:t}]}}:null},DMr=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},LMr=e=>!e||typeof e!="object"||!("name"in e)?"unknown":typeof e.name=="string"?e.name:"unknown",dQe=(e,t,n)=>{if(e)return(t?e[t]:void 0)??(n?e[n]:void 0)},zMr=e=>{const t=K$t(e);return t===null?null:e.role==="signal"&&t==="assistant"?MMr(e):t===e.role?e:{...e,role:t}},fQe=(e,t,n)=>{switch(e){case EEe:return o.jsx(HMr,{});case OEe:return o.jsx(WMr,{});case _Ee:return o.jsx(ZMr,{});case jEe:return o.jsx(GMr,{});case TEe:return o.jsx(QMr,{});case CEe:return o.jsx(YMr,{});case kEe:return o.jsx(KMr,{});case NEe:return o.jsx(XMr,{});case"skill":return o.jsx(JMr,{name:LMr(t)});default:return o.jsx(VMr,{toolName:e,input:t,output:n})}},FMr=({message:e})=>{const t=DMr(e),n=qNr(),r=K$t(e),s=zMr(e);if(s===null)return null;const a=e.content.metadata,i={Text:c=>o.jsx(BMr,{txt:c.text??"",role:r,metadata:a}),Reasoning:c=>("state"in c?c.state:void 0)!=="streaming"?null:o.jsx(V$t,{text:"Reasoning..."}),Data:c=>c.type==="data-signal"&&D4(c.data)?o.jsx(Y$t,{signal:c.data}):null,ToolInvocation:c=>{const u=c.toolInvocation,d=dQe(t,u.toolName,u.toolCallId);if(d&&u.state!=="result")return o.jsx(uQe,{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 fQe(u.toolName,f,p)},DynamicTool:c=>{const u=c.toolName??c.type.replace(/^tool-/,""),d=dQe(t,u,c.toolCallId);return d&&c.state!=="output-available"?o.jsx(uQe,{toolCallId:d.toolCallId,toolName:d.toolName}):c.state!=="output-available"?null:fQe(u,c.input,c.output)}},l={Error:({text:c})=>o.jsx(UMr,{error:kMr(c),onRetry:n}),Warning:z$t,Tripwire:F$t};return o.jsx(A9,{message:s,...i,status:l})},BMr=({txt:e,role:t,metadata:n})=>t==="user"?o.jsx("div",{className:"flex justify-end",children:o.jsx(ye,{variant:"ui-md",className:"max-w-[80%] rounded-2xl bg-white px-4 py-2.5 text-black [&_li]:!my-0 [&_li]:!leading-normal [&_ol]:!space-y-1 [&_p]:!leading-normal [&_p]:!whitespace-normal [&_ul]:!space-y-1",as:"div",children:o.jsx(Xp,{children:e})})}):t==="assistant"||t==="system"?o.jsx(ye,{variant:"ui-md",className:"text-neutral4 max-w-[80%] [&_li]:!my-0 [&_li]:!leading-normal [&_ol]:!space-y-1 [&_p]:!leading-normal [&_p]:!whitespace-normal [&_ul]:!space-y-1",as:"div",children:o.jsx(HEe,{text:e,metadata:n})}):null,UMr=({error:e,onRetry:t})=>o.jsxs(tC,{className:"border-accent6/40 bg-accent6/5 flex max-w-[80%] flex-col gap-3 p-4",role:"alert","data-testid":"agent-builder-chat-error",children:[o.jsxs("div",{className:"flex items-start gap-2.5",children:[o.jsx(Rd,{className:"text-accent6 mt-0.5 size-4 shrink-0","aria-hidden":!0}),o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",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(Pf,{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[t!==null&&o.jsxs(ce,{variant:"default",onClick:t,className:"gap-1.5","data-testid":"agent-builder-chat-error-retry",children:[o.jsx(a1,{className:"size-3.5","aria-hidden":!0}),"Try again"]}),o.jsx(Fd,{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(Bd,{children:o.jsx("pre",{className:"text-neutral4 bg-surface1 max-h-48 overflow-auto rounded-md p-2 text-xs break-all whitespace-pre-wrap","data-testid":"agent-builder-chat-error-details",children:e.details})})]}):t!==null&&o.jsx("div",{className:"flex items-center gap-3",children:o.jsxs(ce,{variant:"default",onClick:t,className:"gap-1.5","data-testid":"agent-builder-chat-error-retry",children:[o.jsx(a1,{className:"size-3.5","aria-hidden":!0}),"Try again"]})})]}),qMr=({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(kt,{className:"h-10 w-56 rounded-2xl"})}),o.jsx(kt,{className:"h-6 w-[70%] rounded-full"}),o.jsx(kt,{className:"h-6 w-[55%] rounded-full"}),o.jsx("div",{className:"flex justify-end",children:o.jsx(kt,{className:"h-10 w-40 rounded-2xl"})}),o.jsx(kt,{className:"h-6 w-[65%] rounded-full"})]}),pQe=e=>{if(e===void 0)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}},VMr=({toolName:e,input:t,output:n})=>{const r=pQe(t),s=pQe(n),a=s.length>0;return o.jsx(X$t,{testId:"agent-builder-chat-generic-tool",children:o.jsxs(Pf,{children:[o.jsxs(Fd,{className:"group flex w-full items-center gap-2 text-left","data-testid":"agent-builder-chat-generic-tool-trigger",children:[o.jsxs("span",{className:"border-border1/60 bg-surface1 inline-flex items-center gap-1.5 rounded-md border px-2 py-0.5",children:[o.jsx(Vp,{className:"text-neutral4 size-3.5 shrink-0","aria-hidden":!0}),o.jsxs(ye,{variant:"ui-sm",className:"text-neutral5",as:"span",children:["Executing ",o.jsx("span",{className:"text-neutral6 font-mono",children:e})]})]}),o.jsx(aa,{className:"text-neutral4 size-4 shrink-0 transition-transform group-data-[state=open]:rotate-90","aria-hidden":!0})]}),o.jsx(Bd,{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:"border-border1/60 bg-surface1 overflow-hidden rounded-md border",children:[o.jsx("div",{className:"border-border1/60 border-b px-2 py-1",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",as:"div",children:"Input"})}),o.jsx("pre",{className:"text-neutral5 m-0 max-h-[320px] overflow-auto p-3 text-xs leading-relaxed break-words whitespace-pre-wrap",children:r||"{}"})]}),a?o.jsxs("div",{className:"border-border1/60 bg-surface1 overflow-hidden rounded-md border",children:[o.jsx("div",{className:"border-border1/60 border-b px-2 py-1",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",as:"div",children:"Output"})}),o.jsx("pre",{className:"text-neutral5 m-0 max-h-[320px] overflow-auto p-3 text-xs leading-relaxed break-words whitespace-pre-wrap",children:s})]}):null]})})]})})},X$t=({children:e,testId:t,className:n})=>o.jsx(tC,{"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}),m0=({icon:e,label:t,value:n})=>o.jsxs("div",{className:"animate-in fade-in slide-in-from-right-4 flex max-w-full min-w-0 items-start gap-2 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:"text-neutral6 font-semibold",children:n})]})]}),HMr=()=>{const{watch:e}=Ur(),t=e("name");return t?o.jsx(m0,{icon:o.jsx(_ot,{}),label:"Setting the agent name:",value:t}):null},WMr=()=>{const{watch:e}=Ur(),t=e("description");return t?o.jsx(m0,{icon:o.jsx(_ot,{}),label:"Setting the agent description:",value:t}):null},ZMr=()=>{const{watch:e}=Ur(),t=e("instructions");return t?o.jsx(m0,{icon:o.jsx(Nc,{}),label:"Setting the agent instructions:",value:t}):null},GMr=()=>{const{agentId:e,toolsData:t,agentsData:n,workflowsData:r}=cC(),{watch:s}=Ur(),a=s("tools"),i=s("agents"),l=s("workflows"),u=q$t({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(m0,{icon:o.jsx(Vp,{}),label:"Enabling tools:",value:d})},QMr=()=>{const{availableSkills:e}=cC(),{watch:t}=Ur(),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(m0,{icon:o.jsx(Fxe,{}),label:"Enabling skills:",value:s})},YMr=()=>{const{watch:e}=Ur(),t=e("model");return t?o.jsx(m0,{icon:o.jsx(qI,{providerId:t.provider,size:16}),label:"Setting agent model to",value:`${t.provider}/${t.name}`}):null},KMr=()=>{const{watch:e}=Ur(),t=e("browserEnabled");return o.jsx(m0,{icon:t?o.jsx(Kx,{}):o.jsx(hGt,{}),label:"Browser access",value:t?"enabled":"disabled"})},XMr=()=>{const{watch:e}=Ur(),t=e("workspaceId");return t?o.jsx(m0,{icon:o.jsx(Not,{}),label:"Setting workspace to",value:t}):null},JMr=({name:e})=>o.jsx(m0,{icon:o.jsx(Fxe,{}),label:"Using super-powers:",value:e}),eDr=e=>{const t=v.useRef(null);return v.useEffect(()=>{const n=t.current;n&&n.scrollTo({top:n.scrollHeight,behavior:"smooth"})},[e]),t},tDr=(e,t)=>{const[n,r]=v.useState(!1);return v.useEffect(()=>{if(!e){r(!1);return}const s=setTimeout(()=>r(!0),t);return()=>clearTimeout(s)},[e,t]),n},nDr=300,rDr=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,ZEe=({messages:e,isLoading:t=!1,isRunning:n=!1,emptyState:r,skeletonTestId:s})=>{const a=eDr(e),i=t&&e.length===0,l=tDr(i,nDr),c=!t&&e.length===0&&r!==void 0,u=e[e.length-1],d=n&&!i&&(u?.role!=="assistant"||!rDr(u));return o.jsx("div",{ref:a,className:"min-h-0 flex-1 overflow-y-auto px-6 py-6",style:{viewTransitionName:"agent-builder-messages"},children:l?o.jsx(qMr,{testId:s}):c?r:o.jsxs("div",{className:"flex flex-col gap-6",children:[e.map(f=>o.jsx(FMr,{message:f},f.id)),d&&o.jsx(U2t,{testId:"agent-builder-chat-pending"})]})})},hQe="builder-agent",sDr=e=>`agent-builder-${e}`,aDr=({initialUserMessage:e,isFreshThread:t=!1,features:n,availableAgentTools:r=[],availableWorkspaces:s=[],availableSkills:a=[],toolsReady:i=!0,agentId:l,children:c})=>{const u=sDr(l),{data:d,isLoading:f}=uW({agentId:hQe,threadId:u,memory:!t}),p=v.useMemo(()=>[],[l]),h=d?.messages??p,m=(d?.messages?.length??0)>0,{models:g,isLoading:y}=iS(),b=n.model?g:[],{isLoading:x}=M4(),S=i&&(!n.model||!y)&&!x,k=sIr({features:n,availableAgentTools:r,availableWorkspaces:s,availableSkills:a,availableModels:b,integrationToolsLoading:x}),{control:C}=Ur(),_=zn({control:C}),E=IIr({availableWorkspaces:s}),T=v.useMemo(()=>({...k,...n.skills?{[F2t]:E}:{}}),[k,E,n.skills]),N=v.useMemo(()=>({isLoading:f,agentId:l}),[f,l]),I=S&&!f&&!m?e:void 0,A=YNr(_,{availableAgentTools:r,availableSkills:a,availableWorkspaces:s,availableModels:b,features:n,starterUserMessage:e});return o.jsx(T2t,{agentId:hQe,threadId:u,initialMessages:h,initialUserMessage:I,clientTools:T,extraInstructions:A,debounceTime:1e3,children:o.jsx(J$t.Provider,{value:N,children:c})})},J$t=v.createContext({isLoading:!1,agentId:""}),iDr=()=>o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[o.jsx(oDr,{}),o.jsx(lDr,{})]}),oDr=()=>{const e=wEe(),t=bu(),{isLoading:n}=v.useContext(J$t);return o.jsx(ZEe,{messages:e,isLoading:n,isRunning:t,skeletonTestId:"agent-builder-conversation-messages-skeleton"})},lDr=()=>{const e=E2t(),t=SEe(),{draft:n,setDraft:r,trimmed:s,handleFormSubmit:a,handleKeyDown:i}=j2t({onSubmit:t});return o.jsx(REe,{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 cDr(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 uDr(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 uF(e,t){return Object.fromEntries(Object.entries(e??{}).filter(([,n])=>n).map(([n])=>{const r=t.get(n);return[n,r?{description:r}:{}]}))}function dDr(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=uF(e.tools,r),c=uF(e.agents,s),u=uF(e.workflows,a),d=uF(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,g=cDr(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:g}}function fDr(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 pDr({agentId:e,availableAgentTools:t=[],availableSkills:n=[],onSuccess:r,silent:s=!1}){const{updateStoredAgent:a}=P1(e),i=R4();return{save:v.useCallback(async c=>{const u=dDr(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 g=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),g}catch(g){const y=fDr(g);throw y?De.error(y.message):De.error(`Failed to save agent: ${g instanceof Error?g.message:"Unknown error"}`),g}},[e,t,n,a,r,i,s]),isSaving:a.isPending}}const hDr=600,mDr=2e3;function gDr({agentId:e,availableAgentTools:t=[],availableSkills:n=[],debounceMs:r=hDr,savedDisplayMs:s=mDr}){const a=Ur(),{save:i}=pDr({agentId:e,availableAgentTools:t,availableSkills:n,silent:!0}),[l,c]=v.useState("idle"),[u,d]=v.useState(null),f=v.useRef(a.getValues()),p=v.useRef(0),h=v.useRef(null),m=v.useCallback(()=>{h.current&&(clearTimeout(h.current),h.current=null)},[]),g=v.useCallback(async()=>{const S=++p.current,k=f.current;m(),c("saving"),d(null);try{if(await i(k),S!==p.current)return;c("saved"),h.current=setTimeout(()=>{h.current=null,c("idle")},s)}catch(C){if(S!==p.current)return;c("error"),d(C instanceof Error?C:new Error(String(C)))}},[m,i,s]),y=Uy(()=>{g()},r);v.useEffect(()=>{const S=a.watch(k=>{f.current=k,y()});return()=>{S.unsubscribe()}},[a,y]),v.useEffect(()=>()=>{y.flush(),m()},[m,y]);const b=v.useCallback(()=>{g()},[g]),x=v.useCallback(()=>{y.flush()},[y]);return{status:l,lastError:u,retry:b,flushNow:x}}const eMt=v.createContext(null),vDr=({storedAgent:e,availableAgentTools:t,onModeToggle:n,children:r})=>{const{agentId:s,availableSkills:a,availableWorkspaces:i,initialUserMessage:l,isOwner:c}=cC(),u=Bf(),d=c&&e.visibility==="public",f=l!==void 0,p=gDr({agentId:s,availableAgentTools:t,availableSkills:a}),h=v.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(eMt.Provider,{value:h,children:o.jsx(aDr,{agentId:s,features:u,availableAgentTools:t,availableWorkspaces:i,availableSkills:a,initialUserMessage:l,isFreshThread:f,toolsReady:!0,children:r})})},g0=()=>{const e=v.useContext(eMt);if(!e)throw new Error("useEditPage must be used inside <EditPageProvider>");return e};function yDr({platform:e,agentId:t,onCancel:n,onClose:r}){const{mutateAsync:s,isPending:a}=b2t(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(br,{children:[o.jsx(hr,{children:"Are you sure?"}),o.jsxs(Bs,{children:["Your agent will be removed from ",o.jsx("span",{className:"text-neutral6",children:e.name}),"."]})]}),o.jsxs(ic,{children:[o.jsx(ce,{variant:"ghost",onClick:n,disabled:a,children:"Cancel"}),o.jsx(ce,{variant:"default",onClick:i,disabled:a,"data-testid":`publish-channel-dialog-${e.id}-disconnect-confirm`,children:a?"Disconnecting…":"Confirm"})]})]})}const bDr=({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"})]}),xDr=({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"})}),wDr=({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"})}),SDr=({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"})}),kDr={slack:bDr,discord:xDr,telegram:wDr};function GEe({platform:e,className:t}){const n=kDr[e.toLowerCase()]??SDr;return o.jsx(n,{className:t})}const ODr={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"},_Dr={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 CDr(e){return{...ODr,..._Dr[e]??{}}}function EDr({platform:e,agentId:t,installation:n,onClose:r,onDisconnectRequest:s}){const{connect:a,isConnecting:i}=xEe(e.id,{onClose:r}),l=CDr(e.id),c=l.requireActiveInstallation&&n?.status!=="active"?void 0:n,u=()=>{a(t)};return o.jsxs(o.Fragment,{children:[o.jsxs(br,{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(GEe,{platform:e.id,className:"h-8 w-8 shrink-0"}),o.jsxs(hr,{children:[e.name," integration"]})]}),o.jsx(Bs,{children:l.description(e.name)})]}),o.jsx(Rr,{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(ic,{children:e.isConfigured&&c?o.jsx(ce,{variant:"default",onClick:s,"data-testid":`publish-channel-dialog-${e.id}-disconnect`,children:"Disconnect"}):e.isConfigured?o.jsx(ce,{variant:"default",onClick:u,disabled:i,"data-testid":`publish-channel-dialog-${e.id}-connect`,children:i?"Connecting…":l.connectLabel}):o.jsx(ce,{variant:"default",onClick:r,children:"Close"})})]})}function TDr({platform:e,agentId:t,installation:n,open:r,onOpenChange:s,initialView:a="publish"}){const[i,l]=v.useState(a);v.useEffect(()=>{r&&l(a)},[r,a]);const c=()=>s(!1);return o.jsx(vr,{open:r,onOpenChange:s,children:o.jsx(yr,{"data-testid":`publish-channel-dialog-${e.id}`,children:i==="publish"?o.jsx(EDr,{platform:e,agentId:t,installation:n,onClose:c,onDisconnectRequest:()=>l("confirm-disconnect")}):o.jsx(yDr,{platform:e,agentId:t,onCancel:()=>l("publish"),onClose:c})})})}function jDr(e){const{canPublishToChannel:t}=g0(),n=Ur(),{updateStoredAgent:r}=P1(e),[s,a]=v.useState(null),[i,l]=v.useState(!1),[c,u]=v.useState(null),d=xEe("slack"),f=v.useCallback(x=>{const{platform:S,installation:k}=x;if(S.id==="slack"&&S.isConfigured&&!k){d.connect(e);return}u(x)},[e,d]),p=v.useCallback((x,S)=>{const k={platform:x,installation:S};if(t){f(k);return}a(k),l(!0)},[t,f]),h=v.useCallback(()=>{l(!1),a(null)},[]),m=v.useCallback(async()=>{if(s)try{await r.mutateAsync({visibility:"public"}),n.setValue("visibility","public",{shouldDirty:!1}),De.success("Agent added to the library");const x=s;l(!1),a(null),f(x)}catch(x){De.error(`Failed to add to library: ${x instanceof Error?x.message:"Unknown error"}`)}},[s,r,n,f]),g=s?.platform.name??"this channel",y=v.useMemo(()=>o.jsx(vr,{open:i,onOpenChange:x=>!x&&h(),children:o.jsxs(yr,{"data-testid":"agent-builder-publish-before-connect-dialog",children:[o.jsxs(br,{children:[o.jsxs(hr,{children:["Add this agent to your library to connect ",g,"?"]}),o.jsxs(Bs,{children:["Connecting to ",g," 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 ",g,"."]})]}),o.jsxs(ic,{children:[o.jsx(ce,{variant:"ghost",onClick:h,disabled:r.isPending,"data-testid":"agent-builder-publish-before-connect-dialog-cancel",children:"Cancel"}),o.jsx(ce,{variant:"default",onClick:m,disabled:r.isPending,"data-testid":"agent-builder-publish-before-connect-dialog-confirm",children:"Add to library & continue"})]})]})}),[i,h,m,g,r.isPending]),b=c?o.jsx(TDr,{platform:c.platform,agentId:e,installation:c.installation,open:!0,onOpenChange:x=>{x||u(null)}}):null;return{requestPublishAndConnect:p,dialog:y,channelDialog:b}}const NDr={slack:"Creates a Slack bot powered by this agent."},tMt=({agentId:e,editable:t=!0})=>{const{data:n=[],isLoading:r}=kZ(),{canPublishToChannel:s}=g0(),{requestPublishAndConnect:a,dialog:i,channelDialog:l}=jDr(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(kt,{className:"h-6 w-48"}),o.jsx(kt,{className:"h-4 w-80"})]}),o.jsxs("div",{className:"flex flex-wrap items-stretch justify-center gap-4",children:[o.jsxs("div",{className:"border-border1 bg-surface3 flex w-48 flex-col items-center gap-3 rounded-xl border px-4 py-6",children:[o.jsx(kt,{className:"size-14 rounded-xl"}),o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsx(kt,{className:"h-4 w-24"}),o.jsx(kt,{className:"h-3 w-32"})]}),o.jsx(kt,{className:"h-badge-default w-20 rounded-full"})]}),o.jsxs("div",{className:"border-border1 bg-surface3 flex w-48 flex-col items-center gap-3 rounded-xl border px-4 py-6",children:[o.jsx(kt,{className:"size-14 rounded-xl"}),o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsx(kt,{className:"h-4 w-24"}),o.jsx(kt,{className:"h-3 w-32"})]}),o.jsx(kt,{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:"text-neutral6 font-semibold",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(IDr,{platform:c,agentId:e,disabled:!t,requiresLibrary:!s,onSelect:u=>a(c,u)},c.id))})]}),i,l]})},IDr=({platform:e,agentId:t,disabled:n,requiresLibrary:r,onSelect:s})=>{const{data:a=[]}=y2t(e.id,t),i=a.find(u=>u.status==="active"),l=NDr[e.id],c=e.isConfigured&&r;return o.jsxs("button",{type:"button",onClick:()=>s(i),disabled:n,"data-testid":`integration-card-${e.id}`,className:"border-border1 bg-surface3 hover:bg-surface4 focus-visible:ring-accent1 flex w-48 flex-col items-center gap-3 rounded-xl border px-4 py-6 text-center transition-colors focus-visible:ring-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-60",children:[o.jsx("div",{className:"bg-surface4 grid size-14 place-items-center rounded-xl",children:o.jsx(GEe,{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:"text-neutral6 font-semibold",children:e.name}),l?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:l}):null]}),e.isConfigured?i?o.jsx(Og,{variant:"success",size:"sm",withDot:!0,children:"Connected"}):o.jsx(Og,{variant:"neutral",size:"sm",withDot:!0,children:"Not connected"}):o.jsx(Og,{variant:"warning",size:"sm",withDot:!0,children:"Not configured"}),c?o.jsx(Og,{variant:"warning",size:"sm",withDot:!0,children:"Add to library to connect"}):null]})},ADr=X("group/input-group relative flex w-full flex-1 items-center","border border-border1 text-neutral6",xs.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"),nMt=X("has-[>[data-align=block-start]]:rounded-xl","has-[>[data-align=block-end]]:rounded-xl","has-[textarea]:rounded-xl"),mQe=X("rounded-full bg-surface-overlay-soft","hover:bg-surface-overlay-strong",Vgt,"outline-hidden focus-within:bg-surface-overlay-strong focus-within:outline-hidden",Ugt,nMt),RDr=co(ADr,{variants:{variant:{default:mQe,filled:mQe,outline:X("rounded-full bg-transparent",Vgt,"outline-hidden focus-within:outline-hidden",Ugt,nMt)}},defaultVariants:{variant:"default"}}),zu=v.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(RDr({variant:n}),PP[t],e),...r}));zu.displayName="InputGroup";const PDr=co(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"}}),ru=v.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(PDr({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}));ru.displayName="InputGroupAddon";const $Dr=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"),rMt=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"),Fu=v.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",$Dr,rMt,"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}));Fu.displayName="InputGroupInput";const MDr=v.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",rMt,"placeholder:duration-normal placeholder:text-neutral2 placeholder:transition-opacity","focus:placeholder:opacity-70","disabled:cursor-not-allowed",e),...r}));MDr.displayName="InputGroupTextarea";const DDr=v.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}));DDr.displayName="InputGroupText";const sMt=v.forwardRef(({size:e="icon-sm",variant:t="ghost",type:n="button",...r},s)=>o.jsx(ce,{ref:s,type:n,size:e,variant:t,...r}));sMt.displayName="InputGroupButton";const aMt=({title:e,subtitle:t,icon:n,isSelected:r,disabled:s=!1,onClick:a,ariaLabel:i,testId:l,checkTestId:c,footer:u})=>{const d=p0(),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:"text-neutral6 truncate font-medium",children:e}),t&&o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 truncate",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(fa,{className:"h-3 w-3"})})]}),u]})},LDr=({title:e,items:t,isChecked:n,onToggle:r,onSelectAll:s,onClearAll:a,disabled:i=!1,testIdPrefix:l})=>{const c=p0(),[u,d]=v.useState(""),f=v.useMemo(()=>{const p=u.trim().toLowerCase();return p?t.filter(h=>h.label.toLowerCase().includes(p)):t},[t,u]);return o.jsxs("div",{className:"border-border1 flex h-full min-h-0 flex-col gap-3 border-r px-6 py-6","data-testid":`${l}-filter`,children:[o.jsx("div",{className:"bg-surface3 shrink-0 rounded-full","data-testid":`${l}-filter-search`,children:o.jsxs(zu,{variant:"outline",size:"lg",children:[o.jsx(ru,{align:"inline-start",children:o.jsx(Xa,{})}),o.jsx(Fu,{type:"search","aria-label":`Filter ${e.toLowerCase()}`,placeholder:`Filter ${e.toLowerCase()}...`,onChange:p=>d(p.target.value)})]})}),o.jsxs("div",{className:"text-ui-xs flex shrink-0 items-center gap-2",children:[o.jsx("button",{type:"button",onClick:s,disabled:i,"data-testid":`${l}-filter-select-all`,className:"text-neutral3 hover:text-neutral6 transition-colors 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 hover:text-neutral6 transition-colors disabled:cursor-not-allowed disabled:opacity-60",children:"Clear all"})]}),o.jsx(Fr,{className:"min-h-0 flex-1",viewPortClassName:"pr-2",children:f.length===0?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 px-1 py-2",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(qo,{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 data-[state=checked]:shadow-none [&_svg]:h-2.5 [&_svg]:w-2.5"}),p.icon&&o.jsx("span",{className:"flex shrink-0 items-center",children:p.icon}),o.jsx("span",{className:"truncate",children:p.label})]})},p.id)})})})]})},iMt=({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:"border-border1 flex h-full min-h-0 flex-col gap-3 border-r px-6 py-6",children:[o.jsx(kt,{className:"h-10 w-full rounded-md"}),o.jsx(kt,{className:"h-4 w-28"}),o.jsx(kt,{className:"h-7 w-full rounded-md"}),o.jsx(kt,{className:"h-7 w-full rounded-md"}),o.jsx(kt,{className:"h-7 w-full rounded-md"}),o.jsx(kt,{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:"max-w-[30ch] shrink-0",children:o.jsx(kt,{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(kt,{className:"h-4 w-24"}),o.jsxs("div",{className:"grid grid-cols-1 content-start gap-2 sm:grid-cols-2 lg:gap-6 2xl:grid-cols-3",children:[o.jsx(kt,{className:"h-20 rounded-lg"}),o.jsx(kt,{className:"h-20 rounded-lg"}),o.jsx(kt,{className:"h-20 rounded-lg"}),o.jsx(kt,{className:"h-20 rounded-lg"}),o.jsx(kt,{className:"h-20 rounded-lg"}),o.jsx(kt,{className:"h-20 rounded-lg"})]})]})})]})]})}),oMt=({editable:e=!0})=>{const t=n0();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(UDr,{provider:r,modelId:s})})}return o.jsx("div",{className:"h-full min-h-0 overflow-hidden","data-testid":"model-detail-picker",children:o.jsx(zDr,{disabled:!e})})},zDr=({disabled:e=!1})=>{const{setValue:t,control:n}=Ur(),r=zn({control:n,name:"model"}),s=n0(),{models:a,isLoading:i}=iS(),[l,c]=v.useState(""),[u,d]=v.useState(null),f=v.useMemo(()=>{const T=new Map;for(const N of a){const I=gi(N.provider);T.has(I)||T.set(I,N.providerName)}return Array.from(T.entries()).map(([N,I])=>({providerId:N,providerName:I})).sort((N,I)=>N.providerName.localeCompare(I.providerName))},[a]),p=T=>u===null||u.has(T),h=T=>{d(N=>{const I=N??new Set(f.map(R=>R.providerId)),A=new Set(I);return A.has(T)?A.delete(T):A.add(T),A})},m=()=>{d(new Set(f.map(T=>T.providerId)))},g=()=>{d(new Set)},y=v.useMemo(()=>f.map(({providerId:T,providerName:N})=>({id:T,label:N,icon:o.jsx(qI,{providerId:T,size:18})})),[f]);if(i)return o.jsx(iMt,{testId:"model-card-picker-loading"});const b=gi(r?.provider??""),x=r?.name??"",S=!!(b&&x),k=a.some(T=>gi(T.provider)===b&&T.model===x),C=S&&s.active&&!k,_=qDr(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(LDr,{title:"Providers",items:y,isChecked:p,onToggle:h,onSelectAll:m,onClearAll:g,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:"bg-surface3 max-w-[30ch] shrink-0 rounded-full",children:o.jsxs(zu,{variant:"outline",size:"lg",children:[o.jsx(ru,{align:"inline-start",children:o.jsx(Xa,{})}),o.jsx(Fu,{type:"search","aria-label":"Search models",placeholder:"Search models or providers...",onChange:T=>c(T.target.value)})]})}),_.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(FDr,{groups:_,selectedProvider:b,selectedModel:x,disabled:e,onChange:(T,N)=>t("model",{provider:T,name:N},{shouldDirty:!0})})]})]}),C&&o.jsx(BDr,{provider:b,modelId:x})]})},FDr=({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 tracking-wide uppercase","data-testid":`model-provider-section-title-${a.providerId}`,children:a.providerName}),o.jsx("div",{className:"grid grid-cols-1 content-start gap-2 sm:grid-cols-2 lg:gap-6 2xl:grid-cols-3",children:a.models.map(i=>{const c=gi(i.provider)===t&&i.model===n;return o.jsx(aMt,{icon:o.jsx(qI,{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))}),BDr=({provider:e,modelId:t})=>o.jsxs("div",{className:"border-accent6 bg-accent6Dark/40 text-accent6 mx-6 mb-6 flex items-start gap-2 rounded-md border px-3 py-2","data-testid":"model-detail-stale-warning",role:"alert",children:[o.jsx(Rd,{className:"mt-0.5 h-4 w-4 shrink-0"}),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."]})]}),UDr=({provider:e,modelId:t})=>o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center gap-2 rounded-md border px-3 py-2","data-testid":"model-detail-locked-chip",children:[o.jsx(Tf,{className:"text-neutral3 h-4 w-4 shrink-0"}),o.jsx(ye,{variant:"ui-sm",className:"text-neutral6 truncate font-medium",children:e&&t?`${e}/${t}`:"Locked by admin"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 ml-auto shrink-0",children:"Set by admin"})]});function qDr(e,t,n,r){const s=n.toLowerCase(),a=e.filter(l=>{const c=gi(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=gi(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 lMt=({editable:e=!0,availableSkills:t=[]})=>{const{setValue:n,getValues:r,watch:s}=Ur(),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(HDr,{}):o.jsx("ul",{className:"flex flex-col",children:t.map(l=>{const c=!!a[l.id];return o.jsx("li",{children:o.jsx(VDr,{skill:l,editable:e,onToggle:i,isChecked:c})},l.id)})})})},VDr=({skill:e,editable:t,onToggle:n,isChecked:r})=>o.jsxs("label",{className:"hover:bg-surface2 flex cursor-pointer items-start gap-3 px-6 py-4 transition-colors","aria-disabled":!t,children:[o.jsx("div",{className:"mt-0.5",children:o.jsx(qo,{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:"text-neutral6 font-medium",children:e.name}),e.description&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-0.5 truncate",title:e.description,children:e.description})]})]}),HDr=()=>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."})}),WDr=({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(aMt,{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:"text-neutral3 flex h-7 items-center","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(on,{className:"h-auto py-0.5 text-[10px]",children:l},l))}):o.jsx("div",{className:"h-7"}):void 0})},ZDr=({tools:e,editable:t,onlySelected:n,onOnlySelectedChange:r,onSearch:s,emptyStateDetails:a,onToggle:i})=>{const l=p0(),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:"bg-surface3 max-w-[30ch] flex-1 rounded-full",children:o.jsxs(zu,{variant:"outline",size:"lg",children:[o.jsx(ru,{align:"inline-start",children:o.jsx(Xa,{})}),o.jsx(Fu,{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(qo,{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 data-[state=checked]:shadow-none [&_svg]:h-2.5 [&_svg]:w-2.5"}),o.jsx("span",{children:"Show only selected"})]})]}),e.length===0?o.jsx(cMt,{details:a}):o.jsx("div",{className:"grid min-h-0 grid-cols-1 content-start gap-2 overflow-y-auto sm:grid-cols-2 lg:gap-6 2xl:grid-cols-3",children:e.map(u=>o.jsx(WDr,{item:u,editable:t,onToggle:i},`${u.type}__${u.id}`))})]})},cMt=({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})}),uMt="__built-in__",GDr=e=>{const t=WI(),n=t.data?.providers;return v.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:uMt,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])},QDr=e=>e.type==="integration"&&e.toolkit?e.toolkit:uMt;function YDr(e,t,n,r){const s=t.trim().toLowerCase();return e.filter(a=>r!==null&&!r.has(QDr(a))||n&&!a.isChecked?!1:s?a.name.toLowerCase().includes(s)||(a.description?.toLowerCase().includes(s)??!1):!0)}function KDr(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 NZ=e=>{const t=We();return yt({queryKey:["tool-provider-toolkits",e],queryFn:()=>t.getToolProvider(e).listToolkits(),enabled:!!e})},dMt=()=>{const e=We(),t=Br();return Ln({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]})}})},fMt=e=>e.split(/[-_\s]+/).filter(Boolean).map(t=>`${t.charAt(0).toUpperCase()}${t.slice(1)}`).join(" "),XDr=()=>{const e=We(),t=Br();return Ln({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]})}})},JDr=400,gQe=e=>{const t=e.trim();return t.length>0?t:null},e3r=({providerId:e,connectionId:t,initialLabel:n})=>{const r=XDr(),s=v.useRef(gQe(n)),a=Uy(l=>{l!==s.current&&r.mutate({providerId:e,connectionId:t,label:l},{onSuccess:()=>{s.current=l,De.success("Connection renamed")}})},JDr);return v.useEffect(()=>()=>{a.flush()},[a]),{scheduleRename:l=>{const c=gQe(l);if(c===s.current){a.cancel();return}a(c)},isPending:r.isPending,error:r.error}},t3r=({providerId:e,connectionId:t,initialLabel:n,iconUrl:r,disabled:s,testIdPrefix:a,showBack:i,onBack:l,onDisconnected:c})=>{const u=e3r({providerId:e,connectionId:t,initialLabel:n}),d=dMt(),[f,p]=v.useState(n),[h,m]=v.useState(!1),g=fMt(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(Rr,{className:"flex flex-col gap-3",children:[i&&o.jsxs(ce,{type:"button",variant:"ghost",size:"sm",onClick:l,"aria-label":"Back to connections","data-testid":`${a}-back`,className:"text-neutral3 -mt-1 -ml-1.5 w-fit",children:[o.jsx(qe,{children:o.jsx(Rot,{})}),"Connections"]}),o.jsxs("div",{className:"flex flex-col items-center gap-4 text-center",children:[o.jsx("div",{className:"bg-surface4 grid size-14 place-items-center overflow-hidden rounded-xl","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(MGt,{})})}),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:[g," 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(Jt,{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(ce,{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(ce,{type:"button",variant:"primary",onClick:y,disabled:s||d.isPending,"data-testid":`${a}-disconnect-confirm`,children:d.isPending?"Disconnecting…":"Disconnect"})]})]})})]})},Uf=({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}),pMt=({children:e,className:t,style:n})=>o.jsx(qe,{size:"lg",className:X("mt-1 shrink-0 text-neutral3",t),style:n,children:e}),qf=({children:e,className:t})=>o.jsx(ye,{as:"p",variant:"ui-lg",className:X("font-medium text-neutral6",t),children:e}),sh=({children:e,className:t})=>o.jsx(ye,{as:"div",variant:"ui-sm",className:X("text-neutral3",t),children:e}),Vf=({children:e,className:t})=>o.jsx("div",{className:X("w-full flex-1",t),children:e}),n3r=({connections:e,testIdPrefix:t,onSelect:n,onAddConnection:r,addingConnection:s=!1,disabled:a=!1})=>o.jsxs(o.Fragment,{children:[o.jsx(Rr,{"data-testid":`${t}-list`,children:o.jsx("div",{className:"flex flex-col gap-2",role:"list",children:e.map(i=>o.jsx(Uf,{className:"hover:bg-surface4 relative items-center rounded-lg px-2 py-2 transition-colors",children:o.jsx(Vf,{className:"min-w-0",children:o.jsxs("button",{type:"button",disabled:a,onClick:()=>n(i.connectionId),"data-testid":`${t}-list-item-${i.connectionId}`,className:"focus-visible:after:ring-accent1 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",children:[o.jsx(qf,{className:"truncate",children:i.label?.trim()||"Unnamed connection"}),o.jsx(qe,{className:"text-neutral3 shrink-0",children:o.jsx(aa,{})})]})})},i.connectionId))})}),r&&o.jsx(ic,{children:o.jsxs(ce,{type:"button",variant:"outline",size:"sm",onClick:r,disabled:a||s,"data-testid":`${t}-add`,children:[s?o.jsx(Jt,{size:"sm"}):o.jsx(qe,{children:o.jsx(Wr,{})}),"Add connection"]})})]}),r3r=({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]=v.useState(null),p=d===null,h=r.find(g=>g.connectionId===d)??null,m=g=>{g||f(null),t(g)};return o.jsx(vr,{open:e,onOpenChange:m,children:o.jsxs(yr,{"data-testid":`${a}-dialog`,className:"sm:max-w-md",children:[o.jsxs(br,{children:[o.jsx(hr,{children:p?`${fMt(n)} connections`:"Manage connection"}),o.jsx(Bs,{children:"Rename or disconnect this authorized account."})]}),e&&(p?o.jsx(n3r,{connections:r,testIdPrefix:a,onSelect:f,onAddConnection:c,addingConnection:u,disabled:s}):h&&o.jsx(t3r,{providerId:n,connectionId:h.connectionId,initialLabel:h.label??"",iconUrl:l,disabled:s,testIdPrefix:a,showBack:!0,onBack:()=>f(null),onDisconnected:g=>{i(g),r.length<=1?m(!1):f(null)}},h.connectionId))]})})},s3r=2e3,a3r=5*6e4,hMt=(e={})=>{const t=We(),n=e.pollIntervalMs??s3r,r=e.timeoutMs??a3r,s=e.openPopup??(a=>window.open(a,"_blank","popup,width=600,height=700"));return Ln({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}:{}}),g=s(h);if(!g)throw new Error("Popup blocked. Please allow popups for this site.");const y=Date.now();for(;Date.now()-y<r;){await new Promise(x=>setTimeout(x,n));const{status:b}=await f.getAuthStatus(m);if(b==="completed"||b==="failed"){try{g.close()}catch{}return{status:b,connectionId:m}}}try{g.close()}catch{}throw new Error("Authorization timed out")}})},mMt=(e,t,n)=>{const r=We(),s=n?.scopeToSelf??!1,a=Im(),i=a.data?.id,l=!s||a.isSuccess||u2t(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})},hbe=32,i3r=e=>{const t=e.replace(/[^A-Za-z0-9 _-]+/g,"-").replace(/^[-\s]+|[-\s]+$/g,""),n=t.length>0?t:"connection";return n.length>hbe?n.slice(0,hbe):n},o3r=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,hbe-i.length)}${i}`}return t.add(s()),r===n.label?n:{...n,label:r}})},l3r=(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)}),c3r=({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:o3r(s.map(a=>({...a,label:a.label||i3r(a.connectionId)})))},u3r=({hasSelectedTool:e,currentPins:t,desiredPins:n,connectionsField:r,setValue:s})=>{v.useEffect(()=>{!e||l3r(t,n)||s(r,n,{shouldDirty:!0})},[e,n,t,r,s])},d3r=({providerId:e,toolkit:t,disabled:n=!1,multipleAllowed:r=!1})=>{const{setValue:s}=Ur(),a=Br(),i=hMt(),l=mMt(e,t,{scopeToSelf:!0}),[c,u]=v.useState(!1),d=NZ(c?e:null),f=v.useMemo(()=>d.data?.data?.find(E=>E.slug===t)?.icon,[d.data?.data,t]),p=v.useMemo(()=>`toolProviders.${e}.connections.${t}`,[e,t]),h=zn({name:p}),m=v.useMemo(()=>h??[],[h]),g=zn({name:`toolProviders.${e}`}),y=v.useMemo(()=>Object.values(g?.tools??{}).some(E=>E?.toolkit===t),[g?.tools,t]),b=v.useMemo(()=>(l.data?.items??[]).filter(E=>E.status==="active"),[l.data?.items]),x=v.useMemo(()=>c3r({activeConnections:b,pinned:m,toolkit:t}),[b,m,t]),S=v.useMemo(()=>b.map(E=>({connectionId:E.connectionId,label:E.label})),[b]);u3r({hasSelectedTool:y,currentPins:m,desiredPins:x,connectionsField:p,setValue:s});const k=E=>{m.some(T=>T.connectionId===E)&&s(p,m.filter(T=>T.connectionId!==E),{shouldDirty:!0})},C=()=>{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]})}})},_=`${e}-${t}`;return l.isPending?o.jsx(kt,{className:"h-7 w-20","data-testid":`toolkit-connection-loading-${_}`}):b.length===0?o.jsx(ce,{type:"button",variant:"outline",size:"sm",onClick:C,disabled:n||i.isPending,"data-testid":`toolkit-connect-${_}`,children:i.isPending?"Connecting…":"Connect"}):o.jsxs("div",{className:"flex items-center gap-1","data-testid":`toolkit-connection-${_}`,children:[o.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"Manage connection","aria-label":`Manage ${t} connection`,onClick:()=>u(!0),disabled:n,"data-testid":`toolkit-manage-${_}`,children:o.jsx(E9,{})}),c&&o.jsx(r3r,{open:!0,onOpenChange:u,providerId:e,connections:S,disabled:n,testIdPrefix:`toolkit-manage-${_}`,onDisconnected:k,iconUrl:f,onAddConnection:r?C:void 0,addingConnection:i.isPending})]})},Zk="tools-toolkit",QEe=v.memo(({item:e,checked:t,disabled:n,onToggle:r,providerId:s,multipleAllowed:a})=>{const i=p0(),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":`${Zk}-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(qo,{checked:t,disabled:n,onCheckedChange:()=>r(e.id),style:l,"data-testid":`${Zk}-filter-checkbox-${e.id}`,className:"h-3.5 w-3.5 shrink-0 shadow-none data-[state=checked]:shadow-none [&_svg]:h-2.5 [&_svg]:w-2.5"}),e.icon&&o.jsx("img",{src:e.icon,alt:"","aria-hidden":!0,"data-testid":`${Zk}-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(d3r,{providerId:s,toolkit:e.id,disabled:n,multipleAllowed:a})})]})});QEe.displayName="ToolkitFilterRow";const f3r=({provider:e,term:t,isChecked:n,onToggle:r,disabled:s,multipleAllowed:a})=>{const{data:i,isLoading:l}=NZ(e.providerId),c=v.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(kt,{className:"h-4 w-20"}),Array.from({length:Math.min(e.presentSlugs.length,3)}).map((u,d)=>o.jsx(kt,{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:"text-neutral3 px-2 pt-1 tracking-wide uppercase",children:e.providerName}),o.jsx("ul",{className:"flex flex-col gap-0.5",children:c.map(u=>o.jsx(QEe,{item:u,checked:n(u.id),disabled:s,onToggle:r,providerId:e.providerId,multipleAllowed:a},u.id))})]})},p3r=({builtIn:e,providers:t,isProvidersLoading:n,isChecked:r,onToggle:s,onSelectAll:a,onClearAll:i,disabled:l=!1,multipleAllowedByProvider:c})=>{const[u,d]=v.useState(""),f=u.trim().toLowerCase(),p=v.useMemo(()=>f?e.filter(h=>h.label.toLowerCase().includes(f)):e,[e,f]);return o.jsxs("div",{className:"border-border1 flex h-full min-h-0 flex-col gap-3 border-r px-6 py-6","data-testid":`${Zk}-filter`,children:[o.jsx("div",{className:"bg-surface3 shrink-0 rounded-full","data-testid":`${Zk}-filter-search`,children:o.jsxs(zu,{variant:"outline",size:"lg",children:[o.jsx(ru,{align:"inline-start",children:o.jsx(Xa,{})}),o.jsx(Fu,{type:"search","aria-label":"Filter toolkits",placeholder:"Filter toolkits...",onChange:h=>d(h.target.value)})]})}),o.jsxs("div",{className:"text-ui-xs flex shrink-0 items-center gap-2",children:[o.jsx("button",{type:"button",onClick:a,disabled:l,"data-testid":`${Zk}-filter-select-all`,className:"text-neutral3 hover:text-neutral6 transition-colors 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":`${Zk}-filter-clear-all`,className:"text-neutral3 hover:text-neutral6 transition-colors disabled:cursor-not-allowed disabled:opacity-60",children:"Clear all"})]}),o.jsx(Fr,{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(QEe,{item:h,checked:r(h.id),disabled:l,onToggle:s},h.id))}),t.map(h=>o.jsx(f3r,{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(kt,{className:"h-7 w-full"},m))})]})})]})},h3r=()=>{const{setValue:e,getValues:t}=Ur(),n=v.useCallback((a,i)=>{const l=t("toolProviders")??{},c=l[a]??{tools:{},connections:{}};e("toolProviders",{...l,[a]:i(c)},{shouldDirty:!0})},[t,e]),r=v.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=v.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(g=>g.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}},m3r=e=>{const[t,n]=v.useState(null),r=v.useCallback(c=>t===null||t.has(c),[t]),s=v.useCallback(c=>{n(u=>{const d=new Set(u??e);return d.has(c)?d.delete(c):d.add(c),d})},[e]),a=v.useCallback(()=>n(null),[]),i=v.useCallback(()=>n(new Set),[]),l=v.useMemo(()=>t!==null&&t.size===0,[t]);return{selected:t,isChecked:r,toggle:s,selectAll:a,clearAll:i,allUnchecked:l}},gMt=({editable:e=!0,availableAgentTools:t=[]})=>{const[n,r]=v.useState(""),[s,a]=v.useState(!1),{builtIn:i,providers:l,allToolkitIds:c,isProvidersLoading:u}=GDr(t),d=m3r(c),{toggle:f}=h3r(),p=WI(),h=v.useMemo(()=>{const b=new Map;for(const x of p.data?.providers??[])b.set(x.id,x.capabilities?.multipleConnectionsPerToolkit??!1);return b},[p.data?.providers]),{isLoading:m}=M4();if(t.length===0)return m?o.jsx(iMt,{testId:"tools-card-picker-loading"}):o.jsx("div",{className:"px-6 py-6","data-testid":"tools-empty-state",children:o.jsx(cMt,{details:"No tools available in this project"})});const g=YDr(t,n,s,d.selected),y=KDr({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(p3r,{builtIn:i,providers:l,isProvidersLoading:u,isChecked:d.isChecked,onToggle:d.toggle,onSelectAll:d.selectAll,onClearAll:d.clearAll,disabled:!e,multipleAllowedByProvider:h}),o.jsx(ZDr,{tools:g,editable:e,onlySelected:s,onOnlySelectedChange:a,onSearch:r,emptyStateDetails:y,onToggle:f})]})},g3r=({agentId:e,availableAgentTools:t,availableSkills:n,disabled:r=!1,fallbackInstructions:s})=>{const i={"--tab-indicator-color":p0().background},{isLoading:l}=M4(),c=x2t({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",g="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(gc,{defaultTab:b,className:"grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] overflow-hidden",children:[o.jsxs(mc,{variant:"line",sticky:!0,className:"!bg-surface3 px-6",style:i,children:[u&&o.jsx(Nr,{value:"model",children:"Model"}),d&&o.jsx(Nr,{value:"tools",children:"Tools"}),o.jsx(Nr,{value:"instructions",children:"Instructions"}),f&&o.jsx(Nr,{value:"skills",children:"Skills"}),p&&o.jsx(Nr,{value:"browser",children:"Browser"}),h&&o.jsx(Nr,{value:"integrations",children:"Integrations"})]}),o.jsxs("div",{className:"h-full min-h-0 overflow-y-auto",children:[u&&o.jsx(Kr,{value:"model",className:g,children:o.jsx(oMt,{editable:y})}),d&&o.jsx(Kr,{value:"tools",className:g,children:o.jsx(gMt,{availableAgentTools:t,editable:y})}),o.jsx(Kr,{value:"instructions",className:m,children:o.jsx(S2t,{editable:y,fallbackPrompt:s})}),f&&o.jsx(Kr,{value:"skills",className:m,children:o.jsx(lMt,{availableSkills:n,editable:y})}),p&&o.jsx(Kr,{value:"browser",className:m,children:o.jsx(w2t,{editable:y})}),h&&o.jsx(Kr,{value:"integrations",className:m,children:o.jsx(tMt,{agentId:e,editable:y})})]})]})})},mbe=["ready","identity","model","tools","instructions","skills","browser","library","integrations","end"],v3r=({gates:e,includeInitial:t})=>{const n=[];for(const r of mbe)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},y3r=(e,t)=>{if(t.includes(e))return e;const n=mbe.indexOf(e);return mbe.slice(n+1).find(r=>t.includes(r))??"end"},vMt=v.createContext(null),b3r=({initialStep:e="end",hasAgentTools:t=!0,children:n})=>{const{availableSkills:r}=cC(),s=x2t({hasAgentTools:t,hasSkills:r.length>0}),a=v.useMemo(()=>v3r({gates:s,includeInitial:e==="ready"}),[s,e]),[i,l]=v.useState(()=>a.includes(e)?e:a[0]??"end");v.useEffect(()=>{l(p=>y3r(p,a))},[a]);const c=v.useCallback(()=>{l(p=>{const h=a.indexOf(p);return h===-1?p:a[h+1]??p})},[a]),u=v.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=v.useMemo(()=>({step:i,next:c,prev:u,steps:a,isLast:d}),[i,c,u,a,d]);return o.jsx(vMt.Provider,{value:f,children:n})},Hf=()=>v.useContext(vMt)??{step:"end",next:()=>{},prev:()=>{},steps:[],isLast:!1},xm=e=>{"startViewTransition"in document?document.startViewTransition(()=>{Ni.flushSync(()=>{e()})}):e()},v0=({children:e,cta:t,title:n,description:r,contentClassName:s,panelClassName:a,panelOverlay:i})=>{const l=p0(),c=bu(),{isLast:u,next:d,prev:f,step:p,steps:h}=Hf(),m=Ws(),{id:g}=Sr(),y={backgroundImage:`conic-gradient(from 0deg at 50% 50%, ${l.background}, ${l.foreground}, ${l.background})`},b=u&&g,S=h.indexOf(p)>0?o.jsxs(ce,{variant:"ghost",onClick:()=>xm(()=>f()),disabled:c,"data-testid":"agent-builder-step-back",children:[o.jsx(qe,{children:o.jsx($c,{})})," ","Back"]}):null;return o.jsxs("div",{className:"border-border1 relative h-full min-h-0 w-full overflow-hidden rounded-3xl border 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-border1 border-b px-6 pt-6 pb-4","data-testid":"agent-step-title-section",children:[o.jsx("h2",{className:"text-neutral6 pb-1 text-3xl font-semibold",children:n}),r&&o.jsx("div",{className:"text-neutral3 w-1/2",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:"border-border1 flex shrink-0 items-center justify-center gap-2 border-t pt-6 pb-6","data-testid":"agent-step-footer",children:[S,o.jsx(ce,{variant:"outline",onClick:()=>xm(()=>d()),disabled:c,children:"See agent configuration"}),o.jsx(ce,{variant:"primary",onClick:()=>m(`/agent-builder/agents/${g}/view`,{viewTransition:!0}),disabled:c,children:"Try agent"})]}):o.jsxs("div",{className:"border-border1 flex shrink-0 items-center justify-center gap-2 border-t pt-6 pb-6","data-testid":"agent-step-footer",children:[S,t]})]})]})},x3r=()=>{const{next:e}=Hf(),t=Ws(),{id:n}=Sr(),r=v.useRef(null);v.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=()=>{xm(()=>{e()})},a=()=>{t(`/agent-builder/agents/${n}/view`,{viewTransition:!0})};return o.jsx(v0,{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(ce,{variant:"outline",onClick:s,"data-testid":"agent-builder-ready-review",children:"Review my agent"}),o.jsx(ce,{variant:"primary",onClick:a,"data-testid":"agent-builder-ready-try",children:"Try my agent"})]}),children:o.jsx("div",{className:"flex h-full w-full flex-col items-center justify-center px-6 py-6 text-center",children:o.jsxs("div",{className:"ready-stage-content flex flex-col items-center gap-4",children:[o.jsx("h2",{className:"text-neutral6 text-4xl font-semibold","data-testid":"agent-builder-ready-heading",children:"Your agent is ready"}),o.jsx("p",{className:"text-neutral3 max-w-md text-lg",children:"You can review and fine-tune everything, or jump straight in and try it out."})]})})})},w3r=({avatar:e,details:t})=>{const{next:n}=Hf(),r=bu(),s=()=>{xm(()=>{n()})};return o.jsx(v0,{cta:o.jsxs(ce,{onClick:s,disabled:r,children:["Continue"," ",o.jsx(qe,{children:o.jsx(Sm,{})})]}),children:o.jsxs("div",{className:"relative flex h-full w-full flex-col items-center justify-center gap-4 px-6 py-6 text-center",children:[e,t]})})},S3r=({agentId:e})=>{const{next:t}=Hf(),n=bu(),{requestChange:r,dialog:s}=bEe(e),{control:a}=Ur(),l=zn({control:a,name:"visibility"})==="public",c=()=>{xm(()=>{t()})};return o.jsx(v0,{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(ce,{onClick:c,disabled:n,children:["Continue"," ",o.jsx(qe,{children:o.jsx(Sm,{})})]}),children:o.jsxs("div",{className:"relative flex h-full w-full flex-col items-center justify-center gap-4 px-6 py-6 text-center","data-testid":"agent-builder-library-step",children:[o.jsx(qe,{size:"lg",className:"text-neutral4",children:o.jsx(Q2,{})}),l?o.jsxs("p",{className:"text-neutral2 flex items-center gap-2","data-testid":"agent-builder-library-added",children:[o.jsx(qe,{children:o.jsx(fa,{})}),"Added to your library"]}):o.jsx(ce,{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]})})},k3r=({provider:e,name:t})=>{const n=gi(e);return o.jsxs(on,{variant:"default",children:[o.jsx(qI,{providerId:n,size:16})," ",n,"/",t]})},O3r=()=>{const{next:e}=Hf(),t=bu(),n=zn({name:"model"}),r=()=>{xm(()=>{e()})};return o.jsx(v0,{title:"Available models",description:n?o.jsxs("div",{className:"flex items-center gap-2",children:["Selected model: ",o.jsx(k3r,{provider:n.provider,name:n.name})]}):void 0,contentClassName:"overflow-hidden",cta:o.jsxs(ce,{onClick:r,disabled:t,children:["Continue"," ",o.jsx(qe,{children:o.jsx(Sm,{})})]}),children:o.jsx(oMt,{editable:!t})})},_3r=()=>{const{availableAgentTools:e}=g0(),{next:t}=Hf(),n=bu(),r=e.filter(a=>a.isChecked).length,s=()=>{xm(()=>{t()})};return o.jsx(v0,{title:"Available tools",description:o.jsxs("div",{className:"flex items-center gap-2",children:["Selected tools:"," ",o.jsx(on,{variant:"default",children:o.jsx("strong",{className:"text-neutral6 font-semibold",children:r})})]}),contentClassName:"overflow-hidden",cta:o.jsxs(ce,{onClick:s,disabled:n,children:["Continue"," ",o.jsx(qe,{children:o.jsx(Sm,{})})]}),children:o.jsx(gMt,{availableAgentTools:e,editable:!n})})},C3r=()=>{const{next:e}=Hf(),t=bu(),n=()=>{xm(()=>{e()})};return o.jsx(v0,{title:"Instructions",cta:o.jsxs(ce,{onClick:n,disabled:t,children:["Continue"," ",o.jsx(qe,{children:o.jsx(Sm,{})})]}),children:o.jsx(S2t,{editable:!t})})},E3r=()=>{const{availableSkills:e}=g0(),{next:t}=Hf(),n=bu(),r=()=>{xm(()=>{t()})};return o.jsx(v0,{title:"Skills",cta:o.jsxs(ce,{onClick:r,disabled:n,children:["Continue"," ",o.jsx(qe,{children:o.jsx(Sm,{})})]}),children:o.jsx(lMt,{availableSkills:e,editable:!n})})},T3r=()=>{const{next:e}=Hf(),t=bu(),n=()=>{xm(()=>{e()})};return o.jsx(v0,{title:"Browser",cta:o.jsxs(ce,{onClick:n,disabled:t,children:["Continue"," ",o.jsx(qe,{children:o.jsx(Sm,{})})]}),children:o.jsx(w2t,{editable:!t})})},j3r=()=>{const{agentId:e}=g0(),{next:t}=Hf(),n=bu(),r=()=>{xm(()=>{t()})};return o.jsx(v0,{title:"Integrations",cta:o.jsxs(ce,{onClick:r,disabled:n,children:["Continue"," ",o.jsx(qe,{children:o.jsx(Sm,{})})]}),children:o.jsx(tMt,{agentId:e,editable:!n})})},yMt=({status:e,lastError:t,onRetry:n})=>e==="saving"?o.jsxs("span",{className:"text-ui-sm text-neutral3 flex items-center gap-1.5","data-testid":"agent-builder-autosave-saving",children:[o.jsx(Jt,{size:"sm"}),"Saving…"]}):e==="saved"?o.jsxs("span",{className:"text-ui-sm text-neutral3 flex items-center gap-1.5","data-testid":"agent-builder-autosave-saved",children:[o.jsx(fa,{className:"h-3.5 w-3.5"}),"Saved"]}):e==="error"?o.jsxs("span",{className:"text-ui-sm text-neutral3 flex items-center gap-1.5","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:"hover:text-neutral4 underline underline-offset-2",children:"Retry"})]}):null,bMt=({className:e,isLoading:t=!1})=>{const{control:n}=Ur(),r=zn({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 min-w-0 items-center gap-2",children:o.jsx("span",{className:"text-ui-md leading-ui-md block truncate text-white","data-testid":"agent-builder-title-name",children:t?o.jsx(kt,{className:"inline-block h-4 w-24 align-middle","data-testid":"agent-builder-title-skeleton"}):s})})})},N3r=({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(C1e,{label:"Agent navigation",className:"min-w-0",listClassName:"min-w-0",children:[o.jsx(B$,{as:za,to:"/agent-builder/agents","data-testid":"agent-builder-back-to-list",children:"Agent list"}),o.jsx(B$,{as:"span",isCurrent:!0,children:o.jsx(bMt,{isLoading:e})})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2 justify-self-end",children:[s&&o.jsx("div",{className:"mr-1 shrink-0",children:s}),a&&o.jsx("div",{className:"flex shrink-0",children:a}),i&&o.jsx("div",{className:"shrink-0 lg:hidden",children:i}),t&&n&&o.jsxs(ce,{variant:"ghost",size:"sm",onClick:n,disabled:r,className:"hidden shrink-0 lg:inline-flex","data-testid":"agent-builder-mode-toggle","aria-label":l,children:[o.jsx(a1,{}),l]})]})]})};function I3r({agentId:e}){const t=Ur(),n=zn({control:t.control,name:"visibility"}),{requestChange:r,dialog:s}=bEe(e),a=n??"private";return o.jsxs(o.Fragment,{children:[a==="private"?o.jsxs(ce,{size:"sm",variant:"default",onClick:()=>r("public"),"data-testid":"agent-builder-visibility-add",children:[o.jsx(Kx,{className:"h-3.5 w-3.5"}),"Add to library"]}):o.jsxs(ce,{size:"sm",variant:"ghost",onClick:()=>r("private"),"data-testid":"agent-builder-visibility-remove",children:[o.jsx(Tf,{className:"h-3.5 w-3.5"}),"Remove from library"]}),s]})}const A3r={slack:"Slack"},R3r=e=>e?A3r[e]??e.charAt(0).toUpperCase()+e.slice(1):"channel",xMt=()=>{const[e]=ri(),t=v.useRef(null),n=e.get("channel_connected"),r=e.get("channel_error"),s=e.get("platform"),a=e.get("team");v.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=R3r(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])},P3r=({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:"grid h-full 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:"grid h-full min-h-0 w-full min-w-0 grid-rows-[1fr_auto] overflow-hidden md:mx-auto md:max-w-[80ch]",children:[o.jsx("div",{className:"h-full min-h-0 min-w-0 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 $3r(e){if(e&&typeof e=="object"&&"type"in e&&e.type==="id"){const t=e.workspaceId;return typeof t=="string"?t:void 0}}function M3r(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 D3r(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 wMt(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(M3r(e?.skills)).map(n=>[n,!0])),workspaceId:$3r(e?.workspace),browserEnabled:e?.browser!=null,visibility:e?.visibility,avatarUrl:t,model:D3r(e?.model),toolProviders:uDr(e?.toolProviders)}}function L3r(){const{id:e}=Sr();return xMt(),o.jsx(gMr,{agentId:e,children:o.jsx(z3r,{})})}const z3r=()=>{const{agentId:e,storedAgent:t,isReady:n,isOwner:r,canWrite:s}=cC();return n?t?!s||!r?o.jsx(Qu,{to:`/agent-builder/agents/${e}/view`,replace:!0}):o.jsx(F3r,{}):o.jsx(Qu,{to:"/agent-builder/agents",replace:!0}):o.jsx(Z3r,{})},F3r=()=>{const{agentId:e,storedAgent:t}=cC(),[n]=v.useState(()=>wMt(t)),r=eS({defaultValues:n});return o.jsx(Q$,{...r,children:o.jsx(SD,{agentId:e,children:o.jsx(B3r,{})})})},B3r=()=>{const{agentId:e,storedAgent:t,toolsData:n,agentsData:r,workflowsData:s,isOwner:a,initialUserMessage:i}=cC(),l=Ws(),{control:c}=Ur(),u=zn({control:c,name:"tools"}),d=zn({control:c,name:"agents"}),f=zn({control:c,name:"workflows"}),p=q$t({toolsData:n,agentsData:r,workflowsData:s,selectedTools:u,selectedAgents:d,selectedWorkflows:f,excludeAgentId:e}),{isLoading:h}=M4(),m=a?()=>l(`/agent-builder/agents/${e}/view`,{viewTransition:!0}):void 0;return o.jsx(b3r,{initialStep:i?"ready":"end",hasAgentTools:p.length>0||h,children:o.jsx(vDr,{storedAgent:t,availableAgentTools:p,onModeToggle:m,children:o.jsx(U3r,{})})})},U3r=()=>{const{step:e}=Hf(),t=Bf(),n=E2t(),{control:r}=Ur(),{dirtyFields:s}=bSe({control:r}),a=zn({control:r,name:"name"})??"",i=zn({control:r,name:"description"})??"",l=zn({control:r,name:"instructions"})??"",c=zn({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,g=e==="identity"&&d&&!n;return o.jsx(P3r,{topBar:o.jsx(V3r,{}),chat:o.jsx(iDr,{}),chatFooter:g?o.jsx(q3r,{}):void 0,profile:m?null:o.jsx(W3r,{}),variant:h,hideMobileChat:e==="end"})},q3r=()=>{const{next:e}=Hf(),t=Ws(),{agentId:n}=g0();return o.jsxs("div",{className:"flex flex-col gap-2 lg:hidden","data-testid":"agent-builder-mobile-initial-ctas",children:[o.jsx(ce,{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(ce,{variant:"outline",onClick:()=>xm(()=>e()),"data-testid":"agent-builder-mobile-initial-cta-config",children:"See configuration"})]})},V3r=()=>{const{autosave:e,onModeToggle:t}=g0(),n=bu(),{step:r}=Hf(),s=r!=="end";return o.jsx(N3r,{isLoading:!1,mode:"build",onModeToggle:s?void 0:t,modeToggleDisabled:n,rightAside:o.jsx(yMt,{status:e.status,lastError:e.lastError,onRetry:e.retry}),mobileExtra:o.jsx(H3r,{})})},H3r=()=>{const{agentId:e}=g0(),t=bu(),{data:n}=uc(),{control:r}=Ur(),s=zn({control:r,name:"name"})??"";return o.jsx(g2t,{agentId:e,showSetVisibility:!!n?.enabled,showDelete:!0,showViewAgent:!0,agentName:s,disabled:t})},W3r=()=>{const{agentId:e,availableAgentTools:t,availableSkills:n,isOwner:r}=g0(),s=bu(),{data:a}=uc(),{control:i}=Ur(),l=zn({control:i,name:"name"})??"",{step:c}=Hf(),u=o.jsxs("div",{className:"hidden items-center gap-2 lg:flex","data-testid":"agent-builder-hero-actions-desktop",children:[a?.enabled&&o.jsx("span",{style:{viewTransitionName:"agent-visibility-select"},children:o.jsx(I3r,{agentId:e})}),r&&o.jsx(ENr,{agentId:e,agentName:l,disabled:s})]});return c==="ready"?o.jsx(x3r,{}):c==="identity"?o.jsx(w3r,{avatar:o.jsx(TGe,{disabled:s}),details:o.jsx(jGe,{mode:"highlighted",disabled:s})}):c==="library"?o.jsx(S3r,{agentId:e}):c==="model"?o.jsx(O3r,{}):c==="tools"?o.jsx(_3r,{}):c==="instructions"?o.jsx(C3r,{}):c==="skills"?o.jsx(E3r,{}):c==="browser"?o.jsx(T3r,{}):c==="integrations"?o.jsx(j3r,{}):o.jsxs(NNr,{children:[o.jsx(INr,{avatar:o.jsx(TGe,{disabled:s}),details:o.jsx(jGe,{disabled:s}),actions:u}),o.jsx(g3r,{agentId:e,availableAgentTools:t,availableSkills:n,disabled:s})]})},Z3r=()=>o.jsx("div",{className:"flex h-screen w-screen items-center justify-center",children:o.jsx(Jt,{})}),SMt=v.createContext(null);function L4(){const e=v.useContext(SMt);if(!e)throw new Error("useBrowserSession must be used within a BrowserSessionProvider");return e}const kMt=v.createContext(null);function OMt(){const e=v.useContext(kMt);if(!e)throw new Error("useBrowserFrame must be used within a BrowserSessionProvider");return{latestFrame:v.useSyncExternalStore(e.subscribe,e.getSnapshot)}}const G3r=["browser_","stagehand_"];function Q3r(e){return G3r.some(t=>e.startsWith(t))}function Y3r(e){if(!e||typeof e!="object")return!1;const t=e;return t.success===!1&&typeof t.code=="string"}const YEe=v.createContext(null);function IZ({children:e}){const[t,n]=v.useState(new Map),r=v.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=v.useMemo(()=>Array.from(t.values()).sort((i,l)=>i.timestamp-l.timestamp),[t]),a=v.useMemo(()=>({toolCalls:s,registerToolCall:r}),[s,r]);return o.jsx(YEe.Provider,{value:a,children:e})}function KEe(){const e=v.useContext(YEe);if(!e)throw new Error("useBrowserToolCalls must be used within a BrowserToolCallsProvider");return e}function K3r(){return v.useContext(YEe)}const vQe={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"},X3r={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 J3r(e){return vQe[e]?vQe[e]:e.replace(/^(browser_|stagehand_)/,"")}function e4r(e,t){const n=X3r[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 _Mt({entry:e}){const[t,n]=v.useState(!1),r=J3r(e.toolName),s=e4r(e.toolName,e.args),{__mastraMetadata:a,...i}=e.args;return o.jsxs("div",{className:"border-border1 border-b last:border-b-0",children:[o.jsxs("button",{type:"button",onClick:()=>n(l=>!l),"aria-expanded":t,className:"hover:bg-surface3 flex w-full items-center gap-2 px-3 py-0.5 text-left transition-colors",children:[o.jsx(aa,{className:X("h-3 w-3 text-neutral3 transition-transform shrink-0",t&&"rotate-90")}),o.jsx(t4r,{status:e.status}),o.jsx("span",{className:"text-neutral6 shrink-0 text-xs font-medium",children:r}),s&&o.jsx("span",{className:"text-neutral3 truncate text-xs",children:s})]}),t&&o.jsxs("div",{className:"space-y-2 px-3 pb-2",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-neutral4 pb-1 text-xs font-medium",children:"Arguments"}),o.jsx(Hr,{data:i,"data-testid":"browser-tool-args"})]}),e.result!==void 0&&e.result!==null&&o.jsxs("div",{children:[o.jsx("p",{className:"text-neutral4 pb-1 text-xs font-medium",children:"Result"}),typeof e.result=="string"?o.jsx("pre",{className:"bg-surface4 max-h-40 overflow-x-auto overflow-y-auto rounded-md p-2 text-xs whitespace-pre",children:e.result}):o.jsx(Hr,{data:e.result,"data-testid":"browser-tool-result"})]})]})]})}function t4r({status:e}){switch(e){case"pending":return o.jsx(ua,{className:"text-neutral4 h-3 w-3 shrink-0 animate-spin"});case"complete":return o.jsx(fa,{className:"h-3 w-3 shrink-0 text-green-500"});case"error":return o.jsx(ps,{className:"h-3 w-3 shrink-0 text-red-500"})}}const n4r=10;function r4r(e){const[t,n]=v.useState([]),r=v.useRef(0),s=v.useRef(e.viewport);v.useEffect(()=>{s.current=e.viewport},[e.viewport]);const a=v.useCallback(i=>{n(l=>l.filter(c=>c.id!==i))},[]);return v.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,g=u.height*h,y=(d.width-m)/2,b=(d.height-g)/2,x=f-y,S=p-b;x<0||S<0||x>m||S>g||n(k=>{if(k.length>=n4r)return k;const C=++r.current;return[...k,{id:C,x:f,y:p}]})}return i.addEventListener("mousedown",l),()=>{i.removeEventListener("mousedown",l)}},[e.enabled,e.imgRef]),{ripples:t,removeRipple:a}}function s4r(){const{toolCalls:e}=KEe();return v.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 a4r=16,yQe=500;function dF(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 bQe(e,t,n){let r;switch(t){case 0:r=e;break;case 1:r=e*a4r;break;case 2:r=e*(n??800);break;default:r=e}return Math.max(-yQe,Math.min(yQe,r))}function _T(e){let t=0;return e.altKey&&(t|=1),e.ctrlKey&&(t|=2),e.metaKey&&(t|=4),e.shiftKey&&(t|=8),t}function i4r(e){return e.length===1}function o4r(e){const t=v.useRef(e.sendMessage),n=v.useRef(e.onEscape);v.useEffect(()=>{t.current=e.sendMessage},[e.sendMessage]),v.useEffect(()=>{n.current=e.onEscape},[e.onEscape]),v.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=_T(l),u=i4r(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,_T(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 l4r(e){const t=v.useRef(e.viewport),n=v.useRef(e.sendMessage);v.useEffect(()=>{t.current=e.viewport},[e.viewport]),v.useEffect(()=>{n.current=e.sendMessage},[e.sendMessage]),v.useEffect(()=>{if(!e.enabled||!e.imgRef.current)return;const r=e.imgRef.current;function s(g,y,b,x,S,k,C,_){const E={type:"mouse",eventType:g,x:y,y:b};x!==void 0&&(E.button=x),S!==void 0&&(E.clickCount=S),k!==void 0&&(E.modifiers=k),C!==void 0&&(E.deltaX=C),_!==void 0&&(E.deltaY=_),n.current(JSON.stringify(E))}function a(g){return g===2?"right":g===1?"middle":"left"}function i(g){const y=t.current;if(!y)return;const b=r.getBoundingClientRect(),x=dF(g.clientX,g.clientY,b,y);if(!x)return;const S=a(g.button),k=_T(g);s("mouseMoved",x.x,x.y,void 0,void 0,k),s("mousePressed",x.x,x.y,S,1,k)}function l(g){const y=t.current;if(!y)return;const b=r.getBoundingClientRect(),x=dF(g.clientX,g.clientY,b,y);if(!x)return;const S=a(g.button);s("mouseReleased",x.x,x.y,S,1,_T(g))}function c(g){g.preventDefault()}function u(g){g.preventDefault();const y=t.current;if(!y)return;const b=r.getBoundingClientRect(),x=dF(g.clientX,g.clientY,b,y);if(!x)return;const S=bQe(g.deltaX,g.deltaMode,y.height),k=bQe(g.deltaY,g.deltaMode,y.height);s("mouseWheel",x.x,x.y,void 0,void 0,_T(g),S,k)}let d=null,f=0,p=null;const h=1e3/30;function m(g){p=g,d===null&&(d=requestAnimationFrame(y=>{if(d=null,!p||y-f<h)return;f=y;const x=t.current;if(!x){p=null;return}const S=p;p=null;const k=r.getBoundingClientRect(),C=dF(S.clientX,S.clientY,k,x);C&&s("mouseMoved",C.x,C.y,void 0,void 0,_T(S))}))}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 c4r={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 u4r({toolName:e}){const t=e?c4r[e]??e.replace(/^(browser_|stagehand_)/,""):"Working";return o.jsx("div",{className:"bg-surface1/40 absolute inset-0 z-10 flex cursor-not-allowed items-center justify-center",children:o.jsxs("div",{className:"bg-surface2 border-border1 flex items-center gap-2 rounded-md border px-3 py-1.5 shadow-sm",children:[o.jsx(ua,{className:"text-accent1 h-3.5 w-3.5 animate-spin"}),o.jsxs("span",{className:"text-neutral4 text-xs font-medium",children:["Agent: ",t]})]})})}const gbe=32,xQe=gbe/2;function d4r({ripples:e,onAnimationEnd:t}){return e.length===0?null:o.jsx(o.Fragment,{children:e.map(n=>o.jsx("span",{className:"animate-click-ripple bg-accent1/40 pointer-events-none absolute rounded-full",style:{left:n.x-xQe,top:n.y-xQe,width:gbe,height:gbe},onAnimationEnd:()=>t(n.id)},n.id))})}function CMt({className:e,onStatusChange:t,onUrlChange:n,onFirstFrame:r}){const s=v.useRef(null),a=v.useRef(null),i=v.useRef(!1),[l,c]=v.useState(!1),[u,d]=v.useState(!1),{status:f,currentUrl:p,viewport:h,sendMessage:m}=L4(),{latestFrame:g}=OMt();v.useEffect(()=>{g&&s.current&&(s.current.src=`data:image/jpeg;base64,${g}`,i.current||(i.current=!0,c(!0)))},[g]);const y=v.useCallback(()=>{d(!1)},[]),b=v.useCallback(()=>{f==="streaming"&&d(!0)},[f]),{isAgentBusy:x,activeToolName:S}=s4r();l4r({imgRef:s,viewport:h,sendMessage:m,enabled:f==="streaming"&&!x}),o4r({sendMessage:m,enabled:u&&f==="streaming"&&l&&!x,onEscape:y});const{ripples:k,removeRipple:C}=r4r({imgRef:s,viewport:h,enabled:f==="streaming"&&l&&!x});v.useEffect(()=>{t?.(f)},[f,t]),v.useEffect(()=>{n?.(p)},[p,n]),v.useEffect(()=>{l&&r?.()},[l,r]),v.useEffect(()=>{if(!u)return;function N(A){a.current&&!a.current.contains(A.target)&&d(!1)}function I(){d(!1)}return document.addEventListener("mousedown",N),window.addEventListener("blur",I),()=>{document.removeEventListener("mousedown",N),window.removeEventListener("blur",I)}},[u]),v.useEffect(()=>{f!=="streaming"&&d(!1)},[f]);const _=(f==="connecting"||f==="browser_starting"||f==="streaming")&&!l,E=f==="disconnected"&&l,T=f==="error";return o.jsxs("div",{ref:a,className:X("relative w-full aspect-video bg-surface2 rounded-md overflow-hidden",u&&!x&&"ring-2 ring-accent1",u&&x&&"ring-2 ring-amber-400",e),children:[o.jsx("img",{ref:s,alt:"Browser screencast",onClick:b,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.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(d4r,{ripples:k,onAnimationEnd:C}),x&&o.jsx(u4r,{toolName:S}),_&&o.jsx(kt,{className:"absolute inset-0"}),E&&o.jsx("div",{className:"bg-surface1/80 absolute inset-0 flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx("div",{className:"border-neutral4 h-4 w-4 animate-spin rounded-full border-2 border-t-transparent"}),o.jsx("span",{className:"text-neutral4 text-sm",children:"Reconnecting..."})]})}),T&&o.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 px-6 py-4 text-center",children:[o.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-full bg-red-500/20",children:o.jsx("svg",{className:"h-7 w-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 EMt({agentName:e="Agent"}){const{hasSession:t,viewMode:n,status:r,currentUrl:s,setViewMode:a,closeBrowser:i}=L4(),{latestFrame:l}=OMt(),{toolCalls:c}=KEe(),u=v.useRef(null),[d,f]=v.useState(!1),p=v.useRef(null),h=n==="expanded";v.useEffect(()=>{if(l){const S=`data:image/jpeg;base64,${l}`;u.current&&(u.current.src=S),d||f(!0)}},[l,d]),v.useEffect(()=>{t||(f(!1),u.current&&(u.current.src=""))},[t]),v.useEffect(()=>{h&&p.current&&(p.current.scrollTop=p.current.scrollHeight)},[c.length,h]);const m=v.useCallback(()=>{a(h?"collapsed":"expanded")},[h,a]),g=v.useCallback(()=>{a("modal")},[a]),y=v.useCallback(async()=>{await i()},[i]),b=v.useMemo(()=>{if(!s)return"Browser";try{return new URL(s).hostname}catch{return s}},[s]);if(!t||n==="modal")return null;const x=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:"bg-surface3 border-border1 relative h-14 w-24 shrink-0 overflow-hidden rounded-md border",children:[d?o.jsx("img",{ref:u,alt:"Browser preview",className:"h-full w-full object-cover"}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Vot,{className:"text-neutral3 h-5 w-5"})}),x&&o.jsx("div",{className:"bg-success absolute top-1 right-1 h-2 w-2 animate-pulse rounded-full"})]}),o.jsxs("div",{className:"min-w-0 flex-1 text-left",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("span",{className:"text-neutral6 truncate text-sm font-medium",children:[e,"'s browser"]}),o.jsx(Og,{variant:x?"success":"neutral",size:"sm",withDot:!0,pulse:x,children:x?"Live":"Idle"})]}),o.jsx("p",{className:"text-neutral4 mt-0.5 truncate text-xs",children:b})]}),o.jsx("div",{className:"text-neutral4 group-hover:text-neutral5 shrink-0 transition-colors",children:h?o.jsx(ka,{className:"h-5 w-5"}):o.jsx(k_,{className:"h-5 w-5"})})]}),h&&o.jsxs("div",{className:"border-border1 border-t",children:[o.jsx("div",{className:"p-3",children:o.jsxs("div",{className:"relative",children:[o.jsx(CMt,{className:"w-full"}),o.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[o.jsx(ce,{variant:"default",size:"icon-sm",tooltip:"Center view",onClick:g,className:"bg-surface1/80 backdrop-blur-sm",children:o.jsx(WGt,{className:"h-3.5 w-3.5"})}),o.jsx(ce,{variant:"default",size:"icon-sm",tooltip:"Close browser",onClick:y,className:"bg-surface1/80 backdrop-blur-sm",children:o.jsx(ps,{className:"h-3.5 w-3.5"})})]})]})}),c.length>0&&o.jsx("div",{ref:p,className:"border-border1 max-h-40 overflow-y-auto border-t",children:o.jsxs("div",{className:"px-3 py-2",children:[o.jsx("h4",{className:"text-neutral4 mb-2 text-xs font-medium",children:"Browser Actions"}),o.jsx("div",{className:"space-y-1",children:c.slice(-5).map(S=>o.jsx(_Mt,{entry:S},S.toolCallId))})]})})]})]})}function f4r({className:e}){const{toolCalls:t}=KEe(),[n,r]=v.useState(!0),s=v.useRef(null);return v.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:"hover:bg-surface3 flex w-full shrink-0 items-center gap-2 px-3 py-1 text-left transition-colors",children:[o.jsx(ka,{className:X("h-3.5 w-3.5 text-neutral3 transition-transform",n?"rotate-180":"")}),o.jsxs("span",{className:"text-neutral4 text-xs font-medium",children:["Browser Actions (",t.length,")"]})]}),n&&o.jsx("div",{ref:s,className:"bg-surface1 flex-1 overflow-y-auto",children:t.map(a=>o.jsx(_Mt,{entry:a},a.toolCallId))})]})}const p4r=(e,t)=>{const n=v.useRef(null);v.useEffect(()=>{e?(n.current=document.activeElement,t?.current?.focus()):n.current&&(n.current.focus(),n.current=null)},[e,t])};function h4r(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 XEe(){const{viewMode:e,status:t,currentUrl:n,hide:r,closeBrowser:s}=L4(),a=e==="modal",i=v.useRef(null);p4r(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{}};v.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=h4r(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:"border-border1 flex shrink-0 items-center gap-3 border-b px-4 py-3",children:[o.jsx(Kx,{className:"text-neutral4 h-4 w-4 shrink-0"}),o.jsx("div",{className:"bg-surface3 border-border1 min-w-0 flex-1 rounded-md border px-3 py-1.5",children:o.jsx("span",{className:X("text-sm truncate block",n?"text-neutral5":"text-neutral3 italic"),children:n||"No URL"})}),o.jsx(Og,{variant:u.variant,size:"sm",withDot:!0,pulse:u.pulse,children:u.label}),o.jsxs("div",{className:"ml-2 flex items-center gap-1",children:[o.jsx(ce,{variant:"ghost",size:"icon-sm",tooltip:"Minimize to chat",onClick:r,children:o.jsx(tQt,{className:"h-4 w-4"})}),n&&o.jsx(ce,{variant:"ghost",size:"icon-sm",tooltip:"Open in new tab",onClick:l,children:o.jsx(_a,{className:"h-4 w-4"})}),o.jsx(ce,{variant:"ghost",size:"icon-sm",tooltip:"Close browser",onClick:s,children:o.jsx(ps,{className:"h-4 w-4"})})]})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto",children:[o.jsx("div",{className:"p-4",children:o.jsx(CMt,{className:"max-h-[60vh] w-full"})}),o.jsx("div",{className:"px-4 pb-4",children:o.jsx(f4r,{})})]})]})})}const TMt=v.createContext({isConversationLoading:!1}),m4r=[],g4r=[{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:zGt},{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:Vp},{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:PGt},{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:_xe}],v4r=({agentId:e,agentName:t,agentDescription:n,agentAvatarUrl:r,children:s})=>{const{data:a}=Im(),i=a?.id?`${a.id}-${e}`:e,{data:l,isLoading:c}=uW({agentId:e,threadId:i,memory:!0}),u=l?.messages??m4r,d=v.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(TMt.Provider,{value:d,children:s})},i)},y4r=({hasBrowser:e=!1})=>{const t=bu(),n=SEe(),{draft:r,setDraft:s,trimmed:a,handleFormSubmit:i,handleKeyDown:l}=j2t({onSubmit:n});return o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[o.jsx(x4r,{onStarterPromptSelect:s}),e&&o.jsx(b4r,{}),o.jsx(REe,{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"})]})},b4r=()=>{const{hasSession:e,viewMode:t}=L4();return!e||t==="modal"?null:o.jsx("div",{className:"mx-auto mb-2 w-full max-w-3xl",children:o.jsx(EMt,{})})},x4r=({onStarterPromptSelect:e})=>{const t=wEe(),n=bu(),{isConversationLoading:r,agentName:s,agentDescription:a,agentAvatarUrl:i}=v.useContext(TMt);return o.jsx(ZEe,{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(g_,{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:g4r.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 border-border1 bg-surface2 duration-normal ease-out-custom hover:border-border2 hover:bg-surface3 focus-visible:ring-accent1 flex gap-3 rounded-3xl border p-4 text-left transition-colors focus-visible:ring-2 focus-visible:outline-none",children:[o.jsx("span",{className:"bg-surface3 text-neutral4 group-hover:text-neutral6 mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md transition-colors",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 group-hover:text-neutral6 font-medium transition-colors",children:l.title}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 group-hover:text-neutral5 mt-1 transition-colors",children:l.description})]})]},l.title))})]})})},w4r=({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(C1e,{label:"Agent navigation",className:"min-w-0",listClassName:"min-w-0",children:[o.jsx(B$,{as:za,to:"/agent-builder/agents","data-testid":"agent-builder-back-to-list",children:"Agent list"}),o.jsx(B$,{as:"span",isCurrent:!0,children:o.jsx(bMt,{isLoading:!1})})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2 justify-self-end",children:[r&&o.jsx("div",{className:"hidden shrink-0 items-center gap-2 lg:flex",children:r}),s&&o.jsx("div",{className:"shrink-0 lg:hidden",children:s}),e&&t&&o.jsxs(ce,{variant:"ghost",size:"sm",onClick:t,disabled:n,className:"hidden shrink-0 lg:inline-flex","data-testid":"agent-builder-mode-toggle","aria-label":a,children:[o.jsx(a1,{}),a]})]})]})};function S4r(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 jMt=v.createContext(null),k4r=({agentId:e,storedAgent:t,currentUserId:n,canWrite:r,children:s})=>{const a=Bf(),i=Ws(),l=v.useMemo(()=>S4r(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=v.useMemo(()=>c?()=>i(`/agent-builder/agents/${e}/edit`,{viewTransition:!0}):void 0,[c,e,i]),m=v.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(jMt.Provider,{value:m,children:o.jsx(v4r,{agentId:e,agentName:t.name,agentDescription:t.description,agentAvatarUrl:l.avatarUrl,children:s})})},NMt=()=>{const e=v.useContext(jMt);if(!e)throw new Error("useViewPage must be used inside <ViewPageProvider>");return e},O4r=({topBar:e,chat:t,browserOverlay:n})=>o.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-1 flex-col",children:[e,o.jsx("div",{className:"min-h-0 w-full min-w-0 flex-1 overflow-hidden px-4 pt-10 pb-4 md:mx-auto md:max-w-[80ch] md:px-10 md:pt-4 md:pb-10","data-testid":"agent-builder-panel-chat",children:t}),n]}),_4r=(e,t)=>["browser-session-probe",e,t],C4r={hasSession:!0,screencastAvailable:!0},E4r=e=>!e||typeof e!="object"?!1:"status"in e&&e.status===404||"statusCode"in e&&e.statusCode===404;function T4r({agentId:e,threadId:t,enabled:n=!0}){const r=We();return yt({queryKey:_4r(e,t),queryFn:async()=>{if(!e)return{hasSession:!1,screencastAvailable:!1};try{return await r.getAgent(e).browserSession(t)}catch(s){if(E4r(s))return C4r;throw s}},enabled:n&&!!e,refetchOnWindowFocus:!0,staleTime:0,retry:1})}function j4r(){const e=We();return Ln({mutationFn:({agentId:t,threadId:n})=>e.getAgent(t).closeBrowser(n),onError:t=>{console.error("[useCloseBrowser] Error closing browser:",t)}})}function N4r(){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 AZ({children:e,agentId:t,threadId:n,enabled:r=!0}){const[s,a]=v.useState(!1),[i,l]=v.useState("collapsed"),{data:c}=T4r({agentId:t,threadId:n,enabled:r}),u=c?.screencastAvailable??!1,d=c?.hasSession??!1,p=r&&u&&(d||i!=="collapsed"),h=v.useRef(p),m=v.useRef(t),g=v.useRef(n);v.useEffect(()=>{h.current=p,m.current=t,g.current=n});const[y,b]=v.useState("idle"),[x,S]=v.useState(null),[k,C]=v.useState(null),_=v.useRef(N4r()),E=v.useRef(null),T=v.useRef(0),N=v.useRef(null),I=v.useRef(null),A=5,R=v.useCallback(()=>{N.current&&(clearTimeout(N.current),N.current=null)},[]),L=v.useCallback(()=>{R(),I.current=null,E.current&&(E.current.close(),E.current=null),T.current=0,a(!1),b("idle"),S(null),_.current.setFrame(null),C(null)},[R]),D=v.useCallback(Z=>{E.current?.readyState===WebSocket.OPEN&&E.current.send(Z)},[]),z=v.useRef(!1),H=v.useCallback(()=>{if(!h.current)return;const Z=m.current,K=g.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 ee=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/browser/${Z}/stream?threadId=${encodeURIComponent(K)}`;try{const J=new WebSocket(ee);z.current=!1,E.current=J,J.onopen=()=>{b("connected"),T.current=0},J.onmessage=ae=>{const fe=ae.data;if(fe.startsWith("{"))try{const Y=JSON.parse(fe);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&&S(Y.url),Y.viewport&&C(Y.viewport)}catch{_.current.setFrame(fe)}else _.current.setFrame(fe),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&&T.current<A){T.current+=1;const fe=Math.min(1e3*Math.pow(2,T.current-1),1e4);b("disconnected"),N.current=setTimeout(()=>{H()},fe)}else T.current>=A?b("error"):b("disconnected")}}catch{b("error")}},[R]);v.useEffect(()=>(p&&t&&n&&H(),()=>{L()}),[p,t,n,H,L]),v.useEffect(()=>{if(!p)return;const Z=()=>{document.visibilityState==="visible"&&y==="disconnected"&&t&&n&&(T.current=0,H())};return document.addEventListener("visibilitychange",Z),()=>{document.removeEventListener("visibilitychange",Z)}},[p,y,t,n,H]);const F=v.useCallback(Z=>{l(Z)},[]),U=v.useCallback(()=>{l("modal")},[]),q=v.useCallback(()=>{l("collapsed")},[]),M=v.useCallback(()=>{a(!1),l("collapsed"),_.current.setFrame(null)},[]),G=j4r(),V=v.useCallback(async()=>{if(!(G.isPending||!t))try{await G.mutateAsync({agentId:t,threadId:n}),M()}catch{}},[t,n,G,M]),$=G.isPending,B=v.useMemo(()=>({hasSession:s,viewMode:i,isPanelOpen:i==="modal",isActive:s,status:y,currentUrl:x,viewport:k,isClosing:$,setViewMode:F,show:U,hide:q,endSession:M,closeBrowser:V,sendMessage:D,connect:H,disconnect:L}),[s,i,y,x,k,$,F,U,q,M,V,D,H,L]);return o.jsx(SMt.Provider,{value:B,children:o.jsx(kMt.Provider,{value:_.current,children:e})})}function I4r(){const{id:e}=Sr(),{data:t,isLoading:n}=j4(e,{status:"draft"}),{data:r,isLoading:s}=Im(),{canWrite:a}=zy();return xMt(),e?n||s?o.jsx($4r,{}):t?o.jsx(k4r,{agentId:e,storedAgent:t,currentUserId:r?.id,canWrite:a,children:o.jsx(A4r,{storedAgent:t})}):o.jsx(Qu,{to:"/agent-builder/agents",replace:!0}):null}const A4r=({storedAgent:e})=>{const{hasBrowser:t,agentId:n,threadId:r}=NMt(),[s]=v.useState(()=>wMt(e)),a=eS({defaultValues:s}),i=o.jsx(R4r,{hasBrowser:t});return t?o.jsx(Q$,{...a,children:o.jsx(SD,{agentId:n,children:o.jsx(IZ,{children:o.jsx(AZ,{agentId:n,threadId:r,children:i})})})}):o.jsx(Q$,{...a,children:o.jsx(SD,{agentId:n,children:i})})},R4r=v.memo(function({hasBrowser:t}){const n=v.useMemo(()=>o.jsx(P4r,{}),[]),r=v.useMemo(()=>o.jsx(y4r,{hasBrowser:t}),[t]),s=v.useMemo(()=>t?o.jsx(XEe,{}):void 0,[t]);return o.jsx(O4r,{topBar:n,chat:r,browserOverlay:s})}),P4r=()=>{const{canModify:e,onModeToggle:t,isOwner:n,agentId:r,agent:s}=NMt(),a=bu();return o.jsx(w4r,{mode:e?"test":void 0,onModeToggle:t,modeToggleDisabled:a,mobileMenu:n&&o.jsx(g2t,{agentId:r,showEditAgent:!0,showDelete:!0,agentName:s.name,disabled:a})})},$4r=()=>o.jsx("div",{className:"flex h-screen w-screen items-center justify-center",children:o.jsx(Jt,{})}),wQe=(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}},M4r=e=>{const t=We(),n=Br(),{requestContext:r}=hs();return Ln({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?wQe(d,s):d)});return a&&n.setQueryData(["stored-skill",e],wQe(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]})}})},D4r={sm:14,md:16},vbe=({skillId:e,isFavorited:t=!1,favoriteCount:n,size:r="md",className:s,showCount:a=!0})=>{const i=Bf(),l=M4r(e),{data:c}=uc();if(!i.favorites)return null;const u=c?Cm(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(ce,{type:"button",variant:"default",size:r,"aria-pressed":t,"aria-label":u?d:f,title:u?d:f,disabled:m,onClick:g=>{g.preventDefault(),g.stopPropagation(),u&&l.mutate({favorited:!t})},className:X("shrink-0",u?"cursor-pointer":"cursor-not-allowed",s),children:[o.jsx(xj,{size:D4r[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 L4r(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 JEe({skills:e,search:t,onSkillClick:n,showFavorites:r=!0}){const s=v.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(Lr,{iconSlot:o.jsx(Xa,{className:"text-neutral3 h-8 w-8"}),titleSlot:"No skills match your search",descriptionSlot:"Try a different name or description."})}):o.jsx("div",{className:"bg-surface2 border-border1 divide-border1 divide-y overflow-hidden rounded-xl border",children:s.map(a=>{const i=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx("div",{className:"text-ui-md text-neutral6 truncate",children:a.name}),a.visibility==="private"&&o.jsxs($n,{children:[o.jsx(Rn,{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(Tf,{})})})}),o.jsx(Pn,{children:"Only visible to you"})]}),(()=>{const l=L4r(a.metadata);if(!l)return null;const c=l.type==="library-copy";return o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsxs("span",{className:"bg-surface5 text-neutral4 inline-flex shrink-0 items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-medium","aria-label":c?"Copied skill":"Imported skill","data-testid":"skill-builder-origin-badge",children:[c?o.jsx(im,{className:"h-2.5 w-2.5"}):o.jsx(kf,{className:"h-2.5 w-2.5"}),l.type==="skills-sh"?"skills.sh":c?"copied":"imported"]})}),o.jsx(Pn,{children:l.type==="skills-sh"?`Imported from ${l.owner}/${l.repo}`:c?`Copied from "${l.sourceSkillName}"`:"Imported from external registry"})]})})()]}),o.jsx("div",{className:"mt-0.5 flex items-center gap-2",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(vbe,{skillId:a.id,isFavorited:a.isFavorited,favoriteCount:a.favoriteCount,size:"sm"})})]}),r&&o.jsx(vbe,{skillId:a.id,isFavorited:a.isFavorited,favoriteCount:a.favoriteCount,size:"sm",className:"hidden shrink-0 md:inline-flex"})]});return n?o.jsx("button",{className:"hover:bg-surface3/50 flex w-full items-start gap-4 px-6 py-5 text-left transition-colors md:items-center",onClick:()=>n(a),children:i},a.id):o.jsx("div",{className:"flex items-start gap-4 px-6 py-5 md:items-center",children:i},a.id)})})}function eTe({rows:e=4}){return o.jsx("div",{className:"bg-surface2 border-border1 divide-border1 divide-y overflow-hidden rounded-xl border",children:Array.from({length:e}).map((t,n)=>o.jsxs("div",{className:"flex items-center gap-4 px-6 py-5",children:[o.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[o.jsx("div",{className:"bg-surface3 h-3.5 w-48 animate-pulse rounded"}),o.jsx("div",{className:"bg-surface3 h-3 w-72 max-w-full animate-pulse rounded"})]}),o.jsx("div",{className:"bg-surface3 h-3 w-16 animate-pulse rounded"})]},n))})}function z4r(){const e=Ws(),[t,n]=v.useState(""),[r,s]=v.useState("agents"),a=Bf(),{data:i}=Im(),l=S=>{const C=!S.authorId||i?.id===S.authorId?"edit":"view";e(`/agent-builder/skills/${S.id}/${C}`,{viewTransition:!0})},c=v.useMemo(()=>({favoritedOnly:!0,orderBy:{field:"updatedAt",direction:"DESC"}}),[]),{data:u,isLoading:d,error:f}=m_(c),{data:p,isLoading:h,error:m}=oS({enabled:r==="skills"&&a.skills}),g=u?.agents??[],y=p?.skills??[],b=(S,k)=>ws(S)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Zs,{})}):Ss(S)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ms,{resource:k})}):o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Hi,{title:`Failed to load favorite ${k}`,message:S.message})}),x=r==="agents"?d?o.jsx(yEe,{rowTestId:"favorite-skeleton-row"}):f?b(f,"agents"):g.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(Lr,{iconSlot:o.jsx(xj,{className:"text-neutral3 h-8 w-8"}),titleSlot:"No favorite agents yet",descriptionSlot:"Star agents to keep them here for quick access."})}):o.jsx(vEe,{agents:g,search:t,rowTestId:"favorite-agent-row"}):h?o.jsx(eTe,{}):m?b(m,"skills"):y.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(Lr,{iconSlot:o.jsx(Ig,{className:"text-neutral3 h-8 w-8"}),titleSlot:"No favorite skills yet",descriptionSlot:"Star skills to keep them here for quick access."})}):o.jsx(JEe,{skills:y,search:t,onSkillClick:l});return o.jsx(o.Fragment,{children:o.jsxs(Bt,{className:"px-4 md:px-10",children:[o.jsxs(Bt.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(Ef,{children:[o.jsxs(Ef.Title,{children:[o.jsx(xj,{})," Favorites"]}),o.jsx(Ef.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:"border-border1 flex overflow-hidden rounded-lg border",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:"max-w-120 flex-1",children:o.jsx(Ff,{onSearch:n,label:"Filter favorites",placeholder:"Filter by name or description"})})]})]}),x]})})}function F4r({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 ybe({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(F4r,{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 B4r=e=>{const t=We();return yt({queryKey:["infrastructure-status"],queryFn:()=>t.getInfrastructureStatus(),enabled:e?.enabled??!0,retry:!1})},aP=({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]}),Dse=({message:e})=>o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:e}),kk=e=>e==null?e:String(e).split(/([\s-]+)/).map(t=>/^[\s-]+$/.test(t)?t:t.charAt(0).toUpperCase()+t.slice(1)).join(""),Lb=({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"})]}),SQe=({entries:e})=>e.length===0?null:o.jsx("div",{className:"border-border1 grid grid-cols-1 gap-3 border-t pt-3 sm:grid-cols-2",children:e.map(t=>o.jsx(Lb,{label:`Config: ${t.key}`,value:kk(t.value)},t.key))}),U4r=()=>{const{hasPermission:e}=Go(),t=e("infrastructure:read"),{data:n,isLoading:r,error:s}=B4r({enabled:t}),a=n;return o.jsxs(Bt,{width:"narrow",children:[o.jsx(Bt.TopArea,{children:o.jsx(Ef,{children:o.jsx(Ef.Title,{children:"Infrastructure"})})}),o.jsx(Bt.MainArea,{className:"mt-6 flex flex-col gap-5",children:o.jsx(ybe,{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(Dse,{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:"border-border1 rounded-md border 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:kk(i.name)}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3",children:["Provider ID: ",i.id]})]}),o.jsx(aP,{ok:i.isConfigured,label:i.isConfigured?"Configured":"Not configured"})]}),o.jsxs("div",{className:"border-border1 mt-3 grid grid-cols-1 gap-3 border-t pt-3 sm:grid-cols-2",children:[o.jsx(Lb,{label:"Registered by",value:`${kk(i.name)} provider`}),o.jsx(Lb,{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:"border-border1 rounded-md border 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:kk(a.browser.provider)})}),o.jsx(aP,{ok:a.browser.registered,label:a.browser.registered?"Provider available":"Provider missing"})]}),a.browser.env?o.jsx("div",{className:"border-border1 mt-3 grid grid-cols-1 gap-3 border-t pt-3 sm:grid-cols-2",children:o.jsx(Lb,{label:"Environment",value:kk(a.browser.env)})}):null,o.jsx(SQe,{entries:a.browser.config})]}):o.jsx(Dse,{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:"border-border1 rounded-md border 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(aP,{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:"border-border1 rounded-md border 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(aP,{ok:a.workspace.hasFilesystem,label:"Filesystem"}),o.jsx(aP,{ok:a.workspace.hasSandbox,label:"Sandbox"})]})]}),o.jsxs("div",{className:"border-border1 mt-3 grid grid-cols-1 gap-3 border-t pt-3 sm:grid-cols-2",children:[o.jsx(Lb,{label:"Config type",value:a.workspace.type==="id"?"Registered workspace":"Inline config"}),a.workspace.workspaceId?o.jsx(Lb,{label:"Workspace ID",value:a.workspace.workspaceId}):null,o.jsx(Lb,{label:"Name",value:a.workspace.name}),o.jsx(Lb,{label:"Filesystem provider",value:kk(a.workspace.filesystemProvider)}),o.jsx(Lb,{label:"Sandbox provider",value:kk(a.workspace.sandboxProvider)})]}),o.jsx(SQe,{entries:a.workspace.config})]}):o.jsx(Dse,{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 q4r(){const e=Ws(),[t,n]=v.useState(""),[r,s]=v.useState("agents"),a=Bf(),{canUseFavorites:i}=zy(),l=v.useMemo(()=>({visibility:"public"}),[]),{data:c,isLoading:u,error:d}=m_(l),{data:f,isLoading:p,error:h}=oS({enabled:r==="skills"&&a.skills}),m=c?.agents??[],g=f?.skills??[],y=x=>ws(x)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Zs,{})}):Ss(x)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ms,{resource:r})}):o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Hi,{title:"Failed to load the library",message:x.message})}),b=r==="agents"?u?o.jsx(yEe,{rowTestId:"library-skeleton-row"}):d?y(d):m.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(Lr,{iconSlot:o.jsx(Q2,{className:"text-neutral3 h-8 w-8"}),titleSlot:"No public agents yet",descriptionSlot:"Mark an agent as Public to share it with the team library."})}):o.jsx(vEe,{agents:m,search:t,rowTestId:"library-agent-row",showFavorites:i}):p?o.jsx(eTe,{}):h?y(h):g.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(Lr,{iconSlot:o.jsx(Ig,{className:"text-neutral3 h-8 w-8"}),titleSlot:"No public skills yet",descriptionSlot:"Mark a skill as Public to share it with the team library."})}):o.jsx(JEe,{skills:g,search:t,onSkillClick:x=>e(`/agent-builder/skills/${x.id}/view`,{viewTransition:!0}),showFavorites:i});return o.jsx(o.Fragment,{children:o.jsxs(Bt,{className:"px-4 md:px-10",children:[o.jsxs(Bt.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(Ef,{children:[o.jsxs(Ef.Title,{children:[o.jsx(Q2,{})," Library"]}),o.jsx(Ef.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:"border-border1 flex overflow-hidden rounded-lg border",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:"max-w-120 flex-1",children:o.jsx(Ff,{onSearch:n,label:"Filter library",placeholder:"Filter by name or description"})})]})]}),b]})})}const ZI=e=>o.jsx(PNn,{...e}),V4r=300*1e3;function H4r(e){const t=We();return yt({queryKey:["builder-registries"],queryFn:()=>t.listBuilderRegistries(),enabled:e?.enabled??!0,retry:!1})}function W4r(e){const t=We();return Ln({mutationFn:async n=>{if(!e)throw new Error("Registry ID is required");return t.searchBuilderRegistry(e,{q:n,limit:10})}})}function Z4r(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:V4r,retry:!1})}function G4r(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 Q4r(e){const t=We(),n=Br();return Ln({mutationFn:async r=>{if(!e)throw new Error("Registry ID is required");return t.installBuilderRegistrySkill(e,r)},onSuccess:()=>{n.invalidateQueries({queryKey:["stored-skills"]})}})}function Y4r(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 kQe(e){return`${e.topSource}/${e.name}`}function K4r({open:e,onOpenChange:t,registryId:n,registryLabel:r,installedSkillIds:s=[],onInstalled:a,onCollision:i}){const[l,c]=v.useState(""),[u,d]=v.useState(null),[f,p]=v.useState(null),{data:h,isLoading:m}=Z4r(e?n:void 0),g=W4r(n),y=Q4r(n),b=v.useMemo(()=>u?.topSource?Y4r(u.topSource):null,[u]),{data:x,isLoading:S}=G4r(n,b?.owner,b?.repo,u?.name,{enabled:!!b&&!!u&&e}),k=Uy(L=>{L.trim().length>=2&&g.mutate(L)},300),C=v.useCallback(L=>{c(L),k(L)},[k]),_=v.useMemo(()=>l.trim().length>=2?g.data?.skills??[]:h?.skills??[],[l,g.data,h]),E=g.isPending,T=l.trim().length>=2,N=v.useMemo(()=>u?s.includes(u.name):!1,[u,s]),I=v.useMemo(()=>b?`https://github.com/${b.owner}/${b.repo}`:null,[b]),A=v.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 D=L?.message??"Install failed";/409/.test(D)||/already exists/i.test(D)?(i?.(u.name),p("A skill with this name already exists. Open the existing skill instead.")):p(D)}}},[u,b,y,a,t,i]),R=v.useCallback(L=>{L||(c(""),d(null),p(null)),t(L)},[t]);return o.jsx(vr,{open:e,onOpenChange:R,children:o.jsxs(yr,{className:"flex h-[80vh] max-w-4xl flex-col",children:[o.jsxs(br,{children:[o.jsxs(hr,{children:["Browse ",r]}),o.jsxs(Bs,{children:["Find a public skill from ",r," and import it into your Builder skill library."]})]}),o.jsxs(Rr,{className:"flex max-h-none flex-1 flex-col gap-4 overflow-hidden",children:[o.jsxs("div",{className:"relative",children:[o.jsx(Xa,{className:"text-neutral3 absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2"}),o.jsx(Cn,{placeholder:`Search ${r}...`,value:l,onChange:L=>C(L.target.value),className:"pl-9","data-testid":"builder-add-skill-search"})]}),o.jsxs("div",{className:"flex min-h-0 flex-1 gap-4",children:[o.jsxs("div",{className:"flex min-h-0 w-1/2 flex-col",children:[o.jsx("div",{className:"text-neutral4 mb-2 text-xs font-medium tracking-wide uppercase",children:T?"Search results":"Popular skills"}),o.jsx(Fr,{className:"border-border1 flex-1 rounded-lg border",children:m||E?o.jsx("div",{className:"flex items-center justify-center py-8",children:o.jsx(ua,{className:"text-neutral3 h-6 w-6 animate-spin"})}):_.length===0?o.jsxs("div",{className:"text-neutral4 flex flex-col items-center justify-center py-8",children:[o.jsx(ty,{className:"mb-2 h-8 w-8"}),o.jsx("p",{className:"text-sm",children:T?"No skills found":"No skills available"})]}):o.jsx("div",{className:"space-y-1 p-2",children:_.map(L=>{const D=kQe(L),z=s.includes(L.name),H=u?kQe(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===D&&"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:"text-neutral6 truncate text-sm font-medium",children:L.name}),z&&o.jsxs("span",{className:"bg-accent1/20 text-accent1 inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-medium",children:[o.jsx(fa,{className:"h-2.5 w-2.5"}),"Installed"]})]}),o.jsx("div",{className:"text-neutral4 truncate text-xs",children:L.topSource})]}),o.jsxs("div",{className:"text-neutral3 flex shrink-0 items-center gap-1 text-xs",children:[o.jsx(kf,{className:"h-3 w-3"}),o.jsx("span",{children:L.installs.toLocaleString()})]})]})},D)})})})]}),o.jsx("div",{className:"border-border1 flex min-h-0 w-1/2 flex-col overflow-hidden rounded-lg border",children:u?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"border-border1 bg-surface3 border-b p-4",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"bg-surface5 rounded-lg p-2",children:o.jsx(ZI,{className:"text-neutral4 h-5 w-5"})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("h3",{className:"text-neutral6 truncate font-semibold",children:u.name}),o.jsxs("div",{className:"text-neutral4 mt-1 flex items-center gap-3 text-xs",children:[o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(Bot,{className:"h-3 w-3"}),u.topSource]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(kf,{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(_a,{className:"h-4 w-4"})})]})}),S?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(ua,{className:"text-neutral3 h-6 w-6 animate-spin"})}):x?o.jsx(Fr,{className:"flex-1",children:o.jsx("div",{className:"p-4",children:o.jsx(Xp,{children:x})})}):o.jsxs("div",{className:"text-neutral4 flex flex-1 flex-col items-center justify-center",children:[o.jsx(ty,{className:"mb-2 h-8 w-8"}),o.jsx("p",{className:"text-sm",children:"Preview unavailable"})]})]}):o.jsxs("div",{className:"text-neutral4 flex flex-1 flex-col items-center justify-center",children:[o.jsx(ty,{className:"mb-2 h-8 w-8"}),o.jsx("p",{className:"text-sm",children:"Select a skill to preview"})]})})]}),u&&o.jsxs("div",{className:"border-border1 flex flex-col gap-3 border-t pt-4",children:[f&&o.jsx("div",{className:"rounded-md border border-red-500/20 bg-red-500/10 px-3 py-2 text-sm text-red-400",children:f}),o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[o.jsx(ce,{variant:"default",onClick:()=>R(!1),children:"Cancel"}),o.jsx(ce,{variant:"primary",onClick:A,disabled:!b||y.isPending||N,"data-testid":"builder-install-skill-button",children:y.isPending?o.jsxs(o.Fragment,{children:[o.jsx(ua,{className:"mr-2 h-4 w-4 animate-spin"}),"Installing..."]}):N?o.jsxs(o.Fragment,{children:[o.jsx(fa,{className:"mr-2 h-4 w-4"}),"Already installed"]}):o.jsxs(o.Fragment,{children:[o.jsx(kf,{className:"mr-2 h-4 w-4"}),"Install"]})})]})]})]})]})})}function X4r(){const e=Ws(),{isLoading:t}=Im(),{hasPermission:n,rbacEnabled:r}=Go(),s=!r||n("stored-skills:write"),a=!r||n("stored-skills:read"),[i,l]=v.useState(null),c=()=>e("/agent-builder/skills/create",{viewTransition:!0}),u=C=>e(`/agent-builder/skills/${C}/edit`,{viewTransition:!0}),{data:d,isLoading:f,error:p}=oS({enabled:!t}),[h,m]=v.useState(""),g=v.useMemo(()=>d?.skills??[],[d?.skills]),y=v.useMemo(()=>g.map(C=>C.id),[g]),{data:b}=H4r({enabled:a&&s}),x=v.useMemo(()=>b?.registries.find(C=>C.enabled)??null,[b]),S=C=>{u(C.id)},k=t||f?o.jsx(eTe,{}):p?ws(p)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Zs,{})}):Ss(p)?o.jsx("div",{className:"flex items-center justify-center pt-10",children:o.jsx(Ms,{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})}):g.length===0?o.jsx("div",{className:"flex items-center justify-center pt-16",children:o.jsx(Lr,{iconSlot:o.jsx(Ig,{className:"text-neutral3 h-8 w-8"}),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(ce,{variant:"primary",onClick:c,children:[o.jsx(Wr,{})," New skill"]}),x&&o.jsxs(ce,{variant:"default",onClick:()=>l({id:x.id,label:x.label}),children:[o.jsx(kf,{})," Browse registry"]})]}):void 0})}):o.jsx(JEe,{skills:g,search:h,onSkillClick:S});return o.jsxs(o.Fragment,{children:[o.jsxs(Bt,{className:"px-4 md:px-10",children:[o.jsxs(Bt.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(Ef,{children:[o.jsxs(Ef.Title,{children:[o.jsx(Ig,{})," My skills"]}),o.jsx(Ef.Description,{children:"Skills you've created."})]}),g.length>0&&s&&o.jsxs("div",{className:"flex w-full shrink-0 flex-col items-stretch gap-2 md:w-auto md:flex-row md:items-center",children:[x&&o.jsxs(ce,{variant:"default",className:"w-full justify-center md:w-auto",onClick:()=>l({id:x.id,label:x.label}),children:[o.jsx(kf,{})," Browse registry"]}),o.jsxs(ce,{variant:"primary",className:"w-full justify-center md:w-auto",onClick:c,children:[o.jsx(Wr,{})," New skill"]})]})]}),o.jsx("div",{className:"max-w-120",children:o.jsx(Ff,{onSearch:m,label:"Filter skills",placeholder:"Filter by name or description"})})]}),k]}),i&&o.jsx(K4r,{open:!!i,onOpenChange:C=>{C||l(null)},registryId:i.id,registryLabel:i.label,installedSkillIds:y,onInstalled:C=>{const _=g.find(E=>E.id===C);lu.success(_?`Imported "${_.name}"`:"Skill imported")},onCollision:C=>{const _=g.find(E=>E.id===C||E.name===C);_?lu.error(`"${_.name}" is already in your library`,{action:{label:"Open existing",onClick:()=>u(_.id)}}):lu.error(`A skill named "${C}" already exists.`)}})]})}const J4r=[{title:"Code reviewer",icon:Vp,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:Nc,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:Uot,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:Tot,prompt:"Build a skill that turns messy research notes into structured findings with sources, methodology, and a tl;dr at the top."}],eLr=e=>e.length<=20?e:e.slice(0,20)+"…",tLr=()=>{const[e,t]=v.useState(""),n=Ws(),r=v.useRef(null),s=AEe(),a=R4(),{data:i}=OZ(),{data:l}=Y1(),c=v.useMemo(()=>(i?.workspaces??[]).filter(g=>g.status!=="archived").sort((g,y)=>(y.runtimeRegistered?1:0)-(g.runtimeRegistered?1:0)).map(g=>({value:g.id,label:g.name})),[i]),u=v.useMemo(()=>{const g=l?.configuration?.agent?.workspace;return g?.type==="id"?g.workspaceId:void 0},[l]),d=e.trim(),f=s.isPending,p=async g=>{if(g.preventDefault(),d.length===0||f)return;const y=kq(),b=u??(c.length===1?c[0].value:void 0);try{await s.mutateAsync({id:y,name:eLr(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=g=>{f||g.key==="Enter"&&!g.shiftKey&&!g.nativeEvent.isComposing&&(g.preventDefault(),g.currentTarget.form?.requestSubmit())},m=g=>{t(g),r.current?.focus()};return o.jsx("div",{className:"starter-aurora bg-surface1 flex min-h-full flex-col items-center justify-center 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-neutral6 text-center font-serif",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 border-border1 bg-surface2 duration-normal ease-out-custom focus-within:border-neutral3 rounded-2xl border transition-colors",style:{viewTransitionName:"skill-chat-composer"},children:[o.jsx(Dl,{ref:r,testId:"skill-builder-starter-input",size:"default",variant:"unstyled",placeholder:"Describe the skill you want to build…",value:e,onChange:g=>t(g.target.value),onKeyDown:h,disabled:f,className:"text-ui-md placeholder:text-neutral3 min-h-[112px] resize-none px-5 py-4 outline-none 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(ce,{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(Jt,{})}):o.jsx(BD,{})})})]})}),o.jsx("div",{className:"flex flex-wrap justify-center gap-2",children:J4r.map((g,y)=>{const b=g.icon;return o.jsxs("button",{type:"button",onClick:()=>m(g.prompt),"data-testid":`skill-builder-starter-example-${g.title.toLowerCase().replace(/\s+/g,"-")}`,style:{animationDelay:`${280+y*40}ms`},className:"starter-chip group border-border1 text-ui-sm text-neutral4 duration-normal ease-out-custom hover:border-border2 hover:bg-surface2 hover:text-neutral6 inline-flex items-center gap-2 rounded-full border bg-transparent px-4 py-2 transition-colors",children:[o.jsx(b,{className:"text-neutral3 group-hover:text-neutral5 h-3.5 w-3.5 transition-colors"}),g.title]},g.title)})})]})})};function nLr(){const{hasPermission:e,rbacEnabled:t}=Go(),n=!t||e("stored-skills:write");oS({enabled:n}),OZ(),Y1();const r=Ws();return n?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"absolute top-3 left-3 z-10 md:top-6 md:left-6",children:o.jsx(ce,{size:"icon-sm",variant:"ghost",onClick:()=>r("/agent-builder/skills",{viewTransition:!0}),className:"rounded-full",tooltip:"Skills list",children:o.jsx($c,{})})}),o.jsx(tLr,{})]}):o.jsx(Qu,{to:"/agent-builder/skills",replace:!0})}function rLr(e){const t=We(),n=Br();return Ln({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 IMt=({skillId:e})=>{const[t,n]=v.useState(!1),r=Ws(),s=rLr(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}},AMt=({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(ce,{variant:"primary","data-testid":"skill-builder-delete-skill-confirm",disabled:r,onClick:()=>{s()},children:r?"Deleting…":"Delete skill"})]})]})}),sLr=({skillId:e,skillName:t,disabled:n=!1})=>{const{open:r,setOpen:s,isPending:a,confirm:i}=IMt({skillId:e});return o.jsxs(o.Fragment,{children:[o.jsxs(ce,{size:"lg",variant:"default",onClick:()=>s(!0),disabled:n||a,className:"w-full","data-testid":"skill-builder-delete-skill",children:[o.jsx(vu,{}),o.jsx("span",{children:"Delete skill"})]}),o.jsx(AMt,{open:r,onOpenChange:s,skillName:t,isPending:a,onConfirm:i})]})},aLr=({skillId:e,skillName:t,disabled:n=!1})=>{const{open:r,setOpen:s,isPending:a,confirm:i}=IMt({skillId:e});return o.jsxs(o.Fragment,{children:[o.jsxs(ot.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(vu,{}),o.jsx("span",{children:"Delete skill"})]}),o.jsx(AMt,{open:r,onOpenChange:s,skillName:t,isPending:a,onConfirm:i})]})};function RMt(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(...RMt(r.children,s))}return n}function tTe(e={}){const t=We(),n=Br(),r=D2t(),{hasPermission:s}=Go(),a=s("workspaces:write"),{silent:i=!1}=e;return Ln({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 x=RMt(h,"");try{await Promise.all(x.map(S=>r.mutateAsync({workspaceId:m,path:`skills/${S.path}`,content:S.content,recursive:!0})))}catch(S){console.warn("[skill] Workspace file write failed, saving to DB only:",S)}}const g=p??(h?Oq(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),g!==void 0&&(b.instructions=g),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 iLr={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 PMt(e){const t=Ur(),n=tTe({silent:!0});return p2t({copy:iLr,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 oLr({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(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ce,{size:"icon-sm",variant:"ghost",tooltip:"More actions","data-testid":"skill-builder-mobile-menu-trigger",children:o.jsx(qD,{})})}),o.jsxs(ot.Content,{align:"end",children:[t&&o.jsx(lLr,{skillId:e,disabled:s}),t&&n&&o.jsx(ot.Separator,{}),n&&o.jsx(aLr,{skillId:e,skillName:r,disabled:s})]})]})})}function lLr({skillId:e,disabled:t}){const n=Ur(),r=zn({control:n.control,name:"visibility"})??"private",{requestChange:s,dialog:a}=PMt(e);return o.jsxs(o.Fragment,{children:[r==="private"?o.jsxs(ot.Item,{"data-testid":"skill-builder-mobile-menu-visibility-add",disabled:t,closeOnClick:!1,onSelect:()=>{s("public")},children:[o.jsx(Kx,{}),o.jsx("span",{children:"Add to library"})]}):o.jsxs(ot.Item,{"data-testid":"skill-builder-mobile-menu-visibility-remove",disabled:t,closeOnClick:!1,onSelect:()=>{s("private")},children:[o.jsx(Tf,{}),o.jsx("span",{children:"Remove from library"})]}),a]})}function cLr({skillId:e}){const t=Ur(),n=zn({control:t.control,name:"visibility"})??"private",{requestChange:r,dialog:s}=PMt(e);return o.jsxs(o.Fragment,{children:[n==="private"?o.jsxs(ce,{size:"sm",variant:"default",onClick:()=>r("public"),"data-testid":"skill-builder-visibility-add",children:[o.jsx(Kx,{className:"h-3.5 w-3.5"}),"Add to library"]}):o.jsxs(ce,{size:"sm",variant:"ghost",onClick:()=>r("private"),"data-testid":"skill-builder-visibility-remove",children:[o.jsx(Tf,{className:"h-3.5 w-3.5"}),"Remove from library"]}),s]})}const uLr=600,dLr=2e3;function fLr({skillId:e,debounceMs:t=uLr,savedDisplayMs:n=dLr}){const r=Ur(),s=tTe({silent:!0}),[a,i]=v.useState("idle"),[l,c]=v.useState(null),u=v.useRef(r.getValues()),d=v.useRef(0),f=v.useRef(null),p=()=>{f.current&&(clearTimeout(f.current),f.current=null)},h=v.useCallback(async()=>{const b=++d.current,x=u.current;p(),i("saving"),c(null);try{const S=Ik(x.name||"untitled"),k=x.name?I2t(S,x.name):S,C=Iv(k,"skill-md",x.instructions??"");if(await s.mutateAsync({id:e,name:x.name,description:x.description,instructions:x.instructions,visibility:x.visibility,workspaceId:x.workspaceId,files:C}),b!==d.current)return;i("saved"),f.current=setTimeout(()=>{f.current=null,i("idle")},n)}catch(S){if(b!==d.current)return;i("error"),c(S instanceof Error?S:new Error(String(S)))}},[e,s,n]),m=Uy(()=>{h()},t);v.useEffect(()=>{const b=r.watch(x=>{u.current=x,m()});return()=>{b.unsubscribe()}},[r,m]),v.useEffect(()=>()=>{m.flush(),p()},[m]);const g=v.useCallback(()=>{h()},[h]),y=v.useCallback(()=>{m.flush()},[m]);return{status:a,lastError:l,retry:g,flushNow:y}}function $Mt(e){const t=We();return yt({queryKey:["stored-skill",e],queryFn:()=>t.getStoredSkill(e).details(),enabled:!!e})}const pLr=({title:e,rightAside:t,primaryAction:n,mobileExtra:r,showForm:s=!0,chat:a,form:i,deleteAction:l})=>{const c=Ws(),[u,d]=v.useState("chat");return o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[o.jsxs("div",{className:"bg-surface1 flex min-w-0 items-center gap-2 px-3 py-2 md:px-6 md:py-3",children:[o.jsx(ce,{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($c,{})}),o.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[o.jsx("div",{className:"text-ui-md text-neutral6 min-w-0 truncate",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:"px-4 pt-4 pb-2 md:hidden",children:o.jsxs("div",{role:"tablist","aria-label":"Workspace view",className:"border-border1 bg-surface3 relative mx-auto flex h-9 w-full max-w-sm items-center rounded-full border 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 w-full flex-1 flex-col md:mx-auto md:max-w-[80ch]",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-border1 border-t px-4 pt-4 pb-4 md:px-6","data-testid":"skill-edit-delete-action",children:l})]})})]})]})},MMt="skillBuilderTool",DMt="readSkillForm",OQe=`# Role
496
496
  You help a user build a skill: a focused set of instructions that gives an agent expertise in a specific area.
@@ -569,7 +569,7 @@ Ask one simple question at a time.`;function hLr(e,t){const n=v.useRef(e);n.curr
569
569
  `);R!==-1?(C=n.slice(0,R),_=n.slice(R+2)):C=n}const E=!!C,T=i??E,I=v.useMemo(()=>(l??[]).find(R=>R.type==="data"&&R.name==="workspace-metadata"&&R.data?.toolCallId===r),[l,r])?.data,A=()=>{!C||d||f(C)};return o.jsxs("div",{className:"mb-4","data-testid":"file-tree-badge",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("button",{onClick:()=>u(R=>!R),className:"flex min-w-0 items-center gap-2",type:"button",children:[o.jsx(qe,{children:o.jsx(k_,{className:X("transition-all",c?"rotate-90":"rotate-180")})}),o.jsxs(on,{icon:o.jsx(JZt,{className:"text-accent6",size:16}),children:["List Files ",o.jsx("span",{className:"text-neutral6 ml-1 font-normal",children:m}),k.length>0&&o.jsxs("span",{className:"text-neutral4 ml-1 font-normal",children:["(",k.join(", "),")"]})]})]}),I?.filesystem&&o.jsxs(p,{href:I.id?`/workspaces/${I.id}?path=${encodeURIComponent(m)}`:"/workspaces",className:"text-neutral6 bg-surface3 border-border1 hover:bg-surface4 hover:border-border2 flex items-center gap-1.5 rounded border px-1.5 py-0.5 text-xs transition-colors",children:[o.jsx(dpe,{className:"size-3"}),o.jsx("span",{children:I.name||I.filesystem.name})]}),c&&E&&_&&o.jsx("span",{className:"text-neutral6 text-xs",children:_})]}),!c&&o.jsxs("div",{className:"pt-2",children:[s&&!T&&o.jsxs("div",{className:"bg-surface2 flex flex-col gap-4 rounded-lg p-4",children:[o.jsxs("div",{children:[o.jsx("p",{className:"pb-2 font-medium",children:"Tool arguments"}),o.jsx(Hr,{data:h,"data-testid":"tool-args"})]}),o.jsx(KI,{toolCalled:T,toolCallId:r,toolApprovalMetadata:s,toolName:e,isNetwork:a})]}),T&&C&&o.jsxs("div",{className:"border-border1 bg-surface2 overflow-hidden rounded-md border",children:[o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center justify-between border-b px-3 py-1.5",children:[_&&o.jsx("span",{className:"text-neutral6 text-xs",children:_}),o.jsx(ce,{variant:"default",size:"icon-sm",tooltip:"Copy tree",onClick:A,disabled:!C,children:o.jsxs("span",{className:"grid",children:[o.jsx("span",{style:{gridArea:"1/1"},className:X("transition-transform",d?"scale-100":"scale-0"),children:o.jsx(fa,{size:14})}),o.jsx("span",{style:{gridArea:"1/1"},className:X("transition-transform",d?"scale-0":"scale-100"),children:o.jsx(im,{size:14})})]})})]}),o.jsx("pre",{className:"text-mastra-el-6 max-h-dropdown-max-height overflow-x-auto overflow-y-auto p-3 font-mono text-xs whitespace-pre",children:C})]}),T&&!E&&o.jsx("div",{className:"border-border1 bg-surface2 rounded-md border px-3 py-2",children:o.jsx("span",{className:"text-neutral6 text-xs",children:"Loading..."})})]})]})},O9r={"🔴":"text-foreground","🟡":"text-foreground","🟢":"text-foreground"},_9r={"🔴":"bg-purple-500/15","🟡":"bg-blue-500/15","🟢":"bg-green-500/15"},C9r={"🔴":"border-l-purple-500","🟡":"border-l-blue-500","🟢":"border-l-green-500"};function E9r(e,t=!1){const n=e.trim();if(!n)return null;if(n.startsWith("* ->")||n.startsWith("->"))return{priority:null,time:null,content:n.replace(/^\*?\s*->\s*/,""),children:[],isNested:!0};if(t&&n.startsWith("-")){const s=n.replace(/^-\s*/,"");return s?{priority:null,time:null,content:s,children:[],isNested:!0}:null}const r=n.match(/^\*\s*(🔴|🟡|🟢)?\s*(?:\((\d{1,2}:\d{2})\))?\s*(.+)$/);if(r){const[,s,a,i]=r;return{priority:s||null,time:a||null,content:i.trim(),children:[],isNested:t}}return n.startsWith("*")?{priority:null,time:null,content:n.replace(/^\*\s*/,""),children:[],isNested:t}:null}function T9r(e){const t={threads:[]},n=e.match(/<current-task>\s*([\s\S]*?)\s*<\/current-task>/);n&&(t.currentTask=n[1].trim());const r=e.match(/<suggested-response>\s*([\s\S]*?)\s*<\/suggested-response>/);r&&(t.suggestedResponse=r[1].trim());const s=e.match(/<observations>\s*([\s\S]*?)\s*<\/observations>/),i=(s?s[1]:e).split(/(?=Thread [a-f0-9]+:)/i);for(const l of i){const c=l.trim();if(!c)continue;const u=c.match(/^Thread ([a-f0-9]+):/i),d=u?u[1]:"default",f=u?c.replace(/^Thread [a-f0-9]+:\s*/i,""):c,p={threadId:d,dateBlocks:[]},h=f.split(`
570
570
  `);let m=null,g=null;for(const y of h){const b=y.trim(),x=b.match(/^Date:\s*(.+?)(?:\s*\(([^)]+)\))?$/);if(x){m&&p.dateBlocks.push(m),m={date:x[1].trim(),relativeTime:x[2]?.trim(),observations:[]},g=null;continue}const S=y.match(/^(\s*)/),C=(S?S[1].length:0)>=2&&(b.startsWith("* ->")||b.startsWith("->")||b.startsWith("-")),_=E9r(b,C);_&&(m||(m={date:"Recent",observations:[]}),_.isNested&&g?g.children.push(_):(m.observations.push(_),g=_))}m&&p.dateBlocks.push(m),p.dateBlocks.length>0&&t.threads.push(p)}return t}function z3t({observation:e,useInheritedTextColor:t}){const n=t?"":e.priority?O9r[e.priority]:"text-muted-foreground",r=t?"":e.priority?_9r[e.priority]:"",s=e.priority?C9r[e.priority]:"border-l-transparent";return o.jsxs("div",{className:X("py-0.5",e.isNested&&"ml-4 border-l border-border/50 pl-2"),children:[o.jsxs("div",{className:X("flex items-start gap-1.5 text-xs",r&&"rounded px-1.5 py-0.5",r,!e.isNested&&e.priority&&`border-l-2 ${s} pl-1.5`),children:[e.isNested&&o.jsx("span",{className:X("shrink-0",t?"opacity-60":"text-muted-foreground"),children:"→"}),o.jsx("span",{className:X("flex-1",n,"[&_code]:bg-black/10 [&_code]:px-1 [&_code]:py-0.5 [&_code]:rounded [&_code]:text-[10px]"),children:o.jsx(Xp,{children:e.content})}),e.time&&o.jsx("span",{className:X("shrink-0 font-mono text-[10px] ml-2",t?"opacity-60":"text-muted-foreground"),children:e.time})]}),e.children.length>0&&o.jsx("div",{className:"mt-0.5",children:e.children.map((a,i)=>o.jsx(z3t,{observation:a,useInheritedTextColor:t},i))})]})}function j9r({block:e,useInheritedTextColor:t}){return o.jsxs("div",{className:"mb-2",children:[o.jsxs("div",{className:X("flex items-center gap-2 mb-1 sticky top-0 backdrop-blur-sm pt-1 pb-1",t?"bg-transparent":"bg-background/95"),children:[o.jsx("span",{className:X("text-xs font-medium",t?"opacity-80":"text-foreground"),children:e.date}),e.relativeTime&&o.jsxs("span",{className:X("text-[10px]",t?"opacity-60":"text-muted-foreground"),children:["(",e.relativeTime,")"]})]}),o.jsx("div",{className:"space-y-0",children:e.observations.map((n,r)=>o.jsx(z3t,{observation:n,useInheritedTextColor:t},r))})]})}function N9r({thread:e,showThreadId:t,useInheritedTextColor:n}){return o.jsxs("div",{className:"mb-3",children:[t&&e.threadId!=="default"&&o.jsxs("div",{className:X("text-[10px] font-mono mb-1 px-1 py-0.5 rounded inline-block",n?"opacity-60 bg-current/10":"text-muted-foreground bg-muted/50"),children:["Thread ",e.threadId]}),e.dateBlocks.map((r,s)=>o.jsx(j9r,{block:r,useInheritedTextColor:n},s))]})}function SF({observations:e,className:t,maxHeight:n,showCurrentTask:r=!1,showSuggestedResponse:s=!1,useInheritedTextColor:a=!1}){const i=v.useMemo(()=>T9r(e),[e]),l=i.threads.length>1||i.threads.length===1&&i.threads[0].threadId!=="default";return i.threads.length===0&&!i.currentTask&&!i.suggestedResponse?o.jsx("div",{className:X("text-xs text-muted-foreground italic",t),children:"No observations"}):o.jsxs("div",{className:X("text-sm overflow-hidden",t),children:[o.jsx("div",{className:X("wrap-break-word",n&&"overflow-y-auto pr-1"),style:n?{maxHeight:n}:void 0,children:i.threads.map((c,u)=>o.jsx(N9r,{thread:c,showThreadId:l,useInheritedTextColor:a},c.threadId+u))}),r&&i.currentTask&&o.jsxs("div",{className:"border-border mt-2 border-t pt-2",children:[o.jsx("div",{className:"text-muted-foreground mb-1 text-[10px] font-medium tracking-wide uppercase",children:"Current Task"}),o.jsx("div",{className:"text-foreground text-xs whitespace-pre-wrap",children:i.currentTask})]}),s&&i.suggestedResponse&&o.jsxs("div",{className:"border-border mt-2 border-t pt-2",children:[o.jsx("div",{className:"text-muted-foreground mb-1 text-[10px] font-medium tracking-wide uppercase",children:"Suggested Response"}),o.jsx("div",{className:"text-foreground/80 text-xs whitespace-pre-wrap italic",children:i.suggestedResponse})]})]})}const up=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(Math.round(e)),I9r=e=>e!=null&&e!=="",F3t=e=>Object.entries(e??{}).filter(([,t])=>I9r(t)),OKe=e=>{if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}},A9r=e=>typeof e=="object"&&e!==null,kF=({className:e})=>o.jsx(Bu,{className:e}),_Ke=({children:e,icon:t,expanded:n,onClick:r,className:s})=>{const a=o.jsxs(o.Fragment,{children:[r&&o.jsx(qe,{children:o.jsx(ka,{className:X("transition-all",n?"rotate-0":"-rotate-90")})}),o.jsx(on,{icon:t,children:e})]});return r?o.jsx("button",{onClick:r,className:X("inline-flex items-center gap-2",s),type:"button",children:a}):o.jsx("div",{className:X("inline-flex items-center gap-2",s),children:a})},CKe=({extractedValues:e,extractionFailures:t,isExpanded:n,onToggle:r})=>{const s=F3t(e),a=t??[];return s.length===0&&a.length===0?null:o.jsxs("div",{className:"mt-2 border-t border-neutral-700 pt-2",children:[o.jsxs("button",{onClick:r,className:"text-foreground flex items-center gap-1 text-[10px] font-medium tracking-wide uppercase transition-opacity hover:opacity-80",children:[n?o.jsx(ka,{className:"h-2.5 w-2.5"}):o.jsx(aa,{className:"h-2.5 w-2.5"}),"Extractions (",s.length,")",a.length>0?` · ${a.length} failed`:""]}),n&&o.jsxs("div",{className:"mt-1 space-y-2",children:[s.map(([i,l])=>o.jsxs("div",{className:"rounded border border-neutral-700/60 bg-black/5 p-2 dark:bg-white/5",children:[o.jsx("div",{className:"text-foreground/70 text-[10px] font-medium tracking-wide uppercase",children:i}),A9r(l)?o.jsx("pre",{className:"text-foreground/80 mt-1 max-h-40 overflow-auto text-[11px] break-words whitespace-pre-wrap",children:OKe(l)}):o.jsx("div",{className:"text-foreground/80 mt-1 text-[11px] [&_code]:rounded [&_code]:bg-black/10 [&_code]:px-1 [&_code]:py-0.5 [&_code]:text-[10px]",children:o.jsx(Xp,{children:OKe(l)})})]},i)),a.map(i=>o.jsxs("div",{className:"rounded border border-red-500/20 bg-red-500/5 p-2 text-red-700",children:[o.jsx("div",{className:"text-[10px] font-medium tracking-wide uppercase",children:i.slug}),o.jsx("div",{className:"mt-1 text-[11px]",children:i.error})]},i.slug))]})]})},R9r=({toolName:e,args:t,metadata:n})=>{const r=n?.omData||t,s=r.cycleId||"",a=r._state||(r.failedAt?"failed":r.completedAt?"complete":r.disconnectedAt?"disconnected":"loading"),i=a==="loading",l=a==="complete",c=a==="failed",u=a==="disconnected",d=a==="buffering",f=a==="buffering-complete",p=a==="buffering-failed",h=a==="activated",m=r.operationType==="reflection",g=F3t(r.extractedValues).length>0||(r.extractionFailures?.length??0)>0,y=c&&m||g,[b,x]=v.useState(y);v.useEffect(()=>{y&&x(!0)},[y]);const[S,k]=v.useState(!0),[C,_]=v.useState(!1),[E,T]=v.useState(!1),[N,I]=v.useState(!1),A="bg-blue-500/10",R="text-blue-600",L="bg-green-500/10",D="text-green-600",z="hover:bg-green-500/20",H="bg-green-500/5",F="border-green-500/10",U="text-green-600",q="bg-surface2",M="border-border-1",G=m?"Reflecting":"Observing",V=m?"Reflected":"Observed";if(i){const $=r.tokensToObserve;return o.jsx("div",{className:"mb-3","data-om-badge":s,"data-om-state":a,"data-om-type":m?"reflection":"observation",children:o.jsxs("div",{className:`inline-flex items-center gap-1.5 rounded-md px-2 py-1 ${A} ${R} my-1 text-xs font-medium`,children:[o.jsx(ua,{className:"h-3 w-3 animate-spin"}),m?o.jsx(Fv,{className:"h-3 w-3"}):o.jsx(kF,{className:"h-3 w-3"}),o.jsxs("span",{children:[G,$?` ~${up($)} tokens`:"..."]})]})})}if(l){const $=r.tokensObserved,B=r.observationTokens,Z=r.observations,K=r.currentTask,ne=r.suggestedResponse,ee=r.extractedValues,J=r.extractionFailures,ae=r.durationMs,fe=$&&B&&B>0?Math.round($/B):null,Y=re=>{const le=re.currentTarget.closest("[data-radix-scroll-area-viewport]")||document.documentElement,ue=le.scrollTop;x(!b),requestAnimationFrame(()=>{le.scrollTop=ue})};return o.jsx("div",{className:"mb-3","data-om-badge":s,"data-om-state":a,"data-om-type":m?"reflection":"observation",children:o.jsxs("div",{className:"my-1",children:[o.jsxs("button",{onClick:Y,className:`inline-flex items-center gap-1.5 rounded-md px-2 py-1 ${L} ${D} text-xs font-medium ${z} cursor-pointer transition-colors`,children:[b?o.jsx(ka,{className:"h-3 w-3"}):o.jsx(aa,{className:"h-3 w-3"}),m?o.jsx(Fv,{className:"h-3 w-3"}):o.jsx(kF,{className:"h-3 w-3"}),o.jsxs("span",{children:[V," ",$?up($):"?","→",B?up(B):"?"," tokens",fe?` (-${fe}x)`:""]})]}),b&&o.jsxs("div",{className:`mt-1 ml-6 rounded-md p-2 ${H} space-y-1.5 border text-xs ${F}`,children:[o.jsxs("div",{className:`flex gap-4 text-[11px] ${U}`,children:[$&&o.jsxs("span",{children:["Input: ",up($)]}),B&&o.jsxs("span",{children:["Output: ",up(B)]}),fe&&fe>1&&o.jsxs("span",{children:["Compression: ",fe,"x"]}),ae&&o.jsxs("span",{children:["Duration: ",(ae/1e3).toFixed(2),"s"]})]}),Z&&o.jsx("div",{className:"mt-1 border-t border-neutral-700 pt-1",children:!K&&!ne?o.jsx(SF,{observations:Z,maxHeight:"500px"}):o.jsxs(o.Fragment,{children:[o.jsxs("button",{onClick:()=>k(!S),className:"text-foreground flex items-center gap-1 text-[10px] font-medium tracking-wide uppercase transition-opacity hover:opacity-80",children:[S?o.jsx(ka,{className:"h-2.5 w-2.5"}):o.jsx(aa,{className:"h-2.5 w-2.5"}),m?"Reflections":"Observations"]}),S&&o.jsx("div",{className:"mt-1",children:o.jsx(SF,{observations:Z,maxHeight:"500px"})})]})}),K&&o.jsxs("div",{className:"mt-2 border-t border-neutral-700 pt-2",children:[o.jsxs("button",{onClick:()=>_(!C),className:"text-foreground flex items-center gap-1 text-[10px] font-medium tracking-wide uppercase transition-opacity hover:opacity-80",children:[C?o.jsx(ka,{className:"h-2.5 w-2.5"}):o.jsx(aa,{className:"h-2.5 w-2.5"}),"Current Task"]}),C&&o.jsx("div",{className:"text-foreground mt-1 text-[11px] [&_code]:rounded [&_code]:bg-black/10 [&_code]:px-1 [&_code]:py-0.5 [&_code]:text-[10px]",children:o.jsx(Xp,{children:K})})]}),ne&&o.jsxs("div",{className:"mt-2 border-t border-neutral-700 pt-2",children:[o.jsxs("button",{onClick:()=>T(!E),className:"text-foreground flex items-center gap-1 text-[10px] font-medium tracking-wide uppercase transition-opacity hover:opacity-80",children:[E?o.jsx(ka,{className:"h-2.5 w-2.5"}):o.jsx(aa,{className:"h-2.5 w-2.5"}),"Suggested Response"]}),E&&o.jsx("div",{className:"text-foreground/80 mt-1 text-[11px] italic [&_code]:rounded [&_code]:bg-black/10 [&_code]:px-1 [&_code]:py-0.5 [&_code]:text-[10px]",children:o.jsx(Xp,{children:ne})})]}),o.jsx(CKe,{extractedValues:ee,extractionFailures:J,isExpanded:N,onToggle:()=>I(!N)})]})]})})}if(u){const $=m?"Reflection interrupted":"Observation interrupted",B=r.tokensToObserve;return o.jsx("div",{className:"mb-3","data-om-badge":s,"data-om-state":a,"data-om-type":m?"reflection":"observation",children:o.jsxs("div",{className:"my-1 inline-flex items-center gap-1.5 rounded-md bg-yellow-500/10 px-2 py-1 text-xs font-medium text-yellow-600",children:[o.jsx(TYt,{className:"h-3 w-3"}),o.jsxs("span",{children:[$,B?` (~${up(B)} tokens)`:""]})]})})}if(c){const $=r.error,B=m?"Reflection failed":"Observation failed";return o.jsx("div",{className:"mb-3","data-om-badge":s,"data-om-state":a,"data-om-type":m?"reflection":"observation",children:o.jsxs("div",{className:"my-1",children:[o.jsxs("button",{onClick:()=>x(!b),className:"inline-flex cursor-pointer items-center gap-1.5 rounded-md bg-red-500/10 px-2 py-1 text-xs font-medium text-red-600 transition-colors hover:bg-red-500/20",children:[b?o.jsx(ka,{className:"h-3 w-3"}):o.jsx(aa,{className:"h-3 w-3"}),o.jsx(G2,{className:"h-3 w-3"}),o.jsx("span",{children:B})]}),b&&$&&o.jsxs("div",{className:"mt-1 ml-4 rounded-md border border-red-500/10 bg-red-500/5 p-2 text-xs text-red-700",children:[o.jsx("span",{className:"font-medium",children:"Error:"})," ",$]})]})})}if(d){const $=r.tokensToBuffer,B=m?"Buffering reflection":"Buffering observations";return o.jsx("div",{className:"mt-2 mb-8","data-om-badge":s,"data-om-state":a,"data-om-type":m?"reflection":"observation",children:o.jsxs(_Ke,{icon:o.jsx(ua,{className:"text-accent6 animate-spin"}),children:[B,$?` ~${up($)} tokens`:"..."]})})}if(f){const $=r.tokensBuffered,B=r.bufferedTokens,{observations:Z,extractedValues:K,extractionFailures:ne}=r,ee=m?"Buffered reflection":"Buffered observations",J=$&&B&&B>0?Math.round($/B):null,ae=fe=>{const Y=fe.currentTarget.closest("[data-radix-scroll-area-viewport]")||document.documentElement,re=Y.scrollTop;x(!b),requestAnimationFrame(()=>{Y.scrollTop=re})};return o.jsx("div",{className:"mt-2 mb-8","data-om-badge":s,"data-om-state":a,"data-om-type":m?"reflection":"observation",children:o.jsxs("div",{children:[o.jsxs(_Ke,{expanded:b,onClick:ae,icon:o.jsx(kF,{className:"text-accent6"}),children:[ee," ",$?up($):"?","→",B?up(B):"?"," tokens",J?` (-${J}x)`:""]}),b&&o.jsxs("div",{className:`mt-2 ml-6 rounded-lg ${q} space-y-2 border p-4 text-xs ${M}`,children:[Z&&o.jsx(SF,{observations:Z,maxHeight:"240px"}),o.jsx(CKe,{extractedValues:K,extractionFailures:ne,isExpanded:N,onToggle:()=>I(!N)})]})]})})}if(p){const $=r.error,B=m?"Buffered reflection failed":"Buffered observation failed";return o.jsx("div",{className:"mb-3","data-om-badge":s,"data-om-state":a,"data-om-type":m?"reflection":"observation",children:o.jsxs("div",{className:"my-1",children:[o.jsxs("button",{onClick:()=>x(!b),className:"inline-flex cursor-pointer items-center gap-1.5 rounded-md border border-dashed border-red-400/40 bg-red-500/10 px-2 py-1 text-xs font-medium text-red-600 transition-colors hover:bg-red-500/20",children:[b?o.jsx(ka,{className:"h-3 w-3"}):o.jsx(aa,{className:"h-3 w-3"}),o.jsx(G2,{className:"h-3 w-3"}),o.jsx("span",{children:B})]}),b&&$&&o.jsxs("div",{className:"mt-1 ml-4 rounded-md border border-red-500/10 bg-red-500/5 p-2 text-xs text-red-700",children:[o.jsx("span",{className:"font-medium",children:"Error:"})," ",$]})]})})}if(h){const $=r.tokensActivated??0,B=r.observationTokens??0,{observations:Z}=r,K=m?"Reflected":"Observed",ne=$&&B&&B>0?Math.round($/B):null,ee=J=>{const ae=J.currentTarget.closest("[data-radix-scroll-area-viewport]")||document.documentElement,fe=ae.scrollTop;x(!b),requestAnimationFrame(()=>{ae.scrollTop=fe})};return o.jsx("div",{className:"mb-3","data-om-badge":s,"data-om-state":a,"data-om-type":m?"reflection":"observation","data-om-no-highlight":"true",children:o.jsxs("div",{className:"my-1",children:[o.jsxs("button",{onClick:ee,className:`inline-flex items-center gap-1.5 rounded-md px-2 py-1 ${L} ${D} text-xs font-medium ${z} cursor-pointer transition-colors`,children:[b?o.jsx(ka,{className:"h-3 w-3"}):o.jsx(aa,{className:"h-3 w-3"}),m?o.jsx(Fv,{className:"h-3 w-3"}):o.jsx(kF,{className:"h-3 w-3"}),o.jsxs("span",{children:[K," ",$?up($):"?","→",B?up(B):"?"," tokens",ne?` (-${ne}x)`:""]})]}),b&&o.jsxs("div",{className:`mt-1 ml-6 rounded-md p-2 ${H} space-y-1.5 border text-xs ${F}`,children:[o.jsxs("div",{className:`flex gap-4 text-[11px] ${U}`,children:[$>0&&o.jsxs("span",{children:["Input: ",up($)]}),B>0&&o.jsxs("span",{children:["Output: ",up(B)]}),ne&&ne>1&&o.jsxs("span",{children:["Compression: ",ne,"x"]})]}),Z&&o.jsx("div",{className:"mt-1 border-t border-neutral-700 pt-1",children:o.jsx(SF,{observations:Z,maxHeight:"500px"})})]})]})})}return o.jsx("div",{className:"mb-3","data-om-badge":s,"data-om-state":a,"data-om-type":m?"reflection":"observation",children:o.jsxs("div",{className:"my-1 inline-flex items-center gap-1.5 rounded-md bg-gray-500/10 px-2 py-1 text-xs font-medium text-gray-600",children:[o.jsx(Fv,{className:"h-3 w-3"}),o.jsx("span",{children:e})]})})},hp="mastra_workspace",Av={FILESYSTEM:{READ_FILE:`${hp}_read_file`,WRITE_FILE:`${hp}_write_file`,EDIT_FILE:`${hp}_edit_file`,LIST_FILES:`${hp}_list_files`,DELETE:`${hp}_delete`,FILE_STAT:`${hp}_file_stat`,MKDIR:`${hp}_mkdir`},SANDBOX:{EXECUTE_COMMAND:`${hp}_execute_command`,GET_PROCESS_OUTPUT:`${hp}_get_process_output`,KILL_PROCESS:`${hp}_kill_process`},SEARCH:{SEARCH:`${hp}_search`,INDEX:`${hp}_index`}},P9r=e=>{switch(e){case"running":return"bg-green-500";case"starting":case"initializing":return"bg-yellow-500";case"stopped":case"paused":return"bg-gray-500";case"error":case"failed":return"bg-red-500";default:return"bg-accent6"}},$9r=(e,t)=>{const[n,r]=v.useState(0),s=v.useRef(null);return v.useEffect(()=>{if(e){r(0),s.current=t||Date.now();const a=setInterval(()=>{s.current&&r(Date.now()-s.current)},100);return()=>clearInterval(a)}else s.current=null},[e,t]),n},M9r=({command:e,content:t,maxHeight:n="20rem",onCopy:r,isCopied:s})=>{const a=v.useRef(null);return v.useEffect(()=>{a.current&&(a.current.scrollTop=a.current.scrollHeight)},[t]),o.jsxs("div",{className:"border-border1 overflow-hidden rounded-md border",children:[e&&o.jsxs("div",{className:"bg-surface3 border-border1 flex items-center justify-between gap-2 border-b px-3 py-2",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx("span",{className:"text-neutral6 shrink-0 text-xs",children:"$"}),o.jsx("code",{className:"text-neutral5 truncate font-mono text-xs",children:e})]}),r&&o.jsx(ce,{variant:"default",size:"icon-sm",tooltip:"Copy output",onClick:r,className:"shrink-0",children:o.jsxs("span",{className:"grid",children:[o.jsx("span",{style:{gridArea:"1/1"},className:X("transition-transform",s?"scale-100":"scale-0"),children:o.jsx(fa,{size:14})}),o.jsx("span",{style:{gridArea:"1/1"},className:X("transition-transform",s?"scale-0":"scale-100"),children:o.jsx(im,{size:14})})]})})]}),o.jsx("pre",{ref:a,style:{maxHeight:n},className:"overflow-x-auto overflow-y-auto bg-black p-3 font-mono text-sm whitespace-pre-wrap text-neutral-300",children:t||o.jsx("span",{className:"text-neutral6 italic",children:"No output"})})]})},D9r=({toolName:e,args:t,result:n,metadata:r,toolCallId:s,toolApprovalMetadata:a,isNetwork:i,toolCalled:l,dataParts:c})=>{const u=v.useMemo(()=>(c??[]).filter(q=>q.type==="data"),[c]),[d,f]=v.useState(!1),{isCopied:p,copyToClipboard:h}=Zp({copiedDuration:1500,showToast:!1}),{Link:m}=bn(),g=u.find(q=>q.name==="sandbox-command"&&q.data?.toolCallId===s);let y="";try{const q=typeof t=="object"?t:JSON.parse(t);e===Av.SANDBOX.EXECUTE_COMMAND?y=q.command||"":(e===Av.SANDBOX.GET_PROCESS_OUTPUT||e===Av.SANDBOX.KILL_PROCESS)&&(y=g?.data?.command||`PID ${q.pid}`)}catch{y=e}const b=u.filter(q=>(q.name==="sandbox-stdout"||q.name==="sandbox-stderr")&&q.data?.toolCallId===s),x=u.find(q=>q.name==="workspace-metadata"&&q.data?.toolCallId===s),S=x?.data,k=u.find(q=>q.name==="sandbox-exit"&&q.data?.toolCallId===s),C=!!k||typeof n=="string",_=!!x,E=_&&!C,T=l??(C||_),N=k?.data?.exitCode,I=k?.data?.success,A=k?.data?.executionTimeMs,R=k?.data?.killed,D=b.map(q=>q.data?.output||"").join("")||(typeof n=="string"?n:""),z=e===Av.SANDBOX.EXECUTE_COMMAND?"Execute Command":e===Av.SANDBOX.GET_PROCESS_OUTPUT?"Get Process Output":e===Av.SANDBOX.KILL_PROCESS?"Kill Process":e,H=b[0]?.data?.timestamp,F=$9r(E,H),U=()=>{!D||p||h(D)};return o.jsxs("div",{className:"mb-4","data-testid":"sandbox-execution-badge",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("button",{onClick:()=>f(q=>!q),className:"flex min-w-0 items-center gap-2",type:"button",children:[o.jsx(qe,{children:o.jsx(k_,{className:X("transition-all",d?"rotate-90":"rotate-180")})}),o.jsx(on,{icon:o.jsx(hYt,{className:"text-accent6",size:16}),children:z}),S?.sandbox&&o.jsxs(m,{href:S.id?`/workspaces/${S.id}`:"/workspaces",className:"text-neutral6 bg-surface3 border-border1 hover:bg-surface4 hover:border-border2 flex items-center gap-1.5 rounded border px-1.5 py-0.5 text-xs transition-colors",onClick:q=>q.stopPropagation(),children:[o.jsx("span",{className:X("w-1.5 h-1.5 rounded-full",P9r(S.sandbox.status))}),o.jsx("span",{children:S.sandbox.name||S.sandbox.provider})]})]}),o.jsx("div",{className:"flex items-center gap-2",children:E?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-accent6 flex items-center gap-1.5 text-xs",children:[o.jsx("span",{className:"bg-accent6 h-1.5 w-1.5 animate-pulse rounded-full"}),o.jsx("span",{className:"animate-pulse",children:"running"})]}),o.jsxs("span",{className:"text-neutral6 text-xs tabular-nums",children:[F,"ms"]})]}):o.jsxs(o.Fragment,{children:[N!==void 0&&(I?o.jsx(fa,{className:"text-green-400",size:14}):R?o.jsx("span",{className:"rounded bg-orange-500/20 px-1.5 py-0.5 text-[10px] font-medium text-orange-400",children:"killed"}):o.jsxs("span",{className:"rounded bg-red-500/20 px-1.5 py-0.5 text-[10px] font-medium text-red-400",children:["exit ",N]})),A!==void 0&&o.jsxs("span",{className:"text-neutral6 text-xs",children:[A,"ms"]})]})})]}),!d&&o.jsxs("div",{className:"pt-2",children:[(D||y)&&o.jsx(M9r,{command:y,content:D,onCopy:D?U:void 0,isCopied:p}),o.jsx(KI,{toolCalled:T,toolCallId:s,toolApprovalMetadata:a,toolName:e,isNetwork:i,isGenerateMode:r?.mode==="generate"})]})]})},EKe=({value:e,testId:t})=>o.jsx("div",{"data-testid":t,children:o.jsx(pTe,{code:JSON.stringify(e,null,2)??String(e),lang:"json",overflow:"scroll"})}),TKe=({toolName:e,args:t,result:n,metadata:r,toolOutput:s,toolCallId:a,toolApprovalMetadata:i,suspendPayload:l,isNetwork:c,toolCalled:u,withoutArgs:d})=>{let f=null;try{const{__mastraMetadata:S,_background:k,...C}=typeof t=="object"?t:JSON.parse(t);f=o.jsx(EKe,{value:C,testId:"tool-args"})}catch{f=o.jsx("pre",{className:"bg-surface4 overflow-x-auto rounded-md p-4 whitespace-pre",children:t})}let p=typeof n=="string"?o.jsx("pre",{className:"bg-surface4 overflow-x-auto rounded-md p-4 whitespace-pre",children:n}):o.jsx(EKe,{value:n,testId:"tool-result"}),h=typeof l=="string"?o.jsx("pre",{className:"bg-surface4 overflow-x-auto rounded-md p-4 whitespace-pre",children:l}):o.jsx(Hr,{data:l,"data-testid":"tool-suspend-payload"});const m=r?.mode==="network"?r.routingDecision:void 0,g=r?.mode==="network"?m?.selectionReason??r.selectionReason:void 0,y=r?.mode==="network"?m??r.agentInput:void 0,b=u??(n||s.length>0),x=(r?.mode==="stream"||r?.mode==="generate")&&r?.backgroundTasks?r.backgroundTasks[a]:void 0;return o.jsx(Z4,{"data-testid":"tool-badge",icon:o.jsx(qd,{className:"text-accent6"}),title:e,extraInfo:r?.mode==="network"?o.jsx(VTe,{selectionReason:g||"",input:y}):x?.taskId&&x?.startedAt?o.jsx(qTe,{backgroundTask:x}):null,initialCollapsed:!(i??l),children:o.jsxs("div",{className:"space-y-4",children:[d?null:o.jsxs("div",{children:[o.jsx("p",{className:"pb-2 font-medium",children:"Tool arguments"}),f]}),h!==void 0&&l&&o.jsxs("div",{children:[o.jsx("p",{className:"pb-2 font-medium",children:"Tool suspend payload"}),h]}),p!==void 0&&n&&o.jsxs("div",{children:[o.jsx("p",{className:"pb-2 font-medium",children:"Tool result"}),p]}),s.length>0&&o.jsxs("div",{children:[o.jsx("p",{className:"pb-2 font-medium",children:"Tool output"}),o.jsx("div",{className:"h-40 overflow-y-auto",children:o.jsx(Hr,{data:s,"data-testid":"tool-output"})})]}),o.jsx(KI,{toolCalled:b,toolCallId:a,toolApprovalMetadata:i,toolName:e,isNetwork:c,isGenerateMode:r?.mode==="generate"})]})})},L9r=e=>e.replace(/[-_\s]+(.)?/g,(n,r)=>r?r.toUpperCase():"").replace(/^(.)/,n=>n.toLowerCase()).replace(/([A-Z])/g," $1").replace(/^./,n=>n.toUpperCase()).trim(),G4=()=>{const e=v.useContext(Vl),t=e.result?.steps??{};return{steps:Object.entries(t).reduce((r,[s,a])=>{const i="tripwire"in a&&a.tripwire;return{...r,[s]:{error:i?void 0:"error"in a?a.error:void 0,tripwire:i?a.tripwire:void 0,startedAt:a.startedAt,endedAt:"endedAt"in a?a.endedAt:void 0,status:a.status,output:"output"in a?a.output:void 0,input:a.payload,resumeData:"resumePayload"in a?a.resumePayload:void 0,suspendOutput:"suspendOutput"in a?a.suspendOutput:void 0,suspendPayload:"suspendPayload"in a?a.suspendPayload:void 0,foreachProgress:"foreachProgress"in a?a.foreachProgress:void 0,duration:"duration"in a?a.duration:void 0,date:"date"in a?a.date:void 0,isForEach:"isForEach"in a?a.isForEach:void 0,mapConfig:"mapConfig"in a?a.mapConfig:void 0,canSuspend:"canSuspend"in a?a.canSuspend:void 0,isParallel:"isParallel"in a?a.isParallel:void 0,stepGraph:"stepGraph"in a?a.stepGraph:void 0}}},{}),runId:e.runId}},z9r=({data:e})=>{const t=e.boundaryRole==="start";return o.jsxs(o.Fragment,{children:[!t&&o.jsx(j1,{type:"target",position:ar.Top,style:{visibility:"hidden"}}),o.jsx("div",{"data-workflow-boundary-node":!0,"data-testid":`workflow-boundary-${e.boundaryRole}`,className:"border-border1 bg-surface3 text-neutral5 flex h-14 w-14 items-center justify-center rounded-full border",children:o.jsx(ye,{variant:"ui-xs",className:"font-medium",children:e.label})}),t&&o.jsx(j1,{type:"source",position:ar.Bottom,style:{visibility:"hidden"}})]})},V2=({data:e,language:t="auto"})=>{const n=o0(),r=i=>{if(t==="javascript")return[IB(),It.lineWrapping];if(t==="json")return[Dp,It.lineWrapping];try{return JSON.parse(i),[Dp,It.lineWrapping]}catch{return i.includes("=>")||i.includes("function")||i.includes("const ")||i.includes("return ")?[IB(),It.lineWrapping]:[It.lineWrapping]}};if(typeof e!="string"){const i=JSON.stringify(e,null,2);return o.jsxs("div",{className:"relative max-h-[500px] overflow-auto",children:[o.jsx("div",{className:"bg-surface4 absolute top-2 right-2 z-10 rounded-full",children:o.jsx(Pa,{content:i})}),o.jsx("div",{className:"bg-surface4 rounded-lg p-4",children:o.jsx(ed,{value:i,theme:n,extensions:[Dp,It.lineWrapping]})})]})}const s=r(e);let a=e;try{const i=JSON.parse(e);a=JSON.stringify(i,null,2)}catch{}return o.jsxs("div",{className:"relative max-h-[500px] overflow-auto",children:[o.jsx("div",{className:"bg-surface4 absolute top-2 right-2 z-10 rounded-full",children:o.jsx(Pa,{content:e})}),o.jsx("div",{className:"bg-surface4 rounded-lg p-4",children:o.jsx(ed,{value:a,theme:n,extensions:s})})]})},F9r=e=>e!==void 0,B9r=({previousStepId:e,output:t,label:n})=>{const[r,s]=v.useState(!1),a=F9r(t),i=n??(e?`${e} output`:"Previous output");return a?o.jsxs(o.Fragment,{children:[o.jsxs(ce,{size:"sm",onClick:()=>s(!0),className:"border-border1 bg-surface3/95 text-neutral5 hover:bg-surface4 h-7 gap-1 rounded-full border px-2 shadow-lg",children:[o.jsx(py,{className:"h-icon-sm w-icon-sm text-accent1"}),"Data"]}),o.jsx(vr,{open:r,onOpenChange:s,children:o.jsxs(yr,{className:"w-full max-w-3xl",children:[o.jsx(br,{children:o.jsx(hr,{children:"Step output"})}),o.jsx(Rr,{className:"max-h-[700px] overflow-auto",children:o.jsxs("div",{className:"border-border1 bg-surface2 min-w-0 rounded-lg border p-3",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral5 mb-2 block",children:i}),o.jsx(V2,{data:t})]})})]})})]}):null},lP="workflow-data-edge",U9r=(e,t)=>e&&t?`${t}.${e}`:e,q9r=e=>{const{steps:t}=G4(),n=v.useContext(Vl),r=e.data,s=U9r(r?.previousStepId,e.parentWorkflowName),a=s?t[s]:void 0,i=n.payload??n.result?.input,l=n.result?.status==="success"?n.result.result:void 0,c=r?.boundaryPayload==="workflow-input"?i===null?void 0:i:r?.boundaryPayload==="workflow-output"?l:a?.output??a?.suspendOutput,u=r?.boundaryPayload==="workflow-input"?"Workflow input":r?.boundaryPayload==="workflow-output"?"Workflow output":void 0,[d,f,p]=Qke(e);return o.jsxs(o.Fragment,{children:[o.jsx(t4,{id:e.id,path:d,markerEnd:e.markerEnd,style:e.style,"data-edge-status":r?.edgeStatus??"idle","data-edge-from":r?.previousStepId,"data-edge-to":r?.nextStepId}),o.jsx(NXn,{children:o.jsx("div",{className:"nodrag nopan",style:{position:"absolute",pointerEvents:"all",transform:`translate(-50%, -50%) translate(${f}px, ${p}px)`},children:o.jsx(B9r,{previousStepId:r?.boundaryPayload?void 0:r?.previousStepId,output:c,label:u})})})]})},V9r=v.memo(q9r),Ru={sleep:"#A855F7",forEach:"#F97316",map:"#F97316",parallel:"#3B82F6",suspend:"#EC4899",workflow:"#8B5CF6",when:"#ECB047",dountil:"#8B5CF6",dowhile:"#06B6D4",until:"#F59E0B",while:"#10B981",if:"#3B82F6",else:"#6B7280"},Sd={sleep:hpe,sleepUntil:UD,forEach:C9,map:C9,parallel:XN,suspend:Cxe,workflow:lV,when:Hot,dountil:UQt,dowhile:VQt,until:hpe,while:a1,if:Nxe,else:yZt},H9r={when:"When condition",dountil:"Do until condition",dowhile:"Do while condition",until:"Until condition",while:"While condition",if:"If condition",else:"Else condition",and:"And condition",or:"Or condition",not:"Not condition"},W9r=e=>{switch(e){case"when":return{icon:Sd.when,color:Ru.when};case"dountil":return{icon:Sd.dountil,color:Ru.dountil};case"dowhile":return{icon:Sd.dowhile,color:Ru.dowhile};case"until":return{icon:Sd.until,color:Ru.until};case"while":return{icon:Sd.while,color:Ru.while};case"if":return{icon:Sd.if,color:Ru.if};case"else":return{icon:Sd.else,color:Ru.else};case"and":case"or":case"not":return{icon:Sd.when,color:Ru.when};default:return{icon:void 0,color:void 0}}},jKe=e=>{const{icon:t,color:n}=W9r(e);if(!(!e||!t||!n))return{id:`condition-${e}`,label:H9r[e]??`${e} condition`,icon:t,color:n}},Z9r=({duration:e,date:t,isForEach:n,mapConfig:r,canSuspend:s,isParallel:a,stepGraph:i})=>{const l=!!(e||t),c=!!n,u=!!(r&&!n),d=!!i;return{isSleepNode:l,isForEachNode:c,isMapNode:u,isNestedWorkflow:d,hasSpecialBadge:l||!!(s||a)||c||u||d}},B3t=e=>{const{isSleepNode:t,isForEachNode:n,isMapNode:r,isNestedWorkflow:s}=Z9r(e),a=[];return t&&a.push({id:e.date?"sleep-until":"sleep",label:e.date?"Sleep until step":"Sleep step",icon:e.date?Sd.sleepUntil:Sd.sleep,color:Ru.sleep}),e.canSuspend&&a.push({id:"suspend",label:"Suspend/resume step",icon:Sd.suspend,color:Ru.suspend}),e.isParallel&&a.push({id:"parallel",label:"Parallel step",icon:Sd.parallel,color:Ru.parallel}),s&&a.push({id:"workflow",label:"Nested workflow step",icon:Sd.workflow,color:Ru.workflow}),n&&a.push({id:"foreach",label:"Foreach step",icon:Sd.forEach,color:Ru.forEach}),r&&a.push({id:"map",label:"Map step",icon:Sd.map,color:Ru.map}),a},U3t=e=>e[0]?.color,Aq=({indicators:e,className:t})=>e.length?o.jsx("div",{className:X("flex items-center gap-1",t),children:e.map(n=>{const r=n.icon;return o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("span",{role:"img",tabIndex:0,"aria-label":n.label,"data-testid":`workflow-card-indicator-${n.id}`,className:"text-neutral5 focus-visible:ring-accent1 inline-flex h-5 w-5 shrink-0 items-center justify-center focus-visible:ring-1 focus-visible:outline-hidden",children:o.jsx(qe,{size:"sm",children:o.jsx(r,{className:"text-current",style:{color:n.color}})})})}),o.jsx(Pn,{children:n.label})]},`badge-${n.id}`)})}):null;var G9r=Object.create,XZ=Object.defineProperty,Q9r=Object.defineProperties,Y9r=Object.getOwnPropertyDescriptor,K9r=Object.getOwnPropertyDescriptors,q3t=Object.getOwnPropertyNames,Rq=Object.getOwnPropertySymbols,X9r=Object.getPrototypeOf,WTe=Object.prototype.hasOwnProperty,V3t=Object.prototype.propertyIsEnumerable,NKe=(e,t,n)=>t in e?XZ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,dy=(e,t)=>{for(var n in t||(t={}))WTe.call(t,n)&&NKe(e,n,t[n]);if(Rq)for(var n of Rq(t))V3t.call(t,n)&&NKe(e,n,t[n]);return e},JZ=(e,t)=>Q9r(e,K9r(t)),H3t=(e,t)=>{var n={};for(var r in e)WTe.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Rq)for(var r of Rq(e))t.indexOf(r)<0&&V3t.call(e,r)&&(n[r]=e[r]);return n},J9r=(e,t)=>function(){return t||(0,e[q3t(e)[0]])((t={exports:{}}).exports,t),t.exports},e7r=(e,t)=>{for(var n in t)XZ(e,n,{get:t[n],enumerable:!0})},t7r=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of q3t(t))!WTe.call(e,s)&&s!==n&&XZ(e,s,{get:()=>t[s],enumerable:!(r=Y9r(t,s))||r.enumerable});return e},n7r=(e,t,n)=>(n=e!=null?G9r(X9r(e)):{},t7r(!e||!e.__esModule?XZ(n,"default",{value:e,enumerable:!0}):n,e)),r7r=J9r({"../../node_modules/.pnpm/prismjs@1.29.0_patch_hash=vrxx3pzkik6jpmgpayxfjunetu/node_modules/prismjs/prism.js"(e,t){var n=(function(){var r=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,s=0,a={},i={util:{encode:function m(g){return g instanceof l?new l(g.type,m(g.content),g.alias):Array.isArray(g)?g.map(m):g.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/\u00a0/g," ")},type:function(m){return Object.prototype.toString.call(m).slice(8,-1)},objId:function(m){return m.__id||Object.defineProperty(m,"__id",{value:++s}),m.__id},clone:function m(g,y){y=y||{};var b,x;switch(i.util.type(g)){case"Object":if(x=i.util.objId(g),y[x])return y[x];b={},y[x]=b;for(var S in g)g.hasOwnProperty(S)&&(b[S]=m(g[S],y));return b;case"Array":return x=i.util.objId(g),y[x]?y[x]:(b=[],y[x]=b,g.forEach(function(k,C){b[C]=m(k,y)}),b);default:return g}},getLanguage:function(m){for(;m;){var g=r.exec(m.className);if(g)return g[1].toLowerCase();m=m.parentElement}return"none"},setLanguage:function(m,g){m.className=m.className.replace(RegExp(r,"gi"),""),m.classList.add("language-"+g)},isActive:function(m,g,y){for(var b="no-"+g;m;){var x=m.classList;if(x.contains(g))return!0;if(x.contains(b))return!1;m=m.parentElement}return!!y}},languages:{plain:a,plaintext:a,text:a,txt:a,extend:function(m,g){var y=i.util.clone(i.languages[m]);for(var b in g)y[b]=g[b];return y},insertBefore:function(m,g,y,b){b=b||i.languages;var x=b[m],S={};for(var k in x)if(x.hasOwnProperty(k)){if(k==g)for(var C in y)y.hasOwnProperty(C)&&(S[C]=y[C]);y.hasOwnProperty(k)||(S[k]=x[k])}var _=b[m];return b[m]=S,i.languages.DFS(i.languages,function(E,T){T===_&&E!=m&&(this[E]=S)}),S},DFS:function m(g,y,b,x){x=x||{};var S=i.util.objId;for(var k in g)if(g.hasOwnProperty(k)){y.call(g,k,g[k],b||k);var C=g[k],_=i.util.type(C);_==="Object"&&!x[S(C)]?(x[S(C)]=!0,m(C,y,null,x)):_==="Array"&&!x[S(C)]&&(x[S(C)]=!0,m(C,y,k,x))}}},plugins:{},highlight:function(m,g,y){var b={code:m,grammar:g,language:y};if(i.hooks.run("before-tokenize",b),!b.grammar)throw new Error('The language "'+b.language+'" has no grammar.');return b.tokens=i.tokenize(b.code,b.grammar),i.hooks.run("after-tokenize",b),l.stringify(i.util.encode(b.tokens),b.language)},tokenize:function(m,g){var y=g.rest;if(y){for(var b in y)g[b]=y[b];delete g.rest}var x=new d;return f(x,x.head,m),u(m,x,g,x.head,0),h(x)},hooks:{all:{},add:function(m,g){var y=i.hooks.all;y[m]=y[m]||[],y[m].push(g)},run:function(m,g){var y=i.hooks.all[m];if(!(!y||!y.length))for(var b=0,x;x=y[b++];)x(g)}},Token:l};function l(m,g,y,b){this.type=m,this.content=g,this.alias=y,this.length=(b||"").length|0}l.stringify=function m(g,y){if(typeof g=="string")return g;if(Array.isArray(g)){var b="";return g.forEach(function(_){b+=m(_,y)}),b}var x={type:g.type,content:m(g.content,y),tag:"span",classes:["token",g.type],attributes:{},language:y},S=g.alias;S&&(Array.isArray(S)?Array.prototype.push.apply(x.classes,S):x.classes.push(S)),i.hooks.run("wrap",x);var k="";for(var C in x.attributes)k+=" "+C+'="'+(x.attributes[C]||"").replace(/"/g,"&quot;")+'"';return"<"+x.tag+' class="'+x.classes.join(" ")+'"'+k+">"+x.content+"</"+x.tag+">"};function c(m,g,y,b){m.lastIndex=g;var x=m.exec(y);if(x&&b&&x[1]){var S=x[1].length;x.index+=S,x[0]=x[0].slice(S)}return x}function u(m,g,y,b,x,S){for(var k in y)if(!(!y.hasOwnProperty(k)||!y[k])){var C=y[k];C=Array.isArray(C)?C:[C];for(var _=0;_<C.length;++_){if(S&&S.cause==k+","+_)return;var E=C[_],T=E.inside,N=!!E.lookbehind,I=!!E.greedy,A=E.alias;if(I&&!E.pattern.global){var R=E.pattern.toString().match(/[imsuy]*$/)[0];E.pattern=RegExp(E.pattern.source,R+"g")}for(var L=E.pattern||E,D=b.next,z=x;D!==g.tail&&!(S&&z>=S.reach);z+=D.value.length,D=D.next){var H=D.value;if(g.length>m.length)return;if(!(H instanceof l)){var F=1,U;if(I){if(U=c(L,z,m,N),!U||U.index>=m.length)break;var V=U.index,q=U.index+U[0].length,M=z;for(M+=D.value.length;V>=M;)D=D.next,M+=D.value.length;if(M-=D.value.length,z=M,D.value instanceof l)continue;for(var G=D;G!==g.tail&&(M<q||typeof G.value=="string");G=G.next)F++,M+=G.value.length;F--,H=m.slice(z,M),U.index-=z}else if(U=c(L,0,H,N),!U)continue;var V=U.index,$=U[0],B=H.slice(0,V),Z=H.slice(V+$.length),K=z+H.length;S&&K>S.reach&&(S.reach=K);var ne=D.prev;B&&(ne=f(g,ne,B),z+=B.length),p(g,ne,F);var ee=new l(k,T?i.tokenize($,T):$,A,$);if(D=f(g,ne,ee),Z&&f(g,D,Z),F>1){var J={cause:k+","+_,reach:K};u(m,g,y,D.prev,z,J),S&&J.reach>S.reach&&(S.reach=J.reach)}}}}}}function d(){var m={value:null,prev:null,next:null},g={value:null,prev:m,next:null};m.next=g,this.head=m,this.tail=g,this.length=0}function f(m,g,y){var b=g.next,x={value:y,prev:g,next:b};return g.next=x,b.prev=x,m.length++,x}function p(m,g,y){for(var b=g.next,x=0;x<y&&b!==m.tail;x++)b=b.next;g.next=b,b.prev=g,m.length-=x}function h(m){for(var g=[],y=m.head.next;y!==m.tail;)g.push(y.value),y=y.next;return g}return i})();t.exports=n,n.default=n}}),Nt=n7r(r7r());Nt.languages.markup={comment:{pattern:/<!--(?:(?!<!--)[\s\S])*?-->/,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^<!|>$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]},Nt.languages.markup.tag.inside["attr-value"].inside.entity=Nt.languages.markup.entity,Nt.languages.markup.doctype.inside["internal-subset"].inside=Nt.languages.markup,Nt.hooks.add("wrap",function(e){e.type==="entity"&&(e.attributes.title=e.content.replace(/&amp;/,"&"))}),Object.defineProperty(Nt.languages.markup.tag,"addInlined",{value:function(e,r){var n={},n=(n["language-"+r]={pattern:/(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,lookbehind:!0,inside:Nt.languages[r]},n.cdata=/^<!\[CDATA\[|\]\]>$/i,{"included-cdata":{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,inside:n}}),r=(n["language-"+r]={pattern:/[\s\S]+/,inside:Nt.languages[r]},{});r[e]={pattern:RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g,function(){return e}),"i"),lookbehind:!0,greedy:!0,inside:n},Nt.languages.insertBefore("markup","cdata",r)}}),Object.defineProperty(Nt.languages.markup.tag,"addAttribute",{value:function(e,t){Nt.languages.markup.tag.inside["special-attr"].push({pattern:RegExp(/(^|["'\s])/.source+"(?:"+e+")"+/\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,"i"),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[t,"language-"+t],inside:Nt.languages[t]},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}}}})}}),Nt.languages.html=Nt.languages.markup,Nt.languages.mathml=Nt.languages.markup,Nt.languages.svg=Nt.languages.markup,Nt.languages.xml=Nt.languages.extend("markup",{}),Nt.languages.ssml=Nt.languages.xml,Nt.languages.atom=Nt.languages.xml,Nt.languages.rss=Nt.languages.xml,(function(e){var t={pattern:/\\[\\(){}[\]^$+*?|.]/,alias:"escape"},n=/\\(?:x[\da-fA-F]{2}|u[\da-fA-F]{4}|u\{[\da-fA-F]+\}|0[0-7]{0,2}|[123][0-7]{2}|c[a-zA-Z]|.)/,r="(?:[^\\\\-]|"+n.source+")",r=RegExp(r+"-"+r),s={pattern:/(<|')[^<>']+(?=[>']$)/,lookbehind:!0,alias:"variable"};e.languages.regex={"char-class":{pattern:/((?:^|[^\\])(?:\\\\)*)\[(?:[^\\\]]|\\[\s\S])*\]/,lookbehind:!0,inside:{"char-class-negation":{pattern:/(^\[)\^/,lookbehind:!0,alias:"operator"},"char-class-punctuation":{pattern:/^\[|\]$/,alias:"punctuation"},range:{pattern:r,inside:{escape:n,"range-punctuation":{pattern:/-/,alias:"operator"}}},"special-escape":t,"char-set":{pattern:/\\[wsd]|\\p\{[^{}]+\}/i,alias:"class-name"},escape:n}},"special-escape":t,"char-set":{pattern:/\.|\\[wsd]|\\p\{[^{}]+\}/i,alias:"class-name"},backreference:[{pattern:/\\(?![123][0-7]{2})[1-9]/,alias:"keyword"},{pattern:/\\k<[^<>']+>/,alias:"keyword",inside:{"group-name":s}}],anchor:{pattern:/[$^]|\\[ABbGZz]/,alias:"function"},escape:n,group:[{pattern:/\((?:\?(?:<[^<>']+>|'[^<>']+'|[>:]|<?[=!]|[idmnsuxU]+(?:-[idmnsuxU]+)?:?))?/,alias:"punctuation",inside:{"group-name":s}},{pattern:/\)/,alias:"punctuation"}],quantifier:{pattern:/(?:[+*?]|\{\d+(?:,\d*)?\})[?+]?/,alias:"number"},alternation:{pattern:/\|/,alias:"keyword"}}})(Nt),Nt.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/},Nt.languages.javascript=Nt.languages.extend("clike",{"class-name":[Nt.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp(/(^|[^\w$])/.source+"(?:"+/NaN|Infinity/.source+"|"+/0[bB][01]+(?:_[01]+)*n?/.source+"|"+/0[oO][0-7]+(?:_[0-7]+)*n?/.source+"|"+/0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source+"|"+/\d+(?:_\d+)*n/.source+"|"+/(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source+")"+/(?![\w$])/.source),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/}),Nt.languages.javascript["class-name"][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/,Nt.languages.insertBefore("javascript","keyword",{regex:{pattern:RegExp(/((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source+/\//.source+"(?:"+/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source+"|"+/(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source+")"+/(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:"language-regex",inside:Nt.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:Nt.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:Nt.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:Nt.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:Nt.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),Nt.languages.insertBefore("javascript","string",{hashbang:{pattern:/^#!.*/,greedy:!0,alias:"comment"},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:Nt.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:"property"}}),Nt.languages.insertBefore("javascript","operator",{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:"property"}}),Nt.languages.markup&&(Nt.languages.markup.tag.addInlined("script","javascript"),Nt.languages.markup.tag.addAttribute(/on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,"javascript")),Nt.languages.js=Nt.languages.javascript,Nt.languages.actionscript=Nt.languages.extend("javascript",{keyword:/\b(?:as|break|case|catch|class|const|default|delete|do|dynamic|each|else|extends|final|finally|for|function|get|if|implements|import|in|include|instanceof|interface|internal|is|namespace|native|new|null|override|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|use|var|void|while|with)\b/,operator:/\+\+|--|(?:[+\-*\/%^]|&&?|\|\|?|<<?|>>?>?|[!=]=?)=?|[~?@]/}),Nt.languages.actionscript["class-name"].alias="function",delete Nt.languages.actionscript.parameter,delete Nt.languages.actionscript["literal-property"],Nt.languages.markup&&Nt.languages.insertBefore("actionscript","string",{xml:{pattern:/(^|[^.])<\/?\w+(?:\s+[^\s>\/=]+=("|')(?:\\[\s\S]|(?!\2)[^\\])*\2)*\s*\/?>/,lookbehind:!0,inside:Nt.languages.markup}}),(function(e){var t=/#(?!\{).+/,n={pattern:/#\{[^}]+\}/,alias:"variable"};e.languages.coffeescript=e.languages.extend("javascript",{comment:t,string:[{pattern:/'(?:\\[\s\S]|[^\\'])*'/,greedy:!0},{pattern:/"(?:\\[\s\S]|[^\\"])*"/,greedy:!0,inside:{interpolation:n}}],keyword:/\b(?:and|break|by|catch|class|continue|debugger|delete|do|each|else|extend|extends|false|finally|for|if|in|instanceof|is|isnt|let|loop|namespace|new|no|not|null|of|off|on|or|own|return|super|switch|then|this|throw|true|try|typeof|undefined|unless|until|when|while|window|with|yes|yield)\b/,"class-member":{pattern:/@(?!\d)\w+/,alias:"variable"}}),e.languages.insertBefore("coffeescript","comment",{"multiline-comment":{pattern:/###[\s\S]+?###/,alias:"comment"},"block-regex":{pattern:/\/{3}[\s\S]*?\/{3}/,alias:"regex",inside:{comment:t,interpolation:n}}}),e.languages.insertBefore("coffeescript","string",{"inline-javascript":{pattern:/`(?:\\[\s\S]|[^\\`])*`/,inside:{delimiter:{pattern:/^`|`$/,alias:"punctuation"},script:{pattern:/[\s\S]+/,alias:"language-javascript",inside:e.languages.javascript}}},"multiline-string":[{pattern:/'''[\s\S]*?'''/,greedy:!0,alias:"string"},{pattern:/"""[\s\S]*?"""/,greedy:!0,alias:"string",inside:{interpolation:n}}]}),e.languages.insertBefore("coffeescript","keyword",{property:/(?!\d)\w+(?=\s*:(?!:))/}),delete e.languages.coffeescript["template-string"],e.languages.coffee=e.languages.coffeescript})(Nt),(function(e){var t=e.languages.javadoclike={parameter:{pattern:/(^[\t ]*(?:\/{3}|\*|\/\*\*)\s*@(?:arg|arguments|param)\s+)\w+/m,lookbehind:!0},keyword:{pattern:/(^[\t ]*(?:\/{3}|\*|\/\*\*)\s*|\{)@[a-z][a-zA-Z-]+\b/m,lookbehind:!0},punctuation:/[{}]/};Object.defineProperty(t,"addSupport",{value:function(n,r){(n=typeof n=="string"?[n]:n).forEach(function(s){var a=function(f){f.inside||(f.inside={}),f.inside.rest=r},i="doc-comment";if(l=e.languages[s]){var l,c=l[i];if((c=c||(l=e.languages.insertBefore(s,"comment",{"doc-comment":{pattern:/(^|[^\\])\/\*\*[^/][\s\S]*?(?:\*\/|$)/,lookbehind:!0,alias:"comment"}}))[i])instanceof RegExp&&(c=l[i]={pattern:c}),Array.isArray(c))for(var u=0,d=c.length;u<d;u++)c[u]instanceof RegExp&&(c[u]={pattern:c[u]}),a(c[u]);else a(c)}})}}),t.addSupport(["java","javascript","php"],t)})(Nt),(function(e){var t=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/,t=(e.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp("@[\\w-](?:"+/[^;{\s"']|\s+(?!\s)/.source+"|"+t.source+")*?"+/(?:;|(?=\s*\{))/.source),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:"selector"},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp("\\burl\\((?:"+t.source+"|"+/(?:[^\\\r\n()"']|\\[\s\S])*/.source+")\\)","i"),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp("^"+t.source+"$"),alias:"url"}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+t.source+")*(?=\\s*\\{)"),lookbehind:!0},string:{pattern:t,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},e.languages.css.atrule.inside.rest=e.languages.css,e.languages.markup);t&&(t.tag.addInlined("style","css"),t.tag.addAttribute("style","css"))})(Nt),(function(e){var t=/("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,t=(e.languages.css.selector={pattern:e.languages.css.selector.pattern,lookbehind:!0,inside:t={"pseudo-element":/:(?:after|before|first-letter|first-line|selection)|::[-\w]+/,"pseudo-class":/:[-\w]+/,class:/\.[-\w]+/,id:/#[-\w]+/,attribute:{pattern:RegExp(`\\[(?:[^[\\]"']|`+t.source+")*\\]"),greedy:!0,inside:{punctuation:/^\[|\]$/,"case-sensitivity":{pattern:/(\s)[si]$/i,lookbehind:!0,alias:"keyword"},namespace:{pattern:/^(\s*)(?:(?!\s)[-*\w\xA0-\uFFFF])*\|(?!=)/,lookbehind:!0,inside:{punctuation:/\|$/}},"attr-name":{pattern:/^(\s*)(?:(?!\s)[-\w\xA0-\uFFFF])+/,lookbehind:!0},"attr-value":[t,{pattern:/(=\s*)(?:(?!\s)[-\w\xA0-\uFFFF])+(?=\s*$)/,lookbehind:!0}],operator:/[|~*^$]?=/}},"n-th":[{pattern:/(\(\s*)[+-]?\d*[\dn](?:\s*[+-]\s*\d+)?(?=\s*\))/,lookbehind:!0,inside:{number:/[\dn]+/,operator:/[+-]/}},{pattern:/(\(\s*)(?:even|odd)(?=\s*\))/i,lookbehind:!0}],combinator:/>|\+|~|\|\|/,punctuation:/[(),]/}},e.languages.css.atrule.inside["selector-function-argument"].inside=t,e.languages.insertBefore("css","property",{variable:{pattern:/(^|[^-\w\xA0-\uFFFF])--(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*/i,lookbehind:!0}}),{pattern:/(\b\d+)(?:%|[a-z]+(?![\w-]))/,lookbehind:!0}),n={pattern:/(^|[^\w.-])-?(?:\d+(?:\.\d+)?|\.\d+)/,lookbehind:!0};e.languages.insertBefore("css","function",{operator:{pattern:/(\s)[+\-*\/](?=\s)/,lookbehind:!0},hexcode:{pattern:/\B#[\da-f]{3,8}\b/i,alias:"color"},color:[{pattern:/(^|[^\w-])(?:AliceBlue|AntiqueWhite|Aqua|Aquamarine|Azure|Beige|Bisque|Black|BlanchedAlmond|Blue|BlueViolet|Brown|BurlyWood|CadetBlue|Chartreuse|Chocolate|Coral|CornflowerBlue|Cornsilk|Crimson|Cyan|DarkBlue|DarkCyan|DarkGoldenRod|DarkGr[ae]y|DarkGreen|DarkKhaki|DarkMagenta|DarkOliveGreen|DarkOrange|DarkOrchid|DarkRed|DarkSalmon|DarkSeaGreen|DarkSlateBlue|DarkSlateGr[ae]y|DarkTurquoise|DarkViolet|DeepPink|DeepSkyBlue|DimGr[ae]y|DodgerBlue|FireBrick|FloralWhite|ForestGreen|Fuchsia|Gainsboro|GhostWhite|Gold|GoldenRod|Gr[ae]y|Green|GreenYellow|HoneyDew|HotPink|IndianRed|Indigo|Ivory|Khaki|Lavender|LavenderBlush|LawnGreen|LemonChiffon|LightBlue|LightCoral|LightCyan|LightGoldenRodYellow|LightGr[ae]y|LightGreen|LightPink|LightSalmon|LightSeaGreen|LightSkyBlue|LightSlateGr[ae]y|LightSteelBlue|LightYellow|Lime|LimeGreen|Linen|Magenta|Maroon|MediumAquaMarine|MediumBlue|MediumOrchid|MediumPurple|MediumSeaGreen|MediumSlateBlue|MediumSpringGreen|MediumTurquoise|MediumVioletRed|MidnightBlue|MintCream|MistyRose|Moccasin|NavajoWhite|Navy|OldLace|Olive|OliveDrab|Orange|OrangeRed|Orchid|PaleGoldenRod|PaleGreen|PaleTurquoise|PaleVioletRed|PapayaWhip|PeachPuff|Peru|Pink|Plum|PowderBlue|Purple|RebeccaPurple|Red|RosyBrown|RoyalBlue|SaddleBrown|Salmon|SandyBrown|SeaGreen|SeaShell|Sienna|Silver|SkyBlue|SlateBlue|SlateGr[ae]y|Snow|SpringGreen|SteelBlue|Tan|Teal|Thistle|Tomato|Transparent|Turquoise|Violet|Wheat|White|WhiteSmoke|Yellow|YellowGreen)(?![\w-])/i,lookbehind:!0},{pattern:/\b(?:hsl|rgb)\(\s*\d{1,3}\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*\)\B|\b(?:hsl|rgb)a\(\s*\d{1,3}\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*(?:0|0?\.\d+|1)\s*\)\B/i,inside:{unit:t,number:n,function:/[\w-]+(?=\()/,punctuation:/[(),]/}}],entity:/\\[\da-f]{1,8}/i,unit:t,number:n})})(Nt),(function(e){var t=/[*&][^\s[\]{},]+/,n=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,r="(?:"+n.source+"(?:[ ]+"+t.source+")?|"+t.source+"(?:[ ]+"+n.source+")?)",s=/(?:[^\s\x00-\x08\x0e-\x1f!"#%&'*,\-:>?@[\]`{|}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]|[?:-]<PLAIN>)(?:[ \t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*/.source.replace(/<PLAIN>/g,function(){return/[^\s\x00-\x08\x0e-\x1f,[\]{}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]/.source}),a=/"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\\\r\n]|\\.)*'/.source;function i(l,c){c=(c||"").replace(/m/g,"")+"m";var u=/([:\-,[{]\s*(?:\s<<prop>>[ \t]+)?)(?:<<value>>)(?=[ \t]*(?:$|,|\]|\}|(?:[\r\n]\s*)?#))/.source.replace(/<<prop>>/g,function(){return r}).replace(/<<value>>/g,function(){return l});return RegExp(u,c)}e.languages.yaml={scalar:{pattern:RegExp(/([\-:]\s*(?:\s<<prop>>[ \t]+)?[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)\S[^\r\n]*(?:\2[^\r\n]+)*)/.source.replace(/<<prop>>/g,function(){return r})),lookbehind:!0,alias:"string"},comment:/#.*/,key:{pattern:RegExp(/((?:^|[:\-,[{\r\n?])[ \t]*(?:<<prop>>[ \t]+)?)<<key>>(?=\s*:\s)/.source.replace(/<<prop>>/g,function(){return r}).replace(/<<key>>/g,function(){return"(?:"+s+"|"+a+")"})),lookbehind:!0,greedy:!0,alias:"atrule"},directive:{pattern:/(^[ \t]*)%.+/m,lookbehind:!0,alias:"important"},datetime:{pattern:i(/\d{4}-\d\d?-\d\d?(?:[tT]|[ \t]+)\d\d?:\d{2}:\d{2}(?:\.\d*)?(?:[ \t]*(?:Z|[-+]\d\d?(?::\d{2})?))?|\d{4}-\d{2}-\d{2}|\d\d?:\d{2}(?::\d{2}(?:\.\d*)?)?/.source),lookbehind:!0,alias:"number"},boolean:{pattern:i(/false|true/.source,"i"),lookbehind:!0,alias:"important"},null:{pattern:i(/null|~/.source,"i"),lookbehind:!0,alias:"important"},string:{pattern:i(a),lookbehind:!0,greedy:!0},number:{pattern:i(/[+-]?(?:0x[\da-f]+|0o[0-7]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|\.inf|\.nan)/.source,"i"),lookbehind:!0},tag:n,important:t,punctuation:/---|[:[\]{}\-,|>?]|\.\.\./},e.languages.yml=e.languages.yaml})(Nt),(function(e){var t=/(?:\\.|[^\\\n\r]|(?:\n|\r\n?)(?![\r\n]))/.source;function n(u){return u=u.replace(/<inner>/g,function(){return t}),RegExp(/((?:^|[^\\])(?:\\{2})*)/.source+"(?:"+u+")")}var r=/(?:\\.|``(?:[^`\r\n]|`(?!`))+``|`[^`\r\n]+`|[^\\|\r\n`])+/.source,s=/\|?__(?:\|__)+\|?(?:(?:\n|\r\n?)|(?![\s\S]))/.source.replace(/__/g,function(){return r}),a=/\|?[ \t]*:?-{3,}:?[ \t]*(?:\|[ \t]*:?-{3,}:?[ \t]*)+\|?(?:\n|\r\n?)/.source,i=(e.languages.markdown=e.languages.extend("markup",{}),e.languages.insertBefore("markdown","prolog",{"front-matter-block":{pattern:/(^(?:\s*[\r\n])?)---(?!.)[\s\S]*?[\r\n]---(?!.)/,lookbehind:!0,greedy:!0,inside:{punctuation:/^---|---$/,"front-matter":{pattern:/\S+(?:\s+\S+)*/,alias:["yaml","language-yaml"],inside:e.languages.yaml}}},blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:"punctuation"},table:{pattern:RegExp("^"+s+a+"(?:"+s+")*","m"),inside:{"table-data-rows":{pattern:RegExp("^("+s+a+")(?:"+s+")*$"),lookbehind:!0,inside:{"table-data":{pattern:RegExp(r),inside:e.languages.markdown},punctuation:/\|/}},"table-line":{pattern:RegExp("^("+s+")"+a+"$"),lookbehind:!0,inside:{punctuation:/\||:?-{3,}:?/}},"table-header-row":{pattern:RegExp("^"+s+"$"),inside:{"table-header":{pattern:RegExp(r),alias:"important",inside:e.languages.markdown},punctuation:/\|/}}}},code:[{pattern:/((?:^|\n)[ \t]*\n|(?:^|\r\n?)[ \t]*\r\n?)(?: {4}|\t).+(?:(?:\n|\r\n?)(?: {4}|\t).+)*/,lookbehind:!0,alias:"keyword"},{pattern:/^```[\s\S]*?^```$/m,greedy:!0,inside:{"code-block":{pattern:/^(```.*(?:\n|\r\n?))[\s\S]+?(?=(?:\n|\r\n?)^```$)/m,lookbehind:!0},"code-language":{pattern:/^(```).+/,lookbehind:!0},punctuation:/```/}}],title:[{pattern:/\S.*(?:\n|\r\n?)(?:==+|--+)(?=[ \t]*$)/m,alias:"important",inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#.+/m,lookbehind:!0,alias:"important",inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])(?:[\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:"punctuation"},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:"punctuation"},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:"url"},bold:{pattern:n(/\b__(?:(?!_)<inner>|_(?:(?!_)<inner>)+_)+__\b|\*\*(?:(?!\*)<inner>|\*(?:(?!\*)<inner>)+\*)+\*\*/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^..)[\s\S]+(?=..$)/,lookbehind:!0,inside:{}},punctuation:/\*\*|__/}},italic:{pattern:n(/\b_(?:(?!_)<inner>|__(?:(?!_)<inner>)+__)+_\b|\*(?:(?!\*)<inner>|\*\*(?:(?!\*)<inner>)+\*\*)+\*/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^.)[\s\S]+(?=.$)/,lookbehind:!0,inside:{}},punctuation:/[*_]/}},strike:{pattern:n(/(~~?)(?:(?!~)<inner>)+\2/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^~~?)[\s\S]+(?=\1$)/,lookbehind:!0,inside:{}},punctuation:/~~?/}},"code-snippet":{pattern:/(^|[^\\`])(?:``[^`\r\n]+(?:`[^`\r\n]+)*``(?!`)|`[^`\r\n]+`(?!`))/,lookbehind:!0,greedy:!0,alias:["code","keyword"]},url:{pattern:n(/!?\[(?:(?!\])<inner>)+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)|[ \t]?\[(?:(?!\])<inner>)+\])/.source),lookbehind:!0,greedy:!0,inside:{operator:/^!/,content:{pattern:/(^\[)[^\]]+(?=\])/,lookbehind:!0,inside:{}},variable:{pattern:/(^\][ \t]?\[)[^\]]+(?=\]$)/,lookbehind:!0},url:{pattern:/(^\]\()[^\s)]+/,lookbehind:!0},string:{pattern:/(^[ \t]+)"(?:\\.|[^"\\])*"(?=\)$)/,lookbehind:!0}}}}),["url","bold","italic","strike"].forEach(function(u){["url","bold","italic","strike","code-snippet"].forEach(function(d){u!==d&&(e.languages.markdown[u].inside.content.inside[d]=e.languages.markdown[d])})}),e.hooks.add("after-tokenize",function(u){u.language!=="markdown"&&u.language!=="md"||(function d(f){if(f&&typeof f!="string")for(var p=0,h=f.length;p<h;p++){var m,g=f[p];g.type!=="code"?d(g.content):(m=g.content[1],g=g.content[3],m&&g&&m.type==="code-language"&&g.type==="code-block"&&typeof m.content=="string"&&(m=m.content.replace(/\b#/g,"sharp").replace(/\b\+\+/g,"pp"),m="language-"+(m=(/[a-z][\w-]*/i.exec(m)||[""])[0].toLowerCase()),g.alias?typeof g.alias=="string"?g.alias=[g.alias,m]:g.alias.push(m):g.alias=[m]))}})(u.tokens)}),e.hooks.add("wrap",function(u){if(u.type==="code-block"){for(var d="",f=0,p=u.classes.length;f<p;f++){var h=u.classes[f],h=/language-(.+)/.exec(h);if(h){d=h[1];break}}var m,g=e.languages[d];g?u.content=e.highlight((function(y){return y=y.replace(i,""),y=y.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi,function(b,x){var S;return(x=x.toLowerCase())[0]==="#"?(S=x[1]==="x"?parseInt(x.slice(2),16):Number(x.slice(1)),c(S)):l[x]||b})})(u.content),g,d):d&&d!=="none"&&e.plugins.autoloader&&(m="md-"+new Date().valueOf()+"-"+Math.floor(1e16*Math.random()),u.attributes.id=m,e.plugins.autoloader.loadLanguages(d,function(){var y=document.getElementById(m);y&&(y.innerHTML=e.highlight(y.textContent,e.languages[d],d))}))}}),RegExp(e.languages.markup.tag.pattern.source,"gi")),l={amp:"&",lt:"<",gt:">",quot:'"'},c=String.fromCodePoint||String.fromCharCode;e.languages.md=e.languages.markdown})(Nt),Nt.languages.graphql={comment:/#.*/,description:{pattern:/(?:"""(?:[^"]|(?!""")")*"""|"(?:\\.|[^\\"\r\n])*")(?=\s*[a-z_])/i,greedy:!0,alias:"string",inside:{"language-markdown":{pattern:/(^"(?:"")?)(?!\1)[\s\S]+(?=\1$)/,lookbehind:!0,inside:Nt.languages.markdown}}},string:{pattern:/"""(?:[^"]|(?!""")")*"""|"(?:\\.|[^\\"\r\n])*"/,greedy:!0},number:/(?:\B-|\b)\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,boolean:/\b(?:false|true)\b/,variable:/\$[a-z_]\w*/i,directive:{pattern:/@[a-z_]\w*/i,alias:"function"},"attr-name":{pattern:/\b[a-z_]\w*(?=\s*(?:\((?:[^()"]|"(?:\\.|[^\\"\r\n])*")*\))?:)/i,greedy:!0},"atom-input":{pattern:/\b[A-Z]\w*Input\b/,alias:"class-name"},scalar:/\b(?:Boolean|Float|ID|Int|String)\b/,constant:/\b[A-Z][A-Z_\d]*\b/,"class-name":{pattern:/(\b(?:enum|implements|interface|on|scalar|type|union)\s+|&\s*|:\s*|\[)[A-Z_]\w*/,lookbehind:!0},fragment:{pattern:/(\bfragment\s+|\.{3}\s*(?!on\b))[a-zA-Z_]\w*/,lookbehind:!0,alias:"function"},"definition-mutation":{pattern:/(\bmutation\s+)[a-zA-Z_]\w*/,lookbehind:!0,alias:"function"},"definition-query":{pattern:/(\bquery\s+)[a-zA-Z_]\w*/,lookbehind:!0,alias:"function"},keyword:/\b(?:directive|enum|extend|fragment|implements|input|interface|mutation|on|query|repeatable|scalar|schema|subscription|type|union)\b/,operator:/[!=|&]|\.{3}/,"property-query":/\w+(?=\s*\()/,object:/\w+(?=\s*\{)/,punctuation:/[!(){}\[\]:=,]/,property:/\w+/},Nt.hooks.add("after-tokenize",function(e){if(e.language==="graphql")for(var t=e.tokens.filter(function(m){return typeof m!="string"&&m.type!=="comment"&&m.type!=="scalar"}),n=0;n<t.length;){var r=t[n++];if(r.type==="keyword"&&r.content==="mutation"){var s=[];if(f(["definition-mutation","punctuation"])&&d(1).content==="("){n+=2;var a=p(/^\($/,/^\)$/);if(a===-1)continue;for(;n<a;n++){var i=d(0);i.type==="variable"&&(h(i,"variable-input"),s.push(i.content))}n=a+1}if(f(["punctuation","property-query"])&&d(0).content==="{"&&(n++,h(d(0),"property-mutation"),0<s.length)){var l=p(/^\{$/,/^\}$/);if(l!==-1)for(var c=n;c<l;c++){var u=t[c];u.type==="variable"&&0<=s.indexOf(u.content)&&h(u,"variable-input")}}}}function d(m){return t[n+m]}function f(m,g){g=g||0;for(var y=0;y<m.length;y++){var b=d(y+g);if(!b||b.type!==m[y])return}return 1}function p(m,g){for(var y=1,b=n;b<t.length;b++){var x=t[b],S=x.content;if(x.type==="punctuation"&&typeof S=="string"){if(m.test(S))y++;else if(g.test(S)&&--y===0)return b}}return-1}function h(m,g){var y=m.alias;y?Array.isArray(y)||(m.alias=y=[y]):m.alias=y=[],y.push(g)}}),Nt.languages.sql={comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,lookbehind:!0},variable:[{pattern:/@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,greedy:!0},/@[\w.$]+/],string:{pattern:/(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,greedy:!0,lookbehind:!0},identifier:{pattern:/(^|[^@\\])`(?:\\[\s\S]|[^`\\]|``)*`/,greedy:!0,lookbehind:!0,inside:{punctuation:/^`|`$/}},function:/\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i,keyword:/\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:COL|_INSERT)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:ING|S)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i,boolean:/\b(?:FALSE|NULL|TRUE)\b/i,number:/\b0x[\da-f]+\b|\b\d+(?:\.\d*)?|\B\.\d+\b/i,operator:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|ILIKE|IN|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,punctuation:/[;[\]()`,.]/},(function(e){var t=e.languages.javascript["template-string"],n=t.pattern.source,r=t.inside.interpolation,s=r.inside["interpolation-punctuation"],a=r.pattern.source;function i(f,p){if(e.languages[f])return{pattern:RegExp("((?:"+p+")\\s*)"+n),lookbehind:!0,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},"embedded-code":{pattern:/[\s\S]+/,alias:f}}}}function l(f,p,h){return f={code:f,grammar:p,language:h},e.hooks.run("before-tokenize",f),f.tokens=e.tokenize(f.code,f.grammar),e.hooks.run("after-tokenize",f),f.tokens}function c(f,p,h){var y=e.tokenize(f,{interpolation:{pattern:RegExp(a),lookbehind:!0}}),m=0,g={},y=l(y.map(function(x){if(typeof x=="string")return x;for(var S,k,x=x.content;f.indexOf((k=m++,S="___"+h.toUpperCase()+"_"+k+"___"))!==-1;);return g[S]=x,S}).join(""),p,h),b=Object.keys(g);return m=0,(function x(S){for(var k=0;k<S.length;k++){if(m>=b.length)return;var C,_,E,T,N,I,A,R=S[k];typeof R=="string"||typeof R.content=="string"?(C=b[m],(A=(I=typeof R=="string"?R:R.content).indexOf(C))!==-1&&(++m,_=I.substring(0,A),N=g[C],E=void 0,(T={})["interpolation-punctuation"]=s,(T=e.tokenize(N,T)).length===3&&((E=[1,1]).push.apply(E,l(T[1],e.languages.javascript,"javascript")),T.splice.apply(T,E)),E=new e.Token("interpolation",T,r.alias,N),T=I.substring(A+C.length),N=[],_&&N.push(_),N.push(E),T&&(x(I=[T]),N.push.apply(N,I)),typeof R=="string"?(S.splice.apply(S,[k,1].concat(N)),k+=N.length-1):R.content=N)):(A=R.content,Array.isArray(A)?x(A):x([A]))}})(y),new e.Token(h,y,"language-"+h,f)}e.languages.javascript["template-string"]=[i("css",/\b(?:styled(?:\([^)]*\))?(?:\s*\.\s*\w+(?:\([^)]*\))*)*|css(?:\s*\.\s*(?:global|resolve))?|createGlobalStyle|keyframes)/.source),i("html",/\bhtml|\.\s*(?:inner|outer)HTML\s*\+?=/.source),i("svg",/\bsvg/.source),i("markdown",/\b(?:markdown|md)/.source),i("graphql",/\b(?:gql|graphql(?:\s*\.\s*experimental)?)/.source),i("sql",/\bsql/.source),t].filter(Boolean);var u={javascript:!0,js:!0,typescript:!0,ts:!0,jsx:!0,tsx:!0};function d(f){return typeof f=="string"?f:Array.isArray(f)?f.map(d).join(""):d(f.content)}e.hooks.add("after-tokenize",function(f){f.language in u&&(function p(h){for(var m=0,g=h.length;m<g;m++){var y,b,x,S=h[m];typeof S!="string"&&(y=S.content,Array.isArray(y)?S.type==="template-string"?(S=y[1],y.length===3&&typeof S!="string"&&S.type==="embedded-code"&&(b=d(S),S=S.alias,S=Array.isArray(S)?S[0]:S,x=e.languages[S])&&(y[1]=c(b,x,S))):p(y):typeof y!="string"&&p([y]))}})(f.tokens)})})(Nt),(function(e){e.languages.typescript=e.languages.extend("javascript",{"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,lookbehind:!0,greedy:!0,inside:null},builtin:/\b(?:Array|Function|Promise|any|boolean|console|never|number|string|symbol|unknown)\b/}),e.languages.typescript.keyword.push(/\b(?:abstract|declare|is|keyof|readonly|require)\b/,/\b(?:asserts|infer|interface|module|namespace|type)\b(?=\s*(?:[{_$a-zA-Z\xA0-\uFFFF]|$))/,/\btype\b(?=\s*(?:[\{*]|$))/),delete e.languages.typescript.parameter,delete e.languages.typescript["literal-property"];var t=e.languages.extend("typescript",{});delete t["class-name"],e.languages.typescript["class-name"].inside=t,e.languages.insertBefore("typescript","function",{decorator:{pattern:/@[$\w\xA0-\uFFFF]+/,inside:{at:{pattern:/^@/,alias:"operator"},function:/^[\s\S]+/}},"generic-function":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,greedy:!0,inside:{function:/^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:t}}}}),e.languages.ts=e.languages.typescript})(Nt),(function(e){var t=e.languages.javascript,n=/\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})+\}/.source,r="(@(?:arg|argument|param|property)\\s+(?:"+n+"\\s+)?)";e.languages.jsdoc=e.languages.extend("javadoclike",{parameter:{pattern:RegExp(r+/(?:(?!\s)[$\w\xA0-\uFFFF.])+(?=\s|$)/.source),lookbehind:!0,inside:{punctuation:/\./}}}),e.languages.insertBefore("jsdoc","keyword",{"optional-parameter":{pattern:RegExp(r+/\[(?:(?!\s)[$\w\xA0-\uFFFF.])+(?:=[^[\]]+)?\](?=\s|$)/.source),lookbehind:!0,inside:{parameter:{pattern:/(^\[)[$\w\xA0-\uFFFF\.]+/,lookbehind:!0,inside:{punctuation:/\./}},code:{pattern:/(=)[\s\S]*(?=\]$)/,lookbehind:!0,inside:t,alias:"language-javascript"},punctuation:/[=[\]]/}},"class-name":[{pattern:RegExp(/(@(?:augments|class|extends|interface|memberof!?|template|this|typedef)\s+(?:<TYPE>\s+)?)[A-Z]\w*(?:\.[A-Z]\w*)*/.source.replace(/<TYPE>/g,function(){return n})),lookbehind:!0,inside:{punctuation:/\./}},{pattern:RegExp("(@[a-z]+\\s+)"+n),lookbehind:!0,inside:{string:t.string,number:t.number,boolean:t.boolean,keyword:e.languages.typescript.keyword,operator:/=>|\.\.\.|[&|?:*]/,punctuation:/[.,;=<>{}()[\]]/}}],example:{pattern:/(@example\s+(?!\s))(?:[^@\s]|\s+(?!\s))+?(?=\s*(?:\*\s*)?(?:@\w|\*\/))/,lookbehind:!0,inside:{code:{pattern:/^([\t ]*(?:\*\s*)?)\S.*$/m,lookbehind:!0,inside:t,alias:"language-javascript"}}}}),e.languages.javadoclike.addSupport("javascript",e.languages.jsdoc)})(Nt),(function(e){e.languages.flow=e.languages.extend("javascript",{}),e.languages.insertBefore("flow","keyword",{type:[{pattern:/\b(?:[Bb]oolean|Function|[Nn]umber|[Ss]tring|[Ss]ymbol|any|mixed|null|void)\b/,alias:"class-name"}]}),e.languages.flow["function-variable"].pattern=/(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=\s*(?:function\b|(?:\([^()]*\)(?:\s*:\s*\w+)?|(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/i,delete e.languages.flow.parameter,e.languages.insertBefore("flow","operator",{"flow-punctuation":{pattern:/\{\||\|\}/,alias:"punctuation"}}),Array.isArray(e.languages.flow.keyword)||(e.languages.flow.keyword=[e.languages.flow.keyword]),e.languages.flow.keyword.unshift({pattern:/(^|[^$]\b)(?:Class|declare|opaque|type)\b(?!\$)/,lookbehind:!0},{pattern:/(^|[^$]\B)\$(?:Diff|Enum|Exact|Keys|ObjMap|PropertyType|Record|Shape|Subtype|Supertype|await)\b(?!\$)/,lookbehind:!0})})(Nt),Nt.languages.n4js=Nt.languages.extend("javascript",{keyword:/\b(?:Array|any|boolean|break|case|catch|class|const|constructor|continue|debugger|declare|default|delete|do|else|enum|export|extends|false|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|module|new|null|number|package|private|protected|public|return|set|static|string|super|switch|this|throw|true|try|typeof|var|void|while|with|yield)\b/}),Nt.languages.insertBefore("n4js","constant",{annotation:{pattern:/@+\w+/,alias:"operator"}}),Nt.languages.n4jsd=Nt.languages.n4js,(function(e){function t(i,l){return RegExp(i.replace(/<ID>/g,function(){return/(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/.source}),l)}e.languages.insertBefore("javascript","function-variable",{"method-variable":{pattern:RegExp("(\\.\\s*)"+e.languages.javascript["function-variable"].pattern.source),lookbehind:!0,alias:["function-variable","method","function","property-access"]}}),e.languages.insertBefore("javascript","function",{method:{pattern:RegExp("(\\.\\s*)"+e.languages.javascript.function.source),lookbehind:!0,alias:["function","property-access"]}}),e.languages.insertBefore("javascript","constant",{"known-class-name":[{pattern:/\b(?:(?:Float(?:32|64)|(?:Int|Uint)(?:8|16|32)|Uint8Clamped)?Array|ArrayBuffer|BigInt|Boolean|DataView|Date|Error|Function|Intl|JSON|(?:Weak)?(?:Map|Set)|Math|Number|Object|Promise|Proxy|Reflect|RegExp|String|Symbol|WebAssembly)\b/,alias:"class-name"},{pattern:/\b(?:[A-Z]\w*)Error\b/,alias:"class-name"}]}),e.languages.insertBefore("javascript","keyword",{imports:{pattern:t(/(\bimport\b\s*)(?:<ID>(?:\s*,\s*(?:\*\s*as\s+<ID>|\{[^{}]*\}))?|\*\s*as\s+<ID>|\{[^{}]*\})(?=\s*\bfrom\b)/.source),lookbehind:!0,inside:e.languages.javascript},exports:{pattern:t(/(\bexport\b\s*)(?:\*(?:\s*as\s+<ID>)?(?=\s*\bfrom\b)|\{[^{}]*\})/.source),lookbehind:!0,inside:e.languages.javascript}}),e.languages.javascript.keyword.unshift({pattern:/\b(?:as|default|export|from|import)\b/,alias:"module"},{pattern:/\b(?:await|break|catch|continue|do|else|finally|for|if|return|switch|throw|try|while|yield)\b/,alias:"control-flow"},{pattern:/\bnull\b/,alias:["null","nil"]},{pattern:/\bundefined\b/,alias:"nil"}),e.languages.insertBefore("javascript","operator",{spread:{pattern:/\.{3}/,alias:"operator"},arrow:{pattern:/=>/,alias:"operator"}}),e.languages.insertBefore("javascript","punctuation",{"property-access":{pattern:t(/(\.\s*)#?<ID>/.source),lookbehind:!0},"maybe-class-name":{pattern:/(^|[^$\w\xA0-\uFFFF])[A-Z][$\w\xA0-\uFFFF]+/,lookbehind:!0},dom:{pattern:/\b(?:document|(?:local|session)Storage|location|navigator|performance|window)\b/,alias:"variable"},console:{pattern:/\bconsole(?=\s*\.)/,alias:"class-name"}});for(var n=["function","function-variable","method","method-variable","property-access"],r=0;r<n.length;r++){var a=n[r],s=e.languages.javascript[a],a=(s=e.util.type(s)==="RegExp"?e.languages.javascript[a]={pattern:s}:s).inside||{};(s.inside=a)["maybe-class-name"]=/^[A-Z][\s\S]*/}})(Nt),(function(e){var t=e.util.clone(e.languages.javascript),n=/(?:\s|\/\/.*(?!.)|\/\*(?:[^*]|\*(?!\/))\*\/)/.source,r=/(?:\{(?:\{(?:\{[^{}]*\}|[^{}])*\}|[^{}])*\})/.source,s=/(?:\{<S>*\.{3}(?:[^{}]|<BRACES>)*\})/.source;function a(c,u){return c=c.replace(/<S>/g,function(){return n}).replace(/<BRACES>/g,function(){return r}).replace(/<SPREAD>/g,function(){return s}),RegExp(c,u)}s=a(s).source,e.languages.jsx=e.languages.extend("markup",t),e.languages.jsx.tag.pattern=a(/<\/?(?:[\w.:-]+(?:<S>+(?:[\w.:$-]+(?:=(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s{'"/>=]+|<BRACES>))?|<SPREAD>))*<S>*\/?)?>/.source),e.languages.jsx.tag.inside.tag.pattern=/^<\/?[^\s>\/]*/,e.languages.jsx.tag.inside["attr-value"].pattern=/=(?!\{)(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s'">]+)/,e.languages.jsx.tag.inside.tag.inside["class-name"]=/^[A-Z]\w*(?:\.[A-Z]\w*)*$/,e.languages.jsx.tag.inside.comment=t.comment,e.languages.insertBefore("inside","attr-name",{spread:{pattern:a(/<SPREAD>/.source),inside:e.languages.jsx}},e.languages.jsx.tag),e.languages.insertBefore("inside","special-attr",{script:{pattern:a(/=<BRACES>/.source),alias:"language-javascript",inside:{"script-punctuation":{pattern:/^=(?=\{)/,alias:"punctuation"},rest:e.languages.jsx}}},e.languages.jsx.tag);function i(c){for(var u=[],d=0;d<c.length;d++){var f=c[d],p=!1;typeof f!="string"&&(f.type==="tag"&&f.content[0]&&f.content[0].type==="tag"?f.content[0].content[0].content==="</"?0<u.length&&u[u.length-1].tagName===l(f.content[0].content[1])&&u.pop():f.content[f.content.length-1].content!=="/>"&&u.push({tagName:l(f.content[0].content[1]),openedBraces:0}):0<u.length&&f.type==="punctuation"&&f.content==="{"?u[u.length-1].openedBraces++:0<u.length&&0<u[u.length-1].openedBraces&&f.type==="punctuation"&&f.content==="}"?u[u.length-1].openedBraces--:p=!0),(p||typeof f=="string")&&0<u.length&&u[u.length-1].openedBraces===0&&(p=l(f),d<c.length-1&&(typeof c[d+1]=="string"||c[d+1].type==="plain-text")&&(p+=l(c[d+1]),c.splice(d+1,1)),0<d&&(typeof c[d-1]=="string"||c[d-1].type==="plain-text")&&(p=l(c[d-1])+p,c.splice(d-1,1),d--),c[d]=new e.Token("plain-text",p,null,p)),f.content&&typeof f.content!="string"&&i(f.content)}}var l=function(c){return c?typeof c=="string"?c:typeof c.content=="string"?c.content:c.content.map(l).join(""):""};e.hooks.add("after-tokenize",function(c){c.language!=="jsx"&&c.language!=="tsx"||i(c.tokens)})})(Nt),(function(e){var t=e.util.clone(e.languages.typescript),t=(e.languages.tsx=e.languages.extend("jsx",t),delete e.languages.tsx.parameter,delete e.languages.tsx["literal-property"],e.languages.tsx.tag);t.pattern=RegExp(/(^|[^\w$]|(?=<\/))/.source+"(?:"+t.pattern.source+")",t.pattern.flags),t.lookbehind=!0})(Nt),Nt.languages.swift={comment:{pattern:/(^|[^\\:])(?:\/\/.*|\/\*(?:[^/*]|\/(?!\*)|\*(?!\/)|\/\*(?:[^*]|\*(?!\/))*\*\/)*\*\/)/,lookbehind:!0,greedy:!0},"string-literal":[{pattern:RegExp(/(^|[^"#])/.source+"(?:"+/"(?:\\(?:\((?:[^()]|\([^()]*\))*\)|\r\n|[^(])|[^\\\r\n"])*"/.source+"|"+/"""(?:\\(?:\((?:[^()]|\([^()]*\))*\)|[^(])|[^\\"]|"(?!""))*"""/.source+")"+/(?!["#])/.source),lookbehind:!0,greedy:!0,inside:{interpolation:{pattern:/(\\\()(?:[^()]|\([^()]*\))*(?=\))/,lookbehind:!0,inside:null},"interpolation-punctuation":{pattern:/^\)|\\\($/,alias:"punctuation"},punctuation:/\\(?=[\r\n])/,string:/[\s\S]+/}},{pattern:RegExp(/(^|[^"#])(#+)/.source+"(?:"+/"(?:\\(?:#+\((?:[^()]|\([^()]*\))*\)|\r\n|[^#])|[^\\\r\n])*?"/.source+"|"+/"""(?:\\(?:#+\((?:[^()]|\([^()]*\))*\)|[^#])|[^\\])*?"""/.source+")\\2"),lookbehind:!0,greedy:!0,inside:{interpolation:{pattern:/(\\#+\()(?:[^()]|\([^()]*\))*(?=\))/,lookbehind:!0,inside:null},"interpolation-punctuation":{pattern:/^\)|\\#+\($/,alias:"punctuation"},string:/[\s\S]+/}}],directive:{pattern:RegExp(/#/.source+"(?:"+/(?:elseif|if)\b/.source+"(?:[ ]*"+/(?:![ \t]*)?(?:\b\w+\b(?:[ \t]*\((?:[^()]|\([^()]*\))*\))?|\((?:[^()]|\([^()]*\))*\))(?:[ \t]*(?:&&|\|\|))?/.source+")+|"+/(?:else|endif)\b/.source+")"),alias:"property",inside:{"directive-name":/^#\w+/,boolean:/\b(?:false|true)\b/,number:/\b\d+(?:\.\d+)*\b/,operator:/!|&&|\|\||[<>]=?/,punctuation:/[(),]/}},literal:{pattern:/#(?:colorLiteral|column|dsohandle|file(?:ID|Literal|Path)?|function|imageLiteral|line)\b/,alias:"constant"},"other-directive":{pattern:/#\w+\b/,alias:"property"},attribute:{pattern:/@\w+/,alias:"atrule"},"function-definition":{pattern:/(\bfunc\s+)\w+/,lookbehind:!0,alias:"function"},label:{pattern:/\b(break|continue)\s+\w+|\b[a-zA-Z_]\w*(?=\s*:\s*(?:for|repeat|while)\b)/,lookbehind:!0,alias:"important"},keyword:/\b(?:Any|Protocol|Self|Type|actor|as|assignment|associatedtype|associativity|async|await|break|case|catch|class|continue|convenience|default|defer|deinit|didSet|do|dynamic|else|enum|extension|fallthrough|fileprivate|final|for|func|get|guard|higherThan|if|import|in|indirect|infix|init|inout|internal|is|isolated|lazy|left|let|lowerThan|mutating|none|nonisolated|nonmutating|open|operator|optional|override|postfix|precedencegroup|prefix|private|protocol|public|repeat|required|rethrows|return|right|safe|self|set|some|static|struct|subscript|super|switch|throw|throws|try|typealias|unowned|unsafe|var|weak|where|while|willSet)\b/,boolean:/\b(?:false|true)\b/,nil:{pattern:/\bnil\b/,alias:"constant"},"short-argument":/\$\d+\b/,omit:{pattern:/\b_\b/,alias:"keyword"},number:/\b(?:[\d_]+(?:\.[\de_]+)?|0x[a-f0-9_]+(?:\.[a-f0-9p_]+)?|0b[01_]+|0o[0-7_]+)\b/i,"class-name":/\b[A-Z](?:[A-Z_\d]*[a-z]\w*)?\b/,function:/\b[a-z_]\w*(?=\s*\()/i,constant:/\b(?:[A-Z_]{2,}|k[A-Z][A-Za-z_]+)\b/,operator:/[-+*/%=!<>&|^~?]+|\.[.\-+*/%=!<>&|^~?]+/,punctuation:/[{}[\]();,.:\\]/},Nt.languages.swift["string-literal"].forEach(function(e){e.inside.interpolation.inside=Nt.languages.swift}),(function(e){e.languages.kotlin=e.languages.extend("clike",{keyword:{pattern:/(^|[^.])\b(?:abstract|actual|annotation|as|break|by|catch|class|companion|const|constructor|continue|crossinline|data|do|dynamic|else|enum|expect|external|final|finally|for|fun|get|if|import|in|infix|init|inline|inner|interface|internal|is|lateinit|noinline|null|object|open|operator|out|override|package|private|protected|public|reified|return|sealed|set|super|suspend|tailrec|this|throw|to|try|typealias|val|var|vararg|when|where|while)\b/,lookbehind:!0},function:[{pattern:/(?:`[^\r\n`]+`|\b\w+)(?=\s*\()/,greedy:!0},{pattern:/(\.)(?:`[^\r\n`]+`|\w+)(?=\s*\{)/,lookbehind:!0,greedy:!0}],number:/\b(?:0[xX][\da-fA-F]+(?:_[\da-fA-F]+)*|0[bB][01]+(?:_[01]+)*|\d+(?:_\d+)*(?:\.\d+(?:_\d+)*)?(?:[eE][+-]?\d+(?:_\d+)*)?[fFL]?)\b/,operator:/\+[+=]?|-[-=>]?|==?=?|!(?:!|==?)?|[\/*%<>]=?|[?:]:?|\.\.|&&|\|\||\b(?:and|inv|or|shl|shr|ushr|xor)\b/}),delete e.languages.kotlin["class-name"];var t={"interpolation-punctuation":{pattern:/^\$\{?|\}$/,alias:"punctuation"},expression:{pattern:/[\s\S]+/,inside:e.languages.kotlin}};e.languages.insertBefore("kotlin","string",{"string-literal":[{pattern:/"""(?:[^$]|\$(?:(?!\{)|\{[^{}]*\}))*?"""/,alias:"multiline",inside:{interpolation:{pattern:/\$(?:[a-z_]\w*|\{[^{}]*\})/i,inside:t},string:/[\s\S]+/}},{pattern:/"(?:[^"\\\r\n$]|\\.|\$(?:(?!\{)|\{[^{}]*\}))*"/,alias:"singleline",inside:{interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$(?:[a-z_]\w*|\{[^{}]*\})/i,lookbehind:!0,inside:t},string:/[\s\S]+/}}],char:{pattern:/'(?:[^'\\\r\n]|\\(?:.|u[a-fA-F0-9]{0,4}))'/,greedy:!0}}),delete e.languages.kotlin.string,e.languages.insertBefore("kotlin","keyword",{annotation:{pattern:/\B@(?:\w+:)?(?:[A-Z]\w*|\[[^\]]+\])/,alias:"builtin"}}),e.languages.insertBefore("kotlin","function",{label:{pattern:/\b\w+@|@\w+\b/,alias:"symbol"}}),e.languages.kt=e.languages.kotlin,e.languages.kts=e.languages.kotlin})(Nt),Nt.languages.c=Nt.languages.extend("clike",{comment:{pattern:/\/\/(?:[^\r\n\\]|\\(?:\r\n?|\n|(?![\r\n])))*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},string:{pattern:/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/,greedy:!0},"class-name":{pattern:/(\b(?:enum|struct)\s+(?:__attribute__\s*\(\([\s\S]*?\)\)\s*)?)\w+|\b[a-z]\w*_t\b/,lookbehind:!0},keyword:/\b(?:_Alignas|_Alignof|_Atomic|_Bool|_Complex|_Generic|_Imaginary|_Noreturn|_Static_assert|_Thread_local|__attribute__|asm|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|inline|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|typeof|union|unsigned|void|volatile|while)\b/,function:/\b[a-z_]\w*(?=\s*\()/i,number:/(?:\b0x(?:[\da-f]+(?:\.[\da-f]*)?|\.[\da-f]+)(?:p[+-]?\d+)?|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?)[ful]{0,4}/i,operator:/>>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?/}),Nt.languages.insertBefore("c","string",{char:{pattern:/'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n]){0,32}'/,greedy:!0}}),Nt.languages.insertBefore("c","string",{macro:{pattern:/(^[\t ]*)#\s*[a-z](?:[^\r\n\\/]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|\\(?:\r\n|[\s\S]))*/im,lookbehind:!0,greedy:!0,alias:"property",inside:{string:[{pattern:/^(#\s*include\s*)<[^>]+>/,lookbehind:!0},Nt.languages.c.string],char:Nt.languages.c.char,comment:Nt.languages.c.comment,"macro-name":[{pattern:/(^#\s*define\s+)\w+\b(?!\()/i,lookbehind:!0},{pattern:/(^#\s*define\s+)\w+\b(?=\()/i,lookbehind:!0,alias:"function"}],directive:{pattern:/^(#\s*)[a-z]+/,lookbehind:!0,alias:"keyword"},"directive-hash":/^#/,punctuation:/##|\\(?=[\r\n])/,expression:{pattern:/\S[\s\S]*/,inside:Nt.languages.c}}}}),Nt.languages.insertBefore("c","function",{constant:/\b(?:EOF|NULL|SEEK_CUR|SEEK_END|SEEK_SET|__DATE__|__FILE__|__LINE__|__TIMESTAMP__|__TIME__|__func__|stderr|stdin|stdout)\b/}),delete Nt.languages.c.boolean,Nt.languages.objectivec=Nt.languages.extend("c",{string:{pattern:/@?"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/,greedy:!0},keyword:/\b(?:asm|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|in|inline|int|long|register|return|self|short|signed|sizeof|static|struct|super|switch|typedef|typeof|union|unsigned|void|volatile|while)\b|(?:@interface|@end|@implementation|@protocol|@class|@public|@protected|@private|@property|@try|@catch|@finally|@throw|@synthesize|@dynamic|@selector)\b/,operator:/-[->]?|\+\+?|!=?|<<?=?|>>?=?|==?|&&?|\|\|?|[~^%?*\/@]/}),delete Nt.languages.objectivec["class-name"],Nt.languages.objc=Nt.languages.objectivec,Nt.languages.reason=Nt.languages.extend("clike",{string:{pattern:/"(?:\\(?:\r\n|[\s\S])|[^\\\r\n"])*"/,greedy:!0},"class-name":/\b[A-Z]\w*/,keyword:/\b(?:and|as|assert|begin|class|constraint|do|done|downto|else|end|exception|external|for|fun|function|functor|if|in|include|inherit|initializer|lazy|let|method|module|mutable|new|nonrec|object|of|open|or|private|rec|sig|struct|switch|then|to|try|type|val|virtual|when|while|with)\b/,operator:/\.{3}|:[:=]|\|>|->|=(?:==?|>)?|<=?|>=?|[|^?'#!~`]|[+\-*\/]\.?|\b(?:asr|land|lor|lsl|lsr|lxor|mod)\b/}),Nt.languages.insertBefore("reason","class-name",{char:{pattern:/'(?:\\x[\da-f]{2}|\\o[0-3][0-7][0-7]|\\\d{3}|\\.|[^'\\\r\n])'/,greedy:!0},constructor:/\b[A-Z]\w*\b(?!\s*\.)/,label:{pattern:/\b[a-z]\w*(?=::)/,alias:"symbol"}}),delete Nt.languages.reason.function,(function(e){for(var t=/\/\*(?:[^*/]|\*(?!\/)|\/(?!\*)|<self>)*\*\//.source,n=0;n<2;n++)t=t.replace(/<self>/g,function(){return t});t=t.replace(/<self>/g,function(){return/[^\s\S]/.source}),e.languages.rust={comment:[{pattern:RegExp(/(^|[^\\])/.source+t),lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/b?"(?:\\[\s\S]|[^\\"])*"|b?r(#*)"(?:[^"]|"(?!\1))*"\1/,greedy:!0},char:{pattern:/b?'(?:\\(?:x[0-7][\da-fA-F]|u\{(?:[\da-fA-F]_*){1,6}\}|.)|[^\\\r\n\t'])'/,greedy:!0},attribute:{pattern:/#!?\[(?:[^\[\]"]|"(?:\\[\s\S]|[^\\"])*")*\]/,greedy:!0,alias:"attr-name",inside:{string:null}},"closure-params":{pattern:/([=(,:]\s*|\bmove\s*)\|[^|]*\||\|[^|]*\|(?=\s*(?:\{|->))/,lookbehind:!0,greedy:!0,inside:{"closure-punctuation":{pattern:/^\||\|$/,alias:"punctuation"},rest:null}},"lifetime-annotation":{pattern:/'\w+/,alias:"symbol"},"fragment-specifier":{pattern:/(\$\w+:)[a-z]+/,lookbehind:!0,alias:"punctuation"},variable:/\$\w+/,"function-definition":{pattern:/(\bfn\s+)\w+/,lookbehind:!0,alias:"function"},"type-definition":{pattern:/(\b(?:enum|struct|trait|type|union)\s+)\w+/,lookbehind:!0,alias:"class-name"},"module-declaration":[{pattern:/(\b(?:crate|mod)\s+)[a-z][a-z_\d]*/,lookbehind:!0,alias:"namespace"},{pattern:/(\b(?:crate|self|super)\s*)::\s*[a-z][a-z_\d]*\b(?:\s*::(?:\s*[a-z][a-z_\d]*\s*::)*)?/,lookbehind:!0,alias:"namespace",inside:{punctuation:/::/}}],keyword:[/\b(?:Self|abstract|as|async|await|become|box|break|const|continue|crate|do|dyn|else|enum|extern|final|fn|for|if|impl|in|let|loop|macro|match|mod|move|mut|override|priv|pub|ref|return|self|static|struct|super|trait|try|type|typeof|union|unsafe|unsized|use|virtual|where|while|yield)\b/,/\b(?:bool|char|f(?:32|64)|[ui](?:8|16|32|64|128|size)|str)\b/],function:/\b[a-z_]\w*(?=\s*(?:::\s*<|\())/,macro:{pattern:/\b\w+!/,alias:"property"},constant:/\b[A-Z_][A-Z_\d]+\b/,"class-name":/\b[A-Z]\w*\b/,namespace:{pattern:/(?:\b[a-z][a-z_\d]*\s*::\s*)*\b[a-z][a-z_\d]*\s*::(?!\s*<)/,inside:{punctuation:/::/}},number:/\b(?:0x[\dA-Fa-f](?:_?[\dA-Fa-f])*|0o[0-7](?:_?[0-7])*|0b[01](?:_?[01])*|(?:(?:\d(?:_?\d)*)?\.)?\d(?:_?\d)*(?:[Ee][+-]?\d+)?)(?:_?(?:f32|f64|[iu](?:8|16|32|64|size)?))?\b/,boolean:/\b(?:false|true)\b/,punctuation:/->|\.\.=|\.{1,3}|::|[{}[\];(),:]/,operator:/[-+*\/%!^]=?|=[=>]?|&[&=]?|\|[|=]?|<<?=?|>>?=?|[@?]/},e.languages.rust["closure-params"].inside.rest=e.languages.rust,e.languages.rust.attribute.inside.string=e.languages.rust.string})(Nt),Nt.languages.go=Nt.languages.extend("clike",{string:{pattern:/(^|[^\\])"(?:\\.|[^"\\\r\n])*"|`[^`]*`/,lookbehind:!0,greedy:!0},keyword:/\b(?:break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go(?:to)?|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/,boolean:/\b(?:_|false|iota|nil|true)\b/,number:[/\b0(?:b[01_]+|o[0-7_]+)i?\b/i,/\b0x(?:[a-f\d_]+(?:\.[a-f\d_]*)?|\.[a-f\d_]+)(?:p[+-]?\d+(?:_\d+)*)?i?(?!\w)/i,/(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?[\d_]+)?i?(?!\w)/i],operator:/[*\/%^!=]=?|\+[=+]?|-[=-]?|\|[=|]?|&(?:=|&|\^=?)?|>(?:>=?|=)?|<(?:<=?|=|-)?|:=|\.\.\./,builtin:/\b(?:append|bool|byte|cap|close|complex|complex(?:64|128)|copy|delete|error|float(?:32|64)|u?int(?:8|16|32|64)?|imag|len|make|new|panic|print(?:ln)?|real|recover|rune|string|uintptr)\b/}),Nt.languages.insertBefore("go","string",{char:{pattern:/'(?:\\.|[^'\\\r\n]){0,10}'/,greedy:!0}}),delete Nt.languages.go["class-name"],(function(e){var t=/\b(?:alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|char8_t|class|co_await|co_return|co_yield|compl|concept|const|const_cast|consteval|constexpr|constinit|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|final|float|for|friend|goto|if|import|inline|int|int16_t|int32_t|int64_t|int8_t|long|module|mutable|namespace|new|noexcept|nullptr|operator|override|private|protected|public|register|reinterpret_cast|requires|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|uint16_t|uint32_t|uint64_t|uint8_t|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/,n=/\b(?!<keyword>)\w+(?:\s*\.\s*\w+)*\b/.source.replace(/<keyword>/g,function(){return t.source});e.languages.cpp=e.languages.extend("c",{"class-name":[{pattern:RegExp(/(\b(?:class|concept|enum|struct|typename)\s+)(?!<keyword>)\w+/.source.replace(/<keyword>/g,function(){return t.source})),lookbehind:!0},/\b[A-Z]\w*(?=\s*::\s*\w+\s*\()/,/\b[A-Z_]\w*(?=\s*::\s*~\w+\s*\()/i,/\b\w+(?=\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>\s*::\s*\w+\s*\()/],keyword:t,number:{pattern:/(?:\b0b[01']+|\b0x(?:[\da-f']+(?:\.[\da-f']*)?|\.[\da-f']+)(?:p[+-]?[\d']+)?|(?:\b[\d']+(?:\.[\d']*)?|\B\.[\d']+)(?:e[+-]?[\d']+)?)[ful]{0,4}/i,greedy:!0},operator:/>>=?|<<=?|->|--|\+\+|&&|\|\||[?:~]|<=>|[-+*/%&|^!=<>]=?|\b(?:and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/,boolean:/\b(?:false|true)\b/}),e.languages.insertBefore("cpp","string",{module:{pattern:RegExp(/(\b(?:import|module)\s+)/.source+"(?:"+/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|<[^<>\r\n]*>/.source+"|"+/<mod-name>(?:\s*:\s*<mod-name>)?|:\s*<mod-name>/.source.replace(/<mod-name>/g,function(){return n})+")"),lookbehind:!0,greedy:!0,inside:{string:/^[<"][\s\S]+/,operator:/:/,punctuation:/\./}},"raw-string":{pattern:/R"([^()\\ ]{0,16})\([\s\S]*?\)\1"/,alias:"string",greedy:!0}}),e.languages.insertBefore("cpp","keyword",{"generic-function":{pattern:/\b(?!operator\b)[a-z_]\w*\s*<(?:[^<>]|<[^<>]*>)*>(?=\s*\()/i,inside:{function:/^\w+/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:e.languages.cpp}}}}),e.languages.insertBefore("cpp","operator",{"double-colon":{pattern:/::/,alias:"punctuation"}}),e.languages.insertBefore("cpp","class-name",{"base-clause":{pattern:/(\b(?:class|struct)\s+\w+\s*:\s*)[^;{}"'\s]+(?:\s+[^;{}"'\s]+)*(?=\s*[;{])/,lookbehind:!0,greedy:!0,inside:e.languages.extend("cpp",{})}}),e.languages.insertBefore("inside","double-colon",{"class-name":/\b[a-z_]\w*\b(?!\s*::)/i},e.languages.cpp["base-clause"])})(Nt),Nt.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0,greedy:!0},"string-interpolation":{pattern:/(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=\}$)/,lookbehind:!0},"conversion-option":{pattern:/![sra](?=[:}]$)/,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},function:{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^[\t ]*)@\w+(?:\.\w+)*/m,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,boolean:/\b(?:False|None|True)\b/,number:/\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,operator:/[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/},Nt.languages.python["string-interpolation"].inside.interpolation.inside.rest=Nt.languages.python,Nt.languages.py=Nt.languages.python,Nt.languages.json={property:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,lookbehind:!0,greedy:!0},string:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,lookbehind:!0,greedy:!0},comment:{pattern:/\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},number:/-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,punctuation:/[{}[\],]/,operator:/:/,boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:"keyword"}},Nt.languages.webmanifest=Nt.languages.json;var ZTe={};e7r(ZTe,{dracula:()=>a7r,duotoneDark:()=>o7r,duotoneLight:()=>c7r,github:()=>d7r,gruvboxMaterialDark:()=>F7r,gruvboxMaterialLight:()=>U7r,jettwaveDark:()=>A7r,jettwaveLight:()=>P7r,nightOwl:()=>p7r,nightOwlLight:()=>m7r,oceanicNext:()=>v7r,okaidia:()=>b7r,oneDark:()=>M7r,oneLight:()=>L7r,palenight:()=>w7r,shadesOfPurple:()=>k7r,synthwave84:()=>_7r,ultramin:()=>E7r,vsDark:()=>W3t,vsLight:()=>N7r});var s7r={plain:{color:"#F8F8F2",backgroundColor:"#282A36"},styles:[{types:["prolog","constant","builtin"],style:{color:"rgb(189, 147, 249)"}},{types:["inserted","function"],style:{color:"rgb(80, 250, 123)"}},{types:["deleted"],style:{color:"rgb(255, 85, 85)"}},{types:["changed"],style:{color:"rgb(255, 184, 108)"}},{types:["punctuation","symbol"],style:{color:"rgb(248, 248, 242)"}},{types:["string","char","tag","selector"],style:{color:"rgb(255, 121, 198)"}},{types:["keyword","variable"],style:{color:"rgb(189, 147, 249)",fontStyle:"italic"}},{types:["comment"],style:{color:"rgb(98, 114, 164)"}},{types:["attr-name"],style:{color:"rgb(241, 250, 140)"}}]},a7r=s7r,i7r={plain:{backgroundColor:"#2a2734",color:"#9a86fd"},styles:[{types:["comment","prolog","doctype","cdata","punctuation"],style:{color:"#6c6783"}},{types:["namespace"],style:{opacity:.7}},{types:["tag","operator","number"],style:{color:"#e09142"}},{types:["property","function"],style:{color:"#9a86fd"}},{types:["tag-id","selector","atrule-id"],style:{color:"#eeebff"}},{types:["attr-name"],style:{color:"#c4b9fe"}},{types:["boolean","string","entity","url","attr-value","keyword","control","directive","unit","statement","regex","atrule","placeholder","variable"],style:{color:"#ffcc99"}},{types:["deleted"],style:{textDecorationLine:"line-through"}},{types:["inserted"],style:{textDecorationLine:"underline"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["important","bold"],style:{fontWeight:"bold"}},{types:["important"],style:{color:"#c4b9fe"}}]},o7r=i7r,l7r={plain:{backgroundColor:"#faf8f5",color:"#728fcb"},styles:[{types:["comment","prolog","doctype","cdata","punctuation"],style:{color:"#b6ad9a"}},{types:["namespace"],style:{opacity:.7}},{types:["tag","operator","number"],style:{color:"#063289"}},{types:["property","function"],style:{color:"#b29762"}},{types:["tag-id","selector","atrule-id"],style:{color:"#2d2006"}},{types:["attr-name"],style:{color:"#896724"}},{types:["boolean","string","entity","url","attr-value","keyword","control","directive","unit","statement","regex","atrule"],style:{color:"#728fcb"}},{types:["placeholder","variable"],style:{color:"#93abdc"}},{types:["deleted"],style:{textDecorationLine:"line-through"}},{types:["inserted"],style:{textDecorationLine:"underline"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["important","bold"],style:{fontWeight:"bold"}},{types:["important"],style:{color:"#896724"}}]},c7r=l7r,u7r={plain:{color:"#393A34",backgroundColor:"#f6f8fa"},styles:[{types:["comment","prolog","doctype","cdata"],style:{color:"#999988",fontStyle:"italic"}},{types:["namespace"],style:{opacity:.7}},{types:["string","attr-value"],style:{color:"#e3116c"}},{types:["punctuation","operator"],style:{color:"#393A34"}},{types:["entity","url","symbol","number","boolean","variable","constant","property","regex","inserted"],style:{color:"#36acaa"}},{types:["atrule","keyword","attr-name","selector"],style:{color:"#00a4db"}},{types:["function","deleted","tag"],style:{color:"#d73a49"}},{types:["function-variable"],style:{color:"#6f42c1"}},{types:["tag","selector","keyword"],style:{color:"#00009f"}}]},d7r=u7r,f7r={plain:{color:"#d6deeb",backgroundColor:"#011627"},styles:[{types:["changed"],style:{color:"rgb(162, 191, 252)",fontStyle:"italic"}},{types:["deleted"],style:{color:"rgba(239, 83, 80, 0.56)",fontStyle:"italic"}},{types:["inserted","attr-name"],style:{color:"rgb(173, 219, 103)",fontStyle:"italic"}},{types:["comment"],style:{color:"rgb(99, 119, 119)",fontStyle:"italic"}},{types:["string","url"],style:{color:"rgb(173, 219, 103)"}},{types:["variable"],style:{color:"rgb(214, 222, 235)"}},{types:["number"],style:{color:"rgb(247, 140, 108)"}},{types:["builtin","char","constant","function"],style:{color:"rgb(130, 170, 255)"}},{types:["punctuation"],style:{color:"rgb(199, 146, 234)"}},{types:["selector","doctype"],style:{color:"rgb(199, 146, 234)",fontStyle:"italic"}},{types:["class-name"],style:{color:"rgb(255, 203, 139)"}},{types:["tag","operator","keyword"],style:{color:"rgb(127, 219, 202)"}},{types:["boolean"],style:{color:"rgb(255, 88, 116)"}},{types:["property"],style:{color:"rgb(128, 203, 196)"}},{types:["namespace"],style:{color:"rgb(178, 204, 214)"}}]},p7r=f7r,h7r={plain:{color:"#403f53",backgroundColor:"#FBFBFB"},styles:[{types:["changed"],style:{color:"rgb(162, 191, 252)",fontStyle:"italic"}},{types:["deleted"],style:{color:"rgba(239, 83, 80, 0.56)",fontStyle:"italic"}},{types:["inserted","attr-name"],style:{color:"rgb(72, 118, 214)",fontStyle:"italic"}},{types:["comment"],style:{color:"rgb(152, 159, 177)",fontStyle:"italic"}},{types:["string","builtin","char","constant","url"],style:{color:"rgb(72, 118, 214)"}},{types:["variable"],style:{color:"rgb(201, 103, 101)"}},{types:["number"],style:{color:"rgb(170, 9, 130)"}},{types:["punctuation"],style:{color:"rgb(153, 76, 195)"}},{types:["function","selector","doctype"],style:{color:"rgb(153, 76, 195)",fontStyle:"italic"}},{types:["class-name"],style:{color:"rgb(17, 17, 17)"}},{types:["tag"],style:{color:"rgb(153, 76, 195)"}},{types:["operator","property","keyword","namespace"],style:{color:"rgb(12, 150, 155)"}},{types:["boolean"],style:{color:"rgb(188, 84, 84)"}}]},m7r=h7r,dp={char:"#D8DEE9",comment:"#999999",keyword:"#c5a5c5",primitive:"#5a9bcf",string:"#8dc891",variable:"#d7deea",boolean:"#ff8b50",tag:"#fc929e",function:"#79b6f2",className:"#FAC863"},g7r={plain:{backgroundColor:"#282c34",color:"#ffffff"},styles:[{types:["attr-name"],style:{color:dp.keyword}},{types:["attr-value"],style:{color:dp.string}},{types:["comment","block-comment","prolog","doctype","cdata","shebang"],style:{color:dp.comment}},{types:["property","number","function-name","constant","symbol","deleted"],style:{color:dp.primitive}},{types:["boolean"],style:{color:dp.boolean}},{types:["tag"],style:{color:dp.tag}},{types:["string"],style:{color:dp.string}},{types:["punctuation"],style:{color:dp.string}},{types:["selector","char","builtin","inserted"],style:{color:dp.char}},{types:["function"],style:{color:dp.function}},{types:["operator","entity","url","variable"],style:{color:dp.variable}},{types:["keyword"],style:{color:dp.keyword}},{types:["atrule","class-name"],style:{color:dp.className}},{types:["important"],style:{fontWeight:"400"}},{types:["bold"],style:{fontWeight:"bold"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["namespace"],style:{opacity:.7}}]},v7r=g7r,y7r={plain:{color:"#f8f8f2",backgroundColor:"#272822"},styles:[{types:["changed"],style:{color:"rgb(162, 191, 252)",fontStyle:"italic"}},{types:["deleted"],style:{color:"#f92672",fontStyle:"italic"}},{types:["inserted"],style:{color:"rgb(173, 219, 103)",fontStyle:"italic"}},{types:["comment"],style:{color:"#8292a2",fontStyle:"italic"}},{types:["string","url"],style:{color:"#a6e22e"}},{types:["variable"],style:{color:"#f8f8f2"}},{types:["number"],style:{color:"#ae81ff"}},{types:["builtin","char","constant","function","class-name"],style:{color:"#e6db74"}},{types:["punctuation"],style:{color:"#f8f8f2"}},{types:["selector","doctype"],style:{color:"#a6e22e",fontStyle:"italic"}},{types:["tag","operator","keyword"],style:{color:"#66d9ef"}},{types:["boolean"],style:{color:"#ae81ff"}},{types:["namespace"],style:{color:"rgb(178, 204, 214)",opacity:.7}},{types:["tag","property"],style:{color:"#f92672"}},{types:["attr-name"],style:{color:"#a6e22e !important"}},{types:["doctype"],style:{color:"#8292a2"}},{types:["rule"],style:{color:"#e6db74"}}]},b7r=y7r,x7r={plain:{color:"#bfc7d5",backgroundColor:"#292d3e"},styles:[{types:["comment"],style:{color:"rgb(105, 112, 152)",fontStyle:"italic"}},{types:["string","inserted"],style:{color:"rgb(195, 232, 141)"}},{types:["number"],style:{color:"rgb(247, 140, 108)"}},{types:["builtin","char","constant","function"],style:{color:"rgb(130, 170, 255)"}},{types:["punctuation","selector"],style:{color:"rgb(199, 146, 234)"}},{types:["variable"],style:{color:"rgb(191, 199, 213)"}},{types:["class-name","attr-name"],style:{color:"rgb(255, 203, 107)"}},{types:["tag","deleted"],style:{color:"rgb(255, 85, 114)"}},{types:["operator"],style:{color:"rgb(137, 221, 255)"}},{types:["boolean"],style:{color:"rgb(255, 88, 116)"}},{types:["keyword"],style:{fontStyle:"italic"}},{types:["doctype"],style:{color:"rgb(199, 146, 234)",fontStyle:"italic"}},{types:["namespace"],style:{color:"rgb(178, 204, 214)"}},{types:["url"],style:{color:"rgb(221, 221, 221)"}}]},w7r=x7r,S7r={plain:{color:"#9EFEFF",backgroundColor:"#2D2A55"},styles:[{types:["changed"],style:{color:"rgb(255, 238, 128)"}},{types:["deleted"],style:{color:"rgba(239, 83, 80, 0.56)"}},{types:["inserted"],style:{color:"rgb(173, 219, 103)"}},{types:["comment"],style:{color:"rgb(179, 98, 255)",fontStyle:"italic"}},{types:["punctuation"],style:{color:"rgb(255, 255, 255)"}},{types:["constant"],style:{color:"rgb(255, 98, 140)"}},{types:["string","url"],style:{color:"rgb(165, 255, 144)"}},{types:["variable"],style:{color:"rgb(255, 238, 128)"}},{types:["number","boolean"],style:{color:"rgb(255, 98, 140)"}},{types:["attr-name"],style:{color:"rgb(255, 180, 84)"}},{types:["keyword","operator","property","namespace","tag","selector","doctype"],style:{color:"rgb(255, 157, 0)"}},{types:["builtin","char","constant","function","class-name"],style:{color:"rgb(250, 208, 0)"}}]},k7r=S7r,O7r={plain:{backgroundColor:"linear-gradient(to bottom, #2a2139 75%, #34294f)",backgroundImage:"#34294f",color:"#f92aad",textShadow:"0 0 2px #100c0f, 0 0 5px #dc078e33, 0 0 10px #fff3"},styles:[{types:["comment","block-comment","prolog","doctype","cdata"],style:{color:"#495495",fontStyle:"italic"}},{types:["punctuation"],style:{color:"#ccc"}},{types:["tag","attr-name","namespace","number","unit","hexcode","deleted"],style:{color:"#e2777a"}},{types:["property","selector"],style:{color:"#72f1b8",textShadow:"0 0 2px #100c0f, 0 0 10px #257c5575, 0 0 35px #21272475"}},{types:["function-name"],style:{color:"#6196cc"}},{types:["boolean","selector-id","function"],style:{color:"#fdfdfd",textShadow:"0 0 2px #001716, 0 0 3px #03edf975, 0 0 5px #03edf975, 0 0 8px #03edf975"}},{types:["class-name","maybe-class-name","builtin"],style:{color:"#fff5f6",textShadow:"0 0 2px #000, 0 0 10px #fc1f2c75, 0 0 5px #fc1f2c75, 0 0 25px #fc1f2c75"}},{types:["constant","symbol"],style:{color:"#f92aad",textShadow:"0 0 2px #100c0f, 0 0 5px #dc078e33, 0 0 10px #fff3"}},{types:["important","atrule","keyword","selector-class"],style:{color:"#f4eee4",textShadow:"0 0 2px #393a33, 0 0 8px #f39f0575, 0 0 2px #f39f0575"}},{types:["string","char","attr-value","regex","variable"],style:{color:"#f87c32"}},{types:["parameter"],style:{fontStyle:"italic"}},{types:["entity","url"],style:{color:"#67cdcc"}},{types:["operator"],style:{color:"ffffffee"}},{types:["important","bold"],style:{fontWeight:"bold"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["entity"],style:{cursor:"help"}},{types:["inserted"],style:{color:"green"}}]},_7r=O7r,C7r={plain:{color:"#282a2e",backgroundColor:"#ffffff"},styles:[{types:["comment"],style:{color:"rgb(197, 200, 198)"}},{types:["string","number","builtin","variable"],style:{color:"rgb(150, 152, 150)"}},{types:["class-name","function","tag","attr-name"],style:{color:"rgb(40, 42, 46)"}}]},E7r=C7r,T7r={plain:{color:"#9CDCFE",backgroundColor:"#1E1E1E"},styles:[{types:["prolog"],style:{color:"rgb(0, 0, 128)"}},{types:["comment"],style:{color:"rgb(106, 153, 85)"}},{types:["builtin","changed","keyword","interpolation-punctuation"],style:{color:"rgb(86, 156, 214)"}},{types:["number","inserted"],style:{color:"rgb(181, 206, 168)"}},{types:["constant"],style:{color:"rgb(100, 102, 149)"}},{types:["attr-name","variable"],style:{color:"rgb(156, 220, 254)"}},{types:["deleted","string","attr-value","template-punctuation"],style:{color:"rgb(206, 145, 120)"}},{types:["selector"],style:{color:"rgb(215, 186, 125)"}},{types:["tag"],style:{color:"rgb(78, 201, 176)"}},{types:["tag"],languages:["markup"],style:{color:"rgb(86, 156, 214)"}},{types:["punctuation","operator"],style:{color:"rgb(212, 212, 212)"}},{types:["punctuation"],languages:["markup"],style:{color:"#808080"}},{types:["function"],style:{color:"rgb(220, 220, 170)"}},{types:["class-name"],style:{color:"rgb(78, 201, 176)"}},{types:["char"],style:{color:"rgb(209, 105, 105)"}}]},W3t=T7r,j7r={plain:{color:"#000000",backgroundColor:"#ffffff"},styles:[{types:["comment"],style:{color:"rgb(0, 128, 0)"}},{types:["builtin"],style:{color:"rgb(0, 112, 193)"}},{types:["number","variable","inserted"],style:{color:"rgb(9, 134, 88)"}},{types:["operator"],style:{color:"rgb(0, 0, 0)"}},{types:["constant","char"],style:{color:"rgb(129, 31, 63)"}},{types:["tag"],style:{color:"rgb(128, 0, 0)"}},{types:["attr-name"],style:{color:"rgb(255, 0, 0)"}},{types:["deleted","string"],style:{color:"rgb(163, 21, 21)"}},{types:["changed","punctuation"],style:{color:"rgb(4, 81, 165)"}},{types:["function","keyword"],style:{color:"rgb(0, 0, 255)"}},{types:["class-name"],style:{color:"rgb(38, 127, 153)"}}]},N7r=j7r,I7r={plain:{color:"#f8fafc",backgroundColor:"#011627"},styles:[{types:["prolog"],style:{color:"#000080"}},{types:["comment"],style:{color:"#6A9955"}},{types:["builtin","changed","keyword","interpolation-punctuation"],style:{color:"#569CD6"}},{types:["number","inserted"],style:{color:"#B5CEA8"}},{types:["constant"],style:{color:"#f8fafc"}},{types:["attr-name","variable"],style:{color:"#9CDCFE"}},{types:["deleted","string","attr-value","template-punctuation"],style:{color:"#cbd5e1"}},{types:["selector"],style:{color:"#D7BA7D"}},{types:["tag"],style:{color:"#0ea5e9"}},{types:["tag"],languages:["markup"],style:{color:"#0ea5e9"}},{types:["punctuation","operator"],style:{color:"#D4D4D4"}},{types:["punctuation"],languages:["markup"],style:{color:"#808080"}},{types:["function"],style:{color:"#7dd3fc"}},{types:["class-name"],style:{color:"#0ea5e9"}},{types:["char"],style:{color:"#D16969"}}]},A7r=I7r,R7r={plain:{color:"#0f172a",backgroundColor:"#f1f5f9"},styles:[{types:["prolog"],style:{color:"#000080"}},{types:["comment"],style:{color:"#6A9955"}},{types:["builtin","changed","keyword","interpolation-punctuation"],style:{color:"#0c4a6e"}},{types:["number","inserted"],style:{color:"#B5CEA8"}},{types:["constant"],style:{color:"#0f172a"}},{types:["attr-name","variable"],style:{color:"#0c4a6e"}},{types:["deleted","string","attr-value","template-punctuation"],style:{color:"#64748b"}},{types:["selector"],style:{color:"#D7BA7D"}},{types:["tag"],style:{color:"#0ea5e9"}},{types:["tag"],languages:["markup"],style:{color:"#0ea5e9"}},{types:["punctuation","operator"],style:{color:"#475569"}},{types:["punctuation"],languages:["markup"],style:{color:"#808080"}},{types:["function"],style:{color:"#0e7490"}},{types:["class-name"],style:{color:"#0ea5e9"}},{types:["char"],style:{color:"#D16969"}}]},P7r=R7r,$7r={plain:{backgroundColor:"hsl(220, 13%, 18%)",color:"hsl(220, 14%, 71%)",textShadow:"0 1px rgba(0, 0, 0, 0.3)"},styles:[{types:["comment","prolog","cdata"],style:{color:"hsl(220, 10%, 40%)"}},{types:["doctype","punctuation","entity"],style:{color:"hsl(220, 14%, 71%)"}},{types:["attr-name","class-name","maybe-class-name","boolean","constant","number","atrule"],style:{color:"hsl(29, 54%, 61%)"}},{types:["keyword"],style:{color:"hsl(286, 60%, 67%)"}},{types:["property","tag","symbol","deleted","important"],style:{color:"hsl(355, 65%, 65%)"}},{types:["selector","string","char","builtin","inserted","regex","attr-value"],style:{color:"hsl(95, 38%, 62%)"}},{types:["variable","operator","function"],style:{color:"hsl(207, 82%, 66%)"}},{types:["url"],style:{color:"hsl(187, 47%, 55%)"}},{types:["deleted"],style:{textDecorationLine:"line-through"}},{types:["inserted"],style:{textDecorationLine:"underline"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["important","bold"],style:{fontWeight:"bold"}},{types:["important"],style:{color:"hsl(220, 14%, 71%)"}}]},M7r=$7r,D7r={plain:{backgroundColor:"hsl(230, 1%, 98%)",color:"hsl(230, 8%, 24%)"},styles:[{types:["comment","prolog","cdata"],style:{color:"hsl(230, 4%, 64%)"}},{types:["doctype","punctuation","entity"],style:{color:"hsl(230, 8%, 24%)"}},{types:["attr-name","class-name","boolean","constant","number","atrule"],style:{color:"hsl(35, 99%, 36%)"}},{types:["keyword"],style:{color:"hsl(301, 63%, 40%)"}},{types:["property","tag","symbol","deleted","important"],style:{color:"hsl(5, 74%, 59%)"}},{types:["selector","string","char","builtin","inserted","regex","attr-value","punctuation"],style:{color:"hsl(119, 34%, 47%)"}},{types:["variable","operator","function"],style:{color:"hsl(221, 87%, 60%)"}},{types:["url"],style:{color:"hsl(198, 99%, 37%)"}},{types:["deleted"],style:{textDecorationLine:"line-through"}},{types:["inserted"],style:{textDecorationLine:"underline"}},{types:["italic"],style:{fontStyle:"italic"}},{types:["important","bold"],style:{fontWeight:"bold"}},{types:["important"],style:{color:"hsl(230, 8%, 24%)"}}]},L7r=D7r,z7r={plain:{color:"#ebdbb2",backgroundColor:"#292828"},styles:[{types:["imports","class-name","maybe-class-name","constant","doctype","builtin","function"],style:{color:"#d8a657"}},{types:["property-access"],style:{color:"#7daea3"}},{types:["tag"],style:{color:"#e78a4e"}},{types:["attr-name","char","url","regex"],style:{color:"#a9b665"}},{types:["attr-value","string"],style:{color:"#89b482"}},{types:["comment","prolog","cdata","operator","inserted"],style:{color:"#a89984"}},{types:["delimiter","boolean","keyword","selector","important","atrule","property","variable","deleted"],style:{color:"#ea6962"}},{types:["entity","number","symbol"],style:{color:"#d3869b"}}]},F7r=z7r,B7r={plain:{color:"#654735",backgroundColor:"#f9f5d7"},styles:[{types:["delimiter","boolean","keyword","selector","important","atrule","property","variable","deleted"],style:{color:"#af2528"}},{types:["imports","class-name","maybe-class-name","constant","doctype","builtin"],style:{color:"#b4730e"}},{types:["string","attr-value"],style:{color:"#477a5b"}},{types:["property-access"],style:{color:"#266b79"}},{types:["function","attr-name","char","url"],style:{color:"#72761e"}},{types:["tag"],style:{color:"#b94c07"}},{types:["comment","prolog","cdata","operator","inserted"],style:{color:"#a89984"}},{types:["entity","number","symbol"],style:{color:"#924f79"}}]},U7r=B7r,q7r=e=>v.useCallback(t=>{var n=t,{className:r,style:s,line:a}=n,i=H3t(n,["className","style","line"]);const l=JZ(dy({},i),{className:Ca("token-line",r)});return typeof e=="object"&&"plain"in e&&(l.style=e.plain),typeof s=="object"&&(l.style=dy(dy({},l.style||{}),s)),l},[e]),V7r=e=>{const t=v.useCallback(({types:n,empty:r})=>{if(e!=null){{if(n.length===1&&n[0]==="plain")return r!=null?{display:"inline-block"}:void 0;if(n.length===1&&r!=null)return e[n[0]]}return Object.assign(r!=null?{display:"inline-block"}:{},...n.map(s=>e[s]))}},[e]);return v.useCallback(n=>{var r=n,{token:s,className:a,style:i}=r,l=H3t(r,["token","className","style"]);const c=JZ(dy({},l),{className:Ca("token",...s.types,a),children:s.content,style:t(s)});return i!=null&&(c.style=dy(dy({},c.style||{}),i)),c},[t])},H7r=/\r\n|\r|\n/,IKe=e=>{e.length===0?e.push({types:["plain"],content:`
571
571
  `,empty:!0}):e.length===1&&e[0].content===""&&(e[0].content=`
572
- `,e[0].empty=!0)},AKe=(e,t)=>{const n=e.length;return n>0&&e[n-1]===t?e:e.concat(t)},W7r=e=>{const t=[[]],n=[e],r=[0],s=[e.length];let a=0,i=0,l=[];const c=[l];for(;i>-1;){for(;(a=r[i]++)<s[i];){let u,d=t[i];const p=n[i][a];if(typeof p=="string"?(d=i>0?d:["plain"],u=p):(d=AKe(d,p.type),p.alias&&(d=AKe(d,p.alias)),u=p.content),typeof u!="string"){i++,t.push(d),n.push(u),r.push(0),s.push(u.length);continue}const h=u.split(H7r),m=h.length;l.push({types:d,content:h[0]});for(let g=1;g<m;g++)IKe(l),c.push(l=[]),l.push({types:d,content:h[g]})}i--,t.pop(),n.pop(),r.pop(),s.pop()}return IKe(l),c},RKe=W7r,Z7r=({prism:e,code:t,grammar:n,language:r})=>v.useMemo(()=>{if(n==null)return RKe([t]);const s={code:t,grammar:n,language:r,tokens:[]};return e.hooks.run("before-tokenize",s),s.tokens=e.tokenize(t,n),e.hooks.run("after-tokenize",s),RKe(s.tokens)},[t,n,r,e]),G7r=(e,t)=>{const{plain:n}=e,r=e.styles.reduce((s,a)=>{const{languages:i,style:l}=a;return i&&!i.includes(t)||a.types.forEach(c=>{const u=dy(dy({},s[c]),l);s[c]=u}),s},{});return r.root=n,r.plain=JZ(dy({},n),{backgroundColor:void 0}),r},Q7r=G7r,Y7r=({children:e,language:t,code:n,theme:r,prism:s})=>{const a=t.toLowerCase(),i=Q7r(r,a),l=q7r(i),c=V7r(i),u=s.languages[a],d=Z7r({prism:s,language:a,code:n,grammar:u});return e({tokens:d,className:`prism-code language-${a}`,style:i!=null?i.root:{},getLineProps:l,getTokenProps:c})},Z3t=e=>v.createElement(Y7r,JZ(dy({},e),{prism:e.prism||Nt,theme:e.theme||W3t,code:e.code,language:e.language}));const K7r=({condition:e,onOpen:t})=>o.jsx("div",{className:"px-3",children:o.jsx(Z3t,{theme:ZTe.oneDark,code:String(e.fnString).trim(),language:"javascript",children:({className:n,style:r,tokens:s,getLineProps:a,getTokenProps:i})=>o.jsx("pre",{className:X("relative font-mono p-3 w-full cursor-pointer rounded-lg text-xs bg-surface4! whitespace-pre-wrap wrap-break-word",n),onClick:t,style:r,children:s.map((l,c)=>o.jsxs("div",{...a({line:l}),children:[o.jsx("span",{className:"text-neutral3 mr-2 inline-block",children:c+1}),l.map((u,d)=>o.jsx("span",{...i({token:u})},d))]},c))})})}),X7r=({open:e,onOpenChange:t,condition:n})=>o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{className:"max-w-[30rem]",children:[o.jsxs(br,{children:[o.jsx(hr,{className:"sr-only",children:"Condition Function"}),o.jsx(Bs,{children:"View the condition function code"})]}),o.jsx(Rr,{children:o.jsx(Fr,{className:"w-full",maxHeight:"400px",children:n&&o.jsx(Z3t,{theme:ZTe.oneDark,code:String(n.fnString).trim(),language:"javascript",children:({className:r,style:s,tokens:a,getLineProps:i,getTokenProps:l})=>o.jsx("pre",{className:`${r} relative mt-2 w-full overflow-x-auto rounded-lg p-3 font-mono text-sm dark:bg-zinc-800`,style:{...s,backgroundColor:"#121212",padding:"0 0.75rem 0 0"},children:a.map((c,u)=>o.jsxs("div",{...i({line:c}),children:[o.jsx("span",{className:"text-neutral3 mr-2 inline-block",children:u+1}),c.map((d,f)=>o.jsx("span",{...l({token:d})},f))]},u))})})})})]})}),J7r=e=>!!e.fnString,eBr=({type:e,conditions:t,previousDisplayStatus:n,isOpen:r,onOpenChange:s,openDialog:a,onOpenDialogChange:i,dialogCondition:l,onConditionClick:c,actionBar:u})=>{const d=(t.some(m=>m.fnString)||t.length>1)&&e!=="else",f=jKe(e),p=f?[f]:[],h=U3t(p);return o.jsxs("div",{"data-workflow-node":!0,"data-workflow-step-status":n??"idle","data-testid":"workflow-condition-node",style:h?{borderLeftColor:h}:void 0,className:X("bg-surface3 rounded-lg w-dropdown-max-height border border-border1",h&&"border-l-4"),children:[o.jsxs(Pf,{open:d?r:!0,onOpenChange:m=>{d&&s(m)},children:[o.jsxs("div",{className:"flex w-full items-center gap-1 px-3 py-2",children:[d&&o.jsx(Fd,{"aria-label":r?"Collapse condition":"Expand condition",className:"text-neutral3 hover:text-neutral5 focus-visible:ring-accent1 inline-flex h-5 w-5 items-center justify-center rounded-full focus-visible:ring-1 focus-visible:outline-hidden",children:o.jsx(qe,{children:o.jsx(ka,{className:X("transition-transform",{"transform rotate-180":r})})})}),o.jsx(Aq,{indicators:p,className:"shrink-0"}),o.jsx("div",{className:"ml-auto flex shrink-0 items-center",children:u})]}),e==="else"?null:o.jsx(Bd,{className:"flex flex-col gap-2 pb-2",children:t.map((m,g)=>{const y=m.conj||e,b=g===0?void 0:jKe(y),x=b?[b]:[];return J7r(m)?o.jsx(K7r,{condition:m,onOpen:()=>c(m)},`condition-code-${g}-${m.fnString}`):o.jsx(v.Fragment,{children:m.ref?.step?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Aq,{indicators:x}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 flex-1",children:[typeof m.ref.step=="string"?m.ref.step:m.ref.step.id,"'s"," ",m.ref.path," ",Object.entries(m.query).map(([S,k])=>`${S} ${String(k)}`)]})]}):null},`condition-ref-${g}-${m.ref?.path??"unknown"}`)})})]}),o.jsx(X7r,{open:a,onOpenChange:i,condition:l})]})},tBr=({startedAt:e,endedAt:t})=>{const[n,r]=v.useState(e);v.useEffect(()=>{const a=setInterval(()=>{r(Date.now())},100);return()=>clearInterval(a)},[e]);const s=t?t-e:n-e;return o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 font-mono whitespace-nowrap",children:[D3t(s,3),"ms"]})},nBr=({displayStatus:e,hasStep:t})=>o.jsxs(qe,{size:"sm",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center",children:[e==="tripwire"&&o.jsx($xe,{className:"text-amber-400",strokeWidth:2}),e==="failed"&&o.jsx(G2,{className:"text-accent2",strokeWidth:2}),e==="success"&&o.jsx(_xe,{className:"text-accent1",strokeWidth:2}),e==="suspended"&&o.jsx(cV,{className:"text-accent3",strokeWidth:2}),e==="waiting"&&o.jsx(ppe,{className:"text-accent5",strokeWidth:2}),e==="running"&&o.jsx(ua,{className:"text-accent6 animate-spin",strokeWidth:2}),!e&&!t&&o.jsx(ZWt,{className:"text-neutral2",strokeWidth:2})]}),rBr=({foreachProgress:e})=>e?o.jsxs("div",{className:"flex items-center gap-2 px-3 pb-2",children:[o.jsx("div",{className:"bg-surface1 h-1.5 flex-1 overflow-hidden rounded-full",children:o.jsx("div",{className:X("h-full rounded-full transition-all duration-300",e.iterationStatus==="failed"?"bg-accent2":"bg-accent1"),style:{width:`${e.totalCount>0?e.completedCount/e.totalCount*100:0}%`}})}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 whitespace-nowrap",children:[e.completedCount," / ",e.totalCount]})]}):null,sBr=({duration:e,date:t})=>o.jsxs(o.Fragment,{children:[e&&o.jsxs(ye,{variant:"ui-sm",className:"text-neutral3 px-3 pb-2",children:["sleeps for ",o.jsxs("strong",{children:[e,"ms"]})]}),t&&o.jsxs(ye,{variant:"ui-sm",className:"text-neutral3 px-3 pb-2",children:["sleeps until ",o.jsx("strong",{children:new Date(t).toLocaleString()})]})]}),aBr=({label:e,description:t,displayStatus:n,hasStep:r,isNestedWorkflowStep:s,stepKey:a,isSelected:i,isWaiting:l,isHovered:c,onHoverChange:u,duration:d,date:f,isForEach:p,foreachProgress:h,mapConfig:m,canSuspend:g,isParallel:y,stepGraph:b,startedAt:x,endedAt:S,actionBar:k})=>{const _=B3t({duration:d,date:f,isForEach:p,mapConfig:m,canSuspend:g,isParallel:y,stepGraph:b}),E=U3t(_);return o.jsxs("div",{"data-workflow-node":!0,"data-workflow-step-key":a,"data-workflow-step-status":n??"idle","data-workflow-step-active":i?"true":void 0,"data-workflow-step-waiting":l?"true":void 0,"data-workflow-step-hovered":c?"true":void 0,"data-testid":s?"workflow-nested-node":"workflow-default-node",onMouseEnter:()=>u?.(!0),onMouseLeave:()=>u?.(!1),style:E?{borderLeftColor:E}:void 0,className:X("bg-surface3 rounded-lg w-[274px] border border-border1 transition-colors hover:border-neutral6",E&&"border-l-4",c&&!i&&"border-neutral6",l&&!i&&"border-accent3",i&&"border-accent1"),children:[o.jsxs("div",{className:X("flex items-center gap-2 px-3 pt-2",!t&&"pb-2"),children:[o.jsx(Aq,{indicators:_,className:"shrink-0"}),o.jsx(nBr,{displayStatus:n,hasStep:r}),o.jsx("div",{className:"min-w-0 flex-1",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral6 block truncate font-medium",title:e,children:e})}),o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-1",children:[x&&o.jsx(tBr,{startedAt:x,endedAt:S}),k]})]}),t&&o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 px-3 pb-2",children:t}),p&&o.jsx(rBr,{foreachProgress:h}),o.jsx(sBr,{duration:d,date:f})]})},cP="text-neutral3 hover:text-neutral6",PKe=e=>{try{return e==null?"{}":JSON.stringify(e,null,2)}catch{return"{}"}},Mae=({label:e,value:t,onChange:n,helperText:r,exampleCode:s})=>{const a=o0(),{handleCopy:i}=Zp({text:t}),{handleCopy:l}=Zp({text:s??"{}"}),[c,u]=v.useState(null),[d,f]=v.useState(!1),[p,h]=v.useState(!1),m=async()=>{if(u(null),!t.trim()){n("{}");return}if(!OD(t)){u("Invalid JSON");return}try{const g=await fj(t);n(g)}catch{u("Unable to format JSON")}};return o.jsxs(o.Fragment,{children:[p&&o.jsxs("div",{className:"border-border1 bg-surface3 space-y-2 rounded-lg border p-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:["Example ",e]}),o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("button",{type:"button",onClick:l,className:cP,"aria-label":"Copy example JSON",children:o.jsx(qe,{children:o.jsx(im,{})})})}),o.jsx(Pn,{children:"Copy example JSON"})]})]}),o.jsx(ed,{value:s,theme:a,extensions:[Dp],className:"bg-surface3 h-[150px] w-full overflow-scroll overflow-y-scroll rounded-lg p-3"})]}),o.jsxs(Pf,{className:"border-border1 bg-surface3 rounded-lg border",open:d,onOpenChange:f,children:[o.jsxs("div",{className:"flex w-full items-center justify-between px-3",children:[o.jsxs("div",{children:[o.jsx(ye,{as:"label",variant:"ui-md",className:"text-neutral3",children:e}),r&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:r})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("button",{type:"button",onClick:m,className:cP,"aria-label":"Format JSON",children:o.jsx(qe,{children:o.jsx(Ry,{})})})}),o.jsx(Pn,{children:"Format JSON"})]}),o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("button",{type:"button",onClick:i,className:cP,"aria-label":"Copy JSON",children:o.jsx(qe,{children:o.jsx(im,{})})})}),o.jsx(Pn,{children:"Copy JSON"})]}),s&&o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("button",{type:"button",onClick:()=>h(!p),className:cP,"aria-label":p?"Hide example JSON":"View example JSON",children:o.jsx(qe,{children:p?o.jsx(RZt,{}):o.jsx(Bu,{})})})}),o.jsx(Pn,{children:"View example JSON"})]}),o.jsx(Fd,{asChild:!0,children:o.jsx("button",{type:"button",className:cP,"aria-label":d?`Collapse ${e}`:`Expand ${e}`,children:o.jsx(qe,{className:X("transition-transform",d?"rotate-0":"-rotate-90"),children:o.jsx(ka,{})})})})]})]}),o.jsxs(Bd,{className:"space-y-2",children:[o.jsx(ed,{value:t,onChange:n,theme:a,extensions:[Dp],className:"bg-surface3 h-[260px] overflow-hidden overflow-y-scroll rounded-lg p-3"}),c&&o.jsx(ye,{variant:"ui-sm",className:"text-accent2",children:c})]})]})]})},Dae=({stepKey:e,closeModal:t,isPerStepRun:n,isContinueRun:r,buttonText:s="Start time travel",inputData:a})=>{const{result:i,workflow:l,timeTravelWorkflowStream:c,runId:u,workflowId:d,setDebugMode:f}=v.useContext(Vl),p=ql(),h=a?{payload:a}:i?.steps?.[e],[m,g]=v.useState(()=>"{}"),[y,b]=v.useState(()=>"{}"),[x,S]=v.useState(()=>"{}"),[k,C]=v.useState(null),[_,E]=v.useState(!1),T=l?.allSteps?.[e],{schema:N}=v.useMemo(()=>{if(!T?.inputSchema)return{schema:yp(dr(),Lj())};try{const A=Ax(T.inputSchema),R=l?.stateSchema?gm(hm(Ax(l.stateSchema))):null,L=gm(hm(A));return{schema:R?Os({inputData:L,initialState:R.optional()}):L,schemaError:null}}catch(A){return console.error("Failed to parse step schema",A),{schema:yp(dr(),Lj())}}},[T?.inputSchema,l?.stateSchema]),I=async A=>{C(null),E(!0);try{const R=m.trim()?JSON.parse(m):{},L=y.trim()?JSON.parse(y):{},D=x.trim()?JSON.parse(x):{},{initialState:z,inputData:H}=A??{},F=l?.stateSchema?H:A,U={runId:u,workflowId:d,step:e,inputData:F,initialState:z,resumeData:Object.keys(R)?.length>0?R:void 0,context:Object.keys(L)?.length>0?L:void 0,nestedStepsContext:Object.keys(D)?.length>0?D:void 0,requestContext:p,...r?{perStep:!1}:{}};r&&f(!1),c(U),t()}catch(R){console.error("Invalid JSON provided",R),C(R instanceof Error?R.message:"Error time traveling workflow")}finally{E(!1)}};return o.jsx(cc,{children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(ye,{as:"p",variant:"ui-lg",className:"text-neutral3",children:"Input data"}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3",children:["Step: ",e]})]}),o.jsx(YB,{schema:N,defaultValues:h?.payload,isSubmitLoading:_,submitButtonLabel:s,onSubmit:I,children:o.jsxs("div",{className:"space-y-4 pb-4",children:[n||r?null:o.jsxs(o.Fragment,{children:[o.jsx(Mae,{label:"Resume Data (JSON)",value:m,onChange:g,helperText:"Provide any resume payloads that should be passed to the step."}),o.jsx(Mae,{label:"Context (JSON)",value:y,onChange:b,helperText:"Only include top level steps (no nested workflow steps) that are required in the time travel execution.",exampleCode:PKe({stepId:{status:"success",payload:{value:"test value"},output:{value:"test output"}}})}),o.jsx(Mae,{label:"Nested Step Context (JSON)",value:x,onChange:S,helperText:"Includes nested workflow steps that are required in the time travel execution.",exampleCode:PKe({nestedWorkflowId:{stepId:{status:"success",payload:{value:"test value"},output:{value:"test output"}}}})})]}),k&&o.jsx(ye,{variant:"ui-sm",className:"text-accent2",children:k})]})})]})})},G3t=({input:e,resumeData:t,output:n,suspendOutput:r,error:s,tripwire:a,mapConfig:i,stepName:l,stepId:c,onShowNestedGraph:u,stepKey:d,stepsFlow:f})=>{const[p,h]=v.useState(!1),[m,g]=v.useState(!1),[y,b]=v.useState(!1),[x,S]=v.useState(!1),[k,C]=v.useState(!1),[_,E]=v.useState(!1),{withoutTimeTravel:T,debugMode:N,result:I,runSnapshot:A,timeTravelWorkflowStream:R,runId:L,workflowId:D,setDebugMode:z}=v.useContext(Vl),{showMapConfig:H,stepDetail:F,closeStepDetail:U}=dW(),q=ql(),M=I?.status??A?.status,G="max-w-4xl w-full",V=!T&&d&&!i&&M!=="running"&&M!=="paused",$=d&&N&&M==="paused",B=v.useMemo(()=>{if(!d||!$)return;const Y=f?.[d]??[];if(Y.length===0)return;if(Y.length>1)return{hasMultiSteps:!0,input:Y.reduce((le,ue)=>(I?.steps?.[ue]?.status==="success"&&(le[ue]=I?.steps?.[ue].output),le),{})};const re=Y[0];if(I?.steps?.[re]?.status==="success")return{hasMultiSteps:!1,input:I?.steps?.[re].output}},[d,f,$,I]),Z=$&&B&&!I?.steps?.[d],K=F?.type==="map-config"&&F?.stepName===l,ne=F?.type==="nested-graph"&&F?.stepName===l,ee=()=>{K?U():H({stepName:l,stepId:c,mapConfig:i})},J=()=>{ne?U():u?.()},ae=Y=>{if(!d||!B)return;const re={runId:L,workflowId:D,step:d,inputData:B?.hasMultiSteps?void 0:B?.input,requestContext:q,...Y?{perStep:!1}:{},...B?.hasMultiSteps?{context:Object.keys(B.input)?.reduce((le,ue)=>(le[ue]={status:"success",output:B.input[ue]},le),{})}:{}};Y&&z(!1),R(re)};return!(s||a||i||t||u||V||Z)?null:o.jsxs(o.Fragment,{children:[o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ce,{size:"icon-sm",variant:"ghost","aria-label":"Step actions",title:"Step actions",className:"nodrag nopan",children:o.jsx(qD,{})})}),o.jsxs(ot.Content,{align:"end",children:[u&&o.jsxs(ot.Item,{onSelect:J,children:[o.jsx(lV,{}),o.jsx("span",{children:ne?"Hide nested graph":"View nested graph"})]}),V&&o.jsxs(ot.Item,{onSelect:()=>S(!0),children:[o.jsx(aZt,{}),o.jsx("span",{children:"Time travel"})]}),Z&&o.jsxs(o.Fragment,{children:[o.jsxs(ot.Item,{onSelect:()=>{i?ae():E(!0)},children:[o.jsx(jf,{}),o.jsx("span",{children:"Run step"})]}),o.jsxs(ot.Item,{onSelect:()=>{i?ae(!0):C(!0)},children:[o.jsx(Xot,{}),o.jsx("span",{children:"Continue run"})]})]}),i&&o.jsxs(ot.Item,{onSelect:ee,children:[o.jsx(Ry,{}),o.jsx("span",{children:K?"Hide map config":"Map config"})]}),t&&o.jsxs(ot.Item,{onSelect:()=>h(!0),children:[o.jsx(Qot,{}),o.jsx("span",{children:"Resume data"})]}),s&&o.jsxs(ot.Item,{onSelect:()=>g(!0),children:[o.jsx(vj,{}),o.jsx("span",{children:"Error"})]}),a&&o.jsxs(ot.Item,{onSelect:()=>b(!0),className:"text-amber-400",children:[o.jsx($xe,{}),o.jsx("span",{children:"Tripwire"})]})]})]}),V&&o.jsx(vr,{open:x,onOpenChange:S,children:o.jsxs(yr,{className:G,children:[o.jsxs(br,{children:[o.jsxs(hr,{children:["Time travel to ",d]}),o.jsx(Bs,{children:"Time travel to a specific workflow step"})]}),o.jsx(Rr,{className:"max-h-[600px]",children:o.jsx(Dae,{stepKey:d,closeModal:()=>S(!1)})})]})}),Z&&!i&&o.jsxs(o.Fragment,{children:[o.jsx(vr,{open:_,onOpenChange:E,children:o.jsxs(yr,{className:G,children:[o.jsxs(br,{children:[o.jsxs(hr,{children:["Run step ",d]}),o.jsx(Bs,{children:"Run a specific workflow step"})]}),o.jsx(Rr,{className:"max-h-[600px]",children:o.jsx(Dae,{stepKey:d,closeModal:()=>E(!1),isPerStepRun:!0,buttonText:"Run step",inputData:B?.input})})]})}),o.jsx(vr,{open:k,onOpenChange:C,children:o.jsxs(yr,{className:G,children:[o.jsxs(br,{children:[o.jsxs(hr,{children:["Continue run ",d]}),o.jsx(Bs,{children:"Continue the workflow run from this step"})]}),o.jsx(Rr,{className:"max-h-[600px]",children:o.jsx(Dae,{stepKey:d,closeModal:()=>C(!1),isContinueRun:!0,buttonText:"Continue run",inputData:B?.input})})]})})]}),t&&o.jsx(vr,{open:p,onOpenChange:h,children:o.jsxs(yr,{className:G,children:[o.jsxs(br,{children:[o.jsxs(hr,{children:[l," resume data"]}),o.jsx(Bs,{children:"View the resume data for this step"})]}),o.jsx(Rr,{children:o.jsx(V2,{data:t})})]})}),s&&o.jsx(vr,{open:m,onOpenChange:g,children:o.jsxs(yr,{className:G,children:[o.jsxs(br,{children:[o.jsxs(hr,{children:[l," error"]}),o.jsx(Bs,{children:"View the error details for this step"})]}),o.jsx(Rr,{children:o.jsx(V2,{data:s})})]})}),a&&o.jsx(vr,{open:y,onOpenChange:b,children:o.jsxs(yr,{className:G,children:[o.jsxs(br,{children:[o.jsxs(hr,{children:[l," tripwire"]}),o.jsx(Bs,{children:"View the tripwire details for this step"})]}),o.jsx(Rr,{children:o.jsx(V2,{data:{reason:a.reason,retry:a.retry,metadata:a.metadata,processorId:a.processorId}})})]})})]})},Q3t=e=>{const t=e?.status==="failed"&&e?.tripwire!==void 0;return{displayStatus:t?"tripwire":e?.status,isTripwire:t}},iBr=({data:e,parentWorkflowName:t,stepsFlow:n})=>{const{steps:r}=G4(),{selectedStepId:s,hoverStepId:a,setHoverStepId:i}=kH(),{showNestedGraph:l}=dW(),c=aOe(),{label:u,stepId:d,description:f}=e,p=e.mapConfig??("step"in e.workflowStep?e.workflowStep.step?.mapConfig:void 0),h=e.stepGraph??("step"in e.workflowStep?e.workflowStep.step?.serializedStepFlow:void 0)??(e.workflowStep.kind==="nested-workflow-step"&&e.workflowStep.flow.type==="workflow"?e.workflowStep.flow.serializedStepFlow:void 0),m=t?`${t}.${u}`:u,g=t?`${t}.${d||u}`:d||u,y=s===g,b=c===g,x=a===g,S=r[g],{displayStatus:k,isTripwire:C}=Q3t(S);return o.jsx(aBr,{label:u,description:f,displayStatus:k,hasStep:!!S,isNestedWorkflowStep:e.workflowStep.kind==="nested-workflow-step",stepKey:g,isSelected:y,isWaiting:b,isHovered:x,onHoverChange:_=>i(_?g:null),duration:e.duration,date:e.date,isForEach:e.isForEach,foreachProgress:S?.foreachProgress,mapConfig:p,canSuspend:e.canSuspend,isParallel:e.isParallel,stepGraph:h,startedAt:S?.startedAt,endedAt:S?.endedAt,actionBar:o.jsx(G3t,{stepName:u,stepId:d,resumeData:S?.resumeData,error:C?void 0:S?.error,tripwire:C?S?.tripwire:void 0,mapConfig:p,onShowNestedGraph:h?()=>l({label:u,fullStep:m,stepGraph:h}):void 0,status:k,stepKey:g,stepsFlow:n})})},oBr=({data:e})=>{const[t,n]=v.useState(!0),[r,s]=v.useState(!1),[a,i]=v.useState(),{steps:l}=G4(),c=e.conditions??[],u=c[0]?.type,d=e.previousStepId?l[e.previousStepId]:void 0,f=e.nextStepId?l[e.nextStepId]:void 0,{displayStatus:p,isTripwire:h}=Q3t(d);return o.jsx(eBr,{type:u,conditions:c,previousDisplayStatus:p,hasPreviousStep:!!d,hasNextStep:!!f,isOpen:t,onOpenChange:n,openDialog:r,onOpenDialogChange:s,dialogCondition:a,onConditionClick:m=>{i(m),s(!0)},actionBar:o.jsx(G3t,{stepName:e.nextStepId??e.label,mapConfig:e.mapConfig,tripwire:h?d?.tripwire:void 0,status:f?p:void 0})})};function lBr({data:e,parentWorkflowName:t,stepsFlow:n}){const r=e.workflowStep.kind==="conditional"?o.jsx(oBr,{data:e}):o.jsx(iBr,{data:e,parentWorkflowName:t,stepsFlow:n});return o.jsxs(o.Fragment,{children:[!e.withoutTopHandle&&o.jsx(j1,{type:"target",position:ar.Top,style:{visibility:"hidden"}}),r,!e.withoutBottomHandle&&o.jsx(j1,{type:"source",position:ar.Bottom,style:{visibility:"hidden"}})]})}const Lae=(e,t)=>e&&t?`${t}.${e}`:e,Y3t=({edges:e,workflowName:t,stepGraph:n})=>{const{steps:r}=G4(),s=v.useContext(Vl),a=t?r[t]?.status==="success":s.result?.status==="success",i=v.useMemo(()=>LOt(e),[e]),l=v.useMemo(()=>{const f=zOt(i),{conditionalStepIds:p}=FOt(n??s.workflow?.stepGraph),h=m=>r[Lae(m,t)??""]?.status==="success";return m=>!!m&&sOe({stepId:m,conditionalStepIds:p,stepSuccessors:f,stepsFlow:i,isStepSuccess:h})},[i,n,s.workflow?.stepGraph,r,t]),c=v.useMemo(()=>({[ig]:f=>o.jsx(lBr,{parentWorkflowName:t,...f,stepsFlow:i}),[QB]:f=>o.jsx(z9r,{...f})}),[i,t]),u=v.useMemo(()=>({[lP]:f=>o.jsx(V9r,{parentWorkflowName:t,...f})}),[t]),d=v.useMemo(()=>e.map(f=>{const p=Lae(f.data?.previousStepId,t),h=Lae(f.data?.nextStepId,t),m=r[p??""]?.status==="success",g=r[h??""]?.status,y=l(f.data?.nextStepId);if(f.data?.boundaryPayload==="workflow-output"){const x=a;return{...f,type:lP,animated:x?!1:f.animated,data:{...f.data,edgeStatus:x?"success":"idle"},style:{...f.style,stroke:x?"#22c55e":"#8e8e8e",strokeDasharray:x?"none":f.style?.strokeDasharray}}}if(f.data?.boundaryPayload==="workflow-input"){const x=!!g&&g!=="skipped";return{...f,type:lP,animated:x?!1:f.animated,data:{...f.data,edgeStatus:x?"success":"idle"},style:{...f.style,stroke:x?"#22c55e":"#8e8e8e",strokeDasharray:x?"none":f.style?.strokeDasharray}}}if(f.data?.conditionNode){const S=!!g&&g!=="skipped"&&!y;return{...f,type:lP,animated:S?!1:f.animated,data:{...f.data,edgeStatus:S?"success":"idle"},style:{...f.style,stroke:S?"#22c55e":"#8e8e8e",strokeDasharray:S?"none":f.style?.strokeDasharray}}}const b=m&&g!=="skipped"&&!y;return{...f,type:lP,animated:b?!1:f.animated,data:{...f.data,edgeStatus:b?"success":"idle"},style:{...f.style,stroke:b?"#22c55e":"#8e8e8e",strokeDasharray:b?"none":f.style?.strokeDasharray}}}),[e,r,t,a,l]);return{edgeTypes:u,nodeTypes:c,stepsFlow:i,styledEdges:d}};function K3t(e,t,n=(r,s)=>r===s){return e.length===t.length&&e.every((r,s)=>n(r,t[s]))}function X3t(e,t){return e-t}function cBr(e,t,n){const r=e.slice();return r[t]=n,r.sort(X3t)}function J3t(e,t,n,r,s,a){let i=e;return i=js(i,n,r),s&&(i=cBr(a,t,js(i,a[t-1]||-1/0,a[t+1]||1/0))),i}function e4t(e,t,n){if(!Array.isArray(e))return!0;const r=e.reduce((s,a,i,l)=>(i===l.length-1||s.push(Math.abs(a-l[i+1])),s),[]);return Math.min(...r)>=t*n}const Q4={activeThumbIndex:()=>null,max:()=>null,min:()=>null,minStepsBetweenValues:()=>null,step:()=>null,values:()=>null,...X1},t4t=v.createContext(void 0);function eG(){const e=v.useContext(t4t);if(e===void 0)throw new Error(kr(62));return e}function uBr(e){return"key"in e?BOn:$k}function dBr(e,t){return typeof e=="number"&&typeof t=="number"?e===t:Array.isArray(e)&&Array.isArray(t)?K3t(e,t):!1}const fBr=v.forwardRef(function(t,n){const{"aria-labelledby":r,className:s,defaultValue:a,disabled:i=!1,id:l,format:c,largeStep:u=10,locale:d,render:f,max:p=100,min:h=0,minStepsBetweenValues:m=0,form:g,name:y,onValueChange:b,onValueCommitted:x,orientation:S="horizontal",step:k=1,thumbCollisionBehavior:C="push",thumbAlignment:_="center",value:E,style:T,...N}=t,I=Vi(l),A=nIn(I),R=wt(b),L=wt(x),{clearErrors:D}=dI(),{state:z,disabled:H,name:F,setTouched:U,setDirty:q,validityData:M,shouldValidateOnChange:G,validation:V}=Em(),{labelId:$}=r0(),[B,Z]=v.useState(),K=r??yH($,B),ne=H||i,ee=F??y,[J,ae]=_f({controlled:E,default:a??h,name:"Slider"}),fe=v.useRef(null),Y=v.useRef(null),re=v.useRef([]),le=v.useRef(null),ue=v.useRef(null),oe=v.useRef(-1),me=v.useRef(null),be=v.useRef(null),xe=v.useRef("none"),Ce=eo(c),[ke,Ne]=v.useState(-1),[$e,de]=v.useState(-1),[te,se]=v.useState(!1),[he,we]=v.useState(()=>new Map),[Te,Re]=v.useState([void 0,void 0]),Ze=wt(tt=>{Ne(tt),tt!==-1&&de(tt)});uI(Y,I,J),qv(J,()=>{D(ee),G()?V.commit(J):V.commit(J,!0);const tt=M.initialValue;let Dt;Array.isArray(J)&&Array.isArray(tt)?Dt=!K3t(J,tt):Dt=J!==tt,q(Dt)});const Ge=wt(tt=>{tt&&(Y.current=tt)}),je=Array.isArray(J),Ee=v.useMemo(()=>je?J.slice().sort(X3t):[js(J,h,p)],[p,h,je,J]),Oe=wt((tt,Dt)=>{if(Number.isNaN(tt)||dBr(tt,J))return;const at=Dt??Yt(Lo,void 0,void 0,{activeThumbIndex:-1});xe.current=at.reason;const gt=at.event,ht=gt.constructor??Event,Ct=new ht(gt.type,gt);Object.defineProperty(Ct,"target",{writable:!0,value:{value:tt,name:ee}}),at.event=Ct,be.current=tt,R(tt,at),!at.isCanceled&&ae(tt)}),Ie=wt((tt,Dt,at)=>{const gt=J3t(tt,Dt,h,p,je,Ee);if(e4t(gt,k,m)){const ht=uBr(at);Oe(gt,Yt(ht,at.nativeEvent,void 0,{activeThumbIndex:Dt})),U(!0);const Ct=be.current??gt;L(Ct,Ck(ht,at.nativeEvent))}});$t(()=>{const tt=kc(pr(fe.current));ne&&mn(fe.current,tt)&&tt.blur()},[ne]),ne&&ke!==-1&&Ze(-1);const Me=v.useMemo(()=>({...z,activeThumbIndex:ke,disabled:ne,dragging:te,orientation:S,max:p,min:h,minStepsBetweenValues:m,step:k,values:Ee}),[z,ke,ne,te,p,h,m,S,k,Ee]),Ue=v.useMemo(()=>({active:ke,controlRef:Y,disabled:ne,dragging:te,validation:V,formatOptionsRef:Ce,handleInputChange:Ie,indicatorPosition:Te,inset:_!=="center",labelId:K,rootLabelId:A,largeStep:u,lastUsedThumbIndex:$e,lastChangedValueRef:be,lastChangeReasonRef:xe,form:g,locale:d,max:p,min:h,minStepsBetweenValues:m,name:ee,onValueCommitted:L,orientation:S,pressedInputRef:le,pressedThumbCenterOffsetRef:ue,pressedThumbIndexRef:oe,pressedValuesRef:me,registerFieldControlRef:Ge,renderBeforeHydration:_==="edge",setActive:Ze,setDragging:se,setIndicatorPosition:Re,setLabelId:Z,setValue:Oe,state:Me,step:k,thumbCollisionBehavior:C,thumbMap:he,thumbRefs:re,values:Ee}),[ke,Y,K,A,ne,te,V,Ce,Ie,Te,u,$e,be,xe,g,d,p,h,m,ee,L,S,le,ue,oe,me,Ge,Ze,se,Re,Z,Oe,Me,k,C,_,he,re,Ee]),Je=Nn("div",t,{state:Me,ref:[n,fe],props:[{"aria-labelledby":K,id:I,role:"group"},V.getValidationProps,N],stateAttributesMapping:Q4});return o.jsx(t4t.Provider,{value:Ue,children:o.jsx(fI,{elementsRef:re,onMapChange:we,children:Je})})}),$Ke=new Map;function pBr(e,t){const n=JSON.stringify({locale:e,options:t}),r=$Ke.get(n);if(r)return r;const s=new Intl.NumberFormat(e,t);return $Ke.set(n,s),s}function g9(e,t,n){return e==null?"":pBr(t,n).format(e)}function n4t(e){const t=e.getBoundingClientRect();return{x:(t.left+t.right)/2,y:(t.top+t.bottom)/2}}function H2(e){if(e===0)return 0;if(Math.abs(e)<1){const n=e.toExponential().split("e-"),r=n[0].split(".")[1];return(r?r.length:0)+parseInt(n[1],10)}const t=e.toString().split(".")[1];return t?t.length:0}function r4t(e,t,n){const r=Math.round((e-n)/t)*t+n;return Number(r.toFixed(Math.max(H2(t),H2(n))))}function MKe({values:e,index:t,nextValue:n,min:r,max:s,step:a,minStepsBetweenValues:i,initialValues:l}){if(e.length===0)return[];const c=e.slice(),u=a*i,d=c.length-1,f=l??e,p=r+t*u,h=s-(d-t)*u;c[t]=js(n,p,h);for(let m=t+1;m<=d;m+=1){const g=c[m-1]+u,y=s-(d-m)*u,b=f[m]??c[m];let x=Math.max(c[m],g);b<x&&(x=Math.max(b,g)),c[m]=js(x,g,y)}for(let m=t-1;m>=0;m-=1){const g=c[m+1]-u,y=r+m*u,b=f[m]??c[m];let x=Math.min(c[m],g);b>x&&(x=Math.min(b,g)),c[m]=js(x,y,g)}for(let m=0;m<=d;m+=1)c[m]=Number(c[m].toFixed(12));return c}function hBr({behavior:e,values:t,currentValues:n,initialValues:r,pressedIndex:s,nextValue:a,min:i,max:l,step:c,minStepsBetweenValues:u}){const d=n??t,f=r??t;if(!(d.length>1))return{value:a,thumbIndex:0,didSwap:!1};const h=c*u;switch(e){case"swap":{const m=d[s],g=1e-7,y=d.slice(),b=y[s-1],x=y[s+1],S=b!=null?b+h:i,k=x!=null?x-h:l,C=js(a,S,k),_=Number(C.toFixed(12));y[s]=_;const E=a>m,T=a<m,N=E&&x!=null&&a>=x-g,I=T&&b!=null&&a<=b+g;if(!N&&!I)return{value:y,thumbIndex:s,didSwap:!1};const A=N?s+1:s-1,R=y.map((H,F)=>{if(F===s)return _;const U=f[F];return U??d[F]});let L=a;N?L=Math.max(a,y[A]):L=Math.min(a,y[A]);const D=MKe({values:y,index:A,nextValue:L,min:i,max:l,step:c,minStepsBetweenValues:u,initialValues:R}),z=N?A-1:A+1;if(z>=0&&z<D.length){const H=D[z-1],F=D[z+1];let U=H!=null?H+h:i;U=Math.max(U,i+z*h);let q=F!=null?F-h:l;q=Math.min(q,l-(D.length-1-z)*h);const M=js(_,U,q);D[z]=Number(M.toFixed(12))}return{value:D,thumbIndex:A,didSwap:!0}}case"push":return{value:MKe({values:d,index:s,nextValue:a,min:i,max:l,step:c,minStepsBetweenValues:u}),thumbIndex:s,didSwap:!1};default:{const m=d.slice(),g=m[s-1],y=m[s+1],b=g!=null?g+h:i,x=y!=null?y-h:l,S=js(a,b,x);return m[s]=Number(S.toFixed(12)),{value:m,thumbIndex:s,didSwap:!1}}}}const mBr=2;function gBr(e,t){if(!e)return{start:0,end:0};function n(a){const i=a!=null?parseFloat(a):0;return Number.isNaN(i)?0:i}const r=t?"Top":"InlineStart",s=t?"Bottom":"InlineEnd";return{start:n(e[`border${r}Width`])+n(e[`padding${r}`]),end:n(e[`border${s}Width`])+n(e[`padding${s}`])}}function OF(e,t){if(t.current!=null&&e.changedTouches){const n=e;for(let r=0;r<n.changedTouches.length;r+=1){const s=n.changedTouches[r];if(s.identifier===t.current)return{x:s.clientX,y:s.clientY}}return null}return{x:e.clientX,y:e.clientY}}const vBr=v.forwardRef(function(t,n){const{render:r,className:s,style:a,...i}=t,{disabled:l,dragging:c,inset:u,lastChangedValueRef:d,lastChangeReasonRef:f,max:p,min:h,minStepsBetweenValues:m,onValueCommitted:g,orientation:y,pressedInputRef:b,pressedThumbCenterOffsetRef:x,pressedThumbIndexRef:S,pressedValuesRef:k,registerFieldControlRef:C,renderBeforeHydration:_,setActive:E,setDragging:T,setValue:N,state:I,step:A,thumbCollisionBehavior:R,thumbRefs:L,values:D}=eG(),z=Ly(),H=D.length>1,F=y==="vertical",U=v.useRef(null),q=v.useRef(null),M=wt(ue=>{ue&&q.current==null&&(q.current=ta(ue).getComputedStyle(ue))}),G=v.useRef(null),V=v.useRef(0),$=v.useRef(0),B=eo(D);function Z(ue){S.current!==ue&&(S.current=ue);const oe=L.current[ue];if(!oe){x.current=null,b.current=null;return}b.current=oe.querySelector('input[type="range"]')}function K(ue){const oe=U.current;if(!oe)return null;const{width:me,height:be,bottom:xe,left:Ce,right:ke}=oe.getBoundingClientRect(),Ne=gBr(q.current,F),$e=$.current,de=(F?be:me)-Ne.start-Ne.end-$e*2,te=x.current??0,se=ue.x-te,he=ue.y-te,we=F?xe-he-Ne.end:(z==="rtl"?ke-se:se-Ce)-Ne.start,Te=js((we-$e)/de,0,1);let Re=(p-h)*Te+h;if(Re=r4t(Re,A,h),Re=js(Re,h,p),!H)return{value:Re,thumbIndex:0,didSwap:!1};const Ze=S.current;if(Ze<0)return null;const Ge=hBr({behavior:R,values:D,currentValues:B.current??D,initialValues:k.current,pressedIndex:Ze,nextValue:Re,min:h,max:p,step:A,minStepsBetweenValues:m});return R==="swap"&&Ge.didSwap?Z(Ge.thumbIndex):S.current=Ge.thumbIndex,Ge}function ne(ue){k.current=H?D.slice():null,B.current=D;const oe=S.current;let me=oe;if(oe>-1&&oe<D.length){if(D[oe]===p){let be=oe;for(;be>0&&D[be-1]===p;)be-=1;me=be}}else{const be=F?"y":"x";let xe;me=-1;for(let Ce=0;Ce<L.current.length;Ce+=1){const ke=L.current[Ce];if(Er(ke)){const Ne=n4t(ke),$e=Math.abs(ue[be]-Ne[be]);(xe===void 0||$e<=xe)&&(me=Ce,xe=$e)}}}if(me>-1&&me!==oe&&Z(me),u){const be=L.current[me];if(Er(be)){const xe=be.getBoundingClientRect(),Ce=F?"height":"width";$.current=xe[Ce]/2}}}function ee(ue){const oe=L.current?.[ue]?.querySelector('input[type="range"]');oe&&oe.focus({preventScroll:!0,focusVisible:!1})}const J=wt(ue=>{const oe=OF(ue,G);if(oe==null)return;if(V.current+=1,ue.type==="pointermove"&&ue.buttons===0){ae(ue);return}const me=K(oe);me!=null&&e4t(me.value,A,m)&&(!c&&V.current>mBr&&T(!0),N(me.value,Yt(UOn,ue,void 0,{activeThumbIndex:me.thumbIndex})),B.current=Array.isArray(me.value)?me.value:[me.value],me.didSwap&&ee(me.thumbIndex))});function ae(ue){E(-1),T(!1),b.current=null,x.current=null;const oe=OF(ue,G),me=oe!=null?K(oe):null;if(me!=null){const be=f.current;g(d.current??me.value,Ck(be,ue))}"pointerType"in ue&&U.current?.hasPointerCapture(ue.pointerId)&&U.current?.releasePointerCapture(ue.pointerId),S.current=-1,G.current=null,k.current=null,Y()}const fe=wt(ue=>{if(l)return;const oe=ue.changedTouches[0];oe!=null&&(G.current=oe.identifier);const me=OF(ue,G);if(me!=null){ne(me);const xe=K(me);if(xe==null)return;ee(xe.thumbIndex),N(xe.value,Yt(l5e,ue,void 0,{activeThumbIndex:xe.thumbIndex})),B.current=Array.isArray(xe.value)?xe.value:[xe.value],xe.didSwap&&ee(xe.thumbIndex)}V.current=0;const be=pr(U.current);be.addEventListener("touchmove",J,{passive:!0}),be.addEventListener("touchend",ae,{passive:!0})}),Y=wt(()=>{const ue=pr(U.current);ue.removeEventListener("pointermove",J),ue.removeEventListener("pointerup",ae),ue.removeEventListener("touchmove",J),ue.removeEventListener("touchend",ae),k.current=null}),re=m1();return v.useEffect(()=>{const ue=U.current;if(!ue)return()=>Y();const oe=Vr(ue,"touchstart",fe,{passive:!0});return()=>{oe(),re.cancel(),Y()}},[Y,fe,U,re]),v.useEffect(()=>{l&&Y()},[l,Y]),Nn("div",t,{state:I,ref:[n,C,U,M],props:[{"data-base-ui-slider-control":_?"":void 0,onPointerDown(ue){const oe=U.current,me=Ei(ue.nativeEvent);if(!oe||l||ue.defaultPrevented||!Er(me)||ue.button!==0)return;const be=OF(ue,G);if(be!=null){ne(be);const Ce=K(be);if(Ce==null)return;mn(L.current[Ce.thumbIndex],kc(pr(oe)))?ue.preventDefault():re.request(()=>{ee(Ce.thumbIndex)}),T(!0),x.current!=null||(N(Ce.value,Yt(l5e,ue.nativeEvent,void 0,{activeThumbIndex:Ce.thumbIndex})),B.current=Array.isArray(Ce.value)?Ce.value:[Ce.value],Ce.didSwap&&ee(Ce.thumbIndex))}ue.nativeEvent.pointerId&&oe.setPointerCapture(ue.nativeEvent.pointerId),V.current=0;const xe=pr(U.current);xe.addEventListener("pointermove",J,{passive:!0}),xe.addEventListener("pointerup",ae,{once:!0})}},i],stateAttributesMapping:Q4})}),yBr=v.forwardRef(function(t,n){const{render:r,className:s,style:a,...i}=t,{state:l}=eG();return Nn("div",t,{state:l,ref:n,props:[{style:{position:"relative"}},i],stateAttributesMapping:Q4})});function Cbe(e,t,n){return(e-t)*100/(n-t)}let bBr=(function(e){return e.index="data-index",e.dragging="data-dragging",e.orientation="data-orientation",e.disabled="data-disabled",e.valid="data-valid",e.invalid="data-invalid",e.touched="data-touched",e.dirty="data-dirty",e.focused="data-focused",e})({});const xBr='!function(){const t=document.currentScript?.parentElement;if(!t)return;const e=t.closest("[data-base-ui-slider-control]");if(!e)return;const r=e.querySelector("[data-base-ui-slider-indicator]"),i=e.getBoundingClientRect(),n="vertical"===e.getAttribute("data-orientation")?"height":"width",o=e.querySelectorAll(\'input[type="range"]\'),l=o.length>1,s=o.length-1;let a=null,u=null;for(let t=0;t<o.length;t+=1){const e=o[t],y=parseFloat(e.getAttribute("value")??"");if(Number.isNaN(y))return;const c=e.parentElement;if(!c)return;const p=parseFloat(e.getAttribute("max")??"100"),g=parseFloat(e.getAttribute("min")??"0"),b=c?.getBoundingClientRect(),d=i[n]-b[n],m=100*(y-g)/(p-g),v=(b[n]/2+d*m/100)/i[n]*100;c.style.setProperty("--position",`${v}%`),Number.isFinite(v)&&(c.style.removeProperty("visibility"),r&&(0===t?(a=v,r.style.setProperty("--start-position",`${v}%`),l||r.style.removeProperty("visibility")):t===s&&(u=v-(a??0),r.style.setProperty("--end-position",`${v}%`),r.style.setProperty("--relative-size",`${u}%`),r.style.removeProperty("visibility"))))}}();',wBr=new Set([...J1,vyt,yyt]);function SBr(e,t,n,r){if(!(t<0))return e.length===2?t===0?`${g9(e[t],r,n)} start range`:`${g9(e[t],r,n)} end range`:n?g9(e[t],r,n):void 0}function IE(e,t,n,r,s){const a=n===1?e+t:e-t,i=Number(a.toFixed(Math.max(H2(e),H2(t),H2(r))));return js(i,r,s)}const kBr=v.forwardRef(function(t,n){const{render:r,children:s,className:a,"aria-describedby":i,"aria-label":l,"aria-labelledby":c,disabled:u=!1,getAriaLabel:d,getAriaValueText:f,id:p,index:h,inputRef:m,onBlur:g,onFocus:y,onKeyDown:b,tabIndex:x,style:S,...k}=t,{nonce:C}=SH(),_=Vi(p),{active:E,lastUsedThumbIndex:T,controlRef:N,disabled:I,validation:A,formatOptionsRef:R,handleInputChange:L,inset:D,labelId:z,largeStep:H,locale:F,max:U,min:q,minStepsBetweenValues:M,form:G,name:V,orientation:$,pressedInputRef:B,pressedThumbCenterOffsetRef:Z,pressedThumbIndexRef:K,renderBeforeHydration:ne,setActive:ee,setIndicatorPosition:J,state:ae,step:fe,values:Y}=eG(),re=Ly(),le=u||I,ue=Y.length>1,oe=$==="vertical",me=re==="rtl",{setTouched:be,setFocused:xe,validationMode:Ce}=Em(),ke=v.useRef(null),Ne=v.useRef(null),$e=v.useRef(!1),de=Vi(),te=W_(),se=ue?de:te,he=v.useMemo(()=>({inputId:se}),[se]),{ref:we,index:Te}=s0({metadata:he}),Re=ue?h??Te:0,Ze=Re===Y.length-1,Ge=Y[Re],je=Cbe(Ge,q,U),[Ee,Oe]=v.useState(),Ie=CCe(),Me=T>=0&&T<Y.length?T:-1,Ue=wt(()=>{const ct=N.current,pt=ke.current;if(!ct||!pt)return;const Zt=pt.getBoundingClientRect(),Gt=ct.getBoundingClientRect(),xn=oe?"height":"width",Ae=Gt[xn]-Zt[xn],Le=(Zt[xn]/2+Ae*je/100)/Gt[xn]*100,et=Number.isFinite(Le)?Le:void 0;Oe(et),Re===0?J(rt=>[et,rt[1]]):Ze&&J(rt=>[rt[0],et])});$t(()=>{D&&queueMicrotask(Ue)},[Ue,D]),$t(()=>{D&&Ue()},[Ue,D,je]),$t(()=>{if(!D)return;const ct=N.current,pt=ke.current;if(!ct||!pt)return;const Zt=ta(ct).ResizeObserver;if(typeof Zt!="function")return;const Gt=new Zt(Ue);return Gt.observe(ct),Gt.observe(pt),()=>{Gt.disconnect()}},[N,Ue,D]);const Je=oe?"bottom":"insetInlineStart",tt=oe?"left":"top";let Dt;ue?E===Re?Dt=2:Me===Re&&(Dt=1):E===Re&&(Dt=1);let at;D?at={"--position":`${Ee??0}%`,visibility:ne&&Ie||Ee===void 0?"hidden":void 0,position:"absolute",[Je]:"var(--position)",[tt]:"50%",translate:`${(oe||!me?-1:1)*50}% ${(oe?1:-1)*50}%`,zIndex:Dt}:at=Number.isFinite(je)?{position:"absolute",[Je]:`${je}%`,[tt]:"50%",translate:`${(oe||!me?-1:1)*50}% ${(oe?1:-1)*50}%`,zIndex:Dt}:g1;let gt;$==="vertical"&&(gt=me?"vertical-rl":"vertical-lr");const ht=typeof d=="function"?d(Re):l,Ct=Bo({"aria-label":ht,"aria-labelledby":c??(ht==null?z:void 0),"aria-describedby":i,"aria-orientation":$,"aria-valuenow":Ge,"aria-valuetext":typeof f=="function"?f(g9(Ge,F,R.current??void 0),Ge,Re):SBr(Y,Re,R.current??void 0,F),disabled:le,form:G,id:se,max:U,min:q,name:V,onChange(ct){L(ct.currentTarget.valueAsNumber,Re,ct)},onFocus(ct){const pt=$e.current;$e.current=!1,ee(Re),xe(!0),pt&&ct.stopPropagation()},onBlur(ct){if($e.current){ct.stopPropagation();return}ke.current&&(ee(-1),be(!0),xe(!1),Ce==="onBlur"&&A.commit(J3t(Ge,Re,q,U,ue,Y)))},onKeyDown(ct){if(!wBr.has(ct.key))return;J1.has(ct.key)&&ct.stopPropagation();let pt=null;const Zt=r4t(Ge,fe,q);switch(ct.key){case zT:pt=IE(Zt,ct.shiftKey?H:fe,1,q,U);break;case FT:pt=IE(Zt,ct.shiftKey?H:fe,me?-1:1,q,U);break;case Dk:pt=IE(Zt,ct.shiftKey?H:fe,-1,q,U);break;case q$:pt=IE(Zt,ct.shiftKey?H:fe,me?1:-1,q,U);break;case vyt:pt=IE(Zt,H,1,q,U);break;case yyt:pt=IE(Zt,H,-1,q,U);break;case j3:pt=U,ue&&(pt=Number.isFinite(Y[Re+1])?Y[Re+1]-fe*M:U);break;case T3:pt=q,ue&&(pt=Number.isFinite(Y[Re-1])?Y[Re-1]+fe*M:q);break}if(pt!==null){const Gt=ct.currentTarget;Umt(Gt)||($e.current=!0,Gt.blur(),Gt.focus({preventScroll:!0,focusVisible:!0})),L(pt,Re,ct),ct.preventDefault()}},step:fe,style:{...g1,width:"100%",height:"100%",writingMode:gt},tabIndex:x??void 0,type:"range",value:Ge??""},A.getInputValidationProps),tn=Yu(Ne,A.inputRef,m);return Nn("div",t,{state:ae,ref:[n,we,ke],props:[{[bBr.index]:Re,children:o.jsxs(v.Fragment,{children:[s,o.jsx("input",{ref:tn,...Ct,suppressHydrationWarning:!0}),D&&Ie&&ne&&Ze&&o.jsx("script",{nonce:C,dangerouslySetInnerHTML:{__html:xBr},suppressHydrationWarning:!0})]}),id:_,onBlur:g,onFocus:y,onPointerDown(ct){if(K.current=Re,ke.current!=null){const pt=$==="horizontal"?"x":"y",Zt=n4t(ke.current),Gt=($==="horizontal"?ct.clientX:ct.clientY)-Zt[pt];Z.current=Gt}Ne.current!=null&&B.current!==Ne.current&&(B.current=Ne.current)},style:at,suppressHydrationWarning:ne||void 0},k],stateAttributesMapping:Q4})});function OBr(e,t,n,r,s,a){const i=n===void 0||t&&r===void 0?"hidden":void 0,l=e?"bottom":"insetInlineStart",c=e?"height":"width",d={visibility:s&&a?"hidden":i,position:e?"absolute":"relative",[e?"width":"height"]:"inherit"};return d["--start-position"]=`${n??0}%`,t?(d["--relative-size"]=`${(r??0)-(n??0)}%`,d[l]="var(--start-position)",d[c]="var(--relative-size)",d):(d[l]=0,d[c]="var(--start-position)",d)}function _Br(e,t,n,r){const s=e?"bottom":"insetInlineStart",a=e?"height":"width",l={position:e?"absolute":"relative",[e?"width":"height"]:"inherit"};if(!t)return l[s]=0,l[a]=`${n}%`,l;const c=r-n;return l[s]=`${n}%`,l[a]=`${c}%`,l}const CBr=v.forwardRef(function(t,n){const{render:r,className:s,style:a,...i}=t,{indicatorPosition:l,inset:c,max:u,min:d,orientation:f,renderBeforeHydration:p,state:h,values:m}=eG(),g=CCe(),y=f==="vertical",b=m.length>1,x=c?OBr(y,b,l[0],l[1],p,g):_Br(y,b,Cbe(m[0],d,u),Cbe(m[m.length-1],d,u));return Nn("div",t,{state:h,ref:n,props:[{"data-base-ui-slider-indicator":p?"":void 0,style:x,suppressHydrationWarning:p||void 0},i],stateAttributesMapping:Q4})});function DKe(e){return typeof e=="number"?[e]:[...e]}const Ebe=({className:e,defaultValue:t,value:n,min:r=0,max:s=100,onValueChange:a,onValueCommitted:i,...l})=>{const c=Array.isArray(n)?n:Array.isArray(t)?t:[r];return o.jsx(fBr,{className:X("w-full",e),defaultValue:t,value:n,min:r,max:s,thumbAlignment:"edge",onValueChange:a?(u,d)=>a(DKe(u),d):void 0,onValueCommitted:i?(u,d)=>i(DKe(u),d):void 0,...l,children:o.jsxs(vBr,{className:X("group relative flex w-full cursor-pointer touch-none items-center select-none","data-[orientation=horizontal]:py-3","data-[orientation=vertical]:h-full data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col data-[orientation=vertical]:px-3","data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50"),children:[o.jsx(yBr,{className:X("relative grow overflow-hidden rounded-full bg-neutral6/20 select-none","data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full","data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"),children:o.jsx(CBr,{className:X("bg-neutral6 select-none","data-[orientation=horizontal]:h-full","data-[orientation=vertical]:w-full")})}),c.map((u,d)=>o.jsx(kBr,{index:d,className:X("relative block h-5 w-2.5 shrink-0 rounded-full border-2 border-neutral6 bg-neutral2 outline-hidden select-none",'after:absolute after:-inset-2 after:content-[""]',"duration-normal transition-shadow","hover:ring-2 hover:ring-neutral6/30","has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-neutral6/60","data-[orientation=vertical]:h-2.5 data-[orientation=vertical]:w-5","data-[disabled]:pointer-events-none")},d))]})})},GTe=v.forwardRef(({className:e,...t},n)=>{const{zoom:r}=AXn(),{zoomTo:s,zoomIn:a,zoomOut:i,fitView:l}=e4();return o.jsxs(J3,{ref:n,className:X("flex items-center gap-1 rounded-full border border-border1 bg-surface2 p-1 text-neutral6",e),...t,children:[o.jsx(ce,{size:"icon-sm",tooltip:"Zoom out",onClick:()=>i({duration:300}),children:o.jsx(rQt,{})}),o.jsx(Ebe,{className:"w-[140px]",value:[r],min:.01,max:1,step:.01,onValueChange:c=>{s(c[0])}}),o.jsx(ce,{size:"icon-sm",tooltip:"Zoom in",onClick:()=>a({duration:300}),children:o.jsx(Wr,{})}),o.jsxs(ce,{size:"sm",className:"min-w-16 tabular-nums",onClick:()=>s(1,{duration:300}),children:[(100*r).toFixed(0),"%"]}),o.jsx(ce,{size:"icon-sm",tooltip:"Fit view",onClick:()=>l({duration:300,maxZoom:1}),children:o.jsx(VGt,{})})]})});GTe.displayName="ZoomSlider";function EBr({workflow:e}){const{nodes:t,edges:n}=rOe(e),[r,s,a]=IOt(t),[i]=AOt(n),{edgeTypes:l,nodeTypes:c,styledEdges:u}=Y3t({edges:i}),d=v.useRef(null),{selectedStepId:f}=kH(),p=aOe(),h=fJn(),{getNodes:m,setCenter:g}=e4(),y=f??p??h,b=v.useEffectEvent(x=>{const S=cJn(m(),x);if(!S)return;d.current?.focus({preventScroll:!0});const k=S.measured?.width??S.width??274,C=S.measured?.height??S.height??100;g(S.position.x+k/2,S.position.y+C/2,{duration:300,zoom:1})});return v.useEffect(()=>{y&&b(y)},[y,r]),o.jsx("div",{ref:d,tabIndex:-1,"data-testid":"workflow-graph-viewport",className:"bg-surface2 h-full w-full outline-none",children:o.jsxs(NOt,{nodes:r,edges:u,edgeTypes:l,nodeTypes:c,onNodesChange:a,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,children:[o.jsx(GTe,{position:"bottom-left"}),o.jsx(POt,{variant:ly.Dots,gap:12,size:.5})]})})}function s4t({workflowId:e,workflow:t,isLoading:n}){const{snapshot:r}=v.useContext(Vl);return n?o.jsx("div",{className:"p-4",children:o.jsx(kt,{className:"h-full"})}):t?o.jsx(nOe,{children:o.jsx(EBr,{workflow:r?.serializedStepGraph?{stepGraph:r?.serializedStepGraph}:t})}):o.jsx("div",{className:"grid h-full place-items-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx(vj,{}),o.jsxs("div",{children:["We couldn't find ",L9r(e)," workflow."]})]})})}function Qh(e,t){return e.length<=t?e:e.slice(0,t)+"…"}const TBr=5e3,jBr={};function NBr(e){return e instanceof Tx&&e.status===404}function IBr(e){return NBr(e)?!1:TBr}const ABr=()=>{const e=We(),{requestContext:t}=hs(),{data:n}=yt({queryKey:["workflow-run-counts",t],queryFn:()=>e.listWorkflowRunCounts(t),retry:!1,refetchInterval:r=>IBr(r.state.error)});return n??jBr};function RBr(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function PBr(e){const t=new Map;for(const[n,r]of Object.entries(e))t.set(n,n),r.name&&t.set(r.name,n);return t}function $Br(e,t,n){const r=PBr(t),s=[],a=(i,l,c,u,d,f)=>{const p=RBr(i).filter(g=>{const y=r.get(g);return y===void 0||!u.has(y)});if(s.push({kind:"workflow",workflow:i,pathKey:l,depth:c,nestedIds:p,guides:d,isLastChild:f}),!n.has(l)||p.length===0)return;const h=new Set(u).add(i.id),m=c===0?[]:[...d,!f];for(const[g,y]of p.entries()){const b=g===p.length-1,x=r.get(y);if(x===void 0){s.push({kind:"inline",stepId:y,description:i.allSteps?.[y]?.description,pathKey:`${l}/${y}`,depth:c+1,guides:m,isLastChild:b});continue}a({...t[x],id:x},`${l}/${x}`,c+1,h,m,b)}};for(const i of e)a(i,i.id,0,new Set([i.id]),[],!1);return s}const LKe="auto 24rem minmax(0, 1fr) auto auto auto";function zKe({guides:e,isLastChild:t}){return o.jsxs("span",{"aria-hidden":!0,className:"-my-6 flex shrink-0 self-stretch",children:[e.map((n,r)=>o.jsx("span",{className:X("w-6",n&&"border-l border-border1")},r)),o.jsxs("span",{className:"relative w-6",children:[o.jsx("span",{className:X("absolute left-0 top-0 border-l border-border1",t?"h-1/2":"h-full")}),o.jsx("span",{className:"border-border1 absolute top-1/2 left-0 w-3.5 border-b"})]})]})}function FKe({row:e,isExpanded:t,onToggle:n}){const r=e.kind==="workflow"&&e.nestedIds.length>0,s=e.kind==="workflow"?e.workflow.name:e.stepId;return o.jsx("div",{className:"flex items-center pl-5",children:r?o.jsx("button",{type:"button","aria-expanded":t,"aria-label":`${t?"Collapse":"Expand"} nested workflows of ${s}`,className:"text-neutral4 hover:text-neutral2 relative grid size-5 shrink-0 place-items-center before:absolute before:-inset-1.5 before:content-['']",onClick:n,children:o.jsx(aa,{className:X("size-4 transition-transform",t&&"rotate-90")})}):o.jsx("span",{className:"size-5 shrink-0","aria-hidden":!0})})}function MBr({workflows:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=bn(),[a,i]=v.useState(new Set),l=v.useMemo(()=>Object.keys(e).map(p=>({...e[p],id:p})),[e]),c=v.useMemo(()=>{const p=n.toLowerCase();return l.filter(h=>h.name?.toLowerCase().includes(p)||h.description?.toLowerCase().includes(p))},[l,n]),u=v.useMemo(()=>$Br(c,e,a),[c,e,a]),d=ABr(),f=p=>{i(h=>{const m=new Set(h);return m.has(p)?m.delete(p):m.add(p),m})};return t?o.jsx(ll,{columns:LKe,fit:"container"}):o.jsxs(ge,{columns:LKe,fit:"container",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:o.jsx("span",{className:"sr-only",children:"Expand"})}),o.jsx(ge.TopCell,{children:"Name"}),o.jsx(ge.TopCell,{children:"Description"}),o.jsx(ge.TopCell,{children:"Running"}),o.jsx(ge.TopCell,{children:"Pending input"}),o.jsx(ge.TopCell,{children:"Number of steps"})]}),u.length===0&&n?o.jsx(ge.NoMatch,{message:"No Workflows match your search"}):null,u.map(p=>{const h=a.has(p.pathKey),m=()=>f(p.pathKey);if(p.kind==="inline")return o.jsxs(ge.RowWrapper,{children:[o.jsx(FKe,{row:p,isExpanded:h,onToggle:m}),o.jsxs("div",{className:"col-span-5 col-start-2 grid grid-cols-subgrid gap-8 px-5",children:[o.jsx(ge.NameCell,{children:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(zKe,{guides:p.guides,isLastChild:p.isLastChild}),o.jsx("span",{className:"truncate",children:Qh(p.stepId,50)}),o.jsx("span",{title:"Nested workflow not registered standalone",className:"text-ui-smd text-neutral4 shrink-0",children:"inline"})]})}),o.jsx(ge.DescriptionCell,{children:Qh(p.description??"",200)}),o.jsx(ge.TextCell,{className:"text-center",children:""}),o.jsx(ge.TextCell,{className:"text-center",children:""}),o.jsx(ge.TextCell,{className:"text-center",children:""})]})]},`workflow-${p.pathKey}`);const{workflow:g,pathKey:y,nestedIds:b}=p,x=Qh(g.name,50),S=Qh(g.description??"",200),k=Object.keys(g.steps??{}).length,C=d[g.id]?.running??0,_=d[g.id]?.suspended??0,E=b.length>0;return o.jsxs(ge.RowWrapper,{children:[o.jsx(FKe,{row:p,isExpanded:h,onToggle:m}),o.jsxs(ge.RowLink,{colStart:2,to:r.workflowLink(g.id),LinkComponent:s,children:[o.jsx(ge.NameCell,{children:o.jsxs("span",{className:"flex items-center gap-1.5",children:[p.depth>0?o.jsx(zKe,{guides:p.guides,isLastChild:p.isLastChild}):null,o.jsx("span",{className:"truncate",children:x}),g.origin==="stored"?o.jsx(on,{size:"xs",variant:"info",title:"Registered via the stored-workflows API",children:"Stored"}):null,E?o.jsxs("span",{title:`Nested workflows: ${b.join(", ")}`,className:"text-ui-smd text-neutral4 inline-flex shrink-0 items-center gap-1",children:[o.jsx(XN,{"aria-hidden":!0,className:"size-3.5"}),b.length]}):null]})}),o.jsx(ge.DescriptionCell,{children:S}),o.jsx(ge.TextCell,{className:"text-center",children:C>0?o.jsxs("span",{className:"text-positive1 inline-flex items-center gap-1.5","aria-label":`${C} run${C===1?"":"s"} in progress`,children:[o.jsx("span",{"aria-hidden":!0,className:"bg-positive1 size-2 rounded-full motion-safe:animate-pulse"}),C]}):""}),o.jsx(ge.TextCell,{className:"text-center",children:_>0?o.jsxs("span",{className:"text-warning1 inline-flex items-center gap-1.5","aria-label":`${_} run${_===1?"":"s"} awaiting input`,children:[o.jsx(cV,{"aria-hidden":!0,className:"size-3.5"}),_]}):""}),o.jsx(ge.TextCell,{className:"text-center",children:k||""})]})]},`workflow-${y}`)})]})}const DBr=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx($f,{}),titleSlot:"No Workflows yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra workflows are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/workflows/overview",target:"_blank",rel:"noopener noreferrer",children:["Workflows Documentation ",o.jsx(_a,{})]})})});function LBr({value:e,onValueChange:t,placeholder:n="Select a workflow...",searchPlaceholder:r="Search workflows...",emptyText:s="No workflows found.",className:a,disabled:i=!1,variant:l}){const{data:c={},isLoading:u,isError:d,error:f}=Ky(),{navigate:p,paths:h}=bn();v.useEffect(()=>{if(d){const y=f instanceof Error?f.message:"Failed to load workflows";De.error(`Error loading workflows: ${y}`)}},[d,f]);const m=Object.keys(c).map(y=>({label:c[y]?.name||y,value:y})),g=y=>{t?t(y):y&&y!==e&&p(h.workflowLink(y))};return o.jsx(Fl,{options:m,value:e,onValueChange:g,placeholder:u?"Loading workflows...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||d,variant:l})}const zBr=({result:e,workflowId:t,isStreaming:n,metadata:r,toolCallId:s,toolApprovalMetadata:a,suspendPayload:i,toolName:l,isNetwork:c,toolCalled:u})=>{const{runId:d,status:f}=e||{},{data:p,isLoading:h}=n4(t),{data:m,isLoading:g}=d_t(t,{enabled:!!d&&!n}),y=m?.find(T=>T.runId===d),b=g||!y,x=typeof y?.snapshot=="object"?y?.snapshot:void 0,S=r?.mode==="network"?r.routingDecision:void 0,k=r?.mode==="network"?S?.selectionReason??r.selectionReason:void 0,C=r?.mode==="network"?S??r.agentInput:void 0,_=(r?.mode==="stream"||r?.mode==="generate")&&r?.backgroundTasks?r.backgroundTasks[s]:void 0;let E=typeof i=="string"?o.jsx("pre",{className:"bg-surface4 overflow-x-auto rounded-md p-4 whitespace-pre",children:i}):o.jsx(Hr,{data:i,"data-testid":"tool-suspend-payload"});return h||!p?o.jsx(HTe,{}):o.jsxs(Z4,{"data-testid":"workflow-badge",icon:o.jsx(rd,{className:"text-accent3"}),title:p.name,initialCollapsed:!1,extraInfo:r?.mode==="network"?o.jsx(VTe,{selectionReason:k??"",input:C}):_?.taskId&&_?.startedAt?o.jsx(qTe,{backgroundTask:_}):null,children:[!n&&!b&&o.jsx(xOe,{snapshot:x,workflowId:t,initialRunId:d,withoutTimeTravel:!0,children:o.jsx(BKe,{workflowId:t,workflow:p,runId:d})}),n&&o.jsx(BKe,{workflowId:t,workflow:p,runId:d}),E!==void 0&&i&&o.jsxs("div",{children:[o.jsx("p",{className:"pb-2 font-medium",children:"Workflow suspend payload"}),E]}),o.jsx(KI,{toolCalled:u??!!f,toolCallId:s,toolApprovalMetadata:a,toolName:l,isNetwork:c,isGenerateMode:r?.mode==="generate"})]})},BKe=({workflowId:e,workflow:t,runId:n})=>{const{Link:r}=bn();return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[o.jsx(ce,{as:r,href:`/workflows/${e}/graph`,children:"Go to workflow"}),n&&o.jsx(ce,{as:r,href:`/workflows/${e}/graph/${n}`,children:"See run"})]}),o.jsx("div",{className:"h-[60vh] w-full overflow-hidden rounded-md",children:o.jsx(K_t,{children:o.jsx(wOe,{children:o.jsx(s4t,{workflowId:e,workflow:t})})})})]})},FBr=e=>{const{setResult:t}=v.useContext(Vl);v.useEffect(()=>{e&&t(e)},[e,t])};function _t(e,t,n){function r(l,c){var u;Object.defineProperty(l,"_zod",{value:l._zod??{},enumerable:!1}),(u=l._zod).traits??(u.traits=new Set),l._zod.traits.add(e),t(l,c);for(const d in i.prototype)d in l||Object.defineProperty(l,d,{value:i.prototype[d].bind(l)});l._zod.constr=i,l._zod.def=c}const s=n?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:e});function i(l){var c;const u=n?.Parent?new a:this;r(u,l),(c=u._zod).deferred??(c.deferred=[]);for(const d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class _D extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const a4t={};function $1(e){return a4t}function BBr(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,s])=>t.indexOf(+r)===-1).map(([r,s])=>s)}function UBr(e,t){return typeof t=="bigint"?t.toString():t}function QTe(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function YTe(e){return e==null}function KTe(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function qBr(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,a=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return a%i/10**s}function so(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function tG(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function uP(e){return JSON.stringify(e)}const i4t=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Pq(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const VBr=QTe(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function $q(e){if(Pq(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(Pq(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const HBr=new Set(["string","number","symbol"]);function Y4(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gC(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function sr(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function WBr(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const ZBr={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function GBr(e,t){const n={},r=e._zod.def;for(const s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(n[s]=r.shape[s])}return gC(e,{...e._zod.def,shape:n,checks:[]})}function QBr(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&delete n[s]}return gC(e,{...e._zod.def,shape:n,checks:[]})}function YBr(e,t){if(!$q(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return tG(this,"shape",r),r},checks:[]};return gC(e,n)}function KBr(e,t){return gC(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return tG(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function XBr(e,t,n){const r=t._zod.def.shape,s={...r};if(n)for(const a in n){if(!(a in r))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(s[a]=e?new e({type:"optional",innerType:r[a]}):r[a])}else for(const a in r)s[a]=e?new e({type:"optional",innerType:r[a]}):r[a];return gC(t,{...t._zod.def,shape:s,checks:[]})}function JBr(e,t,n){const r=t._zod.def.shape,s={...r};if(n)for(const a in n){if(!(a in s))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(s[a]=new e({type:"nonoptional",innerType:r[a]}))}else for(const a in r)s[a]=new e({type:"nonoptional",innerType:r[a]});return gC(t,{...t._zod.def,shape:s,checks:[]})}function W2(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Qk(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function _F(e){return typeof e=="string"?e:e?.message}function M1(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const s=_F(e.inst?._zod.def?.error?.(e))??_F(t?.error?.(e))??_F(n.customError?.(e))??_F(n.localeError?.(e))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function XTe(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function CD(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const o4t=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,UBr,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},l4t=_t("$ZodError",o4t),c4t=_t("$ZodError",o4t,{Parent:Error});function eUr(e,t=n=>n.message){const n={},r=[];for(const s of e.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}function tUr(e,t){const n=t||function(a){return a.message},r={_errors:[]},s=a=>{for(const i of a.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(l=>s({issues:l}));else if(i.code==="invalid_key")s({issues:i.issues});else if(i.code==="invalid_element")s({issues:i.issues});else if(i.path.length===0)r._errors.push(n(i));else{let l=r,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(n(i))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return s(e),r}const nUr=e=>(t,n,r,s)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new _D;if(i.issues.length){const l=new(s?.Err??e)(i.issues.map(c=>M1(c,a,$1())));throw i4t(l,s?.callee),l}return i.value},rUr=e=>async(t,n,r,s)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const l=new(s?.Err??e)(i.issues.map(c=>M1(c,a,$1())));throw i4t(l,s?.callee),l}return i.value},u4t=e=>(t,n,r)=>{const s=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new _D;return a.issues.length?{success:!1,error:new(e??l4t)(a.issues.map(i=>M1(i,s,$1())))}:{success:!0,data:a.value}},d4t=u4t(c4t),f4t=e=>async(t,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>M1(i,s,$1())))}:{success:!0,data:a.value}},sUr=f4t(c4t),aUr=/^[cC][^\s-]{8,}$/,iUr=/^[0-9a-z]+$/,oUr=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lUr=/^[0-9a-vA-V]{20}$/,cUr=/^[A-Za-z0-9]{27}$/,uUr=/^[a-zA-Z0-9_-]{21}$/,dUr=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,fUr=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,UKe=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,pUr=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,hUr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function mUr(){return new RegExp(hUr,"u")}const gUr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,vUr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,yUr=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bUr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xUr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,p4t=/^[A-Za-z0-9_-]*$/,wUr=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,SUr=/^\+(?:[0-9]){6,14}[0-9]$/,h4t="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",kUr=new RegExp(`^${h4t}$`);function m4t(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function OUr(e){return new RegExp(`^${m4t(e)}$`)}function _Ur(e){const t=m4t({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${h4t}T(?:${r})$`)}const CUr=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},EUr=/^\d+$/,TUr=/^-?\d+(?:\.\d+)?/i,jUr=/true|false/i,NUr=/null/i,IUr=/^[^A-Z]*$/,AUr=/^[^a-z]*$/,Wf=_t("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),g4t={number:"number",bigint:"bigint",object:"date"},v4t=_t("$ZodCheckLessThan",(e,t)=>{Wf.init(e,t);const n=g4t[typeof t.value];e._zod.onattach.push(r=>{const s=r._zod.bag,a=(t.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?s.maximum=t.value:s.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),y4t=_t("$ZodCheckGreaterThan",(e,t)=>{Wf.init(e,t);const n=g4t[typeof t.value];e._zod.onattach.push(r=>{const s=r._zod.bag,a=(t.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?s.minimum=t.value:s.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),RUr=_t("$ZodCheckMultipleOf",(e,t)=>{Wf.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):qBr(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),PUr=_t("$ZodCheckNumberFormat",(e,t)=>{Wf.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[s,a]=ZBr[t.format];e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,l.minimum=s,l.maximum=a,n&&(l.pattern=EUr)}),e._zod.check=i=>{const l=i.value;if(n){if(!Number.isInteger(l)){i.issues.push({expected:r,format:t.format,code:"invalid_type",input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?i.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):i.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}l<s&&i.issues.push({origin:"number",input:l,code:"too_small",minimum:s,inclusive:!0,inst:e,continue:!t.abort}),l>a&&i.issues.push({origin:"number",input:l,code:"too_big",maximum:a,inst:e})}}),$Ur=_t("$ZodCheckMaxLength",(e,t)=>{var n;Wf.init(e,t),(n=e._zod.def).when??(n.when=r=>{const s=r.value;return!YTe(s)&&s.length!==void 0}),e._zod.onattach.push(r=>{const s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<s&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const s=r.value;if(s.length<=t.maximum)return;const i=XTe(s);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),MUr=_t("$ZodCheckMinLength",(e,t)=>{var n;Wf.init(e,t),(n=e._zod.def).when??(n.when=r=>{const s=r.value;return!YTe(s)&&s.length!==void 0}),e._zod.onattach.push(r=>{const s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>s&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const s=r.value;if(s.length>=t.minimum)return;const i=XTe(s);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),DUr=_t("$ZodCheckLengthEquals",(e,t)=>{var n;Wf.init(e,t),(n=e._zod.def).when??(n.when=r=>{const s=r.value;return!YTe(s)&&s.length!==void 0}),e._zod.onattach.push(r=>{const s=r._zod.bag;s.minimum=t.length,s.maximum=t.length,s.length=t.length}),e._zod.check=r=>{const s=r.value,a=s.length;if(a===t.length)return;const i=XTe(s),l=a>t.length;r.issues.push({origin:i,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),nG=_t("$ZodCheckStringFormat",(e,t)=>{var n,r;Wf.init(e,t),e._zod.onattach.push(s=>{const a=s._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=s=>{t.pattern.lastIndex=0,!t.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:t.format,input:s.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),LUr=_t("$ZodCheckRegex",(e,t)=>{nG.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),zUr=_t("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=IUr),nG.init(e,t)}),FUr=_t("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=AUr),nG.init(e,t)}),BUr=_t("$ZodCheckIncludes",(e,t)=>{Wf.init(e,t);const n=Y4(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(s=>{const a=s._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),e._zod.check=s=>{s.value.includes(t.includes,t.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:s.value,inst:e,continue:!t.abort})}}),UUr=_t("$ZodCheckStartsWith",(e,t)=>{Wf.init(e,t);const n=new RegExp(`^${Y4(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),qUr=_t("$ZodCheckEndsWith",(e,t)=>{Wf.init(e,t);const n=new RegExp(`.*${Y4(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),VUr=_t("$ZodCheckOverwrite",(e,t)=>{Wf.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class HUr{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
572
+ `,e[0].empty=!0)},AKe=(e,t)=>{const n=e.length;return n>0&&e[n-1]===t?e:e.concat(t)},W7r=e=>{const t=[[]],n=[e],r=[0],s=[e.length];let a=0,i=0,l=[];const c=[l];for(;i>-1;){for(;(a=r[i]++)<s[i];){let u,d=t[i];const p=n[i][a];if(typeof p=="string"?(d=i>0?d:["plain"],u=p):(d=AKe(d,p.type),p.alias&&(d=AKe(d,p.alias)),u=p.content),typeof u!="string"){i++,t.push(d),n.push(u),r.push(0),s.push(u.length);continue}const h=u.split(H7r),m=h.length;l.push({types:d,content:h[0]});for(let g=1;g<m;g++)IKe(l),c.push(l=[]),l.push({types:d,content:h[g]})}i--,t.pop(),n.pop(),r.pop(),s.pop()}return IKe(l),c},RKe=W7r,Z7r=({prism:e,code:t,grammar:n,language:r})=>v.useMemo(()=>{if(n==null)return RKe([t]);const s={code:t,grammar:n,language:r,tokens:[]};return e.hooks.run("before-tokenize",s),s.tokens=e.tokenize(t,n),e.hooks.run("after-tokenize",s),RKe(s.tokens)},[t,n,r,e]),G7r=(e,t)=>{const{plain:n}=e,r=e.styles.reduce((s,a)=>{const{languages:i,style:l}=a;return i&&!i.includes(t)||a.types.forEach(c=>{const u=dy(dy({},s[c]),l);s[c]=u}),s},{});return r.root=n,r.plain=JZ(dy({},n),{backgroundColor:void 0}),r},Q7r=G7r,Y7r=({children:e,language:t,code:n,theme:r,prism:s})=>{const a=t.toLowerCase(),i=Q7r(r,a),l=q7r(i),c=V7r(i),u=s.languages[a],d=Z7r({prism:s,language:a,code:n,grammar:u});return e({tokens:d,className:`prism-code language-${a}`,style:i!=null?i.root:{},getLineProps:l,getTokenProps:c})},Z3t=e=>v.createElement(Y7r,JZ(dy({},e),{prism:e.prism||Nt,theme:e.theme||W3t,code:e.code,language:e.language}));const K7r=({condition:e,onOpen:t})=>o.jsx("div",{className:"px-3",children:o.jsx(Z3t,{theme:ZTe.oneDark,code:String(e.fnString).trim(),language:"javascript",children:({className:n,style:r,tokens:s,getLineProps:a,getTokenProps:i})=>o.jsx("pre",{className:X("relative font-mono p-3 w-full cursor-pointer rounded-lg text-xs bg-surface4! whitespace-pre-wrap wrap-break-word",n),onClick:t,style:r,children:s.map((l,c)=>o.jsxs("div",{...a({line:l}),children:[o.jsx("span",{className:"text-neutral3 mr-2 inline-block",children:c+1}),l.map((u,d)=>o.jsx("span",{...i({token:u})},d))]},c))})})}),X7r=({open:e,onOpenChange:t,condition:n})=>o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{className:"max-w-[30rem]",children:[o.jsxs(br,{children:[o.jsx(hr,{className:"sr-only",children:"Condition Function"}),o.jsx(Bs,{children:"View the condition function code"})]}),o.jsx(Rr,{children:o.jsx(Fr,{className:"w-full",maxHeight:"400px",children:n&&o.jsx(Z3t,{theme:ZTe.oneDark,code:String(n.fnString).trim(),language:"javascript",children:({className:r,style:s,tokens:a,getLineProps:i,getTokenProps:l})=>o.jsx("pre",{className:`${r} relative mt-2 w-full overflow-x-auto rounded-lg p-3 font-mono text-sm dark:bg-zinc-800`,style:{...s,backgroundColor:"#121212",padding:"0 0.75rem 0 0"},children:a.map((c,u)=>o.jsxs("div",{...i({line:c}),children:[o.jsx("span",{className:"text-neutral3 mr-2 inline-block",children:u+1}),c.map((d,f)=>o.jsx("span",{...l({token:d})},f))]},u))})})})})]})}),J7r=e=>!!e.fnString,eBr=({type:e,conditions:t,previousDisplayStatus:n,isOpen:r,onOpenChange:s,openDialog:a,onOpenDialogChange:i,dialogCondition:l,onConditionClick:c,actionBar:u})=>{const d=(t.some(m=>m.fnString)||t.length>1)&&e!=="else",f=jKe(e),p=f?[f]:[],h=U3t(p);return o.jsxs("div",{"data-workflow-node":!0,"data-workflow-step-status":n??"idle","data-testid":"workflow-condition-node",style:h?{borderLeftColor:h}:void 0,className:X("bg-surface3 rounded-lg w-dropdown-max-height border border-border1",h&&"border-l-4"),children:[o.jsxs(Pf,{open:d?r:!0,onOpenChange:m=>{d&&s(m)},children:[o.jsxs("div",{className:"flex w-full items-center gap-1 px-3 py-2",children:[d&&o.jsx(Fd,{"aria-label":r?"Collapse condition":"Expand condition",className:"text-neutral3 hover:text-neutral5 focus-visible:ring-accent1 inline-flex h-5 w-5 items-center justify-center rounded-full focus-visible:ring-1 focus-visible:outline-hidden",children:o.jsx(qe,{children:o.jsx(ka,{className:X("transition-transform",{"transform rotate-180":r})})})}),o.jsx(Aq,{indicators:p,className:"shrink-0"}),o.jsx("div",{className:"ml-auto flex shrink-0 items-center",children:u})]}),e==="else"?null:o.jsx(Bd,{className:"flex flex-col gap-2 pb-2",children:t.map((m,g)=>{const y=m.conj||e,b=g===0?void 0:jKe(y),x=b?[b]:[];return J7r(m)?o.jsx(K7r,{condition:m,onOpen:()=>c(m)},`condition-code-${g}-${m.fnString}`):o.jsx(v.Fragment,{children:m.ref?.step?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Aq,{indicators:x}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 flex-1",children:[typeof m.ref.step=="string"?m.ref.step:m.ref.step.id,"'s"," ",m.ref.path," ",Object.entries(m.query).map(([S,k])=>`${S} ${String(k)}`)]})]}):null},`condition-ref-${g}-${m.ref?.path??"unknown"}`)})})]}),o.jsx(X7r,{open:a,onOpenChange:i,condition:l})]})},tBr=({startedAt:e,endedAt:t})=>{const[n,r]=v.useState(e);v.useEffect(()=>{const a=setInterval(()=>{r(Date.now())},100);return()=>clearInterval(a)},[e]);const s=t?t-e:n-e;return o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 font-mono whitespace-nowrap",children:[D3t(s,3),"ms"]})},nBr=({displayStatus:e,hasStep:t})=>o.jsxs(qe,{size:"sm",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center",children:[e==="tripwire"&&o.jsx($xe,{className:"text-amber-400",strokeWidth:2}),e==="failed"&&o.jsx(G2,{className:"text-accent2",strokeWidth:2}),e==="success"&&o.jsx(_xe,{className:"text-accent1",strokeWidth:2}),e==="suspended"&&o.jsx(cV,{className:"text-accent3",strokeWidth:2}),e==="waiting"&&o.jsx(ppe,{className:"text-accent5",strokeWidth:2}),e==="running"&&o.jsx(ua,{className:"text-accent6 animate-spin",strokeWidth:2}),!e&&!t&&o.jsx(ZWt,{className:"text-neutral2",strokeWidth:2})]}),rBr=({foreachProgress:e})=>e?o.jsxs("div",{className:"flex items-center gap-2 px-3 pb-2",children:[o.jsx("div",{className:"bg-surface1 h-1.5 flex-1 overflow-hidden rounded-full",children:o.jsx("div",{className:X("h-full rounded-full transition-all duration-300",e.iterationStatus==="failed"?"bg-accent2":"bg-accent1"),style:{width:`${e.totalCount>0?e.completedCount/e.totalCount*100:0}%`}})}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 whitespace-nowrap",children:[e.completedCount," / ",e.totalCount]})]}):null,sBr=({duration:e,date:t})=>o.jsxs(o.Fragment,{children:[e&&o.jsxs(ye,{variant:"ui-sm",className:"text-neutral3 px-3 pb-2",children:["sleeps for ",o.jsxs("strong",{children:[e,"ms"]})]}),t&&o.jsxs(ye,{variant:"ui-sm",className:"text-neutral3 px-3 pb-2",children:["sleeps until ",o.jsx("strong",{children:new Date(t).toLocaleString()})]})]}),aBr=({label:e,description:t,displayStatus:n,hasStep:r,isNestedWorkflowStep:s,stepKey:a,isSelected:i,isWaiting:l,isHovered:c,onHoverChange:u,duration:d,date:f,isForEach:p,foreachProgress:h,mapConfig:m,canSuspend:g,isParallel:y,stepGraph:b,startedAt:x,endedAt:S,actionBar:k})=>{const _=B3t({duration:d,date:f,isForEach:p,mapConfig:m,canSuspend:g,isParallel:y,stepGraph:b}),E=U3t(_);return o.jsxs("div",{"data-workflow-node":!0,"data-workflow-step-key":a,"data-workflow-step-status":n??"idle","data-workflow-step-active":i?"true":void 0,"data-workflow-step-waiting":l?"true":void 0,"data-workflow-step-hovered":c?"true":void 0,"data-testid":s?"workflow-nested-node":"workflow-default-node",onMouseEnter:()=>u?.(!0),onMouseLeave:()=>u?.(!1),style:E?{borderLeftColor:E}:void 0,className:X("bg-surface3 rounded-lg w-[274px] border border-border1 transition-colors hover:border-neutral6",E&&"border-l-4",c&&!i&&"border-neutral6",l&&!i&&"border-accent3",i&&"border-accent1"),children:[o.jsxs("div",{className:X("flex items-center gap-2 px-3 pt-2",!t&&"pb-2"),children:[o.jsx(Aq,{indicators:_,className:"shrink-0"}),o.jsx(nBr,{displayStatus:n,hasStep:r}),o.jsx("div",{className:"min-w-0 flex-1",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral6 block truncate font-medium",title:e,children:e})}),o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-1",children:[x&&o.jsx(tBr,{startedAt:x,endedAt:S}),k]})]}),t&&o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 px-3 pb-2",children:t}),p&&o.jsx(rBr,{foreachProgress:h}),o.jsx(sBr,{duration:d,date:f})]})},cP="text-neutral3 hover:text-neutral6",PKe=e=>{try{return e==null?"{}":JSON.stringify(e,null,2)}catch{return"{}"}},Mae=({label:e,value:t,onChange:n,helperText:r,exampleCode:s})=>{const a=o0(),{handleCopy:i}=Zp({text:t}),{handleCopy:l}=Zp({text:s??"{}"}),[c,u]=v.useState(null),[d,f]=v.useState(!1),[p,h]=v.useState(!1),m=async()=>{if(u(null),!t.trim()){n("{}");return}if(!OD(t)){u("Invalid JSON");return}try{const g=await fj(t);n(g)}catch{u("Unable to format JSON")}};return o.jsxs(o.Fragment,{children:[p&&o.jsxs("div",{className:"border-border1 bg-surface3 space-y-2 rounded-lg border p-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:["Example ",e]}),o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("button",{type:"button",onClick:l,className:cP,"aria-label":"Copy example JSON",children:o.jsx(qe,{children:o.jsx(im,{})})})}),o.jsx(Pn,{children:"Copy example JSON"})]})]}),o.jsx(ed,{value:s,theme:a,extensions:[Dp],className:"bg-surface3 h-[150px] w-full overflow-scroll overflow-y-scroll rounded-lg p-3"})]}),o.jsxs(Pf,{className:"border-border1 bg-surface3 rounded-lg border",open:d,onOpenChange:f,children:[o.jsxs("div",{className:"flex w-full items-center justify-between px-3",children:[o.jsxs("div",{children:[o.jsx(ye,{as:"label",variant:"ui-md",className:"text-neutral3",children:e}),r&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:r})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("button",{type:"button",onClick:m,className:cP,"aria-label":"Format JSON",children:o.jsx(qe,{children:o.jsx(Ry,{})})})}),o.jsx(Pn,{children:"Format JSON"})]}),o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("button",{type:"button",onClick:i,className:cP,"aria-label":"Copy JSON",children:o.jsx(qe,{children:o.jsx(im,{})})})}),o.jsx(Pn,{children:"Copy JSON"})]}),s&&o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("button",{type:"button",onClick:()=>h(!p),className:cP,"aria-label":p?"Hide example JSON":"View example JSON",children:o.jsx(qe,{children:p?o.jsx(RZt,{}):o.jsx(Bu,{})})})}),o.jsx(Pn,{children:"View example JSON"})]}),o.jsx(Fd,{asChild:!0,children:o.jsx("button",{type:"button",className:cP,"aria-label":d?`Collapse ${e}`:`Expand ${e}`,children:o.jsx(qe,{className:X("transition-transform",d?"rotate-0":"-rotate-90"),children:o.jsx(ka,{})})})})]})]}),o.jsxs(Bd,{className:"space-y-2",children:[o.jsx(ed,{value:t,onChange:n,theme:a,extensions:[Dp],className:"bg-surface3 h-[260px] overflow-hidden overflow-y-scroll rounded-lg p-3"}),c&&o.jsx(ye,{variant:"ui-sm",className:"text-accent2",children:c})]})]})]})},Dae=({stepKey:e,closeModal:t,isPerStepRun:n,isContinueRun:r,buttonText:s="Start time travel",inputData:a})=>{const{result:i,workflow:l,timeTravelWorkflowStream:c,runId:u,workflowId:d,setDebugMode:f}=v.useContext(Vl),p=ql(),h=a?{payload:a}:i?.steps?.[e],[m,g]=v.useState(()=>"{}"),[y,b]=v.useState(()=>"{}"),[x,S]=v.useState(()=>"{}"),[k,C]=v.useState(null),[_,E]=v.useState(!1),T=l?.allSteps?.[e],{schema:N}=v.useMemo(()=>{if(!T?.inputSchema)return{schema:yp(dr(),Lj())};try{const A=Ax(T.inputSchema),R=l?.stateSchema?gm(hm(Ax(l.stateSchema))):null,L=gm(hm(A));return{schema:R?Os({inputData:L,initialState:R.optional()}):L,schemaError:null}}catch(A){return console.error("Failed to parse step schema",A),{schema:yp(dr(),Lj())}}},[T?.inputSchema,l?.stateSchema]),I=async A=>{C(null),E(!0);try{const R=m.trim()?JSON.parse(m):{},L=y.trim()?JSON.parse(y):{},D=x.trim()?JSON.parse(x):{},{initialState:z,inputData:H}=A??{},F=l?.stateSchema?H:A,U={runId:u,workflowId:d,step:e,inputData:F,initialState:z,resumeData:Object.keys(R)?.length>0?R:void 0,context:Object.keys(L)?.length>0?L:void 0,nestedStepsContext:Object.keys(D)?.length>0?D:void 0,requestContext:p,...r?{perStep:!1}:{}};r&&f(!1),c(U),t()}catch(R){console.error("Invalid JSON provided",R),C(R instanceof Error?R.message:"Error time traveling workflow")}finally{E(!1)}};return o.jsx(cc,{children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(ye,{as:"p",variant:"ui-lg",className:"text-neutral3",children:"Input data"}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3",children:["Step: ",e]})]}),o.jsx(YB,{schema:N,defaultValues:h?.payload,isSubmitLoading:_,submitButtonLabel:s,onSubmit:I,children:o.jsxs("div",{className:"space-y-4 pb-4",children:[n||r?null:o.jsxs(o.Fragment,{children:[o.jsx(Mae,{label:"Resume Data (JSON)",value:m,onChange:g,helperText:"Provide any resume payloads that should be passed to the step."}),o.jsx(Mae,{label:"Context (JSON)",value:y,onChange:b,helperText:"Only include top level steps (no nested workflow steps) that are required in the time travel execution.",exampleCode:PKe({stepId:{status:"success",payload:{value:"test value"},output:{value:"test output"}}})}),o.jsx(Mae,{label:"Nested Step Context (JSON)",value:x,onChange:S,helperText:"Includes nested workflow steps that are required in the time travel execution.",exampleCode:PKe({nestedWorkflowId:{stepId:{status:"success",payload:{value:"test value"},output:{value:"test output"}}}})})]}),k&&o.jsx(ye,{variant:"ui-sm",className:"text-accent2",children:k})]})})]})})},G3t=({input:e,resumeData:t,output:n,suspendOutput:r,error:s,tripwire:a,mapConfig:i,stepName:l,stepId:c,onShowNestedGraph:u,stepKey:d,stepsFlow:f})=>{const[p,h]=v.useState(!1),[m,g]=v.useState(!1),[y,b]=v.useState(!1),[x,S]=v.useState(!1),[k,C]=v.useState(!1),[_,E]=v.useState(!1),{withoutTimeTravel:T,debugMode:N,result:I,runSnapshot:A,timeTravelWorkflowStream:R,runId:L,workflowId:D,setDebugMode:z}=v.useContext(Vl),{showMapConfig:H,stepDetail:F,closeStepDetail:U}=dW(),q=ql(),M=I?.status??A?.status,G="max-w-4xl w-full",V=!T&&d&&!i&&M!=="running"&&M!=="paused",$=d&&N&&M==="paused",B=v.useMemo(()=>{if(!d||!$)return;const Y=f?.[d]??[];if(Y.length===0)return;if(Y.length>1)return{hasMultiSteps:!0,input:Y.reduce((le,ue)=>(I?.steps?.[ue]?.status==="success"&&(le[ue]=I?.steps?.[ue].output),le),{})};const re=Y[0];if(I?.steps?.[re]?.status==="success")return{hasMultiSteps:!1,input:I?.steps?.[re].output}},[d,f,$,I]),Z=$&&B&&!I?.steps?.[d],K=F?.type==="map-config"&&F?.stepName===l,ne=F?.type==="nested-graph"&&F?.stepName===l,ee=()=>{K?U():H({stepName:l,stepId:c,mapConfig:i})},J=()=>{ne?U():u?.()},ae=Y=>{if(!d||!B)return;const re={runId:L,workflowId:D,step:d,inputData:B?.hasMultiSteps?void 0:B?.input,requestContext:q,...Y?{perStep:!1}:{},...B?.hasMultiSteps?{context:Object.keys(B.input)?.reduce((le,ue)=>(le[ue]={status:"success",output:B.input[ue]},le),{})}:{}};Y&&z(!1),R(re)};return!(s||a||i||t||u||V||Z)?null:o.jsxs(o.Fragment,{children:[o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ce,{size:"icon-sm",variant:"ghost","aria-label":"Step actions",title:"Step actions",className:"nodrag nopan",children:o.jsx(qD,{})})}),o.jsxs(ot.Content,{align:"end",children:[u&&o.jsxs(ot.Item,{onSelect:J,children:[o.jsx(lV,{}),o.jsx("span",{children:ne?"Hide nested graph":"View nested graph"})]}),V&&o.jsxs(ot.Item,{onSelect:()=>S(!0),children:[o.jsx(aZt,{}),o.jsx("span",{children:"Time travel"})]}),Z&&o.jsxs(o.Fragment,{children:[o.jsxs(ot.Item,{onSelect:()=>{i?ae():E(!0)},children:[o.jsx(jf,{}),o.jsx("span",{children:"Run step"})]}),o.jsxs(ot.Item,{onSelect:()=>{i?ae(!0):C(!0)},children:[o.jsx(Xot,{}),o.jsx("span",{children:"Continue run"})]})]}),i&&o.jsxs(ot.Item,{onSelect:ee,children:[o.jsx(Ry,{}),o.jsx("span",{children:K?"Hide map config":"Map config"})]}),t&&o.jsxs(ot.Item,{onSelect:()=>h(!0),children:[o.jsx(Qot,{}),o.jsx("span",{children:"Resume data"})]}),s&&o.jsxs(ot.Item,{onSelect:()=>g(!0),children:[o.jsx(vj,{}),o.jsx("span",{children:"Error"})]}),a&&o.jsxs(ot.Item,{onSelect:()=>b(!0),className:"text-amber-400",children:[o.jsx($xe,{}),o.jsx("span",{children:"Tripwire"})]})]})]}),V&&o.jsx(vr,{open:x,onOpenChange:S,children:o.jsxs(yr,{className:G,children:[o.jsxs(br,{children:[o.jsxs(hr,{children:["Time travel to ",d]}),o.jsx(Bs,{children:"Time travel to a specific workflow step"})]}),o.jsx(Rr,{className:"max-h-[600px]",children:o.jsx(Dae,{stepKey:d,closeModal:()=>S(!1)})})]})}),Z&&!i&&o.jsxs(o.Fragment,{children:[o.jsx(vr,{open:_,onOpenChange:E,children:o.jsxs(yr,{className:G,children:[o.jsxs(br,{children:[o.jsxs(hr,{children:["Run step ",d]}),o.jsx(Bs,{children:"Run a specific workflow step"})]}),o.jsx(Rr,{className:"max-h-[600px]",children:o.jsx(Dae,{stepKey:d,closeModal:()=>E(!1),isPerStepRun:!0,buttonText:"Run step",inputData:B?.input})})]})}),o.jsx(vr,{open:k,onOpenChange:C,children:o.jsxs(yr,{className:G,children:[o.jsxs(br,{children:[o.jsxs(hr,{children:["Continue run ",d]}),o.jsx(Bs,{children:"Continue the workflow run from this step"})]}),o.jsx(Rr,{className:"max-h-[600px]",children:o.jsx(Dae,{stepKey:d,closeModal:()=>C(!1),isContinueRun:!0,buttonText:"Continue run",inputData:B?.input})})]})})]}),t&&o.jsx(vr,{open:p,onOpenChange:h,children:o.jsxs(yr,{className:G,children:[o.jsxs(br,{children:[o.jsxs(hr,{children:[l," resume data"]}),o.jsx(Bs,{children:"View the resume data for this step"})]}),o.jsx(Rr,{children:o.jsx(V2,{data:t})})]})}),s&&o.jsx(vr,{open:m,onOpenChange:g,children:o.jsxs(yr,{className:G,children:[o.jsxs(br,{children:[o.jsxs(hr,{children:[l," error"]}),o.jsx(Bs,{children:"View the error details for this step"})]}),o.jsx(Rr,{children:o.jsx(V2,{data:s})})]})}),a&&o.jsx(vr,{open:y,onOpenChange:b,children:o.jsxs(yr,{className:G,children:[o.jsxs(br,{children:[o.jsxs(hr,{children:[l," tripwire"]}),o.jsx(Bs,{children:"View the tripwire details for this step"})]}),o.jsx(Rr,{children:o.jsx(V2,{data:{reason:a.reason,retry:a.retry,metadata:a.metadata,processorId:a.processorId}})})]})})]})},Q3t=e=>{const t=e?.status==="failed"&&e?.tripwire!==void 0;return{displayStatus:t?"tripwire":e?.status,isTripwire:t}},iBr=({data:e,parentWorkflowName:t,stepsFlow:n})=>{const{steps:r}=G4(),{selectedStepId:s,hoverStepId:a,setHoverStepId:i}=kH(),{showNestedGraph:l}=dW(),c=aOe(),{label:u,stepId:d,description:f}=e,p=e.mapConfig??("step"in e.workflowStep?e.workflowStep.step?.mapConfig:void 0),h=e.stepGraph??("step"in e.workflowStep?e.workflowStep.step?.serializedStepFlow:void 0)??(e.workflowStep.kind==="nested-workflow-step"&&e.workflowStep.flow.type==="workflow"?e.workflowStep.flow.serializedStepFlow:void 0),m=t?`${t}.${u}`:u,g=t?`${t}.${d||u}`:d||u,y=s===g,b=c===g,x=a===g,S=r[g],{displayStatus:k,isTripwire:C}=Q3t(S);return o.jsx(aBr,{label:u,description:f,displayStatus:k,hasStep:!!S,isNestedWorkflowStep:e.workflowStep.kind==="nested-workflow-step",stepKey:g,isSelected:y,isWaiting:b,isHovered:x,onHoverChange:_=>i(_?g:null),duration:e.duration,date:e.date,isForEach:e.isForEach,foreachProgress:S?.foreachProgress,mapConfig:p,canSuspend:e.canSuspend,isParallel:e.isParallel,stepGraph:h,startedAt:S?.startedAt,endedAt:S?.endedAt,actionBar:o.jsx(G3t,{stepName:u,stepId:d,resumeData:S?.resumeData,error:C?void 0:S?.error,tripwire:C?S?.tripwire:void 0,mapConfig:p,onShowNestedGraph:h?()=>l({label:u,fullStep:m,stepGraph:h}):void 0,status:k,stepKey:g,stepsFlow:n})})},oBr=({data:e})=>{const[t,n]=v.useState(!0),[r,s]=v.useState(!1),[a,i]=v.useState(),{steps:l}=G4(),c=e.conditions??[],u=c[0]?.type,d=e.previousStepId?l[e.previousStepId]:void 0,f=e.nextStepId?l[e.nextStepId]:void 0,{displayStatus:p,isTripwire:h}=Q3t(d);return o.jsx(eBr,{type:u,conditions:c,previousDisplayStatus:p,hasPreviousStep:!!d,hasNextStep:!!f,isOpen:t,onOpenChange:n,openDialog:r,onOpenDialogChange:s,dialogCondition:a,onConditionClick:m=>{i(m),s(!0)},actionBar:o.jsx(G3t,{stepName:e.nextStepId??e.label,mapConfig:e.mapConfig,tripwire:h?d?.tripwire:void 0,status:f?p:void 0})})};function lBr({data:e,parentWorkflowName:t,stepsFlow:n}){const r=e.workflowStep.kind==="conditional"?o.jsx(oBr,{data:e}):o.jsx(iBr,{data:e,parentWorkflowName:t,stepsFlow:n});return o.jsxs(o.Fragment,{children:[!e.withoutTopHandle&&o.jsx(j1,{type:"target",position:ar.Top,style:{visibility:"hidden"}}),r,!e.withoutBottomHandle&&o.jsx(j1,{type:"source",position:ar.Bottom,style:{visibility:"hidden"}})]})}const Lae=(e,t)=>e&&t?`${t}.${e}`:e,Y3t=({edges:e,workflowName:t,stepGraph:n})=>{const{steps:r}=G4(),s=v.useContext(Vl),a=t?r[t]?.status==="success":s.result?.status==="success",i=v.useMemo(()=>LOt(e),[e]),l=v.useMemo(()=>{const f=zOt(i),{conditionalStepIds:p}=FOt(n??s.workflow?.stepGraph),h=m=>r[Lae(m,t)??""]?.status==="success";return m=>!!m&&sOe({stepId:m,conditionalStepIds:p,stepSuccessors:f,stepsFlow:i,isStepSuccess:h})},[i,n,s.workflow?.stepGraph,r,t]),c=v.useMemo(()=>({[ig]:f=>o.jsx(lBr,{parentWorkflowName:t,...f,stepsFlow:i}),[QB]:f=>o.jsx(z9r,{...f})}),[i,t]),u=v.useMemo(()=>({[lP]:f=>o.jsx(V9r,{parentWorkflowName:t,...f})}),[t]),d=v.useMemo(()=>e.map(f=>{const p=Lae(f.data?.previousStepId,t),h=Lae(f.data?.nextStepId,t),m=r[p??""]?.status==="success",g=r[h??""]?.status,y=l(f.data?.nextStepId);if(f.data?.boundaryPayload==="workflow-output"){const x=a;return{...f,type:lP,animated:x?!1:f.animated,data:{...f.data,edgeStatus:x?"success":"idle"},style:{...f.style,stroke:x?"#22c55e":"#8e8e8e",strokeDasharray:x?"none":f.style?.strokeDasharray}}}if(f.data?.boundaryPayload==="workflow-input"){const x=!!g&&g!=="skipped";return{...f,type:lP,animated:x?!1:f.animated,data:{...f.data,edgeStatus:x?"success":"idle"},style:{...f.style,stroke:x?"#22c55e":"#8e8e8e",strokeDasharray:x?"none":f.style?.strokeDasharray}}}if(f.data?.conditionNode){const S=!!g&&g!=="skipped"&&!y;return{...f,type:lP,animated:S?!1:f.animated,data:{...f.data,edgeStatus:S?"success":"idle"},style:{...f.style,stroke:S?"#22c55e":"#8e8e8e",strokeDasharray:S?"none":f.style?.strokeDasharray}}}const b=m&&g!=="skipped"&&!y;return{...f,type:lP,animated:b?!1:f.animated,data:{...f.data,edgeStatus:b?"success":"idle"},style:{...f.style,stroke:b?"#22c55e":"#8e8e8e",strokeDasharray:b?"none":f.style?.strokeDasharray}}}),[e,r,t,a,l]);return{edgeTypes:u,nodeTypes:c,stepsFlow:i,styledEdges:d}};function K3t(e,t,n=(r,s)=>r===s){return e.length===t.length&&e.every((r,s)=>n(r,t[s]))}function X3t(e,t){return e-t}function cBr(e,t,n){const r=e.slice();return r[t]=n,r.sort(X3t)}function J3t(e,t,n,r,s,a){let i=e;return i=js(i,n,r),s&&(i=cBr(a,t,js(i,a[t-1]||-1/0,a[t+1]||1/0))),i}function e4t(e,t,n){if(!Array.isArray(e))return!0;const r=e.reduce((s,a,i,l)=>(i===l.length-1||s.push(Math.abs(a-l[i+1])),s),[]);return Math.min(...r)>=t*n}const Q4={activeThumbIndex:()=>null,max:()=>null,min:()=>null,minStepsBetweenValues:()=>null,step:()=>null,values:()=>null,...X1},t4t=v.createContext(void 0);function eG(){const e=v.useContext(t4t);if(e===void 0)throw new Error(kr(62));return e}function uBr(e){return"key"in e?BOn:$k}function dBr(e,t){return typeof e=="number"&&typeof t=="number"?e===t:Array.isArray(e)&&Array.isArray(t)?K3t(e,t):!1}const fBr=v.forwardRef(function(t,n){const{"aria-labelledby":r,className:s,defaultValue:a,disabled:i=!1,id:l,format:c,largeStep:u=10,locale:d,render:f,max:p=100,min:h=0,minStepsBetweenValues:m=0,form:g,name:y,onValueChange:b,onValueCommitted:x,orientation:S="horizontal",step:k=1,thumbCollisionBehavior:C="push",thumbAlignment:_="center",value:E,style:T,...N}=t,I=Vi(l),A=nIn(I),R=wt(b),L=wt(x),{clearErrors:D}=dI(),{state:z,disabled:H,name:F,setTouched:U,setDirty:q,validityData:M,shouldValidateOnChange:G,validation:V}=Em(),{labelId:$}=r0(),[B,Z]=v.useState(),K=r??yH($,B),ne=H||i,ee=F??y,[J,ae]=_f({controlled:E,default:a??h,name:"Slider"}),fe=v.useRef(null),Y=v.useRef(null),re=v.useRef([]),le=v.useRef(null),ue=v.useRef(null),oe=v.useRef(-1),me=v.useRef(null),be=v.useRef(null),xe=v.useRef("none"),Ce=eo(c),[ke,Ne]=v.useState(-1),[$e,de]=v.useState(-1),[te,se]=v.useState(!1),[he,we]=v.useState(()=>new Map),[Te,Re]=v.useState([void 0,void 0]),Ze=wt(tt=>{Ne(tt),tt!==-1&&de(tt)});uI(Y,I,J),qv(J,()=>{D(ee),G()?V.commit(J):V.commit(J,!0);const tt=M.initialValue;let Dt;Array.isArray(J)&&Array.isArray(tt)?Dt=!K3t(J,tt):Dt=J!==tt,q(Dt)});const Ge=wt(tt=>{tt&&(Y.current=tt)}),je=Array.isArray(J),Ee=v.useMemo(()=>je?J.slice().sort(X3t):[js(J,h,p)],[p,h,je,J]),Oe=wt((tt,Dt)=>{if(Number.isNaN(tt)||dBr(tt,J))return;const at=Dt??Yt(Lo,void 0,void 0,{activeThumbIndex:-1});xe.current=at.reason;const gt=at.event,ht=gt.constructor??Event,Ct=new ht(gt.type,gt);Object.defineProperty(Ct,"target",{writable:!0,value:{value:tt,name:ee}}),at.event=Ct,be.current=tt,R(tt,at),!at.isCanceled&&ae(tt)}),Ie=wt((tt,Dt,at)=>{const gt=J3t(tt,Dt,h,p,je,Ee);if(e4t(gt,k,m)){const ht=uBr(at);Oe(gt,Yt(ht,at.nativeEvent,void 0,{activeThumbIndex:Dt})),U(!0);const Ct=be.current??gt;L(Ct,Ck(ht,at.nativeEvent))}});$t(()=>{const tt=kc(pr(fe.current));ne&&mn(fe.current,tt)&&tt.blur()},[ne]),ne&&ke!==-1&&Ze(-1);const Me=v.useMemo(()=>({...z,activeThumbIndex:ke,disabled:ne,dragging:te,orientation:S,max:p,min:h,minStepsBetweenValues:m,step:k,values:Ee}),[z,ke,ne,te,p,h,m,S,k,Ee]),Ue=v.useMemo(()=>({active:ke,controlRef:Y,disabled:ne,dragging:te,validation:V,formatOptionsRef:Ce,handleInputChange:Ie,indicatorPosition:Te,inset:_!=="center",labelId:K,rootLabelId:A,largeStep:u,lastUsedThumbIndex:$e,lastChangedValueRef:be,lastChangeReasonRef:xe,form:g,locale:d,max:p,min:h,minStepsBetweenValues:m,name:ee,onValueCommitted:L,orientation:S,pressedInputRef:le,pressedThumbCenterOffsetRef:ue,pressedThumbIndexRef:oe,pressedValuesRef:me,registerFieldControlRef:Ge,renderBeforeHydration:_==="edge",setActive:Ze,setDragging:se,setIndicatorPosition:Re,setLabelId:Z,setValue:Oe,state:Me,step:k,thumbCollisionBehavior:C,thumbMap:he,thumbRefs:re,values:Ee}),[ke,Y,K,A,ne,te,V,Ce,Ie,Te,u,$e,be,xe,g,d,p,h,m,ee,L,S,le,ue,oe,me,Ge,Ze,se,Re,Z,Oe,Me,k,C,_,he,re,Ee]),Je=Nn("div",t,{state:Me,ref:[n,fe],props:[{"aria-labelledby":K,id:I,role:"group"},V.getValidationProps,N],stateAttributesMapping:Q4});return o.jsx(t4t.Provider,{value:Ue,children:o.jsx(fI,{elementsRef:re,onMapChange:we,children:Je})})}),$Ke=new Map;function pBr(e,t){const n=JSON.stringify({locale:e,options:t}),r=$Ke.get(n);if(r)return r;const s=new Intl.NumberFormat(e,t);return $Ke.set(n,s),s}function g9(e,t,n){return e==null?"":pBr(t,n).format(e)}function n4t(e){const t=e.getBoundingClientRect();return{x:(t.left+t.right)/2,y:(t.top+t.bottom)/2}}function H2(e){if(e===0)return 0;if(Math.abs(e)<1){const n=e.toExponential().split("e-"),r=n[0].split(".")[1];return(r?r.length:0)+parseInt(n[1],10)}const t=e.toString().split(".")[1];return t?t.length:0}function r4t(e,t,n){const r=Math.round((e-n)/t)*t+n;return Number(r.toFixed(Math.max(H2(t),H2(n))))}function MKe({values:e,index:t,nextValue:n,min:r,max:s,step:a,minStepsBetweenValues:i,initialValues:l}){if(e.length===0)return[];const c=e.slice(),u=a*i,d=c.length-1,f=l??e,p=r+t*u,h=s-(d-t)*u;c[t]=js(n,p,h);for(let m=t+1;m<=d;m+=1){const g=c[m-1]+u,y=s-(d-m)*u,b=f[m]??c[m];let x=Math.max(c[m],g);b<x&&(x=Math.max(b,g)),c[m]=js(x,g,y)}for(let m=t-1;m>=0;m-=1){const g=c[m+1]-u,y=r+m*u,b=f[m]??c[m];let x=Math.min(c[m],g);b>x&&(x=Math.min(b,g)),c[m]=js(x,y,g)}for(let m=0;m<=d;m+=1)c[m]=Number(c[m].toFixed(12));return c}function hBr({behavior:e,values:t,currentValues:n,initialValues:r,pressedIndex:s,nextValue:a,min:i,max:l,step:c,minStepsBetweenValues:u}){const d=n??t,f=r??t;if(!(d.length>1))return{value:a,thumbIndex:0,didSwap:!1};const h=c*u;switch(e){case"swap":{const m=d[s],g=1e-7,y=d.slice(),b=y[s-1],x=y[s+1],S=b!=null?b+h:i,k=x!=null?x-h:l,C=js(a,S,k),_=Number(C.toFixed(12));y[s]=_;const E=a>m,T=a<m,N=E&&x!=null&&a>=x-g,I=T&&b!=null&&a<=b+g;if(!N&&!I)return{value:y,thumbIndex:s,didSwap:!1};const A=N?s+1:s-1,R=y.map((H,F)=>{if(F===s)return _;const U=f[F];return U??d[F]});let L=a;N?L=Math.max(a,y[A]):L=Math.min(a,y[A]);const D=MKe({values:y,index:A,nextValue:L,min:i,max:l,step:c,minStepsBetweenValues:u,initialValues:R}),z=N?A-1:A+1;if(z>=0&&z<D.length){const H=D[z-1],F=D[z+1];let U=H!=null?H+h:i;U=Math.max(U,i+z*h);let q=F!=null?F-h:l;q=Math.min(q,l-(D.length-1-z)*h);const M=js(_,U,q);D[z]=Number(M.toFixed(12))}return{value:D,thumbIndex:A,didSwap:!0}}case"push":return{value:MKe({values:d,index:s,nextValue:a,min:i,max:l,step:c,minStepsBetweenValues:u}),thumbIndex:s,didSwap:!1};default:{const m=d.slice(),g=m[s-1],y=m[s+1],b=g!=null?g+h:i,x=y!=null?y-h:l,S=js(a,b,x);return m[s]=Number(S.toFixed(12)),{value:m,thumbIndex:s,didSwap:!1}}}}const mBr=2;function gBr(e,t){if(!e)return{start:0,end:0};function n(a){const i=a!=null?parseFloat(a):0;return Number.isNaN(i)?0:i}const r=t?"Top":"InlineStart",s=t?"Bottom":"InlineEnd";return{start:n(e[`border${r}Width`])+n(e[`padding${r}`]),end:n(e[`border${s}Width`])+n(e[`padding${s}`])}}function OF(e,t){if(t.current!=null&&e.changedTouches){const n=e;for(let r=0;r<n.changedTouches.length;r+=1){const s=n.changedTouches[r];if(s.identifier===t.current)return{x:s.clientX,y:s.clientY}}return null}return{x:e.clientX,y:e.clientY}}const vBr=v.forwardRef(function(t,n){const{render:r,className:s,style:a,...i}=t,{disabled:l,dragging:c,inset:u,lastChangedValueRef:d,lastChangeReasonRef:f,max:p,min:h,minStepsBetweenValues:m,onValueCommitted:g,orientation:y,pressedInputRef:b,pressedThumbCenterOffsetRef:x,pressedThumbIndexRef:S,pressedValuesRef:k,registerFieldControlRef:C,renderBeforeHydration:_,setActive:E,setDragging:T,setValue:N,state:I,step:A,thumbCollisionBehavior:R,thumbRefs:L,values:D}=eG(),z=Ly(),H=D.length>1,F=y==="vertical",U=v.useRef(null),q=v.useRef(null),M=wt(ue=>{ue&&q.current==null&&(q.current=ta(ue).getComputedStyle(ue))}),G=v.useRef(null),V=v.useRef(0),$=v.useRef(0),B=eo(D);function Z(ue){S.current!==ue&&(S.current=ue);const oe=L.current[ue];if(!oe){x.current=null,b.current=null;return}b.current=oe.querySelector('input[type="range"]')}function K(ue){const oe=U.current;if(!oe)return null;const{width:me,height:be,bottom:xe,left:Ce,right:ke}=oe.getBoundingClientRect(),Ne=gBr(q.current,F),$e=$.current,de=(F?be:me)-Ne.start-Ne.end-$e*2,te=x.current??0,se=ue.x-te,he=ue.y-te,we=F?xe-he-Ne.end:(z==="rtl"?ke-se:se-Ce)-Ne.start,Te=js((we-$e)/de,0,1);let Re=(p-h)*Te+h;if(Re=r4t(Re,A,h),Re=js(Re,h,p),!H)return{value:Re,thumbIndex:0,didSwap:!1};const Ze=S.current;if(Ze<0)return null;const Ge=hBr({behavior:R,values:D,currentValues:B.current??D,initialValues:k.current,pressedIndex:Ze,nextValue:Re,min:h,max:p,step:A,minStepsBetweenValues:m});return R==="swap"&&Ge.didSwap?Z(Ge.thumbIndex):S.current=Ge.thumbIndex,Ge}function ne(ue){k.current=H?D.slice():null,B.current=D;const oe=S.current;let me=oe;if(oe>-1&&oe<D.length){if(D[oe]===p){let be=oe;for(;be>0&&D[be-1]===p;)be-=1;me=be}}else{const be=F?"y":"x";let xe;me=-1;for(let Ce=0;Ce<L.current.length;Ce+=1){const ke=L.current[Ce];if(Er(ke)){const Ne=n4t(ke),$e=Math.abs(ue[be]-Ne[be]);(xe===void 0||$e<=xe)&&(me=Ce,xe=$e)}}}if(me>-1&&me!==oe&&Z(me),u){const be=L.current[me];if(Er(be)){const xe=be.getBoundingClientRect(),Ce=F?"height":"width";$.current=xe[Ce]/2}}}function ee(ue){const oe=L.current?.[ue]?.querySelector('input[type="range"]');oe&&oe.focus({preventScroll:!0,focusVisible:!1})}const J=wt(ue=>{const oe=OF(ue,G);if(oe==null)return;if(V.current+=1,ue.type==="pointermove"&&ue.buttons===0){ae(ue);return}const me=K(oe);me!=null&&e4t(me.value,A,m)&&(!c&&V.current>mBr&&T(!0),N(me.value,Yt(UOn,ue,void 0,{activeThumbIndex:me.thumbIndex})),B.current=Array.isArray(me.value)?me.value:[me.value],me.didSwap&&ee(me.thumbIndex))});function ae(ue){E(-1),T(!1),b.current=null,x.current=null;const oe=OF(ue,G),me=oe!=null?K(oe):null;if(me!=null){const be=f.current;g(d.current??me.value,Ck(be,ue))}"pointerType"in ue&&U.current?.hasPointerCapture(ue.pointerId)&&U.current?.releasePointerCapture(ue.pointerId),S.current=-1,G.current=null,k.current=null,Y()}const fe=wt(ue=>{if(l)return;const oe=ue.changedTouches[0];oe!=null&&(G.current=oe.identifier);const me=OF(ue,G);if(me!=null){ne(me);const xe=K(me);if(xe==null)return;ee(xe.thumbIndex),N(xe.value,Yt(l5e,ue,void 0,{activeThumbIndex:xe.thumbIndex})),B.current=Array.isArray(xe.value)?xe.value:[xe.value],xe.didSwap&&ee(xe.thumbIndex)}V.current=0;const be=pr(U.current);be.addEventListener("touchmove",J,{passive:!0}),be.addEventListener("touchend",ae,{passive:!0})}),Y=wt(()=>{const ue=pr(U.current);ue.removeEventListener("pointermove",J),ue.removeEventListener("pointerup",ae),ue.removeEventListener("touchmove",J),ue.removeEventListener("touchend",ae),k.current=null}),re=m1();return v.useEffect(()=>{const ue=U.current;if(!ue)return()=>Y();const oe=Vr(ue,"touchstart",fe,{passive:!0});return()=>{oe(),re.cancel(),Y()}},[Y,fe,U,re]),v.useEffect(()=>{l&&Y()},[l,Y]),Nn("div",t,{state:I,ref:[n,C,U,M],props:[{"data-base-ui-slider-control":_?"":void 0,onPointerDown(ue){const oe=U.current,me=Ei(ue.nativeEvent);if(!oe||l||ue.defaultPrevented||!Er(me)||ue.button!==0)return;const be=OF(ue,G);if(be!=null){ne(be);const Ce=K(be);if(Ce==null)return;mn(L.current[Ce.thumbIndex],kc(pr(oe)))?ue.preventDefault():re.request(()=>{ee(Ce.thumbIndex)}),T(!0),x.current!=null||(N(Ce.value,Yt(l5e,ue.nativeEvent,void 0,{activeThumbIndex:Ce.thumbIndex})),B.current=Array.isArray(Ce.value)?Ce.value:[Ce.value],Ce.didSwap&&ee(Ce.thumbIndex))}ue.nativeEvent.pointerId&&oe.setPointerCapture(ue.nativeEvent.pointerId),V.current=0;const xe=pr(U.current);xe.addEventListener("pointermove",J,{passive:!0}),xe.addEventListener("pointerup",ae,{once:!0})}},i],stateAttributesMapping:Q4})}),yBr=v.forwardRef(function(t,n){const{render:r,className:s,style:a,...i}=t,{state:l}=eG();return Nn("div",t,{state:l,ref:n,props:[{style:{position:"relative"}},i],stateAttributesMapping:Q4})});function Cbe(e,t,n){return(e-t)*100/(n-t)}let bBr=(function(e){return e.index="data-index",e.dragging="data-dragging",e.orientation="data-orientation",e.disabled="data-disabled",e.valid="data-valid",e.invalid="data-invalid",e.touched="data-touched",e.dirty="data-dirty",e.focused="data-focused",e})({});const xBr='!function(){const t=document.currentScript?.parentElement;if(!t)return;const e=t.closest("[data-base-ui-slider-control]");if(!e)return;const r=e.querySelector("[data-base-ui-slider-indicator]"),i=e.getBoundingClientRect(),n="vertical"===e.getAttribute("data-orientation")?"height":"width",o=e.querySelectorAll(\'input[type="range"]\'),l=o.length>1,s=o.length-1;let a=null,u=null;for(let t=0;t<o.length;t+=1){const e=o[t],y=parseFloat(e.getAttribute("value")??"");if(Number.isNaN(y))return;const c=e.parentElement;if(!c)return;const p=parseFloat(e.getAttribute("max")??"100"),g=parseFloat(e.getAttribute("min")??"0"),b=c?.getBoundingClientRect(),d=i[n]-b[n],m=100*(y-g)/(p-g),v=(b[n]/2+d*m/100)/i[n]*100;c.style.setProperty("--position",`${v}%`),Number.isFinite(v)&&(c.style.removeProperty("visibility"),r&&(0===t?(a=v,r.style.setProperty("--start-position",`${v}%`),l||r.style.removeProperty("visibility")):t===s&&(u=v-(a??0),r.style.setProperty("--end-position",`${v}%`),r.style.setProperty("--relative-size",`${u}%`),r.style.removeProperty("visibility"))))}}();',wBr=new Set([...J1,vyt,yyt]);function SBr(e,t,n,r){if(!(t<0))return e.length===2?t===0?`${g9(e[t],r,n)} start range`:`${g9(e[t],r,n)} end range`:n?g9(e[t],r,n):void 0}function IE(e,t,n,r,s){const a=n===1?e+t:e-t,i=Number(a.toFixed(Math.max(H2(e),H2(t),H2(r))));return js(i,r,s)}const kBr=v.forwardRef(function(t,n){const{render:r,children:s,className:a,"aria-describedby":i,"aria-label":l,"aria-labelledby":c,disabled:u=!1,getAriaLabel:d,getAriaValueText:f,id:p,index:h,inputRef:m,onBlur:g,onFocus:y,onKeyDown:b,tabIndex:x,style:S,...k}=t,{nonce:C}=SH(),_=Vi(p),{active:E,lastUsedThumbIndex:T,controlRef:N,disabled:I,validation:A,formatOptionsRef:R,handleInputChange:L,inset:D,labelId:z,largeStep:H,locale:F,max:U,min:q,minStepsBetweenValues:M,form:G,name:V,orientation:$,pressedInputRef:B,pressedThumbCenterOffsetRef:Z,pressedThumbIndexRef:K,renderBeforeHydration:ne,setActive:ee,setIndicatorPosition:J,state:ae,step:fe,values:Y}=eG(),re=Ly(),le=u||I,ue=Y.length>1,oe=$==="vertical",me=re==="rtl",{setTouched:be,setFocused:xe,validationMode:Ce}=Em(),ke=v.useRef(null),Ne=v.useRef(null),$e=v.useRef(!1),de=Vi(),te=W_(),se=ue?de:te,he=v.useMemo(()=>({inputId:se}),[se]),{ref:we,index:Te}=s0({metadata:he}),Re=ue?h??Te:0,Ze=Re===Y.length-1,Ge=Y[Re],je=Cbe(Ge,q,U),[Ee,Oe]=v.useState(),Ie=CCe(),Me=T>=0&&T<Y.length?T:-1,Ue=wt(()=>{const ct=N.current,pt=ke.current;if(!ct||!pt)return;const Zt=pt.getBoundingClientRect(),Gt=ct.getBoundingClientRect(),xn=oe?"height":"width",Ae=Gt[xn]-Zt[xn],Le=(Zt[xn]/2+Ae*je/100)/Gt[xn]*100,et=Number.isFinite(Le)?Le:void 0;Oe(et),Re===0?J(rt=>[et,rt[1]]):Ze&&J(rt=>[rt[0],et])});$t(()=>{D&&queueMicrotask(Ue)},[Ue,D]),$t(()=>{D&&Ue()},[Ue,D,je]),$t(()=>{if(!D)return;const ct=N.current,pt=ke.current;if(!ct||!pt)return;const Zt=ta(ct).ResizeObserver;if(typeof Zt!="function")return;const Gt=new Zt(Ue);return Gt.observe(ct),Gt.observe(pt),()=>{Gt.disconnect()}},[N,Ue,D]);const Je=oe?"bottom":"insetInlineStart",tt=oe?"left":"top";let Dt;ue?E===Re?Dt=2:Me===Re&&(Dt=1):E===Re&&(Dt=1);let at;D?at={"--position":`${Ee??0}%`,visibility:ne&&Ie||Ee===void 0?"hidden":void 0,position:"absolute",[Je]:"var(--position)",[tt]:"50%",translate:`${(oe||!me?-1:1)*50}% ${(oe?1:-1)*50}%`,zIndex:Dt}:at=Number.isFinite(je)?{position:"absolute",[Je]:`${je}%`,[tt]:"50%",translate:`${(oe||!me?-1:1)*50}% ${(oe?1:-1)*50}%`,zIndex:Dt}:g1;let gt;$==="vertical"&&(gt=me?"vertical-rl":"vertical-lr");const ht=typeof d=="function"?d(Re):l,Ct=Bo({"aria-label":ht,"aria-labelledby":c??(ht==null?z:void 0),"aria-describedby":i,"aria-orientation":$,"aria-valuenow":Ge,"aria-valuetext":typeof f=="function"?f(g9(Ge,F,R.current??void 0),Ge,Re):SBr(Y,Re,R.current??void 0,F),disabled:le,form:G,id:se,max:U,min:q,name:V,onChange(ct){L(ct.currentTarget.valueAsNumber,Re,ct)},onFocus(ct){const pt=$e.current;$e.current=!1,ee(Re),xe(!0),pt&&ct.stopPropagation()},onBlur(ct){if($e.current){ct.stopPropagation();return}ke.current&&(ee(-1),be(!0),xe(!1),Ce==="onBlur"&&A.commit(J3t(Ge,Re,q,U,ue,Y)))},onKeyDown(ct){if(!wBr.has(ct.key))return;J1.has(ct.key)&&ct.stopPropagation();let pt=null;const Zt=r4t(Ge,fe,q);switch(ct.key){case zT:pt=IE(Zt,ct.shiftKey?H:fe,1,q,U);break;case FT:pt=IE(Zt,ct.shiftKey?H:fe,me?-1:1,q,U);break;case Dk:pt=IE(Zt,ct.shiftKey?H:fe,-1,q,U);break;case q$:pt=IE(Zt,ct.shiftKey?H:fe,me?1:-1,q,U);break;case vyt:pt=IE(Zt,H,1,q,U);break;case yyt:pt=IE(Zt,H,-1,q,U);break;case j3:pt=U,ue&&(pt=Number.isFinite(Y[Re+1])?Y[Re+1]-fe*M:U);break;case T3:pt=q,ue&&(pt=Number.isFinite(Y[Re-1])?Y[Re-1]+fe*M:q);break}if(pt!==null){const Gt=ct.currentTarget;Umt(Gt)||($e.current=!0,Gt.blur(),Gt.focus({preventScroll:!0,focusVisible:!0})),L(pt,Re,ct),ct.preventDefault()}},step:fe,style:{...g1,width:"100%",height:"100%",writingMode:gt},tabIndex:x??void 0,type:"range",value:Ge??""},A.getInputValidationProps),tn=Yu(Ne,A.inputRef,m);return Nn("div",t,{state:ae,ref:[n,we,ke],props:[{[bBr.index]:Re,children:o.jsxs(v.Fragment,{children:[s,o.jsx("input",{ref:tn,...Ct,suppressHydrationWarning:!0}),D&&Ie&&ne&&Ze&&o.jsx("script",{nonce:C,dangerouslySetInnerHTML:{__html:xBr},suppressHydrationWarning:!0})]}),id:_,onBlur:g,onFocus:y,onPointerDown(ct){if(K.current=Re,ke.current!=null){const pt=$==="horizontal"?"x":"y",Zt=n4t(ke.current),Gt=($==="horizontal"?ct.clientX:ct.clientY)-Zt[pt];Z.current=Gt}Ne.current!=null&&B.current!==Ne.current&&(B.current=Ne.current)},style:at,suppressHydrationWarning:ne||void 0},k],stateAttributesMapping:Q4})});function OBr(e,t,n,r,s,a){const i=n===void 0||t&&r===void 0?"hidden":void 0,l=e?"bottom":"insetInlineStart",c=e?"height":"width",d={visibility:s&&a?"hidden":i,position:e?"absolute":"relative",[e?"width":"height"]:"inherit"};return d["--start-position"]=`${n??0}%`,t?(d["--relative-size"]=`${(r??0)-(n??0)}%`,d[l]="var(--start-position)",d[c]="var(--relative-size)",d):(d[l]=0,d[c]="var(--start-position)",d)}function _Br(e,t,n,r){const s=e?"bottom":"insetInlineStart",a=e?"height":"width",l={position:e?"absolute":"relative",[e?"width":"height"]:"inherit"};if(!t)return l[s]=0,l[a]=`${n}%`,l;const c=r-n;return l[s]=`${n}%`,l[a]=`${c}%`,l}const CBr=v.forwardRef(function(t,n){const{render:r,className:s,style:a,...i}=t,{indicatorPosition:l,inset:c,max:u,min:d,orientation:f,renderBeforeHydration:p,state:h,values:m}=eG(),g=CCe(),y=f==="vertical",b=m.length>1,x=c?OBr(y,b,l[0],l[1],p,g):_Br(y,b,Cbe(m[0],d,u),Cbe(m[m.length-1],d,u));return Nn("div",t,{state:h,ref:n,props:[{"data-base-ui-slider-indicator":p?"":void 0,style:x,suppressHydrationWarning:p||void 0},i],stateAttributesMapping:Q4})});function DKe(e){return typeof e=="number"?[e]:[...e]}const Ebe=({className:e,defaultValue:t,value:n,min:r=0,max:s=100,onValueChange:a,onValueCommitted:i,...l})=>{const c=Array.isArray(n)?n:Array.isArray(t)?t:[r];return o.jsx(fBr,{className:X("w-full",e),defaultValue:t,value:n,min:r,max:s,thumbAlignment:"edge",onValueChange:a?(u,d)=>a(DKe(u),d):void 0,onValueCommitted:i?(u,d)=>i(DKe(u),d):void 0,...l,children:o.jsxs(vBr,{className:X("group relative flex w-full cursor-pointer touch-none items-center select-none","data-[orientation=horizontal]:py-3","data-[orientation=vertical]:h-full data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col data-[orientation=vertical]:px-3","data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50"),children:[o.jsx(yBr,{className:X("relative grow overflow-hidden rounded-full bg-neutral6/20 select-none","data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full","data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"),children:o.jsx(CBr,{className:X("bg-neutral6 select-none","data-[orientation=horizontal]:h-full","data-[orientation=vertical]:w-full")})}),c.map((u,d)=>o.jsx(kBr,{index:d,className:X("relative block h-5 w-2.5 shrink-0 rounded-full border-2 border-neutral6 bg-neutral2 outline-hidden select-none",'after:absolute after:-inset-2 after:content-[""]',"duration-normal transition-shadow","hover:ring-2 hover:ring-neutral6/30","has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-neutral6/60","data-[orientation=vertical]:h-2.5 data-[orientation=vertical]:w-5","data-[disabled]:pointer-events-none")},d))]})})},GTe=v.forwardRef(({className:e,...t},n)=>{const{zoom:r}=AXn(),{zoomTo:s,zoomIn:a,zoomOut:i,fitView:l}=e4();return o.jsxs(J3,{ref:n,className:X("flex items-center gap-1 rounded-full border border-border1 bg-surface2 p-1 text-neutral6",e),...t,children:[o.jsx(ce,{size:"icon-sm",tooltip:"Zoom out",onClick:()=>i({duration:300}),children:o.jsx(rQt,{})}),o.jsx(Ebe,{className:"w-[140px]",value:[r],min:.01,max:1,step:.01,onValueChange:c=>{s(c[0])}}),o.jsx(ce,{size:"icon-sm",tooltip:"Zoom in",onClick:()=>a({duration:300}),children:o.jsx(Wr,{})}),o.jsxs(ce,{size:"sm",className:"min-w-16 tabular-nums",onClick:()=>s(1,{duration:300}),children:[(100*r).toFixed(0),"%"]}),o.jsx(ce,{size:"icon-sm",tooltip:"Fit view",onClick:()=>l({duration:300,maxZoom:1}),children:o.jsx(VGt,{})})]})});GTe.displayName="ZoomSlider";function EBr({workflow:e}){const{nodes:t,edges:n}=rOe(e),[r,s,a]=IOt(t),[i]=AOt(n),{edgeTypes:l,nodeTypes:c,styledEdges:u}=Y3t({edges:i}),d=v.useRef(null),{selectedStepId:f}=kH(),p=aOe(),h=fJn(),{getNodes:m,setCenter:g}=e4(),y=f??p??h,b=v.useEffectEvent(x=>{const S=cJn(m(),x);if(!S)return;d.current?.focus({preventScroll:!0});const k=S.measured?.width??S.width??274,C=S.measured?.height??S.height??100;g(S.position.x+k/2,S.position.y+C/2,{duration:300,zoom:1})});return v.useEffect(()=>{y&&b(y)},[y,r]),o.jsx("div",{ref:d,tabIndex:-1,"data-testid":"workflow-graph-viewport",className:"bg-surface2 h-full w-full outline-none",children:o.jsxs(NOt,{nodes:r,edges:u,edgeTypes:l,nodeTypes:c,onNodesChange:a,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,children:[o.jsx(GTe,{position:"bottom-left"}),o.jsx(POt,{variant:ly.Dots,gap:12,size:.5})]})})}function s4t({workflowId:e,workflow:t,isLoading:n}){const{snapshot:r}=v.useContext(Vl);return n?o.jsx("div",{className:"p-4",children:o.jsx(kt,{className:"h-full"})}):t?o.jsx(nOe,{children:o.jsx(EBr,{workflow:r?.serializedStepGraph?{stepGraph:r?.serializedStepGraph}:t})}):o.jsx("div",{className:"grid h-full place-items-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx(vj,{}),o.jsxs("div",{children:["We couldn't find ",L9r(e)," workflow."]})]})})}function Qh(e,t){return e.length<=t?e:e.slice(0,t)+"…"}const TBr=5e3,jBr={};function NBr(e){return e instanceof Tx&&e.status===404}function IBr(e){return NBr(e)?!1:TBr}const ABr=()=>{const e=We(),{requestContext:t}=hs(),{data:n}=yt({queryKey:["workflow-run-counts",t],queryFn:()=>e.listWorkflowRunCounts(t),retry:!1,refetchInterval:r=>IBr(r.state.error)});return n??jBr};function RBr(e){return Object.keys(e.steps??{}).filter(t=>e.allSteps?.[t]?.isWorkflow)}function PBr(e){const t=new Map;for(const[n,r]of Object.entries(e))t.set(n,n),r.name&&t.set(r.name,n);return t}function $Br(e,t,n){const r=PBr(t),s=[],a=(i,l,c,u,d,f)=>{const p=RBr(i).filter(g=>{const y=r.get(g);return y===void 0||!u.has(y)});if(s.push({kind:"workflow",workflow:i,pathKey:l,depth:c,nestedIds:p,guides:d,isLastChild:f}),!n.has(l)||p.length===0)return;const h=new Set(u).add(i.id),m=c===0?[]:[...d,!f];for(const[g,y]of p.entries()){const b=g===p.length-1,x=r.get(y);if(x===void 0){s.push({kind:"inline",stepId:y,description:i.allSteps?.[y]?.description,pathKey:`${l}/${y}`,depth:c+1,guides:m,isLastChild:b});continue}a({...t[x],id:x},`${l}/${x}`,c+1,h,m,b)}};for(const i of e)a(i,i.id,0,new Set([i.id]),[],!1);return s}const LKe="auto 24rem minmax(0, 1fr) auto auto auto";function zKe({guides:e,isLastChild:t}){return o.jsxs("span",{"aria-hidden":!0,className:"-my-6 flex shrink-0 self-stretch",children:[e.map((n,r)=>o.jsx("span",{className:X("w-6",n&&"border-l border-border1")},r)),o.jsxs("span",{className:"relative w-6",children:[o.jsx("span",{className:X("absolute left-0 top-0 border-l border-border1",t?"h-1/2":"h-full")}),o.jsx("span",{className:"border-border1 absolute top-1/2 left-0 w-3.5 border-b"})]})]})}function FKe({row:e,isExpanded:t,onToggle:n}){const r=e.kind==="workflow"&&e.nestedIds.length>0,s=e.kind==="workflow"?e.workflow.name:e.stepId;return o.jsx("div",{className:"flex items-center pl-5",children:r?o.jsx("button",{type:"button","aria-expanded":t,"aria-label":`${t?"Collapse":"Expand"} nested workflows of ${s}`,className:"text-neutral4 hover:text-neutral2 relative grid size-5 shrink-0 place-items-center before:absolute before:-inset-1.5 before:content-['']",onClick:n,children:o.jsx(aa,{className:X("size-4 transition-transform",t&&"rotate-90")})}):o.jsx("span",{className:"size-5 shrink-0","aria-hidden":!0})})}function MBr({workflows:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=bn(),[a,i]=v.useState(new Set),l=v.useMemo(()=>Object.keys(e).map(p=>({...e[p],id:p})),[e]),c=v.useMemo(()=>{const p=n.toLowerCase();return l.filter(h=>h.name?.toLowerCase().includes(p)||h.description?.toLowerCase().includes(p))},[l,n]),u=v.useMemo(()=>$Br(c,e,a),[c,e,a]),d=ABr(),f=p=>{i(h=>{const m=new Set(h);return m.has(p)?m.delete(p):m.add(p),m})};return t?o.jsx(ll,{columns:LKe,fit:"container"}):o.jsxs(ge,{columns:LKe,fit:"container",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:o.jsx("span",{className:"sr-only",children:"Expand"})}),o.jsx(ge.TopCell,{children:"Name"}),o.jsx(ge.TopCell,{children:"Description"}),o.jsx(ge.TopCell,{children:"Running"}),o.jsx(ge.TopCell,{children:"Pending input"}),o.jsx(ge.TopCell,{children:"Number of steps"})]}),u.length===0&&n?o.jsx(ge.NoMatch,{message:"No Workflows match your search"}):null,u.map(p=>{const h=a.has(p.pathKey),m=()=>f(p.pathKey);if(p.kind==="inline")return o.jsxs(ge.RowWrapper,{children:[o.jsx(FKe,{row:p,isExpanded:h,onToggle:m}),o.jsxs("div",{className:"col-span-5 col-start-2 grid grid-cols-subgrid gap-8 px-5",children:[o.jsx(ge.NameCell,{children:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(zKe,{guides:p.guides,isLastChild:p.isLastChild}),o.jsx("span",{className:"truncate",children:Qh(p.stepId,50)}),o.jsx("span",{title:"Nested workflow not registered standalone",className:"text-ui-smd text-neutral4 shrink-0",children:"inline"})]})}),o.jsx(ge.DescriptionCell,{children:Qh(p.description??"",200)}),o.jsx(ge.TextCell,{className:"text-center",children:""}),o.jsx(ge.TextCell,{className:"text-center",children:""}),o.jsx(ge.TextCell,{className:"text-center",children:""})]})]},`workflow-${p.pathKey}`);const{workflow:g,pathKey:y,nestedIds:b}=p,x=Qh(g.name,50),S=Qh(g.description??"",200),k=Object.keys(g.steps??{}).length,C=d[g.id]?.running??0,_=d[g.id]?.suspended??0,E=b.length>0;return o.jsxs(ge.RowWrapper,{children:[o.jsx(FKe,{row:p,isExpanded:h,onToggle:m}),o.jsxs(ge.RowLink,{colStart:2,to:r.workflowLink(g.id),LinkComponent:s,children:[o.jsx(ge.NameCell,{children:o.jsxs("span",{className:"flex items-center gap-1.5",children:[p.depth>0?o.jsx(zKe,{guides:p.guides,isLastChild:p.isLastChild}):null,o.jsx("span",{className:"truncate",children:x}),g.origin==="dynamic"?o.jsx(on,{size:"xs",variant:"info",title:"Registered via the dynamic-workflows API",children:"Dynamic"}):null,E?o.jsxs("span",{title:`Nested workflows: ${b.join(", ")}`,className:"text-ui-smd text-neutral4 inline-flex shrink-0 items-center gap-1",children:[o.jsx(XN,{"aria-hidden":!0,className:"size-3.5"}),b.length]}):null]})}),o.jsx(ge.DescriptionCell,{children:S}),o.jsx(ge.TextCell,{className:"text-center",children:C>0?o.jsxs("span",{className:"text-positive1 inline-flex items-center gap-1.5","aria-label":`${C} run${C===1?"":"s"} in progress`,children:[o.jsx("span",{"aria-hidden":!0,className:"bg-positive1 size-2 rounded-full motion-safe:animate-pulse"}),C]}):""}),o.jsx(ge.TextCell,{className:"text-center",children:_>0?o.jsxs("span",{className:"text-warning1 inline-flex items-center gap-1.5","aria-label":`${_} run${_===1?"":"s"} awaiting input`,children:[o.jsx(cV,{"aria-hidden":!0,className:"size-3.5"}),_]}):""}),o.jsx(ge.TextCell,{className:"text-center",children:k||""})]})]},`workflow-${y}`)})]})}const DBr=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx($f,{}),titleSlot:"No Workflows yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra workflows are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/workflows/overview",target:"_blank",rel:"noopener noreferrer",children:["Workflows Documentation ",o.jsx(_a,{})]})})});function LBr({value:e,onValueChange:t,placeholder:n="Select a workflow...",searchPlaceholder:r="Search workflows...",emptyText:s="No workflows found.",className:a,disabled:i=!1,variant:l}){const{data:c={},isLoading:u,isError:d,error:f}=Ky(),{navigate:p,paths:h}=bn();v.useEffect(()=>{if(d){const y=f instanceof Error?f.message:"Failed to load workflows";De.error(`Error loading workflows: ${y}`)}},[d,f]);const m=Object.keys(c).map(y=>({label:c[y]?.name||y,value:y})),g=y=>{t?t(y):y&&y!==e&&p(h.workflowLink(y))};return o.jsx(Fl,{options:m,value:e,onValueChange:g,placeholder:u?"Loading workflows...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||d,variant:l})}const zBr=({result:e,workflowId:t,isStreaming:n,metadata:r,toolCallId:s,toolApprovalMetadata:a,suspendPayload:i,toolName:l,isNetwork:c,toolCalled:u})=>{const{runId:d,status:f}=e||{},{data:p,isLoading:h}=n4(t),{data:m,isLoading:g}=d_t(t,{enabled:!!d&&!n}),y=m?.find(T=>T.runId===d),b=g||!y,x=typeof y?.snapshot=="object"?y?.snapshot:void 0,S=r?.mode==="network"?r.routingDecision:void 0,k=r?.mode==="network"?S?.selectionReason??r.selectionReason:void 0,C=r?.mode==="network"?S??r.agentInput:void 0,_=(r?.mode==="stream"||r?.mode==="generate")&&r?.backgroundTasks?r.backgroundTasks[s]:void 0;let E=typeof i=="string"?o.jsx("pre",{className:"bg-surface4 overflow-x-auto rounded-md p-4 whitespace-pre",children:i}):o.jsx(Hr,{data:i,"data-testid":"tool-suspend-payload"});return h||!p?o.jsx(HTe,{}):o.jsxs(Z4,{"data-testid":"workflow-badge",icon:o.jsx(rd,{className:"text-accent3"}),title:p.name,initialCollapsed:!1,extraInfo:r?.mode==="network"?o.jsx(VTe,{selectionReason:k??"",input:C}):_?.taskId&&_?.startedAt?o.jsx(qTe,{backgroundTask:_}):null,children:[!n&&!b&&o.jsx(xOe,{snapshot:x,workflowId:t,initialRunId:d,withoutTimeTravel:!0,children:o.jsx(BKe,{workflowId:t,workflow:p,runId:d})}),n&&o.jsx(BKe,{workflowId:t,workflow:p,runId:d}),E!==void 0&&i&&o.jsxs("div",{children:[o.jsx("p",{className:"pb-2 font-medium",children:"Workflow suspend payload"}),E]}),o.jsx(KI,{toolCalled:u??!!f,toolCallId:s,toolApprovalMetadata:a,toolName:l,isNetwork:c,isGenerateMode:r?.mode==="generate"})]})},BKe=({workflowId:e,workflow:t,runId:n})=>{const{Link:r}=bn();return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[o.jsx(ce,{as:r,href:`/workflows/${e}/graph`,children:"Go to workflow"}),n&&o.jsx(ce,{as:r,href:`/workflows/${e}/graph/${n}`,children:"See run"})]}),o.jsx("div",{className:"h-[60vh] w-full overflow-hidden rounded-md",children:o.jsx(K_t,{children:o.jsx(wOe,{children:o.jsx(s4t,{workflowId:e,workflow:t})})})})]})},FBr=e=>{const{setResult:t}=v.useContext(Vl);v.useEffect(()=>{e&&t(e)},[e,t])};function _t(e,t,n){function r(l,c){var u;Object.defineProperty(l,"_zod",{value:l._zod??{},enumerable:!1}),(u=l._zod).traits??(u.traits=new Set),l._zod.traits.add(e),t(l,c);for(const d in i.prototype)d in l||Object.defineProperty(l,d,{value:i.prototype[d].bind(l)});l._zod.constr=i,l._zod.def=c}const s=n?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:e});function i(l){var c;const u=n?.Parent?new a:this;r(u,l),(c=u._zod).deferred??(c.deferred=[]);for(const d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class _D extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const a4t={};function $1(e){return a4t}function BBr(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,s])=>t.indexOf(+r)===-1).map(([r,s])=>s)}function UBr(e,t){return typeof t=="bigint"?t.toString():t}function QTe(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function YTe(e){return e==null}function KTe(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function qBr(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,a=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return a%i/10**s}function so(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function tG(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function uP(e){return JSON.stringify(e)}const i4t=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Pq(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const VBr=QTe(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function $q(e){if(Pq(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(Pq(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const HBr=new Set(["string","number","symbol"]);function Y4(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gC(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function sr(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function WBr(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const ZBr={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function GBr(e,t){const n={},r=e._zod.def;for(const s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(n[s]=r.shape[s])}return gC(e,{...e._zod.def,shape:n,checks:[]})}function QBr(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&delete n[s]}return gC(e,{...e._zod.def,shape:n,checks:[]})}function YBr(e,t){if(!$q(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return tG(this,"shape",r),r},checks:[]};return gC(e,n)}function KBr(e,t){return gC(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return tG(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function XBr(e,t,n){const r=t._zod.def.shape,s={...r};if(n)for(const a in n){if(!(a in r))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(s[a]=e?new e({type:"optional",innerType:r[a]}):r[a])}else for(const a in r)s[a]=e?new e({type:"optional",innerType:r[a]}):r[a];return gC(t,{...t._zod.def,shape:s,checks:[]})}function JBr(e,t,n){const r=t._zod.def.shape,s={...r};if(n)for(const a in n){if(!(a in s))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(s[a]=new e({type:"nonoptional",innerType:r[a]}))}else for(const a in r)s[a]=new e({type:"nonoptional",innerType:r[a]});return gC(t,{...t._zod.def,shape:s,checks:[]})}function W2(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Qk(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function _F(e){return typeof e=="string"?e:e?.message}function M1(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const s=_F(e.inst?._zod.def?.error?.(e))??_F(t?.error?.(e))??_F(n.customError?.(e))??_F(n.localeError?.(e))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function XTe(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function CD(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const o4t=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,UBr,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},l4t=_t("$ZodError",o4t),c4t=_t("$ZodError",o4t,{Parent:Error});function eUr(e,t=n=>n.message){const n={},r=[];for(const s of e.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}function tUr(e,t){const n=t||function(a){return a.message},r={_errors:[]},s=a=>{for(const i of a.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(l=>s({issues:l}));else if(i.code==="invalid_key")s({issues:i.issues});else if(i.code==="invalid_element")s({issues:i.issues});else if(i.path.length===0)r._errors.push(n(i));else{let l=r,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(n(i))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return s(e),r}const nUr=e=>(t,n,r,s)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new _D;if(i.issues.length){const l=new(s?.Err??e)(i.issues.map(c=>M1(c,a,$1())));throw i4t(l,s?.callee),l}return i.value},rUr=e=>async(t,n,r,s)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const l=new(s?.Err??e)(i.issues.map(c=>M1(c,a,$1())));throw i4t(l,s?.callee),l}return i.value},u4t=e=>(t,n,r)=>{const s=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new _D;return a.issues.length?{success:!1,error:new(e??l4t)(a.issues.map(i=>M1(i,s,$1())))}:{success:!0,data:a.value}},d4t=u4t(c4t),f4t=e=>async(t,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>M1(i,s,$1())))}:{success:!0,data:a.value}},sUr=f4t(c4t),aUr=/^[cC][^\s-]{8,}$/,iUr=/^[0-9a-z]+$/,oUr=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lUr=/^[0-9a-vA-V]{20}$/,cUr=/^[A-Za-z0-9]{27}$/,uUr=/^[a-zA-Z0-9_-]{21}$/,dUr=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,fUr=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,UKe=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,pUr=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,hUr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function mUr(){return new RegExp(hUr,"u")}const gUr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,vUr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,yUr=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bUr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xUr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,p4t=/^[A-Za-z0-9_-]*$/,wUr=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,SUr=/^\+(?:[0-9]){6,14}[0-9]$/,h4t="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",kUr=new RegExp(`^${h4t}$`);function m4t(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function OUr(e){return new RegExp(`^${m4t(e)}$`)}function _Ur(e){const t=m4t({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${h4t}T(?:${r})$`)}const CUr=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},EUr=/^\d+$/,TUr=/^-?\d+(?:\.\d+)?/i,jUr=/true|false/i,NUr=/null/i,IUr=/^[^A-Z]*$/,AUr=/^[^a-z]*$/,Wf=_t("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),g4t={number:"number",bigint:"bigint",object:"date"},v4t=_t("$ZodCheckLessThan",(e,t)=>{Wf.init(e,t);const n=g4t[typeof t.value];e._zod.onattach.push(r=>{const s=r._zod.bag,a=(t.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?s.maximum=t.value:s.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),y4t=_t("$ZodCheckGreaterThan",(e,t)=>{Wf.init(e,t);const n=g4t[typeof t.value];e._zod.onattach.push(r=>{const s=r._zod.bag,a=(t.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?s.minimum=t.value:s.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),RUr=_t("$ZodCheckMultipleOf",(e,t)=>{Wf.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):qBr(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),PUr=_t("$ZodCheckNumberFormat",(e,t)=>{Wf.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[s,a]=ZBr[t.format];e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,l.minimum=s,l.maximum=a,n&&(l.pattern=EUr)}),e._zod.check=i=>{const l=i.value;if(n){if(!Number.isInteger(l)){i.issues.push({expected:r,format:t.format,code:"invalid_type",input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?i.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):i.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}l<s&&i.issues.push({origin:"number",input:l,code:"too_small",minimum:s,inclusive:!0,inst:e,continue:!t.abort}),l>a&&i.issues.push({origin:"number",input:l,code:"too_big",maximum:a,inst:e})}}),$Ur=_t("$ZodCheckMaxLength",(e,t)=>{var n;Wf.init(e,t),(n=e._zod.def).when??(n.when=r=>{const s=r.value;return!YTe(s)&&s.length!==void 0}),e._zod.onattach.push(r=>{const s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<s&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const s=r.value;if(s.length<=t.maximum)return;const i=XTe(s);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),MUr=_t("$ZodCheckMinLength",(e,t)=>{var n;Wf.init(e,t),(n=e._zod.def).when??(n.when=r=>{const s=r.value;return!YTe(s)&&s.length!==void 0}),e._zod.onattach.push(r=>{const s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>s&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const s=r.value;if(s.length>=t.minimum)return;const i=XTe(s);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),DUr=_t("$ZodCheckLengthEquals",(e,t)=>{var n;Wf.init(e,t),(n=e._zod.def).when??(n.when=r=>{const s=r.value;return!YTe(s)&&s.length!==void 0}),e._zod.onattach.push(r=>{const s=r._zod.bag;s.minimum=t.length,s.maximum=t.length,s.length=t.length}),e._zod.check=r=>{const s=r.value,a=s.length;if(a===t.length)return;const i=XTe(s),l=a>t.length;r.issues.push({origin:i,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),nG=_t("$ZodCheckStringFormat",(e,t)=>{var n,r;Wf.init(e,t),e._zod.onattach.push(s=>{const a=s._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=s=>{t.pattern.lastIndex=0,!t.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:t.format,input:s.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),LUr=_t("$ZodCheckRegex",(e,t)=>{nG.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),zUr=_t("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=IUr),nG.init(e,t)}),FUr=_t("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=AUr),nG.init(e,t)}),BUr=_t("$ZodCheckIncludes",(e,t)=>{Wf.init(e,t);const n=Y4(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(s=>{const a=s._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),e._zod.check=s=>{s.value.includes(t.includes,t.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:s.value,inst:e,continue:!t.abort})}}),UUr=_t("$ZodCheckStartsWith",(e,t)=>{Wf.init(e,t);const n=new RegExp(`^${Y4(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),qUr=_t("$ZodCheckEndsWith",(e,t)=>{Wf.init(e,t);const n=new RegExp(`.*${Y4(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),VUr=_t("$ZodCheckOverwrite",(e,t)=>{Wf.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class HUr{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
573
573
  `).filter(i=>i),s=Math.min(...r.map(i=>i.length-i.trimStart().length)),a=r.map(i=>i.slice(s)).map(i=>" ".repeat(this.indent*2)+i);for(const i of a)this.content.push(i)}compile(){const t=Function,n=this?.args,s=[...(this?.content??[""]).map(a=>` ${a}`)];return new t(...n,s.join(`
574
574
  `))}}const WUr={major:4,minor:0,patch:0},lo=_t("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=WUr;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const s of r)for(const a of s._zod.onattach)a(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const s=(a,i,l)=>{let c=W2(a),u;for(const d of i){if(d._zod.def.when){if(!d._zod.def.when(a))continue}else if(c)continue;const f=a.issues.length,p=d._zod.check(a);if(p instanceof Promise&&l?.async===!1)throw new _D;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,a.issues.length!==f&&(c||(c=W2(a,f)))});else{if(a.issues.length===f)continue;c||(c=W2(a,f))}}return u?u.then(()=>a):a};e._zod.run=(a,i)=>{const l=e._zod.parse(a,i);if(l instanceof Promise){if(i.async===!1)throw new _D;return l.then(c=>s(c,r,i))}return s(l,r,i)}}e["~standard"]={validate:s=>{try{const a=d4t(e,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return sUr(e,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),JTe=_t("$ZodString",(e,t)=>{lo.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??CUr(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ao=_t("$ZodStringFormat",(e,t)=>{nG.init(e,t),JTe.init(e,t)}),ZUr=_t("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=fUr),Ao.init(e,t)}),GUr=_t("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=UKe(r))}else t.pattern??(t.pattern=UKe());Ao.init(e,t)}),QUr=_t("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=pUr),Ao.init(e,t)}),YUr=_t("$ZodURL",(e,t)=>{Ao.init(e,t),e._zod.check=n=>{try{const r=n.value,s=new URL(r),a=s.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:wUr.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&a.endsWith("/")?n.value=a.slice(0,-1):n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),KUr=_t("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=mUr()),Ao.init(e,t)}),XUr=_t("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=uUr),Ao.init(e,t)}),JUr=_t("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=aUr),Ao.init(e,t)}),eqr=_t("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=iUr),Ao.init(e,t)}),tqr=_t("$ZodULID",(e,t)=>{t.pattern??(t.pattern=oUr),Ao.init(e,t)}),nqr=_t("$ZodXID",(e,t)=>{t.pattern??(t.pattern=lUr),Ao.init(e,t)}),rqr=_t("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=cUr),Ao.init(e,t)}),sqr=_t("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=_Ur(t)),Ao.init(e,t)}),aqr=_t("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=kUr),Ao.init(e,t)}),iqr=_t("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=OUr(t)),Ao.init(e,t)}),oqr=_t("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=dUr),Ao.init(e,t)}),lqr=_t("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=gUr),Ao.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),cqr=_t("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=vUr),Ao.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),uqr=_t("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=yUr),Ao.init(e,t)}),dqr=_t("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=bUr),Ao.init(e,t),e._zod.check=n=>{const[r,s]=n.value.split("/");try{if(!s)throw new Error;const a=Number(s);if(`${a}`!==s)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function b4t(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const fqr=_t("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=xUr),Ao.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{b4t(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function pqr(e){if(!p4t.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return b4t(n)}const hqr=_t("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=p4t),Ao.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{pqr(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),mqr=_t("$ZodE164",(e,t)=>{t.pattern??(t.pattern=SUr),Ao.init(e,t)});function gqr(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||t&&(!("alg"in s)||s.alg!==t))}catch{return!1}}const vqr=_t("$ZodJWT",(e,t)=>{Ao.init(e,t),e._zod.check=n=>{gqr(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),x4t=_t("$ZodNumber",(e,t)=>{lo.init(e,t),e._zod.pattern=e._zod.bag.pattern??TUr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const s=n.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return n;const a=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:e,...a?{received:a}:{}}),n}}),yqr=_t("$ZodNumber",(e,t)=>{PUr.init(e,t),x4t.init(e,t)}),bqr=_t("$ZodBoolean",(e,t)=>{lo.init(e,t),e._zod.pattern=jUr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const s=n.value;return typeof s=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:e}),n}}),xqr=_t("$ZodNull",(e,t)=>{lo.init(e,t),e._zod.pattern=NUr,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const s=n.value;return s===null||n.issues.push({expected:"null",code:"invalid_type",input:s,inst:e}),n}}),wqr=_t("$ZodUnknown",(e,t)=>{lo.init(e,t),e._zod.parse=n=>n}),Sqr=_t("$ZodNever",(e,t)=>{lo.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function qKe(e,t,n){e.issues.length&&t.issues.push(...Qk(n,e.issues)),t.value[n]=e.value}const kqr=_t("$ZodArray",(e,t)=>{lo.init(e,t),e._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),n;n.value=Array(s.length);const a=[];for(let i=0;i<s.length;i++){const l=s[i],c=t.element._zod.run({value:l,issues:[]},r);c instanceof Promise?a.push(c.then(u=>qKe(u,n,i))):qKe(c,n,i)}return a.length?Promise.all(a).then(()=>n):n}});function CF(e,t,n){e.issues.length&&t.issues.push(...Qk(n,e.issues)),t.value[n]=e.value}function VKe(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...Qk(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const Oqr=_t("$ZodObject",(e,t)=>{lo.init(e,t);const n=QTe(()=>{const f=Object.keys(t.shape);for(const h of f)if(!(t.shape[h]instanceof lo))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);const p=WBr(t.shape);return{shape:t.shape,keys:f,keySet:new Set(f),numKeys:f.length,optionalKeys:new Set(p)}});so(e._zod,"propValues",()=>{const f=t.shape,p={};for(const h in f){const m=f[h]._zod;if(m.values){p[h]??(p[h]=new Set);for(const g of m.values)p[h].add(g)}}return p});const r=f=>{const p=new HUr(["shape","payload","ctx"]),h=n.value,m=x=>{const S=uP(x);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`};p.write("const input = payload.value;");const g=Object.create(null);let y=0;for(const x of h.keys)g[x]=`key_${y++}`;p.write("const newResult = {}");for(const x of h.keys)if(h.optionalKeys.has(x)){const S=g[x];p.write(`const ${S} = ${m(x)};`);const k=uP(x);p.write(`
575
575
  if (${S}.issues.length) {
@@ -717,7 +717,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
717
717
  }
718
718
  ]`})]})]})}function Kcs({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-accent2/30 rounded-md border p-3",children:[o.jsxs("div",{className:"text-accent2 mb-2 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(Rd,{className:"h-4 w-4"})}),o.jsxs("span",{className:"text-sm font-medium",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-accent2/80 space-y-1 text-sm",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-accent2/60 mt-2 text-xs",children:["+",r," more error",r!==1?"s":""]})]})}function Xcs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=v.useState("upload"),[i,l]=v.useState(null),[c,u]=v.useState({current:0,total:0}),[d,f]=v.useState(null),[p,h]=v.useState(!1),{parseFile:m,isParsing:g,error:y}=Ols(),{batchInsertItems:b}=Ii(),x=v.useCallback(async I=>{try{const A=await m(I);l(A),a("preview")}catch{}},[m]),S=v.useCallback(async()=>{if(!i||i.items.length===0)return;a("importing"),h(!0);const{items:I}=i;u({current:0,total:I.length});try{await b.mutateAsync({datasetId:e,items:I.map(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=v.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&De.success(`Imported ${d.success} item${d.success!==1?"s":""}`),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150)},[n,r,d]),C=v.useCallback(()=>{p||(n(!1),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150))},[p,n]),_=i&&i.items.length>0&&i.errors.length===0,E=()=>{switch(s){case"upload":return o.jsx(Ycs,{onFileSelect:x,isParsing:g,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(Kcs,{errors:i.errors}),o.jsx("div",{className:"text-neutral4 text-sm",children:"Please fix the errors in your JSON file and try again."})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-neutral4 text-sm",children:["Found ",i.items.length," valid item",i.items.length!==1?"s":""," to import."]}),o.jsx(Qcs,{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(Jt,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Importing items..."}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",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-neutral1 text-lg font-medium",children:"Import Complete"}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",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":"",")"]})]})]})]})}},T=()=>{switch(s){case"upload":return o.jsx(ce,{onClick:C,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(ce,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(ce,{variant:"primary",onClick:S,disabled:!_,children:["Import ",i?.items.length??0," Item",i?.items.length!==1?"s":""]})]});case"importing":return null;case"complete":return o.jsx(ce,{variant:"primary",onClick:k,children:"Done"})}},N={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(vr,{open:t,onOpenChange:C,children:o.jsxs(yr,{className:"max-h-[90vh] max-w-2xl",children:[o.jsxs(br,{children:[o.jsx(hr,{children:N[s]}),o.jsx(Bs,{children:"Import dataset items from a JSON file."})]}),o.jsx(Rr,{className:"max-h-[50vh] min-h-[200px] overflow-y-auto",children:E()}),o.jsx(ic,{className:"flex justify-end gap-2 px-6 pt-4",children:T()})]})})}const pAe=e=>{const t=We(),{data:n}=MD(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:l.comment??""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})},Jcs=e=>{const t=We(),{data:n}=MD(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:l.comment??""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})};function eus(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 VBt({datasetId:e,experimentId:t,featuredItemId:n}){const r=We(),{data:s}=a0(e),{data:a,isLoading:i}=pAe(e),{data:l,isLoading:c}=Jcs(e),u=v.useMemo(()=>t?(a??[]).filter(je=>je.experimentId===t):a,[a,t]),d=v.useMemo(()=>t?(l??[]).filter(je=>je.experimentId===t):l,[l,t]),{updateExperimentResult:f}=Ii(),[p,h]=v.useState(n??null);v.useEffect(()=>{n!==void 0&&h(n)},[n]);const[m,g]=v.useState(null),[y,b]=v.useState(new Set),[x,S]=v.useState(!1),[k,C]=v.useState(!1),[_,E]=v.useState(!1),[T,N]=v.useState(""),[I,A]=v.useState(""),[R,L]=v.useState(""),[D,z]=v.useState([]),[H,F]=v.useState(!1),[U,q]=v.useState(null),M=v.useMemo(()=>U??u??[],[U,u]);v.useEffect(()=>{q(null)},[e,t]),v.useEffect(()=>{u&&U===null&&q(u)},[u,U]);const G=v.useMemo(()=>{const je=new Set;if(s?.tags)for(const Ee of s.tags)je.add(Ee);for(const Ee of M)for(const Oe of Ee.tags)je.add(Oe);return[...je].sort()},[s,M]),V=v.useCallback(je=>{!s||!e||(s.tags??[]).includes(je)},[s,e]),$=v.useMemo(()=>m?m==="__untagged__"?M.filter(je=>je.tags.length===0):M.filter(je=>je.tags.includes(m)):M,[M,m]),B=v.useMemo(()=>{const je=new Map;for(const Ee of M)for(const Oe of Ee.tags)je.set(Oe,(je.get(Oe)??0)+1);return[...je.entries()].sort((Ee,Oe)=>Oe[1]-Ee[1])},[M]),Z=v.useMemo(()=>M.filter(je=>je.tags.length===0).length,[M]),K=v.useMemo(()=>{let je=0;return m&&je++,x&&je++,je},[m,x]),ne=v.useCallback((je,Ee)=>{q(Ie=>(Ie??[]).map(Me=>Me.id===je?{...Me,tags:Ee}:Me));const Oe=M.find(Ie=>Ie.id===je);Oe?.experimentId&&Oe?.datasetId&&f.mutate({datasetId:Oe.datasetId,experimentId:Oe.experimentId,resultId:Oe.id,tags:Ee})},[M,f]),ee=v.useCallback((je,Ee)=>{const Oe=M.find(Ie=>Ie.id===je);Oe?.traceId&&Ee!==void 0&&r.createFeedback({feedback:{traceId:Oe.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:Ee==="positive"?1:-1,experimentId:Oe.experimentId??void 0,sourceId:Oe.id}}).catch(()=>{}),q(Ie=>(Ie??[]).map(Me=>Me.id===je?{...Me,rating:Ee}:Me))},[M,r]),J=v.useCallback((je,Ee)=>{const Oe=M.find(Ie=>Ie.id===je);Oe?.experimentId&&Oe?.datasetId&&f.mutate({datasetId:Oe.datasetId,experimentId:Oe.experimentId,resultId:Oe.id,comment:Ee}),Oe?.traceId&&r.createFeedback({feedback:{traceId:Oe.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:Ee,comment:Ee,experimentId:Oe.experimentId??void 0,sourceId:Oe.id}}).catch(()=>{}),q(Ie=>(Ie??[]).map(Me=>Me.id===je?{...Me,comment:Ee}:Me))},[M,r,f]),ae=v.useCallback(je=>{const Ee=M.find(Oe=>Oe.id===je);q(Oe=>(Oe??[]).filter(Ie=>Ie.id!==je)),b(Oe=>{const Ie=new Set(Oe);return Ie.delete(je),Ie}),p===je&&h(null),Ee?.experimentId&&Ee?.datasetId&&f.mutate({datasetId:Ee.datasetId,experimentId:Ee.experimentId,resultId:Ee.id,status:null})},[M,f,p]),fe=v.useCallback(je=>{const Ee=M.find(Oe=>Oe.id===je);q(Oe=>(Oe??[]).filter(Ie=>Ie.id!==je)),b(Oe=>{const Ie=new Set(Oe);return Ie.delete(je),Ie}),p===je&&h(null),Ee?.experimentId&&Ee?.datasetId&&f.mutate({datasetId:Ee.datasetId,experimentId:Ee.experimentId,resultId:Ee.id,status:"complete"})},[M,f,p]),Y=v.useMemo(()=>{const je=x?d??[]:$;return!x||!m?je:m==="__untagged__"?je.filter(Ee=>Ee.tags.length===0):je.filter(Ee=>Ee.tags.includes(m))},[x,d,$,m]),re=x?c:!1,le=v.useMemo(()=>new Set(Y.map(je=>je.id)),[Y]),ue=v.useMemo(()=>[...y].filter(je=>le.has(je)).length,[y,le]),oe=Y.length>0&&ue===Y.length,me=ue>0&&!oe,be=v.useCallback(je=>{b(Ee=>{const Oe=new Set(Ee);return Oe.has(je)?Oe.delete(je):Oe.add(je),Oe})},[]),xe=v.useCallback(()=>{b(oe?new Set:new Set(Y.map(je=>je.id)))},[oe,Y]),Ce=v.useCallback(je=>{for(const Ee of y){const Oe=M.find(Ie=>Ie.id===Ee);Oe&&!Oe.tags.includes(je)&&ne(Ee,[...Oe.tags,je])}},[M,y,ne]),ke=v.useCallback(je=>{for(const Ee of y){const Oe=M.find(Ie=>Ie.id===Ee);Oe&&Oe.tags.includes(je)&&ne(Ee,Oe.tags.filter(Ie=>Ie!==je))}},[M,y,ne]),Ne=v.useCallback(()=>{for(const je of y)fe(je);b(new Set)},[y,fe]),$e=v.useCallback(()=>{for(const je of y)ae(je);b(new Set)},[y,ae]),de=v.useCallback(()=>{N(""),E(!0)},[]),te=v.useCallback(async()=>{if(!(!I||!R)){C(!0),E(!1);try{const je=M.filter(Oe=>y.has(Oe.id));if(je.length===0){C(!1);return}const Ee=await r.clusterFailures({modelId:`${I}/${R}`,items:je.map(Oe=>({id:Oe.id,input:Oe.input,output:Oe.output??void 0,error:typeof Oe.error=="string"?Oe.error:Oe.error?String(Oe.error):void 0,scores:Oe.scores,existingTags:Oe.tags.length>0?Oe.tags:void 0})),availableTags:G.length>0?G:void 0,prompt:T||void 0});Ee.proposedTags&&Ee.proposedTags.length>0&&(z(Ee.proposedTags.map(Oe=>({...Oe,accepted:!0}))),F(!0))}catch(je){console.error("Analysis failed:",je)}finally{C(!1)}}},[I,R,M,y,r,G,T]),se=v.useCallback(()=>{for(const je of D){if(!je.accepted)continue;const Ee=M.find(Oe=>Oe.id===je.itemId);if(Ee){const Oe=[...new Set([...Ee.tags,...je.tags])];ne(Ee.id,Oe)}}F(!1)},[D,M,ne]),he=v.useCallback(je=>{h(Ee=>Ee===je?null:je)},[]),we=v.useMemo(()=>p?Y.find(je=>je.id===p)??null:null,[p,Y]),Te=p?Y.findIndex(je=>je.id===p):-1,Re=Te>0?()=>h(Y[Te-1].id):void 0,Ze=Te>=0&&Te<Y.length-1?()=>h(Y[Te+1].id):void 0,Ge="auto minmax(15rem,1fr) 10rem 8rem 6rem 6rem";return i?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Jt,{className:"h-6 w-6"})}):o.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[o.jsx(vr,{open:_,onOpenChange:E,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Analyze Items"}),o.jsx(Bs,{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(zt,{className:"mb-1 block text-xs",children:"Provider"}),o.jsx(Qy,{value:I,onValueChange:A})]}),o.jsxs("div",{children:[o.jsx(zt,{className:"mb-1 block text-xs",children:"Model"}),o.jsx(Yy,{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(zt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx(Dl,{value:T,onChange:je=>N(je.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"mt-1 text-xs"})]})]}),o.jsxs(ic,{children:[o.jsx(ce,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),o.jsxs(ce,{onClick:te,disabled:!I||!R||k,children:[k?o.jsx(Jt,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(vr,{open:H,onOpenChange:F,children:o.jsxs(yr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Review Proposed Tags"}),o.jsxs(Bs,{children:[D.filter(je=>je.accepted).length," of ",D.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:D.map((je,Ee)=>{const Oe=M.find(Ie=>Ie.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(qo,{checked:je.accepted,onCheckedChange:Ie=>z(Me=>Me.map((Ue,Je)=>Je===Ee?{...Ue,accepted:!!Ie}:Ue))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 block truncate",children:Oe?typeof Oe.input=="string"?Oe.input.slice(0,100):JSON.stringify(Oe.input).slice(0,100):je.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:je.tags.map((Ie,Me)=>o.jsx(E7t,{tag:Ie,onRename:Ue=>z(Je=>Je.map((tt,Dt)=>Dt===Ee?{...tt,tags:tt.tags.map((at,gt)=>gt===Me?Ue:at)}:tt)),onRemove:()=>z(Ue=>Ue.map((Je,tt)=>tt===Ee?{...Je,tags:Je.tags.filter((Dt,at)=>at!==Me)}:Je))},`${Ie}-${Me}`))}),je.reason&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:je.reason})]})]})},je.itemId)})}),o.jsxs(ic,{children:[o.jsx(ce,{variant:"outline",onClick:()=>F(!1),children:"Cancel"}),o.jsxs(ce,{onClick:se,disabled:D.filter(je=>je.accepted).length===0,children:["Accept ",D.filter(je=>je.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:X("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",we&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid w-full content-start gap-8 overflow-y-auto",children:[o.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-4 gap-x-6",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsxs(ce,{variant:"outline",size:"md",children:[o.jsx(zot,{}),"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(ot.Content,{align:"start",className:X("min-w-48"),children:[o.jsxs(ot.Sub,{children:[o.jsxs(ot.SubTrigger,{children:["Status",x&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(ot.SubContent,{children:[o.jsx(ot.CheckboxItem,{checked:!x,onCheckedChange:()=>{S(!1),h(null)},onSelect:je=>je.preventDefault(),children:"Review Queue"}),o.jsx(ot.CheckboxItem,{checked:x,onCheckedChange:()=>{S(!0),h(null)},onSelect:je=>je.preventDefault(),children:"Completed"})]})]}),o.jsxs(ot.Sub,{children:[o.jsxs(ot.SubTrigger,{children:["Tags",m&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(ot.SubContent,{children:[o.jsx(ot.CheckboxItem,{checked:!m,onCheckedChange:()=>g(null),onSelect:je=>je.preventDefault(),children:"All"}),Z>0&&o.jsx(ot.CheckboxItem,{checked:m==="__untagged__",onCheckedChange:()=>g(m==="__untagged__"?null:"__untagged__"),onSelect:je=>je.preventDefault(),children:"Untagged"}),B.length>0&&o.jsx(ot.Separator,{}),B.map(([je])=>o.jsx(ot.CheckboxItem,{checked:m===je,onCheckedChange:()=>g(m===je?null:je),onSelect:Ee=>Ee.preventDefault(),children:je},je))]})]}),K>0&&o.jsxs(o.Fragment,{children:[o.jsx(ot.Separator,{}),o.jsxs(ot.Item,{onSelect:()=>{g(null),S(!1),h(null)},children:[o.jsx(ps,{}),"Clear all filters"]})]})]})]}),K>0&&o.jsxs(ce,{variant:"outline",size:"md",onClick:()=>{g(null),S(!1),h(null)},children:[o.jsx(ps,{}),"Reset"]})]}),!x&&y.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(C7t,{selectedCount:y.size,vocabulary:G,onApplyTag:Ce,onRemoveTag:ke,onNewTag:je=>Ce(je)}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsxs(ce,{disabled:k,children:[k?o.jsx(Jt,{className:"h-4 w-4"}):o.jsx(qe,{size:"sm",children:o.jsx(ka,{})}),"Actions"]})}),o.jsxs(ot.Content,{align:"end",children:[o.jsxs(ot.Item,{onSelect:Ne,children:[o.jsx(qe,{size:"sm",children:o.jsx(gO,{})}),"Complete"]}),o.jsxs(ot.Item,{onSelect:$e,children:[o.jsx(qe,{size:"sm",children:o.jsx(vu,{})}),"Remove"]}),o.jsx(ot.Separator,{}),o.jsxs(ot.Item,{onSelect:de,children:[o.jsx(qe,{size:"sm",children:o.jsx(Ig,{})}),"Analyze"]})]})]})]})]}),re?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Jt,{className:"h-6 w-6"})}):Y.length===0?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsxs("div",{className:"px-8 text-center",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 block",children:x?"No completed reviews yet":"No items to review"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-2 block",children:x?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})]})}):o.jsxs(ge,{columns:Ge,className:"min-w-0",children:[o.jsxs(ge.Top,{hasLeadingCell:!0,children:[x?o.jsx(ge.TopCell,{children:" "}):o.jsx(ge.TopSelectCell,{checked:oe?!0:me?"indeterminate":!1,onToggle:()=>xe(),"aria-label":"Select all"}),o.jsxs(ge.TopCells,{colStart:2,children:[o.jsx(ge.TopCell,{children:"Input"}),o.jsx(ge.TopCell,{children:"Comment"}),o.jsx(ge.TopCell,{children:"Tags"}),o.jsx(ge.TopCell,{children:"Rating"}),o.jsx(ge.TopCell,{children:"Scores"})]})]}),Y.map(je=>{const Ee=je.scores?Object.entries(je.scores):[],Oe=p===je.id,Ie=o.jsxs(o.Fragment,{children:[o.jsx(ge.Cell,{height:"compact",className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:eus(je.input,200)})}),o.jsx(ge.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(ge.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(ge.Cell,{height:"compact",children:[je.rating==="positive"&&o.jsx(qe,{size:"sm",className:"text-positive1",children:o.jsx(Lxe,{})}),je.rating==="negative"&&o.jsx(qe,{size:"sm",className:"text-negative1",children:o.jsx(Dxe,{})}),!je.rating&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(ge.Cell,{height:"compact",children:Ee.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:o.jsx(om,{})}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 font-mono",children:Ee[0][1].toFixed(2)}),Ee.length>1&&o.jsxs(on,{variant:"default",children:["+",Ee.length-1]})]}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(ge.RowWrapper,{children:[x?o.jsx(ge.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(ge.SelectCell,{checked:y.has(je.id),onToggle:()=>be(je.id),"aria-label":`Select item ${je.id}`}),o.jsx(ge.RowButton,{flushLeft:!0,colStart:2,featured:Oe,onClick:()=>he(je.id),children:Ie})]},je.id)})]})]}),we&&o.jsx(_7t,{item:we,isCompleted:x,tagVocabulary:G,onRate:je=>ee(we.id,je),onSetTags:je=>{ne(we.id,je);for(const Ee of je)G.includes(Ee)||V(Ee)},onComment:je=>J(we.id,je),onRemove:()=>ae(we.id),onComplete:x?void 0:()=>fe(we.id),onPrevious:Re,onNext:Ze,onClose:()=>h(null)})]})]})}function tus({datasetId:e,onAddItemClick:t,onNavigateToDataset:n}){const{navigate:r}=bn(),[s,a]=ri(),{tab:i,activeVersion:l,handleTabChange:c}=dAe(s,a),[u,d]=v.useState(!1),[f,p]=v.useState(!1),[h,m]=v.useState(!1),[g,y]=v.useState([]),[b,x]=v.useState(!1),[S,k]=v.useState([]),[C,_]=v.useState(!1),[E,T]=v.useState([]),[N,I]=v.useState(0),[A,R]=v.useState(null),[L,D]=v.useState(""),[z]=aSe(L,300),{data:H}=a0(e),{data:F=[],total:U,isLoading:q,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:V}=B1(e,z||void 0,l),{total:$}=B1(e,void 0,l),[B,Z]=v.useState({}),{data:K,isLoading:ne}=MD(e,void 0,B),{data:ee}=MD(e),{deleteItems:J}=Ii(),ae=K?.experiments??[],fe=ee?.experiments??[],Y=ncs({hasSearchQuery:!!z,filteredItemsLength:F.length,unfilteredItemsTotal:$,itemsTotal:U}),{data:re}=pAe(e),le=re?.length??0,ue=se=>{R(se)},oe=()=>{R(null)},me=se=>{y(se),m(!0)},be=se=>{k(se),x(!0)},xe=se=>{x(se),se||(k([]),I(he=>he+1))},Ce=se=>{r(`/datasets/${e}/items?items=${se.join(",")}`)},ke=se=>{r(`/datasets/${e}/versions?ids=${se.join(",")}`)},Ne=se=>{T(se),_(!0)},$e=async()=>{await J.mutateAsync({datasetId:e,itemIds:E}),De.success(`Deleted ${E.length} items`),_(!1),T([]),I(se=>se+1)},de=se=>{m(!1),y([]),I(he=>he+1),n?.(se)},te=se=>{m(se),se||(y([]),I(he=>he+1))};return o.jsxs(o.Fragment,{children:[o.jsxs(gc,{defaultTab:"items",value:i,onValueChange:c,className:"grid h-full grid-rows-[auto_1fr]",children:[o.jsxs(mc,{children:[o.jsxs(Nr,{value:"items",children:["Items ",o.jsx(ea,{color:"gray",children:Y})]}),o.jsxs(Nr,{value:"experiments",children:["Experiments",o.jsx(ea,{color:"gray",children:ae.length})]}),o.jsxs(Nr,{value:"review",children:["Review",le>0&&o.jsx(ea,{color:"orange",children:le})]})]}),o.jsx(Kr,{value:"items",className:"mt-5 grid overflow-auto pb-0",children:o.jsx(Gcs,{datasetId:e,items:F,isLoading:q,featuredItemId:A,onItemSelect:ue,onItemClose:oe,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>p(!0),onBulkDeleteClick:Ne,onCreateDatasetClick:me,onAddToDatasetClick:be,onCompareItemsClick:Ce,datasetName:H?.name,clearSelectionTrigger:N,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:V,searchQuery:L,activeSearchQuery:z,onSearchChange:D,currentDatasetVersion:H?.version,onCompareVersionsClick:ke})}),o.jsx(Kr,{value:"experiments",className:"mt-5 grid overflow-auto pb-0",children:o.jsx(bcs,{experiments:ae,allExperiments:fe,isLoading:ne,datasetId:e,filters:B,onFiltersChange:Z})}),o.jsx(Kr,{value:"review",className:"mt-2 overflow-auto pb-0",children:o.jsx(VBt,{datasetId:e})})]}),o.jsx(dcs,{datasetId:e,open:u,onOpenChange:d}),o.jsx(Xcs,{datasetId:e,open:f,onOpenChange:p}),o.jsx(Bls,{open:h,onOpenChange:te,items:g,onSuccess:de}),o.jsx(Uls,{open:b,onOpenChange:xe,items:S,currentDatasetId:e}),o.jsx(At,{open:C,onOpenChange:_,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:$e,children:J.isPending?"Deleting...":"Delete"})]})]})})]})}function nus(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 uie({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-destructive text-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function rus({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=v.useState("{}"),[i,l]=v.useState(""),[c,u]=v.useState(""),[d,f]=v.useState(""),[p,h]=v.useState(""),[m,g]=v.useState(null),{addItem:y}=Ii(),b=async _=>{_.preventDefault();let E;try{E=JSON.parse(s)}catch{De.error("Input must be valid JSON");return}let T;if(i.trim())try{T=JSON.parse(i)}catch{De.error("Ground Truth must be valid JSON");return}let N;if(c.trim())try{N=JSON.parse(c)}catch{De.error("Expected Trajectory must be valid JSON");return}let I;if(d.trim())try{const 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:T,expectedTrajectory:N,toolMocks:I,requestContext:A}),De.success("Item added successfully"),g(null),a("{}"),l(""),u(""),f(""),h(""),n(!1),r?.()}catch(R){const L=nus(R);L?g(L):De.error(`Failed to add item: ${R instanceof Error?R.message:"Unknown error"}`)}},x=_=>{a(_),m?.field==="input"&&g(null)},S=_=>{l(_),m?.field==="groundTruth"&&g(null)},k=_=>{f(_),m?.field==="toolMocks"&&g(null)},C=()=>{a("{}"),l(""),u(""),f(""),h(""),g(null),n(!1)};return o.jsx(vr,{open:t,onOpenChange:n,children:o.jsxs(yr,{className:"max-w-lg",children:[o.jsx(br,{children:o.jsx(hr,{children:"Add Item"})}),o.jsx(Rr,{children:o.jsxs("form",{onSubmit:b,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(zt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Hr,{value:s,onChange:x,showCopyButton:!1,className:"min-h-[120px]"}),m?.field==="input"&&o.jsx(uie,{field:"input",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(zt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Hr,{value:i,onChange:S,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="groundTruth"&&o.jsx(uie,{field:"groundTruth",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(zt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Hr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(zt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Hr,{value:d,onChange:k,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="toolMocks"&&o.jsx(uie,{field:"toolMocks",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(zt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Hr,{value:p,onChange:h,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ce,{type:"button",onClick:C,children:"Cancel"}),o.jsx(ce,{type:"submit",variant:"primary",disabled:y.isPending,children:y.isPending?"Adding...":"Add Item"})]})]})})]})})}function sus({item:e}){return o.jsx(ha,{withMargins:!1,children:o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{size:"smaller",children:[o.jsx(GN,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(Pa,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(ha.Description,{children:[o.jsxs(_o,{children:[o.jsx(Iot,{})," Created ",rr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(_o,{children:[o.jsx(O_,{})," Version v",e.datasetVersion]})]})]})})}function hAe({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(wIe,{children:[o.jsx(As.CodeSection,{title:"Input",icon:o.jsx(vO,{}),codeStr:t}),o.jsx(As.CodeSection,{title:"Ground Truth",icon:o.jsx(Eg,{}),codeStr:n}),s&&o.jsx(As.CodeSection,{title:"Expected Trajectory",icon:o.jsx(Pxe,{}),codeStr:s}),o.jsx(As.CodeSection,{title:"Metadata",icon:o.jsx(KN,{}),codeStr:r})]})}function aus({selectedScorers:e,setSelectedScorers:t,disabled:n=!1,container:r}){const{data:s,isLoading:a}=ch(),i=v.useMemo(()=>s?Object.entries(s).map(([l,c])=>({value:l,label:c.scorer?.config?.name||l,description:c.scorer?.config?.description||""})):[],[s]);return o.jsxs("div",{className:"grid gap-2",children:[o.jsx(zt,{children:"Scorers (Optional)"}),o.jsx(Fl,{multiple:!0,options:i,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||a,container:r})]})}const ius=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function ous({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=Am(),{data:l,isLoading:c}=Ky(),{data:u,isLoading:d}=ch(),f=e==="agent"?Object.entries(a??{}).map(([g,y])=>({value:g,label:y.name??g})):e==="workflow"?Object.entries(l??{}).map(([g,y])=>({value:g,label:y.name??g})):e==="scorer"?Object.entries(u??{}).map(([g,y])=>({value:g,label:y.scorer?.config?.name??g})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=g=>{t(g),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(zt,{children:"Target Type"}),o.jsx(Fl,{options:ius,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(zt,{children:m}),o.jsx(Fl,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}function lus({requestContextSchema:e,onChange:t}){const n=v.useMemo(()=>{try{return gm(hm(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(zt,{children:"Request Context"}),o.jsx(z3,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-destructive text-sm",children:"Failed to parse request context schema"})}function cus({datasetId:e,version:t,requestContextSchema:n,open:r,onOpenChange:s,onSuccess:a}){const i=v.useRef(null),[l,c]=v.useState(""),[u,d]=v.useState(""),[f,p]=v.useState([]),[h,m]=v.useState({}),[g,y]=v.useState(""),{triggerExperiment:b}=Ii(),x=!!(n&&Object.keys(n).length>0),S=l&&u,k=b.isPending,C=()=>{c(""),d(""),p([]),m({}),y("")},_=()=>{if(x){const N=Object.entries(h).filter(([,I])=>I!==void 0&&I!=="");return N.length>0?Object.fromEntries(N):void 0}if(g.trim()){let N;try{N=JSON.parse(g)}catch{throw new Error("Request Context must be valid JSON")}if(!N||typeof N!="object"||Array.isArray(N))throw new Error("Request Context must be a JSON object");return N}},E=async()=>{if(!S)return;let N;try{N=_()}catch(I){const A=I instanceof Error?I.message:"Request Context must be valid JSON";lu.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:N});lu.success("Experiment triggered successfully"),s(!1),a?.(I.experimentId),C()}catch(I){const A=I instanceof Error?I.message:"Failed to trigger experiment";lu.error(A)}},T=()=>{k||(s(!1),C())};return o.jsx(vr,{open:r,onOpenChange:T,children:o.jsxs(yr,{ref:i,children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Run Experiment"}),o.jsx(Bs,{children:t?`Execute items from ${rr(new Date(t),"MMM d, yyyy")} version against a target.`:"Execute all items in this dataset against a target."})]}),o.jsxs(Rr,{className:"grid gap-6",children:[o.jsx(ous,{targetType:l,setTargetType:c,targetId:u,setTargetId:d,container:i}),l&&l!=="scorer"&&o.jsx(aus,{selectedScorers:f,setSelectedScorers:p,disabled:k,container:i}),x?o.jsx(lus,{requestContextSchema:n,onChange:m}):o.jsxs("div",{className:"space-y-2",children:[o.jsx(zt,{children:"Request Context (JSON, optional)"}),o.jsx(Hr,{value:g,onChange:y,showCopyButton:!1,className:"min-h-[80px]"})]})]}),o.jsxs(ic,{className:"px-6 pt-4",children:[o.jsx(ce,{onClick:T,disabled:k,children:"Cancel"}),o.jsx(ce,{variant:"primary",onClick:E,disabled:!S||k,children:k?o.jsxs(o.Fragment,{children:[o.jsx(Jt,{className:"h-4 w-4"}),"Running..."]}):"Run"})]})]})})}const uus=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})},mAe=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 die(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function dus({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(wn.SectionHeading,{icon:o.jsx(Vp,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(Sn,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(Sn.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: ",die(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>die(i.args)).join(", ")]})]})}),o.jsx("div",{className:"border-border1 divide-border1 divide-y rounded border 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:"text-neutral4 font-mono",children:i.toolName}),o.jsx("span",{className:"text-neutral3 ml-2 font-mono text-xs",children:die(i.args)})]}),o.jsx("span",{className:`shrink-0 rounded px-2 py-0.5 text-xs ${fus(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function fus(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 pus({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d,onCollapsedChange:f}){const[p,h]=v.useState(!1),m=d??p,g=f??h,y=!!e?.error,b=HF(e?.input),x=HF(e?.output),S=HF(e?.groundTruth),k=u&&e.status!=="needs-review"&&e.status!=="complete",C=Array.isArray(e.tags)?e.tags:[];return o.jsxs(wn,{collapsed:m,children:[o.jsxs(wn.Header,{children:[o.jsxs(wn.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(ce,{size:"md",tooltip:m?"Expand panel":"Collapse panel",onClick:()=>g(!m),children:m?o.jsx($ot,{}):o.jsx(Pot,{})}),o.jsx(wn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),o.jsxs(ce,{size:"md",onClick:a,disabled:!e.traceId,children:[o.jsx(mAe,{}),"Trace"]}),o.jsx(wn.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!m&&o.jsxs(wn.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[o.jsxs(Vt,{children:[o.jsx(Vt.Key,{children:"Item Id"}),o.jsx(Vt.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(Vt.Key,{children:"Created"}),o.jsx(Vt.Value,{children:rr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),y&&o.jsx(Sn,{variant:"destructive",title:"Error",children:o.jsx(Sn.Message,{children:HF(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(ge,{columns:"1fr 1fr",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Scorer"}),o.jsx(ge.TopCell,{children:"Score"})]}),t.map(_=>o.jsxs(ge.RowButton,{featured:c===_.id,onClick:()=>l?.(_.id),children:[o.jsx(ge.Cell,{height:"compact",children:_.scorerId}),o.jsx(ge.MonoCell,{children:_.score.toFixed(3)})]},_.id))]}),e.toolMockReport&&o.jsx(dus,{report:e.toolMockReport}),(e.status||C.length>0||k)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(wn.SectionHeading,{icon:o.jsx(KN,{}),className:"mb-2",children:"Review"}),(e.status||C.length>0)&&o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.status&&o.jsx("span",{className:`rounded-full px-2 py-0.5 text-xs 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}),C.map(_=>o.jsx("span",{className:"bg-surface4 text-neutral4 rounded px-2 py-0.5 text-xs",children:_},_))]}),k&&o.jsx("div",{children:o.jsxs(ce,{size:"sm",onClick:()=>u(e.id),children:[o.jsx(iV,{}),"Flag for Review"]})}),e.status==="needs-review"&&i&&o.jsx("div",{children:o.jsxs(ce,{size:"sm",onClick:i,children:[o.jsx(_a,{}),"Review"]})})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(wn.CodeSection,{title:"Input",icon:o.jsx(GN,{}),codeStr:b}),o.jsx(wn.CodeSection,{title:"Output",icon:o.jsx(Eg,{}),codeStr:x}),o.jsx(wn.CodeSection,{title:"Ground Truth",icon:o.jsx(Mxe,{}),codeStr:S})]})]})]})}function HF(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function hus({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:a,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,selectedIds:d,onToggleSelect:f}){const p=!!(d&&f),h=[p?"auto":"",...s.map(g=>g.size)].filter(Boolean).join(" "),m=s.some(g=>g.name==="input");return t?o.jsx(ll,{columns:h}):o.jsxs(ge,{columns:h,className:"min-w-0",children:[o.jsxs(ge.Top,{hasLeadingCell:p,children:[p&&o.jsx(ge.TopCell,{children:" "}),p?o.jsx(ge.TopCells,{colStart:2,children:s.map(g=>o.jsx(ge.TopCell,{children:g.label},g.name))}):s.map(g=>o.jsx(ge.TopCell,{children:g.label},g.name))]}),e.length===0?o.jsx(ge.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map(g=>{const y=!!g.error,b=g.id===n,x=o.jsxs(o.Fragment,{children:[o.jsx(ge.IdCell,{id:g.itemId}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("div",{className:"relative flex h-full w-10 items-center justify-center bg-transparent",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(Pn,{children:y?"Error":"Success"})]})}),m&&o.jsx(ge.MonoCell,{children:gus(mus(g.input),200)}),i?.map(S=>{const C=a?.[g.itemId]?.find(_=>_.scorerId===S);return o.jsx(ge.Cell,{height:"compact",className:"text-neutral3 text-ui-smd font-mono",children:C!=null?C.score.toFixed(3):"-"},S)})]});return p?o.jsxs(ge.RowWrapper,{children:[o.jsx(ge.SelectCell,{checked:d.has(g.id),onToggle:()=>f(g.id),"aria-label":`Select result ${g.itemId}`}),o.jsx(ge.RowButton,{flushLeft:!0,colStart:2,featured:b,onClick:()=>r(g.id),children:x})]},g.id):o.jsx(ge.RowButton,{featured:b,onClick:()=>r(g.id),children:x},g.id)}),o.jsx(ge.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function mus(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function gus(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function vus(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function yus({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i}){const[l,c]=v.useState(!1),u=a??l,d=i??c,f=vus(e),p=f?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(wn,{collapsed:u,children:[o.jsxs(wn.Header,{children:[o.jsxs(wn.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[i&&o.jsx(ce,{size:"md",tooltip:u?"Expand panel":"Collapse panel",onClick:()=>d(!u),children:u?o.jsx($ot,{}):o.jsx(Pot,{})}),(n||t)&&o.jsx(wn.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&o.jsxs(ce,{size:"md",onClick:s,disabled:!e.traceId,children:[o.jsx(mAe,{}),"Trace"]}),o.jsx(wn.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!u&&o.jsx(wn.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(wn.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(om,{}),codeStr:e.reason||p,simplified:!0}),!f&&o.jsxs(o.Fragment,{children:[o.jsx(wn.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(Th,{}),codeStr:e.preprocessPrompt||p,simplified:!0}),o.jsx(wn.CodeSection,{title:"Analyze Prompt",icon:o.jsx(Th,{}),codeStr:e.analyzePrompt||p,simplified:!0}),o.jsx(wn.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(Th,{}),codeStr:e.generateScorePrompt||p,simplified:!0}),o.jsx(wn.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(Th,{}),codeStr:e.generateReasonPrompt||p,simplified:!0})]})]})})]})}const zJe=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"avg",label:"Avg Score",size:"1fr"},{name:"count",label:"Items Scored",size:"1fr"}];function bus({scoresByItemId:e,experimentStatus:t}){const n=v.useMemo(()=>{if(!e)return[];const r={};for(const s of Object.values(e))for(const a of s)r[a.scorerId]||(r[a.scorerId]={sum:0,count:0}),r[a.scorerId].sum+=a.score,r[a.scorerId].count++;return Object.entries(r).map(([s,{sum:a,count:i}])=>({scorerId:s,avg:a/i,count:i})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))},[e]);if(n.length===0){const r=t==="running"||t==="pending",s=e!==void 0;let a,i;return r?(a="Experiment in progress",i="Summary metrics will appear here once the experiment completes."):s?(a="No scorers configured",i="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(a="Loading scores",i="Fetching scorer results…"),o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(Lr,{iconSlot:o.jsx(om,{className:"text-neutral3 h-8 w-8"}),titleSlot:a,descriptionSlot:i})})}return o.jsxs(yn,{children:[o.jsxs(yn.Header,{columns:zJe,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:zJe,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 HBt({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const[c,u]=v.useState(null),[d,f]=v.useState(null),[p,h]=v.useState(void 0),[m,g]=v.useState(null),[y,b]=v.useState(new Set),[x,S]=v.useState(!1),[k,C]=v.useState(!1),[_,E]=v.useState(!1),[T,N]=v.useState(!1),{updateExperimentResult:I}=Ii(),A=v.useCallback(te=>{b(se=>{const he=new Set(se);return he.has(te)?he.delete(te):he.add(te),he})},[]),R=v.useCallback(()=>b(new Set),[]),L=v.useCallback(()=>{const te=r.filter(se=>!!se.error).map(se=>se.id);b(new Set(te))},[r]),D=v.useCallback(async te=>{if(x||te.length===0)return;S(!0);let se=0;const he=new Set;try{for(const we of te)try{await I.mutateAsync({datasetId:t,experimentId:e,resultId:we,status:"needs-review"}),se++,he.add(we)}catch{}}finally{S(!1)}he.size>0&&b(we=>{const Te=new Set(we);for(const Re of he)Te.delete(Re);return Te}),se>0&&De(`${se} result${se>1?"s":""} flagged for review`)},[t,e,x,I]),z=r.find(te=>te.id===c)??null,[H,F]=v.useState("summary"),[U,q]=v.useState(null),M=te=>{F(te),te!=="reviews"&&q(null)},{data:G}=pAe(t),V=(G??[]).filter(te=>te.experimentId===e).length,{data:$}=w7t(e,n),B=v.useMemo(()=>{if(!$)return[];const te=new Set;for(const se of Object.values($))for(const he of se)te.add(he.scorerId);return[...te].sort()},[$]),Z=te=>{u(te),f(null),h(void 0),g(null)},K=te=>{Z(te===c?null:te)},ne=()=>{Z(null)},ee=()=>{if(!z)return;const te=r.findIndex(se=>se.id===z.id);if(te>=0&&te<r.length-1)return()=>Z(r[te+1].id)},J=()=>{if(!z)return;const te=r.findIndex(se=>se.id===z.id);if(te>0)return()=>Z(r[te-1].id)},ae=z?$?.[z.itemId]:void 0,fe=ae?.find(te=>te.id===m)??null,Y=te=>{g(te===m?null:te),f(null),h(void 0)},re=()=>{if(!m||!ae)return;const te=ae.findIndex(se=>se.id===m);if(te>=0&&te<ae.length-1)return()=>g(ae[te+1].id)},le=()=>{if(!m||!ae)return;const te=ae.findIndex(se=>se.id===m);if(te>0)return()=>g(ae[te-1].id)},{data:ue,isLoading:oe}=uus(d),me=ue?.spans,{data:be,isLoading:xe}=DL(d,p),Ce=be?.span,{handlePreviousSpan:ke,handleNextSpan:Ne}=cAe(me,p??null,h),$e=(()=>{const te=[],se=!!fe,he=!!d;return te.push(k?"auto":se||he?"2fr":"1fr"),se&&te.push(T?"auto":"3fr"),he&&te.push(_?"auto":"3fr"),he&&p&&te.push("3fr"),te.join(" ")})(),de=v.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"status",label:"Status",size:"5rem"},{name:"input",label:"Input",size:"minmax(15rem,1fr)"},...B.map(te=>({name:te,label:te,size:"12rem"}))],[B]);return o.jsxs(gc,{defaultTab:"summary",value:H,onValueChange:M,className:"grid h-full grid-rows-[auto_1fr] overflow-hidden",children:[o.jsxs(mc,{children:[o.jsx(Nr,{value:"summary",children:"Summary"}),o.jsx(Nr,{value:"results",children:"Results"}),o.jsxs(Nr,{value:"reviews",children:["Reviews",V>0&&o.jsx(ea,{color:"orange",children:V})]})]}),o.jsx(Kr,{value:"summary",className:"mt-5 overflow-y-auto",children:o.jsx(bus,{scoresByItemId:$,experimentStatus:n})}),o.jsx(Kr,{value:"reviews",className:"mt-2 overflow-auto pb-0",children:o.jsx(VBt,{datasetId:t,experimentId:e,featuredItemId:U})}),o.jsxs(Kr,{value:"results",className:"mt-2 grid grid-rows-[auto_1fr] overflow-hidden",children:[o.jsxs("div",{className:"mb-4",children:[y.size>0&&o.jsxs("div",{className:"bg-surface3 flex items-center gap-2 px-4 py-2",children:[o.jsxs(ye,{variant:"ui-xs",className:"text-neutral5 font-medium",children:[y.size," selected"]}),o.jsx("div",{className:"flex-1"}),o.jsxs(ce,{variant:"outline",size:"sm",disabled:x,onClick:()=>D([...y]),children:[o.jsx(qe,{size:"sm",children:o.jsx(iV,{})}),"Flag for Review"]}),o.jsx(ce,{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(ce,{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 w-full overflow-y-auto",children:o.jsx("div",{className:"grid w-full content-start gap-8 overflow-y-auto",children:o.jsx(hus,{results:r,isLoading:s,featuredResultId:c,onResultClick:K,columns:de,scoresByItemId:$,scorerIds:B,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:y,onToggleSelect:A})})}),z&&o.jsxs("div",{className:"grid max-h-full min-h-0 content-start gap-4 overflow-auto",style:{gridTemplateRows:$e},children:[o.jsx(pus,{result:z,scores:ae,onPrevious:J(),onNext:ee(),onClose:ne,onScoreClick:Y,featuredScoreId:m,onShowTrace:()=>{z.traceId&&(f(z.traceId),h(void 0),g(null),C(!0),E(!1))},onOpenInReview:()=>{q(z.id),F("reviews")},onFlagForReview:te=>D([te]),collapsed:k,onCollapsedChange:C}),fe&&o.jsx(yus,{score:fe,onNext:re(),onPrevious:le(),onClose:()=>g(null),onShowTrace:()=>{fe.traceId&&(f(fe.traceId),h(void 0),C(!0),N(!0),E(!1))},collapsed:T,onCollapsedChange:N}),d&&o.jsxs(o.Fragment,{children:[o.jsx(tAe,{traceId:d,spans:me,isLoading:oe,onClose:()=>{f(null),h(void 0),C(!1),N(!1)},onSpanSelect:h,initialSpanId:p??null,placement:"traces-list",showUnavailableFeaturesMsg:!1,collapsed:_,onCollapsedChange:E,LinkComponent:by,traceHref:`/traces/${d}`}),p&&o.jsx(XIe,{traceId:d,spanId:p,span:Ce,isLoading:xe,onPrevious:ke,onNext:Ne,onClose:()=>h(void 0)})]})]})]})]})]})}const xus={pending:o.jsx(yj,{}),running:o.jsx(hpe,{}),completed:o.jsx(fa,{}),failed:o.jsx(ps,{})};function wus({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:"text-ui-lg text-neutral4 bg-surface5 flex items-center gap-2 rounded-lg p-1 px-3 capitalize",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:xus[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 Sus({onPrevious:e,onNext:t,previousAriaLabel:n="Previous",nextAriaLabel:r="Next"}){return o.jsxs(Mr,{spacing:"close",children:[o.jsxs(ce,{onClick:e,disabled:!e,"aria-label":n,children:[o.jsx(fH,{})," Prev"]}),o.jsxs(ce,{onClick:t,disabled:!t,"aria-label":r,children:["Next",o.jsx(w3,{})]})]})}function gAe({delta:e}){const t=e>0?o.jsx(ea,{size:"small",color:"green",intensity:"muted",children:o.jsx(BD,{})}):e<0?o.jsx(ea,{size:"small",color:"red",intensity:"muted",children:o.jsx(rWt,{})}):null;return o.jsxs("span",{className:X("font-mono text-sm text-neutral4 min-w-20"),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+ ":e<0?"- ":""}),Math.abs(e).toFixed(2)," ",t]})}function WF(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function kus({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(Qr,{withLeftSeparator:!0,children:[o.jsxs(Qr.Toolbar,{children:[o.jsx(Sus,{onPrevious:a,onNext:i,previousAriaLabel:"Previous comparison item",nextAriaLabel:"Next comparison item"}),o.jsx(Mr,{children:o.jsx(ce,{onClick:l,"aria-label":"Close comparison detail panel",children:o.jsx(ps,{})})})]}),o.jsxs(Qr.Content,{className:"pb-6",children:[o.jsx(ha,{withMargins:!1,children:o.jsx(ha.Column,{children:o.jsxs(ha.Title,{size:"smaller",children:[o.jsx(GN,{})," ",e.itemId]})})}),d?o.jsx(o.Fragment,{children:o.jsxs(wIe,{children:[p.length>0&&o.jsxs("div",{className:"grid gap-3",children:[o.jsx("h4",{className:"text-neutral5 text-sm font-medium",children:"Scores"}),o.jsx("div",{className:"grid gap-2",children:p.map(h=>{const m=c?.scores[h]??null,g=u?.scores[h]??null,y=m!=null&&g!=null?g-m:null;return o.jsxs("div",{className:"bg-surface2 flex items-center justify-between gap-4 rounded-lg px-3 py-2",children:[o.jsx("span",{className:"text-neutral5 text-sm font-medium",children:h}),o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("span",{className:"text-neutral3 text-sm",children:[m!=null?m.toFixed(3):"-"," →"," ",g!=null?g.toFixed(3):"-"]}),y!=null&&o.jsx(gAe,{delta:y})]})]},h)})})]}),o.jsx(As.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(ea,{color:"purple",children:"Baseline "})," Experiment Output"]}),icon:o.jsx(Eg,{}),codeStr:WF(c?.output)}),o.jsx(As.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(ea,{color:"cyan",children:"Contender "})," Experiment Output"]}),icon:o.jsx(Eg,{}),codeStr:WF(u?.output)}),o.jsx(As.CodeSection,{title:"Item Input",icon:o.jsx(vO,{}),codeStr:WF(e.input)}),o.jsx(As.CodeSection,{title:"Item Ground Truth",icon:o.jsx(Mxe,{}),codeStr:WF(e.groundTruth)})]})}):o.jsx(Sn,{variant:"warning",title:"Comparison not available",children:o.jsx(Sn.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 Ous({items:e,baselineId:t,contenderId:n,scorerIds:r,featuredItemId:s,columns:a,onItemClick:i}){return o.jsx(Qr,{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 justify-center gap-5 font-mono",children:m!=null?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-neutral2 flex min-w-24 items-center",children:[p?.toFixed(2)," → ",h?.toFixed(2)]}),o.jsx(gAe,{delta:m})]}):o.jsx("span",{className:"text-neutral1",children:"-"})},f)})})]})},l.itemId)})})})]})})}const _us={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 FJe({datasetId:e,experiment:t,type:n}){const{Link:r}=bn(),{label:s,color:a,customStyle:i}=_us[n];if(!t)return null;const l=t.createdAt?new Date(t.createdAt):null,c=cS(t.id)??t.id,u=t.name||c,d=o.jsx(ce,{as:r,href:`/datasets/${e}/experiments/${t.id}`,children:o.jsx("span",{className:"min-w-0 truncate",children:u})});return o.jsxs("div",{className:`border-border1 grid gap-3 rounded-lg border-2 p-5 ${i}`,children:[o.jsxs("div",{className:"flex w-full items-center gap-3 overflow-clip",children:[n==="contender"&&o.jsxs(ea,{size:"small",color:a,children:[s,o.jsx(Sm,{})]}),t.description?o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:d}),o.jsx(Pn,{children:t.description})]}):d,n==="baseline"&&o.jsxs(ea,{size:"small",color:a,children:[o.jsx($c,{})," ",s]})]}),o.jsxs("div",{className:"text-ui-sm text-neutral3 flex flex-wrap gap-x-4 gap-y-1",children:[t.name&&o.jsxs(_o,{children:[o.jsx(fpe,{})," ",c]}),o.jsxs(_o,{children:[o.jsx(Mxe,{})," ",t.targetType," / ",t.targetId]}),o.jsxs(_o,{children:[o.jsx(lV,{})," v",t.datasetVersion??"—"]}),l&&o.jsxs(_o,{children:[o.jsx(Aot,{})," ",rr(l,"MMM d, yyyy HH:mm")]})]})]})}function Cus({datasetId:e,experimentIdA:t,experimentIdB:n,onSwap:r}){const[s,a]=v.useState(null),{data:i,isLoading:l,error:c}=hls(e,t,n),{data:u}=Kq(e,t),{data:d}=Kq(e,n),f=u&&d&&u.datasetVersion!==d.datasetVersion,p=v.useMemo(()=>{if(!i)return[];const E=new Set;for(const T of i.items)for(const N of Object.values(T.results))if(N)for(const I of Object.keys(N.scores))E.add(I);return[...E].sort()},[i]),h=v.useMemo(()=>{if(!i||p.length===0)return[];const E=i.baselineId,T=t===E?n:t;return p.map(N=>{let I=0,A=0,R=0,L=0;for(const F of i.items){const U=F.results[E]?.scores[N],q=F.results[T]?.scores[N];U!=null&&(I+=U,R++),q!=null&&(A+=q,L++)}const D=R>0?I/R:null,z=L>0?A/L:null,H=D!=null&&z!=null?z-D:null;return{scorerId:N,avgA:D,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"}],g=v.useMemo(()=>[{name:"itemId",label:"Item ID",size:"8rem"},...s?[]:p.map(E=>({name:E,label:E,size:"1fr"}))],[p,s]),y=i?.items.find(E=>E.itemId===s)??null,b=E=>{a(E===s?null:E)},x=()=>{a(null)},S=()=>{if(!i||!s)return;const E=i.items.findIndex(T=>T.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(T=>T.itemId===s);if(E>0)return()=>a(i.items[E-1].itemId)};if(l)return o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(Jt,{})});if(c)return o.jsx(Sn,{variant:"warning",title:"Error loading comparison",children:o.jsx(Sn.Message,{children:c instanceof Error?c.message:"Unknown error"})});if(!i||i.items.length===0)return o.jsx("div",{className:"text-neutral4 py-8 text-center text-sm",children:"No comparison data"});const C=i.baselineId,_=t===C?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(FJe,{datasetId:e,experiment:u,type:"baseline"}),o.jsx("div",{className:"before:bg-border1 relative flex items-center justify-center px-[2vw] before:absolute before:inset-y-0 before:left-1/2 before:w-[2px] before:-translate-x-1/2",children:o.jsx("div",{className:"bg-surface2 relative z-1 rounded-lg p-2",children:o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx(ce,{onClick:r,children:"VS"})}),o.jsx(Pn,{children:"Switch the order"})]})})}),o.jsx(FJe,{datasetId:e,experiment:d,type:"contender"})]}),f&&o.jsx(Sn,{variant:"warning",title:"Version mismatch",children:o.jsxs(Sn.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(MXe,{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(MXe,{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:T,avgB:N,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:T!=null?T.toFixed(3):"-"}),o.jsx(yn.TextCell,{className:"text-center font-mono",children:N!=null?N.toFixed(3):"-"}),o.jsx(yn.TextCell,{className:"flex justify-center",children:I!=null?o.jsx(gAe,{delta:I}):"-"})]},E))})})]}),o.jsxs(fy,{className:X({"grid-cols-[1fr_2fr]":!!y}),children:[o.jsx(Ous,{items:i.items,baselineId:C,contenderId:_,scorerIds:p,featuredItemId:s,columns:g,onItemClick:b}),!!y&&o.jsx(kus,{item:y,baselineId:C,contenderId:_,baselineVersion:u?.datasetVersion,contenderVersion:d?.datasetVersion,onPrevious:k(),onNext:S(),onClose:x})]})]})}function Eus({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=uAe(e,t),[l,c]=v.useState(!1),[u,d]=v.useState(new Set),f=b=>{n?.(b)},p=b=>s==null?b.isLatest:b.datasetVersion===s,h=b=>{d(x=>{const S=new Set(x);if(S.has(b))S.delete(b);else if(S.size>=2){const[k]=Array.from(S);return new Set([k,b])}else S.add(b);return S})},m=()=>{c(!1),d(new Set)},g=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(Qr,{className:"min-w-56",children:[l?o.jsx(Qr.Toolbar,{className:"grid w-full justify-stretch gap-3",children:o.jsxs(Mr,{children:[o.jsx(ce,{onClick:m,children:"Cancel"}),o.jsx(ce,{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(Qr.Toolbar,{children:o.jsxs(ce,{onClick:g,className:"w-full",children:[o.jsx(s1,{})," Compare Ver."]})})}),i?o.jsx(Tus,{}):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 x=String(b.datasetVersion),S=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(yn.Row,{isSelected:l&&u.has(x),children:[l&&o.jsx(yn.LabelCell,{children:o.jsx(qo,{checked:u.has(x),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||h(x)},"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:S,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function Tus(){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 jus(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${rr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function Nus({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=$Ie(e),a=(s??[]).map(i=>({value:String(i.version),label:`${jus(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(Qr.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(jc,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(jc,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const Ius=[{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"}],Aus={added:{color:"blue",borderColor:"border-blue-900",icon:o.jsx(Wr,{}),tooltip:"Added in this version"},changed:{color:"orange",borderColor:"border-yellow-900",icon:o.jsx(Zot,{}),tooltip:"Changed in this version"},same:{color:"green",borderColor:"border-green-900",icon:o.jsx(NZt,{}),tooltip:"Same in both versions"}};function fie({red:e=!1,tooltip:t}){return o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx(mWt,{className:X("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),t&&o.jsx(Pn,{children:t})]})}function uk({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}=Aus[e];return o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"text-ui-md text-neutral4 flex min-w-16 justify-end pr-3",children:["v. ",t]}),o.jsx(ea,{color:n,size:"small",children:r})]})}),o.jsx(Pn,{children:s})]})}function Rus(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function Pus({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=Rus(u,d);return o.jsxs(yn.Row,{columns:Ius,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(uk,{variant:"added",version:u.datasetVersion}):f==="changed"&&l?o.jsx(uk,{variant:"changed",version:u.datasetVersion}):o.jsx(uk,{version:u.datasetVersion})}):o.jsx(yn.Cell,{className:"flex items-center justify-center",children:o.jsx(fie,{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(uk,{variant:"added",version:d.datasetVersion}):f==="changed"&&!l?o.jsx(uk,{variant:"changed",version:d.datasetVersion}):o.jsx(uk,{version:d.datasetVersion})}):o.jsx(yn.Cell,{className:"flex items-center justify-center",children:o.jsx(fie,{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(uk,{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(fie,{tooltip:o.jsxs(o.Fragment,{children:["Comparing is available",o.jsx("br",{})," only for changed items"]})})})]},c)})})})})}const BJe={needsReview:"#facc15",complete:"#22c55e"},$us=[{label:"Needs Review",color:BJe.needsReview},{label:"Reviewed",color:BJe.complete}];function Mus({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=v.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,p=0;const h=[];for(const m of e.counts){const g=m.needsReview+m.complete;if(g===0)continue;p+=g,g>f&&(f=g);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,x=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);h.push({name:x,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(BN,{data:a,segments:$us,maxVal:i,fmt:u=>String(u)}):o.jsx(Wt.NoData,{message:"No items have been sent to review yet"})})]})}function vAe(){const e=We();return yt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function WBt(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 Dus(e,t){const n=new Map,r=WBt(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 Lus(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 zus=10;function Fus(){const[e,t]=v.useState(!1),[n,r]=v.useState(""),[s,a]=v.useState("all"),[i,l]=v.useState("all"),[c,u]=v.useState("all"),[d,f]=v.useState(0),{data:p,isLoading:h,error:m}=Wg({page:d,perPage:zus}),{data:g,isLoading:y,error:b}=kQ(),{data:x}=vAe(),S=v.useMemo(()=>p?.datasets??[],[p?.datasets]),k=p?.pagination?.hasMore??!1,C=v.useMemo(()=>g?.experiments??[],[g?.experiments]),_=v.useMemo(()=>Als(S),[S]),E=v.useMemo(()=>Dus(x,C),[x,C]),T=h||y,N=m||b,I=()=>t(!0),A=v.useCallback(()=>f(q=>q+1),[]),R=v.useCallback(()=>f(q=>Math.max(0,q-1)),[]),L=v.useCallback(q=>{r(q),f(0)},[]),D=v.useCallback(q=>{a(q),f(0)},[]),z=v.useCallback(q=>{l(q),f(0)},[]),H=v.useCallback(q=>{u(q),f(0)},[]);if(N&&ws(N))return o.jsx(cr,{children:o.jsx(Zs,{})});if(N&&Ss(N))return o.jsx(cr,{children:o.jsx(Ms,{resource:"datasets"})});if(N)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load datasets",message:N.message})});if(S.length===0&&!T&&d===0)return o.jsxs(o.Fragment,{children:[o.jsx(cr,{children:o.jsx(Dls,{onCreateClick:I})}),o.jsx(rxe,{open:e,onOpenChange:t})]});const F=s!=="all"||i!=="all"||c!=="all"||n!=="",U=()=>{r(""),a("all"),l("all"),u("all"),f(0)};return o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsx(Fls,{search:n,onSearchChange:L,targetFilter:s,onTargetFilterChange:D,experimentFilter:i,onExperimentFilterChange:z,tagFilter:c,onTagFilterChange:H,tagOptions:_,onReset:U,hasActiveFilters:F,onCreateClick:I})}),o.jsx(Mls,{datasets:S,experiments:C,reviewByDataset:E,isLoading:T,search:n,targetFilter:s,experimentFilter:i,tagFilter:c,currentPage:d,hasMore:k,onNextPage:A,onPrevPage:R}),o.jsx(rxe,{open:e,onOpenChange:t})]})}function ZF({children:e}){return o.jsxs(Bt,{height:"full",children:[o.jsx("div",{}),o.jsx(Bt.MainArea,{isCentered:!0,children:e})]})}function Bus(){const{datasetId:e}=Sr(),t=Ws(),[n,r]=ri(),{activeVersion:s}=dAe(n,r),[a,i]=v.useState(!1),[l,c]=v.useState(!1),[u,d]=v.useState(!1),[f,p]=v.useState(!1),[h,m]=v.useState(!1),{data:g,error:y,isLoading:b}=a0(e),{data:x=[],isLoading:S}=B1(e,void 0,s),k=!S&&x.length===0;if(b)return null;if(y&&ws(y))return o.jsx(ZF,{children:o.jsx(Zs,{})});if(y&&Ss(y))return o.jsx(ZF,{children:o.jsx(Ms,{resource:"datasets"})});if(y&&gEe(y)||!b&&!y&&!g)return o.jsx(ZF,{children:o.jsx(Lr,{iconSlot:o.jsx(py,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(ce,{as:za,to:"/datasets",children:[o.jsx($c,{}),"Back to Datasets"]})})});if(y)return o.jsx(ZF,{children:o.jsx(Hi,{title:"Failed to load dataset",message:y instanceof Error?y.message:"An unexpected error occurred. Please try again."})});const C=E=>{t(`/datasets/${e}/experiments/${E}`)},_=()=>{t("/datasets")};return o.jsxs(o.Fragment,{children:[o.jsxs(Bt,{height:"full",children:[o.jsx(Bt.TopArea,{children:o.jsxs(Bt.Row,{children:[o.jsxs(Bt.Column,{children:[g?.description&&o.jsx("p",{className:"text-ui-smd text-neutral3 mb-1",children:g.description}),o.jsxs(Vt,{numOfCol:2,children:[o.jsx(Vt.Key,{children:"Created at"}),o.jsx(Vt.Value,{children:g?.createdAt?rr(new Date(g.createdAt),"MMM d, yyyy"):""}),o.jsx(Vt.Key,{children:"Latest version"}),o.jsxs(Vt.Value,{children:["v",g?.version??""]})]})]}),o.jsx(Bt.Column,{children:o.jsxs(Mr,{children:[k?o.jsxs($n,{children:[o.jsx(Rn,{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(ce,{variant:"primary",children:[o.jsx(jf,{}),s!=null?`Run on v${s}`:"Run Experiment"]})})})}),o.jsx(Pn,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(ce,{variant:"primary",onClick:()=>i(!0),children:[o.jsx(jf,{}),s!=null?`Run on v${s}`:"Run Experiment"]}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ce,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(qD,{})})}),o.jsxs(ot.Content,{align:"end",className:"w-48",children:[o.jsxs(ot.Item,{onSelect:()=>d(!0),children:[o.jsx(lm,{})," Edit Dataset"]}),o.jsxs(ot.Item,{onSelect:()=>m(!0),children:[o.jsx(im,{})," Duplicate Dataset"]}),o.jsxs(ot.Item,{onSelect:()=>p(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(vu,{})," Delete Dataset"]})]})]})]})})]})}),o.jsx(Bt.MainArea,{children:o.jsx(tus,{datasetId:e,onAddItemClick:()=>c(!0)})})]}),o.jsx(cus,{datasetId:e,version:s??void 0,requestContextSchema:g?.requestContextSchema,open:a,onOpenChange:i,onSuccess:C}),o.jsx(rus,{datasetId:e,open:l,onOpenChange:c}),g&&o.jsx(Wls,{open:u,onOpenChange:d,dataset:{id:g.id,name:g.name,description:g?.description||"",targetType:g.targetType,inputSchema:g.inputSchema,groundTruthSchema:g.groundTruthSchema,requestContextSchema:g.requestContextSchema}}),g&&o.jsx(qls,{open:h,onOpenChange:m,sourceDatasetId:g.id,sourceDatasetName:g.name,sourceDatasetDescription:g.description,sourceDatasetTargetType:g.targetType}),g&&o.jsx(Gls,{open:f,onOpenChange:p,datasetId:g.id,datasetName:g.name,onSuccess:_})]})}function ZBt({experiment:e}){const{Link:t,paths:n}=bn(),{data:r}=Am(),{data:s}=Ky(),{data:a}=ch(),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(Bt.TopArea,{children:o.jsxs(Bt.Row,{children:[o.jsx(Bt.Column,{children:o.jsxs(Vt,{numOfCol:2,children:[e.name&&o.jsxs(o.Fragment,{children:[o.jsx(Vt.Key,{children:"Name"}),o.jsx(Vt.Value,{children:e.name})]}),e.description&&o.jsxs(o.Fragment,{children:[o.jsx(Vt.Key,{children:"Description"}),o.jsx(Vt.Value,{children:e.description})]}),o.jsx(Vt.Key,{children:"Created at"}),o.jsx(Vt.Value,{children:rr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")}),e.completedAt&&o.jsxs(o.Fragment,{children:[o.jsx(Vt.Key,{children:"Completed at"}),o.jsx(Vt.Value,{children:rr(new Date(e.completedAt),"MMM d, yyyy 'at' h:mm a")})]}),o.jsx(Vt.Key,{children:"Target"}),o.jsx(Vt.ValueLink,{href:i(),as:t,children:l()}),e.agentVersion&&o.jsxs(o.Fragment,{children:[o.jsx(Vt.Key,{children:"Version"}),c?o.jsx(Vt.ValueLink,{href:c,as:t,children:e.agentVersion}):o.jsx(Vt.Value,{children:e.agentVersion})]})]})}),o.jsx(Bt.Column,{children:o.jsx(wus,{experiment:e})})]})})}function GF({children:e}){return o.jsxs(Bt,{height:"full",children:[o.jsx("div",{}),o.jsx(Bt.MainArea,{isCentered:!0,children:e})]})}function Uus(){const{datasetId:e,experimentId:t}=Sr(),{data:n,isLoading:r,error:s}=Kq(e,t),{data:a,isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u}=iQ({datasetId:e,experimentId:t,experimentStatus:n?.status});return!e||!t||r?null:s&&ws(s)?o.jsx(GF,{children:o.jsx(Zs,{})}):s&&Ss(s)?o.jsx(GF,{children:o.jsx(Ms,{resource:"datasets"})}):s&&gEe(s)||!r&&!s&&!n?o.jsx(GF,{children:o.jsx(Lr,{iconSlot:o.jsx(Cxe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${t}".`,actionSlot:o.jsxs(ce,{as:za,to:`/datasets/${e}?tab=experiments`,children:[o.jsx($c,{}),"Back to Dataset"]})})}):s?o.jsx(GF,{children:o.jsx(Hi,{title:"Failed to load experiment",message:s instanceof Error?s.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Bt,{height:"full",children:[o.jsx(ZBt,{experiment:n}),o.jsx(Bt.MainArea,{children:o.jsx(HBt,{experimentId:t,datasetId:e,experimentStatus:n.status,results:a??[],isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u})})]})}function qus(){const{datasetId:e}=Sr(),[t,n]=ri(),{error:r}=a0(e??""),s=t.get("baseline")??"",a=t.get("contender")??"";return r&&ws(r)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})}):r&&Ss(r)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"datasets"})})}):!e||!s||!a?o.jsx(ds,{children:o.jsx(Ny,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"mt-2 text-sm",children:["Use the URL format: /datasets/","{datasetId}","/experiments?baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):o.jsx(ds,{children:o.jsx(Ny,{children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[100rem] content-start px-12",children:[o.jsxs(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(s1,{})," Dataset Experiments Comparison"]}),o.jsxs(ha.Description,{children:["Comparing"," ",o.jsx(za,{to:`/datasets/${e}/experiments/${s}`,children:s.slice(0,8)})," vs"," ",o.jsx(za,{to:`/datasets/${e}/experiments/${a}`,children:a.slice(0,8)})]})]}),o.jsx(ha.Column,{children:o.jsxs(ce,{as:za,to:`/datasets/${e}`,children:[o.jsx($c,{}),"Back to Dataset"]})})]}),o.jsx(Cus,{datasetId:e,experimentIdA:s,experimentIdB:a,onSwap:()=>{n({baseline:a,contender:s})}})]})})})}function Vus(){const{datasetId:e,itemId:t}=Sr(),{Link:n}=bn(),r=Ws(),{data:s,isLoading:a,error:i}=uAe(e??"",t??""),{updateItem:l,deleteItem:c}=Ii(),{data:u}=a0(e??""),d=s?.[0]??null,f=d?.isDeleted??!1,[p,h]=v.useState(null),m=v.useMemo(()=>!d||f?{input:"",groundTruth:"",metadata:"",trajectory:"",toolMocks:"",requestContext:""}:{input:JSON.stringify(d.input,null,2),groundTruth:d.groundTruth?JSON.stringify(d.groundTruth,null,2):"",metadata:d.metadata?JSON.stringify(d.metadata,null,2):"",trajectory:d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):"",toolMocks:d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):"",requestContext:d.requestContext?JSON.stringify(d.requestContext,null,2):""},[d,f]),g=d?.datasetVersion??0,[y,b]=v.useState(!1),[x,S]=v.useState(m.input),[k,C]=v.useState(m.groundTruth),[_,E]=v.useState(m.metadata),[T,N]=v.useState(m.trajectory),[I,A]=v.useState(m.toolMocks),[R,L]=v.useState(m.requestContext),[D,z]=v.useState(g);g!==D&&(z(g),S(m.input),C(m.groundTruth),E(m.metadata),N(m.trajectory),A(m.toolMocks),L(m.requestContext));const[H,F]=v.useState(!1),U=ee=>{h(f?ee:ee.isLatest?null:ee)},q=()=>{h(null)},M=!f&&p!=null,G=()=>{M||b(!0)},V=()=>{M||F(!0)},$=async()=>{if(!e||!t)return;let ee;try{ee=JSON.parse(x)}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(_.trim())try{ae=JSON.parse(_)}catch{De.error("Metadata must be valid JSON");return}let fe;const Y=T!==m.trajectory;if(Y&&T.trim())try{fe=JSON.parse(T)}catch{De.error("Expected Trajectory must be valid JSON");return}let re;const le=I!==m.toolMocks;if(le&&I.trim())try{const me=JSON.parse(I);if(!Array.isArray(me)){De.error("Tool Mocks must be a JSON array");return}re=me}catch{De.error("Tool Mocks must be valid JSON");return}let ue;const oe=R!==m.requestContext;if(oe&&R.trim())try{ue=JSON.parse(R)}catch{De.error("Request Context must be valid JSON");return}try{await l.mutateAsync({datasetId:e,itemId:t,input:ee,groundTruth:J,metadata:ae,...Y?{expectedTrajectory:fe??null}:{},...le?{toolMocks:re??[]}:{},...oe?{requestContext:ue}:{}}),De.success("Item updated successfully"),b(!1)}catch(me){De.error(`Failed to update item: ${me instanceof Error?me.message:"Unknown error"}`)}},B=()=>{d&&(S(JSON.stringify(d.input,null,2)),C(d.groundTruth?JSON.stringify(d.groundTruth,null,2):""),E(d.metadata?JSON.stringify(d.metadata,null,2):""),N(d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):""),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(ee){De.error(`Failed to delete item: ${ee instanceof Error?ee.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&&ws(i)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})}):i&&Ss(i)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"datasets"})})}):a?null:!e||!t||!s||s.length===0?o.jsx(ds,{children:o.jsx(Ny,{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:"mx-auto grid h-full max-w-[60rem] grid-rows-[auto_1fr] gap-6",children:[o.jsxs(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(GN,{}),t," ",o.jsx(Pa,{content:t})]}),o.jsx(ha.Description,{children:o.jsxs(_o,{children:["Item of ",o.jsx(py,{})," ",u?.name]})}),o.jsxs(ha.Description,{children:[o.jsxs(_o,{children:[o.jsx(Iot,{})," Created at"," ",d?.createdAt?rr(new Date(d.createdAt),"MMM d, yyyy"):""]}),o.jsxs(_o,{children:[o.jsx(O_,{})," Latest version v",d?.datasetVersion??""]})]})]}),o.jsx(ha.Column,{children:!y&&!f&&o.jsxs(Mr,{children:[o.jsxs(ce,{onClick:G,disabled:M,title:M?"Return to latest version to edit":void 0,children:[o.jsx(Zot,{})," Edit"]}),o.jsxs(ce,{onClick:V,disabled:M,title:M?"Return to latest version to delete":void 0,children:[o.jsx(vu,{})," Delete"]})]})})]}),o.jsxs(fy,{className:y?"grid-cols-1":"grid-cols-[1fr_auto]",children:[o.jsxs(Qr,{withRightSeparator:!y,children:[f&&d&&o.jsx(Sn,{variant:"destructive",title:"Item deleted",children:o.jsxs(Sn.Message,{children:["This item was deleted at version v",d.datasetVersion]})}),!f&&M&&p&&o.jsx(Sn,{variant:"warning",title:"Previous version",action:o.jsxs(Sn.Button,{onClick:q,children:[o.jsx(Cot,{})," Return to the latest version"]}),children:o.jsxs(Sn.Message,{children:["Viewing version v",p.datasetVersion]})}),y?o.jsx(UBt,{inputValue:x,setInputValue:S,groundTruthValue:k,setGroundTruthValue:C,metadataValue:_,setMetadataValue:E,trajectoryValue:T,setTrajectoryValue:N,toolMocksValue:I,setToolMocksValue:A,requestContextValue:R,setRequestContextValue:L,validationErrors:null,onSave:$,onCancel:B,isSaving:l.isPending}):ne?o.jsx(hAe,{item:ne,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})]}),!y&&o.jsx(Qr,{children:o.jsx(Eus,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:U,onCompareVersionsClick:ee=>{r(`/datasets/${e}/items/${t}/versions?ids=${ee.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 UJe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function Hus(){const{datasetId:e}=Sr(),[t,n]=ri(),r=t.get("items")?.split(",").filter(Boolean)??[],{data:s,error:a}=a0(e??""),{Link:i}=bn(),[l,c]=v.useState(!1),{data:u}=Xq(e??"",r[0]??""),{data:d}=Xq(e??"",r[1]??"");return a&&ws(a)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})}):a&&Ss(a)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"datasets"})})}):!e||r.length<2?o.jsx(ds,{children:o.jsx(Ny,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two items to compare."})})})}):o.jsxs(ds,{children:[o.jsx(By,{owner:"dataset-items-compare",children:o.jsxs(ce,{as:za,to:`/datasets/${e}`,variant:"outline",children:[o.jsx($c,{}),"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(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(s1,{}),"Compare Dataset Items"]}),o.jsx(ha.Description,{children:o.jsxs(_o,{children:["Comparing ",r.length," items of"," ",o.jsx(za,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:s?.name||e?.slice(0,8)})]})})]}),o.jsx(ha.Column,{children:o.jsx(Mr,{children:o.jsx(ce,{variant:"primary",onClick:()=>c(f=>!f),children:l?o.jsxs(o.Fragment,{children:[o.jsx(Exe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(SZt,{})," Diff View"]})})})})]}),o.jsx(fy,{className:"grid-cols-[1fr_3vw_1fr]",children:r.map((f,p)=>o.jsxs(v.Fragment,{children:[o.jsx(Wus,{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(PTe,{codeA:UJe(u),codeB:UJe(d)})]})})]})}function Wus({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=Xq(e,t),{data:u}=B1(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(Qr,{children:[o.jsxs(Qr.Toolbar,{className:"flex gap-4",children:[o.jsxs(ma,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(va,{"aria-label":"Item",children:o.jsx(ga,{placeholder:"Select item"})}),o.jsx(ya,{children:f.map(p=>o.jsx($r,{value:p.value,disabled:p.disabled,children:p.label},p.value))})]}),o.jsxs(ce,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(O_,{}),"Versions"]})]}),i&&o.jsx(Qr.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(sus,{item:l}),o.jsx(hAe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function qJe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function Zus(){const{datasetId:e,itemId:t}=Sr(),[n,r]=ri(),[s,a]=v.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(h=>!isNaN(h)&&h>0)??[],{data:l,error:c}=a0(e??""),{Link:u}=bn(),{data:d}=uAe(e??"",t??""),{data:f}=lxe(e??"",t??"",i[0]??0,l?.version),{data:p}=lxe(e??"",t??"",i[1]??0,l?.version);return c&&ws(c)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})}):c&&Ss(c)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"datasets"})})}):!e||!t||i.length<2?o.jsx(ds,{children:o.jsx(Ny,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})}):o.jsxs(ds,{children:[o.jsx(By,{owner:"dataset-item-versions-compare",children:o.jsxs(ce,{as:za,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx($c,{}),"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(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(s1,{}),"Compare Dataset Item Versions"]}),o.jsx(ha.Description,{children:o.jsxs(_o,{children:["Comparing ",i.length," versions of"," ",o.jsx(za,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(ha.Column,{children:o.jsx(Mr,{children:o.jsx(ce,{variant:"primary",onClick:()=>a(h=>!h),children:s?o.jsxs(o.Fragment,{children:[o.jsx(Exe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(oGt,{})," Diff View"]})})})})]}),o.jsx(fy,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((h,m)=>o.jsxs(v.Fragment,{children:[o.jsx(Gus,{datasetId:e,itemId:t,datasetVersion:h,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:g=>{const y=[...i];y[m]=g,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:X("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),s&&f&&p&&o.jsx(PTe,{codeA:qJe(f),codeB:qJe(p)})]})})]})}function Gus({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}=lxe(e,t,n,r),p=new Set(a.filter((g,y)=>y!==l)),h=s.map(g=>{const y=typeof g.updatedAt=="string"?new Date(g.updatedAt):g.updatedAt;return{value:String(g.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",g.datasetVersion]})," - ",rr(y,"MMM d, yyyy h:mm a"),g.isLatest?o.jsx(ea,{color:"blue",size:"small",children:"Latest"}):null]}),disabled:p.has(g.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(Qr,{children:[o.jsxs(Qr.Toolbar,{className:"grid grid-cols-[auto_1fr] gap-4",children:[o.jsx(O_,{className:"h-6 w-6 opacity-50"}),o.jsxs(ma,{name:`compare-version-${l}`,value:String(n),onValueChange:g=>u(Number(g)),children:[o.jsx(va,{"aria-label":"Version",className:"w-full",children:o.jsx(ga,{placeholder:"Select version"})}),o.jsx(ya,{children:h.map(g=>o.jsx($r,{value:g.value,disabled:g.disabled,children:g.label},g.value))})]})]}),c&&o.jsx(Qr.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(hAe,{item:m,Link:i})})]})}function Qus(){const{datasetId:e}=Sr(),[t]=ri(),n=t.get("ids")?.split(",").map(Number).filter(g=>!isNaN(g)&&g>0)??[],r=Ws(),{data:s,error:a}=a0(e??""),i=B1(e??"",void 0,n[0]??null),l=B1(e??"",void 0,n[1]??null),c=v.useMemo(()=>i.data??[],[i.data]),u=v.useMemo(()=>l.data??[],[l.data]),d=v.useMemo(()=>{const g=new Map;for(const y of[...c,...u])g.has(y.id)||g.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...g.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=v.useMemo(()=>new Map(c.map(g=>[g.id,g])),[c]),p=v.useMemo(()=>new Map(u.map(g=>[g.id,g])),[u]);if(a&&ws(a))return o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})});if(a&&Ss(a))return o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(ds,{children:o.jsx(Ny,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const h=(g,y,b)=>{r(`/datasets/${e}/items/${g}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(g,y)=>{r(`/datasets/${e}/versions?ids=${g},${y}`,{replace:!0})};return o.jsx(ds,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-6",children:[o.jsxs(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(KQt,{})," Compare Dataset Versions"]}),o.jsx(ha.Description,{children:o.jsxs(_o,{children:[o.jsx(O_,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(ha.Column,{children:o.jsxs(ce,{as:za,to:`/datasets/${e}`,children:[o.jsx($c,{}),"Back to Dataset"]})})]}),o.jsx(fy,{children:o.jsxs(Qr,{children:[o.jsx(Nus,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(Pus,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p,onItemClick:h})]})})]})})})}function cxe({children:e,className:t}){return o.jsx("div",{className:X("flex flex-wrap gap-8",t),children:e})}function Yus(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 Kus({scorers:e,datasets:t,experiments:n,avgScore:r,prevAvgScore:s,totalNeedsReview:a,isLoadingScorers:i,isLoadingDatasets:l,isLoadingExperiments:c,isLoadingScores:u,isLoadingReview:d}){const f=e?Object.keys(e).length:void 0,p=t?.length,h=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,g=Yus(n);return o.jsxs(o.Fragment,{children:[o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Total Scorers"}),i?o.jsx(Jr.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(f)}),o.jsx(Jr.NoChange,{message:"Static count"})]}):o.jsx(Jr.NoData,{})]}),o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Total Datasets"}),l?o.jsx(Jr.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(p)}),o.jsx(Jr.NoChange,{message:"Static count"})]}):o.jsx(Jr.NoData,{})]}),o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Avg Score"}),u?o.jsx(Jr.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(r)}),m?o.jsx(Jr.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(Jr.NoChange,{})]}):o.jsx(Jr.NoData,{})]}),o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Total Experiments"}),c?o.jsx(Jr.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(h)}),g?o.jsx(Jr.Change,{changePct:g.changePct,prevValue:g.prevValue}):o.jsx(Jr.NoChange,{})]}):o.jsx(Jr.NoData,{})]}),o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Needs Review"}),d?o.jsx(Jr.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(a)}),a>0?o.jsx(Jr.NoChange,{message:"items pending review"}):o.jsx(Jr.NoChange,{message:"All caught up"})]}):o.jsx(Jr.NoData,{})]})]})}const VJe="minmax(9rem,1fr) 1fr auto auto auto auto auto auto auto";function Xus(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}const Jus={completed:"success",running:"warning",failed:"error",pending:"neutral"};function eds({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all"}){const{paths:l,Link:c}=bn(),u=v.useMemo(()=>{const p=new Map;return t?.forEach(h=>p.set(h.id,h.name)),p},[t]),d=v.useMemo(()=>[...e].sort((p,h)=>{const m=p.createdAt?new Date(p.createdAt).getTime():0;return(h.createdAt?new Date(h.createdAt).getTime():0)-m}),[e]),f=v.useMemo(()=>{const p=s.toLowerCase();return d.filter(h=>{const m=h.datasetId?u.get(h.datasetId)??"":"",g=!p||h.id.toLowerCase().includes(p)||(h.name??"").toLowerCase().includes(p)||m.toLowerCase().includes(p)||(h.targetId??"").toLowerCase().includes(p),y=a==="all"||h.status===a,b=i==="all"||h.datasetId===i;return g&&y&&b})},[d,s,u,a,i]);return r?o.jsx(ll,{columns:VJe}):o.jsxs(ge,{columns:VJe,variant:"striped",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Experiment"}),o.jsx(ge.TopCell,{children:"Dataset"}),o.jsx(ge.TopCell,{children:"Target"}),o.jsx(ge.TopCell,{children:"Status"}),o.jsx(ge.TopCell,{className:"text-center",children:"Items"}),o.jsx(ge.TopCell,{className:"text-center",children:"Succeeded"}),o.jsx(ge.TopCell,{className:"text-center",children:"Failed"}),o.jsx(ge.TopCell,{className:"text-center",children:"Review"}),o.jsx(ge.TopCell,{children:"Date"})]}),f.map(p=>{const h=p.datasetId?u.get(p.datasetId)??cS(p.datasetId)??p.datasetId:"—",m=p.status??"pending",g=p.succeededCount??0,y=p.failedCount??0,b=p.totalItems??0,x=b>0?Math.round(g/b*100):0;return o.jsxs(ge.RowLink,{to:l.experimentLink(p.id),LinkComponent:c,children:[o.jsx(ge.Cell,{children:o.jsx(BBt,{experiment:p})}),o.jsx(ge.TextCell,{children:h}),o.jsx(ge.Cell,{children:o.jsxs("span",{className:"truncate",children:[p.targetType," ",p.targetId]})}),o.jsx(ge.Cell,{children:o.jsx(Og,{variant:Jus[m]??"neutral",withDot:!0,children:m})}),o.jsx(ge.TextCell,{className:"text-center",children:b}),o.jsx(ge.TextCell,{className:"text-center",children:o.jsxs("span",{className:g>0?"text-accent1":"",children:[g," (",x,"%)"]})}),o.jsx(ge.TextCell,{className:"text-center",children:o.jsx("span",{className:y>0?"text-accent2":"",children:y})}),o.jsx(ge.Cell,{className:"text-center",children:(()=>{const S=n?.get(p.id);if(!S)return o.jsx("span",{className:"text-neutral2",children:"—"});const k=S.needsReview+S.complete;return k===0?o.jsx("span",{className:"text-neutral2",children:"—"}):S.needsReview>0?o.jsxs(ea,{size:"small",color:"yellow",children:[S.needsReview," pending"]}):o.jsxs(ea,{size:"small",color:"green",children:[S.complete,"/",k," reviewed"]})})()}),o.jsx(ge.TextCell,{children:Xus(p.createdAt)})]},p.id)})]})}const tds=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function nds(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const QF={completed:"#22c55e",running:"#facc15",pending:"#fb923c",failed:"#f87171"},rds=[{label:"Completed",color:QF.completed},{label:"Running",color:QF.running},{label:"Pending",color:QF.pending},{label:"Failed",color:QF.failed}];function sds({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=v.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const p=f.datasetId??"unknown";c.has(p)||c.set(p,{completed:0,running:0,pending:0,failed:0});const h=c.get(p),m=f.status;m in h&&h[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,p])=>{const h=p.completed+p.running+p.pending+p.failed;return h>u&&(u=h),{name:l.get(f)??f.slice(0,12),values:[p.completed,p.running,p.pending,p.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(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(BN,{data:s,segments:rds,maxVal:a,fmt:l=>String(l)}):o.jsx(Wt.NoData,{message:"No experiments have been run yet"})})]})}const ads=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx($f,{}),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(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/datasets/running-experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(_a,{})]})})})});function ids({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(Ff,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t}),o.jsxs(Mr,{children:[o.jsx(jc,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...tds],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(jc,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(ce,{onClick:l,size:"sm",variant:"default",children:[o.jsx(ps,{className:"size-3"})," Reset"]})]})]})}function ods(){const[e,t]=v.useState("all"),[n,r]=v.useState({}),{data:s,isLoading:a,error:i}=ch(),{data:l,isLoading:c,error:u}=Wg(),{data:d,isLoading:f,error:p}=kQ(),{data:h,isLoading:m,isError:g,error:y}=Res(n),{data:b,isLoading:x,isError:S,error:k}=vAe(),C=l?.datasets,_=d?.experiments,E=v.useMemo(()=>Lus(b),[b]),T=i||u||p||y||k;return T&&ws(T)?o.jsx(cr,{children:o.jsx(Zs,{})}):T&&Ss(T)?o.jsx(cr,{children:o.jsx(Ms,{resource:"evaluation"})}):T?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load evaluation data",message:T.message})}):o.jsxs(Bt,{width:"wide",height:"full",children:[o.jsx(Bt.TopArea,{children:o.jsx(Bt.Row,{children:o.jsx(Bt.Column,{children:o.jsx(a4,{preset:e,onPresetChange:t,dateFrom:n.start,dateTo:n.end,onDateChange:(N,I)=>r(A=>I==="from"?{...A,start:N}:{...A,end:N})})})})}),o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsx(cxe,{children:o.jsx(Kus,{scorers:s,datasets:C,experiments:_,avgScore:h?.avgScore??null,prevAvgScore:h?.prevAvgScore??null,totalNeedsReview:E.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(qJr,{summaryData:h?.summaryData??[],overTimeData:h?.overTimeData??[],scorerNames:h?.scorerNames??[],avgScore:h?.avgScore??null,isLoading:m,isError:g}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(zls,{experiments:_,isLoading:f,isError:!!p}),o.jsx(sds,{experiments:_,datasets:C,isLoading:f,isError:!!p})]}),o.jsx(Mus,{reviewSummary:b,experiments:_,datasets:C,isLoading:x,isError:!!S})]})]})}function lds(){const[e,t]=v.useState(""),[n,r]=v.useState("all"),[s,a]=v.useState("all"),{data:i,isLoading:l,error:c}=Wg(),{data:u,isLoading:d,error:f}=kQ(),{data:p}=vAe(),h=v.useMemo(()=>i?.datasets??[],[i?.datasets]),m=v.useMemo(()=>u?.experiments??[],[u?.experiments]),g=v.useMemo(()=>nds(h),[h]),y=v.useMemo(()=>WBt(p),[p]),b=l||d,x=f||c;if(x&&ws(x))return o.jsx(cr,{children:o.jsx(Zs,{})});if(f&&Ss(f))return o.jsx(cr,{children:o.jsx(Ms,{resource:"experiments"})});if(c&&Ss(c))return o.jsx(cr,{children:o.jsx(Ms,{resource:"datasets"})});if(x)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load experiments",message:x.message})});if(m.length===0&&!b)return o.jsx(cr,{children:o.jsx(ads,{})});const S=n!=="all"||s!=="all"||e!=="",k=()=>{t(""),r("all"),a("all")};return o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsx(ids,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:g,onReset:k,hasActiveFilters:S})}),o.jsx(eds,{experiments:m,datasets:h,reviewByExperiment:y,isLoading:b,search:e,statusFilter:n,datasetFilter:s})]})}function YF({children:e}){return o.jsxs(Bt,{height:"full",children:[o.jsx("div",{}),o.jsx(Bt.MainArea,{isCentered:!0,children:e})]})}function cds(){const{experimentId:e}=Sr(),{data:t,isLoading:n}=kQ(),s=t?.experiments?.find(h=>h.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=Kq(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p}=iQ({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&ws(l)?o.jsx(YF,{children:o.jsx(Zs,{})}):l&&Ss(l)?o.jsx(YF,{children:o.jsx(Ms,{resource:"datasets"})}):l&&gEe(l)||!n&&!s||!i&&!l&&!a?o.jsx(YF,{children:o.jsx(Lr,{iconSlot:o.jsx(Cxe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(ce,{as:za,to:"/experiments",children:[o.jsx($c,{}),"Back to Experiments"]})})}):l?o.jsx(YF,{children:o.jsx(Hi,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Bt,{height:"full",children:[o.jsx(ZBt,{experiment:a}),o.jsx(Bt.MainArea,{children:o.jsx(HBt,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p})})]})}function uds({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 GBt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(uds,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function dds({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(GBt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function fds({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(dds,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(GBt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function pds({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:a,providersError:i,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:p,onToolkitChange:h,onLabelChange:m,onConnect:g}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>p(y.target.value),disabled:a,children:[o.jsx("option",{value:"",children:"— select provider —"}),e.map(y=>o.jsxs("option",{value:y.id,children:[y.displayName??y.name," (",y.id,")"]},y.id))]}),a&&o.jsx("span",{className:"text-gray-500",children:"Loading providers…"}),i?o.jsx("span",{className:"text-red-600",children:String(i)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"toolkit-select",children:"Toolkit"}),o.jsxs("select",{id:"toolkit-select",className:"border rounded px-2 py-1 w-full",value:r,onChange:y=>h(y.target.value),disabled:!n||l,children:[o.jsx("option",{value:"",children:"— select toolkit —"}),t.map(y=>o.jsxs("option",{value:y.slug,children:[y.name," (",y.slug,")"]},y.slug))]}),l&&o.jsx("span",{className:"text-gray-500",children:"Loading toolkits…"}),c?o.jsx("span",{className:"text-red-600",children:String(c)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"label-input",children:"Label (optional)"}),o.jsx("input",{id:"label-input",type:"text",className:"border rounded px-2 py-1 w-full",placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value),disabled:!n||!r})]}),o.jsx("button",{type:"button",className:"bg-blue-600 text-white rounded px-4 py-2 disabled:opacity-50",onClick:g,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const HJe=e=>e.authorId?.trim()||"shared",hds=(e,t)=>{if(!t||new Set(e.map(HJe)).size<=1)return null;const r=new Map;for(const a of e){const i=HJe(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},mds=["*","tool-providers:*","tool-providers:admin"];function gds(){const{data:e}=Im();return e?.permissions?.some(t=>mds.includes(t))??!1}function vds(){const[e,t]=v.useState(""),[n,r]=v.useState(""),[s,a]=v.useState(""),i=WI(),l=NZ(e||null),c=mMt(e||null,n||null),u=hMt(),d=dMt(),f=gds(),p=i.data?.providers??[],h=l.data?.data??[],m=v.useMemo(()=>c.data?.items??[],[c.data?.items]),g=v.useMemo(()=>hds(m,f),[m,f]),y=S=>{t(S),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{a(""),c.refetch()}})},x=S=>{d.mutate({providerId:e,connectionId:S})};return o.jsxs("div",{className:"p-6 max-w-3xl space-y-6 text-sm",children:[o.jsx("h1",{className:"text-2xl font-semibold",children:"Integrations"}),o.jsx("p",{className:"text-gray-500",children:"Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect."}),o.jsx(pds,{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(fds,{providerId:e,toolkit:n,connections:m,groupedByAuthor:g,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:x})]})}function yds({title:e,description:t,errorBanner:n,children:r}){return o.jsx("div",{"data-testid":"login-page",className:"bg-surface1 flex min-h-screen items-center justify-center",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(nm,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-xl font-semibold",children:e})]}),t,n,r]})})}function QBt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=uc(),{mutate:i,isPending:l,error:c}=uIr(),{mutate:u,isPending:d,error:f}=fIr(),{mutate:p,isPending:h}=R2t(),[m,g]=v.useState(n),[y,b]=v.useState(""),[x,S]=v.useState(""),[k,C]=v.useState("");if(a)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:_}=s,E=_.type==="sso"||_.type==="both",T=_.type==="credentials"||_.type==="both",N=_.sso,I=_.signUpEnabled!==!1,A=m==="signin"||!I,R=A?l:d,L=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href=lQ("/")},z=M=>{M.preventDefault(),A?i({email:x,password:k},{onSuccess:D}):u({email:x,password:k,name:y||void 0},{onSuccess:D})},H=()=>{p({redirectUri:e},{onSuccess:M=>{window.location.href=M.url}})},F=()=>{g(A?"signup":"signin")},U=_.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(Tf,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-sm",children:_.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(yds,{title:A?"Sign in to Mastra Studio":"Create your account",description:U,errorBanner:q,children:[T&&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:"text-neutral4 block text-sm",children:"Name"}),o.jsx(Cn,{id:"name",type:"text",value:y,onChange:M=>b(M.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"email",className:"text-neutral4 block text-sm",children:"Email"}),o.jsx(Cn,{id:"email",type:"email",value:x,onChange:M=>S(M.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"password",className:"text-neutral4 block text-sm",children:"Password"}),o.jsx(Cn,{id:"password",type:"password",value:k,onChange:M=>C(M.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(ce,{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&&T&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"border-border1 w-full border-t"})}),o.jsx("div",{className:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),E&&N&&o.jsxs(ce,{onClick:H,disabled:h,className:"w-full",size:"lg",variant:"outline",children:[N.icon&&o.jsx("span",{className:"mr-2",children:N.icon}),h?"Redirecting...":N.text||"Sign in"]})]})}function bds(){const[e]=ri(),t=Ws(),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(QBt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}function xds({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 wds({onClick:e,tooltip:t="Close panel",className:n}){return o.jsx(ce,{size:"md",onClick:e,"aria-label":"Close Panel",tooltip:t,className:n,children:o.jsx(Ku,{})})}function Sds(){return xI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"#939393",background:"transparent"},styles:[{tag:[pe.className,pe.propertyName]}]})}function kds(){const e=It.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=Zg.define([{tag:[pe.comment,pe.bracket],color:"var(--neutral2)"},{tag:[pe.string,pe.meta,pe.regexp],color:"var(--accent1)"},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:"var(--accent6)"},{tag:[pe.keyword,pe.operator,pe.tagName],color:"var(--accent2)"},{tag:[pe.function(pe.propertyName),pe.propertyName],color:"var(--accent5)"},{tag:[pe.definition(pe.variableName),pe.function(pe.variableName),pe.className,pe.attributeName],color:"var(--accent3)"},{tag:[pe.variableName,pe.number],color:"var(--accent5)"},{tag:[pe.name,pe.quote],color:"var(--accent1)"}]);return[e,tS(t)]}const Ods=()=>{const e=Z_().resolvedTheme==="dark";return v.useMemo(()=>e?Sds():kds(),[e])};function _ds({codeStr:e="",title:t,icon:n,simplified:r=!1,className:s}){const a=Ods(),[i,l]=v.useState(!1),c=v.useMemo(()=>{try{const f=JSON.parse(e);return uxe(f||"")}catch{return!1}},[e]),u=i?e?.replace(/\\n/g,`
719
719
  `):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(Pa,{content:e||"No content",size:"sm"}),c&&o.jsx(ce,{size:"sm","aria-label":i?"Show escaped newlines":"Show multiline text",onClick:()=>l(f=>!f),children:i?o.jsx(F$,{}):o.jsx(F7,{})})]})]}),o.jsx("div",{className:"border-border1 bg-surface3 text-ui-sm text-neutral4 max-h-[30vh] overflow-hidden overflow-y-auto rounded-lg border p-3 break-all dark:border-white/10 dark:bg-black/20",children:d?o.jsx("div",{className:"text-neutral4 font-mono break-all",children:o.jsx("pre",{className:"text-wrap",children:u})}):o.jsx(ed,{extensions:[Hj(),It.lineWrapping],theme:a,value:e,editable:!1})})]})}function uxe(e){if(typeof e=="string"){const t=e.indexOf(`
720
- `);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>uxe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>uxe(t))}return!1}function Cds({children:e}){return o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e})}function Eds({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 Tds({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 jds({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 Nds({className:e,children:t}){return o.jsx("dt",{className:X("shrink-0 py-0.5 text-ui-smd text-neutral2",e),children:t})}function Ids({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 Ads({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 Rds=Object.assign(jds,{Key:Nds,Value:Ids,Header:Ads});function Pds({children:e}){return o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center justify-center gap-2 px-4 py-6",children:[o.jsx(Jt,{size:"sm",variant:"pulse",className:"text-neutral3"})," ",e??"Loading..."]})}function $ds({children:e}){return o.jsx("p",{className:"text-ui-sm text-neutral2 px-4 py-6",children:e??"No data found."})}const Bi=Object.assign(xds,{Header:Eds,Heading:Tds,CloseButton:wds,LoadingData:Pds,NoData:$ds,Content:Cds,KeyValueList:Rds,CodeSection:_ds}),fp=Bi.KeyValueList;function Mds(e){return e instanceof Date?e:new Date(e)}function Dds({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=v.useState(!1),d=i??c,f=l??u,p=Mds(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:rr(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[l&&o.jsx(ce,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(pH,{}):o.jsx(d1e,{})}),o.jsxs(Mr,{spacing:"close",children:[o.jsx(ce,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(fH,{})}),o.jsx(ce,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(w3,{})})]}),o.jsx(Bi.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Bi.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",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(ce,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(B7,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",h]})]}),o.jsx(Pa,{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(ce,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(B7,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(Pa,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(fp,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(fp.Key,{children:"Entity Type"}),o.jsx(fp.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(fp.Key,{children:"Entity Name"}),o.jsx(fp.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(fp.Key,{children:"Service"}),o.jsx(fp.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(fp.Key,{children:"Environment"}),o.jsx(fp.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(fp.Key,{children:"Source"}),o.jsx(fp.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([g,y])=>o.jsxs(v.Fragment,{children:[o.jsx(fp.Key,{children:g}),o.jsx(fp.Value,{children:String(y)})]},g))})]}),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 Lds({error:e,resource:t,errorTitle:n}){if(ws(e))return o.jsx(Zs,{});if(Ss(e))return o.jsx(Ms,{resource:t});if(I4(e))return o.jsx(Lr,{iconSlot:o.jsx(U7,{}),titleSlot:"Observability storage is not available",descriptionSlot:"The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio."});if(N4(e,"logs"))return o.jsx(Lr,{iconSlot:o.jsx(U7,{}),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 zds({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 Fds={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 Bds({level:e}){const t=Fds[e];return o.jsx(Io,{height:"compact",children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function Uds({entityType:e,className:t}){const n=X("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Ho,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(rd,{className:n,"aria-hidden":!0});case"tool":return o.jsx(qd,{className:n,"aria-hidden":!0});default:return null}}function qds({entityType:e,entityName:t}){const n=e??"";return o.jsxs(Io,{height:"compact",className:"flex min-w-0 items-center gap-2",children:[o.jsx(Uds,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function Vds({message:e}){return o.jsx(Io,{height:"compact",className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function Hds({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(Io,{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(iTe,{children:t})}const Ql=Object.assign(F4,{Top:DZ,TopCell:fC,TopCellWithTooltip:LZ,TopCellSmart:nDt,RowWrapper:uTe,RowButton:B4,RowLink:tDt,Spacer:dTe,NoMatch:MZ,DateCell:oTe,TimeCell:lTe,LevelCell:Bds,EntityCell:qds,MessageCell:Vds,DataCell:Hds,NextPageLoading:$Z}),WJe="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",Wds=36,Zds=8;function Gds({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=v.useRef(null),u=EBt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>Wds,overscan:Zds}),d=v.useRef(t);if(v.useEffect(()=>{d.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),d.current=t},[t]),t)return o.jsx(ll,{columns:WJe});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:WJe,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(g=>{const y=e[g.index];if(!y)return null;const b=a.get(y);if(!b)return null;const x=b===i;return o.jsxs(Ql.RowButton,{ref:u.measureElement,"data-index":g.index,onClick:()=>l(y),featured:x,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 Qds({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=>Yds(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(QIe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(ZIe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Yds(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 Kds={"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"},pie="MMM d, yyyy HH:mm",hie="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function Xds({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${Kds[e]}`,description:hie}:t&&n?{title:`No logs between ${rr(t,pie)} and ${rr(n,pie)}`,description:hie}:t?{title:`No logs since ${rr(t,pie)}`,description:hie}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const Jds=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=Xds({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(U7,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(f1e,{})]})})})},efs=20,tfs=1e4;function nfs(e,t,n){if(e?.pagination?.hasMore)return n+1}function rfs(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 sfs(e){return N4(e.state.error,"logs")||I4(e.state.error)?!1:tfs}const afs=({filters:e}={})=>{const t=We(),{inView:n,setRef:r}=X_(),s=Q1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:efs},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:nfs,select:rfs,retry:!1,refetchInterval:sfs}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return v.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}},KF={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},YBt=[{label:"Agent",entityType:KF.AGENT},{label:"Workflow",entityType:KF.WORKFLOW},{label:"Scorer",entityType:KF.SCORER},{label:"Ingest",entityType:KF.INGEST}],ifs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Yx="rootEntityType",sx="datePreset",ax="dateFrom",ix="dateTo",ofs=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"},LL=Object.keys(Il),yAe=new Set(["tags"]),bAe="mastra:logs:saved-filters";function lfs(e,t=bAe){const n=pfs(e),r=e.get(sx);r&&n.set(sx,r);const s=e.get(ax);s&&n.set(ax,s);const a=e.get(ix);a&&n.set(ix,a);try{localStorage.setItem(t,n.toString())}catch{}}function cfs(e=bAe){try{localStorage.removeItem(e)}catch{}}function ZJe(e=bAe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function ufs(e){if(e.has(sx)||e.has(ax)||e.has(ix)||e.has(Yx))return!0;for(const t of LL)if(e.has(Il[t]))return!0;return!1}function dfs({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:YBt.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:ifs.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 ffs(e){const t=[],n=new Map([[Yx,"rootEntityType"]]);for(const s of LL)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),yAe.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 pfs(e){const t=new URLSearchParams,n=e.get(Yx);n&&t.set(Yx,n);for(const r of LL){const s=Il[r];if(yAe.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 hfs(e,t){e.delete(Yx);for(const n of LL)e.delete(Il[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Yx,n.value);continue}const r=Il[n.fieldId];if(r){if(yAe.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 mfs({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 gfs(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 vfs="Filters setting for Logs saved",yfs="Filters setting for Logs cleared up";function bfs(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=v.useState(()=>ZJe(r)!==null),c=v.useCallback(()=>{lfs(e,r),l(!0);const f=s?.saved??vfs;f!==!1&&De.success(f)},[e,r,s?.saved]),u=v.useCallback(()=>{cfs(r),l(!1);const f=s?.cleared??yfs;f!==!1&&De.success(f)},[r,s?.cleared]),d=v.useRef(!1);return v.useEffect(()=>{if(a||d.current||(d.current=!0,ufs(e)))return;const f=ZJe(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,g]of f)h.append(m,g);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function xfs(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 wfs(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,xfs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function Sfs(e,t,n,r){const s=v.useMemo(()=>wfs(e),[e]),a=v.useMemo(()=>{const h=new Map;for(const[m,g]of e.entries()){const y=s.get(g);y&&h.set(y,{log:g,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=v.useCallback(h=>s.get(h),[s]),d=v.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 dxe="logId",fxe="traceId",pxe="spanId",yP=1440*60*1e3,kfs={"last-24h":yP,"last-3d":3*yP,"last-7d":7*yP,"last-14d":14*yP,"last-30d":30*yP};function XF(e){e.delete(dxe),e.delete(fxe),e.delete(pxe)}function Ofs(e,t,n){const{onRemoveAll:r}={},s=v.useMemo(()=>{const C=e.get(sx);return C&&ofs.has(C)?C:"last-24h"},[e]),a=e.get(ax),i=e.get(ix),l=v.useMemo(()=>{if(s==="custom"){if(!a)return;const _=new Date(a);return Number.isNaN(_.getTime())?void 0:_}if(s==="all")return;const C=kfs[s];return C?new Date(Date.now()-C):void 0},[s,a]),c=v.useMemo(()=>{if(s!=="custom"||!i)return;const C=new Date(i);return Number.isNaN(C.getTime())?void 0:C},[s,i]),u=v.useRef(s);u.current=s;const d=e.get(dxe),f=e.get(fxe),p=e.get(pxe),h=v.useMemo(()=>YBt.find(C=>C.entityType===e.get(Yx)),[e]),m=v.useMemo(()=>ffs(e),[e]),g=v.useCallback(C=>{t(_=>{const E=new URLSearchParams(_);for(const[T,N]of Object.entries(C)){const I=T==="logId"?dxe:T==="traceId"?fxe:pxe;N?E.set(I,N):E.delete(I)}return E},{replace:!0})},[t]),y=v.useCallback(C=>{t(_=>{const E=new URLSearchParams(_);return hfs(E,C),XF(E),E},{replace:!0})},[t]),b=y,x=v.useCallback((C,_)=>{if(u.current!=="custom")return;const E=_==="from"?ax:ix;t(T=>{const N=new URLSearchParams(T);return C?N.set(E,C.toISOString()):N.delete(E),XF(N),N},{replace:!0})},[t]),S=v.useCallback(C=>{u.current=C,t(_=>{const E=new URLSearchParams(_);return C==="last-24h"?(E.delete(sx),E.delete(ax),E.delete(ix)):C==="custom"?E.set(sx,"custom"):(E.set(sx,C),E.delete(ax),E.delete(ix)),XF(E),E},{replace:!0})},[t]),k=v.useCallback(()=>{t(C=>{const _=new URLSearchParams(C);_.delete(Yx);for(const E of LL)_.delete(Il[E]);return _.delete(sx),_.delete(ax),_.delete(ix),XF(_),_},{replace:!0}),r?.()},[t,r]);return v.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:g,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:S,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,g,b,x,S,k,y])}const Nb=Bi.KeyValueList;function _fs({spanId:e,span:t,isLoading:n,onClose:r}){const s=KIe(t?.startedAt,t?.endedAt);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(Nb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(Nb.Key,{children:"Type"}),o.jsx(Nb.Value,{children:t.spanType})]}),t.startedAt&&o.jsxs(o.Fragment,{children:[o.jsx(Nb.Key,{children:"Started"}),o.jsx(Nb.Value,{children:rr(new Date(t.startedAt),"MMM dd, HH:mm:ss.SSS")})]}),t.endedAt&&o.jsxs(o.Fragment,{children:[o.jsx(Nb.Key,{children:"Ended"}),o.jsx(Nb.Value,{children:rr(new Date(t.endedAt),"MMM dd, HH:mm:ss.SSS")})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(Nb.Key,{children:"Duration"}),o.jsx(Nb.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Bi.CodeSection,{title:"Input",icon:o.jsx(Jhe,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Output",icon:o.jsx(eme,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Metadata",icon:o.jsx(Tw,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Attributes",icon:o.jsx(Tw,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Bi.NoData,{children:"Span not found."})]})}function Cfs({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=v.useMemo(()=>eAe(t??[]),[t]),[l,c]=v.useState([]);v.useEffect(()=>{i.length>0&&c(JIe(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(OBt,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function Efs(){const[e,t]=ri(),n=Ofs(e,t),r=bfs(e,t),[s,a]=v.useState(),[i,l]=v.useState(!1),{data:c=[],isPending:u}=oAe(),{data:d=[],isPending:f}=sAe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=aAe(),{data:m=[],isPending:g}=iAe(),y=v.useMemo(()=>dfs({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:g,environments:h}}),[c,d,m,p,u,f,g,h]),b=v.useMemo(()=>mfs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:S,error:k,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:E}=afs({filters:b}),{logIdMap:T,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=Sfs(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=lAe(n.featuredTraceId??null),{data:z,isLoading:H}=DL(n.featuredTraceId??"",n.featuredSpanId??""),F=v.useCallback(()=>n.applyFilterTokens(gfs(y,n.filterTokens)),[y,n]),U=v.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),q=v.useCallback(K=>n.handleFeaturedChange({traceId:K,spanId:null}),[n]),M=v.useCallback((K,ne)=>n.handleFeaturedChange({traceId:K,spanId:ne}),[n]),G=v.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),V=v.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=v.useCallback(K=>n.handleFeaturedChange({spanId:K??null}),[n]),B=o.jsxs(Bt.TopArea,{children:[o.jsx(Bt.Row,{children:o.jsxs(Bt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(a4,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:S,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(YIe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx(Qds,{isLoading:S,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(Bt,{width:"wide",height:"full",children:[B,o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsx(Lds,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!S&&!Z?o.jsxs(Bt,{width:"wide",height:"full",children:[B,o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsx(Jds,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Bt,{width:"wide",height:"full",children:[B,o.jsx(zds,{logCollapsed:i,listSlot:o.jsx(Gds,{logs:x,isLoading:S,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:E,logIdMap:T,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(Dds,{log:N,onClose:U,onTraceClick:q,onSpanClick:M,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(Cfs,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(_fs,{spanId:n.featuredSpanId,span:z?.span,isLoading:H,onClose:V}):null})]})}function Tfs({server:e}){const{paths:t,Link:n}=bn(),s=We().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=J8t(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=Qh(e.name,50);return o.jsxs(ge.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(ge.NameCell,{children:f}),o.jsx(ge.DescriptionCell,{children:a}),o.jsx(ge.TextCell,{className:"text-center",children:u||""}),o.jsx(ge.TextCell,{className:"text-center",children:c||""}),o.jsx(ge.TextCell,{className:"text-center",children:d||""})]})}function jfs({mcpServers:e,isLoading:t,search:n=""}){const r=v.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(ll,{columns:"auto 1fr auto auto auto"}):o.jsxs(ge,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Name"}),o.jsx(ge.TopCell,{children:"URL"}),o.jsx(ge.TopCellSmart,{long:"Agents",short:o.jsx(Ho,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(ge.TopCellSmart,{long:"Tools",short:o.jsx(qd,{}),tooltip:"Tools",className:"text-center"}),o.jsx(ge.TopCellSmart,{long:"Workflows",short:o.jsx(rd,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(ge.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(Tfs,{server:s},s.id))]})}const Nfs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx($f,{}),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(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(_a,{})]})})}),Ifs=()=>{const{data:e=[],isLoading:t,error:n}=JG(),[r,s]=v.useState("");return n&&ws(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx(Ms,{resource:"MCP servers"})}):n?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(cr,{children:o.jsx(Nfs,{})}):o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(Ff,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(jfs,{mcpServers:e,isLoading:t,search:r})]})},Afs=(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 Rfs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=bn(),i=v.useMemo(()=>Afs(e,t),[e,t]),l=v.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(ll,{columns:"auto 1fr auto"}):o.jsxs(ge,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Name"}),o.jsx(ge.TopCell,{children:"Description"}),o.jsx(ge.TopCellSmart,{long:"Agents",short:o.jsx(Ho,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(ge.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=Qh(c.id,50),d=Qh(c.description??"",200),f=c.agents.length;return o.jsxs(ge.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(ge.NameCell,{children:u}),o.jsx(ge.DescriptionCell,{children:d}),o.jsx(ge.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const Pfs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx($f,{}),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(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(_a,{})]})})}),$fs=()=>{const e=We();return Ln({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new A_;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}}})},Mfs=({toolId:e})=>{const{canExecute:t}=Go(),n=t("tools"),{data:r={}}=Am(),s=v.useMemo(()=>{for(const g of Object.values(r))if(g.tools){const y=Object.values(g.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=SNr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=$fs(),{requestContext:p}=hs();v.useEffect(()=>{if(l){const g=l instanceof Error?l.message:"Failed to load tool";De.error(`Error loading tool: ${g}`)}},[l]);const h=async(g,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:g,requestContext:b})},m=c?.inputSchema?gm(hm(Ax(c?.inputSchema))):Os({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(kt,{className:"mb-4 h-8 w-48"}),o.jsx(kt,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(OIe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function Dfs({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}=VI(),{data:p={},isLoading:h,isError:m,error:g}=Am(),{navigate:y,paths:b}=bn();v.useEffect(()=>{if(d){const C=f instanceof Error?f.message:"Failed to load tools";De.error(`Error loading tools: ${C}`)}},[d,f]),v.useEffect(()=>{if(m){const C=g instanceof Error?g.message:"Failed to load agents";De.error(`Error loading agents: ${C}`)}},[m,g]);const x=new Map;Object.values(p).forEach(C=>{C.tools&&Object.values(C.tools).forEach(_=>{x.has(_.id)||x.set(_.id,_)})}),Object.values(c).forEach(C=>{x.has(C.id)||x.set(C.id,C)});const S=Array.from(x.values()).map(C=>({label:C.id,value:C.id})),k=C=>{t?t(C):C&&C!==e&&y(b.toolLink(C))};return o.jsx(Fl,{options:S,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const Lfs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=v.useState({sseUrl:"",httpStreamUrl:""});if(v.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(Ny,{children:o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(Ny,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(on,{icon:o.jsx(wBt,{className:"text-neutral6"}),className:"text-neutral4! rounded-r-sm",children:"Version"}),o.jsx(on,{className:"text-neutral4! rounded-l-sm",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:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(on,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",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:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(on,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",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:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(on,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",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:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(zfs,{server:t})})]})},zfs=({server:e})=>{const{data:t={},isLoading:n}=J8t(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"overflow-y-scroll p-5",children:[o.jsxs("div",{className:"text-neutral6 flex items-center gap-2",children:[o.jsx(qe,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(wC,{})}),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(Bfs,{tool:a,serverId:e.id},s)})})]})};function Ffs(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 Bfs=({tool:e,serverId:t})=>{const n=v.useRef(null),{Link:r,paths:s}=bn(),a=_9t[e.toolType||"tool"],i=Ffs(e._meta);return o.jsxs(Uf,{onClick:()=>n.current?.click(),children:[o.jsx(pMt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Vf,{children:[o.jsx(qf,{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(on,{className:"py-0 text-[10px]",children:"App"})]})}),o.jsx(sh,{children:e.description})]})]})},Ufs=()=>{const{serverId:e}=Sr(),{data:t=[],isLoading:n}=JG(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(Lfs,{isLoading:n,server:r})})};function qfs(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 Vfs=({toolId:e,serverId:t})=>{const{canExecute:n}=Go(),r=n("tools"),s=We(),{data:a,isLoading:i,error:l}=vIe(t,e),{mutateAsync:c,isPending:u,data:d}=PKr(t,e),f=a?qfs(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=v.useCallback(async(y,b)=>await c(b),[c]);v.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";De.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(kt,{className:"mb-4 h-8 w-48"}),o.jsx(kt,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let g;try{g=gm(hm(a.inputSchema))}catch(y){console.error("Error processing input schema:",y),De.error("Failed to process tool input schema."),g=Os({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(X8t,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(OIe,{executionResult:d,isExecutingTool:u,zodInputSchema:g,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},Hfs=()=>{const{serverId:e,toolId:t}=Sr(),{data:n,isLoading:r}=vIe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Vfs,{toolId:t,serverId:e})})},KBt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],UN="rootEntityType",qN={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"},OQ=Object.keys(qN),xAe="mastra:metrics:saved-filters";function Wfs(e){const t=Kfs(e);try{localStorage.setItem(xAe,t.toString())}catch{}}function Zfs(){try{localStorage.removeItem(xAe)}catch{}}function XBt(){try{const e=localStorage.getItem(xAe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function Gfs(e){if(e.has(UN))return!0;for(const t of OQ)if(e.has(qN[t]))return!0;return!1}function Qfs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:KBt.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 Yfs(e){const t=[],n=new Map([[UN,"rootEntityType"]]);for(const s of OQ)n.set(qN[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 Kfs(e){const t=new URLSearchParams,n=e.getAll(UN);for(const r of n)t.append(UN,r);for(const r of OQ){const s=qN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function Xfs(e,t){e.delete(UN);for(const n of OQ)e.delete(qN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?UN:qN[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 Jfs="Any";function GJe(e){const t=e.trim();return t===""||t===Jfs}const eps=new Set(KBt.map(e=>e.entityType));function QJe(e){const t=e.trim();return eps.has(t)?t:void 0}function tps(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=>!GJe(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?QJe(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(GJe(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=QJe(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const JBt=[{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"}],nps=new Set(JBt.map(e=>e.value));function rps(e){return typeof e=="string"&&(nps.has(e)||e==="custom")}const eUt=v.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function _Q(){return v.useContext(eUt)}function sps(e,t){return e!=="custom"?JBt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${rr(t.from,"MMM d, yyyy")} – ${rr(t.to,"MMM d, yyyy")}`:rr(t.from,"MMM d, yyyy"):"Custom range"}function aps({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=v.useMemo(()=>JSON.stringify(n),[n]),d=v.useMemo(()=>n,[u]),f=v.useMemo(()=>tps(d),[d]),p=v.useMemo(()=>JSON.stringify(f),[f]),h=sps(t,a),m=v.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(eUt.Provider,{value:m,children:e})}const ips=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function ops(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 lps(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 cps(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=_Q(),s=v.useRef(e);s.current=e;const a=v.useRef(n);return a.current=n,o.jsx(a4,{preset:ops(e),onPresetChange:i=>{const l=lps(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:ips})}const hxe=1440*60*1e3,ups={"24h":hxe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function dps(e,t,n){if(e!=="custom"){const r=ups[e]??hxe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-hxe),end:t?.to??new Date(n)}}function Mm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=_Q(),s=v.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=v.useMemo(()=>dps(e,t,i),[e,t,i]),c=v.useMemo(()=>({timestamp:l,...n}),[l,r]),u=v.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function tUt(){const e=We(),{filters:t,filterKey:n}=Mm();return yt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function zL({href:e,LinkComponent:t="a"}){return o.jsx(ce,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(kjn,{})})}function fps({href:e,LinkComponent:t="a"}){return o.jsx(ce,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(rNn,{})})}const pps=[{dataKey:"p50",label:"p50",color:qp.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:qp.yellow,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p95,0)/e.length)}`:"0",suffix:"avg ms"})}];function hps(e){return e==="agents"||e==="workflows"||e==="tools"}function mie({data:e,onPointClick:t}){return e.length===0?o.jsx(Wt.NoData,{message:"No latency data yet"}):o.jsx(Qq,{data:e,series:pps,onPointClick:t?n=>{const r=n;typeof r?.tsMs=="number"&&Number.isFinite(r.tsMs)&&t(r)}:void 0})}function mps({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]=v.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),g=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=g.length>0?`${Math.round(g.reduce((b,x)=>b+x,0)/g.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(gc,{value:p,onValueChange:b=>{hps(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(mc,{children:[o.jsx(Nr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Nr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Nr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Kr,{value:"agents",children:o.jsx(mie,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Kr,{value:"workflows",children:o.jsx(mie,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Kr,{value:"tools",children:o.jsx(mie,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Wt.NoData,{message:"No latency data yet"})})]})}function gps(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 vps(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 nUt(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=gps(s);l&&e.set(t,l)}function Do(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function rUt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function YJe({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(Mw,"branches"),nUt(a,Dw,Lw,zw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Gx,i),r.status&&a.set(Qx,r.status),Do(a,Nl.entityName,r.entityName??n.entityName),Do(a,Nl.threadId,r.threadId??n.threadId),Do(a,Nl.resourceId,r.resourceId??n.resourceId),Do(a,Nl.entityId,n.entityId),Do(a,Nl.runId,n.runId),Do(a,Nl.sessionId,n.sessionId),Do(a,Nl.requestId,n.requestId),Do(a,Nl.userId,n.userId),Do(a,Nl.organizationId,n.organizationId),Do(a,Nl.experimentId,n.experimentId),Do(a,Nl.serviceName,n.serviceName),Do(a,Nl.environment,n.environment),rUt(a,Nl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function yps({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;nUt(a,sx,ax,ix,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Yx,i),Do(a,Il.entityName,r.entityName??n.entityName),Do(a,Il.threadId,r.threadId??n.threadId),Do(a,Il.resourceId,r.resourceId??n.resourceId),Do(a,Il.runId,n.runId),Do(a,Il.sessionId,n.sessionId),Do(a,Il.requestId,n.requestId),Do(a,Il.userId,n.userId),Do(a,Il.organizationId,n.organizationId),Do(a,Il.experimentId,n.experimentId),Do(a,Il.serviceName,n.serviceName),Do(a,Il.environment,n.environment),rUt(a,Il.tags,n.tags),r.status==="error"&&a.append(Il.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function cA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=_Q(),a=v.useCallback((c={})=>YJe({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=v.useCallback((c={})=>yps({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=v.useCallback((c,u,d)=>{const f=vps(u,d);return YJe({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const sUt="1h";async function gie(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:sUt,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 bps(){const e=We(),{filters:t,filterKey:n}=Mm();return yt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([gie(e,"mastra_agent_duration_ms",t),gie(e,"mastra_workflow_duration_ms",t),gie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:sUt}}})}const KJe={agents:du.AGENT,workflows:du.WORKFLOW_RUN,tools:du.TOOL};function xps(){const{data:e,isLoading:t,isError:n}=bps(),{getTracesHref:r,getBucketTracesHref:s}=cA(),{Link:a}=bn(),i=Ws();return o.jsx(mps,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:KJe[l]},c.tsMs,"1h"))},actions:l=>o.jsx(zL,{href:r({rootEntityType:KJe[l]}),LinkComponent:a})})}function wps(e){return e==="threads"||e==="resources"}function vie(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Sps({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=v.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,g=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"}),g?o.jsx(Wt.Actions,{children:g}):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(gc,{defaultTab:"threads",value:i,onValueChange:y=>{wps(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(mc,{children:[o.jsx(Nr,{value:"threads",children:"Threads"}),o.jsx(Nr,{value:"resources",children:"Resources"})]}),o.jsx(Kr,{value:"threads",children:d?o.jsxs(ge,{columns:"auto auto auto auto auto",...axe,children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ge.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:vie(y.threadId)}),o.jsx(ge.NumberCell,{children:y.resourceId?vie(y.resourceId):"—"}),o.jsx(ge.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(ge.NumberCell,{children:y.tokens>0?Ml(y.tokens):"—"}),o.jsx(ge.NumberCell,{children:y.cost!=null?sm(y.cost,y.costUnit):"—"})]});return b?o.jsx(ge.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ge.RowStatic,{children:x},y.key)})]}):o.jsx(Wt.NoData,{message:"No thread activity yet"})}),o.jsx(Kr,{value:"resources",children:f?o.jsxs(ge,{columns:"auto auto auto auto",...axe,children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ge.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:vie(y.resourceId)}),o.jsx(ge.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(ge.NumberCell,{children:y.tokens>0?Ml(y.tokens):"—"}),o.jsx(ge.NumberCell,{children:y.cost!=null?sm(y.cost,y.costUnit):"—"})]});return b?o.jsx(ge.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ge.RowStatic,{children:x},y.key)})]}):o.jsx(Wt.NoData,{message:"No resource activity yet"})})]})})]})}const yie=20;function kps(){const e=We(),{filters:t,filterKey:n}=Mm();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:yie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:yie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:yie})]),l=new Map,c=d=>lA(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 bie=20;function Ops(){const e=We(),{filters:t,filterKey:n}=Mm();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:bie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:bie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:bie})]),l=new Map,c=d=>lA(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 _ps(){const e=kps(),t=Ops(),{getTracesHref:n}=cA(),{Link:r}=bn();return o.jsx(Sps,{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 FL({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:e}),o.jsx(Jr.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(Jr.Error,{}):s?o.jsx(Jr.Loading,{}):i?r!=null?o.jsx(Jr.Change,{changePct:r,prevValue:n}):o.jsx(Jr.NoChange,{}):o.jsx(Jr.NoData,{})]})}function Cps(){const e=We(),{filters:t,filterKey:n}=Mm();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 Eps(){const e=We(),{filters:t,filterKey:n}=Mm();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 Tps(){const e=We(),{filters:t,filterKey:n}=Mm();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 jps(){const e=We(),{filters:t,filterKey:n}=Mm();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 Nps(){const{data:e,isLoading:t,isError:n}=tUt();return o.jsx(FL,{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 Ips(){const{data:e,isLoading:t,isError:n}=Tps();return o.jsx(FL,{label:"Total Model Cost",value:e?.cost!=null?sm(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?sm(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function Aps(){const{data:e,isLoading:t,isError:n}=jps();return o.jsx(FL,{label:"Total Tokens",value:e?.value!=null?Ml(e.value):null,prevValue:e?.previousValue!=null?Ml(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Rps(){const{data:e,isLoading:t,isError:n}=Eps();return o.jsx(FL,{label:"Total Threads",value:e?.value!=null?Ml(e.value):null,prevValue:e?.previousValue!=null?Ml(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Pps(){const{data:e,isLoading:t,isError:n}=Cps();return o.jsx(FL,{label:"Total Resources",value:e?.value!=null?Ml(e.value):null,prevValue:e?.previousValue!=null?Ml(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function $ps({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=>Mps(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(QIe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(ZIe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Mps(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 Dps({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?sm(l):"—":c.size===1?u=l>0?sm(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(ge,{columns:"auto auto auto auto auto auto",...axe,children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{sticky:"start",children:"Model"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(ge.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:l.model}),o.jsx(ge.NumberCell,{children:l.input}),o.jsx(ge.NumberCell,{children:l.output}),o.jsx(ge.NumberCell,{children:l.cacheRead}),o.jsx(ge.NumberCell,{children:l.cacheWrite}),o.jsx(ge.NumberCell,{highlight:!0,children:l.cost!=null?sm(l.cost,l.costUnit):"—"})]});return c?o.jsx(ge.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(ge.RowStatic,{children:u},l.model)})]}):o.jsx(Wt.NoData,{message:"No model usage data yet"})})]})}function Lps(){const e=We(),{filters:t,filterKey:n}=Mm();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=>lA(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:Ml(f.input),output:Ml(f.output),cacheRead:Ml(f.cacheRead),cacheWrite:Ml(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function zps(){const{data:e,isLoading:t,isError:n}=Lps(),{getTracesHref:r}=cA(),{Link:s}=bn();return o.jsx(Dps,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:du.AGENT}),actions:o.jsx(zL,{href:r({rootEntityType:du.AGENT}),LinkComponent:s})})}function Fps(e){return e==="tokens"||e==="cost"}function Bps({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=v.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.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,g=h?f.reduce((b,x)=>b+(x.cost??0),0):0,y=h&&g>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:sm(g,m),label:"Total cost"}):o.jsx(Wt.Summary,{value:Ml(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(gc,{defaultTab:"tokens",value:i,onValueChange:b=>{Fps(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(mc,{children:[o.jsx(Nr,{value:"tokens",children:"Tokens"}),o.jsx(Nr,{value:"cost",children:"Cost"})]}),o.jsx(Kr,{value:"tokens",children:o.jsx(BN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:qp.blueDark},{label:"Output",color:qp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:Ml})}),o.jsx(Kr,{value:"cost",children:y?o.jsx(BN,{LinkComponent:a,data:f.slice().sort((b,x)=>(x.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:qp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>sm(b,m)}):o.jsx(Wt.NoData,{message:"No cost data yet"})})]}):o.jsx(Wt.NoData,{message:"No token usage data yet"})})]})}function Ups(){const e=We(),{filters:t,filterKey:n}=Mm();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=>lA(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 qps(){const{data:e,isLoading:t,isError:n}=Ups(),{getTracesHref:r}=cA(),{Link:s}=bn();return o.jsx(Bps,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:du.AGENT,entityName:a.name}),actions:o.jsx(zL,{href:r({rootEntityType:du.AGENT}),LinkComponent:s})})}function mxe(e,t=Ml){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const Vps=[{dataKey:"input",label:"Input tokens",color:qp.blue,aggregate:mxe("input")},{dataKey:"output",label:"Output tokens",color:qp.yellow,aggregate:mxe("output")}];function Hps(e){return e==="tokens"||e==="cost"}function Wps({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=v.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,C)=>k+C.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),g=m?[...h][0]??null:null,y=m?f.reduce((k,C)=>k+(C.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",S=[{dataKey:"cost",label:"Cost",color:qp.purple,aggregate:mxe("cost",k=>sm(k,g))}];return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Wt.Summary,{value:sm(y,g),label:"Total cost"}):o.jsx(Wt.Summary,{value:Ml(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(gc,{defaultTab:"tokens",value:a,onValueChange:k=>{Hps(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(mc,{children:[o.jsx(Nr,{value:"tokens",children:"Tokens"}),o.jsx(Nr,{value:"cost",children:"Cost"})]}),o.jsx(Kr,{value:"tokens",children:o.jsx(Qq,{data:c,series:Vps})}),o.jsx(Kr,{value:"cost",children:b?o.jsx(Qq,{data:p,series:S}):o.jsx(Wt.NoData,{message:"No cost data yet"})})]}):o.jsx(Wt.NoData,{message:"No token usage data yet"})})]})}function Zps(e){return e==="24h"?"1h":"1d"}function Gps(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 XJe(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 Qps(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function Yps(){const e=We(),{datePreset:t,filters:n,filterKey:r}=Mm(),s=Zps(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 XJe(l,a.series[0],"input"),XJe(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:Gps(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:Qps(u)}}),interval:s}}})}function Kps(){const{data:e,isLoading:t,isError:n}=Yps(),{getTracesHref:r}=cA(),{Link:s}=bn();return o.jsx(Wps,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(zL,{href:r(),LinkComponent:s})})}function xie({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(BN,{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:qp.blueDark},{label:"Errors",color:qp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:Ml})}function Xps({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=v.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,g)=>m+g.completed+g.errors,0):0,p=m=>r?g=>r(m,g):void 0,h=m=>s?g=>s(m,g):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:Ml(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(gc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(mc,{children:[o.jsx(Nr,{value:"agents",children:"Agents"}),o.jsx(Nr,{value:"workflows",children:"Workflows"}),o.jsx(Nr,{value:"tools",children:"Tools"})]}),o.jsx(Kr,{value:"agents",children:e.agentData.length>0?o.jsx(xie,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No agent data yet"})}),o.jsx(Kr,{value:"workflows",children:e.workflowData.length>0?o.jsx(xie,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No workflow data yet"})}),o.jsx(Kr,{value:"tools",children:e.toolData.length>0?o.jsx(xie,{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 wie(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=lA(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 Jps(){const e=We(),{filters:t,filterKey:n}=Mm();return yt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([wie(e,"mastra_agent_duration_ms",t),wie(e,"mastra_workflow_duration_ms",t),wie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const JF={agents:du.AGENT,workflows:du.WORKFLOW_RUN,tools:du.TOOL};function ehs(){const{data:e,isLoading:t,isError:n}=Jps(),{getTracesHref:r,getLogsHref:s}=cA(),{Link:a}=bn();return o.jsx(Xps,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:JF[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:JF[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(zL,{href:r({rootEntityType:JF[i]}),LinkComponent:a}),o.jsx(fps,{href:s({rootEntityType:JF[i],status:"error"}),LinkComponent:a})]})})}const Sie="period",e8="dateFrom",t8="dateTo";function ths(){const[e,t]=ri(),n=e.get(Sie),r=rps(n)?n:"24h",s=v.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(e8)),p=d(e.get(t8));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=v.useMemo(()=>Yfs(e),[e.toString()]),i=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(Sie):p.set(Sie,d),d!=="custom"&&(p.delete(e8),p.delete(t8)),p},{replace:!0})},[t]),l=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(e8,d.from.toISOString()):p.delete(e8),d?.to?p.set(t8,d.to.toISOString()):p.delete(t8),p},{replace:!0})},[t]),c=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return Xfs(p,d),p},{replace:!0})},[t]),u=v.useRef(!1);return v.useEffect(()=>{if(u.current||(u.current=!0,Gfs(e)))return;const d=XBt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(aps,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(nhs,{})})}function nhs(){const[e]=ri(),{error:t,isLoading:n}=tUt(),{filterTokens:r,setFilterTokens:s}=_Q(),[a,i]=v.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=jBt(),{data:d,isLoading:f}=oAe(),{data:p,isLoading:h}=sAe(),{data:m,isLoading:g}=iAe(),{data:y,isLoading:b}=aAe(),x=v.useMemo(()=>Qfs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:g,environments:b}}),[d,p,m,y,f,h,g,b]),[S,k]=v.useState(()=>XBt()!==null),C=v.useCallback(()=>{Wfs(e),k(!0),De.success("Filters setting for Metrics saved")},[e]),_=v.useCallback(()=>{Zfs(),k(!1),De.success("Filters setting for Metrics cleared up")},[]),E=v.useCallback(()=>{s([])},[s]),T=v.useCallback(()=>{const N=r.map(I=>{const A=x.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(N)},[x,r,s]);return t&&ws(t)?o.jsx(cr,{children:o.jsx(Zs,{})}):t&&Ss(t)?o.jsx(cr,{children:o.jsx(Ms,{resource:"metrics"})}):t?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Bt,{width:"wide",height:"full",children:[o.jsxs(Bt.TopArea,{children:[o.jsx(Bt.Row,{children:o.jsxs(Bt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(cps,{}),o.jsx(YIe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx($ps,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:T,onRemoveAll:E,onSave:C,onRemoveSaved:S?_:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(Sn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(Sn.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(cxe,{children:[o.jsx(Nps,{}),o.jsx(Ips,{}),o.jsx(Aps,{}),o.jsx(Rps,{}),o.jsx(Pps,{})]}),o.jsxs(cxe,{children:[o.jsx(zps,{}),o.jsx(qps,{}),o.jsx(Kps,{}),o.jsx(_ps,{}),o.jsx(ehs,{}),o.jsx(xps,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx($f,{}),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(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(_a,{})]})})})]})}const rhs=50;function shs(){const{paths:e}=bn(),{isCmsAvailable:t}=dS(),[n,r]=v.useState(""),[s,a]=v.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=E9t({page:s,perPage:rhs}),d=i?.promptBlocks??[],f=i?.hasMore??!1,p=v.useCallback(()=>{u||a(g=>g+1)},[u]),h=v.useCallback(()=>{u||a(g=>Math.max(0,g-1))},[u]),m=v.useCallback(g=>{r(g),a(0)},[]);return c&&ws(c)?o.jsx(cr,{children:o.jsx(Zs,{})}):c&&Ss(c)?o.jsx(cr,{children:o.jsx(Ms,{resource:"prompt blocks"})}):c?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(cr,{children:o.jsx(Bts,{})}):o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsxs(Bt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Ff,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(ce,{as:za,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Wr,{}),"Create Prompt"]})]})}),o.jsx(Fts,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:p,onPrevPage:h})]})}function ahs(){return o.jsx(Bt,{width:"narrow",children:o.jsx(Bt.MainArea,{children:o.jsx(bXr,{children:o.jsx(Dbe,{})})})})}const ihs=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:EZt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:jot,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:_a,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:bj,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:Dot,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:Not,href:"https://mastra.ai/contact?ref=studio",external:!0}];function ohs(){return o.jsx(Bt,{width:"narrow",children:o.jsx(Bt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:ihs.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group border-border1 bg-surface2 hover:border-accent1 hover:bg-surface3 flex flex-col gap-3 rounded-lg border p-5 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"text-icon3 group-hover:text-accent1 h-5 w-5 transition-colors"}),o.jsx("span",{className:"text-ui-md text-text1 font-medium",children:e.title}),e.external&&o.jsx(_a,{className:"text-icon3 ml-auto h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function lhs(){const{data:e={},isLoading:t,error:n}=ch(),[r,s]=v.useState(""),[a,i]=v.useState("all");if(n&&ws(n))return o.jsx(cr,{children:o.jsx(Zs,{})});if(n&&Ss(n))return o.jsx(cr,{children:o.jsx(Ms,{resource:"scorers"})});if(n)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(cr,{children:o.jsx(GJr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsx(YJr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(ZJr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function chs(){const{scorerId:e}=Sr(),[t,n]=ri(),r=t.get("scoreId")??void 0,[s,a]=v.useState(r),[i,l]=v.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=OJr(e),{data:d={},isLoading:f,error:p}=Am(),{isLoading:h,error:m}=Ky(),{data:g=[],isLoading:y,error:b,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k}=kJr({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),C=v.useMemo(()=>c?.agentIds?.filter(q=>d[q]).map(q=>({value:q,label:d[q].name,type:"AGENT"}))||[],[c?.agentIds,d]),_=v.useMemo(()=>c?.workflowIds?.map(q=>({value:q,label:q,type:"WORKFLOW"}))||[],[c?.workflowIds]),E=v.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...C,..._],[C,_]),T=t.get("entity")??"all",N=E.find(q=>q.value===T);N&&N.value!==i?.value&&l(N),v.useEffect(()=>{if(u){const q=u instanceof Error?u.message:"Failed to load scorer";De.error(`Error loading scorer: ${q}`)}},[u]),v.useEffect(()=>{if(p){const q=p instanceof Error?p.message:"Failed to load agents";De.error(`Error loading agents: ${q}`)}},[p]),v.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(M=>{const G=new URLSearchParams(M);return G.set("entity",q.value),G})};v.useEffect(()=>{const q=t.get("scoreId")??void 0;if(q===s)return;if(!q){a(void 0);return}g.find(G=>G.id===q)&&a(q)},[t,g]);const A=v.useCallback(q=>{a(q||void 0),n(M=>{const G=new URLSearchParams(M);return q?G.set("scoreId",q):G.delete("scoreId"),G})},[n]);if(!c)return null;const R=ws(u)||ws(p)||ws(m),L=u&&Ss(u),D=!R&&!L&&(u||p||m),z=!y&&g.length===0,H=i?.value!=="all",F=c?.scorer?.source==="stored"?o.jsx(By,{owner:"scorer-detail",children:o.jsxs(ce,{variant:"default",as:za,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(lm,{})," Edit"]})}):null;if(R||L||D||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(Bt,{width:"wide",height:"full",children:[F,o.jsx(Bt.MainArea,{isCentered:!0,children:R?o.jsx(Zs,{}):L?o.jsx(Ms,{resource:"scorers"}):D?o.jsx(Hi,{title:"Failed to load scorer",message:q}):o.jsx(gJr,{})})]})}return o.jsxs(Bt,{width:"wide",children:[F,o.jsx(Bt.TopArea,{children:o.jsx(vJr,{selectedEntity:i,entityOptions:E,onEntityChange:I,onReset:()=>{n(q=>{const M=new URLSearchParams(q);return M.set("entity","all"),M})},isLoading:y||f||h})}),o.jsx(mJr,{scores:g,isLoading:y,selectedScoreId:s,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k,onScoreClick:A,errorMsg:b?.message})]})}function uhs({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(zt,{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-neutral3 text-sm",children:t})]}),s]})}const aUt=[{value:"dark",label:"Dark",Icon:iQt},{value:"light",label:"Light",Icon:yYt},{value:"system",label:"System",Icon:Vot}],dhs=e=>aUt.some(t=>t.value===e);function fhs({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex max-w-full min-w-0 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 phs=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=gH(),{theme:r,setTheme:s}=Z_();return o.jsx(Bt,{width:"narrow",children:o.jsxs(Bt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(ybe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(uhs,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(ma,{value:r,onValueChange:a=>{dhs(a)&&s(a)},children:[o.jsx(va,{id:"theme",className:"w-full sm:w-48",children:o.jsx(ga,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(ya,{children:aUt.map(a=>o.jsx($r,{value:a.value,children:o.jsx(fhs,{option:a})},a.value))})]})})}),o.jsx(ybe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(uDt,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function hhs(){const[e]=ri(),t=Ws(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(QBt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}const iUt=e=>o.jsx("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,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"})});function mhs(e){return e.replace(/\/$/,"").split("/").pop()}function CQ({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 ghs({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:"bg-surface3 h-16 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:"thumb transition-scale h-full w-full bg-cover 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:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",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(Ho,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(qd,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Hot,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(XN,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(wC,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center 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:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(iUt,{})," ",mhs(a.githubUrl)]})})]},a.slug)})})}function vhs({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(CN,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(jc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(jc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(ce,{onClick:c,children:["Reset ",o.jsx(ps,{})]})]})}function yhs(){const{data:e,isLoading:t}=Xtr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=v.useState("all"),[l,c]=v.useState("all"),[u,d]=v.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{p.push({value:x,label:x})});const h=(x,S)=>{S==="tag"?i(x):S==="provider"&&c(x)},m=x=>{d(x)},g=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(ds,{children:[o.jsx(E1e,{children:o.jsxs(Jvt,{children:[o.jsx(qe,{children:o.jsx(ty,{})}),"Templates"]})}),o.jsxs("div",{className:X("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(vhs,{selectedTag:a,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?g:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(ghs,{templates:y,linkComponent:za,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const bhs="1.58.0-alpha.4";function xhs({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(Rd,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(nGt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(CQ,{className:"text-neutral3 mb-8 content-center space-y-4",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:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",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:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs dark:bg-gray-800",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:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function whs({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(CQ,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",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(Wot,{})]}),o.jsx(jc,{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] items-start gap-4",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(Jt,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(v.Fragment,{children:[o.jsx(RO,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(RO,{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-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",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(r9t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ce,{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(Jt,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Sm,{})]})})]})})}function Shs({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(ty,{}),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 gap-x-24 lg:grid-cols-[1fr_1fr]",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:"mt-0.5 shrink-0",children:o.jsx(Xx,{className:"h-[1.1em] w-[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(Nxe,{className:"text-neutral4 h-[1em] w-[1em]"}),o.jsx("span",{className:"text-ui-md text-neutral5 font-medium",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 text-ui-sm rounded px-1.5 py-0.5 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:"text-neutral3 text-ui-md hover:text-neutral5 mt-auto flex items-center gap-2",children:[o.jsx(iUt,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(xIe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function khs(e){switch(e){case"running":return o.jsx(Jt,{});case"success":return o.jsx(Ix,{});case"failed":return o.jsx(Ku,{});default:return null}}function Ohs({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",xs.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",xs.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",xs.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:s(e)}),t.description&&o.jsx("p",{className:"text-ui-md text-neutral2 -mt-0.5",children:t.description})]})]}),o.jsx("div",{className:X("flex size-[1.75rem] items-center justify-center self-center rounded-full",xs.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:khs(t.status)})]})}function _hs({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:X(n),children:t.map((r,s)=>o.jsx(Ohs,{stepId:r.id,step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function Chs({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",xs.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",xs.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(Jt,{}):s+1})},r.id))}),o.jsxs("div",{className:X("text-center text-xs text-neutral3",xs.colors),children:[n," of ",t," steps completed"]})]})}function Ehs({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=g=>g==="input"||g.endsWith(".input")||g.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(g)||/[0-9a-f]{8,}/.test(g)?!1:r?.allSteps?g in r.allSteps:!0,f=Object.entries(c).filter(([g,y])=>d(g)),p=f.length,h=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([g,y])=>({id:g,status:y?.status,description:y?.description,title:g.charAt(0).toUpperCase()+g.slice(1).replace(/-/g," "),isActive:i?.id===g}));return o.jsxs(CQ,{className:"text-neutral3 mb-8 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-lg font-semibold",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-6",children:o.jsx(Chs,{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(gQt,{}),l||"Something went wrong"]}),u&&o.jsx(_hs,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 grid justify-items-center gap-4 text-center text-sm",children:[o.jsx(Jt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Ths({name:e,installedEntities:t}){return o.jsxs(CQ,{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Wot,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-neutral3 text-center",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(xIe,{data:t})]})}function jhs(){const{templateSlug:e}=Sr(),[t,n]=ri(),[r,s]=v.useState(""),[a,i]=v.useState(""),[l,c]=v.useState(""),[u,d]=v.useState({}),[f,p]=v.useState([]),[h,m]=v.useState(null),[g,y]=v.useState(!1),[b,x]=v.useState(""),[S,k]=v.useState(!1),[C,_]=v.useState(!1),[E,T]=v.useState([]),{data:N,isLoading:I}=Jtr({repoOrSlug:e,owner:"mastra-ai"}),R=bhs?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=enr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:z,isLoading:H}=tnr(),{mutateAsync:F,isPending:U}=nnr(),{mutateAsync:q}=rnr(),{streamInstall:M,streamResult:G,isStreaming:V}=anr(z),{observeInstall:$,streamResult:B,isStreaming:Z}=inr(z);v.useEffect(()=>{const re=t.get("runId");re&&!g&&!h&&!V&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:re}),x(re),q({runId:re}).then(le=>{const ue=le.snapshot;if(ue?.status==="success"&&ue?.result?.success)y(!0);else if(ue?.result?.success===!1)if(ue?.result?.validationResults&&!ue?.result?.validationResults?.valid&&ue?.result?.validationResults?.remainingErrors>0){const{remainingErrors:me,errors:be}=ue.result.validationResults,xe=`Template installation completed but ${me} validation issue${me>1?"s":""} remain unresolved.`;m(xe),T(be||[])}else{const me=ue?.result?.message||ue?.result?.error||"Template installation failed";m(typeof me=="string"?me:String(me))}}).catch(le=>{console.error("❌ Failed to fetch run details:",le),m("Failed to retrieve installation status after reload")}))},[t,g,h,V,Z,q]),v.useEffect(()=>{const re=t.get("runId"),le=t.get("resume"),ue=t.get("provider");if(re&&le==="true"&&ue&&!V&&!Z&&!S&&!C&&z){x(re),k(!0);try{q({runId:re}).then(oe=>{if(oe.snapshot?.status==="running")return $.mutateAsync({runId:re})}).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,S,C,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:N?.tools?.length?N.tools.map(re=>re).join(", "):"n/a",icon:o.jsx(qd,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(re=>re).join(", "):"n/a",icon:o.jsx(Ho,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(re=>re).join(", "):"n/a",icon:o.jsx(XN,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Fv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(KN,{})}],ee=[{...ne[0]},{...ne[1]},{...ne[2]}].filter(re=>re.value!=="n/a");v.useEffect(()=>{L&&d(L)},[L]),v.useEffect(()=>{const re=G||B;re?.phase==="error"&&re?.error&&m(typeof re.error=="string"?re.error:String(re.error))},[G?.phase,G?.error,B?.phase,B?.error]);const J=re=>{s(re)},ae=async re=>(i(re.provider),c(re.modelId),{message:"Model updated successfully"}),fe=async()=>{const re=Object.entries(u).reduce((le,[ue,oe])=>(oe===""&&le.push(ue),le),[]);if(re.length>0){p(re);return}if(N){m(null),y(!1),x(""),_(!0);try{const ue={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:oe}=await F({});x(oe),n(me=>{const be=new URLSearchParams(me);return be.set("runId",oe),be.set("resume","true"),be.set("provider",r||"openai"),be}),await M.mutateAsync({inputData:ue,selectedModel:{provider:a,modelId:l},runId:oe})}catch(le){_(!1),m(le?.message||"Template installation failed"),console.error("Template installation failed",le)}}},Y=re=>{const{name:le,value:ue}=re.target;ue.trim()===""?p(oe=>[...oe,le]):p(oe=>oe.filter(me=>me!==le)),d(oe=>({...oe,[le]:ue}))};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:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-6",children:[o.jsx(Shs,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:ne,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(V||Z)&&o.jsx(Ehs,{name:N.title,streamResult:Z?B:G,runId:b,workflowInfo:z}),g&&o.jsx(Ths,{name:N.title,installedEntities:ee,linkComponent:za}),h&&o.jsx(xhs,{errorMsg:h,validationErrors:E.length>0?E:G?.validationResults?.errors||B?.validationResults?.errors}),!V&&!Z&&!g&&!h&&o.jsx(whs,{providerOptions:K,selectedProvider:r,onProviderChange:J,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:fe,handleVariableChange:Y,isLoadingEnvVars:D||H,isInstalling:U,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const Nhs=()=>{const{toolId:e,agentId:t}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(sts,{toolId:e,agentId:t})})},Ihs=()=>{const{toolId:e}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(Mfs,{toolId:e})})};function Ahs(){const{traceId:e}=Sr(),[t,n]=ri(),r=Ws(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=v.useState(s??null),[d,f]=v.useState(),[p,h]=v.useState(i),[m,g]=v.useState(0),[y,b]=v.useState(!1),{data:x,isLoading:S,error:k}=lAe(e),C=v.useMemo(()=>x?.spans??[],[x?.spans]),_=v.useMemo(()=>C.find(ae=>ae.parentSpanId==null),[C]),{data:E,isLoading:T}=DL(e,c??"");v.useEffect(()=>g(0),[e,c]);const{data:N,isLoading:I}=ch(),{data:A,isLoading:R}=S9t({traceId:e,spanId:c??void 0,page:m}),[L,D]=v.useState(0);v.useEffect(()=>D(0),[e,c]);const{data:z,isLoading:H}=DBt({traceId:e,page:L});v.useEffect(()=>{if(l&&A?.scores&&!d){const ae=A.scores.find(fe=>fe.id===l);ae&&f(ae)}},[l,A?.scores,d]);const F=v.useCallback(ae=>{const fe=new URLSearchParams(t);for(const[Y,re]of Object.entries(ae))re===null||re===""?fe.delete(Y):fe.set(Y,re);n(fe,{replace:!0})},[t,n]),U=v.useCallback(ae=>{const fe=ae??null,Y=fe===c;u(fe),Y||(f(void 0),h("details"),F({spanId:fe,tab:null,scoreId:null}))},[c,F]),q=v.useCallback(()=>{u(null),f(void 0),h("details"),F({spanId:null,tab:null,scoreId:null})},[F]),M=v.useCallback(ae=>{u(ae),f(void 0),h("details"),F({spanId:ae,tab:null,scoreId:null})},[F]),{handlePreviousSpan:G,handleNextSpan:V}=cAe(C,c,M),$=v.useCallback(ae=>{const fe=ae;h(fe),f(void 0),F({tab:fe==="details"?null:fe,scoreId:null})},[F]),B=v.useCallback(ae=>{f(ae),F({scoreId:ae.id})},[F]),Z=v.useCallback(()=>{f(void 0),F({scoreId:null})},[F]),K=v.useCallback(()=>{r("/traces")},[r]),ne=v.useCallback(()=>{h("scoring"),_&&c!==_.spanId?(u(_.spanId),f(void 0),F({spanId:_.spanId,tab:"scoring",scoreId:null})):F({tab:"scoring"})},[_,c,F]),ee=_?o.jsx(By,{owner:"trace-detail",children:o.jsxs(Mr,{children:[o.jsxs(ce,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:ne,children:[o.jsx(QWt,{}),"Evaluate"]}),o.jsxs(ce,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(Ad,{}),"Save"]})]})}):null,J=_?o.jsx(Bt.Row,{children:o.jsx(Bt.Column,{children:o.jsx(xBt,{rootSpan:_,numOfCol:3})})}):null;return k?o.jsxs(Bt,{height:"full",children:[ee,J&&o.jsx(Bt.TopArea,{children:J}),o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsx(_Bt,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Bt,{height:"full",className:"grid-rows-[auto_minmax(0,1fr)] content-normal",children:[ee,J&&o.jsx(Bt.TopArea,{children:J}),o.jsx(ABt,{rootSpanId:_?.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(tAe,{traceId:e,spans:C,isLoading:S,onClose:K,onSpanSelect:U,onEvaluateTrace:ne,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!S&&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(XIe,{traceId:e,spanId:c,span:E?.span,isLoading:T,onClose:q,onPrevious:G,onNext:V,activeTab:p,onTabChange:$,feedbackTabBadge:z?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(PBt,{feedbackData:z,onPageChange:D,isLoadingFeedbackData:H}),scoringTabBadge:A?.pagination?.total??void 0,scoringTabSlot:({span:ae,traceId:fe,spanId:Y})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(MBt,{traceId:fe,isTopLevelSpan:!ae.parentSpanId,spanId:Y,entityType:ae.attributes?.agentId||ae.entityType===du.AGENT?"Agent":ae.attributes?.workflowId||ae.entityType===du.WORKFLOW_RUN?"Workflow":void 0,scorers:N,isLoadingScorers:I}),o.jsx($Bt,{scoresData:A,onPageChange:g,isLoadingScoresData:R,onScoreSelect:B})]})}),d&&o.jsx(bIe,{score:d,onClose:Z})]})]})]})}function Rhs(){const{data:e,isLoading:t,error:n}=Ky(),[r,s]=v.useState("");return n&&ws(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx(Ms,{resource:"workflows"})}):n?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(cr,{children:o.jsx(DBr,{})}):o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsxs(Bt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Ff,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(ce,{as:za,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(UD,{}),"Schedules"]})]})}),o.jsx(MBr,{workflows:e||{},isLoading:t,search:r})]})}const Phs={active:"bg-accent1",paused:"bg-accent3"},$hs={active:"text-accent1",paused:"text-accent3"},oUt=({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 ${Phs[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${$hs[e]}`,children:e})]}),hj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),Z2=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 lUt({status:e}){const{icon:t,color:n}=Mhs(e);return o.jsxs("span",{className:`text-ui-sm inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function Mhs(e){switch(e){case"success":return{icon:o.jsx(fa,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(ps,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Jt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(aV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx($f,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(yj,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const JJe="auto auto auto auto 1fr";function Dhs(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 Lhs(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 zhs=3e4,Fhs=5*6e4;function Bhs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=bn();return t?o.jsx(ll,{columns:JJe}):e.length===0?o.jsx(ye,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(ge,{columns:JJe,className:"min-w-0",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Run"}),o.jsx(ge.TopCell,{children:"Status"}),o.jsx(ge.TopCell,{children:"Started"}),o.jsx(ge.TopCell,{children:"Duration"}),o.jsx(ge.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=Lhs(u),f=`Scheduled ${hj(c.scheduledFireAt)} — published ${hj(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),g=!p&&m>zhs&&m<=Fhs,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),x=o.jsx("span",{className:b?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:c.runId}),S=o.jsxs(o.Fragment,{children:[o.jsx(ge.Cell,{height:"compact",children:x}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(Rd,{size:14}),"publish failed"]}):c.run?o.jsx(lUt,{status:c.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),h?o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(Rd,{size:14})})}),o.jsx(Pn,{children:h})]}):null]})}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:Z2(c.actualFireAt)}),g?o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(Rd,{size:14})})}),o.jsxs(Pn,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(ge.Cell,{height:"compact",children:c.run?o.jsx("span",{children:Dhs(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(ge.Cell,{height:"compact",children:" "})]});return b?o.jsx(ge.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:S},y):o.jsx(ge.RowStatic,{children:S},y)}),o.jsx(ge.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const Uhs=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)}})},eet=25,qhs=e=>{const t=We(),{inView:n,setRef:r}=X_(),s=Q1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:eet,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<eet))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return v.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},Vhs=e=>{const t=We(),n=Br();return Ln({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 n8({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function Hhs(){const{scheduleId:e}=Sr(),{paths:t}=bn(),{data:n,error:r}=Uhs(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=qhs(e),d=Vhs(e);if(r&&ws(r))return o.jsx(cr,{children:o.jsx(Zs,{})});if(r&&Ss(r))return o.jsx(cr,{children:o.jsx(Ms,{resource:"schedules"})});if(r)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsx(Bt.Row,{className:"justify-end",children:o.jsxs(Bt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(ce,{as:za,to:t.schedulesLink(),variant:"ghost",children:[o.jsx($c,{}),"Back to schedules"]}),f?o.jsx(ce,{as:za,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ce,{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(cV,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(jf,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-6 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(n8,{label:p?"Agent":"Workflow",children:f?o.jsx(za,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(za,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(n8,{label:"Cron",children:[o.jsx("code",{className:"text-ui-md font-mono",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 text-ui-sm ml-2",children:n.timezone}):null]}),o.jsx(n8,{label:"Status",children:o.jsx(oUt,{status:n.status})}),o.jsx(n8,{label:"Next fire",children:o.jsx("span",{title:hj(n.nextFireAt),children:Z2(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(Bhs,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const tet="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function Whs({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=bn(),a=v.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:tet}):o.jsxs(ge,{columns:tet,variant:"striped",className:"min-w-0",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Target"}),o.jsx(ge.TopCell,{children:"Schedule ID"}),o.jsx(ge.TopCell,{children:"Cron"}),o.jsx(ge.TopCell,{children:"Status"}),o.jsx(ge.TopCell,{children:"Next fire"}),o.jsx(ge.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(ge.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(ge.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(ge.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(ge.NameCell,{children:i.workflowId??i.agentId}),o.jsx(ge.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:i.id,children:i.id})}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(ge.Cell,{height:"compact",children:o.jsx(oUt,{status:i.status})}),o.jsx(ge.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:hj(i.nextFireAt),children:Z2(i.nextFireAt)})}),o.jsx(ge.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(lUt,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:hj(i.lastFireAt),children:i.lastFireAt?Z2(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:hj(i.lastFireAt),children:Z2(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function Zhs({workflowId:e}={}){const{data:t,isLoading:n,error:r}=_1e(e?{workflowId:e}:{}),[s,a]=v.useState("");return r?o.jsx(Hi,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(Ff,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(Whs,{schedules:t??[],isLoading:n,search:s})})]})}function Ghs(){const[e]=ri(),t=e.get("workflowId")??void 0,{error:n}=_1e(t?{workflowId:t}:{});return n&&ws(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx(Ms,{resource:"schedules"})}):o.jsx(Bt,{children:o.jsx("div",{className:"h-full",children:o.jsx(Zhs,{workflowId:t})})})}function Qhs({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=rOe({stepGraph:e}),[a,i]=v.useState(!1),[l,c,u]=IOt(r),[d]=AOt(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=Y3t({edges:d,workflowName:n,stepGraph:e});return v.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsxs(NOt,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(GTe,{position:"bottom-left"}),o.jsx(POt,{variant:ly.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Jt,{})})})}function Yhs(){const{stepDetail:e,closeStepDetail:t}=dW();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(C9,{className:"h-4 w-4",style:{color:Ru.map}}),e.type==="nested-graph"&&o.jsx(rd,{className:"h-4 w-4",style:{color:Ru.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:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(ps,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(V2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(nOe,{children:o.jsx(Qhs,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function Khs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function Xhs(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 Jhs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border 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:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(qe,{children:o.jsx(aV,{})}),"Step suspended"]}),o.jsx(on,{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?gm(hm(Ax(i.resumeSchema))):yp(dr(),Lj());return o.jsx(ems,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function ems({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=v.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",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:"text-neutral3 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(lQt,{})}),"The step is asking"]}),o.jsxs(Pf,{open:a,onOpenChange:i,children:[o.jsxs(Fd,{className:"border-border1 bg-surface3 flex w-full items-center justify-between gap-2 rounded-lg border px-3 py-2.5",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(qe,{children:o.jsx(aa,{className:X("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ye,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:Xhs(e.suspendPayload,e.stepId)})]}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:Khs(e.suspendPayload)})]}),o.jsx(Bd,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Hr,{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:"text-neutral3 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(dQt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(YB,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(jf,{}),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 tms(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=v.useContext(Vl),{runId:a}=Sr(),i=BOt(e,r??""),l=hJn(),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:"animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 absolute top-2 right-2 z-20 max-h-[calc(100%-1rem)] w-[380px] max-w-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg duration-300",children:o.jsx(Jhs,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const nms=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"})]}),rms=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"})]}),sms=e=>e.includes("."),ams=e=>e==="input"||e.endsWith(".input"),ims=1;function oms(e){return`${Number((e/1e3).toPrecision(3))}s`}function lms(e,t){const n=Object.entries(e).filter(([i])=>!ams(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,ims);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:sms(i)}})}const cms=({status:e})=>o.jsxs(qe,{children:[e==="success"&&o.jsx(nms,{className:"text-accent1"}),e==="failed"&&o.jsx(rms,{className:"text-accent2"}),e==="suspended"&&o.jsx(aV,{className:"text-accent3"}),e==="waiting"&&o.jsx(ppe,{className:"text-accent5"}),e==="skipped"&&o.jsx(ppe,{className:"text-icon3"}),e==="running"&&o.jsx(ua,{className:"text-accent6 animate-spin"})]}),ums={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function cUt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const net=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},dms=e=>{const t=e;return B3t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},fms=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=dms(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(cms,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ce,{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(fYt,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(Aq,{indicators:c,className:"shrink-0"})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:cUt(e.stepId)}),o.jsx("div",{className:"bg-surface4 relative h-2 min-w-0 rounded",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 ${ums[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ce,{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(uYt,{})})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:oms(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function pms(){const{steps:e}=G4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=kH(),[a,i]=v.useState(()=>Date.now()),[l,c]=v.useState(!1),[u,d]=v.useState(null),f=v.useRef(null);R1e(f,{enabled:!l});const p=lms(e,a),h=p.some(m=>m.isRunning);return v.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),v.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"rounded-studio-panel border-border1/50 bg-surface3 pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden border 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:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(ka,{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,g)=>o.jsx(fms,{row:m,index:g,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:net(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:net(y.step.output)})},`timeline-item-${m.stepId}-${g}`))})]})}),o.jsx(vr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(qOt,{data:u.data,title:`${cUt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const hms=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=dW();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(s4t,{workflowId:e,workflow:t,isLoading:n}),o.jsx(tms,{}),o.jsx(pms,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(Yhs,{})})]})},ret=()=>{const{workflowId:e}=Sr(),{data:t,isLoading:n,error:r}=n4(e);return r&&ws(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})}):r&&Ss(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"workflows"})}):o.jsx(wOe,{children:o.jsx(hms,{workflowId:e,workflow:t??void 0,isLoading:n})})};function mms(e,t){if(e==null)return{};var n,r,s=Z1t(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 gxe(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 gms(e){if(Array.isArray(e))return gxe(e)}function vms(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function yms(e,t){if(e){if(typeof e=="string")return gxe(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)?gxe(e,t):void 0}}function bms(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
720
+ `);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>uxe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>uxe(t))}return!1}function Cds({children:e}){return o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e})}function Eds({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 Tds({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 jds({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 Nds({className:e,children:t}){return o.jsx("dt",{className:X("shrink-0 py-0.5 text-ui-smd text-neutral2",e),children:t})}function Ids({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 Ads({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 Rds=Object.assign(jds,{Key:Nds,Value:Ids,Header:Ads});function Pds({children:e}){return o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center justify-center gap-2 px-4 py-6",children:[o.jsx(Jt,{size:"sm",variant:"pulse",className:"text-neutral3"})," ",e??"Loading..."]})}function $ds({children:e}){return o.jsx("p",{className:"text-ui-sm text-neutral2 px-4 py-6",children:e??"No data found."})}const Bi=Object.assign(xds,{Header:Eds,Heading:Tds,CloseButton:wds,LoadingData:Pds,NoData:$ds,Content:Cds,KeyValueList:Rds,CodeSection:_ds}),fp=Bi.KeyValueList;function Mds(e){return e instanceof Date?e:new Date(e)}function Dds({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=v.useState(!1),d=i??c,f=l??u,p=Mds(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:rr(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[l&&o.jsx(ce,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(pH,{}):o.jsx(d1e,{})}),o.jsxs(Mr,{spacing:"close",children:[o.jsx(ce,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(fH,{})}),o.jsx(ce,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(w3,{})})]}),o.jsx(Bi.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Bi.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",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(ce,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(B7,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",h]})]}),o.jsx(Pa,{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(ce,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(B7,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(Pa,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(fp,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(fp.Key,{children:"Entity Type"}),o.jsx(fp.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(fp.Key,{children:"Entity Name"}),o.jsx(fp.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(fp.Key,{children:"Service"}),o.jsx(fp.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(fp.Key,{children:"Environment"}),o.jsx(fp.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(fp.Key,{children:"Source"}),o.jsx(fp.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([g,y])=>o.jsxs(v.Fragment,{children:[o.jsx(fp.Key,{children:g}),o.jsx(fp.Value,{children:String(y)})]},g))})]}),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 Lds({error:e,resource:t,errorTitle:n}){if(ws(e))return o.jsx(Zs,{});if(Ss(e))return o.jsx(Ms,{resource:t});if(I4(e))return o.jsx(Lr,{iconSlot:o.jsx(U7,{}),titleSlot:"Observability storage is not available",descriptionSlot:"The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio."});if(N4(e,"logs"))return o.jsx(Lr,{iconSlot:o.jsx(U7,{}),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 zds({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 Fds={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 Bds({level:e}){const t=Fds[e];return o.jsx(Io,{height:"compact",children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function Uds({entityType:e,className:t}){const n=X("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Ho,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(rd,{className:n,"aria-hidden":!0});case"tool":return o.jsx(qd,{className:n,"aria-hidden":!0});default:return null}}function qds({entityType:e,entityName:t}){const n=e??"";return o.jsxs(Io,{height:"compact",className:"flex min-w-0 items-center gap-2",children:[o.jsx(Uds,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function Vds({message:e}){return o.jsx(Io,{height:"compact",className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function Hds({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(Io,{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(iTe,{children:t})}const Ql=Object.assign(F4,{Top:DZ,TopCell:fC,TopCellWithTooltip:LZ,TopCellSmart:nDt,RowWrapper:uTe,RowButton:B4,RowLink:tDt,Spacer:dTe,NoMatch:MZ,DateCell:oTe,TimeCell:lTe,LevelCell:Bds,EntityCell:qds,MessageCell:Vds,DataCell:Hds,NextPageLoading:$Z}),WJe="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",Wds=36,Zds=8;function Gds({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=v.useRef(null),u=EBt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>Wds,overscan:Zds}),d=v.useRef(t);if(v.useEffect(()=>{d.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),d.current=t},[t]),t)return o.jsx(ll,{columns:WJe});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:WJe,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(g=>{const y=e[g.index];if(!y)return null;const b=a.get(y);if(!b)return null;const x=b===i;return o.jsxs(Ql.RowButton,{ref:u.measureElement,"data-index":g.index,onClick:()=>l(y),featured:x,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 Qds({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=>Yds(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(QIe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(ZIe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Yds(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 Kds={"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"},pie="MMM d, yyyy HH:mm",hie="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function Xds({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${Kds[e]}`,description:hie}:t&&n?{title:`No logs between ${rr(t,pie)} and ${rr(n,pie)}`,description:hie}:t?{title:`No logs since ${rr(t,pie)}`,description:hie}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const Jds=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=Xds({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(U7,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(f1e,{})]})})})},efs=20,tfs=1e4;function nfs(e,t,n){if(e?.pagination?.hasMore)return n+1}function rfs(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 sfs(e){return N4(e.state.error,"logs")||I4(e.state.error)?!1:tfs}const afs=({filters:e}={})=>{const t=We(),{inView:n,setRef:r}=X_(),s=Q1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:efs},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:nfs,select:rfs,retry:!1,refetchInterval:sfs}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return v.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}},KF={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},YBt=[{label:"Agent",entityType:KF.AGENT},{label:"Workflow",entityType:KF.WORKFLOW},{label:"Scorer",entityType:KF.SCORER},{label:"Ingest",entityType:KF.INGEST}],ifs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Yx="rootEntityType",sx="datePreset",ax="dateFrom",ix="dateTo",ofs=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"},LL=Object.keys(Il),yAe=new Set(["tags"]),bAe="mastra:logs:saved-filters";function lfs(e,t=bAe){const n=pfs(e),r=e.get(sx);r&&n.set(sx,r);const s=e.get(ax);s&&n.set(ax,s);const a=e.get(ix);a&&n.set(ix,a);try{localStorage.setItem(t,n.toString())}catch{}}function cfs(e=bAe){try{localStorage.removeItem(e)}catch{}}function ZJe(e=bAe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function ufs(e){if(e.has(sx)||e.has(ax)||e.has(ix)||e.has(Yx))return!0;for(const t of LL)if(e.has(Il[t]))return!0;return!1}function dfs({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:YBt.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:ifs.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 ffs(e){const t=[],n=new Map([[Yx,"rootEntityType"]]);for(const s of LL)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),yAe.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 pfs(e){const t=new URLSearchParams,n=e.get(Yx);n&&t.set(Yx,n);for(const r of LL){const s=Il[r];if(yAe.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 hfs(e,t){e.delete(Yx);for(const n of LL)e.delete(Il[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Yx,n.value);continue}const r=Il[n.fieldId];if(r){if(yAe.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 mfs({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 gfs(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 vfs="Filters setting for Logs saved",yfs="Filters setting for Logs cleared up";function bfs(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=v.useState(()=>ZJe(r)!==null),c=v.useCallback(()=>{lfs(e,r),l(!0);const f=s?.saved??vfs;f!==!1&&De.success(f)},[e,r,s?.saved]),u=v.useCallback(()=>{cfs(r),l(!1);const f=s?.cleared??yfs;f!==!1&&De.success(f)},[r,s?.cleared]),d=v.useRef(!1);return v.useEffect(()=>{if(a||d.current||(d.current=!0,ufs(e)))return;const f=ZJe(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,g]of f)h.append(m,g);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function xfs(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 wfs(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,xfs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function Sfs(e,t,n,r){const s=v.useMemo(()=>wfs(e),[e]),a=v.useMemo(()=>{const h=new Map;for(const[m,g]of e.entries()){const y=s.get(g);y&&h.set(y,{log:g,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=v.useCallback(h=>s.get(h),[s]),d=v.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 dxe="logId",fxe="traceId",pxe="spanId",yP=1440*60*1e3,kfs={"last-24h":yP,"last-3d":3*yP,"last-7d":7*yP,"last-14d":14*yP,"last-30d":30*yP};function XF(e){e.delete(dxe),e.delete(fxe),e.delete(pxe)}function Ofs(e,t,n){const{onRemoveAll:r}={},s=v.useMemo(()=>{const C=e.get(sx);return C&&ofs.has(C)?C:"last-24h"},[e]),a=e.get(ax),i=e.get(ix),l=v.useMemo(()=>{if(s==="custom"){if(!a)return;const _=new Date(a);return Number.isNaN(_.getTime())?void 0:_}if(s==="all")return;const C=kfs[s];return C?new Date(Date.now()-C):void 0},[s,a]),c=v.useMemo(()=>{if(s!=="custom"||!i)return;const C=new Date(i);return Number.isNaN(C.getTime())?void 0:C},[s,i]),u=v.useRef(s);u.current=s;const d=e.get(dxe),f=e.get(fxe),p=e.get(pxe),h=v.useMemo(()=>YBt.find(C=>C.entityType===e.get(Yx)),[e]),m=v.useMemo(()=>ffs(e),[e]),g=v.useCallback(C=>{t(_=>{const E=new URLSearchParams(_);for(const[T,N]of Object.entries(C)){const I=T==="logId"?dxe:T==="traceId"?fxe:pxe;N?E.set(I,N):E.delete(I)}return E},{replace:!0})},[t]),y=v.useCallback(C=>{t(_=>{const E=new URLSearchParams(_);return hfs(E,C),XF(E),E},{replace:!0})},[t]),b=y,x=v.useCallback((C,_)=>{if(u.current!=="custom")return;const E=_==="from"?ax:ix;t(T=>{const N=new URLSearchParams(T);return C?N.set(E,C.toISOString()):N.delete(E),XF(N),N},{replace:!0})},[t]),S=v.useCallback(C=>{u.current=C,t(_=>{const E=new URLSearchParams(_);return C==="last-24h"?(E.delete(sx),E.delete(ax),E.delete(ix)):C==="custom"?E.set(sx,"custom"):(E.set(sx,C),E.delete(ax),E.delete(ix)),XF(E),E},{replace:!0})},[t]),k=v.useCallback(()=>{t(C=>{const _=new URLSearchParams(C);_.delete(Yx);for(const E of LL)_.delete(Il[E]);return _.delete(sx),_.delete(ax),_.delete(ix),XF(_),_},{replace:!0}),r?.()},[t,r]);return v.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:g,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:S,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,g,b,x,S,k,y])}const Nb=Bi.KeyValueList;function _fs({spanId:e,span:t,isLoading:n,onClose:r}){const s=KIe(t?.startedAt,t?.endedAt);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(Nb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(Nb.Key,{children:"Type"}),o.jsx(Nb.Value,{children:t.spanType})]}),t.startedAt&&o.jsxs(o.Fragment,{children:[o.jsx(Nb.Key,{children:"Started"}),o.jsx(Nb.Value,{children:rr(new Date(t.startedAt),"MMM dd, HH:mm:ss.SSS")})]}),t.endedAt&&o.jsxs(o.Fragment,{children:[o.jsx(Nb.Key,{children:"Ended"}),o.jsx(Nb.Value,{children:rr(new Date(t.endedAt),"MMM dd, HH:mm:ss.SSS")})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(Nb.Key,{children:"Duration"}),o.jsx(Nb.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Bi.CodeSection,{title:"Input",icon:o.jsx(Jhe,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Output",icon:o.jsx(eme,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Metadata",icon:o.jsx(Tw,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Attributes",icon:o.jsx(Tw,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Bi.NoData,{children:"Span not found."})]})}function Cfs({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=v.useMemo(()=>eAe(t??[]),[t]),[l,c]=v.useState([]);v.useEffect(()=>{i.length>0&&c(JIe(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(OBt,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function Efs(){const[e,t]=ri(),n=Ofs(e,t),r=bfs(e,t),[s,a]=v.useState(),[i,l]=v.useState(!1),{data:c=[],isPending:u}=oAe(),{data:d=[],isPending:f}=sAe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=aAe(),{data:m=[],isPending:g}=iAe(),y=v.useMemo(()=>dfs({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:g,environments:h}}),[c,d,m,p,u,f,g,h]),b=v.useMemo(()=>mfs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:S,error:k,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:E}=afs({filters:b}),{logIdMap:T,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=Sfs(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=lAe(n.featuredTraceId??null),{data:z,isLoading:H}=DL(n.featuredTraceId??"",n.featuredSpanId??""),F=v.useCallback(()=>n.applyFilterTokens(gfs(y,n.filterTokens)),[y,n]),U=v.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),q=v.useCallback(K=>n.handleFeaturedChange({traceId:K,spanId:null}),[n]),M=v.useCallback((K,ne)=>n.handleFeaturedChange({traceId:K,spanId:ne}),[n]),G=v.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),V=v.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=v.useCallback(K=>n.handleFeaturedChange({spanId:K??null}),[n]),B=o.jsxs(Bt.TopArea,{children:[o.jsx(Bt.Row,{children:o.jsxs(Bt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(a4,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:S,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(YIe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx(Qds,{isLoading:S,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(Bt,{width:"wide",height:"full",children:[B,o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsx(Lds,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!S&&!Z?o.jsxs(Bt,{width:"wide",height:"full",children:[B,o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsx(Jds,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Bt,{width:"wide",height:"full",children:[B,o.jsx(zds,{logCollapsed:i,listSlot:o.jsx(Gds,{logs:x,isLoading:S,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:E,logIdMap:T,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(Dds,{log:N,onClose:U,onTraceClick:q,onSpanClick:M,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(Cfs,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(_fs,{spanId:n.featuredSpanId,span:z?.span,isLoading:H,onClose:V}):null})]})}function Tfs({server:e}){const{paths:t,Link:n}=bn(),s=We().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=J8t(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=Qh(e.name,50);return o.jsxs(ge.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(ge.NameCell,{children:f}),o.jsx(ge.DescriptionCell,{children:a}),o.jsx(ge.TextCell,{className:"text-center",children:u||""}),o.jsx(ge.TextCell,{className:"text-center",children:c||""}),o.jsx(ge.TextCell,{className:"text-center",children:d||""})]})}function jfs({mcpServers:e,isLoading:t,search:n=""}){const r=v.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(ll,{columns:"auto 1fr auto auto auto"}):o.jsxs(ge,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Name"}),o.jsx(ge.TopCell,{children:"URL"}),o.jsx(ge.TopCellSmart,{long:"Agents",short:o.jsx(Ho,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(ge.TopCellSmart,{long:"Tools",short:o.jsx(qd,{}),tooltip:"Tools",className:"text-center"}),o.jsx(ge.TopCellSmart,{long:"Workflows",short:o.jsx(rd,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(ge.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(Tfs,{server:s},s.id))]})}const Nfs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx($f,{}),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(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(_a,{})]})})}),Ifs=()=>{const{data:e=[],isLoading:t,error:n}=JG(),[r,s]=v.useState("");return n&&ws(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx(Ms,{resource:"MCP servers"})}):n?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(cr,{children:o.jsx(Nfs,{})}):o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(Ff,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(jfs,{mcpServers:e,isLoading:t,search:r})]})},Afs=(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 Rfs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=bn(),i=v.useMemo(()=>Afs(e,t),[e,t]),l=v.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(ll,{columns:"auto 1fr auto"}):o.jsxs(ge,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Name"}),o.jsx(ge.TopCell,{children:"Description"}),o.jsx(ge.TopCellSmart,{long:"Agents",short:o.jsx(Ho,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(ge.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=Qh(c.id,50),d=Qh(c.description??"",200),f=c.agents.length;return o.jsxs(ge.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(ge.NameCell,{children:u}),o.jsx(ge.DescriptionCell,{children:d}),o.jsx(ge.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const Pfs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx($f,{}),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(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(_a,{})]})})}),$fs=()=>{const e=We();return Ln({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new A_;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}}})},Mfs=({toolId:e})=>{const{canExecute:t}=Go(),n=t("tools"),{data:r={}}=Am(),s=v.useMemo(()=>{for(const g of Object.values(r))if(g.tools){const y=Object.values(g.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=SNr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=$fs(),{requestContext:p}=hs();v.useEffect(()=>{if(l){const g=l instanceof Error?l.message:"Failed to load tool";De.error(`Error loading tool: ${g}`)}},[l]);const h=async(g,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:g,requestContext:b})},m=c?.inputSchema?gm(hm(Ax(c?.inputSchema))):Os({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(kt,{className:"mb-4 h-8 w-48"}),o.jsx(kt,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(OIe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function Dfs({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}=VI(),{data:p={},isLoading:h,isError:m,error:g}=Am(),{navigate:y,paths:b}=bn();v.useEffect(()=>{if(d){const C=f instanceof Error?f.message:"Failed to load tools";De.error(`Error loading tools: ${C}`)}},[d,f]),v.useEffect(()=>{if(m){const C=g instanceof Error?g.message:"Failed to load agents";De.error(`Error loading agents: ${C}`)}},[m,g]);const x=new Map;Object.values(p).forEach(C=>{C.tools&&Object.values(C.tools).forEach(_=>{x.has(_.id)||x.set(_.id,_)})}),Object.values(c).forEach(C=>{x.has(C.id)||x.set(C.id,C)});const S=Array.from(x.values()).map(C=>({label:C.id,value:C.id})),k=C=>{t?t(C):C&&C!==e&&y(b.toolLink(C))};return o.jsx(Fl,{options:S,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const Lfs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=v.useState({sseUrl:"",httpStreamUrl:""});if(v.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(Ny,{children:o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(Ny,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(on,{icon:o.jsx(wBt,{className:"text-neutral6"}),className:"text-neutral4! rounded-r-sm",children:"Version"}),o.jsx(on,{className:"text-neutral4! rounded-l-sm",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:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(on,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",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:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(on,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",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:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(on,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",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:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(zfs,{server:t})})]})},zfs=({server:e})=>{const{data:t={},isLoading:n}=J8t(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"overflow-y-scroll p-5",children:[o.jsxs("div",{className:"text-neutral6 flex items-center gap-2",children:[o.jsx(qe,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(wC,{})}),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(Bfs,{tool:a,serverId:e.id},s)})})]})};function Ffs(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 Bfs=({tool:e,serverId:t})=>{const n=v.useRef(null),{Link:r,paths:s}=bn(),a=_9t[e.toolType||"tool"],i=Ffs(e._meta);return o.jsxs(Uf,{onClick:()=>n.current?.click(),children:[o.jsx(pMt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Vf,{children:[o.jsx(qf,{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(on,{className:"py-0 text-[10px]",children:"App"})]})}),o.jsx(sh,{children:e.description})]})]})},Ufs=()=>{const{serverId:e}=Sr(),{data:t=[],isLoading:n}=JG(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(Lfs,{isLoading:n,server:r})})};function qfs(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 Vfs=({toolId:e,serverId:t})=>{const{canExecute:n}=Go(),r=n("tools"),s=We(),{data:a,isLoading:i,error:l}=vIe(t,e),{mutateAsync:c,isPending:u,data:d}=PKr(t,e),f=a?qfs(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=v.useCallback(async(y,b)=>await c(b),[c]);v.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";De.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(kt,{className:"mb-4 h-8 w-48"}),o.jsx(kt,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let g;try{g=gm(hm(a.inputSchema))}catch(y){console.error("Error processing input schema:",y),De.error("Failed to process tool input schema."),g=Os({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(X8t,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(OIe,{executionResult:d,isExecutingTool:u,zodInputSchema:g,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},Hfs=()=>{const{serverId:e,toolId:t}=Sr(),{data:n,isLoading:r}=vIe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Vfs,{toolId:t,serverId:e})})},KBt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],UN="rootEntityType",qN={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"},OQ=Object.keys(qN),xAe="mastra:metrics:saved-filters";function Wfs(e){const t=Kfs(e);try{localStorage.setItem(xAe,t.toString())}catch{}}function Zfs(){try{localStorage.removeItem(xAe)}catch{}}function XBt(){try{const e=localStorage.getItem(xAe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function Gfs(e){if(e.has(UN))return!0;for(const t of OQ)if(e.has(qN[t]))return!0;return!1}function Qfs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:KBt.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 Yfs(e){const t=[],n=new Map([[UN,"rootEntityType"]]);for(const s of OQ)n.set(qN[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 Kfs(e){const t=new URLSearchParams,n=e.getAll(UN);for(const r of n)t.append(UN,r);for(const r of OQ){const s=qN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function Xfs(e,t){e.delete(UN);for(const n of OQ)e.delete(qN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?UN:qN[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 Jfs="Any";function GJe(e){const t=e.trim();return t===""||t===Jfs}const eps=new Set(KBt.map(e=>e.entityType));function QJe(e){const t=e.trim();return eps.has(t)?t:void 0}function tps(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=>!GJe(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?QJe(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(GJe(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=QJe(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const JBt=[{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"}],nps=new Set(JBt.map(e=>e.value));function rps(e){return typeof e=="string"&&(nps.has(e)||e==="custom")}const eUt=v.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function _Q(){return v.useContext(eUt)}function sps(e,t){return e!=="custom"?JBt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${rr(t.from,"MMM d, yyyy")} – ${rr(t.to,"MMM d, yyyy")}`:rr(t.from,"MMM d, yyyy"):"Custom range"}function aps({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=v.useMemo(()=>JSON.stringify(n),[n]),d=v.useMemo(()=>n,[u]),f=v.useMemo(()=>tps(d),[d]),p=v.useMemo(()=>JSON.stringify(f),[f]),h=sps(t,a),m=v.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(eUt.Provider,{value:m,children:e})}const ips=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function ops(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 lps(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 cps(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=_Q(),s=v.useRef(e);s.current=e;const a=v.useRef(n);return a.current=n,o.jsx(a4,{preset:ops(e),onPresetChange:i=>{const l=lps(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:ips})}const hxe=1440*60*1e3,ups={"24h":hxe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function dps(e,t,n){if(e!=="custom"){const r=ups[e]??hxe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-hxe),end:t?.to??new Date(n)}}function Mm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=_Q(),s=v.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=v.useMemo(()=>dps(e,t,i),[e,t,i]),c=v.useMemo(()=>({timestamp:l,...n}),[l,r]),u=v.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function tUt(){const e=We(),{filters:t,filterKey:n}=Mm();return yt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function zL({href:e,LinkComponent:t="a"}){return o.jsx(ce,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(kjn,{})})}function fps({href:e,LinkComponent:t="a"}){return o.jsx(ce,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(rNn,{})})}const pps=[{dataKey:"p50",label:"p50",color:qp.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:qp.yellow,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p95,0)/e.length)}`:"0",suffix:"avg ms"})}];function hps(e){return e==="agents"||e==="workflows"||e==="tools"}function mie({data:e,onPointClick:t}){return e.length===0?o.jsx(Wt.NoData,{message:"No latency data yet"}):o.jsx(Qq,{data:e,series:pps,onPointClick:t?n=>{const r=n;typeof r?.tsMs=="number"&&Number.isFinite(r.tsMs)&&t(r)}:void 0})}function mps({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]=v.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),g=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=g.length>0?`${Math.round(g.reduce((b,x)=>b+x,0)/g.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(gc,{value:p,onValueChange:b=>{hps(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(mc,{children:[o.jsx(Nr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Nr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Nr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Kr,{value:"agents",children:o.jsx(mie,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Kr,{value:"workflows",children:o.jsx(mie,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Kr,{value:"tools",children:o.jsx(mie,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Wt.NoData,{message:"No latency data yet"})})]})}function gps(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 vps(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 nUt(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=gps(s);l&&e.set(t,l)}function Do(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function rUt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function YJe({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(Mw,"branches"),nUt(a,Dw,Lw,zw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Gx,i),r.status&&a.set(Qx,r.status),Do(a,Nl.entityName,r.entityName??n.entityName),Do(a,Nl.threadId,r.threadId??n.threadId),Do(a,Nl.resourceId,r.resourceId??n.resourceId),Do(a,Nl.entityId,n.entityId),Do(a,Nl.runId,n.runId),Do(a,Nl.sessionId,n.sessionId),Do(a,Nl.requestId,n.requestId),Do(a,Nl.userId,n.userId),Do(a,Nl.organizationId,n.organizationId),Do(a,Nl.experimentId,n.experimentId),Do(a,Nl.serviceName,n.serviceName),Do(a,Nl.environment,n.environment),rUt(a,Nl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function yps({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;nUt(a,sx,ax,ix,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Yx,i),Do(a,Il.entityName,r.entityName??n.entityName),Do(a,Il.threadId,r.threadId??n.threadId),Do(a,Il.resourceId,r.resourceId??n.resourceId),Do(a,Il.runId,n.runId),Do(a,Il.sessionId,n.sessionId),Do(a,Il.requestId,n.requestId),Do(a,Il.userId,n.userId),Do(a,Il.organizationId,n.organizationId),Do(a,Il.experimentId,n.experimentId),Do(a,Il.serviceName,n.serviceName),Do(a,Il.environment,n.environment),rUt(a,Il.tags,n.tags),r.status==="error"&&a.append(Il.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function cA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=_Q(),a=v.useCallback((c={})=>YJe({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=v.useCallback((c={})=>yps({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=v.useCallback((c,u,d)=>{const f=vps(u,d);return YJe({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const sUt="1h";async function gie(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:sUt,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 bps(){const e=We(),{filters:t,filterKey:n}=Mm();return yt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([gie(e,"mastra_agent_duration_ms",t),gie(e,"mastra_workflow_duration_ms",t),gie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:sUt}}})}const KJe={agents:du.AGENT,workflows:du.WORKFLOW_RUN,tools:du.TOOL};function xps(){const{data:e,isLoading:t,isError:n}=bps(),{getTracesHref:r,getBucketTracesHref:s}=cA(),{Link:a}=bn(),i=Ws();return o.jsx(mps,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:KJe[l]},c.tsMs,"1h"))},actions:l=>o.jsx(zL,{href:r({rootEntityType:KJe[l]}),LinkComponent:a})})}function wps(e){return e==="threads"||e==="resources"}function vie(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Sps({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=v.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,g=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"}),g?o.jsx(Wt.Actions,{children:g}):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(gc,{defaultTab:"threads",value:i,onValueChange:y=>{wps(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(mc,{children:[o.jsx(Nr,{value:"threads",children:"Threads"}),o.jsx(Nr,{value:"resources",children:"Resources"})]}),o.jsx(Kr,{value:"threads",children:d?o.jsxs(ge,{columns:"auto auto auto auto auto",...axe,children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ge.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:vie(y.threadId)}),o.jsx(ge.NumberCell,{children:y.resourceId?vie(y.resourceId):"—"}),o.jsx(ge.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(ge.NumberCell,{children:y.tokens>0?Ml(y.tokens):"—"}),o.jsx(ge.NumberCell,{children:y.cost!=null?sm(y.cost,y.costUnit):"—"})]});return b?o.jsx(ge.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ge.RowStatic,{children:x},y.key)})]}):o.jsx(Wt.NoData,{message:"No thread activity yet"})}),o.jsx(Kr,{value:"resources",children:f?o.jsxs(ge,{columns:"auto auto auto auto",...axe,children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ge.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:vie(y.resourceId)}),o.jsx(ge.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(ge.NumberCell,{children:y.tokens>0?Ml(y.tokens):"—"}),o.jsx(ge.NumberCell,{children:y.cost!=null?sm(y.cost,y.costUnit):"—"})]});return b?o.jsx(ge.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ge.RowStatic,{children:x},y.key)})]}):o.jsx(Wt.NoData,{message:"No resource activity yet"})})]})})]})}const yie=20;function kps(){const e=We(),{filters:t,filterKey:n}=Mm();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:yie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:yie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:yie})]),l=new Map,c=d=>lA(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 bie=20;function Ops(){const e=We(),{filters:t,filterKey:n}=Mm();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:bie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:bie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:bie})]),l=new Map,c=d=>lA(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 _ps(){const e=kps(),t=Ops(),{getTracesHref:n}=cA(),{Link:r}=bn();return o.jsx(Sps,{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 FL({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:e}),o.jsx(Jr.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(Jr.Error,{}):s?o.jsx(Jr.Loading,{}):i?r!=null?o.jsx(Jr.Change,{changePct:r,prevValue:n}):o.jsx(Jr.NoChange,{}):o.jsx(Jr.NoData,{})]})}function Cps(){const e=We(),{filters:t,filterKey:n}=Mm();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 Eps(){const e=We(),{filters:t,filterKey:n}=Mm();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 Tps(){const e=We(),{filters:t,filterKey:n}=Mm();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 jps(){const e=We(),{filters:t,filterKey:n}=Mm();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 Nps(){const{data:e,isLoading:t,isError:n}=tUt();return o.jsx(FL,{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 Ips(){const{data:e,isLoading:t,isError:n}=Tps();return o.jsx(FL,{label:"Total Model Cost",value:e?.cost!=null?sm(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?sm(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function Aps(){const{data:e,isLoading:t,isError:n}=jps();return o.jsx(FL,{label:"Total Tokens",value:e?.value!=null?Ml(e.value):null,prevValue:e?.previousValue!=null?Ml(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Rps(){const{data:e,isLoading:t,isError:n}=Eps();return o.jsx(FL,{label:"Total Threads",value:e?.value!=null?Ml(e.value):null,prevValue:e?.previousValue!=null?Ml(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Pps(){const{data:e,isLoading:t,isError:n}=Cps();return o.jsx(FL,{label:"Total Resources",value:e?.value!=null?Ml(e.value):null,prevValue:e?.previousValue!=null?Ml(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function $ps({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=>Mps(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(QIe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(ZIe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Mps(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 Dps({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?sm(l):"—":c.size===1?u=l>0?sm(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(ge,{columns:"auto auto auto auto auto auto",...axe,children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{sticky:"start",children:"Model"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(ge.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:l.model}),o.jsx(ge.NumberCell,{children:l.input}),o.jsx(ge.NumberCell,{children:l.output}),o.jsx(ge.NumberCell,{children:l.cacheRead}),o.jsx(ge.NumberCell,{children:l.cacheWrite}),o.jsx(ge.NumberCell,{highlight:!0,children:l.cost!=null?sm(l.cost,l.costUnit):"—"})]});return c?o.jsx(ge.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(ge.RowStatic,{children:u},l.model)})]}):o.jsx(Wt.NoData,{message:"No model usage data yet"})})]})}function Lps(){const e=We(),{filters:t,filterKey:n}=Mm();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=>lA(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:Ml(f.input),output:Ml(f.output),cacheRead:Ml(f.cacheRead),cacheWrite:Ml(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function zps(){const{data:e,isLoading:t,isError:n}=Lps(),{getTracesHref:r}=cA(),{Link:s}=bn();return o.jsx(Dps,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:du.AGENT}),actions:o.jsx(zL,{href:r({rootEntityType:du.AGENT}),LinkComponent:s})})}function Fps(e){return e==="tokens"||e==="cost"}function Bps({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=v.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.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,g=h?f.reduce((b,x)=>b+(x.cost??0),0):0,y=h&&g>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:sm(g,m),label:"Total cost"}):o.jsx(Wt.Summary,{value:Ml(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(gc,{defaultTab:"tokens",value:i,onValueChange:b=>{Fps(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(mc,{children:[o.jsx(Nr,{value:"tokens",children:"Tokens"}),o.jsx(Nr,{value:"cost",children:"Cost"})]}),o.jsx(Kr,{value:"tokens",children:o.jsx(BN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:qp.blueDark},{label:"Output",color:qp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:Ml})}),o.jsx(Kr,{value:"cost",children:y?o.jsx(BN,{LinkComponent:a,data:f.slice().sort((b,x)=>(x.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:qp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>sm(b,m)}):o.jsx(Wt.NoData,{message:"No cost data yet"})})]}):o.jsx(Wt.NoData,{message:"No token usage data yet"})})]})}function Ups(){const e=We(),{filters:t,filterKey:n}=Mm();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=>lA(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 qps(){const{data:e,isLoading:t,isError:n}=Ups(),{getTracesHref:r}=cA(),{Link:s}=bn();return o.jsx(Bps,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:du.AGENT,entityName:a.name}),actions:o.jsx(zL,{href:r({rootEntityType:du.AGENT}),LinkComponent:s})})}function mxe(e,t=Ml){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const Vps=[{dataKey:"input",label:"Input tokens",color:qp.blue,aggregate:mxe("input")},{dataKey:"output",label:"Output tokens",color:qp.yellow,aggregate:mxe("output")}];function Hps(e){return e==="tokens"||e==="cost"}function Wps({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=v.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,C)=>k+C.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),g=m?[...h][0]??null:null,y=m?f.reduce((k,C)=>k+(C.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",S=[{dataKey:"cost",label:"Cost",color:qp.purple,aggregate:mxe("cost",k=>sm(k,g))}];return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Wt.Summary,{value:sm(y,g),label:"Total cost"}):o.jsx(Wt.Summary,{value:Ml(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(gc,{defaultTab:"tokens",value:a,onValueChange:k=>{Hps(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(mc,{children:[o.jsx(Nr,{value:"tokens",children:"Tokens"}),o.jsx(Nr,{value:"cost",children:"Cost"})]}),o.jsx(Kr,{value:"tokens",children:o.jsx(Qq,{data:c,series:Vps})}),o.jsx(Kr,{value:"cost",children:b?o.jsx(Qq,{data:p,series:S}):o.jsx(Wt.NoData,{message:"No cost data yet"})})]}):o.jsx(Wt.NoData,{message:"No token usage data yet"})})]})}function Zps(e){return e==="24h"?"1h":"1d"}function Gps(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 XJe(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 Qps(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function Yps(){const e=We(),{datePreset:t,filters:n,filterKey:r}=Mm(),s=Zps(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 XJe(l,a.series[0],"input"),XJe(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:Gps(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:Qps(u)}}),interval:s}}})}function Kps(){const{data:e,isLoading:t,isError:n}=Yps(),{getTracesHref:r}=cA(),{Link:s}=bn();return o.jsx(Wps,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(zL,{href:r(),LinkComponent:s})})}function xie({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(BN,{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:qp.blueDark},{label:"Errors",color:qp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:Ml})}function Xps({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=v.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,g)=>m+g.completed+g.errors,0):0,p=m=>r?g=>r(m,g):void 0,h=m=>s?g=>s(m,g):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:Ml(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(gc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(mc,{children:[o.jsx(Nr,{value:"agents",children:"Agents"}),o.jsx(Nr,{value:"workflows",children:"Workflows"}),o.jsx(Nr,{value:"tools",children:"Tools"})]}),o.jsx(Kr,{value:"agents",children:e.agentData.length>0?o.jsx(xie,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No agent data yet"})}),o.jsx(Kr,{value:"workflows",children:e.workflowData.length>0?o.jsx(xie,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No workflow data yet"})}),o.jsx(Kr,{value:"tools",children:e.toolData.length>0?o.jsx(xie,{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 wie(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=lA(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 Jps(){const e=We(),{filters:t,filterKey:n}=Mm();return yt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([wie(e,"mastra_agent_duration_ms",t),wie(e,"mastra_workflow_duration_ms",t),wie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const JF={agents:du.AGENT,workflows:du.WORKFLOW_RUN,tools:du.TOOL};function ehs(){const{data:e,isLoading:t,isError:n}=Jps(),{getTracesHref:r,getLogsHref:s}=cA(),{Link:a}=bn();return o.jsx(Xps,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:JF[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:JF[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(zL,{href:r({rootEntityType:JF[i]}),LinkComponent:a}),o.jsx(fps,{href:s({rootEntityType:JF[i],status:"error"}),LinkComponent:a})]})})}const Sie="period",e8="dateFrom",t8="dateTo";function ths(){const[e,t]=ri(),n=e.get(Sie),r=rps(n)?n:"24h",s=v.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(e8)),p=d(e.get(t8));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=v.useMemo(()=>Yfs(e),[e.toString()]),i=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(Sie):p.set(Sie,d),d!=="custom"&&(p.delete(e8),p.delete(t8)),p},{replace:!0})},[t]),l=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(e8,d.from.toISOString()):p.delete(e8),d?.to?p.set(t8,d.to.toISOString()):p.delete(t8),p},{replace:!0})},[t]),c=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return Xfs(p,d),p},{replace:!0})},[t]),u=v.useRef(!1);return v.useEffect(()=>{if(u.current||(u.current=!0,Gfs(e)))return;const d=XBt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(aps,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(nhs,{})})}function nhs(){const[e]=ri(),{error:t,isLoading:n}=tUt(),{filterTokens:r,setFilterTokens:s}=_Q(),[a,i]=v.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=jBt(),{data:d,isLoading:f}=oAe(),{data:p,isLoading:h}=sAe(),{data:m,isLoading:g}=iAe(),{data:y,isLoading:b}=aAe(),x=v.useMemo(()=>Qfs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:g,environments:b}}),[d,p,m,y,f,h,g,b]),[S,k]=v.useState(()=>XBt()!==null),C=v.useCallback(()=>{Wfs(e),k(!0),De.success("Filters setting for Metrics saved")},[e]),_=v.useCallback(()=>{Zfs(),k(!1),De.success("Filters setting for Metrics cleared up")},[]),E=v.useCallback(()=>{s([])},[s]),T=v.useCallback(()=>{const N=r.map(I=>{const A=x.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(N)},[x,r,s]);return t&&ws(t)?o.jsx(cr,{children:o.jsx(Zs,{})}):t&&Ss(t)?o.jsx(cr,{children:o.jsx(Ms,{resource:"metrics"})}):t?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Bt,{width:"wide",height:"full",children:[o.jsxs(Bt.TopArea,{children:[o.jsx(Bt.Row,{children:o.jsxs(Bt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(cps,{}),o.jsx(YIe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx($ps,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:T,onRemoveAll:E,onSave:C,onRemoveSaved:S?_:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(Sn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(Sn.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(cxe,{children:[o.jsx(Nps,{}),o.jsx(Ips,{}),o.jsx(Aps,{}),o.jsx(Rps,{}),o.jsx(Pps,{})]}),o.jsxs(cxe,{children:[o.jsx(zps,{}),o.jsx(qps,{}),o.jsx(Kps,{}),o.jsx(_ps,{}),o.jsx(ehs,{}),o.jsx(xps,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx($f,{}),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(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(_a,{})]})})})]})}const rhs=50;function shs(){const{paths:e}=bn(),{isCmsAvailable:t}=dS(),[n,r]=v.useState(""),[s,a]=v.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=E9t({page:s,perPage:rhs}),d=i?.promptBlocks??[],f=i?.hasMore??!1,p=v.useCallback(()=>{u||a(g=>g+1)},[u]),h=v.useCallback(()=>{u||a(g=>Math.max(0,g-1))},[u]),m=v.useCallback(g=>{r(g),a(0)},[]);return c&&ws(c)?o.jsx(cr,{children:o.jsx(Zs,{})}):c&&Ss(c)?o.jsx(cr,{children:o.jsx(Ms,{resource:"prompt blocks"})}):c?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(cr,{children:o.jsx(Bts,{})}):o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsxs(Bt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Ff,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(ce,{as:za,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Wr,{}),"Create Prompt"]})]})}),o.jsx(Fts,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:p,onPrevPage:h})]})}function ahs(){return o.jsx(Bt,{width:"narrow",children:o.jsx(Bt.MainArea,{children:o.jsx(bXr,{children:o.jsx(Dbe,{})})})})}const ihs=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:EZt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:jot,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:_a,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:bj,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:Dot,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:Not,href:"https://mastra.ai/contact?ref=studio",external:!0}];function ohs(){return o.jsx(Bt,{width:"narrow",children:o.jsx(Bt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:ihs.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group border-border1 bg-surface2 hover:border-accent1 hover:bg-surface3 flex flex-col gap-3 rounded-lg border p-5 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"text-icon3 group-hover:text-accent1 h-5 w-5 transition-colors"}),o.jsx("span",{className:"text-ui-md text-text1 font-medium",children:e.title}),e.external&&o.jsx(_a,{className:"text-icon3 ml-auto h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function lhs(){const{data:e={},isLoading:t,error:n}=ch(),[r,s]=v.useState(""),[a,i]=v.useState("all");if(n&&ws(n))return o.jsx(cr,{children:o.jsx(Zs,{})});if(n&&Ss(n))return o.jsx(cr,{children:o.jsx(Ms,{resource:"scorers"})});if(n)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(cr,{children:o.jsx(GJr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsx(YJr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(ZJr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function chs(){const{scorerId:e}=Sr(),[t,n]=ri(),r=t.get("scoreId")??void 0,[s,a]=v.useState(r),[i,l]=v.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=OJr(e),{data:d={},isLoading:f,error:p}=Am(),{isLoading:h,error:m}=Ky(),{data:g=[],isLoading:y,error:b,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k}=kJr({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),C=v.useMemo(()=>c?.agentIds?.filter(q=>d[q]).map(q=>({value:q,label:d[q].name,type:"AGENT"}))||[],[c?.agentIds,d]),_=v.useMemo(()=>c?.workflowIds?.map(q=>({value:q,label:q,type:"WORKFLOW"}))||[],[c?.workflowIds]),E=v.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...C,..._],[C,_]),T=t.get("entity")??"all",N=E.find(q=>q.value===T);N&&N.value!==i?.value&&l(N),v.useEffect(()=>{if(u){const q=u instanceof Error?u.message:"Failed to load scorer";De.error(`Error loading scorer: ${q}`)}},[u]),v.useEffect(()=>{if(p){const q=p instanceof Error?p.message:"Failed to load agents";De.error(`Error loading agents: ${q}`)}},[p]),v.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(M=>{const G=new URLSearchParams(M);return G.set("entity",q.value),G})};v.useEffect(()=>{const q=t.get("scoreId")??void 0;if(q===s)return;if(!q){a(void 0);return}g.find(G=>G.id===q)&&a(q)},[t,g]);const A=v.useCallback(q=>{a(q||void 0),n(M=>{const G=new URLSearchParams(M);return q?G.set("scoreId",q):G.delete("scoreId"),G})},[n]);if(!c)return null;const R=ws(u)||ws(p)||ws(m),L=u&&Ss(u),D=!R&&!L&&(u||p||m),z=!y&&g.length===0,H=i?.value!=="all",F=c?.scorer?.source==="stored"?o.jsx(By,{owner:"scorer-detail",children:o.jsxs(ce,{variant:"default",as:za,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(lm,{})," Edit"]})}):null;if(R||L||D||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(Bt,{width:"wide",height:"full",children:[F,o.jsx(Bt.MainArea,{isCentered:!0,children:R?o.jsx(Zs,{}):L?o.jsx(Ms,{resource:"scorers"}):D?o.jsx(Hi,{title:"Failed to load scorer",message:q}):o.jsx(gJr,{})})]})}return o.jsxs(Bt,{width:"wide",children:[F,o.jsx(Bt.TopArea,{children:o.jsx(vJr,{selectedEntity:i,entityOptions:E,onEntityChange:I,onReset:()=>{n(q=>{const M=new URLSearchParams(q);return M.set("entity","all"),M})},isLoading:y||f||h})}),o.jsx(mJr,{scores:g,isLoading:y,selectedScoreId:s,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k,onScoreClick:A,errorMsg:b?.message})]})}function uhs({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(zt,{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-neutral3 text-sm",children:t})]}),s]})}const aUt=[{value:"dark",label:"Dark",Icon:iQt},{value:"light",label:"Light",Icon:yYt},{value:"system",label:"System",Icon:Vot}],dhs=e=>aUt.some(t=>t.value===e);function fhs({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex max-w-full min-w-0 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 phs=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=gH(),{theme:r,setTheme:s}=Z_();return o.jsx(Bt,{width:"narrow",children:o.jsxs(Bt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(ybe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(uhs,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(ma,{value:r,onValueChange:a=>{dhs(a)&&s(a)},children:[o.jsx(va,{id:"theme",className:"w-full sm:w-48",children:o.jsx(ga,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(ya,{children:aUt.map(a=>o.jsx($r,{value:a.value,children:o.jsx(fhs,{option:a})},a.value))})]})})}),o.jsx(ybe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(uDt,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function hhs(){const[e]=ri(),t=Ws(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(QBt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}const iUt=e=>o.jsx("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,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"})});function mhs(e){return e.replace(/\/$/,"").split("/").pop()}function CQ({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 ghs({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:"bg-surface3 h-16 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:"thumb transition-scale h-full w-full bg-cover 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:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",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(Ho,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(qd,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Hot,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(XN,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(wC,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center 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:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(iUt,{})," ",mhs(a.githubUrl)]})})]},a.slug)})})}function vhs({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(CN,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(jc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(jc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(ce,{onClick:c,children:["Reset ",o.jsx(ps,{})]})]})}function yhs(){const{data:e,isLoading:t}=Xtr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=v.useState("all"),[l,c]=v.useState("all"),[u,d]=v.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{p.push({value:x,label:x})});const h=(x,S)=>{S==="tag"?i(x):S==="provider"&&c(x)},m=x=>{d(x)},g=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(ds,{children:[o.jsx(E1e,{children:o.jsxs(Jvt,{children:[o.jsx(qe,{children:o.jsx(ty,{})}),"Templates"]})}),o.jsxs("div",{className:X("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(vhs,{selectedTag:a,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?g:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(ghs,{templates:y,linkComponent:za,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const bhs="1.58.0-alpha.6";function xhs({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(Rd,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(nGt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(CQ,{className:"text-neutral3 mb-8 content-center space-y-4",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:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",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:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs dark:bg-gray-800",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:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function whs({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(CQ,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",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(Wot,{})]}),o.jsx(jc,{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] items-start gap-4",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(Jt,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(v.Fragment,{children:[o.jsx(RO,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(RO,{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-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",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(r9t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ce,{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(Jt,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Sm,{})]})})]})})}function Shs({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(ty,{}),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 gap-x-24 lg:grid-cols-[1fr_1fr]",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:"mt-0.5 shrink-0",children:o.jsx(Xx,{className:"h-[1.1em] w-[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(Nxe,{className:"text-neutral4 h-[1em] w-[1em]"}),o.jsx("span",{className:"text-ui-md text-neutral5 font-medium",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 text-ui-sm rounded px-1.5 py-0.5 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:"text-neutral3 text-ui-md hover:text-neutral5 mt-auto flex items-center gap-2",children:[o.jsx(iUt,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(xIe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function khs(e){switch(e){case"running":return o.jsx(Jt,{});case"success":return o.jsx(Ix,{});case"failed":return o.jsx(Ku,{});default:return null}}function Ohs({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",xs.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",xs.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",xs.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:s(e)}),t.description&&o.jsx("p",{className:"text-ui-md text-neutral2 -mt-0.5",children:t.description})]})]}),o.jsx("div",{className:X("flex size-[1.75rem] items-center justify-center self-center rounded-full",xs.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:khs(t.status)})]})}function _hs({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:X(n),children:t.map((r,s)=>o.jsx(Ohs,{stepId:r.id,step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function Chs({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",xs.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",xs.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(Jt,{}):s+1})},r.id))}),o.jsxs("div",{className:X("text-center text-xs text-neutral3",xs.colors),children:[n," of ",t," steps completed"]})]})}function Ehs({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=g=>g==="input"||g.endsWith(".input")||g.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(g)||/[0-9a-f]{8,}/.test(g)?!1:r?.allSteps?g in r.allSteps:!0,f=Object.entries(c).filter(([g,y])=>d(g)),p=f.length,h=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([g,y])=>({id:g,status:y?.status,description:y?.description,title:g.charAt(0).toUpperCase()+g.slice(1).replace(/-/g," "),isActive:i?.id===g}));return o.jsxs(CQ,{className:"text-neutral3 mb-8 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-lg font-semibold",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-6",children:o.jsx(Chs,{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(gQt,{}),l||"Something went wrong"]}),u&&o.jsx(_hs,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 grid justify-items-center gap-4 text-center text-sm",children:[o.jsx(Jt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Ths({name:e,installedEntities:t}){return o.jsxs(CQ,{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Wot,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-neutral3 text-center",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(xIe,{data:t})]})}function jhs(){const{templateSlug:e}=Sr(),[t,n]=ri(),[r,s]=v.useState(""),[a,i]=v.useState(""),[l,c]=v.useState(""),[u,d]=v.useState({}),[f,p]=v.useState([]),[h,m]=v.useState(null),[g,y]=v.useState(!1),[b,x]=v.useState(""),[S,k]=v.useState(!1),[C,_]=v.useState(!1),[E,T]=v.useState([]),{data:N,isLoading:I}=Jtr({repoOrSlug:e,owner:"mastra-ai"}),R=bhs?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=enr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:z,isLoading:H}=tnr(),{mutateAsync:F,isPending:U}=nnr(),{mutateAsync:q}=rnr(),{streamInstall:M,streamResult:G,isStreaming:V}=anr(z),{observeInstall:$,streamResult:B,isStreaming:Z}=inr(z);v.useEffect(()=>{const re=t.get("runId");re&&!g&&!h&&!V&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:re}),x(re),q({runId:re}).then(le=>{const ue=le.snapshot;if(ue?.status==="success"&&ue?.result?.success)y(!0);else if(ue?.result?.success===!1)if(ue?.result?.validationResults&&!ue?.result?.validationResults?.valid&&ue?.result?.validationResults?.remainingErrors>0){const{remainingErrors:me,errors:be}=ue.result.validationResults,xe=`Template installation completed but ${me} validation issue${me>1?"s":""} remain unresolved.`;m(xe),T(be||[])}else{const me=ue?.result?.message||ue?.result?.error||"Template installation failed";m(typeof me=="string"?me:String(me))}}).catch(le=>{console.error("❌ Failed to fetch run details:",le),m("Failed to retrieve installation status after reload")}))},[t,g,h,V,Z,q]),v.useEffect(()=>{const re=t.get("runId"),le=t.get("resume"),ue=t.get("provider");if(re&&le==="true"&&ue&&!V&&!Z&&!S&&!C&&z){x(re),k(!0);try{q({runId:re}).then(oe=>{if(oe.snapshot?.status==="running")return $.mutateAsync({runId:re})}).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,S,C,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:N?.tools?.length?N.tools.map(re=>re).join(", "):"n/a",icon:o.jsx(qd,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(re=>re).join(", "):"n/a",icon:o.jsx(Ho,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(re=>re).join(", "):"n/a",icon:o.jsx(XN,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Fv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(KN,{})}],ee=[{...ne[0]},{...ne[1]},{...ne[2]}].filter(re=>re.value!=="n/a");v.useEffect(()=>{L&&d(L)},[L]),v.useEffect(()=>{const re=G||B;re?.phase==="error"&&re?.error&&m(typeof re.error=="string"?re.error:String(re.error))},[G?.phase,G?.error,B?.phase,B?.error]);const J=re=>{s(re)},ae=async re=>(i(re.provider),c(re.modelId),{message:"Model updated successfully"}),fe=async()=>{const re=Object.entries(u).reduce((le,[ue,oe])=>(oe===""&&le.push(ue),le),[]);if(re.length>0){p(re);return}if(N){m(null),y(!1),x(""),_(!0);try{const ue={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:oe}=await F({});x(oe),n(me=>{const be=new URLSearchParams(me);return be.set("runId",oe),be.set("resume","true"),be.set("provider",r||"openai"),be}),await M.mutateAsync({inputData:ue,selectedModel:{provider:a,modelId:l},runId:oe})}catch(le){_(!1),m(le?.message||"Template installation failed"),console.error("Template installation failed",le)}}},Y=re=>{const{name:le,value:ue}=re.target;ue.trim()===""?p(oe=>[...oe,le]):p(oe=>oe.filter(me=>me!==le)),d(oe=>({...oe,[le]:ue}))};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:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-6",children:[o.jsx(Shs,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:ne,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(V||Z)&&o.jsx(Ehs,{name:N.title,streamResult:Z?B:G,runId:b,workflowInfo:z}),g&&o.jsx(Ths,{name:N.title,installedEntities:ee,linkComponent:za}),h&&o.jsx(xhs,{errorMsg:h,validationErrors:E.length>0?E:G?.validationResults?.errors||B?.validationResults?.errors}),!V&&!Z&&!g&&!h&&o.jsx(whs,{providerOptions:K,selectedProvider:r,onProviderChange:J,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:fe,handleVariableChange:Y,isLoadingEnvVars:D||H,isInstalling:U,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const Nhs=()=>{const{toolId:e,agentId:t}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(sts,{toolId:e,agentId:t})})},Ihs=()=>{const{toolId:e}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(Mfs,{toolId:e})})};function Ahs(){const{traceId:e}=Sr(),[t,n]=ri(),r=Ws(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=v.useState(s??null),[d,f]=v.useState(),[p,h]=v.useState(i),[m,g]=v.useState(0),[y,b]=v.useState(!1),{data:x,isLoading:S,error:k}=lAe(e),C=v.useMemo(()=>x?.spans??[],[x?.spans]),_=v.useMemo(()=>C.find(ae=>ae.parentSpanId==null),[C]),{data:E,isLoading:T}=DL(e,c??"");v.useEffect(()=>g(0),[e,c]);const{data:N,isLoading:I}=ch(),{data:A,isLoading:R}=S9t({traceId:e,spanId:c??void 0,page:m}),[L,D]=v.useState(0);v.useEffect(()=>D(0),[e,c]);const{data:z,isLoading:H}=DBt({traceId:e,page:L});v.useEffect(()=>{if(l&&A?.scores&&!d){const ae=A.scores.find(fe=>fe.id===l);ae&&f(ae)}},[l,A?.scores,d]);const F=v.useCallback(ae=>{const fe=new URLSearchParams(t);for(const[Y,re]of Object.entries(ae))re===null||re===""?fe.delete(Y):fe.set(Y,re);n(fe,{replace:!0})},[t,n]),U=v.useCallback(ae=>{const fe=ae??null,Y=fe===c;u(fe),Y||(f(void 0),h("details"),F({spanId:fe,tab:null,scoreId:null}))},[c,F]),q=v.useCallback(()=>{u(null),f(void 0),h("details"),F({spanId:null,tab:null,scoreId:null})},[F]),M=v.useCallback(ae=>{u(ae),f(void 0),h("details"),F({spanId:ae,tab:null,scoreId:null})},[F]),{handlePreviousSpan:G,handleNextSpan:V}=cAe(C,c,M),$=v.useCallback(ae=>{const fe=ae;h(fe),f(void 0),F({tab:fe==="details"?null:fe,scoreId:null})},[F]),B=v.useCallback(ae=>{f(ae),F({scoreId:ae.id})},[F]),Z=v.useCallback(()=>{f(void 0),F({scoreId:null})},[F]),K=v.useCallback(()=>{r("/traces")},[r]),ne=v.useCallback(()=>{h("scoring"),_&&c!==_.spanId?(u(_.spanId),f(void 0),F({spanId:_.spanId,tab:"scoring",scoreId:null})):F({tab:"scoring"})},[_,c,F]),ee=_?o.jsx(By,{owner:"trace-detail",children:o.jsxs(Mr,{children:[o.jsxs(ce,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:ne,children:[o.jsx(QWt,{}),"Evaluate"]}),o.jsxs(ce,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(Ad,{}),"Save"]})]})}):null,J=_?o.jsx(Bt.Row,{children:o.jsx(Bt.Column,{children:o.jsx(xBt,{rootSpan:_,numOfCol:3})})}):null;return k?o.jsxs(Bt,{height:"full",children:[ee,J&&o.jsx(Bt.TopArea,{children:J}),o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsx(_Bt,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Bt,{height:"full",className:"grid-rows-[auto_minmax(0,1fr)] content-normal",children:[ee,J&&o.jsx(Bt.TopArea,{children:J}),o.jsx(ABt,{rootSpanId:_?.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(tAe,{traceId:e,spans:C,isLoading:S,onClose:K,onSpanSelect:U,onEvaluateTrace:ne,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!S&&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(XIe,{traceId:e,spanId:c,span:E?.span,isLoading:T,onClose:q,onPrevious:G,onNext:V,activeTab:p,onTabChange:$,feedbackTabBadge:z?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(PBt,{feedbackData:z,onPageChange:D,isLoadingFeedbackData:H}),scoringTabBadge:A?.pagination?.total??void 0,scoringTabSlot:({span:ae,traceId:fe,spanId:Y})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(MBt,{traceId:fe,isTopLevelSpan:!ae.parentSpanId,spanId:Y,entityType:ae.attributes?.agentId||ae.entityType===du.AGENT?"Agent":ae.attributes?.workflowId||ae.entityType===du.WORKFLOW_RUN?"Workflow":void 0,scorers:N,isLoadingScorers:I}),o.jsx($Bt,{scoresData:A,onPageChange:g,isLoadingScoresData:R,onScoreSelect:B})]})}),d&&o.jsx(bIe,{score:d,onClose:Z})]})]})]})}function Rhs(){const{data:e,isLoading:t,error:n}=Ky(),[r,s]=v.useState("");return n&&ws(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx(Ms,{resource:"workflows"})}):n?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(cr,{children:o.jsx(DBr,{})}):o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsxs(Bt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Ff,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(ce,{as:za,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(UD,{}),"Schedules"]})]})}),o.jsx(MBr,{workflows:e||{},isLoading:t,search:r})]})}const Phs={active:"bg-accent1",paused:"bg-accent3"},$hs={active:"text-accent1",paused:"text-accent3"},oUt=({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 ${Phs[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${$hs[e]}`,children:e})]}),hj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),Z2=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 lUt({status:e}){const{icon:t,color:n}=Mhs(e);return o.jsxs("span",{className:`text-ui-sm inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function Mhs(e){switch(e){case"success":return{icon:o.jsx(fa,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(ps,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Jt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(aV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx($f,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(yj,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const JJe="auto auto auto auto 1fr";function Dhs(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 Lhs(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 zhs=3e4,Fhs=5*6e4;function Bhs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=bn();return t?o.jsx(ll,{columns:JJe}):e.length===0?o.jsx(ye,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(ge,{columns:JJe,className:"min-w-0",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Run"}),o.jsx(ge.TopCell,{children:"Status"}),o.jsx(ge.TopCell,{children:"Started"}),o.jsx(ge.TopCell,{children:"Duration"}),o.jsx(ge.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=Lhs(u),f=`Scheduled ${hj(c.scheduledFireAt)} — published ${hj(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),g=!p&&m>zhs&&m<=Fhs,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),x=o.jsx("span",{className:b?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:c.runId}),S=o.jsxs(o.Fragment,{children:[o.jsx(ge.Cell,{height:"compact",children:x}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(Rd,{size:14}),"publish failed"]}):c.run?o.jsx(lUt,{status:c.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),h?o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(Rd,{size:14})})}),o.jsx(Pn,{children:h})]}):null]})}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:Z2(c.actualFireAt)}),g?o.jsxs($n,{children:[o.jsx(Rn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(Rd,{size:14})})}),o.jsxs(Pn,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(ge.Cell,{height:"compact",children:c.run?o.jsx("span",{children:Dhs(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(ge.Cell,{height:"compact",children:" "})]});return b?o.jsx(ge.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:S},y):o.jsx(ge.RowStatic,{children:S},y)}),o.jsx(ge.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const Uhs=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)}})},eet=25,qhs=e=>{const t=We(),{inView:n,setRef:r}=X_(),s=Q1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:eet,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<eet))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return v.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},Vhs=e=>{const t=We(),n=Br();return Ln({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 n8({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function Hhs(){const{scheduleId:e}=Sr(),{paths:t}=bn(),{data:n,error:r}=Uhs(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=qhs(e),d=Vhs(e);if(r&&ws(r))return o.jsx(cr,{children:o.jsx(Zs,{})});if(r&&Ss(r))return o.jsx(cr,{children:o.jsx(Ms,{resource:"schedules"})});if(r)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsx(Bt.Row,{className:"justify-end",children:o.jsxs(Bt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(ce,{as:za,to:t.schedulesLink(),variant:"ghost",children:[o.jsx($c,{}),"Back to schedules"]}),f?o.jsx(ce,{as:za,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ce,{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(cV,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(jf,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-6 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(n8,{label:p?"Agent":"Workflow",children:f?o.jsx(za,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(za,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(n8,{label:"Cron",children:[o.jsx("code",{className:"text-ui-md font-mono",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 text-ui-sm ml-2",children:n.timezone}):null]}),o.jsx(n8,{label:"Status",children:o.jsx(oUt,{status:n.status})}),o.jsx(n8,{label:"Next fire",children:o.jsx("span",{title:hj(n.nextFireAt),children:Z2(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(Bhs,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const tet="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function Whs({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=bn(),a=v.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:tet}):o.jsxs(ge,{columns:tet,variant:"striped",className:"min-w-0",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Target"}),o.jsx(ge.TopCell,{children:"Schedule ID"}),o.jsx(ge.TopCell,{children:"Cron"}),o.jsx(ge.TopCell,{children:"Status"}),o.jsx(ge.TopCell,{children:"Next fire"}),o.jsx(ge.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(ge.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(ge.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(ge.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(ge.NameCell,{children:i.workflowId??i.agentId}),o.jsx(ge.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:i.id,children:i.id})}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(ge.Cell,{height:"compact",children:o.jsx(oUt,{status:i.status})}),o.jsx(ge.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:hj(i.nextFireAt),children:Z2(i.nextFireAt)})}),o.jsx(ge.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(lUt,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:hj(i.lastFireAt),children:i.lastFireAt?Z2(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:hj(i.lastFireAt),children:Z2(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function Zhs({workflowId:e}={}){const{data:t,isLoading:n,error:r}=_1e(e?{workflowId:e}:{}),[s,a]=v.useState("");return r?o.jsx(Hi,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(Ff,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(Whs,{schedules:t??[],isLoading:n,search:s})})]})}function Ghs(){const[e]=ri(),t=e.get("workflowId")??void 0,{error:n}=_1e(t?{workflowId:t}:{});return n&&ws(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx(Ms,{resource:"schedules"})}):o.jsx(Bt,{children:o.jsx("div",{className:"h-full",children:o.jsx(Zhs,{workflowId:t})})})}function Qhs({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=rOe({stepGraph:e}),[a,i]=v.useState(!1),[l,c,u]=IOt(r),[d]=AOt(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=Y3t({edges:d,workflowName:n,stepGraph:e});return v.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsxs(NOt,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(GTe,{position:"bottom-left"}),o.jsx(POt,{variant:ly.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Jt,{})})})}function Yhs(){const{stepDetail:e,closeStepDetail:t}=dW();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(C9,{className:"h-4 w-4",style:{color:Ru.map}}),e.type==="nested-graph"&&o.jsx(rd,{className:"h-4 w-4",style:{color:Ru.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:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(ps,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(V2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(nOe,{children:o.jsx(Qhs,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function Khs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function Xhs(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 Jhs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border 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:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(qe,{children:o.jsx(aV,{})}),"Step suspended"]}),o.jsx(on,{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?gm(hm(Ax(i.resumeSchema))):yp(dr(),Lj());return o.jsx(ems,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function ems({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=v.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",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:"text-neutral3 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(lQt,{})}),"The step is asking"]}),o.jsxs(Pf,{open:a,onOpenChange:i,children:[o.jsxs(Fd,{className:"border-border1 bg-surface3 flex w-full items-center justify-between gap-2 rounded-lg border px-3 py-2.5",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(qe,{children:o.jsx(aa,{className:X("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ye,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:Xhs(e.suspendPayload,e.stepId)})]}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:Khs(e.suspendPayload)})]}),o.jsx(Bd,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Hr,{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:"text-neutral3 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(dQt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(YB,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(jf,{}),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 tms(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=v.useContext(Vl),{runId:a}=Sr(),i=BOt(e,r??""),l=hJn(),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:"animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 absolute top-2 right-2 z-20 max-h-[calc(100%-1rem)] w-[380px] max-w-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg duration-300",children:o.jsx(Jhs,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const nms=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"})]}),rms=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"})]}),sms=e=>e.includes("."),ams=e=>e==="input"||e.endsWith(".input"),ims=1;function oms(e){return`${Number((e/1e3).toPrecision(3))}s`}function lms(e,t){const n=Object.entries(e).filter(([i])=>!ams(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,ims);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:sms(i)}})}const cms=({status:e})=>o.jsxs(qe,{children:[e==="success"&&o.jsx(nms,{className:"text-accent1"}),e==="failed"&&o.jsx(rms,{className:"text-accent2"}),e==="suspended"&&o.jsx(aV,{className:"text-accent3"}),e==="waiting"&&o.jsx(ppe,{className:"text-accent5"}),e==="skipped"&&o.jsx(ppe,{className:"text-icon3"}),e==="running"&&o.jsx(ua,{className:"text-accent6 animate-spin"})]}),ums={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function cUt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const net=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},dms=e=>{const t=e;return B3t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},fms=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=dms(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(cms,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ce,{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(fYt,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(Aq,{indicators:c,className:"shrink-0"})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:cUt(e.stepId)}),o.jsx("div",{className:"bg-surface4 relative h-2 min-w-0 rounded",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 ${ums[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ce,{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(uYt,{})})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:oms(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function pms(){const{steps:e}=G4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=kH(),[a,i]=v.useState(()=>Date.now()),[l,c]=v.useState(!1),[u,d]=v.useState(null),f=v.useRef(null);R1e(f,{enabled:!l});const p=lms(e,a),h=p.some(m=>m.isRunning);return v.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),v.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"rounded-studio-panel border-border1/50 bg-surface3 pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden border 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:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(ka,{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,g)=>o.jsx(fms,{row:m,index:g,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:net(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:net(y.step.output)})},`timeline-item-${m.stepId}-${g}`))})]})}),o.jsx(vr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(qOt,{data:u.data,title:`${cUt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const hms=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=dW();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(s4t,{workflowId:e,workflow:t,isLoading:n}),o.jsx(tms,{}),o.jsx(pms,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(Yhs,{})})]})},ret=()=>{const{workflowId:e}=Sr(),{data:t,isLoading:n,error:r}=n4(e);return r&&ws(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})}):r&&Ss(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"workflows"})}):o.jsx(wOe,{children:o.jsx(hms,{workflowId:e,workflow:t??void 0,isLoading:n})})};function mms(e,t){if(e==null)return{};var n,r,s=Z1t(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 gxe(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 gms(e){if(Array.isArray(e))return gxe(e)}function vms(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function yms(e,t){if(e){if(typeof e=="string")return gxe(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)?gxe(e,t):void 0}}function bms(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
721
721
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function vxe(e){return gms(e)||vms(e)||yms(e)||bms()}function LD(e){"@babel/helpers - typeof";return LD=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},LD(e)}function xms(e,t){if(LD(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(LD(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function wms(e){var t=xms(e,"string");return LD(t)=="symbol"?t:t+""}function uUt(e,t,n){return(t=wms(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function set(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 ET(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?set(Object(n),!0).forEach(function(r){uUt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):set(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Sms(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 kie={};function kms(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return kie[t]||(kie[t]=Sms(e)),kie[t]}function Oms(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=kms(r);return s.reduce(function(a,i){return ET(ET({},a),n[i])},t)}function aet(e){return e.join(" ")}function _ms(e,t){var n=0;return function(r){return n+=1,r.map(function(s,a){return dUt({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(a)})})}}function dUt(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=_ms(n,a),p;if(!a)p=ET(ET({},l),{},{className:aet(l.className)});else{var h=Object.keys(n).reduce(function(b,x){return x.split(".").forEach(function(S){b.includes(S)||b.push(S)}),b},[]),m=l.className&&l.className.includes("token")?["token"]:[],g=l.className&&m.concat(l.className.filter(function(b){return!h.includes(b)}));p=ET(ET({},l),{},{className:aet(g)||void 0,style:Oms(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return ze.createElement(u,QO({key:i},p),y)}}const Cms=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var Ems=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function iet(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 Fw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?iet(Object(n),!0).forEach(function(r){uUt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):iet(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var Tms=/\n/g;function jms(e){return e.match(Tms)}function Nms(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map(function(s,a){var i=a+n;return ze.createElement("span",{key:"line-".concat(a),className:"react-syntax-highlighter-line-number",style:typeof r=="function"?r(i):r},"".concat(i,`
722
722
  `))})}function Ims(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 ze.createElement("code",{style:Object.assign({},n,s)},Nms({lines:t.replace(/\n$/,"").split(`
723
723
  `),style:i,startingLineNumber:l}))}function Ams(e){return"".concat(e.toString().length,".25em")}function fUt(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 pUt(e,t,n){var r={display:"inline-block",minWidth:Ams(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,a=Fw(Fw({},r),s);return a}function S9(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?Fw({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(vxe(m.className.trim().split(/\s+/)),vxe(u)):u,n&&a){var g=pUt(r,n,s);t.unshift(fUt(n,g))}return f&d&&(m.style=Fw({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function hUt(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(S9({children:[s],className:vxe(new Set(t))}));else if(s.children){var a=t.concat(s.properties.className);hUt(s.children,a).forEach(function(i){return n.push(i)})}}return n}function Rms(e,t,n,r,s,a,i,l,c){var u,d=hUt(e.value),f=[],p=-1,h=0;function m(C,_){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return S9({children:C,lineNumber:_,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:E,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function g(C,_){if(r&&_&&s){var E=pUt(l,_,i);C.unshift(fUt(_,E))}return C}function y(C,_){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||E.length>0?m(C,_,E):g(C,_)}for(var b=function(){var _=d[h],E=_.children[0].value,T=jms(E);if(T){var N=E.split(`