@abstractframework/observer 0.8.0 → 0.10.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,178 @@
1
+ var rE=Object.defineProperty;var iE=(e,t,n)=>t in e?rE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var jn=(e,t,n)=>iE(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 c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).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 Gv(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var uy={exports:{}},ph={},dy={exports:{}},Sn={};/**
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 Qx;function oE(){if(Qx)return Sn;Qx=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"),c=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(){}},x=Object.assign,k={};function v(z,ne,se){this.props=z,this.context=ne,this.refs=k,this.updater=se||y}v.prototype.isReactComponent={},v.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")},v.prototype.forceUpdate=function(z){this.updater.enqueueForceUpdate(this,z,"forceUpdate")};function N(){}N.prototype=v.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=$,x(E,v.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 V=/\/+/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(V,"$&/")+"/"),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(V,"$&/")+"/")+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 H={current:null},J={transition:null},U={ReactCurrentDispatcher:H,ReactCurrentBatchConfig:J,ReactCurrentOwner:D};function te(){throw Error("act(...) is not supported in production builds of React.")}return Sn.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}},Sn.Component=v,Sn.Fragment=n,Sn.Profiler=i,Sn.PureComponent=$,Sn.StrictMode=r,Sn.Suspense=d,Sn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=U,Sn.act=te,Sn.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=x({},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}},Sn.createContext=function(z){return z={$$typeof:c,_currentValue:z,_currentValue2:z,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},z.Provider={$$typeof:o,_context:z},z.Consumer=z},Sn.createElement=I,Sn.createFactory=function(z){var ne=I.bind(null,z);return ne.type=z,ne},Sn.createRef=function(){return{current:null}},Sn.forwardRef=function(z){return{$$typeof:l,render:z}},Sn.isValidElement=G,Sn.lazy=function(z){return{$$typeof:m,_payload:{_status:-1,_result:z},_init:L}},Sn.memo=function(z,ne){return{$$typeof:h,type:z,compare:ne===void 0?null:ne}},Sn.startTransition=function(z){var ne=J.transition;J.transition={};try{z()}finally{J.transition=ne}},Sn.unstable_act=te,Sn.useCallback=function(z,ne){return H.current.useCallback(z,ne)},Sn.useContext=function(z){return H.current.useContext(z)},Sn.useDebugValue=function(){},Sn.useDeferredValue=function(z){return H.current.useDeferredValue(z)},Sn.useEffect=function(z,ne){return H.current.useEffect(z,ne)},Sn.useId=function(){return H.current.useId()},Sn.useImperativeHandle=function(z,ne,se){return H.current.useImperativeHandle(z,ne,se)},Sn.useInsertionEffect=function(z,ne){return H.current.useInsertionEffect(z,ne)},Sn.useLayoutEffect=function(z,ne){return H.current.useLayoutEffect(z,ne)},Sn.useMemo=function(z,ne){return H.current.useMemo(z,ne)},Sn.useReducer=function(z,ne,se){return H.current.useReducer(z,ne,se)},Sn.useRef=function(z){return H.current.useRef(z)},Sn.useState=function(z){return H.current.useState(z)},Sn.useSyncExternalStore=function(z,ne,se){return H.current.useSyncExternalStore(z,ne,se)},Sn.useTransition=function(){return H.current.useTransition()},Sn.version="18.3.1",Sn}var eb;function wm(){return eb||(eb=1,dy.exports=oE()),dy.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 tb;function aE(){if(tb)return ph;tb=1;var e=wm(),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 c(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 ph.Fragment=n,ph.jsx=c,ph.jsxs=c,ph}var nb;function lE(){return nb||(nb=1,uy.exports=aE()),uy.exports}var s=lE(),p=wm();const Ee=Gv(p);var H_={},fy={exports:{}},vi={},hy={exports:{}},my={};/**
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 sb;function cE(){return sb||(sb=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 c=Date,l=c.now();e.unstable_now=function(){return c.now()-l}}var d=[],h=[],m=1,_=null,g=3,y=!1,x=!1,k=!1,v=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),!x)if(n(d)!==null)x=!0,L(P);else{var U=n(h);U!==null&&H(S,U.startTime-J)}}function P(J,U){x=!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&&H(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 V(){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(){$(V)};else if(typeof MessageChannel<"u"){var A=new MessageChannel,O=A.port2;A.port1.onmessage=V,M=function(){O.postMessage(null)}}else M=function(){v(V,0)};function L(J){R=J,D||(D=!0,M())}function H(J,U){I=v(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(){x||y||(x=!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,H(S,te-z))):(J.sortIndex=ne,t(d,J),x||y||(x=!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}}}})(my)),my}var rb;function uE(){return rb||(rb=1,hy.exports=cE()),hy.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 ib;function dE(){if(ib)return vi;ib=1;var e=wm(),t=uE();function n(a){for(var u="https://reactjs.org/docs/error-decoder.html?invariant="+a,f=1;f<arguments.length;f++)u+="&args[]="+encodeURIComponent(arguments[f]);return"Minified React error #"+a+"; visit "+u+" 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,u){c(a,u),c(a+"Capture",u)}function c(a,u){for(i[a]=u,a=0;a<u.length;a++)r.add(u[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,u,f,w){if(f!==null&&f.type===0)return!1;switch(typeof u){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 x(a,u,f,w){if(u===null||typeof u>"u"||y(a,u,f,w))return!0;if(w)return!1;if(f!==null)switch(f.type){case 3:return!u;case 4:return u===!1;case 5:return isNaN(u);case 6:return isNaN(u)||1>u}return!1}function k(a,u,f,w,j,C,q){this.acceptsBooleans=u===2||u===3||u===4,this.attributeName=w,this.attributeNamespace=j,this.mustUseProperty=f,this.propertyName=a,this.type=u,this.sanitizeURL=C,this.removeEmptyString=q}var v={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){v[a]=new k(a,0,!1,a,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var u=a[0];v[u]=new k(u,1,!1,a[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(a){v[a]=new k(a,2,!1,a.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){v[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){v[a]=new k(a,3,!1,a.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(a){v[a]=new k(a,3,!0,a,null,!1,!1)}),["capture","download"].forEach(function(a){v[a]=new k(a,4,!1,a,null,!1,!1)}),["cols","rows","size","span"].forEach(function(a){v[a]=new k(a,6,!1,a,null,!1,!1)}),["rowSpan","start"].forEach(function(a){v[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 u=a.replace(N,$);v[u]=new k(u,1,!1,a,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var u=a.replace(N,$);v[u]=new k(u,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(a){var u=a.replace(N,$);v[u]=new k(u,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(a){v[a]=new k(a,1,!1,a.toLowerCase(),null,!1,!1)}),v.xlinkHref=new k("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(a){v[a]=new k(a,1,!1,a.toLowerCase(),null,!0,!0)});function E(a,u,f,w){var j=v.hasOwnProperty(u)?v[u]:null;(j!==null?j.type!==0:w||!(2<u.length)||u[0]!=="o"&&u[0]!=="O"||u[1]!=="n"&&u[1]!=="N")&&(x(u,f,j,w)&&(f=null),w||j===null?g(u)&&(f===null?a.removeAttribute(u):a.setAttribute(u,""+f)):j.mustUseProperty?a[j.propertyName]=f===null?j.type===3?!1:"":f:(u=j.attributeName,w=j.attributeNamespace,f===null?a.removeAttribute(u):(j=j.type,f=j===3||j===4&&f===!0?"":""+f,w?a.setAttributeNS(w,u,f):a.setAttribute(u,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"),V=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"),H=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 u=f.stack.trim().match(/\n( *(at )?)/);z=u&&u[1]||""}return`
34
+ `+z+a}var se=!1;function de(a,u){if(!a||se)return"";se=!0;var f=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(u)if(u=function(){throw Error()},Object.defineProperty(u.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(u,[])}catch(Te){var w=Te}Reflect.construct(a,[],u)}else{try{u.call()}catch(Te){w=Te}a.call(u.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 V:var u=a.render;return a=a.displayName,a||(a=u.displayName||u.name||"",a=a!==""?"ForwardRef("+a+")":"ForwardRef"),a;case O:return u=a.displayName||null,u!==null?u:Me(a.type)||"Memo";case L:u=a._payload,a=a._init;try{return Me(a(u))}catch{}}return null}function je(a){var u=a.type;switch(a.tag){case 24:return"Cache";case 9:return(u.displayName||"Context")+".Consumer";case 10:return(u._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return a=u.render,a=a.displayName||a.name||"",u.displayName||(a!==""?"ForwardRef("+a+")":"ForwardRef");case 7:return"Fragment";case 5:return u;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Me(u);case 8:return u===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 u=="function")return u.displayName||u.name||null;if(typeof u=="string")return u}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 u=a.type;return(a=a.nodeName)&&a.toLowerCase()==="input"&&(u==="checkbox"||u==="radio")}function Ae(a){var u=xe(a)?"checked":"value",f=Object.getOwnPropertyDescriptor(a.constructor.prototype,u),w=""+a[u];if(!a.hasOwnProperty(u)&&typeof f<"u"&&typeof f.get=="function"&&typeof f.set=="function"){var j=f.get,C=f.set;return Object.defineProperty(a,u,{configurable:!0,get:function(){return j.call(this)},set:function(q){w=""+q,C.call(this,q)}}),Object.defineProperty(a,u,{enumerable:f.enumerable}),{getValue:function(){return w},setValue:function(q){w=""+q},stopTracking:function(){a._valueTracker=null,delete a[u]}}}}function Ve(a){a._valueTracker||(a._valueTracker=Ae(a))}function mt(a){if(!a)return!1;var u=a._valueTracker;if(!u)return!0;var f=u.getValue(),w="";return a&&(w=xe(a)?a.checked?"true":"false":a.value),a=w,a!==f?(u.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,u){var f=u.checked;return te({},u,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:f??a._wrapperState.initialChecked})}function ze(a,u){var f=u.defaultValue==null?"":u.defaultValue,w=u.checked!=null?u.checked:u.defaultChecked;f=ae(u.value!=null?u.value:f),a._wrapperState={initialChecked:w,initialValue:f,controlled:u.type==="checkbox"||u.type==="radio"?u.checked!=null:u.value!=null}}function He(a,u){u=u.checked,u!=null&&E(a,"checked",u,!1)}function ct(a,u){He(a,u);var f=ae(u.value),w=u.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}u.hasOwnProperty("value")?Dt(a,u.type,f):u.hasOwnProperty("defaultValue")&&Dt(a,u.type,ae(u.defaultValue)),u.checked==null&&u.defaultChecked!=null&&(a.defaultChecked=!!u.defaultChecked)}function Qe(a,u,f){if(u.hasOwnProperty("value")||u.hasOwnProperty("defaultValue")){var w=u.type;if(!(w!=="submit"&&w!=="reset"||u.value!==void 0&&u.value!==null))return;u=""+a._wrapperState.initialValue,f||u===a.value||(a.value=u),a.defaultValue=u}f=a.name,f!==""&&(a.name=""),a.defaultChecked=!!a._wrapperState.initialChecked,f!==""&&(a.name=f)}function Dt(a,u,f){(u!=="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,u,f,w){if(a=a.options,u){u={};for(var j=0;j<f.length;j++)u["$"+f[j]]=!0;for(f=0;f<a.length;f++)j=u.hasOwnProperty("$"+a[f].value),a[f].selected!==j&&(a[f].selected=j),j&&w&&(a[f].defaultSelected=!0)}else{for(f=""+ae(f),u=null,j=0;j<a.length;j++){if(a[j].value===f){a[j].selected=!0,w&&(a[j].defaultSelected=!0);return}u!==null||a[j].disabled||(u=a[j])}u!==null&&(u.selected=!0)}}function ce(a,u){if(u.dangerouslySetInnerHTML!=null)throw Error(n(91));return te({},u,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function Q(a,u){var f=u.value;if(f==null){if(f=u.children,u=u.defaultValue,f!=null){if(u!=null)throw Error(n(92));if($e(f)){if(1<f.length)throw Error(n(93));f=f[0]}u=f}u==null&&(u=""),f=u}a._wrapperState={initialValue:ae(f)}}function _e(a,u){var f=ae(u.value),w=ae(u.defaultValue);f!=null&&(f=""+f,f!==a.value&&(a.value=f),u.defaultValue==null&&a.defaultValue!==f&&(a.defaultValue=f)),w!=null&&(a.defaultValue=""+w)}function le(a){var u=a.textContent;u===a._wrapperState.initialValue&&u!==""&&u!==null&&(a.value=u)}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,u){return a==null||a==="http://www.w3.org/1999/xhtml"?Se(u):a==="http://www.w3.org/2000/svg"&&u==="foreignObject"?"http://www.w3.org/1999/xhtml":a}var dt,yt=(function(a){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(u,f,w,j){MSApp.execUnsafeLocalFunction(function(){return a(u,f,w,j)})}:a})(function(a,u){if(a.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in a)a.innerHTML=u;else{for(dt=dt||document.createElement("div"),dt.innerHTML="<svg>"+u.valueOf().toString()+"</svg>",u=dt.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;u.firstChild;)a.appendChild(u.firstChild)}});function _t(a,u){if(u){var f=a.firstChild;if(f&&f===a.lastChild&&f.nodeType===3){f.nodeValue=u;return}}a.textContent=u}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(u){u=u+a.charAt(0).toUpperCase()+a.substring(1),It[u]=It[a]})});function St(a,u,f){return u==null||typeof u=="boolean"||u===""?"":f||typeof u!="number"||u===0||It.hasOwnProperty(a)&&It[a]?(""+u).trim():u+"px"}function ut(a,u){a=a.style;for(var f in u)if(u.hasOwnProperty(f)){var w=f.indexOf("--")===0,j=St(f,u[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 Rt(a,u){if(u){if(Ot[a]&&(u.children!=null||u.dangerouslySetInnerHTML!=null))throw Error(n(137,a));if(u.dangerouslySetInnerHTML!=null){if(u.children!=null)throw Error(n(60));if(typeof u.dangerouslySetInnerHTML!="object"||!("__html"in u.dangerouslySetInnerHTML))throw Error(n(61))}if(u.style!=null&&typeof u.style!="object")throw Error(n(62))}}function mn(a,u){if(a.indexOf("-")===-1)return typeof u.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 wn=null;function On(a){return a=a.target||a.srcElement||window,a.correspondingUseElement&&(a=a.correspondingUseElement),a.nodeType===3?a.parentNode:a}var Ks=null,rs=null,ge=null;function Re(a){if(a=na(a)){if(typeof Ks!="function")throw Error(n(280));var u=a.stateNode;u&&(u=To(u),Ks(a.stateNode,a.type,u))}}function gt(a){rs?ge?ge.push(a):ge=[a]:rs=a}function re(){if(rs){var a=rs,u=ge;if(ge=rs=null,Re(a),u)for(a=0;a<u.length;a++)Re(u[a])}}function fe(a,u){return a(u)}function Ce(){}var Ie=!1;function We(a,u,f){if(Ie)return a(u,f);Ie=!0;try{return fe(a,u,f)}finally{Ie=!1,(rs!==null||ge!==null)&&(Ce(),re())}}function Ue(a,u){var f=a.stateNode;if(f===null)return null;var w=To(f);if(w===null)return null;f=w[u];e:switch(u){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,u,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,u,f,w,j,C,q,ie,ue){var Te=Array.prototype.slice.call(arguments,3);try{u.apply(f,Te)}catch(Ze){this.onError(Ze)}}var xt=!1,At=null,zt=!1,ot=null,Yt={onError:function(a){xt=!0,At=a}};function vn(a,u,f,w,j,C,q,ie,ue){xt=!1,At=null,vt.apply(Yt,arguments)}function hn(a,u,f,w,j,C,q,ie,ue){if(vn.apply(this,arguments),xt){if(xt){var Te=At;xt=!1,At=null}else throw Error(n(198));zt||(zt=!0,ot=Te)}}function sn(a){var u=a,f=a;if(a.alternate)for(;u.return;)u=u.return;else{a=u;do u=a,(u.flags&4098)!==0&&(f=u.return),a=u.return;while(a)}return u.tag===3?f:null}function Ht(a){if(a.tag===13){var u=a.memoizedState;if(u===null&&(a=a.alternate,a!==null&&(u=a.memoizedState)),u!==null)return u.dehydrated}return null}function is(a){if(sn(a)!==a)throw Error(n(188))}function Be(a){var u=a.alternate;if(!u){if(u=sn(a),u===null)throw Error(n(188));return u!==a?null:a}for(var f=a,w=u;;){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 is(j),a;if(C===w)return is(j),u;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:u}function Qt(a){return a=Be(a),a!==null?Mt(a):null}function Mt(a){if(a.tag===5||a.tag===6)return a;for(a=a.child;a!==null;){var u=Mt(a);if(u!==null)return u;a=a.sibling}return null}var Fn=t.unstable_scheduleCallback,fn=t.unstable_cancelCallback,Xe=t.unstable_shouldYield,nn=t.unstable_requestPaint,cn=t.unstable_now,Ar=t.unstable_getCurrentPriorityLevel,As=t.unstable_ImmediatePriority,ws=t.unstable_UserBlockingPriority,_r=t.unstable_NormalPriority,we=t.unstable_LowPriority,Nt=t.unstable_IdlePriority,zn=null,nr=null;function $i(a){if(nr&&typeof nr.onCommitFiberRoot=="function")try{nr.onCommitFiberRoot(zn,a,void 0,(a.current.flags&128)===128)}catch{}}var sr=Math.clz32?Math.clz32:ul,xo=Math.log,dc=Math.LN2;function ul(a){return a>>>=0,a===0?32:31-(xo(a)/dc|0)|0}var js=64,pr=4194304;function Rs(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 Bi(a,u){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=Rs(ie):(C&=q,C!==0&&(w=Rs(C)))}else q=f&~j,q!==0?w=Rs(q):C!==0&&(w=Rs(C));if(w===0)return 0;if(u!==0&&u!==w&&(u&j)===0&&(j=w&-w,C=u&-u,j>=C||j===16&&(C&4194240)!==0))return u;if((w&4)!==0&&(w|=f&16),u=a.entangledLanes,u!==0)for(a=a.entanglements,u&=w;0<u;)f=31-sr(u),j=1<<f,w|=a[f],u&=~j;return w}function dl(a,u){switch(a){case 1:case 2:case 4:return u+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 u+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 vs(a,u){for(var f=a.suspendedLanes,w=a.pingedLanes,j=a.expirationTimes,C=a.pendingLanes;0<C;){var q=31-sr(C),ie=1<<q,ue=j[q];ue===-1?((ie&f)===0||(ie&w)!==0)&&(j[q]=dl(ie,u)):ue<=u&&(a.expiredLanes|=ie),C&=~ie}}function si(a){return a=a.pendingLanes&-1073741825,a!==0?a:a&1073741824?1073741824:0}function Ls(){var a=js;return js<<=1,(js&4194240)===0&&(js=64),a}function ri(a){for(var u=[],f=0;31>f;f++)u.push(a);return u}function Ss(a,u,f){a.pendingLanes|=u,u!==536870912&&(a.suspendedLanes=0,a.pingedLanes=0),a=a.eventTimes,u=31-sr(u),a[u]=f}function ii(a,u){var f=a.pendingLanes&~u;a.pendingLanes=u,a.suspendedLanes=0,a.pingedLanes=0,a.expiredLanes&=u,a.mutableReadLanes&=u,a.entangledLanes&=u,u=a.entanglements;var w=a.eventTimes;for(a=a.expirationTimes;0<f;){var j=31-sr(f),C=1<<j;u[j]=0,w[j]=-1,a[j]=-1,f&=~C}}function Ui(a,u){var f=a.entangledLanes|=u;for(a=a.entanglements;f;){var w=31-sr(f),j=1<<w;j&u|a[w]&u&&(a[w]|=u),f&=~j}}var In=0;function $a(a){return a&=-a,1<a?4<a?(a&268435455)!==0?16:536870912:4:1}var fl,hl,Tr,fc,Wi,Ca=!1,bo=[],Fs=null,zs=null,gr=null,ko=new Map,Wr=new Map,Mr=[],qr="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 hc(a,u){switch(a){case"focusin":case"focusout":Fs=null;break;case"dragenter":case"dragleave":zs=null;break;case"mouseover":case"mouseout":gr=null;break;case"pointerover":case"pointerout":ko.delete(u.pointerId);break;case"gotpointercapture":case"lostpointercapture":Wr.delete(u.pointerId)}}function Vr(a,u,f,w,j,C){return a===null||a.nativeEvent!==C?(a={blockedOn:u,domEventName:f,eventSystemFlags:w,nativeEvent:C,targetContainers:[j]},u!==null&&(u=na(u),u!==null&&hl(u)),a):(a.eventSystemFlags|=w,u=a.targetContainers,j!==null&&u.indexOf(j)===-1&&u.push(j),a)}function ku(a,u,f,w,j){switch(u){case"focusin":return Fs=Vr(Fs,a,u,f,w,j),!0;case"dragenter":return zs=Vr(zs,a,u,f,w,j),!0;case"mouseover":return gr=Vr(gr,a,u,f,w,j),!0;case"pointerover":var C=j.pointerId;return ko.set(C,Vr(ko.get(C)||null,a,u,f,w,j)),!0;case"gotpointercapture":return C=j.pointerId,Wr.set(C,Vr(Wr.get(C)||null,a,u,f,w,j)),!0}return!1}function Ci(a){var u=Fa(a.target);if(u!==null){var f=sn(u);if(f!==null){if(u=f.tag,u===13){if(u=Ht(f),u!==null){a.blockedOn=u,Wi(a.priority,function(){Tr(f)});return}}else if(u===3&&f.stateNode.current.memoizedState.isDehydrated){a.blockedOn=f.tag===3?f.stateNode.containerInfo:null;return}}}a.blockedOn=null}function Xo(a){if(a.blockedOn!==null)return!1;for(var u=a.targetContainers;0<u.length;){var f=he(a.domEventName,a.eventSystemFlags,u[0],a.nativeEvent);if(f===null){f=a.nativeEvent;var w=new f.constructor(f.type,f);wn=w,f.target.dispatchEvent(w),wn=null}else return u=na(f),u!==null&&hl(u),a.blockedOn=f,!1;u.shift()}return!0}function ml(a,u,f){Xo(a)&&f.delete(u)}function jo(){Ca=!1,Fs!==null&&Xo(Fs)&&(Fs=null),zs!==null&&Xo(zs)&&(zs=null),gr!==null&&Xo(gr)&&(gr=null),ko.forEach(ml),Wr.forEach(ml)}function oi(a,u){a.blockedOn===u&&(a.blockedOn=null,Ca||(Ca=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,jo)))}function Ea(a){function u(j){return oi(j,a)}if(0<bo.length){oi(bo[0],a);for(var f=1;f<bo.length;f++){var w=bo[f];w.blockedOn===a&&(w.blockedOn=null)}}for(Fs!==null&&oi(Fs,a),zs!==null&&oi(zs,a),gr!==null&&oi(gr,a),ko.forEach(u),Wr.forEach(u),f=0;f<Mr.length;f++)w=Mr[f],w.blockedOn===a&&(w.blockedOn=null);for(;0<Mr.length&&(f=Mr[0],f.blockedOn===null);)Ci(f),f.blockedOn===null&&Mr.shift()}var qi=S.ReactCurrentBatchConfig,rr=!0;function cf(a,u,f,w){var j=In,C=qi.transition;qi.transition=null;try{In=1,Kn(a,u,f,w)}finally{In=j,qi.transition=C}}function ai(a,u,f,w){var j=In,C=qi.transition;qi.transition=null;try{In=4,Kn(a,u,f,w)}finally{In=j,qi.transition=C}}function Kn(a,u,f,w){if(rr){var j=he(a,u,f,w);if(j===null)jl(a,u,w,Y,f),hc(a,w);else if(ku(j,a,u,f,w))w.stopPropagation();else if(hc(a,w),u&4&&-1<qr.indexOf(a)){for(;j!==null;){var C=na(j);if(C!==null&&fl(C),C=he(a,u,f,w),C===null&&jl(a,u,w,Y,f),C===j)break;j=C}j!==null&&w.stopPropagation()}else jl(a,u,w,null,f)}}var Y=null;function he(a,u,f,w){if(Y=null,a=On(w),a=Fa(a),a!==null)if(u=sn(a),u===null)a=null;else if(f=u.tag,f===13){if(a=Ht(u),a!==null)return a;a=null}else if(f===3){if(u.stateNode.current.memoizedState.isDehydrated)return u.tag===3?u.stateNode.containerInfo:null;a=null}else u!==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(Ar()){case As:return 1;case ws:return 4;case _r: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,u=Ye,f=u.length,w,j="value"in De?De.value:De.textContent,C=j.length;for(a=0;a<f&&u[a]===j[a];a++);var q=f-a;for(w=1;w<=q&&u[f-w]===j[C-w];w++);return ht=j.slice(a,1<w?1-w:void 0)}function Pt(a){var u=a.keyCode;return"charCode"in a?(a=a.charCode,a===0&&u===13&&(a=13)):a=u,a===10&&(a=13),32<=a||a===13?a:0}function Bt(){return!0}function pn(){return!1}function En(a){function u(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(u.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}),u}var Js={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Ft=En(Js),bn=te({},Js,{view:0,detail:0}),as=En(bn),Hn,Rr,yr,Vi=te({},bn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:pl,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!==yr&&(yr&&a.type==="mousemove"?(Hn=a.screenX-yr.screenX,Rr=a.screenY-yr.screenY):Rr=Hn=0,yr=a),Hn)},movementY:function(a){return"movementY"in a?a.movementY:Rr}}),_l=En(Vi),Hi=te({},Vi,{dataTransfer:0}),uf=En(Hi),mc=te({},bn,{relatedTarget:0}),Aa=En(mc),Ta=te({},Js,{animationName:0,elapsedTime:0,pseudoElement:0}),df=En(Ta),_c=te({},Js,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),pc=En(_c),ju=te({},Js,{data:0}),ff=En(ju),Su={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},hf={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"},Nu={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function $u(a){var u=this.nativeEvent;return u.getModifierState?u.getModifierState(a):(a=Nu[a])?!!u[a]:!1}function pl(){return $u}var Om=te({},bn,{key:function(a){if(a.key){var u=Su[a.key]||a.key;if(u!=="Unidentified")return u}return a.type==="keypress"?(a=Pt(a),a===13?"Enter":String.fromCharCode(a)):a.type==="keydown"||a.type==="keyup"?hf[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:pl,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}}),Ma=En(Om),Pm=te({},Vi,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Cu=En(Pm),mf=te({},bn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:pl}),_f=En(mf),gl=te({},Js,{propertyName:0,elapsedTime:0,pseudoElement:0}),Dm=En(gl),Fm=te({},Vi,{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}),pf=En(Fm),Kg=[9,13,27,32],Eu=l&&"CompositionEvent"in window,yl=null;l&&"documentMode"in document&&(yl=document.documentMode);var Jg=l&&"TextEvent"in window&&!yl,Au=l&&(!Eu||yl&&8<yl&&11>=yl),An=" ",Tu=!1;function zm(a,u){switch(a){case"keyup":return Kg.indexOf(u.keyCode)!==-1;case"keydown":return u.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Mu(a){return a=a.detail,typeof a=="object"&&"data"in a?a.data:null}var wl=!1;function gf(a,u){switch(a){case"compositionend":return Mu(u);case"keypress":return u.which!==32?null:(Tu=!0,An);case"textInput":return a=u.data,a===An&&Tu?null:a;default:return null}}function Yg(a,u){if(wl)return a==="compositionend"||!Eu&&zm(a,u)?(a=Wt(),ht=Ye=De=null,wl=!1,a):null;switch(a){case"paste":return null;case"keypress":if(!(u.ctrlKey||u.altKey||u.metaKey)||u.ctrlKey&&u.altKey){if(u.char&&1<u.char.length)return u.char;if(u.which)return String.fromCharCode(u.which)}return null;case"compositionend":return Au&&u.locale!=="ko"?null:u.data;default:return null}}var Ns={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 So(a){var u=a&&a.nodeName&&a.nodeName.toLowerCase();return u==="input"?!!Ns[a.type]:u==="textarea"}function yf(a,u,f,w){gt(w),u=Ai(u,"onChange"),0<u.length&&(f=new Ft("onChange","change",null,f,w),a.push({event:f,listeners:u}))}var gc=null,Gi=null;function wf(a){vr(a,0)}function Zo(a){var u=$l(a);if(mt(u))return a}function Bm(a,u){if(a==="change")return u}var Um=!1;if(l){var vf;if(l){var xf="oninput"in document;if(!xf){var bf=document.createElement("div");bf.setAttribute("oninput","return;"),xf=typeof bf.oninput=="function"}vf=xf}else vf=!1;Um=vf&&(!document.documentMode||9<document.documentMode)}function Wm(){gc&&(gc.detachEvent("onpropertychange",kf),Gi=gc=null)}function kf(a){if(a.propertyName==="value"&&Zo(Gi)){var u=[];yf(u,Gi,a,On(a)),We(wf,u)}}function Xg(a,u,f){a==="focusin"?(Wm(),gc=u,Gi=f,gc.attachEvent("onpropertychange",kf)):a==="focusout"&&Wm()}function qm(a){if(a==="selectionchange"||a==="keyup"||a==="keydown")return Zo(Gi)}function Vm(a,u){if(a==="click")return Zo(u)}function jf(a,u){if(a==="input"||a==="change")return Zo(u)}function vl(a,u){return a===u&&(a!==0||1/a===1/u)||a!==a&&u!==u}var wr=typeof Object.is=="function"?Object.is:vl;function Ki(a,u){if(wr(a,u))return!0;if(typeof a!="object"||a===null||typeof u!="object"||u===null)return!1;var f=Object.keys(a),w=Object.keys(u);if(f.length!==w.length)return!1;for(w=0;w<f.length;w++){var j=f[w];if(!d.call(u,j)||!wr(a[j],u[j]))return!1}return!0}function xl(a){for(;a&&a.firstChild;)a=a.firstChild;return a}function yc(a,u){var f=xl(a);a=0;for(var w;f;){if(f.nodeType===3){if(w=a+f.textContent.length,a<=u&&w>=u)return{node:f,offset:u-a};a=w}e:{for(;f;){if(f.nextSibling){f=f.nextSibling;break e}f=f.parentNode}f=void 0}f=xl(f)}}function Ru(a,u){return a&&u?a===u?!0:a&&a.nodeType===3?!1:u&&u.nodeType===3?Ru(a,u.parentNode):"contains"in a?a.contains(u):a.compareDocumentPosition?!!(a.compareDocumentPosition(u)&16):!1:!1}function Sf(){for(var a=window,u=nt();u instanceof a.HTMLIFrameElement;){try{var f=typeof u.contentWindow.location.href=="string"}catch{f=!1}if(f)a=u.contentWindow;else break;u=nt(a.document)}return u}function Ra(a){var u=a&&a.nodeName&&a.nodeName.toLowerCase();return u&&(u==="input"&&(a.type==="text"||a.type==="search"||a.type==="tel"||a.type==="url"||a.type==="password")||u==="textarea"||a.contentEditable==="true")}function Hm(a){var u=Sf(),f=a.focusedElem,w=a.selectionRange;if(u!==f&&f&&f.ownerDocument&&Ru(f.ownerDocument.documentElement,f)){if(w!==null&&Ra(f)){if(u=w.start,a=w.end,a===void 0&&(a=u),"selectionStart"in f)f.selectionStart=u,f.selectionEnd=Math.min(a,f.value.length);else if(a=(u=f.ownerDocument||document)&&u.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=yc(f,C);var q=yc(f,w);j&&q&&(a.rangeCount!==1||a.anchorNode!==j.node||a.anchorOffset!==j.offset||a.focusNode!==q.node||a.focusOffset!==q.offset)&&(u=u.createRange(),u.setStart(j.node,j.offset),a.removeAllRanges(),C>w?(a.addRange(u),a.extend(q.node,q.offset)):(u.setEnd(q.node,q.offset),a.addRange(u)))}}for(u=[],a=f;a=a.parentNode;)a.nodeType===1&&u.push({element:a,left:a.scrollLeft,top:a.scrollTop});for(typeof f.focus=="function"&&f.focus(),f=0;f<u.length;f++)a=u[f],a.element.scrollLeft=a.left,a.element.scrollTop=a.top}}var wc=l&&"documentMode"in document&&11>=document.documentMode,Ji=null,Nf=null,La=null,$f=!1;function Lu(a,u,f){var w=f.window===f?f.document:f.nodeType===9?f:f.ownerDocument;$f||Ji==null||Ji!==nt(w)||(w=Ji,"selectionStart"in w&&Ra(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}),La&&Ki(La,w)||(La=w,w=Ai(Nf,"onSelect"),0<w.length&&(u=new Ft("onSelect","select",null,u,f),a.push({event:u,listeners:w}),u.target=Ji)))}function Ia(a,u){var f={};return f[a.toLowerCase()]=u.toLowerCase(),f["Webkit"+a]="webkit"+u,f["Moz"+a]="moz"+u,f}var Lr={animationend:Ia("Animation","AnimationEnd"),animationiteration:Ia("Animation","AnimationIteration"),animationstart:Ia("Animation","AnimationStart"),transitionend:Ia("Transition","TransitionEnd")},Qo={},Gm={};l&&(Gm=document.createElement("div").style,"AnimationEvent"in window||(delete Lr.animationend.animation,delete Lr.animationiteration.animation,delete Lr.animationstart.animation),"TransitionEvent"in window||delete Lr.transitionend.transition);function Oa(a){if(Qo[a])return Qo[a];if(!Lr[a])return a;var u=Lr[a],f;for(f in u)if(u.hasOwnProperty(f)&&f in Gm)return Qo[a]=u[f];return a}var Km=Oa("animationend"),Iu=Oa("animationiteration"),bl=Oa("animationstart"),Hr=Oa("transitionend"),No=new Map,vc="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 Gr(a,u){No.set(a,u),o(u,[a])}for(var xc=0;xc<vc.length;xc++){var Pa=vc[xc],$o=Pa.toLowerCase(),Ou=Pa[0].toUpperCase()+Pa.slice(1);Gr($o,"on"+Ou)}Gr(Km,"onAnimationEnd"),Gr(Iu,"onAnimationIteration"),Gr(bl,"onAnimationStart"),Gr("dblclick","onDoubleClick"),Gr("focusin","onFocus"),Gr("focusout","onBlur"),Gr(Hr,"onTransitionEnd"),c("onMouseEnter",["mouseout","mouseover"]),c("onMouseLeave",["mouseout","mouseover"]),c("onPointerEnter",["pointerout","pointerover"]),c("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 Co="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(" "),kl=new Set("cancel close invalid load scroll toggle".split(" ").concat(Co));function Eo(a,u,f){var w=a.type||"unknown-event";a.currentTarget=f,hn(w,u,void 0,a),a.currentTarget=null}function vr(a,u){u=(u&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(u)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;Eo(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;Eo(j,ie,Te),C=ue}}}if(zt)throw a=ot,zt=!1,ot=null,a}function Bn(a,u){var f=u[Sl];f===void 0&&(f=u[Sl]=new Set);var w=a+"__bubble";f.has(w)||(Pu(u,a,2,!1),f.add(w))}function ea(a,u,f){var w=0;u&&(w|=4),Pu(f,a,w,u)}var Da="_reactListening"+Math.random().toString(36).slice(2);function Ei(a){if(!a[Da]){a[Da]=!0,r.forEach(function(f){f!=="selectionchange"&&(kl.has(f)||ea(f,!1,a),ea(f,!0,a))});var u=a.nodeType===9?a:a.ownerDocument;u===null||u[Da]||(u[Da]=!0,ea("selectionchange",!1,u))}}function Pu(a,u,f,w){switch(Oe(u)){case 1:var j=cf;break;case 4:j=ai;break;default:j=Kn}f=j.bind(null,u,f,a),j=void 0,!et||u!=="touchstart"&&u!=="touchmove"&&u!=="wheel"||(j=!0),w?j!==void 0?a.addEventListener(u,f,{capture:!0,passive:j}):a.addEventListener(u,f,!0):j!==void 0?a.addEventListener(u,f,{passive:j}):a.addEventListener(u,f,!1)}function jl(a,u,f,w,j){var C=w;if((u&1)===0&&(u&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=Fa(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=On(f),tt=[];e:{var Je=No.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=Ma;break;case"focusin":$t="focus",kt=Aa;break;case"focusout":$t="blur",kt=Aa;break;case"beforeblur":case"afterblur":kt=Aa;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=_l;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":kt=uf;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":kt=_f;break;case Km:case Iu:case bl:kt=df;break;case Hr:kt=Dm;break;case"scroll":kt=as;break;case"wheel":kt=pf;break;case"copy":case"cut":case"paste":kt=pc;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":kt=Cu}var Tt=(u&4)!==0,Os=!Tt&&a==="scroll",ve=Tt?Je!==null?Je+"Capture":null:Je;Tt=[];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&&Tt.push(Ir(me,it,Ne)))),Os)break;me=me.return}0<Tt.length&&(Je=new kt(Je,$t,null,f,Ze),tt.push({event:Je,listeners:Tt}))}}if((u&7)===0){e:{if(Je=a==="mouseover"||a==="pointerover",kt=a==="mouseout"||a==="pointerout",Je&&f!==wn&&($t=f.relatedTarget||f.fromElement)&&(Fa($t)||$t[Ti]))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?Fa($t):null,$t!==null&&(Os=sn($t),$t!==Os||$t.tag!==5&&$t.tag!==6)&&($t=null)):(kt=null,$t=Te),kt!==$t)){if(Tt=_l,it="onMouseLeave",ve="onMouseEnter",me="mouse",(a==="pointerout"||a==="pointerover")&&(Tt=Cu,it="onPointerLeave",ve="onPointerEnter",me="pointer"),Os=kt==null?Je:$l(kt),Ne=$t==null?Je:$l($t),Je=new Tt(it,me+"leave",kt,f,Ze),Je.target=Os,Je.relatedTarget=Ne,it=null,Fa(Ze)===Te&&(Tt=new Tt(ve,me+"enter",$t,f,Ze),Tt.target=Ne,Tt.relatedTarget=Os,it=Tt),Os=it,kt&&$t)t:{for(Tt=kt,ve=$t,me=0,Ne=Tt;Ne;Ne=xr(Ne))me++;for(Ne=0,it=ve;it;it=xr(it))Ne++;for(;0<me-Ne;)Tt=xr(Tt),me--;for(;0<Ne-me;)ve=xr(ve),Ne--;for(;me--;){if(Tt===ve||ve!==null&&Tt===ve.alternate)break t;Tt=xr(Tt),ve=xr(ve)}Tt=null}else Tt=null;kt!==null&&Cf(tt,Je,kt,Tt,!1),$t!==null&&Os!==null&&Cf(tt,Os,$t,Tt,!0)}}e:{if(Je=Te?$l(Te):window,kt=Je.nodeName&&Je.nodeName.toLowerCase(),kt==="select"||kt==="input"&&Je.type==="file")var Lt=Bm;else if(So(Je))if(Um)Lt=jf;else{Lt=qm;var Gt=Xg}else(kt=Je.nodeName)&&kt.toLowerCase()==="input"&&(Je.type==="checkbox"||Je.type==="radio")&&(Lt=Vm);if(Lt&&(Lt=Lt(a,Te))){yf(tt,Lt,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?$l(Te):window,a){case"focusin":(So(Gt)||Gt.contentEditable==="true")&&(Ji=Gt,Nf=Te,La=null);break;case"focusout":La=Nf=Ji=null;break;case"mousedown":$f=!0;break;case"contextmenu":case"mouseup":case"dragend":$f=!1,Lu(tt,f,Ze);break;case"selectionchange":if(wc)break;case"keydown":case"keyup":Lu(tt,f,Ze)}var Kt;if(Eu)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 wl?zm(a,f)&&(dn="onCompositionEnd"):a==="keydown"&&f.keyCode===229&&(dn="onCompositionStart");dn&&(Au&&f.locale!=="ko"&&(wl||dn!=="onCompositionStart"?dn==="onCompositionEnd"&&wl&&(Kt=Wt()):(De=Ze,Ye="value"in De?De.value:De.textContent,wl=!0)),Gt=Ai(Te,dn),0<Gt.length&&(dn=new ff(dn,a,null,f,Ze),tt.push({event:dn,listeners:Gt}),Kt?dn.data=Kt:(Kt=Mu(f),Kt!==null&&(dn.data=Kt)))),(Kt=Jg?gf(a,f):Yg(a,f))&&(Te=Ai(Te,"onBeforeInput"),0<Te.length&&(Ze=new ff("onBeforeInput","beforeinput",null,f,Ze),tt.push({event:Ze,listeners:Te}),Ze.data=Kt))}vr(tt,u)})}function Ir(a,u,f){return{instance:a,listener:u,currentTarget:f}}function Ai(a,u){for(var f=u+"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(Ir(a,C,j)),C=Ue(a,u),C!=null&&w.push(Ir(a,C,j))),a=a.return}return w}function xr(a){if(a===null)return null;do a=a.return;while(a&&a.tag!==5);return a||null}function Cf(a,u,f,w,j){for(var C=u._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(Ir(f,ue,ie))):j||(ue=Ue(f,C),ue!=null&&q.push(Ir(f,ue,ie)))),f=f.return}q.length!==0&&a.push({event:u,listeners:q})}var bc=/\r\n?/g,Jm=/\u0000|\uFFFD/g;function Du(a){return(typeof a=="string"?a:""+a).replace(bc,`
38
+ `).replace(Jm,"")}function kc(a,u,f){if(u=Du(u),Du(a)!==u&&f)throw Error(n(425))}function jc(){}var Fu=null,Ef=null;function zu(a,u){return a==="textarea"||a==="noscript"||typeof u.children=="string"||typeof u.children=="number"||typeof u.dangerouslySetInnerHTML=="object"&&u.dangerouslySetInnerHTML!==null&&u.dangerouslySetInnerHTML.__html!=null}var Af=typeof setTimeout=="function"?setTimeout:void 0,Ym=typeof clearTimeout=="function"?clearTimeout:void 0,Xm=typeof Promise=="function"?Promise:void 0,Zm=typeof queueMicrotask=="function"?queueMicrotask:typeof Xm<"u"?function(a){return Xm.resolve(null).then(a).catch(Zg)}:Af;function Zg(a){setTimeout(function(){throw a})}function Bu(a,u){var f=u,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),Ea(u);return}w--}else f!=="$"&&f!=="$?"&&f!=="$!"||w++;f=j}while(f);Ea(u)}function ta(a){for(;a!=null;a=a.nextSibling){var u=a.nodeType;if(u===1||u===3)break;if(u===8){if(u=a.data,u==="$"||u==="$!"||u==="$?")break;if(u==="/$")return null}}return a}function Tf(a){a=a.previousSibling;for(var u=0;a;){if(a.nodeType===8){var f=a.data;if(f==="$"||f==="$!"||f==="$?"){if(u===0)return a;u--}else f==="/$"&&u++}a=a.previousSibling}return null}var Yi=Math.random().toString(36).slice(2),Xi="__reactFiber$"+Yi,Ao="__reactProps$"+Yi,Ti="__reactContainer$"+Yi,Sl="__reactEvents$"+Yi,Qm="__reactListeners$"+Yi,Nl="__reactHandles$"+Yi;function Fa(a){var u=a[Xi];if(u)return u;for(var f=a.parentNode;f;){if(u=f[Ti]||f[Xi]){if(f=u.alternate,u.child!==null||f!==null&&f.child!==null)for(a=Tf(a);a!==null;){if(f=a[Xi])return f;a=Tf(a)}return u}a=f,f=a.parentNode}return null}function na(a){return a=a[Xi]||a[Ti],!a||a.tag!==5&&a.tag!==6&&a.tag!==13&&a.tag!==3?null:a}function $l(a){if(a.tag===5||a.tag===6)return a.stateNode;throw Error(n(33))}function To(a){return a[Ao]||null}var Mf=[],Mo=-1;function sa(a){return{current:a}}function Pn(a){0>Mo||(a.current=Mf[Mo],Mf[Mo]=null,Mo--)}function Xn(a,u){Mo++,Mf[Mo]=a.current,a.current=u}var li={},Ts=sa(li),br=sa(!1),Ro=li;function Zi(a,u){var f=a.type.contextTypes;if(!f)return li;var w=a.stateNode;if(w&&w.__reactInternalMemoizedUnmaskedChildContext===u)return w.__reactInternalMemoizedMaskedChildContext;var j={},C;for(C in f)j[C]=u[C];return w&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=u,a.__reactInternalMemoizedMaskedChildContext=j),j}function ir(a){return a=a.childContextTypes,a!=null}function Lo(){Pn(br),Pn(Ts)}function Uu(a,u,f){if(Ts.current!==li)throw Error(n(168));Xn(Ts,u),Xn(br,f)}function e_(a,u,f){var w=a.stateNode;if(u=u.childContextTypes,typeof w.getChildContext!="function")return f;w=w.getChildContext();for(var j in w)if(!(j in u))throw Error(n(108,je(a)||"Unknown",j));return te({},f,w)}function Cl(a){return a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||li,Ro=Ts.current,Xn(Ts,a),Xn(br,br.current),!0}function Wu(a,u,f){var w=a.stateNode;if(!w)throw Error(n(169));f?(a=e_(a,u,Ro),w.__reactInternalMemoizedMergedChildContext=a,Pn(br),Pn(Ts),Xn(Ts,a)):Pn(br),Xn(br,f)}var Io=null,qu=!1,ra=!1;function or(a){Io===null?Io=[a]:Io.push(a)}function Vu(a){qu=!0,or(a)}function Qi(){if(!ra&&Io!==null){ra=!0;var a=0,u=In;try{var f=Io;for(In=1;a<f.length;a++){var w=f[a];do w=w(!0);while(w!==null)}Io=null,qu=!1}catch(j){throw Io!==null&&(Io=Io.slice(a+1)),Fn(As,Qi),j}finally{In=u,ra=!1}}return null}var El=[],Al=0,Tl=null,Hu=0,kr=[],Kr=0,eo=null,to=1,no="";function za(a,u){El[Al++]=Hu,El[Al++]=Tl,Tl=a,Hu=u}function Rf(a,u,f){kr[Kr++]=to,kr[Kr++]=no,kr[Kr++]=eo,eo=a;var w=to;a=no;var j=32-sr(w)-1;w&=~(1<<j),f+=1;var C=32-sr(u)+j;if(30<C){var q=j-j%5;C=(w&(1<<q)-1).toString(32),w>>=q,j-=q,to=1<<32-sr(u)+j|f<<j|w,no=C+a}else to=1<<C|f<<j|w,no=a}function Gu(a){a.return!==null&&(za(a,1),Rf(a,1,0))}function Ku(a){for(;a===Tl;)Tl=El[--Al],El[Al]=null,Hu=El[--Al],El[Al]=null;for(;a===eo;)eo=kr[--Kr],kr[Kr]=null,no=kr[--Kr],kr[Kr]=null,to=kr[--Kr],kr[Kr]=null}var Jr=null,Or=null,Zn=!1,Mi=null;function t_(a,u){var f=Pe(5,null,null,0);f.elementType="DELETED",f.stateNode=u,f.return=a,u=a.deletions,u===null?(a.deletions=[f],a.flags|=16):u.push(f)}function n_(a,u){switch(a.tag){case 5:var f=a.type;return u=u.nodeType!==1||f.toLowerCase()!==u.nodeName.toLowerCase()?null:u,u!==null?(a.stateNode=u,Jr=a,Or=ta(u.firstChild),!0):!1;case 6:return u=a.pendingProps===""||u.nodeType!==3?null:u,u!==null?(a.stateNode=u,Jr=a,Or=null,!0):!1;case 13:return u=u.nodeType!==8?null:u,u!==null?(f=eo!==null?{id:to,overflow:no}:null,a.memoizedState={dehydrated:u,treeContext:f,retryLane:1073741824},f=Pe(18,null,null,0),f.stateNode=u,f.return=a,a.child=f,Jr=a,Or=null,!0):!1;default:return!1}}function Lf(a){return(a.mode&1)!==0&&(a.flags&128)===0}function Sc(a){if(Zn){var u=Or;if(u){var f=u;if(!n_(a,u)){if(Lf(a))throw Error(n(418));u=ta(f.nextSibling);var w=Jr;u&&n_(a,u)?t_(w,f):(a.flags=a.flags&-4097|2,Zn=!1,Jr=a)}}else{if(Lf(a))throw Error(n(418));a.flags=a.flags&-4097|2,Zn=!1,Jr=a}}}function s_(a){for(a=a.return;a!==null&&a.tag!==5&&a.tag!==3&&a.tag!==13;)a=a.return;Jr=a}function Ml(a){if(a!==Jr)return!1;if(!Zn)return s_(a),Zn=!0,!1;var u;if((u=a.tag!==3)&&!(u=a.tag!==5)&&(u=a.type,u=u!=="head"&&u!=="body"&&!zu(a.type,a.memoizedProps)),u&&(u=Or)){if(Lf(a))throw r_(),Error(n(418));for(;u;)t_(a,u),u=ta(u.nextSibling)}if(s_(a),a.tag===13){if(a=a.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(n(317));e:{for(a=a.nextSibling,u=0;a;){if(a.nodeType===8){var f=a.data;if(f==="/$"){if(u===0){Or=ta(a.nextSibling);break e}u--}else f!=="$"&&f!=="$!"&&f!=="$?"||u++}a=a.nextSibling}Or=null}}else Or=Jr?ta(a.stateNode.nextSibling):null;return!0}function r_(){for(var a=Or;a;)a=ta(a.nextSibling)}function Ba(){Or=Jr=null,Zn=!1}function If(a){Mi===null?Mi=[a]:Mi.push(a)}var Of=S.ReactCurrentBatchConfig;function Ke(a,u,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 u!==null&&u.ref!==null&&typeof u.ref=="function"&&u.ref._stringRef===C?u.ref:(u=function(q){var ie=j.refs;q===null?delete ie[C]:ie[C]=q},u._stringRef=C,u)}if(typeof a!="string")throw Error(n(284));if(!f._owner)throw Error(n(290,a))}return a}function Un(a,u){throw a=Object.prototype.toString.call(u),Error(n(31,a==="[object Object]"?"object with keys {"+Object.keys(u).join(", ")+"}":a))}function ci(a){var u=a._init;return u(a._payload)}function Pf(a){function u(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;)u(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=en(Ne,ve.mode,it),me.return=ve,me):(me=j(me,Ne),me.return=ve,me)}function ue(ve,me,Ne,it){var Lt=Ne.type;return Lt===R?Ze(ve,me,Ne.props.children,it,Ne.key):me!==null&&(me.elementType===Lt||typeof Lt=="object"&&Lt!==null&&Lt.$$typeof===L&&ci(Lt)===me.type)?(it=j(me,Ne.props),it.ref=Ke(ve,me,Ne),it.return=ve,it):(it=xn(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=Yn(Ne,ve.mode,it),me.return=ve,me):(me=j(me,Ne.children||[]),me.return=ve,me)}function Ze(ve,me,Ne,it,Lt){return me===null||me.tag!==7?(me=qt(Ne,ve.mode,it,Lt),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=en(""+me,ve.mode,Ne),me.return=ve,me;if(typeof me=="object"&&me!==null){switch(me.$$typeof){case P:return Ne=xn(me.type,me.key,me.props,null,ve.mode,Ne),Ne.ref=Ke(ve,null,me),Ne.return=ve,Ne;case D:return me=Yn(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;Un(ve,me)}return null}function Je(ve,me,Ne,it){var Lt=me!==null?me.key:null;if(typeof Ne=="string"&&Ne!==""||typeof Ne=="number")return Lt!==null?null:ie(ve,me,""+Ne,it);if(typeof Ne=="object"&&Ne!==null){switch(Ne.$$typeof){case P:return Ne.key===Lt?ue(ve,me,Ne,it):null;case D:return Ne.key===Lt?Te(ve,me,Ne,it):null;case L:return Lt=Ne._init,Je(ve,me,Lt(Ne._payload),it)}if($e(Ne)||U(Ne))return Lt!==null?null:Ze(ve,me,Ne,it,null);Un(ve,Ne)}return null}function kt(ve,me,Ne,it,Lt){if(typeof it=="string"&&it!==""||typeof it=="number")return ve=ve.get(Ne)||null,ie(me,ve,""+it,Lt);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,Lt);case D:return ve=ve.get(it.key===null?Ne:it.key)||null,Te(me,ve,it,Lt);case L:var Gt=it._init;return kt(ve,me,Ne,Gt(it._payload),Lt)}if($e(it)||U(it))return ve=ve.get(Ne)||null,Ze(me,ve,it,Lt,null);Un(me,it)}return null}function $t(ve,me,Ne,it){for(var Lt=null,Gt=null,Kt=me,dn=me=0,fr=null;Kt!==null&&dn<Ne.length;dn++){Kt.index>dn?(fr=Kt,Kt=null):fr=Kt.sibling;var Wn=Je(ve,Kt,Ne[dn],it);if(Wn===null){Kt===null&&(Kt=fr);break}a&&Kt&&Wn.alternate===null&&u(ve,Kt),me=C(Wn,me,dn),Gt===null?Lt=Wn:Gt.sibling=Wn,Gt=Wn,Kt=fr}if(dn===Ne.length)return f(ve,Kt),Zn&&za(ve,dn),Lt;if(Kt===null){for(;dn<Ne.length;dn++)Kt=tt(ve,Ne[dn],it),Kt!==null&&(me=C(Kt,me,dn),Gt===null?Lt=Kt:Gt.sibling=Kt,Gt=Kt);return Zn&&za(ve,dn),Lt}for(Kt=w(ve,Kt);dn<Ne.length;dn++)fr=kt(Kt,ve,dn,Ne[dn],it),fr!==null&&(a&&fr.alternate!==null&&Kt.delete(fr.key===null?dn:fr.key),me=C(fr,me,dn),Gt===null?Lt=fr:Gt.sibling=fr,Gt=fr);return a&&Kt.forEach(function(Hl){return u(ve,Hl)}),Zn&&za(ve,dn),Lt}function Tt(ve,me,Ne,it){var Lt=U(Ne);if(typeof Lt!="function")throw Error(n(150));if(Ne=Lt.call(Ne),Ne==null)throw Error(n(151));for(var Gt=Lt=null,Kt=me,dn=me=0,fr=null,Wn=Ne.next();Kt!==null&&!Wn.done;dn++,Wn=Ne.next()){Kt.index>dn?(fr=Kt,Kt=null):fr=Kt.sibling;var Hl=Je(ve,Kt,Wn.value,it);if(Hl===null){Kt===null&&(Kt=fr);break}a&&Kt&&Hl.alternate===null&&u(ve,Kt),me=C(Hl,me,dn),Gt===null?Lt=Hl:Gt.sibling=Hl,Gt=Hl,Kt=fr}if(Wn.done)return f(ve,Kt),Zn&&za(ve,dn),Lt;if(Kt===null){for(;!Wn.done;dn++,Wn=Ne.next())Wn=tt(ve,Wn.value,it),Wn!==null&&(me=C(Wn,me,dn),Gt===null?Lt=Wn:Gt.sibling=Wn,Gt=Wn);return Zn&&za(ve,dn),Lt}for(Kt=w(ve,Kt);!Wn.done;dn++,Wn=Ne.next())Wn=kt(Kt,ve,dn,Wn.value,it),Wn!==null&&(a&&Wn.alternate!==null&&Kt.delete(Wn.key===null?dn:Wn.key),me=C(Wn,me,dn),Gt===null?Lt=Wn:Gt.sibling=Wn,Gt=Wn);return a&&Kt.forEach(function(sE){return u(ve,sE)}),Zn&&za(ve,dn),Lt}function Os(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 Lt=Ne.key,Gt=me;Gt!==null;){if(Gt.key===Lt){if(Lt=Ne.type,Lt===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===Lt||typeof Lt=="object"&&Lt!==null&&Lt.$$typeof===L&&ci(Lt)===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 u(ve,Gt);Gt=Gt.sibling}Ne.type===R?(me=qt(Ne.props.children,ve.mode,it,Ne.key),me.return=ve,ve=me):(it=xn(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 u(ve,me);me=me.sibling}me=Yn(Ne,ve.mode,it),me.return=ve,ve=me}return q(ve);case L:return Gt=Ne._init,Os(ve,me,Gt(Ne._payload),it)}if($e(Ne))return $t(ve,me,Ne,it);if(U(Ne))return Tt(ve,me,Ne,it);Un(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=en(Ne,ve.mode,it),me.return=ve,ve=me),q(ve)):f(ve,me)}return Os}var Oo=Pf(!0),Df=Pf(!1),Po=sa(null),Rl=null,Ll=null,Ff=null;function zf(){Ff=Ll=Rl=null}function Bf(a){var u=Po.current;Pn(Po),a._currentValue=u}function Ju(a,u,f){for(;a!==null;){var w=a.alternate;if((a.childLanes&u)!==u?(a.childLanes|=u,w!==null&&(w.childLanes|=u)):w!==null&&(w.childLanes&u)!==u&&(w.childLanes|=u),a===f)break;a=a.return}}function Ua(a,u){Rl=a,Ff=Ll=null,a=a.dependencies,a!==null&&a.firstContext!==null&&((a.lanes&u)!==0&&(Cs=!0),a.firstContext=null)}function ui(a){var u=a._currentValue;if(Ff!==a)if(a={context:a,memoizedValue:u,next:null},Ll===null){if(Rl===null)throw Error(n(308));Ll=a,Rl.dependencies={lanes:0,firstContext:a}}else Ll=Ll.next=a;return u}var so=null;function Yu(a){so===null?so=[a]:so.push(a)}function ar(a,u,f,w){var j=u.interleaved;return j===null?(f.next=f,Yu(u)):(f.next=j.next,j.next=f),u.interleaved=f,un(a,w)}function un(a,u){a.lanes|=u;var f=a.alternate;for(f!==null&&(f.lanes|=u),f=a,a=a.return;a!==null;)a.childLanes|=u,f=a.alternate,f!==null&&(f.childLanes|=u),f=a,a=a.return;return f.tag===3?f.stateNode:null}var _s=!1;function Nc(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Uf(a,u){a=a.updateQueue,u.updateQueue===a&&(u.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function Yr(a,u){return{eventTime:a,lane:u,tag:0,payload:null,callback:null,next:null}}function Xr(a,u,f){var w=a.updateQueue;if(w===null)return null;if(w=w.shared,(Tn&2)!==0){var j=w.pending;return j===null?u.next=u:(u.next=j.next,j.next=u),w.pending=u,un(a,f)}return j=w.interleaved,j===null?(u.next=u,Yu(w)):(u.next=j.next,j.next=u),w.interleaved=u,un(a,f)}function rn(a,u,f){if(u=u.updateQueue,u!==null&&(u=u.shared,(f&4194240)!==0)){var w=u.lanes;w&=a.pendingLanes,f|=w,u.lanes=f,Ui(a,f)}}function i_(a,u){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=u:C=C.next=u}else j=C=u;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=u:a.next=u,f.lastBaseUpdate=u}function Il(a,u,f,w){var j=a.updateQueue;_s=!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,Tt=ie;switch(Je=u,kt=f,Tt.tag){case 1:if($t=Tt.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=Tt.payload,Je=typeof $t=="function"?$t.call(kt,tt,Je):$t,Je==null)break e;tt=te({},tt,Je);break e;case 2:_s=!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,u=j.shared.interleaved,u!==null){j=u;do q|=j.lane,j=j.next;while(j!==u)}else C===null&&(j.shared.lanes=0);ca|=q,a.lanes=q,a.memoizedState=tt}}function o_(a,u,f){if(a=u.effects,u.effects=null,a!==null)for(u=0;u<a.length;u++){var w=a[u],j=w.callback;if(j!==null){if(w.callback=null,w=f,typeof j!="function")throw Error(n(191,j));j.call(w)}}}var $c={},ro=sa($c),Cc=sa($c),Wa=sa($c);function jr(a){if(a===$c)throw Error(n(174));return a}function Xu(a,u){switch(Xn(Wa,u),Xn(Cc,a),Xn(ro,$c),a=u.nodeType,a){case 9:case 11:u=(u=u.documentElement)?u.namespaceURI:pe(null,"");break;default:a=a===8?u.parentNode:u,u=a.namespaceURI||null,a=a.tagName,u=pe(u,a)}Pn(ro),Xn(ro,u)}function di(){Pn(ro),Pn(Cc),Pn(Wa)}function fi(a){jr(Wa.current);var u=jr(ro.current),f=pe(u,a.type);u!==f&&(Xn(Cc,a),Xn(ro,f))}function Ol(a){Cc.current===a&&(Pn(ro),Pn(Cc))}var ps=sa(0);function Zu(a){for(var u=a;u!==null;){if(u.tag===13){var f=u.memoizedState;if(f!==null&&(f=f.dehydrated,f===null||f.data==="$?"||f.data==="$!"))return u}else if(u.tag===19&&u.memoizedProps.revealOrder!==void 0){if((u.flags&128)!==0)return u}else if(u.child!==null){u.child.return=u,u=u.child;continue}if(u===a)break;for(;u.sibling===null;){if(u.return===null||u.return===a)return null;u=u.return}u.sibling.return=u.return,u=u.sibling}return null}var Ec=[];function Qu(){for(var a=0;a<Ec.length;a++)Ec[a]._workInProgressVersionPrimary=null;Ec.length=0}var Pl=S.ReactCurrentDispatcher,Wf=S.ReactCurrentBatchConfig,Qn=0,ls=null,$s=null,Dn=null,Ac=!1,Do=!1,qa=0,io=0;function Bs(){throw Error(n(321))}function qf(a,u){if(u===null)return!1;for(var f=0;f<u.length&&f<a.length;f++)if(!wr(a[f],u[f]))return!1;return!0}function Vf(a,u,f,w,j,C){if(Qn=C,ls=u,u.memoizedState=null,u.updateQueue=null,u.lanes=0,Pl.current=a===null||a.memoizedState===null?Ic:ty,a=f(w,j),Do){C=0;do{if(Do=!1,qa=0,25<=C)throw Error(n(301));C+=1,Dn=$s=null,u.updateQueue=null,Pl.current=Zf,a=f(w,j)}while(Do)}if(Pl.current=Fl,u=$s!==null&&$s.next!==null,Qn=0,Dn=$s=ls=null,Ac=!1,u)throw Error(n(300));return a}function Hf(){var a=qa!==0;return qa=0,a}function hi(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Dn===null?ls.memoizedState=Dn=a:Dn=Dn.next=a,Dn}function Pr(){if($s===null){var a=ls.alternate;a=a!==null?a.memoizedState:null}else a=$s.next;var u=Dn===null?ls.memoizedState:Dn.next;if(u!==null)Dn=u,$s=a;else{if(a===null)throw Error(n(310));$s=a,a={memoizedState:$s.memoizedState,baseState:$s.baseState,baseQueue:$s.baseQueue,queue:$s.queue,next:null},Dn===null?ls.memoizedState=Dn=a:Dn=Dn.next=a}return Dn}function Tc(a,u){return typeof u=="function"?u(a):u}function Mc(a){var u=Pr(),f=u.queue;if(f===null)throw Error(n(311));f.lastRenderedReducer=a;var w=$s,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((Qn&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,ls.lanes|=Ze,ca|=Ze}Te=Te.next}while(Te!==null&&Te!==C);ue===null?q=w:ue.next=ie,wr(w,u.memoizedState)||(Cs=!0),u.memoizedState=w,u.baseState=q,u.baseQueue=ue,f.lastRenderedState=w}if(a=f.interleaved,a!==null){j=a;do C=j.lane,ls.lanes|=C,ca|=C,j=j.next;while(j!==a)}else j===null&&(f.lanes=0);return[u.memoizedState,f.dispatch]}function Gf(a){var u=Pr(),f=u.queue;if(f===null)throw Error(n(311));f.lastRenderedReducer=a;var w=f.dispatch,j=f.pending,C=u.memoizedState;if(j!==null){f.pending=null;var q=j=j.next;do C=a(C,q.action),q=q.next;while(q!==j);wr(C,u.memoizedState)||(Cs=!0),u.memoizedState=C,u.baseQueue===null&&(u.baseState=C),f.lastRenderedState=C}return[C,w]}function ia(){}function a_(a,u){var f=ls,w=Pr(),j=u(),C=!wr(w.memoizedState,j);if(C&&(w.memoizedState=j,Cs=!0),w=w.queue,kn(Kf.bind(null,f,w,a),[a]),w.getSnapshot!==u||C||Dn!==null&&Dn.memoizedState.tag&1){if(f.flags|=2048,Dl(9,l_.bind(null,f,w,j,u),void 0,null),Is===null)throw Error(n(349));(Qn&30)!==0||Rc(f,u,j)}return j}function Rc(a,u,f){a.flags|=16384,a={getSnapshot:u,value:f},u=ls.updateQueue,u===null?(u={lastEffect:null,stores:null},ls.updateQueue=u,u.stores=[a]):(f=u.stores,f===null?u.stores=[a]:f.push(a))}function l_(a,u,f,w){u.value=f,u.getSnapshot=w,oo(u)&&c_(a)}function Kf(a,u,f){return f(function(){oo(u)&&c_(a)})}function oo(a){var u=a.getSnapshot;a=a.value;try{var f=u();return!wr(a,f)}catch{return!0}}function c_(a){var u=un(a,1);u!==null&&gi(u,a,1,-1)}function u_(a){var u=hi();return typeof a=="function"&&(a=a()),u.memoizedState=u.baseState=a,a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Tc,lastRenderedState:a},u.queue=a,a=a.dispatch=ey.bind(null,ls,a),[u.memoizedState,a]}function Dl(a,u,f,w){return a={tag:a,create:u,destroy:f,deps:w,next:null},u=ls.updateQueue,u===null?(u={lastEffect:null,stores:null},ls.updateQueue=u,u.lastEffect=a.next=a):(f=u.lastEffect,f===null?u.lastEffect=a.next=a:(w=f.next,f.next=a,a.next=w,u.lastEffect=a)),a}function d_(){return Pr().memoizedState}function ed(a,u,f,w){var j=hi();ls.flags|=a,j.memoizedState=Dl(1|u,f,void 0,w===void 0?null:w)}function td(a,u,f,w){var j=Pr();w=w===void 0?null:w;var C=void 0;if($s!==null){var q=$s.memoizedState;if(C=q.destroy,w!==null&&qf(w,q.deps)){j.memoizedState=Dl(u,f,C,w);return}}ls.flags|=a,j.memoizedState=Dl(1|u,f,C,w)}function f_(a,u){return ed(8390656,8,a,u)}function kn(a,u){return td(2048,8,a,u)}function Us(a,u){return td(4,2,a,u)}function lr(a,u){return td(4,4,a,u)}function nd(a,u){if(typeof u=="function")return a=a(),u(a),function(){u(null)};if(u!=null)return a=a(),u.current=a,function(){u.current=null}}function Lc(a,u,f){return f=f!=null?f.concat([a]):null,td(4,4,nd.bind(null,u,a),f)}function sd(){}function h_(a,u){var f=Pr();u=u===void 0?null:u;var w=f.memoizedState;return w!==null&&u!==null&&qf(u,w[1])?w[0]:(f.memoizedState=[a,u],a)}function m_(a,u){var f=Pr();u=u===void 0?null:u;var w=f.memoizedState;return w!==null&&u!==null&&qf(u,w[1])?w[0]:(a=a(),f.memoizedState=[a,u],a)}function Jf(a,u,f){return(Qn&21)===0?(a.baseState&&(a.baseState=!1,Cs=!0),a.memoizedState=f):(wr(f,u)||(f=Ls(),ls.lanes|=f,ca|=f,a.baseState=!0),u)}function rd(a,u){var f=In;In=f!==0&&4>f?f:4,a(!0);var w=Wf.transition;Wf.transition={};try{a(!1),u()}finally{In=f,Wf.transition=w}}function __(){return Pr().memoizedState}function Qg(a,u,f){var w=Uo(a);if(f={lane:w,action:f,hasEagerState:!1,eagerState:null,next:null},Yf(a))Xf(u,f);else if(f=ar(a,u,f,w),f!==null){var j=$r();gi(f,a,w,j),Ri(f,u,w)}}function ey(a,u,f){var w=Uo(a),j={lane:w,action:f,hasEagerState:!1,eagerState:null,next:null};if(Yf(a))Xf(u,j);else{var C=a.alternate;if(a.lanes===0&&(C===null||C.lanes===0)&&(C=u.lastRenderedReducer,C!==null))try{var q=u.lastRenderedState,ie=C(q,f);if(j.hasEagerState=!0,j.eagerState=ie,wr(ie,q)){var ue=u.interleaved;ue===null?(j.next=j,Yu(u)):(j.next=ue.next,ue.next=j),u.interleaved=j;return}}catch{}finally{}f=ar(a,u,j,w),f!==null&&(j=$r(),gi(f,a,w,j),Ri(f,u,w))}}function Yf(a){var u=a.alternate;return a===ls||u!==null&&u===ls}function Xf(a,u){Do=Ac=!0;var f=a.pending;f===null?u.next=u:(u.next=f.next,f.next=u),a.pending=u}function Ri(a,u,f){if((f&4194240)!==0){var w=u.lanes;w&=a.pendingLanes,f|=w,u.lanes=f,Ui(a,f)}}var Fl={readContext:ui,useCallback:Bs,useContext:Bs,useEffect:Bs,useImperativeHandle:Bs,useInsertionEffect:Bs,useLayoutEffect:Bs,useMemo:Bs,useReducer:Bs,useRef:Bs,useState:Bs,useDebugValue:Bs,useDeferredValue:Bs,useTransition:Bs,useMutableSource:Bs,useSyncExternalStore:Bs,useId:Bs,unstable_isNewReconciler:!1},Ic={readContext:ui,useCallback:function(a,u){return hi().memoizedState=[a,u===void 0?null:u],a},useContext:ui,useEffect:f_,useImperativeHandle:function(a,u,f){return f=f!=null?f.concat([a]):null,ed(4194308,4,nd.bind(null,u,a),f)},useLayoutEffect:function(a,u){return ed(4194308,4,a,u)},useInsertionEffect:function(a,u){return ed(4,2,a,u)},useMemo:function(a,u){var f=hi();return u=u===void 0?null:u,a=a(),f.memoizedState=[a,u],a},useReducer:function(a,u,f){var w=hi();return u=f!==void 0?f(u):u,w.memoizedState=w.baseState=u,a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:u},w.queue=a,a=a.dispatch=Qg.bind(null,ls,a),[w.memoizedState,a]},useRef:function(a){var u=hi();return a={current:a},u.memoizedState=a},useState:u_,useDebugValue:sd,useDeferredValue:function(a){return hi().memoizedState=a},useTransition:function(){var a=u_(!1),u=a[0];return a=rd.bind(null,a[1]),hi().memoizedState=a,[u,a]},useMutableSource:function(){},useSyncExternalStore:function(a,u,f){var w=ls,j=hi();if(Zn){if(f===void 0)throw Error(n(407));f=f()}else{if(f=u(),Is===null)throw Error(n(349));(Qn&30)!==0||Rc(w,u,f)}j.memoizedState=f;var C={value:f,getSnapshot:u};return j.queue=C,f_(Kf.bind(null,w,C,a),[a]),w.flags|=2048,Dl(9,l_.bind(null,w,C,f,u),void 0,null),f},useId:function(){var a=hi(),u=Is.identifierPrefix;if(Zn){var f=no,w=to;f=(w&~(1<<32-sr(w)-1)).toString(32)+f,u=":"+u+"R"+f,f=qa++,0<f&&(u+="H"+f.toString(32)),u+=":"}else f=io++,u=":"+u+"r"+f.toString(32)+":";return a.memoizedState=u},unstable_isNewReconciler:!1},ty={readContext:ui,useCallback:h_,useContext:ui,useEffect:kn,useImperativeHandle:Lc,useInsertionEffect:Us,useLayoutEffect:lr,useMemo:m_,useReducer:Mc,useRef:d_,useState:function(){return Mc(Tc)},useDebugValue:sd,useDeferredValue:function(a){var u=Pr();return Jf(u,$s.memoizedState,a)},useTransition:function(){var a=Mc(Tc)[0],u=Pr().memoizedState;return[a,u]},useMutableSource:ia,useSyncExternalStore:a_,useId:__,unstable_isNewReconciler:!1},Zf={readContext:ui,useCallback:h_,useContext:ui,useEffect:kn,useImperativeHandle:Lc,useInsertionEffect:Us,useLayoutEffect:lr,useMemo:m_,useReducer:Gf,useRef:d_,useState:function(){return Gf(Tc)},useDebugValue:sd,useDeferredValue:function(a){var u=Pr();return $s===null?u.memoizedState=a:Jf(u,$s.memoizedState,a)},useTransition:function(){var a=Gf(Tc)[0],u=Pr().memoizedState;return[a,u]},useMutableSource:ia,useSyncExternalStore:a_,useId:__,unstable_isNewReconciler:!1};function mi(a,u){if(a&&a.defaultProps){u=te({},u),a=a.defaultProps;for(var f in a)u[f]===void 0&&(u[f]=a[f]);return u}return u}function Qf(a,u,f,w){u=a.memoizedState,f=f(w,u),f=f==null?u:te({},u,f),a.memoizedState=f,a.lanes===0&&(a.updateQueue.baseState=f)}var id={isMounted:function(a){return(a=a._reactInternals)?sn(a)===a:!1},enqueueSetState:function(a,u,f){a=a._reactInternals;var w=$r(),j=Uo(a),C=Yr(w,j);C.payload=u,f!=null&&(C.callback=f),u=Xr(a,C,j),u!==null&&(gi(u,a,j,w),rn(u,a,j))},enqueueReplaceState:function(a,u,f){a=a._reactInternals;var w=$r(),j=Uo(a),C=Yr(w,j);C.tag=1,C.payload=u,f!=null&&(C.callback=f),u=Xr(a,C,j),u!==null&&(gi(u,a,j,w),rn(u,a,j))},enqueueForceUpdate:function(a,u){a=a._reactInternals;var f=$r(),w=Uo(a),j=Yr(f,w);j.tag=2,u!=null&&(j.callback=u),u=Xr(a,j,w),u!==null&&(gi(u,a,w,f),rn(u,a,w))}};function p_(a,u,f,w,j,C,q){return a=a.stateNode,typeof a.shouldComponentUpdate=="function"?a.shouldComponentUpdate(w,C,q):u.prototype&&u.prototype.isPureReactComponent?!Ki(f,w)||!Ki(j,C):!0}function g_(a,u,f){var w=!1,j=li,C=u.contextType;return typeof C=="object"&&C!==null?C=ui(C):(j=ir(u)?Ro:Ts.current,w=u.contextTypes,C=(w=w!=null)?Zi(a,j):li),u=new u(f,C),a.memoizedState=u.state!==null&&u.state!==void 0?u.state:null,u.updater=id,a.stateNode=u,u._reactInternals=a,w&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=j,a.__reactInternalMemoizedMaskedChildContext=C),u}function y_(a,u,f,w){a=u.state,typeof u.componentWillReceiveProps=="function"&&u.componentWillReceiveProps(f,w),typeof u.UNSAFE_componentWillReceiveProps=="function"&&u.UNSAFE_componentWillReceiveProps(f,w),u.state!==a&&id.enqueueReplaceState(u,u.state,null)}function eh(a,u,f,w){var j=a.stateNode;j.props=f,j.state=a.memoizedState,j.refs={},Nc(a);var C=u.contextType;typeof C=="object"&&C!==null?j.context=ui(C):(C=ir(u)?Ro:Ts.current,j.context=Zi(a,C)),j.state=a.memoizedState,C=u.getDerivedStateFromProps,typeof C=="function"&&(Qf(a,u,C,f),j.state=a.memoizedState),typeof u.getDerivedStateFromProps=="function"||typeof j.getSnapshotBeforeUpdate=="function"||typeof j.UNSAFE_componentWillMount!="function"&&typeof j.componentWillMount!="function"||(u=j.state,typeof j.componentWillMount=="function"&&j.componentWillMount(),typeof j.UNSAFE_componentWillMount=="function"&&j.UNSAFE_componentWillMount(),u!==j.state&&id.enqueueReplaceState(j,j.state,null),Il(a,f,j,w),j.state=a.memoizedState),typeof j.componentDidMount=="function"&&(a.flags|=4194308)}function Va(a,u){try{var f="",w=u;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:u,stack:j,digest:null}}function Oc(a,u,f){return{value:a,source:null,stack:f??null,digest:u??null}}function th(a,u){try{console.error(u.value)}catch(f){setTimeout(function(){throw f})}}var ny=typeof WeakMap=="function"?WeakMap:Map;function Pc(a,u,f){f=Yr(-1,f),f.tag=3,f.payload={element:null};var w=u.value;return f.callback=function(){Hc||(Hc=!0,lh=w),th(a,u)},f}function w_(a,u,f){f=Yr(-1,f),f.tag=3;var w=a.type.getDerivedStateFromError;if(typeof w=="function"){var j=u.value;f.payload=function(){return w(j)},f.callback=function(){th(a,u)}}var C=a.stateNode;return C!==null&&typeof C.componentDidCatch=="function"&&(f.callback=function(){th(a,u),typeof w!="function"&&(pi===null?pi=new Set([this]):pi.add(this));var q=u.stack;this.componentDidCatch(u.value,{componentStack:q!==null?q:""})}),f}function oa(a,u,f){var w=a.pingCache;if(w===null){w=a.pingCache=new ny;var j=new Set;w.set(u,j)}else j=w.get(u),j===void 0&&(j=new Set,w.set(u,j));j.has(f)||(j.add(f),a=X.bind(null,a,u,f),u.then(a,a))}function cr(a){do{var u;if((u=a.tag===13)&&(u=a.memoizedState,u=u!==null?u.dehydrated!==null:!0),u)return a;a=a.return}while(a!==null);return null}function Ws(a,u,f,w,j){return(a.mode&1)===0?(a===u?a.flags|=65536:(a.flags|=128,f.flags|=131072,f.flags&=-52805,f.tag===1&&(f.alternate===null?f.tag=17:(u=Yr(-1,1),u.tag=2,Xr(f,u,1))),f.lanes|=1),a):(a.flags|=65536,a.lanes=j,a)}var ao=S.ReactCurrentOwner,Cs=!1;function xs(a,u,f,w){u.child=a===null?Df(u,null,f,w):Oo(u,a.child,f,w)}function _i(a,u,f,w,j){f=f.render;var C=u.ref;return Ua(u,j),w=Vf(a,u,f,w,C,j),f=Hf(),a!==null&&!Cs?(u.updateQueue=a.updateQueue,u.flags&=-2053,a.lanes&=~j,zo(a,u,j)):(Zn&&f&&Gu(u),u.flags|=1,xs(a,u,w,j),u.child)}function v_(a,u,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?(u.tag=15,u.type=C,Dc(a,u,C,w,j)):(a=xn(f.type,null,w,u,u.mode,j),a.ref=u.ref,a.return=u,u.child=a)}if(C=a.child,(a.lanes&j)===0){var q=C.memoizedProps;if(f=f.compare,f=f!==null?f:Ki,f(q,w)&&a.ref===u.ref)return zo(a,u,j)}return u.flags|=1,a=lt(C,w),a.ref=u.ref,a.return=u,u.child=a}function Dc(a,u,f,w,j){if(a!==null){var C=a.memoizedProps;if(Ki(C,w)&&a.ref===u.ref)if(Cs=!1,u.pendingProps=w=C,(a.lanes&j)!==0)(a.flags&131072)!==0&&(Cs=!0);else return u.lanes=a.lanes,zo(a,u,j)}return nh(a,u,f,w,j)}function x_(a,u,f){var w=u.pendingProps,j=w.children,C=a!==null?a.memoizedState:null;if(w.mode==="hidden")if((u.mode&1)===0)u.memoizedState={baseLanes:0,cachePool:null,transitions:null},Xn(uo,Nr),Nr|=f;else{if((f&1073741824)===0)return a=C!==null?C.baseLanes|f:f,u.lanes=u.childLanes=1073741824,u.memoizedState={baseLanes:a,cachePool:null,transitions:null},u.updateQueue=null,Xn(uo,Nr),Nr|=a,null;u.memoizedState={baseLanes:0,cachePool:null,transitions:null},w=C!==null?C.baseLanes:f,Xn(uo,Nr),Nr|=w}else C!==null?(w=C.baseLanes|f,u.memoizedState=null):w=f,Xn(uo,Nr),Nr|=w;return xs(a,u,j,f),u.child}function od(a,u){var f=u.ref;(a===null&&f!==null||a!==null&&a.ref!==f)&&(u.flags|=512,u.flags|=2097152)}function nh(a,u,f,w,j){var C=ir(f)?Ro:Ts.current;return C=Zi(u,C),Ua(u,j),f=Vf(a,u,f,w,C,j),w=Hf(),a!==null&&!Cs?(u.updateQueue=a.updateQueue,u.flags&=-2053,a.lanes&=~j,zo(a,u,j)):(Zn&&w&&Gu(u),u.flags|=1,xs(a,u,f,j),u.child)}function b_(a,u,f,w,j){if(ir(f)){var C=!0;Cl(u)}else C=!1;if(Ua(u,j),u.stateNode===null)Bl(a,u),g_(u,f,w),eh(u,f,w,j),w=!0;else if(a===null){var q=u.stateNode,ie=u.memoizedProps;q.props=ie;var ue=q.context,Te=f.contextType;typeof Te=="object"&&Te!==null?Te=ui(Te):(Te=ir(f)?Ro:Ts.current,Te=Zi(u,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)&&y_(u,q,w,Te),_s=!1;var Je=u.memoizedState;q.state=Je,Il(u,w,q,j),ue=u.memoizedState,ie!==w||Je!==ue||br.current||_s?(typeof Ze=="function"&&(Qf(u,f,Ze,w),ue=u.memoizedState),(ie=_s||p_(u,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"&&(u.flags|=4194308)):(typeof q.componentDidMount=="function"&&(u.flags|=4194308),u.memoizedProps=w,u.memoizedState=ue),q.props=w,q.state=ue,q.context=Te,w=ie):(typeof q.componentDidMount=="function"&&(u.flags|=4194308),w=!1)}else{q=u.stateNode,Uf(a,u),ie=u.memoizedProps,Te=u.type===u.elementType?ie:mi(u.type,ie),q.props=Te,tt=u.pendingProps,Je=q.context,ue=f.contextType,typeof ue=="object"&&ue!==null?ue=ui(ue):(ue=ir(f)?Ro:Ts.current,ue=Zi(u,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)&&y_(u,q,w,ue),_s=!1,Je=u.memoizedState,q.state=Je,Il(u,w,q,j);var $t=u.memoizedState;ie!==tt||Je!==$t||br.current||_s?(typeof kt=="function"&&(Qf(u,f,kt,w),$t=u.memoizedState),(Te=_s||p_(u,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"&&(u.flags|=4),typeof q.getSnapshotBeforeUpdate=="function"&&(u.flags|=1024)):(typeof q.componentDidUpdate!="function"||ie===a.memoizedProps&&Je===a.memoizedState||(u.flags|=4),typeof q.getSnapshotBeforeUpdate!="function"||ie===a.memoizedProps&&Je===a.memoizedState||(u.flags|=1024),u.memoizedProps=w,u.memoizedState=$t),q.props=w,q.state=$t,q.context=ue,w=Te):(typeof q.componentDidUpdate!="function"||ie===a.memoizedProps&&Je===a.memoizedState||(u.flags|=4),typeof q.getSnapshotBeforeUpdate!="function"||ie===a.memoizedProps&&Je===a.memoizedState||(u.flags|=1024),w=!1)}return ad(a,u,f,w,C,j)}function ad(a,u,f,w,j,C){od(a,u);var q=(u.flags&128)!==0;if(!w&&!q)return j&&Wu(u,f,!1),zo(a,u,C);w=u.stateNode,ao.current=u;var ie=q&&typeof f.getDerivedStateFromError!="function"?null:w.render();return u.flags|=1,a!==null&&q?(u.child=Oo(u,a.child,null,C),u.child=Oo(u,null,ie,C)):xs(a,u,ie,C),u.memoizedState=w.state,j&&Wu(u,f,!0),u.child}function aa(a){var u=a.stateNode;u.pendingContext?Uu(a,u.pendingContext,u.pendingContext!==u.context):u.context&&Uu(a,u.context,!1),Xu(a,u.containerInfo)}function zl(a,u,f,w,j){return Ba(),If(j),u.flags|=256,xs(a,u,f,w),u.child}var ld={dehydrated:null,treeContext:null,retryLane:0};function cd(a){return{baseLanes:a,cachePool:null,transitions:null}}function k_(a,u,f){var w=u.pendingProps,j=ps.current,C=!1,q=(u.flags&128)!==0,ie;if((ie=q)||(ie=a!==null&&a.memoizedState===null?!1:(j&2)!==0),ie?(C=!0,u.flags&=-129):(a===null||a.memoizedState!==null)&&(j|=1),Xn(ps,j&1),a===null)return Sc(u),a=u.memoizedState,a!==null&&(a=a.dehydrated,a!==null)?((u.mode&1)===0?u.lanes=1:a.data==="$!"?u.lanes=8:u.lanes=1073741824,null):(q=w.children,a=w.fallback,C?(w=u.mode,C=u.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=u,a.return=u,C.sibling=a,u.child=C,u.child.memoizedState=cd(f),u.memoizedState=ld,a):ud(u,q));if(j=a.memoizedState,j!==null&&(ie=j.dehydrated,ie!==null))return sy(a,u,q,w,ie,j,f);if(C){C=w.fallback,q=u.mode,j=a.child,ie=j.sibling;var ue={mode:"hidden",children:w.children};return(q&1)===0&&u.child!==j?(w=u.child,w.childLanes=0,w.pendingProps=ue,u.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=u,w.return=u,w.sibling=C,u.child=w,w=C,C=u.child,q=a.child.memoizedState,q=q===null?cd(f):{baseLanes:q.baseLanes|f,cachePool:null,transitions:q.transitions},C.memoizedState=q,C.childLanes=a.childLanes&~f,u.memoizedState=ld,w}return C=a.child,a=C.sibling,w=lt(C,{mode:"visible",children:w.children}),(u.mode&1)===0&&(w.lanes=f),w.return=u,w.sibling=null,a!==null&&(f=u.deletions,f===null?(u.deletions=[a],u.flags|=16):f.push(a)),u.child=w,u.memoizedState=null,w}function ud(a,u){return u=ft({mode:"visible",children:u},a.mode,0,null),u.return=a,a.child=u}function Fo(a,u,f,w){return w!==null&&If(w),Oo(u,a.child,null,f),a=ud(u,u.pendingProps.children),a.flags|=2,u.memoizedState=null,a}function sy(a,u,f,w,j,C,q){if(f)return u.flags&256?(u.flags&=-257,w=Oc(Error(n(422))),Fo(a,u,q,w)):u.memoizedState!==null?(u.child=a.child,u.flags|=128,null):(C=w.fallback,j=u.mode,w=ft({mode:"visible",children:w.children},j,0,null),C=qt(C,j,q,null),C.flags|=2,w.return=u,C.return=u,w.sibling=C,u.child=w,(u.mode&1)!==0&&Oo(u,a.child,null,q),u.child.memoizedState=cd(q),u.memoizedState=ld,C);if((u.mode&1)===0)return Fo(a,u,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=Oc(C,w,void 0),Fo(a,u,q,w)}if(ie=(q&a.childLanes)!==0,Cs||ie){if(w=Is,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),gi(w,a,j,-1))}return gd(),w=Oc(Error(n(421))),Fo(a,u,q,w)}return j.data==="$?"?(u.flags|=128,u.child=a.child,u=oe.bind(null,a),j._reactRetry=u,null):(a=C.treeContext,Or=ta(j.nextSibling),Jr=u,Zn=!0,Mi=null,a!==null&&(kr[Kr++]=to,kr[Kr++]=no,kr[Kr++]=eo,to=a.id,no=a.overflow,eo=u),u=ud(u,w.children),u.flags|=4096,u)}function Fc(a,u,f){a.lanes|=u;var w=a.alternate;w!==null&&(w.lanes|=u),Ju(a.return,u,f)}function dd(a,u,f,w,j){var C=a.memoizedState;C===null?a.memoizedState={isBackwards:u,rendering:null,renderingStartTime:0,last:w,tail:f,tailMode:j}:(C.isBackwards=u,C.rendering=null,C.renderingStartTime=0,C.last=w,C.tail=f,C.tailMode=j)}function j_(a,u,f){var w=u.pendingProps,j=w.revealOrder,C=w.tail;if(xs(a,u,w.children,f),w=ps.current,(w&2)!==0)w=w&1|2,u.flags|=128;else{if(a!==null&&(a.flags&128)!==0)e:for(a=u.child;a!==null;){if(a.tag===13)a.memoizedState!==null&&Fc(a,f,u);else if(a.tag===19)Fc(a,f,u);else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===u)break e;for(;a.sibling===null;){if(a.return===null||a.return===u)break e;a=a.return}a.sibling.return=a.return,a=a.sibling}w&=1}if(Xn(ps,w),(u.mode&1)===0)u.memoizedState=null;else switch(j){case"forwards":for(f=u.child,j=null;f!==null;)a=f.alternate,a!==null&&Zu(a)===null&&(j=f),f=f.sibling;f=j,f===null?(j=u.child,u.child=null):(j=f.sibling,f.sibling=null),dd(u,!1,j,f,C);break;case"backwards":for(f=null,j=u.child,u.child=null;j!==null;){if(a=j.alternate,a!==null&&Zu(a)===null){u.child=j;break}a=j.sibling,j.sibling=f,f=j,j=a}dd(u,!0,f,null,C);break;case"together":dd(u,!1,null,null,void 0);break;default:u.memoizedState=null}return u.child}function Bl(a,u){(u.mode&1)===0&&a!==null&&(a.alternate=null,u.alternate=null,u.flags|=2)}function zo(a,u,f){if(a!==null&&(u.dependencies=a.dependencies),ca|=u.lanes,(f&u.childLanes)===0)return null;if(a!==null&&u.child!==a.child)throw Error(n(153));if(u.child!==null){for(a=u.child,f=lt(a,a.pendingProps),u.child=f,f.return=u;a.sibling!==null;)a=a.sibling,f=f.sibling=lt(a,a.pendingProps),f.return=u;f.sibling=null}return u.child}function ry(a,u,f){switch(u.tag){case 3:aa(u),Ba();break;case 5:fi(u);break;case 1:ir(u.type)&&Cl(u);break;case 4:Xu(u,u.stateNode.containerInfo);break;case 10:var w=u.type._context,j=u.memoizedProps.value;Xn(Po,w._currentValue),w._currentValue=j;break;case 13:if(w=u.memoizedState,w!==null)return w.dehydrated!==null?(Xn(ps,ps.current&1),u.flags|=128,null):(f&u.child.childLanes)!==0?k_(a,u,f):(Xn(ps,ps.current&1),a=zo(a,u,f),a!==null?a.sibling:null);Xn(ps,ps.current&1);break;case 19:if(w=(f&u.childLanes)!==0,(a.flags&128)!==0){if(w)return j_(a,u,f);u.flags|=128}if(j=u.memoizedState,j!==null&&(j.rendering=null,j.tail=null,j.lastEffect=null),Xn(ps,ps.current),w)break;return null;case 22:case 23:return u.lanes=0,x_(a,u,f)}return zo(a,u,f)}var S_,Sr,Ha,N_;S_=function(a,u){for(var f=u.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===u)break;for(;f.sibling===null;){if(f.return===null||f.return===u)return;f=f.return}f.sibling.return=f.return,f=f.sibling}},Sr=function(){},Ha=function(a,u,f,w){var j=a.memoizedProps;if(j!==w){a=u.stateNode,jr(ro.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=jc)}Rt(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"&&Bn("scroll",a),C||ie===ue||(C=[])):(C=C||[]).push(Te,ue))}f&&(C=C||[]).push("style",f);var Te=C;(u.updateQueue=Te)&&(u.flags|=4)}},N_=function(a,u,f,w){f!==w&&(u.flags|=4)};function Ul(a,u){if(!Zn)switch(a.tailMode){case"hidden":u=a.tail;for(var f=null;u!==null;)u.alternate!==null&&(f=u),u=u.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?u||a.tail===null?a.tail=null:a.tail.sibling=null:w.sibling=null}}function Jn(a){var u=a.alternate!==null&&a.alternate.child===a.child,f=0,w=0;if(u)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,u}function sh(a,u,f){var w=u.pendingProps;switch(Ku(u),u.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Jn(u),null;case 1:return ir(u.type)&&Lo(),Jn(u),null;case 3:return w=u.stateNode,di(),Pn(br),Pn(Ts),Qu(),w.pendingContext&&(w.context=w.pendingContext,w.pendingContext=null),(a===null||a.child===null)&&(Ml(u)?u.flags|=4:a===null||a.memoizedState.isDehydrated&&(u.flags&256)===0||(u.flags|=1024,Mi!==null&&(ch(Mi),Mi=null))),Sr(a,u),Jn(u),null;case 5:Ol(u);var j=jr(Wa.current);if(f=u.type,a!==null&&u.stateNode!=null)Ha(a,u,f,w,j),a.ref!==u.ref&&(u.flags|=512,u.flags|=2097152);else{if(!w){if(u.stateNode===null)throw Error(n(166));return Jn(u),null}if(a=jr(ro.current),Ml(u)){w=u.stateNode,f=u.type;var C=u.memoizedProps;switch(w[Xi]=u,w[Ao]=C,a=(u.mode&1)!==0,f){case"dialog":Bn("cancel",w),Bn("close",w);break;case"iframe":case"object":case"embed":Bn("load",w);break;case"video":case"audio":for(j=0;j<Co.length;j++)Bn(Co[j],w);break;case"source":Bn("error",w);break;case"img":case"image":case"link":Bn("error",w),Bn("load",w);break;case"details":Bn("toggle",w);break;case"input":ze(w,C),Bn("invalid",w);break;case"select":w._wrapperState={wasMultiple:!!C.multiple},Bn("invalid",w);break;case"textarea":Q(w,C),Bn("invalid",w)}Rt(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&&kc(w.textContent,ie,a),j=["children",ie]):typeof ie=="number"&&w.textContent!==""+ie&&(C.suppressHydrationWarning!==!0&&kc(w.textContent,ie,a),j=["children",""+ie]):i.hasOwnProperty(q)&&ie!=null&&q==="onScroll"&&Bn("scroll",w)}switch(f){case"input":Ve(w),Qe(w,C,!0);break;case"textarea":Ve(w),le(w);break;case"select":case"option":break;default:typeof C.onClick=="function"&&(w.onclick=jc)}w=j,u.updateQueue=w,w!==null&&(u.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[Xi]=u,a[Ao]=w,S_(a,u,!1,!1),u.stateNode=a;e:{switch(q=mn(f,w),f){case"dialog":Bn("cancel",a),Bn("close",a),j=w;break;case"iframe":case"object":case"embed":Bn("load",a),j=w;break;case"video":case"audio":for(j=0;j<Co.length;j++)Bn(Co[j],a);j=w;break;case"source":Bn("error",a),j=w;break;case"img":case"image":case"link":Bn("error",a),Bn("load",a),j=w;break;case"details":Bn("toggle",a),j=w;break;case"input":ze(a,w),j=rt(a,w),Bn("invalid",a);break;case"option":j=w;break;case"select":a._wrapperState={wasMultiple:!!w.multiple},j=te({},w,{value:void 0}),Bn("invalid",a);break;case"textarea":Q(a,w),j=ce(a,w),Bn("invalid",a);break;default:j=w}Rt(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"&&Bn("scroll",a):ue!=null&&E(a,C,ue,q))}switch(f){case"input":Ve(a),Qe(a,w,!1);break;case"textarea":Ve(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=jc)}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&&(u.flags|=4)}u.ref!==null&&(u.flags|=512,u.flags|=2097152)}return Jn(u),null;case 6:if(a&&u.stateNode!=null)N_(a,u,a.memoizedProps,w);else{if(typeof w!="string"&&u.stateNode===null)throw Error(n(166));if(f=jr(Wa.current),jr(ro.current),Ml(u)){if(w=u.stateNode,f=u.memoizedProps,w[Xi]=u,(C=w.nodeValue!==f)&&(a=Jr,a!==null))switch(a.tag){case 3:kc(w.nodeValue,f,(a.mode&1)!==0);break;case 5:a.memoizedProps.suppressHydrationWarning!==!0&&kc(w.nodeValue,f,(a.mode&1)!==0)}C&&(u.flags|=4)}else w=(f.nodeType===9?f:f.ownerDocument).createTextNode(w),w[Xi]=u,u.stateNode=w}return Jn(u),null;case 13:if(Pn(ps),w=u.memoizedState,a===null||a.memoizedState!==null&&a.memoizedState.dehydrated!==null){if(Zn&&Or!==null&&(u.mode&1)!==0&&(u.flags&128)===0)r_(),Ba(),u.flags|=98560,C=!1;else if(C=Ml(u),w!==null&&w.dehydrated!==null){if(a===null){if(!C)throw Error(n(318));if(C=u.memoizedState,C=C!==null?C.dehydrated:null,!C)throw Error(n(317));C[Xi]=u}else Ba(),(u.flags&128)===0&&(u.memoizedState=null),u.flags|=4;Jn(u),C=!1}else Mi!==null&&(ch(Mi),Mi=null),C=!0;if(!C)return u.flags&65536?u:null}return(u.flags&128)!==0?(u.lanes=f,u):(w=w!==null,w!==(a!==null&&a.memoizedState!==null)&&w&&(u.child.flags|=8192,(u.mode&1)!==0&&(a===null||(ps.current&1)!==0?ys===0&&(ys=3):gd())),u.updateQueue!==null&&(u.flags|=4),Jn(u),null);case 4:return di(),Sr(a,u),a===null&&Ei(u.stateNode.containerInfo),Jn(u),null;case 10:return Bf(u.type._context),Jn(u),null;case 17:return ir(u.type)&&Lo(),Jn(u),null;case 19:if(Pn(ps),C=u.memoizedState,C===null)return Jn(u),null;if(w=(u.flags&128)!==0,q=C.rendering,q===null)if(w)Ul(C,!1);else{if(ys!==0||a!==null&&(a.flags&128)!==0)for(a=u.child;a!==null;){if(q=Zu(a),q!==null){for(u.flags|=128,Ul(C,!1),w=q.updateQueue,w!==null&&(u.updateQueue=w,u.flags|=4),u.subtreeFlags=0,w=f,f=u.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 Xn(ps,ps.current&1|2),u.child}a=a.sibling}C.tail!==null&&cn()>ua&&(u.flags|=128,w=!0,Ul(C,!1),u.lanes=4194304)}else{if(!w)if(a=Zu(q),a!==null){if(u.flags|=128,w=!0,f=a.updateQueue,f!==null&&(u.updateQueue=f,u.flags|=4),Ul(C,!0),C.tail===null&&C.tailMode==="hidden"&&!q.alternate&&!Zn)return Jn(u),null}else 2*cn()-C.renderingStartTime>ua&&f!==1073741824&&(u.flags|=128,w=!0,Ul(C,!1),u.lanes=4194304);C.isBackwards?(q.sibling=u.child,u.child=q):(f=C.last,f!==null?f.sibling=q:u.child=q,C.last=q)}return C.tail!==null?(u=C.tail,C.rendering=u,C.tail=u.sibling,C.renderingStartTime=cn(),u.sibling=null,f=ps.current,Xn(ps,w?f&1|2:f&1),u):(Jn(u),null);case 22:case 23:return pd(),w=u.memoizedState!==null,a!==null&&a.memoizedState!==null!==w&&(u.flags|=8192),w&&(u.mode&1)!==0?(Nr&1073741824)!==0&&(Jn(u),u.subtreeFlags&6&&(u.flags|=8192)):Jn(u),null;case 24:return null;case 25:return null}throw Error(n(156,u.tag))}function $_(a,u){switch(Ku(u),u.tag){case 1:return ir(u.type)&&Lo(),a=u.flags,a&65536?(u.flags=a&-65537|128,u):null;case 3:return di(),Pn(br),Pn(Ts),Qu(),a=u.flags,(a&65536)!==0&&(a&128)===0?(u.flags=a&-65537|128,u):null;case 5:return Ol(u),null;case 13:if(Pn(ps),a=u.memoizedState,a!==null&&a.dehydrated!==null){if(u.alternate===null)throw Error(n(340));Ba()}return a=u.flags,a&65536?(u.flags=a&-65537|128,u):null;case 19:return Pn(ps),null;case 4:return di(),null;case 10:return Bf(u.type._context),null;case 22:case 23:return pd(),null;case 24:return null;default:return null}}var zc=!1,ur=!1,iy=typeof WeakSet=="function"?WeakSet:Set,jt=null;function qs(a,u){var f=a.ref;if(f!==null)if(typeof f=="function")try{f(null)}catch(w){Z(a,u,w)}else f.current=null}function Ga(a,u,f){try{f()}catch(w){Z(a,u,w)}}var rh=!1;function C_(a,u){if(Fu=rr,a=Sf(),Ra(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(Ef={focusedElem:a,selectionRange:f},rr=!1,jt=u;jt!==null;)if(u=jt,a=u.child,(u.subtreeFlags&1028)!==0&&a!==null)a.return=u,jt=a;else for(;jt!==null;){u=jt;try{var $t=u.alternate;if((u.flags&1024)!==0)switch(u.tag){case 0:case 11:case 15:break;case 1:if($t!==null){var Tt=$t.memoizedProps,Os=$t.memoizedState,ve=u.stateNode,me=ve.getSnapshotBeforeUpdate(u.elementType===u.type?Tt:mi(u.type,Tt),Os);ve.__reactInternalSnapshotBeforeUpdate=me}break;case 3:var Ne=u.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(u,u.return,it)}if(a=u.sibling,a!==null){a.return=u.return,jt=a;break}jt=u.return}return $t=rh,rh=!1,$t}function lo(a,u,f){var w=u.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&&Ga(u,f,C)}j=j.next}while(j!==w)}}function Bc(a,u){if(u=u.updateQueue,u=u!==null?u.lastEffect:null,u!==null){var f=u=u.next;do{if((f.tag&a)===a){var w=f.create;f.destroy=w()}f=f.next}while(f!==u)}}function Li(a){var u=a.ref;if(u!==null){var f=a.stateNode;switch(a.tag){case 5:a=f;break;default:a=f}typeof u=="function"?u(a):u.current=a}}function E_(a){var u=a.alternate;u!==null&&(a.alternate=null,E_(u)),a.child=null,a.deletions=null,a.sibling=null,a.tag===5&&(u=a.stateNode,u!==null&&(delete u[Xi],delete u[Ao],delete u[Sl],delete u[Qm],delete u[Nl])),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 A_(a){return a.tag===5||a.tag===3||a.tag===4}function ih(a){e:for(;;){for(;a.sibling===null;){if(a.return===null||A_(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 Ii(a,u,f){var w=a.tag;if(w===5||w===6)a=a.stateNode,u?f.nodeType===8?f.parentNode.insertBefore(a,u):f.insertBefore(a,u):(f.nodeType===8?(u=f.parentNode,u.insertBefore(a,f)):(u=f,u.appendChild(a)),f=f._reactRootContainer,f!=null||u.onclick!==null||(u.onclick=jc));else if(w!==4&&(a=a.child,a!==null))for(Ii(a,u,f),a=a.sibling;a!==null;)Ii(a,u,f),a=a.sibling}function Uc(a,u,f){var w=a.tag;if(w===5||w===6)a=a.stateNode,u?f.insertBefore(a,u):f.appendChild(a);else if(w!==4&&(a=a.child,a!==null))for(Uc(a,u,f),a=a.sibling;a!==null;)Uc(a,u,f),a=a.sibling}var Ys=null,Oi=!1;function la(a,u,f){for(f=f.child;f!==null;)oh(a,u,f),f=f.sibling}function oh(a,u,f){if(nr&&typeof nr.onCommitFiberUnmount=="function")try{nr.onCommitFiberUnmount(zn,f)}catch{}switch(f.tag){case 5:ur||qs(f,u);case 6:var w=Ys,j=Oi;Ys=null,la(a,u,f),Ys=w,Oi=j,Ys!==null&&(Oi?(a=Ys,f=f.stateNode,a.nodeType===8?a.parentNode.removeChild(f):a.removeChild(f)):Ys.removeChild(f.stateNode));break;case 18:Ys!==null&&(Oi?(a=Ys,f=f.stateNode,a.nodeType===8?Bu(a.parentNode,f):a.nodeType===1&&Bu(a,f),Ea(a)):Bu(Ys,f.stateNode));break;case 4:w=Ys,j=Oi,Ys=f.stateNode.containerInfo,Oi=!0,la(a,u,f),Ys=w,Oi=j;break;case 0:case 11:case 14:case 15:if(!ur&&(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)&&Ga(f,u,q),j=j.next}while(j!==w)}la(a,u,f);break;case 1:if(!ur&&(qs(f,u),w=f.stateNode,typeof w.componentWillUnmount=="function"))try{w.props=f.memoizedProps,w.state=f.memoizedState,w.componentWillUnmount()}catch(ie){Z(f,u,ie)}la(a,u,f);break;case 21:la(a,u,f);break;case 22:f.mode&1?(ur=(w=ur)||f.memoizedState!==null,la(a,u,f),ur=w):la(a,u,f);break;default:la(a,u,f)}}function T_(a){var u=a.updateQueue;if(u!==null){a.updateQueue=null;var f=a.stateNode;f===null&&(f=a.stateNode=new iy),u.forEach(function(w){var j=Ge.bind(null,a,w);f.has(w)||(f.add(w),w.then(j,j))})}}function Cn(a,u){var f=u.deletions;if(f!==null)for(var w=0;w<f.length;w++){var j=f[w];try{var C=a,q=u,ie=q;e:for(;ie!==null;){switch(ie.tag){case 5:Ys=ie.stateNode,Oi=!1;break e;case 3:Ys=ie.stateNode.containerInfo,Oi=!0;break e;case 4:Ys=ie.stateNode.containerInfo,Oi=!0;break e}ie=ie.return}if(Ys===null)throw Error(n(160));oh(C,q,j),Ys=null,Oi=!1;var ue=j.alternate;ue!==null&&(ue.return=null),j.return=null}catch(Te){Z(j,u,Te)}}if(u.subtreeFlags&12854)for(u=u.child;u!==null;)gs(u,a),u=u.sibling}function gs(a,u){var f=a.alternate,w=a.flags;switch(a.tag){case 0:case 11:case 14:case 15:if(Cn(u,a),cs(a),w&4){try{lo(3,a,a.return),Bc(3,a)}catch(Tt){Z(a,a.return,Tt)}try{lo(5,a,a.return)}catch(Tt){Z(a,a.return,Tt)}}break;case 1:Cn(u,a),cs(a),w&512&&f!==null&&qs(f,f.return);break;case 5:if(Cn(u,a),cs(a),w&512&&f!==null&&qs(f,f.return),a.flags&32){var j=a.stateNode;try{_t(j,"")}catch(Tt){Z(a,a.return,Tt)}}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&&He(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[Ao]=C}catch(Tt){Z(a,a.return,Tt)}}break;case 6:if(Cn(u,a),cs(a),w&4){if(a.stateNode===null)throw Error(n(162));j=a.stateNode,C=a.memoizedProps;try{j.nodeValue=C}catch(Tt){Z(a,a.return,Tt)}}break;case 3:if(Cn(u,a),cs(a),w&4&&f!==null&&f.memoizedState.isDehydrated)try{Ea(u.containerInfo)}catch(Tt){Z(a,a.return,Tt)}break;case 4:Cn(u,a),cs(a);break;case 13:Cn(u,a),cs(a),j=a.child,j.flags&8192&&(C=j.memoizedState!==null,j.stateNode.isHidden=C,!C||j.alternate!==null&&j.alternate.memoizedState!==null||(Vc=cn())),w&4&&T_(a);break;case 22:if(Ze=f!==null&&f.memoizedState!==null,a.mode&1?(ur=(Te=ur)||Ze,Cn(u,a),ur=Te):Cn(u,a),cs(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:lo(4,Je,Je.return);break;case 1:qs(Je,Je.return);var $t=Je.stateNode;if(typeof $t.componentWillUnmount=="function"){w=Je,f=Je.return;try{u=w,$t.props=u.memoizedProps,$t.state=u.memoizedState,$t.componentWillUnmount()}catch(Tt){Z(w,f,Tt)}}break;case 5:qs(Je,Je.return);break;case 22:if(Je.memoizedState!==null){fd(tt);continue}}kt!==null?(kt.return=Je,jt=kt):fd(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(Tt){Z(a,a.return,Tt)}}}else if(tt.tag===6){if(Ze===null)try{tt.stateNode.nodeValue=Te?"":tt.memoizedProps}catch(Tt){Z(a,a.return,Tt)}}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:Cn(u,a),cs(a),w&4&&T_(a);break;case 21:break;default:Cn(u,a),cs(a)}}function cs(a){var u=a.flags;if(u&2){try{e:{for(var f=a.return;f!==null;){if(A_(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=ih(a);Uc(a,C,j);break;case 3:case 4:var q=w.stateNode.containerInfo,ie=ih(a);Ii(a,ie,q);break;default:throw Error(n(161))}}catch(ue){Z(a,a.return,ue)}a.flags&=-3}u&4096&&(a.flags&=-4097)}function M_(a,u,f){jt=a,R_(a)}function R_(a,u,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||zc;if(!q){var ie=j.alternate,ue=ie!==null&&ie.memoizedState!==null||ur;ie=zc;var Te=ur;if(zc=q,(ur=ue)&&!Te)for(jt=j;jt!==null;)q=jt,ue=q.child,q.tag===22&&q.memoizedState!==null?I_(j):ue!==null?(ue.return=q,jt=ue):I_(j);for(;C!==null;)jt=C,R_(C),C=C.sibling;jt=j,zc=ie,ur=Te}L_(a)}else(j.subtreeFlags&8772)!==0&&C!==null?(C.return=j,jt=C):L_(a)}}function L_(a){for(;jt!==null;){var u=jt;if((u.flags&8772)!==0){var f=u.alternate;try{if((u.flags&8772)!==0)switch(u.tag){case 0:case 11:case 15:ur||Bc(5,u);break;case 1:var w=u.stateNode;if(u.flags&4&&!ur)if(f===null)w.componentDidMount();else{var j=u.elementType===u.type?f.memoizedProps:mi(u.type,f.memoizedProps);w.componentDidUpdate(j,f.memoizedState,w.__reactInternalSnapshotBeforeUpdate)}var C=u.updateQueue;C!==null&&o_(u,C,w);break;case 3:var q=u.updateQueue;if(q!==null){if(f=null,u.child!==null)switch(u.child.tag){case 5:f=u.child.stateNode;break;case 1:f=u.child.stateNode}o_(u,q,f)}break;case 5:var ie=u.stateNode;if(f===null&&u.flags&4){f=ie;var ue=u.memoizedProps;switch(u.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(u.memoizedState===null){var Te=u.alternate;if(Te!==null){var Ze=Te.memoizedState;if(Ze!==null){var tt=Ze.dehydrated;tt!==null&&Ea(tt)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}ur||u.flags&512&&Li(u)}catch(Je){Z(u,u.return,Je)}}if(u===a){jt=null;break}if(f=u.sibling,f!==null){f.return=u.return,jt=f;break}jt=u.return}}function fd(a){for(;jt!==null;){var u=jt;if(u===a){jt=null;break}var f=u.sibling;if(f!==null){f.return=u.return,jt=f;break}jt=u.return}}function I_(a){for(;jt!==null;){var u=jt;try{switch(u.tag){case 0:case 11:case 15:var f=u.return;try{Bc(4,u)}catch(ue){Z(u,f,ue)}break;case 1:var w=u.stateNode;if(typeof w.componentDidMount=="function"){var j=u.return;try{w.componentDidMount()}catch(ue){Z(u,j,ue)}}var C=u.return;try{Li(u)}catch(ue){Z(u,C,ue)}break;case 5:var q=u.return;try{Li(u)}catch(ue){Z(u,q,ue)}}}catch(ue){Z(u,u.return,ue)}if(u===a){jt=null;break}var ie=u.sibling;if(ie!==null){ie.return=u.return,jt=ie;break}jt=u.return}}var oy=Math.ceil,co=S.ReactCurrentDispatcher,ah=S.ReactCurrentOwner,Zr=S.ReactCurrentBatchConfig,Tn=0,Is=null,Es=null,Vs=0,Nr=0,uo=sa(0),ys=0,Wl=null,ca=0,Wc=0,fo=0,qc=null,Ms=null,Vc=0,ua=1/0,ho=null,Hc=!1,lh=null,pi=null,mo=!1,da=null,fa=0,Gc=0,ql=null,Bo=-1,hd=0;function $r(){return(Tn&6)!==0?cn():Bo!==-1?Bo:Bo=cn()}function Uo(a){return(a.mode&1)===0?1:(Tn&2)!==0&&Vs!==0?Vs&-Vs:Of.transition!==null?(hd===0&&(hd=Ls()),hd):(a=In,a!==0||(a=window.event,a=a===void 0?16:Oe(a.type)),a)}function gi(a,u,f,w){if(50<Gc)throw Gc=0,ql=null,Error(n(185));Ss(a,f,w),((Tn&2)===0||a!==Is)&&(a===Is&&((Tn&2)===0&&(Wc|=f),ys===4&&Wo(a,Vs)),Dr(a,w),f===1&&Tn===0&&(u.mode&1)===0&&(ua=cn()+500,qu&&Qi()))}function Dr(a,u){var f=a.callbackNode;vs(a,u);var w=Bi(a,a===Is?Vs:0);if(w===0)f!==null&&fn(f),a.callbackNode=null,a.callbackPriority=0;else if(u=w&-w,a.callbackPriority!==u){if(f!=null&&fn(f),u===1)a.tag===0?Vu(uh.bind(null,a)):or(uh.bind(null,a)),Zm(function(){(Tn&6)===0&&Qi()}),f=null;else{switch($a(w)){case 1:f=As;break;case 4:f=ws;break;case 16:f=_r;break;case 536870912:f=Nt;break;default:f=_r}f=ye(f,O_.bind(null,a))}a.callbackPriority=u,a.callbackNode=f}}function O_(a,u){if(Bo=-1,hd=0,(Tn&6)!==0)throw Error(n(327));var f=a.callbackNode;if(F()&&a.callbackNode!==f)return null;var w=Bi(a,a===Is?Vs:0);if(w===0)return null;if((w&30)!==0||(w&a.expiredLanes)!==0||u)u=Kc(a,w);else{u=w;var j=Tn;Tn|=2;var C=fh();(Is!==a||Vs!==u)&&(ho=null,ua=cn()+500,ma(a,u));do try{F_();break}catch(ie){dh(a,ie)}while(!0);zf(),co.current=C,Tn=j,Es!==null?u=0:(Is=null,Vs=0,u=ys)}if(u!==0){if(u===2&&(j=si(a),j!==0&&(w=j,u=md(a,j))),u===1)throw f=Wl,ma(a,0),Wo(a,w),Dr(a,cn()),f;if(u===6)Wo(a,w);else{if(j=a.current.alternate,(w&30)===0&&!P_(j)&&(u=Kc(a,w),u===2&&(C=si(a),C!==0&&(w=C,u=md(a,C))),u===1))throw f=Wl,ma(a,0),Wo(a,w),Dr(a,cn()),f;switch(a.finishedWork=j,a.finishedLanes=w,u){case 0:case 1:throw Error(n(345));case 2:b(a,Ms,ho);break;case 3:if(Wo(a,w),(w&130023424)===w&&(u=Vc+500-cn(),10<u)){if(Bi(a,0)!==0)break;if(j=a.suspendedLanes,(j&w)!==w){$r(),a.pingedLanes|=a.suspendedLanes&j;break}a.timeoutHandle=Af(b.bind(null,a,Ms,ho),u);break}b(a,Ms,ho);break;case 4:if(Wo(a,w),(w&4194240)===w)break;for(u=a.eventTimes,j=-1;0<w;){var q=31-sr(w);C=1<<q,q=u[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*oy(w/1960))-w,10<w){a.timeoutHandle=Af(b.bind(null,a,Ms,ho),w);break}b(a,Ms,ho);break;case 5:b(a,Ms,ho);break;default:throw Error(n(329))}}}return Dr(a,cn()),a.callbackNode===f?O_.bind(null,a):null}function md(a,u){var f=qc;return a.current.memoizedState.isDehydrated&&(ma(a,u).flags|=256),a=Kc(a,u),a!==2&&(u=Ms,Ms=f,u!==null&&ch(u)),a}function ch(a){Ms===null?Ms=a:Ms.push.apply(Ms,a)}function P_(a){for(var u=a;;){if(u.flags&16384){var f=u.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(!wr(C(),j))return!1}catch{return!1}}}if(f=u.child,u.subtreeFlags&16384&&f!==null)f.return=u,u=f;else{if(u===a)break;for(;u.sibling===null;){if(u.return===null||u.return===a)return!0;u=u.return}u.sibling.return=u.return,u=u.sibling}}return!0}function Wo(a,u){for(u&=~fo,u&=~Wc,a.suspendedLanes|=u,a.pingedLanes&=~u,a=a.expirationTimes;0<u;){var f=31-sr(u),w=1<<f;a[f]=-1,u&=~w}}function uh(a){if((Tn&6)!==0)throw Error(n(327));F();var u=Bi(a,0);if((u&1)===0)return Dr(a,cn()),null;var f=Kc(a,u);if(a.tag!==0&&f===2){var w=si(a);w!==0&&(u=w,f=md(a,w))}if(f===1)throw f=Wl,ma(a,0),Wo(a,u),Dr(a,cn()),f;if(f===6)throw Error(n(345));return a.finishedWork=a.current.alternate,a.finishedLanes=u,b(a,Ms,ho),Dr(a,cn()),null}function _d(a,u){var f=Tn;Tn|=1;try{return a(u)}finally{Tn=f,Tn===0&&(ua=cn()+500,qu&&Qi())}}function ha(a){da!==null&&da.tag===0&&(Tn&6)===0&&F();var u=Tn;Tn|=1;var f=Zr.transition,w=In;try{if(Zr.transition=null,In=1,a)return a()}finally{In=w,Zr.transition=f,Tn=u,(Tn&6)===0&&Qi()}}function pd(){Nr=uo.current,Pn(uo)}function ma(a,u){a.finishedWork=null,a.finishedLanes=0;var f=a.timeoutHandle;if(f!==-1&&(a.timeoutHandle=-1,Ym(f)),Es!==null)for(f=Es.return;f!==null;){var w=f;switch(Ku(w),w.tag){case 1:w=w.type.childContextTypes,w!=null&&Lo();break;case 3:di(),Pn(br),Pn(Ts),Qu();break;case 5:Ol(w);break;case 4:di();break;case 13:Pn(ps);break;case 19:Pn(ps);break;case 10:Bf(w.type._context);break;case 22:case 23:pd()}f=f.return}if(Is=a,Es=a=lt(a.current,null),Vs=Nr=u,ys=0,Wl=null,fo=Wc=ca=0,Ms=qc=null,so!==null){for(u=0;u<so.length;u++)if(f=so[u],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}so=null}return a}function dh(a,u){do{var f=Es;try{if(zf(),Pl.current=Fl,Ac){for(var w=ls.memoizedState;w!==null;){var j=w.queue;j!==null&&(j.pending=null),w=w.next}Ac=!1}if(Qn=0,Dn=$s=ls=null,Do=!1,qa=0,ah.current=null,f===null||f.return===null){ys=1,Wl=u,Es=null;break}e:{var C=a,q=f.return,ie=f,ue=u;if(u=Vs,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=cr(q);if(kt!==null){kt.flags&=-257,Ws(kt,q,ie,C,u),kt.mode&1&&oa(C,Te,u),u=kt,ue=Te;var $t=u.updateQueue;if($t===null){var Tt=new Set;Tt.add(ue),u.updateQueue=Tt}else $t.add(ue);break e}else{if((u&1)===0){oa(C,Te,u),gd();break e}ue=Error(n(426))}}else if(Zn&&ie.mode&1){var Os=cr(q);if(Os!==null){(Os.flags&65536)===0&&(Os.flags|=256),Ws(Os,q,ie,C,u),If(Va(ue,ie));break e}}C=ue=Va(ue,ie),ys!==4&&(ys=2),qc===null?qc=[C]:qc.push(C),C=q;do{switch(C.tag){case 3:C.flags|=65536,u&=-u,C.lanes|=u;var ve=Pc(C,ue,u);i_(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"&&(pi===null||!pi.has(Ne)))){C.flags|=65536,u&=-u,C.lanes|=u;var it=w_(C,ie,u);i_(C,it);break e}}C=C.return}while(C!==null)}mh(f)}catch(Lt){u=Lt,Es===f&&f!==null&&(Es=f=f.return);continue}break}while(!0)}function fh(){var a=co.current;return co.current=Fl,a===null?Fl:a}function gd(){(ys===0||ys===3||ys===2)&&(ys=4),Is===null||(ca&268435455)===0&&(Wc&268435455)===0||Wo(Is,Vs)}function Kc(a,u){var f=Tn;Tn|=2;var w=fh();(Is!==a||Vs!==u)&&(ho=null,ma(a,u));do try{D_();break}catch(j){dh(a,j)}while(!0);if(zf(),Tn=f,co.current=w,Es!==null)throw Error(n(261));return Is=null,Vs=0,ys}function D_(){for(;Es!==null;)hh(Es)}function F_(){for(;Es!==null&&!Xe();)hh(Es)}function hh(a){var u=ke(a.alternate,a,Nr);a.memoizedProps=a.pendingProps,u===null?mh(a):Es=u,ah.current=null}function mh(a){var u=a;do{var f=u.alternate;if(a=u.return,(u.flags&32768)===0){if(f=sh(f,u,Nr),f!==null){Es=f;return}}else{if(f=$_(f,u),f!==null){f.flags&=32767,Es=f;return}if(a!==null)a.flags|=32768,a.subtreeFlags=0,a.deletions=null;else{ys=6,Es=null;return}}if(u=u.sibling,u!==null){Es=u;return}Es=u=a}while(u!==null);ys===0&&(ys=5)}function b(a,u,f){var w=In,j=Zr.transition;try{Zr.transition=null,In=1,T(a,u,f,w)}finally{Zr.transition=j,In=w}return null}function T(a,u,f,w){do F();while(da!==null);if((Tn&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(ii(a,C),a===Is&&(Es=Is=null,Vs=0),(f.subtreeFlags&2064)===0&&(f.flags&2064)===0||mo||(mo=!0,ye(_r,function(){return F(),null})),C=(f.flags&15990)!==0,(f.subtreeFlags&15990)!==0||C){C=Zr.transition,Zr.transition=null;var q=In;In=1;var ie=Tn;Tn|=4,ah.current=null,C_(a,f),gs(f,a),Hm(Ef),rr=!!Fu,Ef=Fu=null,a.current=f,M_(f),nn(),Tn=ie,In=q,Zr.transition=C}else a.current=f;if(mo&&(mo=!1,da=a,fa=j),C=a.pendingLanes,C===0&&(pi=null),$i(f.stateNode),Dr(a,cn()),u!==null)for(w=a.onRecoverableError,f=0;f<u.length;f++)j=u[f],w(j.value,{componentStack:j.stack,digest:j.digest});if(Hc)throw Hc=!1,a=lh,lh=null,a;return(fa&1)!==0&&a.tag!==0&&F(),C=a.pendingLanes,(C&1)!==0?a===ql?Gc++:(Gc=0,ql=a):Gc=0,Qi(),null}function F(){if(da!==null){var a=$a(fa),u=Zr.transition,f=In;try{if(Zr.transition=null,In=16>a?16:a,da===null)var w=!1;else{if(a=da,da=null,fa=0,(Tn&6)!==0)throw Error(n(331));var j=Tn;for(Tn|=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:lo(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(E_(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 Tt=$t.child;if(Tt!==null){$t.child=null;do{var Os=Tt.sibling;Tt.sibling=null,Tt=Os}while(Tt!==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:lo(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:Bc(9,ie)}}catch(Lt){Z(ie,ie.return,Lt)}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(Tn=j,Qi(),nr&&typeof nr.onPostCommitFiberRoot=="function")try{nr.onPostCommitFiberRoot(zn,a)}catch{}w=!0}return w}finally{In=f,Zr.transition=u}}return!1}function B(a,u,f){u=Va(f,u),u=Pc(a,u,1),a=Xr(a,u,1),u=$r(),a!==null&&(Ss(a,1,u),Dr(a,u))}function Z(a,u,f){if(a.tag===3)B(a,a,f);else for(;u!==null;){if(u.tag===3){B(u,a,f);break}else if(u.tag===1){var w=u.stateNode;if(typeof u.type.getDerivedStateFromError=="function"||typeof w.componentDidCatch=="function"&&(pi===null||!pi.has(w))){a=Va(f,a),a=w_(u,a,1),u=Xr(u,a,1),a=$r(),u!==null&&(Ss(u,1,a),Dr(u,a));break}}u=u.return}}function X(a,u,f){var w=a.pingCache;w!==null&&w.delete(u),u=$r(),a.pingedLanes|=a.suspendedLanes&f,Is===a&&(Vs&f)===f&&(ys===4||ys===3&&(Vs&130023424)===Vs&&500>cn()-Vc?ma(a,0):fo|=f),Dr(a,u)}function ee(a,u){u===0&&((a.mode&1)===0?u=1:(u=pr,pr<<=1,(pr&130023424)===0&&(pr=4194304)));var f=$r();a=un(a,u),a!==null&&(Ss(a,u,f),Dr(a,f))}function oe(a){var u=a.memoizedState,f=0;u!==null&&(f=u.retryLane),ee(a,f)}function Ge(a,u){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(u),ee(a,f)}var ke;ke=function(a,u,f){if(a!==null)if(a.memoizedProps!==u.pendingProps||br.current)Cs=!0;else{if((a.lanes&f)===0&&(u.flags&128)===0)return Cs=!1,ry(a,u,f);Cs=(a.flags&131072)!==0}else Cs=!1,Zn&&(u.flags&1048576)!==0&&Rf(u,Hu,u.index);switch(u.lanes=0,u.tag){case 2:var w=u.type;Bl(a,u),a=u.pendingProps;var j=Zi(u,Ts.current);Ua(u,f),j=Vf(null,u,w,a,j,f);var C=Hf();return u.flags|=1,typeof j=="object"&&j!==null&&typeof j.render=="function"&&j.$$typeof===void 0?(u.tag=1,u.memoizedState=null,u.updateQueue=null,ir(w)?(C=!0,Cl(u)):C=!1,u.memoizedState=j.state!==null&&j.state!==void 0?j.state:null,Nc(u),j.updater=id,u.stateNode=j,j._reactInternals=u,eh(u,w,a,f),u=ad(null,u,w,!0,C,f)):(u.tag=0,Zn&&C&&Gu(u),xs(null,u,j,f),u=u.child),u;case 16:w=u.elementType;e:{switch(Bl(a,u),a=u.pendingProps,j=w._init,w=j(w._payload),u.type=w,j=u.tag=pt(w),a=mi(w,a),j){case 0:u=nh(null,u,w,a,f);break e;case 1:u=b_(null,u,w,a,f);break e;case 11:u=_i(null,u,w,a,f);break e;case 14:u=v_(null,u,w,mi(w.type,a),f);break e}throw Error(n(306,w,""))}return u;case 0:return w=u.type,j=u.pendingProps,j=u.elementType===w?j:mi(w,j),nh(a,u,w,j,f);case 1:return w=u.type,j=u.pendingProps,j=u.elementType===w?j:mi(w,j),b_(a,u,w,j,f);case 3:e:{if(aa(u),a===null)throw Error(n(387));w=u.pendingProps,C=u.memoizedState,j=C.element,Uf(a,u),Il(u,w,null,f);var q=u.memoizedState;if(w=q.element,C.isDehydrated)if(C={element:w,isDehydrated:!1,cache:q.cache,pendingSuspenseBoundaries:q.pendingSuspenseBoundaries,transitions:q.transitions},u.updateQueue.baseState=C,u.memoizedState=C,u.flags&256){j=Va(Error(n(423)),u),u=zl(a,u,w,f,j);break e}else if(w!==j){j=Va(Error(n(424)),u),u=zl(a,u,w,f,j);break e}else for(Or=ta(u.stateNode.containerInfo.firstChild),Jr=u,Zn=!0,Mi=null,f=Df(u,null,w,f),u.child=f;f;)f.flags=f.flags&-3|4096,f=f.sibling;else{if(Ba(),w===j){u=zo(a,u,f);break e}xs(a,u,w,f)}u=u.child}return u;case 5:return fi(u),a===null&&Sc(u),w=u.type,j=u.pendingProps,C=a!==null?a.memoizedProps:null,q=j.children,zu(w,j)?q=null:C!==null&&zu(w,C)&&(u.flags|=32),od(a,u),xs(a,u,q,f),u.child;case 6:return a===null&&Sc(u),null;case 13:return k_(a,u,f);case 4:return Xu(u,u.stateNode.containerInfo),w=u.pendingProps,a===null?u.child=Oo(u,null,w,f):xs(a,u,w,f),u.child;case 11:return w=u.type,j=u.pendingProps,j=u.elementType===w?j:mi(w,j),_i(a,u,w,j,f);case 7:return xs(a,u,u.pendingProps,f),u.child;case 8:return xs(a,u,u.pendingProps.children,f),u.child;case 12:return xs(a,u,u.pendingProps.children,f),u.child;case 10:e:{if(w=u.type._context,j=u.pendingProps,C=u.memoizedProps,q=j.value,Xn(Po,w._currentValue),w._currentValue=q,C!==null)if(wr(C.value,q)){if(C.children===j.children&&!br.current){u=zo(a,u,f);break e}}else for(C=u.child,C!==null&&(C.return=u);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=Yr(-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),Ju(C.return,f,u),ie.lanes|=f;break}ue=ue.next}}else if(C.tag===10)q=C.type===u.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),Ju(q,f,u),q=C.sibling}else q=C.child;if(q!==null)q.return=C;else for(q=C;q!==null;){if(q===u){q=null;break}if(C=q.sibling,C!==null){C.return=q.return,q=C;break}q=q.return}C=q}xs(a,u,j.children,f),u=u.child}return u;case 9:return j=u.type,w=u.pendingProps.children,Ua(u,f),j=ui(j),w=w(j),u.flags|=1,xs(a,u,w,f),u.child;case 14:return w=u.type,j=mi(w,u.pendingProps),j=mi(w.type,j),v_(a,u,w,j,f);case 15:return Dc(a,u,u.type,u.pendingProps,f);case 17:return w=u.type,j=u.pendingProps,j=u.elementType===w?j:mi(w,j),Bl(a,u),u.tag=1,ir(w)?(a=!0,Cl(u)):a=!1,Ua(u,f),g_(u,w,j),eh(u,w,j,f),ad(null,u,w,!0,a,f);case 19:return j_(a,u,f);case 22:return x_(a,u,f)}throw Error(n(156,u.tag))};function ye(a,u){return Fn(a,u)}function Fe(a,u,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=u,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,u,f,w){return new Fe(a,u,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===V)return 11;if(a===O)return 14}return 2}function lt(a,u){var f=a.alternate;return f===null?(f=Pe(a.tag,u,a.key,a.mode),f.elementType=a.elementType,f.type=a.type,f.stateNode=a.stateNode,f.alternate=a,a.alternate=f):(f.pendingProps=u,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,u=a.dependencies,f.dependencies=u===null?null:{lanes:u.lanes,firstContext:u.firstContext},f.sibling=a.sibling,f.index=a.index,f.ref=a.ref,f}function xn(a,u,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,u);case I:q=8,j|=8;break;case W:return a=Pe(12,f,u,j|2),a.elementType=W,a.lanes=C,a;case M:return a=Pe(13,f,u,j),a.elementType=M,a.lanes=C,a;case A:return a=Pe(19,f,u,j),a.elementType=A,a.lanes=C,a;case H:return ft(f,j,C,u);default:if(typeof a=="object"&&a!==null)switch(a.$$typeof){case G:q=10;break e;case K:q=9;break e;case V: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 u=Pe(q,f,u,j),u.elementType=a,u.type=w,u.lanes=C,u}function qt(a,u,f,w){return a=Pe(7,a,w,u),a.lanes=f,a}function ft(a,u,f,w){return a=Pe(22,a,w,u),a.elementType=H,a.lanes=f,a.stateNode={isHidden:!1},a}function en(a,u,f){return a=Pe(6,a,null,u),a.lanes=f,a}function Yn(a,u,f){return u=Pe(4,a.children!==null?a.children:[],a.key,u),u.lanes=f,u.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation},u}function us(a,u,f,w,j){this.tag=u,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=ri(0),this.expirationTimes=ri(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ri(0),this.identifierPrefix=w,this.onRecoverableError=j,this.mutableSourceEagerHydrationData=null}function dr(a,u,f,w,j,C,q,ie,ue){return a=new us(a,u,f,ie,ue),u===1?(u=1,C===!0&&(u|=8)):u=0,C=Pe(3,null,null,u),a.current=C,C.stateNode=a,C.memoizedState={element:w,isDehydrated:f,cache:null,transitions:null,pendingSuspenseBoundaries:null},Nc(C),a}function yi(a,u,f){var w=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:D,key:w==null?null:""+w,children:a,containerInfo:u,implementation:f}}function wi(a){if(!a)return li;a=a._reactInternals;e:{if(sn(a)!==a||a.tag!==1)throw Error(n(170));var u=a;do{switch(u.tag){case 3:u=u.stateNode.context;break e;case 1:if(ir(u.type)){u=u.stateNode.__reactInternalMemoizedMergedChildContext;break e}}u=u.return}while(u!==null);throw Error(n(171))}if(a.tag===1){var f=a.type;if(ir(f))return e_(a,f,u)}return u}function Vl(a,u,f,w,j,C,q,ie,ue){return a=dr(f,w,!0,a,j,C,q,ie,ue),a.context=wi(null),f=a.current,w=$r(),j=Uo(f),C=Yr(w,j),C.callback=u??null,Xr(f,C,j),a.current.lanes=j,Ss(a,j,w),Dr(a,w),a}function z_(a,u,f,w){var j=u.current,C=$r(),q=Uo(j);return f=wi(f),u.context===null?u.context=f:u.pendingContext=f,u=Yr(C,q),u.payload={element:a},w=w===void 0?null:w,w!==null&&(u.callback=w),a=Xr(j,u,q),a!==null&&(gi(a,j,q,C),rn(a,j,q)),q}function B_(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 Yx(a,u){if(a=a.memoizedState,a!==null&&a.dehydrated!==null){var f=a.retryLane;a.retryLane=f!==0&&f<u?f:u}}function ay(a,u){Yx(a,u),(a=a.alternate)&&Yx(a,u)}function QC(){return null}var Xx=typeof reportError=="function"?reportError:function(a){console.error(a)};function ly(a){this._internalRoot=a}U_.prototype.render=ly.prototype.render=function(a){var u=this._internalRoot;if(u===null)throw Error(n(409));z_(a,u,null,null)},U_.prototype.unmount=ly.prototype.unmount=function(){var a=this._internalRoot;if(a!==null){this._internalRoot=null;var u=a.containerInfo;ha(function(){z_(null,a,null,null)}),u[Ti]=null}};function U_(a){this._internalRoot=a}U_.prototype.unstable_scheduleHydration=function(a){if(a){var u=fc();a={blockedOn:null,target:a,priority:u};for(var f=0;f<Mr.length&&u!==0&&u<Mr[f].priority;f++);Mr.splice(f,0,a),f===0&&Ci(a)}};function cy(a){return!(!a||a.nodeType!==1&&a.nodeType!==9&&a.nodeType!==11)}function W_(a){return!(!a||a.nodeType!==1&&a.nodeType!==9&&a.nodeType!==11&&(a.nodeType!==8||a.nodeValue!==" react-mount-point-unstable "))}function Zx(){}function eE(a,u,f,w,j){if(j){if(typeof w=="function"){var C=w;w=function(){var Te=B_(q);C.call(Te)}}var q=Vl(u,w,a,0,null,!1,!1,"",Zx);return a._reactRootContainer=q,a[Ti]=q.current,Ei(a.nodeType===8?a.parentNode:a),ha(),q}for(;j=a.lastChild;)a.removeChild(j);if(typeof w=="function"){var ie=w;w=function(){var Te=B_(ue);ie.call(Te)}}var ue=dr(a,0,!1,null,null,!1,!1,"",Zx);return a._reactRootContainer=ue,a[Ti]=ue.current,Ei(a.nodeType===8?a.parentNode:a),ha(function(){z_(u,ue,f,w)}),ue}function q_(a,u,f,w,j){var C=f._reactRootContainer;if(C){var q=C;if(typeof j=="function"){var ie=j;j=function(){var ue=B_(q);ie.call(ue)}}z_(u,q,a,j)}else q=eE(f,u,a,j,w);return B_(q)}fl=function(a){switch(a.tag){case 3:var u=a.stateNode;if(u.current.memoizedState.isDehydrated){var f=Rs(u.pendingLanes);f!==0&&(Ui(u,f|1),Dr(u,cn()),(Tn&6)===0&&(ua=cn()+500,Qi()))}break;case 13:ha(function(){var w=un(a,1);if(w!==null){var j=$r();gi(w,a,1,j)}}),ay(a,1)}},hl=function(a){if(a.tag===13){var u=un(a,134217728);if(u!==null){var f=$r();gi(u,a,134217728,f)}ay(a,134217728)}},Tr=function(a){if(a.tag===13){var u=Uo(a),f=un(a,u);if(f!==null){var w=$r();gi(f,a,u,w)}ay(a,u)}},fc=function(){return In},Wi=function(a,u){var f=In;try{return In=a,u()}finally{In=f}},Ks=function(a,u,f){switch(u){case"input":if(ct(a,f),u=f.name,f.type==="radio"&&u!=null){for(f=a;f.parentNode;)f=f.parentNode;for(f=f.querySelectorAll("input[name="+JSON.stringify(""+u)+'][type="radio"]'),u=0;u<f.length;u++){var w=f[u];if(w!==a&&w.form===a.form){var j=To(w);if(!j)throw Error(n(90));mt(w),ct(w,j)}}}break;case"textarea":_e(a,f);break;case"select":u=f.value,u!=null&&Le(a,!!f.multiple,u,!1)}},fe=_d,Ce=ha;var tE={usingClientEntryPoint:!1,Events:[na,$l,To,gt,re,_d]},_h={findFiberByHostInstance:Fa,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},nE={bundleType:_h.bundleType,version:_h.version,rendererPackageName:_h.rendererPackageName,rendererConfig:_h.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=Qt(a),a===null?null:a.stateNode},findFiberByHostInstance:_h.findFiberByHostInstance||QC,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 V_=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!V_.isDisabled&&V_.supportsFiber)try{zn=V_.inject(nE),nr=V_}catch{}}return vi.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=tE,vi.createPortal=function(a,u){var f=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!cy(u))throw Error(n(200));return yi(a,u,null,f)},vi.createRoot=function(a,u){if(!cy(a))throw Error(n(299));var f=!1,w="",j=Xx;return u!=null&&(u.unstable_strictMode===!0&&(f=!0),u.identifierPrefix!==void 0&&(w=u.identifierPrefix),u.onRecoverableError!==void 0&&(j=u.onRecoverableError)),u=dr(a,1,!1,null,null,f,!1,w,j),a[Ti]=u.current,Ei(a.nodeType===8?a.parentNode:a),new ly(u)},vi.findDOMNode=function(a){if(a==null)return null;if(a.nodeType===1)return a;var u=a._reactInternals;if(u===void 0)throw typeof a.render=="function"?Error(n(188)):(a=Object.keys(a).join(","),Error(n(268,a)));return a=Qt(u),a=a===null?null:a.stateNode,a},vi.flushSync=function(a){return ha(a)},vi.hydrate=function(a,u,f){if(!W_(u))throw Error(n(200));return q_(null,a,u,!0,f)},vi.hydrateRoot=function(a,u,f){if(!cy(a))throw Error(n(405));var w=f!=null&&f.hydratedSources||null,j=!1,C="",q=Xx;if(f!=null&&(f.unstable_strictMode===!0&&(j=!0),f.identifierPrefix!==void 0&&(C=f.identifierPrefix),f.onRecoverableError!==void 0&&(q=f.onRecoverableError)),u=Vl(u,null,a,1,f??null,j,!1,C,q),a[Ti]=u.current,Ei(a),w)for(a=0;a<w.length;a++)f=w[a],j=f._getVersion,j=j(f._source),u.mutableSourceEagerHydrationData==null?u.mutableSourceEagerHydrationData=[f,j]:u.mutableSourceEagerHydrationData.push(f,j);return new U_(u)},vi.render=function(a,u,f){if(!W_(u))throw Error(n(200));return q_(null,a,u,!1,f)},vi.unmountComponentAtNode=function(a){if(!W_(a))throw Error(n(40));return a._reactRootContainer?(ha(function(){q_(null,null,a,!1,function(){a._reactRootContainer=null,a[Ti]=null})}),!0):!1},vi.unstable_batchedUpdates=_d,vi.unstable_renderSubtreeIntoContainer=function(a,u,f,w){if(!W_(f))throw Error(n(200));if(a==null||a._reactInternals===void 0)throw Error(n(38));return q_(a,u,f,!1,w)},vi.version="18.3.1-next-f1338f8080-20240426",vi}var ob;function qj(){if(ob)return fy.exports;ob=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(),fy.exports=dE(),fy.exports}var ab;function fE(){if(ab)return H_;ab=1;var e=qj();return H_.createRoot=e.createRoot,H_.hydrateRoot=e.hydrateRoot,H_}var hE=fE();const mE=Gv(hE),Vj=[{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"]}];Vj.map(e=>({id:e.id,label:e.label}));function _E(e){return`theme-${String(e||"").trim()||"dark"}`}function lb(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(_E(e))}catch{}}const Tw=[{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}],Mw=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function pE(e){const t=String(e).trim();return Tw.find(n=>n.id===t)||Tw[1]}function gE(e){const t=String(e).trim();return Mw.find(n=>n.id===t)||Mw[1]}function cb(e){try{const t=document.documentElement,n=pE(e.font_scale||"md"),r=gE(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(r.density))}catch{}}const _y={sm:"(max-width: 767.98px)",md:"(max-width: 1023.98px)",short:"(max-height: 500px)"};function yE(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function ub(e){const[t,n]=p.useState(()=>yE(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 gh=null;function wE(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 vE(){if(gh)return gh;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:c}=wE(window.innerHeight,{height:e.height,offsetTop:e.offsetTop,scale:e.scale||1});t.style.setProperty("--vv-height",`${o}px`),t.style.setProperty("--keyboard-inset",`${c}px`)},i=()=>{n||(n=window.requestAnimationFrame(r))};return r(),e.addEventListener("resize",i),e.addEventListener("scroll",i),window.addEventListener("orientationchange",i),gh=()=>{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"),gh=null},gh}var bg=qj();function yd(...e){return e.filter(Boolean).join(" ")}function Ur({value:e,options:t,placeholder:n="Select…",disabled:r=!1,loading:i=!1,searchable:o=!0,searchPlaceholder:c="Search…",allowCustom:l=!1,clearable:d=!1,minPopoverWidth:h=240,variant:m="panel",className:_,triggerClassName:g,ariaLabel:y,id:x,includeValueOption:k=!1,onOpen:v,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(v),G=p.useId(),K=x||`af-select-${G.replace(/[^a-zA-Z0-9_-]/g,"")}`,V=`${K}-listbox`,[M,A]=p.useState(!1),[O,L]=p.useState(""),[H,J]=p.useState(0),[U,te]=p.useState("bottom"),[z,ne]=p.useState({left:0,top:0,width:0});p.useEffect(()=>{W.current=v},[v]);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 Ve=$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[H];return Q&&Ve(Q.value),!0}return!1},nt=$e=>{if(!r){if(M){if(mt($e))return;if($e.key===" "&&!o){$e.preventDefault();const Le=ae[H];Le&&Ve(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,He=je!=null&&je.disabled?je.reason||"Unavailable":"",ct=M&&ae.length>0?`${K}-opt-${H}`:void 0,Qe=s.jsx("span",{className:yd("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:yd("af-select",m==="pin"?"af-select--pin":"af-select--panel",_),children:[s.jsxs("button",{ref:D,id:K,type:"button",className:yd("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?V:void 0,"aria-activedescendant":o?void 0:ct,"aria-label":y,children:[Dt,s.jsx("span",{className:yd("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?bg.createPortal(s.jsxs("div",{ref:R,className:yd("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:c,onKeyDown:mt,role:"combobox","aria-expanded":!0,"aria-controls":V,"aria-activedescendant":ct,"aria-invalid":!!He,"aria-describedby":He?`${K}-custom-error`:void 0}),He?s.jsx("div",{id:`${K}-custom-error`,className:"af-select-custom-error",role:"alert",children:He}):null]}):null,s.jsx("div",{className:"af-select-options",role:"listbox",id:V,"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===H,_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:yd("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:()=>Ve($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 xE(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 bE(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 Rw="Provided by connected pin";function Hj(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"),c=String(e.modelLabel||"Model"),l=String(e.providerPlaceholder||"(select)"),d=String(e.modelPlaceholder||"(select)"),h=String(e.provider||"").trim(),m=String(e.model||"").trim(),_=xE(e.providers),g=bE(e.models),y=typeof e.markSaved=="object"?e.markSaved:null,x=(S,P,D,R)=>e.markSaved&&!D&&!R&&(!y||y[P]===S)?`${S} (saved)`:S,k=t||!!e.loadingProviders,v=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:x(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:x(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:Rw}),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(Ur,{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:c}),e.modelPinned?E("model",m):s.jsx(Ur,{value:m,options:$,placeholder:r?i:d,disabled:v,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:c,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 kE(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 jE(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 db(e){const t=kE(e);return t===!1?"off":t?String(t.num_draft_tokens):""}function SE(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 NE(e){const t=jE(e.capabilities),n=db(e.value),r=(t==null?void 0:t.supported_depths.map(String))||[],i=db(t==null?void 0:t.default),o=e.inheritLabel||"Workflow / Gateway default",c=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(Ur,{ariaLabel:"MTP depth",value:n,placeholder:c,disabled:e.disabled||e.loading,options:[{value:"",label:c},{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(SE(d))}),l&&!e.hideNote?s.jsx("div",{role:"status",className:"af-pmp__hint",children:l}):null]})}const Xh="api/gateway",vm="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?`${Xh}/${t}`:Xh}function Kv(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 $E(e){const t=String(e||""),n=`/${Xh}/`;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 CE(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 EE(e,t="Gateway default"){const n=CE(e);return n?`${t} · ${n}`:t}const AE="The gateway does not say which reasoning levels this model supports.",TE="Set anyway",ME="Reasoning and MTP choices appear when the gateway can describe the selected model.",RE="Reasoning choices appear when the gateway can describe the selected model.";function Gj(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||{},c=!!(o.provider||o.model),[l,d]=p.useState(!r),h=i||c||!(r&&!l),m=r&&(i||c||!l),_=p.useRef(r);p.useEffect(()=>{r&&!_.current&&d(!1),_.current=r},[r]);const[g,y]=p.useState([]),[x,k]=p.useState(!1),[v,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,V]=p.useState({status:"idle",value:null,message:""}),M=e.fetchGatewayDefault;p.useEffect(()=>{if(!M||t)return;let Le=!0;const ce=Q=>V(_e=>JSON.stringify(_e)===JSON.stringify(Q)?_e:Q);return V(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 H=String(n.model||"").trim(),J=e.defaultModeLabel||"Gateway default",U=K.status==="none"?`${J} · none configured`:EE(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=H||(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 Ve=e.inheritLabel||"Workflow / Gateway default",mt=m&&(A!=null&&A.reasoning)?`${Ve} (${A.reasoning})`:Ve,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",He=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"&&He&&(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||He)&&(Qe.length>0||ze==="unknown"&&He);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||c?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(Hj,{provider:L,model:H,providers:g,models:$,modelDisplayNames:S,markSaved:O.current,providerPinned:o.provider,modelPinned:o.model,disabled:t,loadingProviders:x,loadingModels:D,providerError:v||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:Rw})]}):nt&&$e?s.jsxs("div",{className:"af-pmp__reasoning","data-reasoning-state":ze,children:[s.jsx("label",{children:e.reasoningLabel||"Reasoning effort"}),s.jsx(Ur,{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"&&He?s.jsxs("div",{className:"af-pmp__hint","data-reasoning-unknown":"",children:[AE," ",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:""})}})," ",TE]})]}):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:Rw})]}):nt&&e.enableSpeculation?s.jsx(NE,{value:n.speculation,inheritLabel:Ve,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?ME:RE,s.jsxs("details",{className:"af-pmp__details",children:[s.jsx("summary",{children:"Technical details"}),s.jsx("span",{children:de.error})]})]}):null]})}function fb(...e){return e.filter(Boolean).join(" ")}function LE({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:c="",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:x=!1,onTokenChange:k,onShowTokenChange:v,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:V=!1,error:M,message:A,className:O,onSubmit:L,onClose:H,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:fb("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:fb("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:c,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:x?"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:()=>v==null?void 0:v(!x),disabled:U,children:x?"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:H,disabled:U,children:W}):null,V?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 IE(e){return e==="light"?"Light":"Dark"}function OE(e){const t=e.themes&&e.themes.length?e.themes:Vj,n=e.showSwatches!==!1,r=e.variant||"panel",i=p.useMemo(()=>{const c={};for(const l of t)c[l.id]=l;return c},[t]),o=p.useMemo(()=>t.map(c=>({value:c.id,label:c.label,group:IE(c.group)})),[t]);return s.jsx(Ur,{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:c=>e.onChange(String(c||"").trim()),renderValue:(c,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,x)=>s.jsx("span",{className:"af-theme-swatch",style:{background:y}},`${d}:${x}`))}):null]})},renderOption:(c,l)=>{const d=String(c.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:c.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 PE(e){const t=e.scales&&e.scales.length?e.scales:Tw,n=e.variant||"panel",r=p.useMemo(()=>t.map(i=>({value:i.id,label:i.label})),[t]);return s.jsx(Ur,{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 DE(e){const t=e.densities&&e.densities.length?e.densities:Mw,n=e.variant||"panel",r=p.useMemo(()=>t.map(i=>({value:i.id,label:i.label})),[t]);return s.jsx(Ur,{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 FE=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function zE(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,c=FE.has(e);return s.jsxs("svg",{width:t,height:t,viewBox:c?"0 0 16 16":"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:c?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,zE(e)]})}function BE(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function UE(e){return BE(e)?!e.checked:null}let WE=0;function Fi(e){const{label:t,checked:n,onChange:r,description:i,reasonVisible:o=!0,describedBy:c,hint:l,busy:d=!1,variant:h="inline",ariaLabel:m,className:_,id:g,action:y}=e,x=String(e.unavailableReason||"").trim(),k=!!x,v=c||(g?`${g}-reason`:k?`af-switch-reason-${++WE}`: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=UE({checked:n,unavailableReason:x,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?v:void 0,"aria-busy":d?"true":void 0,"aria-label":m,"aria-description":i?void 0:l,title:k?l?`${x}
41
+ ${l}`:x: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||c?E:s.jsxs("span",{className:h==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[E,s.jsx("span",{id:v,className:o?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:x})]})}function qE(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 c;return(c=e.onChange)==null?void 0:c.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 VE=150,Jv="data-af-tip";function HE(e,t,n,r=6,i=8){let o="top",c=e.top-r-t.height;if(c<i){const h=e.bottom+r;(h+t.height<=n.height-i||n.height-e.bottom>e.top)&&(c=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)),c=Math.max(i,Math.min(c,n.height-i-t.height)),{top:Math.round(c),left:Math.round(d),side:o}}let hb=0;function Kj(e){return e?String(e.getAttribute(Jv)||"").trim():""}function py(e,t){const n=e;if(!n||typeof n.closest!="function")return null;const r=n.closest(`[${Jv}]`);return!r||!t.contains(r)||!Kj(r)?null:r}function GE(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:VE;hb+=1;const o=n.createElement("div");o.className="af-tooltip",o.setAttribute("role","tooltip");const c=`af-tooltip-${hb}`;o.setAttribute("id",c),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},x=()=>{m&&clearTimeout(m),m=null},k=()=>{if(!l)return;const O=l.getBoundingClientRect(),L=o.getBoundingClientRect(),H=HE(O,{width:L.width,height:L.height},{width:r.innerWidth,height:r.innerHeight});o.style.top=`${H.top}px`,o.style.left=`${H.left}px`,o.setAttribute("data-side",H.side)},v=()=>{if(y(),x(),!l)return;String(l.getAttribute("aria-describedby")||"").split(/\s+/).includes(c)&&(g?l.setAttribute("aria-describedby",g):l.removeAttribute("aria-describedby")),g=null,l=null,o.hidden=!0,o.textContent=""},N=O=>{y(),x(),l&&l!==O&&v();const L=Kj(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!==c?J:null,O.setAttribute("aria-describedby",g?`${g} ${c}`:c)}k()},$=O=>{x(),l!==O&&d!==O&&(y(),d=O,h=setTimeout(()=>{const L=d;h=null,d=null,L&&N(L)},i))},E=()=>{y(),l&&(x(),m=setTimeout(v,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)){x();return}const H=py(O.target,e);H&&$(H)},D=O=>{const H=O.relatedTarget||null;if(!(H&&(o.contains(H)||l&&l.contains(H)||d&&d.contains(H)))){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=py(O.target,e);L&&S(L)&&$(L)},W=O=>{const L=py(O.target,e);L&&(L===l||L===d)&&v()},G=()=>{_=!1,v()},K=O=>{if(O.key==="Escape"||O.key==="Esc"){l?(O.preventDefault(),v()):y();return}!O.metaKey&&!O.ctrlKey&&!O.altKey&&(_=!0)},V=()=>v(),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",V,!0),r.addEventListener("resize",V);let A=!1;return()=>{A||(A=!0,v(),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",V,!0),r.removeEventListener("resize",V),o.parentNode&&o.parentNode.removeChild(o))}}const G_=new WeakMap;function KE(e){let t=G_.get(e);t||(t={count:0,release:GE(e)},G_.set(e,t)),t.count+=1;let n=!1;return()=>{if(n)return;n=!0;const r=G_.get(e);r&&(r.count-=1,r.count<=0&&(r.release(),G_.delete(e)))}}function sf(){p.useEffect(()=>{if(!(typeof document>"u"))return KE(document)},[])}function mb(e){sf();const t=Ee.Children.only(e.children),n=String(e.content||"").trim();return n?Ee.cloneElement(t,{[Jv]:n}):t}async function Lw(e=vm){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 JE(e,t=vm){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 Jj(e=vm){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 gy(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 Yj(e){var o,c;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=(c=t.principal)==null?void 0:c.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 YE(e){const t=e.connectionPath||vm,[n,r]=p.useState(!1),[i,o]=p.useState(!1),[c,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"),[x,k]=p.useState(""),[v,N]=p.useState(!1),[$,E]=p.useState(!0),[S,P]=p.useState(""),[D,R]=p.useState(""),I=p.useMemo(()=>Yj(c),[c]),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()&&_(gy(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(""),Lw(t).then(O=>{var H;W(O),typeof O.gateway_url=="string"&&O.gateway_url.trim()&&_(gy(O.gateway_url));const L=(H=O.gateway)==null?void 0:H.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=gy(m);_(M);const A=await JE({gateway_url:M,gateway_user_id:g,gateway_token:x,persist:$},t);W(A),k(""),h(!0),e.onClose()}catch(M){P(String((M==null?void 0:M.message)||M))}finally{o(!1)}},V=async()=>{o(!0),P(""),R("");try{await Jj(t),k("");const M=await Lw(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(LE,{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:x,tokenPlaceholder:c!=null&&c.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:v,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&&!!(c!=null&&c.has_session),onSignOut:V,error:S,message:D,onSubmit:K})})})}function Xj(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function XE(e){const t=e||{},n=t.connectionPath||vm,r=t.variant||"dismissable",i=p.useRef(t.onStatusChange);i.current=t.onStatusChange;const o=p.useRef(r);o.current=r;const c=p.useRef(!!t.autoOpenMidSession);c.current=!!t.autoOpenMidSession;const[l,d]=p.useState(null),[h,m]=p.useState("loading"),[_,g]=p.useState(!1),y=p.useRef(!1),x=p.useRef(!1),k=p.useRef("loading"),v=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=Xj(A);if(O)m("connected"),k.current="connected",y.current=!1,v.current="none",x.current||g(!1);else if(A!==null){const H=k.current;m("disconnected"),k.current="disconnected",H!=="disconnected"&&(v.current=N.current?"signout":H==="connected"?"mid":"boot");const J=o.current==="blocking"||v.current!=="mid"||c.current;!y.current&&J&&g(!0)}A!==null&&(x.current=O)},[]),S=p.useCallback(async()=>{const A=$.current;try{const O=await Lw(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 Jj(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)},[]),V=p.useCallback(()=>{const A=k.current;r==="blocking"&&A==="disconnected"||(A==="disconnected"&&(y.current=!0),g(!1))},[r]),M=p.useMemo(()=>({isOpen:_,onClose:V,blocking:r==="blocking"&&h!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:l,onStatusChange:E}),[_,V,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 ZE(){return globalThis.crypto}function QE(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 nl(){const e=ZE();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return QE(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function kg(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 e2(){return nl()}function t2(){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 n2(e){const t=e.commandsPath||wt("commands"),n=e2(),r=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),i=e.csrfToken!==void 0?[e.csrfToken]:t2();i.length===0&&i.push("");let o=null;for(const c of i){const l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...c?{"x-abstract-csrf":c}:{}},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 s2(e){const[t,n]=p.useState(""),[r,i]=p.useState({kind:"idle"}),o=p.useRef(!1),c=p.useRef(0);p.useEffect(()=>{c.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=c.current;i({kind:"sending"});try{const x=e.submit?await e.submit(e.runId,_):await n2({runId:e.runId,guidance:_,commandsPath:e.commandsPath});if(c.current!==g)return;if(!x.accepted&&!x.duplicate){i({kind:"error",detail:"The gateway did not accept this steer (accepted=false)."});return}i({kind:"queued",seq:x.seq,duplicate:x.duplicate}),n(""),(y=e.onSent)==null||y.call(e,{...x,guidance:_})}catch(x){c.current===g&&i({kind:"error",detail:String((x==null?void 0:x.message)||x)})}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 yy={neutral:"var(--text-secondary)",muted:"var(--text-muted)",accent:"var(--accent)",info:"var(--info)",success:"var(--success)",warning:"var(--warning)",error:"var(--error)"},r2=/^var\(--[a-z0-9-]+\)$/i;function i2(e,t){const n=e||"neutral";if(n==="custom"){const r=String(t||"").trim();return r2.test(r)?r:yy.neutral}return yy[n]||yy.neutral}function Zj(e,t,n){return[e,`${e}--${t.tone||"neutral"}`,t.size==="sm"?`${e}--sm`:"",n||"",t.className||""].filter(Boolean).join(" ")}function Qj(e){return{"--af-chip-hue":i2(e.tone,e.hue)}}function _b(e){return s.jsxs("span",{className:Zj("af-chip",e,e.onRemove?"af-chip--removable":""),style:Qj(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 o2(e){return s.jsx("button",{type:"button",className:Zj("af-chip",e,"af-chip--button"),style:Qj(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 a2='button:not(:disabled), [href], input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function l2(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(a2)||e)}function c2(){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}}function pb(e){return e==="auto"?"var(--af-topbar-h, 0px)":typeof e=="number"&&Number.isFinite(e)?e:0}function u2(e){const t=e.closeOnEscape!==!1,n=p.useRef(null);p.useEffect(()=>{if(!e.open||!t)return;const c=l=>{l.key!=="Escape"||l.defaultPrevented||(l.preventDefault(),e.onClose())};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[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 c=n.current;if(e.open){if(r.current=document.activeElement,c&&c.contains(document.activeElement))return;const m=window.setTimeout(()=>{var _;(_=l2(c,c2()))==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||c&&c.contains(d))&&((h=l.focus)==null||h.call(l,{preventScroll:!0}))},[e.open,i]),p.useEffect(()=>{const c=n.current;c&&(e.open?c.removeAttribute("inert"):c.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:pb(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:pb(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 d2(e,t,n,r=4,i=8){let o=e.bottom+r,c=!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,c=!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:c,leftward:d}}let gb=0;function f2(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")||(gb+=1,t.setAttribute("id",`af-menu-${gb}`)),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 c=!1;const l=()=>{if(!c)return;const E=e.getBoundingClientRect(),S=t.getBoundingClientRect(),P=d2(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=>{c||(c=!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=>{c&&(c=!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(),c?m(!0):h(0)},x=E=>{E.key==="ArrowDown"||(E.key==="Enter"||E.key===" ")&&!c?(E.preventDefault(),h(0)):E.key==="ArrowUp"&&(E.preventDefault(),h(-1))},k=E=>{if(!c||E.key!=="Escape"&&E.key!=="Esc")return;const S=E.target;S&&S!==e&&!t.contains(S)&&S!==r.body||(E.preventDefault(),m(!0))},v=E=>{if(!c)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",x),t.addEventListener("keydown",v),t.addEventListener("click",N);let $=!1;return()=>{$||($=!0,m(!1),e.removeEventListener("click",y),e.removeEventListener("keydown",x),t.removeEventListener("keydown",v),t.removeEventListener("click",N))}}function h2(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 f2(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 m2={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"},_2={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"}},p2={framework:m2,apps:_2},Wp=p2;function eS(){return{...Wp.framework}}function g2(){return Object.keys(Wp.apps).sort()}function y2(e,t){const n=Object.prototype.hasOwnProperty.call(Wp.apps,e)?Wp.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${g2().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 w2(e,t){try{const n=await e(wt("about"),{method:"GET",headers:{Accept:"application/json"},signal:t});if(!n.ok)return Hh(null,`HTTP ${n.status}`);const r=await n.json().catch(()=>null);return Hh(r)}catch(n){return Hh(null,String((n==null?void 0:n.message)||n||"request failed"))}}const v2={framework:null,frameworkNote:"checking…",gateway:null,gatewayNote:"checking…"};function Rd(e){return typeof e=="string"?e.trim():""}function Hh(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=Rd(n.abstractgateway),i=Rd(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 x2(e){const t=eS();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 b2(e){const t=e||{},n=Rd(t.framework),r=Rd(t.gateway);return[["AbstractFramework",n||Rd(t.frameworkNote)||"not reported"],["AbstractGateway",r||Rd(t.gatewayNote)||"not connected"]]}const k2='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function j2(e,t,n){if(e.key!=="Tab"||!t)return;const r=Array.from(t.querySelectorAll(k2));if(r.length===0){e.preventDefault();return}const i=r[0],o=r[r.length-1],c=!!n&&t.contains(n);e.shiftKey?(n===i||!c)&&(e.preventDefault(),o.focus()):(n===o||!c)&&(e.preventDefault(),i.focus())}function S2(e){const t=eS();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:b2(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:x2(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 N2(e){sf();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 c=d=>{if(!d.defaultPrevented){if(d.key==="Escape"){d.preventDefault(),i.current();return}j2(d,n.current,document.activeElement)}};return window.addEventListener("keydown",c),()=>{window.removeEventListener("keydown",c),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(S2,{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 $p={theme:"dark",font_scale:"md",header_density:"standard"};function $2(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:$p.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:$p.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:$p.header_density}}function C2(e){return`af_appearance_${e}_v1`}function E2(e,t){const n=C2(e),r=p.useMemo(()=>({...$p,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[i,o]=p.useState(()=>{let c=r;try{const l=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);l&&(c=$2({...r,...JSON.parse(l)}))}catch{}try{lb(c.theme),cb({font_scale:c.font_scale,header_density:c.header_density})}catch{}return c});return p.useEffect(()=>{lb(i.theme),cb({font_scale:i.font_scale,header_density:i.header_density});try{localStorage.setItem(n,JSON.stringify(i))}catch{}},[n,i]),[i,o]}function tS(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(OE,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),s.jsx("label",{className:"af-appearance__label",children:"Font size"}),s.jsx(PE,{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(DE,{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 A2="default";function sc(e){return typeof e=="string"?e.trim():""}function yb(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0}function T2(e){var h;if(!e||!Xj(e))return null;const t=(h=e.gateway)==null?void 0:h.principal;if(!t||typeof t!="object")return null;const n=sc(t.user_id);if(!n)return null;const r={userId:n},i=sc(t.tenant_id);i&&(r.tenantId=i);const o=sc(t.runtime_id);o&&(r.runtimeId=o);const c=yb(t.roles);c&&(r.roles=c);const l=yb(t.scopes);l&&(r.scopes=l);const d=sc(t.source);return d&&(r.source=d),typeof t.admin=="boolean"&&(r.admin=t.admin),r}function nS(e){const t=sc(e.displayName)||sc(e.userId),n=sc(e.tenantId);return n&&n!==A2?`${n}/${t}`:t}function sS(e){const t=sc(e);if(!t)return"";try{return new URL(t).host||t}catch{return t}}function M2(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 R2(e){return typeof e.openModal=="function"&&typeof e.signOut=="function"}function L2(e,t){return R2(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 I2(e,t){const n=sS(t);return`Signed in as ${nS(e)}${n?` · gateway ${n}`:""}`}const wy="--af-topbar-h";function O2(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 c=()=>{o=`${Math.max(0,Math.round(r.getBoundingClientRect().bottom))}px`,i.style.setProperty(wy,o)};c();const l=typeof ResizeObserver<"u"?new ResizeObserver(c):null;l==null||l.observe(r);const d={passive:!0,capture:!0};return window.addEventListener("resize",c),window.addEventListener("scroll",c,d),()=>{l==null||l.disconnect(),window.removeEventListener("resize",c),window.removeEventListener("scroll",c,d),o&&i.style.getPropertyValue(wy)===o&&i.style.removeProperty(wy)}},[e,t])}function P2(e){const t=typeof navigator<"u"?navigator.clipboard:void 0;return!t||typeof t.writeText!="function"?null:()=>{t.writeText(e).catch(()=>{})}}function D2(e){var S,P;const t=L2(e.connection,e.onSignOut),{phase:n,signingOut:r}=t,[i,o]=p.useState(!1),[c,l]=p.useState(!1),[d,h]=p.useState(void 0),m=p.useRef(null);sf(),O2(m,e.publishHeight!==!1);const _=e.about,g=e.appearance,y=!!(g&&"value"in g),x=_&&!_.versions?_.fetch:void 0,k=p.useRef(x);k.current=x,p.useEffect(()=>{const D=k.current;if(!i||!D)return;const R=typeof AbortController<"u"?new AbortController:null;let I=!0;return h(v2),w2(D,R==null?void 0:R.signal).then(W=>{I&&h(W)}),()=>{I=!1,R==null||R.abort()}},[i]);const v=M2(n,r),N=e.identity&&n==="connected"?T2(t.status):null,$=()=>void t.disconnect();let E=null;if(N&&e.identity){const D=nS(N),R=I2(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=P2(N.userId),G=sS((P=t.status)==null?void 0:P.gateway_url);E=s.jsx(h2,{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:v.title,"aria-label":v.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:v.label})]}),_?s.jsx(N2,{open:i,onClose:()=>o(!1),identity:_.identity,versions:_.versions||(_.fetch?d:void 0),extra:_.extra}):null,g&&"value"in g?s.jsx(tS,{open:c,onClose:()=>l(!1),value:g.value,onChange:g.onChange,title:g.title,note:g.note}):null]})}function Iw(e){return e?[e.provider,e.model].map(t=>String(t||"").trim()).filter(Boolean).join(" / "):""}function wb(e,t,n=!1){if(n)return"unknown";if(!e)return"";const r=e[t];return!r||!r.configured?"not set":Iw(r)||"not set"}function F2(e,t){var n;return e.stt_provider?Iw({provider:e.stt_provider,model:e.stt_model}):(n=t==null?void 0:t.stt)!=null&&n.configured?Iw(t.stt):""}function rS(e,t){return`${Math.max(0,Math.floor((t-e)/1e3))} s`}function z2(e,t,n){return`Transcribing… ${rS(e,t)}${n?` · ${n}`:""}`}const jg=()=>{var e;return(e=globalThis.navigator)==null?void 0:e.mediaDevices};function qp(e){var i;const t=kg("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=jg())!=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 iS(e){const t=jg();if(!t||typeof t.enumerateDevices!="function")return{devices:[],labelled:!1};const r=(await t.enumerateDevices()).filter(c=>c.kind===e),i=r.some(c=>!!c.label);return{devices:r.filter(c=>c.deviceId&&c.deviceId!=="default"&&c.deviceId!=="communications").map((c,l)=>({id:String(c.deviceId),label:String(c.label||`${e==="audioinput"?"Microphone":"Speaker"} ${l+1}`)})),labelled:i}}async function B2(){const e=jg();if(!(e!=null&&e.getUserMedia))throw new Error(kg("the microphone")||"This browser cannot record audio.");(await e.getUserMedia({audio:!0})).getTracks().forEach(n=>n.stop())}async function oS(e){const t=jg();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 Sg(){const e=globalThis;return e.AudioContext||e.webkitAudioContext||null}function aS(){const e=Sg();return!!(e&&e.prototype&&typeof e.prototype.createMediaStreamDestination=="function")}function lS(e,t,n=1){const r=Sg();if(!r)return()=>{};const i=new r,o=i.createMediaStreamSource(e),c=i.createAnalyser();c.fftSize=1024,o.connect(c);const l=new Float32Array(c.fftSize);let d=!0;const m=setInterval(()=>{if(!d)return;c.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 cS=.02;function vb(){return Object.assign(new Error("The recording was stopped before it began."),{name:"AbortError"})}async function uS(e){var o,c,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 vb();const n=await oS(e.deviceId);if((c=e.signal)!=null&&c.aborted)throw n.getTracks().forEach(d=>d.stop()),vb();let r=0;const i=lS(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=x=>(x==null?void 0:x.data)&&h.push(x.data),d.onstop=()=>g(),d.onerror=x=>y((x==null?void 0:x.error)||new Error("Recording failed."))});d.start(),await new Promise(g=>{var x,k;if((x=e.signal)!=null&&x.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 dS(e,t={}){var i,o,c,l;if((i=t.signal)!=null&&i.aborted)return;const n=Sg();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((c=r.resume)==null?void 0:c.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=Gd(t.volume),m.connect(r.destination);const _=r.createBufferSource();_.buffer=h,_.connect(m),await new Promise(g=>{var x,k;const y=()=>{try{_.stop()}catch{}g()};_.onended=()=>{var v,N;(N=(v=t.signal)==null?void 0:v.removeEventListener)==null||N.call(v,"abort",y),g()},(k=(x=t.signal)==null?void 0:x.addEventListener)==null||k.call(x,"abort",y,{once:!0}),_.start()})}finally{(l=r.close)==null||l.call(r)}}async function U2(e={}){var r,i;const t=Sg();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 c=.3*Gd(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(c,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 Gd(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)?1:Math.min(1,Math.max(0,t))}function Ow(e){return(e&&typeof e=="object"?e.capture_mode:e)==="toggle"?"toggle":"hold"}async function*W2(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 c=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(!c.ok){const m=await c.json().catch(()=>null),_=m&&typeof m=="object"&&m.detail?String(m.detail):`HTTP ${c.status}`;throw new Error(_)}if(!c.body)throw new Error("TTS stream has no body");const l=c.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 x=null;try{x=JSON.parse(y)}catch{throw new Error("TTS stream returned invalid JSON.")}if(x&&x.type==="error")throw new Error(String(x.error||"TTS stream error"));const k=x&&typeof x.audio_b64=="string"?x.audio_b64:"";if(k){const v=atob(k),N=new Uint8Array(v.length);for(let $=0;$<v.length;$+=1)N[$]=v.charCodeAt($);yield N.buffer}if(x&&(x.type==="done"||x.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 yh(e,t){const n=String((t==null?void 0:t.message)||t||"").trim().replace(/\.$/,"");return n?`${e}: ${n}.`:`${e}.`}const q2=350;function V2(){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 H2(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function G2(){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 vy(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,c)=>{try{r(n,o,c)}catch(l){c(l)}})}function K2(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),c=r.getUint32(i+4,!0);if(o==="data")return t.slice(0,i+8);i+=8+c+c%2}return null}function J2(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 fS(){const e=globalThis,t=e==null?void 0:e.AudioContext;return!!(t&&t.prototype&&typeof t.prototype.setSinkId=="function")}const K_=new WeakMap;function Y2(e,t){const n=e;if(!(typeof n.setSinkId!="function"||K_.get(e)===t)){K_.set(e,t);try{Promise.resolve(n.setSinkId(t)).catch(()=>K_.delete(e))}catch{K_.delete(e)}}}function X2(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(()=>H2()&&(typeof e.tts=="function"||typeof e.tts_stream=="function"),[e.tts,e.tts_stream]),i=p.useMemo(()=>V2()&&typeof e.transcribe=="function",[e.transcribe]),[o,c]=p.useState({key:"",status:"idle"}),l=p.useRef(o),d=p.useCallback(le=>{l.current=le,c(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),x=p.useRef(null),k=p.useRef(0),v=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;Y2(pe,t.current.output_device_id||""),dt.gain.value=Gd(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=Gd(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="",x.current=null,k.current=0,v.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,x.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));v.current=_t.currentTime-ut,k.current=ut,y.current=bt,h.current=le,bt.onended=()=>{y.current===bt&&(y.current=null,k.current=0,v.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,v.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));v.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"})},V=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,x.current=null,k.current=0,v.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 vy(dt.ctx,St),It||(It=K2(St))}catch{if(!It)continue;try{ut=await vy(dt.ctx,J2(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(yh("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 Rt=Math.max(0,It.ctx.currentTime-Number(v.current||0));k.current=Rt}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 Rt=x.current;if(Rt){n==null||n(""),D.current=!1;try{await G(pe,Rt,k.current)}catch(mn){n==null||n(yh("Reading aloud failed",mn)),d({key:"",status:"idle"})}return}}if(St&&bt.status==="loading")return;if(typeof _t=="function"){await V(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,x.current=null,k.current=0,v.current=0,h.current=pe,m.current=pe,d({key:pe,status:"loading"}),n==null||n("");try{const Rt=await yt(dt);if(m.current!==pe||N.current!==ut)return;const mn=await vy(It.ctx,Rt);if(m.current!==pe||N.current!==ut)return;x.current=mn,k.current=0,await G(pe,mn,0)}catch(Rt){if(N.current!==ut)return;m.current===pe&&(m.current="",h.current="",d({key:"",status:"idle"})),n==null||n(yh("Reading aloud failed",Rt))}},[]),[A,O]=p.useState(!1),[L,H]=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),Ve=p.useRef(0),mt=p.useRef(null),nt=p.useRef(0),rt=p.useRef(new Set),ze=p.useRef(null),He=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{}He(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,H(!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=Ve.current?Date.now()-Ve.current:1/0;if(!le||!le.size||pe<q2){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;H(!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,H(!1),Ae(0))}}const Q=p.useCallback(async()=>{if(n==null||n(""),!U.current){n==null||n(kg("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 oS(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=lS(Se,He,Number.isFinite(pe)&&pe>0?pe:1)}catch{}const dt=G2();be.current=dt;let yt=Se;const _t=Number(t.current.input_gain??1);if(Number.isFinite(_t)&&_t>0&&_t!==1&&aS()){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(yh("The recording could not be prepared",bt))}}},It.start(),Ve.current=Date.now(),Ae(Ve.current),te(!0)}catch(Se){if(le!==Me.current)return;$e(),se.current=null,te(!1),Ae(0),n==null||n(qp(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(yh("The recording could not stop",Se))}}},[]);return p.useEffect(()=>{if(!A||t.current.stop_on_pointerup===!1||t.current.stop_on_pointerup===void 0&&Ow(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:Ow(e.capture_mode),add_transcript_listener:Dt}}const Z2={diary:"var(--accent)",question:"#e7b45a",dream:"#c084dd",interest:"#7bd88a",lesson:"#6ea8d8",world_model:"#5eead4"};function xb(e){const t=String(e||"");return t.length>14?`${t.slice(0,10)}…${t.slice(-4)}`:t}function xy(e){const[t,n]=p.useState(!1),[r,i]=p.useState(null),o=p.useRef(!1),c=typeof e.entryId=="string"&&e.entryId.trim()?e.entryId.trim():null,l=e.kind&&Z2[e.kind]||"var(--text-muted)",d=p.useCallback(async()=>{if(!(!c||!e.onOpen||o.current)){o.current=!0,n(!0),i(null);try{await e.onOpen(c)}catch(h){i(String((h==null?void 0:h.message)||h||"could not open"))}finally{o.current=!1,n(!1)}}},[c,e.onOpen]);return!c||!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}),c&&e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:xb(c)}):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 ${c}`),"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:xb(c)}):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 bb=["Your voices","Engine voices","Shared voices"];function hS(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 Ng(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 Q2(e){return Array.from(new Set(e.map(Ng).filter(Boolean))).sort()}function eA(e,t){if(!t)return!0;const n=Ng(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 mS={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"},_S=mS,_u=e=>_S[e]||e,by=e=>String((e==null?void 0:e.voice_id)||(e==null?void 0:e.id)||""),J_=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):[],tA=200;function nA({value:e,onChange:t,fetchCatalog:n,intro:r,delivery:i=!0,quality:o=!0,showReset:c=!0,defaultHint:l,voiceDefaultLabel:d,createVoice:h,voiceLibrary:m,previewVoice:_,previewOn:g,recordFrom:y}){var ct,Qe,Dt,$e,Le;const x=m||h,[k,v]=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,V]=p.useState(!1),[M,A]=p.useState(""),[O,L]=p.useState(0),H=p.useRef(e);H.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,v({state:"playing",error:""}),dS(ce,{deviceId:(g==null?void 0:g.deviceId)||"",volume:g==null?void 0:g.volume,signal:_e.signal}).then(()=>J.current&&N.current===Q&&v({state:"idle",error:""})).catch(le=>J.current&&N.current===Q&&v({state:"idle",error:z(le)}))},se=ce=>{if(!_)return;U();const Q=N.current,_e=new AbortController;$.current=_e,v({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,v({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}v({state:"loading",error:""}),P.current=setTimeout(()=>{P.current=null,J.current&&N.current===Q&&se(ce)},tA)},be=()=>{if(k.state!=="idle"){U(),v({state:"idle",error:""});return}const ce=H.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 V(!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&&V(!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]):"",Ve=Q2(Me),mt=Ve.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)&&(eA(ce,nt)||je(ce)===Ae)).map(ce=>{const Q=Ng(ce);return{value:je(ce),group:hS(ce),label:`${ce.label||ce.name||ce.id}${Q?` · ${_u(Q)}`:""}${!e.provider&&ce.provider?` · ${ce.provider}`:""}`}}).sort((ce,Q)=>bb.indexOf(ce.group)-bb.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 He=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(Gj,{defaultHint:l,value:{provider:e.provider||"",model:e.model||""},onChange:ce=>{U(),v({state:"idle",error:""}),t({...e,...ce,voice:"",profile:""})},fetchProviders:async()=>{const ce=await D.current();if(ce.error&&!J_(ce.tts_providers||ce.providers).length)throw new Error(ce.error);return J_(ce.tts_providers||ce.providers).map(Q=>({name:Q}))},fetchModels:async ce=>{var pe,dt;const Q=await D.current(ce),_e=J_(((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(Ur,{ariaLabel:"Voice language",placeholder:"Any language",value:M,searchable:!1,options:[{value:"",label:"Any language"},...Ve.map(ce=>({value:ce,label:_u(ce)}))],onChange:A})]}):null,s.jsxs("label",{children:["Voice / profile",s.jsxs("span",{className:"af-voice-settings__voice-row",children:[s.jsx(Ur,{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:""}}He(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=>He({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=>He({quality_preset:ce.target.value}),children:[s.jsx("option",{value:"",children:"Gateway default"}),J_(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=>He({instructions:ce.target.value})})]}):null]}):null,x&&(x.design||x.clone)?s.jsx(iA,{creation:x,defaultLanguage:nt,recordFrom:y,onCreated:(ce,Q)=>{const _e=H.current;t({..._e,provider:Q||_e.provider||"",model:"",voice:ce,profile:""}),L(le=>le+1)}}):null,m!=null&&m.list?s.jsx(aA,{library:m,refreshKey:O,onChanged:()=>L(ce=>ce+1),onRemoved:ce=>{const Q=H.current;Q.voice===ce&&t({...Q,voice:""})}}):null,c?s.jsx("button",{type:"button",onClick:()=>t({}),children:"Reset to Gateway defaults"}):null]})}const sA={value:"",label:"Detect from the recording"},rA=3e4;function iA({creation:e,defaultLanguage:t,onCreated:n,recordFrom:r,cloneRoute:i}){const[o,c]=p.useState(e.design?"design":"clone"),[l,d]=p.useState(""),[h,m]=p.useState(""),[_,g]=p.useState(t||"en"),[y,x]=p.useState(""),[k,v]=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),V=p.useRef(!0),M=p.useRef(null);p.useEffect(()=>(V.current=!0,()=>{var U;V.current=!1,(U=M.current)==null||U.abort()}),[]);const A=Object.keys(_S).map(U=>({value:U,label:_u(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"}),uS({deviceId:(r==null?void 0:r.deviceId)||"",gain:r==null?void 0:r.gain,ms:rA,signal:U.signal,onLevel:z=>V.current&&I(z)}).then(({blob:z,peak:ne})=>{if(V.current){if(ne<cS){G({text:"The microphone recorded silence. Pick another input in the voice settings, then record again.",tone:"error"});return}v(z),G({text:`Recording ready (${Math.max(1,Math.round((Date.now()-te)/1e3))} s).`,tone:"ok"})}}).catch(z=>{V.current&&((z==null?void 0:z.name)==="AbortError"?G({text:"Recording cancelled.",tone:"info"}):G({text:qp(z),tone:"error"}))}).finally(()=>{M.current===U&&(M.current=null),V.current&&(D(!1),I(0))})},H=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(!V.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(!V.current)return;G({text:`The voice was not created: ${String((U==null?void 0:U.message)||U).replace(/\.$/,"")}.`,tone:"error"})}finally{K.current=!1,V.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:()=>c("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:()=>c("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;v(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(Ur,{ariaLabel:"Voice language for creation",value:O,searchable:!1,options:o==="design"?A:[sA,...A],onChange:o==="design"?g:x})]}),s.jsx("button",{type:"button","data-action":"create-voice",disabled:E||!J,onClick:H,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 oA=e=>Array.isArray(e)?e:Array.isArray(e==null?void 0:e.voices)?e.voices:[],kb=e=>String((e==null?void 0:e.message)||e||"").trim().replace(/\.$/,"");function aA({library:e,refreshKey:t,onChanged:n,onRemoved:r}){const[i,o]=p.useState([]),[c,l]=p.useState({loading:!0,error:""}),[d,h]=p.useState(null),[m,_]=p.useState(""),[g,y]=p.useState(""),[x,k]=p.useState({text:"",tone:"info"}),[v,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(oA(W).filter(G=>{var K;return by(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: ${kb(W)}.`})),()=>{I=!1}},[t,v]);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:`${kb(K)||"The gateway refused"}.`,tone:"error"})).finally(()=>{E.current=!1,S.current&&y("")}))},D=R=>String(R.name||R.label||by(R));return s.jsxs("fieldset",{className:"af-voice-library","data-voice-library":!0,children:[s.jsx("legend",{children:"Manage voices"}),c.loading&&!i.length?s.jsx("p",{role:"status",children:"Loading your voices…"}):null,c.error?s.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status","data-voice-note":"library",children:c.error}):null,!c.loading&&!c.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=by(R),W=hS(R)==="Shared voices",G=Ng(R),K=String(R.engine||R.provider||""),V=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:V||!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:V,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?_u(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:V,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:V,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,x.text?s.jsx("p",{className:`af-voice-note af-voice-note--${x.tone}`,role:"status","data-voice-note":"library-action",children:x.text}):null]})}const ky=wt("automations"),lA=wt("trigger-sources"),cA=wt("me/email"),uA=wt("me/email/accounts"),dA=wt("triggers/connections"),fA=wt("automations/schedule-preview");class jb 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 hA(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 jy(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 mA(){return nl()}function _A(e){const t=e.newId??mA,n=i=>`${ky}/${encodeURIComponent(i)}`;async function r(i,o,c){const l={accept:"application/json",...e.headers?e.headers():{}},d={method:i,headers:l};c!==void 0&&(l["content-type"]="application/json",d.body=JSON.stringify(c));const h=await e.fetch(Kv(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 jb(hA(h.status,_));if(!g||_===null||typeof _!="object")throw new jb({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",`${ky}${jy({status:i.status,cursor:i.cursor,limit:i.limit})}`),getAutomation:i=>r("GET",n(i)),createAutomation:i=>r("POST",ky,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${jy({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${jy({cursor:o.cursor,limit:o.limit})}`),listTriggerSources:()=>r("GET",lA),getMyEmail:()=>r("GET",cA),listTriggerConnections:()=>r("GET",dA),listMailboxes:()=>r("GET",uA),previewSchedule:i=>r("POST",fA,{trigger:i})}}function pS(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 gS(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 pA(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 Pw(e){return e.flow_id==="@default"?"@default":`${"bundle_ref"in e?e.bundle_ref:""}:${e.flow_id}`}const gA={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",unarchive:"Unarchive",discuss:"Discuss"},yA={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.`},wA="Next scheduled run: {time}.",vA="Growing context: later runs see this run in their history.",xA={run_now:{name:"playCircle"}},bA={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."},kA={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."},Yv={labels:gA,hints:yA,run_now_next_run_line:wA,run_now_growing_line:vA,icons:xA,email:bA,schedule:kA},Cp={manual:"By hand",schedule:"On a schedule",something:"When something arrives",main_mailbox:"your main mailbox"};function xm(e){const t=String(e||"");return t.startsWith("feed")?"feed":t.startsWith("webhook")?"webhook":"other"}function yS(e,t){const n=xm(t);return n==="feed"?`When ${e} has a new item`:n==="webhook"?`When ${e} is called`:`When ${e} sends something`}function wS(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 uc(e){if(!e)return!1;const t=String(e.source_id||"");return!(t==="schedule"||t==="manual"||!t)}function $g(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"?Cp.main_mailbox:r}function Xv(e,t){const n=wS(e);return n?(t??[]).find(r=>r.connection_id===n)??null:null}function jA(e,t,n){var c;if(!e||!uc(e))return"";const r=String(e.source_id||"");if(r.startsWith("email"))return $g((c=e.config)==null?void 0:c.account,n);const i=Xv(e,t);if(i!=null&&i.label)return i.label;const o=xm(r);return o==="feed"?"A feed":o==="webhook"?"A webhook":"A connection"}function bm(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():Cp.schedule}if(o==="manual")return Cp.manual;if(o.startsWith("email"))return`When mail arrives in ${$g((l=e.config)==null?void 0:l.account,n)}`;if(wS(e)){const d=Xv(e,t),h=xm(o),m=(d==null?void 0:d.label)||(h==="feed"?"a feed":h==="webhook"?"a webhook":"a connection");return yS(m,o)}return Cp.something}const SA=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Sy(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,c]=r.split("-"),l=`${Number(c)} ${SA[Number(o)-1]??o}`;return{day:r,clock:i,label:l}}function NA(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 Zh(e,t={}){if(!e)return"";const n=Date.parse(e);if(Number.isNaN(n))return"";const r=NA(t.timeZone),i=r??"UTC",o=r?"":" UTC",c=t.nowMs??Date.now(),l=Sy(n,i),d=Sy(c,i).day,h=Sy(c-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 Ka(e){return typeof e=="string"?e.trim():""}function Y_(e){return e?`: “${e}”`:""}function X_(e,t,n){return`${e} ${e===1?t:n}`}function $A(e,t={}){var m,_,g;if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e,r=Ka(n.type),i=/^abstract\.(.+)\.v(\d+)$/.exec(r),o=i?i[1]:"";if(!o||o==="schedule"||o==="manual")return null;const c=n.data&&typeof n.data=="object"&&!Array.isArray(n.data)?n.data:{},l=Zh(Ka(n.time),{timeZone:t.timeZone,nowMs:t.nowMs});let d="",h="";if(o.startsWith("email")){const y=Array.isArray(c.messages)?c.messages:[],x=typeof c.count=="number"?c.count:y.length;if(!x)return null;d=$g((_=(m=t.trigger)==null?void 0:m.config)==null?void 0:_.account,t.mailboxes),h=`${X_(x,"new message","new messages")}${Y_(Ka((g=y[0])==null?void 0:g.subject))}`}else{const y=Array.isArray(c.events)?c.events:[],x=typeof c.count=="number"?c.count:y.length;if(!x)return null;const k=y[0]&&typeof y[0]=="object"?y[0]:{},v=k.data&&typeof k.data=="object"&&!Array.isArray(k.data)?k.data:{},N=Ka(c.connection_id)||Ka(n.connectionid),$={source_id:o,config:{connection_id:N}},E=Xv(N?$:t.trigger,t.connections),S=xm(o);d=(E==null?void 0:E.label)||jA(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=x===1?"Test event":`${x} test events`:S==="webhook"?h=`${X_(x,"call","calls")}${Y_(Ka(k.subject))}`:S==="feed"?h=`${X_(x,"new item","new items")}${Y_(Ka(v.title)||Ka(k.subject))}`:h=`${X_(x,"new event","new events")}${Y_(Ka(k.subject))}`}return{source:d,what:h,at:l,text:[d,h,l].filter(Boolean).join(" · ")}}const CA=/^([1-9][0-9]*)([smhd])$/,EA={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function km(e){if(typeof e!="string")return null;const t=CA.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function AA(e){const t=km(e);if(!t)return`every ${e}`;const[n,r]=EA[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${r}`}function Dw(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 Zv(e,t,n){return bm(e,n==null?void 0:n.connections,n==null?void 0:n.mailboxes,t)}function vS(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const TA={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},$n=Yv.email,xS="email.received",bS=1,MA="1h",RA="60s",kS=60,Qv=100,Fw=1e3,Sb=200,Nb=200,$b=50;function Cg(e){return!!e&&e.source_id===xS&&e.source_version===bS}function Eg(e){return!!e&&e.effective_enabled===!0}function jS(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 LA=/[\s<>,;:"()[\]]/;function zw(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!LA.test(t)}function IA(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const SS={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function ex(e){return e?MA:RA}function NS(e){const t=km(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function Ny(e,t,n,r,i){const o=jS(e);if(!o.length)return null;const c=o.filter(l=>!n(l));return c.length&&i.push(`${t}: ${c.join(", ")} ${c.length===1?"is not":"are not"} ${r}.`),o.length>Sb&&i.push(`${t}: at most ${Sb} entries.`),o}function OA(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=ex(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&&(NS(n.every)??0)<kS&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=Qv:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>Fw?t.push(`At most this many emails per run: a whole number from 1 to ${Fw}.`):n.max_batch=e.maxBatch;const r={},i=Ny(e.fromIn,$n.from_in,zw,"an email address",t);i&&(r.from_in=i);const o=Ny(e.fromDomainIn,$n.from_domain_in,IA,"a domain like example.com",t);o&&(r.from_domain_in=o);const c=Ny(e.toIn,$n.to_in,zw,"an email address",t);c&&(r.to_in=c);const l=e.subjectContains.trim();return l&&(l.length>Nb||/[\r\n]/.test(l)?t.push(`${$n.subject_contains}: one line of at most ${Nb} 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 $S(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:ex(t.uses_model!==!1);r.push(`checked ${AA(o)}`);const c=typeof t.max_batch=="number"?t.max_batch:Qv;return r.push(`up to ${c} per run`),r.join(" · ")}const Gh={mode:"self",addresses:""};function Bw(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=jS(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=>!zw(i));return r.length&&t.push(`${$n.recipients_list}: ${r.join(", ")} ${r.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>$b&&t.push(`At most ${$b-1} addresses.`),{recipients:["self",...n],errors:t}}function PA(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function DA(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function CS(e,t=["self"]){return{channels:e?["console","email"]:["console"],...t.some(n=>n!=="self")?{recipients:t}:{}}}function ES(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function FA(e){return ES(e)?"In the console and by email":"In the console"}const go={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive",unarchive:"automation.unarchive"},zA=new Set(["running","waiting","backoff"]);function BA(e,t=[]){return e.current_occurrence!=null}function AS(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 TS(e,t){var n;return e.next_run_at&&e.next_run_local?`${FS(e.next_run_local,e.time_zone)} (${UA(e.next_run_at,t)})`:e.status==="paused"?"none while paused":e.status==="active"&&e.trigger&&uc(e.trigger)?Cb.event:e.status==="active"&&((n=e.trigger)==null?void 0:n.source_id)==="manual"?Cb.manual:"none scheduled"}const Cb={event:"when something new arrives",manual:"when someone presses Run now"};function UA(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 Qh(e,t=[],n=!1){const r=new Set(e.capabilities),i=e.status,o=BA(e,t),c=(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:c("pause",i==="active",i==="paused"?"Already paused.":"The automation has ended."),resume:c("resume",i==="paused",i==="active"?"Already running on schedule.":"The automation has ended."),run_now:c("run_now",l&&!o,o?"An occurrence is in progress.":"The automation has ended."),stop_current:c("stop_current",o,"Nothing is running."),revise:c("revise",!0,""),archive:c("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 WA(e){return e.status==="active"?go.pause:go.resume}function qA(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 VA(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=qA(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:!zA.has(t.status)}})}function HA(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function MS(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 GA={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 Vp(e){return{title:GA[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function tx(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 RS(e,t){var o,c,l;const n=e.trigger,r=n.source_id==="schedule"||Cg(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:YA(n)?eT(n.config):null,context:e.context_mode,growingMaxTokens:Number(((c=(o=t==null?void 0:t.context)==null?void 0:o.growing)==null?void 0:c.max_tokens)??e.growing_max_tokens??em),prompt:typeof i=="string"?i:null,toolApproval:t?t.policy.tool_approval:null,tools:pS(t==null?void 0:t.target.input_data),notifyEmail:t?ES(t.notify):null,emailRecipients:t?PA((l=t.notify)==null?void 0:l.recipients):null}}function KA(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 c=RS(e,n);if(t.every!==c.every&&t.every!==null){const h=Cg(e.trigger);if(!km(t.every))r.push("Interval must be a whole number of minutes, hours or days.");else if(h&&(NS(t.every)??0)<kS)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&&c.calendar&&JSON.stringify(t.calendar)!==JSON.stringify(c.calendar)){const h=nx(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??c.growingMaxTokens:c.growingMaxTokens;if(IS(l)||r.push(LS),(t.context!==e.context_mode||l!==c.growingMaxTokens)&&(i.context=OS(t.context,l)),n&&typeof c.prompt=="string"&&typeof t.prompt=="string"&&t.prompt.trim()!==c.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(c.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:gS(h.input_data||{},t.tools)}}if(n&&t.toolApproval&&t.toolApproval!==c.toolApproval&&(i.policy={tool_approval:t.toolApproval}),n&&typeof t.notifyEmail=="boolean"){const h=Bw(t.notifyEmail?t.emailRecipients??Gh:c.emailRecipients??Gh),m=Bw(c.emailRecipients??Gh).recipients;h.errors.length?r.push(...h.errors):(t.notifyEmail!==c.notifyEmail||JSON.stringify(h.recipients)!==JSON.stringify(m))&&(i.notify=CS(t.notifyEmail,h.recipients))}if(r.length)return{errors:r};if(n&&t.target&&Pw(t.target)!==Pw(n.target)){const h=((d=i.target)==null?void 0:d.input_data)||n.target.input_data;i.target={...t.target,input_data:pA(h)}}return Object.keys(i).length?i:null}const em=5e4,JA="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.",LS="Max growing context must be a positive whole number of tokens.";function IS(e){return Number.isSafeInteger(e)&&e>0}function OS(e,t){return{mode:e,...t!==em?{growing:{max_tokens:t}}:{}}}const fs=Yv.schedule,Hp=["mon","tue","wed","thu","fri","sat","sun"],PS=["daily","weekly","monthly"],DS=2;function YA(e){return e.source_id==="schedule"&&e.source_version===DS}const XA=/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/;function FS(e,t){if(!e)return"";const n=XA.exec(e);return n?`${n[1]} ${n[2]}${t?` ${t}`:""}`:e}function ZA(e,t="account"){return(t==="account"?fs.time_zone_line:fs.time_zone_line_automation).replace("{time_zone}",e)}const QA=/^([01][0-9]|2[0-3]):[0-5][0-9]$/;function zS(e){return PS.includes(e.kind)}function nx(e){const t=[];if(QA.test(e.at)||t.push(fs.error_at),e.kind==="weekly"){const n=Hp.filter(r=>e.days.includes(r));return n.length||t.push(fs.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(fs.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 eT(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)?Hp.filter(r=>t.days.includes(r)):[]}:t.kind==="monthly"?{kind:"monthly",at:n,day:t.day==="last"?"last":Number(t.day)}:null}const tT=[{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 BS(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 nT(e){const t=e.trim().split(`
56
+ `)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}const sT=/^\d{4}-\d{2}-\d{2}T([01][0-9]|2[0-3]):[0-5][0-9]$/;function Eb(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=BS(e.until);r?n.until=r:t.push("Stop at must be a date and time (UTC).")}return n}function rT(e){const t=[],n=e.when;if(n.kind==="once"){const l=(n.at||"").trim().slice(0,16);return sT.test(l)?{config:{kind:"once",at:l},errors:t}:{config:null,errors:[fs.error_once]}}if(zS(n)){const l=nx(n),d=Eb(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=BS(e.startAt),o||t.push("First run must be a date and time (UTC)."));const c=Eb(e,t);return t.length||!i?{config:null,errors:t}:{config:{kind:"every",every:i,...o?{start_at:o}:{},...c},errors:t}}function US(e){const t=rT(e);return t.config?{trigger:{source_id:"schedule",source_version:DS,config:t.config},errors:[]}:{trigger:null,errors:t.errors}}function iT(e){return e.kind==="every"||e.kind==="once"||zS(e)}function WS(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()||nT(r);i.length>120&&n.push("Title is at most 120 characters.");const o=e.trigger==="email",c=o?OA(e.email??SS):null,l=o?null:US(e);n.push(...c?c.errors:l.errors);const d=e.notifyEmail&&e.emailRecipients&&e.emailRecipients.mode==="list"?Bw(e.emailRecipients):null;d&&n.push(...d.errors);const h=e.growingMaxTokens??em;if(e.context==="growing"&&!IS(h)&&n.push(LS),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:c?{source_id:xS,source_version:bS,config:c.config}:l.trigger,context:OS(e.context,e.context==="growing"?h:em),policy:{tool_approval:e.toolApproval??"auto"}};return e.notifyEmail===!0&&(_.notify=CS(!0,d==null?void 0:d.recipients)),{ok:!0,body:_}}const oT="Tools run without asking (you approve them now by creating this automation)";function aT(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 lT(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 qS={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class cT{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||uT(n.error))&&this.open.delete(t)}}function uT(e){return tx(e)&&e.status>0&&e.code!=="invalid_response"}function dT(){return nl()}class fT{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 Ab(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 hT="08:00",mT=["mon"],VS={at:hT,days:[...mT],day:1};function sx(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 rx(e,t){return{...e,at:t.at,...t.kind==="weekly"?{days:[...t.days]}:{},...t.kind==="monthly"?{day:t.day}:{}}}function Tb(e){return rx(VS,e)}const _T=[...Array.from({length:31},(e,t)=>String(t+1)),"last"];function HS(e){const t=e.value,n=r=>{if(t.kind!=="weekly")return;const i=t.days.includes(r);e.onChange({...t,days:Hp.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":fs.days_legend,children:[s.jsx("span",{children:fs.days_legend}),Hp.map(r=>s.jsx(o2,{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:fs.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:fs.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:_T.map(r=>s.jsx("option",{value:r,children:r==="last"?fs.last_day:r},r))})]}):null,s.jsx("label",{htmlFor:`${e.idBase}-at`,children:fs.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":fs.time_label,onChange:r=>e.onChange({...t,at:r.target.value.slice(0,5)})})]})]})}function pT(e){return s.jsxs("p",{className:"af-schedule__tz","data-time-zone":e.timeZone,children:[s.jsx(mb,{content:fs.time_zone_hint,children:s.jsx("span",{tabIndex:0,className:"af-schedule__tz-text",children:ZA(e.timeZone,e.whose??"account")})}),e.onOpenPreferences&&(e.whose??"account")==="account"?s.jsxs(s.Fragment,{children:[" · ",s.jsx(mb,{content:fs.time_zone_change_hint,children:s.jsx("button",{type:"button",className:"af-auto__link af-schedule__tz-change",onClick:e.onOpenPreferences,children:fs.time_zone_change})})]}):null]})}function gT(e){const t=e;return typeof(t==null?void 0:t.message)=="string"&&t.message?t.message:String(e)}function GS(e,t,n=250){const r=e?JSON.stringify(e):"",[i,o]=p.useState({phase:"idle"}),c=p.useRef(0),l=p.useRef(t);return l.current=t,p.useEffect(()=>{const d=++c.current;if(!r){o({phase:"idle"});return}o({phase:"loading"});const h=setTimeout(()=>{l.current(JSON.parse(r)).then(m=>{c.current===d&&o({phase:"ok",description:m})},m=>{c.current===d&&o({phase:"error",message:gT(m)})})},n);return()=>clearTimeout(h)},[r,n]),i}function Uw(e){const t=e.state;return t.phase==="ok"?s.jsxs(s.Fragment,{children:[e.showZone===!1?null:s.jsx(pT,{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"?fs.describing:e.incompleteText??fs.incomplete})}function Mb(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 Ww(e){const t=e.disabled===!0,n=p.useMemo(()=>Mb([...e.options||[],...e.value||[]]),[e.options,e.value]),r=p.useMemo(()=>Mb(e.value||[]),[e.value]),[i,o]=p.useState(!1),[c,l]=p.useState(""),d=p.useMemo(()=>{const _=c.trim().toLowerCase();return _?n.filter(g=>g.toLowerCase().includes(_)):n},[n,c]),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:c,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 x=new Set(h);y.target.checked?x.add(_):x.delete(_),e.onChange(Array.from(x.values()))}}),s.jsx("span",{children:_})]},_)}),d.length?null:s.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function KS(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(Ww,{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 JS="@default",YS="No workflows available for this app — ask your admin.",XS={shared:"Shared",mine:"Mine"};class Gl extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function yT(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 wT(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function vT(e,t={}){return e===null?wT(t):yT(e,t)}function Di(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Hs(e){return typeof e=="string"?e.trim():""}const Z_="update the gateway";function xT(e,t){var l,d;const n=Di(e.default_agent_workflows);if(!n)return{status:"unavailable",reason:"the gateway does not report a default workflow"};const r=Di(n[t]);if(!r)return{status:"unavailable",reason:Hs((d=Di((l=Di(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 c=Hs(r.bundle_version);return{status:"ok",name:Hs(r.name)||o,bundleId:i,bundleVersion:c,flowId:o,workflowId:Hs(r.workflow_id)||`${i}${c?`@${c}`:""}:${o}`}}function bT(e,t,n={}){var l,d;const r=Di(e);if(!r)throw new Gl("The gateway's workflow list is not a JSON object.");const i=Hs(r.executable_for);if(t===null){if(i)throw new Gl(`Asked for every workflow, the gateway listed only ${i}.`)}else if(i!==t)throw new Gl(i?`The gateway listed workflows for ${i}, not ${t}.`:`This gateway does not filter workflows per app (no executable_for in its answer): ${Z_}.`);if(!Array.isArray(r.items))throw new Gl("The gateway's workflow list has no items.");const o=[];for(const h of r.items){const m=Di(h),_=Hs(m==null?void 0:m.bundle_id);if(!m||!_)throw new Gl("The gateway listed a workflow without a bundle id.");const g=Di(m.owner),y=Hs(g==null?void 0:g.kind);if(y!=="gateway"&&y!=="user")throw new Gl(`The gateway did not say who owns ${_} (owner missing): ${Z_}.`);if(typeof m.shipped!="boolean")throw new Gl(`The gateway did not say whether ${_} ships with it (shipped missing): ${Z_}.`);const x=Hs(m.bundle_version),k=Array.isArray(m.entrypoints)?m.entrypoints:[];for(const v of k){const N=Di(v),$=Hs(N==null?void 0:N.flow_id);if(!N||!$)continue;const E=Array.isArray(N.interfaces)?N.interfaces.map(Hs).filter(Boolean):[],S=$T((l=Di(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 Gl(`The gateway offered ${_}:${$}, which does not declare ${t}: ${Z_}.`);o.push({value:Hs(N.workflow_id)||`${_}${x?`@${x}`:""}:${$}`,bundleId:_,bundleVersion:x,flowId:$,name:Hs(N.name)||Hs((d=Di(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 c=n.defaultInterface??t;return{interfaceId:t,entries:o,gatewayDefault:c?xT(r,c):{status:"unavailable",reason:"no interface named for the gateway default"}}}function kT(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:XS[n],entries:e.filter(r=>r.group===n).sort(t)})).filter(n=>n.entries.length>0)}const jT={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function ST(e){return jT[e]??e}function NT(e,t=[]){const n=e.bundleVersion?`@${e.bundleVersion}`:"";return e.showInterfaces?!e.interfaces.length&&e.automationTrigger?[bm(e.automationTrigger),n].filter(Boolean).join(" · "):[[...new Set(e.interfaces.map(ST))].join(", "),n].filter(Boolean).join(" · "):n}function $T(e){var o;const t=Di((o=Di(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=Di(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 ET(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function AT(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 TT(e,t=!0){const n=(e==null?void 0:e.entries)??[],r=[];t&&r.push({key:"default",value:JS,name:"Gateway default",detail:ET((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const i of kT(n))for(const o of i.entries)r.push({key:o.value,value:o.value,name:o.name,detail:NT(o,n),title:CT(o),group:i.id,entry:o});return r}async function MT(e,t,n){var o;const r=await fetch(Kv(e,wt(t)),{credentials:"include",headers:{Accept:"application/json"},signal:n}),i=await r.json().catch(()=>null);if(!r.ok){const c=((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(c||`The gateway answered ${r.status}.`)}return i}function RT(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 ZS(e){const{interfaceId:t,defaultInterface:n,allVersions:r=!1,enabled:i=!0,gatewayBaseUrl:o,reloadKey:c}=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;_(v=>({...v,status:"loading",error:""}));const x=vT(t,{allVersions:r});return(l.current?l.current(x,{signal:y.signal}):MT(o,x,y.signal)).then(v=>{y.signal.aborted||_({status:"ready",data:bT(v,t,{defaultInterface:n}),error:""})}).catch(v=>{y.signal.aborted||_({status:"error",data:null,error:RT(v)})}),()=>y.abort()},[t,n,r,i,o,c,d]);const g=p.useCallback(()=>h(y=>y+1),[]);return{...m,reload:g}}function LT(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)),c=r-t.bottom-16;return c>=220||c>=t.top?{position:"fixed",left:o,width:i,top:t.bottom+4,maxHeight:Math.max(160,c)}:{position:"fixed",left:o,width:i,bottom:r-t.top+4,maxHeight:Math.max(160,t.top-16)}}function QS(...e){return e.filter(Boolean).join(" ")}function eN(e){const t=ZS({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`,[c,l]=p.useState(!1),[d,h]=p.useState(-1),m=p.useRef(null),_=p.useRef(null),[g,y]=p.useState({}),x=e.entryDetail,k=p.useMemo(()=>TT(n.data,r).map(I=>{const W=I.entry&&x?x(I.entry):null;return W?{...I,detail:W}:I}),[n.data,r,x]),v=k.find(I=>I.value===e.value),N=v?{name:v.name,detail:v.detail}:e.currentLabel?{name:e.currentLabel.name,detail:e.currentLabel.detail||""}:n.status==="loading"?{name:"Loading flows…",detail:""}:{name:e.value===JS?"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(LT(_.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(!c)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)}},[c,S]),p.useEffect(()=>{var W;if(!c||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"})},[c,d,i]);const R=I=>{if(!c){["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=AT(I.key,d,k.length);W!==null&&(I.preventDefault(),h(W))};return s.jsxs("div",{ref:m,className:QS("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":c,"aria-controls":o,"aria-activedescendant":c&&d>=0?`${i}-opt-${d}`:void 0,"aria-disabled":E?void 0:!0,title:$||void 0,onClick:()=>c?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"})]}),c?s.jsx(IT,{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:YS}):null]})}function IT(e){const t=(o,c)=>s.jsxs("div",{id:`${e.idBase}-opt-${c}`,role:"option","aria-selected":o.value===e.value,"data-value":o.value,title:o.title,className:QS("af-workflow-picker__option",c===e.highlight&&"af-workflow-picker__option--highlighted",o.value===e.value&&"af-workflow-picker__option--selected"),onMouseEnter:()=>e.onHighlight(c),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,c)=>({row:o,index:c})),r=n.filter(o=>o.row.group===null),i=["shared","mine"].map(o=>({g:o,items:n.filter(c=>c.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:c})=>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:XS[o]}),c.map(l=>t(l.row,l.index))]},o)),i.length===0?s.jsx("p",{className:"af-workflow-picker__empty",children:YS}):null]})}function OT(e){const t=Pw(e.target);return s.jsxs("div",{className:"af-auto__field",children:[s.jsx("span",{children:"Flow"}),s.jsx(eN,{...e.options,ariaLabel:"Automation flow",value:t,currentLabel:{name:PT(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 PT(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(":"),c=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===c&&(!l||_.flowId===l)))==null?void 0:m.name)||c||e}async function DT(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("@"),c=o<0?r:r.slice(0,o),l=o<0?"":r.slice(o+1),d=await t.request(`bundles/${encodeURIComponent(c)}/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[x,k]of Object.entries(h.properties))k&&"default"in k&&(m[x]=k.default);Object.assign(m,e.input_data||{});const _=(Array.isArray(h.required)?h.required:[]).filter(x=>m[x]===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 tN(e){if(Eg(e.status))return null;const t=$n.not_set_up,n=$n.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 FT(e){const t=e.value,n=l=>e.onChange({...t,...l}),r=l=>`${e.idBase}-email-${l}`,i=km(ex(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"}),c=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:$n.every_label}),s.jsx("input",{type:"number",min:1,step:1,value:String(o.amount),disabled:c,"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:c,"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:$n.interval_rule}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("batch"),children:[s.jsx("span",{children:$n.max_batch_label}),s.jsx("input",{id:r("batch"),name:"email_max_batch",type:"number",min:1,max:Fw,step:1,disabled:c,value:String(t.maxBatch??Qv),onChange:l=>n({maxBatch:l.target.value.trim()===""?null:Number(l.target.value)})})]}),s.jsx("p",{className:"af-auto__hint",children:$n.max_batch_hint}),s.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:c,children:[s.jsx("legend",{children:$n.filters_legend}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("from"),children:[s.jsx("span",{children:$n.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:$n.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:$n.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:$n.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:$n.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:$n.has_attachment_any}),s.jsx("option",{value:"yes",children:$n.has_attachment_yes}),s.jsx("option",{value:"no",children:$n.has_attachment_no})]})]}),s.jsx("p",{className:"af-auto__hint",children:$n.list_hint})]})]})}function zT(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(Fi,{variant:"row",action:"notify-email",label:$n.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:[$n.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:$n.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"})})," ",$n.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"})})," ",$n.recipients_list]}),e.recipients.mode==="list"?s.jsx("textarea",{name:"email_recipient_list","aria-label":$n.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:$n.recipients_hint})]}):null]})}const BT={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function nN(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:TA[t]??t}),n?s.jsx(qe,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const Rb="Discuss this run",Ag=e=>s.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function UT(e){return tx(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function WT(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 qT(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 VT(e){const t=e.summary,n=AS(t),r=qT(t,e.triggerSources),i=TS(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(nN,{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:[Zv(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:vS(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:MS(t)})]})]})}function HT(e){var c,l;const t=e.definition,n=e.renderText??Ag,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," · ",Zv(t.trigger,e.served,{connections:e.triggerConnections,mailboxes:e.mailboxes}),Cg(t.trigger)?s.jsx("div",{className:"af-auto__hint","data-def":"email_rule",children:$S(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:[vS(t.context.mode),t.context.mode==="growing"?` · ${Number(((c=t.context.growing)==null?void 0:c.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:FA(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:DA(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(WT,{path:t.workspace_root})})]}):null,s.jsx("dt",{children:"Revision"}),s.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const jm=Yv,wa=jm.labels,Ho={active:"play",pause:"pause",resume:"play",run_now:jm.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",unarchive:"unarchive",discuss:"chat"},qw=jm.hints,GT=jm.run_now_next_run_line,KT=jm.run_now_growing_line;function Gp(e,t){const n=[qw[e]];return e==="run_now"&&t&&(t.next_run_local&&n.push(GT.replace("{time}",FS(t.next_run_local,t.time_zone))),t.context_mode==="growing"&&n.push(KT)),n.join(`
58
+ `)}function JT(e,t,n){const r=new Map;for(const c of t){const l=e[c];if(l.enabled)continue;const d=l.reason??"Not available now.";r.set(d,[...r.get(d)??[],c])}const i=[],o={};return[...r.entries()].forEach(([c,l],d)=>{const h=`${n}-why-${d}`;i.push({id:h,text:`${l.map(m=>wa[m]).join(", ")}: ${c}`});for(const m of l)o[m]=h}),{lines:i,describedBy:o}}function Br(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 YT(e){const t=Qh(e.summary,e.occurrences,e.busy),n=e.summary.status==="archived",i=JT(t,["active","run_now","stop_current","revise",n?"unarchive":"archive"],e.idBase??`af-auto-${e.summary.automation_id}`),o=(c,l,d)=>{const h=Gp(c,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)??c,disabled:!t[c].enabled,title:t[c].enabled?h:`${t[c].reason}
59
+ ${h}`,"aria-description":h,"aria-describedby":i.describedBy[c],"aria-pressed":d==null?void 0:d.pressed,onClick:l,children:s.jsx(Br,{icon:Ho[c],label:(d==null?void 0:d.label)??wa[c]})},c)};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(Fi,{className:"af-auto__switch",action:"active",label:wa.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:Gp("active",e.summary),onChange:()=>e.onCommand(WA(e.summary))},"active"),o("run_now",()=>e.onCommand(go.run_now)),o("stop_current",()=>e.onCommand(go.stop_current)),o("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),n?o("unarchive",()=>e.onCommand(go.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(c=>s.jsx("span",{id:c.id,children:c.text},c.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(go.archive),children:s.jsx(Br,{icon:"archive",label:"Archive"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:s.jsx(Br,{icon:"x",label:"Keep it"})})]})]}):null]})}const Lb=[["m","minutes"],["h","hours"],["d","days"]];function XT(e,t){const n=v=>{const N=e.elements.namedItem(v);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,c=e.elements.namedItem("context"),l=c&&(c.value==="growing"||c.value==="independent")?c.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"),x=n("email_recipient_list"),k=y&&(y.value==="self"||y.value==="list")?{mode:y.value,addresses:x??""}: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 ZT(e){var D;const t=RS(e.summary,e.definition),[n,r]=p.useState(),[i,o]=p.useState(t.tools??null),[c,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?Tb(t.calendar):null),x=m&&g?sx(m,g):null,k=(()=>{if(!x)return null;const R=nx(x);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}:{}}}})(),v=GS(k,e.previewSchedule),N=t.every?km(t.every):null,$=N&&N.unit==="s"?[["s","seconds"],...Lb]:Lb,E=`af-auto-revise-${e.summary.automation_id}`,S=Eg(e.emailStatus),P=Cg(e.summary.trigger);return s.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${E}-heading`,onSubmit:R=>{R.preventDefault(),e.onSubmit({...XT(R.currentTarget,t),...x?{calendar:x}:{},...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(OT,{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?$n.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:$n.interval_rule}):null]}):x?s.jsxs("fieldset",{className:"af-auto__field","data-field":"calendar",children:[s.jsx("legend",{children:fs.legend}),s.jsx("div",{className:"af-auto__row",role:"radiogroup","aria-label":"Schedule kind",children:PS.map(R=>s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:`${E}-calendar-kind`,value:R,checked:x.kind===R,disabled:e.busy,onChange:()=>_(R)})," ",fs[`kind_${R}`]]},R))}),s.jsx(HS,{value:x,onChange:R=>y(I=>rx(I??Tb(R),R)),idBase:E,disabled:e.busy}),s.jsx(Uw,{state:v,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:c!=="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||c!=="growing",defaultValue:t.growingMaxTokens}),s.jsx("span",{className:"af-auto__hint",children:JA})]})})]}),t.toolApproval?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?s.jsx(KS,{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(tN,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),s.jsx(qE,{variant:"row",action:"notify-email",name:"notify_email",label:$n.notify_label,defaultChecked:!!t.notifyEmail,onChange:h,unavailableReason:!S&&!t.notifyEmail?"Connect a mailbox first.":null}),s.jsxs("p",{className:"af-auto__hint",children:[$n.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:$n.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",$n.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"})," ",$n.recipients_list]}),s.jsx("textarea",{name:"email_recipient_list","aria-label":$n.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!S&&t.emailRecipients.mode!=="list"}),s.jsx("p",{className:"af-auto__hint",children:$n.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(Br,{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(Br,{icon:"x",label:"Cancel"})}):null]})]})}function QT(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 eM(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 tM="What the agent received";function Vw(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function nM(e){const t=e.wait,n=`${e.idBase}-${t.run_id}-${t.wait_key}-prompt`,r=c=>e.onAnswerWait(t.run_id,t.wait_key,c),i=e.renderText??Ag,o=c=>s.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[s.jsx("span",{className:"af-auto-wait__kind",children:qS[t.kind]??"Waiting"}),t.prompt?i(t.prompt):s.jsxs("span",{children:[" ",c]})]});if(t.kind==="tool_approval"){const c=aT(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."),c&&c.length?s.jsx("ul",{className:"af-auto-wait__calls","aria-label":"Tool calls to approve",children:c.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(Br,{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(Br,{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:c=>{var d;c.preventDefault();const l=lT(Vw(c.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(Br,{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:c=>{c.preventDefault();const l=Vw(c.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(c=>s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"wait-choice",disabled:e.busy,onClick:()=>r({response:c}),children:c},c))}):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(Br,{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 sM(e){const{row:t,tone:n,badge:r,statusText:i}=e.view,o=`af-auto-occ-${t.run_id}`,c=e.renderText??Ag,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=(v,N)=>e.renderTurn?e.renderTurn({kind:v,role:v==="trigger"?"user":"assistant",text:N,index:t.index,runId:t.run_id}):c(N),m=e.renderTurn?" af-auto-turn--card":"",_=typeof e.task=="string"?e.task.trim():"",g=QT(t.user_turn,_)!==null,y=eM(t),x=Zh(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 ${Dw(t.fired_at)}`,children:[s.jsxs("span",{className:"af-auto-turn__index",children:["Run #",t.index]}),y?` · ${y}`:"",x?` · ${x}`:""]}),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:tM}),s.jsx("div",{className:"af-auto-received__body",children:c(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:Dw(t.finished_at),children:[" · ",Zh(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:c(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(v=>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:v.url,name:v.name,mimeType:v.mime_type,runId:t.run_id})},children:[s.jsx(qe,{name:"file",size:13,className:"af-auto__btn-icon"})," ",v.name]}):s.jsx("span",{className:"af-auto-artifact__name",children:v.name})," ",s.jsx("span",{className:"af-auto-turn__muted",children:v.mime_type})]},v.artifact_id))}):null,t.waits.map(v=>s.jsx(nM,{wait:v,busy:e.busy,idBase:o,onAnswerWait:e.onAnswerWait,onWaitError:e.onWaitError,renderText:e.renderText},`${v.run_id}:${v.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(Br,{icon:"list",label:"Open run ledger"})}),e.onOpenResource?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-ledger-json",onClick:()=>{var v;return(v=e.onOpenResource)==null?void 0:v.call(e,{kind:"ledger",url:t.ledger_url,name:`run-${t.run_id}-ledger.json`,runId:t.run_id})},children:s.jsx(Br,{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 v;return(v=e.onOpenWorkspace)==null?void 0:v.call(e,t.run_id)},children:s.jsx(Br,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?s.jsxs("form",{className:"af-auto-discuss","aria-label":`${Rb}, from run ${t.index}`,onSubmit:v=>{v.preventDefault();const N=Vw(v.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(Br,{icon:"send",label:"Start discussion"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:s.jsx(Br,{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:qw.discuss,"aria-description":qw.discuss,"aria-describedby":d?`${o}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:s.jsx(Br,{icon:Ho.discuss,label:Rb})}),d?s.jsx("span",{className:"af-auto__reasons",id:`${o}-discuss-why`,children:d}):null]})]})]})}const rM=5e3,iM={[go.pause]:"Automation paused.",[go.resume]:"Automation active.",[go.run_now]:"Run requested.",[go.stop_current]:"Stop requested.",[go.unarchive]:"Unarchived: it is paused until you make it active."};function oM(e){var Me,je;const{summary:t,busy:n}=e,r=e.renderText??Ag,i=p.useId(),o=p.useRef(null),[c,l]=p.useState(!1),d=e.editOpen!==void 0,m=Qh(t,e.occurrences,!1).revise.enabled&&(d?e.editOpen===!0:c),_=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 x=ae=>{var xe;d||l(ae),(xe=y.current)==null||xe.call(y,ae)},[k,v]=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),rM);return()=>clearTimeout(ae)},[R]),p.useEffect(()=>{var xe;if(!m)return;v([]);const ae=Ab(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=Ab(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 cT(e.newId??dT));const V=K.current,M=ae=>D(UT(ae)),A=(ae,xe,Ae)=>{D(null),I(null),xe(V.idFor(ae)).then(Ve=>{V.settle(ae,{ok:!0}),Ae(Ve)},Ve=>{V.settle(ae,{ok:!1,error:Ve}),M(Ve)})},O=HA(t),L=p.useRef(e.onSeen);L.current=e.onSeen;const H=p.useRef(null);H.current||(H.current=new fT),p.useEffect(()=>{const ae=H.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),Ve=>{ae.failed(xe,Ae),M(Ve)})});const J=Qh(t,e.occurrences,n),U=VA(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?$A(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?Vp(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(VT,{summary:t,workflowLabel:e.workflowName,triggerSources:e.triggerSources,titleId:i,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace,triggerConnections:e.triggerConnections,mailboxes:e.mailboxes}),s.jsx(YT,{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===go.archive?($(!1),I("Archive requested."),G(['[data-action="archive"]'])):I(iM[ae]??"Command sent.")}),onToggleRevise:()=>{v([]),x(!m)},onAskArchive:()=>$(!0),onCancelArchive:()=>{$(!1),G(['[data-action="archive"]'])}})]}),m&&g?s.jsx(ZT,{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:()=>{x(!1),G(['[data-action="edit"]'])},onSubmit:ae=>{const xe=g.summary,Ae=KA(xe,ae,g.definition);if(Ae===null){v(["Nothing changed."]);return}if("errors"in Ae){v(Ae.errors);return}v([]),A(`revise:${xe.revision}:${JSON.stringify(Ae)}`,async Ve=>{const mt=ae.target&&Ae.target?{...Ae,target:await(e.prepareTarget?e.prepareTarget(Ae.target):DT(Ae.target,e.workflowPickerOptions))}:Ae;return e.onRevise(mt,xe.revision,{command_id:Ve})},()=>{I("Saved; applies from the next run."),x(!1),G(['[data-action="edit"]'])})}}):e.definition?s.jsx(HT,{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," · ",Dw(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:qS[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(Br,{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(sM,{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 Ve;D(null);try{Promise.resolve((Ve=e.onOpenResource)==null?void 0:Ve.call(e,Ae)).catch(M)}catch(mt){M(mt)}}:void 0,discussOpen:E===ae.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(Ae,Ve,mt)=>{D(null),e.onAnswerWait(Ae,Ve,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,Ve)=>A(`discuss:${Ae}:${Ve}`,mt=>e.onDiscuss(Ae,Ve,{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 sN=72;function aM(e,t=sN){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 c=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>c&&(c=m)}return c<=0?r:r.map(l=>l/c)}function Q_(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 lM(e,t,n){return!(t>0)||!(n>0)?0:Math.min(n,Math.max(0,e/t*n))}function cM(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 c=null;try{const l=await(await fetch(e)).arrayBuffer();c=new o;const d=await c.decodeAudioData(l);i&&r({peaks:aM(d.getChannelData(0)),note:""})}catch(l){i&&r({peaks:null,note:`Waveform unavailable: ${l instanceof Error?l.message:String(l)}`})}finally{c&&c.close().catch(()=>{})}})(),()=>{i=!1}},[e,t]),n}function Tg(e){const t=p.useRef(null),n=p.useRef(null),[r,i]=p.useState(!1),[o,c]=p.useState(0),[l,d]=p.useState(null),[h,m]=p.useState(""),{peaks:_,note:g}=cM(e.src,e.peaks),y=_??new Array(sN).fill(0),x=l&&l>0?Math.min(1,o/l):0,k=e.name?`Audio ${e.name}`:"Audio",v=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,c(S))},[]),$=S=>{var D;const P=(D=n.current)==null?void 0:D.getBoundingClientRect();!P||!l||N(lM(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(),v())};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=>c(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:v,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":`${Q_(o)} of ${Q_(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<=x;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:[Q_(o)," / ",Q_(l)]}),h?s.jsx("p",{className:"af-audio__error",role:"alert",children:h}):null]})}const pu=e=>new Set(e.split(/\s+/).filter(Boolean)),uM=pu("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"),dM=pu("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"),fM=pu("if then else elif fi for while do done case esac in function return export local readonly set unset echo exit source"),hM=pu("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"),Ib=pu("true false null yes no on off"),mM={c:{line:["//"],block:["/*","*/"],strings:['"',"'","`"],keywords:uM},python:{line:["#"],strings:['"',"'"],triple:!0,keywords:dM},shell:{line:["#"],strings:['"',"'"],keywords:fM},sql:{line:["--"],block:["/*","*/"],strings:["'",'"'],keywords:hM},data:{line:["#"],strings:['"',"'"],keywords:Ib},json:{line:[],strings:['"'],keywords:Ib},css:{line:[],block:["/*","*/"],strings:['"',"'"],keywords:pu("")},markup:{line:[],block:["<!--","-->"],strings:['"',"'"],keywords:pu("")}},_M={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 ix(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 _M[i]||""}const pM=e=>e>="0"&&e<="9",gM=e=>/[A-Za-z_$]/.test(e),Ob=e=>/[A-Za-z0-9_$]/.test(e);function rN(e,t){const n=String(e??""),r=mM[t];if(!r)return n?[{kind:"plain",text:n}]:[];const i=[];let o="";const c=(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;c("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;c("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),x=y===-1?n.length:y+3;c("string",n.slice(l,x)),l=x;continue}let _=l+1;for(;_<n.length&&n[_]!==d&&(d==="`"||n[_]!==`
64
+ `);)_+=n[_]==="\\"?2:1;const g=Math.min(n.length,_+1);c("string",n.slice(l,g)),l=g;continue}if(pM(d)&&!(l>0&&Ob(n[l-1]))){let m=l+1;for(;m<n.length&&/[0-9a-fA-FxXoObB._]/.test(n[m]);)m+=1;c("number",n.slice(l,m)),l=m;continue}if(gM(d)){let m=l+1;for(;m<n.length&&Ob(n[m]);)m+=1;const _=n.slice(l,m),g=t==="sql"?r.keywords.has(_.toLowerCase()):r.keywords.has(_);c(g?"keyword":"plain",_),l=m;continue}c("plain",d),l+=1}return o&&i.push({kind:"plain",text:o}),i}function ep({text:e,language:t="",lineNumbers:n=!0,className:r,ariaLabel:i}){const o=ix(t),c=rN(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?yM(c).map((d,h)=>s.jsxs("span",{className:"af-code__line","data-line":h+1,children:[d.map((m,_)=>Pb(m,_)),`
66
+ `]},h)):c.map((d,h)=>Pb(d,h))})})}function Pb(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 yM(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 iN=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Oh=6e4,Ph=60*Oh,tp=24*Ph;function Sm(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)?Sm(Number(t)):Date.parse(t)}function Db(e){return e<10?`0${e}`:String(e)}function Fb(e,t){const n=Sm(e);if(!Number.isFinite(n))return"";const r=new Date(n),i=r.getFullYear()===new Date(t).getFullYear();return`${iN[r.getMonth()]} ${r.getDate()}${i?"":`, ${r.getFullYear()}`}`}function ox(e){const t=Sm(e);if(!Number.isFinite(t))return"";const n=new Date(t);return`${iN[n.getMonth()]} ${n.getDate()}, ${n.getFullYear()}, ${Db(n.getHours())}:${Db(n.getMinutes())}`}function Kp(e,t){const n=Sm(e);if(!Number.isFinite(n)||!Number.isFinite(t))return"";const r=t-n;if(r<0){const o=-r;if(o<Oh)return"due now";if(o<Ph)return`in ${Math.round(o/Oh)} min`;if(o<tp)return`in ${Math.round(o/Ph)} h`;const c=Math.round(o/tp);return c<7?`in ${c} ${c===1?"day":"days"}`:Fb(n,t)}if(r<Oh)return"just now";if(r<Ph)return`${Math.floor(r/Oh)} min ago`;if(r<tp)return`${Math.floor(r/Ph)} h ago`;const i=Math.floor(r/tp);return i===1?"yesterday":i<7?`${i} days ago`:Fb(n,t)}const wM=new Set("png jpg jpeg gif webp bmp ico avif".split(" ")),vM=new Set("mp3 wav ogg oga opus m4a aac flac weba".split(" ")),xM=new Set("mp4 m4v webm mov ogv mkv".split(" ")),bM=new Set("mts cts".split(" ")),kM=new Set(["video/mp2t"]),jM=new Set("txt log csv tsv rst adoc org tex diff patch lock".split(" "));function SM(e){const t=String(e||"").split("/").pop()||"",n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():t.toLowerCase()}function Jp(e,t=""){const n=SM(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":wM.has(n)?"image":vM.has(n)?"audio":xM.has(n)?"video":ix(e)||bM.has(n)?"code":jM.has(n)?"text":r.startsWith("image/")&&r!=="image/svg+xml"?"image":r.startsWith("audio/")?"audio":r.startsWith("video/")&&!kM.has(r)?"video":r.startsWith("text/")?"text":["application/javascript","application/xml","application/x-yaml","application/toml"].includes(r)?"code":"binary"}function Hw(e){return e==="markdown"||e==="code"||e==="json"||e==="text"}function Mg(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 NM(e){const t=e.kind??Jp(e.name,e.contentType),n=Mg(e.sizeBytes),r=e.modified!==void 0?Kp(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:ox(e.modified),dateTime:new Date(Sm(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($M,{kind:t,p:e})]})})]})}function $M({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(wh,{});case"audio":return t.url?s.jsx(Tg,{src:t.url,name:t.name}):s.jsx(wh,{});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(wh,{});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(wh,{});case"markdown":return t.renderMarkdown?s.jsx("div",{className:"af-file-viewer__markdown",children:t.renderMarkdown(n)}):s.jsx(ep,{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(ep,{text:r,language:"json"})]})}case"code":return s.jsx(ep,{text:n,language:t.name});case"text":return s.jsx(ep,{text:n,language:"",lineNumbers:!1});default:return s.jsx(wh,{})}}function wh(){return s.jsx("p",{className:"af-file-viewer__muted",children:"No preview for this file type. Use Download to open it."})}function Dh(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 oc(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 zb(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(oc,{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 qn={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."},ti=qn;function CM(e){return e==="any_except_denied"?ti.postureAnyExceptDenied:ti.postureAllowedOnly}function EM(e){return e==="any_except_denied"?ti.postureAnyExceptDeniedHelp:ti.postureAllowedOnlyHelp}function Bb(e){return e==="ro"?ti.accessRead:e==="deny"?ti.accessDenied:ti.accessReadWrite}function AM(e){return e==="gateway"?ti.gatewayHelp:e==="account"?ti.accountHelp:e==="session"?ti.sessionHelp:ti.runHelp}const Ub={deny:0,ro:1,rw:2},$y=["rw","ro","deny"];function TM(e){if(e===null)return{allowed:[...$y],reasons:{}};const t=e==="deny"?ti.capRefused:ti.capReadOnly,n=$y.filter(i=>Ub[i]<=Ub[e]),r={};for(const i of $y)n.includes(i)||(r[i]=t);return{allowed:n,reasons:r}}function MM(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,c=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 x=e==="gateway"?null:c.get(y.path)??null,{allowed:k,reasons:v}=TM(x);return{path:y.path,mode:y.mode,cap:x,allowed:k,reasons:v,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:`${ti.gatewayPrefix} ${l.gateway_summary}`,summary:e==="gateway"?n.summary:l.summary,locked:o}}function RM(e,t){return t==="any_except_denied"?"deny":e==="gateway"?"rw":"ro"}function Nm(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 LM(e,t,n,r){return Nm(e,{...t,folders:t.folders.map(i=>i.path===n?{path:n,mode:r}:i)})}function IM(e,t,n){return Nm(e,{...t,posture:n})}function OM(e,t,n){return Nm(e,{...t,default_mode:n})}function PM(e,t,n,r){const i=String(n).trim();return Nm(e,{...t,folders:[...t.folders,{path:i,mode:RM(e,t.posture)}]})}function DM(e,t,n){return Nm(e,{...t,folders:t.folders.filter(r=>r.path!==n)})}function FM(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 zM(e){let t=String(e||"");for(;t.endsWith("/");)t=t.slice(0,-1);return t}function BM(e="me",t=Xh){return`${zM(t)}/workspace/effective/${encodeURIComponent(e)}`}const Wb=e=>e==="ro"||e==="rw"||e==="deny",UM=e=>e==="ro"||e==="rw",WM=e=>e==="allowed_only"||e==="any_except_denied",qb="The gateway answered with an older workspace model (it needs the round-11 workspace API).";function qM(e){const t=e&&typeof e=="object"?e:{};if("shared_workspace"in t)throw new Error(qb);if(!(WM(t.posture)&&(UM(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"&&Wb(r.mode)&&Wb(r.cap))))throw new Error(`The gateway answered without the effective workspaces (posture, default_mode, folders with cap, summary, gateway_summary). ${qb}`);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 tm(e,t="me",n=Xh){const r=BM(t,n);return async(i,o)=>qM(await e(r,{method:"POST",body:o?{workspace:i,session:o}:{workspace:i}}))}function Rg(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 Vb(e){const t=Rg(e).trim()||"The gateway refused the change.";return`${t}${/[.!?]$/.test(t)?"":"."} ${ti.notSaved}`}const VM=e=>!!e&&typeof e=="object"&&"policy"in e&&"effective"in e;function HM(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 oN(e){sf();const t=e.idPrefix||"af-workspace",[n,r]=p.useState(null),[i,o]=p.useState({}),[c,l]=p.useState(null),[d,h]=p.useState(""),[m,_]=p.useState(null),g=String(e.unavailableReason||"").trim(),y=e.level,x=e.level==="run"?HM(e.value,e.effective):e.state,k=e.level==="run"?e.effective:e.state,v=m&&m.base===k?m.value:x,N=v?MM(y,v):null,$=O=>{if(e.level==="run"){const L=e,H=O.configured===!1?null:{posture:O.posture,default_mode:O.default_mode,folders:O.folders};return Promise.resolve(L.onChange(H))}return e.save(O)};async function E(O,L){if(n!==null||g)return!1;r(O),l(null),o(H=>{const J={...H};return delete J[O],J});try{const H=await $(L);return VM(H)&&_({base:k,value:H}),l(O),!0}catch(H){return o(J=>({...J,[O]:Vb(H)})),!1}finally{r(null)}}const S=O=>i[O]?s.jsx("span",{className:"af-workspace__refusal",role:"alert","data-workspace":"refusal",children:i[O]}):c===O?s.jsx("span",{className:"af-workspace__saved",role:"status","data-workspace":"saved",children:qn.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:Bb(O)}),D=(O,L,H,J,U)=>s.jsx("span",{className:"af-workspace__access",role:"group","aria-label":O,"data-workspace":U,"data-access":L,children:H.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",qn.builtinRefused);if(!O.editable||!v)return P(O.mode);const L=v.policy;return s.jsxs(s.Fragment,{children:[D(`${qn.accessLabel} ${O.path}`,O.mode,["rw","ro","deny"].map(H=>({value:H,text:Bb(H),reason:O.reasons[H]})),H=>void E(O.path,LM(y,L,O.path,H)),"workspace-mode"),s.jsx("button",{type:"button",className:"af-workspace__icon-btn","data-action":"workspace-remove","aria-label":`${qn.remove} ${O.path}`,"data-af-tip":`${qn.remove} ${O.path}`,"aria-disabled":g||n!==null?"true":void 0,onClick:()=>g||n!==null?void 0:void E(O.path,DM(y,L,O.path)),children:s.jsx(qe,{name:"x",size:16})})]})};async function I(O){if(!v||!N||!N.canAdd)return;const L=O.trim();L&&await E("add",PM(y,v.policy,L))&&h("")}async function W(){if(!e.choose||n!==null||g)return;let O;try{O=await e.choose()}catch(L){o(H=>({...H,add:Vb(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"):[],V=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"?qn.followGateway:qn.useDefault,A=y==="account"?qn.followGatewayHelp:qn.useDefaultHelp;return s.jsx(Dh,{id:t,className:`af-workspace af-workspace--${y}${e.className?` ${e.className}`:""}`,title:y==="gateway"?qn.gatewayTitle:qn.title,help:AM(y),children:e.loadError?s.jsx("p",{className:"af-workspace__refusal",role:"alert","data-workspace":"load-error",children:e.loadError}):!N||!v?s.jsx("p",{className:"af-workspace__note","data-workspace":"loading",children:qn.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(Fi,{variant:"row",label:M,description:A,checked:N.following,busy:n==="follow",unavailableReason:g||(N.locked?qn.locked:null),reasonVisible:!1,describedBy:g?`${t}-blocked`:void 0,action:y==="account"?"workspace-follow-gateway":"workspace-use-default",onChange:O=>void E("follow",FM(v,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(qn.postureLabel,N.posture,[{value:"allowed_only",text:qn.postureAllowedOnly},{value:"any_except_denied",text:qn.postureAnyExceptDenied}],O=>void E("posture",IM(y,v.policy,O)),"workspace-posture"),s.jsx("span",{className:"af-workspace__note","data-workspace":"posture-help",children:EM(N.posture)}),S("posture")]}),s.jsxs("ul",{className:"af-workspace__list","aria-label":qn.title,"data-workspace":"list",children:[G.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-allowed",children:qn.allowedTitle}):null,G.map(V),K.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-refused",children:qn.deniedTitle}):null,K.map(V),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:qn.everythingElse}),s.jsx("span",{className:"af-workspace__controls",children:N.everythingElse.editable?D(`${qn.accessLabel} ${qn.everythingElse}`,N.everythingElse.mode,[{value:"rw",text:qn.accessReadWrite},{value:"ro",text:qn.accessRead}],O=>void E("everything-else",OM(y,v.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":qn.addPlaceholder,placeholder:qn.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 H={...L};return delete H.add,H}))}}),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:qn.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:qn.choose}):null,S("add")]}):null]}),N.posture==="allowed_only"&&!G.length?s.jsx("p",{className:"af-workspace__note","data-workspace":"empty",children:qn.emptyAllowed}):null,y==="session"||y==="run"?s.jsx("p",{className:"af-workspace__note","data-workspace":"private",children:qn.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 Cy=e=>`${Math.round(e*100)} %`,GM="Safari does not let a page choose the output device: replies play on the system output (change it in the system sound settings).";function KM(e){var D,R,I;const t=!!e.unavailableReason,n=e.outputSelectable??fS(),r=p.useId(),[i,o]=p.useState({devices:[],labelled:!0}),[c,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}),_=Gd(h.reply_volume),g=h.reply_muted===!0,y=e.showMute!==!1||g,x=e.listDevices||iS,k=p.useRef(x);k.current=x;const v=()=>{n&&k.current("audiooutput").then(W=>d.current&&o(W)).catch(()=>d.current&&o({devices:[],labelled:!1}))};p.useEffect(()=>{t||v()},[n,t,e.devicesKey]);const N=()=>{l({text:"Playing a short chime…",tone:"info"}),U2({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(oc,{label:S,setting:"output-device",help:n?void 0:GM,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(Ur,{ariaLabel:S,placeholder:"System default",value:n?$:"",options:E,disabled:t||!n,searchable:!1,onOpen:v,onChange:W=>m({output_device:W})})}),c.text?s.jsx("p",{className:`af-voice-note af-voice-note--${c.tone}`,role:"status","data-voice-note":"speaker",children:c.text}):null,s.jsxs(oc,{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 (${Cy(_)})`:Cy(_),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":Cy(_)})]})]})}function JM(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 YM(e){const t=JM(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 Ey=e=>`${Math.round(e*100)} %`;function aN(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)||t<=0?1:Math.min(1.5,Math.max(.5,t))}function XM(e){var K,V,M;const t=!!e.unavailableReason,n=p.useId(),[r,i]=p.useState({devices:[],labelled:!0}),[o,c]=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=aS(),y=e.value,x=A=>e.onChange({...y,...A}),k=aN(y.input_gain),v=e.listDevices||iS,N=p.useRef(v);N.current=v;const $=()=>{N.current("audioinput").then(A=>_.current&&i(A)).catch(()=>_.current&&i({devices:[],labelled:!1}))};p.useEffect(()=>{t||$()},[t]);const E=()=>{c(""),B2().then(()=>{var A;$(),(A=e.onDevicesChanged)==null||A.call(e)}).catch(A=>_.current&&c(qp(A)))},S=()=>{d({phase:"recording",message:"Recording 3 seconds — say something.",tone:"info"}),uS({deviceId:y.input_device||"",ms:3e3,gain:k,onLevel:A=>_.current&&m(A)}).then(async({blob:A,peak:O})=>{var L,H,J;if(_.current){if(O<cS){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 dS(A,{deviceId:((L=e.playOn)==null?void 0:L.deviceId)||"",volume:(H=e.playOn)==null?void 0:H.volume}),_.current&&(d({phase:"idle",message:`The microphone works (peak level ${Ey(O)}).`,tone:"ok"}),$(),(J=e.onDevicesChanged)==null||J.call(e))}}).catch(A=>_.current&&d({phase:"idle",message:qp(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=((V=e.labels)==null?void 0:V.gain)||"Input level";return s.jsxs("div",{className:`af-voice-input${e.className?` ${e.className}`:""}`,"data-voice-input":!0,children:[s.jsx(oc,{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(Ur,{ariaLabel:W,placeholder:"System default",value:P,options:D,disabled:t,searchable:!1,onOpen:$,onChange:A=>x({input_device:A})})}),s.jsx(YM,{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(oc,{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":Ey(k),onChange:A=>x({input_gain:Number(A.currentTarget.value)/100})}),s.jsx("span",{className:"af-voice-range__value",children:Ey(k)})]}):null]})}const ZM=["provider","model","voice","profile","speed","quality_preset","instructions"];function QM(e){const t={};for(const n of ZM){const r=e[n];r!==void 0&&r!==""&&r!==null&&(t[n]=r)}return t}function eR(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 tR=[{value:"",label:"Detect automatically"},...Object.keys(mS).map(e=>({value:e,label:_u(e)}))],nR=[{value:"hold",label:"Hold to talk"},{value:"toggle",label:"Tap to talk"}];function sR(e){return[e.provider,e.model,e.profile||e.voice].filter(Boolean).join(" · ")}function rR(e){return[e.stt_provider,e.stt_model].filter(Boolean).join(" · ")}const iR=[{value:"",label:"Gateway default"},{value:"standard",label:"Balanced"},{value:"low",label:"Faster (lower quality)"},{value:"high",label:"Higher quality (slower)"}],Hb=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 oR(e){var be,Me,je,ae,xe,Ae,Ve,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 c=p.useRef(e.fetchLanguages);c.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,x]=p.useState(""),[k,v]=p.useState(0),[N,$]=p.useState(null),E=e.outputSelectable??fS(),S=e.value,P=e.nested?"flat":"card",D=ze=>e.onChange({...S,...ze}),R=Gd(S.reply_volume),I=aN(S.input_gain),W=r.tts!==!1&&!e.ttsSlot,G=r.stt!==!1,K=W||G||!!e.ttsSlot,V=e.voiceLibrary||e.createVoice;p.useEffect(()=>{if(n)return;let ze=!0;return i.current().then(He=>ze&&d(He||{})).catch(()=>ze&&d({})),g||o.current().then(He=>ze&&m({value:He||{},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=c.current;if(n||!ze||r.microphone===!1)return;let He=!0;return ze("stt",M||void 0).then(ct=>He&&$(Array.isArray(ct)?ct.map(Qe=>String(Qe).toLowerCase()).filter(Boolean):[])).catch(()=>He&&$(null)),()=>{He=!1}},[n,A,M,r.microphone]);const O=wb(_.value,"tts",_.failed),L=wb(_.value,"stt",_.failed),H=[(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 He;return ze&&ze.configured?String(((He=ze.hint)==null?void 0:He.sentence)||"").trim():""}).filter(Boolean),U=!!((mt=(Ve=l.controls)==null?void 0:Ve.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:_u(ze)}))]:[...tR],ne=S.stt_language||"";ne&&!z.some(ze=>ze.value===ne)&&z.push({value:ne,label:`${_u(ne)} (saved)`});const se=Ow(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(Dh,{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(zb,{label:"Text → speech",setting:"tts",defaultSummary:O,overrideSummary:sR(S),overrideOwner:t,open:y==="tts",onToggle:()=>x(y==="tts"?"":"tts"),onReset:()=>D({provider:"",model:"",voice:"",profile:""}),disabled:n,children:s.jsx(nA,{value:S,onChange:ze=>e.onChange({...S,...ze}),fetchCatalog:e.fetchCatalog,intro:null,quality:!1,showReset:!1,voiceDefaultLabel:"Gateway default",voiceLibrary:V,previewVoice:e.previewVoice?(ze,He,ct)=>e.previewVoice({...S,...ze},He,ct):void 0,previewOn:te,recordFrom:{deviceId:S.input_device||"",gain:I}})}):null,G?s.jsx(zb,{label:"Speech → text",setting:"stt",defaultSummary:L,overrideSummary:rR(S),overrideOwner:t,open:y==="stt",onToggle:()=>x(y==="stt"?"":"stt"),onReset:()=>D({stt_provider:"",stt_model:""}),disabled:n,children:s.jsx(Gj,{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 Hb(ze.stt_providers).map(He=>({name:He}))},fetchModels:async ze=>{var ct;const He=await i.current(ze);return Hb(((ct=He.stt_models_by_provider)==null?void 0:ct[ze])||He.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,H.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(Dh,{variant:P,title:"Output",children:s.jsx(KM,{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(Dh,{variant:P,title:"Microphone",children:[s.jsx(XM,{value:S,onChange:e.onChange,levelSource:e.levelSource,listDevices:e.listDevices,playOn:te,onDevicesChanged:()=>v(ze=>ze+1),unavailableReason:e.unavailableReason}),s.jsx(oc,{label:"Spoken language",setting:"stt-language",help:"Naming it skips detection: transcription is faster.",children:s.jsx(Ur,{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(oc,{label:"Microphone button",setting:"capture-mode",children:s.jsx(Ur,{ariaLabel:"Microphone button",value:se,options:nR,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(Fi,{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(Dh,{variant:P,title:"Replies",children:[s.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"read-aloud",children:s.jsx(Fi,{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(oc,{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(Ur,{ariaLabel:"Voice latency",placeholder:"Gateway default",value:U&&S.quality_preset||"",options:iR,disabled:n||!U,searchable:!1,onChange:ze=>D({quality_preset:ze})})})]}):null]})}function Lg(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 aR(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function lR(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 cR(e){return e.endsWith(`
68
+ `)?e:`${e}
69
+ `}function uR(e){return String(e||"").trimStart().startsWith("```")}function lN(e,t){const r=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const i of e){const o=lR(i);r.push(`## ${o}`,"");const c=String(i.content||""),l=Lg(c);l!==null&&!uR(c)?r.push("```json",aR(l).trimEnd(),"```",""):r.push(cR(c).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 il(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 cN(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),c=document.createElement("a");c.href=o,c.download=t,document.body.appendChild(c),c.click(),c.remove(),window.setTimeout(()=>URL.revokeObjectURL(o),1e3)}const dR=3,fR=Number.MAX_SAFE_INTEGER;function uN(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function dN(e){return Array.isArray(e)}function hR(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Ld({kind:e,children:t}){return s.jsx("span",{className:`pc-json-token ${e}`,children:t})}function mR(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(Ld,{kind:"string",children:t})}function _R(e,t,n){return e===null?s.jsx(Ld,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(mR,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?s.jsx(Ld,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx(Ld,{kind:"boolean",children:e?"true":"false"}):s.jsx(Ld,{kind:"string",children:JSON.stringify(String(e))})}function pR(e){return dN(e)?e.length===1?"1 item":`${e.length} items`:uN(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function fN(e){const{label:t,value:n,depth:r,collapseAfterDepth:i,expansionMode:o,expansionVersion:c,trailingComma:l}=e,d=r*14,h=uN(n),m=dN(n),_=h||m,g=r<i,[y,x]=p.useState(g);p.useEffect(()=>{x(g)},[g,c]);const k=t?s.jsxs(s.Fragment,{children:[s.jsx(Ld,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!_)return s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:d},children:[k,_R(n,o,c),l?",":""]});const v=m?"[":"{",N=m?"]":"}",$=pR(n),E=y?`${v}`:`${v}…${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=>x(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(fN,{label:P.label,value:P.value,depth:r+1,collapseAfterDepth:i,expansionMode:o,expansionVersion:c,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 gR(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 hr(e){const{value:t,className:n,showCopy:r=!0}=e,[i,o]=p.useState({mode:"folded",version:0}),[c,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):dR,h=i.mode==="unfolded"?fR:d,m=p.useMemo(()=>typeof t=="string"?gR(t):t,[t]),_=p.useMemo(()=>hR(t),[t]),g=["pc-json-viewer",n].filter(Boolean).join(" ");p.useEffect(()=>{o(x=>({mode:"folded",version:x.version+1}))},[m]);const y=()=>{o(x=>({mode:x.mode==="unfolded"?"folded":"unfolded",version:x.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 il(_).then(x=>{l(x?"copied":"failed"),window.setTimeout(()=>l("idle"),2e3)}),children:c==="copied"?"Copied":c==="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(fN,{value:m,depth:0,collapseAfterDepth:h,expansionMode:i.mode,expansionVersion:i.version,trailingComma:!1})})]})}function yR({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=rN(e,ix(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 c=await il(e);r(c?"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((c,l)=>c.kind==="plain"?s.jsx(Ee.Fragment,{children:c.text},l):s.jsx("span",{className:`af-code__${c.kind}`,children:c.text},l))})})]})}function vh(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 c=-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&&(c===-1||g<c||g===c&&y.length>l.length)&&(c=g,l=y)}if(c===-1||!l){r.push(n.slice(o));break}c>o&&r.push(n.slice(o,c));const d=t.hits===0&&t.id?t.id:void 0,h=n.slice(c,c+l.length);r.push(s.jsx("span",{id:d,className:t.className,children:h},`hl:${t.hits}`)),t.hits+=1,o=c+l.length}return r}function hN(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const Gw="http://same-origin.invalid/";function wR(e){try{const t=new URL(e,Gw);return t.protocol==="http:"&&t.origin===new URL(Gw).origin}catch{return!1}}function mN(e){const t=String(e||"").trim();return hN(t)??(t&&wR(t)?t:void 0)}let au=null;function vR(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??Gw;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 _N(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 Gb(e){return!!e&&/[\p{L}\p{N}]/u.test(e)}function Qa(e,t){const n=[],r=String(e??"");let i=0,o="";const c=()=>{if(o){for(const l of vh(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),_=mN(r.slice(d+2,h));if(_&&au&&!au(_)){c(),n.push(_N(`img:${i}`,_,m)),i=h+1;continue}if(_){c(),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?vh(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),_=hN(r.slice(d+2,h));if(_){c(),n.push(s.jsx("a",{className:"pc-md_link",href:_,target:_.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:Qa(m,t)},`link:${i}`)),i=h+1;continue}}}}if(l==="`"){const d=r.indexOf("`",i+1);if(d!==-1){c();const h=r.slice(i+1,d);n.push(s.jsx("code",{children:t?vh(h,t):h},`code:${i}`)),i=d+1;continue}}if(l==="_"&&!Gb(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]||" ")||Gb(r[m+h])||h===1&&r[m+1]==="_");)m=r.indexOf(d,m+1);if(m!==-1&&m>i+h){c();const _=r.slice(i+h,m),g=Qa(_,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){c();const h=r.slice(i+2,d);n.push(s.jsx("strong",{children:t?vh(h,t):h},`bold:${i}`)),i=d+2;continue}}if(l==="*"&&r[i+1]!=="*"){const d=r.indexOf("*",i+1);if(d!==-1){c();const h=r.slice(i+1,d);n.push(s.jsx("em",{children:t?vh(h,t):h},`em:${i}`)),i=d+1;continue}}o+=l,i+=1}return c(),n}function xR(e){return String(e??"").replace(/\r\n/g,`
72
+ `).replace(/\r/g,`
73
+ `).split(`
74
+ `)}function Ep(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 bR(e){const t=[];for(const i of e){const o=Ep(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 c=o.node.items,l=c[c.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 c=r.length>0?r[r.length-1]:null,l={ordered:i.ordered,start:i.start,items:[]};if(c){const d=c.node.items,h=d[d.length-1];h?h.children.push(l):c.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 c={ordered:i.ordered,start:i.start,items:[]};n.push(c),r.push({indent:i.indent,node:c}),o=r[r.length-1]}o.node.items.push({content:i.content,children:[]})}return n}function pN(e,t,n){const r=e.items.map((i,o)=>s.jsxs("li",{children:[Qa(i.content,t),i.children.map((c,l)=>pN(c,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 kR(e,t,n){return bR(e).map((r,i)=>pN(r,t,`${n}:${i}`))}function Kb(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 Jb(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 Yb=/^(#{1,5})\s+(.*)$/;function Xb(e){return e.trim().startsWith("```")}function Zb(e){return e.trimStart().startsWith(">")}function Ni(e){const t=au;au=e.images==="link"?e.inlineImage||vR:null;try{return jR(e)}finally{au=t}}function jR({text:e,className:t,highlight:n,highlights:r,highlightClassName:i,highlightId:o}){const c=xR(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(;_<c.length;){const y=String(c[_]??"");if(!y.trim()){_+=1;continue}const x=y.trim();if(/^([-_*])(\s*\1){2,}$/.test(x)){l.push(s.jsx("hr",{className:"pc-md_hr"},`hr:${_}`)),_+=1;continue}const k=y.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(k){const $=mN(k[2]||"");if($&&au&&!au($)){l.push(s.jsx("p",{className:"pc-md_p",children:_N(`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:Qa(E,m)}):null]},`figure:${_}`)),_+=1;continue}}if(Xb(y)){const E=y.trim().replace(/```/g,"").trim(),S=[];for(_+=1;_<c.length&&!String(c[_]??"").trim().startsWith("```");)S.push(String(c[_]??"")),_+=1;_<c.length&&(_+=1);const P=S.join(`
75
+ `);l.push(s.jsx(yR,{code:P,lang:E},`pre:${_}`));continue}const v=y.match(Yb);if(v){const $=v[1].length,E=v[2]||"",S=Qa(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(Zb(y)){const $=[];for(;_<c.length&&String(c[_]??"").trimStart().startsWith(">");){const S=String(c[_]??"").trimStart();$.push(S.replace(/^>\s?/,"")),_+=1}l.push(s.jsx("blockquote",{className:"pc-md_quote",children:$.map((E,S)=>s.jsxs(Ee.Fragment,{children:[Qa(E,m),S<$.length-1?s.jsx("br",{}):null]},`q:${_}:${S}`))},`quote:${_}`));continue}if(y.includes("|")&&_+1<c.length&&Jb(String(c[_+1]??""))){const $=Kb(y),E=Math.max(1,$.length),S=[];for(_+=2;_<c.length;){const P=String(c[_]??"");if(!P.trim()||!P.includes("|"))break;const D=Kb(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:Qa(P,m)},`th:${_}:${D}`))})}),s.jsx("tbody",{children:S.map((P,D)=>s.jsx("tr",{children:P.map((R,I)=>s.jsx("td",{children:Qa(R,m)},`td:${_}:${D}:${I}`))},`tr:${_}:${D}`))})]})},`table:${_}`));continue}if(Ep(y)){const $=[];for(;_<c.length;){const E=String(c[_]??"");if(!E.trim()||E.trimStart().startsWith("```"))break;if(Ep(E)||/^\s{2,}\S/.test(E)){$.push(E),_+=1;continue}break}l.push(s.jsx(Ee.Fragment,{children:kR($,m,`list:${_}`)},`list:${_}`));continue}const N=[];for(;_<c.length&&String(c[_]??"").trim()&&!(N.length>0&&Ep(String(c[_]??"")));){const $=String(c[_]??"");if(N.length>0&&(Yb.test($)||Xb($)||Zb($))||N.length>0&&$.includes("|")&&_+1<c.length&&Jb(String(c[_+1]??"")))break;N.push($),_+=1}l.push(s.jsx("p",{className:"pc-md_p",children:N.map(($,E)=>s.jsxs(Ee.Fragment,{children:[Qa($,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 gN(e){const t=String(e.text??""),n=p.useMemo(()=>Lg(t),[t]),r=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?s.jsx("div",{className:r,children:s.jsx(hr,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?s.jsx("div",{className:r,children:e.renderMarkdown(t)}):s.jsx("div",{className:r,children:s.jsx(Ni,{text:t,images:e.images,inlineImage:e.inlineImage})})}const SR=new Set("html htm xhtml xht shtml svg svgz xml xsl xslt mht mhtml".split(" ")),NR=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 yN(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 $R(e,t){const n=String(t||"").split("/").pop()||"",r=n.lastIndexOf(".");if(r>0&&SR.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:NR.has(i)}function CR(e){const t=n=>!!n&&(!yN(n)||$R(e.contentType,e.name));if(t(e.href))return e.href;if(t(e.src))return e.src}const Qb=1024*1024,ER="1 MiB",AR=25*1024*1024,wN=(e,t)=>`${wt(`runs/${encodeURIComponent(e)}/workspace`)}/content?${new URLSearchParams({path:t})}`;function TR(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 MR(e,t,n){var h;const r=new TextDecoder;let i="",o=0;const c=(h=e.body)==null?void 0:h.getReader();if(c){for(;o<t;){const{done:m,value:_}=await c.read();if(m)break;const g=_.subarray(0,t-o);o+=g.length,i+=r.decode(g,{stream:!0})}await c.cancel().catch(()=>{})}else i=(await e.text()).slice(0,t),o=i.length;const l=TR(e)??n,d=l!==void 0?l>o:o>=t;return{text:i,received:o,total:l,partial:d}}function RR(e){return`Showing the first ${ER} of ${e!==void 0?Mg(e):"a file of unknown size"}; download for the rest.`}function LR(e){try{return decodeURIComponent(e)}catch{return e}}function IR(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(LR(m));return h.length?wN(t,h.join("/")):null},c=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,_),x=d.slice(_+2,g).trim(),k=x.startsWith(r)?x:o(x);h+=k?`![${y}](${k})`:`[image: ${y||x}](${x})`,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:c(d)).join(`
77
+ `)}function OR(e,t,n,r){const[i,o]=p.useState({status:"idle"});return p.useEffect(()=>{if(!n||!t){o({status:"idle"});return}const c=new AbortController;let l="";const d=Jp(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>AR){o({status:"error",kind:d,message:`Too large to preview (${Mg(n.size_bytes)}); use Download.`});return}o({status:"loading",kind:d});const h=Hw(d);return(async()=>{var m;try{const _=await e(wN(t,n.path),{signal:c.signal,...h?{headers:{Range:`bytes=0-${Qb-1}`}}:{}});if(!_.ok)throw new Error(`Preview failed (HTTP ${_.status}): ${await _.text().catch(()=>"")||_.statusText||"no reason given"}`);const g=_.headers.get("content-type")||"",y=Jp(n.name,g);if(Hw(y)){const x=await MR(_,Qb,n.size_bytes);if(c.signal.aborted)return;o({status:"ready",kind:y,contentType:g,text:y==="markdown"?IR(x.text,t,n.path):x.text,partial:x.partial,total:x.total});return}if(y==="image"||y==="audio"||y==="video"||y==="pdf"){const x=await _.blob();if(c.signal.aborted)return;l=URL.createObjectURL(x.type?x:new Blob([x],{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(()=>{})),c.signal.aborted||o({status:"ready",kind:"binary",contentType:g,partial:!1})}catch(_){c.signal.aborted||o({status:"error",kind:d,message:String((_==null?void 0:_.message)||_)})}})(),()=>{c.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 vN(e){const{markdownImages:t,inlineImage:n,renderMarkdown:r,...i}=e;return s.jsx(NM,{...i,nowMs:e.nowMs??Date.now(),renderMarkdown:r||(o=>s.jsx(Ni,{text:o,...t?{images:t}:{},...n?{inlineImage:n}:{}}))})}function PR(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:RR(e.total)}:{}}}function Fh(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Zl(e){return typeof e=="string"?e.trim():""}function DR(e){var i;const t=Fh(e);if(!t)return null;const n=Fh(t.sandbox);if(n&&Zl(n.kind))return n;const r=Fh((i=Fh(t.output))==null?void 0:i.sandbox);return r&&Zl(r.kind)?r:null}function Kw(e){const t=DR(e);if(!t)return null;const n=Zl(t.kind),r=Zl(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=[],c=Zl(t.private_workspace);c&&o.push({path:c,mode:"Read & write",private:!0});for(const d of Array.isArray(t.allowed)?t.allowed:[]){const h=Fh(d),m=Zl(h==null?void 0:h.path);m&&o.push({path:m,mode:Zl(h==null?void 0:h.mode)==="ro"?"Read-only":"Read & write"})}for(const d of Array.isArray(t.refused)?t.refused:[]){const h=Zl(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 xN({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 Ay=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,bi=e=>typeof e=="string"?e.trim():typeof e=="number"?String(e):"";function FR(e){const t=bi(e==null?void 0:e.decision);if(t!=="auto_approved"&&t!=="denied")return null;const n=Ay(e==null?void 0:e.policy),r=Ay(n==null?void 0:n.set_by),i=bi(r==null?void 0:r.user_id)||bi(r==null?void 0:r.client),o=typeof(n==null?void 0:n.revision)=="number"?n.revision:void 0,c={decision:t,...bi(e==null?void 0:e.source)?{source:bi(e==null?void 0:e.source)}:{},...o!==void 0?{revision:o}:{},...i?{setBy:i}:{},...bi(n==null?void 0:n.set_at)?{setAt:bi(n==null?void 0:n.set_at)}:{}},l=(Array.isArray(e==null?void 0:e.tool_calls)?e.tool_calls:[]).map(d=>Ay(d)).filter(d=>!!(d&&bi(d.call_id))).map(d=>({callId:bi(d.call_id),name:bi(d.name),...bi(d.matched)?{matched:bi(d.matched)}:{}}));return l.length?{provenance:c,calls:l}:null}function Yp(e){if(e.decision==="denied")return"Denied by this chat's policy";const t=e.setAt?ox(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 e0(e){const t=new Map;for(const n of e||[]){const r=bi(n==null?void 0:n.name);if(!r)continue;const i=bi(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 bN(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function zR(e){const t=bN(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(([c])=>c===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 kN({tool:e,showCopy:t=!0}){const[n,r]=p.useState(!1),i=bN(e.arguments),o=zR(e.arguments),c=["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}),c]}):"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:Yp(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:[Yp(e.policy),e.policy.matched?` · matched ${e.policy.matched}`:""]}):null,s.jsx(xN,{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 il(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(hr,{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(hr,{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(hr,{value:e.output})})]}):null]})]})}function jN({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(kN,{tool:r,showCopy:t},r.id))]})}const Cr="not reported",Qr=e=>e===void 0?Cr:Math.round(e).toLocaleString(),ki=e=>{if(e===void 0)return Cr;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`},SN=e=>e===void 0?Cr:`${Math.round(e).toLocaleString()} tok/s`,BR=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",lu=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,UR=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function WR(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 Xp(e){const t=[],n=(e.models||[]).map(UR),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 qR(e){const t=e.modelCalls||[],n=[],r=[{label:"Input",value:Qr(e.inputTokens)},{label:"Output",value:Qr(e.outputTokens)}];if(e.reasoningTokens!==void 0&&r.push({label:"Reasoning",value:Qr(e.reasoningTokens),hint:"part of output"}),r.push({label:"Total",value:Qr(e.totalTokens)}),n.push({heading:`Usage · ${lu(e.llmCalls,"model call")}`,rows:r}),e.measuredCacheCalls){const o=e.cachedTokens||0,c=e.fedTokens||0,l=[{label:"Reused from cache",value:`${Qr(o)}${o+c?` (${BR(o,o+c)})`:""}`},{label:"Newly processed",value:Qr(e.fedTokens)},{label:"Outcome",value:WR(t.map(d=>d.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Cr},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Cr}];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:Cr}]});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:`${Qr(i[0].inputTokens)} tokens`}]}):i.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${Qr(i[0].inputTokens)} → ${Qr(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,c)=>[String(c+1),Qr(o.inputTokens),o.cachedTokens===void 0?"—":Qr(o.cachedTokens),o.fedTokens===void 0?"—":Qr(o.fedTokens),Qr(o.outputTokens),o.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Cr:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:Xp(e)}}function np(e,t,n,r){if(e===void 0)return Cr;const i=[ki(e)];return t!==void 0&&i.push(`${t.toLocaleString()} ${r}${n!==void 0?` at ${SN(n)}`:""}`),i.join(" · ")}function VR(e){var h,m,_;const t=e.modelCalls||[],n=[],r=e.durationMs,i=[{label:"Wall clock",value:ki(r)}];if(i.push({label:"Model",value:e.genTimeMs===void 0?Cr:`${ki(e.genTimeMs)} · ${lu(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),i.push({label:"Tools",value:e.toolTimeMs!==void 0?`${ki(e.toolTimeMs)} · ${lu(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Cr:"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?ki(g):"overlaps (parallel runs)",hint:"wall − model − tools: routing, hand-offs, model load"})}n.push({heading:"Turn",rows:i});const o=[],c=e.ttftCalls||0,l=e.promptPhaseCalls||0;e.promptPhaseMs!==void 0?o.push({label:c&&c===l?"Prefill (TTFT)":"Prefill",value:np(e.promptPhaseMs,e.promptPhaseNewTokens,e.promptPhaseTokensPerSecond,"new tok"),hint:c===l?"measured time to first token":c?`TTFT measured on ${c} of ${l}; rest from provider rate`:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0&&e.prefillNewTokensPerSecond!==void 0?o.push({label:"Prefill",value:np(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?o.push({label:"Prefill",value:`${ki(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${SN(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):o.push({label:"Prefill",value:Cr}),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?np(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):np(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(x=>x.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?Cr:`${Math.round(d.acceptanceRate*100)}% · ${Qr(d.acceptedTokens)} of ${Qr(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`:Cr}${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:`${ki(e.toolTimeMs)} · ${lu(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${ki(e.slowestToolBatch.ms)} · ${NN(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?"—":`${ki(g.promptMs)}${g.promptSource==="rate"?"*":""}`,g.promptNewTokensPerSecond===void 0?"—":Math.round(g.promptNewTokensPerSecond).toLocaleString(),g.generationMs===void 0?"—":ki(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?Cr:`${ki(r)} wall clock`,sections:n,footer:Xp(e)}}function NN(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${lu(e.calls,"call")} (${e.tools.join(", ")})`}function HR(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:Xp(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?`${ki(d.ms)}${d.sharedBatches?" +shared":""}`:d.sharedBatches?"shared":Cr])},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 c=[{label:"Tool time",value:e.toolTimeMs===void 0?Cr:`${ki(e.toolTimeMs)} · ${lu(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&c.push({label:"Slowest batch",value:`${ki(e.slowestToolBatch.ms)} · ${NN(e.slowestToolBatch)}`}),t.push({heading:"Timing",rows:c,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:`${lu(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:Xp(e)}}function Ty(e,t){return e==="tokens"?qR(t):e==="time"?VR(t):HR(t)}function GR(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===Cr?"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((c,l)=>s.jsx("td",{children:c},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 Ja=8;function KR(e){const[t,n]=p.useState(!!e.defaultOpen),[r,i]=p.useState(null),o=p.useRef(null),c=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 v=o.current,N=c.current;if(!v||!N)return;const $=v.getBoundingClientRect(),E=N.offsetWidth,S=N.offsetHeight,P=window.innerWidth,D=window.innerHeight,R=$.top-Ja-S,I=$.bottom+Ja,W=R>=Ja?R:I+S<=D-Ja?I:Math.max(Ja,D-Ja-S),G=Math.min(Math.max(Ja,$.left),Math.max(Ja,P-Ja-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=v=>{v.key==="Escape"&&n(!1)};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]);const g=typeof e.onClick=="function",y=g?"button":"span",x=t?s.jsx(GR,{detail:e.detail,id:d,panelRef:c,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})]}),x&&typeof document<"u"?bg.createPortal(x,document.body):x]})}function JR(e){const t=e.totalTokens!==void 0?Ty("tokens",e):null,n=Ty("tools",e),r=e.durationMs!==void 0?Ty("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 YR(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 XR=new Set(["blob:","data:","http:","https:"]);function Zp(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return XR.has(new URL(t,n).protocol)?t:void 0}catch{return}}function $N(e,t){return yN(e)?{href:e,download:t||"file"}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function ZR({item:e,onOpen:t,markdown:n}){const[r,i]=p.useState(!1),o=Zp(e.src),c=String(e.name||e.label||"").trim()||"File",l=CR({href:e.href?Zp(e.href):void 0,src:o,contentType:e.contentType,name:e.name||e.label}),d=Jp(c,e.contentType),h=Hw(d),m=typeof e.text=="string";if(!o&&!l&&!m)return null;const _=Mg(e.size),g=String(e.label||"").trim()||c;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:c,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",...$N(l,String(e.name||"").trim()||g),children:"Raw file"}):null]}),r&&!t?s.jsx(vN,{className:"pc-chat-media__viewer",name:c,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 QR({item:e,onOpenFile:t,markdown:n}){const[r,i]=p.useState(!1);if(e.kind==="file")return s.jsx(ZR,{item:e,onOpen:t,markdown:n||{}});const o=Zp(e.src),c=e.href?Zp(e.href):void 0,l=e.kind==="image"||e.kind==="audio"||e.kind==="video"?e.kind:null;if(!l||!o&&!c)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(Tg,{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",c?"; open the raw file with the link.":"."]}):null,c?s.jsx("figcaption",{className:"pc-chat-media__caption",children:s.jsx("a",{className:"pc-chat-media__link",...$N(c,String(e.name||"").trim()||h),children:h})}):null]})}function ax(e){var D,R;const t=e.message,n=p.useMemo(()=>YR(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,c]=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,x=Array.isArray(e.attachments)?e.attachments:Array.isArray(t.attachments)?t.attachments:[],k=t.statistics,v=t.stats,N=p.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(v)?v:k?JR(k):[],[e.stats,v,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(kN,{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 il(String(t.content||""));c(I?"copied":"failed"),l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(()=>c("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(gN,{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(QR,{item:I,onOpenFile:e.onOpenMedia,markdown:{renderMarkdown:e.renderMarkdown,images:e.images,inlineImage:e.inlineImage}},I.id||`${I.kind}:${I.src}:${W}`))}):null,x.length?s.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:x.slice(0,24).map((I,W)=>{const G=String(I.label||"").trim()||"attachment",K=String(I.target||"").trim(),V=String(I.title||"").trim(),M=!!I.disabled||typeof I.onClick!="function";return s.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:V||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(KR,{label:G,detail:I.detail,icon:I.icon,onClick:I.onClick},I.id||`${G}:${W}`);const K=String(I.title||"").trim(),V=typeof I.onClick=="function",M=V?"button":"span";return s.jsxs(M,{...V?{type:"button"}:{},className:["pc-chat-stat",V?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:K||void 0,onClick:V?()=>{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 eL(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function lx(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,c]=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 _=()=>{c(eL(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 x;const g=m[0],y=String(g.id||"")||String(g.ts||"")+":"+String(g.role||"")+":"+_;return g.toolActivity?s.jsx(jN,{tools:m.map(k=>k.toolActivity),showCopy:(x=e.messageProps)==null?void 0:x.showCopy},y):s.jsx(ax,{message:g,...e.messageProps||{}},y)}),e.after,s.jsx("div",{ref:i})]})}const cx=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,c=!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(),c&&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:!c,onClick:()=>t.onSubmit(),children:o?t.busyLabel||"Thinking…":t.sendLabel||"Send"})]}),t.overlay]})});function zh(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function t0(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 n0(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function ux(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 c=r[o];if(!c||c.kind!=="file")continue;const l=typeof c.webkitGetAsEntry=="function"?c.webkitGetAsEntry():null,d=typeof c.getAsFile=="function"?c.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 CN(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 tL={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function xh(e){return String(e).padStart(2,"0")}function nL(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=tL[String(t||"").toLowerCase()]||r.split(".").pop()||"bin",o=`${n.getFullYear()}-${xh(n.getMonth()+1)}-${xh(n.getDate())} at ${xh(n.getHours())}.${xh(n.getMinutes())}.${xh(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!r?"Pasted image":"Pasted file"} ${o}.${i}`}function EN(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}=ux(e);return r.map(i=>{const o=nL(i.name,i.type,t);return o===i.name?i:new File([i],o,{type:i.type,lastModified:i.lastModified})})}class sL{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 Bh="llm.delta",Ed="llm.delta_end";function rL(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Jc(e){return typeof e=="string"&&e.trim()!==""}function iL(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function AN(e){return"reason"in e}function TN(e,t){const n=rL(e),r=n==null?void 0:n.kind,i=t||(typeof r=="string"&&r?r:n&&"reason"in n?Ed:Bh),o=d=>{throw new Error(`Malformed ${i} event from the gateway: ${d}`)};if(t!==void 0&&t!==Bh&&t!==Ed&&o(`unknown event name ${JSON.stringify(t)}`),!n)return o("the payload is not an object");r!==void 0&&r!==Bh&&r!==Ed&&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`),Jc(n.run_id)||o("run_id is missing"),Jc(n.call_id)||o("call_id is missing"),iL(n.seq)||o("seq is not a non-negative integer");const c=t||r?(t||r)===Ed:"reason"in n;n.root_run_id!==void 0&&!Jc(n.root_run_id)&&o("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!Jc(n.parent_run_id)&&o("parent_run_id is neither a run id nor null");const l={run_id:n.run_id,...Jc(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...Jc(n.node_id)?{node_id:n.node_id}:{},call_id:n.call_id,seq:n.seq};return c?(["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:Ed,...l,reason:n.reason,...Jc(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:Bh,...l,text:n.text,channel:n.channel,snapshot:n.snapshot})}function oL(e,t){if(e!==Bh&&e!==Ed)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 TN(n,e)}const aL={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 lL(e){return`This reply is not streamed: ${e?aL[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}const dx=e=>wt(`runs/${encodeURIComponent(e)}/workspace`);function cL(e){return dx(e)}function uL(e,t){return`${dx(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function dL(e,t){return`${dx(e)}/content?${new URLSearchParams({path:t})}`}async function rf(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 fL(e,t){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null,r=c=>{throw new Error(`Unexpected /workspace/files response from the gateway: ${c}.`)};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((c,l)=>{const d=c&&typeof c=="object"?c:{};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 hL(e,t,n){const r=await e(cL(t),{signal:n});if(!r.ok)throw await rf(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 mL(e,t,n,r){const i=await e(uL(t,n),{signal:r});if(!i.ok)throw await rf(i,"The folder could not be listed");return fL(await i.json(),n)}async function _L(e,t,n,r){const i=await e(dL(t,n),{signal:r});if(!i.ok)throw await rf(i,"The file could not be read");return await i.blob()}async function pL(e,t,n,r){const i=await hL(e,t,r);return{where:i,listing:i.exists?await mL(e,t,n,r):null}}function gL(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 MN(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 yL(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function wL(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 vL=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function xL(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return vL.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 RN(e,t,n){const r=n==="open"?xL(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 c=document.createElement("a");c.href=o,c.download=t,document.body.appendChild(c),c.click(),c.remove()}window.setTimeout(()=>URL.revokeObjectURL(o),6e4)}async function bL(e,t,n){const r=await e($E(t),{signal:n.signal});if(!r.ok)throw await rf(r,`${n.name} could not be read`);RN(await r.blob(),n.name,n.mode??"open")}function kL(e){const t=String(e||"").split(/[\\/]/).filter(Boolean);return t.length?t[t.length-1]:String(e||"")}function jL(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 SL(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function LN(e){var V;const{fetchGateway:t,runId:n}=e,[r,i]=p.useState({runId:n,path:""}),o=r.runId===n?r.path:"",[c,l]=p.useState(null),[d,h]=p.useState(""),[m,_]=p.useState(""),[g,y]=p.useState(!!n),[x,k]=p.useState(""),[v,N]=p.useState(!1),[$,E]=p.useState(0),[S,P]=p.useState(null),D=S&&S.runId===n&&!e.onSelectFile?S.entry:null,R=OR(t,n,D,`${e.refreshKey??""}:${$}`);p.useEffect(()=>{if(!n)return;const M=new AbortController;return y(!0),h(""),(async()=>{try{const A=await pL(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=c&&c.runId===n?c:null,W=p.useCallback(async M=>{k(M.path),h("");try{RN(await _L(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(NL,{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:x,selectedPath:e.onSelectFile?e.selectedPath:D==null?void 0:D.path,className:e.className,nowMs:K,openingFolder:v,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||SL)(G).then(M=>_(M?"Path copied.":"Could not copy; select the path instead."))}:void 0,onOpenFolder:e.onOpenFolder&&jL(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(vN,{name:D.name,path:D.path,sizeBytes:D.size_bytes,modified:D.mtime,nowMs:K,...PR(R),actions:(V=e.fileActions)==null?void 0:V.call(e,D),onDownload:()=>void W(D),onClose:()=>P(null)}):null})}function NL(e){var o,c,l,d;const t=e.listing?wL(e.listing):"",n=(c=(o=e.where)==null?void 0:o.host)==null?void 0:c.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:kL(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:gL(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:yL(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:MN(h.size_bytes)}),h.mtime!==void 0&&Kp(h.mtime,i)?s.jsx("time",{className:"pc-ws__time",title:ox(h.mtime),"data-meta":"modified",children:Kp(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 $L={registry_scope:"tenant_catalog",bundle_id:"docs-qa",bundle_version:"0.1.1",flow_id:"docsqa001"},IN="docs";function CL(e){return wt(`docs/corpus?${new URLSearchParams({app:String(e||"")})}`)}function My(e){return`${String(e||"app")}-docs-assistant:${nl()}`}function EL(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}),{...$L,session_id:e.sessionId,kind:IN,input_data:t}}function ON(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 AL(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),c=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"}`+(c?` (history window: the most recent ${c.toLocaleString("en-US")} tokens of whole messages).`:".")}async function*TL(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:c,done:l}=await n.read();if(l)break;i+=r.decode(c,{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 ML(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 rc(e,t){if(!e.ok)throw await rf(e,t);return e.json()}function RL(e){const t=e.pollMs??1e3,n=e.timeoutMs??18e4;let r=null;return async(i,o)=>{var x;const{fetchGateway:c,source:l}=e;if(r===null){const k=await c(CL(l.app),{signal:o.signal,headers:{Accept:"application/json"}}),v=await rc(k,`The ${l.name} documentation could not be read, so nothing was asked`),N=typeof(v==null?void 0:v.text)=="string"?v.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 v=new FormData;v.append("session_id",o.sessionId),v.append("file",k,k.name||"upload.bin"),v.append("filename",k.name||"upload.bin"),k.type&&v.append("content_type",k.type);const N=await rc(await c(wt("attachments/upload"),{method:"POST",body:v,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 rc(await c(wt("runs/start"),{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(EL({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 v=await c(wt(`runs/${encodeURIComponent(_)}/ledger/stream?after=0`),{signal:g.signal,headers:{Accept:"text/event-stream"}});if(!v.ok||!v.body)return;let N="",$="";for await(const E of TL(v.body,g.signal)){const S=oL(E.event,E.data);!S||AN(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 ML(t,o.signal);const v=await rc(await c(wt(`runs/${encodeURIComponent(_)}`),{signal:o.signal}),"The docs-qa run could not be read"),N=String((v==null?void 0:v.status)||"").toLowerCase();if(N==="completed"){(x=o.onHistory)==null||x.call(o,(v==null?void 0:v.session_history)??null);const $=ON(v);if(!$)throw new Error(`The docs-qa run ${_} completed without an answer.`);return $}if(N==="failed"||N==="cancelled"){const $=v==null?void 0:v.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 LL(e,t,n={}){const r=new URLSearchParams({root_only:"true",kind:IN,limit:"500",include_ledger_len:"false"}),i=await rc(await e(wt(`runs?${r}`),{signal:n.signal}),"The docs assistant history could not be read"),o=`${String(t||"app")}-docs-assistant:`,c=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=c.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=_),c.set(h,m)}const l=[...c.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,x)=>y.created<x.created?-1:1).map(y=>y.id);let _="";try{const y=await rc(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 IL(e,t,n,r){var o;const i=[];for(const c of t.runIds){const[l,d]=await Promise.all([rc(await e(wt(`runs/${encodeURIComponent(c)}/input_data`),{signal:r}),"A past question could not be read"),rc(await e(wt(`runs/${encodeURIComponent(c)}`),{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-${c}`,role:"user",content:h,ts:String((d==null?void 0:d.created_at)||"")||void 0});const m=ON(d),_=String((d==null?void 0:d.status)||"").toLowerCase();i.push(m?{id:`a-${c}`,role:"assistant",title:n,content:m,ts:String((d==null?void 0:d.updated_at)||"")||void 0}:{id:`a-${c}`,role:"assistant",title:n,level:"warn",content:_==="completed"?"This answer was empty.":`No answer: the run is ${_||"unknown"}.`})}return i}function OL(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:[Kp(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 PL=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml)$/i;function DL(e){const t=p.useRef(null),[n,r]=p.useState(!1),i=!!e.blockedNotice,o=!!e.busy,c=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||!zh((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=ux(h.dataTransfer);m.files.length&&((_=e.onAddFiles)==null||_.call(e,m.files)),m.folders.length&&((g=e.onNotice)==null||g.call(e,CN(m.folders)))},children:[s.jsx(lx,{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(cx,{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=EN(h.clipboardData);m.length&&(h.preventDefault(),(_=e.onAddFiles)==null||_.call(e,m))},leading:c.length?s.jsx("div",{className:"pc-chat-attachments pc-docs-assistant__files",role:"list","aria-label":"Attached files",children:c.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 sp(){return new Date().toISOString()}function FL(e){sf();const{source:t}=e,n=p.useRef(e.fetchGateway);n.current=e.fetchGateway;const r=p.useMemo(()=>e.ask||RL({fetchGateway:(M,A)=>n.current(M,A),source:t}),[e.ask,t.app,t.name]),i=p.useRef(My(t.app)),[o,c]=p.useState([]),l=p.useRef(o);l.current=o;const[d,h]=p.useState(""),[m,_]=p.useState([]),[g,y]=p.useState(!1),[x,k]=p.useState(""),v=p.useRef(null),[N,$]=p.useState(!1),[E,S]=p.useState({state:"loading",items:[]});p.useEffect(()=>()=>{var M;return(M=v.current)==null?void 0:M.abort()},[]);const P=p.useCallback(async()=>{S(M=>({...M,state:"loading"}));try{const M=await LL((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=v.current)==null||A.abort(),S(O=>({...O,state:"loading"}));try{const O=await IL((L,H)=>n.current(L,H),M,t.name);i.current=M.sessionId,c(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 rf(A,"The conversation could not be archived");i.current===M.sessionId&&(i.current=My(t.app),c([])),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=v.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:nl(),file:O,preview:PL.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})),H=O.map(de=>({id:de.id,label:de.file.name,title:de.file.name,disabled:!0})),J={id:`u-${nl()}`,role:"user",content:A,ts:sp(),...L.length?{media:L}:{},...H.length?{attachments:H}:{}},U=`a-${nl()}`,te=[...l.current,J],z={id:U,role:"assistant",title:t.name,content:"",ts:sp(),live:{callId:U,reasoning:"",label:"answering"}};c([...te,z]),y(!0);const ne=new AbortController;v.current=ne;const se=de=>c([...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(AL(be))});ne.signal.aborted||se({id:U,role:"assistant",title:t.name,content:de,ts:sp()})}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:sp()})}finally{v.current===ne&&(v.current=null),y(!1)}},[r,g,m,e.connected,t.name]),G=()=>{var M;(M=v.current)==null||M.abort(),i.current=My(t.app),c([]),_([]),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})})]}),V=s.jsxs(s.Fragment,{children:[N?s.jsx("div",{className:"pc-docs-assistant pc-docs-assistant--history",children:s.jsx(OL,{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(DL,{source:t,messages:o,draft:d,onDraftChange:h,onSend:()=>void W(d),onStop:()=>{var M;return(M=v.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:x,suggestions:e.suggestions,onSuggestion:M=>void W(M),placeholder:e.placeholder})})]});return{headerActions:K,body:V}}function zL(e){const{headerActions:t,body:n}=FL(e);return s.jsx(u2,{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 s0="replay_view_v1",BL=["version","root_run_id","workflow","session_id","status","display_status","cursor","interaction","open_waits","usage","warnings"],r0=["runs","messages","activities","artifacts"],PN=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function DN(e){return e==null?"None":e===!0?"True":e===!1?"False":String(e)}function UL(e){const t=typeof e=="boolean"?Number(e):e;if(typeof t=="number"&&Number.isInteger(t)){const n=String(Math.abs(t));return t<0?`-${n.padStart(11,"0")}`:n.padStart(12,"0")}return DN(e)}function i0(e,t){if(e===t)return 0;const n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){const i=e.charCodeAt(r),o=t.charCodeAt(r);if(i===o)continue;const c=l=>l>=55296&&l<=57343;return c(i)||c(o)?(e.codePointAt(r)??i)-(t.codePointAt(r)??o):i-o}return e.length-t.length}function Jw(e,t){return DN(e==="runs"?t.run_id:t.id)}function Yw(e,t){return[(Array.isArray(t.order)&&t.order.length?t.order:[]).map(UL),Jw(e,t)]}function FN(e,t){const n=Math.min(e[0].length,t[0].length);for(let r=0;r<n;r+=1){const i=i0(e[0][r],t[0][r]);if(i)return i}return e[0].length!==t[0].length?e[0].length-t[0].length:i0(e[1],t[1])}function WL(e,t){return FN(Yw("messages",e),Yw("messages",t))}function Xw(e,t){if(e===t)return!0;if(e===void 0||t===void 0)return e===t||e==null&&t==null;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>Xw(n,t[r]));if(e&&t&&typeof e=="object"&&typeof t=="object"){const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(i=>PN(t,i)&&Xw(e[i],t[i]))}return!1}function qL(e,t){const n=e&&Object.keys(e).length?{...e}:Object.fromEntries(r0.map(r=>[r,[]]));for(const r of BL)PN(t,r)&&(n[r]=t[r]);for(const r of r0){const i=t[r],o=Array.isArray(n[r])&&n[r].length?n[r]:[];if(!Array.isArray(i)||!i.length){n[r]=o;continue}const c=[...o],l=new Map(c.map((h,m)=>[Jw(r,h),m]));let d=!1;for(const h of i){const m=Jw(r,h),_=l.get(m);_===void 0?(l.set(m,c.length),c.push(h),d=!0):(Xw(c[_].order??null,h.order??null)||(d=!0),c[_]=h)}if(d){const h=c.map(m=>({it:m,key:Yw(r,m)}));h.sort((m,_)=>FN(m.key,_.key)),n[r]=h.map(m=>m.it)}else n[r]=c}return n}let VL=class{constructor(){this.lastEventId="",this.buffer="",this.event="",this.data=[],this.pendingCr=!1}push(t){const n=[];let r=t;for(this.pendingCr&&r.startsWith(`
86
+ `)&&(r=r.slice(1)),this.pendingCr=!1,this.buffer+=r;;){const i=/\r\n|\n|\r/.exec(this.buffer);if(!i)break;if(i[0]==="\r"&&i.index===this.buffer.length-1){const c=this.buffer.slice(0,i.index);this.buffer="",this.pendingCr=!0,this.line(c,n);break}const o=this.buffer.slice(0,i.index);this.buffer=this.buffer.slice(i.index+i[0].length),this.line(o,n)}return n}line(t,n){if(t===""){this.data.length&&n.push({event:this.event||"message",data:this.data.join(`
87
+ `),...this.id!==void 0?{id:this.id}:{}}),this.event="",this.data=[],this.id=void 0;return}if(t.startsWith(":"))return;const r=t.indexOf(":"),i=r<0?t:t.slice(0,r);let o=r<0?"":t.slice(r+1);o.startsWith(" ")&&(o=o.slice(1)),i==="event"?this.event=o:i==="data"?this.data.push(o):i==="id"&&!o.includes("\0")&&(this.id=o,this.lastEventId=o)}};class HL{constructor(){this.view=null,this.lastEventId=null,this.terminal=!1}adopt(t,n){var r,i,o;return this.view&&o0((r=t.cursor)==null?void 0:r.runs,(i=this.view.cursor)==null?void 0:i.runs)?!1:(this.view=t,this.lastEventId=GL(n)||((o=t.cursor)==null?void 0:o.token)||null,!0)}apply(t){var i,o,c,l;if(t.event==="done")return this.terminal=!0,"done";if(t.event!=="view"&&t.event!=="delta")return"ignored";const n=JSON.parse(t.data);if(t.event==="view")return this.view=n,this.lastEventId=t.id||((i=this.view.cursor)==null?void 0:i.token)||null,"view";if(!this.view)throw new Error("replay view: a delta arrived before any view (reconnect without Last-Event-ID).");const r=t.id||((o=n.cursor)==null?void 0:o.token)||null;return r&&r===this.lastEventId?"duplicate":o0((c=n.cursor)==null?void 0:c.runs,(l=this.view.cursor)==null?void 0:l.runs)?"stale":(this.view=qL(this.view,n),this.lastEventId=r,"delta")}}function GL(e){return String(e||"").trim().replace(/^W\//,"").replace(/^"|"$/g,"")}function o0(e,t){if(!e||!t)return!1;let n=!1;for(const[r,i]of Object.entries(t)){const o=e[r];if(typeof o!="number"){i>0&&(n=!0);continue}if(o>i)return!1;o<i&&(n=!0)}for(const[r,i]of Object.entries(e))if(!(r in t)&&i>0)return!1;return n}class KL extends Error{constructor(t,n){super(`This gateway does not serve the replay view (GET runs/{id}/view answered ${t}${n?`: ${n}`:""}); AbstractGateway 0.17.0 or later serves it.`),this.name="ReplayViewUnavailableError",this.status=t}}async function a0(e){let t="";try{const r=await e.text();try{const i=JSON.parse(r);t=typeof i.detail=="string"?i.detail:r}catch{t=r}}catch{t=""}if(e.status===405||e.status===404&&t.trim()==="Not Found")return new KL(e.status,t.trim());const n=new Error(t||`Gateway answered ${e.status}`);return n.status=e.status,n.detail=t,n}const l0=e=>`runs/${encodeURIComponent(e)}/view`;function JL(e){const t=e.fetch;return{...e.advertised!==void 0?{advertised:e.advertised}:{},async getView(n,r={}){const i={Accept:"application/json"};r.ifNoneMatch&&(i["If-None-Match"]=r.ifNoneMatch);const o=r.at?`?at=${encodeURIComponent(r.at)}`:"",c=await t(`${l0(n)}${o}`,{method:"GET",headers:i,...r.signal?{signal:r.signal}:{}}),l=c.headers.get("etag");if(c.status===304)return{notModified:!0,etag:l,bytes:0};if(!c.ok)throw await a0(c);const d=new Uint8Array(await c.arrayBuffer()),h=JSON.parse(new TextDecoder().decode(d));if((h==null?void 0:h.version)!==s0)throw new Error(`Unsupported replay view version ${JSON.stringify(h==null?void 0:h.version)} (this client reads ${s0}).`);return{notModified:!1,view:h,etag:l,bytes:d.byteLength}},async streamView(n,r){var m;const i={Accept:"text/event-stream"};r.lastEventId&&(i["Last-Event-ID"]=r.lastEventId);const o=await t(`${l0(n)}/stream`,{method:"GET",headers:i,signal:r.signal});if(!o.ok)throw await a0(o);if(!o.body)throw new Error("The replay view stream has no body.");(m=r.onOpen)==null||m.call(r);const c=new VL,l=new TextDecoder,d=o.body.getReader();let h=0;try{for(;;){const{done:_,value:g}=await d.read();if(_)break;h+=g.byteLength;for(const y of c.push(l.decode(g,{stream:!0})))if(r.onFrame(y),y.event==="done")return{bytes:h}}for(const _ of c.push(l.decode()))r.onFrame(_)}finally{try{await d.cancel()}catch{}}return{bytes:h}}}}const yn=e=>typeof e=="string"?e.trim():typeof e=="number"?String(e):"",gu=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,c0=new Set(["completed","failed","cancelled"]),YL=new Set(["write_file","create_file","save_file","edit_file","update_file","replace_in_file","delete_file","remove_file","move_file","rename_file","copy_file"]);function zN(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=e.kind==="ask_user"?"user":e.kind==="event"?"event":"tool_approval",r={wait_key:e.wait_key,reason:n,details:t};return e.prompt!=null&&(r.prompt=e.prompt),Array.isArray(e.choices)&&(r.choices=e.choices),typeof e.allow_free_text=="boolean"&&(r.allow_free_text=e.allow_free_text),{runId:e.run_id,wait:r,...e.step_id?{stepId:e.step_id}:{},kind:e.kind,...e.command?{command:e.command}:{}}}function XL(e,t){const n=yn(e.status||t.status).toLowerCase();return n==="completed"?"completed":n==="waiting"?"waiting":n==="running"||n==="started"||n==="pending"?"running":"failed"}function ZL(e){const t=gu(e.policy_decision),n=yn(t==null?void 0:t.decision);if(n!=="auto_approved"&&n!=="denied")return;const r=gu(t==null?void 0:t.set_by),i=yn(r==null?void 0:r.user_id)||yn(r==null?void 0:r.client);return{decision:n,...yn(e.decided_by)?{source:yn(e.decided_by)}:{},...yn(e.matched)?{matched:yn(e.matched)}:{},...typeof(t==null?void 0:t.revision)=="number"?{revision:t.revision}:{},...i?{setBy:i}:{},...yn(t==null?void 0:t.set_at)?{setAt:yn(t==null?void 0:t.set_at)}:{}}}function QL(e,t){if(typeof e.error=="string"&&e.error.trim())return e.error.trim();const n=gu(e.error);if(n)return yn(n.message)||yn(n.detail)||JSON.stringify(n);if(t==="denied")return"Denied";if(t==="cancelled")return"Cancelled"}function eI(e){return(Array.isArray(e.tool_calls)?e.tool_calls:[]).map((n,r)=>{const i=XL(n,e),o=yn(n.status||e.status).toLowerCase(),c=ZL(n),l=i==="failed"?QL(n,o):void 0;return{id:`${e.id}:${yn(n.id)||r}`,runId:e.run_id,name:yn(n.name)||"tool",...n.arguments!==void 0?{arguments:n.arguments}:{},...n.output!==void 0?{output:n.output}:{},status:i,...i==="completed"?{success:!0}:i==="failed"?{success:!1}:{},...l?{error:l}:{},...yn(e.started_at)?{startedAt:yn(e.started_at)}:{},...yn(e.ended_at)?{endedAt:yn(e.ended_at)}:{},...yn(n.id)?{callId:yn(n.id)}:{},...c?{policy:c}:{}}})}function BN(e){return{id:`tool:${e.id}`,role:"system",kind:"tool_activity",title:"Tool activity",runId:e.runId,toolActivity:e,content:JSON.stringify({tool:e.name,status:e.status,arguments:e.arguments,output:e.output,error:e.error},null,2),ts:e.endedAt||e.startedAt}}function tI(e){const t=yn(e.decision);if(t!=="auto_approved"&&t!=="denied")return null;const n=gu(e.policy),r=gu(n==null?void 0:n.set_by),i=yn(r==null?void 0:r.user_id)||yn(r==null?void 0:r.client),o={decision:t,...yn(e.source)?{source:yn(e.source)}:{},...typeof(n==null?void 0:n.revision)=="number"?{revision:n.revision}:{},...i?{setBy:i}:{},...yn(n==null?void 0:n.set_at)?{setAt:yn(n==null?void 0:n.set_at)}:{}};return{id:`policy:${e.id}`,role:"system",kind:"tool_policy_decision",title:"Tool policy",runId:e.run_id,content:Yp(o),ts:yn(e.started_at)||void 0}}function nI(e){const t=gu(e.usage)||{},n=new Set;let r=0,i=0,o=1/0,c=-1/0;for(const h of e.activities||[]){const m=Date.parse(yn(h.started_at)),_=Date.parse(yn(h.ended_at));if(Number.isFinite(m)&&(o=Math.min(o,m)),Number.isFinite(_)&&(c=Math.max(c,_)),h.kind==="llm"&&(i+=1),h.kind==="tool")for(const g of h.tool_calls||[]){if(r+=1,yn(g.status)!=="completed"||!YL.has(yn(g.name)))continue;const y=gu(g.arguments)||{},x=yn(y.destination)||yn(y.destination_path)||yn(y.file_path)||yn(y.path)||yn(y.filename);x&&n.add(x)}}const l=h=>typeof h=="number"&&Number.isFinite(h)?h:void 0,d={llmCalls:l(t.llm_calls)??i,toolCalls:r,changedFiles:[...n]};return l(t.input_tokens)!==void 0&&(d.inputTokens=l(t.input_tokens)),l(t.output_tokens)!==void 0&&(d.outputTokens=l(t.output_tokens)),l(t.total_tokens)!==void 0&&(d.totalTokens=l(t.total_tokens)),Number.isFinite(o)&&Number.isFinite(c)&&(d.durationMs=Math.max(0,c-o)),d}function sI(e,t){const n=Array.isArray(e.order)&&typeof e.order[0]=="string"&&e.order[0]?e.order[0]:void 0,r=yn(e.level).toLowerCase();return{id:e.id,role:e.role,kind:e.kind,content:e.text,runId:e.run_id,...n?{ts:n}:{},...e.role==="system"?{title:"Workflow",level:r==="error"?"error":r==="warn"||r==="warning"?"warn":"info"}:{},...Array.isArray(e.artifact_ids)&&e.artifact_ids.length?{artifactIds:[...e.artifact_ids]}:{},...t?{statistics:t}:{}}}function rI(e){const t=e.root_run_id,n=nI(e),r=e.interaction?zN(e.interaction):null,i=e.interaction?`${e.interaction.run_id}:${e.interaction.step_id||""}:question`:"",o=(e.messages||[]).find(y=>y.id===`${t}:final`),c=o?o.repeats||o.id:"",l=[];for(const y of e.messages||[])y.kind==="final"&&y.repeats||y.kind==="question"&&y.id===i||l.push({order:y.order,id:y.id,message:sI(y,y.id===c?n:void 0)});const d=[],h=[],m=[];for(const y of e.activities||[])if(y.kind==="tool"){const x=eI(y);d.push(...x),x.forEach((k,v)=>l.push({order:[...y.order||[],v],id:`${y.id}:${v}`,message:BN(k)}))}else if(y.kind==="tool_policy"){const x=tI(y);x&&l.push({order:y.order,id:y.id,message:x})}else if(y.kind==="llm")for(const x of y.step_ids||[])(c0.has(y.status)?m:h).push(`${y.run_id}:${x}`);l.sort((y,x)=>WL(y,x));const _=new Map((e.runs||[]).map(y=>[y.run_id,yn(y.status).toLowerCase()])),g=yn(e.status).toLowerCase()||"unknown";return{messages:l.map(y=>y.message),tools:d,interaction:c0.has(g)?null:r,status:g,displayStatus:yn(e.display_status),openLlmCalls:h,endedLlmCalls:m,runStatus:_,statistics:n}}const ss=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Ap=e=>Array.isArray(e)?e.map(ss):[],Mn=e=>typeof e=="string"?e:"",bh=e=>Mn(e.runtime_call_id||e.call_uid),Ya=e=>Mn(e.call_id||e.id);function UN(e,t){const n=t.record,r=ss(n.effect);if(r.type!=="tool_calls")return[];const i=ss(n.result),o=Ap(ss(r.payload).tool_calls),c=o.length||n.status!=="waiting"?o:Ap(ss(ss(i.wait).details).tool_calls),l=Ap(i.results),d=c.length?c:l,h=[];return d.forEach((m,_)=>{let g=bh(m)?l.filter(D=>bh(D)===bh(m)):[];!g.length&&Ya(m)&&c.filter(D=>Ya(D)===Ya(m)).length===1&&(g=l.filter(D=>Ya(D)===Ya(m)));const y=c.length?g.length===1?g[0]:c.length===l.length?l[_]:{}:m,x=bh(m)||bh(y)||`${Mn(n.idempotency_key)||Mn(n.step_id)||t.cursor}:${_}`,k=`${t.runId}:${x}`,v=e.get(k),N=Mn(m.name||y.name)||(v==null?void 0:v.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??(v==null?void 0:v.arguments),P={...v,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)}:{},...Kw(y)?{sandbox:Kw(y)}:{},...Ya(m)||Ya(y)?{callId:Ya(m)||Ya(y)}:{},startedAt:(v==null?void 0:v.startedAt)||Mn(n.started_at)||void 0,endedAt:$&&Mn(n.ended_at)||(v==null?void 0:v.endedAt)};v&&["completed","failed"].includes(v.status)&&!$||(e.set(k,P),h.push(P))}),h}function Ad(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function ya(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 WN(e){if(typeof e=="string")try{return ss(JSON.parse(e))}catch{return{}}return ss(e)}function wd(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function iI(e){return ya(e,["reasoning_tokens","thinking_tokens"])??ya(ss(e.completion_tokens_details),["reasoning_tokens"])??ya(ss(e.output_tokens_details),["reasoning_tokens"])}function oI(e){const t=ss(typeof e=="string"&&e.trim().startsWith("{")?WN(e):e);return Mn(t.error_class)}function aI(e){const t=new Map;for(const n of e){const r=n.record;if(ss(r.effect).type!=="emit_event")continue;const i=ss(r.result);if(Mn(i.name)!=="abstract.progress")continue;const o=ss(i.payload);if(Mn(o.kind)!=="llm"||!Mn(o.step_id))continue;const c=`${Mn(o.run_id)||n.runId}:${Mn(o.step_id)}`,l=t.get(c)||{},d=Ad(o.ttft_s);d!==void 0&&(l.ttftS=d),l.provider=l.provider||Mn(o.provider)||void 0,l.model=l.model||Mn(o.model)||void 0,t.set(c,l)}return t}function Ry(e){var k,v,N,$;const t=new Map,n=new Set,r=new Set,i={llmCalls:0,toolCalls:0,changedFiles:[]};let o=1/0,c=-1/0,l=!1,d=0,h=0,m=0;const _=aI(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(Mn(ae));Number.isFinite(xe)&&(o=Math.min(o,xe),c=Math.max(c,xe))}for(const ae of UN(t,E))ae.status==="waiting"&&y.add(ae.id);if(ss(S.effect).type!=="llm_call"||S.status!=="completed")continue;i.llmCalls+=1;const D=ss(S.result),R=ss(D.output),I=ss(D.usage||D.token_usage||D.tokens||R.usage||R.token_usage||R.tokens),W=ya(I,["input_tokens","prompt_tokens","prompt","input","in"]),G=ya(I,["output_tokens","completion_tokens","completion","output","out"]),K=ya(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 V=Ad(D.gen_time??R.gen_time);V!==void 0&&(i.genTimeMs=(i.genTimeMs||0)+V,i.timedCalls=(i.timedCalls||0)+1);const M=ss(D.metadata||R.metadata),A=ss(M.performance),O=Ad(A.prompt_tokens_per_second),L=Ad(A.generation_tokens_per_second),H=ss(M.prompt_cache),J=Ad(H.cached_tokens),U=Ad(H.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=Mn(H.outcome);if(ae){const xe=i.cacheOutcomes||[];xe.includes(ae)||xe.push(ae),i.cacheOutcomes=xe}}const te=Mn(S.step_id)||void 0,z=te&&_.get(`${E.runId}:${te}`)||{},ne=ss(D.route),se={runId:E.runId};te&&(se.stepId=te),Mn(S.started_at)&&(se.startedAt=Mn(S.started_at));const de=Mn(D.model||R.model)||Mn(ne.model)||z.model,be=Mn(ne.provider)||Mn(ss(M._provider_request).provider)||z.provider||Mn(D.provider);de&&(se.model=de),be&&(se.provider=be),de&&(i.models=wd(i.models,de)),be&&(i.providers=wd(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=iI(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),Mn(H.outcome)&&(se.cacheOutcome=Mn(H.outcome)),Mn(H.backend)&&(se.cacheBackend=Mn(H.backend),i.cacheBackends=wd(i.cacheBackends,se.cacheBackend)),V!==void 0&&(se.genTimeMs=V),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&&V!==void 0&&V>=se.ttftMs?se.generationMs=V-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=ss(M.speculation);if(Object.keys(je).length){const ae={};Mn(je.mode)&&(ae.mode=Mn(je.mode)),typeof je.used=="boolean"&&(ae.used=je.used),Mn(je.draft_kind)&&(ae.draftKind=Mn(je.draft_kind));const xe=ya(je,["accepted_tokens"]),Ae=ya(je,["drafted_tokens"]),Ve=ya(je,["rounds"]),mt=ya(je,["num_draft_tokens"]);xe!==void 0&&(ae.acceptedTokens=xe),Ae!==void 0&&(ae.draftedTokens=Ae),xe!==void 0&&Ae&&(ae.acceptanceRate=xe/Ae),Ve!==void 0&&(ae.rounds=Ve),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=wd(nt.modes,ae.mode)),ae.draftKind&&(nt.draftKinds=wd(nt.draftKinds,ae.draftKind)),xe!==void 0&&Ae!==void 0&&(nt.acceptedTokens=(nt.acceptedTokens||0)+xe,nt.draftedTokens=(nt.draftedTokens||0)+Ae),Ve!==void 0&&(nt.rounds=(nt.rounds||0)+Ve),mt!==void 0&&(nt.draftLengths=wd(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 x=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=oI(E.output);K&&((D.errors||(D.errors={}))[K]=(((v=D.errors)==null?void 0:v[K])||0)+1)}const R=Date.parse(Mn(E.startedAt)),I=Date.parse(Mn(E.endedAt));if(Number.isFinite(R)&&Number.isFinite(I)&&I>=R){const K=`${E.runId}|${E.startedAt}|${E.endedAt}`,V=x.get(K)||{ms:I-R,calls:0,names:new Map,waited:!1};V.calls+=1,V.names.set(E.name,(V.names.get(E.name)||0)+1),y.has(E.id)&&(V.waited=!0),x.set(K,V)}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=WN(E.arguments),G=Mn(W.destination||W.destination_path||W.file_path||W.path||W.filename);G&&r.add(G)}for(const E of x.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(c)&&(i.durationMs=Math.max(0,c-o)),{tools:[...t.values()],statistics:i}}function lI(e){const t=ss(ss(e).ledgers);return Object.entries(t).flatMap(([n,r])=>Ap(ss(r).items).map((i,o)=>({runId:n,cursor:Number(i.cursor)||o+1,record:Object.keys(ss(i.record)).length?ss(i.record):i})))}const u0=e=>`${e} ${e===1?"file":"files"}`;function cI(e){const t=e.filter(i=>i.state==="queued"||i.state==="uploading").length;if(t)return`Wait for ${u0(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.`:`${u0(n.length)} were not attached. ${r?"Retry or remove":"Remove"} them before sending.`}const uI=new Set(["blob:","data:","http:","https:"]);function dI(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return uI.has(new URL(t,n).protocol)?t:void 0}catch{return}}function fI(e){const t=typeof e.size=="number"?MN(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 hI(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}=fI(n),c=dI(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:c?s.jsx("img",{className:"pc-attachment-chip__thumb",src:c,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 mI(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 Uh={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 d0(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function _I(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 qo=Uh;function pI(e){var V,M,A;const t=e.interaction,n=e.variant==="card",[r,i]=p.useState(""),[o,c]=p.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[l,d]=p.useState(null),[h,m]=p.useState(!1),[_,g]=p.useState(""),[y,x]=p.useState(null),k=`${t.kind}:${t.id}`,v=p.useRef(k),N=p.useRef(!1),$=p.useRef(!1),E=p.useRef(!0),S=p.useRef(0);v.current!==k&&(v.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 H=k,J=++S.current;N.current=!0,x(null),g(""),d(O);try{const te=await L();if(!E.current||v.current!==H||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||v.current!==H||S.current!==J)return;x({submission:O,message:d0(te)}),g("The action failed. You can try again."),(U=e.onError)==null||U.call(e,te)}finally{if(!E.current||v.current!==H||S.current!==J)return;N.current=!1,d(null)}},R=async O=>{var H;if(e.disabled||N.current||$.current)return;const L=k;try{if(await O(),!E.current||v.current!==L)return;x(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||v.current!==L)return;g(`Could not leave this for later: ${d0(J)}`),(H=e.onError)==null||H.call(e,J)}};p.useEffect(()=>{i(""),c(t.kind==="event-wait"&&t.initialPayload||""),x(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,()=>mI(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}),(V=t.choices)!=null&&V.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||qo.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||qo.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||qo.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||qo.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||qo.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||qo.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||qo.allowForChat}):null,(t.approveKinds||[]).map(H=>s.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-session pc-workflow-interaction__allow-kind","data-decision":"approve-kind","data-kind":H.kind,disabled:L,title:O||void 0,onClick:()=>void D({kind:"approve-kind",toolset:H.kind},H.onApprove),children:(l==null?void 0:l.kind)==="approve-kind"&&l.toolset===H.kind?"Allowing…":H.label||qo.allowKindForChat(H.kind)},H.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||qo.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:H=>t.remember.onChange(H.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:qo.denyForChatNote}),s.jsx("div",{className:"pc-workflow-interaction__buttons",children:t.denyOptions.map(H=>s.jsx("button",{type:"button",className:"pc-workflow-interaction__deny","data-decision":"deny-chat","data-key":H.key,disabled:P,onClick:()=>void D({kind:"deny-chat",key:H.key},H.onDeny),children:(l==null?void 0:l.kind)==="deny-chat"&&l.key===H.key?"Denying…":H.label},H.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=>c(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||qo.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(_I,{message:y.message,onRetry:I,disabled:P}):null,s.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:_})]})}function vd(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function gI(e){var Q;sf();const[t,n]=p.useState(!1),[r,i]=p.useState(!1),[o,c]=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,x]=p.useState("idle"),k=p.useRef(null),v=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(()=>(v.current=!0,()=>{var _e;v.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,V=(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,H=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:CN(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){v.current&&d({action:"attach",message:vd(pe)})}}}},je=p.useRef(Me);je.current=Me,p.useEffect(()=>{if(!J||typeof window>"u")return;const _e=new sL;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(!zh((mn=ut.dataTransfer)==null?void 0:mn.types))return;_e.enter(Date.now());const Ot=Se(ut.target),Rt=t0(ut.dataTransfer);z(wn=>wn&&wn.over===Ot&&wn.count===(Rt??wn.count)?wn:{count:Rt??(wn==null?void 0:wn.count)??null,over:Ot}),dt()},_t=ut=>{var Rt;if(!zh((Rt=ut.dataTransfer)==null?void 0:Rt.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)??t0(ut.dataTransfer),over:Ot}),dt()},It=ut=>{var Ot;zh((Ot=ut.dataTransfer)==null?void 0:Ot.types)&&(_e.leave(Date.now())||pe())},bt=ut=>{var On;if(!zh((On=ut.dataTransfer)==null?void 0:On.types))return;const Ot=Se(ut.target),Rt=ut.defaultPrevented&&!Ot;if(ut.preventDefault(),pe(),Rt)return;if(!Ot){d({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:mn,folders:wn}=ux(ut.dataTransfer);je.current(mn,wn)},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=EN(_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":n0(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":n0(te.count):ne,Ve=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(!v.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){v.current&&S.current===Se&&d({action:"steer",message:vd(pe)})}finally{v.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 Ve(_e);if(!e.sendWhileBusy&&e.busy)return;const le=H.length?cI(H):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){v.current&&S.current===Se&&!pe.signal.aborted&&d({action:"send",message:vd(dt)})}finally{k.current===pe&&(k.current=null),v.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){v.current&&P.current===_e&&d({action:"cancel",message:vd(pe)})}finally{v.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),c(!0);try{await e.onAttach()}catch(le){v.current&&D.current===_e&&d({action:"attach",message:vd(le)})}finally{v.current&&D.current===_e&&(E.current=!1,c(!1))}},ze=()=>{l&&((l.action==="send"||l.action==="steer")&&mt(),l.action==="cancel"&&nt(),l.action==="attach"&&rt())},He=e.toolbar||null,ct=_e=>lN((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){v.current&&d({action:"toolbar",message:vd(le)})}}},Dt=async()=>{const _e=await il(ct());v.current&&(x(_e?"copied":"failed"),typeof window<"u"&&window.setTimeout(()=>v.current&&x("idle"),1200))},$e=He?s.jsxs("div",{className:"pc-workflow-chat__toolbar",role:"toolbar","aria-label":"Conversation actions",children:[He.onNewSession?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"new",disabled:I,onClick:()=>void Qe(He.onNewSession),children:[s.jsx(qe,{name:"plus",size:14}),s.jsx("span",{children:"New chat"})]}):null,He.onClear?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"clear",disabled:I,onClick:()=>void Qe(He.onClear),children:[s.jsx(qe,{name:"trash",size:14}),s.jsx("span",{children:"Clear"})]}):null,He.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,He.exportTranscript?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"export",onClick:()=>{const _e=He.exportTranscript;cN({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(lx,{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(pI,{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(cx,{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||H.length?s.jsxs("div",{className:"pc-workflow-chat__attachments",children:[H.length?s.jsx(hI,{items:H,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||V,onClick:()=>void nt(),children:[s.jsx(qe,{name:"x",size:14}),s.jsx("span",{children:r||V?"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 yI(e){return e.source==="replay_view"?"Live view from the gateway (replay view)":e.source==="ledger_fold"?`Rebuilt in this client from the run ledger${e.sourceReason?`: ${e.sourceReason}`:""}`:""}function wI(e){return e.toolApprovalGranted?null:e.interaction}const Ly={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function Jt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ct(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function Wh(e){return Array.isArray(e)?e:[]}function vI(e){const t=Jt(e);return!!(t&&(t.code==="revision_conflict"||t.reason_code==="revision_conflict"||t.status===409||t.name==="SessionToolPolicyConflict"))}function xi(e){return Ct(e==null?void 0:e.status).toLowerCase()||"unknown"}function ds(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function _a(e){const t=Jt(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function xI(e){const t=Jt(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function Iy(e){const t=n=>{if(Array.isArray(n))return n.map(t);const r=Jt(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 Zw(e){if(typeof e=="string")return e.trim();const t=Jt(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 xd(e){const t=Zw(e);if(t)return t;if(!Jt(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function f0(e){if(!e)return"";for(const r of["prompt","request","task","message","query","input"]){const i=Ct(e[r]);if(i)return i}const t=Jt(e.context);for(const r of["task","message"]){const i=Ct(t==null?void 0:t[r]);if(i)return i}const n=Wh(t==null?void 0:t.messages);for(let r=n.length-1;r>=0;r-=1){const i=Jt(n[r]);if(Ct(i==null?void 0:i.role).toLowerCase()!=="user")continue;const o=Ct(i==null?void 0:i.content);if(o)return o}return""}function qN(e){const t=Jt(e.result);return Jt(t==null?void 0:t.wait)}function Oy(e){return e?Ct(e.reason)==="subworkflow"||Ct(e.wait_key).startsWith("subworkflow:"):!1}function h0(e,t){return!!(e&&e.runId===t.runId&&Ct(e.wait.wait_key)===Ct(t.wait.wait_key))}function Qw(e){return Jt(e.effect)||{}}function bI(e,t){return Ct(e.run_id)||t}function m0(e){return Ct(e.ended_at)||Ct(e.started_at)||void 0}function _0(e){const t=new Set,n=h=>{const m=Ct(h);m&&t.add(m)},r=Jt(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=Qw(e),o=Jt(i.payload);Ct(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 c=qN(e),l=Jt(c==null?void 0:c.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=Ct(c==null?void 0:c.wait_key);return d.startsWith("subworkflow:")&&n(d.slice(12)),[...t]}const Py=new WeakMap,kI=/^(live|live-end|stream-unavailable):/;function jI(e){return!!(e&&typeof e=="object"&&e.name==="ReplayViewUnavailableError")}function p0(e){const t=String(e||""),n=t.indexOf("~");return n<0?"":t.slice(n+1)}class SI{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...Ly},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,this.source=null,this.viewFold=null,this.viewRun=null,this.viewDigest="",this.viewAssistantIds=new Set,this.viewTerminalRuns=new Set,this.viewStreamEnded=!1;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=Ct(n.sessionToolPolicyUnavailableReason)),this.snapshot=this.withSessionPolicy({...Ly})}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?"":Ct(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=Ct((r=this.snapshot.run)==null?void 0:r.session_id)||Ct((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(vI(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(ds(this.snapshot.status))throw new Error("This run has already ended.");if(n.runId!==t.runId||Ct(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 c=[...new Set(i.map(h=>Ct(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,...c.length?{ask:c}:{},...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}}withSource(t){const{source:n,sourceReason:r,...i}=t;return this.source?{...i,source:this.source.source,...this.source.reason?{sourceReason:this.source.reason}:{}}:i}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.source=null,this.viewFold=null,this.viewRun=null,this.viewDigest="",this.viewAssistantIds.clear(),this.viewTerminalRuns.clear(),this.viewStreamEnded=!1,this.set({...Ly})}dispose(){this.reset(),this.subscribers.clear()}async load(t){const n=Ct(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{if(await this.loadView(n,r,i.signal)||!this.live(r))return;this.set({...this.snapshot});const[o,c]=await Promise.all([this.transport.getRun(n,i.signal),this.transport.getHistory(n,i.signal)]);if(!this.live(r))return;const l=Jt(o),d=Jt(l==null?void 0:l.waiting),h=xi(l);if(await this.ingestHistory(c,n,r),!this.live(r))return;if(this.set({...this.snapshot,run:l,status:h,loading:!1,...d&&!ds(h)?{interaction:this.interactionWith({runId:n,wait:d})}:{}}),l&&this.updateRunState(n,l),d)for(const m of _0({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=Ct(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)||"",c=`${i}\0${t}\0${o}\0${Iy(n)}`;let l=this.commandIds.get(c);l||(l=this.newCommandId(),this.commandIds.set(c,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=Jt(g);if(y&&y.accepted===!1)throw t==="cancel"&&(this.stopRequested=!1,this.recomputeStop()),new Error(Ct(y.detail)||"Gateway did not accept the command");return this.commandIds.delete(c),this.viewFold?["pause","resume","cancel"].includes(t)&&this.refreshViewRun(d):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||Ct(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:Ct(r.wait.wait_key),payload:{response:t}})}answerEvent(t,n){const r=this.requireInteraction();if(n&&(r.runId!==n.runId||Ct(r.wait.wait_key)!==n.waitKey||n.stepId!==void 0&&r.stepId!==n.stepId))throw new Error("This wait has changed. Review the current one before answering.");if(!r.command)throw new Error("This wait has no resume command (it does not come from the replay view): send the event instead.");return this.sendCommand("resume",{wait_key:Ct(r.wait.wait_key),payload:t})}approve(t,n){const r=this.requireInteraction();if(ds(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(r.runId!==n.runId||Ct(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:Ct(r.wait.wait_key),payload:{approved:!!t}}).then(o=>{if(!this.live(i))return o;const c=this.occurrenceKey(r);return this.approvedWaits.add(c),t&&this.isToolApproval(r)&&!this.grantedToolWaits.has(c)&&(this.grantedToolWaits.add(c),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||ds(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||ds(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){Iy(t)!==Iy(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}:${Ct(t.wait.wait_key)}${t.stepId?`:${t.stepId}`:""}`}interactionWith(t){const n=this.snapshot.interaction;return n&&Oy(t.wait)&&!Oy(n.wait)?n:n&&h0(n,t)&&t.stepId===void 0&&n.stepId!==void 0?{...t,stepId:n.stepId}:t}adoptDurableWait(t,n){const r=Jt(n.waiting);if(!r||xi(n)!=="waiting"||Oy(r)||ds(this.snapshot.status)||this.resolvedWaits.has(`${t}:${Ct(r.wait_key)}`))return;const i=this.interactionWith({runId:t,wait:r}),o=this.snapshot.interaction;o&&h0(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||ds(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:!!Ct(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 c=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:c}:{}}}toolCallsMatch(t,n){var i;const r=Wh((i=Jt(t.wait.details))==null?void 0:i.tool_calls);return r.length>0&&r.every(o=>{var l;const c=Ct((l=Jt(o))==null?void 0:l.name);return!!c&&n.includes(c)})}isToolApproval(t){const n=Jt(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:Ct(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(c=>{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(c,!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(!Ct(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.withSource(this.withSessionPolicy(t)));for(const n of this.subscribers)n();this.autoApproveCurrentWait()}async loadView(t,n,r){const i=this.transport.replayView,o=m=>(this.live(n)&&(this.source={source:"ledger_fold",reason:m}),!1);if(!i)return o("this app's transport does not read the replay view");if(i.advertised===!1)return o("the gateway does not advertise the replay view");const c=Py.get(i);if(typeof c=="string")return o(c);let l,d;try{[l,d]=await Promise.all([i.getView(t,{signal:r}),this.transport.getRun(t,r)])}catch(m){if(!jI(m))throw m;const _=m instanceof Error?m.message:"the gateway does not serve the replay view";return Py.set(i,_),o(_)}if(Py.set(i,!0),!this.live(n))return!0;if(l.notModified)throw new Error("The gateway answered 304 to a replay view read without If-None-Match.");this.source={source:"replay_view"},this.viewRun=Jt(d);const h=new HL;return h.adopt(l.view,l.etag),this.viewFold=h,this.viewDigest=p0(h.lastEventId),this.adoptView(),this.followView(t,n),this.followLiveReplies(t,n),!0}adoptView(){var h,m,_;const t=(h=this.viewFold)==null?void 0:h.view;if(!t)return;const n=rI(t);this.toolActivities=new Map(n.tools.map(g=>[g.id,g]));for(const g of n.endedLlmCalls)this.closedLiveCalls.has(g)||this.closeLiveReply(g);for(const g of t.messages||[])g.role!=="assistant"||this.viewAssistantIds.has(g.id)||(this.viewAssistantIds.add(g.id),this.closeLiveRepliesOfRun(g.run_id));for(const[g,y]of n.runStatus)!ds(y)||this.viewTerminalRuns.has(g)||(this.viewTerminalRuns.add(g),this.endLiveRepliesOfRun(g,y));this.openLlmSteps=new Set(n.openLlmCalls);const r=ds(n.status),i=this.snapshot.messages.filter(g=>kI.test(String(g.id||""))),o={...this.viewRun||{},run_id:t.root_run_id,status:n.status,...t.session_id?{session_id:t.session_id}:{}};let c=n.interaction;const l=this.snapshot.interaction;if(c&&l&&l.runId===c.runId&&Ct(l.wait.wait_key)===Ct(c.wait.wait_key)&&l.stepId!==c.stepId&&(l.stepId===void 0||c.stepId===void 0)){const{stepId:g,...y}=c;c=l.stepId===void 0?y:{...y,stepId:l.stepId}}this.set({...this.snapshot,view:t,run:o,status:n.status,displayStatus:r?"":n.displayStatus,messages:[...n.messages,...i],interaction:c,loading:!1,...r?{autoApproveTools:!1}:{}}),(this.stopRequested||this.forcedStop)&&this.recomputeStop();const d=p0((m=this.viewFold)==null?void 0:m.lastEventId);d!==this.viewDigest&&Object.keys(((_=t.cursor)==null?void 0:_.runs)||{}).length<=32&&(this.viewDigest=d,this.refreshViewRun(this.generation))}async followView(t,n){const r=this.transport.replayView,i=this.viewFold;if(!r||!i)return;let o=0;for(;this.live(n)&&this.viewFold===i&&!i.terminal;){this.set({...this.snapshot,connection:o?"reconnecting":"connecting"});try{if(await r.streamView(t,{lastEventId:i.lastEventId,signal:this.controller.signal,onOpen:()=>{this.live(n)&&this.set({...this.snapshot,connection:"connected",error:null})},onFrame:c=>{if(!this.live(n)||this.viewFold!==i)return;o=0;const l=i.apply(c);(l==="view"||l==="delta")&&this.adoptView()}}),!this.live(n))return;if(i.terminal)break;o+=1}catch(c){if(!this.live(n))return;if(o+=1,this.fail(c,!1),_a(c)){this.set({...this.snapshot,connection:"disconnected"});return}}if(o>=5||!this.live(n))break;await this.waitForRetry(Math.min(2e3,150*2**(o-1)))}if(this.viewStreamEnded=!0,!(!this.live(n)||this.viewFold!==i)){if(i.terminal||ds(this.snapshot.status)){this.set({...this.snapshot,connection:"disconnected"});return}this.set({...this.snapshot,connection:"disconnected",error:this.snapshot.error||"Replay view stream reconnect limit reached. Reconnect the workflow to continue."})}}async followLiveReplies(t,n){var i,o,c;let r=0;try{for(;this.live(n)&&this.viewFold&&!this.viewStreamEnded&&!ds(this.snapshot.status);){const l=Number((c=(o=(i=this.viewFold.view)==null?void 0:i.cursor)==null?void 0:o.runs)==null?void 0:c[t])||0;this.dropLiveRepliesVia(t);try{if(await this.transport.streamLedger(t,l,()=>{},this.controller.signal,void 0,d=>{this.live(n)&&(r=0,this.ingestDelta(t,d))}),!this.live(n))return;r+=1}catch(d){if(!this.live(n))return;if(r+=1,_a(d)){this.fail(d);return}}if(r>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(r-1)))}}finally{this.live(n)&&this.closeLiveRepliesVia(t)}}async refreshView(t){var o;const n=this.transport.replayView,r=this.viewFold;if(!n||!r)return;const i=await n.getView(this.rootRunId,{ifNoneMatch:r.lastEventId?`"${r.lastEventId}"`:null,signal:(o=this.controller)==null?void 0:o.signal});!this.live(t)||this.viewFold!==r||i.notModified||r.adopt(i.view,i.etag)&&this.adoptView()}async refreshViewRun(t){var n;try{const r=Jt(await this.transport.getRun(this.rootRunId,(n=this.controller)==null?void 0:n.signal));if(!r||!this.live(t)||!this.viewFold)return;this.viewRun=r,this.adoptView()}catch(r){this.live(t)&&this.fail(r,!1)}}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=Jt(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(_a(i))throw i;this.fail(i,!1)}if(await this.catchUp(t,n),!this.live(n)||ds(xi(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(_a(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,c=await this.transport.getLedger(t,o,(r=this.controller)==null?void 0:r.signal);if(!this.live(n))return;const l=Jt(c),d=Array.isArray(c)?c:Wh(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)&&!ds(xi(this.runStates.get(t)||null));){const o=this.cursors.get(t)||0;this.set({...this.snapshot,connection:r?"reconnecting":"connecting"});try{let c=!1;const l=()=>{!this.live(n)||c||(c=!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=Jt(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(c){if(!this.live(n))return;if(r+=1,this.fail(c,!1),_a(c)){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(ds(xi(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=Jt(t);if(!i)return;const o=Jt(i.session),c=Wh(o==null?void 0:o.turns).map(Jt).filter(h=>!!h);if(await this.hydrateHistoricalSessionRuns(c,n,r),!this.live(r))return;for(const h of c){const m=Ct(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=f0(Jt(i.input_data));h&&this.addMessage({id:l,role:"user",content:h})}const d=Jt(i.ledgers);if(d)for(const[h,m]of Object.entries(d)){const _=Jt(m);for(const g of Wh(_==null?void 0:_.items))this.ingestItem(h,g)}}ingestSessionTurn(t,n,r){if(!t)return;const i=Ct(t.run_id)||n,o=Jt(t.input_data)||Jt(t.input)||{},c=Ct(t.prompt)||f0(o);c&&this.addMessage({id:`turn:${i}:user`,role:"user",content:c,ts:Ct(t.created_at)||void 0});const l=this.historicalRunFailures.get(i);if(l){const _=Ct(t.answer)||Zw(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&&ds(xi(r))?xd(r.output):"")||(r?Ct(t.answer)||Zw(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:Ct(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,r){const i=[...new Set(t.map(d=>Ct(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,c=!1;const l=async()=>{var d,h,m;for(;!c&&this.live(r);){const _=i[o++];if(!_)return;try{const g=Jt(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(_,Ry(lI(y)))}catch(y){if(!this.live(r))return;if(_a(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=xI(g)===404;this.historicalRuns.set(_,null),this.historicalRunFailures.set(_,{missing:y,detail:g instanceof Error?g.message:Ct((m=Jt(g))==null?void 0:m.detail)||"request failed"}),_a(g)&&(c=!0,this.fail(g))}}};if(await Promise.all(Array.from({length:Math.min(4,i.length)},()=>l())),c&&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=Jt(n),i=Jt(r==null?void 0:r.record)||r;if(!i)return;const o=bI(i,t),c=Number(r==null?void 0:r.cursor),l=Number.isFinite(c)&&c>0?c:(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=Ry(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 _0(i))h!==o&&this.catchUpAndWatch(h,this.generation)}}foldRecord(t,n,r){var m,_,g;const i=Qw(n),o=Ct(i.type).toLowerCase(),c=Jt(n.result),l=Ct(n.status).toLowerCase(),d=m0(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=xd(c)||xd(Jt(i.payload));y&&this.addRunAssistantMessage(t,{id:`answer:${t}:${r}`,role:"assistant",content:y,ts:d})}if(o==="emit_event"&&l==="completed"){const y=Jt(i.payload)||{},x=Jt(c),k=Ct(y.name)||Ct(x==null?void 0:x.name),v=y.payload!==void 0?y.payload:x==null?void 0:x.payload;if(["abstract.message","abstractcode.message"].includes(k)){const N=xd(v);if(N){const $=Ct((m=Jt(v))==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=Jt(v),$=N?N.status??N.text??N.value:v,E=Date.parse(d||"");!ds(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=FR(Jt(v));if(N){this.addMessage({id:`policy:${t}:${r}`,role:"system",kind:"tool_policy_decision",title:"Tool policy",content:Yp(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=xd(v);N&&this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Tool activity",content:N,ts:d})}}const h=qN(n);if(l==="waiting"&&h&&!ds(this.snapshot.status)&&!ds(xi(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${Ct(h.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:h,...Ct(n.step_id)?{stepId:Ct(n.step_id)}:{}})})),o==="tool_calls")for(const y of UN(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(y);if(o==="resume"&&(c==null?void 0:c.resumed)===!0){const y=Ct((_=Jt(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 c=Ct(n.step_id);if(c){const l=`${t}:${c}`;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 c=Jt(Qw(n).payload)||{},l=Jt(n.result),d=Ct(c.name)||Ct(l==null?void 0:l.name),h=Jt(c.payload!==void 0?c.payload:l==null?void 0:l.payload);d==="abstract.status"&&Ct(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:Ct(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.viewFold?[]:[this.rootRunId,...[...this.watchedRuns].filter(l=>l!==this.rootRunId)];let c=!1;if(this.viewFold)try{await this.refreshView(t)}catch(l){c=!0,this.live(t)&&(this.fail(l,!1),i=this.snapshot.error)}for(const l of o)try{await this.catchUp(l,t)}catch(d){c=!0,this.live(t)&&(this.fail(d,!1),i=this.snapshot.error)}!c&&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=Ct(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;return BN(n?{...t,policy:n}:t)}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=TN(n)}catch(d){this.fail(d,!1);return}const i=`${r.run_id}:${r.call_id}`;if(AN(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}},c=r.channel==="reasoning"?"reasoning":"text",l=o.seq[r.channel];if(r.snapshot){if(r.seq<l)return;o[c]=r.text}else{if(r.seq<=l)return;o[c]+=r.text}o.seq[r.channel]=r.seq,o.via=t,this.liveReplies.set(i,o),this.liveDirty.add(i),this.scheduleLiveRender()}runEnded(t){var r,i;const n=(r=this.viewFold)==null?void 0:r.view;return n?ds(String(((i=n.runs.find(o=>o.run_id===t))==null?void 0:i.status)||""))||t===this.rootRunId&&ds(String(n.status||"")):ds(xi(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(c=>c.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 c=[...this.snapshot.messages];if(n==="restarted"){const l=this.restartNote(t);this.seenMessages.add(String(l.id)),c[o]=l}else if(n){const l=`live-end:${r.runId}:${r.callId}`;this.seenMessages.add(l),c[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 c.splice(o,1);this.set({...this.snapshot,messages:c})}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:lL(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;_a(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:Ct((o=Jt(t))==null?void 0:o.detail)||String(t),..._a(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),ds(xi(n))&&this.endLiveRepliesOfRun(t,xi(n)),t!==this.rootRunId){ds(xi(n))&&((o=this.snapshot.interaction)==null?void 0:o.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const r=xi(n),i=ds(r);if(i){const c=xd(n.output);c&&this.upsertFinal(t,c,m0(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:Ry(this.snapshot.records).statistics},c=this.snapshot.messages.findIndex(d=>d.id===i||String(d.id||"").startsWith(`answer:${t}:`)&&d.content===n);if(c<0){this.set({...this.snapshot,messages:[...this.snapshot.messages,o]});return}const l=[...this.snapshot.messages];l[c]=o,this.set({...this.snapshot,messages:l})}async refreshRunState(t,n){var r;try{const i=Jt(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&&!ds(xi(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||ds(xi(this.runStates.get(t)||null)))return;try{const i=Jt(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(_a(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 c=setTimeout(d,t),l=()=>{clearTimeout(c),d()};function d(){r.removeEventListener("abort",l),o()}r.addEventListener("abort",l,{once:!0})})}}function NI(e){const t=p.useMemo(()=>new SI(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 Yc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Fr(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function g0(e){return["session","workflow","run","global"].includes(e)?e:null}function Yl(e){return{scope:Fr(e==null?void 0:e.scope).toLowerCase(),name:Fr(e==null?void 0:e.name)||Fr(e==null?void 0:e.event_name),scopeId:Fr(e==null?void 0:e.scope_id)||Fr(e==null?void 0:e.scopeId),sessionId:Fr(e==null?void 0:e.session_id)||Fr(e==null?void 0:e.sessionId),workflowId:Fr(e==null?void 0:e.workflow_id)||Fr(e==null?void 0:e.workflowId),runId:Fr(e==null?void 0:e.run_id)||Fr(e==null?void 0:e.runId)}}function $I(e,t){const n=e.wait,r=Fr(n.wait_key),i=[Yl(n),Yl(Yc(n.details))];for(const o of t){if(o.runId!==e.runId)continue;const c=o.record,l=Yc(c.result),d=Yc(l==null?void 0:l.wait),h=Yc(c.effect),m=Yc(h==null?void 0:h.payload);Fr(d==null?void 0:d.wait_key)!==r&&Fr(m==null?void 0:m.wait_key)!==r||i.push(Yl(c),Yl(m),Yl(Yc(m==null?void 0:m.details)),Yl(d),Yl(Yc(d==null?void 0:d.details)))}return i}function Dy(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function VN(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function CI(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?VN(t,n,i):null}function EI(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const r=Fr(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=g0(i[1]);if(!o)return{target:null,error:"The event wait uses an unsupported scope."};const c=$I(e,Array.isArray(t)?t:[]),l=new Map;for(const g of c){const y=g0(g.scope);if(!y||!g.name)continue;if(y!==o)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const x=`evt:${y}:`,k=`:${g.name}`;if(!r.startsWith(x)||!r.endsWith(k)||r.length<=x.length+k.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const v=r.slice(x.length,-k.length),N=Dy(y,g);if(N&&N!==v)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const $=VN(y,v,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 c){const y=Dy(o,g);y&&d.add(y)}if(Fr(n==null?void 0:n.run_id)===e.runId){const g=Yl(n||null),y=Dy(o,g);y&&d.add(y)}const m=[...d].map(g=>CI(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 HN(e){return s.jsx(gN,{text:e,images:"link"})}const AI={trigger:"Trigger",answer:"Automation"};function y0(e,t){return s.jsx(ax,{...t,message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:AI[e.kind],runId:e.runId},images:"link"})}function TI(e){const t=e;return!!(t&&typeof t=="object"&&typeof t.run_id=="string"&&typeof t.wait_key=="string"&&!("wait"in t))}function MI(e,t,n={}){var h;if(!e)return null;const r=TI(e)?zN(e):e,i=r.wait,o=`${r.runId}:${i.wait_key}:${r.stepId||""}`,c=i.details||{};if(c.mode==="approval_required"||c.kind==="tool_approval"){const m=Array.isArray(c.tool_calls)?c.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,x=n.onAllowForSession,k=String(n.approveAllScope||"").trim(),v=((h=n.remember)==null?void 0:h.call(n,g))||void 0,N=Uh,$=x?{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=x()}),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),V=P.ask?[...P.ask]:void 0,M=(H,J)=>{var te;const U=String(((te=H==null?void 0:H.scope)==null?void 0:te[J])||"").trim();return U?`Applies: ${U}`:N.noScopeNote},A=H=>({outcomeNote:[e0(H==null?void 0:H.clamped),M(H,"approve")].filter(Boolean).join(" ")}),O=H=>({outcomeNote:`${N.denyForChatNote} ${M(H,"deny")}`}),L=e0(K.clamped);if(K.mode==="unavailable")E={scopeNote:N.unavailablePolicyNote(K.reason||"")};else if(K.mode==="gateway"){const H=[...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=(V||[]).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}:{},...V?{ask:V}:{}})),approveKinds:H.map(z=>({kind:z,label:N.allowKindForChat(z),onApprove:async()=>A(await R.call(t,_,z,V?{ask:V}:{}))})),denyOptions:[...g.map(z=>({key:`tool:${z}`,label:N.denyToolForChat(z),onDeny:async()=>O(await I.call(t,_,z,V?{ask:V}:{}))})),...H.map(z=>({key:`kind:${z}`,label:N.denyKindForChat(z),onDeny:async()=>O(await W.call(t,_,z,V?{ask:V}:{}))}))],...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=x?{...$,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(jN,{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(hr,{value:m.length?m:c})]})]}),approveLabel:Uh.allowOnce,denyLabel:Uh.deny,approveAllLabel:y?Uh.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}:{},...v?{remember:v}:{},...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||c.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:")){if(r.command){const x=t.answerEvent;if(typeof x!="function")throw new Error("presentInteraction: an event wait from the replay view needs a WorkflowSessionController (answerEvent).");const k={runId:r.runId,waitKey:d,stepId:r.stepId};return{id:o,kind:"event-wait",title:"Waiting for your input",eventName:d,prompt:String(i.prompt||"This workflow is waiting for an event."),description:Array.isArray(i.choices)&&i.choices.length?`Expected: ${i.choices.map(v=>String(typeof v=="object"&&v!==null?v.label??v.value??"":v)).join(", ")}`:"The data you send resumes this wait.",initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send",onSend:async v=>{await x.call(t,JSON.parse(v||"{}"),k)}}}const _=EI(r,n.records||[],n.currentRun??null),g=_.target,y=(g==null?void 0:g.name)||"";return{id:o,kind:"event-wait",title:g?"Waiting for an event":"Event routing unavailable",eventName:y,prompt:String(i.prompt||`This workflow will continue when “${y||"its trigger"}” arrives.`),description:g?"You can also send the expected event here.":`This event cannot be sent safely. ${_.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async x=>{if(!g)throw new Error(_.error);const k=JSON.parse(x||"{}"),v={name:g.name,scope:g.scope,payload:k};g.scope==="session"?v.session_id=g.scopeId:g.scope==="workflow"?v.workflow_id=g.scopeId:g.scope==="run"&&(v.run_id=g.scopeId),await t.emitEvent(v)}}}return null}const RI={app:"observer",name:"AbstractObserver"},LI=["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 II(e){const t=p.useRef(e.gateway);t.current=e.gateway;const n=(r,i)=>t.current.fetch_gateway(r,i);return s.jsx(zL,{open:e.open,onClose:e.onClose,source:RI,fetchGateway:n,connected:e.connected,topOffset:e.topOffset,placeholder:"Ask about the observer…",suggestions:LI})}function OI(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 PI(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 DI(e,t,n){return e<=0?-1:t<0?n?e-1:0:(t+(n?e-1:1))%e}const FI='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function zI(e){return typeof document>"u"?!1:Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e)}function BI(e){const[t,n]=p.useReducer(OI,!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 c;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:zI(i.current)});return}if(m.key!=="Tab"||!i.current)return;const _=Array.from(i.current.querySelectorAll(FI)).filter(y=>y.offsetParent!==null||y===document.activeElement),g=DI(_.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,(c=r.current)==null||c.focus())},[t]),{open:t,set_open:c=>n({type:c?"open":"close"}),toggle_ref:r,sidebar_ref:i,attrs:PI(e.is_drawer,t)}}function UI(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function rp(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function WI(e){const t=rp(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=rp(e.replayed_messages),r=rp(e.dropped_tokens),i=rp(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 qI(e){const t=WI(e.history);return t?s.jsx(ax,{message:{role:"system",level:"info",title:"History",content:t}}):null}const VI="api/local/reveal",HI="sw.js",ev="#run/";function GI(e){return`${ev}${encodeURIComponent(String(e||"").trim())}`}function GN(e){const t=String(e||"");if(!t.startsWith(ev))return"";const n=t.slice(ev.length).split("?")[0];if(!n||n.includes("/"))return"";try{return decodeURIComponent(n).trim()}catch{return""}}function KI(e){return`Run ${e} cannot be opened: it does not exist on this gateway, or your account cannot see it.`}function JI(e){const t=GN(e.hash);if(t)return t;const n=c=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(c),r=c=>{const l=c.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 YI={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"},XI=new Set(["wait","resume","memory","model","node"]),ZI=new Set(["abstract.status","abstract.progress","abstract.steer_seen","abstract.summary"]),QI={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 eO(e){const t=String(e||"").trim();return t?YI[t]||"other":"node"}function tO(e,t,n){return n?!1:e==="event"?ZI.has(String(t||"").trim()):XI.has(e)}const nO=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 sO(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 c=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,x,k,v]=c;for(let N=0;N<64;N++){const $=(y>>>6|y<<26)^(y>>>11|y<<21)^(y>>>25|y<<7),E=y&x^~y&k,S=v+$+E+nO[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;v=k,k=x,x=y,y=g+S>>>0,g=_,_=m,m=h,h=S+R>>>0}c[0]=c[0]+h>>>0,c[1]=c[1]+m>>>0,c[2]=c[2]+_>>>0,c[3]=c[3]+g>>>0,c[4]=c[4]+y>>>0,c[5]=c[5]+x>>>0,c[6]=c[6]+k>>>0,c[7]=c[7]+v>>>0}return Array.from(c,d=>d.toString(16).padStart(8,"0")).join("")}const tv="$slim";function rO(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&e[tv]&&typeof e[tv]=="object")}function iO(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 oO(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 aO(e,t){const n=e&&e[tv];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 c=String(n.field||"");if(!(c in r))return{state:"missing",reason:`the started record has no "${c}" field`};i=r[c]}else if(n.kind==="started_messages_layout"){if(i=Array.isArray(n.layout)?oO(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 c=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>c.length)return{state:"missing",reason:"appendix position out of range"};c.splice(h,0,d.item)}i=c}return sO(JSON.stringify(i))!==String(n.sha256||"")?{state:"unverified",value:i,reason:"checksum differs from the record"}:{state:"resolved",value:i}}function lO(e,t){const n=[],r=[],i=(o,c,l)=>{if(l>14)return o;if(rO(o)){const d=aO(o,t);return d.state==="missing"?(n.push({path:c,reason:d.reason}),o):(d.state==="unverified"&&r.push({path:c,reason:d.reason}),d.value)}if(Array.isArray(o)){let d=null;return o.forEach((h,m)=>{const _=i(h,`${c}[${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],c?`${c}.${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 w0(e){const t=Date.parse(String(e||""));return Number.isFinite(t)?t:null}function KN(e){const t=e==null?void 0:e.result;return t&&typeof t=="object"&&Array.isArray(t.results)?t.results:[]}function cO(e,t){return e?String(e.status||"")==="failed"||e.error?!0:t==="tool"&&KN(e).some(n=>n&&n.success===!1):!1}function uO(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 Ig(e,t){var h,m,_,g,y,x;const n=String(t||"").trim(),r=(e||[]).filter(k=>k&&k.record&&String(k.run_id||k.record.run_id||"").trim()===n).sort((k,v)=>(k.cursor||0)-(v.cursor||0)),i=iO(r.map(k=>k.record)),o=new Map,c=[];for(const k of r){const v=k.record,$=uO(v)||`cursor:${k.cursor}`;let E=o.get($);E||(E={cursor:k.cursor,started:null,latest:v,latest_cursor:k.cursor},o.set($,E),c.push($)),String(v.status||"")==="started"&&!E.started&&(E.started=v),k.cursor>=E.latest_cursor&&(E.latest=v,E.latest_cursor=k.cursor)}let l=0;const d=[];for(const k of c){const v=o.get(k),N=lO(v.latest,i),$=N.value,E=String(((h=$==null?void 0:$.effect)==null?void 0:h.type)||((_=(m=v.started)==null?void 0:m.effect)==null?void 0:_.type)||"").trim(),S=eO(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=cO($,S),R=String(((x=v.started)==null?void 0:x.started_at)||($==null?void 0:$.started_at)||""),I=String(($==null?void 0:$.ended_at)||""),W=w0(R),G=w0(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:v.cursor,started_at:R,ended_at:I,duration_ms:W!==null&&G!==null?Math.max(0,G-W):null,started:v.started,record:$,failed:D,housekeeping:tO(S,P,D),cycle:l,unresolved:N.unresolved,unverified:N.unverified})}return d}function dO(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 fO={view:"cycles",only:"all",all_steps:!1,q:""};function hO(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 mO=["all","llm","tools","failed"];function v0(e){const t=String(e||""),n=t.indexOf("?");if(n<0)return{...fO};const r=new URLSearchParams(t.slice(n+1)),i=String(r.get("only")||"");return{view:r.get("view")==="steps"?"steps":"cycles",only:mO.includes(i)?i:"all",all_steps:r.get("all")==="1",q:String(r.get("q")||"")}}function _O(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 zd(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(`
88
+ `):e==null?"":JSON.stringify(e,null,2)}function JN(e){if(typeof e!="string")return e??{};try{return JSON.parse(e)}catch{return e}}function YN(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:JN(t.arguments??((r=t.function)==null?void 0:r.arguments))}}):[]}function x0(e){const t={role:String((e==null?void 0:e.role)||"?"),content:zd(e==null?void 0:e.content)},n=YN(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 b0(e){const t=Number(e);return Number.isFinite(t)&&e!==null&&e!==void 0?t:null}const pO={"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 $m(e){var x,k,v,N,$,E,S;const t=e.record||{},n=((k=(x=e.started)==null?void 0:x.effect)!=null&&k.payload&&typeof e.started.effect.payload=="object"?e.started.effect.payload:(v=t==null?void 0:t.effect)==null?void 0:v.payload)||{},r=t!=null&&t.result&&typeof t.result=="object"?t.result:{},i=r.usage||r.token_usage||{},o=[],c=e.unverified.map(P=>`${P.path}: ${P.reason}`);for(const P of e.unresolved){const D=pO[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?`
89
+
90
+ `:"")+zd(P.content):h.push(x0(P))}else(Array.isArray(n.messages)||typeof n.prompt=="string")&&(m="payload",h=(Array.isArray(n.messages)?n.messages:[]).map(x0),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:b0(i.prompt_tokens??i.input_tokens),tokens_out:b0(i.completion_tokens??i.output_tokens),system:d,messages:h,messages_source:m,tools:g,response:zd(r.content??r.response??""),tool_calls:YN(r.tool_calls),reasoning:zd(r.reasoning??((S=r==null?void 0:r.metadata)==null?void 0:S.reasoning)??""),missing:o,unverified:c}}function Cm(e){var i,o,c,l;const t=((o=(i=e.record)==null?void 0:i.effect)==null?void 0:o.payload)||((l=(c=e.started)==null?void 0:c.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:JN((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=KN(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?"":zd(d.output),error:(d==null?void 0:d.error)==null?"":zd(d.error),call_id:String((d==null?void 0:d.call_id)||""),raw:d}));return{calls:n,results:r}}function gO(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 Em(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 XN(e){var n,r,i,o,c,l,d,h,m,_,g;const t=e.record||{};switch(e.kind){case"llm_call":{const y=$m(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=Cm(e).calls;if(!y.length)return"";const x=`${y[0].name}(${gO(y[0].arguments)})`;return y.length>1?`${x} +${y.length-1} more`:x}case"event":return e.event_name;case"subflow":{const y=Em(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=(c=t==null?void 0:t.effect)==null?void 0:c.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 ZN(e){return e.kind==="llm_call"?$m(e).model:""}function yO(e,t){var r,i;const n=[e.kind,e.effect_type,e.event_name,e.node_id,t,e.status,XN(e),ZN(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(`
91
+ `).toLowerCase()}function wO(e){var r,i;const t=Array.from(new Set((e||[]).map(o=>{var c;return String(o.run_id||((c=o.record)==null?void 0:c.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 c of Ig(e,o))if((c.failed||String(c.status||"")==="failed")&&(n.failed_steps+=1),c.kind==="llm_call"){n.llm_calls+=1;const l=((i=(r=c.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(c.kind==="tool"){const l=Cm(c);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 vO(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 xO(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function zr(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 tn(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,`
92
+ `).replace(/\r/g,`
93
+ `).split(`
94
+ `),c=o.slice(0,Math.max(1,r)).join(`
95
+ `),l=o.length>r,d=c.length>n?`${c.slice(0,Math.max(0,n-1))}…`:c;return l&&d===c?`${c}…`:d}function Ln(e,t){const n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function k0(e){const t=String(e||"").trim();return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function Vt(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 bO(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 cu(e){const t=Vt(e);return t===null?"—":bO(t)}function nm(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,c=n%60,l=r%24;return i>0?`${i}d ${l}h`:r>0?`${r}h ${c}m`:n>0?`${n}m ${o}s`:`${t}s`}function bu(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),c=o%24,l=Math.floor(o/24);return l>0?`${l}d ${c}h`:o>0?`${o}h ${i}m`:r>0?`${r}m ${n}s`:`${Math.max(0,t)}s`}function Kd(e){const t=Vt(e);return t===null?"—":new Date(t).toLocaleString()}function Vn(...e){for(const t of e){const n=String(t??"").trim();if(n)return n}return""}function kO(...e){for(const t of e){const n=Number(t);if(Number.isFinite(n))return n}return null}function hs(e){const t=String(e||"").trim().toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}function Jd(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function Id(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function jO(e){const t=String((e==null?void 0:e.status)||"").trim();return hs(t)?String((e==null?void 0:e.finished_at)||(e==null?void 0:e.updated_at)||"").trim():""}function Am(e,t=Date.now()){const n=Vt(Id(e));if(n===null)return-1;const r=Vt(jO(e));return Math.max(0,(r!==null?r:t)-n)}function yu(e,t=Date.now()){return bu(Am(e,t))}function SO(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 Qp(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 sm(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 Sa(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 NO={all:"All",llm:"LLM calls",tools:"Tools",failed:"Failed"};function yo(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function xa(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 Fy(e){return`${e.toLocaleString("en-US")} chars`}function fx(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(xa,{title:"Raw JSON",copy:yo(t),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(hr,{value:t,collapseAfterDepth:2,showCopy:!1})})})}function $O(e){const t=$m(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(xa,{title:"System",meta:Fy(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(xa,{title:"Messages",meta:`${t.messages.length}${t.messages_source==="sent"?" · as sent":""}`,copy:yo(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((c,l)=>s.jsx("pre",{className:"rs_text mono",children:`${c.name}(${yo(c.arguments)})`},l))]},i)})})}):null,t.tools.length?s.jsx(xa,{title:"Tools offered",meta:String(t.tools.length),copy:yo(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(xa,{title:"Response",meta:t.tool_calls.length?`${t.tool_calls.length} tool call${t.tool_calls.length===1?"":"s"}`:t.response?Fy(t.response.length):"empty",copy:t.response||yo(t.tool_calls),open:!0,on_copy:e.on_copy,children:[t.response?s.jsx("div",{className:"rs_markdown",children:s.jsx(Ni,{text:t.response})}):null,t.tool_calls.map((r,i)=>s.jsx("pre",{className:"rs_text mono",children:`${r.name}(${yo(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(xa,{title:"Reasoning",meta:Fy(t.reasoning.length),copy:t.reasoning,on_copy:e.on_copy,children:s.jsx("pre",{className:"rs_text",children:t.reasoning})}):null,s.jsx(fx,{step:e.step,on_copy:e.on_copy})]})}function CO(e){const t=Cm(e.step);return s.jsxs(s.Fragment,{children:[s.jsx(xa,{title:"Calls",meta:String(t.calls.length),copy:yo(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}(${yo(n.arguments)})`},r))}),s.jsxs(xa,{title:"Results",meta:String(t.results.length),copy:yo(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(xN,{sandbox:Kw(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(fx,{step:e.step,on_copy:e.on_copy})]})}function EO(e){var i,o,c;const t=e.step.record||{},n=((o=(i=e.step.started)==null?void 0:i.effect)==null?void 0:o.payload)??((c=t==null?void 0:t.effect)==null?void 0:c.payload),r=e.step.kind==="subflow"?Em(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:yo(t.error)}):null,n!=null?s.jsx(xa,{title:"Payload",copy:yo(n),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(hr,{value:n,collapseAfterDepth:2,showCopy:!1})})}):null,t.result!==void 0&&t.result!==null?s.jsx(xa,{title:"Result",copy:yo(t.result),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(hr,{value:t.result,collapseAfterDepth:2,showCopy:!1})})}):null,s.jsx(fx,{step:e.step,on_copy:e.on_copy})]})}function AO(e){const t=e.step,n=XN(t),r=ZN(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:QI[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 ${Sa(i)}`,children:i||"—"}),s.jsx("span",{className:"rs_dur",children:t.duration_ms!==null?bu(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($O,{step:t,on_copy:e.on_copy}):t.kind==="tool"?s.jsx(CO,{step:t,on_copy:e.on_copy}):s.jsx(EO,{step:t,on_copy:e.on_copy,on_open_run:e.on_open_run})}):null]})}function TO(e){const{state:t}=e,n=p.useMemo(()=>Ig(e.items,e.run_id),[e.items,e.run_id]),[r,i]=p.useState({}),o=x=>e.node_label(x.run_id,x.node_id),c=p.useMemo(()=>new Map,[n]),d=hO(n,t,x=>{let k=c.get(x.id);return k===void 0&&(k=yO(x,o(x)),c.set(x.id,k)),k}),h=n.some(x=>x.kind==="llm_call"),m=n.reduce((x,k)=>k.kind==="llm_call"?x+1:x,0),_=n.length-d.length,g=x=>e.on_state({...t,...x}),y=x=>s.jsx(AO,{step:x,node_label:o(x),open:r[x.id]===!0,on_toggle:()=>i(k=>({...k,[x.id]:!k[x.id]})),on_copy:e.on_copy,on_open_run:e.on_open_run},x.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:x=>e.on_select_run(String(x.target.value||"")),"aria-label":"Run",children:e.run_options.map(x=>s.jsxs("option",{value:x,children:[Ln(x,14),e.run_llm_counts[x]?` · ${e.run_llm_counts[x]} LLM`:""]},x))}):null]}),s.jsxs("div",{className:"rs_toolbar",children:[s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Layout",children:["cycles","steps"].map(x=>s.jsx("button",{type:"button",role:"radio","aria-checked":t.view===x,className:`seg_btn ${t.view===x?"active":""}`,onClick:()=>g({view:x}),children:x==="cycles"?"Cycles":"Steps"},x))}),s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Show",children:["all","llm","tools","failed"].map(x=>s.jsx("button",{type:"button",role:"radio","data-filter":x,"aria-checked":t.only===x,className:`seg_btn ${t.only===x?"active":""}`,onClick:()=>g({only:x}),children:NO[x]},x))}),s.jsx("input",{className:"rs_search",type:"search",value:t.q,onChange:x=>g({q:x.target.value}),placeholder:"Search steps","aria-label":"Search steps",autoComplete:"off",spellCheck:!1}),t.only==="all"?s.jsx(Fi,{label:"All steps",action:"show-all-steps",hint:"Also list status events, waits, resumes and memory bookkeeping.",checked:t.all_steps,onChange:x=>g({all_steps:x})}):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?dO(d).map(x=>s.jsxs("section",{className:"rs_cycle","data-cycle":x.cycle,children:[s.jsx("h3",{className:"rs_cycle_head",children:x.cycle===0?"Before the first call":`Cycle ${x.cycle}`}),x.steps.map(y)]},x.cycle)):d.map(y)]})}function MO(e){const[t,n]=p.useState(!1),r=e.answer.length>j0,i=t||!r?e.answer:`${e.answer.slice(0,j0).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 ${Sa(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(Ni,{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 j0=600;let Tp={connections:null,mailboxes:null};const RO=new Set;function LO(e){if(!(e.connections===Tp.connections&&e.mailboxes===Tp.mailboxes)){Tp={connections:e.connections,mailboxes:e.mailboxes};for(const t of RO)t()}}function IO(e,t,n=Tp){return!e||typeof e!="object"?"":bm(e,n.connections,n.mailboxes,t)}const S0="—";function bd(e){return typeof e=="string"&&e?e:void 0}function OO(e){return e.endsWith("+00:00")||e.endsWith("Z")}function zy(e){if(!e||typeof e!="object")return e;const t=e,n={...e},r=bd(t.next_run_at)??bd(t.next_fire_at);let i=bd(t.next_run_local),o=bd(t.time_zone)??"";return!i&&!o&&r&&OO(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=bd(t.schedule_rule_text)??S0,n.schedule_text=bd(t.schedule_text)??S0,n}function PO(e){return{...e,listAutomations:async t=>{const n=await e.listAutomations(t);return{...n,items:(n.items??[]).map(zy)}},getAutomation:async t=>{const n=await e.getAutomation(t);return n!=null&&n.summary?{...n,summary:zy(n.summary)}:n},createAutomation:async t=>{const n=await e.createAutomation(t);return n!=null&&n.summary?{...n,summary:zy(n.summary)}:n}}}const DO="@default:",Bd="abstractcode.agent.v1";function N0(e,t){var n;return e?e.kind==="default"?e.interface===Bd?"@default":"":((n=t.find(r=>r.bundleId===e.bundle_id&&r.flowId===e.flow_id))==null?void 0:n.value)??"":""}function FO(e,t){return e==="@default"?{kind:"default",interface:Bd}:t?{kind:"bundle",bundle_id:t.bundleId,flow_id:t.flowId}:null}function zO(e){return e?e.kind==="default"?`${DO}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function BO(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 UO(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 WO={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 qO(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 VO="#launch/automate";function HO(e){const t=GN(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 nv={when:"every",email_account:"default",connection_id:"",calendar:VS,email:SS,notify_email:!1,email_recipients:Gh,amount:"24",unit:"h",once_at:"",context:"independent",growing_max_tokens:String(em),tool_approval:"auto",title:"",start_at:"",count:"",until:""},$0={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."},QN=["use_context"],GO="This choice also tells the flow whether to read the earlier runs.",e1=["event"];function KO(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 t1(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 JO(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:!0}function YO(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()}:{}},c={...n.input_data||{}};for(const[m,_]of Object.entries(t||{}))JO(_)&&(c[m]=_);return{form:o,input_data:c}}function XO(e,t){return e.interfaces.length?null:e.automationTrigger?[bm(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 n1(e){return[...e||[]].filter(t=>t.configured!==!1&&t.can_read!==!1).sort((t,n)=>Number(n.primary)-Number(t.primary))}function ZO(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 QO(e,t){const n=[];for(const r of n1(e))n.push({value:`mail:${r.account_id}`,label:`Mail arrives in ${$g(r.account_id,e)}`,group:"mail",problem:""});for(const r of t||[]){if(r.status&&r.status!=="active"&&r.status!=="paused")continue;const i=yS(r.label||"a connection",r.source_id),o=ZO(r);n.push({value:`conn:${r.connection_id}`,label:`${i.replace(/^When /,"")}${o?` — ${o.startsWith("not working")?"not working":o}`:""}`,group:xm(r.source_id),problem:o})}return n}function Xc(e){return e.when==="email"?`mail:${e.email_account||"default"}`:e.when==="connection"&&e.connection_id?`conn:${e.connection_id}`:""}function C0(e){return e.startsWith("mail:")?{when:"email",email_account:e.slice(5)||"default"}:e.startsWith("conn:")?{when:"connection",connection_id:e.slice(5)}:{}}function hx(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?sx(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 e3(e,t){if(e.when==="defaults")return t&&t.trigger.source_id==="schedule"?t1(t):null;if(e.when==="email"||e.when==="connection"||e.when==="manual")return null;const n=hx(e,"preview");return iT(n.when)?US(n).trigger:null}function t3(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?n1(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:[$n.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=UO(t.input_data),c=typeof o.prompt=="string"?o.prompt:"";delete o.prompt;for(const g of QN)delete o[g];for(const g of e1)delete o[g];delete o.workspace_root;let l;try{l=BO(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=hx(d?{...e,when:"every",amount:"24",unit:"h",start_at:"",count:"",until:""}:e,c,t.email_usable===!0||e.when==="email"&&r),m=WS(h,{target:l,requestId:t.request_id});if(!m.ok)return m;const _=m.body;return e.when==="defaults"&&t.defaults?_.trigger=t1(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 n3(e,t=!1){if(e.when==="email"){if(!t)return"";const n=WS(hx(e,"preview",!0),{target:{flow_id:"@default",interface:Bd},requestId:"preview"});return n.ok?`Runs ${$S(n.body.trigger.config)}.`:""}return""}class s3{constructor(t){jn(this,"key","");jn(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 r3(e,t,n){const r=t3(e,{...t,request_id:""});if(!r.ok)return r;const{request_id:i,...o}=r.body,c=n.id_for(JSON.stringify(o));return{ok:!0,body:{...r.body,request_id:c}}}function pa(e){return typeof e=="string"?e:e??null}function ip(e){var t,n,r,i,o,c;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:pa(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:pa(e==null?void 0:e.created_at),updated_at:pa(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:pa(e==null?void 0:e.parent_run_id),session_id:pa(e==null?void 0:e.session_id),actor_id:pa(e==null?void 0:e.actor_id),session_kind:pa(e==null?void 0:e.session_kind),automation_id:pa(e==null?void 0:e.automation_id),role:pa(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:pa(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():((c=e==null?void 0:e.schedule)==null?void 0:c.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 i3(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 Og(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 s1(e){const t=Og(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`run #${e.occurrence_index}`:"automation run":t==="legacy"?"legacy schedule":t||""}function o3(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 el(e){return e.legacy===!0||e.capabilities.includes("legacy")}function r1(e,t=Date.now(),n){const r=el(e),i=e.last_occurrence,o=i&&i.attempts>1?` after ${i.attempts} attempts`:"",c=e.attention.unread||e.attention.pending_waits>0,l=!r&&uc(e.trigger)&&e.status==="active"&&!e.next_run_at,d=l&&i?Zh(i.fired_at,{timeZone:e.time_zone,nowMs:t,style:"day"}):"";return{id:e.automation_id,title:e.title,cadence:Zv(e.trigger,e,n??null),next_run:l?"runs when something new arrives":TS(e,t),listening:l,current:AS(e),state:e.status,last:i?i.excerpt:"",last_status:i?`${d?`last: ${d} · `:""}#${i.index} ${i.status}${o}`:"no runs yet",attention:c?MS(e):null,legacy:r}}function i1(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 a3(e,t){const n=Qh(e,[],t),r=i1(e),i=t?{enabled:!1,reason:"Working…"}:el(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 l3(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 c3(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 u3=/^([1-9][0-9]*)([smhd])$/;function d3(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 f3(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 c=[],l={...nv},d=typeof n.interval=="string"?n.interval.trim():"";if(!d)l.when="once",c.push("The legacy schedule ran once; pick the date and time to run.");else{const g=u3.exec(d);let y=g?Number(g[1]):0,x=g?g[2]:"";x==="s"&&y%60===0&&(y=y/60,x="m"),x==="m"||x==="h"||x==="d"?(l.amount=String(y),l.unit=x):c.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=d3(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:c}}const h3={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 m3(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 c=await r(o),l=c&&typeof c=="object"?c.input_data:null;return l&&typeof l=="object"&&!Array.isArray(l)?l:null}}:{},answer_wait:async(o,c,l)=>{await e.submit_command({command_id:t(),run_id:o,type:"resume",payload:{wait_key:c,payload:l},client_id:"web_pwa"})},legacy_command:async(o,c,l)=>{await e.submit_command({command_id:t(),run_id:o,type:c,payload:l,client_id:"web_pwa"})},now_iso:n}}function _3(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 By(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function E0(e){return e.items.filter(t=>t.status==="archived").length}function mx(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 p3=3e4,op=50;function Pi(e){return tx(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function Uy(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 g3{constructor(t,n,r=[1500,4e3]){jn(this,"state",{...h3});jn(this,"listeners",new Set);jn(this,"list_seq",0);jn(this,"detail_seq",0);jn(this,"sources_loaded",!1);jn(this,"client");jn(this,"preview_schedule",t=>this.client.previewSchedule(t));jn(this,"events_inflight",new Set);jn(this,"definitions",new Map);this.host=n,this.followups_ms=r,this.client=PO(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:op});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;LO({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 Eg(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:Pi(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&&el(o)){this.set({detail:{automation_id:n,summary:o,definition:null,occurrences:[],next_cursor:null,error:null,occurrence_events:{}}});return}const[c,l]=await Promise.all([this.client.getAutomation(n),this.client.listOccurrences(n,{limit:op})]);if(r!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:o??c.summary,definition:c.definition,occurrences:Uy([],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:Pi(o)})}}async reload_occurrences(t){const n=this.state.detail;if(!n||n.automation_id!==t||el(n.summary))return;const[r,i]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:op})]),o=this.state.detail;if(!o||o.automation_id!==t)return;const c=this.state.items.find(l=>l.automation_id===t);this.set({detail:{...o,summary:c??r.summary,definition:r.definition,occurrences:Uy(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||el(n.summary)||!uc(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 c=this.state.detail;!c||c.automation_id!==t||this.set({detail:{...c,occurrence_events:{...c.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:op}),r=this.state.detail;if(!r||r.automation_id!==t.automation_id)return;this.set({detail:{...r,occurrences:Uy(r.occurrences,n.items),next_cursor:n.next_cursor}}),this.load_occurrence_events(t.automation_id)}catch(n){this.set({error:Pi(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 Pi(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 Pi(o)}finally{this.set({busy:!1})}}definition(t){if(el(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(c=>c.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:mx(n,o)}),o}catch(o){throw Pi(o)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(r){throw Pi(r)}}async answer_wait(t,n,r,i){var o;this.set({busy:!0});try{const c=(((o=this.state.detail)==null?void 0:o.occurrences)||[]).flatMap(l=>l.waits).find(l=>l.run_id===n&&l.wait_key===r);if(!c)throw new Error(`No loaded wait ${r} on run ${n}; reload the automation.`);await this.host.answer_wait(n,r,_3(c.kind,i)),await this.after_change(t)}catch(c){throw Pi(c)}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"?A0(t.title,n==="resume"):`${y3[n]} sent to “${t.title}”.`,confirm_archive_id:""})}catch(i){this.set({error:Pi(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(!el(t))throw new Error("legacy_action on a non-legacy automation");const r=c3(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}”.`:A0(t.title,n==="legacy_resume")}),await this.refresh()}catch(i){this.set({error:Pi(i)})}finally{this.set({busy:!1})}}report_error(t){this.set({error:Pi(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 A0(e,t){return t?`“${e}” is active: it runs on its schedule.`:`“${e}” is paused: scheduled runs are skipped.`}const y3={run_now:"Run now",archive:"Archive"},_o={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 w3(e,t,n){const r=n&&n.phase==="ok"?n.description.schedule_rule_text:null;return bm(e.trigger,t.connections,t.mailboxes,r?{schedule_rule_text:r}:null)}function v3(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:WO[e.mode]})]})}function x3(e){var h,m;const t=e.form,n=Eg(e.email_status),r=QO(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===Xc(t))?"every":t.when,c=o==="email"||o==="connection",l=n3(t,n),d=(_,g,y,x,k=!1)=>s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:_,checked:y,disabled:e.disabled||k,onChange:x})," ",g]},_);return s.jsxs("div",{className:"automate_fields",children:[s.jsxs("fieldset",{"data-section":"when",children:[s.jsx("legend",{children:fs.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"})})," ",_o.use_flow," ",s.jsx("strong",{"data-field":"flow-trigger",children:w3(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"})})," ",_o.other]})]}):null,o==="defaults"&&i?i.trigger.source_id==="schedule"?s.jsx("div",{className:"automate_preview automate_preview--served",children:s.jsx(Uw,{state:e.served,onOpenPreferences:e.on_open_preferences,showZone:!0})}):s.jsx("p",{className:"help_text muted","data-help":"flow-trigger",children:uc(i.trigger)?_o.event_help:i.trigger.source_id==="manual"?_o.manual_help:""}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"automate_row",role:"radiogroup","aria-label":"Schedule kind",children:[d("every",fs.kind_every,o==="every",()=>e.on_change({when:"every"})),["daily","weekly","monthly"].map(_=>d(_,fs[`kind_${_}`],o===_,()=>e.on_change({when:_}))),d("once",fs.kind_once,o==="once",()=>e.on_change({when:"once"})),d("arrives",_o.arrives,c,()=>e.on_change(r.length?C0(r.some(_=>_.value===Xc(t))?Xc(t):r[0].value):{when:"connection",connection_id:""})),d("manual",_o.manual,o==="manual",()=>e.on_change({when:"manual"}))]}),c?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:Xc(t),disabled:e.disabled,onChange:_=>e.on_change(C0(_.target.value)),children:[Xc(t)?null:s.jsx("option",{value:"",children:_o.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:[_o.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,c&&((m=r.find(_=>_.value===Xc(t)))!=null&&m.problem)?s.jsx("div",{className:"warn_callout",role:"note","data-note":"arrival-problem",children:`This one is ${r.find(_=>_.value===Xc(t)).problem}. It runs again once it reads; fix it on the gateway console's Triggers page.`}):null,o==="email"?s.jsx(FT,{value:t.email,onChange:_=>e.on_change({email:_}),disabled:e.disabled,idBase:"automate"}):o==="daily"||o==="weekly"||o==="monthly"?s.jsx(HS,{value:sx(o,t.calendar),onChange:_=>e.on_change({calendar:rx(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:tT.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:fs.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:fs.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:_o.event_help}):o==="manual"?s.jsx("p",{className:"help_text muted","data-help":"manual",children:_o.manual_help}):s.jsx("div",{className:"automate_preview automate_preview--served",children:s.jsx(Uw,{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) — ",$0.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"})," — ",$0.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:GO})]}),s.jsxs("fieldset",{"data-section":"tools",children:[s.jsx("legend",{children:"Tools"}),e.available_tools&&e.on_tools_change?s.jsx(KS,{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:_o.untrusted_mail}):o==="connection"||o==="defaults"&&i&&uc(i.trigger)?s.jsx("p",{className:"help_text muted","data-event-rule":"untrusted",children:_o.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"})})," ",oT,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(tN,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),s.jsx(zT,{notifyEmail:n&&t.notify_email,onNotifyEmailChange:_=>e.on_change({notify_email:_}),recipients:n?t.email_recipients:Gh,onRecipientsChange:_=>e.on_change({email_recipients:_}),disabled:e.disabled||!n,idBase:"automate"})]})]})}function T0(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toISOString().slice(0,16)}function M0(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 b3(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:M0(t.start_at),disabled:e.disabled,onChange:n=>e.on_change({start_at:T0(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:M0(t.until),disabled:e.disabled,onChange:n=>e.on_change({until:T0(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 k3(e,t){const n=String(t||"").trim();return n||`Loading ${String(e||"").trim()||"data"}…`}function ol(e){const t=k3(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 j3={console:"Console",tray:"Tray",watch:"Watch",phone:"Phone",email:"Email",assistant:"Assistant",code:"Code"};function S3(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 N3(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 $3(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 C3(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 E3(e){const t=j3[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 A3=3e3,T3=5;function M3(e,t){return t>T3?!1:e.quiet_reason==="not recorded yet"||e.quiet_reason==="still running"?!0:!!e.attention&&e.deliveries.length===0}function R0(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 R3(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(ol,{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(L3,{after:t.after})]})}function L3(e){const t=e.after,n=N3(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(c=>!c.record_key||c.record_key===i.record_key);return s.jsxs("li",{children:[s.jsx("span",{className:"after_run_alert_title",children:$3(i)}),s.jsxs("span",{className:"muted",children:[" ","· ",C3(i),i.raised_at?` · ${R0(i.raised_at)}`:""]}),o.length?s.jsx("ul",{className:"after_run_deliveries",children:o.map((c,l)=>s.jsxs("li",{"data-state":c.state,children:[E3(c),c.time?s.jsxs("span",{className:"muted",children:[" · ",R0(c.time)]}):null]},`${c.channel}:${c.device||""}:${l}`))}):s.jsx("div",{className:"muted",children:"No delivery recorded yet."})]},i.record_key)})}):s.jsx("span",{"data-field":"quiet",children:S3(t.quiet_reason)})})]})}const I3=[1e3,3e3];async function O3(e,t=I3){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 P3(e){const{run_id:t,read:n}=e,[r,i]=p.useState({status:"loading"}),[o,c]=p.useState(0),l=p.useRef(null),d=p.useCallback(()=>{i({status:"loading"}),c(h=>h+1)},[]);return p.useEffect(()=>{let h=!0,m=0;const _=async()=>{m+=1;try{const g=await O3(()=>n(t));if(!h)return;i({status:"ready",after:g}),M3(g,m)&&(l.current=setTimeout(_,A3))}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(R3,{state:r})}function Zs(){return nl()}const o1=kg("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).",a1="Copy failed — select and copy";function l1(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function D3(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 Tm(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 D3(t)}const F3=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 z3(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),c=(l,d)=>l>>>d|l<<32-d;for(let l=0;l<n.length;l+=64){for(let v=0;v<16;v++)o[v]=r.getUint32(l+v*4,!1);for(let v=16;v<64;v++){const N=c(o[v-15],7)^c(o[v-15],18)^o[v-15]>>>3,$=c(o[v-2],17)^c(o[v-2],19)^o[v-2]>>>10;o[v]=o[v-16]+N+o[v-7]+$>>>0}let[d,h,m,_,g,y,x,k]=[i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7]];for(let v=0;v<64;v++){const N=c(g,6)^c(g,11)^c(g,25),$=g&y^~g&x,E=k+N+$+F3[v]+o[v]>>>0,S=c(d,2)^c(d,13)^c(d,22),P=d&h^d&m^h&m,D=S+P>>>0;k=x,x=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]+x>>>0,i[7]=i[7]+k>>>0}return Array.from(i,l=>l.toString(16).padStart(8,"0")).join("")}async function B3(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 z3(t)}const U3=/^[a-zA-Z0-9_-]+$/;function L0(e){return U3.test(String(e||"").trim())}async function W3(e){const t=String(e||"");return B3(t)}async function q3(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(L0(t)){const r=`session_memory_${t}`;if(L0(r))return r}return`session_memory_sha_${(await W3(t)).slice(0,32)}`}const c1="abstractobserver_voice";function V3(){var e;try{const t=(e=globalThis.localStorage)==null?void 0:e.getItem(c1),n=t?JSON.parse(t):null;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return{}}}const sv=new Set;function H3(e){var t;try{(t=globalThis.localStorage)==null||t.setItem(c1,JSON.stringify(e||{}))}catch{}for(const n of sv)n(e||{})}function u1(){const[e,t]=p.useState(()=>V3());return p.useEffect(()=>(sv.add(t),()=>{sv.delete(t)}),[]),[e,H3]}function d1(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 G3(e){if(e)return{design:t=>e.voice_design(t),clone:(t,n)=>e.voice_clone(t,n)}}function K3(e){const t=e.gateway;return s.jsx(oR,{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:G3(t),unavailableReason:e.connected&&t?null:"Connect to a gateway to configure voice."})}const J3=18e4;function Y3(e,t,n,r=()=>{}){return async function*(i,o){r(),yield*W2({path:e.gateway_url(wt(`runs/${encodeURIComponent(t)}/voice/tts/stream`)),headers:e.auth_headers(),signal:o,body:{text:i,request_id:Zs(),...QM(n())}})}}function X3(e,t,n,r,i=()=>{},o=J3){return async(c,l)=>{i();const d=String(l||c.type||"").toLowerCase(),h=d.includes("mp4")?"m4a":d.includes("ogg")?"ogg":d.includes("wav")?"wav":"webm",m=new File([c],`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:Zs(),...eR(r())}),new Promise((x,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 f1(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 q3(r).then(x=>y&&o(x)).catch(()=>y&&o("")),()=>{y=!1}},[r]);const c=`${r}|${i}`,l=p.useRef(c);l.current=c;const d=p.useRef(n);d.current=n;const h=p.useRef(e);h.current=e;const m=()=>{if(l.current!==c)throw new Error("Voice session changed.")},_=!!(t&&i&&r),g=X2({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:_?Y3(t,i,()=>d.current,m):void 0,transcribe:_?X3(t,r,i,()=>d.current,m):void 0,on_transcript:y=>{l.current===c&&h.current.on_transcript(y)},on_error:y=>{l.current===c&&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 x;g.stop_tts(),(x=g.cancel_voice_ptt_recording)==null||x.call(g)}},[c,g.stop_tts,g.cancel_voice_ptt_recording]),{...g,run_id:i}}function h1(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 Z3(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 Q3=350;function m1(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()})},c=()=>{if(n.current){if(n.current=!1,Date.now()-i.current<Q3){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",c),window.addEventListener("pointercancel",c),window.addEventListener("blur",y),()=>{window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),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=Z3(!!l),h=F2(e.prefs,e.defaults),m=t.voice_ptt_recording?`Recording… ${l?rS(l,d):""}`.trim():t.voice_ptt_busy?z2(l||d,d,h):"",g=!l1()?o1: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:c,onPointerCancel:c,onKeyDown:y=>{[" ","Enter"].includes(y.key)&&!y.repeat&&(y.preventDefault(),o())},onKeyUp:y=>{[" ","Enter"].includes(y.key)&&(y.preventDefault(),c())},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 eP(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 tP="abstractobserver";function nP(e){return{replayView:JL({fetch:(t,n)=>e.fetch_gateway(wt(t),n)}),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 sP(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 rP=new Set(["completed","failed","cancelled"]);function iP(e){var G;const{gateway:t,discussion:n}=e,r=p.useMemo(()=>nP(t),[t]),[i,o]=p.useState(((G=n.session)==null?void 0:G.run_id)||""),[c,l]=p.useState(""),[d,h]=p.useState(!1),[m,_]=p.useState(""),{controller:g,snapshot:y}=NI({transport:r,runId:i,enabled:e.connected,clientId:tP}),x=n.session,k=!!i&&!rP.has(y.status)&&y.status!=="idle",v=wI(y),[N]=u1(),$=d1(e.connected?t:null,e.connected),[E,S]=p.useState(""),P=f1({gateway:e.connected?t:null,session_id:(x==null?void 0:x.session_id)||e.voice_session_id||"",prefs:N,on_error:S,on_transcript:K=>l(V=>V.trim()?`${V.trimEnd()}
96
+ ${K}`:K)}),D=p.useMemo(()=>{for(let K=y.messages.length-1;K>=0;K-=1){const V=y.messages[K];if(V.role==="assistant")return V.live?null:{key:String(V.id||""),text:String(V.content||"")}}return null},[y.messages]);h1(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 V=K.trim();if(V){h(!0);try{if(x){const A=String(((M=y.run)==null?void 0:M.workflow_id)||""),O=sP(A),L=await t.start_run(O.flow_id,{prompt:V},{bundle_id:O.bundle_id,session_id:x.session_id});o(L)}else{const A=await e.on_fork(n.automation_id,n.occurrence_index,V);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"}),x?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:x.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:x.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":(x==null?void 0:x.session_id)||void 0,children:[m&&x?s.jsx(LN,{fetchGateway:t.fetch_gateway,runId:m==="own"?x.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(gI,{header:W,messages:y.messages,draft:c,onDraftChange:l,onSend:I,busy:k||d,busyLabel:d?x?"Starting…":"Forking the automation…":v?"Waiting for you":"Working…",onCancel:k?()=>g.cancel():void 0,stopState:y.stop??null,disabled:!e.connected,interaction:MI(v,g,{records:y.records,currentRun:y.run}),placeholder:x?"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(m1,{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:s.jsxs(s.Fragment,{children:[y.error?s.jsx("div",{className:"observe_context_card error",role:"alert",children:y.error}):null,y.source?s.jsx("div",{className:"help_text muted discussion_source","data-source":y.source,title:y.sourceReason||void 0,children:yI(y)}):null]})})]})}const oP=qn.title;function I0(e){return`${oP}: ${e}`}const aP=["workspace_access_mode","workspace_allowed_paths"];function lP(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.folders))}function cP(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 lP(t)?t:null}function _1(e,t){const n={...e||{}};for(const r of aP)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 uP(e,t){const n=e.target;return{target:{bundle_ref:n.bundle_ref,flow_id:n.flow_id,input_data:_1(n.input_data,t)}}}const dP=3e4,rv=new WeakMap;function fP(e,t,n=Date.now()){let r=rv.get(e);r||rv.set(e,r=new Map);const i=JSON.stringify(t),o=r.get(i);if(o&&n-o.at<dP)return o.answer;const c=tm(e)(t).then(l=>l.summary);return c.catch(()=>r==null?void 0:r.delete(i)),r.set(i,{at:n,answer:c}),c}function hP(e){rv.delete(e)}function mP(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 fP(e.request,e.value).then(o=>i&&n(I0(o))).catch(o=>i&&n(I0(Rg(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 _P(e){const{connected:t,request:n,value:r}=e,[i,o]=p.useState(null),[c,l]=p.useState(null),d=JSON.stringify(r);p.useEffect(()=>{if(!t){o(null),l(null);return}let g=!0;return l(null),tm(n)(r).then(y=>g&&o(y)).catch(y=>g&&l(`Could not read your workspaces: ${Rg(y)}`)),()=>{g=!1}},[t,d,n]);const h=e.on_change,m=p.useCallback(async g=>{const y=await tm(n)(g);await h(g),o(y),hP(n)},[n,h]),_=t?e.disabled?"Saving…":null:"Connect to your gateway to choose workspaces.";return s.jsx(oN,{level:"run",idPrefix:e.id_prefix,value:r,effective:i,onChange:m,loadError:t?c:_,unavailableReason:_,footer:e.footer})}class pP{constructor(){jn(this,"made",new Map);jn(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:_1(n.target.input_data,r)}}}}async function gP(e,t,n,r,i){const o=t.expected(n.automation_id,n.summary.revision);await e.revise(n.automation_id,uP(n.definition,r),o,i),t.record(n.automation_id,o,r)}function p1(e){return`abstractobserver_list_open_${e}`}function g1(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function yP(e,t=g1()){try{return(t==null?void 0:t.getItem(p1(e)))!=="0"}catch{return!0}}function wP(e,t,n=g1()){try{n==null||n.setItem(p1(e),t?"1":"0")}catch{}}function eg(e){const[t,n]=p.useState(()=>yP(e)),r=p.useCallback(()=>{n(i=>{const o=!i;return wP(e,o),o})},[e]);return[t,r]}function tg(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 vP=5e3,xP=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],bP={pause:wa.pause,resume:wa.resume,run_now:wa.run_now,edit:wa.revise,archive:`${wa.archive}…`,discuss:wa.discuss},kP={pause:Ho.pause,resume:Ho.resume,run_now:Ho.run_now,edit:Ho.revise,archive:Ho.archive,discuss:Ho.discuss},jP={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},SP={legacy_pause:Ho.pause,legacy_resume:Ho.resume,legacy_run_now:Ho.run_now,open_run:"list",recreate:"refresh"};function NP(e){return s.jsx("span",{className:"auto_state","data-field":"state",children:s.jsx(nN,{status:e.status})})}function ap(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 $P={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"},CP="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function O0(e){const t=e.busy||e.ctl.enabled?null:e.ctl.reason||"Not available now.";return s.jsx(Fi,{variant:"sm",className:"auto_switch",action:"active",id:`auto-active-${e.summary.automation_id}`,label:wa.active,checked:e.summary.status==="active",unavailableReason:t,busy:e.busy,hint:e.hint,onChange:e.onChange})}function EP(e){const t=e.summary,n=r1(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,x,k)=>s.jsxs("button",{type:"button",className:`btn btn_sm auto_action${x?" auto_action_icon":""}${g?` ${g}`:""}`,"data-action":d,disabled:!m.enabled,title:[x?h:null,m.enabled?null:m.reason,k].filter(Boolean).join(`
97
+ `)||void 0,"aria-label":x?h:void 0,"aria-description":k,onClick:_,children:[y?s.jsx(qe,{name:y,size:13}):null,x?null:s.jsx("span",{children:h})]},d);let c;if(n.legacy){const d=l3(t,i),h=t.status==="paused"?"legacy_resume":"legacy_pause",m=["legacy_run_now","open_run","recreate"];c=[s.jsx(O0,{summary:t,busy:i,ctl:d[h],hint:CP,onChange:()=>e.h.on_legacy_action(t,h)},"active"),...m.map(_=>o(_,$P[_],d[_],()=>e.h.on_legacy_action(t,_),void 0,SP[_]))]}else{const d=a3(t,i),h=t.status==="active"?"pause":"resume",m=["run_now","edit","discuss","archive"];c=[s.jsx(O0,{summary:t,busy:i,ctl:d.active,hint:Gp("active",t),onChange:()=>e.h.on_row_action(t,h)},"active"),...m.map(_=>o(_,bP[_],d[_],()=>e.h.on_row_action(t,_),_==="archive"?"danger auto_action_end":void 0,kP[_],_==="archive",Gp(jP[_],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(NP,{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(ap,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?s.jsx(ap,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,s.jsx(ap,{icon:"clock",field:"next",label:n.listening?"When it runs":"Next run",children:n.listening?n.next_run:`next: ${n.next_run}`}),s.jsx(ap,{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:HN(n.last)}):null]}),s.jsx("div",{className:"auto_row_actions",role:"toolbar","aria-label":`Controls for ${n.title}`,children:c}),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 AP(e){const t=e.state,n=e.list?e.list.open:!0,r=t.error??t.list_error,i=r?Vp(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(tg,{open:n,on_toggle:e.list.on_toggle,controls:"auto_list_body",title:"Automations",count:By(t).length}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_title",children:"Automations"}),s.jsx("span",{className:"pane_count",children:By(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:xP.map(([o,c])=>s.jsx("option",{value:o,children:c},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:VO,"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(ol,{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,E0(t)>0&&t.status_filter!=="archived"?s.jsx("div",{className:"auto_show_archived",children:s.jsx(Fi,{variant:"sm",action:"show-archived",label:`Archived (${E0(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:By(t).map(o=>s.jsx(EP,{summary:o,state:t,h:e.h},o.automation_id))})]})]})}function TP(e,t,n,r){const i=e.state,o=i.detail;if(!o||el(o.summary))return null;const c=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(c,l,d,h==null?void 0:h.command_id);const m=r.expected(c,d),_=await e.revise(c,r.changes(c,l),m,h==null?void 0:h.command_id);return r.note(c,m),_},onCommand:(l,d,h)=>e.command(c,l,d,h==null?void 0:h.command_id),onDiscuss:async(l,d,h)=>{const m=await e.discuss(c,l,d,h==null?void 0:h.request_id);return t.on_open_session(m,mx(l),l),m},onSeen:l=>e.seen(c,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(c,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 MP(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 c=n.slice(0,i),l=n.slice(o+1);return((d=t.find(h=>h.bundleId===c&&h.flowId===l))==null?void 0:d.name)||void 0}function RP(e){const{fetchGateway:t,messageProps:n,readRunAfter:r,...i}=e,o=i.onOpenResource??(t?l=>bL(t,l.url,{name:l.name}):void 0),c=l=>l.kind==="answer"&&r?s.jsxs(s.Fragment,{children:[y0(l,n),s.jsx(P3,{run_id:l.runId,read:r})]}):y0(l,n);return s.jsx(oM,{...i,onOpenResource:o,renderText:HN,renderTurn:c})}function LP(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(ol,{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(el(t.summary)){const g=r1(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=TP(e.ctl,e.host,e.edit,n==null?void 0:n.revisions),i=e.ctl,o=t.definition,c=cP(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(_P,{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:c,disabled:i.state.busy,on_change:g=>gP(i,n.revisions,{automation_id:t.automation_id,summary:t.summary,definition:o},g,nl())})]}):s.jsxs("details",{className:"auto_workspaces_details","data-field":"workspaces-details",children:[s.jsx("summary",{children:"Workspaces"}),s.jsx(mP,{request:n.request,connected:n.connected,value:c,refresh_key:t.summary.revision??""})]})}):null,r?s.jsx(RP,{...r,readRunAfter:e.host.read_run_after,workflowName:MP(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 IP(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=i1(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function OP(e){const t=e.ctl,n=p.useRef(null);n.current||(n.current=new pP);const r=e.workspace_request?{request:e.workspace_request,connected:e.active,definition:S=>t.definition(S)}:void 0,[i,o]=eg("automations"),[c,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,x]=p.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");p.useEffect(()=>{const S=()=>x(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(),p3);return()=>window.clearInterval(S)},[t,e.active,y,e.available.available]);const k=t.state.detail,v=t.state.notice;p.useEffect(()=>{if(!v)return;const S=window.setTimeout(()=>t.dismiss_notice(),vP);return()=>window.clearTimeout(S)},[t,v]);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=IP(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(AP,{state:t.state,available:e.available,h:E,list:{open:i,on_toggle:o},ws:r}),c?s.jsx(iP,{gateway:e.gateway,discussion:c,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,mx(P),P),l(I=>I&&{...I,session:R}),R},on_close:()=>l(null)},c.opened):s.jsx(LP,{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(LN,{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 PP(e){return s.jsx(Fi,{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 DP(e){return s.jsx("div",{className:`settings_choice ${e.checked?"on":""}`,children:s.jsx(Fi,{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 FP="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function zP(e){return s.jsx(Fi,{variant:"sm",action:"schedule-active",className:"observe_schedule_switch",label:"Active",hint:FP,checked:e.active,unavailableReason:e.unavailableReason,busy:e.busy,onChange:e.onChange})}function BP(e){return s.jsx(Fi,{variant:"sm",action:"mindmap-live",label:"Live",hint:"Refresh the map as new memory arrives.",checked:e.checked,onChange:e.onChange})}function UP(e){return s.jsx(Fi,{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 P0={framework:null,gateway:null,gatewayNote:"checking…"};function WP(){const e="0.10.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 qP(){return y2("abstractobserver",WP())}async function VP(e){let t;try{t=await e.gateway_about()}catch(n){return Hh(null,n instanceof Error?n.message||n.name:String(n))}return Hh(t)}class ng{constructor(t){this._maxSize=ng._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=ng._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 HP(e){try{return new URL(String(e)),!0}catch{return!1}}function GP({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return HP(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function KP({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function JP({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function YP(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,c)=>o+c,0)/r.length:null}return null}async function XP({baseUrl:e,endpoint:t,token:n,getToken:r,signal:i,fetchImpl:o}={}){const c=GP({baseUrl:e,endpoint:t}),l=await KP({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(c,{method:"GET",headers:{Accept:"application/json",...JP({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 kh=Object.freeze({tickMs:1500,historySize:20,endpoint:"api/gateway/host/metrics/gpu",baseUrl:"",mode:"full"});function ZP(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function D0(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function F0(e,t){const n=Number(e);return Number.isFinite(n)?Math.floor(n):t}function Wy(e,t=1){const n=D0(Number(e)/100,0,1),r=Math.round(140-140*n),i=D0(Number(t),0,1);return i>=1?`hsl(${r} 85% 55%)`:`hsl(${r} 85% 55% / ${i})`}function z0(e){const t={...kh,...e||{}};return t.tickMs=Math.max(250,F0(t.tickMs,kh.tickMs)),t.historySize=Math.max(1,Math.min(200,F0(t.historySize,kh.historySize))),t.endpoint=String(t.endpoint||kh.endpoint),t.baseUrl=String(t.baseUrl||""),t.mode=String(t.mode||kh.mode).trim().toLowerCase(),t.mode!=="icon"&&(t.mode="full"),t}function QP(){return`
98
+ :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}
99
+ .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)}
100
+ .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))}
101
+ .wrap.icon .top{display:none}
102
+ .wrap.icon .bars{height:var(--monitor-gpu-bars-height,18px)}
103
+ .top{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
104
+ .label{font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.9}
105
+ .value{font-variant-numeric:tabular-nums;font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.95}
106
+ .bars{display:flex;align-items:flex-end;gap:2px;height:var(--monitor-gpu-bars-height,34px);overflow:hidden}
107
+ .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}
108
+ .bar.missing{background:var(--monitor-gpu-bar-missing,#62708a);opacity:.35}
109
+ .bar.error{background:var(--monitor-gpu-bar-error,#ff6b6b);opacity:.7}
110
+ .muted{opacity:.6}
111
+ `}class e4{constructor(t,n={}){if(!t||typeof t!="object")throw new TypeError("target element is required");this._target=t,this._opts=z0(n),this._buffer=new ng(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=QP();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 c=document.createElement("div");c.className="value muted",c.textContent="—",i.appendChild(o),i.appendChild(c);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:c,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=z0({...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(),c=this._buffer.last(),l=Number.isFinite(c)?Math.max(0,Math.min(100,c)):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",Wy(l,.95)),n.style.setProperty("--monitor-gpu-accent-glow",Wy(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,x=y>=0?o[y]:null,k=Number.isFinite(x)?x:null,v=k==null?0:ZP(k/100),N=Math.max(2,Math.min(m,Math.round(v*m)));g.style.height=`${N}px`,g.style.background=k==null?"":Wy(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 XP({baseUrl:this._opts.baseUrl,endpoint:this._opts.endpoint,token:t,getToken:n,signal:this._abort.signal}),o=i&&i.payload,c=o&&typeof o=="object"?o.supported!==!1:!0,l=YP(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(!c||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 t4(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 e4(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"),c=this.getAttribute("endpoint"),l=this.getAttribute("base-url"),d=this.getAttribute("mode");return{...i!=null?{tickMs:i}:{},...o!=null?{historySize:o}:{},...c!=null?{endpoint:c}:{},...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 Yd(e){return String(e||"").trim().toLowerCase()}function Pg(e){return`${(e==null?void 0:e.filename)||""} ${(e==null?void 0:e.source_path)||""}`.trim().toLowerCase()}function Kh(e,t){return t.some(n=>e.endsWith(n))}function n4(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 s4(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 r4(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 y1(e,t){var c,l,d,h,m;const n=Yd(e==null?void 0:e.content_type),r=Pg(e),i=[e==null?void 0:e.semantic_kind,e==null?void 0:e.render_kind,e==null?void 0:e.task,(c=e==null?void 0:e.tags)==null?void 0:c.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")||Kh(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,`
112
+ `).replace(/\r/g,`
113
+ `).split(`
114
+ `);return w1(o)}function i4(e){const n=String(e||"").replace(/\r\n/g,`
115
+ `).replace(/\r/g,`
116
+ `).split(`
117
+ `),r=n.findIndex(c=>/^Markdown Content:\s*$/i.test(c.trim()));if(r===-1)return null;const i=[];for(const c of n.slice(0,r)){const l=c.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(`
118
+ `).trim();return!i.length&&!o?null:{metadata:i,body:o}}function o4(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 a4(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:w1(e)}function w1(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 l4(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,`
119
+ `).replace(/\r/g,`
120
+ `).split(`
121
+ `).map(d=>d.trim()).filter(Boolean).slice(0,80);if(i.length<12)return!1;const o=i.filter(d=>d.length<=28).length,c=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||c>=2)}function c4(e,t){var h;const n=String(t||""),r=n4(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,`
122
+ `).replace(/\r/g,`
123
+ `).split(`
124
+ `),o=i.map(m=>m.trim()).filter(Boolean);if(o.length<2||l4(n)||o4(i)||a4(i))return!1;const c=((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 c>=24&&d>=2&&(l>=1||o[0].length<=140)}function Jh(e){const t=Yd(e==null?void 0:e.modality),n=Yd(e==null?void 0:e.content_type),r=Pg(e),i=s4(e);return t==="image"||n.startsWith("image/")||Kh(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)||Kh(r,[".wav",".mp3",".m4a",".aac",".flac",".ogg",".opus",".aiff",".mid",".midi"])?"audio":t==="video"||n.startsWith("video/")||Kh(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")||y1(e,"")?"text":"binary"}function sg(e,t){const n=Yd(e==null?void 0:e.content_type),r=Pg(e),i=String(t||"").trim();return n.includes("html")||r.endsWith(".html")||r.endsWith(".htm")||r4(t)?"html":y1(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("["))&&Lg(i)!==null?"json":c4(e,t)?"markdown":"text"}function _x(e,t=""){const n=Jh(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=Yd(e==null?void 0:e.modality),i=Yd(e==null?void 0:e.content_type),o=Pg(e);return r==="document"||i.includes("pdf")||Kh(o,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return sg(e,t)}function qy(e){var h,m;const t=String(e||"").replace(/\r\n/g,`
125
+ `).replace(/\r/g,`
126
+ `).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,c="";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 x=(y[3]||"").trim();if(!x)return[`${l(g)}${_.trim()}`];const k=x.match(/[^\s="'<>`]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>`]+))?/g)||[x];return[`${l(g)}${y[1]}${y[2]}`,...k.map(v=>`${l(g+1)}${v.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])||"";c&&k===c&&(c=""),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")&&(c=k));continue}if(c){const k=g.trim();k&&i.push(...k.split(`
127
+ `).map(v=>`${l(o)}${v.trimEnd()}`));continue}const x=g.replace(/\s+/g," ").trim();x&&i.push(`${l(o)}${x}`)}return i.join(`
128
+ `)}const u4=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function px(e){const t=typeof e=="string"?e:String(e??""),n=u4.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 v1(...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 iv(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>iv(t)).filter(Boolean).join(`
129
+ `).trim();if(typeof e=="object"){const t=e.text??e.content??e.message??e.value;if(t!==e){const n=iv(t);if(n)return n}}return""}function x1(e){const t=px(iv(e));return{text:t.text,runtime_metadata:t.metadata}}function d4(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=px(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 c=o.length-1;c>=0;c-=1){const l=o[c],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=x1((l==null?void 0:l.content)??(l==null?void 0:l.text)??l);if(h.text)return{text:h.text,runtime_metadata:v1(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 f4(e,t=6){var o,c;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=x1((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=v1(h.runtime_metadata,l!=null&&l.runtime_metadata&&typeof l.runtime_metadata=="object"?l.runtime_metadata:null,(c=l==null?void 0:l.metadata)!=null&&c.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 b1(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function h4(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 k1="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function j1(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 gx(e,t){const n=String((e==null?void 0:e.reason)||"").trim().toLowerCase(),r=h4(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 S1(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 N1(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),r=px(n),i=d4(t);return r.text&&!b1(r.text)?{text:r.text,runtime_metadata:r.metadata}:i.text?i:{text:r.text||n,runtime_metadata:r.metadata}}function m4(e,t){return N1(e,t).text}function _4(e,t){return e||String(t||"").trim()||{}}function Go(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 wu(e){const t=String(e.status||"unknown").trim()||"unknown";return s.jsx("span",{className:`run_status_pill ${Sa(t)}`,children:t})}function p4(e){var o;const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(hs(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?gx(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 rm(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?tn(t,{max_chars:220,max_lines:2}):tn(zr(t,400),{max_chars:220,max_lines:2}):""}function g4(e){const t=p4(e);if(t)return t;const n=rm(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":hs(i)?"Terminal":"No current activity reported"}function $1(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 B0(e){const t=$1(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=Vn(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=Vn(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 y4(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 w4(e,t){if(!e||typeof e!="object")return null;const n=y4(e),r=$1(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:{},c=Vn(n.artifact_id,e.artifact_id,e.$artifact,e.id,r.artifact_id,r.$artifact,r.id,i.artifact_id,i.$artifact);if(!c)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=Vn(n.filename,e.filename,r.filename,i.filename,d.filename,d.name,e.name,r.name),m=Vn(n.source_path,e.source_path,r.source_path,i.source_path,e.path,r.path,d.path,d.source_path,d.file_path),_=Vn(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=Vn(n.render_kind,o.render_kind,e.render_kind,d.render_kind),y=Vn(n.semantic_kind,o.semantic_kind,e.semantic_kind,d.semantic_kind,d.artifact_type),x=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:{},v=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:c,run_id:Vn(n.run_id,e.run_id,r.run_id,i.run_id,d.run_id,v.run_id),content_type:_,modality:Vn(n.modality,e.modality,o.modality,d.modality)||B0({...e,ref:r,metadata:i,tags:d}),semantic_kind:y||B0({...e,ref:r,metadata:i,tags:d}),render_kind:g||_x({content_type:_,filename:h,source_path:m,modality:Vn(n.modality,e.modality,d.modality),tags:d}),task:Vn(n.task,o.task,e.task,d.task,d.provider_task),classification_source:Vn(n.classification_source,o.classification_source,e.classification_source),session_id:Vn(n.session_id,o.session_id,e.session_id,d.session_id),workflow_id:Vn(n.workflow_id,o.workflow_id,e.workflow_id,d.workflow_id,d.workflow),node_id:Vn(n.node_id,o.node_id,e.node_id,d.node_id,d.node),step_id:Vn(n.step_id,o.step_id,e.step_id,d.step_id),effect_id:Vn(n.effect_id,o.effect_id,e.effect_id,d.effect_id,d.effect_idempotency_key),turn_id:Vn(n.turn_id,o.turn_id,e.turn_id,d.turn_id,d.turn),ledger_cursor:Vn(n.ledger_cursor,o.ledger_cursor,e.ledger_cursor,d.ledger_cursor,d.step_cursor),parent_run_id:Vn(n.parent_run_id,o.parent_run_id,e.parent_run_id,d.parent_run_id),actor_id:Vn(n.actor_id,o.actor_id,e.actor_id,d.actor_id),title:Vn(n.title,e.title,d.title,d.label,d.name),created_at:Vn(n.created_at,e.created_at,r.created_at,i.created_at,d.created_at),size_bytes:kO(n.size_bytes,e.size_bytes,r.size_bytes,i.size_bytes,d.size_bytes),filename:h,source_path:m,sha256:Vn(n.sha256,e.sha256,r.sha256,i.sha256,d.sha256),tags:d,producer:k,provenance:v,generation:N,media:$,source_refs:Array.isArray(n.source_refs)?n.source_refs:Array.isArray(e.source_refs)?e.source_refs:[],access:x,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(Vn(n.classification_source,o.classification_source,e.classification_source))),descriptor:o,source:t,raw:e}}function rg(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||Ln(e.artifact_id,16)}function v4(e,t){if(t==="type")return Wd(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return ov(e);if(t==="node")return Ud(e)||"(node unknown)";if(t==="workflow")return yx(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 im(e)||e.source||"artifact";const n=Vt(e.created_at);return n===null?"(unknown time)":new Date(n).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function yx(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 Ud(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 ov(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=Ud(e),i=Vt(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"}),c=e!=null&&e.run_id?Ln(String(e.run_id),10):"unknown run";return r?`${c} · ${r} · ${o}`:`${c} · ${o}`}function U0(e){if(!e)return"provenance unavailable";const t=[],n=yx(e),r=Ud(e),i=im(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 ru(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 Wd(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 x4(e){return e==="html"?"HTML":e==="json"?"JSON":e==="audio"?"Unclassified audio":e==="code"?"Code":e.slice(0,1).toUpperCase()+e.slice(1)}function b4(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 k4(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 W0(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 j4(e){const t=Kd(e.created_at),n=cu(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function q0(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=Kd(n);return r==="—"?"—":r}function V0(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=im(e),o=Wd(e);return i?`${o} ${i}`:`${o} artifact`}function im(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,c,l,d,h,m;if(!e)return"";const t=Vn((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,(c=e.generation)==null?void 0:c.provider),n=Vn((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 S4(e){var t,n,r,i;return e?Vn((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 H0(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),c=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(c)&&c>0&&d.push(`${c} 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 G0(e){return e.source_path||e.filename||""}function ig(e,t,n){const r=e.run_id&&t[e.run_id]||null;if(!r)return e;const i=Go(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 av(e,t,n,r=""){const i=ig(e,t,n),o=_x(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]||Wd(i)}function Za(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 lp(e){var o,c,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)||((c=n==null?void 0:n.payload)==null?void 0:c.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 of(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 N4(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 E1(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),r=N4(e),i=Za(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 kd(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):zr(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:zr(e,320),duration:-1}}function A1(e){var c,l,d,h,m,_,g,y,x;if(!e||typeof e!="object")return"";const t=String(((c=e==null?void 0:e.effect)==null?void 0:c.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 v=k,N=[v.response,v.answer,v.message,v.text,v.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((x=(y=e==null?void 0:e.effect)==null?void 0:y.payload)==null?void 0:x.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 Mp(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 $4(e){return!!(e&&String(e.status||"")==="waiting")}function C4(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)?zr(l.messages,1800):"",_=typeof d.content=="string"?d.content:typeof d.response=="string"?d.response:typeof o.result=="string"?String(o.result):"",g=Vt(o.started_at),y=Vt(o.ended_at),x=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:tn(m,{max_chars:1200,max_lines:10}),response_preview:tn(_,{max_chars:1200,max_lines:10}),missing_response:!String(_||"").trim(),tokens:{prompt:x,completion:k,total:Number(h.total_tokens??x+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?zr(o.error,500):"",raw:o})}return t.sort((i,o)=>(Vt(o.ts)??0)-(Vt(i.ts)??0))}function K0(e){const t=e.size||18,n=Jh(e.artifact),r=_x(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 E4=2,A4=Number.MAX_SAFE_INTEGER;function T4(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 M4(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:qy(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 c=String(o.textContent||"").trim();return c?{kind:"text",text:c}:null}if(o.nodeType===Node.COMMENT_NODE)return{kind:"comment",text:String(o.textContent||"")};if(o.nodeType===Node.ELEMENT_NODE){const c=o,l=Array.from(c.attributes||[]).map(h=>({name:h.name,value:h.value})),d=Array.from(c.childNodes||[]).map(i).filter(Boolean);return{kind:"element",tag:c.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:qy(t)||t}]}catch{return[{kind:"text",text:qy(t)||t}]}}function Vy(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 T1(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(Vy,{tag:t.tag,attrs:t.attrs,selfClosing:!0})});const c=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(Vy,{tag:t.tag,attrs:t.attrs}),!i&&c?s.jsxs("span",{className:"html-tree__summary_text",children:[" ",T4(c.text)]}):null]}),i?s.jsxs("div",{className:"html-tree__children",children:[t.children.map((l,d)=>s.jsx(T1,{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(Vy,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function R4(e){const t=p.useMemo(()=>M4(e.text),[e.text]),[n,r]=p.useState({mode:"folded",version:0}),i=n.mode==="unfolded"?A4:E4;p.useEffect(()=>{r(c=>({mode:"folded",version:c.version+1}))},[e.text]);const o=()=>{r(c=>({mode:c.mode==="unfolded"?"folded":"unfolded",version:c.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((c,l)=>s.jsx(T1,{node:c,depth:0,collapseAfterDepth:i,expansionMode:n.mode,expansionVersion:n.version},`root:${l}`))})]})}function L4(e){var r;const t=i4(e.text);if(!t)return s.jsx("div",{className:`${e.className} structured markdown_preview`,children:s.jsx(Ni,{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(Ni,{text:t.body||e.text})]})}function M1(e){const t=String(e.text||""),n=sg(e.artifact,t);if(n==="json"){const r=Lg(t);if(r!==null)return s.jsx("div",{className:`${e.className} structured`,children:s.jsx(hr,{value:r,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?s.jsx(L4,{text:t,className:e.className}):n==="html"?s.jsx(R4,{text:t,className:e.className}):s.jsx("pre",{className:`mono ${e.className}`,children:t})}function I4(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:rg(n)}):t.kind==="audio"&&t.url?s.jsx(Tg,{className:"runtime_inline_preview audio",src:t.url,name:rg(n)}):t.kind==="video"&&t.url?s.jsx("video",{className:"runtime_inline_preview media",src:t.url,controls:!0}):s.jsx(M1,{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 wx(e){const t=e==null?void 0:e.waiting;return t&&typeof t=="object"?t:null}function R1(e){const t=wx(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function J0(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 O4(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 vx(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(hs(t)||t!=="waiting")return"none";const n=wx(e),r=R1(e);return of(n).length?"tool_approval":r==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":r==="subworkflow"?"subworkflow":r==="event"?J0(n)?"user_response":"external_event":r==="user"||J0(n)?"user_response":"unknown_wait"}function P4(e){const t=wx(e),n=of(t),r=vx(e);return r==="tool_approval"?`Tool approval: ${O4(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 D4(e){const t=vx(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.":hs(n)?"Open the ledger and artifacts for the final outcome.":"Open the run to inspect current activity."}function Y0(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 F4(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label??"",i=String(e.status||"unknown").trim().toLowerCase()||"unknown",o=vx(e),c=hs(i),l=Am(e,n),d=Vt(e.updated_at||e.created_at)??0,h=i==="running"&&l>=14400*1e3,m=P4(e)||Y0(e)||(e.current_node?`Current node: ${e.current_node}`:i==="running"?"Running":c?"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":c&&(_="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:c?8:7,y=o==="tool_approval"||o==="user_response",x=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,R1(e),m,Y0(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:D4(e),action_label:x,search_text:k,is_terminal:c,needs_user_action:y,is_stale:h,duration_ms:l,updated_ms:d}}function z4(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label_by_id??{};return e.map(i=>F4(i,{now_ms:n,workflow_label:r[String(i.workflow_id||"")]||String(i.workflow_id||"")}))}function B4(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 U4(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 W4(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 q4(e){const[t,n]=p.useState("attention"),[r,i]=eg("system_queues"),[o,c]=eg("system_runs"),[l,d]=p.useState(""),[h,m]=p.useState("attention"),[_,g]=p.useState(""),y=p.useMemo(()=>{const L={};for(const H of e.artifacts){const J=String(H.run_id||"").trim();J&&(L[J]=(L[J]||0)+1)}return L},[e.artifacts]),x=p.useMemo(()=>z4(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),k=p.useMemo(()=>B4(x),[x]),v=p.useMemo(()=>{const L=U4(x,{queue:t,query:l});return W4(L,h)},[x,t,l,h]),N=v.find(L=>String(L.run_id||"")===_)||v.find(L=>String(L.run_id||"")===e.selected_run_id)||v[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?of(I):[],G=(N==null?void 0:N.reason)||(I?gx(I,W):""),K=(N==null?void 0:N.expected_action)||(I?S1(I,W):""),V=I?m4(I,null):"",M=E&&y[E]||0,A=hs($==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(tg,{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(tg,{open:o,on_toggle:c,controls:"runtime_ops_runs",title:"Runs",count:v.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:[!v.length&&e.loading&&!e.runs.length?s.jsx(ol,{what:"activity"}):null,!v.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,v.map(L=>{const H=L.run,J=String(H.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:Go(H,e.workflow_label_by_id)}),L.is_stale?s.jsx("span",{className:"chip warn",children:"stale"}):null,s.jsx(wu,{status:H.status})]}),s.jsxs("div",{className:"runtime_ops_row_sub",children:[s.jsx("span",{className:"mono",children:Ln(J,18)}),s.jsx("span",{children:cu(H.updated_at||H.created_at)}),s.jsx("span",{children:yu(H)}),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(H.llm_calls||0).toLocaleString()," llm"]}),s.jsxs("span",{children:[Number(H.tool_calls||0).toLocaleString()," tools"]}),s.jsxs("span",{children:[Number(H.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(wu,{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:Go($,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Ln(E,28)})]}),s.jsxs("div",{className:"runtime_ops_decision",children:[s.jsx("strong",{children:(N==null?void 0:N.reason)||g4($)}),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:Kd(Id($))})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:yu($)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last event"}),s.jsx("strong",{children:Kd($.updated_at||$.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:$.session_id?Ln(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:Ln(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 il(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}),V?s.jsxs("div",{className:"runtime_ops_wait_request",children:[s.jsx("span",{children:"Request"}),s.jsx(Ni,{text:V})]}):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,H)=>s.jsxs(Ee.Fragment,{children:[s.jsx("span",{className:"chip mono warn",children:String((L==null?void 0:L.name)||"tool")}),j1(L).map(J=>s.jsxs("span",{className:"chip muted",title:k1,children:[J,"~"]},`${H}:${J}`))]},`${String((L==null?void 0:L.name)||"tool")}:${H}`))}):null,s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"muted",children:"Raw wait payload"}),s.jsx(hr,{value:I,collapseAfterDepth:3,showCopy:!0})]})]}):null,rm($)?s.jsx("div",{className:"warn_callout",children:rm($)}):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 il(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 V4(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)),c=!!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 H of n)M[H]=Number(O[H]||L[H]||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()))},x=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,v=e.artifact_run_filter?Go(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,H)=>{const J=Jd(L.status)?0:1,U=Jd(H.status)?0:1;if(J!==U)return J-U;const te=Vt(L.updated_at||L.created_at)??0;return(Vt(H.updated_at||H.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,zr(((U=L.effect)==null?void 0:U.payload)??{},900),zr(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=C4(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,`
130
+ `).replace(/\r/g,`
131
+ `).split(`
132
+ `).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",V=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:Ln(e.artifact_run_filter,18)})]}):null,e.session_id?s.jsxs("span",{className:"chip muted",children:["session ",s.jsx("span",{className:"mono",children:Ln(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(x.waiting.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Running"}),s.jsx("strong",{children:E(x.running.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Failed"}),s.jsx("strong",{children:E(x.failed.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsxs("span",{children:["Artifacts",c?" (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(q4,{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=x4(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:v||Ln(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 ",ru(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:Go(M,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Ln(A,15)}),s.jsx("span",{children:yu(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(ol,{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?Go(O,e.workflow_label_by_id):yx(A),H=H0(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(K0,{artifact:A,size:18}),s.jsxs("div",{className:"artifact_row_main",children:[s.jsxs("div",{className:"artifact_row_title",children:[s.jsx("strong",{children:V0(ig(A,e.run_by_id,e.workflow_label_by_id))}),s.jsx("span",{className:"artifact_type_badge",children:Wd(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"})," ",j4(A)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Size"})," ",ru(A.size_bytes)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Last seen"})," ",q0(A)]}),J?s.jsxs("span",{children:[s.jsx("b",{children:"Accesses"})," ",J.toLocaleString()]}):null,H?s.jsxs("span",{children:[s.jsx("b",{children:"Media"})," ",H]}):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"})," ",Ln(A.run_id,13)]}):null,s.jsxs("span",{children:[s.jsx("b",{children:"Turn"})," ",ov(A)]}),Ud(A)?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Node"})," ",Ud(A)]}):null,im(A)?s.jsxs("span",{children:[s.jsx("b",{children:"Source"})," ",im(A)]}):null]}),s.jsxs("div",{className:"artifact_row_facts tertiary",children:[s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"ID"})," ",Ln(A.artifact_id,22)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Provenance"})," ",U0(A)]})]}),G0(A)?s.jsx("div",{className:"artifact_row_path mono",children:G0(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?av(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):av(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=S4(t),A=C1(t),O=H0(t),L=Number(((U=t.access)==null?void 0:U.access_count)||0)||0,H=Vn((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=Vn((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(K0,{artifact:t,size:22}),s.jsxs("div",{children:[s.jsx("div",{className:"artifact_detail_title",children:V0(ig(t,e.run_by_id,e.workflow_label_by_id))}),s.jsxs("div",{className:"artifact_detail_subtitle",children:[Wd(t)," • ",t.render_kind||e.embedded_preview.render_kind||t.modality||"artifact"," • ",t.content_type||"unknown MIME"," • ",ru(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),s.jsx(I4,{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:Wd(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:Kd(t.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Size"}),s.jsx("strong",{children:ru(t.size_bytes)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last seen"}),s.jsx("strong",{children:q0(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?Ln(t.run_id,24):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:k?Go(k,e.workflow_label_by_id):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Turn"}),s.jsx("strong",{children:ov(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Ud(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:U0(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Artifact id"}),s.jsx("strong",{className:"mono",children:Ln(t.artifact_id,30)})]}),t.sha256?s.jsxs("div",{children:[s.jsx("span",{children:"sha256"}),s.jsx("strong",{className:"mono",children:Ln(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(hr,{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:()=>{H&&window.open(H,"_blank","noopener,noreferrer")},disabled:!H,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 il(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(hr,{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:V})]}),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?Go(S,e.workflow_label_by_id):e.selected_run_id?Ln(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Ln(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?Ln(String(S.session_id),28):e.session_id?Ln(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(ol,{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(),H=String((A==null?void 0:A.node_id)||"").trim(),J=Vn(A==null?void 0:A.ended_at,A==null?void 0:A.started_at,A==null?void 0:A.ts),U=Za(A),te=E1(A),z=O?tn(zr(((de=A==null?void 0:A.effect)==null?void 0:de.payload)??{},1200),{max_chars:1200,max_lines:6}):"",ne=A1(A)||(U?`Waiting for ${String(U.reason||"input")}`:"")||((A==null?void 0:A.result)!==void 0?zr(A.result,700):"");return s.jsxs("article",{className:`runtime_log_event ${Sa(L)}`,children:[s.jsxs("div",{className:"runtime_log_event_header",children:[s.jsxs("span",{className:"mono",children:["#",M.cursor]}),s.jsx(wu,{status:L||"record"}),O?s.jsx("span",{className:"chip mono muted",children:O}):null,H?s.jsx("strong",{className:"mono",children:H}):null,J?s.jsx("span",{className:"mono muted",children:Kd(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||Mp(A),z&&z!=="{}"?z:""].filter(Boolean).join(`
133
+ `)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:tn(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(hr,{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?Go(S,e.workflow_label_by_id):e.selected_run_id?Ln(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Ln(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:Ln(M.run_id,16)}):null,s.jsx("span",{children:bu(M.duration_ms)}),M.status?s.jsx(wu,{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(hr,{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(`
134
+ `):"(audit tail not loaded or no lines match search)"})]})]}):null]})}function H4(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,c=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":c?"Your answer":"Response to resume this wait"}),s.jsx("textarea",{className:"mono wait_response_input",value:t,onChange:l=>n(l.target.value),placeholder:c?"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 X0(e,t,n){if(Og(e)==="automation"){const r=String(e.automation_id||e.run_id||"").trim();return n[r]||"Automation"}return Go(e,t)}function Z0(e){const t=Og(e.run);return t?s.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:s1(e.run)}):null}function G4(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,c)=>o+c.rows.reduce((l,d)=>{const h=[d.run,...d.children];return l+h.filter(m=>Jd(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(tg,{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(ol,{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(c=>{const l=c.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:X0(l,e.workflow_label_by_id,e.automation_titles)}),s.jsx(Z0,{run:l}),l.status?s.jsx(wu,{status:sm(l)}):null]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Ln(d,13)}),s.jsx("span",{children:Id(l)?cu(Id(l)):"no start"}),s.jsx("span",{children:yu(l)})]})]}),c.children.length?s.jsx("div",{className:"run_tree_children",children:c.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:X0(m,e.workflow_label_by_id,e.automation_titles)}),s.jsx(Z0,{run:m}),s.jsx(wu,{status:sm(m)})]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Ln(_,13)}),s.jsx("span",{children:Id(m)?cu(Id(m)):"child"}),s.jsx("span",{children:yu(m)})]})]},_)})}):null]},d)})]},o.key))]})]})}class K4{constructor(){jn(this,"_buffer","");jn(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const r=this._buffer.indexOf(`
135
+ `);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(`
136
+ `)};n(h)}this._current={data_lines:[]};continue}const c=o.indexOf(":"),l=c===-1?o:o.slice(0,c),d=c===-1?"":o.slice(c+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 Xt=Kv;function Xs(e,t=3e4){const n=AbortSignal.timeout(t),r=AbortSignal.any,i=e?typeof r=="function"?r([e,n]):e:n;return L1.set(i,t),i}const L1=new WeakMap;class J4 extends Error{constructor(n){super(n);jn(this,"name","GatewayTimeout")}}class Y4 extends Error{constructor(n){super(n);jn(this,"name","Superseded")}}async function an(e,t){try{return await globalThis.fetch(e,t)}catch(n){throw I1(n,e,t)}}async function Hy(e,t,n){try{return await e.json()}catch(r){throw I1(r,t,n)}}function I1(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,c=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(c){const d=i&&L1.get(i)||3e4;return new J4(`${l}: no answer within ${Math.round(d/1e3)} s — the gateway is busy`)}return new Y4(`${l}: superseded`)}}function lv(){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 Zt(e){const t=(e||"").trim(),n={};return t&&(n.Authorization=`Bearer ${t}`),{...n,...lv()}}async function bs(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class cv extends Error{constructor(n,r){super(r);jn(this,"status");this.name="GatewayRequestError",this.status=n}}async function Zc(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 cv(e.status,`${t} (HTTP ${e.status}): ${r||e.statusText||"no reason given"}`)}async function Gy(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 Ky{constructor(t){jn(this,"_cfg");jn(this,"fetch_gateway",(t,n)=>fetch(Xt(this._cfg.base_url,t),{...n,headers:{...n==null?void 0:n.headers,...Zt(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(),c=String(t||"").trim(),l=String((r==null?void 0:r.interface)||"").trim();if(c==="@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),c&&(d.flow_id=c),c==="@default"&&(d.interface=l),o&&(d.session_id=o),r!=null&&r.workspace&&(d.workspace=r.workspace);const h=await an(Xt(this._cfg.base_url,wt("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(d)});if(!h.ok)throw new Error(await Gy(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(Xt(this._cfg.base_url,t),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});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(Xt(this._cfg.base_url,t),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});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(c=>String(c||"")).filter(Boolean):void 0})).filter(o=>o.name)}catch{return null}return null}async get_run(t){const n=await an(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}`)),{headers:{...Zt(this._cfg.auth_token)}});if(!n.ok)throw new Error(`get_run failed: ${await bs(n)}`);return await n.json()}async find_run(t){const n=await an(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}`)),{headers:{...Zt(this._cfg.auth_token)}});if(n.status===404||n.status===403)return null;if(!n.ok)throw await Zc(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=Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/history_bundle?${i.toString()}`)),c=await an(o,{headers:{...Zt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`get_run_history_bundle failed: ${await bs(c)}`);return await c.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(),c=(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),c&&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=Xt(this._cfg.base_url,wt(`runs?${l.toString()}`)),h=await an(d,{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!h.ok)throw new Error(`list_runs failed: ${await bs(h)}`);return await Hy(h,d,{signal:Xs()})}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=Xt(this._cfg.base_url,wt(`audit/tail?max_bytes=${encodeURIComponent(String(n))}`)),i=await an(r,{headers:{...Zt(this._cfg.auth_token)}});if(!i.ok)throw new Error(`audit_log_tail failed: ${await bs(i)}`);return await i.json()}async gateway_about(){const t=await an(Xt(this._cfg.base_url,wt("about")),{headers:{...Zt(this._cfg.auth_token)},signal:Xs(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(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(n)}/input_data`)),{headers:{...Zt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_run_input_data failed: ${await bs(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(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(n)}/after`)),{headers:{...Zt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_run_after failed: ${await bs(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,c=Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(i))}&offset=${encodeURIComponent(String(o))}`)),l=await an(c,{headers:{...Zt(this._cfg.auth_token)}});if(!l.ok)throw new Error(`list_run_artifacts failed: ${await bs(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,c=Xt(this._cfg.base_url,wt(`sessions/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(i))}&offset=${encodeURIComponent(String(o))}`)),l=await an(c,{headers:{...Zt(this._cfg.auth_token)}});if(!l.ok)throw new Error(`list_session_artifacts failed: ${await bs(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(),c=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(),x=String((t==null?void 0:t.cursor)||"").trim(),k=String((t==null?void 0:t.order_by)||"").trim(),v=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),c&&n.set("artifact_kind",c),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),x&&n.set("cursor",x),k&&n.set("order_by",k),v&&n.set("order",v),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(Xt(this._cfg.base_url,wt(`artifacts/search?${n.toString()}`)),{headers:{...Zt(this._cfg.auth_token)}});if(!P.ok)throw new Error(`search_artifacts failed: ${await bs(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(Xt(this._cfg.base_url,wt(`artifacts/stats?${n.toString()}`)),{headers:{...Zt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`artifact_stats failed: ${await bs(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 c=String((r==null?void 0:r.access)||"").trim(),l=c?`?access=${encodeURIComponent(c)}`:"",d=Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(i)}/artifacts/${encodeURIComponent(o)}/content${l}`)),h=await an(d,{headers:{...Zt(this._cfg.auth_token)}});if(!h.ok)throw new Error(`download_run_artifact_content failed: ${await bs(h)}`);return await h.blob()}async list_entities(){const t=await an(Xt(this._cfg.base_url,wt("entities")),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!t.ok)throw new Error(`list_entities failed: ${await bs(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(Xt(this._cfg.base_url,wt("entities/spec/phases")),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!t.ok)throw new Error(`get_entity_phases_spec failed: ${await bs(t)}`);return await t.json()}async get_entity_cognition(t){const n=await an(Xt(this._cfg.base_url,wt(`entities/${encodeURIComponent(t)}/cognition`)),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!n.ok)throw new Error(`get_entity_cognition failed: ${await bs(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(Xt(this._cfg.base_url,wt(`entities/${encodeURIComponent(n)}/card`)),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!r.ok)throw new Error(`get_entity_card failed: ${await bs(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=Xt(this._cfg.base_url,wt(`entities/${encodeURIComponent(r)}/diary/${encodeURIComponent(i)}?reason=${encodeURIComponent("observer board hint chip")}`)),c=await an(o,{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!c.ok)throw new Error(`read_entity_diary_entry failed: ${await bs(c)}`);return await c.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=Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}/ledger?after=${encodeURIComponent(String(r))}&limit=${encodeURIComponent(String(i))}`)),c=await an(o,{headers:{...Zt(this._cfg.auth_token)},signal:Xs(n==null?void 0:n.signal)});if(!c.ok)throw new Error(`get_ledger failed: ${c.status}`);const l=await Hy(c,o,{signal:Xs()}),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(Xt(this._cfg.base_url,wt("runs/ledger/batch")),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify({runs:n,limit:r}),signal:Xs()});if(!i.ok)throw new Error(`get_ledger_batch failed: ${i.status}`);const o=await Hy(i,Xt(this._cfg.base_url,wt("runs/ledger/batch")),{method:"POST",signal:Xs()}),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 c=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";c&&(i.model=c);const l=await an(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/summary`)),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(i)});if(!l.ok)throw await Zc(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 c=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";c&&(i.model=c);const l=await an(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/chat`)),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(i)});if(!l.ok)throw await Zc(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 c={audio_artifact:i};for(const m of["language","provider","model","request_id"]){const _=String((n==null?void 0:n[m])||"").trim();_&&(c[m]=_)}const l=await an(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(c)});if(!l.ok)throw await Zc(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(Xt(this._cfg.base_url,wt("voice/defaults")),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!t.ok)throw await Zc(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(Xt(this._cfg.base_url,wt(`voice/voices?${r.toString()}`)),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!i.ok)throw await Zc(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(Xt(this._cfg.base_url,wt("voice/design")),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(n)});if(!r.ok)throw new cv(r.status,await Gy(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(Xt(this._cfg.base_url,wt("voice/clones")),{method:"POST",headers:{...Zt(this._cfg.auth_token)},body:r});if(!i.ok)throw new cv(i.status,await Gy(i)||`The gateway could not clone the voice (HTTP ${i.status}).`);return await i.json()}gateway_url(t){return Xt(this._cfg.base_url,t)}auth_headers(){return Zt(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},c=String((n==null?void 0:n.voice)||"").trim();c&&(o.voice=c);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(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/voice/tts`)),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!h.ok)throw new Error(`voice_tts failed: ${await bs(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 c=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";c&&(i.model=c);const l=typeof(n==null?void 0:n.title)=="string"?String(n.title).trim():"";l&&(i.title=l);const d=await an(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/chat_threads`)),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(i)});if(!d.ok)throw new Error(`save_chat_thread failed: ${await bs(d)}`);return await d.json()}async list_bundles(){const t=await an(Xt(this._cfg.base_url,wt("bundles")),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});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(Xt(this._cfg.base_url,wt(t)),{headers:{...Zt(this._cfg.auth_token)},signal:n??Xs()});if(!r.ok)throw new Error(await bs(r));return await r.json()}async reload_bundles(){const t=await an(Xt(this._cfg.base_url,wt("bundles/reload")),{method:"POST",headers:{...Zt(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 c=await an(Xt(this._cfg.base_url,wt("bundles/upload")),{method:"POST",headers:{...Zt(this._cfg.auth_token)},body:o});if(!c.ok)throw new Error(`upload_bundle failed: ${await bs(c)}`);return await c.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",c=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),c&&l.append("content_type",c);const d=await an(Xt(this._cfg.base_url,wt("attachments/upload")),{method:"POST",headers:{...Zt(this._cfg.auth_token)},body:l});if(!d.ok)throw new Error(`attachments_upload failed: ${await bs(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 c=Xt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(r)}?${i.toString()}`)),l=await an(c,{method:"DELETE",headers:{...Zt(this._cfg.auth_token)}});if(!l.ok)throw new Error(`remove_bundle failed: ${await bs(l)}`);return await l.json()}async discovery_tools(){const t=await an(Xt(this._cfg.base_url,wt("discovery/tools")),{headers:{...Zt(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=Xt(this._cfg.base_url,wt(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),i=await an(r,{headers:{...Zt(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(Xt(this._cfg.base_url,wt(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...Zt(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(Xt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(n)}`)),{headers:{...Zt(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(Xt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(r)}/flows/${encodeURIComponent(i)}`)),{headers:{...Zt(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(Xt(this._cfg.base_url,wt(`workflows/${encodeURIComponent(n)}/flow`)),{headers:{...Zt(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(Xt(this._cfg.base_url,wt("discovery/capabilities")),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!t.ok)throw new Error(`discovery_capabilities failed: ${await bs(t)}`);return await t.json()}automations_client(){const t=this._cfg.auth_token;return _A({fetch:(n,r)=>fetch(n,r),baseUrl:this._cfg.base_url,headers:()=>Zt(t)})}async submit_command(t){const n=await an(Xt(this._cfg.base_url,wt("commands")),{method:"POST",headers:{"Content-Type":"application/json",...Zt(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},c=String((t==null?void 0:t.run_id)||"").trim();c&&(o.run_id=c);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 x=String((t==null?void 0:t.active_at)||"").trim();x&&(o.active_at=x);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 v=await an(Xt(this._cfg.base_url,wt("kg/query")),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!v.ok)throw new Error(`kg_query failed: ${await bs(v)}`);return await v.json()}async stream_ledger(t,n){var _;const r=Number((n==null?void 0:n.after)||0),i=n.on_step,o=n.signal,c=Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}/ledger/stream?after=${encodeURIComponent(String(r))}`)),l=await an(c,{headers:{Accept:"text/event-stream",...Zt(this._cfg.auth_token)},signal:o});if(!l.ok)throw await Zc(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 K4;for(;;){const{value:g,done:y}=await d.read();if(y)return;const x=h.decode(g,{stream:!0});m.push(x,k=>{if(!(k.event!=="step"||!k.data))try{const v=JSON.parse(k.data);v&&typeof v.cursor=="number"&&v.record&&i(v)}catch{}})}}}function X4(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 c=null;try{c=o?JSON.parse(o):null}catch{c=null}if(!i.ok)throw new Error(typeof(c==null?void 0:c.detail)=="string"?c.detail:typeof((l=c==null?void 0:c.detail)==null?void 0:l.message)=="string"?c.detail.message:o||`Gateway request failed (${i.status})`);return c}}function Z4({connected:e,request:t,value:n,onChange:r,disabled:i}){const[o,c]=p.useState(null),[l,d]=p.useState(null),h=JSON.stringify(n);p.useEffect(()=>{if(!e){c(null),d(null);return}let g=!0;return d(null),tm(t)(n).then(y=>g&&c(y)).catch(y=>g&&d(`Could not read your workspaces: ${Rg(y)}`)),()=>{g=!1}},[e,h,t]);const m=p.useCallback(async g=>{const y=await tm(t)(g);c(y),r(g)},[t,r]),_=e?i?"The run is starting.":null:"Connect to your gateway to choose workspaces.";return s.jsx(oN,{level:"run",idPrefix:"observer-launch-workspace",value:n,effective:o,onChange:m,loadError:e?l:_,unavailableReason:_})}function Q4(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class eD{constructor(t){jn(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)||Zs()),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:Zs(),method:"tools/call",params:{name:n,arguments:i}},c=await fetch(this._cfg.url,{method:"POST",headers:{"Content-Type":"application/json",...Q4(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)return{call_id:r,name:n,success:!1,output:null,error:`Worker HTTP ${c.status}`};const l=await c.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 Q0{constructor(t,n){jn(this,"pending",[]);jn(this,"scheduled",!1);jn(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 ek(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 tD(e,t){const n=Vt(e.updated_at||e.created_at)??0;return(Vt(t.updated_at||t.created_at)??0)-n}function nD(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=ek(g);if(String(g.role||"")==="occurrence"&&y&&!i[y]){const x={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]=x,r.push(x)}}const o={},c={};for(const g of r){const y=String(g.run_id||"").trim();if(!y)continue;const x=ek(g,t.parent_hint?t.parent_hint(y):"");c[y]=x,x&&(o[x]||(o[x]=[])).push(g)}const l=g=>{const y=String(g.status||"").trim().toLowerCase();return t.filter==="all"?!0:t.filter==="active"?Jd(y):t.filter==="waiting"?y==="waiting":t.filter==="terminal"?hs(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(),x=y?t.workflow_label_by_id[y]||y:"";return[g.run_id,y,x,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 x=c[y];(!x||!i[x])&&h.push(y)}const m={},_=g=>{if(t.group_by==="workflow"){const x=String(g.schedule_target_workflow_id||g.workflow_id||"").trim()||"(unknown workflow)";return{key:x,label:t.workflow_label_by_id[x]||x}}if(t.group_by==="session"){const x=String(g.session_id||"").trim()||"(no session)";return{key:x,label:x}}const y=String(g.status||"").trim().toLowerCase()||"unknown";return Jd(y)?{key:"active",label:"Active"}:y==="failed"?{key:"failed",label:"Failed"}:hs(y)?{key:"finished",label:"Finished"}:{key:y,label:y}};for(const g of h){const y=i[g];if(!y)continue;const x=[...o[g]||[]].sort(tD),k=x.some(N=>l(N)&&d(N));if(!(l(y)&&d(y))&&!k)continue;const v=_(y);m[v.key]||(m[v.key]={key:v.key,label:v.label,rows:[]}),m[v.key].rows.push({run:y,children:x})}return Object.values(m).sort((g,y)=>{const x={active:0,waiting:1,failed:2,finished:3},k=x[g.key]??10,v=x[y.key]??10;return k!==v?k-v:g.label.localeCompare(y.label)})}const tk=60;function Xd(e){try{const t=JSON.stringify(e);return t===void 0?String(e):t}catch{return String(e)}}function Jy(e,t,n){return`${e.toLocaleString("en-US")} ${e===1?t:n}`}function og(e){if(e===void 0)return"undefined";if(typeof e=="string")return e.length<=tk&&!e.includes(`
137
+ `)?JSON.stringify(e):`text (${Jy(e.length,"char","chars")})`;if(e===null||typeof e!="object")return Xd(e);const t=Xd(e);return t.length<=tk?t:Array.isArray(e)?`list (${Jy(e.length,"item","items")})`:`object (${Jy(Object.keys(e).length,"key","keys")})`}function sD(e){return e===void 0?!1:e&&typeof e=="object"&&!Array.isArray(e)?Object.values(e).some(t=>og(t)!==Xd(t)):og(e)!==Xd(e)}function rD(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}: ${og(e[n])}`).join(", ")}}`:"{}"}return og(e)}function Od(e){return Vt(e)}function iD(e){return e==null||e===""?"":typeof e=="string"?e:Xd(e)}function nk(e){return e.length?e[e.length-1]:null}function sk(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 c=Em(e.record);if(c&&t(c)==="running")return"running"}return"waiting"}return n==="failed"?"failed":n==="completed"||e.ended_at?"done":"running"}function oD(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 rk(e){const t=new Map;for(const i of[...e].sort((o,c)=>o.seq-c.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}oD(o[0],i[0])&&(i=o)}r.push(i.shift())}return r}function aD(e){return Od(e.ended_at)??Od(e.started_at)}function lD(e,t,n){var k,v,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 c=new Map;for(const W of i)c.set(W,Ig(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?nk(c.get(W)||[]):null,V=K?sk(K,M=>h(M,G+1)):null;return d.set(W,V),V},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 c.get(W)||[]){const K=String(G.node_id||"").trim();if(!K)continue;const V=l(W,K);if(!V)continue;const M=_(V,K);M.steps.push({step:G,rid:W,t:aD(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()),V=i.indexOf(String(G.x.run_id||G.x.record.run_id||"").trim());return K!==V?K-V:(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 V=l(G,K),M=V?m.get(V):void 0;M&&M.records.push({rec:W.record,rid:G,t:Od(W.record.ended_at)??Od(W.record.started_at),seq:g++})}const x={};for(const[W,G]of m){const K=G.facts,V=rk(G.steps).map(se=>se.step),M=nk(V);K.visits=V.length,K.status=sk(M,se=>h(se)),K.last_effect=M.effect_type,K.last_status=M.status;let A=0,O=0,L=0,H=!1,J=0,U=null;const te=new Map;for(const se of V){const de=Od(se.started_at),be=Od(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=(v=se.record)==null?void 0:v.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))&&(H=!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=Cm(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=iD((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=rD(K.last_result),K.tools=Array.from(te.values()),J&&U){const se=$m(U);if(K.llm={calls:J,model:se.model,provider:se.provider},H&&(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=rk(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=Em(se);be&&!K.subruns.includes(be)&&K.subruns.push(be)}if(z)for(const se of K.waits)se.open=se.wait_key===z;x[W]=K}return x}function cD(e){const t={};for(const[n,r]of Object.entries(e||{}))t[n]=r.status;return t}function uD(e){const{records:t,context:n,...r}=e;return JSON.stringify(r,null,2)}function dD(e){return e.records.map(t=>Xd(t)).join(`
138
+ `)}function fD(e){return e.context?JSON.stringify(e.context,null,2):""}function Yy(e){return typeof e=="number"&&Number.isFinite(e)?new Date(e).toISOString():null}function hD(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:Yy(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?Yy(i.first_ms):null,last_at:i?Yy(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 mD={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"},_D=[{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 pD(){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:[_D.map(n=>s.jsxs("div",{className:"pin-legend-row",children:[s.jsx("span",{className:"pin-legend-shape",style:{color:mD[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 uv={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 gD(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(uv,e)}function yD(e){return gD(e)?uv[e]:uv.any}function wD(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 vD=280,xD=6,bD=360,kD=1500;function O1(e,t=vD,n=xD){const r=String(e??"");let i=r.length,o=-1;for(let c=0;c<n&&(o=r.indexOf(`
139
+ `,o+1),o!==-1);c+=1)c===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 al(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 jD(e){return e===null||["string","number","boolean"].includes(typeof e)}function ik(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function SD(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(jD))return{head:n,items:e.map(o=>String(o)),item_word:"items"};const r=new Map;for(const o of e)r.set(ik(o),(r.get(ik(o))||0)+1);const i=[...r.entries()].map(([o,c])=>`${c} ${o}${c===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:al(e),items:[],item_word:"items"}}function ND(e,t=bD){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 Dg(e){const[t,n]=p.useState("");p.useEffect(()=>{if(!t)return;const i=window.setTimeout(()=>n(""),kD);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 Tm(e.text)?"copied":"failed")},children:t==="copied"?"copied":t==="failed"?"copy failed":"⧉"})}function P1(e){const t=e.size??12,n=t/2,r=e.filled?"currentColor":"none",i=wD(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 c=[[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:c,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:yD(e.type)},"aria-hidden":"true",children:o})}function $D(e){const[t,n]=p.useState(!1),{shown:r,clamped:i}=O1(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 CD(e){const[t,n]=p.useState(!1),r=ND(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(c=>!c),children:t?"show less":`show all ${e.items.length.toLocaleString("en-US")} ${e.word}`}):null]})}function ED(e){const[t,n]=p.useState(!1),r=SD(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(CD,{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:al(e.value)}):null]})]})}function om(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($D,{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(ED,{value:t}):s.jsx("code",{className:"ap_pin_scalar",children:String(t)})}function AD(e){return e.state==="value"?al(e.value):e.state==="not_provided"&&e.flow_default?al(e.flow_default.value):null}function TD(e){const{pin:t}=e;if(t.state==="value")return s.jsx(om,{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(om,{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 MD(e){const{pin:t}=e,n=t.typed?t.type:"untyped",r=AD(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(P1,{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(Dg,{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(TD,{pin:t,side:e.side,outputs_final:e.outputs_final})})]})}function ok(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(MD,{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(P1,{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(Dg,{text:al(i),label:r,on_copy:e.on_copy}):null]}),s.jsx("div",{className:"ap_pin_value",children:s.jsx(om,{value:i})})]},r))})]}):null]})}const dv=5*6e4;function RD(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 xx(e,t){const{by_id:n,children_of:r}=RD(e);return{by_id:n,children_of:r,now_ms:Date.now(),...t||{}}}function D1(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 LD(e,t){return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function ID(e,t,n){var o,c;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(((c=n==null?void 0:n.details)==null?void 0:c.kind)||"").trim().toLowerCase()==="pause"}function ak(e){return e?String(e.prompt||"").trim()?!0:Array.isArray(e.choices)&&e.choices.length>0:!1}function fv(e){return Vt((e==null?void 0:e.updated_at)||(e==null?void 0:e.created_at)||"")}function er(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 OD(e,t){return e===null?"":er(t-e)}function lk(e,t){if(e===null)return"";const n=new Date(e).toISOString().slice(11,16),r=e-t;return r>0?`${n} UTC (in ${nm(r)})`:`${n} UTC (due)`}function Pd(e,t){const n=String(e||"").replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const PD=6e4;function DD(e,t){var c;const n=D1(e,t),r=String(((c=n==null?void 0:n.details)==null?void 0:c.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=>!hs(String((l==null?void 0:l.status)||"")));return o.length?(o.sort((l,d)=>(fv(d)??0)-(fv(l)??0)),o[0]):null}function Fg(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,c=i>=0?t.slice(i+1):"";return c&&!/^[0-9a-f]{8,}$/i.test(c)?c:o||ni(t)}function FD(e){const t=String(e||"").trim(),n=ni(t);return n&&n!==t?`${n} — ${t}`:t}function F1(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 ni(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 Zd(e){const t=String(e||"").trim();return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function Qd(e,t,n=0){const r=zD(e,t,n);return{...r,brief:r.brief||r.text}}function zD(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:dv,o=String((e==null?void 0:e.run_id)||"").trim(),c=String((e==null?void 0:e.status)||"").trim().toLowerCase(),l=D1(e,t),d=LD(e,l),h=fv(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=OD(h,r),y=g?` · ${g}`:"";if(hs(c)){const V=sm(e),M=String((e==null?void 0:e.error)||"").trim(),A=(N=t.details)==null?void 0:N.get(o),O=Vt((e==null?void 0:e.created_at)||""),L=Vt((e==null?void 0:e.updated_at)||""),H=O!==null&&L!==null&&L>=O?er(L-O):"";let J=V;V==="failed"?J=M?`failed: ${Pd(M,120)}`:"failed":V==="completed"?J=H?`completed in ${H}`:"completed":V==="stopped"?J="stopped before the turn finished":V==="cancelled"&&(J="cancelled");const U=String((A==null?void 0:A.error)||"").trim();return V==="failed"&&!M&&U&&(J=`failed: ${Pd(U,120)}`),{..._,verb:"done",lane:"done",object:J,actor:"none",action:"open_run",text:J}}if(m==="controller"){const V=($=t.automations)==null?void 0:$.get(String((e==null?void 0:e.automation_id)||o)),M=Vt((l==null?void 0:l.until)||""),A=(V==null?void 0:V.next_fire_ms)??M,O=[];V!=null&&V.current&&!hs(V.current.status)?O.push(`run #${V.current.index} in progress`):d==="subworkflow"&&O.push("a run is in progress"),(V==null?void 0:V.status)==="paused"?O.push("paused: scheduled runs are skipped"):A!==null?O.push(`next run in ${nm(Math.max(0,A-r))}`):(V==null?void 0:V.status)==="completed"||(V==null?void 0:V.status)==="failed"?O.push(`${V.status}: no next run`):V!=null&&V.event_driven?O.push("listening"):((E=V==null?void 0:V.trigger)==null?void 0:E.source_id)==="manual"?O.push("runs when someone presses Run now"):O.push("next run not scheduled"),V!=null&&V.last&&O.push(`last #${V.last.index} ${V.last.status}`),V&&O.push(`${V.occurrence_count} turn${V.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 V="draft · not started";return{..._,verb:"scheduled",lane:"scheduled",object:V,actor:"none",action:"open_run",text:V}}if(c==="running"){const V=((S=t.pulses)==null?void 0:S.get(o))||null,M=V&&V.ended_ms===null&&V.started_ms!==null?V:null,A=Math.max(h??0,(V==null?void 0:V.ended_ms)??0,(V==null?void 0:V.started_ms)??0)||null,O=A?Math.max(0,r-A):null,L=O!==null&&O>i,H=M?`${M.effect||M.node_id||"step"} open ${er(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}`),H?U.push(H):O!==null&&U.push(`last step ${er(O)} ago`),L&&U.push("no progress"),{..._,verb:"running",lane:"working",object:H||J||"",actor:"runtime",action:"open_run",stale_ms:O,stalled:L,open_step:H,text:U.join(" · ")}}if(c!=="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 V=c?`${c}${y}`:"state unknown";return{..._,object:V,text:V,action:"inspect"}}if(ID(e,t,l)){const V=`paused${y} · resume when ready`;return{..._,verb:"paused",lane:"needs_you",object:"paused",actor:"you",action:"resume",text:V}}const x=of(l);if(x.length){const V=x.map(O=>String((O==null?void 0:O.name)||"tool").trim()).filter(Boolean),M=`${V.slice(0,3).join(", ")}${V.length>3?` +${V.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(ak(l)){const A=Pd(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 V=n<4?DD(e,t):null;if(!V){const L=String(((I=l==null?void 0:l.details)==null?void 0:I.sub_run_id)||"").trim(),H=L?(W=t.fates)==null?void 0:W.get(L):void 0,U=F1(e,t)||H&&Fg(H.workflow_id)||Zd(L);if(H&&H.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(H&&hs(H.status)){const z=Vt(H.updated_at),ne=z!==null?Math.max(0,t.now_ms-z):null;if(ne!==null&&ne<=PD){const Me=`its subrun ${U} ${H.status} ${er(ne)} ago · resuming${y}`;return{..._,verb:"running",lane:"working",object:`subrun ${U}`,actor:"runtime",action:"open_run",text:Me}}const se=ne!==null?` ${er(ne)} ago`:"",de=H.status==="cancelled"?"was cancelled":H.status==="failed"?"failed":`ended ${H.status}`,be=`stuck: subrun ${U} ${de}${se}, this run was not resumed${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:`subrun ${U} (${H.status})`,actor:"you",action:"open_run",stuck:!0,stuck_facts:{subrun:U,status:H.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=Qd(V,t,n+1),A=ni(String(V.workflow_id||""))||Zd(String(V.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 ${er(M.stale_ms)} ago`),M.stalled&&L.push("no progress"),{..._,verb:"running",lane:"working",object:`subrun ${A}`,actor:"run",actor_run_id:String(V.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(V.run_id||""),action:"open_subrun",unresolved:M.unresolved,text:O}}if(d==="until"){const V=Vt((l==null?void 0:l.until)||""),M=V!==null?`sleeps until ${lk(V,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(ak(l)){const L=Pd(String((l==null?void 0:l.prompt)||""),80),H=L?`asks: ${L}${y}`:`asks a question${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:L||"a question",actor:"you",action:"answer",text:H,brief:`asks a question${y}`}}const V=Vt((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=V!==null?`waiting for ${A} until ${lk(V,r)}`:`waiting for ${A}${y}`;return{..._,object:A,actor:"external",action:"open_run",text:O}}if(d==="job"){const V=`waiting for a delegated tool job${y}`;return{..._,object:"a delegated tool job",actor:"runtime",action:"open_run",text:V}}const k=String((l==null?void 0:l.wait_key)||"").trim(),v=`waiting, reason unknown${k?` (${k})`:""}${y} · inspect`;return{..._,object:"unknown",actor:"unknown",action:"inspect",text:v}}function z1(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=sm({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 Xy={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,c=ni(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"),c&&n!=="controller"&&!(o!=null&&o.title)&&h.push(c),n==="controller"&&o&&h.push(o.cadence),{kind:"automation",glyph:Xy.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=[c,String((e==null?void 0:e.parent_run_id)||"").trim()?"subrun":""].filter(Boolean);return{kind:"agent",glyph:Xy.agent,label:"session",secondary:h.join(" · "),automation_id:"",id_hint:l}}return{kind:"run",glyph:Xy.run,label:"",secondary:c,automation_id:"",id_hint:""}}function U1(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 c=String(((y=e==null?void 0:e.brief)==null?void 0:y.task_excerpt)||"").trim();if(c)return{text:Pd(c,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:Pd(n.excerpt,80),source:"excerpt",untitled:!1}:{text:ni(String((e==null?void 0:e.workflow_id)||""))||"(workflow?)",source:"workflow",untitled:!0}}function bx(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?IO(e):""}function Mm(e){var k,v,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,c=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((v=n==null?void 0:n.notify)==null?void 0:v.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,x=(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()||bx(y,x),trigger_text:String((t==null?void 0:t.trigger_text)||"").trim(),trigger:y,event_driven:uc(y),time_zone:String((t==null?void 0:t.time_zone)||"").trim(),next_fire_ms:Vt((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:Vt(o.fired_at||""),finished_ms:Vt(o.finished_at||"")}:null,occurrence_count:typeof(t==null?void 0:t.occurrence_count)=="number"?t.occurrence_count:0,current:c?{index:Number(c.index||0),run_id:String(c.run_id||""),status:String(c.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:x,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 BD(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:Vt(r.started_at||""),ended_ms:Vt(r.ended_at||"")}}function Rn(e){return typeof e=="string"?e:e==null?"":String(e)}function ck(e,t){const n=Rn(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function W1(e){const t=Rn(e==null?void 0:e.targetHandle),n=Rn(e==null?void 0:e.sourceHandle);return!!(t==="exec-in"||n==="exec-out"||t.includes("exec")||n.includes("exec"))}function q1(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{};return Rn((t==null?void 0:t.nodeType)||(e==null?void 0:e.type)||"").trim()}function V1(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=Rn(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 UD(e){const t=Rn(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(q1(r)==="on_flow_start"){const i=Rn(r==null?void 0:r.id).trim();if(i)return i}return""}function Zy(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 jh(e,t){const n=Rn(e).trim(),r=Rn(t).trim();return r?n?`${n}::${r}`:r:""}function WD(e){const t=e.root&&typeof e.root=="object"?e.root:{};if(!e.expand_subflows)return t;const n=[],r=[],i=new Set,o=(c,l,d,h)=>{if(!c||typeof c!="object"||n.length>=e.max_nodes||r.length>=e.max_edges)return;const m=Array.isArray(c.nodes)?c.nodes:[],_=Array.isArray(c.edges)?c.edges:[];for(const g of m){const y=Rn(g==null?void 0:g.id).trim();if(!y)continue;const x=jh(l,y);if(!x||i.has(x))continue;const k=Zy(g),v={...g,id:x,position:{x:k.x+d.x,y:k.y+d.y}};if(n.push(v),i.add(x),n.length>=e.max_nodes)break}for(const g of _){if(!W1(g))continue;const y=Rn(g==null?void 0:g.source).trim(),x=Rn(g==null?void 0:g.target).trim();if(!y||!x)continue;const k=jh(l,y),v=jh(l,x);if(!k||!v)continue;const N=Rn(g==null?void 0:g.id).trim(),$=N?`${k}->${v}::${N}`:`${k}->${v}`;if(r.push({...g,id:$,source:k,target:v}),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(q1(g)!=="subflow")continue;const y=V1(g);if(!y)continue;const x=e.flow_by_id[y];if(!x||typeof x!="object")continue;const k=jh(l,Rn(g==null?void 0:g.id));if(!k)continue;const v=UD(x);if(!v)continue;const $=(Array.isArray(x.nodes)?x.nodes:[]).find(W=>Rn(W==null?void 0:W.id).trim()===v)||null;if(!$)continue;const E=Zy(g),S=Zy($),R={x:E.x+d.x+240-S.x,y:E.y+d.y+0-S.y},I=jh(k,v);r.push({id:`${k}=>${I}`,source:k,target:I,sourceHandle:"exec-out",targetHandle:"exec-in"}),o(x,k,R,h+1)}};return o(t,"",{x:0,y:0},0),{...t,id:Rn(t.id),nodes:n,edges:r}}function qD(e){const t=Rn(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 VD(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 c=new Set,l=(r[o.id]||[]).slice();for(;l.length;){const d=l.pop();if(!d||c.has(d))continue;if(c.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)c.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 uk(e,t){const i=Math.max(t.w*8,160),o=Math.max(t.h*8,120),c=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:c,h:l}}const HD=new Set(["completed","failed","cancelled","stopped"]),H1={running:"here",waiting:"waiting here",failed:"failed here",done:"here",none:"here"},G1={running:"running",waiting:"waiting",failed:"failed",done:"done",none:"not visited"},K1={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 J1(e){const t=(e==null?void 0:e.waits.find(n=>n.open))||null;return t?K1[t.reason]||`waiting (${t.reason||"reason not recorded"})`:"waiting, reason not recorded"}function Qc(e){return e==="running"?3:e==="waiting"?2:0}function dk(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 fk=typeof window>"u"?p.useEffect:p.useLayoutEffect;function GD(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 Rp(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 Tm(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??a1:e.label})})}function hk(e){const[t,n]=p.useState(!1),{shown:r,clamped:i}=O1(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 KD(e){const[t,n]=p.useState(!1),r=sD(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 JD(e){const{node:t,facts:n,status:r}=e,i=r==="waiting"?J1(n):G1[r],o=n?[`${n.visits.toLocaleString("en-US")} visit${n.visits===1?"":"s"}`,n.first_ms!==null?`first ${dk(n.first_ms)}`:"",n.last_ms!==null?`last ${dk(n.last_ms)}`:"",`${bu(n.duration_ms)} in steps`].filter(Boolean):[],c=(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:H1[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(" · ")})]}),c?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"LLM"}),s.jsx("dd",{children:[c.model||"model not recorded",c.provider||"provider not recorded",`${c.calls.toLocaleString("en-US")} call${c.calls===1?"":"s"}`,c.tokens?`${c.tokens.in.toLocaleString("en-US")} in · ${c.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:K1[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(hk,{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:Zd(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(KD,{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(hk,{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(Rp,{label:"Copy facts (JSON)",disabled:!n,get_text:()=>n?uD(n):""}),s.jsx(Rp,{label:"Copy records (JSONL)",disabled:!n||!n.records.length,get_text:()=>n?dD(n):""}),n!=null&&n.context?s.jsx(Rp,{label:"Copy context",get_text:()=>fD(n)}):null]})]})}function YD(e){var gt;const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=e.flow,r=Rn(e.active_node_id),i=e.recent_nodes||{},o=e.visited_nodes||{},c=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=WD({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 Qt=Rn(Be==null?void 0:Be.id).trim();if(!Qt)continue;const Mt=Be!=null&&Be.position&&typeof Be.position=="object"?Be.position:{},Fn=typeof Mt.x=="number"?Mt.x:0,fn=typeof Mt.y=="number"?Mt.y:0,Xe=Be!=null&&Be.data&&typeof Be.data=="object"?Be.data:{},nn=Rn((Xe==null?void 0:Xe.label)||(Be==null?void 0:Be.label)||Qt)||Qt,cn=Rn((Xe==null?void 0:Xe.nodeType)||(Be==null?void 0:Be.type)||"unknown")||"unknown",Ar=Rn((Xe==null?void 0:Xe.headerColor)||(Be==null?void 0:Be.headerColor)||"")||"",As=Xe!=null&&Xe.eventConfig&&typeof Xe.eventConfig=="object"?Xe.eventConfig:null,ws=As&&typeof As.schedule=="string"?Rn(As.schedule).trim():"",_r=As&&typeof As.recurrent=="boolean"?!!As.recurrent:void 0,we=cn==="subflow"?V1(Be):"",Nt=ws||_r!==void 0||we?{schedule:ws||void 0,recurrent:_r,subflow_id:we||void 0}:void 0;Ie.push({id:Qt,x:Fn,y:fn,label:nn,type:cn,color:Ar,meta:Nt})}const We={};for(const Be of Ie)We[Be.id]=Be;let Ue=[];for(const Be of Ce){if(!W1(Be))continue;const Qt=Rn(Be==null?void 0:Be.source).trim(),Mt=Rn(Be==null?void 0:Be.target).trim();!Qt||!Mt||Ue.push({id:Rn((Be==null?void 0:Be.id)||`${Qt}->${Mt}`),source:Qt,target:Mt})}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 Qt=VD({nodes:Ie,edges:Ue,keep_id:Mt=>{if(r&&Mt===r)return!0;const Fn=We[Mt];if(!Fn)return!1;const fn=Rn(Fn.type).trim().toLowerCase();return fn==="on_flow_start"||fn==="on_flow_end"||fn==="subflow"?!0:!qD(fn)},max_edges:900});Ie=Qt.nodes,Ue=Qt.edges}if(e.prefer_vertical===!0&&Ie.length>=2){const Be=Ie.map(Xe=>Xe.x),Qt=Ie.map(Xe=>Xe.y),Mt=Math.max(...Be)-Math.min(...Be),Fn=Math.max(...Qt)-Math.min(...Qt);Mt>=Fn&&(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,At=vt/2,zt=xt/2;let ot=0,Yt=0,vn=0,hn=0;Ie.length&&(ot=Math.min(...Ie.map(Be=>Be.x)),Yt=Math.min(...Ie.map(Be=>Be.y)),vn=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(Qt=>`${Qt.source}->${Qt.target}`));for(const Qt of Ue){if(!Be.has(`${Qt.target}->${Qt.source}`))continue;const Mt=at[Qt.source],Fn=at[Qt.target];if(!Mt||!Fn)continue;const fn=Mt.x+At,Xe=Mt.y+zt,nn=Fn.x+At,cn=Fn.y+zt,Ar=Math.max(1,Math.hypot(nn-fn,cn-Xe)),As=Math.max(28,Math.min(72,Ar*.14)),ws=Math.min(200,As*3.5);ws>sn&&(sn=ws)}}const Ht=60+sn,is={x:ot-Ht,y:Yt-Ht,w:vn-ot+Ht*2,h:hn-Yt+Ht*2,node_w:vt,node_h:xt};return{nodes:Ie,edges:Ue,bounds:is}},[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})),x=p.useRef(g);x.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),v=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),V=`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)},H=(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(),[]),fk(()=>{$&&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}})};fk(()=>{$&&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=Rn(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(c)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=Rn(e.schedule_next_in).trim(),je=Rn(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=Rn((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"},Ve=re=>{var vt;const fe=Rn((vt=re.meta)==null?void 0:vt.subflow_id).trim(),Ce=fe&&e.flow_by_id?e.flow_by_id[fe]:null,We=Rn(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=Ve(re);Ce=We.label,Ie=We.sub}return{label:Ce,type:Ie}},nt=Rn(e.run_status).trim().toLowerCase(),rt=e.run_line||null,ze=Rn(e.run_id).trim(),He=!!(nt||rt||ze),ct=nt?HD.has(nt):rt?rt.verb==="done":!1,Qe=nt==="failed"||nt==="cancelled",Dt=e.node_facts||{},$e=e.node_status||cD(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=Qc(Ie),at=Qc(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&&He){let re=null;for(const[fe,Ce]of Object.entries(Le))(ct?Qe&&Ce.s==="failed":Qc(Ce.s)>0)&&(!re||Qc(Ce.s)>Qc(re.s)||Qc(Ce.s)===Qc(re.s)&&Ce.t>re.t)&&(re={id:fe,...Ce});Q=re?re.id:""}const _e=re=>ct&&nt==="cancelled"&&re==="failed"?"cancelled here":H1[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=Sa(nt||(rt?{running:"running",needs_you:"waiting",paused:"paused",waiting:"waiting",scheduled:"scheduled",done:""}[rt.verb]??"":"")),St=Q?z[Q]:void 0,ut=Rn(e.current_node_label).trim()||(St?mt(St,Q===se).label:""),Ot=!!ut&&(!ct||Qe),Rt=`${le.size.toLocaleString("en-US")} node${le.size===1?"":"s"} visited${dt!==null?` in ${bu(dt)}`:""}`,mn=He?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:["· ",Rt]}):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 He?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 wn=(re,fe,Ce)=>{const Ie=Ce||x.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}},On=(re,fe,Ce)=>{const Ie=Ce||x.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,At=re.y-vt*et;y(uk({x:xt,y:At,w:Ue,h:et},m))},Ks=(re,fe,Ce)=>{const Ie=Ce||x.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=>uk({x:(Ce||xt).x-at,y:(Ce||xt).y-vt,w:(Ce||xt).w,h:(Ce||xt).h},m))},rs=(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,At=Math.min(vt,xt);return{x:re+Ce*At,y:fe+Ie*At}},ge=()=>JSON.stringify(hD({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=wn(fe.left+fe.width/2,fe.top+fe.height/2);On(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=wn(fe.left+fe.width/2,fe.top+fe.height/2);On(Ce,1.18)},title:"Zoom out",children:"−"}),s.jsx(Rp,{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(pD,{})]}),s.jsxs("svg",{ref:_,className:"graph_svg",viewBox:te,role:"group","aria-label":"Workflow execution graph",onWheel:re=>{re.preventDefault();const fe=wn(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)),On(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)v.current={mode:"pan",start_view:x.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},At=x.current;v.current={mode:"pinch",start_view:At,start_client:xt,start_dist:vt,anchor_svg:wn(xt.x,xt.y,At)}}},onPointerMove:re=>{if(!k.current.has(re.pointerId))return;k.current.set(re.pointerId,{x:re.clientX,y:re.clientY});const fe=v.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;Ks(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;On(fe.anchor_svg,vt,fe.start_view)}},onPointerUp:re=>{k.current.delete(re.pointerId),k.current.size===0&&(v.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&&H(fe.id,!1)},onPointerCancel:re=>{k.current.delete(re.pointerId),k.current.size===0&&(v.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=rs(Ie,We,at,vt),At=rs(Ue,et,-at,-vt),zt=re.source!==re.target&&N.has(`${re.target}->${re.source}`),ot=Math.max(1,Math.hypot(at,vt)),Yt=-vt/ot,vn=at/ot,hn=String(re.source)<String(re.target)?1:-1,Ht=Math.abs(at)>=Math.abs(vt)?at>=0:vt>=0,is=!zt||Ht,Be=Math.max(28,Math.min(72,ot*.14)),Qt=Math.min(200,Be*3.5),Mt=zt&&!is?Qt*hn:0,Fn=(xt.x+At.x)/2+Yt*Mt,fn=(xt.y+At.y)/2+vn*Mt,Xe=zt&&!is?`M ${xt.x} ${xt.y} Q ${Fn} ${fn} ${At.x} ${At.y}`:`M ${xt.x} ${xt.y} L ${At.x} ${At.y}`,nn=c&&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=c&&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:At}=mt(re,!!Ie),zt=ck(xt,22),ot=ck(At,22),Yt=et?_e(Ue):"",vn=Yt?Math.round(Yt.length*6.2+14):0,hn=Ue==="waiting"?J1(Dt[re.id]):G1[Ue],sn=($==null?void 0:$.id)===re.id;return s.jsxs("g",{ref:Ht=>{D.current[re.id]=Ht},className:at,transform:`translate(${re.x}, ${re.y})`,"data-flow-node":re.id,"data-run-status":Ue,tabIndex:0,role:"button","aria-label":`${xt} (${At}): ${hn}${Yt?`, ${Yt}`:""}`,"aria-haspopup":"dialog","aria-expanded":sn,"aria-describedby":sn?V:void 0,onPointerDown:Ht=>{W.current={id:re.id,x:Ht.clientX,y:Ht.clientY}},onMouseEnter:()=>{($==null?void 0:$.mode)!=="pinned"&&(M(),!sn&&(I.current=window.setTimeout(()=>{v.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:Ht=>{var is;sn&&($==null?void 0:$.mode)==="focus"&&!((is=R.current)!=null&&is.contains(Ht.relatedTarget))&&L(re.id)},onKeyDown:Ht=>{Ht.key!=="Enter"&&Ht.key!==" "||(Ht.preventDefault(),H(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(GD,{status:Ue})}):null,Yt?s.jsxs("g",{className:"flow_here_chip",transform:`translate(${m.node_w-26-vn}, -9)`,"aria-hidden":"true",children:[s.jsx("rect",{width:vn,height:18,rx:9,ry:9}),s.jsx("text",{x:7,y:12.5,children:Yt})]}):null]},re.id)})]}),$&&Re&&S&&typeof document<"u"?bg.createPortal(s.jsx("div",{ref:R,id:V,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(JD,{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 Er(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=Er(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var Qy={exports:{}},ew={},tw={exports:{}},nw={};/**
140
+ * @license React
141
+ * use-sync-external-store-shim.production.js
142
+ *
143
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
144
+ *
145
+ * This source code is licensed under the MIT license found in the
146
+ * LICENSE file in the root directory of this source tree.
147
+ */var mk;function XD(){if(mk)return nw;mk=1;var e=wm();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,c=e.useDebugValue;function l(_,g){var y=g(),x=r({inst:{value:y,getSnapshot:g}}),k=x[0].inst,v=x[1];return o(function(){k.value=y,k.getSnapshot=g,d(k)&&v({inst:k})},[_,y,g]),i(function(){return d(k)&&v({inst:k}),_(function(){d(k)&&v({inst:k})})},[_]),c(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 nw.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:m,nw}var _k;function ZD(){return _k||(_k=1,tw.exports=XD()),tw.exports}/**
148
+ * @license React
149
+ * use-sync-external-store-shim/with-selector.production.js
150
+ *
151
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
152
+ *
153
+ * This source code is licensed under the MIT license found in the
154
+ * LICENSE file in the root directory of this source tree.
155
+ */var pk;function QD(){if(pk)return ew;pk=1;var e=wm(),t=ZD();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,c=e.useEffect,l=e.useMemo,d=e.useDebugValue;return ew.useSyncExternalStoreWithSelector=function(h,m,_,g,y){var x=o(null);if(x.current===null){var k={hasValue:!1,value:null};x.current=k}else k=x.current;x=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 v=i(h,x[0],x[1]);return c(function(){k.hasValue=!0,k.value=v},[v]),d(v),v},ew}var gk;function e5(){return gk||(gk=1,Qy.exports=QD()),Qy.exports}var t5=e5();const n5=Gv(t5),s5={},yk=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(x=>x(t,y))}},i=()=>t,d={setState:r,getState:i,getInitialState:()=>h,subscribe:m=>(n.add(m),()=>n.delete(m)),destroy:()=>{(s5?"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},r5=e=>e?yk(e):yk,{useDebugValue:i5}=Ee,{useSyncExternalStoreWithSelector:o5}=n5,a5=e=>e;function Y1(e,t=a5,n){const r=o5(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return i5(r),r}const wk=(e,t)=>{const n=r5(e),r=(i,o=t)=>Y1(n,i,o);return Object.assign(r,n),r},l5=(e,t)=>e?wk(e,t):wk;function mr(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 c5={value:()=>{}};function zg(){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 Lp(n)}function Lp(e){this._=e}function u5(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}})}Lp.prototype=zg.prototype={constructor:Lp,on:function(e,t){var n=this._,r=u5(e+"",n),i,o=-1,c=r.length;if(arguments.length<2){for(;++o<c;)if((i=(e=r[o]).type)&&(i=d5(n[i],e.name)))return i;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++o<c;)if(i=(e=r[o]).type)n[i]=vk(n[i],e.name,t);else if(t==null)for(i in n)n[i]=vk(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 Lp(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 d5(e,t){for(var n=0,r=e.length,i;n<r;++n)if((i=e[n]).name===t)return i.value}function vk(e,t,n){for(var r=0,i=e.length;r<i;++r)if(e[r].name===t){e[r]=c5,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var hv="http://www.w3.org/1999/xhtml";const xk={svg:"http://www.w3.org/2000/svg",xhtml:hv,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Bg(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),xk.hasOwnProperty(t)?{space:xk[t],local:e}:e}function f5(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===hv&&t.documentElement.namespaceURI===hv?t.createElement(e):t.createElementNS(n,e)}}function h5(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function X1(e){var t=Bg(e);return(t.local?h5:f5)(t)}function m5(){}function kx(e){return e==null?m5:function(){return this.querySelector(e)}}function _5(e){typeof e!="function"&&(e=kx(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o=t[i],c=o.length,l=r[i]=new Array(c),d,h,m=0;m<c;++m)(d=o[m])&&(h=e.call(d,d.__data__,m,o))&&("__data__"in d&&(h.__data__=d.__data__),l[m]=h);return new zi(r,this._parents)}function p5(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function g5(){return[]}function Z1(e){return e==null?g5:function(){return this.querySelectorAll(e)}}function y5(e){return function(){return p5(e.apply(this,arguments))}}function w5(e){typeof e=="function"?e=y5(e):e=Z1(e);for(var t=this._groups,n=t.length,r=[],i=[],o=0;o<n;++o)for(var c=t[o],l=c.length,d,h=0;h<l;++h)(d=c[h])&&(r.push(e.call(d,d.__data__,h,c)),i.push(d));return new zi(r,i)}function Q1(e){return function(){return this.matches(e)}}function e$(e){return function(t){return t.matches(e)}}var v5=Array.prototype.find;function x5(e){return function(){return v5.call(this.children,e)}}function b5(){return this.firstElementChild}function k5(e){return this.select(e==null?b5:x5(typeof e=="function"?e:e$(e)))}var j5=Array.prototype.filter;function S5(){return Array.from(this.children)}function N5(e){return function(){return j5.call(this.children,e)}}function $5(e){return this.selectAll(e==null?S5:N5(typeof e=="function"?e:e$(e)))}function C5(e){typeof e!="function"&&(e=Q1(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o=t[i],c=o.length,l=r[i]=[],d,h=0;h<c;++h)(d=o[h])&&e.call(d,d.__data__,h,o)&&l.push(d);return new zi(r,this._parents)}function t$(e){return new Array(e.length)}function E5(){return new zi(this._enter||this._groups.map(t$),this._parents)}function ag(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}ag.prototype={constructor:ag,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 A5(e){return function(){return e}}function T5(e,t,n,r,i,o){for(var c=0,l,d=t.length,h=o.length;c<h;++c)(l=t[c])?(l.__data__=o[c],r[c]=l):n[c]=new ag(e,o[c]);for(;c<d;++c)(l=t[c])&&(i[c]=l)}function M5(e,t,n,r,i,o,c){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=c.call(d,d.__data__,l,t)+"",h.has(y)?i[l]=d:h.set(y,d));for(l=0;l<_;++l)y=c.call(e,o[l],l,o)+"",(d=h.get(y))?(r[l]=d,d.__data__=o[l],h.delete(y)):n[l]=new ag(e,o[l]);for(l=0;l<m;++l)(d=t[l])&&h.get(g[l])===d&&(i[l]=d)}function R5(e){return e.__data__}function L5(e,t){if(!arguments.length)return Array.from(this,R5);var n=t?M5:T5,r=this._parents,i=this._groups;typeof e!="function"&&(e=A5(e));for(var o=i.length,c=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=I5(e.call(m,m&&m.__data__,h,r)),x=y.length,k=l[h]=new Array(x),v=c[h]=new Array(x),N=d[h]=new Array(g);n(m,_,k,v,N,y,t);for(var $=0,E=0,S,P;$<x;++$)if(S=k[$]){for($>=E&&(E=$+1);!(P=v[E])&&++E<x;);S._next=P||null}}return c=new zi(c,r),c._enter=l,c._exit=d,c}function I5(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function O5(){return new zi(this._exit||this._groups.map(t$),this._parents)}function P5(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 D5(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,i=n.length,o=r.length,c=Math.min(i,o),l=new Array(i),d=0;d<c;++d)for(var h=n[d],m=r[d],_=h.length,g=l[d]=new Array(_),y,x=0;x<_;++x)(y=h[x]||m[x])&&(g[x]=y);for(;d<i;++d)l[d]=n[d];return new zi(l,this._parents)}function F5(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],i=r.length-1,o=r[i],c;--i>=0;)(c=r[i])&&(o&&c.compareDocumentPosition(o)^4&&o.parentNode.insertBefore(c,o),o=c);return this}function z5(e){e||(e=B5);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 c=n[o],l=c.length,d=i[o]=new Array(l),h,m=0;m<l;++m)(h=c[m])&&(d[m]=h);d.sort(t)}return new zi(i,this._parents).order()}function B5(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function U5(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function W5(){return Array.from(this)}function q5(){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 c=r[i];if(c)return c}return null}function V5(){let e=0;for(const t of this)++e;return e}function H5(){return!this.node()}function G5(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var i=t[n],o=0,c=i.length,l;o<c;++o)(l=i[o])&&e.call(l,l.__data__,o,i);return this}function K5(e){return function(){this.removeAttribute(e)}}function J5(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Y5(e,t){return function(){this.setAttribute(e,t)}}function X5(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function Z5(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function Q5(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 eF(e,t){var n=Bg(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?J5:K5:typeof t=="function"?n.local?Q5:Z5:n.local?X5:Y5)(n,t))}function n$(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function tF(e){return function(){this.style.removeProperty(e)}}function nF(e,t,n){return function(){this.style.setProperty(e,t,n)}}function sF(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function rF(e,t,n){return arguments.length>1?this.each((t==null?tF:typeof t=="function"?sF:nF)(e,t,n??"")):ef(this.node(),e)}function ef(e,t){return e.style.getPropertyValue(t)||n$(e).getComputedStyle(e,null).getPropertyValue(t)}function iF(e){return function(){delete this[e]}}function oF(e,t){return function(){this[e]=t}}function aF(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function lF(e,t){return arguments.length>1?this.each((t==null?iF:typeof t=="function"?aF:oF)(e,t)):this.node()[e]}function s$(e){return e.trim().split(/^|\s+/)}function jx(e){return e.classList||new r$(e)}function r$(e){this._node=e,this._names=s$(e.getAttribute("class")||"")}r$.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 i$(e,t){for(var n=jx(e),r=-1,i=t.length;++r<i;)n.add(t[r])}function o$(e,t){for(var n=jx(e),r=-1,i=t.length;++r<i;)n.remove(t[r])}function cF(e){return function(){i$(this,e)}}function uF(e){return function(){o$(this,e)}}function dF(e,t){return function(){(t.apply(this,arguments)?i$:o$)(this,e)}}function fF(e,t){var n=s$(e+"");if(arguments.length<2){for(var r=jx(this.node()),i=-1,o=n.length;++i<o;)if(!r.contains(n[i]))return!1;return!0}return this.each((typeof t=="function"?dF:t?cF:uF)(n,t))}function hF(){this.textContent=""}function mF(e){return function(){this.textContent=e}}function _F(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function pF(e){return arguments.length?this.each(e==null?hF:(typeof e=="function"?_F:mF)(e)):this.node().textContent}function gF(){this.innerHTML=""}function yF(e){return function(){this.innerHTML=e}}function wF(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function vF(e){return arguments.length?this.each(e==null?gF:(typeof e=="function"?wF:yF)(e)):this.node().innerHTML}function xF(){this.nextSibling&&this.parentNode.appendChild(this)}function bF(){return this.each(xF)}function kF(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function jF(){return this.each(kF)}function SF(e){var t=typeof e=="function"?e:X1(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function NF(){return null}function $F(e,t){var n=typeof e=="function"?e:X1(e),r=t==null?NF:typeof t=="function"?t:kx(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function CF(){var e=this.parentNode;e&&e.removeChild(this)}function EF(){return this.each(CF)}function AF(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function TF(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function MF(e){return this.select(e?TF:AF)}function RF(e){return arguments.length?this.property("__data__",e):this.node().__data__}function LF(e){return function(t){e.call(this,t,this.__data__)}}function IF(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 OF(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 PF(e,t,n){return function(){var r=this.__on,i,o=LF(t);if(r){for(var c=0,l=r.length;c<l;++c)if((i=r[c]).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 DF(e,t,n){var r=IF(e+""),i,o=r.length,c;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((c=r[i]).type===m.type&&c.name===m.name)return m.value}return}for(l=t?PF:OF,i=0;i<o;++i)this.each(l(r[i],t,n));return this}function a$(e,t,n){var r=n$(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 FF(e,t){return function(){return a$(this,e,t)}}function zF(e,t){return function(){return a$(this,e,t.apply(this,arguments))}}function BF(e,t){return this.each((typeof t=="function"?zF:FF)(e,t))}function*UF(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],i=0,o=r.length,c;i<o;++i)(c=r[i])&&(yield c)}var l$=[null];function zi(e,t){this._groups=e,this._parents=t}function Rm(){return new zi([[document.documentElement]],l$)}function WF(){return this}zi.prototype=Rm.prototype={constructor:zi,select:_5,selectAll:w5,selectChild:k5,selectChildren:$5,filter:C5,data:L5,enter:E5,exit:O5,join:P5,merge:D5,selection:WF,order:F5,sort:z5,call:U5,nodes:W5,node:q5,size:V5,empty:H5,each:G5,attr:eF,style:rF,property:lF,classed:fF,text:pF,html:vF,raise:bF,lower:jF,append:SF,insert:$F,remove:EF,clone:MF,datum:RF,on:DF,dispatch:BF,[Symbol.iterator]:UF};function wo(e){return typeof e=="string"?new zi([[document.querySelector(e)]],[document.documentElement]):new zi([[e]],l$)}function qF(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Vo(e,t){if(e=qF(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 VF={passive:!1},am={capture:!0,passive:!1};function sw(e){e.stopImmediatePropagation()}function qd(e){e.preventDefault(),e.stopImmediatePropagation()}function c$(e){var t=e.document.documentElement,n=wo(e).on("dragstart.drag",qd,am);"onselectstart"in t?n.on("selectstart.drag",qd,am):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function u$(e,t){var n=e.document.documentElement,r=wo(e).on("dragstart.drag",null);t&&(r.on("click.drag",qd,am),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 cp=e=>()=>e;function mv(e,{sourceEvent:t,subject:n,target:r,identifier:i,active:o,x:c,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:c,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}})}mv.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function HF(e){return!e.ctrlKey&&!e.button}function GF(){return this.parentNode}function KF(e,t){return t??{x:e.x,y:e.y}}function JF(){return navigator.maxTouchPoints||"ontouchstart"in this}function YF(){var e=HF,t=GF,n=KF,r=JF,i={},o=zg("start","drag","end"),c=0,l,d,h,m,_=0;function g(S){S.on("mousedown.drag",y).filter(r).on("touchstart.drag",v).on("touchmove.drag",N,VF).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&&(wo(S.view).on("mousemove.drag",x,am).on("mouseup.drag",k,am),c$(S.view),sw(S),h=!1,l=S.clientX,d=S.clientY,D("start",S))}}function x(S){if(qd(S),!h){var P=S.clientX-l,D=S.clientY-d;h=P*P+D*D>_}i.mouse("drag",S)}function k(S){wo(S.view).on("mousemove.drag mouseup.drag",null),u$(S.view,h),qd(S),i.mouse("end",S)}function v(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]))&&(sw(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])&&(qd(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])&&(sw(S),I("end",S,P[R]))}function E(S,P,D,R,I,W){var G=o.copy(),K=Vo(W||D,P),V,M,A;if((A=n.call(S,new mv("beforestart",{sourceEvent:D,target:g,identifier:I,active:c,x:K[0],y:K[1],dx:0,dy:0,dispatch:G}),R))!=null)return V=A.x-K[0]||0,M=A.y-K[1]||0,function O(L,H,J){var U=K,te;switch(L){case"start":i[I]=O,te=c++;break;case"end":delete i[I],--c;case"drag":K=Vo(J||H,P),te=c;break}G.call(L,S,new mv(L,{sourceEvent:H,subject:A,target:g,identifier:I,active:te,x:K[0]+V,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:cp(!!S),g):e},g.container=function(S){return arguments.length?(t=typeof S=="function"?S:cp(S),g):t},g.subject=function(S){return arguments.length?(n=typeof S=="function"?S:cp(S),g):n},g.touchable=function(S){return arguments.length?(r=typeof S=="function"?S:cp(!!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 Sx(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function d$(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Lm(){}var lm=.7,lg=1/lm,Vd="\\s*([+-]?\\d+)\\s*",cm="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ja="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",XF=/^#([0-9a-f]{3,8})$/,ZF=new RegExp(`^rgb\\(${Vd},${Vd},${Vd}\\)$`),QF=new RegExp(`^rgb\\(${ja},${ja},${ja}\\)$`),e6=new RegExp(`^rgba\\(${Vd},${Vd},${Vd},${cm}\\)$`),t6=new RegExp(`^rgba\\(${ja},${ja},${ja},${cm}\\)$`),n6=new RegExp(`^hsl\\(${cm},${ja},${ja}\\)$`),s6=new RegExp(`^hsla\\(${cm},${ja},${ja},${cm}\\)$`),bk={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};Sx(Lm,um,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:kk,formatHex:kk,formatHex8:r6,formatHsl:i6,formatRgb:jk,toString:jk});function kk(){return this.rgb().formatHex()}function r6(){return this.rgb().formatHex8()}function i6(){return f$(this).formatHsl()}function jk(){return this.rgb().formatRgb()}function um(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=XF.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Sk(t):n===3?new Si(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?up(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?up(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=ZF.exec(e))?new Si(t[1],t[2],t[3],1):(t=QF.exec(e))?new Si(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=e6.exec(e))?up(t[1],t[2],t[3],t[4]):(t=t6.exec(e))?up(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=n6.exec(e))?Ck(t[1],t[2]/100,t[3]/100,1):(t=s6.exec(e))?Ck(t[1],t[2]/100,t[3]/100,t[4]):bk.hasOwnProperty(e)?Sk(bk[e]):e==="transparent"?new Si(NaN,NaN,NaN,0):null}function Sk(e){return new Si(e>>16&255,e>>8&255,e&255,1)}function up(e,t,n,r){return r<=0&&(e=t=n=NaN),new Si(e,t,n,r)}function o6(e){return e instanceof Lm||(e=um(e)),e?(e=e.rgb(),new Si(e.r,e.g,e.b,e.opacity)):new Si}function _v(e,t,n,r){return arguments.length===1?o6(e):new Si(e,t,n,r??1)}function Si(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Sx(Si,_v,d$(Lm,{brighter(e){return e=e==null?lg:Math.pow(lg,e),new Si(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?lm:Math.pow(lm,e),new Si(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Si(uu(this.r),uu(this.g),uu(this.b),cg(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:Nk,formatHex:Nk,formatHex8:a6,formatRgb:$k,toString:$k}));function Nk(){return`#${iu(this.r)}${iu(this.g)}${iu(this.b)}`}function a6(){return`#${iu(this.r)}${iu(this.g)}${iu(this.b)}${iu((isNaN(this.opacity)?1:this.opacity)*255)}`}function $k(){const e=cg(this.opacity);return`${e===1?"rgb(":"rgba("}${uu(this.r)}, ${uu(this.g)}, ${uu(this.b)}${e===1?")":`, ${e})`}`}function cg(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function uu(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function iu(e){return e=uu(e),(e<16?"0":"")+e.toString(16)}function Ck(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Ko(e,t,n,r)}function f$(e){if(e instanceof Ko)return new Ko(e.h,e.s,e.l,e.opacity);if(e instanceof Lm||(e=um(e)),!e)return new Ko;if(e instanceof Ko)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),c=NaN,l=o-i,d=(o+i)/2;return l?(t===o?c=(n-r)/l+(n<r)*6:n===o?c=(r-t)/l+2:c=(t-n)/l+4,l/=d<.5?o+i:2-o-i,c*=60):l=d>0&&d<1?0:c,new Ko(c,l,d,e.opacity)}function l6(e,t,n,r){return arguments.length===1?f$(e):new Ko(e,t,n,r??1)}function Ko(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Sx(Ko,l6,d$(Lm,{brighter(e){return e=e==null?lg:Math.pow(lg,e),new Ko(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?lm:Math.pow(lm,e),new Ko(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 Si(rw(e>=240?e-240:e+120,i,r),rw(e,i,r),rw(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new Ko(Ek(this.h),dp(this.s),dp(this.l),cg(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=cg(this.opacity);return`${e===1?"hsl(":"hsla("}${Ek(this.h)}, ${dp(this.s)*100}%, ${dp(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Ek(e){return e=(e||0)%360,e<0?e+360:e}function dp(e){return Math.max(0,Math.min(1,e||0))}function rw(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 h$=e=>()=>e;function c6(e,t){return function(n){return e+n*t}}function u6(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 d6(e){return(e=+e)==1?m$:function(t,n){return n-t?u6(t,n,e):h$(isNaN(t)?n:t)}}function m$(e,t){var n=t-e;return n?c6(e,n):h$(isNaN(e)?t:e)}const Ak=(function e(t){var n=d6(t);function r(i,o){var c=n((i=_v(i)).r,(o=_v(o)).r),l=n(i.g,o.g),d=n(i.b,o.b),h=m$(i.opacity,o.opacity);return function(m){return i.r=c(m),i.g=l(m),i.b=d(m),i.opacity=h(m),i+""}}return r.gamma=e,r})(1);function Ql(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var pv=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,iw=new RegExp(pv.source,"g");function f6(e){return function(){return e}}function h6(e){return function(t){return e(t)+""}}function m6(e,t){var n=pv.lastIndex=iw.lastIndex=0,r,i,o,c=-1,l=[],d=[];for(e=e+"",t=t+"";(r=pv.exec(e))&&(i=iw.exec(t));)(o=i.index)>n&&(o=t.slice(n,o),l[c]?l[c]+=o:l[++c]=o),(r=r[0])===(i=i[0])?l[c]?l[c]+=i:l[++c]=i:(l[++c]=null,d.push({i:c,x:Ql(r,i)})),n=iw.lastIndex;return n<t.length&&(o=t.slice(n),l[c]?l[c]+=o:l[++c]=o),l.length<2?d[0]?h6(d[0].x):f6(t):(t=d.length,function(h){for(var m=0,_;m<t;++m)l[(_=d[m]).i]=_.x(h);return l.join("")})}var Tk=180/Math.PI,gv={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function _$(e,t,n,r,i,o){var c,l,d;return(c=Math.sqrt(e*e+t*t))&&(e/=c,t/=c),(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,c=-c),{translateX:i,translateY:o,rotate:Math.atan2(t,e)*Tk,skewX:Math.atan(d)*Tk,scaleX:c,scaleY:l}}var fp;function _6(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?gv:_$(t.a,t.b,t.c,t.d,t.e,t.f)}function p6(e){return e==null||(fp||(fp=document.createElementNS("http://www.w3.org/2000/svg","g")),fp.setAttribute("transform",e),!(e=fp.transform.baseVal.consolidate()))?gv:(e=e.matrix,_$(e.a,e.b,e.c,e.d,e.e,e.f))}function p$(e,t,n,r){function i(h){return h.length?h.pop()+" ":""}function o(h,m,_,g,y,x){if(h!==_||m!==g){var k=y.push("translate(",null,t,null,n);x.push({i:k-4,x:Ql(h,_)},{i:k-2,x:Ql(m,g)})}else(_||g)&&y.push("translate("+_+t+g+n)}function c(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:Ql(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:Ql(h,m)}):m&&_.push(i(_)+"skewX("+m+r)}function d(h,m,_,g,y,x){if(h!==_||m!==g){var k=y.push(i(y)+"scale(",null,",",null,")");x.push({i:k-4,x:Ql(h,_)},{i:k-2,x:Ql(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),c(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 x=-1,k=g.length,v;++x<k;)_[(v=g[x]).i]=v.x(y);return _.join("")}}}var g6=p$(_6,"px, ","px)","deg)"),y6=p$(p6,", ",")",")"),w6=1e-12;function Mk(e){return((e=Math.exp(e))+1/e)/2}function v6(e){return((e=Math.exp(e))-1/e)/2}function x6(e){return((e=Math.exp(2*e))-1)/(e+1)}const b6=(function e(t,n,r){function i(o,c){var l=o[0],d=o[1],h=o[2],m=c[0],_=c[1],g=c[2],y=m-l,x=_-d,k=y*y+x*x,v,N;if(k<w6)N=Math.log(g/h)/t,v=function(R){return[l+R*y,d+R*x,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,v=function(R){var I=R*N,W=Mk(P),G=h/(n*$)*(W*x6(t*I+P)-v6(P));return[l+G*y,d+G*x,h*W/Mk(t*I+P)]}}return v.duration=N*1e3*t/Math.SQRT2,v}return i.rho=function(o){var c=Math.max(.001,+o),l=c*c,d=l*l;return e(c,l,d)},i})(Math.SQRT2,2,4);var tf=0,qh=0,Sh=0,g$=1e3,ug,Vh,dg=0,vu=0,Ug=0,dm=typeof performance=="object"&&performance.now?performance:Date,y$=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Nx(){return vu||(y$(k6),vu=dm.now()+Ug)}function k6(){vu=0}function fg(){this._call=this._time=this._next=null}fg.prototype=w$.prototype={constructor:fg,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Nx():+n)+(t==null?0:+t),!this._next&&Vh!==this&&(Vh?Vh._next=this:ug=this,Vh=this),this._call=e,this._time=n,yv()},stop:function(){this._call&&(this._call=null,this._time=1/0,yv())}};function w$(e,t,n){var r=new fg;return r.restart(e,t,n),r}function j6(){Nx(),++tf;for(var e=ug,t;e;)(t=vu-e._time)>=0&&e._call.call(void 0,t),e=e._next;--tf}function Rk(){vu=(dg=dm.now())+Ug,tf=qh=0;try{j6()}finally{tf=0,N6(),vu=0}}function S6(){var e=dm.now(),t=e-dg;t>g$&&(Ug-=t,dg=e)}function N6(){for(var e,t=ug,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:ug=n);Vh=e,yv(r)}function yv(e){if(!tf){qh&&(qh=clearTimeout(qh));var t=e-vu;t>24?(e<1/0&&(qh=setTimeout(Rk,e-dm.now()-Ug)),Sh&&(Sh=clearInterval(Sh))):(Sh||(dg=dm.now(),Sh=setInterval(S6,g$)),tf=1,y$(Rk))}}function Lk(e,t,n){var r=new fg;return t=t==null?0:+t,r.restart(i=>{r.stop(),e(i+t)},t,n),r}var $6=zg("start","end","cancel","interrupt"),C6=[],v$=0,Ik=1,wv=2,Ip=3,Ok=4,vv=5,Op=6;function Wg(e,t,n,r,i,o){var c=e.__transition;if(!c)e.__transition={};else if(n in c)return;E6(e,n,{name:t,index:r,group:i,on:$6,tween:C6,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:v$})}function $x(e,t){var n=Yo(e,t);if(n.state>v$)throw new Error("too late; already scheduled");return n}function Na(e,t){var n=Yo(e,t);if(n.state>Ip)throw new Error("too late; already running");return n}function Yo(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function E6(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=w$(o,0,n.time);function o(h){n.state=Ik,n.timer.restart(c,n.delay,n.time),n.delay<=h&&c(h-n.delay)}function c(h){var m,_,g,y;if(n.state!==Ik)return d();for(m in r)if(y=r[m],y.name===n.name){if(y.state===Ip)return Lk(c);y.state===Ok?(y.state=Op,y.timer.stop(),y.on.call("interrupt",e,e.__data__,y.index,y.group),delete r[m]):+m<t&&(y.state=Op,y.timer.stop(),y.on.call("cancel",e,e.__data__,y.index,y.group),delete r[m])}if(Lk(function(){n.state===Ip&&(n.state=Ok,n.timer.restart(l,n.delay,n.time),l(h))}),n.state=wv,n.on.call("start",e,e.__data__,n.index,n.group),n.state===wv){for(n.state=Ip,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=vv,1),_=-1,g=i.length;++_<g;)i[_].call(e,m);n.state===vv&&(n.on.call("end",e,e.__data__,n.index,n.group),d())}function d(){n.state=Op,n.timer.stop(),delete r[t];for(var h in r)return;delete e.__transition}}function Pp(e,t){var n=e.__transition,r,i,o=!0,c;if(n){t=t==null?null:t+"";for(c in n){if((r=n[c]).name!==t){o=!1;continue}i=r.state>wv&&r.state<vv,r.state=Op,r.timer.stop(),r.on.call(i?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[c]}o&&delete e.__transition}}function A6(e){return this.each(function(){Pp(this,e)})}function T6(e,t){var n,r;return function(){var i=Na(this,e),o=i.tween;if(o!==n){r=n=o;for(var c=0,l=r.length;c<l;++c)if(r[c].name===t){r=r.slice(),r.splice(c,1);break}}i.tween=r}}function M6(e,t,n){var r,i;if(typeof n!="function")throw new Error;return function(){var o=Na(this,e),c=o.tween;if(c!==r){i=(r=c).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 R6(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Yo(this.node(),n).tween,i=0,o=r.length,c;i<o;++i)if((c=r[i]).name===e)return c.value;return null}return this.each((t==null?T6:M6)(n,e,t))}function Cx(e,t,n){var r=e._id;return e.each(function(){var i=Na(this,r);(i.value||(i.value={}))[t]=n.apply(this,arguments)}),function(i){return Yo(i,r).value[t]}}function x$(e,t){var n;return(typeof t=="number"?Ql:t instanceof um?Ak:(n=um(t))?(t=n,Ak):m6)(e,t)}function L6(e){return function(){this.removeAttribute(e)}}function I6(e){return function(){this.removeAttributeNS(e.space,e.local)}}function O6(e,t,n){var r,i=n+"",o;return function(){var c=this.getAttribute(e);return c===i?null:c===r?o:o=t(r=c,n)}}function P6(e,t,n){var r,i=n+"",o;return function(){var c=this.getAttributeNS(e.space,e.local);return c===i?null:c===r?o:o=t(r=c,n)}}function D6(e,t,n){var r,i,o;return function(){var c,l=n(this),d;return l==null?void this.removeAttribute(e):(c=this.getAttribute(e),d=l+"",c===d?null:c===r&&d===i?o:(i=d,o=t(r=c,l)))}}function F6(e,t,n){var r,i,o;return function(){var c,l=n(this),d;return l==null?void this.removeAttributeNS(e.space,e.local):(c=this.getAttributeNS(e.space,e.local),d=l+"",c===d?null:c===r&&d===i?o:(i=d,o=t(r=c,l)))}}function z6(e,t){var n=Bg(e),r=n==="transform"?y6:x$;return this.attrTween(e,typeof t=="function"?(n.local?F6:D6)(n,r,Cx(this,"attr."+e,t)):t==null?(n.local?I6:L6)(n):(n.local?P6:O6)(n,r,t))}function B6(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function U6(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function W6(e,t){var n,r;function i(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&U6(e,o)),n}return i._value=t,i}function q6(e,t){var n,r;function i(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&B6(e,o)),n}return i._value=t,i}function V6(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=Bg(e);return this.tween(n,(r.local?W6:q6)(r,t))}function H6(e,t){return function(){$x(this,e).delay=+t.apply(this,arguments)}}function G6(e,t){return t=+t,function(){$x(this,e).delay=t}}function K6(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?H6:G6)(t,e)):Yo(this.node(),t).delay}function J6(e,t){return function(){Na(this,e).duration=+t.apply(this,arguments)}}function Y6(e,t){return t=+t,function(){Na(this,e).duration=t}}function X6(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?J6:Y6)(t,e)):Yo(this.node(),t).duration}function Z6(e,t){if(typeof t!="function")throw new Error;return function(){Na(this,e).ease=t}}function Q6(e){var t=this._id;return arguments.length?this.each(Z6(t,e)):Yo(this.node(),t).ease}function e8(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Na(this,e).ease=n}}function t8(e){if(typeof e!="function")throw new Error;return this.each(e8(this._id,e))}function n8(e){typeof e!="function"&&(e=Q1(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o=t[i],c=o.length,l=r[i]=[],d,h=0;h<c;++h)(d=o[h])&&e.call(d,d.__data__,h,o)&&l.push(d);return new ll(r,this._parents,this._name,this._id)}function s8(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),c=new Array(r),l=0;l<o;++l)for(var d=t[l],h=n[l],m=d.length,_=c[l]=new Array(m),g,y=0;y<m;++y)(g=d[y]||h[y])&&(_[y]=g);for(;l<r;++l)c[l]=t[l];return new ll(c,this._parents,this._name,this._id)}function r8(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 i8(e,t,n){var r,i,o=r8(t)?$x:Na;return function(){var c=o(this,e),l=c.on;l!==r&&(i=(r=l).copy()).on(t,n),c.on=i}}function o8(e,t){var n=this._id;return arguments.length<2?Yo(this.node(),n).on.on(e):this.each(i8(n,e,t))}function a8(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function l8(){return this.on("end.remove",a8(this._id))}function c8(e){var t=this._name,n=this._id;typeof e!="function"&&(e=kx(e));for(var r=this._groups,i=r.length,o=new Array(i),c=0;c<i;++c)for(var l=r[c],d=l.length,h=o[c]=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]=_,Wg(h[g],t,n,g,h,Yo(m,n)));return new ll(o,this._parents,t,n)}function u8(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Z1(e));for(var r=this._groups,i=r.length,o=[],c=[],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,x=Yo(m,n),k=0,v=g.length;k<v;++k)(y=g[k])&&Wg(y,t,n,k,g,x);o.push(g),c.push(m)}return new ll(o,c,t,n)}var d8=Rm.prototype.constructor;function f8(){return new d8(this._groups,this._parents)}function h8(e,t){var n,r,i;return function(){var o=ef(this,e),c=(this.style.removeProperty(e),ef(this,e));return o===c?null:o===n&&c===r?i:i=t(n=o,r=c)}}function b$(e){return function(){this.style.removeProperty(e)}}function m8(e,t,n){var r,i=n+"",o;return function(){var c=ef(this,e);return c===i?null:c===r?o:o=t(r=c,n)}}function _8(e,t,n){var r,i,o;return function(){var c=ef(this,e),l=n(this),d=l+"";return l==null&&(d=l=(this.style.removeProperty(e),ef(this,e))),c===d?null:c===r&&d===i?o:(i=d,o=t(r=c,l))}}function p8(e,t){var n,r,i,o="style."+t,c="end."+o,l;return function(){var d=Na(this,e),h=d.on,m=d.value[o]==null?l||(l=b$(t)):void 0;(h!==n||i!==m)&&(r=(n=h).copy()).on(c,i=m),d.on=r}}function g8(e,t,n){var r=(e+="")=="transform"?g6:x$;return t==null?this.styleTween(e,h8(e,r)).on("end.style."+e,b$(e)):typeof t=="function"?this.styleTween(e,_8(e,r,Cx(this,"style."+e,t))).each(p8(this._id,e)):this.styleTween(e,m8(e,r,t),n).on("end.style."+e,null)}function y8(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function w8(e,t,n){var r,i;function o(){var c=t.apply(this,arguments);return c!==i&&(r=(i=c)&&y8(e,c,n)),r}return o._value=t,o}function v8(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,w8(e,t,n??""))}function x8(e){return function(){this.textContent=e}}function b8(e){return function(){var t=e(this);this.textContent=t??""}}function k8(e){return this.tween("text",typeof e=="function"?b8(Cx(this,"text",e)):x8(e==null?"":e+""))}function j8(e){return function(t){this.textContent=e.call(this,t)}}function S8(e){var t,n;function r(){var i=e.apply(this,arguments);return i!==n&&(t=(n=i)&&j8(i)),t}return r._value=e,r}function N8(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,S8(e))}function $8(){for(var e=this._name,t=this._id,n=k$(),r=this._groups,i=r.length,o=0;o<i;++o)for(var c=r[o],l=c.length,d,h=0;h<l;++h)if(d=c[h]){var m=Yo(d,t);Wg(d,e,n,h,c,{time:m.time+m.delay+m.duration,delay:0,duration:m.duration,ease:m.ease})}return new ll(r,this._parents,e,n)}function C8(){var e,t,n=this,r=n._id,i=n.size();return new Promise(function(o,c){var l={value:c},d={value:function(){--i===0&&o()}};n.each(function(){var h=Na(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 E8=0;function ll(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function k$(){return++E8}var Xa=Rm.prototype;ll.prototype={constructor:ll,select:c8,selectAll:u8,selectChild:Xa.selectChild,selectChildren:Xa.selectChildren,filter:n8,merge:s8,selection:f8,transition:$8,call:Xa.call,nodes:Xa.nodes,node:Xa.node,size:Xa.size,empty:Xa.empty,each:Xa.each,on:o8,attr:z6,attrTween:V6,style:g8,styleTween:v8,text:k8,textTween:N8,remove:l8,tween:R6,delay:K6,duration:X6,ease:Q6,easeVarying:t8,end:C8,[Symbol.iterator]:Xa[Symbol.iterator]};function A8(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var T8={time:null,delay:0,duration:250,ease:A8};function M8(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 R8(e){var t,n;e instanceof ll?(t=e._id,e=e._name):(t=k$(),(n=T8).time=Nx(),e=e==null?null:e+"");for(var r=this._groups,i=r.length,o=0;o<i;++o)for(var c=r[o],l=c.length,d,h=0;h<l;++h)(d=c[h])&&Wg(d,e,t,h,c,n||M8(d,t));return new ll(r,this._parents,e,t)}Rm.prototype.interrupt=A6;Rm.prototype.transition=R8;const hp=e=>()=>e;function L8(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 tl(e,t,n){this.k=e,this.x=t,this.y=n}tl.prototype={constructor:tl,scale:function(e){return e===1?this:new tl(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new tl(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 sl=new tl(1,0,0);tl.prototype;function ow(e){e.stopImmediatePropagation()}function Nh(e){e.preventDefault(),e.stopImmediatePropagation()}function I8(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function O8(){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 Pk(){return this.__zoom||sl}function P8(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function D8(){return navigator.maxTouchPoints||"ontouchstart"in this}function F8(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],c=e.invertY(t[1][1])-n[1][1];return e.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),c>o?(o+c)/2:Math.min(0,o)||Math.max(0,c))}function j$(){var e=I8,t=O8,n=F8,r=P8,i=D8,o=[0,1/0],c=[[-1/0,-1/0],[1/0,1/0]],l=250,d=b6,h=zg("start","zoom","end"),m,_,g,y=500,x=150,k=0,v=10;function N(A){A.property("__zoom",Pk).on("wheel.zoom",I,{passive:!1}).on("mousedown.zoom",W).on("dblclick.zoom",G).filter(i).on("touchstart.zoom",K).on("touchmove.zoom",V).on("touchend.zoom touchcancel.zoom",M).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}N.transform=function(A,O,L,H){var J=A.selection?A.selection():A;J.property("__zoom",Pk),A!==J?P(A,O,L,H):J.interrupt().each(function(){D(this,arguments).event(H).start().zoom(null,typeof O=="function"?O.apply(this,arguments):O).end()})},N.scaleBy=function(A,O,L,H){N.scaleTo(A,function(){var J=this.__zoom.k,U=typeof O=="function"?O.apply(this,arguments):O;return J*U},L,H)},N.scaleTo=function(A,O,L,H){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,c)},L,H)},N.translateBy=function(A,O,L,H){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),c)},null,H)},N.translateTo=function(A,O,L,H,J){N.transform(A,function(){var U=t.apply(this,arguments),te=this.__zoom,z=H==null?S(U):typeof H=="function"?H.apply(this,arguments):H;return n(sl.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,c)},H,J)};function $(A,O){return O=Math.max(o[0],Math.min(o[1],O)),O===A.k?A:new tl(O,A.x,A.y)}function E(A,O,L){var H=O[0]-L[0]*A.k,J=O[1]-L[1]*A.k;return H===A.x&&J===A.y?A:new tl(A.k,H,J)}function S(A){return[(+A[0][0]+ +A[1][0])/2,(+A[0][1]+ +A[1][1])/2]}function P(A,O,L,H){A.on("start.zoom",function(){D(this,arguments).event(H).start()}).on("interrupt.zoom end.zoom",function(){D(this,arguments).event(H).end()}).tween("zoom",function(){var J=this,U=arguments,te=D(J,U).event(H),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 tl(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=wo(this.that).datum();h.call(A,this.that,new L8(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),H=this.__zoom,J=Math.max(o[0],Math.min(o[1],H.k*Math.pow(2,r.apply(this,arguments)))),U=Vo(A);if(L.wheel)(L.mouse[0][0]!==U[0]||L.mouse[0][1]!==U[1])&&(L.mouse[1]=H.invert(L.mouse[0]=U)),clearTimeout(L.wheel);else{if(H.k===J)return;L.mouse=[U,H.invert(U)],Pp(this),L.start()}Nh(A),L.wheel=setTimeout(te,x),L.zoom("mouse",n(E($(H,J),L.mouse[0],L.mouse[1]),L.extent,c));function te(){L.wheel=null,L.end()}}function W(A,...O){if(g||!e.apply(this,arguments))return;var L=A.currentTarget,H=D(this,O,!0).event(A),J=wo(A.view).on("mousemove.zoom",ne,!0).on("mouseup.zoom",se,!0),U=Vo(A,L),te=A.clientX,z=A.clientY;c$(A.view),ow(A),H.mouse=[U,this.__zoom.invert(U)],Pp(this),H.start();function ne(de){if(Nh(de),!H.moved){var be=de.clientX-te,Me=de.clientY-z;H.moved=be*be+Me*Me>k}H.event(de).zoom("mouse",n(E(H.that.__zoom,H.mouse[0]=Vo(de,L),H.mouse[1]),H.extent,c))}function se(de){J.on("mousemove.zoom mouseup.zoom",null),u$(de.view,H.moved),Nh(de),H.event(de).end()}}function G(A,...O){if(e.apply(this,arguments)){var L=this.__zoom,H=Vo(A.changedTouches?A.changedTouches[0]:A,this),J=L.invert(H),U=L.k*(A.shiftKey?.5:2),te=n(E($(L,U),H,J),t.apply(this,O),c);Nh(A),l>0?wo(this).transition().duration(l).call(P,te,H,A):wo(this).call(N.transform,te,H,A)}}function K(A,...O){if(e.apply(this,arguments)){var L=A.touches,H=L.length,J=D(this,O,A.changedTouches.length===H).event(A),U,te,z,ne;for(ow(A),te=0;te<H;++te)z=L[te],ne=Vo(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)),Pp(this),J.start())}}function V(A,...O){if(this.__zooming){var L=D(this,O).event(A),H=A.changedTouches,J=H.length,U,te,z,ne;for(Nh(A),U=0;U<J;++U)te=H[U],z=Vo(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,c))}}function M(A,...O){if(this.__zooming){var L=D(this,O).event(A),H=A.changedTouches,J=H.length,U,te;for(ow(A),g&&clearTimeout(g),g=setTimeout(function(){g=null},y),U=0;U<J;++U)te=H[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=Vo(te,this),Math.hypot(_[0]-te[0],_[1]-te[1])<v)){var z=wo(this).on("dblclick.zoom");z&&z.apply(this,arguments)}}}return N.wheelDelta=function(A){return arguments.length?(r=typeof A=="function"?A:hp(+A),N):r},N.filter=function(A){return arguments.length?(e=typeof A=="function"?A:hp(!!A),N):e},N.touchable=function(A){return arguments.length?(i=typeof A=="function"?A:hp(!!A),N):i},N.extent=function(A){return arguments.length?(t=typeof A=="function"?A:hp([[+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?(c[0][0]=+A[0][0],c[1][0]=+A[1][0],c[0][1]=+A[0][1],c[1][1]=+A[1][1],N):[[c[0][0],c[0][1]],[c[1][0],c[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?(v=+A,N):v},N}const qg=p.createContext(null),z8=qg.Provider,cl={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.`},S$=cl.error001();function ms(e,t){const n=p.useContext(qg);if(n===null)throw new Error(S$);return Y1(n,e,t)}const tr=()=>{const e=p.useContext(qg);if(e===null)throw new Error(S$);return p.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},B8=e=>e.userSelectionActive?"none":"all";function fm({position:e,children:t,className:n,style:r,...i}){const o=ms(B8),c=`${e}`.split("-");return Ee.createElement("div",{className:Er(["react-flow__panel",n,...c]),style:{...r,pointerEvents:o},...i},t)}function U8({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:Ee.createElement(fm,{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 W8=({x:e,y:t,label:n,labelStyle:r={},labelShowBg:i=!0,labelBgStyle:o={},labelBgPadding:c=[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}),x=Er(["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:x,visibility:g.width?"visible":"hidden",...m},i&&Ee.createElement("rect",{width:g.width+2*c[0],x:-c[0],y:-c[1],height:g.height+2*c[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 q8=p.memo(W8);const Ex=e=>({width:e.offsetWidth,height:e.offsetHeight}),nf=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Ax=(e={x:0,y:0},t)=>({x:nf(e.x,t[0][0],t[1][0]),y:nf(e.y,t[0][1],t[1][1])}),Dk=(e,t,n)=>e<t?nf(Math.abs(e-t),1,50)/50:e>n?-nf(Math.abs(e-n),1,50)/50:0,N$=(e,t)=>{const n=Dk(e.x,35,t.width-35)*20,r=Dk(e.y,35,t.height-35)*20;return[n,r]},$$=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)}),hm=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),E$=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Fk=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),V8=(e,t)=>E$(C$(hm(e),hm(t))),xv=(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)},H8=e=>vo(e.width)&&vo(e.height)&&vo(e.x)&&vo(e.y),vo=e=>!isNaN(e)&&isFinite(e),Gs=Symbol.for("internals"),A$=["Enter"," ","Escape"],G8=(e,t)=>{},K8=e=>"nativeEvent"in e;function bv(e){var i,o;const t=K8(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 T$=e=>"clientX"in e,ac=(e,t)=>{var o,c;const n=T$(e),r=n?e.clientX:(o=e.touches)==null?void 0:o[0].clientX,i=n?e.clientY:(c=e.touches)==null?void 0:c[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:i-((t==null?void 0:t.top)??0)}},hg=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0},Im=({id:e,path:t,labelX:n,labelY:r,label:i,labelStyle:o,labelShowBg:c,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&&vo(n)&&vo(r)?Ee.createElement(q8,{x:n,y:r,label:i,labelStyle:o,labelShowBg:c,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h}):null);Im.displayName="BaseEdge";function $h(e,t,n){return n===void 0?n:r=>{const i=t().edges.find(o=>o.id===e);i&&n(r,{...i})}}function M$({sourceX:e,sourceY:t,targetX:n,targetY:r}){const i=Math.abs(n-e)/2,o=n<e?n+i:n-i,c=Math.abs(r-t)/2,l=r<t?r+c:r-c;return[o,l,i,c]}function R$({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:i,sourceControlY:o,targetControlX:c,targetControlY:l}){const d=e*.125+i*.375+c*.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 xu;(function(e){e.Strict="strict",e.Loose="loose"})(xu||(xu={}));var ou;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(ou||(ou={}));var mm;(function(e){e.Partial="partial",e.Full="full"})(mm||(mm={}));var nc;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(nc||(nc={}));var _m;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(_m||(_m={}));var Ut;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(Ut||(Ut={}));function zk({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 L$({sourceX:e,sourceY:t,sourcePosition:n=Ut.Bottom,targetX:r,targetY:i,targetPosition:o=Ut.Top}){const[c,l]=zk({pos:n,x1:e,y1:t,x2:r,y2:i}),[d,h]=zk({pos:o,x1:r,y1:i,x2:e,y2:t}),[m,_,g,y]=R$({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:c,sourceControlY:l,targetControlX:d,targetControlY:h});return[`M${e},${t} C${c},${l} ${d},${h} ${r},${i}`,m,_,g,y]}const Tx=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:i=Ut.Bottom,targetPosition:o=Ut.Top,label:c,labelStyle:l,labelShowBg:d,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:_,style:g,markerEnd:y,markerStart:x,interactionWidth:k})=>{const[v,N,$]=L$({sourceX:e,sourceY:t,sourcePosition:i,targetX:n,targetY:r,targetPosition:o});return Ee.createElement(Im,{path:v,labelX:N,labelY:$,label:c,labelStyle:l,labelShowBg:d,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:_,style:g,markerEnd:y,markerStart:x,interactionWidth:k})});Tx.displayName="SimpleBezierEdge";const Bk={[Ut.Left]:{x:-1,y:0},[Ut.Right]:{x:1,y:0},[Ut.Top]:{x:0,y:-1},[Ut.Bottom]:{x:0,y:1}},J8=({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},Uk=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function Y8({source:e,sourcePosition:t=Ut.Bottom,target:n,targetPosition:r=Ut.Top,center:i,offset:o}){const c=Bk[t],l=Bk[r],d={x:e.x+c.x*o,y:e.y+c.y*o},h={x:n.x+l.x*o,y:n.y+l.y*o},m=J8({source:d,sourcePosition:t,target:h}),_=m.x!==0?"x":"y",g=m[_];let y=[],x,k;const v={x:0,y:0},N={x:0,y:0},[$,E,S,P]=M$({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(c[_]*l[_]===-1){x=i.x||$,k=i.y||E;const R=[{x,y:d.y},{x,y:h.y}],I=[{x:d.x,y:k},{x:h.x,y:k}];c[_]===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=c.x===g?I:R:y=c.y===g?R:I,t===r){const M=Math.abs(e[_]-n[_]);if(M<=o){const A=Math.min(o-1,o-M);c[_]===g?v[_]=(d[_]>e[_]?-1:1)*A:N[_]=(h[_]>n[_]?-1:1)*A}}if(t!==r){const M=_==="x"?"y":"x",A=c[_]===l[M],O=d[M]>h[M],L=d[M]<h[M];(c[_]===1&&(!A&&O||A&&L)||c[_]!==1&&(!A&&L||A&&O))&&(y=_==="x"?R:I)}const W={x:d.x+v.x,y:d.y+v.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)),V=Math.max(Math.abs(W.y-y[0].y),Math.abs(G.y-y[0].y));K>=V?(x=(W.x+G.x)/2,k=y[0].y):(x=y[0].x,k=(W.y+G.y)/2)}return[[e,{x:d.x+v.x,y:d.y+v.y},...y,{x:h.x+N.x,y:h.y+N.y},n],x,k,S,P]}function X8(e,t,n,r){const i=Math.min(Uk(e,t)/2,Uk(t,n)/2,r),{x:o,y:c}=t;if(e.x===o&&o===n.x||e.y===c&&c===n.y)return`L${o} ${c}`;if(e.y===c){const h=e.x<n.x?-1:1,m=e.y<n.y?1:-1;return`L ${o+i*h},${c}Q ${o},${c} ${o},${c+i*m}`}const l=e.x<n.x?1:-1,d=e.y<n.y?-1:1;return`L ${o},${c+i*d}Q ${o},${c} ${o+i*l},${c}`}function kv({sourceX:e,sourceY:t,sourcePosition:n=Ut.Bottom,targetX:r,targetY:i,targetPosition:o=Ut.Top,borderRadius:c=5,centerX:l,centerY:d,offset:h=20}){const[m,_,g,y,x]=Y8({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:i},targetPosition:o,center:{x:l,y:d},offset:h});return[m.reduce((v,N,$)=>{let E="";return $>0&&$<m.length-1?E=X8(m[$-1],N,m[$+1],c):E=`${$===0?"M":"L"}${N.x} ${N.y}`,v+=E,v},""),_,g,y,x]}const Vg=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:i,labelStyle:o,labelShowBg:c,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,sourcePosition:_=Ut.Bottom,targetPosition:g=Ut.Top,markerEnd:y,markerStart:x,pathOptions:k,interactionWidth:v})=>{const[N,$,E]=kv({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(Im,{path:N,labelX:$,labelY:E,label:i,labelStyle:o,labelShowBg:c,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,markerEnd:y,markerStart:x,interactionWidth:v})});Vg.displayName="SmoothStepEdge";const Mx=p.memo(e=>{var t;return Ee.createElement(Vg,{...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])})});Mx.displayName="StepEdge";function Z8({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[i,o,c,l]=M$({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,i,o,c,l]}const Rx=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:i,labelStyle:o,labelShowBg:c,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,markerEnd:_,markerStart:g,interactionWidth:y})=>{const[x,k,v]=Z8({sourceX:e,sourceY:t,targetX:n,targetY:r});return Ee.createElement(Im,{path:x,labelX:k,labelY:v,label:i,labelStyle:o,labelShowBg:c,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,markerEnd:_,markerStart:g,interactionWidth:y})});Rx.displayName="StraightEdge";function mp(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Wk({pos:e,x1:t,y1:n,x2:r,y2:i,c:o}){switch(e){case Ut.Left:return[t-mp(t-r,o),n];case Ut.Right:return[t+mp(r-t,o),n];case Ut.Top:return[t,n-mp(n-i,o)];case Ut.Bottom:return[t,n+mp(i-n,o)]}}function I$({sourceX:e,sourceY:t,sourcePosition:n=Ut.Bottom,targetX:r,targetY:i,targetPosition:o=Ut.Top,curvature:c=.25}){const[l,d]=Wk({pos:n,x1:e,y1:t,x2:r,y2:i,c}),[h,m]=Wk({pos:o,x1:r,y1:i,x2:e,y2:t,c}),[_,g,y,x]=R$({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,x]}const mg=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:i=Ut.Bottom,targetPosition:o=Ut.Top,label:c,labelStyle:l,labelShowBg:d,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:_,style:g,markerEnd:y,markerStart:x,pathOptions:k,interactionWidth:v})=>{const[N,$,E]=I$({sourceX:e,sourceY:t,sourcePosition:i,targetX:n,targetY:r,targetPosition:o,curvature:k==null?void 0:k.curvature});return Ee.createElement(Im,{path:N,labelX:$,labelY:E,label:c,labelStyle:l,labelShowBg:d,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:_,style:g,markerEnd:y,markerStart:x,interactionWidth:v})});mg.displayName="BezierEdge";const Lx=p.createContext(null),Q8=Lx.Provider;Lx.Consumer;const ez=()=>p.useContext(Lx),tz=e=>"id"in e&&"source"in e&&"target"in e,nz=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`reactflow__edge-${e}${t||""}-${n}${r||""}`,jv=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`,sz=(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)),rz=(e,t)=>{if(!e.source||!e.target)return t;let n;return tz(e)?n={...e}:n={...e,id:nz(e)},sz(n,t)?t:t.concat(n)},Sv=({x:e,y:t},[n,r,i],o,[c,l])=>{const d={x:(e-n)/i,y:(t-r)/i};return o?{x:c*Math.round(d.x/c),y:l*Math.round(d.y/l)}:d},O$=({x:e,y:t},[n,r,i])=>({x:e*i+n,y:t*i+r}),du=(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}},Hg=(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:c}=du(i,t).positionAbsolute;return C$(r,hm({x:o,y:c,width:i.width||0,height:i.height||0}))},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return E$(n)},P$=(e,t,[n,r,i]=[0,0,1],o=!1,c=!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:x=!1}=m;if(c&&!y||x)return!1;const{positionAbsolute:k}=du(m,l),v={x:k.x,y:k.y,width:_||0,height:g||0},N=xv(d,v),$=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},D$=(e,t)=>{const n=e.map(r=>r.id);return t.filter(r=>n.includes(r.source)||n.includes(r.target))},F$=(e,t,n,r,i,o=.1)=>{const c=t/(e.width*(1+o)),l=n/(e.height*(1+o)),d=Math.min(c,l),h=nf(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}},nu=(e,t=0)=>e.transition().duration(t);function qk(e,t,n,r){return(t[n]||[]).reduce((i,o)=>{var c,l;return`${e.id}-${o.id}-${n}`!==r&&i.push({id:o.id||null,type:n,nodeId:e.id,x:(((c=e.positionAbsolute)==null?void 0:c.x)??0)+o.x+o.width/2,y:(((l=e.positionAbsolute)==null?void 0:l.y)??0)+o.y+o.height/2}),i},[])}function iz(e,t,n,r,i,o){const{x:c,y:l}=ac(e),h=t.elementsFromPoint(c,l).find(x=>x.classList.contains("react-flow__handle"));if(h){const x=h.getAttribute("data-nodeid");if(x){const k=Ix(void 0,h),v=h.getAttribute("data-handleid"),N=o({nodeId:x,id:v,type:k});if(N){const $=i.find(E=>E.nodeId===x&&E.type===k&&E.id===v);return{handle:{id:v,type:k,nodeId:x,x:($==null?void 0:$.x)||n.x,y:($==null?void 0:$.y)||n.y},validHandleResult:N}}}}let m=[],_=1/0;if(i.forEach(x=>{const k=Math.sqrt((x.x-n.x)**2+(x.y-n.y)**2);if(k<=r){const v=o(x);k<=_&&(k<_?m=[{handle:x,validHandleResult:v}]:k===_&&m.push({handle:x,validHandleResult:v}),_=k)}}),!m.length)return{handle:null,validHandleResult:z$()};if(m.length===1)return m[0];const g=m.some(({validHandleResult:x})=>x.isValid),y=m.some(({handle:x})=>x.type==="target");return m.find(({handle:x,validHandleResult:k})=>y?x.type==="target":g?k.isValid:!0)||m[0]}const oz={source:null,target:null,sourceHandle:null,targetHandle:null},z$=()=>({handleDomNode:null,isValid:!1,connection:oz,endHandle:null});function B$(e,t,n,r,i,o,c){const l=i==="target",d=c.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={...z$(),handleDomNode:d};if(d){const m=Ix(void 0,d),_=d.getAttribute("data-nodeid"),g=d.getAttribute("data-handleid"),y=d.classList.contains("connectable"),x=d.classList.contains("connectableend"),k={source:l?_:n,sourceHandle:l?g:r,target:l?n:_,targetHandle:l?r:g};h.connection=k,y&&x&&(t===xu.Strict?l&&m==="source"||!l&&m==="target":_!==n||g!==r)&&(h.endHandle={nodeId:_,handleId:g,type:m},h.isValid=o(k))}return h}function az({nodes:e,nodeId:t,handleId:n,handleType:r}){return e.reduce((i,o)=>{if(o[Gs]){const{handleBounds:c}=o[Gs];let l=[],d=[];c&&(l=qk(o,c,"source",`${t}-${n}-${r}`),d=qk(o,c,"target",`${t}-${n}-${r}`)),i.push(...l,...d)}return i},[])}function Ix(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function aw(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function lz(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function U$({event:e,handleId:t,nodeId:n,onConnect:r,isTarget:i,getState:o,setState:c,isValidConnection:l,edgeUpdaterType:d,onEdgeUpdateEnd:h}){const m=$$(e.target),{connectionMode:_,domNode:g,autoPanOnConnect:y,connectionRadius:x,onConnectStart:k,panBy:v,getNodes:N,cancelConnection:$}=o();let E=0,S;const{x:P,y:D}=ac(e),R=m==null?void 0:m.elementFromPoint(P,D),I=Ix(d,R),W=g==null?void 0:g.getBoundingClientRect();if(!W||!I)return;let G,K=ac(e,W),V=!1,M=null,A=!1,O=null;const L=az({nodes:N(),nodeId:n,handleId:t,handleType:I}),H=()=>{if(!y)return;const[te,z]=N$(K,W);v({x:te,y:z}),E=requestAnimationFrame(H)};c({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=ac(te,W);const{handle:ne,validHandleResult:se}=iz(te,m,Sv(K,z,!1,[1,1]),x,L,de=>B$(de,_,n,t,i?"target":"source",l,m));if(S=ne,V||(H(),V=!0),O=se.handleDomNode,M=se.connection,A=se.isValid,c({connectionPosition:S&&A?O$({x:S.x,y:S.y},z):K,connectionStatus:lz(!!S,A),connectionEndHandle:se.endHandle}),!S&&!A&&!O)return aw(G);M.source!==M.target&&O&&(aw(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)),aw(G),$(),cancelAnimationFrame(E),V=!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 Vk=()=>!0,cz=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),uz=(e,t,n)=>r=>{const{connectionStartHandle:i,connectionEndHandle:o,connectionClickStartHandle:c}=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:(c==null?void 0:c.nodeId)===e&&(c==null?void 0:c.handleId)===t&&(c==null?void 0:c.type)===n}},W$=p.forwardRef(({type:e="source",position:t=Ut.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:i=!0,isConnectableEnd:o=!0,id:c,onConnect:l,children:d,className:h,onMouseDown:m,onTouchStart:_,...g},y)=>{var W,G;const x=c||null,k=e==="target",v=tr(),N=ez(),{connectOnClick:$,noPanClassName:E}=ms(cz,mr),{connecting:S,clickConnecting:P}=ms(uz(N,x,e),mr);N||(G=(W=v.getState()).onError)==null||G.call(W,"010",cl.error010());const D=K=>{const{defaultEdgeOptions:V,onConnect:M,hasDefaultEdges:A}=v.getState(),O={...V,...K};if(A){const{edges:L,setEdges:H}=v.getState();H(rz(O,L))}M==null||M(O),l==null||l(O)},R=K=>{if(!N)return;const V=T$(K);i&&(V&&K.button===0||!V)&&U$({event:K,handleId:x,nodeId:N,onConnect:D,isTarget:k,getState:v.getState,setState:v.setState,isValidConnection:n||v.getState().isValidConnection||Vk}),V?m==null||m(K):_==null||_(K)},I=K=>{const{onClickConnectStart:V,onClickConnectEnd:M,connectionClickStartHandle:A,connectionMode:O,isValidConnection:L}=v.getState();if(!N||!A&&!i)return;if(!A){V==null||V(K,{nodeId:N,handleId:x,handleType:e}),v.setState({connectionClickStartHandle:{nodeId:N,type:e,handleId:x}});return}const H=$$(K.target),J=n||L||Vk,{connection:U,isValid:te}=B$({nodeId:N,id:x,type:e},O,A.nodeId,A.handleId||null,A.type,J,H);te&&D(U),M==null||M(K),v.setState({connectionClickStartHandle:null})};return Ee.createElement("div",{"data-handleid":x,"data-nodeid":N,"data-handlepos":t,"data-id":`${N}-${x}-${e}`,className:Er(["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)});W$.displayName="Handle";var _g=p.memo(W$);const q$=({data:e,isConnectable:t,targetPosition:n=Ut.Top,sourcePosition:r=Ut.Bottom})=>Ee.createElement(Ee.Fragment,null,Ee.createElement(_g,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,Ee.createElement(_g,{type:"source",position:r,isConnectable:t}));q$.displayName="DefaultNode";var Nv=p.memo(q$);const V$=({data:e,isConnectable:t,sourcePosition:n=Ut.Bottom})=>Ee.createElement(Ee.Fragment,null,e==null?void 0:e.label,Ee.createElement(_g,{type:"source",position:n,isConnectable:t}));V$.displayName="InputNode";var H$=p.memo(V$);const G$=({data:e,isConnectable:t,targetPosition:n=Ut.Top})=>Ee.createElement(Ee.Fragment,null,Ee.createElement(_g,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);G$.displayName="OutputNode";var K$=p.memo(G$);const Ox=()=>null;Ox.displayName="GroupNode";const dz=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),_p=e=>e.id;function fz(e,t){return mr(e.selectedNodes.map(_p),t.selectedNodes.map(_p))&&mr(e.selectedEdges.map(_p),t.selectedEdges.map(_p))}const J$=p.memo(({onSelectionChange:e})=>{const t=tr(),{selectedNodes:n,selectedEdges:r}=ms(dz,fz);return p.useEffect(()=>{const i={nodes:n,edges:r};e==null||e(i),t.getState().onSelectionChange.forEach(o=>o(i))},[n,r,e]),null});J$.displayName="SelectionListener";const hz=e=>!!e.onSelectionChange;function mz({onSelectionChange:e}){const t=ms(hz);return e||t?Ee.createElement(J$,{onSelectionChange:e}):null}const _z=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 jd(e,t){p.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function Nn(e,t,n){p.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const pz=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:i,onConnectStart:o,onConnectEnd:c,onClickConnectStart:l,onClickConnectEnd:d,nodesDraggable:h,nodesConnectable:m,nodesFocusable:_,edgesFocusable:g,edgesUpdatable:y,elevateNodesOnSelect:x,minZoom:k,maxZoom:v,nodeExtent:N,onNodesChange:$,onEdgesChange:E,elementsSelectable:S,connectionMode:P,snapGrid:D,snapToGrid:R,translateExtent:I,connectOnClick:W,defaultEdgeOptions:G,fitView:K,fitViewOptions:V,onNodesDelete:M,onEdgesDelete:A,onNodeDrag:O,onNodeDragStart:L,onNodeDragStop:H,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:Ve,setDefaultNodesAndEdges:mt,setMinZoom:nt,setMaxZoom:rt,setTranslateExtent:ze,setNodeExtent:He,reset:ct}=ms(_z,mr),Qe=tr();return p.useEffect(()=>{const Dt=r==null?void 0:r.map($e=>({...$e,...G}));return mt(n,Dt),()=>{ct()}},[]),Nn("defaultEdgeOptions",G,Qe.setState),Nn("connectionMode",P,Qe.setState),Nn("onConnect",i,Qe.setState),Nn("onConnectStart",o,Qe.setState),Nn("onConnectEnd",c,Qe.setState),Nn("onClickConnectStart",l,Qe.setState),Nn("onClickConnectEnd",d,Qe.setState),Nn("nodesDraggable",h,Qe.setState),Nn("nodesConnectable",m,Qe.setState),Nn("nodesFocusable",_,Qe.setState),Nn("edgesFocusable",g,Qe.setState),Nn("edgesUpdatable",y,Qe.setState),Nn("elementsSelectable",S,Qe.setState),Nn("elevateNodesOnSelect",x,Qe.setState),Nn("snapToGrid",R,Qe.setState),Nn("snapGrid",D,Qe.setState),Nn("onNodesChange",$,Qe.setState),Nn("onEdgesChange",E,Qe.setState),Nn("connectOnClick",W,Qe.setState),Nn("fitViewOnInit",K,Qe.setState),Nn("fitViewOnInitOptions",V,Qe.setState),Nn("onNodesDelete",M,Qe.setState),Nn("onEdgesDelete",A,Qe.setState),Nn("onNodeDrag",O,Qe.setState),Nn("onNodeDragStart",L,Qe.setState),Nn("onNodeDragStop",H,Qe.setState),Nn("onSelectionDrag",J,Qe.setState),Nn("onSelectionDragStart",U,Qe.setState),Nn("onSelectionDragStop",te,Qe.setState),Nn("noPanClassName",z,Qe.setState),Nn("nodeOrigin",ne,Qe.setState),Nn("rfId",se,Qe.setState),Nn("autoPanOnConnect",de,Qe.setState),Nn("autoPanOnNodeDrag",be,Qe.setState),Nn("onError",Me,Qe.setState),Nn("connectionRadius",je,Qe.setState),Nn("isValidConnection",ae,Qe.setState),Nn("nodeDragThreshold",xe,Qe.setState),jd(e,Ae),jd(t,Ve),jd(k,nt),jd(v,rt),jd(I,ze),jd(N,He),null},Hk={display:"none"},gz={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Y$="react-flow__node-desc",X$="react-flow__edge-desc",yz="react-flow__aria-live",wz=e=>e.ariaLiveMessage;function vz({rfId:e}){const t=ms(wz);return Ee.createElement("div",{id:`${yz}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:gz},t)}function xz({rfId:e,disableKeyboardA11y:t}){return Ee.createElement(Ee.Fragment,null,Ee.createElement("div",{id:`${Y$}-${e}`,style:Hk},"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:`${X$}-${e}`,style:Hk},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&Ee.createElement(vz,{rfId:e}))}var pm=(e=null,t={actInsideInputWithModifier:!0})=>{const[n,r]=p.useState(!1),i=p.useRef(!1),o=p.useRef(new Set([])),[c,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)&&bv(y))return!1;const k=Kk(y.code,l);o.current.add(y[k]),Gk(c,o.current,!1)&&(y.preventDefault(),r(!0))},_=y=>{if((!i.current||i.current&&!t.actInsideInputWithModifier)&&bv(y))return!1;const k=Kk(y.code,l);Gk(c,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 Gk(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(i=>t.has(i)))}function Kk(e,t){return t.includes(e)?"code":"key"}function Z$(e,t,n,r){var c,l;if(!e.parentNode)return n;const i=t.get(e.parentNode),o=du(i,r);return Z$(i,t,{x:(n.x??0)+o.x,y:(n.y??0)+o.y,z:(((c=i[Gs])==null?void 0:c.z)??0)>(n.z??0)?((l=i[Gs])==null?void 0:l.z)??0:n.z??0},r)}function Q$(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:c,z:l}=Z$(r,e,{...r.position,z:((i=r[Gs])==null?void 0:i.z)??0},t);r.positionAbsolute={x:o,y:c},r[Gs].z=l,n!=null&&n[r.id]&&(r[Gs].isParent=!0)}})}function lw(e,t,n,r){const i=new Map,o={},c=r?1e3:0;return e.forEach(l=>{var g;const d=(vo(l.zIndex)?l.zIndex:0)+(l.selected?c: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,Gs,{enumerable:!1,value:{handleBounds:_||(g=h==null?void 0:h[Gs])==null?void 0:g.handleBounds,z:d}}),i.set(l.id,m)}),Q$(i,n,o),i}function eC(e,t={}){const{getNodes:n,width:r,height:i,minZoom:o,maxZoom:c,d3Zoom:l,d3Selection:d,fitViewOnInitDone:h,fitViewOnInit:m,nodeOrigin:_}=e(),g=t.initial&&!h&&m;if(l&&d&&(g||!t.initial)){const x=n().filter(v=>{var $;const N=t.includeHiddenNodes?v.width&&v.height:!v.hidden;return($=t.nodes)!=null&&$.length?N&&t.nodes.some(E=>E.id===v.id):N}),k=x.every(v=>v.width&&v.height);if(x.length>0&&k){const v=Hg(x,_),{x:N,y:$,zoom:E}=F$(v,r,i,t.minZoom??o,t.maxZoom??c,t.padding??.1),S=sl.translate(N,$).scale(E);return typeof t.duration=="number"&&t.duration>0?l.transform(nu(d,t.duration),S):l.transform(d,S),!0}}return!1}function bz(e,t){return e.forEach(n=>{const r=t.get(n.id);r&&t.set(r.id,{...r,[Gs]:r[Gs],selected:n.selected})}),new Map(t)}function kz(e,t){return t.map(n=>{const r=e.find(i=>i.id===n.id);return r&&(n.selected=r.selected),n})}function pp({changedNodes:e,changedEdges:t,get:n,set:r}){const{nodeInternals:i,edges:o,onNodesChange:c,onEdgesChange:l,hasDefaultNodes:d,hasDefaultEdges:h}=n();e!=null&&e.length&&(d&&r({nodeInternals:bz(e,i)}),c==null||c(e)),t!=null&&t.length&&(h&&r({edges:kz(t,o)}),l==null||l(t))}const Sd=()=>{},jz={zoomIn:Sd,zoomOut:Sd,zoomTo:Sd,getZoom:()=>1,setViewport:Sd,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:Sd,fitBounds:Sd,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},Sz=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),Nz=()=>{const e=tr(),{d3Zoom:t,d3Selection:n}=ms(Sz,mr);return p.useMemo(()=>n&&t?{zoomIn:i=>t.scaleBy(nu(n,i==null?void 0:i.duration),1.2),zoomOut:i=>t.scaleBy(nu(n,i==null?void 0:i.duration),1/1.2),zoomTo:(i,o)=>t.scaleTo(nu(n,o==null?void 0:o.duration),i),getZoom:()=>e.getState().transform[2],setViewport:(i,o)=>{const[c,l,d]=e.getState().transform,h=sl.translate(i.x??c,i.y??l).scale(i.zoom??d);t.transform(nu(n,o==null?void 0:o.duration),h)},getViewport:()=>{const[i,o,c]=e.getState().transform;return{x:i,y:o,zoom:c}},fitView:i=>eC(e.getState,i),setCenter:(i,o,c)=>{const{width:l,height:d,maxZoom:h}=e.getState(),m=typeof(c==null?void 0:c.zoom)<"u"?c.zoom:h,_=l/2-i*m,g=d/2-o*m,y=sl.translate(_,g).scale(m);t.transform(nu(n,c==null?void 0:c.duration),y)},fitBounds:(i,o)=>{const{width:c,height:l,minZoom:d,maxZoom:h}=e.getState(),{x:m,y:_,zoom:g}=F$(i,c,l,d,h,(o==null?void 0:o.padding)??.1),y=sl.translate(m,_).scale(g);t.transform(nu(n,o==null?void 0:o.duration),y)},project:i=>{const{transform:o,snapToGrid:c,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"),Sv(i,o,c,l)},screenToFlowPosition:i=>{const{transform:o,snapToGrid:c,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 Sv(_,o,c,l)},flowToScreenPosition:i=>{const{transform:o,domNode:c}=e.getState();if(!c)return i;const{x:l,y:d}=c.getBoundingClientRect(),h=O$(i,o);return{x:h.x+l,y:h.y+d}},viewportInitialized:!0}:jz,[t,n])};function Px(){const e=Nz(),t=tr(),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(v=>({...v}))},[]),o=p.useCallback(k=>{const{edges:v=[]}=t.getState();return v.find(N=>N.id===k)},[]),c=p.useCallback(k=>{const{getNodes:v,setNodes:N,hasDefaultNodes:$,onNodesChange:E}=t.getState(),S=v(),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:v=[],setEdges:N,hasDefaultEdges:$,onEdgesChange:E}=t.getState(),S=typeof k=="function"?k(v):k;if($)N(S);else if(E){const P=S.length===0?v.map(D=>({type:"remove",id:D.id})):S.map(D=>({item:D,type:"reset"}));E(P)}},[]),d=p.useCallback(k=>{const v=Array.isArray(k)?k:[k],{getNodes:N,setNodes:$,hasDefaultNodes:E,onNodesChange:S}=t.getState();if(E){const D=[...N(),...v];$(D)}else if(S){const P=v.map(D=>({item:D,type:"add"}));S(P)}},[]),h=p.useCallback(k=>{const v=Array.isArray(k)?k:[k],{edges:N=[],setEdges:$,hasDefaultEdges:E,onEdgesChange:S}=t.getState();if(E)$([...N,...v]);else if(S){const P=v.map(D=>({item:D,type:"add"}));S(P)}},[]),m=p.useCallback(()=>{const{getNodes:k,edges:v=[],transform:N}=t.getState(),[$,E,S]=N;return{nodes:k().map(P=>({...P})),edges:v.map(P=>({...P})),viewport:{x:$,y:E,zoom:S}}},[]),_=p.useCallback(({nodes:k,edges:v})=>{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=(v||[]).map(O=>O.id),V=$().reduce((O,L)=>{const H=!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)||H)&&O.push(L),O},[]),M=E.filter(O=>typeof O.deletable=="boolean"?O.deletable:!0),A=M.filter(O=>K.includes(O.id));if(V||A){const O=D$(V,M),L=[...A,...O],H=L.reduce((J,U)=>(J.includes(U.id)||J.push(U.id),J),[]);if((P||S)&&(P&&t.setState({edges:E.filter(J=>!H.includes(J.id))}),S&&(V.forEach(J=>{N.delete(J.id)}),t.setState({nodeInternals:new Map(N)}))),H.length>0&&(R==null||R(L),W&&W(H.map(J=>({id:J,type:"remove"})))),V.length>0&&(D==null||D(V),I)){const J=V.map(U=>({id:U.id,type:"remove"}));I(J)}}},[]),g=p.useCallback(k=>{const v=H8(k),N=v?null:t.getState().nodeInternals.get(k.id);return!v&&!N?[null,null,v]:[v?k:Fk(N),N,v]},[]),y=p.useCallback((k,v=!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=Fk(P),R=xv(D,$);return v&&R>0||R>=$.width*$.height}):[]},[]),x=p.useCallback((k,v,N=!0)=>{const[$]=g(k);if(!$)return!1;const E=xv($,v);return N&&E>0||E>=$.width*$.height},[]);return p.useMemo(()=>({...e,getNodes:n,getNode:r,getEdges:i,getEdge:o,setNodes:c,setEdges:l,addNodes:d,addEdges:h,toObject:m,deleteElements:_,getIntersectingNodes:y,isNodeIntersecting:x}),[e,n,r,i,o,c,l,d,h,m,_,y,x])}const $z={actInsideInputWithModifier:!1};var Cz=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=tr(),{deleteElements:r}=Px(),i=pm(e,$z),o=pm(t);p.useEffect(()=>{if(i){const{edges:c,getNodes:l}=n.getState(),d=l().filter(m=>m.selected),h=c.filter(m=>m.selected);r({nodes:d,edges:h}),n.setState({nodesSelectionActive:!1})}},[i]),p.useEffect(()=>{n.setState({multiSelectionActive:o})},[o])};function Ez(e){const t=tr();p.useEffect(()=>{let n;const r=()=>{var o,c;if(!e.current)return;const i=Ex(e.current);(i.height===0||i.width===0)&&((c=(o=t.getState()).onError)==null||c.call(o,"004",cl.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 Dx={position:"absolute",width:"100%",height:"100%",top:0,left:0},Az=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,gp=e=>({x:e.x,y:e.y,zoom:e.k}),Nd=(e,t)=>e.target.closest(`.${t}`),Jk=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Yk=e=>{const t=e.ctrlKey&&hg()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},Tz=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),Mz=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:r,zoomOnScroll:i=!0,zoomOnPinch:o=!0,panOnScroll:c=!1,panOnScrollSpeed:l=.5,panOnScrollMode:d=ou.Free,zoomOnDoubleClick:h=!0,elementsSelectable:m,panOnDrag:_=!0,defaultViewport:g,translateExtent:y,minZoom:x,maxZoom:k,zoomActivationKeyCode:v,preventScrolling:N=!0,children:$,noWheelClassName:E,noPanClassName:S})=>{const P=p.useRef(),D=tr(),R=p.useRef(!1),I=p.useRef(!1),W=p.useRef(null),G=p.useRef({x:0,y:0,zoom:0}),{d3Zoom:K,d3Selection:V,d3ZoomHandler:M,userSelectionActive:A}=ms(Tz,mr),O=pm(v),L=p.useRef(0),H=p.useRef(!1),J=p.useRef();return Ez(W),p.useEffect(()=>{if(W.current){const U=W.current.getBoundingClientRect(),te=j$().scaleExtent([x,k]).translateExtent(y),z=wo(W.current).call(te),ne=sl.translate(g.x,g.y).scale(nf(g.zoom,x,k)),se=[[0,0],[U.width,U.height]],de=te.constrain()(ne,se,y);te.transform(z,de),te.wheelDelta(Yk),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(()=>{V&&K&&(c&&!O&&!A?V.on("wheel.zoom",U=>{if(Nd(U,E))return!1;U.preventDefault(),U.stopImmediatePropagation();const te=V.property("__zoom").k||1,z=hg();if(U.ctrlKey&&o&&z){const xe=Vo(U),Ae=Yk(U),Ve=te*Math.pow(2,Ae);K.scaleTo(V,Ve,xe,U);return}const ne=U.deltaMode===1?20:1;let se=d===ou.Vertical?0:U.deltaX*ne,de=d===ou.Horizontal?0:U.deltaY*ne;!z&&U.shiftKey&&d!==ou.Vertical&&(se=U.deltaY*ne,de=0),K.translateBy(V,-(se/te)*l,-(de/te)*l,{internal:!0});const be=gp(V.property("__zoom")),{onViewportChangeStart:Me,onViewportChange:je,onViewportChangeEnd:ae}=D.getState();clearTimeout(J.current),H.current||(H.current=!0,t==null||t(U,be),Me==null||Me(be)),H.current&&(e==null||e(U,be),je==null||je(be),J.current=setTimeout(()=>{n==null||n(U,be),ae==null||ae(be),H.current=!1},150))},{passive:!1}):typeof M<"u"&&V.on("wheel.zoom",function(U,te){if(!N||Nd(U,E))return null;U.preventDefault(),M.call(this,U,te)},{passive:!1}))},[A,c,d,V,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=gp(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&&Jk(_,L.current??0)),(e||te)&&!((z=U.sourceEvent)!=null&&z.internal)){const ne=gp(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&&Jk(_,L.current??0)&&!I.current&&r(U.sourceEvent),I.current=!1,(n||te)&&Az(G.current,U.transform)){const z=gp(U.transform);G.current=z,clearTimeout(P.current),P.current=setTimeout(()=>{te==null||te(z),n==null||n(U.sourceEvent,z)},c?150:0)}})},[K,c,_,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"&&(Nd(U,"react-flow__node")||Nd(U,"react-flow__edge")))return!0;if(!_&&!te&&!c&&!h&&!o||A||!h&&U.type==="dblclick"||Nd(U,E)&&U.type==="wheel"||Nd(U,S)&&(U.type!=="wheel"||c&&U.type==="wheel"&&!O)||!o&&U.ctrlKey&&U.type==="wheel"||!te&&!c&&!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,c,h,_,m,O]),Ee.createElement("div",{className:"react-flow__renderer",ref:W,style:Dx},$)},Rz=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Lz(){const{userSelectionActive:e,userSelectionRect:t}=ms(Rz,mr);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 Xk(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 Iz(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 c={...i};for(const l of o)if(l)switch(l.type){case"select":{c.selected=l.selected;break}case"position":{typeof l.position<"u"&&(c.position=l.position),typeof l.positionAbsolute<"u"&&(c.positionAbsolute=l.positionAbsolute),typeof l.dragging<"u"&&(c.dragging=l.dragging),c.expandParent&&Xk(r,c);break}case"dimensions":{typeof l.dimensions<"u"&&(c.width=l.dimensions.width,c.height=l.dimensions.height),typeof l.updateStyle<"u"&&(c.style={...c.style||{},...l.dimensions}),typeof l.resizing=="boolean"&&(c.resizing=l.resizing),c.expandParent&&Xk(r,c);break}case"remove":return r}return r.push(c),r},n)}function Oz(e,t){return Iz(e,t)}const ec=(e,t)=>({id:e,type:"select",selected:t});function Dd(e,t){return e.reduce((n,r)=>{const i=t.includes(r.id);return!r.selected&&i?(r.selected=!0,n.push(ec(r.id,!0))):r.selected&&!i&&(r.selected=!1,n.push(ec(r.id,!1))),n},[])}const cw=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},Pz=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),tC=p.memo(({isSelecting:e,selectionMode:t=mm.Full,panOnDrag:n,onSelectionStart:r,onSelectionEnd:i,onPaneClick:o,onPaneContextMenu:c,onPaneScroll:l,onPaneMouseEnter:d,onPaneMouseMove:h,onPaneMouseLeave:m,children:_})=>{const g=p.useRef(null),y=tr(),x=p.useRef(0),k=p.useRef(0),v=p.useRef(),{userSelectionActive:N,elementsSelectable:$,dragging:E}=ms(Pz,mr),S=()=>{y.setState({userSelectionActive:!1,userSelectionRect:null}),x.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}c==null||c(M)},R=l?M=>l(M):void 0,I=M=>{const{resetSelectedElements:A,domNode:O}=y.getState();if(v.current=O==null?void 0:O.getBoundingClientRect(),!$||!e||M.button!==0||M.target!==g.current||!v.current)return;const{x:L,y:H}=ac(M,v.current);A(),y.setState({userSelectionRect:{width:0,height:0,startX:L,startY:H,x:L,y:H}}),r==null||r(M)},W=M=>{const{userSelectionRect:A,nodeInternals:O,edges:L,transform:H,onNodesChange:J,onEdgesChange:U,nodeOrigin:te,getNodes:z}=y.getState();if(!e||!v.current||!A)return;y.setState({userSelectionActive:!0,nodesSelectionActive:!1});const ne=ac(M,v.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=P$(O,be,H,t===mm.Partial,!0,te),ae=D$(je,L).map(Ae=>Ae.id),xe=je.map(Ae=>Ae.id);if(x.current!==xe.length){x.current=xe.length;const Ae=Dd(Me,xe);Ae.length&&(J==null||J(Ae))}if(k.current!==ae.length){k.current=ae.length;const Ae=Dd(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:x.current>0}),S(),i==null||i(M)},K=M=>{N&&(y.setState({nodesSelectionActive:x.current>0}),i==null||i(M)),S()},V=$&&(e||N);return Ee.createElement("div",{className:Er(["react-flow__pane",{dragging:E,selection:e}]),onClick:V?void 0:cw(P,g),onContextMenu:cw(D,g),onWheel:cw(R,g),onMouseEnter:V?void 0:d,onMouseDown:V?I:void 0,onMouseMove:V?W:h,onMouseUp:V?G:void 0,onMouseLeave:V?K:m,ref:g,style:Dx},_,Ee.createElement(Lz,null))});tC.displayName="Pane";function nC(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:nC(n,t):!1}function Zk(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 Dz(e,t,n,r){return Array.from(e.values()).filter(i=>(i.selected||i.id===r)&&(!i.parentNode||!nC(i,e))&&(i.draggable||t&&typeof i.draggable>"u")).map(i=>{var o,c;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-(((c=i.positionAbsolute)==null?void 0:c.y)??0)},delta:{x:0,y:0},extent:i.extent,parentNode:i.parentNode,width:i.width,height:i.height,expandParent:i.expandParent}})}function Fz(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function sC(e,t,n,r,i=[0,0],o){const c=Fz(e,e.extent||r);let l=c;if(e.extent==="parent"&&!e.expandParent)if(e.parentNode&&e.width&&e.height){const m=n.get(e.parentNode),{x:_,y:g}=du(m,i).positionAbsolute;l=m&&vo(_)&&vo(g)&&vo(m.width)&&vo(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",cl.error005()),l=c;else if(e.extent&&e.parentNode&&e.extent!=="parent"){const m=n.get(e.parentNode),{x:_,y:g}=du(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=du(m,i).positionAbsolute}const h=l&&l!=="parent"?Ax(t,l):t;return{position:{x:h.x-d.x,y:h.y-d.y},positionAbsolute:h}}function uw({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 Qk=(e,t,n,r)=>{const i=t.querySelectorAll(e);if(!i||!i.length)return null;const o=Array.from(i),c=t.getBoundingClientRect(),l={x:c.width*r[0],y:c.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-c.left-l.x)/n,y:(h.top-c.top-l.y)/n,...Ex(d)}})};function Ch(e,t,n){return n===void 0?n:r=>{const i=t().nodeInternals.get(e);i&&n(r,{...i})}}function $v({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:i,unselectNodesAndEdges:o,multiSelectionActive:c,nodeInternals:l,onError:d}=t.getState(),h=l.get(e);if(!h){d==null||d("012",cl.error012(e));return}t.setState({nodesSelectionActive:!1}),h.selected?(n||h.selected&&c)&&(o({nodes:[h],edges:[]}),requestAnimationFrame(()=>{var m;return(m=r==null?void 0:r.current)==null?void 0:m.blur()})):i([e])}function zz(){const e=tr();return p.useCallback(({sourceEvent:n})=>{const{transform:r,snapGrid:i,snapToGrid:o}=e.getState(),c=n.touches?n.touches[0].clientX:n.clientX,l=n.touches?n.touches[0].clientY:n.clientY,d={x:(c-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 dw(e){return(t,n,r)=>e==null?void 0:e(t,r)}function rC({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:i,isSelectable:o,selectNodesOnDrag:c}){const l=tr(),[d,h]=p.useState(!1),m=p.useRef([]),_=p.useRef({x:null,y:null}),g=p.useRef(0),y=p.useRef(null),x=p.useRef({x:0,y:0}),k=p.useRef(null),v=p.useRef(!1),N=p.useRef(!1),$=zz();return p.useEffect(()=>{if(e!=null&&e.current){const E=wo(e.current),S=({x:R,y:I})=>{const{nodeInternals:W,onNodeDrag:G,onSelectionDrag:K,updateNodePositions:V,nodeExtent:M,snapGrid:A,snapToGrid:O,nodeOrigin:L,onError:H}=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=Hg(m.current,L);U=hm(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=sC(z,ne,W,se,L,H);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;V(m.current,!0,!0),h(!0);const te=i?G:dw(K);if(te&&k.current){const[z,ne]=uw({nodeId:i,dragItems:m.current,nodeInternals:W});te(k.current,z,ne)}},P=()=>{if(!y.current)return;const[R,I]=N$(x.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:V,onSelectionDragStart:M}=l.getState();N.current=!0;const A=i?V:dw(M);(!c||!o)&&!W&&i&&((L=I.get(i))!=null&&L.selected||K()),i&&o&&c&&$v({id:i,store:l,nodeRef:e});const O=$(R);if(_.current=O,m.current=Dz(I,G,O,i),A&&m.current){const[H,J]=uw({nodeId:i,dragItems:m.current,nodeInternals:I});A(R.sourceEvent,H,J)}};if(t)E.on(".drag",null);else{const R=YF().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,x.current=ac(I.sourceEvent,y.current)}).on("drag",I=>{var V,M;const W=$(I),{autoPanOnNodeDrag:G,nodeDragThreshold:K}=l.getState();if(!v.current&&N.current&&G&&(v.current=!0,P()),!N.current){const A=W.xSnapped-(((V=_==null?void 0:_.current)==null?void 0:V.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,x.current=ac(I.sourceEvent,y.current),S(W))}).on("end",I=>{if(N.current&&(h(!1),v.current=!1,N.current=!1,cancelAnimationFrame(g.current),m.current)){const{updateNodePositions:W,nodeInternals:G,onNodeDragStop:K,onSelectionDragStop:V}=l.getState(),M=i?K:dw(V);if(W(m.current,!1,!1),M){const[A,O]=uw({nodeId:i,dragItems:m.current,nodeInternals:G});M(I.sourceEvent,A,O)}}}).filter(I=>{const W=I.target;return!I.button&&(!n||!Zk(W,`.${n}`,e))&&(!r||Zk(W,r,e))});return E.call(R),()=>{E.on(".drag",null)}}}},[e,t,n,r,o,l,i,c,$]),d}function iC(){const e=tr();return p.useCallback(n=>{const{nodeInternals:r,nodeExtent:i,updateNodePositions:o,getNodes:c,snapToGrid:l,snapGrid:d,onError:h,nodesDraggable:m}=e.getState(),_=c().filter($=>$.selected&&($.draggable||m&&typeof $.draggable>"u")),g=l?d[0]:5,y=l?d[1]:5,x=n.isShiftPressed?4:1,k=n.x*g*x,v=n.y*y*x,N=_.map($=>{if($.positionAbsolute){const E={x:$.positionAbsolute.x+k,y:$.positionAbsolute.y+v};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}=sC($,E,r,i,void 0,h);$.position=P,$.positionAbsolute=S}return $});o(N,!0,!1)},[])}const Hd={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var Eh=e=>{const t=({id:n,type:r,data:i,xPos:o,yPos:c,xPosOrigin:l,yPosOrigin:d,selected:h,onClick:m,onMouseEnter:_,onMouseMove:g,onMouseLeave:y,onContextMenu:x,onDoubleClick:k,style:v,className:N,isDraggable:$,isSelectable:E,isConnectable:S,isFocusable:P,selectNodesOnDrag:D,sourcePosition:R,targetPosition:I,hidden:W,resizeObserver:G,dragHandle:K,zIndex:V,isParent:M,noDragClassName:A,noPanClassName:O,initialized:L,disableKeyboardA11y:H,ariaLabel:J,rfId:U,hasHandleBounds:te})=>{const z=tr(),ne=p.useRef(null),se=p.useRef(R),de=p.useRef(I),be=p.useRef(r),Me=E||$||m||_||g||y,je=iC(),ae=Ch(n,z.getState,_),xe=Ch(n,z.getState,g),Ae=Ch(n,z.getState,y),Ve=Ch(n,z.getState,x),mt=Ch(n,z.getState,k),nt=He=>{const{nodeDragThreshold:ct}=z.getState();if(E&&(!D||!$||ct>0)&&$v({id:n,store:z,nodeRef:ne}),m){const Qe=z.getState().nodeInternals.get(n);Qe&&m(He,{...Qe})}},rt=He=>{if(!bv(He))if(A$.includes(He.key)&&E){const ct=He.key==="Escape";$v({id:n,store:z,unselect:ct,nodeRef:ne})}else!H&&$&&h&&Object.prototype.hasOwnProperty.call(Hd,He.key)&&(z.setState({ariaLiveMessage:`Moved selected node ${He.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~o}, y: ${~~c}`}),je({x:Hd[He.key].x,y:Hd[He.key].y,isShiftPressed:He.shiftKey}))};p.useEffect(()=>()=>{ne.current&&(G==null||G.unobserve(ne.current))},[]),p.useEffect(()=>{if(ne.current&&!W){const He=ne.current;(!L||!te)&&(G==null||G.unobserve(He),G==null||G.observe(He))}},[W,L,te]),p.useEffect(()=>{const He=be.current!==r,ct=se.current!==R,Qe=de.current!==I;ne.current&&(He||ct||Qe)&&(He&&(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=rC({nodeRef:ne,disabled:W||!$,noDragClassName:A,handleSelector:K,nodeId:n,isSelectable:E,selectNodesOnDrag:D});return W?null:Ee.createElement("div",{className:Er(["react-flow__node",`react-flow__node-${r}`,{[O]:$},N,{selected:h,selectable:E,parent:M,dragging:ze}]),ref:ne,style:{zIndex:V,transform:`translate(${l}px,${d}px)`,pointerEvents:Me?"all":"none",visibility:L?"visible":"hidden",...v},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:ae,onMouseMove:xe,onMouseLeave:Ae,onContextMenu:Ve,onClick:nt,onDoubleClick:mt,onKeyDown:P?rt:void 0,tabIndex:P?0:void 0,role:P?"button":void 0,"aria-describedby":H?void 0:`${Y$}-${U}`,"aria-label":J},Ee.createElement(Q8,{value:n},Ee.createElement(e,{id:n,data:i,type:r,xPos:o,yPos:c,selected:h,isConnectable:S,sourcePosition:R,targetPosition:I,dragging:ze,dragHandle:K,zIndex:V})))};return t.displayName="NodeWrapper",p.memo(t)};const Bz=e=>{const t=e.getNodes().filter(n=>n.selected);return{...Hg(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function Uz({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=tr(),{width:i,height:o,x:c,y:l,transformString:d,userSelectionActive:h}=ms(Bz,mr),m=iC(),_=p.useRef(null);if(p.useEffect(()=>{var x;n||(x=_.current)==null||x.focus({preventScroll:!0})},[n]),rC({nodeRef:_}),h||!i||!o)return null;const g=e?x=>{const k=r.getState().getNodes().filter(v=>v.selected);e(x,k)}:void 0,y=x=>{Object.prototype.hasOwnProperty.call(Hd,x.key)&&m({x:Hd[x.key].x,y:Hd[x.key].y,isShiftPressed:x.shiftKey})};return Ee.createElement("div",{className:Er(["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:c}}))}var Wz=p.memo(Uz);const qz=e=>e.nodesSelectionActive,oC=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:o,onPaneScroll:c,deleteKeyCode:l,onMove:d,onMoveStart:h,onMoveEnd:m,selectionKeyCode:_,selectionOnDrag:g,selectionMode:y,onSelectionStart:x,onSelectionEnd:k,multiSelectionKeyCode:v,panActivationKeyCode:N,zoomActivationKeyCode:$,elementsSelectable:E,zoomOnScroll:S,zoomOnPinch:P,panOnScroll:D,panOnScrollSpeed:R,panOnScrollMode:I,zoomOnDoubleClick:W,panOnDrag:G,defaultViewport:K,translateExtent:V,minZoom:M,maxZoom:A,preventScrolling:O,onSelectionContextMenu:L,noWheelClassName:H,noPanClassName:J,disableKeyboardA11y:U})=>{const te=ms(qz),z=pm(_),ne=pm(N),se=ne||G,de=ne||D,be=z||g&&se!==!0;return Cz({deleteKeyCode:l,multiSelectionKeyCode:v}),Ee.createElement(Mz,{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:V,minZoom:M,maxZoom:A,zoomActivationKeyCode:$,preventScrolling:O,noWheelClassName:H,noPanClassName:J},Ee.createElement(tC,{onSelectionStart:x,onSelectionEnd:k,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:o,onPaneScroll:c,panOnDrag:se,isSelecting:!!be,selectionMode:y},e,te&&Ee.createElement(Wz,{onSelectionContextMenu:L,noPanClassName:J,disableKeyboardA11y:U})))};oC.displayName="FlowRenderer";var Vz=p.memo(oC);function Hz(e){return ms(p.useCallback(n=>e?P$(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function Gz(e){const t={input:Eh(e.input||H$),default:Eh(e.default||Nv),output:Eh(e.output||K$),group:Eh(e.group||Ox)},n={},r=Object.keys(e).filter(i=>!["input","default","output","group"].includes(i)).reduce((i,o)=>(i[o]=Eh(e[o]||Nv),i),n);return{...t,...r}}const Kz=({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]},Jz=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),aC=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:i,updateNodeDimensions:o,onError:c}=ms(Jz,mr),l=Hz(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:Dx},l.map(m=>{var P,D,R;let _=m.type||"default";e.nodeTypes[_]||(c==null||c("003",cl.error003(_)),_="default");const g=e.nodeTypes[_]||e.nodeTypes.default,y=!!(m.draggable||t&&typeof m.draggable>"u"),x=!!(m.selectable||i&&typeof m.selectable>"u"),k=!!(m.connectable||n&&typeof m.connectable>"u"),v=!!(m.focusable||r&&typeof m.focusable>"u"),N=e.nodeExtent?Ax(m.positionAbsolute,e.nodeExtent):m.positionAbsolute,$=(N==null?void 0:N.x)??0,E=(N==null?void 0:N.y)??0,S=Kz({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:x,isConnectable:k,isFocusable:v,resizeObserver:h,dragHandle:m.dragHandle,zIndex:((P=m[Gs])==null?void 0:P.z)??0,isParent:!!((D=m[Gs])!=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[Gs])!=null&&R.handleBounds)})}))};aC.displayName="NodeRenderer";var Yz=p.memo(aC);const Xz=(e,t,n)=>n===Ut.Left?e-t:n===Ut.Right?e+t:e,Zz=(e,t,n)=>n===Ut.Top?e-t:n===Ut.Bottom?e+t:e,ej="react-flow__edgeupdater",tj=({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:i,onMouseEnter:o,onMouseOut:c,type:l})=>Ee.createElement("circle",{onMouseDown:i,onMouseEnter:o,onMouseOut:c,className:Er([ej,`${ej}-${l}`]),cx:Xz(t,r,e),cy:Zz(n,r,e),r,stroke:"transparent",fill:"transparent"}),Qz=()=>!0;var $d=e=>{const t=({id:n,className:r,type:i,data:o,onClick:c,onEdgeDoubleClick:l,selected:d,animated:h,label:m,labelStyle:_,labelShowBg:g,labelBgStyle:y,labelBgPadding:x,labelBgBorderRadius:k,style:v,source:N,target:$,sourceX:E,sourceY:S,targetX:P,targetY:D,sourcePosition:R,targetPosition:I,elementsSelectable:W,hidden:G,sourceHandleId:K,targetHandleId:V,onContextMenu:M,onMouseEnter:A,onMouseMove:O,onMouseLeave:L,edgeUpdaterRadius:H,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,Ve]=p.useState(!1),[mt,nt]=p.useState(!1),rt=tr(),ze=p.useMemo(()=>`url('#${jv(ne,se)}')`,[ne,se]),He=p.useMemo(()=>`url('#${jv(z,se)}')`,[z,se]);if(G)return null;const ct=_t=>{var Rt;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]}),(Rt=xe.current)==null||Rt.blur()):bt([n])),c&&c(_t,Ot))},Qe=$h(n,rt.getState,l),Dt=$h(n,rt.getState,M),$e=$h(n,rt.getState,A),Le=$h(n,rt.getState,O),ce=$h(n,rt.getState,L),Q=(_t,It)=>{if(_t.button!==0)return;const{edges:bt,isValidConnection:St}=rt.getState(),ut=It?$:N,Ot=(It?V:K)||null,Rt=It?"target":"source",mn=St||Qz,wn=It,On=bt.find(ge=>ge.id===n);nt(!0),U==null||U(_t,On,Rt);const Ks=ge=>{nt(!1),te==null||te(ge,On,Rt)};U$({event:_t,handleId:Ot,nodeId:ut,onConnect:ge=>J==null?void 0:J(On,ge),isTarget:wn,getState:rt.getState,setState:rt.setState,isValidConnection:mn,edgeUpdaterType:Rt,onEdgeUpdateEnd:Ks})},_e=_t=>Q(_t,!0),le=_t=>Q(_t,!1),Se=()=>Ve(!0),pe=()=>Ve(!1),dt=!W&&!c,yt=_t=>{var It;if(A$.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(Rt=>Rt.id===n)]})):St([n])}};return Ee.createElement("g",{className:Er(["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?`${X$}-${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:x,labelBgBorderRadius:k,data:o,style:v,sourceX:E,sourceY:S,targetX:P,targetY:D,sourcePosition:R,targetPosition:I,sourceHandleId:K,targetHandleId:V,markerStart:ze,markerEnd:He,pathOptions:je,interactionWidth:ae}),Me&&Ee.createElement(Ee.Fragment,null,(Me==="source"||Me===!0)&&Ee.createElement(tj,{position:R,centerX:E,centerY:S,radius:H,onMouseDown:_e,onMouseEnter:Se,onMouseOut:pe,type:"source"}),(Me==="target"||Me===!0)&&Ee.createElement(tj,{position:I,centerX:P,centerY:D,radius:H,onMouseDown:le,onMouseEnter:Se,onMouseOut:pe,type:"target"})))};return t.displayName="EdgeWrapper",p.memo(t)};function eB(e){const t={default:$d(e.default||mg),straight:$d(e.bezier||Rx),step:$d(e.step||Mx),smoothstep:$d(e.step||Vg),simplebezier:$d(e.simplebezier||Tx)},n={},r=Object.keys(e).filter(i=>!["default","bezier"].includes(i)).reduce((i,o)=>(i[o]=$d(e[o]||mg),i),n);return{...t,...r}}function nj(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,c=(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+c/2};case Ut.Bottom:return{x:r+o/2,y:i+c};case Ut.Left:return{x:r,y:i+c/2}}}function sj(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const tB=(e,t,n,r,i,o)=>{const c=nj(n,e,t),l=nj(o,r,i);return{sourceX:c.x,sourceY:c.y,targetX:l.x,targetY:l.y}};function nB({sourcePos:e,targetPos:t,sourceWidth:n,sourceHeight:r,targetWidth:i,targetHeight:o,width:c,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=hm({x:(0-d[0])/d[2],y:(0-d[1])/d[2],width:c/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 rj(e){var r,i,o,c,l;const t=((r=e==null?void 0:e[Gs])==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:((c=e==null?void 0:e.positionAbsolute)==null?void 0:c.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 sB=[{level:0,isMaxLevel:!0,edges:[]}];function rB(e,t,n=!1){let r=-1;const i=e.reduce((c,l)=>{var m,_;const d=vo(l.zIndex);let h=d?l.zIndex:0;if(n){const g=t.get(l.target),y=t.get(l.source),x=l.selected||(g==null?void 0:g.selected)||(y==null?void 0:y.selected),k=Math.max(((m=y==null?void 0:y[Gs])==null?void 0:m.z)||0,((_=g==null?void 0:g[Gs])==null?void 0:_.z)||0,1e3);h=(d?l.zIndex:0)+(x?k:0)}return c[h]?c[h].push(l):c[h]=[l],r=h>r?h:r,c},{}),o=Object.entries(i).map(([c,l])=>{const d=+c;return{edges:l,level:d,isMaxLevel:d===r}});return o.length===0?sB:o}function iB(e,t,n){const r=ms(p.useCallback(i=>e?i.edges.filter(o=>{const c=t.get(o.source),l=t.get(o.target);return(c==null?void 0:c.width)&&(c==null?void 0:c.height)&&(l==null?void 0:l.width)&&(l==null?void 0:l.height)&&nB({sourcePos:c.positionAbsolute||{x:0,y:0},targetPos:l.positionAbsolute||{x:0,y:0},sourceWidth:c.width,sourceHeight:c.height,targetWidth:l.width,targetHeight:l.height,width:i.width,height:i.height,transform:i.transform})}):i.edges,[e,t]));return rB(r,t,n)}const oB=({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"}),aB=({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"}),ij={[_m.Arrow]:oB,[_m.ArrowClosed]:aB};function lB(e){const t=tr();return p.useMemo(()=>{var i,o;return Object.prototype.hasOwnProperty.call(ij,e)?ij[e]:((o=(i=t.getState()).onError)==null||o.call(i,"009",cl.error009(e)),null)},[e])}const cB=({id:e,type:t,color:n,width:r=12.5,height:i=12.5,markerUnits:o="strokeWidth",strokeWidth:c,orient:l="auto-start-reverse"})=>{const d=lB(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:c})):null},uB=({defaultColor:e,rfId:t})=>n=>{const r=[];return n.edges.reduce((i,o)=>([o.markerStart,o.markerEnd].forEach(c=>{if(c&&typeof c=="object"){const l=jv(c,t);r.includes(l)||(i.push({id:l,color:c.color||e,...c}),r.push(l))}}),i),[]).sort((i,o)=>i.id.localeCompare(o.id))},lC=({defaultColor:e,rfId:t})=>{const n=ms(p.useCallback(uB({defaultColor:e,rfId:t}),[e,t]),(r,i)=>!(r.length!==i.length||r.some((o,c)=>o.id!==i[c].id)));return Ee.createElement("defs",null,n.map(r=>Ee.createElement(cB,{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})))};lC.displayName="MarkerDefinitions";var dB=p.memo(lC);const fB=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}),cC=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:r,edgeTypes:i,noPanClassName:o,onEdgeUpdate:c,onEdgeContextMenu:l,onEdgeMouseEnter:d,onEdgeMouseMove:h,onEdgeMouseLeave:m,onEdgeClick:_,edgeUpdaterRadius:g,onEdgeDoubleClick:y,onEdgeUpdateStart:x,onEdgeUpdateEnd:k,children:v})=>{const{edgesFocusable:N,edgesUpdatable:$,elementsSelectable:E,width:S,height:P,connectionMode:D,nodeInternals:R,onError:I}=ms(fB,mr),W=iB(t,R,n);return S?Ee.createElement(Ee.Fragment,null,W.map(({level:G,edges:K,isMaxLevel:V})=>Ee.createElement("svg",{key:G,style:{zIndex:G},width:S,height:P,className:"react-flow__edges react-flow__container"},V&&Ee.createElement(dB,{defaultColor:e,rfId:r}),Ee.createElement("g",null,K.map(M=>{const[A,O,L]=rj(R.get(M.source)),[H,J,U]=rj(R.get(M.target));if(!L||!U)return null;let te=M.type||"default";i[te]||(I==null||I("011",cl.error011(te)),te="default");const z=i[te]||i.default,ne=D===xu.Strict?J.target:(J.target??[]).concat(J.source??[]),se=sj(O.source,M.sourceHandle),de=sj(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 c<"u"&&(M.updatable||$&&typeof M.updatable>"u");if(!se||!de)return I==null||I("008",cl.error008(se,M)),null;const{sourceX:xe,sourceY:Ae,targetX:Ve,targetY:mt}=tB(A,se,be,H,de,Me);return Ee.createElement(z,{key:M.id,id:M.id,className:Er([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:Ve,targetY:mt,sourcePosition:be,targetPosition:Me,elementsSelectable:E,onEdgeUpdate:c,onContextMenu:l,onMouseEnter:d,onMouseMove:h,onMouseLeave:m,onClick:_,edgeUpdaterRadius:g,onEdgeDoubleClick:y,onEdgeUpdateStart:x,onEdgeUpdateEnd:k,rfId:r,ariaLabel:M.ariaLabel,isFocusable:je,isUpdatable:ae,pathOptions:"pathOptions"in M?M.pathOptions:void 0,interactionWidth:M.interactionWidth})})))),v):null};cC.displayName="EdgeRenderer";var hB=p.memo(cC);const mB=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function _B({children:e}){const t=ms(mB);return Ee.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function pB(e){const t=Px(),n=p.useRef(!1);p.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const gB={[Ut.Left]:Ut.Right,[Ut.Right]:Ut.Left,[Ut.Top]:Ut.Bottom,[Ut.Bottom]:Ut.Top},uC=({nodeId:e,handleType:t,style:n,type:r=nc.Bezier,CustomComponent:i,connectionStatus:o})=>{var D,R,I;const{fromNode:c,handleId:l,toX:d,toY:h,connectionMode:m}=ms(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]),mr),_=(D=c==null?void 0:c[Gs])==null?void 0:D.handleBounds;let g=_==null?void 0:_[t];if(m===xu.Loose&&(g=g||(_==null?void 0:_[t==="source"?"target":"source"])),!c||!g)return null;const y=l?g.find(W=>W.id===l):g[0],x=y?y.x+y.width/2:(c.width??0)/2,k=y?y.y+y.height/2:c.height??0,v=(((R=c.positionAbsolute)==null?void 0:R.x)??0)+x,N=(((I=c.positionAbsolute)==null?void 0:I.y)??0)+k,$=y==null?void 0:y.position,E=$?gB[$]:null;if(!$||!E)return null;if(i)return Ee.createElement(i,{connectionLineType:r,connectionLineStyle:n,fromNode:c,fromHandle:y,fromX:v,fromY:N,toX:d,toY:h,fromPosition:$,toPosition:E,connectionStatus:o});let S="";const P={sourceX:v,sourceY:N,sourcePosition:$,targetX:d,targetY:h,targetPosition:E};return r===nc.Bezier?[S]=I$(P):r===nc.Step?[S]=kv({...P,borderRadius:0}):r===nc.SmoothStep?[S]=kv(P):r===nc.SimpleBezier?[S]=L$(P):S=`M${v},${N} ${d},${h}`,Ee.createElement("path",{d:S,fill:"none",className:"react-flow__connection-path",style:n})};uC.displayName="ConnectionLine";const yB=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function wB({containerStyle:e,style:t,type:n,component:r}){const{nodeId:i,handleType:o,nodesConnectable:c,width:l,height:d,connectionStatus:h}=ms(yB,mr);return!(i&&o&&l&&c)?null:Ee.createElement("svg",{style:e,width:l,height:d,className:"react-flow__edges react-flow__connectionline react-flow__container"},Ee.createElement("g",{className:Er(["react-flow__connection",h])},Ee.createElement(uC,{nodeId:i,handleType:o,style:t,type:n,CustomComponent:r,connectionStatus:h})))}function oj(e,t){return p.useRef(null),tr(),p.useMemo(()=>t(e),[e])}const dC=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:r,onMoveEnd:i,onInit:o,onNodeClick:c,onEdgeClick:l,onNodeDoubleClick:d,onEdgeDoubleClick:h,onNodeMouseEnter:m,onNodeMouseMove:_,onNodeMouseLeave:g,onNodeContextMenu:y,onSelectionContextMenu:x,onSelectionStart:k,onSelectionEnd:v,connectionLineType:N,connectionLineStyle:$,connectionLineComponent:E,connectionLineContainerStyle:S,selectionKeyCode:P,selectionOnDrag:D,selectionMode:R,multiSelectionKeyCode:I,panActivationKeyCode:W,zoomActivationKeyCode:G,deleteKeyCode:K,onlyRenderVisibleElements:V,elementsSelectable:M,selectNodesOnDrag:A,defaultViewport:O,translateExtent:L,minZoom:H,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:Ve,onPaneScroll:mt,onPaneContextMenu:nt,onEdgeUpdate:rt,onEdgeContextMenu:ze,onEdgeMouseEnter:He,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=oj(e,Gz),It=oj(t,eB);return pB(o),Ee.createElement(Vz,{onPaneClick:ae,onPaneMouseEnter:xe,onPaneMouseMove:Ae,onPaneMouseLeave:Ve,onPaneContextMenu:nt,onPaneScroll:mt,deleteKeyCode:K,selectionKeyCode:P,selectionOnDrag:D,selectionMode:R,onSelectionStart:k,onSelectionEnd:v,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:H,maxZoom:J,onSelectionContextMenu:x,preventScrolling:U,noDragClassName:ce,noWheelClassName:Q,noPanClassName:_e,disableKeyboardA11y:Se},Ee.createElement(_B,null,Ee.createElement(hB,{edgeTypes:It,onEdgeClick:l,onEdgeDoubleClick:h,onEdgeUpdate:rt,onlyRenderVisibleElements:V,onEdgeContextMenu:ze,onEdgeMouseEnter:He,onEdgeMouseMove:ct,onEdgeMouseLeave:Qe,onEdgeUpdateStart:$e,onEdgeUpdateEnd:Le,edgeUpdaterRadius:Dt,defaultMarkerColor:te,noPanClassName:_e,elevateEdgesOnSelect:!!le,disableKeyboardA11y:Se,rfId:yt},Ee.createElement(wB,{style:$,type:N,component:E,containerStyle:S})),Ee.createElement("div",{className:"react-flow__edgelabel-renderer"}),Ee.createElement(Yz,{nodeTypes:_t,onNodeClick:c,onNodeDoubleClick:d,onNodeMouseEnter:m,onNodeMouseMove:_,onNodeMouseLeave:g,onNodeContextMenu:y,selectNodesOnDrag:A,onlyRenderVisibleElements:V,noPanClassName:_e,noDragClassName:ce,disableKeyboardA11y:Se,nodeOrigin:pe,nodeExtent:dt,rfId:yt})))};dC.displayName="GraphView";var vB=p.memo(dC);const Cv=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Kl={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:Cv,nodeExtent:Cv,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:xu.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:G8,isValidConnection:void 0},xB=()=>l5((e,t)=>({...Kl,setNodes:n=>{const{nodeInternals:r,nodeOrigin:i,elevateNodesOnSelect:o}=t();e({nodeInternals:lw(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",c=i?lw(n,new Map,t().nodeOrigin,t().elevateNodesOnSelect):new Map;e({nodeInternals:c,edges:o?r:[],hasDefaultNodes:i,hasDefaultEdges:o})},updateNodeDimensions:n=>{const{onNodesChange:r,nodeInternals:i,fitViewOnInit:o,fitViewOnInitDone:c,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,v)=>{const N=i.get(v.id);if(N){const $=Ex(v.nodeElement);!!($.width&&$.height&&(N.width!==$.width||N.height!==$.height||v.forceUpdate))&&(i.set(N.id,{...N,[Gs]:{...N[Gs],handleBounds:{source:Qk(".source",v.nodeElement,g,h),target:Qk(".target",v.nodeElement,g,h)}},...$}),k.push({id:N.id,type:"dimensions",dimensions:$}))}return k},[]);Q$(i,h);const x=c||o&&!c&&eC(t,{initial:!0,...l});e({nodeInternals:new Map(i),fitViewOnInitDone:x}),(y==null?void 0:y.length)>0&&(r==null||r(y))},updateNodePositions:(n,r=!0,i=!1)=>{const{triggerNodeChanges:o}=t(),c=n.map(l=>{const d={id:l.id,type:"position",dragging:i};return r&&(d.positionAbsolute=l.positionAbsolute,d.position=l.position),d});o(c)},triggerNodeChanges:n=>{const{onNodesChange:r,nodeInternals:i,hasDefaultNodes:o,nodeOrigin:c,getNodes:l,elevateNodesOnSelect:d}=t();if(n!=null&&n.length){if(o){const h=Oz(n,l()),m=lw(h,i,c,d);e({nodeInternals:m})}r==null||r(n)}},addSelectedNodes:n=>{const{multiSelectionActive:r,edges:i,getNodes:o}=t();let c,l=null;r?c=n.map(d=>ec(d,!0)):(c=Dd(o(),n),l=Dd(i,[])),pp({changedNodes:c,changedEdges:l,get:t,set:e})},addSelectedEdges:n=>{const{multiSelectionActive:r,edges:i,getNodes:o}=t();let c,l=null;r?c=n.map(d=>ec(d,!0)):(c=Dd(i,n),l=Dd(o(),[])),pp({changedNodes:l,changedEdges:c,get:t,set:e})},unselectNodesAndEdges:({nodes:n,edges:r}={})=>{const{edges:i,getNodes:o}=t(),c=n||o(),l=r||i,d=c.map(m=>(m.selected=!1,ec(m.id,!1))),h=l.map(m=>ec(m.id,!1));pp({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=>ec(l.id,!1)),c=n.filter(l=>l.selected).map(l=>ec(l.id,!1));pp({changedNodes:o,changedEdges:c,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:r}=t();r.forEach(i=>{i.positionAbsolute=Ax(i.position,n)}),e({nodeExtent:n,nodeInternals:new Map(r)})},panBy:n=>{const{transform:r,width:i,height:o,d3Zoom:c,d3Selection:l,translateExtent:d}=t();if(!c||!l||!n.x&&!n.y)return!1;const h=sl.translate(r[0]+n.x,r[1]+n.y).scale(r[2]),m=[[0,0],[i,o]],_=c==null?void 0:c.constrain()(h,m,d);return c.transform(l,_),r[0]!==_.x||r[1]!==_.y||r[2]!==_.k},cancelConnection:()=>e({connectionNodeId:Kl.connectionNodeId,connectionHandleId:Kl.connectionHandleId,connectionHandleType:Kl.connectionHandleType,connectionStatus:Kl.connectionStatus,connectionStartHandle:Kl.connectionStartHandle,connectionEndHandle:Kl.connectionEndHandle}),reset:()=>e({...Kl})}),Object.is),Fx=({children:e})=>{const t=p.useRef(null);return t.current||(t.current=xB()),Ee.createElement(z8,{value:t.current},e)};Fx.displayName="ReactFlowProvider";const fC=({children:e})=>p.useContext(qg)?Ee.createElement(Ee.Fragment,null,e):Ee.createElement(Fx,null,e);fC.displayName="ReactFlowWrapper";const bB={input:H$,default:Nv,output:K$,group:Ox},kB={default:mg,straight:Rx,step:Mx,smoothstep:Vg,simplebezier:Tx},jB=[0,0],SB=[15,15],NB={x:0,y:0,zoom:1},$B={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},hC=p.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:i,nodeTypes:o=bB,edgeTypes:c=kB,onNodeClick:l,onEdgeClick:d,onInit:h,onMove:m,onMoveStart:_,onMoveEnd:g,onConnect:y,onConnectStart:x,onConnectEnd:k,onClickConnectStart:v,onClickConnectEnd:N,onNodeMouseEnter:$,onNodeMouseMove:E,onNodeMouseLeave:S,onNodeContextMenu:P,onNodeDoubleClick:D,onNodeDragStart:R,onNodeDrag:I,onNodeDragStop:W,onNodesDelete:G,onEdgesDelete:K,onSelectionChange:V,onSelectionDragStart:M,onSelectionDrag:A,onSelectionDragStop:O,onSelectionContextMenu:L,onSelectionStart:H,onSelectionEnd:J,connectionMode:U=xu.Strict,connectionLineType:te=nc.Bezier,connectionLineStyle:z,connectionLineComponent:ne,connectionLineContainerStyle:se,deleteKeyCode:de="Backspace",selectionKeyCode:be="Shift",selectionOnDrag:Me=!1,selectionMode:je=mm.Full,panActivationKeyCode:ae="Space",multiSelectionKeyCode:xe=hg()?"Meta":"Control",zoomActivationKeyCode:Ae=hg()?"Meta":"Control",snapToGrid:Ve=!1,snapGrid:mt=SB,onlyRenderVisibleElements:nt=!1,selectNodesOnDrag:rt=!0,nodesDraggable:ze,nodesConnectable:He,nodesFocusable:ct,nodeOrigin:Qe=jB,edgesFocusable:Dt,edgesUpdatable:$e,elementsSelectable:Le,defaultViewport:ce=NB,minZoom:Q=.5,maxZoom:_e=2,translateExtent:le=Cv,preventScrolling:Se=!0,nodeExtent:pe,defaultMarkerColor:dt="#b1b1b7",zoomOnScroll:yt=!0,zoomOnPinch:_t=!0,panOnScroll:It=!1,panOnScrollSpeed:bt=.5,panOnScrollMode:St=ou.Free,zoomOnDoubleClick:ut=!0,panOnDrag:Ot=!0,onPaneClick:Rt,onPaneMouseEnter:mn,onPaneMouseMove:wn,onPaneMouseLeave:On,onPaneScroll:Ks,onPaneContextMenu:rs,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:At="nowheel",noPanClassName:zt="nopan",fitView:ot=!1,fitViewOptions:Yt,connectOnClick:vn=!0,attributionPosition:hn,proOptions:sn,defaultEdgeOptions:Ht,elevateNodesOnSelect:is=!0,elevateEdgesOnSelect:Be=!1,disableKeyboardA11y:Qt=!1,autoPanOnConnect:Mt=!0,autoPanOnNodeDrag:Fn=!0,connectionRadius:fn=20,isValidConnection:Xe,onError:nn,style:cn,id:Ar,nodeDragThreshold:As,...ws},_r)=>{const we=Ar||"1";return Ee.createElement("div",{...ws,style:{...cn,...$B},ref:_r,className:Er(["react-flow",i]),"data-testid":"rf__wrapper",id:Ar},Ee.createElement(fC,null,Ee.createElement(vB,{onInit:h,onMove:m,onMoveStart:_,onMoveEnd:g,onNodeClick:l,onEdgeClick:d,onNodeMouseEnter:$,onNodeMouseMove:E,onNodeMouseLeave:S,onNodeContextMenu:P,onNodeDoubleClick:D,nodeTypes:o,edgeTypes:c,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:Rt,onPaneMouseEnter:mn,onPaneMouseMove:wn,onPaneMouseLeave:On,onPaneScroll:Ks,onPaneContextMenu:rs,onSelectionContextMenu:L,onSelectionStart:H,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:At,noPanClassName:zt,elevateEdgesOnSelect:Be,rfId:we,disableKeyboardA11y:Qt,nodeOrigin:Qe,nodeExtent:pe}),Ee.createElement(pz,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:y,onConnectStart:x,onConnectEnd:k,onClickConnectStart:v,onClickConnectEnd:N,nodesDraggable:ze,nodesConnectable:He,nodesFocusable:ct,edgesFocusable:Dt,edgesUpdatable:$e,elementsSelectable:Le,elevateNodesOnSelect:is,minZoom:Q,maxZoom:_e,nodeExtent:pe,onNodesChange:at,onEdgesChange:vt,snapToGrid:Ve,snapGrid:mt,connectionMode:U,translateExtent:le,connectOnClick:vn,defaultEdgeOptions:Ht,fitView:ot,fitViewOptions:Yt,onNodesDelete:G,onEdgesDelete:K,onNodeDragStart:R,onNodeDrag:I,onNodeDragStop:W,onSelectionDrag:A,onSelectionDragStart:M,onSelectionDragStop:O,noPanClassName:zt,nodeOrigin:Qe,rfId:we,autoPanOnConnect:Mt,autoPanOnNodeDrag:Fn,onError:nn,connectionRadius:fn,isValidConnection:Xe,nodeDragThreshold:As}),Ee.createElement(mz,{onSelectionChange:V}),ge,Ee.createElement(U8,{proOptions:sn,position:hn}),Ee.createElement(xz,{rfId:we,disableKeyboardA11y:Qt})))});hC.displayName="ReactFlow";const mC=({id:e,x:t,y:n,width:r,height:i,style:o,color:c,strokeColor:l,strokeWidth:d,className:h,borderRadius:m,shapeRendering:_,onClick:g,selected:y})=>{const{background:x,backgroundColor:k}=o||{},v=c||x||k;return Ee.createElement("rect",{className:Er(["react-flow__minimap-node",{selected:y},h]),x:t,y:n,rx:m,ry:m,width:r,height:i,fill:v,stroke:l,strokeWidth:d,shapeRendering:_,onClick:g?N=>g(N,e):void 0})};mC.displayName="MiniMapNode";var CB=p.memo(mC);const EB=e=>e.nodeOrigin,AB=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),fw=e=>e instanceof Function?e:()=>e;function TB({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:i=2,nodeComponent:o=CB,onClick:c}){const l=ms(AB,mr),d=ms(EB),h=fw(t),m=fw(e),_=fw(n),g=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return Ee.createElement(Ee.Fragment,null,l.map(y=>{const{x,y:k}=du(y,d).positionAbsolute;return Ee.createElement(o,{key:y.id,x,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:c,id:y.id})}))}var MB=p.memo(TB);const RB=200,LB=150,IB=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?V8(Hg(t,e.nodeOrigin),n):n,rfId:e.rfId}},OB="react-flow__minimap-desc";function _C({style:e,className:t,nodeStrokeColor:n="transparent",nodeColor:r="#e2e2e2",nodeClassName:i="",nodeBorderRadius:o=5,nodeStrokeWidth:c=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:x=!1,zoomable:k=!1,ariaLabel:v="React Flow mini map",inversePan:N=!1,zoomStep:$=10,offsetScale:E=5}){const S=tr(),P=p.useRef(null),{boundingRect:D,viewBB:R,rfId:I}=ms(IB,mr),W=(e==null?void 0:e.width)??RB,G=(e==null?void 0:e.height)??LB,K=D.width/W,V=D.height/G,M=Math.max(K,V),A=M*W,O=M*G,L=E*M,H=D.x-(A-D.width)/2-L,J=D.y-(O-D.height)/2-L,U=A+L*2,te=O+L*2,z=`${OB}-${I}`,ne=p.useRef(0);ne.current=M,p.useEffect(()=>{if(P.current){const be=wo(P.current),Me=xe=>{const{transform:Ae,d3Selection:Ve,d3Zoom:mt}=S.getState();if(xe.sourceEvent.type!=="wheel"||!Ve||!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(Ve,rt)},je=xe=>{const{transform:Ae,d3Selection:Ve,d3Zoom:mt,translateExtent:nt,width:rt,height:ze}=S.getState();if(xe.sourceEvent.type!=="mousemove"||!Ve||!mt)return;const He=ne.current*Math.max(1,Ae[2])*(N?-1:1),ct={x:Ae[0]-xe.sourceEvent.movementX*He,y:Ae[1]-xe.sourceEvent.movementY*He},Qe=[[0,0],[rt,ze]],Dt=sl.translate(ct.x,ct.y).scale(Ae[2]),$e=mt.constrain()(Dt,Qe,nt);mt.transform(Ve,$e)},ae=j$().on("zoom",x?je:null).on("zoom.wheel",k?Me:null);return be.call(ae),()=>{be.on("zoom",null)}}},[x,k,N,$]);const se=g?be=>{const Me=Vo(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(fm,{position:_,style:e,className:Er(["react-flow__minimap",t]),"data-testid":"rf__minimap"},Ee.createElement("svg",{width:W,height:G,viewBox:`${H} ${J} ${U} ${te}`,role:"img","aria-labelledby":z,ref:P,onClick:se},v&&Ee.createElement("title",{id:z},v),Ee.createElement(MB,{onClick:de,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:o,nodeClassName:i,nodeStrokeWidth:c,nodeComponent:l}),Ee.createElement("path",{className:"react-flow__minimap-mask",d:`M${H-L},${J-L}h${U+L*2}v${te+L*2}h${-U-L*2}z
156
+ 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"})))}_C.displayName="MiniMap";var PB=p.memo(_C);function DB(){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 FB(){return Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},Ee.createElement("path",{d:"M0 0h32v4.2H0z"}))}function zB(){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 BB(){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 UB(){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 Fd=({children:e,className:t,...n})=>Ee.createElement("button",{type:"button",className:Er(["react-flow__controls-button",t]),...n},e);Fd.displayName="ControlButton";const WB=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),pC=({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:i,onZoomIn:o,onZoomOut:c,onFitView:l,onInteractiveChange:d,className:h,children:m,position:_="bottom-left"})=>{const g=tr(),[y,x]=p.useState(!1),{isInteractive:k,minZoomReached:v,maxZoomReached:N}=ms(WB,mr),{zoomIn:$,zoomOut:E,fitView:S}=Px();if(p.useEffect(()=>{x(!0)},[]),!y)return null;const P=()=>{$(),o==null||o()},D=()=>{E(),c==null||c()},R=()=>{S(i),l==null||l()},I=()=>{g.setState({nodesDraggable:!k,nodesConnectable:!k,elementsSelectable:!k}),d==null||d(!k)};return Ee.createElement(fm,{className:Er(["react-flow__controls",h]),position:_,style:e,"data-testid":"rf__controls"},t&&Ee.createElement(Ee.Fragment,null,Ee.createElement(Fd,{onClick:P,className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:N},Ee.createElement(DB,null)),Ee.createElement(Fd,{onClick:D,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:v},Ee.createElement(FB,null))),n&&Ee.createElement(Fd,{className:"react-flow__controls-fitview",onClick:R,title:"fit view","aria-label":"fit view"},Ee.createElement(zB,null)),r&&Ee.createElement(Fd,{className:"react-flow__controls-interactive",onClick:I,title:"toggle interactivity","aria-label":"toggle interactivity"},k?Ee.createElement(UB,null):Ee.createElement(BB,null)),m)};pC.displayName="Controls";var qB=p.memo(pC),Jo;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(Jo||(Jo={}));function VB({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 HB({color:e,radius:t}){return Ee.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const GB={[Jo.Dots]:"#91919a",[Jo.Lines]:"#eee",[Jo.Cross]:"#e2e2e2"},KB={[Jo.Dots]:1,[Jo.Lines]:1,[Jo.Cross]:6},JB=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function gC({id:e,variant:t=Jo.Dots,gap:n=20,size:r,lineWidth:i=1,offset:o=2,color:c,style:l,className:d}){const h=p.useRef(null),{transform:m,patternId:_}=ms(JB,mr),g=c||GB[t],y=r||KB[t],x=t===Jo.Dots,k=t===Jo.Cross,v=Array.isArray(n)?n:[n,n],N=[v[0]*m[2]||1,v[1]*m[2]||1],$=y*m[2],E=k?[$,$]:N,S=x?[$/o,$/o]:[E[0]/o,E[1]/o];return Ee.createElement("svg",{className:Er(["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]})`},x?Ee.createElement(HB,{color:g,radius:$/o}):Ee.createElement(VB,{dimensions:E,color:g,lineWidth:i})),Ee.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${_+e})`}))}gC.displayName="Background";var YB=p.memo(gC);function yC(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 c=typeof t.maxAbsTranslate=="number"&&Number.isFinite(t.maxAbsTranslate)?Math.abs(t.maxAbsTranslate):1e6;if(Math.abs(r)>c||Math.abs(i)>c)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 pg(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 XB(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("-"),c=o>0?i.slice(0,o):i;return c==="person"?"person":c==="org"?"org":c==="concept"?"concept":c==="claim"?"claim":c==="event"?"event":c==="doc"?"doc":c==="thing"?"thing":"entity"}return r==="schema"||r==="skos"||r==="dcterms"||r==="rdf"||r==="cito"?"vocab":"entity"}function ZB(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return pg(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 pg(t)}function Ev(e){const r=Math.max(1,Math.ceil(Math.sqrt(e.length))),i={};for(let o=0;o<e.length;o++){const c=Math.floor(o/r),l=o%r;i[e[o]]={x:l*240,y:c*120}}return i}function Av(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 wC(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 QB(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 c=0;c<r;c++){const l=o+2*Math.PI*c/r;n[e[c]]={x:i*Math.cos(l),y:i*Math.sin(l)}}return n}function aj(e,t,n){var x;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 v=String((k==null?void 0:k.source)||"").trim(),N=String((k==null?void 0:k.target)||"").trim();if(!v||!N||v===N)continue;const $=i.get(v),E=i.get(N);$&&$.add(N),E&&E.add(v)}let o=e[0],c=-1;for(const k of e){const v=((x=i.get(k))==null?void 0:x.size)??0;(v>c||v===c&&k.localeCompare(o)<0)&&(o=k,c=v)}const l=new Map,d=[];for(l.set(o,0),d.push(o);d.length;){const k=d.shift(),v=l.get(k)??0,N=Array.from(i.get(k)??[]);N.sort(($,E)=>$.localeCompare(E));for(const $ of N)l.has($)||(l.set($,v+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 v=l.get(k)??0,N=m.get(v);N?N.push(k):m.set(v,[k])}const _=Array.from(m.keys()).sort((k,v)=>k-v),g=260,y=n%360*Math.PI/180;for(const k of _){const v=m.get(k)||[];if(v.sort((S,P)=>S.localeCompare(P)),k===0){if(v.length===1)r[v[0]]={x:0,y:0};else for(let P=0;P<v.length;P++){const D=y+2*Math.PI*P/v.length;r[v[P]]={x:80*Math.cos(D),y:80*Math.sin(D)}}continue}const N=g*k,$=v.length;if($===1){r[v[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[v[S]]={x:N*Math.cos(P),y:N*Math.sin(P)}}}return r}function Td(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 Ev(i);if(n==="circle")return QB(i,r);if(n==="radial")return aj(i,e.edges,r);if(n==="force"){const o=aj(i,e.edges,r),c=wC(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+(c()-.5)*l,y:m.y+(c()-.5)*l}}return d}return Ev(i)}function eU(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 tU(e,t={}){const n=!!(t.groupEdges??!0),r=Math.max(1,t.maxEdgeLabelPredicates??3),i=eU(e),o=new Set;for(const g of i){const y=String(g.subject||"").trim(),x=String(g.object||"").trim();y&&o.add(y),x&&o.add(x)}const c=Array.from(o);c.sort((g,y)=>g.localeCompare(y));const l=Ev(c),d=c.map(g=>({id:g,type:"default",data:{label:ZB(g),kind:XB(g)},position:l[g]||{x:0,y:0}})),h=new Map,m=(g,y)=>{const x=String(g.subject||"").trim(),k=String(g.object||"").trim(),v=String(g.predicate||"").trim();return n?`edge:${x}:${k}`:`edge:${y}:${x}:${v}:${k}`};for(let g=0;g<i.length;g++){const y=i[g],x=m(y,g),k=h.get(x);k?k.push(y):h.set(x,[y])}const _=[];for(const[g,y]of h.entries()){const x=y[0],k=String(x.subject||"").trim(),v=String(x.object||"").trim();if(!k||!v)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?`${pg(R)}×${I}`:pg(R)).join(" | "),P=$.length>r?` +${$.length-r}`:"",D=`${S}${P}`.trim();_.push({id:g,source:k,target:v,label:D,animated:!1,data:{assertions:y,predicateSummary:D}})}return{nodes:d,edges:_}}function nU(e,t,n,r={}){const i=r.directed!==!1,o=String(t||"").trim(),c=String(n||"").trim();if(!o||!c)return null;if(o===c)return{nodeIds:[o],edgeIds:[]};const l=new Map,d=(k,v,N)=>{const $=l.get(k);$?$.push({to:v,edgeId:N}):l.set(k,[{to:v,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(),v=l.get(k)||[];for(const N of v)if(!m.has(N.to)){if(m.set(N.to,k),_.set(N.to,N.edgeId),N.to===c){h.length=0;break}h.push(N.to)}}if(!m.has(c))return null;const g=[],y=[];let x=c;for(;x;){g.push(x);const k=_.get(x);k&&y.push(k),x=m.get(x)||null}return g.reverse(),y.reverse(),{nodeIds:g,edgeIds:y}}const lj={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function yp(e,t={}){const n={...lj,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):lj.seed},r=e.nodes.map(y=>y.id),i=r.length,o=new Float64Array(2*i),c=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??Td(e,{kind:"force",seed:n.seed}),m=wC(n.seed||1),_=Math.max(8,Math.min(38,Math.sqrt(i)*2.25));for(let y=0;y<i;y++){const x=r[y],k=h[x],v=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]=v+(m()-.5)*_,o[2*y+1]=N+(m()-.5)*_,c[2*y]=0,c[2*y+1]=0}const g=[];for(const y of e.edges){const x=d.get(String((y==null?void 0:y.source)||"").trim()),k=d.get(String((y==null?void 0:y.target)||"").trim());typeof x!="number"||typeof k!="number"||x===k||g.push(x,k)}return{nodeIds:r,pos:o,vel:c,acc:l,edges:new Uint32Array(g),options:n,tick:0}}function sU(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 x=0;x<n;x++){const k=e.pos[2*x],v=e.pos[2*x+1];for(let N=x+1;N<n;N++){const $=e.pos[2*N]-k,E=e.pos[2*N+1]-v,S=$*$+E*E+1e-6,P=1/Math.sqrt(S),D=y/S,R=D*$*P,I=D*E*P;e.acc[2*x]-=R,e.acc[2*x+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 x=h[y],k=h[y+1],v=e.pos[2*x],N=e.pos[2*x+1],$=e.pos[2*k],E=e.pos[2*k+1],S=$-v,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*x]+=W,e.acc[2*x+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 x=(e.vel[2*y]+e.acc[2*y]*i)*_,k=(e.vel[2*y+1]+e.acc[2*y+1]*i)*_;const v=Math.sqrt(x*x+k*k);if(v>g){const N=g/v;x*=N,k*=N}e.vel[2*y]=x,e.vel[2*y+1]=k,e.pos[2*y]+=x*i,e.pos[2*y+1]+=k*i}e.tick+=1}}function rU(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 iU(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 cj(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function oU(){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 aU(){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 vC(e,t,n,r){const i=typeof e=="number"&&Number.isFinite(e)?e:r;return Math.min(n,Math.max(t,i))}function Ah(e){const t=vC(e,.6,2.4,1),n=240*t,r=9e3*t*t;return{springLength:n,repulsionStrength:r}}const gm="abstractuic_amx_saved_layouts_v1",Tv=.025,Mv=6,xC=1e6;function zx(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function Rv(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function lU(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 uj(e){const t=zx();if(!t)return null;const n=String(e??"").trim();if(!n)return null;try{const r=t.getItem(gm);if(!r)return null;const i=JSON.parse(r),o=i&&typeof i=="object"&&!Array.isArray(i)?i:null;if(!o)return null;const c=o[n],l=c&&typeof c=="object"&&!Array.isArray(c)?c:null;if(!l)return null;const d=l.version===1?1:null;if(d===null)return null;const h=Rv(l.kind,"grid"),m=typeof l.seed=="number"&&Number.isFinite(l.seed)?Math.trunc(l.seed):Av(n),_=l.positions&&typeof l.positions=="object"&&!Array.isArray(l.positions)?l.positions:null,g={};if(_)for(const[k,v]of Object.entries(_)){const N=lU(v);N&&(g[String(k)]=N)}const y=yC(l.viewport,{minZoom:Tv,maxZoom:Mv,maxAbsTranslate:xC})??void 0,x=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:x}}catch{return null}}function cU(e,t){const n=zx();if(!n)return;const r=String(e??"").trim();if(r)try{const i=n.getItem(gm),o=i?JSON.parse(i):null,c=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:{};c[r]=t,n.setItem(gm,JSON.stringify(c))}catch{}}function uU(e){const t=zx();if(!t)return;const n=String(e??"").trim();if(n)try{const r=t.getItem(gm);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(gm,JSON.stringify(o))}catch{}}function dU(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function hw(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 c=Math.trunc(o);if(r&&c===-1)return-1;if(!(!n&&c<=0)&&!(n&&c<0))return c}function fU(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 hU(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 c=e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)?e.attributes:null,l=c&&c._retrieval&&typeof c._retrieval=="object"&&!Array.isArray(c._retrieval)?c._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 mU(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),c=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:c}),l]})}function Th(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 _U(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 Mh(e){const t=_U(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"),c=String(n.getUTCHours()).padStart(2,"0"),l=String(n.getUTCMinutes()).padStart(2,"0");return`${r}/${i}/${o} ${c}:${l}`}function bC(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 mw(e,t){const n=String(e??"").trim().toLowerCase();return!!(n&&t.has(n))}function pU(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 c=i.slice(0,n).map(([d,h])=>{const m=bC(d);return h>1?`${m}×${h}`:m}).join(" | "),l=i.length>n?` +${i.length-n}`:"";return`${c}${l}`.trim()}function gU({resetKey:e,queryMode:t,items:n,activeMemoryText:r,packets:i,packetsVersion:o,packedCount:c,dropped:l,estimatedTokens:d,effort:h,warnings:m,onQuery:_,onItemsReplace:g,onOpenSpan:y,onOpenTranscript:x}){var Kn;const k=p.useRef(null),v=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??v),$=t==="replace"?"replace":"override",[E,S]=p.useState(null),[P,D]=p.useState(null),[R,I]=p.useState(!1),[W,G]=p.useState(""),[K,V]=p.useState(!1),[M,A]=p.useState("");p.useEffect(()=>{S(null),D(null),G(""),I(!1),A(""),V(!1)},[N]);const[O,L]=p.useState(""),[H,J]=p.useState(!0),[U,te]=p.useState(!1),[z,ne]=p.useState(!0),[se]=p.useState(()=>({compact:oU(),show:!1})),de=se.compact,[be,Me]=p.useState(se.show),[je,ae]=p.useState(!1),xe=N,Ae=p.useMemo(()=>Av(xe),[xe]),[Ve,mt]=p.useState("grid"),[nt,rt]=p.useState(Ae),[ze,He]=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[Rt,mn]=p.useState(""),[wn,On]=p.useState(""),Ks=p.useMemo(()=>{var he;const Y=(he=n==null?void 0:n[0])==null?void 0:he.scope;return cj(Y,"session")},[n]),[rs,ge]=p.useState(Ks),[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(""),[At,zt]=p.useState(""),[ot,Yt]=p.useState(""),[vn,hn]=p.useState("qwen/qwen3-next-80b");p.useEffect(()=>{ge(Ks)},[N]);const sn=Array.isArray(n)?n:[],Ht=typeof r=="string"?r:"",is=Array.isArray(i)?i:[],Be=typeof o=="number"?o:void 0,Qt=typeof c=="number"?c:void 0,Mt=typeof l=="number"?l:void 0,Fn=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:Ht,Ar=(E==null?void 0:E.effort)??fn,As=(E==null?void 0:E.warnings)??Xe,ws=p.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),_r=p.useMemo(()=>z?nn:(nn||[]).filter(Y=>!mw(Y==null?void 0:Y.predicate,ws)),[nn,z,ws]),we=p.useMemo(()=>tU(nn,{groupEdges:H}),[nn,H]),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=>!mw(ht==null?void 0:ht.predicate,ws));if(!De.length)continue;const Ye=pU(De);Y.push({...he,label:Ye,data:{...he.data,assertions:De,predicateSummary:Ye}})}return{nodes:we.nodes,edges:Y}},[we,z,ws]),zn=p.useMemo(()=>Nt.nodes.map(Y=>Y.id),[Nt.nodes]),nr=p.useMemo(()=>{const Y=zn[0]||"",he=zn[zn.length-1]||"";return`${zn.length}:${Y}:${he}`},[zn]),$i=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]),sr=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]),xo=O.trim().toLowerCase(),dc=p.useMemo(()=>{var he;if(!xo)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(xo)||Ye.includes(xo))&&Y.add(Oe.id)}return Y},[Nt.nodes,xo]),ul=p.useCallback((Y,he)=>{const Oe={};for(const De of zn){const Ye=Y[De]||he[De];Oe[De]=Ye?{x:Ye.x,y:Ye.y}:{x:0,y:0}}return Oe},[zn]);p.useEffect(()=>{ut(Y=>{const he=Td(Nt,{kind:Ve,seed:nt}),Oe={};for(const De of zn){const Ye=Y[De]||he[De];Oe[De]=Ye?{x:Ye.x,y:Ye.y}:{x:0,y:0}}return Oe})},[Nt,Ve,nt,zn,nr]),p.useEffect(()=>{if(!Le.current)return;const Y=k.current;if(!(!Y||typeof Y.fitView!="function")&&zn.length){Le.current=!1;try{Y.fitView({padding:.2,duration:0})}catch{try{Y.fitView({padding:.2})}catch{}}}},[zn.length,nr,St]),p.useEffect(()=>{He(!1),Dt.current=null,$e.current=null,Le.current=!1,le.current=0,Se.current=0,pe.current=0;const Y=uj(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=Td(Nt,{kind:Y.kind,seed:Y.seed});ut(ul(Y.positions,De));return}_t(!1),bt("");const he=Av(xe);rt(he);const Oe=Td(Nt,{kind:Ve,seed:he});ut(Oe),Ve==="force"&&Nt.nodes.length>0&&Nt.nodes.length<=320&&(Dt.current=yp(Nt,{seed:he,positions:Oe,...Ah(ct)}),He(!0))},[xe]);const js=p.useMemo(()=>{const Y=String(Rt||"").trim(),he=String(wn||"").trim();return!Y||!he?null:nU(Nt,Y,he,{directed:U})},[Nt,Rt,wn,U]),pr=!!(js&&String(Rt||"").trim()&&String(wn||"").trim()),Rs=p.useMemo(()=>{const Y=String(Rt||"").trim(),he=String(wn||"").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:_r.length}},[U,Nt.edges,Nt.nodes.length,wn,Rt,_r.length]),Bi=p.useMemo(()=>new Set((js==null?void 0:js.nodeIds)||[]),[js]),dl=p.useMemo(()=>new Set((js==null?void 0:js.edgeIds)||[]),[js]),[vs,si]=p.useState(""),[Ls,ri]=p.useState(""),Ss=!!(String(vs||"").trim()||String(Ls||"").trim()),ii=p.useMemo(()=>{const Y=new Set,he=new Set,Oe=String(vs||"").trim(),De=String(Ls||"").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,Ls,vs]);p.useEffect(()=>{si(""),ri(""),mn(""),On("")},[N]);const[Ui,In]=p.useState(!1);p.useEffect(()=>{In(!1)},[N]),p.useEffect(()=>{ze||(Dt.current=null)},[ze]),p.useEffect(()=>{if(Ve!=="force")return;const Y=Dt.current;if(!Y)return;const he=Ah(ct);Y.options.springLength=he.springLength,Y.options.repulsionStrength=he.repulsionStrength},[Ve,ct]),p.useEffect(()=>{Ve!=="force"&&ze&&He(!1)},[Ve,ze]),p.useEffect(()=>{if(!ze||Ve!=="force"||Nt.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;Dt.current||(Dt.current=yp(Nt,{seed:nt,positions:Ot.current,...Ah(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){He(!1);return}sU(Bt,De),Oe+=De,ut(iU(Bt)),(rU(Bt)<=ht||Oe>=Ye)&&He(!1)};return Y=window.requestAnimationFrame(Wt),()=>{window.cancelAnimationFrame(Y)}},[Nt,Ve,ze,nt]);const $a=p.useMemo(()=>Nt.nodes.map(Y=>{var bn;const he=Bi.has(Y.id),Oe=dc.has(Y.id),De=vs===Y.id,Ye=Ss&&ii.nodes.has(Y.id),ht=Th((bn=Y.data)==null?void 0:bn.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,En=Pt&&pn?`${Pt}, ${pn}`:pn||Pt||void 0,Js=he?"rgba(168, 85, 247, 0.10)":Oe?"rgba(34, 211, 238, 0.08)":ht.bg,Ft=pr?he||De?1:.16:Ss?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:Js,color:"rgba(255,255,255,0.92)",opacity:Ft,padding:8,fontSize:12,boxShadow:En,width:180,cursor:"pointer"}}}),[Nt.nodes,pr,dc,St,vs,Bi,Ss,ii.nodes]),fl=p.useMemo(()=>Nt.edges.map(Y=>{const he=dl.has(Y.id),Oe=Ls===Y.id,De=Ss&&ii.edges.has(Y.id),Ye=he?"rgba(168, 85, 247, 0.9)":Ss?De||Oe?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",ht=he?2.75:Ss?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)":pr?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",Bt=pr?he||Oe?1:.1:Ss?De||Oe?1:.08:1,pn=pr?he||Oe?1:0:Ss?De||Oe?1:0:1,En=pr?he||Oe?String(Y.label||""):"":String(Y.label||"");return{...Y,label:En,style:{...Y.style||{},stroke:Ye,strokeWidth:ht,filter:Wt,opacity:Bt},animated:!1,markerEnd:{type:_m.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,pr,Ls,dl,Ss,ii.edges]),hl=p.useMemo(()=>{if(!Ls)return[];const Y=Nt.edges.find(Oe=>Oe.id===Ls),he=Y&&Y.data&&Array.isArray(Y.data.assertions)?Y.data.assertions:[];return Array.isArray(he)?he:[]},[Nt.edges,Ls]),Tr=p.useMemo(()=>Ls&&Nt.edges.find(Y=>Y.id===Ls)||null,[Nt.edges,Ls]),fc=p.useMemo(()=>{const Y=String(vs||"").trim();return Y?nn.filter(he=>!he||typeof he!="object"||!(he.subject===Y||he.object===Y)?!1:z?!0:!mw(he.predicate,ws)):[]},[nn,vs,z,ws]),Wi=p.useMemo(()=>Ls?hl:fc,[hl,Ls,fc]),Ca=p.useMemo(()=>{const Y=new Map;for(const he of Wi){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=Mh(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:Mh(pn),assertion:he})}return Array.from(Y.values()).sort((he,Oe)=>String(Oe.last_observed_at||"").localeCompare(String(he.last_observed_at||"")))},[Wi]),bo=p.useMemo(()=>{const Y=new Map;for(const he of Wi){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=Mh(Wt),ht.assertion=he)):Y.set(Ye,{run_id:Ye,count:1,last_observed_at:Wt,last_observed_at_fmt:Mh(Wt),assertion:he})}return Array.from(Y.values()).sort((he,Oe)=>String(Oe.last_observed_at||"").localeCompare(String(he.last_observed_at||"")))},[Wi]),Fs=p.useCallback(Y=>{const he=String(Y.run_id||"").trim(),Oe=typeof Y.span_id=="string"?String(Y.span_id).trim():"";if(he){if(x){try{x({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,x]),zs=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{}}},[]),gr=p.useCallback(()=>{const Y=k.current;if(!(!Y||typeof Y.fitView!="function")){if(vs&&typeof Y.getNode=="function"){const he=Y.getNode(vs);if(he){Y.fitView({nodes:[he],padding:.55,duration:350});return}}Y.fitView({padding:.2,duration:350})}},[vs]),ko=p.useCallback(Y=>{const he=Y.kind,Oe=Math.trunc(Y.seed);He(!1),Dt.current=null,$e.current=null,mt(he),rt(Oe);const De=Td(Nt,{kind:he,seed:Oe});ut(De),he==="force"&&(Y.autoPlay??!0)&&Nt.nodes.length>0&&Nt.nodes.length<=320&&(Dt.current=yp(Nt,{seed:Oe,positions:De,...Ah(ct)}),He(!0))},[Nt,ct]),Wr=p.useCallback(()=>{if(Ve==="force"){if(ze){He(!1);return}Dt.current=yp(Nt,{seed:nt,positions:Ot.current,...Ah(ct)}),He(!0)}},[Nt,Ve,ze,nt,ct]);p.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&dt.current&&window.cancelAnimationFrame(dt.current)},[]);const Mr=p.useCallback(()=>{const Y=k.current;if(!Y||typeof Y.getViewport!="function"||!zn.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(zn.length,180),pn=Ot.current;let En=0,Js=0;for(const Ft of zn){const bn=pn[Ft];if(!bn||!Number.isFinite(bn.x)||!Number.isFinite(bn.y))continue;Js+=1;const as=[{x:bn.x,y:bn.y},{x:bn.x+90,y:bn.y+24}];for(const Hn of as){const Rr=Hn.x*Ye+ht,yr=Hn.y*Ye+Wt;if(Rr>-Pt&&Rr<Oe.width+Pt&&yr>-Pt&&yr<Oe.height+Pt)return!1}if(En++,En>=Bt)break}return Js?!0:null},[zn]),qr=p.useCallback(Y=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||dt.current||(dt.current=window.requestAnimationFrame(()=>{dt.current=0;const he=Mr();if(he===null){if(pe.current>=12)return;pe.current+=1,window.setTimeout(()=>qr(`${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(()=>qr(`${Y}:retry`),220)}))},[Mr]);p.useEffect(()=>{Se.current=0,le.current=0,pe.current=0,qr("mount")},[N,qr]),p.useEffect(()=>{qr("graph change")},[nr,qr]),p.useEffect(()=>{const Y=_e.current;if(!Y||typeof window>"u"||typeof ResizeObserver!="function")return;const he=new ResizeObserver(()=>qr("resize"));return he.observe(Y),()=>he.disconnect()},[qr]);const hc=p.useCallback(()=>{const Y=new Date().toISOString(),he={};for(const Wt of zn){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=yC(Ye,{minZoom:Tv,maxZoom:Mv,maxAbsTranslate:xC})??void 0;cU(xe,{version:1,kind:Ve,seed:nt,positions:he,viewport:ht,saved_at:Y}),_t(!0),bt(Y),He(!1)},[xe,Ve,nt,zn]),Vr=p.useCallback(()=>{const Y=uj(xe);if(!Y)return;He(!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=Td(Nt,{kind:Y.kind,seed:Y.seed});if(ut(ul(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}}},[ul,Nt,xe]),ku=p.useCallback(()=>{uU(xe),_t(!1),bt("")},[xe]),Ci=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&&He(!1)},[ze]),Xo=p.useMemo(()=>{const Y=new Map;for(const he of Nt.edges)Y.set(he.id,he);return Y},[Nt.edges]),ml=p.useMemo(()=>{var De;if(!js)return[];const Y=js.nodeIds||[],he=js.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=Xo.get(Pt),pn=String(((De=Bt==null?void 0:Bt.data)==null?void 0:De.predicateSummary)||(Bt==null?void 0:Bt.label)||"").trim(),En=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:En})}return Oe},[Xo,js]),jo=p.useCallback(async()=>{if(_){G(""),A(""),I(!0);try{const Y=dU(vt),he=hw(At,{allowZero:!0,allowNegativeOne:!0}),Oe=hw(ot,{allowZero:!0}),De=await _({scope:rs,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:vn||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)}}},[At,ot,vt,vn,et,g,_,We,$,re,Re,rs,Ce]),oi=p.useCallback(async()=>{if(!_)return;const Y=String(Rt||"").trim(),he=String(wn||"").trim();if(!Y||!he)return;const Oe=Math.max(200,hw(At)??80),De=60;A(""),G(""),V(!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 bn=`${Ft.subject}|${Ft.predicate}|${Ft.object}|${String(Ft.observed_at||"")}|${String(Ft.scope||"")}|${String(Ft.owner_id||"")}`;ht.has(bn)||(ht.add(bn),Ye.push(Ft))};for(const Ft of nn)Wt(Ft);const Pt=U,Bt=new Set,pn=[Y],En=new Set([Y]),Js=async Ft=>{const bn=await _({scope:rs,recall_level:Re,min_score:0,limit:Oe,subject:Ft,query_text:void 0,max_input_tokens:0,model:void 0});if(bn&&Array.isArray(bn.items)){for(const as of bn.items)if(Wt(as),typeof as.subject=="string"&&as.subject.trim()===Ft&&typeof as.object=="string"){const Hn=as.object.trim();Hn&&!En.has(Hn)&&(En.add(Hn),pn.push(Hn))}}if(!Pt){const as=await _({scope:rs,recall_level:Re,min_score:0,limit:Oe,object:Ft,query_text:void 0,max_input_tokens:0,model:void 0});if(as&&Array.isArray(as.items)){for(const Hn of as.items)if(Wt(Hn),typeof Hn.object=="string"&&Hn.object.trim()===Ft&&typeof Hn.subject=="string"){const Rr=Hn.subject.trim();Rr&&!En.has(Rr)&&(En.add(Rr),pn.push(Rr))}}}};for(;pn.length&&Bt.size<De&&!En.has(he);){const Ft=pn.shift();!Ft||Bt.has(Ft)||(Bt.add(Ft),await Js(Ft))}S({ok:!0,count:Ye.length,items:Ye,active_memory_text:cn,raw:{expanded_for_path:!0,expanded_nodes:Bt.size,discovered_nodes:En.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:En.size,merged:Ye.length,directed:Pt}}})}catch(Ye){const ht=Ye instanceof Error?Ye.message:String(Ye);A(ht||"Expand neighborhood failed")}finally{V(!1)}},[U,cn,nn,At,g,_,wn,Rt,$,Re,rs]),Ea=p.useCallback(()=>{S(null),D(null),G(""),I(!1),A(""),V(!1),mn(""),On(""),si(""),ri("")},[]),qi="Search KG",rr=Nt.nodes.length,cf=Nt.edges.length,ai=_r.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:Ve,onChange:Y=>mt(Rv(Y.target.value,Ve)),disabled:!zn.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)"})]}),Ve==="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(vC(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:()=>ko({kind:Ve,seed:nt}),disabled:!zn.length,children:"Apply"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Wr,disabled:!zn.length||Ve!=="force",children:ze?"Pause simulation":"Play simulation"})]})}),s.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:_e,children:[s.jsx(Fx,{children:s.jsxs(hC,{nodes:$a,edges:fl,defaultViewport:{x:0,y:0,zoom:1},minZoom:Tv,maxZoom:Mv,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,qr("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:Ci,onNodeClick:(Y,he)=>{ri(""),si(he.id)},onEdgeClick:(Y,he)=>{si(""),ri(he.id)},onPaneClick:()=>{si(""),ri("")},children:[s.jsx(qB,{className:"amx-flow-controls",children:s.jsx(Fd,{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(aU,{})})}),s.jsx(fm,{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(PB,{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 Th((he=Y.data)==null?void 0:he.kind).minimap}}):null,je?s.jsxs(fm,{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:Th(Y).stroke},children:he},Y))})]}):null,s.jsx(YB,{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:qi}),s.jsxs("span",{className:"amx-small",children:[ai," assertions · ",rr," nodes · ",cf," 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(H),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:Ve,onChange:Y=>mt(Rv(Y.target.value,Ve)),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:()=>ko({kind:Ve,seed:nt}),disabled:!zn.length,children:"Apply layout"}),Ve==="force"?s.jsx("button",{type:"button",className:"amx-btn",onClick:Wr,disabled:!zn.length,children:ze?"Pause simulation":"Play simulation"}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:hc,disabled:!zn.length,children:"Save layout"}),yt?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:Vr,children:"Load saved"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:ku,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:Rt,onChange:Y=>mn(Y.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),zn.map(Y=>s.jsx("option",{value:Y,children:(()=>{const he=$i.get(Y)||Y;return he===Y?he:`${he} (${Y})`})()},Y))]})]}),s.jsxs("label",{children:["path end",s.jsxs("select",{value:wn,onChange:Y=>On(Y.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),zn.map(Y=>s.jsx("option",{value:Y,children:(()=>{const he=$i.get(Y)||Y;return he===Y?he:`${he} (${Y})`})()},Y))]})]})]}),js?s.jsx("div",{className:"amx-small",style:{marginTop:10},children:ml.map((Y,he)=>{const Oe=$i.get(Y.from)||Y.from,De=$i.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}`)})}):Rt&&wn?s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["No path found in the current subgraph (",(Rs==null?void 0:Rs.assertions)??ai," assertions · ",(Rs==null?void 0:Rs.nodes)??Nt.nodes.length," nodes ·"," ",(Rs==null?void 0:Rs.edges)??Nt.edges.length," edges). Start reaches ",(Rs==null?void 0:Rs.reachableFromStart)??0," nodes.",_?s.jsx("div",{style:{marginTop:10},children:s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void oi(),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:At,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:rs,onChange:Y=>ge(cj(Y.target.value,rs)),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=>Yt(Y.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["model (budgeting)",s.jsx("input",{value:vn,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 jo(),disabled:!_||R,children:R?"Querying…":"Query store"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Ea,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=fU(Ar);return Y?s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:Y}):null})(),(()=>{const Y=As;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)??Qt,Oe=(E==null?void 0:E.dropped)??Mt,De=(E==null?void 0:E.estimated_tokens)??Fn,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:mU(cn||"(empty)",O)}),(()=>{const Y=E!=null&&E.packets&&Array.isArray(E.packets)?E.packets:is;return!Array.isArray(Y)||Y.length===0?null:s.jsxs("div",{style:{marginTop:10},children:[s.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>In(he=>!he),children:[Ui?"Hide":"Show"," packets (",Y.length,")"]}),Ui?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."}),vs?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:$i.get(vs)||vs}),s.jsxs("div",{className:"amx-small",children:["kind=",sr.get(vs)||"entity"," · id=",vs]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void zs(vs),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:gr,children:"Focus"})]})]}):Tr&&Tr.source&&Tr.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:[Tr.source," —",String(Tr.label||((Kn=Tr.data)==null?void 0:Kn.predicateSummary)||"").trim()||"?","→ ",Tr.target]}),s.jsxs("div",{className:"amx-small",children:["edge_id=",Tr.id]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void zs(Tr.id),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:gr,children:"Fit"})]})]}):s.jsx("div",{className:"amx-small",style:{marginBottom:10,opacity:.9},children:"(no selection)"}),s.jsx("div",{className:"amx-list",children:Wi.slice(0,80).map((Y,he)=>{const Oe=String(Y.subject||"").trim(),De=String(Y.predicate||"").trim(),Ye=String(Y.object||"").trim(),ht=$i.get(Oe)||Oe,Wt=$i.get(Ye)||Ye,Pt=sr.get(Oe)||"entity",Bt=sr.get(Ye)||"entity",pn=Th(Pt),En=Th(Bt),Js=Mh(Y.observed_at),Ft=hU(Y),bn=Y.provenance&&typeof Y.provenance=="object"&&!Array.isArray(Y.provenance)?Y.provenance:null,as=bn&&typeof bn.span_id=="string"?bn.span_id.trim():"",Hn=bn&&typeof bn.writer_run_id=="string"?bn.writer_run_id.trim():"",Rr=typeof Y.owner_id=="string"?Y.owner_id.trim():"",yr=Hn||Rr,Vi=!!((x||y)&&as&&yr),_l=!!(x&&Hn&&!as),Hi=Vi||_l;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&&(ri(""),si(Oe))},children:ht||Oe||"(subject)"}),s.jsx("span",{className:"amx-arrow",children:"—"}),s.jsx("span",{className:"amx-predicate",title:De,children:bC(De)||"(predicate)"}),s.jsx("span",{className:"amx-arrow",children:"→"}),s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:En.stroke,background:En.bg},title:Ye,onClick:()=>{Ye&&(ri(""),si(Ye))},children:Wt||Ye||"(object)"})]}),s.jsxs("div",{className:"amx-triple-meta",children:[Js?s.jsxs("span",{className:"amx-small",title:String(Y.observed_at||""),children:["[",Js,"]"]}):null,Ft?s.jsx("span",{className:"amx-small",children:Ft}):null]}),as||Hn?s.jsxs("div",{className:"amx-triple-actions",children:[as?s.jsxs("span",{className:"amx-small",children:["span:",as]}):null,Hn?s.jsxs("span",{className:"amx-small",children:["run:",Hn]}):null,Hi?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(Vi&&as&&yr){Fs({run_id:yr,span_id:as,assertion:Y});return}_l&&Hn&&Fs({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)."}),Ca.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:Ca.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||x?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Fs({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,x&&bo.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:bo.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:()=>Fs({run_id:Y.run_id,assertion:Y.assertion}),children:"Open transcript"})]},Y.run_id))})]}):null,!Ca.length&&!(x&&bo.length)?s.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})})}function tc({open:e,title:t,children:n,actions:r,variant:i="default",onClose:o}){const c=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":c,children:[s.jsxs("div",{className:"modal_header",children:[s.jsx("div",{className:"modal_title",id:c,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 _w(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function Xl(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 su(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"),c=String(t.getUTCMinutes()).padStart(2,"0");return`${n}/${r}/${i} ${o}:${c}`}function yU(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=Xl(t);return n!==null?su(n):t}function Bx(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,`
157
+ `).replace(/\\n/g,`
158
+ `).replace(/\\t/g," "):""}function kC(e){return String(e??"").replace(/[*_`~]/g,"")}function wp(e,t){const n=!!(t!=null&&t.strip_punct),r=Bx(e);let i=kC(r).replace(/\s+/g," ").trim().toLowerCase();return n&&(i=i.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),i}function vp(e,t){const n=String(t??"").trim();if(!n)return!1;const r=wp(n,{strip_punct:!1});if(!r)return!1;if(wp(String(e??""),{strip_punct:!1}).includes(r))return!0;const o=wp(n,{strip_punct:!0});return o?wp(String(e??""),{strip_punct:!0}).includes(o):!1}function dj(e){const t=Bx(e).trim();if(!t)return[];const n=[],r=c=>{const l=String(c??"").replace(/\s+/g," ").trim();l&&(l.length<6||n.includes(l)||n.push(l))},i=t.search(/[`*_~]/);if(i>0){const c=t.slice(0,i);c.replace(/\s+/g," ").trim().length>=10&&r(c)}const o=[/`([^`]+)`/g,/\*\*([^*]+)\*\*/g,/__([^_]+)__/g,/\*([^*]+)\*/g,/_([^_]+)_/g];for(const c of o){let l;for(;(l=c.exec(t))!==null;){const d=String(l[1]??"").trim();d&&r(d)}}return r(kC(t)),n}function wU(e){const t=String(e??"").replace(/\r\n/g,`
159
+ `).replace(/\r/g,`
160
+ `);if(!t)return null;const n=t.split(`
161
+ `);let r;const i=[],o=[];let c=null,l=[],d=!1;const h=()=>{if(!c)return;const g=l.join(`
162
+ `).trim();g&&o.push({role:c,lines:[g]}),c=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 x=g.match(/^\s*(USER|ASSISTANT|SYSTEM)\s*:\s*(.*)$/i);if(x){d=!0,h();const k=String(x[1]||"").trim().toLowerCase();c=k==="user"?"user":k==="assistant"?"assistant":"system";const v=String(x[2]??"");l=v?[v]:[];continue}c?l.push(g):i.push(g)}if(h(),!d||!o.length)return null;const m=i.join(`
163
+ `).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(`
164
+ `)});return _.messages.length?_:null}function fj(e,t){const n=String(e||""),r=String(t||"");return r>n?r:n}function hj(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(),c=String((e==null?void 0:e.owner_id)||"").trim();return`${t}|${n}|${r}|${i}|${o}|${c}`}function vU(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(),c=String((e==null?void 0:e.owner_id)||"").trim(),l=[];o&&l.push(`scope=${o}`),c&&l.push(`owner=${c}`);const d=l.length?` (${l.join(", ")})`:"";return`${t?`[${t}] `:""}${n} --${r}--> ${i}${d}`}function xU({gateway:e,selected_run_id:t,selected_session_id:n}){const[r,i]=p.useState(String(t||"").trim()),[o,c]=p.useState(String(n||"").trim()),[l,d]=p.useState("all"),h=l==="all",[m,_]=p.useState(!0),[g,y]=p.useState(750),[x,k]=p.useState(5e3),[v,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),[V,M]=p.useState(!1),[A,O]=p.useState(""),[L,H]=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),Ve=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 Bx(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=Ve;return!ge||!Re?!1:vp(ge,Re)},[Ve,mt]),ze=p.useMemo(()=>{const ge=nt,Re=Ve;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);vp(Ce,Re)&&gt.push(re)}return gt},[Ve,nt]),He=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&&!(V||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,V,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(()=>{c(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 v){const re=Xl(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}},[v]),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?v:v.filter(Re=>{const gt=Xl(Re==null?void 0:Re.observed_at);return gt===null?!0:gt<=ge})},[v,_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=hj(We);if(fe.has(Ue))continue;fe.add(Ue),Ce.push(We);const et=String(We.observed_at||"").trim();et&&(Ie=fj(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=_w(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(),At=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"?At?zt.session_id=At:xt&&(zt.run_id=xt):Re==="all"&&(xt?zt.run_id=xt:At&&(zt.session_id=At)));try{const ot=await e.kg_query(zt),Yt=Array.isArray(ot==null?void 0:ot.items)?ot.items:[],vn=ot==null?void 0:ot.warnings;return{ok:(ot==null?void 0:ot.ok)!==!1,count:Number((ot==null?void 0:ot.count)||Yt.length),items:Yt,warnings:vn,raw:ot}}catch(ot){const Yt=ot instanceof Error?ot.message:String(ot);if(Yt.includes("Run '")&&Yt.includes("not found")&&!At&&(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:[],Ht=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:Ht,raw:hn}}throw new Error(Yt||"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"),H(`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]),Rt=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 At=typeof xt.note=="string"?String(xt.note):"";if(At&&At.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"),H(`transcript run:${Re}`),be(null),je(""),xe(ge.assertion&&typeof ge.assertion=="object"?ge.assertion:null),Ae.current=!1;try{const gt=await Rt({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,Rt]),wn=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(()=>{v.length||wn()},[]);const On=p.useCallback(async ge=>{const Re=_w(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]),Ks=p.useCallback((ge,Re)=>{var gt;if((Re==null?void 0:Re.kind)==="live query"){const re=Q.current;re&&(ce.current={scope:_w(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]),rs=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,x)),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=hj(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=fj(et,xt))}We.length&&(Le.current=et,N(at=>{const vt=at.concat(We);return vt.sort((xt,At)=>String((At==null?void 0:At.observed_at)||"").localeCompare(String((xt==null?void 0:xt.observed_at)||""))),vt}),W(at=>{const vt=at.concat(Ue);return vt.sort((xt,At)=>At.expires_at_ms-xt.expires_at_ms),vt.slice(0,30)}))},[x,ut]);return p.useEffect(()=>{if(!m)return;let ge=!1,Re=null;const gt=async()=>{if(!ge){try{await rs()}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,rs]),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 wn(),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(BP,{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=>c(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:x,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(gU,{title:"mindmap",resetKey:_e,queryMode:"replace",items:bt,warnings:$,onQuery:On,onItemsReplace:Ks,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:vU(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:su(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(),"/",v.length.toLocaleString()]})]})}):null]}),s.jsxs(tc,{open:G,title:L||"source",onClose:()=>{K(!1)},children:[V?s.jsx("div",{className:"mono muted",children:"Loading…"}):null,A?s.jsx("div",{className:"mindmap_error mono",children:A}):null,!V&&!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=su(Xl(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?Xl(fe):null,Ie=Ce!==null?su(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?Xl(Ue):null,vt=et?Xl(et):null,xt=at!==null&&vt!==null?`${su(at)} → ${su(vt)}`:"";if(re){const At=wU(re);if(At){const zt=Ve,ot=zt?At.messages.findIndex(sn=>vp(sn.content,zt)):-1,Yt=zt?dj(zt):[],vn=At.created_at||fe,hn=vn?yU(vn):fe?Ie:"";return s.jsx("div",{className:"source_chat",children:At.messages.map((sn,Ht)=>{const is=sn.role,Be=!!(zt&&vp(sn.content,zt)),Qt=is==="user"?"USER":is==="assistant"?"ASSISTANT":"SYSTEM";return s.jsxs("div",{id:Ht===ot?"source_note_msg_hit_0":void 0,className:`source_msg source_${is} ${Be?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Ht+1," · ",Qt,Be?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),hn?s.jsx("span",{title:vn||"",children:hn}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Ni,{text:sn.content,highlights:Be&&Yt.length?Yt:void 0,highlightClassName:"source_note_hit",highlightId:Ht===ot?"source_note_hit_0":void 0})})]},`note_msg:${Ht}`)})})}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(Ni,{text:re,highlights:Ve?dj(Ve):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(gt){const At=new Map;for(const ot of gt){const Yt=typeof(ot==null?void 0:ot.role)=="string"?String(ot.role):"unknown";At.set(Yt,(At.get(Yt)||0)+1)}const zt=Array.from(At.entries()).sort((ot,Yt)=>Yt[1]-ot[1]||ot[0].localeCompare(Yt[0])).map(([ot,Yt])=>`${ot}×${Yt}`).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,Yt)=>{var Mt,Fn;const vn=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):"",Ht=sn?Xl(sn):null,is=Ht!==null?su(Ht):sn,Be=typeof(ot==null?void 0:ot.message_id)=="string"?String(ot.message_id):typeof((Mt=ot==null?void 0:ot.metadata)==null?void 0:Mt.message_id)=="string"?String(ot.metadata.message_id):typeof((Fn=ot==null?void 0:ot.metadata)==null?void 0:Fn.id)=="string"?String(ot.metadata.id):"",Qt=He.has(Yt);return s.jsxs("div",{id:`source_msg_${Yt}`,className:`source_msg source_${vn} ${Qt?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Yt+1," · ",vn,Qt?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:is}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Ni,{text:hn})})]},Yt)})]})}return s.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof ge=="string"?ge:Me)||"(empty)"})})()]}):null]})]})}const bU=6e4,kU=10*6e4;function jU(e){return Math.min(kU,bU*2**Math.max(0,e-1))}function Gg(){return{value_version:"",value:null,has_value:!1,attempt_version:"",inflight:!1,failures:0,failed_at:null,error:""}}function SU(e,t,n,r){const i=[],o=new Set;for(const c of e||[]){const l=String((c==null?void 0:c.id)||"").trim();if(!l||o.has(l))continue;o.add(l);const d=t.get(l);if(!d){i.push({id:l,version:String(c.version||"")});continue}if(!d.inflight){if(d.failed_at!==null){n-d.failed_at>=jU(d.failures)&&i.push({id:l,version:String(c.version||"")});continue}r!=null&&r.immutable&&d.has_value||d.value_version!==String(c.version||"")&&i.push({id:l,version:String(c.version||"")})}}return i}function NU(e,t){const n=e.get(t.id)||Gg();e.set(t.id,{...n,attempt_version:t.version,inflight:!0})}function $U(e,t,n){const r=e.get(t.id)||Gg();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 CU(e,t,n,r){const i=e.get(t.id)||Gg();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 EU(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 AU(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 TU(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 c=t.get(o);if(!c||c.inflight){r.add(o);continue}c.failed_at===null&&(!c.has_value||n!=null&&n.current_only&&c.value_version!==String(i.version||""))&&r.add(o)}return r}function ks(e){return String((e==null?void 0:e.run_id)||"").trim()}function mj(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 MU(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 RU(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 LU(e){return(e||[]).filter(t=>ks(t)&&RU(t)).map(t=>({id:ks(t),version:""}))}const IU=6e4;function OU(e,t=Date.now(),n=IU){const r=[];for(const i of e||[]){if(!ks(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 c=Vt((i==null?void 0:i.updated_at)||(i==null?void 0:i.created_at)||"");c!==null&&t-c<n||r.push({id:ks(i),version:String(o)})}return r}function PU(e){return{after:Math.max(0,Math.floor(e)-1),limit:1}}function DU(e,t){const n=[],r=new Set,i=o=>{r.has(ks(o))||(r.add(ks(o)),n.push({id:ks(o),version:String((o==null?void 0:o.updated_at)||"")}))};for(const o of e||[]){if(!ks(o)||String((o==null?void 0:o.status)||"").trim().toLowerCase()!=="waiting")continue;const c=mj(o);(c==="user"||t&&c==="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&&!hs(String((l==null?void 0:l.status)||""))&&o.add(d)}let c=0;for(const l of t){if(c>=FU)break;!ks(l)||String((l==null?void 0:l.status)||"").trim().toLowerCase()!=="waiting"||mj(l)==="subworkflow"&&!o.has(ks(l))&&(i(l),c+=1)}}return n}const FU=50,zU=e=>({run_id:e,status:"missing",updated_at:"",workflow_id:"",error:"not found"});function BU(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 UU(e,t){var i,o;const n=[],r=new Set;for(const c of e.values()){const l=String(((o=(i=c==null?void 0:c.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 WU(e,t){var c;const n=Array.isArray(t==null?void 0:t.pin_ids)?t.pin_ids.map(l=>String(l)):[],r=(c=t==null?void 0:t.input_data)==null?void 0:c.prompt,o=(n.includes("prompt")||n.length===0)&&typeof r=="string"?r.trim():"";return{run_id:e,excerpt:o}}const qU=12;function _j(e,t,n=qU){const r=[],i=new Set;for(const o of e||[]){let c=0;for(const l of o||[]){const d=ks(l);!d||i.has(d)||(t===null?c>=n:!t.has(d))||(i.add(d),r.push(l),c+=1)}}return r}const gg="abstractobserver_board_cache_v1:",VU=400,Lv=6e5;function HU(e,t){const n=new Map;if(!e)return n;try{const r=e.getItem(gg+t);if(!r)return n;const i=JSON.parse(r);if(!Array.isArray(i))return n;for(const o of i){const c=String((o==null?void 0:o.id)||"").trim();!c||o.value===null||o.value===void 0||n.set(c,{...Gg(),value:o.value,has_value:!0,value_version:String(o.version??"")})}}catch{return new Map}return n}function GU(e,t,n){if(e)try{let r=[];for(const[o,c]of n)!c.has_value||c.value===null||c.inflight||c.failed_at!==null||r.push({id:o,version:c.value_version,value:c.value});r=r.slice(-VU);let i=JSON.stringify(r);for(;i.length>Lv&&r.length;)r=r.slice(Math.max(1,Math.floor(r.length/4))),i=JSON.stringify(r);r.length?e.setItem(gg+t,i):e.removeItem(gg+t)}catch{}}function jC(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}const KU=4,af={automation:0,wait_detail:1,pulse:1,run_brief:2,outcome:3};class JU{constructor(t=KU){jn(this,"queue",[]);jn(this,"seq",0);jn(this,"active",0);jn(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 pj=new WeakMap;function YU(e){let t=pj.get(e);return t||(t=new JU,pj.set(e,t)),t}const gj=new WeakMap;function XU(e){let t=gj.get(e);return t||(t=e.automations_client(),gj.set(e,t)),t}function ZU(e){return e.map(t=>`${t.id}@${t.version}`).sort().join("|")}const yj=new WeakMap;function QU(e,t,n){let r=yj.get(e);r||(r=new Map,yj.set(e,r));let i=r.get(t);return i||(i=n!=null&&n.persist?HU(n.storage===void 0?jC():n.storage,t):new Map,r.set(t,i)),i}const pw=new Map;function e9(e,t){if(typeof setTimeout>"u")return;const n=pw.get(e);n!==void 0&&clearTimeout(n),pw.set(e,setTimeout(()=>{pw.delete(e),GU(jC(),e,t)},250))}function lf(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?QU(e,r.scope,{persist:r.persist}):new Map,gen:i.current.gen+1});const[o,c]=p.useReducer(x=>x+1,0),l=ZU(t),d=Math.floor(Date.now()/3e4),h=p.useRef(n);h.current=n,p.useEffect(()=>{const x=i.current;if(!x.client)return;const k=x.client,v=x.gen,N=SU(t,x.entries,Date.now(),{immutable:r.immutable});if(!N.length)return;const $=YU(k);for(const E of N)NU(x.entries,E),$.submit(r.priority,async()=>{try{const S=await h.current(k,E);if(i.current.gen!==v)return;$U(x.entries,E,S),r.persist&&e9(r.scope,x.entries)}catch(S){if(i.current.gen!==v)return;CU(x.entries,E,S,Date.now())}c()});c()},[e,l,d,o,r.priority,r.immutable]);const m=p.useMemo(()=>EU(t,i.current.entries,{current_only:r.current_only}),[l,o,r.current_only,e]),_=p.useMemo(()=>AU(t,i.current.entries),[l,o,e]),g=p.useMemo(()=>TU(t,i.current.entries,{current_only:r.current_only}),[l,o,r.current_only,e]),y=p.useMemo(()=>x=>{const k=i.current.entries.get(x);k&&!k.inflight&&i.current.entries.set(x,{...k,value_version:"\0stale",failed_at:null,failures:0}),c()},[]);return{map:m,pending:_,loading:g,invalidate:y}}function t9(e){var r;const t=Mm(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 n9(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:{},c=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:c,stop_at_ms:Vt(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 s9(e,t){const n=p.useMemo(()=>MU(t),[t]),r=lf(e,n,async(o,c)=>t9(await XU(o).getAutomation(c.id)),{scope:"automation",priority:af.automation}),i=p.useMemo(()=>{const o=new Map,c=new Map;for(const[l,d]of r.map)o.set(l,d.brief),d.revision!==null&&c.set(l,d.revision);return{map:o,revisions:c}},[r.map]);return{map:i.map,revisions:i.revisions,records:r.map,pending:r.pending,loading:r.loading,invalidate:r.invalidate}}function r9(e,t){const n=p.useMemo(()=>LU(t),[t]),r=lf(e,n,async(i,o)=>WU(o.id,await i.get_run_input_data(o.id)),{scope:"excerpt_v2",priority:af.run_brief,immutable:!0,persist:!0});return{map:r.map,pending:r.pending,loading:r.loading}}function i9(e,t){const n=p.useMemo(()=>OU(t,Date.now()),[t]),r=lf(e,n,async(i,o)=>{const c=Number(String(o.version).split(":")[0]||0),l=await i.get_ledger(o.id,PU(c)),d=Array.isArray(l==null?void 0:l.items)?l.items:[];return d.length?BD(o.id,c,d[d.length-1]):null},{scope:"pulse",priority:af.pulse});return{map:r.map,pending:r.pending,loading:r.loading}}const o9=!0;function a9(e,t,n){const r=p.useMemo(()=>DU(t,n),[t,n]),i=lf(e,r,async(o,c)=>await o.get_run(c.id),{scope:"wait_detail",priority:af.wait_detail,current_only:o9});return{map:i.map,pending:i.pending,loading:i.loading}}function l9(e,t,n){const r=p.useMemo(()=>UU(t,n),[t,n]),i=lf(e,r,async(o,c)=>{try{return BU(c.id,await o.get_run(c.id))}catch(l){if(/\b404\b|not found/i.test(String((l==null?void 0:l.message)||l||"")))return zU(c.id);throw l}},{scope:"subrun_fate",priority:af.wait_detail});return{map:i.map,pending:i.pending,loading:i.loading}}const c9=!0;function u9(e){return(e||[]).filter(t=>ks(t)&&hs(String((t==null?void 0:t.status)||""))).map(t=>({id:ks(t),version:""}))}function d9(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 f9(e){const t=e==null?void 0:e.total;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}async function h9(e,t){const[n,r]=await Promise.all([e.get_run(t),e.list_run_artifacts(t,{limit:1}).then(f9,()=>null)]);return{answer:d9(n),artifacts:r}}function m9(e,t){const n=p.useMemo(()=>u9(t),[t]),r=lf(e,n,async(i,o)=>await h9(i,o.id),{scope:"outcome",priority:af.outcome,immutable:c9,persist:!0});return{map:r.map,pending:r.pending,loading:r.loading}}function _9(){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 x=String(y.target.dataset.runId||"").trim();x&&(y.isIntersecting?!i.current.has(x):i.current.has(x))&&(y.isIntersecting?i.current.add(x):i.current.delete(x),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]),c=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:c}}const wj=200,vj=500,p9=6e4,g9=1e4,y9=15e3,w9=["llm_calls","tool_calls","tokens_total"];function v9(e,t){if(!t)return e;const n={...e};for(const r of w9){const i=e[r];i==null&&(n[r]=t[r]??null)}return t.archived===!0&&(n.archived=!0),n}function gw(e){return!String((e==null?void 0:e.parent_run_id)||"").trim()||String((e==null?void 0:e.role)||"").trim()==="occurrence"}class x9{constructor(t){jn(this,"sweep_rows",[]);jn(this,"sweep_at",null);jn(this,"sweep_started_at",null);jn(this,"sweep_inflight",!1);jn(this,"active_rows",[]);jn(this,"active_complete",!1);jn(this,"early",!1);jn(this,"active_at",null);jn(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>=p9||this.early&&r>=y9?!0:n&&r>=g9}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=>!!ks(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=>!!ks(n)),this.sweep_rows=Array.isArray(t.sweep_rows)?t.sweep_rows.filter(n=>!!ks(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(ks)),o=new Set,c=[];for(const l of[...t||[],...n||[]]){const d=ks(l);!d||o.has(d)||(o.add(d),c.push(l))}if(this.active_rows=c,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(ks(l),l);const n=new Set,r=[];for(const l of this.active_rows)n.add(ks(l)),r.push(v9(l,t.get(ks(l))));const i=new Map(r.map(l=>[ks(l),l])),o=[...r],c=r.filter(l=>gw(l)&&!t.has(ks(l)));for(const l of this.sweep_rows){const d=ks(l),h=i.get(d);if(h){gw(h)&&c.push(h);continue}this.active_complete&&!hs(String((l==null?void 0:l.status)||""))||o.push(l),gw(l)&&c.push(l)}return{roots:c,all:o}}}function b9(e,t){return`${gg}runs:${String(e||"").trim()}:${String(t||"").trim()}`}function k9(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 j9(e,t,n){if(e)try{let r=JSON.stringify(n);if(r.length>Lv&&(r=JSON.stringify({...n,sweep_rows:[]})),r.length>Lv){e.removeItem(t);return}e.setItem(t,r)}catch{}}function xj(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}const Iv=new WeakMap;let Ov=null;function S9(e,t){let n=Iv.get(e);if(!n||n.epoch!==t){const r=Ov;n=new x9(t),r&&r.epoch===t&&(r.sweep_at!==null&&n.adopt_sweep(r),n.adopt_active(r)),Iv.set(e,n)}return Ov=n,n}function N9(e){return Iv.get(e)||null}function bj(e){return Ov===e}const xp=["needs_you","working","waiting_on","scheduled","done"],SC={needs_you:"Needs you",working:"Working",waiting_on:"Waiting on…",scheduled:"Scheduled",done:"Done"},$9={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"},C9={needs_you:"nothing needs you",working:"no agent is working",waiting_on:"nothing is blocked",scheduled:"nothing scheduled",done:"no recent runs"},E9=8;function A9(){return{needs_you:[],working:[],waiting_on:[],scheduled:[],done:[]}}function Qs(e){return String((e==null?void 0:e.run_id)||"").trim()}function yw(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 T9(e,t,n,r){const i=(e==null?void 0:e.paused)===!0||(n==null?void 0:n.paused)===!0;return z1({...e,paused:i},t,Qp(n),r??null)}function va(e,t){const n=String(e||"").trim();return n.length>t?`${n.slice(0,t-1)}…`:n}function bp(e,t,n,r){var x,k;const i=Qs(e),o=(x=t.details)==null?void 0:x.get(i),c=(o==null?void 0:o.waiting)??(e==null?void 0:e.waiting),l=c&&typeof c=="object"?c:null,d=of(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=Vt((l==null?void 0:l.until)||"");return{run_id:i,lane:n.lane,line:n,title:U1(e,t,r),subject:B1(e,t),status_word:T9(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(v=>String((v==null?void 0:v.name)||"tool")).filter(Boolean),pending_calls:d.map(v=>({name:String((v==null?void 0:v.name)||"tool"),arguments:(v==null?void 0:v.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:Vt((l==null?void 0:l.since)||(e==null?void 0:e.updated_at)||(e==null?void 0:e.created_at)||""),duration_ms:Am(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:Og(e),tag_label:s1(e),actor_run_label:g?ni(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 M9(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}const kp=(e,t)=>e===null?t===null?0:1:t===null?-1:e-t,kj=(e,t)=>e===null?t===null?0:1:t===null?-1:t-e;function R9(e){return e.needs_you.sort((t,n)=>Number(t.stuck&&!t.asks.length)-Number(n.stuck&&!n.asks.length)||kp(t.since_ms,n.since_ms)),e.working.sort((t,n)=>Number(n.line.stalled)-Number(t.line.stalled)||kj(t.line.stale_ms,n.line.stale_ms)||kp(t.since_ms,n.since_ms)),e.waiting_on.sort((t,n)=>kp(t.since_ms,n.since_ms)),e.scheduled.sort((t,n)=>kp(t.next_fire_ms,n.next_fire_ms)),e.done.sort((t,n)=>Number(n.failed)-Number(t.failed)||kj(t.since_ms,n.since_ms)),e}function jj(e){var y,x,k;const t=A9(),n=[],r=[],i=new Set;for(const v of e.active||[]){const N=Qs(v);!N||i.has(N)||(i.add(N),(hs(v==null?void 0:v.status)?r:n).push(v))}for(const v of e.done||[]){const N=Qs(v);!N||i.has(N)||(i.add(N),hs(v==null?void 0:v.status)&&r.push(v))}const o=xx([...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}),c=new Map(n.map(v=>[Qs(v),v])),l=new Map,d=v=>{const N=Qs(v);let $=l.get(N);return $||($=Qd(v,o),l.set(N,$)),$},h=v=>yw(v)||!c.has(String((v==null?void 0:v.parent_run_id)||"").trim()),m=v=>Vt(String((v==null?void 0:v.updated_at)||(v==null?void 0:v.created_at)||""))??0,_=v=>(o.children_of.get(v)||[]).filter(N=>c.has(Qs(N))&&!yw(N)).sort((N,$)=>m($)-m(N)),g=new Set;for(const v of n){if(!h(v))continue;const N=d(v);if(String((v==null?void 0:v.role)||"").trim()==="controller"){const G=String((v==null?void 0:v.automation_id)||"").trim()||Qs(v);if(g.has(G))continue;g.add(G);const K=bp(v,o,N,(y=e.run_briefs)==null?void 0:y.get(Qs(v)));t[K.lane].push(K);continue}const $=bp(v,o,N,(x=e.run_briefs)==null?void 0:x.get(Qs(v))),E=[],S=[];let P=N.verb==="running",D=!!N.stuck,R=0;const I=(G,K)=>{var O;const V=d(G),M=K<6?_(Qs(G)):[],A=M.length>0;if(E.length>=E9)R+=1;else{const L=A?F1(G,o):"";E.push({run_id:Qs(G),depth:K,name:Fg(String((G==null?void 0:G.workflow_id)||""))||Zd(Qs(G)),title:FD(String((G==null?void 0:G.workflow_id)||""))||Qs(G),words:A?L?`waits at ${L} ↓`:"waits for ↓":V.brief||V.text,stuck:!!V.stuck,asks:V.lane==="needs_you"&&!V.stuck,running:V.verb==="running"&&!A,stuck_facts:V.stuck_facts,since_ms:Vt(String((G==null?void 0:G.updated_at)||(G==null?void 0:G.created_at)||""))})}K>0?(V.lane==="needs_you"&&!V.stuck&&S.push(bp(G,o,V,(O=e.run_briefs)==null?void 0:O.get(Qs(G)))),V.stuck&&(D=!0),V.verb==="running"&&(P=!0)):A&&V.lane==="needs_you"&&!V.stuck&&S.push($);for(const L of M)I(L,K+1)};I(v,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 v of r){if(!yw(v)&&o.by_id.has(String((v==null?void 0:v.parent_run_id)||"").trim()))continue;const N=bp(v,o,d(v),(k=e.run_briefs)==null?void 0:k.get(Qs(v)));t.done.push(N)}return R9(t)}function L9(e,t){const r=(t&&t.length?t:e||[]).filter(o=>Qs(o)&&!hs(o==null?void 0:o.status)),i=[...t||[],...e||[]].filter(o=>Qs(o)&&hs(o==null?void 0:o.status));return{active:r,done:i}}const NC="board_stall_after_ms",Ux=[{ms:5*6e4,label:"5m"},{ms:15*6e4,label:"15m"},{ms:60*6e4,label:"1h"}];function $C(e){try{const t=Number(e==null?void 0:e.getItem(NC));return Ux.some(n=>n.ms===t)?t:dv}catch{return dv}}function CC(e){var t;return((t=Ux.find(n=>n.ms===e))==null?void 0:t.label)||er(e)}function I9(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function EC(e){const t=String((e==null?void 0:e.actor_id)||"").trim();return t&&t.toLowerCase()!=="gateway"?t:""}const AC=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],yg=e=>String(e).padStart(2,"0");function fu(e,t=Date.now()){const n=new Date(e),r=n.getFullYear()===new Date(t).getFullYear()?"":` ${n.getFullYear()}`;return`${AC[n.getMonth()]} ${n.getDate()}${r}, ${yg(n.getHours())}:${yg(n.getMinutes())}`}function O9(e){const t=new Date(e);return`${AC[t.getUTCMonth()]} ${t.getUTCDate()}, ${yg(t.getUTCHours())}:${yg(t.getUTCMinutes())} UTC`}function Pv(e,t=Date.now()){const n=e-t;return n>0?`in ${er(n)}`:`${er(-n)} ago`}function P9(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 ic=e=>e.split(" ").join(" ");function Wx(e,t){const n=e.since_ms!==null?` since ${ic(fu(e.since_ms,t))} ${ic(`(${er(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=EC(e.row);return r==="approve"?{who:i,text:`needs approval for ${P9(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 Yh(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 Dv(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?va(Yh(o),t):Yh(o)}`);return`${e.name}(${r.join(", ")})`}function D9(e){const t=e.arguments;return t==null?"":typeof t!="object"||Array.isArray(t)?Yh(t):Object.entries(t).map(([n,r])=>Array.isArray(r)&&r.length&&r.every(i=>i===null||typeof i!="object")?`${n}:
165
+ ${r.map(i=>Yh(i)).join(`
166
+ `)}`:`${n}: ${Yh(r)}`).join(`
167
+ `)}const Dp=600,Fp=4e3;function TC(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:va(r,Dp),full:va(r,Fp)}:null}if(e.line.action==="approve"&&e.pending_calls.length){const r=e.pending_calls.map(o=>Dv(o,120)).join(" · "),i=e.pending_calls.map(o=>Dv(o)).join(`
168
+ `);return{text:va(r,Dp),full:va(i,Fp)}}return e.prompt?{text:va(e.prompt,Dp),full:va(e.prompt,Fp)}:null}function F9(e,t){if(e.lane!=="done"||e.failed)return null;const n=String((t==null?void 0:t.answer)||"").trim();return n?{text:va(n,Dp),full:va(n,Fp)}:null}function MC(e,t){const n=[];return e.role==="controller"||(e.duration_ms>=0&&n.push(er(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 qx(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 z9(e,t,n){return`${String(e||"").split("#")[0]}#session=${encodeURIComponent(t)}&run=${encodeURIComponent(n)}`}const Sj="Install the AbstractCode web app (npx @abstractframework/code) to open this conversation";function Nj(e){return e.lane!=="done"&&e.role!=="controller"}const B9={automation:"automation",brief:"run brief",excerpt:"prompt",workflow:"untitled"};function wg(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 U9=[25e3,5e4,1e5,2e5];function RC(e,t){var E;const n=e.trigger_text||e.schedule_rule_text||(e.trigger?bx(e.trigger):"")||e.cadence||"",r=e.current&&!hs(e.current.status)?e.current:null,i=((E=e.trigger)==null?void 0:E.source_id)==="manual";let o="",c="";if(e.status==="paused")o="paused",c=e.paused_reason||"scheduled runs are skipped while paused";else if(r)o=`run #${r.index} in progress`,c=e.next_fire_ms!==null?`next run ${fu(e.next_fire_ms,t)}`:"";else if(e.next_fire_ms!==null)o=`next ${ic(Pv(e.next_fire_ms,t))}`,c=`next run ${fu(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?Zh(new Date(e.last.fired_ms).toISOString(),{timeZone:e.time_zone||null,nowMs:t,style:"day"}):"";o=S?`listening · last: ${ic(S)}`:"listening",c="runs every time something new arrives"}else i||(o="no next run");const l=[n,o].filter(Boolean),d={text:ww(l),title:[n,c].filter(Boolean).join(" · "),parts:l},h=ic(`${e.occurrence_count} turn${e.occurrence_count===1?"":"s"}`);if(!e.last)return{schedule:d,last:{text:ww(["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?ic(Pv(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}`:""}`,v=m.fired_ms!==null&&m.finished_ms!==null&&m.finished_ms>=m.fired_ms?er(m.finished_ms-m.fired_ms):"",N=[k,h],$=[`#${m.index} ${m.status}`,m.fired_ms!==null?`fired ${fu(m.fired_ms,t)}`:"",v?`took ${v}`:"",y].filter(Boolean).join(" · ");return{schedule:d,last:{text:ww(N),title:$,failed:_,parts:N,failure:y}}}function ww(e){return e.join(" · ").split(" ").join(" ")}function W9(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 · ${lc(n)} budget`:`context ${lc(r)} / ${lc(n)}`;return{mode:t,used:r,budget:n,label:i,ratio:r!==null&&n!==null?Math.min(1,r/n):null}}function q9(e){return{context:{mode:"growing",growing:{max_tokens:e}}}}function V9(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 H9={phase:"idle",custom:"",error:"",optimistic:null};function G9(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 K9(e,t){const n=t.optimistic;return n&&n.base===e.growing_max_tokens?n.value:e.growing_max_tokens}async function J9(e,t,n,r){try{return await e(t,q9(r),n),{type:"saved"}}catch(i){return{type:"failed",error:Pi(i).message||"the change was not saved"}}}function Y9(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&&!hs(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=Qh(r,[],t),o=e.status==="paused",c=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:c}:{command:"automation.pause",label:"Pause schedule",state:i.pause}}}async function X9(e,t,n){try{return await e(t,n),null}catch(r){return Pi(r).message||"the command was not sent"}}const eu={run:"Run",spend:"Spend",automation:"Automation",schedule:"Schedule",policy:"Policy",after:"After each run",where:"Where"};function Fv(e,t){return`${e.toLocaleString("en-US")} ${t}${e===1?"":"s"}`}function Rh(e,t,n,r,i=!1){return n===null?null:{id:e,label:t,value:i?O9(n):fu(n,r),aside:Pv(n,r),copy:new Date(n).toISOString()}}function Z9(e){const t=e.line;return t.verb==="paused"?"you, to resume it":t.action==="approve"?`your approval of ${Fv(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 $j(e,t){if(!t)return null;const n=ni(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 Q9(e,t){var h,m,_,g;const{now_ms:n}=t,r=e.automation,i=t.facts??null,o=e.row,c=e.role==="controller",l=[];if(!c){const y=[];if(!e.automation_id){const $=wg(e);_n(y,{id:"title",label:"Title",value:$,long:!0,source:B9[e.title.source]}),e.task&&e.task!==$&&_n(y,{id:"task",label:"Task",value:e.task,long:!0,source:"prompt"})}_n(y,$j("workflow",e.workflow_id)),_n(y,{id:"run_id",label:"Run id",value:e.run_id,mono:!0});const x=String((o==null?void 0:o.session_id)||"").trim();x&&_n(y,{id:"session",label:"Session",value:x,mono:!0}),_n(y,Rh("started","Started",Vt((o==null?void 0:o.created_at)||""),n)),_n(y,Rh("last_activity","Last activity",Vt((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:EC(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:Z9(e)}),_n(y,Rh("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:D9($),chips:[$.name],long:!0,copy:Dv($)})):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:eu.run,rows:y});const v=[],N=e.lane!=="done";e.duration_ms>=0&&_n(v,{id:"duration",label:"Duration",value:er(e.duration_ms),aside:N?"so far":""}),e.tokens_total!==null&&_n(v,{id:"tokens",label:"Tokens",value:e.tokens_total.toLocaleString("en-US"),source:"whole run tree"}),e.llm_calls!==null&&_n(v,{id:"llm_calls",label:"LLM calls",value:e.llm_calls.toLocaleString("en-US")}),e.tool_calls!==null&&_n(v,{id:"tool_calls",label:"Tool calls",value:e.tool_calls.toLocaleString("en-US")}),typeof((m=t.outcome)==null?void 0:m.artifacts)=="number"&&_n(v,{id:"artifacts",label:"Artifacts",value:t.outcome.artifacts.toLocaleString("en-US")}),e.tokens_total===null&&e.llm_calls===null&&e.tool_calls===null&&_n(v,{id:"metrics",label:"Metrics",value:"not measured yet: the 60 s metrics sweep fills them"}),l.push({id:"spend",title:eu.spend,rows:v})}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,$j("target_workflow",(i==null?void 0:i.workflow_id)||(c?"":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:eu.automation,rows:y});const x=[];_n(x,{id:"trigger",label:"Trigger",value:r.trigger_text||(r.trigger?bx(r.trigger,r.schedule_rule_text):"")||r.cadence||"not on the record",source:(i==null?void 0:i.trigger_source)||""}),r.status==="paused"?_n(x,{id:"next",label:"Next run",value:"none while paused: scheduled runs are skipped"}):_n(x,Rh("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&&!hs(r.current.status)?r.current:null;if(k&&_n(x,{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?er(r.last.finished_ms-r.last.fired_ms):"",E=r.last.fired_ms!==null?fu(r.last.fired_ms,n):"";_n(x,{id:"last",label:"Last run",value:`#${r.last.index} ${r.last.status}`,aside:[$,E].filter(Boolean).join(" · ")})}_n(x,{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(x,{id:"stop_after",label:"Stop after",value:Fv(i.stop_after,"run")}),(i==null?void 0:i.stop_at_ms)!==null&&(i==null?void 0:i.stop_at_ms)!==void 0&&_n(x,Rh("stop_at","Stop at",i.stop_at_ms,n,!0)),l.push({id:"schedule",title:eu.schedule,rows:x});const v=[];if(r.context_mode){const $=r.context_mode==="growing"&&typeof r.growing_max_tokens=="number"&&r.growing_max_tokens>0?`capped at ${lc(r.growing_max_tokens)} tokens`:"";_n(v,{id:"context",label:"Context",value:r.context_mode,aside:$})}_n(v,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(v,{id:"model",label:"Model",value:N}),r.max_iterations!==null&&_n(v,{id:"max_iterations",label:"Max iterations",value:String(r.max_iterations)}),r.tool_approval&&_n(v,{id:"tool_approval",label:"Tool approval",value:r.tool_approval}),r.untrusted_input_tools&&_n(v,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(v,{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(v,{id:"retry",label:"Retry",value:$.max_attempts!==null?Fv($.max_attempts,"attempt"):"on failure",aside:E})}l.push({id:"policy",title:eu.policy,rows:v}),l.push({id:"after",title:eu.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:eu.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 zv={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},vw={"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"},Cj="48h";function Ej(e,t,n=Date.now()){const r=zv[t]??null;if(r===null)return{visible:e,hidden_count:0};const i=n-r,o=[];let c=0;for(const l of e)l.since_ms===null||l.since_ms>=i?o.push(l):c+=1;return{visible:o,hidden_count:c}}const xw=4;function eW(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=c=>Array.isArray(c)?c.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 Aj(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 tW(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(Aj).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(Aj).filter(h=>h!==null):[],c=typeof((d=e==null?void 0:e.lessons)==null?void 0:d.total)=="number"?e.lessons.total:o.length;return{questions:n.slice(0,xw),questions_total:n.length,problems:r.slice(0,xw),problems_total:r.length,lessons:o.slice(0,xw),lessons_total:c}}function lc(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 nW(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 sW=6e4;function bw(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 kw(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function zp(e){return e.toLowerCase().replace(/[_-]+/g," ")}function rW(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:zp(_),phase:_});const g=(h=n[_])==null?void 0:h.spoken_synonyms;if(Array.isArray(g))for(const y of g){const x=zp(String(y||"").trim());x&&i.push({needle:x,phase:_})}}const c=(typeof t.initial_phase=="string"&&r.includes(t.initial_phase)?t.initial_phase:null)??(r.includes("sleep")?"sleep":null);if(!c)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(),x=zp(String(_||"").trim());x&&r.includes(y)&&l.push({needle:x,phase:y})}return{phases:r,synonyms:i,modes:l,initial:c,version:typeof t.version=="number"?t.version:null,sha256:String((e==null?void 0:e.sha256)||"").trim()}}const iW=["asleep","sleep","dream"],oW=["rest"],aW=["awake","idle"];function lW(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const r=zp(n),i=t.synonyms.filter(c=>r.includes(c.needle)).sort((c,l)=>l.needle.length-c.needle.length);if(i.length)return i[0].phase;const o=t.modes.filter(c=>r.includes(c.needle)).sort((c,l)=>l.needle.length-c.needle.length);return o.length?o[0].phase:n.includes("task")&&!n.includes("no_task")&&t.phases.includes("work")?"work":iW.some(c=>n.includes(c))?t.initial:oW.some(c=>n.includes(c))&&t.phases.includes("personal")?"personal":aW.some(c=>n.includes(c))?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 cW=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),uW=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function dW(e){if(!e)return cW;const t=e.phases.filter(n=>uW.has(n));return new Set([...t,"paused","stopped","unknown"])}const fW={needs_you:3,working:3,waiting_on:2,scheduled:2,done:3};function po(e){return s.jsx("span",{className:`mc_sk${e.className?` ${e.className}`:""}`,style:e.width?{width:e.width}:void 0,"aria-hidden":"true"})}function hW(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(po,{className:"mc_sk_title",width:n%2?"72%":"58%"}),s.jsx(po,{className:"mc_sk_pill"})]}),s.jsx(po,{width:"88%"}),s.jsx(po,{width:"46%"})]},n))})}function ym(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(po,{width:e.width||"84%"})})}const mW="mc_entities mc_entities_reserved",_W="mc_entities mc_entities_empty",pW=4,LC=12;function gW(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(po,{className:"mc_sk_title",width:n%2?"64%":"48%"}),s.jsx(po,{className:"mc_sk_chip"}),s.jsx(po,{width:"70%"}),s.jsx(po,{width:"42%"}),s.jsx(po,{width:"56%"})]}),s.jsx(po,{className:"mc_sk_hints",width:"120px"})]},n))})}const rl={},yW=["needs_you","working","waiting_on"];function wW(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 IC(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,c=0;const l=[];for(const h of i){if(!h.length)continue;if(n!=null&&n.batch){const g=o,y=c;let x=[];try{x=await n.batch(h,(k,v)=>{var N;return(N=n.on_progress)==null?void 0:N.call(n,g+k,y+v)})}catch(k){x=h.map(v=>({run_id:v,error:String((k==null?void 0:k.message)||k||"cancel failed")}))}for(const k of x)o+=1,k.error&&(c+=1,l.push({run_id:k.run_id,error:k.error}));(d=n.on_progress)==null||d.call(n,o,c);continue}let m=0;const _=async()=>{var g;for(;m<h.length;){const y=h[m++],x=await Kx(t,y);o+=1,x.type==="failed"&&(c+=1,l.push({run_id:y,error:x.error})),(g=n==null?void 0:n.on_progress)==null||g.call(n,o,c)}};await Promise.all(Array.from({length:Math.min(r,h.length)},_))}return{done:o,failed:c,failures:l}}function vW(e,t,n,r=0){const i=n??t,o=`Cancel all ${i} task${i===1?"":"s"} in ${SC[e]}`;return i<t||r>0?`${o} (${t} run${t===1?"":"s"} asked)`:o}function xW(e,t,n,r){const[i,o]=p.useReducer(wW,{phase:"idle"}),c=t.length,l=r==null?void 0:r.targets,d=l?l.ids:[...t],h=d.length,m=!!n&&c>0&&yW.includes(e),_=vW(e,l?l.cards:c,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 IC(d,n,{batch:r==null?void 0:r.on_cancel_runs,waves:l==null?void 0:l.waves,on_progress:(y,x)=>o({type:"progress",done:y,failed:x})}),o({type:"finish"}),window.setTimeout(()=>o({type:"dismiss"}),4e3))}}}function bW(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 kW(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:RW}),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 jW(e){var i,o,c,l,d;(i=rl.lane)==null||i.call(rl,e.col);const t=`mc_column_title_${e.col}`,n=xW(e.col,((o=e.cancel)==null?void 0:o.run_ids)??[],(c=e.cancel)==null?void 0:c.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(bW,{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(kW,{state:n.state,label:n.label,on_run:()=>void n.run(),on_keep:n.keep}):null,e.children]})}const Ds=e=>e.stopPropagation(),SW=typeof window>"u"?p.useEffect:p.useLayoutEffect;function NW(e){const{line:t}=e.card;if(t.actor==="run"){const n=e.card.actor_run_label,r=n&&!t.text.includes(n)?`run ${va(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:Ds,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 $W(){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 Vx(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 Tm(e.text)?"copied":"failed"),window.setTimeout(()=>n(""),1500)},onKeyDown:Ds,children:t==="copied"?"copied":t==="failed"?"copy failed":s.jsx($W,{})})}const CW=320,EW=6;function AW(e){const[t,n]=p.useState(!1),r=e.text,i=r.length>CW||r.split(`
169
+ `).length>EW;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 TW(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,c)=>s.jsx("code",{className:"mc_tag",children:o},`${o}:${c}`))}):null,n||!t.value?null:t.long?s.jsx(AW,{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(Vx,{text:t.copy??t.value,label:(t.label||"value").toLowerCase()}):null})]})}function Tj(e,t){var d,h;const n=new Map;for(const m of t){const _=Qs(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 c=0,l=0;for(const m of i){if(r(m))continue;c+=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:c,tasks:o.length,runs:c,parents:l}}const MW="Cancel this task: this run, its parents below the automation, and everything working under them";function OC(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 RW="Everything working under those tasks stops too; automation schedules are not touched.";function LW(e){const[t,n]=p.useState(e.current),[r,i]=p.useState(!1),[o,c]=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),c("");try{await e.on_rename(e.automation_id,d,e.revision),c("renamed"),(m=e.on_renamed)==null||m.call(e,e.automation_id)}catch(_){c(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 PC(e){var i;const t=qx(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:z9(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:Ds,onKeyDown:Ds,children:r?s.jsx(qe,{name:"terminal",size:15}):"Open in Code"}):s.jsx("span",{className:"mc_btn_wrap",title:Sj,children:s.jsx("button",{type:"button",className:r?"btn mc_icon_btn":"btn mc_btn_sm mc_btn_quiet",disabled:!0,title:Sj,"aria-label":"Open in Code",children:r?s.jsx(qe,{name:"terminal",size:15}):"Open in Code"})})}function Hx(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 Gx={phase:"idle",error:""};async function Kx(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 Jx(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 DC(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:MW,"aria-label":"Cancel this task",onClick:()=>e.on_event({type:"ask"}),children:e.variant==="icon"?s.jsx(qe,{name:"x",size:15}):"Cancel"})}function IW(e){return s.jsxs(s.Fragment,{children:[e.state.phase==="idle"?DC(e):null,Jx(e)]})}function OW(e){var o;const[t,n]=p.useReducer(Hx,Gx),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 FC(e.on_cancel_run,e.run_id,r,e.on_cancel_runs))};return s.jsx(IW,{state:t,on_event:n,on_send:()=>void i(),variant:e.variant,question:OC(r,e.run_id)})}async function FC(e,t,n,r){var o;if(!n||n.ids.length<=1)return Kx(e,(n==null?void 0:n.ids[0])||t);const i=await IC(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 PW(e){const{card:t}=e,n=t.automation,r=Q9(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,c=!!(o||!i&&e.on_open_run||qx(t)||Nj(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(TW,{row:d}),l.id==="automation"&&d.id==="title"&&(n!=null&&n.can_revise)?s.jsx(LW,{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,c?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(PC,{card:t,code_app:e.code_app}),Nj(t)&&e.on_cancel_run?s.jsx(OW,{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 DW=500,FW=580;let hu=null;function ba(){hu!==null&&window.clearTimeout(hu),hu=null}function Mj(e,t=DW){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 c=Math.min(Math.max(8,n.right-i),r-i-8);return{top:n.bottom+6,left:c,width:i,side:!1}}function zW(e){const{anchor:t,on_close:n,on_hover:r,...i}=e;return s.jsx(zC,{anchor:t,on_close:n,on_hover:r,label:`About ${e.card.title.text}`,children:s.jsx(PW,{...i})})}function zC(e){const t=p.useRef(null),n=e.width,[r,i]=p.useState(()=>e.anchor.current?Mj(e.anchor.current,n):null),o=p.useRef(e);return o.current=e,SW(()=>{var g;const c=t.current,l=(g=e.anchor.current)==null?void 0:g.getBoundingClientRect();if(!c||!l||!r)return;const d=c.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 c=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(Mj(h,o.current.width))};return document.addEventListener("keydown",c,!0),document.addEventListener("pointerdown",l,!0),window.addEventListener("resize",d),window.addEventListener("scroll",d,!0),()=>{document.removeEventListener("keydown",c,!0),document.removeEventListener("pointerdown",l,!0),window.removeEventListener("resize",d),window.removeEventListener("scroll",d,!0)}},[]),r?bg.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:Ds,onKeyDown:Ds,children:e.children}),document.body):null}function BW(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(Vx,{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(Ni,{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 Bp(e){const[t,n]=p.useState(""),r=p.useRef(null),i=()=>{ba(),hu=window.setTimeout(()=>n(c=>c==="hover"?"":c),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:()=>{ba(),t||(hu=window.setTimeout(()=>n(c=>c||"hover"),150))},onMouseLeave:()=>t==="hover"?i():ba(),onClick:c=>{c.stopPropagation(),ba(),n(t==="pinned"?"":"pinned")},children:e.children}),t&&typeof document<"u"?s.jsx(zC,{anchor:r,label:`The full ${o}`,width:FW,className:"mc_pop_text",on_close:()=>n(""),on_hover:c=>c?ba():t==="hover"?i():void 0,children:s.jsx(BW,{kind:e.kind,text:e.full,about:e.about,on_open:e.on_open,on_close:()=>n("")})}):null]})}function UW(e){const[t,n]=p.useState(""),r=p.useRef(null),i=()=>{ba(),hu=window.setTimeout(()=>n(c=>c==="hover"?"":c),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:c=>{c.stopPropagation(),ba(),n(t==="pinned"?"":"pinned")},onKeyDown:Ds,onMouseEnter:()=>{ba(),t||(hu=window.setTimeout(()=>n(c=>c||"hover"),150))},onMouseLeave:()=>t==="hover"?i():ba(),children:s.jsx(qe,{name:"info",size:15})}),t&&typeof document<"u"?s.jsx(zW,{...e,anchor:r,on_close:c=>{var l;n(""),c&&((l=r.current)==null||l.focus())},on_hover:c=>c?ba():t==="hover"?i():void 0}):null]})}function WW(e){const t=e.title.text;if(e.subject.kind==="agent"||e.subject.kind==="run"){const r=ni(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:Ds,onKeyDown:Ds,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 jw(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 Bv(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 qW(e){const{card:t}=e,n=t.automation,[r,i]=p.useReducer(G9,H9),o=n?RC(n,e.now_ms):null,c=n?K9(n,r):null,l=n?W9({...n,growing_max_tokens:c}):null,d=!!(n!=null&&n.can_revise&&e.on_revise_automation),h=V9(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}),J9(g,n.automation_id,e.revision??null,_).then(y=>{var x;i(y),y.type==="saved"&&((x=e.on_renamed)==null||x.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(Bv,{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(Bv,{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(ym,{what:"the schedule",width:"90%"}),s.jsx(ym,{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:Ds,onKeyDown:Ds,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 ${(c==null?void 0:c.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:[U9.map(_=>s.jsx("button",{type:"button",className:`btn mc_btn_sm${_===c?" is_current":" mc_btn_quiet"}`,"aria-pressed":_===c,title:`${_.toLocaleString("en-US")} tokens`,onClick:()=>m(_),children:lc(_)},_)),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 VW={busy:"",error:""},Rj={enabled:!1,reason:"commands are not wired on this host"},HW={enabled:!0},GW="Stop this subrun and everything under it? Its parent continues and may delegate again",KW="Stop this subrun and everything under it: its parent continues and may delegate again";function JW(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?` ${er(e.ended_ms)} ago`:"";return`its subrun ${e.subrun} ${t}${n} and this run was not resumed`}function UC(e){const t=typeof e.since_ms=="number"?` since ${ic(fu(e.since_ms,e.now_ms))} ${ic(`(${er(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:Ds,children:e.name})," ",s.jsxs("span",{className:"mc_ask_words",children:["stuck",t]})]}),s.jsxs("div",{className:"mc_stuck_why",children:[YW(JW(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 YW(e){return e&&e[0].toUpperCase()+e.slice(1)}function XW(e){const{row:t}=e,[n,r]=p.useReducer(Hx,Gx),i=async()=>{e.on_cancel_run&&(r({type:"send"}),r(await Kx(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:Ds,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:KW,"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:Jx({state:n,on_event:r,on_send:()=>void i(),question:GW})}):null]})}function ZW(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:Ds,onKeyDown:Ds,children:[t.chain.map((o,c)=>s.jsx(XW,{row:o,on_open_run:e.on_open_run,on_cancel_run:e.on_cancel_run},o.run_id||`more-${c}`)),t.asks.map(o=>{var h;const c=(h=e.ask_detail)==null?void 0:h[o.run_id],l=TC(o,c),d=Wx(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:Ds,children:Fg(o.workflow_id)||Zd(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(ym,{what:"the request"}):l?s.jsx(Bp,{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:c,busy:i(o)})]},o.run_id)}),n?s.jsx(UC,{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 QW(e){var V,M;const{card:t}=e;(V=rl.card)==null||V.call(rl,t.run_id);const[n,r]=p.useReducer(Hx,Gx),[i,o]=p.useState(VW),c=t.status_word,l=WW(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?TC(t,e.detail):null,y=d?null:F9(t,e.outcome),x=MC(t,e.outcome),k=m?Wx(t,e.now_ms):null,v=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 FC(E,t.run_id,S,e.on_cancel_runs)))},D=A=>{!e.on_automation_command||i.busy||(o({busy:A,error:""}),X9(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?Y9(t.automation,i.busy!==""):null,I=n.phase!=="idle"||n.error||i.error,G=!(d||_&&(!!qx(t)||!!E))&&x.length>0,K=x.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(Bv,{parts:x})}):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(po,{className:"mc_sk_title",width:"64%"})}):h||t.task?s.jsxs(Bp,{kind:"task",text:t.title.text,full:t.task||wg(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(_b,{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:wg(t),children:[t.title.text,t.title.untitled?s.jsxs(s.Fragment,{children:[" ",s.jsx(_b,{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 ${Sa(c)}`,children:c==="unknown"?"?":c})]}),(l.label||l.secondary||t.archived)&&!(h&&!l.label&&!t.archived&&t.chain[0]&&(l.secondary===t.chain[0].name||l.secondary===ni(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(qW,{...e}):h?s.jsx(ZW,{...e,on_cancel_task:E?()=>r({type:"ask"}):void 0}):N?s.jsx(ym,{what:"the answer"}):y?s.jsx(Bp,{kind:"answer",text:y.text,full:y.full,about:t.title.text,on_open:()=>e.on_open_run(t.run_id),children:s.jsx(Ni,{text:y.text,images:"link",className:"mc_glimpse_md"})}):s.jsxs("div",{className:"mc_card_state",children:[s.jsx(NW,{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 ${er(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:Ds,children:"Inspect →"})]}):null]}),v?s.jsx(ym,{what:"the request"}):g?s.jsx(Bp,{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(UC,{run_id:t.run_id,name:Fg(t.workflow_id)||Zd(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:Ds,onKeyDown:Ds,children:[Jx({state:n,on_event:r,on_send:()=>void P(),question:OC(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:Ds,onKeyDown:Ds,children:[d&&R?s.jsxs(s.Fragment,{children:[s.jsx(jw,{state:e.on_open_automation?HW:{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(jw,{state:e.on_automation_command?R.run_now:Rj,label:"Run now",icon:"playCircle",busy:i.busy==="automation.run_now",onClick:()=>D("automation.run_now")}),s.jsx(jw,{state:e.on_automation_command?R.toggle.state:Rj,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(PC,{card:t,code_app:e.code_app,variant:"icon"}):null,E?n.phase==="idle"?DC({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(Vx,{text:t.run_id,label:"the run id",title:t.run_id}),s.jsx(UW,{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 Lj=new WeakMap;let Ij=0;function eq(e){if(!e||typeof e!="object")return String(e??"");let t=Lj.get(e);return t===void 0&&(Ij+=1,t=Ij,Lj.set(e,t)),`#${t}`}function tq(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function nq(e,t){const n=e.line,r=e.row||{},i=e.role==="controller"&&e.automation?RC(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,wg(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"?er(n.stale_ms):"",e.tool_names.join(","),tq(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=>Uv(o,t)).join("|"),String(e.stuck),e.since_ms,e.next_fire_ms,MC(e).join("·"),e.llm_calls,r.session_id,r.actor_id,r.pause_reason,r.created_at,r.updated_at,r.status,eq(e.automation),e.lane==="needs_you"?Wx(e,t).text:"",i?`${i.schedule.text}|${i.schedule.title}|${i.last.text}|${i.last.title}`:""].join("")}const Oj=new WeakMap;function Uv(e,t){const n=Oj.get(e);if(n&&n.now_ms===t)return n.sig;const r=nq(e,t);return Oj.set(e,{now_ms:t,sig:r}),r}function sq(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]||{},c=Object.keys(i),l=Object.keys(o);if(c.length!==l.length||c.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:Uv(e.card,e.now_ms)===Uv(t.card,t.now_ms)}const rq=Ee.memo(QW,sq),Sw=8;function iq(e){var ze,He,ct,Qe,Dt,$e,Le,ce;(ze=rl.page)==null||ze.call(rl);const t=Date.now(),[n,r]=p.useState(()=>$C(I9())),i=p.useMemo(()=>L9(e.runs,e.all_runs),[e.runs,e.all_runs]),o=p.useMemo(()=>[...i.active,...i.done],[i]),c=s9(e.client,o),l=i9(e.client,i.active),d=_9(),h=p.useMemo(()=>Object.fromEntries(xp.map(Q=>[Q,_e=>d.attach(Q,_e)])),[d.attach]),[m,_]=p.useState(""),[g,y]=p.useState(""),[x,k]=p.useState(!1),[v,N]=p.useState(()=>{try{const Q=localStorage.getItem("abstractobserver_done_window_v1");return Q&&Q in zv?Q:Cj}catch{return Cj}}),$=p.useMemo(()=>jj({active:i.active,done:i.done,pulses:l.map,automations:c.map,now_ms:Date.now(),stall_after_ms:n}),[i,l.map,c.map,n]),E=p.useMemo(()=>Ej($.done,v,Date.now()).visible,[$,v]),S=p.useMemo(()=>(x?E:E.slice(0,Sw)).map(Q=>Q.row),[E,x]),P=p.useMemo(()=>_j(xp.map(Q=>Q==="done"?S:$[Q].flatMap(_e=>[_e.row,..._e.asks.map(le=>le.row)])),d.visible),[$,S,d.visible]),D=a9(e.client,P,i.active),R=p.useMemo(()=>new Set(i.active.map(Q=>Qs(Q))),[i.active]),I=l9(e.client,D.map,R),W=r9(e.client,P),G=p.useMemo(()=>_j([S],d.visible),[S,d.visible]),K=m9(e.client,G),V=p.useRef(new WeakMap),M=p.useMemo(()=>{const Q=new Map;for(const[_e,le]of c.records){const Se=le.raw&&typeof le.raw=="object"?le.raw:null;let pe=Se?V.current.get(Se):void 0;pe||(pe=n9(le.raw),Se&&V.current.set(Se,pe)),Q.set(_e,pe)}return Q},[c.records]),A=p.useMemo(()=>W.map.size||D.map.size?jj({active:i.active,done:i.done,details:D.map,fates:I.map,pulses:l.map,automations:c.map,run_briefs:W.map,now_ms:Date.now(),stall_after_ms:n}):$,[$,W.map,i,D.map,l.map,c.map,n]),O=p.useMemo(()=>Ej(A.done,v,t),[A.done,v]),L=xp.map(Q=>A[Q].map(_e=>[_e.run_id,..._e.asks.map(le=>le.run_id)].join("+")).join(",")).join("|")+`|${x}|${v}`;p.useEffect(()=>{d.refresh()},[L,d.refresh]);const[H,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=>Tj([Q],xe.current),act:(Q,_e)=>void je.current(Q,_e),resume:Q=>void ae.current(Q)}),[]),Ve=String(((He=e.code_app)==null?void 0:He.url)||"").trim(),mt=p.useMemo(()=>Ve?{url:Ve}:null,[Ve]),nt=p.useMemo(()=>Q=>{c.invalidate(Q),window.setTimeout(()=>c.invalidate(Q),2e3)},[c.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?c.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?c.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?_W:mW,"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(ol,{what:"entities"}),s.jsx(gW,{n:e.entities_total?Math.min(e.entities_total,LC):pW})]}):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=lW(_e,e.phase_graph),Se=dW(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=nW(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?` · ${bw(t-_e,t)} ago`:""]}):_e===null?null:_e<=sW?s.jsx("span",{className:"mc_entity_live",title:`last moment ${bw(t-_e,t)} ago`,children:"● active"}):s.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[bw(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: ${lc(Q.live_visit_tokens)} tk`:""}${Q.spend_warning?`; ${Q.spend_warning}`:""}`,children:[lc(Q.tokens_total)," tk",Q.live_visit_tokens!==null?` (+${lc(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":H===Q.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>J(H===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(!H)return null;const Q=ne.find(Se=>Se.name===H);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(xy,{kind:"question",label:Se.title||kw(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(xy,{kind:"problem",label:Se.title||kw(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(xy,{kind:"lesson",label:Se.title||kw(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(tc,{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 ",M9(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:xp.map(Q=>{const _e=Q==="done"?O.visible:A[Q],le=Q==="done"&&!x?_e.slice(0,Sw):_e,Se=e.runs_refreshed_at===null||Q==="done"&&e.done_loaded===!1;return s.jsxs(jW,{col:Q,title:SC[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:Tj(_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(NC,String(dt))}catch{}},children:Ux.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:v,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(zv).map(pe=>s.jsx("option",{value:pe,children:vw[pe]},pe))}):null,children:[s.jsx("div",{className:"mc_column_hint muted",children:$9[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(ol,{what:Q==="done"&&e.runs_refreshed_at!==null?"finished runs":"runs"}),s.jsx(hW,{n:fW[Q]})]}):null,le.map(pe=>s.jsx(rq,{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 ${vw[v]} — ${O.hidden_count} older`:C9[Q]}):null,Q==="done"&&_e.length>Sw&&!x?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 ",vw[v]]}):null]})]},Q)})})]})}function Et(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ln(e){return typeof e=="string"?e.trim():""}function Gn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Up(e){return typeof e=="boolean"?e:null}function ei(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():String(t??"").trim()).filter(Boolean):null}function Pj(e){return typeof e=="string"?e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean):ei(e)}function mu(e,t){return!!e&&Object.prototype.hasOwnProperty.call(e,t)}function os(e){return Math.round(e).toLocaleString("en-US")}function WC(e){const t=Et(e);return!!t&&(mu(t,"definition")||mu(t,"summary"))}function oq(e,t,n){var v,N,$,E;const r=Et((v=Et(t))==null?void 0:v.input_data),i=Et((N=Et(t))==null?void 0:N.workspace),o=WC(n)?n:null,c=o?Mm(o):n??null,l=Et(o==null?void 0:o.definition),d=Et(($=Et(l==null?void 0:l.target))==null?void 0:$.input_data),h=Et(d==null?void 0:d._runtime),m=Et(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]="",[]},x=(S,...P)=>{for(const[D,R]of P){const I=Gn(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",c==null?void 0:c.model]),provider:g("provider",["run",r==null?void 0:r.provider],["automation",d==null?void 0:d.provider],["automation",c==null?void 0:c.provider]),tools:y("tools",ei,["run",r==null?void 0:r.tools],["automation",d==null?void 0:d.tools],["automation",k(c==null?void 0:c.tools)]),tool_approval:g("tool_approval",["automation",m==null?void 0:m.tool_approval],["automation",c==null?void 0:c.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=Et(e))==null?void 0:E.workspace_root],["run",i==null?void 0:i.workspace_root],["run",r==null?void 0:r.workspace_root],["automation",c==null?void 0:c.workspace_root],["automation",d==null?void 0:d.workspace_root]),workspace_allowed_paths:y("workspace_allowed_paths",Pj,["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",Pj,["run",i==null?void 0:i.workspace_ignored_paths],["automation",d==null?void 0:d.workspace_ignored_paths]),allowed_tools:y("allowed_tools",ei,["automation",h==null?void 0:h.allowed_tools]),max_iterations:x("max_iterations",["run",r==null?void 0:r.max_iterations],["automation",d==null?void 0:d.max_iterations],["automation",c==null?void 0:c.max_iterations]),untrusted_input_tools:y("untrusted_input_tools",ei,["automation",m==null?void 0:m.untrusted_input_tools]),email_allowed_recipients:y("email_allowed_recipients",ei,["automation",m==null?void 0:m.email_allowed_recipients]),source:_}}function qC(e){const t=Et(e);if(!t)return null;if(Array.isArray(t.nodes))return t;const n=Et(t.flow);return n&&Array.isArray(n.nodes)?n:null}function Wv(e){const t=Et(e==null?void 0:e.data)||{};return ln(t.nodeType)||ln(e==null?void 0:e.type)}const aq=new Set(["exec-out","exec-in","exec"]);function qv(e,t){const n=Et(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=Et(i);if(!o)return!1;const c=ln(o.id);return!!c&&ln(o.type)!=="execution"&&!aq.has(c)})}function Dj(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 Fj(e,t,n){return{id:e,label:e,type:"any",typed:!1,required:!1,description:"",state:t,value:n,flow_default:null}}function lq(e,t,n){var R;const r=qC(e),i=r?r.nodes:[],o=i.find(I=>Wv(I)==="on_flow_start")||null,c=i.filter(I=>Wv(I)==="on_flow_end"),l=Et(t),d=Et(l==null?void 0:l.input_data),h=Et((R=Et(o==null?void 0:o.data))==null?void 0:R.pinDefaults)||{},m=[],_=new Set,g=I=>d?mu(d,I)?{state:"value",value:d[I]}:{state:"not_provided",value:void 0}:{state:"unknown",value:void 0};for(const I of o?qv(o,"outputs"):[]){const W=ln(I.id);if(_.has(W))continue;_.add(W);const{state:G,value:K}=g(W),V=G==="not_provided"&&mu(h,W)?{value:h[W]}:null;m.push(Dj(I,G,K,V))}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(Fj(W,G,K))}const y=d?Object.keys(d).filter(I=>!_.has(I)).map(I=>[I,d[I]]):[],x=Et(n),k=!!x&&hs(x.status),v=x?x.output:void 0,N=Et(v),$=I=>x?N&&mu(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 c)for(const W of qv(I,"inputs")){const G=ln(W.id);if(S.has(G))continue;S.add(G);const{state:K,value:V}=$(G);E.push(Dj(W,K,V,null))}const P=c.length>0&&S.size===0;let D=[];if(P){const I=!!x&&v!==null&&v!==void 0;E.push(Fj("output",x?I?"value":"absent":"unknown",I?v:void 0))}else N?D=Object.keys(N).filter(I=>!S.has(I)).map(I=>[I,N[I]]):x&&v!==null&&v!==void 0&&(D=[["output",v]]);return{inputs:m,outputs:E,also_sent:y,also_returned:D,end_is_passthrough:P,flow_found:!!r,start_found:!!o,end_found:c.length>0,outputs_final:k}}function Nw(e,t,n=`${t}s`){return e===1?t:n}function cq(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 ${os(e.replayed_messages)} of ${os(r)} ${Nw(r,"message")}`:`replayed ${os(e.replayed_messages)} ${Nw(e.replayed_messages,"message")}`;e.replayed_tokens!==null?i+=` (${os(e.replayed_tokens)}${e.max_tokens!==null?` of ${os(e.max_tokens)}`:""} tokens)`:e.max_tokens!==null&&(i+=` (budget ${os(e.max_tokens)} tokens)`),t.push(i)}else e.max_tokens!==null&&t.push(`history budget ${os(e.max_tokens)} tokens`);if(e.dropped_messages!==null)if(e.dropped_messages>0){const r=e.dropped_tokens!==null&&e.dropped_tokens>0?` (${os(e.dropped_tokens)} tokens)`:"";t.push(`${n?"":"at least "}${os(e.dropped_messages)} older ${Nw(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 Vv(e){var l;const t=Et(e),n=Et(t==null?void 0:t.session_history),r=Et((l=Et(t==null?void 0:t.limits))==null?void 0:l.tokens);let i=null;if(r){const d=Gn(r.estimated_used),h=Gn(r.max_tokens),m=Gn(r.max_input_tokens),_=m??h,g=Gn(r.pct),y=g!==null?g*100:d!==null&&_!==null&&_>0?d/_*100:null,x=Gn(r.warn_tokens_pct);i={used:d,max_tokens:h,max_input_tokens:m,budget:_,pct:y,warn_pct:x,over_warn:y!==null&&x!==null&&y>=x}}const o=(ei(t==null?void 0:t.flow_warnings)||[]).filter(Boolean),c={replayed_messages:Gn(n==null?void 0:n.replayed_messages),replayed_tokens:Gn(n==null?void 0:n.replayed_tokens),max_tokens:Gn(n==null?void 0:n.max_tokens),dropped_messages:Gn(n==null?void 0:n.dropped_messages),dropped_tokens:Gn(n==null?void 0:n.dropped_tokens),dropped_counts_complete:Up(n==null?void 0:n.dropped_counts_complete),oversize_turn_kept:Up(n==null?void 0:n.oversize_turn_kept)};return{has_history:!!n,policy:ln(n==null?void 0:n.policy),...c,strict:Up(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?cq(c):""}}const uq=16;function ji(e){return String((e==null?void 0:e.run_id)||"").trim()}function Hv(e){return String((e==null?void 0:e.role)||"").trim()}function zj(e){return Vt(e.created_at||e.updated_at||"")??0}function dq(e,t){const n=String(e||"").trim();let r=t.get(n);if(!r)return n;const i=new Set;for(;r;){const o=ji(r);if(i.add(o),Hv(r)==="occurrence")return o;const c=String(r.parent_run_id||"").trim(),l=c?t.get(c):void 0;if(!l||i.has(c)||Hv(l)==="controller")return o;r=l}return n}function VC(e,t){const n=String(e||"").trim(),r=new Map,i=new Map;for(const y of t||[]){const x=ji(y);x&&r.set(x,y)}for(const y of r.values()){const x=String(y.parent_run_id||"").trim();if(!x||x===ji(y))continue;const k=i.get(x)||[];k.push(y),i.set(x,k)}if(!r.has(n))return{subject_id:n,root:null,controller:null,controller_id:"",subject_found:!1,size:0};const o=dq(n,r),c=r.get(o);let l=0;const d=new Set,h=(y,x)=>{const k=ji(y);d.add(k),l+=1;const v=x<uq?[...i.get(k)||[]].filter(N=>!d.has(ji(N))):[];return v.sort((N,$)=>zj(N)-zj($)||ji(N).localeCompare(ji($))),{run:y,depth:x,is_subject:k===n,children:v.map(N=>h(N,x+1))}},m=h(c,0);let _=null,g="";return Hv(c)==="occurrence"&&(g=String(c.parent_run_id||c.automation_id||"").trim(),_=g&&r.get(g)||null),{subject_id:n,root:m,controller:_,controller_id:g,subject_found:!0,size:l}}function HC(e){const t=[],n=r=>{t.push(r);for(const i of r.children)n(i)};return e&&n(e),t}function fq(e,t,n=Date.now()){const r=e&&"children"in e?e:(e==null?void 0:e.root)??null,i=new Map;for(const c of t||[]){const l=ji(c);l&&i.set(l,c)}const o=HC(r).map(c=>{const l=ji(c.run),d=i.get(l)??c.run,h=Gn(d==null?void 0:d.tokens_total),m=Gn(d==null?void 0:d.llm_calls),_=Gn(d==null?void 0:d.tool_calls),g=Gn(d==null?void 0:d.steps),y=Am(c.run,n),x=String(c.run.status||"").trim().toLowerCase();return{run_id:l,depth:c.depth,workflow_id:String(c.run.workflow_id||"").trim(),status:x,is_subject:c.is_subject,duration_ms:y>=0?y:null,running:!hs(x),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(c=>c.has_metrics)}}function gn(e,t){return{value:e,source:t,why:""}}function ts(e,t=""){return{value:null,source:t,why:e}}const Ps={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 Md(e){return`${new Date(e).toISOString().slice(0,19).replace("T"," ")} UTC`}function hq(e){var r,i,o,c;const t=$m(e),n=Et((o=Et((i=Et((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((c=Et(n==null?void 0:n.payload))==null?void 0:c.model)}}function mq(e){var c,l,d,h,m;const t=Et((l=Et((c=e.started)==null?void 0:c.effect))==null?void 0:l.payload),n=Et((h=Et((d=e.record)==null?void 0:d.effect))==null?void 0:h.payload),r=Et(t==null?void 0:t.vars)&&!((m=Et(t==null?void 0:t.vars))!=null&&m.$slim)?Et(t==null?void 0:t.vars):Et(n==null?void 0:n.vars),i=Et(r==null?void 0:r._runtime),o=Et(r==null?void 0:r._limits);return{run_id:Em(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:ei(i==null?void 0:i.allowed_tools),max_iterations:Gn(o==null?void 0:o.max_iterations)}}function _q(e,t,n=[]){var _,g,y,x,k,v,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 c=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 Ig(e,$)){E.steps+=1;const P=Vt(S.started_at),D=Vt(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=hq(S),I=`${R.provider}\0${R.model}`,W=c.get(I)||{provider:R.provider,model:R.model,calls:0,run_ids:[]};W.calls+=1,W.run_ids.includes($)||W.run_ids.push($),c.set(I,W)}else if(S.kind==="tool"){const R=Cm(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 V=Math.max(K.calls,K.results);E.tool_calls+=V,E.tool_failures+=K.failures;const M=l.get(G)||{name:G,calls:0,failures:0,run_ids:[],outside_declared:null};M.calls+=V,M.failures+=K.failures,M.run_ids.includes($)||M.run_ids.push($),l.set(G,M)}const W=ei((x=Et((y=(g=S.started)==null?void 0:g.effect)==null?void 0:y.payload))==null?void 0:x.allowed_tools)??ei((N=Et((v=(k=S.record)==null?void 0:k.effect)==null?void 0:v.payload))==null?void 0:N.allowed_tools);W!==null&&r.allowlist===null&&(r.allowlist=W)}else if(S.kind==="subflow"){const R=mq(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=[...c.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 jp(e,t){for(const[n,r]of e)if(r!=null)return gn(r,n);return ts(t)}function Cd(e){const t=ln(e);return t||null}function tu(e,t){const n=ln(e),r=ln(t);return n||r?{provider:n,model:r,calls:null}:null}const pq=new Set(["controller","occurrence","descendant","discussion"]);function gq(e,t,n,r,i,o,c=Date.now(),l={}){var hn,sn,Ht,is,Be,Qt,Mt,Fn,fn;const d=Et(e),h=Et(t),m=Et(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),x={...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]!==""&&(x[Xe]=d[Xe]);const k=WC(r)?r:null,v=k?Mm(k):r??null,N=Et(k==null?void 0:k.definition),$=Et(k==null?void 0:k.summary),E=Et((sn=Et(N==null?void 0:N.target))==null?void 0:sn.input_data),S=Et(E==null?void 0:E._runtime),P=Et(N==null?void 0:N.policy),D=ln(x.role),R=!!ln(x.automation_id)||pq.has(D)||ln(x.session_kind)==="automation",I=R?v?Ps.wire:Ps.automation_not_loaded:Ps.not_automation,W=qC(n),G=W&&W.nodes.find(Xe=>Wv(Xe)==="on_flow_start")||null,K=Et((Ht=Et(G==null?void 0:G.data))==null?void 0:Ht.pinDefaults),V=new Set(G?qv(G,"outputs").map(Xe=>ln(Xe.id)):[]),M=Xe=>m&&mu(m,Xe)?void 0:K&&mu(K,Xe)?K[Xe]:void 0,A=VC(_,g),O=HC(A.root).filter(Xe=>ji(Xe.run)!==_&&yq(Xe,_,A.root)).map(Xe=>ji(Xe.run)),L=_q(i,_,O),H=L.loaded?Ps.ledger_no_records:Ps.ledger_not_loaded,J=L.loaded&&L.subject_found,U=oq(e,t,k??v),te=Xe=>U.source[Xe]==="run"?"run":U.source[Xe]==="automation"?"automation":"",z=Et(d==null?void 0:d.output),ne=Et(z==null?void 0:z.meta),se=ln(x.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:ni(se),version:de,flow_name:ln(W==null?void 0:W.name)},"run"):ts(Ps.wire),Me=R?v?gn({kind:"automation",title:v.title,id:v.automation_id},"automation"):ts(Ps.automation_not_loaded):ln(x.session_id)?gn({kind:"session",title:"",id:ln(x.session_id)},"run"):gn({kind:"run",title:"",id:_},"run"),je=ln(x.parent_run_id),ae=je?y(je):void 0,xe=Gn(x.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=Gn(ae==null?void 0:ae.occurrence_index);Ae=`subrun of ${Xe==="occurrence"&&nn!==null?`run #${nn}`:ni(ln(ae==null?void 0:ae.workflow_id))||"a parent run (row not loaded)"}`}else Ae=ln(x.session_id)?"run in a session":"top-level run";const Ve=gn({text:Ae,parent_run_id:je},"run"),nt=[["run",tu(m==null?void 0:m.provider,m==null?void 0:m.model)],["flow default",tu(M("provider"),M("model"))],["automation",tu(E==null?void 0:E.provider,E==null?void 0:E.model)],["automation",tu(S==null?void 0:S.provider,S==null?void 0:S.model)],["automation",k?null:tu(v==null?void 0:v.provider,v==null?void 0:v.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"):tu(ne==null?void 0:ne.provider,ne==null?void 0:ne.model)?rt=gn([tu(ne==null?void 0:ne.provider,ne==null?void 0:ne.model)],"output"):nt?rt=gn([nt[1]],nt[0]):rt=ts(Ps.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 He=m&&typeof m.system=="string"?gn(m.system,"run"):W?Cd(M("system"))!==null?gn(String(M("system")),"flow default"):V.has("system")?ts("none declared: not provided and the flow has no default","flow"):ts("the flow has no system pin","flow"):ts(Ps.flow_not_loaded),ct=jp([["run",m&&typeof m.prompt=="string"&&m.prompt.trim()?m.prompt:null],["run",Cd((is=Et(m==null?void 0:m.context))==null?void 0:is.task)],["flow default",Cd(M("prompt"))],["automation",Cd(E==null?void 0:E.prompt)],["automation",k?null:Cd(v==null?void 0:v.task)]],Ps.no_default),Qe=jp([["run",ei(m==null?void 0:m.tools)],["flow default",ei(M("tools"))],["automation",ei(E==null?void 0:E.tools)],["automation",ei(S==null?void 0:S.allowed_tools)],["automation",k?null:(Be=v==null?void 0:v.tools)!=null&&Be.length?v.tools:null]],Ps.no_default),Dt=((Qt=L.subruns.find(Xe=>Xe.allowed_tools!==null))==null?void 0:Qt.allowed_tools)??null,$e=jp([["used",J?L.allowlist:null],["used",J?Dt:null],["automation",ei(S==null?void 0:S.allowed_tools)],["automation",k?null:(v==null?void 0:v.allowed_tools)??null]],R?I:J?"the ledger shows no enforced allowlist":H),Le=Qe.value,ce=J?gn(L.tools.map(Xe=>({...Xe,outside_declared:Le===null?null:!Le.includes(Xe.name)})),"used"):ts(H),Q=(Xe,nn)=>Xe!==null&&U.source[nn]?gn(Xe,te(nn)):ts(I),_e=Q(Cd(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)):ts(Ps.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(_)||x,_t=J?gn(L.llm_calls,"used"):Gn(yt==null?void 0:yt.llm_calls)!==null?gn(Gn(yt.llm_calls),"listing"):ts(H),It=J?gn({calls:L.tool_calls,failures:L.tool_failures},"used"):Gn(yt==null?void 0:yt.tool_calls)!==null?gn({calls:Gn(yt.tool_calls),failures:null},"listing"):ts(H),bt=A.root?((Mt=vg(A.root,_))==null?void 0:Mt.children)||[]:[],St=J?gn(L.subruns,"used"):bt.length?gn(bt.map(Xe=>({run_id:ji(Xe.run),workflow_id:ln(Xe.run.workflow_id),from_run_id:_,provider:"",model:"",allowed_tools:null,max_iterations:null})),"listing"):ts(L.loaded?Ps.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=Et(nn);cn&&Object.keys(cn).length===1&&typeof cn.$artifact=="string"&&cn.$artifact.trim()&&ut.push({pin:Xe,id:cn.$artifact.trim()})}const Ot=hs(x.status);let Rt;d?Ot?z&&typeof z.response=="string"&&z.response.trim()?Rt=gn(z.response,"output"):typeof d.output=="string"&&d.output.trim()?Rt=gn(d.output,"output"):ln(d.error)?Rt=gn(ln(d.error),"run"):Rt=ts("the output carries no response text"):Rt=ts(Ps.not_ended):Rt=ts("run detail not loaded");const mn=Vt(x.created_at||""),wn=Ot?Vt(x.updated_at||""):null,On=Am(x,c),Ks=On>=0?gn(On,"run"):L.first_ms!==null&&L.last_ms!==null?gn(L.last_ms-L.first_ms,"used"):ts(Ps.wire),rs=J?((Fn=L.subruns.find(Xe=>Xe.max_iterations!==null))==null?void 0:Fn.max_iterations)??null:null,ge=jp([["used",rs],["run",Gn(m==null?void 0:m.max_iterations)],["flow default",Gn(M("max_iterations"))],["automation",Gn(E==null?void 0:E.max_iterations)],["automation",k?null:(v==null?void 0:v.max_iterations)??null]],Ps.no_default),Re=Gn(ne==null?void 0:ne.iterations)!==null?gn(Gn(ne==null?void 0:ne.iterations),"output"):ts(Ot?"the output carries no iteration count":Ps.not_ended),gt=Vv(e).tokens,re=Et($==null?void 0:$.trigger)||Et(N==null?void 0:N.trigger),fe=Et(re==null?void 0:re.config),Ce=v!=null&&v.cadence?gn({text:v.cadence,start_ms:Vt((fe==null?void 0:fe.start_at)||"")},"automation"):ts(I),Ie=R?gn({index:xe,count:v?v.occurrence_count:null},v?"automation":"run"):ts(Ps.not_automation),We=Gn(fe==null?void 0:fe.count)!==null?gn(Gn(fe==null?void 0:fe.count),"automation"):ts(R&&re?"no count limit":I,R&&re?"automation":""),Ue=Vt((fe==null?void 0:fe.until)||""),et=Ue!==null?gn(Ue,"automation"):ts(R&&re?"no end date":I,R&&re?"automation":""),at=Et(P==null?void 0:P.retry),vt=Et(at==null?void 0:at.backoff),xt=P?gn({max_attempts:Gn(at==null?void 0:at.max_attempts),backoff_initial:ln(vt==null?void 0:vt.initial),backoff_factor:Gn(vt==null?void 0:vt.factor),backoff_max:ln(vt==null?void 0:vt.max),failure:ln(P.failure),misfire:ln(P.misfire),serial:Up(P.serial)},"automation"):ts(I),At=N&&Array.isArray((fn=Et(N.notify))==null?void 0:fn.channels)?gn(ei(N.notify.channels),"automation"):ts(I),zt=Vv(e),ot=v!=null&&v.context_mode||zt.has_history?gn({mode:(v==null?void 0:v.context_mode)||"",growing_max_tokens:(v==null?void 0:v.growing_max_tokens)??null,replayed_messages:zt.replayed_messages,replayed_tokens:zt.replayed_tokens,dropped_messages:zt.dropped_messages,dropped_tokens:zt.dropped_tokens},v!=null&&v.context_mode?"automation":"run"):ts(R?I:"no session history on this run"),Yt=dt.root.value?gn(dt.root.value,dt.root.source):ts(Ps.wire);let vn;if(!R)vn=ts(Ps.not_automation);else if(!v)vn=ts(Ps.automation_not_loaded);else{const Xe=v.status;if(Xe==="paused")vn=gn({kind:"none",at_ms:null,text:"no next run (paused)"},"automation");else if(Xe==="completed")vn=gn(v.last&&xe!==null&&v.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")vn=gn({kind:"none",at_ms:null,text:"no next run (archived)"},"automation");else if(Xe==="failed")vn=gn({kind:"none",at_ms:null,text:"no next run (the automation failed)"},"automation");else if(v.next_fire_ms!==null){const nn=nm(v.next_fire_ms-c);vn=gn({kind:"next_at",at_ms:v.next_fire_ms,text:`next run at ${Md(v.next_fire_ms)}${nn?` (in ${nn})`:""}`},"automation")}else if(ln(re==null?void 0:re.source_id)==="manual")vn=gn({kind:"on_trigger",at_ms:null,text:"next run when someone runs it"},"automation");else if(v.event_driven||uc(re)){const nn=v.cadence||"when something new arrives";vn=gn({kind:"on_trigger",at_ms:null,text:`next run ${nn.charAt(0).toLowerCase()}${nn.slice(1)}`},"automation")}else vn=ts("no next fire time on this wire","automation")}return{subject_id:_,is_automation:R,who:{workflow:be,subject:Me,role:Ve,model:rt,model_declared:ze,system_prompt:He,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:Rt,children_not_loaded:L.missing_run_ids},how_long:{started_ms:mn,finished_ms:wn,running:!Ot,duration:Ks,max_iterations:ge,iterations_used:Re,tokens:gt,cadence:Ce,next_fire_ms:(v==null?void 0:v.next_fire_ms)??null,occurrence:Ie,stop_after:We,stop_at:et,retry:xt},after:{notify:At,context:ot,outputs_to:Yt,next:vn},ledger:L}}function vg(e,t){if(ji(e.run)===t)return e;for(const n of e.children){const r=vg(n,t);if(r)return r}return null}function yq(e,t,n){const r=n?vg(n,t):null;return!!r&&r!==e&&!!vg(r,ji(e.run))}const wq=["status","updated_at","current_node","paused","error","waiting"],vq=["workflow_id","created_at","parent_run_id","session_id","automation_id","role","occurrence_index","session_kind"];function GC(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=Vt(e.updated_at||""),r=Vt(t.updated_at||"");return n===null||r===null?!0:r>=n}function KC(e,t){if(!t||typeof t!="object")return e;const n={...e};for(const r of vq)(n[r]===void 0||n[r]===null||n[r]==="")&&t[r]!==void 0&&t[r]!==null&&(n[r]=t[r]);if(GC(e,t))for(const r of wq)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}function xq(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 ns(e){return s.jsx("p",{className:`ap_note ap_note_${e.kind}`,role:e.kind==="error"?"alert":void 0,children:e.children})}function cc(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 bq={approve:"Review approval",answer:"Answer",resume:"Resume",open_subrun:"Open subrun",inspect:"Inspect"};function JC(e,t,n,r){return z1(e,t,n??null,r??null)}function kq(e,t){const n=bq[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 jq(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=ni(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 Sq(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):Tm(e.run_id)},children:"⧉"})}const Nq={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 YC(e){return e.source?s.jsx("span",{className:"ap_source","data-source":e.source,title:Nq[e.source],children:e.source}):null}function $q(e){return s.jsx("span",{className:"ap_absent",children:e.fact.source==="gateway"?e.fact.why:`— ${e.fact.why||"not on this wire"}`})}function ka(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(YC,{source:e.source||""}),e.copy?s.jsx(Dg,{text:e.copy,label:e.label.toLowerCase()}):null]})]})}function es(e){const{fact:t}=e,n=t.value!==null;return s.jsx(ka,{id:e.id,label:e.label,source:t.source,copy:n?e.copy?e.copy(t.value):al(t.value):null,children:n?e.render?e.render(t.value):s.jsx(om,{value:t.value}):s.jsx($q,{fact:t})})}function Jl(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 Lh(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 $w(e){return[e.provider,e.model].filter(Boolean).join(" · ")||"model not recorded on the call"}function Cq(e,t){if(e.length!==t.length)return!1;const n=new Set(e);return t.every(r=>n.has(r))}function ga(e,t,n=`${t}s`){return`${os(e)} ${e===1?t:n}`}function Eq(e){var P,D;const{prof:t,p:n,line:r,ctx:i}=e,o=[];n.loading.input_data&&o.push(s.jsx(ns,{kind:"loading",children:"loading the run's inputs…"},"li")),n.errors.input_data&&o.push(s.jsxs(ns,{kind:"error",children:["inputs unavailable: ",n.errors.input_data]},"ei")),n.loading.detail&&o.push(s.jsx(ns,{kind:"loading",children:"loading the run detail…"},"ld")),n.errors.detail&&o.push(s.jsxs(ns,{kind:"error",children:["run detail unavailable: ",n.errors.detail]},"ed")),n.loading.flow&&o.push(s.jsx(ns,{kind:"loading",children:"loading the flow (its defaults)…"},"lf")),n.loading.records&&o.push(s.jsx(ns,{kind:"loading",children:"loading the ledger…"},"lr")),n.errors.records&&o.push(s.jsxs(ns,{kind:"error",children:["ledger unavailable: ",n.errors.records]},"er")),t.is_automation&&!n.automation_body&&!n.automation&&o.push(s.jsx(ns,{kind:"absent",children:"automation definition not loaded: tool policy unknown"},"na"));const c=R=>{const I=i.by_id.get(R);return ni(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,x=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,v=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?" · ":"",os(R(I))," ",I.run_id===t.subject_id?"in this run":s.jsxs(s.Fragment,{children:["in ",l(I.run_id,c(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 (",ga(N.length,"subrun")," not loaded here:"," ",N.map((R,I)=>s.jsxs("span",{children:[I?", ":"",l(R,c(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(Jl,{items:R.map(I=>I==="self"&&h.operator_email?`self (${h.operator_email})`:I),empty:"none"});return s.jsxs(cc,{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(Lh,{id:"who",title:"Who",question:"is this agent",children:[s.jsx(es,{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(es,{id:"subject",label:"Subject",fact:d.subject,render:R=>R.kind==="automation"?s.jsx(om,{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(es,{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 ",os(_.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(es,{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:[$w(W),W.calls!==null?s.jsxs("span",{className:"ap_muted",children:[" × ",ga(W.calls,"call")]}):null]},G)),(I=d.model_declared)!=null&&I.value?s.jsxs("span",{className:"ap_finding",children:["asked for ",$w(d.model_declared.value)," ",s.jsx(YC,{source:d.model_declared.source})]}):null]})},copy:R=>R.map($w).join(`
170
+ `)}),s.jsx(es,{id:"system",label:"System prompt",fact:d.system_prompt}),s.jsx(es,{id:"task",label:"Task",fact:d.task})]}),s.jsxs(Lh,{id:"access",title:"Access",question:"what it may use",children:[s.jsx(es,{id:"tools_allowed",label:"May call",fact:h.tools_allowed,render:R=>s.jsx(Jl,{items:R})}),s.jsx(es,{id:"runtime_allowlist",label:"Runtime allowlist",fact:h.runtime_allowlist,render:R=>h.tools_allowed.value&&R.length&&Cq(R,h.tools_allowed.value)?s.jsxs("span",{children:["the same ",ga(R.length,"tool")," as above"]}):s.jsx(Jl,{items:R})}),s.jsx(es,{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," × ",os(I.calls),I.failures?`, ${os(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(es,{id:"tool_approval",label:"Tool approval",fact:h.tool_approval,render:R=>s.jsx("span",{children:R})}),s.jsx(es,{id:"untrusted_input_tools",label:"Untrusted-input tools",fact:h.untrusted_input_tools,render:R=>s.jsx(Jl,{items:R})}),s.jsx(es,{id:"email_recipients",label:"Email recipients",fact:h.email_recipients,render:S}),s.jsx(es,{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,x]}),copy:R=>y.root.value?`${R}
171
+ ${y.root.value}`:R}),y.allowed_paths.value!==null?s.jsx(es,{id:"allowed_paths",label:"Allowed paths",fact:y.allowed_paths,render:R=>s.jsx(Jl,{items:R})}):null,y.ignored_paths.value!==null?s.jsx(es,{id:"ignored_paths",label:"Ignored paths",fact:y.ignored_paths,render:R=>s.jsx(Jl,{items:R})}):null]}),s.jsxs(Lh,{id:"does",title:"Does",question:"what it did",children:[s.jsx(ka,{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(es,{id:"llm_calls",label:"LLM calls",fact:m.llm_calls,render:R=>s.jsxs("span",{className:"ap_stack",children:[s.jsx("span",{children:os(R)}),m.llm_calls.source==="used"?v(I=>I.llm_calls):E(m.llm_calls)]})}),s.jsx(es,{id:"tool_calls",label:"Tool calls",fact:m.tool_calls,render:R=>s.jsxs("span",{className:"ap_stack",children:[s.jsxs("span",{children:[os(R.calls),R.failures?`, ${os(R.failures)} failed`:R.failures===0&&R.calls?", none failed":""]}),m.tool_calls.source==="used"?v(I=>I.tool_calls):E(m.tool_calls),m.tool_calls.source==="used"?$:null]})}),s.jsx(es,{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?ga(I.allowed_tools.length,"tool"):"",I.max_iterations!==null?`max ${os(I.max_iterations)} iterations`:""].filter(Boolean),K=ni(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(ka,{id:"artifacts",label:"Artifacts",source:"output",copy:m.artifacts.map(R=>R.id).join(`
172
+ `),children:s.jsxs("span",{children:[ga(m.artifacts.length,"artifact"),": ",s.jsx(Jl,{items:m.artifacts.map(R=>R.pin)})]})}):null,s.jsx(es,{id:"outcome",label:"Outcome",fact:m.outcome})]}),s.jsxs(Lh,{id:"how_long",title:"How long",question:"it runs and may run",children:[s.jsx(ka,{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:Md(_.started_ms)}):s.jsx("span",{className:"ap_absent",children:"— not on this wire"})}),s.jsx(ka,{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:Md(_.finished_ms)}):s.jsx("span",{className:"ap_muted",children:_.running?"so far (still active)":"— not on this wire"})}),s.jsx(es,{id:"duration",label:"Duration",fact:_.duration,render:R=>s.jsxs("span",{children:[bu(R),_.running?" so far":""]}),copy:R=>String(R)}),s.jsx(es,{id:"max_iterations",label:"Max iterations",fact:_.max_iterations}),s.jsx(es,{id:"iterations_used",label:"Iterations used",fact:_.iterations_used}),s.jsx(ka,{id:"token_limit",label:"Token limit",source:_.tokens?"run":"",copy:_.tokens?al(((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?os(_.tokens.used):"—",_.tokens.budget!==null?` of ${os(_.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(es,{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 ",Md(R.start_ms)]}):null,_.next_fire_ms!==null?s.jsxs("span",{children:[" · next ",Md(_.next_fire_ms)]}):null]})}),s.jsx(es,{id:"occurrences",label:"Occurrences",fact:_.occurrence,render:R=>s.jsxs("span",{children:[R.index!==null?`#${os(R.index)}`:"this run",R.count!==null?` of ${os(R.count)} so far`:""," · ",_.stop_after.value!==null?`stops after ${ga(_.stop_after.value,"scheduled occurrence")}`:_.stop_after.why," · ",_.stop_at.value!==null?`stops at ${Md(_.stop_at.value)}`:_.stop_at.why]})}),s.jsx(es,{id:"retry",label:"Retry policy",fact:_.retry,render:R=>s.jsx("span",{children:[R.max_attempts!==null?ga(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(Lh,{id:"after",title:"After",question:"what it may do next",children:[s.jsx(es,{id:"notify",label:"Notifies",fact:g.notify,render:R=>s.jsx(Jl,{items:R.map(I=>I==="email"?"email → the owner's registered address (not on this wire)":I),empty:"nobody (no channel)"})}),s.jsx(es,{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 ${os(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?ga(R.replayed_messages,"message"):"?",R.replayed_tokens!==null?` (${os(R.replayed_tokens)} tokens)`:"",R.dropped_messages!==null?`, left out ${ga(R.dropped_messages,"message")}${R.dropped_tokens?` (${os(R.dropped_tokens)} tokens)`:""}`:""]}):null]})}),s.jsx(es,{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}),x,m.artifacts.length?s.jsxs("span",{className:"ap_muted",children:["· ",ga(m.artifacts.length,"artifact")," in the output"]}):null]})}),s.jsx(es,{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 Aq(e){const{p:t}=e,n=p.useMemo(()=>lq(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(ns,{kind:"loading",children:"loading the flow…"}):t.errors.flow?s.jsxs(ns,{kind:"error",children:["the flow did not load (",t.errors.flow,"): pin types unknown"]}):n.flow_found?n.start_found?null:s.jsx(ns,{kind:"absent",children:"the flow has no On Flow Start node"}):s.jsx(ns,{kind:"absent",children:"no flow JSON for this run: pin types unknown"}),o=t.loading.input_data?s.jsx(ns,{kind:"loading",children:"loading the run's inputs…"}):t.errors.input_data?s.jsxs(ns,{kind:"error",children:["inputs unavailable: ",t.errors.input_data]}):t.input_data?s.jsx(ns,{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,c=t.loading.detail?s.jsx(ns,{kind:"loading",children:"loading the run detail…"}):t.errors.detail?s.jsxs(ns,{kind:"error",children:["output unavailable: ",t.errors.detail]}):n.flow_found&&!n.end_found?s.jsx(ns,{kind:"absent",children:"the flow has no On Flow End node"}):n.end_is_passthrough?s.jsx(ns,{kind:"info",children:"the end declares no pins: the run returns its last node's output"}):t.detail&&!n.outputs_final?s.jsx(ns,{kind:"info",children:"values appear when the run ends"}):null;return s.jsxs(cc,{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(ok,{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]}),c,s.jsx(ok,{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 Tq(e){var l,d,h;const{p:t}=e,n=p.useMemo(()=>Vv(t.detail),[t.detail]);if(t.loading.detail&&!t.detail)return s.jsx(cc,{id:"context",title:"Context",children:s.jsx(ns,{kind:"loading",children:"loading the run detail…"})});if(!t.detail)return s.jsx(cc,{id:"context",title:"Context",children:t.errors.detail?s.jsxs(ns,{kind:"error",children:["run detail unavailable: ",t.errors.detail]}):s.jsx(ns,{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),c=(l=t.detail)==null?void 0:l.session_history;return s.jsx(cc,{id:"context",title:"Context",children:s.jsxs("dl",{className:"ap_ptable",children:[s.jsx(ka,{id:"window",label:"Window",source:n.has_history?"run":"",copy:n.has_history?al(c):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(ka,{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(ka,{id:"tokens",label:"Tokens",source:r?"run":"",copy:r?al(((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?os(r.used):"—",r.budget!==null?` of ${os(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(ka,{id:"flow_warnings",label:"Flow warnings",source:t.detail?"run":"",copy:n.flow_warnings.length?n.flow_warnings.join(`
173
+ `):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 XC(e){const t=ni(String(e.workflow_id||""))||"(workflow?)";return String(e.role||"").trim()==="occurrence"&&typeof e.occurrence_index=="number"?`run #${e.occurrence_index} · ${t}`:t}function ZC(e){const{node:t,ctx:n}=e,r=t.run,i=Qd(r,n),o=JC(r,i),c=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 ${c}`,"data-run-id":c,onClick:()=>e.on_open_run(c),children:[s.jsx("span",{className:`chip ${Sa(o)}`,children:o}),s.jsx("span",{className:"ap_tree_name",children:XC(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(ZC,{node:l,ctx:n,on_open_run:e.on_open_run},String(l.run.run_id)))}):null]})}function Sp(e){return e===null?"—":os(e)}function Mq(e){var E,S;const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=p.useMemo(()=>KC(e.run,e.detail),[e.run,e.detail]),r=String(n.run_id||"").trim(),i=GC(e.run,e.detail),o=p.useMemo(()=>e.automation??(e.automation_body?Mm(e.automation_body):null),[e.automation,e.automation_body]),c=p.useMemo(()=>xq(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),xx(c,{now_ms:t,details:P,pulses:e.pulses,automations:D,stall_after_ms:e.stall_after_ms})},[c,e.detail,i,r,o,t,e.pulses,e.stall_after_ms]),d=Qd(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(),_=U1(n,l,m?{excerpt:m}:null),g=JC(n,d,Qp(e.detail),e.automation),y=[h.label&&h.label!==_.text?h.label:"",h.secondary].filter(Boolean),x=kq(d,r),k=p.useMemo(()=>gq(e.detail,e.input_data,e.flow,e.automation_body??o,e.records,c,t,{subject_run_id:r,row:n}),[e.detail,e.input_data,e.flow,e.automation_body,o,e.records,c,t,r,n]),v=p.useMemo(()=>VC(r,c),[r,c]),N=p.useMemo(()=>fq(v,c,t),[v,c,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 ${Sa(g,Qp(e.detail))}`,children:g}),s.jsx(Sq,{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(jq,{line:d,ctx:l,on_open_run:e.on_open_run}),x?s.jsx("button",{type:"button",className:`btn ${d.actor==="you"?"primary":""} ap_action`,onClick:()=>e.on_action(x.action,x.run_id),children:x.label}):null]}),e.loading.detail?s.jsx(ns,{kind:"loading",children:"reading the run detail… (the line above is from the listing row)"}):null,e.errors.detail?s.jsxs(ns,{kind:"error",children:["run detail unavailable: ",e.errors.detail," (the line above is from the listing row)"]}):null,e.detail&&!i?s.jsx(ns,{kind:"info",children:"the listing row is newer than the detail: the line above is from the row"}):null]}),s.jsx(Eq,{prof:k,p:e,line:d,ctx:l}),s.jsx(Aq,{p:e}),s.jsx(Tq,{p:e}),s.jsx(cc,{id:"tree",title:"Run tree",meta:v.size?`${v.size} run${v.size===1?"":"s"}`:void 0,children:v.root?s.jsxs(s.Fragment,{children:[v.controller_id?s.jsxs("button",{type:"button",className:"ap_tree_parent",title:`Open the automation's controller run ${v.controller_id}`,"data-run-id":v.controller_id,onClick:()=>e.on_open_run(v.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:[v.controller?Qd(v.controller,l).text:"controller (row not loaded)"," · other occurrences not shown"]})]}):null,s.jsx("ul",{className:`ap_tree ${v.controller_id?"ap_tree_under_parent":""}`,children:s.jsx(ZC,{node:v.root,ctx:l,on_open_run:e.on_open_run})})]}):s.jsx(ns,{kind:"absent",children:"this run is not among the loaded rows"})}),s.jsxs(cc,{id:"spend",title:"Spend",meta:"tree-inclusive",children:[N.any_metrics?null:s.jsx(ns,{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?XC(D):"run (row not loaded)"}),s.jsx(Dg,{text:P.run_id,label:"run id"})]}),s.jsx("td",{children:P.duration_ms===null?"—":`${bu(P.duration_ms)}${P.running?" so far":""}`}),s.jsx("td",{children:Sp(P.tokens_total)}),s.jsx("td",{children:Sp(P.llm_calls)}),s.jsx("td",{children:Sp(P.tool_calls)}),s.jsx("td",{children:Sp(P.steps)})]},P.run_id)})})]})}):s.jsx(ns,{kind:"absent",children:"no rows"})]}),s.jsxs(cc,{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 Bj={key:"",loading:!1,input_data:null,input_error:"",flow:null,flow_error:"",automation_body:null,automation:null,automation_error:"",runs:[],runs_error:""},Np=500,xg="http://127.0.0.1:8080";function Uj(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 Ih(e){const t=String(e||"").trim();return t.startsWith("abstractcode.")?`abstract.${t.slice(13)}`:t}function Cw(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 Ew(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function Rq(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 Lq(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:{},c=[];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]),c.push(_)}return c}function Aw(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 Iq(){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)||xg),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:xg,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 Oq(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function Pq(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=[],n=(i,o)=>{const c=String(o??"").trim();c&&(t.some(l=>l.label===i&&l.value===c)||t.push({label:i,value:c}))},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 Wj(e){const t=Pq(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 Dq(){return typeof window>"u"?"":JI(window.location)}function Fq(){try{const e="abstractobserver_session_id_v1",t=window.sessionStorage.getItem(e);if(t&&t.trim())return t.trim();const n=`obs_${Zs()}`;return window.sessionStorage.setItem(e,n),n}catch{return""}}function zq(){var P_,Wo,uh,_d,ha,pd,ma,dh,fh,gd,Kc,D_,F_,hh,mh;const[e,t]=p.useState("board"),[n,r]=p.useState(()=>Iq()),i=typeof window<"u"&&((P_=window.__ABSTRACT_UI_CONFIG__)==null?void 0:P_.monitor_gpu)===!0,o=typeof window<"u"&&(((Wo=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Wo.entity_app_url)||"").trim().replace(/\/+$/,"")||"http://127.0.0.1:3007",c=p.useRef(null),[l,d]=p.useState(""),[h,m]=p.useState(""),[_,g]=p.useState(()=>Dq()),[y,x]=p.useState(""),[k,v]=p.useState(""),[N,$]=p.useState(""),[E,S]=p.useState("{}"),[P]=p.useState(()=>Fq()),[D,R]=p.useState(null),[I,W]=p.useState(!1),[G,K]=p.useState(""),[V,M]=p.useState(!1),[A,O]=p.useState(""),[L,H]=p.useState(!1),J=XE({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((uh=window.__ABSTRACT_UI_CONFIG__)==null?void 0:uh.gateway_url)||xg,onStatusChange:b=>qf(b)}),[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),[Ve,mt]=p.useState(null);function nt(b){ae(b),Ae(!0)}const[rt,ze]=p.useState(""),[He,ct]=p.useState(nv),[Qe,Dt]=p.useState([]),[$e,Le]=p.useState(null),[ce,Q]=p.useState(!1),[_e,le]=p.useState([]),Se=p.useRef(new s3(Zs)),[pe,dt]=p.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[yt,_t]=E2("abstractobserver",{legacyKey:"abstractobserver_settings"}),[It,bt]=p.useState(!1),[St,ut]=p.useState(!1),[Ot,Rt]=p.useState([]),[mn,wn]=p.useState([]),[On,Ks]=p.useState([]),[rs,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,At]=p.useState(!1),[zt,ot]=p.useState([]),[Yt,vn]=p.useState([]),[hn,sn]=p.useState({}),[Ht,is]=p.useState(!1),[Be,Qt]=p.useState(!1),[Mt,Fn]=p.useState(!1),[fn,Xe]=p.useState([]),[nn,cn]=p.useState([]),Ar=p.useRef(0),As=p.useRef(null);As.current||(As.current=new Q0(b=>window.setTimeout(b,40),b=>Xe(T=>T.concat(b))));const ws=p.useRef(null);ws.current||(ws.current=new Q0(b=>window.setTimeout(b,40),b=>cn(T=>T.concat(b))));const _r=p.useRef({scanned:0,found:null}),[we,Nt]=p.useState(null),[zn,nr]=p.useState(""),[$i,sr]=p.useState(!1),xo=p.useRef(null),[dc,ul]=p.useState({}),[js,pr]=p.useState({}),[Rs,Bi]=p.useState(!1),[dl,vs]=p.useState(""),[si,Ls]=p.useState(!0),[ri,Ss]=p.useState(""),[ii,Ui]=p.useState(!1),[In,$a]=p.useState(!1),[fl,hl]=p.useState(6),[Tr,fc]=p.useState("standard"),[Wi,Ca]=p.useState(""),[bo,Fs]=p.useState(""),[zs,gr]=p.useState(!1),[ko,Wr]=p.useState(!1),[Mr,qr]=p.useState("pause"),[hc,Vr]=p.useState(""),[ku,Ci]=p.useState(""),[Xo,ml]=p.useState(""),jo=p.useRef(null),oi=p.useRef(null),[Ea,qi]=p.useState(!1),rr=p.useRef(null),[cf,ai]=p.useState(""),[Kn,Y]=p.useState(Bj),he=p.useRef(0),[Oe,De]=p.useState(""),[Ye,ht]=p.useState(""),[Wt,Pt]=p.useState(""),[Bt,pn]=p.useState(!1),[En,Js]=p.useState("idle"),[Ft,bn]=p.useState([]),[as,Hn]=p.useState(null),Rr=p.useRef(null),[yr,Vi]=p.useState(!1),[_l,Hi]=p.useState(""),[uf,mc]=p.useState(""),[Aa,Ta]=p.useState(""),[df,_c]=p.useState([]),[pc,ju]=p.useState(!1),[ff,Su]=p.useState(""),[hf,Nu]=p.useState(""),[$u,pl]=p.useState(!1),[Om,Ma]=p.useState(""),Pm=p.useMemo(()=>{if(!Ft.length)return"";try{return JSON.stringify(Ft.map(b=>({role:b.role,content:b.content,ts:b.ts})))}catch{return"1"}},[Ft]),Cu=p.useMemo(()=>Ft.length?Aa?Pm!==Aa:!0:!1,[Pm,Ft.length,Aa]),mf=p.useMemo(()=>df.map(b=>{const T=String(b.title||"").trim()||`Chat ${String(b.thread_id||"").slice(0,8)}`,F=String(b.created_at||"").trim(),B=F?F.replace("T"," ").slice(0,19):"",Z=String(b.run_id||"").trim()?String(b.run_id).slice(0,8):"",X=[T,B&&`(${B})`,Z&&`run ${Z}`].filter(Boolean).join(" • ");return{value:String(b.thread_id||""),label:X}}),[df]);p.useEffect(()=>{i&&t4()},[i]),p.useEffect(()=>{if(!i)return;const b=c.current;b&&(b.token=n.gateway_auth_mode==="direct"&&n.auth_token||"")},[i,n.auth_token,n.gateway_auth_mode]);const[,_f]=p.useState([]),[gl,Dm]=p.useState([]),Fm=(b,T)=>{const F=Date.now();Dm(B=>{const Z=B.findIndex(ee=>ee.title===b);if(Z<0)return[...B,{title:b,preview:T,count:1,at:F}].slice(-4);const X=[...B];return X[Z]={title:b,preview:T,count:X[Z].count+1,at:F},X})},pf=gl.length?gl.map(b=>{const T=new Date(b.at),F=`${String(T.getHours()).padStart(2,"0")}:${String(T.getMinutes()).padStart(2,"0")}`;return`${b.title}: ${b.preview} · ${F}${b.count>1?` ×${b.count}`:""}`}).join(" — "):"",[Kg,Eu]=p.useState(!1),yl=p.useRef(""),Jg=p.useRef("");p.useEffect(()=>{var T,F;const b=String(((F=(T=U==null?void 0:U.gateway)==null?void 0:T.principal)==null?void 0:F.user_id)||"").trim();yl.current=b||(L&&n.gateway_auth_mode==="direct"?"direct":"")},[U,L,n.gateway_auth_mode]);const[Au,An]=p.useState(""),[Tu,zm]=p.useState(""),[Mu,wl]=p.useState("all"),[gf,Yg]=p.useState("status"),[Ns,So]=p.useState("ledger"),yf=ub(_y.md),gc=ub(`${_y.sm}, ${_y.short}`),Gi=BI({is_drawer:yf,page:e}),wf=Gi.open,Zo=Gi.set_open,[Bm,Um]=eg("observe_runs"),vf=Gi.toggle_ref,xf=Gi.sidebar_ref,bf=p.useRef(null),[Wm,kf]=p.useState(()=>v0(typeof window<"u"?window.location.hash:"")),[Xg,qm]=p.useState(""),[Vm,jf]=p.useState(""),[vl,wr]=p.useState(""),[Ki,xl]=p.useState(null),[yc,Ru]=p.useState({}),[Sf,Ra]=p.useState(!1),[Hm,wc]=p.useState(""),[Ji,Nf]=p.useState(!1),[La,$f]=p.useState(!1),[Lu,Ia]=p.useState(()=>Date.now()),[Lr,Qo]=p.useState(""),[Gm,Oa]=p.useState({}),[Km,Iu]=p.useState({}),bl=p.useRef([]),Hr=p.useRef(null),No=p.useRef(""),vc=p.useRef({}),Gr=p.useRef({}),xc=p.useRef({}),Pa=p.useRef(new Set),[$o,Ou]=p.useState([]),Co=p.useRef(""),kl=p.useRef({}),Eo=p.useRef(null),vr=p.useRef(null),Bn=p.useRef(0),ea=p.useRef({}),Da=p.useRef(!1),Ei=p.useRef(new Set),[Pu,jl]=p.useState(""),[Ir,Ai]=p.useState(""),xr=p.useRef(""),Cf=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[bc,Jm]=p.useState("activity"),[Du,kc]=p.useState([]),[jc,Fu]=p.useState(0),[Ef,zu]=p.useState(0),[Af,Ym]=p.useState({}),[Xm,Zm]=p.useState({}),[Zg,Bu]=p.useState(!1),[ta,Tf]=p.useState(""),[Yi,Xi]=p.useState(""),[Ao,Ti]=p.useState("all"),[Sl,Qm]=p.useState(""),[Nl,Fa]=p.useState([]),[na,$l]=p.useState("all"),[To,Mf]=p.useState("type"),[Mo,sa]=p.useState("newest"),[Pn,Xn]=p.useState(""),[li,Ts]=p.useState(""),[br,Ro]=p.useState(""),[Zi,ir]=p.useState(0),[Lo,Uu]=p.useState(()=>Cf()),[e_,Cl]=p.useState(!1),[Wu,Io]=p.useState(""),[qu,ra]=p.useState(""),[or,Vu]=p.useState(""),[Qi,El]=p.useState("text"),[Al,Tl]=p.useState(null),[Hu,kr]=p.useState(!1),[Kr,eo]=p.useState(""),[to,no]=p.useState(""),[za,Rf]=p.useState(""),[Gu,Ku]=p.useState(!1),[Jr,Or]=p.useState(""),[Zn,Mi]=p.useState("run_ledger"),[t_,n_]=p.useState(""),[Lf,Sc]=p.useState([]),[s_,Ml]=p.useState(""),[r_,Ba]=p.useState(!1),[If,Of]=p.useState(""),Ke=p.useMemo(()=>new Ky({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]),Un=p.useMemo(()=>new g3(Ke.automations_client(),m3(Ke,Zs,on)),[Ke]),ci=p.useSyncExternalStore(b=>Un.subscribe(b),()=>Un.state),Pf=qO(n.gateway_url),Oo=Pf?()=>{window.open(Pf,"_blank","noopener,noreferrer")}:void 0,Df=p.useCallback(b=>XO(b,{connections:ci.trigger_connections,mailboxes:ci.mailboxes}),[ci.trigger_connections,ci.mailboxes]),Po=p.useMemo(()=>!rt&&N.trim()&&k.trim()?KO(D,N.trim(),k.trim()):null,[D,N,k,rt]),Rl=p.useRef("");p.useEffect(()=>{if(!xe||je!=="automate"||!Po)return;const b=`${N.trim()}:${k.trim()}`;if(Rl.current===b)return;Rl.current=b;let T={};try{const B=JSON.parse(E||"{}");B&&typeof B=="object"&&!Array.isArray(B)&&(T=B)}catch{T={}}const F=YO(He,T,Po);ct(F.form),S(JSON.stringify(F.input_data,null,2))},[xe,je,Po,N,k]);const Ll=GS(xe&&je==="automate"&&L?e3(He,Po):null,Un.preview_schedule);p.useEffect(()=>{xe&&je==="automate"&&L&&(Un.load_email_status(),Un.load_trigger_vocab())},[e,je,L,Un]),p.useEffect(()=>{L&&Un.load_trigger_vocab()},[L,Un]),p.useEffect(()=>{const b=()=>{const T=HO(window.location.hash);if(T){if(T.page==="run"){g(T.run_id),kf(v0(window.location.hash));return}if(T.page==="launch"){nt(T.mode);return}t(T.page)}};return b(),window.addEventListener("hashchange",b),()=>window.removeEventListener("hashchange",b)},[]);const Ff=p.useMemo(()=>{const b={};for(const T of ci.items)b[T.automation_id]=T.title;return b},[ci.items]),zf=p.useMemo(()=>qP(),[]),[Bf,Ju]=p.useState(P0),Ua=p.useRef(0);function ui(){const b=++Ua.current;Ju(P0),VP(Ke).then(T=>{b===Ua.current&&Ju(T)})}const so=p.useMemo(()=>n.worker_url.trim()?new eD({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),Yu=p.useMemo(()=>X4(Ke.fetch_gateway,lv),[Ke]),ar=fn.length?fn[fn.length-1].record:null,un=p.useMemo(()=>Za(ar),[ar]),_s=p.useMemo(()=>{const b=N.trim();if(!D||!b||String(D.bundle_id||"").trim()&&String(D.bundle_id||"").trim()!==b)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]),Nc=p.useMemo(()=>{const b=_s==null?void 0:_s.inputs;return Array.isArray(b)?b:[]},[_s]),Uf=p.useMemo(()=>Lq(Ki),[Ki]),Yr=p.useMemo(()=>Nc.length?Nc:Uf,[Nc,Uf]),Xr=p.useMemo(()=>{const b=typeof(we==null?void 0:we.workflow_id)=="string"?String(we.workflow_id):"",T=Uj(b);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=_s==null?void 0:_s.node_index;return F&&typeof F=="object"?F:{}},[we,D,_s]);p.useEffect(()=>{Oq(n)},[n]),p.useEffect(()=>()=>{Eo.current&&Eo.current.abort(),vr.current&&vr.current.abort(),jo.current&&window.clearTimeout(jo.current),oi.current&&window.clearTimeout(oi.current),Hr.current&&window.clearTimeout(Hr.current),rr.current&&window.clearTimeout(rr.current)},[]);const rn=p.useMemo(()=>{const b=E.trim();if(!b)return{};try{const T=JSON.parse(b);return typeof T!="object"||T===null||Array.isArray(T)?null:T}catch{return null}},[E]),i_=typeof(rn==null?void 0:rn.prompt)=="string"?String(rn.prompt):"",Il=typeof(rn==null?void 0:rn.provider)=="string"?String(rn.provider):"",o_=typeof(rn==null?void 0:rn.model)=="string"?String(rn.model):"",$c=typeof(rn==null?void 0:rn.workspace_root)=="string"?String(rn.workspace_root):"",ro=p.useMemo(()=>{const b=rn==null?void 0:rn.workspace;return b&&typeof b=="object"&&!Array.isArray(b)?b:null},[rn]),Cc=Yr.length>0&&!!N.trim(),Wa=b=>{const T=String(b||"").trim().toLowerCase();return T==="object"||T==="memory"||T==="assertion"||T==="assertions"||T==="any"};p.useEffect(()=>{pr({})},[N,k]),p.useEffect(()=>{rn!==null&&ul(b=>{const T={};for(const F of Yr){if(!F||typeof F!="object")continue;const B=String(F.id||"").trim();if(!B)continue;const Z=String(F.type||"").trim();if(!Wa(Z))continue;if(String(js[B]||"").trim()){T[B]=typeof b[B]=="string"?b[B]:"";continue}const ee=rn==null?void 0:rn[B];ee===void 0?T[B]="":T[B]=xO(ee)}return T})},[Yr,rn,js]);const jr=rt?{kind:"default",interface:rt}:N.trim()&&k.trim()?{kind:"bundle",bundle_id:N.trim(),flow_id:k.trim()}:null,Xu=zO(jr),di=Array.isArray(rn==null?void 0:rn.skills)?rn.skills.map(b=>String(b||"").trim()).filter(Boolean):[],fi=p.useMemo(()=>{const b={};for(const T of Ot){const F=String(T.workflow_id||"").trim(),B=String(T.label||"").trim();F&&B&&(b[F]=B)}return b},[Ot]),Ol=ZS({interfaceId:null,defaultInterface:Bd,request:(b,T)=>Ke.get_gateway_json(b,T.signal),enabled:L,reloadKey:Ot}),ps=p.useMemo(()=>{const b=new Set;for(const T of Array.isArray(Yt)?Yt:[]){const F=String((T==null?void 0:T.name)||"").trim();F&&b.add(F)}return Array.from(b).sort()},[Yt]),Zu=p.useMemo(()=>{const b=[];for(const T of Array.isArray(Yt)?Yt:[]){const F=String((T==null?void 0:T.name)||"").trim();if(!F)continue;const B=String((T==null?void 0:T.display_name)||"").trim();b.push({name:F,display_name:B||void 0})}return b},[Yt]),Ec=p.useMemo(()=>{const b=new Set;for(const T of zt||[]){if(!T||typeof T!="object")continue;const F=String(T.name||"").trim();F&&b.add(F)}return Array.from(b).sort()},[zt]),Qu=p.useMemo(()=>{const b=n.maintenance_ai_provider.trim();if(!b)return{models:[],error:""};const T=hn[b];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]),Pl=n.maintenance_ai_provider.trim(),Wf=!!(Pl&&L&&!Object.prototype.hasOwnProperty.call(hn,Pl));p.useEffect(()=>{const b=Il.trim();if(!b||hn[b]||kl.current[b])return;kl.current[b]=!0;let T=!1;return(async()=>{try{const B=await Ke.discovery_provider_models(b);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,[b]:{models:Z,error:X||void 0}}))}catch(B){if(T)return;sn(Z=>({...Z,[b]:{models:[],error:String((B==null?void 0:B.message)||B||"Failed to load models")}}))}finally{delete kl.current[b]}})(),()=>{T=!0}},[Il,hn,Ke]),p.useEffect(()=>{const b=n.maintenance_ai_provider.trim();if(!b||!L||hn[b]||kl.current[b])return;kl.current[b]=!0;let T=!1;return(async()=>{try{const B=await Ke.discovery_provider_models(b);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,[b]:{models:Z,error:X||void 0}}))}catch(B){if(T)return;sn(Z=>({...Z,[b]:{models:[],error:String((B==null?void 0:B.message)||B||"Failed to load models")}}))}finally{delete kl.current[b]}})(),()=>{T=!0}},[n.maintenance_ai_provider,hn,Ke,L]);function Qn(b,T){const F=String(b||"").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 ls(b){const T=String(b||"").trim();if(!T)return K("Missing bundle_id"),null;K(""),W(!0);try{const F=await Ke.get_bundle(T);return R(F),kn({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 $s(b){const T=[],F=Array.isArray(b==null?void 0:b.items)?b.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 Dn(b=Ke,T){if(et.current&&!(T!=null&&T.force))return;et.current=!0;const F=io.current;ge(!0);const B=ye=>ye.map(ip).filter(Fe=>!!Fe.run_id),Z=ye=>Array.isArray(ye==null?void 0:ye.items)?ye.items:[],X=S9(b,F),ee=()=>{const ye=X.view();wn(ye.roots),Ks(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(kn({ts:on(),kind:"error",title:Fe,preview:tn(Pe)}),Fm(Fe,tn(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,kn({ts:on(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(st/1e3)}s`})}},Ge=yl.current,ke=Ge?b9(String(n.gateway_url||""),Ge):"";Jg.current=ke,ke&&X.active_at===null&&X.seed(k9(xj(),ke))&&X.active_at!==null&&(ee(),gt(X.active_at),Eu(!0));try{const[ye,Fe]=await Promise.allSettled([b.list_runs({status:"running",limit:wj}),b.list_runs({status:"waiting",limit:vj})]);if(F!==io.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"),xn=!!(Pe&&st)&&pt.length<wj&&lt.length<vj&&(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),xn),!(Pe&&st)&&qt&&(X.seeded=!0),ee(),gt(Date.now()),Eu(!(Pe&&st)&&qt),Pe&&st&&Dm([]),vt.current=0,at.current=0,ke&&Pe&&st&&window.setTimeout(()=>j9(xj(),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()),b.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 b.list_runs({limit:200,root_only:!0,archived_only:!0,include_metrics:!0});return[ye,Pe]}).then(([ye,Fe])=>{if(F!==io.current||!bj(X))return X.fail_sweep();const Pe=i3(Z(ye),Z(Fe));X.apply_sweep(B(Pe),Date.now()),ee()},ye=>{X.fail_sweep(),!(F!==io.current||!bj(X))&&oe(ye,"Refresh run metrics failed")}))}async function Ac(b){var oe,Ge,ke;const T=io.current;H(!0),sn({}),b.list_apps().then(ye=>{if(T!==io.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===io.current&&mt(null)});const[F,,B,Z,X]=await Promise.allSettled([b.list_bundles(),Dn(b),b.discovery_tools(),b.discovery_providers({include_models:!1}),b.discovery_capabilities()]);if(T!==io.current)return;if(F.status==="rejected"&&B.status==="rejected"&&Z.status==="rejected"){H(!1),O(Aw(F.reason,n)),kn({ts:on(),kind:"error",title:"Discovery failed",preview:tn(String(F.reason||""))});return}dt(X.status==="fulfilled"?o3(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=$s(F.value);ee=ye.length,Rt(ye)}else Rt([]),kn({ts:on(),kind:"error",title:"Discovery bundles failed",preview:tn(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([]),kn({ts:on(),kind:"error",title:"Discovery tools failed",preview:tn(String(B.reason||""))});if(Z.status==="fulfilled"){const ye=Array.isArray((ke=Z.value)==null?void 0:ke.items)?Z.value.items:[];vn(ye)}else vn([]),kn({ts:on(),kind:"error",title:"Discovery providers failed",preview:tn(String(Z.reason||""))});kn({ts:on(),kind:"info",title:"Gateway discovery loaded",preview:tn(`workflows: ${ee}`)})}async function Do(b){var T,F;O(""),H(!1),M(!0);try{if(!(b!=null&&b.prefer_direct)&&(await J.refresh(),qa.current))return;const B=String(n.auth_token||"").trim();if(!B){b!=null&&b.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 Ky({base_url:Z,auth_token:B});await X.list_bundles(),r(ee=>({...ee,gateway_auth_mode:"direct"})),await Ac(X)}catch(B){O(Aw(B,n))}finally{M(!1)}}const qa=p.useRef(!1),io=p.useRef(0),Bs=p.useRef(!1);function qf(b){var F,B,Z;te(b);const T=!!(b&&b.has_session&&((F=b.gateway)!=null&&F.ok));if(qa.current=T,T){if(Bs.current=!1,L&&n.gateway_auth_mode==="direct")return;const X=String(((Z=(B=b==null?void 0:b.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),Ac(new Ky({base_url:"",auth_token:""})).catch(ee=>O(Aw(ee,n))).finally(()=>M(!1));return}b&&!b.has_session&&(n.gateway_auth_mode==="session"&&hi({keep_session:!0}),String(n.auth_token||"").trim()&&!L&&!Bs.current&&(Bs.current=!0,Do({prefer_direct:!0})))}async function Vf(){if(!(xt||V)){At(!0);try{await Ke.reload_bundles();const b=await Ke.list_bundles(),T=$s(b);Rt(T),kn({ts:on(),kind:"info",title:"Bundles reloaded",preview:tn(`workflows: ${T.length}`)})}catch(b){const T=String((b==null?void 0:b.message)||b||"Bundle reload failed");kn({ts:on(),kind:"error",title:"Bundle reload failed",preview:tn(T),data:{error:T}})}finally{At(!1)}}}async function Hf(b){if($i||V||!L)return;const T=b;if(T){sr(!0),An("");try{const F=await Ke.upload_bundle(T,{overwrite:!1,reload:!0});kn({ts:on(),kind:"info",title:"Bundle uploaded",preview:tn(String((F==null?void 0:F.bundle_ref)||""))});const B=await Ke.list_bundles(),Z=$s(B);Rt(Z)}catch(F){const B=String((F==null?void 0:F.message)||F||"Upload failed");An(B),kn({ts:on(),kind:"error",title:"Upload .flow failed",preview:tn(B),data:{error:B}})}finally{sr(!1);try{xo.current&&(xo.current.value="")}catch{}}}}function hi(b){io.current+=1,b!=null&&b.keep_session||(J.signOut().catch(()=>{}),qa.current=!1),Fl(),$(""),v(""),wr(""),R(null),K(""),W(!1),Rt([]),wn([]),Ks([]),gt(null),fe(null),Ie(0),ot([]),vn([]),sn({}),O(""),H(!1),te(null),r(T=>({...T,auth_token:""})),kn({ts:on(),kind:"info",title:"Gateway disconnected"})}async function Pr(b){const T=String(b??"");T&&Us(await Tm(T)?"Copied to clipboard":a1,2)}p.useEffect(()=>{const b=l.trim();if(!Ht||!b)return;let T=!1;const F=async()=>{if(!(at.current>Date.now()))try{const Z=await Ke.get_run(b);T||Nt(Z)}catch{}};F();const B=window.setInterval(F,2e3);return()=>{T=!0,window.clearInterval(B)}},[Ht,l,Ke]),p.useEffect(()=>{if(!L)return;let b=null,T=!1,F=!1;const B=ee=>{T||(b!==null&&window.clearTimeout(b),b=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 Dn(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,b!==null&&window.clearTimeout(b),document.removeEventListener("visibilitychange",X)}},[L,Ke]);const[Tc,Mc]=p.useState(null);p.useEffect(()=>{if(!L){Mc(null);return}let b=!1;return(async()=>{try{const T=await Ke.get_entity_phases_spec();if(b)return;const F=rW(T);if(Mc(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&&kn({ts:on(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:tn(`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(!b){Mc(null);const F=String((T==null?void 0:T.message)||T||"");/404|not found/i.test(F)||kn({ts:on(),kind:"info",title:"Phase-graph fetch failed — pre-wire fallback vocabulary in use (#FALLBACK)",preview:tn(F),data:{error:F}})}}})(),()=>{b=!0}},[L]),p.useEffect(()=>{if(!L){fe(null),Ie(0),Ue("");return}let b=!1,T=null;const F=async()=>{if(!(at.current>Date.now())){try{const B=await Ke.list_entities();b||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,LC),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,xn=Array.isArray(ye==null?void 0:ye.warnings)?ye.warnings.map(ft=>String(ft||"")).filter(Boolean):[],qt=tW(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:xn.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:eW(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")}}}));b||(fe(X),Ie(B.entities.length),Ue(""))}catch(B){if(!b){fe([]);const Z=String((B==null?void 0:B.message)||B||"");Ue(/404|not found/i.test(Z)?"":Z)}}b||(T=window.setTimeout(()=>void F(),3e4))}};return F(),()=>{b=!0,T!==null&&window.clearTimeout(T)}},[L,Ke]);async function Gf(b,T,F){const B=String(T||"").trim();if(!b||!B)throw new Error("This wait has no wait_key yet — open the run to inspect.");await Ke.submit_command({command_id:Zs(),run_id:b,type:"resume",payload:{wait_key:B,payload:F||{}},client_id:"web_pwa"}),kn({ts:on(),kind:"info",title:"Board resume submitted",preview:tn(`run ${b} · wait ${B}`),data:{run_id:b,wait_key:B}}),Dn(Ke,{force:!0}),window.setTimeout(()=>void Dn(Ke,{force:!0}),1200)}const ia=p.useMemo(()=>{const b=we==null?void 0:we.session_id;return typeof b=="string"?b.trim():b==null?"":String(b||"").trim()},[we]),a_=p.useMemo(()=>{const b=String(ia||"").trim();return b||String(P||"").trim()},[ia,P]);p.useEffect(()=>{L||Pt("")},[L]);const[Rc,l_]=u1(),Kf=d1(L?Ke:null,L),oo=f1({gateway:L?Ke:null,session_id:a_,prefs:Rc,on_error:Pt,on_transcript:b=>{const T=String(b||"").trim();T&&(De(F=>{const B=String(F||"");return B.trim()?`${B.trimEnd()}
174
+ ${T}`:T}),window.setTimeout(()=>{var F;return(F=Rr.current)==null?void 0:F.focus()},0))}}),c_=p.useMemo(()=>{for(let b=Ft.length-1;b>=0;b-=1){const T=Ft[b];if(T.role==="assistant")return T.local_error?null:{key:String(T.id||T.ts||""),text:String(T.content||"")}}return null},[Ft]);h1(oo,Rc.read_aloud===!0,c_);function u_(b,T){try{const F=URL.createObjectURL(b),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 Dl(){const b=Vm.trim();if(!b){Us("This run recorded no workspace",2);return}try{const T=await fetch(VI,{method:"POST",headers:{"Content-Type":"application/json",...lv()},body:JSON.stringify({path:b})}),F=await T.json().catch(()=>({}));T.ok&&(F!=null&&F.ok)?Us(`Opened ${String(F.path||b)}`,2):Us(String((F==null?void 0:F.error)||`Folder reveal failed (${T.status})`),3)}catch(T){Us(String((T==null?void 0:T.message)||T||"Folder reveal failed"),3)}}async function d_(b){const T=String((b==null?void 0:b.run_id)||"").trim(),F=String((b==null?void 0:b.artifact_id)||"").trim();if(!T||!F){Us("Artifact download needs a run id",3);return}const B=rg(b)||F;try{const Z=await Ke.download_run_artifact_content(T,F,{access:"preview"});u_(Z,k0(B)),Us("Downloaded artifact",2)}catch(Z){Us(String((Z==null?void 0:Z.message)||Z||"Download failed"),3)}}async function ed(b){const T=String((b==null?void 0:b.run_id)||"").trim(),F=String((b==null?void 0:b.artifact_id)||"").trim();if(!T||!F){Us("Artifact preview needs a run id",3);return}const B=rg(b),Z=String((b==null?void 0:b.content_type)||"").trim().toLowerCase(),X=Jh(b);if(Io(B||F),ra(""),eo(""),El(X),Tl(b),Cl(!0),or&&(URL.revokeObjectURL(or),Vu("")),X==="binary"){ra(`(Binary artifact: ${Z||"unknown"}; download to view.)`);return}if(X==="text"&&typeof b.size_bytes=="number"&&b.size_bytes>15e5){ra(`(Text artifact is ${b.size_bytes.toLocaleString()} bytes; download to view.)`);return}kr(!0);try{const ee=await Ke.download_run_artifact_content(T,F,{access:"preview"});if(X==="text"){const oe=await ee.text(),Ge=sg(b,oe),ke=Ge==="json"?15e5:Ge==="markdown"?25e4:Ge==="html"?3e5:22e3;ra(oe.length>ke&&Ge!=="text"?`${ru(b.size_bytes??oe.length)} ${Ge.toUpperCase()} artifact. Download to inspect it.`:oe.length>ke?`${oe.slice(0,Math.max(0,ke-1))}…`:oe)}else Vu(URL.createObjectURL(ee))}catch(ee){eo(String((ee==null?void 0:ee.message)||ee||"Preview failed"))}finally{kr(!1)}}p.useEffect(()=>()=>{or&&URL.revokeObjectURL(or)},[or]);async function td(b){const T=String(b.artifact_id||"").trim(),F=String(b.run_id||"").trim(),B=Jh(b);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 ${b.content_type||b.modality||"this artifact"}. Download to inspect it.`,url:"",loading:!1,error:""};if(B==="text"&&typeof b.size_bytes=="number"&&b.size_bytes>5e5)return{artifact_id:T,kind:B,render_kind:"",text:`${ru(b.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=sg(b,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"?`${ru(b.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 f_(b){if(Lo.url&&URL.revokeObjectURL(Lo.url),!b){Uu(Cf());return}const T=String(b.artifact_id||"").trim(),F=Jh(b);Uu({artifact_id:T,kind:F,render_kind:"",text:"",url:"",loading:!0,error:""}),Uu(await td(b))}function kn(b){const T=String(b.id||"").trim()||Zs();_f(F=>[{...b,id:T},...F].slice(0,800))}function Us(b,T){ml(b),oi.current&&window.clearTimeout(oi.current),qi(!1),window.requestAnimationFrame(()=>qi(!0)),oi.current=window.setTimeout(()=>{qi(!1),oi.current=null},1500),jo.current&&(window.clearTimeout(jo.current),jo.current=null),T>0&&(jo.current=window.setTimeout(()=>{ml(""),jo.current=null},Math.max(1,T)*1e3))}function lr(b,T){const F=String(b||"").trim(),B=String(T||"").trim();if(!B)return"";const Z=F?String(vc.current[F]||"").trim():"";return Z?`${Z}::${B}`:B}function nd(b,T,F){const B=String(b||"").trim(),Z=String(T||"").trim(),X=String(F||"").trim();if(!B||!Z||!X)return;const ee=lr(B,Z);ee&&(vc.current[X]=ee,Gr.current[X]=B,xc.current[X]={parent_run_id:B,parent_node_id:Z},Pa.current.has(X)||(Pa.current.add(X),Ou(oe=>oe.includes(X)?oe:[...oe,X])))}function Lc(b){const T=String(b||"").trim();if(!T)return;const F=Date.now(),B=No.current;No.current=T,Ia(F),Oa(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}),Iu(Z=>{if(typeof Z[T]=="number")return Z;const X={...Z,[T]:F};if(bl.current.push(T),bl.current.length>8e3){const ee=bl.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();Oa(X=>{const ee={};for(const[oe,Ge]of Object.entries(X))typeof Ge=="number"&&Ge>Z&&(ee[oe]=Ge);return ee}),Ia(Z),Hr.current=null},2200)}function sd(b,T){var lt,xn,qt;const F=String(T||"").trim()||l.trim();Ar.current=b.cursor,(lt=As.current)==null||lt.push({cursor:b.cursor,record:b.record}),F&&Ei.current.add(`${F}:${b.cursor}`);const B=lp(b.record),Z=B&&B.name?Ih(B.name):"",X=b.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((xn=X==null?void 0:X.effect)==null?void 0:xn.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:en}=kd(B==null?void 0:B.payload);Us(ft,en)}const Fe=ee?lr(ye,ee):"";if(oe==="waiting"){const ft=Za(X);if(String((ft==null?void 0:ft.reason)||"").trim()==="subworkflow"){const Yn=typeof((qt=ft==null?void 0:ft.details)==null?void 0:qt.sub_run_id)=="string"?String(ft.details.sub_run_id):"";Yn&&ee&&nd(ye,ee,Yn)}}if(ee&&(Lc(lr(ye,ee)),oe==="waiting"||oe==="running")){const ft=lr(ye,ee);ft&&(No.current=ft,Qo(ft))}let Pe="step",st=Fe||ee||"(node?)",pt="";if(B&&B.name&&Ew(B.name))Pe=Z==="abstract.message"?"message":"event",st=Z||B.name,pt=tn(Z==="abstract.steer_seen"?Cw(B==null?void 0:B.payload):kd(B==null?void 0:B.payload).text);else if(X!=null&&X.error)Pe="error",st="error",pt=tn(zr(X.error,360));else if(oe==="waiting"){const ft=Za(X),en=String((ft==null?void 0:ft.reason)||"").trim();pt=tn(en?`waiting • ${en}`:"waiting")}else X!=null&&X.result?pt=tn(zr(X.result,360)):Ge?pt=tn(Ge):pt=tn(Mp(X));kn({id:`step:${ke||F||"?"}:${b.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:b.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 h_(b,T){var pt,lt,xn;Bn.current=Math.max(Bn.current,T.cursor);const F=`${b}:${T.cursor}`;if(!!Ei.current.has(F))return;Ei.current.add(F),(pt=ws.current)==null||pt.push({run_id:b,cursor:T.cursor,record:T.record});const Z=lp(T.record),X=Z&&Z.name?Ih(Z.name):"",ee=T.record,oe=typeof(ee==null?void 0:ee.node_id)=="string"?ee.node_id:"",Ge=oe?lr(b,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=Za(ee);if(String((qt==null?void 0:qt.reason)||"").trim()==="subworkflow"){const en=typeof((xn=qt==null?void 0:qt.details)==null?void 0:xn.sub_run_id)=="string"?String(qt.details.sub_run_id):"";en&&oe&&nd(b,oe,en),en&&xr.current.trim()===String(b||"").trim()&&(xr.current=en,Ai(en))}}if(oe&&(Lc(lr(b,oe)),ke==="waiting"||ke==="running")){const qt=lr(b,oe);qt&&(No.current=qt,Qo(qt))}if((ke==="completed"||ke==="failed")&&xr.current.trim()===String(b||"").trim()){const qt=String(Gr.current[String(b||"").trim()]||"").trim();qt&&qt!==l.trim()?(xr.current=qt,Ai(qt)):(xr.current="",Ai(""))}if(X==="abstract.status"&&b===l.trim()){const{text:qt,duration:ft}=kd(Z==null?void 0:Z.payload);Us(qt,ft)}let Fe="step",Pe=Ge||oe||"(node?)",st="";if(Z&&Z.name&&Ew(Z.name))Fe=X==="abstract.message"?"message":"event",Pe=`subrun • ${X||Z.name}`,st=tn(X==="abstract.steer_seen"?Cw(Z==null?void 0:Z.payload):kd(Z==null?void 0:Z.payload).text);else if(ee!=null&&ee.error)Fe="error",Pe="error",st=tn(zr(ee.error,360));else if(ke==="waiting"){const qt=Za(ee),ft=String((qt==null?void 0:qt.reason)||"").trim();st=tn(ft?`waiting • ${ft}`:"waiting")}else ee!=null&&ee.result?st=tn(zr(ee.result,360)):ye?st=tn(ye):st=tn(Mp(ee));kn({id:`step:${b}:${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:b,node_id:Ge||oe,status:ke,effect_type:ye,emit_name:X||(Z==null?void 0:Z.name)||""})}function m_(b,T){var lt,xn,qt;const F=String(b||"").trim();if(!F)return;const B=`${F}:${T.cursor}`;if(!!Ei.current.has(B))return;Ei.current.add(B),(lt=ws.current)==null||lt.push({run_id:F,cursor:T.cursor,record:T.record});const X=lp(T.record),ee=X&&X.name?Ih(X.name):"",oe=T.record,Ge=typeof(oe==null?void 0:oe.node_id)=="string"?oe.node_id:"",ke=Ge?lr(F,Ge):"",ye=typeof(oe==null?void 0:oe.status)=="string"?oe.status:"",Fe=typeof((xn=oe==null?void 0:oe.effect)==null?void 0:xn.type)=="string"?oe.effect.type:"";if(ye==="waiting"){const ft=Za(oe);if(String((ft==null?void 0:ft.reason)||"").trim()==="subworkflow"){const Yn=typeof((qt=ft==null?void 0:ft.details)==null?void 0:qt.sub_run_id)=="string"?String(ft.details.sub_run_id):"";Yn&&Ge&&nd(F,Ge,Yn)}}if(Ge&&(Lc(lr(F,Ge)),ye==="waiting"||ye==="running")){const ft=lr(F,Ge);ft&&(No.current=ft,Qo(ft))}if(ee==="abstract.status"&&F===l.trim()){const{text:ft,duration:en}=kd(X==null?void 0:X.payload);Us(ft,en)}let Pe="step",st=ke||Ge||"(node?)",pt="";if(X&&X.name&&Ew(X.name))Pe=ee==="abstract.message"?"message":"event",st=`subrun • ${ee||X.name}`,pt=tn(ee==="abstract.steer_seen"?Cw(X==null?void 0:X.payload):kd(X==null?void 0:X.payload).text);else if(oe!=null&&oe.error)Pe="error",st="error",pt=tn(zr(oe.error,360));else if(ye==="waiting"){const ft=Za(oe),en=String((ft==null?void 0:ft.reason)||"").trim();pt=tn(en?`waiting • ${en}`:"waiting")}else oe!=null&&oe.result?pt=tn(zr(oe.result,360)):Fe?pt=tn(Fe):pt=tn(Mp(oe));kn({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 Jf(b,T){var B,Z;let F=T.after;for(;;){if((B=T.signal)!=null&&B.aborted)return F;const X=await Ke.get_ledger(b,{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 Ar.current=F,F;const oe=F;for(let Ge=0;Ge<ee.length;Ge++){const ke=ee[Ge];sd({cursor:oe+Ge+1,record:ke},b)}F=typeof X.next_after=="number"?X.next_after:F}}async function rd(b){var X,ee,oe,Ge;const T=String(b||"").trim();An(""),Qt(!0),is(!1),(X=As.current)==null||X.reset(),(ee=ws.current)==null||ee.reset(),_r.current={scanned:0,found:null},Xe([]),Ar.current=0,cn([]),Ei.current=new Set,_f([]),qm(""),ml(""),Nt(null),ai(""),jf(""),Qo(""),No.current="",Oa({}),Iu({}),bl.current=[],Ia(Date.now()),vc.current=T?{[T]:""}:{},Gr.current={},xc.current={},Pa.current=new Set,Ou([]),Co.current="",xr.current="",Ai(""),ea.current={},Hr.current&&window.clearTimeout(Hr.current),Hr.current=null,rr.current&&window.clearTimeout(rr.current),rr.current=null,Eo.current&&Eo.current.abort(),vr.current&&vr.current.abort(),vr.current=null,Bn.current=0,jl("");const F=new AbortController;Eo.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=Uj(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():"";jf(pt)}catch{jf("")}ke&&ye&&($(ke),v(ye),wr(ye),await ls(ke)),await Jf(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)Pa.current.add(lt);Ou(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 xn="",qt=-1;for(const ft of pt){const en=typeof((Ge=Pe==null?void 0:Pe[ft])==null?void 0:Ge.total)=="number"?Number(Pe[ft].total):0;en>qt&&(xn=ft,qt=en)}xn&&qt>Math.max(lt*3,lt+20)&&(xr.current=xn,Ai(xn))}catch{}}}catch{}is(!0),kn({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");An(ye),kn({ts:on(),kind:"error",title:"Connection error",preview:tn(ye),data:{error:ye}}),is(!1)}finally{F.signal.aborted||Qt(!1)}if(!B||F.signal.aborted)return;(async()=>{let ke=250;for(;!F.signal.aborted;){try{const ye=await Jf(T,{after:Ar.current,signal:F.signal});await Ke.stream_ledger(T,{after:ye,on_step:Fe=>sd(Fe,T),signal:F.signal})}catch(ye){if(F.signal.aborted)break;const Fe=String((ye==null?void 0:ye.message)||ye||"stream error");kn({ts:on(),kind:"error",title:"Ledger stream error (will retry)",preview:tn(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 __(){const b=jr,T=(b==null?void 0:b.kind)==="bundle"?b.flow_id:(b==null?void 0:b.kind)==="default"?"@default":"",F=(b==null?void 0:b.kind)==="bundle"?b.bundle_id:"";if(!b){const B="Select a workflow first (Launch → pick a workflow).";return An(B),B}An(""),Qt(!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 An(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=(Yr||[]).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 An(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}:{},...b.kind==="default"?{interface:b.interface}:{},session_id:String(P||"").trim()||null});return m(ye),d(ye),nr(""),await rd(ye),Dn(),null}catch(B){const Z=String((B==null?void 0:B.message)||B||"start failed");return An(Z),Z}finally{Qt(!1)}}async function Qg(){if(Dt([]),Le(null),!pe.available){Dt([pe.reason]);return}const b=r3(He,{choice:jr,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:Un.email_usable,defaults:Po,mailboxes:ci.mailboxes,connections:ci.trigger_connections},Se.current);if(!b.ok){Dt(b.errors);return}Q(!0);try{const T=await Ke.automations_client().createAutomation(b.body);Se.current.reset(),le([]),ct(nv),Rl.current="",kn({ts:on(),kind:"info",title:"Automation created",preview:tn(`${b.body.title} · ${T.automation_id}`)}),Ae(!1),t("automations"),await Un.refresh(),await Un.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 ey(){if(nr(""),je==="automate"){await Qg();return}const b=await __();if(b){nr(b);return}Ae(!1),So("ledger"),t("observe")}async function Yf(b){if(Qn("skills",void 0),!!b){if(b.kind==="default"){ze(b.interface),$(""),v(""),R(null);return}ze(""),$(b.bundle_id),v(b.flow_id),wr(b.flow_id),await ls(b.bundle_id)}}async function Xf(b){const[T,F]=await Promise.all([Ke.get_run(b),Ke.get_run_input_data(b)]),B=f3(T,F);await Yf(B.choice),S(JSON.stringify(B.input_data,null,2)),ct(B.form),le([`Recreating the legacy schedule ${Ln(b,14)} as an automation. The legacy schedule keeps running until you suspend it.`,...B.notes]),Se.current.reset(),nt("automate")}async function Ri(b,T){const F=String(b||"").trim();if(!F)return;if(Be){Us(`Still attaching — retry in a moment (${Ln(F,14)})`,2500);return}An(""),x("");const B=String((T==null?void 0:T.root_run_id)||F).trim()||F;m(B),d(F),await rd(F)}p.useEffect(()=>{const b=String(_||"").trim();if(!b)return;let T=!1;return(async()=>{try{if(L||await Do({open_modal_if_needed:!0}),T)return;So("ledger"),t("observe");const F=await Ke.find_run(b);if(T)return;if(F===null){Fl(),x(b);return}await Ri(b),ql()}catch(F){T||An(String((F==null?void 0:F.message)||F||"Failed to attach run from URL"))}finally{T||g("")}})(),()=>{T=!0}},[_]);function Fl(){var b,T;Eo.current&&Eo.current.abort(),Eo.current=null,vr.current&&vr.current.abort(),vr.current=null,Bn.current=0,jl(""),d(""),m(""),vc.current={},Gr.current={},xc.current={},Pa.current=new Set,Ou([]),Co.current="",xr.current="",Ai(""),ea.current={},ai(""),Hr.current&&window.clearTimeout(Hr.current),Hr.current=null,rr.current&&window.clearTimeout(rr.current),rr.current=null,is(!1),Qt(!1),Fn(!1),Ar.current=0,(b=As.current)==null||b.reset(),(T=ws.current)==null||T.reset(),_r.current={scanned:0,found:null},Xe([]),cn([]),Ei.current=new Set,Nt(null),_f([]),Qo(""),No.current="",Oa({}),Iu({}),bl.current=[],Ia(Date.now()),Us("",-1),An(""),bn([]),Hn(null),De(""),ht(""),pn(!1),Vi(!1),Hi(""),mc(""),Ta(""),_c([]),ju(!1),Su(""),Nu(""),pl(!1),Ma("")}p.useEffect(()=>{bn([]),Hn(null),De(""),ht(""),pn(!1),Vi(!1),Hi(""),mc(""),Ta(""),_c([]),ju(!1),Su(""),Nu(""),pl(!1),Ma("")},[l]),p.useEffect(()=>{Ns==="chat"&&l.trim()&&L&&Oc()},[Ns,l,L,we==null?void 0:we.workflow_id]);async function Ic(b,T,F){const B=String(b||"").trim();if(!B)return An("Missing run_id"),"Missing run_id";An("");try{const Z={},X=String((F==null?void 0:F.reason)||"").trim();X&&(Z.reason=X),await Ke.submit_command({command_id:Zs(),run_id:B,type:T,payload:Z,client_id:"web_pwa"}),kn({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 Dn(Ke,{force:!0}),window.setTimeout(()=>void Dn(Ke,{force:!0}),900),window.setTimeout(()=>void Dn(Ke,{force:!0}),2400),null}catch(Z){const X=String((Z==null?void 0:Z.message)||Z||`${T} failed`);return An(X),X}}async function ty(b,T){const F=b.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:Zs(),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)),kn({ts:on(),kind:X?"error":"info",title:`cancel submitted ×${F.length}${X?` · ${X} failed`:""}`,preview:"",data:{run_ids:F,failed:X}}),F.length&&(Dn(Ke,{force:!0}),window.setTimeout(()=>void Dn(Ke,{force:!0}),2400)),B}async function Zf(b,T){return Ic(l.trim(),b,T)}async function mi(b,T="Stopped from AbstractObserver"){const F=String(b||"").trim();if(!F||!window.confirm(`Cancel run ${Ln(F,24)}?`))return;await Ic(F,"cancel",{reason:T})||Us("Cancel submitted",2)}async function Qf(){var F;const b=l.trim();if(!b){An("Select a run first.");return}if(!L){An("Connect to the gateway first.");return}if(Mt)return;const T=String(((F=we==null?void 0:we.waiting)==null?void 0:F.reason)||"").trim().toLowerCase()||String(Ws||"").trim().toLowerCase();if(!Jn||_i||xs||Cs.toLowerCase()!=="waiting"||T!=="until"){An("This run is not a scheduled wait that can be triggered now.");return}An(""),Fn(!0);try{const B={payload:{mode:"run_now",requested_at:on()}},Z=String(cr||"").trim();Z&&(B.wait_key=Z),await Ke.submit_command({command_id:Zs(),run_id:b,type:"resume",payload:B,client_id:"web_pwa"}),kn({ts:on(),kind:"info",title:"Scheduled run triggered",preview:tn(`run ${b}`),data:{run_id:b,until:ao||null}});try{const X=await Ke.get_run(b);Nt(X)}catch{}}catch(B){An(String((B==null?void 0:B.message)||B||"Failed to trigger scheduled run"))}finally{Fn(!1)}}async function id(b){const T=l.trim();if(!T)return An("Missing run_id"),"Missing run_id";if(ii)return"Schedule update already in progress";const F=String(b.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 Ss(Z),Z}Ss(""),An(""),Ui(!0),Qt(!0);try{await Ke.submit_command({command_id:Zs(),run_id:T,type:"update_schedule",payload:{interval:F,apply_immediately:b.apply_immediately!==!1},client_id:"web_pwa"}),kn({ts:on(),kind:"info",title:"Schedule updated",preview:tn(`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 Ss(X),An(X),X}finally{Qt(!1),Ui(!1)}}async function p_(b){const T=l.trim();if(!T)return An("Missing run_id"),"Missing run_id";if(zs)return"Compaction already in progress";const F=typeof(b==null?void 0:b.preserve_recent)=="number"?b.preserve_recent:fl,B=Math.max(0,Math.min(500,Math.floor(Number.isFinite(F)?F:6))),Z=(b==null?void 0:b.compression_mode)||Tr,X=String((b==null?void 0:b.focus)??Wi??"").trim();Fs(""),An(""),gr(!0),Qt(!0);try{const ee={preserve_recent:B,compression_mode:Z};return X&&(ee.focus=X),await Ke.submit_command({command_id:Zs(),run_id:T,type:"compact_memory",payload:ee,client_id:"web_pwa"}),kn({ts:on(),kind:"info",title:"Compaction requested",preview:tn(`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 Fs(oe),An(oe),oe}finally{Qt(!1),gr(!1)}}async function g_(){const b=l.trim();if(!b){ht("Select a run first.");return}if(!L){ht("Connect to the gateway first.");return}const T=Oe.trim();if(!T||Bt)return;if(oo.voice_ptt_busy){Pt("Wait for transcription to finish.");return}ht(""),Pt(""),pn(!0);const B={id:`local:${Zs()}`,role:"user",content:T,ts:on()};bn(Z=>[...Z,B]),De("");try{const Z=UI(Ft,B),X=n.maintenance_ai_provider.trim(),ee=n.maintenance_ai_model.trim(),oe=await Ke.run_chat(b,{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),bn(ye=>[...ye,{id:`local:${Zs()}`,role:"assistant",content:Ge,ts:ke}])}catch(Z){const X=SO(Z);ht(X),bn(ee=>[...ee,{id:`local:${Zs()}`,role:"assistant",content:`(error: ${X})`,ts:on(),local_error:!0}])}finally{pn(!1)}}function y_(b){const T=String(b.id||b.ts||"").trim(),F=String(b.content||"").trim();!T||!F||(Pt(""),oo.toggle_tts(T,F))}function eh(b){const T=String(b.id||b.ts||"").trim(),F=oo.tts_playback;return!T||!F.key||F.key!==T?"idle":F.status}function Va(b){if(!Ft.length)return;const T=l.trim(),F=T?`Run ${T}`:"Chat",B=lN(Ft.map(Z=>({role:Z.role,content:Z.content,ts:Z.ts})),{heading:F});if(b==="download"){const Z=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),X=`abstractobserver-chat-${k0(T||"run")}-${Z}.md`;cN({filename:X,text:B,mime:"text/markdown;charset=utf-8"});return}(async()=>{const Z=await il(B);Js(Z?"copied":"failed"),window.setTimeout(()=>Js("idle"),900)})()}async function Oc(){const b=typeof(we==null?void 0:we.workflow_id)=="string"?String(we.workflow_id).trim():"";if(!b){_c([]);return}if(L&&!pc){Su(""),ju(!0);try{const T=await Ke.list_runs({limit:200,workflow_id:b,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){_c([]);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 xn=typeof lt.thread_id=="string"?String(lt.thread_id).trim():"";if(!xn||Ge.has(xn))continue;Ge.add(xn);const qt=typeof lt.created_at=="string"?String(lt.created_at):"",ft=typeof lt.title=="string"?String(lt.title):"",en=typeof lt.workflow_id=="string"?String(lt.workflow_id):b,Yn=typeof lt.run_id=="string"?String(lt.run_id):ke.run_id,us=typeof lt.provider=="string"?String(lt.provider):"",dr=typeof lt.model=="string"?String(lt.model):"",yi=typeof lt.message_count=="number"?Number(lt.message_count):null,wi=lt.chat_artifact,Vl=wi&&typeof wi=="object"&&typeof wi.$artifact=="string"?String(wi.$artifact):"";Vl&&oe.push({thread_id:xn,created_at:qt,title:ft||`Chat ${xn.slice(0,8)}`,run_id:Yn,workflow_id:en,message_count:yi,provider:us,model:dr,artifact_id:Vl})}}oe.sort((ke,ye)=>String(ye.created_at||"").localeCompare(String(ke.created_at||""))),_c(oe)}catch(T){Su(String((T==null?void 0:T.message)||T||"Failed to load saved discussions"))}finally{ju(!1)}}}async function th(){const b=l.trim();if(!b){Hi("Select a run first.");return}if(!L){Hi("Connect to the gateway first.");return}if(Ft.length&&!yr){Hi(""),Vi(!0);try{const T=n.maintenance_ai_provider.trim(),F=n.maintenance_ai_model.trim(),B=await Ke.save_chat_thread(b,{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();mc(Z);try{const ee=JSON.stringify(Ft.map(oe=>({role:oe.role,content:oe.content,ts:oe.ts})));Ta(ee)}catch{Ta("1")}typeof(B==null?void 0:B.thread_id)=="string"&&String(B.thread_id).trim()&&Nu(String(B.thread_id).trim());const X=!!(B!=null&&B.duplicate);Us(X?"Already saved":"Saved discussion",2),await Oc()}catch(T){Hi(String((T==null?void 0:T.message)||T||"Failed to save discussion"))}finally{Vi(!1)}}}async function ny(){const b=String(hf||"").trim();if(!b)return;const T=df.find(Z=>String(Z.thread_id||"").trim()===b)||null;if(!T){Ma("Saved discussion not found (refresh list).");return}if(!L){Ma("Connect to the gateway first.");return}if($u)return;const F=Ft.length>0,B=(()=>{if(!F)return!1;if(!Aa)return!0;try{return JSON.stringify(Ft.map(X=>({role:X.role,content:X.content,ts:X.ts})))!==Aa}catch{return!0}})();if(!(F&&B&&!window.confirm("Replace the current chat with the selected saved discussion? Unsaved changes will be lost."))){Ma(""),pl(!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:${b}:${ye}`,role:Pe,content:st.trim(),ts:pt})}bn(ke),Hn(null),De(""),ht(""),Hi(""),mc(Ge||"");try{const ye=JSON.stringify(ke.map(Fe=>({role:Fe.role,content:Fe.content,ts:Fe.ts})));Ta(ye)}catch{Ta("1")}Us("Loaded discussion",2)}catch(Z){Ma(String((Z==null?void 0:Z.message)||Z||"Failed to load saved discussion"))}finally{pl(!1)}}}async function Pc(b){const T=l.trim(),F=String((un==null?void 0:un.wait_key)||"").trim();if(!T||!F){An("No active wait to resume");return}if(String((un==null?void 0:un.reason)||"").trim()==="subworkflow"){An("This run is waiting on a subworkflow; attach to the child run instead of resuming manually.");return}An(""),Fn(!0);try{await Ke.submit_command({command_id:Zs(),run_id:T,type:"resume",payload:{wait_key:F,payload:b||{}},client_id:"web_pwa"}),kn({ts:on(),kind:"info",title:"Resume submitted",preview:tn(`wait_key: ${F}`),data:{wait_key:F,payload:b||{}}}),ai(F);try{const B=await Ke.get_run(T);Nt(B)}catch{}Dn(Ke,{force:!0}),window.setTimeout(()=>void Dn(Ke,{force:!0}),900),window.setTimeout(()=>void Dn(Ke,{force:!0}),2400),rr.current&&window.clearTimeout(rr.current),rr.current=window.setTimeout(()=>{ai(B=>B===F?"":B)},2e3)}catch(B){An(String((B==null?void 0:B.message)||B||"resume failed"))}finally{Fn(!1)}}async function w_(b){if(!so){An("No worker configured");return}if(!Mt){An(""),Fn(!0);try{const T=[];for(const F of b){const B=await so.call_tool(F);T.push(B)}await Pc({mode:"executed",results:T})}finally{Fn(!1)}}}const oa=p.useMemo(()=>of(un),[un]),cr=String((un==null?void 0:un.wait_key)||"").trim(),Ws=String((un==null?void 0:un.reason)||"").trim(),ao=typeof(un==null?void 0:un.until)=="string"?String(un.until):"",Cs=typeof(we==null?void 0:we.status)=="string"?String(we.status):"",xs=!!(we!=null&&we.paused),_i=Cs==="completed"||Cs==="failed"||Cs==="cancelled",v_=Ws==="until"&&!!ao,Dc=!_i&&$4(ar)&&(!!cr||v_),x_=Ws==="user",od=Ws==="event"?Ih(Rq(cr)):"",nh=Ws==="event"&&od==="abstract.ask",b_=oa.length>0,ad=Dc&&cr&&(x_||nh||b_)&&cf!==cr&&e!=="board"&&!(e==="observe"&&Ns==="agent"),aa=typeof((_d=un==null?void 0:un.details)==null?void 0:_d.sub_run_id)=="string"?String(un.details.sub_run_id):"",zl={run_id:l.trim(),workflow_id:typeof(we==null?void 0:we.workflow_id)=="string"?String(we.workflow_id):null,status:Cs,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},ld=fn.slice(-10).map(b=>{var T,F,B,Z,X,ee;return{cursor:b.cursor,node_id:String(((T=b.record)==null?void 0:T.node_id)||"").trim(),status:String(((F=b.record)==null?void 0:F.status)||"").trim(),effect_type:String(((Z=(B=b.record)==null?void 0:B.effect)==null?void 0:Z.type)||"").trim(),ts:String(((X=b.record)==null?void 0:X.ended_at)||((ee=b.record)==null?void 0:ee.started_at)||"").trim(),summary:E1(b.record)}}),cd=gx(un,oa),k_=S1(un,oa),ud=N1(un,rn),Fo=ud.text,sy=ud.runtime_metadata,Fc=String((un==null?void 0:un.prompt)||"").trim(),dd=f4(rn,6),j_=!!(Fc&&b1(Fc)),Bl=!!(Fc&&!j_),zo=Bl?"Question from workflow":Fo&&Fo!==Fc?"Closest prior user request":"Request context",ry=_4(rn,E),S_=!!E.trim(),Sr=we!=null&&we.schedule&&typeof we.schedule=="object"?we.schedule:null,Ha=typeof(Sr==null?void 0:Sr.interval)=="string"?String(Sr.interval).trim():"",N_=typeof(Sr==null?void 0:Sr.share_context)=="boolean"?!!Sr.share_context:null,Ul=typeof(Sr==null?void 0:Sr.repeat_count)=="number"?Number(Sr.repeat_count):null,Jn=!!(we!=null&&we.is_scheduled)||!!Sr,sh=Jn&&!!Ha,$_=Cs==="running"&&!xs?"Pause":"Resume",zc=Jn?xs?"resume":"pause":$_==="Pause"?"pause":"resume",ur=Jn?!l.trim()||Be||Mt||_i:!l.trim()||Be||Mt||_i||zc==="resume"&&!xs,iy=l.trim()?_i?"The schedule has ended.":null:"No run selected.",jt=Jn&&!xs&&!_i&&!Be&&!Mt&&Cs.toLowerCase()==="waiting"&&(String(((ha=we==null?void 0:we.waiting)==null?void 0:ha.reason)||"").trim().toLowerCase()==="until"||Ws==="until")&&!!String(ao||"").trim(),qs=(pd=we==null?void 0:we.limits)==null?void 0:pd.tokens,Ga=typeof(qs==null?void 0:qs.pct)=="number"?Number(qs.pct):null,rh=qs==null?void 0:qs.estimated_used,C_=(qs==null?void 0:qs.max_input_tokens)??(qs==null?void 0:qs.max_tokens),lo=p.useMemo(()=>{const b=_r.current;fn.length<b.scanned&&(b.scanned=0,b.found=null);for(let T=b.scanned;T<fn.length;T++){const F=fn[T],B=F==null?void 0:F.record;if(!B)continue;const Z=lp(B);if((Z&&Z.name?Ih(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()&&(b.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 b.scanned=fn.length,b.found},[fn]);p.useEffect(()=>{xr.current=Ir.trim()},[Ir]),p.useEffect(()=>{const b=l.trim(),T=aa.trim();if(!(Ht&&Ws==="subworkflow"&&!!T&&T!==b)){Co.current="",Ir.trim()&&Ai("");return}Co.current!==T&&(Co.current=T,xr.current=T,Ai(T))},[Ht,l,Ws,aa,Ir]),p.useEffect(()=>{Ru({})},[N]);const Bc=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]),Li=p.useMemo(()=>{const b=String((we==null?void 0:we.workflow_id)||"").trim();return Ht&&Jn?b:""},[Ht,Jn,we==null?void 0:we.workflow_id]),E_=p.useMemo(()=>{var ee;if(!Ht||!l.trim()||!Li.trim())return Lr;const b=String((we==null?void 0:we.status)||"").trim().toLowerCase(),T=String((we==null?void 0:we.current_node)||"").trim();if(b!=="waiting"&&b!=="running"||!T)return Lr;const F=lr(l.trim(),T);if(!F)return Lr;const B=String(Ws||((ee=we==null?void 0:we.waiting)==null?void 0:ee.reason)||"").trim().toLowerCase(),Z=typeof(ar==null?void 0:ar.node_id)=="string"?String(ar.node_id).trim():"",X=typeof(ar==null?void 0:ar.status)=="string"?String(ar.status).trim().toLowerCase():"";return b==="waiting"&&B==="until"||!Lr.trim()||(X==="waiting"||X==="running")&&!Z?F:Lr},[Ht,l,Li,we==null?void 0:we.status,we==null?void 0:we.current_node,(ma=we==null?void 0:we.waiting)==null?void 0:ma.reason,Ws,Lr,ar]),A_=p.useMemo(()=>{const b={},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=lr(B,X);if(!ee)return;const oe=String((Z==null?void 0:Z.ended_at)||(Z==null?void 0:Z.started_at)||"").trim(),Ge=Vt(oe);Ge!==null&&(b[ee]=Math.max(b[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 b},[fn,nn,l,$o]);p.useEffect(()=>{var F;if(!Ht||!l.trim()||!Li.trim())return;const b=String((we==null?void 0:we.current_node)||"").trim();!b||String(((F=we==null?void 0:we.waiting)==null?void 0:F.reason)||"").trim()==="subworkflow"||Lc(lr(l.trim(),b))},[Ht,l,Li,we==null?void 0:we.current_node,(dh=we==null?void 0:we.waiting)==null?void 0:dh.reason]),p.useEffect(()=>{const b=String((_s==null?void 0:_s.flow_id)||"").trim();b&&(vl.trim()||wr(b))},[_s,vl]),p.useEffect(()=>{const b=Li.trim(),T=N.trim(),F=vl.trim();if(b){let Z=!1;return Ra(!0),wc(""),Ke.get_workflow_flow(b).then(X=>{if(Z)return;const ee=X==null?void 0:X.flow;xl(ee&&typeof ee=="object"?ee:null)}).catch(X=>{Z||(xl(null),wc(String((X==null?void 0:X.message)||X||"Failed to load workflow flow")))}).finally(()=>{Z||Ra(!1)}),()=>{Z=!0}}if(!T||!F){xl(null),wc(""),Ra(!1);return}let B=!1;return Ra(!0),wc(""),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;xl(ee),ee&&Ru(oe=>({...oe,[F]:ee}))}).catch(Z=>{B||(xl(null),wc(String((Z==null?void 0:Z.message)||Z||"Failed to load flow")))}).finally(()=>{B||Ra(!1)}),()=>{B=!0}},[Li,N,vl,Ke]),p.useEffect(()=>{const b=N.trim();if(!Ji||!b||!Ki)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),xn=typeof lt=="string"?lt.trim():"";xn&&Fe.push(xn.includes(":")?xn.split(":",2)[1]:xn)}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=yc[Pe];st&&ee(st,ye+1)}};ee(Ki,0);const oe=Array.from(X).filter(ke=>!yc[ke]).slice(0,20);return oe.length?((async()=>{for(const ke of oe){if(T)return;try{const ye=await Ke.get_bundle_flow(b,ke),Fe=ye==null?void 0:ye.flow,Pe=Fe&&typeof Fe=="object"?Fe:null;if(!Pe)continue;Ru(st=>st[ke]?st:{...st,[ke]:Pe})}catch{}}})(),()=>{T=!0}):void 0},[Ji,N,Ki,yc,Ke]);const ih=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(Bc)).sort()},[D,Bc]);p.useEffect(()=>{_i&&Lr.trim()&&(Qo(""),No.current="")},[_i,l,Lr]),p.useEffect(()=>{const b=Ir.trim(),T=l.trim();if(!(Ht&&!!b&&b!==T)){vr.current&&vr.current.abort(),vr.current=null,Bn.current=0,Pu&&jl("");return}if(Pu===b)return;vr.current&&vr.current.abort();const B=new AbortController;vr.current=B,Bn.current=0,jl(b),kn({ts:on(),kind:"info",title:`Following run ${b} (status/events)`});let Z=250;return(async()=>{for(;!B.signal.aborted;){try{await Ke.stream_ledger(b,{after:Bn.current,on_step:ee=>h_(b,ee),signal:B.signal});return}catch(ee){if(B.signal.aborted)break;const oe=String((ee==null?void 0:ee.message)||ee||"stream error");kn({ts:on(),kind:"error",title:"Child ledger stream error (will retry)",preview:tn(oe),data:{child_run_id:b,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()}},[Ht,Ir,l,Ke,Pu]),p.useEffect(()=>{if(!Ht||!l.trim())return;let b=!1;const T=async()=>{if(!b&&!Da.current&&$o.length&&!(at.current>Date.now())){Da.current=!0;try{const B=$o.map(oe=>String(oe||"").trim()).filter(Boolean);if(!B.length)return;const Z=B.map(oe=>({run_id:oe,after:Number(ea.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(b)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(ea.current[oe]||0),Fe=Number(ea.current[oe]||0);for(let Pe=0;Pe<ke.length;Pe++){const st=ke[Pe];m_(oe,{cursor:Fe+Pe+1,record:st})}ea.current[oe]=ye}}catch(B){if(b||String((B==null?void 0:B.name)||"")==="Superseded")return;kn({ts:on(),kind:"error",title:"Subrun digest poll failed",preview:tn(String((B==null?void 0:B.message)||B||""))}),Fm("Subrun digest poll failed",tn(String((B==null?void 0:B.message)||B||"")))}finally{Da.current=!1}}};T();const F=window.setInterval(()=>void T(),2e3);return()=>{b=!0,window.clearInterval(F),Da.current=!1}},[Ht,l,$o,Ke]);const Ii=p.useMemo(()=>{const b=l.trim(),T=[];for(const F of fn)!F||!F.record||T.push({run_id:b,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]),Uc=p.useMemo(()=>{var T,F,B,Z;const b={};for(const X of Ii){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"&&(b[ee]=(b[ee]||0)+1)}return b},[Ii]),Ys=p.useMemo(()=>{const b=Ir.trim();if(b)return b;let T="",F=-1;for(const[B,Z]of Object.entries(Uc))Z>F&&(T=B,F=Z);return T||l.trim()},[Uc,Ir,l]),Oi=(Xg.trim()||Ys).trim(),la=p.useMemo(()=>{var Z;const b=new Set,T=l.trim(),F=Ir.trim();T&&b.add(T),F&&b.add(F);for(const X of $o){const ee=String(X||"").trim();ee&&b.add(ee)}for(const X of Ii){const ee=String(X.run_id||((Z=X.record)==null?void 0:Z.run_id)||"").trim();ee&&b.add(ee)}const B=Array.from(b);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,Ir,$o,Ii]),oh=p.useMemo(()=>{var b;for(let T=fn.length-1;T>=0;T--){const F=A1((b=fn[T])==null?void 0:b.record);if(F)return F}return""},[fn]);function T_(b){kf(b);const T=l.trim();if(!(!T||typeof window>"u"))try{window.history.replaceState(null,"",_O(GI(T),b))}catch{}}const Cn=p.useMemo(()=>{const b=l.trim();return b&&(On.find(T=>String(T.run_id||"").trim()===b)||mn.find(T=>String(T.run_id||"").trim()===b))||null},[On,mn,l]),gs=p.useMemo(()=>Cn||(we&&String((we==null?void 0:we.run_id)||"").trim()?ip(we):null),[Cn,we]),cs=gs?`${String(gs.run_id||"")}|${String(gs.workflow_id||"")}|${String(gs.automation_id||"")}|${String(gs.session_id||"")}`:"",M_=String((gs==null?void 0:gs.session_id)||"").trim(),R_=String((gs==null?void 0:gs.updated_at)||""),L_=Math.floor(Date.now()/6e4);p.useEffect(()=>{if(e!=="observe"||Ns!=="agent"||!M_||!L||Kn.key!==cs||Kn.loading)return;const b=he.current;Ke.list_runs({session_id:M_,include_metrics:!0,limit:200}).then(T=>{if(b!==he.current)return;const F=Array.isArray(T==null?void 0:T.items)?T.items.map(ip):[];Y(B=>B.key===cs?{...B,runs:F,runs_error:""}:B)}).catch(T=>{b===he.current&&Y(F=>F.key===cs?{...F,runs_error:String((T==null?void 0:T.message)||T||"failed")}:F)})},[R_,L_,Kn.key,Kn.loading]),p.useEffect(()=>{if(e!=="observe"||Ns!=="agent"||!cs||!L||Kn.key===cs)return;const b=gs,T=String(b.run_id||"").trim(),F=++he.current;Y({...Bj,key:cs,loading:!0});const B=String(b.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(b.automation_id||"").trim(),ee=String(b.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 xn;return lt.status==="rejected"?String(((xn=lt.reason)==null?void 0:xn.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(ip):[];Y({key:cs,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?Mm(Pe):null,automation_error:Fe(ke),runs:st,runs_error:Fe(ye)})})},[e,Ns,cs,L,Kn.key]);const fd=p.useMemo(()=>{const b=new Map;for(const T of Kn.runs)String(T.run_id||"").trim()&&b.set(String(T.run_id).trim(),T);for(const T of On){const F=String(T.run_id||"").trim();if(!F)continue;const B=b.get(F);b.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 gs&&!b.has(String(gs.run_id||"").trim())&&b.set(String(gs.run_id).trim(),gs),Array.from(b.values())},[Kn.runs,On,gs]),I_=p.useMemo(()=>lD(Ii,l.trim(),lr),[Ii,l,$o]),oy=p.useMemo(()=>{if(!gs)return null;const b=KC(gs,we),T=new Map;return we&&T.set(String(b.run_id||"").trim(),we),Qd(b,xx(fd,{now_ms:Lu,details:T}))},[gs,we,fd,Lu]),co=String((we==null?void 0:we.status)||(Cn==null?void 0:Cn.status)||"").trim(),ah=String(Ws||((fh=we==null?void 0:we.waiting)==null?void 0:fh.reason)||(Cn==null?void 0:Cn.waiting_reason)||"").trim().toLowerCase(),Zr=!!(we!=null&&we.is_scheduled||Cn!=null&&Cn.is_scheduled),Tn=!!(we!=null&&we.paused||Cn!=null&&Cn.paused),Is=Zr&&co.toLowerCase()==="waiting",Es=Is&&ah==="until",Vs=Vt(ao),Nr=Es&&Vs!==null?nm(Vs-Date.now()):"",uo=Qp(we),ys=Zr&&Tn?"Suspended":Is?"Scheduled":sm({status:co,paused:Tn,stop_reason:uo});async function Wl(){if(L){Bu(!0),Tf("");try{const b=Ao,T=b==="session"?String(Sl||ia||P||"").trim():"",F=b==="run"?String(Pn||l||"").trim():"",B=b4(na),Z=Nl.length?Nl.join(","):"",X=k4(Mo),ee=Math.max(0,Zi)*Np,oe=await Ke.search_artifacts({scope:b,session_id:T||void 0,run_id:F||void 0,query:Yi||void 0,artifact_kind:Z||void 0,created_after:B||void 0,include_stats:!0,limit:Np,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=w4(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=W0(oe);let st=Pe;if(Nl.length)try{const pt=await Ke.search_artifacts({scope:b,session_id:T||void 0,run_id:F||void 0,query:Yi||void 0,created_after:B||void 0,include_stats:!0,limit:1,offset:0,order_by:X.order_by,order:X.order});st=W0(pt)}catch{st=Pe}Fu(Number.isFinite(Fe)?Math.max(0,Fe):Ge.length),zu(Number((ye==null?void 0:ye.total_bytes)??(ye==null?void 0:ye.byte_total)??0)||0),Ym(Pe),Zm(st),kc(Ge),Ro(pt=>{var lt;return pt&&Ge.some(xn=>xn.artifact_id===pt)?pt:((lt=Ge[0])==null?void 0:lt.artifact_id)||""})}catch(b){Tf(String((b==null?void 0:b.message)||b||"Failed to load artifacts")),kc([]),Fu(0),zu(0),Ym({}),Zm({}),Ro("")}finally{Bu(!1)}}}async function ca(){if(L){Ku(!0),Or("");try{const b=await Ke.audit_log_tail({max_bytes:16e4}),T=typeof(b==null?void 0:b.bytes)=="number"?Number(b.bytes):0,F=!!(b!=null&&b.truncated);no(String((b==null?void 0:b.content)||"")),Rf(`${T.toLocaleString()} bytes${F?" (tail)":""}`)}catch(b){Or(String((b==null?void 0:b.message)||b||"Failed to load audit log")),no(""),Rf("")}finally{Ku(!1)}}}async function Wc(b){if(!L)return;const T=String(b||li||Pn||l||"").trim();if(!T){Sc([]),Ml(""),Of("Select a run in Activity or Artifacts to load its runtime ledger.");return}Ba(!0),Of("");try{const F=await Ke.get_ledger(T,{after:0,limit:2e3}),B=Array.isArray(F.items)?F.items:[];Sc(B.map((X,ee)=>({cursor:ee+1,record:X})));const Z=typeof F.next_after=="number"?Number(F.next_after):B.length;Ml(`${B.length.toLocaleString()} record${B.length===1?"":"s"}${Z>=2e3?" (first 2,000)":""}`)}catch(F){Of(String((F==null?void 0:F.message)||F||"Failed to load run ledger")),Sc([]),Ml("")}finally{Ba(!1)}}p.useEffect(()=>{L&&e==="runtime"&&Wl()},[L,e,Ao,Sl,Pn,Yi,Nl,na,Mo,Zi]),p.useEffect(()=>{L&&(Gu||to||e==="runtime"&&ca())},[L,e,Ns]),p.useEffect(()=>{if(!L||e!=="runtime"||bc!=="logs"||Zn!=="run_ledger"&&Zn!=="provider_calls")return;const b=String(li||Pn||l||"").trim();b&&Wc(b)},[L,e,bc,Zn,li,Pn,l]);const fo=p.useMemo(()=>{const b=new Map;for(const T of[...mn,...On]){const F=String(T.run_id||"").trim();F&&b.set(F,T)}for(const T of $o){const F=String(T||"").trim();!F||b.has(F)||b.set(F,{run_id:F,workflow_id:null,status:"",created_at:null,updated_at:null,ledger_len:null,parent_run_id:Gr.current[F]||null,session_id:ia||null})}return l.trim()&&!b.has(l.trim())&&b.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):ia||null}),Array.from(b.values()).sort((T,F)=>{const B=Vt(T.updated_at||T.created_at)??0;return(Vt(F.updated_at||F.created_at)??0)-B})},[On,mn,l,we,fn.length,$o,ia]),qc=p.useMemo(()=>nD(fo,{query:Tu,filter:Mu,group_by:gf,workflow_label_by_id:fi,parent_hint:b=>Gr.current[b]||""}),[fo,Tu,Mu,gf,fi]),Ms=p.useMemo(()=>{const b={};for(const T of fo){const F=String(T.run_id||"").trim();F&&(b[F]=T)}return b},[fo]),Vc=String(li||Pn||l||"").trim(),ua=Vc&&Ms[Vc]||null,ho=String(Sl||(ua==null?void 0:ua.session_id)||ia||P||"").trim(),Hc=p.useMemo(()=>Du.map(b=>ig(b,Ms,fi)),[Du,Ms,fi]);p.useEffect(()=>{ir(0)},[Yi,Nl,na,Pn,Mo,To,Ao,Sl]);const lh=Math.max(1,Math.ceil(jc/Np)),pi=Math.min(Math.max(0,Zi),lh-1);p.useEffect(()=>{Zi!==pi&&ir(pi)},[Zi,pi]);const mo=p.useMemo(()=>Hc,[Hc,pi]),da=p.useMemo(()=>{const b={};for(const T of mo){const F=To==="type"?av(T,Ms,fi):v4(T,To);b[F]||(b[F]=[]),b[F].push(T)}return Object.entries(b).map(([T,F])=>({key:T,items:F})).sort((T,F)=>{var B,Z;if(To==="time"){const X=Vt((B=T.items[0])==null?void 0:B.created_at)??0,ee=Vt((Z=F.items[0])==null?void 0:Z.created_at)??0;if(X!==ee)return ee-X}return T.key.localeCompare(F.key)})},[mo,To,Ms,fi]),fa=p.useMemo(()=>{const b=br.trim();return b?mo.find(T=>T.artifact_id===b)||mo[0]||null:mo[0]||null},[mo,br]);p.useEffect(()=>{e!=="runtime"||bc!=="artifacts"||f_(fa)},[e,bc,fa==null?void 0:fa.artifact_id]),p.useEffect(()=>()=>{Lo.url&&URL.revokeObjectURL(Lo.url)},[Lo.url]);const Gc=p.useMemo(()=>fo.filter(b=>Jd(b.status)),[fo]);p.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!L||se)return;let b=!1;return(async()=>{const[T,F]=await Promise.all([Ke.list_skills(),Ke.list_mcp_servers()]);b||(ne(T),Me(F),de(!0))})(),()=>{b=!0}},[e,L,se]);function ql(){gc&&window.setTimeout(()=>{var b;return(b=bf.current)==null?void 0:b.scrollIntoView({block:"start"})},60)}function Bo(b){So(b),ql()}const hd=[{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})}],$r={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},Uo=s.jsx(Z4,{connected:L,request:Yu,value:ro,onChange:b=>Qn("workspace",b===null?void 0:b),disabled:Be||Mt}),gi=s.jsx(s.Fragment,{children:jr?s.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",di.length?` · ${di.length} skill${di.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(b=>{var Z;const T=di.includes(b.name),F=b.blocked===!0,B=b.requires_review===!0&&!F;return s.jsxs("label",{className:`launch_skill_row ${F?"is_blocked":""} ${T?"is_on":""}`,title:[b.description||"",b.tree_hash?`tree ${b.tree_hash.slice(0,16)}…`:"",F&&((Z=b.reasons)!=null&&Z.length)?`blocked: ${b.reasons.join("; ")}`:""].filter(Boolean).join(`
175
+ `),children:[s.jsx("input",{type:"checkbox",checked:T,disabled:F||Be||Mt||ce,onChange:X=>{const ee=X.target.checked?Array.from(new Set([...di,b.name])):di.filter(oe=>oe!==b.name);Qn("skills",ee.length?ee:void 0)}}),s.jsx("span",{className:"launch_skill_name",children:b.name}),b.trust_level?s.jsx("span",{className:`chip ${F?"danger":B?"warn":"muted"}`,children:F?"blocked":B?"review":b.trust_level}):null,b.description?s.jsx("span",{className:"launch_skill_desc",children:b.description}):null]},b.name)})}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"The gateway's skills shelf is empty."}),di.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}),Dr=s.jsxs("section",{className:"launch_workspaces","data-section":"workspaces",style:{marginTop:"10px"},children:[s.jsx("div",{className:"launch_label launch_section_title",children:"Workspaces"}),Uo,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:$c,onChange:b=>Qn("workspace_root",b.target.value||void 0),placeholder:"/path/to/workspace",disabled:Be||Mt}),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."})]})})]}),O_=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:xo,type:"file",accept:".flow",style:{display:"none"},onChange:b=>{const T=b.target.files&&b.target.files.length?b.target.files[0]:null;T&&Hf(T)}}),s.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var b;return(b=xo.current)==null?void 0:b.click()},disabled:!L||V||$i||Be||Mt,title:"Upload a .flow bundle",children:$i?"…":"Upload .flow"}),s.jsxs("button",{type:"button",className:"btn launch_btn_reload",onClick:()=>void Vf(),disabled:!L||V||xt||Be||Mt,title:"Reload picks up server-side edits",children:[s.jsx(qe,{name:"refresh",size:14}),xt?"…":"Reload bundles"]})]})]});function md(b){t("observe"),So("ledger"),Ri(b)}const ch={on_select:b=>void Un.select(b),on_row_action:(b,T)=>{if(T==="discuss"||T==="edit")throw new Error(`${T} is routed by AutomationsPage (route_row_action), not the app handlers.`);if(T==="archive"){Un.ask_archive(b.automation_id);return}Un.row_action(b,T)},on_legacy_action:(b,T)=>{if(T==="open_run"){md(b.automation_id);return}if(T==="recreate"){Xf(b.automation_id).catch(F=>Un.report_error(F));return}Un.legacy_action(b,T)},on_confirm_archive:b=>void Un.row_action(b,"archive"),on_cancel_archive:()=>Un.ask_archive(""),on_status_filter:b=>void Un.set_status_filter(b),on_refresh:()=>void Un.refresh(),on_new:()=>nt("automate"),on_show_archived:b=>Un.set_show_archived(b)};return s.jsxs("div",{className:`app-shell shell${wf?" nav_open":""}`,children:[yf&&wf?s.jsx("div",{className:"shell_nav_backdrop","aria-hidden":"true",onClick:()=>Zo(!1)}):null,s.jsxs("aside",{className:"shell_sidebar",id:"shell_nav",ref:xf,...Gi.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:()=>Zo(!1),children:s.jsx(qe,{name:"x",size:16})})]}),s.jsxs("nav",{className:"shell_nav",children:[hd.map(b=>s.jsxs("button",{className:`shell_nav_item ${e===b.id?"active":""}`,onClick:()=>{t(b.id),Zo(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:b.icon}),s.jsx("span",{className:"shell_nav_label",children:b.label})]},b.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"),Zo(!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":V?"Gateway: connecting…":"Gateway: signed out",children:[s.jsx("span",{className:`gateway_led ${L?"ok":V?"warn":"err"}`,"aria-hidden":"true"}),s.jsx("span",{className:`shell_connection_label ${L&&((Kc=(gd=U==null?void 0:U.gateway)==null?void 0:gd.principal)!=null&&Kc.user_id)?"mono":""}`,children:L?((F_=(D_=U==null?void 0:U.gateway)==null?void 0:D_.principal)==null?void 0:F_.user_id)||(n.gateway_auth_mode==="direct"?"direct dev":"connected"):V?"connecting…":"signed out"}),L&&pf?s.jsxs("span",{className:"shell_connection_notice",role:"status",title:pf,children:[gl[gl.length-1].title,gl.reduce((b,T)=>b+T.count,0)>1?` ×${gl.reduce((b,T)=>b+T.count,0)}`:""]}):null]})})]}),s.jsxs("div",{className:"shell_main",...Gi.attrs.main,children:[s.jsxs("header",{className:"shell_header",children:[s.jsx("button",{ref:vf,type:"button",className:"shell_nav_toggle","data-nav-toggle":!0,"aria-label":"Open navigation","aria-controls":"shell_nav","aria-expanded":wf,title:"Navigation",onClick:()=>Zo(!0),children:s.jsx(qe,{name:"list",size:18})}),s.jsx("div",{className:"shell_header_title",children:$r[e]||"Observer"}),s.jsxs("div",{className:"shell_header_actions",children:[i?s.jsx("monitor-gpu",{ref:c,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(D2,{docs:{open:St,onToggle:()=>ut(b=>!b),label:"Docs assistant"},appearance:{onOpen:()=>bt(!0)},about:{identity:zf,versions:Bf,onOpen:ui},connection:{phase:J.phase,signingOut:J.signingOut,onConnect:()=>J.openModal(),onDisconnect:()=>hi()}})]})]}),s.jsx(YE,{...J.modalProps}),s.jsx(tS,{open:It,onClose:()=>bt(!1),value:yt,onChange:_t}),s.jsx(II,{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(iq,{gateway_connected:L,runs:mn,all_runs:On,runs_refreshed_at:Re,runs_stale:Kg,notice:pf,entities:re,entities_total:Ce,entities_error:We,on_open_run:b=>{t("observe"),So("agent"),Ri(b)},on_resume_wait:Gf,on_open_automation:b=>{Ae(!1),t("automations"),Un.refresh().then(()=>Un.select(b))},entity_app_href:o,on_read_diary:(b,T)=>Ke.read_entity_diary_entry(b,T),phase_graph:Tc,client:Ke,on_rename_automation:(b,T,F)=>Un.revise(b,{title:T},F??null),on_revise_automation:(b,T,F)=>Un.revise(b,T,F),on_automation_command:(b,T)=>Un.command(b,T),on_resume_run:b=>Ic(b,"resume"),on_cancel_run:b=>Ic(b,"cancel"),on_cancel_runs:ty,code_app:Ve,done_loaded:(()=>{const b=N9(Ke);return b!==null&&b.epoch===io.current&&b.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:V,children:V?"Connecting…":"Sign in"}),s.jsx("button",{className:"btn",onClick:()=>void Do({open_modal_if_needed:!0}),disabled:V,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:Yj(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:()=>hi(),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(PP,{checked:n.auto_connect_gateway,onChange:b=>r(T=>({...T,auto_connect_gateway:b}))})}),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:b=>r(T=>({...T,gateway_url:b.target.value})),placeholder:xg})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Dev bearer token"}),s.jsx("input",{type:"password",value:n.auth_token,onChange:b=>r(T=>({...T,auth_token:b.target.value,gateway_auth_mode:"direct"})),placeholder:"development only — prefer the sign-in dialog"})]}),s.jsx("button",{className:"btn",onClick:()=>void Do({prefer_direct:!0}),disabled:V,children:V?"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(Hj,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:Zu,models:Qu.models,loadingProviders:V,loadingModels:Wf,modelError:Pl?Qu.error:"",allowCustomProvider:!0,allowCustomModel:!0,allowGatewayDefault:!0,gatewayDefaultLabel:"(gateway default)",onChange:b=>r(T=>({...T,maintenance_ai_provider:b.provider,maintenance_ai_model:b.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(b=>{const T=n.assistant_skill_names.includes(b.name);return s.jsx(DP,{name:b.name,version:b.version,description:b.description,checked:T,onChange:F=>r(B=>({...B,assistant_skill_names:F?Array.from(new Set([...B.assistant_skill_names,b.name])):B.assistant_skill_names.filter(Z=>Z!==b.name)}))},b.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:b=>r(T=>({...T,worker_url:b.target.value})),placeholder:"https://your-mcp-worker-endpoint"}),s.jsx("input",{className:"mono",type:"password",value:n.worker_token,onChange:b=>r(T=>({...T,worker_token:b.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(K3,{gateway:L?Ke:null,connected:L,defaults:Kf,value:Rc,onChange:l_})})]})]})}):null,s.jsx(tc,{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(v3,{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(b=>s.jsx("div",{children:b},b))}):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(eN,{id:"launch-workflow-picker",className:"launch_workflow_picker",interfaceId:null,defaultInterface:Bd,ariaLabel:"Flow",workflows:Ol,entryDetail:Df,value:N0(jr,((hh=Ol.data)==null?void 0:hh.entries)??[]),currentLabel:jr&&!N0(jr,((mh=Ol.data)==null?void 0:mh.entries)??[])?{name:fi[Xu]||Xu}:null,unavailableReason:L?V?"Loading flows…":null:"Sign in to load flows.",onChange:(b,T)=>{const F=FO(b,T);F&&Yf(F)}})}),s.jsxs("div",{className:"field",children:[_s!=null&&_s.description?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(_s.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"}),jr?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."})]}):Cc?s.jsx("div",{className:"launch_inputs",children:(()=>{const b=Be||Mt,T=[],F=[];for(const X of Yr){if(!X||typeof X!="object")continue;const ee=String(X.id||"").trim();if(!ee||je==="automate"&&QN.includes(ee)||je==="automate"&&e1.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"||Wa(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:zr(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(us=>String(us||"").trim()).filter(Boolean):[],en=Array.isArray(Pe)?Pe.map(us=>String(us||"").trim()).filter(Boolean):[],Yn=Array.from(new Set([...Ec,...ft,...en])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx(Ww,{options:Yn,value:ft,disabled:b,placeholder:"(no tools selected)",onChange:us=>Qn(oe,us)})]},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(us=>String(us||"").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 en=(be||[]).map(us=>us.name),Yn=Array.from(new Set([...en,...ft])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx(Ww,{options:Yn,value:ft,disabled:b,placeholder:"(no MCP servers selected)",onChange:us=>Qn(oe,us)})]},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:en=>Qn(oe,en.target.value),disabled:b,children:[s.jsx("option",{value:"",children:lt||"(select)"}),ps.map(en=>s.jsx("option",{value:en,children:en},en))]})]},oe)}if(ye==="model"||ye==="model_text"){const ft=typeof pt=="string"?String(pt):"",en=String((rn==null?void 0:rn.provider)||"").trim(),Yn=en?hn[en]:void 0,us=Yn&&Array.isArray(Yn.models)?Yn.models.map(dr=>String(dr||"").trim()).filter(Boolean):[];return s.jsxs("div",{className:ee||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ke}),us.length?s.jsxs("select",{value:ft,onChange:dr=>Qn(oe,dr.target.value),disabled:b,children:[s.jsx("option",{value:"",children:lt||"(select)"}),us.map(dr=>s.jsx("option",{value:dr,children:dr},dr))]}):s.jsx("input",{value:ft,onChange:dr=>Qn(oe,dr.target.value),placeholder:lt||"model id",disabled:b})]},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:en=>{const Yn=String(en.target.value||"").trim();Yn?Qn(oe,Yn==="true"):Qn(oe,void 0)},disabled:b,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:en=>{const Yn=String(en.target.value||"").trim();if(!Yn){Qn(oe,void 0);return}const us=Number(Yn);Number.isFinite(us)&&Qn(oe,us)},placeholder:lt,disabled:b})]},oe)}if(ye==="array"){const ft=Array.isArray(pt)?pt.map(en=>String(en||"").trim()).filter(Boolean).join(`
176
+ `):"";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:en=>{const Yn=String(en.target.value||"").split(/\r?\n/g).map(us=>String(us||"").trim()).filter(Boolean);Qn(oe,Yn.length?Yn:void 0)},placeholder:lt||"(one item per line)",rows:2,disabled:b})]},oe)}if(Wa(ye)){const ft=typeof dc[oe]=="string"?dc[oe]:"",en=String(js[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:Yn=>{const us=String(Yn.target.value??"");ul(yi=>({...yi,[oe]:us}));const dr=us.trim();if(!dr){pr(yi=>{const wi={...yi};return delete wi[oe],wi}),Qn(oe,void 0);return}try{const yi=JSON.parse(dr);pr(wi=>{const Vl={...wi};return delete Vl[oe],Vl}),Qn(oe,yi)}catch(yi){pr(wi=>({...wi,[oe]:String((yi==null?void 0:yi.message)||yi||"Invalid JSON")}))}},placeholder:lt||"{...}",rows:3,disabled:b}),en?s.jsx("div",{className:"launch_field_error",children:en}):null]},oe)}const xn=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:xn,onChange:ft=>Qn(oe,ft.target.value),placeholder:lt||(oe==="prompt"?"What should the agent do?":"System instructions (optional)"),rows:3,disabled:b})]},oe):s.jsxs("div",{className:ee||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx("input",{value:xn,onChange:ft=>Qn(oe,ft.target.value),placeholder:lt,disabled:b})]},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:i_,onChange:b=>Qn("prompt",b.target.value),placeholder:"What do you want the workflow/agent to do?",rows:3,disabled:Be||Mt})]}),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:Il,onChange:b=>Qn("provider",b.target.value),placeholder:"lmstudio / ollama / openai / ...",disabled:Be||Mt})]})}),s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Model (common)"}),s.jsx("input",{value:o_,onChange:b=>Qn("model",b.target.value),placeholder:"qwen/qwen3-next-80b / gpt-4.1 / ...",disabled:Be||Mt})]})})]})]}):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(x3,{form:He,email_status:ci.email_status,on_open_my_email:Oo,served:Ll,on_open_preferences:Oo,defaults:Po,connections:ci.trigger_connections,mailboxes:ci.mailboxes,tools:pS(rn||{})??void 0,available_tools:Ec,on_tools_change:b=>S(JSON.stringify(gS(rn||{},b),null,2)),disabled:ce,on_change:b=>ct(T=>({...T,...b})),workspaces:Uo}),s.jsx(b3,{form:He,disabled:ce,on_change:b=>ct(T=>({...T,...b}))}),gi]}):s.jsxs(s.Fragment,{children:[gi,Dr,O_]}),s.jsx("div",{className:"section_divider"}),zn?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:zn})]}):null,je==="automate"&&Qe.length?s.jsx("ul",{className:"automate_errors",role:"alert",children:Qe.map(b=>s.jsx("li",{children:b},b))}):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:Vp($e).title})," ",Vp($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 b=je==="automate",T=L?jr?rn===null?"Inputs contain invalid JSON":b&&!pe.available?"Automations unavailable on this gateway":Be||Mt?"Attaching to a run…":V||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 ey(),disabled:!!T,title:T,children:b?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(OP,{workflowPickerOptions:{interfaceId:null,defaultInterface:Bd,workflows:Ol,entryDetail:Df,request:(b,T)=>Ke.get_gateway_json(b,T.signal)},availableTools:Ec,ctl:Un,gateway:Ke,active:e==="automations"&&L,available:pe,h:ch,voice_session_id:P,workspace_request:Yu,host:{on_open_run:b=>md(b),...Oo?{on_open_my_email:Oo}:{},on_open_session:(b,T)=>{kn({ts:on(),kind:"info",title:"Discussion started",preview:tn(T),data:b})}}}):null,e==="runtime"?s.jsx(V4,{runs_loading:rs,gateway_connected:L,tab:bc,runs:fo,active_runs:Gc,all_artifacts:Du,artifacts:mo,artifact_total_count:jc,artifact_total_bytes:Ef,artifact_facets:Af,artifact_type_facets:Xm,artifact_page:pi,artifact_page_size:Np,artifact_groups:da,selected_artifact:fa,embedded_preview:Lo,loading:Zg,error:ta,query:Yi,scope:Ao,type_filters:Nl,date_filter:na,group_by:To,sort_by:Mo,artifact_run_filter:Pn,audit_log_text:to,audit_log_meta:za,audit_log_loading:Gu,audit_log_error:Jr,workflow_label_by_id:fi,run_by_id:Ms,selected_run_id:Vc,session_id:ho,runtime_log_source:Zn,runtime_log_query:t_,runtime_ledger_log_items:Lf,runtime_ledger_log_meta:s_,runtime_ledger_log_loading:r_,runtime_ledger_log_error:If,on_tab_change:Jm,on_query_change:Xi,on_scope_change:Ti,on_session_filter_change:Qm,on_type_filters_change:Fa,on_date_filter_change:$l,on_group_by_change:Mf,on_sort_by_change:sa,on_artifact_page_change:ir,on_artifact_run_filter_change:b=>{const T=String(b||"").trim();Xn(T),T&&Ts(T),T&&Ao!=="run"&&Ti("run")},on_refresh_artifacts:()=>void Wl(),on_refresh_audit:()=>void ca(),on_refresh_runtime_ledger:b=>void Wc(b),on_runtime_log_source_change:Mi,on_runtime_log_query_change:n_,on_select_run:b=>{const T=String(b||"").trim();Ts(T);const F=T&&Ms[T]||null,B=String((F==null?void 0:F.session_id)||"").trim();B&&Qm(B)},on_select_artifact:Ro,on_preview_artifact:b=>void ed(b),on_download_artifact:b=>void d_(b),on_open_run:b=>{Ts(String(b||"").trim()),t("observe"),So("ledger"),Ri(b)},on_open_ledger:b=>{Ts(String(b||"").trim()),t("observe"),So("ledger"),Ri(b)},on_refresh_runs:()=>void Dn(Ke,{force:!0}),on_reconnect:()=>void Do({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:L?s.jsx(xU,{gateway:Ke,selected_run_id:li,selected_session_id:ho}):null}):null,e==="observe"?s.jsx("div",{className:"page observe_page",children:s.jsxs("div",{className:`observatory_layout${Bm?"":" list_collapsed"}`,children:[s.jsx(G4,{sections:qc,selected_run_id:l,root_run_id:h,search:Tu,filter:Mu,group_by:gf,loading:rs,connected:L,on_sign_in:()=>J.openModal(),total_runs:fo.length,workflow_label_by_id:fi,automation_titles:Ff,on_search:zm,on_filter:wl,on_group_by:Yg,on_refresh:()=>void Dn(),on_select:(b,T)=>{Ri(b,{root_run_id:T||b}),ql()},list:{open:Bm,on_toggle:Um}}),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:fi[String((Cn==null?void 0:Cn.workflow_id)||"")]||String((Cn==null?void 0:Cn.workflow_id)||"").trim()||Ln(l.trim(),22)}),s.jsx("span",{className:"chip mono muted",children:Ln(l.trim(),14)}),s.jsx("span",{className:`chip ${Sa(ys||co,uo)}`,title:String((uo==null?void 0:uo.headline)||""),children:ys||co||"unknown"})]}):y?s.jsx("span",{className:"observe_run_identity_empty observe_run_link_missing",role:"alert",children:KI(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:[Jn?s.jsx(zP,{active:!xs,unavailableReason:iy,busy:Be||Mt,onChange:b=>{if(!b){qr("pause"),Vr(""),Ci(""),Wr(!0);return}Zf("resume")}}):s.jsx("button",{className:"btn",onClick:()=>{if(zc==="pause"){qr("pause"),Vr(""),Ci(""),Wr(!0);return}Zf("resume")},disabled:ur,children:$_}),jt?s.jsx("button",{className:"btn primary",onClick:()=>void Qf(),disabled:Be||Mt||_i||xs,children:"Run now"}):null,s.jsx("button",{className:"btn danger",onClick:()=>{qr("cancel"),Vr(""),Ci(""),Wr(!0)},disabled:Be||Mt||_i,children:"Cancel"}),s.jsx("button",{className:"btn btn_icon",onClick:Fl,title:"Clear the run view",children:s.jsx(qe,{name:"x",size:14})})]}):null]}),l.trim()&&!_i?s.jsx("div",{className:"observe_steer_row",children:s.jsx(s2,{runId:l.trim(),parked:Dc,submit:(b,T)=>Ke.submit_command({command_id:`steer-${Zs()}`,run_id:b,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:()=>kn({ts:on(),kind:"info",title:"Steer queued",preview:"inject_guidance submitted — delivery shows as abstract.steer_seen in the ledger"})})}):null,Dc||Jn||Au?s.jsxs("div",{className:"observe_toolbar_context",children:[Dc?s.jsxs("div",{className:"observe_context_card info",children:[s.jsxs("div",{className:"observe_context_label",children:[(()=>{const b=Jn?xs?"suspended":"scheduled":"waiting";return s.jsx("span",{className:`chip ${Sa(b)}`,children:b})})(),s.jsx("span",{className:"muted",children:Ws||"unknown"})]}),s.jsxs("div",{className:"observe_context_body",children:[cr?s.jsxs("span",{className:"mono",title:cr,children:[s.jsx("span",{className:"muted",children:"wait_key"}),": ",Ln(cr,46)]}):null,Ws==="event"&&od?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"event"}),": ",od]}):null,Ws==="subworkflow"&&aa?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"child"}),": ",Ln(aa,18)]}):null,Ws==="until"&&ao?s.jsxs("span",{className:"mono",title:ao,children:[s.jsx("span",{className:"muted",children:"until"}),": ",Ln(ao,46)]}):null,Ws==="until"&&ao?s.jsx("span",{className:"mono muted",children:(()=>{const b=Vt(ao),T=b!==null?new Date(b).toLocaleString():ao,F=b!==null?nm(b-Date.now()):"";return`Next at ${T}${F?` (in ${F})`:""}`})()}):null]}),Ws==="subworkflow"&&aa?s.jsxs("div",{className:"observe_context_actions",children:[s.jsx("button",{className:"btn primary",onClick:async()=>{d(aa),await rd(aa)},disabled:Be,children:"Attach to child"}),h.trim()&&h.trim()!==l.trim()?s.jsx("button",{className:"btn",onClick:async()=>{d(h.trim()),await rd(h.trim())},disabled:Be,children:"Back to root"}):null]}):null]}):null,Jn?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:sh?`every ${Ha}`:"once"})]}),s.jsxs("div",{className:"observe_context_body",children:[Ha?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"interval"}),": ",Ha]}):null,s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"share ctx"}),": ",N_?"yes":"no"]}),typeof Ul=="number"?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"repeats"}),": ",Ul]}):null]}),Ga!==null?s.jsxs("div",{className:"observe_context_budget",children:[s.jsxs("span",{className:"mono muted",children:[typeof rh=="number"&&typeof C_=="number"?`${rh.toLocaleString()} / ${C_.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,Ga))*100)}%`]}),s.jsx("div",{className:"observe_budget_bar",children:s.jsx("div",{className:`observe_budget_fill ${Ga>=.9?"danger":Ga>=.75?"warn":"ok"}`,style:{width:`${Math.round(Math.max(0,Math.min(1,Ga))*100)}%`}})})]}):null,s.jsxs("div",{className:"observe_context_actions",children:[sh?s.jsx("button",{className:"btn",onClick:()=>{vs(Ha||""),Ls(!0),Ss(""),Bi(!0)},disabled:Be||ii,children:"Edit schedule"}):null,sh?s.jsx("button",{className:"btn",onClick:()=>{Fs(""),$a(!0)},disabled:Be||zs,children:"Compact context"}):null,s.jsx("button",{className:"btn",onClick:()=>void Xf(l.trim()).catch(b=>An(String((b==null?void 0:b.message)||b))),disabled:Be||!l.trim(),title:"Open Launch → Automate prefilled from this schedule (this schedule is not changed)",children:"Recreate as automation"})]})]}):null,Au?s.jsxs("div",{className:"observe_context_card error",children:[s.jsx("span",{className:"chip danger",children:"error"}),s.jsx("span",{className:"mono",children:Au})]}):null]}):null]}),s.jsxs("div",{className:"card panel_card card_scroll observe_viewer observe_viewer_full",ref:bf,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":Ns==="agent",className:`tab ${Ns==="agent"?"active":""}`,onClick:()=>Bo("agent"),children:"Agent"}),s.jsx("button",{role:"tab","aria-selected":Ns==="ledger",className:`tab ${Ns==="ledger"?"active":""}`,onClick:()=>Bo("ledger"),children:"Ledger"}),s.jsx("button",{role:"tab","aria-selected":Ns==="graph",className:`tab ${Ns==="graph"?"active":""}`,onClick:()=>Bo("graph"),children:"Flow"}),s.jsx("button",{role:"tab","aria-selected":Ns==="chat",className:`tab ${Ns==="chat"?"active":""}`,onClick:()=>Bo("chat"),children:"Ask"})]}),Ns==="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=Vt(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(`
177
+ `);Pr(Z)},children:"Copy JSONL"})}):null,Ns==="graph"?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsx("button",{className:`seg_action ${Ji?"active":""}`,"aria-pressed":Ji,onClick:()=>Nf(b=>!b),children:"Subflows"}),s.jsx("button",{className:`seg_action ${La?"active":""}`,"aria-pressed":La,onClick:()=>$f(b=>!b),children:"Path"}),ih.length?s.jsx("select",{className:"mono seg_select",value:vl,onChange:b=>wr(String(b.target.value||"")),disabled:!!Li.trim()||!N.trim()||Sf,children:ih.map(b=>s.jsx("option",{value:b,children:b},b))}):null]}):null]}),Ns==="agent"?l.trim()&&gs?s.jsx(Mq,{run:gs,detail:we,input_data:Kn.key===cs?Kn.input_data:null,flow:Kn.key===cs?Kn.flow:null,automation:Kn.key===cs?Kn.automation:null,automation_body:Kn.key===cs?Kn.automation_body:null,runs:fd,records:Ii,stall_after_ms:$C(typeof localStorage>"u"?null:localStorage),loading:{detail:Be&&!we,input_data:Kn.key!==cs||Kn.loading,flow:Kn.key!==cs||Kn.loading},errors:Kn.key===cs?{input_data:Kn.input_error||void 0,flow:Kn.flow_error||void 0}:{},on_open_run:b=>void Ri(b),on_ask:()=>Bo("chat"),on_action:(b,T)=>{if(b==="resume"){Ic(T,"resume");return}if(b==="open_subrun"){Ri(T);return}ai(""),Bo("ledger")},on_reveal_workspace:()=>void Dl(),on_copy:b=>void Pr(b)}):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,Ns==="ledger"?l.trim()?s.jsxs("div",{className:"rs_page",children:[s.jsx(MO,{status:ys||co||"unknown",duration:Cn?yu(Cn):"",facts:vO(wO(Ii)),error:rm(Cn)||String((we==null?void 0:we.error)||"").trim(),answer:oh||String((lo==null?void 0:lo.text)||"").trim(),waiting_for_user:!!(un!=null&&un.wait_key)&&String((un==null?void 0:un.reason)||"")==="user",on_answer_wait:()=>ai(""),workspace_root:Vm,on_reveal_workspace:()=>void Dl(),speak:L?s.jsx(eP,{voice:oo,speak_key:`outcome:${l.trim()}`,text:rm(Cn)||String((we==null?void 0:we.error)||"").trim()||oh||String((lo==null?void 0:lo.text)||"").trim(),error:Wt}):null,on_open_artifacts:()=>{const b=String(l||"").trim();b&&(Ts(b),Xn(b),Ti("run")),Jm("artifacts"),t("runtime")}}),s.jsx(TO,{items:Ii,run_id:Oi,run_options:la,run_llm_counts:Uc,on_select_run:b=>qm(b),state:Wm,on_state:T_,node_label:(b,T)=>{const F=T?(Xr==null?void 0:Xr[lr(b,T)])||(Xr==null?void 0:Xr[T]):null;return String((F==null?void 0:F.label)||T||"").trim()},on_copy:b=>void Pr(b),on_open_run:b=>void Ri(b,{root_run_id:h||l||b})})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run on the left to inspect it — or start one from Launch."}):null,Ns==="graph"?s.jsxs(s.Fragment,{children:[Hm?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:Hm})]}):null,Sf?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:Li.trim()?Li.trim():vl})]}),s.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,s.jsx("div",{className:"graph_panel",children:s.jsx(YD,{flow:Ki,flow_by_id:yc,expand_subflows:Ji,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:Nr,schedule_interval:Ha,node_last_ms:A_,active_node_id:E_,recent_nodes:Gm,visited_nodes:Km,highlight_path:La,now_ms:Lu,run_id:l.trim(),run_line:oy,run_status:ys||co,node_facts:I_,on_open_run:b=>void Ri(b)})})]}):null,Ns==="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(Ur,{value:hf,options:mf,placeholder:pc?"Loading…":mf.length?"Select a saved discussion…":"(none saved)",disabled:!l.trim()||!L||!mf.length,loading:pc,searchable:!0,clearable:!0,onChange:b=>{Nu(b),Ma("")}})}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[s.jsx("button",{className:"btn",type:"button",disabled:!hf.trim()||!L||$u,onClick:()=>void ny(),children:$u?"Loading…":"Load"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ft.length||Bt||yr||$u,onClick:()=>{bn([]),Hn(null),De(""),ht(""),Hi(""),mc(""),Ta("")},children:"Clear"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>void Oc(),disabled:!l.trim()||!L||pc,children:pc?"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||yr||!Cu,onClick:()=>void th(),title:Cu?"":"No changes since last save",children:yr?"Saving…":!Cu&&uf?"Saved":"Save discussion"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ft.length,onClick:()=>Va("download"),children:"Export Markdown"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ft.length,onClick:()=>Va("copy"),children:En==="copied"?"Copied":En==="failed"?"Copy failed":"Copy Markdown"})]}),uf?s.jsxs("div",{className:"chat_hint",children:["Last saved: ",cu(uf)]}):null,_l?s.jsx("div",{className:"chat_hint chat_hint_danger",children:_l}):null,Om?s.jsx("div",{className:"chat_hint chat_hint_danger",children:Om}):null,ff?s.jsx("div",{className:"chat_hint chat_hint_danger",children:ff}):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(lx,{messages:Ft,className:"log_scroll",after:s.jsx(qI,{history:as}),afterKey:as?`${as.replayed_messages}:${as.dropped_messages}`:null,messageProps:oo.tts_supported&&L?{onSpeakToggle:y_,getSpeakState:eh,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(cx,{ref:Rr,value:Oe,onChange:De,onSubmit:()=>void g_(),placeholder:"Ask about this run…",disabled:!l.trim()||!L||Bt,busy:Bt||oo.voice_ptt_busy,busyLabel:oo.voice_ptt_busy?"Transcribing…":"Thinking…",rows:3,sendButtonClassName:"btn primary",actions:s.jsx(m1,{voice:oo,defaults:Kf.value,prefs:Rc,blocked:L?Bt?"Wait for the answer.":null:"Connect to the gateway first."})}),l1()?null:s.jsx("div",{className:"mono muted","data-testid":"voice-https-hint",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:o1})]})]}):null,l.trim()?s.jsxs("div",{className:`status_bar ${Ea?"pulse":""}`,children:[s.jsx("strong",{children:"Run"}),":"," ",s.jsx("span",{className:"mono",children:ys||co||"unknown"}),Es&&Nr?s.jsxs("span",{className:"mono muted",children:[" • next in ",Nr]}):null,Xo?s.jsxs("span",{className:"mono muted",children:[" • ",Xo]}):null]}):null]})]})]})}):null,s.jsxs(tc,{open:e_,title:Wu||"Artifact",onClose:()=>{Cl(!1),ra(""),eo(""),kr(!1),Tl(null),or&&(URL.revokeObjectURL(or),Vu(""))},actions:s.jsx("button",{className:"btn",onClick:()=>{Cl(!1),ra(""),eo(""),kr(!1),Tl(null),or&&(URL.revokeObjectURL(or),Vu(""))},children:"Close"}),children:[Hu?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,Kr?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:Kr}):null,Qi==="image"&&or?s.jsx("img",{className:"runtime_preview_media",src:or,alt:Wu||"Artifact preview"}):Qi==="audio"&&or?s.jsx(Tg,{className:"runtime_preview_media",src:or,name:Wu||void 0}):Qi==="video"&&or?s.jsx("video",{className:"runtime_preview_media",controls:!0,src:or}):s.jsx(M1,{artifact:Al,text:qu||"(empty)",className:"runtime_preview_text"})]}),Rs?s.jsxs(tc,{open:Rs,title:"Edit schedule",onClose:()=>{Bi(!1),vs(""),Ls(!0),Ss(""),Ui(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Bi(!1),vs(""),Ls(!0),Ss(""),Ui(!1)},disabled:Be||ii,children:"Back"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await id({interval:dl,apply_immediately:si})||(Bi(!1),Ss(""),Ui(!1))},disabled:Be||ii||!dl.trim(),children:"Save"})]}),children:[ri?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:ri})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Interval"}),s.jsx("input",{className:"mono",value:dl,onChange:b=>vs(String(b.target.value||"")),placeholder:"20m / 1h / 0.5s / 250ms",disabled:Be||ii}),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(b=>s.jsx("button",{className:"btn",onClick:()=>vs(b),disabled:Be||ii,children:b},b))})]}),s.jsx("div",{className:"field",children:s.jsx(UP,{checked:si,busy:Be||ii,onChange:Ls})})]}):null,In?s.jsxs(tc,{open:In,title:"Compact scheduled context",onClose:()=>{$a(!1),Fs(""),gr(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{$a(!1),Fs(""),gr(!1)},disabled:Be||zs,children:"Cancel"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await p_({preserve_recent:fl,compression_mode:Tr,focus:Wi})||($a(!1),Fs(""),gr(!1))},disabled:Be||zs,children:zs?"Compacting…":"Compact"})]}),children:[bo?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:bo})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Preserve recent turns"}),s.jsx("input",{type:"number",min:1,value:String(fl),onChange:b=>hl(Math.max(1,parseInt(b.target.value||"6",10)||6)),disabled:Be||zs})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Mode"}),s.jsxs("select",{value:Tr,onChange:b=>fc(b.target.value),disabled:Be||zs,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:Wi,onChange:b=>Ca(String(b.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:Be||zs})]})]}):null,ko?s.jsxs(tc,{open:ko,title:Mr==="cancel"?"Cancel run":Jn?"Suspend schedule":"Pause run",onClose:()=>{Wr(!1),Vr(""),Ci("")},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Wr(!1),Vr(""),Ci("")},disabled:Be||Mt,children:"Back"}),s.jsx("button",{className:`btn ${Mr==="cancel"?"danger":"primary"}`,onClick:async()=>{Ci("");const b=await Zf(Mr,{reason:hc});if(b){Ci(b);return}Wr(!1),Vr(""),Ci("")},disabled:Be||Mt,children:Mr==="pause"?Jn?"Suspend":"Pause":"Cancel"})]}),children:[ku?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:ku})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Reason (optional)"}),s.jsx("input",{className:"mono",value:hc,onChange:b=>Vr(b.target.value),placeholder:"reason…"})]})]}):null,ad?s.jsxs(tc,{open:ad,title:cd,onClose:()=>{cr&&ai(cr)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{So("ledger"),t("observe"),ql(),cr&&ai(cr)},disabled:!l.trim(),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>cr&&ai(cr),disabled:Mt,children:"Dismiss"}),oa.length?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn danger",disabled:Mt,onClick:()=>Pc({approved:!1}),children:"Reject"}),s.jsx("button",{className:"btn",disabled:Mt,onClick:()=>Pc({approved:!0}),children:"Approve only"}),s.jsx("button",{className:"btn primary",disabled:!so||Mt,onClick:()=>w_(oa),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:cd}),s.jsx("p",{children:k_})]}),s.jsx(wu,{status:Cs||"waiting"})]}),Fo?s.jsxs("div",{className:`wait_request_card ${Bl?"":"inferred"}`,children:[s.jsx("span",{children:zo}),s.jsx(Wj,{metadata:sy}),s.jsx(Ni,{text:Fo}),Bl?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."}),dd.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:dd.map((b,T)=>s.jsxs("div",{className:`wait_turn_row role_${b.role.replace(/[^a-z0-9_-]+/g,"_")}`,children:[s.jsxs("div",{className:"wait_turn_meta",children:[s.jsx("strong",{children:b.role==="assistant"?"Assistant":b.role==="user"||b.role==="human"?"User":b.role}),b.ts?s.jsx("span",{className:"mono muted",children:cu(b.ts)}):null]}),s.jsx(Wj,{metadata:b.runtime_metadata}),s.jsx(Ni,{text:tn(b.text,{max_chars:1200,max_lines:10})})]},`${b.role}:${T}`))})]}):null,s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:Go(zl,fi)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:Ln(l.trim(),24)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:zl.current_node||String((ar==null?void 0:ar.node_id)||"—")})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:yu(zl)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:zl.session_id?Ln(String(zl.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:Ln(cr,28)})]})]}),S_?s.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!Fo,children:[s.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(hr,{value:ry,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:[ld.map(b=>s.jsxs("div",{className:"wait_event_row",children:[s.jsxs("span",{className:"mono",children:["#",b.cursor]}),s.jsx("strong",{children:b.summary||b.effect_type||b.status||"event"}),s.jsx("span",{className:"mono muted",children:[b.node_id,b.status,cu(b.ts)].filter(Boolean).join(" · ")})]},`${b.cursor}:${b.node_id}:${b.status}`)),ld.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),oa.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:oa.map((b,T)=>s.jsxs("div",{className:"wait_tool_card",children:[s.jsxs("div",{className:"wait_tool_header",children:[s.jsx("strong",{children:String((b==null?void 0:b.name)||"tool")}),s.jsxs("div",{className:"wait_tool_badges",children:[s.jsx("span",{className:"chip mono warn",children:"approval"}),j1(b).map(F=>s.jsxs("span",{className:"chip mono muted",title:k1,children:[F,"~"]},F))]})]}),s.jsx("div",{className:"wait_tool_args",children:s.jsx(hr,{value:(b==null?void 0:b.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((b==null?void 0:b.name)||"tool")}:${T}`))}),so?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 mi(l.trim(),"Cancelled from wait prompt"),disabled:!l.trim()||Mt,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(hr,{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:Fo||"No explicit prompt was provided. Open the ledger for context before responding."}),s.jsx(H4,{wait:un,disabled:Mt,on_submit:b=>Pc({response:b})}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void mi(l.trim(),"Cancelled from wait prompt"),disabled:!l.trim()||Mt,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(hr,{value:un||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(HI).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}vE();mE.createRoot(document.getElementById("root")).render(s.jsx(Ee.StrictMode,{children:s.jsx(zq,{})}));
178
+ //# sourceMappingURL=index-Ch6SmizF.js.map