@abstractframework/observer 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,176 @@
1
+ var FC=Object.defineProperty;var zC=(e,t,n)=>t in e?FC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var kn=(e,t,n)=>zC(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const u of o.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}})();function Bv(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ay={exports:{}},mh={},ly={exports:{}},jn={};/**
2
+ * @license React
3
+ * react.production.min.js
4
+ *
5
+ * Copyright (c) Facebook, Inc. and its affiliates.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */var Gx;function BC(){if(Gx)return jn;Gx=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),u=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),_=Symbol.iterator;function g(z){return z===null||typeof z!="object"?null:(z=_&&z[_]||z["@@iterator"],typeof z=="function"?z:null)}var y={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},b=Object.assign,k={};function x(z,ne,se){this.props=z,this.context=ne,this.refs=k,this.updater=se||y}x.prototype.isReactComponent={},x.prototype.setState=function(z,ne){if(typeof z!="object"&&typeof z!="function"&&z!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,z,ne,"setState")},x.prototype.forceUpdate=function(z){this.updater.enqueueForceUpdate(this,z,"forceUpdate")};function N(){}N.prototype=x.prototype;function $(z,ne,se){this.props=z,this.context=ne,this.refs=k,this.updater=se||y}var E=$.prototype=new N;E.constructor=$,b(E,x.prototype),E.isPureReactComponent=!0;var S=Array.isArray,P=Object.prototype.hasOwnProperty,D={current:null},R={key:!0,ref:!0,__self:!0,__source:!0};function I(z,ne,se){var de,be={},Me=null,je=null;if(ne!=null)for(de in ne.ref!==void 0&&(je=ne.ref),ne.key!==void 0&&(Me=""+ne.key),ne)P.call(ne,de)&&!R.hasOwnProperty(de)&&(be[de]=ne[de]);var ae=arguments.length-2;if(ae===1)be.children=se;else if(1<ae){for(var xe=Array(ae),Ae=0;Ae<ae;Ae++)xe[Ae]=arguments[Ae+2];be.children=xe}if(z&&z.defaultProps)for(de in ae=z.defaultProps,ae)be[de]===void 0&&(be[de]=ae[de]);return{$$typeof:e,type:z,key:Me,ref:je,props:be,_owner:D.current}}function W(z,ne){return{$$typeof:e,type:z.type,key:ne,ref:z.ref,props:z.props,_owner:z._owner}}function G(z){return typeof z=="object"&&z!==null&&z.$$typeof===e}function K(z){var ne={"=":"=0",":":"=2"};return"$"+z.replace(/[=:]/g,function(se){return ne[se]})}var H=/\/+/g;function M(z,ne){return typeof z=="object"&&z!==null&&z.key!=null?K(""+z.key):ne.toString(36)}function A(z,ne,se,de,be){var Me=typeof z;(Me==="undefined"||Me==="boolean")&&(z=null);var je=!1;if(z===null)je=!0;else switch(Me){case"string":case"number":je=!0;break;case"object":switch(z.$$typeof){case e:case t:je=!0}}if(je)return je=z,be=be(je),z=de===""?"."+M(je,0):de,S(be)?(se="",z!=null&&(se=z.replace(H,"$&/")+"/"),A(be,ne,se,"",function(Ae){return Ae})):be!=null&&(G(be)&&(be=W(be,se+(!be.key||je&&je.key===be.key?"":(""+be.key).replace(H,"$&/")+"/")+z)),ne.push(be)),1;if(je=0,de=de===""?".":de+":",S(z))for(var ae=0;ae<z.length;ae++){Me=z[ae];var xe=de+M(Me,ae);je+=A(Me,ne,se,xe,be)}else if(xe=g(z),typeof xe=="function")for(z=xe.call(z),ae=0;!(Me=z.next()).done;)Me=Me.value,xe=de+M(Me,ae++),je+=A(Me,ne,se,xe,be);else if(Me==="object")throw ne=String(z),Error("Objects are not valid as a React child (found: "+(ne==="[object Object]"?"object with keys {"+Object.keys(z).join(", ")+"}":ne)+"). If you meant to render a collection of children, use an array instead.");return je}function O(z,ne,se){if(z==null)return z;var de=[],be=0;return A(z,de,"","",function(Me){return ne.call(se,Me,be++)}),de}function L(z){if(z._status===-1){var ne=z._result;ne=ne(),ne.then(function(se){(z._status===0||z._status===-1)&&(z._status=1,z._result=se)},function(se){(z._status===0||z._status===-1)&&(z._status=2,z._result=se)}),z._status===-1&&(z._status=0,z._result=ne)}if(z._status===1)return z._result.default;throw z._result}var V={current:null},J={transition:null},U={ReactCurrentDispatcher:V,ReactCurrentBatchConfig:J,ReactCurrentOwner:D};function te(){throw Error("act(...) is not supported in production builds of React.")}return jn.Children={map:O,forEach:function(z,ne,se){O(z,function(){ne.apply(this,arguments)},se)},count:function(z){var ne=0;return O(z,function(){ne++}),ne},toArray:function(z){return O(z,function(ne){return ne})||[]},only:function(z){if(!G(z))throw Error("React.Children.only expected to receive a single React element child.");return z}},jn.Component=x,jn.Fragment=n,jn.Profiler=i,jn.PureComponent=$,jn.StrictMode=r,jn.Suspense=d,jn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=U,jn.act=te,jn.cloneElement=function(z,ne,se){if(z==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+z+".");var de=b({},z.props),be=z.key,Me=z.ref,je=z._owner;if(ne!=null){if(ne.ref!==void 0&&(Me=ne.ref,je=D.current),ne.key!==void 0&&(be=""+ne.key),z.type&&z.type.defaultProps)var ae=z.type.defaultProps;for(xe in ne)P.call(ne,xe)&&!R.hasOwnProperty(xe)&&(de[xe]=ne[xe]===void 0&&ae!==void 0?ae[xe]:ne[xe])}var xe=arguments.length-2;if(xe===1)de.children=se;else if(1<xe){ae=Array(xe);for(var Ae=0;Ae<xe;Ae++)ae[Ae]=arguments[Ae+2];de.children=ae}return{$$typeof:e,type:z.type,key:be,ref:Me,props:de,_owner:je}},jn.createContext=function(z){return z={$$typeof:u,_currentValue:z,_currentValue2:z,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},z.Provider={$$typeof:o,_context:z},z.Consumer=z},jn.createElement=I,jn.createFactory=function(z){var ne=I.bind(null,z);return ne.type=z,ne},jn.createRef=function(){return{current:null}},jn.forwardRef=function(z){return{$$typeof:l,render:z}},jn.isValidElement=G,jn.lazy=function(z){return{$$typeof:m,_payload:{_status:-1,_result:z},_init:L}},jn.memo=function(z,ne){return{$$typeof:h,type:z,compare:ne===void 0?null:ne}},jn.startTransition=function(z){var ne=J.transition;J.transition={};try{z()}finally{J.transition=ne}},jn.unstable_act=te,jn.useCallback=function(z,ne){return V.current.useCallback(z,ne)},jn.useContext=function(z){return V.current.useContext(z)},jn.useDebugValue=function(){},jn.useDeferredValue=function(z){return V.current.useDeferredValue(z)},jn.useEffect=function(z,ne){return V.current.useEffect(z,ne)},jn.useId=function(){return V.current.useId()},jn.useImperativeHandle=function(z,ne,se){return V.current.useImperativeHandle(z,ne,se)},jn.useInsertionEffect=function(z,ne){return V.current.useInsertionEffect(z,ne)},jn.useLayoutEffect=function(z,ne){return V.current.useLayoutEffect(z,ne)},jn.useMemo=function(z,ne){return V.current.useMemo(z,ne)},jn.useReducer=function(z,ne,se){return V.current.useReducer(z,ne,se)},jn.useRef=function(z){return V.current.useRef(z)},jn.useState=function(z){return V.current.useState(z)},jn.useSyncExternalStore=function(z,ne,se){return V.current.useSyncExternalStore(z,ne,se)},jn.useTransition=function(){return V.current.useTransition()},jn.version="18.3.1",jn}var Kx;function gm(){return Kx||(Kx=1,ly.exports=BC()),ly.exports}/**
10
+ * @license React
11
+ * react-jsx-runtime.production.min.js
12
+ *
13
+ * Copyright (c) Facebook, Inc. and its affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ */var Jx;function UC(){if(Jx)return mh;Jx=1;var e=gm(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,i=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function u(l,d,h){var m,_={},g=null,y=null;h!==void 0&&(g=""+h),d.key!==void 0&&(g=""+d.key),d.ref!==void 0&&(y=d.ref);for(m in d)r.call(d,m)&&!o.hasOwnProperty(m)&&(_[m]=d[m]);if(l&&l.defaultProps)for(m in d=l.defaultProps,d)_[m]===void 0&&(_[m]=d[m]);return{$$typeof:t,type:l,key:g,ref:y,props:_,_owner:i.current}}return mh.Fragment=n,mh.jsx=u,mh.jsxs=u,mh}var Yx;function WC(){return Yx||(Yx=1,ay.exports=UC()),ay.exports}var s=WC(),p=gm();const Ee=Bv(p);var q_={},cy={exports:{}},wi={},uy={exports:{}},dy={};/**
18
+ * @license React
19
+ * scheduler.production.min.js
20
+ *
21
+ * Copyright (c) Facebook, Inc. and its affiliates.
22
+ *
23
+ * This source code is licensed under the MIT license found in the
24
+ * LICENSE file in the root directory of this source tree.
25
+ */var Xx;function qC(){return Xx||(Xx=1,(function(e){function t(J,U){var te=J.length;J.push(U);e:for(;0<te;){var z=te-1>>>1,ne=J[z];if(0<i(ne,U))J[z]=U,J[te]=ne,te=z;else break e}}function n(J){return J.length===0?null:J[0]}function r(J){if(J.length===0)return null;var U=J[0],te=J.pop();if(te!==U){J[0]=te;e:for(var z=0,ne=J.length,se=ne>>>1;z<se;){var de=2*(z+1)-1,be=J[de],Me=de+1,je=J[Me];if(0>i(be,te))Me<ne&&0>i(je,be)?(J[z]=je,J[Me]=te,z=Me):(J[z]=be,J[de]=te,z=de);else if(Me<ne&&0>i(je,te))J[z]=je,J[Me]=te,z=Me;else break e}}return U}function i(J,U){var te=J.sortIndex-U.sortIndex;return te!==0?te:J.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var u=Date,l=u.now();e.unstable_now=function(){return u.now()-l}}var d=[],h=[],m=1,_=null,g=3,y=!1,b=!1,k=!1,x=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,$=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(J){for(var U=n(h);U!==null;){if(U.callback===null)r(h);else if(U.startTime<=J)r(h),U.sortIndex=U.expirationTime,t(d,U);else break;U=n(h)}}function S(J){if(k=!1,E(J),!b)if(n(d)!==null)b=!0,L(P);else{var U=n(h);U!==null&&V(S,U.startTime-J)}}function P(J,U){b=!1,k&&(k=!1,N(I),I=-1),y=!0;var te=g;try{for(E(U),_=n(d);_!==null&&(!(_.expirationTime>U)||J&&!K());){var z=_.callback;if(typeof z=="function"){_.callback=null,g=_.priorityLevel;var ne=z(_.expirationTime<=U);U=e.unstable_now(),typeof ne=="function"?_.callback=ne:_===n(d)&&r(d),E(U)}else r(d);_=n(d)}if(_!==null)var se=!0;else{var de=n(h);de!==null&&V(S,de.startTime-U),se=!1}return se}finally{_=null,g=te,y=!1}}var D=!1,R=null,I=-1,W=5,G=-1;function K(){return!(e.unstable_now()-G<W)}function H(){if(R!==null){var J=e.unstable_now();G=J;var U=!0;try{U=R(!0,J)}finally{U?M():(D=!1,R=null)}}else D=!1}var M;if(typeof $=="function")M=function(){$(H)};else if(typeof MessageChannel<"u"){var A=new MessageChannel,O=A.port2;A.port1.onmessage=H,M=function(){O.postMessage(null)}}else M=function(){x(H,0)};function L(J){R=J,D||(D=!0,M())}function V(J,U){I=x(function(){J(e.unstable_now())},U)}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(J){J.callback=null},e.unstable_continueExecution=function(){b||y||(b=!0,L(P))},e.unstable_forceFrameRate=function(J){0>J||125<J?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):W=0<J?Math.floor(1e3/J):5},e.unstable_getCurrentPriorityLevel=function(){return g},e.unstable_getFirstCallbackNode=function(){return n(d)},e.unstable_next=function(J){switch(g){case 1:case 2:case 3:var U=3;break;default:U=g}var te=g;g=U;try{return J()}finally{g=te}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(J,U){switch(J){case 1:case 2:case 3:case 4:case 5:break;default:J=3}var te=g;g=J;try{return U()}finally{g=te}},e.unstable_scheduleCallback=function(J,U,te){var z=e.unstable_now();switch(typeof te=="object"&&te!==null?(te=te.delay,te=typeof te=="number"&&0<te?z+te:z):te=z,J){case 1:var ne=-1;break;case 2:ne=250;break;case 5:ne=1073741823;break;case 4:ne=1e4;break;default:ne=5e3}return ne=te+ne,J={id:m++,callback:U,priorityLevel:J,startTime:te,expirationTime:ne,sortIndex:-1},te>z?(J.sortIndex=te,t(h,J),n(d)===null&&J===n(h)&&(k?(N(I),I=-1):k=!0,V(S,te-z))):(J.sortIndex=ne,t(d,J),b||y||(b=!0,L(P))),J},e.unstable_shouldYield=K,e.unstable_wrapCallback=function(J){var U=g;return function(){var te=g;g=U;try{return J.apply(this,arguments)}finally{g=te}}}})(dy)),dy}var Zx;function HC(){return Zx||(Zx=1,uy.exports=qC()),uy.exports}/**
26
+ * @license React
27
+ * react-dom.production.min.js
28
+ *
29
+ * Copyright (c) Facebook, Inc. and its affiliates.
30
+ *
31
+ * This source code is licensed under the MIT license found in the
32
+ * LICENSE file in the root directory of this source tree.
33
+ */var Qx;function VC(){if(Qx)return wi;Qx=1;var e=gm(),t=HC();function n(a){for(var c="https://reactjs.org/docs/error-decoder.html?invariant="+a,f=1;f<arguments.length;f++)c+="&args[]="+encodeURIComponent(arguments[f]);return"Minified React error #"+a+"; visit "+c+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=new Set,i={};function o(a,c){u(a,c),u(a+"Capture",c)}function u(a,c){for(i[a]=c,a=0;a<c.length;a++)r.add(c[a])}var l=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),d=Object.prototype.hasOwnProperty,h=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,m={},_={};function g(a){return d.call(_,a)?!0:d.call(m,a)?!1:h.test(a)?_[a]=!0:(m[a]=!0,!1)}function y(a,c,f,w){if(f!==null&&f.type===0)return!1;switch(typeof c){case"function":case"symbol":return!0;case"boolean":return w?!1:f!==null?!f.acceptsBooleans:(a=a.toLowerCase().slice(0,5),a!=="data-"&&a!=="aria-");default:return!1}}function b(a,c,f,w){if(c===null||typeof c>"u"||y(a,c,f,w))return!0;if(w)return!1;if(f!==null)switch(f.type){case 3:return!c;case 4:return c===!1;case 5:return isNaN(c);case 6:return isNaN(c)||1>c}return!1}function k(a,c,f,w,j,C,q){this.acceptsBooleans=c===2||c===3||c===4,this.attributeName=w,this.attributeNamespace=j,this.mustUseProperty=f,this.propertyName=a,this.type=c,this.sanitizeURL=C,this.removeEmptyString=q}var x={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){x[a]=new k(a,0,!1,a,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var c=a[0];x[c]=new k(c,1,!1,a[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(a){x[a]=new k(a,2,!1,a.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){x[a]=new k(a,2,!1,a,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){x[a]=new k(a,3,!1,a.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(a){x[a]=new k(a,3,!0,a,null,!1,!1)}),["capture","download"].forEach(function(a){x[a]=new k(a,4,!1,a,null,!1,!1)}),["cols","rows","size","span"].forEach(function(a){x[a]=new k(a,6,!1,a,null,!1,!1)}),["rowSpan","start"].forEach(function(a){x[a]=new k(a,5,!1,a.toLowerCase(),null,!1,!1)});var N=/[\-:]([a-z])/g;function $(a){return a[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var c=a.replace(N,$);x[c]=new k(c,1,!1,a,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var c=a.replace(N,$);x[c]=new k(c,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(a){var c=a.replace(N,$);x[c]=new k(c,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(a){x[a]=new k(a,1,!1,a.toLowerCase(),null,!1,!1)}),x.xlinkHref=new k("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(a){x[a]=new k(a,1,!1,a.toLowerCase(),null,!0,!0)});function E(a,c,f,w){var j=x.hasOwnProperty(c)?x[c]:null;(j!==null?j.type!==0:w||!(2<c.length)||c[0]!=="o"&&c[0]!=="O"||c[1]!=="n"&&c[1]!=="N")&&(b(c,f,j,w)&&(f=null),w||j===null?g(c)&&(f===null?a.removeAttribute(c):a.setAttribute(c,""+f)):j.mustUseProperty?a[j.propertyName]=f===null?j.type===3?!1:"":f:(c=j.attributeName,w=j.attributeNamespace,f===null?a.removeAttribute(c):(j=j.type,f=j===3||j===4&&f===!0?"":""+f,w?a.setAttributeNS(w,c,f):a.setAttribute(c,f))))}var S=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,P=Symbol.for("react.element"),D=Symbol.for("react.portal"),R=Symbol.for("react.fragment"),I=Symbol.for("react.strict_mode"),W=Symbol.for("react.profiler"),G=Symbol.for("react.provider"),K=Symbol.for("react.context"),H=Symbol.for("react.forward_ref"),M=Symbol.for("react.suspense"),A=Symbol.for("react.suspense_list"),O=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),V=Symbol.for("react.offscreen"),J=Symbol.iterator;function U(a){return a===null||typeof a!="object"?null:(a=J&&a[J]||a["@@iterator"],typeof a=="function"?a:null)}var te=Object.assign,z;function ne(a){if(z===void 0)try{throw Error()}catch(f){var c=f.stack.trim().match(/\n( *(at )?)/);z=c&&c[1]||""}return`
34
+ `+z+a}var se=!1;function de(a,c){if(!a||se)return"";se=!0;var f=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(c)if(c=function(){throw Error()},Object.defineProperty(c.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(c,[])}catch(Te){var w=Te}Reflect.construct(a,[],c)}else{try{c.call()}catch(Te){w=Te}a.call(c.prototype)}else{try{throw Error()}catch(Te){w=Te}a()}}catch(Te){if(Te&&w&&typeof Te.stack=="string"){for(var j=Te.stack.split(`
35
+ `),C=w.stack.split(`
36
+ `),q=j.length-1,ie=C.length-1;1<=q&&0<=ie&&j[q]!==C[ie];)ie--;for(;1<=q&&0<=ie;q--,ie--)if(j[q]!==C[ie]){if(q!==1||ie!==1)do if(q--,ie--,0>ie||j[q]!==C[ie]){var ue=`
37
+ `+j[q].replace(" at new "," at ");return a.displayName&&ue.includes("<anonymous>")&&(ue=ue.replace("<anonymous>",a.displayName)),ue}while(1<=q&&0<=ie);break}}}finally{se=!1,Error.prepareStackTrace=f}return(a=a?a.displayName||a.name:"")?ne(a):""}function be(a){switch(a.tag){case 5:return ne(a.type);case 16:return ne("Lazy");case 13:return ne("Suspense");case 19:return ne("SuspenseList");case 0:case 2:case 15:return a=de(a.type,!1),a;case 11:return a=de(a.type.render,!1),a;case 1:return a=de(a.type,!0),a;default:return""}}function Me(a){if(a==null)return null;if(typeof a=="function")return a.displayName||a.name||null;if(typeof a=="string")return a;switch(a){case R:return"Fragment";case D:return"Portal";case W:return"Profiler";case I:return"StrictMode";case M:return"Suspense";case A:return"SuspenseList"}if(typeof a=="object")switch(a.$$typeof){case K:return(a.displayName||"Context")+".Consumer";case G:return(a._context.displayName||"Context")+".Provider";case H:var c=a.render;return a=a.displayName,a||(a=c.displayName||c.name||"",a=a!==""?"ForwardRef("+a+")":"ForwardRef"),a;case O:return c=a.displayName||null,c!==null?c:Me(a.type)||"Memo";case L:c=a._payload,a=a._init;try{return Me(a(c))}catch{}}return null}function je(a){var c=a.type;switch(a.tag){case 24:return"Cache";case 9:return(c.displayName||"Context")+".Consumer";case 10:return(c._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return a=c.render,a=a.displayName||a.name||"",c.displayName||(a!==""?"ForwardRef("+a+")":"ForwardRef");case 7:return"Fragment";case 5:return c;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Me(c);case 8:return c===I?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof c=="function")return c.displayName||c.name||null;if(typeof c=="string")return c}return null}function ae(a){switch(typeof a){case"boolean":case"number":case"string":case"undefined":return a;case"object":return a;default:return""}}function xe(a){var c=a.type;return(a=a.nodeName)&&a.toLowerCase()==="input"&&(c==="checkbox"||c==="radio")}function Ae(a){var c=xe(a)?"checked":"value",f=Object.getOwnPropertyDescriptor(a.constructor.prototype,c),w=""+a[c];if(!a.hasOwnProperty(c)&&typeof f<"u"&&typeof f.get=="function"&&typeof f.set=="function"){var j=f.get,C=f.set;return Object.defineProperty(a,c,{configurable:!0,get:function(){return j.call(this)},set:function(q){w=""+q,C.call(this,q)}}),Object.defineProperty(a,c,{enumerable:f.enumerable}),{getValue:function(){return w},setValue:function(q){w=""+q},stopTracking:function(){a._valueTracker=null,delete a[c]}}}}function He(a){a._valueTracker||(a._valueTracker=Ae(a))}function mt(a){if(!a)return!1;var c=a._valueTracker;if(!c)return!0;var f=c.getValue(),w="";return a&&(w=xe(a)?a.checked?"true":"false":a.value),a=w,a!==f?(c.setValue(a),!0):!1}function nt(a){if(a=a||(typeof document<"u"?document:void 0),typeof a>"u")return null;try{return a.activeElement||a.body}catch{return a.body}}function rt(a,c){var f=c.checked;return te({},c,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:f??a._wrapperState.initialChecked})}function ze(a,c){var f=c.defaultValue==null?"":c.defaultValue,w=c.checked!=null?c.checked:c.defaultChecked;f=ae(c.value!=null?c.value:f),a._wrapperState={initialChecked:w,initialValue:f,controlled:c.type==="checkbox"||c.type==="radio"?c.checked!=null:c.value!=null}}function Ve(a,c){c=c.checked,c!=null&&E(a,"checked",c,!1)}function ct(a,c){Ve(a,c);var f=ae(c.value),w=c.type;if(f!=null)w==="number"?(f===0&&a.value===""||a.value!=f)&&(a.value=""+f):a.value!==""+f&&(a.value=""+f);else if(w==="submit"||w==="reset"){a.removeAttribute("value");return}c.hasOwnProperty("value")?Dt(a,c.type,f):c.hasOwnProperty("defaultValue")&&Dt(a,c.type,ae(c.defaultValue)),c.checked==null&&c.defaultChecked!=null&&(a.defaultChecked=!!c.defaultChecked)}function Qe(a,c,f){if(c.hasOwnProperty("value")||c.hasOwnProperty("defaultValue")){var w=c.type;if(!(w!=="submit"&&w!=="reset"||c.value!==void 0&&c.value!==null))return;c=""+a._wrapperState.initialValue,f||c===a.value||(a.value=c),a.defaultValue=c}f=a.name,f!==""&&(a.name=""),a.defaultChecked=!!a._wrapperState.initialChecked,f!==""&&(a.name=f)}function Dt(a,c,f){(c!=="number"||nt(a.ownerDocument)!==a)&&(f==null?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+f&&(a.defaultValue=""+f))}var $e=Array.isArray;function Le(a,c,f,w){if(a=a.options,c){c={};for(var j=0;j<f.length;j++)c["$"+f[j]]=!0;for(f=0;f<a.length;f++)j=c.hasOwnProperty("$"+a[f].value),a[f].selected!==j&&(a[f].selected=j),j&&w&&(a[f].defaultSelected=!0)}else{for(f=""+ae(f),c=null,j=0;j<a.length;j++){if(a[j].value===f){a[j].selected=!0,w&&(a[j].defaultSelected=!0);return}c!==null||a[j].disabled||(c=a[j])}c!==null&&(c.selected=!0)}}function ce(a,c){if(c.dangerouslySetInnerHTML!=null)throw Error(n(91));return te({},c,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function Q(a,c){var f=c.value;if(f==null){if(f=c.children,c=c.defaultValue,f!=null){if(c!=null)throw Error(n(92));if($e(f)){if(1<f.length)throw Error(n(93));f=f[0]}c=f}c==null&&(c=""),f=c}a._wrapperState={initialValue:ae(f)}}function _e(a,c){var f=ae(c.value),w=ae(c.defaultValue);f!=null&&(f=""+f,f!==a.value&&(a.value=f),c.defaultValue==null&&a.defaultValue!==f&&(a.defaultValue=f)),w!=null&&(a.defaultValue=""+w)}function le(a){var c=a.textContent;c===a._wrapperState.initialValue&&c!==""&&c!==null&&(a.value=c)}function Se(a){switch(a){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function pe(a,c){return a==null||a==="http://www.w3.org/1999/xhtml"?Se(c):a==="http://www.w3.org/2000/svg"&&c==="foreignObject"?"http://www.w3.org/1999/xhtml":a}var dt,yt=(function(a){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(c,f,w,j){MSApp.execUnsafeLocalFunction(function(){return a(c,f,w,j)})}:a})(function(a,c){if(a.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in a)a.innerHTML=c;else{for(dt=dt||document.createElement("div"),dt.innerHTML="<svg>"+c.valueOf().toString()+"</svg>",c=dt.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;c.firstChild;)a.appendChild(c.firstChild)}});function _t(a,c){if(c){var f=a.firstChild;if(f&&f===a.lastChild&&f.nodeType===3){f.nodeValue=c;return}}a.textContent=c}var It={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},bt=["Webkit","ms","Moz","O"];Object.keys(It).forEach(function(a){bt.forEach(function(c){c=c+a.charAt(0).toUpperCase()+a.substring(1),It[c]=It[a]})});function St(a,c,f){return c==null||typeof c=="boolean"||c===""?"":f||typeof c!="number"||c===0||It.hasOwnProperty(a)&&It[a]?(""+c).trim():c+"px"}function ut(a,c){a=a.style;for(var f in c)if(c.hasOwnProperty(f)){var w=f.indexOf("--")===0,j=St(f,c[f],w);f==="float"&&(f="cssFloat"),w?a.setProperty(f,j):a[f]=j}}var Ot=te({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Mt(a,c){if(c){if(Ot[a]&&(c.children!=null||c.dangerouslySetInnerHTML!=null))throw Error(n(137,a));if(c.dangerouslySetInnerHTML!=null){if(c.children!=null)throw Error(n(60));if(typeof c.dangerouslySetInnerHTML!="object"||!("__html"in c.dangerouslySetInnerHTML))throw Error(n(61))}if(c.style!=null&&typeof c.style!="object")throw Error(n(62))}}function mn(a,c){if(a.indexOf("-")===-1)return typeof c.is=="string";switch(a){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var yn=null;function In(a){return a=a.target||a.srcElement||window,a.correspondingUseElement&&(a=a.correspondingUseElement),a.nodeType===3?a.parentNode:a}var Gs=null,ss=null,ge=null;function Re(a){if(a=ta(a)){if(typeof Gs!="function")throw Error(n(280));var c=a.stateNode;c&&(c=Ao(c),Gs(a.stateNode,a.type,c))}}function gt(a){ss?ge?ge.push(a):ge=[a]:ss=a}function re(){if(ss){var a=ss,c=ge;if(ge=ss=null,Re(a),c)for(a=0;a<c.length;a++)Re(c[a])}}function fe(a,c){return a(c)}function Ce(){}var Ie=!1;function We(a,c,f){if(Ie)return a(c,f);Ie=!0;try{return fe(a,c,f)}finally{Ie=!1,(ss!==null||ge!==null)&&(Ce(),re())}}function Ue(a,c){var f=a.stateNode;if(f===null)return null;var w=Ao(f);if(w===null)return null;f=w[c];e:switch(c){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(w=!w.disabled)||(a=a.type,w=!(a==="button"||a==="input"||a==="select"||a==="textarea")),a=!w;break e;default:a=!1}if(a)return null;if(f&&typeof f!="function")throw Error(n(231,c,typeof f));return f}var et=!1;if(l)try{var at={};Object.defineProperty(at,"passive",{get:function(){et=!0}}),window.addEventListener("test",at,at),window.removeEventListener("test",at,at)}catch{et=!1}function vt(a,c,f,w,j,C,q,ie,ue){var Te=Array.prototype.slice.call(arguments,3);try{c.apply(f,Te)}catch(Ze){this.onError(Ze)}}var xt=!1,Et=null,zt=!1,ot=null,Jt={onError:function(a){xt=!0,Et=a}};function wn(a,c,f,w,j,C,q,ie,ue){xt=!1,Et=null,vt.apply(Jt,arguments)}function hn(a,c,f,w,j,C,q,ie,ue){if(wn.apply(this,arguments),xt){if(xt){var Te=Et;xt=!1,Et=null}else throw Error(n(198));zt||(zt=!0,ot=Te)}}function sn(a){var c=a,f=a;if(a.alternate)for(;c.return;)c=c.return;else{a=c;do c=a,(c.flags&4098)!==0&&(f=c.return),a=c.return;while(a)}return c.tag===3?f:null}function Vt(a){if(a.tag===13){var c=a.memoizedState;if(c===null&&(a=a.alternate,a!==null&&(c=a.memoizedState)),c!==null)return c.dehydrated}return null}function rs(a){if(sn(a)!==a)throw Error(n(188))}function Be(a){var c=a.alternate;if(!c){if(c=sn(a),c===null)throw Error(n(188));return c!==a?null:a}for(var f=a,w=c;;){var j=f.return;if(j===null)break;var C=j.alternate;if(C===null){if(w=j.return,w!==null){f=w;continue}break}if(j.child===C.child){for(C=j.child;C;){if(C===f)return rs(j),a;if(C===w)return rs(j),c;C=C.sibling}throw Error(n(188))}if(f.return!==w.return)f=j,w=C;else{for(var q=!1,ie=j.child;ie;){if(ie===f){q=!0,f=j,w=C;break}if(ie===w){q=!0,w=j,f=C;break}ie=ie.sibling}if(!q){for(ie=C.child;ie;){if(ie===f){q=!0,f=C,w=j;break}if(ie===w){q=!0,w=C,f=j;break}ie=ie.sibling}if(!q)throw Error(n(189))}}if(f.alternate!==w)throw Error(n(190))}if(f.tag!==3)throw Error(n(188));return f.stateNode.current===f?a:c}function Zt(a){return a=Be(a),a!==null?Tt(a):null}function Tt(a){if(a.tag===5||a.tag===6)return a;for(a=a.child;a!==null;){var c=Tt(a);if(c!==null)return c;a=a.sibling}return null}var Dn=t.unstable_scheduleCallback,fn=t.unstable_cancelCallback,Xe=t.unstable_shouldYield,nn=t.unstable_requestPaint,cn=t.unstable_now,Er=t.unstable_getCurrentPriorityLevel,Cs=t.unstable_ImmediatePriority,gs=t.unstable_UserBlockingPriority,mr=t.unstable_NormalPriority,we=t.unstable_LowPriority,Nt=t.unstable_IdlePriority,Fn=null,tr=null;function Ni(a){if(tr&&typeof tr.onCommitFiberRoot=="function")try{tr.onCommitFiberRoot(Fn,a,void 0,(a.current.flags&128)===128)}catch{}}var nr=Math.clz32?Math.clz32:ll,vo=Math.log,uc=Math.LN2;function ll(a){return a>>>=0,a===0?32:31-(vo(a)/uc|0)|0}var bs=64,_r=4194304;function Ts(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return a}}function zi(a,c){var f=a.pendingLanes;if(f===0)return 0;var w=0,j=a.suspendedLanes,C=a.pingedLanes,q=f&268435455;if(q!==0){var ie=q&~j;ie!==0?w=Ts(ie):(C&=q,C!==0&&(w=Ts(C)))}else q=f&~j,q!==0?w=Ts(q):C!==0&&(w=Ts(C));if(w===0)return 0;if(c!==0&&c!==w&&(c&j)===0&&(j=w&-w,C=c&-c,j>=C||j===16&&(C&4194240)!==0))return c;if((w&4)!==0&&(w|=f&16),c=a.entangledLanes,c!==0)for(a=a.entanglements,c&=w;0<c;)f=31-nr(c),j=1<<f,w|=a[f],c&=~j;return w}function cl(a,c){switch(a){case 1:case 2:case 4:return c+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return c+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function ys(a,c){for(var f=a.suspendedLanes,w=a.pingedLanes,j=a.expirationTimes,C=a.pendingLanes;0<C;){var q=31-nr(C),ie=1<<q,ue=j[q];ue===-1?((ie&f)===0||(ie&w)!==0)&&(j[q]=cl(ie,c)):ue<=c&&(a.expiredLanes|=ie),C&=~ie}}function ni(a){return a=a.pendingLanes&-1073741825,a!==0?a:a&1073741824?1073741824:0}function Ms(){var a=bs;return bs<<=1,(bs&4194240)===0&&(bs=64),a}function si(a){for(var c=[],f=0;31>f;f++)c.push(a);return c}function ks(a,c,f){a.pendingLanes|=c,c!==536870912&&(a.suspendedLanes=0,a.pingedLanes=0),a=a.eventTimes,c=31-nr(c),a[c]=f}function ri(a,c){var f=a.pendingLanes&~c;a.pendingLanes=c,a.suspendedLanes=0,a.pingedLanes=0,a.expiredLanes&=c,a.mutableReadLanes&=c,a.entangledLanes&=c,c=a.entanglements;var w=a.eventTimes;for(a=a.expirationTimes;0<f;){var j=31-nr(f),C=1<<j;c[j]=0,w[j]=-1,a[j]=-1,f&=~C}}function Bi(a,c){var f=a.entangledLanes|=c;for(a=a.entanglements;f;){var w=31-nr(f),j=1<<w;j&c|a[w]&c&&(a[w]|=c),f&=~j}}var Ln=0;function Sa(a){return a&=-a,1<a?4<a?(a&268435455)!==0?16:536870912:4:1}var ul,dl,Ar,dc,Ui,Na=!1,xo=[],Ps=null,Ds=null,pr=null,bo=new Map,Ur=new Map,Tr=[],Wr="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function fc(a,c){switch(a){case"focusin":case"focusout":Ps=null;break;case"dragenter":case"dragleave":Ds=null;break;case"mouseover":case"mouseout":pr=null;break;case"pointerover":case"pointerout":bo.delete(c.pointerId);break;case"gotpointercapture":case"lostpointercapture":Ur.delete(c.pointerId)}}function qr(a,c,f,w,j,C){return a===null||a.nativeEvent!==C?(a={blockedOn:c,domEventName:f,eventSystemFlags:w,nativeEvent:C,targetContainers:[j]},c!==null&&(c=ta(c),c!==null&&dl(c)),a):(a.eventSystemFlags|=w,c=a.targetContainers,j!==null&&c.indexOf(j)===-1&&c.push(j),a)}function xu(a,c,f,w,j){switch(c){case"focusin":return Ps=qr(Ps,a,c,f,w,j),!0;case"dragenter":return Ds=qr(Ds,a,c,f,w,j),!0;case"mouseover":return pr=qr(pr,a,c,f,w,j),!0;case"pointerover":var C=j.pointerId;return bo.set(C,qr(bo.get(C)||null,a,c,f,w,j)),!0;case"gotpointercapture":return C=j.pointerId,Ur.set(C,qr(Ur.get(C)||null,a,c,f,w,j)),!0}return!1}function $i(a){var c=Pa(a.target);if(c!==null){var f=sn(c);if(f!==null){if(c=f.tag,c===13){if(c=Vt(f),c!==null){a.blockedOn=c,Ui(a.priority,function(){Ar(f)});return}}else if(c===3&&f.stateNode.current.memoizedState.isDehydrated){a.blockedOn=f.tag===3?f.stateNode.containerInfo:null;return}}}a.blockedOn=null}function Yo(a){if(a.blockedOn!==null)return!1;for(var c=a.targetContainers;0<c.length;){var f=he(a.domEventName,a.eventSystemFlags,c[0],a.nativeEvent);if(f===null){f=a.nativeEvent;var w=new f.constructor(f.type,f);yn=w,f.target.dispatchEvent(w),yn=null}else return c=ta(f),c!==null&&dl(c),a.blockedOn=f,!1;c.shift()}return!0}function fl(a,c,f){Yo(a)&&f.delete(c)}function ko(){Na=!1,Ps!==null&&Yo(Ps)&&(Ps=null),Ds!==null&&Yo(Ds)&&(Ds=null),pr!==null&&Yo(pr)&&(pr=null),bo.forEach(fl),Ur.forEach(fl)}function ii(a,c){a.blockedOn===c&&(a.blockedOn=null,Na||(Na=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,ko)))}function $a(a){function c(j){return ii(j,a)}if(0<xo.length){ii(xo[0],a);for(var f=1;f<xo.length;f++){var w=xo[f];w.blockedOn===a&&(w.blockedOn=null)}}for(Ps!==null&&ii(Ps,a),Ds!==null&&ii(Ds,a),pr!==null&&ii(pr,a),bo.forEach(c),Ur.forEach(c),f=0;f<Tr.length;f++)w=Tr[f],w.blockedOn===a&&(w.blockedOn=null);for(;0<Tr.length&&(f=Tr[0],f.blockedOn===null);)$i(f),f.blockedOn===null&&Tr.shift()}var Wi=S.ReactCurrentBatchConfig,sr=!0;function af(a,c,f,w){var j=Ln,C=Wi.transition;Wi.transition=null;try{Ln=1,Gn(a,c,f,w)}finally{Ln=j,Wi.transition=C}}function oi(a,c,f,w){var j=Ln,C=Wi.transition;Wi.transition=null;try{Ln=4,Gn(a,c,f,w)}finally{Ln=j,Wi.transition=C}}function Gn(a,c,f,w){if(sr){var j=he(a,c,f,w);if(j===null)bl(a,c,w,Y,f),fc(a,w);else if(xu(j,a,c,f,w))w.stopPropagation();else if(fc(a,w),c&4&&-1<Wr.indexOf(a)){for(;j!==null;){var C=ta(j);if(C!==null&&ul(C),C=he(a,c,f,w),C===null&&bl(a,c,w,Y,f),C===j)break;j=C}j!==null&&w.stopPropagation()}else bl(a,c,w,null,f)}}var Y=null;function he(a,c,f,w){if(Y=null,a=In(w),a=Pa(a),a!==null)if(c=sn(a),c===null)a=null;else if(f=c.tag,f===13){if(a=Vt(c),a!==null)return a;a=null}else if(f===3){if(c.stateNode.current.memoizedState.isDehydrated)return c.tag===3?c.stateNode.containerInfo:null;a=null}else c!==a&&(a=null);return Y=a,null}function Oe(a){switch(a){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(Er()){case Cs:return 1;case gs:return 4;case mr:case we:return 16;case Nt:return 536870912;default:return 16}default:return 16}}var De=null,Ye=null,ht=null;function Wt(){if(ht)return ht;var a,c=Ye,f=c.length,w,j="value"in De?De.value:De.textContent,C=j.length;for(a=0;a<f&&c[a]===j[a];a++);var q=f-a;for(w=1;w<=q&&c[f-w]===j[C-w];w++);return ht=j.slice(a,1<w?1-w:void 0)}function Pt(a){var c=a.keyCode;return"charCode"in a?(a=a.charCode,a===0&&c===13&&(a=13)):a=c,a===10&&(a=13),32<=a||a===13?a:0}function Bt(){return!0}function pn(){return!1}function Cn(a){function c(f,w,j,C,q){this._reactName=f,this._targetInst=j,this.type=w,this.nativeEvent=C,this.target=q,this.currentTarget=null;for(var ie in a)a.hasOwnProperty(ie)&&(f=a[ie],this[ie]=f?f(C):C[ie]);return this.isDefaultPrevented=(C.defaultPrevented!=null?C.defaultPrevented:C.returnValue===!1)?Bt:pn,this.isPropagationStopped=pn,this}return te(c.prototype,{preventDefault:function(){this.defaultPrevented=!0;var f=this.nativeEvent;f&&(f.preventDefault?f.preventDefault():typeof f.returnValue!="unknown"&&(f.returnValue=!1),this.isDefaultPrevented=Bt)},stopPropagation:function(){var f=this.nativeEvent;f&&(f.stopPropagation?f.stopPropagation():typeof f.cancelBubble!="unknown"&&(f.cancelBubble=!0),this.isPropagationStopped=Bt)},persist:function(){},isPersistent:Bt}),c}var Ks={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Ft=Cn(Ks),xn=te({},Ks,{view:0,detail:0}),os=Cn(xn),Hn,Mr,gr,qi=te({},xn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:ml,button:0,buttons:0,relatedTarget:function(a){return a.relatedTarget===void 0?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){return"movementX"in a?a.movementX:(a!==gr&&(gr&&a.type==="mousemove"?(Hn=a.screenX-gr.screenX,Mr=a.screenY-gr.screenY):Mr=Hn=0,gr=a),Hn)},movementY:function(a){return"movementY"in a?a.movementY:Mr}}),hl=Cn(qi),Hi=te({},qi,{dataTransfer:0}),lf=Cn(Hi),hc=te({},xn,{relatedTarget:0}),Ca=Cn(hc),Ea=te({},Ks,{animationName:0,elapsedTime:0,pseudoElement:0}),cf=Cn(Ea),mc=te({},Ks,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),_c=Cn(mc),bu=te({},Ks,{data:0}),uf=Cn(bu),ku={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},df={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},ju={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Su(a){var c=this.nativeEvent;return c.getModifierState?c.getModifierState(a):(a=ju[a])?!!c[a]:!1}function ml(){return Su}var Lm=te({},xn,{key:function(a){if(a.key){var c=ku[a.key]||a.key;if(c!=="Unidentified")return c}return a.type==="keypress"?(a=Pt(a),a===13?"Enter":String.fromCharCode(a)):a.type==="keydown"||a.type==="keyup"?df[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:ml,charCode:function(a){return a.type==="keypress"?Pt(a):0},keyCode:function(a){return a.type==="keydown"||a.type==="keyup"?a.keyCode:0},which:function(a){return a.type==="keypress"?Pt(a):a.type==="keydown"||a.type==="keyup"?a.keyCode:0}}),Aa=Cn(Lm),Im=te({},qi,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Nu=Cn(Im),ff=te({},xn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:ml}),hf=Cn(ff),_l=te({},Ks,{propertyName:0,elapsedTime:0,pseudoElement:0}),Om=Cn(_l),Pm=te({},qi,{deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0}),mf=Cn(Pm),Hg=[9,13,27,32],$u=l&&"CompositionEvent"in window,pl=null;l&&"documentMode"in document&&(pl=document.documentMode);var Vg=l&&"TextEvent"in window&&!pl,Cu=l&&(!$u||pl&&8<pl&&11>=pl),En=" ",Eu=!1;function Dm(a,c){switch(a){case"keyup":return Hg.indexOf(c.keyCode)!==-1;case"keydown":return c.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Au(a){return a=a.detail,typeof a=="object"&&"data"in a?a.data:null}var gl=!1;function _f(a,c){switch(a){case"compositionend":return Au(c);case"keypress":return c.which!==32?null:(Eu=!0,En);case"textInput":return a=c.data,a===En&&Eu?null:a;default:return null}}function Gg(a,c){if(gl)return a==="compositionend"||!$u&&Dm(a,c)?(a=Wt(),ht=Ye=De=null,gl=!1,a):null;switch(a){case"paste":return null;case"keypress":if(!(c.ctrlKey||c.altKey||c.metaKey)||c.ctrlKey&&c.altKey){if(c.char&&1<c.char.length)return c.char;if(c.which)return String.fromCharCode(c.which)}return null;case"compositionend":return Cu&&c.locale!=="ko"?null:c.data;default:return null}}var js={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function jo(a){var c=a&&a.nodeName&&a.nodeName.toLowerCase();return c==="input"?!!js[a.type]:c==="textarea"}function pf(a,c,f,w){gt(w),c=Ei(c,"onChange"),0<c.length&&(f=new Ft("onChange","change",null,f,w),a.push({event:f,listeners:c}))}var pc=null,Vi=null;function gf(a){wr(a,0)}function Xo(a){var c=Sl(a);if(mt(c))return a}function Fm(a,c){if(a==="change")return c}var zm=!1;if(l){var yf;if(l){var wf="oninput"in document;if(!wf){var vf=document.createElement("div");vf.setAttribute("oninput","return;"),wf=typeof vf.oninput=="function"}yf=wf}else yf=!1;zm=yf&&(!document.documentMode||9<document.documentMode)}function Bm(){pc&&(pc.detachEvent("onpropertychange",xf),Vi=pc=null)}function xf(a){if(a.propertyName==="value"&&Xo(Vi)){var c=[];pf(c,Vi,a,In(a)),We(gf,c)}}function Kg(a,c,f){a==="focusin"?(Bm(),pc=c,Vi=f,pc.attachEvent("onpropertychange",xf)):a==="focusout"&&Bm()}function Um(a){if(a==="selectionchange"||a==="keyup"||a==="keydown")return Xo(Vi)}function Wm(a,c){if(a==="click")return Xo(c)}function bf(a,c){if(a==="input"||a==="change")return Xo(c)}function yl(a,c){return a===c&&(a!==0||1/a===1/c)||a!==a&&c!==c}var yr=typeof Object.is=="function"?Object.is:yl;function Gi(a,c){if(yr(a,c))return!0;if(typeof a!="object"||a===null||typeof c!="object"||c===null)return!1;var f=Object.keys(a),w=Object.keys(c);if(f.length!==w.length)return!1;for(w=0;w<f.length;w++){var j=f[w];if(!d.call(c,j)||!yr(a[j],c[j]))return!1}return!0}function wl(a){for(;a&&a.firstChild;)a=a.firstChild;return a}function gc(a,c){var f=wl(a);a=0;for(var w;f;){if(f.nodeType===3){if(w=a+f.textContent.length,a<=c&&w>=c)return{node:f,offset:c-a};a=w}e:{for(;f;){if(f.nextSibling){f=f.nextSibling;break e}f=f.parentNode}f=void 0}f=wl(f)}}function Tu(a,c){return a&&c?a===c?!0:a&&a.nodeType===3?!1:c&&c.nodeType===3?Tu(a,c.parentNode):"contains"in a?a.contains(c):a.compareDocumentPosition?!!(a.compareDocumentPosition(c)&16):!1:!1}function kf(){for(var a=window,c=nt();c instanceof a.HTMLIFrameElement;){try{var f=typeof c.contentWindow.location.href=="string"}catch{f=!1}if(f)a=c.contentWindow;else break;c=nt(a.document)}return c}function Ta(a){var c=a&&a.nodeName&&a.nodeName.toLowerCase();return c&&(c==="input"&&(a.type==="text"||a.type==="search"||a.type==="tel"||a.type==="url"||a.type==="password")||c==="textarea"||a.contentEditable==="true")}function qm(a){var c=kf(),f=a.focusedElem,w=a.selectionRange;if(c!==f&&f&&f.ownerDocument&&Tu(f.ownerDocument.documentElement,f)){if(w!==null&&Ta(f)){if(c=w.start,a=w.end,a===void 0&&(a=c),"selectionStart"in f)f.selectionStart=c,f.selectionEnd=Math.min(a,f.value.length);else if(a=(c=f.ownerDocument||document)&&c.defaultView||window,a.getSelection){a=a.getSelection();var j=f.textContent.length,C=Math.min(w.start,j);w=w.end===void 0?C:Math.min(w.end,j),!a.extend&&C>w&&(j=w,w=C,C=j),j=gc(f,C);var q=gc(f,w);j&&q&&(a.rangeCount!==1||a.anchorNode!==j.node||a.anchorOffset!==j.offset||a.focusNode!==q.node||a.focusOffset!==q.offset)&&(c=c.createRange(),c.setStart(j.node,j.offset),a.removeAllRanges(),C>w?(a.addRange(c),a.extend(q.node,q.offset)):(c.setEnd(q.node,q.offset),a.addRange(c)))}}for(c=[],a=f;a=a.parentNode;)a.nodeType===1&&c.push({element:a,left:a.scrollLeft,top:a.scrollTop});for(typeof f.focus=="function"&&f.focus(),f=0;f<c.length;f++)a=c[f],a.element.scrollLeft=a.left,a.element.scrollTop=a.top}}var yc=l&&"documentMode"in document&&11>=document.documentMode,Ki=null,jf=null,Ma=null,Sf=!1;function Mu(a,c,f){var w=f.window===f?f.document:f.nodeType===9?f:f.ownerDocument;Sf||Ki==null||Ki!==nt(w)||(w=Ki,"selectionStart"in w&&Ta(w)?w={start:w.selectionStart,end:w.selectionEnd}:(w=(w.ownerDocument&&w.ownerDocument.defaultView||window).getSelection(),w={anchorNode:w.anchorNode,anchorOffset:w.anchorOffset,focusNode:w.focusNode,focusOffset:w.focusOffset}),Ma&&Gi(Ma,w)||(Ma=w,w=Ei(jf,"onSelect"),0<w.length&&(c=new Ft("onSelect","select",null,c,f),a.push({event:c,listeners:w}),c.target=Ki)))}function Ra(a,c){var f={};return f[a.toLowerCase()]=c.toLowerCase(),f["Webkit"+a]="webkit"+c,f["Moz"+a]="moz"+c,f}var Rr={animationend:Ra("Animation","AnimationEnd"),animationiteration:Ra("Animation","AnimationIteration"),animationstart:Ra("Animation","AnimationStart"),transitionend:Ra("Transition","TransitionEnd")},Zo={},Hm={};l&&(Hm=document.createElement("div").style,"AnimationEvent"in window||(delete Rr.animationend.animation,delete Rr.animationiteration.animation,delete Rr.animationstart.animation),"TransitionEvent"in window||delete Rr.transitionend.transition);function La(a){if(Zo[a])return Zo[a];if(!Rr[a])return a;var c=Rr[a],f;for(f in c)if(c.hasOwnProperty(f)&&f in Hm)return Zo[a]=c[f];return a}var Vm=La("animationend"),Ru=La("animationiteration"),vl=La("animationstart"),Hr=La("transitionend"),So=new Map,wc="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function Vr(a,c){So.set(a,c),o(c,[a])}for(var vc=0;vc<wc.length;vc++){var Ia=wc[vc],No=Ia.toLowerCase(),Lu=Ia[0].toUpperCase()+Ia.slice(1);Vr(No,"on"+Lu)}Vr(Vm,"onAnimationEnd"),Vr(Ru,"onAnimationIteration"),Vr(vl,"onAnimationStart"),Vr("dblclick","onDoubleClick"),Vr("focusin","onFocus"),Vr("focusout","onBlur"),Vr(Hr,"onTransitionEnd"),u("onMouseEnter",["mouseout","mouseover"]),u("onMouseLeave",["mouseout","mouseover"]),u("onPointerEnter",["pointerout","pointerover"]),u("onPointerLeave",["pointerout","pointerover"]),o("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),o("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),o("onBeforeInput",["compositionend","keypress","textInput","paste"]),o("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),o("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),o("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var $o="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),xl=new Set("cancel close invalid load scroll toggle".split(" ").concat($o));function Co(a,c,f){var w=a.type||"unknown-event";a.currentTarget=f,hn(w,c,void 0,a),a.currentTarget=null}function wr(a,c){c=(c&4)!==0;for(var f=0;f<a.length;f++){var w=a[f],j=w.event;w=w.listeners;e:{var C=void 0;if(c)for(var q=w.length-1;0<=q;q--){var ie=w[q],ue=ie.instance,Te=ie.currentTarget;if(ie=ie.listener,ue!==C&&j.isPropagationStopped())break e;Co(j,ie,Te),C=ue}else for(q=0;q<w.length;q++){if(ie=w[q],ue=ie.instance,Te=ie.currentTarget,ie=ie.listener,ue!==C&&j.isPropagationStopped())break e;Co(j,ie,Te),C=ue}}}if(zt)throw a=ot,zt=!1,ot=null,a}function zn(a,c){var f=c[kl];f===void 0&&(f=c[kl]=new Set);var w=a+"__bubble";f.has(w)||(Iu(c,a,2,!1),f.add(w))}function Qo(a,c,f){var w=0;c&&(w|=4),Iu(f,a,w,c)}var Oa="_reactListening"+Math.random().toString(36).slice(2);function Ci(a){if(!a[Oa]){a[Oa]=!0,r.forEach(function(f){f!=="selectionchange"&&(xl.has(f)||Qo(f,!1,a),Qo(f,!0,a))});var c=a.nodeType===9?a:a.ownerDocument;c===null||c[Oa]||(c[Oa]=!0,Qo("selectionchange",!1,c))}}function Iu(a,c,f,w){switch(Oe(c)){case 1:var j=af;break;case 4:j=oi;break;default:j=Gn}f=j.bind(null,c,f,a),j=void 0,!et||c!=="touchstart"&&c!=="touchmove"&&c!=="wheel"||(j=!0),w?j!==void 0?a.addEventListener(c,f,{capture:!0,passive:j}):a.addEventListener(c,f,!0):j!==void 0?a.addEventListener(c,f,{passive:j}):a.addEventListener(c,f,!1)}function bl(a,c,f,w,j){var C=w;if((c&1)===0&&(c&2)===0&&w!==null)e:for(;;){if(w===null)return;var q=w.tag;if(q===3||q===4){var ie=w.stateNode.containerInfo;if(ie===j||ie.nodeType===8&&ie.parentNode===j)break;if(q===4)for(q=w.return;q!==null;){var ue=q.tag;if((ue===3||ue===4)&&(ue=q.stateNode.containerInfo,ue===j||ue.nodeType===8&&ue.parentNode===j))return;q=q.return}for(;ie!==null;){if(q=Pa(ie),q===null)return;if(ue=q.tag,ue===5||ue===6){w=C=q;continue e}ie=ie.parentNode}}w=w.return}We(function(){var Te=C,Ze=In(f),tt=[];e:{var Je=So.get(a);if(Je!==void 0){var kt=Ft,$t=a;switch(a){case"keypress":if(Pt(f)===0)break e;case"keydown":case"keyup":kt=Aa;break;case"focusin":$t="focus",kt=Ca;break;case"focusout":$t="blur",kt=Ca;break;case"beforeblur":case"afterblur":kt=Ca;break;case"click":if(f.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":kt=hl;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":kt=lf;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":kt=hf;break;case Vm:case Ru:case vl:kt=cf;break;case Hr:kt=Om;break;case"scroll":kt=os;break;case"wheel":kt=mf;break;case"copy":case"cut":case"paste":kt=_c;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":kt=Nu}var At=(c&4)!==0,Ls=!At&&a==="scroll",ve=At?Je!==null?Je+"Capture":null:Je;At=[];for(var me=Te,Ne;me!==null;){Ne=me;var it=Ne.stateNode;if(Ne.tag===5&&it!==null&&(Ne=it,ve!==null&&(it=Ue(me,ve),it!=null&&At.push(Lr(me,it,Ne)))),Ls)break;me=me.return}0<At.length&&(Je=new kt(Je,$t,null,f,Ze),tt.push({event:Je,listeners:At}))}}if((c&7)===0){e:{if(Je=a==="mouseover"||a==="pointerover",kt=a==="mouseout"||a==="pointerout",Je&&f!==yn&&($t=f.relatedTarget||f.fromElement)&&(Pa($t)||$t[Ai]))break e;if((kt||Je)&&(Je=Ze.window===Ze?Ze:(Je=Ze.ownerDocument)?Je.defaultView||Je.parentWindow:window,kt?($t=f.relatedTarget||f.toElement,kt=Te,$t=$t?Pa($t):null,$t!==null&&(Ls=sn($t),$t!==Ls||$t.tag!==5&&$t.tag!==6)&&($t=null)):(kt=null,$t=Te),kt!==$t)){if(At=hl,it="onMouseLeave",ve="onMouseEnter",me="mouse",(a==="pointerout"||a==="pointerover")&&(At=Nu,it="onPointerLeave",ve="onPointerEnter",me="pointer"),Ls=kt==null?Je:Sl(kt),Ne=$t==null?Je:Sl($t),Je=new At(it,me+"leave",kt,f,Ze),Je.target=Ls,Je.relatedTarget=Ne,it=null,Pa(Ze)===Te&&(At=new At(ve,me+"enter",$t,f,Ze),At.target=Ne,At.relatedTarget=Ls,it=At),Ls=it,kt&&$t)t:{for(At=kt,ve=$t,me=0,Ne=At;Ne;Ne=vr(Ne))me++;for(Ne=0,it=ve;it;it=vr(it))Ne++;for(;0<me-Ne;)At=vr(At),me--;for(;0<Ne-me;)ve=vr(ve),Ne--;for(;me--;){if(At===ve||ve!==null&&At===ve.alternate)break t;At=vr(At),ve=vr(ve)}At=null}else At=null;kt!==null&&Nf(tt,Je,kt,At,!1),$t!==null&&Ls!==null&&Nf(tt,Ls,$t,At,!0)}}e:{if(Je=Te?Sl(Te):window,kt=Je.nodeName&&Je.nodeName.toLowerCase(),kt==="select"||kt==="input"&&Je.type==="file")var Rt=Fm;else if(jo(Je))if(zm)Rt=bf;else{Rt=Um;var Gt=Kg}else(kt=Je.nodeName)&&kt.toLowerCase()==="input"&&(Je.type==="checkbox"||Je.type==="radio")&&(Rt=Wm);if(Rt&&(Rt=Rt(a,Te))){pf(tt,Rt,f,Ze);break e}Gt&&Gt(a,Je,Te),a==="focusout"&&(Gt=Je._wrapperState)&&Gt.controlled&&Je.type==="number"&&Dt(Je,"number",Je.value)}switch(Gt=Te?Sl(Te):window,a){case"focusin":(jo(Gt)||Gt.contentEditable==="true")&&(Ki=Gt,jf=Te,Ma=null);break;case"focusout":Ma=jf=Ki=null;break;case"mousedown":Sf=!0;break;case"contextmenu":case"mouseup":case"dragend":Sf=!1,Mu(tt,f,Ze);break;case"selectionchange":if(yc)break;case"keydown":case"keyup":Mu(tt,f,Ze)}var Kt;if($u)e:{switch(a){case"compositionstart":var dn="onCompositionStart";break e;case"compositionend":dn="onCompositionEnd";break e;case"compositionupdate":dn="onCompositionUpdate";break e}dn=void 0}else gl?Dm(a,f)&&(dn="onCompositionEnd"):a==="keydown"&&f.keyCode===229&&(dn="onCompositionStart");dn&&(Cu&&f.locale!=="ko"&&(gl||dn!=="onCompositionStart"?dn==="onCompositionEnd"&&gl&&(Kt=Wt()):(De=Ze,Ye="value"in De?De.value:De.textContent,gl=!0)),Gt=Ei(Te,dn),0<Gt.length&&(dn=new uf(dn,a,null,f,Ze),tt.push({event:dn,listeners:Gt}),Kt?dn.data=Kt:(Kt=Au(f),Kt!==null&&(dn.data=Kt)))),(Kt=Vg?_f(a,f):Gg(a,f))&&(Te=Ei(Te,"onBeforeInput"),0<Te.length&&(Ze=new uf("onBeforeInput","beforeinput",null,f,Ze),tt.push({event:Ze,listeners:Te}),Ze.data=Kt))}wr(tt,c)})}function Lr(a,c,f){return{instance:a,listener:c,currentTarget:f}}function Ei(a,c){for(var f=c+"Capture",w=[];a!==null;){var j=a,C=j.stateNode;j.tag===5&&C!==null&&(j=C,C=Ue(a,f),C!=null&&w.unshift(Lr(a,C,j)),C=Ue(a,c),C!=null&&w.push(Lr(a,C,j))),a=a.return}return w}function vr(a){if(a===null)return null;do a=a.return;while(a&&a.tag!==5);return a||null}function Nf(a,c,f,w,j){for(var C=c._reactName,q=[];f!==null&&f!==w;){var ie=f,ue=ie.alternate,Te=ie.stateNode;if(ue!==null&&ue===w)break;ie.tag===5&&Te!==null&&(ie=Te,j?(ue=Ue(f,C),ue!=null&&q.unshift(Lr(f,ue,ie))):j||(ue=Ue(f,C),ue!=null&&q.push(Lr(f,ue,ie)))),f=f.return}q.length!==0&&a.push({event:c,listeners:q})}var xc=/\r\n?/g,Gm=/\u0000|\uFFFD/g;function Ou(a){return(typeof a=="string"?a:""+a).replace(xc,`
38
+ `).replace(Gm,"")}function bc(a,c,f){if(c=Ou(c),Ou(a)!==c&&f)throw Error(n(425))}function kc(){}var Pu=null,$f=null;function Du(a,c){return a==="textarea"||a==="noscript"||typeof c.children=="string"||typeof c.children=="number"||typeof c.dangerouslySetInnerHTML=="object"&&c.dangerouslySetInnerHTML!==null&&c.dangerouslySetInnerHTML.__html!=null}var Cf=typeof setTimeout=="function"?setTimeout:void 0,Km=typeof clearTimeout=="function"?clearTimeout:void 0,Jm=typeof Promise=="function"?Promise:void 0,Ym=typeof queueMicrotask=="function"?queueMicrotask:typeof Jm<"u"?function(a){return Jm.resolve(null).then(a).catch(Jg)}:Cf;function Jg(a){setTimeout(function(){throw a})}function Fu(a,c){var f=c,w=0;do{var j=f.nextSibling;if(a.removeChild(f),j&&j.nodeType===8)if(f=j.data,f==="/$"){if(w===0){a.removeChild(j),$a(c);return}w--}else f!=="$"&&f!=="$?"&&f!=="$!"||w++;f=j}while(f);$a(c)}function ea(a){for(;a!=null;a=a.nextSibling){var c=a.nodeType;if(c===1||c===3)break;if(c===8){if(c=a.data,c==="$"||c==="$!"||c==="$?")break;if(c==="/$")return null}}return a}function Ef(a){a=a.previousSibling;for(var c=0;a;){if(a.nodeType===8){var f=a.data;if(f==="$"||f==="$!"||f==="$?"){if(c===0)return a;c--}else f==="/$"&&c++}a=a.previousSibling}return null}var Ji=Math.random().toString(36).slice(2),Yi="__reactFiber$"+Ji,Eo="__reactProps$"+Ji,Ai="__reactContainer$"+Ji,kl="__reactEvents$"+Ji,Xm="__reactListeners$"+Ji,jl="__reactHandles$"+Ji;function Pa(a){var c=a[Yi];if(c)return c;for(var f=a.parentNode;f;){if(c=f[Ai]||f[Yi]){if(f=c.alternate,c.child!==null||f!==null&&f.child!==null)for(a=Ef(a);a!==null;){if(f=a[Yi])return f;a=Ef(a)}return c}a=f,f=a.parentNode}return null}function ta(a){return a=a[Yi]||a[Ai],!a||a.tag!==5&&a.tag!==6&&a.tag!==13&&a.tag!==3?null:a}function Sl(a){if(a.tag===5||a.tag===6)return a.stateNode;throw Error(n(33))}function Ao(a){return a[Eo]||null}var Af=[],To=-1;function na(a){return{current:a}}function On(a){0>To||(a.current=Af[To],Af[To]=null,To--)}function Yn(a,c){To++,Af[To]=a.current,a.current=c}var ai={},Es=na(ai),xr=na(!1),Mo=ai;function Xi(a,c){var f=a.type.contextTypes;if(!f)return ai;var w=a.stateNode;if(w&&w.__reactInternalMemoizedUnmaskedChildContext===c)return w.__reactInternalMemoizedMaskedChildContext;var j={},C;for(C in f)j[C]=c[C];return w&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=c,a.__reactInternalMemoizedMaskedChildContext=j),j}function rr(a){return a=a.childContextTypes,a!=null}function Ro(){On(xr),On(Es)}function zu(a,c,f){if(Es.current!==ai)throw Error(n(168));Yn(Es,c),Yn(xr,f)}function Zm(a,c,f){var w=a.stateNode;if(c=c.childContextTypes,typeof w.getChildContext!="function")return f;w=w.getChildContext();for(var j in w)if(!(j in c))throw Error(n(108,je(a)||"Unknown",j));return te({},f,w)}function Nl(a){return a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||ai,Mo=Es.current,Yn(Es,a),Yn(xr,xr.current),!0}function Bu(a,c,f){var w=a.stateNode;if(!w)throw Error(n(169));f?(a=Zm(a,c,Mo),w.__reactInternalMemoizedMergedChildContext=a,On(xr),On(Es),Yn(Es,a)):On(xr),Yn(xr,f)}var Lo=null,Uu=!1,sa=!1;function ir(a){Lo===null?Lo=[a]:Lo.push(a)}function Wu(a){Uu=!0,ir(a)}function Zi(){if(!sa&&Lo!==null){sa=!0;var a=0,c=Ln;try{var f=Lo;for(Ln=1;a<f.length;a++){var w=f[a];do w=w(!0);while(w!==null)}Lo=null,Uu=!1}catch(j){throw Lo!==null&&(Lo=Lo.slice(a+1)),Dn(Cs,Zi),j}finally{Ln=c,sa=!1}}return null}var $l=[],Cl=0,El=null,qu=0,br=[],Gr=0,Qi=null,eo=1,to="";function Da(a,c){$l[Cl++]=qu,$l[Cl++]=El,El=a,qu=c}function Tf(a,c,f){br[Gr++]=eo,br[Gr++]=to,br[Gr++]=Qi,Qi=a;var w=eo;a=to;var j=32-nr(w)-1;w&=~(1<<j),f+=1;var C=32-nr(c)+j;if(30<C){var q=j-j%5;C=(w&(1<<q)-1).toString(32),w>>=q,j-=q,eo=1<<32-nr(c)+j|f<<j|w,to=C+a}else eo=1<<C|f<<j|w,to=a}function Hu(a){a.return!==null&&(Da(a,1),Tf(a,1,0))}function Vu(a){for(;a===El;)El=$l[--Cl],$l[Cl]=null,qu=$l[--Cl],$l[Cl]=null;for(;a===Qi;)Qi=br[--Gr],br[Gr]=null,to=br[--Gr],br[Gr]=null,eo=br[--Gr],br[Gr]=null}var Kr=null,Ir=null,Xn=!1,Ti=null;function Qm(a,c){var f=Pe(5,null,null,0);f.elementType="DELETED",f.stateNode=c,f.return=a,c=a.deletions,c===null?(a.deletions=[f],a.flags|=16):c.push(f)}function e_(a,c){switch(a.tag){case 5:var f=a.type;return c=c.nodeType!==1||f.toLowerCase()!==c.nodeName.toLowerCase()?null:c,c!==null?(a.stateNode=c,Kr=a,Ir=ea(c.firstChild),!0):!1;case 6:return c=a.pendingProps===""||c.nodeType!==3?null:c,c!==null?(a.stateNode=c,Kr=a,Ir=null,!0):!1;case 13:return c=c.nodeType!==8?null:c,c!==null?(f=Qi!==null?{id:eo,overflow:to}:null,a.memoizedState={dehydrated:c,treeContext:f,retryLane:1073741824},f=Pe(18,null,null,0),f.stateNode=c,f.return=a,a.child=f,Kr=a,Ir=null,!0):!1;default:return!1}}function Mf(a){return(a.mode&1)!==0&&(a.flags&128)===0}function jc(a){if(Xn){var c=Ir;if(c){var f=c;if(!e_(a,c)){if(Mf(a))throw Error(n(418));c=ea(f.nextSibling);var w=Kr;c&&e_(a,c)?Qm(w,f):(a.flags=a.flags&-4097|2,Xn=!1,Kr=a)}}else{if(Mf(a))throw Error(n(418));a.flags=a.flags&-4097|2,Xn=!1,Kr=a}}}function t_(a){for(a=a.return;a!==null&&a.tag!==5&&a.tag!==3&&a.tag!==13;)a=a.return;Kr=a}function Al(a){if(a!==Kr)return!1;if(!Xn)return t_(a),Xn=!0,!1;var c;if((c=a.tag!==3)&&!(c=a.tag!==5)&&(c=a.type,c=c!=="head"&&c!=="body"&&!Du(a.type,a.memoizedProps)),c&&(c=Ir)){if(Mf(a))throw n_(),Error(n(418));for(;c;)Qm(a,c),c=ea(c.nextSibling)}if(t_(a),a.tag===13){if(a=a.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(n(317));e:{for(a=a.nextSibling,c=0;a;){if(a.nodeType===8){var f=a.data;if(f==="/$"){if(c===0){Ir=ea(a.nextSibling);break e}c--}else f!=="$"&&f!=="$!"&&f!=="$?"||c++}a=a.nextSibling}Ir=null}}else Ir=Kr?ea(a.stateNode.nextSibling):null;return!0}function n_(){for(var a=Ir;a;)a=ea(a.nextSibling)}function Fa(){Ir=Kr=null,Xn=!1}function Rf(a){Ti===null?Ti=[a]:Ti.push(a)}var Lf=S.ReactCurrentBatchConfig;function Ke(a,c,f){if(a=f.ref,a!==null&&typeof a!="function"&&typeof a!="object"){if(f._owner){if(f=f._owner,f){if(f.tag!==1)throw Error(n(309));var w=f.stateNode}if(!w)throw Error(n(147,a));var j=w,C=""+a;return c!==null&&c.ref!==null&&typeof c.ref=="function"&&c.ref._stringRef===C?c.ref:(c=function(q){var ie=j.refs;q===null?delete ie[C]:ie[C]=q},c._stringRef=C,c)}if(typeof a!="string")throw Error(n(284));if(!f._owner)throw Error(n(290,a))}return a}function Bn(a,c){throw a=Object.prototype.toString.call(c),Error(n(31,a==="[object Object]"?"object with keys {"+Object.keys(c).join(", ")+"}":a))}function li(a){var c=a._init;return c(a._payload)}function If(a){function c(ve,me){if(a){var Ne=ve.deletions;Ne===null?(ve.deletions=[me],ve.flags|=16):Ne.push(me)}}function f(ve,me){if(!a)return null;for(;me!==null;)c(ve,me),me=me.sibling;return null}function w(ve,me){for(ve=new Map;me!==null;)me.key!==null?ve.set(me.key,me):ve.set(me.index,me),me=me.sibling;return ve}function j(ve,me){return ve=lt(ve,me),ve.index=0,ve.sibling=null,ve}function C(ve,me,Ne){return ve.index=Ne,a?(Ne=ve.alternate,Ne!==null?(Ne=Ne.index,Ne<me?(ve.flags|=2,me):Ne):(ve.flags|=2,me)):(ve.flags|=1048576,me)}function q(ve){return a&&ve.alternate===null&&(ve.flags|=2),ve}function ie(ve,me,Ne,it){return me===null||me.tag!==6?(me=Qt(Ne,ve.mode,it),me.return=ve,me):(me=j(me,Ne),me.return=ve,me)}function ue(ve,me,Ne,it){var Rt=Ne.type;return Rt===R?Ze(ve,me,Ne.props.children,it,Ne.key):me!==null&&(me.elementType===Rt||typeof Rt=="object"&&Rt!==null&&Rt.$$typeof===L&&li(Rt)===me.type)?(it=j(me,Ne.props),it.ref=Ke(ve,me,Ne),it.return=ve,it):(it=vn(Ne.type,Ne.key,Ne.props,null,ve.mode,it),it.ref=Ke(ve,me,Ne),it.return=ve,it)}function Te(ve,me,Ne,it){return me===null||me.tag!==4||me.stateNode.containerInfo!==Ne.containerInfo||me.stateNode.implementation!==Ne.implementation?(me=Jn(Ne,ve.mode,it),me.return=ve,me):(me=j(me,Ne.children||[]),me.return=ve,me)}function Ze(ve,me,Ne,it,Rt){return me===null||me.tag!==7?(me=qt(Ne,ve.mode,it,Rt),me.return=ve,me):(me=j(me,Ne),me.return=ve,me)}function tt(ve,me,Ne){if(typeof me=="string"&&me!==""||typeof me=="number")return me=Qt(""+me,ve.mode,Ne),me.return=ve,me;if(typeof me=="object"&&me!==null){switch(me.$$typeof){case P:return Ne=vn(me.type,me.key,me.props,null,ve.mode,Ne),Ne.ref=Ke(ve,null,me),Ne.return=ve,Ne;case D:return me=Jn(me,ve.mode,Ne),me.return=ve,me;case L:var it=me._init;return tt(ve,it(me._payload),Ne)}if($e(me)||U(me))return me=qt(me,ve.mode,Ne,null),me.return=ve,me;Bn(ve,me)}return null}function Je(ve,me,Ne,it){var Rt=me!==null?me.key:null;if(typeof Ne=="string"&&Ne!==""||typeof Ne=="number")return Rt!==null?null:ie(ve,me,""+Ne,it);if(typeof Ne=="object"&&Ne!==null){switch(Ne.$$typeof){case P:return Ne.key===Rt?ue(ve,me,Ne,it):null;case D:return Ne.key===Rt?Te(ve,me,Ne,it):null;case L:return Rt=Ne._init,Je(ve,me,Rt(Ne._payload),it)}if($e(Ne)||U(Ne))return Rt!==null?null:Ze(ve,me,Ne,it,null);Bn(ve,Ne)}return null}function kt(ve,me,Ne,it,Rt){if(typeof it=="string"&&it!==""||typeof it=="number")return ve=ve.get(Ne)||null,ie(me,ve,""+it,Rt);if(typeof it=="object"&&it!==null){switch(it.$$typeof){case P:return ve=ve.get(it.key===null?Ne:it.key)||null,ue(me,ve,it,Rt);case D:return ve=ve.get(it.key===null?Ne:it.key)||null,Te(me,ve,it,Rt);case L:var Gt=it._init;return kt(ve,me,Ne,Gt(it._payload),Rt)}if($e(it)||U(it))return ve=ve.get(Ne)||null,Ze(me,ve,it,Rt,null);Bn(me,it)}return null}function $t(ve,me,Ne,it){for(var Rt=null,Gt=null,Kt=me,dn=me=0,dr=null;Kt!==null&&dn<Ne.length;dn++){Kt.index>dn?(dr=Kt,Kt=null):dr=Kt.sibling;var Un=Je(ve,Kt,Ne[dn],it);if(Un===null){Kt===null&&(Kt=dr);break}a&&Kt&&Un.alternate===null&&c(ve,Kt),me=C(Un,me,dn),Gt===null?Rt=Un:Gt.sibling=Un,Gt=Un,Kt=dr}if(dn===Ne.length)return f(ve,Kt),Xn&&Da(ve,dn),Rt;if(Kt===null){for(;dn<Ne.length;dn++)Kt=tt(ve,Ne[dn],it),Kt!==null&&(me=C(Kt,me,dn),Gt===null?Rt=Kt:Gt.sibling=Kt,Gt=Kt);return Xn&&Da(ve,dn),Rt}for(Kt=w(ve,Kt);dn<Ne.length;dn++)dr=kt(Kt,ve,dn,Ne[dn],it),dr!==null&&(a&&dr.alternate!==null&&Kt.delete(dr.key===null?dn:dr.key),me=C(dr,me,dn),Gt===null?Rt=dr:Gt.sibling=dr,Gt=dr);return a&&Kt.forEach(function(ql){return c(ve,ql)}),Xn&&Da(ve,dn),Rt}function At(ve,me,Ne,it){var Rt=U(Ne);if(typeof Rt!="function")throw Error(n(150));if(Ne=Rt.call(Ne),Ne==null)throw Error(n(151));for(var Gt=Rt=null,Kt=me,dn=me=0,dr=null,Un=Ne.next();Kt!==null&&!Un.done;dn++,Un=Ne.next()){Kt.index>dn?(dr=Kt,Kt=null):dr=Kt.sibling;var ql=Je(ve,Kt,Un.value,it);if(ql===null){Kt===null&&(Kt=dr);break}a&&Kt&&ql.alternate===null&&c(ve,Kt),me=C(ql,me,dn),Gt===null?Rt=ql:Gt.sibling=ql,Gt=ql,Kt=dr}if(Un.done)return f(ve,Kt),Xn&&Da(ve,dn),Rt;if(Kt===null){for(;!Un.done;dn++,Un=Ne.next())Un=tt(ve,Un.value,it),Un!==null&&(me=C(Un,me,dn),Gt===null?Rt=Un:Gt.sibling=Un,Gt=Un);return Xn&&Da(ve,dn),Rt}for(Kt=w(ve,Kt);!Un.done;dn++,Un=Ne.next())Un=kt(Kt,ve,dn,Un.value,it),Un!==null&&(a&&Un.alternate!==null&&Kt.delete(Un.key===null?dn:Un.key),me=C(Un,me,dn),Gt===null?Rt=Un:Gt.sibling=Un,Gt=Un);return a&&Kt.forEach(function(DC){return c(ve,DC)}),Xn&&Da(ve,dn),Rt}function Ls(ve,me,Ne,it){if(typeof Ne=="object"&&Ne!==null&&Ne.type===R&&Ne.key===null&&(Ne=Ne.props.children),typeof Ne=="object"&&Ne!==null){switch(Ne.$$typeof){case P:e:{for(var Rt=Ne.key,Gt=me;Gt!==null;){if(Gt.key===Rt){if(Rt=Ne.type,Rt===R){if(Gt.tag===7){f(ve,Gt.sibling),me=j(Gt,Ne.props.children),me.return=ve,ve=me;break e}}else if(Gt.elementType===Rt||typeof Rt=="object"&&Rt!==null&&Rt.$$typeof===L&&li(Rt)===Gt.type){f(ve,Gt.sibling),me=j(Gt,Ne.props),me.ref=Ke(ve,Gt,Ne),me.return=ve,ve=me;break e}f(ve,Gt);break}else c(ve,Gt);Gt=Gt.sibling}Ne.type===R?(me=qt(Ne.props.children,ve.mode,it,Ne.key),me.return=ve,ve=me):(it=vn(Ne.type,Ne.key,Ne.props,null,ve.mode,it),it.ref=Ke(ve,me,Ne),it.return=ve,ve=it)}return q(ve);case D:e:{for(Gt=Ne.key;me!==null;){if(me.key===Gt)if(me.tag===4&&me.stateNode.containerInfo===Ne.containerInfo&&me.stateNode.implementation===Ne.implementation){f(ve,me.sibling),me=j(me,Ne.children||[]),me.return=ve,ve=me;break e}else{f(ve,me);break}else c(ve,me);me=me.sibling}me=Jn(Ne,ve.mode,it),me.return=ve,ve=me}return q(ve);case L:return Gt=Ne._init,Ls(ve,me,Gt(Ne._payload),it)}if($e(Ne))return $t(ve,me,Ne,it);if(U(Ne))return At(ve,me,Ne,it);Bn(ve,Ne)}return typeof Ne=="string"&&Ne!==""||typeof Ne=="number"?(Ne=""+Ne,me!==null&&me.tag===6?(f(ve,me.sibling),me=j(me,Ne),me.return=ve,ve=me):(f(ve,me),me=Qt(Ne,ve.mode,it),me.return=ve,ve=me),q(ve)):f(ve,me)}return Ls}var Io=If(!0),Of=If(!1),Oo=na(null),Tl=null,Ml=null,Pf=null;function Df(){Pf=Ml=Tl=null}function Ff(a){var c=Oo.current;On(Oo),a._currentValue=c}function Gu(a,c,f){for(;a!==null;){var w=a.alternate;if((a.childLanes&c)!==c?(a.childLanes|=c,w!==null&&(w.childLanes|=c)):w!==null&&(w.childLanes&c)!==c&&(w.childLanes|=c),a===f)break;a=a.return}}function za(a,c){Tl=a,Pf=Ml=null,a=a.dependencies,a!==null&&a.firstContext!==null&&((a.lanes&c)!==0&&(Ns=!0),a.firstContext=null)}function ci(a){var c=a._currentValue;if(Pf!==a)if(a={context:a,memoizedValue:c,next:null},Ml===null){if(Tl===null)throw Error(n(308));Ml=a,Tl.dependencies={lanes:0,firstContext:a}}else Ml=Ml.next=a;return c}var no=null;function Ku(a){no===null?no=[a]:no.push(a)}function or(a,c,f,w){var j=c.interleaved;return j===null?(f.next=f,Ku(c)):(f.next=j.next,j.next=f),c.interleaved=f,un(a,w)}function un(a,c){a.lanes|=c;var f=a.alternate;for(f!==null&&(f.lanes|=c),f=a,a=a.return;a!==null;)a.childLanes|=c,f=a.alternate,f!==null&&(f.childLanes|=c),f=a,a=a.return;return f.tag===3?f.stateNode:null}var hs=!1;function Sc(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function zf(a,c){a=a.updateQueue,c.updateQueue===a&&(c.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function Jr(a,c){return{eventTime:a,lane:c,tag:0,payload:null,callback:null,next:null}}function Yr(a,c,f){var w=a.updateQueue;if(w===null)return null;if(w=w.shared,(An&2)!==0){var j=w.pending;return j===null?c.next=c:(c.next=j.next,j.next=c),w.pending=c,un(a,f)}return j=w.interleaved,j===null?(c.next=c,Ku(w)):(c.next=j.next,j.next=c),w.interleaved=c,un(a,f)}function rn(a,c,f){if(c=c.updateQueue,c!==null&&(c=c.shared,(f&4194240)!==0)){var w=c.lanes;w&=a.pendingLanes,f|=w,c.lanes=f,Bi(a,f)}}function s_(a,c){var f=a.updateQueue,w=a.alternate;if(w!==null&&(w=w.updateQueue,f===w)){var j=null,C=null;if(f=f.firstBaseUpdate,f!==null){do{var q={eventTime:f.eventTime,lane:f.lane,tag:f.tag,payload:f.payload,callback:f.callback,next:null};C===null?j=C=q:C=C.next=q,f=f.next}while(f!==null);C===null?j=C=c:C=C.next=c}else j=C=c;f={baseState:w.baseState,firstBaseUpdate:j,lastBaseUpdate:C,shared:w.shared,effects:w.effects},a.updateQueue=f;return}a=f.lastBaseUpdate,a===null?f.firstBaseUpdate=c:a.next=c,f.lastBaseUpdate=c}function Rl(a,c,f,w){var j=a.updateQueue;hs=!1;var C=j.firstBaseUpdate,q=j.lastBaseUpdate,ie=j.shared.pending;if(ie!==null){j.shared.pending=null;var ue=ie,Te=ue.next;ue.next=null,q===null?C=Te:q.next=Te,q=ue;var Ze=a.alternate;Ze!==null&&(Ze=Ze.updateQueue,ie=Ze.lastBaseUpdate,ie!==q&&(ie===null?Ze.firstBaseUpdate=Te:ie.next=Te,Ze.lastBaseUpdate=ue))}if(C!==null){var tt=j.baseState;q=0,Ze=Te=ue=null,ie=C;do{var Je=ie.lane,kt=ie.eventTime;if((w&Je)===Je){Ze!==null&&(Ze=Ze.next={eventTime:kt,lane:0,tag:ie.tag,payload:ie.payload,callback:ie.callback,next:null});e:{var $t=a,At=ie;switch(Je=c,kt=f,At.tag){case 1:if($t=At.payload,typeof $t=="function"){tt=$t.call(kt,tt,Je);break e}tt=$t;break e;case 3:$t.flags=$t.flags&-65537|128;case 0:if($t=At.payload,Je=typeof $t=="function"?$t.call(kt,tt,Je):$t,Je==null)break e;tt=te({},tt,Je);break e;case 2:hs=!0}}ie.callback!==null&&ie.lane!==0&&(a.flags|=64,Je=j.effects,Je===null?j.effects=[ie]:Je.push(ie))}else kt={eventTime:kt,lane:Je,tag:ie.tag,payload:ie.payload,callback:ie.callback,next:null},Ze===null?(Te=Ze=kt,ue=tt):Ze=Ze.next=kt,q|=Je;if(ie=ie.next,ie===null){if(ie=j.shared.pending,ie===null)break;Je=ie,ie=Je.next,Je.next=null,j.lastBaseUpdate=Je,j.shared.pending=null}}while(!0);if(Ze===null&&(ue=tt),j.baseState=ue,j.firstBaseUpdate=Te,j.lastBaseUpdate=Ze,c=j.shared.interleaved,c!==null){j=c;do q|=j.lane,j=j.next;while(j!==c)}else C===null&&(j.shared.lanes=0);la|=q,a.lanes=q,a.memoizedState=tt}}function r_(a,c,f){if(a=c.effects,c.effects=null,a!==null)for(c=0;c<a.length;c++){var w=a[c],j=w.callback;if(j!==null){if(w.callback=null,w=f,typeof j!="function")throw Error(n(191,j));j.call(w)}}}var Nc={},so=na(Nc),$c=na(Nc),Ba=na(Nc);function kr(a){if(a===Nc)throw Error(n(174));return a}function Ju(a,c){switch(Yn(Ba,c),Yn($c,a),Yn(so,Nc),a=c.nodeType,a){case 9:case 11:c=(c=c.documentElement)?c.namespaceURI:pe(null,"");break;default:a=a===8?c.parentNode:c,c=a.namespaceURI||null,a=a.tagName,c=pe(c,a)}On(so),Yn(so,c)}function ui(){On(so),On($c),On(Ba)}function di(a){kr(Ba.current);var c=kr(so.current),f=pe(c,a.type);c!==f&&(Yn($c,a),Yn(so,f))}function Ll(a){$c.current===a&&(On(so),On($c))}var ms=na(0);function Yu(a){for(var c=a;c!==null;){if(c.tag===13){var f=c.memoizedState;if(f!==null&&(f=f.dehydrated,f===null||f.data==="$?"||f.data==="$!"))return c}else if(c.tag===19&&c.memoizedProps.revealOrder!==void 0){if((c.flags&128)!==0)return c}else if(c.child!==null){c.child.return=c,c=c.child;continue}if(c===a)break;for(;c.sibling===null;){if(c.return===null||c.return===a)return null;c=c.return}c.sibling.return=c.return,c=c.sibling}return null}var Cc=[];function Xu(){for(var a=0;a<Cc.length;a++)Cc[a]._workInProgressVersionPrimary=null;Cc.length=0}var Il=S.ReactCurrentDispatcher,Bf=S.ReactCurrentBatchConfig,Zn=0,as=null,Ss=null,Pn=null,Ec=!1,Po=!1,Ua=0,ro=0;function Fs(){throw Error(n(321))}function Uf(a,c){if(c===null)return!1;for(var f=0;f<c.length&&f<a.length;f++)if(!yr(a[f],c[f]))return!1;return!0}function Wf(a,c,f,w,j,C){if(Zn=C,as=c,c.memoizedState=null,c.updateQueue=null,c.lanes=0,Il.current=a===null||a.memoizedState===null?Lc:Zg,a=f(w,j),Po){C=0;do{if(Po=!1,Ua=0,25<=C)throw Error(n(301));C+=1,Pn=Ss=null,c.updateQueue=null,Il.current=Yf,a=f(w,j)}while(Po)}if(Il.current=Pl,c=Ss!==null&&Ss.next!==null,Zn=0,Pn=Ss=as=null,Ec=!1,c)throw Error(n(300));return a}function qf(){var a=Ua!==0;return Ua=0,a}function fi(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Pn===null?as.memoizedState=Pn=a:Pn=Pn.next=a,Pn}function Or(){if(Ss===null){var a=as.alternate;a=a!==null?a.memoizedState:null}else a=Ss.next;var c=Pn===null?as.memoizedState:Pn.next;if(c!==null)Pn=c,Ss=a;else{if(a===null)throw Error(n(310));Ss=a,a={memoizedState:Ss.memoizedState,baseState:Ss.baseState,baseQueue:Ss.baseQueue,queue:Ss.queue,next:null},Pn===null?as.memoizedState=Pn=a:Pn=Pn.next=a}return Pn}function Ac(a,c){return typeof c=="function"?c(a):c}function Tc(a){var c=Or(),f=c.queue;if(f===null)throw Error(n(311));f.lastRenderedReducer=a;var w=Ss,j=w.baseQueue,C=f.pending;if(C!==null){if(j!==null){var q=j.next;j.next=C.next,C.next=q}w.baseQueue=j=C,f.pending=null}if(j!==null){C=j.next,w=w.baseState;var ie=q=null,ue=null,Te=C;do{var Ze=Te.lane;if((Zn&Ze)===Ze)ue!==null&&(ue=ue.next={lane:0,action:Te.action,hasEagerState:Te.hasEagerState,eagerState:Te.eagerState,next:null}),w=Te.hasEagerState?Te.eagerState:a(w,Te.action);else{var tt={lane:Ze,action:Te.action,hasEagerState:Te.hasEagerState,eagerState:Te.eagerState,next:null};ue===null?(ie=ue=tt,q=w):ue=ue.next=tt,as.lanes|=Ze,la|=Ze}Te=Te.next}while(Te!==null&&Te!==C);ue===null?q=w:ue.next=ie,yr(w,c.memoizedState)||(Ns=!0),c.memoizedState=w,c.baseState=q,c.baseQueue=ue,f.lastRenderedState=w}if(a=f.interleaved,a!==null){j=a;do C=j.lane,as.lanes|=C,la|=C,j=j.next;while(j!==a)}else j===null&&(f.lanes=0);return[c.memoizedState,f.dispatch]}function Hf(a){var c=Or(),f=c.queue;if(f===null)throw Error(n(311));f.lastRenderedReducer=a;var w=f.dispatch,j=f.pending,C=c.memoizedState;if(j!==null){f.pending=null;var q=j=j.next;do C=a(C,q.action),q=q.next;while(q!==j);yr(C,c.memoizedState)||(Ns=!0),c.memoizedState=C,c.baseQueue===null&&(c.baseState=C),f.lastRenderedState=C}return[C,w]}function ra(){}function i_(a,c){var f=as,w=Or(),j=c(),C=!yr(w.memoizedState,j);if(C&&(w.memoizedState=j,Ns=!0),w=w.queue,bn(Vf.bind(null,f,w,a),[a]),w.getSnapshot!==c||C||Pn!==null&&Pn.memoizedState.tag&1){if(f.flags|=2048,Ol(9,o_.bind(null,f,w,j,c),void 0,null),Rs===null)throw Error(n(349));(Zn&30)!==0||Mc(f,c,j)}return j}function Mc(a,c,f){a.flags|=16384,a={getSnapshot:c,value:f},c=as.updateQueue,c===null?(c={lastEffect:null,stores:null},as.updateQueue=c,c.stores=[a]):(f=c.stores,f===null?c.stores=[a]:f.push(a))}function o_(a,c,f,w){c.value=f,c.getSnapshot=w,io(c)&&a_(a)}function Vf(a,c,f){return f(function(){io(c)&&a_(a)})}function io(a){var c=a.getSnapshot;a=a.value;try{var f=c();return!yr(a,f)}catch{return!0}}function a_(a){var c=un(a,1);c!==null&&pi(c,a,1,-1)}function l_(a){var c=fi();return typeof a=="function"&&(a=a()),c.memoizedState=c.baseState=a,a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Ac,lastRenderedState:a},c.queue=a,a=a.dispatch=Xg.bind(null,as,a),[c.memoizedState,a]}function Ol(a,c,f,w){return a={tag:a,create:c,destroy:f,deps:w,next:null},c=as.updateQueue,c===null?(c={lastEffect:null,stores:null},as.updateQueue=c,c.lastEffect=a.next=a):(f=c.lastEffect,f===null?c.lastEffect=a.next=a:(w=f.next,f.next=a,a.next=w,c.lastEffect=a)),a}function c_(){return Or().memoizedState}function Zu(a,c,f,w){var j=fi();as.flags|=a,j.memoizedState=Ol(1|c,f,void 0,w===void 0?null:w)}function Qu(a,c,f,w){var j=Or();w=w===void 0?null:w;var C=void 0;if(Ss!==null){var q=Ss.memoizedState;if(C=q.destroy,w!==null&&Uf(w,q.deps)){j.memoizedState=Ol(c,f,C,w);return}}as.flags|=a,j.memoizedState=Ol(1|c,f,C,w)}function u_(a,c){return Zu(8390656,8,a,c)}function bn(a,c){return Qu(2048,8,a,c)}function zs(a,c){return Qu(4,2,a,c)}function ar(a,c){return Qu(4,4,a,c)}function ed(a,c){if(typeof c=="function")return a=a(),c(a),function(){c(null)};if(c!=null)return a=a(),c.current=a,function(){c.current=null}}function Rc(a,c,f){return f=f!=null?f.concat([a]):null,Qu(4,4,ed.bind(null,c,a),f)}function td(){}function d_(a,c){var f=Or();c=c===void 0?null:c;var w=f.memoizedState;return w!==null&&c!==null&&Uf(c,w[1])?w[0]:(f.memoizedState=[a,c],a)}function f_(a,c){var f=Or();c=c===void 0?null:c;var w=f.memoizedState;return w!==null&&c!==null&&Uf(c,w[1])?w[0]:(a=a(),f.memoizedState=[a,c],a)}function Gf(a,c,f){return(Zn&21)===0?(a.baseState&&(a.baseState=!1,Ns=!0),a.memoizedState=f):(yr(f,c)||(f=Ms(),as.lanes|=f,la|=f,a.baseState=!0),c)}function nd(a,c){var f=Ln;Ln=f!==0&&4>f?f:4,a(!0);var w=Bf.transition;Bf.transition={};try{a(!1),c()}finally{Ln=f,Bf.transition=w}}function h_(){return Or().memoizedState}function Yg(a,c,f){var w=Bo(a);if(f={lane:w,action:f,hasEagerState:!1,eagerState:null,next:null},Kf(a))Jf(c,f);else if(f=or(a,c,f,w),f!==null){var j=Nr();pi(f,a,w,j),Mi(f,c,w)}}function Xg(a,c,f){var w=Bo(a),j={lane:w,action:f,hasEagerState:!1,eagerState:null,next:null};if(Kf(a))Jf(c,j);else{var C=a.alternate;if(a.lanes===0&&(C===null||C.lanes===0)&&(C=c.lastRenderedReducer,C!==null))try{var q=c.lastRenderedState,ie=C(q,f);if(j.hasEagerState=!0,j.eagerState=ie,yr(ie,q)){var ue=c.interleaved;ue===null?(j.next=j,Ku(c)):(j.next=ue.next,ue.next=j),c.interleaved=j;return}}catch{}finally{}f=or(a,c,j,w),f!==null&&(j=Nr(),pi(f,a,w,j),Mi(f,c,w))}}function Kf(a){var c=a.alternate;return a===as||c!==null&&c===as}function Jf(a,c){Po=Ec=!0;var f=a.pending;f===null?c.next=c:(c.next=f.next,f.next=c),a.pending=c}function Mi(a,c,f){if((f&4194240)!==0){var w=c.lanes;w&=a.pendingLanes,f|=w,c.lanes=f,Bi(a,f)}}var Pl={readContext:ci,useCallback:Fs,useContext:Fs,useEffect:Fs,useImperativeHandle:Fs,useInsertionEffect:Fs,useLayoutEffect:Fs,useMemo:Fs,useReducer:Fs,useRef:Fs,useState:Fs,useDebugValue:Fs,useDeferredValue:Fs,useTransition:Fs,useMutableSource:Fs,useSyncExternalStore:Fs,useId:Fs,unstable_isNewReconciler:!1},Lc={readContext:ci,useCallback:function(a,c){return fi().memoizedState=[a,c===void 0?null:c],a},useContext:ci,useEffect:u_,useImperativeHandle:function(a,c,f){return f=f!=null?f.concat([a]):null,Zu(4194308,4,ed.bind(null,c,a),f)},useLayoutEffect:function(a,c){return Zu(4194308,4,a,c)},useInsertionEffect:function(a,c){return Zu(4,2,a,c)},useMemo:function(a,c){var f=fi();return c=c===void 0?null:c,a=a(),f.memoizedState=[a,c],a},useReducer:function(a,c,f){var w=fi();return c=f!==void 0?f(c):c,w.memoizedState=w.baseState=c,a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:c},w.queue=a,a=a.dispatch=Yg.bind(null,as,a),[w.memoizedState,a]},useRef:function(a){var c=fi();return a={current:a},c.memoizedState=a},useState:l_,useDebugValue:td,useDeferredValue:function(a){return fi().memoizedState=a},useTransition:function(){var a=l_(!1),c=a[0];return a=nd.bind(null,a[1]),fi().memoizedState=a,[c,a]},useMutableSource:function(){},useSyncExternalStore:function(a,c,f){var w=as,j=fi();if(Xn){if(f===void 0)throw Error(n(407));f=f()}else{if(f=c(),Rs===null)throw Error(n(349));(Zn&30)!==0||Mc(w,c,f)}j.memoizedState=f;var C={value:f,getSnapshot:c};return j.queue=C,u_(Vf.bind(null,w,C,a),[a]),w.flags|=2048,Ol(9,o_.bind(null,w,C,f,c),void 0,null),f},useId:function(){var a=fi(),c=Rs.identifierPrefix;if(Xn){var f=to,w=eo;f=(w&~(1<<32-nr(w)-1)).toString(32)+f,c=":"+c+"R"+f,f=Ua++,0<f&&(c+="H"+f.toString(32)),c+=":"}else f=ro++,c=":"+c+"r"+f.toString(32)+":";return a.memoizedState=c},unstable_isNewReconciler:!1},Zg={readContext:ci,useCallback:d_,useContext:ci,useEffect:bn,useImperativeHandle:Rc,useInsertionEffect:zs,useLayoutEffect:ar,useMemo:f_,useReducer:Tc,useRef:c_,useState:function(){return Tc(Ac)},useDebugValue:td,useDeferredValue:function(a){var c=Or();return Gf(c,Ss.memoizedState,a)},useTransition:function(){var a=Tc(Ac)[0],c=Or().memoizedState;return[a,c]},useMutableSource:ra,useSyncExternalStore:i_,useId:h_,unstable_isNewReconciler:!1},Yf={readContext:ci,useCallback:d_,useContext:ci,useEffect:bn,useImperativeHandle:Rc,useInsertionEffect:zs,useLayoutEffect:ar,useMemo:f_,useReducer:Hf,useRef:c_,useState:function(){return Hf(Ac)},useDebugValue:td,useDeferredValue:function(a){var c=Or();return Ss===null?c.memoizedState=a:Gf(c,Ss.memoizedState,a)},useTransition:function(){var a=Hf(Ac)[0],c=Or().memoizedState;return[a,c]},useMutableSource:ra,useSyncExternalStore:i_,useId:h_,unstable_isNewReconciler:!1};function hi(a,c){if(a&&a.defaultProps){c=te({},c),a=a.defaultProps;for(var f in a)c[f]===void 0&&(c[f]=a[f]);return c}return c}function Xf(a,c,f,w){c=a.memoizedState,f=f(w,c),f=f==null?c:te({},c,f),a.memoizedState=f,a.lanes===0&&(a.updateQueue.baseState=f)}var sd={isMounted:function(a){return(a=a._reactInternals)?sn(a)===a:!1},enqueueSetState:function(a,c,f){a=a._reactInternals;var w=Nr(),j=Bo(a),C=Jr(w,j);C.payload=c,f!=null&&(C.callback=f),c=Yr(a,C,j),c!==null&&(pi(c,a,j,w),rn(c,a,j))},enqueueReplaceState:function(a,c,f){a=a._reactInternals;var w=Nr(),j=Bo(a),C=Jr(w,j);C.tag=1,C.payload=c,f!=null&&(C.callback=f),c=Yr(a,C,j),c!==null&&(pi(c,a,j,w),rn(c,a,j))},enqueueForceUpdate:function(a,c){a=a._reactInternals;var f=Nr(),w=Bo(a),j=Jr(f,w);j.tag=2,c!=null&&(j.callback=c),c=Yr(a,j,w),c!==null&&(pi(c,a,w,f),rn(c,a,w))}};function m_(a,c,f,w,j,C,q){return a=a.stateNode,typeof a.shouldComponentUpdate=="function"?a.shouldComponentUpdate(w,C,q):c.prototype&&c.prototype.isPureReactComponent?!Gi(f,w)||!Gi(j,C):!0}function __(a,c,f){var w=!1,j=ai,C=c.contextType;return typeof C=="object"&&C!==null?C=ci(C):(j=rr(c)?Mo:Es.current,w=c.contextTypes,C=(w=w!=null)?Xi(a,j):ai),c=new c(f,C),a.memoizedState=c.state!==null&&c.state!==void 0?c.state:null,c.updater=sd,a.stateNode=c,c._reactInternals=a,w&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=j,a.__reactInternalMemoizedMaskedChildContext=C),c}function p_(a,c,f,w){a=c.state,typeof c.componentWillReceiveProps=="function"&&c.componentWillReceiveProps(f,w),typeof c.UNSAFE_componentWillReceiveProps=="function"&&c.UNSAFE_componentWillReceiveProps(f,w),c.state!==a&&sd.enqueueReplaceState(c,c.state,null)}function Zf(a,c,f,w){var j=a.stateNode;j.props=f,j.state=a.memoizedState,j.refs={},Sc(a);var C=c.contextType;typeof C=="object"&&C!==null?j.context=ci(C):(C=rr(c)?Mo:Es.current,j.context=Xi(a,C)),j.state=a.memoizedState,C=c.getDerivedStateFromProps,typeof C=="function"&&(Xf(a,c,C,f),j.state=a.memoizedState),typeof c.getDerivedStateFromProps=="function"||typeof j.getSnapshotBeforeUpdate=="function"||typeof j.UNSAFE_componentWillMount!="function"&&typeof j.componentWillMount!="function"||(c=j.state,typeof j.componentWillMount=="function"&&j.componentWillMount(),typeof j.UNSAFE_componentWillMount=="function"&&j.UNSAFE_componentWillMount(),c!==j.state&&sd.enqueueReplaceState(j,j.state,null),Rl(a,f,j,w),j.state=a.memoizedState),typeof j.componentDidMount=="function"&&(a.flags|=4194308)}function Wa(a,c){try{var f="",w=c;do f+=be(w),w=w.return;while(w);var j=f}catch(C){j=`
39
+ Error generating stack: `+C.message+`
40
+ `+C.stack}return{value:a,source:c,stack:j,digest:null}}function Ic(a,c,f){return{value:a,source:null,stack:f??null,digest:c??null}}function Qf(a,c){try{console.error(c.value)}catch(f){setTimeout(function(){throw f})}}var Qg=typeof WeakMap=="function"?WeakMap:Map;function Oc(a,c,f){f=Jr(-1,f),f.tag=3,f.payload={element:null};var w=c.value;return f.callback=function(){Hc||(Hc=!0,oh=w),Qf(a,c)},f}function g_(a,c,f){f=Jr(-1,f),f.tag=3;var w=a.type.getDerivedStateFromError;if(typeof w=="function"){var j=c.value;f.payload=function(){return w(j)},f.callback=function(){Qf(a,c)}}var C=a.stateNode;return C!==null&&typeof C.componentDidCatch=="function"&&(f.callback=function(){Qf(a,c),typeof w!="function"&&(_i===null?_i=new Set([this]):_i.add(this));var q=c.stack;this.componentDidCatch(c.value,{componentStack:q!==null?q:""})}),f}function ia(a,c,f){var w=a.pingCache;if(w===null){w=a.pingCache=new Qg;var j=new Set;w.set(c,j)}else j=w.get(c),j===void 0&&(j=new Set,w.set(c,j));j.has(f)||(j.add(f),a=X.bind(null,a,c,f),c.then(a,a))}function lr(a){do{var c;if((c=a.tag===13)&&(c=a.memoizedState,c=c!==null?c.dehydrated!==null:!0),c)return a;a=a.return}while(a!==null);return null}function Bs(a,c,f,w,j){return(a.mode&1)===0?(a===c?a.flags|=65536:(a.flags|=128,f.flags|=131072,f.flags&=-52805,f.tag===1&&(f.alternate===null?f.tag=17:(c=Jr(-1,1),c.tag=2,Yr(f,c,1))),f.lanes|=1),a):(a.flags|=65536,a.lanes=j,a)}var oo=S.ReactCurrentOwner,Ns=!1;function ws(a,c,f,w){c.child=a===null?Of(c,null,f,w):Io(c,a.child,f,w)}function mi(a,c,f,w,j){f=f.render;var C=c.ref;return za(c,j),w=Wf(a,c,f,w,C,j),f=qf(),a!==null&&!Ns?(c.updateQueue=a.updateQueue,c.flags&=-2053,a.lanes&=~j,Fo(a,c,j)):(Xn&&f&&Hu(c),c.flags|=1,ws(a,c,w,j),c.child)}function y_(a,c,f,w,j){if(a===null){var C=f.type;return typeof C=="function"&&!st(C)&&C.defaultProps===void 0&&f.compare===null&&f.defaultProps===void 0?(c.tag=15,c.type=C,Pc(a,c,C,w,j)):(a=vn(f.type,null,w,c,c.mode,j),a.ref=c.ref,a.return=c,c.child=a)}if(C=a.child,(a.lanes&j)===0){var q=C.memoizedProps;if(f=f.compare,f=f!==null?f:Gi,f(q,w)&&a.ref===c.ref)return Fo(a,c,j)}return c.flags|=1,a=lt(C,w),a.ref=c.ref,a.return=c,c.child=a}function Pc(a,c,f,w,j){if(a!==null){var C=a.memoizedProps;if(Gi(C,w)&&a.ref===c.ref)if(Ns=!1,c.pendingProps=w=C,(a.lanes&j)!==0)(a.flags&131072)!==0&&(Ns=!0);else return c.lanes=a.lanes,Fo(a,c,j)}return eh(a,c,f,w,j)}function w_(a,c,f){var w=c.pendingProps,j=w.children,C=a!==null?a.memoizedState:null;if(w.mode==="hidden")if((c.mode&1)===0)c.memoizedState={baseLanes:0,cachePool:null,transitions:null},Yn(co,Sr),Sr|=f;else{if((f&1073741824)===0)return a=C!==null?C.baseLanes|f:f,c.lanes=c.childLanes=1073741824,c.memoizedState={baseLanes:a,cachePool:null,transitions:null},c.updateQueue=null,Yn(co,Sr),Sr|=a,null;c.memoizedState={baseLanes:0,cachePool:null,transitions:null},w=C!==null?C.baseLanes:f,Yn(co,Sr),Sr|=w}else C!==null?(w=C.baseLanes|f,c.memoizedState=null):w=f,Yn(co,Sr),Sr|=w;return ws(a,c,j,f),c.child}function rd(a,c){var f=c.ref;(a===null&&f!==null||a!==null&&a.ref!==f)&&(c.flags|=512,c.flags|=2097152)}function eh(a,c,f,w,j){var C=rr(f)?Mo:Es.current;return C=Xi(c,C),za(c,j),f=Wf(a,c,f,w,C,j),w=qf(),a!==null&&!Ns?(c.updateQueue=a.updateQueue,c.flags&=-2053,a.lanes&=~j,Fo(a,c,j)):(Xn&&w&&Hu(c),c.flags|=1,ws(a,c,f,j),c.child)}function v_(a,c,f,w,j){if(rr(f)){var C=!0;Nl(c)}else C=!1;if(za(c,j),c.stateNode===null)Fl(a,c),__(c,f,w),Zf(c,f,w,j),w=!0;else if(a===null){var q=c.stateNode,ie=c.memoizedProps;q.props=ie;var ue=q.context,Te=f.contextType;typeof Te=="object"&&Te!==null?Te=ci(Te):(Te=rr(f)?Mo:Es.current,Te=Xi(c,Te));var Ze=f.getDerivedStateFromProps,tt=typeof Ze=="function"||typeof q.getSnapshotBeforeUpdate=="function";tt||typeof q.UNSAFE_componentWillReceiveProps!="function"&&typeof q.componentWillReceiveProps!="function"||(ie!==w||ue!==Te)&&p_(c,q,w,Te),hs=!1;var Je=c.memoizedState;q.state=Je,Rl(c,w,q,j),ue=c.memoizedState,ie!==w||Je!==ue||xr.current||hs?(typeof Ze=="function"&&(Xf(c,f,Ze,w),ue=c.memoizedState),(ie=hs||m_(c,f,ie,w,Je,ue,Te))?(tt||typeof q.UNSAFE_componentWillMount!="function"&&typeof q.componentWillMount!="function"||(typeof q.componentWillMount=="function"&&q.componentWillMount(),typeof q.UNSAFE_componentWillMount=="function"&&q.UNSAFE_componentWillMount()),typeof q.componentDidMount=="function"&&(c.flags|=4194308)):(typeof q.componentDidMount=="function"&&(c.flags|=4194308),c.memoizedProps=w,c.memoizedState=ue),q.props=w,q.state=ue,q.context=Te,w=ie):(typeof q.componentDidMount=="function"&&(c.flags|=4194308),w=!1)}else{q=c.stateNode,zf(a,c),ie=c.memoizedProps,Te=c.type===c.elementType?ie:hi(c.type,ie),q.props=Te,tt=c.pendingProps,Je=q.context,ue=f.contextType,typeof ue=="object"&&ue!==null?ue=ci(ue):(ue=rr(f)?Mo:Es.current,ue=Xi(c,ue));var kt=f.getDerivedStateFromProps;(Ze=typeof kt=="function"||typeof q.getSnapshotBeforeUpdate=="function")||typeof q.UNSAFE_componentWillReceiveProps!="function"&&typeof q.componentWillReceiveProps!="function"||(ie!==tt||Je!==ue)&&p_(c,q,w,ue),hs=!1,Je=c.memoizedState,q.state=Je,Rl(c,w,q,j);var $t=c.memoizedState;ie!==tt||Je!==$t||xr.current||hs?(typeof kt=="function"&&(Xf(c,f,kt,w),$t=c.memoizedState),(Te=hs||m_(c,f,Te,w,Je,$t,ue)||!1)?(Ze||typeof q.UNSAFE_componentWillUpdate!="function"&&typeof q.componentWillUpdate!="function"||(typeof q.componentWillUpdate=="function"&&q.componentWillUpdate(w,$t,ue),typeof q.UNSAFE_componentWillUpdate=="function"&&q.UNSAFE_componentWillUpdate(w,$t,ue)),typeof q.componentDidUpdate=="function"&&(c.flags|=4),typeof q.getSnapshotBeforeUpdate=="function"&&(c.flags|=1024)):(typeof q.componentDidUpdate!="function"||ie===a.memoizedProps&&Je===a.memoizedState||(c.flags|=4),typeof q.getSnapshotBeforeUpdate!="function"||ie===a.memoizedProps&&Je===a.memoizedState||(c.flags|=1024),c.memoizedProps=w,c.memoizedState=$t),q.props=w,q.state=$t,q.context=ue,w=Te):(typeof q.componentDidUpdate!="function"||ie===a.memoizedProps&&Je===a.memoizedState||(c.flags|=4),typeof q.getSnapshotBeforeUpdate!="function"||ie===a.memoizedProps&&Je===a.memoizedState||(c.flags|=1024),w=!1)}return id(a,c,f,w,C,j)}function id(a,c,f,w,j,C){rd(a,c);var q=(c.flags&128)!==0;if(!w&&!q)return j&&Bu(c,f,!1),Fo(a,c,C);w=c.stateNode,oo.current=c;var ie=q&&typeof f.getDerivedStateFromError!="function"?null:w.render();return c.flags|=1,a!==null&&q?(c.child=Io(c,a.child,null,C),c.child=Io(c,null,ie,C)):ws(a,c,ie,C),c.memoizedState=w.state,j&&Bu(c,f,!0),c.child}function oa(a){var c=a.stateNode;c.pendingContext?zu(a,c.pendingContext,c.pendingContext!==c.context):c.context&&zu(a,c.context,!1),Ju(a,c.containerInfo)}function Dl(a,c,f,w,j){return Fa(),Rf(j),c.flags|=256,ws(a,c,f,w),c.child}var od={dehydrated:null,treeContext:null,retryLane:0};function ad(a){return{baseLanes:a,cachePool:null,transitions:null}}function x_(a,c,f){var w=c.pendingProps,j=ms.current,C=!1,q=(c.flags&128)!==0,ie;if((ie=q)||(ie=a!==null&&a.memoizedState===null?!1:(j&2)!==0),ie?(C=!0,c.flags&=-129):(a===null||a.memoizedState!==null)&&(j|=1),Yn(ms,j&1),a===null)return jc(c),a=c.memoizedState,a!==null&&(a=a.dehydrated,a!==null)?((c.mode&1)===0?c.lanes=1:a.data==="$!"?c.lanes=8:c.lanes=1073741824,null):(q=w.children,a=w.fallback,C?(w=c.mode,C=c.child,q={mode:"hidden",children:q},(w&1)===0&&C!==null?(C.childLanes=0,C.pendingProps=q):C=ft(q,w,0,null),a=qt(a,w,f,null),C.return=c,a.return=c,C.sibling=a,c.child=C,c.child.memoizedState=ad(f),c.memoizedState=od,a):ld(c,q));if(j=a.memoizedState,j!==null&&(ie=j.dehydrated,ie!==null))return ey(a,c,q,w,ie,j,f);if(C){C=w.fallback,q=c.mode,j=a.child,ie=j.sibling;var ue={mode:"hidden",children:w.children};return(q&1)===0&&c.child!==j?(w=c.child,w.childLanes=0,w.pendingProps=ue,c.deletions=null):(w=lt(j,ue),w.subtreeFlags=j.subtreeFlags&14680064),ie!==null?C=lt(ie,C):(C=qt(C,q,f,null),C.flags|=2),C.return=c,w.return=c,w.sibling=C,c.child=w,w=C,C=c.child,q=a.child.memoizedState,q=q===null?ad(f):{baseLanes:q.baseLanes|f,cachePool:null,transitions:q.transitions},C.memoizedState=q,C.childLanes=a.childLanes&~f,c.memoizedState=od,w}return C=a.child,a=C.sibling,w=lt(C,{mode:"visible",children:w.children}),(c.mode&1)===0&&(w.lanes=f),w.return=c,w.sibling=null,a!==null&&(f=c.deletions,f===null?(c.deletions=[a],c.flags|=16):f.push(a)),c.child=w,c.memoizedState=null,w}function ld(a,c){return c=ft({mode:"visible",children:c},a.mode,0,null),c.return=a,a.child=c}function Do(a,c,f,w){return w!==null&&Rf(w),Io(c,a.child,null,f),a=ld(c,c.pendingProps.children),a.flags|=2,c.memoizedState=null,a}function ey(a,c,f,w,j,C,q){if(f)return c.flags&256?(c.flags&=-257,w=Ic(Error(n(422))),Do(a,c,q,w)):c.memoizedState!==null?(c.child=a.child,c.flags|=128,null):(C=w.fallback,j=c.mode,w=ft({mode:"visible",children:w.children},j,0,null),C=qt(C,j,q,null),C.flags|=2,w.return=c,C.return=c,w.sibling=C,c.child=w,(c.mode&1)!==0&&Io(c,a.child,null,q),c.child.memoizedState=ad(q),c.memoizedState=od,C);if((c.mode&1)===0)return Do(a,c,q,null);if(j.data==="$!"){if(w=j.nextSibling&&j.nextSibling.dataset,w)var ie=w.dgst;return w=ie,C=Error(n(419)),w=Ic(C,w,void 0),Do(a,c,q,w)}if(ie=(q&a.childLanes)!==0,Ns||ie){if(w=Rs,w!==null){switch(q&-q){case 4:j=2;break;case 16:j=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:j=32;break;case 536870912:j=268435456;break;default:j=0}j=(j&(w.suspendedLanes|q))!==0?0:j,j!==0&&j!==C.retryLane&&(C.retryLane=j,un(a,j),pi(w,a,j,-1))}return _d(),w=Ic(Error(n(421))),Do(a,c,q,w)}return j.data==="$?"?(c.flags|=128,c.child=a.child,c=oe.bind(null,a),j._reactRetry=c,null):(a=C.treeContext,Ir=ea(j.nextSibling),Kr=c,Xn=!0,Ti=null,a!==null&&(br[Gr++]=eo,br[Gr++]=to,br[Gr++]=Qi,eo=a.id,to=a.overflow,Qi=c),c=ld(c,w.children),c.flags|=4096,c)}function Dc(a,c,f){a.lanes|=c;var w=a.alternate;w!==null&&(w.lanes|=c),Gu(a.return,c,f)}function cd(a,c,f,w,j){var C=a.memoizedState;C===null?a.memoizedState={isBackwards:c,rendering:null,renderingStartTime:0,last:w,tail:f,tailMode:j}:(C.isBackwards=c,C.rendering=null,C.renderingStartTime=0,C.last=w,C.tail=f,C.tailMode=j)}function b_(a,c,f){var w=c.pendingProps,j=w.revealOrder,C=w.tail;if(ws(a,c,w.children,f),w=ms.current,(w&2)!==0)w=w&1|2,c.flags|=128;else{if(a!==null&&(a.flags&128)!==0)e:for(a=c.child;a!==null;){if(a.tag===13)a.memoizedState!==null&&Dc(a,f,c);else if(a.tag===19)Dc(a,f,c);else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===c)break e;for(;a.sibling===null;){if(a.return===null||a.return===c)break e;a=a.return}a.sibling.return=a.return,a=a.sibling}w&=1}if(Yn(ms,w),(c.mode&1)===0)c.memoizedState=null;else switch(j){case"forwards":for(f=c.child,j=null;f!==null;)a=f.alternate,a!==null&&Yu(a)===null&&(j=f),f=f.sibling;f=j,f===null?(j=c.child,c.child=null):(j=f.sibling,f.sibling=null),cd(c,!1,j,f,C);break;case"backwards":for(f=null,j=c.child,c.child=null;j!==null;){if(a=j.alternate,a!==null&&Yu(a)===null){c.child=j;break}a=j.sibling,j.sibling=f,f=j,j=a}cd(c,!0,f,null,C);break;case"together":cd(c,!1,null,null,void 0);break;default:c.memoizedState=null}return c.child}function Fl(a,c){(c.mode&1)===0&&a!==null&&(a.alternate=null,c.alternate=null,c.flags|=2)}function Fo(a,c,f){if(a!==null&&(c.dependencies=a.dependencies),la|=c.lanes,(f&c.childLanes)===0)return null;if(a!==null&&c.child!==a.child)throw Error(n(153));if(c.child!==null){for(a=c.child,f=lt(a,a.pendingProps),c.child=f,f.return=c;a.sibling!==null;)a=a.sibling,f=f.sibling=lt(a,a.pendingProps),f.return=c;f.sibling=null}return c.child}function ty(a,c,f){switch(c.tag){case 3:oa(c),Fa();break;case 5:di(c);break;case 1:rr(c.type)&&Nl(c);break;case 4:Ju(c,c.stateNode.containerInfo);break;case 10:var w=c.type._context,j=c.memoizedProps.value;Yn(Oo,w._currentValue),w._currentValue=j;break;case 13:if(w=c.memoizedState,w!==null)return w.dehydrated!==null?(Yn(ms,ms.current&1),c.flags|=128,null):(f&c.child.childLanes)!==0?x_(a,c,f):(Yn(ms,ms.current&1),a=Fo(a,c,f),a!==null?a.sibling:null);Yn(ms,ms.current&1);break;case 19:if(w=(f&c.childLanes)!==0,(a.flags&128)!==0){if(w)return b_(a,c,f);c.flags|=128}if(j=c.memoizedState,j!==null&&(j.rendering=null,j.tail=null,j.lastEffect=null),Yn(ms,ms.current),w)break;return null;case 22:case 23:return c.lanes=0,w_(a,c,f)}return Fo(a,c,f)}var k_,jr,qa,j_;k_=function(a,c){for(var f=c.child;f!==null;){if(f.tag===5||f.tag===6)a.appendChild(f.stateNode);else if(f.tag!==4&&f.child!==null){f.child.return=f,f=f.child;continue}if(f===c)break;for(;f.sibling===null;){if(f.return===null||f.return===c)return;f=f.return}f.sibling.return=f.return,f=f.sibling}},jr=function(){},qa=function(a,c,f,w){var j=a.memoizedProps;if(j!==w){a=c.stateNode,kr(so.current);var C=null;switch(f){case"input":j=rt(a,j),w=rt(a,w),C=[];break;case"select":j=te({},j,{value:void 0}),w=te({},w,{value:void 0}),C=[];break;case"textarea":j=ce(a,j),w=ce(a,w),C=[];break;default:typeof j.onClick!="function"&&typeof w.onClick=="function"&&(a.onclick=kc)}Mt(f,w);var q;f=null;for(Te in j)if(!w.hasOwnProperty(Te)&&j.hasOwnProperty(Te)&&j[Te]!=null)if(Te==="style"){var ie=j[Te];for(q in ie)ie.hasOwnProperty(q)&&(f||(f={}),f[q]="")}else Te!=="dangerouslySetInnerHTML"&&Te!=="children"&&Te!=="suppressContentEditableWarning"&&Te!=="suppressHydrationWarning"&&Te!=="autoFocus"&&(i.hasOwnProperty(Te)?C||(C=[]):(C=C||[]).push(Te,null));for(Te in w){var ue=w[Te];if(ie=j!=null?j[Te]:void 0,w.hasOwnProperty(Te)&&ue!==ie&&(ue!=null||ie!=null))if(Te==="style")if(ie){for(q in ie)!ie.hasOwnProperty(q)||ue&&ue.hasOwnProperty(q)||(f||(f={}),f[q]="");for(q in ue)ue.hasOwnProperty(q)&&ie[q]!==ue[q]&&(f||(f={}),f[q]=ue[q])}else f||(C||(C=[]),C.push(Te,f)),f=ue;else Te==="dangerouslySetInnerHTML"?(ue=ue?ue.__html:void 0,ie=ie?ie.__html:void 0,ue!=null&&ie!==ue&&(C=C||[]).push(Te,ue)):Te==="children"?typeof ue!="string"&&typeof ue!="number"||(C=C||[]).push(Te,""+ue):Te!=="suppressContentEditableWarning"&&Te!=="suppressHydrationWarning"&&(i.hasOwnProperty(Te)?(ue!=null&&Te==="onScroll"&&zn("scroll",a),C||ie===ue||(C=[])):(C=C||[]).push(Te,ue))}f&&(C=C||[]).push("style",f);var Te=C;(c.updateQueue=Te)&&(c.flags|=4)}},j_=function(a,c,f,w){f!==w&&(c.flags|=4)};function zl(a,c){if(!Xn)switch(a.tailMode){case"hidden":c=a.tail;for(var f=null;c!==null;)c.alternate!==null&&(f=c),c=c.sibling;f===null?a.tail=null:f.sibling=null;break;case"collapsed":f=a.tail;for(var w=null;f!==null;)f.alternate!==null&&(w=f),f=f.sibling;w===null?c||a.tail===null?a.tail=null:a.tail.sibling=null:w.sibling=null}}function Kn(a){var c=a.alternate!==null&&a.alternate.child===a.child,f=0,w=0;if(c)for(var j=a.child;j!==null;)f|=j.lanes|j.childLanes,w|=j.subtreeFlags&14680064,w|=j.flags&14680064,j.return=a,j=j.sibling;else for(j=a.child;j!==null;)f|=j.lanes|j.childLanes,w|=j.subtreeFlags,w|=j.flags,j.return=a,j=j.sibling;return a.subtreeFlags|=w,a.childLanes=f,c}function th(a,c,f){var w=c.pendingProps;switch(Vu(c),c.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Kn(c),null;case 1:return rr(c.type)&&Ro(),Kn(c),null;case 3:return w=c.stateNode,ui(),On(xr),On(Es),Xu(),w.pendingContext&&(w.context=w.pendingContext,w.pendingContext=null),(a===null||a.child===null)&&(Al(c)?c.flags|=4:a===null||a.memoizedState.isDehydrated&&(c.flags&256)===0||(c.flags|=1024,Ti!==null&&(ah(Ti),Ti=null))),jr(a,c),Kn(c),null;case 5:Ll(c);var j=kr(Ba.current);if(f=c.type,a!==null&&c.stateNode!=null)qa(a,c,f,w,j),a.ref!==c.ref&&(c.flags|=512,c.flags|=2097152);else{if(!w){if(c.stateNode===null)throw Error(n(166));return Kn(c),null}if(a=kr(so.current),Al(c)){w=c.stateNode,f=c.type;var C=c.memoizedProps;switch(w[Yi]=c,w[Eo]=C,a=(c.mode&1)!==0,f){case"dialog":zn("cancel",w),zn("close",w);break;case"iframe":case"object":case"embed":zn("load",w);break;case"video":case"audio":for(j=0;j<$o.length;j++)zn($o[j],w);break;case"source":zn("error",w);break;case"img":case"image":case"link":zn("error",w),zn("load",w);break;case"details":zn("toggle",w);break;case"input":ze(w,C),zn("invalid",w);break;case"select":w._wrapperState={wasMultiple:!!C.multiple},zn("invalid",w);break;case"textarea":Q(w,C),zn("invalid",w)}Mt(f,C),j=null;for(var q in C)if(C.hasOwnProperty(q)){var ie=C[q];q==="children"?typeof ie=="string"?w.textContent!==ie&&(C.suppressHydrationWarning!==!0&&bc(w.textContent,ie,a),j=["children",ie]):typeof ie=="number"&&w.textContent!==""+ie&&(C.suppressHydrationWarning!==!0&&bc(w.textContent,ie,a),j=["children",""+ie]):i.hasOwnProperty(q)&&ie!=null&&q==="onScroll"&&zn("scroll",w)}switch(f){case"input":He(w),Qe(w,C,!0);break;case"textarea":He(w),le(w);break;case"select":case"option":break;default:typeof C.onClick=="function"&&(w.onclick=kc)}w=j,c.updateQueue=w,w!==null&&(c.flags|=4)}else{q=j.nodeType===9?j:j.ownerDocument,a==="http://www.w3.org/1999/xhtml"&&(a=Se(f)),a==="http://www.w3.org/1999/xhtml"?f==="script"?(a=q.createElement("div"),a.innerHTML="<script><\/script>",a=a.removeChild(a.firstChild)):typeof w.is=="string"?a=q.createElement(f,{is:w.is}):(a=q.createElement(f),f==="select"&&(q=a,w.multiple?q.multiple=!0:w.size&&(q.size=w.size))):a=q.createElementNS(a,f),a[Yi]=c,a[Eo]=w,k_(a,c,!1,!1),c.stateNode=a;e:{switch(q=mn(f,w),f){case"dialog":zn("cancel",a),zn("close",a),j=w;break;case"iframe":case"object":case"embed":zn("load",a),j=w;break;case"video":case"audio":for(j=0;j<$o.length;j++)zn($o[j],a);j=w;break;case"source":zn("error",a),j=w;break;case"img":case"image":case"link":zn("error",a),zn("load",a),j=w;break;case"details":zn("toggle",a),j=w;break;case"input":ze(a,w),j=rt(a,w),zn("invalid",a);break;case"option":j=w;break;case"select":a._wrapperState={wasMultiple:!!w.multiple},j=te({},w,{value:void 0}),zn("invalid",a);break;case"textarea":Q(a,w),j=ce(a,w),zn("invalid",a);break;default:j=w}Mt(f,j),ie=j;for(C in ie)if(ie.hasOwnProperty(C)){var ue=ie[C];C==="style"?ut(a,ue):C==="dangerouslySetInnerHTML"?(ue=ue?ue.__html:void 0,ue!=null&&yt(a,ue)):C==="children"?typeof ue=="string"?(f!=="textarea"||ue!=="")&&_t(a,ue):typeof ue=="number"&&_t(a,""+ue):C!=="suppressContentEditableWarning"&&C!=="suppressHydrationWarning"&&C!=="autoFocus"&&(i.hasOwnProperty(C)?ue!=null&&C==="onScroll"&&zn("scroll",a):ue!=null&&E(a,C,ue,q))}switch(f){case"input":He(a),Qe(a,w,!1);break;case"textarea":He(a),le(a);break;case"option":w.value!=null&&a.setAttribute("value",""+ae(w.value));break;case"select":a.multiple=!!w.multiple,C=w.value,C!=null?Le(a,!!w.multiple,C,!1):w.defaultValue!=null&&Le(a,!!w.multiple,w.defaultValue,!0);break;default:typeof j.onClick=="function"&&(a.onclick=kc)}switch(f){case"button":case"input":case"select":case"textarea":w=!!w.autoFocus;break e;case"img":w=!0;break e;default:w=!1}}w&&(c.flags|=4)}c.ref!==null&&(c.flags|=512,c.flags|=2097152)}return Kn(c),null;case 6:if(a&&c.stateNode!=null)j_(a,c,a.memoizedProps,w);else{if(typeof w!="string"&&c.stateNode===null)throw Error(n(166));if(f=kr(Ba.current),kr(so.current),Al(c)){if(w=c.stateNode,f=c.memoizedProps,w[Yi]=c,(C=w.nodeValue!==f)&&(a=Kr,a!==null))switch(a.tag){case 3:bc(w.nodeValue,f,(a.mode&1)!==0);break;case 5:a.memoizedProps.suppressHydrationWarning!==!0&&bc(w.nodeValue,f,(a.mode&1)!==0)}C&&(c.flags|=4)}else w=(f.nodeType===9?f:f.ownerDocument).createTextNode(w),w[Yi]=c,c.stateNode=w}return Kn(c),null;case 13:if(On(ms),w=c.memoizedState,a===null||a.memoizedState!==null&&a.memoizedState.dehydrated!==null){if(Xn&&Ir!==null&&(c.mode&1)!==0&&(c.flags&128)===0)n_(),Fa(),c.flags|=98560,C=!1;else if(C=Al(c),w!==null&&w.dehydrated!==null){if(a===null){if(!C)throw Error(n(318));if(C=c.memoizedState,C=C!==null?C.dehydrated:null,!C)throw Error(n(317));C[Yi]=c}else Fa(),(c.flags&128)===0&&(c.memoizedState=null),c.flags|=4;Kn(c),C=!1}else Ti!==null&&(ah(Ti),Ti=null),C=!0;if(!C)return c.flags&65536?c:null}return(c.flags&128)!==0?(c.lanes=f,c):(w=w!==null,w!==(a!==null&&a.memoizedState!==null)&&w&&(c.child.flags|=8192,(c.mode&1)!==0&&(a===null||(ms.current&1)!==0?ps===0&&(ps=3):_d())),c.updateQueue!==null&&(c.flags|=4),Kn(c),null);case 4:return ui(),jr(a,c),a===null&&Ci(c.stateNode.containerInfo),Kn(c),null;case 10:return Ff(c.type._context),Kn(c),null;case 17:return rr(c.type)&&Ro(),Kn(c),null;case 19:if(On(ms),C=c.memoizedState,C===null)return Kn(c),null;if(w=(c.flags&128)!==0,q=C.rendering,q===null)if(w)zl(C,!1);else{if(ps!==0||a!==null&&(a.flags&128)!==0)for(a=c.child;a!==null;){if(q=Yu(a),q!==null){for(c.flags|=128,zl(C,!1),w=q.updateQueue,w!==null&&(c.updateQueue=w,c.flags|=4),c.subtreeFlags=0,w=f,f=c.child;f!==null;)C=f,a=w,C.flags&=14680066,q=C.alternate,q===null?(C.childLanes=0,C.lanes=a,C.child=null,C.subtreeFlags=0,C.memoizedProps=null,C.memoizedState=null,C.updateQueue=null,C.dependencies=null,C.stateNode=null):(C.childLanes=q.childLanes,C.lanes=q.lanes,C.child=q.child,C.subtreeFlags=0,C.deletions=null,C.memoizedProps=q.memoizedProps,C.memoizedState=q.memoizedState,C.updateQueue=q.updateQueue,C.type=q.type,a=q.dependencies,C.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext}),f=f.sibling;return Yn(ms,ms.current&1|2),c.child}a=a.sibling}C.tail!==null&&cn()>ca&&(c.flags|=128,w=!0,zl(C,!1),c.lanes=4194304)}else{if(!w)if(a=Yu(q),a!==null){if(c.flags|=128,w=!0,f=a.updateQueue,f!==null&&(c.updateQueue=f,c.flags|=4),zl(C,!0),C.tail===null&&C.tailMode==="hidden"&&!q.alternate&&!Xn)return Kn(c),null}else 2*cn()-C.renderingStartTime>ca&&f!==1073741824&&(c.flags|=128,w=!0,zl(C,!1),c.lanes=4194304);C.isBackwards?(q.sibling=c.child,c.child=q):(f=C.last,f!==null?f.sibling=q:c.child=q,C.last=q)}return C.tail!==null?(c=C.tail,C.rendering=c,C.tail=c.sibling,C.renderingStartTime=cn(),c.sibling=null,f=ms.current,Yn(ms,w?f&1|2:f&1),c):(Kn(c),null);case 22:case 23:return md(),w=c.memoizedState!==null,a!==null&&a.memoizedState!==null!==w&&(c.flags|=8192),w&&(c.mode&1)!==0?(Sr&1073741824)!==0&&(Kn(c),c.subtreeFlags&6&&(c.flags|=8192)):Kn(c),null;case 24:return null;case 25:return null}throw Error(n(156,c.tag))}function S_(a,c){switch(Vu(c),c.tag){case 1:return rr(c.type)&&Ro(),a=c.flags,a&65536?(c.flags=a&-65537|128,c):null;case 3:return ui(),On(xr),On(Es),Xu(),a=c.flags,(a&65536)!==0&&(a&128)===0?(c.flags=a&-65537|128,c):null;case 5:return Ll(c),null;case 13:if(On(ms),a=c.memoizedState,a!==null&&a.dehydrated!==null){if(c.alternate===null)throw Error(n(340));Fa()}return a=c.flags,a&65536?(c.flags=a&-65537|128,c):null;case 19:return On(ms),null;case 4:return ui(),null;case 10:return Ff(c.type._context),null;case 22:case 23:return md(),null;case 24:return null;default:return null}}var Fc=!1,cr=!1,ny=typeof WeakSet=="function"?WeakSet:Set,jt=null;function Us(a,c){var f=a.ref;if(f!==null)if(typeof f=="function")try{f(null)}catch(w){Z(a,c,w)}else f.current=null}function Ha(a,c,f){try{f()}catch(w){Z(a,c,w)}}var nh=!1;function N_(a,c){if(Pu=sr,a=kf(),Ta(a)){if("selectionStart"in a)var f={start:a.selectionStart,end:a.selectionEnd};else e:{f=(f=a.ownerDocument)&&f.defaultView||window;var w=f.getSelection&&f.getSelection();if(w&&w.rangeCount!==0){f=w.anchorNode;var j=w.anchorOffset,C=w.focusNode;w=w.focusOffset;try{f.nodeType,C.nodeType}catch{f=null;break e}var q=0,ie=-1,ue=-1,Te=0,Ze=0,tt=a,Je=null;t:for(;;){for(var kt;tt!==f||j!==0&&tt.nodeType!==3||(ie=q+j),tt!==C||w!==0&&tt.nodeType!==3||(ue=q+w),tt.nodeType===3&&(q+=tt.nodeValue.length),(kt=tt.firstChild)!==null;)Je=tt,tt=kt;for(;;){if(tt===a)break t;if(Je===f&&++Te===j&&(ie=q),Je===C&&++Ze===w&&(ue=q),(kt=tt.nextSibling)!==null)break;tt=Je,Je=tt.parentNode}tt=kt}f=ie===-1||ue===-1?null:{start:ie,end:ue}}else f=null}f=f||{start:0,end:0}}else f=null;for($f={focusedElem:a,selectionRange:f},sr=!1,jt=c;jt!==null;)if(c=jt,a=c.child,(c.subtreeFlags&1028)!==0&&a!==null)a.return=c,jt=a;else for(;jt!==null;){c=jt;try{var $t=c.alternate;if((c.flags&1024)!==0)switch(c.tag){case 0:case 11:case 15:break;case 1:if($t!==null){var At=$t.memoizedProps,Ls=$t.memoizedState,ve=c.stateNode,me=ve.getSnapshotBeforeUpdate(c.elementType===c.type?At:hi(c.type,At),Ls);ve.__reactInternalSnapshotBeforeUpdate=me}break;case 3:var Ne=c.stateNode.containerInfo;Ne.nodeType===1?Ne.textContent="":Ne.nodeType===9&&Ne.documentElement&&Ne.removeChild(Ne.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(it){Z(c,c.return,it)}if(a=c.sibling,a!==null){a.return=c.return,jt=a;break}jt=c.return}return $t=nh,nh=!1,$t}function ao(a,c,f){var w=c.updateQueue;if(w=w!==null?w.lastEffect:null,w!==null){var j=w=w.next;do{if((j.tag&a)===a){var C=j.destroy;j.destroy=void 0,C!==void 0&&Ha(c,f,C)}j=j.next}while(j!==w)}}function zc(a,c){if(c=c.updateQueue,c=c!==null?c.lastEffect:null,c!==null){var f=c=c.next;do{if((f.tag&a)===a){var w=f.create;f.destroy=w()}f=f.next}while(f!==c)}}function Ri(a){var c=a.ref;if(c!==null){var f=a.stateNode;switch(a.tag){case 5:a=f;break;default:a=f}typeof c=="function"?c(a):c.current=a}}function $_(a){var c=a.alternate;c!==null&&(a.alternate=null,$_(c)),a.child=null,a.deletions=null,a.sibling=null,a.tag===5&&(c=a.stateNode,c!==null&&(delete c[Yi],delete c[Eo],delete c[kl],delete c[Xm],delete c[jl])),a.stateNode=null,a.return=null,a.dependencies=null,a.memoizedProps=null,a.memoizedState=null,a.pendingProps=null,a.stateNode=null,a.updateQueue=null}function C_(a){return a.tag===5||a.tag===3||a.tag===4}function sh(a){e:for(;;){for(;a.sibling===null;){if(a.return===null||C_(a.return))return null;a=a.return}for(a.sibling.return=a.return,a=a.sibling;a.tag!==5&&a.tag!==6&&a.tag!==18;){if(a.flags&2||a.child===null||a.tag===4)continue e;a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}function Li(a,c,f){var w=a.tag;if(w===5||w===6)a=a.stateNode,c?f.nodeType===8?f.parentNode.insertBefore(a,c):f.insertBefore(a,c):(f.nodeType===8?(c=f.parentNode,c.insertBefore(a,f)):(c=f,c.appendChild(a)),f=f._reactRootContainer,f!=null||c.onclick!==null||(c.onclick=kc));else if(w!==4&&(a=a.child,a!==null))for(Li(a,c,f),a=a.sibling;a!==null;)Li(a,c,f),a=a.sibling}function Bc(a,c,f){var w=a.tag;if(w===5||w===6)a=a.stateNode,c?f.insertBefore(a,c):f.appendChild(a);else if(w!==4&&(a=a.child,a!==null))for(Bc(a,c,f),a=a.sibling;a!==null;)Bc(a,c,f),a=a.sibling}var Js=null,Ii=!1;function aa(a,c,f){for(f=f.child;f!==null;)rh(a,c,f),f=f.sibling}function rh(a,c,f){if(tr&&typeof tr.onCommitFiberUnmount=="function")try{tr.onCommitFiberUnmount(Fn,f)}catch{}switch(f.tag){case 5:cr||Us(f,c);case 6:var w=Js,j=Ii;Js=null,aa(a,c,f),Js=w,Ii=j,Js!==null&&(Ii?(a=Js,f=f.stateNode,a.nodeType===8?a.parentNode.removeChild(f):a.removeChild(f)):Js.removeChild(f.stateNode));break;case 18:Js!==null&&(Ii?(a=Js,f=f.stateNode,a.nodeType===8?Fu(a.parentNode,f):a.nodeType===1&&Fu(a,f),$a(a)):Fu(Js,f.stateNode));break;case 4:w=Js,j=Ii,Js=f.stateNode.containerInfo,Ii=!0,aa(a,c,f),Js=w,Ii=j;break;case 0:case 11:case 14:case 15:if(!cr&&(w=f.updateQueue,w!==null&&(w=w.lastEffect,w!==null))){j=w=w.next;do{var C=j,q=C.destroy;C=C.tag,q!==void 0&&((C&2)!==0||(C&4)!==0)&&Ha(f,c,q),j=j.next}while(j!==w)}aa(a,c,f);break;case 1:if(!cr&&(Us(f,c),w=f.stateNode,typeof w.componentWillUnmount=="function"))try{w.props=f.memoizedProps,w.state=f.memoizedState,w.componentWillUnmount()}catch(ie){Z(f,c,ie)}aa(a,c,f);break;case 21:aa(a,c,f);break;case 22:f.mode&1?(cr=(w=cr)||f.memoizedState!==null,aa(a,c,f),cr=w):aa(a,c,f);break;default:aa(a,c,f)}}function E_(a){var c=a.updateQueue;if(c!==null){a.updateQueue=null;var f=a.stateNode;f===null&&(f=a.stateNode=new ny),c.forEach(function(w){var j=Ge.bind(null,a,w);f.has(w)||(f.add(w),w.then(j,j))})}}function $n(a,c){var f=c.deletions;if(f!==null)for(var w=0;w<f.length;w++){var j=f[w];try{var C=a,q=c,ie=q;e:for(;ie!==null;){switch(ie.tag){case 5:Js=ie.stateNode,Ii=!1;break e;case 3:Js=ie.stateNode.containerInfo,Ii=!0;break e;case 4:Js=ie.stateNode.containerInfo,Ii=!0;break e}ie=ie.return}if(Js===null)throw Error(n(160));rh(C,q,j),Js=null,Ii=!1;var ue=j.alternate;ue!==null&&(ue.return=null),j.return=null}catch(Te){Z(j,c,Te)}}if(c.subtreeFlags&12854)for(c=c.child;c!==null;)_s(c,a),c=c.sibling}function _s(a,c){var f=a.alternate,w=a.flags;switch(a.tag){case 0:case 11:case 14:case 15:if($n(c,a),ls(a),w&4){try{ao(3,a,a.return),zc(3,a)}catch(At){Z(a,a.return,At)}try{ao(5,a,a.return)}catch(At){Z(a,a.return,At)}}break;case 1:$n(c,a),ls(a),w&512&&f!==null&&Us(f,f.return);break;case 5:if($n(c,a),ls(a),w&512&&f!==null&&Us(f,f.return),a.flags&32){var j=a.stateNode;try{_t(j,"")}catch(At){Z(a,a.return,At)}}if(w&4&&(j=a.stateNode,j!=null)){var C=a.memoizedProps,q=f!==null?f.memoizedProps:C,ie=a.type,ue=a.updateQueue;if(a.updateQueue=null,ue!==null)try{ie==="input"&&C.type==="radio"&&C.name!=null&&Ve(j,C),mn(ie,q);var Te=mn(ie,C);for(q=0;q<ue.length;q+=2){var Ze=ue[q],tt=ue[q+1];Ze==="style"?ut(j,tt):Ze==="dangerouslySetInnerHTML"?yt(j,tt):Ze==="children"?_t(j,tt):E(j,Ze,tt,Te)}switch(ie){case"input":ct(j,C);break;case"textarea":_e(j,C);break;case"select":var Je=j._wrapperState.wasMultiple;j._wrapperState.wasMultiple=!!C.multiple;var kt=C.value;kt!=null?Le(j,!!C.multiple,kt,!1):Je!==!!C.multiple&&(C.defaultValue!=null?Le(j,!!C.multiple,C.defaultValue,!0):Le(j,!!C.multiple,C.multiple?[]:"",!1))}j[Eo]=C}catch(At){Z(a,a.return,At)}}break;case 6:if($n(c,a),ls(a),w&4){if(a.stateNode===null)throw Error(n(162));j=a.stateNode,C=a.memoizedProps;try{j.nodeValue=C}catch(At){Z(a,a.return,At)}}break;case 3:if($n(c,a),ls(a),w&4&&f!==null&&f.memoizedState.isDehydrated)try{$a(c.containerInfo)}catch(At){Z(a,a.return,At)}break;case 4:$n(c,a),ls(a);break;case 13:$n(c,a),ls(a),j=a.child,j.flags&8192&&(C=j.memoizedState!==null,j.stateNode.isHidden=C,!C||j.alternate!==null&&j.alternate.memoizedState!==null||(qc=cn())),w&4&&E_(a);break;case 22:if(Ze=f!==null&&f.memoizedState!==null,a.mode&1?(cr=(Te=cr)||Ze,$n(c,a),cr=Te):$n(c,a),ls(a),w&8192){if(Te=a.memoizedState!==null,(a.stateNode.isHidden=Te)&&!Ze&&(a.mode&1)!==0)for(jt=a,Ze=a.child;Ze!==null;){for(tt=jt=Ze;jt!==null;){switch(Je=jt,kt=Je.child,Je.tag){case 0:case 11:case 14:case 15:ao(4,Je,Je.return);break;case 1:Us(Je,Je.return);var $t=Je.stateNode;if(typeof $t.componentWillUnmount=="function"){w=Je,f=Je.return;try{c=w,$t.props=c.memoizedProps,$t.state=c.memoizedState,$t.componentWillUnmount()}catch(At){Z(w,f,At)}}break;case 5:Us(Je,Je.return);break;case 22:if(Je.memoizedState!==null){ud(tt);continue}}kt!==null?(kt.return=Je,jt=kt):ud(tt)}Ze=Ze.sibling}e:for(Ze=null,tt=a;;){if(tt.tag===5){if(Ze===null){Ze=tt;try{j=tt.stateNode,Te?(C=j.style,typeof C.setProperty=="function"?C.setProperty("display","none","important"):C.display="none"):(ie=tt.stateNode,ue=tt.memoizedProps.style,q=ue!=null&&ue.hasOwnProperty("display")?ue.display:null,ie.style.display=St("display",q))}catch(At){Z(a,a.return,At)}}}else if(tt.tag===6){if(Ze===null)try{tt.stateNode.nodeValue=Te?"":tt.memoizedProps}catch(At){Z(a,a.return,At)}}else if((tt.tag!==22&&tt.tag!==23||tt.memoizedState===null||tt===a)&&tt.child!==null){tt.child.return=tt,tt=tt.child;continue}if(tt===a)break e;for(;tt.sibling===null;){if(tt.return===null||tt.return===a)break e;Ze===tt&&(Ze=null),tt=tt.return}Ze===tt&&(Ze=null),tt.sibling.return=tt.return,tt=tt.sibling}}break;case 19:$n(c,a),ls(a),w&4&&E_(a);break;case 21:break;default:$n(c,a),ls(a)}}function ls(a){var c=a.flags;if(c&2){try{e:{for(var f=a.return;f!==null;){if(C_(f)){var w=f;break e}f=f.return}throw Error(n(160))}switch(w.tag){case 5:var j=w.stateNode;w.flags&32&&(_t(j,""),w.flags&=-33);var C=sh(a);Bc(a,C,j);break;case 3:case 4:var q=w.stateNode.containerInfo,ie=sh(a);Li(a,ie,q);break;default:throw Error(n(161))}}catch(ue){Z(a,a.return,ue)}a.flags&=-3}c&4096&&(a.flags&=-4097)}function A_(a,c,f){jt=a,T_(a)}function T_(a,c,f){for(var w=(a.mode&1)!==0;jt!==null;){var j=jt,C=j.child;if(j.tag===22&&w){var q=j.memoizedState!==null||Fc;if(!q){var ie=j.alternate,ue=ie!==null&&ie.memoizedState!==null||cr;ie=Fc;var Te=cr;if(Fc=q,(cr=ue)&&!Te)for(jt=j;jt!==null;)q=jt,ue=q.child,q.tag===22&&q.memoizedState!==null?R_(j):ue!==null?(ue.return=q,jt=ue):R_(j);for(;C!==null;)jt=C,T_(C),C=C.sibling;jt=j,Fc=ie,cr=Te}M_(a)}else(j.subtreeFlags&8772)!==0&&C!==null?(C.return=j,jt=C):M_(a)}}function M_(a){for(;jt!==null;){var c=jt;if((c.flags&8772)!==0){var f=c.alternate;try{if((c.flags&8772)!==0)switch(c.tag){case 0:case 11:case 15:cr||zc(5,c);break;case 1:var w=c.stateNode;if(c.flags&4&&!cr)if(f===null)w.componentDidMount();else{var j=c.elementType===c.type?f.memoizedProps:hi(c.type,f.memoizedProps);w.componentDidUpdate(j,f.memoizedState,w.__reactInternalSnapshotBeforeUpdate)}var C=c.updateQueue;C!==null&&r_(c,C,w);break;case 3:var q=c.updateQueue;if(q!==null){if(f=null,c.child!==null)switch(c.child.tag){case 5:f=c.child.stateNode;break;case 1:f=c.child.stateNode}r_(c,q,f)}break;case 5:var ie=c.stateNode;if(f===null&&c.flags&4){f=ie;var ue=c.memoizedProps;switch(c.type){case"button":case"input":case"select":case"textarea":ue.autoFocus&&f.focus();break;case"img":ue.src&&(f.src=ue.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(c.memoizedState===null){var Te=c.alternate;if(Te!==null){var Ze=Te.memoizedState;if(Ze!==null){var tt=Ze.dehydrated;tt!==null&&$a(tt)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}cr||c.flags&512&&Ri(c)}catch(Je){Z(c,c.return,Je)}}if(c===a){jt=null;break}if(f=c.sibling,f!==null){f.return=c.return,jt=f;break}jt=c.return}}function ud(a){for(;jt!==null;){var c=jt;if(c===a){jt=null;break}var f=c.sibling;if(f!==null){f.return=c.return,jt=f;break}jt=c.return}}function R_(a){for(;jt!==null;){var c=jt;try{switch(c.tag){case 0:case 11:case 15:var f=c.return;try{zc(4,c)}catch(ue){Z(c,f,ue)}break;case 1:var w=c.stateNode;if(typeof w.componentDidMount=="function"){var j=c.return;try{w.componentDidMount()}catch(ue){Z(c,j,ue)}}var C=c.return;try{Ri(c)}catch(ue){Z(c,C,ue)}break;case 5:var q=c.return;try{Ri(c)}catch(ue){Z(c,q,ue)}}}catch(ue){Z(c,c.return,ue)}if(c===a){jt=null;break}var ie=c.sibling;if(ie!==null){ie.return=c.return,jt=ie;break}jt=c.return}}var sy=Math.ceil,lo=S.ReactCurrentDispatcher,ih=S.ReactCurrentOwner,Xr=S.ReactCurrentBatchConfig,An=0,Rs=null,$s=null,Ws=0,Sr=0,co=na(0),ps=0,Bl=null,la=0,Uc=0,uo=0,Wc=null,As=null,qc=0,ca=1/0,fo=null,Hc=!1,oh=null,_i=null,ho=!1,ua=null,da=0,Vc=0,Ul=null,zo=-1,dd=0;function Nr(){return(An&6)!==0?cn():zo!==-1?zo:zo=cn()}function Bo(a){return(a.mode&1)===0?1:(An&2)!==0&&Ws!==0?Ws&-Ws:Lf.transition!==null?(dd===0&&(dd=Ms()),dd):(a=Ln,a!==0||(a=window.event,a=a===void 0?16:Oe(a.type)),a)}function pi(a,c,f,w){if(50<Vc)throw Vc=0,Ul=null,Error(n(185));ks(a,f,w),((An&2)===0||a!==Rs)&&(a===Rs&&((An&2)===0&&(Uc|=f),ps===4&&Uo(a,Ws)),Pr(a,w),f===1&&An===0&&(c.mode&1)===0&&(ca=cn()+500,Uu&&Zi()))}function Pr(a,c){var f=a.callbackNode;ys(a,c);var w=zi(a,a===Rs?Ws:0);if(w===0)f!==null&&fn(f),a.callbackNode=null,a.callbackPriority=0;else if(c=w&-w,a.callbackPriority!==c){if(f!=null&&fn(f),c===1)a.tag===0?Wu(lh.bind(null,a)):ir(lh.bind(null,a)),Ym(function(){(An&6)===0&&Zi()}),f=null;else{switch(Sa(w)){case 1:f=Cs;break;case 4:f=gs;break;case 16:f=mr;break;case 536870912:f=Nt;break;default:f=mr}f=ye(f,L_.bind(null,a))}a.callbackPriority=c,a.callbackNode=f}}function L_(a,c){if(zo=-1,dd=0,(An&6)!==0)throw Error(n(327));var f=a.callbackNode;if(F()&&a.callbackNode!==f)return null;var w=zi(a,a===Rs?Ws:0);if(w===0)return null;if((w&30)!==0||(w&a.expiredLanes)!==0||c)c=Gc(a,w);else{c=w;var j=An;An|=2;var C=uh();(Rs!==a||Ws!==c)&&(fo=null,ca=cn()+500,ha(a,c));do try{P_();break}catch(ie){ch(a,ie)}while(!0);Df(),lo.current=C,An=j,$s!==null?c=0:(Rs=null,Ws=0,c=ps)}if(c!==0){if(c===2&&(j=ni(a),j!==0&&(w=j,c=fd(a,j))),c===1)throw f=Bl,ha(a,0),Uo(a,w),Pr(a,cn()),f;if(c===6)Uo(a,w);else{if(j=a.current.alternate,(w&30)===0&&!I_(j)&&(c=Gc(a,w),c===2&&(C=ni(a),C!==0&&(w=C,c=fd(a,C))),c===1))throw f=Bl,ha(a,0),Uo(a,w),Pr(a,cn()),f;switch(a.finishedWork=j,a.finishedLanes=w,c){case 0:case 1:throw Error(n(345));case 2:v(a,As,fo);break;case 3:if(Uo(a,w),(w&130023424)===w&&(c=qc+500-cn(),10<c)){if(zi(a,0)!==0)break;if(j=a.suspendedLanes,(j&w)!==w){Nr(),a.pingedLanes|=a.suspendedLanes&j;break}a.timeoutHandle=Cf(v.bind(null,a,As,fo),c);break}v(a,As,fo);break;case 4:if(Uo(a,w),(w&4194240)===w)break;for(c=a.eventTimes,j=-1;0<w;){var q=31-nr(w);C=1<<q,q=c[q],q>j&&(j=q),w&=~C}if(w=j,w=cn()-w,w=(120>w?120:480>w?480:1080>w?1080:1920>w?1920:3e3>w?3e3:4320>w?4320:1960*sy(w/1960))-w,10<w){a.timeoutHandle=Cf(v.bind(null,a,As,fo),w);break}v(a,As,fo);break;case 5:v(a,As,fo);break;default:throw Error(n(329))}}}return Pr(a,cn()),a.callbackNode===f?L_.bind(null,a):null}function fd(a,c){var f=Wc;return a.current.memoizedState.isDehydrated&&(ha(a,c).flags|=256),a=Gc(a,c),a!==2&&(c=As,As=f,c!==null&&ah(c)),a}function ah(a){As===null?As=a:As.push.apply(As,a)}function I_(a){for(var c=a;;){if(c.flags&16384){var f=c.updateQueue;if(f!==null&&(f=f.stores,f!==null))for(var w=0;w<f.length;w++){var j=f[w],C=j.getSnapshot;j=j.value;try{if(!yr(C(),j))return!1}catch{return!1}}}if(f=c.child,c.subtreeFlags&16384&&f!==null)f.return=c,c=f;else{if(c===a)break;for(;c.sibling===null;){if(c.return===null||c.return===a)return!0;c=c.return}c.sibling.return=c.return,c=c.sibling}}return!0}function Uo(a,c){for(c&=~uo,c&=~Uc,a.suspendedLanes|=c,a.pingedLanes&=~c,a=a.expirationTimes;0<c;){var f=31-nr(c),w=1<<f;a[f]=-1,c&=~w}}function lh(a){if((An&6)!==0)throw Error(n(327));F();var c=zi(a,0);if((c&1)===0)return Pr(a,cn()),null;var f=Gc(a,c);if(a.tag!==0&&f===2){var w=ni(a);w!==0&&(c=w,f=fd(a,w))}if(f===1)throw f=Bl,ha(a,0),Uo(a,c),Pr(a,cn()),f;if(f===6)throw Error(n(345));return a.finishedWork=a.current.alternate,a.finishedLanes=c,v(a,As,fo),Pr(a,cn()),null}function hd(a,c){var f=An;An|=1;try{return a(c)}finally{An=f,An===0&&(ca=cn()+500,Uu&&Zi())}}function fa(a){ua!==null&&ua.tag===0&&(An&6)===0&&F();var c=An;An|=1;var f=Xr.transition,w=Ln;try{if(Xr.transition=null,Ln=1,a)return a()}finally{Ln=w,Xr.transition=f,An=c,(An&6)===0&&Zi()}}function md(){Sr=co.current,On(co)}function ha(a,c){a.finishedWork=null,a.finishedLanes=0;var f=a.timeoutHandle;if(f!==-1&&(a.timeoutHandle=-1,Km(f)),$s!==null)for(f=$s.return;f!==null;){var w=f;switch(Vu(w),w.tag){case 1:w=w.type.childContextTypes,w!=null&&Ro();break;case 3:ui(),On(xr),On(Es),Xu();break;case 5:Ll(w);break;case 4:ui();break;case 13:On(ms);break;case 19:On(ms);break;case 10:Ff(w.type._context);break;case 22:case 23:md()}f=f.return}if(Rs=a,$s=a=lt(a.current,null),Ws=Sr=c,ps=0,Bl=null,uo=Uc=la=0,As=Wc=null,no!==null){for(c=0;c<no.length;c++)if(f=no[c],w=f.interleaved,w!==null){f.interleaved=null;var j=w.next,C=f.pending;if(C!==null){var q=C.next;C.next=j,w.next=q}f.pending=w}no=null}return a}function ch(a,c){do{var f=$s;try{if(Df(),Il.current=Pl,Ec){for(var w=as.memoizedState;w!==null;){var j=w.queue;j!==null&&(j.pending=null),w=w.next}Ec=!1}if(Zn=0,Pn=Ss=as=null,Po=!1,Ua=0,ih.current=null,f===null||f.return===null){ps=1,Bl=c,$s=null;break}e:{var C=a,q=f.return,ie=f,ue=c;if(c=Ws,ie.flags|=32768,ue!==null&&typeof ue=="object"&&typeof ue.then=="function"){var Te=ue,Ze=ie,tt=Ze.tag;if((Ze.mode&1)===0&&(tt===0||tt===11||tt===15)){var Je=Ze.alternate;Je?(Ze.updateQueue=Je.updateQueue,Ze.memoizedState=Je.memoizedState,Ze.lanes=Je.lanes):(Ze.updateQueue=null,Ze.memoizedState=null)}var kt=lr(q);if(kt!==null){kt.flags&=-257,Bs(kt,q,ie,C,c),kt.mode&1&&ia(C,Te,c),c=kt,ue=Te;var $t=c.updateQueue;if($t===null){var At=new Set;At.add(ue),c.updateQueue=At}else $t.add(ue);break e}else{if((c&1)===0){ia(C,Te,c),_d();break e}ue=Error(n(426))}}else if(Xn&&ie.mode&1){var Ls=lr(q);if(Ls!==null){(Ls.flags&65536)===0&&(Ls.flags|=256),Bs(Ls,q,ie,C,c),Rf(Wa(ue,ie));break e}}C=ue=Wa(ue,ie),ps!==4&&(ps=2),Wc===null?Wc=[C]:Wc.push(C),C=q;do{switch(C.tag){case 3:C.flags|=65536,c&=-c,C.lanes|=c;var ve=Oc(C,ue,c);s_(C,ve);break e;case 1:ie=ue;var me=C.type,Ne=C.stateNode;if((C.flags&128)===0&&(typeof me.getDerivedStateFromError=="function"||Ne!==null&&typeof Ne.componentDidCatch=="function"&&(_i===null||!_i.has(Ne)))){C.flags|=65536,c&=-c,C.lanes|=c;var it=g_(C,ie,c);s_(C,it);break e}}C=C.return}while(C!==null)}fh(f)}catch(Rt){c=Rt,$s===f&&f!==null&&($s=f=f.return);continue}break}while(!0)}function uh(){var a=lo.current;return lo.current=Pl,a===null?Pl:a}function _d(){(ps===0||ps===3||ps===2)&&(ps=4),Rs===null||(la&268435455)===0&&(Uc&268435455)===0||Uo(Rs,Ws)}function Gc(a,c){var f=An;An|=2;var w=uh();(Rs!==a||Ws!==c)&&(fo=null,ha(a,c));do try{O_();break}catch(j){ch(a,j)}while(!0);if(Df(),An=f,lo.current=w,$s!==null)throw Error(n(261));return Rs=null,Ws=0,ps}function O_(){for(;$s!==null;)dh($s)}function P_(){for(;$s!==null&&!Xe();)dh($s)}function dh(a){var c=ke(a.alternate,a,Sr);a.memoizedProps=a.pendingProps,c===null?fh(a):$s=c,ih.current=null}function fh(a){var c=a;do{var f=c.alternate;if(a=c.return,(c.flags&32768)===0){if(f=th(f,c,Sr),f!==null){$s=f;return}}else{if(f=S_(f,c),f!==null){f.flags&=32767,$s=f;return}if(a!==null)a.flags|=32768,a.subtreeFlags=0,a.deletions=null;else{ps=6,$s=null;return}}if(c=c.sibling,c!==null){$s=c;return}$s=c=a}while(c!==null);ps===0&&(ps=5)}function v(a,c,f){var w=Ln,j=Xr.transition;try{Xr.transition=null,Ln=1,T(a,c,f,w)}finally{Xr.transition=j,Ln=w}return null}function T(a,c,f,w){do F();while(ua!==null);if((An&6)!==0)throw Error(n(327));f=a.finishedWork;var j=a.finishedLanes;if(f===null)return null;if(a.finishedWork=null,a.finishedLanes=0,f===a.current)throw Error(n(177));a.callbackNode=null,a.callbackPriority=0;var C=f.lanes|f.childLanes;if(ri(a,C),a===Rs&&($s=Rs=null,Ws=0),(f.subtreeFlags&2064)===0&&(f.flags&2064)===0||ho||(ho=!0,ye(mr,function(){return F(),null})),C=(f.flags&15990)!==0,(f.subtreeFlags&15990)!==0||C){C=Xr.transition,Xr.transition=null;var q=Ln;Ln=1;var ie=An;An|=4,ih.current=null,N_(a,f),_s(f,a),qm($f),sr=!!Pu,$f=Pu=null,a.current=f,A_(f),nn(),An=ie,Ln=q,Xr.transition=C}else a.current=f;if(ho&&(ho=!1,ua=a,da=j),C=a.pendingLanes,C===0&&(_i=null),Ni(f.stateNode),Pr(a,cn()),c!==null)for(w=a.onRecoverableError,f=0;f<c.length;f++)j=c[f],w(j.value,{componentStack:j.stack,digest:j.digest});if(Hc)throw Hc=!1,a=oh,oh=null,a;return(da&1)!==0&&a.tag!==0&&F(),C=a.pendingLanes,(C&1)!==0?a===Ul?Vc++:(Vc=0,Ul=a):Vc=0,Zi(),null}function F(){if(ua!==null){var a=Sa(da),c=Xr.transition,f=Ln;try{if(Xr.transition=null,Ln=16>a?16:a,ua===null)var w=!1;else{if(a=ua,ua=null,da=0,(An&6)!==0)throw Error(n(331));var j=An;for(An|=4,jt=a.current;jt!==null;){var C=jt,q=C.child;if((jt.flags&16)!==0){var ie=C.deletions;if(ie!==null){for(var ue=0;ue<ie.length;ue++){var Te=ie[ue];for(jt=Te;jt!==null;){var Ze=jt;switch(Ze.tag){case 0:case 11:case 15:ao(8,Ze,C)}var tt=Ze.child;if(tt!==null)tt.return=Ze,jt=tt;else for(;jt!==null;){Ze=jt;var Je=Ze.sibling,kt=Ze.return;if($_(Ze),Ze===Te){jt=null;break}if(Je!==null){Je.return=kt,jt=Je;break}jt=kt}}}var $t=C.alternate;if($t!==null){var At=$t.child;if(At!==null){$t.child=null;do{var Ls=At.sibling;At.sibling=null,At=Ls}while(At!==null)}}jt=C}}if((C.subtreeFlags&2064)!==0&&q!==null)q.return=C,jt=q;else e:for(;jt!==null;){if(C=jt,(C.flags&2048)!==0)switch(C.tag){case 0:case 11:case 15:ao(9,C,C.return)}var ve=C.sibling;if(ve!==null){ve.return=C.return,jt=ve;break e}jt=C.return}}var me=a.current;for(jt=me;jt!==null;){q=jt;var Ne=q.child;if((q.subtreeFlags&2064)!==0&&Ne!==null)Ne.return=q,jt=Ne;else e:for(q=me;jt!==null;){if(ie=jt,(ie.flags&2048)!==0)try{switch(ie.tag){case 0:case 11:case 15:zc(9,ie)}}catch(Rt){Z(ie,ie.return,Rt)}if(ie===q){jt=null;break e}var it=ie.sibling;if(it!==null){it.return=ie.return,jt=it;break e}jt=ie.return}}if(An=j,Zi(),tr&&typeof tr.onPostCommitFiberRoot=="function")try{tr.onPostCommitFiberRoot(Fn,a)}catch{}w=!0}return w}finally{Ln=f,Xr.transition=c}}return!1}function B(a,c,f){c=Wa(f,c),c=Oc(a,c,1),a=Yr(a,c,1),c=Nr(),a!==null&&(ks(a,1,c),Pr(a,c))}function Z(a,c,f){if(a.tag===3)B(a,a,f);else for(;c!==null;){if(c.tag===3){B(c,a,f);break}else if(c.tag===1){var w=c.stateNode;if(typeof c.type.getDerivedStateFromError=="function"||typeof w.componentDidCatch=="function"&&(_i===null||!_i.has(w))){a=Wa(f,a),a=g_(c,a,1),c=Yr(c,a,1),a=Nr(),c!==null&&(ks(c,1,a),Pr(c,a));break}}c=c.return}}function X(a,c,f){var w=a.pingCache;w!==null&&w.delete(c),c=Nr(),a.pingedLanes|=a.suspendedLanes&f,Rs===a&&(Ws&f)===f&&(ps===4||ps===3&&(Ws&130023424)===Ws&&500>cn()-qc?ha(a,0):uo|=f),Pr(a,c)}function ee(a,c){c===0&&((a.mode&1)===0?c=1:(c=_r,_r<<=1,(_r&130023424)===0&&(_r=4194304)));var f=Nr();a=un(a,c),a!==null&&(ks(a,c,f),Pr(a,f))}function oe(a){var c=a.memoizedState,f=0;c!==null&&(f=c.retryLane),ee(a,f)}function Ge(a,c){var f=0;switch(a.tag){case 13:var w=a.stateNode,j=a.memoizedState;j!==null&&(f=j.retryLane);break;case 19:w=a.stateNode;break;default:throw Error(n(314))}w!==null&&w.delete(c),ee(a,f)}var ke;ke=function(a,c,f){if(a!==null)if(a.memoizedProps!==c.pendingProps||xr.current)Ns=!0;else{if((a.lanes&f)===0&&(c.flags&128)===0)return Ns=!1,ty(a,c,f);Ns=(a.flags&131072)!==0}else Ns=!1,Xn&&(c.flags&1048576)!==0&&Tf(c,qu,c.index);switch(c.lanes=0,c.tag){case 2:var w=c.type;Fl(a,c),a=c.pendingProps;var j=Xi(c,Es.current);za(c,f),j=Wf(null,c,w,a,j,f);var C=qf();return c.flags|=1,typeof j=="object"&&j!==null&&typeof j.render=="function"&&j.$$typeof===void 0?(c.tag=1,c.memoizedState=null,c.updateQueue=null,rr(w)?(C=!0,Nl(c)):C=!1,c.memoizedState=j.state!==null&&j.state!==void 0?j.state:null,Sc(c),j.updater=sd,c.stateNode=j,j._reactInternals=c,Zf(c,w,a,f),c=id(null,c,w,!0,C,f)):(c.tag=0,Xn&&C&&Hu(c),ws(null,c,j,f),c=c.child),c;case 16:w=c.elementType;e:{switch(Fl(a,c),a=c.pendingProps,j=w._init,w=j(w._payload),c.type=w,j=c.tag=pt(w),a=hi(w,a),j){case 0:c=eh(null,c,w,a,f);break e;case 1:c=v_(null,c,w,a,f);break e;case 11:c=mi(null,c,w,a,f);break e;case 14:c=y_(null,c,w,hi(w.type,a),f);break e}throw Error(n(306,w,""))}return c;case 0:return w=c.type,j=c.pendingProps,j=c.elementType===w?j:hi(w,j),eh(a,c,w,j,f);case 1:return w=c.type,j=c.pendingProps,j=c.elementType===w?j:hi(w,j),v_(a,c,w,j,f);case 3:e:{if(oa(c),a===null)throw Error(n(387));w=c.pendingProps,C=c.memoizedState,j=C.element,zf(a,c),Rl(c,w,null,f);var q=c.memoizedState;if(w=q.element,C.isDehydrated)if(C={element:w,isDehydrated:!1,cache:q.cache,pendingSuspenseBoundaries:q.pendingSuspenseBoundaries,transitions:q.transitions},c.updateQueue.baseState=C,c.memoizedState=C,c.flags&256){j=Wa(Error(n(423)),c),c=Dl(a,c,w,f,j);break e}else if(w!==j){j=Wa(Error(n(424)),c),c=Dl(a,c,w,f,j);break e}else for(Ir=ea(c.stateNode.containerInfo.firstChild),Kr=c,Xn=!0,Ti=null,f=Of(c,null,w,f),c.child=f;f;)f.flags=f.flags&-3|4096,f=f.sibling;else{if(Fa(),w===j){c=Fo(a,c,f);break e}ws(a,c,w,f)}c=c.child}return c;case 5:return di(c),a===null&&jc(c),w=c.type,j=c.pendingProps,C=a!==null?a.memoizedProps:null,q=j.children,Du(w,j)?q=null:C!==null&&Du(w,C)&&(c.flags|=32),rd(a,c),ws(a,c,q,f),c.child;case 6:return a===null&&jc(c),null;case 13:return x_(a,c,f);case 4:return Ju(c,c.stateNode.containerInfo),w=c.pendingProps,a===null?c.child=Io(c,null,w,f):ws(a,c,w,f),c.child;case 11:return w=c.type,j=c.pendingProps,j=c.elementType===w?j:hi(w,j),mi(a,c,w,j,f);case 7:return ws(a,c,c.pendingProps,f),c.child;case 8:return ws(a,c,c.pendingProps.children,f),c.child;case 12:return ws(a,c,c.pendingProps.children,f),c.child;case 10:e:{if(w=c.type._context,j=c.pendingProps,C=c.memoizedProps,q=j.value,Yn(Oo,w._currentValue),w._currentValue=q,C!==null)if(yr(C.value,q)){if(C.children===j.children&&!xr.current){c=Fo(a,c,f);break e}}else for(C=c.child,C!==null&&(C.return=c);C!==null;){var ie=C.dependencies;if(ie!==null){q=C.child;for(var ue=ie.firstContext;ue!==null;){if(ue.context===w){if(C.tag===1){ue=Jr(-1,f&-f),ue.tag=2;var Te=C.updateQueue;if(Te!==null){Te=Te.shared;var Ze=Te.pending;Ze===null?ue.next=ue:(ue.next=Ze.next,Ze.next=ue),Te.pending=ue}}C.lanes|=f,ue=C.alternate,ue!==null&&(ue.lanes|=f),Gu(C.return,f,c),ie.lanes|=f;break}ue=ue.next}}else if(C.tag===10)q=C.type===c.type?null:C.child;else if(C.tag===18){if(q=C.return,q===null)throw Error(n(341));q.lanes|=f,ie=q.alternate,ie!==null&&(ie.lanes|=f),Gu(q,f,c),q=C.sibling}else q=C.child;if(q!==null)q.return=C;else for(q=C;q!==null;){if(q===c){q=null;break}if(C=q.sibling,C!==null){C.return=q.return,q=C;break}q=q.return}C=q}ws(a,c,j.children,f),c=c.child}return c;case 9:return j=c.type,w=c.pendingProps.children,za(c,f),j=ci(j),w=w(j),c.flags|=1,ws(a,c,w,f),c.child;case 14:return w=c.type,j=hi(w,c.pendingProps),j=hi(w.type,j),y_(a,c,w,j,f);case 15:return Pc(a,c,c.type,c.pendingProps,f);case 17:return w=c.type,j=c.pendingProps,j=c.elementType===w?j:hi(w,j),Fl(a,c),c.tag=1,rr(w)?(a=!0,Nl(c)):a=!1,za(c,f),__(c,w,j),Zf(c,w,j,f),id(null,c,w,!0,a,f);case 19:return b_(a,c,f);case 22:return w_(a,c,f)}throw Error(n(156,c.tag))};function ye(a,c){return Dn(a,c)}function Fe(a,c,f,w){this.tag=a,this.key=f,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=c,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=w,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Pe(a,c,f,w){return new Fe(a,c,f,w)}function st(a){return a=a.prototype,!(!a||!a.isReactComponent)}function pt(a){if(typeof a=="function")return st(a)?1:0;if(a!=null){if(a=a.$$typeof,a===H)return 11;if(a===O)return 14}return 2}function lt(a,c){var f=a.alternate;return f===null?(f=Pe(a.tag,c,a.key,a.mode),f.elementType=a.elementType,f.type=a.type,f.stateNode=a.stateNode,f.alternate=a,a.alternate=f):(f.pendingProps=c,f.type=a.type,f.flags=0,f.subtreeFlags=0,f.deletions=null),f.flags=a.flags&14680064,f.childLanes=a.childLanes,f.lanes=a.lanes,f.child=a.child,f.memoizedProps=a.memoizedProps,f.memoizedState=a.memoizedState,f.updateQueue=a.updateQueue,c=a.dependencies,f.dependencies=c===null?null:{lanes:c.lanes,firstContext:c.firstContext},f.sibling=a.sibling,f.index=a.index,f.ref=a.ref,f}function vn(a,c,f,w,j,C){var q=2;if(w=a,typeof a=="function")st(a)&&(q=1);else if(typeof a=="string")q=5;else e:switch(a){case R:return qt(f.children,j,C,c);case I:q=8,j|=8;break;case W:return a=Pe(12,f,c,j|2),a.elementType=W,a.lanes=C,a;case M:return a=Pe(13,f,c,j),a.elementType=M,a.lanes=C,a;case A:return a=Pe(19,f,c,j),a.elementType=A,a.lanes=C,a;case V:return ft(f,j,C,c);default:if(typeof a=="object"&&a!==null)switch(a.$$typeof){case G:q=10;break e;case K:q=9;break e;case H:q=11;break e;case O:q=14;break e;case L:q=16,w=null;break e}throw Error(n(130,a==null?a:typeof a,""))}return c=Pe(q,f,c,j),c.elementType=a,c.type=w,c.lanes=C,c}function qt(a,c,f,w){return a=Pe(7,a,w,c),a.lanes=f,a}function ft(a,c,f,w){return a=Pe(22,a,w,c),a.elementType=V,a.lanes=f,a.stateNode={isHidden:!1},a}function Qt(a,c,f){return a=Pe(6,a,null,c),a.lanes=f,a}function Jn(a,c,f){return c=Pe(4,a.children!==null?a.children:[],a.key,c),c.lanes=f,c.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation},c}function cs(a,c,f,w,j){this.tag=c,this.containerInfo=a,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=si(0),this.expirationTimes=si(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=si(0),this.identifierPrefix=w,this.onRecoverableError=j,this.mutableSourceEagerHydrationData=null}function ur(a,c,f,w,j,C,q,ie,ue){return a=new cs(a,c,f,ie,ue),c===1?(c=1,C===!0&&(c|=8)):c=0,C=Pe(3,null,null,c),a.current=C,C.stateNode=a,C.memoizedState={element:w,isDehydrated:f,cache:null,transitions:null,pendingSuspenseBoundaries:null},Sc(C),a}function gi(a,c,f){var w=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:D,key:w==null?null:""+w,children:a,containerInfo:c,implementation:f}}function yi(a){if(!a)return ai;a=a._reactInternals;e:{if(sn(a)!==a||a.tag!==1)throw Error(n(170));var c=a;do{switch(c.tag){case 3:c=c.stateNode.context;break e;case 1:if(rr(c.type)){c=c.stateNode.__reactInternalMemoizedMergedChildContext;break e}}c=c.return}while(c!==null);throw Error(n(171))}if(a.tag===1){var f=a.type;if(rr(f))return Zm(a,f,c)}return c}function Wl(a,c,f,w,j,C,q,ie,ue){return a=ur(f,w,!0,a,j,C,q,ie,ue),a.context=yi(null),f=a.current,w=Nr(),j=Bo(f),C=Jr(w,j),C.callback=c??null,Yr(f,C,j),a.current.lanes=j,ks(a,j,w),Pr(a,w),a}function D_(a,c,f,w){var j=c.current,C=Nr(),q=Bo(j);return f=yi(f),c.context===null?c.context=f:c.pendingContext=f,c=Jr(C,q),c.payload={element:a},w=w===void 0?null:w,w!==null&&(c.callback=w),a=Yr(j,c,q),a!==null&&(pi(a,j,q,C),rn(a,j,q)),q}function F_(a){if(a=a.current,!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function qx(a,c){if(a=a.memoizedState,a!==null&&a.dehydrated!==null){var f=a.retryLane;a.retryLane=f!==0&&f<c?f:c}}function ry(a,c){qx(a,c),(a=a.alternate)&&qx(a,c)}function LC(){return null}var Hx=typeof reportError=="function"?reportError:function(a){console.error(a)};function iy(a){this._internalRoot=a}z_.prototype.render=iy.prototype.render=function(a){var c=this._internalRoot;if(c===null)throw Error(n(409));D_(a,c,null,null)},z_.prototype.unmount=iy.prototype.unmount=function(){var a=this._internalRoot;if(a!==null){this._internalRoot=null;var c=a.containerInfo;fa(function(){D_(null,a,null,null)}),c[Ai]=null}};function z_(a){this._internalRoot=a}z_.prototype.unstable_scheduleHydration=function(a){if(a){var c=dc();a={blockedOn:null,target:a,priority:c};for(var f=0;f<Tr.length&&c!==0&&c<Tr[f].priority;f++);Tr.splice(f,0,a),f===0&&$i(a)}};function oy(a){return!(!a||a.nodeType!==1&&a.nodeType!==9&&a.nodeType!==11)}function B_(a){return!(!a||a.nodeType!==1&&a.nodeType!==9&&a.nodeType!==11&&(a.nodeType!==8||a.nodeValue!==" react-mount-point-unstable "))}function Vx(){}function IC(a,c,f,w,j){if(j){if(typeof w=="function"){var C=w;w=function(){var Te=F_(q);C.call(Te)}}var q=Wl(c,w,a,0,null,!1,!1,"",Vx);return a._reactRootContainer=q,a[Ai]=q.current,Ci(a.nodeType===8?a.parentNode:a),fa(),q}for(;j=a.lastChild;)a.removeChild(j);if(typeof w=="function"){var ie=w;w=function(){var Te=F_(ue);ie.call(Te)}}var ue=ur(a,0,!1,null,null,!1,!1,"",Vx);return a._reactRootContainer=ue,a[Ai]=ue.current,Ci(a.nodeType===8?a.parentNode:a),fa(function(){D_(c,ue,f,w)}),ue}function U_(a,c,f,w,j){var C=f._reactRootContainer;if(C){var q=C;if(typeof j=="function"){var ie=j;j=function(){var ue=F_(q);ie.call(ue)}}D_(c,q,a,j)}else q=IC(f,c,a,j,w);return F_(q)}ul=function(a){switch(a.tag){case 3:var c=a.stateNode;if(c.current.memoizedState.isDehydrated){var f=Ts(c.pendingLanes);f!==0&&(Bi(c,f|1),Pr(c,cn()),(An&6)===0&&(ca=cn()+500,Zi()))}break;case 13:fa(function(){var w=un(a,1);if(w!==null){var j=Nr();pi(w,a,1,j)}}),ry(a,1)}},dl=function(a){if(a.tag===13){var c=un(a,134217728);if(c!==null){var f=Nr();pi(c,a,134217728,f)}ry(a,134217728)}},Ar=function(a){if(a.tag===13){var c=Bo(a),f=un(a,c);if(f!==null){var w=Nr();pi(f,a,c,w)}ry(a,c)}},dc=function(){return Ln},Ui=function(a,c){var f=Ln;try{return Ln=a,c()}finally{Ln=f}},Gs=function(a,c,f){switch(c){case"input":if(ct(a,f),c=f.name,f.type==="radio"&&c!=null){for(f=a;f.parentNode;)f=f.parentNode;for(f=f.querySelectorAll("input[name="+JSON.stringify(""+c)+'][type="radio"]'),c=0;c<f.length;c++){var w=f[c];if(w!==a&&w.form===a.form){var j=Ao(w);if(!j)throw Error(n(90));mt(w),ct(w,j)}}}break;case"textarea":_e(a,f);break;case"select":c=f.value,c!=null&&Le(a,!!f.multiple,c,!1)}},fe=hd,Ce=fa;var OC={usingClientEntryPoint:!1,Events:[ta,Sl,Ao,gt,re,hd]},hh={findFiberByHostInstance:Pa,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},PC={bundleType:hh.bundleType,version:hh.version,rendererPackageName:hh.rendererPackageName,rendererConfig:hh.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:S.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){return a=Zt(a),a===null?null:a.stateNode},findFiberByHostInstance:hh.findFiberByHostInstance||LC,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var W_=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!W_.isDisabled&&W_.supportsFiber)try{Fn=W_.inject(PC),tr=W_}catch{}}return wi.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=OC,wi.createPortal=function(a,c){var f=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!oy(c))throw Error(n(200));return gi(a,c,null,f)},wi.createRoot=function(a,c){if(!oy(a))throw Error(n(299));var f=!1,w="",j=Hx;return c!=null&&(c.unstable_strictMode===!0&&(f=!0),c.identifierPrefix!==void 0&&(w=c.identifierPrefix),c.onRecoverableError!==void 0&&(j=c.onRecoverableError)),c=ur(a,1,!1,null,null,f,!1,w,j),a[Ai]=c.current,Ci(a.nodeType===8?a.parentNode:a),new iy(c)},wi.findDOMNode=function(a){if(a==null)return null;if(a.nodeType===1)return a;var c=a._reactInternals;if(c===void 0)throw typeof a.render=="function"?Error(n(188)):(a=Object.keys(a).join(","),Error(n(268,a)));return a=Zt(c),a=a===null?null:a.stateNode,a},wi.flushSync=function(a){return fa(a)},wi.hydrate=function(a,c,f){if(!B_(c))throw Error(n(200));return U_(null,a,c,!0,f)},wi.hydrateRoot=function(a,c,f){if(!oy(a))throw Error(n(405));var w=f!=null&&f.hydratedSources||null,j=!1,C="",q=Hx;if(f!=null&&(f.unstable_strictMode===!0&&(j=!0),f.identifierPrefix!==void 0&&(C=f.identifierPrefix),f.onRecoverableError!==void 0&&(q=f.onRecoverableError)),c=Wl(c,null,a,1,f??null,j,!1,C,q),a[Ai]=c.current,Ci(a),w)for(a=0;a<w.length;a++)f=w[a],j=f._getVersion,j=j(f._source),c.mutableSourceEagerHydrationData==null?c.mutableSourceEagerHydrationData=[f,j]:c.mutableSourceEagerHydrationData.push(f,j);return new z_(c)},wi.render=function(a,c,f){if(!B_(c))throw Error(n(200));return U_(null,a,c,!1,f)},wi.unmountComponentAtNode=function(a){if(!B_(a))throw Error(n(40));return a._reactRootContainer?(fa(function(){U_(null,null,a,!1,function(){a._reactRootContainer=null,a[Ai]=null})}),!0):!1},wi.unstable_batchedUpdates=hd,wi.unstable_renderSubtreeIntoContainer=function(a,c,f,w){if(!B_(f))throw Error(n(200));if(a==null||a._reactInternals===void 0)throw Error(n(38));return U_(a,c,f,!1,w)},wi.version="18.3.1-next-f1338f8080-20240426",wi}var eb;function Aj(){if(eb)return cy.exports;eb=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(),cy.exports=VC(),cy.exports}var tb;function GC(){if(tb)return q_;tb=1;var e=Aj();return q_.createRoot=e.createRoot,q_.hydrateRoot=e.hydrateRoot,q_}var KC=GC();const JC=Bv(KC),Tj=[{id:"dark",label:"Dark (Abstract)",group:"dark",swatches:["#1a1a2e","#16213e","#0f3460","#e94560","#60a5fa","#27ae60"]},{id:"observer-night",label:"Observer Night",group:"dark",swatches:["#0b0f14","#10161e","#161e28","#e8a54a","#6ea8d8","#7bc98c"]},{id:"catppuccin-mocha",label:"Catppuccin Mocha",group:"dark",swatches:["#1e1e2e","#181825","#313244","#cba6f7","#89b4fa","#a6e3a1"]},{id:"catppuccin-macchiato",label:"Catppuccin Macchiato",group:"dark",swatches:["#24273a","#1e2030","#363a4f","#c6a0f6","#8aadf4","#a6da95"]},{id:"catppuccin-frappe",label:"Catppuccin Frappe",group:"dark",swatches:["#303446","#292c3c","#414559","#ca9ee6","#8caaee","#a6d189"]},{id:"rose-pine",label:"Rose Pine",group:"dark",swatches:["#191724","#1f1d2e","#26233a","#c4a7e7","#31748f","#9ccfd8"]},{id:"rose-pine-moon",label:"Rose Pine Moon",group:"dark",swatches:["#232136","#2a273f","#393552","#c4a7e7","#3e8fb0","#9ccfd8"]},{id:"tokyo-night",label:"Tokyo Night",group:"dark",swatches:["#1a1b26","#24283b","#414868","#7aa2f7","#2ac3de","#9ece6a"]},{id:"nord",label:"Nord",group:"dark",swatches:["#2e3440","#3b4252","#434c5e","#88c0d0","#5e81ac","#a3be8c"]},{id:"one-dark",label:"One Dark",group:"dark",swatches:["#282c34","#21252b","#3a3f4b","#61afef","#c678dd","#98c379"]},{id:"dracula",label:"Dracula",group:"dark",swatches:["#282a36","#343746","#44475a","#ff79c6","#8be9fd","#50fa7b"]},{id:"monokai",label:"Monokai",group:"dark",swatches:["#272822","#2d2e27","#3e3d32","#66d9ef","#a1efe4","#a6e22e"]},{id:"gruvbox",label:"Gruvbox",group:"dark",swatches:["#282828","#3c3836","#504945","#fe8019","#83a598","#b8bb26"]},{id:"solarized-dark",label:"Solarized Dark",group:"dark",swatches:["#002b36","#073642","#0b4b5a","#268bd2","#2aa198","#859900"]},{id:"everforest-dark",label:"Everforest Dark",group:"dark",swatches:["#2b3339","#323c41","#3a464c","#a7c080","#7fbbb3","#a7c080"]},{id:"catppuccin-latte",label:"Catppuccin Latte",group:"light",swatches:["#eff1f5","#e6e9ef","#ccd0da","#8839ef","#1e66f5","#40a02b"]},{id:"rose-pine-dawn",label:"Rose Pine Dawn",group:"light",swatches:["#faf4ed","#fffaf3","#f2e9e1","#907aa9","#56949f","#286983"]},{id:"one-light",label:"One Light",group:"light",swatches:["#fafafa","#ffffff","#e5e5e6","#4078f2","#a626a4","#50a14f"]},{id:"everforest-light",label:"Everforest Light",group:"light",swatches:["#fdf6e3","#fffbef","#e8e0cc","#4f8f5a","#3a94c5","#4f8f5a"]},{id:"solarized-light",label:"Solarized Light",group:"light",swatches:["#fdf6e3","#eee8d5","#e3ddc9","#268bd2","#2aa198","#859900"]},{id:"light",label:"Light",group:"light",swatches:["#f7f7fb","#ffffff","#e6e8f0","#e94560","#2563eb","#16a34a"]}];Tj.map(e=>({id:e.id,label:e.label}));function YC(e){return`theme-${String(e||"").trim()||"dark"}`}function nb(e){try{const t=document.documentElement,n=Array.from(t.classList).filter(r=>r.startsWith("theme-"));for(const r of n)t.classList.remove(r);t.classList.add(YC(e))}catch{}}const $w=[{id:"sm",label:"Small",scale:.9},{id:"md",label:"Medium",scale:1},{id:"lg",label:"Large",scale:1.1},{id:"xl",label:"Extra Large",scale:1.2}],Cw=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function XC(e){const t=String(e).trim();return $w.find(n=>n.id===t)||$w[1]}function ZC(e){const t=String(e).trim();return Cw.find(n=>n.id===t)||Cw[1]}function sb(e){try{const t=document.documentElement,n=XC(e.font_scale||"md"),r=ZC(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(r.density))}catch{}}const fy={sm:"(max-width: 767.98px)",md:"(max-width: 1023.98px)",short:"(max-height: 500px)"};function QC(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function rb(e){const[t,n]=p.useState(()=>QC(e));return p.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(e),i=()=>n(r.matches);return i(),typeof r.addEventListener=="function"?r.addEventListener("change",i):r.addListener(i),()=>{typeof r.removeEventListener=="function"?r.removeEventListener("change",i):r.removeListener(i)}},[e]),t}let _h=null;function e2(e,t){const n=Math.max(0,Math.round(e));if(!(t.scale<=1.01))return{vvHeight:n,keyboardInset:0};const r=Math.max(0,Math.min(n,Math.round(t.height))),i=Math.max(0,Math.round(e-t.height-Math.max(0,t.offsetTop)));return{vvHeight:r,keyboardInset:i}}function t2(){if(_h)return _h;if(typeof window>"u"||typeof document>"u")return()=>{};const e=window.visualViewport;if(!e)return()=>{};const t=document.documentElement;let n=0;const r=()=>{n=0;const{vvHeight:o,keyboardInset:u}=e2(window.innerHeight,{height:e.height,offsetTop:e.offsetTop,scale:e.scale||1});t.style.setProperty("--vv-height",`${o}px`),t.style.setProperty("--keyboard-inset",`${u}px`)},i=()=>{n||(n=window.requestAnimationFrame(r))};return r(),e.addEventListener("resize",i),e.addEventListener("scroll",i),window.addEventListener("orientationchange",i),_h=()=>{e.removeEventListener("resize",i),e.removeEventListener("scroll",i),window.removeEventListener("orientationchange",i),n&&window.cancelAnimationFrame(n),t.style.removeProperty("--vv-height"),t.style.removeProperty("--keyboard-inset"),_h=null},_h}var wg=Aj();function pd(...e){return e.filter(Boolean).join(" ")}function Br({value:e,options:t,placeholder:n="Select…",disabled:r=!1,loading:i=!1,searchable:o=!0,searchPlaceholder:u="Search…",allowCustom:l=!1,clearable:d=!1,minPopoverWidth:h=240,variant:m="panel",className:_,triggerClassName:g,ariaLabel:y,id:b,includeValueOption:k=!1,onOpen:x,customOptionLabel:N,validateCustomValue:$,onChange:E,renderOption:S,renderValue:P}){const D=p.useRef(null),R=p.useRef(null),I=p.useRef(null),W=p.useRef(x),G=p.useId(),K=b||`af-select-${G.replace(/[^a-zA-Z0-9_-]/g,"")}`,H=`${K}-listbox`,[M,A]=p.useState(!1),[O,L]=p.useState(""),[V,J]=p.useState(0),[U,te]=p.useState("bottom"),[z,ne]=p.useState({left:0,top:0,width:0});p.useEffect(()=>{W.current=x},[x]);const se=p.useMemo(()=>{if(!k)return t;const $e=String(e??"").trim();return!$e||t.some(Le=>Le.value===$e)?t:[...t,{value:$e,label:$e}]},[k,t,e]),de=p.useMemo(()=>{const $e=String(e??"");return se.find(Le=>Le.value===$e)||null},[se,e]),be=p.useMemo(()=>(de==null?void 0:de.label)||String(e||"").trim()||"",[de,e]),Me=p.useMemo(()=>{const $e=O.trim().toLowerCase();return $e?se.filter(Le=>Le.label.toLowerCase().includes($e)||Le.value.toLowerCase().includes($e)):se},[se,O]),je=p.useMemo(()=>{if(!l)return null;const $e=O.trim();if(!$e||se.some(Q=>Q.value===$e))return null;const ce=($==null?void 0:$($e,{options:se}))||"";return{value:$e,label:N?N($e):`Use "${$e}"`,disabled:!!ce,reason:ce}},[l,N,se,O,$]),ae=p.useMemo(()=>{const $e=je?[je,...Me]:Me;if($e.length>0)return $e;const Le=String(e??"").trim();return i&&Le?[{value:Le,label:be||Le}]:$e},[je,Me,i,be,e]),xe=p.useCallback(()=>{const $e=D.current;if(!$e)return;const Le=$e.getBoundingClientRect(),ce=Math.max(Le.width,h),Q=Math.max(8,Math.min(Le.left,window.innerWidth-ce-8)),_e=window.innerHeight-Le.bottom,le=Le.top,Se=_e>=220||_e>=le?"bottom":"top";te(Se);const pe=Se==="bottom"?Le.bottom+6:Le.top-6;ne({left:Q,top:pe,width:ce})},[h]),Ae=p.useCallback(()=>{A(!1),L("")},[]);p.useEffect(()=>{var $e;M&&(($e=W.current)==null||$e.call(W))},[M]),p.useEffect(()=>{if(!M)return;xe();const $e=()=>xe();return window.addEventListener("resize",$e),window.addEventListener("scroll",$e,!0),()=>{window.removeEventListener("resize",$e),window.removeEventListener("scroll",$e,!0)}},[M,xe]),p.useEffect(()=>{if(!M)return;const $e=Le=>{var Q,_e;const ce=Le.target;ce&&((Q=D.current)!=null&&Q.contains(ce)||(_e=R.current)!=null&&_e.contains(ce)||Ae())};return document.addEventListener("mousedown",$e,!0),()=>document.removeEventListener("mousedown",$e,!0)},[M,Ae]),p.useEffect(()=>{if(!M)return;const $e=Math.max(0,ae.findIndex(Le=>Le.value===e));J($e===-1?0:$e),o&&setTimeout(()=>{var Le;return(Le=I.current)==null?void 0:Le.focus()},0)},[M,o,e,ae]);const He=$e=>{var ce;const Le=ae.find(Q=>Q.value===$e);Le!=null&&Le.disabled||(E($e),Ae(),(ce=D.current)==null||ce.focus())},mt=$e=>{var Le,ce;if($e.key==="Escape")return $e.preventDefault(),Ae(),(Le=D.current)==null||Le.focus(),!0;if($e.key==="Tab")return Ae(),(ce=D.current)==null||ce.focus(),!1;if($e.key==="ArrowDown")return $e.preventDefault(),J(Q=>Math.min(Q+1,Math.max(0,ae.length-1))),!0;if($e.key==="ArrowUp")return $e.preventDefault(),J(Q=>Math.max(Q-1,0)),!0;if($e.key==="Home")return $e.preventDefault(),J(0),!0;if($e.key==="End")return $e.preventDefault(),J(Math.max(0,ae.length-1)),!0;if($e.key==="Enter"){$e.preventDefault();const Q=ae[V];return Q&&He(Q.value),!0}return!1},nt=$e=>{if(!r){if(M){if(mt($e))return;if($e.key===" "&&!o){$e.preventDefault();const Le=ae[V];Le&&He(Le.value)}return}($e.key==="Enter"||$e.key===" "||$e.key==="ArrowDown"||$e.key==="ArrowUp")&&($e.preventDefault(),A(!0))}},rt=!!String(e||"").trim(),ze=rt?be:n,Ve=je!=null&&je.disabled?je.reason||"Unavailable":"",ct=M&&ae.length>0?`${K}-opt-${V}`:void 0,Qe=s.jsx("span",{className:pd("af-select-value",!rt&&"af-select-value--placeholder"),children:i&&!rt?"Loading…":ze}),Dt=P?P(de,String(e||"")):Qe;return s.jsxs("span",{className:pd("af-select",m==="pin"?"af-select--pin":"af-select--panel",_),children:[s.jsxs("button",{ref:D,id:K,type:"button",className:pd("af-select-trigger",d&&rt&&"af-select-trigger--clearable",g),disabled:r,onMouseDown:$e=>$e.stopPropagation(),onClick:$e=>{$e.stopPropagation(),!r&&A(Le=>!Le)},onKeyDown:nt,role:o?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":M,"aria-controls":M?H:void 0,"aria-activedescendant":o?void 0:ct,"aria-label":y,children:[Dt,s.jsx("span",{className:pd("af-select-caret",M&&"af-select-caret--open"),children:"▾"})]}),d&&rt?s.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:r,onMouseDown:$e=>{$e.preventDefault(),$e.stopPropagation()},onClick:$e=>{var Le;$e.preventDefault(),$e.stopPropagation(),E(""),Ae(),(Le=D.current)==null||Le.focus()},title:"Clear",children:"×"}):null,M?wg.createPortal(s.jsxs("div",{ref:R,className:pd("af-select-popover",U==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${z.left}px`,top:`${z.top}px`,width:`${z.width}px`},onMouseDown:$e=>$e.stopPropagation(),onClick:$e=>$e.stopPropagation(),onWheel:$e=>$e.stopPropagation(),onKeyDown:mt,tabIndex:-1,children:[o?s.jsxs("div",{className:"af-select-search",children:[s.jsx("input",{ref:I,className:"af-select-search-input",value:O,onChange:$e=>L($e.target.value),placeholder:u,onKeyDown:mt,role:"combobox","aria-expanded":!0,"aria-controls":H,"aria-activedescendant":ct,"aria-invalid":!!Ve,"aria-describedby":Ve?`${K}-custom-error`:void 0}),Ve?s.jsx("div",{id:`${K}-custom-error`,className:"af-select-custom-error",role:"alert",children:Ve}):null]}):null,s.jsx("div",{className:"af-select-options",role:"listbox",id:H,"aria-label":y,children:i&&ae.length===0?s.jsx("div",{className:"af-select-empty",children:"Loading…"}):ae.length===0?s.jsx("div",{className:"af-select-empty",children:"No results"}):ae.map(($e,Le)=>{var pe;const ce=$e.value===e,Q=Le===V,_e=String($e.group||"").trim(),le=Le>0?String(((pe=ae[Le-1])==null?void 0:pe.group)||"").trim():"",Se=!!_e&&_e!==le;return s.jsxs(Ee.Fragment,{children:[Se?s.jsx("div",{className:"af-select-group",role:"presentation",children:_e}):null,s.jsx("div",{id:`${K}-opt-${Le}`,role:"option","aria-selected":ce,className:pd("af-select-option",ce&&"af-select-option--selected",Q&&"af-select-option--highlighted",$e.disabled&&"af-select-option--disabled"),title:$e.disabled?$e.reason||"Unavailable":void 0,onMouseEnter:()=>J(Le),onMouseDown:dt=>{dt.preventDefault(),dt.stopPropagation()},onClick:()=>He($e.value),"aria-disabled":$e.disabled?!0:void 0,children:S?S($e,{selected:ce,highlighted:Q}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"af-select-option-label",children:[s.jsx("span",{children:$e.label}),$e.reason?s.jsx("small",{className:"af-select-option-reason",children:$e.reason}):null]}),ce?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},$e.value)})})]}),document.body):null]})}function n2(e){const t=new Set,n=[];for(const r of e||[]){if(!r||typeof r!="object")continue;const i=String(r.name||"").trim();!i||t.has(i)||(t.add(i),n.push({name:i,display_name:typeof r.display_name=="string"?r.display_name:void 0}))}return n.sort((r,i)=>r.name.localeCompare(i.name)),n}function s2(e){const t=new Set,n=[];for(const r of e||[]){const i=String(r||"").trim();!i||t.has(i)||(t.add(i),n.push(i))}return n.sort(),n}const Ew="Provided by connected pin";function Mj(e){const t=e.disabled===!0,n=e.layout||"stack",r=e.allowGatewayDefault!==!1,i=String(e.gatewayDefaultLabel||"(gateway default)"),o=String(e.providerLabel||"Provider"),u=String(e.modelLabel||"Model"),l=String(e.providerPlaceholder||"(select)"),d=String(e.modelPlaceholder||"(select)"),h=String(e.provider||"").trim(),m=String(e.model||"").trim(),_=n2(e.providers),g=s2(e.models),y=typeof e.markSaved=="object"?e.markSaved:null,b=(S,P,D,R)=>e.markSaved&&!D&&!R&&(!y||y[P]===S)?`${S} (saved)`:S,k=t||!!e.loadingProviders,x=t||!!e.loadingModels,N=[...r?[{value:"",label:i}]:[],..._.map(S=>({value:S.name,label:S.display_name?`${S.display_name} (${S.name})`:S.name})),...e.markSaved&&h&&!_.some(S=>S.name===h)?[{value:h,label:b(h,"provider",e.loadingProviders,e.providerError)}]:[]],$=[...r?[{value:"",label:i}]:[],...g.map(S=>{var P;return{value:S,label:((P=e.modelDisplayNames)==null?void 0:P[S])||S}}),...e.markSaved&&m&&!g.includes(m)?[{value:m,label:b(m,"model",e.loadingModels,e.modelError)}]:[]],E=(S,P)=>s.jsxs("div",{className:"af-pmp__pinned","data-pinned":S,children:[s.jsx("span",{className:"af-pmp__pinned-text",children:Ew}),P?s.jsxs("span",{className:"mono muted",children:[" · ",P]}):null]});return s.jsxs("div",{className:e.className,style:n==="row"?{display:"flex",gap:"10px",flexWrap:"wrap",alignItems:"flex-start"}:{display:"flex",flexDirection:"column",gap:"10px"},children:[s.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[s.jsx("label",{children:o}),e.providerPinned?E("provider",h):s.jsx(Br,{value:h,options:N,placeholder:r?i:l,disabled:k,loading:!!e.loadingProviders,searchable:!0,allowCustom:e.allowCustomProvider===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:o,onChange:S=>e.onChange({provider:String(S||"").trim(),model:""})}),e.loadingProviders?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading providers…"}):null,e.providerError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.providerError}):null]}),s.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[s.jsx("label",{children:u}),e.modelPinned?E("model",m):s.jsx(Br,{value:m,options:$,placeholder:r?i:d,disabled:x,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:u,onChange:S=>e.onChange({provider:h,model:String(S||"").trim()})}),e.loadingModels?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading models…"}):null,e.modelError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.modelError}):null]})]})}function r2(e){if(e===!1||e&&typeof e=="object"&&e.mode==="off")return!1;if(!e||typeof e!="object")return;const t=e;if(!(t.mode!=="native_mtp"||!Number.isInteger(t.num_draft_tokens)||Number(t.num_draft_tokens)<1))return{mode:"native_mtp",num_draft_tokens:Number(t.num_draft_tokens),require_acceleration:!0}}function i2(e){var n;const t=(n=e==null?void 0:e.execution)==null?void 0:n.speculation;return!t||typeof t.supported!="boolean"?null:{supported:t.supported,ready:typeof t.ready=="boolean"?t.ready:null,reason:typeof t.reason=="string"?t.reason:null,supported_depths:t.supported&&Array.isArray(t.supported_depths)?[...new Set(t.supported_depths.filter(r=>typeof r=="number"&&Number.isInteger(r)&&r>0))]:[],default:Object.prototype.hasOwnProperty.call(t,"effective_default")?t.effective_default:t.default,requires_reload:typeof t.requires_reload=="boolean"?t.requires_reload:null}}function ib(e){const t=r2(e);return t===!1?"off":t?String(t.num_draft_tokens):""}function o2(e){if(e==="off")return!1;if(!(!/^\d+$/.test(e)||Number(e)<1))return{mode:"native_mtp",num_draft_tokens:Number(e),require_acceleration:!0}}function a2(e){const t=i2(e.capabilities),n=ib(e.value),r=(t==null?void 0:t.supported_depths.map(String))||[],i=ib(t==null?void 0:t.default),o=e.inheritLabel||"Workflow / Gateway default",u=i?`${o} (${i==="off"?"Off":`depth ${i}`})`:o,l=e.error||(e.loading?"Checking MTP capability…":t?t.reason||(t.requires_reload?"Model reload required before MTP can run.":t.ready===!1?"MTP is supported but not ready on this instance.":t.ready===null&&t.supported?"MTP support verified; loaded-instance readiness is unknown.":t.supported?"":"MTP is not supported on this model/backend."):"MTP capability unknown; no depth is assumed.");return s.jsxs("div",{className:"af-pmp__speculation",children:[s.jsx("label",{children:"MTP depth"}),s.jsx(Br,{ariaLabel:"MTP depth",value:n,placeholder:u,disabled:e.disabled||e.loading,options:[{value:"",label:u},{value:"off",label:"Off"},...r.map(d=>({value:d,label:`Depth ${d}`})),...n&&n!=="off"&&!r.includes(n)?[{value:n,label:`Depth ${n} (saved)`}]:[]],onChange:d=>e.onChange(o2(d))}),l&&!e.hideNote?s.jsx("div",{role:"status",className:"af-pmp__hint",children:l}):null]})}const Jh="api/gateway",ym="api/connection/gateway";function wt(e){const t=String(e||"");if(t.startsWith("/"))throw new Error(`gatewayApiPath takes a route relative to the gateway API, got ${JSON.stringify(t)}.`);return t?`${Jh}/${t}`:Jh}function Uv(e,t){const n=String(t||"");if(n.startsWith("/"))throw new Error(`joinBaseUrl takes a relative path, got ${JSON.stringify(n)}.`);let r=String(e??"");for(;r.endsWith("/");)r=r.slice(0,-1);return r?`${r}/${n}`:n}function l2(e){const t=String(e||""),n=`/${Jh}/`;if(!t.startsWith(n)||t.length===n.length)throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (expected ${JSON.stringify(n)}…).`);const r=t.slice(n.length).split(/[?#]/,1)[0];if(/\\|%2f|%5c/i.test(r))throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (encoded slash or backslash).`);for(const i of r.split("/")){const o=i.replace(/%2e/gi,".");if(o==="."||o==="..")throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (a "." or ".." segment).`)}return t.slice(1)}function c2(e){if(!e)return"";const t=[`${e.provider} / ${e.model}`];return e.reasoning&&t.push(`reasoning ${e.reasoning}`),e.speculation===!1?t.push("MTP off"):e.speculation&&t.push(`MTP depth ${e.speculation.num_draft_tokens}`),t.join(" · ")}function u2(e,t="Gateway default"){const n=c2(e);return n?`${t} · ${n}`:t}const d2="The gateway does not say which reasoning levels this model supports.",f2="Set anyway",h2="Reasoning and MTP choices appear when the gateway can describe the selected model.",m2="Reasoning choices appear when the gateway can describe the selected model.";function Rj(e){const t=e.disabled===!0,n=e.value||{provider:"",model:""},r=!String(n.provider||"").trim()&&!String(n.model||"").trim(),i=e.layout==="compact",o=e.pinned||{},u=!!(o.provider||o.model),[l,d]=p.useState(!r),h=i||u||!(r&&!l),m=r&&(i||u||!l),_=p.useRef(r);p.useEffect(()=>{r&&!_.current&&d(!1),_.current=r},[r]);const[g,y]=p.useState([]),[b,k]=p.useState(!1),[x,N]=p.useState(""),[$,E]=p.useState([]),[S,P]=p.useState({}),[D,R]=p.useState(!1),[I,W]=p.useState(""),G=p.useRef(e);G.current=e;const[K,H]=p.useState({status:"idle",value:null,message:""}),M=e.fetchGatewayDefault;p.useEffect(()=>{if(!M||t)return;let Le=!0;const ce=Q=>H(_e=>JSON.stringify(_e)===JSON.stringify(Q)?_e:Q);return H(Q=>Q.status==="idle"?{...Q,status:"loading"}:Q),M().then(Q=>{var _e;Le&&(Q?(_e=Q.warnings)!=null&&_e.length?ce({status:"unusable",value:Q,message:Q.warnings.join(" ")}):ce({status:"resolved",value:Q,message:""}):ce({status:"none",value:null,message:""}))}).catch(Q=>{Le&&ce({status:"error",value:null,message:String((Q==null?void 0:Q.message)||Q)})}),()=>{Le=!1}},[M,t]);const A=K.status==="resolved"?K.value:null,O=p.useRef({provider:String(n.provider||"").trim(),model:String(n.model||"").trim()});p.useEffect(()=>{if(!h||o.provider||t)return;let Le=!0;return k(!0),(async()=>{try{const ce=await G.current.fetchProviders();if(!Le)return;y(Array.isArray(ce)?ce:[]),N("")}catch(ce){if(!Le)return;y([]),N(`#FALLBACK provider discovery failed: ${String((ce==null?void 0:ce.message)||ce)}`)}finally{Le&&k(!1)}})(),()=>{Le=!1}},[h,o.provider,t]);const L=String(n.provider||"").trim();p.useEffect(()=>{if(!L||t||o.model){E([]),W(""),R(!1);return}let Le=!0;return E([]),R(!0),W(""),(async()=>{try{const ce=await G.current.fetchModels(L);if(!Le)return;const Q=[],_e={};for(const le of Array.isArray(ce)?ce:[]){const Se=typeof le=="string"?le:String((le==null?void 0:le.id)||"");Se&&(Q.push(Se),typeof le!="string"&&(le!=null&&le.label)&&le.label!==Se&&(_e[Se]=String(le.label)))}E(Q),P(_e)}catch(ce){if(!Le)return;E([]),W(`#FALLBACK model discovery failed: ${String((ce==null?void 0:ce.message)||ce)}`)}finally{Le&&R(!1)}})(),()=>{Le=!1}},[L,t,o.model]);const V=String(n.model||"").trim(),J=e.defaultModeLabel||"Gateway default",U=K.status==="none"?`${J} · none configured`:u2(A,J),te=e.customModeLabel||"Custom",z=e.effectiveDefault||(K.value?{provider:K.value.provider,model:K.value.model}:void 0),ne=L||(z==null?void 0:z.provider)||"",se=V||(L?"":z==null?void 0:z.model)||"",[de,be]=p.useState({levels:[],error:"",loading:!1}),[Me,je]=p.useState(!1),ae=!!e.fetchModelCapabilities,[xe,Ae]=p.useState();p.useEffect(()=>{let Le=!0;if(Ae(void 0),be({levels:[],error:"",loading:ae&&!!se}),!(!ae||!se||t))return G.current.fetchModelCapabilities(se,ne).then(ce=>{var pe;if(!Le)return;if(ce!=null&&ce.error)throw new Error(String(ce.error));Ae(ce);const Q=(ce==null?void 0:ce.capabilities)||ce||{},_e=Q.reasoning_levels||Q.thinking_levels,le=Array.isArray(_e)?[...new Set(_e.filter(dt=>typeof dt=="string"&&!!dt.trim()))]:[];!le.length&&Q.thinking_support===!0&&((pe=Q.thinking_control)!=null&&pe.prompt_disable_token)&&le.push("off","auto");const Se=typeof Q.thinking_support=="boolean"?Q.thinking_support:void 0;be({levels:le,support:Se,error:"",loading:!1})}).catch(ce=>{Le&&be({levels:[],error:String((ce==null?void 0:ce.message)||ce),loading:!1})}),()=>{Le=!1}},[ne,se,ae,t]),p.useEffect(()=>je(!1),[ne,se]);const He=e.inheritLabel||"Workflow / Gateway default",mt=m&&(A!=null&&A.reasoning)?`${He} (${A.reasoning})`:He,nt=!m||e.optionsInDefaultMode!==!1,rt=e.reasoningLadder?[...new Set(e.reasoningLadder.filter(Le=>typeof Le=="string"&&Le.trim()))]:null,ze=de.loading?"loading":de.levels.length||de.support===!0?"supported":de.support===!1?"unsupported":"unknown",Ve=e.unknownReasoning==="allow-override"&&!!(rt!=null&&rt.length),ct=String(n.reasoning||"").trim();let Qe=[],Dt=!1;if(!rt)Qe=de.levels.map(Le=>({value:Le,label:Le}));else if(ze==="supported"||ze==="loading"){const Le=de.levels;Qe=[...rt,...Le.filter(Q=>!rt.includes(Q))].map(Q=>!Le.length||Le.includes(Q)?{value:Q,label:Q}:{value:Q,label:Q,disabled:!0,reason:"This model does not advertise it"})}else ze==="unknown"&&Ve&&(Dt=!Me,Qe=rt.map(Le=>({value:Le,label:Le})));ct&&!Qe.some(Le=>Le.value===ct)&&Qe.push({value:ct,label:`${ct} (saved)`});const $e=(ae||Ve)&&(Qe.length>0||ze==="unknown"&&Ve);return s.jsxs("div",{className:`af-pmp${i?" af-pmp--compact":""}${e.className?` ${e.className}`:""}`,"data-gateway-default":M?K.status:void 0,children:[i||u?null:s.jsxs("div",{className:"af-pmp__seg",role:"tablist","aria-label":"Provider mode",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":m,className:`af-pmp__seg-btn${m?" is-active":""}`,onClick:()=>{d(!1),e.onChange({...n,provider:"",model:"",...ae?{reasoning:""}:{}})},disabled:t,title:U,"data-default-choice":"",children:U}),s.jsx("button",{type:"button",role:"tab","aria-selected":!m,className:`af-pmp__seg-btn${m?"":" is-active"}`,onClick:()=>{d(!0)},disabled:t,children:te})]}),K.status==="error"||K.status==="unusable"?s.jsx("div",{role:"status",className:"af-pmp__hint","data-gateway-default-problem":K.status,children:K.status==="error"?`The gateway's default could not be read: ${K.message}`:`Gateway warning: ${K.message}`}):null,h?s.jsx(Mj,{provider:L,model:V,providers:g,models:$,modelDisplayNames:S,markSaved:O.current,providerPinned:o.provider,modelPinned:o.model,disabled:t,loadingProviders:b,loadingModels:D,providerError:x||void 0,modelError:I||void 0,providerLabel:e.providerLabel,modelLabel:e.modelLabel,allowGatewayDefault:i,gatewayDefaultLabel:i?U:void 0,allowCustomProvider:e.allowCustom!==!1,allowCustomModel:e.allowCustom!==!1,onChange:Le=>e.onChange({...n,provider:Le.provider,model:Le.model,...ae?{reasoning:""}:{}})}):s.jsx("div",{className:"af-pmp__hint",children:e.defaultHint||"The gateway picks its configured default provider and model for this task."}),nt&&o.reasoning?s.jsxs("div",{className:"af-pmp__reasoning",children:[s.jsx("label",{children:e.reasoningLabel||"Reasoning effort"}),s.jsx("div",{className:"af-pmp__pinned","data-pinned":"reasoning",children:Ew})]}):nt&&$e?s.jsxs("div",{className:"af-pmp__reasoning","data-reasoning-state":ze,children:[s.jsx("label",{children:e.reasoningLabel||"Reasoning effort"}),s.jsx(Br,{ariaLabel:e.reasoningLabel||"Reasoning effort",placeholder:mt,value:n.reasoning||"",options:[{value:"",label:mt},...Qe],disabled:t||de.loading||Dt,onChange:Le=>e.onChange({...n,reasoning:Le})}),ze==="unknown"&&Ve?s.jsxs("div",{className:"af-pmp__hint","data-reasoning-unknown":"",children:[d2," ",s.jsxs("label",{className:"af-pmp__override",children:[s.jsx("input",{type:"checkbox",checked:Me,disabled:t,onChange:Le=>{je(Le.target.checked),!Le.target.checked&&n.reasoning&&e.onChange({...n,reasoning:""})}})," ",f2]})]}):null]}):null,nt&&e.enableSpeculation&&o.speculation?s.jsxs("div",{className:"af-pmp__speculation",children:[s.jsx("label",{children:"MTP depth"}),s.jsx("div",{className:"af-pmp__pinned","data-pinned":"speculation",children:Ew})]}):nt&&e.enableSpeculation?s.jsx(a2,{value:n.speculation,inheritLabel:He,onChange:Le=>e.onChange({...n,speculation:Le}),capabilities:xe,disabled:t,loading:de.loading,hideNote:!!de.error}):null,nt&&de.error?s.jsxs("div",{role:"status",className:"af-pmp__hint","data-discovery":"unavailable",children:[e.enableSpeculation?h2:m2,s.jsxs("details",{className:"af-pmp__details",children:[s.jsx("summary",{children:"Technical details"}),s.jsx("span",{children:de.error})]})]}):null]})}function ob(...e){return e.filter(Boolean).join(" ")}function _2({kicker:e="AbstractGateway connection",title:t="Connect to AbstractGateway",description:n="Sign in with the Gateway user token assigned by the Gateway admin.",statusLabel:r="Not signed in",statusTone:i="neutral",showGatewayUrl:o=!1,gatewayUrl:u="",gatewayUrlPlaceholder:l="http://127.0.0.1:8080",onGatewayUrlChange:d,userId:h,userPlaceholder:m="admin",onUserIdChange:_,token:g,tokenPlaceholder:y="Paste Gateway user token",showToken:b=!1,onTokenChange:k,onShowTokenChange:x,remember:N=!1,rememberLabel:$="Remember this browser",onRememberChange:E,loading:S=!1,submitting:P=!1,submitDisabled:D=!1,submitLabel:R="Sign in",submittingLabel:I="Signing in...",closeLabel:W="Close",signOutLabel:G="Sign out",showClose:K=!1,showSignOut:H=!1,error:M,message:A,className:O,onSubmit:L,onClose:V,onSignOut:J}){const U=S||P,te=U||D||!String(h||"").trim()||!String(g||"").trim(),z=ne=>{ne.preventDefault(),!te&&L()};return s.jsxs("form",{className:ob("af-gateway-signin",O),onSubmit:z,children:[s.jsxs("div",{className:"af-gateway-signin__hero",children:[s.jsxs("div",{children:[s.jsx("div",{className:"af-gateway-signin__kicker",children:e}),s.jsx("h2",{children:t}),n?s.jsx("p",{children:n}):null]}),s.jsx("div",{className:"af-gateway-signin__mark","aria-hidden":"true",children:"↔"})]}),s.jsx("div",{className:"af-gateway-signin__status-row",children:s.jsx("span",{className:ob("af-gateway-signin__status",`af-gateway-signin__status--${i}`),children:r})}),s.jsxs("div",{className:"af-gateway-signin__form",children:[o?s.jsxs(s.Fragment,{children:[s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-url",children:"Gateway URL"}),s.jsx("input",{id:"gateway-session-url",value:u,onChange:ne=>d==null?void 0:d(ne.target.value),placeholder:l,autoComplete:"url",disabled:U})]}):null,s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-user",children:"Gateway user"}),s.jsx("input",{id:"gateway-session-user",value:h,onChange:ne=>_(ne.target.value),placeholder:m,autoComplete:"username",disabled:U}),s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-token",children:"Gateway token"}),s.jsxs("div",{className:"af-gateway-signin__token-input",children:[s.jsx("input",{id:"gateway-session-token",type:b?"text":"password",value:g,onChange:ne=>k(ne.target.value),placeholder:y,autoComplete:"off","data-1p-ignore":"","data-lpignore":"true","data-bwignore":"",spellCheck:!1,disabled:U}),s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>x==null?void 0:x(!b),disabled:U,children:b?"Hide":"Show"})]}),s.jsxs("label",{className:"af-gateway-signin__checkbox",children:[s.jsx("input",{type:"checkbox",checked:!!N,onChange:ne=>E==null?void 0:E(ne.target.checked),disabled:U}),$]})]}),M?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:M}):null,!M&&A?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:A}):null,s.jsxs("div",{className:"af-gateway-signin__actions",children:[K?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:V,disabled:U,children:W}):null,H?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(J==null?void 0:J()),disabled:U,children:G}):null,s.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:te,children:P?I:R})]})]})}function p2(e){return e==="light"?"Light":"Dark"}function g2(e){const t=e.themes&&e.themes.length?e.themes:Tj,n=e.showSwatches!==!1,r=e.variant||"panel",i=p.useMemo(()=>{const u={};for(const l of t)u[l.id]=l;return u},[t]),o=p.useMemo(()=>t.map(u=>({value:u.id,label:u.label,group:p2(u.group)})),[t]);return s.jsx(Br,{value:e.value,options:o,placeholder:e.placeholder||"Select theme…",disabled:e.disabled===!0,searchable:!0,allowCustom:!1,clearable:!1,variant:r,className:e.className,triggerClassName:e.triggerClassName,onChange:u=>e.onChange(String(u||"").trim()),renderValue:(u,l)=>{const d=String(l||"").trim(),h=i[d],m=(h==null?void 0:h.label)||d||e.placeholder||"Select theme…",_=(h==null?void 0:h.swatches)||null,g=!d;return s.jsxs("span",{className:"af-theme-value",children:[s.jsx("span",{className:`af-theme-label ${g?"af-theme-label--placeholder":""}`.trim(),children:m}),n&&_?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:_.map((y,b)=>s.jsx("span",{className:"af-theme-swatch",style:{background:y}},`${d}:${b}`))}):null]})},renderOption:(u,l)=>{const d=String(u.value||"").trim(),h=i[d],m=(h==null?void 0:h.swatches)||null;return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"af-theme-option-label",children:u.label}),s.jsxs("span",{className:"af-theme-option-right",children:[n&&m?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:m.map((_,g)=>s.jsx("span",{className:"af-theme-swatch",style:{background:_}},`${d}:${g}`))}):null,l.selected?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function y2(e){const t=e.scales&&e.scales.length?e.scales:$w,n=e.variant||"panel",r=p.useMemo(()=>t.map(i=>({value:i.id,label:i.label})),[t]);return s.jsx(Br,{value:e.value,options:r,placeholder:e.placeholder||"Font size…",disabled:e.disabled===!0,searchable:!1,allowCustom:!1,clearable:!1,variant:n,className:e.className,triggerClassName:e.triggerClassName,onChange:i=>e.onChange(String(i||"").trim())})}function w2(e){const t=e.densities&&e.densities.length?e.densities:Cw,n=e.variant||"panel",r=p.useMemo(()=>t.map(i=>({value:i.id,label:i.label})),[t]);return s.jsx(Br,{value:e.value,options:r,placeholder:e.placeholder||"Header size…",disabled:e.disabled===!0,searchable:!1,allowCustom:!1,clearable:!1,variant:n,className:e.className,triggerClassName:e.triggerClassName,onChange:i=>e.onChange(String(i||"").trim())})}const v2=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function x2(e){switch(e){case"chat":return s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"});case"plus":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 5v14"}),s.jsx("path",{d:"M5 12h14"})]});case"history":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 7v5l3 3"})]});case"refresh":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M21 12a9 9 0 0 0-15.5-6.4L3 8"}),s.jsx("path",{d:"M3 3v5h5"}),s.jsx("path",{d:"M3 12a9 9 0 0 0 15.5 6.4L21 16"}),s.jsx("path",{d:"M21 21v-5h-5"})]});case"cog":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"activity":return s.jsx("path",{d:"M22 12h-4l-3 9L9 3l-3 9H2"});case"settings":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 6h16"}),s.jsx("circle",{cx:"8",cy:"6",r:"2"}),s.jsx("path",{d:"M4 12h16"}),s.jsx("circle",{cx:"16",cy:"12",r:"2"}),s.jsx("path",{d:"M4 18h16"}),s.jsx("circle",{cx:"10",cy:"18",r:"2"})]});case"user":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"8",r:"4"}),s.jsx("path",{d:"M4 21a8 8 0 0 1 16 0"})]});case"bot":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 2v3"}),s.jsx("rect",{x:"5",y:"6",width:"14",height:"14",rx:"3"}),s.jsx("circle",{cx:"9",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("path",{d:"M9 17h6"})]});case"paperclip":return s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a5.5 5.5 0 0 1-7.78-7.78l9.19-9.19a3.5 3.5 0 0 1 4.95 4.95l-9.2 9.19a1.5 1.5 0 0 1-2.12-2.12l8.49-8.48"});case"mic":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3z"}),s.jsx("path",{d:"M19 11a7 7 0 0 1-14 0"}),s.jsx("path",{d:"M12 18v4"}),s.jsx("path",{d:"M8 22h8"})]});case"speaker":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M11 5L6 9H2v6h4l5 4V5z"}),s.jsx("path",{d:"M15.5 8.5a5 5 0 0 1 0 7"}),s.jsx("path",{d:"M18 6a9 9 0 0 1 0 12"})]});case"pause":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"}),s.jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"})]});case"terminal":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2",ry:"2"}),s.jsx("path",{d:"M7 9l3 3-3 3"}),s.jsx("path",{d:"M12 15h5"})]});case"edit":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 20h9"}),s.jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"})]});case"download":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),s.jsx("path",{d:"M7 10l5 5 5-5"}),s.jsx("path",{d:"M12 15V3"})]});case"loader":return s.jsx("path",{d:"M21 12a9 9 0 1 1-3.3-6.9"});case"info":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 16v-4"}),s.jsx("circle",{cx:"12",cy:"8",r:"0.75",fill:"currentColor",stroke:"none"})]});case"warning":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 3l10 18H2L12 3z"}),s.jsx("path",{d:"M12 9v4"}),s.jsx("circle",{cx:"12",cy:"17",r:"0.75",fill:"currentColor",stroke:"none"})]});case"error":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M15 9l-6 6"}),s.jsx("path",{d:"M9 9l6 6"})]});case"copy":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M5 15V5a2 2 0 0 1 2-2h10"})]});case"check":return s.jsx("path",{d:"M20 6L9 17l-5-5"});case"x":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M18 6L6 18"}),s.jsx("path",{d:"M6 6l12 12"})]});case"chevronDown":return s.jsx("path",{d:"M6 9l6 6 6-6"});case"chevronRight":return s.jsx("path",{d:"M9 18l6-6-6-6"});case"trash":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 6h18"}),s.jsx("path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}),s.jsx("path",{d:"M6 6l1 16h10l1-16"}),s.jsx("path",{d:"M10 11v6"}),s.jsx("path",{d:"M14 11v6"})]});case"send":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M22 2L11 13"}),s.jsx("path",{d:"M22 2L15 22l-4-9-9-4 20-7z"})]});case"thumbsUp":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M7 10v11"}),s.jsx("path",{d:"M7 10l4.5-8a2 2 0 0 1 3.6 1.5L14 8h5.2a2 2 0 0 1 2 2.4l-1.6 8a2 2 0 0 1-2 1.6H7"})]});case"thumbsDown":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M17 14V3"}),s.jsx("path",{d:"M17 14l-4.5 8a2 2 0 0 1-3.6-1.5L10 16H4.8a2 2 0 0 1-2-2.4l1.6-8a2 2 0 0 1 2-1.6H17"})]});case"thumbsUpFilled":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M7 10v11"}),s.jsx("path",{d:"M7 10l4.5-8a2 2 0 0 1 3.6 1.5L14 8h5.2a2 2 0 0 1 2 2.4l-1.6 8a2 2 0 0 1-2 1.6H7z",fill:"currentColor",stroke:"none"})]});case"thumbsDownFilled":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M17 14V3"}),s.jsx("path",{d:"M17 14l-4.5 8a2 2 0 0 1-3.6-1.5L10 16H4.8a2 2 0 0 1-2-2.4l1.6-8a2 2 0 0 1 2-1.6H17z",fill:"currentColor",stroke:"none"})]});case"board":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"1.5",y:"2",width:"3.6",height:"12",rx:"1"}),s.jsx("rect",{x:"6.2",y:"2",width:"3.6",height:"8.5",rx:"1"}),s.jsx("rect",{x:"10.9",y:"2",width:"3.6",height:"5.5",rx:"1"})]});case"inbox":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M2 9.5 L4 3.5 h8 l2 6"}),s.jsx("path",{d:"M2 9.5 v3 h12 v-3"}),s.jsx("path",{d:"M2 9.5 h3.4 l1 1.6 h3.2 l1-1.6 H14"})]});case"server":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"2",y:"2.5",width:"12",height:"4.6",rx:"1.2"}),s.jsx("rect",{x:"2",y:"8.9",width:"12",height:"4.6",rx:"1.2"}),s.jsx("circle",{cx:"4.6",cy:"4.8",r:"0.8",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"4.6",cy:"11.2",r:"0.8",fill:"currentColor",stroke:"none"})]});case"agent":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"4.5",width:"10",height:"8",rx:"2"}),s.jsx("path",{d:"M8 4.5V2.2"}),s.jsx("circle",{cx:"8",cy:"1.8",r:"0.9",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"5.8",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"10.2",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"})]});case"playCircle":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),s.jsx("path",{d:"M6.5 5.6 L11 8 L6.5 10.4 Z",fill:"currentColor",stroke:"none"})]});case"list":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M2.5 4h11"}),s.jsx("path",{d:"M2.5 8h11"}),s.jsx("path",{d:"M2.5 12h7"})]});case"gear":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"8",cy:"8",r:"2.2"}),s.jsx("path",{d:"M8 1.6v2"}),s.jsx("path",{d:"M8 12.4v2"}),s.jsx("path",{d:"M1.6 8h2"}),s.jsx("path",{d:"M12.4 8h2"}),s.jsx("path",{d:"M3.5 3.5l1.4 1.4"}),s.jsx("path",{d:"M11.1 11.1l1.4 1.4"}),s.jsx("path",{d:"M12.5 3.5l-1.4 1.4"}),s.jsx("path",{d:"M4.9 11.1l-1.4 1.4"})]});case"sparkle":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"}),s.jsx("path",{d:"M18.5 15.5l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8z"})]});case"contrast":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 3a9 9 0 0 1 0 18z",fill:"currentColor",stroke:"none"})]});case"logout":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),s.jsx("path",{d:"M16 17l5-5-5-5"}),s.jsx("path",{d:"M21 12H9"})]});case"play":return s.jsx("path",{d:"M7 4.5v15a1 1 0 0 0 1.5.86l12-7.5a1 1 0 0 0 0-1.72l-12-7.5A1 1 0 0 0 7 4.5z",fill:"currentColor",stroke:"none"});case"stop":return s.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2",fill:"currentColor",stroke:"none"});case"folder":return s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"});case"file":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("path",{d:"M14 2v6h6"})]});case"archive":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),s.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),s.jsx("path",{d:"M10 12h4"})]});case"unarchive":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),s.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),s.jsx("path",{d:"M12 18v-6"}),s.jsx("path",{d:"m9 14 3-3 3 3"})]});case"clock":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 6v6h4"})]});case"book":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M2 4h6a4 4 0 0 1 4 4v13a3 3 0 0 0-3-3H2z"}),s.jsx("path",{d:"M22 4h-6a4 4 0 0 0-4 4v13a3 3 0 0 1 3-3h7z"})]});case"compose":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),s.jsx("path",{d:"M18.4 2.6a2.1 2.1 0 0 1 3 3L12 15l-4 1 1-4z"})]});case"image":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("circle",{cx:"9",cy:"9",r:"2"}),s.jsx("path",{d:"M21 15l-3.1-3.1a2 2 0 0 0-2.8 0L6 21"})]});case"video":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"2",y:"6",width:"14",height:"12",rx:"2"}),s.jsx("path",{d:"M16 10.5l5.2-3.1a.5.5 0 0 1 .8.4v8.4a.5.5 0 0 1-.8.4L16 13.5"})]});case"camera":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3z"}),s.jsx("circle",{cx:"12",cy:"13",r:"3"})]});case"music":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M9 18V5l12-2v13"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("circle",{cx:"18",cy:"16",r:"3"})]});case"database":return s.jsxs(s.Fragment,{children:[s.jsx("ellipse",{cx:"12",cy:"5",rx:"9",ry:"3"}),s.jsx("path",{d:"M3 5v14a9 3 0 0 0 18 0V5"}),s.jsx("path",{d:"M3 12a9 3 0 0 0 18 0"})]});case"branch":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M6 3v12"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]});case"loop":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M17 2l4 4-4 4"}),s.jsx("path",{d:"M3 11v-1a4 4 0 0 1 4-4h14"}),s.jsx("path",{d:"M7 22l-4-4 4-4"}),s.jsx("path",{d:"M21 13v1a4 4 0 0 1-4 4H3"})]});case"variable":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M8 21s-4-3-4-9 4-9 4-9"}),s.jsx("path",{d:"M16 3s4 3 4 9-4 9-4 9"}),s.jsx("path",{d:"M15 9l-6 6"}),s.jsx("path",{d:"M9 9l6 6"})]});case"minus":return s.jsx("path",{d:"M5 12h14"});case"divide":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"6",r:"1.25",fill:"currentColor",stroke:"none"}),s.jsx("path",{d:"M5 12h14"}),s.jsx("circle",{cx:"12",cy:"18",r:"1.25",fill:"currentColor",stroke:"none"})]});case"function":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("path",{d:"M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3"}),s.jsx("path",{d:"M9 11.2h5.7"})]});case"zoomIn":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("path",{d:"M21 21l-4.35-4.35"}),s.jsx("path",{d:"M11 8v6"}),s.jsx("path",{d:"M8 11h6"})]});case"zoomOut":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("path",{d:"M21 21l-4.35-4.35"}),s.jsx("path",{d:"M8 11h6"})]});case"fitView":return s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),s.jsx("path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}),s.jsx("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}),s.jsx("path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"})]});case"lock":return s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"4",y:"11",width:"16",height:"10",rx:"2"}),s.jsx("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"})]});default:return null}}function qe({name:e,size:t=16,className:n,title:r,...i}){const o=r?void 0:!0,u=v2.has(e);return s.jsxs("svg",{width:t,height:t,viewBox:u?"0 0 16 16":"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:u?1.4:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,"aria-hidden":o,role:r?"img":"presentation",...i,children:[r?s.jsx("title",{children:r}):null,x2(e)]})}function b2(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function k2(e){return b2(e)?!e.checked:null}let j2=0;function Di(e){const{label:t,checked:n,onChange:r,description:i,reasonVisible:o=!0,describedBy:u,hint:l,busy:d=!1,variant:h="inline",ariaLabel:m,className:_,id:g,action:y}=e,b=String(e.unavailableReason||"").trim(),k=!!b,x=u||(g?`${g}-reason`:k?`af-switch-reason-${++j2}`:void 0),N=["af-switch",h==="row"?"af-switch--row":h==="sm"?"af-switch--sm":"",k?"af-switch--unavailable":"",_||""].filter(Boolean).join(" "),$=S=>{const P=k2({checked:n,unavailableReason:b,busy:d});if(P===null){S.preventDefault();return}r==null||r(P)},E=s.jsxs("button",{type:"button",role:"switch",id:g,className:N,"data-action":y,"aria-checked":n?"true":"false","aria-disabled":k?"true":void 0,"aria-describedby":k?x:void 0,"aria-busy":d?"true":void 0,"aria-label":m,"aria-description":i?void 0:l,title:k?l?`${b}
41
+ ${l}`:b:l,onClick:$,children:[s.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:s.jsx("span",{className:"af-switch__thumb"})}),s.jsxs("span",{className:"af-switch__text",children:[s.jsx("span",{className:"af-switch__label",children:t}),i?s.jsx("span",{className:"af-switch__desc",children:i}):null]})]});return!k||u?E:s.jsxs("span",{className:h==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[E,s.jsx("span",{id:x,className:o?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:b})]})}function S2(e){const t=String(e.unavailableReason||"").trim(),n=["af-switch","af-switch--native",e.variant==="row"?"af-switch--row":"",t?"af-switch--unavailable":""].filter(Boolean).join(" "),r=t?`${e.id||e.name}-reason`:void 0,i=s.jsxs("label",{className:n,title:t||void 0,"data-action":e.action,children:[s.jsx("input",{type:"checkbox",role:"switch",className:"af-switch__input",id:e.id,name:e.name,defaultChecked:e.defaultChecked,onChange:o=>{var u;return(u=e.onChange)==null?void 0:u.call(e,o.target.checked)},disabled:!!t,"aria-describedby":r}),s.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:s.jsx("span",{className:"af-switch__thumb"})}),s.jsx("span",{className:"af-switch__text",children:s.jsx("span",{className:"af-switch__label",children:e.label})})]});return t?s.jsxs("span",{className:e.variant==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[i,s.jsx("span",{id:r,className:"af-switch__reason",children:t})]}):i}const N2=150,Wv="data-af-tip";function $2(e,t,n,r=6,i=8){let o="top",u=e.top-r-t.height;if(u<i){const h=e.bottom+r;(h+t.height<=n.height-i||n.height-e.bottom>e.top)&&(u=h,o="bottom")}let d=(e.left+e.right)/2-t.width/2;return d=Math.max(i,Math.min(d,n.width-i-t.width)),u=Math.max(i,Math.min(u,n.height-i-t.height)),{top:Math.round(u),left:Math.round(d),side:o}}let ab=0;function Lj(e){return e?String(e.getAttribute(Wv)||"").trim():""}function hy(e,t){const n=e;if(!n||typeof n.closest!="function")return null;const r=n.closest(`[${Wv}]`);return!r||!t.contains(r)||!Lj(r)?null:r}function C2(e,t={}){if(!e)throw new Error("bindAfTooltips: a root (document or element) is required");const n=e.nodeType===9?e:e.ownerDocument,r=n.defaultView||globalThis,i=typeof t.delayMs=="number"&&t.delayMs>=0?t.delayMs:N2;ab+=1;const o=n.createElement("div");o.className="af-tooltip",o.setAttribute("role","tooltip");const u=`af-tooltip-${ab}`;o.setAttribute("id",u),o.hidden=!0,(n.body||n.documentElement).appendChild(o);let l=null,d=null,h=null,m=null,_=!1,g=null;const y=()=>{h&&clearTimeout(h),h=null,d=null},b=()=>{m&&clearTimeout(m),m=null},k=()=>{if(!l)return;const O=l.getBoundingClientRect(),L=o.getBoundingClientRect(),V=$2(O,{width:L.width,height:L.height},{width:r.innerWidth,height:r.innerHeight});o.style.top=`${V.top}px`,o.style.left=`${V.left}px`,o.setAttribute("data-side",V.side)},x=()=>{if(y(),b(),!l)return;String(l.getAttribute("aria-describedby")||"").split(/\s+/).includes(u)&&(g?l.setAttribute("aria-describedby",g):l.removeAttribute("aria-describedby")),g=null,l=null,o.hidden=!0,o.textContent=""},N=O=>{y(),b(),l&&l!==O&&x();const L=Lj(O);if(!L||O.isConnected===!1)return;if(l=O,o.textContent=L,o.hidden=!1,String(O.getAttribute("aria-label")||"").trim()!==L){const J=O.getAttribute("aria-describedby");g=J&&J!==u?J:null,O.setAttribute("aria-describedby",g?`${g} ${u}`:u)}k()},$=O=>{b(),l!==O&&d!==O&&(y(),d=O,h=setTimeout(()=>{const L=d;h=null,d=null,L&&N(L)},i))},E=()=>{y(),l&&(b(),m=setTimeout(x,100))},S=O=>{try{if(typeof O.matches=="function")return O.matches(":focus-visible")}catch{}return _},P=O=>{if(O.pointerType==="touch")return;if(o.contains(O.target)){b();return}const V=hy(O.target,e);V&&$(V)},D=O=>{const V=O.relatedTarget||null;if(!(V&&(o.contains(V)||l&&l.contains(V)||d&&d.contains(V)))){if(d&&!l){y();return}l&&E()}},R=O=>{const L=O.relatedTarget||null;L&&(o.contains(L)||l&&l.contains(L))||E()},I=O=>{const L=hy(O.target,e);L&&S(L)&&$(L)},W=O=>{const L=hy(O.target,e);L&&(L===l||L===d)&&x()},G=()=>{_=!1,x()},K=O=>{if(O.key==="Escape"||O.key==="Esc"){l?(O.preventDefault(),x()):y();return}!O.metaKey&&!O.ctrlKey&&!O.altKey&&(_=!0)},H=()=>x(),M=e;M.addEventListener("pointerover",P),M.addEventListener("pointerout",D),M.addEventListener("focusin",I),M.addEventListener("focusout",W),o.addEventListener("pointerover",P),o.addEventListener("pointerout",R),n.addEventListener("pointerdown",G,!0),r.addEventListener("keydown",K,!0),r.addEventListener("scroll",H,!0),r.addEventListener("resize",H);let A=!1;return()=>{A||(A=!0,x(),M.removeEventListener("pointerover",P),M.removeEventListener("pointerout",D),M.removeEventListener("focusin",I),M.removeEventListener("focusout",W),o.removeEventListener("pointerover",P),o.removeEventListener("pointerout",R),n.removeEventListener("pointerdown",G,!0),r.removeEventListener("keydown",K,!0),r.removeEventListener("scroll",H,!0),r.removeEventListener("resize",H),o.parentNode&&o.parentNode.removeChild(o))}}const H_=new WeakMap;function E2(e){let t=H_.get(e);t||(t={count:0,release:C2(e)},H_.set(e,t)),t.count+=1;let n=!1;return()=>{if(n)return;n=!0;const r=H_.get(e);r&&(r.count-=1,r.count<=0&&(r.release(),H_.delete(e)))}}function tf(){p.useEffect(()=>{if(!(typeof document>"u"))return E2(document)},[])}function lb(e){tf();const t=Ee.Children.only(e.children),n=String(e.content||"").trim();return n?Ee.cloneElement(t,{[Wv]:n}):t}async function Aw(e=ym){const t=await fetch(e),n=await t.json().catch(()=>null);if(!t.ok){const r=n&&typeof n=="object"&&n.detail?String(n.detail):`HTTP ${t.status}`;throw new Error(r)}return n}async function A2(e,t=ym){const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await n.json().catch(()=>null);if(!n.ok){const i=r&&typeof r=="object"&&r.detail?String(r.detail):`HTTP ${n.status}`;throw new Error(i)}return r}async function Ij(e=ym){const t=await fetch(e,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({})),r=n&&typeof n=="object"&&n.detail?String(n.detail):`HTTP ${t.status}`;throw new Error(r)}}function my(e){let t=String(e||"").trim();for(let n=0;n<2&&t;n+=1){try{const o=JSON.parse(t);if(typeof o=="string"&&o!==t){t=o.trim();continue}}catch{}const r=t[0],i=t[t.length-1];if(r==='"'&&i==='"'||r==="'"&&i==="'"){t=t.slice(1,-1).trim();continue}break}return t.replace(/\/+$/,"")}function Oj(e){var o,u;if(!e)return{label:"Signed out",tone:"warn"};if(!e.has_session)return{label:"Signed out",tone:"warn"};const t=e.gateway||{},n=(o=t.principal)==null?void 0:o.user_id,r=(u=t.principal)==null?void 0:u.runtime_id;if(t.ok&&n)return{label:`Signed in as ${n}${r?` · runtime ${r}`:""}`,tone:"ok"};if(t.ok)return{label:"Signed in",tone:"ok"};const i=t.error||t.detail;return typeof i=="string"&&i.trim()?{label:"Session rejected — sign in again",tone:"err"}:{label:"Sign in required",tone:"err"}}function T2(e){const t=e.connectionPath||ym,[n,r]=p.useState(!1),[i,o]=p.useState(!1),[u,l]=p.useState(null),[d,h]=p.useState(!1);p.useEffect(()=>{e.isOpen||h(!1)},[e.isOpen]);const[m,_]=p.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[g,y]=p.useState("admin"),[b,k]=p.useState(""),[x,N]=p.useState(!1),[$,E]=p.useState(!0),[S,P]=p.useState(""),[D,R]=p.useState(""),I=p.useMemo(()=>Oj(u),[u]),W=M=>{var A;l(M),(A=e.onStatusChange)==null||A.call(e,M)},G=p.useRef(!1);if(p.useEffect(()=>{var A;if(!e.isOpen)return;const M=!G.current;if(G.current=!0,M&&e.initialStatus!==void 0&&e.initialStatus!==null){const O=e.initialStatus;W(O),typeof O.gateway_url=="string"&&O.gateway_url.trim()&&_(my(O.gateway_url));const L=(A=O.gateway)==null?void 0:A.principal;L!=null&&L.user_id&&y(L.user_id);return}r(!0),P(""),Aw(t).then(O=>{var V;W(O),typeof O.gateway_url=="string"&&O.gateway_url.trim()&&_(my(O.gateway_url));const L=(V=O.gateway)==null?void 0:V.principal;L!=null&&L.user_id&&y(L.user_id)}).catch(O=>P(`Failed to load connection status: ${String((O==null?void 0:O.message)||O)}`)).finally(()=>r(!1))},[e.isOpen]),p.useEffect(()=>{if(!e.isOpen)return;const M=A=>{A.key==="Escape"&&!A.defaultPrevented&&!e.blocking&&(A.preventDefault(),e.onClose())};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||d)return null;const K=async()=>{o(!0),P(""),R("");try{const M=my(m);_(M);const A=await A2({gateway_url:M,gateway_user_id:g,gateway_token:b,persist:$},t);W(A),k(""),h(!0),e.onClose()}catch(M){P(String((M==null?void 0:M.message)||M))}finally{o(!1)}},H=async()=>{o(!0),P(""),R("");try{await Ij(t),k("");const M=await Aw(t).catch(()=>null);W(M),R("Signed out. This browser no longer holds a gateway session.")}catch(M){P(String((M==null?void 0:M.message)||M))}finally{o(!1)}};return s.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:M=>{!e.blocking&&M.target===M.currentTarget&&e.onClose()},children:s.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:s.jsx(_2,{kicker:`${e.appName||"AbstractFramework"} connection`,title:"Connect this browser to AbstractGateway",description:"Sign in with a Gateway user token. The app exchanges it for an HTTP-only browser session and never stores the raw token.",statusLabel:I.label,statusTone:I.tone,showGatewayUrl:!0,gatewayUrl:m,onGatewayUrlChange:M=>_(M),userId:g,onUserIdChange:y,token:b,tokenPlaceholder:u!=null&&u.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:x,onTokenChange:k,onShowTokenChange:N,remember:$,rememberLabel:"Keep this browser signed in",onRememberChange:E,loading:n,submitting:i,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(u!=null&&u.has_session),onSignOut:H,error:S,message:D,onSubmit:K})})})}function Pj(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function M2(e){const t=e||{},n=t.connectionPath||ym,r=t.variant||"dismissable",i=p.useRef(t.onStatusChange);i.current=t.onStatusChange;const o=p.useRef(r);o.current=r;const u=p.useRef(!!t.autoOpenMidSession);u.current=!!t.autoOpenMidSession;const[l,d]=p.useState(null),[h,m]=p.useState("loading"),[_,g]=p.useState(!1),y=p.useRef(!1),b=p.useRef(!1),k=p.useRef("loading"),x=p.useRef("none"),N=p.useRef(!1),$=p.useRef(0),E=p.useCallback(A=>{var L;$.current+=1,d(A),(L=i.current)==null||L.call(i,A);const O=Pj(A);if(O)m("connected"),k.current="connected",y.current=!1,x.current="none",b.current||g(!1);else if(A!==null){const V=k.current;m("disconnected"),k.current="disconnected",V!=="disconnected"&&(x.current=N.current?"signout":V==="connected"?"mid":"boot");const J=o.current==="blocking"||x.current!=="mid"||u.current;!y.current&&J&&g(!0)}A!==null&&(b.current=O)},[]),S=p.useCallback(async()=>{const A=$.current;try{const O=await Aw(n);if($.current!==A)return;E(O)}catch{if($.current!==A)return;E(null)}},[n,E]),[P,D]=p.useState(!1),[R,I]=p.useState(null),W=p.useCallback(async()=>{D(!0),I(null),$.current+=1;let A=null;try{await Ij(n)}catch(O){A=String((O==null?void 0:O.message)||O||"Sign-out request failed")}N.current=!0;try{await S()}finally{N.current=!1}return I(A),D(!1),A===null&&k.current!=="connected"},[n,S]),G=p.useRef(!1);p.useEffect(()=>{G.current||(G.current=!0,S())},[S]);const K=p.useCallback(()=>{g(!0)},[]),H=p.useCallback(()=>{const A=k.current;r==="blocking"&&A==="disconnected"||(A==="disconnected"&&(y.current=!0),g(!1))},[r]),M=p.useMemo(()=>({isOpen:_,onClose:H,blocking:r==="blocking"&&h!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:l,onStatusChange:E}),[_,H,r,h,t.appName,n,t.defaultGatewayUrl,l,E]);return{status:l,phase:h,connected:h==="connected",modalOpen:_,signingOut:P,signOutError:R,openModal:K,refresh:S,signOut:W,modalProps:M}}function R2(){return globalThis.crypto}function L2(e){if(e.length<16)throw new Error("uuidV4FromBytes: needs 16 bytes");const t=Array.from(e.subarray(0,16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const n=t.map(r=>r.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function el(){const e=R2();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return L2(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function vg(e){return globalThis.isSecureContext!==!1?null:`This page is loaded over http, so ${e} is unavailable — open it over https (for example through tailscale serve; the gateway console's Network page explains how) or on the gateway's own computer.`}function I2(){return el()}function O2(){const e=[];try{if(typeof document>"u")return e;for(const t of String(document.cookie||"").split(";")){const n=t.indexOf("=");if(n<0||!t.slice(0,n).trim().endsWith("_gateway_csrf"))continue;const i=t.slice(n+1).trim();let o=i;try{o=decodeURIComponent(i)}catch{}o&&!e.includes(o)&&e.push(o)}}catch{}return e}async function P2(e){const t=e.commandsPath||wt("commands"),n=I2(),r=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),i=e.csrfToken!==void 0?[e.csrfToken]:O2();i.length===0&&i.push("");let o=null;for(const u of i){const l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...u?{"x-abstract-csrf":u}:{}},body:r}),d=await l.json().catch(()=>null);if(!l.ok){const h=d&&typeof d=="object"&&d.detail?String(d.detail):`HTTP ${l.status}`;if(o=new Error(h),l.status===403&&d&&typeof d=="object"&&d.reason_code==="csrf_required")continue;throw o}return{accepted:!!(d!=null&&d.accepted),duplicate:!!(d!=null&&d.duplicate),seq:Number((d==null?void 0:d.seq)??0)}}throw o||new Error("Steer submit failed")}function D2(e){const[t,n]=p.useState(""),[r,i]=p.useState({kind:"idle"}),o=p.useRef(!1),u=p.useRef(0);p.useEffect(()=>{u.current+=1,i({kind:"idle"})},[e.runId]);const l=!e.disabled&&t.trim().length>0&&r.kind!=="sending",d=p.useMemo(()=>e.parked?"Run is waiting — your guidance delivers at its next wake (steers do not wake runs).":"Delivers at the run's next loop boundary.",[e.parked]),h=async()=>{var y;const _=t.trim();if(!_||o.current||e.disabled)return;o.current=!0;const g=u.current;i({kind:"sending"});try{const b=e.submit?await e.submit(e.runId,_):await P2({runId:e.runId,guidance:_,commandsPath:e.commandsPath});if(u.current!==g)return;if(!b.accepted&&!b.duplicate){i({kind:"error",detail:"The gateway did not accept this steer (accepted=false)."});return}i({kind:"queued",seq:b.seq,duplicate:b.duplicate}),n(""),(y=e.onSent)==null||y.call(e,{...b,guidance:_})}catch(b){u.current===g&&i({kind:"error",detail:String((b==null?void 0:b.message)||b)})}finally{o.current=!1}},m=_=>{_.key==="Enter"&&(_.metaKey||_.ctrlKey)&&(_.preventDefault(),h())};return s.jsxs("div",{className:`af-steer${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"af-steer__row",children:[s.jsx("textarea",{className:"af-steer__input",value:t,rows:2,placeholder:e.placeholder||"Steer this run…","aria-label":e.ariaLabel||"Steer message",disabled:e.disabled||r.kind==="sending",onChange:_=>{n(_.target.value),(r.kind==="error"||r.kind==="queued")&&i({kind:"idle"})},onKeyDown:m}),s.jsx("button",{type:"button",className:"af-steer__send",disabled:!l,onClick:()=>void h(),title:"Send guidance (Cmd/Ctrl+Enter)",children:r.kind==="sending"?"Sending…":"Steer"})]}),s.jsx("div",{className:"af-steer__status",role:"status","aria-live":"polite",children:r.kind==="queued"?s.jsxs("span",{className:"af-steer__ok",children:[r.duplicate?`Already queued (seq ${r.seq}).`:`Queued (seq ${r.seq}).`," ",d," ","Watch for the steer_seen ack in the run ledger."]}):r.kind==="error"?s.jsx("span",{className:"af-steer__err",children:r.detail}):s.jsx("span",{className:"af-steer__hint",children:d})})]})}const _y={neutral:"var(--text-secondary)",muted:"var(--text-muted)",accent:"var(--accent)",info:"var(--info)",success:"var(--success)",warning:"var(--warning)",error:"var(--error)"},F2=/^var\(--[a-z0-9-]+\)$/i;function z2(e,t){const n=e||"neutral";if(n==="custom"){const r=String(t||"").trim();return F2.test(r)?r:_y.neutral}return _y[n]||_y.neutral}function Dj(e,t,n){return[e,`${e}--${t.tone||"neutral"}`,t.size==="sm"?`${e}--sm`:"",n||"",t.className||""].filter(Boolean).join(" ")}function Fj(e){return{"--af-chip-hue":z2(e.tone,e.hue)}}function cb(e){return s.jsxs("span",{className:Dj("af-chip",e,e.onRemove?"af-chip--removable":""),style:Fj(e),title:e.title,children:[s.jsx("span",{className:"af-chip__label",children:e.children}),e.onRemove?s.jsx("button",{type:"button",className:"af-chip__remove","aria-label":e.removeLabel||"Remove",onClick:t=>{var n;t.stopPropagation(),(n=e.onRemove)==null||n.call(e)},children:s.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.6",strokeLinecap:"round",children:[s.jsx("path",{d:"M18 6L6 18"}),s.jsx("path",{d:"M6 6l12 12"})]})}):null]})}function B2(e){return s.jsx("button",{type:"button",className:Dj("af-chip",e,"af-chip--button"),style:Fj(e),title:e.title,onClick:e.onClick,"aria-pressed":typeof e.pressed=="boolean"?e.pressed:void 0,"aria-expanded":typeof e.expanded=="boolean"?e.expanded:void 0,"aria-label":e.ariaLabel,disabled:e.disabled,tabIndex:e.tabIndex,children:s.jsx("span",{className:"af-chip__label",children:e.children})})}const U2='button:not(:disabled), [href], input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function W2(e,t=!1){if(!e)return null;const n=e.querySelector(".af-drawer__body")||e,r=n.querySelector("[data-autofocus]");return r||(t?e:n.querySelector("textarea:not(:disabled)")||n.querySelector(U2)||e)}function q2(){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}}function ub(e){return e==="auto"?"var(--af-topbar-h, 0px)":typeof e=="number"&&Number.isFinite(e)?e:0}function H2(e){const t=e.closeOnEscape!==!1,n=p.useRef(null);p.useEffect(()=>{if(!e.open||!t)return;const u=l=>{l.key!=="Escape"||l.defaultPrevented||(l.preventDefault(),e.onClose())};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e.open,t,e.onClose]);const r=p.useRef(null),i=e.manageFocus!==!1,o=p.useRef(!1);return p.useEffect(()=>{var h;if(!o.current){o.current=!0;return}if(!i||typeof document>"u")return;const u=n.current;if(e.open){if(r.current=document.activeElement,u&&u.contains(document.activeElement))return;const m=window.setTimeout(()=>{var _;(_=W2(u,q2()))==null||_.focus({preventScroll:!0})},0);return()=>window.clearTimeout(m)}const l=r.current;r.current=null;const d=document.activeElement;l&&l.isConnected&&(!d||d===document.body||u&&u.contains(d))&&((h=l.focus)==null||h.call(l,{preventScroll:!0}))},[e.open,i]),p.useEffect(()=>{const u=n.current;u&&(e.open?u.removeAttribute("inert"):u.setAttribute("inert",""))},[e.open]),s.jsxs(s.Fragment,{children:[e.backdrop&&e.open?s.jsx("div",{className:"af-drawer-backdrop","aria-hidden":"true",onClick:e.onClose,style:{top:ub(e.topOffset)}}):null,s.jsxs("div",{ref:n,className:`af-drawer${e.side==="left"?" af-drawer--left":""}${e.topOffset?" af-drawer--offset":""}${e.open?" af-drawer--open":""}${e.className?` ${e.className}`:""}`,style:{width:e.width||420,top:ub(e.topOffset),display:e.open?void 0:"none"},role:"complementary","aria-label":e.label,"aria-hidden":e.open?void 0:!0,tabIndex:-1,children:[e.title!==void 0?s.jsxs("div",{className:"af-drawer__header",children:[s.jsx("div",{className:"af-drawer__title",children:e.title}),s.jsxs("div",{className:"af-drawer__header-actions",children:[e.headerActions,s.jsx("button",{type:"button",className:"af-drawer__close","aria-label":"Close panel",onClick:e.onClose,children:"×"})]})]}):null,s.jsx("div",{className:"af-drawer__body",children:e.children})]})]})}function V2(e,t,n,r=4,i=8){let o=e.bottom+r,u=!1;if(o+t.height>n.height-i){const h=e.top-r-t.height;(h>=i||e.top>n.height-e.bottom)&&(o=h,u=!0)}let l=e.left,d=!1;return l+t.width>n.width-i&&(l=e.right-t.width,d=!0),l=Math.max(i,Math.min(l,n.width-i-t.width)),o=Math.max(i,o),{top:Math.round(o),left:Math.round(l),up:u,leftward:d}}let db=0;function G2(e,t,n={}){if(!e||!t)throw new Error("bindAfMenu: button and menu are required");const r=n.document||e.ownerDocument,i=r.defaultView||globalThis;t.getAttribute("id")||(db+=1,t.setAttribute("id",`af-menu-${db}`)),e.setAttribute("aria-haspopup","menu"),e.setAttribute("aria-expanded","false"),e.setAttribute("aria-controls",String(t.getAttribute("id"))),t.setAttribute("role","menu"),t.hidden=!0;const o=()=>{const E=Array.from(t.querySelectorAll(".af-menu__item")),S=E.filter(P=>!P.hidden&&!P.hasAttribute("disabled"));for(const P of E)P.setAttribute("role","menuitem"),P.setAttribute("tabindex","-1");return S};o();let u=!1;const l=()=>{if(!u)return;const E=e.getBoundingClientRect(),S=t.getBoundingClientRect(),P=V2(E,{width:S.width,height:S.height},{width:i.innerWidth,height:i.innerHeight});t.style.top=`${P.top}px`,t.style.left=`${P.left}px`,t.setAttribute("data-placement",`${P.up?"top":"bottom"}-${P.leftward?"end":"start"}`)},d=E=>{const S=o();if(!S.length)return;const P=(E%S.length+S.length)%S.length;S[P].focus({preventScroll:!0})},h=E=>{u||(u=!0,t.hidden=!1,e.setAttribute("aria-expanded","true"),l(),d(E),r.addEventListener("pointerdown",_,!0),r.addEventListener("mousedown",_,!0),i.addEventListener("scroll",l,!0),i.addEventListener("resize",g),i.addEventListener("keydown",k,!0),n.onOpen&&n.onOpen())},m=E=>{u&&(u=!1,t.hidden=!0,e.setAttribute("aria-expanded","false"),r.removeEventListener("pointerdown",_,!0),r.removeEventListener("mousedown",_,!0),i.removeEventListener("scroll",l,!0),i.removeEventListener("resize",g),i.removeEventListener("keydown",k,!0),E&&e.focus({preventScroll:!0}),n.onClose&&n.onClose())};function _(E){const S=E.target;S&&(t.contains(S)||e.contains(S))||m(!1)}function g(){m(!1)}const y=E=>{E.preventDefault(),u?m(!0):h(0)},b=E=>{E.key==="ArrowDown"||(E.key==="Enter"||E.key===" ")&&!u?(E.preventDefault(),h(0)):E.key==="ArrowUp"&&(E.preventDefault(),h(-1))},k=E=>{if(!u||E.key!=="Escape"&&E.key!=="Esc")return;const S=E.target;S&&S!==e&&!t.contains(S)&&S!==r.body||(E.preventDefault(),m(!0))},x=E=>{if(!u)return;const P=o().indexOf(r.activeElement);E.key==="ArrowDown"?(E.preventDefault(),d(P+1)):E.key==="ArrowUp"?(E.preventDefault(),d(P<0?-1:P-1)):E.key==="Home"?(E.preventDefault(),d(0)):E.key==="End"?(E.preventDefault(),d(-1)):E.key==="Tab"&&m(!1)},N=E=>{const S=E.target,P=S&&typeof S.closest=="function"?S.closest(".af-menu__item"):null;if(!P||!t.contains(P))return;const D=r.activeElement,R=!D||D===r.body||t.contains(D);m(R)};e.addEventListener("click",y),e.addEventListener("keydown",b),t.addEventListener("keydown",x),t.addEventListener("click",N);let $=!1;return()=>{$||($=!0,m(!1),e.removeEventListener("click",y),e.removeEventListener("keydown",b),t.removeEventListener("keydown",x),t.removeEventListener("click",N))}}function K2(e){const t=p.useRef(null),n=p.useRef(null),r=e.items.filter(o=>o&&!o.hidden),i=r.length>0;return p.useEffect(()=>{if(!(!i||!t.current||!n.current))return G2(t.current,n.current)},[i]),i?s.jsxs("div",{className:`af-menu${e.className?` ${e.className}`:""}`,children:[s.jsx("button",{type:"button",ref:t,className:`af-menu__button${e.buttonClassName?` ${e.buttonClassName}`:""}`,"aria-label":e.label,title:e.title,"data-af-tip":e.tip,"aria-haspopup":"menu","aria-expanded":"false",children:e.buttonContent!==void 0?e.buttonContent:s.jsx("span",{"aria-hidden":"true",children:"⋯"})}),s.jsxs("div",{className:"af-menu__list",role:"menu",ref:n,hidden:!0,children:[e.header!==void 0&&e.header!==null?s.jsx("div",{className:"af-menu__header",role:"presentation",children:e.header}):null,r.map(o=>s.jsx("button",{type:"button",role:"menuitem",tabIndex:-1,"data-menu-id":o.id,className:`af-menu__item${o.danger?" af-menu__item--danger":""}`,onClick:()=>o.onSelect(),children:o.label},o.id))]})]}):null}const J2={name:"AbstractFramework",website:"https://abstractframework.ai",github_org:"https://github.com/lpalbou",author:"Laurent-Philippe Albou, PhD",years:"2023-2026",license:"MIT",copyright:"© 2023-2026 Laurent-Philippe Albou, PhD. Released under the MIT License.",contact_email:"contact@abstractframework.ai"},Y2={abstractframework:{name:"AbstractFramework",website:"https://abstractframework.ai",repo:"https://github.com/lpalbou/AbstractFramework",docs:"https://github.com/lpalbou/AbstractFramework/tree/main/docs",issues:"https://github.com/lpalbou/AbstractFramework/issues",feedback:"https://github.com/lpalbou/AbstractFramework/issues/new?labels=feedback"},abstractgateway:{name:"AbstractGateway",website:"https://abstractframework.ai/gateway",repo:"https://github.com/lpalbou/AbstractGateway",docs:"https://www.lpalbou.info/AbstractGateway/",issues:"https://github.com/lpalbou/AbstractGateway/issues",feedback:"https://github.com/lpalbou/AbstractGateway/issues/new?labels=feedback"},abstractcode:{name:"AbstractCode",website:"https://abstractframework.ai/code",repo:"https://github.com/lpalbou/AbstractCode",docs:"https://github.com/lpalbou/AbstractCode/tree/main/docs",issues:"https://github.com/lpalbou/AbstractCode/issues",feedback:"https://github.com/lpalbou/AbstractCode/issues/new?labels=feedback"},abstractassistant:{name:"AbstractAssistant",website:"https://abstractframework.ai/assistant",repo:"https://github.com/lpalbou/AbstractAssistant",docs:"https://github.com/lpalbou/AbstractAssistant/blob/main/docs/README.md",issues:"https://github.com/lpalbou/AbstractAssistant/issues",feedback:"https://github.com/lpalbou/AbstractAssistant/issues/new?labels=feedback"},abstractflow:{name:"AbstractFlow",website:"https://abstractframework.ai/flow",repo:"https://github.com/lpalbou/AbstractFlow",docs:"https://github.com/lpalbou/AbstractFlow#readme",issues:"https://github.com/lpalbou/AbstractFlow/issues",feedback:"https://github.com/lpalbou/AbstractFlow/issues/new?labels=feedback"},abstractcontinuum:{name:"AbstractContinuum",website:"https://abstractframework.ai",repo:"https://github.com/lpalbou/AbstractContinuum",docs:"https://github.com/lpalbou/AbstractContinuum/tree/main/docs",issues:"https://github.com/lpalbou/AbstractContinuum/issues",feedback:"https://github.com/lpalbou/AbstractContinuum/issues/new?labels=feedback"},abstractentity:{name:"AbstractEntity",website:"https://abstractframework.ai",repo:"https://github.com/lpalbou/AbstractEntity",docs:"https://github.com/lpalbou/AbstractEntity/tree/main/docs",issues:"https://github.com/lpalbou/AbstractEntity/issues",feedback:"https://github.com/lpalbou/AbstractEntity/issues/new?labels=feedback"},abstractobserver:{name:"AbstractObserver",website:"https://abstractframework.ai/observer",repo:"https://github.com/lpalbou/AbstractObserver",docs:"https://github.com/lpalbou/AbstractObserver#readme",issues:"https://github.com/lpalbou/AbstractObserver/issues",feedback:"https://github.com/lpalbou/AbstractObserver/issues/new?labels=feedback"},abstractcore:{name:"AbstractCore",website:"https://www.abstractcore.ai",repo:"https://github.com/lpalbou/AbstractCore",docs:"https://github.com/lpalbou/AbstractCore/tree/main/docs",issues:"https://github.com/lpalbou/AbstractCore/issues",feedback:"https://github.com/lpalbou/AbstractCore/issues/new?labels=feedback"},abstractuic:{name:"AbstractUIC",website:"https://abstractframework.ai",repo:"https://github.com/lpalbou/AbstractUIC",docs:"https://github.com/lpalbou/AbstractUIC/tree/main/docs",issues:"https://github.com/lpalbou/AbstractUIC/issues",feedback:"https://github.com/lpalbou/AbstractUIC/issues/new?labels=feedback"}},X2={framework:J2,apps:Y2},Bp=X2;function zj(){return{...Bp.framework}}function Z2(){return Object.keys(Bp.apps).sort()}function Q2(e,t){const n=Object.prototype.hasOwnProperty.call(Bp.apps,e)?Bp.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${Z2().join(", ")})`);return{id:e,name:n.name,version:t,website:n.website,repo:n.repo,docs:n.docs,issues:n.issues,feedback:n.feedback}}async function eE(e,t){try{const n=await e(wt("about"),{method:"GET",headers:{Accept:"application/json"},signal:t});if(!n.ok)return qh(null,`HTTP ${n.status}`);const r=await n.json().catch(()=>null);return qh(r)}catch(n){return qh(null,String((n==null?void 0:n.message)||n||"request failed"))}}const tE={framework:null,frameworkNote:"checking…",gateway:null,gatewayNote:"checking…"};function Td(e){return typeof e=="string"?e.trim():""}function qh(e,t){if(t!=null)return{framework:null,gateway:null,gatewayNote:`unavailable (${String(t).trim()||"unknown error"})`};const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=Td(n.abstractgateway),i=Td(n.abstractframework);return{framework:i||null,gateway:r||null,...r&&!i?{frameworkNote:"not installed on the gateway host"}:{},...r?{}:{gatewayNote:"unavailable (the gateway did not report its version)"}}}function nE(e){const t=zj();return[{id:"website",label:"Website",href:e.website,title:e.website},{id:"source",label:"Source",href:e.repo,title:e.repo},{id:"docs",label:"Docs",href:e.docs,title:e.docs},{id:"issues",label:"Issues",href:e.issues,title:e.issues},{id:"feedback",label:"Feedback",href:e.feedback,title:e.feedback},{id:"contact",label:"Contact",href:`mailto:${t.contact_email}`,title:t.contact_email}]}function sE(e){const t=e||{},n=Td(t.framework),r=Td(t.gateway);return[["AbstractFramework",n||Td(t.frameworkNote)||"not reported"],["AbstractGateway",r||Td(t.gatewayNote)||"not connected"]]}const rE='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function iE(e,t,n){if(e.key!=="Tab"||!t)return;const r=Array.from(t.querySelectorAll(rE));if(r.length===0){e.preventDefault();return}const i=r[0],o=r[r.length-1],u=!!n&&t.contains(n);e.shiftKey?(n===i||!u)&&(e.preventDefault(),o.focus()):(n===o||!u)&&(e.preventDefault(),i.focus())}function oE(e){const t=zj();return s.jsxs("div",{className:`af-about-card${e.className?` ${e.className}`:""}`,"data-app":e.identity.id,children:[s.jsxs("div",{className:"af-about-card__head",children:[s.jsxs("h2",{className:"af-about-card__name",id:e.titleId,children:[e.identity.name," ",s.jsx("span",{className:"af-about-card__version",children:e.identity.version})]}),e.action]}),s.jsx("dl",{className:"af-about-card__versions",children:sE(e.versions).map(([n,r])=>s.jsxs("div",{className:"af-about-card__fact",children:[s.jsx("dt",{children:n}),s.jsx("dd",{children:r})]},n))}),s.jsx("nav",{className:"af-about-card__links","aria-label":`${e.identity.name} links`,children:nE(e.identity).map(n=>n.href.startsWith("mailto:")?s.jsx("a",{className:"af-about-card__link","data-link":n.id,href:n.href,title:n.title,children:n.label},n.id):s.jsx("a",{className:"af-about-card__link","data-link":n.id,href:n.href,title:n.title,target:"_blank",rel:"noopener noreferrer",children:n.label},n.id))}),e.extra!==void 0&&e.extra!==null?s.jsx("div",{className:"af-about-card__extra",children:e.extra}):null,s.jsx("p",{className:"af-about-card__legal",children:t.copyright})]})}function aE(e){tf();const t=p.useRef(null),n=p.useRef(null),r=p.useId(),i=p.useRef(e.onClose);return i.current=e.onClose,p.useEffect(()=>{var l;if(!e.open)return;const o=document.activeElement;(l=t.current)==null||l.focus();const u=d=>{if(!d.defaultPrevented){if(d.key==="Escape"){d.preventDefault(),i.current();return}iE(d,n.current,document.activeElement)}};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u),o&&typeof o.focus=="function"&&o.focus()}},[e.open]),e.open?s.jsx("div",{className:"af-appearance-overlay af-about-overlay",onClick:e.onClose,role:"presentation",children:s.jsx("div",{ref:n,className:"af-appearance af-about",role:"dialog","aria-modal":"true","aria-labelledby":r,onClick:o=>o.stopPropagation(),children:s.jsx(oE,{identity:e.identity,versions:e.versions,extra:e.extra,titleId:r,action:s.jsx("button",{ref:t,type:"button",className:"af-about-card__close","data-action":"close-about",onClick:e.onClose,"aria-label":"Close","data-af-tip":"Close About",children:s.jsx(qe,{name:"x",size:16})})})})}):null}const Sp={theme:"dark",font_scale:"md",header_density:"standard"};function lE(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:Sp.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:Sp.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:Sp.header_density}}function cE(e){return`af_appearance_${e}_v1`}function uE(e,t){const n=cE(e),r=p.useMemo(()=>({...Sp,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[i,o]=p.useState(()=>{let u=r;try{const l=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);l&&(u=lE({...r,...JSON.parse(l)}))}catch{}try{nb(u.theme),sb({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return p.useEffect(()=>{nb(i.theme),sb({font_scale:i.font_scale,header_density:i.header_density});try{localStorage.setItem(n,JSON.stringify(i))}catch{}},[n,i]),[i,o]}function Bj(e){return p.useEffect(()=>{if(!e.open)return;const t=n=>{n.key!=="Escape"||n.defaultPrevented||(n.preventDefault(),e.onClose())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[e.open,e.onClose]),e.open?s.jsx("div",{className:"af-appearance-overlay",onClick:e.onClose,role:"presentation",children:s.jsxs("div",{className:"af-appearance",role:"dialog","aria-modal":"true","aria-label":e.title||"Appearance",onClick:t=>t.stopPropagation(),children:[s.jsx("div",{className:"af-appearance__title",children:e.title||"Appearance"}),s.jsx("div",{className:"af-appearance__note",children:e.note||"Stored locally in this browser, per app."}),s.jsxs("div",{className:"af-appearance__grid",children:[s.jsx("label",{className:"af-appearance__label",children:"Theme"}),s.jsx(g2,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),s.jsx("label",{className:"af-appearance__label",children:"Font size"}),s.jsx(y2,{value:e.value.font_scale,onChange:t=>e.onChange({...e.value,font_scale:t})}),s.jsx("label",{className:"af-appearance__label",children:"Header size"}),s.jsx(w2,{value:e.value.header_density,onChange:t=>e.onChange({...e.value,header_density:t})})]}),s.jsx("div",{className:"af-appearance__actions",children:s.jsx("button",{type:"button",className:"af-appearance__close",onClick:e.onClose,children:"Close"})})]})}):null}const dE="default";function nc(e){return typeof e=="string"?e.trim():""}function fb(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0}function fE(e){var h;if(!e||!Pj(e))return null;const t=(h=e.gateway)==null?void 0:h.principal;if(!t||typeof t!="object")return null;const n=nc(t.user_id);if(!n)return null;const r={userId:n},i=nc(t.tenant_id);i&&(r.tenantId=i);const o=nc(t.runtime_id);o&&(r.runtimeId=o);const u=fb(t.roles);u&&(r.roles=u);const l=fb(t.scopes);l&&(r.scopes=l);const d=nc(t.source);return d&&(r.source=d),typeof t.admin=="boolean"&&(r.admin=t.admin),r}function Uj(e){const t=nc(e.displayName)||nc(e.userId),n=nc(e.tenantId);return n&&n!==dE?`${n}/${t}`:t}function Wj(e){const t=nc(e);if(!t)return"";try{return new URL(t).host||t}catch{return t}}function hE(e,t){return{label:t?"Disconnecting…":e==="connected"?"Disconnect":e==="loading"?"Connecting…":"Connect",title:e==="connected"?"Disconnect from gateway":e==="loading"?"Checking gateway session…":"Connect to gateway"}}function mE(e){return typeof e.openModal=="function"&&typeof e.signOut=="function"}function _E(e,t){return mE(e)?{phase:e.phase,signingOut:e.signingOut===!0,connect:e.openModal,disconnect:async()=>{await e.signOut()===!0&&(t==null||t())},status:e.status,signOutError:e.signOutError||null}:{phase:e.phase,signingOut:e.signingOut===!0,connect:e.onConnect,disconnect:async()=>{e.onDisconnect()},status:e.status??null,signOutError:e.signOutError||null}}function pE(e,t){const n=Wj(t);return`Signed in as ${Uj(e)}${n?` · gateway ${n}`:""}`}const py="--af-topbar-h";function gE(e,t=!0){p.useEffect(()=>{if(!t||typeof window>"u"||typeof document>"u")return;const n=e.current;if(!n)return;const r=n.closest("[data-af-topbar], header")||n.parentElement||n,i=document.documentElement;let o="";const u=()=>{o=`${Math.max(0,Math.round(r.getBoundingClientRect().bottom))}px`,i.style.setProperty(py,o)};u();const l=typeof ResizeObserver<"u"?new ResizeObserver(u):null;l==null||l.observe(r);const d={passive:!0,capture:!0};return window.addEventListener("resize",u),window.addEventListener("scroll",u,d),()=>{l==null||l.disconnect(),window.removeEventListener("resize",u),window.removeEventListener("scroll",u,d),o&&i.style.getPropertyValue(py)===o&&i.style.removeProperty(py)}},[e,t])}function yE(e){const t=typeof navigator<"u"?navigator.clipboard:void 0;return!t||typeof t.writeText!="function"?null:()=>{t.writeText(e).catch(()=>{})}}function wE(e){var S,P;const t=_E(e.connection,e.onSignOut),{phase:n,signingOut:r}=t,[i,o]=p.useState(!1),[u,l]=p.useState(!1),[d,h]=p.useState(void 0),m=p.useRef(null);tf(),gE(m,e.publishHeight!==!1);const _=e.about,g=e.appearance,y=!!(g&&"value"in g),b=_&&!_.versions?_.fetch:void 0,k=p.useRef(b);k.current=b,p.useEffect(()=>{const D=k.current;if(!i||!D)return;const R=typeof AbortController<"u"?new AbortController:null;let I=!0;return h(tE),eE(D,R==null?void 0:R.signal).then(W=>{I&&h(W)}),()=>{I=!1,R==null||R.abort()}},[i]);const x=hE(n,r),N=e.identity&&n==="connected"?fE(t.status):null,$=()=>void t.disconnect();let E=null;if(N&&e.identity){const D=Uj(N),R=pE(N,(S=t.status)==null?void 0:S.gateway_url),I=s.jsxs(s.Fragment,{children:[s.jsx(qe,{name:"user",size:14}),s.jsx("span",{className:"af-topbar__identity-label",children:D})]});if(e.identity==="badge")E=s.jsx("span",{className:"af-topbar__identity af-topbar__identity--badge","data-af-identity":"badge","data-af-tip":R,"aria-label":R,children:I});else{const W=yE(N.userId),G=Wj((P=t.status)==null?void 0:P.gateway_url);E=s.jsx(K2,{label:`Account: ${R}`,tip:R,className:"af-topbar__account",buttonClassName:"af-topbar__identity af-topbar__identity--menu",buttonContent:I,header:s.jsxs("span",{className:"af-topbar__account-head","data-af-identity":"menu",children:[s.jsxs("span",{className:"af-topbar__account-who",children:["Signed in as ",D]}),G?s.jsxs("span",{className:"af-topbar__account-host",children:["Gateway ",G]}):null]}),items:[{id:"copy-user-id",label:"Copy user id",onSelect:W||(()=>{}),hidden:!W},{id:"disconnect",label:"Disconnect",onSelect:$,danger:!0,hidden:r}]})}}return s.jsxs("div",{ref:m,className:`af-topbar${e.className?` ${e.className}`:""}`,role:"group","aria-label":"App actions",children:[e.extraActions,e.docs?s.jsx("button",{type:"button",className:`af-topbar__btn af-topbar__btn--docs${e.docs.open?" is-active":""}`,"aria-pressed":e.docs.open,"aria-label":e.docs.label||"Docs assistant","data-af-tip":e.docs.label||"Docs assistant",onClick:e.docs.onToggle,children:s.jsx(qe,{name:"book",size:16})}):null,e.assistant?s.jsx("button",{type:"button",className:`af-topbar__btn af-topbar__btn--assistant${e.assistant.open?" is-active":""}`,"aria-pressed":e.assistant.open,"aria-label":e.assistant.label||"Open assistant","data-af-tip":e.assistant.label||"Assistant",onClick:e.assistant.onToggle,children:s.jsx(qe,{name:"sparkle",size:16})}):null,g?s.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--appearance","aria-label":g.label||"Appearance (theme and typography)","data-af-tip":g.label||"Appearance (theme and text size)","aria-haspopup":y?"dialog":void 0,onClick:()=>{"value"in g?l(!0):g.onOpen()},children:s.jsx(qe,{name:"contrast",size:16})}):null,_?s.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--about","aria-label":_.label||`About ${_.identity.name}`,"data-af-tip":_.label||`About ${_.identity.name}`,"aria-haspopup":"dialog",onClick:()=>{var D;o(!0),(D=_.onOpen)==null||D.call(_)},children:s.jsx(qe,{name:"info",size:16})}):null,E,t.signOutError?s.jsxs("span",{className:"af-topbar__signout-error",role:"alert","data-af-tip":`Disconnect failed: ${t.signOutError}`,"aria-label":`Disconnect failed: ${t.signOutError}`,children:[s.jsx(qe,{name:"warning",size:14}),s.jsx("span",{className:"af-topbar__signout-error-label",children:"Disconnect failed"})]}):null,s.jsxs("button",{type:"button",className:`af-topbar__pill af-topbar__pill--${n}`,onClick:n==="connected"?$:t.connect,disabled:r,title:x.title,"aria-label":x.title,children:[s.jsx("span",{className:`af-topbar__dot af-topbar__dot--${n}`,"aria-hidden":"true"}),s.jsx("span",{className:"af-topbar__pill-label",children:x.label})]}),_?s.jsx(aE,{open:i,onClose:()=>o(!1),identity:_.identity,versions:_.versions||(_.fetch?d:void 0),extra:_.extra}):null,g&&"value"in g?s.jsx(Bj,{open:u,onClose:()=>l(!1),value:g.value,onChange:g.onChange,title:g.title,note:g.note}):null]})}function Tw(e){return e?[e.provider,e.model].map(t=>String(t||"").trim()).filter(Boolean).join(" / "):""}function hb(e,t,n=!1){if(n)return"unknown";if(!e)return"";const r=e[t];return!r||!r.configured?"not set":Tw(r)||"not set"}function vE(e,t){var n;return e.stt_provider?Tw({provider:e.stt_provider,model:e.stt_model}):(n=t==null?void 0:t.stt)!=null&&n.configured?Tw(t.stt):""}function qj(e,t){return`${Math.max(0,Math.floor((t-e)/1e3))} s`}function xE(e,t,n){return`Transcribing… ${qj(e,t)}${n?` · ${n}`:""}`}const xg=()=>{var e;return(e=globalThis.navigator)==null?void 0:e.mediaDevices};function Up(e){var i;const t=vg("the microphone");if(t)return t;const n=String((e==null?void 0:e.name)||"");if(n==="NotAllowedError"||n==="SecurityError"||n==="PermissionDeniedError")return"The browser blocked the microphone. Allow it for this site (the icon left of the address), then try again.";if(n==="NotFoundError"||n==="DevicesNotFoundError")return"No microphone was found. Connect one, then try again.";if(n==="OverconstrainedError")return"The chosen microphone is not connected. Pick another one in Settings → Voice.";if(n==="NotReadableError"||n==="TrackStartError")return"Another app is using the microphone. Close it, then try again.";if(!((i=xg())!=null&&i.getUserMedia))return"This browser cannot record audio.";const r=String((e==null?void 0:e.message)||e||"").trim();return r?`The microphone did not start: ${r.replace(/\.$/,"")}.`:"The microphone did not start."}async function Hj(e){const t=xg();if(!t||typeof t.enumerateDevices!="function")return{devices:[],labelled:!1};const r=(await t.enumerateDevices()).filter(u=>u.kind===e),i=r.some(u=>!!u.label);return{devices:r.filter(u=>u.deviceId&&u.deviceId!=="default"&&u.deviceId!=="communications").map((u,l)=>({id:String(u.deviceId),label:String(u.label||`${e==="audioinput"?"Microphone":"Speaker"} ${l+1}`)})),labelled:i}}async function bE(){const e=xg();if(!(e!=null&&e.getUserMedia))throw new Error(vg("the microphone")||"This browser cannot record audio.");(await e.getUserMedia({audio:!0})).getTracks().forEach(n=>n.stop())}async function Vj(e){const t=xg();if(!(t!=null&&t.getUserMedia))throw Object.assign(new Error("This browser cannot record audio."),{name:"NotSupportedError"});return t.getUserMedia({audio:e?{deviceId:{exact:e}}:!0})}function bg(){const e=globalThis;return e.AudioContext||e.webkitAudioContext||null}function Gj(){const e=bg();return!!(e&&e.prototype&&typeof e.prototype.createMediaStreamDestination=="function")}function Kj(e,t,n=1){const r=bg();if(!r)return()=>{};const i=new r,o=i.createMediaStreamSource(e),u=i.createAnalyser();u.fftSize=1024,o.connect(u);const l=new Float32Array(u.fftSize);let d=!0;const m=setInterval(()=>{if(!d)return;u.getFloatTimeDomainData(l);let _=0;for(let g=0;g<l.length;g+=1)_+=l[g]*l[g];t(Math.min(1,Math.sqrt(_/l.length)*4*n))},50);return()=>{var _;d=!1,clearInterval(m);try{o.disconnect()}catch{}(_=i.close)==null||_.call(i)}}const Jj=.02;function mb(){return Object.assign(new Error("The recording was stopped before it began."),{name:"AbortError"})}async function Yj(e){var o,u,l;const t=globalThis.MediaRecorder;if(typeof t!="function")throw Object.assign(new Error("This browser cannot record audio."),{name:"NotSupportedError"});if((o=e.signal)!=null&&o.aborted)throw mb();const n=await Vj(e.deviceId);if((u=e.signal)!=null&&u.aborted)throw n.getTracks().forEach(d=>d.stop()),mb();let r=0;const i=Kj(n,d=>{var h;r=Math.max(r,d),(h=e.onLevel)==null||h.call(e,d)},e.gain??1);try{const d=new t(n),h=[],m=new Promise((g,y)=>{d.ondataavailable=b=>(b==null?void 0:b.data)&&h.push(b.data),d.onstop=()=>g(),d.onerror=b=>y((b==null?void 0:b.error)||new Error("Recording failed."))});d.start(),await new Promise(g=>{var b,k;if((b=e.signal)!=null&&b.aborted)return g();const y=setTimeout(g,e.ms??3e3);(k=e.signal)==null||k.addEventListener("abort",()=>{clearTimeout(y),g()},{once:!0})}),d.stop(),await m;const _=String(d.mimeType||"audio/webm");return{blob:new Blob(h,{type:_}),peak:r,mime:_}}finally{i(),n.getTracks().forEach(d=>d.stop()),(l=e.onLevel)==null||l.call(e,0)}}async function Xj(e,t={}){var i,o,u,l;if((i=t.signal)!=null&&i.aborted)return;const n=bg();if(!n)throw new Error("This browser cannot play audio.");const r=new n;try{t.deviceId&&typeof r.setSinkId=="function"&&await r.setSinkId(t.deviceId);const d=e instanceof Blob?await e.arrayBuffer():e,h=await r.decodeAudioData(d.slice(0));if((o=t.signal)!=null&&o.aborted)return;if(r.state==="suspended"&&await((u=r.resume)==null?void 0:u.call(r)),r.state==="suspended")throw new Error("The browser held the sound back: press play to hear it");const m=r.createGain();m.gain.value=Hd(t.volume),m.connect(r.destination);const _=r.createBufferSource();_.buffer=h,_.connect(m),await new Promise(g=>{var b,k;const y=()=>{try{_.stop()}catch{}g()};_.onended=()=>{var x,N;(N=(x=t.signal)==null?void 0:x.removeEventListener)==null||N.call(x,"abort",y),g()},(k=(b=t.signal)==null?void 0:b.addEventListener)==null||k.call(b,"abort",y,{once:!0}),_.start()})}finally{(l=r.close)==null||l.call(r)}}async function kE(e={}){var r,i;const t=bg();if(!t)throw new Error("This browser cannot play audio.");const n=new t;try{e.deviceId&&typeof n.setSinkId=="function"&&await n.setSinkId(e.deviceId),n.state==="suspended"&&await((r=n.resume)==null?void 0:r.call(n));const o=n.createGain();o.connect(n.destination);const u=.3*Hd(e.volume),l=n.currentTime+.02;[660,880].forEach((d,h)=>{const m=n.createOscillator(),_=n.createGain();m.frequency.value=d,m.connect(_),_.connect(o);const g=l+h*.22;_.gain.setValueAtTime(0,g),_.gain.linearRampToValueAtTime(u,g+.02),_.gain.exponentialRampToValueAtTime(1e-4,g+.2),m.start(g),m.stop(g+.21)}),await new Promise(d=>setTimeout(d,520))}finally{(i=n.close)==null||i.call(n)}}function Hd(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)?1:Math.min(1,Math.max(0,t))}function Mw(e){return(e&&typeof e=="object"?e.capture_mode:e)==="toggle"?"toggle":"hold"}async function*jE(e){var r,i,o;const t=new AbortController,n=()=>t.abort();(r=e.signal)!=null&&r.aborted?n():(i=e.signal)==null||i.addEventListener("abort",n,{once:!0});try{const u=await fetch(e.path,{method:"POST",headers:{"Content-Type":"application/json",...e.csrfToken?{"x-abstract-csrf":e.csrfToken}:{},...e.headers||{}},body:JSON.stringify(e.body),signal:t.signal});if(!u.ok){const m=await u.json().catch(()=>null),_=m&&typeof m=="object"&&m.detail?String(m.detail):`HTTP ${u.status}`;throw new Error(_)}if(!u.body)throw new Error("TTS stream has no body");const l=u.body.getReader(),d=new TextDecoder;let h="";for(;;){const{done:m,value:_}=await l.read();h+=m?d.decode():d.decode(_,{stream:!0}),m&&h.trim()&&(h+=`
42
+ `);let g;for(;(g=h.indexOf(`
43
+ `))>=0;){const y=h.slice(0,g).trim();if(h=h.slice(g+1),!y)continue;let b=null;try{b=JSON.parse(y)}catch{throw new Error("TTS stream returned invalid JSON.")}if(b&&b.type==="error")throw new Error(String(b.error||"TTS stream error"));const k=b&&typeof b.audio_b64=="string"?b.audio_b64:"";if(k){const x=atob(k),N=new Uint8Array(x.length);for(let $=0;$<x.length;$+=1)N[$]=x.charCodeAt($);yield N.buffer}if(b&&(b.type==="done"||b.type==="cancelled"))return}if(m)throw new Error("TTS stream ended before synthesis completed.")}}finally{(o=e.signal)==null||o.removeEventListener("abort",n),t.abort()}}function ph(e,t){const n=String((t==null?void 0:t.message)||t||"").trim().replace(/\.$/,"");return n?`${e}: ${n}.`:`${e}.`}const SE=350;function NE(){var t;if(typeof window>"u")return!1;const e=navigator;return!!((t=e==null?void 0:e.mediaDevices)!=null&&t.getUserMedia)&&typeof window.MediaRecorder=="function"}function $E(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function CE(){const e=window.MediaRecorder,t=r=>{var i;try{return!!((i=e==null?void 0:e.isTypeSupported)!=null&&i.call(e,r))}catch{return!1}},n=["audio/webm;codecs=opus","audio/webm","audio/mp4","audio/ogg;codecs=opus","audio/ogg"];for(const r of n)if(t(r))return r;return""}async function gy(e,t){var i;const n=t.slice(0),r=(i=e.decodeAudioData)==null?void 0:i.bind(e);if(typeof r!="function")throw new Error("decodeAudioData not available");try{const o=r(n);if(o&&typeof o.then=="function")return await o}catch{}return await new Promise((o,u)=>{try{r(n,o,u)}catch(l){u(l)}})}function EE(e){const t=new Uint8Array(e);if(t.length<44)return null;const n=o=>String.fromCharCode(t[o],t[o+1],t[o+2],t[o+3]);if(n(0)!=="RIFF"||n(8)!=="WAVE")return null;const r=new DataView(e);let i=12;for(;i+8<=t.length;){const o=n(i),u=r.getUint32(i+4,!0);if(o==="data")return t.slice(0,i+8);i+=8+u+u%2}return null}function AE(e,t){const n=new Uint8Array(t),r=new Uint8Array(e.length+n.length);r.set(e,0),r.set(n,e.length);const i=new DataView(r.buffer);return i.setUint32(4,r.length-8,!0),i.setUint32(e.length-4,n.length,!0),r.buffer}function Zj(){const e=globalThis,t=e==null?void 0:e.AudioContext;return!!(t&&t.prototype&&typeof t.prototype.setSinkId=="function")}const V_=new WeakMap;function TE(e,t){const n=e;if(!(typeof n.setSinkId!="function"||V_.get(e)===t)){V_.set(e,t);try{Promise.resolve(n.setSinkId(t)).catch(()=>V_.delete(e))}catch{V_.delete(e)}}}function ME(e){const t=p.useRef(e);t.current=e;const n=le=>{var Se,pe;return(pe=(Se=t.current).on_error)==null?void 0:pe.call(Se,le)},r=p.useMemo(()=>$E()&&(typeof e.tts=="function"||typeof e.tts_stream=="function"),[e.tts,e.tts_stream]),i=p.useMemo(()=>NE()&&typeof e.transcribe=="function",[e.transcribe]),[o,u]=p.useState({key:"",status:"idle"}),l=p.useRef(o),d=p.useCallback(le=>{l.current=le,u(Se=>Se.key===le.key&&Se.status===le.status?Se:le)},[]),h=p.useRef(""),m=p.useRef(""),_=p.useRef(null),g=p.useRef(null),y=p.useRef(null),b=p.useRef(null),k=p.useRef(0),x=p.useRef(0),N=p.useRef(0),$=p.useRef(null),E=p.useRef([]),S=p.useRef(0),P=p.useRef(!0),D=p.useRef(!1),R=()=>{try{const le=globalThis,Se=(le==null?void 0:le.AudioContext)||(le==null?void 0:le.webkitAudioContext);if(!Se)return null;if(!_.current){const yt=new Se,_t=yt.createGain();_t.gain.value=1,_t.connect(yt.destination),_.current=yt,g.current=_t}const pe=_.current,dt=g.current;if(!pe||!dt)return null;TE(pe,t.current.output_device_id||""),dt.gain.value=Hd(t.current.volume)*(t.current.muted?0:1);try{pe.state==="suspended"&&pe.resume()}catch{}return{ctx:pe,gain:dt}}catch{return null}};p.useEffect(()=>{const le=g.current;le&&(le.gain.value=Hd(e.volume)*(e.muted?0:1))},[e.volume,e.muted]);const I=p.useCallback(()=>{const le=y.current;if(y.current=null,!!le){try{le.onended=null}catch{}try{le.stop()}catch{}try{le.disconnect()}catch{}}},[]),W=p.useCallback(()=>{var le;I(),N.current+=1,(le=$.current)==null||le.abort(),$.current=null,E.current=[],S.current=0,P.current=!0,D.current=!1,m.current="",h.current="",b.current=null,k.current=0,x.current=0,d({key:"",status:"idle"})},[I,d]);p.useEffect(()=>()=>{var le,Se;W();try{(le=g.current)==null||le.disconnect()}catch{}try{(Se=_.current)==null||Se.close()}catch{}_.current=null,g.current=null,b.current=null},[]);const G=async(le,Se,pe)=>{const dt=N.current,yt=R();if(!yt)throw new Error("TTS playback is not supported in this browser");const{ctx:_t,gain:It}=yt;try{_t.state==="suspended"&&await _t.resume()}catch{}if(dt!==N.current)return;I();const bt=_t.createBufferSource();bt.buffer=Se,bt.connect(It);const St=Number.isFinite(Number(Se.duration))?Number(Se.duration):0,ut=Math.max(0,Math.min(Number(pe||0),St>0?Math.max(0,St-.01):0));x.current=_t.currentTime-ut,k.current=ut,y.current=bt,h.current=le,bt.onended=()=>{y.current===bt&&(y.current=null,k.current=0,x.current=0,h.current="",d({key:"",status:"idle"}))},bt.start(0,ut),d({key:le,status:"playing"})},K=(le,Se)=>{if(Se!==N.current)return;const pe=R();if(!pe)return;const dt=E.current,yt=S.current;if(yt>=dt.length){P.current&&(h.current="",k.current=0,x.current=0,d({key:"",status:"idle"}));return}const _t=dt[yt],{ctx:It,gain:bt}=pe;I();const St=It.createBufferSource();St.buffer=_t,St.connect(bt);const ut=Number.isFinite(Number(_t.duration))?Number(_t.duration):0,Ot=Math.max(0,Math.min(Number(k.current||0),ut>0?Math.max(0,ut-.01):0));x.current=It.currentTime-Ot,y.current=St,h.current=le,St.onended=()=>{Se===N.current&&y.current===St&&(y.current=null,S.current=yt+1,k.current=0,K(le,Se))};try{It.state==="suspended"&&It.resume()}catch{}St.start(0,Ot),d({key:le,status:"playing"})},H=async(le,Se,pe)=>{var bt;const dt=R();if(!dt){n==null||n("This browser cannot play spoken replies.");return}I();const yt=++N.current;(bt=$.current)==null||bt.abort();const _t=new AbortController;$.current=_t,E.current=[],S.current=0,P.current=!1,D.current=!1,b.current=null,k.current=0,x.current=0,h.current=le,m.current=le,d({key:le,status:"loading"}),n==null||n("");let It=null;try{for await(const St of pe(Se,_t.signal)){if(yt!==N.current)return;let ut;try{ut=await gy(dt.ctx,St),It||(It=EE(St))}catch{if(!It)continue;try{ut=await gy(dt.ctx,AE(It,St))}catch{continue}}if(yt!==N.current)return;E.current.push(ut),!y.current&&!D.current&&(m.current="",K(le,yt))}if(yt!==N.current)return;if(P.current=!0,E.current.length===0){n==null||n("Reading aloud failed: the voice engine returned no audio."),W();return}!y.current&&!D.current&&K(le,yt)}catch(St){if(yt!==N.current)return;n==null||n(ph("Reading aloud failed",St)),W()}finally{$.current===_t&&($.current=null)}},M=p.useCallback(async(le,Se)=>{var Ot;const pe=String(le||"").trim(),dt=String(Se||"").trim();if(!pe||!dt)return;const yt=t.current.tts,_t=t.current.tts_stream;if(typeof yt!="function"&&typeof _t!="function"){n==null||n("Reading aloud is not available on this gateway.");return}const It=R();if(!It){n==null||n("This browser cannot play spoken replies.");return}const bt=l.current,St=bt.key===pe;if(St&&bt.status==="playing"){if(y.current){const Mt=Math.max(0,It.ctx.currentTime-Number(x.current||0));k.current=Mt}else k.current=0;D.current=!0,I(),d({key:pe,status:"paused"});return}if(St&&bt.status==="paused"){if(E.current.length>0){n==null||n(""),D.current=!1,d({key:pe,status:"playing"}),K(pe,N.current);return}const Mt=b.current;if(Mt){n==null||n(""),D.current=!1;try{await G(pe,Mt,k.current)}catch(mn){n==null||n(ph("Reading aloud failed",mn)),d({key:"",status:"idle"})}return}}if(St&&bt.status==="loading")return;if(typeof _t=="function"){await H(pe,dt,_t);return}I(),N.current+=1,(Ot=$.current)==null||Ot.abort(),$.current=null;const ut=N.current;E.current=[],S.current=0,P.current=!0,D.current=!1,b.current=null,k.current=0,x.current=0,h.current=pe,m.current=pe,d({key:pe,status:"loading"}),n==null||n("");try{const Mt=await yt(dt);if(m.current!==pe||N.current!==ut)return;const mn=await gy(It.ctx,Mt);if(m.current!==pe||N.current!==ut)return;b.current=mn,k.current=0,await G(pe,mn,0)}catch(Mt){if(N.current!==ut)return;m.current===pe&&(m.current="",h.current="",d({key:"",status:"idle"})),n==null||n(ph("Reading aloud failed",Mt))}},[]),[A,O]=p.useState(!1),[L,V]=p.useState(!1),J=p.useRef(!1),U=p.useRef(i);U.current=i;const te=p.useCallback(le=>{J.current=le,O(Se=>Se===le?Se:le)},[]),z=p.useRef(!1),ne=p.useRef(null),se=p.useRef(null),de=p.useRef([]),be=p.useRef(""),Me=p.useRef(0),je=p.useRef(!1),ae=p.useRef(!1),[xe,Ae]=p.useState(0),He=p.useRef(0),mt=p.useRef(null),nt=p.useRef(0),rt=p.useRef(new Set),ze=p.useRef(null),Ve=p.useCallback(le=>{const Se=Math.round(Math.min(1,Math.max(0,Number(le)||0))*20)/20;if(Se!==nt.current){nt.current=Se;for(const pe of Array.from(rt.current))pe(Se)}},[]),ct=p.useCallback(le=>(rt.current.add(le),le(nt.current),()=>{rt.current.delete(le)}),[]),Qe=p.useRef(new Set),Dt=p.useCallback(le=>(Qe.current.add(le),()=>{Qe.current.delete(le)}),[]);function $e(){var pe,dt;const le=ze.current;ze.current=null;try{le==null||le()}catch{}Ve(0);try{(dt=(pe=ne.current)==null?void 0:pe.getTracks)==null||dt.call(pe).forEach(yt=>{try{yt.stop()}catch{}})}catch{}ne.current=null;const Se=mt.current;mt.current=null;try{Se==null||Se.close()}catch{}}const Le=p.useCallback(()=>{Me.current+=1,je.current=!1;const le=se.current;if(le){le.onstop=null,le.ondataavailable=null,le.onerror=null;try{le.stop()}catch{}}se.current=null,$e(),te(!1),z.current=!1,V(!1),Ae(0),de.current=[]},[te]);p.useEffect(()=>()=>Le(),[Le]);async function ce(le,Se){var _t,It;if(n==null||n(""),z.current)return;const pe=He.current?Date.now()-He.current:1/0;if(!le||!le.size||pe<SE){Ae(0),n==null||n("The recording was too short. Hold the microphone button while you speak, or tap it once to start and again to stop.");return}const dt=t.current.transcribe;if(typeof dt!="function"){n==null||n("Speech to text is not available on this gateway.");return}z.current=!0;const yt=Me.current;V(!0),Ae(Date.now());try{const bt=await dt(le,Se),St=typeof bt=="string"||!bt?{text:String(bt||"")}:bt,ut=String(St.text||"").trim();if(yt!==Me.current)return;if(ut){(It=(_t=t.current).on_transcript)==null||It.call(_t,ut,{...St,text:ut});for(const Ot of Array.from(Qe.current))Ot(ut,{...St,text:ut})}else n==null||n("Nothing was heard. Check the microphone in Settings → Voice (Test), then try again.")}catch(bt){if(yt===Me.current){const St=String((bt==null?void 0:bt.message)||bt||"").trim().replace(/\.$/,"");n==null||n(St?`Transcription failed: ${St}.`:"Transcription failed.")}}finally{yt===Me.current&&(z.current=!1,V(!1),Ae(0))}}const Q=p.useCallback(async()=>{if(n==null||n(""),!U.current){n==null||n(vg("the microphone")??"Voice recording is not supported in this browser (MediaRecorder/getUserMedia unavailable).");return}if(z.current||je.current||J.current||se.current)return;de.current=[];const le=Me.current;je.current=!0,ae.current=!1;try{const Se=await Vj(t.current.input_device_id||"");if(le!==Me.current){Se.getTracks().forEach(bt=>bt.stop());return}if(ae.current){ae.current=!1,Se.getTracks().forEach(bt=>bt.stop()),Ae(0);return}ne.current=Se;const pe=Number(t.current.input_gain??1);try{ze.current=Kj(Se,Ve,Number.isFinite(pe)&&pe>0?pe:1)}catch{}const dt=CE();be.current=dt;let yt=Se;const _t=Number(t.current.input_gain??1);if(Number.isFinite(_t)&&_t>0&&_t!==1&&Gj()){const bt=globalThis.AudioContext||globalThis.webkitAudioContext,St=new bt,ut=St.createGain();ut.gain.value=_t;const Ot=St.createMediaStreamDestination();St.createMediaStreamSource(Se).connect(ut),ut.connect(Ot),mt.current=St,yt=Ot.stream}const It=dt?new MediaRecorder(yt,{mimeType:dt}):new MediaRecorder(yt);se.current=It,It.ondataavailable=bt=>{if(le===Me.current)try{bt!=null&&bt.data&&de.current.push(bt.data)}catch{}},It.onerror=()=>{le===Me.current&&(n==null||n("Recording failed. Try again, or pick another microphone in Settings → Voice."))},It.onstop=()=>{if(le===Me.current){te(!1),$e(),se.current=null;try{const bt=new Blob(de.current,{type:be.current||""});ce(bt,be.current)}catch(bt){n==null||n(ph("The recording could not be prepared",bt))}}},It.start(),He.current=Date.now(),Ae(He.current),te(!0)}catch(Se){if(le!==Me.current)return;$e(),se.current=null,te(!1),Ae(0),n==null||n(Up(Se))}finally{le===Me.current&&(je.current=!1)}},[]),_e=p.useCallback(()=>{const le=se.current;if(je.current&&!le){ae.current=!0;return}if(!(!J.current||!le)){te(!1);try{le.stop()}catch(Se){n==null||n(ph("The recording could not stop",Se))}}},[]);return p.useEffect(()=>{if(!A||t.current.stop_on_pointerup===!1||t.current.stop_on_pointerup===void 0&&Mw(t.current.capture_mode)==="toggle")return;const le=()=>_e();return window.addEventListener("pointerup",le),window.addEventListener("pointercancel",le),()=>{window.removeEventListener("pointerup",le),window.removeEventListener("pointercancel",le)}},[A]),{tts_supported:r,tts_playback:o,toggle_tts:M,stop_tts:W,voice_ptt_supported:i,voice_ptt_recording:A,voice_ptt_busy:L,start_voice_ptt_recording:Q,stop_voice_ptt_recording:_e,cancel_voice_ptt_recording:Le,voice_ptt_since:xe,subscribe_level:ct,voice_capture_mode:Mw(e.capture_mode),add_transcript_listener:Dt}}const RE={diary:"var(--accent)",question:"#e7b45a",dream:"#c084dd",interest:"#7bd88a",lesson:"#6ea8d8",world_model:"#5eead4"};function _b(e){const t=String(e||"");return t.length>14?`${t.slice(0,10)}…${t.slice(-4)}`:t}function yy(e){const[t,n]=p.useState(!1),[r,i]=p.useState(null),o=p.useRef(!1),u=typeof e.entryId=="string"&&e.entryId.trim()?e.entryId.trim():null,l=e.kind&&RE[e.kind]||"var(--text-muted)",d=p.useCallback(async()=>{if(!(!u||!e.onOpen||o.current)){o.current=!0,n(!0),i(null);try{await e.onOpen(u)}catch(h){i(String((h==null?void 0:h.message)||h||"could not open"))}finally{o.current=!1,n(!1)}}},[u,e.onOpen]);return!u||!e.onOpen?s.jsxs("span",{className:["af-memory-hint","af-memory-hint--text",e.className||""].filter(Boolean).join(" "),title:e.title,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:l},"aria-hidden":"true"}),s.jsx("span",{className:"af-memory-hint__label",children:e.label}),u&&e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:_b(u)}):null]}):s.jsxs("span",{className:["af-memory-hint",e.className||""].filter(Boolean).join(" "),children:[s.jsxs("button",{type:"button",className:"af-memory-hint__btn",onClick:()=>void d(),disabled:t,title:e.title||(e.command?e.command:`open ${u}`),"aria-label":`Open ${e.kind||"memory"} entry: ${e.label}`,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:l},"aria-hidden":"true"}),s.jsx("span",{className:"af-memory-hint__label",children:e.label}),e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:_b(u)}):null,s.jsx("span",{className:"af-memory-hint__act","aria-hidden":"true",children:t?"…":"↗"})]}),e.command?s.jsx("code",{className:"af-memory-hint__cmd",children:e.command}):null,r?s.jsx("span",{className:"af-memory-hint__err",role:"alert",children:r}):null]})}const pb=["Your voices","Engine voices","Shared voices"];function Qj(e){var r,i;const t=e&&e.tags||{},n=(i=(r=e==null?void 0:e.params)==null?void 0:r.meta)==null?void 0:i.scope;return t.builtin?"Shared voices":(e==null?void 0:e.kind)==="clone"||(e==null?void 0:e.voice_kind)==="clone"?n==="library"?"Shared voices":"Your voices":"Engine voices"}function kg(e){var t;return String((e==null?void 0:e.language)||((t=e==null?void 0:e.tags)==null?void 0:t.language_code)||"").trim().toLowerCase()}function LE(e){return Array.from(new Set(e.map(kg).filter(Boolean))).sort()}function IE(e,t){if(!t)return!0;const n=kg(e);if(n===t)return!0;const r=Array.isArray(e==null?void 0:e.languages)?e.languages.map(i=>String(i).toLowerCase()):[];return!n&&r.length===0?!0:r.includes(t)}const eS={en:"English",fr:"French",de:"German",es:"Spanish",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",nl:"Dutch",pl:"Polish",tr:"Turkish",ar:"Arabic",hi:"Hindi"},tS=eS,mu=e=>tS[e]||e,wy=e=>String((e==null?void 0:e.voice_id)||(e==null?void 0:e.id)||""),G_=e=>Array.isArray(e)?e.map(t=>typeof t=="string"?t:(t==null?void 0:t.id)||(t==null?void 0:t.name)).filter(Boolean):[],OE=200;function PE({value:e,onChange:t,fetchCatalog:n,intro:r,delivery:i=!0,quality:o=!0,showReset:u=!0,defaultHint:l,voiceDefaultLabel:d,createVoice:h,voiceLibrary:m,previewVoice:_,previewOn:g,recordFrom:y}){var ct,Qe,Dt,$e,Le;const b=m||h,[k,x]=p.useState({state:"idle",error:""}),N=p.useRef(0),$=p.useRef(null),E=p.useRef(null),S=p.useRef(null),P=p.useRef(null),D=p.useRef(n);D.current=n;const[R,I]=p.useState({}),[W,G]=p.useState(""),[K,H]=p.useState(!1),[M,A]=p.useState(""),[O,L]=p.useState(0),V=p.useRef(e);V.current=e;const J=p.useRef(!0),U=()=>{var ce,Q;N.current+=1,P.current!==null&&clearTimeout(P.current),P.current=null,(ce=$.current)==null||ce.abort(),$.current=null,(Q=E.current)==null||Q.abort(),E.current=null};p.useEffect(()=>(J.current=!0,()=>{J.current=!1,U()}),[]);const te=ce=>JSON.stringify([ce.provider||"",ce.model||"",ce.voice||"",ce.profile||""]),z=ce=>`The sample did not play: ${String((ce==null?void 0:ce.message)||ce).replace(/\.$/,"")}.`,ne=(ce,Q)=>{const _e=new AbortController;E.current=_e,x({state:"playing",error:""}),Xj(ce,{deviceId:(g==null?void 0:g.deviceId)||"",volume:g==null?void 0:g.volume,signal:_e.signal}).then(()=>J.current&&N.current===Q&&x({state:"idle",error:""})).catch(le=>J.current&&N.current===Q&&x({state:"idle",error:z(le)}))},se=ce=>{if(!_)return;U();const Q=N.current,_e=new AbortController;$.current=_e,x({state:"loading",error:""}),_(ce,void 0,{signal:_e.signal}).then(le=>{!J.current||N.current!==Q||($.current=null,S.current={key:te(ce),bytes:le},ne(le,Q))}).catch(le=>{!J.current||N.current!==Q||($.current=null,x({state:"idle",error:z(le)}))})},de=ce=>{if(!_)return;U();const Q=N.current;if(S.current&&S.current.key===te(ce)){ne(S.current.bytes,Q);return}x({state:"loading",error:""}),P.current=setTimeout(()=>{P.current=null,J.current&&N.current===Q&&se(ce)},OE)},be=()=>{if(k.state!=="idle"){U(),x({state:"idle",error:""});return}const ce=V.current;if(S.current&&S.current.key===te(ce)){U(),ne(S.current.bytes,N.current);return}se(ce)};p.useEffect(()=>{A("")},[e.provider]),p.useEffect(()=>{let ce=!0;return H(!0),I({}),G(""),D.current(e.provider,e.model).then(Q=>{ce&&(I(Q),G(Q.error?String(Q.error):""))}).catch(Q=>{ce&&G(String((Q==null?void 0:Q.message)||Q))}).finally(()=>{ce&&H(!1)}),()=>{ce=!1}},[e.provider,e.model,O]);const Me=Array.isArray(R.items)?R.items:[...Array.isArray(R.profiles)?R.profiles.map(ce=>({...ce,voice_kind:"profile"})):[],...Array.isArray(R.voices)?R.voices.map(ce=>({...ce,voice_kind:"voice"})):[]],je=ce=>JSON.stringify([ce.provider||"",ce.model||"",ce.voice_kind==="profile"?"profile":"voice",ce.id]),ae=ce=>(!e.provider||!ce.provider||ce.provider===e.provider)&&(!e.model||!ce.model||ce.model===e.model),xe=Me.find(ce=>ce.id===(e.profile||e.voice)&&ce.voice_kind==="profile"==!!e.profile&&ae(ce))||(!e.profile&&e.voice?Me.find(ce=>ce.id===e.voice&&ce.voice_kind==="profile"&&ae(ce)):void 0),Ae=xe?je(xe):e.profile||e.voice?JSON.stringify([e.provider||"",e.model||"",e.profile?"profile":"voice",e.profile||e.voice]):"",He=LE(Me),mt=He.length>1;p.useEffect(()=>{!mt&&!K&&A("")},[mt,K]);const nt=mt?M:"",rt=Me.filter(ce=>(ce==null?void 0:ce.id)&&(!e.provider||!ce.provider||ce.provider===e.provider)&&(IE(ce,nt)||je(ce)===Ae)).map(ce=>{const Q=kg(ce);return{value:je(ce),group:Qj(ce),label:`${ce.label||ce.name||ce.id}${Q?` · ${mu(Q)}`:""}${!e.provider&&ce.provider?` · ${ce.provider}`:""}`}}).sort((ce,Q)=>pb.indexOf(ce.group)-pb.indexOf(Q.group)),ze=String(((ct=xe==null?void 0:xe.tags)==null?void 0:ct.description)||"").trim();Ae&&!rt.some(ce=>ce.value===Ae)&&rt.unshift({value:Ae,group:"",label:`${e.profile||e.voice} (saved)`});const Ve=ce=>t({...e,...ce});return s.jsxs("div",{className:"af-voice-settings",children:[r===void 0?s.jsx("p",{children:"Speech is generated by your authenticated Gateway. Leave routing and voice unset to use its defaults."}):r,s.jsx(Rj,{defaultHint:l,value:{provider:e.provider||"",model:e.model||""},onChange:ce=>{U(),x({state:"idle",error:""}),t({...e,...ce,voice:"",profile:""})},fetchProviders:async()=>{const ce=await D.current();if(ce.error&&!G_(ce.tts_providers||ce.providers).length)throw new Error(ce.error);return G_(ce.tts_providers||ce.providers).map(Q=>({name:Q}))},fetchModels:async ce=>{var pe,dt;const Q=await D.current(ce),_e=G_(((pe=Q.tts_models_by_provider)==null?void 0:pe[ce])||Q.tts_models||Q.models),le=Array.isArray((dt=Q.tts_model_details_by_provider)==null?void 0:dt[ce])?Q.tts_model_details_by_provider[ce]:[],Se=new Map(le.filter(yt=>yt&&yt.id).map(yt=>[String(yt.id),String(yt.label||(yt.role==="cloning"?`${yt.id} (clones)`:yt.id))]));return _e.map(yt=>({id:yt,label:Se.get(yt)||yt}))},providerLabel:"Speech provider",modelLabel:"Speech model"}),mt?s.jsxs("label",{children:["Voices that speak",s.jsx(Br,{ariaLabel:"Voice language",placeholder:"Any language",value:M,searchable:!1,options:[{value:"",label:"Any language"},...He.map(ce=>({value:ce,label:mu(ce)}))],onChange:A})]}):null,s.jsxs("label",{children:["Voice / profile",s.jsxs("span",{className:"af-voice-settings__voice-row",children:[s.jsx(Br,{ariaLabel:"AI voice",placeholder:d||"Gateway / provider default",value:Ae,disabled:K,options:[{value:"",label:d||"Gateway / provider default"},...rt],onChange:ce=>{let Q;if(!ce)Q={voice:"",profile:""};else{const[_e,le,Se,pe]=JSON.parse(ce);Q={provider:_e||e.provider||"",model:le||(_e&&_e!==e.provider?"":e.model)||"",voice:Se==="voice"?pe:"",profile:Se==="profile"?pe:""}}Ve(Q),de({...e,...Q})}}),_?s.jsx("button",{type:"button",className:"af-voice-settings__sample","data-action":"play-sample","data-state":k.state,"aria-busy":k.state==="loading","aria-label":k.state==="playing"?"Stop the sample":k.state==="loading"?"Cancel the sample":"Play a sample of this voice",title:k.state==="playing"?"Stop":k.state==="loading"?"Synthesizing… (click to cancel)":"Play a sample",disabled:K&&k.state==="idle",onClick:be,children:s.jsx("span",{"aria-hidden":"true",children:k.state==="playing"?"■":"▶"})}):null]})]}),k.error?s.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status","data-voice-note":"sample",children:k.error}):null,ze?s.jsx("p",{className:"af-voice-settings__description",children:ze}):null,K?s.jsx("p",{role:"status",children:"Loading available voices…"}):null,W?s.jsxs("p",{role:"alert",children:["Voice discovery unavailable: ",W,". Your saved choice is preserved."]}):null,!K&&!W&&e.provider&&Me.length===0&&String(R.unavailable_reason||"").trim()?s.jsx("p",{className:"af-voice-note",role:"status","data-voice-note":"unavailable",children:String(R.unavailable_reason).trim()}):null,i?s.jsxs(s.Fragment,{children:[s.jsxs("label",{children:["Speaking speed",s.jsxs("select",{"aria-label":"Speech speed",value:e.speed??"",onChange:ce=>Ve({speed:ce.target.value?Number(ce.target.value):void 0}),children:[s.jsx("option",{value:"",children:"Gateway default"}),[.5,.75,1,1.25,1.5,2].map(ce=>s.jsxs("option",{value:ce,children:[ce,"×"]},ce))]})]}),o&&((Dt=(Qe=R.controls)==null?void 0:Qe.quality_preset)!=null&&Dt.supported)?s.jsxs("label",{children:["Quality",s.jsxs("select",{"aria-label":"Speech quality",value:e.quality_preset||"",onChange:ce=>Ve({quality_preset:ce.target.value}),children:[s.jsx("option",{value:"",children:"Gateway default"}),G_(R.controls.quality_preset.values).map(ce=>s.jsx("option",{value:ce,children:ce},ce))]})]}):null,(Le=($e=R.controls)==null?void 0:$e.instructions)!=null&&Le.supported?s.jsxs("label",{children:["Delivery instructions",s.jsx("textarea",{"aria-label":"Voice delivery instructions",rows:3,placeholder:"For example: calm, clear, and conversational",value:e.instructions||"",onChange:ce=>Ve({instructions:ce.target.value})})]}):null]}):null,b&&(b.design||b.clone)?s.jsx(zE,{creation:b,defaultLanguage:nt,recordFrom:y,onCreated:(ce,Q)=>{const _e=V.current;t({..._e,provider:Q||_e.provider||"",model:"",voice:ce,profile:""}),L(le=>le+1)}}):null,m!=null&&m.list?s.jsx(UE,{library:m,refreshKey:O,onChanged:()=>L(ce=>ce+1),onRemoved:ce=>{const Q=V.current;Q.voice===ce&&t({...Q,voice:""})}}):null,u?s.jsx("button",{type:"button",onClick:()=>t({}),children:"Reset to Gateway defaults"}):null]})}const DE={value:"",label:"Detect from the recording"},FE=3e4;function zE({creation:e,defaultLanguage:t,onCreated:n,recordFrom:r,cloneRoute:i}){const[o,u]=p.useState(e.design?"design":"clone"),[l,d]=p.useState(""),[h,m]=p.useState(""),[_,g]=p.useState(t||"en"),[y,b]=p.useState(""),[k,x]=p.useState(null),[N,$]=p.useState(""),[E,S]=p.useState(!1),[P,D]=p.useState(!1),[R,I]=p.useState(0),[W,G]=p.useState({text:"",tone:"info"}),K=p.useRef(!1),H=p.useRef(!0),M=p.useRef(null);p.useEffect(()=>(H.current=!0,()=>{var U;H.current=!1,(U=M.current)==null||U.abort()}),[]);const A=Object.keys(tS).map(U=>({value:U,label:mu(U)})),O=o==="design"?_:y,L=()=>{if(M.current){M.current.abort();return}const U=new AbortController;M.current=U;const te=Date.now();D(!0),G({text:"Recording — read a few sentences, then press Stop.",tone:"info"}),Yj({deviceId:(r==null?void 0:r.deviceId)||"",gain:r==null?void 0:r.gain,ms:FE,signal:U.signal,onLevel:z=>H.current&&I(z)}).then(({blob:z,peak:ne})=>{if(H.current){if(ne<Jj){G({text:"The microphone recorded silence. Pick another input in the voice settings, then record again.",tone:"error"});return}x(z),G({text:`Recording ready (${Math.max(1,Math.round((Date.now()-te)/1e3))} s).`,tone:"ok"})}}).catch(z=>{H.current&&((z==null?void 0:z.name)==="AbortError"?G({text:"Recording cancelled.",tone:"info"}):G({text:Up(z),tone:"error"}))}).finally(()=>{M.current===U&&(M.current=null),H.current&&(D(!1),I(0))})},V=async()=>{if(!(K.current||M.current)){K.current=!0,S(!0),G({text:o==="design"?"Creating the voice from your description…":"Cloning the voice from your recording…",tone:"info"});try{const U=o==="design"?await e.design({description:l.trim(),name:h.trim()||void 0,language:_}):await e.clone(k,{name:h.trim()||void 0,reference_text:N.trim()||void 0,...y?{language:y}:{},...i!=null&&i.provider?{provider:i.provider}:{},...i!=null&&i.provider&&i.model?{model:i.model}:{}});if(!H.current)return;G({text:`Voice ready: ${U.name||U.voice_id}. It is selected above.`,tone:"ok"}),n(U.voice_id,U.engine||(o==="design"?"qwen3-tts":void 0))}catch(U){if(!H.current)return;G({text:`The voice was not created: ${String((U==null?void 0:U.message)||U).replace(/\.$/,"")}.`,tone:"error"})}finally{K.current=!1,H.current&&S(!1)}}},J=o==="design"?!!l.trim():!!k&&!P;return s.jsxs("fieldset",{className:"af-voice-create","data-voice-create":!0,children:[s.jsx("legend",{children:"Create a voice"}),s.jsxs("div",{className:"af-voice-create__modes",role:"tablist",children:[e.design?s.jsx("button",{type:"button",role:"tab","aria-selected":o==="design","data-create-mode":"design",disabled:E||P,onClick:()=>u("design"),children:"From a description"}):null,e.clone?s.jsx("button",{type:"button",role:"tab","aria-selected":o==="clone","data-create-mode":"clone",disabled:E||P,onClick:()=>u("clone"),children:"From a recording"}):null]}),o==="design"?s.jsxs("label",{children:["Describe the voice",s.jsx("textarea",{"aria-label":"Voice description",rows:3,placeholder:"A calm, warm adult female voice with a slight British accent, speaking slowly.",value:l,onChange:U=>d(U.target.value)})]}):s.jsxs(s.Fragment,{children:[s.jsxs("label",{children:["Recording",s.jsx("input",{"aria-label":"Voice recording",type:"file",accept:"audio/*",disabled:P,onChange:U=>{const te=U.target.files&&U.target.files[0]||null;x(te),te&&G({text:"",tone:"info"})}})]}),s.jsxs("div",{className:"af-voice-create__record",children:[s.jsx("button",{type:"button","data-action":"record-sample",disabled:E,onClick:L,children:P?"Stop":"Record"}),P?s.jsx("div",{className:"af-voice-meter","data-voice-meter":!0,role:"meter","aria-label":"Recording level","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(R*100),children:s.jsx("span",{className:"af-voice-meter__fill",style:{width:`${Math.round(R*100)}%`}})}):null]}),s.jsxs("label",{children:["What the recording says (optional)",s.jsx("input",{"aria-label":"Recording transcript",value:N,onChange:U=>$(U.target.value)})]})]}),s.jsxs("label",{children:["Name",s.jsx("input",{"aria-label":"Voice name",value:h,placeholder:"My voice",onChange:U=>m(U.target.value)})]}),s.jsxs("label",{children:["Language",s.jsx(Br,{ariaLabel:"Voice language for creation",value:O,searchable:!1,options:o==="design"?A:[DE,...A],onChange:o==="design"?g:b})]}),s.jsx("button",{type:"button","data-action":"create-voice",disabled:E||!J,onClick:V,children:E?"Creating…":"Create voice"}),W.text?s.jsx("p",{className:`af-voice-note af-voice-note--${W.tone}`,role:"status","data-voice-note":"create",children:W.text}):null]})}const BE=e=>Array.isArray(e)?e:Array.isArray(e==null?void 0:e.voices)?e.voices:[],gb=e=>String((e==null?void 0:e.message)||e||"").trim().replace(/\.$/,"");function UE({library:e,refreshKey:t,onChanged:n,onRemoved:r}){const[i,o]=p.useState([]),[u,l]=p.useState({loading:!0,error:""}),[d,h]=p.useState(null),[m,_]=p.useState(""),[g,y]=p.useState(""),[b,k]=p.useState({text:"",tone:"info"}),[x,N]=p.useState(0),$=p.useRef(e);$.current=e;const E=p.useRef(!1),S=p.useRef(!0);p.useEffect(()=>(S.current=!0,()=>{S.current=!1}),[]),p.useEffect(()=>{const R=$.current.list;if(!R)return;let I=!0;return l(W=>({loading:!0,error:W.error})),R().then(W=>{I&&(o(BE(W).filter(G=>{var K;return wy(G)&&!((K=G==null?void 0:G.tags)!=null&&K.builtin)})),l({loading:!1,error:""}))}).catch(W=>I&&l({loading:!1,error:`The voices could not be listed: ${gb(W)}.`})),()=>{I=!1}},[t,x]);const P=(R,I,W,G)=>{E.current||(E.current=!0,y(R),k({text:"",tone:"info"}),I().then(()=>{S.current&&(k({text:W,tone:"ok"}),h(null),_(""),G==null||G(),N(K=>K+1),n==null||n())}).catch(K=>S.current&&k({text:`${gb(K)||"The gateway refused"}.`,tone:"error"})).finally(()=>{E.current=!1,S.current&&y("")}))},D=R=>String(R.name||R.label||wy(R));return s.jsxs("fieldset",{className:"af-voice-library","data-voice-library":!0,children:[s.jsx("legend",{children:"Manage voices"}),u.loading&&!i.length?s.jsx("p",{role:"status",children:"Loading your voices…"}):null,u.error?s.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status","data-voice-note":"library",children:u.error}):null,!u.loading&&!u.error&&!i.length?s.jsx("p",{className:"af-voice-library__empty",children:"No voices of your own yet."}):null,i.length?s.jsx("ul",{className:"af-voice-library__list",children:i.map(R=>{const I=wy(R),W=Qj(R)==="Shared voices",G=kg(R),K=String(R.engine||R.provider||""),H=g===I;return s.jsxs("li",{className:"af-voice-library__item","data-voice-id":I,children:[(d==null?void 0:d.id)===I?s.jsxs("span",{className:"af-voice-library__edit",children:[s.jsx("input",{"aria-label":`New name for ${D(R)}`,value:d.name,onChange:M=>h({id:I,name:M.target.value})}),s.jsx("button",{type:"button","data-action":"save-voice-name",disabled:H||!d.name.trim(),onClick:()=>P(I,()=>$.current.rename(I,{name:d.name.trim()}),`Renamed to ${d.name.trim()}.`),children:"Save"}),s.jsx("button",{type:"button","data-action":"cancel-voice-name",disabled:H,onClick:()=>h(null),children:"Cancel"})]}):s.jsxs("span",{className:"af-voice-library__name",children:[D(R),s.jsx("span",{className:"af-voice-library__meta",children:[W?"Shared":"Yours",G?mu(G):"",K].filter(Boolean).join(" · ")})]}),m===I?s.jsxs("span",{className:"af-voice-library__confirm",role:"group","aria-label":`Delete ${D(R)}?`,children:["Delete ",D(R),"?",s.jsx("button",{type:"button","data-action":"confirm-delete-voice",disabled:H,onClick:()=>P(I,()=>$.current.remove(I),`${D(R)} was deleted.`,()=>r==null?void 0:r(I)),children:"Delete"}),s.jsx("button",{type:"button","data-action":"keep-voice",disabled:H,onClick:()=>_(""),children:"Keep"})]}):(d==null?void 0:d.id)!==I?s.jsxs("span",{className:"af-voice-library__actions",children:[e.rename?s.jsx("button",{type:"button","data-action":"rename-voice",disabled:!!g,onClick:()=>h({id:I,name:D(R)}),children:"Rename"}):null,e.remove?s.jsx("button",{type:"button","data-action":"delete-voice",disabled:!!g,onClick:()=>_(I),children:"Delete"}):null,e.share&&!W?s.jsx("button",{type:"button","data-action":"share-voice",disabled:!!g,onClick:()=>P(I,()=>$.current.share(I),`${D(R)} is shared with everyone.`),children:"Share"}):null]}):null]},I)})}):null,b.text?s.jsx("p",{className:`af-voice-note af-voice-note--${b.tone}`,role:"status","data-voice-note":"library-action",children:b.text}):null]})}const vy=wt("automations"),WE=wt("trigger-sources"),qE=wt("me/email"),HE=wt("me/email/accounts"),VE=wt("triggers/connections"),GE=wt("automations/schedule-preview");class yb extends Error{constructor(t){super(t.message),this.name="AutomationApiError",this.status=t.status,this.code=t.code,t.field!==void 0&&(this.field=t.field),t.command_id!==void 0&&(this.command_id=t.command_id)}}function KE(e,t){const n=t&&typeof t=="object"?t.detail:void 0;if(n&&typeof n=="object"&&!Array.isArray(n)){const r=n;if(typeof r.reason_code=="string"&&r.reason_code&&typeof r.message=="string"){const i={status:e,code:r.reason_code,message:r.message};return typeof r.field=="string"&&(i.field=r.field),typeof r.command_id=="string"&&(i.command_id=r.command_id),i}}return{status:e,code:"invalid_response",message:`The gateway answered HTTP ${e} without an automation error envelope.`}}function xy(e){const t=new URLSearchParams;for(const[r,i]of Object.entries(e))i!==void 0&&t.set(r,String(i));const n=t.toString();return n?`?${n}`:""}function JE(){return el()}function YE(e){const t=e.newId??JE,n=i=>`${vy}/${encodeURIComponent(i)}`;async function r(i,o,u){const l={accept:"application/json",...e.headers?e.headers():{}},d={method:i,headers:l};u!==void 0&&(l["content-type"]="application/json",d.body=JSON.stringify(u));const h=await e.fetch(Uv(e.baseUrl,o),d),m=await h.text();let _,g=!1;if(m)try{_=JSON.parse(m),g=!0}catch{g=!1}if(!h.ok)throw new yb(KE(h.status,_));if(!g||_===null||typeof _!="object")throw new yb({status:h.status,code:"invalid_response",message:`The gateway answered ${i} ${o} with a body that is not a JSON object.`});return _}return{listAutomations:(i={})=>r("GET",`${vy}${xy({status:i.status,cursor:i.cursor,limit:i.limit})}`),getAutomation:i=>r("GET",n(i)),createAutomation:i=>r("POST",vy,i),reviseAutomation:(i,o)=>r("PATCH",n(i),{command_id:o.command_id??t(),...o.expected_revision!==void 0?{expected_revision:o.expected_revision}:{},changes:o.changes}),sendAutomationCommand:(i,o)=>r("POST",`${n(i)}/commands`,{command_id:o.command_id??t(),type:o.type,...o.payload!==void 0?{payload:o.payload}:{}}),listOccurrences:(i,o={})=>r("GET",`${n(i)}/occurrences${xy({cursor:o.cursor,limit:o.limit})}`),discuss:(i,o)=>r("POST",`${n(i)}/discuss`,{request_id:o.request_id??t(),occurrence_index:o.occurrence_index,prompt:o.prompt}),markSeen:(i,o)=>r("POST",`${n(i)}/seen`,{attention_cursor:o}),listAttention:(i,o={})=>r("GET",`${n(i)}/attention${xy({cursor:o.cursor,limit:o.limit})}`),listTriggerSources:()=>r("GET",WE),getMyEmail:()=>r("GET",qE),listTriggerConnections:()=>r("GET",VE),listMailboxes:()=>r("GET",HE),previewSchedule:i=>r("POST",GE,{trigger:i})}}function nS(e){const t=e==null?void 0:e._runtime,n=Array.isArray(t==null?void 0:t.allowed_tools)?t.allowed_tools:null,r=Array.isArray(e==null?void 0:e.tools)?e.tools:n;return Array.isArray(r)?r.filter(i=>typeof i=="string"&&(!n||n.includes(i))):null}function sS(e,t){const n={...e},r=e._runtime&&typeof e._runtime=="object"?{...e._runtime}:{};return t===null?(delete n.tools,delete r.allowed_tools):(n.tools=[...t],r.allowed_tools=[...t]),Object.keys(r).length?n._runtime=r:delete n._runtime,n}function XE(e){const t=["prompt","tools","provider","model","temperature","seed","max_iterations","max_in_tokens","system","_limits"],n={};for(const i of t)i in e&&(n[i]=e[i]);const r=e._runtime;if(r&&typeof r=="object"){const i={};for(const o of["allowed_tools","provider","model","thinking","speculation","stream"])o in r&&(i[o]=r[o]);Object.keys(i).length&&(n._runtime=i)}return n}function Rw(e){return e.flow_id==="@default"?"@default":`${"bundle_ref"in e?e.bundle_ref:""}:${e.flow_id}`}const ZE={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",unarchive:"Unarchive",discuss:"Discuss"},QE={active:`On: it runs on its schedule. Off: paused, scheduled runs are skipped.
44
+ Pausing lets a run in progress finish, without further retries; Run now still works and keeps it paused.
45
+ Making it active again restarts the schedule at its next time after now; times missed while paused are skipped.`,pause:`Stop scheduled runs until you resume.
46
+ A run in progress finishes; a pending retry is cancelled. Run now still works.`,resume:`Restart the schedule at its next time after now.
47
+ Times missed while paused are skipped; resuming does not run it now.`,run_now:`Run it once now, without waiting for the schedule.
48
+ The schedule does not move: the next scheduled run keeps its time, or starts right after this run if its time comes first.
49
+ Does not count toward a run limit. Works while paused; it stays paused.
50
+ Not available while a run is in progress.`,stop_current:`Cancel the run in progress, or its pending retry.
51
+ It ends as cancelled, with no failure notice. The schedule continues.`,revise:`Change the task, schedule or settings.
52
+ Changes apply from the next run; a run in progress keeps its inputs. A changed schedule restarts from now, so no past time runs.`,archive:`Stop it for good: it will not run again.
53
+ A run in progress finishes; the history stays readable.`,unarchive:`Bring it back from the archive, paused: nothing runs until you make it active.
54
+ An automation that had already finished or failed keeps that status; its history is unchanged.`,discuss:`Talk about the results in a separate conversation, seeded with the runs up to this one.
55
+ It has its own workspace (the automation's files are read-only) and never changes the automation.`},eA="Next scheduled run: {time}.",tA="Growing context: later runs see this run in their history.",nA={run_now:{name:"playCircle"}},sA={not_set_up:"Connect a mailbox first — open My email",open_my_email:"open My email",filters_legend:"Only mail that matches (all optional)",from_in:"From these addresses",from_domain_in:"From these domains",to_in:"Sent to these addresses",subject_contains:"Subject contains",has_attachment:"Attachments",has_attachment_any:"any",has_attachment_yes:"only with attachments",has_attachment_no:"only without attachments",list_hint:"Separate entries with commas or new lines. Exact addresses and domains only (no patterns).",every_label:"Check for new mail every",interval_rule:"An automation that runs a model on new mail checks once an hour by default; one that needs no model checks every 60 s. The shortest interval is 60 s.",max_batch_label:"At most this many emails per run",max_batch_hint:"The rest wait for the next run. Each email is read once by this automation; mail that arrived before it was created, or while it is paused, is not processed.",notify_label:"Email result",notify_hint:"Email each completed run’s result to the selected recipients.",recipients_legend:"Recipients",recipients_self:"Only me (default)",recipients_list:"Me and these addresses",recipients_hint:"Separate multiple addresses with commas."},rA={legend:"When",kind_every:"Repeat",kind_daily:"Daily",kind_weekly:"Weekly",kind_monthly:"Monthly",kind_once:"Once at…",every_label:"Every",at_label:"at",time_label:"Time of day",days_legend:"On",days:{mon:"Mon",tue:"Tue",wed:"Wed",thu:"Thu",fri:"Fri",sat:"Sat",sun:"Sun"},day_label:"on day",last_day:"last",once_label:"Run once at",time_zone_line:"in {time_zone} (your account's time zone)",time_zone_line_automation:"in {time_zone} (this automation's time zone)",time_zone_hint:"Daily, weekly, monthly and one-time runs keep this wall-clock time when daylight saving time changes. A day the month does not have (31 in April) runs on its last day. Repeat runs at a fixed interval in UTC.",time_zone_change:"Change in preferences",time_zone_change_hint:"Your account's time zone is set in your preferences; new automations use it.",time_zone_default:"Gateway default ({time_zone})",time_zone_search:"Search time zones",describing:"Checking the schedule…",incomplete:"Incomplete schedule.",error_at:"Pick the time of day (HH:MM).",error_days:"Pick at least one day.",error_day:"Pick a day of the month: 1 to 31, or last.",error_once:"Pick the date and time to run once."},qv={labels:ZE,hints:QE,run_now_next_run_line:eA,run_now_growing_line:tA,icons:nA,email:sA,schedule:rA},Np={manual:"By hand",schedule:"On a schedule",something:"When something arrives",main_mailbox:"your main mailbox"};function wm(e){const t=String(e||"");return t.startsWith("feed")?"feed":t.startsWith("webhook")?"webhook":"other"}function rS(e,t){const n=wm(t);return n==="feed"?`When ${e} has a new item`:n==="webhook"?`When ${e} is called`:`When ${e} sends something`}function iS(e){if(!e)return"";const t=e.config??{};return(typeof t.connection_id=="string"?t.connection_id:typeof e.connection_id=="string"?e.connection_id:"").trim()}function cc(e){if(!e)return!1;const t=String(e.source_id||"");return!(t==="schedule"||t==="manual"||!t)}function jg(e,t){const n=typeof e=="string"?e.trim():"",r=!n||n==="self"?"default":n,i=(t??[]).find(o=>o.account_id===r)??(r==="default"?(t??[]).find(o=>o.primary):void 0);return i!=null&&i.address?i.address:r==="default"?Np.main_mailbox:r}function Hv(e,t){const n=iS(e);return n?(t??[]).find(r=>r.connection_id===n)??null:null}function iA(e,t,n){var u;if(!e||!cc(e))return"";const r=String(e.source_id||"");if(r.startsWith("email"))return jg((u=e.config)==null?void 0:u.account,n);const i=Hv(e,t);if(i!=null&&i.label)return i.label;const o=wm(r);return o==="feed"?"A feed":o==="webhook"?"A webhook":"A connection"}function vm(e,t,n,r){var l;const i=typeof(r==null?void 0:r.trigger_text)=="string"?r.trigger_text.trim():"";if(i)return i;if(!e)return"";const o=String(e.source_id||"");if(o==="schedule"){const d=r==null?void 0:r.schedule_rule_text;return typeof d=="string"&&d.trim()?d.trim():Np.schedule}if(o==="manual")return Np.manual;if(o.startsWith("email"))return`When mail arrives in ${jg((l=e.config)==null?void 0:l.account,n)}`;if(iS(e)){const d=Hv(e,t),h=wm(o),m=(d==null?void 0:d.label)||(h==="feed"?"a feed":h==="webhook"?"a webhook":"a connection");return rS(m,o)}return Np.something}const oA=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function by(e,t){const n=new Date(e),r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(n),i=new Intl.DateTimeFormat("en-GB",{timeZone:t,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(n),[,o,u]=r.split("-"),l=`${Number(u)} ${oA[Number(o)-1]??o}`;return{day:r,clock:i,label:l}}function aA(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;try{return new Intl.DateTimeFormat("en-GB",{timeZone:t}),t}catch{return null}}function Yh(e,t={}){if(!e)return"";const n=Date.parse(e);if(Number.isNaN(n))return"";const r=aA(t.timeZone),i=r??"UTC",o=r?"":" UTC",u=t.nowMs??Date.now(),l=by(n,i),d=by(u,i).day,h=by(u-864e5,i).day;return l.day===d?`${t.style==="day"?"today ":""}${l.clock}${o}`:l.day===h?`yesterday ${l.clock}${o}`:`${l.label} ${l.clock}${o}`}function Va(e){return typeof e=="string"?e.trim():""}function K_(e){return e?`: “${e}”`:""}function J_(e,t,n){return`${e} ${e===1?t:n}`}function lA(e,t={}){var m,_,g;if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e,r=Va(n.type),i=/^abstract\.(.+)\.v(\d+)$/.exec(r),o=i?i[1]:"";if(!o||o==="schedule"||o==="manual")return null;const u=n.data&&typeof n.data=="object"&&!Array.isArray(n.data)?n.data:{},l=Yh(Va(n.time),{timeZone:t.timeZone,nowMs:t.nowMs});let d="",h="";if(o.startsWith("email")){const y=Array.isArray(u.messages)?u.messages:[],b=typeof u.count=="number"?u.count:y.length;if(!b)return null;d=jg((_=(m=t.trigger)==null?void 0:m.config)==null?void 0:_.account,t.mailboxes),h=`${J_(b,"new message","new messages")}${K_(Va((g=y[0])==null?void 0:g.subject))}`}else{const y=Array.isArray(u.events)?u.events:[],b=typeof u.count=="number"?u.count:y.length;if(!b)return null;const k=y[0]&&typeof y[0]=="object"?y[0]:{},x=k.data&&typeof k.data=="object"&&!Array.isArray(k.data)?k.data:{},N=Va(u.connection_id)||Va(n.connectionid),$={source_id:o,config:{connection_id:N}},E=Hv(N?$:t.trigger,t.connections),S=wm(o);d=(E==null?void 0:E.label)||iA(N?$:t.trigger??$,t.connections,t.mailboxes);const P=D=>{var R;return!!D&&typeof D=="object"&&((R=D.data)==null?void 0:R.test)===!0};y.length&&y.every(P)?h=b===1?"Test event":`${b} test events`:S==="webhook"?h=`${J_(b,"call","calls")}${K_(Va(k.subject))}`:S==="feed"?h=`${J_(b,"new item","new items")}${K_(Va(x.title)||Va(k.subject))}`:h=`${J_(b,"new event","new events")}${K_(Va(k.subject))}`}return{source:d,what:h,at:l,text:[d,h,l].filter(Boolean).join(" · ")}}const cA=/^([1-9][0-9]*)([smhd])$/,uA={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function xm(e){if(typeof e!="string")return null;const t=cA.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function dA(e){const t=xm(e);if(!t)return`every ${e}`;const[n,r]=uA[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${r}`}function Lw(e){if(!e)return"";const t=Date.parse(e);if(Number.isNaN(t))return e;const n=new Date(t).toISOString(),r=n.slice(17,19);return`${n.slice(0,10)} ${n.slice(11,16)}${r==="00"?"":`:${r}`} UTC`}function Vv(e,t,n){return vm(e,n==null?void 0:n.connections,n==null?void 0:n.mailboxes,t)}function oS(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const fA={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},Nn=qv.email,aS="email.received",lS=1,hA="1h",mA="60s",cS=60,Gv=100,Iw=1e3,wb=200,vb=200,xb=50;function Sg(e){return!!e&&e.source_id===aS&&e.source_version===lS}function Ng(e){return!!e&&e.effective_enabled===!0}function uS(e){const t=[];for(const n of String(e??"").split(/[\s,;]+/)){const r=n.trim().toLowerCase();r&&!t.includes(r)&&t.push(r)}return t}const _A=/[\s<>,;:"()[\]]/;function Ow(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!_A.test(t)}function pA(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const dS={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function Kv(e){return e?hA:mA}function fS(e){const t=xm(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function ky(e,t,n,r,i){const o=uS(e);if(!o.length)return null;const u=o.filter(l=>!n(l));return u.length&&i.push(`${t}: ${u.join(", ")} ${u.length===1?"is not":"are not"} ${r}.`),o.length>wb&&i.push(`${t}: at most ${wb} entries.`),o}function gA(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=Kv(e.usesModel):!Number.isInteger(e.every.amount)||e.every.amount<1?t.push("The check interval must be a whole number of at least 1."):n.every=`${e.every.amount}${e.every.unit}`,n.every!==void 0&&(fS(n.every)??0)<cS&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=Gv:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>Iw?t.push(`At most this many emails per run: a whole number from 1 to ${Iw}.`):n.max_batch=e.maxBatch;const r={},i=ky(e.fromIn,Nn.from_in,Ow,"an email address",t);i&&(r.from_in=i);const o=ky(e.fromDomainIn,Nn.from_domain_in,pA,"a domain like example.com",t);o&&(r.from_domain_in=o);const u=ky(e.toIn,Nn.to_in,Ow,"an email address",t);u&&(r.to_in=u);const l=e.subjectContains.trim();return l&&(l.length>vb||/[\r\n]/.test(l)?t.push(`${Nn.subject_contains}: one line of at most ${vb} characters.`):r.subject_contains=l),e.hasAttachment==="yes"?r.has_attachment=!0:e.hasAttachment==="no"&&(r.has_attachment=!1),Object.keys(r).length&&(n.filter=r),{config:n,errors:t}}function hS(e){const t=e,n=t.filter??{},r=["when an email arrives"],i=[...n.from_in??[],...n.from_domain_in??[]];i.length&&r.push(`from ${i.join(", ")}`),n.to_in&&n.to_in.length&&r.push(`to ${n.to_in.join(", ")}`),typeof n.subject_contains=="string"&&n.subject_contains&&r.push(`subject contains “${n.subject_contains}”`),n.has_attachment===!0&&r.push("with attachments"),n.has_attachment===!1&&r.push("without attachments");const o=typeof t.every=="string"?t.every:Kv(t.uses_model!==!1);r.push(`checked ${dA(o)}`);const u=typeof t.max_batch=="number"?t.max_batch:Gv;return r.push(`up to ${u} per run`),r.join(" · ")}const Hh={mode:"self",addresses:""};function Pw(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=uS(e.addresses).filter(i=>i!=="self");n.length||t.push("Name at least one address the automation may email, or choose Only me.");const r=n.filter(i=>!Ow(i));return r.length&&t.push(`${Nn.recipients_list}: ${r.join(", ")} ${r.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>xb&&t.push(`At most ${xb-1} addresses.`),{recipients:["self",...n],errors:t}}function yA(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function wA(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function mS(e,t=["self"]){return{channels:e?["console","email"]:["console"],...t.some(n=>n!=="self")?{recipients:t}:{}}}function _S(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function vA(e){return _S(e)?"In the console and by email":"In the console"}const po={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive",unarchive:"automation.unarchive"},xA=new Set(["running","waiting","backoff"]);function bA(e,t=[]){return e.current_occurrence!=null}function pS(e){const t=e.current_occurrence;if(!t)return null;const n=t.attempt>1?` (attempt ${t.attempt})`:"";return t.status==="backoff"?`Run #${t.index} waiting to retry (attempt ${t.attempt+1})`:t.status==="admitted"?`Run #${t.index} starting${n}`:`Run #${t.index} running${n}`}function gS(e,t){var n;return e.next_run_at&&e.next_run_local?`${SS(e.next_run_local,e.time_zone)} (${kA(e.next_run_at,t)})`:e.status==="paused"?"none while paused":e.status==="active"&&e.trigger&&cc(e.trigger)?bb.event:e.status==="active"&&((n=e.trigger)==null?void 0:n.source_id)==="manual"?bb.manual:"none scheduled"}const bb={event:"when something new arrives",manual:"when someone presses Run now"};function kA(e,t){const n=Date.parse(e);if(Number.isNaN(n))return"";const r=Math.round((n-t)/6e4);if(r<=0)return"due now";if(r<60)return`in ${r} min`;const i=Math.floor(r/60);return i<24?`in ${i} h${r%60?` ${r%60} min`:""}`:`in ${Math.floor(i/24)} d${i%24?` ${i%24} h`:""}`}function Xh(e,t=[],n=!1){const r=new Set(e.capabilities),i=e.status,o=bA(e,t),u=(m,_,g)=>n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:r.has(m)?i==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:_?{enabled:!0}:{enabled:!1,reason:g}:{enabled:!1,reason:"Not permitted for this automation."},l=i==="active"||i==="paused",d=i==="active"?"pause":"resume";return{active:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:i==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:l?r.has(d)?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."}:{enabled:!1,reason:"The automation has ended."},pause:u("pause",i==="active",i==="paused"?"Already paused.":"The automation has ended."),resume:u("resume",i==="paused",i==="active"?"Already running on schedule.":"The automation has ended."),run_now:u("run_now",l&&!o,o?"An occurrence is in progress.":"The automation has ended."),stop_current:u("stop_current",o,"Nothing is running."),revise:u("revise",!0,""),archive:u("archive",!0,""),unarchive:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:i!=="archived"?{enabled:!1,reason:"Not archived."}:r.has("unarchive")?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."},discuss:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: discussion is not available."}:r.has("discuss")?{enabled:!0}:{enabled:!1,reason:"Discussion is not permitted for this automation."}}}function jA(e){return e.status==="active"?po.pause:po.resume}function SA(e){return e.status==="failed"?"failed":e.waits.length>0||e.status==="waiting"?"waiting":e.notify!==null?"notified":e.status==="running"||e.status==="backoff"?"running":"quiet"}function NA(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=SA(t),r=`${t.attempts} ${t.attempts===1?"attempt":"attempts"}`,i=n==="failed"?`Failed after ${r}`:n==="waiting"?"Waiting for you":n==="notified"?"Notified":n==="running"?"Running":null,o=t.status==="completed"&&t.attempts>1?`completed after ${r}`:t.status;return{row:t,tone:n,notable:n==="failed"||n==="waiting"||n==="notified",badge:i,statusText:o,canDiscuss:!xA.has(t.status)}})}function $A(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function yS(e){const t=e.attention,n=[];return t.unseen_count>0&&n.push(`${t.unseen_count} unseen`),t.pending_waits>0&&n.push(`${t.pending_waits} waiting for you`),n.length?n.join(" · "):"nothing new"}const CA={unauthorized:"Sign in to the gateway to manage automations.",forbidden:"You are not allowed to do this with automations.",automation_not_found:"This automation does not exist (or is not yours).",occurrence_not_found:"That occurrence does not exist.",revision_conflict:"The automation changed since this view loaded. Reload it, then try again.",automation_busy:"An occurrence is already running or queued. Wait for it to finish.",invalid_state:"The automation's current state does not allow this.",identity_conflict:"This request id was already used for a different request.",invalid_request:"The gateway rejected the request as malformed.",invalid_definition:"The automation definition is not valid.",unsupported_feature:"The gateway does not support this yet.",unknown_trigger_source:"The gateway does not know this trigger source.",invalid_response:"The gateway gave an unexpected answer.",invalid_payload:"That answer could not be sent."};function Wp(e){return{title:CA[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function Jv(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.status=="number"&&typeof t.code=="string"&&typeof t.message=="string"}function wS(e,t){var o,u,l;const n=e.trigger,r=n.source_id==="schedule"||Sg(n)?n.config.every:void 0,i=t?t.target.input_data.prompt:void 0;return{title:e.title,every:typeof r=="string"?r:null,calendar:TA(n)?IA(n.config):null,context:e.context_mode,growingMaxTokens:Number(((u=(o=t==null?void 0:t.context)==null?void 0:o.growing)==null?void 0:u.max_tokens)??e.growing_max_tokens??Zh),prompt:typeof i=="string"?i:null,toolApproval:t?t.policy.tool_approval:null,tools:nS(t==null?void 0:t.target.input_data),notifyEmail:t?_S(t.notify):null,emailRecipients:t?yA((l=t.notify)==null?void 0:l.recipients):null}}function EA(e,t,n){var d;const r=[],i={},o=t.title.trim();o?o.length>120?r.push("Title is at most 120 characters."):o!==e.title&&(i.title=o):r.push("Title is required.");const u=wS(e,n);if(t.every!==u.every&&t.every!==null){const h=Sg(e.trigger);if(!xm(t.every))r.push("Interval must be a whole number of minutes, hours or days.");else if(h&&(fS(t.every)??0)<cS)r.push("The check interval is at least 60 seconds.");else{const m={...e.trigger.config,every:t.every};h&&delete m.start_at,i.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:m}}}if(t.calendar&&u.calendar&&JSON.stringify(t.calendar)!==JSON.stringify(u.calendar)){const h=Yv(t.calendar);if(!h.config)r.push(...h.errors);else{const m=e.trigger.config,_={...h.config,...typeof m.time_zone=="string"?{time_zone:m.time_zone}:{},...typeof m.count=="number"?{count:m.count}:{},...typeof m.until=="string"?{until:m.until}:{}};i.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:_}}}const l=t.context==="growing"?t.growingMaxTokens??u.growingMaxTokens:u.growingMaxTokens;if(xS(l)||r.push(vS),(t.context!==e.context_mode||l!==u.growingMaxTokens)&&(i.context=bS(t.context,l)),n&&typeof u.prompt=="string"&&typeof t.prompt=="string"&&t.prompt.trim()!==u.prompt.trim()){const h=t.prompt.trim();h?i.target={bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:{...n.target.input_data,prompt:h}}:r.push("Task is required.")}if(n&&t.tools!==void 0&&JSON.stringify(t.tools)!==JSON.stringify(u.tools)){const h=i.target||{bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:n.target.input_data};i.target={...h,input_data:sS(h.input_data||{},t.tools)}}if(n&&t.toolApproval&&t.toolApproval!==u.toolApproval&&(i.policy={tool_approval:t.toolApproval}),n&&typeof t.notifyEmail=="boolean"){const h=Pw(t.notifyEmail?t.emailRecipients??Hh:u.emailRecipients??Hh),m=Pw(u.emailRecipients??Hh).recipients;h.errors.length?r.push(...h.errors):(t.notifyEmail!==u.notifyEmail||JSON.stringify(h.recipients)!==JSON.stringify(m))&&(i.notify=mS(t.notifyEmail,h.recipients))}if(r.length)return{errors:r};if(n&&t.target&&Rw(t.target)!==Rw(n.target)){const h=((d=i.target)==null?void 0:d.input_data)||n.target.input_data;i.target={...t.target,input_data:XE(h)}}return Object.keys(i).length?i:null}const Zh=5e4,AA="Limits history carried into the next run, keeping recent whole turns. The newest turn is kept even if oversized. New messages and tool results can grow context beyond this budget.",vS="Max growing context must be a positive whole number of tokens.";function xS(e){return Number.isSafeInteger(e)&&e>0}function bS(e,t){return{mode:e,...t!==Zh?{growing:{max_tokens:t}}:{}}}const us=qv.schedule,qp=["mon","tue","wed","thu","fri","sat","sun"],kS=["daily","weekly","monthly"],jS=2;function TA(e){return e.source_id==="schedule"&&e.source_version===jS}const MA=/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/;function SS(e,t){if(!e)return"";const n=MA.exec(e);return n?`${n[1]} ${n[2]}${t?` ${t}`:""}`:e}function RA(e,t="account"){return(t==="account"?us.time_zone_line:us.time_zone_line_automation).replace("{time_zone}",e)}const LA=/^([01][0-9]|2[0-3]):[0-5][0-9]$/;function NS(e){return kS.includes(e.kind)}function Yv(e){const t=[];if(LA.test(e.at)||t.push(us.error_at),e.kind==="weekly"){const n=qp.filter(r=>e.days.includes(r));return n.length||t.push(us.error_days),t.length?{config:null,errors:t}:{config:{kind:"weekly",days:n,at:e.at},errors:t}}return e.kind==="monthly"?(e.day==="last"||Number.isInteger(e.day)&&e.day>=1&&e.day<=31||t.push(us.error_day),t.length?{config:null,errors:t}:{config:{kind:"monthly",day:e.day,at:e.at},errors:t}):t.length?{config:null,errors:t}:{config:{kind:"daily",at:e.at},errors:t}}function IA(e){const t=e,n=typeof t.at=="string"?t.at:"";return t.kind==="daily"?{kind:"daily",at:n}:t.kind==="weekly"?{kind:"weekly",at:n,days:Array.isArray(t.days)?qp.filter(r=>t.days.includes(r)):[]}:t.kind==="monthly"?{kind:"monthly",at:n,day:t.day==="last"?"last":Number(t.day)}:null}const OA=[{label:"every 5 minutes",when:{kind:"every",amount:5,unit:"m"}},{label:"every 30 minutes",when:{kind:"every",amount:30,unit:"m"}},{label:"every hour",when:{kind:"every",amount:1,unit:"h"}},{label:"every 8 hours",when:{kind:"every",amount:8,unit:"h"}},{label:"every 24 hours",when:{kind:"every",amount:24,unit:"h"}},{label:"every 7 days",when:{kind:"every",amount:7,unit:"d"}}];function $S(e){if(!e)return null;const t=/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})(:\d{2})?$/.exec(e.trim());if(!t)return null;const n=`${t[1]}T${t[2]}${t[3]??":00"}Z`;return Number.isNaN(Date.parse(n))?null:n}function PA(e){const t=e.trim().split(`
56
+ `)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}const DA=/^\d{4}-\d{2}-\d{2}T([01][0-9]|2[0-3]):[0-5][0-9]$/;function kb(e,t){const n={};if(e.count!==void 0&&(!Number.isInteger(e.count)||e.count<1?t.push("Maximum runs must be a whole number of at least 1."):n.count=e.count),e.until){const r=$S(e.until);r?n.until=r:t.push("Stop at must be a date and time (UTC).")}return n}function FA(e){const t=[],n=e.when;if(n.kind==="once"){const l=(n.at||"").trim().slice(0,16);return DA.test(l)?{config:{kind:"once",at:l},errors:t}:{config:null,errors:[us.error_once]}}if(NS(n)){const l=Yv(n),d=kb(e,l.errors);return l.config&&!l.errors.length?{config:{...l.config,...d},errors:[]}:{config:null,errors:l.errors}}const r=n.amount;let i=null;!Number.isInteger(r)||r<1?t.push("The interval must be a whole number of at least 1."):i=`${r}${n.unit}`;let o=null;e.startAt&&(o=$S(e.startAt),o||t.push("First run must be a date and time (UTC)."));const u=kb(e,t);return t.length||!i?{config:null,errors:t}:{config:{kind:"every",every:i,...o?{start_at:o}:{},...u},errors:t}}function CS(e){const t=FA(e);return t.config?{trigger:{source_id:"schedule",source_version:jS,config:t.config},errors:[]}:{trigger:null,errors:t.errors}}function zA(e){return e.kind==="every"||e.kind==="once"||NS(e)}function ES(e,t){const n=[];t.target||n.push("Choose what to run.");const r=e.prompt.trim();r||n.push("Write the task to run.");const i=(e.title??"").trim()||PA(r);i.length>120&&n.push("Title is at most 120 characters.");const o=e.trigger==="email",u=o?gA(e.email??dS):null,l=o?null:CS(e);n.push(...u?u.errors:l.errors);const d=e.notifyEmail&&e.emailRecipients&&e.emailRecipients.mode==="list"?Pw(e.emailRecipients):null;d&&n.push(...d.errors);const h=e.growingMaxTokens??Zh;if(e.context==="growing"&&!xS(h)&&n.push(vS),n.length||!t.target)return{ok:!1,errors:n};const m={...t.target,input_data:{...t.target.input_data??{},prompt:r}},_={request_id:t.requestId,title:i,target:m,trigger:u?{source_id:aS,source_version:lS,config:u.config}:l.trigger,context:bS(e.context,e.context==="growing"?h:Zh),policy:{tool_approval:e.toolApproval??"auto"}};return e.notifyEmail===!0&&(_.notify=mS(!0,d==null?void 0:d.recipients)),{ok:!0,body:_}}const BA="Tools run without asking (you approve them now by creating this automation)";function UA(e){if(e.kind!=="tool_approval"||!Array.isArray(e.details))return null;const t=[];for(const n of e.details){if(!n||typeof n!="object"||Array.isArray(n))return null;const r=n;if(typeof r.name!="string"||!r.arguments||typeof r.arguments!="object"||Array.isArray(r.arguments)||r.call_id!==void 0&&typeof r.call_id!="string")return null;t.push({name:r.name,arguments:r.arguments,...typeof r.call_id=="string"?{call_id:r.call_id}:{}})}return t}function WA(e){const t=e.trim();if(!t)return{ok:!1,error:"Enter a JSON payload."};try{return{ok:!0,payload:JSON.parse(t)}}catch(n){return{ok:!1,error:`The payload is not valid JSON (${n instanceof Error?n.message:String(n)}).`}}}const AS={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class qA{constructor(t){this.mint=t,this.open=new Map}idFor(t){let n=this.open.get(t);return n===void 0&&(n=this.mint(),this.open.set(t,n)),n}settle(t,n){(n.ok||HA(n.error))&&this.open.delete(t)}}function HA(e){return Jv(e)&&e.status>0&&e.code!=="invalid_response"}function VA(){return el()}class GA{constructor(){this.acked=null,this.inflight=null,this.failedKey=null,this.failedToken=void 0}next(t,n){return!t||t===this.acked||t===this.inflight||t===this.failedKey&&n===this.failedToken?null:(this.inflight=t,t)}succeeded(t){this.inflight===t&&(this.inflight=null),this.acked=t,this.failedKey=null}failed(t,n){this.inflight===t&&(this.inflight=null),this.failedKey=t,this.failedToken=n}get acknowledged(){return this.acked}}function jb(e,t){if(!e)return null;for(const n of t){const r=e.querySelector(n);if(r&&r.disabled!==!0&&typeof r.focus=="function")return r}return null}const KA="08:00",JA=["mon"],TS={at:KA,days:[...JA],day:1};function Xv(e,t){return e==="weekly"?{kind:e,at:t.at,days:[...t.days]}:e==="monthly"?{kind:e,at:t.at,day:t.day}:{kind:e,at:t.at}}function Zv(e,t){return{...e,at:t.at,...t.kind==="weekly"?{days:[...t.days]}:{},...t.kind==="monthly"?{day:t.day}:{}}}function Sb(e){return Zv(TS,e)}const YA=[...Array.from({length:31},(e,t)=>String(t+1)),"last"];function MS(e){const t=e.value,n=r=>{if(t.kind!=="weekly")return;const i=t.days.includes(r);e.onChange({...t,days:qp.filter(o=>o===r?!i:t.days.includes(o))})};return s.jsxs("div",{className:"af-schedule__calendar","data-calendar-kind":t.kind,children:[t.kind==="weekly"?s.jsxs("div",{className:"af-auto__row af-schedule__days",role:"group","aria-label":us.days_legend,children:[s.jsx("span",{children:us.days_legend}),qp.map(r=>s.jsx(B2,{className:"af-schedule__day",pressed:t.days.includes(r),disabled:e.disabled,onClick:()=>n(r),tone:"accent",children:s.jsx("span",{"data-day":r,children:us.days[r]})},r))]}):null,s.jsxs("div",{className:"af-auto__row",children:[t.kind==="monthly"?s.jsxs(s.Fragment,{children:[s.jsx("label",{htmlFor:`${e.idBase}-month-day`,children:us.day_label}),s.jsx("select",{id:`${e.idBase}-month-day`,name:"calendar_day",value:String(t.day),disabled:e.disabled,onChange:r=>e.onChange({...t,day:r.target.value==="last"?"last":Number(r.target.value)}),children:YA.map(r=>s.jsx("option",{value:r,children:r==="last"?us.last_day:r},r))})]}):null,s.jsx("label",{htmlFor:`${e.idBase}-at`,children:us.at_label}),s.jsx("input",{id:`${e.idBase}-at`,name:"calendar_at",type:"time",step:60,required:!0,value:t.at,disabled:e.disabled,"aria-label":us.time_label,onChange:r=>e.onChange({...t,at:r.target.value.slice(0,5)})})]})]})}function XA(e){return s.jsxs("p",{className:"af-schedule__tz","data-time-zone":e.timeZone,children:[s.jsx(lb,{content:us.time_zone_hint,children:s.jsx("span",{tabIndex:0,className:"af-schedule__tz-text",children:RA(e.timeZone,e.whose??"account")})}),e.onOpenPreferences&&(e.whose??"account")==="account"?s.jsxs(s.Fragment,{children:[" · ",s.jsx(lb,{content:us.time_zone_change_hint,children:s.jsx("button",{type:"button",className:"af-auto__link af-schedule__tz-change",onClick:e.onOpenPreferences,children:us.time_zone_change})})]}):null]})}function ZA(e){const t=e;return typeof(t==null?void 0:t.message)=="string"&&t.message?t.message:String(e)}function RS(e,t,n=250){const r=e?JSON.stringify(e):"",[i,o]=p.useState({phase:"idle"}),u=p.useRef(0),l=p.useRef(t);return l.current=t,p.useEffect(()=>{const d=++u.current;if(!r){o({phase:"idle"});return}o({phase:"loading"});const h=setTimeout(()=>{l.current(JSON.parse(r)).then(m=>{u.current===d&&o({phase:"ok",description:m})},m=>{u.current===d&&o({phase:"error",message:ZA(m)})})},n);return()=>clearTimeout(h)},[r,n]),i}function Dw(e){const t=e.state;return t.phase==="ok"?s.jsxs(s.Fragment,{children:[e.showZone===!1?null:s.jsx(XA,{timeZone:t.description.time_zone,whose:e.whose,onOpenPreferences:e.onOpenPreferences}),s.jsx("p",{className:"af-schedule__preview","aria-live":"polite","data-preview":"served",children:t.description.first_run_sentence})]}):t.phase==="error"?s.jsx("p",{className:"af-schedule__preview af-auto__warn",role:"alert","data-preview":"error",children:t.message}):s.jsx("p",{className:"af-schedule__preview","aria-live":"polite","data-preview":t.phase,children:t.phase==="loading"?us.describing:e.incompleteText??us.incomplete})}function Nb(e){const t=Array.from(new Set(e.map(n=>String(n||"").trim()).filter(Boolean)));return t.sort((n,r)=>n.localeCompare(r)),t}function Fw(e){const t=e.disabled===!0,n=p.useMemo(()=>Nb([...e.options||[],...e.value||[]]),[e.options,e.value]),r=p.useMemo(()=>Nb(e.value||[]),[e.value]),[i,o]=p.useState(!1),[u,l]=p.useState(""),d=p.useMemo(()=>{const _=u.trim().toLowerCase();return _?n.filter(g=>g.toLowerCase().includes(_)):n},[n,u]),h=p.useMemo(()=>new Set(r),[r]),m=typeof e.max_list_height_px=="number"?e.max_list_height_px:220;return s.jsxs("div",{className:"af_multi_select",children:[s.jsxs("div",{className:"af_multi_select_row",children:[s.jsxs("button",{className:"btn",type:"button",onClick:()=>o(_=>!_),disabled:t||!n.length,"aria-expanded":i,children:[i?"Hide":"Select"," • ",r.length>0?`${r.length} of ${n.length}`:e.placeholder||"(none)"]}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange(n.slice()),disabled:t||!n.length||r.length===n.length,title:"Select all",children:"All"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange([]),disabled:t||r.length===0,title:"Clear selection",children:"Clear"})]}),r.length>0?s.jsx("div",{className:"af_multi_select_chips",children:r.map(_=>s.jsxs("button",{type:"button",disabled:t,"aria-label":`Remove ${_}`,className:"af_multi_select_chip",title:_,onClick:()=>{if(t)return;const g=new Set(h);g.delete(_),e.onChange(Array.from(g.values()))},children:[_,t?null:s.jsx("span",{className:"af_multi_select_chip_x",children:"×"})]},_))}):null,i?s.jsxs("div",{className:"af_multi_select_panel",children:[s.jsx("input",{className:"mono",value:u,onChange:_=>l(String(_.target.value||"")),placeholder:"filter…","aria-label":"Filter options",disabled:t}),s.jsxs("div",{className:"af_multi_select_list",style:{maxHeight:`${m}px`},children:[d.map(_=>{const g=h.has(_);return s.jsxs("label",{className:`af_multi_select_item mono ${g?"checked":""}`,children:[s.jsx("input",{type:"checkbox",checked:g,disabled:t,onChange:y=>{const b=new Set(h);y.target.checked?b.add(_):b.delete(_),e.onChange(Array.from(b.values()))}}),s.jsx("span",{children:_})]},_)}),d.length?null:s.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function LS(e){return s.jsxs("div",{className:"af-auto__field","data-field":"tool-selection",children:[s.jsxs("label",{children:[s.jsx("input",{type:"checkbox",checked:e.value===null,disabled:e.disabled,onChange:t=>e.onChange(t.target.checked?null:[])})," Use the flow's default tools"]}),e.value!==null?s.jsx(Fw,{options:e.availableTools,value:e.value,disabled:e.disabled,placeholder:"No tools enabled",onChange:e.onChange}):null,s.jsx("p",{className:"af-auto__hint",children:"Choose which tools this automation can use. An empty selection disables tools. Gateway restrictions always apply."})]})}const IS="@default",OS="No workflows available for this app — ask your admin.",PS={shared:"Shared",mine:"Mine"};class Hl extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function QA(e,t={}){const n=String(e||"").trim();if(!n)throw new Error("executableWorkflowsPath needs the interface the app runs (e.g. abstractcode.agent.v1).");return`bundles?executable_for=${encodeURIComponent(n)}${t.allVersions?"&all_versions=true":""}`}function eT(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function tT(e,t={}){return e===null?eT(t):QA(e,t)}function Pi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Hs(e){return typeof e=="string"?e.trim():""}const Y_="update the gateway";function nT(e,t){var l,d;const n=Pi(e.default_agent_workflows);if(!n)return{status:"unavailable",reason:"the gateway does not report a default workflow"};const r=Pi(n[t]);if(!r)return{status:"unavailable",reason:Hs((d=Pi((l=Pi(e.default_agent_workflows_unavailable))==null?void 0:l[t]))==null?void 0:d.reason)||`no default workflow for ${t}`};const i=Hs(r.bundle_id),o=Hs(r.flow_id);if(!i||!o)return{status:"unavailable",reason:"the gateway's default workflow is missing its bundle or flow"};const u=Hs(r.bundle_version);return{status:"ok",name:Hs(r.name)||o,bundleId:i,bundleVersion:u,flowId:o,workflowId:Hs(r.workflow_id)||`${i}${u?`@${u}`:""}:${o}`}}function sT(e,t,n={}){var l,d;const r=Pi(e);if(!r)throw new Hl("The gateway's workflow list is not a JSON object.");const i=Hs(r.executable_for);if(t===null){if(i)throw new Hl(`Asked for every workflow, the gateway listed only ${i}.`)}else if(i!==t)throw new Hl(i?`The gateway listed workflows for ${i}, not ${t}.`:`This gateway does not filter workflows per app (no executable_for in its answer): ${Y_}.`);if(!Array.isArray(r.items))throw new Hl("The gateway's workflow list has no items.");const o=[];for(const h of r.items){const m=Pi(h),_=Hs(m==null?void 0:m.bundle_id);if(!m||!_)throw new Hl("The gateway listed a workflow without a bundle id.");const g=Pi(m.owner),y=Hs(g==null?void 0:g.kind);if(y!=="gateway"&&y!=="user")throw new Hl(`The gateway did not say who owns ${_} (owner missing): ${Y_}.`);if(typeof m.shipped!="boolean")throw new Hl(`The gateway did not say whether ${_} ships with it (shipped missing): ${Y_}.`);const b=Hs(m.bundle_version),k=Array.isArray(m.entrypoints)?m.entrypoints:[];for(const x of k){const N=Pi(x),$=Hs(N==null?void 0:N.flow_id);if(!N||!$)continue;const E=Array.isArray(N.interfaces)?N.interfaces.map(Hs).filter(Boolean):[],S=lT((l=Pi(m.automation_defaults))==null?void 0:l[$]),P=N.triggerable===!0||!!S;if(t===null){if(!E.length&&!P)continue}else if(!E.includes(t))throw new Hl(`The gateway offered ${_}:${$}, which does not declare ${t}: ${Y_}.`);o.push({value:Hs(N.workflow_id)||`${_}${b?`@${b}`:""}:${$}`,bundleId:_,bundleVersion:b,flowId:$,name:Hs(N.name)||Hs((d=Pi(m.metadata))==null?void 0:d.name)||_,description:Hs(N.description)||Hs(m.description),registryScope:Hs(m.registry_scope)||"private",group:y==="user"?"mine":"shared",shipped:m.shipped,interfaces:E,...t===null?{showInterfaces:!0}:{},...S?{automationTrigger:S}:{},...P?{triggerable:!0}:{}})}}const u=n.defaultInterface??t;return{interfaceId:t,entries:o,gatewayDefault:u?nT(r,u):{status:"unavailable",reason:"no interface named for the gateway default"}}}function rT(e){const t=(n,r)=>n.name.localeCompare(r.name)||r.bundleVersion.localeCompare(n.bundleVersion,void 0,{numeric:!0})||n.value.localeCompare(r.value);return["shared","mine"].map(n=>({id:n,label:PS[n],entries:e.filter(r=>r.group===n).sort(t)})).filter(n=>n.entries.length>0)}const iT={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function oT(e){return iT[e]??e}function aT(e,t=[]){const n=e.bundleVersion?`@${e.bundleVersion}`:"";return e.showInterfaces?!e.interfaces.length&&e.automationTrigger?[vm(e.automationTrigger),n].filter(Boolean).join(" · "):[[...new Set(e.interfaces.map(oT))].join(", "),n].filter(Boolean).join(" · "):n}function lT(e){var o;const t=Pi((o=Pi(e))==null?void 0:o.trigger),n=Hs(t==null?void 0:t.source_id);if(!t||!n||typeof t.source_version!="number")return;const r=Pi(t.config)??{},i=Hs(t.connection_id);return{source_id:n,source_version:t.source_version,config:r,...i?{connection_id:i}:{}}}function cT(e){return e.value}function uT(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function dT(e,t,n){return n<=0?null:e==="ArrowDown"?t<0?0:Math.min(n-1,t+1):e==="ArrowUp"?t<0?n-1:Math.max(0,t-1):e==="Home"?0:e==="End"?n-1:null}function fT(e,t=!0){const n=(e==null?void 0:e.entries)??[],r=[];t&&r.push({key:"default",value:IS,name:"Gateway default",detail:uT((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const i of rT(n))for(const o of i.entries)r.push({key:o.value,value:o.value,name:o.name,detail:aT(o,n),title:cT(o),group:i.id,entry:o});return r}async function hT(e,t,n){var o;const r=await fetch(Uv(e,wt(t)),{credentials:"include",headers:{Accept:"application/json"},signal:n}),i=await r.json().catch(()=>null);if(!r.ok){const u=((o=i==null?void 0:i.detail)==null?void 0:o.message)||(i==null?void 0:i.message)||(typeof(i==null?void 0:i.detail)=="string"?i.detail:"");throw new Error(u||`The gateway answered ${r.status}.`)}return i}function mT(e){var n;const t=e;return String(((n=t==null?void 0:t.detail)==null?void 0:n.message)||(t==null?void 0:t.message)||t||"The workflow list could not be loaded.")}function DS(e){const{interfaceId:t,defaultInterface:n,allVersions:r=!1,enabled:i=!0,gatewayBaseUrl:o,reloadKey:u}=e,l=p.useRef(e.request);l.current=e.request;const[d,h]=p.useState(0),[m,_]=p.useState({status:"idle",data:null,error:""});p.useEffect(()=>{if(!i){_({status:"idle",data:null,error:""});return}const y=new AbortController;_(x=>({...x,status:"loading",error:""}));const b=tT(t,{allVersions:r});return(l.current?l.current(b,{signal:y.signal}):hT(o,b,y.signal)).then(x=>{y.signal.aborted||_({status:"ready",data:sT(x,t,{defaultInterface:n}),error:""})}).catch(x=>{y.signal.aborted||_({status:"error",data:null,error:mT(x)})}),()=>y.abort()},[t,n,r,i,o,u,d]);const g=p.useCallback(()=>h(y=>y+1),[]);return{...m,reload:g}}function _T(e){if(!e||typeof window>"u")return{};const t=e.getBoundingClientRect(),n=window.innerWidth,r=window.innerHeight,i=Math.min(Math.max(t.width,300),440,n-32),o=Math.max(16,Math.min(t.left,n-16-i)),u=r-t.bottom-16;return u>=220||u>=t.top?{position:"fixed",left:o,width:i,top:t.bottom+4,maxHeight:Math.max(160,u)}:{position:"fixed",left:o,width:i,bottom:r-t.top+4,maxHeight:Math.max(160,t.top-16)}}function FS(...e){return e.filter(Boolean).join(" ")}function zS(e){const t=DS({interfaceId:e.interfaceId,defaultInterface:e.defaultInterface,request:e.request,gatewayBaseUrl:e.gatewayBaseUrl,allVersions:e.allVersions,enabled:e.workflows?!1:e.enabled!==!1}),n=e.workflows??t,r=e.showDefault!==!1&&(e.interfaceId!==null||!!e.defaultInterface),i=p.useId().replace(/:/g,""),o=`${i}-list`,[u,l]=p.useState(!1),[d,h]=p.useState(-1),m=p.useRef(null),_=p.useRef(null),[g,y]=p.useState({}),b=e.entryDetail,k=p.useMemo(()=>fT(n.data,r).map(I=>{const W=I.entry&&b?b(I.entry):null;return W?{...I,detail:W}:I}),[n.data,r,b]),x=k.find(I=>I.value===e.value),N=x?{name:x.name,detail:x.detail}:e.currentLabel?{name:e.currentLabel.name,detail:e.currentLabel.detail||""}:n.status==="loading"?{name:"Loading flows…",detail:""}:{name:e.value===IS?"Gateway default":"Choose a flow",detail:""},$=String(e.unavailableReason||"").trim(),E=!$&&n.status==="ready",S=p.useCallback(()=>{l(!1),h(-1)},[]),P=p.useCallback(()=>{if(!E)return;y(_T(_.current)),l(!0);const I=k.findIndex(W=>W.value===e.value);h(I>=0?I:0)},[E,k,e.value]),D=p.useCallback(I=>{var W;S(),I.value!==e.value&&e.onChange(I.value,I.entry),(W=_.current)==null||W.focus()},[S,e]);p.useEffect(()=>{if(!u)return;const I=G=>{m.current&&!m.current.contains(G.target)&&S()},W=()=>S();return document.addEventListener("mousedown",I),document.addEventListener("touchstart",I),window.addEventListener("resize",W),()=>{document.removeEventListener("mousedown",I),document.removeEventListener("touchstart",I),window.removeEventListener("resize",W)}},[u,S]),p.useEffect(()=>{var W;if(!u||d<0)return;const I=typeof document<"u"?document.getElementById(`${i}-opt-${d}`):null;(W=I==null?void 0:I.scrollIntoView)==null||W.call(I,{block:"nearest"})},[u,d,i]);const R=I=>{if(!u){["Enter"," ","ArrowDown","ArrowUp"].includes(I.key)&&(I.preventDefault(),P());return}if(I.key==="Escape"){I.preventDefault(),S();return}if(I.key==="Tab"){S();return}if(I.key==="Enter"||I.key===" "){I.preventDefault(),d>=0&&k[d]&&D(k[d]);return}const W=dT(I.key,d,k.length);W!==null&&(I.preventDefault(),h(W))};return s.jsxs("div",{ref:m,className:FS("af-workflow-picker",e.className),"data-interface":e.interfaceId??"any",children:[s.jsxs("button",{ref:_,id:e.id,type:"button",role:"combobox",className:"af-workflow-picker__trigger","aria-label":e.ariaLabel||"Workflow","aria-describedby":`${i}-value`,"aria-haspopup":"listbox","aria-expanded":u,"aria-controls":o,"aria-activedescendant":u&&d>=0?`${i}-opt-${d}`:void 0,"aria-disabled":E?void 0:!0,title:$||void 0,onClick:()=>u?S():P(),onKeyDown:R,children:[s.jsxs("span",{className:"af-workflow-picker__value",id:`${i}-value`,children:[s.jsx("span",{className:"af-workflow-picker__name",children:N.name}),N.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:N.detail}):null]}),s.jsx("span",{className:"af-workflow-picker__caret","aria-hidden":"true"})]}),u?s.jsx(pT,{id:o,idBase:i,rows:k,value:e.value,highlight:d,ariaLabel:e.ariaLabel||"Workflow",style:g,onHighlight:h,onChoose:D}):null,n.status==="error"?s.jsx("span",{className:"af-workflow-picker__error",role:"alert",children:n.error}):n.status==="ready"&&k.every(I=>!I.entry)&&!r?s.jsx("span",{className:"af-workflow-picker__empty",role:"status",children:OS}):null]})}function pT(e){const t=(o,u)=>s.jsxs("div",{id:`${e.idBase}-opt-${u}`,role:"option","aria-selected":o.value===e.value,"data-value":o.value,title:o.title,className:FS("af-workflow-picker__option",u===e.highlight&&"af-workflow-picker__option--highlighted",o.value===e.value&&"af-workflow-picker__option--selected"),onMouseEnter:()=>e.onHighlight(u),onMouseDown:l=>l.preventDefault(),onClick:()=>e.onChoose(o),children:[s.jsx("span",{className:"af-workflow-picker__name",children:o.name}),o.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:o.detail}):null]},o.key),n=e.rows.map((o,u)=>({row:o,index:u})),r=n.filter(o=>o.row.group===null),i=["shared","mine"].map(o=>({g:o,items:n.filter(u=>u.row.group===o)})).filter(o=>o.items.length>0);return s.jsxs("div",{id:e.id,role:"listbox","aria-label":e.ariaLabel,className:"af-workflow-picker__list",style:e.style,children:[r.map(o=>t(o.row,o.index)),i.map(({g:o,items:u})=>s.jsxs("div",{role:"group","aria-labelledby":`${e.idBase}-g-${o}`,"data-group":o,children:[s.jsx("div",{id:`${e.idBase}-g-${o}`,className:"af-workflow-picker__group",role:"presentation",children:PS[o]}),u.map(l=>t(l.row,l.index))]},o)),i.length===0?s.jsx("p",{className:"af-workflow-picker__empty",children:OS}):null]})}function gT(e){const t=Rw(e.target);return s.jsxs("div",{className:"af-auto__field",children:[s.jsx("span",{children:"Flow"}),s.jsx(zS,{...e.options,ariaLabel:"Automation flow",value:t,currentLabel:{name:yT(t,e.options)},onChange:(n,r)=>e.onChange(n==="@default"?{flow_id:"@default",interface:e.options.interfaceId||e.options.defaultInterface||"abstractcode.agent.v1"}:{bundle_ref:`${r.bundleId}@${r.bundleVersion}`,flow_id:r.flowId})})]})}function yT(e,t){var d,h,m;const n=((h=(d=t.workflows)==null?void 0:d.data)==null?void 0:h.entries)??[],r=n.find(_=>_.value===e);if(r)return r.name;const i=e.indexOf("@"),o=e.lastIndexOf(":"),u=i>0?e.slice(0,i):o>0?e.slice(0,o):e,l=o>0?e.slice(o+1):"";return((m=n.find(_=>_.bundleId===u&&(!l||_.flowId===l)))==null?void 0:m.name)||u||e}async function wT(e,t){var g,y;const n=e.flow_id==="@default"?(y=(g=t.workflows)==null?void 0:g.data)==null?void 0:y.gatewayDefault:null,r="bundle_ref"in e?e.bundle_ref:(n==null?void 0:n.status)==="ok"?`${n.bundleId}@${n.bundleVersion}`:"",i=e.flow_id!=="@default"?e.flow_id:(n==null?void 0:n.status)==="ok"?n.flowId:"";if(!r||!i||!t.request)throw new Error("Workflow inputs could not be checked. Refresh the workflow list and try again.");const o=r.lastIndexOf("@"),u=o<0?r:r.slice(0,o),l=o<0?"":r.slice(o+1),d=await t.request(`bundles/${encodeURIComponent(u)}/flows/${encodeURIComponent(i)}/input_schema${l?`?bundle_version=${encodeURIComponent(l)}`:""}`,{signal:new AbortController().signal}),h=(d==null?void 0:d.input_data_schema)||d;if(!h||typeof h!="object"||!h.properties)throw new Error("This workflow does not report its input requirements. Choose another workflow.");const m={...d.defaults||{}};for(const[b,k]of Object.entries(h.properties))k&&"default"in k&&(m[b]=k.default);Object.assign(m,e.input_data||{});const _=(Array.isArray(h.required)?h.required:[]).filter(b=>m[b]===void 0);if(_.length)throw new Error(`This workflow needs additional inputs: ${_.join(", ")}. Configure a new automation from that workflow's input form, or choose a compatible workflow.`);return{...e,input_data:m}}function BS(e){if(Ng(e.status))return null;const t=Nn.not_set_up,n=Nn.open_my_email,r=t.endsWith(n)?t.slice(0,t.length-n.length):`${t} `,i=e.status&&e.status.admin_disabled&&typeof e.status.admin_disabled.cause=="string"?e.status.admin_disabled.cause:"";return s.jsxs("p",{className:"af-auto__hint af-email__notice",role:"note","data-email-setup":"missing",children:[r,e.onOpenMyEmail?s.jsx("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-my-email",onClick:e.onOpenMyEmail,children:n}):n,i?s.jsxs("span",{className:"af-email__cause",children:[" (",i,")"]}):null]})}function vT(e){const t=e.value,n=l=>e.onChange({...t,...l}),r=l=>`${e.idBase}-email-${l}`,i=xm(Kv(t.usesModel)),o=t.every??(i&&i.unit==="s"?{amount:Math.max(1,Math.round(i.amount/60)),unit:"m"}:{amount:i?i.amount:1,unit:i?i.unit:"h"}),u=e.disabled===!0;return s.jsxs("div",{className:"af-email__trigger","data-field":"email-trigger",children:[s.jsxs("div",{className:"af-auto__row",children:[s.jsx("span",{children:Nn.every_label}),s.jsx("input",{type:"number",min:1,step:1,value:String(o.amount),disabled:u,"aria-label":"Check interval amount",name:"email_every_amount",onChange:l=>n({every:{amount:Number(l.target.value),unit:o.unit}})}),s.jsxs("select",{value:o.unit,disabled:u,"aria-label":"Check interval unit",name:"email_every_unit",onChange:l=>n({every:{amount:o.amount,unit:l.target.value}}),children:[s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"}),s.jsx("option",{value:"d",children:"days"})]})]}),s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:Nn.interval_rule}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("batch"),children:[s.jsx("span",{children:Nn.max_batch_label}),s.jsx("input",{id:r("batch"),name:"email_max_batch",type:"number",min:1,max:Iw,step:1,disabled:u,value:String(t.maxBatch??Gv),onChange:l=>n({maxBatch:l.target.value.trim()===""?null:Number(l.target.value)})})]}),s.jsx("p",{className:"af-auto__hint",children:Nn.max_batch_hint}),s.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:u,children:[s.jsx("legend",{children:Nn.filters_legend}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("from"),children:[s.jsx("span",{children:Nn.from_in}),s.jsx("input",{id:r("from"),name:"email_from_in",value:t.fromIn,spellCheck:!1,placeholder:"alice@example.com, billing@example.org",onChange:l=>n({fromIn:l.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("domain"),children:[s.jsx("span",{children:Nn.from_domain_in}),s.jsx("input",{id:r("domain"),name:"email_from_domain_in",value:t.fromDomainIn,spellCheck:!1,placeholder:"example.com",onChange:l=>n({fromDomainIn:l.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("to"),children:[s.jsx("span",{children:Nn.to_in}),s.jsx("input",{id:r("to"),name:"email_to_in",value:t.toIn,spellCheck:!1,onChange:l=>n({toIn:l.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("subject"),children:[s.jsx("span",{children:Nn.subject_contains}),s.jsx("input",{id:r("subject"),name:"email_subject_contains",value:t.subjectContains,maxLength:200,onChange:l=>n({subjectContains:l.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("attach"),children:[s.jsx("span",{children:Nn.has_attachment}),s.jsxs("select",{id:r("attach"),name:"email_has_attachment",value:t.hasAttachment,onChange:l=>n({hasAttachment:l.target.value}),children:[s.jsx("option",{value:"any",children:Nn.has_attachment_any}),s.jsx("option",{value:"yes",children:Nn.has_attachment_yes}),s.jsx("option",{value:"no",children:Nn.has_attachment_no})]})]}),s.jsx("p",{className:"af-auto__hint",children:Nn.list_hint})]})]})}function xT(e){const t=r=>`${e.idBase}-email-${r}`,n=e.disabled===!0;return s.jsxs("div",{className:"af-email__options","data-field":"email-options",children:[s.jsx(Di,{variant:"row",action:"notify-email",label:Nn.notify_label,checked:e.notifyEmail,unavailableReason:n?"Connect a mailbox first.":null,onChange:r=>e.onNotifyEmailChange(r)}),s.jsxs("p",{className:"af-auto__hint",children:[Nn.notify_hint," Turn on Email result to choose yourself or other email addresses."]}),e.notifyEmail?s.jsxs("fieldset",{className:"af-auto__field",disabled:n,"data-field":"email-recipients",children:[s.jsx("legend",{children:Nn.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:t("rcpt"),value:"self",checked:e.recipients.mode==="self",onChange:()=>e.onRecipientsChange({...e.recipients,mode:"self"})})," ",Nn.recipients_self]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:t("rcpt"),value:"list",checked:e.recipients.mode==="list",onChange:()=>e.onRecipientsChange({...e.recipients,mode:"list"})})," ",Nn.recipients_list]}),e.recipients.mode==="list"?s.jsx("textarea",{name:"email_recipient_list","aria-label":Nn.recipients_list,rows:2,spellCheck:!1,value:e.recipients.addresses,placeholder:"colleague@example.com",onChange:r=>e.onRecipientsChange({mode:"list",addresses:r.target.value})}):null,s.jsx("p",{className:"af-auto__hint",children:Nn.recipients_hint})]}):null]})}const bT={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function US(e){const t=String(e.status),n=bT[t];return s.jsxs("span",{className:`af-auto__status af-auto__status--${t}${e.className?` ${e.className}`:""}`,"data-state":t,children:[s.jsx("span",{className:"af-auto__status-word",children:fA[t]??t}),n?s.jsx(qe,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const $b="Discuss this run",$g=e=>s.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function kT(e){return Jv(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function jT(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return s.jsx("code",{className:"af-auto__path-text",children:t.map((n,r)=>s.jsxs(Ee.Fragment,{children:[n,r<t.length-1?s.jsx("wbr",{}):null]},r))})}function ST(e,t){const n=e.trigger,r=t.find(i=>i.id===n.source_id&&i.version===n.source_version);return r?"available"in r&&r.available===!1?`Trigger source ${n.source_id}@${n.source_version} is unavailable${r.unavailable_reason?`: ${r.unavailable_reason}`:"."}`:null:`This gateway does not list the trigger source ${n.source_id}@${n.source_version}.`}function NT(e){const t=e.summary,n=pS(t),r=ST(t,e.triggerSources),i=gS(t,e.nowMs??Date.now());return s.jsxs("header",{className:"af-auto__head",children:[s.jsxs("div",{className:"af-auto__titlebar",children:[s.jsx("h2",{className:"af-auto__title",id:e.titleId,tabIndex:-1,children:t.title}),s.jsx(US,{status:t.status}),t.legacy?s.jsx("span",{className:"af-auto__legacy",children:"Legacy schedule"}):null]}),s.jsxs("dl",{className:"af-auto__facts",children:[e.workflowLabel?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Flow"}),s.jsx("dd",{"data-fact":"workflow",children:e.workflowLabel})]}):null,s.jsx("dt",{children:"When"}),s.jsxs("dd",{"data-fact":"trigger",children:[Vv(t.trigger,t,{connections:e.triggerConnections,mailboxes:e.mailboxes}),r?s.jsxs("span",{className:"af-auto__warn",role:"note",children:[" ",r]}):null]}),s.jsx("dt",{children:"Context"}),s.jsx("dd",{"data-fact":"context",children:oS(t.context_mode)}),n?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Now"}),s.jsx("dd",{"data-fact":"current",className:"is-notable",children:n})]}):null,s.jsx("dt",{children:"Next run"}),s.jsx("dd",{"data-fact":"next",children:i}),s.jsx("dt",{children:"Runs"}),s.jsx("dd",{"data-fact":"count",children:t.occurrence_count}),t.workspace_root&&e.onOpenWorkspace?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Files"}),s.jsx("dd",{"data-fact":"workspace",className:"af-auto__workspace",children:s.jsxs("button",{type:"button",className:"af-auto__path","data-action":"open-workspace",title:`Browse the automation's folder
57
+ ${t.workspace_root}`,"aria-label":"Browse the automation's files",onClick:()=>{var o;return(o=e.onOpenWorkspace)==null?void 0:o.call(e,t.automation_id)},children:[s.jsx(qe,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx("span",{children:"Browse its files"})]})})]}):null,s.jsx("dt",{children:"Attention"}),s.jsx("dd",{"data-fact":"attention",className:t.attention.unread||t.attention.pending_waits?"is-notable":void 0,children:yS(t)})]})]})}function $T(e){var u,l;const t=e.definition,n=e.renderText??$g,r=t.target.input_data.prompt,i=t.policy.retry,o=t.policy.tool_approval;return s.jsxs("details",{className:"af-auto__definition","data-definition-revision":t.revision,open:e.open,children:[s.jsxs("summary",{children:[s.jsx(qe,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),s.jsx(qe,{name:"file",size:14}),s.jsx("span",{className:"af-auto__definition-title",children:"Details"})]}),s.jsxs("dl",{className:"af-auto__facts",children:[s.jsx("dt",{children:"Target"}),s.jsx("dd",{"data-def":"target",children:s.jsx("code",{children:t.target.workflow_id})}),typeof r=="string"&&r?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Task"}),s.jsx("dd",{"data-def":"prompt",children:n(r)})]}):null,s.jsx("dt",{children:"Trigger"}),s.jsxs("dd",{"data-def":"trigger",children:[t.trigger.source_id,"@",t.trigger.source_version," · ",Vv(t.trigger,e.served,{connections:e.triggerConnections,mailboxes:e.mailboxes}),Sg(t.trigger)?s.jsx("div",{className:"af-auto__hint","data-def":"email_rule",children:hS(t.trigger.config)}):null,s.jsx("pre",{className:"af-auto__json",children:JSON.stringify(t.trigger.config,null,2)})]}),s.jsx("dt",{children:"Context"}),s.jsxs("dd",{"data-def":"context",children:[oS(t.context.mode),t.context.mode==="growing"?` · ${Number(((u=t.context.growing)==null?void 0:u.max_tokens)??5e4).toLocaleString()} tokens`:""]}),s.jsx("dt",{children:"Tools"}),s.jsx("dd",{"data-def":"tool_approval",children:o==="ask"?"Ask before each tool call (ask)":o==="auto"?"Run without asking (auto)":String(o)}),s.jsx("dt",{children:"Notify"}),s.jsx("dd",{"data-def":"notify",children:vA(t.notify)}),(l=t.notify)!=null&&l.channels.includes("email")?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Recipients"}),s.jsx("dd",{"data-def":"email_recipients",children:wA(t.notify.recipients)})]}):null,s.jsx("dt",{children:"Retries"}),s.jsxs("dd",{"data-def":"retry",children:[i.max_attempts," ",i.max_attempts===1?"attempt":"attempts",", backoff ",i.backoff.initial," ×",i.backoff.factor," up to ",i.backoff.max]}),t.workspace_root?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Folder"}),s.jsx("dd",{"data-def":"workspace",children:s.jsx(jT,{path:t.workspace_root})})]}):null,s.jsx("dt",{children:"Revision"}),s.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const bm=qv,ga=bm.labels,Ho={active:"play",pause:"pause",resume:"play",run_now:bm.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",unarchive:"unarchive",discuss:"chat"},zw=bm.hints,CT=bm.run_now_next_run_line,ET=bm.run_now_growing_line;function Hp(e,t){const n=[zw[e]];return e==="run_now"&&t&&(t.next_run_local&&n.push(CT.replace("{time}",SS(t.next_run_local,t.time_zone))),t.context_mode==="growing"&&n.push(ET)),n.join(`
58
+ `)}function AT(e,t,n){const r=new Map;for(const u of t){const l=e[u];if(l.enabled)continue;const d=l.reason??"Not available now.";r.set(d,[...r.get(d)??[],u])}const i=[],o={};return[...r.entries()].forEach(([u,l],d)=>{const h=`${n}-why-${d}`;i.push({id:h,text:`${l.map(m=>ga[m]).join(", ")}: ${u}`});for(const m of l)o[m]=h}),{lines:i,describedBy:o}}function zr(e){return s.jsxs(s.Fragment,{children:[s.jsx(qe,{name:e.icon,size:14,className:"af-auto__btn-icon"}),s.jsx("span",{children:e.label})]})}function TT(e){const t=Xh(e.summary,e.occurrences,e.busy),n=e.summary.status==="archived",i=AT(t,["active","run_now","stop_current","revise",n?"unarchive":"archive"],e.idBase??`af-auto-${e.summary.automation_id}`),o=(u,l,d)=>{const h=Hp(u,e.summary);return s.jsx("button",{type:"button",className:`af-auto__btn${d!=null&&d.danger?" af-auto__btn--danger":""}`,"data-action":(d==null?void 0:d.action)??u,disabled:!t[u].enabled,title:t[u].enabled?h:`${t[u].reason}
59
+ ${h}`,"aria-description":h,"aria-describedby":i.describedBy[u],"aria-pressed":d==null?void 0:d.pressed,onClick:l,children:s.jsx(zr,{icon:Ho[u],label:(d==null?void 0:d.label)??ga[u]})},u)};return s.jsxs("div",{className:"af-auto__controls-wrap",children:[s.jsxs("div",{className:"af-auto__actionbar",children:[s.jsxs("div",{className:"af-auto__controls",role:"toolbar","aria-label":"Automation controls",children:[s.jsx(Di,{className:"af-auto__switch",action:"active",label:ga.active,checked:e.summary.status==="active",unavailableReason:t.active.enabled?null:t.active.reason??"Not available now.",describedBy:i.describedBy.active,busy:e.busy,hint:Hp("active",e.summary),onChange:()=>e.onCommand(jA(e.summary))},"active"),o("run_now",()=>e.onCommand(po.run_now)),o("stop_current",()=>e.onCommand(po.stop_current)),o("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),n?o("unarchive",()=>e.onCommand(po.unarchive)):o("archive",e.onAskArchive,{danger:!0,label:"Archive…"})]}),s.jsx("span",{className:`af-auto__notice${e.notice?" af-auto__notice--on":""}`,role:"status",tabIndex:-1,children:e.notice?s.jsxs(s.Fragment,{children:[s.jsx(qe,{name:"check",size:13}),s.jsx("span",{className:"af-auto__notice-text",children:e.notice}),e.onDismissNotice?s.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-notice","aria-label":"Dismiss",title:"Dismiss",onClick:e.onDismissNotice,children:s.jsx(qe,{name:"x",size:12})}):null]}):null})]}),i.lines.length?s.jsxs("p",{className:"af-auto__reasons",children:[s.jsx(qe,{name:"info",size:12,className:"af-auto__reasons-icon"}),i.lines.map(u=>s.jsx("span",{id:u.id,children:u.text},u.id))]}):null,e.summary.status==="paused"&&t.run_now.enabled?s.jsx("p",{className:"af-auto__hint",children:"Paused: scheduled runs are skipped. Run now works and keeps it paused."}):null,e.confirmingArchive&&!n?s.jsxs("div",{className:"af-auto__confirm",role:"group","aria-label":"Confirm archive",children:[s.jsxs("p",{children:["Archive “",e.summary.title,"”? Its history stays readable; it will not run again. The current run, if any, finishes."]}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"archive-confirm",disabled:!t.archive.enabled,onClick:()=>e.onCommand(po.archive),children:s.jsx(zr,{icon:"archive",label:"Archive"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:s.jsx(zr,{icon:"x",label:"Keep it"})})]})]}):null]})}const Cb=[["m","minutes"],["h","hours"],["d","days"]];function MT(e,t){const n=x=>{const N=e.elements.namedItem(x);return N&&typeof N.value=="string"?N.value:null},r=n("every_amount"),i=n("every_unit"),o=r!==null&&i!==null?`${r.trim()}${i}`:t.every,u=e.elements.namedItem("context"),l=u&&(u.value==="growing"||u.value==="independent")?u.value:t.context,d=n("prompt"),h=e.elements.namedItem("tool_approval"),m=h&&(h.value==="auto"||h.value==="ask")?h.value:t.toolApproval??null,_=e.elements.namedItem("notify_email"),g=_&&typeof _.checked=="boolean"?_.checked:t.notifyEmail??null,y=e.elements.namedItem("email_recipients"),b=n("email_recipient_list"),k=y&&(y.value==="self"||y.value==="list")?{mode:y.value,addresses:b??""}:t.emailRecipients??null;return{title:n("title")??t.title,every:o,context:l,growingMaxTokens:n("growing_max_tokens")===null?t.growingMaxTokens:Number(n("growing_max_tokens")),prompt:d??t.prompt??null,toolApproval:m,notifyEmail:g,emailRecipients:k}}function RT(e){var D;const t=wS(e.summary,e.definition),[n,r]=p.useState(),[i,o]=p.useState(t.tools??null),[u,l]=p.useState(t.context),[d,h]=p.useState(!!t.notifyEmail),[m,_]=p.useState(((D=t.calendar)==null?void 0:D.kind)??null),[g,y]=p.useState(t.calendar?Sb(t.calendar):null),b=m&&g?Xv(m,g):null,k=(()=>{if(!b)return null;const R=Yv(b);if(!R.config)return null;const I=e.summary.trigger.config.time_zone;return{source_id:e.summary.trigger.source_id,source_version:e.summary.trigger.source_version,config:{...R.config,...typeof I=="string"?{time_zone:I}:{}}}})(),x=RS(k,e.previewSchedule),N=t.every?xm(t.every):null,$=N&&N.unit==="s"?[["s","seconds"],...Cb]:Cb,E=`af-auto-revise-${e.summary.automation_id}`,S=Ng(e.emailStatus),P=Sg(e.summary.trigger);return s.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${E}-heading`,onSubmit:R=>{R.preventDefault(),e.onSubmit({...MT(R.currentTarget,t),...b?{calendar:b}:{},...n?{target:n}:{},...e.availableTools!==void 0?{tools:i}:{}})},onKeyDown:R=>{R.key==="Escape"&&e.onCancel&&(R.preventDefault(),e.onCancel())},children:[e.heading===null?s.jsx("span",{id:`${E}-heading`,hidden:!0,children:"Edit automation"}):s.jsxs("h3",{className:"af-auto__form-title",id:`${E}-heading`,children:[s.jsx(qe,{name:"edit",size:14})," ",e.heading??"Edit automation"]}),e.definition&&e.workflowPickerOptions?s.jsx(gT,{target:n||e.definition.target,options:e.workflowPickerOptions,onChange:r}):null,s.jsxs("label",{className:"af-auto__field",htmlFor:`${E}-title`,children:[s.jsx("span",{children:"Title"}),s.jsx("input",{id:`${E}-title`,name:"title",defaultValue:t.title,maxLength:120,required:!0})]}),t.prompt!==null&&t.prompt!==void 0?s.jsxs("label",{className:"af-auto__field",htmlFor:`${E}-prompt`,children:[s.jsx("span",{children:"Task"}),s.jsx("textarea",{id:`${E}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
60
+ `).length+1)),required:!0})]}):null,N?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:P?Nn.every_label:"Repeat every (UTC)"}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("input",{name:"every_amount",type:"number",min:1,step:1,defaultValue:N.amount,"aria-label":"Interval amount"}),s.jsx("select",{name:"every_unit",defaultValue:N.unit,"aria-label":"Interval unit",children:$.map(([R,I])=>s.jsx("option",{value:R,children:I},R))})]}),P?s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:Nn.interval_rule}):null]}):b?s.jsxs("fieldset",{className:"af-auto__field","data-field":"calendar",children:[s.jsx("legend",{children:us.legend}),s.jsx("div",{className:"af-auto__row",role:"radiogroup","aria-label":"Schedule kind",children:kS.map(R=>s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:`${E}-calendar-kind`,value:R,checked:b.kind===R,disabled:e.busy,onChange:()=>_(R)})," ",us[`kind_${R}`]]},R))}),s.jsx(MS,{value:b,onChange:R=>y(I=>Zv(I??Sb(R),R)),idBase:E,disabled:e.busy}),s.jsx(Dw,{state:x,whose:"automation"})]}):s.jsx("p",{className:"af-auto__hint",children:"This trigger has no interval to change."}),s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Context"}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"independent",defaultChecked:t.context==="independent",onChange:()=>l("independent")})," Independent — each run starts fresh"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing",onChange:()=>l("growing")})," Growing — each run sees the previous runs"]}),s.jsx("div",{hidden:u!=="growing",children:s.jsxs("label",{className:"af-auto__field",children:[s.jsx("span",{children:"Max growing context (tokens)"}),s.jsx("input",{name:"growing_max_tokens",type:"number",min:1,step:1,disabled:e.busy||u!=="growing",defaultValue:t.growingMaxTokens}),s.jsx("span",{className:"af-auto__hint",children:AA})]})})]}),t.toolApproval?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?s.jsx(LS,{availableTools:e.availableTools,value:i,onChange:o,disabled:e.busy}):null,s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"tool_approval",value:"auto",defaultChecked:t.toolApproval==="auto"})," Run without asking"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"tool_approval",value:"ask",defaultChecked:t.toolApproval==="ask"})," Ask before each tool call"]})]}):null,t.notifyEmail!==null&&t.notifyEmail!==void 0&&t.emailRecipients?s.jsxs("fieldset",{className:"af-auto__field","data-field":"email",children:[s.jsx("legend",{children:"Mailbox"}),S?null:s.jsx(BS,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),s.jsx(S2,{variant:"row",action:"notify-email",name:"notify_email",label:Nn.notify_label,defaultChecked:!!t.notifyEmail,onChange:h,unavailableReason:!S&&!t.notifyEmail?"Connect a mailbox first.":null}),s.jsxs("p",{className:"af-auto__hint",children:[Nn.notify_hint," Turn on Email result to choose yourself or other email addresses."]}),s.jsx("div",{hidden:!d,children:s.jsxs("fieldset",{className:"af-auto__field",disabled:!d,"data-field":"email-recipients",children:[s.jsx("legend",{children:Nn.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",Nn.recipients_self]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"list",defaultChecked:t.emailRecipients.mode==="list",disabled:!S&&t.emailRecipients.mode!=="list"})," ",Nn.recipients_list]}),s.jsx("textarea",{name:"email_recipient_list","aria-label":Nn.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!S&&t.emailRecipients.mode!=="list"}),s.jsx("p",{className:"af-auto__hint",children:Nn.recipients_hint})]})})]}):null,s.jsx("p",{className:"af-auto__hint",children:"Changes apply from the next run; runs that a new schedule would have had in the past are not made up."}),e.errors.length?s.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:e.errors.map(R=>s.jsx("li",{children:R},R))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"edit-save",disabled:e.busy,children:s.jsx(zr,{icon:"check",label:e.submitLabel??"Save changes"})}),e.onCancel?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"edit-cancel",onClick:e.onCancel,children:s.jsx(zr,{icon:"x",label:"Cancel"})}):null]})]})}function LT(e,t){const n=typeof t=="string"?t.trim():"",r=typeof e=="string"?e:"",i=r.indexOf(`
61
+ `);if(!n||i<0||!r.startsWith("["))return null;const o=r.slice(i+1);return o===n||o.startsWith(`${n}
62
+ `)?n:null}function IT(e){var n;const t=String(((n=e.trigger)==null?void 0:n.source_id)||"");return t==="schedule"?"on schedule":t==="manual"?"run by hand":t.startsWith("email")?"new mail":t?"something arrived":""}const OT="What the agent received";function Bw(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function PT(e){const t=e.wait,n=`${e.idBase}-${t.run_id}-${t.wait_key}-prompt`,r=u=>e.onAnswerWait(t.run_id,t.wait_key,u),i=e.renderText??$g,o=u=>s.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[s.jsx("span",{className:"af-auto-wait__kind",children:AS[t.kind]??"Waiting"}),t.prompt?i(t.prompt):s.jsxs("span",{children:[" ",u]})]});if(t.kind==="tool_approval"){const u=UA(t);return s.jsxs("div",{className:"af-auto-wait af-auto-wait--tool_approval",role:"group","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,children:[o("A tool call needs your approval."),u&&u.length?s.jsx("ul",{className:"af-auto-wait__calls","aria-label":"Tool calls to approve",children:u.map((l,d)=>s.jsxs("li",{"data-tool":l.name,children:[s.jsx("code",{className:"af-auto-wait__tool",children:l.name}),s.jsx("pre",{className:"af-auto-wait__args",children:JSON.stringify(l.arguments,null,2)})]},l.call_id??`${l.name}:${d}`))}):s.jsx("p",{className:"af-auto__hint",children:"The gateway did not list the tool calls; open the run to see them before approving."}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-approve",disabled:e.busy,onClick:()=>r({approved:!0}),children:s.jsx(zr,{icon:"check",label:"Approve"})}),s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"wait-deny",disabled:e.busy,onClick:()=>r({approved:!1}),children:s.jsx(zr,{icon:"x",label:"Deny"})})]})]})}return t.kind==="event"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--event","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{var d;u.preventDefault();const l=WA(Bw(u.currentTarget,"payload"));l.ok?r({payload:l.payload}):(d=e.onWaitError)==null||d.call(e,l.error)},children:[o("The run waits for an event."),s.jsx("textarea",{name:"payload",rows:3,"aria-label":"Event payload (JSON)",placeholder:'{"key": "value"}',disabled:e.busy}),s.jsx("div",{className:"af-auto__row",children:s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-send-event",disabled:e.busy,children:s.jsx(zr,{icon:"send",label:"Send event"})})})]}):t.kind==="ask_user"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--ask_user","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{u.preventDefault();const l=Bw(u.currentTarget,"response");l&&r({response:l})},children:[o("The run is waiting for your input."),t.choices&&t.choices.length?s.jsx("div",{className:"af-auto__row",role:"group","aria-label":"Choices",children:t.choices.map(u=>s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"wait-choice",disabled:e.busy,onClick:()=>r({response:u}),children:u},u))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("input",{name:"response","aria-label":"Your answer",placeholder:"Your answer",disabled:e.busy}),s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-answer",disabled:e.busy,children:s.jsx(zr,{icon:"send",label:"Answer"})})]})]}):s.jsxs("div",{className:"af-auto-wait",role:"group","data-wait-key":t.wait_key,"data-wait-kind":String(t.kind),"aria-labelledby":n,children:[o("The run is waiting."),s.jsxs("p",{className:"af-auto__hint",children:["This kind of wait (",String(t.kind),") cannot be answered here; open the run."]})]})}function DT(e){const{row:t,tone:n,badge:r,statusText:i}=e.view,o=`af-auto-occ-${t.run_id}`,u=e.renderText??$g,l=e.discuss.enabled&&e.view.canDiscuss&&!e.busy,d=e.discuss.enabled?e.view.canDiscuss?null:"Available once this run finishes.":e.discuss.reason??"Not available.",h=(x,N)=>e.renderTurn?e.renderTurn({kind:x,role:x==="trigger"?"user":"assistant",text:N,index:t.index,runId:t.run_id}):u(N),m=e.renderTurn?" af-auto-turn--card":"",_=typeof e.task=="string"?e.task.trim():"",g=LT(t.user_turn,_)!==null,y=IT(t),b=Yh(t.fired_at,{timeZone:e.timeZone,nowMs:e.nowMs,style:"day"}),k=n==="failed"?t.failure?"No answer.":"No answer: the run failed.":n==="waiting"?"Waiting for your answer.":n==="running"?"Running…":"No answer.";return s.jsxs("li",{className:`af-auto-occ af-auto-occ--${n}`,"data-index":t.index,"data-tone":n,"aria-labelledby":`${o}-h`,children:[s.jsxs("div",{className:`af-auto-turn af-auto-turn--trigger${m}`,"data-turn":"trigger",children:[s.jsxs("div",{className:"af-auto-turn__meta",id:`${o}-h`,title:`${t.trigger.summary} · fired ${Lw(t.fired_at)}`,children:[s.jsxs("span",{className:"af-auto-turn__index",children:["Run #",t.index]}),y?` · ${y}`:"",b?` · ${b}`:""]}),e.eventCard?s.jsxs("div",{className:"af-auto-event","data-event-card":"true",children:[s.jsx(qe,{name:"inbox",size:14,className:"af-auto__btn-icon"}),s.jsxs("span",{className:"af-auto-event__text",children:[s.jsx("strong",{className:"af-auto-event__source",children:e.eventCard.source}),e.eventCard.what?s.jsxs("span",{children:[" · ",e.eventCard.what]}):null,e.eventCard.at?s.jsxs("span",{className:"af-auto-turn__muted",children:[" · ",e.eventCard.at]}):null]})]}):null,(g?_:t.user_turn).trim()?s.jsx("div",{className:"af-auto-turn__text",children:h("trigger",g?_:t.user_turn)}):null,g?s.jsxs("details",{className:"af-auto-received","data-received":"true",children:[s.jsx("summary",{children:OT}),s.jsx("div",{className:"af-auto-received__body",children:u(t.user_turn)})]}):null]}),s.jsxs("div",{className:`af-auto-turn af-auto-turn--answer${m}`,"data-turn":"answer",children:[s.jsxs("div",{className:"af-auto-turn__meta",children:[r?s.jsx("span",{className:`af-auto-badge af-auto-badge--${n}`,children:r}):null,s.jsx("span",{className:"af-auto-turn__status",children:i}),t.finished_at?s.jsxs("span",{title:Lw(t.finished_at),children:[" · ",Yh(t.finished_at,{timeZone:e.timeZone,nowMs:e.nowMs,style:"day"})]}):null]}),t.notify?s.jsxs("div",{className:"af-auto-notify","data-notify":"true",children:[s.jsx("strong",{children:t.notify.title}),t.notify.body?s.jsx("div",{className:"af-auto-notify__body",children:u(t.notify.body)}):null]}):null,t.failure?s.jsxs("div",{className:"af-auto-failure","data-failure":t.failure.reason_code,children:[s.jsx("strong",{children:t.failure.reason_code}),": ",t.failure.message," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["(after ",t.failure.attempts," ",t.failure.attempts===1?"attempt":"attempts",")"]})]}):null,t.answer?s.jsx("div",{className:"af-auto-turn__text",children:h("answer",t.answer)}):s.jsx("div",{className:"af-auto-turn__empty",children:k}),t.artifacts.length?s.jsx("ul",{className:"af-auto-artifacts","aria-label":"Artifacts",children:t.artifacts.map(x=>s.jsxs("li",{children:[e.onOpenResource?s.jsxs("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-artifact",onClick:()=>{var N;return(N=e.onOpenResource)==null?void 0:N.call(e,{kind:"artifact",url:x.url,name:x.name,mimeType:x.mime_type,runId:t.run_id})},children:[s.jsx(qe,{name:"file",size:13,className:"af-auto__btn-icon"})," ",x.name]}):s.jsx("span",{className:"af-auto-artifact__name",children:x.name})," ",s.jsx("span",{className:"af-auto-turn__muted",children:x.mime_type})]},x.artifact_id))}):null,t.waits.map(x=>s.jsx(PT,{wait:x,busy:e.busy,idBase:o,onAnswerWait:e.onAnswerWait,onWaitError:e.onWaitError,renderText:e.renderText},`${x.run_id}:${x.wait_key}`))]}),s.jsxs("div",{className:"af-auto-occ__foot",children:[s.jsxs("details",{className:"af-auto-occ__details",children:[s.jsx("summary",{children:"Run details"}),s.jsxs("dl",{className:"af-auto__facts",children:[s.jsx("dt",{children:"Run"}),s.jsx("dd",{children:s.jsx("code",{children:t.run_id})}),s.jsx("dt",{children:"Attempts"}),s.jsx("dd",{children:t.attempts})]}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-run",onClick:()=>e.onOpenRun(t.run_id),children:s.jsx(zr,{icon:"list",label:"Open run ledger"})}),e.onOpenResource?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-ledger-json",onClick:()=>{var x;return(x=e.onOpenResource)==null?void 0:x.call(e,{kind:"ledger",url:t.ledger_url,name:`run-${t.run_id}-ledger.json`,runId:t.run_id})},children:s.jsx(zr,{icon:"file",label:"Ledger (JSON)"})}):null,t.workspace_url&&e.onOpenWorkspace?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-workspace",title:"Browse this run's folder",onClick:()=>{var x;return(x=e.onOpenWorkspace)==null?void 0:x.call(e,t.run_id)},children:s.jsx(zr,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?s.jsxs("form",{className:"af-auto-discuss","aria-label":`${$b}, from run ${t.index}`,onSubmit:x=>{x.preventDefault();const N=Bw(x.currentTarget,"prompt");N&&e.onDiscussSubmit(t.index,N)},children:[s.jsxs("p",{className:"af-auto__hint",children:["Starts a new conversation from run #",t.index," with the automation's whole history (runs 1–",t.index,"). It works in its own folder; the automation's files can be read but not changed (by the file tools; shell commands are not sandboxed), and nothing is written back into the automation."]}),s.jsx("textarea",{name:"prompt",rows:3,"aria-label":"Your message",placeholder:"Ask about this result…",required:!0}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"discuss-submit",disabled:e.busy,children:s.jsx(zr,{icon:"send",label:"Start discussion"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:s.jsx(zr,{icon:"x",label:"Cancel"})})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","data-action":"discuss",disabled:!l,title:zw.discuss,"aria-description":zw.discuss,"aria-describedby":d?`${o}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:s.jsx(zr,{icon:Ho.discuss,label:$b})}),d?s.jsx("span",{className:"af-auto__reasons",id:`${o}-discuss-why`,children:d}):null]})]})]})}const FT=5e3,zT={[po.pause]:"Automation paused.",[po.resume]:"Automation active.",[po.run_now]:"Run requested.",[po.stop_current]:"Stop requested.",[po.unarchive]:"Unarchived: it is paused until you make it active."};function BT(e){var Me,je;const{summary:t,busy:n}=e,r=e.renderText??$g,i=p.useId(),o=p.useRef(null),[u,l]=p.useState(!1),d=e.editOpen!==void 0,m=Xh(t,e.occurrences,!1).revise.enabled&&(d?e.editOpen===!0:u),_=p.useRef(null);m?(!_.current||_.current.summary.automation_id!==t.automation_id)&&(_.current={summary:t,definition:e.definition}):_.current=null;const g=_.current,y=p.useRef(e.onEditOpenChange);y.current=e.onEditOpenChange;const b=ae=>{var xe;d||l(ae),(xe=y.current)==null||xe.call(y,ae)},[k,x]=p.useState([]),[N,$]=p.useState(!1),[E,S]=p.useState(null),[P,D]=p.useState(null),[R,I]=p.useState(null);p.useEffect(()=>{if(!R)return;const ae=setTimeout(()=>I(null),FT);return()=>clearTimeout(ae)},[R]),p.useEffect(()=>{var xe;if(!m)return;x([]);const ae=jb(o.current,['.af-auto__revise [name="title"]']);ae==null||ae.focus(),(xe=ae==null?void 0:ae.scrollIntoView)==null||xe.call(ae,{block:"nearest"})},[m,t.automation_id]);const[W,G]=p.useState(null);p.useEffect(()=>{var ae;W&&((ae=jb(o.current,[...W,".af-auto__notice",".af-auto__title"]))==null||ae.focus(),G(null))},[W]);const K=p.useRef(null);K.current||(K.current=new qA(e.newId??VA));const H=K.current,M=ae=>D(kT(ae)),A=(ae,xe,Ae)=>{D(null),I(null),xe(H.idFor(ae)).then(He=>{H.settle(ae,{ok:!0}),Ae(He)},He=>{H.settle(ae,{ok:!1,error:He}),M(He)})},O=$A(t),L=p.useRef(e.onSeen);L.current=e.onSeen;const V=p.useRef(null);V.current||(V.current=new GA),p.useEffect(()=>{const ae=V.current,xe=O?`${t.automation_id}|${O}`:null;if(!O||!ae.next(xe,t))return;const Ae=t;L.current(O).then(()=>ae.succeeded(xe),He=>{ae.failed(xe,Ae),M(He)})});const J=Xh(t,e.occurrences,n),U=NA(e.occurrences),te=(je=(Me=e.definition)==null?void 0:Me.target.input_data)==null?void 0:je.prompt,z=ae=>e.occurrenceEvents&&ae in e.occurrenceEvents?lA(e.occurrenceEvents[ae],{trigger:t.trigger,connections:e.triggerConnections,mailboxes:e.mailboxes,timeZone:t.time_zone,nowMs:e.nowMs}):null,ne=t.occurrence_count-e.occurrences.length,se=P??e.error??null,de=se?Wp(se):null,be=t.attention;return s.jsxs("section",{ref:o,className:`af-auto${e.className?` ${e.className}`:""}`,...e.hideHeader?{"aria-label":t.title}:{"aria-labelledby":i},"aria-busy":n,"data-text-rendering":e.renderText?"rich":"unformatted",children:[e.hideHeader?null:s.jsxs(s.Fragment,{children:[s.jsx(NT,{summary:t,workflowLabel:e.workflowName,triggerSources:e.triggerSources,titleId:i,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace,triggerConnections:e.triggerConnections,mailboxes:e.mailboxes}),s.jsx(TT,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:N,reviseOpen:m,notice:R,onDismissNotice:()=>I(null),idBase:`${i}-ctl`,onCommand:ae=>A(`command:${ae}`,xe=>e.onCommand(ae,void 0,{command_id:xe}),()=>{ae===po.archive?($(!1),I("Archive requested."),G(['[data-action="archive"]'])):I(zT[ae]??"Command sent.")}),onToggleRevise:()=>{x([]),b(!m)},onAskArchive:()=>$(!0),onCancelArchive:()=>{$(!1),G(['[data-action="archive"]'])}})]}),m&&g?s.jsx(RT,{summary:g.summary,definition:g.definition,busy:n,errors:k,availableTools:e.availableTools,workflowPickerOptions:e.workflowPickerOptions,emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,previewSchedule:e.previewSchedule,onCancel:()=>{b(!1),G(['[data-action="edit"]'])},onSubmit:ae=>{const xe=g.summary,Ae=EA(xe,ae,g.definition);if(Ae===null){x(["Nothing changed."]);return}if("errors"in Ae){x(Ae.errors);return}x([]),A(`revise:${xe.revision}:${JSON.stringify(Ae)}`,async He=>{const mt=ae.target&&Ae.target?{...Ae,target:await(e.prepareTarget?e.prepareTarget(Ae.target):wT(Ae.target,e.workflowPickerOptions))}:Ae;return e.onRevise(mt,xe.revision,{command_id:He})},()=>{I("Saved; applies from the next run."),b(!1),G(['[data-action="edit"]'])})}}):e.definition?s.jsx($T,{definition:e.definition,renderText:r,served:t,triggerConnections:e.triggerConnections,mailboxes:e.mailboxes}):null,de?s.jsxs("div",{className:"af-auto__error",role:"alert","data-code":se==null?void 0:se.code,children:[s.jsx(qe,{name:"error",size:14,className:"af-auto__btn-icon"}),s.jsxs("span",{className:"af-auto__error-text",children:[s.jsx("strong",{children:de.title})," ",s.jsx("span",{children:de.detail})]}),P?s.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:()=>D(null),children:s.jsx(qe,{name:"x",size:12})}):null]}):null,be.items.length||be.waits.length?s.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:s.jsxs("ul",{children:[be.items.map(ae=>s.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${ae.kind}`,"data-cursor":ae.cursor,children:[s.jsx("span",{className:`af-auto-badge af-auto-badge--${ae.kind==="failure"?"failed":"notified"}`,children:ae.kind==="failure"?"Failed":"Notified"})," ",s.jsx("strong",{children:ae.title})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",ae.index," · ",Lw(ae.at)]}),ae.body?s.jsx("div",{className:"af-auto__attention-body",children:r(ae.body)}):null]},ae.cursor)),be.waits.map(ae=>s.jsxs("li",{className:"af-auto__attention-item af-auto__attention-item--wait",children:[s.jsx("span",{className:"af-auto-badge af-auto-badge--waiting","data-wait-kind":ae.kind,children:AS[ae.kind]??"Waiting for you"})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",ae.index]}),ae.prompt?s.jsx("div",{className:"af-auto__attention-body",children:r(ae.prompt)}):null]},`${ae.run_id}:${ae.wait_key}`))]})}):null,ne>0?s.jsx("button",{type:"button",className:"af-auto__btn af-auto__more","data-action":"load-more",disabled:n,onClick:e.onLoadMore,children:s.jsx(zr,{icon:"history",label:`Load earlier runs (${ne} more)`})}):null,U.length?s.jsx("ol",{className:"af-auto__timeline","aria-label":"Runs",children:U.map(ae=>{const xe=`[data-index="${ae.row.index}"]`;return s.jsx(DT,{view:ae,busy:n,eventCard:z(ae.row.run_id),task:typeof te=="string"?te:void 0,timeZone:t.time_zone,nowMs:e.nowMs,discuss:J.discuss,renderText:r,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?Ae=>{var He;D(null);try{Promise.resolve((He=e.onOpenResource)==null?void 0:He.call(e,Ae)).catch(M)}catch(mt){M(mt)}}:void 0,discussOpen:E===ae.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(Ae,He,mt)=>{D(null),e.onAnswerWait(Ae,He,mt).then(()=>I("Answer sent."),M)},onWaitError:Ae=>D({status:0,code:"invalid_payload",message:Ae}),onDiscussOpen:S,onDiscussCancel:()=>{S(null),G([`${xe} [data-action="discuss"]`])},onDiscussSubmit:(Ae,He)=>A(`discuss:${Ae}:${He}`,mt=>e.onDiscuss(Ae,He,{request_id:mt}),()=>{S(null),I("Discussion started in a new conversation."),G([`${xe} [data-action="discuss"]`])})},ae.row.run_id)})}):s.jsx("p",{className:"af-auto__empty",children:"No runs yet."})]})}const WS=72;function UT(e,t=WS){const n=Math.max(1,Math.floor(t)),r=new Array(n).fill(0),i=e.length;if(!i)return r;const o=i/n;let u=0;for(let l=0;l<n;l+=1){const d=Math.floor(l*o),h=Math.max(d+1,Math.floor((l+1)*o));let m=0;for(let _=d;_<h&&_<i;_+=1){const g=Math.abs(Number(e[_])||0);g>m&&(m=g)}r[l]=m,m>u&&(u=m)}return u<=0?r:r.map(l=>l/u)}function X_(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"--:--";const t=Math.floor(e),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=String(t%60).padStart(2,"0");return n>0?`${n}:${String(r).padStart(2,"0")}:${i}`:`${r}:${i}`}function WT(e,t,n){return!(t>0)||!(n>0)?0:Math.min(n,Math.max(0,e/t*n))}function qT(e,t){const[n,r]=p.useState({peaks:t??null,note:""});return p.useEffect(()=>{if(t){r({peaks:t,note:""});return}let i=!0;r({peaks:null,note:""});const o=typeof window<"u"?window.AudioContext||window.webkitAudioContext:void 0;if(!e||!o||typeof fetch!="function"){r({peaks:null,note:"Waveform unavailable in this browser."});return}return(async()=>{let u=null;try{const l=await(await fetch(e)).arrayBuffer();u=new o;const d=await u.decodeAudioData(l);i&&r({peaks:UT(d.getChannelData(0)),note:""})}catch(l){i&&r({peaks:null,note:`Waveform unavailable: ${l instanceof Error?l.message:String(l)}`})}finally{u&&u.close().catch(()=>{})}})(),()=>{i=!1}},[e,t]),n}function Cg(e){const t=p.useRef(null),n=p.useRef(null),[r,i]=p.useState(!1),[o,u]=p.useState(0),[l,d]=p.useState(null),[h,m]=p.useState(""),{peaks:_,note:g}=qT(e.src,e.peaks),y=_??new Array(WS).fill(0),b=l&&l>0?Math.min(1,o/l):0,k=e.name?`Audio ${e.name}`:"Audio",x=p.useCallback(()=>{const S=t.current;S&&(S.paused?S.play().catch(P=>m(P instanceof Error?P.message:String(P))):S.pause())},[]),N=p.useCallback(S=>{const P=t.current;!P||!Number.isFinite(S)||(P.currentTime=S,u(S))},[]),$=S=>{var D;const P=(D=n.current)==null?void 0:D.getBoundingClientRect();!P||!l||N(WT(S-P.left,P.width,l))},E=S=>{if(!l)return;const P=S.key==="ArrowRight"||S.key==="ArrowUp"?5:S.key==="ArrowLeft"||S.key==="ArrowDown"?-5:0;P?(S.preventDefault(),N(Math.min(l,Math.max(0,o+P)))):S.key==="Home"?(S.preventDefault(),N(0)):S.key==="End"?(S.preventDefault(),N(l)):(S.key===" "||S.key==="Enter")&&(S.preventDefault(),x())};return s.jsxs("div",{className:`af-audio${e.className?` ${e.className}`:""}`,"data-playing":r?"true":"false",children:[s.jsx("audio",{ref:t,src:e.src,preload:"metadata",onPlay:()=>i(!0),onPause:()=>i(!1),onEnded:()=>i(!1),onTimeUpdate:S=>u(S.currentTarget.currentTime),onLoadedMetadata:S=>d(Number.isFinite(S.currentTarget.duration)?S.currentTarget.duration:null),onDurationChange:S=>d(Number.isFinite(S.currentTarget.duration)?S.currentTarget.duration:null),onError:()=>m("This audio cannot be played in this browser. Use Download to open it.")}),s.jsx("button",{type:"button",className:"af-audio__play","data-action":r?"pause-audio":"play-audio","aria-label":r?`Pause ${k}`:`Play ${k}`,title:r?"Pause":"Play",onClick:x,children:s.jsx(qe,{name:r?"pause":"play",size:16})}),s.jsx("div",{ref:n,className:"af-audio__wave",role:"slider",tabIndex:0,"aria-label":`Seek in ${k}`,"aria-valuemin":0,"aria-valuemax":Math.round(l??0),"aria-valuenow":Math.round(o),"aria-valuetext":`${X_(o)} of ${X_(l)}`,title:g||void 0,"data-waveform":_?"decoded":"flat",onKeyDown:E,onPointerDown:S=>{var P,D;(D=(P=S.currentTarget).setPointerCapture)==null||D.call(P,S.pointerId),$(S.clientX)},onPointerMove:S=>{S.buttons&1&&$(S.clientX)},children:s.jsx("svg",{viewBox:`0 0 ${y.length*2} 32`,preserveAspectRatio:"none","aria-hidden":"true",focusable:"false",children:y.map((S,P)=>{const D=Math.max(1.5,S*30),R=(P+.5)/y.length<=b;return s.jsx("rect",{className:R?"af-audio__bar af-audio__bar--played":"af-audio__bar",x:P*2+.3,y:16-D/2,width:1.4,height:D,rx:.6},P)})})}),s.jsxs("span",{className:"af-audio__time","aria-hidden":"true",children:[X_(o)," / ",X_(l)]}),h?s.jsx("p",{className:"af-audio__error",role:"alert",children:h}):null]})}const _u=e=>new Set(e.split(/\s+/).filter(Boolean)),HT=_u("if else for while do switch case default break continue return function const let var class extends new this super import export from as async await try catch finally throw typeof instanceof in of void delete yield static public private protected interface type enum implements package struct fn impl trait pub use mod mut match loop where crate self Self func go defer chan map range select int long short char float double bool boolean string true false null nil undefined None True False namespace using template typename virtual override final abstract sealed record val object fun when is"),VT=_u("def class return if elif else for while in not and or is import from as with try except finally raise pass break continue lambda yield global nonlocal assert del async await None True False self match case"),GT=_u("if then else elif fi for while do done case esac in function return export local readonly set unset echo exit source"),KT=_u("select from where insert into values update set delete create table index view drop alter add join left right inner outer on group by order having limit offset as and or not null is in like between union all distinct primary key foreign references default"),Eb=_u("true false null yes no on off"),JT={c:{line:["//"],block:["/*","*/"],strings:['"',"'","`"],keywords:HT},python:{line:["#"],strings:['"',"'"],triple:!0,keywords:VT},shell:{line:["#"],strings:['"',"'"],keywords:GT},sql:{line:["--"],block:["/*","*/"],strings:["'",'"'],keywords:KT},data:{line:["#"],strings:['"',"'"],keywords:Eb},json:{line:[],strings:['"'],keywords:Eb},css:{line:[],block:["/*","*/"],strings:['"',"'"],keywords:_u("")},markup:{line:[],block:["<!--","-->"],strings:['"',"'"],keywords:_u("")}},YT={js:"c",mjs:"c",cjs:"c",jsx:"c",ts:"c",tsx:"c",java:"c",kt:"c",c:"c",h:"c",cc:"c",cpp:"c",hpp:"c",cs:"c",go:"c",rs:"c",swift:"c",scala:"c",dart:"c",php:"c",py:"python",pyi:"python",rb:"shell",sh:"shell",bash:"shell",zsh:"shell",fish:"shell",ps1:"shell",sql:"sql",yaml:"data",yml:"data",toml:"data",ini:"data",cfg:"data",conf:"data",env:"data",json:"json",jsonl:"json",css:"css",scss:"css",less:"css",html:"markup",htm:"markup",xml:"markup",svg:"markup",vue:"markup",javascript:"c",typescript:"c",rust:"c",python:"python",shell:"shell"};function Qv(e){const t=String(e||"").trim().toLowerCase(),n=t.split("/").pop()||t;if(n==="dockerfile"||n==="makefile")return"shell";const r=n.lastIndexOf("."),i=r>=0?n.slice(r+1):n;return YT[i]||""}const XT=e=>e>="0"&&e<="9",ZT=e=>/[A-Za-z_$]/.test(e),Ab=e=>/[A-Za-z0-9_$]/.test(e);function qS(e,t){const n=String(e??""),r=JT[t];if(!r)return n?[{kind:"plain",text:n}]:[];const i=[];let o="";const u=(d,h)=>{if(h){if(d==="plain"){o+=h;return}o&&i.push({kind:"plain",text:o}),o="",i.push({kind:d,text:h})}};let l=0;for(;l<n.length;){const d=n[l];if(r.line.find(m=>n.startsWith(m,l))){const m=n.indexOf(`
63
+ `,l),_=m===-1?n.length:m;u("comment",n.slice(l,_)),l=_;continue}if(r.block&&n.startsWith(r.block[0],l)){const m=n.indexOf(r.block[1],l+r.block[0].length),_=m===-1?n.length:m+r.block[1].length;u("comment",n.slice(l,_)),l=_;continue}if(r.strings.includes(d)){const m=r.triple&&n.startsWith(d.repeat(3),l)?d.repeat(3):"";if(m){const y=n.indexOf(m,l+3),b=y===-1?n.length:y+3;u("string",n.slice(l,b)),l=b;continue}let _=l+1;for(;_<n.length&&n[_]!==d&&(d==="`"||n[_]!==`
64
+ `);)_+=n[_]==="\\"?2:1;const g=Math.min(n.length,_+1);u("string",n.slice(l,g)),l=g;continue}if(XT(d)&&!(l>0&&Ab(n[l-1]))){let m=l+1;for(;m<n.length&&/[0-9a-fA-FxXoObB._]/.test(n[m]);)m+=1;u("number",n.slice(l,m)),l=m;continue}if(ZT(d)){let m=l+1;for(;m<n.length&&Ab(n[m]);)m+=1;const _=n.slice(l,m),g=t==="sql"?r.keywords.has(_.toLowerCase()):r.keywords.has(_);u(g?"keyword":"plain",_),l=m;continue}u("plain",d),l+=1}return o&&i.push({kind:"plain",text:o}),i}function Z_({text:e,language:t="",lineNumbers:n=!0,className:r,ariaLabel:i}){const o=Qv(t),u=qS(e,o),l=n?String(e??"").split(`
65
+ `).length:0;return s.jsx("pre",{className:`af-code${n?" af-code--numbered":""}${r?` ${r}`:""}`,"data-language":o||"text","aria-label":i,style:n?{"--af-code-gutter":`${String(l).length+1}ch`}:void 0,children:s.jsx("code",{children:n?QT(u).map((d,h)=>s.jsxs("span",{className:"af-code__line","data-line":h+1,children:[d.map((m,_)=>Tb(m,_)),`
66
+ `]},h)):u.map((d,h)=>Tb(d,h))})})}function Tb(e,t){return e.kind==="plain"?s.jsx(Ee.Fragment,{children:e.text},t):s.jsx("span",{className:`af-code__${e.kind}`,children:e.text},t)}function QT(e){const t=[[]];for(const n of e)n.text.split(`
67
+ `).forEach((i,o)=>{o>0&&t.push([]),i&&t[t.length-1].push({kind:n.kind,text:i})});return t}const HS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Lh=6e4,Ih=60*Lh,Q_=24*Ih;function km(e){if(e==null||e==="")return NaN;if(e instanceof Date)return e.getTime();if(typeof e=="number")return Number.isFinite(e)?e<1e12?e*1e3:e:NaN;const t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?km(Number(t)):Date.parse(t)}function Mb(e){return e<10?`0${e}`:String(e)}function Rb(e,t){const n=km(e);if(!Number.isFinite(n))return"";const r=new Date(n),i=r.getFullYear()===new Date(t).getFullYear();return`${HS[r.getMonth()]} ${r.getDate()}${i?"":`, ${r.getFullYear()}`}`}function ex(e){const t=km(e);if(!Number.isFinite(t))return"";const n=new Date(t);return`${HS[n.getMonth()]} ${n.getDate()}, ${n.getFullYear()}, ${Mb(n.getHours())}:${Mb(n.getMinutes())}`}function Vp(e,t){const n=km(e);if(!Number.isFinite(n)||!Number.isFinite(t))return"";const r=t-n;if(r<0){const o=-r;if(o<Lh)return"due now";if(o<Ih)return`in ${Math.round(o/Lh)} min`;if(o<Q_)return`in ${Math.round(o/Ih)} h`;const u=Math.round(o/Q_);return u<7?`in ${u} ${u===1?"day":"days"}`:Rb(n,t)}if(r<Lh)return"just now";if(r<Ih)return`${Math.floor(r/Lh)} min ago`;if(r<Q_)return`${Math.floor(r/Ih)} h ago`;const i=Math.floor(r/Q_);return i===1?"yesterday":i<7?`${i} days ago`:Rb(n,t)}const eM=new Set("png jpg jpeg gif webp bmp ico avif".split(" ")),tM=new Set("mp3 wav ogg oga opus m4a aac flac weba".split(" ")),nM=new Set("mp4 m4v webm mov ogv mkv".split(" ")),sM=new Set("mts cts".split(" ")),rM=new Set(["video/mp2t"]),iM=new Set("txt log csv tsv rst adoc org tex diff patch lock".split(" "));function oM(e){const t=String(e||"").split("/").pop()||"",n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():t.toLowerCase()}function Gp(e,t=""){const n=oM(e),r=String(t||"").split(";",1)[0].trim().toLowerCase();return n==="md"||n==="markdown"||r==="text/markdown"?"markdown":n==="json"||r==="application/json"||r.endsWith("+json")?"json":n==="pdf"||r==="application/pdf"?"pdf":eM.has(n)?"image":tM.has(n)?"audio":nM.has(n)?"video":Qv(e)||sM.has(n)?"code":iM.has(n)?"text":r.startsWith("image/")&&r!=="image/svg+xml"?"image":r.startsWith("audio/")?"audio":r.startsWith("video/")&&!rM.has(r)?"video":r.startsWith("text/")?"text":["application/javascript","application/xml","application/x-yaml","application/toml"].includes(r)?"code":"binary"}function Uw(e){return e==="markdown"||e==="code"||e==="json"||e==="text"}function Eg(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;const t=["KiB","MiB","GiB","TiB"];let n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n<10?n.toFixed(1):Math.round(n)} ${t[r]}`}function aM(e){const t=e.kind??Gp(e.name,e.contentType),n=Eg(e.sizeBytes),r=e.modified!==void 0?Vp(e.modified,e.nowMs):"";return s.jsxs("section",{className:`af-file-viewer${e.className?` ${e.className}`:""}`,"aria-label":`Preview of ${e.name}`,"data-kind":t,children:[s.jsxs("header",{className:"af-file-viewer__head",children:[s.jsx(qe,{name:"file",size:15}),s.jsxs("span",{className:"af-file-viewer__title",children:[s.jsx("strong",{className:"af-file-viewer__name",title:e.path||e.name,children:e.name}),n||r?s.jsxs("span",{className:"af-file-viewer__meta",children:[n?s.jsx("span",{"data-meta":"size",children:n}):null,n&&r?s.jsx("span",{"aria-hidden":"true",children:" · "}):null,r?s.jsx("time",{"data-meta":"modified",title:ex(e.modified),dateTime:new Date(km(e.modified)).toISOString(),children:r}):null]}):null]}),e.actions,e.onDownload?s.jsx("button",{type:"button",className:"af-file-viewer__icon-btn","data-action":"download-file",onClick:e.onDownload,title:"Download","aria-label":`Download ${e.name}`,children:s.jsx(qe,{name:"download",size:15})}):null,e.onClose?s.jsx("button",{type:"button",className:"af-file-viewer__icon-btn","data-action":"close-preview",onClick:e.onClose,title:"Close","aria-label":"Close the preview",children:s.jsx(qe,{name:"x",size:15})}):null]}),s.jsx("div",{className:"af-file-viewer__body",children:e.status==="loading"?s.jsx("p",{className:"af-file-viewer__muted",role:"status",children:"Loading preview…"}):e.status==="error"?s.jsx("p",{className:"af-file-viewer__error",role:"alert",children:e.error||"The preview could not be loaded."}):s.jsxs(s.Fragment,{children:[e.partialNote?s.jsx("p",{className:"af-file-viewer__muted",role:"status",children:e.partialNote}):null,s.jsx(lM,{kind:t,p:e})]})})]})}function lM({kind:e,p:t}){const n=t.text??"";switch(e){case"image":return t.url?s.jsx("img",{className:"af-file-viewer__image",src:t.url,alt:t.name}):s.jsx(gh,{});case"audio":return t.url?s.jsx(Cg,{src:t.url,name:t.name}):s.jsx(gh,{});case"video":return t.url?s.jsx("video",{className:"af-file-viewer__image af-file-viewer__video",src:t.url,controls:!0,playsInline:!0,preload:"metadata","aria-label":t.name}):s.jsx(gh,{});case"pdf":return t.url?s.jsx("object",{className:"af-file-viewer__pdf",data:t.url,type:"application/pdf","aria-label":t.name,children:s.jsx("p",{className:"af-file-viewer__muted",children:"This browser cannot show PDFs inline. Use Download to open it."})}):s.jsx(gh,{});case"markdown":return t.renderMarkdown?s.jsx("div",{className:"af-file-viewer__markdown",children:t.renderMarkdown(n)}):s.jsx(Z_,{text:n,language:""});case"json":{let r=n,i="";try{r=JSON.stringify(JSON.parse(n),null,2)}catch{i=t.partialNote?"":"Not valid JSON; shown as text."}return s.jsxs(s.Fragment,{children:[i?s.jsx("p",{className:"af-file-viewer__muted",children:i}):null,s.jsx(Z_,{text:r,language:"json"})]})}case"code":return s.jsx(Z_,{text:n,language:t.name});case"text":return s.jsx(Z_,{text:n,language:"",lineNumbers:!1});default:return s.jsx(gh,{})}}function gh(){return s.jsx("p",{className:"af-file-viewer__muted",children:"No preview for this file type. Use Download to open it."})}function Oh(e){const t=p.useId(),n=`${e.id||t}-title`;return s.jsxs("section",{className:`af-settings-group${e.variant==="flat"?" af-settings-group--flat":""}${e.className?` ${e.className}`:""}`,"aria-labelledby":n,id:e.id,children:[s.jsxs("div",{className:"af-settings-group__head",children:[s.jsx("h3",{className:"af-settings-group__title",id:n,children:e.title}),e.aside?s.jsx("span",{className:"af-settings-group__aside",children:e.aside}):null]}),e.help?s.jsx("p",{className:"af-settings-group__help",children:e.help}):null,s.jsx("div",{className:"af-settings-group__rows",children:e.children})]})}function ic(e){const t=e.htmlFor?"label":"span";return s.jsxs("div",{className:`af-setting-row${e.stack?" af-setting-row--stack":""}${e.className?` ${e.className}`:""}`,"data-setting":e.setting,children:[s.jsxs("div",{className:"af-setting-row__label",children:[s.jsx(t,{className:"af-setting-row__name",...e.htmlFor?{htmlFor:e.htmlFor}:{},children:e.label}),e.help?s.jsx("span",{className:"af-setting-row__help",children:e.help}):null]}),e.children!==void 0||e.trailing?s.jsxs("div",{className:"af-setting-row__control",children:[e.children,e.trailing?s.jsx("span",{className:"af-setting-row__trailing",children:e.trailing}):null]}):null]})}function Lb(e){const t=!!e.overrideSummary,n=p.useId(),r=t?`${e.overrideSummary}${e.overrideOwner?` — ${e.overrideOwner}`:""}`:`Gateway default${e.defaultSummary?` · ${e.defaultSummary}`:""}`;return s.jsxs("div",{className:"af-override","data-setting":e.setting,"data-overridden":t?"true":"false",children:[s.jsx(ic,{label:e.label,help:e.help,trailing:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"change","aria-expanded":e.open,"aria-controls":n,disabled:e.disabled,onClick:e.onToggle,children:e.open?"Done":"Change"}),t&&e.onReset?s.jsx("button",{type:"button",className:"af-setting-btn af-setting-btn--quiet","data-action":"use-default",disabled:e.disabled,onClick:e.onReset,children:"Use gateway default"}):null]}),children:s.jsx("span",{className:"af-override__summary",title:r,children:r})}),s.jsx("div",{className:"af-override__editor",id:n,hidden:!e.open,children:e.open?e.children:null})]})}const Wn={title:"Workspaces",gatewayTitle:"Eligible workspaces",gatewayHelp:"The workspaces accounts may choose from, and the most each one allows.",accountHelp:"The workspaces this account's agents use, among the eligible ones.",sessionHelp:"The workspaces this conversation uses, among the eligible ones.",runHelp:"The workspaces this run uses, among the eligible ones.",gatewayPrefix:"Gateway:",postureLabel:"Workspaces agents may use",postureAllowedOnly:"Deny everything, allow listed workspaces",postureAllowedOnlyHelp:"Agents may only work in the listed workspaces.",postureAnyExceptDenied:"Allow everything, refuse listed workspaces",postureAnyExceptDeniedHelp:"Agents may work in any workspace except the refused ones.",accessLabel:"Permission",accessRead:"Read-only",accessReadWrite:"Read & write",accessDenied:"Refused",capReadOnly:"The gateway allows this workspace read-only",capRefused:"The gateway refuses this workspace",everythingElse:"Everything else",allowedTitle:"Allowed workspaces",deniedTitle:"Refused workspaces",builtinRefused:"Always refused: the gateway's own data and credentials",emptyAllowed:"No workspace is listed: agents only use their private workspace.",privateNote:"The private workspace of each run is always available, read & write.",addPlaceholder:"Add a workspace path",add:"Add",choose:"Choose…",remove:"Remove",followGateway:"Follow the gateway policy",followGatewayHelp:"On: this account gets exactly what the gateway allows.",useDefault:"Use my default",useDefaultHelp:"On: the account's default workspaces apply.",locked:"These workspaces can be seen here but not changed.",loading:"Loading…",saved:"Saved",notSaved:"Not saved."},ei=Wn;function cM(e){return e==="any_except_denied"?ei.postureAnyExceptDenied:ei.postureAllowedOnly}function uM(e){return e==="any_except_denied"?ei.postureAnyExceptDeniedHelp:ei.postureAllowedOnlyHelp}function Ib(e){return e==="ro"?ei.accessRead:e==="deny"?ei.accessDenied:ei.accessReadWrite}function dM(e){return e==="gateway"?ei.gatewayHelp:e==="account"?ei.accountHelp:e==="session"?ei.sessionHelp:ei.runHelp}const Ob={deny:0,ro:1,rw:2},jy=["rw","ro","deny"];function fM(e){if(e===null)return{allowed:[...jy],reasons:{}};const t=e==="deny"?ei.capRefused:ei.capReadOnly,n=jy.filter(i=>Ob[i]<=Ob[e]),r={};for(const i of jy)n.includes(i)||(r[i]=t);return{allowed:n,reasons:r}}function hM(e,t){const{policy:n}=t,r=t.effective;if(e==="gateway"?typeof n.summary!="string":!r)throw new Error(e==="gateway"?"The gateway workspace policy has no summary line.":`A ${e}-level workspace chooser needs the gateway's effective workspaces.`);const i=e!=="gateway"&&n.configured===!1,o=t.can_edit===!1,u=new Map(((r==null?void 0:r.folders)??[]).map(y=>[y.path,y.cap])),l=r,d=i?l.folders.map(y=>({path:y.path,mode:y.mode})):n.folders,h=i?l.posture:n.posture,m=i?l.default_mode??n.default_mode:n.default_mode,_=!i&&!o,g=d.map(y=>{const b=e==="gateway"?null:u.get(y.path)??null,{allowed:k,reasons:x}=fM(b);return{path:y.path,mode:y.mode,cap:b,allowed:k,reasons:x,builtin:!1,editable:_}});if(e==="gateway")for(const y of n.builtin_refused??[])g.push({path:y,mode:"deny",cap:null,allowed:[],reasons:{},builtin:!0,editable:!1});return{level:e,posture:h,following:i,rows:g,everythingElse:h==="any_except_denied"?{mode:m,editable:_}:null,canAdd:_,gatewayLine:e==="gateway"?null:`${ei.gatewayPrefix} ${l.gateway_summary}`,summary:e==="gateway"?n.summary:l.summary,locked:o}}function mM(e,t){return t==="any_except_denied"?"deny":e==="gateway"?"rw":"ro"}function jm(e,t){const n={posture:t.posture,default_mode:t.default_mode,folders:t.folders.map(r=>({path:r.path,mode:r.mode}))};return e==="gateway"?n:{configured:!0,...n}}function _M(e,t,n,r){return jm(e,{...t,folders:t.folders.map(i=>i.path===n?{path:n,mode:r}:i)})}function pM(e,t,n){return jm(e,{...t,posture:n})}function gM(e,t,n){return jm(e,{...t,default_mode:n})}function yM(e,t,n,r){const i=String(n).trim();return jm(e,{...t,folders:[...t.folders,{path:i,mode:mM(e,t.posture)}]})}function wM(e,t,n){return jm(e,{...t,folders:t.folders.filter(r=>r.path!==n)})}function vM(e,t){if(t)return{configured:!1};const n=e.effective;if(!n)throw new Error("The follow switch needs the gateway's effective workspaces.");return{configured:!0,posture:n.posture,default_mode:n.default_mode??e.policy.default_mode,folders:n.folders.map(r=>({path:r.path,mode:r.mode}))}}function xM(e){let t=String(e||"");for(;t.endsWith("/");)t=t.slice(0,-1);return t}function bM(e="me",t=Jh){return`${xM(t)}/workspace/effective/${encodeURIComponent(e)}`}const Pb=e=>e==="ro"||e==="rw"||e==="deny",kM=e=>e==="ro"||e==="rw",jM=e=>e==="allowed_only"||e==="any_except_denied",Db="The gateway answered with an older workspace model (it needs the round-11 workspace API).";function SM(e){const t=e&&typeof e=="object"?e:{};if("shared_workspace"in t)throw new Error(Db);if(!(jM(t.posture)&&(kM(t.default_mode)||t.default_mode===null&&t.posture==="allowed_only")&&typeof t.summary=="string"&&typeof t.gateway_summary=="string"&&Array.isArray(t.folders)&&t.folders.every(r=>r&&typeof r.path=="string"&&Pb(r.mode)&&Pb(r.cap))))throw new Error(`The gateway answered without the effective workspaces (posture, default_mode, folders with cap, summary, gateway_summary). ${Db}`);return{posture:t.posture,default_mode:t.default_mode,folders:t.folders.map(r=>({path:r.path,mode:r.mode,cap:r.cap,source:r.source})),summary:t.summary,gateway_summary:t.gateway_summary}}function Qh(e,t="me",n=Jh){const r=bM(t,n);return async(i,o)=>SM(await e(r,{method:"POST",body:o?{workspace:i,session:o}:{workspace:i}}))}function Ag(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;const t=e&&typeof e=="object"?e:{},n=t.detail;return n&&typeof n=="object"&&typeof n.message=="string"?n.message:typeof n=="string"?n:typeof t.message=="string"?t.message:""}function Fb(e){const t=Ag(e).trim()||"The gateway refused the change.";return`${t}${/[.!?]$/.test(t)?"":"."} ${ei.notSaved}`}const NM=e=>!!e&&typeof e=="object"&&"policy"in e&&"effective"in e;function $M(e,t){return t?{policy:e?{configured:!0,posture:e.posture,default_mode:e.default_mode,folders:e.folders.map(n=>({...n}))}:{configured:!1,posture:t.posture,default_mode:t.default_mode??"rw",folders:[]},effective:t}:null}function VS(e){tf();const t=e.idPrefix||"af-workspace",[n,r]=p.useState(null),[i,o]=p.useState({}),[u,l]=p.useState(null),[d,h]=p.useState(""),[m,_]=p.useState(null),g=String(e.unavailableReason||"").trim(),y=e.level,b=e.level==="run"?$M(e.value,e.effective):e.state,k=e.level==="run"?e.effective:e.state,x=m&&m.base===k?m.value:b,N=x?hM(y,x):null,$=O=>{if(e.level==="run"){const L=e,V=O.configured===!1?null:{posture:O.posture,default_mode:O.default_mode,folders:O.folders};return Promise.resolve(L.onChange(V))}return e.save(O)};async function E(O,L){if(n!==null||g)return!1;r(O),l(null),o(V=>{const J={...V};return delete J[O],J});try{const V=await $(L);return NM(V)&&_({base:k,value:V}),l(O),!0}catch(V){return o(J=>({...J,[O]:Fb(V)})),!1}finally{r(null)}}const S=O=>i[O]?s.jsx("span",{className:"af-workspace__refusal",role:"alert","data-workspace":"refusal",children:i[O]}):u===O?s.jsx("span",{className:"af-workspace__saved",role:"status","data-workspace":"saved",children:Wn.saved}):null,P=(O,L)=>s.jsx("span",{className:"af-workspace__access-tag","data-workspace":"access","data-access":O,"data-af-tip":L,tabIndex:L?0:void 0,children:Ib(O)}),D=(O,L,V,J,U)=>s.jsx("span",{className:"af-workspace__access",role:"group","aria-label":O,"data-workspace":U,"data-access":L,children:V.map(te=>{const z=!!te.reason||!!g;return s.jsx("button",{type:"button",className:"af-workspace__access-btn","aria-pressed":L===te.value?"true":"false","aria-disabled":z?"true":void 0,"data-af-tip":te.reason||void 0,"data-action":`${U}-${te.value}`,onClick:()=>z||n!==null||te.value===L?void 0:J(te.value),children:te.text},te.value)})}),R=O=>{if(O.builtin)return P("deny",Wn.builtinRefused);if(!O.editable||!x)return P(O.mode);const L=x.policy;return s.jsxs(s.Fragment,{children:[D(`${Wn.accessLabel} ${O.path}`,O.mode,["rw","ro","deny"].map(V=>({value:V,text:Ib(V),reason:O.reasons[V]})),V=>void E(O.path,_M(y,L,O.path,V)),"workspace-mode"),s.jsx("button",{type:"button",className:"af-workspace__icon-btn","data-action":"workspace-remove","aria-label":`${Wn.remove} ${O.path}`,"data-af-tip":`${Wn.remove} ${O.path}`,"aria-disabled":g||n!==null?"true":void 0,onClick:()=>g||n!==null?void 0:void E(O.path,wM(y,L,O.path)),children:s.jsx(qe,{name:"x",size:16})})]})};async function I(O){if(!x||!N||!N.canAdd)return;const L=O.trim();L&&await E("add",yM(y,x.policy,L))&&h("")}async function W(){if(!e.choose||n!==null||g)return;let O;try{O=await e.choose()}catch(L){o(V=>({...V,add:Fb(L)}));return}O&&await I(O)}const G=N?N.rows.filter(O=>O.mode!=="deny"):[],K=N?N.rows.filter(O=>O.mode==="deny"):[],H=O=>s.jsxs("li",{className:"af-workspace__row","data-workspace":O.builtin?"builtin":"row","data-path":O.path,"data-mode":O.mode,"data-cap":O.cap??void 0,children:[s.jsx("code",{className:"af-workspace__path",children:O.path}),s.jsx("span",{className:"af-workspace__controls",children:R(O)}),S(O.path)]},`${O.builtin?"builtin:":""}${O.path}`),M=y==="account"?Wn.followGateway:Wn.useDefault,A=y==="account"?Wn.followGatewayHelp:Wn.useDefaultHelp;return s.jsx(Oh,{id:t,className:`af-workspace af-workspace--${y}${e.className?` ${e.className}`:""}`,title:y==="gateway"?Wn.gatewayTitle:Wn.title,help:dM(y),children:e.loadError?s.jsx("p",{className:"af-workspace__refusal",role:"alert","data-workspace":"load-error",children:e.loadError}):!N||!x?s.jsx("p",{className:"af-workspace__note","data-workspace":"loading",children:Wn.loading}):s.jsxs("div",{className:"af-workspace__body","data-level":y,"data-following":N.following?"true":"false",children:[N.gatewayLine?s.jsx("p",{className:"af-workspace__gateway","data-workspace":"gateway-line",children:N.gatewayLine}):null,g?s.jsx("p",{className:"af-workspace__note",id:`${t}-blocked`,"data-workspace":"blocked",children:g}):null,y!=="gateway"?s.jsxs("div",{className:"af-workspace__follow","data-workspace":"follow",children:[s.jsx(Di,{variant:"row",label:M,description:A,checked:N.following,busy:n==="follow",unavailableReason:g||(N.locked?Wn.locked:null),reasonVisible:!1,describedBy:g?`${t}-blocked`:void 0,action:y==="account"?"workspace-follow-gateway":"workspace-use-default",onChange:O=>void E("follow",vM(x,O))}),S("follow")]}):null,s.jsxs("div",{className:"af-workspace__posture","data-workspace":"posture","data-posture":N.posture,children:[N.following||N.locked?s.jsx("span",{className:"af-workspace__badge",children:cM(N.posture)}):D(Wn.postureLabel,N.posture,[{value:"allowed_only",text:Wn.postureAllowedOnly},{value:"any_except_denied",text:Wn.postureAnyExceptDenied}],O=>void E("posture",pM(y,x.policy,O)),"workspace-posture"),s.jsx("span",{className:"af-workspace__note","data-workspace":"posture-help",children:uM(N.posture)}),S("posture")]}),s.jsxs("ul",{className:"af-workspace__list","aria-label":Wn.title,"data-workspace":"list",children:[G.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-allowed",children:Wn.allowedTitle}):null,G.map(H),K.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-refused",children:Wn.deniedTitle}):null,K.map(H),N.everythingElse?s.jsxs("li",{className:"af-workspace__row","data-workspace":"everything-else","data-mode":N.everythingElse.mode,children:[s.jsx("span",{className:"af-workspace__name",children:Wn.everythingElse}),s.jsx("span",{className:"af-workspace__controls",children:N.everythingElse.editable?D(`${Wn.accessLabel} ${Wn.everythingElse}`,N.everythingElse.mode,[{value:"rw",text:Wn.accessReadWrite},{value:"ro",text:Wn.accessRead}],O=>void E("everything-else",gM(y,x.policy,O)),"workspace-default"):P(N.everythingElse.mode)}),S("everything-else")]}):null,N.canAdd?s.jsxs("li",{className:"af-workspace__add","data-workspace":"add",children:[s.jsx("input",{type:"text",className:"af-workspace__input","aria-label":Wn.addPlaceholder,placeholder:Wn.addPlaceholder,value:d,disabled:!!g||n==="add",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:O=>h(O.target.value),onKeyDown:O=>{O.key==="Enter"?(O.preventDefault(),I(d)):O.key==="Escape"&&(O.preventDefault(),h(""),o(L=>{const V={...L};return delete V.add,V}))}}),s.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-add",disabled:!!g||!d.trim()||n!==null,onClick:()=>void I(d),children:Wn.add}),e.choose?s.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-choose",disabled:!!g||n!==null,onClick:()=>void W(),children:Wn.choose}):null,S("add")]}):null]}),N.posture==="allowed_only"&&!G.length?s.jsx("p",{className:"af-workspace__note","data-workspace":"empty",children:Wn.emptyAllowed}):null,y==="session"||y==="run"?s.jsx("p",{className:"af-workspace__note","data-workspace":"private",children:Wn.privateNote}):null,s.jsx("p",{className:"af-workspace__effective","data-workspace":"effective",children:N.summary}),e.footer?s.jsx("div",{className:"af-workspace__footer",children:e.footer}):null]})})}const Sy=e=>`${Math.round(e*100)} %`,CM="Safari does not let a page choose the output device: replies play on the system output (change it in the system sound settings).";function EM(e){var D,R,I;const t=!!e.unavailableReason,n=e.outputSelectable??Zj(),r=p.useId(),[i,o]=p.useState({devices:[],labelled:!0}),[u,l]=p.useState({text:"",tone:"info"}),d=p.useRef(!0);p.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const h=e.value,m=W=>e.onChange({...h,...W}),_=Hd(h.reply_volume),g=h.reply_muted===!0,y=e.showMute!==!1||g,b=e.listDevices||Hj,k=p.useRef(b);k.current=b;const x=()=>{n&&k.current("audiooutput").then(W=>d.current&&o(W)).catch(()=>d.current&&o({devices:[],labelled:!1}))};p.useEffect(()=>{t||x()},[n,t,e.devicesKey]);const N=()=>{l({text:"Playing a short chime…",tone:"info"}),kE({deviceId:n&&h.output_device||"",volume:_}).then(()=>{if(!d.current)return;const W="Chime played. Heard nothing? Pick another output or raise the volume.";l({text:g?`${W} Replies are muted: unmute them to hear them.`:W,tone:"ok"})}).catch(W=>d.current&&l({text:`The speaker test failed: ${String((W==null?void 0:W.message)||W).replace(/\.$/,"")}.`,tone:"error"}))},$=h.output_device||"",E=[{value:"",label:"System default"},...i.devices.map(W=>({value:W.id,label:W.label})),...$&&!i.devices.some(W=>W.id===$)?[{value:$,label:"Saved speaker (not connected)"}]:[]],S=((D=e.labels)==null?void 0:D.device)||"Output device",P=((R=e.labels)==null?void 0:R.volume)||"Reply volume";return s.jsxs("div",{className:`af-voice-output${e.className?` ${e.className}`:""}`,"data-voice-output":!0,children:[s.jsx(ic,{label:S,setting:"output-device",help:n?void 0:CM,trailing:s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-speaker",disabled:t,onClick:N,children:((I=e.labels)==null?void 0:I.test)||"Test"}),children:s.jsx(Br,{ariaLabel:S,placeholder:"System default",value:n?$:"",options:E,disabled:t||!n,searchable:!1,onOpen:x,onChange:W=>m({output_device:W})})}),u.text?s.jsx("p",{className:`af-voice-note af-voice-note--${u.tone}`,role:"status","data-voice-note":"speaker",children:u.text}):null,s.jsxs(ic,{label:P,setting:"reply-volume",htmlFor:r,trailing:y?s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"mute-replies",disabled:t,onClick:()=>m({reply_muted:!g}),children:g?"Unmute":"Mute"}):void 0,children:[s.jsx("input",{id:r,className:"af-voice-range",type:"range",min:0,max:100,step:5,value:Math.round(_*100),disabled:t,"aria-valuetext":g?`Muted (${Sy(_)})`:Sy(_),onChange:W=>m({reply_volume:Number(W.currentTarget.value)/100})}),s.jsx("span",{className:"af-voice-range__value","data-voice-volume":g?"muted":"on",children:g?"Muted":Sy(_)})]})]})}function AM(e){const[t,n]=p.useState(0),r=e==null?void 0:e.subscribe_level;return p.useEffect(()=>{if(!r){n(0);return}return r(i=>n(Math.min(1,Math.max(0,Number(i)||0))))},[r]),t}function TM(e){const t=AM(e.level===void 0?e.source:null),n=Math.min(1,Math.max(0,e.level===void 0?t:Number(e.level)||0)),r=e.inline?"span":"div";return s.jsx(r,{className:`af-voice-meter${e.className?` ${e.className}`:""}`,"data-voice-meter":!0,"data-voice-meter-source":e.origin||"live",role:"meter","aria-label":e.label||"Microphone level","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(n*100),children:s.jsx("span",{className:"af-voice-meter__fill",style:{width:`${Math.round(n*100)}%`}})})}const Ny=e=>`${Math.round(e*100)} %`;function GS(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)||t<=0?1:Math.min(1.5,Math.max(.5,t))}function MM(e){var K,H,M;const t=!!e.unavailableReason,n=p.useId(),[r,i]=p.useState({devices:[],labelled:!0}),[o,u]=p.useState(""),[l,d]=p.useState({phase:"idle",message:"",tone:"info"}),[h,m]=p.useState(0),_=p.useRef(!0);p.useEffect(()=>(_.current=!0,()=>{_.current=!1}),[]);const g=Gj(),y=e.value,b=A=>e.onChange({...y,...A}),k=GS(y.input_gain),x=e.listDevices||Hj,N=p.useRef(x);N.current=x;const $=()=>{N.current("audioinput").then(A=>_.current&&i(A)).catch(()=>_.current&&i({devices:[],labelled:!1}))};p.useEffect(()=>{t||$()},[t]);const E=()=>{u(""),bE().then(()=>{var A;$(),(A=e.onDevicesChanged)==null||A.call(e)}).catch(A=>_.current&&u(Up(A)))},S=()=>{d({phase:"recording",message:"Recording 3 seconds — say something.",tone:"info"}),Yj({deviceId:y.input_device||"",ms:3e3,gain:k,onLevel:A=>_.current&&m(A)}).then(async({blob:A,peak:O})=>{var L,V,J;if(_.current){if(O<Jj){d({phase:"idle",message:"The microphone recorded silence. Pick another input, or raise its level in the system sound settings.",tone:"error"});return}d({phase:"playing",message:"Playing it back…",tone:"info"}),await Xj(A,{deviceId:((L=e.playOn)==null?void 0:L.deviceId)||"",volume:(V=e.playOn)==null?void 0:V.volume}),_.current&&(d({phase:"idle",message:`The microphone works (peak level ${Ny(O)}).`,tone:"ok"}),$(),(J=e.onDevicesChanged)==null||J.call(e))}}).catch(A=>_.current&&d({phase:"idle",message:Up(A),tone:"error"}))},P=y.input_device||"",D=[{value:"",label:"System default"},...r.devices.map(A=>({value:A.id,label:A.label})),...P&&!r.devices.some(A=>A.id===P)?[{value:P,label:"Saved microphone (not connected)"}]:[]],R=l.phase!=="idle",I=l.phase==="recording",W=((K=e.labels)==null?void 0:K.device)||"Input device",G=((H=e.labels)==null?void 0:H.gain)||"Input level";return s.jsxs("div",{className:`af-voice-input${e.className?` ${e.className}`:""}`,"data-voice-input":!0,children:[s.jsx(ic,{label:W,setting:"input-device",trailing:s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-microphone",disabled:t||R,onClick:S,children:l.phase==="recording"?"Recording…":l.phase==="playing"?"Playing…":((M=e.labels)==null?void 0:M.test)||"Test"}),children:s.jsx(Br,{ariaLabel:W,placeholder:"System default",value:P,options:D,disabled:t,searchable:!1,onOpen:$,onChange:A=>b({input_device:A})})}),s.jsx(TM,{source:I?null:e.levelSource,level:I?h:e.level,origin:I?"test":"live"}),l.message?s.jsx("p",{className:`af-voice-note af-voice-note--${l.tone}`,role:"status","data-voice-note":"microphone",children:l.message}):null,!r.labelled&&!t?s.jsxs("p",{className:"af-voice-note","data-voice-note":"labels",children:["Device names appear once the microphone is allowed."," ",s.jsx("button",{type:"button",className:"af-setting-btn af-setting-btn--quiet","data-action":"show-device-names",onClick:E,children:"Show names"})]}):null,o?s.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status",children:o}):null,g?s.jsxs(ic,{label:G,setting:"input-gain",htmlFor:n,help:"Raises a quiet microphone.",children:[s.jsx("input",{id:n,className:"af-voice-range",type:"range",min:50,max:150,step:10,value:Math.round(k*100),disabled:t,"aria-valuetext":Ny(k),onChange:A=>b({input_gain:Number(A.currentTarget.value)/100})}),s.jsx("span",{className:"af-voice-range__value",children:Ny(k)})]}):null]})}const RM=["provider","model","voice","profile","speed","quality_preset","instructions"];function LM(e){const t={};for(const n of RM){const r=e[n];r!==void 0&&r!==""&&r!==null&&(t[n]=r)}return t}function IM(e){return{...e.stt_provider?{provider:e.stt_provider}:{},...e.stt_provider&&e.stt_model?{model:e.stt_model}:{},...e.stt_language?{language:e.stt_language}:{}}}const OM=[{value:"",label:"Detect automatically"},...Object.keys(eS).map(e=>({value:e,label:mu(e)}))],PM=[{value:"hold",label:"Hold to talk"},{value:"toggle",label:"Tap to talk"}];function DM(e){return[e.provider,e.model,e.profile||e.voice].filter(Boolean).join(" · ")}function FM(e){return[e.stt_provider,e.stt_model].filter(Boolean).join(" · ")}const zM=[{value:"",label:"Gateway default"},{value:"standard",label:"Balanced"},{value:"low",label:"Faster (lower quality)"},{value:"high",label:"Higher quality (slower)"}],zb=e=>Array.isArray(e)?e.map(t=>typeof t=="string"?t:(t==null?void 0:t.id)||(t==null?void 0:t.name)).filter(Boolean):[];function BM(e){var be,Me,je,ae,xe,Ae,He,mt,nt,rt;const t=e.overrideOwner||"this app",n=!!e.unavailableReason,r=e.rows||{},i=p.useRef(e.fetchCatalog);i.current=e.fetchCatalog;const o=p.useRef(e.fetchDefaults);o.current=e.fetchDefaults;const u=p.useRef(e.fetchLanguages);u.current=e.fetchLanguages;const[l,d]=p.useState({}),[h,m]=p.useState({value:null,failed:!1}),_=e.defaults!==void 0?{value:e.defaults,failed:!1}:h,g=e.defaults!==void 0,[y,b]=p.useState(""),[k,x]=p.useState(0),[N,$]=p.useState(null),E=e.outputSelectable??Zj(),S=e.value,P=e.nested?"flat":"card",D=ze=>e.onChange({...S,...ze}),R=Hd(S.reply_volume),I=GS(S.input_gain),W=r.tts!==!1&&!e.ttsSlot,G=r.stt!==!1,K=W||G||!!e.ttsSlot,H=e.voiceLibrary||e.createVoice;p.useEffect(()=>{if(n)return;let ze=!0;return i.current().then(Ve=>ze&&d(Ve||{})).catch(()=>ze&&d({})),g||o.current().then(Ve=>ze&&m({value:Ve||{},failed:!1})).catch(()=>ze&&m({value:null,failed:!0})),()=>{ze=!1}},[n,g]);const M=S.stt_provider||((Me=(be=_.value)==null?void 0:be.stt)!=null&&Me.configured?String(_.value.stt.provider||""):""),A=!!e.fetchLanguages;p.useEffect(()=>{const ze=u.current;if(n||!ze||r.microphone===!1)return;let Ve=!0;return ze("stt",M||void 0).then(ct=>Ve&&$(Array.isArray(ct)?ct.map(Qe=>String(Qe).toLowerCase()).filter(Boolean):[])).catch(()=>Ve&&$(null)),()=>{Ve=!1}},[n,A,M,r.microphone]);const O=hb(_.value,"tts",_.failed),L=hb(_.value,"stt",_.failed),V=[(je=_.value)==null?void 0:je.tts,(ae=_.value)==null?void 0:ae.stt].map(ze=>ze&&!ze.configured?ze.note:"").filter(Boolean),J=[(xe=_.value)==null?void 0:xe.tts,(Ae=_.value)==null?void 0:Ae.stt].map(ze=>{var Ve;return ze&&ze.configured?String(((Ve=ze.hint)==null?void 0:Ve.sentence)||"").trim():""}).filter(Boolean),U=!!((mt=(He=l.controls)==null?void 0:He.quality_preset)!=null&&mt.supported),te={deviceId:E&&S.output_device||"",volume:R},z=N&&N.length?[{value:"",label:"Detect automatically"},...N.map(ze=>({value:ze,label:mu(ze)}))]:[...OM],ne=S.stt_language||"";ne&&!z.some(ze=>ze.value===ne)&&z.push({value:ne,label:`${mu(ne)} (saved)`});const se=Mw(S.capture_mode??((nt=e.captureDefaults)==null?void 0:nt.capture_mode)),de=S.auto_send??((rt=e.captureDefaults)==null?void 0:rt.auto_send)??!1;return s.jsxs("div",{className:`af-voice-section${e.className?` ${e.className}`:""}`,children:[e.unavailableReason?s.jsx("p",{className:"af-settings-group__help",role:"status",children:e.unavailableReason}):null,K?s.jsxs(Oh,{variant:P,title:"Engines",help:"Which engines speak and listen.",children:[e.ttsSlot?s.jsx("div",{className:"af-voice-section__tts-slot","data-voice-slot":"tts",children:e.ttsSlot}):null,W?s.jsx(Lb,{label:"Text → speech",setting:"tts",defaultSummary:O,overrideSummary:DM(S),overrideOwner:t,open:y==="tts",onToggle:()=>b(y==="tts"?"":"tts"),onReset:()=>D({provider:"",model:"",voice:"",profile:""}),disabled:n,children:s.jsx(PE,{value:S,onChange:ze=>e.onChange({...S,...ze}),fetchCatalog:e.fetchCatalog,intro:null,quality:!1,showReset:!1,voiceDefaultLabel:"Gateway default",voiceLibrary:H,previewVoice:e.previewVoice?(ze,Ve,ct)=>e.previewVoice({...S,...ze},Ve,ct):void 0,previewOn:te,recordFrom:{deviceId:S.input_device||"",gain:I}})}):null,G?s.jsx(Lb,{label:"Speech → text",setting:"stt",defaultSummary:L,overrideSummary:FM(S),overrideOwner:t,open:y==="stt",onToggle:()=>b(y==="stt"?"":"stt"),onReset:()=>D({stt_provider:"",stt_model:""}),disabled:n,children:s.jsx(Rj,{value:{provider:S.stt_provider||"",model:S.stt_model||""},onChange:ze=>D({stt_provider:ze.provider,stt_model:ze.model}),fetchProviders:async()=>{const ze=await i.current();return zb(ze.stt_providers).map(Ve=>({name:Ve}))},fetchModels:async ze=>{var ct;const Ve=await i.current(ze);return zb(((ct=Ve.stt_models_by_provider)==null?void 0:ct[ze])||Ve.stt_models)},inheritLabel:"Gateway default",providerLabel:"Transcription provider",modelLabel:"Transcription model"})}):null,_.failed?s.jsx("p",{className:"af-settings-group__help","data-voice-note":"defaults",role:"status",children:"The gateway's default voice routes could not be read. Requests still use them."}):null,V.map(ze=>s.jsx("p",{className:"af-settings-group__help","data-voice-note":"unset",children:ze},ze)),J.map(ze=>s.jsx("p",{className:"af-settings-group__help","data-voice-note":"hint",role:"note",children:ze},ze))]}):null,r.output!==!1?s.jsx(Oh,{variant:P,title:"Output",children:s.jsx(EM,{value:S,onChange:e.onChange,listDevices:e.listDevices,outputSelectable:E,showMute:r.mute===!0,unavailableReason:e.unavailableReason,devicesKey:k})}):null,r.microphone!==!1?s.jsxs(Oh,{variant:P,title:"Microphone",children:[s.jsx(MM,{value:S,onChange:e.onChange,levelSource:e.levelSource,listDevices:e.listDevices,playOn:te,onDevicesChanged:()=>x(ze=>ze+1),unavailableReason:e.unavailableReason}),s.jsx(ic,{label:"Spoken language",setting:"stt-language",help:"Naming it skips detection: transcription is faster.",children:s.jsx(Br,{ariaLabel:"Spoken language",placeholder:"Detect automatically",value:ne,options:z,disabled:n,searchable:!1,onChange:ze=>D({stt_language:ze})})}),r.capture===!0?s.jsxs(s.Fragment,{children:[s.jsx(ic,{label:"Microphone button",setting:"capture-mode",children:s.jsx(Br,{ariaLabel:"Microphone button",value:se,options:PM,disabled:n,searchable:!1,onChange:ze=>D({capture_mode:ze==="toggle"?"toggle":"hold"})})}),s.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"auto-send",children:s.jsx(Di,{label:"Send what you say automatically",description:"Off: what you say lands in the message box for you to review.",variant:"row",checked:de,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:ze=>D({auto_send:ze})})})]}):null]}):null,r.replies!==!1?s.jsxs(Oh,{variant:P,title:"Replies",children:[s.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"read-aloud",children:s.jsx(Di,{label:"Read aloud",description:"Speak each new reply.",variant:"row",checked:S.read_aloud===!0,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:ze=>D({read_aloud:ze})})}),s.jsx(ic,{label:"Voice latency",setting:"latency",help:U?"Trades quality for a faster first word.":"This gateway's voice engine has no latency control.",children:s.jsx(Br,{ariaLabel:"Voice latency",placeholder:"Gateway default",value:U&&S.quality_preset||"",options:zM,disabled:n||!U,searchable:!1,onChange:ze=>D({quality_preset:ze})})})]}):null]})}function Tg(e){const t=String(e??"").trim();if(!t||!(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))return null;try{return JSON.parse(t)}catch{return null}}function UM(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function WM(e){const t=String(e.role||"message").trim()||"message",n=String(e.title||"").trim(),r=String(e.ts||"").trim(),i=[t];return n&&i.push(n),r&&i.push(r),i.join(" · ")}function qM(e){return e.endsWith(`
68
+ `)?e:`${e}
69
+ `}function HM(e){return String(e||"").trimStart().startsWith("```")}function KS(e,t){const r=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const i of e){const o=WM(i);r.push(`## ${o}`,"");const u=String(i.content||""),l=Tg(u);l!==null&&!HM(u)?r.push("```json",UM(l).trimEnd(),"```",""):r.push(qM(u).trimEnd(),""),r.push("---","")}for(;r.length&&!r[r.length-1].trim();)r.pop();return r.length&&r[r.length-1]==="---"&&r.pop(),`${r.join(`
70
+ `).trimEnd()}
71
+ `}async function sl(e){var n;const t=String(e||"");if(!t)return!1;try{if(typeof navigator<"u"&&typeof((n=navigator.clipboard)==null?void 0:n.writeText)=="function")return await navigator.clipboard.writeText(t),!0}catch{}try{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-9999px",document.body.appendChild(r),r.select();const i=document.execCommand("copy")===!0;return document.body.removeChild(r),i}catch{return!1}}function JS(e){const t=String(e.filename||"").trim()||"export.txt",n=String(e.text||""),r=String(e.mime||"text/plain;charset=utf-8"),i=new Blob([n],{type:r}),o=URL.createObjectURL(i),u=document.createElement("a");u.href=o,u.download=t,document.body.appendChild(u),u.click(),u.remove(),window.setTimeout(()=>URL.revokeObjectURL(o),1e3)}const VM=3,GM=Number.MAX_SAFE_INTEGER;function YS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function XS(e){return Array.isArray(e)}function KM(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Md({kind:e,children:t}){return s.jsx("span",{className:`pc-json-token ${e}`,children:t})}function JM(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[r,i]=p.useState(!n||e.expansionMode==="unfolded");return p.useEffect(()=>{n&&i(e.expansionMode==="unfolded")},[n,e.expansionMode,e.expansionVersion]),n?s.jsxs("span",{className:`pc-json-string ${r?"open":"collapsed"}`,children:[s.jsx("button",{type:"button",className:"pc-json-string__toggle",onClick:()=>i(o=>!o),"aria-label":r?"Collapse string value":"Expand string value","aria-expanded":r,children:r?"▾":"▸"}),r?s.jsx("span",{className:"pc-json-token string pc-json-string__value",children:t}):s.jsxs("button",{type:"button",className:"pc-json-string__preview",onClick:()=>i(!0),"aria-label":"Expand string value",children:[s.jsx("span",{className:"pc-json-token string pc-json-string__preview_text",children:t}),s.jsx("span",{className:"pc-json-string__suffix",children:"(...)"})]})]}):s.jsx(Md,{kind:"string",children:t})}function YM(e,t,n){return e===null?s.jsx(Md,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(JM,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?s.jsx(Md,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx(Md,{kind:"boolean",children:e?"true":"false"}):s.jsx(Md,{kind:"string",children:JSON.stringify(String(e))})}function XM(e){return XS(e)?e.length===1?"1 item":`${e.length} items`:YS(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function ZS(e){const{label:t,value:n,depth:r,collapseAfterDepth:i,expansionMode:o,expansionVersion:u,trailingComma:l}=e,d=r*14,h=YS(n),m=XS(n),_=h||m,g=r<i,[y,b]=p.useState(g);p.useEffect(()=>{b(g)},[g,u]);const k=t?s.jsxs(s.Fragment,{children:[s.jsx(Md,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!_)return s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:d},children:[k,YM(n,o,u),l?",":""]});const x=m?"[":"{",N=m?"]":"}",$=XM(n),E=y?`${x}`:`${x}…${N}${$?` (${$})`:""}`,S=m?n.map((P,D)=>({key:String(D),label:void 0,value:P})):Object.entries(n).map(([P,D])=>({key:P,label:P,value:D}));return s.jsxs("details",{className:"pc-json-viewer__details",open:y,onToggle:P=>b(P.currentTarget.open),children:[s.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:d},children:[k,s.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:y?"▾":"▸"}),s.jsx("span",{className:"pc-json-viewer__punct",children:E}),!y&&l?s.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),y?s.jsx("div",{className:"pc-json-viewer__children",children:S.length===0?s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:d},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:N}),l?",":""]}):s.jsxs(s.Fragment,{children:[S.map((P,D)=>{const R=D===S.length-1;return s.jsx(ZS,{label:P.label,value:P.value,depth:r+1,collapseAfterDepth:i,expansionMode:o,expansionVersion:u,trailingComma:!R},`${r}:${t||"root"}:${P.key}`)}),s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:d},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:N}),l?",":""]})]})}):null]})}function ZM(e){const t=e.trim();if(!t)return e;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}function fr(e){const{value:t,className:n,showCopy:r=!0}=e,[i,o]=p.useState({mode:"folded",version:0}),[u,l]=p.useState("idle"),d=typeof e.collapseAfterDepth=="number"&&(Number.isFinite(e.collapseAfterDepth)||e.collapseAfterDepth===1/0)&&e.collapseAfterDepth>=0?e.collapseAfterDepth===1/0?Number.MAX_SAFE_INTEGER:Math.trunc(e.collapseAfterDepth):VM,h=i.mode==="unfolded"?GM:d,m=p.useMemo(()=>typeof t=="string"?ZM(t):t,[t]),_=p.useMemo(()=>KM(t),[t]),g=["pc-json-viewer",n].filter(Boolean).join(" ");p.useEffect(()=>{o(b=>({mode:"folded",version:b.version+1}))},[m]);const y=()=>{o(b=>({mode:b.mode==="unfolded"?"folded":"unfolded",version:b.version+1}))};return s.jsxs("div",{className:g,children:[s.jsxs("div",{className:"pc-json-viewer__toolbar",children:[s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__toggle-all",onClick:y,"aria-expanded":i.mode==="unfolded",children:i.mode==="unfolded"?"Fold all":"Unfold all"}),r?s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__copy",onClick:()=>void sl(_).then(b=>{l(b?"copied":"failed"),window.setTimeout(()=>l("idle"),2e3)}),children:u==="copied"?"Copied":u==="failed"?"Copy failed — select and copy":"Copy JSON"}):null]}),s.jsx("div",{className:"pc-json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:s.jsx(ZS,{value:m,depth:0,collapseAfterDepth:h,expansionMode:i.mode,expansionVersion:i.version,trailingComma:!1})})]})}function QM({code:e,lang:t}){const[n,r]=p.useState("idle"),i=p.useRef(null);p.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]);const o=qS(e,Qv(t));return s.jsxs("div",{className:"pc-md_codeblock",children:[s.jsx("button",{type:"button",className:`pc-md_copy${n!=="idle"?` pc-md_copy--${n}`:""}`,"aria-label":"Copy code",title:n==="idle"?"Copy":n==="copied"?"Copied":"Copy failed",onClick:async()=>{const u=await sl(e);r(u?"copied":"failed"),i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>r("idle"),900)},children:s.jsx(qe,{name:n==="copied"?"check":"copy",size:14})}),s.jsx("pre",{className:"pc-md_pre",children:s.jsx("code",{className:t?`language-${t}`:void 0,children:o.map((u,l)=>u.kind==="plain"?s.jsx(Ee.Fragment,{children:u.text},l):s.jsx("span",{className:`af-code__${u.kind}`,children:u.text},l))})})]})}function yh(e,t){const n=String(e??"");if(!t||!t.needles.length)return[n];const r=[],i=n.toLowerCase();let o=0;for(;o<n.length;){let u=-1,l="";for(let m=0;m<t.needlesLower.length;m++){const _=t.needlesLower[m];if(!_)continue;const g=i.indexOf(_,o);if(g===-1)continue;const y=t.needles[m]||"";y&&(u===-1||g<u||g===u&&y.length>l.length)&&(u=g,l=y)}if(u===-1||!l){r.push(n.slice(o));break}u>o&&r.push(n.slice(o,u));const d=t.hits===0&&t.id?t.id:void 0,h=n.slice(u,u+l.length);r.push(s.jsx("span",{id:d,className:t.className,children:h},`hl:${t.hits}`)),t.hits+=1,o=u+l.length}return r}function QS(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const Ww="http://same-origin.invalid/";function eR(e){try{const t=new URL(e,Ww);return t.protocol==="http:"&&t.origin===new URL(Ww).origin}catch{return!1}}function eN(e){const t=String(e||"").trim();return QS(t)??(t&&eR(t)?t:void 0)}let ou=null;function tR(e){const t=String(e||"").trim();if(!t)return!1;const n=typeof document<"u"&&document.baseURI?document.baseURI:null;if(n===null&&/^[a-z][a-z0-9+.-]*:/i.test(t))return!1;const r=n??Ww;let i,o;try{i=new URL(r).origin,o=new URL(t,r)}catch{return!1}return o.protocol!=="http:"&&o.protocol!=="https:"?!1:o.origin===i}function tN(e,t,n){return s.jsx("a",{className:"pc-md_link pc-md_image_link",href:t,target:"_blank",rel:"noopener noreferrer",children:`image: ${n||t}`},e)}function Bb(e){return!!e&&/[\p{L}\p{N}]/u.test(e)}function Xa(e,t){const n=[],r=String(e??"");let i=0,o="";const u=()=>{if(o){for(const l of yh(o,t))n.push(l);o=""}};for(;i<r.length;){const l=r[i];if(l==="!"&&r[i+1]==="["){const d=r.indexOf("]",i+2);if(d!==-1&&r[d+1]==="("){const h=r.indexOf(")",d+2);if(h!==-1){const m=r.slice(i+2,d),_=eN(r.slice(d+2,h));if(_&&ou&&!ou(_)){u(),n.push(tN(`img:${i}`,_,m)),i=h+1;continue}if(_){u(),n.push(s.jsxs("span",{className:"pc-md_image_inline",children:[s.jsx("img",{className:"pc-md_img",src:_,alt:m,loading:"lazy"}),m?s.jsx("span",{className:"pc-md_img_caption",children:t?yh(m,t):m}):null]},`img:${i}`)),i=h+1;continue}}}}if(l==="["){const d=r.indexOf("]",i+1);if(d!==-1&&r[d+1]==="("){const h=r.indexOf(")",d+2);if(h!==-1){const m=r.slice(i+1,d),_=QS(r.slice(d+2,h));if(_){u(),n.push(s.jsx("a",{className:"pc-md_link",href:_,target:_.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:Xa(m,t)},`link:${i}`)),i=h+1;continue}}}}if(l==="`"){const d=r.indexOf("`",i+1);if(d!==-1){u();const h=r.slice(i+1,d);n.push(s.jsx("code",{children:t?yh(h,t):h},`code:${i}`)),i=d+1;continue}}if(l==="_"&&!Bb(r[i-1])){const d=r[i+1]==="_"?"__":"_",h=d.length;if(r[i+h]&&!/\s/.test(r[i+h])&&r[i+h]!=="_"){let m=r.indexOf(d,i+h);for(;m!==-1&&(/\s/.test(r[m-1]||" ")||Bb(r[m+h])||h===1&&r[m+1]==="_");)m=r.indexOf(d,m+1);if(m!==-1&&m>i+h){u();const _=r.slice(i+h,m),g=Xa(_,t);n.push(h===2?s.jsx("strong",{children:g},`ubold:${i}`):s.jsx("em",{children:g},`uem:${i}`)),i=m+h;continue}}}if(l==="*"&&r[i+1]==="*"){const d=r.indexOf("**",i+2);if(d!==-1){u();const h=r.slice(i+2,d);n.push(s.jsx("strong",{children:t?yh(h,t):h},`bold:${i}`)),i=d+2;continue}}if(l==="*"&&r[i+1]!=="*"){const d=r.indexOf("*",i+1);if(d!==-1){u();const h=r.slice(i+1,d);n.push(s.jsx("em",{children:t?yh(h,t):h},`em:${i}`)),i=d+1;continue}}o+=l,i+=1}return u(),n}function nR(e){return String(e??"").replace(/\r\n/g,`
72
+ `).replace(/\r/g,`
73
+ `).split(`
74
+ `)}function $p(e){const n=String(e??"").match(/^([ \t]*)(?:([-*+])|(\d{1,9})[.)])\s+(.*)$/);return n?{indent:n[1].replace(/\t/g," ").length,ordered:!!n[3],start:n[3]?Math.max(1,parseInt(n[3],10)||1):1,content:n[4]??""}:null}function sR(e){const t=[];for(const i of e){const o=$p(i);o?t.push(o):t.length>0&&i.trim()&&(t[t.length-1].content+=` ${i.trim()}`)}const n=[],r=[];for(const i of t){for(;r.length>0&&i.indent<r[r.length-1].indent;)r.pop();let o=r.length>0?r[r.length-1]:null;if(o&&i.indent>o.indent){const u=o.node.items,l=u[u.length-1];if(l){const d={ordered:i.ordered,start:i.start,items:[]};l.children.push(d),r.push({indent:i.indent,node:d}),o=r[r.length-1]}}else if(o&&o.node.ordered!==i.ordered){r.pop();const u=r.length>0?r[r.length-1]:null,l={ordered:i.ordered,start:i.start,items:[]};if(u){const d=u.node.items,h=d[d.length-1];h?h.children.push(l):u.node.items.push({content:"",children:[l]})}else n.push(l);r.push({indent:i.indent,node:l}),o=r[r.length-1]}if(!o){const u={ordered:i.ordered,start:i.start,items:[]};n.push(u),r.push({indent:i.indent,node:u}),o=r[r.length-1]}o.node.items.push({content:i.content,children:[]})}return n}function nN(e,t,n){const r=e.items.map((i,o)=>s.jsxs("li",{children:[Xa(i.content,t),i.children.map((u,l)=>nN(u,t,`${n}:${o}:${l}`))]},`${n}:li:${o}`));return e.ordered?s.jsx("ol",{className:"pc-md_ol",start:e.start!==1?e.start:void 0,children:r},n):s.jsx("ul",{className:"pc-md_ul",children:r},n)}function rR(e,t,n){return sR(e).map((r,i)=>nN(r,t,`${n}:${i}`))}function Ub(e){let t=String(e??"").trim();return t?(t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>String(n??"").trim())):[]}function Wb(e){let t=String(e??"").trim();if(!t)return!1;t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1));const n=t.split("|").map(r=>String(r??"").trim());return n.length<2?!1:n.every(r=>/^:?-{3,}:?$/.test(r))}const qb=/^(#{1,5})\s+(.*)$/;function Hb(e){return e.trim().startsWith("```")}function Vb(e){return e.trimStart().startsWith(">")}function Si(e){const t=ou;ou=e.images==="link"?e.inlineImage||tR:null;try{return iR(e)}finally{ou=t}}function iR({text:e,className:t,highlight:n,highlights:r,highlightClassName:i,highlightId:o}){const u=nR(e),l=[],d=[];Array.isArray(r)&&d.push(...r),typeof n=="string"&&n.trim()&&d.push(n);const h=Array.from(new Set(d.map(y=>String(y??"").trim()).filter(Boolean))).filter(y=>y.length>=4),m=h.length?{needles:h,needlesLower:h.map(y=>y.toLowerCase()),className:i||"pc-md_hl",id:o,hits:0}:null;let _=0;for(;_<u.length;){const y=String(u[_]??"");if(!y.trim()){_+=1;continue}const b=y.trim();if(/^([-_*])(\s*\1){2,}$/.test(b)){l.push(s.jsx("hr",{className:"pc-md_hr"},`hr:${_}`)),_+=1;continue}const k=y.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(k){const $=eN(k[2]||"");if($&&ou&&!ou($)){l.push(s.jsx("p",{className:"pc-md_p",children:tN(`img:${_}`,$,k[1]||"")},`p:${_}`)),_+=1;continue}if($){const E=k[1]||"";l.push(s.jsxs("figure",{className:"pc-md_figure",children:[s.jsx("img",{className:"pc-md_img",src:$,alt:E,loading:"lazy"}),E?s.jsx("figcaption",{children:Xa(E,m)}):null]},`figure:${_}`)),_+=1;continue}}if(Hb(y)){const E=y.trim().replace(/```/g,"").trim(),S=[];for(_+=1;_<u.length&&!String(u[_]??"").trim().startsWith("```");)S.push(String(u[_]??"")),_+=1;_<u.length&&(_+=1);const P=S.join(`
75
+ `);l.push(s.jsx(QM,{code:P,lang:E},`pre:${_}`));continue}const x=y.match(qb);if(x){const $=x[1].length,E=x[2]||"",S=Xa(E,m);$===1?l.push(s.jsx("h1",{children:S},`h1:${_}`)):$===2?l.push(s.jsx("h2",{children:S},`h2:${_}`)):$===3?l.push(s.jsx("h3",{children:S},`h3:${_}`)):$===4?l.push(s.jsx("h4",{children:S},`h4:${_}`)):l.push(s.jsx("h5",{children:S},`h5:${_}`)),_+=1;continue}if(Vb(y)){const $=[];for(;_<u.length&&String(u[_]??"").trimStart().startsWith(">");){const S=String(u[_]??"").trimStart();$.push(S.replace(/^>\s?/,"")),_+=1}l.push(s.jsx("blockquote",{className:"pc-md_quote",children:$.map((E,S)=>s.jsxs(Ee.Fragment,{children:[Xa(E,m),S<$.length-1?s.jsx("br",{}):null]},`q:${_}:${S}`))},`quote:${_}`));continue}if(y.includes("|")&&_+1<u.length&&Wb(String(u[_+1]??""))){const $=Ub(y),E=Math.max(1,$.length),S=[];for(_+=2;_<u.length;){const P=String(u[_]??"");if(!P.trim()||!P.includes("|"))break;const D=Ub(P),R=[];for(let I=0;I<E;I++)R.push(D[I]??"");S.push(R),_+=1}l.push(s.jsx("div",{className:"pc-md_table_wrap",children:s.jsxs("table",{className:"pc-md_table",children:[s.jsx("thead",{children:s.jsx("tr",{children:$.slice(0,E).map((P,D)=>s.jsx("th",{children:Xa(P,m)},`th:${_}:${D}`))})}),s.jsx("tbody",{children:S.map((P,D)=>s.jsx("tr",{children:P.map((R,I)=>s.jsx("td",{children:Xa(R,m)},`td:${_}:${D}:${I}`))},`tr:${_}:${D}`))})]})},`table:${_}`));continue}if($p(y)){const $=[];for(;_<u.length;){const E=String(u[_]??"");if(!E.trim()||E.trimStart().startsWith("```"))break;if($p(E)||/^\s{2,}\S/.test(E)){$.push(E),_+=1;continue}break}l.push(s.jsx(Ee.Fragment,{children:rR($,m,`list:${_}`)},`list:${_}`));continue}const N=[];for(;_<u.length&&String(u[_]??"").trim()&&!(N.length>0&&$p(String(u[_]??"")));){const $=String(u[_]??"");if(N.length>0&&(qb.test($)||Hb($)||Vb($))||N.length>0&&$.includes("|")&&_+1<u.length&&Wb(String(u[_+1]??"")))break;N.push($),_+=1}l.push(s.jsx("p",{className:"pc-md_p",children:N.map(($,E)=>s.jsxs(Ee.Fragment,{children:[Xa($,m),E<N.length-1?s.jsx("br",{}):null]},`pl:${_}:${E}`))},`p:${_}`))}const g=["pc-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:g,children:l})}function sN(e){const t=String(e.text??""),n=p.useMemo(()=>Tg(t),[t]),r=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?s.jsx("div",{className:r,children:s.jsx(fr,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?s.jsx("div",{className:r,children:e.renderMarkdown(t)}):s.jsx("div",{className:r,children:s.jsx(Si,{text:t,images:e.images,inlineImage:e.inlineImage})})}const oR=new Set("html htm xhtml xht shtml svg svgz xml xsl xslt mht mhtml".split(" ")),aR=new Set(["application/pdf","application/json","text/plain","text/markdown","text/csv","text/tab-separated-values","text/x-python","text/javascript","application/javascript","text/css","text/x-c","text/x-shellscript","text/x-typescript","image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","video/mp4","video/webm","video/quicktime","audio/mpeg","audio/mp4","audio/aac","audio/wav","audio/x-wav","audio/ogg","audio/webm","audio/flac"]);function rN(e){const t=String(e??"");if(!t.trim())return!1;try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/",r=new URL(t,n).protocol;return r==="blob:"||r==="data:"}catch{return!0}}function lR(e,t){const n=String(t||"").split("/").pop()||"",r=n.lastIndexOf(".");if(r>0&&oR.has(n.slice(r+1).toLowerCase()))return!1;const i=String(e||"").split(";",1)[0].trim().toLowerCase();return!i||i==="text/html"||i.includes("xml")?!1:aR.has(i)}function cR(e){const t=n=>!!n&&(!rN(n)||lR(e.contentType,e.name));if(t(e.href))return e.href;if(t(e.src))return e.src}const Gb=1024*1024,uR="1 MiB",dR=25*1024*1024,iN=(e,t)=>`${wt(`runs/${encodeURIComponent(e)}/workspace`)}/content?${new URLSearchParams({path:t})}`;function fR(e){const t=e.headers.get("content-range"),n=t?Number(t.split("/")[1]):NaN;if(Number.isFinite(n))return n;const r=Number(e.headers.get("content-length"));return e.status===200&&Number.isFinite(r)&&e.headers.has("content-length")?r:void 0}async function hR(e,t,n){var h;const r=new TextDecoder;let i="",o=0;const u=(h=e.body)==null?void 0:h.getReader();if(u){for(;o<t;){const{done:m,value:_}=await u.read();if(m)break;const g=_.subarray(0,t-o);o+=g.length,i+=r.decode(g,{stream:!0})}await u.cancel().catch(()=>{})}else i=(await e.text()).slice(0,t),o=i.length;const l=fR(e)??n,d=l!==void 0?l>o:o>=t;return{text:i,received:o,total:l,partial:d}}function mR(e){return`Showing the first ${uR} of ${e!==void 0?Eg(e):"a file of unknown size"}; download for the rest.`}function _R(e){try{return decodeURIComponent(e)}catch{return e}}function pR(e,t,n){const r=`${wt(`runs/${encodeURIComponent(t)}/workspace`)}/content?`,i=n.split("/").slice(0,-1),o=d=>{if(/^[a-z][a-z0-9+.-]*:/i.test(d)||d.startsWith("/")||d.startsWith("#"))return null;const h=[...i];for(const m of d.split(/[?#]/,1)[0].split("/"))if(!(!m||m==="."))if(m===".."){if(!h.length)return null;h.pop()}else h.push(_R(m));return h.length?iN(t,h.join("/")):null},u=d=>{let h="",m=0;for(;m<d.length;){if(d[m]==="!"&&d[m+1]==="["){const _=d.indexOf("]",m+2);if(_!==-1&&d[_+1]==="("){const g=d.indexOf(")",_+2);if(g!==-1){const y=d.slice(m+2,_),b=d.slice(_+2,g).trim(),k=b.startsWith(r)?b:o(b);h+=k?`![${y}](${k})`:`[image: ${y||b}](${b})`,m=g+1;continue}}}h+=d[m],m+=1}return h};let l=!1;return e.split(`
76
+ `).map(d=>/^\s*(```|~~~)/.test(d)?(l=!l,d):l?d:u(d)).join(`
77
+ `)}function gR(e,t,n,r){const[i,o]=p.useState({status:"idle"});return p.useEffect(()=>{if(!n||!t){o({status:"idle"});return}const u=new AbortController;let l="";const d=Gp(n.name);if(d==="binary"){o({status:"ready",kind:"binary",contentType:"",partial:!1});return}if((d==="image"||d==="audio"||d==="video"||d==="pdf")&&typeof n.size_bytes=="number"&&n.size_bytes>dR){o({status:"error",kind:d,message:`Too large to preview (${Eg(n.size_bytes)}); use Download.`});return}o({status:"loading",kind:d});const h=Uw(d);return(async()=>{var m;try{const _=await e(iN(t,n.path),{signal:u.signal,...h?{headers:{Range:`bytes=0-${Gb-1}`}}:{}});if(!_.ok)throw new Error(`Preview failed (HTTP ${_.status}): ${await _.text().catch(()=>"")||_.statusText||"no reason given"}`);const g=_.headers.get("content-type")||"",y=Gp(n.name,g);if(Uw(y)){const b=await hR(_,Gb,n.size_bytes);if(u.signal.aborted)return;o({status:"ready",kind:y,contentType:g,text:y==="markdown"?pR(b.text,t,n.path):b.text,partial:b.partial,total:b.total});return}if(y==="image"||y==="audio"||y==="video"||y==="pdf"){const b=await _.blob();if(u.signal.aborted)return;l=URL.createObjectURL(b.type?b:new Blob([b],{type:y==="pdf"?"application/pdf":g})),o({status:"ready",kind:y,contentType:g,url:l,partial:!1});return}await((m=_.body)==null?void 0:m.cancel().catch(()=>{})),u.signal.aborted||o({status:"ready",kind:"binary",contentType:g,partial:!1})}catch(_){u.signal.aborted||o({status:"error",kind:d,message:String((_==null?void 0:_.message)||_)})}})(),()=>{u.abort(),l&&URL.revokeObjectURL(l)}},[e,t,n==null?void 0:n.path,n==null?void 0:n.name,n==null?void 0:n.size_bytes,r]),i}function oN(e){const{markdownImages:t,inlineImage:n,renderMarkdown:r,...i}=e;return s.jsx(aM,{...i,nowMs:e.nowMs??Date.now(),renderMarkdown:r||(o=>s.jsx(Si,{text:o,...t?{images:t}:{},...n?{inlineImage:n}:{}}))})}function yR(e){return e.status==="idle"||e.status==="loading"?{status:"loading",...e.status==="loading"?{kind:e.kind}:{}}:e.status==="error"?{status:"error",error:e.message,kind:e.kind}:{status:"ready",kind:e.kind,contentType:e.contentType,...e.text!==void 0?{text:e.text}:{},...e.url?{url:e.url}:{},...e.partial?{partialNote:mR(e.total)}:{}}}function Ph(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Xl(e){return typeof e=="string"?e.trim():""}function wR(e){var i;const t=Ph(e);if(!t)return null;const n=Ph(t.sandbox);if(n&&Xl(n.kind))return n;const r=Ph((i=Ph(t.output))==null?void 0:i.sandbox);return r&&Xl(r.kind)?r:null}function qw(e){const t=wR(e);if(!t)return null;const n=Xl(t.kind),r=Xl(t.label)||n,i=Number.isFinite(Number(t.builtin_refused))?Math.max(0,Math.trunc(Number(t.builtin_refused))):0;if(n==="none")return{state:"refused",kind:n,label:r,line:`Sandbox: ${r} — refused`,rows:[],builtinRefused:0};const o=[],u=Xl(t.private_workspace);u&&o.push({path:u,mode:"Read & write",private:!0});for(const d of Array.isArray(t.allowed)?t.allowed:[]){const h=Ph(d),m=Xl(h==null?void 0:h.path);m&&o.push({path:m,mode:Xl(h==null?void 0:h.mode)==="ro"?"Read-only":"Read & write"})}for(const d of Array.isArray(t.refused)?t.refused:[]){const h=Xl(d);h&&o.push({path:h,mode:"Refused"})}if(n==="unsandboxed")return{state:"unsandboxed",kind:n,label:r,line:`Sandbox: ${r}`,rows:[],builtinRefused:0};const l=o.length;return{state:"sandboxed",kind:n,label:r,line:`Sandbox: ${r} · ${l} ${l===1?"workspace":"workspaces"} enforced`,rows:o,builtinRefused:i}}function aN({sandbox:e,className:t}){return e?s.jsxs("div",{className:`pc-tool-sandbox is-${e.state}${t?` ${t}`:""}`,"data-sandbox-kind":e.kind,children:[s.jsx("div",{className:"pc-tool-sandbox__line",children:e.line}),e.rows.length?s.jsxs("ul",{className:"pc-tool-sandbox__rows","aria-label":"Workspaces the sandbox enforced",children:[e.rows.map((n,r)=>s.jsxs("li",{children:[s.jsx("code",{children:n.path}),s.jsx("span",{className:"pc-tool-sandbox__mode",children:n.private?`${n.mode} · this run's folder`:n.mode})]},`${n.mode}:${n.path}:${r}`)),e.builtinRefused?s.jsxs("li",{className:"pc-tool-sandbox__builtin",children:[e.builtinRefused," built-in protected ",e.builtinRefused===1?"folder":"folders"," refused"]}):null]}):null]}):null}const $y=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,xi=e=>typeof e=="string"?e.trim():typeof e=="number"?String(e):"";function vR(e){const t=xi(e==null?void 0:e.decision);if(t!=="auto_approved"&&t!=="denied")return null;const n=$y(e==null?void 0:e.policy),r=$y(n==null?void 0:n.set_by),i=xi(r==null?void 0:r.user_id)||xi(r==null?void 0:r.client),o=typeof(n==null?void 0:n.revision)=="number"?n.revision:void 0,u={decision:t,...xi(e==null?void 0:e.source)?{source:xi(e==null?void 0:e.source)}:{},...o!==void 0?{revision:o}:{},...i?{setBy:i}:{},...xi(n==null?void 0:n.set_at)?{setAt:xi(n==null?void 0:n.set_at)}:{}},l=(Array.isArray(e==null?void 0:e.tool_calls)?e.tool_calls:[]).map(d=>$y(d)).filter(d=>!!(d&&xi(d.call_id))).map(d=>({callId:xi(d.call_id),name:xi(d.name),...xi(d.matched)?{matched:xi(d.matched)}:{}}));return l.length?{provenance:u,calls:l}:null}function Hw(e){if(e.decision==="denied")return"Denied by this chat's policy";const t=e.setAt?ex(e.setAt):"",r=[e.setBy?`set by ${e.setBy}`:"",t?`at ${t}`:""].filter(Boolean).join(" ");return`Allowed by this chat's policy${r?` (${r})`:""}`}function Kb(e){const t=new Map;for(const n of e||[]){const r=xi(n==null?void 0:n.name);if(!r)continue;const i=xi(n==null?void 0:n.reason).replace(/_/g," ")||"not stored";t.set(i,[...t.get(i)||[],r])}return t.size?`Not covered: ${[...t].map(([n,r])=>`${r.join(", ")} (${n})`).join("; ")}`:""}function lN(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function xR(e){const t=lN(e);if(!t||typeof t!="object"||Array.isArray(t))return{label:"input",value:t==null?"":String(t)};const n=Object.entries(t),i=["command","query","url","file_path","path","pattern","name"].map(o=>n.find(([u])=>u===o)).find(Boolean)||n[0];return i?{label:i[0].replace(/_/g," "),value:typeof i[1]=="string"?i[1]:JSON.stringify(i[1])??""}:{label:"",value:""}}function cN({tool:e,showCopy:t=!0}){const[n,r]=p.useState(!1),i=lN(e.arguments),o=xR(e.arguments),u=["file path","path"].includes(o.label)&&o.value.length>60?`${o.value.split(/[\\/]/).pop()} · ${o.value.slice(0,24)}…`:o.value,l=e.error&&/^File ['"].+['"] does not exist\.?$/.test(e.error)?"File not found. Expand for the exact path.":e.error&&e.error.length>180?`${e.error.slice(0,100)}…${e.error.slice(-70)}`:e.error,d={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},h=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,m=i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i):null;return s.jsxs("details",{className:`pc-tool-activity pc-tool-activity--${e.status}`,children:[s.jsxs("summary",{className:"pc-tool-activity__summary",children:[s.jsx("span",{className:"pc-tool-activity__state-icon","aria-hidden":"true",children:s.jsx(qe,{name:e.status==="completed"?"check":e.status==="failed"?"x":e.status==="waiting"?"warning":"loader",size:15})}),s.jsx("strong",{children:e.name}),s.jsx("span",{className:"pc-tool-activity__preview",title:o.value,children:o.value?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pc-tool-activity__key",children:o.label}),u]}):"No parameters"}),s.jsx("span",{className:"pc-tool-activity__status",children:d[e.status]}),e.policy?s.jsx("span",{className:"pc-tool-activity__policy","data-policy":e.policy.decision,title:Hw(e.policy),children:e.policy.decision==="denied"?"Denied by this chat's policy":"Allowed by this chat's policy"}):null,Number.isFinite(h)&&h>=0?s.jsxs("span",{className:"pc-tool-activity__duration",children:[(h/1e3).toFixed(1),"s"]}):null,s.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:s.jsx(qe,{name:"chevronRight",size:13})}),e.error?s.jsx("span",{className:"pc-tool-activity__error",title:e.error,children:l}):null]}),s.jsxs("div",{className:"pc-tool-activity__detail",children:[e.policy?s.jsxs("p",{className:"pc-tool-activity__policy-line","data-policy":e.policy.decision,children:[Hw(e.policy),e.policy.matched?` · matched ${e.policy.matched}`:""]}):null,s.jsx(aN,{sandbox:e.sandbox}),e.error?s.jsxs(s.Fragment,{children:[s.jsx("h4",{children:"Error"}),s.jsx("pre",{className:"pc-tool-activity__output",children:e.error})]}):null,s.jsxs("div",{className:"pc-tool-activity__detail-heading",children:[s.jsx("h4",{children:"Parameters"}),t?s.jsxs("button",{type:"button",onClick:async()=>r(await sl(JSON.stringify(e,null,2))),children:[s.jsx(qe,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),m?s.jsx("dl",{className:"pc-tool-activity__parameters",children:m.map(([_,g])=>s.jsxs(Ee.Fragment,{children:[s.jsx("dt",{children:_}),s.jsx("dd",{children:g&&typeof g=="object"?s.jsx(fr,{value:g}):s.jsx("code",{children:typeof g=="string"?g:JSON.stringify(g)})})]},_))}):e.arguments===void 0?s.jsx("p",{children:"Arguments are unavailable in this ledger."}):s.jsx(fr,{value:i}),e.output!==void 0?s.jsxs(s.Fragment,{children:[s.jsx("h4",{children:"Result"}),typeof e.output=="string"?s.jsx("pre",{className:"pc-tool-activity__output",children:e.output}):s.jsx("div",{className:"pc-tool-activity__output",children:s.jsx(fr,{value:e.output})})]}):null]})]})}function uN({tools:e,showCopy:t}){const n=r=>e.filter(i=>i.status===r).length;return s.jsxs("section",{className:"pc-tool-group","aria-label":"Tool activity",children:[s.jsxs("div",{className:"pc-tool-group__heading",children:[s.jsx(qe,{name:"terminal",size:14}),s.jsx("strong",{children:"Tools"}),s.jsxs("span",{children:[e.length," ",e.length===1?"call":"calls"]}),s.jsx("div",{}),n("running")?s.jsxs("span",{className:"pc-tool-group__running",children:[n("running")," running"]}):null,n("waiting")?s.jsxs("span",{className:"pc-tool-group__waiting",children:[n("waiting")," need approval"]}):null,n("failed")?s.jsxs("span",{className:"pc-tool-group__failed",children:[n("failed")," failed"]}):null,n("completed")?s.jsxs("span",{className:"pc-tool-group__completed",children:[n("completed")," done"]}):null]}),e.map(r=>s.jsx(cN,{tool:r,showCopy:t},r.id))]})}const $r="not reported",Zr=e=>e===void 0?$r:Math.round(e).toLocaleString(),bi=e=>{if(e===void 0)return $r;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;const t=Math.round(e/1e3);return`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`},dN=e=>e===void 0?$r:`${Math.round(e).toLocaleString()} tok/s`,bR=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",au=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,kR=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function jR(e){const t=new Map;for(const n of e)n&&t.set(n,(t.get(n)||0)+1);return[...t].map(([n,r])=>r>1?`${n} ×${r}`:n).join(" · ")}function Kp(e){const t=[],n=(e.models||[]).map(kR),r=e.providers||[];return(n.length||r.length)&&t.push([n.join(", ")||"model not reported",r.join(", ")].filter(Boolean).join(" · ")),t.push("From the run ledger; summed across this turn and its child runs."),t}function SR(e){const t=e.modelCalls||[],n=[],r=[{label:"Input",value:Zr(e.inputTokens)},{label:"Output",value:Zr(e.outputTokens)}];if(e.reasoningTokens!==void 0&&r.push({label:"Reasoning",value:Zr(e.reasoningTokens),hint:"part of output"}),r.push({label:"Total",value:Zr(e.totalTokens)}),n.push({heading:`Usage · ${au(e.llmCalls,"model call")}`,rows:r}),e.measuredCacheCalls){const o=e.cachedTokens||0,u=e.fedTokens||0,l=[{label:"Reused from cache",value:`${Zr(o)}${o+u?` (${bR(o,o+u)})`:""}`},{label:"Newly processed",value:Zr(e.fedTokens)},{label:"Outcome",value:jR(t.map(d=>d.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||$r},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||$r}];e.measuredCacheCalls!==e.llmCalls&&l.push({label:"Measured on",value:`${e.measuredCacheCalls} of ${e.llmCalls} calls`}),n.push({heading:"Prompt cache",rows:l})}else e.llmCalls&&n.push({heading:"Prompt cache",rows:[{label:"Cache reuse",value:$r}]});const i=t.filter(o=>o.inputTokens!==void 0);return i.length===1&&t.length===1?n.push({heading:"Context",rows:[{label:"Prompt size",value:`${Zr(i[0].inputTokens)} tokens`}]}):i.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${Zr(i[0].inputTokens)} → ${Zr(i[i.length-1].inputTokens)} tokens`}],note:"Each call re-sends the conversation, so the input total counts the context once per call."}),t.length>1&&n.push({heading:"Per call",table:{columns:["#","Input","Cached","New","Output","Cache"],rows:t.map((o,u)=>[String(u+1),Zr(o.inputTokens),o.cachedTokens===void 0?"—":Zr(o.cachedTokens),o.fedTokens===void 0?"—":Zr(o.fedTokens),Zr(o.outputTokens),o.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?$r:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:Kp(e)}}function ep(e,t,n,r){if(e===void 0)return $r;const i=[bi(e)];return t!==void 0&&i.push(`${t.toLocaleString()} ${r}${n!==void 0?` at ${dN(n)}`:""}`),i.join(" · ")}function NR(e){var h,m,_;const t=e.modelCalls||[],n=[],r=e.durationMs,i=[{label:"Wall clock",value:bi(r)}];if(i.push({label:"Model",value:e.genTimeMs===void 0?$r:`${bi(e.genTimeMs)} · ${au(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),i.push({label:"Tools",value:e.toolTimeMs!==void 0?`${bi(e.toolTimeMs)} · ${au(e.toolBatches||0,"batch","batches")}`:e.toolCalls?$r:"none",hint:e.toolTimeIncludesApproval?"includes approval wait":void 0}),r!==void 0&&e.genTimeMs!==void 0){const g=r-e.genTimeMs-(e.toolTimeMs||0);i.push({label:"Orchestration",value:g>=0?bi(g):"overlaps (parallel runs)",hint:"wall − model − tools: routing, hand-offs, model load"})}n.push({heading:"Turn",rows:i});const o=[],u=e.ttftCalls||0,l=e.promptPhaseCalls||0;e.promptPhaseMs!==void 0?o.push({label:u&&u===l?"Prefill (TTFT)":"Prefill",value:ep(e.promptPhaseMs,e.promptPhaseNewTokens,e.promptPhaseTokensPerSecond,"new tok"),hint:u===l?"measured time to first token":u?`TTFT measured on ${u} of ${l}; rest from provider rate`:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0&&e.prefillNewTokensPerSecond!==void 0?o.push({label:"Prefill",value:ep(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?o.push({label:"Prefill",value:`${bi(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${dN(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):o.push({label:"Prefill",value:$r}),e.cachedTokens&&(e.promptPhaseMs??e.prefillMs)!==void 0&&o.push({label:"Restored",value:`${e.cachedTokens.toLocaleString()} tok from cache`,hint:"not recomputed"}),o.push({label:"Generation",value:e.generationPhaseMs!==void 0?ep(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):ep(e.decodeMs,e.outputTokens,e.generationTokensPerSecond,"tok")}),e.measuredSpeedCalls&&e.measuredSpeedCalls!==e.llmCalls&&o.push({label:"Speeds from",value:`${e.measuredSpeedCalls} of ${e.llmCalls} calls`}),n.push({heading:"Model",rows:o});const d=e.speculation;if(d){const g=(d.draftKinds||[]).map(b=>b.toUpperCase()).join(", "),y=[{label:"Mode",value:`${d.used?"on":"off"}${g?` · ${g}`:""}${(h=d.modes)!=null&&h.length?` (${d.modes.join(", ")})`:""}`,hint:d.calls!==e.llmCalls||d.used!==d.calls?`used on ${d.used} of ${e.llmCalls} calls`:void 0},{label:"Acceptance",value:d.acceptanceRate===void 0?$r:`${Math.round(d.acceptanceRate*100)}% · ${Zr(d.acceptedTokens)} of ${Zr(d.draftedTokens)} drafted`}];((m=d.draftLengths)!=null&&m.length||d.rounds!==void 0)&&y.push({label:"Draft length",value:`${(_=d.draftLengths)!=null&&_.length?`${d.draftLengths.join("/")} tok/round`:$r}${d.rounds!==void 0?` · ${d.rounds.toLocaleString()} rounds`:""}`}),n.push({heading:"Speculation",rows:y})}return e.slowestToolBatch&&n.push({heading:"Tools",rows:[{label:"Total",value:`${bi(e.toolTimeMs)} · ${au(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${bi(e.slowestToolBatch.ms)} · ${fN(e.slowestToolBatch)}`}],note:e.toolTimeIncludesApproval?"Gated calls are timed from request to result, so this includes waiting for your approval.":void 0}),t.length>1&&n.push({heading:"Per call",table:{columns:["#","Prefill","New tok/s","Gen","Gen tok/s","Cache"],rows:t.map((g,y)=>[String(y+1),g.promptMs===void 0?"—":`${bi(g.promptMs)}${g.promptSource==="rate"?"*":""}`,g.promptNewTokensPerSecond===void 0?"—":Math.round(g.promptNewTokensPerSecond).toLocaleString(),g.generationMs===void 0?"—":bi(g.generationMs),g.generationTokensPerSecond===void 0?"—":Math.round(g.generationTokensPerSecond).toLocaleString(),g.cacheOutcome||"—"])},note:t.some(g=>g.promptSource==="rate")?"* derived from the provider's prompt rate (no TTFT event).":void 0}),{kind:"time",title:"Time",headline:r===void 0?$r:`${bi(r)} wall clock`,sections:n,footer:Kp(e)}}function fN(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${au(e.calls,"call")} (${e.tools.join(", ")})`}function $R(e){const t=[],n=(e.toolsWaiting||0)+(e.toolsRunning||0);if(!e.toolCalls&&!n)return t.push({heading:"Outcome",rows:[{label:"Tools called",value:"none"}]}),{kind:"tools",title:"Tools",headline:"none",sections:t,footer:Kp(e)};const r=[{label:"Succeeded",value:(e.toolCalls-(e.toolsFailed||0)).toLocaleString()},{label:"Failed",value:(e.toolsFailed||0).toLocaleString()}];e.toolsRunning&&r.push({label:"Running",value:e.toolsRunning.toLocaleString()}),e.toolsWaiting&&r.push({label:"Awaiting approval",value:e.toolsWaiting.toLocaleString(),hint:"not run yet — not a failure"}),t.push({heading:"Outcome",rows:r});const i=Object.entries(e.toolBreakdown||{}).sort((l,d)=>d[1].calls-l[1].calls||l[0].localeCompare(d[0]));i.length&&t.push({heading:"By tool",table:{columns:["Tool","Calls","Failed","Time"],rows:i.map(([l,d])=>[l,d.calls.toLocaleString(),d.failed.toLocaleString(),d.ms!==void 0?`${bi(d.ms)}${d.sharedBatches?" +shared":""}`:d.sharedBatches?"shared":$r])},note:i.some(([,l])=>l.sharedBatches)?"A batch that mixed tools ran them together; its time is not split between them.":void 0});const o=i.filter(([,l])=>l.errors&&Object.keys(l.errors).length);o.length&&t.push({heading:"Failures",rows:o.map(([l,d])=>({label:l,value:Object.entries(d.errors).sort((h,m)=>m[1]-h[1]).map(([h,m])=>m>1?`${h} ×${m}`:h).join(" · ")}))});const u=[{label:"Tool time",value:e.toolTimeMs===void 0?$r:`${bi(e.toolTimeMs)} · ${au(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${bi(e.slowestToolBatch.ms)} · ${fN(e.slowestToolBatch)}`}),t.push({heading:"Timing",rows:u,note:e.toolTimeIncludesApproval?"Gated calls are timed from request to result, so this includes waiting for your approval.":void 0}),{kind:"tools",title:"Tools",headline:`${au(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:Kp(e)}}function Cy(e,t){return e==="tokens"?SR(t):e==="time"?NR(t):$R(t)}function CR(e){const t=e.detail;return s.jsxs("div",{ref:e.panelRef,id:e.id,role:"tooltip",className:`pc-stat-detail pc-stat-detail--${t.kind}`,style:e.style,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,children:[s.jsxs("div",{className:"pc-stat-detail-head",children:[s.jsx("span",{className:"pc-stat-detail-title",children:t.title}),s.jsx("span",{className:"pc-stat-detail-headline",children:t.headline})]}),t.sections.map(n=>{var r;return s.jsxs("div",{className:"pc-stat-detail-section",children:[s.jsx("div",{className:"pc-stat-detail-heading",children:n.heading}),(r=n.rows)!=null&&r.length?s.jsx("dl",{className:"pc-stat-detail-rows",children:n.rows.map(i=>s.jsxs(Ee.Fragment,{children:[s.jsx("dt",{children:i.label}),s.jsxs("dd",{children:[s.jsx("span",{className:i.value===$r?"pc-stat-detail-value pc-stat-detail-value--absent":"pc-stat-detail-value",children:i.value}),i.hint?s.jsx("span",{className:"pc-stat-detail-hint",children:i.hint}):null]})]},i.label))}):null,n.table?s.jsxs("table",{className:"pc-stat-detail-table",children:[s.jsx("thead",{children:s.jsx("tr",{children:n.table.columns.map(i=>s.jsx("th",{scope:"col",children:i},i))})}),s.jsx("tbody",{children:n.table.rows.map((i,o)=>s.jsx("tr",{children:i.map((u,l)=>s.jsx("td",{children:u},l))},o))})]}):null,n.note?s.jsx("p",{className:"pc-stat-detail-note",children:n.note}):null]},n.heading)}),s.jsx("div",{className:"pc-stat-detail-foot",children:t.footer.map(n=>s.jsx("div",{children:n},n))})]})}const Ga=8;function ER(e){const[t,n]=p.useState(!!e.defaultOpen),[r,i]=p.useState(null),o=p.useRef(null),u=p.useRef(null),l=p.useRef(null),d=`pc-stat-${p.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,h=p.useCallback(()=>{l.current!==null&&window.clearTimeout(l.current),l.current=null},[]),m=p.useCallback(()=>{h(),n(!0)},[h]),_=p.useCallback(()=>{h(),l.current=window.setTimeout(()=>n(!1),120)},[h]);p.useEffect(()=>h,[h]),p.useLayoutEffect(()=>{if(!t){i(null);return}const k=()=>{const x=o.current,N=u.current;if(!x||!N)return;const $=x.getBoundingClientRect(),E=N.offsetWidth,S=N.offsetHeight,P=window.innerWidth,D=window.innerHeight,R=$.top-Ga-S,I=$.bottom+Ga,W=R>=Ga?R:I+S<=D-Ga?I:Math.max(Ga,D-Ga-S),G=Math.min(Math.max(Ga,$.left),Math.max(Ga,P-Ga-E));i({top:W,left:G})};return k(),window.addEventListener("resize",k),window.addEventListener("scroll",k,!0),()=>{window.removeEventListener("resize",k),window.removeEventListener("scroll",k,!0)}},[t]),p.useEffect(()=>{if(!t)return;const k=x=>{x.key==="Escape"&&n(!1)};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]);const g=typeof e.onClick=="function",y=g?"button":"span",b=t?s.jsx(CR,{detail:e.detail,id:d,panelRef:u,onMouseEnter:h,onMouseLeave:_,style:{position:"fixed",top:(r==null?void 0:r.top)??0,left:(r==null?void 0:r.left)??0,visibility:r?"visible":"hidden"}}):null;return s.jsxs(s.Fragment,{children:[s.jsxs(y,{ref:o,...g?{type:"button"}:{tabIndex:0},className:["pc-chat-stat","pc-chat-stat--detail",g?"pc-chat-stat--clickable":"",e.className].filter(Boolean).join(" "),"aria-label":`${e.label} — ${e.detail.title.toLowerCase()} details`,"aria-describedby":t?d:void 0,"data-stat-kind":e.detail.kind,onMouseEnter:m,onMouseLeave:_,onFocus:m,onBlur:()=>n(!1),onKeyDown:k=>{k.key==="Escape"&&n(!1)},onClick:g?()=>{var k;return(k=e.onClick)==null?void 0:k.call(e)}:void 0,children:[e.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:e.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:e.label})]}),b&&typeof document<"u"?wg.createPortal(b,document.body):b]})}function AR(e){const t=e.totalTokens!==void 0?Cy("tokens",e):null,n=Cy("tools",e),r=e.durationMs!==void 0?Cy("time",e):null;return[...t?[{label:`${e.totalTokens.toLocaleString()} tokens`,detail:t}]:[],{label:`${e.toolCalls} ${e.toolCalls===1?"tool":"tools"}`,detail:n},...e.changedFiles.length?[{label:`${e.changedFiles.length} ${e.changedFiles.length===1?"file":"files"} changed`,title:e.changedFiles.join(`
78
+ `)}]:[],...r?[{label:`${(e.durationMs/1e3).toFixed(e.durationMs<1e4?1:0)}s`,detail:r}]:[]]}function TR(e){const t=String(e.role||"").trim().toLowerCase()||"system",n=String(e.kind||"").trim().toLowerCase(),r=String(e.level||"").trim().toLowerCase();return t==="system"&&n==="report_bug"?{label:String(e.title||"").trim()||"Bug report",icon:"warning",variant:"report_bug"}:t==="system"&&n==="report_feature"?{label:String(e.title||"").trim()||"Feature request",icon:"check",variant:"report_feature"}:t==="user"?{label:String(e.title||"").trim()||"You",icon:"user",variant:"user"}:t==="assistant"?{label:String(e.title||"").trim()||"Agent",icon:"bot",variant:"assistant"}:{label:String(e.title||"").trim()||(r==="error"?"Error":r==="warn"?"Warning":"System"),icon:r==="error"?"error":r==="warn"?"warning":"info",variant:r==="error"?"error":r==="warn"?"warn":"status"}}const MR=new Set(["blob:","data:","http:","https:"]);function Jp(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return MR.has(new URL(t,n).protocol)?t:void 0}catch{return}}function hN(e,t){return rN(e)?{href:e,download:t||"file"}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function RR({item:e,onOpen:t,markdown:n}){const[r,i]=p.useState(!1),o=Jp(e.src),u=String(e.name||e.label||"").trim()||"File",l=cR({href:e.href?Jp(e.href):void 0,src:o,contentType:e.contentType,name:e.name||e.label}),d=Gp(u,e.contentType),h=Uw(d),m=typeof e.text=="string";if(!o&&!l&&!m)return null;const _=Eg(e.size),g=String(e.label||"").trim()||u;return s.jsxs("figure",{className:"pc-chat-media__item pc-chat-media__item--file","data-file-kind":d,children:[s.jsxs("div",{className:"pc-chat-media__file-row",children:[s.jsx(qe,{name:"file",size:14}),s.jsx("span",{className:"pc-chat-media__file-name",title:u,children:g}),_?s.jsx("span",{className:"pc-chat-media__file-size",children:_}):null,t?s.jsx("button",{type:"button",className:"pc-chat-media__file-open","data-action":"open-file",onClick:()=>t({...e,src:o||"",...l?{href:l}:{href:void 0}}),children:"Open"}):s.jsx("button",{type:"button",className:"pc-chat-media__file-open","data-action":"toggle-file","aria-expanded":r,onClick:()=>i(y=>!y),children:r?"Close":"Open"}),l?s.jsx("a",{className:"pc-chat-media__link",...hN(l,String(e.name||"").trim()||g),children:"Raw file"}):null]}),r&&!t?s.jsx(oN,{className:"pc-chat-media__viewer",name:u,kind:d,contentType:e.contentType,sizeBytes:e.size,status:h&&!m?"error":"ready",error:h&&!m?l?"No preview text was supplied for this file; open the raw file.":"No preview text was supplied for this file.":void 0,markdownImages:n.images||"link",...n.inlineImage?{inlineImage:n.inlineImage}:{},...n.renderMarkdown?{renderMarkdown:n.renderMarkdown}:{},...m?{text:e.text}:{},...o&&!h?{url:o}:{},onClose:()=>i(!1)}):null]})}function LR({item:e,onOpenFile:t,markdown:n}){const[r,i]=p.useState(!1);if(e.kind==="file")return s.jsx(RR,{item:e,onOpen:t,markdown:n||{}});const o=Jp(e.src),u=e.href?Jp(e.href):void 0,l=e.kind==="image"||e.kind==="audio"||e.kind==="video"?e.kind:null;if(!l||!o&&!u)return null;const d=l==="image"?"Image":l==="video"?"Video":"Audio",h=String(e.label||"").trim()||`Generated ${d.toLowerCase()}`,m=()=>i(!0);return s.jsxs("figure",{className:`pc-chat-media__item pc-chat-media__item--${l}`,children:[o&&l==="image"?s.jsx("img",{className:"pc-chat-media__image",src:o,alt:h,loading:"lazy",onError:m}):null,o&&l==="video"?s.jsx("video",{className:"pc-chat-media__video",src:o,controls:!0,playsInline:!0,preload:"metadata","aria-label":h,onError:m}):null,o&&l==="audio"?s.jsx(Cg,{className:"pc-chat-media__audio",src:o,name:h}):null,l==="audio"&&String(e.transcript||"").trim()?s.jsxs("details",{className:"pc-chat-media__transcript",children:[s.jsx("summary",{children:"Transcript"}),s.jsx("p",{className:"pc-chat-media__transcript-text",children:String(e.transcript).trim()})]}):null,r?s.jsxs("div",{className:"pc-chat-media__error",role:"note",children:[d," could not be decoded by this browser",u?"; open the raw file with the link.":"."]}):null,u?s.jsx("figcaption",{className:"pc-chat-media__caption",children:s.jsx("a",{className:"pc-chat-media__link",...hN(u,String(e.name||"").trim()||h),children:h})}):null]})}function tx(e){var D,R;const t=e.message,n=p.useMemo(()=>TR(t),[t.kind,t.level,t.role,t.title]),r=String(t.ts||"").trim(),i=p.useMemo(()=>{if(!r)return"";const I=new Date(r);return Number.isFinite(I.getTime())?I.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""},[r]),[o,u]=p.useState("idle"),l=p.useRef(null);p.useEffect(()=>()=>{l.current!==null&&window.clearTimeout(l.current)},[]);const d=t.live,h=!d&&typeof e.onSpeakToggle=="function"&&n.variant==="assistant"&&!!String(t.content||"").trim(),m=h&&((D=e.getSpeakState)==null?void 0:D.call(e,t))||"idle",_=m==="loading"?"loader":m==="playing"?"pause":"speaker",g=m==="loading"?"Generating audio…":m==="playing"?"Pause":m==="paused"?"Resume":"Speak (TTS)",y=e.showCopy!==!1,b=Array.isArray(e.attachments)?e.attachments:Array.isArray(t.attachments)?t.attachments:[],k=t.statistics,x=t.stats,N=p.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(x)?x:k?AR(k):[],[e.stats,x,k]),$=Array.isArray(t.media)?t.media:[],E=String(d?d.reasoning||"":t.reasoning||""),S=!!String(t.content||"").trim();if(t.toolActivity)return s.jsx(cN,{tool:t.toolActivity,showCopy:e.showCopy});const P=e.renderFooter?e.renderFooter(t):null;if(((R=e.variant)==null?void 0:R.call(e,t))==="hint"||t.kind==="tool_policy_decision"){const I=String(t.level||"").trim().toLowerCase();return s.jsxs("div",{className:["pc-chat-hint",I==="warn"||I==="error"?`pc-chat-hint--${I}`:"",e.className].filter(Boolean).join(" "),role:"note","data-variant":"hint",children:[s.jsx("span",{className:"pc-chat-hint__text",children:String(t.content||"")}),P!=null&&P!==!1?s.jsx("div",{className:"pc-chat-footer",children:P}):null]})}return s.jsxs("div",{className:["pc-chat-item",`pc-chat-item--${n.variant}`,d?"pc-chat-item--live":"",e.className].filter(Boolean).join(" "),...d?{"aria-busy":!0}:{},children:[s.jsxs("div",{className:"pc-chat-header",children:[s.jsx("div",{className:"pc-chat-avatar","aria-hidden":"true",children:s.jsx(qe,{name:n.icon,size:14})}),s.jsx("span",{className:"pc-chat-role",children:n.label}),d?s.jsxs("span",{className:"pc-chat-live-indicator",title:d.label?`Pending: ${d.label}`:"The reply is still being written",children:[s.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),d.label||"streaming"]}):null,d!=null&&d.caption?s.jsx("span",{className:"pc-chat-live-caption",children:d.caption}):null,s.jsx("span",{className:"pc-chat-header-spacer"}),i?s.jsx("span",{className:"pc-chat-time",children:i}):null,s.jsxs("div",{className:"pc-chat-header-actions",children:[h?s.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":g,title:g,onClick:()=>{var I;return(I=e.onSpeakToggle)==null?void 0:I.call(e,t)},children:s.jsx(qe,{name:_,size:22,className:m==="loading"?"pc-chat-speak-spinner":void 0})}):null,y?s.jsx("button",{className:`pc-chat-icon-btn ${o!=="idle"?`pc-chat-icon-btn--${o}`:""}`.trim(),type:"button","aria-label":"Copy message",title:o==="idle"?"Copy":o==="copied"?"Copied":"Copy failed",onClick:async()=>{const I=await sl(String(t.content||""));u(I?"copied":"failed"),l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(()=>u("idle"),900)},children:s.jsx(qe,{name:"copy",size:22})}):null]})]}),E.trim()?s.jsxs("details",{className:"pc-chat-thinking",children:[s.jsx("summary",{children:"Thinking"}),s.jsx("div",{className:"pc-chat-thinking-body",children:E})]}):null,S||!d&&!$.length?s.jsx("div",{className:"pc-chat-body",children:s.jsx(sN,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,$.length?s.jsx("div",{className:"pc-chat-media",children:$.slice(0,24).map((I,W)=>s.jsx(LR,{item:I,onOpenFile:e.onOpenMedia,markdown:{renderMarkdown:e.renderMarkdown,images:e.images,inlineImage:e.inlineImage}},I.id||`${I.kind}:${I.src}:${W}`))}):null,b.length?s.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:b.slice(0,24).map((I,W)=>{const G=String(I.label||"").trim()||"attachment",K=String(I.target||"").trim(),H=String(I.title||"").trim(),M=!!I.disabled||typeof I.onClick!="function";return s.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:H||G,onClick:M?void 0:I.onClick,disabled:M,children:[s.jsx(qe,{name:"paperclip",size:14}),K?s.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${K}`,children:K}):null,s.jsx("span",{className:"pc-chat-attachment-name",children:G})]},I.id||`${G}:${W}`)})}):null,N.length?s.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:N.slice(0,12).map((I,W)=>{const G=String(I.label||"").trim();if(!G)return null;if(I.detail)return s.jsx(ER,{label:G,detail:I.detail,icon:I.icon,onClick:I.onClick},I.id||`${G}:${W}`);const K=String(I.title||"").trim(),H=typeof I.onClick=="function",M=H?"button":"span";return s.jsxs(M,{...H?{type:"button"}:{},className:["pc-chat-stat",H?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:K||void 0,onClick:H?()=>{var A;return(A=I.onClick)==null?void 0:A.call(I)}:void 0,children:[I.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:I.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:G})]},I.id||`${G}:${W}`)})}):null,P!=null&&P!==!1?s.jsx("div",{className:"pc-chat-footer",children:P}):null]})}function IR(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function nx(e){const t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,r=p.useRef(null),i=p.useRef(null),[o,u]=p.useState(!0),l=p.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),d=p.useMemo(()=>{var _;const m=[];for(const g of l){const y=m[m.length-1];g.toolActivity&&((_=y==null?void 0:y[0])!=null&&_.toolActivity)&&y[0].runId===g.runId?y.push(g):m.push([g])}return m},[l]);p.useEffect(()=>{if(!n)return;const m=r.current;if(!m)return;const _=()=>{u(IR(m,t))};return m.addEventListener("scroll",_,{passive:!0}),_(),()=>m.removeEventListener("scroll",_)},[n,t]);const h=p.useMemo(()=>{let m=0;for(const _ of l)if(m+=String(_.content??"").length,Array.isArray(_.media))for(const g of _.media)m+=String((g==null?void 0:g.src)??"").length+1;return`${l.length}:${m}:${String(e.afterKey??"")}`},[l,e.afterKey]);return p.useEffect(()=>{if(!n||!o)return;const m=r.current;m&&(m.scrollTop=m.scrollHeight)},[n,o,h]),p.useEffect(()=>{if(!n)return;const m=r.current;if(!m)return;const _=()=>{o&&(m.scrollTop=m.scrollHeight)};return m.addEventListener("load",_,!0),m.addEventListener("loadedmetadata",_,!0),()=>{m.removeEventListener("load",_,!0),m.removeEventListener("loadedmetadata",_,!0)}},[n,o]),s.jsxs("div",{ref:r,className:["pc-chat-thread",e.className].filter(Boolean).join(" "),children:[l.length?null:e.empty||null,d.map((m,_)=>{var b;const g=m[0],y=String(g.id||"")||String(g.ts||"")+":"+String(g.role||"")+":"+_;return g.toolActivity?s.jsx(uN,{tools:m.map(k=>k.toolActivity),showCopy:(b=e.messageProps)==null?void 0:b.showCopy},y):s.jsx(tx,{message:g,...e.messageProps||{}},y)}),e.after,s.jsx("div",{ref:i})]})}const sx=Ee.forwardRef(function(t,n){const r=typeof t.rows=="number"&&Number.isFinite(t.rows)?Math.max(1,Math.trunc(t.rows)):3,i=!!t.disabled,o=!!t.busy,u=!i&&!o&&!!String(t.value||"").trim();return s.jsxs("div",{className:["pc-composer",t.className].filter(Boolean).join(" "),children:[t.leading,s.jsx("textarea",{ref:n,className:["pc-composer__textarea",t.textareaClassName].filter(Boolean).join(" "),value:t.value,onChange:l=>t.onChange(l.target.value),rows:r,style:{"--pc-composer-rows":String(r)},spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off",placeholder:t.placeholder||"","aria-label":t.ariaLabel||t.placeholder||"Message",disabled:i,autoFocus:!!t.autoFocus,onPaste:t.onPaste,onKeyDown:l=>{l.key!=="Enter"||l.shiftKey||l.nativeEvent.isComposing||l.keyCode===229||(l.preventDefault(),u&&t.onSubmit())}}),s.jsxs("div",{className:"pc-composer__row",children:[s.jsx("div",{className:"pc-composer__actions",children:t.actions}),s.jsx("button",{type:"button",className:t.sendButtonClassName||"pc-btn",disabled:!u,onClick:()=>t.onSubmit(),children:o?t.busyLabel||"Thinking…":t.sendLabel||"Send"})]}),t.overlay]})});function Dh(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function Jb(e){var r;const t=e==null?void 0:e.items;if(!t||!t.length)return null;let n=0;for(let i=0;i<t.length;i+=1)((r=t[i])==null?void 0:r.kind)==="file"&&(n+=1);return n>0?n:null}function Yb(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function rx(e){const t=[],n=[],r=e==null?void 0:e.items;if(r&&r.length){for(let o=0;o<r.length;o+=1){const u=r[o];if(!u||u.kind!=="file")continue;const l=typeof u.webkitGetAsEntry=="function"?u.webkitGetAsEntry():null,d=typeof u.getAsFile=="function"?u.getAsFile():null;l!=null&&l.isDirectory?n.push(l.name||(d==null?void 0:d.name)||"folder"):d&&t.push(d)}return{files:t,folders:n}}const i=e==null?void 0:e.files;if(i)for(let o=0;o<i.length;o+=1)i[o]&&t.push(i[o]);return{files:t,folders:n}}function mN(e){return e.length?e.length===1?`"${e[0]}" is a folder. Folders are not supported: drop the files inside it instead.`:`${e.length} folders were dropped. Folders are not supported: drop the files inside them instead.`:""}const OR={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function wh(e){return String(e).padStart(2,"0")}function PR(e,t,n){const r=String(e||"").trim();if(r&&!/^image\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i.test(r))return r;const i=OR[String(t||"").toLowerCase()]||r.split(".").pop()||"bin",o=`${n.getFullYear()}-${wh(n.getMonth()+1)}-${wh(n.getDate())} at ${wh(n.getHours())}.${wh(n.getMinutes())}.${wh(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!r?"Pasted image":"Pasted file"} ${o}.${i}`}function _N(e,t=new Date){if(!e)return[];const n=e.types?Array.from(e.types):[];if(n.includes("text/plain")&&n.includes("text/html"))return[];const{files:r}=rx(e);return r.map(i=>{const o=PR(i.name,i.type,t);return o===i.name?i:new File([i],o,{type:i.type,lastModified:i.lastModified})})}class DR{constructor(t=1200){this.staleMs=t,this.depth=0,this.lastSeen=0}enter(t){this.depth+=1,this.lastSeen=t}over(t){this.depth===0&&(this.depth=1),this.lastSeen=t}leave(t){return this.depth=Math.max(0,this.depth-1),this.lastSeen=t,this.depth>0}reset(){this.depth=0}active(t){return this.depth>0&&t-this.lastSeen<this.staleMs}}const Fh="llm.delta",$d="llm.delta_end";function FR(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Kc(e){return typeof e=="string"&&e.trim()!==""}function zR(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function pN(e){return"reason"in e}function gN(e,t){const n=FR(e),r=n==null?void 0:n.kind,i=t||(typeof r=="string"&&r?r:n&&"reason"in n?$d:Fh),o=d=>{throw new Error(`Malformed ${i} event from the gateway: ${d}`)};if(t!==void 0&&t!==Fh&&t!==$d&&o(`unknown event name ${JSON.stringify(t)}`),!n)return o("the payload is not an object");r!==void 0&&r!==Fh&&r!==$d&&o(`unknown kind ${JSON.stringify(r)}`),r!==void 0&&t!==void 0&&r!==t&&o(`kind ${JSON.stringify(r)} does not match the event name`),Kc(n.run_id)||o("run_id is missing"),Kc(n.call_id)||o("call_id is missing"),zR(n.seq)||o("seq is not a non-negative integer");const u=t||r?(t||r)===$d:"reason"in n;n.root_run_id!==void 0&&!Kc(n.root_run_id)&&o("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!Kc(n.parent_run_id)&&o("parent_run_id is neither a run id nor null");const l={run_id:n.run_id,...Kc(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...Kc(n.node_id)?{node_id:n.node_id}:{},call_id:n.call_id,seq:n.seq};return u?(["completed","failed","cancelled","unavailable"].includes(String(n.reason))||o(`unknown reason ${JSON.stringify(n.reason)}`),n.detail!==void 0&&n.detail!==null&&typeof n.detail!="string"&&o("detail is not a string"),{kind:$d,...l,reason:n.reason,...Kc(n.detail)?{detail:n.detail}:{}}):(typeof n.text!="string"&&o("text is not a string"),n.channel!=="content"&&n.channel!=="reasoning"&&o(`unknown channel ${JSON.stringify(n.channel)}`),typeof n.snapshot!="boolean"&&o("snapshot is not a boolean"),{kind:Fh,...l,text:n.text,channel:n.channel,snapshot:n.snapshot})}function BR(e,t){if(e!==Fh&&e!==$d)return null;let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{throw new Error(`Malformed ${e} event from the gateway: data is not JSON`)}return gN(n,e)}const UR={structured_output:"this step asks the model for structured output",remote_core:"the model runs on a remote AbstractCore server",provider_cannot_stream:"the model provider cannot stream",sink_error:"the gateway could not relay the live text",usage_unavailable:"the provider does not report token usage while streaming"};function WR(e){return`This reply is not streamed: ${e?UR[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}const ix=e=>wt(`runs/${encodeURIComponent(e)}/workspace`);function qR(e){return ix(e)}function HR(e,t){return`${ix(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function VR(e,t){return`${ix(e)}/content?${new URLSearchParams({path:t})}`}async function nf(e,t){let n="";try{const r=await e.text();try{const i=JSON.parse(r),o=(i==null?void 0:i.detail)??(i==null?void 0:i.error)??(i==null?void 0:i.message);n=typeof o=="string"?o:o&&typeof o.message=="string"?o.message:r}catch{n=r}}catch{n=""}return new Error(`${t} (HTTP ${e.status}): ${n.trim()||e.statusText||"no reason given"}`)}function GR(e,t){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null,r=u=>{throw new Error(`Unexpected /workspace/files response from the gateway: ${u}.`)};if(!n)return r("not an object");Array.isArray(n.entries)||r("no `entries` list"),typeof n.truncated!="boolean"&&r("no `truncated` flag");const i=n.entries.map((u,l)=>{const d=u&&typeof u=="object"?u:{};return(typeof d.name!="string"||typeof d.path!="string"||d.type!=="file"&&d.type!=="dir")&&r(`entry ${l+1} lacks a name, path or file/dir type`),d}),o=n.hidden&&typeof n.hidden=="object"&&!Array.isArray(n.hidden)?n.hidden:void 0;return{path:typeof n.path=="string"?n.path:t,entries:i,truncated:n.truncated,...o?{hidden:o}:{}}}async function KR(e,t,n){const r=await e(qR(t),{signal:n});if(!r.ok)throw await nf(r,"The workspace is not available");const i=await r.json();if(!i||typeof i.workspace_root!="string"||typeof i.exists!="boolean")throw new Error("Unexpected /workspace response from the gateway: no `workspace_root` / `exists`.");return i}async function JR(e,t,n,r){const i=await e(HR(t,n),{signal:r});if(!i.ok)throw await nf(i,"The folder could not be listed");return GR(await i.json(),n)}async function YR(e,t,n,r){const i=await e(VR(t,n),{signal:r});if(!i.ok)throw await nf(i,"The file could not be read");return await i.blob()}async function XR(e,t,n,r){const i=await KR(e,t,r);return{where:i,listing:i.exists?await JR(e,t,n,r):null}}function ZR(e){const t=String(e||"").split("/").filter(Boolean),n=[{label:"Workspace",path:""}];return t.forEach((r,i)=>n.push({label:r,path:t.slice(0,i+1).join("/")})),n}function yN(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;const t=["KiB","MiB","GiB","TiB"];let n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n<10?n.toFixed(1):Math.round(n)} ${t[r]}`}function QR(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function eL(e){const t=e.hidden||{},n=Number(t.blocked||0)+Number(t.outside_links||0)+Number(t.other||0),r=[];return n>0&&r.push(`${n} ${n===1?"entry":"entries"} hidden by the gateway's workspace rules`),e.truncated&&r.push("the list is truncated"),r.join("; ")}const tL=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function nL(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return tL.has(t)?{mode:"open",type:t}:t.startsWith("text/")||t.endsWith("+xml")||t.endsWith("+json")||t.endsWith("/xml")||t.endsWith("/javascript")||t.endsWith("/x-yaml")||t.endsWith("/toml")?{mode:"open",type:"text/plain;charset=utf-8"}:{mode:"download"}}function wN(e,t,n){const r=n==="open"?nL(e.type):{mode:"download"},i=r.mode==="open"&&r.type!==e.type?new Blob([e],{type:r.type}):e,o=URL.createObjectURL(i);if(r.mode==="open")window.open(o,"_blank","noopener");else{const u=document.createElement("a");u.href=o,u.download=t,document.body.appendChild(u),u.click(),u.remove()}window.setTimeout(()=>URL.revokeObjectURL(o),6e4)}async function sL(e,t,n){const r=await e(l2(t),{signal:n.signal});if(!r.ok)throw await nf(r,`${n.name} could not be read`);wN(await r.blob(),n.name,n.mode??"open")}function rL(e){const t=String(e||"").split(/[\\/]/).filter(Boolean);return t.length?t[t.length-1]:String(e||"")}function iL(e){var t;return!!(e&&e.open_supported===!0&&((t=e.host)==null?void 0:t.caller_is_this_machine)===!0&&e.exists)}async function oL(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function vN(e){var H;const{fetchGateway:t,runId:n}=e,[r,i]=p.useState({runId:n,path:""}),o=r.runId===n?r.path:"",[u,l]=p.useState(null),[d,h]=p.useState(""),[m,_]=p.useState(""),[g,y]=p.useState(!!n),[b,k]=p.useState(""),[x,N]=p.useState(!1),[$,E]=p.useState(0),[S,P]=p.useState(null),D=S&&S.runId===n&&!e.onSelectFile?S.entry:null,R=gR(t,n,D,`${e.refreshKey??""}:${$}`);p.useEffect(()=>{if(!n)return;const M=new AbortController;return y(!0),h(""),(async()=>{try{const A=await XR(t,n,o,M.signal);M.signal.aborted||l({runId:n,...A})}catch(A){M.signal.aborted||h(String((A==null?void 0:A.message)||A))}finally{M.signal.aborted||y(!1)}})(),()=>M.abort()},[t,n,o,$,e.refreshKey]),p.useEffect(()=>_(""),[n]);const I=u&&u.runId===n?u:null,W=p.useCallback(async M=>{k(M.path),h("");try{wN(await YR(t,n,M.path),M.name,"download")}catch(A){h(String((A==null?void 0:A.message)||A))}finally{k("")}},[t,n]),G=(I==null?void 0:I.where.workspace_root)||"",K=e.nowMs??Date.now();return s.jsx(aL,{title:e.title,note:e.note,where:(I==null?void 0:I.where)??null,path:o,listing:(I==null?void 0:I.listing)??null,error:d,notice:m,loading:g,fileBusy:b,selectedPath:e.onSelectFile?e.selectedPath:D==null?void 0:D.path,className:e.className,nowMs:K,openingFolder:x,onNavigate:M=>{P(null),i({runId:n,path:M})},onRefresh:()=>E(M=>M+1),onFile:M=>void W(M),onSelectFile:e.onSelectFile??(M=>P({runId:n,entry:M})),onClose:e.onClose,onCopyPath:G?()=>{(e.copyText||oL)(G).then(M=>_(M?"Path copied.":"Could not copy; select the path instead."))}:void 0,onOpenFolder:e.onOpenFolder&&iL(I==null?void 0:I.where)?()=>{N(!0),_(""),e.onOpenFolder().then(()=>_("Folder opened on this machine.")).catch(M=>_(`Open folder failed: ${String((M==null?void 0:M.message)||M)}`)).finally(()=>N(!1))}:void 0,preview:D?s.jsx(oN,{name:D.name,path:D.path,sizeBytes:D.size_bytes,modified:D.mtime,nowMs:K,...yR(R),actions:(H=e.fileActions)==null?void 0:H.call(e,D),onDownload:()=>void W(D),onClose:()=>P(null)}):null})}function aL(e){var o,u,l,d;const t=e.listing?eL(e.listing):"",n=(u=(o=e.where)==null?void 0:o.host)==null?void 0:u.hostname,r=((l=e.where)==null?void 0:l.workspace_root)||"",i=e.nowMs??Date.now();return s.jsxs("section",{className:`pc-ws${e.className?` ${e.className}`:""}`,"aria-label":e.title,"data-workspace-root":r||void 0,children:[s.jsxs("header",{className:"pc-ws__head",children:[s.jsxs("span",{className:"pc-ws__title",children:[s.jsx(qe,{name:"folder",size:15})," ",e.title]}),s.jsx("span",{className:"pc-ws__spacer"}),s.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"refresh-folder",onClick:e.onRefresh,disabled:e.loading,title:"Refresh","aria-label":"Refresh the folder",children:s.jsx(qe,{name:"refresh",size:14})}),e.onClose?s.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"close-folder",onClick:e.onClose,title:"Close","aria-label":"Close the file browser",children:s.jsx(qe,{name:"x",size:14})}):null]}),e.where?s.jsxs("div",{className:"pc-ws__root",children:[s.jsx("span",{className:"pc-ws__root-name",title:r,"data-root-name":"true",children:rL(r)}),e.onOpenFolder?s.jsx("button",{type:"button",className:"pc-ws__icon-btn pc-ws__icon-btn--bare","data-action":"open-folder",onClick:e.onOpenFolder,disabled:e.openingFolder,title:"Open folder","aria-label":"Open the folder on this machine",children:s.jsx(qe,{name:"folder",size:14})}):null,e.onCopyPath?s.jsx("button",{type:"button",className:"pc-ws__icon-btn pc-ws__icon-btn--bare","data-action":"copy-path",onClick:e.onCopyPath,title:"Copy path","aria-label":"Copy the folder path",children:s.jsx(qe,{name:"copy",size:14})}):null,n&&((d=e.where.host)==null?void 0:d.caller_is_this_machine)!==!0?s.jsxs("span",{className:"pc-ws__muted",children:[" on ",n]}):null]}):null,e.note?s.jsx("div",{className:"pc-ws__muted",children:e.note}):null,e.notice?s.jsx("div",{className:"pc-ws__muted",role:"status",children:e.notice}):null,e.error?s.jsx("div",{className:"pc-ws__error",role:"alert",children:e.error}):null,e.preview?s.jsx("div",{className:"pc-ws__preview",children:e.preview}):s.jsxs(s.Fragment,{children:[s.jsx("nav",{className:"pc-ws__crumbs","aria-label":"Folder",children:ZR(e.path).map((h,m,_)=>m===_.length-1?s.jsx("span",{"aria-current":"page",children:h.label},h.path):s.jsxs(Ee.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-ws__crumb",onClick:()=>e.onNavigate(h.path),children:h.label}),s.jsx("span",{className:"pc-ws__muted",children:" / "})]},h.path))}),e.loading&&!e.listing?s.jsx("div",{className:"pc-ws__muted",role:"status",children:"Loading…"}):null,e.where&&!e.where.exists?s.jsx("div",{className:"pc-ws__muted",children:"The folder does not exist yet: nothing has been written."}):null,e.listing?e.listing.entries.length?s.jsx("ul",{className:"pc-ws__entries",children:QR(e.listing.entries).map(h=>s.jsx("li",{className:`pc-ws__entry${e.selectedPath===h.path?" is-selected":""}`,"data-type":h.type,"data-path":h.path,children:h.type==="dir"?s.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"open-dir",onClick:()=>e.onNavigate(h.path),children:[s.jsx(qe,{name:"folder",size:14})," ",s.jsxs("span",{className:"pc-ws__label",children:[h.name,"/"]})]}):s.jsxs(s.Fragment,{children:[e.onSelectFile?s.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"select-file","aria-pressed":e.selectedPath===h.path,title:`Preview ${h.name}`,onClick:()=>{var m;return(m=e.onSelectFile)==null?void 0:m.call(e,h)},children:[s.jsx(qe,{name:"file",size:14})," ",s.jsx("span",{className:"pc-ws__label",children:h.name})]}):s.jsxs("span",{className:"pc-ws__name",children:[s.jsx(qe,{name:"file",size:14})," ",s.jsx("span",{className:"pc-ws__label",children:h.name})]}),s.jsxs("span",{className:"pc-ws__meta",children:[s.jsx("span",{className:"pc-ws__size",children:yN(h.size_bytes)}),h.mtime!==void 0&&Vp(h.mtime,i)?s.jsx("time",{className:"pc-ws__time",title:ex(h.mtime),"data-meta":"modified",children:Vp(h.mtime,i)}):null]}),e.onFile?s.jsx("button",{type:"button",className:"pc-ws__icon-btn pc-ws__icon-btn--bare","data-action":"download-file",disabled:e.fileBusy===h.path,onClick:()=>{var m;return(m=e.onFile)==null?void 0:m.call(e,h,"download")},title:"Download","aria-label":`Download ${h.name}`,children:s.jsx(qe,{name:"download",size:14})}):null]})},h.path))}):s.jsx("div",{className:"pc-ws__muted",children:"This folder is empty."}):null,t?s.jsx("div",{className:"pc-ws__muted","data-hidden-note":"true",children:t}):null]})]})}const lL={registry_scope:"tenant_catalog",bundle_id:"docs-qa",bundle_version:"0.1.1",flow_id:"docsqa001"},xN="docs";function cL(e){return wt(`docs/corpus?${new URLSearchParams({app:String(e||"")})}`)}function Ey(e){return`${String(e||"app")}-docs-assistant:${el()}`}function uL(e){const t={prompt:e.question,docs:e.docs,app:e.appName,use_session_history:!0};return e.attachments&&e.attachments.length&&(t.context={attachments:e.attachments}),{...lL,session_id:e.sessionId,kind:xN,input_data:t}}function bN(e){const t=e==null?void 0:e.output;if(typeof t=="string")return t.trim();const n=t==null?void 0:t.response;return typeof n=="string"?n.trim():""}function dL(e){const t=e&&typeof e=="object"?e:{},n=l=>typeof l=="number"&&Number.isFinite(l)&&l>0?Math.trunc(l):0,r=n(t.dropped_messages);if(!r)return"";const i=n(t.replayed_messages),o=n(t.dropped_tokens),u=n(t.max_tokens);return`Earlier messages not replayed: ${r.toLocaleString("en-US")}${o?` (~${o.toLocaleString("en-US")} tokens)`:""}. The model read the newest ${i.toLocaleString("en-US")} message${i===1?"":"s"}`+(u?` (history window: the most recent ${u.toLocaleString("en-US")} tokens of whole messages).`:".")}async function*fL(e,t){const n=e.getReader(),r=new TextDecoder;let i="";const o=()=>{n.cancel().catch(()=>{})};t==null||t.addEventListener("abort",o,{once:!0});try{for(;;){const{value:u,done:l}=await n.read();if(l)break;i+=r.decode(u,{stream:!0}).replace(/\r\n/g,`
79
+ `);let d=i.indexOf(`
80
+
81
+ `);for(;d>=0;){const h=i.slice(0,d);i=i.slice(d+2);let m="message";const _=[];for(const g of h.split(`
82
+ `))g.startsWith("event:")?m=g.slice(6).trim():g.startsWith("data:")&&_.push(g.slice(5).replace(/^ /,""));_.length&&(yield{event:m,data:_.join(`
83
+ `)}),d=i.indexOf(`
84
+
85
+ `)}}}finally{t==null||t.removeEventListener("abort",o)}}function hL(e,t){return new Promise((n,r)=>{if(t.aborted)return r(new DOMException("Aborted","AbortError"));const i=setTimeout(()=>{t.removeEventListener("abort",o),n()},e),o=()=>{clearTimeout(i),r(new DOMException("Aborted","AbortError"))};t.addEventListener("abort",o,{once:!0})})}async function sc(e,t){if(!e.ok)throw await nf(e,t);return e.json()}function mL(e){const t=e.pollMs??1e3,n=e.timeoutMs??18e4;let r=null;return async(i,o)=>{var b;const{fetchGateway:u,source:l}=e;if(r===null){const k=await u(cL(l.app),{signal:o.signal,headers:{Accept:"application/json"}}),x=await sc(k,`The ${l.name} documentation could not be read, so nothing was asked`),N=typeof(x==null?void 0:x.text)=="string"?x.text:"";if(!N.trim())throw new Error(`The gateway returned an empty ${l.name} documentation corpus, so nothing was asked.`);r=N}const d=String(r),h=[];for(const k of o.files||[]){const x=new FormData;x.append("session_id",o.sessionId),x.append("file",k,k.name||"upload.bin"),x.append("filename",k.name||"upload.bin"),k.type&&x.append("content_type",k.type);const N=await sc(await u(wt("attachments/upload"),{method:"POST",body:x,signal:o.signal}),`"${k.name}" could not be attached`),$=N==null?void 0:N.attachment;if(!$||typeof $.$artifact!="string"||!$.$artifact)throw new Error(`"${k.name}" could not be attached: the gateway returned no attachment reference.`);h.push($)}const m=await sc(await u(wt("runs/start"),{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(uL({question:i,docs:d,appName:l.name,sessionId:o.sessionId,attachments:h}))}),"The docs-qa workflow could not start"),_=String((m==null?void 0:m.run_id)||"");if(!_)throw new Error("The gateway did not return a run id for the docs-qa workflow.");const g=new AbortController,y=()=>g.abort();o.signal.addEventListener("abort",y,{once:!0}),o.onText&&(async()=>{var k;try{const x=await u(wt(`runs/${encodeURIComponent(_)}/ledger/stream?after=0`),{signal:g.signal,headers:{Accept:"text/event-stream"}});if(!x.ok||!x.body)return;let N="",$="";for await(const E of fL(x.body,g.signal)){const S=BR(E.event,E.data);!S||pN(S)||S.channel!=="content"||S.run_id!==_||(S.call_id!==N&&(N=S.call_id,$=""),$=S.snapshot?S.text:$+S.text,(k=o.onText)==null||k.call(o,$))}}catch{}})();try{const k=Date.now()+n;for(;;){await hL(t,o.signal);const x=await sc(await u(wt(`runs/${encodeURIComponent(_)}`),{signal:o.signal}),"The docs-qa run could not be read"),N=String((x==null?void 0:x.status)||"").toLowerCase();if(N==="completed"){(b=o.onHistory)==null||b.call(o,(x==null?void 0:x.session_history)??null);const $=bN(x);if(!$)throw new Error(`The docs-qa run ${_} completed without an answer.`);return $}if(N==="failed"||N==="cancelled"){const $=x==null?void 0:x.error,E=typeof $=="string"?$:typeof($==null?void 0:$.message)=="string"?$.message:"";throw new Error(`The docs-qa run ${N}${E?`: ${E}`:""}.`)}if(N==="waiting")throw new Error(`The docs-qa run ${_} is waiting for input it should never need. Inspect it in Observer.`);if(Date.now()>=k)throw new Error(`The docs-qa run ${_} is still running after ${Math.round(n/1e3)} s. It stays in the gateway's history.`)}}finally{o.signal.removeEventListener("abort",y),g.abort()}}}async function _L(e,t,n={}){const r=new URLSearchParams({root_only:"true",kind:xN,limit:"500",include_ledger_len:"false"}),i=await sc(await e(wt(`runs?${r}`),{signal:n.signal}),"The docs assistant history could not be read"),o=`${String(t||"app")}-docs-assistant:`,u=new Map;for(const d of Array.isArray(i==null?void 0:i.items)?i.items:[]){const h=String((d==null?void 0:d.session_id)||"");if(!h.startsWith(o)||!(d!=null&&d.run_id))continue;const m=u.get(h)||{runs:[],updatedAt:""};m.runs.push({id:String(d.run_id),created:String(d.created_at||"")});const _=String(d.updated_at||d.created_at||"");_>m.updatedAt&&(m.updatedAt=_),u.set(h,m)}const l=[...u.entries()].sort((d,h)=>d[1].updatedAt<h[1].updatedAt?1:-1).slice(0,n.max??20);return Promise.all(l.map(async([d,h])=>{var g;const m=h.runs.sort((y,b)=>y.created<b.created?-1:1).map(y=>y.id);let _="";try{const y=await sc(await e(wt(`runs/${encodeURIComponent(m[0])}/input_data`),{signal:n.signal}),"");_=String(((g=y==null?void 0:y.input_data)==null?void 0:g.prompt)||"").trim()}catch{_=""}return{sessionId:d,title:_||"Untitled question",updatedAt:h.updatedAt,runIds:m}}))}async function pL(e,t,n,r){var o;const i=[];for(const u of t.runIds){const[l,d]=await Promise.all([sc(await e(wt(`runs/${encodeURIComponent(u)}/input_data`),{signal:r}),"A past question could not be read"),sc(await e(wt(`runs/${encodeURIComponent(u)}`),{signal:r}),"A past answer could not be read")]),h=String(((o=l==null?void 0:l.input_data)==null?void 0:o.prompt)||"").trim();h&&i.push({id:`u-${u}`,role:"user",content:h,ts:String((d==null?void 0:d.created_at)||"")||void 0});const m=bN(d),_=String((d==null?void 0:d.status)||"").toLowerCase();i.push(m?{id:`a-${u}`,role:"assistant",title:n,content:m,ts:String((d==null?void 0:d.updated_at)||"")||void 0}:{id:`a-${u}`,role:"assistant",title:n,level:"warn",content:_==="completed"?"This answer was empty.":`No answer: the run is ${_||"unknown"}.`})}return i}function gL(e){const[t,n]=p.useState(null);return e.state==="loading"?s.jsx("div",{className:"pc-docs-history__note",role:"status",children:"Loading past conversations…"}):e.state==="error"?s.jsx("div",{className:"pc-docs-history__note pc-docs-history__note--error",role:"alert",children:e.error||"The history could not be read."}):e.items.length?s.jsx("ul",{className:"pc-docs-history","aria-label":"Past conversations",children:e.items.map(r=>s.jsx("li",{className:`pc-docs-history__row${r.sessionId===e.activeSessionId?" is-active":""}`,children:t===r.sessionId?s.jsxs("div",{className:"pc-docs-history__confirm",children:[s.jsx("span",{children:"Archive this conversation? It stays in the gateway; it leaves this list."}),s.jsx("button",{type:"button",className:"pc-docs-history__btn pc-docs-history__btn--danger",onClick:()=>{n(null),e.onArchive(r)},children:"Archive"}),s.jsx("button",{type:"button",className:"pc-docs-history__btn",onClick:()=>n(null),children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"pc-docs-history__open",onClick:()=>e.onOpen(r),title:r.title,children:[s.jsx("span",{className:"pc-docs-history__title",children:r.title}),s.jsxs("span",{className:"pc-docs-history__meta",children:[Vp(r.updatedAt,e.nowMs),r.runIds.length>1?` · ${r.runIds.length} questions`:""]})]}),s.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":`Archive "${r.title}"`,"data-af-tip":`Archive "${r.title}" (kept, hidden)`,onClick:()=>n(r.sessionId),children:s.jsx(qe,{name:"archive",size:16})})]})},r.sessionId))}):s.jsx("div",{className:"pc-docs-history__note",children:"No past conversations yet."})}const yL=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml)$/i;function wL(e){const t=p.useRef(null),[n,r]=p.useState(!1),i=!!e.blockedNotice,o=!!e.busy,u=e.files||[],l=typeof e.onAddFiles=="function"&&!i,d=s.jsxs("div",{className:"pc-docs-assistant__empty",children:[s.jsxs("p",{className:"pc-docs-assistant__empty-text",children:["Ask anything about ",e.source.name,"."]}),e.suggestions&&e.suggestions.length?s.jsx("div",{className:"pc-docs-assistant__suggestions",children:e.suggestions.map(h=>s.jsx("button",{type:"button",className:"pc-docs-assistant__suggestion",disabled:o||i,onClick:()=>{var m;return(m=e.onSuggestion)==null?void 0:m.call(e,h)},children:h},h))}):null]});return s.jsxs("div",{className:`pc-docs-assistant${n?" is-dragging":""}`,onDragOver:h=>{var m;!l||!Dh((m=h.dataTransfer)==null?void 0:m.types)||(h.preventDefault(),r(!0))},onDragLeave:()=>r(!1),onDrop:h=>{var _,g;if(!l)return;h.preventDefault(),r(!1);const m=rx(h.dataTransfer);m.files.length&&((_=e.onAddFiles)==null||_.call(e,m.files)),m.folders.length&&((g=e.onNotice)==null||g.call(e,mN(m.folders)))},children:[s.jsx(nx,{className:"pc-docs-assistant__thread",messages:e.messages,autoScroll:!0,empty:d,messageProps:{showCopy:!0}}),i?s.jsx("div",{className:"pc-docs-assistant__blocked",role:"status",children:e.blockedNotice}):null,e.notice?s.jsx("div",{className:"pc-docs-assistant__notice",role:"status",children:e.notice}):null,s.jsx("div",{className:"pc-docs-assistant__composer",children:s.jsx(sx,{value:e.draft,onChange:e.onDraftChange,onSubmit:e.onSend,placeholder:e.placeholder||`Ask about ${e.source.name}…`,ariaLabel:`Question about ${e.source.name}`,disabled:i,busy:o,rows:1,sendLabel:"Send",busyLabel:"Answering…",onPaste:h=>{var _;if(!l)return;const m=_N(h.clipboardData);m.length&&(h.preventDefault(),(_=e.onAddFiles)==null||_.call(e,m))},leading:u.length?s.jsx("div",{className:"pc-chat-attachments pc-docs-assistant__files",role:"list","aria-label":"Attached files",children:u.map(h=>s.jsxs("span",{role:"listitem",className:"pc-chat-attachment-chip",children:[s.jsx(qe,{name:"paperclip",size:14}),s.jsx("span",{className:"pc-chat-attachment-name",children:h.name}),e.onRemoveFile&&!o?s.jsx("button",{type:"button",className:"pc-docs-assistant__file-remove","aria-label":`Remove ${h.name}`,"data-af-tip":`Remove ${h.name}`,onClick:()=>{var m;return(m=e.onRemoveFile)==null?void 0:m.call(e,h.id)},children:s.jsx(qe,{name:"x",size:12})}):null]},h.id))}):null,actions:s.jsxs(s.Fragment,{children:[l?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"Attach files","data-af-tip":"Attach files to your question",disabled:o,onClick:()=>{var h;return(h=t.current)==null?void 0:h.click()},children:s.jsx(qe,{name:"paperclip",size:16})}),s.jsx("input",{ref:t,type:"file",multiple:!0,hidden:!0,"aria-hidden":"true",tabIndex:-1,onChange:h=>{var _;const m=Array.from(h.currentTarget.files||[]);h.currentTarget.value="",m.length&&((_=e.onAddFiles)==null||_.call(e,m))}})]}):null,o&&e.onStop?s.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"Stop","data-af-tip":"Stop the answer",onClick:e.onStop,children:s.jsx(qe,{name:"stop",size:14})}):null]})})}),s.jsxs("div",{className:"pc-docs-assistant__footer",title:`Answers come from ${e.source.name}'s documentation (llms.txt) through the gateway's docs-qa workflow.`,children:["Grounded on ",e.source.name,"’s documentation (llms.txt) · docs-qa"]})]})}function tp(){return new Date().toISOString()}function vL(e){tf();const{source:t}=e,n=p.useRef(e.fetchGateway);n.current=e.fetchGateway;const r=p.useMemo(()=>e.ask||mL({fetchGateway:(M,A)=>n.current(M,A),source:t}),[e.ask,t.app,t.name]),i=p.useRef(Ey(t.app)),[o,u]=p.useState([]),l=p.useRef(o);l.current=o;const[d,h]=p.useState(""),[m,_]=p.useState([]),[g,y]=p.useState(!1),[b,k]=p.useState(""),x=p.useRef(null),[N,$]=p.useState(!1),[E,S]=p.useState({state:"loading",items:[]});p.useEffect(()=>()=>{var M;return(M=x.current)==null?void 0:M.abort()},[]);const P=p.useCallback(async()=>{S(M=>({...M,state:"loading"}));try{const M=await _L((A,O)=>n.current(A,O),t.app);S({state:"ready",items:M})}catch(M){S({state:"error",items:[],error:String((M==null?void 0:M.message)||M)})}},[t.app]),D=p.useCallback(async M=>{var A;(A=x.current)==null||A.abort(),S(O=>({...O,state:"loading"}));try{const O=await pL((L,V)=>n.current(L,V),M,t.name);i.current=M.sessionId,u(O),k(""),$(!1),S(L=>({...L,state:"ready"}))}catch(O){S(L=>({...L,state:"error",error:String((O==null?void 0:O.message)||O)}))}},[t.name]),R=p.useCallback(async M=>{try{const A=await n.current(wt(`sessions/${encodeURIComponent(M.sessionId)}/archive`),{method:"POST"});if(!A.ok)throw await nf(A,"The conversation could not be archived");i.current===M.sessionId&&(i.current=Ey(t.app),u([])),S(O=>({...O,items:O.items.filter(L=>L.sessionId!==M.sessionId)}))}catch(A){S(O=>({...O,state:"error",error:String((A==null?void 0:A.message)||A)}))}},[t.app]);p.useEffect(()=>{var M;e.connected||(M=x.current)==null||M.abort()},[e.connected]),p.useEffect(()=>()=>{for(const M of m)M.preview&&URL.revokeObjectURL(M.preview)},[]);const I=p.useCallback(M=>{k(""),_(A=>[...A,...M.map(O=>({id:el(),file:O,preview:yL.test(O.type)&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(O):void 0}))])},[]),W=p.useCallback(async M=>{const A=String(M||"").trim();if(!A||g||!e.connected)return;const O=m;h(""),_([]),k("");const L=O.filter(de=>de.preview).map(de=>({kind:"image",src:de.preview,label:de.file.name})),V=O.map(de=>({id:de.id,label:de.file.name,title:de.file.name,disabled:!0})),J={id:`u-${el()}`,role:"user",content:A,ts:tp(),...L.length?{media:L}:{},...V.length?{attachments:V}:{}},U=`a-${el()}`,te=[...l.current,J],z={id:U,role:"assistant",title:t.name,content:"",ts:tp(),live:{callId:U,reasoning:"",label:"answering"}};u([...te,z]),y(!0);const ne=new AbortController;x.current=ne;const se=de=>u([...te,de]);try{const de=await r(A,{signal:ne.signal,sessionId:i.current,files:O.map(be=>be.file),onText:be=>{ne.signal.aborted||se({...z,content:be,live:{callId:U,reasoning:"",label:"streaming"}})},onHistory:be=>k(dL(be))});ne.signal.aborted||se({id:U,role:"assistant",title:t.name,content:de,ts:tp()})}catch(de){const be=ne.signal.aborted;se({id:U,role:"assistant",title:t.name,level:be?"warn":"error",content:be?"Stopped. Nothing more will be shown for this question.":String((de==null?void 0:de.message)||de||"The docs assistant failed."),ts:tp()})}finally{x.current===ne&&(x.current=null),y(!1)}},[r,g,m,e.connected,t.name]),G=()=>{var M;(M=x.current)==null||M.abort(),i.current=Ey(t.app),u([]),_([]),h(""),k("")},K=s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:`pc-docs-assistant__icon-btn${N?" is-active":""}`,"aria-label":"Past conversations","data-af-tip":"Past conversations","aria-pressed":N,disabled:!e.connected||g,onClick:()=>{const M=!N;$(M),M&&P()},children:s.jsx(qe,{name:"history",size:16})}),s.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"New conversation","data-af-tip":"Start a new conversation",disabled:!o.length&&!d&&!m.length&&!N,onClick:()=>{G(),$(!1)},children:s.jsx(qe,{name:"compose",size:16})})]}),H=s.jsxs(s.Fragment,{children:[N?s.jsx("div",{className:"pc-docs-assistant pc-docs-assistant--history",children:s.jsx(gL,{items:E.items,state:E.state,error:E.error,nowMs:Date.now(),activeSessionId:i.current,onOpen:M=>void D(M),onArchive:M=>void R(M)})}):null,s.jsx("div",{hidden:N,style:{display:N?"none":"contents"},children:s.jsx(wL,{source:t,messages:o,draft:d,onDraftChange:h,onSend:()=>void W(d),onStop:()=>{var M;return(M=x.current)==null?void 0:M.abort()},busy:g,blockedNotice:e.connected?void 0:"Connect to the gateway to use the docs assistant.",files:m.map(M=>({id:M.id,name:M.file.name})),onAddFiles:I,onNotice:k,onRemoveFile:M=>_(A=>{const O=A.find(L=>L.id===M);return O!=null&&O.preview&&URL.revokeObjectURL(O.preview),A.filter(L=>L.id!==M)}),notice:b,suggestions:e.suggestions,onSuggestion:M=>void W(M),placeholder:e.placeholder})})]});return{headerActions:K,body:H}}function xL(e){const{headerActions:t,body:n}=vL(e);return s.jsx(H2,{open:e.open,onClose:e.onClose,label:"Docs assistant",title:s.jsxs("span",{className:"pc-docs-assistant__title",children:[s.jsx(qe,{name:"book",size:16}),"Docs assistant"]}),width:e.width||420,topOffset:e.topOffset,manageFocus:e.manageFocus===!0,className:`pc-docs-assistant-drawer${e.className?` ${e.className}`:""}`,headerActions:t,children:n})}const ns=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Cp=e=>Array.isArray(e)?e.map(ns):[],Tn=e=>typeof e=="string"?e:"",vh=e=>Tn(e.runtime_call_id||e.call_uid),Ka=e=>Tn(e.call_id||e.id);function kN(e,t){const n=t.record,r=ns(n.effect);if(r.type!=="tool_calls")return[];const i=ns(n.result),o=Cp(ns(r.payload).tool_calls),u=o.length||n.status!=="waiting"?o:Cp(ns(ns(i.wait).details).tool_calls),l=Cp(i.results),d=u.length?u:l,h=[];return d.forEach((m,_)=>{let g=vh(m)?l.filter(D=>vh(D)===vh(m)):[];!g.length&&Ka(m)&&u.filter(D=>Ka(D)===Ka(m)).length===1&&(g=l.filter(D=>Ka(D)===Ka(m)));const y=u.length?g.length===1?g[0]:u.length===l.length?l[_]:{}:m,b=vh(m)||vh(y)||`${Tn(n.idempotency_key)||Tn(n.step_id)||t.cursor}:${_}`,k=`${t.runId}:${b}`,x=e.get(k),N=Tn(m.name||y.name)||(x==null?void 0:x.name);if(!N)return;const $=n.status==="completed"||n.status==="failed",E=n.status==="failed"||y.success===!1||!!y.error,S=m.arguments??y.arguments??(x==null?void 0:x.arguments),P={...x,id:k,runId:t.runId,name:N,arguments:S,status:$?E?"failed":"completed":n.status==="waiting"?"waiting":"running",...typeof y.success=="boolean"?{success:y.success}:{},...y.output!==void 0||y.result!==void 0?{output:y.output??y.result}:{},...y.error?{error:String(y.error)}:{},...qw(y)?{sandbox:qw(y)}:{},...Ka(m)||Ka(y)?{callId:Ka(m)||Ka(y)}:{},startedAt:(x==null?void 0:x.startedAt)||Tn(n.started_at)||void 0,endedAt:$&&Tn(n.ended_at)||(x==null?void 0:x.endedAt)};x&&["completed","failed"].includes(x.status)&&!$||(e.set(k,P),h.push(P))}),h}function Cd(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function pa(e,t){for(const n of t){const r=e==null?void 0:e[n];if(r==null||r===""||typeof r=="boolean")continue;const i=Number(r);if(Number.isFinite(i)&&i>=0)return Math.trunc(i)}}function jN(e){if(typeof e=="string")try{return ns(JSON.parse(e))}catch{return{}}return ns(e)}function gd(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function bL(e){return pa(e,["reasoning_tokens","thinking_tokens"])??pa(ns(e.completion_tokens_details),["reasoning_tokens"])??pa(ns(e.output_tokens_details),["reasoning_tokens"])}function kL(e){const t=ns(typeof e=="string"&&e.trim().startsWith("{")?jN(e):e);return Tn(t.error_class)}function jL(e){const t=new Map;for(const n of e){const r=n.record;if(ns(r.effect).type!=="emit_event")continue;const i=ns(r.result);if(Tn(i.name)!=="abstract.progress")continue;const o=ns(i.payload);if(Tn(o.kind)!=="llm"||!Tn(o.step_id))continue;const u=`${Tn(o.run_id)||n.runId}:${Tn(o.step_id)}`,l=t.get(u)||{},d=Cd(o.ttft_s);d!==void 0&&(l.ttftS=d),l.provider=l.provider||Tn(o.provider)||void 0,l.model=l.model||Tn(o.model)||void 0,t.set(u,l)}return t}function Ay(e){var k,x,N,$;const t=new Map,n=new Set,r=new Set,i={llmCalls:0,toolCalls:0,changedFiles:[]};let o=1/0,u=-1/0,l=!1,d=0,h=0,m=0;const _=jL(e),g=[],y=new Set;for(const E of e){const S=E.record,P=`${E.runId}:${S.step_id||E.cursor}:${S.status}`;if(n.has(P))continue;n.add(P);for(const ae of[S.started_at,S.ended_at]){const xe=Date.parse(Tn(ae));Number.isFinite(xe)&&(o=Math.min(o,xe),u=Math.max(u,xe))}for(const ae of kN(t,E))ae.status==="waiting"&&y.add(ae.id);if(ns(S.effect).type!=="llm_call"||S.status!=="completed")continue;i.llmCalls+=1;const D=ns(S.result),R=ns(D.output),I=ns(D.usage||D.token_usage||D.tokens||R.usage||R.token_usage||R.tokens),W=pa(I,["input_tokens","prompt_tokens","prompt","input","in"]),G=pa(I,["output_tokens","completion_tokens","completion","output","out"]),K=pa(I,["total_tokens","total"])??(W!==void 0||G!==void 0?(W||0)+(G||0):void 0);K!==void 0&&(W===void 0||G===void 0||W+G!==K)&&(l=!0),W!==void 0&&(i.inputTokens=(i.inputTokens||0)+W),G!==void 0&&(i.outputTokens=(i.outputTokens||0)+G),K!==void 0&&(i.totalTokens=(i.totalTokens||0)+K);const H=Cd(D.gen_time??R.gen_time);H!==void 0&&(i.genTimeMs=(i.genTimeMs||0)+H,i.timedCalls=(i.timedCalls||0)+1);const M=ns(D.metadata||R.metadata),A=ns(M.performance),O=Cd(A.prompt_tokens_per_second),L=Cd(A.generation_tokens_per_second),V=ns(M.prompt_cache),J=Cd(V.cached_tokens),U=Cd(V.fed_tokens);if(O!==void 0||L!==void 0){if(i.measuredSpeedCalls=(i.measuredSpeedCalls||0)+1,O!==void 0&&O>0&&(i.promptTokensPerSecond=(i.promptTokensPerSecond||0)+O,W!==void 0)){const ae=W/O*1e3;i.prefillMs=(i.prefillMs||0)+ae,U!==void 0&&(d+=U,h+=ae)}L!==void 0&&L>0&&(i.generationTokensPerSecond=(i.generationTokensPerSecond||0)+L,G!==void 0&&(i.decodeMs=(i.decodeMs||0)+G/L*1e3))}if(J!==void 0||U!==void 0){i.measuredCacheCalls=(i.measuredCacheCalls||0)+1,i.cachedTokens=(i.cachedTokens||0)+(J||0),i.fedTokens=(i.fedTokens||0)+(U||0);const ae=Tn(V.outcome);if(ae){const xe=i.cacheOutcomes||[];xe.includes(ae)||xe.push(ae),i.cacheOutcomes=xe}}const te=Tn(S.step_id)||void 0,z=te&&_.get(`${E.runId}:${te}`)||{},ne=ns(D.route),se={runId:E.runId};te&&(se.stepId=te),Tn(S.started_at)&&(se.startedAt=Tn(S.started_at));const de=Tn(D.model||R.model)||Tn(ne.model)||z.model,be=Tn(ne.provider)||Tn(ns(M._provider_request).provider)||z.provider||Tn(D.provider);de&&(se.model=de),be&&(se.provider=be),de&&(i.models=gd(i.models,de)),be&&(i.providers=gd(i.providers,be)),(K===void 0||W!==void 0&&G!==void 0&&W+G===K)&&(W!==void 0&&(se.inputTokens=W),G!==void 0&&(se.outputTokens=G)),K!==void 0&&(se.totalTokens=K);const Me=bL(I);Me!==void 0&&(se.reasoningTokens=Me,i.reasoningTokens=(i.reasoningTokens||0)+Me),J!==void 0&&(se.cachedTokens=J),U!==void 0&&(se.fedTokens=U),Tn(V.outcome)&&(se.cacheOutcome=Tn(V.outcome)),Tn(V.backend)&&(se.cacheBackend=Tn(V.backend),i.cacheBackends=gd(i.cacheBackends,se.cacheBackend)),H!==void 0&&(se.genTimeMs=H),O!==void 0&&O>0&&(se.promptTokensPerSecond=O),L!==void 0&&L>0&&(se.generationTokensPerSecond=L),z.ttftS!==void 0?(se.ttftMs=z.ttftS*1e3,se.promptMs=se.ttftMs,se.promptSource="ttft",i.ttftMs=(i.ttftMs||0)+se.ttftMs,i.ttftCalls=(i.ttftCalls||0)+1):se.promptTokensPerSecond!==void 0&&W!==void 0&&(se.promptMs=W/se.promptTokensPerSecond*1e3,se.promptSource="rate"),se.promptMs!==void 0&&(i.promptPhaseMs=(i.promptPhaseMs||0)+se.promptMs,i.promptPhaseCalls=(i.promptPhaseCalls||0)+1,U!==void 0&&se.promptMs>0&&(se.promptNewTokensPerSecond=U/(se.promptMs/1e3),i.promptPhaseNewTokens=(i.promptPhaseNewTokens||0)+U,m+=se.promptMs)),se.ttftMs!==void 0&&H!==void 0&&H>=se.ttftMs?se.generationMs=H-se.ttftMs:se.generationTokensPerSecond!==void 0&&G!==void 0&&(se.generationMs=G/se.generationTokensPerSecond*1e3),se.generationMs!==void 0&&G!==void 0&&(i.generationPhaseMs=(i.generationPhaseMs||0)+se.generationMs,i.generationPhaseTokens=(i.generationPhaseTokens||0)+G);const je=ns(M.speculation);if(Object.keys(je).length){const ae={};Tn(je.mode)&&(ae.mode=Tn(je.mode)),typeof je.used=="boolean"&&(ae.used=je.used),Tn(je.draft_kind)&&(ae.draftKind=Tn(je.draft_kind));const xe=pa(je,["accepted_tokens"]),Ae=pa(je,["drafted_tokens"]),He=pa(je,["rounds"]),mt=pa(je,["num_draft_tokens"]);xe!==void 0&&(ae.acceptedTokens=xe),Ae!==void 0&&(ae.draftedTokens=Ae),xe!==void 0&&Ae&&(ae.acceptanceRate=xe/Ae),He!==void 0&&(ae.rounds=He),mt!==void 0&&(ae.draftLength=mt),se.speculation=ae;const nt=i.speculation||(i.speculation={calls:0,used:0});nt.calls+=1,ae.used&&(nt.used+=1),ae.mode&&(nt.modes=gd(nt.modes,ae.mode)),ae.draftKind&&(nt.draftKinds=gd(nt.draftKinds,ae.draftKind)),xe!==void 0&&Ae!==void 0&&(nt.acceptedTokens=(nt.acceptedTokens||0)+xe,nt.draftedTokens=(nt.draftedTokens||0)+Ae),He!==void 0&&(nt.rounds=(nt.rounds||0)+He),mt!==void 0&&(nt.draftLengths=gd(nt.draftLengths,mt))}g.push(se)}g.length&&(g.every(E=>E.startedAt)&&g.sort((E,S)=>Date.parse(E.startedAt)-Date.parse(S.startedAt)),i.modelCalls=g),m>0&&i.promptPhaseNewTokens!==void 0&&(i.promptPhaseTokensPerSecond=i.promptPhaseNewTokens/(m/1e3)),i.generationPhaseMs&&i.generationPhaseTokens!==void 0&&(i.generationPhaseTokensPerSecond=i.generationPhaseTokens/(i.generationPhaseMs/1e3)),(k=i.speculation)!=null&&k.draftedTokens&&(i.speculation.acceptanceRate=(i.speculation.acceptedTokens||0)/i.speculation.draftedTokens),i.measuredSpeedCalls&&(i.promptTokensPerSecond!==void 0&&(i.promptTokensPerSecond/=i.measuredSpeedCalls),i.generationTokensPerSecond!==void 0&&(i.generationTokensPerSecond/=i.measuredSpeedCalls)),h>0&&(i.prefillNewTokens=d,i.prefillNewTokensPerSecond=d/(h/1e3));const b=new Map;for(const E of t.values()){if(E.status==="waiting"){i.toolsWaiting=(i.toolsWaiting||0)+1;continue}if(E.status==="running"){i.toolsRunning=(i.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(E.status))continue;i.toolCalls+=1;const S=E.status==="failed";S&&(i.toolsFailed=(i.toolsFailed||0)+1);const P=i.toolBreakdown||(i.toolBreakdown={}),D=P[E.name]||(P[E.name]={calls:0,failed:0});if(D.calls+=1,S){D.failed+=1;const K=kL(E.output);K&&((D.errors||(D.errors={}))[K]=(((x=D.errors)==null?void 0:x[K])||0)+1)}const R=Date.parse(Tn(E.startedAt)),I=Date.parse(Tn(E.endedAt));if(Number.isFinite(R)&&Number.isFinite(I)&&I>=R){const K=`${E.runId}|${E.startedAt}|${E.endedAt}`,H=b.get(K)||{ms:I-R,calls:0,names:new Map,waited:!1};H.calls+=1,H.names.set(E.name,(H.names.get(E.name)||0)+1),y.has(E.id)&&(H.waited=!0),b.set(K,H)}if(E.success!==!0||!["write_file","create_file","save_file","edit_file","update_file","replace_in_file","delete_file","remove_file","move_file","rename_file","copy_file"].includes(E.name))continue;const W=jN(E.arguments),G=Tn(W.destination||W.destination_path||W.file_path||W.path||W.filename);G&&r.add(G)}for(const E of b.values()){i.toolBatches=(i.toolBatches||0)+1,i.toolTimeMs=(i.toolTimeMs||0)+E.ms,E.waited&&(i.toolTimeIncludesApproval=!0);const S=[...E.names.keys()].sort();(!i.slowestToolBatch||E.ms>i.slowestToolBatch.ms)&&(i.slowestToolBatch={ms:E.ms,calls:E.calls,tools:S});const P=(N=i.toolBreakdown)==null?void 0:N[S[0]];if(S.length===1&&P)P.ms=(P.ms||0)+E.ms;else for(const D of S){const R=($=i.toolBreakdown)==null?void 0:$[D];R&&(R.sharedBatches=(R.sharedBatches||0)+1)}}return i.changedFiles=[...r],l&&(delete i.inputTokens,delete i.outputTokens),Number.isFinite(o)&&Number.isFinite(u)&&(i.durationMs=Math.max(0,u-o)),{tools:[...t.values()],statistics:i}}function SL(e){const t=ns(ns(e).ledgers);return Object.entries(t).flatMap(([n,r])=>Cp(ns(r).items).map((i,o)=>({runId:n,cursor:Number(i.cursor)||o+1,record:Object.keys(ns(i.record)).length?ns(i.record):i})))}const Xb=e=>`${e} ${e===1?"file":"files"}`;function NL(e){const t=e.filter(i=>i.state==="queued"||i.state==="uploading").length;if(t)return`Wait for ${Xb(t)} to finish uploading.`;const n=e.filter(i=>i.state==="failed"||i.state==="refused");if(!n.length)return null;const r=n.some(i=>i.state==="failed");return n.length===1?`"${n[0].name}" was not attached. ${r?"Retry or remove":"Remove"} it before sending.`:`${Xb(n.length)} were not attached. ${r?"Retry or remove":"Remove"} them before sending.`}const $L=new Set(["blob:","data:","http:","https:"]);function CL(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return $L.has(new URL(t,n).protocol)?t:void 0}catch{return}}function EL(e){const t=typeof e.size=="number"?yN(e.size):"";if(e.state==="queued")return{meta:`Waiting${t?` · ${t}`:""}`,state:"waiting to upload"};if(e.state==="uploading")return{meta:`Uploading${t?` · ${t}`:""}`,state:"uploading"};if(e.state==="attached")return{meta:t,state:"attached"};const n=String(e.error||"").trim()||(e.state==="refused"?"Refused":"Upload failed");return{meta:n,state:`not attached: ${n}`}}function AL(e){const t=Array.isArray(e.items)?e.items:[];return t.length?s.jsx("div",{className:"pc-attachment-chips",role:"list","aria-label":"Attached files",children:t.map(n=>{const r=n.state==="queued"||n.state==="uploading",{meta:i,state:o}=EL(n),u=CL(n.thumbnailUrl);return s.jsxs("div",{role:"listitem",tabIndex:0,className:`pc-attachment-chip is-${n.state}`,"data-state":n.state,"aria-label":`${n.name}, ${o}`,"aria-busy":r||void 0,children:[s.jsx("span",{className:"pc-attachment-chip__icon","aria-hidden":"true",children:u?s.jsx("img",{className:"pc-attachment-chip__thumb",src:u,alt:"",loading:"lazy"}):r?s.jsx("span",{className:"pc-attachment-chip__spinner"}):n.state==="attached"?s.jsx(qe,{name:"paperclip",size:13}):s.jsx(qe,{name:"warning",size:13})}),s.jsxs("span",{className:"pc-attachment-chip__body",children:[s.jsx("span",{className:"pc-attachment-chip__name",title:n.name,children:n.name}),i?s.jsx("span",{className:"pc-attachment-chip__meta",children:i}):null]}),n.state==="failed"&&e.onRetry?s.jsxs("button",{type:"button",className:"pc-attachment-chip__action pc-attachment-chip__retry","data-action":"retry","aria-label":`Retry ${n.name}`,title:"Retry upload",disabled:e.disabled,onClick:()=>{var l;return(l=e.onRetry)==null?void 0:l.call(e,n.id)},children:[s.jsx(qe,{name:"refresh",size:12}),s.jsx("span",{children:"Retry"})]}):null,e.onRemove?s.jsx("button",{type:"button",className:"pc-attachment-chip__action","data-action":"remove","aria-label":`Remove ${n.name}`,title:`Remove ${n.name}`,disabled:e.disabled,onClick:()=>{var l;return(l=e.onRemove)==null?void 0:l.call(e,n.id)},children:s.jsx(qe,{name:"x",size:12})}):null]},n.id)})}):null}function TL(e,t){var n,r;if(e.kind==="ask-user"){if(t.kind==="choice"||t.kind==="free-text")return e.onSubmit(t.answer);if(t.kind==="skip"&&e.onSkip)return e.onSkip();throw new Error("Invalid submission for ask-user interaction")}if(e.kind==="tool-approval"){if(t.kind==="approve")return e.onApprove();if(t.kind==="deny")return e.onDeny();if(t.kind==="approve-all"&&e.onApproveAll)return e.onApproveAll();if(t.kind==="approve-session"&&e.onApproveForSession)return e.onApproveForSession();if(t.kind==="deny-chat"){const i=(n=e.denyOptions)==null?void 0:n.find(o=>o.key===t.key);if(i)return i.onDeny()}if(t.kind==="approve-kind"){const i=(r=e.approveKinds)==null?void 0:r.find(o=>o.kind===t.toolset);if(i)return i.onApprove()}throw new Error("Invalid submission for tool-approval interaction")}if(t.kind==="event")return e.onSend(t.payload);throw new Error("Invalid submission for event-wait interaction")}const zh={deny:"Deny",allowOnce:"Allow once",allowForChat:"Allow for this chat",allowAll:"Allow all enabled tools",allowKindForChat:e=>`Allow all ${e} tools for this chat`,allowForRun:"Allow for this run",localChatPolicyNote:"Allowed for this chat in this browser only — the gateway cannot store chat policies.",localRunPolicyNote:"Allowed until this run ends, in this browser only — the gateway cannot store chat policies.",denyToolForChat:e=>`Always deny ${e} in this chat`,denyKindForChat:e=>`Always deny ${e} tools in this chat`,denyForChatNote:"Always deny applies to every run of this chat, automations and runs that read other people's text included, until the policy is reset; a request shown before it is refused even if approved later.",noScopeNote:"The gateway did not say where this grant applies.",unavailablePolicyNote:e=>`Allow for this chat is unavailable: ${e||"the gateway's capabilities could not be read."} Allow once still works.`,decideLater:"Decide later",submit:"Submit",skip:"Continue without answering",keepWaiting:"Keep waiting",sendEvent:"Send event"};function Zb(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function ML(e){return s.jsxs("div",{className:"pc-workflow-interaction__error",role:"alert",children:[s.jsxs("span",{children:["Could not complete that action: ",e.message]}),s.jsx("button",{type:"button",className:"pc-workflow-interaction__retry",onClick:e.onRetry,disabled:e.disabled,children:"Try again"})]})}const Wo=zh;function RL(e){var H,M,A;const t=e.interaction,n=e.variant==="card",[r,i]=p.useState(""),[o,u]=p.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[l,d]=p.useState(null),[h,m]=p.useState(!1),[_,g]=p.useState(""),[y,b]=p.useState(null),k=`${t.kind}:${t.id}`,x=p.useRef(k),N=p.useRef(!1),$=p.useRef(!1),E=p.useRef(!0),S=p.useRef(0);x.current!==k&&(x.current=k,N.current=!1,$.current=!1,S.current+=1);const P=!!e.disabled||l!==null||h||N.current||$.current,D=async(O,L)=>{var U;if(e.disabled||N.current||$.current)return;const V=k,J=++S.current;N.current=!0,b(null),g(""),d(O);try{const te=await L();if(!E.current||x.current!==V||S.current!==J)return;$.current=!0,m(!0);const z=te&&typeof te=="object"&&typeof te.outcomeNote=="string"?String(te.outcomeNote):"";g(`Response sent. Waiting for the workflow to continue.${z?` ${z}`:""}`)}catch(te){if(!E.current||x.current!==V||S.current!==J)return;b({submission:O,message:Zb(te)}),g("The action failed. You can try again."),(U=e.onError)==null||U.call(e,te)}finally{if(!E.current||x.current!==V||S.current!==J)return;N.current=!1,d(null)}},R=async O=>{var V;if(e.disabled||N.current||$.current)return;const L=k;try{if(await O(),!E.current||x.current!==L)return;b(null),g(t.kind==="tool-approval"?"Left for later. Nothing was sent; the run keeps waiting for this decision.":"Left for later. Nothing was sent; the run keeps waiting for your answer.")}catch(J){if(!E.current||x.current!==L)return;g(`Could not leave this for later: ${Zb(J)}`),(V=e.onError)==null||V.call(e,J)}};p.useEffect(()=>{i(""),u(t.kind==="event-wait"&&t.initialPayload||""),b(null),d(null),m(!1),g("")},[k]),p.useEffect(()=>(E.current=!0,()=>{E.current=!1,S.current+=1,N.current=!1}),[]);const I=()=>{y&&D(y.submission,()=>TL(t,y.submission))},W=t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required"),G=(O,L)=>O?s.jsx("button",{type:"button",className:"pc-workflow-interaction__defer","data-decision":"defer",disabled:P,onClick:()=>void R(O),children:L}):null;let K;if(t.kind==="ask-user")K=s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),(H=t.choices)!=null&&H.length?s.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(O=>s.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice","data-decision":"choice",disabled:P||O.disabled,onClick:()=>void D({kind:"choice",answer:O.id},()=>t.onSubmit(O.id)),children:[s.jsx("span",{children:O.label}),O.description?s.jsx("small",{children:O.description}):null]},O.id))}):null,t.allowFreeText!==!1?s.jsxs("div",{className:"pc-workflow-interaction__entry",children:[s.jsx("textarea",{"aria-label":"Response",value:r,onChange:O=>i(O.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:n?1:2,disabled:P,onKeyDown:O=>{O.key!=="Enter"||O.shiftKey||O.nativeEvent.isComposing||O.keyCode===229||(O.preventDefault(),r.trim()&&D({kind:"free-text",answer:r},()=>t.onSubmit(r)))}},`${k}:text`),s.jsx("button",{type:"button",className:"pc-btn","data-decision":"submit",disabled:P||!r.trim(),onClick:()=>void D({kind:"free-text",answer:r},()=>t.onSubmit(r)),children:(l==null?void 0:l.kind)==="free-text"?"Sending…":t.submitLabel||Wo.submit})]}):null,t.onSkip||t.onDefer?s.jsxs("div",{className:"pc-workflow-interaction__buttons pc-workflow-interaction__buttons--secondary",children:[G(t.onDefer,t.deferLabel||Wo.keepWaiting),t.onSkip?s.jsx("button",{type:"button",className:"pc-workflow-interaction__skip","data-decision":"skip",disabled:P,onClick:()=>void D({kind:"skip"},t.onSkip),children:(l==null?void 0:l.kind)==="skip"?"Continuing…":t.skipLabel||Wo.skip}):null]}):null]});else if(t.kind==="tool-approval"){const O=String(t.disabledReason||"").trim(),L=P||!!O;K=s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsxs("div",{className:"pc-workflow-interaction__prompt",children:["Allow ",s.jsx("strong",{children:t.toolName})," to run?"]}),t.detail?n?s.jsxs("details",{className:"pc-workflow-interaction__review",children:[s.jsx("summary",{children:"Review"}),s.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail})]}):s.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail}):null,s.jsxs("div",{className:"pc-workflow-interaction__buttons",children:[G(t.onDefer,t.deferLabel||Wo.decideLater),s.jsx("button",{type:"button",className:"pc-workflow-interaction__deny","data-decision":"deny",disabled:P,onClick:()=>void D({kind:"deny"},t.onDeny),children:(l==null?void 0:l.kind)==="deny"?"Denying…":t.denyLabel||Wo.deny}),s.jsx("button",{type:"button",className:"pc-btn","data-decision":"approve",disabled:P,onClick:()=>void D({kind:"approve"},t.onApprove),children:(l==null?void 0:l.kind)==="approve"?"Allowing…":t.approveLabel||Wo.allowOnce}),t.onApproveForSession?s.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-session","data-decision":"approve-session",disabled:L,title:O||void 0,onClick:()=>void D({kind:"approve-session"},t.onApproveForSession),children:(l==null?void 0:l.kind)==="approve-session"?"Allowing…":t.approveForSessionLabel||Wo.allowForChat}):null,(t.approveKinds||[]).map(V=>s.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-session pc-workflow-interaction__allow-kind","data-decision":"approve-kind","data-kind":V.kind,disabled:L,title:O||void 0,onClick:()=>void D({kind:"approve-kind",toolset:V.kind},V.onApprove),children:(l==null?void 0:l.kind)==="approve-kind"&&l.toolset===V.kind?"Allowing…":V.label||Wo.allowKindForChat(V.kind)},V.kind)),t.onApproveAll?s.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-all","data-decision":"approve-all",disabled:L,title:O||void 0,onClick:()=>void D({kind:"approve-all"},t.onApproveAll),children:(l==null?void 0:l.kind)==="approve-all"?"Allowing…":t.approveAllLabel||Wo.allowAll}):null]}),t.remember?s.jsxs("label",{className:"pc-workflow-interaction__remember",children:[s.jsx("input",{type:"checkbox",checked:t.remember.checked,disabled:P,onChange:V=>t.remember.onChange(V.target.checked)}),s.jsx("span",{children:t.remember.label})]}):null,t.deniedNote?s.jsx("p",{className:"pc-workflow-interaction__unavailable",role:"note","data-denied-note":"",children:t.deniedNote}):null,(M=t.denyOptions)!=null&&M.length?s.jsxs("details",{className:"pc-workflow-interaction__more","data-more":"",children:[s.jsx("summary",{children:"More"}),s.jsx("p",{className:"pc-workflow-interaction__scope",children:Wo.denyForChatNote}),s.jsx("div",{className:"pc-workflow-interaction__buttons",children:t.denyOptions.map(V=>s.jsx("button",{type:"button",className:"pc-workflow-interaction__deny","data-decision":"deny-chat","data-key":V.key,disabled:P,onClick:()=>void D({kind:"deny-chat",key:V.key},V.onDeny),children:(l==null?void 0:l.kind)==="deny-chat"&&l.key===V.key?"Denying…":V.label},V.key))})]}):null,t.policySummary?s.jsx("p",{className:"pc-workflow-interaction__scope","data-policy-summary":"",children:t.policySummary}):null,t.scopeNote?s.jsx("p",{className:"pc-workflow-interaction__scope-note",role:"note","data-scope-note":"",children:t.scopeNote}):null,t.notCovered?s.jsx("p",{className:"pc-workflow-interaction__unavailable",role:"note","data-not-covered":"",children:t.notCovered}):null,O&&(t.onApproveAll||t.onApproveForSession||(A=t.approveKinds)!=null&&A.length)?s.jsx("p",{className:"pc-workflow-interaction__unavailable",role:"note",children:O}):null,!O&&t.onApproveForSession&&t.approveForSessionDescription?s.jsx("p",{className:"pc-workflow-interaction__scope",children:t.approveForSessionDescription}):null,!O&&t.onApproveAll&&t.approveAllDescription?s.jsx("p",{className:"pc-workflow-interaction__scope",children:t.approveAllDescription}):null]})}else K=s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),s.jsxs("label",{className:"pc-workflow-interaction__entry",children:[s.jsx("span",{children:t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload")}),s.jsx("textarea",{value:o,onChange:O=>u(O.target.value),placeholder:t.payloadPlaceholder||"Enter payload",rows:n?1:2,"aria-label":t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload"),disabled:P},`${k}:payload`)]}),s.jsx("div",{className:"pc-workflow-interaction__buttons",children:s.jsx("button",{type:"button",className:"pc-btn","data-decision":"send-event",disabled:P,onClick:()=>void D({kind:"event",payload:o},()=>t.onSend(o)),children:(l==null?void 0:l.kind)==="event"?"Sending…":t.sendLabel||Wo.sendEvent})})]});return s.jsxs("section",{className:["pc-workflow-interaction",n?"pc-workflow-interaction--card":""].filter(Boolean).join(" "),"data-variant":n?"card":"panel","aria-labelledby":`pc-workflow-interaction-${k}`,children:[s.jsxs("div",{className:"pc-workflow-interaction__heading",children:[s.jsx(qe,{name:t.kind==="tool-approval"?"warning":t.kind==="event-wait"?"history":"info",size:n?14:16}),s.jsxs("div",{children:[s.jsx("h3",{tabIndex:-1,id:`pc-workflow-interaction-${k}`,children:W}),t.description?s.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),K,y?s.jsx(ML,{message:y.message,onRetry:I,disabled:P}):null,s.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:_})]})}function yd(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function LL(e){var Q;tf();const[t,n]=p.useState(!1),[r,i]=p.useState(!1),[o,u]=p.useState(!1),[l,d]=p.useState(null),[h,m]=p.useState(()=>{var _e,le;return((le=(_e=e.steer)==null?void 0:_e.modes)==null?void 0:le[0])||"guide"}),[_,g]=p.useState(null),[y,b]=p.useState("idle"),k=p.useRef(null),x=p.useRef(!0),N=p.useRef(!1),$=p.useRef(!1),E=p.useRef(!1),S=p.useRef(0),P=p.useRef(0),D=p.useRef(0);p.useEffect(()=>(x.current=!0,()=>{var _e;x.current=!1,S.current+=1,P.current+=1,D.current+=1,N.current=!1,$.current=!1,E.current=!1,(_e=k.current)==null||_e.abort(),k.current=null}),[]);const R=!!e.blockedNotice,I=!!e.disabled||R,W=!!e.busy||t,G=t||!!e.busy&&!e.sendWhileBusy,K=e.stopState||null,H=(K==null?void 0:K.phase)==="stopping",M=e.steer&&typeof e.steer.onSteer=="function"?e.steer:null,A=M?(Q=M.modes)!=null&&Q.length?M.modes:["guide"]:[],O=A.includes(h)?h:A[0]||"guide",L=!!M&&!!e.busy,V=Array.isArray(e.attachmentItems)?e.attachmentItems:[];p.useEffect(()=>{g(null)},[!!e.busy]);const J=typeof e.onFiles=="function",U=p.useRef(null),[te,z]=p.useState(null),[ne,se]=p.useState(""),de=p.useRef(e.onFiles);de.current=e.onFiles;const be=p.useRef(I);be.current=I;const Me=async(_e,le)=>{const Se=de.current;if(Se){if(be.current){d({action:"attach",message:"attachments are unavailable right now."});return}if(le.length)d({action:"attach",message:mN(le)});else if(_e.length)d(null);else{d({action:"attach",message:"the drop contained no files."});return}if(_e.length){se(`Attaching ${_e.length} ${_e.length===1?"file":"files"}…`);try{await Se(_e)}catch(pe){x.current&&d({action:"attach",message:yd(pe)})}}}},je=p.useRef(Me);je.current=Me,p.useEffect(()=>{if(!J||typeof window>"u")return;const _e=new DR;let le=0;const Se=ut=>!!(U.current&&ut instanceof Node&&U.current.contains(ut)),pe=()=>{_e.reset(),le&&window.clearInterval(le),le=0,z(null)},dt=()=>{le||(le=window.setInterval(()=>{_e.active(Date.now())||pe()},250))},yt=ut=>{var mn;if(!Dh((mn=ut.dataTransfer)==null?void 0:mn.types))return;_e.enter(Date.now());const Ot=Se(ut.target),Mt=Jb(ut.dataTransfer);z(yn=>yn&&yn.over===Ot&&yn.count===(Mt??yn.count)?yn:{count:Mt??(yn==null?void 0:yn.count)??null,over:Ot}),dt()},_t=ut=>{var Mt;if(!Dh((Mt=ut.dataTransfer)==null?void 0:Mt.types))return;ut.preventDefault(),_e.over(Date.now());const Ot=Se(ut.target);ut.dataTransfer&&(ut.dataTransfer.dropEffect=Ot&&!be.current?"copy":"none"),z(mn=>mn&&mn.over===Ot?mn:{count:(mn==null?void 0:mn.count)??Jb(ut.dataTransfer),over:Ot}),dt()},It=ut=>{var Ot;Dh((Ot=ut.dataTransfer)==null?void 0:Ot.types)&&(_e.leave(Date.now())||pe())},bt=ut=>{var In;if(!Dh((In=ut.dataTransfer)==null?void 0:In.types))return;const Ot=Se(ut.target),Mt=ut.defaultPrevented&&!Ot;if(ut.preventDefault(),pe(),Mt)return;if(!Ot){d({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:mn,folders:yn}=rx(ut.dataTransfer);je.current(mn,yn)},St=ut=>{ut.key==="Escape"&&_e.depth>0&&pe()};return window.addEventListener("dragenter",yt),window.addEventListener("dragover",_t),window.addEventListener("dragleave",It),window.addEventListener("drop",bt),window.addEventListener("dragend",pe),window.addEventListener("blur",pe),window.addEventListener("keydown",St),()=>{window.removeEventListener("dragenter",yt),window.removeEventListener("dragover",_t),window.removeEventListener("dragleave",It),window.removeEventListener("drop",bt),window.removeEventListener("dragend",pe),window.removeEventListener("blur",pe),window.removeEventListener("keydown",St),le&&window.clearInterval(le)}},[J]);const ae=_e=>{if(!J||I)return;const le=_N(_e.clipboardData);le.length&&(_e.preventDefault(),Me(le,[]))},xe=te?s.jsxs("div",{className:["pc-workflow-chat__dropzone",te.over?"is-over":"",I?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[s.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:s.jsx(qe,{name:"paperclip",size:18})}),s.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[s.jsx("strong",{children:I?"Attachments are unavailable right now":Yb(te.count)}),I?null:s.jsx("span",{children:te.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,Ae=te?I?"Attachments are unavailable right now":Yb(te.count):ne,He=async _e=>{if(!M)return;const le=O,Se=++S.current;N.current=!0,d(null),g(null),n(!0);try{const pe=await M.onSteer(_e,le);if(!x.current||S.current!==Se)return;if(!(pe!=null&&pe.accepted)&&!(pe!=null&&pe.duplicate)){d({action:"steer",message:"the gateway did not accept this message (accepted=false)."});return}g({mode:le,...typeof pe.seq=="number"?{seq:pe.seq}:{},duplicate:!!pe.duplicate}),e.onDraftChange("")}catch(pe){x.current&&S.current===Se&&d({action:"steer",message:yd(pe)})}finally{x.current&&S.current===Se&&(N.current=!1,n(!1))}},mt=async()=>{const _e=String(e.draft||"");if(I||N.current||!_e.trim())return;if(L)return void He(_e);if(!e.sendWhileBusy&&e.busy)return;const le=V.length?NL(V):null;if(le){d({action:"send",message:le});return}const Se=++S.current,pe=new AbortController;k.current=pe,N.current=!0,d(null),g(null),n(!0);try{await e.onSend(_e,{signal:pe.signal})}catch(dt){x.current&&S.current===Se&&!pe.signal.aborted&&d({action:"send",message:yd(dt)})}finally{k.current===pe&&(k.current=null),x.current&&S.current===Se&&(N.current=!1,n(!1))}},nt=async()=>{if(I||$.current||!e.onCancel)return;const _e=++P.current;$.current=!0,d(null),i(!0);const Se=k.current||new AbortController;Se.abort(new DOMException("Stopped by the user","AbortError"));try{await e.onCancel(Se.signal)}catch(pe){x.current&&P.current===_e&&d({action:"cancel",message:yd(pe)})}finally{x.current&&P.current===_e&&($.current=!1,i(!1))}},rt=async()=>{if(I||E.current||!e.onAttach)return;const _e=++D.current;E.current=!0,d(null),u(!0);try{await e.onAttach()}catch(le){x.current&&D.current===_e&&d({action:"attach",message:yd(le)})}finally{x.current&&D.current===_e&&(E.current=!1,u(!1))}},ze=()=>{l&&((l.action==="send"||l.action==="steer")&&mt(),l.action==="cancel"&&nt(),l.action==="attach"&&rt())},Ve=e.toolbar||null,ct=_e=>KS((Array.isArray(e.messages)?e.messages:[]).filter(le=>!le.toolActivity&&!le.live&&String(le.content||"").trim()),_e?{heading:_e}:void 0),Qe=async _e=>{if(!I){d(null);try{await _e()}catch(le){x.current&&d({action:"toolbar",message:yd(le)})}}},Dt=async()=>{const _e=await sl(ct());x.current&&(b(_e?"copied":"failed"),typeof window<"u"&&window.setTimeout(()=>x.current&&b("idle"),1200))},$e=Ve?s.jsxs("div",{className:"pc-workflow-chat__toolbar",role:"toolbar","aria-label":"Conversation actions",children:[Ve.onNewSession?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"new",disabled:I,onClick:()=>void Qe(Ve.onNewSession),children:[s.jsx(qe,{name:"plus",size:14}),s.jsx("span",{children:"New chat"})]}):null,Ve.onClear?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"clear",disabled:I,onClick:()=>void Qe(Ve.onClear),children:[s.jsx(qe,{name:"trash",size:14}),s.jsx("span",{children:"Clear"})]}):null,Ve.copyTranscript?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"copy",onClick:()=>void Dt(),children:[s.jsx(qe,{name:y==="copied"?"check":"copy",size:14}),s.jsx("span",{children:y==="copied"?"Copied":y==="failed"?"Copy failed":"Copy"})]}):null,Ve.exportTranscript?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"export",onClick:()=>{const _e=Ve.exportTranscript;JS({filename:_e.filename,text:ct(_e.heading),mime:"text/markdown;charset=utf-8"})},children:[s.jsx(qe,{name:"download",size:14}),s.jsx("span",{children:"Export"})]}):null]}):null,Le=O==="queue"?"Queue":"Steer",ce=_?_.mode==="queue"?`Queued for the next turn${typeof _.seq=="number"?` (seq ${_.seq})`:""}.`:`${_.duplicate?"Already queued":"Queued"}${typeof _.seq=="number"?` (seq ${_.seq})`:""}. ${M!=null&&M.parked?"The run is waiting: your guidance delivers at its next wake (steers do not wake runs).":"Delivers at the run's next loop boundary."}`:"";return s.jsxs("section",{ref:U,className:["pc-workflow-chat",te?"pc-workflow-chat--dragging":"",te!=null&&te.over?"pc-workflow-chat--drag-over":"",e.className].filter(Boolean).join(" "),"aria-label":"Workflow chat","data-stream-replies":e.streamReplies||"gateway_default",children:[e.header||$e?s.jsxs("header",{className:["pc-workflow-chat__header",$e?"pc-workflow-chat__header--toolbar":""].filter(Boolean).join(" "),children:[e.header?s.jsx("div",{className:"pc-workflow-chat__header-main",children:e.header}):null,$e]}):null,s.jsx("div",{className:"pc-workflow-chat__transcript",children:s.jsx(nx,{messages:Array.isArray(e.messages)?e.messages:[],empty:e.emptyState,autoScroll:!0,messageProps:{...e.messageProps,...e.renderMarkdown?{renderMarkdown:e.renderMarkdown}:{}},after:s.jsxs(s.Fragment,{children:[e.interaction?s.jsx(RL,{interaction:e.interaction,disabled:I}):null,R?s.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${R?"blocked":""}`})}),l?s.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[s.jsxs("span",{children:["Could not"," ",l.action==="send"?"send this message":l.action==="steer"?O==="queue"?"queue this message":"steer the run":l.action==="attach"?"attach a file":l.action==="toolbar"?"complete that action":"stop the run",": ",l.message]}),l.action!=="toolbar"?s.jsx("button",{type:"button",onClick:ze,disabled:I,children:"Try again"}):null]}):null,s.jsxs("div",{className:"pc-workflow-chat__composer",children:[s.jsx(sx,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void mt(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:I,busy:L?t:G,sendLabel:L?Le:e.sendLabel,busyLabel:L?O==="queue"?"Queueing…":"Steering…":e.busyLabel,rows:2,leading:e.attachments||V.length?s.jsxs("div",{className:"pc-workflow-chat__attachments",children:[V.length?s.jsx(AL,{items:V,onRemove:e.onRemoveAttachment,onRetry:e.onRetryAttachment,disabled:I}):null,e.attachments]}):null,overlay:xe,onPaste:J?ae:void 0,actions:s.jsxs(s.Fragment,{children:[e.onAttach?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","aria-label":"Attach file","data-af-tip":"Attach a file",disabled:I||o,onClick:()=>void rt(),children:[s.jsx(qe,{name:"paperclip",size:16}),s.jsx("span",{children:o?"Attaching…":"Attach"})]}):null,e.composerExtras,L&&A.length>1?s.jsx("span",{className:"pc-workflow-chat__steer-modes",role:"group","aria-label":"While the run is busy",children:A.map(_e=>s.jsx("button",{type:"button",className:"pc-workflow-chat__steer-mode","data-steer-mode":_e,"aria-pressed":O===_e,disabled:I||t,onClick:()=>m(_e),children:_e==="queue"?"Queue next turn":"Guide this run"},_e))}):null,W&&e.onCancel?s.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:I||r||H,onClick:()=>void nt(),children:[s.jsx(qe,{name:"x",size:14}),s.jsx("span",{children:r||H?"Stopping…":"Stop"})]}):K?s.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${K.phase}`,role:"status","aria-live":"polite",children:K.label}):null]})}),M?s.jsx("div",{className:"pc-workflow-chat__steer-status",role:"status","aria-live":"polite",children:ce}):null,J?s.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:Ae}):null]}),e.footer?s.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}function IL(e){return e.toolApprovalGranted?null:e.interaction}const Ty={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function tn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Lt(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function Bh(e){return Array.isArray(e)?e:[]}function OL(e){const t=tn(e);return!!(t&&(t.code==="revision_conflict"||t.reason_code==="revision_conflict"||t.status===409||t.name==="SessionToolPolicyConflict"))}function vi(e){return Lt(e==null?void 0:e.status).toLowerCase()||"unknown"}function qs(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function Vl(e){const t=tn(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function PL(e){const t=tn(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function My(e){const t=n=>{if(Array.isArray(n))return n.map(t);const r=tn(n);if(!r)return n;const i={};for(const o of Object.keys(r).sort())i[o]=t(r[o]);return i};try{return JSON.stringify(t(e))}catch{return"[unserializable]"}}function Vw(e){if(typeof e=="string")return e.trim();const t=tn(e);if(!t)return"";for(const n of["answer","response","message","text","content","output"]){const r=t[n];if(typeof r=="string"&&r.trim())return r.trim()}return""}function wd(e){const t=Vw(e);if(t)return t;if(!tn(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function Qb(e){if(!e)return"";for(const r of["prompt","request","task","message","query","input"]){const i=Lt(e[r]);if(i)return i}const t=tn(e.context);for(const r of["task","message"]){const i=Lt(t==null?void 0:t[r]);if(i)return i}const n=Bh(t==null?void 0:t.messages);for(let r=n.length-1;r>=0;r-=1){const i=tn(n[r]);if(Lt(i==null?void 0:i.role).toLowerCase()!=="user")continue;const o=Lt(i==null?void 0:i.content);if(o)return o}return""}function SN(e){const t=tn(e.result);return tn(t==null?void 0:t.wait)}function Ry(e){return e?Lt(e.reason)==="subworkflow"||Lt(e.wait_key).startsWith("subworkflow:"):!1}function e0(e,t){return!!(e&&e.runId===t.runId&&Lt(e.wait.wait_key)===Lt(t.wait.wait_key))}function Gw(e){return tn(e.effect)||{}}function DL(e,t){return Lt(e.run_id)||t}function t0(e){return Lt(e.ended_at)||Lt(e.started_at)||void 0}function n0(e){const t=new Set,n=h=>{const m=Lt(h);m&&t.add(m)},r=tn(e.result);n(r==null?void 0:r.sub_run_id),n(r==null?void 0:r.subRunId),n(r==null?void 0:r.child_run_id);const i=Gw(e),o=tn(i.payload);Lt(i.type)==="start_subworkflow"&&(n(o==null?void 0:o.sub_run_id),n(o==null?void 0:o.subRunId),n(o==null?void 0:o.child_run_id));const u=SN(e),l=tn(u==null?void 0:u.details);n(l==null?void 0:l.sub_run_id),n(l==null?void 0:l.subRunId),n(l==null?void 0:l.child_run_id);const d=Lt(u==null?void 0:u.wait_key);return d.startsWith("subworkflow:")&&n(d.slice(12)),[...t]}class FL{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...Ty},this.subscribers=new Set,this.controller=null,this.generation=0,this.rootRunId="",this.cursors=new Map,this.seenRecords=new Set,this.seenMessages=new Set,this.watchedRuns=new Set,this.childCatchUpAttempts=new Map,this.runStates=new Map,this.historicalRuns=new Map,this.historicalRunFailures=new Map,this.commandIds=new Map,this.toolActivities=new Map,this.historicalEvidence=new Map,this.approvedWaits=new Set,this.grantedToolWaits=new Set,this.resolvedWaits=new Set,this.approvalEpoch=0,this.toolApprovalPolicy=null,this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps=new Set,this.forcedStop=null,this.liveReplies=new Map,this.closedLiveCalls=new Set,this.shownLiveCalls=new Set,this.liveDirty=new Set,this.liveRenderTimer=null,this.lastLiveRender=-1/0,this.sessionToolPolicy=null,this.sessionPolicyUnavailableReason="",this.sessionPolicyState=null,this.sessionPolicyClamped=[],this.toolPolicyByCall=new Map;const r=n.liveRenderIntervalMs??60;if(typeof r!="number"||!Number.isFinite(r)||r<0)throw new Error(`liveRenderIntervalMs must be a non-negative number of milliseconds, got ${JSON.stringify(n.liveRenderIntervalMs)}`);this.liveRenderIntervalMs=r,this.sessionToolPolicy=n.sessionToolPolicy||null,this.sessionToolPolicy||(this.sessionPolicyUnavailableReason=Lt(n.sessionToolPolicyUnavailableReason)),this.snapshot=this.withSessionPolicy({...Ty})}sessionPolicyMode(){var t;return((t=this.sessionToolPolicy)==null?void 0:t.supported)===!0?"gateway":!this.sessionToolPolicy&&this.sessionPolicyUnavailableReason?"unavailable":"local-fallback"}sessionPolicyStatus(){const t=this.sessionPolicyMode();return{mode:t,...t==="unavailable"?{reason:this.sessionPolicyUnavailableReason}:{},clamped:this.sessionPolicyClamped,policy:this.sessionPolicyState}}setSessionToolPolicyClient(t,n={}){const r=t?"":Lt(n.reason);if(t===this.sessionToolPolicy&&r===this.sessionPolicyUnavailableReason)return;const i=!!(t&&this.sessionToolPolicy&&t.sessionId===this.sessionToolPolicy.sessionId);this.sessionToolPolicy=t,this.sessionPolicyUnavailableReason=r,i||(this.sessionPolicyState=null,this.sessionPolicyClamped=[]),this.set({...this.snapshot})}gatewayPolicy(){const t=this.sessionToolPolicy;if(this.sessionPolicyMode()==="unavailable")throw new Error(`${this.sessionPolicyUnavailableReason} Allow once still works.`);if(!t||t.supported!==!0)throw new Error("This gateway cannot store chat tool policies (session_tool_policy is not supported).");return t}adoptSessionPolicy(t){var n,r;this.sessionPolicyState=t,this.sessionPolicyClamped=Array.isArray(t==null?void 0:t.clamped)?t.clamped.filter(i=>i&&typeof i=="object"):[],this.set({...this.snapshot}),(r=(n=this.options).onSessionPolicy)==null||r.call(n,t,this.sessionPolicyClamped)}async loadSessionPolicy(){const t=await this.gatewayPolicy().get();return this.adoptSessionPolicy(t),t}requireRootSession(t){var r,i;const n=Lt((r=this.snapshot.run)==null?void 0:r.session_id)||Lt((i=this.runStates.get(this.rootRunId))==null?void 0:i.session_id);if(!n)throw new Error("This chat's session is not known yet: the policy is written to the root run's session.");if(n!==t.sessionId)throw new Error(`The tool policy client is bound to session ${t.sessionId}, but this chat's root run belongs to session ${n}: the policy is written to the root run's session.`)}async currentRevision(t){var i;if(typeof((i=this.sessionPolicyState)==null?void 0:i.revision)=="number")return this.sessionPolicyState.revision;const n=await this.loadSessionPolicy();if(typeof(n==null?void 0:n.revision)=="number")return n.revision;const r=t.revision;return typeof r=="number"?r:void 0}async policyWriteError(t){if(OL(t))return await this.loadSessionPolicy().catch(()=>null),new Error("Someone changed this chat's policy; re-read it before deciding again (it was refreshed).");const n=t instanceof Error?t.message:String(t);return new Error(`This chat's policy was not changed: ${n}`)}requireTarget(t){const n=this.requireInteraction();if(qs(this.snapshot.status))throw new Error("This run has already ended.");if(n.runId!==t.runId||Lt(n.wait.wait_key)!==t.waitKey||t.stepId!==void 0&&n.stepId!==t.stepId)throw new Error("This approval request has changed. Review the current request before deciding.");if(!this.isToolApproval(n))throw new Error("This is not a tool approval request.");return n}async writeThenAnswer(t,n,r,i=[]){this.requireTarget(t);const o=this.gatewayPolicy();this.requireRootSession(o);const u=[...new Set(i.map(h=>Lt(h)).filter(Boolean))];let l={};if(n.deny){const h=await this.currentRevision(o);if(typeof h!="number")throw new Error("This chat's policy was not changed: the gateway did not return a policy revision to guard the deny with.");l={if_revision:h}}let d;try{d=await o.merge({...n,...u.length?{ask:u}:{},...l,client:n.client||"panel-chat"})}catch(h){throw await this.policyWriteError(h)}this.sessionToolPolicy===o&&this.adoptSessionPolicy(d);try{await this.approve(r,t)}catch(h){const m=h instanceof Error?h.message:String(h);throw new Error(`This chat's tool policy was saved, but this request was not answered: ${m} The policy does not answer requests that were already waiting.`)}return d}async approveAllForSession(t,n={}){const r=this.sessionPolicyMode();if(r==="unavailable")throw new Error(`${this.sessionPolicyUnavailableReason} Allow once still works.`);return r!=="gateway"?(await this.allowAllToolsForRun(t),null):this.writeThenAnswer(t,{approve:{all:!0,...typeof n.maxRiskRank=="number"?{max_risk_rank:n.maxRiskRank}:{}}},!0,n.ask)}approveKindForSession(t,n,r={}){return this.writeThenAnswer(t,{approve:{kinds:[n]}},!0,r.ask)}denyKindForSession(t,n,r={}){return this.writeThenAnswer(t,{deny:{kinds:[n]}},!1,r.ask)}denyToolForSession(t,n,r={}){return this.writeThenAnswer(t,{deny:{tools:[n]}},!1,r.ask)}async resetSessionPolicy(){if(this.sessionPolicyMode()==="unavailable")throw new Error(`${this.sessionPolicyUnavailableReason}`);if(this.sessionPolicyMode()!=="gateway"){this.revokeToolApproval();return}const t=this.gatewayPolicy();this.requireRootSession(t);const n=await this.currentRevision(t);if(typeof n!="number")throw new Error("This chat's policy was not reset: the gateway did not return a policy revision to guard the reset with.");try{await t.reset(n)}catch(r){throw await this.policyWriteError(r)}this.adoptSessionPolicy(null)}withSessionPolicy(t){const n=this.sessionPolicyMode(),{sessionPolicyReason:r,...i}=t;return{...i,sessionPolicyMode:n,...n==="unavailable"?{sessionPolicyReason:this.sessionPolicyUnavailableReason}:{},sessionPolicy:this.sessionPolicyState,sessionPolicyClamped:this.sessionPolicyClamped}}subscribe(t){return this.subscribers.add(t),()=>this.subscribers.delete(t)}getSnapshot(){return this.snapshot}reset(){var t;this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.approvalEpoch+=1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps.clear(),this.forcedStop=null,this.generation+=1,(t=this.controller)==null||t.abort(),this.controller=null,this.rootRunId="",this.cursors.clear(),this.seenRecords.clear(),this.seenMessages.clear(),this.watchedRuns.clear(),this.childCatchUpAttempts.clear(),this.runStates.clear(),this.historicalRuns.clear(),this.historicalRunFailures.clear(),this.commandIds.clear(),this.toolActivities.clear(),this.toolPolicyByCall.clear(),this.historicalEvidence.clear(),this.approvedWaits.clear(),this.grantedToolWaits.clear(),this.resolvedWaits.clear(),this.liveReplies.clear(),this.closedLiveCalls.clear(),this.shownLiveCalls.clear(),this.liveDirty.clear(),this.lastLiveRender=-1/0,this.liveRenderTimer&&(clearTimeout(this.liveRenderTimer),this.liveRenderTimer=null),this.set({...Ty})}dispose(){this.reset(),this.subscribers.clear()}async load(t){const n=Lt(t);if(this.reset(),!n)return;const r=++this.generation,i=new AbortController;this.controller=i,this.rootRunId=n,this.set({...this.snapshot,loading:!0,status:"loading",error:null,connection:"connecting"});try{const[o,u]=await Promise.all([this.transport.getRun(n,i.signal),this.transport.getHistory(n,i.signal)]);if(!this.live(r))return;const l=tn(o),d=tn(l==null?void 0:l.waiting),h=vi(l);if(await this.ingestHistory(u,n,r),!this.live(r))return;if(this.set({...this.snapshot,run:l,status:h,loading:!1,...d&&!qs(h)?{interaction:this.interactionWith({runId:n,wait:d})}:{}}),l&&this.updateRunState(n,l),d)for(const m of n0({result:{wait:d}}))m!==n&&this.catchUpAndWatch(m,r);await this.catchUpAndWatch(n,r),this.pollRootLifecycle(n,r)}catch(o){!i.signal.aborted&&this.live(r)&&this.fail(o)}}async sendCommand(t,n={}){var m,_;t==="cancel"&&(this.toolApprovalStopped=!0,this.revokeToolApproval(),this.stopRequested=!0,this.recomputeStop());const r=Lt(n.wait_key),i=t==="resume"?r?this.interactionRunId()||this.rootRunId:this.rootRunId:t==="emit_event"?this.interactionRunId()||this.rootRunId:this.rootRunId;if(!i)throw new Error("No workflow run is loaded");const o=t==="resume"&&r&&((m=this.snapshot.interaction)==null?void 0:m.stepId)||"",u=`${i}\0${t}\0${o}\0${My(n)}`;let l=this.commandIds.get(u);l||(l=this.newCommandId(),this.commandIds.set(u,l));const d=this.generation,h=(_=this.controller)==null?void 0:_.signal;try{const g=await this.transport.submitCommand({command_id:l,run_id:i,type:t,payload:n,...this.options.clientId?{client_id:this.options.clientId}:{}},h);if(!this.live(d))return g;const y=tn(g);if(y&&y.accepted===!1)throw t==="cancel"&&(this.stopRequested=!1,this.recomputeStop()),new Error(Lt(y.detail)||"Gateway did not accept the command");return this.commandIds.delete(u),i===this.rootRunId&&["pause","resume","cancel"].includes(t)&&this.refreshRunState(i,d),g}catch(g){throw this.live(d)&&this.fail(g,!1),g}}resume(t,n){const r=this.requireInteraction();if(n&&(r.runId!==n.runId||Lt(r.wait.wait_key)!==n.waitKey||n.stepId!==void 0&&r.stepId!==n.stepId))throw new Error("This question has changed. Review the current question before answering.");return this.sendCommand("resume",{wait_key:Lt(r.wait.wait_key),payload:{response:t}})}approve(t,n){const r=this.requireInteraction();if(qs(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(r.runId!==n.runId||Lt(r.wait.wait_key)!==n.waitKey||n.stepId!==void 0&&r.stepId!==n.stepId))throw new Error("This approval request has changed. Review the current request before deciding.");if(t&&this.toolApprovalPolicy&&!this.toolCallsMatch(r,this.toolApprovalPolicy.enabledTools))throw new Error("This request includes an unavailable or unselected tool. It cannot be authorized. Deny this request or stop the run and change Tools settings.");const i=this.generation;return this.sendCommand("resume",{wait_key:Lt(r.wait.wait_key),payload:{approved:!!t}}).then(o=>{if(!this.live(i))return o;const u=this.occurrenceKey(r);return this.approvedWaits.add(u),t&&this.isToolApproval(r)&&!this.grantedToolWaits.has(u)&&(this.grantedToolWaits.add(u),this.set({...this.snapshot})),o})}async approveWithPolicyChange(t,n){const r=this.generation,i=this.approvalEpoch;if(!this.isToolApproval(this.requireInteraction()))throw new Error("This is not a tool approval request.");await this.approve(!0,t),!(!this.live(r)||i!==this.approvalEpoch||this.toolApprovalStopped||qs(this.snapshot.status))&&n()}async allowAllToolsForRun(t){const n=this.generation,r=this.approvalEpoch,i=this.requireInteraction();if(!this.isToolApproval(i))throw new Error("This is not a tool approval request.");await this.approve(!0,t),!(!this.live(n)||r!==this.approvalEpoch||qs(this.snapshot.status))&&(this.approvedWaits.add(`${t.runId}:${t.waitKey}${i.stepId?`:${i.stepId}`:""}`),this.set({...this.snapshot,autoApproveTools:!0}))}revokeToolApproval(){this.approvalEpoch+=1,this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1})}setToolApprovalPolicy(t){My(t)!==My(this.toolApprovalPolicy)&&(this.approvalEpoch+=1,this.toolApprovalSuspended=!1,this.toolApprovalPolicy=t?{enabledTools:[...t.enabledTools],autoApproveTools:[...t.autoApproveTools]}:null,this.set({...this.snapshot}))}occurrenceKey(t){return`${t.runId}:${Lt(t.wait.wait_key)}${t.stepId?`:${t.stepId}`:""}`}interactionWith(t){const n=this.snapshot.interaction;return n&&Ry(t.wait)&&!Ry(n.wait)?n:n&&e0(n,t)&&t.stepId===void 0&&n.stepId!==void 0?{...t,stepId:n.stepId}:t}adoptDurableWait(t,n){const r=tn(n.waiting);if(!r||vi(n)!=="waiting"||Ry(r)||qs(this.snapshot.status)||this.resolvedWaits.has(`${t}:${Lt(r.wait_key)}`))return;const i=this.interactionWith({runId:t,wait:r}),o=this.snapshot.interaction;o&&e0(o,i)&&o.stepId===i.stepId||this.set({...this.snapshot,interaction:i})}coveredByStandingPermission(t,n){var r;return t.loading||this.toolApprovalStopped||this.toolApprovalSuspended||!this.toolApprovalPolicy&&!t.autoApproveTools||qs(t.status)||((r=t.run)==null?void 0:r.paused)===!0||t.status==="paused"||!n||!this.isToolApproval(n)||this.toolApprovalPolicy&&(!this.toolCallsMatch(n,this.toolApprovalPolicy.enabledTools)||!this.toolCallsMatch(n,this.toolApprovalPolicy.autoApproveTools))?!1:!!Lt(n.wait.wait_key)}present(t){const n=t.interaction,r=n?this.occurrenceKey(n):"",i=!!(n&&this.isToolApproval(n)&&(this.grantedToolWaits.has(r)||!this.approvedWaits.has(r)&&this.coveredByStandingPermission({...t,loading:!1},n)));if(!i&&!this.snapshot.toolApprovalGranted&&!t.toolApprovalGranted)return t.toolApprovalGranted===!1?t:{...t,toolApprovalGranted:!1};let o=!1;const u=t.messages.map(l=>{var m;const d=l.toolActivity;if(!d||((m=this.toolActivities.get(d.id))==null?void 0:m.status)!=="waiting")return l;const h=i&&d.runId===(n==null?void 0:n.runId)?"running":"waiting";return d.status===h?l:(o=!0,this.toolMessage({...d,status:h}))});return{...t,toolApprovalGranted:i,...o?{messages:u}:{}}}toolCallsMatch(t,n){var i;const r=Bh((i=tn(t.wait.details))==null?void 0:i.tool_calls);return r.length>0&&r.every(o=>{var l;const u=Lt((l=tn(o))==null?void 0:l.name);return!!u&&n.includes(u)})}isToolApproval(t){const n=tn(t.wait.details);return(n==null?void 0:n.mode)==="approval_required"||(n==null?void 0:n.kind)==="tool_approval"}autoApproveCurrentWait(){const t=this.snapshot.interaction;if(!this.coveredByStandingPermission(this.snapshot,t))return;const n={runId:t.runId,waitKey:Lt(t.wait.wait_key),stepId:t.stepId},r=this.occurrenceKey(t);if(this.approvedWaits.has(r))return;this.approvedWaits.add(r),this.grantedToolWaits.add(r);const i=this.generation,o=this.approvalEpoch;this.approve(!0,n).catch(u=>{if(this.live(i)){if(this.grantedToolWaits.delete(r),o!==this.approvalEpoch){this.set({...this.snapshot});return}this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1}),this.fail(u,!1)}})}emitEvent(t){return this.sendCommand("emit_event",t)}cancel(){return this.sendCommand("cancel",{})}requireInteraction(){if(!this.snapshot.interaction)throw new Error("This workflow is not waiting for input");if(!Lt(this.snapshot.interaction.wait.wait_key))throw new Error("The workflow wait has no wait_key");return this.snapshot.interaction}interactionRunId(){var t;return((t=this.snapshot.interaction)==null?void 0:t.runId)||""}live(t){var n;return t===this.generation&&!((n=this.controller)!=null&&n.signal.aborted)}set(t){this.snapshot=this.present(this.withSessionPolicy(t));for(const n of this.subscribers)n();this.autoApproveCurrentWait()}async catchUpAndWatch(t,n){var r;if(!(!this.live(n)||this.watchedRuns.has(t))){this.watchedRuns.add(t);try{if(t!==this.rootRunId)try{const i=tn(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));if(!this.live(n))return;i&&this.updateRunState(t,i)}catch(i){if(!this.live(n))return;if(Vl(i))throw i;this.fail(i,!1)}if(await this.catchUp(t,n),!this.live(n)||qs(vi(this.runStates.get(t)||null)))return;this.childCatchUpAttempts.delete(t),this.watch(t,n)}catch(i){if(!this.live(n))return;if(this.watchedRuns.delete(t),t===this.rootRunId)throw i;if(Vl(i)){this.fail(i);return}const o=(this.childCatchUpAttempts.get(t)||0)+1;if(this.childCatchUpAttempts.set(t,o),this.fail(i,!1),o>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(o-1))),this.live(n)&&this.catchUpAndWatch(t,n)}}}async catchUp(t,n){var r;for(let i=0;i<100&&this.live(n);i+=1){const o=this.cursors.get(t)||0,u=await this.transport.getLedger(t,o,(r=this.controller)==null?void 0:r.signal);if(!this.live(n))return;const l=tn(u),d=Array.isArray(u)?u:Bh(l==null?void 0:l.items);for(const m of d)this.ingestItem(t,m);const h=Number(l==null?void 0:l.next_after);if(!d.length||!Number.isFinite(h)||h<=o)break;this.cursors.set(t,h)}}async watch(t,n){try{await this.followStream(t,n)}finally{this.live(n)&&this.closeLiveRepliesVia(t)}}async followStream(t,n){var i;let r=0;for(;this.live(n)&&!qs(vi(this.runStates.get(t)||null));){const o=this.cursors.get(t)||0;this.set({...this.snapshot,connection:r?"reconnecting":"connecting"});try{let u=!1;const l=()=>{!this.live(n)||u||(u=!0,this.set({...this.snapshot,connection:"connected",error:null}))};if(this.dropLiveRepliesVia(t),await this.transport.streamLedger(t,o,h=>{this.live(n)&&(l(),this.ingestItem(t,h))},this.controller.signal,l,h=>{this.live(n)&&(l(),this.ingestDelta(t,h))}),!this.live(n)||(await this.catchUp(t,n),!this.live(n)))return;const d=tn(await this.transport.getRun(t,(i=this.controller)==null?void 0:i.signal));if(!this.live(n))return;d&&this.updateRunState(t,d),r+=1}catch(u){if(!this.live(n))return;if(r+=1,this.fail(u,!1),Vl(u)){this.set({...this.snapshot,connection:"disconnected"});return}}if(r>=5||!this.live(n))break;await this.waitForRetry(Math.min(2e3,150*2**(r-1)))}if(this.live(n)){if(qs(vi(this.runStates.get(t)||null))){this.set({...this.snapshot,connection:"disconnected"});return}this.set({...this.snapshot,connection:"disconnected",error:this.snapshot.error||"Ledger stream reconnect limit reached. Reconnect the workflow to continue."})}}async ingestHistory(t,n,r){const i=tn(t);if(!i)return;const o=tn(i.session),u=Bh(o==null?void 0:o.turns).map(tn).filter(h=>!!h);if(await this.hydrateHistoricalSessionRuns(u,n,r),!this.live(r))return;for(const h of u){const m=Lt(h==null?void 0:h.run_id)||n;this.ingestSessionTurn(h,n,m!==n&&this.historicalRuns.get(m)||null)}const l=`turn:${n}:user`;if(!this.seenMessages.has(l)){const h=Qb(tn(i.input_data));h&&this.addMessage({id:l,role:"user",content:h})}const d=tn(i.ledgers);if(d)for(const[h,m]of Object.entries(d)){const _=tn(m);for(const g of Bh(_==null?void 0:_.items))this.ingestItem(h,g)}}ingestSessionTurn(t,n,r){if(!t)return;const i=Lt(t.run_id)||n,o=tn(t.input_data)||tn(t.input)||{},u=Lt(t.prompt)||Qb(o);u&&this.addMessage({id:`turn:${i}:user`,role:"user",content:u,ts:Lt(t.created_at)||void 0});const l=this.historicalRunFailures.get(i);if(l){const _=Lt(t.answer)||Vw(t.output),g=l.missing?"is unavailable because the run no longer exists":"could not be restored",y=_?` Saved reply (not verified as the final result): ${_}`:"";this.addMessage({id:`history:${i}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${g}.${y}`});return}const h=(r&&qs(vi(r))?wd(r.output):"")||(r?Lt(t.answer)||Vw(t.output):""),m=this.historicalEvidence.get(i);for(const _ of(m==null?void 0:m.tools)||[])this.upsertTool(_);h&&this.addRunAssistantMessage(i,{id:`final:${i}`,role:"assistant",content:h,runId:i,statistics:m==null?void 0:m.statistics,ts:Lt(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,r){const i=[...new Set(t.map(d=>Lt(d.run_id)).filter(d=>d&&d!==n&&!this.historicalRuns.has(d)&&!this.historicalRunFailures.has(d)))];if(!i.length||!this.live(r))return;let o=0,u=!1;const l=async()=>{var d,h,m;for(;!u&&this.live(r);){const _=i[o++];if(!_)return;try{const g=tn(await this.transport.getRun(_,(d=this.controller)==null?void 0:d.signal));if(!this.live(r))return;if(g){this.historicalRuns.set(_,g);try{const y=await this.transport.getHistory(_,(h=this.controller)==null?void 0:h.signal);if(!this.live(r))return;this.historicalEvidence.set(_,Ay(SL(y)))}catch(y){if(!this.live(r))return;if(Vl(y))throw y;this.fail(new Error(`Earlier turn activity could not be restored: ${y instanceof Error?y.message:String(y)}`),!1)}}else this.historicalRuns.set(_,null),this.historicalRunFailures.set(_,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(g){if(!this.live(r))return;const y=PL(g)===404;this.historicalRuns.set(_,null),this.historicalRunFailures.set(_,{missing:y,detail:g instanceof Error?g.message:Lt((m=tn(g))==null?void 0:m.detail)||"request failed"}),Vl(g)&&(u=!0,this.fail(g))}}};if(await Promise.all(Array.from({length:Math.min(4,i.length)},()=>l())),u&&this.live(r))for(const d of i)!this.historicalRuns.has(d)&&!this.historicalRunFailures.has(d)&&(this.historicalRuns.set(d,null),this.historicalRunFailures.set(d,{missing:!1,detail:"authorization expired before this historical run could be restored"}))}ingestItem(t,n){const r=tn(n),i=tn(r==null?void 0:r.record)||r;if(!i)return;const o=DL(i,t),u=Number(r==null?void 0:r.cursor),l=Number.isFinite(u)&&u>0?u:(this.cursors.get(o)||0)+1,d=`${o}:${l}`;if(!this.seenRecords.has(d)){if(this.seenRecords.add(d),this.cursors.set(o,Math.max(this.cursors.get(o)||0,l)),this.set({...this.snapshot,records:[...this.snapshot.records,{cursor:l,record:i,runId:o}]}),this.foldRecord(o,i,d),this.snapshot.messages.some(h=>h.id===`final:${this.rootRunId}`)){const h=Ay(this.snapshot.records).statistics;this.set({...this.snapshot,messages:this.snapshot.messages.map(m=>m.id===`final:${this.rootRunId}`?{...m,statistics:h}:m)})}for(const h of n0(i))h!==o&&this.catchUpAndWatch(h,this.generation)}}foldRecord(t,n,r){var m,_,g;const i=Gw(n),o=Lt(i.type).toLowerCase(),u=tn(n.result),l=Lt(n.status).toLowerCase(),d=t0(n);if(this.foldStopEvidence(t,n,o,l),["llm_call","tool_calls"].includes(o)&&["started","running"].includes(l)){const y=Date.parse(d||"");(!Number.isFinite(y)||y>=this.displayStatusAt)&&(Number.isFinite(y)&&(this.displayStatusAt=y),this.snapshot.displayStatus&&this.set({...this.snapshot,displayStatus:""}))}if(o==="answer_user"&&l==="completed"){const y=wd(u)||wd(tn(i.payload));y&&this.addRunAssistantMessage(t,{id:`answer:${t}:${r}`,role:"assistant",content:y,ts:d})}if(o==="emit_event"&&l==="completed"){const y=tn(i.payload)||{},b=tn(u),k=Lt(y.name)||Lt(b==null?void 0:b.name),x=y.payload!==void 0?y.payload:b==null?void 0:b.payload;if(["abstract.message","abstractcode.message"].includes(k)){const N=wd(x);if(N){const $=Lt((m=tn(x))==null?void 0:m.level).toLowerCase(),E=$==="error"?"error":["warn","warning"].includes($)?"warn":"info";this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Workflow",content:N,level:E,ts:d})}}if(["abstract.status","abstractcode.status"].includes(k)){const N=tn(x),$=N?N.status??N.text??N.value:x,E=Date.parse(d||"");!qs(this.snapshot.status)&&typeof $=="string"&&(!Number.isFinite(E)||E>=this.displayStatusAt)&&(Number.isFinite(E)&&(this.displayStatusAt=E),this.set({...this.snapshot,displayStatus:$.trim()}))}if(k==="abstract.tool_policy_decision"){const N=vR(tn(x));if(N){this.addMessage({id:`policy:${t}:${r}`,role:"system",kind:"tool_policy_decision",title:"Tool policy",content:Hw(N.provenance),ts:d});for(const $ of N.calls){const E={...N.provenance,...$.matched?{matched:$.matched}:{}};this.toolPolicyByCall.set(`${t}:${$.callId}`,E);for(const S of this.toolActivities.values())S.runId===t&&S.callId===$.callId&&this.upsertTool(S)}}}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(k)){const N=wd(x);N&&this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Tool activity",content:N,ts:d})}}const h=SN(n);if(l==="waiting"&&h&&!qs(this.snapshot.status)&&!qs(vi(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${Lt(h.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:h,...Lt(n.step_id)?{stepId:Lt(n.step_id)}:{}})})),o==="tool_calls")for(const y of kN(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(y);if(o==="resume"&&(u==null?void 0:u.resumed)===!0){const y=Lt((_=tn(i.payload))==null?void 0:_.wait_key);y&&this.resolvedWaits.add(`${t}:${y}`),((g=this.snapshot.interaction)==null?void 0:g.runId)===t&&(this.set({...this.snapshot,interaction:null}),this.refreshRunState(t,this.generation))}}foldStopEvidence(t,n,r,i){let o=!1;if(r==="llm_call"){const u=Lt(n.step_id);if(u){const l=`${t}:${u}`;i==="started"?(this.openLlmSteps.add(l),o=!0):["completed","failed","cancelled","waiting"].includes(i)&&(o=this.openLlmSteps.delete(l)||o),["completed","failed","cancelled"].includes(i)&&this.closeLiveReply(l)}}if(r==="emit_event"&&i==="completed"){const u=tn(Gw(n).payload)||{},l=tn(n.result),d=Lt(u.name)||Lt(l==null?void 0:l.name),h=tn(u.payload!==void 0?u.payload:l==null?void 0:l.payload);d==="abstract.status"&&Lt(h==null?void 0:h.killed_by)==="kill_switch"&&(this.forcedStop=h,o=!0)}o&&this.recomputeStop()}recomputeStop(){let t=null;this.forcedStop?t={phase:"forced",label:Lt(this.forcedStop.text)||"Stop forced: inference killed",record:this.forcedStop}:this.stopRequested&&(t=this.snapshot.status==="cancelled"&&this.openLlmSteps.size===0?{phase:"stopped",label:"Stopped"}:{phase:"stopping",label:"Stopping…"});const n=this.snapshot.stop||null;((n==null?void 0:n.phase)!==(t==null?void 0:t.phase)||(n==null?void 0:n.label)!==(t==null?void 0:t.label))&&this.set({...this.snapshot,stop:t}),(t==null?void 0:t.phase)==="stopping"&&this.snapshot.status==="cancelled"&&this.followStop(this.generation)}async followStop(t){var n;if(!this.stopFollowing){this.stopFollowing=!0;try{let r=500,i=null;for(;this.live(t)&&((n=this.snapshot.stop)==null?void 0:n.phase)==="stopping";){if(await this.waitForRetry(r),!this.live(t))return;const o=[this.rootRunId,...[...this.watchedRuns].filter(l=>l!==this.rootRunId)];let u=!1;for(const l of o)try{await this.catchUp(l,t)}catch(d){u=!0,this.live(t)&&(this.fail(d,!1),i=this.snapshot.error)}!u&&i&&this.snapshot.error===i&&(this.set({...this.snapshot,error:null}),i=null),r=Math.min(5e3,r*2)}}finally{this.generation===t&&(this.stopFollowing=!1)}}}addMessage(t){const n=Lt(t.id)||`${t.role}:${t.content}:${t.ts||""}`;this.seenMessages.has(n)||(this.seenMessages.add(n),this.set({...this.snapshot,messages:[...this.snapshot.messages,{...t,id:n}]}))}toolMessage(t){const n=t.callId?this.toolPolicyByCall.get(`${t.runId}:${t.callId}`):void 0,r=n?{...t,policy:n}:t;return{id:`tool:${r.id}`,role:"system",kind:"tool_activity",title:"Tool activity",runId:r.runId,toolActivity:r,content:JSON.stringify({tool:r.name,status:r.status,arguments:r.arguments,output:r.output,error:r.error},null,2),ts:r.endedAt||r.startedAt}}upsertTool(t){const n=this.toolMessage(t),r=this.snapshot.messages.findIndex(o=>o.id===n.id);if(r<0){this.addMessage(n);return}const i=[...this.snapshot.messages];i[r]=n,this.set({...this.snapshot,messages:i})}addRunAssistantMessage(t,n){this.closeLiveRepliesOfRun(t);const r=`answer:${t}:`,i=`final:${t}`;this.snapshot.messages.some(o=>o.role==="assistant"&&o.content===n.content&&(o.id===i||String(o.id||"").startsWith(r)))||this.addMessage(n)}ingestDelta(t,n){let r;try{r=gN(n)}catch(d){this.fail(d,!1);return}const i=`${r.run_id}:${r.call_id}`;if(pN(r)){if(r.reason==="unavailable"){this.noteStreamUnavailable(r);return}if(r.reason==="cancelled"&&r.detail==="reinvoked"){this.closeLiveReply(i,"restarted");return}this.closeLiveReply(i,r.reason==="completed"?void 0:r.reason);return}if(this.closedLiveCalls.has(i)||this.runEnded(r.run_id)||this.runEnded(this.rootRunId))return;const o=this.liveReplies.get(i)||{runId:r.run_id,callId:r.call_id,nodeId:r.node_id||"",via:t,text:"",reasoning:"",seq:{content:-1,reasoning:-1}},u=r.channel==="reasoning"?"reasoning":"text",l=o.seq[r.channel];if(r.snapshot){if(r.seq<l)return;o[u]=r.text}else{if(r.seq<=l)return;o[u]+=r.text}o.seq[r.channel]=r.seq,o.via=t,this.liveReplies.set(i,o),this.liveDirty.add(i),this.scheduleLiveRender()}runEnded(t){return qs(vi(this.runStates.get(t)||null))}scheduleLiveRender(){if(this.liveRenderTimer)return;const t=this.lastLiveRender+this.liveRenderIntervalMs-Date.now();if(t<=0){this.renderLiveReplies();return}this.liveRenderTimer=setTimeout(()=>{this.liveRenderTimer=null,this.renderLiveReplies()},t)}renderLiveReplies(){if(this.lastLiveRender=Date.now(),!this.liveDirty.size)return;const t=[...this.snapshot.messages];for(const n of this.liveDirty){const r=this.liveReplies.get(n);if(!r)continue;const i=this.liveMessage(r),o=t.findIndex(u=>u.id===i.id);o<0?t.push(i):t[o]=i,this.shownLiveCalls.add(n)}this.liveDirty.clear(),this.set({...this.snapshot,messages:t})}liveMessage(t){const n=t.runId!==this.rootRunId;return{id:`live:${t.runId}:${t.callId}`,role:"assistant",content:t.text,runId:t.runId,live:{callId:t.callId,reasoning:t.reasoning,...n?{caption:`sub-agent · ${t.nodeId||t.runId}`}:{}}}}closeLiveReply(t,n){this.closedLiveCalls.add(t);const r=this.liveReplies.get(t);if(!r){n==="restarted"&&this.shownLiveCalls.has(t)&&this.addMessage(this.restartNote(t));return}this.liveReplies.delete(t),this.liveDirty.delete(t);const i=`live:${r.runId}:${r.callId}`,o=this.snapshot.messages.findIndex(l=>l.id===i);if(o<0)return;const u=[...this.snapshot.messages];if(n==="restarted"){const l=this.restartNote(t);this.seenMessages.add(String(l.id)),u[o]=l}else if(n){const l=`live-end:${r.runId}:${r.callId}`;this.seenMessages.add(l),u[o]={id:l,role:"system",level:"warn",title:"Reply",runId:r.runId,content:n==="failed"?"The reply stopped because the model call failed.":"The reply stopped because the model call was cancelled."}}else u.splice(o,1);this.set({...this.snapshot,messages:u})}restartNote(t){const n=t.slice(0,t.indexOf(":"));return{id:`live-end:${t}`,role:"system",level:"info",title:"Reply",runId:n,content:"Reply restarted: the model call was interrupted and is running again."}}noteStreamUnavailable(t){const n=`${t.run_id}:${t.call_id}`;this.closeLiveReply(n),this.addMessage({id:`stream-unavailable:${t.run_id}:${t.detail||"unknown"}`,role:"system",level:"info",title:"Reply",runId:t.run_id,content:WR(t.detail)})}closeLiveRepliesOfRun(t){for(const n of[...this.liveReplies.values()])n.runId===t&&this.closeLiveReply(`${n.runId}:${n.callId}`)}closeLiveRepliesVia(t,n){for(const r of[...this.liveReplies.values()])(r.via===t||r.runId===t)&&this.closeLiveReply(`${r.runId}:${r.callId}`,n)}endLiveRepliesOfRun(t,n){const r=n==="failed"||n==="cancelled"?n:void 0;if(t===this.rootRunId){for(const i of[...this.liveReplies.values()])this.closeLiveReply(`${i.runId}:${i.callId}`,r);this.closedLiveCalls.clear(),this.shownLiveCalls.clear();return}this.closeLiveRepliesVia(t,r);for(const i of[...this.closedLiveCalls])i.startsWith(`${t}:`)&&this.closedLiveCalls.delete(i);for(const i of[...this.shownLiveCalls])i.startsWith(`${t}:`)&&this.shownLiveCalls.delete(i)}dropLiveRepliesVia(t){const n=new Set;for(const[r,i]of this.liveReplies)i.via===t&&(this.liveReplies.delete(r),this.liveDirty.delete(r),n.add(`live:${i.runId}:${i.callId}`));n.size&&this.set({...this.snapshot,messages:this.snapshot.messages.filter(r=>!n.has(String(r.id)))})}fail(t,n=!0){var r,i,o;Vl(t)&&(this.approvalEpoch+=1,this.toolApprovalStopped=!0,this.toolApprovalSuspended=!0,(i=(r=this.options).onAuthError)==null||i.call(r,t)),this.set({...this.snapshot,error:t instanceof Error?t.message:Lt((o=tn(t))==null?void 0:o.detail)||String(t),...Vl(t)?{autoApproveTools:!1}:{},...n?{connection:"disconnected"}:{}})}newCommandId(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return t.randomUUID();if(t&&typeof t.getRandomValues=="function"){const n=t.getRandomValues(new Uint8Array(16));n[6]=n[6]&15|64,n[8]=n[8]&63|128;const r=Array.from(n,i=>i.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}return`workflow-${Date.now()}-${Math.random().toString(36).slice(2)}`}updateRunState(t,n){var o;if(this.runStates.set(t,n),qs(vi(n))&&this.endLiveRepliesOfRun(t,vi(n)),t!==this.rootRunId){qs(vi(n))&&((o=this.snapshot.interaction)==null?void 0:o.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const r=vi(n),i=qs(r);if(i){const u=wd(n.output);u&&this.upsertFinal(t,u,t0(n))}this.set({...this.snapshot,run:n,status:r,...i?{interaction:null,autoApproveTools:!1,displayStatus:""}:{}}),i||this.adoptDurableWait(t,n),(this.stopRequested||this.forcedStop)&&this.recomputeStop()}upsertFinal(t,n,r){this.closeLiveRepliesOfRun(t);const i=`final:${t}`;this.seenMessages.add(i);const o={id:i,role:"assistant",content:n,ts:r,runId:t,statistics:Ay(this.snapshot.records).statistics},u=this.snapshot.messages.findIndex(d=>d.id===i||String(d.id||"").startsWith(`answer:${t}:`)&&d.content===n);if(u<0){this.set({...this.snapshot,messages:[...this.snapshot.messages,o]});return}const l=[...this.snapshot.messages];l[u]=o,this.set({...this.snapshot,messages:l})}async refreshRunState(t,n){var r;try{const i=tn(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));i&&this.live(n)&&this.updateRunState(t,i)}catch(i){this.live(n)&&this.fail(i,!1)}}async pollRootLifecycle(t,n){var r;for(;this.live(n)&&this.rootRunId===t&&!qs(vi(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||qs(vi(this.runStates.get(t)||null)))return;try{const i=tn(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));i&&this.live(n)&&this.rootRunId===t&&this.updateRunState(t,i)}catch(i){if(!this.live(n))return;if(Vl(i)){this.fail(i);return}this.fail(i,!1)}}}waitForRetry(t){var i;const n=(i=this.controller)==null?void 0:i.signal;if(!n||n.aborted)return Promise.resolve();const r=n;return new Promise(o=>{const u=setTimeout(d,t),l=()=>{clearTimeout(u),d()};function d(){r.removeEventListener("abort",l),o()}r.addEventListener("abort",l,{once:!0})})}}function zL(e){const t=p.useMemo(()=>new FL(e.transport,{onAuthError:e.onAuthError,clientId:e.clientId,...e.liveRenderIntervalMs!==void 0?{liveRenderIntervalMs:e.liveRenderIntervalMs}:{}}),[e.transport,e.onAuthError,e.clientId,e.authScopeKey,e.liveRenderIntervalMs]),n=p.useSyncExternalStore(i=>t.subscribe(i),()=>t.getSnapshot(),()=>t.getSnapshot()),r=String(e.runId||"").trim();return p.useEffect(()=>{t.setToolApprovalPolicy(e.enabled===!1?{enabledTools:[],autoApproveTools:[]}:e.toolApprovalPolicy??null)},[t,e.toolApprovalPolicy,e.enabled]),p.useEffect(()=>{if(e.enabled===!1||!r){t.reset();return}return t.load(r),()=>t.reset()},[t,r,e.enabled]),{controller:t,snapshot:n}}function Jc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Dr(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function s0(e){return["session","workflow","run","global"].includes(e)?e:null}function Jl(e){return{scope:Dr(e==null?void 0:e.scope).toLowerCase(),name:Dr(e==null?void 0:e.name)||Dr(e==null?void 0:e.event_name),scopeId:Dr(e==null?void 0:e.scope_id)||Dr(e==null?void 0:e.scopeId),sessionId:Dr(e==null?void 0:e.session_id)||Dr(e==null?void 0:e.sessionId),workflowId:Dr(e==null?void 0:e.workflow_id)||Dr(e==null?void 0:e.workflowId),runId:Dr(e==null?void 0:e.run_id)||Dr(e==null?void 0:e.runId)}}function BL(e,t){const n=e.wait,r=Dr(n.wait_key),i=[Jl(n),Jl(Jc(n.details))];for(const o of t){if(o.runId!==e.runId)continue;const u=o.record,l=Jc(u.result),d=Jc(l==null?void 0:l.wait),h=Jc(u.effect),m=Jc(h==null?void 0:h.payload);Dr(d==null?void 0:d.wait_key)!==r&&Dr(m==null?void 0:m.wait_key)!==r||i.push(Jl(u),Jl(m),Jl(Jc(m==null?void 0:m.details)),Jl(d),Jl(Jc(d==null?void 0:d.details)))}return i}function Ly(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function NN(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function UL(e,t,n){if(!n)return null;const r=`evt:${t}:${n}:`;if(!e.startsWith(r))return null;const i=e.slice(r.length);return i?NN(t,n,i):null}function WL(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const r=Dr(e.wait.wait_key),i=/^evt:(session|workflow|run|global):/.exec(r);if(!i)return{target:null,error:"The gateway did not provide a canonical event wait key."};const o=s0(i[1]);if(!o)return{target:null,error:"The event wait uses an unsupported scope."};const u=BL(e,Array.isArray(t)?t:[]),l=new Map;for(const g of u){const y=s0(g.scope);if(!y||!g.name)continue;if(y!==o)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const b=`evt:${y}:`,k=`:${g.name}`;if(!r.startsWith(b)||!r.endsWith(k)||r.length<=b.length+k.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const x=r.slice(b.length,-k.length),N=Ly(y,g);if(N&&N!==x)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const $=NN(y,x,g.name);l.set(`${$.scope}\0${$.scopeId}\0${$.name}`,$)}if(l.size>1)return{target:null,error:"Multiple event targets match this wait; routing is unavailable."};if(l.size===1)return{target:[...l.values()][0]};const d=new Set;o==="run"&&d.add(e.runId),o==="global"&&d.add("global");for(const g of u){const y=Ly(o,g);y&&d.add(y)}if(Dr(n==null?void 0:n.run_id)===e.runId){const g=Jl(n||null),y=Ly(o,g);y&&d.add(y)}const m=[...d].map(g=>UL(r,o,g)).filter(g=>!!g),_=new Map(m.map(g=>[`${g.scope}\0${g.scopeId}\0${g.name}`,g]));return _.size===1?{target:[..._.values()][0]}:_.size>1?{target:null,error:"The event key is ambiguous for the available scope metadata."}:{target:null,error:"The gateway did not provide enough canonical event routing metadata."}}function $N(e){return s.jsx(sN,{text:e,images:"link"})}const qL={trigger:"Trigger",answer:"Automation"};function r0(e,t){return s.jsx(tx,{...t,message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:qL[e.kind],runId:e.runId},images:"link"})}function HL(e){const t=e;return!!(t&&typeof t=="object"&&typeof t.run_id=="string"&&typeof t.wait_key=="string"&&!("wait"in t))}function VL(e){const t={...e.details||{}};e.kind==="tool_approval"&&(t.kind="tool_approval",t.tool_calls=Array.isArray(e.tool_calls)?e.tool_calls:[]);const n={wait_key:e.wait_key,reason:e.kind==="ask_user"?"user":"tool_approval",details:t};return e.prompt!=null&&(n.prompt=e.prompt),Array.isArray(e.choices)&&(n.choices=e.choices),typeof e.allow_free_text=="boolean"&&(n.allow_free_text=e.allow_free_text),{runId:e.run_id,wait:n,...e.step_id?{stepId:e.step_id}:{}}}function GL(e,t,n={}){var h;if(!e)return null;const r=HL(e)?VL(e):e,i=r.wait,o=`${r.runId}:${i.wait_key}:${r.stepId||""}`,u=i.details||{};if(u.mode==="approval_required"||u.kind==="tool_approval"){const m=Array.isArray(u.tool_calls)?u.tool_calls:[],_={runId:r.runId,waitKey:String(i.wait_key||""),stepId:r.stepId},g=[...new Set(m.map(D=>String((D==null?void 0:D.name)||"tool")))],y=n.onPermissionsAll,b=n.onAllowForSession,k=String(n.approveAllScope||"").trim(),x=((h=n.remember)==null?void 0:h.call(n,g))||void 0,N=zh,$=b?{approveForSessionLabel:N.allowForChat,approveForSessionDescription:"Allow for this chat approves this batch and the enabled tools for the rest of this chat. Unchecked tools stay unavailable; questions still need your answer.",onApproveForSession:async()=>{let D;await t.approveWithPolicyChange(_,()=>{D=b()}),D&&await D.catch(R=>{throw new Error(`This batch was allowed, but "Allow for this chat" could not be turned on: ${R instanceof Error?R.message:String(R)}`)})}}:{};let E=$,S=[];const P=n.sessionPolicy;if(P){const D=t.approveAllForSession,R=t.approveKindForSession,I=t.denyToolForSession,W=t.denyKindForSession,G=t.sessionPolicyStatus;if(typeof D!="function"||typeof R!="function"||typeof I!="function"||typeof W!="function"||typeof G!="function")throw new Error("presentInteraction: sessionPolicy needs a WorkflowSessionController (approveAllForSession, approveKindForSession, denyToolForSession, denyKindForSession, sessionPolicyStatus).");const K=G.call(t),H=P.ask?[...P.ask]:void 0,M=(V,J)=>{var te;const U=String(((te=V==null?void 0:V.scope)==null?void 0:te[J])||"").trim();return U?`Applies: ${U}`:N.noScopeNote},A=V=>({outcomeNote:[Kb(V==null?void 0:V.clamped),M(V,"approve")].filter(Boolean).join(" ")}),O=V=>({outcomeNote:`${N.denyForChatNote} ${M(V,"deny")}`}),L=Kb(K.clamped);if(K.mode==="unavailable")E={scopeNote:N.unavailablePolicyNote(K.reason||"")};else if(K.mode==="gateway"){const V=[...new Set(m.map(z=>{var ne;return String((z==null?void 0:z.toolset)||"").trim()||String(((ne=P.toolsetOf)==null?void 0:ne.call(P,String((z==null?void 0:z.name)||"")))||"").trim()}).filter(Boolean))],J=(H||[]).map(z=>String(z).trim()).filter(Boolean),U=J.length?`Tools set to Ask keep asking: ${J.join(", ")}.`:"Nothing is set to Ask, so tools that reach destinations the model picks (fetch_url, browser_probe, send_email) are included.",te=K.policy;S=te?g.filter(z=>Object.prototype.hasOwnProperty.call(te.deny||{},z)):[],E={approveForSessionLabel:N.allowForChat,approveForSessionDescription:`Allow for this chat (and Allow all <toolset> tools for this chat) approves this batch and stores a policy for this chat on the gateway: later tool calls of every run of this chat run without asking, until the policy is reset. ${U} Tools the gateway does not authorize stay uncovered.`,onApproveForSession:async()=>A(await D.call(t,_,{...P.maxRiskRank!==void 0?{maxRiskRank:P.maxRiskRank}:{},...H?{ask:H}:{}})),approveKinds:V.map(z=>({kind:z,label:N.allowKindForChat(z),onApprove:async()=>A(await R.call(t,_,z,H?{ask:H}:{}))})),denyOptions:[...g.map(z=>({key:`tool:${z}`,label:N.denyToolForChat(z),onDeny:async()=>O(await I.call(t,_,z,H?{ask:H}:{}))})),...V.map(z=>({key:`kind:${z}`,label:N.denyKindForChat(z),onDeny:async()=>O(await W.call(t,_,z,H?{ask:H}:{}))}))],...S.length?{deniedNote:`Denied by this chat's policy: ${S.join(", ")}. The gateway refuses ${S.length===1?"it":"them"} even if allowed once.`}:{},...te?{policySummary:`This chat's policy: ${Object.keys(te.approve||{}).length} tools allowed without asking, ${Object.keys(te.deny||{}).length} denied. ${M(te,"approve")}`}:{},...L?{notCovered:L}:{}}}else E=b?{...$,scopeNote:N.localChatPolicyNote}:{approveForSessionLabel:N.allowForRun,onApproveForSession:async()=>{await D.call(t,_,{})},scopeNote:N.localRunPolicyNote}}return{id:o,kind:"tool-approval",title:`${m.length||"Requested"} ${m.length===1?"action needs":"actions need"} permission`,toolName:g.join(", ")||"the requested tools",description:"Review the targets below. Allow once approves this batch only.",detail:s.jsxs("div",{className:"pc-approval-summary",children:[s.jsx(uN,{tools:m.map((D,R)=>({id:String((D==null?void 0:D.call_id)||(D==null?void 0:D.id)||R),runId:r.runId,name:(D==null?void 0:D.name)||"Tool",arguments:D==null?void 0:D.arguments,status:"waiting"}))}),s.jsxs("details",{children:[s.jsx("summary",{children:"Review full tool arguments (JSON)"}),s.jsx(fr,{value:m.length?m:u})]})]}),approveLabel:zh.allowOnce,denyLabel:zh.deny,approveAllLabel:y?zh.allowAll:void 0,approveAllDescription:y?`Sets permissions: all${k?` ${k}`:""}, including future turns. Unchecked tools stay unavailable; explicit Ask overrides and Gateway restrictions remain enforced. Questions still need your answer.`:void 0,...E,...n.approveAllDisabledReason?{disabledReason:n.approveAllDisabledReason}:{},...x?{remember:x}:{},...n.onDefer?{onDefer:n.onDefer}:{},onApproveAll:y?async()=>{await t.approveWithPolicyChange(_,()=>{y()})}:void 0,onApprove:async()=>(await t.approve(!0,_),S.length?{outcomeNote:`The gateway refuses ${S.join(", ")}: denied by this chat's policy.`}:void 0),onDeny:async()=>{await t.approve(!1,_)}}}const l={runId:r.runId,waitKey:String(i.wait_key||""),stepId:r.stepId};if(i.reason==="user"||i.reason==="ask_user")return{id:o,kind:"ask-user",title:"A question for you",prompt:String(i.prompt||u.prompt||"How would you like to continue?"),allowFreeText:i.allow_free_text!==!1,choices:(Array.isArray(i.choices)?i.choices:[]).map(m=>typeof m=="object"&&m!==null?{id:String(m.value??m.id??m.label),label:String(m.label??m.text??m.value??m.id),description:m.description}:{id:String(m),label:String(m)}),onSubmit:async m=>{await t.resume(m,l)},...n.allowSkip?{onSkip:async()=>{await t.resume("",l)}}:{},...n.onDefer?{onDefer:n.onDefer}:{}};const d=String(i.wait_key||"");if(i.reason==="event"||d.startsWith("evt:")){const m=WL(r,n.records||[],n.currentRun??null),_=m.target,g=(_==null?void 0:_.name)||"";return{id:o,kind:"event-wait",title:_?"Waiting for an event":"Event routing unavailable",eventName:g,prompt:String(i.prompt||`This workflow will continue when “${g||"its trigger"}” arrives.`),description:_?"You can also send the expected event here.":`This event cannot be sent safely. ${m.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async y=>{if(!_)throw new Error(m.error);const b=JSON.parse(y||"{}"),k={name:_.name,scope:_.scope,payload:b};_.scope==="session"?k.session_id=_.scopeId:_.scope==="workflow"?k.workflow_id=_.scopeId:_.scope==="run"&&(k.run_id=_.scopeId),await t.emitEvent(k)}}}return null}const KL={app:"observer",name:"AbstractObserver"},JL=["How do I see why a run failed?","Where do I find the artifacts a run produced?","What does the Board's Review column mean?","How do I launch a workflow on a schedule?"];function YL(e){const t=p.useRef(e.gateway);t.current=e.gateway;const n=(r,i)=>t.current.fetch_gateway(r,i);return s.jsx(xL,{open:e.open,onClose:e.onClose,source:KL,fetchGateway:n,connected:e.connected,topOffset:e.topOffset,placeholder:"Ask about the observer…",suggestions:JL})}function XL(e,t){switch(t.type){case"open":return!0;case"close":case"page_change":case"layout_change":return!1;case"escape":return t.default_prevented||t.other_modal_open?e:!1}}function ZL(e,t){return e?t?{aside:{"aria-label":"Navigation",role:"dialog","aria-modal":"true"},main:{inert:"","aria-hidden":"true"}}:{aside:{"aria-label":"Navigation",inert:"","aria-hidden":"true"},main:{}}:{aside:{"aria-label":"Navigation"},main:{}}}function QL(e,t,n){return e<=0?-1:t<0?n?e-1:0:(t+(n?e-1:1))%e}const eI='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function tI(e){return typeof document>"u"?!1:Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e)}function nI(e){const[t,n]=p.useReducer(XL,!1),r=p.useRef(null),i=p.useRef(null),o=p.useRef(!1);return p.useEffect(()=>{n({type:"page_change"})},[e.page]),p.useEffect(()=>{n({type:"layout_change"})},[e.is_drawer]),p.useEffect(()=>{var u;if(t){o.current=!0;const l=i.current,d=(l==null?void 0:l.querySelector(".shell_nav_item.active"))||(l==null?void 0:l.querySelector(".shell_nav_item"));d==null||d.focus();const h=m=>{if(m.key==="Escape"){n({type:"escape",default_prevented:m.defaultPrevented,other_modal_open:tI(i.current)});return}if(m.key!=="Tab"||!i.current)return;const _=Array.from(i.current.querySelectorAll(eI)).filter(y=>y.offsetParent!==null||y===document.activeElement),g=QL(_.length,_.indexOf(document.activeElement),m.shiftKey);g>=0&&(m.preventDefault(),_[g].focus())};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)}o.current&&(o.current=!1,(u=r.current)==null||u.focus())},[t]),{open:t,set_open:u=>n({type:u?"open":"close"}),toggle_ref:r,sidebar_ref:i,attrs:ZL(e.is_drawer,t)}}function sI(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function np(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function rI(e){const t=np(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=np(e.replayed_messages),r=np(e.dropped_tokens),i=np(e.max_tokens),o=[`Earlier messages not replayed: ${t.toLocaleString("en-US")}${r?` (~${r.toLocaleString("en-US")} tokens)`:""}.`,`The model read the newest ${n.toLocaleString("en-US")} message${n===1?"":"s"}`+(i?` (history window: the most recent ${i.toLocaleString("en-US")} tokens of whole messages).`:".")];return e.oversize_turn_kept&&o.push("Your latest message alone is larger than the window; it was sent whole."),o.join(" ")}function iI(e){const t=rI(e.history);return t?s.jsx(tx,{message:{role:"system",level:"info",title:"History",content:t}}):null}const oI="api/local/reveal",aI="sw.js",Kw="#run/";function lI(e){return`${Kw}${encodeURIComponent(String(e||"").trim())}`}function CN(e){const t=String(e||"");if(!t.startsWith(Kw))return"";const n=t.slice(Kw.length).split("?")[0];if(!n||n.includes("/"))return"";try{return decodeURIComponent(n).trim()}catch{return""}}function cI(e){return`Run ${e} cannot be opened: it does not exist on this gateway, or your account cannot see it.`}function uI(e){const t=CN(e.hash);if(t)return t;const n=u=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(u),r=u=>{const l=u.split("/").filter(Boolean);return l.length?l[l.length-1].trim():""},i=r(String(e.hash||"").replace(/^#/,""));if(n(i))return i;const o=r(String(e.pathname||""));return n(o)?o:""}const dI={llm_call:"llm_call",tool_calls:"tool",tool_invoke:"tool",entity_tools_execute:"tool",start_subworkflow:"subflow",emit_event:"event",wait_event:"wait",wait_until:"wait",resume:"resume",ask_user:"ask",answer_user:"answer",model_residency:"model",memory_query:"memory",memory_tag:"memory",memory_compact:"memory",memory_note:"memory",memory_rehydrate:"memory",memory_kg_assert:"memory",memory_kg_query:"memory",memory_kg_resolve:"memory",memory_recall:"memory",memory_access:"memory",memory_form:"memory",memory_adjust:"memory",memory_appraise:"memory",memory_consolidate:"memory",memory_probe:"memory",memory_tend:"memory",diary_write:"memory",diary_read:"memory",life_query:"memory",entity_tools_query:"memory",vars_query:"memory"},fI=new Set(["wait","resume","memory","model","node"]),hI=new Set(["abstract.status","abstract.progress","abstract.steer_seen","abstract.summary"]),mI={llm_call:"LLM call",tool:"Tools",subflow:"Subflow",event:"Event",wait:"Wait",resume:"Resume",ask:"Question",answer:"Answer",memory:"Memory",model:"Model",node:"Node",other:"Effect"};function _I(e){const t=String(e||"").trim();return t?dI[t]||"other":"node"}function pI(e,t,n){return n?!1:e==="event"?hI.has(String(t||"").trim()):fI.has(e)}const gI=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function yI(e){const t=new TextEncoder().encode(e),n=t.length*8,r=t.length+9+63>>6<<6,i=new Uint8Array(r);i.set(t),i[t.length]=128;const o=new DataView(i.buffer);o.setUint32(r-8,Math.floor(n/4294967296)),o.setUint32(r-4,n>>>0);const u=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),l=new Uint32Array(64);for(let d=0;d<r;d+=64){for(let N=0;N<16;N++)l[N]=o.getUint32(d+N*4);for(let N=16;N<64;N++){const $=l[N-15],E=l[N-2],S=($>>>7|$<<25)^($>>>18|$<<14)^$>>>3,P=(E>>>17|E<<15)^(E>>>19|E<<13)^E>>>10;l[N]=l[N-16]+S+l[N-7]+P>>>0}let[h,m,_,g,y,b,k,x]=u;for(let N=0;N<64;N++){const $=(y>>>6|y<<26)^(y>>>11|y<<21)^(y>>>25|y<<7),E=y&b^~y&k,S=x+$+E+gI[N]+l[N]>>>0,P=(h>>>2|h<<30)^(h>>>13|h<<19)^(h>>>22|h<<10),D=h&m^h&_^m&_,R=P+D>>>0;x=k,k=b,b=y,y=g+S>>>0,g=_,_=m,m=h,h=S+R>>>0}u[0]=u[0]+h>>>0,u[1]=u[1]+m>>>0,u[2]=u[2]+_>>>0,u[3]=u[3]+g>>>0,u[4]=u[4]+y>>>0,u[5]=u[5]+b>>>0,u[6]=u[6]+k>>>0,u[7]=u[7]+x>>>0}return Array.from(u,d=>d.toString(16).padStart(8,"0")).join("")}const Jw="$slim";function wI(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&e[Jw]&&typeof e[Jw]=="object")}function vI(e){const t=new Map;for(const n of e||[]){if(!n||typeof n!="object"||String(n.status||"")!=="started")continue;const r=String(n.step_id||""),i=n.effect&&typeof n.effect=="object"?n.effect.payload:null;r&&i&&typeof i=="object"&&!t.has(r)&&t.set(r,i)}return t}function xI(e,t){const n=[];for(const r of t)if(r==="system"){if(typeof e.system_prompt!="string"||!e.system_prompt)return null;n.push({role:"system",content:e.system_prompt})}else if(r==="messages"){if(!Array.isArray(e.messages))return null;for(const i of e.messages)i&&typeof i=="object"&&n.push({...i})}else if(r==="prompt"){if(typeof e.prompt!="string"||!e.prompt)return null;n.push({role:"user",content:e.prompt})}else return null;return n}function bI(e,t){const n=e&&e[Jw];if(!n||typeof n!="object")return{state:"missing",reason:"not a $slim marker"};const r=t.get(String(n.step_id||""));if(!r)return{state:"missing",reason:"its started record is not in the loaded ledger"};let i;if(n.kind==="started_payload_field"){const u=String(n.field||"");if(!(u in r))return{state:"missing",reason:`the started record has no "${u}" field`};i=r[u]}else if(n.kind==="started_messages_layout"){if(i=Array.isArray(n.layout)?xI(r,n.layout.map(String)):null,!i)return{state:"missing",reason:"the started record cannot rebuild these messages"}}else return{state:"missing",reason:`unknown $slim kind "${String(n.kind||"")}"`};if(Array.isArray(n.appendix)&&n.appendix.length){if(!Array.isArray(i))return{state:"missing",reason:"appendix on a non-list value"};const u=i.map(d=>d&&typeof d=="object"?{...d}:d),l=[...n.appendix].sort((d,h)=>Number((d==null?void 0:d.at)??-1)-Number((h==null?void 0:h.at)??-1));for(const d of l){const h=Number(d==null?void 0:d.at);if(!Number.isInteger(h)||h<0||h>u.length)return{state:"missing",reason:"appendix position out of range"};u.splice(h,0,d.item)}i=u}return yI(JSON.stringify(i))!==String(n.sha256||"")?{state:"unverified",value:i,reason:"checksum differs from the record"}:{state:"resolved",value:i}}function kI(e,t){const n=[],r=[],i=(o,u,l)=>{if(l>14)return o;if(wI(o)){const d=bI(o,t);return d.state==="missing"?(n.push({path:u,reason:d.reason}),o):(d.state==="unverified"&&r.push({path:u,reason:d.reason}),d.value)}if(Array.isArray(o)){let d=null;return o.forEach((h,m)=>{const _=i(h,`${u}[${m}]`,l+1);_!==h&&((d??(d=[...o]))[m]=_)}),d??o}if(o&&typeof o=="object"){let d=null;for(const h of Object.keys(o)){const m=i(o[h],u?`${u}.${h}`:h,l+1);m!==o[h]&&((d??(d={...o}))[h]=m)}return d??o}return o};return{value:i(e,"",0),unresolved:n,unverified:r}}function i0(e){const t=Date.parse(String(e||""));return Number.isFinite(t)?t:null}function EN(e){const t=e==null?void 0:e.result;return t&&typeof t=="object"&&Array.isArray(t.results)?t.results:[]}function jI(e,t){return e?String(e.status||"")==="failed"||e.error?!0:t==="tool"&&EN(e).some(n=>n&&n.success===!1):!1}function SI(e){var n;const t=String((e==null?void 0:e.idempotency_key)||"").trim();return String(((n=e==null?void 0:e.effect)==null?void 0:n.type)||"")==="tool_calls"&&t?`idem:${t}`:String((e==null?void 0:e.step_id)||"")}function Mg(e,t){var h,m,_,g,y,b;const n=String(t||"").trim(),r=(e||[]).filter(k=>k&&k.record&&String(k.run_id||k.record.run_id||"").trim()===n).sort((k,x)=>(k.cursor||0)-(x.cursor||0)),i=vI(r.map(k=>k.record)),o=new Map,u=[];for(const k of r){const x=k.record,$=SI(x)||`cursor:${k.cursor}`;let E=o.get($);E||(E={cursor:k.cursor,started:null,latest:x,latest_cursor:k.cursor},o.set($,E),u.push($)),String(x.status||"")==="started"&&!E.started&&(E.started=x),k.cursor>=E.latest_cursor&&(E.latest=x,E.latest_cursor=k.cursor)}let l=0;const d=[];for(const k of u){const x=o.get(k),N=kI(x.latest,i),$=N.value,E=String(((h=$==null?void 0:$.effect)==null?void 0:h.type)||((_=(m=x.started)==null?void 0:m.effect)==null?void 0:_.type)||"").trim(),S=_I(E),P=S==="event"?String(((y=(g=$==null?void 0:$.effect)==null?void 0:g.payload)==null?void 0:y.name)||"").trim():"";S==="llm_call"&&(l+=1);const D=jI($,S),R=String(((b=x.started)==null?void 0:b.started_at)||($==null?void 0:$.started_at)||""),I=String(($==null?void 0:$.ended_at)||""),W=i0(R),G=i0(I);d.push({id:`${n}:${k}`,run_id:n,step_id:String(($==null?void 0:$.step_id)||""),node_id:String(($==null?void 0:$.node_id)||""),kind:S,effect_type:E,event_name:P,status:String(($==null?void 0:$.status)||""),cursor:x.cursor,started_at:R,ended_at:I,duration_ms:W!==null&&G!==null?Math.max(0,G-W):null,started:x.started,record:$,failed:D,housekeeping:pI(S,P,D),cycle:l,unresolved:N.unresolved,unverified:N.unverified})}return d}function NI(e){const t=[];for(const n of e){let r=t[t.length-1];(!r||r.cycle!==n.cycle)&&(r={cycle:n.cycle,steps:[],llm:null},t.push(r)),n.kind==="llm_call"&&!r.llm&&(r.llm=n),r.steps.push(n)}return t}const $I={view:"cycles",only:"all",all_steps:!1,q:""};function CI(e,t,n){const r=String(t.q||"").trim().toLowerCase();return e.filter(i=>!(t.only==="llm"&&i.kind!=="llm_call"||t.only==="tools"&&i.kind!=="tool"||t.only==="failed"&&!i.failed||t.only==="all"&&!t.all_steps&&i.housekeeping||r&&!n(i).includes(r)))}const EI=["all","llm","tools","failed"];function o0(e){const t=String(e||""),n=t.indexOf("?");if(n<0)return{...$I};const r=new URLSearchParams(t.slice(n+1)),i=String(r.get("only")||"");return{view:r.get("view")==="steps"?"steps":"cycles",only:EI.includes(i)?i:"all",all_steps:r.get("all")==="1",q:String(r.get("q")||"")}}function AI(e,t){const n=String(e||"").split("?")[0],r=new URLSearchParams;t.view!=="cycles"&&r.set("view",t.view),t.only!=="all"&&r.set("only",t.only),t.all_steps&&r.set("all","1"),t.q.trim()&&r.set("q",t.q);const i=r.toString();return i?`${n}?${i}`:n}function Dd(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof(t==null?void 0:t.text)=="string"?t.text:t!=null&&t.type?`[${String(t.type)}]`:JSON.stringify(t)).join(`
86
+ `):e==null?"":JSON.stringify(e,null,2)}function AN(e){if(typeof e!="string")return e??{};try{return JSON.parse(e)}catch{return e}}function TN(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object").map(t=>{var n,r;return{name:String(t.name||((n=t.function)==null?void 0:n.name)||"?"),arguments:AN(t.arguments??((r=t.function)==null?void 0:r.arguments))}}):[]}function a0(e){const t={role:String((e==null?void 0:e.role)||"?"),content:Dd(e==null?void 0:e.content)},n=TN(e==null?void 0:e.tool_calls);return n.length&&(t.tool_calls=n),e!=null&&e.name&&(t.name=String(e.name)),t}function l0(e){const t=Number(e);return Number.isFinite(t)&&e!==null&&e!==void 0?t:null}const TI={"effect.payload.system_prompt":"System","effect.payload.messages":"Messages","effect.payload.prompt":"Prompt","effect.payload.tools":"Tools offered","result.metadata._provider_request.payload.messages":"Messages sent"};function Sm(e){var b,k,x,N,$,E,S;const t=e.record||{},n=((k=(b=e.started)==null?void 0:b.effect)!=null&&k.payload&&typeof e.started.effect.payload=="object"?e.started.effect.payload:(x=t==null?void 0:t.effect)==null?void 0:x.payload)||{},r=t!=null&&t.result&&typeof t.result=="object"?t.result:{},i=r.usage||r.token_usage||{},o=[],u=e.unverified.map(P=>`${P.path}: ${P.reason}`);for(const P of e.unresolved){const D=TI[P.path];D&&o.push(`${D}: ${P.reason}`)}const l=($=(N=r==null?void 0:r.metadata)==null?void 0:N._provider_request)==null?void 0:$.payload;let d="",h=[],m="";if(l&&Array.isArray(l.messages)){m="sent";for(const P of l.messages)String((P==null?void 0:P.role)||"")==="system"&&!h.length?d+=(d?`
87
+
88
+ `:"")+Dd(P.content):h.push(a0(P))}else(Array.isArray(n.messages)||typeof n.prompt=="string")&&(m="payload",h=(Array.isArray(n.messages)?n.messages:[]).map(a0),typeof n.prompt=="string"&&n.prompt.trim()&&h.push({role:"user",content:n.prompt}));!d&&typeof n.system_prompt=="string"&&(d=n.system_prompt);const g=(Array.isArray(n.tools)?n.tools:Array.isArray(l==null?void 0:l.tools)?l.tools:[]).filter(P=>P&&typeof P=="object").map(P=>{const D=P.function&&typeof P.function=="object"?P.function:P;return{name:String(D.name||"?"),description:String(D.description||""),schema:D.parameters??D.input_schema??null}}),y=(E=r==null?void 0:r.metadata)!=null&&E._provider_request&&typeof r.metadata._provider_request=="object"?r.metadata._provider_request:{};return{provider:String(n.provider||r.provider||y.provider||(l==null?void 0:l.provider)||""),model:String(n.model||r.model||y.model||(l==null?void 0:l.model)||""),tokens_in:l0(i.prompt_tokens??i.input_tokens),tokens_out:l0(i.completion_tokens??i.output_tokens),system:d,messages:h,messages_source:m,tools:g,response:Dd(r.content??r.response??""),tool_calls:TN(r.tool_calls),reasoning:Dd(r.reasoning??((S=r==null?void 0:r.metadata)==null?void 0:S.reasoning)??""),missing:o,unverified:u}}function Nm(e){var i,o,u,l;const t=((o=(i=e.record)==null?void 0:i.effect)==null?void 0:o.payload)||((l=(u=e.started)==null?void 0:u.effect)==null?void 0:l.payload)||{},n=(Array.isArray(t.tool_calls)?t.tool_calls:[]).map(d=>{var h,m;return{name:String((d==null?void 0:d.name)||((h=d==null?void 0:d.function)==null?void 0:h.name)||"?"),arguments:AN((d==null?void 0:d.arguments)??((m=d==null?void 0:d.function)==null?void 0:m.arguments)),call_id:String((d==null?void 0:d.call_id)||(d==null?void 0:d.id)||"")}}),r=EN(e.record).map(d=>({name:String((d==null?void 0:d.name)||"?"),success:typeof(d==null?void 0:d.success)=="boolean"?d.success:null,output:(d==null?void 0:d.output)==null?"":Dd(d.output),error:(d==null?void 0:d.error)==null?"":Dd(d.error),call_id:String((d==null?void 0:d.call_id)||""),raw:d}));return{calls:n,results:r}}function MI(e){return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).map(([t,n])=>`${t}=${JSON.stringify(n)}`).join(", "):typeof e=="string"?e:JSON.stringify(e??"")}function $m(e){var r,i,o;const t=(r=e==null?void 0:e.result)==null?void 0:r.wait,n=typeof(t==null?void 0:t.wait_key)=="string"&&t.wait_key.startsWith("subworkflow:")?t.wait_key.slice(12):"";return String(((i=t==null?void 0:t.details)==null?void 0:i.sub_run_id)||((o=e==null?void 0:e.result)==null?void 0:o.sub_run_id)||n||"").trim()}function MN(e){var n,r,i,o,u,l,d,h,m,_,g;const t=e.record||{};switch(e.kind){case"llm_call":{const y=Sm(e);return y.tokens_in!==null||y.tokens_out!==null?`${(y.tokens_in??0).toLocaleString("en-US")} in · ${(y.tokens_out??0).toLocaleString("en-US")} out`:""}case"tool":{const y=Nm(e).calls;if(!y.length)return"";const b=`${y[0].name}(${MI(y[0].arguments)})`;return y.length>1?`${b} +${y.length-1} more`:b}case"event":return e.event_name;case"subflow":{const y=$m(t);return[String(((r=(n=t==null?void 0:t.effect)==null?void 0:n.payload)==null?void 0:r.workflow_id)||""),y].filter(Boolean).join(" · ")}case"wait":case"resume":return String(((o=(i=t==null?void 0:t.result)==null?void 0:i.wait)==null?void 0:o.reason)||((l=(u=t==null?void 0:t.effect)==null?void 0:u.payload)==null?void 0:l.reason)||"");case"ask":return String(((h=(d=t==null?void 0:t.effect)==null?void 0:d.payload)==null?void 0:h.prompt)||"");case"answer":return String(((_=(m=t==null?void 0:t.effect)==null?void 0:m.payload)==null?void 0:_.message)||((g=t==null?void 0:t.result)==null?void 0:g.message)||"");default:return e.effect_type}}function RN(e){return e.kind==="llm_call"?Sm(e).model:""}function RI(e,t){var r,i;const n=[e.kind,e.effect_type,e.event_name,e.node_id,t,e.status,MN(e),RN(e)];try{n.push(JSON.stringify(((i=(r=e.started)==null?void 0:r.effect)==null?void 0:i.payload)??null)),n.push(JSON.stringify(e.record??null))}catch{}return n.join(`
89
+ `).toLowerCase()}function LI(e){var r,i;const t=Array.from(new Set((e||[]).map(o=>{var u;return String(o.run_id||((u=o.record)==null?void 0:u.run_id)||"").trim()}).filter(Boolean))),n={llm_calls:0,tokens:0,tool_calls:0,tool_failures:0,failed_steps:0};for(const o of t)for(const u of Mg(e,o))if((u.failed||String(u.status||"")==="failed")&&(n.failed_steps+=1),u.kind==="llm_call"){n.llm_calls+=1;const l=((i=(r=u.record)==null?void 0:r.result)==null?void 0:i.usage)||{};n.tokens+=Number(l.total_tokens??Number(l.prompt_tokens??l.input_tokens??0)+Number(l.completion_tokens??l.output_tokens??0))||0}else if(u.kind==="tool"){const l=Nm(u);n.tool_calls+=Math.max(l.calls.length,l.results.length),n.tool_failures+=l.results.filter(d=>d.success===!1).length}return n}function II(e){const t=[];return e.llm_calls&&t.push(`${e.llm_calls} LLM call${e.llm_calls===1?"":"s"}`),e.tokens&&t.push(`${e.tokens.toLocaleString("en-US")} tokens`),e.tool_calls&&t.push(`${e.tool_calls} tool call${e.tool_calls===1?"":"s"}${e.tool_failures?`, ${e.tool_failures} failed`:""}`),e.failed_steps&&t.push(`${e.failed_steps} failed step${e.failed_steps===1?"":"s"}`),t.join(" · ")}function on(){return new Date().toISOString()}function OI(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Fr(e,t){try{const n=JSON.stringify(e);return typeof n!="string"?String(e):n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}catch{const n=String(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}}function en(e,t){const n=typeof(t==null?void 0:t.max_chars)=="number"?t.max_chars:360,r=typeof(t==null?void 0:t.max_lines)=="number"?t.max_lines:2,o=String(e||"").replace(/\r\n/g,`
90
+ `).replace(/\r/g,`
91
+ `).split(`
92
+ `),u=o.slice(0,Math.max(1,r)).join(`
93
+ `),l=o.length>r,d=u.length>n?`${u.slice(0,Math.max(0,n-1))}…`:u;return l&&d===u?`${u}…`:d}function Rn(e,t){const n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function c0(e){const t=String(e||"").trim();return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function Ht(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),r=Date.parse(n);return Number.isFinite(r)?r:null}function PI(e){const t=Date.now()-e,n=Math.floor(t/1e3),r=Math.floor(n/60),i=Math.floor(r/60),o=Math.floor(i/24);return n<60?"just now":r<60?`${r}m ago`:i<24?`${i}h ago`:o<=3?`${o}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function lu(e){const t=Ht(e);return t===null?"—":PI(t)}function em(e){if(!Number.isFinite(e))return"";const t=Math.floor(e/1e3);if(t<=0)return"now";const n=Math.floor(t/60),r=Math.floor(n/60),i=Math.floor(r/24),o=t%60,u=n%60,l=r%24;return i>0?`${i}d ${l}h`:r>0?`${r}h ${u}m`:n>0?`${n}m ${o}s`:`${t}s`}function vu(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"—";const t=Math.floor(e/1e3),n=t%60,r=Math.floor(t/60),i=r%60,o=Math.floor(r/60),u=o%24,l=Math.floor(o/24);return l>0?`${l}d ${u}h`:o>0?`${o}h ${i}m`:r>0?`${r}m ${n}s`:`${Math.max(0,t)}s`}function Vd(e){const t=Ht(e);return t===null?"—":new Date(t).toLocaleString()}function qn(...e){for(const t of e){const n=String(t??"").trim();if(n)return n}return""}function DI(...e){for(const t of e){const n=Number(t);if(Number.isFinite(n))return n}return null}function ds(e){const t=String(e||"").trim().toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}function Gd(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function Rd(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function FI(e){const t=String((e==null?void 0:e.status)||"").trim();return ds(t)?String((e==null?void 0:e.finished_at)||(e==null?void 0:e.updated_at)||"").trim():""}function Cm(e,t=Date.now()){const n=Ht(Rd(e));if(n===null)return-1;const r=Ht(FI(e));return Math.max(0,(r!==null?r:t)-n)}function pu(e,t=Date.now()){return vu(Cm(e,t))}function zI(e){return(e&&typeof e=="object"&&"message"in e?String(e.message||"").trim():String(e??"").trim())||"the request failed without a reason (no response body)"}function Yp(e){var n;const t=((n=e==null?void 0:e.output)==null?void 0:n.stop_reason)??(e==null?void 0:e.stop_reason)??null;return t&&typeof t=="object"?t:null}function tm(e){const t=String((e==null?void 0:e.status)??"").trim().toLowerCase(),n=t==="completed"||t==="failed"||t==="cancelled";return e!=null&&e.paused&&!n?"paused":t==="completed"&&(e!=null&&e.stop_reason)&&e.stop_reason.finished===!1?"stopped":t||"unknown"}function ka(e,t){const n=String(e??"").trim().toLowerCase();return n==="stopped"?"warn":n==="completed"?t&&t.finished===!1?"warn":"ok":n==="failed"||n==="cancelled"?"danger":n==="waiting"||n==="paused"||n==="suspended"?"warn":n==="running"||n==="scheduled"||n==="listening"?"info":"muted"}const BI={all:"All",llm:"LLM calls",tools:"Tools",failed:"Failed"};function go(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function wa(e){return s.jsxs("details",{className:"rs_section",open:e.open,children:[s.jsxs("summary",{children:[s.jsx("span",{className:"rs_section_title",children:e.title}),e.meta?s.jsx("span",{className:"rs_section_meta",children:e.meta}):null,e.copy!==void 0?s.jsx("button",{type:"button",className:"rs_copy",onClick:t=>{t.preventDefault(),t.stopPropagation(),e.on_copy(e.copy||"")},children:"Copy"}):null]}),s.jsx("div",{className:"rs_section_body",children:e.children})]})}function Iy(e){return`${e.toLocaleString("en-US")} chars`}function ox(e){const t=e.step.started&&e.step.started!==e.step.record?{started:e.step.started,record:e.step.record}:e.step.record;return s.jsx(wa,{title:"Raw JSON",copy:go(t),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(fr,{value:t,collapseAfterDepth:2,showCopy:!1})})})}function UI(e){const t=Sm(e.step),n=!t.system&&!t.messages.length&&!t.missing.length;return s.jsxs(s.Fragment,{children:[t.missing.map(r=>s.jsxs("p",{className:"rs_notice",children:["Prompt body not kept: ",r,"."]},r)),n?s.jsx("p",{className:"rs_notice",children:"Prompt body not kept: this record carries no request messages."}):null,t.unverified.length?s.jsxs("p",{className:"rs_notice",children:["Rebuilt prompt may differ from what was sent: ",t.unverified.join("; "),"."]}):null,t.system?s.jsx(wa,{title:"System",meta:Iy(t.system.length),copy:t.system,on_copy:e.on_copy,children:s.jsx("pre",{className:"rs_text",children:t.system})}):null,t.messages.length?s.jsx(wa,{title:"Messages",meta:`${t.messages.length}${t.messages_source==="sent"?" · as sent":""}`,copy:go(t.messages),on_copy:e.on_copy,children:s.jsx("ol",{className:"rs_messages",children:t.messages.map((r,i)=>{var o;return s.jsxs("li",{className:`rs_msg rs_msg_${r.role}`,children:[s.jsxs("span",{className:"rs_role",children:[r.role,r.name?` · ${r.name}`:""]}),r.content?s.jsx("pre",{className:"rs_text",children:r.content}):null,(o=r.tool_calls)==null?void 0:o.map((u,l)=>s.jsx("pre",{className:"rs_text mono",children:`${u.name}(${go(u.arguments)})`},l))]},i)})})}):null,t.tools.length?s.jsx(wa,{title:"Tools offered",meta:String(t.tools.length),copy:go(t.tools),on_copy:e.on_copy,children:s.jsx("ul",{className:"rs_tools",children:t.tools.map(r=>s.jsxs("li",{children:[s.jsx("strong",{className:"mono",children:r.name}),r.description?s.jsxs("span",{children:[" — ",r.description]}):null]},r.name))})}):null,s.jsxs(wa,{title:"Response",meta:t.tool_calls.length?`${t.tool_calls.length} tool call${t.tool_calls.length===1?"":"s"}`:t.response?Iy(t.response.length):"empty",copy:t.response||go(t.tool_calls),open:!0,on_copy:e.on_copy,children:[t.response?s.jsx("div",{className:"rs_markdown",children:s.jsx(Si,{text:t.response})}):null,t.tool_calls.map((r,i)=>s.jsx("pre",{className:"rs_text mono",children:`${r.name}(${go(r.arguments)})`},i)),!t.response&&!t.tool_calls.length?s.jsx("p",{className:"rs_muted",children:"No text and no tool call."}):null]}),t.reasoning?s.jsx(wa,{title:"Reasoning",meta:Iy(t.reasoning.length),copy:t.reasoning,on_copy:e.on_copy,children:s.jsx("pre",{className:"rs_text",children:t.reasoning})}):null,s.jsx(ox,{step:e.step,on_copy:e.on_copy})]})}function WI(e){const t=Nm(e.step);return s.jsxs(s.Fragment,{children:[s.jsx(wa,{title:"Calls",meta:String(t.calls.length),copy:go(t.calls),open:!0,on_copy:e.on_copy,children:t.calls.map((n,r)=>s.jsx("pre",{className:"rs_text mono",children:`${n.name}(${go(n.arguments)})`},r))}),s.jsxs(wa,{title:"Results",meta:String(t.results.length),copy:go(t.results),open:!0,on_copy:e.on_copy,children:[t.results.length?null:s.jsx("p",{className:"rs_muted",children:"No result recorded yet."}),s.jsx("ol",{className:"rs_messages",children:t.results.map((n,r)=>s.jsxs("li",{className:`rs_msg ${n.success===!1?"rs_msg_failed":""}`,children:[s.jsxs("span",{className:"rs_role",children:[n.name," · ",n.success===!1?"failed":n.success?"ok":"unknown"]}),s.jsx(aN,{sandbox:qw(n.raw),className:"rs_sandbox"}),n.error?s.jsx("pre",{className:"rs_text",children:n.error}):null,n.output?s.jsx("pre",{className:"rs_text",children:n.output}):null]},r))})]}),s.jsx(ox,{step:e.step,on_copy:e.on_copy})]})}function qI(e){var i,o,u;const t=e.step.record||{},n=((o=(i=e.step.started)==null?void 0:i.effect)==null?void 0:o.payload)??((u=t==null?void 0:t.effect)==null?void 0:u.payload),r=e.step.kind==="subflow"?$m(t):"";return s.jsxs(s.Fragment,{children:[r&&e.on_open_run?s.jsxs("p",{className:"rs_line_actions",children:[s.jsx("span",{className:"mono",children:r}),s.jsx("button",{type:"button",className:"btn btn_sm",onClick:()=>{var l;return(l=e.on_open_run)==null?void 0:l.call(e,r)},children:"Open"})]}):null,t.error?s.jsx("pre",{className:"rs_text rs_error",children:typeof t.error=="string"?t.error:go(t.error)}):null,n!=null?s.jsx(wa,{title:"Payload",copy:go(n),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(fr,{value:n,collapseAfterDepth:2,showCopy:!1})})}):null,t.result!==void 0&&t.result!==null?s.jsx(wa,{title:"Result",copy:go(t.result),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(fr,{value:t.result,collapseAfterDepth:2,showCopy:!1})})}):null,s.jsx(ox,{step:e.step,on_copy:e.on_copy})]})}function HI(e){const t=e.step,n=MN(t),r=RN(t),i=t.failed&&t.status!=="failed"?"failed":t.status;return s.jsxs("article",{className:`rs_card ${t.failed?"rs_failed":""}`,"data-kind":t.kind,"data-step-id":t.step_id||void 0,children:[s.jsxs("button",{type:"button",className:"rs_card_head","aria-expanded":e.open,onClick:e.on_toggle,children:[s.jsx("span",{className:"rs_chevron","aria-hidden":"true",children:e.open?"▾":"▸"}),s.jsx("span",{className:"rs_kind",children:mI[t.kind]}),s.jsx("span",{className:"rs_node",children:e.node_label||t.node_id||t.effect_type||"step"}),s.jsx("span",{className:`rs_status ${ka(i)}`,children:i||"—"}),s.jsx("span",{className:"rs_dur",children:t.duration_ms!==null?vu(t.duration_ms):""}),r?s.jsx("span",{className:"rs_detail",children:r}):null,n?s.jsx("span",{className:"rs_line",children:n}):null]}),e.open?s.jsx("div",{className:"rs_card_body",children:t.kind==="llm_call"?s.jsx(UI,{step:t,on_copy:e.on_copy}):t.kind==="tool"?s.jsx(WI,{step:t,on_copy:e.on_copy}):s.jsx(qI,{step:t,on_copy:e.on_copy,on_open_run:e.on_open_run})}):null]})}function VI(e){const{state:t}=e,n=p.useMemo(()=>Mg(e.items,e.run_id),[e.items,e.run_id]),[r,i]=p.useState({}),o=b=>e.node_label(b.run_id,b.node_id),u=p.useMemo(()=>new Map,[n]),d=CI(n,t,b=>{let k=u.get(b.id);return k===void 0&&(k=RI(b,o(b)),u.set(b.id,k)),k}),h=n.some(b=>b.kind==="llm_call"),m=n.reduce((b,k)=>k.kind==="llm_call"?b+1:b,0),_=n.length-d.length,g=b=>e.on_state({...t,...b}),y=b=>s.jsx(HI,{step:b,node_label:o(b),open:r[b.id]===!0,on_toggle:()=>i(k=>({...k,[b.id]:!k[b.id]})),on_copy:e.on_copy,on_open_run:e.on_open_run},b.id);return s.jsxs("div",{className:"rs_view",children:[s.jsxs("div",{className:"rs_count",children:[s.jsxs("span",{children:[d.length," of ",n.length," steps",h?` · ${m} cycle${m===1?"":"s"}`:"",_&&t.only==="all"&&!t.all_steps&&!t.q?` · ${_} housekeeping hidden`:""]}),e.run_options.length>1?s.jsx("select",{className:"seg_select mono",value:e.run_id,onChange:b=>e.on_select_run(String(b.target.value||"")),"aria-label":"Run",children:e.run_options.map(b=>s.jsxs("option",{value:b,children:[Rn(b,14),e.run_llm_counts[b]?` · ${e.run_llm_counts[b]} LLM`:""]},b))}):null]}),s.jsxs("div",{className:"rs_toolbar",children:[s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Layout",children:["cycles","steps"].map(b=>s.jsx("button",{type:"button",role:"radio","aria-checked":t.view===b,className:`seg_btn ${t.view===b?"active":""}`,onClick:()=>g({view:b}),children:b==="cycles"?"Cycles":"Steps"},b))}),s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Show",children:["all","llm","tools","failed"].map(b=>s.jsx("button",{type:"button",role:"radio","data-filter":b,"aria-checked":t.only===b,className:`seg_btn ${t.only===b?"active":""}`,onClick:()=>g({only:b}),children:BI[b]},b))}),s.jsx("input",{className:"rs_search",type:"search",value:t.q,onChange:b=>g({q:b.target.value}),placeholder:"Search steps","aria-label":"Search steps",autoComplete:"off",spellCheck:!1}),t.only==="all"?s.jsx(Di,{label:"All steps",action:"show-all-steps",hint:"Also list status events, waits, resumes and memory bookkeeping.",checked:t.all_steps,onChange:b=>g({all_steps:b})}):null]}),n.length?null:s.jsx("p",{className:"rs_muted",children:"No steps recorded for this run yet."}),n.length&&!d.length?s.jsx("p",{className:"rs_muted",children:"No step matches."}):null,t.view==="cycles"&&h?NI(d).map(b=>s.jsxs("section",{className:"rs_cycle","data-cycle":b.cycle,children:[s.jsx("h3",{className:"rs_cycle_head",children:b.cycle===0?"Before the first call":`Cycle ${b.cycle}`}),b.steps.map(y)]},b.cycle)):d.map(y)]})}function GI(e){const[t,n]=p.useState(!1),r=e.answer.length>u0,i=t||!r?e.answer:`${e.answer.slice(0,u0).trimEnd()}…`;return s.jsxs("section",{className:"rs_outcome","aria-label":"Run summary",children:[s.jsxs("p",{className:"rs_outcome_facts",children:[s.jsx("span",{className:`rs_status ${ka(e.status)}`,children:e.status||"unknown"}),[e.duration,e.facts].filter(Boolean).join(" · ")]}),e.error?s.jsx("p",{className:"rs_text rs_error",children:e.error}):null,!e.error&&e.answer?s.jsxs("div",{className:"rs_markdown rs_outcome_text",children:[s.jsx(Si,{text:i}),r?s.jsx("button",{type:"button",className:"rs_link","aria-expanded":t,onClick:()=>n(o=>!o),children:t?"Less":"More"}):null]}):null,s.jsxs("div",{className:"rs_outcome_actions",children:[e.waiting_for_user&&e.on_answer_wait?s.jsx("button",{type:"button",className:"btn primary",onClick:e.on_answer_wait,children:"Answer"}):null,e.speak,s.jsx("button",{type:"button",className:"btn",onClick:e.on_open_artifacts,title:"This run's artifacts in System",children:"Artifacts"}),e.workspace_root?s.jsx("button",{type:"button",className:"btn",onClick:e.on_reveal_workspace,title:e.workspace_root,children:"Folder"}):null]})]})}const u0=600;let Ep={connections:null,mailboxes:null};const KI=new Set;function JI(e){if(!(e.connections===Ep.connections&&e.mailboxes===Ep.mailboxes)){Ep={connections:e.connections,mailboxes:e.mailboxes};for(const t of KI)t()}}function YI(e,t,n=Ep){return!e||typeof e!="object"?"":vm(e,n.connections,n.mailboxes,t)}const d0="—";function vd(e){return typeof e=="string"&&e?e:void 0}function XI(e){return e.endsWith("+00:00")||e.endsWith("Z")}function Oy(e){if(!e||typeof e!="object")return e;const t=e,n={...e},r=vd(t.next_run_at)??vd(t.next_fire_at);let i=vd(t.next_run_local),o=vd(t.time_zone)??"";return!i&&!o&&r&&XI(r)&&(i=r,o="UTC"),r?n.next_run_at=r:delete n.next_run_at,i?n.next_run_local=i:delete n.next_run_local,n.time_zone=o,n.schedule_rule_text=vd(t.schedule_rule_text)??d0,n.schedule_text=vd(t.schedule_text)??d0,n}function ZI(e){return{...e,listAutomations:async t=>{const n=await e.listAutomations(t);return{...n,items:(n.items??[]).map(Oy)}},getAutomation:async t=>{const n=await e.getAutomation(t);return n!=null&&n.summary?{...n,summary:Oy(n.summary)}:n},createAutomation:async t=>{const n=await e.createAutomation(t);return n!=null&&n.summary?{...n,summary:Oy(n.summary)}:n}}}const QI="@default:",Fd="abstractcode.agent.v1";function f0(e,t){var n;return e?e.kind==="default"?e.interface===Fd?"@default":"":((n=t.find(r=>r.bundleId===e.bundle_id&&r.flowId===e.flow_id))==null?void 0:n.value)??"":""}function e3(e,t){return e==="@default"?{kind:"default",interface:Fd}:t?{kind:"bundle",bundle_id:t.bundleId,flow_id:t.flowId}:null}function t3(e){return e?e.kind==="default"?`${QI}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function n3(e,t,n){if(!e)return null;if(e.kind==="default")return{flow_id:"@default",interface:e.interface,input_data:n};const r=String(t(e.bundle_id)||"").trim();if(!r)throw new Error(`The gateway listed no bundle_ref for bundle "${e.bundle_id}". Reload bundles, then try again.`);return{bundle_ref:r,flow_id:e.flow_id,input_data:n}}function s3(e){const t={};for(const[n,r]of Object.entries(e||{}))if(typeof r=="string"){const i=r.trim();i&&(t[n]=i)}else r!==void 0&&(t[n]=r);return t}const r3={once:"Run once: start this flow now, a single run you can watch in Observe.",automate:"Automate: the flow runs by itself — with its own trigger, on a schedule, when something arrives (mail, a feed, a webhook), or by hand; manage it on the Automations page."};function i3(e){const t=String(e||"").trim();if(!t)return null;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}/console#users`}catch{return null}}const o3="#launch/automate";function a3(e){const t=CN(String(e||""));if(t)return{page:"run",run_id:t};const n=String(e||"").replace(/^#\/?/,"");if(n==="automations")return{page:"automations"};const r=/^launch(?:\/(once|automate))?$/.exec(n);return r?{page:"launch",mode:r[1]||"once"}:null}const Yw={when:"every",email_account:"default",connection_id:"",calendar:TS,email:dS,notify_email:!1,email_recipients:Hh,amount:"24",unit:"h",once_at:"",context:"independent",growing_max_tokens:String(Zh),tool_approval:"auto",title:"",start_at:"",count:"",until:""},h0={independent:"Each run starts fresh in its own conversation. Runs never see each other.",growing:"Each run is a new turn of one conversation and sees the previous runs. The most recent whole turns are replayed within your token budget; older runs drop out. The newest turn is kept whole even if it exceeds the budget."},LN=["use_context"],l3="This choice also tells the flow whether to read the earlier runs.",IN=["event"];function c3(e,t,n){if(!e||typeof e!="object")return null;const r=String(e.bundle_id||"").trim();if(r&&r!==String(t||"").trim())return null;const i=e.automation_defaults&&typeof e.automation_defaults=="object"?e.automation_defaults[String(n||"").trim()]:null;if(!i||typeof i!="object")return null;const o=i.trigger;return!o||typeof o!="object"||typeof o.source_id!="string"||typeof o.source_version!="number"?null:i}function ON(e){const t={...e.trigger.config||{}};return e.trigger.connection_id&&!t.connection_id&&(t.connection_id=e.trigger.connection_id),{source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:t}}function u3(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:!0}function d3(e,t,n){var l,d,h;const r=((l=n.context)==null?void 0:l.mode)==="growing"?"growing":"independent",i=(h=(d=n.context)==null?void 0:d.growing)==null?void 0:h.max_tokens,o={...e,when:"defaults",context:r,...typeof i=="number"&&i>0?{growing_max_tokens:String(i)}:{},...!e.title.trim()&&typeof n.title=="string"&&n.title.trim()?{title:n.title.trim()}:{}},u={...n.input_data||{}};for(const[m,_]of Object.entries(t||{}))u3(_)&&(u[m]=_);return{form:o,input_data:u}}function f3(e,t){return e.interfaces.length?null:e.automationTrigger?[vm(e.automationTrigger,t.connections,t.mailboxes),e.bundleVersion?`@${e.bundleVersion}`:""].filter(Boolean).join(" · "):e.triggerable?["Runs by itself",e.bundleVersion?`@${e.bundleVersion}`:""].filter(Boolean).join(" · "):null}function PN(e){return[...e||[]].filter(t=>t.configured!==!1&&t.can_read!==!1).sort((t,n)=>Number(n.primary)-Number(t.primary))}function h3(e){const t=e.last_error&&typeof e.last_error=="object"?e.last_error:null;if(t){const n=i=>typeof t[i]=="string"?String(t[i]).trim():"";return`not working: ${n("cause")||n("message")||n("code")||"it failed"}${n("fix")?` ${n("fix")}`:""}`.trim()}return e.paused===!0||e.status==="paused"?"paused":""}function m3(e,t){const n=[];for(const r of PN(e))n.push({value:`mail:${r.account_id}`,label:`Mail arrives in ${jg(r.account_id,e)}`,group:"mail",problem:""});for(const r of t||[]){if(r.status&&r.status!=="active"&&r.status!=="paused")continue;const i=rS(r.label||"a connection",r.source_id),o=h3(r);n.push({value:`conn:${r.connection_id}`,label:`${i.replace(/^When /,"")}${o?` — ${o.startsWith("not working")?"not working":o}`:""}`,group:wm(r.source_id),problem:o})}return n}function Yc(e){return e.when==="email"?`mail:${e.email_account||"default"}`:e.when==="connection"&&e.connection_id?`conn:${e.connection_id}`:""}function m0(e){return e.startsWith("mail:")?{when:"email",email_account:e.slice(5)||"default"}:e.startsWith("conn:")?{when:"connection",connection_id:e.slice(5)}:{}}function ax(e,t,n=!1){const r=e.when==="every",i=e.when==="daily"||e.when==="weekly"||e.when==="monthly";return{prompt:t,when:e.when==="once"?{kind:"once",at:e.once_at}:i?Xv(e.when,e.calendar):{kind:"every",amount:Number(e.amount),unit:e.unit},...n&&e.when==="email"?{trigger:"email",email:e.email}:{},...n&&e.notify_email?{notifyEmail:!0}:{},...n&&e.email_recipients.mode==="list"?{emailRecipients:e.email_recipients}:{},context:e.context,growingMaxTokens:Number(e.growing_max_tokens),toolApproval:e.tool_approval,title:e.title,...r&&e.start_at?{startAt:e.start_at}:{},...(r||i)&&e.count.trim()?{count:Number(e.count)}:{},...(r||i)&&e.until?{until:e.until}:{}}}function _3(e,t){if(e.when==="defaults")return t&&t.trigger.source_id==="schedule"?ON(t):null;if(e.when==="email"||e.when==="connection"||e.when==="manual")return null;const n=ax(e,"preview");return zA(n.when)?CS(n).trigger:null}function p3(e,t){if(t.input_data===null)return{ok:!1,errors:["The inputs are not valid JSON."]};const n=String(e.email_account||"default").trim()||"default",r=t.mailboxes?PN(t.mailboxes).some(g=>g.account_id===n||n==="default"&&g.primary):n==="default"&&t.email_usable===!0;if(e.when==="email"&&!r)return{ok:!1,errors:[Nn.not_set_up]};if(e.when==="defaults"&&!t.defaults)return{ok:!1,errors:["This flow has no trigger of its own: choose Other trigger…."]};let i=null;if(e.when==="connection"&&(i=(t.connections||[]).find(g=>g.connection_id===e.connection_id)??null,!i))return{ok:!1,errors:["Choose what to listen to under When something arrives."]};const o=s3(t.input_data),u=typeof o.prompt=="string"?o.prompt:"";delete o.prompt;for(const g of LN)delete o[g];for(const g of IN)delete o[g];delete o.workspace_root;let l;try{l=n3(t.choice,t.bundle_ref_for,o)}catch(g){return{ok:!1,errors:[String((g==null?void 0:g.message)||g)]}}const d=e.when==="defaults"||e.when==="connection"||e.when==="manual",h=ax(d?{...e,when:"every",amount:"24",unit:"h",start_at:"",count:"",until:""}:e,u,t.email_usable===!0||e.when==="email"&&r),m=ES(h,{target:l,requestId:t.request_id});if(!m.ok)return m;const _=m.body;return e.when==="defaults"&&t.defaults?_.trigger=ON(t.defaults):e.when==="connection"&&i?_.trigger={source_id:i.source_id,source_version:i.source_version,config:{connection_id:i.connection_id}}:e.when==="manual"?_.trigger={source_id:"manual",source_version:1,config:{}}:e.when==="email"&&n!=="default"&&(_.trigger={..._.trigger,config:{..._.trigger.config,account:n}}),{ok:!0,body:_}}function g3(e,t=!1){if(e.when==="email"){if(!t)return"";const n=ES(ax(e,"preview",!0),{target:{flow_id:"@default",interface:Fd},requestId:"preview"});return n.ok?`Runs ${hS(n.body.trigger.config)}.`:""}return""}class y3{constructor(t){kn(this,"key","");kn(this,"id","");this.mint=t}id_for(t){return(!this.id||t!==this.key)&&(this.key=t,this.id=this.mint()),this.id}reset(){this.key="",this.id=""}}function w3(e,t,n){const r=p3(e,{...t,request_id:""});if(!r.ok)return r;const{request_id:i,...o}=r.body,u=n.id_for(JSON.stringify(o));return{ok:!0,body:{...r.body,request_id:u}}}function ma(e){return typeof e=="string"?e:e??null}function sp(e){var t,n,r,i,o,u;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:ma(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:ma(e==null?void 0:e.created_at),updated_at:ma(e==null?void 0:e.updated_at),ledger_len:typeof(e==null?void 0:e.ledger_len)=="number"?Number(e.ledger_len):(e==null?void 0:e.ledger_len)??null,parent_run_id:ma(e==null?void 0:e.parent_run_id),session_id:ma(e==null?void 0:e.session_id),actor_id:ma(e==null?void 0:e.actor_id),session_kind:ma(e==null?void 0:e.session_kind),automation_id:ma(e==null?void 0:e.automation_id),role:ma(e==null?void 0:e.role),occurrence_index:typeof(e==null?void 0:e.occurrence_index)=="number"?Number(e.occurrence_index):null,is_scheduled:typeof(e==null?void 0:e.is_scheduled)=="boolean"?!!e.is_scheduled:(e==null?void 0:e.is_scheduled)??null,paused:typeof(e==null?void 0:e.paused)=="boolean"?!!e.paused:(e==null?void 0:e.paused)??null,pause_reason:ma(e==null?void 0:e.pause_reason),is_draft:(e==null?void 0:e.is_draft)===!0,waiting_reason:typeof((t=e==null?void 0:e.waiting)==null?void 0:t.reason)=="string"?String(e.waiting.reason):((n=e==null?void 0:e.waiting)==null?void 0:n.reason)??null,schedule_interval:typeof((r=e==null?void 0:e.schedule)==null?void 0:r.interval)=="string"?String(e.schedule.interval).trim():((i=e==null?void 0:e.schedule)==null?void 0:i.interval)??null,schedule_target_workflow_id:typeof((o=e==null?void 0:e.schedule)==null?void 0:o.target_workflow_id)=="string"?String(e.schedule.target_workflow_id).trim():((u=e==null?void 0:e.schedule)==null?void 0:u.target_workflow_id)??null,current_node:typeof(e==null?void 0:e.current_node)=="string"?String(e.current_node).trim():(e==null?void 0:e.current_node)??null,llm_calls:typeof(e==null?void 0:e.llm_calls)=="number"?Number(e.llm_calls):(e==null?void 0:e.llm_calls)??null,tool_calls:typeof(e==null?void 0:e.tool_calls)=="number"?Number(e.tool_calls):(e==null?void 0:e.tool_calls)??null,tokens_total:typeof(e==null?void 0:e.tokens_total)=="number"?Number(e.tokens_total):(e==null?void 0:e.tokens_total)??null,error:(e==null?void 0:e.error)??null,waiting:(e==null?void 0:e.waiting)??null,archived:(e==null?void 0:e.archived)===!0}}function v3(e,t){const n=new Set(e.map(i=>String((i==null?void 0:i.run_id)||""))),r=[...e];for(const i of t){const o=String((i==null?void 0:i.run_id)||"");!o||n.has(o)||(n.add(o),r.push(i))}return r}function Rg(e){const t=String((e==null?void 0:e.role)||"").trim(),n=String((e==null?void 0:e.session_kind)||"").trim();return t==="controller"?"automation":t==="occurrence"||t==="descendant"||n==="occurrence"?"occurrence":t==="discussion"||n==="discussion"?"discussion":t==="legacy_schedule"||(e==null?void 0:e.is_scheduled)===!0?"legacy":null}function DN(e){const t=Rg(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`run #${e.occurrence_index}`:"automation run":t==="legacy"?"legacy schedule":t||""}function x3(e){var n,r,i;const t=(i=(r=(n=e==null?void 0:e.capabilities)==null?void 0:n.contracts)==null?void 0:r.common)==null?void 0:i.automations;return t&&typeof t=="object"&&t.available===!0?{available:!0,reason:""}:t&&typeof t=="object"&&t.available===!1?{available:!1,reason:"This gateway has the Automations API turned off."}:{available:!1,reason:"This gateway does not advertise the Automations API (capabilities.contracts.common.automations). Update AbstractGateway to use automations; legacy schedules stay manageable from their run view."}}function Za(e){return e.legacy===!0||e.capabilities.includes("legacy")}function FN(e,t=Date.now(),n){const r=Za(e),i=e.last_occurrence,o=i&&i.attempts>1?` after ${i.attempts} attempts`:"",u=e.attention.unread||e.attention.pending_waits>0,l=!r&&cc(e.trigger)&&e.status==="active"&&!e.next_run_at,d=l&&i?Yh(i.fired_at,{timeZone:e.time_zone,nowMs:t,style:"day"}):"";return{id:e.automation_id,title:e.title,cadence:Vv(e.trigger,e,n??null),next_run:l?"runs when something new arrives":gS(e,t),listening:l,current:pS(e),state:e.status,last:i?i.excerpt:"",last_status:i?`${d?`last: ${d} · `:""}#${i.index} ${i.status}${o}`:"no runs yet",attention:u?yS(e):null,legacy:r}}function zN(e){const t=e.last_occurrence;if(!t)return null;const r=["completed","failed","cancelled"].includes(String(t.status))?t.index:t.index-1;return r>=1?r:null}function b3(e,t){const n=Xh(e,[],t),r=zN(e),i=t?{enabled:!1,reason:"Working…"}:Za(e)?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:e.capabilities.includes("discuss")?r===null?{enabled:!1,reason:e.last_occurrence?"Available once the first run finishes.":"No occurrence to discuss yet."}:{enabled:!0,reason:`Discuss run #${r} in a new chat (a fork of this automation).`}:{enabled:!1,reason:"Not permitted for this automation."};return{active:n.active,pause:n.pause,resume:n.resume,run_now:n.run_now,edit:n.revise,archive:n.archive,discuss:i}}function k3(e,t){const n=o=>({enabled:!1,reason:o});if(t)return{legacy_pause:n("Working…"),legacy_resume:n("Working…"),legacy_run_now:n("Working…"),open_run:{enabled:!0},recreate:n("Working…")};const r=e.status==="paused",i=e.status==="active"||e.status==="paused";return{legacy_pause:r?n("Already suspended."):i?{enabled:!0}:n("The schedule has ended."),legacy_resume:r?{enabled:!0}:n(i?"Already running on schedule.":"The schedule has ended."),legacy_run_now:e.status==="active"?{enabled:!0}:n(r?"The schedule is off: switch Active on first.":"The schedule has ended."),open_run:{enabled:!0},recreate:{enabled:!0}}}function j3(e,t){return e==="legacy_pause"?{type:"pause",payload:{reason:"Suspended from the Observer's Automations page"}}:e==="legacy_resume"?{type:"resume",payload:{}}:{type:"resume",payload:{payload:{mode:"run_now",requested_at:t}}}}const S3=/^([1-9][0-9]*)([smhd])$/;function N3(e){if(typeof e!="string"||!e.trim())return"";const t=Date.parse(e);return Number.isNaN(t)?"":new Date(t).toISOString().slice(0,16)}function $3(e,t){const n=e!=null&&e.schedule&&typeof e.schedule=="object"?e.schedule:null;if(!n)throw new Error("This run carries no legacy schedule metadata; nothing to recreate.");const r=String(n.target_bundle_ref||"").trim(),i=String(n.target_host_bundle_id||n.target_bundle_id||(r.includes("@")?r.slice(0,r.lastIndexOf("@")):"")||(t==null?void 0:t.bundle_id)||"").trim(),o=String(n.target_flow_id||(t==null?void 0:t.flow_id)||"").trim();if(!i||!o)throw new Error("The legacy schedule does not name its target workflow.");const u=[],l={...Yw},d=typeof n.interval=="string"?n.interval.trim():"";if(!d)l.when="once",u.push("The legacy schedule ran once; pick the date and time to run.");else{const g=S3.exec(d);let y=g?Number(g[1]):0,b=g?g[2]:"";b==="s"&&y%60===0&&(y=y/60,b="m"),b==="m"||b==="h"||b==="d"?(l.amount=String(y),l.unit=b):u.push(`The legacy interval "${d}" is not a whole number of minutes, hours or days; choose an interval.`)}typeof n.repeat_count=="number"&&n.repeat_count>=1&&(l.count=String(n.repeat_count));const h=N3(n.repeat_until);h&&(l.until=h),l.context=n.share_context===!1?"independent":"growing";const m=t&&typeof t.input_data=="object"&&t.input_data&&!Array.isArray(t.input_data)?t.input_data:{},_={};for(const[g,y]of Object.entries(m))g==="workflow_selection"||g.startsWith("_")||(_[g]=y);return{choice:{kind:"bundle",bundle_id:i,flow_id:o},input_data:_,form:l,notes:u}}const C3={items:[],loaded:!1,loading:!1,list_error:null,error:null,refreshed_at:null,status_filter:"",show_archived:!1,selected_id:"",detail:null,trigger_sources:[],busy:!1,notice:"",confirm_archive_id:"",email_status:null,trigger_connections:null,mailboxes:null};function E3(e,t,n){var i;const r=(i=e.get_run_input_data)==null?void 0:i.bind(e);return{...r?{run_input_data:async o=>{const u=await r(o),l=u&&typeof u=="object"?u.input_data:null;return l&&typeof l=="object"&&!Array.isArray(l)?l:null}}:{},answer_wait:async(o,u,l)=>{await e.submit_command({command_id:t(),run_id:o,type:"resume",payload:{wait_key:u,payload:l},client_id:"web_pwa"})},legacy_command:async(o,u,l)=>{await e.submit_command({command_id:t(),run_id:o,type:u,payload:l,client_id:"web_pwa"})},now_iso:n}}function A3(e,t){if(e==="ask_user"){if(typeof t.response!="string")throw new Error("An ask_user wait is answered with {response: string}.");return{response:t.response}}if(e==="tool_approval"){if(typeof t.approved!="boolean")throw new Error("A tool_approval wait is answered with {approved: true|false}.");const n=t.tool_ids;if(n!==void 0&&!(Array.isArray(n)&&n.every(r=>typeof r=="string")))throw new Error("tool_ids must be a list of strings.");return{approved:t.approved,...n!==void 0?{tool_ids:n}:{}}}if(e==="event"){if(!("payload"in t))throw new Error("An event wait is answered with {payload}.");return{payload:t.payload}}throw new Error(`This wait has no known kind (${JSON.stringify(e)}); the gateway must type its waits (ask_user, tool_approval, event).`)}function Py(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function _0(e){return e.items.filter(t=>t.status==="archived").length}function lx(e,t){return`A conversation about run #${e} started. It works in its own folder; it can read the automation's files but not change them (shell commands are not sandboxed), and nothing is written back into the automation.`}const T3=3e4,rp=50;function Oi(e){return Jv(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function Dy(e,t){const n=new Map;for(const r of e)n.set(r.run_id,r);for(const r of t)n.set(r.run_id,r);return Array.from(n.values()).sort((r,i)=>i.index-r.index)}class M3{constructor(t,n,r=[1500,4e3]){kn(this,"state",{...C3});kn(this,"listeners",new Set);kn(this,"list_seq",0);kn(this,"detail_seq",0);kn(this,"sources_loaded",!1);kn(this,"client");kn(this,"preview_schedule",t=>this.client.previewSchedule(t));kn(this,"events_inflight",new Set);kn(this,"definitions",new Map);this.host=n,this.followups_ms=r,this.client=ZI(t)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}set(t){this.state={...this.state,...t};for(const n of this.listeners)n()}async list_all(){const t=[];let n;for(let r=0;r<200;r+=1){const i=await this.client.listAutomations({...this.state.status_filter?{status:this.state.status_filter}:{},...n?{cursor:n}:{},limit:rp});if(t.push(...i.items),!i.next_cursor)return t;n=i.next_cursor}throw new Error("GET /api/gateway/automations kept returning next_cursor after 200 pages.")}async load_trigger_vocab(){const[t,n]=await Promise.all([this.client.listTriggerConnections?this.client.listTriggerConnections().then(o=>Array.isArray(o==null?void 0:o.connections)?o.connections:null,()=>null):Promise.resolve(null),this.client.listMailboxes?this.client.listMailboxes().then(o=>Array.isArray(o==null?void 0:o.items)?o.items:null,()=>null):Promise.resolve(null)]),r=t??this.state.trigger_connections,i=n??this.state.mailboxes;JI({connections:r,mailboxes:i}),this.set({trigger_connections:r,mailboxes:i})}async load_email_status(){try{const t=await this.client.getMyEmail();this.set({email_status:t&&typeof t=="object"?t:null})}catch{this.set({email_status:null})}}get email_usable(){return Ng(this.state.email_status)}async refresh(){const t=++this.list_seq;this.set({loading:!0});try{const n=await this.list_all();if(this.load_email_status(),this.load_trigger_vocab(),t!==this.list_seq)return;const r=this.state.detail,i=r?n.find(o=>o.automation_id===r.automation_id):void 0;this.set({items:n,loaded:!0,loading:!1,list_error:null,refreshed_at:Date.now(),...r&&i?{detail:{...r,summary:i}}:{}}),r&&await this.reload_occurrences(r.automation_id)}catch(n){if(t!==this.list_seq)return;this.set({loading:!1,loaded:!0,list_error:Oi(n)})}}async set_status_filter(t){this.set({status_filter:t}),await this.refresh()}async load_trigger_sources(){if(this.sources_loaded)return;const t=await this.client.listTriggerSources();this.sources_loaded=!0,this.set({trigger_sources:t.items})}async select(t){var i;const n=String(t||"").trim(),r=++this.detail_seq;if(!n){this.set({selected_id:"",detail:null});return}this.set({selected_id:n,notice:"",...((i=this.state.detail)==null?void 0:i.automation_id)!==n?{detail:null}:{}});try{const o=this.state.items.find(d=>d.automation_id===n);if(o&&Za(o)){this.set({detail:{automation_id:n,summary:o,definition:null,occurrences:[],next_cursor:null,error:null,occurrence_events:{}}});return}const[u,l]=await Promise.all([this.client.getAutomation(n),this.client.listOccurrences(n,{limit:rp})]);if(r!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:o??u.summary,definition:u.definition,occurrences:Dy([],l.items),next_cursor:l.next_cursor,error:null,occurrence_events:{}}}),this.load_occurrence_events(n),await this.load_trigger_sources()}catch(o){if(r!==this.detail_seq)return;this.set({error:Oi(o)})}}async reload_occurrences(t){const n=this.state.detail;if(!n||n.automation_id!==t||Za(n.summary))return;const[r,i]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:rp})]),o=this.state.detail;if(!o||o.automation_id!==t)return;const u=this.state.items.find(l=>l.automation_id===t);this.set({detail:{...o,summary:u??r.summary,definition:r.definition,occurrences:Dy(o.occurrences,i.items),next_cursor:o.occurrences.length>i.items.length?o.next_cursor:i.next_cursor}}),this.load_occurrence_events(t)}async load_occurrence_events(t){const n=this.state.detail,r=this.host.run_input_data;if(!r||!n||n.automation_id!==t||Za(n.summary)||!cc(n.summary.trigger))return;const i=n.occurrences.map(l=>l.run_id).filter(l=>l&&!(l in n.occurrence_events)&&!this.events_inflight.has(l));if(!i.length)return;for(const l of i)this.events_inflight.add(l);const o={};try{await Promise.all(i.map(async l=>{try{const d=await r(l);o[l]=d&&typeof d=="object"&&"event"in d?d.event:null}catch{o[l]=null}}))}finally{for(const l of i)this.events_inflight.delete(l)}const u=this.state.detail;!u||u.automation_id!==t||this.set({detail:{...u,occurrence_events:{...u.occurrence_events,...o}}})}async load_more(){const t=this.state.detail;if(!(!t||!t.next_cursor))try{const n=await this.client.listOccurrences(t.automation_id,{cursor:t.next_cursor,limit:rp}),r=this.state.detail;if(!r||r.automation_id!==t.automation_id)return;this.set({detail:{...r,occurrences:Dy(r.occurrences,n.items),next_cursor:n.next_cursor}}),this.load_occurrence_events(t.automation_id)}catch(n){this.set({error:Oi(n)})}}async after_change(t){await this.refresh();for(const n of this.followups_ms)setTimeout(()=>void this.refresh(),n)}async command(t,n,r,i){this.set({busy:!0});try{const o=await this.client.sendAutomationCommand(t,{type:n,...r?{payload:r}:{},...i?{command_id:i}:{}});return await this.after_change(t),o}catch(o){throw Oi(o)}finally{this.set({busy:!1})}}async revise(t,n,r,i){this.set({busy:!0});try{const o=await this.client.reviseAutomation(t,{changes:n,...r!==null?{expected_revision:r}:{},...i?{command_id:i}:{}});return await this.after_change(t),o}catch(o){throw Oi(o)}finally{this.set({busy:!1})}}definition(t){if(Za(t))return Promise.resolve(null);const n=t.automation_id,r=this.state.detail;if(r&&r.automation_id===n&&r.definition&&r.definition.revision===t.revision)return Promise.resolve(r.definition);const i=this.definitions.get(n);if(i&&i.revision===t.revision)return i.answer;const o=this.client.getAutomation(n).then(u=>u.definition??null);return o.catch(()=>this.definitions.delete(n)),this.definitions.set(n,{revision:t.revision,answer:o}),o}async discuss(t,n,r,i){this.set({busy:!0});try{const o=await this.client.discuss(t,{occurrence_index:n,prompt:r,...i?{request_id:i}:{}});return this.set({notice:lx(n,o)}),o}catch(o){throw Oi(o)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(r){throw Oi(r)}}async answer_wait(t,n,r,i){var o;this.set({busy:!0});try{const u=(((o=this.state.detail)==null?void 0:o.occurrences)||[]).flatMap(l=>l.waits).find(l=>l.run_id===n&&l.wait_key===r);if(!u)throw new Error(`No loaded wait ${r} on run ${n}; reload the automation.`);await this.host.answer_wait(n,r,A3(u.kind,i)),await this.after_change(t)}catch(u){throw Oi(u)}finally{this.set({busy:!1})}}async row_action(t,n){const r=`automation.${n}`;this.set({error:null,notice:""});try{await this.command(t.automation_id,r),this.set({notice:n==="run_now"&&t.status==="paused"?`Run now sent to “${t.title}”; it stays paused.`:n==="pause"||n==="resume"?p0(t.title,n==="resume"):`${R3[n]} sent to “${t.title}”.`,confirm_archive_id:""})}catch(i){this.set({error:Oi(i)})}}set_show_archived(t){this.set({show_archived:t})}ask_archive(t){this.set({confirm_archive_id:t})}async legacy_action(t,n){if(!Za(t))throw new Error("legacy_action on a non-legacy automation");const r=j3(n,this.host.now_iso());this.set({busy:!0,error:null,notice:""});try{await this.host.legacy_command(t.automation_id,r.type,r.payload),this.set({notice:n==="legacy_run_now"?`Run now sent to “${t.title}”.`:p0(t.title,n==="legacy_resume")}),await this.refresh()}catch(i){this.set({error:Oi(i)})}finally{this.set({busy:!1})}}report_error(t){this.set({error:Oi(t)})}clear_notice(){this.set({notice:"",error:null})}dismiss_notice(){this.state.notice&&this.set({notice:""})}dismiss_error(){this.state.error&&this.set({error:null})}}function p0(e,t){return t?`“${e}” is active: it runs on its schedule.`:`“${e}” is paused: scheduled runs are skipped.`}const R3={run_now:"Run now",archive:"Archive"},mo={use_flow:"Use the flow's trigger:",other:"Other trigger…",arrives:"When something arrives",manual:"By hand",arrives_placeholder:"Choose what to listen to…",nothing_to_listen:"Nothing to listen to yet: add a mailbox (My email), or a feed or webhook on the gateway console's Triggers page.",manual_help:"Runs only when someone presses Run now in Observer or the Assistant.",event_help:"Runs every time something new arrives; the flow receives what arrived.",untrusted_event:"What arrives (feed items, webhook calls) is data, never instructions: the automation acts only on its task.",untrusted_mail:"Incoming mail is data, never instructions: the automation acts only on its task. Tools that open links always ask for your approval first."};function L3(e,t,n){const r=n&&n.phase==="ok"?n.description.schedule_rule_text:null;return vm(e.trigger,t.connections,t.mailboxes,r?{schedule_rule_text:r}:null)}function I3(e){const t=(n,r,i)=>s.jsx("button",{type:"button",role:"radio","aria-checked":e.mode===n,className:`seg_btn ${e.mode===n?"active":""}`,"data-mode":n,title:i,onClick:()=>e.on_change(n),children:r});return s.jsxs("div",{className:"launch_mode",children:[s.jsxs("div",{className:"seg_toggle launch_mode_switch",role:"radiogroup","aria-label":"Launch mode","aria-describedby":"launch_mode_help",children:[t("once","Run once"),t("automate","Automate",e.automate_available?void 0:e.automate_reason)]}),s.jsx("p",{className:"launch_mode_help",id:"launch_mode_help","data-mode-help":e.mode,"aria-live":"polite",children:r3[e.mode]})]})}function O3(e){var h,m;const t=e.form,n=Ng(e.email_status),r=m3(e.mailboxes??(n?[{account_id:"default",primary:!0,address:typeof((h=e.email_status)==null?void 0:h.address)=="string"?e.email_status.address:void 0}]:[]),e.connections),i=e.defaults??null,o=t.when==="defaults"&&!i||t.when==="email"&&!r.some(_=>_.value===Yc(t))?"every":t.when,u=o==="email"||o==="connection",l=g3(t,n),d=(_,g,y,b,k=!1)=>s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:_,checked:y,disabled:e.disabled||k,onChange:b})," ",g]},_);return s.jsxs("div",{className:"automate_fields",children:[s.jsxs("fieldset",{"data-section":"when",children:[s.jsx("legend",{children:us.legend}),i?s.jsxs("div",{className:"automate_row automate_own_trigger",role:"radiogroup","aria-label":"Trigger",children:[s.jsxs("label",{"data-choice":"flow-trigger",children:[s.jsx("input",{type:"radio",name:"automate_own",value:"defaults",checked:o==="defaults",disabled:e.disabled,onChange:()=>e.on_change({when:"defaults"})})," ",mo.use_flow," ",s.jsx("strong",{"data-field":"flow-trigger",children:L3(i,{connections:e.connections,mailboxes:e.mailboxes},e.served)})]}),s.jsxs("label",{"data-choice":"other-trigger",children:[s.jsx("input",{type:"radio",name:"automate_own",value:"other",checked:o!=="defaults",disabled:e.disabled,onChange:()=>e.on_change({when:"every"})})," ",mo.other]})]}):null,o==="defaults"&&i?i.trigger.source_id==="schedule"?s.jsx("div",{className:"automate_preview automate_preview--served",children:s.jsx(Dw,{state:e.served,onOpenPreferences:e.on_open_preferences,showZone:!0})}):s.jsx("p",{className:"help_text muted","data-help":"flow-trigger",children:cc(i.trigger)?mo.event_help:i.trigger.source_id==="manual"?mo.manual_help:""}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"automate_row",role:"radiogroup","aria-label":"Schedule kind",children:[d("every",us.kind_every,o==="every",()=>e.on_change({when:"every"})),["daily","weekly","monthly"].map(_=>d(_,us[`kind_${_}`],o===_,()=>e.on_change({when:_}))),d("once",us.kind_once,o==="once",()=>e.on_change({when:"once"})),d("arrives",mo.arrives,u,()=>e.on_change(r.length?m0(r.some(_=>_.value===Yc(t))?Yc(t):r[0].value):{when:"connection",connection_id:""})),d("manual",mo.manual,o==="manual",()=>e.on_change({when:"manual"}))]}),u?r.length?s.jsxs("label",{className:"automate_row",children:[s.jsx("span",{className:"sr-only",children:"What to listen to"}),s.jsxs("select",{"data-field":"arrival","aria-label":"What to listen to",value:Yc(t),disabled:e.disabled,onChange:_=>e.on_change(m0(_.target.value)),children:[Yc(t)?null:s.jsx("option",{value:"",children:mo.arrives_placeholder}),r.map(_=>s.jsx("option",{value:_.value,"data-group":_.group,children:_.label},_.value))]})]}):s.jsxs("div",{className:"help_text",role:"note","data-note":"nothing-to-listen",children:[mo.nothing_to_listen,e.on_open_my_email?s.jsxs(s.Fragment,{children:[" ",s.jsx("button",{type:"button",className:"btn btn_sm","data-action":"open-my-email",onClick:e.on_open_my_email,children:"Open My email"})]}):null]}):null,u&&((m=r.find(_=>_.value===Yc(t)))!=null&&m.problem)?s.jsx("div",{className:"warn_callout",role:"note","data-note":"arrival-problem",children:`This one is ${r.find(_=>_.value===Yc(t)).problem}. It runs again once it reads; fix it on the gateway console's Triggers page.`}):null,o==="email"?s.jsx(vT,{value:t.email,onChange:_=>e.on_change({email:_}),disabled:e.disabled,idBase:"automate"}):o==="daily"||o==="weekly"||o==="monthly"?s.jsx(MS,{value:Xv(o,t.calendar),onChange:_=>e.on_change({calendar:Zv(t.calendar,_)}),idBase:"automate",disabled:e.disabled}):o==="every"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"automate_row",role:"group","aria-label":"Presets",children:OA.map(_=>_.when.kind==="every"?s.jsx("button",{type:"button",className:"btn btn_sm","data-preset":_.label,"aria-pressed":Number(t.amount)===_.when.amount&&t.unit===_.when.unit,disabled:e.disabled,onClick:()=>{_.when.kind==="every"&&e.on_change({amount:String(_.when.amount),unit:_.when.unit})},children:_.label},_.label):null)}),s.jsxs("div",{className:"automate_row",children:[s.jsx("span",{children:us.every_label}),s.jsx("input",{type:"number",min:1,step:1,value:t.amount,disabled:e.disabled,"aria-label":"Interval amount",onChange:_=>e.on_change({amount:_.target.value})}),s.jsxs("select",{value:t.unit,disabled:e.disabled,"aria-label":"Interval unit",onChange:_=>e.on_change({unit:_.target.value}),children:[s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"}),s.jsx("option",{value:"d",children:"days"})]})]})]}):o==="once"?s.jsxs("label",{className:"automate_row",children:[s.jsx("span",{children:us.once_label}),s.jsx("input",{type:"datetime-local",value:t.once_at,disabled:e.disabled,onChange:_=>e.on_change({once_at:_.target.value})})]}):null,o==="email"?l?s.jsx("div",{className:"automate_preview","aria-live":"polite","data-preview":"true",children:l}):null:o==="connection"?s.jsx("p",{className:"help_text muted","data-help":"arrives",children:mo.event_help}):o==="manual"?s.jsx("p",{className:"help_text muted","data-help":"manual",children:mo.manual_help}):s.jsx("div",{className:"automate_preview automate_preview--served",children:s.jsx(Dw,{state:e.served,onOpenPreferences:e.on_open_preferences,showZone:o!=="every"})})]})]}),s.jsxs("fieldset",{"data-section":"context",children:[s.jsx("legend",{children:"Context"}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_context",value:"independent",checked:t.context==="independent",disabled:e.disabled,onChange:()=>e.on_change({context:"independent"})})," ",s.jsx("strong",{children:"Independent"})," (default) — ",h0.independent]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_context",value:"growing",checked:t.context==="growing",disabled:e.disabled,onChange:()=>e.on_change({context:"growing"})})," ",s.jsx("strong",{children:"Growing"})," — ",h0.growing]}),t.context==="growing"?s.jsxs("label",{children:["Max growing context (tokens)",s.jsx("input",{type:"number",min:1,step:1,required:!0,value:t.growing_max_tokens,disabled:e.disabled,onChange:_=>e.on_change({growing_max_tokens:_.target.value})})]}):null,s.jsx("p",{className:"help_text muted","data-context-owns":"use_context",children:l3})]}),s.jsxs("fieldset",{"data-section":"tools",children:[s.jsx("legend",{children:"Tools"}),e.available_tools&&e.on_tools_change?s.jsx(LS,{availableTools:e.available_tools,value:e.tools??null,onChange:e.on_tools_change,disabled:e.disabled}):null,o==="email"||o==="defaults"&&i&&i.trigger.source_id.startsWith("email")?s.jsx("p",{className:"help_text muted","data-email-rule":"untrusted",children:mo.untrusted_mail}):o==="connection"||o==="defaults"&&i&&cc(i.trigger)?s.jsx("p",{className:"help_text muted","data-event-rule":"untrusted",children:mo.untrusted_event}):null,s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_tools",value:"auto",checked:t.tool_approval==="auto",disabled:e.disabled,onChange:()=>e.on_change({tool_approval:"auto"})})," ",BA,e.tools&&e.tools.length?s.jsxs("span",{className:"automate_preview",children:[" — ",e.tools.join(", ")]}):null]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_tools",value:"ask",checked:t.tool_approval==="ask",disabled:e.disabled,onChange:()=>e.on_change({tool_approval:"ask"})})," Ask each time — every tool call waits for your approval on the Automations page"]})]}),e.workspaces?s.jsx("div",{className:"automate_workspaces","data-section":"workspaces",role:"group","aria-label":"Workspaces",children:e.workspaces}):null,s.jsxs("fieldset",{"data-section":"email",children:[s.jsx("legend",{children:"Email"}),n?null:s.jsx(BS,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),s.jsx(xT,{notifyEmail:n&&t.notify_email,onNotifyEmailChange:_=>e.on_change({notify_email:_}),recipients:n?t.email_recipients:Hh,onRecipientsChange:_=>e.on_change({email_recipients:_}),disabled:e.disabled||!n,idBase:"automate"})]})]})}function g0(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toISOString().slice(0,16)}function y0(e){if(!e)return"";const t=new Date(`${e.length===16?`${e}:00`:e}Z`);if(Number.isNaN(t.getTime()))return e;const n=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function P3(e){const t=e.form;return s.jsx("div",{className:"automate_fields",children:s.jsxs("fieldset",{className:"automate_limits","data-section":"limits",children:[s.jsx("legend",{children:"Title and limits"}),s.jsxs("div",{className:"launch_grid",children:[s.jsxs("label",{className:"launch_grid_cell",style:{gridColumn:"1 / -1"},children:[s.jsx("span",{className:"launch_label",children:"Title"}),s.jsx("input",{value:t.title,maxLength:120,disabled:e.disabled,placeholder:"Defaults to the task's first line",onChange:n=>e.on_change({title:n.target.value})})]}),t.when==="every"||t.when==="daily"||t.when==="weekly"||t.when==="monthly"?s.jsxs(s.Fragment,{children:[t.when==="every"?s.jsxs("label",{className:"launch_grid_cell",children:[s.jsx("span",{className:"launch_label",children:"First run"}),s.jsx("input",{type:"datetime-local","aria-describedby":"automate_limits_help",value:y0(t.start_at),disabled:e.disabled,onChange:n=>e.on_change({start_at:g0(n.target.value)})})]}):null,s.jsxs("label",{className:"launch_grid_cell",children:[s.jsx("span",{className:"launch_label",children:"Stop after this many runs"}),s.jsx("input",{type:"number",min:1,step:1,value:t.count,disabled:e.disabled,onChange:n=>e.on_change({count:n.target.value})})]}),s.jsxs("label",{className:"launch_grid_cell",children:[s.jsx("span",{className:"launch_label",children:"Stop on"}),s.jsx("input",{type:"datetime-local","aria-describedby":"automate_limits_help",value:y0(t.until),disabled:e.disabled,onChange:n=>e.on_change({until:g0(n.target.value)})})]})]}):null]}),t.when==="every"||t.when==="daily"||t.when==="weekly"||t.when==="monthly"?s.jsx("p",{className:"help_text muted",id:"automate_limits_help","data-help":"limits",children:"All optional. Leave the first run empty to start now; times are in this browser's clock."}):null]})})}function D3(e,t){const n=String(t||"").trim();return n||`Loading ${String(e||"").trim()||"data"}…`}function rl(e){const t=D3(e.what,e.label),n=e.size==="block"?"block":"inline";return s.jsxs("div",{className:`af_loading af_loading_${n}${e.className?` ${e.className}`:""}`,role:"status","aria-live":"polite","aria-busy":"true",children:[s.jsx("span",{className:"af_loading_spin","aria-hidden":"true",children:s.jsx(qe,{name:"loader",size:n==="block"?20:16})}),s.jsx("span",{className:"af_loading_text",children:t})]})}const F3={console:"Console",tray:"Tray",watch:"Watch",phone:"Phone",email:"Email",assistant:"Assistant",code:"Code"};function z3(e){switch(e){case"empty title":return"Nothing to notify: the title was empty.";case"no notify":return"Nothing to notify: this flow has no Notify me step.";case"still running":return"Still running: nothing has been sent yet.";case"not recorded yet":return"Finished; the automation has not recorded what it sends yet.";default:return e?`Nothing was sent (${e}).`:"Nothing was sent."}}function B3(e){var n;const t=(n=e.trigger)==null?void 0:n.arrived;return t?t.line?`${t.count} ${t.noun}: ${t.line}`:`${t.count} ${t.noun}`:null}function U3(e){return e.title?`“${e.title}”`:e.from==="wait"?e.kind==="question"?"A question for you":"An approval for you":e.from==="email_when_done"?e.kind==="failure"?"It failed":"It finished":"Untitled"}function W3(e){return e.from==="wait"?e.open?"waiting for your answer":"answered":e.from==="email_when_done"?"Email me when done":e.from==="notify_me"?"Notify me":e.from==="failure"?"The run failed":e.from==="publish"?"Publish to channel, with Alert on":"On Flow End’s notify (older flows)"}function q3(e){const t=F3[e.channel]||e.channel,n=e.device_name?`${t} (${e.device_name})`:t,r=e.state==="failed";if(e.channel==="console")return`${n} · listed · ${r?"not listed":"sent"}`;const i=e.via==="push"?"push notification":e.via==="outbox"?"email":"shown by the app";return`${n} · ${i} · ${r?`not delivered${e.reason?`: ${e.reason}`:""}`:"sent"}`}const H3=3e3,V3=5;function G3(e,t){return t>V3?!1:e.quiet_reason==="not recorded yet"||e.quiet_reason==="still running"?!0:!!e.attention&&e.deliveries.length===0}function w0(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function K3(e){const t=e.state;return s.jsxs("section",{className:"after_run","data-section":"after-the-run","aria-label":"After the run",children:[s.jsx("div",{className:"after_run_title",children:"After the run"}),t.status==="loading"?s.jsx(rl,{what:"after the run",label:"Reading what happened after the run…"}):t.status==="failed"?s.jsxs("div",{className:"after_run_error",role:"alert",children:[s.jsxs("span",{children:["Could not read what happened after the run: ",t.error]}),t.on_retry?s.jsx("button",{type:"button",className:"btn btn_sm",onClick:t.on_retry,children:"Retry"}):null]}):s.jsx(J3,{after:t.after})]})}function J3(e){const t=e.after,n=B3(t),r=t.alerts&&t.alerts.length?t.alerts:t.attention?[t.attention]:[];return s.jsxs("dl",{className:"after_run_facts",children:[t.trigger&&n?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"What arrived"}),s.jsx("dd",{"data-field":"arrived",children:n})]}):null,t.run.note?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Note"}),s.jsx("dd",{"data-field":"note",children:t.run.note})]}):null,s.jsx("dt",{children:"Notified"}),s.jsx("dd",{"data-field":"notified",children:r.length?s.jsx("ul",{className:"after_run_alerts",children:r.map(i=>{const o=t.deliveries.filter(u=>!u.record_key||u.record_key===i.record_key);return s.jsxs("li",{children:[s.jsx("span",{className:"after_run_alert_title",children:U3(i)}),s.jsxs("span",{className:"muted",children:[" ","· ",W3(i),i.raised_at?` · ${w0(i.raised_at)}`:""]}),o.length?s.jsx("ul",{className:"after_run_deliveries",children:o.map((u,l)=>s.jsxs("li",{"data-state":u.state,children:[q3(u),u.time?s.jsxs("span",{className:"muted",children:[" · ",w0(u.time)]}):null]},`${u.channel}:${u.device||""}:${l}`))}):s.jsx("div",{className:"muted",children:"No delivery recorded yet."})]},i.record_key)})}):s.jsx("span",{"data-field":"quiet",children:z3(t.quiet_reason)})})]})}const Y3=[1e3,3e3];async function X3(e,t=Y3){let n=null;for(let r=0;r<=t.length;r++)try{return await e()}catch(i){n=i,r<t.length&&await new Promise(o=>setTimeout(o,t[r]))}throw n}function Z3(e){const{run_id:t,read:n}=e,[r,i]=p.useState({status:"loading"}),[o,u]=p.useState(0),l=p.useRef(null),d=p.useCallback(()=>{i({status:"loading"}),u(h=>h+1)},[]);return p.useEffect(()=>{let h=!0,m=0;const _=async()=>{m+=1;try{const g=await X3(()=>n(t));if(!h)return;i({status:"ready",after:g}),G3(g,m)&&(l.current=setTimeout(_,H3))}catch(g){if(!h)return;i(y=>y.status==="ready"?y:{status:"failed",error:g instanceof Error?g.message:String(g),on_retry:d})}};return _(),()=>{h=!1,l.current&&clearTimeout(l.current)}},[t,n,o,d]),s.jsx(K3,{state:r})}function Xs(){return el()}const BN=vg("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).",UN="Copy failed — select and copy";function WN(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function Q3(e){var i;const t=globalThis.document;if(!t||!t.body||typeof t.execCommand!="function")return!1;const n=t.createElement("textarea");n.value=e,n.setAttribute("readonly",""),n.style.position="fixed",n.style.top="0",n.style.left="-9999px",n.style.opacity="0";const r=t.activeElement;t.body.appendChild(n);try{return n.select(),n.setSelectionRange(0,e.length),t.execCommand("copy")===!0}catch{return!1}finally{t.body.removeChild(n);try{(i=r==null?void 0:r.focus)==null||i.call(r)}catch{}}}async function Em(e){var r;const t=String(e??""),n=globalThis.navigator;if(typeof((r=n==null?void 0:n.clipboard)==null?void 0:r.writeText)=="function")try{return await n.clipboard.writeText(t),!0}catch{}return Q3(t)}const eO=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function tO(e){const t=e.length,n=new Uint8Array(t+9+63>>6<<6);n.set(e),n[t]=128;const r=new DataView(n.buffer);r.setUint32(n.length-8,Math.floor(t/536870912),!1),r.setUint32(n.length-4,t<<3>>>0,!1);const i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64),u=(l,d)=>l>>>d|l<<32-d;for(let l=0;l<n.length;l+=64){for(let x=0;x<16;x++)o[x]=r.getUint32(l+x*4,!1);for(let x=16;x<64;x++){const N=u(o[x-15],7)^u(o[x-15],18)^o[x-15]>>>3,$=u(o[x-2],17)^u(o[x-2],19)^o[x-2]>>>10;o[x]=o[x-16]+N+o[x-7]+$>>>0}let[d,h,m,_,g,y,b,k]=[i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7]];for(let x=0;x<64;x++){const N=u(g,6)^u(g,11)^u(g,25),$=g&y^~g&b,E=k+N+$+eO[x]+o[x]>>>0,S=u(d,2)^u(d,13)^u(d,22),P=d&h^d&m^h&m,D=S+P>>>0;k=b,b=y,y=g,g=_+E>>>0,_=m,m=h,h=d,d=E+D>>>0}i[0]=i[0]+d>>>0,i[1]=i[1]+h>>>0,i[2]=i[2]+m>>>0,i[3]=i[3]+_>>>0,i[4]=i[4]+g>>>0,i[5]=i[5]+y>>>0,i[6]=i[6]+b>>>0,i[7]=i[7]+k>>>0}return Array.from(i,l=>l.toString(16).padStart(8,"0")).join("")}async function nO(e){var r;const t=new TextEncoder().encode(String(e??"")),n=(r=globalThis.crypto)==null?void 0:r.subtle;if(n&&typeof n.digest=="function"){const i=await n.digest("SHA-256",t);return Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("")}return tO(t)}const sO=/^[a-zA-Z0-9_-]+$/;function v0(e){return sO.test(String(e||"").trim())}async function rO(e){const t=String(e||"");return nO(t)}async function iO(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(v0(t)){const r=`session_memory_${t}`;if(v0(r))return r}return`session_memory_sha_${(await rO(t)).slice(0,32)}`}const qN="abstractobserver_voice";function oO(){var e;try{const t=(e=globalThis.localStorage)==null?void 0:e.getItem(qN),n=t?JSON.parse(t):null;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return{}}}const Xw=new Set;function aO(e){var t;try{(t=globalThis.localStorage)==null||t.setItem(qN,JSON.stringify(e||{}))}catch{}for(const n of Xw)n(e||{})}function HN(){const[e,t]=p.useState(()=>oO());return p.useEffect(()=>(Xw.add(t),()=>{Xw.delete(t)}),[]),[e,aO]}function VN(e,t){const[n,r]=p.useState({value:null,failed:!1});return p.useEffect(()=>{if(!t||!e){r({value:null,failed:!1});return}let i=!0;return e.voice_defaults().then(o=>i&&r({value:o||{},failed:!1})).catch(()=>i&&r({value:null,failed:!0})),()=>{i=!1}},[e,t]),n}function lO(e){if(e)return{design:t=>e.voice_design(t),clone:(t,n)=>e.voice_clone(t,n)}}function cO(e){const t=e.gateway;return s.jsx(BM,{value:e.value,onChange:e.onChange,fetchCatalog:(n,r)=>t?t.voice_catalog(n,r):Promise.reject(new Error("Connect to a gateway to configure voice.")),fetchDefaults:()=>t?t.voice_defaults():Promise.reject(new Error("Connect to a gateway to configure voice.")),defaults:e.defaults.value??void 0,overrideOwner:"this app",nested:!0,createVoice:lO(t),unavailableReason:e.connected&&t?null:"Connect to a gateway to configure voice."})}const uO=18e4;function dO(e,t,n,r=()=>{}){return async function*(i,o){r(),yield*jE({path:e.gateway_url(wt(`runs/${encodeURIComponent(t)}/voice/tts/stream`)),headers:e.auth_headers(),signal:o,body:{text:i,request_id:Xs(),...LM(n())}})}}function fO(e,t,n,r,i=()=>{},o=uO){return async(u,l)=>{i();const d=String(l||u.type||"").toLowerCase(),h=d.includes("mp4")?"m4a":d.includes("ogg")?"ogg":d.includes("wav")?"wav":"webm",m=new File([u],`recording.${h}`,{type:d||"audio/webm"}),_=await e.attachments_upload(t,m,{filename:m.name,content_type:m.type});i();let g;const y=await Promise.race([e.audio_transcribe(n,{audio_artifact:_,request_id:Xs(),...IM(r())}),new Promise((b,k)=>{g=setTimeout(()=>k(new Error(`the gateway did not answer within ${Math.round(o/1e3)} s`)),o)})]).finally(()=>clearTimeout(g));return i(),{text:String(y.text||""),provider:y.provider,model:y.model}}}function GN(e){const{gateway:t,prefs:n}=e,r=String(e.session_id||"").trim(),[i,o]=p.useState("");p.useEffect(()=>{let y=!0;if(!r){o("");return}return iO(r).then(b=>y&&o(b)).catch(()=>y&&o("")),()=>{y=!1}},[r]);const u=`${r}|${i}`,l=p.useRef(u);l.current=u;const d=p.useRef(n);d.current=n;const h=p.useRef(e);h.current=e;const m=()=>{if(l.current!==u)throw new Error("Voice session changed.")},_=!!(t&&i&&r),g=ME({output_device_id:n.output_device||"",input_device_id:n.input_device||"",input_gain:n.input_gain,volume:n.reply_volume,stop_on_pointerup:!1,tts_stream:_?dO(t,i,()=>d.current,m):void 0,transcribe:_?fO(t,r,i,()=>d.current,m):void 0,on_transcript:y=>{l.current===u&&h.current.on_transcript(y)},on_error:y=>{l.current===u&&h.current.on_error(y)}});return p.useEffect(()=>{var y;return g.stop_tts(),(y=g.cancel_voice_ptt_recording)==null||y.call(g),()=>{var b;g.stop_tts(),(b=g.cancel_voice_ptt_recording)==null||b.call(g)}},[u,g.stop_tts,g.cancel_voice_ptt_recording]),{...g,run_id:i}}function KN(e,t,n){const r=p.useRef(null);p.useEffect(()=>{const i=(n==null?void 0:n.key)||"";if(r.current===null){r.current=i;return}!i||i===r.current||(r.current=i,t&&e.tts_supported&&(n!=null&&n.text.trim())&&e.toggle_tts(i,n.text))},[n==null?void 0:n.key,n==null?void 0:n.text,t,e.tts_supported,e.toggle_tts])}function hO(e){const[t,n]=p.useState(()=>Date.now());return p.useEffect(()=>{if(!e)return;n(Date.now());const r=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(r)},[e]),t}const mO=350;function JN(e){const{voice:t}=e,n=p.useRef(!1),r=p.useRef(!1),i=p.useRef(0),o=()=>{if(r.current){r.current=!1,t.stop_voice_ptt_recording();return}n.current=!0,i.current=Date.now(),t.start_voice_ptt_recording().then(()=>{!n.current&&!r.current&&t.stop_voice_ptt_recording()})},u=()=>{if(n.current){if(n.current=!1,Date.now()-i.current<mO){r.current=!0;return}t.stop_voice_ptt_recording()}};p.useEffect(()=>{const y=()=>{n.current=!1,r.current=!1,t.stop_voice_ptt_recording()};return window.addEventListener("pointerup",u),window.addEventListener("pointercancel",u),window.addEventListener("blur",y),()=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",u),window.removeEventListener("blur",y)}},[t.stop_voice_ptt_recording]),p.useEffect(()=>{t.voice_ptt_recording||(r.current=!1)},[t.voice_ptt_recording]);const l=t.voice_ptt_since||0,d=hO(!!l),h=vE(e.prefs,e.defaults),m=t.voice_ptt_recording?`Recording… ${l?qj(l,d):""}`.trim():t.voice_ptt_busy?xE(l||d,d,h):"",g=!WN()?BN:e.blocked||(t.voice_ptt_supported?null:"Dictation is not available on this gateway connection.");return s.jsxs("span",{className:"voice_tools","data-voice-tools":!0,children:[s.jsx("button",{type:"button",className:`btn btn_icon voice_btn${t.voice_ptt_recording?" danger":""}`,"data-action":"dictate","aria-label":t.voice_ptt_recording?"Recording — tap or release to transcribe":"Hold to dictate","aria-pressed":t.voice_ptt_recording,title:g||"Hold to dictate, or tap to start and tap again to stop (Space or Enter on keyboard)",disabled:!!g||t.voice_ptt_busy,onPointerDown:y=>{y.button===0&&o()},onPointerUp:u,onPointerCancel:u,onKeyDown:y=>{[" ","Enter"].includes(y.key)&&!y.repeat&&(y.preventDefault(),o())},onKeyUp:y=>{[" ","Enter"].includes(y.key)&&(y.preventDefault(),u())},children:s.jsx(qe,{name:t.voice_ptt_busy?"loader":"mic",size:15})}),t.tts_playback.status!=="idle"?s.jsx("button",{type:"button",className:"btn btn_icon","data-action":"stop-speaking","aria-label":"Stop spoken reply",title:"Stop spoken reply",onClick:t.stop_tts,children:s.jsx(qe,{name:"x",size:14})}):null,m?s.jsx("span",{role:"status",className:"voice_status mono","data-voice-status":!0,children:m}):null,e.error?s.jsx("span",{role:"alert",className:"voice_error","data-voice-error":!0,children:e.error}):null]})}function _O(e){const{voice:t}=e;if(!t.tts_supported||!e.text.trim())return null;const n=t.tts_playback.key===e.speak_key?t.tts_playback.status:"idle",r=n==="loading"?"Preparing…":n==="playing"?"Stop":n==="paused"?"Resume":"Read aloud";return s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"btn","data-action":"read-aloud","data-speak-state":n,"aria-pressed":n==="playing"||n==="loading",title:n==="playing"?"Stop reading aloud":"Read this aloud with the gateway's voice",onClick:()=>n==="playing"||n==="loading"?t.stop_tts():void t.toggle_tts(e.speak_key,e.text),children:[s.jsx(qe,{name:n==="playing"||n==="loading"?"x":"speaker",size:14})," ",r]}),e.error?s.jsx("span",{role:"alert",className:"voice_error","data-voice-error":!0,children:e.error}):null]})}const pO="abstractobserver";function gO(e){return{getRun:t=>e.get_run(t),getHistory:t=>e.get_run_history_bundle(t,{include_subruns:!0,include_session:!0,ledger_mode:"full"}),getLedger:(t,n,r)=>e.get_ledger(t,{after:n,limit:200,signal:r}),streamLedger:(t,n,r,i,o)=>e.stream_ledger(t,{after:n,on_step:r,signal:i,on_open:o}),submitCommand:t=>e.submit_command(t)}}function yO(e){const t=String(e||"").trim(),n=t.indexOf(":");if(n<=0||n===t.length-1)throw new Error(`The discussion's workflow id ${JSON.stringify(t)} is not bundle@version:flow; its next turn cannot be started.`);return{bundle_id:t.slice(0,n),flow_id:t.slice(n+1)}}const wO=new Set(["completed","failed","cancelled"]);function vO(e){var G;const{gateway:t,discussion:n}=e,r=p.useMemo(()=>gO(t),[t]),[i,o]=p.useState(((G=n.session)==null?void 0:G.run_id)||""),[u,l]=p.useState(""),[d,h]=p.useState(!1),[m,_]=p.useState(""),{controller:g,snapshot:y}=zL({transport:r,runId:i,enabled:e.connected,clientId:pO}),b=n.session,k=!!i&&!wO.has(y.status)&&y.status!=="idle",x=IL(y),[N]=HN(),$=VN(e.connected?t:null,e.connected),[E,S]=p.useState(""),P=GN({gateway:e.connected?t:null,session_id:(b==null?void 0:b.session_id)||e.voice_session_id||"",prefs:N,on_error:S,on_transcript:K=>l(H=>H.trim()?`${H.trimEnd()}
94
+ ${K}`:K)}),D=p.useMemo(()=>{for(let K=y.messages.length-1;K>=0;K-=1){const H=y.messages[K];if(H.role==="assistant")return H.live?null:{key:String(H.id||""),text:String(H.content||"")}}return null},[y.messages]);KN(P,N.read_aloud===!0,D);const R=K=>P.tts_playback.key&&P.tts_playback.key===String(K.id||"")?P.tts_playback.status:"idle",I=async K=>{var M;const H=K.trim();if(H){h(!0);try{if(b){const A=String(((M=y.run)==null?void 0:M.workflow_id)||""),O=yO(A),L=await t.start_run(O.flow_id,{prompt:H},{bundle_id:O.bundle_id,session_id:b.session_id});o(L)}else{const A=await e.on_fork(n.automation_id,n.occurrence_index,H);o(A.run_id)}l("")}finally{h(!1)}}},W=s.jsxs("div",{className:"discussion_head",children:[s.jsxs("button",{type:"button",className:"btn btn_sm","data-action":"discussion-back",onClick:e.on_close,title:`Back to ${n.automation_title}`,children:[s.jsx(qe,{name:"chevronRight",size:13,className:"flip_x"})," ",n.automation_title]}),s.jsxs("span",{className:"discussion_title",children:[s.jsx(qe,{name:"chat",size:15})," Discussion — fork at #",n.occurrence_index]}),s.jsx("span",{className:"pane_spacer"}),b?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`btn btn_sm${m==="own"?" active":""}`,"data-action":"discussion-files",onClick:()=>_(m==="own"?"":"own"),title:b.workspace_root,children:[s.jsx(qe,{name:"folder",size:14})," Its files"]}),s.jsxs("button",{type:"button",className:`btn btn_sm${m==="mounted"?" active":""}`,"data-action":"automation-files",onClick:()=>_(m==="mounted"?"":"mounted"),title:b.mounted_workspace,children:[s.jsx(qe,{name:"folder",size:14})," Automation files"]})]}):null]});return s.jsxs("section",{className:"pane auto_detail auto_discussion","data-discussion-session":(b==null?void 0:b.session_id)||void 0,children:[m&&b?s.jsx(vN,{fetchGateway:t.fetch_gateway,runId:m==="own"?b.run_id:n.automation_id,title:m==="own"?"Discussion files":"Automation files",note:m==="own"?"The discussion's own writable folder.":"Mounted read-only for the discussion's file tools; nothing is written back.",onClose:()=>_(""),refreshKey:y.status}):null,s.jsx(LL,{header:W,messages:y.messages,draft:u,onDraftChange:l,onSend:I,busy:k||d,busyLabel:d?b?"Starting…":"Forking the automation…":x?"Waiting for you":"Working…",onCancel:k?()=>g.cancel():void 0,stopState:y.stop??null,disabled:!e.connected,interaction:GL(x,g,{records:y.records,currentRun:y.run}),placeholder:b?"Ask a follow-up…":`Ask about run #${n.occurrence_index}…`,emptyState:s.jsxs("div",{className:"help_text muted discussion_intro",children:["A new conversation from run #",n.occurrence_index," with the automation's history (runs 1–",n.occurrence_index,"). It works in its own folder; it can read the automation's files but not change them (by the file tools; shell commands are not sandboxed), and nothing is written back into the automation."]}),composerExtras:s.jsx(JN,{voice:P,defaults:$.value,prefs:N,blocked:e.connected?null:"Connect to the gateway first.",error:E}),messageProps:P.tts_supported?{onSpeakToggle:K=>{S(""),P.toggle_tts(String(K.id||""),String(K.content||""))},getSpeakState:R}:void 0,footer:y.error?s.jsx("div",{className:"observe_context_card error",role:"alert",children:y.error}):null})]})}const xO=Wn.title;function x0(e){return`${xO}: ${e}`}const bO=["workspace_access_mode","workspace_allowed_paths"];function kO(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.folders))}function jO(e){var n,r;const t=(r=(n=e==null?void 0:e.target)==null?void 0:n.input_data)==null?void 0:r.workspace;return kO(t)?t:null}function YN(e,t){const n={...e||{}};for(const r of bO)delete n[r];return t===null?delete n.workspace:n.workspace={posture:t.posture,default_mode:t.default_mode,folders:t.folders.map(r=>({path:r.path,mode:r.mode}))},n}function SO(e,t){const n=e.target;return{target:{bundle_ref:n.bundle_ref,flow_id:n.flow_id,input_data:YN(n.input_data,t)}}}const NO=3e4,Zw=new WeakMap;function $O(e,t,n=Date.now()){let r=Zw.get(e);r||Zw.set(e,r=new Map);const i=JSON.stringify(t),o=r.get(i);if(o&&n-o.at<NO)return o.answer;const u=Qh(e)(t).then(l=>l.summary);return u.catch(()=>r==null?void 0:r.delete(i)),r.set(i,{at:n,answer:u}),u}function CO(e){Zw.delete(e)}function EO(e){const[t,n]=p.useState(null),r=JSON.stringify(e.value);return p.useEffect(()=>{if(!e.connected||!e.request){n(null);return}let i=!0;return $O(e.request,e.value).then(o=>i&&n(x0(o))).catch(o=>i&&n(x0(Ag(o)))),()=>{i=!1}},[e.request,e.connected,r,e.refresh_key]),t?s.jsx("span",{className:"auto_workspaces_line","data-field":"workspaces",title:t,children:t}):null}function AO(e){const{connected:t,request:n,value:r}=e,[i,o]=p.useState(null),[u,l]=p.useState(null),d=JSON.stringify(r);p.useEffect(()=>{if(!t){o(null),l(null);return}let g=!0;return l(null),Qh(n)(r).then(y=>g&&o(y)).catch(y=>g&&l(`Could not read your workspaces: ${Ag(y)}`)),()=>{g=!1}},[t,d,n]);const h=e.on_change,m=p.useCallback(async g=>{const y=await Qh(n)(g);await h(g),o(y),CO(n)},[n,h]),_=t?e.disabled?"Saving…":null:"Connect to your gateway to choose workspaces.";return s.jsx(VS,{level:"run",idPrefix:e.id_prefix,value:r,effective:i,onChange:m,loadError:t?u:_,unavailableReason:_,footer:e.footer})}class TO{constructor(){kn(this,"made",new Map);kn(this,"current",new Map)}record(t,n,r){if(this.current.set(t,r),n===null)return;let i=this.made.get(t);i||this.made.set(t,i=new Set),i.add(n+1)}note(t,n){if(n===null)return;let r=this.made.get(t);r||this.made.set(t,r=new Set),r.add(n+1)}expected(t,n){if(n===null)return null;const r=this.made.get(t);let i=n;for(;r&&r.has(i+1);)i+=1;return i}changes(t,n){if(!this.current.has(t)||!n.target)return n;const r=this.current.get(t)??null;return{...n,target:{...n.target,input_data:YN(n.target.input_data,r)}}}}async function MO(e,t,n,r,i){const o=t.expected(n.automation_id,n.summary.revision);await e.revise(n.automation_id,SO(n.definition,r),o,i),t.record(n.automation_id,o,r)}function XN(e){return`abstractobserver_list_open_${e}`}function ZN(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function RO(e,t=ZN()){try{return(t==null?void 0:t.getItem(XN(e)))!=="0"}catch{return!0}}function LO(e,t,n=ZN()){try{n==null||n.setItem(XN(e),t?"1":"0")}catch{}}function Xp(e){const[t,n]=p.useState(()=>RO(e)),r=p.useCallback(()=>{n(i=>{const o=!i;return LO(e,o),o})},[e]);return[t,r]}function Zp(e){return s.jsxs("button",{type:"button",className:`list_disclosure${e.className?` ${e.className}`:""}`,"aria-expanded":e.open,"aria-controls":e.controls,onClick:e.on_toggle,title:e.open?`Hide ${e.title.toLowerCase()}`:`Show ${e.title.toLowerCase()}`,children:[s.jsx(qe,{name:e.open?"chevronDown":"chevronRight",size:14}),s.jsx("span",{className:"pane_title",children:e.title}),e.count!==void 0?s.jsx("span",{className:"pane_count",children:e.count}):null]})}const IO=5e3,OO=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],PO={pause:ga.pause,resume:ga.resume,run_now:ga.run_now,edit:ga.revise,archive:`${ga.archive}…`,discuss:ga.discuss},DO={pause:Ho.pause,resume:Ho.resume,run_now:Ho.run_now,edit:Ho.revise,archive:Ho.archive,discuss:Ho.discuss},FO={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},zO={legacy_pause:Ho.pause,legacy_resume:Ho.resume,legacy_run_now:Ho.run_now,open_run:"list",recreate:"refresh"};function BO(e){return s.jsx("span",{className:"auto_state","data-field":"state",children:s.jsx(US,{status:e.status})})}function ip(e){return s.jsxs("span",{className:`auto_fact${e.className?` ${e.className}`:""}`,"data-field":e.field,title:e.label,children:[s.jsx(qe,{name:e.icon,size:12}),s.jsx("span",{children:e.children})]})}const UO={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"},WO="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function b0(e){const t=e.busy||e.ctl.enabled?null:e.ctl.reason||"Not available now.";return s.jsx(Di,{variant:"sm",className:"auto_switch",action:"active",id:`auto-active-${e.summary.automation_id}`,label:ga.active,checked:e.summary.status==="active",unavailableReason:t,busy:e.busy,hint:e.hint,onChange:e.onChange})}function qO(e){const t=e.summary,n=FN(t,Date.now(),{connections:e.state.trigger_connections,mailboxes:e.state.mailboxes}),r=e.state.selected_id===t.automation_id,i=e.state.busy,o=(d,h,m,_,g,y,b,k)=>s.jsxs("button",{type:"button",className:`btn btn_sm auto_action${b?" auto_action_icon":""}${g?` ${g}`:""}`,"data-action":d,disabled:!m.enabled,title:[b?h:null,m.enabled?null:m.reason,k].filter(Boolean).join(`
95
+ `)||void 0,"aria-label":b?h:void 0,"aria-description":k,onClick:_,children:[y?s.jsx(qe,{name:y,size:13}):null,b?null:s.jsx("span",{children:h})]},d);let u;if(n.legacy){const d=k3(t,i),h=t.status==="paused"?"legacy_resume":"legacy_pause",m=["legacy_run_now","open_run","recreate"];u=[s.jsx(b0,{summary:t,busy:i,ctl:d[h],hint:WO,onChange:()=>e.h.on_legacy_action(t,h)},"active"),...m.map(_=>o(_,UO[_],d[_],()=>e.h.on_legacy_action(t,_),void 0,zO[_]))]}else{const d=b3(t,i),h=t.status==="active"?"pause":"resume",m=["run_now","edit","discuss","archive"];u=[s.jsx(b0,{summary:t,busy:i,ctl:d.active,hint:Hp("active",t),onChange:()=>e.h.on_row_action(t,h)},"active"),...m.map(_=>o(_,PO[_],d[_],()=>e.h.on_row_action(t,_),_==="archive"?"danger auto_action_end":void 0,DO[_],_==="archive",Hp(FO[_],t)))]}const l=e.state.confirm_archive_id===t.automation_id;return s.jsxs("li",{className:`auto_row${r?" selected":""}`,"data-automation-id":t.automation_id,"data-legacy":n.legacy?"true":void 0,children:[s.jsxs("button",{type:"button",className:"auto_row_main",onClick:()=>e.h.on_select(t.automation_id),"aria-current":r?"true":void 0,children:[s.jsxs("span",{className:"auto_row_title",children:[n.title,n.legacy?s.jsx("span",{className:"chip scheduled",children:"legacy"}):null,s.jsx(BO,{status:n.state}),n.attention?s.jsxs("span",{className:"chip warn auto_row_attention","data-field":"attention",children:[s.jsx(qe,{name:"warning",size:12})," ",n.attention]}):null]}),s.jsxs("span",{className:"auto_row_facts",children:[s.jsx(ip,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?s.jsx(ip,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,s.jsx(ip,{icon:"clock",field:"next",label:n.listening?"When it runs":"Next run",children:n.listening?n.next_run:`next: ${n.next_run}`}),s.jsx(ip,{icon:"info",field:"last-status",label:"Last run",children:n.last_status})]}),n.last?s.jsx("span",{className:"auto_row_excerpt","data-field":"excerpt",children:$N(n.last)}):null]}),s.jsx("div",{className:"auto_row_actions",role:"toolbar","aria-label":`Controls for ${n.title}`,children:u}),l?s.jsxs("div",{className:"auto_row_confirm",role:"group","aria-label":"Confirm archive",children:[s.jsxs("span",{children:["Archive “",n.title,"”? Its history stays readable; it will not run again."]}),s.jsxs("button",{type:"button",className:"btn btn_sm danger auto_action","data-action":"archive-confirm",disabled:i,onClick:()=>e.h.on_confirm_archive(t),children:[s.jsx(qe,{name:"archive",size:13}),s.jsx("span",{children:"Archive"})]}),s.jsxs("button",{type:"button",className:"btn btn_sm auto_action","data-action":"archive-cancel",onClick:e.h.on_cancel_archive,children:[s.jsx(qe,{name:"x",size:13}),s.jsx("span",{children:"Keep it"})]})]}):null]})}function HO(e){const t=e.state,n=e.list?e.list.open:!0,r=t.error??t.list_error,i=r?Wp(r):null;return s.jsxs("section",{className:`pane auto_list${n?"":" list_collapsed"}`,"aria-label":"Automations",children:[s.jsxs("div",{className:"pane_header",children:[e.list?s.jsx(Zp,{open:n,on_toggle:e.list.on_toggle,controls:"auto_list_body",title:"Automations",count:Py(t).length}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_title",children:"Automations"}),s.jsx("span",{className:"pane_count",children:Py(t).length})]}),s.jsx("span",{className:"pane_spacer"}),s.jsx("select",{className:"seg_select",value:t.status_filter,onChange:o=>e.h.on_status_filter(o.target.value),"aria-label":"Filter by status",children:OO.map(([o,u])=>s.jsx("option",{value:o,children:u},o||"all"))}),s.jsx("button",{type:"button",className:"btn btn_sm auto_icon_btn","data-action":"refresh",onClick:e.h.on_refresh,disabled:t.loading||!e.available.available,title:"Refresh","aria-label":"Refresh",children:s.jsx(qe,{name:t.loading?"loader":"refresh",size:14})}),s.jsxs("a",{className:`btn btn_sm auto_new${e.available.available?"":" disabled"}`,"data-action":"new",href:o3,"aria-disabled":!e.available.available,title:"New automation: run a flow by itself","aria-label":"New automation",onClick:o=>{o.preventDefault(),e.available.available&&e.h.on_new()},children:[s.jsx(qe,{name:"plus",size:14}),s.jsx("span",{className:"auto_new_label",children:"New automation"})]})]}),s.jsxs("div",{className:"pane_body scroll",id:"auto_list_body",hidden:!n,children:[e.available.available?null:s.jsx("div",{className:"warn_callout",role:"note","data-unavailable":"true",children:e.available.reason}),i?s.jsxs("div",{className:"observe_context_card error auto_list_error",role:"alert","data-code":r==null?void 0:r.code,children:[s.jsx(qe,{name:"error",size:14}),s.jsxs("span",{className:"auto_list_msg",children:[s.jsx("strong",{children:i.title})," ",s.jsx("span",{children:i.detail})]}),t.error&&e.h.on_dismiss_error?s.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_error,children:s.jsx(qe,{name:"x",size:12})}):null]}):null,s.jsx("div",{className:`auto_notice${t.notice?" on":""}`,role:"status",children:t.notice?s.jsxs(s.Fragment,{children:[s.jsx(qe,{name:"check",size:13}),s.jsx("span",{className:"auto_list_msg",children:t.notice}),e.h.on_dismiss_notice?s.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-notice","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_notice,children:s.jsx(qe,{name:"x",size:12})}):null]}):null}),e.available.available&&!t.loaded&&t.loading?s.jsx(rl,{what:"automations"}):null,e.available.available&&t.loaded&&!t.items.length?s.jsx("div",{className:"help_text muted","data-empty":"automations",children:"No automations yet. Make one in Flow, or press New automation."}):null,_0(t)>0&&t.status_filter!=="archived"?s.jsx("div",{className:"auto_show_archived",children:s.jsx(Di,{variant:"sm",action:"show-archived",label:`Archived (${_0(t)})`,hint:"List archived automations too. Their history stays readable; they do not run.",checked:t.show_archived,onChange:o=>e.h.on_show_archived(o)})}):null,s.jsx("ul",{className:"auto_rows",children:Py(t).map(o=>s.jsx(qO,{summary:o,state:t,h:e.h},o.automation_id))})]})]})}function VO(e,t,n,r){const i=e.state,o=i.detail;if(!o||Za(o.summary))return null;const u=o.automation_id;return{summary:o.summary,...o.definition?{definition:o.definition}:{},occurrences:o.occurrences,triggerSources:i.trigger_sources,triggerConnections:i.trigger_connections,mailboxes:i.mailboxes,occurrenceEvents:o.occurrence_events,busy:i.busy,...o.error?{error:o.error}:{},onRevise:async(l,d,h)=>{if(!r)return e.revise(u,l,d,h==null?void 0:h.command_id);const m=r.expected(u,d),_=await e.revise(u,r.changes(u,l),m,h==null?void 0:h.command_id);return r.note(u,m),_},onCommand:(l,d,h)=>e.command(u,l,d,h==null?void 0:h.command_id),onDiscuss:async(l,d,h)=>{const m=await e.discuss(u,l,d,h==null?void 0:h.request_id);return t.on_open_session(m,lx(l),l),m},onSeen:l=>e.seen(u,l),onLoadMore:()=>void e.load_more(),onOpenRun:l=>t.on_open_run(l),...t.on_open_workspace?{onOpenWorkspace:t.on_open_workspace}:{},...t.fetch_gateway?{fetchGateway:t.fetch_gateway}:{},onAnswerWait:(l,d,h)=>e.answer_wait(u,l,d,h),...n?{editOpen:n.open,onEditOpenChange:n.on_change}:{},emailStatus:i.email_status,previewSchedule:e.preview_schedule,...t.on_open_my_email?{onOpenMyEmail:()=>{var l;return(l=t.on_open_my_email)==null?void 0:l.call(t)}}:{}}}function GO(e,t){var d;const n=String(e||"").trim();if(!n||!(t!=null&&t.length))return;const r=t.find(h=>h.value===n);if(r!=null&&r.name)return r.name;const i=n.indexOf("@"),o=n.lastIndexOf(":");if(i<=0||o<=i)return;const u=n.slice(0,i),l=n.slice(o+1);return((d=t.find(h=>h.bundleId===u&&h.flowId===l))==null?void 0:d.name)||void 0}function KO(e){const{fetchGateway:t,messageProps:n,readRunAfter:r,...i}=e,o=i.onOpenResource??(t?l=>sL(t,l.url,{name:l.name}):void 0),u=l=>l.kind==="answer"&&r?s.jsxs(s.Fragment,{children:[r0(l,n),s.jsx(Z3,{run_id:l.runId,read:r})]}):r0(l,n);return s.jsx(BT,{...i,onOpenResource:o,renderText:$N,renderTurn:u})}function JO(e){var l,d,h,m,_;const t=e.ctl.state.detail;if(!t&&e.ctl.state.selected_id)return s.jsx("section",{className:"pane auto_detail auto_detail_empty","aria-busy":"true",children:s.jsx(rl,{what:"automation",size:"block"})});if(!t)return s.jsx("section",{className:"pane auto_detail auto_detail_empty",children:s.jsx("div",{className:"help_text muted",children:"Select an automation to read its runs, change it, or talk about a result."})});if(Za(t.summary)){const g=FN(t.summary);return s.jsxs("section",{className:"pane auto_detail","data-legacy":"true",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:g.title}),s.jsx("span",{className:"chip scheduled",children:"legacy"})]}),s.jsxs("div",{className:"pane_body",children:[s.jsxs("p",{className:"help_text",children:["A schedule created before automations (",g.cadence,"). It keeps working with its existing controls: suspend, resume, run now and edit the interval from its run view. “Recreate as automation” opens Launch → Automate prefilled with its workflow, inputs and interval; the legacy schedule is not changed."]}),s.jsxs("div",{className:"auto_row_actions",children:[s.jsx("button",{type:"button",className:"btn btn_sm","data-action":"open_run",onClick:()=>e.h.on_legacy_action(t.summary,"open_run"),children:"Open run"}),s.jsx("button",{type:"button",className:"btn btn_sm primary","data-action":"recreate",onClick:()=>e.h.on_legacy_action(t.summary,"recreate"),children:"Recreate as automation"})]})]})]})}const n=e.workspaces,r=VO(e.ctl,e.host,e.edit,n==null?void 0:n.revisions),i=e.ctl,o=t.definition,u=jO(o);return s.jsxs("section",{className:"pane auto_detail",children:[e.browser??null,n&&o?s.jsx("div",{className:"auto_workspaces","data-section":"workspaces","data-editing":(l=e.edit)!=null&&l.open?"true":void 0,children:(d=e.edit)!=null&&d.open?s.jsxs("details",{className:"auto_workspaces_details","data-field":"workspaces-details",children:[s.jsx("summary",{children:"Workspaces"}),s.jsx(AO,{footer:s.jsx("p",{className:"help_text muted auto_workspaces_help",children:"Each change is saved at once as a new revision; it applies from the next run."}),id_prefix:`observer-automation-workspace-${t.automation_id}`,connected:n.connected,request:n.request,value:u,disabled:i.state.busy,on_change:g=>MO(i,n.revisions,{automation_id:t.automation_id,summary:t.summary,definition:o},g,el())})]}):s.jsxs("details",{className:"auto_workspaces_details","data-field":"workspaces-details",children:[s.jsx("summary",{children:"Workspaces"}),s.jsx(EO,{request:n.request,connected:n.connected,value:u,refresh_key:t.summary.revision??""})]})}):null,r?s.jsx(KO,{...r,readRunAfter:e.host.read_run_after,workflowName:GO(o==null?void 0:o.target.workflow_id,(_=(m=(h=e.workflowPickerOptions)==null?void 0:h.workflows)==null?void 0:m.data)==null?void 0:_.entries),workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools}):null]})}function YO(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=zN(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function XO(e){const t=e.ctl,n=p.useRef(null);n.current||(n.current=new TO);const r=e.workspace_request?{request:e.workspace_request,connected:e.active,definition:S=>t.definition(S)}:void 0,[i,o]=Xp("automations"),[u,l]=p.useState(null),d=S=>l(P=>({...S,opened:((P==null?void 0:P.opened)||0)+1})),[h,m]=p.useState(""),[_,g]=p.useState("");p.useSyncExternalStore(S=>t.subscribe(S),()=>t.state,()=>t.state);const[y,b]=p.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");p.useEffect(()=>{const S=()=>b(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",S),()=>document.removeEventListener("visibilitychange",S)},[]),p.useEffect(()=>{if(!e.active||!y||!e.available.available)return;t.refresh();const S=window.setInterval(()=>void t.refresh(),T3);return()=>window.clearInterval(S)},[t,e.active,y,e.available.available]);const k=t.state.detail,x=t.state.notice;p.useEffect(()=>{if(!x)return;const S=window.setTimeout(()=>t.dismiss_notice(),IO);return()=>window.clearTimeout(S)},[t,x]);const N=Ee.useCallback(S=>e.gateway.get_run_after(S),[e.gateway]),$={...e.host,on_open_workspace:S=>m(P=>P===S?"":S),fetch_gateway:e.gateway.fetch_gateway,read_run_after:N,on_open_session:(S,P,D)=>{e.host.on_open_session(S,P,D),k&&d({automation_id:k.automation_id,automation_title:k.summary.title,occurrence_index:D,session:S})}},E={...e.h,on_select:S=>{l(null),m(""),S!==_&&g(""),e.h.on_select(S)},on_dismiss_notice:()=>t.dismiss_notice(),on_dismiss_error:()=>t.dismiss_error(),on_row_action:(S,P)=>{const D=YO(S,P);D.kind==="forward"?e.h.on_row_action(S,P):D.kind==="edit"?(l(null),m(""),g(S.automation_id),e.h.on_select(S.automation_id)):D.kind==="discuss"&&(e.h.on_select(S.automation_id),d({automation_id:S.automation_id,automation_title:S.title,occurrence_index:D.index}))}};return s.jsxs("div",{className:`page auto_page${i?"":" list_collapsed"}`,children:[s.jsx(HO,{state:t.state,available:e.available,h:E,list:{open:i,on_toggle:o},ws:r}),u?s.jsx(vO,{gateway:e.gateway,discussion:u,connected:e.active,voice_session_id:e.voice_session_id||"",on_fork:async(S,P,D)=>{const R=await t.discuss(S,P,D);return e.host.on_open_session(R,lx(P),P),l(I=>I&&{...I,session:R}),R},on_close:()=>l(null)},u.opened):s.jsx(JO,{workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools,ctl:t,host:$,h:E,edit:{open:!!k&&_===k.automation_id,on_change:S=>g(S&&k?k.automation_id:"")},workspaces:e.workspace_request?{request:e.workspace_request,connected:e.active,revisions:n.current}:void 0,browser:h?s.jsx(vN,{fetchGateway:e.gateway.fetch_gateway,runId:h,title:h===(k==null?void 0:k.automation_id)?"Automation files":"Run files",onClose:()=>m("")}):void 0})]})}function ZO(e){return s.jsx(Di,{variant:"row",action:"auto-connect",label:"Auto-connect on load",description:"Reuse the browser session automatically when the app opens.",checked:e.checked,onChange:e.onChange})}function QO(e){return s.jsx("div",{className:`settings_choice ${e.checked?"on":""}`,children:s.jsx(Di,{variant:"row",action:"assistant-skill",label:s.jsxs("span",{className:"settings_choice_name",children:[e.name,e.version?s.jsxs("em",{children:[" v",e.version]}):null]}),ariaLabel:e.name,description:e.description||void 0,checked:e.checked,onChange:e.onChange})})}const e4="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function t4(e){return s.jsx(Di,{variant:"sm",action:"schedule-active",className:"observe_schedule_switch",label:"Active",hint:e4,checked:e.active,unavailableReason:e.unavailableReason,busy:e.busy,onChange:e.onChange})}function n4(e){return s.jsx(Di,{variant:"sm",action:"mindmap-live",label:"Live",hint:"Refresh the map as new memory arrives.",checked:e.checked,onChange:e.onChange})}function s4(e){return s.jsx(Di,{variant:"row",action:"apply-immediately",label:"Apply immediately",description:"Recompute the next run from now if the schedule is waiting.",checked:e.checked,busy:e.busy,onChange:e.onChange})}const k0={framework:null,gateway:null,gatewayNote:"checking…"};function r4(){const e="0.9.0".trim();if(!e)throw new Error("AbstractObserver: __APP_VERSION__ is not defined; the vite/vitest config must inject it from package.json");return e}function i4(){return Q2("abstractobserver",r4())}async function o4(e){let t;try{t=await e.gateway_about()}catch(n){return qh(null,n instanceof Error?n.message||n.name:String(n))}return qh(t)}class Qp{constructor(t){this._maxSize=Qp._normalizeMaxSize(t),this._values=[]}get maxSize(){return this._maxSize}get size(){return this._values.length}static _normalizeMaxSize(t){const n=Number(t);return!Number.isFinite(n)||n<=0?1:Math.min(1e3,Math.floor(n))}setMaxSize(t){const n=Qp._normalizeMaxSize(t);this._maxSize=n,this._values.length>n&&(this._values=this._values.slice(this._values.length-n))}clear(){this._values=[]}push(t){const n=Number(t),r=Number.isFinite(n)?n:null;this._values.push(r),this._values.length>this._maxSize&&this._values.splice(0,this._values.length-this._maxSize)}values(){return this._values.slice()}last(){return this._values.length?this._values[this._values.length-1]:null}}function a4(e){try{return new URL(String(e)),!0}catch{return!1}}function l4({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return a4(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function c4({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function u4({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function d4(e){if(!e||typeof e!="object")return null;const t=Number(e.utilization_gpu_pct);if(Number.isFinite(t))return t;const n=e.gpus;if(Array.isArray(n)&&n.length){const r=n.map(o=>Number(o&&o.utilization_gpu_pct)).filter(o=>Number.isFinite(o));return r.length?r.reduce((o,u)=>o+u,0)/r.length:null}return null}async function f4({baseUrl:e,endpoint:t,token:n,getToken:r,signal:i,fetchImpl:o}={}){const u=l4({baseUrl:e,endpoint:t}),l=await c4({token:n,getToken:r}),d=o||globalThis.fetch;if(typeof d!="function")return{ok:!1,status:0,error:"fetch_unavailable",payload:null};let h;try{h=await d(u,{method:"GET",headers:{Accept:"application/json",...u4({token:l})},signal:i})}catch(_){return{ok:!1,status:0,error:"network_error",detail:_ instanceof Error?_.message:String(_),payload:null}}let m=null;try{m=await h.json()}catch{m=null}return{ok:h.ok,status:h.status,error:h.ok?null:"http_error",payload:m}}const xh=Object.freeze({tickMs:1500,historySize:20,endpoint:"api/gateway/host/metrics/gpu",baseUrl:"",mode:"full"});function h4(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function j0(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function S0(e,t){const n=Number(e);return Number.isFinite(n)?Math.floor(n):t}function Fy(e,t=1){const n=j0(Number(e)/100,0,1),r=Math.round(140-140*n),i=j0(Number(t),0,1);return i>=1?`hsl(${r} 85% 55%)`:`hsl(${r} 85% 55% / ${i})`}function N0(e){const t={...xh,...e||{}};return t.tickMs=Math.max(250,S0(t.tickMs,xh.tickMs)),t.historySize=Math.max(1,Math.min(200,S0(t.historySize,xh.historySize))),t.endpoint=String(t.endpoint||xh.endpoint),t.baseUrl=String(t.baseUrl||""),t.mode=String(t.mode||xh.mode).trim().toLowerCase(),t.mode!=="icon"&&(t.mode="full"),t}function m4(){return`
96
+ :host{display:inline-block;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,"Apple Color Emoji","Segoe UI Emoji";line-height:1}
97
+ .wrap{box-sizing:border-box;display:flex;flex-direction:column;gap:6px;padding:var(--monitor-gpu-padding,8px 10px);border:1px solid var(--monitor-gpu-border,#2a2f3a);border-radius:var(--monitor-gpu-radius,10px);background:var(--monitor-gpu-bg,#0b1020);color:var(--monitor-gpu-fg,#e7eaf0);width:var(--monitor-gpu-width,180px)}
98
+ .wrap.icon{gap:var(--monitor-gpu-gap,4px);padding:var(--monitor-gpu-padding,4px);border-radius:var(--monitor-gpu-radius,999px);width:var(--monitor-gpu-width,30px);background:linear-gradient(180deg,rgba(255,255,255,0.08),rgba(255,255,255,0.02)),var(--monitor-gpu-bg,#0b1020);box-shadow:0 0 14px var(--monitor-gpu-accent-glow, rgba(76,195,255,0.18))}
99
+ .wrap.icon .top{display:none}
100
+ .wrap.icon .bars{height:var(--monitor-gpu-bars-height,18px)}
101
+ .top{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
102
+ .label{font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.9}
103
+ .value{font-variant-numeric:tabular-nums;font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.95}
104
+ .bars{display:flex;align-items:flex-end;gap:2px;height:var(--monitor-gpu-bars-height,34px);overflow:hidden}
105
+ .bar{flex:1;min-width:0;border-radius:2px;background:var(--monitor-gpu-bar,#4cc3ff);height:2px;opacity:.9;transition:height .25s ease, background .25s ease, opacity .25s ease}
106
+ .bar.missing{background:var(--monitor-gpu-bar-missing,#62708a);opacity:.35}
107
+ .bar.error{background:var(--monitor-gpu-bar-error,#ff6b6b);opacity:.7}
108
+ .muted{opacity:.6}
109
+ `}class _4{constructor(t,n={}){if(!t||typeof t!="object")throw new TypeError("target element is required");this._target=t,this._opts=N0(n),this._buffer=new Qp(this._opts.historySize),this._timer=null,this._timer_gen=0,this._running=!1,this._abort=null,this._resumeTimer=null,this._mounted=!1,this._els=null,this._token=n.token,this._getToken=n.getToken,this._stoppedForAuth=!1}get options(){return{...this._opts}}set token(t){this._token=t,String(this._token||"").trim()&&this._stoppedForAuth&&(this._stoppedForAuth=!1,this.start())}get token(){return this._token}set getToken(t){this._getToken=t}get getToken(){return this._getToken}mount(){if(this._mounted)return;if(typeof document>"u")throw new Error("MonitorGpuWidget requires a browser DOM");const t=this._target;t.textContent="";const n=document.createElement("style");n.textContent=m4();const r=document.createElement("div");r.className=this._opts.mode==="icon"?"wrap icon":"wrap";const i=document.createElement("div");i.className="top";const o=document.createElement("div");o.className="label",o.textContent="GPU";const u=document.createElement("div");u.className="value muted",u.textContent="—",i.appendChild(o),i.appendChild(u);const l=document.createElement("div");l.className="bars",r.appendChild(i),r.appendChild(l),t.appendChild(n),t.appendChild(r),this._els={wrap:r,value:u,bars:l},this._mounted=!0,this._rebuildBars(),this._render()}start(){this.mount(),!this._running&&(this._running=!0,this._timer_gen+=1,this._poll_loop(this._timer_gen))}stop(){this._running=!1,this._timer_gen+=1,this._timer&&(clearTimeout(this._timer),this._timer=null),this._resumeTimer&&(clearTimeout(this._resumeTimer),this._resumeTimer=null),this._abort&&(this._abort.abort(),this._abort=null)}destroy(){this.stop(),this._target&&this._mounted&&(this._target.textContent=""),this._mounted=!1,this._els=null}setOptions(t){const n=N0({...this._opts,...t||{}}),r=n.historySize!==this._opts.historySize,i=n.tickMs!==this._opts.tickMs,o=n.mode!==this._opts.mode;this._opts=n,o&&this._mounted&&this._els&&this._els.wrap&&(this._els.wrap.className=n.mode==="icon"?"wrap icon":"wrap"),r&&(this._buffer.setMaxSize(n.historySize),this._mounted&&this._rebuildBars()),i&&this._running?(this.stop(),this.start()):this._mounted&&this._render()}push(t){this._buffer.push(t),this._render()}_rebuildBars(){if(!this._els)return;const{bars:t}=this._els;t.textContent="";for(let n=0;n<this._opts.historySize;n+=1){const r=document.createElement("div");r.className="bar missing",r.style.height="2px",t.appendChild(r)}}_render({error:t=!1}={}){if(!this._els)return;const{wrap:n,value:r,bars:i}=this._els,o=this._buffer.values(),u=this._buffer.last(),l=Number.isFinite(u)?Math.max(0,Math.min(100,u)):null;l==null?(r.textContent=t?"N/A":"—",r.classList.add("muted")):(r.textContent=`${l.toFixed(0)}%`,r.classList.remove("muted")),n&&(n.title=l==null?"GPU —":`GPU ${l.toFixed(0)}%`,l==null?(n.style.removeProperty("--monitor-gpu-accent"),n.style.removeProperty("--monitor-gpu-accent-glow")):(n.style.setProperty("--monitor-gpu-accent",Fy(l,.95)),n.style.setProperty("--monitor-gpu-accent-glow",Fy(l,.35))));const d=Array.from(i.children),h=Math.max(0,d.length-o.length),m=Math.max(2,i&&typeof i.clientHeight=="number"&&i.clientHeight>0?i.clientHeight:34);for(let _=0;_<d.length;_+=1){const g=d[_],y=_-h,b=y>=0?o[y]:null,k=Number.isFinite(b)?b:null,x=k==null?0:h4(k/100),N=Math.max(2,Math.min(m,Math.round(x*m)));g.style.height=`${N}px`,g.style.background=k==null?"":Fy(k),g.className="bar",k==null&&g.classList.add("missing"),t&&g.classList.add("error")}}async _tick(){const t=String(this._token||"").trim(),n=this._getToken,r=!!t||typeof n=="function";this._abort&&this._abort.abort(),this._abort=new AbortController;const i=await f4({baseUrl:this._opts.baseUrl,endpoint:this._opts.endpoint,token:t,getToken:n,signal:this._abort.signal}),o=i&&i.payload,u=o&&typeof o=="object"?o.supported!==!1:!0,l=d4(o);if(!i.ok){if(this._buffer.push(null),this._render({error:!0}),i.status===401||i.status===403){const d=String(this._token||"").trim(),h=typeof this._getToken=="function";if(!r&&(!!d||h))return;this._stoppedForAuth=!0,this.stop()}else i.status===429&&(this.stop(),this._resumeTimer=setTimeout(()=>{this._resumeTimer=null,this._mounted&&this.start()},3e4));return}if(!u||l==null){this._buffer.push(null),this._render();return}this._buffer.push(l),this._render()}async _poll_loop(t){!this._running||t!==this._timer_gen||(await this._tick(),!(!this._running||t!==this._timer_gen)&&(this._timer=setTimeout(()=>{this._timer=null,this._poll_loop(t)},this._opts.tickMs)))}}function p4(e="monitor-gpu"){if(typeof globalThis>"u"||typeof globalThis.customElements>"u"||globalThis.customElements.get(e))return;const t=globalThis.HTMLElement||class{};class n extends t{static get observedAttributes(){return["tick-ms","history-size","endpoint","base-url","mode"]}constructor(){super(),this._shadow=this.attachShadow?this.attachShadow({mode:"open"}):null;const i=this._shadow||this;this._controller=new _4(i,{}),this._upgradeProperty("token"),this._upgradeProperty("getToken"),this._upgradeProperty("mode")}_upgradeProperty(i){if(!Object.prototype.hasOwnProperty.call(this,i))return;const o=this[i];try{delete this[i]}catch{}this[i]=o}connectedCallback(){this._controller.setOptions(this._readAttrs());const i=()=>{this.isConnected&&this._controller.start()};typeof queueMicrotask=="function"?queueMicrotask(i):Promise.resolve().then(i)}disconnectedCallback(){this._controller.destroy()}attributeChangedCallback(){this._controller.setOptions(this._readAttrs())}_readAttrs(){const i=this.getAttribute("tick-ms"),o=this.getAttribute("history-size"),u=this.getAttribute("endpoint"),l=this.getAttribute("base-url"),d=this.getAttribute("mode");return{...i!=null?{tickMs:i}:{},...o!=null?{historySize:o}:{},...u!=null?{endpoint:u}:{},...l!=null?{baseUrl:l}:{},...d!=null?{mode:d}:{}}}set token(i){this._controller.token=i}get token(){return this._controller.token}set getToken(i){this._controller.getToken=i}get getToken(){return this._controller.getToken}set tickMs(i){this._controller.setOptions({tickMs:i})}get tickMs(){return this._controller.options.tickMs}set historySize(i){this._controller.setOptions({historySize:i})}get historySize(){return this._controller.options.historySize}set endpoint(i){this._controller.setOptions({endpoint:i})}get endpoint(){return this._controller.options.endpoint}set baseUrl(i){this._controller.setOptions({baseUrl:i})}get baseUrl(){return this._controller.options.baseUrl}set mode(i){this._controller.setOptions({mode:i})}get mode(){return this._controller.options.mode}}globalThis.customElements.define(e,n)}function Kd(e){return String(e||"").trim().toLowerCase()}function Lg(e){return`${(e==null?void 0:e.filename)||""} ${(e==null?void 0:e.source_path)||""}`.trim().toLowerCase()}function Vh(e,t){return t.some(n=>e.endsWith(n))}function g4(e){const t=(e==null?void 0:e.tags)||{};return[e==null?void 0:e.content_type,e==null?void 0:e.filename,e==null?void 0:e.source_path,e==null?void 0:e.modality,t.kind,t.type,t.source,t.format,t.content_format,t.name].map(n=>String(n||"").trim()).filter(Boolean).join(" ").toLowerCase()}function y4(e){const t=(e==null?void 0:e.tags)||{};return[e==null?void 0:e.content_type,e==null?void 0:e.filename,e==null?void 0:e.source_path,e==null?void 0:e.modality,e==null?void 0:e.semantic_kind,e==null?void 0:e.render_kind,e==null?void 0:e.task,t.semantic_kind,t.render_kind,t.kind,t.type,t.task,t.provider_task,t.source,t.format,t.content_format,t.name].map(n=>String(n||"").trim()).filter(Boolean).join(" ").toLowerCase()}function w4(e){const t=String(e||"").trimStart().slice(0,4096).toLowerCase();return t?!!(/^<!doctype\s+html\b/.test(t)||/^<html[\s>]/.test(t)||/<head[\s>][\s\S]*<\/head>/.test(t)||/<body[\s>][\s\S]*<\/body>/.test(t)||/<(?:article|main|section|div|p|h[1-6]|meta|title|script|style)\b[\s\S]*>/.test(t)&&/<\/(?:article|main|section|div|p|h[1-6]|title|script|style)>/.test(t)):!1}function QN(e,t){var u,l,d,h,m;const n=Kd(e==null?void 0:e.content_type),r=Lg(e),i=[e==null?void 0:e.semantic_kind,e==null?void 0:e.render_kind,e==null?void 0:e.task,(u=e==null?void 0:e.tags)==null?void 0:u.semantic_kind,(l=e==null?void 0:e.tags)==null?void 0:l.render_kind,(d=e==null?void 0:e.tags)==null?void 0:d.task,(h=e==null?void 0:e.tags)==null?void 0:h.kind,(m=e==null?void 0:e.tags)==null?void 0:m.type].map(_=>String(_||"").trim().toLowerCase()).filter(Boolean).join(" ");if(/(^|[^a-z0-9])(code|source_code|script|program|executable)([^a-z0-9]|$)/i.test(i)||n.includes("javascript")||n.includes("typescript")||n.includes("x-python")||n.includes("x-shellscript")||n.includes("x-rust")||n.includes("x-go")||n.includes("x-java")||n.includes("x-csrc")||n.includes("x-c++src")||Vh(r,[".py",".js",".jsx",".ts",".tsx",".mjs",".cjs",".sh",".bash",".zsh",".go",".rs",".java",".c",".cc",".cpp",".h",".hpp",".cs",".php",".rb",".swift",".kt",".sql"]))return!0;const o=String(t||"").replace(/\r\n/g,`
110
+ `).replace(/\r/g,`
111
+ `).split(`
112
+ `);return e1(o)}function v4(e){const n=String(e||"").replace(/\r\n/g,`
113
+ `).replace(/\r/g,`
114
+ `).split(`
115
+ `),r=n.findIndex(u=>/^Markdown Content:\s*$/i.test(u.trim()));if(r===-1)return null;const i=[];for(const u of n.slice(0,r)){const l=u.match(/^\s*([A-Za-z][A-Za-z0-9 /_-]{1,40}):\s*(.+?)\s*$/);l&&i.push({label:l[1].trim(),value:l[2].trim()})}const o=n.slice(r+1).join(`
116
+ `).trim();return!i.length&&!o?null:{metadata:i,body:o}}function x4(e){const t=e.map(n=>n.trim()).filter(Boolean).slice(0,8);if(t.length<2)return!1;for(const n of[","," ",";"]){const r=t.map(i=>i.split(n).length);if(r[0]>=3&&r.every(i=>Math.abs(i-r[0])<=1))return!0}return!1}function b4(e){const t=e.map(r=>r.trimEnd()).filter(Boolean).slice(0,20);if(!t.length)return!1;const n=t.filter(r=>/^(\[[^\]]+\]|\d{4}-\d{2}-\d{2}[t\s]|\w+:\s|traceback\b|error\b|warn\b|info\b)/i.test(r.trim())).length;return t.length>=4&&n/t.length>=.55?!0:e1(e)}function e1(e){const t=e.map(r=>r.trimEnd()).filter(Boolean).slice(0,20);if(!t.length)return!1;const n=t.filter(r=>/[{};]\s*$/.test(r)||/^\s*(import|export|const|let|var|function|class|def|if|for|while|return)\b/.test(r)).length;return t.length>=4&&n/t.length>=.55}function k4(e){const t=String(e||"");if(!t.trim())return!1;const n=t.match(/\\[A-Za-z]{2,}\b/g)||[];if(n.length>=1&&/\\(?:setcctype|sectctype|documentclass|begin|end|maketitle|geq|leq|cite|ref|label)\b/.test(t)||n.length>=4)return!0;const i=t.replace(/\r\n/g,`
117
+ `).replace(/\r/g,`
118
+ `).split(`
119
+ `).map(d=>d.trim()).filter(Boolean).slice(0,80);if(i.length<12)return!1;const o=i.filter(d=>d.length<=28).length,u=i.filter(d=>/^[,.;:()†]+$/.test(d)).length;return i.filter(d=>/^(abstract\.?|introduction|references|appendix|figure\s+\d+|table\s+\d+)\b/i.test(d)).length>=2&&(o/i.length>=.45||u>=2)}function j4(e,t){var h;const n=String(t||""),r=g4(e);if(/(^|[^a-z0-9])(markdown|mdown)([^a-z0-9]|$)/i.test(r))return!0;if(!n.trim())return!1;if(/(^|\n)\s*Markdown Content:\s*(\n|$)/i.test(n)||n.includes("```")||/(^|\n)\s*#{1,6}\s+\S/.test(n)||/(^|\n)[ \t]*[-*][ \t]+\S/.test(n)||/(^|\n)[ \t]*\d+[\.)][ \t]+\S/.test(n)||/\*\*[^*\n][\s\S]*?\*\*/.test(n)||/\[[^\]\n]+\]\([^)]+\)/.test(n)||/(^|\n)\s*\|.+\|\s*(\n|$)/.test(n)&&/(^|\n)\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*(\n|$)/.test(n))return!0;const i=n.replace(/\r\n/g,`
120
+ `).replace(/\r/g,`
121
+ `).split(`
122
+ `),o=i.map(m=>m.trim()).filter(Boolean);if(o.length<2||k4(n)||x4(i)||b4(i))return!1;const u=((h=n.match(/[A-Za-z][A-Za-z'-]+/g))==null?void 0:h.length)||0,l=i.filter(m=>!m.trim()).length,d=o.filter(m=>/[A-Za-z]{3,}/.test(m)&&m.length>=12).length;return u>=24&&d>=2&&(l>=1||o[0].length<=140)}function Gh(e){const t=Kd(e==null?void 0:e.modality),n=Kd(e==null?void 0:e.content_type),r=Lg(e),i=y4(e);return t==="image"||n.startsWith("image/")||Vh(r,[".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".tif",".tiff",".heic"])?"image":t==="audio"||t==="voice"||t==="music"||t==="sound"||n.startsWith("audio/")||/(tts|stt|voice|music|sound|speech|audio)/i.test(i)||Vh(r,[".wav",".mp3",".m4a",".aac",".flac",".ogg",".opus",".aiff",".mid",".midi"])?"audio":t==="video"||n.startsWith("video/")||Vh(r,[".mp4",".mov",".webm",".mkv",".avi",".m4v"])?"video":!n||t==="text"||n.startsWith("text/")||n.includes("json")||n.includes("yaml")||n.includes("toml")||n.includes("xml")||n.includes("html")||n.includes("markdown")||n.includes("csv")||QN(e,"")?"text":"binary"}function eg(e,t){const n=Kd(e==null?void 0:e.content_type),r=Lg(e),i=String(t||"").trim();return n.includes("html")||r.endsWith(".html")||r.endsWith(".htm")||w4(t)?"html":QN(e,t)?"code":n.includes("markdown")||r.endsWith(".md")||r.endsWith(".markdown")?"markdown":n.includes("json")||r.endsWith(".json")||r.endsWith(".jsonl")||(i.startsWith("{")||i.startsWith("["))&&Tg(i)!==null?"json":j4(e,t)?"markdown":"text"}function cx(e,t=""){const n=Gh(e);if(n==="image"||n==="video")return n;if(n==="audio"){const r=(e==null?void 0:e.tags)||{},i=[e==null?void 0:e.semantic_kind,e==null?void 0:e.modality,e==null?void 0:e.task,r.semantic_kind,r.modality,r.kind,r.task,r.source,e==null?void 0:e.filename,e==null?void 0:e.source_path].map(o=>String(o||"").trim().toLowerCase()).filter(Boolean).join(" ");return/(^|[^a-z0-9])(voice|tts|speech)([^a-z0-9]|$)/i.test(i)?"voice":/(^|[^a-z0-9])(music|song|instrumental|t2m)([^a-z0-9]|$)/i.test(i)?"music":/(^|[^a-z0-9])(sound|sfx|recording)([^a-z0-9]|$)/i.test(i)?"sound":"audio"}if(n==="binary"){const r=Kd(e==null?void 0:e.modality),i=Kd(e==null?void 0:e.content_type),o=Lg(e);return r==="document"||i.includes("pdf")||Vh(o,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return eg(e,t)}function zy(e){var h,m;const t=String(e||"").replace(/\r\n/g,`
123
+ `).replace(/\r/g,`
124
+ `).trim();if(!t)return"";const n=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),r=t.match(/<!--[\s\S]*?-->|<!doctype\b[^>]*>|<!\[CDATA\[[\s\S]*?\]\]>|<\/?[A-Za-z][^>]*>|[^<]+/gi)||[t],i=[];let o=0,u="";const l=_=>" ".repeat(Math.max(0,_)),d=(_,g)=>{const y=_.match(/^(<\/?|<!)([^\s/>]+)([\s\S]*?)(\/?>)$/);if(!y||_.length<=120||_.startsWith("</")||_.startsWith("<!"))return[`${l(g)}${_.trim()}`];const b=(y[3]||"").trim();if(!b)return[`${l(g)}${_.trim()}`];const k=b.match(/[^\s="'<>`]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>`]+))?/g)||[b];return[`${l(g)}${y[1]}${y[2]}`,...k.map(x=>`${l(g+1)}${x.trim()}`),`${l(g)}${y[4]}`]};for(const _ of r){const g=String(_||"");if(!g.trim())continue;const y=g.trim().toLowerCase();if(y.startsWith("</")){const k=((h=y.match(/^<\/\s*([a-z0-9:-]+)/))==null?void 0:h[1])||"";u&&k===u&&(u=""),o=Math.max(0,o-1),i.push(`${l(o)}${g.trim()}`);continue}if(g.trimStart().startsWith("<")){i.push(...d(g,o));const k=((m=y.match(/^<\s*([a-z0-9:-]+)/))==null?void 0:m[1])||"";/\/>\s*$/.test(g)||y.startsWith("<!")||n.has(k)||(o+=1,(k==="script"||k==="style")&&(u=k));continue}if(u){const k=g.trim();k&&i.push(...k.split(`
125
+ `).map(x=>`${l(o)}${x.trimEnd()}`));continue}const b=g.replace(/\s+/g," ").trim();b&&i.push(`${l(o)}${b}`)}return i.join(`
126
+ `)}const S4=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function ux(e){const t=typeof e=="string"?e:String(e??""),n=S4.exec(t);if(!n)return{text:t.trim(),metadata:null,stripped:!1};let r=null;try{const i=JSON.parse(String(n[1]||"").trim());i&&typeof i=="object"&&!Array.isArray(i)&&(r=i)}catch{r=null}return{text:t.slice(n[0].length).trim(),metadata:r,stripped:!0}}function t1(...e){const t={};for(const n of e)if(!(!n||typeof n!="object"||Array.isArray(n)))for(const[r,i]of Object.entries(n))i==null||String(i).trim()===""||(t[r]=i);return Object.keys(t).length?t:null}function Qw(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>Qw(t)).filter(Boolean).join(`
127
+ `).trim();if(typeof e=="object"){const t=e.text??e.content??e.message??e.value;if(t!==e){const n=Qw(t);if(n)return n}}return""}function n1(e){const t=ux(Qw(e));return{text:t.text,runtime_metadata:t.metadata}}function N4(e){var r,i;if(!e)return{text:"",runtime_metadata:null};const t=typeof e.prompt=="string"?String(e.prompt).trim():"";if(t){const o=ux(t);return{text:o.text,runtime_metadata:o.metadata}}const n=[(r=e.context)==null?void 0:r.messages,e.messages,e.conversation,e.history].filter(Array.isArray);for(const o of n)for(let u=o.length-1;u>=0;u-=1){const l=o[u],d=String((l==null?void 0:l.role)||(l==null?void 0:l.speaker)||"").trim().toLowerCase();if(d&&d!=="user"&&d!=="human")continue;const h=n1((l==null?void 0:l.content)??(l==null?void 0:l.text)??l);if(h.text)return{text:h.text,runtime_metadata:t1(h.runtime_metadata,l!=null&&l.runtime_metadata&&typeof l.runtime_metadata=="object"?l.runtime_metadata:null,(i=l==null?void 0:l.metadata)!=null&&i.runtime_metadata&&typeof l.metadata.runtime_metadata=="object"?l.metadata.runtime_metadata:null)}}return{text:"",runtime_metadata:null}}function $4(e,t=6){var o,u;if(!e)return[];const r=[(o=e.context)==null?void 0:o.messages,e.messages,e.conversation,e.history].filter(Array.isArray).find(l=>l.length)||[],i=[];for(const l of r){const d=String((l==null?void 0:l.role)||(l==null?void 0:l.speaker)||(l==null?void 0:l.author)||"").trim().toLowerCase()||"message",h=n1((l==null?void 0:l.content)??(l==null?void 0:l.text)??(l==null?void 0:l.message)??l),m=h.text;if(!m)continue;const _=String((l==null?void 0:l.ts)||(l==null?void 0:l.timestamp)||(l==null?void 0:l.created_at)||(l==null?void 0:l.time)||"").trim(),g=t1(h.runtime_metadata,l!=null&&l.runtime_metadata&&typeof l.runtime_metadata=="object"?l.runtime_metadata:null,(u=l==null?void 0:l.metadata)!=null&&u.runtime_metadata&&typeof l.metadata.runtime_metadata=="object"?l.metadata.runtime_metadata:null);i.push({role:d,text:m,ts:_,runtime_metadata:g})}return i.slice(Math.max(0,i.length-Math.max(1,t)))}function s1(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function C4(e){const t=e.map(n=>String((n==null?void 0:n.name)||"tool").trim()).filter(Boolean);return t.length?`${t.slice(0,3).join(", ")}${t.length>3?` +${t.length-3}`:""}`:""}const r1="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function i1(e){const t=String((e==null?void 0:e.name)||"").trim().toLowerCase(),n=e!=null&&e.arguments&&typeof e.arguments=="object"?e.arguments:{},r=String((n==null?void 0:n.command)||(n==null?void 0:n.cmd)||(n==null?void 0:n.shell)||"").trim().toLowerCase(),i=[];return(t.includes("execute_command")||t.includes("terminal")||r)&&i.push("Shell"),/[;&|]?\s*(rm|rmdir|mv|chmod|chown|sudo)\b/.test(r)&&i.push("Destructive risk"),/(^|\s)(curl|wget|scp|ssh|nc|ncat|ftp)\b/.test(r)&&i.push("Network"),/(^|\s)(cat|sed|rg|grep|ls|find|pwd)\b/.test(r)&&!/[>|]\s*\S/.test(r)&&i.push("Read path"),/[>|]\s*\S|(^|\s)(tee|touch|mkdir|cp)\b/.test(r)&&i.push("Filesystem write"),i.length||i.push("Tool call"),Array.from(new Set(i)).slice(0,4)}function dx(e,t){const n=String((e==null?void 0:e.reason)||"").trim().toLowerCase(),r=C4(t);return t.length?`Approval required: ${r||"tool call"}`:n==="user"?"Waiting for your answer":n==="event"?"Waiting for a user response event":n==="subworkflow"?"Waiting for a subworkflow":n==="until"?"Scheduled wait":n?`Waiting: ${n}`:"Waiting for input"}function o1(e,t){return t.length?"Review the requested tool call, then approve and execute it, approve without local execution, reject it, or cancel the whole run.":(Array.isArray(e==null?void 0:e.choices)?(e==null?void 0:e.choices)||[]:[]).length?"Select one of the allowed responses, then submit it to resume this run.":(e==null?void 0:e.allow_free_text)===!1?"This wait does not allow free text. Use the available response control or inspect the ledger.":String((e==null?void 0:e.prompt)||"").trim()?"Answer the workflow question below. Submitting resumes only this wait.":"No explicit question was emitted. Inspect the original request and recent ledger context before responding."}function a1(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),r=ux(n),i=N4(t);return r.text&&!s1(r.text)?{text:r.text,runtime_metadata:r.metadata}:i.text?i:{text:r.text||n,runtime_metadata:r.metadata}}function E4(e,t){return a1(e,t).text}function A4(e,t){return e||String(t||"").trim()||{}}function Vo(e,t){const n=String((e==null?void 0:e.schedule_target_workflow_id)||(e==null?void 0:e.workflow_id)||"").trim();return n?t[n]||n:"(workflow unknown)"}function gu(e){const t=String(e.status||"unknown").trim()||"unknown";return s.jsx("span",{className:`run_status_pill ${ka(t)}`,children:t})}function T4(e){var o;const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(ds(t))return"";const n=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,r=String((n==null?void 0:n.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase(),i=Array.isArray((o=n==null?void 0:n.details)==null?void 0:o.tool_calls)?n.details.tool_calls:[];return i.length?dx(n,i):r==="user"?"Waiting for your answer":r==="event"?"Waiting for a response event":r==="subworkflow"?"Waiting for subworkflow":r==="until"?"Scheduled wait":r?`Waiting: ${r}`:t==="waiting"?"Waiting, reason unknown":""}function nm(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?en(t,{max_chars:220,max_lines:2}):en(Fr(t,400),{max_chars:220,max_lines:2}):""}function M4(e){const t=T4(e);if(t)return t;const n=nm(e);if(n)return n;const r=String((e==null?void 0:e.current_node)||"").trim();if(r)return`Current node: ${r}`;const i=String((e==null?void 0:e.status)||"").trim().toLowerCase();return i==="running"?"Running":ds(i)?"Terminal":"No current activity reported"}function l1(e){return e!=null&&e.ref&&typeof e.ref=="object"?e.ref:e!=null&&e.artifact_ref&&typeof e.artifact_ref=="object"?e.artifact_ref:e!=null&&e.artifact&&typeof e.artifact=="object"?e.artifact:{}}function $0(e){const t=l1(e),n=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},r=e!=null&&e.tags&&typeof e.tags=="object"?e.tags:{},i=qn(e==null?void 0:e.modality,t==null?void 0:t.modality,n==null?void 0:n.modality,r.modality).toLowerCase();if(i)return i;const o=qn(e==null?void 0:e.content_type,e==null?void 0:e.mime_type,e==null?void 0:e.mime,t==null?void 0:t.content_type,t==null?void 0:t.mime_type,t==null?void 0:t.mime,n==null?void 0:n.content_type,r.content_type).toLowerCase();return o.startsWith("image/")?"image":o.startsWith("audio/")?"audio":o.startsWith("video/")?"video":o.includes("pdf")?"document":o.startsWith("text/")||o.includes("json")||o.includes("markdown")||o.includes("csv")?"text":"artifact"}function R4(e){return!e||typeof e!="object"?{}:e.artifact_envelope_v1&&typeof e.artifact_envelope_v1=="object"?e.artifact_envelope_v1:e.envelope&&typeof e.envelope=="object"?e.envelope:e}function L4(e,t){if(!e||typeof e!="object")return null;const n=R4(e),r=l1(e),i=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},o=n!=null&&n.descriptor&&typeof n.descriptor=="object"?n.descriptor:e!=null&&e.descriptor&&typeof e.descriptor=="object"?e.descriptor:{},u=qn(n.artifact_id,e.artifact_id,e.$artifact,e.id,r.artifact_id,r.$artifact,r.id,i.artifact_id,i.$artifact);if(!u)return null;const l={...r.tags&&typeof r.tags=="object"?r.tags:{},...i.tags&&typeof i.tags=="object"?i.tags:{},...n.tags&&typeof n.tags=="object"?n.tags:{},...e.tags&&typeof e.tags=="object"?e.tags:{}},d={};for(const[S,P]of Object.entries(l)){const D=String(S||"").trim();D&&(d[D]=String(P??""))}const h=qn(n.filename,e.filename,r.filename,i.filename,d.filename,d.name,e.name,r.name),m=qn(n.source_path,e.source_path,r.source_path,i.source_path,e.path,r.path,d.path,d.source_path,d.file_path),_=qn(n.content_type,e.content_type,e.mime_type,e.mime,r.content_type,r.mime_type,r.mime,i.content_type,d.content_type),g=qn(n.render_kind,o.render_kind,e.render_kind,d.render_kind),y=qn(n.semantic_kind,o.semantic_kind,e.semantic_kind,d.semantic_kind,d.artifact_type),b=n.access&&typeof n.access=="object"?n.access:e.access&&typeof e.access=="object"?e.access:{},k=n.producer&&typeof n.producer=="object"?n.producer:e.producer&&typeof e.producer=="object"?e.producer:o.producer&&typeof o.producer=="object"?o.producer:{},x=n.provenance&&typeof n.provenance=="object"?n.provenance:e.provenance&&typeof e.provenance=="object"?e.provenance:o.provenance&&typeof o.provenance=="object"?o.provenance:{},N=n.generation&&typeof n.generation=="object"?n.generation:e.generation&&typeof e.generation=="object"?e.generation:o.generation&&typeof o.generation=="object"?o.generation:{},$=n.media&&typeof n.media=="object"?n.media:e.media&&typeof e.media=="object"?e.media:o.media&&typeof o.media=="object"?o.media:{},E=n.links&&typeof n.links=="object"?n.links:e.links&&typeof e.links=="object"?e.links:o.links&&typeof o.links=="object"?o.links:{};return{artifact_id:u,run_id:qn(n.run_id,e.run_id,r.run_id,i.run_id,d.run_id,x.run_id),content_type:_,modality:qn(n.modality,e.modality,o.modality,d.modality)||$0({...e,ref:r,metadata:i,tags:d}),semantic_kind:y||$0({...e,ref:r,metadata:i,tags:d}),render_kind:g||cx({content_type:_,filename:h,source_path:m,modality:qn(n.modality,e.modality,d.modality),tags:d}),task:qn(n.task,o.task,e.task,d.task,d.provider_task),classification_source:qn(n.classification_source,o.classification_source,e.classification_source),session_id:qn(n.session_id,o.session_id,e.session_id,d.session_id),workflow_id:qn(n.workflow_id,o.workflow_id,e.workflow_id,d.workflow_id,d.workflow),node_id:qn(n.node_id,o.node_id,e.node_id,d.node_id,d.node),step_id:qn(n.step_id,o.step_id,e.step_id,d.step_id),effect_id:qn(n.effect_id,o.effect_id,e.effect_id,d.effect_id,d.effect_idempotency_key),turn_id:qn(n.turn_id,o.turn_id,e.turn_id,d.turn_id,d.turn),ledger_cursor:qn(n.ledger_cursor,o.ledger_cursor,e.ledger_cursor,d.ledger_cursor,d.step_cursor),parent_run_id:qn(n.parent_run_id,o.parent_run_id,e.parent_run_id,d.parent_run_id),actor_id:qn(n.actor_id,o.actor_id,e.actor_id,d.actor_id),title:qn(n.title,e.title,d.title,d.label,d.name),created_at:qn(n.created_at,e.created_at,r.created_at,i.created_at,d.created_at),size_bytes:DI(n.size_bytes,e.size_bytes,r.size_bytes,i.size_bytes,d.size_bytes),filename:h,source_path:m,sha256:qn(n.sha256,e.sha256,r.sha256,i.sha256,d.sha256),tags:d,producer:k,provenance:x,generation:N,media:$,source_refs:Array.isArray(n.source_refs)?n.source_refs:Array.isArray(e.source_refs)?e.source_refs:[],access:b,links:E,available_actions:Array.isArray(n.available_actions)?n.available_actions.map(String):Array.isArray(e.available_actions)?e.available_actions.map(String):[],provider_trace_available:!!(n.provider_trace_available??e.provider_trace_available),audit_available:!!(n.audit_available??e.audit_available),legacy_inferred:!!((n.legacy_inferred??e.legacy_inferred)||/(?:legacy|inferred|runtime_tags|runtime_mime)/i.test(qn(n.classification_source,o.classification_source,e.classification_source))),descriptor:o,source:t,raw:e}}function tg(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||Rn(e.artifact_id,16)}function I4(e,t){if(t==="type")return Bd(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return ev(e);if(t==="node")return zd(e)||"(node unknown)";if(t==="workflow")return fx(e)||"(workflow unknown)";if(t==="location"){const i=(e.source_path||e.filename||"").split("/").filter(Boolean);return i.length>1?i.slice(0,-1).join("/"):"(root)"}if(t==="source")return sm(e)||e.source||"artifact";const n=Ht(e.created_at);return n===null?"(unknown time)":new Date(n).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function fx(e){const t=(e==null?void 0:e.tags)||{};return String((e==null?void 0:e.workflow_id)||t.workflow_id||t.workflow||"").trim()}function zd(e){const t=(e==null?void 0:e.tags)||{},n=String((e==null?void 0:e.node_id)||t.node_id||t.node||(e==null?void 0:e.step_id)||t.step_id||"").trim();if(n)return n;const i=String((e==null?void 0:e.source_path)||t.path||"").trim().match(/(?:^|[._:/-])(node-[A-Za-z0-9_-]+)/);return i!=null&&i[1]?String(i[1]):""}function ev(e){const t=(e==null?void 0:e.tags)||{},n=String((e==null?void 0:e.turn_id)||t.turn_id||t.turn||t.cycle||(e==null?void 0:e.ledger_cursor)||t.ledger_cursor||t.step_cursor||"").trim();if(n)return`turn ${n}`;const r=zd(e),i=Ht(e==null?void 0:e.created_at),o=i===null?"unknown time":new Date(i).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),u=e!=null&&e.run_id?Rn(String(e.run_id),10):"unknown run";return r?`${u} · ${r} · ${o}`:`${u} · ${o}`}function C0(e){if(!e)return"provenance unavailable";const t=[],n=fx(e),r=zd(e),i=sm(e),o=c1(e);return n&&t.push(n),r&&t.push(r),i&&t.push(i),o&&t.push(o),t.length?t.join(" · "):"provenance unavailable"}function su(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"—";const t=["B","KB","MB","GB","TB"];let n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;const i=r===0?0:n>=10?1:2;return`${n.toFixed(i)} ${t[r]}`}function Bd(e){const t=String((e==null?void 0:e.semantic_kind)||(e==null?void 0:e.modality)||"").trim().toLowerCase(),n=String((e==null?void 0:e.render_kind)||"").trim().toLowerCase(),r=t||n||"artifact";return{voice:"Voice",music:"Music",sound:"Sound",recording:"Recording",audio:"Unclassified audio",image:"Image",video:"Video",markdown:"Markdown",html:"HTML",json:"JSON",document:"Document",code:"Code",text:"Text",binary:"Other",artifact:"Other"}[r]||r.replace(/[_-]+/g," ").replace(/\b\w/g,o=>o.toUpperCase())}function O4(e){return e==="html"?"HTML":e==="json"?"JSON":e==="audio"?"Unclassified audio":e==="code"?"Code":e.slice(0,1).toUpperCase()+e.slice(1)}function P4(e){const t=Date.now();if(e==="hour")return new Date(t-3600*1e3).toISOString();if(e==="week")return new Date(t-10080*60*1e3).toISOString();if(e==="month")return new Date(t-720*60*60*1e3).toISOString();if(e==="today"){const n=new Date(t);return new Date(n.getFullYear(),n.getMonth(),n.getDate()).toISOString()}return""}function D4(e){return e==="oldest"?{order_by:"created_at",order:"asc"}:e==="size_desc"?{order_by:"size_bytes",order:"desc"}:e==="size_asc"?{order_by:"size_bytes",order:"asc"}:e==="last_access"?{order_by:"last_accessed_at",order:"desc"}:e==="turn"?{order_by:"turn",order:"asc"}:e==="type"?{order_by:"semantic_kind",order:"asc"}:{order_by:"created_at",order:"desc"}}function E0(e){const t=e!=null&&e.stats&&typeof e.stats=="object"?e.stats:{},n=t!=null&&t.facets&&typeof t.facets=="object"?t.facets:e!=null&&e.facets&&typeof e.facets=="object"?e.facets:{};return n&&typeof n=="object"?n:{}}function F4(e){const t=Vd(e.created_at),n=lu(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function A0(e){var i;const t=e.tags||{},n=String(((i=e.access)==null?void 0:i.last_accessed_at)||t.last_accessed_at||t.accessed_at||t.updated_at||e.created_at||"").trim(),r=Vd(n);return r==="—"?"—":r}function T0(e){const t=e.tags||{},n=String(e.title||t.title||t.name||t.label||e.filename||"").trim();if(n)return n;const r=String(e.source_path||t.path||"").trim();if(r)return r.split("/").filter(Boolean).slice(-1)[0]||r;const i=sm(e),o=Bd(e);return i?`${o} ${i}`:`${o} artifact`}function sm(e){var n;const t=e.tags||{};return String(e.task||((n=e.provenance)==null?void 0:n.source)||t.task||t.kind||t.source||e.source||"").trim()}function c1(e){var r,i,o,u,l,d,h,m;if(!e)return"";const t=qn((r=e.producer)==null?void 0:r.provider,(i=e.producer)==null?void 0:i.provider_id,(o=e.provenance)==null?void 0:o.provider,(u=e.generation)==null?void 0:u.provider),n=qn((l=e.producer)==null?void 0:l.model,(d=e.producer)==null?void 0:d.model_id,(h=e.provenance)==null?void 0:h.model,(m=e.generation)==null?void 0:m.model);return t&&n?`${t} / ${n}`:t||n}function z4(e){var t,n,r,i;return e?qn((t=e.generation)==null?void 0:t.prompt,(n=e.generation)==null?void 0:n.input,(r=e.generation)==null?void 0:r.text,(i=e.provenance)==null?void 0:i.prompt):""}function M0(e){if(!e)return"";const t=e.media||{},n=Number(t.duration_s??t.duration_seconds??t.duration),r=Number(t.width??t.image_width??t.video_width),i=Number(t.height??t.image_height??t.video_height),o=Number(t.sample_rate??t.sample_rate_hz),u=Number(t.channels);if(Number.isFinite(n)&&n>0){const d=[`${n>=60?`${Math.floor(n/60)}m ${Math.round(n%60)}s`:`${n.toFixed(n>=10?1:2)}s`}`];return Number.isFinite(o)&&o>0&&d.push(`${Math.round(o/1e3)} kHz`),Number.isFinite(u)&&u>0&&d.push(`${u} ch`),d.join(" · ")}if(Number.isFinite(r)&&Number.isFinite(i)&&r>0&&i>0)return`${Math.round(r)} x ${Math.round(i)}`;const l=Number(t.page_count??t.pages);return Number.isFinite(l)&&l>0?`${Math.round(l)} pages`:""}function R0(e){return e.source_path||e.filename||""}function ng(e,t,n){const r=e.run_id&&t[e.run_id]||null;if(!r)return e;const i=Vo(r,n),o={...e.tags||{}};return i&&!o.workflow&&(o.workflow=i),i&&!o.workflow_id&&(o.workflow_id=i),{...e,workflow_id:e.workflow_id||i,tags:o}}function tv(e,t,n,r=""){const i=ng(e,t,n),o=cx(i,r);return{json:"JSON",html:"HTML",markdown:"Markdown",code:"Code",voice:"Voice",music:"Music",sound:"Sound",audio:"Unclassified audio",image:"Image",video:"Video",document:"Document",text:"Text",other:"Other"}[o]||Bd(i)}function Ya(e){var r;const t=e,n=(r=t==null?void 0:t.result)==null?void 0:r.wait;return!n||typeof n!="object"?null:n}function op(e){var o,u,l;const t=e,n=t==null?void 0:t.effect;if(!n||typeof n!="object"||String(n.type||"")!=="emit_event")return null;const r=String(((o=n==null?void 0:n.payload)==null?void 0:o.name)||((u=n==null?void 0:n.payload)==null?void 0:u.event_name)||"").trim();if(!r)return null;const i=(l=n==null?void 0:n.payload)==null?void 0:l.payload;return{name:r,payload:i}}function sf(e){const t=e,n=t==null?void 0:t.details;if(!n||typeof n!="object")return[];if(Array.isArray(n))return n.filter(i=>i&&typeof i=="object"&&typeof i.name=="string");const r=n==null?void 0:n.tool_calls;return Array.isArray(r)?r:[]}function B4(e){var i,o;const t=String((e==null?void 0:e.status)||"").trim(),n=String(((i=e==null?void 0:e.effect)==null?void 0:i.type)||"").trim(),r=(o=e==null?void 0:e.effect)!=null&&o.payload&&typeof e.effect.payload=="object"?String(e.effect.payload.name||"").trim():"";return n==="emit_event"&&r?r:n||t||"record"}function u1(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),r=B4(e),i=Ya(e);if(i){const o=String(i.reason||"").trim();if(String(i.prompt||"").trim())return`${t||"node"} is waiting for a response`;if(o)return`${t||"node"} is waiting (${o})`}return e.error?`${t||"node"} failed`:n==="completed"?`${t||"node"} completed ${r}`:n==="running"?`${t||"node"} started ${r}`:n==="waiting"?`${t||"node"} is waiting`:[t,n,r].filter(Boolean).join(" · ")||"Ledger record"}function xd(e){if(typeof e=="string")return{text:e,duration:-1};if(e&&typeof e=="object"){const t=typeof e.text=="string"?String(e.text):typeof e.value=="string"?String(e.value):typeof e.message=="string"?String(e.message):Fr(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:Fr(e,320),duration:-1}}function d1(e){var u,l,d,h,m,_,g,y,b;if(!e||typeof e!="object")return"";const t=String(((u=e==null?void 0:e.effect)==null?void 0:u.type)||"").trim(),n=e==null?void 0:e.result,r=k=>typeof k=="string"?k.trim():k==null?"":typeof k=="number"||typeof k=="boolean"?String(k):"",i=k=>{if(!k||typeof k!="object")return"";const x=k,N=[x.response,x.answer,x.message,x.text,x.content];for(const $ of N){const E=r($);if(E)return E}return""};if(t==="answer_user"){const k=r(n==null?void 0:n.message)||r((l=n==null?void 0:n.output)==null?void 0:l.message)||r((d=n==null?void 0:n.output)==null?void 0:d.response)||r((m=(h=e==null?void 0:e.effect)==null?void 0:h.payload)==null?void 0:m.message)||r((g=(_=e==null?void 0:e.effect)==null?void 0:_.payload)==null?void 0:g.text)||r((b=(y=e==null?void 0:e.effect)==null?void 0:y.payload)==null?void 0:b.content);if(k)return k}if(t==="llm_call"){const k=i(n)||r(n==null?void 0:n.output)||i(n==null?void 0:n.output)||r(n==null?void 0:n.response);if(k)return k}return r(n==null?void 0:n.output)||i(n==null?void 0:n.output)||i(n)||r(n==null?void 0:n.response)}function Ap(e){var i;const t=String((e==null?void 0:e.node_id)||""),n=String((e==null?void 0:e.status)||""),r=String(((i=e==null?void 0:e.effect)==null?void 0:i.type)||"");return`${t||"(node?)"} • ${n||"(status?)"} • ${r||"(effect?)"}`}function U4(e){return!!(e&&String(e.status||"")==="waiting")}function W4(e){var n,r;const t=[];for(const i of e||[]){const o=i.record;if(String(((n=o==null?void 0:o.effect)==null?void 0:n.type)||"").trim()!=="llm_call")continue;const l=(r=o==null?void 0:o.effect)!=null&&r.payload&&typeof o.effect.payload=="object"?o.effect.payload:{},d=o!=null&&o.result&&typeof o.result=="object"?o.result:{},h=(d==null?void 0:d.usage)||(d==null?void 0:d.token_usage)||{},m=typeof l.prompt=="string"?l.prompt:Array.isArray(l.messages)?Fr(l.messages,1800):"",_=typeof d.content=="string"?d.content:typeof d.response=="string"?d.response:typeof o.result=="string"?String(o.result):"",g=Ht(o.started_at),y=Ht(o.ended_at),b=Number(h.prompt_tokens??h.input_tokens??0)||0,k=Number(h.completion_tokens??h.output_tokens??0)||0;t.push({id:`${String(i.run_id||o.run_id||"")}:${i.cursor}`,cursor:Number(i.cursor||0),ts:String(o.ended_at||o.started_at||""),run_id:String(i.run_id||o.run_id||"").trim(),node_id:String(o.node_id||"").trim(),provider:String(l.provider||d.provider||d.runtime_provider||"").trim(),model:String(l.model||d.model||d.runtime_model||"").trim(),prompt_preview:en(m,{max_chars:1200,max_lines:10}),response_preview:en(_,{max_chars:1200,max_lines:10}),missing_response:!String(_||"").trim(),tokens:{prompt:b,completion:k,total:Number(h.total_tokens??b+k)||0},duration_ms:g!==null&&y!==null?Math.max(0,y-g):typeof d.gen_time=="number"?Number(d.gen_time)*1e3:null,status:String(o.status||"").trim(),error:o.error?Fr(o.error,500):"",raw:o})}return t.sort((i,o)=>(Ht(o.ts)??0)-(Ht(i.ts)??0))}function L0(e){const t=e.size||18,n=Gh(e.artifact),r=cx(e.artifact,""),i=`artifact_glyph ${r==="code"?"code":n}`,o={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"};return n==="image"?s.jsx("span",{className:i,children:s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M7 15l3-3 3 3 2-2 4 4"}),s.jsx("circle",{cx:"8",cy:"9",r:"1.4"})]})}):n==="audio"?s.jsx("span",{className:i,children:s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 12h2"}),s.jsx("path",{d:"M8 8v8"}),s.jsx("path",{d:"M12 5v14"}),s.jsx("path",{d:"M16 8v8"}),s.jsx("path",{d:"M20 12h-2"})]})}):n==="video"?s.jsx("span",{className:i,children:s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M9 9l6 3-6 3V9z",fill:"currentColor",stroke:"none"})]})}):r==="code"?s.jsx("span",{className:i,children:s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M8 8l-4 4 4 4"}),s.jsx("path",{d:"M16 8l4 4-4 4"}),s.jsx("path",{d:"M14 4l-4 16"})]})}):n==="text"?s.jsx("span",{className:i,children:s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M7 3h7l5 5v13H7z"}),s.jsx("path",{d:"M14 3v6h6"}),s.jsx("path",{d:"M10 13h7"}),s.jsx("path",{d:"M10 17h5"})]})}):s.jsx("span",{className:i,children:s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M7 3h7l5 5v13H7z"}),s.jsx("path",{d:"M14 3v6h6"}),s.jsx("path",{d:"M9 14h8"})]})})}const q4=2,H4=Number.MAX_SAFE_INTEGER;function V4(e,t=120){const n=String(e||"").replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1)).trimEnd()}…`}function G4(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:zy(t)||t}];try{const n=new DOMParser().parseFromString(t,"text/html"),r=[];n.doctype&&r.push({kind:"doctype",name:n.doctype.name||"html"});const i=o=>{if(o.nodeType===Node.TEXT_NODE){const u=String(o.textContent||"").trim();return u?{kind:"text",text:u}:null}if(o.nodeType===Node.COMMENT_NODE)return{kind:"comment",text:String(o.textContent||"")};if(o.nodeType===Node.ELEMENT_NODE){const u=o,l=Array.from(u.attributes||[]).map(h=>({name:h.name,value:h.value})),d=Array.from(u.childNodes||[]).map(i).filter(Boolean);return{kind:"element",tag:u.tagName.toLowerCase(),attrs:l,children:d}}return null};if(n.documentElement){const o=i(n.documentElement);o&&r.push(o)}return r.length?r:[{kind:"text",text:zy(t)||t}]}catch{return[{kind:"text",text:zy(t)||t}]}}function By(e){return e.closing?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"runtime_html_punct",children:"</"}),s.jsx("span",{className:"runtime_html_tag",children:e.tag}),s.jsx("span",{className:"runtime_html_punct",children:">"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"runtime_html_punct",children:"<"}),s.jsx("span",{className:"runtime_html_tag",children:e.tag}),e.attrs.map(t=>s.jsxs(Ee.Fragment,{children:[" ",s.jsx("span",{className:"runtime_html_attr",children:t.name}),s.jsx("span",{className:"runtime_html_punct",children:"="}),s.jsxs("span",{className:"runtime_html_value",children:['"',t.value,'"']})]},`${e.tag}:${t.name}:${t.value}`)),s.jsx("span",{className:"runtime_html_punct",children:e.selfClosing?" />":">"})]})}function f1(e){const t=e.node,n=e.depth*14,r=e.depth<e.collapseAfterDepth,[i,o]=p.useState(r);if(p.useEffect(()=>{o(r)},[r,e.expansionVersion]),t.kind==="doctype")return s.jsxs("div",{className:"html-tree__line",style:{paddingLeft:n},children:[s.jsx("span",{className:"runtime_html_punct",children:"<!DOCTYPE "}),s.jsx("span",{className:"runtime_html_tag",children:t.name}),s.jsx("span",{className:"runtime_html_punct",children:">"})]});if(t.kind==="comment")return s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx("span",{className:"runtime_html_comment",children:`<!-- ${t.text.trim()} -->`})});if(t.kind==="text")return s.jsx("div",{className:"html-tree__line html-tree__text",style:{paddingLeft:n},children:t.text});if(!t.children.length)return s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx(By,{tag:t.tag,attrs:t.attrs,selfClosing:!0})});const u=t.children.find(l=>l.kind==="text");return s.jsxs("details",{className:"html-tree__details",open:i,onToggle:l=>o(l.currentTarget.open),children:[s.jsxs("summary",{className:"html-tree__summary",style:{paddingLeft:n},children:[s.jsx("span",{className:"html-tree__caret","aria-hidden":"true",children:i?"▾":"▸"}),s.jsx(By,{tag:t.tag,attrs:t.attrs}),!i&&u?s.jsxs("span",{className:"html-tree__summary_text",children:[" ",V4(u.text)]}):null]}),i?s.jsxs("div",{className:"html-tree__children",children:[t.children.map((l,d)=>s.jsx(f1,{node:l,depth:e.depth+1,collapseAfterDepth:e.collapseAfterDepth,expansionMode:e.expansionMode,expansionVersion:e.expansionVersion},`${e.depth}:${t.kind}:${t.tag}:${d}`)),s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx(By,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function K4(e){const t=p.useMemo(()=>G4(e.text),[e.text]),[n,r]=p.useState({mode:"folded",version:0}),i=n.mode==="unfolded"?H4:q4;p.useEffect(()=>{r(u=>({mode:"folded",version:u.version+1}))},[e.text]);const o=()=>{r(u=>({mode:u.mode==="unfolded"?"folded":"unfolded",version:u.version+1}))};return s.jsxs("div",{className:`${e.className} structured html_source_preview`,children:[s.jsx("div",{className:"html-tree__toolbar",children:s.jsx("button",{type:"button",className:"btn html-tree__toggle",onClick:o,"aria-expanded":n.mode==="unfolded",children:n.mode==="unfolded"?"Fold all":"Unfold all"})}),s.jsx("div",{className:"html-tree__tree",role:"tree","aria-label":"HTML source tree",children:t.map((u,l)=>s.jsx(f1,{node:u,depth:0,collapseAfterDepth:i,expansionMode:n.mode,expansionVersion:n.version},`root:${l}`))})]})}function J4(e){var r;const t=v4(e.text);if(!t)return s.jsx("div",{className:`${e.className} structured markdown_preview`,children:s.jsx(Si,{text:e.text})});const n=((r=t.metadata.find(i=>i.label.toLowerCase()==="title"))==null?void 0:r.value)||"";return s.jsxs("div",{className:`${e.className} structured markdown_preview artifact_markdown_report`,children:[n?s.jsx("h1",{className:"artifact_markdown_title",children:n}):null,t.metadata.length?s.jsx("dl",{className:"artifact_markdown_meta",children:t.metadata.map(i=>{const o=/^https?:\/\//i.test(i.value);return s.jsxs("div",{children:[s.jsx("dt",{children:i.label}),s.jsx("dd",{children:o?s.jsx("a",{href:i.value,target:"_blank",rel:"noreferrer",children:i.value}):i.value})]},`${i.label}:${i.value}`)})}):null,s.jsx(Si,{text:t.body||e.text})]})}function h1(e){const t=String(e.text||""),n=eg(e.artifact,t);if(n==="json"){const r=Tg(t);if(r!==null)return s.jsx("div",{className:`${e.className} structured`,children:s.jsx(fr,{value:r,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?s.jsx(J4,{text:t,className:e.className}):n==="html"?s.jsx(K4,{text:t,className:e.className}):s.jsx("pre",{className:`mono ${e.className}`,children:t})}function Y4(e){const t=e.preview,n=e.artifact;return n?t.loading?s.jsx("div",{className:"runtime_inline_preview empty",children:"Loading preview…"}):t.error?s.jsx("div",{className:"runtime_inline_preview empty danger",children:t.error}):t.kind==="image"&&t.url?s.jsx("img",{className:"runtime_inline_preview media",src:t.url,alt:tg(n)}):t.kind==="audio"&&t.url?s.jsx(Cg,{className:"runtime_inline_preview audio",src:t.url,name:tg(n)}):t.kind==="video"&&t.url?s.jsx("video",{className:"runtime_inline_preview media",src:t.url,controls:!0}):s.jsx(h1,{artifact:n,text:t.text||"Preview unavailable. Use Preview or Download.",className:"runtime_inline_preview text"}):s.jsx("div",{className:"runtime_inline_preview empty",children:"Select an artifact to preview it here."})}function hx(e){const t=e==null?void 0:e.waiting;return t&&typeof t=="object"?t:null}function m1(e){const t=hx(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function I0(e){return e?String(e.prompt||"").trim()||Array.isArray(e.choices)&&e.choices.length>0?!0:e.allow_free_text!==!1&&String(e.reason||"").trim().toLowerCase()==="user":!1}function X4(e){const t=e.map(n=>String((n==null?void 0:n.name)||"tool").trim()).filter(Boolean);return t.length?`${t.slice(0,3).join(", ")}${t.length>3?` +${t.length-3}`:""}`:""}function mx(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(ds(t)||t!=="waiting")return"none";const n=hx(e),r=m1(e);return sf(n).length?"tool_approval":r==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":r==="subworkflow"?"subworkflow":r==="event"?I0(n)?"user_response":"external_event":r==="user"||I0(n)?"user_response":"unknown_wait"}function Z4(e){const t=hx(e),n=sf(t),r=mx(e);return r==="tool_approval"?`Tool approval: ${X4(n)||"tool call"}`:r==="user_response"?Array.isArray(t==null?void 0:t.choices)&&t.choices.length>0?"Choice required":"User response needed":r==="scheduled"?String((e==null?void 0:e.role)||"").trim()==="controller"?"Automation waiting for its next run":"Scheduled wait":r==="subworkflow"?"Waiting for subworkflow":r==="external_event"?"Waiting for external event":r==="unknown_wait"?"Waiting, context unclear":""}function Q4(e){const t=mx(e);if(t==="tool_approval")return"Review the tool request, then approve, reject, or cancel the whole run.";if(t==="user_response")return"Answer the workflow request. Submit resumes only this wait.";if(t==="scheduled")return"No response is needed. The run resumes when the scheduled time arrives or it is manually resumed.";if(t==="subworkflow")return"No direct response is needed. Inspect the child workflow or cancel the parent run.";if(t==="external_event")return"No direct response is available here. Inspect the ledger or the event source.";if(t==="unknown_wait")return"No clear prompt was provided. Review the input and recent ledger before taking action.";const n=String((e==null?void 0:e.status)||"").trim().toLowerCase();return n==="failed"?"Open the ledger, artifacts, or logs to inspect the failure.":n==="running"?"Watch the ledger/provider traces or cancel the workflow if it should stop.":ds(n)?"Open the ledger and artifacts for the final outcome.":"Open the run to inspect current activity."}function O0(e){const t=e==null?void 0:e.error;if(!t)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function eP(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label??"",i=String(e.status||"unknown").trim().toLowerCase()||"unknown",o=mx(e),u=ds(i),l=Cm(e,n),d=Ht(e.updated_at||e.created_at)??0,h=i==="running"&&l>=14400*1e3,m=Z4(e)||O0(e)||(e.current_node?`Current node: ${e.current_node}`:i==="running"?"Running":u?"Terminal":"No current activity reported");let _="all";o==="tool_approval"?_="tool_approval":o==="user_response"?_="user_wait":o==="scheduled"?_="scheduled":o==="subworkflow"||o==="external_event"?_="subflows":i==="failed"?_="failed":i==="running"?_="running":u&&(_="finished");const g=o==="tool_approval"?0:o==="user_response"?1:o==="unknown_wait"?2:i==="failed"?3:h?4:i==="running"?5:o!=="none"?6:u?8:7,y=o==="tool_approval"||o==="user_response",b=o==="tool_approval"?"Open approval":o==="user_response"?"Open wait":"Open Observe",k=[e.run_id,e.workflow_id,r,e.session_id,e.parent_run_id,e.status,e.current_node,m1(e),m,O0(e)].join(" ").toLowerCase();return{run:e,run_id:String(e.run_id||"").trim(),status:i,wait_kind:o,queue:_,attention_rank:g,reason:m,expected_action:Q4(e),action_label:b,search_text:k,is_terminal:u,needs_user_action:y,is_stale:h,duration_ms:l,updated_ms:d}}function tP(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label_by_id??{};return e.map(i=>eP(i,{now_ms:n,workflow_label:r[String(i.workflow_id||"")]||String(i.workflow_id||"")}))}function nP(e){const t={attention:0,user_wait:0,tool_approval:0,running:0,failed:0,scheduled:0,subflows:0,finished:0,all:e.length};for(const n of e)t[n.queue]+=1,n.queue!=="finished"&&(n.needs_user_action||n.status==="failed"||n.is_stale||n.wait_kind==="unknown_wait")&&(t.attention+=1);return t}function sP(e,t){const n=t.queue,i=(t.query??"").trim().toLowerCase();return e.filter(o=>{if(n==="attention"){if(!(o.needs_user_action||o.status==="failed"||o.is_stale||o.wait_kind==="unknown_wait"))return!1}else if(n!=="all"&&o.queue!==n)return!1;return!i||o.search_text.includes(i)})}function rP(e,t){const n=[...e];return n.sort((r,i)=>{if(t==="recent")return i.updated_ms-r.updated_ms;if(t==="oldest")return r.updated_ms-i.updated_ms;if(t==="duration")return i.duration_ms-r.duration_ms;if(t==="tokens")return(Number(i.run.tokens_total||0)||0)-(Number(r.run.tokens_total||0)||0);if(t==="workflow")return String(r.run.workflow_id||"").localeCompare(String(i.run.workflow_id||""));const o=r.attention_rank-i.attention_rank;return o!==0?o:i.updated_ms-r.updated_ms}),n}function iP(e){const[t,n]=p.useState("attention"),[r,i]=Xp("system_queues"),[o,u]=Xp("system_runs"),[l,d]=p.useState(""),[h,m]=p.useState("attention"),[_,g]=p.useState(""),y=p.useMemo(()=>{const L={};for(const V of e.artifacts){const J=String(V.run_id||"").trim();J&&(L[J]=(L[J]||0)+1)}return L},[e.artifacts]),b=p.useMemo(()=>tP(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),k=p.useMemo(()=>nP(b),[b]),x=p.useMemo(()=>{const L=sP(b,{queue:t,query:l});return rP(L,h)},[b,t,l,h]),N=x.find(L=>String(L.run_id||"")===_)||x.find(L=>String(L.run_id||"")===e.selected_run_id)||x[0]||null,$=(N==null?void 0:N.run)||null,E=String(($==null?void 0:$.run_id)||"").trim(),S=String(($==null?void 0:$.session_id)||"").trim(),P=p.useMemo(()=>S?new Set(e.runs.filter(L=>String(L.session_id||"").trim()===S).map(L=>String(L.run_id||"").trim()).filter(Boolean)):new Set,[e.runs,S]),D=S?P.size:0,R=p.useMemo(()=>S?e.artifacts.filter(L=>String(L.session_id||"").trim()===S||P.has(String(L.run_id||"").trim())).length:0,[e.artifacts,S,P]),I=$!=null&&$.waiting&&typeof $.waiting=="object"?$.waiting:null,W=I?sf(I):[],G=(N==null?void 0:N.reason)||(I?dx(I,W):""),K=(N==null?void 0:N.expected_action)||(I?o1(I,W):""),H=I?E4(I,null):"",M=E&&y[E]||0,A=ds($==null?void 0:$.status),O=[{key:"attention",label:"Needs attention",count:k.attention},{key:"user_wait",label:"Needs my response",count:k.user_wait},{key:"tool_approval",label:"Tool approvals",count:k.tool_approval},{key:"running",label:"Running",count:k.running},{key:"failed",label:"Failed",count:k.failed},{key:"scheduled",label:"Scheduled",count:k.scheduled},{key:"subflows",label:"Subflows / external events",count:k.subflows},{key:"finished",label:"Finished",count:k.finished},{key:"all",label:"All loaded",count:k.all}];return s.jsxs("div",{className:`runtime_ops_layout${r?"":" queues_collapsed"}${o?"":" runs_collapsed"}`,children:[s.jsxs("aside",{className:`pane runtime_ops_filters${r?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"pane_header runtime_ops_filter_header",children:[s.jsx(Zp,{open:r,on_toggle:i,controls:"runtime_ops_queues",title:"Queues"}),s.jsx("div",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.gateway_connected?e.on_refresh_runs:e.on_reconnect,children:[s.jsx(qe,{name:"refresh",size:14}),e.gateway_connected?"Refresh":"Reconnect"]})]}),s.jsxs("div",{className:"pane_body scroll runtime_ops_queue_list",id:"runtime_ops_queues",hidden:!r,children:[O.map(L=>s.jsxs("button",{className:`runtime_ops_filter ${t===L.key?"selected":""}`,"aria-pressed":t===L.key,onClick:()=>n(L.key),children:[s.jsx("span",{children:L.label}),s.jsx("strong",{children:L.count.toLocaleString()})]},L.key)),s.jsx("div",{className:"runtime_ops_hint",children:"Counts are for the loaded runtime page. Refine search or refresh when supervising large runtimes."})]})]}),s.jsxs("section",{className:`pane runtime_ops_table_panel${o?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"pane_header runtime_ops_list_header",children:[s.jsx(Zp,{open:o,on_toggle:u,controls:"runtime_ops_runs",title:"Runs",count:x.length.toLocaleString()}),s.jsx("div",{className:"pane_spacer"}),s.jsx("input",{value:l,onChange:L=>d(L.target.value),placeholder:"Search workflow, run, node, status, error"}),s.jsxs("select",{className:"seg_select",value:h,onChange:L=>m(L.target.value),children:[s.jsx("option",{value:"attention",children:"Attention order"}),s.jsx("option",{value:"recent",children:"Latest event"}),s.jsx("option",{value:"oldest",children:"Oldest event"}),s.jsx("option",{value:"duration",children:"Longest duration"}),s.jsx("option",{value:"tokens",children:"Most tokens"}),s.jsx("option",{value:"workflow",children:"Workflow"})]})]}),s.jsxs("div",{className:"pane_body scroll runtime_ops_rows",id:"runtime_ops_runs",hidden:!o,children:[!x.length&&e.loading&&!e.runs.length?s.jsx(rl,{what:"activity"}):null,!x.length&&!(e.loading&&!e.runs.length)?s.jsx("div",{className:"runtime_ops_empty",children:e.gateway_connected?"No runs match this queue.":"Gateway offline. Runtime activity cannot be loaded until the connection is restored."}):null,x.map(L=>{const V=L.run,J=String(V.run_id||"").trim(),U=y[J]||0;return s.jsxs("div",{className:`raised runtime_ops_row ${J===E?"selected":""}`,"aria-current":J===E?"true":void 0,tabIndex:0,onClick:()=>{g(J),e.on_select_run(J)},onKeyDown:te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),g(J),e.on_select_run(J))},children:[s.jsxs("div",{className:"runtime_ops_row_top",children:[s.jsx("strong",{className:"runtime_ops_row_name",children:Vo(V,e.workflow_label_by_id)}),L.is_stale?s.jsx("span",{className:"chip warn",children:"stale"}):null,s.jsx(gu,{status:V.status})]}),s.jsxs("div",{className:"runtime_ops_row_sub",children:[s.jsx("span",{className:"mono",children:Rn(J,18)}),s.jsx("span",{children:lu(V.updated_at||V.created_at)}),s.jsx("span",{children:pu(V)}),s.jsx("span",{className:"runtime_ops_row_reason",title:L.reason,children:L.reason})]}),s.jsxs("div",{className:"runtime_ops_row_foot",children:[s.jsxs("span",{className:"runtime_ops_row_facts",children:[s.jsxs("span",{children:[Number(V.llm_calls||0).toLocaleString()," llm"]}),s.jsxs("span",{children:[Number(V.tool_calls||0).toLocaleString()," tools"]}),s.jsxs("span",{children:[Number(V.tokens_total||0).toLocaleString()," tok"]}),s.jsxs("span",{children:[U.toLocaleString()," artifacts"]})]}),s.jsxs("div",{className:"runtime_ops_actions",children:[L.needs_user_action?s.jsx("button",{className:"btn primary",onClick:te=>{te.stopPropagation(),e.on_open_run(J)},children:L.action_label}):s.jsx("button",{className:"btn",onClick:te=>{te.stopPropagation(),e.on_open_run(J)},children:"Open"}),s.jsx("button",{className:"btn",onClick:te=>{te.stopPropagation(),e.on_open_ledger(J)},children:"Ledger"}),s.jsx("button",{className:"btn",onClick:te=>{te.stopPropagation(),e.on_select_run(J),e.on_open_logs()},children:"Logs"}),s.jsx("button",{className:"btn",onClick:te=>{te.stopPropagation(),e.on_filter_artifacts(J)},children:"Artifacts"})]})]})]},J)})]})]}),s.jsxs("aside",{className:"pane runtime_ops_inspector",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Run inspector"}),$?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pane_spacer"}),s.jsx(gu,{status:$.status})]}):null]}),s.jsx("div",{className:"pane_body scroll runtime_ops_inspector_body",children:$?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_ops_inspector_head",children:[s.jsx("h3",{children:Vo($,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Rn(E,28)})]}),s.jsxs("div",{className:"runtime_ops_decision",children:[s.jsx("strong",{children:(N==null?void 0:N.reason)||M4($)}),s.jsx("span",{children:(N==null?void 0:N.expected_action)||(String($.status||"").toLowerCase()==="waiting"?"This run is paused until the pending wait is resolved or the run is cancelled.":A?"This run is terminal. Open the ledger for the narrative and final error/output.":"This run is active or recently updated. Use ledger/provider logs to inspect live work.")})]}),s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Started"}),s.jsx("strong",{children:Vd(Rd($))})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:pu($)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last event"}),s.jsx("strong",{children:Vd($.updated_at||$.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:$.session_id?Rn(String($.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:$.current_node||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Visible artifacts"}),s.jsx("strong",{children:M.toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:Number($.llm_calls||0).toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Tokens"}),s.jsx("strong",{children:Number($.tokens_total||0).toLocaleString()})]})]}),S?s.jsxs("section",{className:"runtime_ops_session_context",children:[s.jsxs("div",{children:[s.jsx("span",{className:"run_hero_eyebrow",children:"Session context"}),s.jsx("strong",{className:"mono",children:Rn(S,30)})]}),s.jsxs("div",{className:"runtime_ops_session_facts",children:[s.jsxs("span",{children:[D.toLocaleString()," loaded run",D===1?"":"s"]}),s.jsxs("span",{children:[R.toLocaleString()," visible artifact",R===1?"":"s"]})]}),s.jsxs("div",{className:"runtime_detail_actions compact",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_filter_session_artifacts(S),children:"Open session artifacts"}),s.jsx("button",{className:"btn",onClick:()=>void sl(S),children:"Copy session id"})]})]}):null,I?s.jsxs("div",{className:"runtime_ops_wait_summary",children:[s.jsxs("div",{className:"runtime_ops_wait_header",children:[s.jsx("span",{className:"run_hero_eyebrow",children:"Blocked on"}),s.jsx("strong",{children:G})]}),s.jsx("p",{children:K}),H?s.jsxs("div",{className:"runtime_ops_wait_request",children:[s.jsx("span",{children:"Request"}),s.jsx(Si,{text:H})]}):s.jsx("div",{className:"runtime_ops_wait_request muted",children:"No explicit prompt is attached to this wait. Open Observe or the ledger for full run context before responding."}),W.length?s.jsx("div",{className:"runtime_ops_wait_tools",children:W.map((L,V)=>s.jsxs(Ee.Fragment,{children:[s.jsx("span",{className:"chip mono warn",children:String((L==null?void 0:L.name)||"tool")}),i1(L).map(J=>s.jsxs("span",{className:"chip muted",title:r1,children:[J,"~"]},`${V}:${J}`))]},`${String((L==null?void 0:L.name)||"tool")}:${V}`))}):null,s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"muted",children:"Raw wait payload"}),s.jsx(fr,{value:I,collapseAfterDepth:3,showCopy:!0})]})]}):null,nm($)?s.jsx("div",{className:"warn_callout",children:nm($)}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(E),children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(E),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>e.on_filter_artifacts(E),children:"Open artifacts"}),s.jsx("button",{className:"btn",onClick:e.on_open_logs,children:"Open logs"}),s.jsx("button",{className:"btn",onClick:()=>void sl(E),children:"Copy run id"})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run to inspect why it is active or blocked."})})]})]})}function oP(e){const t=e.selected_artifact,n=["voice","music","sound","recording","audio","image","video","markdown","html","json","document","code","text","other"],r=[{value:"all",label:"Any time"},{value:"hour",label:"Last hour"},{value:"today",label:"Today"},{value:"week",label:"7 days"},{value:"month",label:"30 days"}],i=p.useMemo(()=>new Set(e.type_filters),[e.type_filters]),o=Math.max(0,Number(e.artifact_total_count||0)),u=!!e.query.trim()||e.type_filters.length>0||e.date_filter!=="all"||e.scope!=="all"||!!e.artifact_run_filter.trim(),l=Math.max(1,Number(e.artifact_page_size||500)),d=Math.max(1,Math.ceil(o/l)),h=Math.min(Math.max(0,Number(e.artifact_page||0)),d-1),m=o?h*l+1:0,_=Math.min(o,h*l+e.artifacts.length),g=p.useMemo(()=>{const M={},A=e.artifact_type_facets&&Object.keys(e.artifact_type_facets).length?e.artifact_type_facets:e.artifact_facets,O=(A==null?void 0:A.semantic_kind)||{},L=(A==null?void 0:A.render_kind)||{};for(const V of n)M[V]=Number(O[V]||L[V]||0);return M.audio=Number(O.audio||0),M.other=Number(O.other||0)+Number(O.artifact||0)+Number(O.binary||0)+Number(O["(none)"]||0),M},[e.artifact_facets,e.artifact_type_facets]),y=M=>{const A=new Set(i);A.has(M)?A.delete(M):A.add(M),e.on_type_filters_change(Array.from(A.values()))},b=p.useMemo(()=>{const M={waiting:[],running:[],failed:[],cancelled:[],completed:[],other:[]};for(const A of e.runs){const O=String(A.status||"").trim().toLowerCase();O==="waiting"?M.waiting.push(A):O==="running"?M.running.push(A):O==="failed"?M.failed.push(A):O==="cancelled"?M.cancelled.push(A):O==="completed"?M.completed.push(A):M.other.push(A)}return M},[e.runs]),k=t!=null&&t.run_id&&e.run_by_id[t.run_id]||null,x=e.artifact_run_filter?Vo(e.run_by_id[e.artifact_run_filter],e.workflow_label_by_id):"",N=p.useMemo(()=>{var O;const M=new Set,A=((O=e.artifact_facets)==null?void 0:O.run_id)||{};for(const L of Object.keys(A))L&&L!=="(none)"&&M.add(L);for(const L of e.artifacts)L.run_id&&M.add(L.run_id);for(const L of e.active_runs)L.run_id&&M.add(String(L.run_id));return Array.from(M).map(L=>e.run_by_id[L]||{run_id:L,workflow_id:null,status:"",created_at:null,updated_at:null}).sort((L,V)=>{const J=Gd(L.status)?0:1,U=Gd(V.status)?0:1;if(J!==U)return J-U;const te=Ht(L.updated_at||L.created_at)??0;return(Ht(V.updated_at||V.created_at)??0)-te}).slice(0,160)},[e.artifacts,e.active_runs,e.run_by_id,e.artifact_facets]),$=M=>{e.on_artifact_run_filter_change(M),e.on_session_filter_change(""),e.on_scope_change(M?"run":"all")},E=M=>e.gateway_connected?Math.max(0,Number(M||0)).toLocaleString():"—",S=e.selected_run_id&&e.run_by_id[e.selected_run_id]||null,P=p.useMemo(()=>{const M=e.runtime_log_query.trim().toLowerCase(),A=e.runtime_ledger_log_items||[];return M?A.filter(O=>{var J,U;const L=O.record||{};return[O.cursor,L.run_id,L.node_id,L.status,(J=L.effect)==null?void 0:J.type,L.started_at,L.ended_at,Fr(((U=L.effect)==null?void 0:U.payload)??{},900),Fr(L.result??{},900)].join(" ").toLowerCase().includes(M)}):A},[e.runtime_ledger_log_items,e.runtime_log_query]),D=p.useMemo(()=>{const M=e.runtime_log_query.trim().toLowerCase(),A=W4(e.runtime_ledger_log_items);return M?A.filter(O=>[O.provider,O.model,O.run_id,O.node_id,O.status,O.error,O.prompt_preview,O.response_preview,O.tokens.prompt,O.tokens.completion,O.tokens.total].join(" ").toLowerCase().includes(M)):A},[e.runtime_ledger_log_items,e.runtime_log_query]),R=D.reduce((M,A)=>M+(Number(A.tokens.total)||0),0),I=D.filter(M=>M.missing_response||M.error).length,W=p.useMemo(()=>{const M=e.runtime_log_query.trim().toLowerCase(),A=String(e.audit_log_text||"").replace(/\r\n/g,`
128
+ `).replace(/\r/g,`
129
+ `).split(`
130
+ `).filter(Boolean);return M?A.filter(O=>O.toLowerCase().includes(M)):A},[e.audit_log_text,e.runtime_log_query]),G=e.runtime_log_source==="run_ledger"||e.runtime_log_source==="provider_calls",K=e.runtime_log_source==="run_ledger"?"Selected Run Ledger":e.runtime_log_source==="provider_calls"?"Provider Calls":"Gateway HTTP Audit",H=e.runtime_log_source==="run_ledger"?"Runtime execution records for the selected workflow run.":e.runtime_log_source==="provider_calls"?"Model/provider call records extracted from the selected run ledger.":"Global Gateway HTTP/audit tail. This is system activity, not artifact provenance.";return s.jsxs("div",{className:"page runtime_page",children:[s.jsxs("section",{className:"runtime_header",children:[s.jsxs("div",{children:[s.jsx("div",{className:"run_hero_eyebrow",children:"System"}),s.jsx("h2",{children:e.tab==="activity"?"Activity monitor":e.tab==="artifacts"?"Artifact explorer":e.tab==="memory"?"Active memory":"Logs"}),s.jsxs("div",{className:"run_hero_meta",children:[s.jsx("span",{className:`status_pill ${e.gateway_connected?"ok":"warn"}`,children:e.gateway_connected?"gateway connected":"gateway offline"}),e.tab==="artifacts"&&e.artifact_run_filter?s.jsxs("span",{className:"chip muted",children:["filtered run ",s.jsx("span",{className:"mono",children:Rn(e.artifact_run_filter,18)})]}):null,e.session_id?s.jsxs("span",{className:"chip muted",children:["session ",s.jsx("span",{className:"mono",children:Rn(e.session_id,18)})]}):null]})]}),s.jsxs("div",{className:"metric_grid compact runtime_header_metrics",children:[s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Waiting"}),s.jsx("strong",{children:E(b.waiting.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Running"}),s.jsx("strong",{children:E(b.running.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Failed"}),s.jsx("strong",{children:E(b.failed.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsxs("span",{children:["Artifacts",u?" (filtered)":""]}),s.jsx("strong",{children:E(o)})]})]})]}),s.jsx("nav",{className:"runtime_mode_tabs",role:"tablist","aria-label":"System sections",children:["activity","artifacts","memory","logs"].map(M=>s.jsxs("button",{role:"tab","aria-selected":e.tab===M,className:`runtime_mode_tab ${e.tab===M?"active":""}`,onClick:()=>e.on_tab_change(M),children:[s.jsx(qe,{name:M==="activity"?"history":M==="artifacts"?"download":M==="memory"?"agent":"terminal",size:14}),s.jsx("span",{children:M==="activity"?"Activity":M==="artifacts"?"Artifacts":M==="memory"?"Memory":"Logs"})]},M))}),e.gateway_connected?null:s.jsxs("div",{className:"runtime_offline_banner",role:"status",children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Gateway offline"}),s.jsx("span",{children:"Activity, artifacts, memory, and logs are unavailable until the gateway reconnects."})]}),s.jsxs("div",{children:[s.jsx("button",{className:"btn primary",onClick:e.on_reconnect,children:"Reconnect"}),s.jsx("button",{className:"btn",onClick:e.on_open_settings,children:"Settings"})]})]}),e.error?s.jsx("div",{className:"warn_callout",children:e.error}):null,e.tab==="activity"?s.jsx(iP,{gateway_connected:e.gateway_connected,loading:e.runs_loading,runs:e.runs,artifacts:e.artifacts,selected_run_id:e.selected_run_id,workflow_label_by_id:e.workflow_label_by_id,on_select_run:e.on_select_run,on_open_run:e.on_open_run,on_open_ledger:e.on_open_ledger,on_refresh_runs:e.on_refresh_runs,on_reconnect:e.on_reconnect,on_open_logs:()=>e.on_tab_change("logs"),on_filter_artifacts:M=>{$(M),e.on_select_run(M),e.on_tab_change("artifacts")},on_filter_session_artifacts:M=>{M&&(e.on_artifact_run_filter_change(""),e.on_session_filter_change(M),e.on_scope_change("session"),e.on_tab_change("artifacts"))}}):null,e.tab==="memory"?e.memory_panel?s.jsx("div",{className:"runtime_memory_panel",children:e.memory_panel}):s.jsx("div",{className:"empty_state_inline",children:"The memory explorer needs a gateway connection — sign in to browse knowledge-graph assertions."}):null,e.tab==="artifacts"?s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"pane runtime_artifact_toolbar","aria-label":"Find artifacts",children:[s.jsxs("div",{className:"runtime_artifact_toolbar_top",children:[s.jsxs("label",{className:"artifact_filter_field artifact_filter_search",children:[s.jsx("span",{children:"Search"}),s.jsx("input",{value:e.query,onChange:M=>e.on_query_change(M.target.value),placeholder:"title, path, hash, run, workflow, tag"})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Scope"}),s.jsxs("select",{className:"seg_select",value:e.scope,onChange:M=>{const A=M.target.value;A!=="run"&&e.on_artifact_run_filter_change(""),A==="session"?e.on_session_filter_change(e.session_id):e.on_session_filter_change(""),e.on_scope_change(A)},children:[s.jsx("option",{value:"all",children:"All runtime"}),s.jsx("option",{value:"session",children:"This session"}),s.jsx("option",{value:"run",children:"Selected run"})]})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Group"}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:M=>e.on_group_by_change(M.target.value),children:[s.jsx("option",{value:"type",children:"Type"}),s.jsx("option",{value:"time",children:"Date"}),s.jsx("option",{value:"turn",children:"Turn"}),s.jsx("option",{value:"node",children:"Node"}),s.jsx("option",{value:"workflow",children:"Workflow"}),s.jsx("option",{value:"run",children:"Run"}),s.jsx("option",{value:"location",children:"Location"}),s.jsx("option",{value:"source",children:"Source"})]})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Sort"}),s.jsxs("select",{className:"seg_select",value:e.sort_by,onChange:M=>e.on_sort_by_change(M.target.value),children:[s.jsx("option",{value:"newest",children:"Newest"}),s.jsx("option",{value:"oldest",children:"Oldest"}),s.jsx("option",{value:"last_access",children:"Last accessed"}),s.jsx("option",{value:"turn",children:"Turn order"}),s.jsx("option",{value:"type",children:"Type"}),s.jsx("option",{value:"size_desc",children:"Largest"}),s.jsx("option",{value:"size_asc",children:"Smallest"})]})]}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh_artifacts,disabled:!e.gateway_connected||e.loading,children:[s.jsx(qe,{name:"refresh",size:14}),e.loading?"Loading…":"Refresh"]})]}),s.jsxs("div",{className:"artifact_filter_section",children:[s.jsxs("div",{className:"artifact_filter_label",children:["Type ",s.jsx("span",{className:"muted",children:"OR"})]}),s.jsxs("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact type filters combine with OR",children:[n.map(M=>{const A=i.has(M),O=g[M]||0,L=O4(M);return s.jsxs("button",{type:"button","aria-pressed":A,"aria-label":`${L} artifact type filter. Type filters combine with OR.`,title:`${L}: ${A?"in the filter":"not in the filter"}. Type filters combine with OR.`,className:`artifact_filter_chip ${A?"active":""}`,onClick:()=>y(M),children:[s.jsx("span",{children:L}),s.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?O.toLocaleString():"—"})]},M)}),e.type_filters.length?s.jsx("button",{type:"button",className:"artifact_filter_chip clear",onClick:()=>e.on_type_filters_change([]),children:"Clear types"}):null]})]}),s.jsxs("div",{className:"artifact_filter_section",children:[s.jsx("div",{className:"artifact_filter_label",children:"Date"}),s.jsx("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact date filters",children:r.map(M=>s.jsx("button",{type:"button","aria-pressed":e.date_filter===M.value,className:`artifact_filter_chip ${e.date_filter===M.value?"active":""}`,onClick:()=>e.on_date_filter_change(M.value),children:M.label},M.value))})]})]}),s.jsx("div",{className:"artifact_scope_banner",children:e.artifact_run_filter?s.jsxs(s.Fragment,{children:["Showing artifacts for ",s.jsx("strong",{children:x||Rn(e.artifact_run_filter,18)}),".",s.jsx("button",{className:"btn",onClick:()=>$(""),children:"Show all"})]}):s.jsxs(s.Fragment,{children:["Showing artifacts across the selected runtime scope. Select a run to filter the inventory. ",e.artifact_total_bytes?s.jsxs("span",{className:"mono muted",children:["Total size ",su(e.artifact_total_bytes)]}):null]})}),s.jsxs("div",{className:"runtime_artifacts_layout",children:[s.jsxs("aside",{className:"pane artifact_filter_rail",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Runs"}),s.jsx("span",{className:"pane_count",children:N.length.toLocaleString()})]}),s.jsxs("div",{className:"pane_body scroll artifact_filter_rail_list",children:[s.jsxs("button",{className:`artifact_filter_run ${e.artifact_run_filter?"":"selected"}`,onClick:()=>$(""),children:[s.jsx("strong",{children:"All artifacts"}),s.jsx("span",{children:e.gateway_connected?`${o.toLocaleString()} match${o===1?"":"es"}`:"counts unavailable"})]}),N.map(M=>{const A=String(M.run_id||"").trim(),O=A===e.artifact_run_filter||A===(t==null?void 0:t.run_id);return s.jsxs("button",{className:`artifact_filter_run ${O?"selected":""}`,onClick:()=>$(A),title:A,children:[s.jsx("strong",{children:Vo(M,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Rn(A,15)}),s.jsx("span",{children:pu(M)})]},A)})]})]}),s.jsxs("section",{className:"pane runtime_artifact_browser",children:[s.jsxs("div",{className:"pane_header artifact_browser_header",children:[s.jsx("span",{className:"pane_title",children:"Artifacts"}),s.jsx("span",{className:"pane_count",children:o?`${m.toLocaleString()}-${_.toLocaleString()} of ${o.toLocaleString()}`:"0 items"}),s.jsx("div",{className:"pane_spacer"}),d>1?s.jsxs("div",{className:"artifact_pagination","aria-label":"Artifact pages",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(0),disabled:h<=0,children:"First"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(h-1),disabled:h<=0,children:"Prev"}),s.jsxs("span",{className:"muted artifact_page_label",children:["Page ",(h+1).toLocaleString()," / ",d.toLocaleString()]}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(h+1),disabled:h>=d-1,children:"Next"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(d-1),disabled:h>=d-1,children:"Last"})]}):null]}),s.jsxs("div",{className:"pane_body scroll artifact_browser_body",children:[!e.artifact_groups.length&&e.loading?s.jsx(rl,{what:"artifacts",size:"block"}):null,!e.artifact_groups.length&&!e.loading?s.jsx("div",{className:"empty_state_inline",children:e.gateway_connected?"No artifacts match the current filters.":"Gateway offline. Artifact inventory cannot be loaded until the connection is restored."}):null,s.jsx("div",{className:"artifact_group_list",children:e.artifact_groups.map(M=>s.jsxs("section",{className:"artifact_group",children:[s.jsxs("div",{className:"artifact_group_header",children:[s.jsx("span",{children:M.key}),s.jsx("span",{className:"artifact_group_count",children:M.items.length})]}),M.items.map(A=>{var U;const O=A.run_id&&e.run_by_id[A.run_id]||null,L=O?Vo(O,e.workflow_label_by_id):fx(A),V=M0(A),J=Number(((U=A.access)==null?void 0:U.access_count)||0)||0;return s.jsxs("button",{className:`artifact_row ${(t==null?void 0:t.artifact_id)===A.artifact_id?"selected":""}`,onClick:()=>{e.on_select_artifact(A.artifact_id),A.run_id&&e.on_select_run(A.run_id)},title:A.artifact_id,children:[s.jsx(L0,{artifact:A,size:18}),s.jsxs("div",{className:"artifact_row_main",children:[s.jsxs("div",{className:"artifact_row_title",children:[s.jsx("strong",{children:T0(ng(A,e.run_by_id,e.workflow_label_by_id))}),s.jsx("span",{className:"artifact_type_badge",children:Bd(A)}),A.render_kind&&A.render_kind!==A.semantic_kind?s.jsx("span",{className:"artifact_type_badge muted",children:A.render_kind}):null,A.legacy_inferred?s.jsx("span",{className:"artifact_type_badge inferred",children:"legacy inferred"}):null]}),s.jsxs("div",{className:"artifact_row_facts",children:[s.jsxs("span",{children:[s.jsx("b",{children:"Created"})," ",F4(A)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Size"})," ",su(A.size_bytes)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Last seen"})," ",A0(A)]}),J?s.jsxs("span",{children:[s.jsx("b",{children:"Accesses"})," ",J.toLocaleString()]}):null,V?s.jsxs("span",{children:[s.jsx("b",{children:"Media"})," ",V]}):null,A.content_type?s.jsxs("span",{children:[s.jsx("b",{children:"MIME"})," ",A.content_type]}):null]}),s.jsxs("div",{className:"artifact_row_facts secondary",children:[L?s.jsxs("span",{children:[s.jsx("b",{children:"Workflow"})," ",L]}):null,A.run_id?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Run"})," ",Rn(A.run_id,13)]}):null,s.jsxs("span",{children:[s.jsx("b",{children:"Turn"})," ",ev(A)]}),zd(A)?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Node"})," ",zd(A)]}):null,sm(A)?s.jsxs("span",{children:[s.jsx("b",{children:"Source"})," ",sm(A)]}):null]}),s.jsxs("div",{className:"artifact_row_facts tertiary",children:[s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"ID"})," ",Rn(A.artifact_id,22)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Provenance"})," ",C0(A)]})]}),R0(A)?s.jsx("div",{className:"artifact_row_path mono",children:R0(A)}):null]})]},A.artifact_id)})]},M.key))})]})]}),s.jsx("aside",{className:"runtime_detail",children:s.jsxs("section",{className:"overview_panel runtime_artifact_detail",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Artifact Detail"}),t?s.jsx("span",{className:"chip mono muted",children:e.embedded_preview.render_kind?tv(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):tv(t,e.run_by_id,e.workflow_label_by_id)}):null]}),t?s.jsxs(s.Fragment,{children:[(()=>{var U,te,z,ne,se,de,be;const M=z4(t),A=c1(t),O=M0(t),L=Number(((U=t.access)==null?void 0:U.access_count)||0)||0,V=qn((te=t.links)==null?void 0:te.provider_trace,(z=t.links)==null?void 0:z.provider_trace_url,(ne=t.links)==null?void 0:ne.provider_trace_id),J=qn((se=t.links)==null?void 0:se.audit,(de=t.links)==null?void 0:de.audit_tail,(be=t.links)==null?void 0:be.audit_url);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"artifact_detail_header",children:[s.jsx(L0,{artifact:t,size:22}),s.jsxs("div",{children:[s.jsx("div",{className:"artifact_detail_title",children:T0(ng(t,e.run_by_id,e.workflow_label_by_id))}),s.jsxs("div",{className:"artifact_detail_subtitle",children:[Bd(t)," • ",t.render_kind||e.embedded_preview.render_kind||t.modality||"artifact"," • ",t.content_type||"unknown MIME"," • ",su(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),s.jsx(Y4,{artifact:t,preview:e.embedded_preview}),s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Semantic type"}),s.jsx("strong",{children:Bd(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Render kind"}),s.jsx("strong",{children:t.render_kind||e.embedded_preview.render_kind||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Created"}),s.jsx("strong",{children:Vd(t.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Size"}),s.jsx("strong",{children:su(t.size_bytes)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last seen"}),s.jsx("strong",{children:A0(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Accesses"}),s.jsx("strong",{children:L?L.toLocaleString():"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:t.run_id?Rn(t.run_id,24):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:k?Vo(k,e.workflow_label_by_id):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Turn"}),s.jsx("strong",{children:ev(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:zd(t)||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider/model"}),s.jsx("strong",{children:A||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Media facts"}),s.jsx("strong",{children:O||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Trace"}),s.jsx("strong",{children:t.provider_trace_available?"available":"not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provenance"}),s.jsx("strong",{children:C0(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Artifact id"}),s.jsx("strong",{className:"mono",children:Rn(t.artifact_id,30)})]}),t.sha256?s.jsxs("div",{children:[s.jsx("span",{children:"sha256"}),s.jsx("strong",{className:"mono",children:Rn(t.sha256,30)})]}):null]}),M?s.jsxs("div",{className:"artifact_provenance_panel",children:[s.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),s.jsx("div",{className:"artifact_prompt_text",children:M})]}):s.jsxs("div",{className:"artifact_provenance_panel muted",children:[s.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),s.jsx("div",{className:"artifact_prompt_text",children:"Generation prompt not recorded by the runtime artifact descriptor."})]}),Object.keys(t.generation||{}).length||Object.keys(t.producer||{}).length?s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Generation and producer metadata"}),s.jsx(fr,{value:{generation:t.generation,producer:t.producer,source_refs:t.source_refs},collapseAfterDepth:3,showCopy:!0})]}):null,t.source_path?s.jsx("div",{className:"artifact_detail_path mono",children:t.source_path}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_preview_artifact(t),disabled:!t.run_id,children:e.embedded_preview.render_kind==="html"?"Open as web page":"Open full preview"}),s.jsx("button",{className:"btn",onClick:()=>e.on_download_artifact(t),disabled:!t.run_id,children:"Download"}),s.jsx("button",{className:"btn",onClick:()=>$(t.run_id),disabled:!t.run_id,children:"Show run artifacts"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(t.run_id),disabled:!t.run_id,children:"Open in Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(t.run_id),disabled:!t.run_id,children:"Open run ledger"}),s.jsx("button",{className:"btn",onClick:()=>{V&&window.open(V,"_blank","noopener,noreferrer")},disabled:!V,children:"Open provider trace"}),s.jsx("button",{className:"btn",onClick:()=>{J?window.open(J,"_blank","noopener,noreferrer"):e.on_tab_change("logs")},disabled:!J&&!t.audit_available,children:"Open audit trail"}),s.jsx("button",{className:"btn",onClick:()=>void sl(t.artifact_id),disabled:!t.artifact_id,children:"Copy artifact id"})]})]})})(),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw metadata"}),s.jsx(fr,{value:t.raw,collapseAfterDepth:3,showCopy:!0})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select an artifact to inspect metadata, preview, or download content."})]})})]})]}):null,e.tab==="logs"?s.jsxs("section",{className:"overview_panel runtime_logs_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:K}),s.jsx("div",{className:"mono muted",children:H})]}),s.jsxs("div",{className:"actions",style:{marginTop:0},children:[G&&e.runtime_ledger_log_meta?s.jsx("span",{className:"mono muted",children:e.runtime_ledger_log_meta}):null,e.runtime_log_source==="gateway_audit"&&e.audit_log_meta?s.jsx("span",{className:"mono muted",children:e.audit_log_meta}):null,s.jsxs("button",{className:"btn btn_icon",onClick:()=>{G?e.on_refresh_runtime_ledger(e.selected_run_id):e.on_refresh_audit()},disabled:G?e.runtime_ledger_log_loading:e.audit_log_loading,children:[s.jsx(qe,{name:"refresh",size:14}),G?e.runtime_ledger_log_loading?"Loading…":"Refresh":e.audit_log_loading?"Loading…":"Refresh"]})]})]}),s.jsxs("div",{className:"runtime_log_toolbar",children:[s.jsxs("div",{className:"seg_toggle mono",children:[s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="run_ledger"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("run_ledger"),children:"Run ledger"}),s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="provider_calls"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("provider_calls"),children:"Provider calls"}),s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="gateway_audit"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("gateway_audit"),children:"Gateway audit"})]}),s.jsx("input",{className:"mono",value:e.runtime_log_query,onChange:M=>e.on_runtime_log_query_change(M.target.value),placeholder:"Search node, status, effect, payload, error"})]}),e.runtime_log_source==="run_ledger"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_log_context",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Selected run"}),s.jsx("strong",{children:S?Vo(S,e.workflow_label_by_id):e.selected_run_id?Rn(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Rn(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:S!=null&&S.session_id?Rn(String(S.session_id),28):e.session_id?Rn(e.session_id,28):"—"})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>$(e.selected_run_id),disabled:!e.selected_run_id,children:"Run artifacts"})]})]}),e.runtime_ledger_log_error?s.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:s.jsx("div",{className:"empty_state_inline",children:"Select a run in Activity or Artifact Explorer to inspect its runtime ledger."}),e.selected_run_id&&!P.length&&e.runtime_ledger_log_loading?s.jsx(rl,{what:"ledger"}):null,e.selected_run_id&&!P.length&&!e.runtime_ledger_log_loading?s.jsx("div",{className:"empty_state_inline",children:"No ledger records match the current search."}):null,s.jsx("div",{className:"runtime_log_event_list","aria-label":"Selected run ledger records",children:P.map(M=>{var se,de;const A=M.record||{},O=String(((se=A==null?void 0:A.effect)==null?void 0:se.type)||"").trim(),L=String((A==null?void 0:A.status)||"").trim(),V=String((A==null?void 0:A.node_id)||"").trim(),J=qn(A==null?void 0:A.ended_at,A==null?void 0:A.started_at,A==null?void 0:A.ts),U=Ya(A),te=u1(A),z=O?en(Fr(((de=A==null?void 0:A.effect)==null?void 0:de.payload)??{},1200),{max_chars:1200,max_lines:6}):"",ne=d1(A)||(U?`Waiting for ${String(U.reason||"input")}`:"")||((A==null?void 0:A.result)!==void 0?Fr(A.result,700):"");return s.jsxs("article",{className:`runtime_log_event ${ka(L)}`,children:[s.jsxs("div",{className:"runtime_log_event_header",children:[s.jsxs("span",{className:"mono",children:["#",M.cursor]}),s.jsx(gu,{status:L||"record"}),O?s.jsx("span",{className:"chip mono muted",children:O}):null,V?s.jsx("strong",{className:"mono",children:V}):null,J?s.jsx("span",{className:"mono muted",children:Vd(J)}):null]}),s.jsxs("div",{className:"runtime_log_event_body",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Request / activity"}),s.jsx("p",{children:[te||Ap(A),z&&z!=="{}"?z:""].filter(Boolean).join(`
131
+ `)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:en(ne||"—",{max_chars:1200,max_lines:6})})]})]}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw ledger record"}),s.jsx(fr,{value:A,collapseAfterDepth:3,showCopy:!0})]})]},`${e.selected_run_id}:${M.cursor}`)})})]}):e.runtime_log_source==="provider_calls"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_log_context",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Selected run"}),s.jsx("strong",{children:S?Vo(S,e.workflow_label_by_id):e.selected_run_id?Rn(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Rn(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:D.length.toLocaleString()}),s.jsx("em",{className:"mono",children:R?`${R.toLocaleString()} tokens`:"tokens not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Issues"}),s.jsx("strong",{children:I.toLocaleString()})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_runtime_log_source_change("run_ledger"),disabled:!e.selected_run_id,children:"Run ledger"})]})]}),e.runtime_ledger_log_error?s.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:s.jsx("div",{className:"empty_state_inline",children:"Select a run in Activity or Artifact Explorer to inspect provider calls."}),e.selected_run_id&&!D.length&&!e.runtime_ledger_log_loading?s.jsx("div",{className:"empty_state_inline",children:"No provider calls are present in the selected run ledger, or none match the current search."}):null,s.jsx("div",{className:"provider_activity_list runtime_provider_log_list",children:D.map(M=>s.jsxs("article",{className:`provider_activity ${M.error||M.missing_response?"danger":""}`,children:[s.jsxs("div",{className:"provider_activity_header",children:[s.jsxs("div",{children:[s.jsx("h4",{children:[M.provider||"provider unknown",M.model||"model unknown"].join(" / ")}),s.jsxs("div",{className:"timeline_subtitle",children:[M.node_id?s.jsx("span",{className:"mono",children:M.node_id}):null,M.run_id?s.jsx("span",{className:"mono",children:Rn(M.run_id,16)}):null,s.jsx("span",{children:vu(M.duration_ms)}),M.status?s.jsx(gu,{status:M.status}):null]})]}),s.jsxs("div",{className:"provider_tokens mono",children:[M.tokens.total?M.tokens.total.toLocaleString():"—"," tokens"]})]}),s.jsxs("div",{className:"provider_preview_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Prompt / messages"}),s.jsx("p",{children:M.prompt_preview||"No prompt payload captured"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Response / error"}),s.jsx("p",{children:M.response_preview||M.error||"No response captured"})]})]}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw provider ledger record"}),s.jsx(fr,{value:M.raw,collapseAfterDepth:3,showCopy:!0})]})]},M.id))})]}):s.jsxs(s.Fragment,{children:[e.audit_log_error?s.jsx("div",{className:"warn_callout",children:e.audit_log_error}):null,s.jsx("pre",{className:"mono audit_log_tail",children:W.length?W.join(`
132
+ `):"(audit tail not loaded or no lines match search)"})]})]}):null]})}function aP(e){const[t,n]=p.useState(""),r=Array.isArray(e.wait.choices)?e.wait.choices:[],i=e.wait.allow_free_text!==!1,o=e.disabled===!0,u=String(e.wait.prompt||"").trim();return s.jsxs(s.Fragment,{children:[r.length?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Expected response"}),s.jsxs("select",{className:"mono",value:t,onChange:l=>n(l.target.value),children:[s.jsx("option",{value:"",children:"(select)"}),r.map((l,d)=>s.jsx("option",{value:String(l),children:String(l)},d))]})]}):null,i?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:r.length?"Or type a response":u?"Your answer":"Response to resume this wait"}),s.jsx("textarea",{className:"mono wait_response_input",value:t,onChange:l=>n(l.target.value),placeholder:u?"Type your answer to the request above…":"Type the response the workflow is waiting for…",rows:4})]}):null,s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn primary",disabled:o||!t.trim(),onClick:()=>e.on_submit(t.trim()),children:"Submit response"})})]})}function P0(e,t,n){if(Rg(e)==="automation"){const r=String(e.automation_id||e.run_id||"").trim();return n[r]||"Automation"}return Vo(e,t)}function D0(e){const t=Rg(e.run);return t?s.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:DN(e.run)}):null}function lP(e){const t=e.selected_run_id.trim(),n=e.list?e.list.open:!0,r=e.root_run_id.trim()||t,i=e.sections.reduce((o,u)=>o+u.rows.reduce((l,d)=>{const h=[d.run,...d.children];return l+h.filter(m=>Gd(m.status)).length},0),0);return s.jsxs("aside",{className:`observatory_sidebar pane${n?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"run_nav_header pane_header",children:[e.list?s.jsx(Zp,{open:n,on_toggle:e.list.on_toggle,controls:"run_nav_controls run_nav_tree",title:"Runs",count:`${e.total_runs.toLocaleString()} runs • ${i.toLocaleString()} active`}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_title",children:"Runs"}),s.jsxs("span",{className:"pane_count",children:[e.total_runs.toLocaleString()," runs • ",i.toLocaleString()," active"]})]}),s.jsx("span",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh,disabled:e.loading,title:"Refresh workflow runs",children:[s.jsx(qe,{name:"refresh",size:14}),e.loading?"…":""]})]}),s.jsxs("div",{className:"run_nav_controls",id:"run_nav_controls",hidden:!n,children:[s.jsx("input",{value:e.search,onChange:o=>e.on_search(o.target.value),placeholder:"Search runs, sessions, workflows"}),s.jsxs("div",{className:"run_nav_filter_row",children:[s.jsx("div",{className:"seg_toggle run_nav_segments",children:["active","waiting","terminal","failed","all"].map(o=>s.jsx("button",{className:`seg_btn ${e.filter===o?"active":""}`,onClick:()=>e.on_filter(o),children:o},o))}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:o=>e.on_group_by(o.target.value),title:"Group workflow runs",children:[s.jsx("option",{value:"status",children:"Group by status"}),s.jsx("option",{value:"workflow",children:"Group by workflow"}),s.jsx("option",{value:"session",children:"Group by session"})]})]})]}),s.jsxs("div",{className:"run_tree",id:"run_nav_tree",hidden:!n,children:[e.sections.length?null:e.connected&&e.loading?s.jsx(rl,{what:"runs"}):e.connected?s.jsx("div",{className:"run_tree_empty",children:"No runs match the current filters."}):s.jsxs("div",{className:"run_tree_empty",children:["Gateway offline — runs are unavailable."," ",s.jsx("button",{className:"btn btn_sm",onClick:e.on_sign_in,children:"Sign in"})]}),e.sections.map(o=>s.jsxs("section",{className:"run_tree_section",children:[s.jsxs("div",{className:"run_tree_section_header",children:[s.jsx("span",{children:o.label}),s.jsx("span",{className:"mono",children:o.rows.length})]}),o.rows.map(u=>{const l=u.run,d=String(l.run_id||"").trim(),h=d===t;return s.jsxs("div",{className:"run_tree_group",children:[s.jsxs("button",{className:`run_tree_item ${h?"selected":""} ${d===r?"root_context":""}`,onClick:()=>e.on_select(d,d),title:d,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:P0(l,e.workflow_label_by_id,e.automation_titles)}),s.jsx(D0,{run:l}),l.status?s.jsx(gu,{status:tm(l)}):null]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Rn(d,13)}),s.jsx("span",{children:Rd(l)?lu(Rd(l)):"no start"}),s.jsx("span",{children:pu(l)})]})]}),u.children.length?s.jsx("div",{className:"run_tree_children",children:u.children.map(m=>{const _=String(m.run_id||"").trim();return s.jsxs("button",{className:`run_tree_item run_tree_child ${_===t?"selected":""}`,onClick:()=>e.on_select(_,d),title:_,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:P0(m,e.workflow_label_by_id,e.automation_titles)}),s.jsx(D0,{run:m}),s.jsx(gu,{status:tm(m)})]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Rn(_,13)}),s.jsx("span",{children:Rd(m)?lu(Rd(m)):"child"}),s.jsx("span",{children:pu(m)})]})]},_)})}):null]},d)})]},o.key))]})]})}class cP{constructor(){kn(this,"_buffer","");kn(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const r=this._buffer.indexOf(`
133
+ `);if(r===-1)return;const i=this._buffer.slice(0,r);this._buffer=this._buffer.slice(r+1);const o=i.endsWith("\r")?i.slice(0,-1):i;if(o.startsWith(":"))continue;if(o===""){if(this._current.data_lines.length>0||this._current.event||this._current.id){const h={id:this._current.id,event:this._current.event,data:this._current.data_lines.join(`
134
+ `)};n(h)}this._current={data_lines:[]};continue}const u=o.indexOf(":"),l=u===-1?o:o.slice(0,u),d=u===-1?"":o.slice(u+1).trimStart();if(l==="id"){this._current.id=d;continue}if(l==="event"){this._current.event=d;continue}if(l==="data"){this._current.data_lines.push(d);continue}}}}const Yt=Uv;function Ys(e,t=3e4){const n=AbortSignal.timeout(t),r=AbortSignal.any,i=e?typeof r=="function"?r([e,n]):e:n;return _1.set(i,t),i}const _1=new WeakMap;class uP extends Error{constructor(n){super(n);kn(this,"name","GatewayTimeout")}}class dP extends Error{constructor(n){super(n);kn(this,"name","Superseded")}}async function an(e,t){try{return await globalThis.fetch(e,t)}catch(n){throw p1(n,e,t)}}async function Uy(e,t,n){try{return await e.json()}catch(r){throw p1(r,t,n)}}function p1(e,t,n){{const r=String((e==null?void 0:e.name)||"");if(r!=="AbortError"&&r!=="TimeoutError")return e;const i=n==null?void 0:n.signal,o=i==null?void 0:i.reason,u=r==="TimeoutError"||String((o==null?void 0:o.name)||"")==="TimeoutError";let l=String(t);try{const d=new URL(t,typeof location<"u"?location.href:"http://localhost/");l=`${String((n==null?void 0:n.method)||"GET").toUpperCase()} ${d.pathname}${d.search?"?"+d.searchParams.toString().slice(0,60):""}`}catch{}if(u){const d=i&&_1.get(i)||3e4;return new uP(`${l}: no answer within ${Math.round(d/1e3)} s — the gateway is busy`)}return new dP(`${l}: superseded`)}}function nv(){var t;const e={};try{const n=(t=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("abstractobserver_gateway_csrf=")))==null?void 0:t.slice(30);n&&(e["X-AbstractObserver-CSRF"]=decodeURIComponent(n))}catch{}return e}function Xt(e){const t=(e||"").trim(),n={};return t&&(n.Authorization=`Bearer ${t}`),{...n,...nv()}}async function vs(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class sv extends Error{constructor(n,r){super(r);kn(this,"status");this.name="GatewayRequestError",this.status=n}}async function Xc(e,t){let n="";try{n=(await e.text()).trim()}catch{n=""}let r=n;try{const i=JSON.parse(n),o=i&&typeof i=="object"?i.detail:void 0;typeof o=="string"&&o.trim()?r=o.trim():o&&typeof o=="object"&&typeof o.message=="string"&&o.message.trim()&&(r=o.message.trim())}catch{}return new sv(e.status,`${t} (HTTP ${e.status}): ${r||e.statusText||"no reason given"}`)}async function Wy(e){var n;let t="";try{t=(await e.text()).trim()}catch{return""}try{const r=(n=JSON.parse(t))==null?void 0:n.detail;return typeof r=="string"?r.trim():r&&typeof r.message=="string"?r.message.trim():""}catch{return t}}class qy{constructor(t){kn(this,"_cfg");kn(this,"fetch_gateway",(t,n)=>fetch(Yt(this._cfg.base_url,t),{...n,headers:{...n==null?void 0:n.headers,...Xt(this._cfg.auth_token)}}));this._cfg={...t,base_url:(t.base_url||"").trim()}}async start_run(t,n,r){const i=String((r==null?void 0:r.bundle_id)||"").trim(),o=(r==null?void 0:r.session_id)===null||(r==null?void 0:r.session_id)===void 0?"":String(r.session_id||"").trim(),u=String(t||"").trim(),l=String((r==null?void 0:r.interface)||"").trim();if(u==="@default"&&(!l||i))throw new Error("start_run: flow_id '@default' needs `interface` and no bundle_id");const d={input_data:n||{}};i&&(d.bundle_id=i),u&&(d.flow_id=u),u==="@default"&&(d.interface=l),o&&(d.session_id=o),r!=null&&r.workspace&&(d.workspace=r.workspace);const h=await an(Yt(this._cfg.base_url,wt("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...Xt(this._cfg.auth_token)},body:JSON.stringify(d)});if(!h.ok)throw new Error(await Wy(h)||`start_run failed: ${h.status}`);const m=await h.json(),_=m==null?void 0:m.run_id;if(typeof _!="string"||!_)throw new Error("start_run: missing run_id");return _}async list_mcp_servers(){for(const t of[wt("mcp/servers"),wt("mcp"),wt("discovery/mcp")])try{const n=await an(Yt(this._cfg.base_url,t),{headers:{...Xt(this._cfg.auth_token)},signal:Ys()});if(n.status===404||!n.ok)continue;const r=await n.json(),i=Array.isArray(r)?r:Array.isArray(r==null?void 0:r.servers)?r.servers:Array.isArray(r==null?void 0:r.items)?r.items:null;if(!i)continue;return i.map(o=>({name:String((o==null?void 0:o.name)||(o==null?void 0:o.id)||"").trim(),url:typeof(o==null?void 0:o.url)=="string"?o.url:void 0,description:typeof(o==null?void 0:o.description)=="string"?o.description:void 0,auth_required:typeof(o==null?void 0:o.auth_required)=="boolean"?o.auth_required:void 0})).filter(o=>o.name)}catch{return null}return null}async list_skills(){for(const t of[wt("skills"),wt("skills/registry")])try{const n=await an(Yt(this._cfg.base_url,t),{headers:{...Xt(this._cfg.auth_token)},signal:Ys()});if(n.status===404||!n.ok)continue;const r=await n.json(),i=Array.isArray(r)?r:Array.isArray(r==null?void 0:r.skills)?r.skills:Array.isArray(r==null?void 0:r.items)?r.items:null;if(!i)continue;return i.map(o=>({name:String((o==null?void 0:o.name)||(o==null?void 0:o.id)||"").trim(),description:typeof(o==null?void 0:o.description)=="string"?o.description:void 0,version:typeof(o==null?void 0:o.version)=="string"?o.version:void 0,trust_level:typeof(o==null?void 0:o.trust_level)=="string"?o.trust_level:void 0,blocked:typeof(o==null?void 0:o.blocked)=="boolean"?o.blocked:void 0,requires_review:typeof(o==null?void 0:o.requires_review)=="boolean"?o.requires_review:void 0,tree_hash:typeof(o==null?void 0:o.tree_hash)=="string"?o.tree_hash:void 0,reasons:Array.isArray(o==null?void 0:o.reasons)?o.reasons.map(u=>String(u||"")).filter(Boolean):void 0})).filter(o=>o.name)}catch{return null}return null}async get_run(t){const n=await an(Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}`)),{headers:{...Xt(this._cfg.auth_token)}});if(!n.ok)throw new Error(`get_run failed: ${await vs(n)}`);return await n.json()}async find_run(t){const n=await an(Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}`)),{headers:{...Xt(this._cfg.auth_token)}});if(n.status===404||n.status===403)return null;if(!n.ok)throw await Xc(n,"Opening the run failed");return await n.json()}async get_run_history_bundle(t,n){const r=String(t||"").trim();if(!r)throw new Error("get_run_history_bundle: run_id is required");const i=new URLSearchParams;(n==null?void 0:n.include_subruns)===!1&&i.set("include_subruns","false"),(n==null?void 0:n.include_session)===!0&&i.set("include_session","true"),typeof(n==null?void 0:n.session_turn_limit)=="number"&&Number.isFinite(n.session_turn_limit)&&i.set("session_turn_limit",String(Math.max(1,Math.trunc(n.session_turn_limit)))),n!=null&&n.ledger_mode&&i.set("ledger_mode",String(n.ledger_mode)),typeof(n==null?void 0:n.ledger_max_items)=="number"&&Number.isFinite(n.ledger_max_items)&&i.set("ledger_max_items",String(Math.max(0,Math.trunc(n.ledger_max_items))));const o=Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/history_bundle?${i.toString()}`)),u=await an(o,{headers:{...Xt(this._cfg.auth_token)}});if(!u.ok)throw new Error(`get_run_history_bundle failed: ${await vs(u)}`);return await u.json()}async list_runs(t){const n=typeof(t==null?void 0:t.limit)=="number"?t.limit:50,r=String((t==null?void 0:t.status)||"").trim(),i=String((t==null?void 0:t.workflow_id)||"").trim(),o=String((t==null?void 0:t.session_id)||"").trim(),u=(t==null?void 0:t.root_only)===!0,l=new URLSearchParams;l.set("limit",String(n)),r&&l.set("status",r),i&&l.set("workflow_id",i),o&&l.set("session_id",o),u&&l.set("root_only","true"),(t==null?void 0:t.archived_only)===!0&&l.set("archived_only","true"),typeof(t==null?void 0:t.include_ledger_len)=="boolean"&&l.set("include_ledger_len",String(t.include_ledger_len)),typeof(t==null?void 0:t.include_metrics)=="boolean"&&l.set("include_metrics",String(t.include_metrics)),typeof(t==null?void 0:t.include_drafts)=="boolean"&&l.set("include_drafts",String(t.include_drafts));const d=Yt(this._cfg.base_url,wt(`runs?${l.toString()}`)),h=await an(d,{headers:{...Xt(this._cfg.auth_token)},signal:Ys()});if(!h.ok)throw new Error(`list_runs failed: ${await vs(h)}`);return await Uy(h,d,{signal:Ys()})}async audit_log_tail(t){const n=typeof(t==null?void 0:t.max_bytes)=="number"?Math.max(1024,Math.min(4e5,Math.floor(t.max_bytes))):8e4,r=Yt(this._cfg.base_url,wt(`audit/tail?max_bytes=${encodeURIComponent(String(n))}`)),i=await an(r,{headers:{...Xt(this._cfg.auth_token)}});if(!i.ok)throw new Error(`audit_log_tail failed: ${await vs(i)}`);return await i.json()}async gateway_about(){const t=await an(Yt(this._cfg.base_url,wt("about")),{headers:{...Xt(this._cfg.auth_token)},signal:Ys(void 0,1e4)});if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.json()}async get_run_input_data(t){const n=String(t||"").trim();if(!n)throw new Error("get_run_input_data: run_id is required");const r=await an(Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(n)}/input_data`)),{headers:{...Xt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_run_input_data failed: ${await vs(r)}`);return await r.json()}async get_run_after(t){const n=String(t||"").trim();if(!n)throw new Error("get_run_after: run_id is required");const r=await an(Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(n)}/after`)),{headers:{...Xt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_run_after failed: ${await vs(r)}`);return await r.json()}async list_run_artifacts(t,n){const r=String(t||"").trim();if(!r)throw new Error("list_run_artifacts: run_id is required");const i=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,o=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,u=Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(i))}&offset=${encodeURIComponent(String(o))}`)),l=await an(u,{headers:{...Xt(this._cfg.auth_token)}});if(!l.ok)throw new Error(`list_run_artifacts failed: ${await vs(l)}`);return await l.json()}async list_session_artifacts(t,n){const r=String(t||"").trim();if(!r)throw new Error("list_session_artifacts: session_id is required");const i=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,o=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,u=Yt(this._cfg.base_url,wt(`sessions/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(i))}&offset=${encodeURIComponent(String(o))}`)),l=await an(u,{headers:{...Xt(this._cfg.auth_token)}});if(!l.ok)throw new Error(`list_session_artifacts failed: ${await vs(l)}`);return await l.json()}async search_artifacts(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");const r=String((t==null?void 0:t.session_id)||"").trim(),i=String((t==null?void 0:t.run_id)||"").trim(),o=String((t==null?void 0:t.modality)||"").trim(),u=String((t==null?void 0:t.artifact_kind)||"").trim(),l=String((t==null?void 0:t.semantic_kind)||"").trim(),d=String((t==null?void 0:t.render_kind)||"").trim(),h=String((t==null?void 0:t.workflow_id)||"").trim(),m=String((t==null?void 0:t.node_id)||"").trim(),_=String((t==null?void 0:t.content_type)||"").trim(),g=String((t==null?void 0:t.query)||"").trim(),y=String((t==null?void 0:t.tags)||"").trim(),b=String((t==null?void 0:t.cursor)||"").trim(),k=String((t==null?void 0:t.order_by)||"").trim(),x=String((t==null?void 0:t.order)||"").trim(),N=String((t==null?void 0:t.created_after)||"").trim(),$=String((t==null?void 0:t.created_before)||"").trim(),E=typeof(t==null?void 0:t.limit)=="number"?t.limit:500,S=typeof(t==null?void 0:t.offset)=="number"?Math.max(0,Math.floor(t.offset)):0;r&&n.set("session_id",r),i&&n.set("run_id",i),o&&n.set("modality",o),u&&n.set("artifact_kind",u),l&&n.set("semantic_kind",l),d&&n.set("render_kind",d),h&&n.set("workflow_id",h),m&&n.set("node_id",m),_&&n.set("content_type",_),g&&n.set("query",g),y&&n.set("tags",y),b&&n.set("cursor",b),k&&n.set("order_by",k),x&&n.set("order",x),N&&n.set("created_after",N),$&&n.set("created_before",$),t!=null&&t.include_stats&&n.set("include_stats","true"),n.set("limit",String(E)),n.set("offset",String(S));const P=await an(Yt(this._cfg.base_url,wt(`artifacts/search?${n.toString()}`)),{headers:{...Xt(this._cfg.auth_token)}});if(!P.ok)throw new Error(`search_artifacts failed: ${await vs(P)}`);return await P.json()}async artifact_stats(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");for(const i of["session_id","run_id","modality","semantic_kind","render_kind","workflow_id","node_id","content_type","query","tags","created_after","created_before"]){const o=String((t==null?void 0:t[i])||"").trim();o&&n.set(i,o)}const r=await an(Yt(this._cfg.base_url,wt(`artifacts/stats?${n.toString()}`)),{headers:{...Xt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`artifact_stats failed: ${await vs(r)}`);return await r.json()}async download_run_artifact_content(t,n,r){const i=String(t||"").trim(),o=String(n||"").trim();if(!i)throw new Error("download_run_artifact_content: run_id is required");if(!o)throw new Error("download_run_artifact_content: artifact_id is required");const u=String((r==null?void 0:r.access)||"").trim(),l=u?`?access=${encodeURIComponent(u)}`:"",d=Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(i)}/artifacts/${encodeURIComponent(o)}/content${l}`)),h=await an(d,{headers:{...Xt(this._cfg.auth_token)}});if(!h.ok)throw new Error(`download_run_artifact_content failed: ${await vs(h)}`);return await h.blob()}async list_entities(){const t=await an(Yt(this._cfg.base_url,wt("entities")),{headers:{...Xt(this._cfg.auth_token)},signal:Ys()});if(!t.ok)throw new Error(`list_entities failed: ${await vs(t)}`);const n=await t.json();return{entities:Array.isArray(n==null?void 0:n.entities)?n.entities:[]}}async get_entity_phases_spec(){const t=await an(Yt(this._cfg.base_url,wt("entities/spec/phases")),{headers:{...Xt(this._cfg.auth_token)},signal:Ys()});if(!t.ok)throw new Error(`get_entity_phases_spec failed: ${await vs(t)}`);return await t.json()}async get_entity_cognition(t){const n=await an(Yt(this._cfg.base_url,wt(`entities/${encodeURIComponent(t)}/cognition`)),{headers:{...Xt(this._cfg.auth_token)},signal:Ys()});if(!n.ok)throw new Error(`get_entity_cognition failed: ${await vs(n)}`);return await n.json()}async get_entity_card(t){const n=String(t||"").trim();if(!n)throw new Error("get_entity_card: name is required");const r=await an(Yt(this._cfg.base_url,wt(`entities/${encodeURIComponent(n)}/card`)),{headers:{...Xt(this._cfg.auth_token)},signal:Ys()});if(!r.ok)throw new Error(`get_entity_card failed: ${await vs(r)}`);return await r.json()}async read_entity_diary_entry(t,n){const r=String(t||"").trim(),i=String(n||"").trim();if(!r||!i)throw new Error("read_entity_diary_entry: name and entry_id are required");const o=Yt(this._cfg.base_url,wt(`entities/${encodeURIComponent(r)}/diary/${encodeURIComponent(i)}?reason=${encodeURIComponent("observer board hint chip")}`)),u=await an(o,{headers:{...Xt(this._cfg.auth_token)},signal:Ys()});if(!u.ok)throw new Error(`read_entity_diary_entry failed: ${await vs(u)}`);return await u.json()}async get_ledger(t,n){const r=Number((n==null?void 0:n.after)||0),i=Number((n==null?void 0:n.limit)||0),o=Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}/ledger?after=${encodeURIComponent(String(r))}&limit=${encodeURIComponent(String(i))}`)),u=await an(o,{headers:{...Xt(this._cfg.auth_token)},signal:Ys(n==null?void 0:n.signal)});if(!u.ok)throw new Error(`get_ledger failed: ${u.status}`);const l=await Uy(u,o,{signal:Ys()}),d=Array.isArray(l==null?void 0:l.items)?l.items:[],h=typeof(l==null?void 0:l.next_after)=="number"?l.next_after:r;return{items:d,next_after:h}}async get_ledger_batch(t){const n=Array.isArray(t==null?void 0:t.runs)?t.runs:[],r=Number((t==null?void 0:t.limit)||0),i=await an(Yt(this._cfg.base_url,wt("runs/ledger/batch")),{method:"POST",headers:{"Content-Type":"application/json",...Xt(this._cfg.auth_token)},body:JSON.stringify({runs:n,limit:r}),signal:Ys()});if(!i.ok)throw new Error(`get_ledger_batch failed: ${i.status}`);const o=await Uy(i,Yt(this._cfg.base_url,wt("runs/ledger/batch")),{method:"POST",signal:Ys()}),l=(o&&typeof o=="object"?o:{}).runs;return{runs:l&&typeof l=="object"?l:{}}}async generate_run_summary(t,n){const r=String(t||"").trim();if(!r)throw new Error("generate_run_summary: run_id is required");const i={include_subruns:(n==null?void 0:n.include_subruns)!==!1},o=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";o&&(i.provider=o);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(i.model=u);const l=await an(Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/summary`)),{method:"POST",headers:{"Content-Type":"application/json",...Xt(this._cfg.auth_token)},body:JSON.stringify(i)});if(!l.ok)throw await Xc(l,"The gateway could not summarize this run");return await l.json()}async run_chat(t,n){const r=String(t||"").trim();if(!r)throw new Error("run_chat: run_id is required");const i={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[],persist:!!(n!=null&&n.persist)},o=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";o&&(i.provider=o);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(i.model=u);const l=await an(Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/chat`)),{method:"POST",headers:{"Content-Type":"application/json",...Xt(this._cfg.auth_token)},body:JSON.stringify(i)});if(!l.ok)throw await Xc(l,"The gateway could not answer");return await l.json()}async audio_transcribe(t,n){const r=String(t||"").trim();if(!r)throw new Error("audio_transcribe: run_id is required");const i=n==null?void 0:n.audio_artifact;if(!i||typeof i!="object")throw new Error("audio_transcribe: audio_artifact is required");if(!String(i.$artifact||"").trim())throw new Error("audio_transcribe: audio_artifact.$artifact is required");const u={audio_artifact:i};for(const m of["language","provider","model","request_id"]){const _=String((n==null?void 0:n[m])||"").trim();_&&(u[m]=_)}const l=await an(Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...Xt(this._cfg.auth_token)},body:JSON.stringify(u)});if(!l.ok)throw await Xc(l,"The gateway refused the transcription");const d=await l.json(),h=String((d==null?void 0:d.text)||"");return{ok:!!(d!=null&&d.ok),run_id:String((d==null?void 0:d.run_id)||""),request_id:String((d==null?void 0:d.request_id)||""),text:h,transcript_artifact:d==null?void 0:d.transcript_artifact,provider:d!=null&&d.provider?String(d.provider):null,model:d!=null&&d.model?String(d.model):null,duration_ms:Number.isFinite(Number(d==null?void 0:d.duration_ms))?Number(d.duration_ms):null}}async voice_defaults(){const t=await an(Yt(this._cfg.base_url,wt("voice/defaults")),{headers:{...Xt(this._cfg.auth_token)},signal:Ys()});if(!t.ok)throw await Xc(t,"The gateway could not list its voice defaults");return await t.json()}async voice_catalog(t,n){const r=new URLSearchParams({compact:"true"});t&&r.set("provider",t),n&&r.set("model",n);const i=await an(Yt(this._cfg.base_url,wt(`voice/voices?${r.toString()}`)),{headers:{...Xt(this._cfg.auth_token)},signal:Ys()});if(!i.ok)throw await Xc(i,"The gateway could not list its voices");return await i.json()}async voice_design(t){const n={description:t.description};t.name&&(n.name=t.name),t.language&&(n.language=t.language);const r=await an(Yt(this._cfg.base_url,wt("voice/design")),{method:"POST",headers:{"Content-Type":"application/json",...Xt(this._cfg.auth_token)},body:JSON.stringify(n)});if(!r.ok)throw new sv(r.status,await Wy(r)||`The gateway could not create the voice (HTTP ${r.status}).`);return await r.json()}async voice_clone(t,n){const r=new FormData;r.set("file",t,t.name||"recording.wav"),n.name&&r.set("name",n.name),n.language&&r.set("language",n.language),n.reference_text&&r.set("reference_text",n.reference_text);const i=await an(Yt(this._cfg.base_url,wt("voice/clones")),{method:"POST",headers:{...Xt(this._cfg.auth_token)},body:r});if(!i.ok)throw new sv(i.status,await Wy(i)||`The gateway could not clone the voice (HTTP ${i.status}).`);return await i.json()}gateway_url(t){return Yt(this._cfg.base_url,t)}auth_headers(){return Xt(this._cfg.auth_token)}async voice_tts(t,n){const r=String(t||"").trim();if(!r)throw new Error("voice_tts: run_id is required");const i=String((n==null?void 0:n.text)||"").trim();if(!i)throw new Error("voice_tts: text is required");const o={text:i},u=String((n==null?void 0:n.voice)||"").trim();u&&(o.voice=u);const l=String((n==null?void 0:n.format)||"").trim();l&&(o.format=l);const d=String((n==null?void 0:n.request_id)||"").trim();d&&(o.request_id=d);const h=await an(Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/voice/tts`)),{method:"POST",headers:{"Content-Type":"application/json",...Xt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!h.ok)throw new Error(`voice_tts failed: ${await vs(h)}`);const m=await h.json();return{ok:!!(m!=null&&m.ok),run_id:String((m==null?void 0:m.run_id)||""),request_id:String((m==null?void 0:m.request_id)||""),audio_artifact:m==null?void 0:m.audio_artifact}}async save_chat_thread(t,n){const r=String(t||"").trim();if(!r)throw new Error("save_chat_thread: run_id is required");const i={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[]},o=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";o&&(i.provider=o);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(i.model=u);const l=typeof(n==null?void 0:n.title)=="string"?String(n.title).trim():"";l&&(i.title=l);const d=await an(Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/chat_threads`)),{method:"POST",headers:{"Content-Type":"application/json",...Xt(this._cfg.auth_token)},body:JSON.stringify(i)});if(!d.ok)throw new Error(`save_chat_thread failed: ${await vs(d)}`);return await d.json()}async list_bundles(){const t=await an(Yt(this._cfg.base_url,wt("bundles")),{headers:{...Xt(this._cfg.auth_token)},signal:Ys()});if(!t.ok)throw new Error(`list_bundles failed: ${t.status}`);return await t.json()}async list_apps(){return await this.get_gateway_json("apps")}async get_gateway_json(t,n){const r=await an(Yt(this._cfg.base_url,wt(t)),{headers:{...Xt(this._cfg.auth_token)},signal:n??Ys()});if(!r.ok)throw new Error(await vs(r));return await r.json()}async reload_bundles(){const t=await an(Yt(this._cfg.base_url,wt("bundles/reload")),{method:"POST",headers:{...Xt(this._cfg.auth_token)}});if(!t.ok)throw new Error(`reload_bundles failed: ${t.status}`);return await t.json()}async upload_bundle(t,n){const r=(n==null?void 0:n.overwrite)===!0,i=(n==null?void 0:n.reload)!==!1,o=new FormData;o.set("overwrite",r?"true":"false"),o.set("reload",i?"true":"false"),o.set("file",t,t.name||"upload.flow");const u=await an(Yt(this._cfg.base_url,wt("bundles/upload")),{method:"POST",headers:{...Xt(this._cfg.auth_token)},body:o});if(!u.ok)throw new Error(`upload_bundle failed: ${await vs(u)}`);return await u.json()}async attachments_upload(t,n,r){const i=String(t||"").trim();if(!i)throw new Error("attachments_upload: session_id is required");if(!n)throw new Error("attachments_upload: file is required");const o=String((r==null?void 0:r.filename)||"").trim()||String((n==null?void 0:n.name)||"").trim()||"upload.bin",u=String((r==null?void 0:r.content_type)||"").trim()||String((n==null?void 0:n.type)||"").trim(),l=new FormData;l.append("session_id",i),l.append("file",n,o),l.append("filename",o),u&&l.append("content_type",u);const d=await an(Yt(this._cfg.base_url,wt("attachments/upload")),{method:"POST",headers:{...Xt(this._cfg.auth_token)},body:l});if(!d.ok)throw new Error(`attachments_upload failed: ${await vs(d)}`);const h=await d.json(),m=h==null?void 0:h.attachment;if(!m||typeof m!="object")throw new Error("attachments_upload: missing attachment");if(!String(m.$artifact||"").trim())throw new Error("attachments_upload: missing attachment.$artifact");return m}async remove_bundle(t,n){const r=String(t||"").trim();if(!r)throw new Error("remove_bundle: bundle_id is required");const i=new URLSearchParams,o=String((n==null?void 0:n.bundle_version)||"").trim();o&&i.set("bundle_version",o),i.set("reload",(n==null?void 0:n.reload)===!1?"false":"true");const u=Yt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(r)}?${i.toString()}`)),l=await an(u,{method:"DELETE",headers:{...Xt(this._cfg.auth_token)}});if(!l.ok)throw new Error(`remove_bundle failed: ${await vs(l)}`);return await l.json()}async discovery_tools(){const t=await an(Yt(this._cfg.base_url,wt("discovery/tools")),{headers:{...Xt(this._cfg.auth_token)}});if(!t.ok)throw new Error(`discovery_tools failed: ${t.status}`);return await t.json()}async discovery_providers(t){const n=(t==null?void 0:t.include_models)===!0,r=Yt(this._cfg.base_url,wt(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),i=await an(r,{headers:{...Xt(this._cfg.auth_token)}});if(!i.ok)throw new Error(`discovery_providers failed: ${i.status}`);return await i.json()}async discovery_provider_models(t){const n=String(t||"").trim();if(!n)throw new Error("discovery_provider_models: provider_name is required");const r=await an(Yt(this._cfg.base_url,wt(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...Xt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`discovery_provider_models failed: ${r.status}`);return await r.json()}async get_bundle(t){const n=String(t||"").trim();if(!n)throw new Error("get_bundle: bundle_id is required");const r=await an(Yt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(n)}`)),{headers:{...Xt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_bundle failed: ${r.status}`);return await r.json()}async get_bundle_flow(t,n){const r=String(t||"").trim(),i=String(n||"").trim();if(!r)throw new Error("get_bundle_flow: bundle_id is required");if(!i)throw new Error("get_bundle_flow: flow_id is required");const o=await an(Yt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(r)}/flows/${encodeURIComponent(i)}`)),{headers:{...Xt(this._cfg.auth_token)}});if(!o.ok)throw new Error(`get_bundle_flow failed: ${o.status}`);return await o.json()}async get_workflow_flow(t){const n=String(t||"").trim();if(!n)throw new Error("get_workflow_flow: workflow_id is required");const r=await an(Yt(this._cfg.base_url,wt(`workflows/${encodeURIComponent(n)}/flow`)),{headers:{...Xt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_workflow_flow failed: ${r.status}`);return await r.json()}async discovery_capabilities(){const t=await an(Yt(this._cfg.base_url,wt("discovery/capabilities")),{headers:{...Xt(this._cfg.auth_token)},signal:Ys()});if(!t.ok)throw new Error(`discovery_capabilities failed: ${await vs(t)}`);return await t.json()}automations_client(){const t=this._cfg.auth_token;return YE({fetch:(n,r)=>fetch(n,r),baseUrl:this._cfg.base_url,headers:()=>Xt(t)})}async submit_command(t){const n=await an(Yt(this._cfg.base_url,wt("commands")),{method:"POST",headers:{"Content-Type":"application/json",...Xt(this._cfg.auth_token)},body:JSON.stringify(t)});if(!n.ok)throw new Error(`submit_command failed: ${n.status}`);return await n.json()}async kg_query(t){const n=String((t==null?void 0:t.scope)||"session").trim().toLowerCase(),r=String((t==null?void 0:t.order)||"desc").trim().toLowerCase(),i=typeof(t==null?void 0:t.limit)=="number"&&Number.isFinite(t.limit)?Number(t.limit):500,o={scope:n,order:r,limit:i},u=String((t==null?void 0:t.run_id)||"").trim();u&&(o.run_id=u);const l=String((t==null?void 0:t.session_id)||"").trim();l&&(o.session_id=l);const d=String((t==null?void 0:t.owner_id)||"").trim();d&&(o.owner_id=d),t!=null&&t.all_owners&&(o.all_owners=!0);const h=String((t==null?void 0:t.subject)||"").trim();h&&(o.subject=h);const m=String((t==null?void 0:t.predicate)||"").trim();m&&(o.predicate=m);const _=String((t==null?void 0:t.object)||"").trim();_&&(o.object=_);const g=String((t==null?void 0:t.since)||"").trim();g&&(o.since=g);const y=String((t==null?void 0:t.until)||"").trim();y&&(o.until=y);const b=String((t==null?void 0:t.active_at)||"").trim();b&&(o.active_at=b);const k=String((t==null?void 0:t.query_text)||"").trim();k&&(o.query_text=k),typeof(t==null?void 0:t.min_score)=="number"&&Number.isFinite(t.min_score)&&(o.min_score=Number(t.min_score));const x=await an(Yt(this._cfg.base_url,wt("kg/query")),{method:"POST",headers:{"Content-Type":"application/json",...Xt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!x.ok)throw new Error(`kg_query failed: ${await vs(x)}`);return await x.json()}async stream_ledger(t,n){var _;const r=Number((n==null?void 0:n.after)||0),i=n.on_step,o=n.signal,u=Yt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}/ledger/stream?after=${encodeURIComponent(String(r))}`)),l=await an(u,{headers:{Accept:"text/event-stream",...Xt(this._cfg.auth_token)},signal:o});if(!l.ok)throw await Xc(l,"The ledger stream was refused");if(!l.body)throw new Error("stream_ledger: response body is missing");(_=n.on_open)==null||_.call(n);const d=l.body.getReader(),h=new TextDecoder("utf-8"),m=new cP;for(;;){const{value:g,done:y}=await d.read();if(y)return;const b=h.decode(g,{stream:!0});m.push(b,k=>{if(!(k.event!=="step"||!k.data))try{const x=JSON.parse(k.data);x&&typeof x.cursor=="number"&&x.record&&i(x)}catch{}})}}}function fP(e,t=()=>({})){return async(n,r)=>{var l;const i=await e(n,{method:r.method,headers:{Accept:"application/json",...r.body!==void 0?{"Content-Type":"application/json"}:{},...t()},...r.body!==void 0?{body:JSON.stringify(r.body)}:{}}),o=await i.text();let u=null;try{u=o?JSON.parse(o):null}catch{u=null}if(!i.ok)throw new Error(typeof(u==null?void 0:u.detail)=="string"?u.detail:typeof((l=u==null?void 0:u.detail)==null?void 0:l.message)=="string"?u.detail.message:o||`Gateway request failed (${i.status})`);return u}}function hP({connected:e,request:t,value:n,onChange:r,disabled:i}){const[o,u]=p.useState(null),[l,d]=p.useState(null),h=JSON.stringify(n);p.useEffect(()=>{if(!e){u(null),d(null);return}let g=!0;return d(null),Qh(t)(n).then(y=>g&&u(y)).catch(y=>g&&d(`Could not read your workspaces: ${Ag(y)}`)),()=>{g=!1}},[e,h,t]);const m=p.useCallback(async g=>{const y=await Qh(t)(g);u(y),r(g)},[t,r]),_=e?i?"The run is starting.":null:"Connect to your gateway to choose workspaces.";return s.jsx(VS,{level:"run",idPrefix:"observer-launch-workspace",value:n,effective:o,onChange:m,loadError:e?l:_,unavailableReason:_})}function mP(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class _P{constructor(t){kn(this,"_cfg");this._cfg={...t,url:(t.url||"").trim()}}async call_tool(t){const n=String((t==null?void 0:t.name)||"").trim(),r=String((t==null?void 0:t.call_id)||(t==null?void 0:t.id)||Xs()),i=t!=null&&t.arguments&&typeof t.arguments=="object"?t.arguments:{};if(!n)return{call_id:r,name:"",success:!1,output:null,error:"Missing tool name"};const o={jsonrpc:"2.0",id:Xs(),method:"tools/call",params:{name:n,arguments:i}},u=await fetch(this._cfg.url,{method:"POST",headers:{"Content-Type":"application/json",...mP(this._cfg.auth_token)},body:JSON.stringify(o)});if(!u.ok)return{call_id:r,name:n,success:!1,output:null,error:`Worker HTTP ${u.status}`};const l=await u.json().catch(()=>null),d=l==null?void 0:l.result,h=!!(d!=null&&d.isError),_=(Array.isArray(d==null?void 0:d.content)?d.content:[]).find(y=>y&&y.type==="text"&&typeof y.text=="string"),g=(_==null?void 0:_.text)??"";return h?{call_id:r,name:n,success:!1,output:null,error:g||"Tool failed"}:{call_id:r,name:n,success:!0,output:g,error:null}}}class F0{constructor(t,n){kn(this,"pending",[]);kn(this,"scheduled",!1);kn(this,"generation",0);this.schedule=t,this.on_flush=n}push(t){if(this.pending.push(t),this.scheduled)return;this.scheduled=!0;const n=this.generation;this.schedule(()=>{if(n!==this.generation)return;this.scheduled=!1;const r=this.pending;this.pending=[],r.length&&this.on_flush(r)})}reset(){this.generation+=1,this.pending=[],this.scheduled=!1}pending_count(){return this.pending.length}}function z0(e,t=""){const n=String(e.role||"").trim(),r=String(e.automation_id||"").trim();return n==="occurrence"&&r&&r!==e.run_id?r:String(e.parent_run_id||t||"").trim()}function pP(e,t){const n=Ht(e.updated_at||e.created_at)??0;return(Ht(t.updated_at||t.created_at)??0)-n}function gP(e,t){const n=t.query.trim().toLowerCase(),r=[...e],i={};for(const g of r){const y=String(g.run_id||"").trim();y&&(i[y]=g)}for(const g of e){const y=z0(g);if(String(g.role||"")==="occurrence"&&y&&!i[y]){const b={run_id:y,workflow_id:null,status:"",role:"controller",session_kind:"automation",automation_id:y,updated_at:g.updated_at??null,created_at:g.created_at??null};i[y]=b,r.push(b)}}const o={},u={};for(const g of r){const y=String(g.run_id||"").trim();if(!y)continue;const b=z0(g,t.parent_hint?t.parent_hint(y):"");u[y]=b,b&&(o[b]||(o[b]=[])).push(g)}const l=g=>{const y=String(g.status||"").trim().toLowerCase();return t.filter==="all"?!0:t.filter==="active"?Gd(y):t.filter==="waiting"?y==="waiting":t.filter==="terminal"?ds(y):t.filter==="failed"?y==="failed":!0},d=g=>{if(!n)return!0;const y=String(g.workflow_id||g.schedule_target_workflow_id||"").trim(),b=y?t.workflow_label_by_id[y]||y:"";return[g.run_id,y,b,g.session_id,g.status,g.session_kind,g.automation_id].join(" ").toLowerCase().includes(n)},h=[];for(const g of r){const y=String(g.run_id||"").trim();if(!y)continue;const b=u[y];(!b||!i[b])&&h.push(y)}const m={},_=g=>{if(t.group_by==="workflow"){const b=String(g.schedule_target_workflow_id||g.workflow_id||"").trim()||"(unknown workflow)";return{key:b,label:t.workflow_label_by_id[b]||b}}if(t.group_by==="session"){const b=String(g.session_id||"").trim()||"(no session)";return{key:b,label:b}}const y=String(g.status||"").trim().toLowerCase()||"unknown";return Gd(y)?{key:"active",label:"Active"}:y==="failed"?{key:"failed",label:"Failed"}:ds(y)?{key:"finished",label:"Finished"}:{key:y,label:y}};for(const g of h){const y=i[g];if(!y)continue;const b=[...o[g]||[]].sort(pP),k=b.some(N=>l(N)&&d(N));if(!(l(y)&&d(y))&&!k)continue;const x=_(y);m[x.key]||(m[x.key]={key:x.key,label:x.label,rows:[]}),m[x.key].rows.push({run:y,children:b})}return Object.values(m).sort((g,y)=>{const b={active:0,waiting:1,failed:2,finished:3},k=b[g.key]??10,x=b[y.key]??10;return k!==x?k-x:g.label.localeCompare(y.label)})}const B0=60;function Jd(e){try{const t=JSON.stringify(e);return t===void 0?String(e):t}catch{return String(e)}}function Hy(e,t,n){return`${e.toLocaleString("en-US")} ${e===1?t:n}`}function sg(e){if(e===void 0)return"undefined";if(typeof e=="string")return e.length<=B0&&!e.includes(`
135
+ `)?JSON.stringify(e):`text (${Hy(e.length,"char","chars")})`;if(e===null||typeof e!="object")return Jd(e);const t=Jd(e);return t.length<=B0?t:Array.isArray(e)?`list (${Hy(e.length,"item","items")})`:`object (${Hy(Object.keys(e).length,"key","keys")})`}function yP(e){return e===void 0?!1:e&&typeof e=="object"&&!Array.isArray(e)?Object.values(e).some(t=>sg(t)!==Jd(t)):sg(e)!==Jd(e)}function wP(e){if(e===void 0)return"";if(e&&typeof e=="object"&&!Array.isArray(e)){const t=Object.keys(e);return t.length?`{${t.map(n=>`${n}: ${sg(e[n])}`).join(", ")}}`:"{}"}return sg(e)}function Ld(e){return Ht(e)}function vP(e){return e==null||e===""?"":typeof e=="string"?e:Jd(e)}function U0(e){return e.length?e[e.length-1]:null}function W0(e,t){var r,i;const n=String(e.status||"").trim().toLowerCase();if(n==="started"||n==="running")return"running";if(n==="waiting"){const o=(i=(r=e.record)==null?void 0:r.result)==null?void 0:i.wait;if(String((o==null?void 0:o.reason)||"")==="subworkflow"){const u=$m(e.record);if(u&&t(u)==="running")return"running"}return"waiting"}return n==="failed"?"failed":n==="completed"||e.ended_at?"done":"running"}function xP(e,t){return e.t===null||t.t===null?e.t===null&&(t.t!==null||e.seq<t.seq):e.t<t.t||e.t===t.t&&e.seq<t.seq}function q0(e){const t=new Map;for(const i of[...e].sort((o,u)=>o.seq-u.seq)){const o=t.get(i.rid)||[];o.push(i),t.set(i.rid,o)}const n=Array.from(t.values()),r=[];for(;n.some(i=>i.length);){let i=null;for(const o of n)if(o.length){if(!i){i=o;continue}xP(o[0],i[0])&&(i=o)}r.push(i.shift())}return r}function bP(e){return Ld(e.ended_at)??Ld(e.started_at)}function kP(e,t,n){var k,x,N,$,E,S,P,D,R,I;const r=String(t||"").trim();if(!r)return{};const i=[],o=new Set;for(const W of e||[]){const G=String((W==null?void 0:W.run_id)||((k=W==null?void 0:W.record)==null?void 0:k.run_id)||"").trim();G&&!o.has(G)&&(o.add(G),i.push(G))}i.sort((W,G)=>W===r?-1:G===r?1:0);const u=new Map;for(const W of i)u.set(W,Mg(e,W));const l=(W,G)=>{const K=String(n(W,G)||"").trim();return!K||W!==r&&K===G?"":K},d=new Map,h=(W,G=0)=>{if(d.has(W))return d.get(W)??null;d.set(W,null);const K=G<6?U0(u.get(W)||[]):null,H=K?W0(K,M=>h(M,G+1)):null;return d.set(W,H),H},m=new Map,_=(W,G)=>{let K=m.get(W);return K||(K={facts:{node_id:G,graph_id:W,run_ids:[],status:"done",visits:0,first_ms:null,last_ms:null,duration_ms:0,last_effect:"",last_status:"",llm:null,tools:[],waits:[],subruns:[],last_result_summary:"",last_result:void 0,last_error:"",context:null,records:[]},steps:[],records:[]},m.set(W,K)),K};let g=0;for(const W of i)for(const G of u.get(W)||[]){const K=String(G.node_id||"").trim();if(!K)continue;const H=l(W,K);if(!H)continue;const M=_(H,K);M.steps.push({step:G,rid:W,t:bP(G),seq:g++}),M.facts.run_ids.includes(W)||M.facts.run_ids.push(W)}const y=(e||[]).filter(W=>W&&W.record).map((W,G)=>({x:W,i:G})).sort((W,G)=>{const K=i.indexOf(String(W.x.run_id||W.x.record.run_id||"").trim()),H=i.indexOf(String(G.x.run_id||G.x.record.run_id||"").trim());return K!==H?K-H:(W.x.cursor||0)-(G.x.cursor||0)||W.i-G.i});g=0;for(const{x:W}of y){const G=String(W.run_id||W.record.run_id||"").trim(),K=String(W.record.node_id||"").trim();if(!G||!K)continue;const H=l(G,K),M=H?m.get(H):void 0;M&&M.records.push({rec:W.record,rid:G,t:Ld(W.record.ended_at)??Ld(W.record.started_at),seq:g++})}const b={};for(const[W,G]of m){const K=G.facts,H=q0(G.steps).map(se=>se.step),M=U0(H);K.visits=H.length,K.status=W0(M,se=>h(se)),K.last_effect=M.effect_type,K.last_status=M.status;let A=0,O=0,L=0,V=!1,J=0,U=null;const te=new Map;for(const se of H){const de=Ld(se.started_at),be=Ld(se.ended_at)??de;if(de!==null&&(K.first_ms=K.first_ms===null?de:Math.min(K.first_ms,de)),be!==null&&(K.last_ms=K.last_ms===null?be:Math.max(K.last_ms,be)),typeof se.duration_ms=="number"&&(K.duration_ms+=se.duration_ms),se.kind==="llm_call"){J+=1,U=se;const je=((N=(x=se.record)==null?void 0:x.result)==null?void 0:N.usage)||((E=($=se.record)==null?void 0:$.result)==null?void 0:E.token_usage)||null;if(je&&typeof je=="object"){const ae=Number(je.prompt_tokens??je.input_tokens),xe=Number(je.completion_tokens??je.output_tokens),Ae=Number(je.total_tokens);(Number.isFinite(ae)||Number.isFinite(xe)||Number.isFinite(Ae))&&(V=!0,A+=Number.isFinite(ae)?ae:0,O+=Number.isFinite(xe)?xe:0,L+=Number.isFinite(Ae)?Ae:(Number.isFinite(ae)?ae:0)+(Number.isFinite(xe)?xe:0))}}else if(se.kind==="tool"){const je=Nm(se),ae=je.calls.length?je.calls.map(xe=>xe.name):je.results.map(xe=>xe.name);for(const xe of ae){const Ae=te.get(xe)||{name:xe,calls:0,failed:0};Ae.calls+=1,te.set(xe,Ae)}for(const xe of je.results){if(xe.success!==!1)continue;const Ae=te.get(xe.name)||{name:xe.name,calls:0,failed:0};Ae.failed+=1,te.set(xe.name,Ae)}}const Me=vP((S=se.record)==null?void 0:S.error);Me&&(K.last_error=Me),se.record&&Object.prototype.hasOwnProperty.call(se.record,"result")&&se.record.result!==void 0&&se.record.result!==null&&(K.last_result=se.record.result)}if(K.last_result_summary=wP(K.last_result),K.tools=Array.from(te.values()),J&&U){const se=Sm(U);if(K.llm={calls:J,model:se.model,provider:se.provider},V&&(K.llm.tokens={in:A,out:O,total:L}),se.messages.length||se.system){const de=se.system?[{role:"system",content:se.system},...se.messages]:[...se.messages];K.context={provider:se.provider,model:se.model,messages_source:se.messages_source,messages:de}}}K.records=q0(G.records).map(se=>se.rec);const z=K.status==="waiting"||K.status==="running"&&String(M.status)==="waiting"?String(((R=(D=(P=M.record)==null?void 0:P.result)==null?void 0:D.wait)==null?void 0:R.wait_key)||""):"",ne=new Set;for(const se of K.records){const de=(I=se==null?void 0:se.result)==null?void 0:I.wait;if(String(se.status||"")==="waiting"&&de&&typeof de=="object"){const Me=String(de.wait_key||""),je=`${String(de.reason||"")}|${Me}`;if(!ne.has(je)){ne.add(je);const ae={reason:String(de.reason||""),wait_key:Me,open:!1};typeof de.prompt=="string"&&de.prompt&&(ae.prompt=de.prompt),K.waits.push(ae)}}const be=$m(se);be&&!K.subruns.includes(be)&&K.subruns.push(be)}if(z)for(const se of K.waits)se.open=se.wait_key===z;b[W]=K}return b}function jP(e){const t={};for(const[n,r]of Object.entries(e||{}))t[n]=r.status;return t}function SP(e){const{records:t,context:n,...r}=e;return JSON.stringify(r,null,2)}function NP(e){return e.records.map(t=>Jd(t)).join(`
136
+ `)}function $P(e){return e.context?JSON.stringify(e.context,null,2):""}function Vy(e){return typeof e=="number"&&Number.isFinite(e)?new Date(e).toISOString():null}function CP(e){const t=new Map(e.nodes.map(r=>[r.id,r])),n=e.current_id?t.get(e.current_id):void 0;return{run_id:e.run_id,status:e.status,state:e.state,finished:e.finished,as_of:Vy(e.now_ms)||"",current_node:n?{id:n.id,label:n.label,type:n.type,status:e.status_of(n.id)}:null,nodes:e.nodes.map(r=>{const i=e.facts[r.id];return{id:r.id,label:r.label,type:r.type,status:e.status_of(r.id),visits:i?i.visits:0,first_at:i?Vy(i.first_ms):null,last_at:i?Vy(i.last_ms):null,duration_ms:i?i.duration_ms:0,llm:i?i.llm:null,tools:i?i.tools:[],waits:i?i.waits:[],subruns:i?i.subruns:[],last_result_summary:i?i.last_result_summary:"",last_error:i?i.last_error:""}}),edges:e.edges.map(r=>({source:r.source,target:r.target}))}}const EP={execution:"#FFFFFF",string:"#FF00FF",number:"#00FF00",boolean:"#FF0000",object:"#00FFFF",array:"#FF8800",tools:"#FF8800",provider:"#00D2FF",model:"#9D4EDD",provider_text:"#00D2FF",model_text:"#9D4EDD",provider_image:"#19D3B8",model_image:"#8B5CF6",provider_voice:"#22D3EE",model_voice:"#A855F7",agent:"#4488FF",any:"#888888"},AP=[{type:"execution",label:"Execution",shape:"▷",description:"Controls flow order"},{type:"string",label:"String",shape:"●",description:"Text data"},{type:"number",label:"Number",shape:"●",description:"Integer or float"},{type:"boolean",label:"Boolean",shape:"◇",description:"True/False"},{type:"object",label:"Object",shape:"●",description:"JSON objects"},{type:"array",label:"Array",shape:"■",description:"Collections"},{type:"tools",label:"Tools",shape:"■",description:"Tool allowlist (string[])"},{type:"provider_text",label:"Text Provider",shape:"●",description:"Text/LLM provider id/name"},{type:"provider_image",label:"Image Provider",shape:"●",description:"Image-generation provider id"},{type:"provider_voice",label:"Voice Provider",shape:"●",description:"Voice/TTS/STT provider id"},{type:"provider",label:"Provider (legacy)",shape:"●",description:"Legacy unscoped provider id/name"},{type:"model",label:"Model",shape:"●",description:"Model id/name scoped by the selected provider"},{type:"agent",label:"Agent",shape:"⬢",description:"Agent reference"},{type:"any",label:"Any",shape:"●",description:"Accepts any type"}];function TP(){const[e,t]=p.useState(!0);return s.jsxs("div",{className:"pin-legend",children:[s.jsxs("button",{className:"pin-legend-toggle mono",type:"button",onClick:()=>t(n=>!n),title:"Pin Type Legend",children:[e?"?":"×"," Pin Types"]}),e?null:s.jsxs("div",{className:"pin-legend-content",children:[AP.map(n=>s.jsxs("div",{className:"pin-legend-row",children:[s.jsx("span",{className:"pin-legend-shape",style:{color:EP[n.type]},children:n.shape}),s.jsx("span",{className:"pin-legend-label mono",children:n.label}),s.jsx("span",{className:"pin-legend-desc mono",children:n.description})]},n.type)),s.jsxs("div",{className:"pin-legend-rules mono",children:[s.jsx("strong",{children:"Connection Rules:"}),s.jsxs("ul",{children:[s.jsx("li",{children:"Execution connects to Execution only"}),s.jsx("li",{children:'"Any" type accepts all data types'}),s.jsx("li",{children:"Same types always compatible"}),s.jsx("li",{children:"Array and Object are interchangeable"}),s.jsx("li",{children:'"Tools" is compatible with Array (specialized string[])'})]})]})]})]})}const rv={execution:"#FFFFFF",string:"#FF00FF",number:"#00FF00",boolean:"#FF0000",object:"#00FFFF",json_schema:"#00FFFF",artifact:"#5EEAD4",artifact_image:"#19D3B8",artifact_audio:"#22D3EE",artifact_text:"#D946EF",artifact_video:"#A855F7",artifacts:"#2DD4BF",artifacts_image:"#0F766E",artifacts_audio:"#0891B2",artifacts_text:"#C026D3",artifacts_video:"#7C3AED",workspace_file:"#84CC16",workspace_folder:"#65A30D",memory:"#00C49A",assertion:"#00B8D4",assertions:"#00B8D4",array:"#FF8800",tools:"#FF8800",provider:"#00D2FF",model:"#9D4EDD",provider_text:"#00D2FF",model_text:"#9D4EDD",provider_image:"#19D3B8",model_image:"#9D4EDD",provider_video:"#A855F7",model_video:"#9D4EDD",provider_voice:"#22D3EE",model_voice:"#9D4EDD",provider_music:"#F59E0B",model_music:"#9D4EDD",agent:"#4488FF",email:"#FBBF24",emails:"#D97706",any:"#888888"};function MP(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(rv,e)}function RP(e){return MP(e)?rv[e]:rv.any}function LP(e){switch(e){case"execution":return"triangle";case"boolean":return"diamond";case"array":case"tools":case"assertions":return"square";case"agent":return"hexagon";default:return"circle"}}const IP=280,OP=6,PP=360,DP=1500;function g1(e,t=IP,n=OP){const r=String(e??"");let i=r.length,o=-1;for(let u=0;u<n&&(o=r.indexOf(`
137
+ `,o+1),o!==-1);u+=1)u===n-1&&(i=Math.min(i,o));return i=Math.min(i,t),i>=r.length?{shown:r,clamped:!1}:{shown:`${r.slice(0,i).trimEnd()}…`,clamped:!0}}function il(e){if(e===void 0)return"";if(typeof e=="string")return e;if(e===null||typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function FP(e){return e===null||["string","number","boolean"].includes(typeof e)}function H0(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function zP(e){if(Array.isArray(e)){const t=e.length,n=`array · ${t} item${t===1?"":"s"}`;if(!t)return{head:n,items:[],item_word:"items"};if(e.every(FP))return{head:n,items:e.map(o=>String(o)),item_word:"items"};const r=new Map;for(const o of e)r.set(H0(o),(r.get(H0(o))||0)+1);const i=[...r.entries()].map(([o,u])=>`${u} ${o}${u===1||o==="null"?"":"s"}`);return{head:`${n} (${i.join(", ")})`,items:[],item_word:"items"}}if(e&&typeof e=="object"){const t=e,n=Object.keys(t);return n.length===1&&typeof t.$artifact=="string"?{head:`artifact ${String(t.$artifact)}`,items:[],item_word:"keys"}:{head:`object · ${n.length} key${n.length===1?"":"s"}`,items:n,item_word:"keys"}}return{head:il(e),items:[],item_word:"items"}}function BP(e,t=PP){let n=0;for(let r=0;r<e.length;r+=1)if(n+=e[r].length+(r?2:0),n>t)return r;return e.length}function Ig(e){const[t,n]=p.useState("");p.useEffect(()=>{if(!t)return;const i=window.setTimeout(()=>n(""),DP);return()=>window.clearTimeout(i)},[t]);const r=`Copy ${e.label}`;return s.jsx("button",{type:"button",className:`ap_copy_btn${t?` is_${t}`:""}${e.className?` ${e.className}`:""}`,title:r,"aria-label":r,onClick:async i=>{if(i.stopPropagation(),e.on_copy){e.on_copy(e.text),n("copied");return}n(await Em(e.text)?"copied":"failed")},children:t==="copied"?"copied":t==="failed"?"copy failed":"⧉"})}function y1(e){const t=e.size??12,n=t/2,r=e.filled?"currentColor":"none",i=LP(e.type);let o;if(i==="triangle")o=s.jsx("polygon",{points:`0,0 ${t},${n} 0,${t}`,fill:r,stroke:"currentColor",strokeWidth:"1.5"});else if(i==="diamond")o=s.jsx("polygon",{points:`${n},0 ${t},${n} ${n},${t} 0,${n}`,fill:r,stroke:"currentColor",strokeWidth:"1.5"});else if(i==="square")o=s.jsx("rect",{x:"1",y:"1",width:t-2,height:t-2,fill:r,stroke:"currentColor",strokeWidth:"1.5"});else if(i==="hexagon"){const u=[[n,0],[t,t*.25],[t,t*.75],[n,t],[0,t*.75],[0,t*.25]].map(([l,d])=>`${l},${d}`).join(" ");o=s.jsx("polygon",{points:u,fill:r,stroke:"currentColor",strokeWidth:"1.5"})}else o=s.jsx("circle",{cx:n,cy:n,r:n-1,fill:r,stroke:"currentColor",strokeWidth:"1.5"});return s.jsx("svg",{className:"ap_pin_glyph","data-pin-shape":i,width:t,height:t,viewBox:`0 0 ${t} ${t}`,style:{color:RP(e.type)},"aria-hidden":"true",children:o})}function UP(e){const[t,n]=p.useState(!1),{shown:r,clamped:i}=g1(e.text);return e.text?s.jsxs("span",{className:"ap_pin_string",children:[s.jsx("span",{className:"ap_pin_text",children:t||!i?e.text:r}),i?s.jsx("button",{type:"button",className:"ap_link_btn","aria-expanded":t,onClick:()=>n(o=>!o),children:t?"show less":`show all (${e.text.length.toLocaleString("en-US")} chars)`}):null]}):s.jsx("span",{className:"ap_pin_muted",children:"empty text"})}function WP(e){const[t,n]=p.useState(!1),r=BP(e.items),o=r<e.items.length&&!t?e.items.slice(0,r):e.items;return s.jsxs("span",{className:"ap_json_items",children:[s.jsx("span",{className:"ap_json_list",children:o.join(", ")}),r<e.items.length?s.jsx("button",{type:"button",className:"ap_link_btn","aria-expanded":t,onClick:()=>n(u=>!u),children:t?"show less":`show all ${e.items.length.toLocaleString("en-US")} ${e.word}`}):null]})}function qP(e){const[t,n]=p.useState(!1),r=zP(e.value);return s.jsxs("div",{className:"ap_json",children:[s.jsxs("div",{className:"ap_json_head",children:[s.jsxs("span",{className:"ap_json_shape mono",children:[r.head,r.items.length?":":""]}),r.items.length?s.jsx(WP,{items:r.items,word:r.item_word}):null]}),s.jsxs("details",{className:"ap_json_details",open:t,onToggle:i=>n(i.currentTarget.open),children:[s.jsx("summary",{className:"mono",children:"full JSON"}),t?s.jsx("pre",{className:"ap_json_body mono",children:il(e.value)}):null]})]})}function rm(e){const t=e.value;return t===void 0?s.jsx("span",{className:"ap_pin_muted",children:"—"}):t===null?s.jsx("code",{className:"ap_pin_scalar ap_pin_muted",children:"null"}):typeof t=="string"?s.jsx(UP,{text:t}):typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"?s.jsx("code",{className:"ap_pin_scalar",children:String(t)}):typeof t=="object"?s.jsx(qP,{value:t}):s.jsx("code",{className:"ap_pin_scalar",children:String(t)})}function HP(e){return e.state==="value"?il(e.value):e.state==="not_provided"&&e.flow_default?il(e.flow_default.value):null}function VP(e){const{pin:t}=e;if(t.state==="value")return s.jsx(rm,{value:t.value});if(t.state==="not_provided")return s.jsxs("div",{className:"ap_pin_muted ap_pin_unsent",children:[s.jsx("span",{children:"not provided"}),t.flow_default?s.jsxs("div",{className:"ap_pin_default",children:[s.jsx("span",{className:"ap_pin_default_label",children:"flow default"})," ",s.jsx(rm,{value:t.flow_default.value})]}):null,t.required&&!t.flow_default?s.jsx("span",{className:"ap_pin_required",children:" · required"}):null]});const n=t.state==="unknown"?"not loaded":e.side==="out"?e.outputs_final?"not in the run's output":"no output until the run ends":"no value";return s.jsx("span",{className:"ap_pin_muted",title:n,children:"—"})}function GP(e){const{pin:t}=e,n=t.typed?t.type:"untyped",r=HP(t);return s.jsxs("li",{className:`ap_pin ap_pin_${t.state} ap_copyable`,"data-pin-id":t.id,"data-pin-state":t.state,children:[s.jsxs("span",{className:"ap_pin_head",title:t.description||void 0,children:[s.jsx(y1,{type:t.type,filled:t.state==="value"}),s.jsx("span",{className:"ap_pin_name",children:t.label}),s.jsx("span",{className:"ap_pin_type mono",children:n}),r!==null?s.jsx(Ig,{text:r,label:t.state==="value"?t.label:`${t.label} flow default`,on_copy:e.on_copy}):null]}),s.jsx("div",{className:"ap_pin_value",children:s.jsx(VP,{pin:t,side:e.side,outputs_final:e.outputs_final})})]})}function V0(e){const t=e.also||[],n=e.outputs_final===!0;return s.jsxs("div",{className:"ap_pins","aria-label":e.label,children:[e.pins.length?s.jsx("ul",{className:"ap_pin_list",children:e.pins.map(r=>s.jsx(GP,{pin:r,side:e.side,outputs_final:n,on_copy:e.on_copy},r.id))}):s.jsx("p",{className:"ap_pin_muted ap_pins_empty",children:e.empty_text||"no pins"}),t.length?s.jsxs("div",{className:"ap_pins_also",children:[s.jsx("div",{className:"ap_pins_also_label",children:e.also_label||"also on the wire"}),s.jsx("ul",{className:"ap_pin_list",children:t.map(([r,i])=>s.jsxs("li",{className:"ap_pin ap_pin_also ap_copyable","data-pin-id":r,"data-pin-state":"also",children:[s.jsxs("span",{className:"ap_pin_head",children:[s.jsx(y1,{type:"any",filled:!0}),s.jsx("span",{className:"ap_pin_name",children:r}),s.jsx("span",{className:"ap_pin_type mono",children:"not a pin"}),i!==void 0?s.jsx(Ig,{text:il(i),label:r,on_copy:e.on_copy}):null]}),s.jsx("div",{className:"ap_pin_value",children:s.jsx(rm,{value:i})})]},r))})]}):null]})}const iv=5*6e4;function KP(e){const t=new Map,n=new Map;for(const r of e||[]){const i=String((r==null?void 0:r.run_id)||"").trim();i&&t.set(i,r)}for(const r of t.values()){const i=String((r==null?void 0:r.parent_run_id)||"").trim();if(!i)continue;const o=n.get(i)||[];o.push(r),n.set(i,o)}return{by_id:t,children_of:n}}function _x(e,t){const{by_id:n,children_of:r}=KP(e);return{by_id:n,children_of:r,now_ms:Date.now(),...t||{}}}function w1(e,t){var i;const n=(i=t.details)==null?void 0:i.get(String((e==null?void 0:e.run_id)||"")),r=(n==null?void 0:n.waiting)??(e==null?void 0:e.waiting);return r&&typeof r=="object"?r:null}function JP(e,t){return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function YP(e,t,n){var o,u;const r=(o=t.details)==null?void 0:o.get(String((e==null?void 0:e.run_id)||""));return(e==null?void 0:e.paused)===!0||(r==null?void 0:r.paused)===!0||String((n==null?void 0:n.wait_key)||"").startsWith("pause:")?!0:String(((u=n==null?void 0:n.details)==null?void 0:u.kind)||"").trim().toLowerCase()==="pause"}function G0(e){return e?String(e.prompt||"").trim()?!0:Array.isArray(e.choices)&&e.choices.length>0:!1}function ov(e){return Ht((e==null?void 0:e.updated_at)||(e==null?void 0:e.created_at)||"")}function Qs(e){const t=Math.max(0,Math.floor(e/1e3)),n=Math.floor(t/60),r=Math.floor(n/60),i=Math.floor(r/24);return i>0?`${i}d ${r%24}h`:r>0?`${r}h ${n%60}m`:n>0?`${n}m`:`${t}s`}function XP(e,t){return e===null?"":Qs(t-e)}function K0(e,t){if(e===null)return"";const n=new Date(e).toISOString().slice(11,16),r=e-t;return r>0?`${n} UTC (in ${em(r)})`:`${n} UTC (due)`}function Id(e,t){const n=String(e||"").replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const ZP=6e4;function QP(e,t){var u;const n=w1(e,t),r=String(((u=n==null?void 0:n.details)==null?void 0:u.sub_run_id)||"").trim();if(r&&t.by_id.has(r))return t.by_id.get(r)||null;const o=(t.children_of.get(String((e==null?void 0:e.run_id)||""))||[]).filter(l=>!ds(String((l==null?void 0:l.status)||"")));return o.length?(o.sort((l,d)=>(ov(d)??0)-(ov(l)??0)),o[0]):null}function Og(e){const t=String(e||"").trim();if(!t)return"";const n=t.match(/^visual_react_agent_(.+)$/);if(n){const l=n[1],d=l.match(/^(.+?)_(\d+)_(\d+)_(\d+)_(.+)$/);if(d){const h=d[1];let m=d[5];return m.startsWith(`${h}_`)?m=m.slice(h.length+1):m=m.replace(/^[^_]+_/,""),m||l}return l}const r=t.indexOf("@"),i=t.indexOf(":",r<0?0:r),o=r>=0?t.slice(0,r):i>=0?t.slice(0,i):t,u=i>=0?t.slice(i+1):"";return u&&!/^[0-9a-f]{8,}$/i.test(u)?u:o||ti(t)}function e5(e){const t=String(e||"").trim(),n=ti(t);return n&&n!==t?`${n} — ${t}`:t}function v1(e,t){var r,i;const n=String((e==null?void 0:e.run_id)||"");return String(((i=(r=t.details)==null?void 0:r.get(n))==null?void 0:i.current_node)||(e==null?void 0:e.current_node)||"").trim()}function ti(e){const t=String(e||"").trim();if(!t)return"";const n=t.includes("@")?t.split(":")[0]:t,[r,i]=n.split("@"),o=String(r||"").split(".").pop()||r||"";return i?`${o} ${i}`:o}function Yd(e){const t=String(e||"").trim();return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function Xd(e,t,n=0){const r=t5(e,t,n);return{...r,brief:r.brief||r.text}}function t5(e,t,n=0){var N,$,E,S,P,D,R,I,W,G,K;const r=t.now_ms,i=typeof t.stall_after_ms=="number"?t.stall_after_ms:iv,o=String((e==null?void 0:e.run_id)||"").trim(),u=String((e==null?void 0:e.status)||"").trim().toLowerCase(),l=w1(e,t),d=JP(e,l),h=ov(e),m=String((e==null?void 0:e.role)||"").trim(),_={verb:"waiting",lane:"waiting_on",object:"",actor:"unknown",actor_run_id:"",action:"inspect",since_ms:h,stale_ms:null,stalled:!1,open_step:"",unresolved:!1,text:"",brief:""},g=XP(h,r),y=g?` · ${g}`:"";if(ds(u)){const H=tm(e),M=String((e==null?void 0:e.error)||"").trim(),A=(N=t.details)==null?void 0:N.get(o),O=Ht((e==null?void 0:e.created_at)||""),L=Ht((e==null?void 0:e.updated_at)||""),V=O!==null&&L!==null&&L>=O?Qs(L-O):"";let J=H;H==="failed"?J=M?`failed: ${Id(M,120)}`:"failed":H==="completed"?J=V?`completed in ${V}`:"completed":H==="stopped"?J="stopped before the turn finished":H==="cancelled"&&(J="cancelled");const U=String((A==null?void 0:A.error)||"").trim();return H==="failed"&&!M&&U&&(J=`failed: ${Id(U,120)}`),{..._,verb:"done",lane:"done",object:J,actor:"none",action:"open_run",text:J}}if(m==="controller"){const H=($=t.automations)==null?void 0:$.get(String((e==null?void 0:e.automation_id)||o)),M=Ht((l==null?void 0:l.until)||""),A=(H==null?void 0:H.next_fire_ms)??M,O=[];H!=null&&H.current&&!ds(H.current.status)?O.push(`run #${H.current.index} in progress`):d==="subworkflow"&&O.push("a run is in progress"),(H==null?void 0:H.status)==="paused"?O.push("paused: scheduled runs are skipped"):A!==null?O.push(`next run in ${em(Math.max(0,A-r))}`):(H==null?void 0:H.status)==="completed"||(H==null?void 0:H.status)==="failed"?O.push(`${H.status}: no next run`):H!=null&&H.event_driven?O.push("listening"):((E=H==null?void 0:H.trigger)==null?void 0:E.source_id)==="manual"?O.push("runs when someone presses Run now"):O.push("next run not scheduled"),H!=null&&H.last&&O.push(`last #${H.last.index} ${H.last.status}`),H&&O.push(`${H.occurrence_count} turn${H.occurrence_count===1?"":"s"}`);const L=O.join(" · ");return{..._,verb:"scheduled",lane:"scheduled",object:L,actor:"clock",action:"open_run",text:L}}if((e==null?void 0:e.is_draft)===!0){const H="draft · not started";return{..._,verb:"scheduled",lane:"scheduled",object:H,actor:"none",action:"open_run",text:H}}if(u==="running"){const H=((S=t.pulses)==null?void 0:S.get(o))||null,M=H&&H.ended_ms===null&&H.started_ms!==null?H:null,A=Math.max(h??0,(H==null?void 0:H.ended_ms)??0,(H==null?void 0:H.started_ms)??0)||null,O=A?Math.max(0,r-A):null,L=O!==null&&O>i,V=M?`${M.effect||M.node_id||"step"} open ${Qs(r-M.started_ms)}`:"",J=String(((D=(P=t.details)==null?void 0:P.get(o))==null?void 0:D.current_node)||(e==null?void 0:e.current_node)||"").trim(),U=["running"];return J&&U.push(`step ${J}`),V?U.push(V):O!==null&&U.push(`last step ${Qs(O)} ago`),L&&U.push("no progress"),{..._,verb:"running",lane:"working",object:V||J||"",actor:"runtime",action:"open_run",stale_ms:O,stalled:L,open_step:V,text:U.join(" · ")}}if(u!=="waiting"){if((e==null?void 0:e.is_scheduled)===!0){const M=e!=null&&e.schedule_interval?`scheduled · every ${e.schedule_interval}`:"scheduled";return{..._,verb:"scheduled",lane:"scheduled",object:M,actor:"clock",action:"open_run",text:M}}const H=u?`${u}${y}`:"state unknown";return{..._,object:H,text:H,action:"inspect"}}if(YP(e,t,l)){const H=`paused${y} · resume when ready`;return{..._,verb:"paused",lane:"needs_you",object:"paused",actor:"you",action:"resume",text:H}}const b=sf(l);if(b.length){const H=b.map(O=>String((O==null?void 0:O.name)||"tool").trim()).filter(Boolean),M=`${H.slice(0,3).join(", ")}${H.length>3?` +${H.length-3}`:""}`,A=`needs your approval: ${M||"tool call"}${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:`approval: ${M}`,actor:"you",action:"approve",text:A}}if(d==="user"){if(G0(l)){const A=Id(String((l==null?void 0:l.prompt)||""),80),O=A?`asks: ${A}${y}`:`asks a question${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:A||"a question",actor:"you",action:"answer",text:O,brief:`asks a question${y}`}}if(((R=t.details)==null?void 0:R.has(o))===!0){const A=`waits for your answer${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:"your answer",actor:"you",action:"answer",text:A}}const M=`needs you: question, approval or pause${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:"question, approval or pause",actor:"you",action:"open_run",unresolved:!0,text:M}}if(d==="subworkflow"){const H=n<4?QP(e,t):null;if(!H){const L=String(((I=l==null?void 0:l.details)==null?void 0:I.sub_run_id)||"").trim(),V=L?(W=t.fates)==null?void 0:W.get(L):void 0,U=v1(e,t)||V&&Og(V.workflow_id)||Yd(L);if(V&&V.status==="missing"){const z=`stuck: subrun ${U} no longer exists${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:`subrun ${U} (missing)`,actor:"you",action:"open_run",stuck:!0,stuck_facts:{subrun:U,status:"missing",ended_ms:null},text:z}}if(V&&ds(V.status)){const z=Ht(V.updated_at),ne=z!==null?Math.max(0,t.now_ms-z):null;if(ne!==null&&ne<=ZP){const Me=`its subrun ${U} ${V.status} ${Qs(ne)} ago · resuming${y}`;return{..._,verb:"running",lane:"working",object:`subrun ${U}`,actor:"runtime",action:"open_run",text:Me}}const se=ne!==null?` ${Qs(ne)} ago`:"",de=V.status==="cancelled"?"was cancelled":V.status==="failed"?"failed":`ended ${V.status}`,be=`stuck: subrun ${U} ${de}${se}, this run was not resumed${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:`subrun ${U} (${V.status})`,actor:"you",action:"open_run",stuck:!0,stuck_facts:{subrun:U,status:V.status,ended_ms:ne},text:be}}if(L){const z=`waiting for its subrun ${U} to finish${y}`;return{..._,object:`subrun ${U}`,actor:"run",actor_run_id:L,action:"open_subrun",text:z}}const te=`waiting for a subrun to finish${y}`;return{..._,object:"a subrun",actor:"run",action:"open_run",text:te}}const M=Xd(H,t,n+1),A=ti(String(H.workflow_id||""))||Yd(String(H.run_id||""));if(M.verb==="running"){const L=[`running subrun ${A}`];return M.open_step?L.push(M.open_step):M.stale_ms!==null&&L.push(`last step ${Qs(M.stale_ms)} ago`),M.stalled&&L.push("no progress"),{..._,verb:"running",lane:"working",object:`subrun ${A}`,actor:"run",actor_run_id:String(H.run_id||""),action:"open_subrun",stale_ms:M.stale_ms,stalled:M.stalled,open_step:M.open_step,text:L.join(" · ")}}const O=`waiting for subrun ${A}: ${M.brief||M.text}`;return{..._,verb:"waiting",lane:"waiting_on",object:`subrun ${A}`,actor:"run",actor_run_id:String(H.run_id||""),action:"open_subrun",unresolved:M.unresolved,text:O}}if(d==="until"){const H=Ht((l==null?void 0:l.until)||""),M=H!==null?`sleeps until ${K0(H,r)}`:`sleeps until an unknown time${y}`,A=(e==null?void 0:e.is_scheduled)===!0;return{..._,...A?{verb:"scheduled",lane:"scheduled"}:{},object:"the clock",actor:"clock",action:"open_run",text:M}}if(d==="event"){if(G0(l)){const L=Id(String((l==null?void 0:l.prompt)||""),80),V=L?`asks: ${L}${y}`:`asks a question${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:L||"a question",actor:"you",action:"answer",text:V,brief:`asks a question${y}`}}const H=Ht((l==null?void 0:l.until)||""),M=String(((G=l==null?void 0:l.details)==null?void 0:G.event)||((K=l==null?void 0:l.details)==null?void 0:K.name)||"").trim(),A=M?`event ${M}`:"an event",O=H!==null?`waiting for ${A} until ${K0(H,r)}`:`waiting for ${A}${y}`;return{..._,object:A,actor:"external",action:"open_run",text:O}}if(d==="job"){const H=`waiting for a delegated tool job${y}`;return{..._,object:"a delegated tool job",actor:"runtime",action:"open_run",text:H}}const k=String((l==null?void 0:l.wait_key)||"").trim(),x=`waiting, reason unknown${k?` (${k})`:""}${y} · inspect`;return{..._,object:"unknown",actor:"unknown",action:"inspect",text:x}}function x1(e,t,n,r){if(String((e==null?void 0:e.role)||"").trim()==="controller")return(r==null?void 0:r.status)==="paused"?"paused":r!=null&&r.event_driven?"listening":"scheduled";if(t.stuck)return"stuck";const i=tm({status:e==null?void 0:e.status,paused:(e==null?void 0:e.paused)===!0||t.verb==="paused",stop_reason:n??null});return t.verb==="running"&&i==="waiting"?"running":i}const Gy={automation:"⟳",agent:"◉",run:"▭"};function b1(e,t){var d;const n=String((e==null?void 0:e.role)||"").trim(),r=String((e==null?void 0:e.session_kind)||"").trim(),i=String((e==null?void 0:e.automation_id)||"").trim(),o=i?(d=t.automations)==null?void 0:d.get(i):void 0,u=ti(String((e==null?void 0:e.workflow_id)||""));if(n==="controller"||n==="occurrence"||n==="descendant"||n==="discussion"||r==="automation"){const h=[];return n==="occurrence"&&typeof(e==null?void 0:e.occurrence_index)=="number"?h.push(`run #${e.occurrence_index}`):n==="descendant"&&typeof(e==null?void 0:e.occurrence_index)=="number"?h.push(`run #${e.occurrence_index} · subrun`):n==="discussion"&&h.push("discussion"),u&&n!=="controller"&&!(o!=null&&o.title)&&h.push(u),n==="controller"&&o&&h.push(o.cadence),{kind:"automation",glyph:Gy.automation,label:(o==null?void 0:o.title)||"",secondary:h.join(" · "),automation_id:i,id_hint:i}}const l=String((e==null?void 0:e.session_id)||"").trim();if(l){const h=[u,String((e==null?void 0:e.parent_run_id)||"").trim()?"subrun":""].filter(Boolean);return{kind:"agent",glyph:Gy.agent,label:"session",secondary:h.join(" · "),automation_id:"",id_hint:l}}return{kind:"run",glyph:Gy.run,label:"",secondary:u,automation_id:"",id_hint:""}}function k1(e,t,n){var _,g,y;const r=String((e==null?void 0:e.automation_id)||"").trim(),i=r?(_=t.automations)==null?void 0:_.get(r):void 0;if(i!=null&&i.title)return{text:i.title,source:"automation",untitled:!1};const o=String(((g=e==null?void 0:e.brief)==null?void 0:g.title)||"").trim();if(o)return{text:o,source:"brief",untitled:!1};const u=String(((y=e==null?void 0:e.brief)==null?void 0:y.task_excerpt)||"").trim();if(u)return{text:Id(u,80),source:"brief",untitled:!1};const l=String((e==null?void 0:e.session_kind)||"").trim(),d=String((e==null?void 0:e.role)||"").trim();return!(!!r||l==="automation"||d==="occurrence"||d==="descendant"||d==="controller")&&(n!=null&&n.excerpt)?{text:Id(n.excerpt,80),source:"excerpt",untitled:!1}:{text:ti(String((e==null?void 0:e.workflow_id)||""))||"(workflow?)",source:"workflow",untitled:!0}}function px(e,t=""){var r;if(!e||typeof e!="object")return"";const n=String((e==null?void 0:e.source_id)||"").trim();if(n==="schedule"){if(t)return t;const i=String(((r=e==null?void 0:e.config)==null?void 0:r.every)||"").trim();return i?`every ${i}`:"scheduled"}return n?YI(e):""}function Am(e){var k,x,N,$,E,S,P,D;const t=e!=null&&e.summary&&typeof e.summary=="object"?e.summary:null,n=e!=null&&e.definition&&typeof e.definition=="object"?e.definition:null,r=String((t==null?void 0:t.automation_id)||(e==null?void 0:e.automation_id)||"").trim();if(!r)return null;const i=(k=n==null?void 0:n.target)!=null&&k.input_data&&typeof n.target.input_data=="object"?n.target.input_data:{},o=t!=null&&t.last_occurrence&&typeof t.last_occurrence=="object"?t.last_occurrence:null,u=t!=null&&t.current_occurrence&&typeof t.current_occurrence=="object"?t.current_occurrence:null,l=Array.isArray(i==null?void 0:i.tools)?i.tools.map(R=>String(R)).filter(Boolean):[],d=Array.isArray((x=n==null?void 0:n.notify)==null?void 0:x.channels)?n.notify.channels.map(R=>String(R)):[],h=Array.isArray(t==null?void 0:t.capabilities)?t.capabilities.map(R=>String(R)):[],m=i!=null&&i._runtime&&typeof i._runtime=="object"?i._runtime:{},_=R=>Array.isArray(R)?R.map(I=>String(I)).filter(Boolean):null,g=t!=null&&t.trigger&&typeof t.trigger=="object"?t.trigger:n!=null&&n.trigger&&typeof n.trigger=="object"?n.trigger:null,y=g?{source_id:String(g.source_id||""),source_version:Number(g.source_version||0),config:g.config&&typeof g.config=="object"?g.config:{}}:null,b=(y==null?void 0:y.source_id)==="schedule"?String((t==null?void 0:t.schedule_rule_text)||"").trim():"";return{automation_id:r,title:String((t==null?void 0:t.title)||(n==null?void 0:n.title)||"").trim(),status:String((t==null?void 0:t.status)||"").trim(),cadence:String((t==null?void 0:t.trigger_text)||"").trim()||px(y,b),trigger_text:String((t==null?void 0:t.trigger_text)||"").trim(),trigger:y,event_driven:cc(y),time_zone:String((t==null?void 0:t.time_zone)||"").trim(),next_fire_ms:Ht((t==null?void 0:t.next_run_at)||(t==null?void 0:t.next_fire_at)||""),last:o?{index:Number(o.index||0),status:String(o.status||""),fired_ms:Ht(o.fired_at||""),finished_ms:Ht(o.finished_at||"")}:null,occurrence_count:typeof(t==null?void 0:t.occurrence_count)=="number"?t.occurrence_count:0,current:u?{index:Number(u.index||0),run_id:String(u.run_id||""),status:String(u.status||"")}:null,context_mode:String((t==null?void 0:t.context_mode)||((N=n==null?void 0:n.context)==null?void 0:N.mode)||"").trim(),growing_max_tokens:typeof(t==null?void 0:t.growing_max_tokens)=="number"?t.growing_max_tokens:null,model:String((i==null?void 0:i.model)||"").trim(),provider:String((i==null?void 0:i.provider)||"").trim(),tools:l,max_iterations:typeof(i==null?void 0:i.max_iterations)=="number"?i.max_iterations:null,tool_approval:String((($=n==null?void 0:n.policy)==null?void 0:$.tool_approval)||"").trim(),allowed_tools:_(m.allowed_tools),untrusted_input_tools:_((E=n==null?void 0:n.policy)==null?void 0:E.untrusted_input_tools),email_allowed_recipients:_((S=n==null?void 0:n.policy)==null?void 0:S.email_allowed_recipients),workspace_access_mode:String((i==null?void 0:i.workspace_access_mode)||"").trim(),notify_channels:d,task:String((i==null?void 0:i.prompt)||((P=i==null?void 0:i.context)==null?void 0:P.task)||"").trim(),workspace_root:String((t==null?void 0:t.workspace_root)||(n==null?void 0:n.workspace_root)||"").trim(),can_revise:h.includes("revise"),capabilities:h,legacy:(t==null?void 0:t.legacy)===!0,schedule_rule_text:b,next_run_local:String((t==null?void 0:t.next_run_local)||"").trim(),paused_reason:String((t==null?void 0:t.paused_reason)||"").trim(),context_used_tokens:typeof(t==null?void 0:t.context_used_tokens)=="number"&&Number.isFinite(t.context_used_tokens)&&t.context_used_tokens>=0?t.context_used_tokens:null,last_run_id:String((o==null?void 0:o.run_id)||"").trim(),last_excerpt:String((o==null?void 0:o.excerpt)||"").trim(),last_notification_text:String(((D=t==null?void 0:t.last_notification)==null?void 0:D.text)||"").trim()}}function n5(e,t,n){var i;const r=n!=null&&n.record&&typeof n.record=="object"?n.record:n;return!r||typeof r!="object"?null:{run_id:String(e||"").trim(),ledger_len:Number(t||0),node_id:String(r.node_id||"").trim(),effect:String(((i=r==null?void 0:r.effect)==null?void 0:i.type)||"").trim(),status:String(r.status||"").trim(),started_ms:Ht(r.started_at||""),ended_ms:Ht(r.ended_at||"")}}function Mn(e){return typeof e=="string"?e:e==null?"":String(e)}function J0(e,t){const n=Mn(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function j1(e){const t=Mn(e==null?void 0:e.targetHandle),n=Mn(e==null?void 0:e.sourceHandle);return!!(t==="exec-in"||n==="exec-out"||t.includes("exec")||n.includes("exec"))}function S1(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{};return Mn((t==null?void 0:t.nodeType)||(e==null?void 0:e.type)||"").trim()}function N1(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{},n=(t==null?void 0:t.subflowId)||(t==null?void 0:t.flowId),r=Mn(n).trim();if(!r)return"";if(r.includes(":")){const i=r.split(":",2);if(i.length===2&&i[1])return i[1].trim()}return r}function s5(e){const t=Mn(e==null?void 0:e.entryNode).trim();if(t)return t;const n=Array.isArray(e==null?void 0:e.nodes)?e.nodes:[];for(const r of n)if(S1(r)==="on_flow_start"){const i=Mn(r==null?void 0:r.id).trim();if(i)return i}return""}function Ky(e){const t=e!=null&&e.position&&typeof e.position=="object"?e.position:{},n=typeof t.x=="number"?t.x:0,r=typeof t.y=="number"?t.y:0;return{x:n,y:r}}function bh(e,t){const n=Mn(e).trim(),r=Mn(t).trim();return r?n?`${n}::${r}`:r:""}function r5(e){const t=e.root&&typeof e.root=="object"?e.root:{};if(!e.expand_subflows)return t;const n=[],r=[],i=new Set,o=(u,l,d,h)=>{if(!u||typeof u!="object"||n.length>=e.max_nodes||r.length>=e.max_edges)return;const m=Array.isArray(u.nodes)?u.nodes:[],_=Array.isArray(u.edges)?u.edges:[];for(const g of m){const y=Mn(g==null?void 0:g.id).trim();if(!y)continue;const b=bh(l,y);if(!b||i.has(b))continue;const k=Ky(g),x={...g,id:b,position:{x:k.x+d.x,y:k.y+d.y}};if(n.push(x),i.add(b),n.length>=e.max_nodes)break}for(const g of _){if(!j1(g))continue;const y=Mn(g==null?void 0:g.source).trim(),b=Mn(g==null?void 0:g.target).trim();if(!y||!b)continue;const k=bh(l,y),x=bh(l,b);if(!k||!x)continue;const N=Mn(g==null?void 0:g.id).trim(),$=N?`${k}->${x}::${N}`:`${k}->${x}`;if(r.push({...g,id:$,source:k,target:x}),r.length>=e.max_edges)break}if(!(h>=e.max_depth))for(const g of m){if(n.length>=e.max_nodes||r.length>=e.max_edges)return;if(S1(g)!=="subflow")continue;const y=N1(g);if(!y)continue;const b=e.flow_by_id[y];if(!b||typeof b!="object")continue;const k=bh(l,Mn(g==null?void 0:g.id));if(!k)continue;const x=s5(b);if(!x)continue;const $=(Array.isArray(b.nodes)?b.nodes:[]).find(W=>Mn(W==null?void 0:W.id).trim()===x)||null;if(!$)continue;const E=Ky(g),S=Ky($),R={x:E.x+d.x+240-S.x,y:E.y+d.y+0-S.y},I=bh(k,x);r.push({id:`${k}=>${I}`,source:k,target:I,sourceHandle:"exec-out",targetHandle:"exec-in"}),o(b,k,R,h+1)}};return o(t,"",{x:0,y:0},0),{...t,id:Mn(t.id),nodes:n,edges:r}}function i5(e){const t=Mn(e).trim().toLowerCase();return t?!!(t.startsWith("literal")||t.includes("literal")||t==="concat"||t==="join"||t==="cast"||t==="parse_json"||t==="stringify_json"||t==="break_object"||t==="get_property"||t==="set_property"||t.includes("get_property")||t.includes("set_property")||t==="get_variable"||t==="set_variable"||t.includes("get_variable")||t.includes("set_variable")||t==="json_schema"):!1}function o5(e){const t=e.nodes.filter(o=>e.keep_id(o.id)),n=new Set(t.map(o=>o.id)),r={};for(const o of e.edges)r[o.source]||(r[o.source]=[]),r[o.source].push(o.target);const i=new Map;for(const o of t){const u=new Set,l=(r[o.id]||[]).slice();for(;l.length;){const d=l.pop();if(!d||u.has(d))continue;if(u.add(d),n.has(d)){const m=`${o.id}->${d}`;i.has(m)||i.set(m,{id:m,source:o.id,target:d});continue}const h=r[d]||[];for(const m of h)u.has(m)||l.push(m);if(i.size>=e.max_edges)break}if(i.size>=e.max_edges)break}return{nodes:t,edges:Array.from(i.values())}}function Y0(e,t){const i=Math.max(t.w*8,160),o=Math.max(t.h*8,120),u=Math.max(160,Math.min(i,e.w)),l=Math.max(120,Math.min(o,e.h));return{x:e.x,y:e.y,w:u,h:l}}const a5=new Set(["completed","failed","cancelled","stopped"]),$1={running:"here",waiting:"waiting here",failed:"failed here",done:"here",none:"here"},C1={running:"running",waiting:"waiting",failed:"failed",done:"done",none:"not visited"},E1={user:"waiting for you",subworkflow:"waiting for its subrun",until:"waiting for the clock",event:"waiting for an event",job:"waiting for a tool job"};function A1(e){const t=(e==null?void 0:e.waits.find(n=>n.open))||null;return t?E1[t.reason]||`waiting (${t.reason||"reason not recorded"})`:"waiting, reason not recorded"}function Zc(e){return e==="running"?3:e==="waiting"?2:0}function X0(e){if(typeof e!="number"||!Number.isFinite(e))return"";const t=new Date(e);return[t.getHours(),t.getMinutes(),t.getSeconds()].map(n=>String(n).padStart(2,"0")).join(":")}const Z0=typeof window>"u"?p.useEffect:p.useLayoutEffect;function l5(e){const t=e.status;if(t==="none")return null;let n;return t==="running"?n=s.jsx("circle",{className:"flow_badge_spin",r:4,fill:"none",strokeDasharray:"18 8"}):t==="waiting"?n=s.jsx("path",{d:"M -2 -3.5 V 3.5 M 2 -3.5 V 3.5"}):t==="failed"?n=s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M 0 -4 V 1"}),s.jsx("circle",{className:"flow_badge_dot",cx:0,cy:3.6,r:.9})]}):n=s.jsx("path",{d:"M -3.5 0.2 L -1 2.8 L 3.6 -2.6"}),s.jsxs(s.Fragment,{children:[s.jsx("circle",{className:"flow_badge_bg",r:8.5}),n]})}function Tp(e){const[t,n]=p.useState("idle"),r=p.useRef(null);return p.useEffect(()=>()=>{r.current!==null&&window.clearTimeout(r.current)},[]),s.jsx("button",{type:"button",className:e.className||"btn flow_copy_btn",title:e.title,"aria-label":e.title,disabled:e.disabled,"data-copy-state":t,onClick:async i=>{i.stopPropagation();const o=await Em(e.get_text());n(o?"copied":"failed"),r.current!==null&&window.clearTimeout(r.current),r.current=window.setTimeout(()=>n("idle"),1500)},children:s.jsx("span",{"aria-live":"polite",children:t==="copied"?e.copied??"Copied":t==="failed"?e.failed??UN:e.label})})}function Q0(e){const[t,n]=p.useState(!1),{shown:r,clamped:i}=g1(e.text);return s.jsxs("span",{className:"flow_facts_text",children:[s.jsx("span",{children:t||!i?e.text:r}),i?s.jsx("button",{type:"button",className:"flow_link_btn","aria-expanded":t,onClick:()=>n(o=>!o),children:t?"show less":`show all (${e.text.length.toLocaleString("en-US")} chars)`}):null]})}function c5(e){const[t,n]=p.useState(!1),r=yP(e.value);return s.jsxs("span",{className:"flow_facts_text",children:[s.jsx("code",{className:"flow_facts_summary",children:e.summary}),r?s.jsx("button",{type:"button",className:"flow_link_btn","aria-expanded":t,onClick:()=>n(i=>!i),children:t?"show less":"show all"}):null,r&&t?s.jsx("pre",{className:"flow_facts_json",children:JSON.stringify(e.value,null,2)}):null]})}function u5(e){const{node:t,facts:n,status:r}=e,i=r==="waiting"?A1(n):C1[r],o=n?[`${n.visits.toLocaleString("en-US")} visit${n.visits===1?"":"s"}`,n.first_ms!==null?`first ${X0(n.first_ms)}`:"",n.last_ms!==null?`last ${X0(n.last_ms)}`:"",`${vu(n.duration_ms)} in steps`].filter(Boolean):[],u=(n==null?void 0:n.llm)||null;return s.jsxs("div",{className:"flow_facts",children:[s.jsxs("div",{className:"flow_facts_head",children:[s.jsx("span",{className:"flow_facts_title",children:t.label}),s.jsx("span",{className:"flow_facts_type",children:t.type})]}),s.jsxs("div",{className:"flow_facts_status",children:[s.jsx("span",{className:"flow_status_chip","data-run-status":r,children:i}),e.here?s.jsx("span",{className:"flow_facts_here",children:$1[r]}):null]}),n?s.jsxs("dl",{className:"flow_facts_rows",children:[s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Visits"}),s.jsx("dd",{children:o.join(" · ")})]}),u?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"LLM"}),s.jsx("dd",{children:[u.model||"model not recorded",u.provider||"provider not recorded",`${u.calls.toLocaleString("en-US")} call${u.calls===1?"":"s"}`,u.tokens?`${u.tokens.in.toLocaleString("en-US")} in · ${u.tokens.out.toLocaleString("en-US")} out tokens`:""].filter(Boolean).join(" · ")})]}):null,n.tools.length?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Tools"}),s.jsx("dd",{children:s.jsxs("table",{className:"flow_facts_tools",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{scope:"col",children:"tool"}),s.jsx("th",{scope:"col",children:"calls"}),s.jsx("th",{scope:"col",children:"failed"})]})}),s.jsx("tbody",{children:n.tools.map(l=>s.jsxs("tr",{"data-failed":l.failed>0?"true":void 0,children:[s.jsx("td",{children:l.name}),s.jsx("td",{children:l.calls}),s.jsx("td",{children:l.failed})]},l.name))})]})})]}):null,n.waits.length?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Waits"}),s.jsx("dd",{children:s.jsx("ul",{className:"flow_facts_list",children:n.waits.map((l,d)=>s.jsxs("li",{children:[s.jsx("span",{children:E1[l.reason]||l.reason||"reason not recorded"}),l.open?s.jsx("span",{className:"flow_facts_open",children:" · now"}):null,l.prompt?s.jsxs(s.Fragment,{children:[" · ",s.jsx(Q0,{text:l.prompt})]}):null]},`${l.reason}|${l.wait_key}|${d}`))})})]}):null,n.subruns.length?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Subruns"}),s.jsx("dd",{className:"flow_facts_subruns",children:n.subruns.map(l=>s.jsx("button",{type:"button",className:"flow_link_btn mono",title:e.on_open_run?`Open run ${l}`:`${l} (opening runs is not wired here)`,disabled:!e.on_open_run,onClick:()=>{var d;return(d=e.on_open_run)==null?void 0:d.call(e,l)},children:Yd(l)},l))})]}):null,n.last_result_summary?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Result"}),s.jsx("dd",{children:s.jsx(c5,{summary:n.last_result_summary,value:n.last_result})})]}):null,n.last_error?s.jsxs("div",{className:"flow_facts_row flow_facts_error",children:[s.jsx("dt",{children:"Error"}),s.jsx("dd",{children:s.jsx(Q0,{text:n.last_error})})]}):null]}):s.jsx("p",{className:"flow_facts_none",children:e.finished?"Not visited in this run.":"Not visited yet."}),s.jsxs("div",{className:"flow_facts_actions",children:[s.jsx(Tp,{label:"Copy facts (JSON)",disabled:!n,get_text:()=>n?SP(n):""}),s.jsx(Tp,{label:"Copy records (JSONL)",disabled:!n||!n.records.length,get_text:()=>n?NP(n):""}),n!=null&&n.context?s.jsx(Tp,{label:"Copy context",get_text:()=>$P(n)}):null]})]})}function d5(e){var gt;const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=e.flow,r=Mn(e.active_node_id),i=e.recent_nodes||{},o=e.visited_nodes||{},u=e.highlight_path===!0,l=typeof e.vertical_compact=="number"?Math.max(.4,Math.min(1,e.vertical_compact)):.78,{nodes:d,edges:h,bounds:m}=p.useMemo(()=>{const re=r5({root:n||{},flow_by_id:e.flow_by_id||{},expand_subflows:e.expand_subflows===!0,max_depth:3,max_nodes:700,max_edges:900}),fe=Array.isArray(re.nodes)?re.nodes:[],Ce=Array.isArray(re.edges)?re.edges:[];let Ie=[];for(const Be of fe){const Zt=Mn(Be==null?void 0:Be.id).trim();if(!Zt)continue;const Tt=Be!=null&&Be.position&&typeof Be.position=="object"?Be.position:{},Dn=typeof Tt.x=="number"?Tt.x:0,fn=typeof Tt.y=="number"?Tt.y:0,Xe=Be!=null&&Be.data&&typeof Be.data=="object"?Be.data:{},nn=Mn((Xe==null?void 0:Xe.label)||(Be==null?void 0:Be.label)||Zt)||Zt,cn=Mn((Xe==null?void 0:Xe.nodeType)||(Be==null?void 0:Be.type)||"unknown")||"unknown",Er=Mn((Xe==null?void 0:Xe.headerColor)||(Be==null?void 0:Be.headerColor)||"")||"",Cs=Xe!=null&&Xe.eventConfig&&typeof Xe.eventConfig=="object"?Xe.eventConfig:null,gs=Cs&&typeof Cs.schedule=="string"?Mn(Cs.schedule).trim():"",mr=Cs&&typeof Cs.recurrent=="boolean"?!!Cs.recurrent:void 0,we=cn==="subflow"?N1(Be):"",Nt=gs||mr!==void 0||we?{schedule:gs||void 0,recurrent:mr,subflow_id:we||void 0}:void 0;Ie.push({id:Zt,x:Dn,y:fn,label:nn,type:cn,color:Er,meta:Nt})}const We={};for(const Be of Ie)We[Be.id]=Be;let Ue=[];for(const Be of Ce){if(!j1(Be))continue;const Zt=Mn(Be==null?void 0:Be.source).trim(),Tt=Mn(Be==null?void 0:Be.target).trim();!Zt||!Tt||Ue.push({id:Mn((Be==null?void 0:Be.id)||`${Zt}->${Tt}`),source:Zt,target:Tt})}const et=new Set(Ie.map(Be=>Be.id));if(Ue=Ue.filter(Be=>et.has(Be.source)&&et.has(Be.target)),e.simplify===!0){const Zt=o5({nodes:Ie,edges:Ue,keep_id:Tt=>{if(r&&Tt===r)return!0;const Dn=We[Tt];if(!Dn)return!1;const fn=Mn(Dn.type).trim().toLowerCase();return fn==="on_flow_start"||fn==="on_flow_end"||fn==="subflow"?!0:!i5(fn)},max_edges:900});Ie=Zt.nodes,Ue=Zt.edges}if(e.prefer_vertical===!0&&Ie.length>=2){const Be=Ie.map(Xe=>Xe.x),Zt=Ie.map(Xe=>Xe.y),Tt=Math.max(...Be)-Math.min(...Be),Dn=Math.max(...Zt)-Math.min(...Zt);Tt>=Dn&&(Ie=Ie.map(Xe=>({...Xe,x:Xe.y,y:Xe.x})));const fn=Math.min(...Ie.map(Xe=>Xe.y));Ie=Ie.map(Xe=>({...Xe,y:fn+(Xe.y-fn)*l}))}const at={};for(const Be of Ie)at[Be.id]=Be;const vt=160,xt=56,Et=vt/2,zt=xt/2;let ot=0,Jt=0,wn=0,hn=0;Ie.length&&(ot=Math.min(...Ie.map(Be=>Be.x)),Jt=Math.min(...Ie.map(Be=>Be.y)),wn=Math.max(...Ie.map(Be=>Be.x+vt)),hn=Math.max(...Ie.map(Be=>Be.y+xt)));let sn=0;if(Ue.length){const Be=new Set(Ue.map(Zt=>`${Zt.source}->${Zt.target}`));for(const Zt of Ue){if(!Be.has(`${Zt.target}->${Zt.source}`))continue;const Tt=at[Zt.source],Dn=at[Zt.target];if(!Tt||!Dn)continue;const fn=Tt.x+Et,Xe=Tt.y+zt,nn=Dn.x+Et,cn=Dn.y+zt,Er=Math.max(1,Math.hypot(nn-fn,cn-Xe)),Cs=Math.max(28,Math.min(72,Er*.14)),gs=Math.min(200,Cs*3.5);gs>sn&&(sn=gs)}}const Vt=60+sn,rs={x:ot-Vt,y:Jt-Vt,w:wn-ot+Vt*2,h:hn-Jt+Vt*2,node_w:vt,node_h:xt};return{nodes:Ie,edges:Ue,bounds:rs}},[n,e.flow_by_id,e.expand_subflows,e.simplify,e.prefer_vertical,r,l]),_=p.useRef(null),[g,y]=p.useState(()=>({x:m.x,y:m.y,w:m.w,h:m.h})),b=p.useRef(g);b.current=g,p.useEffect(()=>{y({x:m.x,y:m.y,w:m.w,h:m.h})},[m.x,m.y,m.w,m.h]);const k=p.useRef(new Map),x=p.useRef(null),N=p.useMemo(()=>{const re=new Set;for(const fe of h)re.add(`${fe.source}->${fe.target}`);return re},[h]),[$,E]=p.useState(null),[S,P]=p.useState(null),D=p.useRef({}),R=p.useRef(null),I=p.useRef(null),W=p.useRef(null),G=p.useRef(!1),H=`flow_facts_${p.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,M=()=>{I.current!==null&&window.clearTimeout(I.current),I.current=null},A=re=>{const fe=D.current[re];if(!fe||typeof window>"u")return;const Ce=fe.getBoundingClientRect(),Ie=window.innerWidth,We=Math.min(400,Ie-16);let Ue=Ce.right+10,et=Ce.top;Ue+We>Ie-8&&(Ue=Ce.left-10-We),Ue<8&&(Ue=Math.min(Math.max(8,Ce.left),Math.max(8,Ie-We-8)),et=Ce.bottom+8),P(at=>at&&at.top===et&&at.left===Ue&&at.width===We?at:{top:et,left:Ue,width:We})},O=(re,fe)=>{M(),A(re),E({id:re,mode:fe})},L=re=>{M(),I.current=window.setTimeout(()=>E(fe=>fe&&fe.id===re&&fe.mode!=="pinned"?null:fe),200)},V=(re,fe)=>{if(M(),$&&$.id===re&&$.mode==="pinned"){E(null);return}A(re),E({id:re,mode:"pinned"}),fe&&window.setTimeout(()=>{var Ce;return(Ce=R.current)==null?void 0:Ce.focus()},0)};p.useEffect(()=>()=>M(),[]),Z0(()=>{$&&A($.id)},[$==null?void 0:$.id,g.x,g.y,g.w,g.h]);const J=()=>{const re=R.current;if(!re)return;const fe=re.offsetHeight,Ce=window.innerHeight;P(Ie=>{if(!Ie||Ie.top+fe<=Ce-8)return Ie;const We=Math.max(8,Ce-8-fe);return We===Ie.top?Ie:{...Ie,top:We}})};Z0(()=>{$&&S&&J()},[$==null?void 0:$.id,S==null?void 0:S.top,S==null?void 0:S.left,S==null?void 0:S.width]);const U=!!S;p.useEffect(()=>{const re=R.current;if(!$||!re||typeof ResizeObserver>"u")return;const fe=new ResizeObserver(()=>J());return fe.observe(re),()=>fe.disconnect()},[$==null?void 0:$.id,U]),p.useEffect(()=>{if(!$)return;const re=Ie=>{var We;Ie.key==="Escape"&&(E(null),$.mode!=="hover"&&(G.current=!0,(We=D.current[$.id])==null||We.focus(),G.current=!1))},fe=Ie=>{var Ue;const We=Ie.target;We&&((Ue=R.current)!=null&&Ue.contains(We))||We&&typeof We.closest=="function"&&We.closest("[data-flow-node]")||E(null)},Ce=()=>A($.id);return document.addEventListener("keydown",re,!0),document.addEventListener("pointerdown",fe,!0),window.addEventListener("resize",Ce),window.addEventListener("scroll",Ce,!0),()=>{document.removeEventListener("keydown",re,!0),document.removeEventListener("pointerdown",fe,!0),window.removeEventListener("resize",Ce),window.removeEventListener("scroll",Ce,!0)}},[$==null?void 0:$.id,$==null?void 0:$.mode]);const te=`${g.x} ${g.y} ${g.w} ${g.h}`,z={};for(const re of d)z[re.id]=re;const ne=re=>{let fe=Mn(re).trim();if(!fe)return"";if(z[fe])return fe;for(;fe.includes("::");)if(fe=fe.slice(0,Math.max(0,fe.lastIndexOf("::"))),z[fe])return fe;return""},se=ne(r),de={};for(const[re,fe]of Object.entries(i)){if(typeof fe!="number")continue;const Ce=ne(re);Ce&&(de[Ce]=Math.max(de[Ce]||0,fe))}const be={};if(u)for(const[re,fe]of Object.entries(o)){if(typeof fe!="number")continue;const Ce=ne(re);Ce&&(be[Ce]=typeof be[Ce]=="number"?Math.min(be[Ce],fe):fe)}const Me=Mn(e.schedule_next_in).trim(),je=Mn(e.schedule_interval).trim(),ae=e.node_last_ms&&typeof e.node_last_ms=="object"?e.node_last_ms:{},xe=re=>{try{const fe=new Date(re),Ce=String(fe.getHours()).padStart(2,"0"),Ie=String(fe.getMinutes()).padStart(2,"0");return`${Ce}:${Ie}`}catch{return""}},Ae=(re,fe)=>{var Ue,et;const Ce=Mn((Ue=re.meta)==null?void 0:Ue.schedule).trim();if(!(((et=re.meta)==null?void 0:et.recurrent)===!0))return fe&&Me?`next ${Me}`:Ce&&Ce.length<=12&&!Ce.includes("T")?`in ${Ce}`:"scheduled";const We=Ce||je;return We?fe&&Me?`${We} • next ${Me}`:`every ${We}`:fe&&Me?`next ${Me}`:"scheduled"},He=re=>{var vt;const fe=Mn((vt=re.meta)==null?void 0:vt.subflow_id).trim(),Ce=fe&&e.flow_by_id?e.flow_by_id[fe]:null,We=Mn(Ce==null?void 0:Ce.name).trim()||fe||re.label||re.id,Ue=typeof ae[re.id]=="number"?Number(ae[re.id]):null,et=Ue!==null?xe(Ue):"",at=et?`last ${et}`:"subflow";return{label:We,sub:at}},mt=(re,fe)=>{let Ce=re.label||re.id,Ie=re.type;if(re.type==="on_schedule")Ie=Ae(re,fe);else if(re.type==="subflow"){const We=He(re);Ce=We.label,Ie=We.sub}return{label:Ce,type:Ie}},nt=Mn(e.run_status).trim().toLowerCase(),rt=e.run_line||null,ze=Mn(e.run_id).trim(),Ve=!!(nt||rt||ze),ct=nt?a5.has(nt):rt?rt.verb==="done":!1,Qe=nt==="failed"||nt==="cancelled",Dt=e.node_facts||{},$e=e.node_status||jP(Dt),Le={};for(const[re,fe]of Object.entries($e)){const Ce=ne(re);if(!Ce)continue;let Ie=fe;ct&&(Ie==="running"||Ie==="waiting")&&(Ie=Qe?"failed":"done");const We=((gt=Dt[re])==null?void 0:gt.last_ms)??(typeof ae[re]=="number"?ae[re]:0),Ue=Le[Ce];if(!Ue){Le[Ce]={s:Ie,t:We};continue}const et=Zc(Ie),at=Zc(Ue.s);(et!==at?et>at:We!==Ue.t?We>Ue.t:Ie==="failed"&&Ue.s!=="failed")&&(Le[Ce]={s:Ie,t:We})}const ce=re=>{var fe;return((fe=Le[re])==null?void 0:fe.s)||"none"};let Q=se;if(!Q&&Ve){let re=null;for(const[fe,Ce]of Object.entries(Le))(ct?Qe&&Ce.s==="failed":Zc(Ce.s)>0)&&(!re||Zc(Ce.s)>Zc(re.s)||Zc(Ce.s)===Zc(re.s)&&Ce.t>re.t)&&(re={id:fe,...Ce});Q=re?re.id:""}const _e=re=>ct&&nt==="cancelled"&&re==="failed"?"cancelled here":$1[re],le=new Set;let Se=null,pe=null;for(const[re,fe]of Object.entries(Dt)){if(!fe||fe.visits<=0)continue;const Ce=ne(re);Ce&&le.add(Ce),fe.first_ms!==null&&(Se=Se===null?fe.first_ms:Math.min(Se,fe.first_ms)),fe.last_ms!==null&&(pe=pe===null?fe.last_ms:Math.max(pe,fe.last_ms))}for(const[re,fe]of Object.entries(o)){if(typeof fe!="number")continue;const Ce=ne(re);Ce&&le.add(Ce)}if(Se===null||pe===null){const re=Object.values(ae).filter(fe=>typeof fe=="number"&&Number.isFinite(fe));re.length>=2&&(Se=Math.min(...re),pe=Math.max(...re))}const dt=Se!==null&&pe!==null&&pe>=Se?pe-Se:null,yt=re=>re?re==="waiting"?"waiting, reason not loaded":re:"state not loaded",_t=(rt==null?void 0:rt.text)||yt(nt),bt=ka(nt||(rt?{running:"running",needs_you:"waiting",paused:"paused",waiting:"waiting",scheduled:"scheduled",done:""}[rt.verb]??"":"")),St=Q?z[Q]:void 0,ut=Mn(e.current_node_label).trim()||(St?mt(St,Q===se).label:""),Ot=!!ut&&(!ct||Qe),Mt=`${le.size.toLocaleString("en-US")} node${le.size===1?"":"s"} visited${dt!==null?` in ${vu(dt)}`:""}`,mn=Ve?s.jsxs("div",{className:"flow_banner","data-phase":ct?"finished":"ongoing",children:[s.jsx("span",{className:`chip ${bt}`,children:ct?"finished":"ongoing"}),s.jsx("span",{className:"flow_banner_text",children:_t}),Ot?s.jsxs("span",{className:"flow_banner_at",children:["· at ",s.jsx("strong",{children:ut})]}):null,ct&&n?s.jsxs("span",{className:"flow_banner_meta",children:["· ",Mt]}):null]}):s.jsxs("div",{className:"flow_banner","data-phase":"none",children:[s.jsx("span",{className:"chip muted",children:"no run"}),s.jsx("span",{className:"flow_banner_text",children:"the workflow only — open a run to see where it is"})]});if(!n)return Ve?s.jsxs("div",{className:"graph_wrap",children:[mn,s.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"})]}):s.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"});const yn=(re,fe,Ce)=>{const Ie=Ce||b.current,We=_.current;if(!We)return{x:re,y:fe};const Ue=We.getBoundingClientRect(),et=Ue.width>0?(re-Ue.left)/Ue.width:0,at=Ue.height>0?(fe-Ue.top)/Ue.height:0;return{x:Ie.x+et*Ie.w,y:Ie.y+at*Ie.h}},In=(re,fe,Ce)=>{const Ie=Ce||b.current,We=Math.max(.12,Math.min(8,fe)),Ue=Ie.w*We,et=Ie.h*We,at=Ie.w>0?(re.x-Ie.x)/Ie.w:.5,vt=Ie.h>0?(re.y-Ie.y)/Ie.h:.5,xt=re.x-at*Ue,Et=re.y-vt*et;y(Y0({x:xt,y:Et,w:Ue,h:et},m))},Gs=(re,fe,Ce)=>{const Ie=Ce||b.current,We=_.current;if(!We)return;const Ue=We.getBoundingClientRect(),et=.88,at=Ue.width>0?re/Ue.width*Ie.w*et:0,vt=Ue.height>0?fe/Ue.height*Ie.h*et:0;y(xt=>Y0({x:(Ce||xt).x-at,y:(Ce||xt).y-vt,w:(Ce||xt).w,h:(Ce||xt).h},m))},ss=(re,fe,Ce,Ie)=>{const We=m.node_w,Ue=m.node_h,et=Math.abs(Ce),at=Math.abs(Ie);if(et<1e-6&&at<1e-6)return{x:re,y:fe};const vt=et>1e-6?We/2/et:Number.POSITIVE_INFINITY,xt=at>1e-6?Ue/2/at:Number.POSITIVE_INFINITY,Et=Math.min(vt,xt);return{x:re+Ce*Et,y:fe+Ie*Et}},ge=()=>JSON.stringify(CP({run_id:ze,status:nt,state:_t,finished:ct,now_ms:t,current_id:Q,nodes:d.map(re=>({id:re.id,label:mt(re,!1).label,type:re.type})),edges:h,facts:Dt,status_of:ce}),null,2),Re=$?z[$.id]:void 0;return s.jsxs("div",{className:"graph_wrap",children:[mn,s.jsxs("div",{className:"graph_corner",children:[s.jsxs("div",{className:"graph_corner_buttons",children:[s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>y({x:m.x,y:m.y,w:m.w,h:m.h}),title:"Recenter",children:"⤢"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const re=_.current;if(!re)return;const fe=re.getBoundingClientRect(),Ce=yn(fe.left+fe.width/2,fe.top+fe.height/2);In(Ce,.84)},title:"Zoom in",children:"+"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const re=_.current;if(!re)return;const fe=re.getBoundingClientRect(),Ce=yn(fe.left+fe.width/2,fe.top+fe.height/2);In(Ce,1.18)},title:"Zoom out",children:"−"}),s.jsx(Tp,{className:"btn graph_corner_btn flow_copy_state_btn",title:"Copy run state (JSON: where the run is and what each node did)",label:"⧉",copied:"✓",failed:"!",get_text:ge})]}),s.jsx(TP,{})]}),s.jsxs("svg",{ref:_,className:"graph_svg",viewBox:te,role:"group","aria-label":"Workflow execution graph",onWheel:re=>{re.preventDefault();const fe=yn(re.clientX,re.clientY),Ce=typeof re.deltaY=="number"?re.deltaY:0,Ie=typeof re.deltaMode=="number"?Number(re.deltaMode):0,We=Ie===1?Ce*24:Ie===2?Ce*800:Ce,Ue=45e-5*1.15*1.1;let et=Math.exp(We*Ue);et=Math.max(.86,Math.min(1.16,et)),In(fe,et)},onPointerDown:re=>{var Ce,Ie;(Ie=(Ce=re.currentTarget).setPointerCapture)==null||Ie.call(Ce,re.pointerId),k.current.set(re.pointerId,{x:re.clientX,y:re.clientY});const fe=Array.from(k.current.values());if(fe.length===1)x.current={mode:"pan",start_view:b.current,start_client:{x:re.clientX,y:re.clientY},start_dist:0,anchor_svg:{x:0,y:0}};else if(fe.length>=2){W.current=null;const We=fe[0],Ue=fe[1],et=We.x-Ue.x,at=We.y-Ue.y,vt=Math.max(1,Math.hypot(et,at)),xt={x:(We.x+Ue.x)/2,y:(We.y+Ue.y)/2},Et=b.current;x.current={mode:"pinch",start_view:Et,start_client:xt,start_dist:vt,anchor_svg:yn(xt.x,xt.y,Et)}}},onPointerMove:re=>{if(!k.current.has(re.pointerId))return;k.current.set(re.pointerId,{x:re.clientX,y:re.clientY});const fe=x.current;if(!fe)return;const Ce=Array.from(k.current.values());if(fe.mode==="pan"&&Ce.length===1){const Ie=re.clientX-fe.start_client.x,We=re.clientY-fe.start_client.y;Gs(Ie,We,fe.start_view)}else if(fe.mode==="pinch"&&Ce.length>=2){const Ie=Ce[0],We=Ce[1],Ue=Ie.x-We.x,et=Ie.y-We.y,at=Math.max(1,Math.hypot(Ue,et)),vt=fe.start_dist/at;In(fe.anchor_svg,vt,fe.start_view)}},onPointerUp:re=>{k.current.delete(re.pointerId),k.current.size===0&&(x.current=null);const fe=W.current;W.current=null,fe&&k.current.size===0&&Math.hypot(re.clientX-fe.x,re.clientY-fe.y)<5&&V(fe.id,!1)},onPointerCancel:re=>{k.current.delete(re.pointerId),k.current.size===0&&(x.current=null),W.current=null},children:[s.jsxs("defs",{children:[s.jsx("marker",{id:"arrow",viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"8",markerHeight:"8",orient:"auto-start-reverse",children:s.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"rgba(148,163,184,0.55)"})}),s.jsxs("filter",{id:"glow",children:[s.jsx("feGaussianBlur",{stdDeviation:"3",result:"coloredBlur"}),s.jsxs("feMerge",{children:[s.jsx("feMergeNode",{in:"coloredBlur"}),s.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),h.map(re=>{const fe=z[re.source],Ce=z[re.target];if(!fe||!Ce)return null;const Ie=fe.x+m.node_w/2,We=fe.y+m.node_h/2,Ue=Ce.x+m.node_w/2,et=Ce.y+m.node_h/2,at=Ue-Ie,vt=et-We,xt=ss(Ie,We,at,vt),Et=ss(Ue,et,-at,-vt),zt=re.source!==re.target&&N.has(`${re.target}->${re.source}`),ot=Math.max(1,Math.hypot(at,vt)),Jt=-vt/ot,wn=at/ot,hn=String(re.source)<String(re.target)?1:-1,Vt=Math.abs(at)>=Math.abs(vt)?at>=0:vt>=0,rs=!zt||Vt,Be=Math.max(28,Math.min(72,ot*.14)),Zt=Math.min(200,Be*3.5),Tt=zt&&!rs?Zt*hn:0,Dn=(xt.x+Et.x)/2+Jt*Tt,fn=(xt.y+Et.y)/2+wn*Tt,Xe=zt&&!rs?`M ${xt.x} ${xt.y} Q ${Dn} ${fn} ${Et.x} ${Et.y}`:`M ${xt.x} ${xt.y} L ${Et.x} ${Et.y}`,nn=u&&be&&be[re.source]!==void 0&&be[re.target]!==void 0;return s.jsx("path",{d:Xe,className:`graph_edge ${nn?"visited":""}`,markerEnd:"url(#arrow)",fill:"none"},re.id)}),d.map(re=>{const Ce=(typeof de[re.id]=="number"?de[re.id]:0)>t,Ie=se&&re.id===se,We=u&&be&&be[re.id]!==void 0,Ue=ce(re.id),et=!!Q&&re.id===Q,at=`graph_node ${Ie?"active":Ce?"recent":""} ${We?"visited":""}${et?" here":""}`,vt=re.color||"rgba(255,255,255,0.16)",{label:xt,type:Et}=mt(re,!!Ie),zt=J0(xt,22),ot=J0(Et,22),Jt=et?_e(Ue):"",wn=Jt?Math.round(Jt.length*6.2+14):0,hn=Ue==="waiting"?A1(Dt[re.id]):C1[Ue],sn=($==null?void 0:$.id)===re.id;return s.jsxs("g",{ref:Vt=>{D.current[re.id]=Vt},className:at,transform:`translate(${re.x}, ${re.y})`,"data-flow-node":re.id,"data-run-status":Ue,tabIndex:0,role:"button","aria-label":`${xt} (${Et}): ${hn}${Jt?`, ${Jt}`:""}`,"aria-haspopup":"dialog","aria-expanded":sn,"aria-describedby":sn?H:void 0,onPointerDown:Vt=>{W.current={id:re.id,x:Vt.clientX,y:Vt.clientY}},onMouseEnter:()=>{($==null?void 0:$.mode)!=="pinned"&&(M(),!sn&&(I.current=window.setTimeout(()=>{x.current||O(re.id,"hover")},150)))},onMouseLeave:()=>{sn&&($==null?void 0:$.mode)==="hover"?L(re.id):($==null?void 0:$.mode)!=="pinned"&&M()},onFocus:()=>{G.current||sn&&($==null?void 0:$.mode)==="pinned"||O(re.id,"focus")},onBlur:Vt=>{var rs;sn&&($==null?void 0:$.mode)==="focus"&&!((rs=R.current)!=null&&rs.contains(Vt.relatedTarget))&&L(re.id)},onKeyDown:Vt=>{Vt.key!=="Enter"&&Vt.key!==" "||(Vt.preventDefault(),V(re.id,!0))},children:[Ue==="running"||Ue==="waiting"||Ue==="failed"||et?s.jsx("rect",{className:"flow_node_ring",x:-5,y:-5,width:m.node_w+10,height:m.node_h+10,rx:16,ry:16}):null,s.jsx("rect",{className:"graph_node_bg",width:m.node_w,height:m.node_h,rx:12,ry:12}),s.jsx("rect",{className:"graph_node_bar",width:m.node_w,height:6,rx:12,ry:12,fill:vt}),s.jsx("text",{className:"graph_node_label",x:12,y:28,children:zt}),s.jsx("text",{className:"graph_node_type",x:12,y:46,children:ot}),re.type==="on_schedule"?s.jsx("text",{className:"graph_node_icon",x:m.node_w-18,y:18,children:"⏰"}):null,Ue!=="none"?s.jsx("g",{className:"flow_status_badge",transform:`translate(${m.node_w-12}, 0)`,"aria-hidden":"true",children:s.jsx(l5,{status:Ue})}):null,Jt?s.jsxs("g",{className:"flow_here_chip",transform:`translate(${m.node_w-26-wn}, -9)`,"aria-hidden":"true",children:[s.jsx("rect",{width:wn,height:18,rx:9,ry:9}),s.jsx("text",{x:7,y:12.5,children:Jt})]}):null]},re.id)})]}),$&&Re&&S&&typeof document<"u"?wg.createPortal(s.jsx("div",{ref:R,id:H,className:"flow_facts_pop",role:"dialog","aria-label":`About the node ${mt(Re,Re.id===se).label}`,tabIndex:-1,style:{top:S.top,left:S.left,width:S.width},onMouseEnter:M,onMouseLeave:()=>$.mode==="hover"?L($.id):void 0,onBlur:re=>{$.mode==="focus"&&!re.currentTarget.contains(re.relatedTarget)&&L($.id)},children:s.jsx(u5,{node:{id:Re.id,...mt(Re,Re.id===se)},facts:Dt[Re.id]||null,status:ce(Re.id),here:Re.id===Q,finished:ct,on_open_run:e.on_open_run})}),document.body):null]})}function Cr(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=Cr(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var Jy={exports:{}},Yy={},Xy={exports:{}},Zy={};/**
138
+ * @license React
139
+ * use-sync-external-store-shim.production.js
140
+ *
141
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
142
+ *
143
+ * This source code is licensed under the MIT license found in the
144
+ * LICENSE file in the root directory of this source tree.
145
+ */var ek;function f5(){if(ek)return Zy;ek=1;var e=gm();function t(_,g){return _===g&&(_!==0||1/_===1/g)||_!==_&&g!==g}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,i=e.useEffect,o=e.useLayoutEffect,u=e.useDebugValue;function l(_,g){var y=g(),b=r({inst:{value:y,getSnapshot:g}}),k=b[0].inst,x=b[1];return o(function(){k.value=y,k.getSnapshot=g,d(k)&&x({inst:k})},[_,y,g]),i(function(){return d(k)&&x({inst:k}),_(function(){d(k)&&x({inst:k})})},[_]),u(y),y}function d(_){var g=_.getSnapshot;_=_.value;try{var y=g();return!n(_,y)}catch{return!0}}function h(_,g){return g()}var m=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?h:l;return Zy.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:m,Zy}var tk;function h5(){return tk||(tk=1,Xy.exports=f5()),Xy.exports}/**
146
+ * @license React
147
+ * use-sync-external-store-shim/with-selector.production.js
148
+ *
149
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
150
+ *
151
+ * This source code is licensed under the MIT license found in the
152
+ * LICENSE file in the root directory of this source tree.
153
+ */var nk;function m5(){if(nk)return Yy;nk=1;var e=gm(),t=h5();function n(h,m){return h===m&&(h!==0||1/h===1/m)||h!==h&&m!==m}var r=typeof Object.is=="function"?Object.is:n,i=t.useSyncExternalStore,o=e.useRef,u=e.useEffect,l=e.useMemo,d=e.useDebugValue;return Yy.useSyncExternalStoreWithSelector=function(h,m,_,g,y){var b=o(null);if(b.current===null){var k={hasValue:!1,value:null};b.current=k}else k=b.current;b=l(function(){function N(D){if(!$){if($=!0,E=D,D=g(D),y!==void 0&&k.hasValue){var R=k.value;if(y(R,D))return S=R}return S=D}if(R=S,r(E,D))return R;var I=g(D);return y!==void 0&&y(R,I)?(E=D,R):(E=D,S=I)}var $=!1,E,S,P=_===void 0?null:_;return[function(){return N(m())},P===null?void 0:function(){return N(P())}]},[m,_,g,y]);var x=i(h,b[0],b[1]);return u(function(){k.hasValue=!0,k.value=x},[x]),d(x),x},Yy}var sk;function _5(){return sk||(sk=1,Jy.exports=m5()),Jy.exports}var p5=_5();const g5=Bv(p5),y5={},rk=e=>{let t;const n=new Set,r=(m,_)=>{const g=typeof m=="function"?m(t):m;if(!Object.is(g,t)){const y=t;t=_??(typeof g!="object"||g===null)?g:Object.assign({},t,g),n.forEach(b=>b(t,y))}},i=()=>t,d={setState:r,getState:i,getInitialState:()=>h,subscribe:m=>(n.add(m),()=>n.delete(m)),destroy:()=>{(y5?"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()}},h=t=e(r,i,d);return d},w5=e=>e?rk(e):rk,{useDebugValue:v5}=Ee,{useSyncExternalStoreWithSelector:x5}=g5,b5=e=>e;function T1(e,t=b5,n){const r=x5(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return v5(r),r}const ik=(e,t)=>{const n=w5(e),r=(i,o=t)=>T1(n,i,o);return Object.assign(r,n),r},k5=(e,t)=>e?ik(e,t):ik;function hr(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,i]of e)if(!Object.is(i,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}var j5={value:()=>{}};function Pg(){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 Mp(n)}function Mp(e){this._=e}function S5(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",i=n.indexOf(".");if(i>=0&&(r=n.slice(i+1),n=n.slice(0,i)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}Mp.prototype=Pg.prototype={constructor:Mp,on:function(e,t){var n=this._,r=S5(e+"",n),i,o=-1,u=r.length;if(arguments.length<2){for(;++o<u;)if((i=(e=r[o]).type)&&(i=N5(n[i],e.name)))return i;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++o<u;)if(i=(e=r[o]).type)n[i]=ok(n[i],e.name,t);else if(t==null)for(i in n)n[i]=ok(n[i],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new Mp(e)},call:function(e,t){if((i=arguments.length-2)>0)for(var n=new Array(i),r=0,i,o;r<i;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(o=this._[e],r=0,i=o.length;r<i;++r)o[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],i=0,o=r.length;i<o;++i)r[i].value.apply(t,n)}};function N5(e,t){for(var n=0,r=e.length,i;n<r;++n)if((i=e[n]).name===t)return i.value}function ok(e,t,n){for(var r=0,i=e.length;r<i;++r)if(e[r].name===t){e[r]=j5,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var av="http://www.w3.org/1999/xhtml";const ak={svg:"http://www.w3.org/2000/svg",xhtml:av,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Dg(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),ak.hasOwnProperty(t)?{space:ak[t],local:e}:e}function $5(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===av&&t.documentElement.namespaceURI===av?t.createElement(e):t.createElementNS(n,e)}}function C5(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function M1(e){var t=Dg(e);return(t.local?C5:$5)(t)}function E5(){}function gx(e){return e==null?E5:function(){return this.querySelector(e)}}function A5(e){typeof e!="function"&&(e=gx(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o=t[i],u=o.length,l=r[i]=new Array(u),d,h,m=0;m<u;++m)(d=o[m])&&(h=e.call(d,d.__data__,m,o))&&("__data__"in d&&(h.__data__=d.__data__),l[m]=h);return new Fi(r,this._parents)}function T5(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function M5(){return[]}function R1(e){return e==null?M5:function(){return this.querySelectorAll(e)}}function R5(e){return function(){return T5(e.apply(this,arguments))}}function L5(e){typeof e=="function"?e=R5(e):e=R1(e);for(var t=this._groups,n=t.length,r=[],i=[],o=0;o<n;++o)for(var u=t[o],l=u.length,d,h=0;h<l;++h)(d=u[h])&&(r.push(e.call(d,d.__data__,h,u)),i.push(d));return new Fi(r,i)}function L1(e){return function(){return this.matches(e)}}function I1(e){return function(t){return t.matches(e)}}var I5=Array.prototype.find;function O5(e){return function(){return I5.call(this.children,e)}}function P5(){return this.firstElementChild}function D5(e){return this.select(e==null?P5:O5(typeof e=="function"?e:I1(e)))}var F5=Array.prototype.filter;function z5(){return Array.from(this.children)}function B5(e){return function(){return F5.call(this.children,e)}}function U5(e){return this.selectAll(e==null?z5:B5(typeof e=="function"?e:I1(e)))}function W5(e){typeof e!="function"&&(e=L1(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o=t[i],u=o.length,l=r[i]=[],d,h=0;h<u;++h)(d=o[h])&&e.call(d,d.__data__,h,o)&&l.push(d);return new Fi(r,this._parents)}function O1(e){return new Array(e.length)}function q5(){return new Fi(this._enter||this._groups.map(O1),this._parents)}function rg(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}rg.prototype={constructor:rg,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 H5(e){return function(){return e}}function V5(e,t,n,r,i,o){for(var u=0,l,d=t.length,h=o.length;u<h;++u)(l=t[u])?(l.__data__=o[u],r[u]=l):n[u]=new rg(e,o[u]);for(;u<d;++u)(l=t[u])&&(i[u]=l)}function G5(e,t,n,r,i,o,u){var l,d,h=new Map,m=t.length,_=o.length,g=new Array(m),y;for(l=0;l<m;++l)(d=t[l])&&(g[l]=y=u.call(d,d.__data__,l,t)+"",h.has(y)?i[l]=d:h.set(y,d));for(l=0;l<_;++l)y=u.call(e,o[l],l,o)+"",(d=h.get(y))?(r[l]=d,d.__data__=o[l],h.delete(y)):n[l]=new rg(e,o[l]);for(l=0;l<m;++l)(d=t[l])&&h.get(g[l])===d&&(i[l]=d)}function K5(e){return e.__data__}function J5(e,t){if(!arguments.length)return Array.from(this,K5);var n=t?G5:V5,r=this._parents,i=this._groups;typeof e!="function"&&(e=H5(e));for(var o=i.length,u=new Array(o),l=new Array(o),d=new Array(o),h=0;h<o;++h){var m=r[h],_=i[h],g=_.length,y=Y5(e.call(m,m&&m.__data__,h,r)),b=y.length,k=l[h]=new Array(b),x=u[h]=new Array(b),N=d[h]=new Array(g);n(m,_,k,x,N,y,t);for(var $=0,E=0,S,P;$<b;++$)if(S=k[$]){for($>=E&&(E=$+1);!(P=x[E])&&++E<b;);S._next=P||null}}return u=new Fi(u,r),u._enter=l,u._exit=d,u}function Y5(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function X5(){return new Fi(this._exit||this._groups.map(O1),this._parents)}function Z5(e,t,n){var r=this.enter(),i=this,o=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(i=t(i),i&&(i=i.selection())),n==null?o.remove():n(o),r&&i?r.merge(i).order():i}function Q5(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,i=n.length,o=r.length,u=Math.min(i,o),l=new Array(i),d=0;d<u;++d)for(var h=n[d],m=r[d],_=h.length,g=l[d]=new Array(_),y,b=0;b<_;++b)(y=h[b]||m[b])&&(g[b]=y);for(;d<i;++d)l[d]=n[d];return new Fi(l,this._parents)}function eD(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],i=r.length-1,o=r[i],u;--i>=0;)(u=r[i])&&(o&&u.compareDocumentPosition(o)^4&&o.parentNode.insertBefore(u,o),o=u);return this}function tD(e){e||(e=nD);function t(_,g){return _&&g?e(_.__data__,g.__data__):!_-!g}for(var n=this._groups,r=n.length,i=new Array(r),o=0;o<r;++o){for(var u=n[o],l=u.length,d=i[o]=new Array(l),h,m=0;m<l;++m)(h=u[m])&&(d[m]=h);d.sort(t)}return new Fi(i,this._parents).order()}function nD(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function sD(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function rD(){return Array.from(this)}function iD(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],i=0,o=r.length;i<o;++i){var u=r[i];if(u)return u}return null}function oD(){let e=0;for(const t of this)++e;return e}function aD(){return!this.node()}function lD(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var i=t[n],o=0,u=i.length,l;o<u;++o)(l=i[o])&&e.call(l,l.__data__,o,i);return this}function cD(e){return function(){this.removeAttribute(e)}}function uD(e){return function(){this.removeAttributeNS(e.space,e.local)}}function dD(e,t){return function(){this.setAttribute(e,t)}}function fD(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function hD(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function mD(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 _D(e,t){var n=Dg(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?uD:cD:typeof t=="function"?n.local?mD:hD:n.local?fD:dD)(n,t))}function P1(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function pD(e){return function(){this.style.removeProperty(e)}}function gD(e,t,n){return function(){this.style.setProperty(e,t,n)}}function yD(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function wD(e,t,n){return arguments.length>1?this.each((t==null?pD:typeof t=="function"?yD:gD)(e,t,n??"")):Zd(this.node(),e)}function Zd(e,t){return e.style.getPropertyValue(t)||P1(e).getComputedStyle(e,null).getPropertyValue(t)}function vD(e){return function(){delete this[e]}}function xD(e,t){return function(){this[e]=t}}function bD(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function kD(e,t){return arguments.length>1?this.each((t==null?vD:typeof t=="function"?bD:xD)(e,t)):this.node()[e]}function D1(e){return e.trim().split(/^|\s+/)}function yx(e){return e.classList||new F1(e)}function F1(e){this._node=e,this._names=D1(e.getAttribute("class")||"")}F1.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 z1(e,t){for(var n=yx(e),r=-1,i=t.length;++r<i;)n.add(t[r])}function B1(e,t){for(var n=yx(e),r=-1,i=t.length;++r<i;)n.remove(t[r])}function jD(e){return function(){z1(this,e)}}function SD(e){return function(){B1(this,e)}}function ND(e,t){return function(){(t.apply(this,arguments)?z1:B1)(this,e)}}function $D(e,t){var n=D1(e+"");if(arguments.length<2){for(var r=yx(this.node()),i=-1,o=n.length;++i<o;)if(!r.contains(n[i]))return!1;return!0}return this.each((typeof t=="function"?ND:t?jD:SD)(n,t))}function CD(){this.textContent=""}function ED(e){return function(){this.textContent=e}}function AD(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function TD(e){return arguments.length?this.each(e==null?CD:(typeof e=="function"?AD:ED)(e)):this.node().textContent}function MD(){this.innerHTML=""}function RD(e){return function(){this.innerHTML=e}}function LD(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function ID(e){return arguments.length?this.each(e==null?MD:(typeof e=="function"?LD:RD)(e)):this.node().innerHTML}function OD(){this.nextSibling&&this.parentNode.appendChild(this)}function PD(){return this.each(OD)}function DD(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function FD(){return this.each(DD)}function zD(e){var t=typeof e=="function"?e:M1(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function BD(){return null}function UD(e,t){var n=typeof e=="function"?e:M1(e),r=t==null?BD:typeof t=="function"?t:gx(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function WD(){var e=this.parentNode;e&&e.removeChild(this)}function qD(){return this.each(WD)}function HD(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function VD(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function GD(e){return this.select(e?VD:HD)}function KD(e){return arguments.length?this.property("__data__",e):this.node().__data__}function JD(e){return function(t){e.call(this,t,this.__data__)}}function YD(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 XD(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,i=t.length,o;n<i;++n)o=t[n],(!e.type||o.type===e.type)&&o.name===e.name?this.removeEventListener(o.type,o.listener,o.options):t[++r]=o;++r?t.length=r:delete this.__on}}}function ZD(e,t,n){return function(){var r=this.__on,i,o=JD(t);if(r){for(var u=0,l=r.length;u<l;++u)if((i=r[u]).type===e.type&&i.name===e.name){this.removeEventListener(i.type,i.listener,i.options),this.addEventListener(i.type,i.listener=o,i.options=n),i.value=t;return}}this.addEventListener(e.type,o,n),i={type:e.type,name:e.name,value:t,listener:o,options:n},r?r.push(i):this.__on=[i]}}function QD(e,t,n){var r=YD(e+""),i,o=r.length,u;if(arguments.length<2){var l=this.node().__on;if(l){for(var d=0,h=l.length,m;d<h;++d)for(i=0,m=l[d];i<o;++i)if((u=r[i]).type===m.type&&u.name===m.name)return m.value}return}for(l=t?ZD:XD,i=0;i<o;++i)this.each(l(r[i],t,n));return this}function U1(e,t,n){var r=P1(e),i=r.CustomEvent;typeof i=="function"?i=new i(t,n):(i=r.document.createEvent("Event"),n?(i.initEvent(t,n.bubbles,n.cancelable),i.detail=n.detail):i.initEvent(t,!1,!1)),e.dispatchEvent(i)}function eF(e,t){return function(){return U1(this,e,t)}}function tF(e,t){return function(){return U1(this,e,t.apply(this,arguments))}}function nF(e,t){return this.each((typeof t=="function"?tF:eF)(e,t))}function*sF(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],i=0,o=r.length,u;i<o;++i)(u=r[i])&&(yield u)}var W1=[null];function Fi(e,t){this._groups=e,this._parents=t}function Tm(){return new Fi([[document.documentElement]],W1)}function rF(){return this}Fi.prototype=Tm.prototype={constructor:Fi,select:A5,selectAll:L5,selectChild:D5,selectChildren:U5,filter:W5,data:J5,enter:q5,exit:X5,join:Z5,merge:Q5,selection:rF,order:eD,sort:tD,call:sD,nodes:rD,node:iD,size:oD,empty:aD,each:lD,attr:_D,style:wD,property:kD,classed:$D,text:TD,html:ID,raise:PD,lower:FD,append:zD,insert:UD,remove:qD,clone:GD,datum:KD,on:QD,dispatch:nF,[Symbol.iterator]:sF};function yo(e){return typeof e=="string"?new Fi([[document.querySelector(e)]],[document.documentElement]):new Fi([[e]],W1)}function iF(e){let t;for(;t=e.sourceEvent;)e=t;return e}function qo(e,t){if(e=iF(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 i=t.getBoundingClientRect();return[e.clientX-i.left-t.clientLeft,e.clientY-i.top-t.clientTop]}}return[e.pageX,e.pageY]}const oF={passive:!1},im={capture:!0,passive:!1};function Qy(e){e.stopImmediatePropagation()}function Ud(e){e.preventDefault(),e.stopImmediatePropagation()}function q1(e){var t=e.document.documentElement,n=yo(e).on("dragstart.drag",Ud,im);"onselectstart"in t?n.on("selectstart.drag",Ud,im):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function H1(e,t){var n=e.document.documentElement,r=yo(e).on("dragstart.drag",null);t&&(r.on("click.drag",Ud,im),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 ap=e=>()=>e;function lv(e,{sourceEvent:t,subject:n,target:r,identifier:i,active:o,x:u,y:l,dx:d,dy:h,dispatch:m}){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:i,enumerable:!0,configurable:!0},active:{value:o,enumerable:!0,configurable:!0},x:{value:u,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:d,enumerable:!0,configurable:!0},dy:{value:h,enumerable:!0,configurable:!0},_:{value:m}})}lv.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function aF(e){return!e.ctrlKey&&!e.button}function lF(){return this.parentNode}function cF(e,t){return t??{x:e.x,y:e.y}}function uF(){return navigator.maxTouchPoints||"ontouchstart"in this}function dF(){var e=aF,t=lF,n=cF,r=uF,i={},o=Pg("start","drag","end"),u=0,l,d,h,m,_=0;function g(S){S.on("mousedown.drag",y).filter(r).on("touchstart.drag",x).on("touchmove.drag",N,oF).on("touchend.drag touchcancel.drag",$).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function y(S,P){if(!(m||!e.call(this,S,P))){var D=E(this,t.call(this,S,P),S,P,"mouse");D&&(yo(S.view).on("mousemove.drag",b,im).on("mouseup.drag",k,im),q1(S.view),Qy(S),h=!1,l=S.clientX,d=S.clientY,D("start",S))}}function b(S){if(Ud(S),!h){var P=S.clientX-l,D=S.clientY-d;h=P*P+D*D>_}i.mouse("drag",S)}function k(S){yo(S.view).on("mousemove.drag mouseup.drag",null),H1(S.view,h),Ud(S),i.mouse("end",S)}function x(S,P){if(e.call(this,S,P)){var D=S.changedTouches,R=t.call(this,S,P),I=D.length,W,G;for(W=0;W<I;++W)(G=E(this,R,S,P,D[W].identifier,D[W]))&&(Qy(S),G("start",S,D[W]))}}function N(S){var P=S.changedTouches,D=P.length,R,I;for(R=0;R<D;++R)(I=i[P[R].identifier])&&(Ud(S),I("drag",S,P[R]))}function $(S){var P=S.changedTouches,D=P.length,R,I;for(m&&clearTimeout(m),m=setTimeout(function(){m=null},500),R=0;R<D;++R)(I=i[P[R].identifier])&&(Qy(S),I("end",S,P[R]))}function E(S,P,D,R,I,W){var G=o.copy(),K=qo(W||D,P),H,M,A;if((A=n.call(S,new lv("beforestart",{sourceEvent:D,target:g,identifier:I,active:u,x:K[0],y:K[1],dx:0,dy:0,dispatch:G}),R))!=null)return H=A.x-K[0]||0,M=A.y-K[1]||0,function O(L,V,J){var U=K,te;switch(L){case"start":i[I]=O,te=u++;break;case"end":delete i[I],--u;case"drag":K=qo(J||V,P),te=u;break}G.call(L,S,new lv(L,{sourceEvent:V,subject:A,target:g,identifier:I,active:te,x:K[0]+H,y:K[1]+M,dx:K[0]-U[0],dy:K[1]-U[1],dispatch:G}),R)}}return g.filter=function(S){return arguments.length?(e=typeof S=="function"?S:ap(!!S),g):e},g.container=function(S){return arguments.length?(t=typeof S=="function"?S:ap(S),g):t},g.subject=function(S){return arguments.length?(n=typeof S=="function"?S:ap(S),g):n},g.touchable=function(S){return arguments.length?(r=typeof S=="function"?S:ap(!!S),g):r},g.on=function(){var S=o.on.apply(o,arguments);return S===o?g:S},g.clickDistance=function(S){return arguments.length?(_=(S=+S)*S,g):Math.sqrt(_)},g}function wx(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function V1(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Mm(){}var om=.7,ig=1/om,Wd="\\s*([+-]?\\d+)\\s*",am="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ba="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",fF=/^#([0-9a-f]{3,8})$/,hF=new RegExp(`^rgb\\(${Wd},${Wd},${Wd}\\)$`),mF=new RegExp(`^rgb\\(${ba},${ba},${ba}\\)$`),_F=new RegExp(`^rgba\\(${Wd},${Wd},${Wd},${am}\\)$`),pF=new RegExp(`^rgba\\(${ba},${ba},${ba},${am}\\)$`),gF=new RegExp(`^hsl\\(${am},${ba},${ba}\\)$`),yF=new RegExp(`^hsla\\(${am},${ba},${ba},${am}\\)$`),lk={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};wx(Mm,lm,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:ck,formatHex:ck,formatHex8:wF,formatHsl:vF,formatRgb:uk,toString:uk});function ck(){return this.rgb().formatHex()}function wF(){return this.rgb().formatHex8()}function vF(){return G1(this).formatHsl()}function uk(){return this.rgb().formatRgb()}function lm(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=fF.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?dk(t):n===3?new ji(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?lp(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?lp(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=hF.exec(e))?new ji(t[1],t[2],t[3],1):(t=mF.exec(e))?new ji(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=_F.exec(e))?lp(t[1],t[2],t[3],t[4]):(t=pF.exec(e))?lp(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=gF.exec(e))?mk(t[1],t[2]/100,t[3]/100,1):(t=yF.exec(e))?mk(t[1],t[2]/100,t[3]/100,t[4]):lk.hasOwnProperty(e)?dk(lk[e]):e==="transparent"?new ji(NaN,NaN,NaN,0):null}function dk(e){return new ji(e>>16&255,e>>8&255,e&255,1)}function lp(e,t,n,r){return r<=0&&(e=t=n=NaN),new ji(e,t,n,r)}function xF(e){return e instanceof Mm||(e=lm(e)),e?(e=e.rgb(),new ji(e.r,e.g,e.b,e.opacity)):new ji}function cv(e,t,n,r){return arguments.length===1?xF(e):new ji(e,t,n,r??1)}function ji(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}wx(ji,cv,V1(Mm,{brighter(e){return e=e==null?ig:Math.pow(ig,e),new ji(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?om:Math.pow(om,e),new ji(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new ji(cu(this.r),cu(this.g),cu(this.b),og(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:fk,formatHex:fk,formatHex8:bF,formatRgb:hk,toString:hk}));function fk(){return`#${ru(this.r)}${ru(this.g)}${ru(this.b)}`}function bF(){return`#${ru(this.r)}${ru(this.g)}${ru(this.b)}${ru((isNaN(this.opacity)?1:this.opacity)*255)}`}function hk(){const e=og(this.opacity);return`${e===1?"rgb(":"rgba("}${cu(this.r)}, ${cu(this.g)}, ${cu(this.b)}${e===1?")":`, ${e})`}`}function og(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function cu(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function ru(e){return e=cu(e),(e<16?"0":"")+e.toString(16)}function mk(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Go(e,t,n,r)}function G1(e){if(e instanceof Go)return new Go(e.h,e.s,e.l,e.opacity);if(e instanceof Mm||(e=lm(e)),!e)return new Go;if(e instanceof Go)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),o=Math.max(t,n,r),u=NaN,l=o-i,d=(o+i)/2;return l?(t===o?u=(n-r)/l+(n<r)*6:n===o?u=(r-t)/l+2:u=(t-n)/l+4,l/=d<.5?o+i:2-o-i,u*=60):l=d>0&&d<1?0:u,new Go(u,l,d,e.opacity)}function kF(e,t,n,r){return arguments.length===1?G1(e):new Go(e,t,n,r??1)}function Go(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}wx(Go,kF,V1(Mm,{brighter(e){return e=e==null?ig:Math.pow(ig,e),new Go(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?om:Math.pow(om,e),new Go(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,i=2*n-r;return new ji(ew(e>=240?e-240:e+120,i,r),ew(e,i,r),ew(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new Go(_k(this.h),cp(this.s),cp(this.l),og(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=og(this.opacity);return`${e===1?"hsl(":"hsla("}${_k(this.h)}, ${cp(this.s)*100}%, ${cp(this.l)*100}%${e===1?")":`, ${e})`}`}}));function _k(e){return e=(e||0)%360,e<0?e+360:e}function cp(e){return Math.max(0,Math.min(1,e||0))}function ew(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 K1=e=>()=>e;function jF(e,t){return function(n){return e+n*t}}function SF(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 NF(e){return(e=+e)==1?J1:function(t,n){return n-t?SF(t,n,e):K1(isNaN(t)?n:t)}}function J1(e,t){var n=t-e;return n?jF(e,n):K1(isNaN(e)?t:e)}const pk=(function e(t){var n=NF(t);function r(i,o){var u=n((i=cv(i)).r,(o=cv(o)).r),l=n(i.g,o.g),d=n(i.b,o.b),h=J1(i.opacity,o.opacity);return function(m){return i.r=u(m),i.g=l(m),i.b=d(m),i.opacity=h(m),i+""}}return r.gamma=e,r})(1);function Zl(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var uv=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,tw=new RegExp(uv.source,"g");function $F(e){return function(){return e}}function CF(e){return function(t){return e(t)+""}}function EF(e,t){var n=uv.lastIndex=tw.lastIndex=0,r,i,o,u=-1,l=[],d=[];for(e=e+"",t=t+"";(r=uv.exec(e))&&(i=tw.exec(t));)(o=i.index)>n&&(o=t.slice(n,o),l[u]?l[u]+=o:l[++u]=o),(r=r[0])===(i=i[0])?l[u]?l[u]+=i:l[++u]=i:(l[++u]=null,d.push({i:u,x:Zl(r,i)})),n=tw.lastIndex;return n<t.length&&(o=t.slice(n),l[u]?l[u]+=o:l[++u]=o),l.length<2?d[0]?CF(d[0].x):$F(t):(t=d.length,function(h){for(var m=0,_;m<t;++m)l[(_=d[m]).i]=_.x(h);return l.join("")})}var gk=180/Math.PI,dv={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Y1(e,t,n,r,i,o){var u,l,d;return(u=Math.sqrt(e*e+t*t))&&(e/=u,t/=u),(d=e*n+t*r)&&(n-=e*d,r-=t*d),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,d/=l),e*r<t*n&&(e=-e,t=-t,d=-d,u=-u),{translateX:i,translateY:o,rotate:Math.atan2(t,e)*gk,skewX:Math.atan(d)*gk,scaleX:u,scaleY:l}}var up;function AF(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?dv:Y1(t.a,t.b,t.c,t.d,t.e,t.f)}function TF(e){return e==null||(up||(up=document.createElementNS("http://www.w3.org/2000/svg","g")),up.setAttribute("transform",e),!(e=up.transform.baseVal.consolidate()))?dv:(e=e.matrix,Y1(e.a,e.b,e.c,e.d,e.e,e.f))}function X1(e,t,n,r){function i(h){return h.length?h.pop()+" ":""}function o(h,m,_,g,y,b){if(h!==_||m!==g){var k=y.push("translate(",null,t,null,n);b.push({i:k-4,x:Zl(h,_)},{i:k-2,x:Zl(m,g)})}else(_||g)&&y.push("translate("+_+t+g+n)}function u(h,m,_,g){h!==m?(h-m>180?m+=360:m-h>180&&(h+=360),g.push({i:_.push(i(_)+"rotate(",null,r)-2,x:Zl(h,m)})):m&&_.push(i(_)+"rotate("+m+r)}function l(h,m,_,g){h!==m?g.push({i:_.push(i(_)+"skewX(",null,r)-2,x:Zl(h,m)}):m&&_.push(i(_)+"skewX("+m+r)}function d(h,m,_,g,y,b){if(h!==_||m!==g){var k=y.push(i(y)+"scale(",null,",",null,")");b.push({i:k-4,x:Zl(h,_)},{i:k-2,x:Zl(m,g)})}else(_!==1||g!==1)&&y.push(i(y)+"scale("+_+","+g+")")}return function(h,m){var _=[],g=[];return h=e(h),m=e(m),o(h.translateX,h.translateY,m.translateX,m.translateY,_,g),u(h.rotate,m.rotate,_,g),l(h.skewX,m.skewX,_,g),d(h.scaleX,h.scaleY,m.scaleX,m.scaleY,_,g),h=m=null,function(y){for(var b=-1,k=g.length,x;++b<k;)_[(x=g[b]).i]=x.x(y);return _.join("")}}}var MF=X1(AF,"px, ","px)","deg)"),RF=X1(TF,", ",")",")"),LF=1e-12;function yk(e){return((e=Math.exp(e))+1/e)/2}function IF(e){return((e=Math.exp(e))-1/e)/2}function OF(e){return((e=Math.exp(2*e))-1)/(e+1)}const PF=(function e(t,n,r){function i(o,u){var l=o[0],d=o[1],h=o[2],m=u[0],_=u[1],g=u[2],y=m-l,b=_-d,k=y*y+b*b,x,N;if(k<LF)N=Math.log(g/h)/t,x=function(R){return[l+R*y,d+R*b,h*Math.exp(t*R*N)]};else{var $=Math.sqrt(k),E=(g*g-h*h+r*k)/(2*h*n*$),S=(g*g-h*h-r*k)/(2*g*n*$),P=Math.log(Math.sqrt(E*E+1)-E),D=Math.log(Math.sqrt(S*S+1)-S);N=(D-P)/t,x=function(R){var I=R*N,W=yk(P),G=h/(n*$)*(W*OF(t*I+P)-IF(P));return[l+G*y,d+G*b,h*W/yk(t*I+P)]}}return x.duration=N*1e3*t/Math.SQRT2,x}return i.rho=function(o){var u=Math.max(.001,+o),l=u*u,d=l*l;return e(u,l,d)},i})(Math.SQRT2,2,4);var Qd=0,Uh=0,kh=0,Z1=1e3,ag,Wh,lg=0,yu=0,Fg=0,cm=typeof performance=="object"&&performance.now?performance:Date,Q1=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function vx(){return yu||(Q1(DF),yu=cm.now()+Fg)}function DF(){yu=0}function cg(){this._call=this._time=this._next=null}cg.prototype=e$.prototype={constructor:cg,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?vx():+n)+(t==null?0:+t),!this._next&&Wh!==this&&(Wh?Wh._next=this:ag=this,Wh=this),this._call=e,this._time=n,fv()},stop:function(){this._call&&(this._call=null,this._time=1/0,fv())}};function e$(e,t,n){var r=new cg;return r.restart(e,t,n),r}function FF(){vx(),++Qd;for(var e=ag,t;e;)(t=yu-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Qd}function wk(){yu=(lg=cm.now())+Fg,Qd=Uh=0;try{FF()}finally{Qd=0,BF(),yu=0}}function zF(){var e=cm.now(),t=e-lg;t>Z1&&(Fg-=t,lg=e)}function BF(){for(var e,t=ag,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:ag=n);Wh=e,fv(r)}function fv(e){if(!Qd){Uh&&(Uh=clearTimeout(Uh));var t=e-yu;t>24?(e<1/0&&(Uh=setTimeout(wk,e-cm.now()-Fg)),kh&&(kh=clearInterval(kh))):(kh||(lg=cm.now(),kh=setInterval(zF,Z1)),Qd=1,Q1(wk))}}function vk(e,t,n){var r=new cg;return t=t==null?0:+t,r.restart(i=>{r.stop(),e(i+t)},t,n),r}var UF=Pg("start","end","cancel","interrupt"),WF=[],t$=0,xk=1,hv=2,Rp=3,bk=4,mv=5,Lp=6;function zg(e,t,n,r,i,o){var u=e.__transition;if(!u)e.__transition={};else if(n in u)return;qF(e,n,{name:t,index:r,group:i,on:UF,tween:WF,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:t$})}function xx(e,t){var n=Jo(e,t);if(n.state>t$)throw new Error("too late; already scheduled");return n}function ja(e,t){var n=Jo(e,t);if(n.state>Rp)throw new Error("too late; already running");return n}function Jo(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function qF(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=e$(o,0,n.time);function o(h){n.state=xk,n.timer.restart(u,n.delay,n.time),n.delay<=h&&u(h-n.delay)}function u(h){var m,_,g,y;if(n.state!==xk)return d();for(m in r)if(y=r[m],y.name===n.name){if(y.state===Rp)return vk(u);y.state===bk?(y.state=Lp,y.timer.stop(),y.on.call("interrupt",e,e.__data__,y.index,y.group),delete r[m]):+m<t&&(y.state=Lp,y.timer.stop(),y.on.call("cancel",e,e.__data__,y.index,y.group),delete r[m])}if(vk(function(){n.state===Rp&&(n.state=bk,n.timer.restart(l,n.delay,n.time),l(h))}),n.state=hv,n.on.call("start",e,e.__data__,n.index,n.group),n.state===hv){for(n.state=Rp,i=new Array(g=n.tween.length),m=0,_=-1;m<g;++m)(y=n.tween[m].value.call(e,e.__data__,n.index,n.group))&&(i[++_]=y);i.length=_+1}}function l(h){for(var m=h<n.duration?n.ease.call(null,h/n.duration):(n.timer.restart(d),n.state=mv,1),_=-1,g=i.length;++_<g;)i[_].call(e,m);n.state===mv&&(n.on.call("end",e,e.__data__,n.index,n.group),d())}function d(){n.state=Lp,n.timer.stop(),delete r[t];for(var h in r)return;delete e.__transition}}function Ip(e,t){var n=e.__transition,r,i,o=!0,u;if(n){t=t==null?null:t+"";for(u in n){if((r=n[u]).name!==t){o=!1;continue}i=r.state>hv&&r.state<mv,r.state=Lp,r.timer.stop(),r.on.call(i?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[u]}o&&delete e.__transition}}function HF(e){return this.each(function(){Ip(this,e)})}function VF(e,t){var n,r;return function(){var i=ja(this,e),o=i.tween;if(o!==n){r=n=o;for(var u=0,l=r.length;u<l;++u)if(r[u].name===t){r=r.slice(),r.splice(u,1);break}}i.tween=r}}function GF(e,t,n){var r,i;if(typeof n!="function")throw new Error;return function(){var o=ja(this,e),u=o.tween;if(u!==r){i=(r=u).slice();for(var l={name:t,value:n},d=0,h=i.length;d<h;++d)if(i[d].name===t){i[d]=l;break}d===h&&i.push(l)}o.tween=i}}function KF(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Jo(this.node(),n).tween,i=0,o=r.length,u;i<o;++i)if((u=r[i]).name===e)return u.value;return null}return this.each((t==null?VF:GF)(n,e,t))}function bx(e,t,n){var r=e._id;return e.each(function(){var i=ja(this,r);(i.value||(i.value={}))[t]=n.apply(this,arguments)}),function(i){return Jo(i,r).value[t]}}function n$(e,t){var n;return(typeof t=="number"?Zl:t instanceof lm?pk:(n=lm(t))?(t=n,pk):EF)(e,t)}function JF(e){return function(){this.removeAttribute(e)}}function YF(e){return function(){this.removeAttributeNS(e.space,e.local)}}function XF(e,t,n){var r,i=n+"",o;return function(){var u=this.getAttribute(e);return u===i?null:u===r?o:o=t(r=u,n)}}function ZF(e,t,n){var r,i=n+"",o;return function(){var u=this.getAttributeNS(e.space,e.local);return u===i?null:u===r?o:o=t(r=u,n)}}function QF(e,t,n){var r,i,o;return function(){var u,l=n(this),d;return l==null?void this.removeAttribute(e):(u=this.getAttribute(e),d=l+"",u===d?null:u===r&&d===i?o:(i=d,o=t(r=u,l)))}}function e6(e,t,n){var r,i,o;return function(){var u,l=n(this),d;return l==null?void this.removeAttributeNS(e.space,e.local):(u=this.getAttributeNS(e.space,e.local),d=l+"",u===d?null:u===r&&d===i?o:(i=d,o=t(r=u,l)))}}function t6(e,t){var n=Dg(e),r=n==="transform"?RF:n$;return this.attrTween(e,typeof t=="function"?(n.local?e6:QF)(n,r,bx(this,"attr."+e,t)):t==null?(n.local?YF:JF)(n):(n.local?ZF:XF)(n,r,t))}function n6(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function s6(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function r6(e,t){var n,r;function i(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&s6(e,o)),n}return i._value=t,i}function i6(e,t){var n,r;function i(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&n6(e,o)),n}return i._value=t,i}function o6(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=Dg(e);return this.tween(n,(r.local?r6:i6)(r,t))}function a6(e,t){return function(){xx(this,e).delay=+t.apply(this,arguments)}}function l6(e,t){return t=+t,function(){xx(this,e).delay=t}}function c6(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?a6:l6)(t,e)):Jo(this.node(),t).delay}function u6(e,t){return function(){ja(this,e).duration=+t.apply(this,arguments)}}function d6(e,t){return t=+t,function(){ja(this,e).duration=t}}function f6(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?u6:d6)(t,e)):Jo(this.node(),t).duration}function h6(e,t){if(typeof t!="function")throw new Error;return function(){ja(this,e).ease=t}}function m6(e){var t=this._id;return arguments.length?this.each(h6(t,e)):Jo(this.node(),t).ease}function _6(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;ja(this,e).ease=n}}function p6(e){if(typeof e!="function")throw new Error;return this.each(_6(this._id,e))}function g6(e){typeof e!="function"&&(e=L1(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o=t[i],u=o.length,l=r[i]=[],d,h=0;h<u;++h)(d=o[h])&&e.call(d,d.__data__,h,o)&&l.push(d);return new ol(r,this._parents,this._name,this._id)}function y6(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,i=n.length,o=Math.min(r,i),u=new Array(r),l=0;l<o;++l)for(var d=t[l],h=n[l],m=d.length,_=u[l]=new Array(m),g,y=0;y<m;++y)(g=d[y]||h[y])&&(_[y]=g);for(;l<r;++l)u[l]=t[l];return new ol(u,this._parents,this._name,this._id)}function w6(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 v6(e,t,n){var r,i,o=w6(t)?xx:ja;return function(){var u=o(this,e),l=u.on;l!==r&&(i=(r=l).copy()).on(t,n),u.on=i}}function x6(e,t){var n=this._id;return arguments.length<2?Jo(this.node(),n).on.on(e):this.each(v6(n,e,t))}function b6(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function k6(){return this.on("end.remove",b6(this._id))}function j6(e){var t=this._name,n=this._id;typeof e!="function"&&(e=gx(e));for(var r=this._groups,i=r.length,o=new Array(i),u=0;u<i;++u)for(var l=r[u],d=l.length,h=o[u]=new Array(d),m,_,g=0;g<d;++g)(m=l[g])&&(_=e.call(m,m.__data__,g,l))&&("__data__"in m&&(_.__data__=m.__data__),h[g]=_,zg(h[g],t,n,g,h,Jo(m,n)));return new ol(o,this._parents,t,n)}function S6(e){var t=this._name,n=this._id;typeof e!="function"&&(e=R1(e));for(var r=this._groups,i=r.length,o=[],u=[],l=0;l<i;++l)for(var d=r[l],h=d.length,m,_=0;_<h;++_)if(m=d[_]){for(var g=e.call(m,m.__data__,_,d),y,b=Jo(m,n),k=0,x=g.length;k<x;++k)(y=g[k])&&zg(y,t,n,k,g,b);o.push(g),u.push(m)}return new ol(o,u,t,n)}var N6=Tm.prototype.constructor;function $6(){return new N6(this._groups,this._parents)}function C6(e,t){var n,r,i;return function(){var o=Zd(this,e),u=(this.style.removeProperty(e),Zd(this,e));return o===u?null:o===n&&u===r?i:i=t(n=o,r=u)}}function s$(e){return function(){this.style.removeProperty(e)}}function E6(e,t,n){var r,i=n+"",o;return function(){var u=Zd(this,e);return u===i?null:u===r?o:o=t(r=u,n)}}function A6(e,t,n){var r,i,o;return function(){var u=Zd(this,e),l=n(this),d=l+"";return l==null&&(d=l=(this.style.removeProperty(e),Zd(this,e))),u===d?null:u===r&&d===i?o:(i=d,o=t(r=u,l))}}function T6(e,t){var n,r,i,o="style."+t,u="end."+o,l;return function(){var d=ja(this,e),h=d.on,m=d.value[o]==null?l||(l=s$(t)):void 0;(h!==n||i!==m)&&(r=(n=h).copy()).on(u,i=m),d.on=r}}function M6(e,t,n){var r=(e+="")=="transform"?MF:n$;return t==null?this.styleTween(e,C6(e,r)).on("end.style."+e,s$(e)):typeof t=="function"?this.styleTween(e,A6(e,r,bx(this,"style."+e,t))).each(T6(this._id,e)):this.styleTween(e,E6(e,r,t),n).on("end.style."+e,null)}function R6(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function L6(e,t,n){var r,i;function o(){var u=t.apply(this,arguments);return u!==i&&(r=(i=u)&&R6(e,u,n)),r}return o._value=t,o}function I6(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,L6(e,t,n??""))}function O6(e){return function(){this.textContent=e}}function P6(e){return function(){var t=e(this);this.textContent=t??""}}function D6(e){return this.tween("text",typeof e=="function"?P6(bx(this,"text",e)):O6(e==null?"":e+""))}function F6(e){return function(t){this.textContent=e.call(this,t)}}function z6(e){var t,n;function r(){var i=e.apply(this,arguments);return i!==n&&(t=(n=i)&&F6(i)),t}return r._value=e,r}function B6(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,z6(e))}function U6(){for(var e=this._name,t=this._id,n=r$(),r=this._groups,i=r.length,o=0;o<i;++o)for(var u=r[o],l=u.length,d,h=0;h<l;++h)if(d=u[h]){var m=Jo(d,t);zg(d,e,n,h,u,{time:m.time+m.delay+m.duration,delay:0,duration:m.duration,ease:m.ease})}return new ol(r,this._parents,e,n)}function W6(){var e,t,n=this,r=n._id,i=n.size();return new Promise(function(o,u){var l={value:u},d={value:function(){--i===0&&o()}};n.each(function(){var h=ja(this,r),m=h.on;m!==e&&(t=(e=m).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(d)),h.on=t}),i===0&&o()})}var q6=0;function ol(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function r$(){return++q6}var Ja=Tm.prototype;ol.prototype={constructor:ol,select:j6,selectAll:S6,selectChild:Ja.selectChild,selectChildren:Ja.selectChildren,filter:g6,merge:y6,selection:$6,transition:U6,call:Ja.call,nodes:Ja.nodes,node:Ja.node,size:Ja.size,empty:Ja.empty,each:Ja.each,on:x6,attr:t6,attrTween:o6,style:M6,styleTween:I6,text:D6,textTween:B6,remove:k6,tween:KF,delay:c6,duration:f6,ease:m6,easeVarying:p6,end:W6,[Symbol.iterator]:Ja[Symbol.iterator]};function H6(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var V6={time:null,delay:0,duration:250,ease:H6};function G6(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 K6(e){var t,n;e instanceof ol?(t=e._id,e=e._name):(t=r$(),(n=V6).time=vx(),e=e==null?null:e+"");for(var r=this._groups,i=r.length,o=0;o<i;++o)for(var u=r[o],l=u.length,d,h=0;h<l;++h)(d=u[h])&&zg(d,e,t,h,u,n||G6(d,t));return new ol(r,this._parents,e,t)}Tm.prototype.interrupt=HF;Tm.prototype.transition=K6;const dp=e=>()=>e;function J6(e,{sourceEvent:t,target:n,transform:r,dispatch:i}){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:i}})}function Qa(e,t,n){this.k=e,this.x=t,this.y=n}Qa.prototype={constructor:Qa,scale:function(e){return e===1?this:new Qa(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Qa(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 tl=new Qa(1,0,0);Qa.prototype;function nw(e){e.stopImmediatePropagation()}function jh(e){e.preventDefault(),e.stopImmediatePropagation()}function Y6(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function X6(){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 kk(){return this.__zoom||tl}function Z6(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function Q6(){return navigator.maxTouchPoints||"ontouchstart"in this}function e8(e,t,n){var r=e.invertX(t[0][0])-n[0][0],i=e.invertX(t[1][0])-n[1][0],o=e.invertY(t[0][1])-n[0][1],u=e.invertY(t[1][1])-n[1][1];return e.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),u>o?(o+u)/2:Math.min(0,o)||Math.max(0,u))}function i$(){var e=Y6,t=X6,n=e8,r=Z6,i=Q6,o=[0,1/0],u=[[-1/0,-1/0],[1/0,1/0]],l=250,d=PF,h=Pg("start","zoom","end"),m,_,g,y=500,b=150,k=0,x=10;function N(A){A.property("__zoom",kk).on("wheel.zoom",I,{passive:!1}).on("mousedown.zoom",W).on("dblclick.zoom",G).filter(i).on("touchstart.zoom",K).on("touchmove.zoom",H).on("touchend.zoom touchcancel.zoom",M).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}N.transform=function(A,O,L,V){var J=A.selection?A.selection():A;J.property("__zoom",kk),A!==J?P(A,O,L,V):J.interrupt().each(function(){D(this,arguments).event(V).start().zoom(null,typeof O=="function"?O.apply(this,arguments):O).end()})},N.scaleBy=function(A,O,L,V){N.scaleTo(A,function(){var J=this.__zoom.k,U=typeof O=="function"?O.apply(this,arguments):O;return J*U},L,V)},N.scaleTo=function(A,O,L,V){N.transform(A,function(){var J=t.apply(this,arguments),U=this.__zoom,te=L==null?S(J):typeof L=="function"?L.apply(this,arguments):L,z=U.invert(te),ne=typeof O=="function"?O.apply(this,arguments):O;return n(E($(U,ne),te,z),J,u)},L,V)},N.translateBy=function(A,O,L,V){N.transform(A,function(){return n(this.__zoom.translate(typeof O=="function"?O.apply(this,arguments):O,typeof L=="function"?L.apply(this,arguments):L),t.apply(this,arguments),u)},null,V)},N.translateTo=function(A,O,L,V,J){N.transform(A,function(){var U=t.apply(this,arguments),te=this.__zoom,z=V==null?S(U):typeof V=="function"?V.apply(this,arguments):V;return n(tl.translate(z[0],z[1]).scale(te.k).translate(typeof O=="function"?-O.apply(this,arguments):-O,typeof L=="function"?-L.apply(this,arguments):-L),U,u)},V,J)};function $(A,O){return O=Math.max(o[0],Math.min(o[1],O)),O===A.k?A:new Qa(O,A.x,A.y)}function E(A,O,L){var V=O[0]-L[0]*A.k,J=O[1]-L[1]*A.k;return V===A.x&&J===A.y?A:new Qa(A.k,V,J)}function S(A){return[(+A[0][0]+ +A[1][0])/2,(+A[0][1]+ +A[1][1])/2]}function P(A,O,L,V){A.on("start.zoom",function(){D(this,arguments).event(V).start()}).on("interrupt.zoom end.zoom",function(){D(this,arguments).event(V).end()}).tween("zoom",function(){var J=this,U=arguments,te=D(J,U).event(V),z=t.apply(J,U),ne=L==null?S(z):typeof L=="function"?L.apply(J,U):L,se=Math.max(z[1][0]-z[0][0],z[1][1]-z[0][1]),de=J.__zoom,be=typeof O=="function"?O.apply(J,U):O,Me=d(de.invert(ne).concat(se/de.k),be.invert(ne).concat(se/be.k));return function(je){if(je===1)je=be;else{var ae=Me(je),xe=se/ae[2];je=new Qa(xe,ne[0]-ae[0]*xe,ne[1]-ae[1]*xe)}te.zoom(null,je)}})}function D(A,O,L){return!L&&A.__zooming||new R(A,O)}function R(A,O){this.that=A,this.args=O,this.active=0,this.sourceEvent=null,this.extent=t.apply(A,O),this.taps=0}R.prototype={event:function(A){return A&&(this.sourceEvent=A),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(A,O){return this.mouse&&A!=="mouse"&&(this.mouse[1]=O.invert(this.mouse[0])),this.touch0&&A!=="touch"&&(this.touch0[1]=O.invert(this.touch0[0])),this.touch1&&A!=="touch"&&(this.touch1[1]=O.invert(this.touch1[0])),this.that.__zoom=O,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(A){var O=yo(this.that).datum();h.call(A,this.that,new J6(A,{sourceEvent:this.sourceEvent,target:N,transform:this.that.__zoom,dispatch:h}),O)}};function I(A,...O){if(!e.apply(this,arguments))return;var L=D(this,O).event(A),V=this.__zoom,J=Math.max(o[0],Math.min(o[1],V.k*Math.pow(2,r.apply(this,arguments)))),U=qo(A);if(L.wheel)(L.mouse[0][0]!==U[0]||L.mouse[0][1]!==U[1])&&(L.mouse[1]=V.invert(L.mouse[0]=U)),clearTimeout(L.wheel);else{if(V.k===J)return;L.mouse=[U,V.invert(U)],Ip(this),L.start()}jh(A),L.wheel=setTimeout(te,b),L.zoom("mouse",n(E($(V,J),L.mouse[0],L.mouse[1]),L.extent,u));function te(){L.wheel=null,L.end()}}function W(A,...O){if(g||!e.apply(this,arguments))return;var L=A.currentTarget,V=D(this,O,!0).event(A),J=yo(A.view).on("mousemove.zoom",ne,!0).on("mouseup.zoom",se,!0),U=qo(A,L),te=A.clientX,z=A.clientY;q1(A.view),nw(A),V.mouse=[U,this.__zoom.invert(U)],Ip(this),V.start();function ne(de){if(jh(de),!V.moved){var be=de.clientX-te,Me=de.clientY-z;V.moved=be*be+Me*Me>k}V.event(de).zoom("mouse",n(E(V.that.__zoom,V.mouse[0]=qo(de,L),V.mouse[1]),V.extent,u))}function se(de){J.on("mousemove.zoom mouseup.zoom",null),H1(de.view,V.moved),jh(de),V.event(de).end()}}function G(A,...O){if(e.apply(this,arguments)){var L=this.__zoom,V=qo(A.changedTouches?A.changedTouches[0]:A,this),J=L.invert(V),U=L.k*(A.shiftKey?.5:2),te=n(E($(L,U),V,J),t.apply(this,O),u);jh(A),l>0?yo(this).transition().duration(l).call(P,te,V,A):yo(this).call(N.transform,te,V,A)}}function K(A,...O){if(e.apply(this,arguments)){var L=A.touches,V=L.length,J=D(this,O,A.changedTouches.length===V).event(A),U,te,z,ne;for(nw(A),te=0;te<V;++te)z=L[te],ne=qo(z,this),ne=[ne,this.__zoom.invert(ne),z.identifier],J.touch0?!J.touch1&&J.touch0[2]!==ne[2]&&(J.touch1=ne,J.taps=0):(J.touch0=ne,U=!0,J.taps=1+!!m);m&&(m=clearTimeout(m)),U&&(J.taps<2&&(_=ne[0],m=setTimeout(function(){m=null},y)),Ip(this),J.start())}}function H(A,...O){if(this.__zooming){var L=D(this,O).event(A),V=A.changedTouches,J=V.length,U,te,z,ne;for(jh(A),U=0;U<J;++U)te=V[U],z=qo(te,this),L.touch0&&L.touch0[2]===te.identifier?L.touch0[0]=z:L.touch1&&L.touch1[2]===te.identifier&&(L.touch1[0]=z);if(te=L.that.__zoom,L.touch1){var se=L.touch0[0],de=L.touch0[1],be=L.touch1[0],Me=L.touch1[1],je=(je=be[0]-se[0])*je+(je=be[1]-se[1])*je,ae=(ae=Me[0]-de[0])*ae+(ae=Me[1]-de[1])*ae;te=$(te,Math.sqrt(je/ae)),z=[(se[0]+be[0])/2,(se[1]+be[1])/2],ne=[(de[0]+Me[0])/2,(de[1]+Me[1])/2]}else if(L.touch0)z=L.touch0[0],ne=L.touch0[1];else return;L.zoom("touch",n(E(te,z,ne),L.extent,u))}}function M(A,...O){if(this.__zooming){var L=D(this,O).event(A),V=A.changedTouches,J=V.length,U,te;for(nw(A),g&&clearTimeout(g),g=setTimeout(function(){g=null},y),U=0;U<J;++U)te=V[U],L.touch0&&L.touch0[2]===te.identifier?delete L.touch0:L.touch1&&L.touch1[2]===te.identifier&&delete L.touch1;if(L.touch1&&!L.touch0&&(L.touch0=L.touch1,delete L.touch1),L.touch0)L.touch0[1]=this.__zoom.invert(L.touch0[0]);else if(L.end(),L.taps===2&&(te=qo(te,this),Math.hypot(_[0]-te[0],_[1]-te[1])<x)){var z=yo(this).on("dblclick.zoom");z&&z.apply(this,arguments)}}}return N.wheelDelta=function(A){return arguments.length?(r=typeof A=="function"?A:dp(+A),N):r},N.filter=function(A){return arguments.length?(e=typeof A=="function"?A:dp(!!A),N):e},N.touchable=function(A){return arguments.length?(i=typeof A=="function"?A:dp(!!A),N):i},N.extent=function(A){return arguments.length?(t=typeof A=="function"?A:dp([[+A[0][0],+A[0][1]],[+A[1][0],+A[1][1]]]),N):t},N.scaleExtent=function(A){return arguments.length?(o[0]=+A[0],o[1]=+A[1],N):[o[0],o[1]]},N.translateExtent=function(A){return arguments.length?(u[0][0]=+A[0][0],u[1][0]=+A[1][0],u[0][1]=+A[0][1],u[1][1]=+A[1][1],N):[[u[0][0],u[0][1]],[u[1][0],u[1][1]]]},N.constrain=function(A){return arguments.length?(n=A,N):n},N.duration=function(A){return arguments.length?(l=+A,N):l},N.interpolate=function(A){return arguments.length?(d=A,N):d},N.on=function(){var A=h.on.apply(h,arguments);return A===h?N:A},N.clickDistance=function(A){return arguments.length?(k=(A=+A)*A,N):Math.sqrt(k)},N.tapDistance=function(A){return arguments.length?(x=+A,N):x},N}const Bg=p.createContext(null),t8=Bg.Provider,al={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,t)=>`Couldn't create edge for ${e?"target":"source"} handle id: "${e?t.targetHandle:t.sourceHandle}", edge id: ${t.id}.`,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.`},o$=al.error001();function fs(e,t){const n=p.useContext(Bg);if(n===null)throw new Error(o$);return T1(n,e,t)}const er=()=>{const e=p.useContext(Bg);if(e===null)throw new Error(o$);return p.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},n8=e=>e.userSelectionActive?"none":"all";function um({position:e,children:t,className:n,style:r,...i}){const o=fs(n8),u=`${e}`.split("-");return Ee.createElement("div",{className:Cr(["react-flow__panel",n,...u]),style:{...r,pointerEvents:o},...i},t)}function s8({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:Ee.createElement(um,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://reactflow.dev/pro"},Ee.createElement("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution"},"React Flow"))}const r8=({x:e,y:t,label:n,labelStyle:r={},labelShowBg:i=!0,labelBgStyle:o={},labelBgPadding:u=[2,4],labelBgBorderRadius:l=2,children:d,className:h,...m})=>{const _=p.useRef(null),[g,y]=p.useState({x:0,y:0,width:0,height:0}),b=Cr(["react-flow__edge-textwrapper",h]);return p.useEffect(()=>{if(_.current){const k=_.current.getBBox();y({x:k.x,y:k.y,width:k.width,height:k.height})}},[n]),typeof n>"u"||!n?null:Ee.createElement("g",{transform:`translate(${e-g.width/2} ${t-g.height/2})`,className:b,visibility:g.width?"visible":"hidden",...m},i&&Ee.createElement("rect",{width:g.width+2*u[0],x:-u[0],y:-u[1],height:g.height+2*u[1],className:"react-flow__edge-textbg",style:o,rx:l,ry:l}),Ee.createElement("text",{className:"react-flow__edge-text",y:g.height/2,dy:"0.3em",ref:_,style:r},n),d)};var i8=p.memo(r8);const kx=e=>({width:e.offsetWidth,height:e.offsetHeight}),ef=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),jx=(e={x:0,y:0},t)=>({x:ef(e.x,t[0][0],t[1][0]),y:ef(e.y,t[0][1],t[1][1])}),jk=(e,t,n)=>e<t?ef(Math.abs(e-t),1,50)/50:e>n?-ef(Math.abs(e-n),1,50)/50:0,a$=(e,t)=>{const n=jk(e.x,35,t.width-35)*20,r=jk(e.y,35,t.height-35)*20;return[n,r]},l$=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},c$=(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)}),dm=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),u$=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Sk=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),o8=(e,t)=>u$(c$(dm(e),dm(t))),_v=(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)},a8=e=>wo(e.width)&&wo(e.height)&&wo(e.x)&&wo(e.y),wo=e=>!isNaN(e)&&isFinite(e),Vs=Symbol.for("internals"),d$=["Enter"," ","Escape"],l8=(e,t)=>{},c8=e=>"nativeEvent"in e;function pv(e){var i,o;const t=c8(e)?e.nativeEvent:e,n=((o=(i=t.composedPath)==null?void 0:i.call(t))==null?void 0:o[0])||e.target;return["INPUT","SELECT","TEXTAREA"].includes(n==null?void 0:n.nodeName)||(n==null?void 0:n.hasAttribute("contenteditable"))||!!(n!=null&&n.closest(".nokey"))}const f$=e=>"clientX"in e,oc=(e,t)=>{var o,u;const n=f$(e),r=n?e.clientX:(o=e.touches)==null?void 0:o[0].clientX,i=n?e.clientY:(u=e.touches)==null?void 0:u[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:i-((t==null?void 0:t.top)??0)}},ug=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0},Rm=({id:e,path:t,labelX:n,labelY:r,label:i,labelStyle:o,labelShowBg:u,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,markerEnd:_,markerStart:g,interactionWidth:y=20})=>Ee.createElement(Ee.Fragment,null,Ee.createElement("path",{id:e,style:m,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:_,markerStart:g}),y&&Ee.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:y,className:"react-flow__edge-interaction"}),i&&wo(n)&&wo(r)?Ee.createElement(i8,{x:n,y:r,label:i,labelStyle:o,labelShowBg:u,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h}):null);Rm.displayName="BaseEdge";function Sh(e,t,n){return n===void 0?n:r=>{const i=t().edges.find(o=>o.id===e);i&&n(r,{...i})}}function h$({sourceX:e,sourceY:t,targetX:n,targetY:r}){const i=Math.abs(n-e)/2,o=n<e?n+i:n-i,u=Math.abs(r-t)/2,l=r<t?r+u:r-u;return[o,l,i,u]}function m$({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:i,sourceControlY:o,targetControlX:u,targetControlY:l}){const d=e*.125+i*.375+u*.375+n*.125,h=t*.125+o*.375+l*.375+r*.125,m=Math.abs(d-e),_=Math.abs(h-t);return[d,h,m,_]}var wu;(function(e){e.Strict="strict",e.Loose="loose"})(wu||(wu={}));var iu;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(iu||(iu={}));var fm;(function(e){e.Partial="partial",e.Full="full"})(fm||(fm={}));var tc;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(tc||(tc={}));var hm;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(hm||(hm={}));var Ut;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(Ut||(Ut={}));function Nk({pos:e,x1:t,y1:n,x2:r,y2:i}){return e===Ut.Left||e===Ut.Right?[.5*(t+r),n]:[t,.5*(n+i)]}function _$({sourceX:e,sourceY:t,sourcePosition:n=Ut.Bottom,targetX:r,targetY:i,targetPosition:o=Ut.Top}){const[u,l]=Nk({pos:n,x1:e,y1:t,x2:r,y2:i}),[d,h]=Nk({pos:o,x1:r,y1:i,x2:e,y2:t}),[m,_,g,y]=m$({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:u,sourceControlY:l,targetControlX:d,targetControlY:h});return[`M${e},${t} C${u},${l} ${d},${h} ${r},${i}`,m,_,g,y]}const Sx=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:i=Ut.Bottom,targetPosition:o=Ut.Top,label:u,labelStyle:l,labelShowBg:d,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:_,style:g,markerEnd:y,markerStart:b,interactionWidth:k})=>{const[x,N,$]=_$({sourceX:e,sourceY:t,sourcePosition:i,targetX:n,targetY:r,targetPosition:o});return Ee.createElement(Rm,{path:x,labelX:N,labelY:$,label:u,labelStyle:l,labelShowBg:d,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:_,style:g,markerEnd:y,markerStart:b,interactionWidth:k})});Sx.displayName="SimpleBezierEdge";const $k={[Ut.Left]:{x:-1,y:0},[Ut.Right]:{x:1,y:0},[Ut.Top]:{x:0,y:-1},[Ut.Bottom]:{x:0,y:1}},u8=({source:e,sourcePosition:t=Ut.Bottom,target:n})=>t===Ut.Left||t===Ut.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},Ck=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function d8({source:e,sourcePosition:t=Ut.Bottom,target:n,targetPosition:r=Ut.Top,center:i,offset:o}){const u=$k[t],l=$k[r],d={x:e.x+u.x*o,y:e.y+u.y*o},h={x:n.x+l.x*o,y:n.y+l.y*o},m=u8({source:d,sourcePosition:t,target:h}),_=m.x!==0?"x":"y",g=m[_];let y=[],b,k;const x={x:0,y:0},N={x:0,y:0},[$,E,S,P]=h$({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(u[_]*l[_]===-1){b=i.x||$,k=i.y||E;const R=[{x:b,y:d.y},{x:b,y:h.y}],I=[{x:d.x,y:k},{x:h.x,y:k}];u[_]===g?y=_==="x"?R:I:y=_==="x"?I:R}else{const R=[{x:d.x,y:h.y}],I=[{x:h.x,y:d.y}];if(_==="x"?y=u.x===g?I:R:y=u.y===g?R:I,t===r){const M=Math.abs(e[_]-n[_]);if(M<=o){const A=Math.min(o-1,o-M);u[_]===g?x[_]=(d[_]>e[_]?-1:1)*A:N[_]=(h[_]>n[_]?-1:1)*A}}if(t!==r){const M=_==="x"?"y":"x",A=u[_]===l[M],O=d[M]>h[M],L=d[M]<h[M];(u[_]===1&&(!A&&O||A&&L)||u[_]!==1&&(!A&&L||A&&O))&&(y=_==="x"?R:I)}const W={x:d.x+x.x,y:d.y+x.y},G={x:h.x+N.x,y:h.y+N.y},K=Math.max(Math.abs(W.x-y[0].x),Math.abs(G.x-y[0].x)),H=Math.max(Math.abs(W.y-y[0].y),Math.abs(G.y-y[0].y));K>=H?(b=(W.x+G.x)/2,k=y[0].y):(b=y[0].x,k=(W.y+G.y)/2)}return[[e,{x:d.x+x.x,y:d.y+x.y},...y,{x:h.x+N.x,y:h.y+N.y},n],b,k,S,P]}function f8(e,t,n,r){const i=Math.min(Ck(e,t)/2,Ck(t,n)/2,r),{x:o,y:u}=t;if(e.x===o&&o===n.x||e.y===u&&u===n.y)return`L${o} ${u}`;if(e.y===u){const h=e.x<n.x?-1:1,m=e.y<n.y?1:-1;return`L ${o+i*h},${u}Q ${o},${u} ${o},${u+i*m}`}const l=e.x<n.x?1:-1,d=e.y<n.y?-1:1;return`L ${o},${u+i*d}Q ${o},${u} ${o+i*l},${u}`}function gv({sourceX:e,sourceY:t,sourcePosition:n=Ut.Bottom,targetX:r,targetY:i,targetPosition:o=Ut.Top,borderRadius:u=5,centerX:l,centerY:d,offset:h=20}){const[m,_,g,y,b]=d8({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:i},targetPosition:o,center:{x:l,y:d},offset:h});return[m.reduce((x,N,$)=>{let E="";return $>0&&$<m.length-1?E=f8(m[$-1],N,m[$+1],u):E=`${$===0?"M":"L"}${N.x} ${N.y}`,x+=E,x},""),_,g,y,b]}const Ug=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:i,labelStyle:o,labelShowBg:u,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,sourcePosition:_=Ut.Bottom,targetPosition:g=Ut.Top,markerEnd:y,markerStart:b,pathOptions:k,interactionWidth:x})=>{const[N,$,E]=gv({sourceX:e,sourceY:t,sourcePosition:_,targetX:n,targetY:r,targetPosition:g,borderRadius:k==null?void 0:k.borderRadius,offset:k==null?void 0:k.offset});return Ee.createElement(Rm,{path:N,labelX:$,labelY:E,label:i,labelStyle:o,labelShowBg:u,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,markerEnd:y,markerStart:b,interactionWidth:x})});Ug.displayName="SmoothStepEdge";const Nx=p.memo(e=>{var t;return Ee.createElement(Ug,{...e,pathOptions:p.useMemo(()=>{var n;return{borderRadius:0,offset:(n=e.pathOptions)==null?void 0:n.offset}},[(t=e.pathOptions)==null?void 0:t.offset])})});Nx.displayName="StepEdge";function h8({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[i,o,u,l]=h$({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,i,o,u,l]}const $x=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:i,labelStyle:o,labelShowBg:u,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,markerEnd:_,markerStart:g,interactionWidth:y})=>{const[b,k,x]=h8({sourceX:e,sourceY:t,targetX:n,targetY:r});return Ee.createElement(Rm,{path:b,labelX:k,labelY:x,label:i,labelStyle:o,labelShowBg:u,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,markerEnd:_,markerStart:g,interactionWidth:y})});$x.displayName="StraightEdge";function fp(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Ek({pos:e,x1:t,y1:n,x2:r,y2:i,c:o}){switch(e){case Ut.Left:return[t-fp(t-r,o),n];case Ut.Right:return[t+fp(r-t,o),n];case Ut.Top:return[t,n-fp(n-i,o)];case Ut.Bottom:return[t,n+fp(i-n,o)]}}function p$({sourceX:e,sourceY:t,sourcePosition:n=Ut.Bottom,targetX:r,targetY:i,targetPosition:o=Ut.Top,curvature:u=.25}){const[l,d]=Ek({pos:n,x1:e,y1:t,x2:r,y2:i,c:u}),[h,m]=Ek({pos:o,x1:r,y1:i,x2:e,y2:t,c:u}),[_,g,y,b]=m$({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:l,sourceControlY:d,targetControlX:h,targetControlY:m});return[`M${e},${t} C${l},${d} ${h},${m} ${r},${i}`,_,g,y,b]}const dg=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:i=Ut.Bottom,targetPosition:o=Ut.Top,label:u,labelStyle:l,labelShowBg:d,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:_,style:g,markerEnd:y,markerStart:b,pathOptions:k,interactionWidth:x})=>{const[N,$,E]=p$({sourceX:e,sourceY:t,sourcePosition:i,targetX:n,targetY:r,targetPosition:o,curvature:k==null?void 0:k.curvature});return Ee.createElement(Rm,{path:N,labelX:$,labelY:E,label:u,labelStyle:l,labelShowBg:d,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:_,style:g,markerEnd:y,markerStart:b,interactionWidth:x})});dg.displayName="BezierEdge";const Cx=p.createContext(null),m8=Cx.Provider;Cx.Consumer;const _8=()=>p.useContext(Cx),p8=e=>"id"in e&&"source"in e&&"target"in e,g8=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`reactflow__edge-${e}${t||""}-${n}${r||""}`,yv=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`,y8=(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)),w8=(e,t)=>{if(!e.source||!e.target)return t;let n;return p8(e)?n={...e}:n={...e,id:g8(e)},y8(n,t)?t:t.concat(n)},wv=({x:e,y:t},[n,r,i],o,[u,l])=>{const d={x:(e-n)/i,y:(t-r)/i};return o?{x:u*Math.round(d.x/u),y:l*Math.round(d.y/l)}:d},g$=({x:e,y:t},[n,r,i])=>({x:e*i+n,y:t*i+r}),uu=(e,t=[0,0])=>{if(!e)return{x:0,y:0,positionAbsolute:{x:0,y:0}};const n=(e.width??0)*t[0],r=(e.height??0)*t[1],i={x:e.position.x-n,y:e.position.y-r};return{...i,positionAbsolute:e.positionAbsolute?{x:e.positionAbsolute.x-n,y:e.positionAbsolute.y-r}:i}},Wg=(e,t=[0,0])=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,i)=>{const{x:o,y:u}=uu(i,t).positionAbsolute;return c$(r,dm({x:o,y:u,width:i.width||0,height:i.height||0}))},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return u$(n)},y$=(e,t,[n,r,i]=[0,0,1],o=!1,u=!1,l=[0,0])=>{const d={x:(t.x-n)/i,y:(t.y-r)/i,width:t.width/i,height:t.height/i},h=[];return e.forEach(m=>{const{width:_,height:g,selectable:y=!0,hidden:b=!1}=m;if(u&&!y||b)return!1;const{positionAbsolute:k}=uu(m,l),x={x:k.x,y:k.y,width:_||0,height:g||0},N=_v(d,x),$=typeof _>"u"||typeof g>"u"||_===null||g===null,E=o&&N>0,S=(_||0)*(g||0);($||E||N>=S||m.dragging)&&h.push(m)}),h},w$=(e,t)=>{const n=e.map(r=>r.id);return t.filter(r=>n.includes(r.source)||n.includes(r.target))},v$=(e,t,n,r,i,o=.1)=>{const u=t/(e.width*(1+o)),l=n/(e.height*(1+o)),d=Math.min(u,l),h=ef(d,r,i),m=e.x+e.width/2,_=e.y+e.height/2,g=t/2-m*h,y=n/2-_*h;return{x:g,y,zoom:h}},tu=(e,t=0)=>e.transition().duration(t);function Ak(e,t,n,r){return(t[n]||[]).reduce((i,o)=>{var u,l;return`${e.id}-${o.id}-${n}`!==r&&i.push({id:o.id||null,type:n,nodeId:e.id,x:(((u=e.positionAbsolute)==null?void 0:u.x)??0)+o.x+o.width/2,y:(((l=e.positionAbsolute)==null?void 0:l.y)??0)+o.y+o.height/2}),i},[])}function v8(e,t,n,r,i,o){const{x:u,y:l}=oc(e),h=t.elementsFromPoint(u,l).find(b=>b.classList.contains("react-flow__handle"));if(h){const b=h.getAttribute("data-nodeid");if(b){const k=Ex(void 0,h),x=h.getAttribute("data-handleid"),N=o({nodeId:b,id:x,type:k});if(N){const $=i.find(E=>E.nodeId===b&&E.type===k&&E.id===x);return{handle:{id:x,type:k,nodeId:b,x:($==null?void 0:$.x)||n.x,y:($==null?void 0:$.y)||n.y},validHandleResult:N}}}}let m=[],_=1/0;if(i.forEach(b=>{const k=Math.sqrt((b.x-n.x)**2+(b.y-n.y)**2);if(k<=r){const x=o(b);k<=_&&(k<_?m=[{handle:b,validHandleResult:x}]:k===_&&m.push({handle:b,validHandleResult:x}),_=k)}}),!m.length)return{handle:null,validHandleResult:x$()};if(m.length===1)return m[0];const g=m.some(({validHandleResult:b})=>b.isValid),y=m.some(({handle:b})=>b.type==="target");return m.find(({handle:b,validHandleResult:k})=>y?b.type==="target":g?k.isValid:!0)||m[0]}const x8={source:null,target:null,sourceHandle:null,targetHandle:null},x$=()=>({handleDomNode:null,isValid:!1,connection:x8,endHandle:null});function b$(e,t,n,r,i,o,u){const l=i==="target",d=u.querySelector(`.react-flow__handle[data-id="${e==null?void 0:e.nodeId}-${e==null?void 0:e.id}-${e==null?void 0:e.type}"]`),h={...x$(),handleDomNode:d};if(d){const m=Ex(void 0,d),_=d.getAttribute("data-nodeid"),g=d.getAttribute("data-handleid"),y=d.classList.contains("connectable"),b=d.classList.contains("connectableend"),k={source:l?_:n,sourceHandle:l?g:r,target:l?n:_,targetHandle:l?r:g};h.connection=k,y&&b&&(t===wu.Strict?l&&m==="source"||!l&&m==="target":_!==n||g!==r)&&(h.endHandle={nodeId:_,handleId:g,type:m},h.isValid=o(k))}return h}function b8({nodes:e,nodeId:t,handleId:n,handleType:r}){return e.reduce((i,o)=>{if(o[Vs]){const{handleBounds:u}=o[Vs];let l=[],d=[];u&&(l=Ak(o,u,"source",`${t}-${n}-${r}`),d=Ak(o,u,"target",`${t}-${n}-${r}`)),i.push(...l,...d)}return i},[])}function Ex(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function sw(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function k8(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function k$({event:e,handleId:t,nodeId:n,onConnect:r,isTarget:i,getState:o,setState:u,isValidConnection:l,edgeUpdaterType:d,onEdgeUpdateEnd:h}){const m=l$(e.target),{connectionMode:_,domNode:g,autoPanOnConnect:y,connectionRadius:b,onConnectStart:k,panBy:x,getNodes:N,cancelConnection:$}=o();let E=0,S;const{x:P,y:D}=oc(e),R=m==null?void 0:m.elementFromPoint(P,D),I=Ex(d,R),W=g==null?void 0:g.getBoundingClientRect();if(!W||!I)return;let G,K=oc(e,W),H=!1,M=null,A=!1,O=null;const L=b8({nodes:N(),nodeId:n,handleId:t,handleType:I}),V=()=>{if(!y)return;const[te,z]=a$(K,W);x({x:te,y:z}),E=requestAnimationFrame(V)};u({connectionPosition:K,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:I,connectionStartHandle:{nodeId:n,handleId:t,type:I},connectionEndHandle:null}),k==null||k(e,{nodeId:n,handleId:t,handleType:I});function J(te){const{transform:z}=o();K=oc(te,W);const{handle:ne,validHandleResult:se}=v8(te,m,wv(K,z,!1,[1,1]),b,L,de=>b$(de,_,n,t,i?"target":"source",l,m));if(S=ne,H||(V(),H=!0),O=se.handleDomNode,M=se.connection,A=se.isValid,u({connectionPosition:S&&A?g$({x:S.x,y:S.y},z):K,connectionStatus:k8(!!S,A),connectionEndHandle:se.endHandle}),!S&&!A&&!O)return sw(G);M.source!==M.target&&O&&(sw(G),G=O,O.classList.add("connecting","react-flow__handle-connecting"),O.classList.toggle("valid",A),O.classList.toggle("react-flow__handle-valid",A))}function U(te){var z,ne;(S||O)&&M&&A&&(r==null||r(M)),(ne=(z=o()).onConnectEnd)==null||ne.call(z,te),d&&(h==null||h(te)),sw(G),$(),cancelAnimationFrame(E),H=!1,A=!1,M=null,O=null,m.removeEventListener("mousemove",J),m.removeEventListener("mouseup",U),m.removeEventListener("touchmove",J),m.removeEventListener("touchend",U)}m.addEventListener("mousemove",J),m.addEventListener("mouseup",U),m.addEventListener("touchmove",J),m.addEventListener("touchend",U)}const Tk=()=>!0,j8=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),S8=(e,t,n)=>r=>{const{connectionStartHandle:i,connectionEndHandle:o,connectionClickStartHandle:u}=r;return{connecting:(i==null?void 0:i.nodeId)===e&&(i==null?void 0:i.handleId)===t&&(i==null?void 0:i.type)===n||(o==null?void 0:o.nodeId)===e&&(o==null?void 0:o.handleId)===t&&(o==null?void 0:o.type)===n,clickConnecting:(u==null?void 0:u.nodeId)===e&&(u==null?void 0:u.handleId)===t&&(u==null?void 0:u.type)===n}},j$=p.forwardRef(({type:e="source",position:t=Ut.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:i=!0,isConnectableEnd:o=!0,id:u,onConnect:l,children:d,className:h,onMouseDown:m,onTouchStart:_,...g},y)=>{var W,G;const b=u||null,k=e==="target",x=er(),N=_8(),{connectOnClick:$,noPanClassName:E}=fs(j8,hr),{connecting:S,clickConnecting:P}=fs(S8(N,b,e),hr);N||(G=(W=x.getState()).onError)==null||G.call(W,"010",al.error010());const D=K=>{const{defaultEdgeOptions:H,onConnect:M,hasDefaultEdges:A}=x.getState(),O={...H,...K};if(A){const{edges:L,setEdges:V}=x.getState();V(w8(O,L))}M==null||M(O),l==null||l(O)},R=K=>{if(!N)return;const H=f$(K);i&&(H&&K.button===0||!H)&&k$({event:K,handleId:b,nodeId:N,onConnect:D,isTarget:k,getState:x.getState,setState:x.setState,isValidConnection:n||x.getState().isValidConnection||Tk}),H?m==null||m(K):_==null||_(K)},I=K=>{const{onClickConnectStart:H,onClickConnectEnd:M,connectionClickStartHandle:A,connectionMode:O,isValidConnection:L}=x.getState();if(!N||!A&&!i)return;if(!A){H==null||H(K,{nodeId:N,handleId:b,handleType:e}),x.setState({connectionClickStartHandle:{nodeId:N,type:e,handleId:b}});return}const V=l$(K.target),J=n||L||Tk,{connection:U,isValid:te}=b$({nodeId:N,id:b,type:e},O,A.nodeId,A.handleId||null,A.type,J,V);te&&D(U),M==null||M(K),x.setState({connectionClickStartHandle:null})};return Ee.createElement("div",{"data-handleid":b,"data-nodeid":N,"data-handlepos":t,"data-id":`${N}-${b}-${e}`,className:Cr(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",E,h,{source:!k,target:k,connectable:r,connectablestart:i,connectableend:o,connecting:P,connectionindicator:r&&(i&&!S||o&&S)}]),onMouseDown:R,onTouchStart:R,onClick:$?I:void 0,ref:y,...g},d)});j$.displayName="Handle";var fg=p.memo(j$);const S$=({data:e,isConnectable:t,targetPosition:n=Ut.Top,sourcePosition:r=Ut.Bottom})=>Ee.createElement(Ee.Fragment,null,Ee.createElement(fg,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,Ee.createElement(fg,{type:"source",position:r,isConnectable:t}));S$.displayName="DefaultNode";var vv=p.memo(S$);const N$=({data:e,isConnectable:t,sourcePosition:n=Ut.Bottom})=>Ee.createElement(Ee.Fragment,null,e==null?void 0:e.label,Ee.createElement(fg,{type:"source",position:n,isConnectable:t}));N$.displayName="InputNode";var $$=p.memo(N$);const C$=({data:e,isConnectable:t,targetPosition:n=Ut.Top})=>Ee.createElement(Ee.Fragment,null,Ee.createElement(fg,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);C$.displayName="OutputNode";var E$=p.memo(C$);const Ax=()=>null;Ax.displayName="GroupNode";const N8=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),hp=e=>e.id;function $8(e,t){return hr(e.selectedNodes.map(hp),t.selectedNodes.map(hp))&&hr(e.selectedEdges.map(hp),t.selectedEdges.map(hp))}const A$=p.memo(({onSelectionChange:e})=>{const t=er(),{selectedNodes:n,selectedEdges:r}=fs(N8,$8);return p.useEffect(()=>{const i={nodes:n,edges:r};e==null||e(i),t.getState().onSelectionChange.forEach(o=>o(i))},[n,r,e]),null});A$.displayName="SelectionListener";const C8=e=>!!e.onSelectionChange;function E8({onSelectionChange:e}){const t=fs(C8);return e||t?Ee.createElement(A$,{onSelectionChange:e}):null}const A8=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset});function bd(e,t){p.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function Sn(e,t,n){p.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const T8=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:i,onConnectStart:o,onConnectEnd:u,onClickConnectStart:l,onClickConnectEnd:d,nodesDraggable:h,nodesConnectable:m,nodesFocusable:_,edgesFocusable:g,edgesUpdatable:y,elevateNodesOnSelect:b,minZoom:k,maxZoom:x,nodeExtent:N,onNodesChange:$,onEdgesChange:E,elementsSelectable:S,connectionMode:P,snapGrid:D,snapToGrid:R,translateExtent:I,connectOnClick:W,defaultEdgeOptions:G,fitView:K,fitViewOptions:H,onNodesDelete:M,onEdgesDelete:A,onNodeDrag:O,onNodeDragStart:L,onNodeDragStop:V,onSelectionDrag:J,onSelectionDragStart:U,onSelectionDragStop:te,noPanClassName:z,nodeOrigin:ne,rfId:se,autoPanOnConnect:de,autoPanOnNodeDrag:be,onError:Me,connectionRadius:je,isValidConnection:ae,nodeDragThreshold:xe})=>{const{setNodes:Ae,setEdges:He,setDefaultNodesAndEdges:mt,setMinZoom:nt,setMaxZoom:rt,setTranslateExtent:ze,setNodeExtent:Ve,reset:ct}=fs(A8,hr),Qe=er();return p.useEffect(()=>{const Dt=r==null?void 0:r.map($e=>({...$e,...G}));return mt(n,Dt),()=>{ct()}},[]),Sn("defaultEdgeOptions",G,Qe.setState),Sn("connectionMode",P,Qe.setState),Sn("onConnect",i,Qe.setState),Sn("onConnectStart",o,Qe.setState),Sn("onConnectEnd",u,Qe.setState),Sn("onClickConnectStart",l,Qe.setState),Sn("onClickConnectEnd",d,Qe.setState),Sn("nodesDraggable",h,Qe.setState),Sn("nodesConnectable",m,Qe.setState),Sn("nodesFocusable",_,Qe.setState),Sn("edgesFocusable",g,Qe.setState),Sn("edgesUpdatable",y,Qe.setState),Sn("elementsSelectable",S,Qe.setState),Sn("elevateNodesOnSelect",b,Qe.setState),Sn("snapToGrid",R,Qe.setState),Sn("snapGrid",D,Qe.setState),Sn("onNodesChange",$,Qe.setState),Sn("onEdgesChange",E,Qe.setState),Sn("connectOnClick",W,Qe.setState),Sn("fitViewOnInit",K,Qe.setState),Sn("fitViewOnInitOptions",H,Qe.setState),Sn("onNodesDelete",M,Qe.setState),Sn("onEdgesDelete",A,Qe.setState),Sn("onNodeDrag",O,Qe.setState),Sn("onNodeDragStart",L,Qe.setState),Sn("onNodeDragStop",V,Qe.setState),Sn("onSelectionDrag",J,Qe.setState),Sn("onSelectionDragStart",U,Qe.setState),Sn("onSelectionDragStop",te,Qe.setState),Sn("noPanClassName",z,Qe.setState),Sn("nodeOrigin",ne,Qe.setState),Sn("rfId",se,Qe.setState),Sn("autoPanOnConnect",de,Qe.setState),Sn("autoPanOnNodeDrag",be,Qe.setState),Sn("onError",Me,Qe.setState),Sn("connectionRadius",je,Qe.setState),Sn("isValidConnection",ae,Qe.setState),Sn("nodeDragThreshold",xe,Qe.setState),bd(e,Ae),bd(t,He),bd(k,nt),bd(x,rt),bd(I,ze),bd(N,Ve),null},Mk={display:"none"},M8={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},T$="react-flow__node-desc",M$="react-flow__edge-desc",R8="react-flow__aria-live",L8=e=>e.ariaLiveMessage;function I8({rfId:e}){const t=fs(L8);return Ee.createElement("div",{id:`${R8}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:M8},t)}function O8({rfId:e,disableKeyboardA11y:t}){return Ee.createElement(Ee.Fragment,null,Ee.createElement("div",{id:`${T$}-${e}`,style:Mk},"Press enter or space to select a node.",!t&&"You can then use the arrow keys to move the node around."," Press delete to remove it and escape to cancel."," "),Ee.createElement("div",{id:`${M$}-${e}`,style:Mk},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&Ee.createElement(I8,{rfId:e}))}var mm=(e=null,t={actInsideInputWithModifier:!0})=>{const[n,r]=p.useState(!1),i=p.useRef(!1),o=p.useRef(new Set([])),[u,l]=p.useMemo(()=>{if(e!==null){const h=(Array.isArray(e)?e:[e]).filter(_=>typeof _=="string").map(_=>_.split("+")),m=h.reduce((_,g)=>_.concat(...g),[]);return[h,m]}return[[],[]]},[e]);return p.useEffect(()=>{const d=typeof document<"u"?document:null,h=(t==null?void 0:t.target)||d;if(e!==null){const m=y=>{if(i.current=y.ctrlKey||y.metaKey||y.shiftKey,(!i.current||i.current&&!t.actInsideInputWithModifier)&&pv(y))return!1;const k=Lk(y.code,l);o.current.add(y[k]),Rk(u,o.current,!1)&&(y.preventDefault(),r(!0))},_=y=>{if((!i.current||i.current&&!t.actInsideInputWithModifier)&&pv(y))return!1;const k=Lk(y.code,l);Rk(u,o.current,!0)?(r(!1),o.current.clear()):o.current.delete(y[k]),y.key==="Meta"&&o.current.clear(),i.current=!1},g=()=>{o.current.clear(),r(!1)};return h==null||h.addEventListener("keydown",m),h==null||h.addEventListener("keyup",_),window.addEventListener("blur",g),()=>{h==null||h.removeEventListener("keydown",m),h==null||h.removeEventListener("keyup",_),window.removeEventListener("blur",g)}}},[e,r]),n};function Rk(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(i=>t.has(i)))}function Lk(e,t){return t.includes(e)?"code":"key"}function R$(e,t,n,r){var u,l;if(!e.parentNode)return n;const i=t.get(e.parentNode),o=uu(i,r);return R$(i,t,{x:(n.x??0)+o.x,y:(n.y??0)+o.y,z:(((u=i[Vs])==null?void 0:u.z)??0)>(n.z??0)?((l=i[Vs])==null?void 0:l.z)??0:n.z??0},r)}function L$(e,t,n){e.forEach(r=>{var i;if(r.parentNode&&!e.has(r.parentNode))throw new Error(`Parent node ${r.parentNode} not found`);if(r.parentNode||n!=null&&n[r.id]){const{x:o,y:u,z:l}=R$(r,e,{...r.position,z:((i=r[Vs])==null?void 0:i.z)??0},t);r.positionAbsolute={x:o,y:u},r[Vs].z=l,n!=null&&n[r.id]&&(r[Vs].isParent=!0)}})}function rw(e,t,n,r){const i=new Map,o={},u=r?1e3:0;return e.forEach(l=>{var g;const d=(wo(l.zIndex)?l.zIndex:0)+(l.selected?u:0),h=t.get(l.id),m={...l,positionAbsolute:{x:l.position.x,y:l.position.y}};l.parentNode&&(o[l.parentNode]=!0);const _=(h==null?void 0:h.type)&&(h==null?void 0:h.type)!==l.type;Object.defineProperty(m,Vs,{enumerable:!1,value:{handleBounds:_||(g=h==null?void 0:h[Vs])==null?void 0:g.handleBounds,z:d}}),i.set(l.id,m)}),L$(i,n,o),i}function I$(e,t={}){const{getNodes:n,width:r,height:i,minZoom:o,maxZoom:u,d3Zoom:l,d3Selection:d,fitViewOnInitDone:h,fitViewOnInit:m,nodeOrigin:_}=e(),g=t.initial&&!h&&m;if(l&&d&&(g||!t.initial)){const b=n().filter(x=>{var $;const N=t.includeHiddenNodes?x.width&&x.height:!x.hidden;return($=t.nodes)!=null&&$.length?N&&t.nodes.some(E=>E.id===x.id):N}),k=b.every(x=>x.width&&x.height);if(b.length>0&&k){const x=Wg(b,_),{x:N,y:$,zoom:E}=v$(x,r,i,t.minZoom??o,t.maxZoom??u,t.padding??.1),S=tl.translate(N,$).scale(E);return typeof t.duration=="number"&&t.duration>0?l.transform(tu(d,t.duration),S):l.transform(d,S),!0}}return!1}function P8(e,t){return e.forEach(n=>{const r=t.get(n.id);r&&t.set(r.id,{...r,[Vs]:r[Vs],selected:n.selected})}),new Map(t)}function D8(e,t){return t.map(n=>{const r=e.find(i=>i.id===n.id);return r&&(n.selected=r.selected),n})}function mp({changedNodes:e,changedEdges:t,get:n,set:r}){const{nodeInternals:i,edges:o,onNodesChange:u,onEdgesChange:l,hasDefaultNodes:d,hasDefaultEdges:h}=n();e!=null&&e.length&&(d&&r({nodeInternals:P8(e,i)}),u==null||u(e)),t!=null&&t.length&&(h&&r({edges:D8(t,o)}),l==null||l(t))}const kd=()=>{},F8={zoomIn:kd,zoomOut:kd,zoomTo:kd,getZoom:()=>1,setViewport:kd,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:kd,fitBounds:kd,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},z8=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),B8=()=>{const e=er(),{d3Zoom:t,d3Selection:n}=fs(z8,hr);return p.useMemo(()=>n&&t?{zoomIn:i=>t.scaleBy(tu(n,i==null?void 0:i.duration),1.2),zoomOut:i=>t.scaleBy(tu(n,i==null?void 0:i.duration),1/1.2),zoomTo:(i,o)=>t.scaleTo(tu(n,o==null?void 0:o.duration),i),getZoom:()=>e.getState().transform[2],setViewport:(i,o)=>{const[u,l,d]=e.getState().transform,h=tl.translate(i.x??u,i.y??l).scale(i.zoom??d);t.transform(tu(n,o==null?void 0:o.duration),h)},getViewport:()=>{const[i,o,u]=e.getState().transform;return{x:i,y:o,zoom:u}},fitView:i=>I$(e.getState,i),setCenter:(i,o,u)=>{const{width:l,height:d,maxZoom:h}=e.getState(),m=typeof(u==null?void 0:u.zoom)<"u"?u.zoom:h,_=l/2-i*m,g=d/2-o*m,y=tl.translate(_,g).scale(m);t.transform(tu(n,u==null?void 0:u.duration),y)},fitBounds:(i,o)=>{const{width:u,height:l,minZoom:d,maxZoom:h}=e.getState(),{x:m,y:_,zoom:g}=v$(i,u,l,d,h,(o==null?void 0:o.padding)??.1),y=tl.translate(m,_).scale(g);t.transform(tu(n,o==null?void 0:o.duration),y)},project:i=>{const{transform:o,snapToGrid:u,snapGrid:l}=e.getState();return console.warn("[DEPRECATED] `project` is deprecated. Instead use `screenToFlowPosition`. There is no need to subtract the react flow bounds anymore! https://reactflow.dev/api-reference/types/react-flow-instance#screen-to-flow-position"),wv(i,o,u,l)},screenToFlowPosition:i=>{const{transform:o,snapToGrid:u,snapGrid:l,domNode:d}=e.getState();if(!d)return i;const{x:h,y:m}=d.getBoundingClientRect(),_={x:i.x-h,y:i.y-m};return wv(_,o,u,l)},flowToScreenPosition:i=>{const{transform:o,domNode:u}=e.getState();if(!u)return i;const{x:l,y:d}=u.getBoundingClientRect(),h=g$(i,o);return{x:h.x+l,y:h.y+d}},viewportInitialized:!0}:F8,[t,n])};function Tx(){const e=B8(),t=er(),n=p.useCallback(()=>t.getState().getNodes().map(k=>({...k})),[]),r=p.useCallback(k=>t.getState().nodeInternals.get(k),[]),i=p.useCallback(()=>{const{edges:k=[]}=t.getState();return k.map(x=>({...x}))},[]),o=p.useCallback(k=>{const{edges:x=[]}=t.getState();return x.find(N=>N.id===k)},[]),u=p.useCallback(k=>{const{getNodes:x,setNodes:N,hasDefaultNodes:$,onNodesChange:E}=t.getState(),S=x(),P=typeof k=="function"?k(S):k;if($)N(P);else if(E){const D=P.length===0?S.map(R=>({type:"remove",id:R.id})):P.map(R=>({item:R,type:"reset"}));E(D)}},[]),l=p.useCallback(k=>{const{edges:x=[],setEdges:N,hasDefaultEdges:$,onEdgesChange:E}=t.getState(),S=typeof k=="function"?k(x):k;if($)N(S);else if(E){const P=S.length===0?x.map(D=>({type:"remove",id:D.id})):S.map(D=>({item:D,type:"reset"}));E(P)}},[]),d=p.useCallback(k=>{const x=Array.isArray(k)?k:[k],{getNodes:N,setNodes:$,hasDefaultNodes:E,onNodesChange:S}=t.getState();if(E){const D=[...N(),...x];$(D)}else if(S){const P=x.map(D=>({item:D,type:"add"}));S(P)}},[]),h=p.useCallback(k=>{const x=Array.isArray(k)?k:[k],{edges:N=[],setEdges:$,hasDefaultEdges:E,onEdgesChange:S}=t.getState();if(E)$([...N,...x]);else if(S){const P=x.map(D=>({item:D,type:"add"}));S(P)}},[]),m=p.useCallback(()=>{const{getNodes:k,edges:x=[],transform:N}=t.getState(),[$,E,S]=N;return{nodes:k().map(P=>({...P})),edges:x.map(P=>({...P})),viewport:{x:$,y:E,zoom:S}}},[]),_=p.useCallback(({nodes:k,edges:x})=>{const{nodeInternals:N,getNodes:$,edges:E,hasDefaultNodes:S,hasDefaultEdges:P,onNodesDelete:D,onEdgesDelete:R,onNodesChange:I,onEdgesChange:W}=t.getState(),G=(k||[]).map(O=>O.id),K=(x||[]).map(O=>O.id),H=$().reduce((O,L)=>{const V=!G.includes(L.id)&&L.parentNode&&O.find(U=>U.id===L.parentNode);return(typeof L.deletable=="boolean"?L.deletable:!0)&&(G.includes(L.id)||V)&&O.push(L),O},[]),M=E.filter(O=>typeof O.deletable=="boolean"?O.deletable:!0),A=M.filter(O=>K.includes(O.id));if(H||A){const O=w$(H,M),L=[...A,...O],V=L.reduce((J,U)=>(J.includes(U.id)||J.push(U.id),J),[]);if((P||S)&&(P&&t.setState({edges:E.filter(J=>!V.includes(J.id))}),S&&(H.forEach(J=>{N.delete(J.id)}),t.setState({nodeInternals:new Map(N)}))),V.length>0&&(R==null||R(L),W&&W(V.map(J=>({id:J,type:"remove"})))),H.length>0&&(D==null||D(H),I)){const J=H.map(U=>({id:U.id,type:"remove"}));I(J)}}},[]),g=p.useCallback(k=>{const x=a8(k),N=x?null:t.getState().nodeInternals.get(k.id);return!x&&!N?[null,null,x]:[x?k:Sk(N),N,x]},[]),y=p.useCallback((k,x=!0,N)=>{const[$,E,S]=g(k);return $?(N||t.getState().getNodes()).filter(P=>{if(!S&&(P.id===E.id||!P.positionAbsolute))return!1;const D=Sk(P),R=_v(D,$);return x&&R>0||R>=$.width*$.height}):[]},[]),b=p.useCallback((k,x,N=!0)=>{const[$]=g(k);if(!$)return!1;const E=_v($,x);return N&&E>0||E>=$.width*$.height},[]);return p.useMemo(()=>({...e,getNodes:n,getNode:r,getEdges:i,getEdge:o,setNodes:u,setEdges:l,addNodes:d,addEdges:h,toObject:m,deleteElements:_,getIntersectingNodes:y,isNodeIntersecting:b}),[e,n,r,i,o,u,l,d,h,m,_,y,b])}const U8={actInsideInputWithModifier:!1};var W8=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=er(),{deleteElements:r}=Tx(),i=mm(e,U8),o=mm(t);p.useEffect(()=>{if(i){const{edges:u,getNodes:l}=n.getState(),d=l().filter(m=>m.selected),h=u.filter(m=>m.selected);r({nodes:d,edges:h}),n.setState({nodesSelectionActive:!1})}},[i]),p.useEffect(()=>{n.setState({multiSelectionActive:o})},[o])};function q8(e){const t=er();p.useEffect(()=>{let n;const r=()=>{var o,u;if(!e.current)return;const i=kx(e.current);(i.height===0||i.width===0)&&((u=(o=t.getState()).onError)==null||u.call(o,"004",al.error004())),t.setState({width:i.width||500,height:i.height||500})};return r(),window.addEventListener("resize",r),e.current&&(n=new ResizeObserver(()=>r()),n.observe(e.current)),()=>{window.removeEventListener("resize",r),n&&e.current&&n.unobserve(e.current)}},[])}const Mx={position:"absolute",width:"100%",height:"100%",top:0,left:0},H8=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,_p=e=>({x:e.x,y:e.y,zoom:e.k}),jd=(e,t)=>e.target.closest(`.${t}`),Ik=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Ok=e=>{const t=e.ctrlKey&&ug()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},V8=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),G8=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:r,zoomOnScroll:i=!0,zoomOnPinch:o=!0,panOnScroll:u=!1,panOnScrollSpeed:l=.5,panOnScrollMode:d=iu.Free,zoomOnDoubleClick:h=!0,elementsSelectable:m,panOnDrag:_=!0,defaultViewport:g,translateExtent:y,minZoom:b,maxZoom:k,zoomActivationKeyCode:x,preventScrolling:N=!0,children:$,noWheelClassName:E,noPanClassName:S})=>{const P=p.useRef(),D=er(),R=p.useRef(!1),I=p.useRef(!1),W=p.useRef(null),G=p.useRef({x:0,y:0,zoom:0}),{d3Zoom:K,d3Selection:H,d3ZoomHandler:M,userSelectionActive:A}=fs(V8,hr),O=mm(x),L=p.useRef(0),V=p.useRef(!1),J=p.useRef();return q8(W),p.useEffect(()=>{if(W.current){const U=W.current.getBoundingClientRect(),te=i$().scaleExtent([b,k]).translateExtent(y),z=yo(W.current).call(te),ne=tl.translate(g.x,g.y).scale(ef(g.zoom,b,k)),se=[[0,0],[U.width,U.height]],de=te.constrain()(ne,se,y);te.transform(z,de),te.wheelDelta(Ok),D.setState({d3Zoom:te,d3Selection:z,d3ZoomHandler:z.on("wheel.zoom"),transform:[de.x,de.y,de.k],domNode:W.current.closest(".react-flow")})}},[]),p.useEffect(()=>{H&&K&&(u&&!O&&!A?H.on("wheel.zoom",U=>{if(jd(U,E))return!1;U.preventDefault(),U.stopImmediatePropagation();const te=H.property("__zoom").k||1,z=ug();if(U.ctrlKey&&o&&z){const xe=qo(U),Ae=Ok(U),He=te*Math.pow(2,Ae);K.scaleTo(H,He,xe,U);return}const ne=U.deltaMode===1?20:1;let se=d===iu.Vertical?0:U.deltaX*ne,de=d===iu.Horizontal?0:U.deltaY*ne;!z&&U.shiftKey&&d!==iu.Vertical&&(se=U.deltaY*ne,de=0),K.translateBy(H,-(se/te)*l,-(de/te)*l,{internal:!0});const be=_p(H.property("__zoom")),{onViewportChangeStart:Me,onViewportChange:je,onViewportChangeEnd:ae}=D.getState();clearTimeout(J.current),V.current||(V.current=!0,t==null||t(U,be),Me==null||Me(be)),V.current&&(e==null||e(U,be),je==null||je(be),J.current=setTimeout(()=>{n==null||n(U,be),ae==null||ae(be),V.current=!1},150))},{passive:!1}):typeof M<"u"&&H.on("wheel.zoom",function(U,te){if(!N||jd(U,E))return null;U.preventDefault(),M.call(this,U,te)},{passive:!1}))},[A,u,d,H,K,M,O,o,N,E,t,e,n]),p.useEffect(()=>{K&&K.on("start",U=>{var ne,se;if(!U.sourceEvent||U.sourceEvent.internal)return null;L.current=(ne=U.sourceEvent)==null?void 0:ne.button;const{onViewportChangeStart:te}=D.getState(),z=_p(U.transform);R.current=!0,G.current=z,((se=U.sourceEvent)==null?void 0:se.type)==="mousedown"&&D.setState({paneDragging:!0}),te==null||te(z),t==null||t(U.sourceEvent,z)})},[K,t]),p.useEffect(()=>{K&&(A&&!R.current?K.on("zoom",null):A||K.on("zoom",U=>{var z;const{onViewportChange:te}=D.getState();if(D.setState({transform:[U.transform.x,U.transform.y,U.transform.k]}),I.current=!!(r&&Ik(_,L.current??0)),(e||te)&&!((z=U.sourceEvent)!=null&&z.internal)){const ne=_p(U.transform);te==null||te(ne),e==null||e(U.sourceEvent,ne)}}))},[A,K,e,_,r]),p.useEffect(()=>{K&&K.on("end",U=>{if(!U.sourceEvent||U.sourceEvent.internal)return null;const{onViewportChangeEnd:te}=D.getState();if(R.current=!1,D.setState({paneDragging:!1}),r&&Ik(_,L.current??0)&&!I.current&&r(U.sourceEvent),I.current=!1,(n||te)&&H8(G.current,U.transform)){const z=_p(U.transform);G.current=z,clearTimeout(P.current),P.current=setTimeout(()=>{te==null||te(z),n==null||n(U.sourceEvent,z)},u?150:0)}})},[K,u,_,n,r]),p.useEffect(()=>{K&&K.filter(U=>{const te=O||i,z=o&&U.ctrlKey;if((_===!0||Array.isArray(_)&&_.includes(1))&&U.button===1&&U.type==="mousedown"&&(jd(U,"react-flow__node")||jd(U,"react-flow__edge")))return!0;if(!_&&!te&&!u&&!h&&!o||A||!h&&U.type==="dblclick"||jd(U,E)&&U.type==="wheel"||jd(U,S)&&(U.type!=="wheel"||u&&U.type==="wheel"&&!O)||!o&&U.ctrlKey&&U.type==="wheel"||!te&&!u&&!z&&U.type==="wheel"||!_&&(U.type==="mousedown"||U.type==="touchstart")||Array.isArray(_)&&!_.includes(U.button)&&(U.type==="mousedown"||U.type==="touchstart"))return!1;const ne=Array.isArray(_)&&_.includes(U.button)||!U.button||U.button<=1;return(!U.ctrlKey||U.type==="wheel")&&ne})},[A,K,i,o,u,h,_,m,O]),Ee.createElement("div",{className:"react-flow__renderer",ref:W,style:Mx},$)},K8=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function J8(){const{userSelectionActive:e,userSelectionRect:t}=fs(K8,hr);return e&&t?Ee.createElement("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}function Pk(e,t){const n=e.find(r=>r.id===t.parentNode);if(n){const r=t.position.x+t.width-n.width,i=t.position.y+t.height-n.height;if(r>0||i>0||t.position.x<0||t.position.y<0){if(n.style={...n.style},n.style.width=n.style.width??n.width,n.style.height=n.style.height??n.height,r>0&&(n.style.width+=r),i>0&&(n.style.height+=i),t.position.x<0){const o=Math.abs(t.position.x);n.position.x=n.position.x-o,n.style.width+=o,t.position.x=0}if(t.position.y<0){const o=Math.abs(t.position.y);n.position.y=n.position.y-o,n.style.height+=o,t.position.y=0}n.width=n.style.width,n.height=n.style.height}}}function Y8(e,t){if(e.some(r=>r.type==="reset"))return e.filter(r=>r.type==="reset").map(r=>r.item);const n=e.filter(r=>r.type==="add").map(r=>r.item);return t.reduce((r,i)=>{const o=e.filter(l=>l.id===i.id);if(o.length===0)return r.push(i),r;const u={...i};for(const l of o)if(l)switch(l.type){case"select":{u.selected=l.selected;break}case"position":{typeof l.position<"u"&&(u.position=l.position),typeof l.positionAbsolute<"u"&&(u.positionAbsolute=l.positionAbsolute),typeof l.dragging<"u"&&(u.dragging=l.dragging),u.expandParent&&Pk(r,u);break}case"dimensions":{typeof l.dimensions<"u"&&(u.width=l.dimensions.width,u.height=l.dimensions.height),typeof l.updateStyle<"u"&&(u.style={...u.style||{},...l.dimensions}),typeof l.resizing=="boolean"&&(u.resizing=l.resizing),u.expandParent&&Pk(r,u);break}case"remove":return r}return r.push(u),r},n)}function X8(e,t){return Y8(e,t)}const Ql=(e,t)=>({id:e,type:"select",selected:t});function Od(e,t){return e.reduce((n,r)=>{const i=t.includes(r.id);return!r.selected&&i?(r.selected=!0,n.push(Ql(r.id,!0))):r.selected&&!i&&(r.selected=!1,n.push(Ql(r.id,!1))),n},[])}const iw=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},Z8=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),O$=p.memo(({isSelecting:e,selectionMode:t=fm.Full,panOnDrag:n,onSelectionStart:r,onSelectionEnd:i,onPaneClick:o,onPaneContextMenu:u,onPaneScroll:l,onPaneMouseEnter:d,onPaneMouseMove:h,onPaneMouseLeave:m,children:_})=>{const g=p.useRef(null),y=er(),b=p.useRef(0),k=p.useRef(0),x=p.useRef(),{userSelectionActive:N,elementsSelectable:$,dragging:E}=fs(Z8,hr),S=()=>{y.setState({userSelectionActive:!1,userSelectionRect:null}),b.current=0,k.current=0},P=M=>{o==null||o(M),y.getState().resetSelectedElements(),y.setState({nodesSelectionActive:!1})},D=M=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){M.preventDefault();return}u==null||u(M)},R=l?M=>l(M):void 0,I=M=>{const{resetSelectedElements:A,domNode:O}=y.getState();if(x.current=O==null?void 0:O.getBoundingClientRect(),!$||!e||M.button!==0||M.target!==g.current||!x.current)return;const{x:L,y:V}=oc(M,x.current);A(),y.setState({userSelectionRect:{width:0,height:0,startX:L,startY:V,x:L,y:V}}),r==null||r(M)},W=M=>{const{userSelectionRect:A,nodeInternals:O,edges:L,transform:V,onNodesChange:J,onEdgesChange:U,nodeOrigin:te,getNodes:z}=y.getState();if(!e||!x.current||!A)return;y.setState({userSelectionActive:!0,nodesSelectionActive:!1});const ne=oc(M,x.current),se=A.startX??0,de=A.startY??0,be={...A,x:ne.x<se?ne.x:se,y:ne.y<de?ne.y:de,width:Math.abs(ne.x-se),height:Math.abs(ne.y-de)},Me=z(),je=y$(O,be,V,t===fm.Partial,!0,te),ae=w$(je,L).map(Ae=>Ae.id),xe=je.map(Ae=>Ae.id);if(b.current!==xe.length){b.current=xe.length;const Ae=Od(Me,xe);Ae.length&&(J==null||J(Ae))}if(k.current!==ae.length){k.current=ae.length;const Ae=Od(L,ae);Ae.length&&(U==null||U(Ae))}y.setState({userSelectionRect:be})},G=M=>{if(M.button!==0)return;const{userSelectionRect:A}=y.getState();!N&&A&&M.target===g.current&&(P==null||P(M)),y.setState({nodesSelectionActive:b.current>0}),S(),i==null||i(M)},K=M=>{N&&(y.setState({nodesSelectionActive:b.current>0}),i==null||i(M)),S()},H=$&&(e||N);return Ee.createElement("div",{className:Cr(["react-flow__pane",{dragging:E,selection:e}]),onClick:H?void 0:iw(P,g),onContextMenu:iw(D,g),onWheel:iw(R,g),onMouseEnter:H?void 0:d,onMouseDown:H?I:void 0,onMouseMove:H?W:h,onMouseUp:H?G:void 0,onMouseLeave:H?K:m,ref:g,style:Mx},_,Ee.createElement(J8,null))});O$.displayName="Pane";function P$(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:P$(n,t):!1}function Dk(e,t,n){let r=e;do{if(r!=null&&r.matches(t))return!0;if(r===n.current)return!1;r=r.parentElement}while(r);return!1}function Q8(e,t,n,r){return Array.from(e.values()).filter(i=>(i.selected||i.id===r)&&(!i.parentNode||!P$(i,e))&&(i.draggable||t&&typeof i.draggable>"u")).map(i=>{var o,u;return{id:i.id,position:i.position||{x:0,y:0},positionAbsolute:i.positionAbsolute||{x:0,y:0},distance:{x:n.x-(((o=i.positionAbsolute)==null?void 0:o.x)??0),y:n.y-(((u=i.positionAbsolute)==null?void 0:u.y)??0)},delta:{x:0,y:0},extent:i.extent,parentNode:i.parentNode,width:i.width,height:i.height,expandParent:i.expandParent}})}function ez(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function D$(e,t,n,r,i=[0,0],o){const u=ez(e,e.extent||r);let l=u;if(e.extent==="parent"&&!e.expandParent)if(e.parentNode&&e.width&&e.height){const m=n.get(e.parentNode),{x:_,y:g}=uu(m,i).positionAbsolute;l=m&&wo(_)&&wo(g)&&wo(m.width)&&wo(m.height)?[[_+e.width*i[0],g+e.height*i[1]],[_+m.width-e.width+e.width*i[0],g+m.height-e.height+e.height*i[1]]]:l}else o==null||o("005",al.error005()),l=u;else if(e.extent&&e.parentNode&&e.extent!=="parent"){const m=n.get(e.parentNode),{x:_,y:g}=uu(m,i).positionAbsolute;l=[[e.extent[0][0]+_,e.extent[0][1]+g],[e.extent[1][0]+_,e.extent[1][1]+g]]}let d={x:0,y:0};if(e.parentNode){const m=n.get(e.parentNode);d=uu(m,i).positionAbsolute}const h=l&&l!=="parent"?jx(t,l):t;return{position:{x:h.x-d.x,y:h.y-d.y},positionAbsolute:h}}function ow({nodeId:e,dragItems:t,nodeInternals:n}){const r=t.map(i=>({...n.get(i.id),position:i.position,positionAbsolute:i.positionAbsolute}));return[e?r.find(i=>i.id===e):r[0],r]}const Fk=(e,t,n,r)=>{const i=t.querySelectorAll(e);if(!i||!i.length)return null;const o=Array.from(i),u=t.getBoundingClientRect(),l={x:u.width*r[0],y:u.height*r[1]};return o.map(d=>{const h=d.getBoundingClientRect();return{id:d.getAttribute("data-handleid"),position:d.getAttribute("data-handlepos"),x:(h.left-u.left-l.x)/n,y:(h.top-u.top-l.y)/n,...kx(d)}})};function Nh(e,t,n){return n===void 0?n:r=>{const i=t().nodeInternals.get(e);i&&n(r,{...i})}}function xv({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:i,unselectNodesAndEdges:o,multiSelectionActive:u,nodeInternals:l,onError:d}=t.getState(),h=l.get(e);if(!h){d==null||d("012",al.error012(e));return}t.setState({nodesSelectionActive:!1}),h.selected?(n||h.selected&&u)&&(o({nodes:[h],edges:[]}),requestAnimationFrame(()=>{var m;return(m=r==null?void 0:r.current)==null?void 0:m.blur()})):i([e])}function tz(){const e=er();return p.useCallback(({sourceEvent:n})=>{const{transform:r,snapGrid:i,snapToGrid:o}=e.getState(),u=n.touches?n.touches[0].clientX:n.clientX,l=n.touches?n.touches[0].clientY:n.clientY,d={x:(u-r[0])/r[2],y:(l-r[1])/r[2]};return{xSnapped:o?i[0]*Math.round(d.x/i[0]):d.x,ySnapped:o?i[1]*Math.round(d.y/i[1]):d.y,...d}},[])}function aw(e){return(t,n,r)=>e==null?void 0:e(t,r)}function F$({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:i,isSelectable:o,selectNodesOnDrag:u}){const l=er(),[d,h]=p.useState(!1),m=p.useRef([]),_=p.useRef({x:null,y:null}),g=p.useRef(0),y=p.useRef(null),b=p.useRef({x:0,y:0}),k=p.useRef(null),x=p.useRef(!1),N=p.useRef(!1),$=tz();return p.useEffect(()=>{if(e!=null&&e.current){const E=yo(e.current),S=({x:R,y:I})=>{const{nodeInternals:W,onNodeDrag:G,onSelectionDrag:K,updateNodePositions:H,nodeExtent:M,snapGrid:A,snapToGrid:O,nodeOrigin:L,onError:V}=l.getState();_.current={x:R,y:I};let J=!1,U={x:0,y:0,x2:0,y2:0};if(m.current.length>1&&M){const z=Wg(m.current,L);U=dm(z)}if(m.current=m.current.map(z=>{const ne={x:R-z.distance.x,y:I-z.distance.y};O&&(ne.x=A[0]*Math.round(ne.x/A[0]),ne.y=A[1]*Math.round(ne.y/A[1]));const se=[[M[0][0],M[0][1]],[M[1][0],M[1][1]]];m.current.length>1&&M&&!z.extent&&(se[0][0]=z.positionAbsolute.x-U.x+M[0][0],se[1][0]=z.positionAbsolute.x+(z.width??0)-U.x2+M[1][0],se[0][1]=z.positionAbsolute.y-U.y+M[0][1],se[1][1]=z.positionAbsolute.y+(z.height??0)-U.y2+M[1][1]);const de=D$(z,ne,W,se,L,V);return J=J||z.position.x!==de.position.x||z.position.y!==de.position.y,z.position=de.position,z.positionAbsolute=de.positionAbsolute,z}),!J)return;H(m.current,!0,!0),h(!0);const te=i?G:aw(K);if(te&&k.current){const[z,ne]=ow({nodeId:i,dragItems:m.current,nodeInternals:W});te(k.current,z,ne)}},P=()=>{if(!y.current)return;const[R,I]=a$(b.current,y.current);if(R!==0||I!==0){const{transform:W,panBy:G}=l.getState();_.current.x=(_.current.x??0)-R/W[2],_.current.y=(_.current.y??0)-I/W[2],G({x:R,y:I})&&S(_.current)}g.current=requestAnimationFrame(P)},D=R=>{var L;const{nodeInternals:I,multiSelectionActive:W,nodesDraggable:G,unselectNodesAndEdges:K,onNodeDragStart:H,onSelectionDragStart:M}=l.getState();N.current=!0;const A=i?H:aw(M);(!u||!o)&&!W&&i&&((L=I.get(i))!=null&&L.selected||K()),i&&o&&u&&xv({id:i,store:l,nodeRef:e});const O=$(R);if(_.current=O,m.current=Q8(I,G,O,i),A&&m.current){const[V,J]=ow({nodeId:i,dragItems:m.current,nodeInternals:I});A(R.sourceEvent,V,J)}};if(t)E.on(".drag",null);else{const R=dF().on("start",I=>{const{domNode:W,nodeDragThreshold:G}=l.getState();G===0&&D(I);const K=$(I);_.current=K,y.current=(W==null?void 0:W.getBoundingClientRect())||null,b.current=oc(I.sourceEvent,y.current)}).on("drag",I=>{var H,M;const W=$(I),{autoPanOnNodeDrag:G,nodeDragThreshold:K}=l.getState();if(!x.current&&N.current&&G&&(x.current=!0,P()),!N.current){const A=W.xSnapped-(((H=_==null?void 0:_.current)==null?void 0:H.x)??0),O=W.ySnapped-(((M=_==null?void 0:_.current)==null?void 0:M.y)??0);Math.sqrt(A*A+O*O)>K&&D(I)}(_.current.x!==W.xSnapped||_.current.y!==W.ySnapped)&&m.current&&N.current&&(k.current=I.sourceEvent,b.current=oc(I.sourceEvent,y.current),S(W))}).on("end",I=>{if(N.current&&(h(!1),x.current=!1,N.current=!1,cancelAnimationFrame(g.current),m.current)){const{updateNodePositions:W,nodeInternals:G,onNodeDragStop:K,onSelectionDragStop:H}=l.getState(),M=i?K:aw(H);if(W(m.current,!1,!1),M){const[A,O]=ow({nodeId:i,dragItems:m.current,nodeInternals:G});M(I.sourceEvent,A,O)}}}).filter(I=>{const W=I.target;return!I.button&&(!n||!Dk(W,`.${n}`,e))&&(!r||Dk(W,r,e))});return E.call(R),()=>{E.on(".drag",null)}}}},[e,t,n,r,o,l,i,u,$]),d}function z$(){const e=er();return p.useCallback(n=>{const{nodeInternals:r,nodeExtent:i,updateNodePositions:o,getNodes:u,snapToGrid:l,snapGrid:d,onError:h,nodesDraggable:m}=e.getState(),_=u().filter($=>$.selected&&($.draggable||m&&typeof $.draggable>"u")),g=l?d[0]:5,y=l?d[1]:5,b=n.isShiftPressed?4:1,k=n.x*g*b,x=n.y*y*b,N=_.map($=>{if($.positionAbsolute){const E={x:$.positionAbsolute.x+k,y:$.positionAbsolute.y+x};l&&(E.x=d[0]*Math.round(E.x/d[0]),E.y=d[1]*Math.round(E.y/d[1]));const{positionAbsolute:S,position:P}=D$($,E,r,i,void 0,h);$.position=P,$.positionAbsolute=S}return $});o(N,!0,!1)},[])}const qd={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var $h=e=>{const t=({id:n,type:r,data:i,xPos:o,yPos:u,xPosOrigin:l,yPosOrigin:d,selected:h,onClick:m,onMouseEnter:_,onMouseMove:g,onMouseLeave:y,onContextMenu:b,onDoubleClick:k,style:x,className:N,isDraggable:$,isSelectable:E,isConnectable:S,isFocusable:P,selectNodesOnDrag:D,sourcePosition:R,targetPosition:I,hidden:W,resizeObserver:G,dragHandle:K,zIndex:H,isParent:M,noDragClassName:A,noPanClassName:O,initialized:L,disableKeyboardA11y:V,ariaLabel:J,rfId:U,hasHandleBounds:te})=>{const z=er(),ne=p.useRef(null),se=p.useRef(R),de=p.useRef(I),be=p.useRef(r),Me=E||$||m||_||g||y,je=z$(),ae=Nh(n,z.getState,_),xe=Nh(n,z.getState,g),Ae=Nh(n,z.getState,y),He=Nh(n,z.getState,b),mt=Nh(n,z.getState,k),nt=Ve=>{const{nodeDragThreshold:ct}=z.getState();if(E&&(!D||!$||ct>0)&&xv({id:n,store:z,nodeRef:ne}),m){const Qe=z.getState().nodeInternals.get(n);Qe&&m(Ve,{...Qe})}},rt=Ve=>{if(!pv(Ve))if(d$.includes(Ve.key)&&E){const ct=Ve.key==="Escape";xv({id:n,store:z,unselect:ct,nodeRef:ne})}else!V&&$&&h&&Object.prototype.hasOwnProperty.call(qd,Ve.key)&&(z.setState({ariaLiveMessage:`Moved selected node ${Ve.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~o}, y: ${~~u}`}),je({x:qd[Ve.key].x,y:qd[Ve.key].y,isShiftPressed:Ve.shiftKey}))};p.useEffect(()=>()=>{ne.current&&(G==null||G.unobserve(ne.current))},[]),p.useEffect(()=>{if(ne.current&&!W){const Ve=ne.current;(!L||!te)&&(G==null||G.unobserve(Ve),G==null||G.observe(Ve))}},[W,L,te]),p.useEffect(()=>{const Ve=be.current!==r,ct=se.current!==R,Qe=de.current!==I;ne.current&&(Ve||ct||Qe)&&(Ve&&(be.current=r),ct&&(se.current=R),Qe&&(de.current=I),z.getState().updateNodeDimensions([{id:n,nodeElement:ne.current,forceUpdate:!0}]))},[n,r,R,I]);const ze=F$({nodeRef:ne,disabled:W||!$,noDragClassName:A,handleSelector:K,nodeId:n,isSelectable:E,selectNodesOnDrag:D});return W?null:Ee.createElement("div",{className:Cr(["react-flow__node",`react-flow__node-${r}`,{[O]:$},N,{selected:h,selectable:E,parent:M,dragging:ze}]),ref:ne,style:{zIndex:H,transform:`translate(${l}px,${d}px)`,pointerEvents:Me?"all":"none",visibility:L?"visible":"hidden",...x},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:ae,onMouseMove:xe,onMouseLeave:Ae,onContextMenu:He,onClick:nt,onDoubleClick:mt,onKeyDown:P?rt:void 0,tabIndex:P?0:void 0,role:P?"button":void 0,"aria-describedby":V?void 0:`${T$}-${U}`,"aria-label":J},Ee.createElement(m8,{value:n},Ee.createElement(e,{id:n,data:i,type:r,xPos:o,yPos:u,selected:h,isConnectable:S,sourcePosition:R,targetPosition:I,dragging:ze,dragHandle:K,zIndex:H})))};return t.displayName="NodeWrapper",p.memo(t)};const nz=e=>{const t=e.getNodes().filter(n=>n.selected);return{...Wg(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function sz({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=er(),{width:i,height:o,x:u,y:l,transformString:d,userSelectionActive:h}=fs(nz,hr),m=z$(),_=p.useRef(null);if(p.useEffect(()=>{var b;n||(b=_.current)==null||b.focus({preventScroll:!0})},[n]),F$({nodeRef:_}),h||!i||!o)return null;const g=e?b=>{const k=r.getState().getNodes().filter(x=>x.selected);e(b,k)}:void 0,y=b=>{Object.prototype.hasOwnProperty.call(qd,b.key)&&m({x:qd[b.key].x,y:qd[b.key].y,isShiftPressed:b.shiftKey})};return Ee.createElement("div",{className:Cr(["react-flow__nodesselection","react-flow__container",t]),style:{transform:d}},Ee.createElement("div",{ref:_,className:"react-flow__nodesselection-rect",onContextMenu:g,tabIndex:n?void 0:-1,onKeyDown:n?void 0:y,style:{width:i,height:o,top:l,left:u}}))}var rz=p.memo(sz);const iz=e=>e.nodesSelectionActive,B$=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:o,onPaneScroll:u,deleteKeyCode:l,onMove:d,onMoveStart:h,onMoveEnd:m,selectionKeyCode:_,selectionOnDrag:g,selectionMode:y,onSelectionStart:b,onSelectionEnd:k,multiSelectionKeyCode:x,panActivationKeyCode:N,zoomActivationKeyCode:$,elementsSelectable:E,zoomOnScroll:S,zoomOnPinch:P,panOnScroll:D,panOnScrollSpeed:R,panOnScrollMode:I,zoomOnDoubleClick:W,panOnDrag:G,defaultViewport:K,translateExtent:H,minZoom:M,maxZoom:A,preventScrolling:O,onSelectionContextMenu:L,noWheelClassName:V,noPanClassName:J,disableKeyboardA11y:U})=>{const te=fs(iz),z=mm(_),ne=mm(N),se=ne||G,de=ne||D,be=z||g&&se!==!0;return W8({deleteKeyCode:l,multiSelectionKeyCode:x}),Ee.createElement(G8,{onMove:d,onMoveStart:h,onMoveEnd:m,onPaneContextMenu:o,elementsSelectable:E,zoomOnScroll:S,zoomOnPinch:P,panOnScroll:de,panOnScrollSpeed:R,panOnScrollMode:I,zoomOnDoubleClick:W,panOnDrag:!z&&se,defaultViewport:K,translateExtent:H,minZoom:M,maxZoom:A,zoomActivationKeyCode:$,preventScrolling:O,noWheelClassName:V,noPanClassName:J},Ee.createElement(O$,{onSelectionStart:b,onSelectionEnd:k,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:o,onPaneScroll:u,panOnDrag:se,isSelecting:!!be,selectionMode:y},e,te&&Ee.createElement(rz,{onSelectionContextMenu:L,noPanClassName:J,disableKeyboardA11y:U})))};B$.displayName="FlowRenderer";var oz=p.memo(B$);function az(e){return fs(p.useCallback(n=>e?y$(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function lz(e){const t={input:$h(e.input||$$),default:$h(e.default||vv),output:$h(e.output||E$),group:$h(e.group||Ax)},n={},r=Object.keys(e).filter(i=>!["input","default","output","group"].includes(i)).reduce((i,o)=>(i[o]=$h(e[o]||vv),i),n);return{...t,...r}}const cz=({x:e,y:t,width:n,height:r,origin:i})=>!n||!r?{x:e,y:t}:i[0]<0||i[1]<0||i[0]>1||i[1]>1?{x:e,y:t}:{x:e-n*i[0],y:t-r*i[1]},uz=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),U$=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:i,updateNodeDimensions:o,onError:u}=fs(uz,hr),l=az(e.onlyRenderVisibleElements),d=p.useRef(),h=p.useMemo(()=>{if(typeof ResizeObserver>"u")return null;const m=new ResizeObserver(_=>{const g=_.map(y=>({id:y.target.getAttribute("data-id"),nodeElement:y.target,forceUpdate:!0}));o(g)});return d.current=m,m},[]);return p.useEffect(()=>()=>{var m;(m=d==null?void 0:d.current)==null||m.disconnect()},[]),Ee.createElement("div",{className:"react-flow__nodes",style:Mx},l.map(m=>{var P,D,R;let _=m.type||"default";e.nodeTypes[_]||(u==null||u("003",al.error003(_)),_="default");const g=e.nodeTypes[_]||e.nodeTypes.default,y=!!(m.draggable||t&&typeof m.draggable>"u"),b=!!(m.selectable||i&&typeof m.selectable>"u"),k=!!(m.connectable||n&&typeof m.connectable>"u"),x=!!(m.focusable||r&&typeof m.focusable>"u"),N=e.nodeExtent?jx(m.positionAbsolute,e.nodeExtent):m.positionAbsolute,$=(N==null?void 0:N.x)??0,E=(N==null?void 0:N.y)??0,S=cz({x:$,y:E,width:m.width??0,height:m.height??0,origin:e.nodeOrigin});return Ee.createElement(g,{key:m.id,id:m.id,className:m.className,style:m.style,type:_,data:m.data,sourcePosition:m.sourcePosition||Ut.Bottom,targetPosition:m.targetPosition||Ut.Top,hidden:m.hidden,xPos:$,yPos:E,xPosOrigin:S.x,yPosOrigin:S.y,selectNodesOnDrag:e.selectNodesOnDrag,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,selected:!!m.selected,isDraggable:y,isSelectable:b,isConnectable:k,isFocusable:x,resizeObserver:h,dragHandle:m.dragHandle,zIndex:((P=m[Vs])==null?void 0:P.z)??0,isParent:!!((D=m[Vs])!=null&&D.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!m.width&&!!m.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:m.ariaLabel,hasHandleBounds:!!((R=m[Vs])!=null&&R.handleBounds)})}))};U$.displayName="NodeRenderer";var dz=p.memo(U$);const fz=(e,t,n)=>n===Ut.Left?e-t:n===Ut.Right?e+t:e,hz=(e,t,n)=>n===Ut.Top?e-t:n===Ut.Bottom?e+t:e,zk="react-flow__edgeupdater",Bk=({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:i,onMouseEnter:o,onMouseOut:u,type:l})=>Ee.createElement("circle",{onMouseDown:i,onMouseEnter:o,onMouseOut:u,className:Cr([zk,`${zk}-${l}`]),cx:fz(t,r,e),cy:hz(n,r,e),r,stroke:"transparent",fill:"transparent"}),mz=()=>!0;var Sd=e=>{const t=({id:n,className:r,type:i,data:o,onClick:u,onEdgeDoubleClick:l,selected:d,animated:h,label:m,labelStyle:_,labelShowBg:g,labelBgStyle:y,labelBgPadding:b,labelBgBorderRadius:k,style:x,source:N,target:$,sourceX:E,sourceY:S,targetX:P,targetY:D,sourcePosition:R,targetPosition:I,elementsSelectable:W,hidden:G,sourceHandleId:K,targetHandleId:H,onContextMenu:M,onMouseEnter:A,onMouseMove:O,onMouseLeave:L,edgeUpdaterRadius:V,onEdgeUpdate:J,onEdgeUpdateStart:U,onEdgeUpdateEnd:te,markerEnd:z,markerStart:ne,rfId:se,ariaLabel:de,isFocusable:be,isUpdatable:Me,pathOptions:je,interactionWidth:ae})=>{const xe=p.useRef(null),[Ae,He]=p.useState(!1),[mt,nt]=p.useState(!1),rt=er(),ze=p.useMemo(()=>`url('#${yv(ne,se)}')`,[ne,se]),Ve=p.useMemo(()=>`url('#${yv(z,se)}')`,[z,se]);if(G)return null;const ct=_t=>{var Mt;const{edges:It,addSelectedEdges:bt,unselectNodesAndEdges:St,multiSelectionActive:ut}=rt.getState(),Ot=It.find(mn=>mn.id===n);Ot&&(W&&(rt.setState({nodesSelectionActive:!1}),Ot.selected&&ut?(St({nodes:[],edges:[Ot]}),(Mt=xe.current)==null||Mt.blur()):bt([n])),u&&u(_t,Ot))},Qe=Sh(n,rt.getState,l),Dt=Sh(n,rt.getState,M),$e=Sh(n,rt.getState,A),Le=Sh(n,rt.getState,O),ce=Sh(n,rt.getState,L),Q=(_t,It)=>{if(_t.button!==0)return;const{edges:bt,isValidConnection:St}=rt.getState(),ut=It?$:N,Ot=(It?H:K)||null,Mt=It?"target":"source",mn=St||mz,yn=It,In=bt.find(ge=>ge.id===n);nt(!0),U==null||U(_t,In,Mt);const Gs=ge=>{nt(!1),te==null||te(ge,In,Mt)};k$({event:_t,handleId:Ot,nodeId:ut,onConnect:ge=>J==null?void 0:J(In,ge),isTarget:yn,getState:rt.getState,setState:rt.setState,isValidConnection:mn,edgeUpdaterType:Mt,onEdgeUpdateEnd:Gs})},_e=_t=>Q(_t,!0),le=_t=>Q(_t,!1),Se=()=>He(!0),pe=()=>He(!1),dt=!W&&!u,yt=_t=>{var It;if(d$.includes(_t.key)&&W){const{unselectNodesAndEdges:bt,addSelectedEdges:St,edges:ut}=rt.getState();_t.key==="Escape"?((It=xe.current)==null||It.blur(),bt({edges:[ut.find(Mt=>Mt.id===n)]})):St([n])}};return Ee.createElement("g",{className:Cr(["react-flow__edge",`react-flow__edge-${i}`,r,{selected:d,animated:h,inactive:dt,updating:Ae}]),onClick:ct,onDoubleClick:Qe,onContextMenu:Dt,onMouseEnter:$e,onMouseMove:Le,onMouseLeave:ce,onKeyDown:be?yt:void 0,tabIndex:be?0:void 0,role:be?"button":"img","data-testid":`rf__edge-${n}`,"aria-label":de===null?void 0:de||`Edge from ${N} to ${$}`,"aria-describedby":be?`${M$}-${se}`:void 0,ref:xe},!mt&&Ee.createElement(e,{id:n,source:N,target:$,selected:d,animated:h,label:m,labelStyle:_,labelShowBg:g,labelBgStyle:y,labelBgPadding:b,labelBgBorderRadius:k,data:o,style:x,sourceX:E,sourceY:S,targetX:P,targetY:D,sourcePosition:R,targetPosition:I,sourceHandleId:K,targetHandleId:H,markerStart:ze,markerEnd:Ve,pathOptions:je,interactionWidth:ae}),Me&&Ee.createElement(Ee.Fragment,null,(Me==="source"||Me===!0)&&Ee.createElement(Bk,{position:R,centerX:E,centerY:S,radius:V,onMouseDown:_e,onMouseEnter:Se,onMouseOut:pe,type:"source"}),(Me==="target"||Me===!0)&&Ee.createElement(Bk,{position:I,centerX:P,centerY:D,radius:V,onMouseDown:le,onMouseEnter:Se,onMouseOut:pe,type:"target"})))};return t.displayName="EdgeWrapper",p.memo(t)};function _z(e){const t={default:Sd(e.default||dg),straight:Sd(e.bezier||$x),step:Sd(e.step||Nx),smoothstep:Sd(e.step||Ug),simplebezier:Sd(e.simplebezier||Sx)},n={},r=Object.keys(e).filter(i=>!["default","bezier"].includes(i)).reduce((i,o)=>(i[o]=Sd(e[o]||dg),i),n);return{...t,...r}}function Uk(e,t,n=null){const r=((n==null?void 0:n.x)||0)+t.x,i=((n==null?void 0:n.y)||0)+t.y,o=(n==null?void 0:n.width)||t.width,u=(n==null?void 0:n.height)||t.height;switch(e){case Ut.Top:return{x:r+o/2,y:i};case Ut.Right:return{x:r+o,y:i+u/2};case Ut.Bottom:return{x:r+o/2,y:i+u};case Ut.Left:return{x:r,y:i+u/2}}}function Wk(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const pz=(e,t,n,r,i,o)=>{const u=Uk(n,e,t),l=Uk(o,r,i);return{sourceX:u.x,sourceY:u.y,targetX:l.x,targetY:l.y}};function gz({sourcePos:e,targetPos:t,sourceWidth:n,sourceHeight:r,targetWidth:i,targetHeight:o,width:u,height:l,transform:d}){const h={x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x+n,t.x+i),y2:Math.max(e.y+r,t.y+o)};h.x===h.x2&&(h.x2+=1),h.y===h.y2&&(h.y2+=1);const m=dm({x:(0-d[0])/d[2],y:(0-d[1])/d[2],width:u/d[2],height:l/d[2]}),_=Math.max(0,Math.min(m.x2,h.x2)-Math.max(m.x,h.x)),g=Math.max(0,Math.min(m.y2,h.y2)-Math.max(m.y,h.y));return Math.ceil(_*g)>0}function qk(e){var r,i,o,u,l;const t=((r=e==null?void 0:e[Vs])==null?void 0:r.handleBounds)||null,n=t&&(e==null?void 0:e.width)&&(e==null?void 0:e.height)&&typeof((i=e==null?void 0:e.positionAbsolute)==null?void 0:i.x)<"u"&&typeof((o=e==null?void 0:e.positionAbsolute)==null?void 0:o.y)<"u";return[{x:((u=e==null?void 0:e.positionAbsolute)==null?void 0:u.x)||0,y:((l=e==null?void 0:e.positionAbsolute)==null?void 0:l.y)||0,width:(e==null?void 0:e.width)||0,height:(e==null?void 0:e.height)||0},t,!!n]}const yz=[{level:0,isMaxLevel:!0,edges:[]}];function wz(e,t,n=!1){let r=-1;const i=e.reduce((u,l)=>{var m,_;const d=wo(l.zIndex);let h=d?l.zIndex:0;if(n){const g=t.get(l.target),y=t.get(l.source),b=l.selected||(g==null?void 0:g.selected)||(y==null?void 0:y.selected),k=Math.max(((m=y==null?void 0:y[Vs])==null?void 0:m.z)||0,((_=g==null?void 0:g[Vs])==null?void 0:_.z)||0,1e3);h=(d?l.zIndex:0)+(b?k:0)}return u[h]?u[h].push(l):u[h]=[l],r=h>r?h:r,u},{}),o=Object.entries(i).map(([u,l])=>{const d=+u;return{edges:l,level:d,isMaxLevel:d===r}});return o.length===0?yz:o}function vz(e,t,n){const r=fs(p.useCallback(i=>e?i.edges.filter(o=>{const u=t.get(o.source),l=t.get(o.target);return(u==null?void 0:u.width)&&(u==null?void 0:u.height)&&(l==null?void 0:l.width)&&(l==null?void 0:l.height)&&gz({sourcePos:u.positionAbsolute||{x:0,y:0},targetPos:l.positionAbsolute||{x:0,y:0},sourceWidth:u.width,sourceHeight:u.height,targetWidth:l.width,targetHeight:l.height,width:i.width,height:i.height,transform:i.transform})}):i.edges,[e,t]));return wz(r,t,n)}const xz=({color:e="none",strokeWidth:t=1})=>Ee.createElement("polyline",{style:{stroke:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",fill:"none",points:"-5,-4 0,0 -5,4"}),bz=({color:e="none",strokeWidth:t=1})=>Ee.createElement("polyline",{style:{stroke:e,fill:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"}),Hk={[hm.Arrow]:xz,[hm.ArrowClosed]:bz};function kz(e){const t=er();return p.useMemo(()=>{var i,o;return Object.prototype.hasOwnProperty.call(Hk,e)?Hk[e]:((o=(i=t.getState()).onError)==null||o.call(i,"009",al.error009(e)),null)},[e])}const jz=({id:e,type:t,color:n,width:r=12.5,height:i=12.5,markerUnits:o="strokeWidth",strokeWidth:u,orient:l="auto-start-reverse"})=>{const d=kz(t);return d?Ee.createElement("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${i}`,viewBox:"-10 -10 20 20",markerUnits:o,orient:l,refX:"0",refY:"0"},Ee.createElement(d,{color:n,strokeWidth:u})):null},Sz=({defaultColor:e,rfId:t})=>n=>{const r=[];return n.edges.reduce((i,o)=>([o.markerStart,o.markerEnd].forEach(u=>{if(u&&typeof u=="object"){const l=yv(u,t);r.includes(l)||(i.push({id:l,color:u.color||e,...u}),r.push(l))}}),i),[]).sort((i,o)=>i.id.localeCompare(o.id))},W$=({defaultColor:e,rfId:t})=>{const n=fs(p.useCallback(Sz({defaultColor:e,rfId:t}),[e,t]),(r,i)=>!(r.length!==i.length||r.some((o,u)=>o.id!==i[u].id)));return Ee.createElement("defs",null,n.map(r=>Ee.createElement(jz,{id:r.id,key:r.id,type:r.type,color:r.color,width:r.width,height:r.height,markerUnits:r.markerUnits,strokeWidth:r.strokeWidth,orient:r.orient})))};W$.displayName="MarkerDefinitions";var Nz=p.memo(W$);const $z=e=>({nodesConnectable:e.nodesConnectable,edgesFocusable:e.edgesFocusable,edgesUpdatable:e.edgesUpdatable,elementsSelectable:e.elementsSelectable,width:e.width,height:e.height,connectionMode:e.connectionMode,nodeInternals:e.nodeInternals,onError:e.onError}),q$=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:r,edgeTypes:i,noPanClassName:o,onEdgeUpdate:u,onEdgeContextMenu:l,onEdgeMouseEnter:d,onEdgeMouseMove:h,onEdgeMouseLeave:m,onEdgeClick:_,edgeUpdaterRadius:g,onEdgeDoubleClick:y,onEdgeUpdateStart:b,onEdgeUpdateEnd:k,children:x})=>{const{edgesFocusable:N,edgesUpdatable:$,elementsSelectable:E,width:S,height:P,connectionMode:D,nodeInternals:R,onError:I}=fs($z,hr),W=vz(t,R,n);return S?Ee.createElement(Ee.Fragment,null,W.map(({level:G,edges:K,isMaxLevel:H})=>Ee.createElement("svg",{key:G,style:{zIndex:G},width:S,height:P,className:"react-flow__edges react-flow__container"},H&&Ee.createElement(Nz,{defaultColor:e,rfId:r}),Ee.createElement("g",null,K.map(M=>{const[A,O,L]=qk(R.get(M.source)),[V,J,U]=qk(R.get(M.target));if(!L||!U)return null;let te=M.type||"default";i[te]||(I==null||I("011",al.error011(te)),te="default");const z=i[te]||i.default,ne=D===wu.Strict?J.target:(J.target??[]).concat(J.source??[]),se=Wk(O.source,M.sourceHandle),de=Wk(ne,M.targetHandle),be=(se==null?void 0:se.position)||Ut.Bottom,Me=(de==null?void 0:de.position)||Ut.Top,je=!!(M.focusable||N&&typeof M.focusable>"u"),ae=typeof u<"u"&&(M.updatable||$&&typeof M.updatable>"u");if(!se||!de)return I==null||I("008",al.error008(se,M)),null;const{sourceX:xe,sourceY:Ae,targetX:He,targetY:mt}=pz(A,se,be,V,de,Me);return Ee.createElement(z,{key:M.id,id:M.id,className:Cr([M.className,o]),type:te,data:M.data,selected:!!M.selected,animated:!!M.animated,hidden:!!M.hidden,label:M.label,labelStyle:M.labelStyle,labelShowBg:M.labelShowBg,labelBgStyle:M.labelBgStyle,labelBgPadding:M.labelBgPadding,labelBgBorderRadius:M.labelBgBorderRadius,style:M.style,source:M.source,target:M.target,sourceHandleId:M.sourceHandle,targetHandleId:M.targetHandle,markerEnd:M.markerEnd,markerStart:M.markerStart,sourceX:xe,sourceY:Ae,targetX:He,targetY:mt,sourcePosition:be,targetPosition:Me,elementsSelectable:E,onEdgeUpdate:u,onContextMenu:l,onMouseEnter:d,onMouseMove:h,onMouseLeave:m,onClick:_,edgeUpdaterRadius:g,onEdgeDoubleClick:y,onEdgeUpdateStart:b,onEdgeUpdateEnd:k,rfId:r,ariaLabel:M.ariaLabel,isFocusable:je,isUpdatable:ae,pathOptions:"pathOptions"in M?M.pathOptions:void 0,interactionWidth:M.interactionWidth})})))),x):null};q$.displayName="EdgeRenderer";var Cz=p.memo(q$);const Ez=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function Az({children:e}){const t=fs(Ez);return Ee.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function Tz(e){const t=Tx(),n=p.useRef(!1);p.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const Mz={[Ut.Left]:Ut.Right,[Ut.Right]:Ut.Left,[Ut.Top]:Ut.Bottom,[Ut.Bottom]:Ut.Top},H$=({nodeId:e,handleType:t,style:n,type:r=tc.Bezier,CustomComponent:i,connectionStatus:o})=>{var D,R,I;const{fromNode:u,handleId:l,toX:d,toY:h,connectionMode:m}=fs(p.useCallback(W=>({fromNode:W.nodeInternals.get(e),handleId:W.connectionHandleId,toX:(W.connectionPosition.x-W.transform[0])/W.transform[2],toY:(W.connectionPosition.y-W.transform[1])/W.transform[2],connectionMode:W.connectionMode}),[e]),hr),_=(D=u==null?void 0:u[Vs])==null?void 0:D.handleBounds;let g=_==null?void 0:_[t];if(m===wu.Loose&&(g=g||(_==null?void 0:_[t==="source"?"target":"source"])),!u||!g)return null;const y=l?g.find(W=>W.id===l):g[0],b=y?y.x+y.width/2:(u.width??0)/2,k=y?y.y+y.height/2:u.height??0,x=(((R=u.positionAbsolute)==null?void 0:R.x)??0)+b,N=(((I=u.positionAbsolute)==null?void 0:I.y)??0)+k,$=y==null?void 0:y.position,E=$?Mz[$]:null;if(!$||!E)return null;if(i)return Ee.createElement(i,{connectionLineType:r,connectionLineStyle:n,fromNode:u,fromHandle:y,fromX:x,fromY:N,toX:d,toY:h,fromPosition:$,toPosition:E,connectionStatus:o});let S="";const P={sourceX:x,sourceY:N,sourcePosition:$,targetX:d,targetY:h,targetPosition:E};return r===tc.Bezier?[S]=p$(P):r===tc.Step?[S]=gv({...P,borderRadius:0}):r===tc.SmoothStep?[S]=gv(P):r===tc.SimpleBezier?[S]=_$(P):S=`M${x},${N} ${d},${h}`,Ee.createElement("path",{d:S,fill:"none",className:"react-flow__connection-path",style:n})};H$.displayName="ConnectionLine";const Rz=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function Lz({containerStyle:e,style:t,type:n,component:r}){const{nodeId:i,handleType:o,nodesConnectable:u,width:l,height:d,connectionStatus:h}=fs(Rz,hr);return!(i&&o&&l&&u)?null:Ee.createElement("svg",{style:e,width:l,height:d,className:"react-flow__edges react-flow__connectionline react-flow__container"},Ee.createElement("g",{className:Cr(["react-flow__connection",h])},Ee.createElement(H$,{nodeId:i,handleType:o,style:t,type:n,CustomComponent:r,connectionStatus:h})))}function Vk(e,t){return p.useRef(null),er(),p.useMemo(()=>t(e),[e])}const V$=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:r,onMoveEnd:i,onInit:o,onNodeClick:u,onEdgeClick:l,onNodeDoubleClick:d,onEdgeDoubleClick:h,onNodeMouseEnter:m,onNodeMouseMove:_,onNodeMouseLeave:g,onNodeContextMenu:y,onSelectionContextMenu:b,onSelectionStart:k,onSelectionEnd:x,connectionLineType:N,connectionLineStyle:$,connectionLineComponent:E,connectionLineContainerStyle:S,selectionKeyCode:P,selectionOnDrag:D,selectionMode:R,multiSelectionKeyCode:I,panActivationKeyCode:W,zoomActivationKeyCode:G,deleteKeyCode:K,onlyRenderVisibleElements:H,elementsSelectable:M,selectNodesOnDrag:A,defaultViewport:O,translateExtent:L,minZoom:V,maxZoom:J,preventScrolling:U,defaultMarkerColor:te,zoomOnScroll:z,zoomOnPinch:ne,panOnScroll:se,panOnScrollSpeed:de,panOnScrollMode:be,zoomOnDoubleClick:Me,panOnDrag:je,onPaneClick:ae,onPaneMouseEnter:xe,onPaneMouseMove:Ae,onPaneMouseLeave:He,onPaneScroll:mt,onPaneContextMenu:nt,onEdgeUpdate:rt,onEdgeContextMenu:ze,onEdgeMouseEnter:Ve,onEdgeMouseMove:ct,onEdgeMouseLeave:Qe,edgeUpdaterRadius:Dt,onEdgeUpdateStart:$e,onEdgeUpdateEnd:Le,noDragClassName:ce,noWheelClassName:Q,noPanClassName:_e,elevateEdgesOnSelect:le,disableKeyboardA11y:Se,nodeOrigin:pe,nodeExtent:dt,rfId:yt})=>{const _t=Vk(e,lz),It=Vk(t,_z);return Tz(o),Ee.createElement(oz,{onPaneClick:ae,onPaneMouseEnter:xe,onPaneMouseMove:Ae,onPaneMouseLeave:He,onPaneContextMenu:nt,onPaneScroll:mt,deleteKeyCode:K,selectionKeyCode:P,selectionOnDrag:D,selectionMode:R,onSelectionStart:k,onSelectionEnd:x,multiSelectionKeyCode:I,panActivationKeyCode:W,zoomActivationKeyCode:G,elementsSelectable:M,onMove:n,onMoveStart:r,onMoveEnd:i,zoomOnScroll:z,zoomOnPinch:ne,zoomOnDoubleClick:Me,panOnScroll:se,panOnScrollSpeed:de,panOnScrollMode:be,panOnDrag:je,defaultViewport:O,translateExtent:L,minZoom:V,maxZoom:J,onSelectionContextMenu:b,preventScrolling:U,noDragClassName:ce,noWheelClassName:Q,noPanClassName:_e,disableKeyboardA11y:Se},Ee.createElement(Az,null,Ee.createElement(Cz,{edgeTypes:It,onEdgeClick:l,onEdgeDoubleClick:h,onEdgeUpdate:rt,onlyRenderVisibleElements:H,onEdgeContextMenu:ze,onEdgeMouseEnter:Ve,onEdgeMouseMove:ct,onEdgeMouseLeave:Qe,onEdgeUpdateStart:$e,onEdgeUpdateEnd:Le,edgeUpdaterRadius:Dt,defaultMarkerColor:te,noPanClassName:_e,elevateEdgesOnSelect:!!le,disableKeyboardA11y:Se,rfId:yt},Ee.createElement(Lz,{style:$,type:N,component:E,containerStyle:S})),Ee.createElement("div",{className:"react-flow__edgelabel-renderer"}),Ee.createElement(dz,{nodeTypes:_t,onNodeClick:u,onNodeDoubleClick:d,onNodeMouseEnter:m,onNodeMouseMove:_,onNodeMouseLeave:g,onNodeContextMenu:y,selectNodesOnDrag:A,onlyRenderVisibleElements:H,noPanClassName:_e,noDragClassName:ce,disableKeyboardA11y:Se,nodeOrigin:pe,nodeExtent:dt,rfId:yt})))};V$.displayName="GraphView";var Iz=p.memo(V$);const bv=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Gl={rfId:"1",width:0,height:0,transform:[0,0,1],nodeInternals:new Map,edges:[],onNodesChange:null,onEdgesChange:null,hasDefaultNodes:!1,hasDefaultEdges:!1,d3Zoom:null,d3Selection:null,d3ZoomHandler:void 0,minZoom:.5,maxZoom:2,translateExtent:bv,nodeExtent:bv,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:wu.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:[0,0],nodeDragThreshold:0,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesUpdatable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,fitViewOnInit:!1,fitViewOnInitDone:!1,fitViewOnInitOptions:void 0,onSelectionChange:[],multiSelectionActive:!1,connectionStartHandle:null,connectionEndHandle:null,connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,connectionRadius:20,onError:l8,isValidConnection:void 0},Oz=()=>k5((e,t)=>({...Gl,setNodes:n=>{const{nodeInternals:r,nodeOrigin:i,elevateNodesOnSelect:o}=t();e({nodeInternals:rw(n,r,i,o)})},getNodes:()=>Array.from(t().nodeInternals.values()),setEdges:n=>{const{defaultEdgeOptions:r={}}=t();e({edges:n.map(i=>({...r,...i}))})},setDefaultNodesAndEdges:(n,r)=>{const i=typeof n<"u",o=typeof r<"u",u=i?rw(n,new Map,t().nodeOrigin,t().elevateNodesOnSelect):new Map;e({nodeInternals:u,edges:o?r:[],hasDefaultNodes:i,hasDefaultEdges:o})},updateNodeDimensions:n=>{const{onNodesChange:r,nodeInternals:i,fitViewOnInit:o,fitViewOnInitDone:u,fitViewOnInitOptions:l,domNode:d,nodeOrigin:h}=t(),m=d==null?void 0:d.querySelector(".react-flow__viewport");if(!m)return;const _=window.getComputedStyle(m),{m22:g}=new window.DOMMatrixReadOnly(_.transform),y=n.reduce((k,x)=>{const N=i.get(x.id);if(N){const $=kx(x.nodeElement);!!($.width&&$.height&&(N.width!==$.width||N.height!==$.height||x.forceUpdate))&&(i.set(N.id,{...N,[Vs]:{...N[Vs],handleBounds:{source:Fk(".source",x.nodeElement,g,h),target:Fk(".target",x.nodeElement,g,h)}},...$}),k.push({id:N.id,type:"dimensions",dimensions:$}))}return k},[]);L$(i,h);const b=u||o&&!u&&I$(t,{initial:!0,...l});e({nodeInternals:new Map(i),fitViewOnInitDone:b}),(y==null?void 0:y.length)>0&&(r==null||r(y))},updateNodePositions:(n,r=!0,i=!1)=>{const{triggerNodeChanges:o}=t(),u=n.map(l=>{const d={id:l.id,type:"position",dragging:i};return r&&(d.positionAbsolute=l.positionAbsolute,d.position=l.position),d});o(u)},triggerNodeChanges:n=>{const{onNodesChange:r,nodeInternals:i,hasDefaultNodes:o,nodeOrigin:u,getNodes:l,elevateNodesOnSelect:d}=t();if(n!=null&&n.length){if(o){const h=X8(n,l()),m=rw(h,i,u,d);e({nodeInternals:m})}r==null||r(n)}},addSelectedNodes:n=>{const{multiSelectionActive:r,edges:i,getNodes:o}=t();let u,l=null;r?u=n.map(d=>Ql(d,!0)):(u=Od(o(),n),l=Od(i,[])),mp({changedNodes:u,changedEdges:l,get:t,set:e})},addSelectedEdges:n=>{const{multiSelectionActive:r,edges:i,getNodes:o}=t();let u,l=null;r?u=n.map(d=>Ql(d,!0)):(u=Od(i,n),l=Od(o(),[])),mp({changedNodes:l,changedEdges:u,get:t,set:e})},unselectNodesAndEdges:({nodes:n,edges:r}={})=>{const{edges:i,getNodes:o}=t(),u=n||o(),l=r||i,d=u.map(m=>(m.selected=!1,Ql(m.id,!1))),h=l.map(m=>Ql(m.id,!1));mp({changedNodes:d,changedEdges:h,get:t,set:e})},setMinZoom:n=>{const{d3Zoom:r,maxZoom:i}=t();r==null||r.scaleExtent([n,i]),e({minZoom:n})},setMaxZoom:n=>{const{d3Zoom:r,minZoom:i}=t();r==null||r.scaleExtent([i,n]),e({maxZoom:n})},setTranslateExtent:n=>{var r;(r=t().d3Zoom)==null||r.translateExtent(n),e({translateExtent:n})},resetSelectedElements:()=>{const{edges:n,getNodes:r}=t(),o=r().filter(l=>l.selected).map(l=>Ql(l.id,!1)),u=n.filter(l=>l.selected).map(l=>Ql(l.id,!1));mp({changedNodes:o,changedEdges:u,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:r}=t();r.forEach(i=>{i.positionAbsolute=jx(i.position,n)}),e({nodeExtent:n,nodeInternals:new Map(r)})},panBy:n=>{const{transform:r,width:i,height:o,d3Zoom:u,d3Selection:l,translateExtent:d}=t();if(!u||!l||!n.x&&!n.y)return!1;const h=tl.translate(r[0]+n.x,r[1]+n.y).scale(r[2]),m=[[0,0],[i,o]],_=u==null?void 0:u.constrain()(h,m,d);return u.transform(l,_),r[0]!==_.x||r[1]!==_.y||r[2]!==_.k},cancelConnection:()=>e({connectionNodeId:Gl.connectionNodeId,connectionHandleId:Gl.connectionHandleId,connectionHandleType:Gl.connectionHandleType,connectionStatus:Gl.connectionStatus,connectionStartHandle:Gl.connectionStartHandle,connectionEndHandle:Gl.connectionEndHandle}),reset:()=>e({...Gl})}),Object.is),Rx=({children:e})=>{const t=p.useRef(null);return t.current||(t.current=Oz()),Ee.createElement(t8,{value:t.current},e)};Rx.displayName="ReactFlowProvider";const G$=({children:e})=>p.useContext(Bg)?Ee.createElement(Ee.Fragment,null,e):Ee.createElement(Rx,null,e);G$.displayName="ReactFlowWrapper";const Pz={input:$$,default:vv,output:E$,group:Ax},Dz={default:dg,straight:$x,step:Nx,smoothstep:Ug,simplebezier:Sx},Fz=[0,0],zz=[15,15],Bz={x:0,y:0,zoom:1},Uz={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},K$=p.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:i,nodeTypes:o=Pz,edgeTypes:u=Dz,onNodeClick:l,onEdgeClick:d,onInit:h,onMove:m,onMoveStart:_,onMoveEnd:g,onConnect:y,onConnectStart:b,onConnectEnd:k,onClickConnectStart:x,onClickConnectEnd:N,onNodeMouseEnter:$,onNodeMouseMove:E,onNodeMouseLeave:S,onNodeContextMenu:P,onNodeDoubleClick:D,onNodeDragStart:R,onNodeDrag:I,onNodeDragStop:W,onNodesDelete:G,onEdgesDelete:K,onSelectionChange:H,onSelectionDragStart:M,onSelectionDrag:A,onSelectionDragStop:O,onSelectionContextMenu:L,onSelectionStart:V,onSelectionEnd:J,connectionMode:U=wu.Strict,connectionLineType:te=tc.Bezier,connectionLineStyle:z,connectionLineComponent:ne,connectionLineContainerStyle:se,deleteKeyCode:de="Backspace",selectionKeyCode:be="Shift",selectionOnDrag:Me=!1,selectionMode:je=fm.Full,panActivationKeyCode:ae="Space",multiSelectionKeyCode:xe=ug()?"Meta":"Control",zoomActivationKeyCode:Ae=ug()?"Meta":"Control",snapToGrid:He=!1,snapGrid:mt=zz,onlyRenderVisibleElements:nt=!1,selectNodesOnDrag:rt=!0,nodesDraggable:ze,nodesConnectable:Ve,nodesFocusable:ct,nodeOrigin:Qe=Fz,edgesFocusable:Dt,edgesUpdatable:$e,elementsSelectable:Le,defaultViewport:ce=Bz,minZoom:Q=.5,maxZoom:_e=2,translateExtent:le=bv,preventScrolling:Se=!0,nodeExtent:pe,defaultMarkerColor:dt="#b1b1b7",zoomOnScroll:yt=!0,zoomOnPinch:_t=!0,panOnScroll:It=!1,panOnScrollSpeed:bt=.5,panOnScrollMode:St=iu.Free,zoomOnDoubleClick:ut=!0,panOnDrag:Ot=!0,onPaneClick:Mt,onPaneMouseEnter:mn,onPaneMouseMove:yn,onPaneMouseLeave:In,onPaneScroll:Gs,onPaneContextMenu:ss,children:ge,onEdgeUpdate:Re,onEdgeContextMenu:gt,onEdgeDoubleClick:re,onEdgeMouseEnter:fe,onEdgeMouseMove:Ce,onEdgeMouseLeave:Ie,onEdgeUpdateStart:We,onEdgeUpdateEnd:Ue,edgeUpdaterRadius:et=10,onNodesChange:at,onEdgesChange:vt,noDragClassName:xt="nodrag",noWheelClassName:Et="nowheel",noPanClassName:zt="nopan",fitView:ot=!1,fitViewOptions:Jt,connectOnClick:wn=!0,attributionPosition:hn,proOptions:sn,defaultEdgeOptions:Vt,elevateNodesOnSelect:rs=!0,elevateEdgesOnSelect:Be=!1,disableKeyboardA11y:Zt=!1,autoPanOnConnect:Tt=!0,autoPanOnNodeDrag:Dn=!0,connectionRadius:fn=20,isValidConnection:Xe,onError:nn,style:cn,id:Er,nodeDragThreshold:Cs,...gs},mr)=>{const we=Er||"1";return Ee.createElement("div",{...gs,style:{...cn,...Uz},ref:mr,className:Cr(["react-flow",i]),"data-testid":"rf__wrapper",id:Er},Ee.createElement(G$,null,Ee.createElement(Iz,{onInit:h,onMove:m,onMoveStart:_,onMoveEnd:g,onNodeClick:l,onEdgeClick:d,onNodeMouseEnter:$,onNodeMouseMove:E,onNodeMouseLeave:S,onNodeContextMenu:P,onNodeDoubleClick:D,nodeTypes:o,edgeTypes:u,connectionLineType:te,connectionLineStyle:z,connectionLineComponent:ne,connectionLineContainerStyle:se,selectionKeyCode:be,selectionOnDrag:Me,selectionMode:je,deleteKeyCode:de,multiSelectionKeyCode:xe,panActivationKeyCode:ae,zoomActivationKeyCode:Ae,onlyRenderVisibleElements:nt,selectNodesOnDrag:rt,defaultViewport:ce,translateExtent:le,minZoom:Q,maxZoom:_e,preventScrolling:Se,zoomOnScroll:yt,zoomOnPinch:_t,zoomOnDoubleClick:ut,panOnScroll:It,panOnScrollSpeed:bt,panOnScrollMode:St,panOnDrag:Ot,onPaneClick:Mt,onPaneMouseEnter:mn,onPaneMouseMove:yn,onPaneMouseLeave:In,onPaneScroll:Gs,onPaneContextMenu:ss,onSelectionContextMenu:L,onSelectionStart:V,onSelectionEnd:J,onEdgeUpdate:Re,onEdgeContextMenu:gt,onEdgeDoubleClick:re,onEdgeMouseEnter:fe,onEdgeMouseMove:Ce,onEdgeMouseLeave:Ie,onEdgeUpdateStart:We,onEdgeUpdateEnd:Ue,edgeUpdaterRadius:et,defaultMarkerColor:dt,noDragClassName:xt,noWheelClassName:Et,noPanClassName:zt,elevateEdgesOnSelect:Be,rfId:we,disableKeyboardA11y:Zt,nodeOrigin:Qe,nodeExtent:pe}),Ee.createElement(T8,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:y,onConnectStart:b,onConnectEnd:k,onClickConnectStart:x,onClickConnectEnd:N,nodesDraggable:ze,nodesConnectable:Ve,nodesFocusable:ct,edgesFocusable:Dt,edgesUpdatable:$e,elementsSelectable:Le,elevateNodesOnSelect:rs,minZoom:Q,maxZoom:_e,nodeExtent:pe,onNodesChange:at,onEdgesChange:vt,snapToGrid:He,snapGrid:mt,connectionMode:U,translateExtent:le,connectOnClick:wn,defaultEdgeOptions:Vt,fitView:ot,fitViewOptions:Jt,onNodesDelete:G,onEdgesDelete:K,onNodeDragStart:R,onNodeDrag:I,onNodeDragStop:W,onSelectionDrag:A,onSelectionDragStart:M,onSelectionDragStop:O,noPanClassName:zt,nodeOrigin:Qe,rfId:we,autoPanOnConnect:Tt,autoPanOnNodeDrag:Dn,onError:nn,connectionRadius:fn,isValidConnection:Xe,nodeDragThreshold:Cs}),Ee.createElement(E8,{onSelectionChange:H}),ge,Ee.createElement(s8,{proOptions:sn,position:hn}),Ee.createElement(O8,{rfId:we,disableKeyboardA11y:Zt})))});K$.displayName="ReactFlow";const J$=({id:e,x:t,y:n,width:r,height:i,style:o,color:u,strokeColor:l,strokeWidth:d,className:h,borderRadius:m,shapeRendering:_,onClick:g,selected:y})=>{const{background:b,backgroundColor:k}=o||{},x=u||b||k;return Ee.createElement("rect",{className:Cr(["react-flow__minimap-node",{selected:y},h]),x:t,y:n,rx:m,ry:m,width:r,height:i,fill:x,stroke:l,strokeWidth:d,shapeRendering:_,onClick:g?N=>g(N,e):void 0})};J$.displayName="MiniMapNode";var Wz=p.memo(J$);const qz=e=>e.nodeOrigin,Hz=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),lw=e=>e instanceof Function?e:()=>e;function Vz({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:i=2,nodeComponent:o=Wz,onClick:u}){const l=fs(Hz,hr),d=fs(qz),h=lw(t),m=lw(e),_=lw(n),g=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return Ee.createElement(Ee.Fragment,null,l.map(y=>{const{x:b,y:k}=uu(y,d).positionAbsolute;return Ee.createElement(o,{key:y.id,x:b,y:k,width:y.width,height:y.height,style:y.style,selected:y.selected,className:_(y),color:h(y),borderRadius:r,strokeColor:m(y),strokeWidth:i,shapeRendering:g,onClick:u,id:y.id})}))}var Gz=p.memo(Vz);const Kz=200,Jz=150,Yz=e=>{const t=e.getNodes(),n={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:n,boundingRect:t.length>0?o8(Wg(t,e.nodeOrigin),n):n,rfId:e.rfId}},Xz="react-flow__minimap-desc";function Y$({style:e,className:t,nodeStrokeColor:n="transparent",nodeColor:r="#e2e2e2",nodeClassName:i="",nodeBorderRadius:o=5,nodeStrokeWidth:u=2,nodeComponent:l,maskColor:d="rgb(240, 240, 240, 0.6)",maskStrokeColor:h="none",maskStrokeWidth:m=1,position:_="bottom-right",onClick:g,onNodeClick:y,pannable:b=!1,zoomable:k=!1,ariaLabel:x="React Flow mini map",inversePan:N=!1,zoomStep:$=10,offsetScale:E=5}){const S=er(),P=p.useRef(null),{boundingRect:D,viewBB:R,rfId:I}=fs(Yz,hr),W=(e==null?void 0:e.width)??Kz,G=(e==null?void 0:e.height)??Jz,K=D.width/W,H=D.height/G,M=Math.max(K,H),A=M*W,O=M*G,L=E*M,V=D.x-(A-D.width)/2-L,J=D.y-(O-D.height)/2-L,U=A+L*2,te=O+L*2,z=`${Xz}-${I}`,ne=p.useRef(0);ne.current=M,p.useEffect(()=>{if(P.current){const be=yo(P.current),Me=xe=>{const{transform:Ae,d3Selection:He,d3Zoom:mt}=S.getState();if(xe.sourceEvent.type!=="wheel"||!He||!mt)return;const nt=-xe.sourceEvent.deltaY*(xe.sourceEvent.deltaMode===1?.05:xe.sourceEvent.deltaMode?1:.002)*$,rt=Ae[2]*Math.pow(2,nt);mt.scaleTo(He,rt)},je=xe=>{const{transform:Ae,d3Selection:He,d3Zoom:mt,translateExtent:nt,width:rt,height:ze}=S.getState();if(xe.sourceEvent.type!=="mousemove"||!He||!mt)return;const Ve=ne.current*Math.max(1,Ae[2])*(N?-1:1),ct={x:Ae[0]-xe.sourceEvent.movementX*Ve,y:Ae[1]-xe.sourceEvent.movementY*Ve},Qe=[[0,0],[rt,ze]],Dt=tl.translate(ct.x,ct.y).scale(Ae[2]),$e=mt.constrain()(Dt,Qe,nt);mt.transform(He,$e)},ae=i$().on("zoom",b?je:null).on("zoom.wheel",k?Me:null);return be.call(ae),()=>{be.on("zoom",null)}}},[b,k,N,$]);const se=g?be=>{const Me=qo(be);g(be,{x:Me[0],y:Me[1]})}:void 0,de=y?(be,Me)=>{const je=S.getState().nodeInternals.get(Me);y(be,je)}:void 0;return Ee.createElement(um,{position:_,style:e,className:Cr(["react-flow__minimap",t]),"data-testid":"rf__minimap"},Ee.createElement("svg",{width:W,height:G,viewBox:`${V} ${J} ${U} ${te}`,role:"img","aria-labelledby":z,ref:P,onClick:se},x&&Ee.createElement("title",{id:z},x),Ee.createElement(Gz,{onClick:de,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:o,nodeClassName:i,nodeStrokeWidth:u,nodeComponent:l}),Ee.createElement("path",{className:"react-flow__minimap-mask",d:`M${V-L},${J-L}h${U+L*2}v${te+L*2}h${-U-L*2}z
154
+ M${R.x},${R.y}h${R.width}v${R.height}h${-R.width}z`,fill:d,fillRule:"evenodd",stroke:h,strokeWidth:m,pointerEvents:"none"})))}Y$.displayName="MiniMap";var Zz=p.memo(Y$);function Qz(){return Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32"},Ee.createElement("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"}))}function eB(){return Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},Ee.createElement("path",{d:"M0 0h32v4.2H0z"}))}function tB(){return Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30"},Ee.createElement("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"}))}function nB(){return Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},Ee.createElement("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"}))}function sB(){return Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},Ee.createElement("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"}))}const Pd=({children:e,className:t,...n})=>Ee.createElement("button",{type:"button",className:Cr(["react-flow__controls-button",t]),...n},e);Pd.displayName="ControlButton";const rB=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),X$=({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:i,onZoomIn:o,onZoomOut:u,onFitView:l,onInteractiveChange:d,className:h,children:m,position:_="bottom-left"})=>{const g=er(),[y,b]=p.useState(!1),{isInteractive:k,minZoomReached:x,maxZoomReached:N}=fs(rB,hr),{zoomIn:$,zoomOut:E,fitView:S}=Tx();if(p.useEffect(()=>{b(!0)},[]),!y)return null;const P=()=>{$(),o==null||o()},D=()=>{E(),u==null||u()},R=()=>{S(i),l==null||l()},I=()=>{g.setState({nodesDraggable:!k,nodesConnectable:!k,elementsSelectable:!k}),d==null||d(!k)};return Ee.createElement(um,{className:Cr(["react-flow__controls",h]),position:_,style:e,"data-testid":"rf__controls"},t&&Ee.createElement(Ee.Fragment,null,Ee.createElement(Pd,{onClick:P,className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:N},Ee.createElement(Qz,null)),Ee.createElement(Pd,{onClick:D,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:x},Ee.createElement(eB,null))),n&&Ee.createElement(Pd,{className:"react-flow__controls-fitview",onClick:R,title:"fit view","aria-label":"fit view"},Ee.createElement(tB,null)),r&&Ee.createElement(Pd,{className:"react-flow__controls-interactive",onClick:I,title:"toggle interactivity","aria-label":"toggle interactivity"},k?Ee.createElement(sB,null):Ee.createElement(nB,null)),m)};X$.displayName="Controls";var iB=p.memo(X$),Ko;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(Ko||(Ko={}));function oB({color:e,dimensions:t,lineWidth:n}){return Ee.createElement("path",{stroke:e,strokeWidth:n,d:`M${t[0]/2} 0 V${t[1]} M0 ${t[1]/2} H${t[0]}`})}function aB({color:e,radius:t}){return Ee.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const lB={[Ko.Dots]:"#91919a",[Ko.Lines]:"#eee",[Ko.Cross]:"#e2e2e2"},cB={[Ko.Dots]:1,[Ko.Lines]:1,[Ko.Cross]:6},uB=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Z$({id:e,variant:t=Ko.Dots,gap:n=20,size:r,lineWidth:i=1,offset:o=2,color:u,style:l,className:d}){const h=p.useRef(null),{transform:m,patternId:_}=fs(uB,hr),g=u||lB[t],y=r||cB[t],b=t===Ko.Dots,k=t===Ko.Cross,x=Array.isArray(n)?n:[n,n],N=[x[0]*m[2]||1,x[1]*m[2]||1],$=y*m[2],E=k?[$,$]:N,S=b?[$/o,$/o]:[E[0]/o,E[1]/o];return Ee.createElement("svg",{className:Cr(["react-flow__background",d]),style:{...l,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:h,"data-testid":"rf__background"},Ee.createElement("pattern",{id:_+e,x:m[0]%N[0],y:m[1]%N[1],width:N[0],height:N[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${S[0]},-${S[1]})`},b?Ee.createElement(aB,{color:g,radius:$/o}):Ee.createElement(oB,{dimensions:E,color:g,lineWidth:i})),Ee.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${_+e})`}))}Z$.displayName="Background";var dB=p.memo(Z$);function Q$(e,t={}){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null;if(!n)return null;const r=typeof n.x=="number"&&Number.isFinite(n.x)?n.x:null,i=typeof n.y=="number"&&Number.isFinite(n.y)?n.y:null,o=typeof n.zoom=="number"&&Number.isFinite(n.zoom)?n.zoom:null;if(r===null||i===null||o===null)return null;const u=typeof t.maxAbsTranslate=="number"&&Number.isFinite(t.maxAbsTranslate)?Math.abs(t.maxAbsTranslate):1e6;if(Math.abs(r)>u||Math.abs(i)>u)return null;const l=typeof t.minZoom=="number"&&Number.isFinite(t.minZoom)?t.minZoom:.025,d=typeof t.maxZoom=="number"&&Number.isFinite(t.maxZoom)?t.maxZoom:6,h=Math.min(l,d),m=Math.max(l,d);return{x:r,y:i,zoom:Math.min(m,Math.max(h,o))}}function hg(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");return n!==-1&&n<t.length-1?t.slice(n+1):t}function fB(e){const t=String(e||"").trim();if(!t)return"entity";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return"entity";const r=t.slice(0,n).toLowerCase(),i=t.slice(n+1).toLowerCase();if(r==="ex"){const o=i.indexOf("-"),u=o>0?i.slice(0,o):i;return u==="person"?"person":u==="org"?"org":u==="concept"?"concept":u==="claim"?"claim":u==="event"?"event":u==="doc"?"doc":u==="thing"?"thing":"entity"}return r==="schema"||r==="skos"||r==="dcterms"||r==="rdf"||r==="cito"?"vocab":"entity"}function hB(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return hg(t);const r=t.slice(0,n).toLowerCase(),i=t.slice(n+1);if(r==="ex"){const o=i.indexOf("-");if(o>0&&o<i.length-1)return i.slice(o+1)}return hg(t)}function kv(e){const r=Math.max(1,Math.ceil(Math.sqrt(e.length))),i={};for(let o=0;o<e.length;o++){const u=Math.floor(o/r),l=o%r;i[e[o]]={x:l*240,y:u*120}}return i}function jv(e){const t=String(e??"");let n=2166136261;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return n>>>0}function eC(e){let t=e>>>0;return()=>{t+=1831565813;let n=Math.imul(t^t>>>15,1|t);return n^=n+Math.imul(n^n>>>7,61|n),((n^n>>>14)>>>0)/4294967296}}function mB(e,t){const n={},r=e.length;if(!r)return n;const i=Math.max(260,Math.sqrt(r)*150),o=t%360*Math.PI/180;for(let u=0;u<r;u++){const l=o+2*Math.PI*u/r;n[e[u]]={x:i*Math.cos(l),y:i*Math.sin(l)}}return n}function Gk(e,t,n){var b;const r={};if(!e.length)return r;const i=new Map;for(const k of e)i.set(k,new Set);for(const k of t){const x=String((k==null?void 0:k.source)||"").trim(),N=String((k==null?void 0:k.target)||"").trim();if(!x||!N||x===N)continue;const $=i.get(x),E=i.get(N);$&&$.add(N),E&&E.add(x)}let o=e[0],u=-1;for(const k of e){const x=((b=i.get(k))==null?void 0:b.size)??0;(x>u||x===u&&k.localeCompare(o)<0)&&(o=k,u=x)}const l=new Map,d=[];for(l.set(o,0),d.push(o);d.length;){const k=d.shift(),x=l.get(k)??0,N=Array.from(i.get(k)??[]);N.sort(($,E)=>$.localeCompare(E));for(const $ of N)l.has($)||(l.set($,x+1),d.push($))}let h=0;for(const k of l.values())h=Math.max(h,k);for(const k of e)l.has(k)||l.set(k,h+1);const m=new Map;for(const k of e){const x=l.get(k)??0,N=m.get(x);N?N.push(k):m.set(x,[k])}const _=Array.from(m.keys()).sort((k,x)=>k-x),g=260,y=n%360*Math.PI/180;for(const k of _){const x=m.get(k)||[];if(x.sort((S,P)=>S.localeCompare(P)),k===0){if(x.length===1)r[x[0]]={x:0,y:0};else for(let P=0;P<x.length;P++){const D=y+2*Math.PI*P/x.length;r[x[P]]={x:80*Math.cos(D),y:80*Math.sin(D)}}continue}const N=g*k,$=x.length;if($===1){r[x[0]]={x:N,y:0};continue}const E=y+k*.35;for(let S=0;S<$;S++){const P=E+2*Math.PI*S/$;r[x[S]]={x:N*Math.cos(P),y:N*Math.sin(P)}}}return r}function Ed(e,t={}){const n=t.kind??"grid",r=typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):0,i=e.nodes.map(o=>o.id);if(n==="grid")return kv(i);if(n==="circle")return mB(i,r);if(n==="radial")return Gk(i,e.edges,r);if(n==="force"){const o=Gk(i,e.edges,r),u=eC(r||1),l=Math.max(10,Math.min(42,Math.sqrt(i.length)*2.75)),d={};for(const h of i){const m=o[h]||{x:0,y:0};d[h]={x:m.x+(u()-.5)*l,y:m.y+(u()-.5)*l}}return d}return kv(i)}function _B(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&typeof t.subject=="string"&&typeof t.predicate=="string"&&typeof t.object=="string"):[]}function pB(e,t={}){const n=!!(t.groupEdges??!0),r=Math.max(1,t.maxEdgeLabelPredicates??3),i=_B(e),o=new Set;for(const g of i){const y=String(g.subject||"").trim(),b=String(g.object||"").trim();y&&o.add(y),b&&o.add(b)}const u=Array.from(o);u.sort((g,y)=>g.localeCompare(y));const l=kv(u),d=u.map(g=>({id:g,type:"default",data:{label:hB(g),kind:fB(g)},position:l[g]||{x:0,y:0}})),h=new Map,m=(g,y)=>{const b=String(g.subject||"").trim(),k=String(g.object||"").trim(),x=String(g.predicate||"").trim();return n?`edge:${b}:${k}`:`edge:${y}:${b}:${x}:${k}`};for(let g=0;g<i.length;g++){const y=i[g],b=m(y,g),k=h.get(b);k?k.push(y):h.set(b,[y])}const _=[];for(const[g,y]of h.entries()){const b=y[0],k=String(b.subject||"").trim(),x=String(b.object||"").trim();if(!k||!x)continue;const N=new Map;for(const R of y){const I=String(R.predicate||"").trim();I&&N.set(I,(N.get(I)||0)+1)}const $=Array.from(N.entries());$.sort((R,I)=>I[1]-R[1]||R[0].localeCompare(I[0]));const S=$.slice(0,r).map(([R,I])=>I>1?`${hg(R)}×${I}`:hg(R)).join(" | "),P=$.length>r?` +${$.length-r}`:"",D=`${S}${P}`.trim();_.push({id:g,source:k,target:x,label:D,animated:!1,data:{assertions:y,predicateSummary:D}})}return{nodes:d,edges:_}}function gB(e,t,n,r={}){const i=r.directed!==!1,o=String(t||"").trim(),u=String(n||"").trim();if(!o||!u)return null;if(o===u)return{nodeIds:[o],edgeIds:[]};const l=new Map,d=(k,x,N)=>{const $=l.get(k);$?$.push({to:x,edgeId:N}):l.set(k,[{to:x,edgeId:N}])};for(const k of e.edges)d(k.source,k.target,k.id),i||d(k.target,k.source,k.id);const h=[o],m=new Map,_=new Map;for(m.set(o,null),_.set(o,null);h.length;){const k=h.shift(),x=l.get(k)||[];for(const N of x)if(!m.has(N.to)){if(m.set(N.to,k),_.set(N.to,N.edgeId),N.to===u){h.length=0;break}h.push(N.to)}}if(!m.has(u))return null;const g=[],y=[];let b=u;for(;b;){g.push(b);const k=_.get(b);k&&y.push(k),b=m.get(b)||null}return g.reverse(),y.reverse(),{nodeIds:g,edgeIds:y}}const Kk={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function pp(e,t={}){const n={...Kk,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):Kk.seed},r=e.nodes.map(y=>y.id),i=r.length,o=new Float64Array(2*i),u=new Float64Array(2*i),l=new Float64Array(2*i),d=new Map;for(let y=0;y<i;y++)d.set(r[y],y);const h=t.positions??Ed(e,{kind:"force",seed:n.seed}),m=eC(n.seed||1),_=Math.max(8,Math.min(38,Math.sqrt(i)*2.25));for(let y=0;y<i;y++){const b=r[y],k=h[b],x=typeof(k==null?void 0:k.x)=="number"&&Number.isFinite(k.x)?k.x:(m()-.5)*500,N=typeof(k==null?void 0:k.y)=="number"&&Number.isFinite(k.y)?k.y:(m()-.5)*500;o[2*y]=x+(m()-.5)*_,o[2*y+1]=N+(m()-.5)*_,u[2*y]=0,u[2*y+1]=0}const g=[];for(const y of e.edges){const b=d.get(String((y==null?void 0:y.source)||"").trim()),k=d.get(String((y==null?void 0:y.target)||"").trim());typeof b!="number"||typeof k!="number"||b===k||g.push(b,k)}return{nodeIds:r,pos:o,vel:u,acc:l,edges:new Uint32Array(g),options:n,tick:0}}function yB(e,t=1){const n=e.nodeIds.length;if(!n)return;const r=e.options,i=r.dt;for(let o=0;o<Math.max(1,Math.trunc(t));o++){if(e.acc.fill(0),n<=r.maxRepulsionNodes){const y=r.repulsionStrength;for(let b=0;b<n;b++){const k=e.pos[2*b],x=e.pos[2*b+1];for(let N=b+1;N<n;N++){const $=e.pos[2*N]-k,E=e.pos[2*N+1]-x,S=$*$+E*E+1e-6,P=1/Math.sqrt(S),D=y/S,R=D*$*P,I=D*E*P;e.acc[2*b]-=R,e.acc[2*b+1]-=I,e.acc[2*N]+=R,e.acc[2*N+1]+=I}}}const l=r.springLength,d=r.springStrength,h=e.edges;for(let y=0;y<h.length;y+=2){const b=h[y],k=h[y+1],x=e.pos[2*b],N=e.pos[2*b+1],$=e.pos[2*k],E=e.pos[2*k+1],S=$-x,P=E-N,D=S*S+P*P+1e-6,R=Math.sqrt(D),I=d*(R-l),W=I*S/R,G=I*P/R;e.acc[2*b]+=W,e.acc[2*b+1]+=G,e.acc[2*k]-=W,e.acc[2*k+1]-=G}const m=r.centeringStrength;for(let y=0;y<n;y++)e.acc[2*y]+=-m*e.pos[2*y],e.acc[2*y+1]+=-m*e.pos[2*y+1];const _=r.damping,g=r.maxSpeed;for(let y=0;y<n;y++){let b=(e.vel[2*y]+e.acc[2*y]*i)*_,k=(e.vel[2*y+1]+e.acc[2*y+1]*i)*_;const x=Math.sqrt(b*b+k*k);if(x>g){const N=g/x;b*=N,k*=N}e.vel[2*y]=b,e.vel[2*y+1]=k,e.pos[2*y]+=b*i,e.pos[2*y+1]+=k*i}e.tick+=1}}function wB(e){const t=e.nodeIds.length;if(!t)return 0;let n=0;for(let r=0;r<t;r++){const i=e.vel[2*r],o=e.vel[2*r+1];n+=Math.sqrt(i*i+o*o)}return n/t}function vB(e){const t={},n=e.nodeIds.length;for(let r=0;r<n;r++)t[e.nodeIds[r]]={x:e.pos[2*r],y:e.pos[2*r+1]};return t}function Jk(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function xB(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("(pointer: coarse)").matches||window.matchMedia("(max-width: 720px)").matches}catch{return!1}}function bB(){return s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[s.jsx("rect",{x:"3",y:"3",width:"3",height:"3",rx:"1"}),s.jsx("rect",{x:"3",y:"7",width:"3",height:"3",rx:"1"}),s.jsx("rect",{x:"3",y:"11",width:"3",height:"3",rx:"1"}),s.jsx("rect",{x:"8",y:"3.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"}),s.jsx("rect",{x:"8",y:"7.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"}),s.jsx("rect",{x:"8",y:"11.5",width:"6",height:"2",rx:"1",fill:"none",strokeWidth:"1.4"})]})}function tC(e,t,n,r){const i=typeof e=="number"&&Number.isFinite(e)?e:r;return Math.min(n,Math.max(t,i))}function Ch(e){const t=tC(e,.6,2.4,1),n=240*t,r=9e3*t*t;return{springLength:n,repulsionStrength:r}}const _m="abstractuic_amx_saved_layouts_v1",Sv=.025,Nv=6,nC=1e6;function Lx(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function $v(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function kB(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:null;if(!t)return null;const n=typeof t.x=="number"&&Number.isFinite(t.x)?t.x:null,r=typeof t.y=="number"&&Number.isFinite(t.y)?t.y:null;return n===null||r===null?null:{x:n,y:r}}function Yk(e){const t=Lx();if(!t)return null;const n=String(e??"").trim();if(!n)return null;try{const r=t.getItem(_m);if(!r)return null;const i=JSON.parse(r),o=i&&typeof i=="object"&&!Array.isArray(i)?i:null;if(!o)return null;const u=o[n],l=u&&typeof u=="object"&&!Array.isArray(u)?u:null;if(!l)return null;const d=l.version===1?1:null;if(d===null)return null;const h=$v(l.kind,"grid"),m=typeof l.seed=="number"&&Number.isFinite(l.seed)?Math.trunc(l.seed):jv(n),_=l.positions&&typeof l.positions=="object"&&!Array.isArray(l.positions)?l.positions:null,g={};if(_)for(const[k,x]of Object.entries(_)){const N=kB(x);N&&(g[String(k)]=N)}const y=Q$(l.viewport,{minZoom:Sv,maxZoom:Nv,maxAbsTranslate:nC})??void 0,b=typeof l.saved_at=="string"&&l.saved_at.trim()?l.saved_at.trim():"";return{version:d,kind:h,seed:m,positions:g,viewport:y,saved_at:b}}catch{return null}}function jB(e,t){const n=Lx();if(!n)return;const r=String(e??"").trim();if(r)try{const i=n.getItem(_m),o=i?JSON.parse(i):null,u=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:{};u[r]=t,n.setItem(_m,JSON.stringify(u))}catch{}}function SB(e){const t=Lx();if(!t)return;const n=String(e??"").trim();if(n)try{const r=t.getItem(_m);if(!r)return;const i=JSON.parse(r),o=i&&typeof i=="object"&&!Array.isArray(i)?{...i}:null;if(!o||!(n in o))return;delete o[n],t.setItem(_m,JSON.stringify(o))}catch{}}function NB(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function cw(e,t){const n=!!(t!=null&&t.allowZero),r=!!(t!=null&&t.allowNegativeOne),i=String(e??"").trim();if(!i)return;const o=Number(i);if(!Number.isFinite(o))return;const u=Math.trunc(o);if(r&&u===-1)return-1;if(!(!n&&u<=0)&&!(n&&u<0))return u}function $B(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.recall_level=="string"?t.recall_level:"",r=t.applied&&typeof t.applied=="object"&&!Array.isArray(t.applied)?t.applied:null,i=[];return n&&i.push(`recall_level=${n}`),r&&(typeof r.limit=="number"&&i.push(`limit=${r.limit}`),typeof r.min_score=="number"&&i.push(`min_score=${r.min_score}`),typeof r.max_input_tokens=="number"&&i.push(`max_input_tokens=${r.max_input_tokens}`)),i.length?i.join(" · "):null}function CB(e){if(!e||typeof e!="object")return null;const t=[],n=typeof e.scope=="string"?e.scope.trim():"",r=typeof e.owner_id=="string"?e.owner_id.trim():"";n&&t.push(`scope=${n}`),r&&t.push(`owner_id=${r}`);const i=typeof e.confidence=="number"&&Number.isFinite(e.confidence)?e.confidence:null;i!==null&&t.push(`confidence=${i.toFixed(3)}`);const o=e.provenance&&typeof e.provenance=="object"&&!Array.isArray(e.provenance)?e.provenance:null;if(o){const h=typeof o.writer_run_id=="string"?o.writer_run_id.trim():"",m=typeof o.writer_workflow_id=="string"?o.writer_workflow_id.trim():"";h&&t.push(`writer_run_id=${h}`),m&&t.push(`writer_workflow_id=${m}`)}const u=e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)?e.attributes:null,l=u&&u._retrieval&&typeof u._retrieval=="object"&&!Array.isArray(u._retrieval)?u._retrieval:null,d=l&&typeof l.score=="number"&&Number.isFinite(l.score)?l.score:null;return d!==null&&t.push(`score=${d.toFixed(3)}`),t.length?t.join(" · "):null}function EB(e,t){const n=String(e??""),r=String(t??"").trim();if(!r)return n;const i=n.toLowerCase().indexOf(r.toLowerCase());if(i<0)return n;const o=n.slice(0,i),u=n.slice(i,i+r.length),l=n.slice(i+r.length);return s.jsxs(s.Fragment,{children:[o,s.jsx("span",{className:"amx-hl",children:u}),l]})}function Eh(e){const t=String(e??"").trim().toLowerCase();return t==="person"?{stroke:"rgba(96, 165, 250, 0.82)",bg:"rgba(96, 165, 250, 0.10)",minimap:"rgba(96, 165, 250, 0.85)"}:t==="org"?{stroke:"rgba(34, 197, 94, 0.78)",bg:"rgba(34, 197, 94, 0.10)",minimap:"rgba(34, 197, 94, 0.82)"}:t==="concept"?{stroke:"rgba(168, 85, 247, 0.78)",bg:"rgba(168, 85, 247, 0.10)",minimap:"rgba(168, 85, 247, 0.82)"}:t==="claim"?{stroke:"rgba(251, 191, 36, 0.78)",bg:"rgba(251, 191, 36, 0.10)",minimap:"rgba(251, 191, 36, 0.82)"}:t==="event"?{stroke:"rgba(239, 68, 68, 0.74)",bg:"rgba(239, 68, 68, 0.10)",minimap:"rgba(239, 68, 68, 0.80)"}:t==="doc"?{stroke:"rgba(14, 165, 233, 0.74)",bg:"rgba(14, 165, 233, 0.10)",minimap:"rgba(14, 165, 233, 0.80)"}:t==="vocab"?{stroke:"rgba(148, 163, 184, 0.55)",bg:"rgba(148, 163, 184, 0.06)",minimap:"rgba(148, 163, 184, 0.70)"}:t==="thing"?{stroke:"rgba(255, 255, 255, 0.20)",bg:"rgba(255, 255, 255, 0.04)",minimap:"rgba(255, 255, 255, 0.30)"}:{stroke:"rgba(255, 255, 255, 0.14)",bg:"rgba(0, 0, 0, 0.18)",minimap:"rgba(255, 255, 255, 0.24)"}}function AB(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),r=Date.parse(n);return Number.isFinite(r)?r:null}function Ah(e){const t=AB(e);if(t===null)return"";const n=new Date(t),r=n.getUTCFullYear(),i=String(n.getUTCMonth()+1).padStart(2,"0"),o=String(n.getUTCDate()).padStart(2,"0"),u=String(n.getUTCHours()).padStart(2,"0"),l=String(n.getUTCMinutes()).padStart(2,"0");return`${r}/${i}/${o} ${u}:${l}`}function sC(e){const t=String(e??"").trim();if(!t)return"";const n=t.indexOf(":");return n!==-1&&n<t.length-1?t.slice(n+1):t}function uw(e,t){const n=String(e??"").trim().toLowerCase();return!!(n&&t.has(n))}function TB(e,t={}){const n=Math.max(1,t.maxPredicates??3),r=new Map;for(const d of e){const h=String((d==null?void 0:d.predicate)||"").trim();h&&r.set(h,(r.get(h)||0)+1)}const i=Array.from(r.entries());i.sort((d,h)=>h[1]-d[1]||d[0].localeCompare(h[0]));const u=i.slice(0,n).map(([d,h])=>{const m=sC(d);return h>1?`${m}×${h}`:m}).join(" | "),l=i.length>n?` +${i.length-n}`:"";return`${u}${l}`.trim()}function MB({resetKey:e,queryMode:t,items:n,activeMemoryText:r,packets:i,packetsVersion:o,packedCount:u,dropped:l,estimatedTokens:d,effort:h,warnings:m,onQuery:_,onItemsReplace:g,onOpenSpan:y,onOpenTranscript:b}){var Gn;const k=p.useRef(null),x=p.useMemo(()=>{const Y=n==null?void 0:n[0],he=n==null?void 0:n[n.length-1],Oe=Y?`${Y.subject}|${Y.predicate}|${Y.object}`:"",De=he?`${he.subject}|${he.predicate}|${he.object}`:"";return`${(n==null?void 0:n.length)||0}:${Oe}:${De}`},[n]),N=String(e??x),$=t==="replace"?"replace":"override",[E,S]=p.useState(null),[P,D]=p.useState(null),[R,I]=p.useState(!1),[W,G]=p.useState(""),[K,H]=p.useState(!1),[M,A]=p.useState("");p.useEffect(()=>{S(null),D(null),G(""),I(!1),A(""),H(!1)},[N]);const[O,L]=p.useState(""),[V,J]=p.useState(!0),[U,te]=p.useState(!1),[z,ne]=p.useState(!0),[se]=p.useState(()=>({compact:xB(),show:!1})),de=se.compact,[be,Me]=p.useState(se.show),[je,ae]=p.useState(!1),xe=N,Ae=p.useMemo(()=>jv(xe),[xe]),[He,mt]=p.useState("grid"),[nt,rt]=p.useState(Ae),[ze,Ve]=p.useState(!1),[ct,Qe]=p.useState(1),Dt=p.useRef(null),$e=p.useRef(null),Le=p.useRef(!1),[ce,Q]=p.useState(0),_e=p.useRef(null),le=p.useRef(0),Se=p.useRef(0),pe=p.useRef(0),dt=p.useRef(0),[yt,_t]=p.useState(!1),[It,bt]=p.useState(""),[St,ut]=p.useState({}),Ot=p.useRef({});p.useEffect(()=>{Ot.current=St},[St]);const[Mt,mn]=p.useState(""),[yn,In]=p.useState(""),Gs=p.useMemo(()=>{var he;const Y=(he=n==null?void 0:n[0])==null?void 0:he.scope;return Jk(Y,"session")},[n]),[ss,ge]=p.useState(Gs),[Re,gt]=p.useState("standard"),[re,fe]=p.useState(""),[Ce,Ie]=p.useState(""),[We,Ue]=p.useState(""),[et,at]=p.useState(""),[vt,xt]=p.useState(""),[Et,zt]=p.useState(""),[ot,Jt]=p.useState(""),[wn,hn]=p.useState("qwen/qwen3-next-80b");p.useEffect(()=>{ge(Gs)},[N]);const sn=Array.isArray(n)?n:[],Vt=typeof r=="string"?r:"",rs=Array.isArray(i)?i:[],Be=typeof o=="number"?o:void 0,Zt=typeof u=="number"?u:void 0,Tt=typeof l=="number"?l:void 0,Dn=typeof d=="number"?d:void 0,fn=h,Xe=m,nn=$==="override"&&(E!=null&&E.items)&&Array.isArray(E.items)?E.items:sn,cn=typeof(E==null?void 0:E.active_memory_text)=="string"&&E.active_memory_text.trim()?E.active_memory_text:Vt,Er=(E==null?void 0:E.effort)??fn,Cs=(E==null?void 0:E.warnings)??Xe,gs=p.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),mr=p.useMemo(()=>z?nn:(nn||[]).filter(Y=>!uw(Y==null?void 0:Y.predicate,gs)),[nn,z,gs]),we=p.useMemo(()=>pB(nn,{groupEdges:V}),[nn,V]),Nt=p.useMemo(()=>{if(z)return we;const Y=[];for(const he of we.edges){const De=(he&&he.data&&Array.isArray(he.data.assertions)?he.data.assertions:[]).filter(ht=>!uw(ht==null?void 0:ht.predicate,gs));if(!De.length)continue;const Ye=TB(De);Y.push({...he,label:Ye,data:{...he.data,assertions:De,predicateSummary:Ye}})}return{nodes:we.nodes,edges:Y}},[we,z,gs]),Fn=p.useMemo(()=>Nt.nodes.map(Y=>Y.id),[Nt.nodes]),tr=p.useMemo(()=>{const Y=Fn[0]||"",he=Fn[Fn.length-1]||"";return`${Fn.length}:${Y}:${he}`},[Fn]),Ni=p.useMemo(()=>{var he;const Y=new Map;for(const Oe of Nt.nodes)Y.set(Oe.id,String(((he=Oe.data)==null?void 0:he.label)||Oe.id));return Y},[Nt.nodes]),nr=p.useMemo(()=>{var he;const Y=new Map;for(const Oe of Nt.nodes)Y.set(Oe.id,String(((he=Oe.data)==null?void 0:he.kind)||""));return Y},[Nt.nodes]),vo=O.trim().toLowerCase(),uc=p.useMemo(()=>{var he;if(!vo)return new Set;const Y=new Set;for(const Oe of Nt.nodes){const De=String(Oe.id||"").toLowerCase(),Ye=String(((he=Oe.data)==null?void 0:he.label)||"").toLowerCase();(De.includes(vo)||Ye.includes(vo))&&Y.add(Oe.id)}return Y},[Nt.nodes,vo]),ll=p.useCallback((Y,he)=>{const Oe={};for(const De of Fn){const Ye=Y[De]||he[De];Oe[De]=Ye?{x:Ye.x,y:Ye.y}:{x:0,y:0}}return Oe},[Fn]);p.useEffect(()=>{ut(Y=>{const he=Ed(Nt,{kind:He,seed:nt}),Oe={};for(const De of Fn){const Ye=Y[De]||he[De];Oe[De]=Ye?{x:Ye.x,y:Ye.y}:{x:0,y:0}}return Oe})},[Nt,He,nt,Fn,tr]),p.useEffect(()=>{if(!Le.current)return;const Y=k.current;if(!(!Y||typeof Y.fitView!="function")&&Fn.length){Le.current=!1;try{Y.fitView({padding:.2,duration:0})}catch{try{Y.fitView({padding:.2})}catch{}}}},[Fn.length,tr,St]),p.useEffect(()=>{Ve(!1),Dt.current=null,$e.current=null,Le.current=!1,le.current=0,Se.current=0,pe.current=0;const Y=Yk(xe);if(Y&&Object.keys(Y.positions||{}).length){if(mt(Y.kind),rt(Y.seed),_t(!0),bt(Y.saved_at||""),Y.viewport){$e.current=Y.viewport;const Ye=k.current;if(Ye&&typeof Ye.setViewport=="function"){try{Ye.setViewport(Y.viewport,{duration:0})}catch{try{Ye.setViewport(Y.viewport)}catch{}}$e.current=null}}else Le.current=!0;const De=Ed(Nt,{kind:Y.kind,seed:Y.seed});ut(ll(Y.positions,De));return}_t(!1),bt("");const he=jv(xe);rt(he);const Oe=Ed(Nt,{kind:He,seed:he});ut(Oe),He==="force"&&Nt.nodes.length>0&&Nt.nodes.length<=320&&(Dt.current=pp(Nt,{seed:he,positions:Oe,...Ch(ct)}),Ve(!0))},[xe]);const bs=p.useMemo(()=>{const Y=String(Mt||"").trim(),he=String(yn||"").trim();return!Y||!he?null:gB(Nt,Y,he,{directed:U})},[Nt,Mt,yn,U]),_r=!!(bs&&String(Mt||"").trim()&&String(yn||"").trim()),Ts=p.useMemo(()=>{const Y=String(Mt||"").trim(),he=String(yn||"").trim();if(!Y||!he)return null;const Oe=U,De=new Map,Ye=(Pt,Bt)=>{const pn=De.get(Pt);pn?pn.push(Bt):De.set(Pt,[Bt])};for(const Pt of Nt.edges)Ye(Pt.source,Pt.target),Oe||Ye(Pt.target,Pt.source);const ht=new Set,Wt=[];for(ht.add(Y),Wt.push(Y);Wt.length;){const Pt=Wt.shift(),Bt=De.get(Pt)||[];for(const pn of Bt)ht.has(pn)||(ht.add(pn),Wt.push(pn))}return{reachableFromStart:ht.size,endReachable:ht.has(he),nodes:Nt.nodes.length,edges:Nt.edges.length,assertions:mr.length}},[U,Nt.edges,Nt.nodes.length,yn,Mt,mr.length]),zi=p.useMemo(()=>new Set((bs==null?void 0:bs.nodeIds)||[]),[bs]),cl=p.useMemo(()=>new Set((bs==null?void 0:bs.edgeIds)||[]),[bs]),[ys,ni]=p.useState(""),[Ms,si]=p.useState(""),ks=!!(String(ys||"").trim()||String(Ms||"").trim()),ri=p.useMemo(()=>{const Y=new Set,he=new Set,Oe=String(ys||"").trim(),De=String(Ms||"").trim();if(Oe){Y.add(Oe);for(const Ye of Nt.edges)(Ye.source===Oe||Ye.target===Oe)&&(he.add(Ye.id),Y.add(Ye.source),Y.add(Ye.target));return{nodes:Y,edges:he}}if(De){const Ye=Nt.edges.find(ht=>ht.id===De);Ye&&(he.add(Ye.id),Y.add(Ye.source),Y.add(Ye.target))}return{nodes:Y,edges:he}},[Nt.edges,Ms,ys]);p.useEffect(()=>{ni(""),si(""),mn(""),In("")},[N]);const[Bi,Ln]=p.useState(!1);p.useEffect(()=>{Ln(!1)},[N]),p.useEffect(()=>{ze||(Dt.current=null)},[ze]),p.useEffect(()=>{if(He!=="force")return;const Y=Dt.current;if(!Y)return;const he=Ch(ct);Y.options.springLength=he.springLength,Y.options.repulsionStrength=he.repulsionStrength},[He,ct]),p.useEffect(()=>{He!=="force"&&ze&&Ve(!1)},[He,ze]),p.useEffect(()=>{if(!ze||He!=="force"||Nt.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;Dt.current||(Dt.current=pp(Nt,{seed:nt,positions:Ot.current,...Ch(ct)}));let Y=0,he=0,Oe=0;const De=Nt.nodes.length<=140?2:1,Ye=1600,ht=.08,Wt=Pt=>{if(Y=window.requestAnimationFrame(Wt),Pt-he<33)return;he=Pt;const Bt=Dt.current;if(!Bt){Ve(!1);return}yB(Bt,De),Oe+=De,ut(vB(Bt)),(wB(Bt)<=ht||Oe>=Ye)&&Ve(!1)};return Y=window.requestAnimationFrame(Wt),()=>{window.cancelAnimationFrame(Y)}},[Nt,He,ze,nt]);const Sa=p.useMemo(()=>Nt.nodes.map(Y=>{var xn;const he=zi.has(Y.id),Oe=uc.has(Y.id),De=ys===Y.id,Ye=ks&&ri.nodes.has(Y.id),ht=Eh((xn=Y.data)==null?void 0:xn.kind),Wt="rgba(34, 211, 238, 0.88)",Pt=Oe?"0 0 0 1px rgba(34, 211, 238, 0.34), 0 0 16px rgba(34, 211, 238, 0.26), 0 0 44px rgba(34, 211, 238, 0.14)":"",Bt=he?"rgba(168, 85, 247, 0.9)":Oe?Wt:ht.stroke,pn=De?"0 0 0 2px rgba(255,255,255,0.20), 0 18px 46px rgba(0,0,0,0.55)":Ye?"0 0 0 1px rgba(96, 165, 250, 0.28), 0 12px 34px rgba(0,0,0,0.45)":void 0,Cn=Pt&&pn?`${Pt}, ${pn}`:pn||Pt||void 0,Ks=he?"rgba(168, 85, 247, 0.10)":Oe?"rgba(34, 211, 238, 0.08)":ht.bg,Ft=_r?he||De?1:.16:ks?Ye||De?1:.1:1;return{...Y,position:St[Y.id]?{x:St[Y.id].x,y:St[Y.id].y}:Y.position,style:{...Y.style||{},border:`1px solid ${Bt}`,borderRadius:10,background:Ks,color:"rgba(255,255,255,0.92)",opacity:Ft,padding:8,fontSize:12,boxShadow:Cn,width:180,cursor:"pointer"}}}),[Nt.nodes,_r,uc,St,ys,zi,ks,ri.nodes]),ul=p.useMemo(()=>Nt.edges.map(Y=>{const he=cl.has(Y.id),Oe=Ms===Y.id,De=ks&&ri.edges.has(Y.id),Ye=he?"rgba(168, 85, 247, 0.9)":ks?De||Oe?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",ht=he?2.75:ks?De||Oe?2.25:1.25:1.5,Wt=Oe?"drop-shadow(0 0 10px rgba(168, 85, 247, 0.25))":void 0,Pt=he?"rgba(168, 85, 247, 0.9)":_r?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",Bt=_r?he||Oe?1:.1:ks?De||Oe?1:.08:1,pn=_r?he||Oe?1:0:ks?De||Oe?1:0:1,Cn=_r?he||Oe?String(Y.label||""):"":String(Y.label||"");return{...Y,label:Cn,style:{...Y.style||{},stroke:Ye,strokeWidth:ht,filter:Wt,opacity:Bt},animated:!1,markerEnd:{type:hm.ArrowClosed,color:Pt,width:20,height:20},labelShowBg:!0,labelBgPadding:[6,3],labelBgBorderRadius:10,labelBgStyle:{fill:`rgba(0, 0, 0, ${.38*pn})`,stroke:`rgba(255, 255, 255, ${.14*pn})`,strokeWidth:1},labelStyle:{fill:`rgba(255, 255, 255, ${.92*pn})`,fontSize:10,fontWeight:600,letterSpacing:.2,textTransform:"lowercase"}}}),[Nt.edges,_r,Ms,cl,ks,ri.edges]),dl=p.useMemo(()=>{if(!Ms)return[];const Y=Nt.edges.find(Oe=>Oe.id===Ms),he=Y&&Y.data&&Array.isArray(Y.data.assertions)?Y.data.assertions:[];return Array.isArray(he)?he:[]},[Nt.edges,Ms]),Ar=p.useMemo(()=>Ms&&Nt.edges.find(Y=>Y.id===Ms)||null,[Nt.edges,Ms]),dc=p.useMemo(()=>{const Y=String(ys||"").trim();return Y?nn.filter(he=>!he||typeof he!="object"||!(he.subject===Y||he.object===Y)?!1:z?!0:!uw(he.predicate,gs)):[]},[nn,ys,z,gs]),Ui=p.useMemo(()=>Ms?dl:dc,[dl,Ms,dc]),Na=p.useMemo(()=>{const Y=new Map;for(const he of Ui){if(!he||typeof he!="object")continue;const Oe=he.provenance&&typeof he.provenance=="object"&&!Array.isArray(he.provenance)?he.provenance:null,De=Oe&&typeof Oe.span_id=="string"?Oe.span_id.trim():"",Ye=Oe&&typeof Oe.writer_run_id=="string"?Oe.writer_run_id.trim():"",ht=typeof he.owner_id=="string"?he.owner_id.trim():"",Wt=Ye||ht;if(!Wt||!De)continue;const Pt=`${Wt}|${De}`,Bt=Y.get(Pt),pn=typeof he.observed_at=="string"?he.observed_at.trim():"";Bt?(Bt.count+=1,pn&&(!Bt.last_observed_at||pn>Bt.last_observed_at)&&(Bt.last_observed_at=pn,Bt.last_observed_at_fmt=Ah(pn),Bt.assertion=he)):Y.set(Pt,{span_run_id:Wt,span_id:De,writer_run_id:Ye,count:1,last_observed_at:pn,last_observed_at_fmt:Ah(pn),assertion:he})}return Array.from(Y.values()).sort((he,Oe)=>String(Oe.last_observed_at||"").localeCompare(String(he.last_observed_at||"")))},[Ui]),xo=p.useMemo(()=>{const Y=new Map;for(const he of Ui){if(!he||typeof he!="object")continue;const Oe=he.provenance&&typeof he.provenance=="object"&&!Array.isArray(he.provenance)?he.provenance:null,De=Oe&&typeof Oe.span_id=="string"?Oe.span_id.trim():"",Ye=Oe&&typeof Oe.writer_run_id=="string"?Oe.writer_run_id.trim():"";if(!Ye||De)continue;const ht=Y.get(Ye),Wt=typeof he.observed_at=="string"?he.observed_at.trim():"";ht?(ht.count+=1,Wt&&(!ht.last_observed_at||Wt>ht.last_observed_at)&&(ht.last_observed_at=Wt,ht.last_observed_at_fmt=Ah(Wt),ht.assertion=he)):Y.set(Ye,{run_id:Ye,count:1,last_observed_at:Wt,last_observed_at_fmt:Ah(Wt),assertion:he})}return Array.from(Y.values()).sort((he,Oe)=>String(Oe.last_observed_at||"").localeCompare(String(he.last_observed_at||"")))},[Ui]),Ps=p.useCallback(Y=>{const he=String(Y.run_id||"").trim(),Oe=typeof Y.span_id=="string"?String(Y.span_id).trim():"";if(he){if(b){try{b({run_id:he,span_id:Oe||void 0,assertion:Y.assertion})}catch{}return}if(y&&Oe)try{y({run_id:he,span_id:Oe,assertion:Y.assertion})}catch{}}},[y,b]),Ds=p.useCallback(async Y=>{var Oe;const he=String(Y??"");if(he){try{if(typeof((Oe=navigator.clipboard)==null?void 0:Oe.writeText)=="function"){await navigator.clipboard.writeText(he);return}}catch{}try{const De=document.createElement("textarea");De.value=he,De.style.position="fixed",De.style.left="-9999px",document.body.appendChild(De),De.select(),document.execCommand("copy"),document.body.removeChild(De)}catch{}}},[]),pr=p.useCallback(()=>{const Y=k.current;if(!(!Y||typeof Y.fitView!="function")){if(ys&&typeof Y.getNode=="function"){const he=Y.getNode(ys);if(he){Y.fitView({nodes:[he],padding:.55,duration:350});return}}Y.fitView({padding:.2,duration:350})}},[ys]),bo=p.useCallback(Y=>{const he=Y.kind,Oe=Math.trunc(Y.seed);Ve(!1),Dt.current=null,$e.current=null,mt(he),rt(Oe);const De=Ed(Nt,{kind:he,seed:Oe});ut(De),he==="force"&&(Y.autoPlay??!0)&&Nt.nodes.length>0&&Nt.nodes.length<=320&&(Dt.current=pp(Nt,{seed:Oe,positions:De,...Ch(ct)}),Ve(!0))},[Nt,ct]),Ur=p.useCallback(()=>{if(He==="force"){if(ze){Ve(!1);return}Dt.current=pp(Nt,{seed:nt,positions:Ot.current,...Ch(ct)}),Ve(!0)}},[Nt,He,ze,nt,ct]);p.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&dt.current&&window.cancelAnimationFrame(dt.current)},[]);const Tr=p.useCallback(()=>{const Y=k.current;if(!Y||typeof Y.getViewport!="function"||!Fn.length)return null;const he=_e.current;if(!he)return null;const Oe=he.getBoundingClientRect();if(!Number.isFinite(Oe.width)||!Number.isFinite(Oe.height)||Oe.width<64||Oe.height<64)return null;const De=Y.getViewport(),Ye=typeof(De==null?void 0:De.zoom)=="number"&&Number.isFinite(De.zoom)?De.zoom:null,ht=typeof(De==null?void 0:De.x)=="number"&&Number.isFinite(De.x)?De.x:null,Wt=typeof(De==null?void 0:De.y)=="number"&&Number.isFinite(De.y)?De.y:null;if(Ye===null||ht===null||Wt===null||Ye<=0)return null;const Pt=140,Bt=Math.min(Fn.length,180),pn=Ot.current;let Cn=0,Ks=0;for(const Ft of Fn){const xn=pn[Ft];if(!xn||!Number.isFinite(xn.x)||!Number.isFinite(xn.y))continue;Ks+=1;const os=[{x:xn.x,y:xn.y},{x:xn.x+90,y:xn.y+24}];for(const Hn of os){const Mr=Hn.x*Ye+ht,gr=Hn.y*Ye+Wt;if(Mr>-Pt&&Mr<Oe.width+Pt&&gr>-Pt&&gr<Oe.height+Pt)return!1}if(Cn++,Cn>=Bt)break}return Ks?!0:null},[Fn]),Wr=p.useCallback(Y=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||dt.current||(dt.current=window.requestAnimationFrame(()=>{dt.current=0;const he=Tr();if(he===null){if(pe.current>=12)return;pe.current+=1,window.setTimeout(()=>Wr(`${Y}:probe`),120);return}if(he!==!0){pe.current=0,Se.current=0;return}pe.current=0;const Oe=k.current;if(Oe&&typeof Oe.fitView=="function")try{Oe.fitView({padding:.2,duration:0})}catch{try{Oe.fitView({padding:.2})}catch{}}if(Se.current+=1,Se.current>=4&&le.current<1){Se.current=0,le.current+=1,Q(De=>De+1);return}Se.current<8&&window.setTimeout(()=>Wr(`${Y}:retry`),220)}))},[Tr]);p.useEffect(()=>{Se.current=0,le.current=0,pe.current=0,Wr("mount")},[N,Wr]),p.useEffect(()=>{Wr("graph change")},[tr,Wr]),p.useEffect(()=>{const Y=_e.current;if(!Y||typeof window>"u"||typeof ResizeObserver!="function")return;const he=new ResizeObserver(()=>Wr("resize"));return he.observe(Y),()=>he.disconnect()},[Wr]);const fc=p.useCallback(()=>{const Y=new Date().toISOString(),he={};for(const Wt of Fn){const Pt=Ot.current[Wt];Pt&&typeof Pt.x=="number"&&typeof Pt.y=="number"&&(he[Wt]={x:Pt.x,y:Pt.y})}const Oe=k.current,De=Oe&&typeof Oe.toObject=="function"?Oe.toObject():null,Ye=De&&De.viewport?De.viewport:Oe&&typeof Oe.getViewport=="function"?Oe.getViewport():null,ht=Q$(Ye,{minZoom:Sv,maxZoom:Nv,maxAbsTranslate:nC})??void 0;jB(xe,{version:1,kind:He,seed:nt,positions:he,viewport:ht,saved_at:Y}),_t(!0),bt(Y),Ve(!1)},[xe,He,nt,Fn]),qr=p.useCallback(()=>{const Y=Yk(xe);if(!Y)return;Ve(!1),Dt.current=null,mt(Y.kind),rt(Y.seed),_t(!0),bt(Y.saved_at||""),$e.current=Y.viewport||null,Le.current=!Y.viewport;const he=Ed(Nt,{kind:Y.kind,seed:Y.seed});if(ut(ll(Y.positions,he)),Y.viewport){const Oe=k.current;if(Oe&&typeof Oe.setViewport=="function"){try{Oe.setViewport(Y.viewport,{duration:0})}catch{try{Oe.setViewport(Y.viewport)}catch{}}$e.current=null}}},[ll,Nt,xe]),xu=p.useCallback(()=>{SB(xe),_t(!1),bt("")},[xe]),$i=p.useCallback(Y=>{if(!Array.isArray(Y)||Y.length===0)return;let he=!1;ut(Oe=>{let De=Oe,Ye=!1;for(const ht of Y){const Wt=ht&&typeof ht=="object"&&"id"in ht&&typeof ht.id=="string"?String(ht.id):"",Pt=(ht==null?void 0:ht.type)==="position"?ht==null?void 0:ht.position:null;Wt&&Pt&&typeof Pt.x=="number"&&typeof Pt.y=="number"&&(Ye||(De={...Oe},Ye=!0),De[Wt]={x:Pt.x,y:Pt.y},ht!=null&&ht.dragging&&(he=!0))}return Ye?De:Oe}),he&&ze&&Ve(!1)},[ze]),Yo=p.useMemo(()=>{const Y=new Map;for(const he of Nt.edges)Y.set(he.id,he);return Y},[Nt.edges]),fl=p.useMemo(()=>{var De;if(!bs)return[];const Y=bs.nodeIds||[],he=bs.edgeIds||[],Oe=[];for(let Ye=0;Ye<Math.min(Y.length-1,he.length);Ye++){const ht=Y[Ye],Wt=Y[Ye+1],Pt=he[Ye],Bt=Yo.get(Pt),pn=String(((De=Bt==null?void 0:Bt.data)==null?void 0:De.predicateSummary)||(Bt==null?void 0:Bt.label)||"").trim(),Cn=Bt&&Bt.source===ht&&Bt.target===Wt?"forward":Bt&&Bt.source===Wt&&Bt.target===ht?"reverse":"unknown";Oe.push({from:ht,to:Wt,edgeId:Pt,predicate:pn,dir:Cn})}return Oe},[Yo,bs]),ko=p.useCallback(async()=>{if(_){G(""),A(""),I(!0);try{const Y=NB(vt),he=cw(Et,{allowZero:!0,allowNegativeOne:!0}),Oe=cw(ot,{allowZero:!0}),De=await _({scope:ss,owner_id:void 0,recall_level:Re,query_text:re||void 0,subject:Ce||void 0,predicate:We||void 0,object:et||void 0,min_score:Y,limit:he,max_input_tokens:Oe,model:wn||void 0});S(De),D("live query"),$==="replace"&&g&&De&&Array.isArray(De.items)&&g(De.items,{kind:"live query",result:De})}catch(Y){const he=Y instanceof Error?Y.message:String(Y);G(he||"Query failed")}finally{I(!1)}}},[Et,ot,vt,wn,et,g,_,We,$,re,Re,ss,Ce]),ii=p.useCallback(async()=>{if(!_)return;const Y=String(Mt||"").trim(),he=String(yn||"").trim();if(!Y||!he)return;const Oe=Math.max(200,cw(Et)??80),De=60;A(""),G(""),H(!0);try{const Ye=[],ht=new Set,Wt=Ft=>{if(!Ft||typeof Ft!="object"||typeof Ft.subject!="string"||typeof Ft.predicate!="string"||typeof Ft.object!="string")return;const xn=`${Ft.subject}|${Ft.predicate}|${Ft.object}|${String(Ft.observed_at||"")}|${String(Ft.scope||"")}|${String(Ft.owner_id||"")}`;ht.has(xn)||(ht.add(xn),Ye.push(Ft))};for(const Ft of nn)Wt(Ft);const Pt=U,Bt=new Set,pn=[Y],Cn=new Set([Y]),Ks=async Ft=>{const xn=await _({scope:ss,recall_level:Re,min_score:0,limit:Oe,subject:Ft,query_text:void 0,max_input_tokens:0,model:void 0});if(xn&&Array.isArray(xn.items)){for(const os of xn.items)if(Wt(os),typeof os.subject=="string"&&os.subject.trim()===Ft&&typeof os.object=="string"){const Hn=os.object.trim();Hn&&!Cn.has(Hn)&&(Cn.add(Hn),pn.push(Hn))}}if(!Pt){const os=await _({scope:ss,recall_level:Re,min_score:0,limit:Oe,object:Ft,query_text:void 0,max_input_tokens:0,model:void 0});if(os&&Array.isArray(os.items)){for(const Hn of os.items)if(Wt(Hn),typeof Hn.object=="string"&&Hn.object.trim()===Ft&&typeof Hn.subject=="string"){const Mr=Hn.subject.trim();Mr&&!Cn.has(Mr)&&(Cn.add(Mr),pn.push(Mr))}}}};for(;pn.length&&Bt.size<De&&!Cn.has(he);){const Ft=pn.shift();!Ft||Bt.has(Ft)||(Bt.add(Ft),await Ks(Ft))}S({ok:!0,count:Ye.length,items:Ye,active_memory_text:cn,raw:{expanded_for_path:!0,expanded_nodes:Bt.size,discovered_nodes:Cn.size,merged:Ye.length,directed:Pt}}),D("expanded neighborhood"),$==="replace"&&g&&g(Ye,{kind:"expanded neighborhood",result:{ok:!0,count:Ye.length,items:Ye,active_memory_text:cn,raw:{expanded_for_path:!0,expanded_nodes:Bt.size,discovered_nodes:Cn.size,merged:Ye.length,directed:Pt}}})}catch(Ye){const ht=Ye instanceof Error?Ye.message:String(Ye);A(ht||"Expand neighborhood failed")}finally{H(!1)}},[U,cn,nn,Et,g,_,yn,Mt,$,Re,ss]),$a=p.useCallback(()=>{S(null),D(null),G(""),I(!1),A(""),H(!1),mn(""),In(""),ni(""),si("")},[]),Wi="Search KG",sr=Nt.nodes.length,af=Nt.edges.length,oi=mr.length;return s.jsx("div",{className:"amx-host",children:s.jsxs("div",{className:"amx-root",children:[s.jsxs("div",{className:"amx-left",children:[s.jsx("div",{className:"amx-graphbar",role:"toolbar","aria-label":"Graph layout controls",children:s.jsxs("div",{className:"amx-graphbar-row",children:[s.jsx("span",{className:"amx-graphbar-title",children:"layout"}),s.jsxs("select",{value:He,onChange:Y=>mt($v(Y.target.value,He)),disabled:!Fn.length,children:[s.jsx("option",{value:"grid",children:"grid (deterministic)"}),s.jsx("option",{value:"radial",children:"radial (bfs)"}),s.jsx("option",{value:"circle",children:"circle"}),s.jsx("option",{value:"force",children:"force (simulation)"})]}),He==="force"?s.jsxs("label",{className:"amx-graphbar-spread",children:[s.jsx("span",{className:"amx-graphbar-title",children:"spread"}),s.jsx("input",{type:"range",min:"0.7",max:"2.2",step:"0.1",value:ct,onChange:Y=>Qe(tC(Number(Y.target.value),.7,2.2,1))}),s.jsxs("span",{className:"amx-small",children:[ct.toFixed(1),"×"]})]}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>bo({kind:He,seed:nt}),disabled:!Fn.length,children:"Apply"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Ur,disabled:!Fn.length||He!=="force",children:ze?"Pause simulation":"Play simulation"})]})}),s.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:_e,children:[s.jsx(Rx,{children:s.jsxs(K$,{nodes:Sa,edges:ul,defaultViewport:{x:0,y:0,zoom:1},minZoom:Sv,maxZoom:Nv,onInit:Y=>{k.current=Y;const he=$e.current;if(he&&typeof Y.setViewport=="function")try{Y.setViewport(he,{duration:0})}catch{try{Y.setViewport(he)}catch{}}if(Le.current&&typeof Y.fitView=="function")try{Y.fitView({padding:.2,duration:0})}catch{try{Y.fitView({padding:.2})}catch{}}$e.current=null,Le.current=!1,Wr("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:$i,onNodeClick:(Y,he)=>{si(""),ni(he.id)},onEdgeClick:(Y,he)=>{ni(""),si(he.id)},onPaneClick:()=>{ni(""),si("")},children:[s.jsx(iB,{className:"amx-flow-controls",children:s.jsx(Pd,{type:"button",className:`amx-control-legend ${je?"amx-control-legend-active":""}`,onClick:()=>ae(Y=>!Y),title:je?"Hide node color legend":"Show node color legend","aria-label":je?"Hide node color legend":"Show node color legend",children:s.jsx(bB,{})})}),s.jsx(um,{position:"bottom-right",className:"amx-panel-bottom-right",children:s.jsx("div",{className:"amx-panel-toggles",children:s.jsx("button",{type:"button",className:"amx-minimap-toggle",onClick:()=>Me(Y=>!Y),title:be?"Hide minimap preview":"Show minimap preview","aria-label":be?"Hide minimap preview":"Show minimap preview",children:be?"minimap on":"minimap off"})})}),be?s.jsx(Zz,{position:"bottom-right",pannable:!0,zoomable:!0,maskColor:"rgba(0,0,0,0.45)",style:{background:"rgba(12, 18, 34, 0.88)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:10,width:de?120:160,height:de?80:110,marginBottom:56},nodeColor:Y=>{var he;return Eh((he=Y.data)==null?void 0:he.kind).minimap}}):null,je?s.jsxs(um,{position:"bottom-left",className:"amx-legend-panel",children:[s.jsx("div",{className:"amx-legend-title",children:"node colors"}),s.jsx("div",{className:"amx-legend",children:[{k:"person",label:"person"},{k:"org",label:"org"},{k:"concept",label:"concept"},{k:"claim",label:"claim"},{k:"event",label:"event"},{k:"doc",label:"doc"},{k:"vocab",label:"vocab"}].map(({k:Y,label:he})=>s.jsx("span",{className:"amx-legend-item",style:{borderColor:Eh(Y).stroke},children:he},Y))})]}):null,s.jsx(dB,{gap:20,size:1,color:"rgba(255,255,255,0.06)"})]})},ce),s.jsxs("details",{className:"amx-panel amx-controls",children:[s.jsxs("summary",{children:[s.jsx("span",{className:"amx-controls-title",children:Wi}),s.jsxs("span",{className:"amx-small",children:[oi," assertions · ",sr," nodes · ",af," edges"]})]}),s.jsxs("div",{className:"amx-toolbar",style:{marginTop:10},children:[s.jsxs("div",{className:"amx-toolbar-grid",children:[s.jsxs("label",{children:["search / highlight",s.jsx("input",{value:O,onChange:Y=>L(Y.target.value),placeholder:"filter nodes by id/label"})]}),s.jsxs("label",{children:["group edges",s.jsxs("select",{value:String(V),onChange:Y=>J(Y.target.value==="true"),children:[s.jsx("option",{value:"true",children:"group (subject→object)"}),s.jsx("option",{value:"false",children:"no grouping"})]})]}),s.jsxs("label",{children:["view",s.jsxs("select",{value:String(z),onChange:Y=>ne(Y.target.value==="true"),children:[s.jsx("option",{value:"true",children:"all assertions"}),s.jsx("option",{value:"false",children:"hide rdf:type / labels"})]})]}),s.jsxs("label",{children:["path mode",s.jsxs("select",{value:String(U),onChange:Y=>te(Y.target.value==="true"),children:[s.jsx("option",{value:"false",children:"undirected"}),s.jsx("option",{value:"true",children:"directed"})]})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"layout"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["layout",s.jsxs("select",{value:He,onChange:Y=>mt($v(Y.target.value,He)),children:[s.jsx("option",{value:"grid",children:"grid (deterministic)"}),s.jsx("option",{value:"radial",children:"radial (bfs)"}),s.jsx("option",{value:"circle",children:"circle"}),s.jsx("option",{value:"force",children:"force (simulation)"})]})]}),s.jsxs("label",{children:["seed",s.jsx("input",{type:"number",step:"1",value:nt,onChange:Y=>rt(Math.trunc(Number(Y.target.value||0)||0))})]})]}),s.jsxs("div",{className:"amx-actions",style:{marginTop:10},children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>bo({kind:He,seed:nt}),disabled:!Fn.length,children:"Apply layout"}),He==="force"?s.jsx("button",{type:"button",className:"amx-btn",onClick:Ur,disabled:!Fn.length,children:ze?"Pause simulation":"Play simulation"}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:fc,disabled:!Fn.length,children:"Save layout"}),yt?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:qr,children:"Load saved"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:xu,children:"Clear saved"})]}):null]}),s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["Drag nodes to adjust manually; use ",s.jsx("span",{className:"amx-mono",children:"Save layout"})," for a stable, replayable view.",yt?s.jsxs("span",{children:[" ","(saved",It?`: ${It}`:"",")"]}):s.jsx("span",{children:" (no saved layout)"})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"path"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["path start",s.jsxs("select",{value:Mt,onChange:Y=>mn(Y.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),Fn.map(Y=>s.jsx("option",{value:Y,children:(()=>{const he=Ni.get(Y)||Y;return he===Y?he:`${he} (${Y})`})()},Y))]})]}),s.jsxs("label",{children:["path end",s.jsxs("select",{value:yn,onChange:Y=>In(Y.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),Fn.map(Y=>s.jsx("option",{value:Y,children:(()=>{const he=Ni.get(Y)||Y;return he===Y?he:`${he} (${Y})`})()},Y))]})]})]}),bs?s.jsx("div",{className:"amx-small",style:{marginTop:10},children:fl.map((Y,he)=>{const Oe=Ni.get(Y.from)||Y.from,De=Ni.get(Y.to)||Y.to,Ye=Y.dir==="reverse"?" ← ":" → ",ht=Y.predicate?` (${Y.predicate})`:"";return s.jsxs("div",{children:[he===0?s.jsx("span",{children:Oe}):null,Ye,s.jsxs("span",{children:[De,ht]})]},`${Y.edgeId}:${he}`)})}):Mt&&yn?s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["No path found in the current subgraph (",(Ts==null?void 0:Ts.assertions)??oi," assertions · ",(Ts==null?void 0:Ts.nodes)??Nt.nodes.length," nodes ·"," ",(Ts==null?void 0:Ts.edges)??Nt.edges.length," edges). Start reaches ",(Ts==null?void 0:Ts.reachableFromStart)??0," nodes.",_?s.jsx("div",{style:{marginTop:10},children:s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void ii(),disabled:K,children:K?"Expanding…":"Expand neighborhood"})}):null]}):s.jsx("div",{className:"amx-small",style:{marginTop:10},children:"(no path)"})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"query"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["query_text (semantic)",s.jsx("input",{value:re,onChange:Y=>fe(Y.target.value),placeholder:"e.g. emotion chip"})]}),s.jsxs("label",{children:["subject (exact)",s.jsx("input",{value:Ce,onChange:Y=>Ie(Y.target.value),placeholder:"e.g. ex:person-data"})]}),s.jsxs("label",{children:["predicate (exact)",s.jsx("input",{value:We,onChange:Y=>Ue(Y.target.value),placeholder:"e.g. schema:about"})]}),s.jsxs("label",{children:["object (exact)",s.jsx("input",{value:et,onChange:Y=>at(Y.target.value),placeholder:"e.g. ex:concept-emotion-chip"})]}),s.jsxs("label",{children:["min_score",s.jsx("input",{type:"number",step:"any",value:vt,onChange:Y=>xt(Y.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["limit",s.jsx("input",{type:"number",min:"-1",step:"1",value:Et,onChange:Y=>zt(Y.target.value),placeholder:"0/-1 = unlimited (if supported)"})]})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"advanced"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["scope",s.jsxs("select",{value:ss,onChange:Y=>ge(Jk(Y.target.value,ss)),children:[s.jsx("option",{value:"run",children:"run"}),s.jsx("option",{value:"session",children:"session"}),s.jsx("option",{value:"global",children:"global"}),s.jsx("option",{value:"all",children:"all"})]})]}),s.jsxs("label",{children:["recall level",s.jsxs("select",{value:Re,onChange:Y=>gt(Y.target.value||"standard"),children:[s.jsx("option",{value:"urgent",children:"urgent"}),s.jsx("option",{value:"standard",children:"standard"}),s.jsx("option",{value:"deep",children:"deep"})]})]}),s.jsxs("label",{children:["max_input_tokens",s.jsx("input",{type:"number",min:"0",step:"1",value:ot,onChange:Y=>Jt(Y.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["model (budgeting)",s.jsx("input",{value:wn,onChange:Y=>hn(Y.target.value),placeholder:"qwen/qwen3-next-80b"})]})]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void ko(),disabled:!_||R,children:R?"Querying…":"Query store"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:$a,disabled:!E&&!W&&!R,children:"Reset to step output"}),E?s.jsxs("span",{className:"amx-small",children:["showing: ",P||"live query"]}):s.jsx("span",{className:"amx-small",children:"showing: step output"}),W?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:W}):null,M?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:M}):null]})]})]})]})]}),s.jsxs("div",{className:"amx-right",children:[s.jsxs("div",{className:"amx-panel",children:[s.jsx("h3",{children:"Details"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Derived from `memory_kg_query` packetization (max_input_tokens); safe to inject into an LLM system prompt."}),(()=>{const Y=$B(Er);return Y?s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:Y}):null})(),(()=>{const Y=Cs;if(!Y)return null;const he=typeof Y=="string"?Y:Array.isArray(Y)?Y.map(Oe=>String(Oe)).join(" · "):JSON.stringify(Y);return!he||!he.trim()?null:s.jsx("div",{className:"amx-small",style:{marginBottom:8,color:"var(--warning, rgba(255, 180, 90, 0.95))"},children:he})})(),s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:(()=>{const Y=(E==null?void 0:E.packets_version)??Be,he=(E==null?void 0:E.packed_count)??Zt,Oe=(E==null?void 0:E.dropped)??Tt,De=(E==null?void 0:E.estimated_tokens)??Dn,Ye=[];return typeof Y=="number"&&Ye.push(`packets_v${Y}`),typeof he=="number"&&Ye.push(`packed=${he}`),typeof Oe=="number"&&Ye.push(`dropped=${Oe}`),typeof De=="number"&&Ye.push(`est_tokens=${De}`),Ye.length?Ye.join(" · "):"No packetization stats (set max_input_tokens > 0)."})()}),s.jsx("div",{className:"amx-active-memory",children:EB(cn||"(empty)",O)}),(()=>{const Y=E!=null&&E.packets&&Array.isArray(E.packets)?E.packets:rs;return!Array.isArray(Y)||Y.length===0?null:s.jsxs("div",{style:{marginTop:10},children:[s.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>Ln(he=>!he),children:[Bi?"Hide":"Show"," packets (",Y.length,")"]}),Bi?s.jsx("div",{className:"amx-list",style:{marginTop:10},children:Y.slice(0,120).map((he,Oe)=>{const De=he&&typeof he=="object"&&!Array.isArray(he)?he:null,Ye=De&&typeof De.statement=="string"?De.statement:typeof he=="string"?he:"",ht=De&&(typeof De.retrieval_score=="number"||typeof De.retrieval_score=="string")?De.retrieval_score:null,Wt=De&&typeof De.observed_at=="string"?De.observed_at:null;return s.jsxs("div",{className:"amx-item",children:[s.jsx("div",{className:"amx-mono",children:Ye||"(packet)"}),Wt||ht!==null?s.jsxs("div",{className:"amx-small",children:[Wt?`[${Wt}]`:null,Wt&&ht!==null?" ":null,ht!==null?`score:${ht}`:null]}):null]},Oe)})}):null]})})(),s.jsx("div",{style:{marginTop:14,marginBottom:12,borderTop:"1px solid var(--ui-border-1, rgba(255,255,255,0.08))"}}),s.jsx("div",{className:"amx-small",style:{marginBottom:8,fontWeight:700,opacity:.9},children:"Inspect"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Click a node or edge to inspect its assertions."}),ys?s.jsxs("div",{className:"amx-item",style:{marginBottom:10,display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsx("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:Ni.get(ys)||ys}),s.jsxs("div",{className:"amx-small",children:["kind=",nr.get(ys)||"entity"," · id=",ys]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Ds(ys),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:pr,children:"Focus"})]})]}):Ar&&Ar.source&&Ar.target?s.jsxs("div",{className:"amx-item",style:{marginBottom:10,display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:[Ar.source," —",String(Ar.label||((Gn=Ar.data)==null?void 0:Gn.predicateSummary)||"").trim()||"?","→ ",Ar.target]}),s.jsxs("div",{className:"amx-small",children:["edge_id=",Ar.id]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Ds(Ar.id),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:pr,children:"Fit"})]})]}):s.jsx("div",{className:"amx-small",style:{marginBottom:10,opacity:.9},children:"(no selection)"}),s.jsx("div",{className:"amx-list",children:Ui.slice(0,80).map((Y,he)=>{const Oe=String(Y.subject||"").trim(),De=String(Y.predicate||"").trim(),Ye=String(Y.object||"").trim(),ht=Ni.get(Oe)||Oe,Wt=Ni.get(Ye)||Ye,Pt=nr.get(Oe)||"entity",Bt=nr.get(Ye)||"entity",pn=Eh(Pt),Cn=Eh(Bt),Ks=Ah(Y.observed_at),Ft=CB(Y),xn=Y.provenance&&typeof Y.provenance=="object"&&!Array.isArray(Y.provenance)?Y.provenance:null,os=xn&&typeof xn.span_id=="string"?xn.span_id.trim():"",Hn=xn&&typeof xn.writer_run_id=="string"?xn.writer_run_id.trim():"",Mr=typeof Y.owner_id=="string"?Y.owner_id.trim():"",gr=Hn||Mr,qi=!!((b||y)&&os&&gr),hl=!!(b&&Hn&&!os),Hi=qi||hl;return s.jsxs("div",{className:"amx-item amx-triple-card",children:[s.jsxs("div",{className:"amx-triple-row",children:[s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:pn.stroke,background:pn.bg},title:Oe,onClick:()=>{Oe&&(si(""),ni(Oe))},children:ht||Oe||"(subject)"}),s.jsx("span",{className:"amx-arrow",children:"—"}),s.jsx("span",{className:"amx-predicate",title:De,children:sC(De)||"(predicate)"}),s.jsx("span",{className:"amx-arrow",children:"→"}),s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Cn.stroke,background:Cn.bg},title:Ye,onClick:()=>{Ye&&(si(""),ni(Ye))},children:Wt||Ye||"(object)"})]}),s.jsxs("div",{className:"amx-triple-meta",children:[Ks?s.jsxs("span",{className:"amx-small",title:String(Y.observed_at||""),children:["[",Ks,"]"]}):null,Ft?s.jsx("span",{className:"amx-small",children:Ft}):null]}),os||Hn?s.jsxs("div",{className:"amx-triple-actions",children:[os?s.jsxs("span",{className:"amx-small",children:["span:",os]}):null,Hn?s.jsxs("span",{className:"amx-small",children:["run:",Hn]}):null,Hi?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(qi&&os&&gr){Ps({run_id:gr,span_id:os,assertion:Y});return}hl&&Hn&&Ps({run_id:Hn,assertion:Y})},children:"Open transcript"}):null]}):null]},he)})})]}),s.jsxs("div",{className:"amx-panel",children:[s.jsx("h3",{children:"Transcript"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Pivot from a triple to its provenance transcript (span/note artifact, or run input fallback)."}),Na.length?s.jsxs("div",{style:{marginBottom:12},children:[s.jsx("div",{className:"amx-small",style:{marginBottom:6,opacity:.85},children:"spans"}),s.jsx("div",{className:"amx-list",style:{maxHeight:320},children:Na.slice(0,60).map(Y=>s.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["span:",Y.span_id]}),s.jsxs("div",{className:"amx-small",children:["run_id=",Y.span_run_id," · assertions=",Y.count,Y.last_observed_at_fmt?` · last=[${Y.last_observed_at_fmt}]`:""]})]}),y||b?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ps({run_id:Y.span_run_id,span_id:Y.span_id,assertion:Y.assertion}),children:"Open transcript"}):null]},`${Y.span_run_id}|${Y.span_id}`))})]}):null,b&&xo.length?s.jsxs("div",{style:{marginBottom:12},children:[s.jsx("div",{className:"amx-small",style:{marginBottom:6,opacity:.85},children:"runs (fallback)"}),s.jsx("div",{className:"amx-list",style:{maxHeight:240},children:xo.slice(0,40).map(Y=>s.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["run:",Y.run_id]}),s.jsxs("div",{className:"amx-small",children:["assertions=",Y.count,Y.last_observed_at_fmt?` · last=[${Y.last_observed_at_fmt}]`:""]})]}),s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ps({run_id:Y.run_id,assertion:Y.assertion}),children:"Open transcript"})]},Y.run_id))})]}):null,!Na.length&&!(b&&xo.length)?s.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})})}function ec({open:e,title:t,children:n,actions:r,variant:i="default",onClose:o}){const u=p.useId();if(p.useEffect(()=>{if(!e)return;const d=h=>{h.key==="Escape"&&o()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e,o]),!e)return null;const l=i==="fullscreen";return s.jsx("div",{className:`modal_backdrop${l?" fullscreen":""}`,onMouseDown:d=>{d.target===d.currentTarget&&o()},children:s.jsxs("div",{className:`modal_panel${l?" fullscreen":""}`,role:"dialog","aria-modal":"true","aria-labelledby":u,children:[s.jsxs("div",{className:"modal_header",children:[s.jsx("div",{className:"modal_title",id:u,children:t}),s.jsx("button",{className:"btn",onClick:o,children:"Close"})]}),s.jsx("div",{className:"modal_body",children:n}),r?s.jsx("div",{className:"modal_footer",children:r}):null]})})}function dw(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function Yl(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),r=Date.parse(n);return Number.isFinite(r)?r:null}function nu(e){if(typeof e!="number"||!Number.isFinite(e))return"—";const t=new Date(e),n=t.getUTCFullYear(),r=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0"),o=String(t.getUTCHours()).padStart(2,"0"),u=String(t.getUTCMinutes()).padStart(2,"0");return`${n}/${r}/${i} ${o}:${u}`}function RB(e){const t=String(e??"").trim();if(!t)return"";if(/^\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}$/.test(t))return t;const n=Yl(t);return n!==null?nu(n):t}function Ix(e){const t=typeof e=="string"?e:String(e??"");return t?!t.includes("\\n")&&!t.includes("\\r")&&!t.includes("\\t")?t:t.replace(/\\r\\n/g,`
155
+ `).replace(/\\n/g,`
156
+ `).replace(/\\t/g," "):""}function rC(e){return String(e??"").replace(/[*_`~]/g,"")}function gp(e,t){const n=!!(t!=null&&t.strip_punct),r=Ix(e);let i=rC(r).replace(/\s+/g," ").trim().toLowerCase();return n&&(i=i.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),i}function yp(e,t){const n=String(t??"").trim();if(!n)return!1;const r=gp(n,{strip_punct:!1});if(!r)return!1;if(gp(String(e??""),{strip_punct:!1}).includes(r))return!0;const o=gp(n,{strip_punct:!0});return o?gp(String(e??""),{strip_punct:!0}).includes(o):!1}function Xk(e){const t=Ix(e).trim();if(!t)return[];const n=[],r=u=>{const l=String(u??"").replace(/\s+/g," ").trim();l&&(l.length<6||n.includes(l)||n.push(l))},i=t.search(/[`*_~]/);if(i>0){const u=t.slice(0,i);u.replace(/\s+/g," ").trim().length>=10&&r(u)}const o=[/`([^`]+)`/g,/\*\*([^*]+)\*\*/g,/__([^_]+)__/g,/\*([^*]+)\*/g,/_([^_]+)_/g];for(const u of o){let l;for(;(l=u.exec(t))!==null;){const d=String(l[1]??"").trim();d&&r(d)}}return r(rC(t)),n}function LB(e){const t=String(e??"").replace(/\r\n/g,`
157
+ `).replace(/\r/g,`
158
+ `);if(!t)return null;const n=t.split(`
159
+ `);let r;const i=[],o=[];let u=null,l=[],d=!1;const h=()=>{if(!u)return;const g=l.join(`
160
+ `).trim();g&&o.push({role:u,lines:[g]}),u=null,l=[]};for(const g of n){const y=r?null:g.match(/^\s*created_at\s*=\s*(.+)\s*$/i);if(y&&y[1]){r=y[1].trim();continue}const b=g.match(/^\s*(USER|ASSISTANT|SYSTEM)\s*:\s*(.*)$/i);if(b){d=!0,h();const k=String(b[1]||"").trim().toLowerCase();u=k==="user"?"user":k==="assistant"?"assistant":"system";const x=String(b[2]??"");l=x?[x]:[];continue}u?l.push(g):i.push(g)}if(h(),!d||!o.length)return null;const m=i.join(`
161
+ `).trim(),_={messages:[]};r&&(_.created_at=r),m&&_.messages.push({role:"system",content:m});for(const g of o)_.messages.push({role:g.role,content:g.lines.join(`
162
+ `)});return _.messages.length?_:null}function Zk(e,t){const n=String(e||""),r=String(t||"");return r>n?r:n}function Qk(e){const t=String((e==null?void 0:e.subject)||"").trim(),n=String((e==null?void 0:e.predicate)||"").trim(),r=String((e==null?void 0:e.object)||"").trim(),i=String((e==null?void 0:e.observed_at)||"").trim(),o=String((e==null?void 0:e.scope)||"").trim(),u=String((e==null?void 0:e.owner_id)||"").trim();return`${t}|${n}|${r}|${i}|${o}|${u}`}function IB(e){const t=String((e==null?void 0:e.observed_at)||"").trim(),n=String((e==null?void 0:e.subject)||"").trim(),r=String((e==null?void 0:e.predicate)||"").trim(),i=String((e==null?void 0:e.object)||"").trim(),o=String((e==null?void 0:e.scope)||"").trim(),u=String((e==null?void 0:e.owner_id)||"").trim(),l=[];o&&l.push(`scope=${o}`),u&&l.push(`owner=${u}`);const d=l.length?` (${l.join(", ")})`:"";return`${t?`[${t}] `:""}${n} --${r}--> ${i}${d}`}function OB({gateway:e,selected_run_id:t,selected_session_id:n}){const[r,i]=p.useState(String(t||"").trim()),[o,u]=p.useState(String(n||"").trim()),[l,d]=p.useState("all"),h=l==="all",[m,_]=p.useState(!0),[g,y]=p.useState(750),[b,k]=p.useState(5e3),[x,N]=p.useState([]),[$,E]=p.useState(void 0),[S,P]=p.useState(""),[D,R]=p.useState(!1),[I,W]=p.useState([]),[G,K]=p.useState(!1),[H,M]=p.useState(!1),[A,O]=p.useState(""),[L,V]=p.useState(""),[J,U]=p.useState(""),[te,z]=p.useState(""),[ne,se]=p.useState("artifact"),[de,be]=p.useState(null),[Me,je]=p.useState(""),[ae,xe]=p.useState(null),Ae=p.useRef(!1),He=p.useMemo(()=>{const ge=ae,Re=ge!=null&&ge.attributes&&typeof ge.attributes=="object"&&!Array.isArray(ge.attributes)?ge.attributes:null;return(Re&&typeof Re.evidence_quote=="string"?String(Re.evidence_quote):"").trim()},[ae]),mt=p.useMemo(()=>{const ge=de,Re=ge&&typeof ge=="object"&&!Array.isArray(ge)?ge:null,gt=Re&&typeof Re.note=="string"?String(Re.note):"";return Ix(gt).trim()},[de]),nt=p.useMemo(()=>{const ge=de&&typeof de=="object"&&!Array.isArray(de)?de:null,Re=ge&&Array.isArray(ge.messages)?ge.messages:null;return Array.isArray(Re)?Re:null},[de]),rt=p.useMemo(()=>{const ge=mt,Re=He;return!ge||!Re?!1:yp(ge,Re)},[He,mt]),ze=p.useMemo(()=>{const ge=nt,Re=He;if(!ge||!Re)return[];const gt=[];for(let re=0;re<Math.min(ge.length,500);re++){const fe=ge[re],Ce=(fe==null?void 0:fe.content)==null?"":String(fe.content);yp(Ce,Re)&&gt.push(re)}return gt},[He,nt]),Ve=p.useMemo(()=>new Set(ze),[ze]),ct=ze.length?ze[0]:null,Qe=p.useCallback(ge=>{const Re=document.getElementById(`source_msg_${ge}`);Re&&typeof Re.scrollIntoView=="function"&&Re.scrollIntoView({block:"center",behavior:"smooth"})},[]),Dt=p.useCallback(()=>{const ge=document.getElementById("source_note_hit_0")||document.getElementById("source_note_msg_hit_0");ge&&typeof ge.scrollIntoView=="function"&&ge.scrollIntoView({block:"center",behavior:"smooth"})},[]);p.useEffect(()=>{if(G&&!(H||A)&&!Ae.current){if(ct!==null){Ae.current=!0,window.setTimeout(()=>Qe(ct),0);return}if(rt){Ae.current=!0,window.setTimeout(()=>Dt(),0);return}}},[Qe,Dt,A,ct,H,rt,G]);const $e=p.useRef(new Set),Le=p.useRef(""),ce=p.useRef(null),Q=p.useRef(null);p.useEffect(()=>{i(String(t||"").trim())},[t]),p.useEffect(()=>{u(String(n||"").trim())},[n]);const _e=p.useMemo(()=>{const ge=String(r||"").trim(),Re=String(o||"").trim();return`mindmap:${l}:${ge}:${Re}`},[r,o,l]),le=p.useMemo(()=>{let ge=null,Re=null;for(const gt of x){const re=Yl(gt==null?void 0:gt.observed_at);re!==null&&(ge=ge===null?re:Math.min(ge,re),Re=Re===null?re:Math.max(Re,re))}return{min_ms:ge,max_ms:Re}},[x]),Se=1e3,pe=p.useMemo(()=>{const ge=le.min_ms,Re=le.max_ms;if(typeof ge!="number"||typeof Re!="number"||!Number.isFinite(ge)||!Number.isFinite(Re))return null;if(Re<=ge)return{min_ms:ge,max_ms:ge,real_max_ms:Re};const gt=ge+Math.ceil((Re-ge)/Se)*Se;return{min_ms:ge,max_ms:gt,real_max_ms:Re}},[le.max_ms,le.min_ms]),[dt,yt]=p.useState(!0),[_t,It]=p.useState(null);p.useEffect(()=>{dt&&pe&&It(pe.max_ms)},[dt,pe]);const bt=p.useMemo(()=>{const ge=typeof _t=="number"?_t:null;return ge===null?x:x.filter(Re=>{const gt=Yl(Re==null?void 0:Re.observed_at);return gt===null?!0:gt<=ge})},[x,_t]),St=p.useCallback((ge,Re)=>{const gt=Array.isArray(ge)?ge:[],re=String(Le.current||"").trim(),fe=new Set,Ce=[];let Ie="";for(const We of gt){if(!We||typeof We!="object"||typeof We.subject!="string"||typeof We.predicate!="string"||typeof We.object!="string")continue;const Ue=Qk(We);if(fe.has(Ue))continue;fe.add(Ue),Ce.push(We);const et=String(We.observed_at||"").trim();et&&(Ie=Zk(Ie,et))}N(Ce),E(Re==null?void 0:Re.warnings),$e.current=fe,Le.current=Ie||re},[]),ut=p.useCallback(async ge=>{const Re=dw(ge.scope,"session"),gt=String(ge.subject||"").trim(),re=String(ge.predicate||"").trim(),fe=String(ge.object||"").trim(),Ce=String(ge.since||"").trim(),Ie=String(ge.until||"").trim(),We=String(ge.active_at||"").trim(),Ue=String(ge.query_text||"").trim(),et=typeof ge.min_score=="number"&&Number.isFinite(ge.min_score)?Number(ge.min_score):void 0,at=ge.order==="asc"?"asc":"desc",vt=typeof ge.limit=="number"&&Number.isFinite(ge.limit)?Number(ge.limit):0,xt=String(r||"").trim(),Et=String(o||"").trim(),zt={scope:Re,all_owners:h,limit:vt,order:at};gt&&(zt.subject=gt),re&&(zt.predicate=re),fe&&(zt.object=fe),Ce&&(zt.since=Ce),Ie&&(zt.until=Ie),We&&(zt.active_at=We),Ue&&(zt.query_text=Ue),typeof et=="number"&&(zt.min_score=et),h||(Re==="run"?xt&&(zt.run_id=xt):Re==="session"?Et?zt.session_id=Et:xt&&(zt.run_id=xt):Re==="all"&&(xt?zt.run_id=xt:Et&&(zt.session_id=Et)));try{const ot=await e.kg_query(zt),Jt=Array.isArray(ot==null?void 0:ot.items)?ot.items:[],wn=ot==null?void 0:ot.warnings;return{ok:(ot==null?void 0:ot.ok)!==!1,count:Number((ot==null?void 0:ot.count)||Jt.length),items:Jt,warnings:wn,raw:ot}}catch(ot){const Jt=ot instanceof Error?ot.message:String(ot);if(Jt.includes("Run '")&&Jt.includes("not found")&&!Et&&(Re==="session"||Re==="all")&&xt){const hn=await e.kg_query({...zt,run_id:void 0,session_id:xt}),sn=Array.isArray(hn==null?void 0:hn.items)?hn.items:[],Vt=hn==null?void 0:hn.warnings;return{ok:(hn==null?void 0:hn.ok)!==!1,count:Number((hn==null?void 0:hn.count)||sn.length),items:sn,warnings:Vt,raw:hn}}throw new Error(Jt||"KG query failed")}},[h,e,r,o]),Ot=p.useCallback(async ge=>{var re;const Re=String(ge.run_id||"").trim(),gt=String(ge.span_id||"").trim();if(!(!Re||!gt)){K(!0),M(!0),O(""),U(Re),z(gt),se("artifact"),V(`source span:${gt}`),be(null),je(""),xe(ge.assertion&&typeof ge.assertion=="object"?ge.assertion:null),Ae.current=!1;try{const fe=[Re],Ce=typeof((re=ge.assertion)==null?void 0:re.owner_id)=="string"?String(ge.assertion.owner_id).trim():"";Ce&&Ce!==Re&&fe.push(Ce);let Ie=null,We=null;for(const Ue of fe)try{We=await(await e.download_run_artifact_content(Ue,gt)).text(),Ue!==Re&&U(Ue);break}catch(et){Ie=et instanceof Error?et.message:String(et)}if(We==null)throw new Error(Ie||"Failed to load source span");je(We);try{const Ue=JSON.parse(We);be(Ue)}catch{be(null)}}catch(fe){const Ce=fe instanceof Error?fe.message:String(fe);O(Ce||"Failed to load source span")}finally{M(!1)}}},[e]),Mt=p.useCallback(async ge=>{const Re=String(ge.run_id||"").trim();if(!Re)return null;try{const gt=await e.list_run_artifacts(Re,{limit:200}),fe=(Array.isArray(gt==null?void 0:gt.items)?gt.items:[]).map(et=>{const at=typeof(et==null?void 0:et.artifact_id)=="string"?String(et.artifact_id).trim():"",vt=et!=null&&et.tags&&typeof et.tags=="object"&&!Array.isArray(et.tags)?et.tags:null,xt=vt&&typeof vt.kind=="string"?String(vt.kind).trim():"";return{artifact_id:at,kind:xt}}).filter(et=>!!(et.artifact_id&&(et.kind==="conversation_span"||et.kind==="memory_note")));if(!fe.length)return null;if(fe.length===1)return fe[0].artifact_id;const Ce=ge.assertion,Ie=Ce!=null&&Ce.attributes&&typeof Ce.attributes=="object"&&!Array.isArray(Ce.attributes)?Ce.attributes:null,Ue=(Ie&&typeof Ie.evidence_quote=="string"?String(Ie.evidence_quote):"").trim();if(!Ue)return null;for(const et of fe.slice(0,10))try{const vt=await(await e.download_run_artifact_content(Re,et.artifact_id)).text(),xt=JSON.parse(vt);if(xt&&typeof xt=="object"){const Et=typeof xt.note=="string"?String(xt.note):"";if(Et&&Et.includes(Ue))return et.artifact_id;const zt=Array.isArray(xt.messages)?xt.messages:null;if(zt){for(const ot of zt.slice(0,200))if(((ot==null?void 0:ot.content)==null?"":String(ot.content)).includes(Ue))return et.artifact_id}}}catch{}}catch{}return null},[e]),mn=p.useCallback(async ge=>{const Re=String(ge.run_id||"").trim();if(Re){K(!0),M(!0),O(""),U(Re),z(""),se("run_input"),V(`transcript run:${Re}`),be(null),je(""),xe(ge.assertion&&typeof ge.assertion=="object"?ge.assertion:null),Ae.current=!1;try{const gt=await Mt({run_id:Re,assertion:ge.assertion});if(gt){await Ot({run_id:Re,span_id:gt,assertion:ge.assertion});return}const re=await e.get_run_input_data(Re),fe=re&&typeof re=="object"&&!Array.isArray(re)?re.input_data:null,Ce={kind:"run_input_data",run_id:Re};if(re&&typeof(re==null?void 0:re.workflow_id)=="string"&&(Ce.workflow_id=String(re.workflow_id)),fe&&typeof fe=="object"&&!Array.isArray(fe)){const Ie=fe.context,Ue=(Ie&&typeof Ie=="object"&&Array.isArray(Ie.messages)?Ie.messages:null)||(Array.isArray(fe.messages)?fe.messages:null);Array.isArray(Ue)&&(Ce.messages=Ue);const et=["text","prompt","task","message"];for(const at of et){const vt=fe[at];if(typeof vt=="string"&&vt.trim()){Ce.note=vt.trim();break}}Ce.input_data=fe}!Ce.messages&&!Ce.note&&(Ce.note=JSON.stringify(fe??re??{},null,2));try{const Ie=await e.get_run(Re),We=Ie&&typeof(Ie==null?void 0:Ie.created_at)=="string"?String(Ie.created_at):"";We&&(Ce.created_at=We)}catch{}be(Ce),je(JSON.stringify(re,null,2))}catch(gt){const re=gt instanceof Error?gt.message:String(gt);O(re||"Failed to load run input transcript")}finally{M(!1)}}},[e,Ot,Mt]),yn=p.useCallback(async()=>{P(""),R(!0);try{const ge=l==="all"?"all":l,Re=await ut({scope:ge,limit:0,order:"desc"});St(Re.items||[],{warnings:Re.warnings}),ce.current={scope:ge}}catch(ge){const Re=ge instanceof Error?ge.message:String(ge);P(Re||"Load failed")}finally{R(!1)}},[ut,St,l]);p.useEffect(()=>{x.length||yn()},[]);const In=p.useCallback(async ge=>{const Re=dw(ge.scope,"session");return Q.current=ge,await ut({scope:Re,subject:ge.subject,predicate:ge.predicate,object:ge.object,query_text:ge.query_text,min_score:ge.min_score,since:ge.since,until:ge.until,active_at:ge.active_at,limit:typeof ge.limit=="number"?ge.limit:0,order:"desc"})},[ut]),Gs=p.useCallback((ge,Re)=>{var gt;if((Re==null?void 0:Re.kind)==="live query"){const re=Q.current;re&&(ce.current={scope:dw(re.scope,"session"),subject:typeof re.subject=="string"?re.subject:void 0,predicate:typeof re.predicate=="string"?re.predicate:void 0,object:typeof re.object=="string"?re.object:void 0})}St(ge,{warnings:(gt=Re==null?void 0:Re.result)==null?void 0:gt.warnings})},[St]),ss=p.useCallback(async()=>{const ge=ce.current;if(!ge)return;const Re=String(Le.current||"").trim(),gt=await ut({scope:ge.scope,subject:ge.subject,predicate:ge.predicate,object:ge.object,since:Re||void 0,order:"asc",limit:0}),re=Array.isArray(gt.items)?gt.items:[];if(!re.length)return;const Ce=Date.now()+Math.max(250,Math.min(2e4,b)),Ie=$e.current,We=[],Ue=[];let et=String(Le.current||"").trim();for(const at of re){if(!at||typeof at!="object"||typeof at.subject!="string"||typeof at.predicate!="string"||typeof at.object!="string")continue;const vt=Qk(at);if(Ie.has(vt))continue;Ie.add(vt),We.push(at),Ue.push({id:vt,assertion:at,expires_at_ms:Ce});const xt=String(at.observed_at||"").trim();xt&&(et=Zk(et,xt))}We.length&&(Le.current=et,N(at=>{const vt=at.concat(We);return vt.sort((xt,Et)=>String((Et==null?void 0:Et.observed_at)||"").localeCompare(String((xt==null?void 0:xt.observed_at)||""))),vt}),W(at=>{const vt=at.concat(Ue);return vt.sort((xt,Et)=>Et.expires_at_ms-xt.expires_at_ms),vt.slice(0,30)}))},[b,ut]);return p.useEffect(()=>{if(!m)return;let ge=!1,Re=null;const gt=async()=>{if(!ge){try{await ss()}catch{}ge||(Re=window.setTimeout(()=>void gt(),Math.max(250,Math.min(6e4,g))))}};return gt(),()=>{ge=!0,Re!==null&&window.clearTimeout(Re)}},[m,g,ss]),p.useEffect(()=>{if(!I.length)return;const ge=window.setInterval(()=>{const Re=Date.now();W(gt=>gt.filter(re=>re.expires_at_ms>Re))},250);return()=>window.clearInterval(ge)},[I.length]),s.jsxs("div",{className:"mindmap_root",children:[s.jsxs("div",{className:"mindmap_bar",children:[s.jsx("button",{className:"btn",onClick:()=>void yn(),disabled:D,children:D?"Loading…":"Load snapshot"}),s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"source"}),s.jsxs("select",{value:l,onChange:ge=>{const Re=String(ge.target.value||"").trim();(Re==="all"||Re==="global"||Re==="session"||Re==="run")&&d(Re)},children:[s.jsx("option",{value:"all",children:"all memory"}),s.jsx("option",{value:"global",children:"global"}),s.jsx("option",{value:"session",children:"session"}),s.jsx("option",{value:"run",children:"run"})]})]}),s.jsx(n4,{checked:m,onChange:_}),l==="session"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"session_id"}),s.jsx("input",{className:"mono",value:o,onChange:ge=>u(String(ge.target.value||"")),placeholder:"(required)"})]}):null,l==="run"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"run_id"}),s.jsx("input",{className:"mono",value:r,onChange:ge=>i(String(ge.target.value||"")),placeholder:"(required)"})]}):null,s.jsxs("details",{className:"mindmap_details",children:[s.jsx("summary",{className:"mono muted",children:"advanced"}),s.jsx("div",{className:"mindmap_advanced",children:s.jsxs("div",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",style:{width:84},children:"poll_ms"}),s.jsx("input",{type:"number",min:250,max:6e4,step:50,value:g,onChange:ge=>y(Math.max(250,Number(ge.target.value||0)||750))}),s.jsx("span",{className:"mono muted",children:"highlight_ms"}),s.jsx("input",{type:"number",min:250,max:2e4,step:250,value:b,onChange:ge=>k(Math.max(250,Number(ge.target.value||0)||5e3))})]})})]})]}),S?s.jsx("div",{className:"mindmap_error mono",children:S}):null,s.jsxs("div",{className:"mindmap_explorer",children:[s.jsx(MB,{title:"mindmap",resetKey:_e,queryMode:"replace",items:bt,warnings:$,onQuery:In,onItemsReplace:Gs,onOpenSpan:({run_id:ge,span_id:Re,assertion:gt})=>{Ot({run_id:ge,span_id:Re,assertion:gt})},onOpenTranscript:({run_id:ge,span_id:Re,assertion:gt})=>{const re=String(ge||"").trim(),fe=typeof Re=="string"?String(Re).trim():"";re&&(fe?Ot({run_id:re,span_id:fe,assertion:gt}):mn({run_id:re,assertion:gt}))}},_e),I.length?s.jsxs("div",{className:"mindmap_recent mindmap_overlay mindmap_overlay_recent",children:[s.jsx("div",{className:"mindmap_recent_title mono muted",children:"new assertions"}),s.jsx("div",{className:"mindmap_recent_list",children:I.slice().sort((ge,Re)=>Re.expires_at_ms-ge.expires_at_ms).slice(0,12).map(ge=>s.jsx("div",{className:"mindmap_recent_item mono",children:IB(ge.assertion)},ge.id))})]}):null,pe?s.jsx("div",{className:"mindmap_timeline mindmap_overlay mindmap_overlay_timeline",children:s.jsxs("div",{className:"mindmap_timeline_row",children:[s.jsx("div",{className:"mindmap_timeline_label mono muted",children:nu(Math.min(typeof _t=="number"?_t:pe.max_ms,pe.real_max_ms))}),s.jsx("input",{className:"mindmap_slider",type:"range",min:pe.min_ms,max:pe.max_ms,step:Se,value:typeof _t=="number"?_t:pe.max_ms,onChange:ge=>{const Re=Number(ge.target.value||0);It(Re),yt(Re>=pe.max_ms)}}),s.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[bt.length.toLocaleString(),"/",x.length.toLocaleString()]})]})}):null]}),s.jsxs(ec,{open:G,title:L||"source",onClose:()=>{K(!1)},children:[H?s.jsx("div",{className:"mono muted",children:"Loading…"}):null,A?s.jsx("div",{className:"mindmap_error mono",children:A}):null,!H&&!A?s.jsxs("div",{className:"source_span",children:[(()=>{const ge=ae;if(!ge)return null;const Re=String(ge.subject||"").trim(),gt=String(ge.predicate||"").trim(),re=String(ge.object||"").trim(),fe=nu(Yl(ge.observed_at)),Ce=ge.attributes&&typeof ge.attributes=="object"&&!Array.isArray(ge.attributes)?ge.attributes:null,Ie=Ce&&typeof Ce.evidence_quote=="string"?String(Ce.evidence_quote):"",We=Ce&&typeof Ce.original_context=="string"?String(Ce.original_context):"";return s.jsxs("div",{className:"source_header",children:[s.jsxs("div",{className:"mono source_triple",title:`${Re} --${gt}--> ${re}`,children:[Re," ",s.jsxs("span",{className:"muted",children:["—",gt,"→"]})," ",re," ",fe?s.jsxs("span",{className:"muted",children:["[",fe,"]"]}):null]}),Ie?s.jsxs("div",{className:"source_evidence",children:[s.jsx("div",{className:"mono muted",style:{fontSize:11,marginBottom:6},children:"evidence_quote"}),s.jsx("pre",{className:"mono source_evidence_quote",children:Ie}),We?s.jsxs("details",{className:"source_evidence_more",children:[s.jsx("summary",{className:"mono muted",children:"original_context"}),s.jsx("pre",{className:"mono source_evidence_quote",children:We})]}):null]}):null]})})(),s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["run_id=",J," · ",ne==="artifact"?`span_id=${te}`:"source=input_data"]}),s.jsxs("div",{className:"source_actions",children:[ct!==null?s.jsx("button",{className:"btn",onClick:()=>Qe(ct),children:"Jump to evidence"}):null,ct===null&&rt?s.jsx("button",{className:"btn",onClick:()=>Dt(),children:"Jump to evidence"}):null]}),(()=>{const ge=de,Re=ge&&typeof ge=="object"&&!Array.isArray(ge)?ge:null,gt=nt,re=mt,fe=Re&&typeof Re.created_at=="string"?String(Re.created_at):"",Ce=fe?Yl(fe):null,Ie=Ce!==null?nu(Ce):fe,We=Re&&Re.span&&typeof Re.span=="object"&&!Array.isArray(Re.span)?Re.span:null,Ue=We&&typeof We.from_timestamp=="string"?String(We.from_timestamp):"",et=We&&typeof We.to_timestamp=="string"?String(We.to_timestamp):"",at=Ue?Yl(Ue):null,vt=et?Yl(et):null,xt=at!==null&&vt!==null?`${nu(at)} → ${nu(vt)}`:"";if(re){const Et=LB(re);if(Et){const zt=He,ot=zt?Et.messages.findIndex(sn=>yp(sn.content,zt)):-1,Jt=zt?Xk(zt):[],wn=Et.created_at||fe,hn=wn?RB(wn):fe?Ie:"";return s.jsx("div",{className:"source_chat",children:Et.messages.map((sn,Vt)=>{const rs=sn.role,Be=!!(zt&&yp(sn.content,zt)),Zt=rs==="user"?"USER":rs==="assistant"?"ASSISTANT":"SYSTEM";return s.jsxs("div",{id:Vt===ot?"source_note_msg_hit_0":void 0,className:`source_msg source_${rs} ${Be?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Vt+1," · ",Zt,Be?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),hn?s.jsx("span",{title:wn||"",children:hn}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Si,{text:sn.content,highlights:Be&&Jt.length?Jt:void 0,highlightClassName:"source_note_hit",highlightId:Vt===ot?"source_note_hit_0":void 0})})]},`note_msg:${Vt}`)})})}return s.jsxs("div",{className:"source_note",children:[fe?s.jsx("div",{className:"mono muted",style:{marginBottom:10},children:s.jsxs("span",{title:fe,children:["created_at=",Ie]})}):null,s.jsx(Si,{text:re,highlights:He?Xk(He):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(gt){const Et=new Map;for(const ot of gt){const Jt=typeof(ot==null?void 0:ot.role)=="string"?String(ot.role):"unknown";Et.set(Jt,(Et.get(Jt)||0)+1)}const zt=Array.from(Et.entries()).sort((ot,Jt)=>Jt[1]-ot[1]||ot[0].localeCompare(Jt[0])).map(([ot,Jt])=>`${ot}×${Jt}`).join(" · ");return s.jsxs("div",{className:"source_chat",children:[fe?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:[s.jsxs("span",{title:fe,children:["created_at=",Ie]})," · messages=",gt.length]}):null,xt?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["span=",xt]}):null,zt?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["participants: ",zt]}):null,gt.slice(0,200).map((ot,Jt)=>{var Tt,Dn;const wn=typeof(ot==null?void 0:ot.role)=="string"?String(ot.role):"unknown",hn=(ot==null?void 0:ot.content)==null?"":String(ot.content),sn=typeof(ot==null?void 0:ot.timestamp)=="string"?String(ot.timestamp):"",Vt=sn?Yl(sn):null,rs=Vt!==null?nu(Vt):sn,Be=typeof(ot==null?void 0:ot.message_id)=="string"?String(ot.message_id):typeof((Tt=ot==null?void 0:ot.metadata)==null?void 0:Tt.message_id)=="string"?String(ot.metadata.message_id):typeof((Dn=ot==null?void 0:ot.metadata)==null?void 0:Dn.id)=="string"?String(ot.metadata.id):"",Zt=Ve.has(Jt);return s.jsxs("div",{id:`source_msg_${Jt}`,className:`source_msg source_${wn} ${Zt?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Jt+1," · ",wn,Zt?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null,Be?s.jsx("span",{className:"source_msg_id",children:Be}):null]}),sn?s.jsx("span",{title:sn,children:rs}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Si,{text:hn})})]},Jt)})]})}return s.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof ge=="string"?ge:Me)||"(empty)"})})()]}):null]})]})}const PB=6e4,DB=10*6e4;function FB(e){return Math.min(DB,PB*2**Math.max(0,e-1))}function qg(){return{value_version:"",value:null,has_value:!1,attempt_version:"",inflight:!1,failures:0,failed_at:null,error:""}}function zB(e,t,n,r){const i=[],o=new Set;for(const u of e||[]){const l=String((u==null?void 0:u.id)||"").trim();if(!l||o.has(l))continue;o.add(l);const d=t.get(l);if(!d){i.push({id:l,version:String(u.version||"")});continue}if(!d.inflight){if(d.failed_at!==null){n-d.failed_at>=FB(d.failures)&&i.push({id:l,version:String(u.version||"")});continue}r!=null&&r.immutable&&d.has_value||d.value_version!==String(u.version||"")&&i.push({id:l,version:String(u.version||"")})}}return i}function BB(e,t){const n=e.get(t.id)||qg();e.set(t.id,{...n,attempt_version:t.version,inflight:!0})}function UB(e,t,n){const r=e.get(t.id)||qg();e.set(t.id,{...r,value:n,has_value:!0,value_version:t.version,attempt_version:t.version,inflight:!1,failures:0,failed_at:null,error:""})}function WB(e,t,n,r){const i=e.get(t.id)||qg();e.set(t.id,{...i,attempt_version:t.version,inflight:!1,failures:i.failures+1,failed_at:r,error:String((n==null?void 0:n.message)||n||"failed")})}function qB(e,t,n){const r=new Map;for(const i of e||[]){const o=t.get(i.id);!o||!o.has_value||o.value===null||n!=null&&n.current_only&&o.value_version!==i.version||r.set(i.id,o.value)}return r}function HB(e,t){var i;let n=0;const r=new Set;for(const o of e||[])r.has(o.id)||(r.add(o.id),(i=t.get(o.id))!=null&&i.inflight&&(n+=1));return n}function VB(e,t,n){const r=new Set;for(const i of e||[]){const o=String((i==null?void 0:i.id)||"").trim();if(!o||r.has(o))continue;const u=t.get(o);if(!u||u.inflight){r.add(o);continue}u.failed_at===null&&(!u.has_value||n!=null&&n.current_only&&u.value_version!==String(i.version||""))&&r.add(o)}return r}function xs(e){return String((e==null?void 0:e.run_id)||"").trim()}function ej(e){const t=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null;return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function GB(e){const t=new Map;for(const n of e||[]){const r=String((n==null?void 0:n.automation_id)||"").trim();if(!r)continue;String((n==null?void 0:n.role)||"").trim()==="controller"?t.set(r,String((n==null?void 0:n.updated_at)||"")):t.has(r)||t.set(r,"")}return Array.from(t,([n,r])=>({id:n,version:r}))}function KB(e){if(String((e==null?void 0:e.automation_id)||"").trim())return!1;const t=String((e==null?void 0:e.role)||"").trim();return t==="occurrence"||t==="descendant"||t==="controller"?!1:String((e==null?void 0:e.session_kind)||"").trim()!=="automation"}function JB(e){return(e||[]).filter(t=>xs(t)&&KB(t)).map(t=>({id:xs(t),version:""}))}const YB=6e4;function XB(e,t=Date.now(),n=YB){const r=[];for(const i of e||[]){if(!xs(i)||String((i==null?void 0:i.status)||"").trim().toLowerCase()!=="running")continue;const o=typeof(i==null?void 0:i.ledger_len)=="number"?i.ledger_len:null;if(o===null||o<1)continue;const u=Ht((i==null?void 0:i.updated_at)||(i==null?void 0:i.created_at)||"");u!==null&&t-u<n||r.push({id:xs(i),version:String(o)})}return r}function ZB(e){return{after:Math.max(0,Math.floor(e)-1),limit:1}}function QB(e,t){const n=[],r=new Set,i=o=>{r.has(xs(o))||(r.add(xs(o)),n.push({id:xs(o),version:String((o==null?void 0:o.updated_at)||"")}))};for(const o of e||[]){if(!xs(o)||String((o==null?void 0:o.status)||"").trim().toLowerCase()!=="waiting")continue;const u=ej(o);(u==="user"||t&&u==="subworkflow")&&i(o)}if(t){const o=new Set;for(const l of t){const d=String((l==null?void 0:l.parent_run_id)||"").trim();d&&!ds(String((l==null?void 0:l.status)||""))&&o.add(d)}let u=0;for(const l of t){if(u>=e9)break;!xs(l)||String((l==null?void 0:l.status)||"").trim().toLowerCase()!=="waiting"||ej(l)==="subworkflow"&&!o.has(xs(l))&&(i(l),u+=1)}}return n}const e9=50,t9=e=>({run_id:e,status:"missing",updated_at:"",workflow_id:"",error:"not found"});function n9(e,t){return{run_id:e,status:String((t==null?void 0:t.status)||"").trim().toLowerCase(),updated_at:String((t==null?void 0:t.updated_at)||(t==null?void 0:t.created_at)||"").trim(),workflow_id:String((t==null?void 0:t.workflow_id)||"").trim(),error:String((t==null?void 0:t.error)||"").trim()}}function s9(e,t){var i,o;const n=[],r=new Set;for(const u of e.values()){const l=String(((o=(i=u==null?void 0:u.waiting)==null?void 0:i.details)==null?void 0:o.sub_run_id)||"").trim();!l||t.has(l)||r.has(l)||(r.add(l),n.push({id:l,version:""}))}return n}function r9(e,t){var u;const n=Array.isArray(t==null?void 0:t.pin_ids)?t.pin_ids.map(l=>String(l)):[],r=(u=t==null?void 0:t.input_data)==null?void 0:u.prompt,o=(n.includes("prompt")||n.length===0)&&typeof r=="string"?r.trim():"";return{run_id:e,excerpt:o}}const i9=12;function tj(e,t,n=i9){const r=[],i=new Set;for(const o of e||[]){let u=0;for(const l of o||[]){const d=xs(l);!d||i.has(d)||(t===null?u>=n:!t.has(d))||(i.add(d),r.push(l),u+=1)}}return r}const mg="abstractobserver_board_cache_v1:",o9=400,Cv=6e5;function a9(e,t){const n=new Map;if(!e)return n;try{const r=e.getItem(mg+t);if(!r)return n;const i=JSON.parse(r);if(!Array.isArray(i))return n;for(const o of i){const u=String((o==null?void 0:o.id)||"").trim();!u||o.value===null||o.value===void 0||n.set(u,{...qg(),value:o.value,has_value:!0,value_version:String(o.version??"")})}}catch{return new Map}return n}function l9(e,t,n){if(e)try{let r=[];for(const[o,u]of n)!u.has_value||u.value===null||u.inflight||u.failed_at!==null||r.push({id:o,version:u.value_version,value:u.value});r=r.slice(-o9);let i=JSON.stringify(r);for(;i.length>Cv&&r.length;)r=r.slice(Math.max(1,Math.floor(r.length/4))),i=JSON.stringify(r);r.length?e.setItem(mg+t,i):e.removeItem(mg+t)}catch{}}function iC(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}const c9=4,rf={automation:0,wait_detail:1,pulse:1,run_brief:2,outcome:3};class u9{constructor(t=c9){kn(this,"queue",[]);kn(this,"seq",0);kn(this,"active",0);kn(this,"peak",0);this.limit=t}get queued(){return this.queue.length}submit(t,n){this.queue.push({priority:t,seq:this.seq++,task:n}),this.queue.sort((r,i)=>r.priority-i.priority||r.seq-i.seq),this.pump()}pump(){for(;this.active<this.limit&&this.queue.length;){const t=this.queue.shift();this.active+=1,this.peak=Math.max(this.peak,this.active),Promise.resolve().then(t.task).catch(()=>{}).finally(()=>{this.active-=1,this.pump()})}}}const nj=new WeakMap;function d9(e){let t=nj.get(e);return t||(t=new u9,nj.set(e,t)),t}const sj=new WeakMap;function f9(e){let t=sj.get(e);return t||(t=e.automations_client(),sj.set(e,t)),t}function h9(e){return e.map(t=>`${t.id}@${t.version}`).sort().join("|")}const rj=new WeakMap;function m9(e,t,n){let r=rj.get(e);r||(r=new Map,rj.set(e,r));let i=r.get(t);return i||(i=n!=null&&n.persist?a9(n.storage===void 0?iC():n.storage,t):new Map,r.set(t,i)),i}const fw=new Map;function _9(e,t){if(typeof setTimeout>"u")return;const n=fw.get(e);n!==void 0&&clearTimeout(n),fw.set(e,setTimeout(()=>{fw.delete(e),l9(iC(),e,t)},250))}function of(e,t,n,r){const i=p.useRef({client:null,entries:new Map,gen:0});i.current.client!==(e||null)&&(i.current={client:e||null,entries:e?m9(e,r.scope,{persist:r.persist}):new Map,gen:i.current.gen+1});const[o,u]=p.useReducer(b=>b+1,0),l=h9(t),d=Math.floor(Date.now()/3e4),h=p.useRef(n);h.current=n,p.useEffect(()=>{const b=i.current;if(!b.client)return;const k=b.client,x=b.gen,N=zB(t,b.entries,Date.now(),{immutable:r.immutable});if(!N.length)return;const $=d9(k);for(const E of N)BB(b.entries,E),$.submit(r.priority,async()=>{try{const S=await h.current(k,E);if(i.current.gen!==x)return;UB(b.entries,E,S),r.persist&&_9(r.scope,b.entries)}catch(S){if(i.current.gen!==x)return;WB(b.entries,E,S,Date.now())}u()});u()},[e,l,d,o,r.priority,r.immutable]);const m=p.useMemo(()=>qB(t,i.current.entries,{current_only:r.current_only}),[l,o,r.current_only,e]),_=p.useMemo(()=>HB(t,i.current.entries),[l,o,e]),g=p.useMemo(()=>VB(t,i.current.entries,{current_only:r.current_only}),[l,o,r.current_only,e]),y=p.useMemo(()=>b=>{const k=i.current.entries.get(b);k&&!k.inflight&&i.current.entries.set(b,{...k,value_version:"\0stale",failed_at:null,failures:0}),u()},[]);return{map:m,pending:_,loading:g,invalidate:y}}function p9(e){var r;const t=Am(e);if(!t)return null;const n=typeof(e==null?void 0:e.active_revision)=="number"?e.active_revision:typeof((r=e==null?void 0:e.definition)==null?void 0:r.revision)=="number"?e.definition.revision:null;return{brief:t,revision:n,raw:e}}function g9(e){var l,d,h;const t=e!=null&&e.definition&&typeof e.definition=="object"?e.definition:{},n=(l=e==null?void 0:e.summary)!=null&&l.trigger&&typeof e.summary.trigger=="object"?e.summary.trigger:t!=null&&t.trigger&&typeof t.trigger=="object"?t.trigger:{},r=n!=null&&n.config&&typeof n.config=="object"?n.config:{},i=(d=t==null?void 0:t.policy)!=null&&d.retry&&typeof t.policy.retry=="object"?t.policy.retry:null,o=i!=null&&i.backoff&&typeof i.backoff=="object"?i.backoff:{},u=typeof r.count=="number"&&Number.isFinite(r.count)&&r.count>0?r.count:null;return{trigger_source:String((n==null?void 0:n.source_id)||"").trim(),stop_after:u,stop_at_ms:Ht(typeof r.until=="string"?r.until:""),workflow_id:String(((h=t==null?void 0:t.target)==null?void 0:h.workflow_id)||"").trim(),retry:i?{max_attempts:typeof i.max_attempts=="number"?i.max_attempts:null,initial:String(o.initial??"").trim(),factor:typeof o.factor=="number"?o.factor:null,max:String(o.max??"").trim()}:null}}function y9(e,t){const n=p.useMemo(()=>GB(t),[t]),r=of(e,n,async(o,u)=>p9(await f9(o).getAutomation(u.id)),{scope:"automation",priority:rf.automation}),i=p.useMemo(()=>{const o=new Map,u=new Map;for(const[l,d]of r.map)o.set(l,d.brief),d.revision!==null&&u.set(l,d.revision);return{map:o,revisions:u}},[r.map]);return{map:i.map,revisions:i.revisions,records:r.map,pending:r.pending,loading:r.loading,invalidate:r.invalidate}}function w9(e,t){const n=p.useMemo(()=>JB(t),[t]),r=of(e,n,async(i,o)=>r9(o.id,await i.get_run_input_data(o.id)),{scope:"excerpt_v2",priority:rf.run_brief,immutable:!0,persist:!0});return{map:r.map,pending:r.pending,loading:r.loading}}function v9(e,t){const n=p.useMemo(()=>XB(t,Date.now()),[t]),r=of(e,n,async(i,o)=>{const u=Number(String(o.version).split(":")[0]||0),l=await i.get_ledger(o.id,ZB(u)),d=Array.isArray(l==null?void 0:l.items)?l.items:[];return d.length?n5(o.id,u,d[d.length-1]):null},{scope:"pulse",priority:rf.pulse});return{map:r.map,pending:r.pending,loading:r.loading}}const x9=!0;function b9(e,t,n){const r=p.useMemo(()=>QB(t,n),[t,n]),i=of(e,r,async(o,u)=>await o.get_run(u.id),{scope:"wait_detail",priority:rf.wait_detail,current_only:x9});return{map:i.map,pending:i.pending,loading:i.loading}}function k9(e,t,n){const r=p.useMemo(()=>s9(t,n),[t,n]),i=of(e,r,async(o,u)=>{try{return n9(u.id,await o.get_run(u.id))}catch(l){if(/\b404\b|not found/i.test(String((l==null?void 0:l.message)||l||"")))return t9(u.id);throw l}},{scope:"subrun_fate",priority:rf.wait_detail});return{map:i.map,pending:i.pending,loading:i.loading}}const j9=!0;function S9(e){return(e||[]).filter(t=>xs(t)&&ds(String((t==null?void 0:t.status)||""))).map(t=>({id:xs(t),version:""}))}function N9(e){const t=e!=null&&e.output&&typeof e.output=="object"?e.output:null;return typeof(t==null?void 0:t.response)=="string"?t.response.trim():typeof(t==null?void 0:t._last_output)=="string"?t._last_output.trim():""}function $9(e){const t=e==null?void 0:e.total;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}async function C9(e,t){const[n,r]=await Promise.all([e.get_run(t),e.list_run_artifacts(t,{limit:1}).then($9,()=>null)]);return{answer:N9(n),artifacts:r}}function E9(e,t){const n=p.useMemo(()=>S9(t),[t]),r=of(e,n,async(i,o)=>await C9(i,o.id),{scope:"outcome",priority:rf.outcome,immutable:j9,persist:!0});return{map:r.map,pending:r.pending,loading:r.loading}}function A9(){const e=typeof IntersectionObserver<"u",[t,n]=p.useState(()=>e?new Set:null),r=p.useRef(new Map),i=p.useRef(new Set),o=p.useMemo(()=>(l,d)=>{const h=r.current.get(l);if(h&&h.el===d||(h&&(h.observer.disconnect(),r.current.delete(l)),!d||!e))return;const m=new IntersectionObserver(_=>{let g=!1;for(const y of _){const b=String(y.target.dataset.runId||"").trim();b&&(y.isIntersecting?!i.current.has(b):i.current.has(b))&&(y.isIntersecting?i.current.add(b):i.current.delete(b),g=!0)}g&&n(new Set(i.current))},{root:d,rootMargin:"100% 0px 100% 0px"});r.current.set(l,{el:d,observer:m});for(const _ of Array.from(d.querySelectorAll("[data-run-id]")))m.observe(_)},[e]),u=p.useMemo(()=>()=>{for(const{el:l,observer:d}of r.current.values()){d.disconnect();for(const h of Array.from(l.querySelectorAll("[data-run-id]")))d.observe(h)}},[]);return p.useEffect(()=>()=>{for(const{observer:l}of r.current.values())l.disconnect();r.current.clear()},[]),{visible:t,attach:o,refresh:u}}const ij=200,oj=500,T9=6e4,M9=1e4,R9=15e3,L9=["llm_calls","tool_calls","tokens_total"];function I9(e,t){if(!t)return e;const n={...e};for(const r of L9){const i=e[r];i==null&&(n[r]=t[r]??null)}return t.archived===!0&&(n.archived=!0),n}function hw(e){return!String((e==null?void 0:e.parent_run_id)||"").trim()||String((e==null?void 0:e.role)||"").trim()==="occurrence"}class O9{constructor(t){kn(this,"sweep_rows",[]);kn(this,"sweep_at",null);kn(this,"sweep_started_at",null);kn(this,"sweep_inflight",!1);kn(this,"active_rows",[]);kn(this,"active_complete",!1);kn(this,"early",!1);kn(this,"active_at",null);kn(this,"seeded",!1);this.epoch=t}sweep_due(t,n=!1){if(this.sweep_inflight)return!1;if(this.sweep_started_at===null)return!0;const r=t-this.sweep_started_at;return r>=T9||this.early&&r>=R9?!0:n&&r>=M9}begin_sweep(t){this.sweep_inflight=!0,this.sweep_started_at=t,this.early=!1}apply_sweep(t,n){this.sweep_inflight=!1,this.sweep_rows=(t||[]).filter(r=>!!xs(r)),this.sweep_at=n}fail_sweep(){this.sweep_inflight=!1}adopt_sweep(t){this.sweep_rows=t.sweep_rows,this.sweep_at=t.sweep_at}adopt_active(t){t.active_at!==null&&(this.active_rows=t.active_rows,this.active_at=t.active_at,this.active_complete=t.active_complete,this.seeded=t.seeded)}snapshot(){return{active_rows:this.active_rows,sweep_rows:this.sweep_rows,active_at:this.active_at,sweep_at:this.sweep_at}}seed(t){return!t||this.active_at!==null||!Array.isArray(t.active_rows)?!1:(this.active_rows=t.active_rows.filter(n=>!!xs(n)),this.sweep_rows=Array.isArray(t.sweep_rows)?t.sweep_rows.filter(n=>!!xs(n)):[],this.active_at=typeof t.active_at=="number"?t.active_at:null,this.sweep_at=typeof t.sweep_at=="number"?t.sweep_at:null,this.active_complete=!1,this.seeded=!0,this.active_rows.length>0||this.sweep_rows.length>0)}apply_active(t,n,r){this.active_at=Date.now(),this.seeded=!1;const i=new Set(this.active_rows.map(xs)),o=new Set,u=[];for(const l of[...t||[],...n||[]]){const d=xs(l);!d||o.has(d)||(o.add(d),u.push(l))}if(this.active_rows=u,this.active_complete=r,r)for(const l of i)o.has(l)||(this.early=!0)}view(){const t=new Map;for(const l of this.sweep_rows)t.set(xs(l),l);const n=new Set,r=[];for(const l of this.active_rows)n.add(xs(l)),r.push(I9(l,t.get(xs(l))));const i=new Map(r.map(l=>[xs(l),l])),o=[...r],u=r.filter(l=>hw(l)&&!t.has(xs(l)));for(const l of this.sweep_rows){const d=xs(l),h=i.get(d);if(h){hw(h)&&u.push(h);continue}this.active_complete&&!ds(String((l==null?void 0:l.status)||""))||o.push(l),hw(l)&&u.push(l)}return{roots:u,all:o}}}function P9(e,t){return`${mg}runs:${String(e||"").trim()}:${String(t||"").trim()}`}function D9(e,t){if(!e)return null;try{const n=e.getItem(t);if(!n)return null;const r=JSON.parse(n);return!r||typeof r!="object"||!Array.isArray(r.active_rows)?null:{active_rows:r.active_rows,sweep_rows:Array.isArray(r.sweep_rows)?r.sweep_rows:[],active_at:typeof r.active_at=="number"?r.active_at:null,sweep_at:typeof r.sweep_at=="number"?r.sweep_at:null}}catch{return null}}function F9(e,t,n){if(e)try{let r=JSON.stringify(n);if(r.length>Cv&&(r=JSON.stringify({...n,sweep_rows:[]})),r.length>Cv){e.removeItem(t);return}e.setItem(t,r)}catch{}}function aj(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}const Ev=new WeakMap;let Av=null;function z9(e,t){let n=Ev.get(e);if(!n||n.epoch!==t){const r=Av;n=new O9(t),r&&r.epoch===t&&(r.sweep_at!==null&&n.adopt_sweep(r),n.adopt_active(r)),Ev.set(e,n)}return Av=n,n}function B9(e){return Ev.get(e)||null}function lj(e){return Av===e}const wp=["needs_you","working","waiting_on","scheduled","done"],oC={needs_you:"Needs you",working:"Working",waiting_on:"Waiting on…",scheduled:"Scheduled",done:"Done"},U9={needs_you:"only you can move these",working:"an agent is on it",waiting_on:"something else must happen first",scheduled:"will start by itself",done:"read the outcome"},W9={needs_you:"nothing needs you",working:"no agent is working",waiting_on:"nothing is blocked",scheduled:"nothing scheduled",done:"no recent runs"},q9=8;function H9(){return{needs_you:[],working:[],waiting_on:[],scheduled:[],done:[]}}function Zs(e){return String((e==null?void 0:e.run_id)||"").trim()}function mw(e){const t=String((e==null?void 0:e.role)||"").trim();return!String((e==null?void 0:e.parent_run_id)||"").trim()||t==="occurrence"||t==="controller"}function V9(e,t,n,r){const i=(e==null?void 0:e.paused)===!0||(n==null?void 0:n.paused)===!0;return x1({...e,paused:i},t,Yp(n),r??null)}function ya(e,t){const n=String(e||"").trim();return n.length>t?`${n.slice(0,t-1)}…`:n}function vp(e,t,n,r){var b,k;const i=Zs(e),o=(b=t.details)==null?void 0:b.get(i),u=(o==null?void 0:o.waiting)??(e==null?void 0:e.waiting),l=u&&typeof u=="object"?u:null,d=sf(l),h=String((e==null?void 0:e.status)||"").trim().toLowerCase(),m=String((e==null?void 0:e.automation_id)||"").trim(),_=m?((k=t.automations)==null?void 0:k.get(m))??null:null,g=n.actor_run_id?t.by_id.get(n.actor_run_id):void 0,y=Ht((l==null?void 0:l.until)||"");return{run_id:i,lane:n.lane,line:n,title:k1(e,t,r),subject:b1(e,t),status_word:V9(e,n,o,_),workflow_id:String((e==null?void 0:e.workflow_id)||"").trim(),role:String((e==null?void 0:e.role)||"").trim(),wait_key:String((l==null?void 0:l.wait_key)||"").trim(),tool_names:d.map(x=>String((x==null?void 0:x.name)||"tool")).filter(Boolean),pending_calls:d.map(x=>({name:String((x==null?void 0:x.name)||"tool"),arguments:(x==null?void 0:x.arguments)??null})),prompt:String((l==null?void 0:l.prompt)||"").trim(),allow_free_text:(l==null?void 0:l.allow_free_text)!==!1,since_ms:Ht((l==null?void 0:l.since)||(e==null?void 0:e.updated_at)||(e==null?void 0:e.created_at)||""),duration_ms:Cm(e,t.now_ms),tokens_total:typeof(e==null?void 0:e.tokens_total)=="number"?e.tokens_total:null,llm_calls:typeof(e==null?void 0:e.llm_calls)=="number"?e.llm_calls:null,tool_calls:typeof(e==null?void 0:e.tool_calls)=="number"?e.tool_calls:null,failed:h==="failed",error:String((e==null?void 0:e.error)||(o==null?void 0:o.error)||"").trim(),paused:n.verb==="paused",archived:(e==null?void 0:e.archived)===!0,automation_id:m,tag:Rg(e),tag_label:DN(e),actor_run_label:g?ti(String(g.workflow_id||""))||"subrun":"",blocks:[],chain:[],asks:[],stuck:!!n.stuck,next_fire_ms:String((e==null?void 0:e.role)||"").trim()==="controller"?(_==null?void 0:_.next_fire_ms)??y:y,automation:_,task:(_==null?void 0:_.task)||String((r==null?void 0:r.excerpt)||"").trim(),row:e}}function G9(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}const xp=(e,t)=>e===null?t===null?0:1:t===null?-1:e-t,cj=(e,t)=>e===null?t===null?0:1:t===null?-1:t-e;function K9(e){return e.needs_you.sort((t,n)=>Number(t.stuck&&!t.asks.length)-Number(n.stuck&&!n.asks.length)||xp(t.since_ms,n.since_ms)),e.working.sort((t,n)=>Number(n.line.stalled)-Number(t.line.stalled)||cj(t.line.stale_ms,n.line.stale_ms)||xp(t.since_ms,n.since_ms)),e.waiting_on.sort((t,n)=>xp(t.since_ms,n.since_ms)),e.scheduled.sort((t,n)=>xp(t.next_fire_ms,n.next_fire_ms)),e.done.sort((t,n)=>Number(n.failed)-Number(t.failed)||cj(t.since_ms,n.since_ms)),e}function uj(e){var y,b,k;const t=H9(),n=[],r=[],i=new Set;for(const x of e.active||[]){const N=Zs(x);!N||i.has(N)||(i.add(N),(ds(x==null?void 0:x.status)?r:n).push(x))}for(const x of e.done||[]){const N=Zs(x);!N||i.has(N)||(i.add(N),ds(x==null?void 0:x.status)&&r.push(x))}const o=_x([...n,...r],{details:e.details,fates:e.fates,pulses:e.pulses,automations:e.automations,now_ms:e.now_ms,stall_after_ms:e.stall_after_ms}),u=new Map(n.map(x=>[Zs(x),x])),l=new Map,d=x=>{const N=Zs(x);let $=l.get(N);return $||($=Xd(x,o),l.set(N,$)),$},h=x=>mw(x)||!u.has(String((x==null?void 0:x.parent_run_id)||"").trim()),m=x=>Ht(String((x==null?void 0:x.updated_at)||(x==null?void 0:x.created_at)||""))??0,_=x=>(o.children_of.get(x)||[]).filter(N=>u.has(Zs(N))&&!mw(N)).sort((N,$)=>m($)-m(N)),g=new Set;for(const x of n){if(!h(x))continue;const N=d(x);if(String((x==null?void 0:x.role)||"").trim()==="controller"){const G=String((x==null?void 0:x.automation_id)||"").trim()||Zs(x);if(g.has(G))continue;g.add(G);const K=vp(x,o,N,(y=e.run_briefs)==null?void 0:y.get(Zs(x)));t[K.lane].push(K);continue}const $=vp(x,o,N,(b=e.run_briefs)==null?void 0:b.get(Zs(x))),E=[],S=[];let P=N.verb==="running",D=!!N.stuck,R=0;const I=(G,K)=>{var O;const H=d(G),M=K<6?_(Zs(G)):[],A=M.length>0;if(E.length>=q9)R+=1;else{const L=A?v1(G,o):"";E.push({run_id:Zs(G),depth:K,name:Og(String((G==null?void 0:G.workflow_id)||""))||Yd(Zs(G)),title:e5(String((G==null?void 0:G.workflow_id)||""))||Zs(G),words:A?L?`waits at ${L} ↓`:"waits for ↓":H.brief||H.text,stuck:!!H.stuck,asks:H.lane==="needs_you"&&!H.stuck,running:H.verb==="running"&&!A,stuck_facts:H.stuck_facts,since_ms:Ht(String((G==null?void 0:G.updated_at)||(G==null?void 0:G.created_at)||""))})}K>0?(H.lane==="needs_you"&&!H.stuck&&S.push(vp(G,o,H,(O=e.run_briefs)==null?void 0:O.get(Zs(G)))),H.stuck&&(D=!0),H.verb==="running"&&(P=!0)):A&&H.lane==="needs_you"&&!H.stuck&&S.push($);for(const L of M)I(L,K+1)};I(x,0),R&&E.push({run_id:"",depth:1,name:`+${R} more`,title:"",words:"",stuck:!1,asks:!1,running:!1}),D&&!S.length&&($.status_word="stuck"),$.chain=E.length>1?E:[],$.asks=S,$.stuck=D;const W=N.lane==="needs_you"&&!N.stuck;if($.lane=W||S.length||D?"needs_you":P?"working":N.lane,S.length){const G=S.map(K=>K.since_ms).filter(K=>K!==null);G.length&&($.since_ms=Math.min(...G))}t[$.lane].push($)}for(const x of r){if(!mw(x)&&o.by_id.has(String((x==null?void 0:x.parent_run_id)||"").trim()))continue;const N=vp(x,o,d(x),(k=e.run_briefs)==null?void 0:k.get(Zs(x)));t.done.push(N)}return K9(t)}function J9(e,t){const r=(t&&t.length?t:e||[]).filter(o=>Zs(o)&&!ds(o==null?void 0:o.status)),i=[...t||[],...e||[]].filter(o=>Zs(o)&&ds(o==null?void 0:o.status));return{active:r,done:i}}const aC="board_stall_after_ms",Ox=[{ms:5*6e4,label:"5m"},{ms:15*6e4,label:"15m"},{ms:60*6e4,label:"1h"}];function lC(e){try{const t=Number(e==null?void 0:e.getItem(aC));return Ox.some(n=>n.ms===t)?t:iv}catch{return iv}}function cC(e){var t;return((t=Ox.find(n=>n.ms===e))==null?void 0:t.label)||Qs(e)}function Y9(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function uC(e){const t=String((e==null?void 0:e.actor_id)||"").trim();return t&&t.toLowerCase()!=="gateway"?t:""}const dC=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],_g=e=>String(e).padStart(2,"0");function du(e,t=Date.now()){const n=new Date(e),r=n.getFullYear()===new Date(t).getFullYear()?"":` ${n.getFullYear()}`;return`${dC[n.getMonth()]} ${n.getDate()}${r}, ${_g(n.getHours())}:${_g(n.getMinutes())}`}function X9(e){const t=new Date(e);return`${dC[t.getUTCMonth()]} ${t.getUTCDate()}, ${_g(t.getUTCHours())}:${_g(t.getUTCMinutes())} UTC`}function Tv(e,t=Date.now()){const n=e-t;return n>0?`in ${Qs(n)}`:`${Qs(-n)} ago`}function Z9(e){if(!e.length)return"a tool call";const t=new Map;for(const r of e)t.set(r,(t.get(r)||0)+1);const n=Array.from(t,([r,i])=>i>1?`${r} ×${i}`:r);return`${n.slice(0,3).join(", ")}${n.length>3?` and ${n.length-3} more`:""}`}const rc=e=>e.split(" ").join(" ");function Px(e,t){const n=e.since_ms!==null?` since ${rc(du(e.since_ms,t))} ${rc(`(${Qs(Math.max(0,t-e.since_ms))})`)}`:"",r=e.line.action;if(e.line.verb==="paused")return{who:"",text:`paused${n}`};if(e.line.stuck)return{who:"",text:`stuck${n}`};const i=uC(e.row);return r==="approve"?{who:i,text:`needs approval for ${Z9(e.tool_names)}${n}`}:r==="answer"?{who:i,text:`${e.prompt?"asks":"waits for an answer"}${n}`}:e.line.unresolved?{who:i,text:`needs you${n} · question, approval or pause`}:{who:i,text:`needs you${n}`}}function Kh(e){if(typeof e=="string")return e;if(e==null||typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function Mv(e,t=0){const r=(e.arguments&&typeof e.arguments=="object"&&!Array.isArray(e.arguments)?Object.entries(e.arguments):[]).map(([i,o])=>`${i}: ${t>0?ya(Kh(o),t):Kh(o)}`);return`${e.name}(${r.join(", ")})`}function Q9(e){const t=e.arguments;return t==null?"":typeof t!="object"||Array.isArray(t)?Kh(t):Object.entries(t).map(([n,r])=>Array.isArray(r)&&r.length&&r.every(i=>i===null||typeof i!="object")?`${n}:
163
+ ${r.map(i=>Kh(i)).join(`
164
+ `)}`:`${n}: ${Kh(r)}`).join(`
165
+ `)}const Op=600,Pp=4e3;function fC(e,t){var n;if(e.lane!=="needs_you")return null;if(e.line.verb==="paused"){const r=String((t==null?void 0:t.pause_reason)||((n=e.row)==null?void 0:n.pause_reason)||"").trim();return r?{text:ya(r,Op),full:ya(r,Pp)}:null}if(e.line.action==="approve"&&e.pending_calls.length){const r=e.pending_calls.map(o=>Mv(o,120)).join(" · "),i=e.pending_calls.map(o=>Mv(o)).join(`
166
+ `);return{text:ya(r,Op),full:ya(i,Pp)}}return e.prompt?{text:ya(e.prompt,Op),full:ya(e.prompt,Pp)}:null}function eU(e,t){if(e.lane!=="done"||e.failed)return null;const n=String((t==null?void 0:t.answer)||"").trim();return n?{text:ya(n,Op),full:ya(n,Pp)}:null}function hC(e,t){const n=[];return e.role==="controller"||(e.duration_ms>=0&&n.push(Qs(e.duration_ms)),e.tokens_total!==null&&n.push(`${e.tokens_total.toLocaleString("en-US")} tk`),e.tool_calls!==null&&n.push(`${e.tool_calls} tool${e.tool_calls===1?"":"s"}`),e.lane==="done"&&typeof(t==null?void 0:t.artifacts)=="number"&&n.push(`${t.artifacts} artifact${t.artifacts===1?"":"s"}`)),n}function Dx(e){var n;const t=String(((n=e.row)==null?void 0:n.session_id)||"").trim();return!t||e.automation_id||e.subject.kind==="automation"||t.startsWith("automation:")?"":t}function tU(e,t,n){return`${String(e||"").split("#")[0]}#session=${encodeURIComponent(t)}&run=${encodeURIComponent(n)}`}const dj="Install the AbstractCode web app (npx @abstractframework/code) to open this conversation";function fj(e){return e.lane!=="done"&&e.role!=="controller"}const nU={automation:"automation",brief:"run brief",excerpt:"prompt",workflow:"untitled"};function pg(e){var t;if(e.title.source==="excerpt"&&e.task)return e.task;if(e.title.source==="brief"){const n=(t=e.row)==null?void 0:t.brief;return String((n==null?void 0:n.title)||(n==null?void 0:n.task_excerpt)||e.title.text).trim()}return e.title.text}const sU=[25e3,5e4,1e5,2e5];function mC(e,t){var E;const n=e.trigger_text||e.schedule_rule_text||(e.trigger?px(e.trigger):"")||e.cadence||"",r=e.current&&!ds(e.current.status)?e.current:null,i=((E=e.trigger)==null?void 0:E.source_id)==="manual";let o="",u="";if(e.status==="paused")o="paused",u=e.paused_reason||"scheduled runs are skipped while paused";else if(r)o=`run #${r.index} in progress`,u=e.next_fire_ms!==null?`next run ${du(e.next_fire_ms,t)}`:"";else if(e.next_fire_ms!==null)o=`next ${rc(Tv(e.next_fire_ms,t))}`,u=`next run ${du(e.next_fire_ms,t)}${e.next_run_local?` · ${e.next_run_local} (owner's zone)`:""}`;else if(e.status==="completed"||e.status==="failed")o=`${e.status}: no next run`;else if(e.event_driven){const S=e.last&&e.last.fired_ms!==null?Yh(new Date(e.last.fired_ms).toISOString(),{timeZone:e.time_zone||null,nowMs:t,style:"day"}):"";o=S?`listening · last: ${rc(S)}`:"listening",u="runs every time something new arrives"}else i||(o="no next run");const l=[n,o].filter(Boolean),d={text:_w(l),title:[n,u].filter(Boolean).join(" · "),parts:l},h=rc(`${e.occurrence_count} turn${e.occurrence_count===1?"":"s"}`);if(!e.last)return{schedule:d,last:{text:_w(["no run yet",h]),title:"this automation has not run",failed:!1,parts:["no run yet",h],failure:""}};const m=e.last,_=m.status==="failed",g=m.fired_ms!==null?rc(Tv(m.fired_ms,t)):"",y=_?String(e.last_notification_text||e.last_excerpt||"").trim():"",k=!!(r&&r.index===m.index)?`#${m.index} started${g?` ${g}`:""}`:`last #${m.index} ${_?"✗ failed":m.status}${g?` ${g}`:""}`,x=m.fired_ms!==null&&m.finished_ms!==null&&m.finished_ms>=m.fired_ms?Qs(m.finished_ms-m.fired_ms):"",N=[k,h],$=[`#${m.index} ${m.status}`,m.fired_ms!==null?`fired ${du(m.fired_ms,t)}`:"",x?`took ${x}`:"",y].filter(Boolean).join(" · ");return{schedule:d,last:{text:_w(N),title:$,failed:_,parts:N,failure:y}}}function _w(e){return e.join(" · ").split(" ").join(" ")}function rU(e){const t=String(e.context_mode||"").trim();if(t!=="growing")return{mode:t,used:null,budget:null,label:t?`${t} context`:"",ratio:null};const n=typeof e.growing_max_tokens=="number"&&e.growing_max_tokens>0?e.growing_max_tokens:null,r=typeof e.context_used_tokens=="number"&&e.context_used_tokens>=0?e.context_used_tokens:null,i=n===null?"context":r===null?`context · ${ac(n)} budget`:`context ${ac(r)} / ${ac(n)}`;return{mode:t,used:r,budget:n,label:i,ratio:r!==null&&n!==null?Math.min(1,r/n):null}}function iU(e){return{context:{mode:"growing",growing:{max_tokens:e}}}}function oU(e){const t=String(e??"").trim();if(!/^\d+$/.test(t))return null;const n=Number(t);return Number.isSafeInteger(n)&&n>0?n:null}const aU={phase:"idle",custom:"",error:"",optimistic:null};function lU(e,t){switch(t.type){case"open":return e.phase==="idle"?{...e,phase:"choose",error:""}:e;case"close":return e.phase==="choose"?{...e,phase:"idle",custom:""}:e;case"custom":return{...e,custom:t.value};case"save":return e.phase==="choose"?{phase:"saving",custom:"",error:"",optimistic:{value:t.value,base:t.base}}:e;case"saved":return e.phase==="saving"?{...e,phase:"idle"}:e;case"failed":return e.phase==="saving"?{phase:"idle",custom:"",error:t.error||"the change was not saved",optimistic:null}:e}}function cU(e,t){const n=t.optimistic;return n&&n.base===e.growing_max_tokens?n.value:e.growing_max_tokens}async function uU(e,t,n,r){try{return await e(t,iU(r),n),{type:"saved"}}catch(i){return{type:"failed",error:Oi(i).message||"the change was not saved"}}}function dU(e,t){if(!e){const l={enabled:!1,reason:"automation details are loading"};return{run_now:l,toggle:{command:"automation.pause",label:"Pause schedule",state:l}}}const n=e.current&&!ds(e.current.status)?e.current:null,r={automation_id:e.automation_id,title:e.title,status:e.status,capabilities:e.capabilities,legacy:e.legacy,current_occurrence:n?{index:n.index,run_id:n.run_id,status:n.status}:null,occurrence_count:e.occurrence_count},i=Xh(r,[],t),o=e.status==="paused",u=o&&e.paused_reason&&i.resume.enabled?{enabled:!0,reason:`paused by the gateway: ${e.paused_reason}`}:i.resume;return{run_now:i.run_now,toggle:o?{command:"automation.resume",label:"Resume schedule",state:u}:{command:"automation.pause",label:"Pause schedule",state:i.pause}}}async function fU(e,t,n){try{return await e(t,n),null}catch(r){return Oi(r).message||"the command was not sent"}}const Qc={run:"Run",spend:"Spend",automation:"Automation",schedule:"Schedule",policy:"Policy",after:"After each run",where:"Where"};function Rv(e,t){return`${e.toLocaleString("en-US")} ${t}${e===1?"":"s"}`}function Th(e,t,n,r,i=!1){return n===null?null:{id:e,label:t,value:i?X9(n):du(n,r),aside:Tv(n,r),copy:new Date(n).toISOString()}}function hU(e){const t=e.line;return t.verb==="paused"?"you, to resume it":t.action==="approve"?`your approval of ${Rv(e.pending_calls.length||e.tool_names.length||1,"tool call")}`:t.action==="answer"?e.prompt?"your answer to a question":"your answer":t.unresolved?"you: a question, an approval or a resume":t.actor==="clock"?"the clock":t.actor==="external"?t.object||"an external event":t.actor==="run"?t.object||"a subrun":t.object||"unknown"}function hj(e,t){if(!t)return null;const n=ti(t);return{id:e,label:"Workflow",value:n||t,aside:n&&n!==t?t:"",aside_mono:!0,copy:t}}const _n=(e,t)=>{t&&e.push(t)};function mU(e,t){var h,m,_,g;const{now_ms:n}=t,r=e.automation,i=t.facts??null,o=e.row,u=e.role==="controller",l=[];if(!u){const y=[];if(!e.automation_id){const $=pg(e);_n(y,{id:"title",label:"Title",value:$,long:!0,source:nU[e.title.source]}),e.task&&e.task!==$&&_n(y,{id:"task",label:"Task",value:e.task,long:!0,source:"prompt"})}_n(y,hj("workflow",e.workflow_id)),_n(y,{id:"run_id",label:"Run id",value:e.run_id,mono:!0});const b=String((o==null?void 0:o.session_id)||"").trim();b&&_n(y,{id:"session",label:"Session",value:b,mono:!0}),_n(y,Th("started","Started",Ht((o==null?void 0:o.created_at)||""),n)),_n(y,Th("last_activity","Last activity",Ht((o==null?void 0:o.updated_at)||""),n));const k=String((o==null?void 0:o.actor_id)||"").trim();if(_n(y,k?{id:"started_by",label:"Started by",value:k,source:uC(o)?"":"not a person"}:{id:"started_by",label:"Started by",value:"not on this row"}),_n(y,{id:"state",label:"State",value:e.failed&&e.error?`failed: ${e.error}`:e.lane==="needs_you"?e.line.brief:e.line.text,long:!0}),e.lane==="needs_you"||e.lane==="waiting_on")if(_n(y,{id:"wait_kind",label:"Waiting for",value:hU(e)}),_n(y,Th("wait_since","Since",e.since_ms,n)),e.line.verb==="paused"){const $=String(((h=t.detail)==null?void 0:h.pause_reason)||(o==null?void 0:o.pause_reason)||"").trim();$&&_n(y,{id:"pause_reason",label:"Reason",value:$,long:!0})}else e.pending_calls.length?e.pending_calls.forEach(($,E)=>_n(y,{id:`tool_call_${E}`,label:E===0?"Tool calls":"",value:Q9($),chips:[$.name],long:!0,copy:Mv($)})):e.prompt&&_n(y,{id:"question",label:"Question",value:e.prompt,long:!0});e.lane==="working"&&_n(y,{id:"no_progress",label:"No progress",value:`marked after ${cC(t.stall_after_ms)} without a ledger step`,source:"board header"}),l.push({id:"run",title:Qc.run,rows:y});const x=[],N=e.lane!=="done";e.duration_ms>=0&&_n(x,{id:"duration",label:"Duration",value:Qs(e.duration_ms),aside:N?"so far":""}),e.tokens_total!==null&&_n(x,{id:"tokens",label:"Tokens",value:e.tokens_total.toLocaleString("en-US"),source:"whole run tree"}),e.llm_calls!==null&&_n(x,{id:"llm_calls",label:"LLM calls",value:e.llm_calls.toLocaleString("en-US")}),e.tool_calls!==null&&_n(x,{id:"tool_calls",label:"Tool calls",value:e.tool_calls.toLocaleString("en-US")}),typeof((m=t.outcome)==null?void 0:m.artifacts)=="number"&&_n(x,{id:"artifacts",label:"Artifacts",value:t.outcome.artifacts.toLocaleString("en-US")}),e.tokens_total===null&&e.llm_calls===null&&e.tool_calls===null&&_n(x,{id:"metrics",label:"Metrics",value:"not measured yet: the 60 s metrics sweep fills them"}),l.push({id:"spend",title:Qc.spend,rows:x})}if(r){const y=[];_n(y,{id:"title",label:"Title",value:r.title||"untitled",long:!0,source:r.title?"automation":""}),r.task&&_n(y,{id:"task",label:"Task",value:r.task,long:!0}),_n(y,{id:"automation_id",label:"Automation id",value:r.automation_id,mono:!0}),_n(y,hj("target_workflow",(i==null?void 0:i.workflow_id)||(u?"":e.workflow_id))),typeof t.revision=="number"&&_n(y,{id:"revision",label:"Revision",value:String(t.revision)}),r.status&&_n(y,{id:"status",label:"Status",value:r.status}),l.push({id:"automation",title:Qc.automation,rows:y});const b=[];_n(b,{id:"trigger",label:"Trigger",value:r.trigger_text||(r.trigger?px(r.trigger,r.schedule_rule_text):"")||r.cadence||"not on the record",source:(i==null?void 0:i.trigger_source)||""}),r.status==="paused"?_n(b,{id:"next",label:"Next run",value:"none while paused: scheduled runs are skipped"}):_n(b,Th("next","Next run",r.next_fire_ms,n,!0)||{id:"next",label:"Next run",value:r.event_driven?"when something new arrives":((_=r.trigger)==null?void 0:_.source_id)==="manual"?"when someone presses Run now":"none scheduled"});const k=r.current&&!ds(r.current.status)?r.current:null;if(k&&_n(b,{id:"current",label:"In progress",value:`#${k.index} ${k.status}`}),r.last&&!(k&&k.index===r.last.index)){const $=r.last.fired_ms!==null&&r.last.finished_ms!==null&&r.last.finished_ms>=r.last.fired_ms?Qs(r.last.finished_ms-r.last.fired_ms):"",E=r.last.fired_ms!==null?du(r.last.fired_ms,n):"";_n(b,{id:"last",label:"Last run",value:`#${r.last.index} ${r.last.status}`,aside:[$,E].filter(Boolean).join(" · ")})}_n(b,{id:"turns",label:"Turns",value:String(r.occurrence_count)}),(i==null?void 0:i.stop_after)!==null&&(i==null?void 0:i.stop_after)!==void 0&&_n(b,{id:"stop_after",label:"Stop after",value:Rv(i.stop_after,"run")}),(i==null?void 0:i.stop_at_ms)!==null&&(i==null?void 0:i.stop_at_ms)!==void 0&&_n(b,Th("stop_at","Stop at",i.stop_at_ms,n,!0)),l.push({id:"schedule",title:Qc.schedule,rows:b});const x=[];if(r.context_mode){const $=r.context_mode==="growing"&&typeof r.growing_max_tokens=="number"&&r.growing_max_tokens>0?`capped at ${ac(r.growing_max_tokens)} tokens`:"";_n(x,{id:"context",label:"Context",value:r.context_mode,aside:$})}_n(x,r.tools.length?{id:"tools",label:"Tools",value:r.tools.join(", "),chips:r.tools}:{id:"tools",label:"Tools",value:"flow default",source:"flow"});const N=[r.model,r.provider].filter(Boolean).join(" · ");if(N&&_n(x,{id:"model",label:"Model",value:N}),r.max_iterations!==null&&_n(x,{id:"max_iterations",label:"Max iterations",value:String(r.max_iterations)}),r.tool_approval&&_n(x,{id:"tool_approval",label:"Tool approval",value:r.tool_approval}),r.untrusted_input_tools&&_n(x,r.untrusted_input_tools.length?{id:"untrusted",label:"Untrusted input",value:r.untrusted_input_tools.join(", "),chips:r.untrusted_input_tools}:{id:"untrusted",label:"Untrusted input",value:"no tool marked"}),r.email_allowed_recipients&&_n(x,{id:"recipients",label:"Email to",value:r.email_allowed_recipients.length?r.email_allowed_recipients.join(", "):"nobody"}),i!=null&&i.retry){const $=i.retry,E=[$.initial?`backoff ${$.initial}`:"",$.factor!==null?`× ${$.factor}`:"",$.max?`up to ${$.max}`:""].filter(Boolean).join(" ");_n(x,{id:"retry",label:"Retry",value:$.max_attempts!==null?Rv($.max_attempts,"attempt"):"on failure",aside:E})}l.push({id:"policy",title:Qc.policy,rows:x}),l.push({id:"after",title:Qc.after,rows:[r.notify_channels.length?{id:"notify",label:"Notify",value:r.notify_channels.join(", "),chips:r.notify_channels}:{id:"notify",label:"Notify",value:"nobody"}]})}const d=String(((g=t.detail)==null?void 0:g.workspace_root)||(r==null?void 0:r.workspace_root)||"").trim();return d&&l.push({id:"where",title:Qc.where,rows:[{id:"workspace",label:"Workspace",value:d,mono:!0,source:r!=null&&r.workspace_access_mode?r.workspace_access_mode.split("_").join(" "):""}]}),l.filter(y=>y.rows.length>0)}const Lv={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},pw={"12h":"last 12h","24h":"last 24h","48h":"last 48h","72h":"last 72h","7d":"last 7 days","14d":"last 14 days","1m":"last month",all:"all loaded"},mj="48h";function _j(e,t,n=Date.now()){const r=Lv[t]??null;if(r===null)return{visible:e,hidden_count:0};const i=n-r,o=[];let u=0;for(const l of e)l.since_ms===null||l.since_ms>=i?o.push(l):u+=1;return{visible:o,hidden_count:u}}const gw=4;function _U(e){var o;const t=(o=e==null?void 0:e.discoveries)==null?void 0:o.dreams_signals_brief;if(!t||typeof t!="object"||Array.isArray(t))return null;const n=typeof t.count=="number"&&Number.isInteger(t.count)&&t.count>0?t.count:0;if(!n)return null;const r=u=>Array.isArray(u)?u.filter(l=>typeof l=="string").map(l=>l.trim()).filter(Boolean):[],i=typeof t.dreams=="number"&&Number.isInteger(t.dreams)&&t.dreams>0?t.dreams:null;return{count:n,kinds:r(t.kinds),felt_tones:r(t.felt_tones),dreams:i}}function pj(e){if(!e||typeof e!="object")return null;const t=String(e.title||"").trim(),n=String(e.statement||"").trim();if(!t&&!n)return null;const r=typeof e.entry_id=="string"&&e.entry_id.trim()?e.entry_id.trim():null;return{record_id:String(e.record_id||"").trim(),title:t,statement:n,entry_id:r}}function pU(e){var l,d;const t=h=>{var _;const m=(_=e==null?void 0:e[h])==null?void 0:_.open;return Array.isArray(m)?m.map(pj).filter(g=>g!==null):[]},n=t("questions"),r=t("problems"),i=(l=e==null?void 0:e.lessons)==null?void 0:l.lessons,o=Array.isArray(i)?i.map(pj).filter(h=>h!==null):[],u=typeof((d=e==null?void 0:e.lessons)==null?void 0:d.total)=="number"?e.lessons.total:o.length;return{questions:n.slice(0,gw),questions_total:n.length,problems:r.slice(0,gw),problems_total:r.length,lessons:o.slice(0,gw),lessons_total:u}}function ac(e){return e===null||!Number.isFinite(e)||e<0?"":e<1e3?String(Math.round(e)):e<1e6?`${(e/1e3).toFixed(e<1e4?1:0)}k`:`${(e/1e6).toFixed(1)}M`}function gU(e,t=Date.now()){const n=String(e||"").trim();if(!n)return null;const r=Date.parse(n);return Number.isFinite(r)?Math.max(0,t-r):null}const yU=6e4;function yw(e,t=Date.now()){if(e===null||!Number.isFinite(e))return"";const n=Math.max(0,t-e);return n<6e4?`${Math.round(n/1e3)}s`:n<36e5?`${Math.round(n/6e4)}m`:n<864e5?`${(n/36e5).toFixed(1)}h`:`${(n/864e5).toFixed(1)}d`}function ww(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function Dp(e){return e.toLowerCase().replace(/[_-]+/g," ")}function wU(e){var h,m;const t=e!=null&&e.spec&&typeof e.spec=="object"?e.spec:null,n=t!=null&&t.phases&&typeof t.phases=="object"&&!Array.isArray(t.phases)?t.phases:null;if(!n)return null;const r=Object.keys(n).filter(_=>_&&typeof _=="string");if(!r.length)return null;const i=[];for(const _ of r){i.push({needle:Dp(_),phase:_});const g=(h=n[_])==null?void 0:h.spoken_synonyms;if(Array.isArray(g))for(const y of g){const b=Dp(String(y||"").trim());b&&i.push({needle:b,phase:_})}}const u=(typeof t.initial_phase=="string"&&r.includes(t.initial_phase)?t.initial_phase:null)??(r.includes("sleep")?"sleep":null);if(!u)return null;const l=[],d=(m=t==null?void 0:t.state_mode_axis)==null?void 0:m.words;if(d&&typeof d=="object"&&!Array.isArray(d))for(const[_,g]of Object.entries(d)){const y=String((g==null?void 0:g.phase)||"").trim(),b=Dp(String(_||"").trim());b&&r.includes(y)&&l.push({needle:b,phase:y})}return{phases:r,synonyms:i,modes:l,initial:u,version:typeof t.version=="number"?t.version:null,sha256:String((e==null?void 0:e.sha256)||"").trim()}}const vU=["asleep","sleep","dream"],xU=["rest"],bU=["awake","idle"];function kU(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const r=Dp(n),i=t.synonyms.filter(u=>r.includes(u.needle)).sort((u,l)=>l.needle.length-u.needle.length);if(i.length)return i[0].phase;const o=t.modes.filter(u=>r.includes(u.needle)).sort((u,l)=>l.needle.length-u.needle.length);return o.length?o[0].phase:n.includes("task")&&!n.includes("no_task")&&t.phases.includes("work")?"work":vU.some(u=>n.includes(u))?t.initial:xU.some(u=>n.includes(u))&&t.phases.includes("personal")?"personal":bU.some(u=>n.includes(u))?t.initial:n.includes("stop")?"stopped":n.includes("pause")?"paused":n}return n.includes("visit")?"visit":n.includes("sleep")||n.includes("dream")?"sleep":n.includes("personal")||n.includes("own_time")||n.includes("own time")?"personal":n.includes("task")&&!n.includes("no_task")||n.includes("work")?"work":n.includes("awake")||n.includes("idle")?"sleep":n.includes("stop")?"stopped":n.includes("pause")?"paused":n.includes("rest")?"resting":n}const jU=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),SU=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function NU(e){if(!e)return jU;const t=e.phases.filter(n=>SU.has(n));return new Set([...t,"paused","stopped","unknown"])}const $U={needs_you:3,working:3,waiting_on:2,scheduled:2,done:3};function _o(e){return s.jsx("span",{className:`mc_sk${e.className?` ${e.className}`:""}`,style:e.width?{width:e.width}:void 0,"aria-hidden":"true"})}function CU(e){return s.jsx(s.Fragment,{children:Array.from({length:e.n},(t,n)=>s.jsxs("div",{className:"mc_card mc_card_skeleton","aria-hidden":"true",children:[s.jsxs("div",{className:"mc_card_head",children:[s.jsx(_o,{className:"mc_sk_title",width:n%2?"72%":"58%"}),s.jsx(_o,{className:"mc_sk_pill"})]}),s.jsx(_o,{width:"88%"}),s.jsx(_o,{width:"46%"})]},n))})}function pm(e){return s.jsx("div",{className:"mc_sk_row",role:"status","aria-busy":"true","aria-label":`loading ${e.what}`,title:`loading ${e.what}…`,children:s.jsx(_o,{width:e.width||"84%"})})}const EU="mc_entities mc_entities_reserved",AU="mc_entities mc_entities_empty",TU=4,_C=12;function MU(e){return s.jsx(s.Fragment,{children:Array.from({length:e.n},(t,n)=>s.jsxs("div",{className:"mc_entity_cell",children:[s.jsxs("div",{className:"mc_entity mc_entity_skeleton","aria-hidden":"true",children:[s.jsx(_o,{className:"mc_sk_title",width:n%2?"64%":"48%"}),s.jsx(_o,{className:"mc_sk_chip"}),s.jsx(_o,{width:"70%"}),s.jsx(_o,{width:"42%"}),s.jsx(_o,{width:"56%"})]}),s.jsx(_o,{className:"mc_sk_hints",width:"120px"})]},n))})}const nl={},RU=["needs_you","working","waiting_on"];function LU(e,t){switch(t.type){case"ask":return e.phase==="idle"?{phase:"confirm",total:t.total}:e;case"keep":return e.phase==="confirm"?{phase:"idle"}:e;case"start":return e.phase==="confirm"?{phase:"busy",total:t.total,done:0,failed:0}:e;case"progress":return e.phase==="busy"?{...e,done:t.done,failed:t.failed}:e;case"finish":return e.phase==="busy"?{phase:"sent",total:e.total,failed:e.failed}:e;case"dismiss":return e.phase==="sent"?{phase:"idle"}:e}}async function pC(e,t,n){var d;const r=Math.max(1,Math.floor((n==null?void 0:n.concurrency)??3)),i=n!=null&&n.waves&&n.waves.length?n.waves.map(h=>[...h]):[[...e]];let o=0,u=0;const l=[];for(const h of i){if(!h.length)continue;if(n!=null&&n.batch){const g=o,y=u;let b=[];try{b=await n.batch(h,(k,x)=>{var N;return(N=n.on_progress)==null?void 0:N.call(n,g+k,y+x)})}catch(k){b=h.map(x=>({run_id:x,error:String((k==null?void 0:k.message)||k||"cancel failed")}))}for(const k of b)o+=1,k.error&&(u+=1,l.push({run_id:k.run_id,error:k.error}));(d=n.on_progress)==null||d.call(n,o,u);continue}let m=0;const _=async()=>{var g;for(;m<h.length;){const y=h[m++],b=await Ux(t,y);o+=1,b.type==="failed"&&(u+=1,l.push({run_id:y,error:b.error})),(g=n==null?void 0:n.on_progress)==null||g.call(n,o,u)}};await Promise.all(Array.from({length:Math.min(r,h.length)},_))}return{done:o,failed:u,failures:l}}function IU(e,t,n,r=0){const i=n??t,o=`Cancel all ${i} task${i===1?"":"s"} in ${oC[e]}`;return i<t||r>0?`${o} (${t} run${t===1?"":"s"} asked)`:o}function OU(e,t,n,r){const[i,o]=p.useReducer(LU,{phase:"idle"}),u=t.length,l=r==null?void 0:r.targets,d=l?l.ids:[...t],h=d.length,m=!!n&&u>0&&RU.includes(e),_=IU(e,l?l.cards:u,h,(l==null?void 0:l.parents)??0);return{state:i,enabled:m,label:_,ask:()=>o({type:"ask",total:h}),keep:()=>o({type:"keep"}),run:async()=>{n&&(o({type:"start",total:h}),await pC(d,n,{batch:r==null?void 0:r.on_cancel_runs,waves:l==null?void 0:l.waves,on_progress:(y,b)=>o({type:"progress",done:y,failed:b})}),o({type:"finish"}),window.setTimeout(()=>o({type:"dismiss"}),4e3))}}}function PU(e){return s.jsx("button",{type:"button",className:`btn mc_icon_btn mc_cancel mc_lane_cancel${e.open?" is_active":""}`,title:e.label,"aria-label":e.label,"aria-expanded":e.open,onClick:e.on_ask,children:s.jsx(qe,{name:"x",size:14})})}function DU(e){const{state:t}=e;if(t.phase==="confirm")return s.jsxs("div",{className:"mc_lane_band mc_lane_band_confirm",role:"group","aria-label":e.label,children:[s.jsxs("span",{className:"mc_lane_band_q",children:[e.label,"?"]}),s.jsx("span",{className:"mc_lane_band_reach",children:KU}),s.jsxs("span",{className:"mc_lane_band_actions",children:[s.jsx("button",{type:"button",className:"btn danger mc_btn_sm",onClick:e.on_run,children:"Cancel all"}),s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:e.on_keep,children:"Keep"})]})]});if(t.phase==="busy")return s.jsxs("div",{className:"mc_lane_band mc_lane_band_progress",role:"status","aria-live":"polite",children:[s.jsx(qe,{name:"loader",size:14,className:"mc_spin"}),s.jsxs("span",{children:["cancelling ",t.done," / ",t.total,t.failed?` · ${t.failed} failed`:""]})]});if(t.phase==="sent"){const n=t.total-t.failed;return s.jsx("div",{className:"mc_lane_band mc_lane_band_progress",role:"status","aria-live":"polite",children:s.jsxs("span",{children:["cancel asked for ",n," task",n===1?"":"s",t.failed?` · ${t.failed} refused`:""]})})}return null}function FU(e){var i,o,u,l,d;(i=nl.lane)==null||i.call(nl,e.col);const t=`mc_column_title_${e.col}`,n=OU(e.col,((o=e.cancel)==null?void 0:o.run_ids)??[],(u=e.cancel)==null?void 0:u.on_cancel_run,{targets:(l=e.cancel)==null?void 0:l.targets,on_cancel_runs:(d=e.cancel)==null?void 0:d.on_cancel_runs}),r=e.count===null?" is_loading":e.count?"":" is_zero";return s.jsxs("section",{className:`mc_column mc_column_${e.col}`,"aria-labelledby":t,children:[s.jsxs("header",{className:"mc_column_head",children:[s.jsx("h2",{className:"mc_column_title",id:t,children:e.title}),n.enabled?s.jsx(PU,{label:n.label,open:n.state.phase!=="idle",on_ask:n.ask}):null,e.tools,s.jsx("span",{className:`mc_column_count${r}`,title:e.count===null?"loading":e.count_title,"aria-busy":e.count===null||void 0,children:e.count===null?"…":e.count}),e.after]}),n.enabled?s.jsx(DU,{state:n.state,label:n.label,on_run:()=>void n.run(),on_keep:n.keep}):null,e.children]})}const Os=e=>e.stopPropagation(),zU=typeof window>"u"?p.useEffect:p.useLayoutEffect;function BU(e){const{line:t}=e.card;if(t.actor==="run"){const n=e.card.actor_run_label,r=n&&!t.text.includes(n)?`run ${ya(n,28)}`:"subrun";return t.actor_run_id?s.jsx("button",{type:"button",className:"mc_actor mc_actor_run",title:`Open the subrun ${e.card.actor_run_label||""}`.trim(),onClick:i=>{i.stopPropagation(),e.on_open_run(t.actor_run_id)},onKeyDown:Os,children:r}):s.jsx("span",{className:"mc_actor mc_actor_run",title:"Another run ends this wait; it is not listed yet",children:"run"})}return t.actor==="external"?s.jsx("span",{className:"mc_actor mc_actor_external",title:`An external system ends this wait: ${t.object||"an event"}`,children:"external"}):t.actor==="unknown"?s.jsx("span",{className:"mc_actor mc_actor_unknown",title:"Nothing on the wire says what ends this wait",children:"unknown"}):null}function UU(){return s.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[s.jsx("rect",{x:"5.5",y:"5.5",width:"8.5",height:"8.5",rx:"1.6"}),s.jsx("path",{d:"M10.5 3.6V3.1a1.6 1.6 0 0 0-1.6-1.6H3.1a1.6 1.6 0 0 0-1.6 1.6v5.8a1.6 1.6 0 0 0 1.6 1.6h.5"})]})}function Fx(e){const[t,n]=p.useState("");return s.jsx("button",{type:"button",className:`mc_copy${t?` is_${t}`:""}`,title:e.title??`Copy ${e.label}`,"aria-label":`Copy ${e.label}`,onClick:async r=>{r.stopPropagation(),n(await Em(e.text)?"copied":"failed"),window.setTimeout(()=>n(""),1500)},onKeyDown:Os,children:t==="copied"?"copied":t==="failed"?"copy failed":s.jsx(UU,{})})}const WU=320,qU=6;function HU(e){const[t,n]=p.useState(!1),r=e.text,i=r.length>WU||r.split(`
167
+ `).length>qU;return s.jsxs("div",{className:`mc_long${i&&!t?" is_folded":""}`,children:[s.jsx("div",{className:"mc_long_text",children:r}),i?s.jsx("button",{type:"button",className:"mc_long_toggle","aria-expanded":t,onClick:()=>n(!t),children:t?"show less":`show all (${r.length.toLocaleString("en-US")} chars)`}):null]})}function VU(e){var r,i;const t=e.row,n=!!((r=t.chips)!=null&&r.length)&&!t.long;return s.jsxs("div",{className:"mc_info_row","data-row":t.id,children:[s.jsxs("dt",{className:"mc_info_label",children:[t.label,t.source?s.jsx("span",{className:"mc_source",children:t.source}):null]}),s.jsxs("dd",{className:"mc_info_value",children:[(i=t.chips)!=null&&i.length?s.jsx("span",{className:"mc_tags",children:t.chips.map((o,u)=>s.jsx("code",{className:"mc_tag",children:o},`${o}:${u}`))}):null,n||!t.value?null:t.long?s.jsx(HU,{text:t.value}):s.jsx("span",{className:`mc_info_text${t.mono?" mono":""}`,children:t.value}),t.aside?s.jsx("span",{className:`mc_info_aside${t.aside_mono?" mono":""}`,children:t.aside}):null]}),s.jsx("dd",{className:"mc_info_copy",children:t.value||t.copy?s.jsx(Fx,{text:t.copy??t.value,label:(t.label||"value").toLowerCase()}):null})]})}function gj(e,t){var d,h;const n=new Map;for(const m of t){const _=Zs(m);_&&n.set(_,m)}const r=m=>{var _;return String(((_=n.get(m))==null?void 0:_.role)||"").trim()==="controller"},i=Array.from(new Set(e.map(m=>String(m||"").trim()).filter(Boolean))),o=[];let u=0,l=0;for(const m of i){if(r(m))continue;u+=1;let _=m,g=String(((d=n.get(m))==null?void 0:d.parent_run_id)||"").trim();const y=new Set([m]);for(;g&&n.has(g)&&!y.has(g)&&!r(g);)_=g,y.add(g),g=String(((h=n.get(g))==null?void 0:h.parent_run_id)||"").trim();_!==m&&(l+=1),o.includes(_)||o.push(_)}return{ids:o,waves:o.length?[o]:[],cards:u,tasks:o.length,runs:u,parents:l}}const GU="Cancel this task: this run, its parents below the automation, and everything working under them";function gC(e,t){const n=e==null?void 0:e.ids[0];return!!(e&&n&&t&&n!==t)?"Cancel this task? Its parents and everything working under them stop too":"Cancel this run? Everything working under it stops too"}const KU="Everything working under those tasks stops too; automation schedules are not touched.";function JU(e){const[t,n]=p.useState(e.current),[r,i]=p.useState(!1),[o,u]=p.useState(""),l=!!e.on_rename,d=t.trim();return s.jsxs("div",{className:"mc_info_row mc_name_it_row","data-row":"name_it",children:[s.jsx("dt",{className:"mc_info_label",children:"Name it"}),s.jsxs("dd",{className:"mc_info_value",children:[s.jsxs("form",{className:"mc_name_it",onSubmit:async h=>{var m;if(h.preventDefault(),!(!e.on_rename||!d)){i(!0),u("");try{await e.on_rename(e.automation_id,d,e.revision),u("renamed"),(m=e.on_renamed)==null||m.call(e,e.automation_id)}catch(_){u(String((_==null?void 0:_.message)||(_==null?void 0:_.code)||_||"rename failed"))}finally{i(!1)}}},children:[s.jsx("input",{className:"mc_name_it_input","aria-label":"The automation's title",value:t,maxLength:200,disabled:!l||r,title:l?"The automation's title (the Automations page shows the same)":"Renaming is not available here",onChange:h=>n(h.target.value)}),s.jsx("button",{type:"submit",className:"btn mc_btn_sm",disabled:!l||r||!d||d===e.current,title:l?"Save the automation's title":"Renaming is not available here: this host does not wire automation revisions",children:r?"Saving":"Save"})]}),o?s.jsx("span",{className:"mc_name_it_msg",children:o}):null]}),s.jsx("dd",{className:"mc_info_copy"})]})}function yC(e){var i;const t=Dx(e.card);if(!t)return null;const n=String(((i=e.code_app)==null?void 0:i.url)||"").trim(),r=e.variant==="icon";return n?s.jsx("a",{className:r?"btn mc_icon_btn mc_open_code":"btn mc_btn_sm mc_btn_quiet mc_open_code",href:tU(n,t,e.card.run_id),target:"_blank",rel:"noreferrer",title:"Open this conversation in the AbstractCode web app (new tab)","aria-label":"Open in Code",onClick:Os,onKeyDown:Os,children:r?s.jsx(qe,{name:"terminal",size:15}):"Open in Code"}):s.jsx("span",{className:"mc_btn_wrap",title:dj,children:s.jsx("button",{type:"button",className:r?"btn mc_icon_btn":"btn mc_btn_sm mc_btn_quiet",disabled:!0,title:dj,"aria-label":"Open in Code",children:r?s.jsx(qe,{name:"terminal",size:15}):"Open in Code"})})}function zx(e,t){switch(t.type){case"ask":return e.phase==="idle"?{phase:"confirm",error:""}:e;case"keep":return e.phase==="confirm"?{phase:"idle",error:""}:e;case"send":return e.phase==="confirm"?{phase:"busy",error:""}:e;case"done":return e.phase==="busy"?{phase:"sent",error:""}:e;case"failed":return e.phase==="busy"?{phase:"idle",error:t.error||"cancel failed"}:e}}const Bx={phase:"idle",error:""};async function Ux(e,t){try{const n=await e(t);return typeof n=="string"&&n?{type:"failed",error:n}:{type:"done"}}catch(n){return{type:"failed",error:String((n==null?void 0:n.message)||n||"cancel failed")}}}function Wx(e){const{phase:t,error:n}=e.state,r=e.question||"Cancel this run?",i=r.startsWith("Cancel this task")?"Cancel task":r.startsWith("Stop this subrun")?"Stop subrun":"Cancel run";return[t==="confirm"||t==="busy"?s.jsxs("span",{className:"mc_confirm",role:"group","aria-label":r,children:[s.jsx("span",{className:"mc_confirm_q",children:r}),s.jsx("button",{type:"button",className:"btn danger mc_btn_sm",disabled:t==="busy",onClick:e.on_send,children:t==="busy"?"Cancelling":i}),s.jsx("button",{type:"button",className:"btn mc_btn_sm",disabled:t==="busy",onClick:()=>e.on_event({type:"keep"}),children:"Keep"})]},"confirm"):t==="sent"?s.jsx("span",{className:"mc_cancel_sent",children:"cancel requested"},"sent"):null,n?s.jsx("div",{className:"mc_act_error",role:"alert",children:n},"error"):null]}function wC(e){return s.jsx("button",{type:"button",className:e.variant==="icon"?"btn mc_icon_btn mc_cancel":"btn mc_btn_sm mc_btn_quiet mc_cancel",title:GU,"aria-label":"Cancel this task",onClick:()=>e.on_event({type:"ask"}),children:e.variant==="icon"?s.jsx(qe,{name:"x",size:15}):"Cancel"})}function YU(e){return s.jsxs(s.Fragment,{children:[e.state.phase==="idle"?wC(e):null,Wx(e)]})}function XU(e){var o;const[t,n]=p.useReducer(zx,Bx),r=t.phase!=="idle"?(o=e.cancel_targets)==null?void 0:o.call(e,e.run_id):void 0,i=async()=>{n({type:"send"}),n(await vC(e.on_cancel_run,e.run_id,r,e.on_cancel_runs))};return s.jsx(YU,{state:t,on_event:n,on_send:()=>void i(),variant:e.variant,question:gC(r,e.run_id)})}async function vC(e,t,n,r){var o;if(!n||n.ids.length<=1)return Ux(e,(n==null?void 0:n.ids[0])||t);const i=await pC(n.ids,e,{batch:r,waves:n.waves});return i.failed?{type:"failed",error:`${i.failed} of ${i.done} cancels failed: ${((o=i.failures[0])==null?void 0:o.error)||"cancel failed"}`}:{type:"done"}}function ZU(e){const{card:t}=e,n=t.automation,r=mU(t,{now_ms:e.now_ms,stall_after_ms:e.stall_after_ms,detail:e.detail,outcome:e.outcome,facts:e.facts,revision:e.revision}),i=t.role==="controller",o=t.automation_id&&e.on_open_automation?e.on_open_automation:null,u=!!(o||!i&&e.on_open_run||Dx(t)||fj(t)&&e.on_cancel_run);return s.jsxs("div",{className:"mc_info_body",children:[r.map(l=>s.jsxs("section",{className:"mc_info_section","data-section":l.id,children:[s.jsx("h3",{className:"mc_info_section_title",children:l.title}),s.jsx("dl",{className:"mc_info_rows",children:l.rows.map(d=>s.jsxs(Ee.Fragment,{children:[s.jsx(VU,{row:d}),l.id==="automation"&&d.id==="title"&&(n!=null&&n.can_revise)?s.jsx(JU,{automation_id:t.automation_id,current:n.title,revision:e.revision??null,on_rename:e.on_rename_automation,on_renamed:e.on_renamed},`${t.automation_id}:${n.title}`):null]},d.id))})]},l.id)),t.automation_id&&!n?s.jsx("p",{className:"mc_info_note",children:"automation details are loading"}):null,u?s.jsxs("div",{className:"mc_info_actions",children:[o?s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:()=>o(t.automation_id),children:"Open automation"}):null,!i&&e.on_open_run?s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:()=>e.on_open_run(t.run_id),children:"Open run"}):null,s.jsx(yC,{card:t,code_app:e.code_app}),fj(t)&&e.on_cancel_run?s.jsx(XU,{run_id:t.run_id,on_cancel_run:e.on_cancel_run,on_cancel_runs:e.on_cancel_runs,cancel_targets:e.cancel_targets}):null]}):null]})}const QU=500,eW=580;let fu=null;function va(){fu!==null&&window.clearTimeout(fu),fu=null}function yj(e,t=QU){var l;const n=e.getBoundingClientRect(),r=window.innerWidth,i=Math.min(t,r-16),o=(l=e.closest(".mc_card"))==null?void 0:l.getBoundingClientRect();if(o&&o.right+8+i<=r-8)return{top:Math.max(8,o.top),left:o.right+8,width:i,side:!0};if(o&&o.left-8-i>=8)return{top:Math.max(8,o.top),left:o.left-8-i,width:i,side:!0};const u=Math.min(Math.max(8,n.right-i),r-i-8);return{top:n.bottom+6,left:u,width:i,side:!1}}function tW(e){const{anchor:t,on_close:n,on_hover:r,...i}=e;return s.jsx(xC,{anchor:t,on_close:n,on_hover:r,label:`About ${e.card.title.text}`,children:s.jsx(ZU,{...i})})}function xC(e){const t=p.useRef(null),n=e.width,[r,i]=p.useState(()=>e.anchor.current?yj(e.anchor.current,n):null),o=p.useRef(e);return o.current=e,zU(()=>{var g;const u=t.current,l=(g=e.anchor.current)==null?void 0:g.getBoundingClientRect();if(!u||!l||!r)return;const d=u.offsetHeight,h=window.innerHeight;if(r.top+d<=h-8)return;const m=l.top-6-d,_=r.side?Math.max(8,h-8-d):m>=8?m:Math.max(8,h-8-d);_!==r.top&&i({...r,top:_})},[r==null?void 0:r.left,r==null?void 0:r.width,r==null?void 0:r.top,r==null?void 0:r.side]),p.useEffect(()=>{const u=h=>{h.key==="Escape"&&o.current.on_close(!0)},l=h=>{var _,g;const m=h.target;m&&((_=o.current.anchor.current)!=null&&_.contains(m)||(g=t.current)!=null&&g.contains(m))||o.current.on_close(!1)},d=()=>{const h=o.current.anchor.current;h&&i(yj(h,o.current.width))};return document.addEventListener("keydown",u,!0),document.addEventListener("pointerdown",l,!0),window.addEventListener("resize",d),window.addEventListener("scroll",d,!0),()=>{document.removeEventListener("keydown",u,!0),document.removeEventListener("pointerdown",l,!0),window.removeEventListener("resize",d),window.removeEventListener("scroll",d,!0)}},[]),r?wg.createPortal(s.jsx("div",{ref:t,className:`mc_info_pop${e.className?` ${e.className}`:""}`,role:"dialog","aria-label":e.label,style:{top:r.top,left:r.left,width:r.width},onMouseEnter:()=>e.on_hover(!0),onMouseLeave:()=>e.on_hover(!1),onClick:Os,onKeyDown:Os,children:e.children}),document.body):null}function nW(e){const t=e.kind==="answer"?"Answer":e.kind==="task"?"Task":"Request",n=e.text.trim().split(/\s+/).filter(Boolean).length;return s.jsxs("div",{className:"mc_gp",children:[s.jsxs("div",{className:"mc_gp_head",children:[s.jsxs("span",{className:`mc_gp_kind mc_gp_kind_${e.kind}`,children:[s.jsx(qe,{name:e.kind==="answer"?"sparkle":"chat",size:14}),s.jsx("span",{children:t})]}),e.about?s.jsx("span",{className:"mc_gp_about",title:e.about,children:e.about}):null,s.jsxs("span",{className:"mc_gp_meta",children:[n.toLocaleString("en-US")," words · ",e.text.length.toLocaleString("en-US")," chars"]}),s.jsx(Fx,{text:e.text,label:`the full ${t.toLowerCase()}`,title:`Copy the full ${t.toLowerCase()}`}),e.on_close?s.jsx("button",{type:"button",className:"btn mc_icon_btn mc_gp_close",title:"Close","aria-label":"Close",onClick:e.on_close,children:s.jsx(qe,{name:"x",size:14})}):null]}),s.jsx("div",{className:"mc_gp_body",children:s.jsx(Si,{text:e.text,images:"link",className:"mc_pop_md"})}),e.on_open?s.jsx("div",{className:"mc_gp_foot",children:s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:e.on_open,children:"Open the run →"})}):null]})}function Fp(e){const[t,n]=p.useState(""),r=p.useRef(null),i=()=>{va(),fu=window.setTimeout(()=>n(u=>u==="hover"?"":u),200)},o=e.kind==="answer"?"answer":e.kind==="task"?"task":"request";return s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:r,className:e.as_title?"mc_card_title mc_title_glimpse":`mc_glimpse mc_glimpse_${e.kind}`,title:`Read the full ${o}`,onMouseEnter:()=>{va(),t||(fu=window.setTimeout(()=>n(u=>u||"hover"),150))},onMouseLeave:()=>t==="hover"?i():va(),onClick:u=>{u.stopPropagation(),va(),n(t==="pinned"?"":"pinned")},children:e.children}),t&&typeof document<"u"?s.jsx(xC,{anchor:r,label:`The full ${o}`,width:eW,className:"mc_pop_text",on_close:()=>n(""),on_hover:u=>u?va():t==="hover"?i():void 0,children:s.jsx(nW,{kind:e.kind,text:e.full,about:e.about,on_open:e.on_open,on_close:()=>n("")})}):null]})}function sW(e){const[t,n]=p.useState(""),r=p.useRef(null),i=()=>{va(),fu=window.setTimeout(()=>n(u=>u==="hover"?"":u),200)},o=e.card.role==="controller"?"About this automation":"About this run";return s.jsxs(s.Fragment,{children:[s.jsx("button",{ref:r,type:"button",className:"btn mc_icon_btn mc_info_btn",title:o,"aria-label":o,"aria-haspopup":"dialog","aria-expanded":t!=="",onClick:u=>{u.stopPropagation(),va(),n(t==="pinned"?"":"pinned")},onKeyDown:Os,onMouseEnter:()=>{va(),t||(fu=window.setTimeout(()=>n(u=>u||"hover"),150))},onMouseLeave:()=>t==="hover"?i():va(),children:s.jsx(qe,{name:"info",size:15})}),t&&typeof document<"u"?s.jsx(tW,{...e,anchor:r,on_close:u=>{var l;n(""),u&&((l=r.current)==null||l.focus())},on_hover:u=>u?va():t==="hover"?i():void 0}):null]})}function rW(e){const t=e.title.text;if(e.subject.kind==="agent"||e.subject.kind==="run"){const r=ti(e.workflow_id);return{label:"",secondary:r&&r!==t?r:""}}const n=e.subject.label&&e.subject.label!==t?e.subject.label:"";return e.role==="controller"?{label:n,secondary:""}:{label:n,secondary:e.subject.secondary!==t?e.subject.secondary:""}}function bC(e){const{card:t}=e,n=e.busy||e.stale===!0,r=t.line.action,i=()=>e.on_open_run(t.run_id);return s.jsxs("div",{className:"mc_card_review_body",onClick:Os,onKeyDown:Os,children:[r==="approve"&&!t.wait_key?s.jsx("div",{className:"mc_card_line",title:"The wait has not registered a wait_key yet — open the run to inspect.",children:"wait key not published yet — open the run"}):null,s.jsx("div",{className:"mc_card_actions",children:r==="approve"&&t.wait_key?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn success mc_btn_sm",disabled:n,onClick:()=>e.on_act(t,{approved:!0}),children:n?"Resuming…":"Approve"}),s.jsx("button",{type:"button",className:"btn danger mc_btn_sm",disabled:n,onClick:()=>e.on_act(t,{approved:!1}),children:"Reject"})]}):r==="resume"&&e.on_resume?s.jsx("button",{type:"button",className:"btn primary mc_btn_sm",disabled:n,onClick:()=>e.on_resume(t),children:n?"Resuming…":"Resume"}):r==="answer"?s.jsx("button",{type:"button",className:"btn primary mc_btn_sm",onClick:i,children:"Review & answer →"}):s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:i,children:"Open the run →"})})]})}function vw(e){const t=e.state.enabled&&!e.busy,n=e.busy?`${e.label}…`:e.state.enabled?[e.hint||e.label,e.state.reason].filter(Boolean).join(" — "):e.state.reason||"not available",r=s.jsx("button",{type:"button",className:`btn mc_icon_btn${e.className?` ${e.className}`:""}`,disabled:!t,title:n,"aria-label":e.label,onClick:e.onClick,children:s.jsx(qe,{name:e.busy?"loader":e.icon,size:15,className:e.busy?"mc_spin":void 0})});return t?r:s.jsx("span",{className:"mc_btn_wrap",title:n,children:r})}function Iv(e){const t=e.parts.length;return s.jsx(s.Fragment,{children:e.parts.map((n,r)=>s.jsxs(Ee.Fragment,{children:[r?" ":null,s.jsxs("span",{className:"mc_unit",children:[n,r<t-1?s.jsx("span",{className:"mc_sep",children:" ·"}):null]})]},r))})}function iW(e){const{card:t}=e,n=t.automation,[r,i]=p.useReducer(lU,aU),o=n?mC(n,e.now_ms):null,u=n?cU(n,r):null,l=n?rU({...n,growing_max_tokens:u}):null,d=!!(n!=null&&n.can_revise&&e.on_revise_automation),h=oU(r.custom),m=_=>{if(!n||!e.on_revise_automation||r.phase!=="choose")return;const g=e.on_revise_automation;i({type:"save",value:_,base:n.growing_max_tokens}),uU(g,n.automation_id,e.revision??null,_).then(y=>{var b;i(y),y.type==="saved"&&((b=e.on_renamed)==null||b.call(e,n.automation_id))})};return s.jsxs(s.Fragment,{children:[o?s.jsxs("div",{className:"mc_facts",children:[s.jsx("div",{className:"mc_fact_cell mc_fact_schedule",title:o.schedule.title||void 0,children:s.jsx(Iv,{parts:o.schedule.parts})}),s.jsx("div",{className:`mc_fact_cell mc_fact_last${o.last.failed?" is_failed":""}`,title:o.last.title||void 0,children:s.jsx(Iv,{parts:o.last.parts})}),o.last.failure?s.jsx("div",{className:"mc_fact_fail",title:o.last.failure,children:o.last.failure}):null]}):e.automation_loading?s.jsxs("div",{className:"mc_facts","aria-busy":"true",children:[s.jsx(pm,{what:"the schedule",width:"90%"}),s.jsx(pm,{what:"the last run",width:"80%"})]}):s.jsx("div",{className:"mc_card_state",children:s.jsx("span",{className:"mc_state_text",title:t.line.text,children:t.line.text})}),l&&l.mode==="growing"?s.jsxs("div",{className:"mc_ctx",onClick:Os,onKeyDown:Os,children:[s.jsxs("button",{type:"button",className:`mc_ctx_bar${r.phase==="saving"?" is_saving":""}`,"aria-expanded":r.phase!=="idle","aria-label":`${l.label}: change the budget`,disabled:!d||r.phase==="saving",title:d?`${l.used!==null?`${l.used.toLocaleString("en-US")} tokens of history were replayed into the last run`:"the last run recorded no history size"} · budget ${(u==null?void 0:u.toLocaleString("en-US"))??"unset"} tokens · click to change`:`${l.label} · the budget is changed on the Automations page`,onClick:()=>i({type:r.phase==="idle"?"open":"close"}),children:[l.ratio!==null?s.jsx("span",{className:"mc_ctx_track","aria-hidden":"true",children:s.jsx("span",{className:"mc_ctx_fill",style:{width:`${Math.round(l.ratio*100)}%`}})}):null,s.jsx("span",{className:"mc_ctx_label",children:l.label})]}),r.phase==="choose"?s.jsxs("div",{className:"mc_ctx_chooser",role:"group","aria-label":"Context budget",children:[sU.map(_=>s.jsx("button",{type:"button",className:`btn mc_btn_sm${_===u?" is_current":" mc_btn_quiet"}`,"aria-pressed":_===u,title:`${_.toLocaleString("en-US")} tokens`,onClick:()=>m(_),children:ac(_)},_)),s.jsxs("form",{className:"mc_ctx_custom",onSubmit:_=>{_.preventDefault(),h!==null&&m(h)},children:[s.jsx("input",{type:"number",className:"mc_ctx_input",min:1,step:1e3,placeholder:"custom","aria-label":"Custom context budget, in tokens",value:r.custom,onChange:_=>i({type:"custom",value:_.target.value})}),s.jsx("button",{type:"submit",className:"btn mc_btn_sm",disabled:h===null,title:h===null?"a whole number of tokens":`set the budget to ${h.toLocaleString("en-US")} tokens`,children:"Set"})]}),s.jsx("button",{type:"button",className:"btn mc_icon_btn mc_ctx_close","aria-label":"Close",title:"Close",onClick:()=>i({type:"close"}),children:s.jsx(qe,{name:"x",size:15})})]}):null,r.error?s.jsx("div",{className:"mc_act_error",role:"alert",children:r.error}):null]}):l&&l.label?s.jsx("span",{className:"mc_ctx_chip",title:`${l.mode} context: every run starts from the task alone`,children:l.label}):null]})}const oW={busy:"",error:""},wj={enabled:!1,reason:"commands are not wired on this host"},aW={enabled:!0},lW="Stop this subrun and everything under it? Its parent continues and may delegate again",cW="Stop this subrun and everything under it: its parent continues and may delegate again";function uW(e){if(!e)return"a subrun ended and this run was not resumed";if(e.status==="missing")return`its subrun ${e.subrun} no longer exists on the gateway, so this run cannot be resumed`;const t=e.status==="cancelled"?"was cancelled":e.status==="failed"?"failed":`ended ${e.status}`,n=e.ended_ms!==null?` ${Qs(e.ended_ms)} ago`:"";return`its subrun ${e.subrun} ${t}${n} and this run was not resumed`}function kC(e){const t=typeof e.since_ms=="number"?` since ${rc(du(e.since_ms,e.now_ms))} ${rc(`(${Qs(Math.max(0,e.now_ms-e.since_ms))})`)}`:"";return s.jsxs("div",{className:"mc_ask mc_ask_stuck","data-run-id":e.run_id,role:"group","aria-label":"stuck",children:[s.jsxs("div",{className:"mc_ask_head",children:[s.jsx("button",{type:"button",className:"mc_ask_who",onClick:()=>e.on_open_run(e.run_id),onKeyDown:Os,children:e.name})," ",s.jsxs("span",{className:"mc_ask_words",children:["stuck",t]})]}),s.jsxs("div",{className:"mc_stuck_why",children:[dW(uW(e.facts)),"."]}),s.jsxs("div",{className:"mc_card_actions",children:[e.on_cancel_task?s.jsx("button",{type:"button",className:"btn danger mc_btn_sm",onClick:e.on_cancel_task,children:"Cancel task"}):null,s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:()=>e.on_open_run(e.run_id),children:"Open the run →"})]})]})}function dW(e){return e&&e[0].toUpperCase()+e.slice(1)}function fW(e){const{row:t}=e,[n,r]=p.useReducer(zx,Bx),i=async()=>{e.on_cancel_run&&(r({type:"send"}),r(await Ux(e.on_cancel_run,t.run_id)))},o=!t.run_id;return s.jsxs("div",{className:`mc_chain_row${t.stuck?" is_stuck":""}${t.asks?" is_ask":""}${t.running?" is_running":""}`,style:{paddingLeft:`${Math.min(t.depth,5)*14}px`},"data-run-id":t.run_id||void 0,children:[s.jsxs("div",{className:"mc_chain_main",children:[t.depth>0?s.jsx("span",{className:"mc_chain_glyph","aria-hidden":"true",children:"└"}):null,o?s.jsx("span",{className:"mc_chain_name is_more",children:t.name}):s.jsx("button",{type:"button",className:"mc_chain_name",title:`Open ${t.title||t.name}`,onClick:()=>e.on_open_run(t.run_id),onKeyDown:Os,children:t.name}),t.words?s.jsx("span",{className:"mc_chain_words",title:t.words,children:t.words}):null,e.on_cancel_run&&t.depth>0&&!o&&n.phase==="idle"?s.jsx("button",{type:"button",className:"btn mc_icon_btn mc_cancel mc_chain_cancel",title:cW,"aria-label":`Stop subrun ${t.name} only`,onClick:()=>r({type:"ask"}),children:s.jsx(qe,{name:"x",size:13})}):null]}),n.phase!=="idle"||n.error?s.jsx("div",{className:"mc_chain_confirm",children:Wx({state:n,on_event:r,on_send:()=>void i(),question:lW})}):null]})}function hW(e){const{card:t}=e,n=t.stuck&&!t.asks.length?t.chain.find(o=>o.stuck):void 0,r=new Set((e.ask_loading||"").split(",").filter(Boolean)),i=o=>!!e.busy_wait&&e.busy_wait===`${o.run_id}:${o.wait_key}:${o.since_ms??""}`;return s.jsxs("div",{className:"mc_chain",onClick:Os,onKeyDown:Os,children:[t.chain.map((o,u)=>s.jsx(fW,{row:o,on_open_run:e.on_open_run,on_cancel_run:e.on_cancel_run},o.run_id||`more-${u}`)),t.asks.map(o=>{var h;const u=(h=e.ask_detail)==null?void 0:h[o.run_id],l=fC(o,u),d=Px(o,e.now_ms);return s.jsxs("div",{className:"mc_ask","data-run-id":o.run_id,children:[s.jsxs("div",{className:"mc_ask_head",title:o.line.text,children:[s.jsx("button",{type:"button",className:"mc_ask_who",onClick:()=>e.on_open_run(o.run_id),onKeyDown:Os,children:Og(o.workflow_id)||Yd(o.run_id)})," ",s.jsxs("span",{className:"mc_ask_words",children:[d.who?`${d.who} · `:"",d.text]})]}),!l&&r.has(o.run_id)?s.jsx(pm,{what:"the request"}):l?s.jsx(Fp,{kind:"request",text:l.text,full:l.full,about:t.title.text,on_open:()=>e.on_open_run(o.run_id),children:l.text}):null,s.jsx(bC,{...e,card:o,detail:u,busy:i(o)})]},o.run_id)}),n?s.jsx(kC,{run_id:n.run_id,name:n.name,facts:n.stuck_facts,since_ms:n.since_ms,now_ms:e.now_ms,on_open_run:e.on_open_run,on_cancel_task:e.on_cancel_task}):null]})}function mW(e){var H,M;const{card:t}=e;(H=nl.card)==null||H.call(nl,t.run_id);const[n,r]=p.useReducer(zx,Bx),[i,o]=p.useState(oW),u=t.status_word,l=rW(t),d=t.role==="controller",h=t.chain.length>0,m=!d&&t.lane==="needs_you"&&!h,_=!d&&(t.lane==="needs_you"||t.lane==="working"||t.lane==="waiting_on"),g=m?fC(t,e.detail):null,y=d?null:eU(t,e.outcome),b=hC(t,e.outcome),k=m?Px(t,e.now_ms):null,x=m&&!g&&e.detail_loading===!0,N=!d&&t.lane==="done"&&!y&&!t.failed&&e.outcome_loading===!0,$=t.title.untitled&&e.brief_loading===!0,E=_?e.on_cancel_run:void 0,S=n.phase!=="idle"&&E?(M=e.cancel_targets)==null?void 0:M.call(e,t.run_id):void 0,P=async()=>{E&&(r({type:"send"}),r(await vC(E,t.run_id,S,e.on_cancel_runs)))},D=A=>{!e.on_automation_command||i.busy||(o({busy:A,error:""}),fU(e.on_automation_command,t.automation_id,A).then(O=>{var L;o({busy:"",error:O||""}),O||(L=e.on_renamed)==null||L.call(e,t.automation_id)}))},R=d?dU(t.automation,i.busy!==""):null,I=n.phase!=="idle"||n.error||i.error,G=!(d||_&&(!!Dx(t)||!!E))&&b.length>0,K=b.length?s.jsx("div",{className:`mc_card_metrics${G?" mc_foot_metrics":""}`,title:t.lane==="done"?"run time · tokens of the run tree · tool calls · artifacts":"time since the run started · tokens of the run tree · tool calls",children:s.jsx(Iv,{parts:b})}):null;return s.jsxs("div",{className:`mc_card mc_card_${t.lane}${t.failed?" mc_card_failed":""}${t.line.stalled?" mc_card_stalled":""}${d?" mc_card_automation":""}`,"data-lane":t.lane,"data-run-id":t.run_id,onClick:()=>e.on_open_run(t.run_id),role:"button",tabIndex:0,onKeyDown:A=>{A.key==="Enter"&&A.target===A.currentTarget&&e.on_open_run(t.run_id)},children:[s.jsxs("div",{className:"mc_card_head",children:[s.jsx("span",{className:`mc_card_glyph mc_glyph_${t.subject.kind}`,"aria-hidden":"true",children:t.subject.glyph}),$?s.jsx("span",{className:"mc_card_title",title:"loading the title…",children:s.jsx(_o,{className:"mc_sk_title",width:"64%"})}):h||t.task?s.jsxs(Fp,{kind:"task",text:t.title.text,full:t.task||pg(t),about:t.subject.label||t.subject.secondary,on_open:()=>e.on_open_run(t.run_id),as_title:!0,children:[t.title.text,t.title.untitled?s.jsxs(s.Fragment,{children:[" ",s.jsx(cb,{tone:"muted",size:"sm",className:"mc_untitled",title:"No title on the wire yet: the workflow id stands in",children:"untitled"})]}):null]}):s.jsxs("span",{className:"mc_card_title",title:pg(t),children:[t.title.text,t.title.untitled?s.jsxs(s.Fragment,{children:[" ",s.jsx(cb,{tone:"muted",size:"sm",className:"mc_untitled",title:"No title on the wire yet: the workflow id stands in",children:"untitled"})]}):null]}),s.jsx("span",{className:`mc_status ${ka(u)}`,children:u==="unknown"?"?":u})]}),(l.label||l.secondary||t.archived)&&!(h&&!l.label&&!t.archived&&t.chain[0]&&(l.secondary===t.chain[0].name||l.secondary===ti(t.workflow_id)))?s.jsxs("div",{className:"mc_card_subject",children:[l.label?s.jsx("span",{className:"mc_subject_label",title:l.label,children:l.label}):null,l.secondary?s.jsx("span",{className:"mc_subject_secondary",title:l.secondary,children:l.secondary}):null,t.archived?s.jsx("span",{className:"mc_pill","data-tag":"archived",title:"This conversation is archived: hidden from chat lists, kept here and in the ledger",children:"Archived"}):null]}):null,d?s.jsx(iW,{...e}):h?s.jsx(hW,{...e,on_cancel_task:E?()=>r({type:"ask"}):void 0}):N?s.jsx(pm,{what:"the answer"}):y?s.jsx(Fp,{kind:"answer",text:y.text,full:y.full,about:t.title.text,on_open:()=>e.on_open_run(t.run_id),children:s.jsx(Si,{text:y.text,images:"link",className:"mc_glimpse_md"})}):s.jsxs("div",{className:"mc_card_state",children:[s.jsx(BU,{card:t,on_open_run:e.on_open_run}),k?s.jsxs("span",{className:"mc_state_text",title:t.line.text,children:[k.who?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mc_who",title:`Started by ${k.who}`,children:k.who})," · "]}):null,k.text]}):s.jsx("span",{className:"mc_state_text",title:t.failed&&t.error?t.error:t.line.text!==t.line.brief?t.line.text:void 0,children:t.line.text}),t.line.stalled?s.jsx("span",{className:"mc_stall",role:"img","aria-label":"no progress",title:`No ledger step for ${Qs(t.line.stale_ms??0)}: past the ${cC(e.stall_after_ms)} threshold set in the Working lane's head`,children:" ⚠"}):null,t.line.action==="inspect"?s.jsxs(s.Fragment,{children:[" ",s.jsx("button",{type:"button",className:"mc_inspect",onClick:A=>{A.stopPropagation(),e.on_open_run(t.run_id)},onKeyDown:Os,children:"Inspect →"})]}):null]}),x?s.jsx(pm,{what:"the request"}):g?s.jsx(Fp,{kind:"request",text:g.text,full:g.full,about:t.title.text,on_open:()=>e.on_open_run(t.run_id),children:g.text}):null,m&&t.line.stuck?s.jsx(kC,{run_id:t.run_id,name:Og(t.workflow_id)||Yd(t.run_id),facts:t.line.stuck_facts,since_ms:t.since_ms,now_ms:e.now_ms,on_open_run:e.on_open_run,on_cancel_task:E?()=>r({type:"ask"}):void 0}):m?s.jsx(bC,{...e}):null,G?null:K,I?s.jsxs("div",{className:"mc_card_notice",onClick:Os,onKeyDown:Os,children:[Wx({state:n,on_event:r,on_send:()=>void P(),question:gC(S,t.run_id)}),i.error?s.jsx("div",{className:"mc_act_error",role:"alert",children:i.error}):null]}):null,s.jsxs("div",{className:`mc_card_foot${d?" mc_auto_foot":""}`,onClick:Os,onKeyDown:Os,children:[d&&R?s.jsxs(s.Fragment,{children:[s.jsx(vw,{state:e.on_open_automation?aW:{enabled:!1,reason:"not available here"},label:"Open automation",hint:"Open this automation on the Automations page",icon:"loop",onClick:()=>{var A;return(A=e.on_open_automation)==null?void 0:A.call(e,t.automation_id)}}),s.jsx(vw,{state:e.on_automation_command?R.run_now:wj,label:"Run now",icon:"playCircle",busy:i.busy==="automation.run_now",onClick:()=>D("automation.run_now")}),s.jsx(vw,{state:e.on_automation_command?R.toggle.state:wj,label:R.toggle.label,icon:R.toggle.command==="automation.resume"?"play":"pause",busy:i.busy===R.toggle.command,onClick:()=>D(R.toggle.command)})]}):s.jsxs(s.Fragment,{children:[_?s.jsx(yC,{card:t,code_app:e.code_app,variant:"icon"}):null,E?n.phase==="idle"?wC({on_event:r,variant:"icon"}):s.jsx("span",{className:"mc_btn_wrap",title:n.phase==="sent"?"cancel requested":"Cancel this task? Answer just above",children:s.jsx("button",{type:"button",className:"btn mc_icon_btn mc_cancel is_active",disabled:!0,"aria-label":"Cancel this task",children:s.jsx(qe,{name:"x",size:15})})}):null]}),G?K:s.jsx("span",{className:"mc_spacer"}),d?null:s.jsx(Fx,{text:t.run_id,label:"the run id",title:t.run_id}),s.jsx(sW,{card:t,now_ms:e.now_ms,stall_after_ms:e.stall_after_ms,revision:e.revision,detail:e.detail,outcome:e.outcome,facts:e.facts,code_app:e.code_app,on_open_run:e.on_open_run,on_open_automation:e.on_open_automation,on_rename_automation:e.on_rename_automation,on_renamed:e.on_renamed,on_cancel_run:e.on_cancel_run,on_cancel_runs:e.on_cancel_runs,cancel_targets:e.cancel_targets})]})]})}const vj=new WeakMap;let xj=0;function _W(e){if(!e||typeof e!="object")return String(e??"");let t=vj.get(e);return t===void 0&&(xj+=1,t=xj,vj.set(e,t)),`#${t}`}function pW(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function gW(e,t){const n=e.line,r=e.row||{},i=e.role==="controller"&&e.automation?mC(e.automation,t):null;return[e.run_id,e.lane,e.status_word,e.role,e.workflow_id,e.wait_key,e.prompt,e.allow_free_text,e.failed,e.error,e.paused,e.archived,e.automation_id,e.actor_run_label,e.task,e.title.text,e.title.untitled,e.title.source,pg(e),e.subject.kind,e.subject.glyph,e.subject.label,e.subject.secondary,n.text,n.brief,n.verb,n.action,n.actor,n.actor_run_id,n.object,n.stalled,n.unresolved,typeof n.stale_ms=="number"?Qs(n.stale_ms):"",e.tool_names.join(","),pW(e.pending_calls),e.blocks.map(o=>`${o.run_id}:${o.title}`).join("|"),e.chain.map(o=>`${o.run_id}:${o.depth}:${o.words}:${o.stuck}:${o.asks}:${o.running}`).join("|"),e.asks.map(o=>Ov(o,t)).join("|"),String(e.stuck),e.since_ms,e.next_fire_ms,hC(e).join("·"),e.llm_calls,r.session_id,r.actor_id,r.pause_reason,r.created_at,r.updated_at,r.status,_W(e.automation),e.lane==="needs_you"?Px(e,t).text:"",i?`${i.schedule.text}|${i.schedule.title}|${i.last.text}|${i.last.title}`:""].join("")}const bj=new WeakMap;function Ov(e,t){const n=bj.get(e);if(n&&n.now_ms===t)return n.sig;const r=gW(e,t);return bj.set(e,{now_ms:t,sig:r}),r}function yW(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const r of n)if(!(r==="card"||r==="now_ms")){if(r==="ask_detail"){const i=e[r]||{},o=t[r]||{},u=Object.keys(i),l=Object.keys(o);if(u.length!==l.length||u.some(d=>!Object.is(i[d],o[d])))return!1;continue}if(!Object.is(e[r],t[r]))return!1}return e.card===t.card&&e.now_ms===t.now_ms?!0:Ov(e.card,e.now_ms)===Ov(t.card,t.now_ms)}const wW=Ee.memo(mW,yW),xw=8;function vW(e){var ze,Ve,ct,Qe,Dt,$e,Le,ce;(ze=nl.page)==null||ze.call(nl);const t=Date.now(),[n,r]=p.useState(()=>lC(Y9())),i=p.useMemo(()=>J9(e.runs,e.all_runs),[e.runs,e.all_runs]),o=p.useMemo(()=>[...i.active,...i.done],[i]),u=y9(e.client,o),l=v9(e.client,i.active),d=A9(),h=p.useMemo(()=>Object.fromEntries(wp.map(Q=>[Q,_e=>d.attach(Q,_e)])),[d.attach]),[m,_]=p.useState(""),[g,y]=p.useState(""),[b,k]=p.useState(!1),[x,N]=p.useState(()=>{try{const Q=localStorage.getItem("abstractobserver_done_window_v1");return Q&&Q in Lv?Q:mj}catch{return mj}}),$=p.useMemo(()=>uj({active:i.active,done:i.done,pulses:l.map,automations:u.map,now_ms:Date.now(),stall_after_ms:n}),[i,l.map,u.map,n]),E=p.useMemo(()=>_j($.done,x,Date.now()).visible,[$,x]),S=p.useMemo(()=>(b?E:E.slice(0,xw)).map(Q=>Q.row),[E,b]),P=p.useMemo(()=>tj(wp.map(Q=>Q==="done"?S:$[Q].flatMap(_e=>[_e.row,..._e.asks.map(le=>le.row)])),d.visible),[$,S,d.visible]),D=b9(e.client,P,i.active),R=p.useMemo(()=>new Set(i.active.map(Q=>Zs(Q))),[i.active]),I=k9(e.client,D.map,R),W=w9(e.client,P),G=p.useMemo(()=>tj([S],d.visible),[S,d.visible]),K=E9(e.client,G),H=p.useRef(new WeakMap),M=p.useMemo(()=>{const Q=new Map;for(const[_e,le]of u.records){const Se=le.raw&&typeof le.raw=="object"?le.raw:null;let pe=Se?H.current.get(Se):void 0;pe||(pe=g9(le.raw),Se&&H.current.set(Se,pe)),Q.set(_e,pe)}return Q},[u.records]),A=p.useMemo(()=>W.map.size||D.map.size?uj({active:i.active,done:i.done,details:D.map,fates:I.map,pulses:l.map,automations:u.map,run_briefs:W.map,now_ms:Date.now(),stall_after_ms:n}):$,[$,W.map,i,D.map,l.map,u.map,n]),O=p.useMemo(()=>_j(A.done,x,t),[A.done,x]),L=wp.map(Q=>A[Q].map(_e=>[_e.run_id,..._e.asks.map(le=>le.run_id)].join("+")).join(",")).join("|")+`|${b}|${x}`;p.useEffect(()=>{d.refresh()},[L,d.refresh]);const[V,J]=p.useState(""),[U,te]=p.useState(null),z=e.entities===null,ne=e.entities??[],se=Q=>`${Q.run_id}:${Q.wait_key}:${Q.since_ms??""}`;p.useEffect(()=>{m&&(A.needs_you.some(Q=>se(Q)===m||Q.asks.some(_e=>se(_e)===m))||_(""))},[A,m]);async function de(Q,_e){_(se(Q)),y("");try{await e.on_resume_wait(Q.run_id,Q.wait_key,_e)}catch(le){y(`${Q.title.text}: ${String((le==null?void 0:le.message)||le||"resume failed")}`),_("")}}async function be(Q){if(e.on_resume_run){_(se(Q)),y("");try{const _e=await e.on_resume_run(Q.run_id);if(typeof _e=="string"&&_e)throw new Error(_e)}catch(_e){y(`${Q.title.text}: ${String((_e==null?void 0:_e.message)||_e||"resume failed")}`),_("")}}}const Me=p.useRef(e);Me.current=e;const je=p.useRef(de);je.current=de;const ae=p.useRef(be);ae.current=be;const xe=p.useRef(i.active);xe.current=i.active;const Ae=p.useMemo(()=>({open_run:Q=>Me.current.on_open_run(Q),open_automation:Q=>Me.current.on_open_automation(Q),rename:((Q,_e,le)=>Me.current.on_rename_automation(Q,_e,le)),revise:((Q,_e,le)=>Me.current.on_revise_automation(Q,_e,le)),command:((Q,_e)=>Me.current.on_automation_command(Q,_e)),cancel:(Q=>Me.current.on_cancel_run(Q)),cancel_batch:((Q,_e)=>Me.current.on_cancel_runs(Q,_e)),cancel_targets:Q=>gj([Q],xe.current),act:(Q,_e)=>void je.current(Q,_e),resume:Q=>void ae.current(Q)}),[]),He=String(((Ve=e.code_app)==null?void 0:Ve.url)||"").trim(),mt=p.useMemo(()=>He?{url:He}:null,[He]),nt=p.useMemo(()=>Q=>{u.invalidate(Q),window.setTimeout(()=>u.invalidate(Q),2e3)},[u.invalidate]),rt=Q=>({now_ms:t,stall_after_ms:n,busy:m===se(Q),on_open_run:Ae.open_run,on_act:Ae.act,on_resume:e.on_resume_run?Ae.resume:void 0,on_open_automation:Ae.open_automation,on_rename_automation:e.on_rename_automation?Ae.rename:void 0,on_renamed:nt,revision:Q.automation_id?u.revisions.get(Q.automation_id)??null:null,detail:D.map.get(Q.run_id),outcome:K.map.get(Q.run_id)??null,facts:Q.automation_id?M.get(Q.automation_id)??null:null,code_app:mt,on_cancel_run:e.on_cancel_run?Ae.cancel:void 0,on_cancel_runs:e.on_cancel_runs?Ae.cancel_batch:void 0,cancel_targets:Ae.cancel_targets,ask_detail:Q.asks.length?Object.fromEntries(Q.asks.map(_e=>[_e.run_id,D.map.get(_e.run_id)])):void 0,ask_loading:Q.asks.length?Q.asks.filter(_e=>D.loading.has(_e.run_id)).map(_e=>_e.run_id).join(","):void 0,busy_wait:Q.asks.length?m:void 0,stale:e.runs_stale===!0?!0:void 0,on_automation_command:e.on_automation_command?Ae.command:void 0,on_revise_automation:e.on_revise_automation?Ae.revise:void 0,detail_loading:D.loading.has(Q.run_id),brief_loading:W.loading.has(Q.run_id),outcome_loading:K.loading.has(Q.run_id),automation_loading:Q.automation_id?u.loading.has(Q.automation_id):!1});return s.jsxs("div",{className:"page page_scroll mc_page",children:[g?s.jsx("div",{className:"mc_error",children:g}):null,s.jsxs("div",{className:!z&&!ne.length?AU:EU,"aria-busy":z||void 0,children:[s.jsxs("div",{className:"mc_entities_head",children:[s.jsxs("span",{children:["Entities",!z&&e.entities_total>ne.length?` (${ne.length} of ${e.entities_total} — open the entity app for all)`:"",!z&&!ne.length?s.jsx("span",{className:"muted mc_entities_none",children:" — no entities"}):null]}),s.jsx("a",{className:"mc_entity_link",href:e.entity_app_href,target:"_blank",rel:"noreferrer",children:"open the entity app →"})]}),e.entities_error?s.jsx("div",{className:"muted",children:e.entities_error}):null,z?s.jsxs("div",{className:"mc_entities_row",role:"status","aria-label":"loading entities",children:[s.jsx(rl,{what:"entities"}),s.jsx(MU,{n:e.entities_total?Math.min(e.entities_total,_C):TU})]}):null,ne.length?s.jsx("div",{className:"mc_entities_row",children:ne.map(Q=>s.jsxs("div",{className:"mc_entity_cell",children:[s.jsxs("a",{className:"mc_entity",href:`${e.entity_app_href}${e.entity_app_href.includes("?")?"&":"?"}entity=${encodeURIComponent(Q.name)}&live=1`,target:"_blank",rel:"noreferrer",title:[Q.error,Q.age_days!==null?`${Q.age_days.toFixed(0)} days old`:"",Q.last_moment].filter(Boolean).join(" — ")||Q.name,children:[s.jsx("span",{className:"mc_entity_name",children:Q.name}),(()=>{var _t;const _e=String(Q.live_phase||Q.state||"").trim(),le=kU(_e,e.phase_graph),Se=NU(e.phase_graph).has(le)?le:"other",pe=((_t=e.phase_graph)==null?void 0:_t.initial)??"sleep",dt=/awake|idle/i.test(_e)&&le===pe,yt=_e&&_e.toLowerCase()!==le?` — wire word: ${_e}${dt?" (settling)":""}`:"";return s.jsx("span",{className:`mc_entity_phase mc_phase_${Se}`,title:(Q.live_phase?"phase (cognition wire)":"phase from card state — cognition wire unavailable")+yt,children:le})})(),Q.last_moment?s.jsx("span",{className:"mc_entity_moment",title:Q.last_moment,children:Q.last_moment.replace(/_/g," ")}):null,(()=>{if(Q.working===!0)return s.jsx("span",{className:"mc_entity_live",title:"busy now (loop mid-day or live visit — store-read, never fabricated)",children:"● busy"});const _e=gU(Q.last_moment_at,t);return Q.working===!1?s.jsxs("span",{className:"mc_entity_live muted",title:"idle (cognition wire)",children:["idle",_e!==null?` · ${yw(t-_e,t)} ago`:""]}):_e===null?null:_e<=yU?s.jsx("span",{className:"mc_entity_live",title:`last moment ${yw(t-_e,t)} ago`,children:"● active"}):s.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[yw(t-_e,t)," ago"]})})(),Q.tokens_total!==null?s.jsxs("span",{className:"muted mc_entity_spend",title:`lifetime billed tokens (home run ledger)${Q.live_visit_tokens!==null?`; open visit: ${ac(Q.live_visit_tokens)} tk`:""}${Q.spend_warning?`; ${Q.spend_warning}`:""}`,children:[ac(Q.tokens_total)," tk",Q.live_visit_tokens!==null?` (+${ac(Q.live_visit_tokens)})`:"",Q.spend_warning?"*":""]}):null]}),Q.open_questions_total||Q.open_problems_total||Q.lessons_total||Q.dreams_brief?s.jsx("button",{type:"button",className:"mc_entity_hints_btn","aria-expanded":V===Q.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>J(V===Q.name?"":Q.name),children:[Q.open_questions_total?`${Q.open_questions_total} question${Q.open_questions_total>1?"s":""}`:"",Q.open_problems_total?`${Q.open_problems_total} problem${Q.open_problems_total>1?"s":""}`:"",Q.lessons_total?`${Q.lessons_total} lesson${Q.lessons_total>1?"s":""}`:"",Q.dreams_brief?`night: ${Q.dreams_brief.count} signal${Q.dreams_brief.count>1?"s":""}`:""].filter(Boolean).join(" · ")}):null]},Q.name))}):null,(()=>{if(!V)return null;const Q=ne.find(Se=>Se.name===V);if(!Q||!Q.open_questions.length&&!Q.open_problems.length&&!Q.lessons.length&&!Q.dreams_brief)return null;const _e=e.on_read_diary?async Se=>{const pe=await e.on_read_diary(Q.name,Se);te({entity:Q.name,entry:(pe==null?void 0:pe.entry)??pe,seq:typeof(pe==null?void 0:pe.read_recorded_at_seq)=="number"?pe.read_recorded_at_seq:null})}:void 0,le=Q.open_questions_total-Q.open_questions.length+(Q.open_problems_total-Q.open_problems.length)+(Q.lessons_total-Q.lessons.length);return s.jsxs("div",{className:"mc_entity_hints_panel",children:[Q.open_questions.map((Se,pe)=>s.jsx(yy,{kind:"question",label:Se.title||ww(Se.statement),entryId:Se.entry_id,onOpen:_e,title:Se.statement||Se.title},`q_${Se.record_id||pe}`)),Q.open_problems.map((Se,pe)=>s.jsx(yy,{kind:"problem",label:Se.title||ww(Se.statement),entryId:Se.entry_id,onOpen:_e,title:Se.statement||Se.title},`p_${Se.record_id||pe}`)),Q.lessons.map((Se,pe)=>s.jsx(yy,{kind:"lesson",label:Se.title||ww(Se.statement),entryId:Se.entry_id,onOpen:_e,title:Se.statement||Se.title},`l_${Se.record_id||pe}`)),Q.dreams_brief?s.jsxs("span",{className:"mc_entity_dreams muted",title:"night signals carried by STANDING dreams (the sleep pass's maintenance stream; count = signals, not dreams); felt tones color the content, they never rank it — the entity app renders the full stream",children:["night signals: ",Q.dreams_brief.count,Q.dreams_brief.dreams?` across ${Q.dreams_brief.dreams} dream${Q.dreams_brief.dreams>1?"s":""}`:"",Q.dreams_brief.kinds.length?` — ${Q.dreams_brief.kinds.slice(0,6).join(", ")}${Q.dreams_brief.kinds.length>6?` +${Q.dreams_brief.kinds.length-6} more`:""}`:"",Q.dreams_brief.felt_tones.length?` · felt: ${Q.dreams_brief.felt_tones.slice(0,6).join(", ")}`:""]}):null,le>0?s.jsxs("span",{className:"muted mc_entity_hints_more",children:["+",le," more — open the entity app"]}):null]})})()]}),U?s.jsx(ec,{open:!0,title:`${U.entity} — diary entry`,onClose:()=>te(null),children:s.jsxs("div",{className:"mc_diary_entry",children:[s.jsx("div",{className:"mc_diary_meta muted",children:[(ct=U.entry)!=null&&ct.kind?`kind: ${U.entry.kind}`:"",(Qe=U.entry)!=null&&Qe.visibility?`visibility: ${U.entry.visibility}`:"",(Dt=U.entry)!=null&&Dt.written_at?`written: ${U.entry.written_at}`:"",($e=U.entry)!=null&&$e.entry_id?`id: ${U.entry.entry_id}`:""].filter(Boolean).join(" · ")}),s.jsxs("div",{className:"mc_diary_recorded muted",children:["this read was recorded in ",U.entity,"’s stream",U.seq!==null?` (seq ${U.seq})`:""]}),(Le=U.entry)!=null&&Le.gist?s.jsx("div",{className:"mc_diary_gist",children:String(U.entry.gist)}):null,s.jsx("pre",{className:"mc_diary_text",children:String(((ce=U.entry)==null?void 0:ce.text)||"(entry carries no text)")})]})}):null,!e.gateway_connected||e.runs_refreshed_at===null||e.runs_stale||e.notice?s.jsxs("div",{className:"mc_status_line",children:[e.gateway_connected?e.runs_refreshed_at===null?s.jsx("span",{className:"mc_notice mc_loading",role:"status",children:"loading runs…"}):e.runs_stale?s.jsxs("span",{className:"mc_notice mc_loading",role:"status",children:["board as of ",G9(e.runs_refreshed_at)," — refreshing…"]}):null:s.jsx("span",{className:"mc_notice is_bad",role:"status",children:"gateway unreachable: the lanes show the last runs read"}),e.gateway_connected&&e.notice?s.jsx("span",{className:"mc_notice is_bad",role:"status",children:e.notice}):null]}):null,s.jsx("div",{className:"mc_board",children:wp.map(Q=>{const _e=Q==="done"?O.visible:A[Q],le=Q==="done"&&!b?_e.slice(0,xw):_e,Se=e.runs_refreshed_at===null||Q==="done"&&e.done_loaded===!1;return s.jsxs(FU,{col:Q,title:oC[Q],count:Se?null:_e.length,count_title:Q==="done"&&O.hidden_count?`${O.hidden_count} older run(s) outside this window`:Q==="needs_you"&&_e.length?`${_e.length} task${_e.length===1?"":"s"} · ${_e.reduce((pe,dt)=>pe+(dt.asks.length||(dt.line.lane==="needs_you"&&!dt.stuck?1:0)),0)} asks`:void 0,cancel:{run_ids:_e.map(pe=>pe.run_id),targets:gj(_e.map(pe=>pe.run_id),i.active),on_cancel_run:e.on_cancel_run,on_cancel_runs:e.on_cancel_runs},after:Q==="working"?s.jsxs("label",{className:"mc_stall_control",title:"No progress after: a running card whose last ledger step is older than this gets the mark ⚠ and floats to the top of Working",children:[s.jsxs("span",{className:"mc_stall_word","aria-hidden":"true",children:[s.jsx("span",{className:"mc_stall_mark",children:"⚠"})," after"]}),s.jsx("select",{className:"mc_window_select mc_stall_select","aria-label":"no progress after",value:String(n),onChange:pe=>{const dt=Number(pe.target.value);r(dt);try{localStorage.setItem(aC,String(dt))}catch{}},children:Ox.map(pe=>s.jsx("option",{value:String(pe.ms),children:pe.label},pe.ms))})]}):null,tools:Q==="done"?s.jsx("select",{className:"mc_window_select",value:x,title:"Show terminal runs from this time window",onClick:pe=>pe.stopPropagation(),onChange:pe=>{const dt=pe.target.value;N(dt),k(!1);try{localStorage.setItem("abstractobserver_done_window_v1",dt)}catch{}},children:Object.keys(Lv).map(pe=>s.jsx("option",{value:pe,children:pw[pe]},pe))}):null,children:[s.jsx("div",{className:"mc_column_hint muted",children:U9[Q]}),s.jsxs("div",{className:"mc_column_cards",ref:h[Q],"aria-busy":Se||void 0,children:[Se&&!le.length?s.jsxs(s.Fragment,{children:[s.jsx(rl,{what:Q==="done"&&e.runs_refreshed_at!==null?"finished runs":"runs"}),s.jsx(CU,{n:$U[Q]})]}):null,le.map(pe=>s.jsx(wW,{card:pe,...rt(pe)},pe.run_id)),!_e.length&&!Se?s.jsx("div",{className:"mc_empty muted",children:Q==="done"&&O.hidden_count?`none in the ${pw[x]} — ${O.hidden_count} older`:W9[Q]}):null,Q==="done"&&_e.length>xw&&!b?s.jsxs("button",{className:"btn mc_more",onClick:()=>k(!0),children:["show all ",_e.length]}):null,Q==="done"&&O.hidden_count&&_e.length?s.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",O.hidden_count," older outside ",pw[x]]}):null]})]},Q)})})]})}function Ct(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ln(e){return typeof e=="string"?e.trim():""}function Vn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function zp(e){return typeof e=="boolean"?e:null}function Qr(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():String(t??"").trim()).filter(Boolean):null}function kj(e){return typeof e=="string"?e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean):Qr(e)}function hu(e,t){return!!e&&Object.prototype.hasOwnProperty.call(e,t)}function is(e){return Math.round(e).toLocaleString("en-US")}function jC(e){const t=Ct(e);return!!t&&(hu(t,"definition")||hu(t,"summary"))}function xW(e,t,n){var x,N,$,E;const r=Ct((x=Ct(t))==null?void 0:x.input_data),i=Ct((N=Ct(t))==null?void 0:N.workspace),o=jC(n)?n:null,u=o?Am(o):n??null,l=Ct(o==null?void 0:o.definition),d=Ct(($=Ct(l==null?void 0:l.target))==null?void 0:$.input_data),h=Ct(d==null?void 0:d._runtime),m=Ct(l==null?void 0:l.policy),_={},g=(S,...P)=>{for(const[D,R]of P){const I=ln(R);if(I)return _[S]=D,I}return _[S]="",""},y=(S,P,...D)=>{for(const[R,I]of D){const W=P(I);if(W!==null)return _[S]=R,W}return _[S]="",[]},b=(S,...P)=>{for(const[D,R]of P){const I=Vn(R);if(I!==null)return _[S]=D,I}return _[S]="",null},k=S=>S&&S.length?S:null;return{model:g("model",["run",r==null?void 0:r.model],["automation",d==null?void 0:d.model],["automation",u==null?void 0:u.model]),provider:g("provider",["run",r==null?void 0:r.provider],["automation",d==null?void 0:d.provider],["automation",u==null?void 0:u.provider]),tools:y("tools",Qr,["run",r==null?void 0:r.tools],["automation",d==null?void 0:d.tools],["automation",k(u==null?void 0:u.tools)]),tool_approval:g("tool_approval",["automation",m==null?void 0:m.tool_approval],["automation",u==null?void 0:u.tool_approval]),workspace_access_mode:g("workspace_access_mode",["run",i==null?void 0:i.workspace_access_mode],["run",r==null?void 0:r.workspace_access_mode],["automation",d==null?void 0:d.workspace_access_mode]),workspace_root:g("workspace_root",["run",(E=Ct(e))==null?void 0:E.workspace_root],["run",i==null?void 0:i.workspace_root],["run",r==null?void 0:r.workspace_root],["automation",u==null?void 0:u.workspace_root],["automation",d==null?void 0:d.workspace_root]),workspace_allowed_paths:y("workspace_allowed_paths",kj,["run",i==null?void 0:i.workspace_allowed_paths],["automation",d==null?void 0:d.workspace_allowed_paths]),workspace_ignored_paths:y("workspace_ignored_paths",kj,["run",i==null?void 0:i.workspace_ignored_paths],["automation",d==null?void 0:d.workspace_ignored_paths]),allowed_tools:y("allowed_tools",Qr,["automation",h==null?void 0:h.allowed_tools]),max_iterations:b("max_iterations",["run",r==null?void 0:r.max_iterations],["automation",d==null?void 0:d.max_iterations],["automation",u==null?void 0:u.max_iterations]),untrusted_input_tools:y("untrusted_input_tools",Qr,["automation",m==null?void 0:m.untrusted_input_tools]),email_allowed_recipients:y("email_allowed_recipients",Qr,["automation",m==null?void 0:m.email_allowed_recipients]),source:_}}function SC(e){const t=Ct(e);if(!t)return null;if(Array.isArray(t.nodes))return t;const n=Ct(t.flow);return n&&Array.isArray(n.nodes)?n:null}function Pv(e){const t=Ct(e==null?void 0:e.data)||{};return ln(t.nodeType)||ln(e==null?void 0:e.type)}const bW=new Set(["exec-out","exec-in","exec"]);function Dv(e,t){const n=Ct(e==null?void 0:e.data)||{};return(Array.isArray(n[t])&&n[t].length?n[t]:Array.isArray(e==null?void 0:e[t])?e[t]:[]).filter(i=>{const o=Ct(i);if(!o)return!1;const u=ln(o.id);return!!u&&ln(o.type)!=="execution"&&!bW.has(u)})}function jj(e,t,n,r){const i=ln(e.id),o=ln(e.type)||"any";return{id:i,label:ln(e.label)||i,type:o,typed:!0,required:e.required===!0,description:ln(e.description),state:t,value:n,flow_default:r}}function Sj(e,t,n){return{id:e,label:e,type:"any",typed:!1,required:!1,description:"",state:t,value:n,flow_default:null}}function kW(e,t,n){var R;const r=SC(e),i=r?r.nodes:[],o=i.find(I=>Pv(I)==="on_flow_start")||null,u=i.filter(I=>Pv(I)==="on_flow_end"),l=Ct(t),d=Ct(l==null?void 0:l.input_data),h=Ct((R=Ct(o==null?void 0:o.data))==null?void 0:R.pinDefaults)||{},m=[],_=new Set,g=I=>d?hu(d,I)?{state:"value",value:d[I]}:{state:"not_provided",value:void 0}:{state:"unknown",value:void 0};for(const I of o?Dv(o,"outputs"):[]){const W=ln(I.id);if(_.has(W))continue;_.add(W);const{state:G,value:K}=g(W),H=G==="not_provided"&&hu(h,W)?{value:h[W]}:null;m.push(jj(I,G,K,H))}for(const I of Array.isArray(l==null?void 0:l.pin_ids)?l.pin_ids:[]){const W=ln(I);if(!W||_.has(W))continue;_.add(W);const{state:G,value:K}=g(W);m.push(Sj(W,G,K))}const y=d?Object.keys(d).filter(I=>!_.has(I)).map(I=>[I,d[I]]):[],b=Ct(n),k=!!b&&ds(b.status),x=b?b.output:void 0,N=Ct(x),$=I=>b?N&&hu(N,I)?{state:"value",value:N[I]}:{state:"absent",value:void 0}:{state:"unknown",value:void 0},E=[],S=new Set;for(const I of u)for(const W of Dv(I,"inputs")){const G=ln(W.id);if(S.has(G))continue;S.add(G);const{state:K,value:H}=$(G);E.push(jj(W,K,H,null))}const P=u.length>0&&S.size===0;let D=[];if(P){const I=!!b&&x!==null&&x!==void 0;E.push(Sj("output",b?I?"value":"absent":"unknown",I?x:void 0))}else N?D=Object.keys(N).filter(I=>!S.has(I)).map(I=>[I,N[I]]):b&&x!==null&&x!==void 0&&(D=[["output",x]]);return{inputs:m,outputs:E,also_sent:y,also_returned:D,end_is_passthrough:P,flow_found:!!r,start_found:!!o,end_found:u.length>0,outputs_final:k}}function bw(e,t,n=`${t}s`){return e===1?t:n}function jW(e){const t=[],n=e.dropped_counts_complete!==!1;if(e.replayed_messages!==null){const r=e.dropped_messages!==null&&n?e.replayed_messages+e.dropped_messages:null;let i=r!==null?`replayed ${is(e.replayed_messages)} of ${is(r)} ${bw(r,"message")}`:`replayed ${is(e.replayed_messages)} ${bw(e.replayed_messages,"message")}`;e.replayed_tokens!==null?i+=` (${is(e.replayed_tokens)}${e.max_tokens!==null?` of ${is(e.max_tokens)}`:""} tokens)`:e.max_tokens!==null&&(i+=` (budget ${is(e.max_tokens)} tokens)`),t.push(i)}else e.max_tokens!==null&&t.push(`history budget ${is(e.max_tokens)} tokens`);if(e.dropped_messages!==null)if(e.dropped_messages>0){const r=e.dropped_tokens!==null&&e.dropped_tokens>0?` (${is(e.dropped_tokens)} tokens)`:"";t.push(`${n?"":"at least "}${is(e.dropped_messages)} older ${bw(e.dropped_messages,"message")} left out${r}`)}else t.push(n?"nothing left out":"left-out count incomplete");else e.dropped_counts_complete===!1&&t.push("left-out count incomplete");return e.oversize_turn_kept===!0&&t.push("the newest turn alone exceeds the budget and was kept whole"),t.join("; ")}function Fv(e){var l;const t=Ct(e),n=Ct(t==null?void 0:t.session_history),r=Ct((l=Ct(t==null?void 0:t.limits))==null?void 0:l.tokens);let i=null;if(r){const d=Vn(r.estimated_used),h=Vn(r.max_tokens),m=Vn(r.max_input_tokens),_=m??h,g=Vn(r.pct),y=g!==null?g*100:d!==null&&_!==null&&_>0?d/_*100:null,b=Vn(r.warn_tokens_pct);i={used:d,max_tokens:h,max_input_tokens:m,budget:_,pct:y,warn_pct:b,over_warn:y!==null&&b!==null&&y>=b}}const o=(Qr(t==null?void 0:t.flow_warnings)||[]).filter(Boolean),u={replayed_messages:Vn(n==null?void 0:n.replayed_messages),replayed_tokens:Vn(n==null?void 0:n.replayed_tokens),max_tokens:Vn(n==null?void 0:n.max_tokens),dropped_messages:Vn(n==null?void 0:n.dropped_messages),dropped_tokens:Vn(n==null?void 0:n.dropped_tokens),dropped_counts_complete:zp(n==null?void 0:n.dropped_counts_complete),oversize_turn_kept:zp(n==null?void 0:n.oversize_turn_kept)};return{has_history:!!n,policy:ln(n==null?void 0:n.policy),...u,strict:zp(n==null?void 0:n.strict),token_estimator:ln(n==null?void 0:n.token_estimator),session_kind:ln(n==null?void 0:n.session_kind),tokens:i,flow_warnings:o,window_note:n?jW(u):""}}const SW=16;function ki(e){return String((e==null?void 0:e.run_id)||"").trim()}function zv(e){return String((e==null?void 0:e.role)||"").trim()}function Nj(e){return Ht(e.created_at||e.updated_at||"")??0}function NW(e,t){const n=String(e||"").trim();let r=t.get(n);if(!r)return n;const i=new Set;for(;r;){const o=ki(r);if(i.add(o),zv(r)==="occurrence")return o;const u=String(r.parent_run_id||"").trim(),l=u?t.get(u):void 0;if(!l||i.has(u)||zv(l)==="controller")return o;r=l}return n}function NC(e,t){const n=String(e||"").trim(),r=new Map,i=new Map;for(const y of t||[]){const b=ki(y);b&&r.set(b,y)}for(const y of r.values()){const b=String(y.parent_run_id||"").trim();if(!b||b===ki(y))continue;const k=i.get(b)||[];k.push(y),i.set(b,k)}if(!r.has(n))return{subject_id:n,root:null,controller:null,controller_id:"",subject_found:!1,size:0};const o=NW(n,r),u=r.get(o);let l=0;const d=new Set,h=(y,b)=>{const k=ki(y);d.add(k),l+=1;const x=b<SW?[...i.get(k)||[]].filter(N=>!d.has(ki(N))):[];return x.sort((N,$)=>Nj(N)-Nj($)||ki(N).localeCompare(ki($))),{run:y,depth:b,is_subject:k===n,children:x.map(N=>h(N,b+1))}},m=h(u,0);let _=null,g="";return zv(u)==="occurrence"&&(g=String(u.parent_run_id||u.automation_id||"").trim(),_=g&&r.get(g)||null),{subject_id:n,root:m,controller:_,controller_id:g,subject_found:!0,size:l}}function $C(e){const t=[],n=r=>{t.push(r);for(const i of r.children)n(i)};return e&&n(e),t}function $W(e,t,n=Date.now()){const r=e&&"children"in e?e:(e==null?void 0:e.root)??null,i=new Map;for(const u of t||[]){const l=ki(u);l&&i.set(l,u)}const o=$C(r).map(u=>{const l=ki(u.run),d=i.get(l)??u.run,h=Vn(d==null?void 0:d.tokens_total),m=Vn(d==null?void 0:d.llm_calls),_=Vn(d==null?void 0:d.tool_calls),g=Vn(d==null?void 0:d.steps),y=Cm(u.run,n),b=String(u.run.status||"").trim().toLowerCase();return{run_id:l,depth:u.depth,workflow_id:String(u.run.workflow_id||"").trim(),status:b,is_subject:u.is_subject,duration_ms:y>=0?y:null,running:!ds(b),tokens_total:h,llm_calls:m,tool_calls:_,steps:g,has_metrics:h!==null||m!==null||_!==null||g!==null,inclusive:!0}});return{rows:o,inclusive:!0,any_metrics:o.some(u=>u.has_metrics)}}function gn(e,t){return{value:e,source:t,why:""}}function es(e,t=""){return{value:null,source:t,why:e}}const Is={wire:"not on this wire",no_default:"not provided, no default",not_automation:"not an automation run",automation_not_loaded:"automation definition not loaded",ledger_not_loaded:"ledger not loaded here",ledger_no_records:"no ledger records for this run in what is loaded",not_ended:"the run has not ended",flow_not_loaded:"flow not loaded",gateway_default:"gateway default (not reported on this wire)"};function Ad(e){return`${new Date(e).toISOString().slice(0,19).replace("T"," ")} UTC`}function CW(e){var r,i,o,u;const t=Sm(e),n=Ct((o=Ct((i=Ct((r=e.record)==null?void 0:r.result))==null?void 0:i.metadata))==null?void 0:o._provider_request);return{provider:t.provider||ln(n==null?void 0:n.provider),model:t.model||ln(n==null?void 0:n.model)||ln((u=Ct(n==null?void 0:n.payload))==null?void 0:u.model)}}function EW(e){var u,l,d,h,m;const t=Ct((l=Ct((u=e.started)==null?void 0:u.effect))==null?void 0:l.payload),n=Ct((h=Ct((d=e.record)==null?void 0:d.effect))==null?void 0:h.payload),r=Ct(t==null?void 0:t.vars)&&!((m=Ct(t==null?void 0:t.vars))!=null&&m.$slim)?Ct(t==null?void 0:t.vars):Ct(n==null?void 0:n.vars),i=Ct(r==null?void 0:r._runtime),o=Ct(r==null?void 0:r._limits);return{run_id:$m(e.record),workflow_id:ln(t==null?void 0:t.workflow_id)||ln(n==null?void 0:n.workflow_id),from_run_id:e.run_id,provider:ln(i==null?void 0:i.provider),model:ln(i==null?void 0:i.model),allowed_tools:Qr(i==null?void 0:i.allowed_tools),max_iterations:Vn(o==null?void 0:o.max_iterations)}}function AW(e,t,n=[]){var _,g,y,b,k,x,N;const r={loaded:Array.isArray(e),subject_found:!1,runs:[],missing_run_ids:[],llm_calls:0,tool_calls:0,tool_failures:0,models:[],tools:[],subruns:[],allowlist:null,first_ms:null,last_ms:null};if(!Array.isArray(e))return r;const i=String(t||"").trim(),o=new Set;for(const $ of e){const E=String(($==null?void 0:$.run_id)||((_=$==null?void 0:$.record)==null?void 0:_.run_id)||"").trim();E&&($!=null&&$.record)&&o.add(E)}const u=new Map,l=new Map,d=[i,...n.map($=>String($||"").trim()).filter(Boolean)],h=new Set,m=[];for(;d.length;){const $=d.shift();if(!$||h.has($))continue;if(h.add($),!o.has($)){$!==i&&m.push($);continue}$===i&&(r.subject_found=!0);const E={run_id:$,llm_calls:0,tool_calls:0,tool_failures:0,steps:0};for(const S of Mg(e,$)){E.steps+=1;const P=Ht(S.started_at),D=Ht(S.ended_at);for(const R of[P,D])R!==null&&((r.first_ms===null||R<r.first_ms)&&(r.first_ms=R),(r.last_ms===null||R>r.last_ms)&&(r.last_ms=R));if(S.kind==="llm_call"){E.llm_calls+=1;const R=CW(S),I=`${R.provider}\0${R.model}`,W=u.get(I)||{provider:R.provider,model:R.model,calls:0,run_ids:[]};W.calls+=1,W.run_ids.includes($)||W.run_ids.push($),u.set(I,W)}else if(S.kind==="tool"){const R=Nm(S),I=new Map;for(const G of R.calls){const K=I.get(G.name)||{calls:0,results:0,failures:0};K.calls+=1,I.set(G.name,K)}for(const G of R.results){const K=I.get(G.name)||{calls:0,results:0,failures:0};K.results+=1,G.success===!1&&(K.failures+=1),I.set(G.name,K)}for(const[G,K]of I){const H=Math.max(K.calls,K.results);E.tool_calls+=H,E.tool_failures+=K.failures;const M=l.get(G)||{name:G,calls:0,failures:0,run_ids:[],outside_declared:null};M.calls+=H,M.failures+=K.failures,M.run_ids.includes($)||M.run_ids.push($),l.set(G,M)}const W=Qr((b=Ct((y=(g=S.started)==null?void 0:g.effect)==null?void 0:y.payload))==null?void 0:b.allowed_tools)??Qr((N=Ct((x=(k=S.record)==null?void 0:k.effect)==null?void 0:x.payload))==null?void 0:N.allowed_tools);W!==null&&r.allowlist===null&&(r.allowlist=W)}else if(S.kind==="subflow"){const R=EW(S);r.subruns.push(R),R.run_id&&d.push(R.run_id)}}r.llm_calls+=E.llm_calls,r.tool_calls+=E.tool_calls,r.tool_failures+=E.tool_failures,r.runs.push(E)}return r.missing_run_ids=m,r.models=[...u.values()].sort(($,E)=>E.calls-$.calls||$.model.localeCompare(E.model)),r.tools=[...l.values()].sort(($,E)=>E.calls-$.calls||$.name.localeCompare(E.name)),r}function bp(e,t){for(const[n,r]of e)if(r!=null)return gn(r,n);return es(t)}function Nd(e){const t=ln(e);return t||null}function eu(e,t){const n=ln(e),r=ln(t);return n||r?{provider:n,model:r,calls:null}:null}const TW=new Set(["controller","occurrence","descendant","discussion"]);function MW(e,t,n,r,i,o,u=Date.now(),l={}){var hn,sn,Vt,rs,Be,Zt,Tt,Dn,fn;const d=Ct(e),h=Ct(t),m=Ct(h==null?void 0:h.input_data),_=String(l.subject_run_id||(d==null?void 0:d.run_id)||(h==null?void 0:h.run_id)||((hn=l.row)==null?void 0:hn.run_id)||"").trim(),g=Array.isArray(o)?o:[],y=Xe=>g.find(nn=>String((nn==null?void 0:nn.run_id)||"").trim()===Xe),b={...y(_)||{},...l.row||{}};for(const Xe of["workflow_id","status","created_at","updated_at","role","occurrence_index","automation_id","parent_run_id","session_id","session_kind"])d&&d[Xe]!==void 0&&d[Xe]!==null&&d[Xe]!==""&&(b[Xe]=d[Xe]);const k=jC(r)?r:null,x=k?Am(k):r??null,N=Ct(k==null?void 0:k.definition),$=Ct(k==null?void 0:k.summary),E=Ct((sn=Ct(N==null?void 0:N.target))==null?void 0:sn.input_data),S=Ct(E==null?void 0:E._runtime),P=Ct(N==null?void 0:N.policy),D=ln(b.role),R=!!ln(b.automation_id)||TW.has(D)||ln(b.session_kind)==="automation",I=R?x?Is.wire:Is.automation_not_loaded:Is.not_automation,W=SC(n),G=W&&W.nodes.find(Xe=>Pv(Xe)==="on_flow_start")||null,K=Ct((Vt=Ct(G==null?void 0:G.data))==null?void 0:Vt.pinDefaults),H=new Set(G?Dv(G,"outputs").map(Xe=>ln(Xe.id)):[]),M=Xe=>m&&hu(m,Xe)?void 0:K&&hu(K,Xe)?K[Xe]:void 0,A=NC(_,g),O=$C(A.root).filter(Xe=>ki(Xe.run)!==_&&RW(Xe,_,A.root)).map(Xe=>ki(Xe.run)),L=AW(i,_,O),V=L.loaded?Is.ledger_no_records:Is.ledger_not_loaded,J=L.loaded&&L.subject_found,U=xW(e,t,k??x),te=Xe=>U.source[Xe]==="run"?"run":U.source[Xe]==="automation"?"automation":"",z=Ct(d==null?void 0:d.output),ne=Ct(z==null?void 0:z.meta),se=ln(b.workflow_id)||ln(h==null?void 0:h.workflow_id),de=ln(h==null?void 0:h.bundle_version)||(se.includes("@")?se.split("@")[1].split(":")[0]:""),be=se?gn({id:se,name:ti(se),version:de,flow_name:ln(W==null?void 0:W.name)},"run"):es(Is.wire),Me=R?x?gn({kind:"automation",title:x.title,id:x.automation_id},"automation"):es(Is.automation_not_loaded):ln(b.session_id)?gn({kind:"session",title:"",id:ln(b.session_id)},"run"):gn({kind:"run",title:"",id:_},"run"),je=ln(b.parent_run_id),ae=je?y(je):void 0,xe=Vn(b.occurrence_index);let Ae="";if(D==="occurrence")Ae=xe!==null?`run #${xe}`:"automation run";else if(D==="controller")Ae="automation controller (the schedule's own run)";else if(D==="discussion")Ae="discussion of the automation";else if(je){const Xe=ln(ae==null?void 0:ae.role),nn=Vn(ae==null?void 0:ae.occurrence_index);Ae=`subrun of ${Xe==="occurrence"&&nn!==null?`run #${nn}`:ti(ln(ae==null?void 0:ae.workflow_id))||"a parent run (row not loaded)"}`}else Ae=ln(b.session_id)?"run in a session":"top-level run";const He=gn({text:Ae,parent_run_id:je},"run"),nt=[["run",eu(m==null?void 0:m.provider,m==null?void 0:m.model)],["flow default",eu(M("provider"),M("model"))],["automation",eu(E==null?void 0:E.provider,E==null?void 0:E.model)],["automation",eu(S==null?void 0:S.provider,S==null?void 0:S.model)],["automation",k?null:eu(x==null?void 0:x.provider,x==null?void 0:x.model)]].find(([,Xe])=>Xe!==null)||null;let rt;J&&L.models.length?rt=gn(L.models.map(Xe=>({provider:Xe.provider,model:Xe.model,calls:Xe.calls})),"used"):eu(ne==null?void 0:ne.provider,ne==null?void 0:ne.model)?rt=gn([eu(ne==null?void 0:ne.provider,ne==null?void 0:ne.model)],"output"):nt?rt=gn([nt[1]],nt[0]):rt=es(Is.gateway_default,"gateway");let ze=null;if((rt.source==="used"||rt.source==="output")&&nt&&rt.value){const Xe=nt[1];rt.value.some(cn=>(!Xe.provider||cn.provider===Xe.provider)&&(!Xe.model||cn.model===Xe.model))||(ze=gn(Xe,nt[0]))}const Ve=m&&typeof m.system=="string"?gn(m.system,"run"):W?Nd(M("system"))!==null?gn(String(M("system")),"flow default"):H.has("system")?es("none declared: not provided and the flow has no default","flow"):es("the flow has no system pin","flow"):es(Is.flow_not_loaded),ct=bp([["run",m&&typeof m.prompt=="string"&&m.prompt.trim()?m.prompt:null],["run",Nd((rs=Ct(m==null?void 0:m.context))==null?void 0:rs.task)],["flow default",Nd(M("prompt"))],["automation",Nd(E==null?void 0:E.prompt)],["automation",k?null:Nd(x==null?void 0:x.task)]],Is.no_default),Qe=bp([["run",Qr(m==null?void 0:m.tools)],["flow default",Qr(M("tools"))],["automation",Qr(E==null?void 0:E.tools)],["automation",Qr(S==null?void 0:S.allowed_tools)],["automation",k?null:(Be=x==null?void 0:x.tools)!=null&&Be.length?x.tools:null]],Is.no_default),Dt=((Zt=L.subruns.find(Xe=>Xe.allowed_tools!==null))==null?void 0:Zt.allowed_tools)??null,$e=bp([["used",J?L.allowlist:null],["used",J?Dt:null],["automation",Qr(S==null?void 0:S.allowed_tools)],["automation",k?null:(x==null?void 0:x.allowed_tools)??null]],R?I:J?"the ledger shows no enforced allowlist":V),Le=Qe.value,ce=J?gn(L.tools.map(Xe=>({...Xe,outside_declared:Le===null?null:!Le.includes(Xe.name)})),"used"):es(V),Q=(Xe,nn)=>Xe!==null&&U.source[nn]?gn(Xe,te(nn)):es(I),_e=Q(Nd(U.tool_approval),"tool_approval"),le=Q(U.source.untrusted_input_tools?U.untrusted_input_tools:null,"untrusted_input_tools"),Se=Q(U.source.email_allowed_recipients?U.email_allowed_recipients:null,"email_allowed_recipients"),pe=(Xe,nn)=>U.source[nn]?gn(Xe,te(nn)):es(Is.wire),dt={mode:pe(U.workspace_access_mode,"workspace_access_mode"),root:pe(U.workspace_root,"workspace_root"),allowed_paths:pe(U.workspace_allowed_paths,"workspace_allowed_paths"),ignored_paths:pe(U.workspace_ignored_paths,"workspace_ignored_paths")},yt=y(_)||b,_t=J?gn(L.llm_calls,"used"):Vn(yt==null?void 0:yt.llm_calls)!==null?gn(Vn(yt.llm_calls),"listing"):es(V),It=J?gn({calls:L.tool_calls,failures:L.tool_failures},"used"):Vn(yt==null?void 0:yt.tool_calls)!==null?gn({calls:Vn(yt.tool_calls),failures:null},"listing"):es(V),bt=A.root?((Tt=gg(A.root,_))==null?void 0:Tt.children)||[]:[],St=J?gn(L.subruns,"used"):bt.length?gn(bt.map(Xe=>({run_id:ki(Xe.run),workflow_id:ln(Xe.run.workflow_id),from_run_id:_,provider:"",model:"",allowed_tools:null,max_iterations:null})),"listing"):es(L.loaded?Is.ledger_no_records:"none among the loaded rows; ledger not loaded here"),ut=[];if(z)for(const[Xe,nn]of Object.entries(z)){const cn=Ct(nn);cn&&Object.keys(cn).length===1&&typeof cn.$artifact=="string"&&cn.$artifact.trim()&&ut.push({pin:Xe,id:cn.$artifact.trim()})}const Ot=ds(b.status);let Mt;d?Ot?z&&typeof z.response=="string"&&z.response.trim()?Mt=gn(z.response,"output"):typeof d.output=="string"&&d.output.trim()?Mt=gn(d.output,"output"):ln(d.error)?Mt=gn(ln(d.error),"run"):Mt=es("the output carries no response text"):Mt=es(Is.not_ended):Mt=es("run detail not loaded");const mn=Ht(b.created_at||""),yn=Ot?Ht(b.updated_at||""):null,In=Cm(b,u),Gs=In>=0?gn(In,"run"):L.first_ms!==null&&L.last_ms!==null?gn(L.last_ms-L.first_ms,"used"):es(Is.wire),ss=J?((Dn=L.subruns.find(Xe=>Xe.max_iterations!==null))==null?void 0:Dn.max_iterations)??null:null,ge=bp([["used",ss],["run",Vn(m==null?void 0:m.max_iterations)],["flow default",Vn(M("max_iterations"))],["automation",Vn(E==null?void 0:E.max_iterations)],["automation",k?null:(x==null?void 0:x.max_iterations)??null]],Is.no_default),Re=Vn(ne==null?void 0:ne.iterations)!==null?gn(Vn(ne==null?void 0:ne.iterations),"output"):es(Ot?"the output carries no iteration count":Is.not_ended),gt=Fv(e).tokens,re=Ct($==null?void 0:$.trigger)||Ct(N==null?void 0:N.trigger),fe=Ct(re==null?void 0:re.config),Ce=x!=null&&x.cadence?gn({text:x.cadence,start_ms:Ht((fe==null?void 0:fe.start_at)||"")},"automation"):es(I),Ie=R?gn({index:xe,count:x?x.occurrence_count:null},x?"automation":"run"):es(Is.not_automation),We=Vn(fe==null?void 0:fe.count)!==null?gn(Vn(fe==null?void 0:fe.count),"automation"):es(R&&re?"no count limit":I,R&&re?"automation":""),Ue=Ht((fe==null?void 0:fe.until)||""),et=Ue!==null?gn(Ue,"automation"):es(R&&re?"no end date":I,R&&re?"automation":""),at=Ct(P==null?void 0:P.retry),vt=Ct(at==null?void 0:at.backoff),xt=P?gn({max_attempts:Vn(at==null?void 0:at.max_attempts),backoff_initial:ln(vt==null?void 0:vt.initial),backoff_factor:Vn(vt==null?void 0:vt.factor),backoff_max:ln(vt==null?void 0:vt.max),failure:ln(P.failure),misfire:ln(P.misfire),serial:zp(P.serial)},"automation"):es(I),Et=N&&Array.isArray((fn=Ct(N.notify))==null?void 0:fn.channels)?gn(Qr(N.notify.channels),"automation"):es(I),zt=Fv(e),ot=x!=null&&x.context_mode||zt.has_history?gn({mode:(x==null?void 0:x.context_mode)||"",growing_max_tokens:(x==null?void 0:x.growing_max_tokens)??null,replayed_messages:zt.replayed_messages,replayed_tokens:zt.replayed_tokens,dropped_messages:zt.dropped_messages,dropped_tokens:zt.dropped_tokens},x!=null&&x.context_mode?"automation":"run"):es(R?I:"no session history on this run"),Jt=dt.root.value?gn(dt.root.value,dt.root.source):es(Is.wire);let wn;if(!R)wn=es(Is.not_automation);else if(!x)wn=es(Is.automation_not_loaded);else{const Xe=x.status;if(Xe==="paused")wn=gn({kind:"none",at_ms:null,text:"no next run (paused)"},"automation");else if(Xe==="completed")wn=gn(x.last&&xe!==null&&x.last.index===xe?{kind:"last",at_ms:null,text:"this was the last (stop reached)"}:{kind:"none",at_ms:null,text:"no next run (completed: stop reached)"},"automation");else if(Xe==="archived")wn=gn({kind:"none",at_ms:null,text:"no next run (archived)"},"automation");else if(Xe==="failed")wn=gn({kind:"none",at_ms:null,text:"no next run (the automation failed)"},"automation");else if(x.next_fire_ms!==null){const nn=em(x.next_fire_ms-u);wn=gn({kind:"next_at",at_ms:x.next_fire_ms,text:`next run at ${Ad(x.next_fire_ms)}${nn?` (in ${nn})`:""}`},"automation")}else if(ln(re==null?void 0:re.source_id)==="manual")wn=gn({kind:"on_trigger",at_ms:null,text:"next run when someone runs it"},"automation");else if(x.event_driven||cc(re)){const nn=x.cadence||"when something new arrives";wn=gn({kind:"on_trigger",at_ms:null,text:`next run ${nn.charAt(0).toLowerCase()}${nn.slice(1)}`},"automation")}else wn=es("no next fire time on this wire","automation")}return{subject_id:_,is_automation:R,who:{workflow:be,subject:Me,role:He,model:rt,model_declared:ze,system_prompt:Ve,task:ct},access:{tools_allowed:Qe,runtime_allowlist:$e,tools_called:ce,tool_approval:_e,untrusted_input_tools:le,email_recipients:Se,operator_email:ln(S==null?void 0:S.operator_email),workspace:dt},does:{llm_calls:_t,tool_calls:It,subruns:St,artifacts:ut,outcome:Mt,children_not_loaded:L.missing_run_ids},how_long:{started_ms:mn,finished_ms:yn,running:!Ot,duration:Gs,max_iterations:ge,iterations_used:Re,tokens:gt,cadence:Ce,next_fire_ms:(x==null?void 0:x.next_fire_ms)??null,occurrence:Ie,stop_after:We,stop_at:et,retry:xt},after:{notify:Et,context:ot,outputs_to:Jt,next:wn},ledger:L}}function gg(e,t){if(ki(e.run)===t)return e;for(const n of e.children){const r=gg(n,t);if(r)return r}return null}function RW(e,t,n){const r=n?gg(n,t):null;return!!r&&r!==e&&!!gg(r,ki(e.run))}const LW=["status","updated_at","current_node","paused","error","waiting"],IW=["workflow_id","created_at","parent_run_id","session_id","automation_id","role","occurrence_index","session_kind"];function CC(e,t){if(!t||typeof t!="object"||String(t.run_id||"").trim()&&String(t.run_id).trim()!==String(e.run_id||"").trim())return!1;const n=Ht(e.updated_at||""),r=Ht(t.updated_at||"");return n===null||r===null?!0:r>=n}function EC(e,t){if(!t||typeof t!="object")return e;const n={...e};for(const r of IW)(n[r]===void 0||n[r]===null||n[r]==="")&&t[r]!==void 0&&t[r]!==null&&(n[r]=t[r]);if(CC(e,t))for(const r of LW)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}function OW(e,t){const n=String(t.run_id||"").trim();let r=!1;const i=(e||[]).map(o=>String((o==null?void 0:o.run_id)||"").trim()!==n?o:(r=!0,{...o,...t}));return r||i.push(t),i}function ts(e){return s.jsx("p",{className:`ap_note ap_note_${e.kind}`,role:e.kind==="error"?"alert":void 0,children:e.children})}function lc(e){return s.jsxs("section",{className:"ap_block","data-block":e.id,"aria-labelledby":`ap_${e.id}_title`,children:[s.jsxs("header",{className:"ap_block_head",children:[s.jsx("h2",{id:`ap_${e.id}_title`,className:"ap_block_title",children:e.title}),e.meta?s.jsx("span",{className:"ap_block_meta",children:e.meta}):null]}),e.children]})}const PW={approve:"Review approval",answer:"Answer",resume:"Resume",open_subrun:"Open subrun",inspect:"Inspect"};function AC(e,t,n,r){return x1(e,t,n??null,r??null)}function DW(e,t){const n=PW[e.action],r=e.action==="open_subrun"?e.actor_run_id:t;return n&&r?{action:e.action,label:n,run_id:r}:null}function FW(e){const{line:t}=e;if(t.actor==="none")return null;if(t.actor==="run"&&t.actor_run_id){const r=e.ctx.by_id.get(t.actor_run_id),i=ti(String((r==null?void 0:r.workflow_id)||""))||"subrun (row not loaded)";return s.jsxs("button",{type:"button",className:"ap_actor ap_actor_run",title:`Ended by run ${t.actor_run_id}`,onClick:()=>e.on_open_run(t.actor_run_id),children:["run ",i]})}const n=t.actor==="run"?"a run":t.actor;return s.jsx("span",{className:`ap_actor ap_actor_${t.actor}`,title:"Who ends this state",children:n})}function zW(e){return s.jsx("button",{type:"button",className:"btn btn_icon ap_copy",title:`Copy run id ${e.run_id}`,"aria-label":"Copy run id",onClick:()=>{e.on_copy?e.on_copy(e.run_id):Em(e.run_id)},children:"⧉"})}const BW={used:"Read from the run's ledger: what it actually did",output:"Read from the run's own output",run:"Read from this run's detail and inputs","flow default":"The flow's default for a pin the run was not sent (the runtime applies it)",flow:"Read from the flow declaration",automation:"Read from the automation definition, not from this run's inputs",listing:"Read from the run listing: counts include every run below this one",gateway:"The gateway's own default; this wire does not report it"};function TC(e){return e.source?s.jsx("span",{className:"ap_source","data-source":e.source,title:BW[e.source],children:e.source}):null}function UW(e){return s.jsx("span",{className:"ap_absent",children:e.fact.source==="gateway"?e.fact.why:`— ${e.fact.why||"not on this wire"}`})}function xa(e){return s.jsxs("div",{className:"ap_prow ap_copyable","data-row":e.id,children:[s.jsx("dt",{className:"ap_prow_label",children:e.label}),s.jsx("dd",{className:"ap_prow_value",children:e.children}),s.jsxs("dd",{className:"ap_prow_meta",children:[s.jsx(TC,{source:e.source||""}),e.copy?s.jsx(Ig,{text:e.copy,label:e.label.toLowerCase()}):null]})]})}function Qn(e){const{fact:t}=e,n=t.value!==null;return s.jsx(xa,{id:e.id,label:e.label,source:t.source,copy:n?e.copy?e.copy(t.value):il(t.value):null,children:n?e.render?e.render(t.value):s.jsx(rm,{value:t.value}):s.jsx(UW,{fact:t})})}function Kl(e){return e.items.length?s.jsx("span",{className:"ap_tags",children:e.items.map((t,n)=>s.jsx("code",{className:"ap_tag",children:t},`${t}:${n}`))}):s.jsx("span",{className:"ap_muted",children:e.empty||"none"})}function Mh(e){return s.jsxs("section",{className:"ap_pgroup","data-group":e.id,"aria-labelledby":`ap_pg_${e.id}`,children:[s.jsxs("h3",{className:"ap_pgroup_title",id:`ap_pg_${e.id}`,children:[e.title," ",s.jsx("span",{className:"ap_pgroup_q",children:e.question})]}),s.jsx("dl",{className:"ap_ptable",children:e.children})]})}function kw(e){return[e.provider,e.model].filter(Boolean).join(" · ")||"model not recorded on the call"}function WW(e,t){if(e.length!==t.length)return!1;const n=new Set(e);return t.every(r=>n.has(r))}function _a(e,t,n=`${t}s`){return`${is(e)} ${e===1?t:n}`}function qW(e){var P,D;const{prof:t,p:n,line:r,ctx:i}=e,o=[];n.loading.input_data&&o.push(s.jsx(ts,{kind:"loading",children:"loading the run's inputs…"},"li")),n.errors.input_data&&o.push(s.jsxs(ts,{kind:"error",children:["inputs unavailable: ",n.errors.input_data]},"ei")),n.loading.detail&&o.push(s.jsx(ts,{kind:"loading",children:"loading the run detail…"},"ld")),n.errors.detail&&o.push(s.jsxs(ts,{kind:"error",children:["run detail unavailable: ",n.errors.detail]},"ed")),n.loading.flow&&o.push(s.jsx(ts,{kind:"loading",children:"loading the flow (its defaults)…"},"lf")),n.loading.records&&o.push(s.jsx(ts,{kind:"loading",children:"loading the ledger…"},"lr")),n.errors.records&&o.push(s.jsxs(ts,{kind:"error",children:["ledger unavailable: ",n.errors.records]},"er")),t.is_automation&&!n.automation_body&&!n.automation&&o.push(s.jsx(ts,{kind:"absent",children:"automation definition not loaded: tool policy unknown"},"na"));const u=R=>{const I=i.by_id.get(R);return ti(String((I==null?void 0:I.workflow_id)||""))||"a run (row not loaded)"},l=(R,I)=>s.jsx("button",{type:"button",className:"ap_link_btn ap_run_link",title:`Open run ${R}`,"data-run-id":R,onClick:()=>n.on_open_run(R),children:I}),{who:d,access:h,does:m,how_long:_,after:g}=t,y=h.workspace,b=y.root.value&&n.on_reveal_workspace?s.jsx("button",{type:"button",className:"ap_link_btn",onClick:()=>{var R;return(R=n.on_reveal_workspace)==null?void 0:R.call(n)},children:"show folder"}):null,k=t.ledger.runs,x=R=>k.length>1?s.jsx("span",{className:"ap_breakdown",children:k.map((I,W)=>s.jsxs("span",{"data-run-id":I.run_id,children:[W?" · ":"",is(R(I))," ",I.run_id===t.subject_id?"in this run":s.jsxs(s.Fragment,{children:["in ",l(I.run_id,u(I.run_id))]})]},I.run_id))}):null,N=m.children_not_loaded,$=N.length?s.jsxs("span",{className:"ap_breakdown","data-children-not-loaded":N.length,children:["children's calls live in their own view (",_a(N.length,"subrun")," not loaded here:"," ",N.map((R,I)=>s.jsxs("span",{children:[I?", ":"",l(R,u(R))]},R)),")"]}):null,E=R=>R.source==="listing"?s.jsx("span",{className:"ap_breakdown",children:"tree-inclusive: this run and every run below it"}):null,S=R=>s.jsx(Kl,{items:R.map(I=>I==="self"&&h.operator_email?`self (${h.operator_email})`:I),empty:"none"});return s.jsxs(lc,{id:"profile",title:"Agent profile",meta:"who it is · what it can reach · what it does · for how long · what comes after",children:[o,s.jsxs("div",{className:"ap_profile",children:[s.jsxs(Mh,{id:"who",title:"Who",question:"is this agent",children:[s.jsx(Qn,{id:"workflow",label:"Workflow",fact:d.workflow,render:R=>s.jsxs("span",{children:[R.name||R.id,R.flow_name?s.jsxs("span",{className:"ap_muted",children:[" · flow “",R.flow_name,"”"]}):null]}),copy:R=>R.id}),s.jsx(Qn,{id:"subject",label:"Subject",fact:d.subject,render:R=>R.kind==="automation"?s.jsx(rm,{value:R.title||"untitled automation"}):s.jsx("span",{children:R.kind==="session"?"a session (id on copy)":"a standalone run (id on copy)"}),copy:R=>R.id}),s.jsx(Qn,{id:"role",label:"Role",fact:d.role,render:R=>{var I,W;return s.jsxs("span",{children:[R.text,R.parent_run_id&&t.is_automation&&((I=_.occurrence.value)==null?void 0:I.count)!==null&&((W=_.occurrence.value)==null?void 0:W.count)!==void 0&&R.text.startsWith("run #")?s.jsxs("span",{className:"ap_muted",children:[" of ",is(_.occurrence.value.count)," so far"]}):null,R.parent_run_id?s.jsxs(s.Fragment,{children:[" · ",l(R.parent_run_id,"open parent")]}):null]})},copy:R=>R.parent_run_id||R.text}),s.jsx(Qn,{id:"model",label:"Model · provider",fact:d.model,render:R=>{var I;return s.jsxs("span",{className:"ap_stack",children:[R.map((W,G)=>s.jsxs("span",{children:[kw(W),W.calls!==null?s.jsxs("span",{className:"ap_muted",children:[" × ",_a(W.calls,"call")]}):null]},G)),(I=d.model_declared)!=null&&I.value?s.jsxs("span",{className:"ap_finding",children:["asked for ",kw(d.model_declared.value)," ",s.jsx(TC,{source:d.model_declared.source})]}):null]})},copy:R=>R.map(kw).join(`
168
+ `)}),s.jsx(Qn,{id:"system",label:"System prompt",fact:d.system_prompt}),s.jsx(Qn,{id:"task",label:"Task",fact:d.task})]}),s.jsxs(Mh,{id:"access",title:"Access",question:"what it may use",children:[s.jsx(Qn,{id:"tools_allowed",label:"May call",fact:h.tools_allowed,render:R=>s.jsx(Kl,{items:R})}),s.jsx(Qn,{id:"runtime_allowlist",label:"Runtime allowlist",fact:h.runtime_allowlist,render:R=>h.tools_allowed.value&&R.length&&WW(R,h.tools_allowed.value)?s.jsxs("span",{children:["the same ",_a(R.length,"tool")," as above"]}):s.jsx(Kl,{items:R})}),s.jsx(Qn,{id:"tools_called",label:"Did call",fact:h.tools_called,render:R=>s.jsxs("span",{className:"ap_stack",children:[R.length?s.jsx("span",{className:"ap_tags",children:R.map(I=>s.jsxs("span",{className:`ap_tool_use ${I.outside_declared?"ap_tool_outside":""}`,"data-tool":I.name,children:[s.jsxs("code",{className:"ap_tag",children:[I.name," × ",is(I.calls),I.failures?`, ${is(I.failures)} failed`:""]}),I.outside_declared?s.jsx("span",{className:"ap_finding",children:"called outside the declared list"}):null]},I.name))}):s.jsx("span",{className:"ap_muted",children:"none in the loaded ledger"}),$]})}),s.jsx(Qn,{id:"tool_approval",label:"Tool approval",fact:h.tool_approval,render:R=>s.jsx("span",{children:R})}),s.jsx(Qn,{id:"untrusted_input_tools",label:"Untrusted-input tools",fact:h.untrusted_input_tools,render:R=>s.jsx(Kl,{items:R})}),s.jsx(Qn,{id:"email_recipients",label:"Email recipients",fact:h.email_recipients,render:S}),s.jsx(Qn,{id:"workspace",label:"Workspace",fact:y.mode,render:R=>s.jsxs("span",{className:"ap_workspace",children:[s.jsx("span",{children:R||"mode not set"}),y.root.value?s.jsx("code",{className:"ap_path",children:y.root.value}):null,b]}),copy:R=>y.root.value?`${R}
169
+ ${y.root.value}`:R}),y.allowed_paths.value!==null?s.jsx(Qn,{id:"allowed_paths",label:"Allowed paths",fact:y.allowed_paths,render:R=>s.jsx(Kl,{items:R})}):null,y.ignored_paths.value!==null?s.jsx(Qn,{id:"ignored_paths",label:"Ignored paths",fact:y.ignored_paths,render:R=>s.jsx(Kl,{items:R})}):null]}),s.jsxs(Mh,{id:"does",title:"Does",question:"what it did",children:[s.jsx(xa,{id:"now",label:"Now",source:"run",copy:r.text,children:s.jsx("span",{className:r.stalled?"ap_stalled_text":void 0,children:r.text})}),s.jsx(Qn,{id:"llm_calls",label:"LLM calls",fact:m.llm_calls,render:R=>s.jsxs("span",{className:"ap_stack",children:[s.jsx("span",{children:is(R)}),m.llm_calls.source==="used"?x(I=>I.llm_calls):E(m.llm_calls)]})}),s.jsx(Qn,{id:"tool_calls",label:"Tool calls",fact:m.tool_calls,render:R=>s.jsxs("span",{className:"ap_stack",children:[s.jsxs("span",{children:[is(R.calls),R.failures?`, ${is(R.failures)} failed`:R.failures===0&&R.calls?", none failed":""]}),m.tool_calls.source==="used"?x(I=>I.tool_calls):E(m.tool_calls),m.tool_calls.source==="used"?$:null]})}),s.jsx(Qn,{id:"subruns",label:"Delegated subruns",fact:m.subruns,render:R=>R.length?s.jsx("span",{className:"ap_stack",children:R.map((I,W)=>{const G=[[I.provider,I.model].filter(Boolean).join(" · "),I.allowed_tools!==null?_a(I.allowed_tools.length,"tool"):"",I.max_iterations!==null?`max ${is(I.max_iterations)} iterations`:""].filter(Boolean),K=ti(I.workflow_id)||"subrun";return s.jsxs("span",{className:"ap_subrun",children:[I.run_id?l(I.run_id,K):s.jsxs("span",{children:[K," (not started yet)"]}),G.length?s.jsxs("span",{className:"ap_muted",children:[" · handed ",G.join(" · ")]}):null]},`${I.run_id}:${W}`)})}):s.jsx("span",{className:"ap_muted",children:"none"})}),m.artifacts.length?s.jsx(xa,{id:"artifacts",label:"Artifacts",source:"output",copy:m.artifacts.map(R=>R.id).join(`
170
+ `),children:s.jsxs("span",{children:[_a(m.artifacts.length,"artifact"),": ",s.jsx(Kl,{items:m.artifacts.map(R=>R.pin)})]})}):null,s.jsx(Qn,{id:"outcome",label:"Outcome",fact:m.outcome})]}),s.jsxs(Mh,{id:"how_long",title:"How long",question:"it runs and may run",children:[s.jsx(xa,{id:"started",label:"Started",source:_.started_ms!==null?"run":"",copy:_.started_ms!==null?new Date(_.started_ms).toISOString():null,children:_.started_ms!==null?s.jsx("span",{children:Ad(_.started_ms)}):s.jsx("span",{className:"ap_absent",children:"— not on this wire"})}),s.jsx(xa,{id:"finished",label:"Finished",source:_.finished_ms!==null?"run":"",copy:_.finished_ms!==null?new Date(_.finished_ms).toISOString():null,children:_.finished_ms!==null?s.jsx("span",{children:Ad(_.finished_ms)}):s.jsx("span",{className:"ap_muted",children:_.running?"so far (still active)":"— not on this wire"})}),s.jsx(Qn,{id:"duration",label:"Duration",fact:_.duration,render:R=>s.jsxs("span",{children:[vu(R),_.running?" so far":""]}),copy:R=>String(R)}),s.jsx(Qn,{id:"max_iterations",label:"Max iterations",fact:_.max_iterations}),s.jsx(Qn,{id:"iterations_used",label:"Iterations used",fact:_.iterations_used}),s.jsx(xa,{id:"token_limit",label:"Token limit",source:_.tokens?"run":"",copy:_.tokens?il(((D=(P=n.detail)==null?void 0:P.limits)==null?void 0:D.tokens)??_.tokens):null,children:_.tokens&&(_.tokens.used!==null||_.tokens.budget!==null)?s.jsxs("span",{children:[_.tokens.used!==null?is(_.tokens.used):"—",_.tokens.budget!==null?` of ${is(_.tokens.budget)}`:""," tokens",_.tokens.pct!==null?` (${_.tokens.pct<10&&_.tokens.pct>0?_.tokens.pct.toFixed(1):Math.round(_.tokens.pct)}%)`:""]}):s.jsx("span",{className:"ap_absent",children:"— no token estimate on this run"})}),s.jsx(Qn,{id:"cadence",label:"Cadence",fact:_.cadence,render:R=>s.jsxs("span",{children:[R.text,R.start_ms!==null?s.jsxs("span",{className:"ap_muted",children:[" · since ",Ad(R.start_ms)]}):null,_.next_fire_ms!==null?s.jsxs("span",{children:[" · next ",Ad(_.next_fire_ms)]}):null]})}),s.jsx(Qn,{id:"occurrences",label:"Occurrences",fact:_.occurrence,render:R=>s.jsxs("span",{children:[R.index!==null?`#${is(R.index)}`:"this run",R.count!==null?` of ${is(R.count)} so far`:""," · ",_.stop_after.value!==null?`stops after ${_a(_.stop_after.value,"scheduled occurrence")}`:_.stop_after.why," · ",_.stop_at.value!==null?`stops at ${Ad(_.stop_at.value)}`:_.stop_at.why]})}),s.jsx(Qn,{id:"retry",label:"Retry policy",fact:_.retry,render:R=>s.jsx("span",{children:[R.max_attempts!==null?_a(R.max_attempts,"attempt"):"",R.backoff_initial?`backoff ${R.backoff_initial}${R.backoff_factor!==null?` ×${R.backoff_factor}`:""}${R.backoff_max?` up to ${R.backoff_max}`:""}`:"",R.failure?`on failure: ${R.failure}`:"",R.misfire?`misfire: ${R.misfire}`:"",R.serial===!0?"serial":R.serial===!1?"may overlap":""].filter(Boolean).join(" · ")||"no retry fields set"})})]}),s.jsxs(Mh,{id:"after",title:"After",question:"what it may do next",children:[s.jsx(Qn,{id:"notify",label:"Notifies",fact:g.notify,render:R=>s.jsx(Kl,{items:R.map(I=>I==="email"?"email → the owner's registered address (not on this wire)":I),empty:"nobody (no channel)"})}),s.jsx(Qn,{id:"context_plan",label:"Context",fact:g.context,render:R=>s.jsxs("span",{className:"ap_stack",children:[s.jsx("span",{children:R.mode==="growing"?`growing${R.growing_max_tokens!==null?` (cap ${is(R.growing_max_tokens)} tokens)`:""}: each occurrence replays the session so far`:R.mode==="independent"?"independent: each occurrence starts fresh":R.mode||"session history"}),R.replayed_messages!==null||R.replayed_tokens!==null?s.jsxs("span",{className:"ap_muted",children:["this run replayed ",R.replayed_messages!==null?_a(R.replayed_messages,"message"):"?",R.replayed_tokens!==null?` (${is(R.replayed_tokens)} tokens)`:"",R.dropped_messages!==null?`, left out ${_a(R.dropped_messages,"message")}${R.dropped_tokens?` (${is(R.dropped_tokens)} tokens)`:""}`:""]}):null]})}),s.jsx(Qn,{id:"outputs_to",label:"Outputs go to",fact:g.outputs_to,render:R=>s.jsxs("span",{className:"ap_workspace",children:[s.jsx("code",{className:"ap_path",children:R}),b,m.artifacts.length?s.jsxs("span",{className:"ap_muted",children:["· ",_a(m.artifacts.length,"artifact")," in the output"]}):null]})}),s.jsx(Qn,{id:"next",label:"Next",fact:g.next,render:R=>s.jsx("span",{children:R.text}),copy:R=>R.at_ms!==null?new Date(R.at_ms).toISOString():R.text})]})]})]})}function HW(e){const{p:t}=e,n=p.useMemo(()=>kW(t.flow,t.input_data,t.detail),[t.flow,t.input_data,t.detail]),r=n.inputs.filter(l=>l.state==="value").length,i=t.loading.flow?s.jsx(ts,{kind:"loading",children:"loading the flow…"}):t.errors.flow?s.jsxs(ts,{kind:"error",children:["the flow did not load (",t.errors.flow,"): pin types unknown"]}):n.flow_found?n.start_found?null:s.jsx(ts,{kind:"absent",children:"the flow has no On Flow Start node"}):s.jsx(ts,{kind:"absent",children:"no flow JSON for this run: pin types unknown"}),o=t.loading.input_data?s.jsx(ts,{kind:"loading",children:"loading the run's inputs…"}):t.errors.input_data?s.jsxs(ts,{kind:"error",children:["inputs unavailable: ",t.errors.input_data]}):t.input_data?s.jsx(ts,{kind:"info",children:"values as the run holds them now: the gateway reads the run's current variables, so a pin the run writes back (context) shows its latest value"}):null,u=t.loading.detail?s.jsx(ts,{kind:"loading",children:"loading the run detail…"}):t.errors.detail?s.jsxs(ts,{kind:"error",children:["output unavailable: ",t.errors.detail]}):n.flow_found&&!n.end_found?s.jsx(ts,{kind:"absent",children:"the flow has no On Flow End node"}):n.end_is_passthrough?s.jsx(ts,{kind:"info",children:"the end declares no pins: the run returns its last node's output"}):t.detail&&!n.outputs_final?s.jsx(ts,{kind:"info",children:"values appear when the run ends"}):null;return s.jsxs(lc,{id:"pins",title:"Inputs → Outputs",children:[i,s.jsxs("div",{className:"ap_io",children:[s.jsxs("div",{className:"ap_io_col",children:[s.jsxs("h3",{className:"ap_io_title",children:["Inputs",n.inputs.length?s.jsxs("span",{className:"ap_io_meta",children:[n.inputs.length," pin",n.inputs.length===1?"":"s",t.input_data?` · ${r} provided`:""]}):null]}),o,s.jsx(V0,{side:"in",label:"Inputs",pins:n.inputs,also:n.also_sent,also_label:"also sent",empty_text:n.flow_found||t.input_data?"no input pins":"—"})]}),s.jsx("div",{className:"ap_io_arrow","aria-hidden":"true",children:"→"}),s.jsxs("div",{className:"ap_io_col",children:[s.jsxs("h3",{className:"ap_io_title",children:["Outputs",n.outputs.length?s.jsx("span",{className:"ap_io_meta",children:n.end_is_passthrough?"pass-through":`${n.outputs.length} pin${n.outputs.length===1?"":"s"}`}):null]}),u,s.jsx(V0,{side:"out",label:"Outputs",pins:n.outputs,also:n.also_returned,also_label:"also returned",outputs_final:n.outputs_final,empty_text:n.flow_found?"no output pins":"—"})]})]})]})}function VW(e){var l,d,h;const{p:t}=e,n=p.useMemo(()=>Fv(t.detail),[t.detail]);if(t.loading.detail&&!t.detail)return s.jsx(lc,{id:"context",title:"Context",children:s.jsx(ts,{kind:"loading",children:"loading the run detail…"})});if(!t.detail)return s.jsx(lc,{id:"context",title:"Context",children:t.errors.detail?s.jsxs(ts,{kind:"error",children:["run detail unavailable: ",t.errors.detail]}):s.jsx(ts,{kind:"absent",children:"run detail not loaded"})});const r=n.tokens,i=(r==null?void 0:r.pct)!==null&&(r==null?void 0:r.pct)!==void 0?`${r.pct<10&&r.pct>0?r.pct.toFixed(1):Math.round(r.pct)}%`:"",o=[n.policy,n.strict===!0?"strict":"",n.session_kind?`${n.session_kind} session`:""].filter(Boolean),u=(l=t.detail)==null?void 0:l.session_history;return s.jsx(lc,{id:"context",title:"Context",children:s.jsxs("dl",{className:"ap_ptable",children:[s.jsx(xa,{id:"window",label:"Window",source:n.has_history?"run":"",copy:n.has_history?il(u):null,children:n.has_history?s.jsx("span",{className:"ap_window_note",children:n.window_note||"the session-history receipt carries no counts"}):s.jsx("span",{className:"ap_absent",children:"— no session history replayed into this run"})}),n.has_history?s.jsxs(xa,{id:"history_policy",label:"History policy",source:"run",copy:o.length?o.join(" · "):null,children:[o.length?o.join(" · "):s.jsx("span",{className:"ap_absent",children:"— not on this wire"}),n.token_estimator?s.jsx("span",{className:"ap_source",title:n.token_estimator,children:"estimated"}):null]}):null,s.jsx(xa,{id:"tokens",label:"Tokens",source:r?"run":"",copy:r?il(((h=(d=t.detail)==null?void 0:d.limits)==null?void 0:h.tokens)??r):null,children:r&&(r.used!==null||r.budget!==null)?s.jsxs("span",{className:`ap_gauge_wrap ${r.over_warn?"ap_gauge_over":""}`,children:[s.jsxs("span",{className:"ap_gauge_text",children:[r.used!==null?is(r.used):"—",r.budget!==null?` of ${is(r.budget)}`:"",r.max_input_tokens!==null?" input":""," tokens",i?` (${i})`:"",r.warn_pct!==null?` · warns at ${r.warn_pct}%`:""]}),r.pct!==null?s.jsxs("span",{className:"ap_gauge",role:"meter","aria-label":"Context tokens used","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(Math.min(100,r.pct)),children:[s.jsx("span",{className:"ap_gauge_fill",style:{width:`${Math.min(100,Math.max(0,r.pct))}%`}}),r.warn_pct!==null?s.jsx("span",{className:"ap_gauge_warn",style:{left:`${Math.min(100,Math.max(0,r.warn_pct))}%`}}):null]}):null]}):s.jsx("span",{className:"ap_absent",children:"— no token estimate on this run"})}),s.jsx(xa,{id:"flow_warnings",label:"Flow warnings",source:t.detail?"run":"",copy:n.flow_warnings.length?n.flow_warnings.join(`
171
+ `):null,children:n.flow_warnings.length?s.jsx("ul",{className:"ap_warnings",children:n.flow_warnings.map((m,_)=>s.jsx("li",{children:m},_))}):s.jsx("span",{className:"ap_muted",children:"none"})})]})})}function MC(e){const t=ti(String(e.workflow_id||""))||"(workflow?)";return String(e.role||"").trim()==="occurrence"&&typeof e.occurrence_index=="number"?`run #${e.occurrence_index} · ${t}`:t}function RC(e){const{node:t,ctx:n}=e,r=t.run,i=Xd(r,n),o=AC(r,i),u=String(r.run_id||"");return s.jsxs("li",{className:"ap_tree_item",children:[s.jsxs("button",{type:"button",className:`ap_tree_node ${t.is_subject?"ap_tree_subject":""}`,"aria-current":t.is_subject?"true":void 0,title:`Open run ${u}`,"data-run-id":u,onClick:()=>e.on_open_run(u),children:[s.jsx("span",{className:`chip ${ka(o)}`,children:o}),s.jsx("span",{className:"ap_tree_name",children:MC(r)}),s.jsx("span",{className:`ap_tree_line ${i.stalled?"ap_stalled":""}`,children:i.text})]}),t.children.length?s.jsx("ul",{className:"ap_tree_children",children:t.children.map(l=>s.jsx(RC,{node:l,ctx:n,on_open_run:e.on_open_run},String(l.run.run_id)))}):null]})}function kp(e){return e===null?"—":is(e)}function GW(e){var E,S;const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=p.useMemo(()=>EC(e.run,e.detail),[e.run,e.detail]),r=String(n.run_id||"").trim(),i=CC(e.run,e.detail),o=p.useMemo(()=>e.automation??(e.automation_body?Am(e.automation_body):null),[e.automation,e.automation_body]),u=p.useMemo(()=>OW(e.runs||[],n),[e.runs,n]),l=p.useMemo(()=>{const P=new Map;e.detail&&i&&P.set(r,e.detail);const D=new Map;return o!=null&&o.automation_id&&D.set(o.automation_id,o),_x(u,{now_ms:t,details:P,pulses:e.pulses,automations:D,stall_after_ms:e.stall_after_ms})},[u,e.detail,i,r,o,t,e.pulses,e.stall_after_ms]),d=Xd(n,l),h=b1(n,l),m=String(((S=(E=e.input_data)==null?void 0:E.input_data)==null?void 0:S.prompt)||"").trim(),_=k1(n,l,m?{excerpt:m}:null),g=AC(n,d,Yp(e.detail),e.automation),y=[h.label&&h.label!==_.text?h.label:"",h.secondary].filter(Boolean),b=DW(d,r),k=p.useMemo(()=>MW(e.detail,e.input_data,e.flow,e.automation_body??o,e.records,u,t,{subject_run_id:r,row:n}),[e.detail,e.input_data,e.flow,e.automation_body,o,e.records,u,t,r,n]),x=p.useMemo(()=>NC(r,u),[r,u]),N=p.useMemo(()=>$W(x,u,t),[x,u,t]),$=(o==null?void 0:o.title)||"automation";return s.jsxs("article",{className:"ap_page","data-run-id":r,children:[s.jsxs("header",{className:"ap_header",children:[s.jsxs("div",{className:"ap_title_row",children:[s.jsx("span",{className:`ap_mark ap_mark_${h.kind}`,title:h.kind,children:h.glyph}),s.jsx("h1",{className:`ap_title ${_.untitled?"ap_untitled":""}`,title:`Title from: ${_.source}`,children:_.text}),_.untitled?s.jsx("span",{className:"ap_untitled_tag",children:"untitled"}):null,s.jsx("span",{className:`chip ${ka(g,Yp(e.detail))}`,children:g}),s.jsx(zW,{run_id:r,on_copy:e.on_copy})]}),y.length?s.jsx("div",{className:"ap_subject_line",children:y.join(" · ")}):null,s.jsxs("div",{className:`ap_state ap_verb_${d.verb} ${d.stalled?"ap_stalled":""}`,"data-lane":d.lane,children:[s.jsx("span",{className:"ap_state_text",children:d.text}),s.jsx(FW,{line:d,ctx:l,on_open_run:e.on_open_run}),b?s.jsx("button",{type:"button",className:`btn ${d.actor==="you"?"primary":""} ap_action`,onClick:()=>e.on_action(b.action,b.run_id),children:b.label}):null]}),e.loading.detail?s.jsx(ts,{kind:"loading",children:"reading the run detail… (the line above is from the listing row)"}):null,e.errors.detail?s.jsxs(ts,{kind:"error",children:["run detail unavailable: ",e.errors.detail," (the line above is from the listing row)"]}):null,e.detail&&!i?s.jsx(ts,{kind:"info",children:"the listing row is newer than the detail: the line above is from the row"}):null]}),s.jsx(qW,{prof:k,p:e,line:d,ctx:l}),s.jsx(HW,{p:e}),s.jsx(VW,{p:e}),s.jsx(lc,{id:"tree",title:"Run tree",meta:x.size?`${x.size} run${x.size===1?"":"s"}`:void 0,children:x.root?s.jsxs(s.Fragment,{children:[x.controller_id?s.jsxs("button",{type:"button",className:"ap_tree_parent",title:`Open the automation's controller run ${x.controller_id}`,"data-run-id":x.controller_id,onClick:()=>e.on_open_run(x.controller_id),children:[s.jsx("span",{className:"ap_mark ap_mark_automation",children:"⟳"}),s.jsx("span",{className:"ap_tree_name",children:$}),s.jsxs("span",{className:"ap_tree_line",children:[x.controller?Xd(x.controller,l).text:"controller (row not loaded)"," · other occurrences not shown"]})]}):null,s.jsx("ul",{className:`ap_tree ${x.controller_id?"ap_tree_under_parent":""}`,children:s.jsx(RC,{node:x.root,ctx:l,on_open_run:e.on_open_run})})]}):s.jsx(ts,{kind:"absent",children:"this run is not among the loaded rows"})}),s.jsxs(lc,{id:"spend",title:"Spend",meta:"tree-inclusive",children:[N.any_metrics?null:s.jsx(ts,{kind:"absent",children:"token and call counts not loaded: these rows were listed without metrics"}),N.rows.length?s.jsx("div",{className:"ap_table_wrap",children:s.jsxs("table",{className:"ap_spend",children:[s.jsx("caption",{children:"Tree-inclusive: each row counts its own run and every run below it, so rows do not add up."}),s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{scope:"col",children:"Run"}),s.jsx("th",{scope:"col",children:"Time"}),s.jsx("th",{scope:"col",children:"Tokens"}),s.jsx("th",{scope:"col",children:"LLM calls"}),s.jsx("th",{scope:"col",children:"Tool calls"}),s.jsx("th",{scope:"col",children:"Steps"})]})}),s.jsx("tbody",{children:N.rows.map(P=>{const D=l.by_id.get(P.run_id);return s.jsxs("tr",{className:P.is_subject?"ap_spend_subject":void 0,"data-run-id":P.run_id,children:[s.jsxs("th",{scope:"row",className:"ap_copyable",style:{"--ap-depth":P.depth},children:[s.jsx("span",{className:"ap_spend_name",children:D?MC(D):"run (row not loaded)"}),s.jsx(Ig,{text:P.run_id,label:"run id"})]}),s.jsx("td",{children:P.duration_ms===null?"—":`${vu(P.duration_ms)}${P.running?" so far":""}`}),s.jsx("td",{children:kp(P.tokens_total)}),s.jsx("td",{children:kp(P.llm_calls)}),s.jsx("td",{children:kp(P.tool_calls)}),s.jsx("td",{children:kp(P.steps)})]},P.run_id)})})]})}):s.jsx(ts,{kind:"absent",children:"no rows"})]}),s.jsxs(lc,{id:"ask",title:"Ask",children:[s.jsx("p",{className:"ap_window_note",children:e.ask_window_note||"Ask a question about this run and the runs below it."}),s.jsx("button",{type:"button",className:"btn primary ap_ask",onClick:()=>e.on_ask(),children:"Ask about this run"})]})]})}const $j={key:"",loading:!1,input_data:null,input_error:"",flow:null,flow_error:"",automation_body:null,automation:null,automation_error:"",runs:[],runs_error:""},jp=500,yg="http://127.0.0.1:8080";function Cj(e){const t=String(e||"").trim(),n=t.indexOf(":");return n<=0||n>=t.length-1?null:{bundle_id:t.slice(0,n),flow_id:t.slice(n+1)}}function Rh(e){const t=String(e||"").trim();return t.startsWith("abstractcode.")?`abstract.${t.slice(13)}`:t}function jw(e){const t=e&&typeof e=="object"?e:{},n=typeof(t==null?void 0:t.count)=="number"&&Number.isFinite(t.count)?Number(t.count):null,r=typeof(t==null?void 0:t.node_id)=="string"&&t.node_id.trim()?` before ${t.node_id.trim()}`:"";return`${n===null?"steering":`${n} steer message${n===1?"":"s"}`} folded into the run${r} — the loop sees it at this boundary`}function Sw(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function KW(e){const t=String(e||"").trim();if(t.startsWith("evt:")){const n=t.split(":",4);if(n.length===4&&n[3])return String(n[3]).trim()}return t}function JW(e){if(!e||typeof e!="object")return[];const t=Array.isArray(e.nodes)?e.nodes:[];if(!t.length)return[];let n=null;for(const l of t){if(!l||typeof l!="object")continue;const d=l.data&&typeof l.data=="object"?l.data:{};if(String(d.nodeType||l.type||"").trim()==="on_flow_start"){n=l;break}}if(!n)return[];const r=n.data&&typeof n.data=="object"?n.data:{},i=Array.isArray(r.outputs)?r.outputs:[],o=r.pinDefaults&&typeof r.pinDefaults=="object"?r.pinDefaults:{},u=[];for(const l of i){if(!l||typeof l!="object")continue;const d=String(l.id||"").trim();if(!d)continue;const h=String(l.type||"").trim();if(h==="execution"||d==="exec-out"||d==="exec")continue;const m=String(l.label||d).trim()||d,_={id:d,label:m,type:h||"unknown"};o&&Object.prototype.hasOwnProperty.call(o,d)&&(_.default=o[d]),u.push(_)}return u}function Nw(e,t){const n=String((e==null?void 0:e.message)||e||"Discovery failed");if(/\b401\b/.test(n)){const r=String(t.gateway_user||"").trim();return r?`Gateway authentication failed for user '${r}'. Sign in again through the connection dialog. (${n})`:`Gateway authentication failed. Sign in through the connection dialog (or check the dev bearer token under Settings → Advanced). (${n})`}return n}function YW(){try{const e=localStorage.getItem("abstractobserver_settings");if(!e)throw new Error("missing");const t=JSON.parse(e);return{gateway_url:String((t==null?void 0:t.gateway_url)||yg),auth_token:"",gateway_user:String((t==null?void 0:t.gateway_user)||""),gateway_auth_mode:(t==null?void 0:t.gateway_auth_mode)==="direct"?"direct":"session",worker_url:String((t==null?void 0:t.worker_url)||""),worker_token:String((t==null?void 0:t.worker_token)||""),theme:String((t==null?void 0:t.theme)||"dark"),font_scale:String((t==null?void 0:t.font_scale)||(t==null?void 0:t.fontScale)||"md").trim()||"md",header_density:String((t==null?void 0:t.header_density)||(t==null?void 0:t.headerDensity)||"standard").trim()||"standard",auto_connect_gateway:(t==null?void 0:t.auto_connect_gateway)!==!1,maintenance_ai_provider:String((t==null?void 0:t.maintenance_ai_provider)||""),assistant_skill_names:Array.isArray(t==null?void 0:t.assistant_skill_names)?t.assistant_skill_names.map(n=>String(n||"").trim()).filter(Boolean):[],maintenance_ai_model:String((t==null?void 0:t.maintenance_ai_model)||"")}}catch{return{gateway_url:yg,auth_token:"",gateway_user:"",gateway_auth_mode:"session",worker_url:"",worker_token:"",theme:"dark",font_scale:"md",header_density:"standard",auto_connect_gateway:!0,maintenance_ai_provider:"",assistant_skill_names:[],maintenance_ai_model:""}}}function XW(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function ZW(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=[],n=(i,o)=>{const u=String(o??"").trim();u&&(t.some(l=>l.label===i&&l.value===u)||t.push({label:i,value:u}))},r=String(e.display??"").trim().replace(/^\[/,"").replace(/\]$/,"");return n("time",r||e.local_datetime),n("tz",e.timezone),n("country",e.country),n("user",e.user),t}function Ej(e){const t=ZW(e.metadata);return t.length?s.jsx("div",{className:"runtime_metadata_chips","aria-label":"Runtime metadata",children:t.map(n=>s.jsxs("span",{className:"chip mono muted",children:[n.label,": ",n.value]},`${n.label}:${n.value}`))}):null}function QW(){return typeof window>"u"?"":uI(window.location)}function eq(){try{const e="abstractobserver_session_id_v1",t=window.sessionStorage.getItem(e);if(t&&t.trim())return t.trim();const n=`obs_${Xs()}`;return window.sessionStorage.setItem(e,n),n}catch{return""}}function tq(){var I_,Uo,lh,hd,fa,md,ha,ch,uh,_d,Gc,O_,P_,dh,fh;const[e,t]=p.useState("board"),[n,r]=p.useState(()=>YW()),i=typeof window<"u"&&((I_=window.__ABSTRACT_UI_CONFIG__)==null?void 0:I_.monitor_gpu)===!0,o=typeof window<"u"&&(((Uo=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Uo.entity_app_url)||"").trim().replace(/\/+$/,"")||"http://127.0.0.1:3007",u=p.useRef(null),[l,d]=p.useState(""),[h,m]=p.useState(""),[_,g]=p.useState(()=>QW()),[y,b]=p.useState(""),[k,x]=p.useState(""),[N,$]=p.useState(""),[E,S]=p.useState("{}"),[P]=p.useState(()=>eq()),[D,R]=p.useState(null),[I,W]=p.useState(!1),[G,K]=p.useState(""),[H,M]=p.useState(!1),[A,O]=p.useState(""),[L,V]=p.useState(!1),J=M2({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((lh=window.__ABSTRACT_UI_CONFIG__)==null?void 0:lh.gateway_url)||yg,onStatusChange:v=>Uf(v)}),[U,te]=p.useState(null),[z,ne]=p.useState(null),[se,de]=p.useState(!1),[be,Me]=p.useState(null),[je,ae]=p.useState("once"),[xe,Ae]=p.useState(!1),[He,mt]=p.useState(null);function nt(v){ae(v),Ae(!0)}const[rt,ze]=p.useState(""),[Ve,ct]=p.useState(Yw),[Qe,Dt]=p.useState([]),[$e,Le]=p.useState(null),[ce,Q]=p.useState(!1),[_e,le]=p.useState([]),Se=p.useRef(new y3(Xs)),[pe,dt]=p.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[yt,_t]=uE("abstractobserver",{legacyKey:"abstractobserver_settings"}),[It,bt]=p.useState(!1),[St,ut]=p.useState(!1),[Ot,Mt]=p.useState([]),[mn,yn]=p.useState([]),[In,Gs]=p.useState([]),[ss,ge]=p.useState(!1),[Re,gt]=p.useState(null),[re,fe]=p.useState(null),[Ce,Ie]=p.useState(0),[We,Ue]=p.useState(""),et=p.useRef(!1),at=p.useRef(0),vt=p.useRef(0),[xt,Et]=p.useState(!1),[zt,ot]=p.useState([]),[Jt,wn]=p.useState([]),[hn,sn]=p.useState({}),[Vt,rs]=p.useState(!1),[Be,Zt]=p.useState(!1),[Tt,Dn]=p.useState(!1),[fn,Xe]=p.useState([]),[nn,cn]=p.useState([]),Er=p.useRef(0),Cs=p.useRef(null);Cs.current||(Cs.current=new F0(v=>window.setTimeout(v,40),v=>Xe(T=>T.concat(v))));const gs=p.useRef(null);gs.current||(gs.current=new F0(v=>window.setTimeout(v,40),v=>cn(T=>T.concat(v))));const mr=p.useRef({scanned:0,found:null}),[we,Nt]=p.useState(null),[Fn,tr]=p.useState(""),[Ni,nr]=p.useState(!1),vo=p.useRef(null),[uc,ll]=p.useState({}),[bs,_r]=p.useState({}),[Ts,zi]=p.useState(!1),[cl,ys]=p.useState(""),[ni,Ms]=p.useState(!0),[si,ks]=p.useState(""),[ri,Bi]=p.useState(!1),[Ln,Sa]=p.useState(!1),[ul,dl]=p.useState(6),[Ar,dc]=p.useState("standard"),[Ui,Na]=p.useState(""),[xo,Ps]=p.useState(""),[Ds,pr]=p.useState(!1),[bo,Ur]=p.useState(!1),[Tr,Wr]=p.useState("pause"),[fc,qr]=p.useState(""),[xu,$i]=p.useState(""),[Yo,fl]=p.useState(""),ko=p.useRef(null),ii=p.useRef(null),[$a,Wi]=p.useState(!1),sr=p.useRef(null),[af,oi]=p.useState(""),[Gn,Y]=p.useState($j),he=p.useRef(0),[Oe,De]=p.useState(""),[Ye,ht]=p.useState(""),[Wt,Pt]=p.useState(""),[Bt,pn]=p.useState(!1),[Cn,Ks]=p.useState("idle"),[Ft,xn]=p.useState([]),[os,Hn]=p.useState(null),Mr=p.useRef(null),[gr,qi]=p.useState(!1),[hl,Hi]=p.useState(""),[lf,hc]=p.useState(""),[Ca,Ea]=p.useState(""),[cf,mc]=p.useState([]),[_c,bu]=p.useState(!1),[uf,ku]=p.useState(""),[df,ju]=p.useState(""),[Su,ml]=p.useState(!1),[Lm,Aa]=p.useState(""),Im=p.useMemo(()=>{if(!Ft.length)return"";try{return JSON.stringify(Ft.map(v=>({role:v.role,content:v.content,ts:v.ts})))}catch{return"1"}},[Ft]),Nu=p.useMemo(()=>Ft.length?Ca?Im!==Ca:!0:!1,[Im,Ft.length,Ca]),ff=p.useMemo(()=>cf.map(v=>{const T=String(v.title||"").trim()||`Chat ${String(v.thread_id||"").slice(0,8)}`,F=String(v.created_at||"").trim(),B=F?F.replace("T"," ").slice(0,19):"",Z=String(v.run_id||"").trim()?String(v.run_id).slice(0,8):"",X=[T,B&&`(${B})`,Z&&`run ${Z}`].filter(Boolean).join(" • ");return{value:String(v.thread_id||""),label:X}}),[cf]);p.useEffect(()=>{i&&p4()},[i]),p.useEffect(()=>{if(!i)return;const v=u.current;v&&(v.token=n.gateway_auth_mode==="direct"&&n.auth_token||"")},[i,n.auth_token,n.gateway_auth_mode]);const[,hf]=p.useState([]),[_l,Om]=p.useState([]),Pm=(v,T)=>{const F=Date.now();Om(B=>{const Z=B.findIndex(ee=>ee.title===v);if(Z<0)return[...B,{title:v,preview:T,count:1,at:F}].slice(-4);const X=[...B];return X[Z]={title:v,preview:T,count:X[Z].count+1,at:F},X})},mf=_l.length?_l.map(v=>{const T=new Date(v.at),F=`${String(T.getHours()).padStart(2,"0")}:${String(T.getMinutes()).padStart(2,"0")}`;return`${v.title}: ${v.preview} · ${F}${v.count>1?` ×${v.count}`:""}`}).join(" — "):"",[Hg,$u]=p.useState(!1),pl=p.useRef(""),Vg=p.useRef("");p.useEffect(()=>{var T,F;const v=String(((F=(T=U==null?void 0:U.gateway)==null?void 0:T.principal)==null?void 0:F.user_id)||"").trim();pl.current=v||(L&&n.gateway_auth_mode==="direct"?"direct":"")},[U,L,n.gateway_auth_mode]);const[Cu,En]=p.useState(""),[Eu,Dm]=p.useState(""),[Au,gl]=p.useState("all"),[_f,Gg]=p.useState("status"),[js,jo]=p.useState("ledger"),pf=rb(fy.md),pc=rb(`${fy.sm}, ${fy.short}`),Vi=nI({is_drawer:pf,page:e}),gf=Vi.open,Xo=Vi.set_open,[Fm,zm]=Xp("observe_runs"),yf=Vi.toggle_ref,wf=Vi.sidebar_ref,vf=p.useRef(null),[Bm,xf]=p.useState(()=>o0(typeof window<"u"?window.location.hash:"")),[Kg,Um]=p.useState(""),[Wm,bf]=p.useState(""),[yl,yr]=p.useState(""),[Gi,wl]=p.useState(null),[gc,Tu]=p.useState({}),[kf,Ta]=p.useState(!1),[qm,yc]=p.useState(""),[Ki,jf]=p.useState(!1),[Ma,Sf]=p.useState(!1),[Mu,Ra]=p.useState(()=>Date.now()),[Rr,Zo]=p.useState(""),[Hm,La]=p.useState({}),[Vm,Ru]=p.useState({}),vl=p.useRef([]),Hr=p.useRef(null),So=p.useRef(""),wc=p.useRef({}),Vr=p.useRef({}),vc=p.useRef({}),Ia=p.useRef(new Set),[No,Lu]=p.useState([]),$o=p.useRef(""),xl=p.useRef({}),Co=p.useRef(null),wr=p.useRef(null),zn=p.useRef(0),Qo=p.useRef({}),Oa=p.useRef(!1),Ci=p.useRef(new Set),[Iu,bl]=p.useState(""),[Lr,Ei]=p.useState(""),vr=p.useRef(""),Nf=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[xc,Gm]=p.useState("activity"),[Ou,bc]=p.useState([]),[kc,Pu]=p.useState(0),[$f,Du]=p.useState(0),[Cf,Km]=p.useState({}),[Jm,Ym]=p.useState({}),[Jg,Fu]=p.useState(!1),[ea,Ef]=p.useState(""),[Ji,Yi]=p.useState(""),[Eo,Ai]=p.useState("all"),[kl,Xm]=p.useState(""),[jl,Pa]=p.useState([]),[ta,Sl]=p.useState("all"),[Ao,Af]=p.useState("type"),[To,na]=p.useState("newest"),[On,Yn]=p.useState(""),[ai,Es]=p.useState(""),[xr,Mo]=p.useState(""),[Xi,rr]=p.useState(0),[Ro,zu]=p.useState(()=>Nf()),[Zm,Nl]=p.useState(!1),[Bu,Lo]=p.useState(""),[Uu,sa]=p.useState(""),[ir,Wu]=p.useState(""),[Zi,$l]=p.useState("text"),[Cl,El]=p.useState(null),[qu,br]=p.useState(!1),[Gr,Qi]=p.useState(""),[eo,to]=p.useState(""),[Da,Tf]=p.useState(""),[Hu,Vu]=p.useState(!1),[Kr,Ir]=p.useState(""),[Xn,Ti]=p.useState("run_ledger"),[Qm,e_]=p.useState(""),[Mf,jc]=p.useState([]),[t_,Al]=p.useState(""),[n_,Fa]=p.useState(!1),[Rf,Lf]=p.useState(""),Ke=p.useMemo(()=>new qy({base_url:n.gateway_auth_mode==="session"?"":n.gateway_url,auth_token:n.gateway_auth_mode==="session"?"":n.auth_token}),[n.gateway_auth_mode,n.gateway_url,n.auth_token]),Bn=p.useMemo(()=>new M3(Ke.automations_client(),E3(Ke,Xs,on)),[Ke]),li=p.useSyncExternalStore(v=>Bn.subscribe(v),()=>Bn.state),If=i3(n.gateway_url),Io=If?()=>{window.open(If,"_blank","noopener,noreferrer")}:void 0,Of=p.useCallback(v=>f3(v,{connections:li.trigger_connections,mailboxes:li.mailboxes}),[li.trigger_connections,li.mailboxes]),Oo=p.useMemo(()=>!rt&&N.trim()&&k.trim()?c3(D,N.trim(),k.trim()):null,[D,N,k,rt]),Tl=p.useRef("");p.useEffect(()=>{if(!xe||je!=="automate"||!Oo)return;const v=`${N.trim()}:${k.trim()}`;if(Tl.current===v)return;Tl.current=v;let T={};try{const B=JSON.parse(E||"{}");B&&typeof B=="object"&&!Array.isArray(B)&&(T=B)}catch{T={}}const F=d3(Ve,T,Oo);ct(F.form),S(JSON.stringify(F.input_data,null,2))},[xe,je,Oo,N,k]);const Ml=RS(xe&&je==="automate"&&L?_3(Ve,Oo):null,Bn.preview_schedule);p.useEffect(()=>{xe&&je==="automate"&&L&&(Bn.load_email_status(),Bn.load_trigger_vocab())},[e,je,L,Bn]),p.useEffect(()=>{L&&Bn.load_trigger_vocab()},[L,Bn]),p.useEffect(()=>{const v=()=>{const T=a3(window.location.hash);if(T){if(T.page==="run"){g(T.run_id),xf(o0(window.location.hash));return}if(T.page==="launch"){nt(T.mode);return}t(T.page)}};return v(),window.addEventListener("hashchange",v),()=>window.removeEventListener("hashchange",v)},[]);const Pf=p.useMemo(()=>{const v={};for(const T of li.items)v[T.automation_id]=T.title;return v},[li.items]),Df=p.useMemo(()=>i4(),[]),[Ff,Gu]=p.useState(k0),za=p.useRef(0);function ci(){const v=++za.current;Gu(k0),o4(Ke).then(T=>{v===za.current&&Gu(T)})}const no=p.useMemo(()=>n.worker_url.trim()?new _P({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),Ku=p.useMemo(()=>fP(Ke.fetch_gateway,nv),[Ke]),or=fn.length?fn[fn.length-1].record:null,un=p.useMemo(()=>Ya(or),[or]),hs=p.useMemo(()=>{const v=N.trim();if(!D||!v||String(D.bundle_id||"").trim()&&String(D.bundle_id||"").trim()!==v)return null;const T=Array.isArray(D.entrypoints)?D.entrypoints:[];if(!T.length)return null;const F=k.trim();if(F)return T.find(Z=>String(Z.flow_id||"").trim()===F)||null;if(T.length===1)return T[0];const B=String(D.default_entrypoint||"").trim();return B&&T.find(Z=>String(Z.flow_id||"").trim()===B)||null},[D,N,k]),Sc=p.useMemo(()=>{const v=hs==null?void 0:hs.inputs;return Array.isArray(v)?v:[]},[hs]),zf=p.useMemo(()=>JW(Gi),[Gi]),Jr=p.useMemo(()=>Sc.length?Sc:zf,[Sc,zf]),Yr=p.useMemo(()=>{const v=typeof(we==null?void 0:we.workflow_id)=="string"?String(we.workflow_id):"",T=Cj(v);if(T&&D&&String(D.bundle_id||"").trim()===T.bundle_id){const Z=(Array.isArray(D.entrypoints)?D.entrypoints:[]).find(X=>String((X==null?void 0:X.flow_id)||"").trim()===T.flow_id);if(Z&&Z.node_index&&typeof Z.node_index=="object")return Z.node_index}const F=hs==null?void 0:hs.node_index;return F&&typeof F=="object"?F:{}},[we,D,hs]);p.useEffect(()=>{XW(n)},[n]),p.useEffect(()=>()=>{Co.current&&Co.current.abort(),wr.current&&wr.current.abort(),ko.current&&window.clearTimeout(ko.current),ii.current&&window.clearTimeout(ii.current),Hr.current&&window.clearTimeout(Hr.current),sr.current&&window.clearTimeout(sr.current)},[]);const rn=p.useMemo(()=>{const v=E.trim();if(!v)return{};try{const T=JSON.parse(v);return typeof T!="object"||T===null||Array.isArray(T)?null:T}catch{return null}},[E]),s_=typeof(rn==null?void 0:rn.prompt)=="string"?String(rn.prompt):"",Rl=typeof(rn==null?void 0:rn.provider)=="string"?String(rn.provider):"",r_=typeof(rn==null?void 0:rn.model)=="string"?String(rn.model):"",Nc=typeof(rn==null?void 0:rn.workspace_root)=="string"?String(rn.workspace_root):"",so=p.useMemo(()=>{const v=rn==null?void 0:rn.workspace;return v&&typeof v=="object"&&!Array.isArray(v)?v:null},[rn]),$c=Jr.length>0&&!!N.trim(),Ba=v=>{const T=String(v||"").trim().toLowerCase();return T==="object"||T==="memory"||T==="assertion"||T==="assertions"||T==="any"};p.useEffect(()=>{_r({})},[N,k]),p.useEffect(()=>{rn!==null&&ll(v=>{const T={};for(const F of Jr){if(!F||typeof F!="object")continue;const B=String(F.id||"").trim();if(!B)continue;const Z=String(F.type||"").trim();if(!Ba(Z))continue;if(String(bs[B]||"").trim()){T[B]=typeof v[B]=="string"?v[B]:"";continue}const ee=rn==null?void 0:rn[B];ee===void 0?T[B]="":T[B]=OI(ee)}return T})},[Jr,rn,bs]);const kr=rt?{kind:"default",interface:rt}:N.trim()&&k.trim()?{kind:"bundle",bundle_id:N.trim(),flow_id:k.trim()}:null,Ju=t3(kr),ui=Array.isArray(rn==null?void 0:rn.skills)?rn.skills.map(v=>String(v||"").trim()).filter(Boolean):[],di=p.useMemo(()=>{const v={};for(const T of Ot){const F=String(T.workflow_id||"").trim(),B=String(T.label||"").trim();F&&B&&(v[F]=B)}return v},[Ot]),Ll=DS({interfaceId:null,defaultInterface:Fd,request:(v,T)=>Ke.get_gateway_json(v,T.signal),enabled:L,reloadKey:Ot}),ms=p.useMemo(()=>{const v=new Set;for(const T of Array.isArray(Jt)?Jt:[]){const F=String((T==null?void 0:T.name)||"").trim();F&&v.add(F)}return Array.from(v).sort()},[Jt]),Yu=p.useMemo(()=>{const v=[];for(const T of Array.isArray(Jt)?Jt:[]){const F=String((T==null?void 0:T.name)||"").trim();if(!F)continue;const B=String((T==null?void 0:T.display_name)||"").trim();v.push({name:F,display_name:B||void 0})}return v},[Jt]),Cc=p.useMemo(()=>{const v=new Set;for(const T of zt||[]){if(!T||typeof T!="object")continue;const F=String(T.name||"").trim();F&&v.add(F)}return Array.from(v).sort()},[zt]),Xu=p.useMemo(()=>{const v=n.maintenance_ai_provider.trim();if(!v)return{models:[],error:""};const T=hn[v];return T?{models:(Array.isArray(T.models)?T.models:[]).map(B=>String(B||"").trim()).filter(Boolean),error:String(T.error||"")}:{models:[],error:""}},[hn,n.maintenance_ai_provider]),Il=n.maintenance_ai_provider.trim(),Bf=!!(Il&&L&&!Object.prototype.hasOwnProperty.call(hn,Il));p.useEffect(()=>{const v=Rl.trim();if(!v||hn[v]||xl.current[v])return;xl.current[v]=!0;let T=!1;return(async()=>{try{const B=await Ke.discovery_provider_models(v);if(T)return;const Z=Array.isArray(B==null?void 0:B.models)?B.models:[],X=typeof(B==null?void 0:B.error)=="string"?String(B.error):"";sn(ee=>({...ee,[v]:{models:Z,error:X||void 0}}))}catch(B){if(T)return;sn(Z=>({...Z,[v]:{models:[],error:String((B==null?void 0:B.message)||B||"Failed to load models")}}))}finally{delete xl.current[v]}})(),()=>{T=!0}},[Rl,hn,Ke]),p.useEffect(()=>{const v=n.maintenance_ai_provider.trim();if(!v||!L||hn[v]||xl.current[v])return;xl.current[v]=!0;let T=!1;return(async()=>{try{const B=await Ke.discovery_provider_models(v);if(T)return;const Z=Array.isArray(B==null?void 0:B.models)?B.models:[],X=typeof(B==null?void 0:B.error)=="string"?String(B.error):"";sn(ee=>({...ee,[v]:{models:Z,error:X||void 0}}))}catch(B){if(T)return;sn(Z=>({...Z,[v]:{models:[],error:String((B==null?void 0:B.message)||B||"Failed to load models")}}))}finally{delete xl.current[v]}})(),()=>{T=!0}},[n.maintenance_ai_provider,hn,Ke,L]);function Zn(v,T){const F=String(v||"").trim();if(!F)return;let B={};try{const Z=JSON.parse(E||"{}");typeof Z=="object"&&Z!==null&&!Array.isArray(Z)&&(B=Z)}catch{B={}}if(T==null){delete B[F],S(JSON.stringify(B,null,2));return}if(typeof T=="string")T?B[F]=T:delete B[F];else if(Array.isArray(T)){const Z=T.map(X=>X).filter(X=>X!=null);Z.length?B[F]=Z:delete B[F]}else B[F]=T;S(JSON.stringify(B,null,2))}async function as(v){const T=String(v||"").trim();if(!T)return K("Missing bundle_id"),null;K(""),W(!0);try{const F=await Ke.get_bundle(T);return R(F),bn({ts:on(),kind:"info",title:`Loaded bundle ${T}`}),F}catch(F){return R(null),K(String((F==null?void 0:F.message)||F||"Failed to load bundle")),null}finally{W(!1)}}function Ss(v){const T=[],F=Array.isArray(v==null?void 0:v.items)?v.items:[];for(const B of F){const Z=String((B==null?void 0:B.bundle_id)||"").trim();if(!Z)continue;const X=Array.isArray(B==null?void 0:B.entrypoints)?B.entrypoints:[];if(X.length)for(const ee of X){const oe=String((ee==null?void 0:ee.flow_id)||"").trim();if(!oe||(ee==null?void 0:ee.deprecated)===!0)continue;const Ge=`${Z}:${oe}`,ke=String((ee==null?void 0:ee.name)||"").trim(),ye=ke?`${Z} · ${ke}`:`${Z} · ${oe}`,Fe=String((ee==null?void 0:ee.description)||"").trim(),st=(Array.isArray(ee==null?void 0:ee.interfaces)?ee.interfaces:[]).some(lt=>String(lt||"").trim().length>0),pt=Array.isArray(ee==null?void 0:ee.agent_default_interfaces)?ee.agent_default_interfaces.map(lt=>String(lt||"").trim()).filter(Boolean):[];T.push({workflow_id:Ge,bundle_id:Z,bundle_ref:String((B==null?void 0:B.bundle_ref)||"").trim(),flow_id:oe,label:ye,description:Fe||void 0,has_interface:st,agent_default_interfaces:pt})}}return T.sort((B,Z)=>B.label.localeCompare(Z.label)),T}async function Pn(v=Ke,T){if(et.current&&!(T!=null&&T.force))return;et.current=!0;const F=ro.current;ge(!0);const B=ye=>ye.map(sp).filter(Fe=>!!Fe.run_id),Z=ye=>Array.isArray(ye==null?void 0:ye.items)?ye.items:[],X=z9(v,F),ee=()=>{const ye=X.view();yn(ye.roots),Gs(ye.all)},oe=(ye,Fe)=>{if(String((ye==null?void 0:ye.name)||"")==="Superseded")return;const Pe=String((ye==null?void 0:ye.message)||ye||"");if(bn({ts:on(),kind:"error",title:Fe,preview:en(Pe)}),Pm(Fe,en(Pe)),(/\b40[13]\b/.test(Pe)||/unauthorized|forbidden/i.test(Pe))&&J.refresh().catch(()=>{}),/\b429\b/.test(Pe)||/too many requests/i.test(Pe)){const st=Math.min(12e4,Math.max(15e3,vt.current*2||15e3));vt.current=st,at.current=Date.now()+st,bn({ts:on(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(st/1e3)}s`})}},Ge=pl.current,ke=Ge?P9(String(n.gateway_url||""),Ge):"";Vg.current=ke,ke&&X.active_at===null&&X.seed(D9(aj(),ke))&&X.active_at!==null&&(ee(),gt(X.active_at),$u(!0));try{const[ye,Fe]=await Promise.allSettled([v.list_runs({status:"running",limit:ij}),v.list_runs({status:"waiting",limit:oj})]);if(F!==ro.current)return;if(ye.status==="rejected"&&Fe.status==="rejected")throw ye.reason;ye.status==="rejected"&&oe(ye.reason,"Runs listing (running) failed"),Fe.status==="rejected"&&oe(Fe.reason,"Runs listing (waiting) failed");const Pe=ye.status==="fulfilled"?ye.value:null,st=Fe.status==="fulfilled"?Fe.value:null,pt=Pe?Z(Pe):X.active_rows.filter(ft=>String(ft.status||"")==="running"),lt=st?Z(st):X.active_rows.filter(ft=>String(ft.status||"")==="waiting"),vn=!!(Pe&&st)&&pt.length<ij&&lt.length<oj&&(Pe==null?void 0:Pe.has_more)!==!0&&(st==null?void 0:st.has_more)!==!0,qt=X.seeded;X.apply_active(B(pt),B(lt),vn),!(Pe&&st)&&qt&&(X.seeded=!0),ee(),gt(Date.now()),$u(!(Pe&&st)&&qt),Pe&&st&&Om([]),vt.current=0,at.current=0,ke&&Pe&&st&&window.setTimeout(()=>F9(aj(),ke,X.snapshot()),0)}catch(ye){oe(ye,"Refresh runs failed");return}finally{et.current=!1,ge(!1)}X.sweep_due(Date.now(),(T==null?void 0:T.force)===!0)&&(X.begin_sweep(Date.now()),v.list_runs({limit:200,root_only:!0,include_metrics:!0}).then(async ye=>{const Fe=Number(ye==null?void 0:ye.archived_sessions);if(Number.isFinite(Fe)&&Fe<=0)return[ye,{items:[]}];const Pe=await v.list_runs({limit:200,root_only:!0,archived_only:!0,include_metrics:!0});return[ye,Pe]}).then(([ye,Fe])=>{if(F!==ro.current||!lj(X))return X.fail_sweep();const Pe=v3(Z(ye),Z(Fe));X.apply_sweep(B(Pe),Date.now()),ee()},ye=>{X.fail_sweep(),!(F!==ro.current||!lj(X))&&oe(ye,"Refresh run metrics failed")}))}async function Ec(v){var oe,Ge,ke;const T=ro.current;V(!0),sn({}),v.list_apps().then(ye=>{if(T!==ro.current)return;const Pe=(Array.isArray(ye==null?void 0:ye.apps)?ye.apps:[]).find(pt=>String((pt==null?void 0:pt.id)||"")==="code"),st=Pe&&Pe.installed===!0&&Pe.running===!0?String(Pe.url||"").trim():"";mt(st?{url:st}:null)}).catch(()=>{T===ro.current&&mt(null)});const[F,,B,Z,X]=await Promise.allSettled([v.list_bundles(),Pn(v),v.discovery_tools(),v.discovery_providers({include_models:!1}),v.discovery_capabilities()]);if(T!==ro.current)return;if(F.status==="rejected"&&B.status==="rejected"&&Z.status==="rejected"){V(!1),O(Nw(F.reason,n)),bn({ts:on(),kind:"error",title:"Discovery failed",preview:en(String(F.reason||""))});return}dt(X.status==="fulfilled"?x3(X.value):{available:!1,reason:`Could not read the gateway capabilities: ${String(((oe=X.reason)==null?void 0:oe.message)||X.reason)}`});let ee=0;if(F.status==="fulfilled"){const ye=Ss(F.value);ee=ye.length,Mt(ye)}else Mt([]),bn({ts:on(),kind:"error",title:"Discovery bundles failed",preview:en(String(F.reason||""))});if(B.status==="fulfilled"){const ye=Array.isArray((Ge=B.value)==null?void 0:Ge.items)?B.value.items:[];ot(ye)}else ot([]),bn({ts:on(),kind:"error",title:"Discovery tools failed",preview:en(String(B.reason||""))});if(Z.status==="fulfilled"){const ye=Array.isArray((ke=Z.value)==null?void 0:ke.items)?Z.value.items:[];wn(ye)}else wn([]),bn({ts:on(),kind:"error",title:"Discovery providers failed",preview:en(String(Z.reason||""))});bn({ts:on(),kind:"info",title:"Gateway discovery loaded",preview:en(`workflows: ${ee}`)})}async function Po(v){var T,F;O(""),V(!1),M(!0);try{if(!(v!=null&&v.prefer_direct)&&(await J.refresh(),Ua.current))return;const B=String(n.auth_token||"").trim();if(!B){v!=null&&v.open_modal_if_needed&&J.openModal();return}const Z=String(n.gateway_url||"").trim();if(Z){const ee=Z.toLowerCase();if(!ee.startsWith("http://")&&!ee.startsWith("https://"))throw new Error("Gateway URL must start with http:// or https:// (or leave it blank to use same origin / dev proxy).");try{if(String(((T=window==null?void 0:window.location)==null?void 0:T.protocol)||"")==="https:"&&ee.startsWith("http://"))throw new Error("Gateway URL is http:// but this page is https:// (mixed content is blocked). Use https:// or leave Gateway URL blank to use same origin /api proxy.");const Ge=new URL(Z),ke=String(((F=window==null?void 0:window.location)==null?void 0:F.hostname)||"").trim().toLowerCase(),ye=String(Ge.hostname||"").trim().toLowerCase(),Fe=Pe=>Pe==="localhost"||Pe==="127.0.0.1"||Pe==="::1";if(Fe(ye)&&ke&&!Fe(ke))throw new Error("Gateway URL points to localhost, which from this device is not your machine. Use the gateway's public URL (e.g. an ngrok https URL) or leave Gateway URL blank to use same origin /api proxy.")}catch(oe){throw new Error(String((oe==null?void 0:oe.message)||oe||"Invalid Gateway URL"))}}const X=new qy({base_url:Z,auth_token:B});await X.list_bundles(),r(ee=>({...ee,gateway_auth_mode:"direct"})),await Ec(X)}catch(B){O(Nw(B,n))}finally{M(!1)}}const Ua=p.useRef(!1),ro=p.useRef(0),Fs=p.useRef(!1);function Uf(v){var F,B,Z;te(v);const T=!!(v&&v.has_session&&((F=v.gateway)!=null&&F.ok));if(Ua.current=T,T){if(Fs.current=!1,L&&n.gateway_auth_mode==="direct")return;const X=String(((Z=(B=v==null?void 0:v.gateway)==null?void 0:B.principal)==null?void 0:Z.user_id)||"").trim();if(r(ee=>({...ee,gateway_auth_mode:"session",auth_token:"",gateway_user:X||ee.gateway_user})),L&&n.gateway_auth_mode==="session")return;O(""),M(!0),Ec(new qy({base_url:"",auth_token:""})).catch(ee=>O(Nw(ee,n))).finally(()=>M(!1));return}v&&!v.has_session&&(n.gateway_auth_mode==="session"&&fi({keep_session:!0}),String(n.auth_token||"").trim()&&!L&&!Fs.current&&(Fs.current=!0,Po({prefer_direct:!0})))}async function Wf(){if(!(xt||H)){Et(!0);try{await Ke.reload_bundles();const v=await Ke.list_bundles(),T=Ss(v);Mt(T),bn({ts:on(),kind:"info",title:"Bundles reloaded",preview:en(`workflows: ${T.length}`)})}catch(v){const T=String((v==null?void 0:v.message)||v||"Bundle reload failed");bn({ts:on(),kind:"error",title:"Bundle reload failed",preview:en(T),data:{error:T}})}finally{Et(!1)}}}async function qf(v){if(Ni||H||!L)return;const T=v;if(T){nr(!0),En("");try{const F=await Ke.upload_bundle(T,{overwrite:!1,reload:!0});bn({ts:on(),kind:"info",title:"Bundle uploaded",preview:en(String((F==null?void 0:F.bundle_ref)||""))});const B=await Ke.list_bundles(),Z=Ss(B);Mt(Z)}catch(F){const B=String((F==null?void 0:F.message)||F||"Upload failed");En(B),bn({ts:on(),kind:"error",title:"Upload .flow failed",preview:en(B),data:{error:B}})}finally{nr(!1);try{vo.current&&(vo.current.value="")}catch{}}}}function fi(v){ro.current+=1,v!=null&&v.keep_session||(J.signOut().catch(()=>{}),Ua.current=!1),Pl(),$(""),x(""),yr(""),R(null),K(""),W(!1),Mt([]),yn([]),Gs([]),gt(null),fe(null),Ie(0),ot([]),wn([]),sn({}),O(""),V(!1),te(null),r(T=>({...T,auth_token:""})),bn({ts:on(),kind:"info",title:"Gateway disconnected"})}async function Or(v){const T=String(v??"");T&&zs(await Em(T)?"Copied to clipboard":UN,2)}p.useEffect(()=>{const v=l.trim();if(!Vt||!v)return;let T=!1;const F=async()=>{if(!(at.current>Date.now()))try{const Z=await Ke.get_run(v);T||Nt(Z)}catch{}};F();const B=window.setInterval(F,2e3);return()=>{T=!0,window.clearInterval(B)}},[Vt,l,Ke]),p.useEffect(()=>{if(!L)return;let v=null,T=!1,F=!1;const B=ee=>{T||(v!==null&&window.clearTimeout(v),v=window.setTimeout(()=>void Z(),ee))},Z=async()=>{if(F)return;const ee=at.current-Date.now();if(ee>0){B(ee+500);return}F=!0;const oe=Date.now();try{await Pn(Ke)}finally{F=!1;const Ge=Date.now()-oe,ke=document.visibilityState==="hidden"?3e4:5e3;B(Math.max(ke,Ge*3))}},X=()=>{document.visibilityState==="visible"&&Z()};return Z(),document.addEventListener("visibilitychange",X),()=>{T=!0,v!==null&&window.clearTimeout(v),document.removeEventListener("visibilitychange",X)}},[L,Ke]);const[Ac,Tc]=p.useState(null);p.useEffect(()=>{if(!L){Tc(null);return}let v=!1;return(async()=>{try{const T=await Ke.get_entity_phases_spec();if(v)return;const F=wU(T);if(Tc(F),F)try{const B=localStorage.getItem("abstractobserver_phase_graph_id_v1"),Z=B?JSON.parse(B):null;Z&&Z.sha256&&F.sha256&&Z.sha256!==F.sha256&&Z.version===F.version&&bn({ts:on(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:en(`v${F.version}: ${String(Z.sha256).slice(0,12)}… -> ${String(F.sha256).slice(0,12)}…`),data:{prev:Z,now:{sha256:F.sha256,version:F.version}}}),localStorage.setItem("abstractobserver_phase_graph_id_v1",JSON.stringify({sha256:F.sha256,version:F.version}))}catch{}}catch(T){if(!v){Tc(null);const F=String((T==null?void 0:T.message)||T||"");/404|not found/i.test(F)||bn({ts:on(),kind:"info",title:"Phase-graph fetch failed — pre-wire fallback vocabulary in use (#FALLBACK)",preview:en(F),data:{error:F}})}}})(),()=>{v=!0}},[L]),p.useEffect(()=>{if(!L){fe(null),Ie(0),Ue("");return}let v=!1,T=null;const F=async()=>{if(!(at.current>Date.now())){try{const B=await Ke.list_entities();v||Ie(B.entities.length);const Z=B.entities.map(ee=>String((ee==null?void 0:ee.name)||(ee==null?void 0:ee.slug)||"").trim()).filter(Boolean).slice(0,_C),X=await Promise.all(Z.map(async ee=>{var oe,Ge;try{const[ke,ye]=await Promise.all([Ke.get_entity_card(ee),Ke.get_entity_cognition(ee).catch(()=>null)]),Fe=ke!=null&&ke.state&&typeof ke.state=="object"?ke.state:null,Pe=Array.isArray(ke==null?void 0:ke.moments)?ke.moments:[],st=Pe.length?Pe[Pe.length-1]:null,pt=(oe=ye==null?void 0:ye.spend)==null?void 0:oe.lifetime,lt=(Ge=ye==null?void 0:ye.spend)==null?void 0:Ge.live_visit,vn=Array.isArray(ye==null?void 0:ye.warnings)?ye.warnings.map(ft=>String(ft||"")).filter(Boolean):[],qt=pU(ke);return{name:ee,state:String((Fe==null?void 0:Fe.state)??(typeof(ke==null?void 0:ke.state)=="string"?ke.state:"")).trim(),age_days:typeof(ke==null?void 0:ke.age_days)=="number"?ke.age_days:null,last_moment:String((st==null?void 0:st.kind)||"").trim(),last_moment_at:String((st==null?void 0:st.at)||"").trim(),working:typeof(ye==null?void 0:ye.working)=="boolean"?ye.working:null,tokens_total:typeof(pt==null?void 0:pt.tokens_total)=="number"?pt.tokens_total:null,live_visit_tokens:typeof(lt==null?void 0:lt.tokens_total)=="number"?lt.tokens_total:null,spend_warning:vn.join(" | "),live_phase:typeof(ye==null?void 0:ye.phase)=="string"?ye.phase:"",open_questions:qt.questions,open_questions_total:qt.questions_total,open_problems:qt.problems,open_problems_total:qt.problems_total,lessons:qt.lessons,lessons_total:qt.lessons_total,dreams_brief:_U(ke),error:""}}catch(ke){return{name:ee,state:"",age_days:null,last_moment:"",last_moment_at:"",working:null,tokens_total:null,live_visit_tokens:null,spend_warning:"",live_phase:"",open_questions:[],open_questions_total:0,open_problems:[],open_problems_total:0,lessons:[],lessons_total:0,dreams_brief:null,error:String((ke==null?void 0:ke.message)||ke||"card failed")}}}));v||(fe(X),Ie(B.entities.length),Ue(""))}catch(B){if(!v){fe([]);const Z=String((B==null?void 0:B.message)||B||"");Ue(/404|not found/i.test(Z)?"":Z)}}v||(T=window.setTimeout(()=>void F(),3e4))}};return F(),()=>{v=!0,T!==null&&window.clearTimeout(T)}},[L,Ke]);async function Hf(v,T,F){const B=String(T||"").trim();if(!v||!B)throw new Error("This wait has no wait_key yet — open the run to inspect.");await Ke.submit_command({command_id:Xs(),run_id:v,type:"resume",payload:{wait_key:B,payload:F||{}},client_id:"web_pwa"}),bn({ts:on(),kind:"info",title:"Board resume submitted",preview:en(`run ${v} · wait ${B}`),data:{run_id:v,wait_key:B}}),Pn(Ke,{force:!0}),window.setTimeout(()=>void Pn(Ke,{force:!0}),1200)}const ra=p.useMemo(()=>{const v=we==null?void 0:we.session_id;return typeof v=="string"?v.trim():v==null?"":String(v||"").trim()},[we]),i_=p.useMemo(()=>{const v=String(ra||"").trim();return v||String(P||"").trim()},[ra,P]);p.useEffect(()=>{L||Pt("")},[L]);const[Mc,o_]=HN(),Vf=VN(L?Ke:null,L),io=GN({gateway:L?Ke:null,session_id:i_,prefs:Mc,on_error:Pt,on_transcript:v=>{const T=String(v||"").trim();T&&(De(F=>{const B=String(F||"");return B.trim()?`${B.trimEnd()}
172
+ ${T}`:T}),window.setTimeout(()=>{var F;return(F=Mr.current)==null?void 0:F.focus()},0))}}),a_=p.useMemo(()=>{for(let v=Ft.length-1;v>=0;v-=1){const T=Ft[v];if(T.role==="assistant")return T.local_error?null:{key:String(T.id||T.ts||""),text:String(T.content||"")}}return null},[Ft]);KN(io,Mc.read_aloud===!0,a_);function l_(v,T){try{const F=URL.createObjectURL(v),B=document.createElement("a");B.href=F,B.download=T||"download",B.rel="noreferrer",document.body.appendChild(B),B.click(),document.body.removeChild(B),window.setTimeout(()=>URL.revokeObjectURL(F),5e3)}catch{}}async function Ol(){const v=Wm.trim();if(!v){zs("This run recorded no workspace",2);return}try{const T=await fetch(oI,{method:"POST",headers:{"Content-Type":"application/json",...nv()},body:JSON.stringify({path:v})}),F=await T.json().catch(()=>({}));T.ok&&(F!=null&&F.ok)?zs(`Opened ${String(F.path||v)}`,2):zs(String((F==null?void 0:F.error)||`Folder reveal failed (${T.status})`),3)}catch(T){zs(String((T==null?void 0:T.message)||T||"Folder reveal failed"),3)}}async function c_(v){const T=String((v==null?void 0:v.run_id)||"").trim(),F=String((v==null?void 0:v.artifact_id)||"").trim();if(!T||!F){zs("Artifact download needs a run id",3);return}const B=tg(v)||F;try{const Z=await Ke.download_run_artifact_content(T,F,{access:"preview"});l_(Z,c0(B)),zs("Downloaded artifact",2)}catch(Z){zs(String((Z==null?void 0:Z.message)||Z||"Download failed"),3)}}async function Zu(v){const T=String((v==null?void 0:v.run_id)||"").trim(),F=String((v==null?void 0:v.artifact_id)||"").trim();if(!T||!F){zs("Artifact preview needs a run id",3);return}const B=tg(v),Z=String((v==null?void 0:v.content_type)||"").trim().toLowerCase(),X=Gh(v);if(Lo(B||F),sa(""),Qi(""),$l(X),El(v),Nl(!0),ir&&(URL.revokeObjectURL(ir),Wu("")),X==="binary"){sa(`(Binary artifact: ${Z||"unknown"}; download to view.)`);return}if(X==="text"&&typeof v.size_bytes=="number"&&v.size_bytes>15e5){sa(`(Text artifact is ${v.size_bytes.toLocaleString()} bytes; download to view.)`);return}br(!0);try{const ee=await Ke.download_run_artifact_content(T,F,{access:"preview"});if(X==="text"){const oe=await ee.text(),Ge=eg(v,oe),ke=Ge==="json"?15e5:Ge==="markdown"?25e4:Ge==="html"?3e5:22e3;sa(oe.length>ke&&Ge!=="text"?`${su(v.size_bytes??oe.length)} ${Ge.toUpperCase()} artifact. Download to inspect it.`:oe.length>ke?`${oe.slice(0,Math.max(0,ke-1))}…`:oe)}else Wu(URL.createObjectURL(ee))}catch(ee){Qi(String((ee==null?void 0:ee.message)||ee||"Preview failed"))}finally{br(!1)}}p.useEffect(()=>()=>{ir&&URL.revokeObjectURL(ir)},[ir]);async function Qu(v){const T=String(v.artifact_id||"").trim(),F=String(v.run_id||"").trim(),B=Gh(v);if(!F||!T)return{artifact_id:T,kind:B,render_kind:"",text:"Preview needs artifact run metadata.",url:"",loading:!1,error:""};if(B==="binary")return{artifact_id:T,kind:B,render_kind:"",text:`Preview unavailable for ${v.content_type||v.modality||"this artifact"}. Download to inspect it.`,url:"",loading:!1,error:""};if(B==="text"&&typeof v.size_bytes=="number"&&v.size_bytes>5e5)return{artifact_id:T,kind:B,render_kind:"",text:`${su(v.size_bytes)} text artifact. Use Preview for a larger view or Download to inspect locally.`,url:"",loading:!1,error:""};try{const Z=await Ke.download_run_artifact_content(F,T,{access:"preview"});if(B==="text"){const X=await Z.text(),ee=eg(v,X),oe=ee==="json"?5e5:ee==="markdown"?12e4:ee==="html"?3e5:8e3;return{artifact_id:T,kind:B,render_kind:ee,text:X.length>oe&&ee!=="text"?`${su(v.size_bytes??X.length)} ${ee.toUpperCase()} artifact. Use Larger preview or Download to inspect it.`:X.length>oe?`${X.slice(0,Math.max(0,oe-1))}…`:X,url:"",loading:!1,error:""}}return{artifact_id:T,kind:B,render_kind:"",text:"",url:URL.createObjectURL(Z),loading:!1,error:""}}catch(Z){return{artifact_id:T,kind:B,render_kind:"",text:"",url:"",loading:!1,error:String((Z==null?void 0:Z.message)||Z||"Preview failed")}}}async function u_(v){if(Ro.url&&URL.revokeObjectURL(Ro.url),!v){zu(Nf());return}const T=String(v.artifact_id||"").trim(),F=Gh(v);zu({artifact_id:T,kind:F,render_kind:"",text:"",url:"",loading:!0,error:""}),zu(await Qu(v))}function bn(v){const T=String(v.id||"").trim()||Xs();hf(F=>[{...v,id:T},...F].slice(0,800))}function zs(v,T){fl(v),ii.current&&window.clearTimeout(ii.current),Wi(!1),window.requestAnimationFrame(()=>Wi(!0)),ii.current=window.setTimeout(()=>{Wi(!1),ii.current=null},1500),ko.current&&(window.clearTimeout(ko.current),ko.current=null),T>0&&(ko.current=window.setTimeout(()=>{fl(""),ko.current=null},Math.max(1,T)*1e3))}function ar(v,T){const F=String(v||"").trim(),B=String(T||"").trim();if(!B)return"";const Z=F?String(wc.current[F]||"").trim():"";return Z?`${Z}::${B}`:B}function ed(v,T,F){const B=String(v||"").trim(),Z=String(T||"").trim(),X=String(F||"").trim();if(!B||!Z||!X)return;const ee=ar(B,Z);ee&&(wc.current[X]=ee,Vr.current[X]=B,vc.current[X]={parent_run_id:B,parent_node_id:Z},Ia.current.has(X)||(Ia.current.add(X),Lu(oe=>oe.includes(X)?oe:[...oe,X])))}function Rc(v){const T=String(v||"").trim();if(!T)return;const F=Date.now(),B=So.current;So.current=T,Ra(F),La(Z=>{const X={};for(const[ke,ye]of Object.entries(Z))typeof ye=="number"&&ye>F&&(X[ke]=ye);X[T]=Math.max(X[T]||0,F+2e3),B&&B!==T&&(X[B]=Math.max(X[B]||0,F+2e3));const ee=Object.keys(X);if(ee.length<=200)return X;const oe=ee.sort((ke,ye)=>(X[ye]||0)-(X[ke]||0)).slice(0,200),Ge={};for(const ke of oe)Ge[ke]=X[ke]||0;return Ge}),Ru(Z=>{if(typeof Z[T]=="number")return Z;const X={...Z,[T]:F};if(vl.current.push(T),vl.current.length>8e3){const ee=vl.current.splice(0,1500);for(const oe of ee)delete X[oe]}return X}),Hr.current&&window.clearTimeout(Hr.current),Hr.current=window.setTimeout(()=>{const Z=Date.now();La(X=>{const ee={};for(const[oe,Ge]of Object.entries(X))typeof Ge=="number"&&Ge>Z&&(ee[oe]=Ge);return ee}),Ra(Z),Hr.current=null},2200)}function td(v,T){var lt,vn,qt;const F=String(T||"").trim()||l.trim();Er.current=v.cursor,(lt=Cs.current)==null||lt.push({cursor:v.cursor,record:v.record}),F&&Ci.current.add(`${F}:${v.cursor}`);const B=op(v.record),Z=B&&B.name?Rh(B.name):"",X=v.record,ee=typeof(X==null?void 0:X.node_id)=="string"?X.node_id:"",oe=typeof(X==null?void 0:X.status)=="string"?X.status:"",Ge=typeof((vn=X==null?void 0:X.effect)==null?void 0:vn.type)=="string"?X.effect.type:"",ke=typeof(X==null?void 0:X.run_id)=="string"?X.run_id:"",ye=ke||F;if(Z==="abstract.status"&&ye===F){const{text:ft,duration:Qt}=xd(B==null?void 0:B.payload);zs(ft,Qt)}const Fe=ee?ar(ye,ee):"";if(oe==="waiting"){const ft=Ya(X);if(String((ft==null?void 0:ft.reason)||"").trim()==="subworkflow"){const Jn=typeof((qt=ft==null?void 0:ft.details)==null?void 0:qt.sub_run_id)=="string"?String(ft.details.sub_run_id):"";Jn&&ee&&ed(ye,ee,Jn)}}if(ee&&(Rc(ar(ye,ee)),oe==="waiting"||oe==="running")){const ft=ar(ye,ee);ft&&(So.current=ft,Zo(ft))}let Pe="step",st=Fe||ee||"(node?)",pt="";if(B&&B.name&&Sw(B.name))Pe=Z==="abstract.message"?"message":"event",st=Z||B.name,pt=en(Z==="abstract.steer_seen"?jw(B==null?void 0:B.payload):xd(B==null?void 0:B.payload).text);else if(X!=null&&X.error)Pe="error",st="error",pt=en(Fr(X.error,360));else if(oe==="waiting"){const ft=Ya(X),Qt=String((ft==null?void 0:ft.reason)||"").trim();pt=en(Qt?`waiting • ${Qt}`:"waiting")}else X!=null&&X.result?pt=en(Fr(X.result,360)):Ge?pt=en(Ge):pt=en(Ap(X));bn({id:`step:${ke||F||"?"}:${v.cursor}`,ts:String((X==null?void 0:X.ended_at)||(X==null?void 0:X.started_at)||on()),kind:Pe,title:st,preview:pt,data:X,cursor:v.cursor,run_id:ke||F||void 0,node_id:Fe||ee,status:oe,effect_type:Ge,emit_name:Z||(B==null?void 0:B.name)||void 0})}function d_(v,T){var pt,lt,vn;zn.current=Math.max(zn.current,T.cursor);const F=`${v}:${T.cursor}`;if(!!Ci.current.has(F))return;Ci.current.add(F),(pt=gs.current)==null||pt.push({run_id:v,cursor:T.cursor,record:T.record});const Z=op(T.record),X=Z&&Z.name?Rh(Z.name):"",ee=T.record,oe=typeof(ee==null?void 0:ee.node_id)=="string"?ee.node_id:"",Ge=oe?ar(v,oe):"",ke=typeof(ee==null?void 0:ee.status)=="string"?ee.status:"",ye=typeof((lt=ee==null?void 0:ee.effect)==null?void 0:lt.type)=="string"?ee.effect.type:"";if(ke==="waiting"){const qt=Ya(ee);if(String((qt==null?void 0:qt.reason)||"").trim()==="subworkflow"){const Qt=typeof((vn=qt==null?void 0:qt.details)==null?void 0:vn.sub_run_id)=="string"?String(qt.details.sub_run_id):"";Qt&&oe&&ed(v,oe,Qt),Qt&&vr.current.trim()===String(v||"").trim()&&(vr.current=Qt,Ei(Qt))}}if(oe&&(Rc(ar(v,oe)),ke==="waiting"||ke==="running")){const qt=ar(v,oe);qt&&(So.current=qt,Zo(qt))}if((ke==="completed"||ke==="failed")&&vr.current.trim()===String(v||"").trim()){const qt=String(Vr.current[String(v||"").trim()]||"").trim();qt&&qt!==l.trim()?(vr.current=qt,Ei(qt)):(vr.current="",Ei(""))}if(X==="abstract.status"&&v===l.trim()){const{text:qt,duration:ft}=xd(Z==null?void 0:Z.payload);zs(qt,ft)}let Fe="step",Pe=Ge||oe||"(node?)",st="";if(Z&&Z.name&&Sw(Z.name))Fe=X==="abstract.message"?"message":"event",Pe=`subrun • ${X||Z.name}`,st=en(X==="abstract.steer_seen"?jw(Z==null?void 0:Z.payload):xd(Z==null?void 0:Z.payload).text);else if(ee!=null&&ee.error)Fe="error",Pe="error",st=en(Fr(ee.error,360));else if(ke==="waiting"){const qt=Ya(ee),ft=String((qt==null?void 0:qt.reason)||"").trim();st=en(ft?`waiting • ${ft}`:"waiting")}else ee!=null&&ee.result?st=en(Fr(ee.result,360)):ye?st=en(ye):st=en(Ap(ee));bn({id:`step:${v}:${T.cursor}`,ts:String((ee==null?void 0:ee.ended_at)||(ee==null?void 0:ee.started_at)||on()),kind:Fe,title:Pe,preview:st,data:ee,cursor:T.cursor,run_id:v,node_id:Ge||oe,status:ke,effect_type:ye,emit_name:X||(Z==null?void 0:Z.name)||""})}function f_(v,T){var lt,vn,qt;const F=String(v||"").trim();if(!F)return;const B=`${F}:${T.cursor}`;if(!!Ci.current.has(B))return;Ci.current.add(B),(lt=gs.current)==null||lt.push({run_id:F,cursor:T.cursor,record:T.record});const X=op(T.record),ee=X&&X.name?Rh(X.name):"",oe=T.record,Ge=typeof(oe==null?void 0:oe.node_id)=="string"?oe.node_id:"",ke=Ge?ar(F,Ge):"",ye=typeof(oe==null?void 0:oe.status)=="string"?oe.status:"",Fe=typeof((vn=oe==null?void 0:oe.effect)==null?void 0:vn.type)=="string"?oe.effect.type:"";if(ye==="waiting"){const ft=Ya(oe);if(String((ft==null?void 0:ft.reason)||"").trim()==="subworkflow"){const Jn=typeof((qt=ft==null?void 0:ft.details)==null?void 0:qt.sub_run_id)=="string"?String(ft.details.sub_run_id):"";Jn&&Ge&&ed(F,Ge,Jn)}}if(Ge&&(Rc(ar(F,Ge)),ye==="waiting"||ye==="running")){const ft=ar(F,Ge);ft&&(So.current=ft,Zo(ft))}if(ee==="abstract.status"&&F===l.trim()){const{text:ft,duration:Qt}=xd(X==null?void 0:X.payload);zs(ft,Qt)}let Pe="step",st=ke||Ge||"(node?)",pt="";if(X&&X.name&&Sw(X.name))Pe=ee==="abstract.message"?"message":"event",st=`subrun • ${ee||X.name}`,pt=en(ee==="abstract.steer_seen"?jw(X==null?void 0:X.payload):xd(X==null?void 0:X.payload).text);else if(oe!=null&&oe.error)Pe="error",st="error",pt=en(Fr(oe.error,360));else if(ye==="waiting"){const ft=Ya(oe),Qt=String((ft==null?void 0:ft.reason)||"").trim();pt=en(Qt?`waiting • ${Qt}`:"waiting")}else oe!=null&&oe.result?pt=en(Fr(oe.result,360)):Fe?pt=en(Fe):pt=en(Ap(oe));bn({id:`step:${F}:${T.cursor}`,ts:String((oe==null?void 0:oe.ended_at)||(oe==null?void 0:oe.started_at)||on()),kind:Pe,title:st,preview:pt,data:oe,cursor:T.cursor,run_id:F,node_id:ke||Ge,status:ye,effect_type:Fe,emit_name:ee||(X==null?void 0:X.name)||""})}async function Gf(v,T){var B,Z;let F=T.after;for(;;){if((B=T.signal)!=null&&B.aborted)return F;const X=await Ke.get_ledger(v,{after:F,limit:200,signal:T.signal});if((Z=T.signal)!=null&&Z.aborted)return F;const ee=Array.isArray(X.items)?X.items:[];if(!ee.length)return Er.current=F,F;const oe=F;for(let Ge=0;Ge<ee.length;Ge++){const ke=ee[Ge];td({cursor:oe+Ge+1,record:ke},v)}F=typeof X.next_after=="number"?X.next_after:F}}async function nd(v){var X,ee,oe,Ge;const T=String(v||"").trim();En(""),Zt(!0),rs(!1),(X=Cs.current)==null||X.reset(),(ee=gs.current)==null||ee.reset(),mr.current={scanned:0,found:null},Xe([]),Er.current=0,cn([]),Ci.current=new Set,hf([]),Um(""),fl(""),Nt(null),oi(""),bf(""),Zo(""),So.current="",La({}),Ru({}),vl.current=[],Ra(Date.now()),wc.current=T?{[T]:""}:{},Vr.current={},vc.current={},Ia.current=new Set,Lu([]),$o.current="",vr.current="",Ei(""),Qo.current={},Hr.current&&window.clearTimeout(Hr.current),Hr.current=null,sr.current&&window.clearTimeout(sr.current),sr.current=null,Co.current&&Co.current.abort(),wr.current&&wr.current.abort(),wr.current=null,zn.current=0,bl("");const F=new AbortController;Co.current=F;let B=!1;try{let ke="",ye="";try{const Fe=await Ke.get_run(T);Nt(Fe);const Pe=typeof(Fe==null?void 0:Fe.workflow_id)=="string"?String(Fe.workflow_id):"",st=Cj(Pe);st&&(ke=st.bundle_id,ye=st.flow_id)}catch{}try{const Fe=await Ke.get_run_input_data(T);typeof(Fe==null?void 0:Fe.bundle_id)=="string"&&(ke=String(Fe.bundle_id||"").trim()||ke),typeof(Fe==null?void 0:Fe.flow_id)=="string"&&(ye=String(Fe.flow_id||"").trim()||ye);const Pe=Fe&&typeof Fe.input_data=="object"&&Fe.input_data&&!Array.isArray(Fe.input_data)?Fe.input_data:null;Pe&&S(JSON.stringify(Pe,null,2));const st=Fe==null?void 0:Fe.workspace,pt=typeof(st==null?void 0:st.workspace_root)=="string"?String(st.workspace_root).trim():"";bf(pt)}catch{bf("")}ke&&ye&&($(ke),x(ye),yr(ye),await as(ke)),await Gf(T,{after:0,signal:F.signal});try{const Fe=await Ke.get_run_history_bundle(T,{include_subruns:!0,include_session:!1,ledger_mode:"tail",ledger_max_items:1}),Pe=Fe&&typeof Fe=="object"?Fe.ledgers:null,pt=(Pe&&typeof Pe=="object"?Object.keys(Pe):[]).map(lt=>String(lt||"").trim()).filter(Boolean).filter(lt=>lt!==T);if(pt.length){for(const lt of pt)Ia.current.add(lt);Lu(lt=>Array.from(new Set([...lt,...pt])));try{const lt=typeof((oe=Pe==null?void 0:Pe[T])==null?void 0:oe.total)=="number"?Number(Pe[T].total):0;let vn="",qt=-1;for(const ft of pt){const Qt=typeof((Ge=Pe==null?void 0:Pe[ft])==null?void 0:Ge.total)=="number"?Number(Pe[ft].total):0;Qt>qt&&(vn=ft,qt=Qt)}vn&&qt>Math.max(lt*3,lt+20)&&(vr.current=vn,Ei(vn))}catch{}}}catch{}rs(!0),bn({ts:on(),kind:"info",title:`Attached to run ${T}`,data:{run_id:T}}),B=!0}catch(ke){if(F.signal.aborted||String((ke==null?void 0:ke.name)||"")==="Superseded")return;const ye=String((ke==null?void 0:ke.message)||ke||"unknown error");En(ye),bn({ts:on(),kind:"error",title:"Connection error",preview:en(ye),data:{error:ye}}),rs(!1)}finally{F.signal.aborted||Zt(!1)}if(!B||F.signal.aborted)return;(async()=>{let ke=250;for(;!F.signal.aborted;){try{const ye=await Gf(T,{after:Er.current,signal:F.signal});await Ke.stream_ledger(T,{after:ye,on_step:Fe=>td(Fe,T),signal:F.signal})}catch(ye){if(F.signal.aborted)break;const Fe=String((ye==null?void 0:ye.message)||ye||"stream error");bn({ts:on(),kind:"error",title:"Ledger stream error (will retry)",preview:en(Fe),data:{error:Fe}})}if(F.signal.aborted)break;await new Promise(ye=>setTimeout(ye,ke)),ke=Math.min(5e3,Math.floor(ke*1.6))}})()}async function h_(){const v=kr,T=(v==null?void 0:v.kind)==="bundle"?v.flow_id:(v==null?void 0:v.kind)==="default"?"@default":"",F=(v==null?void 0:v.kind)==="bundle"?v.bundle_id:"";if(!v){const B="Select a workflow first (Launch → pick a workflow).";return En(B),B}En(""),Zt(!0);try{let B={};const Z=E.trim();if(Z)try{if(B=JSON.parse(Z),typeof B!="object"||B===null||Array.isArray(B))throw new Error("input_data must be a JSON object")}catch(Fe){const Pe=`Invalid input_data JSON: ${String((Fe==null?void 0:Fe.message)||Fe)}`;return En(Pe),Pe}for(const[Fe,Pe]of Object.entries(B)){if(typeof Pe!="string")continue;const st=Pe.trim();st?B[Fe]=st:delete B[Fe]}const X=(Jr||[]).find(Fe=>Fe&&typeof Fe=="object"&&Fe.id==="prompt"),ee=X&&typeof X=="object"&&Object.prototype.hasOwnProperty.call(X,"default"),oe=B==null?void 0:B.prompt,Ge=typeof oe=="string"?oe.trim():"";if(X&&!ee&&!Ge){const Fe="Missing required input_data.prompt";return En(Fe),Fe}const ke=B.workspace&&typeof B.workspace=="object"?B.workspace:null;delete B.workspace;const ye=await Ke.start_run(T,B,{...ke?{workspace:ke}:{},...F?{bundle_id:F}:{},...v.kind==="default"?{interface:v.interface}:{},session_id:String(P||"").trim()||null});return m(ye),d(ye),tr(""),await nd(ye),Pn(),null}catch(B){const Z=String((B==null?void 0:B.message)||B||"start failed");return En(Z),Z}finally{Zt(!1)}}async function Yg(){if(Dt([]),Le(null),!pe.available){Dt([pe.reason]);return}const v=w3(Ve,{choice:kr,bundle_ref_for:T=>{var F;return((F=Ot.find(B=>B.bundle_id===T))==null?void 0:F.bundle_ref)||""},input_data:rn,email_usable:Bn.email_usable,defaults:Oo,mailboxes:li.mailboxes,connections:li.trigger_connections},Se.current);if(!v.ok){Dt(v.errors);return}Q(!0);try{const T=await Ke.automations_client().createAutomation(v.body);Se.current.reset(),le([]),ct(Yw),Tl.current="",bn({ts:on(),kind:"info",title:"Automation created",preview:en(`${v.body.title} · ${T.automation_id}`)}),Ae(!1),t("automations"),await Bn.refresh(),await Bn.select(T.automation_id)}catch(T){const F=(T&&typeof T=="object"&&typeof T.code=="string"?T:null)||{status:0,code:"client_error",message:String((T==null?void 0:T.message)||T||"Create failed")};Le(F)}finally{Q(!1)}}async function Xg(){if(tr(""),je==="automate"){await Yg();return}const v=await h_();if(v){tr(v);return}Ae(!1),jo("ledger"),t("observe")}async function Kf(v){if(Zn("skills",void 0),!!v){if(v.kind==="default"){ze(v.interface),$(""),x(""),R(null);return}ze(""),$(v.bundle_id),x(v.flow_id),yr(v.flow_id),await as(v.bundle_id)}}async function Jf(v){const[T,F]=await Promise.all([Ke.get_run(v),Ke.get_run_input_data(v)]),B=$3(T,F);await Kf(B.choice),S(JSON.stringify(B.input_data,null,2)),ct(B.form),le([`Recreating the legacy schedule ${Rn(v,14)} as an automation. The legacy schedule keeps running until you suspend it.`,...B.notes]),Se.current.reset(),nt("automate")}async function Mi(v,T){const F=String(v||"").trim();if(!F)return;if(Be){zs(`Still attaching — retry in a moment (${Rn(F,14)})`,2500);return}En(""),b("");const B=String((T==null?void 0:T.root_run_id)||F).trim()||F;m(B),d(F),await nd(F)}p.useEffect(()=>{const v=String(_||"").trim();if(!v)return;let T=!1;return(async()=>{try{if(L||await Po({open_modal_if_needed:!0}),T)return;jo("ledger"),t("observe");const F=await Ke.find_run(v);if(T)return;if(F===null){Pl(),b(v);return}await Mi(v),Ul()}catch(F){T||En(String((F==null?void 0:F.message)||F||"Failed to attach run from URL"))}finally{T||g("")}})(),()=>{T=!0}},[_]);function Pl(){var v,T;Co.current&&Co.current.abort(),Co.current=null,wr.current&&wr.current.abort(),wr.current=null,zn.current=0,bl(""),d(""),m(""),wc.current={},Vr.current={},vc.current={},Ia.current=new Set,Lu([]),$o.current="",vr.current="",Ei(""),Qo.current={},oi(""),Hr.current&&window.clearTimeout(Hr.current),Hr.current=null,sr.current&&window.clearTimeout(sr.current),sr.current=null,rs(!1),Zt(!1),Dn(!1),Er.current=0,(v=Cs.current)==null||v.reset(),(T=gs.current)==null||T.reset(),mr.current={scanned:0,found:null},Xe([]),cn([]),Ci.current=new Set,Nt(null),hf([]),Zo(""),So.current="",La({}),Ru({}),vl.current=[],Ra(Date.now()),zs("",-1),En(""),xn([]),Hn(null),De(""),ht(""),pn(!1),qi(!1),Hi(""),hc(""),Ea(""),mc([]),bu(!1),ku(""),ju(""),ml(!1),Aa("")}p.useEffect(()=>{xn([]),Hn(null),De(""),ht(""),pn(!1),qi(!1),Hi(""),hc(""),Ea(""),mc([]),bu(!1),ku(""),ju(""),ml(!1),Aa("")},[l]),p.useEffect(()=>{js==="chat"&&l.trim()&&L&&Ic()},[js,l,L,we==null?void 0:we.workflow_id]);async function Lc(v,T,F){const B=String(v||"").trim();if(!B)return En("Missing run_id"),"Missing run_id";En("");try{const Z={},X=String((F==null?void 0:F.reason)||"").trim();X&&(Z.reason=X),await Ke.submit_command({command_id:Xs(),run_id:B,type:T,payload:Z,client_id:"web_pwa"}),bn({ts:on(),kind:"info",title:`${T} submitted`,preview:X?`reason: ${X}`:"",data:{run_id:B,type:T,reason:X}});try{if(B===l.trim()){const ee=await Ke.get_run(B);Nt(ee)}}catch{}return Pn(Ke,{force:!0}),window.setTimeout(()=>void Pn(Ke,{force:!0}),900),window.setTimeout(()=>void Pn(Ke,{force:!0}),2400),null}catch(Z){const X=String((Z==null?void 0:Z.message)||Z||`${T} failed`);return En(X),X}}async function Zg(v,T){const F=v.map(Ge=>String(Ge||"").trim()).filter(Boolean),B=[];let Z=0,X=0,ee=0;const oe=async()=>{for(;ee<F.length;){const Ge=F[ee++];try{await Ke.submit_command({command_id:Xs(),run_id:Ge,type:"cancel",payload:{},client_id:"web_pwa"}),B.push({run_id:Ge,error:null})}catch(ke){X+=1,B.push({run_id:Ge,error:String((ke==null?void 0:ke.message)||ke||"cancel failed")})}Z+=1,T==null||T(Z,X)}};return await Promise.all(Array.from({length:Math.min(4,F.length)},oe)),bn({ts:on(),kind:X?"error":"info",title:`cancel submitted ×${F.length}${X?` · ${X} failed`:""}`,preview:"",data:{run_ids:F,failed:X}}),F.length&&(Pn(Ke,{force:!0}),window.setTimeout(()=>void Pn(Ke,{force:!0}),2400)),B}async function Yf(v,T){return Lc(l.trim(),v,T)}async function hi(v,T="Stopped from AbstractObserver"){const F=String(v||"").trim();if(!F||!window.confirm(`Cancel run ${Rn(F,24)}?`))return;await Lc(F,"cancel",{reason:T})||zs("Cancel submitted",2)}async function Xf(){var F;const v=l.trim();if(!v){En("Select a run first.");return}if(!L){En("Connect to the gateway first.");return}if(Tt)return;const T=String(((F=we==null?void 0:we.waiting)==null?void 0:F.reason)||"").trim().toLowerCase()||String(Bs||"").trim().toLowerCase();if(!Kn||mi||ws||Ns.toLowerCase()!=="waiting"||T!=="until"){En("This run is not a scheduled wait that can be triggered now.");return}En(""),Dn(!0);try{const B={payload:{mode:"run_now",requested_at:on()}},Z=String(lr||"").trim();Z&&(B.wait_key=Z),await Ke.submit_command({command_id:Xs(),run_id:v,type:"resume",payload:B,client_id:"web_pwa"}),bn({ts:on(),kind:"info",title:"Scheduled run triggered",preview:en(`run ${v}`),data:{run_id:v,until:oo||null}});try{const X=await Ke.get_run(v);Nt(X)}catch{}}catch(B){En(String((B==null?void 0:B.message)||B||"Failed to trigger scheduled run"))}finally{Dn(!1)}}async function sd(v){const T=l.trim();if(!T)return En("Missing run_id"),"Missing run_id";if(ri)return"Schedule update already in progress";const F=String(v.interval||"").trim();if(!/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.test(F)){const Z="Invalid interval (expected like '20m', '1h', '0.5s', '250ms')";return ks(Z),Z}ks(""),En(""),Bi(!0),Zt(!0);try{await Ke.submit_command({command_id:Xs(),run_id:T,type:"update_schedule",payload:{interval:F,apply_immediately:v.apply_immediately!==!1},client_id:"web_pwa"}),bn({ts:on(),kind:"info",title:"Schedule updated",preview:en(`interval: ${F}`),data:{interval:F},run_id:T});try{const Z=await Ke.get_run(T);Nt(Z)}catch{}return null}catch(Z){const X=String((Z==null?void 0:Z.message)||Z||"update_schedule failed");return ks(X),En(X),X}finally{Zt(!1),Bi(!1)}}async function m_(v){const T=l.trim();if(!T)return En("Missing run_id"),"Missing run_id";if(Ds)return"Compaction already in progress";const F=typeof(v==null?void 0:v.preserve_recent)=="number"?v.preserve_recent:ul,B=Math.max(0,Math.min(500,Math.floor(Number.isFinite(F)?F:6))),Z=(v==null?void 0:v.compression_mode)||Ar,X=String((v==null?void 0:v.focus)??Ui??"").trim();Ps(""),En(""),pr(!0),Zt(!0);try{const ee={preserve_recent:B,compression_mode:Z};return X&&(ee.focus=X),await Ke.submit_command({command_id:Xs(),run_id:T,type:"compact_memory",payload:ee,client_id:"web_pwa"}),bn({ts:on(),kind:"info",title:"Compaction requested",preview:en(`mode: ${Z} • preserve_recent: ${B}`),data:ee,run_id:T}),null}catch(ee){const oe=String((ee==null?void 0:ee.message)||ee||"compact_memory failed");return Ps(oe),En(oe),oe}finally{Zt(!1),pr(!1)}}async function __(){const v=l.trim();if(!v){ht("Select a run first.");return}if(!L){ht("Connect to the gateway first.");return}const T=Oe.trim();if(!T||Bt)return;if(io.voice_ptt_busy){Pt("Wait for transcription to finish.");return}ht(""),Pt(""),pn(!0);const B={id:`local:${Xs()}`,role:"user",content:T,ts:on()};xn(Z=>[...Z,B]),De("");try{const Z=sI(Ft,B),X=n.maintenance_ai_provider.trim(),ee=n.maintenance_ai_model.trim(),oe=await Ke.run_chat(v,{provider:X||void 0,model:ee||void 0,include_subruns:!0,messages:Z}),Ge=String((oe==null?void 0:oe.answer)||"").trim()||"(empty response)",ke=String((oe==null?void 0:oe.generated_at)||"").trim()||on();Hn((oe==null?void 0:oe.history)??null),xn(ye=>[...ye,{id:`local:${Xs()}`,role:"assistant",content:Ge,ts:ke}])}catch(Z){const X=zI(Z);ht(X),xn(ee=>[...ee,{id:`local:${Xs()}`,role:"assistant",content:`(error: ${X})`,ts:on(),local_error:!0}])}finally{pn(!1)}}function p_(v){const T=String(v.id||v.ts||"").trim(),F=String(v.content||"").trim();!T||!F||(Pt(""),io.toggle_tts(T,F))}function Zf(v){const T=String(v.id||v.ts||"").trim(),F=io.tts_playback;return!T||!F.key||F.key!==T?"idle":F.status}function Wa(v){if(!Ft.length)return;const T=l.trim(),F=T?`Run ${T}`:"Chat",B=KS(Ft.map(Z=>({role:Z.role,content:Z.content,ts:Z.ts})),{heading:F});if(v==="download"){const Z=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),X=`abstractobserver-chat-${c0(T||"run")}-${Z}.md`;JS({filename:X,text:B,mime:"text/markdown;charset=utf-8"});return}(async()=>{const Z=await sl(B);Ks(Z?"copied":"failed"),window.setTimeout(()=>Ks("idle"),900)})()}async function Ic(){const v=typeof(we==null?void 0:we.workflow_id)=="string"?String(we.workflow_id).trim():"";if(!v){mc([]);return}if(L&&!_c){ku(""),bu(!0);try{const T=await Ke.list_runs({limit:200,workflow_id:v,root_only:!0}),F=Array.isArray(T==null?void 0:T.items)?T.items:[],B=[];for(const ke of F){const ye=typeof(ke==null?void 0:ke.run_id)=="string"?String(ke.run_id).trim():"";if(!ye)continue;const Fe=typeof(ke==null?void 0:ke.ledger_len)=="number"?Number(ke.ledger_len):0;B.push({run_id:ye,ledger_len:Number.isFinite(Fe)?Fe:0})}if(!B.length){mc([]);return}const Z=400,X=B.map(ke=>({run_id:ke.run_id,after:Math.max(0,(ke.ledger_len||0)-Z)})),ee=await Ke.get_ledger_batch({runs:X,limit:Z}),oe=[],Ge=new Set;for(const ke of B){const ye=ee!=null&&ee.runs&&typeof ee.runs=="object"?ee.runs[ke.run_id]:null,Fe=Array.isArray(ye==null?void 0:ye.items)?ye.items:[];for(const Pe of Fe){const st=Pe==null?void 0:Pe.effect;if(!st||typeof st!="object"||String(st.type||"")!=="emit_event")continue;const pt=st.payload;if(!pt||typeof pt!="object"||String(pt.name||"")!=="abstract.chat.thread")continue;const lt=pt.payload;if(!lt||typeof lt!="object")continue;const vn=typeof lt.thread_id=="string"?String(lt.thread_id).trim():"";if(!vn||Ge.has(vn))continue;Ge.add(vn);const qt=typeof lt.created_at=="string"?String(lt.created_at):"",ft=typeof lt.title=="string"?String(lt.title):"",Qt=typeof lt.workflow_id=="string"?String(lt.workflow_id):v,Jn=typeof lt.run_id=="string"?String(lt.run_id):ke.run_id,cs=typeof lt.provider=="string"?String(lt.provider):"",ur=typeof lt.model=="string"?String(lt.model):"",gi=typeof lt.message_count=="number"?Number(lt.message_count):null,yi=lt.chat_artifact,Wl=yi&&typeof yi=="object"&&typeof yi.$artifact=="string"?String(yi.$artifact):"";Wl&&oe.push({thread_id:vn,created_at:qt,title:ft||`Chat ${vn.slice(0,8)}`,run_id:Jn,workflow_id:Qt,message_count:gi,provider:cs,model:ur,artifact_id:Wl})}}oe.sort((ke,ye)=>String(ye.created_at||"").localeCompare(String(ke.created_at||""))),mc(oe)}catch(T){ku(String((T==null?void 0:T.message)||T||"Failed to load saved discussions"))}finally{bu(!1)}}}async function Qf(){const v=l.trim();if(!v){Hi("Select a run first.");return}if(!L){Hi("Connect to the gateway first.");return}if(Ft.length&&!gr){Hi(""),qi(!0);try{const T=n.maintenance_ai_provider.trim(),F=n.maintenance_ai_model.trim(),B=await Ke.save_chat_thread(v,{provider:T||void 0,model:F||void 0,include_subruns:!0,messages:Ft.map(ee=>({role:ee.role,content:ee.content,ts:ee.ts}))}),Z=typeof(B==null?void 0:B.created_at)=="string"?String(B.created_at):on();hc(Z);try{const ee=JSON.stringify(Ft.map(oe=>({role:oe.role,content:oe.content,ts:oe.ts})));Ea(ee)}catch{Ea("1")}typeof(B==null?void 0:B.thread_id)=="string"&&String(B.thread_id).trim()&&ju(String(B.thread_id).trim());const X=!!(B!=null&&B.duplicate);zs(X?"Already saved":"Saved discussion",2),await Ic()}catch(T){Hi(String((T==null?void 0:T.message)||T||"Failed to save discussion"))}finally{qi(!1)}}}async function Qg(){const v=String(df||"").trim();if(!v)return;const T=cf.find(Z=>String(Z.thread_id||"").trim()===v)||null;if(!T){Aa("Saved discussion not found (refresh list).");return}if(!L){Aa("Connect to the gateway first.");return}if(Su)return;const F=Ft.length>0,B=(()=>{if(!F)return!1;if(!Ca)return!0;try{return JSON.stringify(Ft.map(X=>({role:X.role,content:X.content,ts:X.ts})))!==Ca}catch{return!0}})();if(!(F&&B&&!window.confirm("Replace the current chat with the selected saved discussion? Unsaved changes will be lost."))){Aa(""),ml(!0);try{const X=await(await Ke.download_run_artifact_content(T.run_id,T.artifact_id)).text(),ee=JSON.parse(X),oe=Array.isArray(ee==null?void 0:ee.messages)?ee.messages:[],Ge=typeof(ee==null?void 0:ee.created_at)=="string"?String(ee.created_at):String(T.created_at||""),ke=[];for(let ye=0;ye<oe.length;ye++){const Fe=oe[ye];if(!Fe||typeof Fe!="object")continue;const Pe=String(Fe.role||"").trim()==="assistant"?"assistant":"user",st=typeof Fe.content=="string"?String(Fe.content):"";if(!st.trim())continue;const pt=typeof Fe.ts=="string"?String(Fe.ts):Ge||on();ke.push({id:`thread:${v}:${ye}`,role:Pe,content:st.trim(),ts:pt})}xn(ke),Hn(null),De(""),ht(""),Hi(""),hc(Ge||"");try{const ye=JSON.stringify(ke.map(Fe=>({role:Fe.role,content:Fe.content,ts:Fe.ts})));Ea(ye)}catch{Ea("1")}zs("Loaded discussion",2)}catch(Z){Aa(String((Z==null?void 0:Z.message)||Z||"Failed to load saved discussion"))}finally{ml(!1)}}}async function Oc(v){const T=l.trim(),F=String((un==null?void 0:un.wait_key)||"").trim();if(!T||!F){En("No active wait to resume");return}if(String((un==null?void 0:un.reason)||"").trim()==="subworkflow"){En("This run is waiting on a subworkflow; attach to the child run instead of resuming manually.");return}En(""),Dn(!0);try{await Ke.submit_command({command_id:Xs(),run_id:T,type:"resume",payload:{wait_key:F,payload:v||{}},client_id:"web_pwa"}),bn({ts:on(),kind:"info",title:"Resume submitted",preview:en(`wait_key: ${F}`),data:{wait_key:F,payload:v||{}}}),oi(F);try{const B=await Ke.get_run(T);Nt(B)}catch{}Pn(Ke,{force:!0}),window.setTimeout(()=>void Pn(Ke,{force:!0}),900),window.setTimeout(()=>void Pn(Ke,{force:!0}),2400),sr.current&&window.clearTimeout(sr.current),sr.current=window.setTimeout(()=>{oi(B=>B===F?"":B)},2e3)}catch(B){En(String((B==null?void 0:B.message)||B||"resume failed"))}finally{Dn(!1)}}async function g_(v){if(!no){En("No worker configured");return}if(!Tt){En(""),Dn(!0);try{const T=[];for(const F of v){const B=await no.call_tool(F);T.push(B)}await Oc({mode:"executed",results:T})}finally{Dn(!1)}}}const ia=p.useMemo(()=>sf(un),[un]),lr=String((un==null?void 0:un.wait_key)||"").trim(),Bs=String((un==null?void 0:un.reason)||"").trim(),oo=typeof(un==null?void 0:un.until)=="string"?String(un.until):"",Ns=typeof(we==null?void 0:we.status)=="string"?String(we.status):"",ws=!!(we!=null&&we.paused),mi=Ns==="completed"||Ns==="failed"||Ns==="cancelled",y_=Bs==="until"&&!!oo,Pc=!mi&&U4(or)&&(!!lr||y_),w_=Bs==="user",rd=Bs==="event"?Rh(KW(lr)):"",eh=Bs==="event"&&rd==="abstract.ask",v_=ia.length>0,id=Pc&&lr&&(w_||eh||v_)&&af!==lr&&e!=="board"&&!(e==="observe"&&js==="agent"),oa=typeof((hd=un==null?void 0:un.details)==null?void 0:hd.sub_run_id)=="string"?String(un.details.sub_run_id):"",Dl={run_id:l.trim(),workflow_id:typeof(we==null?void 0:we.workflow_id)=="string"?String(we.workflow_id):null,status:Ns,created_at:typeof(we==null?void 0:we.created_at)=="string"?String(we.created_at):null,updated_at:typeof(we==null?void 0:we.updated_at)=="string"?String(we.updated_at):null,session_id:typeof(we==null?void 0:we.session_id)=="string"?String(we.session_id):null,current_node:typeof(we==null?void 0:we.current_node)=="string"?String(we.current_node):null},od=fn.slice(-10).map(v=>{var T,F,B,Z,X,ee;return{cursor:v.cursor,node_id:String(((T=v.record)==null?void 0:T.node_id)||"").trim(),status:String(((F=v.record)==null?void 0:F.status)||"").trim(),effect_type:String(((Z=(B=v.record)==null?void 0:B.effect)==null?void 0:Z.type)||"").trim(),ts:String(((X=v.record)==null?void 0:X.ended_at)||((ee=v.record)==null?void 0:ee.started_at)||"").trim(),summary:u1(v.record)}}),ad=dx(un,ia),x_=o1(un,ia),ld=a1(un,rn),Do=ld.text,ey=ld.runtime_metadata,Dc=String((un==null?void 0:un.prompt)||"").trim(),cd=$4(rn,6),b_=!!(Dc&&s1(Dc)),Fl=!!(Dc&&!b_),Fo=Fl?"Question from workflow":Do&&Do!==Dc?"Closest prior user request":"Request context",ty=A4(rn,E),k_=!!E.trim(),jr=we!=null&&we.schedule&&typeof we.schedule=="object"?we.schedule:null,qa=typeof(jr==null?void 0:jr.interval)=="string"?String(jr.interval).trim():"",j_=typeof(jr==null?void 0:jr.share_context)=="boolean"?!!jr.share_context:null,zl=typeof(jr==null?void 0:jr.repeat_count)=="number"?Number(jr.repeat_count):null,Kn=!!(we!=null&&we.is_scheduled)||!!jr,th=Kn&&!!qa,S_=Ns==="running"&&!ws?"Pause":"Resume",Fc=Kn?ws?"resume":"pause":S_==="Pause"?"pause":"resume",cr=Kn?!l.trim()||Be||Tt||mi:!l.trim()||Be||Tt||mi||Fc==="resume"&&!ws,ny=l.trim()?mi?"The schedule has ended.":null:"No run selected.",jt=Kn&&!ws&&!mi&&!Be&&!Tt&&Ns.toLowerCase()==="waiting"&&(String(((fa=we==null?void 0:we.waiting)==null?void 0:fa.reason)||"").trim().toLowerCase()==="until"||Bs==="until")&&!!String(oo||"").trim(),Us=(md=we==null?void 0:we.limits)==null?void 0:md.tokens,Ha=typeof(Us==null?void 0:Us.pct)=="number"?Number(Us.pct):null,nh=Us==null?void 0:Us.estimated_used,N_=(Us==null?void 0:Us.max_input_tokens)??(Us==null?void 0:Us.max_tokens),ao=p.useMemo(()=>{const v=mr.current;fn.length<v.scanned&&(v.scanned=0,v.found=null);for(let T=v.scanned;T<fn.length;T++){const F=fn[T],B=F==null?void 0:F.record;if(!B)continue;const Z=op(B);if((Z&&Z.name?Rh(Z.name):"")!=="abstract.summary")continue;const ee=Z!=null&&Z.payload&&typeof Z.payload=="object"?Z.payload:{},oe=typeof(ee==null?void 0:ee.text)=="string"?String(ee.text):"";oe.trim()&&(v.found={cursor:F.cursor,ts:String((B==null?void 0:B.ended_at)||(B==null?void 0:B.started_at)||""),text:oe,provider:typeof(ee==null?void 0:ee.provider)=="string"?String(ee.provider):void 0,model:typeof(ee==null?void 0:ee.model)=="string"?String(ee.model):void 0,generated_at:typeof(ee==null?void 0:ee.generated_at)=="string"?String(ee.generated_at):void 0,source:ee==null?void 0:ee.source})}return v.scanned=fn.length,v.found},[fn]);p.useEffect(()=>{vr.current=Lr.trim()},[Lr]),p.useEffect(()=>{const v=l.trim(),T=oa.trim();if(!(Vt&&Bs==="subworkflow"&&!!T&&T!==v)){$o.current="",Lr.trim()&&Ei("");return}$o.current!==T&&($o.current=T,vr.current=T,Ei(T))},[Vt,l,Bs,oa,Lr]),p.useEffect(()=>{Tu({})},[N]);const zc=p.useMemo(()=>((Array.isArray(D==null?void 0:D.entrypoints)?D==null?void 0:D.entrypoints:[])||[]).map(T=>String((T==null?void 0:T.flow_id)||"").trim()).filter(Boolean),[D]),Ri=p.useMemo(()=>{const v=String((we==null?void 0:we.workflow_id)||"").trim();return Vt&&Kn?v:""},[Vt,Kn,we==null?void 0:we.workflow_id]),$_=p.useMemo(()=>{var ee;if(!Vt||!l.trim()||!Ri.trim())return Rr;const v=String((we==null?void 0:we.status)||"").trim().toLowerCase(),T=String((we==null?void 0:we.current_node)||"").trim();if(v!=="waiting"&&v!=="running"||!T)return Rr;const F=ar(l.trim(),T);if(!F)return Rr;const B=String(Bs||((ee=we==null?void 0:we.waiting)==null?void 0:ee.reason)||"").trim().toLowerCase(),Z=typeof(or==null?void 0:or.node_id)=="string"?String(or.node_id).trim():"",X=typeof(or==null?void 0:or.status)=="string"?String(or.status).trim().toLowerCase():"";return v==="waiting"&&B==="until"||!Rr.trim()||(X==="waiting"||X==="running")&&!Z?F:Rr},[Vt,l,Ri,we==null?void 0:we.status,we==null?void 0:we.current_node,(ha=we==null?void 0:we.waiting)==null?void 0:ha.reason,Bs,Rr,or]),C_=p.useMemo(()=>{const v={},T=l.trim(),F=(B,Z)=>{if(!Z)return;const X=typeof(Z==null?void 0:Z.node_id)=="string"?String(Z.node_id).trim():"";if(!X)return;const ee=ar(B,X);if(!ee)return;const oe=String((Z==null?void 0:Z.ended_at)||(Z==null?void 0:Z.started_at)||"").trim(),Ge=Ht(oe);Ge!==null&&(v[ee]=Math.max(v[ee]||0,Ge))};for(const B of fn)B&&B.record&&F(T,B.record);for(const B of nn)B&&B.record&&F(String(B.run_id||"").trim(),B.record);return v},[fn,nn,l,No]);p.useEffect(()=>{var F;if(!Vt||!l.trim()||!Ri.trim())return;const v=String((we==null?void 0:we.current_node)||"").trim();!v||String(((F=we==null?void 0:we.waiting)==null?void 0:F.reason)||"").trim()==="subworkflow"||Rc(ar(l.trim(),v))},[Vt,l,Ri,we==null?void 0:we.current_node,(ch=we==null?void 0:we.waiting)==null?void 0:ch.reason]),p.useEffect(()=>{const v=String((hs==null?void 0:hs.flow_id)||"").trim();v&&(yl.trim()||yr(v))},[hs,yl]),p.useEffect(()=>{const v=Ri.trim(),T=N.trim(),F=yl.trim();if(v){let Z=!1;return Ta(!0),yc(""),Ke.get_workflow_flow(v).then(X=>{if(Z)return;const ee=X==null?void 0:X.flow;wl(ee&&typeof ee=="object"?ee:null)}).catch(X=>{Z||(wl(null),yc(String((X==null?void 0:X.message)||X||"Failed to load workflow flow")))}).finally(()=>{Z||Ta(!1)}),()=>{Z=!0}}if(!T||!F){wl(null),yc(""),Ta(!1);return}let B=!1;return Ta(!0),yc(""),Ke.get_bundle_flow(T,F).then(Z=>{if(B)return;const X=Z==null?void 0:Z.flow,ee=X&&typeof X=="object"?X:null;wl(ee),ee&&Tu(oe=>({...oe,[F]:ee}))}).catch(Z=>{B||(wl(null),yc(String((Z==null?void 0:Z.message)||Z||"Failed to load flow")))}).finally(()=>{B||Ta(!1)}),()=>{B=!0}},[Ri,N,yl,Ke]),p.useEffect(()=>{const v=N.trim();if(!Ki||!v||!Gi)return;let T=!1;const F=3,B=ke=>{const ye=Array.isArray(ke==null?void 0:ke.nodes)?ke.nodes:[],Fe=[];for(const Pe of ye){const st=Pe!=null&&Pe.data&&typeof Pe.data=="object"?Pe.data:{};if(String((st==null?void 0:st.nodeType)||(Pe==null?void 0:Pe.type)||"").trim()!=="subflow")continue;const lt=(st==null?void 0:st.subflowId)||(st==null?void 0:st.flowId),vn=typeof lt=="string"?lt.trim():"";vn&&Fe.push(vn.includes(":")?vn.split(":",2)[1]:vn)}return Fe},Z=new Set,X=new Set,ee=(ke,ye)=>{if(!(!ke||ye>=F))for(const Fe of B(ke)){const Pe=String(Fe||"").trim();if(!Pe||Z.has(Pe))continue;Z.add(Pe),X.add(Pe);const st=gc[Pe];st&&ee(st,ye+1)}};ee(Gi,0);const oe=Array.from(X).filter(ke=>!gc[ke]).slice(0,20);return oe.length?((async()=>{for(const ke of oe){if(T)return;try{const ye=await Ke.get_bundle_flow(v,ke),Fe=ye==null?void 0:ye.flow,Pe=Fe&&typeof Fe=="object"?Fe:null;if(!Pe)continue;Tu(st=>st[ke]?st:{...st,[ke]:Pe})}catch{}}})(),()=>{T=!0}):void 0},[Ki,N,Gi,gc,Ke]);const sh=p.useMemo(()=>{const T=(Array.isArray(D==null?void 0:D.flows)?D==null?void 0:D.flows:[]).map(F=>String(F||"").trim()).filter(Boolean);return T.length?Array.from(new Set(T)).sort():Array.from(new Set(zc)).sort()},[D,zc]);p.useEffect(()=>{mi&&Rr.trim()&&(Zo(""),So.current="")},[mi,l,Rr]),p.useEffect(()=>{const v=Lr.trim(),T=l.trim();if(!(Vt&&!!v&&v!==T)){wr.current&&wr.current.abort(),wr.current=null,zn.current=0,Iu&&bl("");return}if(Iu===v)return;wr.current&&wr.current.abort();const B=new AbortController;wr.current=B,zn.current=0,bl(v),bn({ts:on(),kind:"info",title:`Following run ${v} (status/events)`});let Z=250;return(async()=>{for(;!B.signal.aborted;){try{await Ke.stream_ledger(v,{after:zn.current,on_step:ee=>d_(v,ee),signal:B.signal});return}catch(ee){if(B.signal.aborted)break;const oe=String((ee==null?void 0:ee.message)||ee||"stream error");bn({ts:on(),kind:"error",title:"Child ledger stream error (will retry)",preview:en(oe),data:{child_run_id:v,error:oe}})}if(B.signal.aborted)break;await new Promise(ee=>setTimeout(ee,Z)),Z=Math.min(5e3,Math.floor(Z*1.6))}})(),()=>{B.abort()}},[Vt,Lr,l,Ke,Iu]),p.useEffect(()=>{if(!Vt||!l.trim())return;let v=!1;const T=async()=>{if(!v&&!Oa.current&&No.length&&!(at.current>Date.now())){Oa.current=!0;try{const B=No.map(oe=>String(oe||"").trim()).filter(Boolean);if(!B.length)return;const Z=B.map(oe=>({run_id:oe,after:Number(Qo.current[oe]||0)})),X=await Ke.get_ledger_batch({runs:Z,limit:200}),ee=X&&typeof X=="object"?X.runs:{};for(const oe of B){if(v)return;const Ge=ee&&typeof ee=="object"?ee[oe]:null,ke=Array.isArray(Ge==null?void 0:Ge.items)?Ge.items:[],ye=typeof(Ge==null?void 0:Ge.next_after)=="number"?Ge.next_after:Number(Qo.current[oe]||0),Fe=Number(Qo.current[oe]||0);for(let Pe=0;Pe<ke.length;Pe++){const st=ke[Pe];f_(oe,{cursor:Fe+Pe+1,record:st})}Qo.current[oe]=ye}}catch(B){if(v||String((B==null?void 0:B.name)||"")==="Superseded")return;bn({ts:on(),kind:"error",title:"Subrun digest poll failed",preview:en(String((B==null?void 0:B.message)||B||""))}),Pm("Subrun digest poll failed",en(String((B==null?void 0:B.message)||B||"")))}finally{Oa.current=!1}}};T();const F=window.setInterval(()=>void T(),2e3);return()=>{v=!0,window.clearInterval(F),Oa.current=!1}},[Vt,l,No,Ke]);const Li=p.useMemo(()=>{const v=l.trim(),T=[];for(const F of fn)!F||!F.record||T.push({run_id:v,cursor:F.cursor,record:F.record});for(const F of nn)!F||!F.record||T.push({run_id:String(F.run_id||"").trim(),cursor:F.cursor,record:F.record});return T},[fn,nn,l]),Bc=p.useMemo(()=>{var T,F,B,Z;const v={};for(const X of Li){const ee=String(X.run_id||((T=X.record)==null?void 0:T.run_id)||"").trim();!ee||String(((B=(F=X.record)==null?void 0:F.effect)==null?void 0:B.type)||"").trim()!=="llm_call"||String(((Z=X.record)==null?void 0:Z.status)||"")!=="started"&&(v[ee]=(v[ee]||0)+1)}return v},[Li]),Js=p.useMemo(()=>{const v=Lr.trim();if(v)return v;let T="",F=-1;for(const[B,Z]of Object.entries(Bc))Z>F&&(T=B,F=Z);return T||l.trim()},[Bc,Lr,l]),Ii=(Kg.trim()||Js).trim(),aa=p.useMemo(()=>{var Z;const v=new Set,T=l.trim(),F=Lr.trim();T&&v.add(T),F&&v.add(F);for(const X of No){const ee=String(X||"").trim();ee&&v.add(ee)}for(const X of Li){const ee=String(X.run_id||((Z=X.record)==null?void 0:Z.run_id)||"").trim();ee&&v.add(ee)}const B=Array.from(v);return B.sort((X,ee)=>T&&X===T&&ee!==T?-1:T&&ee===T&&X!==T?1:F&&X===F&&ee!==F?-1:F&&ee===F&&X!==F?1:X<ee?-1:X>ee?1:0),B},[l,Lr,No,Li]),rh=p.useMemo(()=>{var v;for(let T=fn.length-1;T>=0;T--){const F=d1((v=fn[T])==null?void 0:v.record);if(F)return F}return""},[fn]);function E_(v){xf(v);const T=l.trim();if(!(!T||typeof window>"u"))try{window.history.replaceState(null,"",AI(lI(T),v))}catch{}}const $n=p.useMemo(()=>{const v=l.trim();return v&&(In.find(T=>String(T.run_id||"").trim()===v)||mn.find(T=>String(T.run_id||"").trim()===v))||null},[In,mn,l]),_s=p.useMemo(()=>$n||(we&&String((we==null?void 0:we.run_id)||"").trim()?sp(we):null),[$n,we]),ls=_s?`${String(_s.run_id||"")}|${String(_s.workflow_id||"")}|${String(_s.automation_id||"")}|${String(_s.session_id||"")}`:"",A_=String((_s==null?void 0:_s.session_id)||"").trim(),T_=String((_s==null?void 0:_s.updated_at)||""),M_=Math.floor(Date.now()/6e4);p.useEffect(()=>{if(e!=="observe"||js!=="agent"||!A_||!L||Gn.key!==ls||Gn.loading)return;const v=he.current;Ke.list_runs({session_id:A_,include_metrics:!0,limit:200}).then(T=>{if(v!==he.current)return;const F=Array.isArray(T==null?void 0:T.items)?T.items.map(sp):[];Y(B=>B.key===ls?{...B,runs:F,runs_error:""}:B)}).catch(T=>{v===he.current&&Y(F=>F.key===ls?{...F,runs_error:String((T==null?void 0:T.message)||T||"failed")}:F)})},[T_,M_,Gn.key,Gn.loading]),p.useEffect(()=>{if(e!=="observe"||js!=="agent"||!ls||!L||Gn.key===ls)return;const v=_s,T=String(v.run_id||"").trim(),F=++he.current;Y({...$j,key:ls,loading:!0});const B=String(v.workflow_id||"").trim(),Z=()=>{const oe=B.indexOf("@"),Ge=oe>=0?B.indexOf(":",oe):-1;return oe>=0&&Ge>oe?Ke.get_bundle_flow(B.slice(0,Ge),B.slice(Ge+1)):Ke.get_workflow_flow(B)},X=String(v.automation_id||"").trim(),ee=String(v.session_id||"").trim();Promise.allSettled([Ke.get_run_input_data(T),B?Z():Promise.reject(new Error("the run names no workflow")),X?Ke.automations_client().getAutomation(X):Promise.resolve(null),ee?Ke.list_runs({session_id:ee,include_metrics:!0,limit:200}):Promise.resolve({items:[]})]).then(([oe,Ge,ke,ye])=>{var pt;if(F!==he.current)return;const Fe=lt=>{var vn;return lt.status==="rejected"?String(((vn=lt.reason)==null?void 0:vn.message)||lt.reason||"failed"):""},Pe=ke.status==="fulfilled"?ke.value:null,st=ye.status==="fulfilled"&&Array.isArray((pt=ye.value)==null?void 0:pt.items)?ye.value.items.map(sp):[];Y({key:ls,loading:!1,input_data:oe.status==="fulfilled"?oe.value:null,input_error:Fe(oe),flow:Ge.status==="fulfilled"?Ge.value:null,flow_error:Fe(Ge),automation_body:Pe,automation:Pe?Am(Pe):null,automation_error:Fe(ke),runs:st,runs_error:Fe(ye)})})},[e,js,ls,L,Gn.key]);const ud=p.useMemo(()=>{const v=new Map;for(const T of Gn.runs)String(T.run_id||"").trim()&&v.set(String(T.run_id).trim(),T);for(const T of In){const F=String(T.run_id||"").trim();if(!F)continue;const B=v.get(F);v.set(F,B?{...B,...T,tokens_total:T.tokens_total??B.tokens_total,llm_calls:T.llm_calls??B.llm_calls,tool_calls:T.tool_calls??B.tool_calls}:T)}return _s&&!v.has(String(_s.run_id||"").trim())&&v.set(String(_s.run_id).trim(),_s),Array.from(v.values())},[Gn.runs,In,_s]),R_=p.useMemo(()=>kP(Li,l.trim(),ar),[Li,l,No]),sy=p.useMemo(()=>{if(!_s)return null;const v=EC(_s,we),T=new Map;return we&&T.set(String(v.run_id||"").trim(),we),Xd(v,_x(ud,{now_ms:Mu,details:T}))},[_s,we,ud,Mu]),lo=String((we==null?void 0:we.status)||($n==null?void 0:$n.status)||"").trim(),ih=String(Bs||((uh=we==null?void 0:we.waiting)==null?void 0:uh.reason)||($n==null?void 0:$n.waiting_reason)||"").trim().toLowerCase(),Xr=!!(we!=null&&we.is_scheduled||$n!=null&&$n.is_scheduled),An=!!(we!=null&&we.paused||$n!=null&&$n.paused),Rs=Xr&&lo.toLowerCase()==="waiting",$s=Rs&&ih==="until",Ws=Ht(oo),Sr=$s&&Ws!==null?em(Ws-Date.now()):"",co=Yp(we),ps=Xr&&An?"Suspended":Rs?"Scheduled":tm({status:lo,paused:An,stop_reason:co});async function Bl(){if(L){Fu(!0),Ef("");try{const v=Eo,T=v==="session"?String(kl||ra||P||"").trim():"",F=v==="run"?String(On||l||"").trim():"",B=P4(ta),Z=jl.length?jl.join(","):"",X=D4(To),ee=Math.max(0,Xi)*jp,oe=await Ke.search_artifacts({scope:v,session_id:T||void 0,run_id:F||void 0,query:Ji||void 0,artifact_kind:Z||void 0,created_after:B||void 0,include_stats:!0,limit:jp,offset:ee,order_by:X.order_by,order:X.order}),Ge=[],ke=new Set;for(const pt of Array.isArray(oe==null?void 0:oe.items)?oe.items:[]){const lt=L4(pt,"search");!lt||ke.has(lt.artifact_id)||(ke.add(lt.artifact_id),Ge.push(lt))}const ye=oe!=null&&oe.stats&&typeof oe.stats=="object"?oe.stats:{},Fe=Number((ye==null?void 0:ye.total)??(oe==null?void 0:oe.total)??Ge.length),Pe=E0(oe);let st=Pe;if(jl.length)try{const pt=await Ke.search_artifacts({scope:v,session_id:T||void 0,run_id:F||void 0,query:Ji||void 0,created_after:B||void 0,include_stats:!0,limit:1,offset:0,order_by:X.order_by,order:X.order});st=E0(pt)}catch{st=Pe}Pu(Number.isFinite(Fe)?Math.max(0,Fe):Ge.length),Du(Number((ye==null?void 0:ye.total_bytes)??(ye==null?void 0:ye.byte_total)??0)||0),Km(Pe),Ym(st),bc(Ge),Mo(pt=>{var lt;return pt&&Ge.some(vn=>vn.artifact_id===pt)?pt:((lt=Ge[0])==null?void 0:lt.artifact_id)||""})}catch(v){Ef(String((v==null?void 0:v.message)||v||"Failed to load artifacts")),bc([]),Pu(0),Du(0),Km({}),Ym({}),Mo("")}finally{Fu(!1)}}}async function la(){if(L){Vu(!0),Ir("");try{const v=await Ke.audit_log_tail({max_bytes:16e4}),T=typeof(v==null?void 0:v.bytes)=="number"?Number(v.bytes):0,F=!!(v!=null&&v.truncated);to(String((v==null?void 0:v.content)||"")),Tf(`${T.toLocaleString()} bytes${F?" (tail)":""}`)}catch(v){Ir(String((v==null?void 0:v.message)||v||"Failed to load audit log")),to(""),Tf("")}finally{Vu(!1)}}}async function Uc(v){if(!L)return;const T=String(v||ai||On||l||"").trim();if(!T){jc([]),Al(""),Lf("Select a run in Activity or Artifacts to load its runtime ledger.");return}Fa(!0),Lf("");try{const F=await Ke.get_ledger(T,{after:0,limit:2e3}),B=Array.isArray(F.items)?F.items:[];jc(B.map((X,ee)=>({cursor:ee+1,record:X})));const Z=typeof F.next_after=="number"?Number(F.next_after):B.length;Al(`${B.length.toLocaleString()} record${B.length===1?"":"s"}${Z>=2e3?" (first 2,000)":""}`)}catch(F){Lf(String((F==null?void 0:F.message)||F||"Failed to load run ledger")),jc([]),Al("")}finally{Fa(!1)}}p.useEffect(()=>{L&&e==="runtime"&&Bl()},[L,e,Eo,kl,On,Ji,jl,ta,To,Xi]),p.useEffect(()=>{L&&(Hu||eo||e==="runtime"&&la())},[L,e,js]),p.useEffect(()=>{if(!L||e!=="runtime"||xc!=="logs"||Xn!=="run_ledger"&&Xn!=="provider_calls")return;const v=String(ai||On||l||"").trim();v&&Uc(v)},[L,e,xc,Xn,ai,On,l]);const uo=p.useMemo(()=>{const v=new Map;for(const T of[...mn,...In]){const F=String(T.run_id||"").trim();F&&v.set(F,T)}for(const T of No){const F=String(T||"").trim();!F||v.has(F)||v.set(F,{run_id:F,workflow_id:null,status:"",created_at:null,updated_at:null,ledger_len:null,parent_run_id:Vr.current[F]||null,session_id:ra||null})}return l.trim()&&!v.has(l.trim())&&v.set(l.trim(),{run_id:l.trim(),workflow_id:typeof(we==null?void 0:we.workflow_id)=="string"?String(we.workflow_id):null,status:typeof(we==null?void 0:we.status)=="string"?String(we.status):"",created_at:typeof(we==null?void 0:we.created_at)=="string"?String(we.created_at):null,updated_at:typeof(we==null?void 0:we.updated_at)=="string"?String(we.updated_at):null,ledger_len:fn.length||null,parent_run_id:typeof(we==null?void 0:we.parent_run_id)=="string"?String(we.parent_run_id):null,session_id:typeof(we==null?void 0:we.session_id)=="string"?String(we.session_id):ra||null}),Array.from(v.values()).sort((T,F)=>{const B=Ht(T.updated_at||T.created_at)??0;return(Ht(F.updated_at||F.created_at)??0)-B})},[In,mn,l,we,fn.length,No,ra]),Wc=p.useMemo(()=>gP(uo,{query:Eu,filter:Au,group_by:_f,workflow_label_by_id:di,parent_hint:v=>Vr.current[v]||""}),[uo,Eu,Au,_f,di]),As=p.useMemo(()=>{const v={};for(const T of uo){const F=String(T.run_id||"").trim();F&&(v[F]=T)}return v},[uo]),qc=String(ai||On||l||"").trim(),ca=qc&&As[qc]||null,fo=String(kl||(ca==null?void 0:ca.session_id)||ra||P||"").trim(),Hc=p.useMemo(()=>Ou.map(v=>ng(v,As,di)),[Ou,As,di]);p.useEffect(()=>{rr(0)},[Ji,jl,ta,On,To,Ao,Eo,kl]);const oh=Math.max(1,Math.ceil(kc/jp)),_i=Math.min(Math.max(0,Xi),oh-1);p.useEffect(()=>{Xi!==_i&&rr(_i)},[Xi,_i]);const ho=p.useMemo(()=>Hc,[Hc,_i]),ua=p.useMemo(()=>{const v={};for(const T of ho){const F=Ao==="type"?tv(T,As,di):I4(T,Ao);v[F]||(v[F]=[]),v[F].push(T)}return Object.entries(v).map(([T,F])=>({key:T,items:F})).sort((T,F)=>{var B,Z;if(Ao==="time"){const X=Ht((B=T.items[0])==null?void 0:B.created_at)??0,ee=Ht((Z=F.items[0])==null?void 0:Z.created_at)??0;if(X!==ee)return ee-X}return T.key.localeCompare(F.key)})},[ho,Ao,As,di]),da=p.useMemo(()=>{const v=xr.trim();return v?ho.find(T=>T.artifact_id===v)||ho[0]||null:ho[0]||null},[ho,xr]);p.useEffect(()=>{e!=="runtime"||xc!=="artifacts"||u_(da)},[e,xc,da==null?void 0:da.artifact_id]),p.useEffect(()=>()=>{Ro.url&&URL.revokeObjectURL(Ro.url)},[Ro.url]);const Vc=p.useMemo(()=>uo.filter(v=>Gd(v.status)),[uo]);p.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!L||se)return;let v=!1;return(async()=>{const[T,F]=await Promise.all([Ke.list_skills(),Ke.list_mcp_servers()]);v||(ne(T),Me(F),de(!0))})(),()=>{v=!0}},[e,L,se]);function Ul(){pc&&window.setTimeout(()=>{var v;return(v=vf.current)==null?void 0:v.scrollIntoView({block:"start"})},60)}function zo(v){jo(v),Ul()}const dd=[{id:"board",label:"Board",icon:s.jsx(qe,{name:"board",size:16})},{id:"observe",label:"Observe",icon:s.jsx(qe,{name:"history",size:16})},{id:"runtime",label:"System",icon:s.jsx(qe,{name:"server",size:16})},{id:"automations",label:"Automations",icon:s.jsx(qe,{name:"refresh",size:16})}],Nr={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},Bo=s.jsx(hP,{connected:L,request:Ku,value:so,onChange:v=>Zn("workspace",v===null?void 0:v),disabled:Be||Tt}),pi=s.jsx(s.Fragment,{children:kr?s.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",ui.length?` · ${ui.length} skill${ui.length===1?"":"s"}`:""]}),s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Skills attach knowledge procedures to this run. The gateway resolves selections through the trust gate at start: validated skills activate, unverified ones are held for review, blocked ones never ride."}),z===null?s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"This gateway does not serve a skills inventory yet — the shelf lights up here when it ships."}):z.length?s.jsx("div",{className:"launch_skill_list",children:z.map(v=>{var Z;const T=ui.includes(v.name),F=v.blocked===!0,B=v.requires_review===!0&&!F;return s.jsxs("label",{className:`launch_skill_row ${F?"is_blocked":""} ${T?"is_on":""}`,title:[v.description||"",v.tree_hash?`tree ${v.tree_hash.slice(0,16)}…`:"",F&&((Z=v.reasons)!=null&&Z.length)?`blocked: ${v.reasons.join("; ")}`:""].filter(Boolean).join(`
173
+ `),children:[s.jsx("input",{type:"checkbox",checked:T,disabled:F||Be||Tt||ce,onChange:X=>{const ee=X.target.checked?Array.from(new Set([...ui,v.name])):ui.filter(oe=>oe!==v.name);Zn("skills",ee.length?ee:void 0)}}),s.jsx("span",{className:"launch_skill_name",children:v.name}),v.trust_level?s.jsx("span",{className:`chip ${F?"danger":B?"warn":"muted"}`,children:F?"blocked":B?"review":v.trust_level}):null,v.description?s.jsx("span",{className:"launch_skill_desc",children:v.description}):null]},v.name)})}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"The gateway's skills shelf is empty."}),ui.length?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)",marginTop:"6px"},children:"Selected skills ride the run as input_data.skills; the resolved verdicts land in the run's record."}):null]}):null}),Pr=s.jsxs("section",{className:"launch_workspaces","data-section":"workspaces",style:{marginTop:"10px"},children:[s.jsx("div",{className:"launch_label launch_section_title",children:"Workspaces"}),Bo,s.jsx("div",{className:"launch_grid",style:{marginTop:"8px"},children:s.jsxs("div",{className:"launch_grid_cell",style:{gridColumn:"1 / -1"},children:[s.jsx("label",{className:"launch_label",children:"Run workspace"}),s.jsx("input",{className:"mono",value:Nc,onChange:v=>Zn("workspace_root",v.target.value||void 0),placeholder:"/path/to/workspace",disabled:Be||Tt}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Empty = the run's own private workspace. Otherwise a workspace the gateway's posture reaches; the gateway refuses any other."})]})})]}),L_=s.jsxs("details",{className:"launch_bundles",style:{marginTop:"10px"},children:[s.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Flow files"}),s.jsxs("div",{className:"launch_workflow_bar",style:{marginTop:"8px"},children:[s.jsx("input",{ref:vo,type:"file",accept:".flow",style:{display:"none"},onChange:v=>{const T=v.target.files&&v.target.files.length?v.target.files[0]:null;T&&qf(T)}}),s.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var v;return(v=vo.current)==null?void 0:v.click()},disabled:!L||H||Ni||Be||Tt,title:"Upload a .flow bundle",children:Ni?"…":"Upload .flow"}),s.jsxs("button",{type:"button",className:"btn launch_btn_reload",onClick:()=>void Wf(),disabled:!L||H||xt||Be||Tt,title:"Reload picks up server-side edits",children:[s.jsx(qe,{name:"refresh",size:14}),xt?"…":"Reload bundles"]})]})]});function fd(v){t("observe"),jo("ledger"),Mi(v)}const ah={on_select:v=>void Bn.select(v),on_row_action:(v,T)=>{if(T==="discuss"||T==="edit")throw new Error(`${T} is routed by AutomationsPage (route_row_action), not the app handlers.`);if(T==="archive"){Bn.ask_archive(v.automation_id);return}Bn.row_action(v,T)},on_legacy_action:(v,T)=>{if(T==="open_run"){fd(v.automation_id);return}if(T==="recreate"){Jf(v.automation_id).catch(F=>Bn.report_error(F));return}Bn.legacy_action(v,T)},on_confirm_archive:v=>void Bn.row_action(v,"archive"),on_cancel_archive:()=>Bn.ask_archive(""),on_status_filter:v=>void Bn.set_status_filter(v),on_refresh:()=>void Bn.refresh(),on_new:()=>nt("automate"),on_show_archived:v=>Bn.set_show_archived(v)};return s.jsxs("div",{className:`app-shell shell${gf?" nav_open":""}`,children:[pf&&gf?s.jsx("div",{className:"shell_nav_backdrop","aria-hidden":"true",onClick:()=>Xo(!1)}):null,s.jsxs("aside",{className:"shell_sidebar",id:"shell_nav",ref:wf,...Vi.attrs.aside,children:[s.jsxs("div",{className:"shell_brand",title:"AbstractObserver (Web/PWA)",children:[s.jsx("span",{className:"logo-icon shell_brand_mark","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[s.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4.2",transform:"rotate(-18 12 12)",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",opacity:"0.75"}),s.jsx("circle",{cx:"12",cy:"12",r:"4.7",fill:"currentColor",opacity:"0.95"}),s.jsx("circle",{cx:"10.3",cy:"10.7",r:"1.6",fill:"#ffffff",opacity:"0.18"}),s.jsx("circle",{cx:"19",cy:"13.6",r:"1.2",fill:"currentColor"})]})}),s.jsx("span",{className:"shell_brand_name",children:"Observer"}),s.jsx("button",{type:"button",className:"shell_nav_close","aria-label":"Close navigation",title:"Close navigation",onClick:()=>Xo(!1),children:s.jsx(qe,{name:"x",size:16})})]}),s.jsxs("nav",{className:"shell_nav",children:[dd.map(v=>s.jsxs("button",{className:`shell_nav_item ${e===v.id?"active":""}`,onClick:()=>{t(v.id),Xo(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:v.icon}),s.jsx("span",{className:"shell_nav_label",children:v.label})]},v.id)),s.jsxs("a",{className:"shell_nav_item",href:o,target:"_blank",rel:"noreferrer",title:"Open the entity app (memory graph + visits)",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(qe,{name:"bot",size:16})}),s.jsx("span",{className:"shell_nav_label",children:"Entities ↗"})]}),s.jsxs("button",{className:`shell_nav_item ${e==="settings"?"active":""}`,onClick:()=>{t("settings"),Xo(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(qe,{name:"settings",size:16})}),s.jsx("span",{className:"shell_nav_label",children:"Settings"})]})]}),s.jsx("div",{className:"shell_sidebar_footer",children:s.jsxs("div",{className:"shell_connection shell_connection_passive",title:L?"Gateway connected":H?"Gateway: connecting…":"Gateway: signed out",children:[s.jsx("span",{className:`gateway_led ${L?"ok":H?"warn":"err"}`,"aria-hidden":"true"}),s.jsx("span",{className:`shell_connection_label ${L&&((Gc=(_d=U==null?void 0:U.gateway)==null?void 0:_d.principal)!=null&&Gc.user_id)?"mono":""}`,children:L?((P_=(O_=U==null?void 0:U.gateway)==null?void 0:O_.principal)==null?void 0:P_.user_id)||(n.gateway_auth_mode==="direct"?"direct dev":"connected"):H?"connecting…":"signed out"}),L&&mf?s.jsxs("span",{className:"shell_connection_notice",role:"status",title:mf,children:[_l[_l.length-1].title,_l.reduce((v,T)=>v+T.count,0)>1?` ×${_l.reduce((v,T)=>v+T.count,0)}`:""]}):null]})})]}),s.jsxs("div",{className:"shell_main",...Vi.attrs.main,children:[s.jsxs("header",{className:"shell_header",children:[s.jsx("button",{ref:yf,type:"button",className:"shell_nav_toggle","data-nav-toggle":!0,"aria-label":"Open navigation","aria-controls":"shell_nav","aria-expanded":gf,title:"Navigation",onClick:()=>Xo(!0),children:s.jsx(qe,{name:"list",size:18})}),s.jsx("div",{className:"shell_header_title",children:Nr[e]||"Observer"}),s.jsxs("div",{className:"shell_header_actions",children:[i?s.jsx("monitor-gpu",{ref:u,mode:"icon","history-size":"5","tick-ms":"1500","base-url":n.gateway_auth_mode==="session"?"":n.gateway_url,title:"GPU usage (host)",style:{"--monitor-gpu-width":"34px","--monitor-gpu-bars-height":"22px","--monitor-gpu-padding":"2px 4px","--monitor-gpu-radius":"999px","--monitor-gpu-bg":"rgba(0,0,0,0.22)","--monitor-gpu-border":"rgba(255,255,255,0.16)",flexShrink:0}}):null,s.jsx(wE,{docs:{open:St,onToggle:()=>ut(v=>!v),label:"Docs assistant"},appearance:{onOpen:()=>bt(!0)},about:{identity:Df,versions:Ff,onOpen:ci},connection:{phase:J.phase,signingOut:J.signingOut,onConnect:()=>J.openModal(),onDisconnect:()=>fi()}})]})]}),s.jsx(T2,{...J.modalProps}),s.jsx(Bj,{open:It,onClose:()=>bt(!1),value:yt,onChange:_t}),s.jsx(YL,{open:St,onClose:()=>ut(!1),connected:L,topOffset:44,gateway:Ke}),s.jsxs("div",{className:"app-body shell_content",children:[e==="board"?L?s.jsx(vW,{gateway_connected:L,runs:mn,all_runs:In,runs_refreshed_at:Re,runs_stale:Hg,notice:mf,entities:re,entities_total:Ce,entities_error:We,on_open_run:v=>{t("observe"),jo("agent"),Mi(v)},on_resume_wait:Hf,on_open_automation:v=>{Ae(!1),t("automations"),Bn.refresh().then(()=>Bn.select(v))},entity_app_href:o,on_read_diary:(v,T)=>Ke.read_entity_diary_entry(v,T),phase_graph:Ac,client:Ke,on_rename_automation:(v,T,F)=>Bn.revise(v,{title:T},F??null),on_revise_automation:(v,T,F)=>Bn.revise(v,T,F),on_automation_command:(v,T)=>Bn.command(v,T),on_resume_run:v=>Lc(v,"resume"),on_cancel_run:v=>Lc(v,"cancel"),on_cancel_runs:Zg,code_app:He,done_loaded:(()=>{const v=B9(Ke);return v!==null&&v.epoch===ro.current&&v.sweep_at!==null})()}):s.jsx("div",{className:"page page_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card mc_hero",children:[s.jsx("div",{className:"title",children:s.jsx("h1",{children:"Connect to your gateway"})}),s.jsxs("p",{className:"muted",children:["Mission Control shows every run and entity on one board — but nothing is connected yet.",A?` Last attempt: ${A}`:""]}),s.jsxs("div",{className:"row",style:{gap:"8px",alignItems:"center"},children:[s.jsx("button",{className:"btn primary",onClick:()=>J.openModal(),disabled:H,children:H?"Connecting…":"Sign in"}),s.jsx("button",{className:"btn",onClick:()=>void Po({open_modal_if_needed:!0}),disabled:H,title:"Retry with an existing browser session or a direct dev token",children:"Retry connection"})]})]})})}):null,e==="settings"?s.jsx("div",{className:"page page_scroll",children:s.jsxs("div",{className:"page_inner settings_col",children:[s.jsxs("section",{className:"pane",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Gateway"}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:`chip ${L?"ok":"warn"}`,children:Oj(U).label})]}),s.jsxs("div",{className:"pane_body settings_body",children:[s.jsxs("div",{className:"settings_row",children:[s.jsxs("div",{className:"settings_row_main",children:[s.jsx("div",{className:"settings_row_title",children:"Connection"}),s.jsx("div",{className:"settings_row_help",children:"The shared AbstractFramework sign-in: a gateway user token exchanges for an HTTP-only browser session. Raw tokens are never stored."})]}),s.jsxs("div",{className:"settings_row_actions",children:[s.jsx("button",{className:"btn",onClick:()=>J.openModal(),children:"Manage connection…"}),L?s.jsx("button",{className:"btn",onClick:()=>fi(),title:"Sign this browser out of the gateway (this app's session only)",children:"Sign out"}):null]})]}),A?s.jsx("div",{className:"warn_callout",children:A}):null,s.jsx("div",{className:"settings_row",children:s.jsx(ZO,{checked:n.auto_connect_gateway,onChange:v=>r(T=>({...T,auto_connect_gateway:v}))})}),s.jsxs("details",{className:"settings_advanced",children:[s.jsx("summary",{children:"Advanced: direct dev connection (bearer token, cross-origin)"}),s.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[s.jsx("label",{children:"Gateway URL"}),s.jsx("input",{value:n.gateway_url,onChange:v=>r(T=>({...T,gateway_url:v.target.value})),placeholder:yg})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Dev bearer token"}),s.jsx("input",{type:"password",value:n.auth_token,onChange:v=>r(T=>({...T,auth_token:v.target.value,gateway_auth_mode:"direct"})),placeholder:"development only — prefer the sign-in dialog"})]}),s.jsx("button",{className:"btn",onClick:()=>void Po({prefer_direct:!0}),disabled:H,children:H?"Connecting…":"Connect directly"})]})]})]}),s.jsxs("section",{className:"pane",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Assistant"}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:"chip muted",children:"docs Q&A + run Ask"})]}),s.jsxs("div",{className:"pane_body settings_body",children:[s.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"The model answering the header assistant and the run page's Ask tab. Blank fields follow the gateway defaults."}),s.jsx(Mj,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:Yu,models:Xu.models,loadingProviders:H,loadingModels:Bf,modelError:Il?Xu.error:"",allowCustomProvider:!0,allowCustomModel:!0,allowGatewayDefault:!0,gatewayDefaultLabel:"(gateway default)",onChange:v=>r(T=>({...T,maintenance_ai_provider:v.provider,maintenance_ai_model:v.model}))}),s.jsx("div",{className:"settings_subhead",children:"Skills"}),z===null?s.jsx("div",{className:"settings_row_help",children:L?se?"The gateway does not serve a skills inventory yet — the abstractskill shelf list lights up here the day it ships.":"Probing the gateway for the skills inventory…":"Connect to the gateway to list installable skills (abstractskill shelf)."}):z.length?s.jsx("div",{className:"settings_choice_list",children:z.map(v=>{const T=n.assistant_skill_names.includes(v.name);return s.jsx(QO,{name:v.name,version:v.version,description:v.description,checked:T,onChange:F=>r(B=>({...B,assistant_skill_names:F?Array.from(new Set([...B.assistant_skill_names,v.name])):B.assistant_skill_names.filter(Z=>Z!==v.name)}))},v.name)})}):s.jsx("div",{className:"settings_row_help",children:"The gateway serves an empty skills inventory."}),s.jsx("div",{className:"settings_row_help",children:"Selected skills ride the assistant's runs once the gateway's skills-attachment lane serves them; the selection persists here meanwhile."}),s.jsx("div",{className:"settings_subhead",children:"MCP servers"}),s.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"Remote tool endpoints the assistant may call. The gateway does not serve an MCP inventory yet — one manual endpoint is supported (advanced / potentially dangerous: it executes tool waits from this browser)."}),s.jsxs("div",{className:"settings_mcp_row",children:[s.jsx("input",{className:"mono",value:n.worker_url,onChange:v=>r(T=>({...T,worker_url:v.target.value})),placeholder:"https://your-mcp-worker-endpoint"}),s.jsx("input",{className:"mono",type:"password",value:n.worker_token,onChange:v=>r(T=>({...T,worker_token:v.target.value})),placeholder:"Bearer token (optional)"}),s.jsx("span",{className:`chip ${n.worker_url.trim()?"ok":"muted"}`,children:n.worker_url.trim()?"configured":"none"})]})]})]}),s.jsxs("section",{className:"pane","data-settings-section":"voice",children:[s.jsx("div",{className:"pane_header",children:s.jsx("span",{className:"pane_title",children:"Voice"})}),s.jsx("div",{className:"pane_body settings_body",children:s.jsx(cO,{gateway:L?Ke:null,connected:L,defaults:Vf,value:Mc,onChange:o_})})]})]})}):null,s.jsx(ec,{open:xe,title:je==="automate"?"New automation":"Run once",variant:"fullscreen",onClose:()=>Ae(!1),children:s.jsx("div",{className:"launch_modal_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card",children:[s.jsx(I3,{mode:je,automate_available:pe.available,automate_reason:pe.reason,on_change:ae}),je==="automate"&&!pe.available&&L?s.jsx("div",{className:"warn_callout",role:"note",children:pe.reason}):null,je==="automate"&&_e.length?s.jsx("div",{className:"help_text",role:"note",children:_e.map(v=>s.jsx("div",{children:v},v))}):null,L?null:s.jsxs("div",{className:"warn_callout",children:["Not connected."," ",s.jsx("button",{className:"btn primary",onClick:()=>J.openModal(),children:"Sign in"})," ","to run flows on this gateway."]}),je==="automate"?s.jsx("div",{className:"section_title",children:"What"}):null,s.jsx("div",{className:"launch_workflow_bar",children:s.jsx(zS,{id:"launch-workflow-picker",className:"launch_workflow_picker",interfaceId:null,defaultInterface:Fd,ariaLabel:"Flow",workflows:Ll,entryDetail:Of,value:f0(kr,((dh=Ll.data)==null?void 0:dh.entries)??[]),currentLabel:kr&&!f0(kr,((fh=Ll.data)==null?void 0:fh.entries)??[])?{name:di[Ju]||Ju}:null,unavailableReason:L?H?"Loading flows…":null:"Sign in to load flows.",onChange:(v,T)=>{const F=e3(v,T);F&&Kf(F)}})}),s.jsxs("div",{className:"field",children:[hs!=null&&hs.description?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(hs.description)}):null,I?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading flow…"}):null,G?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:G}):null]}),s.jsx("div",{className:"section_divider"}),s.jsx("div",{className:"section_title",children:"Inputs"}),kr?rn===null?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginTop:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"input error"}),s.jsx("span",{className:"mono",children:on()})]}),s.jsx("div",{className:"body mono",children:"Invalid input JSON — reselect the workflow to reset its inputs."})]}):$c?s.jsx("div",{className:"launch_inputs",children:(()=>{const v=Be||Tt,T=[],F=[];for(const X of Jr){if(!X||typeof X!="object")continue;const ee=String(X.id||"").trim();if(!ee||je==="automate"&&LN.includes(ee)||je==="automate"&&IN.includes(ee))continue;const oe=String(X.type||"").trim().toLowerCase();oe==="tools"||oe==="skills"||oe==="mcp"||oe==="mcp_servers"||ee==="skills"||ee==="mcp"||ee==="mcp_servers"||oe==="array"||Ba(oe)||ee==="prompt"||ee==="system"?T.push(X):F.push(X)}const B=X=>String(X||"").trim().replace(/_/g," ").replace(/\b\w/g,ee=>ee.toUpperCase()),Z=(X,ee)=>{const oe=String(X.id||"").trim();if(!oe)return null;const Ge=String(X.label||oe).trim()||oe,ke=Ge===oe?B(oe):Ge,ye=String(X.type||"").trim().toLowerCase(),Fe=Object.prototype.hasOwnProperty.call(X,"default"),Pe=Fe?X.default:void 0,st=Fe?typeof Pe=="string"?Pe:Fr(Pe,80):"",pt=rn==null?void 0:rn[oe],lt=Fe?`${st}`:"";if(ye==="tools"){if(je==="automate"&&oe==="tools")return null;const ft=Array.isArray(pt)?pt.map(cs=>String(cs||"").trim()).filter(Boolean):[],Qt=Array.isArray(Pe)?Pe.map(cs=>String(cs||"").trim()).filter(Boolean):[],Jn=Array.from(new Set([...Cc,...ft,...Qt])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx(Fw,{options:Jn,value:ft,disabled:v,placeholder:"(no tools selected)",onChange:cs=>Zn(oe,cs)})]},oe)}if(ye==="skills"||oe==="skills")return null;if(ye==="mcp"||ye==="mcp_servers"||oe==="mcp"||oe==="mcp_servers"){const ft=Array.isArray(pt)?pt.map(cs=>String(cs||"").trim()).filter(Boolean):[];if(be===null&&!ft.length)return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx("div",{className:"help_text muted",children:"This gateway does not serve an MCP server inventory yet — MCP selection lights up here when it ships."})]},oe);const Qt=(be||[]).map(cs=>cs.name),Jn=Array.from(new Set([...Qt,...ft])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx(Fw,{options:Jn,value:ft,disabled:v,placeholder:"(no MCP servers selected)",onChange:cs=>Zn(oe,cs)})]},oe)}if(ye==="provider"||ye==="provider_text"){const ft=typeof pt=="string"?String(pt):"";return s.jsxs("div",{className:ee||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsxs("select",{value:ft,onChange:Qt=>Zn(oe,Qt.target.value),disabled:v,children:[s.jsx("option",{value:"",children:lt||"(select)"}),ms.map(Qt=>s.jsx("option",{value:Qt,children:Qt},Qt))]})]},oe)}if(ye==="model"||ye==="model_text"){const ft=typeof pt=="string"?String(pt):"",Qt=String((rn==null?void 0:rn.provider)||"").trim(),Jn=Qt?hn[Qt]:void 0,cs=Jn&&Array.isArray(Jn.models)?Jn.models.map(ur=>String(ur||"").trim()).filter(Boolean):[];return s.jsxs("div",{className:ee||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ke}),cs.length?s.jsxs("select",{value:ft,onChange:ur=>Zn(oe,ur.target.value),disabled:v,children:[s.jsx("option",{value:"",children:lt||"(select)"}),cs.map(ur=>s.jsx("option",{value:ur,children:ur},ur))]}):s.jsx("input",{value:ft,onChange:ur=>Zn(oe,ur.target.value),placeholder:lt||"model id",disabled:v})]},oe)}if(ye==="boolean"){const ft=typeof pt=="boolean"?pt?"true":"false":"";return s.jsxs("div",{className:ee||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsxs("select",{value:ft,onChange:Qt=>{const Jn=String(Qt.target.value||"").trim();Jn?Zn(oe,Jn==="true"):Zn(oe,void 0)},disabled:v,children:[s.jsx("option",{value:"",children:lt||"(default)"}),s.jsx("option",{value:"true",children:"Yes"}),s.jsx("option",{value:"false",children:"No"})]})]},oe)}if(ye==="number"){const ft=typeof pt=="number"&&Number.isFinite(pt)?String(pt):"";return s.jsxs("div",{className:ee||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx("input",{type:"number",value:ft,onChange:Qt=>{const Jn=String(Qt.target.value||"").trim();if(!Jn){Zn(oe,void 0);return}const cs=Number(Jn);Number.isFinite(cs)&&Zn(oe,cs)},placeholder:lt,disabled:v})]},oe)}if(ye==="array"){const ft=Array.isArray(pt)?pt.map(Qt=>String(Qt||"").trim()).filter(Boolean).join(`
174
+ `):"";return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx("textarea",{className:"mono",value:ft,onChange:Qt=>{const Jn=String(Qt.target.value||"").split(/\r?\n/g).map(cs=>String(cs||"").trim()).filter(Boolean);Zn(oe,Jn.length?Jn:void 0)},placeholder:lt||"(one item per line)",rows:2,disabled:v})]},oe)}if(Ba(ye)){const ft=typeof uc[oe]=="string"?uc[oe]:"",Qt=String(bs[oe]||"").trim();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsxs("label",{className:"launch_label",children:[ke," ",s.jsx("span",{className:"launch_label_type",children:ye})]}),s.jsx("textarea",{className:"mono",value:ft,onChange:Jn=>{const cs=String(Jn.target.value??"");ll(gi=>({...gi,[oe]:cs}));const ur=cs.trim();if(!ur){_r(gi=>{const yi={...gi};return delete yi[oe],yi}),Zn(oe,void 0);return}try{const gi=JSON.parse(ur);_r(yi=>{const Wl={...yi};return delete Wl[oe],Wl}),Zn(oe,gi)}catch(gi){_r(yi=>({...yi,[oe]:String((gi==null?void 0:gi.message)||gi||"Invalid JSON")}))}},placeholder:lt||"{...}",rows:3,disabled:v}),Qt?s.jsx("div",{className:"launch_field_error",children:Qt}):null]},oe)}const vn=typeof pt=="string"?String(pt):"";return oe==="prompt"||oe==="system"?s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx("textarea",{value:vn,onChange:ft=>Zn(oe,ft.target.value),placeholder:lt||(oe==="prompt"?"What should the agent do?":"System instructions (optional)"),rows:3,disabled:v})]},oe):s.jsxs("div",{className:ee||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx("input",{value:vn,onChange:ft=>Zn(oe,ft.target.value),placeholder:lt,disabled:v})]},oe)};return T.sort((X,ee)=>{const oe={system:0,prompt:1,tools:2};return(oe[String(X.id||"")]??10)-(oe[String(ee.id||"")]??10)}),s.jsxs(s.Fragment,{children:[T.map(X=>Z(X)),F.length>0?s.jsx("div",{className:"launch_grid",children:F.map(X=>Z(X,"launch_grid_cell"))}):null]})})()}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[s.jsx("label",{children:"Prompt (common)"}),s.jsx("textarea",{value:s_,onChange:v=>Zn("prompt",v.target.value),placeholder:"What do you want the workflow/agent to do?",rows:3,disabled:Be||Tt})]}),s.jsxs("div",{className:"row",children:[s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Provider (common)"}),s.jsx("input",{value:Rl,onChange:v=>Zn("provider",v.target.value),placeholder:"lmstudio / ollama / openai / ...",disabled:Be||Tt})]})}),s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Model (common)"}),s.jsx("input",{value:r_,onChange:v=>Zn("model",v.target.value),placeholder:"qwen/qwen3-next-80b / gpt-4.1 / ...",disabled:Be||Tt})]})})]})]}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Choose a flow above to set its inputs."}),je==="automate"?s.jsxs(s.Fragment,{children:[s.jsx(O3,{form:Ve,email_status:li.email_status,on_open_my_email:Io,served:Ml,on_open_preferences:Io,defaults:Oo,connections:li.trigger_connections,mailboxes:li.mailboxes,tools:nS(rn||{})??void 0,available_tools:Cc,on_tools_change:v=>S(JSON.stringify(sS(rn||{},v),null,2)),disabled:ce,on_change:v=>ct(T=>({...T,...v})),workspaces:Bo}),s.jsx(P3,{form:Ve,disabled:ce,on_change:v=>ct(T=>({...T,...v}))}),pi]}):s.jsxs(s.Fragment,{children:[pi,Pr,L_]}),s.jsx("div",{className:"section_divider"}),Fn?s.jsxs("div",{className:"observe_context_card error",style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:"error"}),s.jsx("span",{className:"mono",children:Fn})]}):null,je==="automate"&&Qe.length?s.jsx("ul",{className:"automate_errors",role:"alert",children:Qe.map(v=>s.jsx("li",{children:v},v))}):null,je==="automate"&&$e?s.jsxs("div",{className:"observe_context_card error",role:"alert","data-code":$e.code,style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:$e.code}),s.jsxs("span",{children:[s.jsx("strong",{children:Wp($e).title})," ",Wp($e).detail,$e.field?s.jsxs("span",{className:"mono",children:[" (",$e.field,")"]}):null]})]}):null,s.jsx("div",{className:"launch_actions_bar launch_actions_stack",children:(()=>{const v=je==="automate",T=L?kr?rn===null?"Inputs contain invalid JSON":v&&!pe.available?"Automations unavailable on this gateway":Be||Tt?"Attaching to a run…":H||I?"Loading…":ce?"Submitting…":"":"Choose a flow":"Sign in first";return s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"launch_submit_btn",onClick:()=>void Xg(),disabled:!!T,title:T,children:v?ce?"Creating…":"Create automation":Be?"Launching…":"Launch now"}),T&&!ce&&!Be?s.jsx("span",{className:"mono muted launch_disabled_reason",children:T}):null]})})()})]})})})}),e==="automations"?s.jsx(XO,{workflowPickerOptions:{interfaceId:null,defaultInterface:Fd,workflows:Ll,entryDetail:Of,request:(v,T)=>Ke.get_gateway_json(v,T.signal)},availableTools:Cc,ctl:Bn,gateway:Ke,active:e==="automations"&&L,available:pe,h:ah,voice_session_id:P,workspace_request:Ku,host:{on_open_run:v=>fd(v),...Io?{on_open_my_email:Io}:{},on_open_session:(v,T)=>{bn({ts:on(),kind:"info",title:"Discussion started",preview:en(T),data:v})}}}):null,e==="runtime"?s.jsx(oP,{runs_loading:ss,gateway_connected:L,tab:xc,runs:uo,active_runs:Vc,all_artifacts:Ou,artifacts:ho,artifact_total_count:kc,artifact_total_bytes:$f,artifact_facets:Cf,artifact_type_facets:Jm,artifact_page:_i,artifact_page_size:jp,artifact_groups:ua,selected_artifact:da,embedded_preview:Ro,loading:Jg,error:ea,query:Ji,scope:Eo,type_filters:jl,date_filter:ta,group_by:Ao,sort_by:To,artifact_run_filter:On,audit_log_text:eo,audit_log_meta:Da,audit_log_loading:Hu,audit_log_error:Kr,workflow_label_by_id:di,run_by_id:As,selected_run_id:qc,session_id:fo,runtime_log_source:Xn,runtime_log_query:Qm,runtime_ledger_log_items:Mf,runtime_ledger_log_meta:t_,runtime_ledger_log_loading:n_,runtime_ledger_log_error:Rf,on_tab_change:Gm,on_query_change:Yi,on_scope_change:Ai,on_session_filter_change:Xm,on_type_filters_change:Pa,on_date_filter_change:Sl,on_group_by_change:Af,on_sort_by_change:na,on_artifact_page_change:rr,on_artifact_run_filter_change:v=>{const T=String(v||"").trim();Yn(T),T&&Es(T),T&&Eo!=="run"&&Ai("run")},on_refresh_artifacts:()=>void Bl(),on_refresh_audit:()=>void la(),on_refresh_runtime_ledger:v=>void Uc(v),on_runtime_log_source_change:Ti,on_runtime_log_query_change:e_,on_select_run:v=>{const T=String(v||"").trim();Es(T);const F=T&&As[T]||null,B=String((F==null?void 0:F.session_id)||"").trim();B&&Xm(B)},on_select_artifact:Mo,on_preview_artifact:v=>void Zu(v),on_download_artifact:v=>void c_(v),on_open_run:v=>{Es(String(v||"").trim()),t("observe"),jo("ledger"),Mi(v)},on_open_ledger:v=>{Es(String(v||"").trim()),t("observe"),jo("ledger"),Mi(v)},on_refresh_runs:()=>void Pn(Ke,{force:!0}),on_reconnect:()=>void Po({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:L?s.jsx(OB,{gateway:Ke,selected_run_id:ai,selected_session_id:fo}):null}):null,e==="observe"?s.jsx("div",{className:"page observe_page",children:s.jsxs("div",{className:`observatory_layout${Fm?"":" list_collapsed"}`,children:[s.jsx(lP,{sections:Wc,selected_run_id:l,root_run_id:h,search:Eu,filter:Au,group_by:_f,loading:ss,connected:L,on_sign_in:()=>J.openModal(),total_runs:uo.length,workflow_label_by_id:di,automation_titles:Pf,on_search:Dm,on_filter:gl,on_group_by:Gg,on_refresh:()=>void Pn(),on_select:(v,T)=>{Mi(v,{root_run_id:T||v}),Ul()},list:{open:Fm,on_toggle:zm}}),s.jsxs("div",{className:"observatory_main",children:[s.jsxs("div",{className:"observe_toolbar",children:[s.jsxs("div",{className:"observe_toolbar_row",children:[l.trim()?s.jsxs("div",{className:"observe_run_identity",title:l.trim(),children:[s.jsx("span",{className:"observe_run_name",children:di[String(($n==null?void 0:$n.workflow_id)||"")]||String(($n==null?void 0:$n.workflow_id)||"").trim()||Rn(l.trim(),22)}),s.jsx("span",{className:"chip mono muted",children:Rn(l.trim(),14)}),s.jsx("span",{className:`chip ${ka(ps||lo,co)}`,title:String((co==null?void 0:co.headline)||""),children:ps||lo||"unknown"})]}):y?s.jsx("span",{className:"observe_run_identity_empty observe_run_link_missing",role:"alert",children:cI(y)}):s.jsx("span",{className:"observe_run_identity_empty",children:"No run selected"}),s.jsx("span",{className:"observe_toolbar_spacer"}),l.trim()?s.jsxs(s.Fragment,{children:[Kn?s.jsx(t4,{active:!ws,unavailableReason:ny,busy:Be||Tt,onChange:v=>{if(!v){Wr("pause"),qr(""),$i(""),Ur(!0);return}Yf("resume")}}):s.jsx("button",{className:"btn",onClick:()=>{if(Fc==="pause"){Wr("pause"),qr(""),$i(""),Ur(!0);return}Yf("resume")},disabled:cr,children:S_}),jt?s.jsx("button",{className:"btn primary",onClick:()=>void Xf(),disabled:Be||Tt||mi||ws,children:"Run now"}):null,s.jsx("button",{className:"btn danger",onClick:()=>{Wr("cancel"),qr(""),$i(""),Ur(!0)},disabled:Be||Tt||mi,children:"Cancel"}),s.jsx("button",{className:"btn btn_icon",onClick:Pl,title:"Clear the run view",children:s.jsx(qe,{name:"x",size:14})})]}):null]}),l.trim()&&!mi?s.jsx("div",{className:"observe_steer_row",children:s.jsx(D2,{runId:l.trim(),parked:Pc,submit:(v,T)=>Ke.submit_command({command_id:`steer-${Xs()}`,run_id:v,type:"inject_guidance",payload:{guidance:T},client_id:"web_pwa"}).then(F=>({accepted:!!(F!=null&&F.accepted),duplicate:!!(F!=null&&F.duplicate),seq:Number((F==null?void 0:F.seq)??0)})),onSent:()=>bn({ts:on(),kind:"info",title:"Steer queued",preview:"inject_guidance submitted — delivery shows as abstract.steer_seen in the ledger"})})}):null,Pc||Kn||Cu?s.jsxs("div",{className:"observe_toolbar_context",children:[Pc?s.jsxs("div",{className:"observe_context_card info",children:[s.jsxs("div",{className:"observe_context_label",children:[(()=>{const v=Kn?ws?"suspended":"scheduled":"waiting";return s.jsx("span",{className:`chip ${ka(v)}`,children:v})})(),s.jsx("span",{className:"muted",children:Bs||"unknown"})]}),s.jsxs("div",{className:"observe_context_body",children:[lr?s.jsxs("span",{className:"mono",title:lr,children:[s.jsx("span",{className:"muted",children:"wait_key"}),": ",Rn(lr,46)]}):null,Bs==="event"&&rd?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"event"}),": ",rd]}):null,Bs==="subworkflow"&&oa?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"child"}),": ",Rn(oa,18)]}):null,Bs==="until"&&oo?s.jsxs("span",{className:"mono",title:oo,children:[s.jsx("span",{className:"muted",children:"until"}),": ",Rn(oo,46)]}):null,Bs==="until"&&oo?s.jsx("span",{className:"mono muted",children:(()=>{const v=Ht(oo),T=v!==null?new Date(v).toLocaleString():oo,F=v!==null?em(v-Date.now()):"";return`Next at ${T}${F?` (in ${F})`:""}`})()}):null]}),Bs==="subworkflow"&&oa?s.jsxs("div",{className:"observe_context_actions",children:[s.jsx("button",{className:"btn primary",onClick:async()=>{d(oa),await nd(oa)},disabled:Be,children:"Attach to child"}),h.trim()&&h.trim()!==l.trim()?s.jsx("button",{className:"btn",onClick:async()=>{d(h.trim()),await nd(h.trim())},disabled:Be,children:"Back to root"}):null]}):null]}):null,Kn?s.jsxs("div",{className:"observe_context_card muted",children:[s.jsxs("div",{className:"observe_context_label",children:[s.jsx("span",{className:"chip muted",children:"schedule"}),s.jsx("span",{className:"muted",children:th?`every ${qa}`:"once"})]}),s.jsxs("div",{className:"observe_context_body",children:[qa?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"interval"}),": ",qa]}):null,s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"share ctx"}),": ",j_?"yes":"no"]}),typeof zl=="number"?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"repeats"}),": ",zl]}):null]}),Ha!==null?s.jsxs("div",{className:"observe_context_budget",children:[s.jsxs("span",{className:"mono muted",children:[typeof nh=="number"&&typeof N_=="number"?`${nh.toLocaleString()} / ${N_.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,Ha))*100)}%`]}),s.jsx("div",{className:"observe_budget_bar",children:s.jsx("div",{className:`observe_budget_fill ${Ha>=.9?"danger":Ha>=.75?"warn":"ok"}`,style:{width:`${Math.round(Math.max(0,Math.min(1,Ha))*100)}%`}})})]}):null,s.jsxs("div",{className:"observe_context_actions",children:[th?s.jsx("button",{className:"btn",onClick:()=>{ys(qa||""),Ms(!0),ks(""),zi(!0)},disabled:Be||ri,children:"Edit schedule"}):null,th?s.jsx("button",{className:"btn",onClick:()=>{Ps(""),Sa(!0)},disabled:Be||Ds,children:"Compact context"}):null,s.jsx("button",{className:"btn",onClick:()=>void Jf(l.trim()).catch(v=>En(String((v==null?void 0:v.message)||v))),disabled:Be||!l.trim(),title:"Open Launch → Automate prefilled from this schedule (this schedule is not changed)",children:"Recreate as automation"})]})]}):null,Cu?s.jsxs("div",{className:"observe_context_card error",children:[s.jsx("span",{className:"chip danger",children:"error"}),s.jsx("span",{className:"mono",children:Cu})]}):null]}):null]}),s.jsxs("div",{className:"card panel_card card_scroll observe_viewer observe_viewer_full",ref:vf,children:[s.jsxs("div",{className:"tab_bar",children:[s.jsxs("div",{role:"tablist","aria-label":"Run views",className:"observe_tablist",children:[s.jsx("button",{role:"tab","aria-selected":js==="agent",className:`tab ${js==="agent"?"active":""}`,onClick:()=>zo("agent"),children:"Agent"}),s.jsx("button",{role:"tab","aria-selected":js==="ledger",className:`tab ${js==="ledger"?"active":""}`,onClick:()=>zo("ledger"),children:"Ledger"}),s.jsx("button",{role:"tab","aria-selected":js==="graph",className:`tab ${js==="graph"?"active":""}`,onClick:()=>zo("graph"),children:"Flow"}),s.jsx("button",{role:"tab","aria-selected":js==="chat",className:`tab ${js==="chat"?"active":""}`,onClick:()=>zo("chat"),children:"Ask"})]}),js==="ledger"&&(fn.length>0||nn.length>0)?s.jsx("div",{className:"tab_bar_controls",children:s.jsx("button",{className:"seg_action",disabled:!fn.length&&!nn.length,title:"Copy full ledger as JSONL",onClick:()=>{const F=[...fn.map(X=>({run_id:l.trim()||X.record.run_id||"",cursor:X.cursor,record:X.record})),...nn.map(X=>({run_id:X.run_id,cursor:X.cursor,record:X.record}))].map(X=>{var Ge,ke;const ee=String(((Ge=X.record)==null?void 0:Ge.ended_at)||((ke=X.record)==null?void 0:ke.started_at)||"").trim(),oe=Ht(ee);return{...X,_ms:oe??0}});F.sort((X,ee)=>(X._ms||0)-(ee._ms||0));const Z=(F.length>5e3?F.slice(F.length-5e3):F).map(({_ms:X,...ee})=>JSON.stringify(ee)).join(`
175
+ `);Or(Z)},children:"Copy JSONL"})}):null,js==="graph"?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsx("button",{className:`seg_action ${Ki?"active":""}`,"aria-pressed":Ki,onClick:()=>jf(v=>!v),children:"Subflows"}),s.jsx("button",{className:`seg_action ${Ma?"active":""}`,"aria-pressed":Ma,onClick:()=>Sf(v=>!v),children:"Path"}),sh.length?s.jsx("select",{className:"mono seg_select",value:yl,onChange:v=>yr(String(v.target.value||"")),disabled:!!Ri.trim()||!N.trim()||kf,children:sh.map(v=>s.jsx("option",{value:v,children:v},v))}):null]}):null]}),js==="agent"?l.trim()&&_s?s.jsx(GW,{run:_s,detail:we,input_data:Gn.key===ls?Gn.input_data:null,flow:Gn.key===ls?Gn.flow:null,automation:Gn.key===ls?Gn.automation:null,automation_body:Gn.key===ls?Gn.automation_body:null,runs:ud,records:Li,stall_after_ms:lC(typeof localStorage>"u"?null:localStorage),loading:{detail:Be&&!we,input_data:Gn.key!==ls||Gn.loading,flow:Gn.key!==ls||Gn.loading},errors:Gn.key===ls?{input_data:Gn.input_error||void 0,flow:Gn.flow_error||void 0}:{},on_open_run:v=>void Mi(v),on_ask:()=>zo("chat"),on_action:(v,T)=>{if(v==="resume"){Lc(T,"resume");return}if(v==="open_subrun"){Mi(T);return}oi(""),zo("ledger")},on_reveal_workspace:()=>void Ol(),on_copy:v=>void Or(v)}):s.jsx("div",{className:"rs_page",children:s.jsx("p",{className:"rs_notice",children:l.trim()?"Loading the run…":"Pick a run to see what its agent can do, what it was given, and where it stands."})}):null,js==="ledger"?l.trim()?s.jsxs("div",{className:"rs_page",children:[s.jsx(GI,{status:ps||lo||"unknown",duration:$n?pu($n):"",facts:II(LI(Li)),error:nm($n)||String((we==null?void 0:we.error)||"").trim(),answer:rh||String((ao==null?void 0:ao.text)||"").trim(),waiting_for_user:!!(un!=null&&un.wait_key)&&String((un==null?void 0:un.reason)||"")==="user",on_answer_wait:()=>oi(""),workspace_root:Wm,on_reveal_workspace:()=>void Ol(),speak:L?s.jsx(_O,{voice:io,speak_key:`outcome:${l.trim()}`,text:nm($n)||String((we==null?void 0:we.error)||"").trim()||rh||String((ao==null?void 0:ao.text)||"").trim(),error:Wt}):null,on_open_artifacts:()=>{const v=String(l||"").trim();v&&(Es(v),Yn(v),Ai("run")),Gm("artifacts"),t("runtime")}}),s.jsx(VI,{items:Li,run_id:Ii,run_options:aa,run_llm_counts:Bc,on_select_run:v=>Um(v),state:Bm,on_state:E_,node_label:(v,T)=>{const F=T?(Yr==null?void 0:Yr[ar(v,T)])||(Yr==null?void 0:Yr[T]):null;return String((F==null?void 0:F.label)||T||"").trim()},on_copy:v=>void Or(v),on_open_run:v=>void Mi(v,{root_run_id:h||l||v})})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run on the left to inspect it — or start one from Launch."}):null,js==="graph"?s.jsxs(s.Fragment,{children:[qm?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"graph error"}),s.jsx("span",{className:"mono",children:on()})]}),s.jsx("div",{className:"body mono",children:qm})]}):null,kf?s.jsxs("div",{className:"log_item log_item_info",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"loading"}),s.jsx("span",{className:"mono",children:Ri.trim()?Ri.trim():yl})]}),s.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,s.jsx("div",{className:"graph_panel",children:s.jsx(d5,{flow:Gi,flow_by_id:gc,expand_subflows:Ki,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:Sr,schedule_interval:qa,node_last_ms:C_,active_node_id:$_,recent_nodes:Hm,visited_nodes:Vm,highlight_path:Ma,now_ms:Mu,run_id:l.trim(),run_line:sy,run_status:ps||lo,node_facts:R_,on_open_run:v=>void Mi(v)})})]}):null,js==="chat"?s.jsxs("div",{className:"ask_tab log_scroll",style:{marginTop:"6px"},children:[s.jsxs("div",{className:"ask_header",children:[s.jsx("span",{className:"ask_title",children:"Ask about this run"}),s.jsx("span",{className:"chip muted",title:"Model comes from Settings → Assistant (blank = gateway default)",children:(n.maintenance_ai_provider.trim()||"gateway")+" / "+(n.maintenance_ai_model.trim()||"default")}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:"ask_hint",children:"Read-only · grounded in this run + subflows"})]}),s.jsxs("details",{className:"ask_manage",children:[s.jsx("summary",{children:"History & export"}),s.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[s.jsxs("div",{className:"actions",style:{justifyContent:"space-between",alignItems:"center",gap:"10px",flexWrap:"wrap",marginTop:0},children:[s.jsx("div",{style:{flex:1,minWidth:260},children:s.jsx(Br,{value:df,options:ff,placeholder:_c?"Loading…":ff.length?"Select a saved discussion…":"(none saved)",disabled:!l.trim()||!L||!ff.length,loading:_c,searchable:!0,clearable:!0,onChange:v=>{ju(v),Aa("")}})}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[s.jsx("button",{className:"btn",type:"button",disabled:!df.trim()||!L||Su,onClick:()=>void Qg(),children:Su?"Loading…":"Load"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ft.length||Bt||gr||Su,onClick:()=>{xn([]),Hn(null),De(""),ht(""),Hi(""),hc(""),Ea("")},children:"Clear"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>void Ic(),disabled:!l.trim()||!L||_c,children:_c?"Refreshing…":"Refresh"})]})]}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:"8px",flexWrap:"wrap"},children:[s.jsx("button",{className:"btn",type:"button",disabled:!Ft.length||!l.trim()||!L||gr||!Nu,onClick:()=>void Qf(),title:Nu?"":"No changes since last save",children:gr?"Saving…":!Nu&&lf?"Saved":"Save discussion"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ft.length,onClick:()=>Wa("download"),children:"Export Markdown"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ft.length,onClick:()=>Wa("copy"),children:Cn==="copied"?"Copied":Cn==="failed"?"Copy failed":"Copy Markdown"})]}),lf?s.jsxs("div",{className:"chat_hint",children:["Last saved: ",lu(lf)]}):null,hl?s.jsx("div",{className:"chat_hint chat_hint_danger",children:hl}):null,Lm?s.jsx("div",{className:"chat_hint chat_hint_danger",children:Lm}):null,uf?s.jsx("div",{className:"chat_hint chat_hint_danger",children:uf}):null]})]}),Ye?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"error"}),s.jsx("span",{className:"mono",children:on()})]}),s.jsx("div",{className:"body mono",children:Ye})]}):null,Wt?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"voice"}),s.jsx("span",{className:"mono",children:on()})]}),s.jsx("div",{className:"body mono",children:Wt})]}):null,s.jsx("div",{className:"chat_messages",style:{marginTop:"10px"},children:s.jsx(nx,{messages:Ft,className:"log_scroll",after:s.jsx(iI,{history:os}),afterKey:os?`${os.replayed_messages}:${os.dropped_messages}`:null,messageProps:io.tts_supported&&L?{onSpeakToggle:p_,getSpeakState:Zf,jsonCollapseAfterDepth:4}:{jsonCollapseAfterDepth:4},empty:s.jsx("div",{className:"chat_empty_hint",children:"Ask about this run (why failed, which tools, what happened in subflows)."})})}),s.jsxs("div",{className:"chat_composer",style:{marginTop:"10px"},children:[s.jsx(sx,{ref:Mr,value:Oe,onChange:De,onSubmit:()=>void __(),placeholder:"Ask about this run…",disabled:!l.trim()||!L||Bt,busy:Bt||io.voice_ptt_busy,busyLabel:io.voice_ptt_busy?"Transcribing…":"Thinking…",rows:3,sendButtonClassName:"btn primary",actions:s.jsx(JN,{voice:io,defaults:Vf.value,prefs:Mc,blocked:L?Bt?"Wait for the answer.":null:"Connect to the gateway first."})}),WN()?null:s.jsx("div",{className:"mono muted","data-testid":"voice-https-hint",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:BN})]})]}):null,l.trim()?s.jsxs("div",{className:`status_bar ${$a?"pulse":""}`,children:[s.jsx("strong",{children:"Run"}),":"," ",s.jsx("span",{className:"mono",children:ps||lo||"unknown"}),$s&&Sr?s.jsxs("span",{className:"mono muted",children:[" • next in ",Sr]}):null,Yo?s.jsxs("span",{className:"mono muted",children:[" • ",Yo]}):null]}):null]})]})]})}):null,s.jsxs(ec,{open:Zm,title:Bu||"Artifact",onClose:()=>{Nl(!1),sa(""),Qi(""),br(!1),El(null),ir&&(URL.revokeObjectURL(ir),Wu(""))},actions:s.jsx("button",{className:"btn",onClick:()=>{Nl(!1),sa(""),Qi(""),br(!1),El(null),ir&&(URL.revokeObjectURL(ir),Wu(""))},children:"Close"}),children:[qu?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,Gr?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:Gr}):null,Zi==="image"&&ir?s.jsx("img",{className:"runtime_preview_media",src:ir,alt:Bu||"Artifact preview"}):Zi==="audio"&&ir?s.jsx(Cg,{className:"runtime_preview_media",src:ir,name:Bu||void 0}):Zi==="video"&&ir?s.jsx("video",{className:"runtime_preview_media",controls:!0,src:ir}):s.jsx(h1,{artifact:Cl,text:Uu||"(empty)",className:"runtime_preview_text"})]}),Ts?s.jsxs(ec,{open:Ts,title:"Edit schedule",onClose:()=>{zi(!1),ys(""),Ms(!0),ks(""),Bi(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{zi(!1),ys(""),Ms(!0),ks(""),Bi(!1)},disabled:Be||ri,children:"Back"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await sd({interval:cl,apply_immediately:ni})||(zi(!1),ks(""),Bi(!1))},disabled:Be||ri||!cl.trim(),children:"Save"})]}),children:[si?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:on()})]}),s.jsx("div",{className:"body mono",children:si})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Interval"}),s.jsx("input",{className:"mono",value:cl,onChange:v=>ys(String(v.target.value||"")),placeholder:"20m / 1h / 0.5s / 250ms",disabled:Be||ri}),s.jsxs("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)"},children:["Accepted units: ",s.jsx("span",{className:"mono",children:"ms"}),", ",s.jsx("span",{className:"mono",children:"s"}),", ",s.jsx("span",{className:"mono",children:"m"}),","," ",s.jsx("span",{className:"mono",children:"h"}),", ",s.jsx("span",{className:"mono",children:"d"}),". This updates the existing scheduled run in place (no context loss)."]})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Quick picks"}),s.jsx("div",{className:"actions",style:{gap:"8px",flexWrap:"wrap"},children:["15m","30m","1h","2h","6h","1d"].map(v=>s.jsx("button",{className:"btn",onClick:()=>ys(v),disabled:Be||ri,children:v},v))})]}),s.jsx("div",{className:"field",children:s.jsx(s4,{checked:ni,busy:Be||ri,onChange:Ms})})]}):null,Ln?s.jsxs(ec,{open:Ln,title:"Compact scheduled context",onClose:()=>{Sa(!1),Ps(""),pr(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Sa(!1),Ps(""),pr(!1)},disabled:Be||Ds,children:"Cancel"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await m_({preserve_recent:ul,compression_mode:Ar,focus:Ui})||(Sa(!1),Ps(""),pr(!1))},disabled:Be||Ds,children:Ds?"Compacting…":"Compact"})]}),children:[xo?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:on()})]}),s.jsx("div",{className:"body mono",children:xo})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Preserve recent turns"}),s.jsx("input",{type:"number",min:1,value:String(ul),onChange:v=>dl(Math.max(1,parseInt(v.target.value||"6",10)||6)),disabled:Be||Ds})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Mode"}),s.jsxs("select",{value:Ar,onChange:v=>dc(v.target.value),disabled:Be||Ds,children:[s.jsx("option",{value:"light",children:"light"}),s.jsx("option",{value:"standard",children:"standard"}),s.jsx("option",{value:"heavy",children:"heavy"})]})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Focus (optional)"}),s.jsx("input",{className:"mono",value:Ui,onChange:v=>Na(String(v.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:Be||Ds})]})]}):null,bo?s.jsxs(ec,{open:bo,title:Tr==="cancel"?"Cancel run":Kn?"Suspend schedule":"Pause run",onClose:()=>{Ur(!1),qr(""),$i("")},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Ur(!1),qr(""),$i("")},disabled:Be||Tt,children:"Back"}),s.jsx("button",{className:`btn ${Tr==="cancel"?"danger":"primary"}`,onClick:async()=>{$i("");const v=await Yf(Tr,{reason:fc});if(v){$i(v);return}Ur(!1),qr(""),$i("")},disabled:Be||Tt,children:Tr==="pause"?Kn?"Suspend":"Pause":"Cancel"})]}),children:[xu?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:on()})]}),s.jsx("div",{className:"body mono",children:xu})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Reason (optional)"}),s.jsx("input",{className:"mono",value:fc,onChange:v=>qr(v.target.value),placeholder:"reason…"})]})]}):null,id?s.jsxs(ec,{open:id,title:ad,onClose:()=>{lr&&oi(lr)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{jo("ledger"),t("observe"),Ul(),lr&&oi(lr)},disabled:!l.trim(),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>lr&&oi(lr),disabled:Tt,children:"Dismiss"}),ia.length?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn danger",disabled:Tt,onClick:()=>Oc({approved:!1}),children:"Reject"}),s.jsx("button",{className:"btn",disabled:Tt,onClick:()=>Oc({approved:!0}),children:"Approve only"}),s.jsx("button",{className:"btn primary",disabled:!no||Tt,onClick:()=>g_(ia),children:"Approve and execute"})]}):null]}),children:[s.jsxs("div",{className:"wait_context_panel",children:[s.jsxs("div",{className:"wait_context_header",children:[s.jsxs("div",{children:[s.jsx("div",{className:"run_hero_eyebrow",children:"What you need to do"}),s.jsx("strong",{children:ad}),s.jsx("p",{children:x_})]}),s.jsx(gu,{status:Ns||"waiting"})]}),Do?s.jsxs("div",{className:`wait_request_card ${Fl?"":"inferred"}`,children:[s.jsx("span",{children:Fo}),s.jsx(Ej,{metadata:ey}),s.jsx(Si,{text:Do}),Fl?null:s.jsx("p",{className:"wait_context_note",children:"The runtime did not attach a specific question to this wait. This is inferred from the run input; verify the session turns and workflow steps before answering."})]}):s.jsx("div",{className:"warn_callout",children:"This wait did not provide a clear prompt or recoverable prior user request. Review the full run input and recent workflow steps before submitting a response."}),cd.length?s.jsxs("section",{className:"wait_context_block wait_conversation_context",children:[s.jsx("span",{children:"Recent session turns"}),s.jsx("div",{className:"wait_turn_list",children:cd.map((v,T)=>s.jsxs("div",{className:`wait_turn_row role_${v.role.replace(/[^a-z0-9_-]+/g,"_")}`,children:[s.jsxs("div",{className:"wait_turn_meta",children:[s.jsx("strong",{children:v.role==="assistant"?"Assistant":v.role==="user"||v.role==="human"?"User":v.role}),v.ts?s.jsx("span",{className:"mono muted",children:lu(v.ts)}):null]}),s.jsx(Ej,{metadata:v.runtime_metadata}),s.jsx(Si,{text:en(v.text,{max_chars:1200,max_lines:10})})]},`${v.role}:${T}`))})]}):null,s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:Vo(Dl,di)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:Rn(l.trim(),24)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Dl.current_node||String((or==null?void 0:or.node_id)||"—")})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:pu(Dl)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:Dl.session_id?Rn(String(Dl.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:Rn(lr,28)})]})]}),k_?s.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!Do,children:[s.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(fr,{value:ty,collapseAfterDepth:4,showCopy:!0})})]}):null,s.jsxs("section",{className:"wait_context_block",children:[s.jsx("span",{children:"Recent workflow steps leading to this wait"}),s.jsxs("div",{className:"wait_event_list",children:[od.map(v=>s.jsxs("div",{className:"wait_event_row",children:[s.jsxs("span",{className:"mono",children:["#",v.cursor]}),s.jsx("strong",{children:v.summary||v.effect_type||v.status||"event"}),s.jsx("span",{className:"mono muted",children:[v.node_id,v.status,lu(v.ts)].filter(Boolean).join(" · ")})]},`${v.cursor}:${v.node_id}:${v.status}`)),od.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),ia.length?s.jsxs("div",{className:"wait_action_panel",children:[s.jsx("div",{className:"wait_action_intro",children:"Approve and execute runs the listed tool request through your configured worker. Approve only sends approval without local execution. Reject returns a denial. Cancel run stops the whole workflow run."}),s.jsx("div",{className:"wait_tool_list",children:ia.map((v,T)=>s.jsxs("div",{className:"wait_tool_card",children:[s.jsxs("div",{className:"wait_tool_header",children:[s.jsx("strong",{children:String((v==null?void 0:v.name)||"tool")}),s.jsxs("div",{className:"wait_tool_badges",children:[s.jsx("span",{className:"chip mono warn",children:"approval"}),i1(v).map(F=>s.jsxs("span",{className:"chip mono muted",title:r1,children:[F,"~"]},F))]})]}),s.jsx("div",{className:"wait_tool_args",children:s.jsx(fr,{value:(v==null?void 0:v.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((v==null?void 0:v.name)||"tool")}:${T}`))}),no?null:s.jsx("div",{className:"warn_callout",children:"No tool worker is configured, so Observer cannot execute these calls directly."}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void hi(l.trim(),"Cancelled from wait prompt"),disabled:!l.trim()||Tt,children:"Cancel whole run"})}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Diagnostics"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(fr,{value:un||{},collapseAfterDepth:3,showCopy:!0})})]})]}):s.jsxs("div",{className:"wait_action_panel",children:[s.jsx("div",{className:"wait_action_intro",children:"Submit only when the request above is clear. The response resumes this wait only; Cancel run attempts to stop the whole workflow and prevent further work."}),s.jsx("div",{className:"wait_prompt_text",children:Do||"No explicit prompt was provided. Open the ledger for context before responding."}),s.jsx(aP,{wait:un,disabled:Tt,on_submit:v=>Oc({response:v})}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void hi(l.trim(),"Cancelled from wait prompt"),disabled:!l.trim()||Tt,children:"Cancel whole run"})}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Diagnostics"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(fr,{value:un||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(aI).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}t2();JC.createRoot(document.getElementById("root")).render(s.jsx(Ee.StrictMode,{children:s.jsx(tq,{})}));
176
+ //# sourceMappingURL=index-B3dE0pZp.js.map