@abstractframework/observer 0.3.0 → 0.5.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,153 @@
1
+ var Z0=Object.defineProperty;var Q0=(e,t,n)=>t in e?Z0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Xs=(e,t,n)=>Q0(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();function Ag(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var O_={exports:{}},cf={},P_={exports:{}},Vt={};/**
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 _y;function ej(){if(_y)return Vt;_y=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),u=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),_=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),y=Symbol.iterator;function w(R){return R===null||typeof R!="object"?null:(R=y&&R[y]||R["@@iterator"],typeof R=="function"?R:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,j={};function C(R,Q,Z){this.props=R,this.context=Q,this.refs=j,this.updater=Z||x}C.prototype.isReactComponent={},C.prototype.setState=function(R,Q){if(typeof R!="object"&&typeof R!="function"&&R!=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,R,Q,"setState")},C.prototype.forceUpdate=function(R){this.updater.enqueueForceUpdate(this,R,"forceUpdate")};function N(){}N.prototype=C.prototype;function T(R,Q,Z){this.props=R,this.context=Q,this.refs=j,this.updater=Z||x}var L=T.prototype=new N;L.constructor=T,S(L,C.prototype),L.isPureReactComponent=!0;var P=Array.isArray,W=Object.prototype.hasOwnProperty,G={current:null},Y={key:!0,ref:!0,__self:!0,__source:!0};function J(R,Q,Z){var X,le={},_e=null,he=null;if(Q!=null)for(X in Q.ref!==void 0&&(he=Q.ref),Q.key!==void 0&&(_e=""+Q.key),Q)W.call(Q,X)&&!Y.hasOwnProperty(X)&&(le[X]=Q[X]);var ye=arguments.length-2;if(ye===1)le.children=Z;else if(1<ye){for(var Ee=Array(ye),ze=0;ze<ye;ze++)Ee[ze]=arguments[ze+2];le.children=Ee}if(R&&R.defaultProps)for(X in ye=R.defaultProps,ye)le[X]===void 0&&(le[X]=ye[X]);return{$$typeof:e,type:R,key:_e,ref:he,props:le,_owner:G.current}}function re(R,Q){return{$$typeof:e,type:R.type,key:Q,ref:R.ref,props:R.props,_owner:R._owner}}function ae(R){return typeof R=="object"&&R!==null&&R.$$typeof===e}function ue(R){var Q={"=":"=0",":":"=2"};return"$"+R.replace(/[=:]/g,function(Z){return Q[Z]})}var B=/\/+/g;function A(R,Q){return typeof R=="object"&&R!==null&&R.key!=null?ue(""+R.key):Q.toString(36)}function $(R,Q,Z,X,le){var _e=typeof R;(_e==="undefined"||_e==="boolean")&&(R=null);var he=!1;if(R===null)he=!0;else switch(_e){case"string":case"number":he=!0;break;case"object":switch(R.$$typeof){case e:case t:he=!0}}if(he)return he=R,le=le(he),R=X===""?"."+A(he,0):X,P(le)?(Z="",R!=null&&(Z=R.replace(B,"$&/")+"/"),$(le,Q,Z,"",function(ze){return ze})):le!=null&&(ae(le)&&(le=re(le,Z+(!le.key||he&&he.key===le.key?"":(""+le.key).replace(B,"$&/")+"/")+R)),Q.push(le)),1;if(he=0,X=X===""?".":X+":",P(R))for(var ye=0;ye<R.length;ye++){_e=R[ye];var Ee=X+A(_e,ye);he+=$(_e,Q,Z,Ee,le)}else if(Ee=w(R),typeof Ee=="function")for(R=Ee.call(R),ye=0;!(_e=R.next()).done;)_e=_e.value,Ee=X+A(_e,ye++),he+=$(_e,Q,Z,Ee,le);else if(_e==="object")throw Q=String(R),Error("Objects are not valid as a React child (found: "+(Q==="[object Object]"?"object with keys {"+Object.keys(R).join(", ")+"}":Q)+"). If you meant to render a collection of children, use an array instead.");return he}function z(R,Q,Z){if(R==null)return R;var X=[],le=0;return $(R,X,"","",function(_e){return Q.call(Z,_e,le++)}),X}function E(R){if(R._status===-1){var Q=R._result;Q=Q(),Q.then(function(Z){(R._status===0||R._status===-1)&&(R._status=1,R._result=Z)},function(Z){(R._status===0||R._status===-1)&&(R._status=2,R._result=Z)}),R._status===-1&&(R._status=0,R._result=Q)}if(R._status===1)return R._result.default;throw R._result}var te={current:null},O={transition:null},F={ReactCurrentDispatcher:te,ReactCurrentBatchConfig:O,ReactCurrentOwner:G};function K(){throw Error("act(...) is not supported in production builds of React.")}return Vt.Children={map:z,forEach:function(R,Q,Z){z(R,function(){Q.apply(this,arguments)},Z)},count:function(R){var Q=0;return z(R,function(){Q++}),Q},toArray:function(R){return z(R,function(Q){return Q})||[]},only:function(R){if(!ae(R))throw Error("React.Children.only expected to receive a single React element child.");return R}},Vt.Component=C,Vt.Fragment=n,Vt.Profiler=o,Vt.PureComponent=T,Vt.StrictMode=r,Vt.Suspense=f,Vt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=F,Vt.act=K,Vt.cloneElement=function(R,Q,Z){if(R==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+R+".");var X=S({},R.props),le=R.key,_e=R.ref,he=R._owner;if(Q!=null){if(Q.ref!==void 0&&(_e=Q.ref,he=G.current),Q.key!==void 0&&(le=""+Q.key),R.type&&R.type.defaultProps)var ye=R.type.defaultProps;for(Ee in Q)W.call(Q,Ee)&&!Y.hasOwnProperty(Ee)&&(X[Ee]=Q[Ee]===void 0&&ye!==void 0?ye[Ee]:Q[Ee])}var Ee=arguments.length-2;if(Ee===1)X.children=Z;else if(1<Ee){ye=Array(Ee);for(var ze=0;ze<Ee;ze++)ye[ze]=arguments[ze+2];X.children=ye}return{$$typeof:e,type:R.type,key:le,ref:_e,props:X,_owner:he}},Vt.createContext=function(R){return R={$$typeof:u,_currentValue:R,_currentValue2:R,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},R.Provider={$$typeof:l,_context:R},R.Consumer=R},Vt.createElement=J,Vt.createFactory=function(R){var Q=J.bind(null,R);return Q.type=R,Q},Vt.createRef=function(){return{current:null}},Vt.forwardRef=function(R){return{$$typeof:c,render:R}},Vt.isValidElement=ae,Vt.lazy=function(R){return{$$typeof:p,_payload:{_status:-1,_result:R},_init:E}},Vt.memo=function(R,Q){return{$$typeof:_,type:R,compare:Q===void 0?null:Q}},Vt.startTransition=function(R){var Q=O.transition;O.transition={};try{R()}finally{O.transition=Q}},Vt.unstable_act=K,Vt.useCallback=function(R,Q){return te.current.useCallback(R,Q)},Vt.useContext=function(R){return te.current.useContext(R)},Vt.useDebugValue=function(){},Vt.useDeferredValue=function(R){return te.current.useDeferredValue(R)},Vt.useEffect=function(R,Q){return te.current.useEffect(R,Q)},Vt.useId=function(){return te.current.useId()},Vt.useImperativeHandle=function(R,Q,Z){return te.current.useImperativeHandle(R,Q,Z)},Vt.useInsertionEffect=function(R,Q){return te.current.useInsertionEffect(R,Q)},Vt.useLayoutEffect=function(R,Q){return te.current.useLayoutEffect(R,Q)},Vt.useMemo=function(R,Q){return te.current.useMemo(R,Q)},Vt.useReducer=function(R,Q,Z){return te.current.useReducer(R,Q,Z)},Vt.useRef=function(R){return te.current.useRef(R)},Vt.useState=function(R){return te.current.useState(R)},Vt.useSyncExternalStore=function(R,Q,Z){return te.current.useSyncExternalStore(R,Q,Z)},Vt.useTransition=function(){return te.current.useTransition()},Vt.version="18.3.1",Vt}var py;function Gf(){return py||(py=1,P_.exports=ej()),P_.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 gy;function tj(){if(gy)return cf;gy=1;var e=Gf(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function u(c,f,_){var p,y={},w=null,x=null;_!==void 0&&(w=""+_),f.key!==void 0&&(w=""+f.key),f.ref!==void 0&&(x=f.ref);for(p in f)r.call(f,p)&&!l.hasOwnProperty(p)&&(y[p]=f[p]);if(c&&c.defaultProps)for(p in f=c.defaultProps,f)y[p]===void 0&&(y[p]=f[p]);return{$$typeof:t,type:c,key:w,ref:x,props:y,_owner:o.current}}return cf.Fragment=n,cf.jsx=u,cf.jsxs=u,cf}var yy;function nj(){return yy||(yy=1,O_.exports=tj()),O_.exports}var s=nj(),m=Gf();const ve=Ag(m);var Qh={},D_={exports:{}},Gr={},F_={exports:{}},z_={};/**
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 wy;function sj(){return wy||(wy=1,(function(e){function t(O,F){var K=O.length;O.push(F);e:for(;0<K;){var R=K-1>>>1,Q=O[R];if(0<o(Q,F))O[R]=F,O[K]=Q,K=R;else break e}}function n(O){return O.length===0?null:O[0]}function r(O){if(O.length===0)return null;var F=O[0],K=O.pop();if(K!==F){O[0]=K;e:for(var R=0,Q=O.length,Z=Q>>>1;R<Z;){var X=2*(R+1)-1,le=O[X],_e=X+1,he=O[_e];if(0>o(le,K))_e<Q&&0>o(he,le)?(O[R]=he,O[_e]=K,R=_e):(O[R]=le,O[X]=K,R=X);else if(_e<Q&&0>o(he,K))O[R]=he,O[_e]=K,R=_e;else break e}}return F}function o(O,F){var K=O.sortIndex-F.sortIndex;return K!==0?K:O.id-F.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,c=u.now();e.unstable_now=function(){return u.now()-c}}var f=[],_=[],p=1,y=null,w=3,x=!1,S=!1,j=!1,C=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,T=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function L(O){for(var F=n(_);F!==null;){if(F.callback===null)r(_);else if(F.startTime<=O)r(_),F.sortIndex=F.expirationTime,t(f,F);else break;F=n(_)}}function P(O){if(j=!1,L(O),!S)if(n(f)!==null)S=!0,E(W);else{var F=n(_);F!==null&&te(P,F.startTime-O)}}function W(O,F){S=!1,j&&(j=!1,N(J),J=-1),x=!0;var K=w;try{for(L(F),y=n(f);y!==null&&(!(y.expirationTime>F)||O&&!ue());){var R=y.callback;if(typeof R=="function"){y.callback=null,w=y.priorityLevel;var Q=R(y.expirationTime<=F);F=e.unstable_now(),typeof Q=="function"?y.callback=Q:y===n(f)&&r(f),L(F)}else r(f);y=n(f)}if(y!==null)var Z=!0;else{var X=n(_);X!==null&&te(P,X.startTime-F),Z=!1}return Z}finally{y=null,w=K,x=!1}}var G=!1,Y=null,J=-1,re=5,ae=-1;function ue(){return!(e.unstable_now()-ae<re)}function B(){if(Y!==null){var O=e.unstable_now();ae=O;var F=!0;try{F=Y(!0,O)}finally{F?A():(G=!1,Y=null)}}else G=!1}var A;if(typeof T=="function")A=function(){T(B)};else if(typeof MessageChannel<"u"){var $=new MessageChannel,z=$.port2;$.port1.onmessage=B,A=function(){z.postMessage(null)}}else A=function(){C(B,0)};function E(O){Y=O,G||(G=!0,A())}function te(O,F){J=C(function(){O(e.unstable_now())},F)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(O){O.callback=null},e.unstable_continueExecution=function(){S||x||(S=!0,E(W))},e.unstable_forceFrameRate=function(O){0>O||125<O?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):re=0<O?Math.floor(1e3/O):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_getFirstCallbackNode=function(){return n(f)},e.unstable_next=function(O){switch(w){case 1:case 2:case 3:var F=3;break;default:F=w}var K=w;w=F;try{return O()}finally{w=K}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(O,F){switch(O){case 1:case 2:case 3:case 4:case 5:break;default:O=3}var K=w;w=O;try{return F()}finally{w=K}},e.unstable_scheduleCallback=function(O,F,K){var R=e.unstable_now();switch(typeof K=="object"&&K!==null?(K=K.delay,K=typeof K=="number"&&0<K?R+K:R):K=R,O){case 1:var Q=-1;break;case 2:Q=250;break;case 5:Q=1073741823;break;case 4:Q=1e4;break;default:Q=5e3}return Q=K+Q,O={id:p++,callback:F,priorityLevel:O,startTime:K,expirationTime:Q,sortIndex:-1},K>R?(O.sortIndex=K,t(_,O),n(f)===null&&O===n(_)&&(j?(N(J),J=-1):j=!0,te(P,K-R))):(O.sortIndex=Q,t(f,O),S||x||(S=!0,E(W))),O},e.unstable_shouldYield=ue,e.unstable_wrapCallback=function(O){var F=w;return function(){var K=w;w=F;try{return O.apply(this,arguments)}finally{w=K}}}})(z_)),z_}var vy;function rj(){return vy||(vy=1,F_.exports=sj()),F_.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 xy;function ij(){if(xy)return Gr;xy=1;var e=Gf(),t=rj();function n(i){for(var a="https://reactjs.org/docs/error-decoder.html?invariant="+i,d=1;d<arguments.length;d++)a+="&args[]="+encodeURIComponent(arguments[d]);return"Minified React error #"+i+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=new Set,o={};function l(i,a){u(i,a),u(i+"Capture",a)}function u(i,a){for(o[i]=a,i=0;i<a.length;i++)r.add(a[i])}var c=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),f=Object.prototype.hasOwnProperty,_=/^[: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]*$/,p={},y={};function w(i){return f.call(y,i)?!0:f.call(p,i)?!1:_.test(i)?y[i]=!0:(p[i]=!0,!1)}function x(i,a,d,h){if(d!==null&&d.type===0)return!1;switch(typeof a){case"function":case"symbol":return!0;case"boolean":return h?!1:d!==null?!d.acceptsBooleans:(i=i.toLowerCase().slice(0,5),i!=="data-"&&i!=="aria-");default:return!1}}function S(i,a,d,h){if(a===null||typeof a>"u"||x(i,a,d,h))return!0;if(h)return!1;if(d!==null)switch(d.type){case 3:return!a;case 4:return a===!1;case 5:return isNaN(a);case 6:return isNaN(a)||1>a}return!1}function j(i,a,d,h,v,b,I){this.acceptsBooleans=a===2||a===3||a===4,this.attributeName=h,this.attributeNamespace=v,this.mustUseProperty=d,this.propertyName=i,this.type=a,this.sanitizeURL=b,this.removeEmptyString=I}var C={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(i){C[i]=new j(i,0,!1,i,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(i){var a=i[0];C[a]=new j(a,1,!1,i[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(i){C[i]=new j(i,2,!1,i.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(i){C[i]=new j(i,2,!1,i,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(i){C[i]=new j(i,3,!1,i.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(i){C[i]=new j(i,3,!0,i,null,!1,!1)}),["capture","download"].forEach(function(i){C[i]=new j(i,4,!1,i,null,!1,!1)}),["cols","rows","size","span"].forEach(function(i){C[i]=new j(i,6,!1,i,null,!1,!1)}),["rowSpan","start"].forEach(function(i){C[i]=new j(i,5,!1,i.toLowerCase(),null,!1,!1)});var N=/[\-:]([a-z])/g;function T(i){return i[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(i){var a=i.replace(N,T);C[a]=new j(a,1,!1,i,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(i){var a=i.replace(N,T);C[a]=new j(a,1,!1,i,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(i){var a=i.replace(N,T);C[a]=new j(a,1,!1,i,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(i){C[i]=new j(i,1,!1,i.toLowerCase(),null,!1,!1)}),C.xlinkHref=new j("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(i){C[i]=new j(i,1,!1,i.toLowerCase(),null,!0,!0)});function L(i,a,d,h){var v=C.hasOwnProperty(a)?C[a]:null;(v!==null?v.type!==0:h||!(2<a.length)||a[0]!=="o"&&a[0]!=="O"||a[1]!=="n"&&a[1]!=="N")&&(S(a,d,v,h)&&(d=null),h||v===null?w(a)&&(d===null?i.removeAttribute(a):i.setAttribute(a,""+d)):v.mustUseProperty?i[v.propertyName]=d===null?v.type===3?!1:"":d:(a=v.attributeName,h=v.attributeNamespace,d===null?i.removeAttribute(a):(v=v.type,d=v===3||v===4&&d===!0?"":""+d,h?i.setAttributeNS(h,a,d):i.setAttribute(a,d))))}var P=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,W=Symbol.for("react.element"),G=Symbol.for("react.portal"),Y=Symbol.for("react.fragment"),J=Symbol.for("react.strict_mode"),re=Symbol.for("react.profiler"),ae=Symbol.for("react.provider"),ue=Symbol.for("react.context"),B=Symbol.for("react.forward_ref"),A=Symbol.for("react.suspense"),$=Symbol.for("react.suspense_list"),z=Symbol.for("react.memo"),E=Symbol.for("react.lazy"),te=Symbol.for("react.offscreen"),O=Symbol.iterator;function F(i){return i===null||typeof i!="object"?null:(i=O&&i[O]||i["@@iterator"],typeof i=="function"?i:null)}var K=Object.assign,R;function Q(i){if(R===void 0)try{throw Error()}catch(d){var a=d.stack.trim().match(/\n( *(at )?)/);R=a&&a[1]||""}return`
34
+ `+R+i}var Z=!1;function X(i,a){if(!i||Z)return"";Z=!0;var d=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(a)if(a=function(){throw Error()},Object.defineProperty(a.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(a,[])}catch(we){var h=we}Reflect.construct(i,[],a)}else{try{a.call()}catch(we){h=we}i.call(a.prototype)}else{try{throw Error()}catch(we){h=we}i()}}catch(we){if(we&&h&&typeof we.stack=="string"){for(var v=we.stack.split(`
35
+ `),b=h.stack.split(`
36
+ `),I=v.length-1,ee=b.length-1;1<=I&&0<=ee&&v[I]!==b[ee];)ee--;for(;1<=I&&0<=ee;I--,ee--)if(v[I]!==b[ee]){if(I!==1||ee!==1)do if(I--,ee--,0>ee||v[I]!==b[ee]){var se=`
37
+ `+v[I].replace(" at new "," at ");return i.displayName&&se.includes("<anonymous>")&&(se=se.replace("<anonymous>",i.displayName)),se}while(1<=I&&0<=ee);break}}}finally{Z=!1,Error.prepareStackTrace=d}return(i=i?i.displayName||i.name:"")?Q(i):""}function le(i){switch(i.tag){case 5:return Q(i.type);case 16:return Q("Lazy");case 13:return Q("Suspense");case 19:return Q("SuspenseList");case 0:case 2:case 15:return i=X(i.type,!1),i;case 11:return i=X(i.type.render,!1),i;case 1:return i=X(i.type,!0),i;default:return""}}function _e(i){if(i==null)return null;if(typeof i=="function")return i.displayName||i.name||null;if(typeof i=="string")return i;switch(i){case Y:return"Fragment";case G:return"Portal";case re:return"Profiler";case J:return"StrictMode";case A:return"Suspense";case $:return"SuspenseList"}if(typeof i=="object")switch(i.$$typeof){case ue:return(i.displayName||"Context")+".Consumer";case ae:return(i._context.displayName||"Context")+".Provider";case B:var a=i.render;return i=i.displayName,i||(i=a.displayName||a.name||"",i=i!==""?"ForwardRef("+i+")":"ForwardRef"),i;case z:return a=i.displayName||null,a!==null?a:_e(i.type)||"Memo";case E:a=i._payload,i=i._init;try{return _e(i(a))}catch{}}return null}function he(i){var a=i.type;switch(i.tag){case 24:return"Cache";case 9:return(a.displayName||"Context")+".Consumer";case 10:return(a._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return i=a.render,i=i.displayName||i.name||"",a.displayName||(i!==""?"ForwardRef("+i+")":"ForwardRef");case 7:return"Fragment";case 5:return a;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return _e(a);case 8:return a===J?"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 a=="function")return a.displayName||a.name||null;if(typeof a=="string")return a}return null}function ye(i){switch(typeof i){case"boolean":case"number":case"string":case"undefined":return i;case"object":return i;default:return""}}function Ee(i){var a=i.type;return(i=i.nodeName)&&i.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function ze(i){var a=Ee(i)?"checked":"value",d=Object.getOwnPropertyDescriptor(i.constructor.prototype,a),h=""+i[a];if(!i.hasOwnProperty(a)&&typeof d<"u"&&typeof d.get=="function"&&typeof d.set=="function"){var v=d.get,b=d.set;return Object.defineProperty(i,a,{configurable:!0,get:function(){return v.call(this)},set:function(I){h=""+I,b.call(this,I)}}),Object.defineProperty(i,a,{enumerable:d.enumerable}),{getValue:function(){return h},setValue:function(I){h=""+I},stopTracking:function(){i._valueTracker=null,delete i[a]}}}}function Be(i){i._valueTracker||(i._valueTracker=ze(i))}function gt(i){if(!i)return!1;var a=i._valueTracker;if(!a)return!0;var d=a.getValue(),h="";return i&&(h=Ee(i)?i.checked?"true":"false":i.value),i=h,i!==d?(a.setValue(i),!0):!1}function Fe(i){if(i=i||(typeof document<"u"?document:void 0),typeof i>"u")return null;try{return i.activeElement||i.body}catch{return i.body}}function tt(i,a){var d=a.checked;return K({},a,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:d??i._wrapperState.initialChecked})}function lt(i,a){var d=a.defaultValue==null?"":a.defaultValue,h=a.checked!=null?a.checked:a.defaultChecked;d=ye(a.value!=null?a.value:d),i._wrapperState={initialChecked:h,initialValue:d,controlled:a.type==="checkbox"||a.type==="radio"?a.checked!=null:a.value!=null}}function Ye(i,a){a=a.checked,a!=null&&L(i,"checked",a,!1)}function Se(i,a){Ye(i,a);var d=ye(a.value),h=a.type;if(d!=null)h==="number"?(d===0&&i.value===""||i.value!=d)&&(i.value=""+d):i.value!==""+d&&(i.value=""+d);else if(h==="submit"||h==="reset"){i.removeAttribute("value");return}a.hasOwnProperty("value")?ht(i,a.type,d):a.hasOwnProperty("defaultValue")&&ht(i,a.type,ye(a.defaultValue)),a.checked==null&&a.defaultChecked!=null&&(i.defaultChecked=!!a.defaultChecked)}function Re(i,a,d){if(a.hasOwnProperty("value")||a.hasOwnProperty("defaultValue")){var h=a.type;if(!(h!=="submit"&&h!=="reset"||a.value!==void 0&&a.value!==null))return;a=""+i._wrapperState.initialValue,d||a===i.value||(i.value=a),i.defaultValue=a}d=i.name,d!==""&&(i.name=""),i.defaultChecked=!!i._wrapperState.initialChecked,d!==""&&(i.name=d)}function ht(i,a,d){(a!=="number"||Fe(i.ownerDocument)!==i)&&(d==null?i.defaultValue=""+i._wrapperState.initialValue:i.defaultValue!==""+d&&(i.defaultValue=""+d))}var xe=Array.isArray;function Le(i,a,d,h){if(i=i.options,a){a={};for(var v=0;v<d.length;v++)a["$"+d[v]]=!0;for(d=0;d<i.length;d++)v=a.hasOwnProperty("$"+i[d].value),i[d].selected!==v&&(i[d].selected=v),v&&h&&(i[d].defaultSelected=!0)}else{for(d=""+ye(d),a=null,v=0;v<i.length;v++){if(i[v].value===d){i[v].selected=!0,h&&(i[v].defaultSelected=!0);return}a!==null||i[v].disabled||(a=i[v])}a!==null&&(a.selected=!0)}}function Ue(i,a){if(a.dangerouslySetInnerHTML!=null)throw Error(n(91));return K({},a,{value:void 0,defaultValue:void 0,children:""+i._wrapperState.initialValue})}function Ft(i,a){var d=a.value;if(d==null){if(d=a.children,a=a.defaultValue,d!=null){if(a!=null)throw Error(n(92));if(xe(d)){if(1<d.length)throw Error(n(93));d=d[0]}a=d}a==null&&(a=""),d=a}i._wrapperState={initialValue:ye(d)}}function Qt(i,a){var d=ye(a.value),h=ye(a.defaultValue);d!=null&&(d=""+d,d!==i.value&&(i.value=d),a.defaultValue==null&&i.defaultValue!==d&&(i.defaultValue=d)),h!=null&&(i.defaultValue=""+h)}function yn(i){var a=i.textContent;a===i._wrapperState.initialValue&&a!==""&&a!==null&&(i.value=a)}function Ut(i){switch(i){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 It(i,a){return i==null||i==="http://www.w3.org/1999/xhtml"?Ut(a):i==="http://www.w3.org/2000/svg"&&a==="foreignObject"?"http://www.w3.org/1999/xhtml":i}var jn,ns=(function(i){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(a,d,h,v){MSApp.execUnsafeLocalFunction(function(){return i(a,d,h,v)})}:i})(function(i,a){if(i.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in i)i.innerHTML=a;else{for(jn=jn||document.createElement("div"),jn.innerHTML="<svg>"+a.valueOf().toString()+"</svg>",a=jn.firstChild;i.firstChild;)i.removeChild(i.firstChild);for(;a.firstChild;)i.appendChild(a.firstChild)}});function $t(i,a){if(a){var d=i.firstChild;if(d&&d===i.lastChild&&d.nodeType===3){d.nodeValue=a;return}}i.textContent=a}var fn={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},Un=["Webkit","ms","Moz","O"];Object.keys(fn).forEach(function(i){Un.forEach(function(a){a=a+i.charAt(0).toUpperCase()+i.substring(1),fn[a]=fn[i]})});function En(i,a,d){return a==null||typeof a=="boolean"||a===""?"":d||typeof a!="number"||a===0||fn.hasOwnProperty(i)&&fn[i]?(""+a).trim():a+"px"}function hn(i,a){i=i.style;for(var d in a)if(a.hasOwnProperty(d)){var h=d.indexOf("--")===0,v=En(d,a[d],h);d==="float"&&(d="cssFloat"),h?i.setProperty(d,v):i[d]=v}}var On=K({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 _n(i,a){if(a){if(On[i]&&(a.children!=null||a.dangerouslySetInnerHTML!=null))throw Error(n(137,i));if(a.dangerouslySetInnerHTML!=null){if(a.children!=null)throw Error(n(60));if(typeof a.dangerouslySetInnerHTML!="object"||!("__html"in a.dangerouslySetInnerHTML))throw Error(n(61))}if(a.style!=null&&typeof a.style!="object")throw Error(n(62))}}function js(i,a){if(i.indexOf("-")===-1)return typeof a.is=="string";switch(i){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Yn=null;function Ss(i){return i=i.target||i.srcElement||window,i.correspondingUseElement&&(i=i.correspondingUseElement),i.nodeType===3?i.parentNode:i}var Mr=null,Pn=null,ce=null;function je(i){if(i=Ua(i)){if(typeof Mr!="function")throw Error(n(280));var a=i.stateNode;a&&(a=Fl(a),Mr(i.stateNode,i.type,a))}}function Je(i){Pn?ce?ce.push(i):ce=[i]:Pn=i}function Ve(){if(Pn){var i=Pn,a=ce;if(ce=Pn=null,je(i),a)for(i=0;i<a.length;i++)je(a[i])}}function rt(i,a){return i(a)}function ct(){}var Et=!1;function St(i,a,d){if(Et)return i(a,d);Et=!0;try{return rt(i,a,d)}finally{Et=!1,(Pn!==null||ce!==null)&&(ct(),Ve())}}function Kt(i,a){var d=i.stateNode;if(d===null)return null;var h=Fl(d);if(h===null)return null;d=h[a];e:switch(a){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(h=!h.disabled)||(i=i.type,h=!(i==="button"||i==="input"||i==="select"||i==="textarea")),i=!h;break e;default:i=!1}if(i)return null;if(d&&typeof d!="function")throw Error(n(231,a,typeof d));return d}var xt=!1;if(c)try{var Yt={};Object.defineProperty(Yt,"passive",{get:function(){xt=!0}}),window.addEventListener("test",Yt,Yt),window.removeEventListener("test",Yt,Yt)}catch{xt=!1}function Wt(i,a,d,h,v,b,I,ee,se){var we=Array.prototype.slice.call(arguments,3);try{a.apply(d,we)}catch(Te){this.onError(Te)}}var Ot=!1,At=null,Tt=!1,De=null,sn={onError:function(i){Ot=!0,At=i}};function dt(i,a,d,h,v,b,I,ee,se){Ot=!1,At=null,Wt.apply(sn,arguments)}function en(i,a,d,h,v,b,I,ee,se){if(dt.apply(this,arguments),Ot){if(Ot){var we=At;Ot=!1,At=null}else throw Error(n(198));Tt||(Tt=!0,De=we)}}function ft(i){var a=i,d=i;if(i.alternate)for(;a.return;)a=a.return;else{i=a;do a=i,(a.flags&4098)!==0&&(d=a.return),i=a.return;while(i)}return a.tag===3?d:null}function Wn(i){if(i.tag===13){var a=i.memoizedState;if(a===null&&(i=i.alternate,i!==null&&(a=i.memoizedState)),a!==null)return a.dehydrated}return null}function cn(i){if(ft(i)!==i)throw Error(n(188))}function er(i){var a=i.alternate;if(!a){if(a=ft(i),a===null)throw Error(n(188));return a!==i?null:i}for(var d=i,h=a;;){var v=d.return;if(v===null)break;var b=v.alternate;if(b===null){if(h=v.return,h!==null){d=h;continue}break}if(v.child===b.child){for(b=v.child;b;){if(b===d)return cn(v),i;if(b===h)return cn(v),a;b=b.sibling}throw Error(n(188))}if(d.return!==h.return)d=v,h=b;else{for(var I=!1,ee=v.child;ee;){if(ee===d){I=!0,d=v,h=b;break}if(ee===h){I=!0,h=v,d=b;break}ee=ee.sibling}if(!I){for(ee=b.child;ee;){if(ee===d){I=!0,d=b,h=v;break}if(ee===h){I=!0,h=b,d=v;break}ee=ee.sibling}if(!I)throw Error(n(189))}}if(d.alternate!==h)throw Error(n(190))}if(d.tag!==3)throw Error(n(188));return d.stateNode.current===d?i:a}function ss(i){return i=er(i),i!==null?Xr(i):null}function Xr(i){if(i.tag===5||i.tag===6)return i;for(i=i.child;i!==null;){var a=Xr(i);if(a!==null)return a;i=i.sibling}return null}var _r=t.unstable_scheduleCallback,hi=t.unstable_cancelCallback,mi=t.unstable_shouldYield,Ds=t.unstable_requestPaint,de=t.unstable_now,pr=t.unstable_getCurrentPriorityLevel,co=t.unstable_ImmediatePriority,gr=t.unstable_UserBlockingPriority,Rr=t.unstable_NormalPriority,Zr=t.unstable_LowPriority,it=t.unstable_IdlePriority,on=null,Fs=null;function Qr(i){if(Fs&&typeof Fs.onCommitFiberRoot=="function")try{Fs.onCommitFiberRoot(on,i,void 0,(i.current.flags&128)===128)}catch{}}var rs=Math.clz32?Math.clz32:Uo,zo=Math.log,Bo=Math.LN2;function Uo(i){return i>>>=0,i===0?32:31-(zo(i)/Bo|0)|0}var Dn=64,yr=4194304;function qn(i){switch(i&-i){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 i&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return i&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return i}}function uo(i,a){var d=i.pendingLanes;if(d===0)return 0;var h=0,v=i.suspendedLanes,b=i.pingedLanes,I=d&268435455;if(I!==0){var ee=I&~v;ee!==0?h=qn(ee):(b&=I,b!==0&&(h=qn(b)))}else I=d&~v,I!==0?h=qn(I):b!==0&&(h=qn(b));if(h===0)return 0;if(a!==0&&a!==h&&(a&v)===0&&(v=h&-h,b=a&-a,v>=b||v===16&&(b&4194240)!==0))return a;if((h&4)!==0&&(h|=d&16),a=i.entangledLanes,a!==0)for(i=i.entanglements,a&=h;0<a;)d=31-rs(a),v=1<<d,h|=i[d],a&=~v;return h}function _i(i,a){switch(i){case 1:case 2:case 4:return a+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 a+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 $n(i,a){for(var d=i.suspendedLanes,h=i.pingedLanes,v=i.expirationTimes,b=i.pendingLanes;0<b;){var I=31-rs(b),ee=1<<I,se=v[I];se===-1?((ee&d)===0||(ee&h)!==0)&&(v[I]=_i(ee,a)):se<=a&&(i.expiredLanes|=ee),b&=~ee}}function zs(i){return i=i.pendingLanes&-1073741825,i!==0?i:i&1073741824?1073741824:0}function fs(){var i=Dn;return Dn<<=1,(Dn&4194240)===0&&(Dn=64),i}function tr(i){for(var a=[],d=0;31>d;d++)a.push(i);return a}function hs(i,a,d){i.pendingLanes|=a,a!==536870912&&(i.suspendedLanes=0,i.pingedLanes=0),i=i.eventTimes,a=31-rs(a),i[a]=d}function Ma(i,a){var d=i.pendingLanes&~a;i.pendingLanes=a,i.suspendedLanes=0,i.pingedLanes=0,i.expiredLanes&=a,i.mutableReadLanes&=a,i.entangledLanes&=a,a=i.entanglements;var h=i.eventTimes;for(i=i.expirationTimes;0<d;){var v=31-rs(d),b=1<<v;a[v]=0,h[v]=-1,i[v]=-1,d&=~b}}function fo(i,a){var d=i.entangledLanes|=a;for(i=i.entanglements;d;){var h=31-rs(d),v=1<<h;v&a|i[h]&a&&(i[h]|=a),d&=~v}}var rn=0;function Ra(i){return i&=-i,1<i?4<i?(i&268435455)!==0?16:536870912:4:1}var Rc,Wo,ms,Lr,Ir,ho=!1,wr=[],ks=null,vr=null,Or=null,nr=new Map,Li=new Map,is=[],Pr="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 La(i,a){switch(i){case"focusin":case"focusout":ks=null;break;case"dragenter":case"dragleave":vr=null;break;case"mouseover":case"mouseout":Or=null;break;case"pointerover":case"pointerout":nr.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":Li.delete(a.pointerId)}}function xr(i,a,d,h,v,b){return i===null||i.nativeEvent!==b?(i={blockedOn:a,domEventName:d,eventSystemFlags:h,nativeEvent:b,targetContainers:[v]},a!==null&&(a=Ua(a),a!==null&&Wo(a)),i):(i.eventSystemFlags|=h,a=i.targetContainers,v!==null&&a.indexOf(v)===-1&&a.push(v),i)}function mo(i,a,d,h,v){switch(a){case"focusin":return ks=xr(ks,i,a,d,h,v),!0;case"dragenter":return vr=xr(vr,i,a,d,h,v),!0;case"mouseover":return Or=xr(Or,i,a,d,h,v),!0;case"pointerover":var b=v.pointerId;return nr.set(b,xr(nr.get(b)||null,i,a,d,h,v)),!0;case"gotpointercapture":return b=v.pointerId,Li.set(b,xr(Li.get(b)||null,i,a,d,h,v)),!0}return!1}function Lc(i){var a=Wi(i.target);if(a!==null){var d=ft(a);if(d!==null){if(a=d.tag,a===13){if(a=Wn(d),a!==null){i.blockedOn=a,Ir(i.priority,function(){ms(d)});return}}else if(a===3&&d.stateNode.current.memoizedState.isDehydrated){i.blockedOn=d.tag===3?d.stateNode.containerInfo:null;return}}}i.blockedOn=null}function Ii(i){if(i.blockedOn!==null)return!1;for(var a=i.targetContainers;0<a.length;){var d=ie(i.domEventName,i.eventSystemFlags,a[0],i.nativeEvent);if(d===null){d=i.nativeEvent;var h=new d.constructor(d.type,d);Yn=h,d.target.dispatchEvent(h),Yn=null}else return a=Ua(d),a!==null&&Wo(a),i.blockedOn=d,!1;a.shift()}return!0}function sr(i,a,d){Ii(i)&&d.delete(a)}function rd(){ho=!1,ks!==null&&Ii(ks)&&(ks=null),vr!==null&&Ii(vr)&&(vr=null),Or!==null&&Ii(Or)&&(Or=null),nr.forEach(sr),Li.forEach(sr)}function rr(i,a){i.blockedOn===a&&(i.blockedOn=null,ho||(ho=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,rd)))}function _o(i){function a(v){return rr(v,i)}if(0<wr.length){rr(wr[0],i);for(var d=1;d<wr.length;d++){var h=wr[d];h.blockedOn===i&&(h.blockedOn=null)}}for(ks!==null&&rr(ks,i),vr!==null&&rr(vr,i),Or!==null&&rr(Or,i),nr.forEach(a),Li.forEach(a),d=0;d<is.length;d++)h=is[d],h.blockedOn===i&&(h.blockedOn=null);for(;0<is.length&&(d=is[0],d.blockedOn===null);)Lc(d),d.blockedOn===null&&is.shift()}var ir=P.ReactCurrentBatchConfig,qo=!0;function pi(i,a,d,h){var v=rn,b=ir.transition;ir.transition=null;try{rn=1,gi(i,a,d,h)}finally{rn=v,ir.transition=b}}function bl(i,a,d,h){var v=rn,b=ir.transition;ir.transition=null;try{rn=4,gi(i,a,d,h)}finally{rn=v,ir.transition=b}}function gi(i,a,d,h){if(qo){var v=ie(i,a,d,h);if(v===null)or(i,a,h,U,d),La(i,h);else if(mo(v,i,a,d,h))h.stopPropagation();else if(La(i,h),a&4&&-1<Pr.indexOf(i)){for(;v!==null;){var b=Ua(v);if(b!==null&&Rc(b),b=ie(i,a,d,h),b===null&&or(i,a,h,U,d),b===v)break;v=b}v!==null&&h.stopPropagation()}else or(i,a,h,null,d)}}var U=null;function ie(i,a,d,h){if(U=null,i=Ss(h),i=Wi(i),i!==null)if(a=ft(i),a===null)i=null;else if(d=a.tag,d===13){if(i=Wn(a),i!==null)return i;i=null}else if(d===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;i=null}else a!==i&&(i=null);return U=i,null}function be(i){switch(i){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(pr()){case co:return 1;case gr:return 4;case Rr:case Zr:return 16;case it:return 536870912;default:return 16}default:return 16}}var ke=null,Ae=null,qe=null;function et(){if(qe)return qe;var i,a=Ae,d=a.length,h,v="value"in ke?ke.value:ke.textContent,b=v.length;for(i=0;i<d&&a[i]===v[i];i++);var I=d-i;for(h=1;h<=I&&a[d-h]===v[b-h];h++);return qe=v.slice(i,1<h?1-h:void 0)}function ot(i){var a=i.keyCode;return"charCode"in i?(i=i.charCode,i===0&&a===13&&(i=13)):i=a,i===10&&(i=13),32<=i||i===13?i:0}function mt(){return!0}function Pt(){return!1}function Jt(i){function a(d,h,v,b,I){this._reactName=d,this._targetInst=v,this.type=h,this.nativeEvent=b,this.target=I,this.currentTarget=null;for(var ee in i)i.hasOwnProperty(ee)&&(d=i[ee],this[ee]=d?d(b):b[ee]);return this.isDefaultPrevented=(b.defaultPrevented!=null?b.defaultPrevented:b.returnValue===!1)?mt:Pt,this.isPropagationStopped=Pt,this}return K(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var d=this.nativeEvent;d&&(d.preventDefault?d.preventDefault():typeof d.returnValue!="unknown"&&(d.returnValue=!1),this.isDefaultPrevented=mt)},stopPropagation:function(){var d=this.nativeEvent;d&&(d.stopPropagation?d.stopPropagation():typeof d.cancelBubble!="unknown"&&(d.cancelBubble=!0),this.isPropagationStopped=mt)},persist:function(){},isPersistent:mt}),a}var Zn={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(i){return i.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},zt=Jt(Zn),an=K({},Zn,{view:0,detail:0}),pn=Jt(an),wn,_s,Ns,br=K({},an,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Sl,button:0,buttons:0,relatedTarget:function(i){return i.relatedTarget===void 0?i.fromElement===i.srcElement?i.toElement:i.fromElement:i.relatedTarget},movementX:function(i){return"movementX"in i?i.movementX:(i!==Ns&&(Ns&&i.type==="mousemove"?(wn=i.screenX-Ns.screenX,_s=i.screenY-Ns.screenY):_s=wn=0,Ns=i),wn)},movementY:function(i){return"movementY"in i?i.movementY:_s}}),Ho=Jt(br),Vo=K({},br,{dataTransfer:0}),jl=Jt(Vo),Ic=K({},an,{relatedTarget:0}),Oc=Jt(Ic),Pc=K({},Zn,{animationName:0,elapsedTime:0,pseudoElement:0}),id=Jt(Pc),Dc=K({},Zn,{clipboardData:function(i){return"clipboardData"in i?i.clipboardData:window.clipboardData}}),Fc=Jt(Dc),zc=K({},Zn,{data:0}),od=Jt(zc),Go={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},th={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"},ad={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function ld(i){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(i):(i=ad[i])?!!a[i]:!1}function Sl(){return ld}var cd=K({},an,{key:function(i){if(i.key){var a=Go[i.key]||i.key;if(a!=="Unidentified")return a}return i.type==="keypress"?(i=ot(i),i===13?"Enter":String.fromCharCode(i)):i.type==="keydown"||i.type==="keyup"?th[i.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Sl,charCode:function(i){return i.type==="keypress"?ot(i):0},keyCode:function(i){return i.type==="keydown"||i.type==="keyup"?i.keyCode:0},which:function(i){return i.type==="keypress"?ot(i):i.type==="keydown"||i.type==="keyup"?i.keyCode:0}}),y_=Jt(cd),ud=K({},br,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),nh=Jt(ud),sh=K({},an,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Sl}),dd=Jt(sh),tn=K({},Zn,{propertyName:0,elapsedTime:0,pseudoElement:0}),fd=Jt(tn),w_=K({},br,{deltaX:function(i){return"deltaX"in i?i.deltaX:"wheelDeltaX"in i?-i.wheelDeltaX:0},deltaY:function(i){return"deltaY"in i?i.deltaY:"wheelDeltaY"in i?-i.wheelDeltaY:"wheelDelta"in i?-i.wheelDelta:0},deltaZ:0,deltaMode:0}),hd=Jt(w_),v_=[9,13,27,32],kl=c&&"CompositionEvent"in window,Nl=null;c&&"documentMode"in document&&(Nl=document.documentMode);var ps=c&&"TextEvent"in window&&!Nl,Oi=c&&(!kl||Nl&&8<Nl&&11>=Nl),md=" ",rh=!1;function Ko(i,a){switch(i){case"keyup":return v_.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Bc(i){return i=i.detail,typeof i=="object"&&"data"in i?i.data:null}var yi=!1;function ih(i,a){switch(i){case"compositionend":return Bc(a);case"keypress":return a.which!==32?null:(rh=!0,md);case"textInput":return i=a.data,i===md&&rh?null:i;default:return null}}function x_(i,a){if(yi)return i==="compositionend"||!kl&&Ko(i,a)?(i=et(),qe=Ae=ke=null,yi=!1,i):null;switch(i){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1<a.char.length)return a.char;if(a.which)return String.fromCharCode(a.which)}return null;case"compositionend":return Oi&&a.locale!=="ko"?null:a.data;default:return null}}var b_={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 oh(i){var a=i&&i.nodeName&&i.nodeName.toLowerCase();return a==="input"?!!b_[i.type]:a==="textarea"}function _d(i,a,d,h){Je(h),a=Qo(a,"onChange"),0<a.length&&(d=new zt("onChange","change",null,d,h),i.push({event:d,listeners:a}))}var Pi=null,Cl=null;function El(i){Xo(i,0)}function Ia(i){var a=ta(i);if(gt(a))return i}function j_(i,a){if(i==="change")return a}var pd=!1;if(c){var $l;if(c){var Al="oninput"in document;if(!Al){var gd=document.createElement("div");gd.setAttribute("oninput","return;"),Al=typeof gd.oninput=="function"}$l=Al}else $l=!1;pd=$l&&(!document.documentMode||9<document.documentMode)}function Tl(){Pi&&(Pi.detachEvent("onpropertychange",yd),Cl=Pi=null)}function yd(i){if(i.propertyName==="value"&&Ia(Cl)){var a=[];_d(a,Cl,i,Ss(i)),St(El,a)}}function ah(i,a,d){i==="focusin"?(Tl(),Pi=a,Cl=d,Pi.attachEvent("onpropertychange",yd)):i==="focusout"&&Tl()}function S_(i){if(i==="selectionchange"||i==="keyup"||i==="keydown")return Ia(Cl)}function Uc(i,a){if(i==="click")return Ia(a)}function lh(i,a){if(i==="input"||i==="change")return Ia(a)}function wd(i,a){return i===a&&(i!==0||1/i===1/a)||i!==i&&a!==a}var ei=typeof Object.is=="function"?Object.is:wd;function Yo(i,a){if(ei(i,a))return!0;if(typeof i!="object"||i===null||typeof a!="object"||a===null)return!1;var d=Object.keys(i),h=Object.keys(a);if(d.length!==h.length)return!1;for(h=0;h<d.length;h++){var v=d[h];if(!f.call(a,v)||!ei(i[v],a[v]))return!1}return!0}function ch(i){for(;i&&i.firstChild;)i=i.firstChild;return i}function vd(i,a){var d=ch(i);i=0;for(var h;d;){if(d.nodeType===3){if(h=i+d.textContent.length,i<=a&&h>=a)return{node:d,offset:a-i};i=h}e:{for(;d;){if(d.nextSibling){d=d.nextSibling;break e}d=d.parentNode}d=void 0}d=ch(d)}}function uh(i,a){return i&&a?i===a?!0:i&&i.nodeType===3?!1:a&&a.nodeType===3?uh(i,a.parentNode):"contains"in i?i.contains(a):i.compareDocumentPosition?!!(i.compareDocumentPosition(a)&16):!1:!1}function Wc(){for(var i=window,a=Fe();a instanceof i.HTMLIFrameElement;){try{var d=typeof a.contentWindow.location.href=="string"}catch{d=!1}if(d)i=a.contentWindow;else break;a=Fe(i.document)}return a}function xd(i){var a=i&&i.nodeName&&i.nodeName.toLowerCase();return a&&(a==="input"&&(i.type==="text"||i.type==="search"||i.type==="tel"||i.type==="url"||i.type==="password")||a==="textarea"||i.contentEditable==="true")}function bd(i){var a=Wc(),d=i.focusedElem,h=i.selectionRange;if(a!==d&&d&&d.ownerDocument&&uh(d.ownerDocument.documentElement,d)){if(h!==null&&xd(d)){if(a=h.start,i=h.end,i===void 0&&(i=a),"selectionStart"in d)d.selectionStart=a,d.selectionEnd=Math.min(i,d.value.length);else if(i=(a=d.ownerDocument||document)&&a.defaultView||window,i.getSelection){i=i.getSelection();var v=d.textContent.length,b=Math.min(h.start,v);h=h.end===void 0?b:Math.min(h.end,v),!i.extend&&b>h&&(v=h,h=b,b=v),v=vd(d,b);var I=vd(d,h);v&&I&&(i.rangeCount!==1||i.anchorNode!==v.node||i.anchorOffset!==v.offset||i.focusNode!==I.node||i.focusOffset!==I.offset)&&(a=a.createRange(),a.setStart(v.node,v.offset),i.removeAllRanges(),b>h?(i.addRange(a),i.extend(I.node,I.offset)):(a.setEnd(I.node,I.offset),i.addRange(a)))}}for(a=[],i=d;i=i.parentNode;)i.nodeType===1&&a.push({element:i,left:i.scrollLeft,top:i.scrollTop});for(typeof d.focus=="function"&&d.focus(),d=0;d<a.length;d++)i=a[d],i.element.scrollLeft=i.left,i.element.scrollTop=i.top}}var k_=c&&"documentMode"in document&&11>=document.documentMode,Oa=null,jd=null,wi=null,qc=!1;function Ml(i,a,d){var h=d.window===d?d.document:d.nodeType===9?d:d.ownerDocument;qc||Oa==null||Oa!==Fe(h)||(h=Oa,"selectionStart"in h&&xd(h)?h={start:h.selectionStart,end:h.selectionEnd}:(h=(h.ownerDocument&&h.ownerDocument.defaultView||window).getSelection(),h={anchorNode:h.anchorNode,anchorOffset:h.anchorOffset,focusNode:h.focusNode,focusOffset:h.focusOffset}),wi&&Yo(wi,h)||(wi=h,h=Qo(jd,"onSelect"),0<h.length&&(a=new zt("onSelect","select",null,a,d),i.push({event:a,listeners:h}),a.target=Oa)))}function Hc(i,a){var d={};return d[i.toLowerCase()]=a.toLowerCase(),d["Webkit"+i]="webkit"+a,d["Moz"+i]="moz"+a,d}var Di={animationend:Hc("Animation","AnimationEnd"),animationiteration:Hc("Animation","AnimationIteration"),animationstart:Hc("Animation","AnimationStart"),transitionend:Hc("Transition","TransitionEnd")},po={},Pa={};c&&(Pa=document.createElement("div").style,"AnimationEvent"in window||(delete Di.animationend.animation,delete Di.animationiteration.animation,delete Di.animationstart.animation),"TransitionEvent"in window||delete Di.transitionend.transition);function Fi(i){if(po[i])return po[i];if(!Di[i])return i;var a=Di[i],d;for(d in a)if(a.hasOwnProperty(d)&&d in Pa)return po[i]=a[d];return i}var Da=Fi("animationend"),Rl=Fi("animationiteration"),Vc=Fi("animationstart"),Sd=Fi("transitionend"),Fa=new Map,kd="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 Dr(i,a){Fa.set(i,a),l(a,[i])}for(var Jo=0;Jo<kd.length;Jo++){var Nd=kd[Jo],Cd=Nd.toLowerCase(),N_=Nd[0].toUpperCase()+Nd.slice(1);Dr(Cd,"on"+N_)}Dr(Da,"onAnimationEnd"),Dr(Rl,"onAnimationIteration"),Dr(Vc,"onAnimationStart"),Dr("dblclick","onDoubleClick"),Dr("focusin","onFocus"),Dr("focusout","onBlur"),Dr(Sd,"onTransitionEnd"),u("onMouseEnter",["mouseout","mouseover"]),u("onMouseLeave",["mouseout","mouseover"]),u("onPointerEnter",["pointerout","pointerover"]),u("onPointerLeave",["pointerout","pointerover"]),l("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),l("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),l("onBeforeInput",["compositionend","keypress","textInput","paste"]),l("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Ll="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(" "),Gc=new Set("cancel close invalid load scroll toggle".split(" ").concat(Ll));function vi(i,a,d){var h=i.type||"unknown-event";i.currentTarget=d,en(h,a,void 0,i),i.currentTarget=null}function Xo(i,a){a=(a&4)!==0;for(var d=0;d<i.length;d++){var h=i[d],v=h.event;h=h.listeners;e:{var b=void 0;if(a)for(var I=h.length-1;0<=I;I--){var ee=h[I],se=ee.instance,we=ee.currentTarget;if(ee=ee.listener,se!==b&&v.isPropagationStopped())break e;vi(v,ee,we),b=se}else for(I=0;I<h.length;I++){if(ee=h[I],se=ee.instance,we=ee.currentTarget,ee=ee.listener,se!==b&&v.isPropagationStopped())break e;vi(v,ee,we),b=se}}}if(Tt)throw i=De,Tt=!1,De=null,i}function Cn(i,a){var d=a[Zc];d===void 0&&(d=a[Zc]=new Set);var h=i+"__bubble";d.has(h)||(Ba(a,i,2,!1),d.add(h))}function za(i,a,d){var h=0;a&&(h|=4),Ba(d,i,h,a)}var Kc="_reactListening"+Math.random().toString(36).slice(2);function Zo(i){if(!i[Kc]){i[Kc]=!0,r.forEach(function(d){d!=="selectionchange"&&(Gc.has(d)||za(d,!1,i),za(d,!0,i))});var a=i.nodeType===9?i:i.ownerDocument;a===null||a[Kc]||(a[Kc]=!0,za("selectionchange",!1,a))}}function Ba(i,a,d,h){switch(be(a)){case 1:var v=pi;break;case 4:v=bl;break;default:v=gi}d=v.bind(null,a,d,i),v=void 0,!xt||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(v=!0),h?v!==void 0?i.addEventListener(a,d,{capture:!0,passive:v}):i.addEventListener(a,d,!0):v!==void 0?i.addEventListener(a,d,{passive:v}):i.addEventListener(a,d,!1)}function or(i,a,d,h,v){var b=h;if((a&1)===0&&(a&2)===0&&h!==null)e:for(;;){if(h===null)return;var I=h.tag;if(I===3||I===4){var ee=h.stateNode.containerInfo;if(ee===v||ee.nodeType===8&&ee.parentNode===v)break;if(I===4)for(I=h.return;I!==null;){var se=I.tag;if((se===3||se===4)&&(se=I.stateNode.containerInfo,se===v||se.nodeType===8&&se.parentNode===v))return;I=I.return}for(;ee!==null;){if(I=Wi(ee),I===null)return;if(se=I.tag,se===5||se===6){h=b=I;continue e}ee=ee.parentNode}}h=h.return}St(function(){var we=b,Te=Ss(d),Me=[];e:{var $e=Fa.get(i);if($e!==void 0){var Ze=zt,nt=i;switch(i){case"keypress":if(ot(d)===0)break e;case"keydown":case"keyup":Ze=y_;break;case"focusin":nt="focus",Ze=Oc;break;case"focusout":nt="blur",Ze=Oc;break;case"beforeblur":case"afterblur":Ze=Oc;break;case"click":if(d.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":Ze=Ho;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Ze=jl;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Ze=dd;break;case Da:case Rl:case Vc:Ze=id;break;case Sd:Ze=fd;break;case"scroll":Ze=pn;break;case"wheel":Ze=hd;break;case"copy":case"cut":case"paste":Ze=Fc;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Ze=nh}var st=(a&4)!==0,ts=!st&&i==="scroll",fe=st?$e!==null?$e+"Capture":null:$e;st=[];for(var oe=we,pe;oe!==null;){pe=oe;var Pe=pe.stateNode;if(pe.tag===5&&Pe!==null&&(pe=Pe,fe!==null&&(Pe=Kt(oe,fe),Pe!=null&&st.push(Fr(oe,Pe,pe)))),ts)break;oe=oe.return}0<st.length&&($e=new Ze($e,nt,null,d,Te),Me.push({event:$e,listeners:st}))}}if((a&7)===0){e:{if($e=i==="mouseover"||i==="pointerover",Ze=i==="mouseout"||i==="pointerout",$e&&d!==Yn&&(nt=d.relatedTarget||d.fromElement)&&(Wi(nt)||nt[Ur]))break e;if((Ze||$e)&&($e=Te.window===Te?Te:($e=Te.ownerDocument)?$e.defaultView||$e.parentWindow:window,Ze?(nt=d.relatedTarget||d.toElement,Ze=we,nt=nt?Wi(nt):null,nt!==null&&(ts=ft(nt),nt!==ts||nt.tag!==5&&nt.tag!==6)&&(nt=null)):(Ze=null,nt=we),Ze!==nt)){if(st=Ho,Pe="onMouseLeave",fe="onMouseEnter",oe="mouse",(i==="pointerout"||i==="pointerover")&&(st=nh,Pe="onPointerLeave",fe="onPointerEnter",oe="pointer"),ts=Ze==null?$e:ta(Ze),pe=nt==null?$e:ta(nt),$e=new st(Pe,oe+"leave",Ze,d,Te),$e.target=ts,$e.relatedTarget=pe,Pe=null,Wi(Te)===we&&(st=new st(fe,oe+"enter",nt,d,Te),st.target=pe,st.relatedTarget=ts,Pe=st),ts=Pe,Ze&&nt)t:{for(st=Ze,fe=nt,oe=0,pe=st;pe;pe=ti(pe))oe++;for(pe=0,Pe=fe;Pe;Pe=ti(Pe))pe++;for(;0<oe-pe;)st=ti(st),oe--;for(;0<pe-oe;)fe=ti(fe),pe--;for(;oe--;){if(st===fe||fe!==null&&st===fe.alternate)break t;st=ti(st),fe=ti(fe)}st=null}else st=null;Ze!==null&&Yc(Me,$e,Ze,st,!1),nt!==null&&ts!==null&&Yc(Me,ts,nt,st,!0)}}e:{if($e=we?ta(we):window,Ze=$e.nodeName&&$e.nodeName.toLowerCase(),Ze==="select"||Ze==="input"&&$e.type==="file")var at=j_;else if(oh($e))if(pd)at=lh;else{at=S_;var yt=ah}else(Ze=$e.nodeName)&&Ze.toLowerCase()==="input"&&($e.type==="checkbox"||$e.type==="radio")&&(at=Uc);if(at&&(at=at(i,we))){_d(Me,at,d,Te);break e}yt&&yt(i,$e,we),i==="focusout"&&(yt=$e._wrapperState)&&yt.controlled&&$e.type==="number"&&ht($e,"number",$e.value)}switch(yt=we?ta(we):window,i){case"focusin":(oh(yt)||yt.contentEditable==="true")&&(Oa=yt,jd=we,wi=null);break;case"focusout":wi=jd=Oa=null;break;case"mousedown":qc=!0;break;case"contextmenu":case"mouseup":case"dragend":qc=!1,Ml(Me,d,Te);break;case"selectionchange":if(k_)break;case"keydown":case"keyup":Ml(Me,d,Te)}var wt;if(kl)e:{switch(i){case"compositionstart":var Ct="onCompositionStart";break e;case"compositionend":Ct="onCompositionEnd";break e;case"compositionupdate":Ct="onCompositionUpdate";break e}Ct=void 0}else yi?Ko(i,d)&&(Ct="onCompositionEnd"):i==="keydown"&&d.keyCode===229&&(Ct="onCompositionStart");Ct&&(Oi&&d.locale!=="ko"&&(yi||Ct!=="onCompositionStart"?Ct==="onCompositionEnd"&&yi&&(wt=et()):(ke=Te,Ae="value"in ke?ke.value:ke.textContent,yi=!0)),yt=Qo(we,Ct),0<yt.length&&(Ct=new od(Ct,i,null,d,Te),Me.push({event:Ct,listeners:yt}),wt?Ct.data=wt:(wt=Bc(d),wt!==null&&(Ct.data=wt)))),(wt=ps?ih(i,d):x_(i,d))&&(we=Qo(we,"onBeforeInput"),0<we.length&&(Te=new od("onBeforeInput","beforeinput",null,d,Te),Me.push({event:Te,listeners:we}),Te.data=wt))}Xo(Me,a)})}function Fr(i,a,d){return{instance:i,listener:a,currentTarget:d}}function Qo(i,a){for(var d=a+"Capture",h=[];i!==null;){var v=i,b=v.stateNode;v.tag===5&&b!==null&&(v=b,b=Kt(i,d),b!=null&&h.unshift(Fr(i,b,v)),b=Kt(i,a),b!=null&&h.push(Fr(i,b,v))),i=i.return}return h}function ti(i){if(i===null)return null;do i=i.return;while(i&&i.tag!==5);return i||null}function Yc(i,a,d,h,v){for(var b=a._reactName,I=[];d!==null&&d!==h;){var ee=d,se=ee.alternate,we=ee.stateNode;if(se!==null&&se===h)break;ee.tag===5&&we!==null&&(ee=we,v?(se=Kt(d,b),se!=null&&I.unshift(Fr(d,se,ee))):v||(se=Kt(d,b),se!=null&&I.push(Fr(d,se,ee)))),d=d.return}I.length!==0&&i.push({event:a,listeners:I})}var Il=/\r\n?/g,zi=/\u0000|\uFFFD/g;function Ol(i){return(typeof i=="string"?i:""+i).replace(Il,`
38
+ `).replace(zi,"")}function go(i,a,d){if(a=Ol(a),Ol(i)!==a&&d)throw Error(n(425))}function Bi(){}var xi=null,Cs=null;function Ui(i,a){return i==="textarea"||i==="noscript"||typeof a.children=="string"||typeof a.children=="number"||typeof a.dangerouslySetInnerHTML=="object"&&a.dangerouslySetInnerHTML!==null&&a.dangerouslySetInnerHTML.__html!=null}var yo=typeof setTimeout=="function"?setTimeout:void 0,Jc=typeof clearTimeout=="function"?clearTimeout:void 0,wo=typeof Promise=="function"?Promise:void 0,Ed=typeof queueMicrotask=="function"?queueMicrotask:typeof wo<"u"?function(i){return wo.resolve(null).then(i).catch(Xc)}:yo;function Xc(i){setTimeout(function(){throw i})}function zr(i,a){var d=a,h=0;do{var v=d.nextSibling;if(i.removeChild(d),v&&v.nodeType===8)if(d=v.data,d==="/$"){if(h===0){i.removeChild(v),_o(a);return}h--}else d!=="$"&&d!=="$?"&&d!=="$!"||h++;d=v}while(d);_o(a)}function Bs(i){for(;i!=null;i=i.nextSibling){var a=i.nodeType;if(a===1||a===3)break;if(a===8){if(a=i.data,a==="$"||a==="$!"||a==="$?")break;if(a==="/$")return null}}return i}function ni(i){i=i.previousSibling;for(var a=0;i;){if(i.nodeType===8){var d=i.data;if(d==="$"||d==="$!"||d==="$?"){if(a===0)return i;a--}else d==="/$"&&a++}i=i.previousSibling}return null}var ea=Math.random().toString(36).slice(2),Br="__reactFiber$"+ea,Pl="__reactProps$"+ea,Ur="__reactContainer$"+ea,Zc="__reactEvents$"+ea,Dl="__reactListeners$"+ea,dh="__reactHandles$"+ea;function Wi(i){var a=i[Br];if(a)return a;for(var d=i.parentNode;d;){if(a=d[Ur]||d[Br]){if(d=a.alternate,a.child!==null||d!==null&&d.child!==null)for(i=ni(i);i!==null;){if(d=i[Br])return d;i=ni(i)}return a}i=d,d=i.parentNode}return null}function Ua(i){return i=i[Br]||i[Ur],!i||i.tag!==5&&i.tag!==6&&i.tag!==13&&i.tag!==3?null:i}function ta(i){if(i.tag===5||i.tag===6)return i.stateNode;throw Error(n(33))}function Fl(i){return i[Pl]||null}var $d=[],na=-1;function vo(i){return{current:i}}function Sn(i){0>na||(i.current=$d[na],$d[na]=null,na--)}function kn(i,a){na++,$d[na]=i.current,i.current=a}var qi={},Es=vo(qi),Us=vo(!1),sa=qi;function ra(i,a){var d=i.type.contextTypes;if(!d)return qi;var h=i.stateNode;if(h&&h.__reactInternalMemoizedUnmaskedChildContext===a)return h.__reactInternalMemoizedMaskedChildContext;var v={},b;for(b in d)v[b]=a[b];return h&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=a,i.__reactInternalMemoizedMaskedChildContext=v),v}function os(i){return i=i.childContextTypes,i!=null}function Qc(){Sn(Us),Sn(Es)}function Wa(i,a,d){if(Es.current!==qi)throw Error(n(168));kn(Es,a),kn(Us,d)}function eu(i,a,d){var h=i.stateNode;if(a=a.childContextTypes,typeof h.getChildContext!="function")return d;h=h.getChildContext();for(var v in h)if(!(v in a))throw Error(n(108,he(i)||"Unknown",v));return K({},d,h)}function ia(i){return i=(i=i.stateNode)&&i.__reactInternalMemoizedMergedChildContext||qi,sa=Es.current,kn(Es,i),kn(Us,Us.current),!0}function Ad(i,a,d){var h=i.stateNode;if(!h)throw Error(n(169));d?(i=eu(i,a,sa),h.__reactInternalMemoizedMergedChildContext=i,Sn(Us),Sn(Es),kn(Es,i)):Sn(Us),kn(Us,d)}var ar=null,tu=!1,qa=!1;function fh(i){ar===null?ar=[i]:ar.push(i)}function Ha(i){tu=!0,fh(i)}function xo(){if(!qa&&ar!==null){qa=!0;var i=0,a=rn;try{var d=ar;for(rn=1;i<d.length;i++){var h=d[i];do h=h(!0);while(h!==null)}ar=null,tu=!1}catch(v){throw ar!==null&&(ar=ar.slice(i+1)),_r(co,xo),v}finally{rn=a,qa=!1}}return null}var Hi=[],Va=0,si=null,zl=0,$s=[],As=0,bo=null,ri=1,jr="";function Vi(i,a){Hi[Va++]=zl,Hi[Va++]=si,si=i,zl=a}function oa(i,a,d){$s[As++]=ri,$s[As++]=jr,$s[As++]=bo,bo=i;var h=ri;i=jr;var v=32-rs(h)-1;h&=~(1<<v),d+=1;var b=32-rs(a)+v;if(30<b){var I=v-v%5;b=(h&(1<<I)-1).toString(32),h>>=I,v-=I,ri=1<<32-rs(a)+v|d<<v|h,jr=b+i}else ri=1<<b|d<<v|h,jr=i}function Bl(i){i.return!==null&&(Vi(i,1),oa(i,1,0))}function Td(i){for(;i===si;)si=Hi[--Va],Hi[Va]=null,zl=Hi[--Va],Hi[Va]=null;for(;i===bo;)bo=$s[--As],$s[As]=null,jr=$s[--As],$s[As]=null,ri=$s[--As],$s[As]=null}var Ws=null,lr=null,An=!1,ii=null;function aa(i,a){var d=q(5,null,null,0);d.elementType="DELETED",d.stateNode=a,d.return=i,a=i.deletions,a===null?(i.deletions=[d],i.flags|=16):a.push(d)}function Ts(i,a){switch(i.tag){case 5:var d=i.type;return a=a.nodeType!==1||d.toLowerCase()!==a.nodeName.toLowerCase()?null:a,a!==null?(i.stateNode=a,Ws=i,lr=Bs(a.firstChild),!0):!1;case 6:return a=i.pendingProps===""||a.nodeType!==3?null:a,a!==null?(i.stateNode=a,Ws=i,lr=null,!0):!1;case 13:return a=a.nodeType!==8?null:a,a!==null?(d=bo!==null?{id:ri,overflow:jr}:null,i.memoizedState={dehydrated:a,treeContext:d,retryLane:1073741824},d=q(18,null,null,0),d.stateNode=a,d.return=i,i.child=d,Ws=i,lr=null,!0):!1;default:return!1}}function Ga(i){return(i.mode&1)!==0&&(i.flags&128)===0}function Ul(i){if(An){var a=lr;if(a){var d=a;if(!Ts(i,a)){if(Ga(i))throw Error(n(418));a=Bs(d.nextSibling);var h=Ws;a&&Ts(i,a)?aa(h,d):(i.flags=i.flags&-4097|2,An=!1,Ws=i)}}else{if(Ga(i))throw Error(n(418));i.flags=i.flags&-4097|2,An=!1,Ws=i}}}function hh(i){for(i=i.return;i!==null&&i.tag!==5&&i.tag!==3&&i.tag!==13;)i=i.return;Ws=i}function nu(i){if(i!==Ws)return!1;if(!An)return hh(i),An=!0,!1;var a;if((a=i.tag!==3)&&!(a=i.tag!==5)&&(a=i.type,a=a!=="head"&&a!=="body"&&!Ui(i.type,i.memoizedProps)),a&&(a=lr)){if(Ga(i))throw su(),Error(n(418));for(;a;)aa(i,a),a=Bs(a.nextSibling)}if(hh(i),i.tag===13){if(i=i.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(n(317));e:{for(i=i.nextSibling,a=0;i;){if(i.nodeType===8){var d=i.data;if(d==="/$"){if(a===0){lr=Bs(i.nextSibling);break e}a--}else d!=="$"&&d!=="$!"&&d!=="$?"||a++}i=i.nextSibling}lr=null}}else lr=Ws?Bs(i.stateNode.nextSibling):null;return!0}function su(){for(var i=lr;i;)i=Bs(i.nextSibling)}function Ka(){lr=Ws=null,An=!1}function Ya(i){ii===null?ii=[i]:ii.push(i)}var mh=P.ReactCurrentBatchConfig;function jo(i,a,d){if(i=d.ref,i!==null&&typeof i!="function"&&typeof i!="object"){if(d._owner){if(d=d._owner,d){if(d.tag!==1)throw Error(n(309));var h=d.stateNode}if(!h)throw Error(n(147,i));var v=h,b=""+i;return a!==null&&a.ref!==null&&typeof a.ref=="function"&&a.ref._stringRef===b?a.ref:(a=function(I){var ee=v.refs;I===null?delete ee[b]:ee[b]=I},a._stringRef=b,a)}if(typeof i!="string")throw Error(n(284));if(!d._owner)throw Error(n(290,i))}return i}function Wl(i,a){throw i=Object.prototype.toString.call(a),Error(n(31,i==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":i))}function Md(i){var a=i._init;return a(i._payload)}function _h(i){function a(fe,oe){if(i){var pe=fe.deletions;pe===null?(fe.deletions=[oe],fe.flags|=16):pe.push(oe)}}function d(fe,oe){if(!i)return null;for(;oe!==null;)a(fe,oe),oe=oe.sibling;return null}function h(fe,oe){for(fe=new Map;oe!==null;)oe.key!==null?fe.set(oe.key,oe):fe.set(oe.index,oe),oe=oe.sibling;return fe}function v(fe,oe){return fe=me(fe,oe),fe.index=0,fe.sibling=null,fe}function b(fe,oe,pe){return fe.index=pe,i?(pe=fe.alternate,pe!==null?(pe=pe.index,pe<oe?(fe.flags|=2,oe):pe):(fe.flags|=2,oe)):(fe.flags|=1048576,oe)}function I(fe){return i&&fe.alternate===null&&(fe.flags|=2),fe}function ee(fe,oe,pe,Pe){return oe===null||oe.tag!==6?(oe=He(pe,fe.mode,Pe),oe.return=fe,oe):(oe=v(oe,pe),oe.return=fe,oe)}function se(fe,oe,pe,Pe){var at=pe.type;return at===Y?Te(fe,oe,pe.props.children,Pe,pe.key):oe!==null&&(oe.elementType===at||typeof at=="object"&&at!==null&&at.$$typeof===E&&Md(at)===oe.type)?(Pe=v(oe,pe.props),Pe.ref=jo(fe,oe,pe),Pe.return=fe,Pe):(Pe=ge(pe.type,pe.key,pe.props,null,fe.mode,Pe),Pe.ref=jo(fe,oe,pe),Pe.return=fe,Pe)}function we(fe,oe,pe,Pe){return oe===null||oe.tag!==4||oe.stateNode.containerInfo!==pe.containerInfo||oe.stateNode.implementation!==pe.implementation?(oe=Xe(pe,fe.mode,Pe),oe.return=fe,oe):(oe=v(oe,pe.children||[]),oe.return=fe,oe)}function Te(fe,oe,pe,Pe,at){return oe===null||oe.tag!==7?(oe=Ne(pe,fe.mode,Pe,at),oe.return=fe,oe):(oe=v(oe,pe),oe.return=fe,oe)}function Me(fe,oe,pe){if(typeof oe=="string"&&oe!==""||typeof oe=="number")return oe=He(""+oe,fe.mode,pe),oe.return=fe,oe;if(typeof oe=="object"&&oe!==null){switch(oe.$$typeof){case W:return pe=ge(oe.type,oe.key,oe.props,null,fe.mode,pe),pe.ref=jo(fe,null,oe),pe.return=fe,pe;case G:return oe=Xe(oe,fe.mode,pe),oe.return=fe,oe;case E:var Pe=oe._init;return Me(fe,Pe(oe._payload),pe)}if(xe(oe)||F(oe))return oe=Ne(oe,fe.mode,pe,null),oe.return=fe,oe;Wl(fe,oe)}return null}function $e(fe,oe,pe,Pe){var at=oe!==null?oe.key:null;if(typeof pe=="string"&&pe!==""||typeof pe=="number")return at!==null?null:ee(fe,oe,""+pe,Pe);if(typeof pe=="object"&&pe!==null){switch(pe.$$typeof){case W:return pe.key===at?se(fe,oe,pe,Pe):null;case G:return pe.key===at?we(fe,oe,pe,Pe):null;case E:return at=pe._init,$e(fe,oe,at(pe._payload),Pe)}if(xe(pe)||F(pe))return at!==null?null:Te(fe,oe,pe,Pe,null);Wl(fe,pe)}return null}function Ze(fe,oe,pe,Pe,at){if(typeof Pe=="string"&&Pe!==""||typeof Pe=="number")return fe=fe.get(pe)||null,ee(oe,fe,""+Pe,at);if(typeof Pe=="object"&&Pe!==null){switch(Pe.$$typeof){case W:return fe=fe.get(Pe.key===null?pe:Pe.key)||null,se(oe,fe,Pe,at);case G:return fe=fe.get(Pe.key===null?pe:Pe.key)||null,we(oe,fe,Pe,at);case E:var yt=Pe._init;return Ze(fe,oe,pe,yt(Pe._payload),at)}if(xe(Pe)||F(Pe))return fe=fe.get(pe)||null,Te(oe,fe,Pe,at,null);Wl(oe,Pe)}return null}function nt(fe,oe,pe,Pe){for(var at=null,yt=null,wt=oe,Ct=oe=0,Is=null;wt!==null&&Ct<pe.length;Ct++){wt.index>Ct?(Is=wt,wt=null):Is=wt.sibling;var un=$e(fe,wt,pe[Ct],Pe);if(un===null){wt===null&&(wt=Is);break}i&&wt&&un.alternate===null&&a(fe,wt),oe=b(un,oe,Ct),yt===null?at=un:yt.sibling=un,yt=un,wt=Is}if(Ct===pe.length)return d(fe,wt),An&&Vi(fe,Ct),at;if(wt===null){for(;Ct<pe.length;Ct++)wt=Me(fe,pe[Ct],Pe),wt!==null&&(oe=b(wt,oe,Ct),yt===null?at=wt:yt.sibling=wt,yt=wt);return An&&Vi(fe,Ct),at}for(wt=h(fe,wt);Ct<pe.length;Ct++)Is=Ze(wt,fe,Ct,pe[Ct],Pe),Is!==null&&(i&&Is.alternate!==null&&wt.delete(Is.key===null?Ct:Is.key),oe=b(Is,oe,Ct),yt===null?at=Is:yt.sibling=Is,yt=Is);return i&&wt.forEach(function(ll){return a(fe,ll)}),An&&Vi(fe,Ct),at}function st(fe,oe,pe,Pe){var at=F(pe);if(typeof at!="function")throw Error(n(150));if(pe=at.call(pe),pe==null)throw Error(n(151));for(var yt=at=null,wt=oe,Ct=oe=0,Is=null,un=pe.next();wt!==null&&!un.done;Ct++,un=pe.next()){wt.index>Ct?(Is=wt,wt=null):Is=wt.sibling;var ll=$e(fe,wt,un.value,Pe);if(ll===null){wt===null&&(wt=Is);break}i&&wt&&ll.alternate===null&&a(fe,wt),oe=b(ll,oe,Ct),yt===null?at=ll:yt.sibling=ll,yt=ll,wt=Is}if(un.done)return d(fe,wt),An&&Vi(fe,Ct),at;if(wt===null){for(;!un.done;Ct++,un=pe.next())un=Me(fe,un.value,Pe),un!==null&&(oe=b(un,oe,Ct),yt===null?at=un:yt.sibling=un,yt=un);return An&&Vi(fe,Ct),at}for(wt=h(fe,wt);!un.done;Ct++,un=pe.next())un=Ze(wt,fe,Ct,un.value,Pe),un!==null&&(i&&un.alternate!==null&&wt.delete(un.key===null?Ct:un.key),oe=b(un,oe,Ct),yt===null?at=un:yt.sibling=un,yt=un);return i&&wt.forEach(function(X0){return a(fe,X0)}),An&&Vi(fe,Ct),at}function ts(fe,oe,pe,Pe){if(typeof pe=="object"&&pe!==null&&pe.type===Y&&pe.key===null&&(pe=pe.props.children),typeof pe=="object"&&pe!==null){switch(pe.$$typeof){case W:e:{for(var at=pe.key,yt=oe;yt!==null;){if(yt.key===at){if(at=pe.type,at===Y){if(yt.tag===7){d(fe,yt.sibling),oe=v(yt,pe.props.children),oe.return=fe,fe=oe;break e}}else if(yt.elementType===at||typeof at=="object"&&at!==null&&at.$$typeof===E&&Md(at)===yt.type){d(fe,yt.sibling),oe=v(yt,pe.props),oe.ref=jo(fe,yt,pe),oe.return=fe,fe=oe;break e}d(fe,yt);break}else a(fe,yt);yt=yt.sibling}pe.type===Y?(oe=Ne(pe.props.children,fe.mode,Pe,pe.key),oe.return=fe,fe=oe):(Pe=ge(pe.type,pe.key,pe.props,null,fe.mode,Pe),Pe.ref=jo(fe,oe,pe),Pe.return=fe,fe=Pe)}return I(fe);case G:e:{for(yt=pe.key;oe!==null;){if(oe.key===yt)if(oe.tag===4&&oe.stateNode.containerInfo===pe.containerInfo&&oe.stateNode.implementation===pe.implementation){d(fe,oe.sibling),oe=v(oe,pe.children||[]),oe.return=fe,fe=oe;break e}else{d(fe,oe);break}else a(fe,oe);oe=oe.sibling}oe=Xe(pe,fe.mode,Pe),oe.return=fe,fe=oe}return I(fe);case E:return yt=pe._init,ts(fe,oe,yt(pe._payload),Pe)}if(xe(pe))return nt(fe,oe,pe,Pe);if(F(pe))return st(fe,oe,pe,Pe);Wl(fe,pe)}return typeof pe=="string"&&pe!==""||typeof pe=="number"?(pe=""+pe,oe!==null&&oe.tag===6?(d(fe,oe.sibling),oe=v(oe,pe),oe.return=fe,fe=oe):(d(fe,oe),oe=He(pe,fe.mode,Pe),oe.return=fe,fe=oe),I(fe)):d(fe,oe)}return ts}var la=_h(!0),Rd=_h(!1),ql=vo(null),ru=null,ca=null,Ja=null;function Ld(){Ja=ca=ru=null}function Id(i){var a=ql.current;Sn(ql),i._currentValue=a}function Od(i,a,d){for(;i!==null;){var h=i.alternate;if((i.childLanes&a)!==a?(i.childLanes|=a,h!==null&&(h.childLanes|=a)):h!==null&&(h.childLanes&a)!==a&&(h.childLanes|=a),i===d)break;i=i.return}}function Xa(i,a){ru=i,Ja=ca=null,i=i.dependencies,i!==null&&i.firstContext!==null&&((i.lanes&a)!==0&&(ur=!0),i.firstContext=null)}function cr(i){var a=i._currentValue;if(Ja!==i)if(i={context:i,memoizedValue:a,next:null},ca===null){if(ru===null)throw Error(n(308));ca=i,ru.dependencies={lanes:0,firstContext:i}}else ca=ca.next=i;return a}var ua=null;function Hl(i){ua===null?ua=[i]:ua.push(i)}function ph(i,a,d,h){var v=a.interleaved;return v===null?(d.next=d,Hl(a)):(d.next=v.next,v.next=d),a.interleaved=d,bi(i,h)}function bi(i,a){i.lanes|=a;var d=i.alternate;for(d!==null&&(d.lanes|=a),d=i,i=i.return;i!==null;)i.childLanes|=a,d=i.alternate,d!==null&&(d.childLanes|=a),d=i,i=i.return;return d.tag===3?d.stateNode:null}var So=!1;function Vl(i){i.updateQueue={baseState:i.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ie(i,a){i=i.updateQueue,a.updateQueue===i&&(a.updateQueue={baseState:i.baseState,firstBaseUpdate:i.firstBaseUpdate,lastBaseUpdate:i.lastBaseUpdate,shared:i.shared,effects:i.effects})}function gn(i,a){return{eventTime:i,lane:a,tag:0,payload:null,callback:null,next:null}}function ji(i,a,d){var h=i.updateQueue;if(h===null)return null;if(h=h.shared,(Ht&2)!==0){var v=h.pending;return v===null?a.next=a:(a.next=v.next,v.next=a),h.pending=a,bi(i,d)}return v=h.interleaved,v===null?(a.next=a,Hl(h)):(a.next=v.next,v.next=a),h.interleaved=a,bi(i,d)}function Gl(i,a,d){if(a=a.updateQueue,a!==null&&(a=a.shared,(d&4194240)!==0)){var h=a.lanes;h&=i.pendingLanes,d|=h,a.lanes=d,fo(i,d)}}function iu(i,a){var d=i.updateQueue,h=i.alternate;if(h!==null&&(h=h.updateQueue,d===h)){var v=null,b=null;if(d=d.firstBaseUpdate,d!==null){do{var I={eventTime:d.eventTime,lane:d.lane,tag:d.tag,payload:d.payload,callback:d.callback,next:null};b===null?v=b=I:b=b.next=I,d=d.next}while(d!==null);b===null?v=b=a:b=b.next=a}else v=b=a;d={baseState:h.baseState,firstBaseUpdate:v,lastBaseUpdate:b,shared:h.shared,effects:h.effects},i.updateQueue=d;return}i=d.lastBaseUpdate,i===null?d.firstBaseUpdate=a:i.next=a,d.lastBaseUpdate=a}function ou(i,a,d,h){var v=i.updateQueue;So=!1;var b=v.firstBaseUpdate,I=v.lastBaseUpdate,ee=v.shared.pending;if(ee!==null){v.shared.pending=null;var se=ee,we=se.next;se.next=null,I===null?b=we:I.next=we,I=se;var Te=i.alternate;Te!==null&&(Te=Te.updateQueue,ee=Te.lastBaseUpdate,ee!==I&&(ee===null?Te.firstBaseUpdate=we:ee.next=we,Te.lastBaseUpdate=se))}if(b!==null){var Me=v.baseState;I=0,Te=we=se=null,ee=b;do{var $e=ee.lane,Ze=ee.eventTime;if((h&$e)===$e){Te!==null&&(Te=Te.next={eventTime:Ze,lane:0,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null});e:{var nt=i,st=ee;switch($e=a,Ze=d,st.tag){case 1:if(nt=st.payload,typeof nt=="function"){Me=nt.call(Ze,Me,$e);break e}Me=nt;break e;case 3:nt.flags=nt.flags&-65537|128;case 0:if(nt=st.payload,$e=typeof nt=="function"?nt.call(Ze,Me,$e):nt,$e==null)break e;Me=K({},Me,$e);break e;case 2:So=!0}}ee.callback!==null&&ee.lane!==0&&(i.flags|=64,$e=v.effects,$e===null?v.effects=[ee]:$e.push(ee))}else Ze={eventTime:Ze,lane:$e,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null},Te===null?(we=Te=Ze,se=Me):Te=Te.next=Ze,I|=$e;if(ee=ee.next,ee===null){if(ee=v.shared.pending,ee===null)break;$e=ee,ee=$e.next,$e.next=null,v.lastBaseUpdate=$e,v.shared.pending=null}}while(!0);if(Te===null&&(se=Me),v.baseState=se,v.firstBaseUpdate=we,v.lastBaseUpdate=Te,a=v.shared.interleaved,a!==null){v=a;do I|=v.lane,v=v.next;while(v!==a)}else b===null&&(v.shared.lanes=0);Ao|=I,i.lanes=I,i.memoizedState=Me}}function gh(i,a,d){if(i=a.effects,a.effects=null,i!==null)for(a=0;a<i.length;a++){var h=i[a],v=h.callback;if(v!==null){if(h.callback=null,h=d,typeof v!="function")throw Error(n(191,v));v.call(h)}}}var Kl={},oi=vo(Kl),Za=vo(Kl),Yl=vo(Kl);function Si(i){if(i===Kl)throw Error(n(174));return i}function gs(i,a){switch(kn(Yl,a),kn(Za,i),kn(oi,Kl),i=a.nodeType,i){case 9:case 11:a=(a=a.documentElement)?a.namespaceURI:It(null,"");break;default:i=i===8?a.parentNode:a,a=i.namespaceURI||null,i=i.tagName,a=It(a,i)}Sn(oi),kn(oi,a)}function qt(){Sn(oi),Sn(Za),Sn(Yl)}function ys(i){Si(Yl.current);var a=Si(oi.current),d=It(a,i.type);a!==d&&(kn(Za,i),kn(oi,d))}function Jl(i){Za.current===i&&(Sn(oi),Sn(Za))}var Tn=vo(0);function ko(i){for(var a=i;a!==null;){if(a.tag===13){var d=a.memoizedState;if(d!==null&&(d=d.dehydrated,d===null||d.data==="$?"||d.data==="$!"))return a}else if(a.tag===19&&a.memoizedProps.revealOrder!==void 0){if((a.flags&128)!==0)return a}else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===i)break;for(;a.sibling===null;){if(a.return===null||a.return===i)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var au=[];function ut(){for(var i=0;i<au.length;i++)au[i]._workInProgressVersionPrimary=null;au.length=0}var lu=P.ReactCurrentDispatcher,Xl=P.ReactCurrentBatchConfig,da=0,Fn=null,Jn=null,as=null,cu=!1,Zl=!1,fa=0,Qa=0;function Ms(){throw Error(n(321))}function Wr(i,a){if(a===null)return!1;for(var d=0;d<a.length&&d<i.length;d++)if(!ei(i[d],a[d]))return!1;return!0}function Sr(i,a,d,h,v,b){if(da=b,Fn=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,lu.current=i===null||i.memoizedState===null?Xt:Xn,i=d(h,v),Zl){b=0;do{if(Zl=!1,fa=0,25<=b)throw Error(n(301));b+=1,as=Jn=null,a.updateQueue=null,lu.current=Nr,i=d(h,v)}while(Zl)}if(lu.current=wu,a=Jn!==null&&Jn.next!==null,da=0,as=Jn=Fn=null,cu=!1,a)throw Error(n(300));return i}function uu(){var i=fa!==0;return fa=0,i}function ki(){var i={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return as===null?Fn.memoizedState=as=i:as=as.next=i,as}function qr(){if(Jn===null){var i=Fn.alternate;i=i!==null?i.memoizedState:null}else i=Jn.next;var a=as===null?Fn.memoizedState:as.next;if(a!==null)as=a,Jn=i;else{if(i===null)throw Error(n(310));Jn=i,i={memoizedState:Jn.memoizedState,baseState:Jn.baseState,baseQueue:Jn.baseQueue,queue:Jn.queue,next:null},as===null?Fn.memoizedState=as=i:as=as.next=i}return as}function Ql(i,a){return typeof a=="function"?a(i):a}function du(i){var a=qr(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=i;var h=Jn,v=h.baseQueue,b=d.pending;if(b!==null){if(v!==null){var I=v.next;v.next=b.next,b.next=I}h.baseQueue=v=b,d.pending=null}if(v!==null){b=v.next,h=h.baseState;var ee=I=null,se=null,we=b;do{var Te=we.lane;if((da&Te)===Te)se!==null&&(se=se.next={lane:0,action:we.action,hasEagerState:we.hasEagerState,eagerState:we.eagerState,next:null}),h=we.hasEagerState?we.eagerState:i(h,we.action);else{var Me={lane:Te,action:we.action,hasEagerState:we.hasEagerState,eagerState:we.eagerState,next:null};se===null?(ee=se=Me,I=h):se=se.next=Me,Fn.lanes|=Te,Ao|=Te}we=we.next}while(we!==null&&we!==b);se===null?I=h:se.next=ee,ei(h,a.memoizedState)||(ur=!0),a.memoizedState=h,a.baseState=I,a.baseQueue=se,d.lastRenderedState=h}if(i=d.interleaved,i!==null){v=i;do b=v.lane,Fn.lanes|=b,Ao|=b,v=v.next;while(v!==i)}else v===null&&(d.lanes=0);return[a.memoizedState,d.dispatch]}function ec(i){var a=qr(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=i;var h=d.dispatch,v=d.pending,b=a.memoizedState;if(v!==null){d.pending=null;var I=v=v.next;do b=i(b,I.action),I=I.next;while(I!==v);ei(b,a.memoizedState)||(ur=!0),a.memoizedState=b,a.baseQueue===null&&(a.baseState=b),d.lastRenderedState=b}return[b,h]}function yh(){}function Mn(i,a){var d=Fn,h=qr(),v=a(),b=!ei(h.memoizedState,v);if(b&&(h.memoizedState=v,ur=!0),h=h.queue,tc(qs.bind(null,d,h,i),[i]),h.getSnapshot!==a||b||as!==null&&as.memoizedState.tag&1){if(d.flags|=2048,Gi(9,fu.bind(null,d,h,v,a),void 0,null),cs===null)throw Error(n(349));(da&30)!==0||Pd(d,a,v)}return v}function Pd(i,a,d){i.flags|=16384,i={getSnapshot:a,value:d},a=Fn.updateQueue,a===null?(a={lastEffect:null,stores:null},Fn.updateQueue=a,a.stores=[i]):(d=a.stores,d===null?a.stores=[i]:d.push(i))}function fu(i,a,d,h){a.value=d,a.getSnapshot=h,Dd(a)&&el(i)}function qs(i,a,d){return d(function(){Dd(a)&&el(i)})}function Dd(i){var a=i.getSnapshot;i=i.value;try{var d=a();return!ei(i,d)}catch{return!0}}function el(i){var a=bi(i,1);a!==null&&ci(a,i,1,-1)}function hu(i){var a=ki();return typeof i=="function"&&(i=i()),a.memoizedState=a.baseState=i,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Ql,lastRenderedState:i},a.queue=i,i=i.dispatch=E_.bind(null,Fn,i),[a.memoizedState,i]}function Gi(i,a,d,h){return i={tag:i,create:a,destroy:d,deps:h,next:null},a=Fn.updateQueue,a===null?(a={lastEffect:null,stores:null},Fn.updateQueue=a,a.lastEffect=i.next=i):(d=a.lastEffect,d===null?a.lastEffect=i.next=i:(h=d.next,d.next=i,i.next=h,a.lastEffect=i)),i}function mu(){return qr().memoizedState}function _u(i,a,d,h){var v=ki();Fn.flags|=i,v.memoizedState=Gi(1|a,d,void 0,h===void 0?null:h)}function pu(i,a,d,h){var v=qr();h=h===void 0?null:h;var b=void 0;if(Jn!==null){var I=Jn.memoizedState;if(b=I.destroy,h!==null&&Wr(h,I.deps)){v.memoizedState=Gi(a,d,b,h);return}}Fn.flags|=i,v.memoizedState=Gi(1|a,d,b,h)}function wh(i,a){return _u(8390656,8,i,a)}function tc(i,a){return pu(2048,8,i,a)}function gu(i,a){return pu(4,2,i,a)}function vh(i,a){return pu(4,4,i,a)}function yu(i,a){if(typeof a=="function")return i=i(),a(i),function(){a(null)};if(a!=null)return i=i(),a.current=i,function(){a.current=null}}function xh(i,a,d){return d=d!=null?d.concat([i]):null,pu(4,4,yu.bind(null,a,i),d)}function kr(){}function ha(i,a){var d=qr();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&Wr(a,h[1])?h[0]:(d.memoizedState=[i,a],i)}function Hn(i,a){var d=qr();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&Wr(a,h[1])?h[0]:(i=i(),d.memoizedState=[i,a],i)}function Fd(i,a,d){return(da&21)===0?(i.baseState&&(i.baseState=!1,ur=!0),i.memoizedState=d):(ei(d,a)||(d=fs(),Fn.lanes|=d,Ao|=d,i.baseState=!0),a)}function bh(i,a){var d=rn;rn=d!==0&&4>d?d:4,i(!0);var h=Xl.transition;Xl.transition={};try{i(!1),a()}finally{rn=d,Xl.transition=h}}function jh(){return qr().memoizedState}function C_(i,a,d){var h=eo(i);if(d={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null},zd(i))Bd(a,d);else if(d=ph(i,a,d,h),d!==null){var v=Ls();ci(d,i,h,v),Sh(d,a,h)}}function E_(i,a,d){var h=eo(i),v={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null};if(zd(i))Bd(a,v);else{var b=i.alternate;if(i.lanes===0&&(b===null||b.lanes===0)&&(b=a.lastRenderedReducer,b!==null))try{var I=a.lastRenderedState,ee=b(I,d);if(v.hasEagerState=!0,v.eagerState=ee,ei(ee,I)){var se=a.interleaved;se===null?(v.next=v,Hl(a)):(v.next=se.next,se.next=v),a.interleaved=v;return}}catch{}finally{}d=ph(i,a,v,h),d!==null&&(v=Ls(),ci(d,i,h,v),Sh(d,a,h))}}function zd(i){var a=i.alternate;return i===Fn||a!==null&&a===Fn}function Bd(i,a){Zl=cu=!0;var d=i.pending;d===null?a.next=a:(a.next=d.next,d.next=a),i.pending=a}function Sh(i,a,d){if((d&4194240)!==0){var h=a.lanes;h&=i.pendingLanes,d|=h,a.lanes=d,fo(i,d)}}var wu={readContext:cr,useCallback:Ms,useContext:Ms,useEffect:Ms,useImperativeHandle:Ms,useInsertionEffect:Ms,useLayoutEffect:Ms,useMemo:Ms,useReducer:Ms,useRef:Ms,useState:Ms,useDebugValue:Ms,useDeferredValue:Ms,useTransition:Ms,useMutableSource:Ms,useSyncExternalStore:Ms,useId:Ms,unstable_isNewReconciler:!1},Xt={readContext:cr,useCallback:function(i,a){return ki().memoizedState=[i,a===void 0?null:a],i},useContext:cr,useEffect:wh,useImperativeHandle:function(i,a,d){return d=d!=null?d.concat([i]):null,_u(4194308,4,yu.bind(null,a,i),d)},useLayoutEffect:function(i,a){return _u(4194308,4,i,a)},useInsertionEffect:function(i,a){return _u(4,2,i,a)},useMemo:function(i,a){var d=ki();return a=a===void 0?null:a,i=i(),d.memoizedState=[i,a],i},useReducer:function(i,a,d){var h=ki();return a=d!==void 0?d(a):a,h.memoizedState=h.baseState=a,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:i,lastRenderedState:a},h.queue=i,i=i.dispatch=C_.bind(null,Fn,i),[h.memoizedState,i]},useRef:function(i){var a=ki();return i={current:i},a.memoizedState=i},useState:hu,useDebugValue:kr,useDeferredValue:function(i){return ki().memoizedState=i},useTransition:function(){var i=hu(!1),a=i[0];return i=bh.bind(null,i[1]),ki().memoizedState=i,[a,i]},useMutableSource:function(){},useSyncExternalStore:function(i,a,d){var h=Fn,v=ki();if(An){if(d===void 0)throw Error(n(407));d=d()}else{if(d=a(),cs===null)throw Error(n(349));(da&30)!==0||Pd(h,a,d)}v.memoizedState=d;var b={value:d,getSnapshot:a};return v.queue=b,wh(qs.bind(null,h,b,i),[i]),h.flags|=2048,Gi(9,fu.bind(null,h,b,d,a),void 0,null),d},useId:function(){var i=ki(),a=cs.identifierPrefix;if(An){var d=jr,h=ri;d=(h&~(1<<32-rs(h)-1)).toString(32)+d,a=":"+a+"R"+d,d=fa++,0<d&&(a+="H"+d.toString(32)),a+=":"}else d=Qa++,a=":"+a+"r"+d.toString(32)+":";return i.memoizedState=a},unstable_isNewReconciler:!1},Xn={readContext:cr,useCallback:ha,useContext:cr,useEffect:tc,useImperativeHandle:xh,useInsertionEffect:gu,useLayoutEffect:vh,useMemo:Hn,useReducer:du,useRef:mu,useState:function(){return du(Ql)},useDebugValue:kr,useDeferredValue:function(i){var a=qr();return Fd(a,Jn.memoizedState,i)},useTransition:function(){var i=du(Ql)[0],a=qr().memoizedState;return[i,a]},useMutableSource:yh,useSyncExternalStore:Mn,useId:jh,unstable_isNewReconciler:!1},Nr={readContext:cr,useCallback:ha,useContext:cr,useEffect:tc,useImperativeHandle:xh,useInsertionEffect:gu,useLayoutEffect:vh,useMemo:Hn,useReducer:ec,useRef:mu,useState:function(){return ec(Ql)},useDebugValue:kr,useDeferredValue:function(i){var a=qr();return Jn===null?a.memoizedState=i:Fd(a,Jn.memoizedState,i)},useTransition:function(){var i=ec(Ql)[0],a=qr().memoizedState;return[i,a]},useMutableSource:yh,useSyncExternalStore:Mn,useId:jh,unstable_isNewReconciler:!1};function Cr(i,a){if(i&&i.defaultProps){a=K({},a),i=i.defaultProps;for(var d in i)a[d]===void 0&&(a[d]=i[d]);return a}return a}function tl(i,a,d,h){a=i.memoizedState,d=d(h,a),d=d==null?a:K({},a,d),i.memoizedState=d,i.lanes===0&&(i.updateQueue.baseState=d)}var nc={isMounted:function(i){return(i=i._reactInternals)?ft(i)===i:!1},enqueueSetState:function(i,a,d){i=i._reactInternals;var h=Ls(),v=eo(i),b=gn(h,v);b.payload=a,d!=null&&(b.callback=d),a=ji(i,b,v),a!==null&&(ci(a,i,v,h),Gl(a,i,v))},enqueueReplaceState:function(i,a,d){i=i._reactInternals;var h=Ls(),v=eo(i),b=gn(h,v);b.tag=1,b.payload=a,d!=null&&(b.callback=d),a=ji(i,b,v),a!==null&&(ci(a,i,v,h),Gl(a,i,v))},enqueueForceUpdate:function(i,a){i=i._reactInternals;var d=Ls(),h=eo(i),v=gn(d,h);v.tag=2,a!=null&&(v.callback=a),a=ji(i,v,h),a!==null&&(ci(a,i,h,d),Gl(a,i,h))}};function kh(i,a,d,h,v,b,I){return i=i.stateNode,typeof i.shouldComponentUpdate=="function"?i.shouldComponentUpdate(h,b,I):a.prototype&&a.prototype.isPureReactComponent?!Yo(d,h)||!Yo(v,b):!0}function Nh(i,a,d){var h=!1,v=qi,b=a.contextType;return typeof b=="object"&&b!==null?b=cr(b):(v=os(a)?sa:Es.current,h=a.contextTypes,b=(h=h!=null)?ra(i,v):qi),a=new a(d,b),i.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,a.updater=nc,i.stateNode=a,a._reactInternals=i,h&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=v,i.__reactInternalMemoizedMaskedChildContext=b),a}function Ud(i,a,d,h){i=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(d,h),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(d,h),a.state!==i&&nc.enqueueReplaceState(a,a.state,null)}function ma(i,a,d,h){var v=i.stateNode;v.props=d,v.state=i.memoizedState,v.refs={},Vl(i);var b=a.contextType;typeof b=="object"&&b!==null?v.context=cr(b):(b=os(a)?sa:Es.current,v.context=ra(i,b)),v.state=i.memoizedState,b=a.getDerivedStateFromProps,typeof b=="function"&&(tl(i,a,b,d),v.state=i.memoizedState),typeof a.getDerivedStateFromProps=="function"||typeof v.getSnapshotBeforeUpdate=="function"||typeof v.UNSAFE_componentWillMount!="function"&&typeof v.componentWillMount!="function"||(a=v.state,typeof v.componentWillMount=="function"&&v.componentWillMount(),typeof v.UNSAFE_componentWillMount=="function"&&v.UNSAFE_componentWillMount(),a!==v.state&&nc.enqueueReplaceState(v,v.state,null),ou(i,d,v,h),v.state=i.memoizedState),typeof v.componentDidMount=="function"&&(i.flags|=4194308)}function nl(i,a){try{var d="",h=a;do d+=le(h),h=h.return;while(h);var v=d}catch(b){v=`
39
+ Error generating stack: `+b.message+`
40
+ `+b.stack}return{value:i,source:a,stack:v,digest:null}}function Wd(i,a,d){return{value:i,source:null,stack:d??null,digest:a??null}}function qd(i,a){try{console.error(a.value)}catch(d){setTimeout(function(){throw d})}}var Ch=typeof WeakMap=="function"?WeakMap:Map;function Hd(i,a,d){d=gn(-1,d),d.tag=3,d.payload={element:null};var h=a.value;return d.callback=function(){fc||(fc=!0,Cu=h),qd(i,a)},d}function No(i,a,d){d=gn(-1,d),d.tag=3;var h=i.type.getDerivedStateFromError;if(typeof h=="function"){var v=a.value;d.payload=function(){return h(v)},d.callback=function(){qd(i,a)}}var b=i.stateNode;return b!==null&&typeof b.componentDidCatch=="function"&&(d.callback=function(){qd(i,a),typeof h!="function"&&(Zi===null?Zi=new Set([this]):Zi.add(this));var I=a.stack;this.componentDidCatch(a.value,{componentStack:I!==null?I:""})}),d}function vu(i,a,d){var h=i.pingCache;if(h===null){h=i.pingCache=new Ch;var v=new Set;h.set(a,v)}else v=h.get(a),v===void 0&&(v=new Set,h.set(a,v));v.has(d)||(v.add(d),i=Kh.bind(null,i,a,d),a.then(i,i))}function Vd(i){do{var a;if((a=i.tag===13)&&(a=i.memoizedState,a=a!==null?a.dehydrated!==null:!0),a)return i;i=i.return}while(i!==null);return null}function xu(i,a,d,h,v){return(i.mode&1)===0?(i===a?i.flags|=65536:(i.flags|=128,d.flags|=131072,d.flags&=-52805,d.tag===1&&(d.alternate===null?d.tag=17:(a=gn(-1,1),a.tag=2,ji(d,a,1))),d.lanes|=1),i):(i.flags|=65536,i.lanes=v,i)}var Eh=P.ReactCurrentOwner,ur=!1;function Hs(i,a,d,h){a.child=i===null?Rd(a,null,d,h):la(a,i.child,d,h)}function $h(i,a,d,h,v){d=d.render;var b=a.ref;return Xa(a,v),h=Sr(i,a,d,h,b,v),d=uu(),i!==null&&!ur?(a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~v,Ji(i,a,v)):(An&&d&&Bl(a),a.flags|=1,Hs(i,a,h,v),a.child)}function Ah(i,a,d,h,v){if(i===null){var b=d.type;return typeof b=="function"&&!ne(b)&&b.defaultProps===void 0&&d.compare===null&&d.defaultProps===void 0?(a.tag=15,a.type=b,Th(i,a,b,h,v)):(i=ge(d.type,null,h,a,a.mode,v),i.ref=a.ref,i.return=a,a.child=i)}if(b=i.child,(i.lanes&v)===0){var I=b.memoizedProps;if(d=d.compare,d=d!==null?d:Yo,d(I,h)&&i.ref===a.ref)return Ji(i,a,v)}return a.flags|=1,i=me(b,h),i.ref=a.ref,i.return=a,a.child=i}function Th(i,a,d,h,v){if(i!==null){var b=i.memoizedProps;if(Yo(b,h)&&i.ref===a.ref)if(ur=!1,a.pendingProps=h=b,(i.lanes&v)!==0)(i.flags&131072)!==0&&(ur=!0);else return a.lanes=i.lanes,Ji(i,a,v)}return bu(i,a,d,h,v)}function Mh(i,a,d){var h=a.pendingProps,v=h.children,b=i!==null?i.memoizedState:null;if(h.mode==="hidden")if((a.mode&1)===0)a.memoizedState={baseLanes:0,cachePool:null,transitions:null},kn(Rn,Ks),Ks|=d;else{if((d&1073741824)===0)return i=b!==null?b.baseLanes|d:d,a.lanes=a.childLanes=1073741824,a.memoizedState={baseLanes:i,cachePool:null,transitions:null},a.updateQueue=null,kn(Rn,Ks),Ks|=i,null;a.memoizedState={baseLanes:0,cachePool:null,transitions:null},h=b!==null?b.baseLanes:d,kn(Rn,Ks),Ks|=h}else b!==null?(h=b.baseLanes|d,a.memoizedState=null):h=d,kn(Rn,Ks),Ks|=h;return Hs(i,a,v,d),a.child}function Rh(i,a){var d=a.ref;(i===null&&d!==null||i!==null&&i.ref!==d)&&(a.flags|=512,a.flags|=2097152)}function bu(i,a,d,h,v){var b=os(d)?sa:Es.current;return b=ra(a,b),Xa(a,v),d=Sr(i,a,d,h,b,v),h=uu(),i!==null&&!ur?(a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~v,Ji(i,a,v)):(An&&h&&Bl(a),a.flags|=1,Hs(i,a,d,v),a.child)}function ju(i,a,d,h,v){if(os(d)){var b=!0;ia(a)}else b=!1;if(Xa(a,v),a.stateNode===null)_a(i,a),Nh(a,d,h),ma(a,d,h,v),h=!0;else if(i===null){var I=a.stateNode,ee=a.memoizedProps;I.props=ee;var se=I.context,we=d.contextType;typeof we=="object"&&we!==null?we=cr(we):(we=os(d)?sa:Es.current,we=ra(a,we));var Te=d.getDerivedStateFromProps,Me=typeof Te=="function"||typeof I.getSnapshotBeforeUpdate=="function";Me||typeof I.UNSAFE_componentWillReceiveProps!="function"&&typeof I.componentWillReceiveProps!="function"||(ee!==h||se!==we)&&Ud(a,I,h,we),So=!1;var $e=a.memoizedState;I.state=$e,ou(a,h,I,v),se=a.memoizedState,ee!==h||$e!==se||Us.current||So?(typeof Te=="function"&&(tl(a,d,Te,h),se=a.memoizedState),(ee=So||kh(a,d,ee,h,$e,se,we))?(Me||typeof I.UNSAFE_componentWillMount!="function"&&typeof I.componentWillMount!="function"||(typeof I.componentWillMount=="function"&&I.componentWillMount(),typeof I.UNSAFE_componentWillMount=="function"&&I.UNSAFE_componentWillMount()),typeof I.componentDidMount=="function"&&(a.flags|=4194308)):(typeof I.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=h,a.memoizedState=se),I.props=h,I.state=se,I.context=we,h=ee):(typeof I.componentDidMount=="function"&&(a.flags|=4194308),h=!1)}else{I=a.stateNode,Ie(i,a),ee=a.memoizedProps,we=a.type===a.elementType?ee:Cr(a.type,ee),I.props=we,Me=a.pendingProps,$e=I.context,se=d.contextType,typeof se=="object"&&se!==null?se=cr(se):(se=os(d)?sa:Es.current,se=ra(a,se));var Ze=d.getDerivedStateFromProps;(Te=typeof Ze=="function"||typeof I.getSnapshotBeforeUpdate=="function")||typeof I.UNSAFE_componentWillReceiveProps!="function"&&typeof I.componentWillReceiveProps!="function"||(ee!==Me||$e!==se)&&Ud(a,I,h,se),So=!1,$e=a.memoizedState,I.state=$e,ou(a,h,I,v);var nt=a.memoizedState;ee!==Me||$e!==nt||Us.current||So?(typeof Ze=="function"&&(tl(a,d,Ze,h),nt=a.memoizedState),(we=So||kh(a,d,we,h,$e,nt,se)||!1)?(Te||typeof I.UNSAFE_componentWillUpdate!="function"&&typeof I.componentWillUpdate!="function"||(typeof I.componentWillUpdate=="function"&&I.componentWillUpdate(h,nt,se),typeof I.UNSAFE_componentWillUpdate=="function"&&I.UNSAFE_componentWillUpdate(h,nt,se)),typeof I.componentDidUpdate=="function"&&(a.flags|=4),typeof I.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof I.componentDidUpdate!="function"||ee===i.memoizedProps&&$e===i.memoizedState||(a.flags|=4),typeof I.getSnapshotBeforeUpdate!="function"||ee===i.memoizedProps&&$e===i.memoizedState||(a.flags|=1024),a.memoizedProps=h,a.memoizedState=nt),I.props=h,I.state=nt,I.context=se,h=we):(typeof I.componentDidUpdate!="function"||ee===i.memoizedProps&&$e===i.memoizedState||(a.flags|=4),typeof I.getSnapshotBeforeUpdate!="function"||ee===i.memoizedProps&&$e===i.memoizedState||(a.flags|=1024),h=!1)}return Gd(i,a,d,h,b,v)}function Gd(i,a,d,h,v,b){Rh(i,a);var I=(a.flags&128)!==0;if(!h&&!I)return v&&Ad(a,d,!1),Ji(i,a,b);h=a.stateNode,Eh.current=a;var ee=I&&typeof d.getDerivedStateFromError!="function"?null:h.render();return a.flags|=1,i!==null&&I?(a.child=la(a,i.child,null,b),a.child=la(a,null,ee,b)):Hs(i,a,ee,b),a.memoizedState=h.state,v&&Ad(a,d,!0),a.child}function Lh(i){var a=i.stateNode;a.pendingContext?Wa(i,a.pendingContext,a.pendingContext!==a.context):a.context&&Wa(i,a.context,!1),gs(i,a.containerInfo)}function sc(i,a,d,h,v){return Ka(),Ya(v),a.flags|=256,Hs(i,a,d,h),a.child}var Kd={dehydrated:null,treeContext:null,retryLane:0};function Ki(i){return{baseLanes:i,cachePool:null,transitions:null}}function Rs(i,a,d){var h=a.pendingProps,v=Tn.current,b=!1,I=(a.flags&128)!==0,ee;if((ee=I)||(ee=i!==null&&i.memoizedState===null?!1:(v&2)!==0),ee?(b=!0,a.flags&=-129):(i===null||i.memoizedState!==null)&&(v|=1),kn(Tn,v&1),i===null)return Ul(a),i=a.memoizedState,i!==null&&(i=i.dehydrated,i!==null)?((a.mode&1)===0?a.lanes=1:i.data==="$!"?a.lanes=8:a.lanes=1073741824,null):(I=h.children,i=h.fallback,b?(h=a.mode,b=a.child,I={mode:"hidden",children:I},(h&1)===0&&b!==null?(b.childLanes=0,b.pendingProps=I):b=Oe(I,h,0,null),i=Ne(i,h,d,null),b.return=a,i.return=a,b.sibling=i,a.child=b,a.child.memoizedState=Ki(d),a.memoizedState=Kd,i):Qn(a,I));if(v=i.memoizedState,v!==null&&(ee=v.dehydrated,ee!==null))return Co(i,a,I,h,ee,v,d);if(b){b=h.fallback,I=a.mode,v=i.child,ee=v.sibling;var se={mode:"hidden",children:h.children};return(I&1)===0&&a.child!==v?(h=a.child,h.childLanes=0,h.pendingProps=se,a.deletions=null):(h=me(v,se),h.subtreeFlags=v.subtreeFlags&14680064),ee!==null?b=me(ee,b):(b=Ne(b,I,d,null),b.flags|=2),b.return=a,h.return=a,h.sibling=b,a.child=h,h=b,b=a.child,I=i.child.memoizedState,I=I===null?Ki(d):{baseLanes:I.baseLanes|d,cachePool:null,transitions:I.transitions},b.memoizedState=I,b.childLanes=i.childLanes&~d,a.memoizedState=Kd,h}return b=i.child,i=b.sibling,h=me(b,{mode:"visible",children:h.children}),(a.mode&1)===0&&(h.lanes=d),h.return=a,h.sibling=null,i!==null&&(d=a.deletions,d===null?(a.deletions=[i],a.flags|=16):d.push(i)),a.child=h,a.memoizedState=null,h}function Qn(i,a){return a=Oe({mode:"visible",children:a},i.mode,0,null),a.return=i,i.child=a}function Er(i,a,d,h){return h!==null&&Ya(h),la(a,i.child,null,d),i=Qn(a,a.pendingProps.children),i.flags|=2,a.memoizedState=null,i}function Co(i,a,d,h,v,b,I){if(d)return a.flags&256?(a.flags&=-257,h=Wd(Error(n(422))),Er(i,a,I,h)):a.memoizedState!==null?(a.child=i.child,a.flags|=128,null):(b=h.fallback,v=a.mode,h=Oe({mode:"visible",children:h.children},v,0,null),b=Ne(b,v,I,null),b.flags|=2,h.return=a,b.return=a,h.sibling=b,a.child=h,(a.mode&1)!==0&&la(a,i.child,null,I),a.child.memoizedState=Ki(I),a.memoizedState=Kd,b);if((a.mode&1)===0)return Er(i,a,I,null);if(v.data==="$!"){if(h=v.nextSibling&&v.nextSibling.dataset,h)var ee=h.dgst;return h=ee,b=Error(n(419)),h=Wd(b,h,void 0),Er(i,a,I,h)}if(ee=(I&i.childLanes)!==0,ur||ee){if(h=cs,h!==null){switch(I&-I){case 4:v=2;break;case 16:v=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:v=32;break;case 536870912:v=268435456;break;default:v=0}v=(v&(h.suspendedLanes|I))!==0?0:v,v!==0&&v!==b.retryLane&&(b.retryLane=v,bi(i,v),ci(h,i,v,-1))}return Au(),h=Wd(Error(n(421))),Er(i,a,I,h)}return v.data==="$?"?(a.flags|=128,a.child=i.child,a=k.bind(null,i),v._reactRetry=a,null):(i=b.treeContext,lr=Bs(v.nextSibling),Ws=a,An=!0,ii=null,i!==null&&($s[As++]=ri,$s[As++]=jr,$s[As++]=bo,ri=i.id,jr=i.overflow,bo=a),a=Qn(a,h.children),a.flags|=4096,a)}function Yi(i,a,d){i.lanes|=a;var h=i.alternate;h!==null&&(h.lanes|=a),Od(i.return,a,d)}function $r(i,a,d,h,v){var b=i.memoizedState;b===null?i.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:h,tail:d,tailMode:v}:(b.isBackwards=a,b.rendering=null,b.renderingStartTime=0,b.last=h,b.tail=d,b.tailMode=v)}function Ih(i,a,d){var h=a.pendingProps,v=h.revealOrder,b=h.tail;if(Hs(i,a,h.children,d),h=Tn.current,(h&2)!==0)h=h&1|2,a.flags|=128;else{if(i!==null&&(i.flags&128)!==0)e:for(i=a.child;i!==null;){if(i.tag===13)i.memoizedState!==null&&Yi(i,d,a);else if(i.tag===19)Yi(i,d,a);else if(i.child!==null){i.child.return=i,i=i.child;continue}if(i===a)break e;for(;i.sibling===null;){if(i.return===null||i.return===a)break e;i=i.return}i.sibling.return=i.return,i=i.sibling}h&=1}if(kn(Tn,h),(a.mode&1)===0)a.memoizedState=null;else switch(v){case"forwards":for(d=a.child,v=null;d!==null;)i=d.alternate,i!==null&&ko(i)===null&&(v=d),d=d.sibling;d=v,d===null?(v=a.child,a.child=null):(v=d.sibling,d.sibling=null),$r(a,!1,v,d,b);break;case"backwards":for(d=null,v=a.child,a.child=null;v!==null;){if(i=v.alternate,i!==null&&ko(i)===null){a.child=v;break}i=v.sibling,v.sibling=d,d=v,v=i}$r(a,!0,d,null,b);break;case"together":$r(a,!1,null,null,void 0);break;default:a.memoizedState=null}return a.child}function _a(i,a){(a.mode&1)===0&&i!==null&&(i.alternate=null,a.alternate=null,a.flags|=2)}function Ji(i,a,d){if(i!==null&&(a.dependencies=i.dependencies),Ao|=a.lanes,(d&a.childLanes)===0)return null;if(i!==null&&a.child!==i.child)throw Error(n(153));if(a.child!==null){for(i=a.child,d=me(i,i.pendingProps),a.child=d,d.return=a;i.sibling!==null;)i=i.sibling,d=d.sibling=me(i,i.pendingProps),d.return=a;d.sibling=null}return a.child}function Yd(i,a,d){switch(a.tag){case 3:Lh(a),Ka();break;case 5:ys(a);break;case 1:os(a.type)&&ia(a);break;case 4:gs(a,a.stateNode.containerInfo);break;case 10:var h=a.type._context,v=a.memoizedProps.value;kn(ql,h._currentValue),h._currentValue=v;break;case 13:if(h=a.memoizedState,h!==null)return h.dehydrated!==null?(kn(Tn,Tn.current&1),a.flags|=128,null):(d&a.child.childLanes)!==0?Rs(i,a,d):(kn(Tn,Tn.current&1),i=Ji(i,a,d),i!==null?i.sibling:null);kn(Tn,Tn.current&1);break;case 19:if(h=(d&a.childLanes)!==0,(i.flags&128)!==0){if(h)return Ih(i,a,d);a.flags|=128}if(v=a.memoizedState,v!==null&&(v.rendering=null,v.tail=null,v.lastEffect=null),kn(Tn,Tn.current),h)break;return null;case 22:case 23:return a.lanes=0,Mh(i,a,d)}return Ji(i,a,d)}var Oh,Jd,Xd,Eo;Oh=function(i,a){for(var d=a.child;d!==null;){if(d.tag===5||d.tag===6)i.appendChild(d.stateNode);else if(d.tag!==4&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===a)break;for(;d.sibling===null;){if(d.return===null||d.return===a)return;d=d.return}d.sibling.return=d.return,d=d.sibling}},Jd=function(){},Xd=function(i,a,d,h){var v=i.memoizedProps;if(v!==h){i=a.stateNode,Si(oi.current);var b=null;switch(d){case"input":v=tt(i,v),h=tt(i,h),b=[];break;case"select":v=K({},v,{value:void 0}),h=K({},h,{value:void 0}),b=[];break;case"textarea":v=Ue(i,v),h=Ue(i,h),b=[];break;default:typeof v.onClick!="function"&&typeof h.onClick=="function"&&(i.onclick=Bi)}_n(d,h);var I;d=null;for(we in v)if(!h.hasOwnProperty(we)&&v.hasOwnProperty(we)&&v[we]!=null)if(we==="style"){var ee=v[we];for(I in ee)ee.hasOwnProperty(I)&&(d||(d={}),d[I]="")}else we!=="dangerouslySetInnerHTML"&&we!=="children"&&we!=="suppressContentEditableWarning"&&we!=="suppressHydrationWarning"&&we!=="autoFocus"&&(o.hasOwnProperty(we)?b||(b=[]):(b=b||[]).push(we,null));for(we in h){var se=h[we];if(ee=v!=null?v[we]:void 0,h.hasOwnProperty(we)&&se!==ee&&(se!=null||ee!=null))if(we==="style")if(ee){for(I in ee)!ee.hasOwnProperty(I)||se&&se.hasOwnProperty(I)||(d||(d={}),d[I]="");for(I in se)se.hasOwnProperty(I)&&ee[I]!==se[I]&&(d||(d={}),d[I]=se[I])}else d||(b||(b=[]),b.push(we,d)),d=se;else we==="dangerouslySetInnerHTML"?(se=se?se.__html:void 0,ee=ee?ee.__html:void 0,se!=null&&ee!==se&&(b=b||[]).push(we,se)):we==="children"?typeof se!="string"&&typeof se!="number"||(b=b||[]).push(we,""+se):we!=="suppressContentEditableWarning"&&we!=="suppressHydrationWarning"&&(o.hasOwnProperty(we)?(se!=null&&we==="onScroll"&&Cn("scroll",i),b||ee===se||(b=[])):(b=b||[]).push(we,se))}d&&(b=b||[]).push("style",d);var we=b;(a.updateQueue=we)&&(a.flags|=4)}},Eo=function(i,a,d,h){d!==h&&(a.flags|=4)};function Xi(i,a){if(!An)switch(i.tailMode){case"hidden":a=i.tail;for(var d=null;a!==null;)a.alternate!==null&&(d=a),a=a.sibling;d===null?i.tail=null:d.sibling=null;break;case"collapsed":d=i.tail;for(var h=null;d!==null;)d.alternate!==null&&(h=d),d=d.sibling;h===null?a||i.tail===null?i.tail=null:i.tail.sibling=null:h.sibling=null}}function ws(i){var a=i.alternate!==null&&i.alternate.child===i.child,d=0,h=0;if(a)for(var v=i.child;v!==null;)d|=v.lanes|v.childLanes,h|=v.subtreeFlags&14680064,h|=v.flags&14680064,v.return=i,v=v.sibling;else for(v=i.child;v!==null;)d|=v.lanes|v.childLanes,h|=v.subtreeFlags,h|=v.flags,v.return=i,v=v.sibling;return i.subtreeFlags|=h,i.childLanes=d,a}function Ph(i,a,d){var h=a.pendingProps;switch(Td(a),a.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return ws(a),null;case 1:return os(a.type)&&Qc(),ws(a),null;case 3:return h=a.stateNode,qt(),Sn(Us),Sn(Es),ut(),h.pendingContext&&(h.context=h.pendingContext,h.pendingContext=null),(i===null||i.child===null)&&(nu(a)?a.flags|=4:i===null||i.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,ii!==null&&(ya(ii),ii=null))),Jd(i,a),ws(a),null;case 5:Jl(a);var v=Si(Yl.current);if(d=a.type,i!==null&&a.stateNode!=null)Xd(i,a,d,h,v),i.ref!==a.ref&&(a.flags|=512,a.flags|=2097152);else{if(!h){if(a.stateNode===null)throw Error(n(166));return ws(a),null}if(i=Si(oi.current),nu(a)){h=a.stateNode,d=a.type;var b=a.memoizedProps;switch(h[Br]=a,h[Pl]=b,i=(a.mode&1)!==0,d){case"dialog":Cn("cancel",h),Cn("close",h);break;case"iframe":case"object":case"embed":Cn("load",h);break;case"video":case"audio":for(v=0;v<Ll.length;v++)Cn(Ll[v],h);break;case"source":Cn("error",h);break;case"img":case"image":case"link":Cn("error",h),Cn("load",h);break;case"details":Cn("toggle",h);break;case"input":lt(h,b),Cn("invalid",h);break;case"select":h._wrapperState={wasMultiple:!!b.multiple},Cn("invalid",h);break;case"textarea":Ft(h,b),Cn("invalid",h)}_n(d,b),v=null;for(var I in b)if(b.hasOwnProperty(I)){var ee=b[I];I==="children"?typeof ee=="string"?h.textContent!==ee&&(b.suppressHydrationWarning!==!0&&go(h.textContent,ee,i),v=["children",ee]):typeof ee=="number"&&h.textContent!==""+ee&&(b.suppressHydrationWarning!==!0&&go(h.textContent,ee,i),v=["children",""+ee]):o.hasOwnProperty(I)&&ee!=null&&I==="onScroll"&&Cn("scroll",h)}switch(d){case"input":Be(h),Re(h,b,!0);break;case"textarea":Be(h),yn(h);break;case"select":case"option":break;default:typeof b.onClick=="function"&&(h.onclick=Bi)}h=v,a.updateQueue=h,h!==null&&(a.flags|=4)}else{I=v.nodeType===9?v:v.ownerDocument,i==="http://www.w3.org/1999/xhtml"&&(i=Ut(d)),i==="http://www.w3.org/1999/xhtml"?d==="script"?(i=I.createElement("div"),i.innerHTML="<script><\/script>",i=i.removeChild(i.firstChild)):typeof h.is=="string"?i=I.createElement(d,{is:h.is}):(i=I.createElement(d),d==="select"&&(I=i,h.multiple?I.multiple=!0:h.size&&(I.size=h.size))):i=I.createElementNS(i,d),i[Br]=a,i[Pl]=h,Oh(i,a,!1,!1),a.stateNode=i;e:{switch(I=js(d,h),d){case"dialog":Cn("cancel",i),Cn("close",i),v=h;break;case"iframe":case"object":case"embed":Cn("load",i),v=h;break;case"video":case"audio":for(v=0;v<Ll.length;v++)Cn(Ll[v],i);v=h;break;case"source":Cn("error",i),v=h;break;case"img":case"image":case"link":Cn("error",i),Cn("load",i),v=h;break;case"details":Cn("toggle",i),v=h;break;case"input":lt(i,h),v=tt(i,h),Cn("invalid",i);break;case"option":v=h;break;case"select":i._wrapperState={wasMultiple:!!h.multiple},v=K({},h,{value:void 0}),Cn("invalid",i);break;case"textarea":Ft(i,h),v=Ue(i,h),Cn("invalid",i);break;default:v=h}_n(d,v),ee=v;for(b in ee)if(ee.hasOwnProperty(b)){var se=ee[b];b==="style"?hn(i,se):b==="dangerouslySetInnerHTML"?(se=se?se.__html:void 0,se!=null&&ns(i,se)):b==="children"?typeof se=="string"?(d!=="textarea"||se!=="")&&$t(i,se):typeof se=="number"&&$t(i,""+se):b!=="suppressContentEditableWarning"&&b!=="suppressHydrationWarning"&&b!=="autoFocus"&&(o.hasOwnProperty(b)?se!=null&&b==="onScroll"&&Cn("scroll",i):se!=null&&L(i,b,se,I))}switch(d){case"input":Be(i),Re(i,h,!1);break;case"textarea":Be(i),yn(i);break;case"option":h.value!=null&&i.setAttribute("value",""+ye(h.value));break;case"select":i.multiple=!!h.multiple,b=h.value,b!=null?Le(i,!!h.multiple,b,!1):h.defaultValue!=null&&Le(i,!!h.multiple,h.defaultValue,!0);break;default:typeof v.onClick=="function"&&(i.onclick=Bi)}switch(d){case"button":case"input":case"select":case"textarea":h=!!h.autoFocus;break e;case"img":h=!0;break e;default:h=!1}}h&&(a.flags|=4)}a.ref!==null&&(a.flags|=512,a.flags|=2097152)}return ws(a),null;case 6:if(i&&a.stateNode!=null)Eo(i,a,i.memoizedProps,h);else{if(typeof h!="string"&&a.stateNode===null)throw Error(n(166));if(d=Si(Yl.current),Si(oi.current),nu(a)){if(h=a.stateNode,d=a.memoizedProps,h[Br]=a,(b=h.nodeValue!==d)&&(i=Ws,i!==null))switch(i.tag){case 3:go(h.nodeValue,d,(i.mode&1)!==0);break;case 5:i.memoizedProps.suppressHydrationWarning!==!0&&go(h.nodeValue,d,(i.mode&1)!==0)}b&&(a.flags|=4)}else h=(d.nodeType===9?d:d.ownerDocument).createTextNode(h),h[Br]=a,a.stateNode=h}return ws(a),null;case 13:if(Sn(Tn),h=a.memoizedState,i===null||i.memoizedState!==null&&i.memoizedState.dehydrated!==null){if(An&&lr!==null&&(a.mode&1)!==0&&(a.flags&128)===0)su(),Ka(),a.flags|=98560,b=!1;else if(b=nu(a),h!==null&&h.dehydrated!==null){if(i===null){if(!b)throw Error(n(318));if(b=a.memoizedState,b=b!==null?b.dehydrated:null,!b)throw Error(n(317));b[Br]=a}else Ka(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;ws(a),b=!1}else ii!==null&&(ya(ii),ii=null),b=!0;if(!b)return a.flags&65536?a:null}return(a.flags&128)!==0?(a.lanes=d,a):(h=h!==null,h!==(i!==null&&i.memoizedState!==null)&&h&&(a.child.flags|=8192,(a.mode&1)!==0&&(i===null||(Tn.current&1)!==0?Ln===0&&(Ln=3):Au())),a.updateQueue!==null&&(a.flags|=4),ws(a),null);case 4:return qt(),Jd(i,a),i===null&&Zo(a.stateNode.containerInfo),ws(a),null;case 10:return Id(a.type._context),ws(a),null;case 17:return os(a.type)&&Qc(),ws(a),null;case 19:if(Sn(Tn),b=a.memoizedState,b===null)return ws(a),null;if(h=(a.flags&128)!==0,I=b.rendering,I===null)if(h)Xi(b,!1);else{if(Ln!==0||i!==null&&(i.flags&128)!==0)for(i=a.child;i!==null;){if(I=ko(i),I!==null){for(a.flags|=128,Xi(b,!1),h=I.updateQueue,h!==null&&(a.updateQueue=h,a.flags|=4),a.subtreeFlags=0,h=d,d=a.child;d!==null;)b=d,i=h,b.flags&=14680066,I=b.alternate,I===null?(b.childLanes=0,b.lanes=i,b.child=null,b.subtreeFlags=0,b.memoizedProps=null,b.memoizedState=null,b.updateQueue=null,b.dependencies=null,b.stateNode=null):(b.childLanes=I.childLanes,b.lanes=I.lanes,b.child=I.child,b.subtreeFlags=0,b.deletions=null,b.memoizedProps=I.memoizedProps,b.memoizedState=I.memoizedState,b.updateQueue=I.updateQueue,b.type=I.type,i=I.dependencies,b.dependencies=i===null?null:{lanes:i.lanes,firstContext:i.firstContext}),d=d.sibling;return kn(Tn,Tn.current&1|2),a.child}i=i.sibling}b.tail!==null&&de()>Ci&&(a.flags|=128,h=!0,Xi(b,!1),a.lanes=4194304)}else{if(!h)if(i=ko(I),i!==null){if(a.flags|=128,h=!0,d=i.updateQueue,d!==null&&(a.updateQueue=d,a.flags|=4),Xi(b,!0),b.tail===null&&b.tailMode==="hidden"&&!I.alternate&&!An)return ws(a),null}else 2*de()-b.renderingStartTime>Ci&&d!==1073741824&&(a.flags|=128,h=!0,Xi(b,!1),a.lanes=4194304);b.isBackwards?(I.sibling=a.child,a.child=I):(d=b.last,d!==null?d.sibling=I:a.child=I,b.last=I)}return b.tail!==null?(a=b.tail,b.rendering=a,b.tail=a.sibling,b.renderingStartTime=de(),a.sibling=null,d=Tn.current,kn(Tn,h?d&1|2:d&1),a):(ws(a),null);case 22:case 23:return $u(),h=a.memoizedState!==null,i!==null&&i.memoizedState!==null!==h&&(a.flags|=8192),h&&(a.mode&1)!==0?(Ks&1073741824)!==0&&(ws(a),a.subtreeFlags&6&&(a.flags|=8192)):ws(a),null;case 24:return null;case 25:return null}throw Error(n(156,a.tag))}function $_(i,a){switch(Td(a),a.tag){case 1:return os(a.type)&&Qc(),i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 3:return qt(),Sn(Us),Sn(Es),ut(),i=a.flags,(i&65536)!==0&&(i&128)===0?(a.flags=i&-65537|128,a):null;case 5:return Jl(a),null;case 13:if(Sn(Tn),i=a.memoizedState,i!==null&&i.dehydrated!==null){if(a.alternate===null)throw Error(n(340));Ka()}return i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 19:return Sn(Tn),null;case 4:return qt(),null;case 10:return Id(a.type._context),null;case 22:case 23:return $u(),null;case 24:return null;default:return null}}var rc=!1,Vn=!1,A_=typeof WeakSet=="function"?WeakSet:Set,Ge=null;function pa(i,a){var d=i.ref;if(d!==null)if(typeof d=="function")try{d(null)}catch(h){Bn(i,a,h)}else d.current=null}function Zd(i,a,d){try{d()}catch(h){Bn(i,a,h)}}var Su=!1;function T_(i,a){if(xi=qo,i=Wc(),xd(i)){if("selectionStart"in i)var d={start:i.selectionStart,end:i.selectionEnd};else e:{d=(d=i.ownerDocument)&&d.defaultView||window;var h=d.getSelection&&d.getSelection();if(h&&h.rangeCount!==0){d=h.anchorNode;var v=h.anchorOffset,b=h.focusNode;h=h.focusOffset;try{d.nodeType,b.nodeType}catch{d=null;break e}var I=0,ee=-1,se=-1,we=0,Te=0,Me=i,$e=null;t:for(;;){for(var Ze;Me!==d||v!==0&&Me.nodeType!==3||(ee=I+v),Me!==b||h!==0&&Me.nodeType!==3||(se=I+h),Me.nodeType===3&&(I+=Me.nodeValue.length),(Ze=Me.firstChild)!==null;)$e=Me,Me=Ze;for(;;){if(Me===i)break t;if($e===d&&++we===v&&(ee=I),$e===b&&++Te===h&&(se=I),(Ze=Me.nextSibling)!==null)break;Me=$e,$e=Me.parentNode}Me=Ze}d=ee===-1||se===-1?null:{start:ee,end:se}}else d=null}d=d||{start:0,end:0}}else d=null;for(Cs={focusedElem:i,selectionRange:d},qo=!1,Ge=a;Ge!==null;)if(a=Ge,i=a.child,(a.subtreeFlags&1028)!==0&&i!==null)i.return=a,Ge=i;else for(;Ge!==null;){a=Ge;try{var nt=a.alternate;if((a.flags&1024)!==0)switch(a.tag){case 0:case 11:case 15:break;case 1:if(nt!==null){var st=nt.memoizedProps,ts=nt.memoizedState,fe=a.stateNode,oe=fe.getSnapshotBeforeUpdate(a.elementType===a.type?st:Cr(a.type,st),ts);fe.__reactInternalSnapshotBeforeUpdate=oe}break;case 3:var pe=a.stateNode.containerInfo;pe.nodeType===1?pe.textContent="":pe.nodeType===9&&pe.documentElement&&pe.removeChild(pe.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(Pe){Bn(a,a.return,Pe)}if(i=a.sibling,i!==null){i.return=a.return,Ge=i;break}Ge=a.return}return nt=Su,Su=!1,nt}function ic(i,a,d){var h=a.updateQueue;if(h=h!==null?h.lastEffect:null,h!==null){var v=h=h.next;do{if((v.tag&i)===i){var b=v.destroy;v.destroy=void 0,b!==void 0&&Zd(a,d,b)}v=v.next}while(v!==h)}}function ku(i,a){if(a=a.updateQueue,a=a!==null?a.lastEffect:null,a!==null){var d=a=a.next;do{if((d.tag&i)===i){var h=d.create;d.destroy=h()}d=d.next}while(d!==a)}}function Vs(i){var a=i.ref;if(a!==null){var d=i.stateNode;switch(i.tag){case 5:i=d;break;default:i=d}typeof a=="function"?a(i):a.current=i}}function ga(i){var a=i.alternate;a!==null&&(i.alternate=null,ga(a)),i.child=null,i.deletions=null,i.sibling=null,i.tag===5&&(a=i.stateNode,a!==null&&(delete a[Br],delete a[Pl],delete a[Zc],delete a[Dl],delete a[dh])),i.stateNode=null,i.return=null,i.dependencies=null,i.memoizedProps=null,i.memoizedState=null,i.pendingProps=null,i.stateNode=null,i.updateQueue=null}function Dh(i){return i.tag===5||i.tag===3||i.tag===4}function Qd(i){e:for(;;){for(;i.sibling===null;){if(i.return===null||Dh(i.return))return null;i=i.return}for(i.sibling.return=i.return,i=i.sibling;i.tag!==5&&i.tag!==6&&i.tag!==18;){if(i.flags&2||i.child===null||i.tag===4)continue e;i.child.return=i,i=i.child}if(!(i.flags&2))return i.stateNode}}function Gs(i,a,d){var h=i.tag;if(h===5||h===6)i=i.stateNode,a?d.nodeType===8?d.parentNode.insertBefore(i,a):d.insertBefore(i,a):(d.nodeType===8?(a=d.parentNode,a.insertBefore(i,d)):(a=d,a.appendChild(i)),d=d._reactRootContainer,d!=null||a.onclick!==null||(a.onclick=Bi));else if(h!==4&&(i=i.child,i!==null))for(Gs(i,a,d),i=i.sibling;i!==null;)Gs(i,a,d),i=i.sibling}function oc(i,a,d){var h=i.tag;if(h===5||h===6)i=i.stateNode,a?d.insertBefore(i,a):d.appendChild(i);else if(h!==4&&(i=i.child,i!==null))for(oc(i,a,d),i=i.sibling;i!==null;)oc(i,a,d),i=i.sibling}var ls=null,Hr=!1;function $o(i,a,d){for(d=d.child;d!==null;)Fh(i,a,d),d=d.sibling}function Fh(i,a,d){if(Fs&&typeof Fs.onCommitFiberUnmount=="function")try{Fs.onCommitFiberUnmount(on,d)}catch{}switch(d.tag){case 5:Vn||pa(d,a);case 6:var h=ls,v=Hr;ls=null,$o(i,a,d),ls=h,Hr=v,ls!==null&&(Hr?(i=ls,d=d.stateNode,i.nodeType===8?i.parentNode.removeChild(d):i.removeChild(d)):ls.removeChild(d.stateNode));break;case 18:ls!==null&&(Hr?(i=ls,d=d.stateNode,i.nodeType===8?zr(i.parentNode,d):i.nodeType===1&&zr(i,d),_o(i)):zr(ls,d.stateNode));break;case 4:h=ls,v=Hr,ls=d.stateNode.containerInfo,Hr=!0,$o(i,a,d),ls=h,Hr=v;break;case 0:case 11:case 14:case 15:if(!Vn&&(h=d.updateQueue,h!==null&&(h=h.lastEffect,h!==null))){v=h=h.next;do{var b=v,I=b.destroy;b=b.tag,I!==void 0&&((b&2)!==0||(b&4)!==0)&&Zd(d,a,I),v=v.next}while(v!==h)}$o(i,a,d);break;case 1:if(!Vn&&(pa(d,a),h=d.stateNode,typeof h.componentWillUnmount=="function"))try{h.props=d.memoizedProps,h.state=d.memoizedState,h.componentWillUnmount()}catch(ee){Bn(d,a,ee)}$o(i,a,d);break;case 21:$o(i,a,d);break;case 22:d.mode&1?(Vn=(h=Vn)||d.memoizedState!==null,$o(i,a,d),Vn=h):$o(i,a,d);break;default:$o(i,a,d)}}function zh(i){var a=i.updateQueue;if(a!==null){i.updateQueue=null;var d=i.stateNode;d===null&&(d=i.stateNode=new A_),a.forEach(function(h){var v=M.bind(null,i,h);d.has(h)||(d.add(h),h.then(v,v))})}}function zn(i,a){var d=a.deletions;if(d!==null)for(var h=0;h<d.length;h++){var v=d[h];try{var b=i,I=a,ee=I;e:for(;ee!==null;){switch(ee.tag){case 5:ls=ee.stateNode,Hr=!1;break e;case 3:ls=ee.stateNode.containerInfo,Hr=!0;break e;case 4:ls=ee.stateNode.containerInfo,Hr=!0;break e}ee=ee.return}if(ls===null)throw Error(n(160));Fh(b,I,v),ls=null,Hr=!1;var se=v.alternate;se!==null&&(se.return=null),v.return=null}catch(we){Bn(v,a,we)}}if(a.subtreeFlags&12854)for(a=a.child;a!==null;)sl(a,i),a=a.sibling}function sl(i,a){var d=i.alternate,h=i.flags;switch(i.tag){case 0:case 11:case 14:case 15:if(zn(a,i),ai(i),h&4){try{ic(3,i,i.return),ku(3,i)}catch(st){Bn(i,i.return,st)}try{ic(5,i,i.return)}catch(st){Bn(i,i.return,st)}}break;case 1:zn(a,i),ai(i),h&512&&d!==null&&pa(d,d.return);break;case 5:if(zn(a,i),ai(i),h&512&&d!==null&&pa(d,d.return),i.flags&32){var v=i.stateNode;try{$t(v,"")}catch(st){Bn(i,i.return,st)}}if(h&4&&(v=i.stateNode,v!=null)){var b=i.memoizedProps,I=d!==null?d.memoizedProps:b,ee=i.type,se=i.updateQueue;if(i.updateQueue=null,se!==null)try{ee==="input"&&b.type==="radio"&&b.name!=null&&Ye(v,b),js(ee,I);var we=js(ee,b);for(I=0;I<se.length;I+=2){var Te=se[I],Me=se[I+1];Te==="style"?hn(v,Me):Te==="dangerouslySetInnerHTML"?ns(v,Me):Te==="children"?$t(v,Me):L(v,Te,Me,we)}switch(ee){case"input":Se(v,b);break;case"textarea":Qt(v,b);break;case"select":var $e=v._wrapperState.wasMultiple;v._wrapperState.wasMultiple=!!b.multiple;var Ze=b.value;Ze!=null?Le(v,!!b.multiple,Ze,!1):$e!==!!b.multiple&&(b.defaultValue!=null?Le(v,!!b.multiple,b.defaultValue,!0):Le(v,!!b.multiple,b.multiple?[]:"",!1))}v[Pl]=b}catch(st){Bn(i,i.return,st)}}break;case 6:if(zn(a,i),ai(i),h&4){if(i.stateNode===null)throw Error(n(162));v=i.stateNode,b=i.memoizedProps;try{v.nodeValue=b}catch(st){Bn(i,i.return,st)}}break;case 3:if(zn(a,i),ai(i),h&4&&d!==null&&d.memoizedState.isDehydrated)try{_o(a.containerInfo)}catch(st){Bn(i,i.return,st)}break;case 4:zn(a,i),ai(i);break;case 13:zn(a,i),ai(i),v=i.child,v.flags&8192&&(b=v.memoizedState!==null,v.stateNode.isHidden=b,!b||v.alternate!==null&&v.alternate.memoizedState!==null||(dc=de())),h&4&&zh(i);break;case 22:if(Te=d!==null&&d.memoizedState!==null,i.mode&1?(Vn=(we=Vn)||Te,zn(a,i),Vn=we):zn(a,i),ai(i),h&8192){if(we=i.memoizedState!==null,(i.stateNode.isHidden=we)&&!Te&&(i.mode&1)!==0)for(Ge=i,Te=i.child;Te!==null;){for(Me=Ge=Te;Ge!==null;){switch($e=Ge,Ze=$e.child,$e.tag){case 0:case 11:case 14:case 15:ic(4,$e,$e.return);break;case 1:pa($e,$e.return);var nt=$e.stateNode;if(typeof nt.componentWillUnmount=="function"){h=$e,d=$e.return;try{a=h,nt.props=a.memoizedProps,nt.state=a.memoizedState,nt.componentWillUnmount()}catch(st){Bn(h,d,st)}}break;case 5:pa($e,$e.return);break;case 22:if($e.memoizedState!==null){Ni(Me);continue}}Ze!==null?(Ze.return=$e,Ge=Ze):Ni(Me)}Te=Te.sibling}e:for(Te=null,Me=i;;){if(Me.tag===5){if(Te===null){Te=Me;try{v=Me.stateNode,we?(b=v.style,typeof b.setProperty=="function"?b.setProperty("display","none","important"):b.display="none"):(ee=Me.stateNode,se=Me.memoizedProps.style,I=se!=null&&se.hasOwnProperty("display")?se.display:null,ee.style.display=En("display",I))}catch(st){Bn(i,i.return,st)}}}else if(Me.tag===6){if(Te===null)try{Me.stateNode.nodeValue=we?"":Me.memoizedProps}catch(st){Bn(i,i.return,st)}}else if((Me.tag!==22&&Me.tag!==23||Me.memoizedState===null||Me===i)&&Me.child!==null){Me.child.return=Me,Me=Me.child;continue}if(Me===i)break e;for(;Me.sibling===null;){if(Me.return===null||Me.return===i)break e;Te===Me&&(Te=null),Me=Me.return}Te===Me&&(Te=null),Me.sibling.return=Me.return,Me=Me.sibling}}break;case 19:zn(a,i),ai(i),h&4&&zh(i);break;case 21:break;default:zn(a,i),ai(i)}}function ai(i){var a=i.flags;if(a&2){try{e:{for(var d=i.return;d!==null;){if(Dh(d)){var h=d;break e}d=d.return}throw Error(n(160))}switch(h.tag){case 5:var v=h.stateNode;h.flags&32&&($t(v,""),h.flags&=-33);var b=Qd(i);oc(i,b,v);break;case 3:case 4:var I=h.stateNode.containerInfo,ee=Qd(i);Gs(i,ee,I);break;default:throw Error(n(161))}}catch(se){Bn(i,i.return,se)}i.flags&=-3}a&4096&&(i.flags&=-4097)}function Bh(i,a,d){Ge=i,Uh(i)}function Uh(i,a,d){for(var h=(i.mode&1)!==0;Ge!==null;){var v=Ge,b=v.child;if(v.tag===22&&h){var I=v.memoizedState!==null||rc;if(!I){var ee=v.alternate,se=ee!==null&&ee.memoizedState!==null||Vn;ee=rc;var we=Vn;if(rc=I,(Vn=se)&&!we)for(Ge=v;Ge!==null;)I=Ge,se=I.child,I.tag===22&&I.memoizedState!==null?Wh(v):se!==null?(se.return=I,Ge=se):Wh(v);for(;b!==null;)Ge=b,Uh(b),b=b.sibling;Ge=v,rc=ee,Vn=we}ef(i)}else(v.subtreeFlags&8772)!==0&&b!==null?(b.return=v,Ge=b):ef(i)}}function ef(i){for(;Ge!==null;){var a=Ge;if((a.flags&8772)!==0){var d=a.alternate;try{if((a.flags&8772)!==0)switch(a.tag){case 0:case 11:case 15:Vn||ku(5,a);break;case 1:var h=a.stateNode;if(a.flags&4&&!Vn)if(d===null)h.componentDidMount();else{var v=a.elementType===a.type?d.memoizedProps:Cr(a.type,d.memoizedProps);h.componentDidUpdate(v,d.memoizedState,h.__reactInternalSnapshotBeforeUpdate)}var b=a.updateQueue;b!==null&&gh(a,b,h);break;case 3:var I=a.updateQueue;if(I!==null){if(d=null,a.child!==null)switch(a.child.tag){case 5:d=a.child.stateNode;break;case 1:d=a.child.stateNode}gh(a,I,d)}break;case 5:var ee=a.stateNode;if(d===null&&a.flags&4){d=ee;var se=a.memoizedProps;switch(a.type){case"button":case"input":case"select":case"textarea":se.autoFocus&&d.focus();break;case"img":se.src&&(d.src=se.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(a.memoizedState===null){var we=a.alternate;if(we!==null){var Te=we.memoizedState;if(Te!==null){var Me=Te.dehydrated;Me!==null&&_o(Me)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}Vn||a.flags&512&&Vs(a)}catch($e){Bn(a,a.return,$e)}}if(a===i){Ge=null;break}if(d=a.sibling,d!==null){d.return=a.return,Ge=d;break}Ge=a.return}}function Ni(i){for(;Ge!==null;){var a=Ge;if(a===i){Ge=null;break}var d=a.sibling;if(d!==null){d.return=a.return,Ge=d;break}Ge=a.return}}function Wh(i){for(;Ge!==null;){var a=Ge;try{switch(a.tag){case 0:case 11:case 15:var d=a.return;try{ku(4,a)}catch(se){Bn(a,d,se)}break;case 1:var h=a.stateNode;if(typeof h.componentDidMount=="function"){var v=a.return;try{h.componentDidMount()}catch(se){Bn(a,v,se)}}var b=a.return;try{Vs(a)}catch(se){Bn(a,b,se)}break;case 5:var I=a.return;try{Vs(a)}catch(se){Bn(a,I,se)}}}catch(se){Bn(a,a.return,se)}if(a===i){Ge=null;break}var ee=a.sibling;if(ee!==null){ee.return=a.return,Ge=ee;break}Ge=a.return}}var M_=Math.ceil,ac=P.ReactCurrentDispatcher,lc=P.ReactCurrentOwner,Gn=P.ReactCurrentBatchConfig,Ht=0,cs=null,vn=null,es=0,Ks=0,Rn=vo(0),Ln=0,cc=null,Ao=0,uc=0,Nu=0,rl=null,Ys=null,dc=0,Ci=1/0,Vr=null,fc=!1,Cu=null,Zi=null,li=!1,To=null,Eu=0,hc=0,Qi=null,il=-1,ol=0;function Ls(){return(Ht&6)!==0?de():il!==-1?il:il=de()}function eo(i){return(i.mode&1)===0?1:(Ht&2)!==0&&es!==0?es&-es:mh.transition!==null?(ol===0&&(ol=fs()),ol):(i=rn,i!==0||(i=window.event,i=i===void 0?16:be(i.type)),i)}function ci(i,a,d,h){if(50<hc)throw hc=0,Qi=null,Error(n(185));hs(i,d,h),((Ht&2)===0||i!==cs)&&(i===cs&&((Ht&2)===0&&(uc|=d),Ln===4&&ui(i,es)),us(i,h),d===1&&Ht===0&&(a.mode&1)===0&&(Ci=de()+500,tu&&xo()))}function us(i,a){var d=i.callbackNode;$n(i,a);var h=uo(i,i===cs?es:0);if(h===0)d!==null&&hi(d),i.callbackNode=null,i.callbackPriority=0;else if(a=h&-h,i.callbackPriority!==a){if(d!=null&&hi(d),a===1)i.tag===0?Ha(mc.bind(null,i)):fh(mc.bind(null,i)),Ed(function(){(Ht&6)===0&&xo()}),d=null;else{switch(Ra(h)){case 1:d=co;break;case 4:d=gr;break;case 16:d=Rr;break;case 536870912:d=it;break;default:d=Rr}d=V(d,Mo.bind(null,i))}i.callbackPriority=a,i.callbackNode=d}}function Mo(i,a){if(il=-1,ol=0,(Ht&6)!==0)throw Error(n(327));var d=i.callbackNode;if(va()&&i.callbackNode!==d)return null;var h=uo(i,i===cs?es:0);if(h===0)return null;if((h&30)!==0||(h&i.expiredLanes)!==0||a)a=_c(i,h);else{a=h;var v=Ht;Ht|=2;var b=sf();(cs!==i||es!==a)&&(Vr=null,Ci=de()+500,Ro(i,a));do try{Vh();break}catch(ee){qh(i,ee)}while(!0);Ld(),ac.current=b,Ht=v,vn!==null?a=0:(cs=null,es=0,a=Ln)}if(a!==0){if(a===2&&(v=zs(i),v!==0&&(h=v,a=tf(i,v))),a===1)throw d=cc,Ro(i,0),ui(i,h),us(i,de()),d;if(a===6)ui(i,h);else{if(v=i.current.alternate,(h&30)===0&&!R_(v)&&(a=_c(i,h),a===2&&(b=zs(i),b!==0&&(h=b,a=tf(i,b))),a===1))throw d=cc,Ro(i,0),ui(i,h),us(i,de()),d;switch(i.finishedWork=v,i.finishedLanes=h,a){case 0:case 1:throw Error(n(345));case 2:Lo(i,Ys,Vr);break;case 3:if(ui(i,h),(h&130023424)===h&&(a=dc+500-de(),10<a)){if(uo(i,0)!==0)break;if(v=i.suspendedLanes,(v&h)!==h){Ls(),i.pingedLanes|=i.suspendedLanes&v;break}i.timeoutHandle=yo(Lo.bind(null,i,Ys,Vr),a);break}Lo(i,Ys,Vr);break;case 4:if(ui(i,h),(h&4194240)===h)break;for(a=i.eventTimes,v=-1;0<h;){var I=31-rs(h);b=1<<I,I=a[I],I>v&&(v=I),h&=~b}if(h=v,h=de()-h,h=(120>h?120:480>h?480:1080>h?1080:1920>h?1920:3e3>h?3e3:4320>h?4320:1960*M_(h/1960))-h,10<h){i.timeoutHandle=yo(Lo.bind(null,i,Ys,Vr),h);break}Lo(i,Ys,Vr);break;case 5:Lo(i,Ys,Vr);break;default:throw Error(n(329))}}}return us(i,de()),i.callbackNode===d?Mo.bind(null,i):null}function tf(i,a){var d=rl;return i.current.memoizedState.isDehydrated&&(Ro(i,a).flags|=256),i=_c(i,a),i!==2&&(a=Ys,Ys=d,a!==null&&ya(a)),i}function ya(i){Ys===null?Ys=i:Ys.push.apply(Ys,i)}function R_(i){for(var a=i;;){if(a.flags&16384){var d=a.updateQueue;if(d!==null&&(d=d.stores,d!==null))for(var h=0;h<d.length;h++){var v=d[h],b=v.getSnapshot;v=v.value;try{if(!ei(b(),v))return!1}catch{return!1}}}if(d=a.child,a.subtreeFlags&16384&&d!==null)d.return=a,a=d;else{if(a===i)break;for(;a.sibling===null;){if(a.return===null||a.return===i)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function ui(i,a){for(a&=~Nu,a&=~uc,i.suspendedLanes|=a,i.pingedLanes&=~a,i=i.expirationTimes;0<a;){var d=31-rs(a),h=1<<d;i[d]=-1,a&=~h}}function mc(i){if((Ht&6)!==0)throw Error(n(327));va();var a=uo(i,0);if((a&1)===0)return us(i,de()),null;var d=_c(i,a);if(i.tag!==0&&d===2){var h=zs(i);h!==0&&(a=h,d=tf(i,h))}if(d===1)throw d=cc,Ro(i,0),ui(i,a),us(i,de()),d;if(d===6)throw Error(n(345));return i.finishedWork=i.current.alternate,i.finishedLanes=a,Lo(i,Ys,Vr),us(i,de()),null}function nf(i,a){var d=Ht;Ht|=1;try{return i(a)}finally{Ht=d,Ht===0&&(Ci=de()+500,tu&&xo())}}function wa(i){To!==null&&To.tag===0&&(Ht&6)===0&&va();var a=Ht;Ht|=1;var d=Gn.transition,h=rn;try{if(Gn.transition=null,rn=1,i)return i()}finally{rn=h,Gn.transition=d,Ht=a,(Ht&6)===0&&xo()}}function $u(){Ks=Rn.current,Sn(Rn)}function Ro(i,a){i.finishedWork=null,i.finishedLanes=0;var d=i.timeoutHandle;if(d!==-1&&(i.timeoutHandle=-1,Jc(d)),vn!==null)for(d=vn.return;d!==null;){var h=d;switch(Td(h),h.tag){case 1:h=h.type.childContextTypes,h!=null&&Qc();break;case 3:qt(),Sn(Us),Sn(Es),ut();break;case 5:Jl(h);break;case 4:qt();break;case 13:Sn(Tn);break;case 19:Sn(Tn);break;case 10:Id(h.type._context);break;case 22:case 23:$u()}d=d.return}if(cs=i,vn=i=me(i.current,null),es=Ks=a,Ln=0,cc=null,Nu=uc=Ao=0,Ys=rl=null,ua!==null){for(a=0;a<ua.length;a++)if(d=ua[a],h=d.interleaved,h!==null){d.interleaved=null;var v=h.next,b=d.pending;if(b!==null){var I=b.next;b.next=v,h.next=I}d.pending=h}ua=null}return i}function qh(i,a){do{var d=vn;try{if(Ld(),lu.current=wu,cu){for(var h=Fn.memoizedState;h!==null;){var v=h.queue;v!==null&&(v.pending=null),h=h.next}cu=!1}if(da=0,as=Jn=Fn=null,Zl=!1,fa=0,lc.current=null,d===null||d.return===null){Ln=1,cc=a,vn=null;break}e:{var b=i,I=d.return,ee=d,se=a;if(a=es,ee.flags|=32768,se!==null&&typeof se=="object"&&typeof se.then=="function"){var we=se,Te=ee,Me=Te.tag;if((Te.mode&1)===0&&(Me===0||Me===11||Me===15)){var $e=Te.alternate;$e?(Te.updateQueue=$e.updateQueue,Te.memoizedState=$e.memoizedState,Te.lanes=$e.lanes):(Te.updateQueue=null,Te.memoizedState=null)}var Ze=Vd(I);if(Ze!==null){Ze.flags&=-257,xu(Ze,I,ee,b,a),Ze.mode&1&&vu(b,we,a),a=Ze,se=we;var nt=a.updateQueue;if(nt===null){var st=new Set;st.add(se),a.updateQueue=st}else nt.add(se);break e}else{if((a&1)===0){vu(b,we,a),Au();break e}se=Error(n(426))}}else if(An&&ee.mode&1){var ts=Vd(I);if(ts!==null){(ts.flags&65536)===0&&(ts.flags|=256),xu(ts,I,ee,b,a),Ya(nl(se,ee));break e}}b=se=nl(se,ee),Ln!==4&&(Ln=2),rl===null?rl=[b]:rl.push(b),b=I;do{switch(b.tag){case 3:b.flags|=65536,a&=-a,b.lanes|=a;var fe=Hd(b,se,a);iu(b,fe);break e;case 1:ee=se;var oe=b.type,pe=b.stateNode;if((b.flags&128)===0&&(typeof oe.getDerivedStateFromError=="function"||pe!==null&&typeof pe.componentDidCatch=="function"&&(Zi===null||!Zi.has(pe)))){b.flags|=65536,a&=-a,b.lanes|=a;var Pe=No(b,ee,a);iu(b,Pe);break e}}b=b.return}while(b!==null)}of(d)}catch(at){a=at,vn===d&&d!==null&&(vn=d=d.return);continue}break}while(!0)}function sf(){var i=ac.current;return ac.current=wu,i===null?wu:i}function Au(){(Ln===0||Ln===3||Ln===2)&&(Ln=4),cs===null||(Ao&268435455)===0&&(uc&268435455)===0||ui(cs,es)}function _c(i,a){var d=Ht;Ht|=2;var h=sf();(cs!==i||es!==a)&&(Vr=null,Ro(i,a));do try{Hh();break}catch(v){qh(i,v)}while(!0);if(Ld(),Ht=d,ac.current=h,vn!==null)throw Error(n(261));return cs=null,es=0,Ln}function Hh(){for(;vn!==null;)rf(vn)}function Vh(){for(;vn!==null&&!mi();)rf(vn)}function rf(i){var a=D(i.alternate,i,Ks);i.memoizedProps=i.pendingProps,a===null?of(i):vn=a,lc.current=null}function of(i){var a=i;do{var d=a.alternate;if(i=a.return,(a.flags&32768)===0){if(d=Ph(d,a,Ks),d!==null){vn=d;return}}else{if(d=$_(d,a),d!==null){d.flags&=32767,vn=d;return}if(i!==null)i.flags|=32768,i.subtreeFlags=0,i.deletions=null;else{Ln=6,vn=null;return}}if(a=a.sibling,a!==null){vn=a;return}vn=a=i}while(a!==null);Ln===0&&(Ln=5)}function Lo(i,a,d){var h=rn,v=Gn.transition;try{Gn.transition=null,rn=1,Gh(i,a,d,h)}finally{Gn.transition=v,rn=h}return null}function Gh(i,a,d,h){do va();while(To!==null);if((Ht&6)!==0)throw Error(n(327));d=i.finishedWork;var v=i.finishedLanes;if(d===null)return null;if(i.finishedWork=null,i.finishedLanes=0,d===i.current)throw Error(n(177));i.callbackNode=null,i.callbackPriority=0;var b=d.lanes|d.childLanes;if(Ma(i,b),i===cs&&(vn=cs=null,es=0),(d.subtreeFlags&2064)===0&&(d.flags&2064)===0||li||(li=!0,V(Rr,function(){return va(),null})),b=(d.flags&15990)!==0,(d.subtreeFlags&15990)!==0||b){b=Gn.transition,Gn.transition=null;var I=rn;rn=1;var ee=Ht;Ht|=4,lc.current=null,T_(i,d),sl(d,i),bd(Cs),qo=!!xi,Cs=xi=null,i.current=d,Bh(d),Ds(),Ht=ee,rn=I,Gn.transition=b}else i.current=d;if(li&&(li=!1,To=i,Eu=v),b=i.pendingLanes,b===0&&(Zi=null),Qr(d.stateNode),us(i,de()),a!==null)for(h=i.onRecoverableError,d=0;d<a.length;d++)v=a[d],h(v.value,{componentStack:v.stack,digest:v.digest});if(fc)throw fc=!1,i=Cu,Cu=null,i;return(Eu&1)!==0&&i.tag!==0&&va(),b=i.pendingLanes,(b&1)!==0?i===Qi?hc++:(hc=0,Qi=i):hc=0,xo(),null}function va(){if(To!==null){var i=Ra(Eu),a=Gn.transition,d=rn;try{if(Gn.transition=null,rn=16>i?16:i,To===null)var h=!1;else{if(i=To,To=null,Eu=0,(Ht&6)!==0)throw Error(n(331));var v=Ht;for(Ht|=4,Ge=i.current;Ge!==null;){var b=Ge,I=b.child;if((Ge.flags&16)!==0){var ee=b.deletions;if(ee!==null){for(var se=0;se<ee.length;se++){var we=ee[se];for(Ge=we;Ge!==null;){var Te=Ge;switch(Te.tag){case 0:case 11:case 15:ic(8,Te,b)}var Me=Te.child;if(Me!==null)Me.return=Te,Ge=Me;else for(;Ge!==null;){Te=Ge;var $e=Te.sibling,Ze=Te.return;if(ga(Te),Te===we){Ge=null;break}if($e!==null){$e.return=Ze,Ge=$e;break}Ge=Ze}}}var nt=b.alternate;if(nt!==null){var st=nt.child;if(st!==null){nt.child=null;do{var ts=st.sibling;st.sibling=null,st=ts}while(st!==null)}}Ge=b}}if((b.subtreeFlags&2064)!==0&&I!==null)I.return=b,Ge=I;else e:for(;Ge!==null;){if(b=Ge,(b.flags&2048)!==0)switch(b.tag){case 0:case 11:case 15:ic(9,b,b.return)}var fe=b.sibling;if(fe!==null){fe.return=b.return,Ge=fe;break e}Ge=b.return}}var oe=i.current;for(Ge=oe;Ge!==null;){I=Ge;var pe=I.child;if((I.subtreeFlags&2064)!==0&&pe!==null)pe.return=I,Ge=pe;else e:for(I=oe;Ge!==null;){if(ee=Ge,(ee.flags&2048)!==0)try{switch(ee.tag){case 0:case 11:case 15:ku(9,ee)}}catch(at){Bn(ee,ee.return,at)}if(ee===I){Ge=null;break e}var Pe=ee.sibling;if(Pe!==null){Pe.return=ee.return,Ge=Pe;break e}Ge=ee.return}}if(Ht=v,xo(),Fs&&typeof Fs.onPostCommitFiberRoot=="function")try{Fs.onPostCommitFiberRoot(on,i)}catch{}h=!0}return h}finally{rn=d,Gn.transition=a}}return!1}function af(i,a,d){a=nl(d,a),a=Hd(i,a,1),i=ji(i,a,1),a=Ls(),i!==null&&(hs(i,1,a),us(i,a))}function Bn(i,a,d){if(i.tag===3)af(i,i,d);else for(;a!==null;){if(a.tag===3){af(a,i,d);break}else if(a.tag===1){var h=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof h.componentDidCatch=="function"&&(Zi===null||!Zi.has(h))){i=nl(d,i),i=No(a,i,1),a=ji(a,i,1),i=Ls(),a!==null&&(hs(a,1,i),us(a,i));break}}a=a.return}}function Kh(i,a,d){var h=i.pingCache;h!==null&&h.delete(a),a=Ls(),i.pingedLanes|=i.suspendedLanes&d,cs===i&&(es&d)===d&&(Ln===4||Ln===3&&(es&130023424)===es&&500>de()-dc?Ro(i,0):Nu|=d),us(i,a)}function g(i,a){a===0&&((i.mode&1)===0?a=1:(a=yr,yr<<=1,(yr&130023424)===0&&(yr=4194304)));var d=Ls();i=bi(i,a),i!==null&&(hs(i,a,d),us(i,d))}function k(i){var a=i.memoizedState,d=0;a!==null&&(d=a.retryLane),g(i,d)}function M(i,a){var d=0;switch(i.tag){case 13:var h=i.stateNode,v=i.memoizedState;v!==null&&(d=v.retryLane);break;case 19:h=i.stateNode;break;default:throw Error(n(314))}h!==null&&h.delete(a),g(i,d)}var D;D=function(i,a,d){if(i!==null)if(i.memoizedProps!==a.pendingProps||Us.current)ur=!0;else{if((i.lanes&d)===0&&(a.flags&128)===0)return ur=!1,Yd(i,a,d);ur=(i.flags&131072)!==0}else ur=!1,An&&(a.flags&1048576)!==0&&oa(a,zl,a.index);switch(a.lanes=0,a.tag){case 2:var h=a.type;_a(i,a),i=a.pendingProps;var v=ra(a,Es.current);Xa(a,d),v=Sr(null,a,h,i,v,d);var b=uu();return a.flags|=1,typeof v=="object"&&v!==null&&typeof v.render=="function"&&v.$$typeof===void 0?(a.tag=1,a.memoizedState=null,a.updateQueue=null,os(h)?(b=!0,ia(a)):b=!1,a.memoizedState=v.state!==null&&v.state!==void 0?v.state:null,Vl(a),v.updater=nc,a.stateNode=v,v._reactInternals=a,ma(a,h,i,d),a=Gd(null,a,h,!0,b,d)):(a.tag=0,An&&b&&Bl(a),Hs(null,a,v,d),a=a.child),a;case 16:h=a.elementType;e:{switch(_a(i,a),i=a.pendingProps,v=h._init,h=v(h._payload),a.type=h,v=a.tag=Ce(h),i=Cr(h,i),v){case 0:a=bu(null,a,h,i,d);break e;case 1:a=ju(null,a,h,i,d);break e;case 11:a=$h(null,a,h,i,d);break e;case 14:a=Ah(null,a,h,Cr(h.type,i),d);break e}throw Error(n(306,h,""))}return a;case 0:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Cr(h,v),bu(i,a,h,v,d);case 1:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Cr(h,v),ju(i,a,h,v,d);case 3:e:{if(Lh(a),i===null)throw Error(n(387));h=a.pendingProps,b=a.memoizedState,v=b.element,Ie(i,a),ou(a,h,null,d);var I=a.memoizedState;if(h=I.element,b.isDehydrated)if(b={element:h,isDehydrated:!1,cache:I.cache,pendingSuspenseBoundaries:I.pendingSuspenseBoundaries,transitions:I.transitions},a.updateQueue.baseState=b,a.memoizedState=b,a.flags&256){v=nl(Error(n(423)),a),a=sc(i,a,h,d,v);break e}else if(h!==v){v=nl(Error(n(424)),a),a=sc(i,a,h,d,v);break e}else for(lr=Bs(a.stateNode.containerInfo.firstChild),Ws=a,An=!0,ii=null,d=Rd(a,null,h,d),a.child=d;d;)d.flags=d.flags&-3|4096,d=d.sibling;else{if(Ka(),h===v){a=Ji(i,a,d);break e}Hs(i,a,h,d)}a=a.child}return a;case 5:return ys(a),i===null&&Ul(a),h=a.type,v=a.pendingProps,b=i!==null?i.memoizedProps:null,I=v.children,Ui(h,v)?I=null:b!==null&&Ui(h,b)&&(a.flags|=32),Rh(i,a),Hs(i,a,I,d),a.child;case 6:return i===null&&Ul(a),null;case 13:return Rs(i,a,d);case 4:return gs(a,a.stateNode.containerInfo),h=a.pendingProps,i===null?a.child=la(a,null,h,d):Hs(i,a,h,d),a.child;case 11:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Cr(h,v),$h(i,a,h,v,d);case 7:return Hs(i,a,a.pendingProps,d),a.child;case 8:return Hs(i,a,a.pendingProps.children,d),a.child;case 12:return Hs(i,a,a.pendingProps.children,d),a.child;case 10:e:{if(h=a.type._context,v=a.pendingProps,b=a.memoizedProps,I=v.value,kn(ql,h._currentValue),h._currentValue=I,b!==null)if(ei(b.value,I)){if(b.children===v.children&&!Us.current){a=Ji(i,a,d);break e}}else for(b=a.child,b!==null&&(b.return=a);b!==null;){var ee=b.dependencies;if(ee!==null){I=b.child;for(var se=ee.firstContext;se!==null;){if(se.context===h){if(b.tag===1){se=gn(-1,d&-d),se.tag=2;var we=b.updateQueue;if(we!==null){we=we.shared;var Te=we.pending;Te===null?se.next=se:(se.next=Te.next,Te.next=se),we.pending=se}}b.lanes|=d,se=b.alternate,se!==null&&(se.lanes|=d),Od(b.return,d,a),ee.lanes|=d;break}se=se.next}}else if(b.tag===10)I=b.type===a.type?null:b.child;else if(b.tag===18){if(I=b.return,I===null)throw Error(n(341));I.lanes|=d,ee=I.alternate,ee!==null&&(ee.lanes|=d),Od(I,d,a),I=b.sibling}else I=b.child;if(I!==null)I.return=b;else for(I=b;I!==null;){if(I===a){I=null;break}if(b=I.sibling,b!==null){b.return=I.return,I=b;break}I=I.return}b=I}Hs(i,a,v.children,d),a=a.child}return a;case 9:return v=a.type,h=a.pendingProps.children,Xa(a,d),v=cr(v),h=h(v),a.flags|=1,Hs(i,a,h,d),a.child;case 14:return h=a.type,v=Cr(h,a.pendingProps),v=Cr(h.type,v),Ah(i,a,h,v,d);case 15:return Th(i,a,a.type,a.pendingProps,d);case 17:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:Cr(h,v),_a(i,a),a.tag=1,os(h)?(i=!0,ia(a)):i=!1,Xa(a,d),Nh(a,h,v),ma(a,h,v,d),Gd(null,a,h,!0,i,d);case 19:return Ih(i,a,d);case 22:return Mh(i,a,d)}throw Error(n(156,a.tag))};function V(i,a){return _r(i,a)}function H(i,a,d,h){this.tag=i,this.key=d,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=a,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=h,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function q(i,a,d,h){return new H(i,a,d,h)}function ne(i){return i=i.prototype,!(!i||!i.isReactComponent)}function Ce(i){if(typeof i=="function")return ne(i)?1:0;if(i!=null){if(i=i.$$typeof,i===B)return 11;if(i===z)return 14}return 2}function me(i,a){var d=i.alternate;return d===null?(d=q(i.tag,a,i.key,i.mode),d.elementType=i.elementType,d.type=i.type,d.stateNode=i.stateNode,d.alternate=i,i.alternate=d):(d.pendingProps=a,d.type=i.type,d.flags=0,d.subtreeFlags=0,d.deletions=null),d.flags=i.flags&14680064,d.childLanes=i.childLanes,d.lanes=i.lanes,d.child=i.child,d.memoizedProps=i.memoizedProps,d.memoizedState=i.memoizedState,d.updateQueue=i.updateQueue,a=i.dependencies,d.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},d.sibling=i.sibling,d.index=i.index,d.ref=i.ref,d}function ge(i,a,d,h,v,b){var I=2;if(h=i,typeof i=="function")ne(i)&&(I=1);else if(typeof i=="string")I=5;else e:switch(i){case Y:return Ne(d.children,v,b,a);case J:I=8,v|=8;break;case re:return i=q(12,d,a,v|2),i.elementType=re,i.lanes=b,i;case A:return i=q(13,d,a,v),i.elementType=A,i.lanes=b,i;case $:return i=q(19,d,a,v),i.elementType=$,i.lanes=b,i;case te:return Oe(d,v,b,a);default:if(typeof i=="object"&&i!==null)switch(i.$$typeof){case ae:I=10;break e;case ue:I=9;break e;case B:I=11;break e;case z:I=14;break e;case E:I=16,h=null;break e}throw Error(n(130,i==null?i:typeof i,""))}return a=q(I,d,a,v),a.elementType=i,a.type=h,a.lanes=b,a}function Ne(i,a,d,h){return i=q(7,i,h,a),i.lanes=d,i}function Oe(i,a,d,h){return i=q(22,i,h,a),i.elementType=te,i.lanes=d,i.stateNode={isHidden:!1},i}function He(i,a,d){return i=q(6,i,null,a),i.lanes=d,i}function Xe(i,a,d){return a=q(4,i.children!==null?i.children:[],i.key,a),a.lanes=d,a.stateNode={containerInfo:i.containerInfo,pendingChildren:null,implementation:i.implementation},a}function Ke(i,a,d,h,v){this.tag=a,this.containerInfo=i,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=tr(0),this.expirationTimes=tr(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=tr(0),this.identifierPrefix=h,this.onRecoverableError=v,this.mutableSourceEagerHydrationData=null}function nn(i,a,d,h,v,b,I,ee,se){return i=new Ke(i,a,d,ee,se),a===1?(a=1,b===!0&&(a|=8)):a=0,b=q(3,null,null,a),i.current=b,b.stateNode=i,b.memoizedState={element:h,isDehydrated:d,cache:null,transitions:null,pendingSuspenseBoundaries:null},Vl(b),i}function Mt(i,a,d){var h=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:G,key:h==null?null:""+h,children:i,containerInfo:a,implementation:d}}function We(i){if(!i)return qi;i=i._reactInternals;e:{if(ft(i)!==i||i.tag!==1)throw Error(n(170));var a=i;do{switch(a.tag){case 3:a=a.stateNode.context;break e;case 1:if(os(a.type)){a=a.stateNode.__reactInternalMemoizedMergedChildContext;break e}}a=a.return}while(a!==null);throw Error(n(171))}if(i.tag===1){var d=i.type;if(os(d))return eu(i,d,a)}return a}function jt(i,a,d,h,v,b,I,ee,se){return i=nn(d,h,!0,i,v,b,I,ee,se),i.context=We(null),d=i.current,h=Ls(),v=eo(d),b=gn(h,v),b.callback=a??null,ji(d,b,v),i.current.lanes=v,hs(i,v,h),us(i,h),i}function mn(i,a,d,h){var v=a.current,b=Ls(),I=eo(v);return d=We(d),a.context===null?a.context=d:a.pendingContext=d,a=gn(b,I),a.payload={element:i},h=h===void 0?null:h,h!==null&&(a.callback=h),i=ji(v,a,I),i!==null&&(ci(i,v,I,b),Gl(i,v,I)),I}function xn(i){if(i=i.current,!i.child)return null;switch(i.child.tag){case 5:return i.child.stateNode;default:return i.child.stateNode}}function Js(i,a){if(i=i.memoizedState,i!==null&&i.dehydrated!==null){var d=i.retryLane;i.retryLane=d!==0&&d<a?d:a}}function dr(i,a){Js(i,a),(i=i.alternate)&&Js(i,a)}function di(){return null}var al=typeof reportError=="function"?reportError:function(i){console.error(i)};function L_(i){this._internalRoot=i}Yh.prototype.render=L_.prototype.render=function(i){var a=this._internalRoot;if(a===null)throw Error(n(409));mn(i,a,null,null)},Yh.prototype.unmount=L_.prototype.unmount=function(){var i=this._internalRoot;if(i!==null){this._internalRoot=null;var a=i.containerInfo;wa(function(){mn(null,i,null,null)}),a[Ur]=null}};function Yh(i){this._internalRoot=i}Yh.prototype.unstable_scheduleHydration=function(i){if(i){var a=Lr();i={blockedOn:null,target:i,priority:a};for(var d=0;d<is.length&&a!==0&&a<is[d].priority;d++);is.splice(d,0,i),d===0&&Lc(i)}};function I_(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11)}function Jh(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11&&(i.nodeType!==8||i.nodeValue!==" react-mount-point-unstable "))}function my(){}function K0(i,a,d,h,v){if(v){if(typeof h=="function"){var b=h;h=function(){var we=xn(I);b.call(we)}}var I=jt(a,h,i,0,null,!1,!1,"",my);return i._reactRootContainer=I,i[Ur]=I.current,Zo(i.nodeType===8?i.parentNode:i),wa(),I}for(;v=i.lastChild;)i.removeChild(v);if(typeof h=="function"){var ee=h;h=function(){var we=xn(se);ee.call(we)}}var se=nn(i,0,!1,null,null,!1,!1,"",my);return i._reactRootContainer=se,i[Ur]=se.current,Zo(i.nodeType===8?i.parentNode:i),wa(function(){mn(a,se,d,h)}),se}function Xh(i,a,d,h,v){var b=d._reactRootContainer;if(b){var I=b;if(typeof v=="function"){var ee=v;v=function(){var se=xn(I);ee.call(se)}}mn(a,I,i,v)}else I=K0(d,a,i,v,h);return xn(I)}Rc=function(i){switch(i.tag){case 3:var a=i.stateNode;if(a.current.memoizedState.isDehydrated){var d=qn(a.pendingLanes);d!==0&&(fo(a,d|1),us(a,de()),(Ht&6)===0&&(Ci=de()+500,xo()))}break;case 13:wa(function(){var h=bi(i,1);if(h!==null){var v=Ls();ci(h,i,1,v)}}),dr(i,1)}},Wo=function(i){if(i.tag===13){var a=bi(i,134217728);if(a!==null){var d=Ls();ci(a,i,134217728,d)}dr(i,134217728)}},ms=function(i){if(i.tag===13){var a=eo(i),d=bi(i,a);if(d!==null){var h=Ls();ci(d,i,a,h)}dr(i,a)}},Lr=function(){return rn},Ir=function(i,a){var d=rn;try{return rn=i,a()}finally{rn=d}},Mr=function(i,a,d){switch(a){case"input":if(Se(i,d),a=d.name,d.type==="radio"&&a!=null){for(d=i;d.parentNode;)d=d.parentNode;for(d=d.querySelectorAll("input[name="+JSON.stringify(""+a)+'][type="radio"]'),a=0;a<d.length;a++){var h=d[a];if(h!==i&&h.form===i.form){var v=Fl(h);if(!v)throw Error(n(90));gt(h),Se(h,v)}}}break;case"textarea":Qt(i,d);break;case"select":a=d.value,a!=null&&Le(i,!!d.multiple,a,!1)}},rt=nf,ct=wa;var Y0={usingClientEntryPoint:!1,Events:[Ua,ta,Fl,Je,Ve,nf]},lf={findFiberByHostInstance:Wi,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},J0={bundleType:lf.bundleType,version:lf.version,rendererPackageName:lf.rendererPackageName,rendererConfig:lf.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:P.ReactCurrentDispatcher,findHostInstanceByFiber:function(i){return i=ss(i),i===null?null:i.stateNode},findFiberByHostInstance:lf.findFiberByHostInstance||di,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 Zh=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Zh.isDisabled&&Zh.supportsFiber)try{on=Zh.inject(J0),Fs=Zh}catch{}}return Gr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Y0,Gr.createPortal=function(i,a){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!I_(a))throw Error(n(200));return Mt(i,a,null,d)},Gr.createRoot=function(i,a){if(!I_(i))throw Error(n(299));var d=!1,h="",v=al;return a!=null&&(a.unstable_strictMode===!0&&(d=!0),a.identifierPrefix!==void 0&&(h=a.identifierPrefix),a.onRecoverableError!==void 0&&(v=a.onRecoverableError)),a=nn(i,1,!1,null,null,d,!1,h,v),i[Ur]=a.current,Zo(i.nodeType===8?i.parentNode:i),new L_(a)},Gr.findDOMNode=function(i){if(i==null)return null;if(i.nodeType===1)return i;var a=i._reactInternals;if(a===void 0)throw typeof i.render=="function"?Error(n(188)):(i=Object.keys(i).join(","),Error(n(268,i)));return i=ss(a),i=i===null?null:i.stateNode,i},Gr.flushSync=function(i){return wa(i)},Gr.hydrate=function(i,a,d){if(!Jh(a))throw Error(n(200));return Xh(null,i,a,!0,d)},Gr.hydrateRoot=function(i,a,d){if(!I_(i))throw Error(n(405));var h=d!=null&&d.hydratedSources||null,v=!1,b="",I=al;if(d!=null&&(d.unstable_strictMode===!0&&(v=!0),d.identifierPrefix!==void 0&&(b=d.identifierPrefix),d.onRecoverableError!==void 0&&(I=d.onRecoverableError)),a=jt(a,null,i,1,d??null,v,!1,b,I),i[Ur]=a.current,Zo(i),h)for(i=0;i<h.length;i++)d=h[i],v=d._getVersion,v=v(d._source),a.mutableSourceEagerHydrationData==null?a.mutableSourceEagerHydrationData=[d,v]:a.mutableSourceEagerHydrationData.push(d,v);return new Yh(a)},Gr.render=function(i,a,d){if(!Jh(a))throw Error(n(200));return Xh(null,i,a,!1,d)},Gr.unmountComponentAtNode=function(i){if(!Jh(i))throw Error(n(40));return i._reactRootContainer?(wa(function(){Xh(null,null,i,!1,function(){i._reactRootContainer=null,i[Ur]=null})}),!0):!1},Gr.unstable_batchedUpdates=nf,Gr.unstable_renderSubtreeIntoContainer=function(i,a,d,h){if(!Jh(d))throw Error(n(200));if(i==null||i._reactInternals===void 0)throw Error(n(38));return Xh(i,a,d,!1,h)},Gr.version="18.3.1-next-f1338f8080-20240426",Gr}var by;function Fv(){if(by)return D_.exports;by=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(),D_.exports=ij(),D_.exports}var jy;function oj(){if(jy)return Qh;jy=1;var e=Fv();return Qh.createRoot=e.createRoot,Qh.hydrateRoot=e.hydrateRoot,Qh}var aj=oj();const lj=Ag(aj),zv=[{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"]}];zv.map(e=>({id:e.id,label:e.label}));function cj(e){return`theme-${String(e||"").trim()||"dark"}`}function Sy(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(cj(e))}catch{}}const Op=[{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}],Pp=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function uj(e){const t=String(e).trim();return Op.find(n=>n.id===t)||Op[1]}function dj(e){const t=String(e).trim();return Pp.find(n=>n.id===t)||Pp[1]}function ky(e){try{const t=document.documentElement,n=uj(e.font_scale||"md"),r=dj(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(r.density))}catch{}}const B_={sm:"(max-width: 767.98px)",md:"(max-width: 1023.98px)",short:"(max-height: 500px)"};function fj(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function Ny(e){const[t,n]=m.useState(()=>fj(e));return m.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(e),o=()=>n(r.matches);return o(),typeof r.addEventListener=="function"?r.addEventListener("change",o):r.addListener(o),()=>{typeof r.removeEventListener=="function"?r.removeEventListener("change",o):r.removeListener(o)}},[e]),t}let uf=null;function hj(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))),o=Math.max(0,Math.round(e-t.height-Math.max(0,t.offsetTop)));return{vvHeight:r,keyboardInset:o}}function mj(){if(uf)return uf;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:l,keyboardInset:u}=hj(window.innerHeight,{height:e.height,offsetTop:e.offsetTop,scale:e.scale||1});t.style.setProperty("--vv-height",`${l}px`),t.style.setProperty("--keyboard-inset",`${u}px`)},o=()=>{n||(n=window.requestAnimationFrame(r))};return r(),e.addEventListener("resize",o),e.addEventListener("scroll",o),window.addEventListener("orientationchange",o),uf=()=>{e.removeEventListener("resize",o),e.removeEventListener("scroll",o),window.removeEventListener("orientationchange",o),n&&window.cancelAnimationFrame(n),t.style.removeProperty("--vv-height"),t.style.removeProperty("--keyboard-inset"),uf=null},uf}var Bv=Fv();function Tu(...e){return e.filter(Boolean).join(" ")}function Ju({value:e,options:t,placeholder:n="Select…",disabled:r=!1,loading:o=!1,searchable:l=!0,searchPlaceholder:u="Search…",allowCustom:c=!1,clearable:f=!1,minPopoverWidth:_=240,variant:p="panel",className:y,triggerClassName:w,ariaLabel:x,id:S,includeValueOption:j=!1,onOpen:C,customOptionLabel:N,validateCustomValue:T,onChange:L,renderOption:P,renderValue:W}){const G=m.useRef(null),Y=m.useRef(null),J=m.useRef(null),re=m.useRef(C),ae=m.useId(),ue=S||`af-select-${ae.replace(/[^a-zA-Z0-9_-]/g,"")}`,B=`${ue}-listbox`,[A,$]=m.useState(!1),[z,E]=m.useState(""),[te,O]=m.useState(0),[F,K]=m.useState("bottom"),[R,Q]=m.useState({left:0,top:0,width:0});m.useEffect(()=>{re.current=C},[C]);const Z=m.useMemo(()=>{if(!j)return t;const xe=String(e??"").trim();return!xe||t.some(Le=>Le.value===xe)?t:[...t,{value:xe,label:xe}]},[j,t,e]),X=m.useMemo(()=>{const xe=String(e??"");return Z.find(Le=>Le.value===xe)||null},[Z,e]),le=m.useMemo(()=>(X==null?void 0:X.label)||String(e||"").trim()||"",[X,e]),_e=m.useMemo(()=>{const xe=z.trim().toLowerCase();return xe?Z.filter(Le=>Le.label.toLowerCase().includes(xe)||Le.value.toLowerCase().includes(xe)):Z},[Z,z]),he=m.useMemo(()=>{if(!c)return null;const xe=z.trim();if(!xe||Z.some(Ft=>Ft.value===xe))return null;const Ue=(T==null?void 0:T(xe,{options:Z}))||"";return{value:xe,label:N?N(xe):`Use "${xe}"`,disabled:!!Ue,reason:Ue}},[c,N,Z,z,T]),ye=m.useMemo(()=>{const xe=he?[he,..._e]:_e;if(xe.length>0)return xe;const Le=String(e??"").trim();return o&&Le?[{value:Le,label:le||Le}]:xe},[he,_e,o,le,e]),Ee=m.useCallback(()=>{const xe=G.current;if(!xe)return;const Le=xe.getBoundingClientRect(),Ue=Math.max(Le.width,_),Ft=Math.max(8,Math.min(Le.left,window.innerWidth-Ue-8)),Qt=window.innerHeight-Le.bottom,yn=Le.top,Ut=Qt>=220||Qt>=yn?"bottom":"top";K(Ut);const It=Ut==="bottom"?Le.bottom+6:Le.top-6;Q({left:Ft,top:It,width:Ue})},[_]),ze=m.useCallback(()=>{$(!1),E("")},[]);m.useEffect(()=>{var xe;A&&((xe=re.current)==null||xe.call(re))},[A]),m.useEffect(()=>{if(!A)return;Ee();const xe=()=>Ee();return window.addEventListener("resize",xe),window.addEventListener("scroll",xe,!0),()=>{window.removeEventListener("resize",xe),window.removeEventListener("scroll",xe,!0)}},[A,Ee]),m.useEffect(()=>{if(!A)return;const xe=Le=>{var Ft,Qt;const Ue=Le.target;Ue&&((Ft=G.current)!=null&&Ft.contains(Ue)||(Qt=Y.current)!=null&&Qt.contains(Ue)||ze())};return document.addEventListener("mousedown",xe,!0),()=>document.removeEventListener("mousedown",xe,!0)},[A,ze]),m.useEffect(()=>{if(!A)return;const xe=Math.max(0,ye.findIndex(Le=>Le.value===e));O(xe===-1?0:xe),l&&setTimeout(()=>{var Le;return(Le=J.current)==null?void 0:Le.focus()},0)},[A,l,e,ye]);const Be=xe=>{var Ue;const Le=ye.find(Ft=>Ft.value===xe);Le!=null&&Le.disabled||(L(xe),ze(),(Ue=G.current)==null||Ue.focus())},gt=xe=>{var Le,Ue;if(xe.key==="Escape")return xe.preventDefault(),ze(),(Le=G.current)==null||Le.focus(),!0;if(xe.key==="Tab")return ze(),(Ue=G.current)==null||Ue.focus(),!1;if(xe.key==="ArrowDown")return xe.preventDefault(),O(Ft=>Math.min(Ft+1,Math.max(0,ye.length-1))),!0;if(xe.key==="ArrowUp")return xe.preventDefault(),O(Ft=>Math.max(Ft-1,0)),!0;if(xe.key==="Home")return xe.preventDefault(),O(0),!0;if(xe.key==="End")return xe.preventDefault(),O(Math.max(0,ye.length-1)),!0;if(xe.key==="Enter"){xe.preventDefault();const Ft=ye[te];return Ft&&Be(Ft.value),!0}return!1},Fe=xe=>{if(!r){if(A){if(gt(xe))return;if(xe.key===" "&&!l){xe.preventDefault();const Le=ye[te];Le&&Be(Le.value)}return}(xe.key==="Enter"||xe.key===" "||xe.key==="ArrowDown"||xe.key==="ArrowUp")&&(xe.preventDefault(),$(!0))}},tt=!!String(e||"").trim(),lt=tt?le:n,Ye=he!=null&&he.disabled?he.reason||"Unavailable":"",Se=A&&ye.length>0?`${ue}-opt-${te}`:void 0,Re=s.jsx("span",{className:Tu("af-select-value",!tt&&"af-select-value--placeholder"),children:o&&!tt?"Loading…":lt}),ht=W?W(X,String(e||"")):Re;return s.jsxs("span",{className:Tu("af-select",p==="pin"?"af-select--pin":"af-select--panel",y),children:[s.jsxs("button",{ref:G,id:ue,type:"button",className:Tu("af-select-trigger",f&&tt&&"af-select-trigger--clearable",w),disabled:r,onMouseDown:xe=>xe.stopPropagation(),onClick:xe=>{xe.stopPropagation(),!r&&$(Le=>!Le)},onKeyDown:Fe,role:l?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":A,"aria-controls":A?B:void 0,"aria-activedescendant":l?void 0:Se,"aria-label":x,children:[ht,s.jsx("span",{className:Tu("af-select-caret",A&&"af-select-caret--open"),children:"▾"})]}),f&&tt?s.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:r,onMouseDown:xe=>{xe.preventDefault(),xe.stopPropagation()},onClick:xe=>{var Le;xe.preventDefault(),xe.stopPropagation(),L(""),ze(),(Le=G.current)==null||Le.focus()},title:"Clear",children:"×"}):null,A?Bv.createPortal(s.jsxs("div",{ref:Y,className:Tu("af-select-popover",F==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${R.left}px`,top:`${R.top}px`,width:`${R.width}px`},onMouseDown:xe=>xe.stopPropagation(),onClick:xe=>xe.stopPropagation(),onWheel:xe=>xe.stopPropagation(),onKeyDown:gt,tabIndex:-1,children:[l?s.jsxs("div",{className:"af-select-search",children:[s.jsx("input",{ref:J,className:"af-select-search-input",value:z,onChange:xe=>E(xe.target.value),placeholder:u,onKeyDown:gt,role:"combobox","aria-expanded":!0,"aria-controls":B,"aria-activedescendant":Se,"aria-invalid":!!Ye,"aria-describedby":Ye?`${ue}-custom-error`:void 0}),Ye?s.jsx("div",{id:`${ue}-custom-error`,className:"af-select-custom-error",role:"alert",children:Ye}):null]}):null,s.jsx("div",{className:"af-select-options",role:"listbox",id:B,"aria-label":x,children:o&&ye.length===0?s.jsx("div",{className:"af-select-empty",children:"Loading…"}):ye.length===0?s.jsx("div",{className:"af-select-empty",children:"No results"}):ye.map((xe,Le)=>{var It;const Ue=xe.value===e,Ft=Le===te,Qt=String(xe.group||"").trim(),yn=Le>0?String(((It=ye[Le-1])==null?void 0:It.group)||"").trim():"",Ut=!!Qt&&Qt!==yn;return s.jsxs(ve.Fragment,{children:[Ut?s.jsx("div",{className:"af-select-group",role:"presentation",children:Qt}):null,s.jsx("div",{id:`${ue}-opt-${Le}`,role:"option","aria-selected":Ue,className:Tu("af-select-option",Ue&&"af-select-option--selected",Ft&&"af-select-option--highlighted",xe.disabled&&"af-select-option--disabled"),title:xe.disabled?xe.reason||"Unavailable":void 0,onMouseEnter:()=>O(Le),onMouseDown:jn=>{jn.preventDefault(),jn.stopPropagation()},onClick:()=>Be(xe.value),"aria-disabled":xe.disabled?!0:void 0,children:P?P(xe,{selected:Ue,highlighted:Ft}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"af-select-option-label",children:[s.jsx("span",{children:xe.label}),xe.reason?s.jsx("small",{className:"af-select-option-reason",children:xe.reason}):null]}),Ue?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},xe.value)})})]}),document.body):null]})}function _j(e){const t=new Set,n=[];for(const r of e||[]){if(!r||typeof r!="object")continue;const o=String(r.name||"").trim();!o||t.has(o)||(t.add(o),n.push({name:o,display_name:typeof r.display_name=="string"?r.display_name:void 0}))}return n.sort((r,o)=>r.name.localeCompare(o.name)),n}function pj(e){const t=new Set,n=[];for(const r of e||[]){const o=String(r||"").trim();!o||t.has(o)||(t.add(o),n.push(o))}return n.sort(),n}function gj(e){const t=e.disabled===!0,n=e.layout||"stack",r=e.allowGatewayDefault!==!1,o=String(e.gatewayDefaultLabel||"(gateway default)"),l=String(e.providerLabel||"Provider"),u=String(e.modelLabel||"Model"),c=String(e.providerPlaceholder||"(select)"),f=String(e.modelPlaceholder||"(select)"),_=String(e.provider||"").trim(),p=String(e.model||"").trim(),y=_j(e.providers),w=pj(e.models),x=t||!!e.loadingProviders,S=t||!!e.loadingModels,j=[...r?[{value:"",label:o}]:[],...y.map(N=>({value:N.name,label:N.display_name?`${N.display_name} (${N.name})`:N.name}))],C=[...r?[{value:"",label:o}]:[],...w.map(N=>({value:N,label:N}))];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:l}),s.jsx(Ju,{value:_,options:j,placeholder:r?o:c,disabled:x,loading:!!e.loadingProviders,searchable:!0,allowCustom:e.allowCustomProvider===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:l,onChange:N=>e.onChange({provider:String(N||"").trim(),model:""})}),e.loadingProviders?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading providers…"}):null,e.providerError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.providerError}):null]}),s.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[s.jsx("label",{children:u}),s.jsx(Ju,{value:p,options:C,placeholder:r?o:f,disabled:S,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:u,onChange:N=>e.onChange({provider:_,model:String(N||"").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 Cy(...e){return e.filter(Boolean).join(" ")}function yj({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:o="neutral",showGatewayUrl:l=!1,gatewayUrl:u="",gatewayUrlPlaceholder:c="http://127.0.0.1:8080",onGatewayUrlChange:f,userId:_,userPlaceholder:p="admin",onUserIdChange:y,token:w,tokenPlaceholder:x="Paste Gateway user token",showToken:S=!1,onTokenChange:j,onShowTokenChange:C,remember:N=!1,rememberLabel:T="Remember this browser",onRememberChange:L,loading:P=!1,submitting:W=!1,submitDisabled:G=!1,submitLabel:Y="Sign in",submittingLabel:J="Signing in...",closeLabel:re="Close",signOutLabel:ae="Sign out",showClose:ue=!1,showSignOut:B=!1,error:A,message:$,className:z,onSubmit:E,onClose:te,onSignOut:O}){const F=P||W,K=F||G||!String(_||"").trim()||!String(w||"").trim(),R=Q=>{Q.preventDefault(),!K&&E()};return s.jsxs("form",{className:Cy("af-gateway-signin",z),onSubmit:R,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:Cy("af-gateway-signin__status",`af-gateway-signin__status--${o}`),children:r})}),s.jsxs("div",{className:"af-gateway-signin__form",children:[l?s.jsxs(s.Fragment,{children:[s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-url",children:"Gateway URL"}),s.jsx("input",{id:"gateway-session-url",value:u,onChange:Q=>f==null?void 0:f(Q.target.value),placeholder:c,autoComplete:"url",disabled:F})]}):null,s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-user",children:"Gateway user"}),s.jsx("input",{id:"gateway-session-user",value:_,onChange:Q=>y(Q.target.value),placeholder:p,autoComplete:"username",disabled:F}),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:S?"text":"password",value:w,onChange:Q=>j(Q.target.value),placeholder:x,autoComplete:"current-password",disabled:F}),s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>C==null?void 0:C(!S),disabled:F,children:S?"Hide":"Show"})]}),s.jsxs("label",{className:"af-gateway-signin__checkbox",children:[s.jsx("input",{type:"checkbox",checked:!!N,onChange:Q=>L==null?void 0:L(Q.target.checked),disabled:F}),T]})]}),A?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:A}):null,!A&&$?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:$}):null,s.jsxs("div",{className:"af-gateway-signin__actions",children:[ue?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:te,disabled:F,children:re}):null,B?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(O==null?void 0:O()),disabled:F,children:ae}):null,s.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:K,children:W?J:Y})]})]})}function wj(e){return e==="light"?"Light":"Dark"}function vj(e){const t=e.themes&&e.themes.length?e.themes:zv,n=e.showSwatches!==!1,r=e.variant||"panel",o=m.useMemo(()=>{const u={};for(const c of t)u[c.id]=c;return u},[t]),l=m.useMemo(()=>t.map(u=>({value:u.id,label:u.label,group:wj(u.group)})),[t]);return s.jsx(Ju,{value:e.value,options:l,placeholder:e.placeholder||"Select theme…",disabled:e.disabled===!0,searchable:!0,allowCustom:!1,clearable:!1,variant:r,className:e.className,triggerClassName:e.triggerClassName,onChange:u=>e.onChange(String(u||"").trim()),renderValue:(u,c)=>{const f=String(c||"").trim(),_=o[f],p=(_==null?void 0:_.label)||f||e.placeholder||"Select theme…",y=(_==null?void 0:_.swatches)||null,w=!f;return s.jsxs("span",{className:"af-theme-value",children:[s.jsx("span",{className:`af-theme-label ${w?"af-theme-label--placeholder":""}`.trim(),children:p}),n&&y?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:y.map((x,S)=>s.jsx("span",{className:"af-theme-swatch",style:{background:x}},`${f}:${S}`))}):null]})},renderOption:(u,c)=>{const f=String(u.value||"").trim(),_=o[f],p=(_==null?void 0:_.swatches)||null;return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"af-theme-option-label",children:u.label}),s.jsxs("span",{className:"af-theme-option-right",children:[n&&p?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:p.map((y,w)=>s.jsx("span",{className:"af-theme-swatch",style:{background:y}},`${f}:${w}`))}):null,c.selected?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function xj(e){const t=e.scales&&e.scales.length?e.scales:Op,n=e.variant||"panel",r=m.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(Ju,{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:o=>e.onChange(String(o||"").trim())})}function bj(e){const t=e.densities&&e.densities.length?e.densities:Pp,n=e.variant||"panel",r=m.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(Ju,{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:o=>e.onChange(String(o||"").trim())})}const jj=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function Sj(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"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"clock":return s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 6v6h4"})]});default:return null}}function Qe({name:e,size:t=16,className:n,title:r,...o}){const l=r?void 0:!0,u=jj.has(e);return s.jsxs("svg",{width:t,height:t,viewBox:u?"0 0 16 16":"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:u?1.4:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,"aria-hidden":l,role:r?"img":"presentation",...o,children:[r?s.jsx("title",{children:r}):null,Sj(e)]})}const Dp="api/gateway",Kf="api/connection/gateway";function bt(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?`${Dp}/${t}`:Dp}function Uv(e,t){const n=String(t||"");if(n.startsWith("/"))throw new Error(`joinBaseUrl takes a relative path, got ${JSON.stringify(n)}.`);let r=String(e??"");for(;r.endsWith("/");)r=r.slice(0,-1);return r?`${r}/${n}`:n}function kj(e){const t=String(e||""),n=`/${Dp}/`;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 o of r.split("/")){const l=o.replace(/%2e/gi,".");if(l==="."||l==="..")throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (a "." or ".." segment).`)}return t.slice(1)}function Nj(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function Cj(e){return Nj(e)?!e.checked:null}let Ej=0;function Ta(e){const{label:t,checked:n,onChange:r,description:o,reasonVisible:l=!0,describedBy:u,hint:c,busy:f=!1,variant:_="inline",ariaLabel:p,className:y,id:w,action:x}=e,S=String(e.unavailableReason||"").trim(),j=!!S,C=u||(w?`${w}-reason`:j?`af-switch-reason-${++Ej}`:void 0),N=["af-switch",_==="row"?"af-switch--row":_==="sm"?"af-switch--sm":"",j?"af-switch--unavailable":"",y||""].filter(Boolean).join(" "),T=P=>{const W=Cj({checked:n,unavailableReason:S,busy:f});if(W===null){P.preventDefault();return}r==null||r(W)},L=s.jsxs("button",{type:"button",role:"switch",id:w,className:N,"data-action":x,"aria-checked":n?"true":"false","aria-disabled":j?"true":void 0,"aria-describedby":j?C:void 0,"aria-busy":f?"true":void 0,"aria-label":p,"aria-description":o?void 0:c,title:j?c?`${S}
41
+ ${c}`:S:c,onClick:T,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}),o?s.jsx("span",{className:"af-switch__desc",children:o}):null]})]});return!j||u?L:s.jsxs("span",{className:_==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[L,s.jsx("span",{id:C,className:l?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:S})]})}function $j(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,o=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,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:[o,s.jsx("span",{id:r,className:"af-switch__reason",children:t})]}):o}async function Fp(e=Kf){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 Aj(e,t=Kf){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 o=r&&typeof r=="object"&&r.detail?String(r.detail):`HTTP ${n.status}`;throw new Error(o)}return r}async function Wv(e=Kf){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 U_(e){let t=String(e||"").trim();for(let n=0;n<2&&t;n+=1){try{const l=JSON.parse(t);if(typeof l=="string"&&l!==t){t=l.trim();continue}}catch{}const r=t[0],o=t[t.length-1];if(r==='"'&&o==='"'||r==="'"&&o==="'"){t=t.slice(1,-1).trim();continue}break}return t.replace(/\/+$/,"")}function qv(e){var l,u;if(!e)return{label:"Signed out",tone:"warn"};if(!e.has_session)return{label:"Signed out",tone:"warn"};const t=e.gateway||{},n=(l=t.principal)==null?void 0:l.user_id,r=(u=t.principal)==null?void 0:u.runtime_id;if(t.ok&&n)return{label:`Signed in as ${n}${r?` · runtime ${r}`:""}`,tone:"ok"};if(t.ok)return{label:"Signed in",tone:"ok"};const o=t.error||t.detail;return typeof o=="string"&&o.trim()?{label:"Session rejected — sign in again",tone:"err"}:{label:"Sign in required",tone:"err"}}function Tj(e){const t=e.connectionPath||Kf,[n,r]=m.useState(!1),[o,l]=m.useState(!1),[u,c]=m.useState(null),[f,_]=m.useState(!1);m.useEffect(()=>{e.isOpen||_(!1)},[e.isOpen]);const[p,y]=m.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[w,x]=m.useState("admin"),[S,j]=m.useState(""),[C,N]=m.useState(!1),[T,L]=m.useState(!0),[P,W]=m.useState(""),[G,Y]=m.useState(""),J=m.useMemo(()=>qv(u),[u]),re=A=>{var $;c(A),($=e.onStatusChange)==null||$.call(e,A)},ae=m.useRef(!1);if(m.useEffect(()=>{var $;if(!e.isOpen)return;const A=!ae.current;if(ae.current=!0,A&&e.initialStatus!==void 0&&e.initialStatus!==null){const z=e.initialStatus;re(z),typeof z.gateway_url=="string"&&z.gateway_url.trim()&&y(U_(z.gateway_url));const E=($=z.gateway)==null?void 0:$.principal;E!=null&&E.user_id&&x(E.user_id);return}r(!0),W(""),Fp(t).then(z=>{var te;re(z),typeof z.gateway_url=="string"&&z.gateway_url.trim()&&y(U_(z.gateway_url));const E=(te=z.gateway)==null?void 0:te.principal;E!=null&&E.user_id&&x(E.user_id)}).catch(z=>W(`Failed to load connection status: ${String((z==null?void 0:z.message)||z)}`)).finally(()=>r(!1))},[e.isOpen]),m.useEffect(()=>{if(!e.isOpen)return;const A=$=>{$.key==="Escape"&&!$.defaultPrevented&&!e.blocking&&($.preventDefault(),e.onClose())};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||f)return null;const ue=async()=>{l(!0),W(""),Y("");try{const A=U_(p);y(A);const $=await Aj({gateway_url:A,gateway_user_id:w,gateway_token:S,persist:T},t);re($),j(""),_(!0),e.onClose()}catch(A){W(String((A==null?void 0:A.message)||A))}finally{l(!1)}},B=async()=>{l(!0),W(""),Y("");try{await Wv(t),j("");const A=await Fp(t).catch(()=>null);re(A),Y("Signed out. This browser no longer holds a gateway session.")}catch(A){W(String((A==null?void 0:A.message)||A))}finally{l(!1)}};return s.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:A=>{!e.blocking&&A.target===A.currentTarget&&e.onClose()},children:s.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:s.jsx(yj,{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:J.label,statusTone:J.tone,showGatewayUrl:!0,gatewayUrl:p,onGatewayUrlChange:A=>y(A),userId:w,onUserIdChange:x,token:S,tokenPlaceholder:u!=null&&u.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:C,onTokenChange:j,onShowTokenChange:N,remember:T,rememberLabel:"Keep this browser signed in",onRememberChange:L,loading:n,submitting:o,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(u!=null&&u.has_session),onSignOut:B,error:P,message:G,onSubmit:ue})})})}function Mj(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function Rj(e){const t=e||{},n=t.connectionPath||Kf,r=t.variant||"dismissable",o=m.useRef(t.onStatusChange);o.current=t.onStatusChange;const l=m.useRef(r);l.current=r;const u=m.useRef(!!t.autoOpenMidSession);u.current=!!t.autoOpenMidSession;const[c,f]=m.useState(null),[_,p]=m.useState("loading"),[y,w]=m.useState(!1),x=m.useRef(!1),S=m.useRef(!1),j=m.useRef("loading"),C=m.useRef("none"),N=m.useRef(!1),T=m.useRef(0),L=m.useCallback($=>{var E;T.current+=1,f($),(E=o.current)==null||E.call(o,$);const z=Mj($);if(z)p("connected"),j.current="connected",x.current=!1,C.current="none",S.current||w(!1);else if($!==null){const te=j.current;p("disconnected"),j.current="disconnected",te!=="disconnected"&&(C.current=N.current?"signout":te==="connected"?"mid":"boot");const O=l.current==="blocking"||C.current!=="mid"||u.current;!x.current&&O&&w(!0)}$!==null&&(S.current=z)},[]),P=m.useCallback(async()=>{const $=T.current;try{const z=await Fp(n);if(T.current!==$)return;L(z)}catch{if(T.current!==$)return;L(null)}},[n,L]),[W,G]=m.useState(!1),[Y,J]=m.useState(null),re=m.useCallback(async()=>{G(!0),J(null),T.current+=1;let $=null;try{await Wv(n)}catch(z){$=String((z==null?void 0:z.message)||z||"Sign-out request failed")}N.current=!0;try{await P()}finally{N.current=!1}J($),G(!1)},[n,P]),ae=m.useRef(!1);m.useEffect(()=>{ae.current||(ae.current=!0,P())},[P]);const ue=m.useCallback(()=>{w(!0)},[]),B=m.useCallback(()=>{const $=j.current;r==="blocking"&&$==="disconnected"||($==="disconnected"&&(x.current=!0),w(!1))},[r]),A=m.useMemo(()=>({isOpen:y,onClose:B,blocking:r==="blocking"&&_!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:c,onStatusChange:L}),[y,B,r,_,t.appName,n,t.defaultGatewayUrl,c,L]);return{status:c,phase:_,connected:_==="connected",modalOpen:y,signingOut:W,signOutError:Y,openModal:ue,refresh:P,signOut:re,modalProps:A}}function Lj(){return globalThis.crypto}function Ij(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 n_(){const e=Lj();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return Ij(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function Oj(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 Pj(){return n_()}function Dj(){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 o=t.slice(n+1).trim();let l=o;try{l=decodeURIComponent(o)}catch{}l&&!e.includes(l)&&e.push(l)}}catch{}return e}async function Fj(e){const t=e.commandsPath||bt("commands"),n=Pj(),r=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),o=e.csrfToken!==void 0?[e.csrfToken]:Dj();o.length===0&&o.push("");let l=null;for(const u of o){const c=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...u?{"x-abstract-csrf":u}:{}},body:r}),f=await c.json().catch(()=>null);if(!c.ok){const _=f&&typeof f=="object"&&f.detail?String(f.detail):`HTTP ${c.status}`;if(l=new Error(_),c.status===403&&f&&typeof f=="object"&&f.reason_code==="csrf_required")continue;throw l}return{accepted:!!(f!=null&&f.accepted),duplicate:!!(f!=null&&f.duplicate),seq:Number((f==null?void 0:f.seq)??0)}}throw l||new Error("Steer submit failed")}function zj(e){const[t,n]=m.useState(""),[r,o]=m.useState({kind:"idle"}),l=m.useRef(!1),u=m.useRef(0);m.useEffect(()=>{u.current+=1,o({kind:"idle"})},[e.runId]);const c=!e.disabled&&t.trim().length>0&&r.kind!=="sending",f=m.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]),_=async()=>{var x;const y=t.trim();if(!y||l.current||e.disabled)return;l.current=!0;const w=u.current;o({kind:"sending"});try{const S=e.submit?await e.submit(e.runId,y):await Fj({runId:e.runId,guidance:y,commandsPath:e.commandsPath});if(u.current!==w)return;if(!S.accepted&&!S.duplicate){o({kind:"error",detail:"The gateway did not accept this steer (accepted=false)."});return}o({kind:"queued",seq:S.seq,duplicate:S.duplicate}),n(""),(x=e.onSent)==null||x.call(e,{...S,guidance:y})}catch(S){u.current===w&&o({kind:"error",detail:String((S==null?void 0:S.message)||S)})}finally{l.current=!1}},p=y=>{y.key==="Enter"&&(y.metaKey||y.ctrlKey)&&(y.preventDefault(),_())};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:y=>{n(y.target.value),(r.kind==="error"||r.kind==="queued")&&o({kind:"idle"})},onKeyDown:p}),s.jsx("button",{type:"button",className:"af-steer__send",disabled:!c,onClick:()=>void _(),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}).`," ",f," ","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:f})})]})}function Bj(e){const t=e.closeOnEscape!==!1,n=m.useRef(null);return m.useEffect(()=>{if(!e.open||!t)return;const r=o=>{o.key!=="Escape"||o.defaultPrevented||(o.preventDefault(),e.onClose())};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[e.open,t,e.onClose]),m.useEffect(()=>{const r=n.current;r&&(e.open?r.removeAttribute("inert"):r.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:e.topOffset||0}}):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:e.topOffset||0,display:e.open?void 0:"none"},role:"complementary","aria-label":e.label,"aria-hidden":e.open?void 0:!0,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})]})]})}const Uj={name:"AbstractFramework",website:"https://abstractframework.ai",author:"Laurent-Philippe Albou, PhD",years:"2023-2026",copyright:"© 2023-2026 Laurent-Philippe Albou, PhD. Released under the MIT License.",contact_email:"contact@abstractframework.ai"},Wj={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"}},qj={framework:Uj,apps:Wj},Mm=qj;function Hj(){return Object.keys(Mm.apps).sort()}function Vj(e,t){const n=Object.prototype.hasOwnProperty.call(Mm.apps,e)?Mm.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${Hj().join(", ")})`);return{id:e,name:n.name,version:t,website:n.website,repo:n.repo,docs:n.docs,issues:n.issues,feedback:n.feedback}}function Gj(e,t){const n=Mm.framework,r=[["Application",`${e.name} ${e.version}`],["Part of",`${n.name} — ${n.website}`],["Author",`${n.author} (${n.years})`],["Copyright",n.copyright],["Website",e.website],["Source",e.repo],["Documentation",e.docs],["Report an issue",e.issues],["Give feedback",e.feedback],["Contact",n.contact_email]];for(const[o,l]of t||[])r.push([String(o),String(l)]);return r}function W_(e){return typeof e=="string"?e.trim():""}function Ey(e,t){if(t!=null)return[["Gateway",`unavailable (${String(t).trim()||"unknown error"})`]];const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=W_(n.abstractgateway);if(!r)return[["Gateway","unavailable (the gateway did not report its version)"]];const o=W_(n.abstractframework),l=[["Gateway",`AbstractGateway ${r}`],["Gateway framework",o?`AbstractFramework ${o}`:"not installed on the gateway host"]],u=n.packages&&typeof n.packages=="object"&&!Array.isArray(n.packages)?n.packages:{},c=Object.keys(u).filter(f=>f!=="abstractgateway"&&f!=="abstractframework").sort((f,_)=>f<_?-1:f>_?1:0);for(const f of c){const _=W_(u[f]);_&&l.push([`Gateway package ${f}`,_])}return l}const Kj='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function Yj(e,t,n){if(e.key!=="Tab"||!t)return;const r=Array.from(t.querySelectorAll(Kj));if(r.length===0){e.preventDefault();return}const o=r[0],l=r[r.length-1],u=!!n&&t.contains(n);e.shiftKey?(n===o||!u)&&(e.preventDefault(),l.focus()):(n===l||!u)&&(e.preventDefault(),o.focus())}const Jj=/https?:\/\/[^\s<>"]+/g;function Xj(e,t){if(e==="Contact")return[{text:t,href:`mailto:${t}`}];const n=[];let r=0;for(const o of t.matchAll(Jj)){const l=o.index??0;l>r&&n.push({text:t.slice(r,l)}),n.push({text:o[0],href:o[0]}),r=l+o[0].length}return(r<t.length||n.length===0)&&n.push({text:t.slice(r)}),n}function Zj({label:e,value:t}){return s.jsx("span",{children:Xj(e,t).map((n,r)=>n.href===void 0?s.jsx(ve.Fragment,{children:n.text},r):n.href.startsWith("mailto:")?s.jsx("a",{className:"af-about__link",href:n.href,children:n.text},r):s.jsx("a",{className:"af-about__link",href:n.href,target:"_blank",rel:"noopener noreferrer",children:n.text},r))})}function Qj(e){const t=m.useRef(null),n=m.useRef(null),r=m.useId(),o=m.useRef(e.onClose);if(o.current=e.onClose,m.useEffect(()=>{var _;if(!e.open)return;const c=document.activeElement;(_=t.current)==null||_.focus();const f=p=>{if(!p.defaultPrevented){if(p.key==="Escape"){p.preventDefault(),o.current();return}Yj(p,n.current,document.activeElement)}};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f),c&&typeof c.focus=="function"&&c.focus()}},[e.open]),!e.open)return null;const l=e.title||`About ${e.identity.name}`,u=Gj(e.identity,e.extraRows);return s.jsx("div",{className:"af-appearance-overlay af-about-overlay",onClick:e.onClose,role:"presentation",children:s.jsxs("div",{ref:n,className:"af-appearance af-about",role:"dialog","aria-modal":"true","aria-labelledby":r,onClick:c=>c.stopPropagation(),children:[s.jsx("div",{className:"af-appearance__title",id:r,children:l}),s.jsx("dl",{className:"af-about__rows",children:u.map(([c,f],_)=>s.jsxs("div",{className:"af-about__row",children:[s.jsx("dt",{className:"af-about__label",children:c}),s.jsx("dd",{className:"af-about__value",children:s.jsx(Zj,{label:c,value:f})})]},`${_}:${c}`))}),s.jsx("div",{className:"af-appearance__actions",children:s.jsx("button",{ref:t,type:"button",className:"af-appearance__close",onClick:e.onClose,children:"Close"})})]})})}function eS(e){const{connection:t}=e,n=t.phase,r=t.signingOut===!0,[o,l]=m.useState(!1),u=e.about,c=r?"Signing out…":n==="connected"?"Disconnect":n==="loading"?"Connecting…":"Connect",f=n==="connected"?"Disconnect from gateway":n==="loading"?"Checking gateway session…":"Connect to gateway";return s.jsxs("div",{className:`af-topbar${e.className?` ${e.className}`:""}`,role:"group","aria-label":"App actions",children:[e.assistant?s.jsx("button",{type:"button",className:`af-topbar__btn${e.assistant.open?" is-active":""}`,"aria-pressed":e.assistant.open,"aria-label":e.assistant.label||"Open assistant",title:e.assistant.label||"Assistant",onClick:e.assistant.onToggle,children:s.jsx(Qe,{name:"sparkle",size:16})}):null,e.appearance?s.jsx("button",{type:"button",className:"af-topbar__btn","aria-label":e.appearance.label||"Appearance (theme and typography)",title:e.appearance.label||"Appearance",onClick:e.appearance.onOpen,children:s.jsx(Qe,{name:"contrast",size:16})}):null,u?s.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--about","aria-label":u.label||`About ${u.identity.name}`,title:u.label||"About","aria-haspopup":"dialog",onClick:()=>{var _;l(!0),(_=u.onOpen)==null||_.call(u)},children:s.jsx(Qe,{name:"info",size:16})}):null,e.extraActions,s.jsxs("button",{type:"button",className:`af-topbar__pill af-topbar__pill--${n}`,onClick:n==="connected"?t.onDisconnect:t.onConnect,disabled:r,title:f,"aria-label":f,children:[s.jsx("span",{className:`af-topbar__dot af-topbar__dot--${n}`,"aria-hidden":"true"}),s.jsx("span",{className:"af-topbar__pill-label",children:c})]}),u?s.jsx(Qj,{open:o,onClose:()=>l(!1),identity:u.identity,extraRows:u.extraRows}):null]})}const jm={theme:"dark",font_scale:"md",header_density:"standard"};function tS(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:jm.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:jm.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:jm.header_density}}function nS(e){return`af_appearance_${e}_v1`}function sS(e,t){const n=nS(e),r=m.useMemo(()=>({...jm,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[o,l]=m.useState(()=>{let u=r;try{const c=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);c&&(u=tS({...r,...JSON.parse(c)}))}catch{}try{Sy(u.theme),ky({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return m.useEffect(()=>{Sy(o.theme),ky({font_scale:o.font_scale,header_density:o.header_density});try{localStorage.setItem(n,JSON.stringify(o))}catch{}},[n,o]),[o,l]}function rS(e){return m.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(vj,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),s.jsx("label",{className:"af-appearance__label",children:"Font size"}),s.jsx(xj,{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(bj,{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 iS={diary:"var(--accent)",question:"#e7b45a",dream:"#c084dd",interest:"#7bd88a",lesson:"#6ea8d8",world_model:"#5eead4"};function $y(e){const t=String(e||"");return t.length>14?`${t.slice(0,10)}…${t.slice(-4)}`:t}function q_(e){const[t,n]=m.useState(!1),[r,o]=m.useState(null),l=m.useRef(!1),u=typeof e.entryId=="string"&&e.entryId.trim()?e.entryId.trim():null,c=e.kind&&iS[e.kind]||"var(--text-muted)",f=m.useCallback(async()=>{if(!(!u||!e.onOpen||l.current)){l.current=!0,n(!0),o(null);try{await e.onOpen(u)}catch(_){o(String((_==null?void 0:_.message)||_||"could not open"))}finally{l.current=!1,n(!1)}}},[u,e.onOpen]);return!u||!e.onOpen?s.jsxs("span",{className:["af-memory-hint","af-memory-hint--text",e.className||""].filter(Boolean).join(" "),title:e.title,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:c},"aria-hidden":"true"}),s.jsx("span",{className:"af-memory-hint__label",children:e.label}),u&&e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:$y(u)}):null]}):s.jsxs("span",{className:["af-memory-hint",e.className||""].filter(Boolean).join(" "),children:[s.jsxs("button",{type:"button",className:"af-memory-hint__btn",onClick:()=>void f(),disabled:t,title:e.title||(e.command?e.command:`open ${u}`),"aria-label":`Open ${e.kind||"memory"} entry: ${e.label}`,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:c},"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:$y(u)}):null,s.jsx("span",{className:"af-memory-hint__act","aria-hidden":"true",children:t?"…":"↗"})]}),e.command?s.jsx("code",{className:"af-memory-hint__cmd",children:e.command}):null,r?s.jsx("span",{className:"af-memory-hint__err",role:"alert",children:r}):null]})}const H_=bt("automations"),oS=bt("trigger-sources"),aS=bt("me/email");class Ay 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 lS(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 o={status:e,code:r.reason_code,message:r.message};return typeof r.field=="string"&&(o.field=r.field),typeof r.command_id=="string"&&(o.command_id=r.command_id),o}}return{status:e,code:"invalid_response",message:`The gateway answered HTTP ${e} without an automation error envelope.`}}function V_(e){const t=new URLSearchParams;for(const[r,o]of Object.entries(e))o!==void 0&&t.set(r,String(o));const n=t.toString();return n?`?${n}`:""}function cS(){return n_()}function uS(e){const t=e.newId??cS,n=o=>`${H_}/${encodeURIComponent(o)}`;async function r(o,l,u){const c={accept:"application/json",...e.headers?e.headers():{}},f={method:o,headers:c};u!==void 0&&(c["content-type"]="application/json",f.body=JSON.stringify(u));const _=await e.fetch(Uv(e.baseUrl,l),f),p=await _.text();let y,w=!1;if(p)try{y=JSON.parse(p),w=!0}catch{w=!1}if(!_.ok)throw new Ay(lS(_.status,y));if(!w||y===null||typeof y!="object")throw new Ay({status:_.status,code:"invalid_response",message:`The gateway answered ${o} ${l} with a body that is not a JSON object.`});return y}return{listAutomations:(o={})=>r("GET",`${H_}${V_({status:o.status,cursor:o.cursor,limit:o.limit})}`),getAutomation:o=>r("GET",n(o)),createAutomation:o=>r("POST",H_,o),reviseAutomation:(o,l)=>r("PATCH",n(o),{command_id:l.command_id??t(),...l.expected_revision!==void 0?{expected_revision:l.expected_revision}:{},changes:l.changes}),sendAutomationCommand:(o,l)=>r("POST",`${n(o)}/commands`,{command_id:l.command_id??t(),type:l.type,...l.payload!==void 0?{payload:l.payload}:{}}),listOccurrences:(o,l={})=>r("GET",`${n(o)}/occurrences${V_({cursor:l.cursor,limit:l.limit})}`),discuss:(o,l)=>r("POST",`${n(o)}/discuss`,{request_id:l.request_id??t(),occurrence_index:l.occurrence_index,prompt:l.prompt}),markSeen:(o,l)=>r("POST",`${n(o)}/seen`,{attention_cursor:l}),listAttention:(o,l={})=>r("GET",`${n(o)}/attention${V_({cursor:l.cursor,limit:l.limit})}`),listTriggerSources:()=>r("GET",oS),getMyEmail:()=>r("GET",aS)}}const dS={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",discuss:"Discuss"},fS={active:`On: it runs on its schedule. Off: paused, scheduled runs are skipped.
42
+ Pausing lets a run in progress finish, without further retries; Run now still works and keeps it paused.
43
+ 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.
44
+ A run in progress finishes; a pending retry is cancelled. Run now still works.`,resume:`Restart the schedule at its next time after now.
45
+ Times missed while paused are skipped; resuming does not run it now.`,run_now:`Run it once now, without waiting for the schedule.
46
+ The schedule does not move: the next scheduled run keeps its time, or starts right after this run if its time comes first.
47
+ Does not count toward a run limit. Works while paused; it stays paused.
48
+ Not available while a run is in progress.`,stop_current:`Cancel the run in progress, or its pending retry.
49
+ It ends as cancelled, with no failure notice. The schedule continues.`,revise:`Change the task, schedule or settings.
50
+ 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.
51
+ A run in progress finishes; the history stays readable.`,discuss:`Talk about the results in a separate conversation, seeded with the runs up to this one.
52
+ It has its own workspace (the automation's files are read-only) and never changes the automation.`},hS="Next scheduled run: {time}.",mS="Growing context: later runs see this run in their history.",_S={run_now:{name:"playCircle"}},pS={trigger_label:"When an email arrives",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.",untrusted_hint:"Incoming mail is data, never instructions: the automation acts only on its task. Link-opening tools (fetch_url, browser_probe) always ask for your approval.",notify_label:"Email me the result",notify_hint:"When a run notifies you, or fails for good, the notice is also emailed to you.",recipients_legend:"May send email without asking to",recipients_self:"Only me (default)",recipients_list:"Me and these addresses",recipients_hint:"Sending to anyone else waits for your approval. Your recipient policy in My email still applies."},Hv={labels:dS,hints:fS,run_now_next_run_line:hS,run_now_growing_line:mS,icons:_S,email:pS},gS=/^([1-9][0-9]*)([smhd])$/,yS={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function Yf(e){if(typeof e!="string")return null;const t=gS.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function Vv(e){const t=Yf(e);if(!t)return`every ${e}`;const[n,r]=yS[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${r}`}function Ca(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 Gv(e){const t=e;if(typeof t.every!="string")return t.start_at?`once at ${Ca(t.start_at)}`:"once, now";const n=[`${Vv(t.every)} (UTC)`];return typeof t.count=="number"&&n.push(`${t.count} ${t.count===1?"run":"runs"} max`),typeof t.until=="string"&&n.push(`until ${Ca(t.until)}`),n.join(" · ")}function Tg(e){return e.source_id==="schedule"&&e.source_version===1?Gv(e.config):e.source_id==="manual"&&e.source_version===1?"manual runs only":s_(e)?tx(e.config):`${e.source_id}@${e.source_version}`}function Kv(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const wS={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},Bt=Hv.email,Yv="email.received",Jv=1,vS="1h",xS="60s",Xv=60,Mg=100,zp=1e3,Ty=200,My=200,Ry=50;function s_(e){return!!e&&e.source_id===Yv&&e.source_version===Jv}function r_(e){return!!e&&e.effective_enabled===!0}function Zv(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 bS=/[\s<>,;:"()[\]]/;function Bp(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!bS.test(t)}function jS(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const Qv={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function Rg(e){return e?vS:xS}function ex(e){const t=Yf(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function G_(e,t,n,r,o){const l=Zv(e);if(!l.length)return null;const u=l.filter(c=>!n(c));return u.length&&o.push(`${t}: ${u.join(", ")} ${u.length===1?"is not":"are not"} ${r}.`),l.length>Ty&&o.push(`${t}: at most ${Ty} entries.`),l}function SS(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=Rg(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&&(ex(n.every)??0)<Xv&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=Mg:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>zp?t.push(`At most this many emails per run: a whole number from 1 to ${zp}.`):n.max_batch=e.maxBatch;const r={},o=G_(e.fromIn,Bt.from_in,Bp,"an email address",t);o&&(r.from_in=o);const l=G_(e.fromDomainIn,Bt.from_domain_in,jS,"a domain like example.com",t);l&&(r.from_domain_in=l);const u=G_(e.toIn,Bt.to_in,Bp,"an email address",t);u&&(r.to_in=u);const c=e.subjectContains.trim();return c&&(c.length>My||/[\r\n]/.test(c)?t.push(`${Bt.subject_contains}: one line of at most ${My} characters.`):r.subject_contains=c),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 tx(e){const t=e,n=t.filter??{},r=["when an email arrives"],o=[...n.from_in??[],...n.from_domain_in??[]];o.length&&r.push(`from ${o.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 l=typeof t.every=="string"?t.every:Rg(t.uses_model!==!1);r.push(`checked ${Vv(l)}`);const u=typeof t.max_batch=="number"?t.max_batch:Mg;return r.push(`up to ${u} per run`),r.join(" · ")}const Lg={mode:"self",addresses:""};function Up(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=Zv(e.addresses).filter(o=>o!=="self");n.length||t.push("Name at least one address the automation may email, or choose Only me.");const r=n.filter(o=>!Bp(o));return r.length&&t.push(`${Bt.recipients_list}: ${r.join(", ")} ${r.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>Ry&&t.push(`At most ${Ry-1} addresses.`),{recipients:["self",...n],errors:t}}function kS(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function NS(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function nx(e){return{channels:e?["console","email"]:["console"]}}function sx(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function CS(e){return sx(e)?"In the console and by email":"In the console"}const Po={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive"},ES=new Set(["running","waiting","backoff"]);function $S(e,t=[]){return e.current_occurrence!=null}function rx(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 ix(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 o=Math.floor(r/60);return o<24?`in ${o} h${r%60?` ${r%60} min`:""}`:`in ${Math.floor(o/24)} d${o%24?` ${o%24} h`:""}`}function Rm(e,t=[],n=!1){const r=new Set(e.capabilities),o=e.status,l=$S(e,t),u=(p,y,w)=>n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:r.has(p)?o==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:y?{enabled:!0}:{enabled:!1,reason:w}:{enabled:!1,reason:"Not permitted for this automation."},c=o==="active"||o==="paused",f=o==="active"?"pause":"resume";return{active:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:o==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:c?r.has(f)?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."}:{enabled:!1,reason:"The automation has ended."},pause:u("pause",o==="active",o==="paused"?"Already paused.":"The automation has ended."),resume:u("resume",o==="paused",o==="active"?"Already running on schedule.":"The automation has ended."),run_now:u("run_now",c&&!l,l?"An occurrence is in progress.":"The automation has ended."),stop_current:u("stop_current",l,"Nothing is running."),revise:u("revise",!0,""),archive:u("archive",!0,""),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 AS(e){return e.status==="active"?Po.pause:Po.resume}function TS(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 MS(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=TS(t),r=`${t.attempts} ${t.attempts===1?"attempt":"attempts"}`,o=n==="failed"?`Failed after ${r}`:n==="waiting"?"Waiting for you":n==="notified"?"Notified":n==="running"?"Running":null,l=t.status==="completed"&&t.attempts>1?`completed after ${r}`:t.status;return{row:t,tone:n,notable:n==="failed"||n==="waiting"||n==="notified",badge:o,statusText:l,canDiscuss:!ES.has(t.status)}})}function RS(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function ox(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 LS={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 Lm(e){return{title:LS[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function Ig(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 ax(e,t){const n=e.trigger,r=n.source_id==="schedule"||s_(n)?n.config.every:void 0,o=t?t.target.input_data.prompt:void 0;return{title:e.title,every:typeof r=="string"?r:null,context:e.context_mode,prompt:typeof o=="string"?o:null,toolApproval:t?t.policy.tool_approval:null,notifyEmail:t?sx(t.notify):null,emailRecipients:t?kS(t.policy.email_allowed_recipients):null}}function IS(e,t,n){const r=[],o={},l=t.title.trim();l?l.length>120?r.push("Title is at most 120 characters."):l!==e.title&&(o.title=l):r.push("Title is required.");const u=ax(e,n);if(t.every!==u.every&&t.every!==null){const c=s_(e.trigger);if(!Yf(t.every))r.push("Interval must be a whole number of minutes, hours or days.");else if(c&&(ex(t.every)??0)<Xv)r.push("The check interval is at least 60 seconds.");else{const f={...e.trigger.config,every:t.every};c&&delete f.start_at,o.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:f}}}if(t.context!==e.context_mode&&(o.context={mode:t.context}),n&&typeof u.prompt=="string"&&typeof t.prompt=="string"&&t.prompt.trim()!==u.prompt.trim()){const c=t.prompt.trim();c?o.target={bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:{...n.target.input_data,prompt:c}}:r.push("Task is required.")}if(n&&t.toolApproval&&t.toolApproval!==u.toolApproval&&(o.policy={tool_approval:t.toolApproval}),n&&typeof t.notifyEmail=="boolean"&&t.notifyEmail!==u.notifyEmail&&(o.notify=nx(t.notifyEmail)),n&&t.emailRecipients){const c=Up(t.emailRecipients),f=Up(u.emailRecipients??Lg).recipients;c.errors.length?r.push(...c.errors):JSON.stringify(c.recipients)!==JSON.stringify(f)&&(o.policy={...o.policy??{},email_allowed_recipients:c.recipients})}return r.length?{errors:r}:Object.keys(o).length?o:null}const OS=[{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 K_(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 PS(e){const t=e.trim().split(`
53
+ `)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}function DS(e){const t=[],n={};if(e.when.kind==="once"){const o=K_(e.when.at);return o?n.start_at=o:t.push("Pick the date and time (UTC) to run once."),{config:n,errors:t}}const r=e.when.amount;if(!Number.isInteger(r)||r<1?t.push("The interval must be a whole number of at least 1."):n.every=`${r}${e.when.unit}`,e.startAt){const o=K_(e.startAt);o?n.start_at=o:t.push("First run must be a date and time (UTC).")}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 o=K_(e.until);o?n.until=o:t.push("Stop at must be a date and time (UTC).")}return{config:n,errors:t}}function Wp(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 o=(e.title??"").trim()||PS(r);o.length>120&&n.push("Title is at most 120 characters.");const l=e.trigger==="email",u=l?SS(e.email??Qv):DS(e);n.push(...u.errors);const c=e.emailRecipients&&e.emailRecipients.mode==="list"?Up(e.emailRecipients):null;if(c&&n.push(...c.errors),n.length||!t.target)return{ok:!1,errors:n};const f={...t.target,input_data:{...t.target.input_data??{},prompt:r}},_={request_id:t.requestId,title:o,target:f,trigger:l?{source_id:Yv,source_version:Jv,config:u.config}:{source_id:"schedule",source_version:1,config:u.config},context:{mode:e.context},policy:{tool_approval:e.toolApproval??"auto",...c?{email_allowed_recipients:c.recipients}:{}}};return e.notifyEmail===!0&&(_.notify=nx(!0)),{ok:!0,body:_}}const FS="Tools run without asking (you approve them now by creating this automation)";function zS(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 BS(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 lx={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class US{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||WS(n.error))&&this.open.delete(t)}}function WS(e){return Ig(e)&&e.status>0&&e.code!=="invalid_response"}function qS(){return n_()}class HS{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 Ly(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}function qp(e){if(r_(e.status))return null;const t=Bt.not_set_up,n=Bt.open_my_email,r=t.endsWith(n)?t.slice(0,t.length-n.length):`${t} `,o=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,o?s.jsxs("span",{className:"af-email__cause",children:[" (",o,")"]}):null]})}function VS(e){const t=e.value,n=c=>e.onChange({...t,...c}),r=c=>`${e.idBase}-email-${c}`,o=Yf(Rg(t.usesModel)),l=t.every??(o&&o.unit==="s"?{amount:Math.max(1,Math.round(o.amount/60)),unit:"m"}:{amount:o?o.amount:1,unit:o?o.unit:"h"}),u=e.disabled===!0;return s.jsxs("div",{className:"af-email__trigger","data-field":"email-trigger",children:[s.jsxs("div",{className:"af-auto__row",children:[s.jsx("span",{children:Bt.every_label}),s.jsx("input",{type:"number",min:1,step:1,value:String(l.amount),disabled:u,"aria-label":"Check interval amount",name:"email_every_amount",onChange:c=>n({every:{amount:Number(c.target.value),unit:l.unit}})}),s.jsxs("select",{value:l.unit,disabled:u,"aria-label":"Check interval unit",name:"email_every_unit",onChange:c=>n({every:{amount:l.amount,unit:c.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:Bt.interval_rule}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("batch"),children:[s.jsx("span",{children:Bt.max_batch_label}),s.jsx("input",{id:r("batch"),name:"email_max_batch",type:"number",min:1,max:zp,step:1,disabled:u,value:String(t.maxBatch??Mg),onChange:c=>n({maxBatch:c.target.value.trim()===""?null:Number(c.target.value)})})]}),s.jsx("p",{className:"af-auto__hint",children:Bt.max_batch_hint}),s.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:u,children:[s.jsx("legend",{children:Bt.filters_legend}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("from"),children:[s.jsx("span",{children:Bt.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:c=>n({fromIn:c.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("domain"),children:[s.jsx("span",{children:Bt.from_domain_in}),s.jsx("input",{id:r("domain"),name:"email_from_domain_in",value:t.fromDomainIn,spellCheck:!1,placeholder:"example.com",onChange:c=>n({fromDomainIn:c.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("to"),children:[s.jsx("span",{children:Bt.to_in}),s.jsx("input",{id:r("to"),name:"email_to_in",value:t.toIn,spellCheck:!1,onChange:c=>n({toIn:c.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("subject"),children:[s.jsx("span",{children:Bt.subject_contains}),s.jsx("input",{id:r("subject"),name:"email_subject_contains",value:t.subjectContains,maxLength:200,onChange:c=>n({subjectContains:c.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("attach"),children:[s.jsx("span",{children:Bt.has_attachment}),s.jsxs("select",{id:r("attach"),name:"email_has_attachment",value:t.hasAttachment,onChange:c=>n({hasAttachment:c.target.value}),children:[s.jsx("option",{value:"any",children:Bt.has_attachment_any}),s.jsx("option",{value:"yes",children:Bt.has_attachment_yes}),s.jsx("option",{value:"no",children:Bt.has_attachment_no})]})]}),s.jsx("p",{className:"af-auto__hint",children:Bt.list_hint})]})]})}function GS(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(Ta,{variant:"row",action:"notify-email",label:Bt.notify_label,checked:e.notifyEmail,unavailableReason:n?"Connect a mailbox first.":null,onChange:r=>e.onNotifyEmailChange(r)}),s.jsx("p",{className:"af-auto__hint",children:Bt.notify_hint}),s.jsxs("fieldset",{className:"af-auto__field",disabled:n,"data-field":"email-recipients",children:[s.jsx("legend",{children:Bt.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"})})," ",Bt.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"})})," ",Bt.recipients_list]}),e.recipients.mode==="list"?s.jsx("textarea",{name:"email_recipient_list","aria-label":Bt.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:Bt.recipients_hint})]})]})}const KS={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function cx(e){const t=String(e.status),n=KS[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:wS[t]??t}),n?s.jsx(Qe,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const Hp="Discuss — fork at this occurrence (own workspace, automation files read-only)",i_=e=>s.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function YS(e){return Ig(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function Iy(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return s.jsx("code",{className:"af-auto__path-text",children:t.map((n,r)=>s.jsxs(ve.Fragment,{children:[n,r<t.length-1?s.jsx("wbr",{}):null]},r))})}function JS(e,t){const n=e.trigger,r=t.find(o=>o.id===n.source_id&&o.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 XS(e){const t=e.summary,n=rx(t),r=JS(t,e.triggerSources),o=t.next_fire_at?`${Ca(t.next_fire_at)} (${ix(t.next_fire_at,e.nowMs??Date.now())})`:t.status==="paused"?"none while paused":"none scheduled";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(cx,{status:t.status}),t.legacy?s.jsx("span",{className:"af-auto__legacy",children:"Legacy schedule"}):null]}),s.jsxs("dl",{className:"af-auto__facts",children:[s.jsx("dt",{children:"When"}),s.jsxs("dd",{"data-fact":"trigger",children:[Tg(t.trigger),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:Kv(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:o}),s.jsx("dt",{children:"Runs"}),s.jsx("dd",{"data-fact":"count",children:t.occurrence_count}),t.workspace_root?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Workspace"}),s.jsx("dd",{"data-fact":"workspace",className:"af-auto__workspace",children:e.onOpenWorkspace?s.jsxs("button",{type:"button",className:"af-auto__path","data-action":"open-workspace",title:`Browse the automation's folder
54
+ ${t.workspace_root}`,"aria-label":`Browse the automation's folder ${t.workspace_root}`,onClick:()=>{var l;return(l=e.onOpenWorkspace)==null?void 0:l.call(e,t.automation_id)},children:[s.jsx(Qe,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(Iy,{path:t.workspace_root})]}):s.jsxs("span",{className:"af-auto__path af-auto__path--static",children:[s.jsx(Qe,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(Iy,{path:t.workspace_root})]})})]}):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:ox(t)}),t.revision!==null?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Revision"}),s.jsx("dd",{"data-fact":"revision",children:t.revision})]}):null]})]})}function ZS(e){const t=e.definition,n=e.renderText??i_,r=t.target.input_data.prompt,o=t.policy.retry,l=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:"Definition"}),s.jsxs("span",{className:"af-auto__definition-meta",children:["revision ",t.revision]})]}),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," · ",Tg(t.trigger),s.jsx("pre",{className:"af-auto__json",children:JSON.stringify(t.trigger.config,null,2)})]}),s.jsx("dt",{children:"Context"}),s.jsx("dd",{"data-def":"context",children:Kv(t.context.mode)}),s.jsx("dt",{children:"Tools"}),s.jsx("dd",{"data-def":"tool_approval",children:l==="ask"?"Ask before each tool call (ask)":l==="auto"?"Run without asking (auto)":String(l)}),s.jsx("dt",{children:"Notify"}),s.jsx("dd",{"data-def":"notify",children:CS(t.notify)}),s.jsx("dt",{children:"May email"}),s.jsx("dd",{"data-def":"email_allowed_recipients",children:NS(t.policy.email_allowed_recipients)}),s.jsx("dt",{children:"Retries"}),s.jsxs("dd",{"data-def":"retry",children:[o.max_attempts," ",o.max_attempts===1?"attempt":"attempts",", backoff ",o.backoff.initial," ×",o.backoff.factor," up to ",o.backoff.max]}),s.jsx("dt",{children:"Revision"}),s.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const Jf=Hv,Oo=Jf.labels,ro={active:"play",pause:"pause",resume:"play",run_now:Jf.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",discuss:"chat"},Vp=Jf.hints,QS=Jf.run_now_next_run_line,ek=Jf.run_now_growing_line;function Im(e,t){const n=[Vp[e]];return e==="run_now"&&t&&(t.next_fire_at&&n.push(QS.replace("{time}",Ca(t.next_fire_at))),t.context_mode==="growing"&&n.push(ek)),n.join(`
55
+ `)}function tk(e,t,n){const r=new Map;for(const u of t){const c=e[u];if(c.enabled)continue;const f=c.reason??"Not available now.";r.set(f,[...r.get(f)??[],u])}const o=[],l={};return[...r.entries()].forEach(([u,c],f)=>{const _=`${n}-why-${f}`;o.push({id:_,text:`${c.map(p=>Oo[p]).join(", ")}: ${u}`});for(const p of c)l[p]=_}),{lines:o,describedBy:l}}function hr(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 nk(e){const t=Rm(e.summary,e.occurrences,e.busy),r=tk(t,["active","run_now","stop_current","revise","archive"],e.idBase??`af-auto-${e.summary.automation_id}`),o=(l,u,c)=>{const f=Im(l,e.summary);return s.jsx("button",{type:"button",className:`af-auto__btn${c!=null&&c.danger?" af-auto__btn--danger":""}`,"data-action":(c==null?void 0:c.action)??l,disabled:!t[l].enabled,title:t[l].enabled?f:`${t[l].reason}
56
+ ${f}`,"aria-description":f,"aria-describedby":r.describedBy[l],"aria-pressed":c==null?void 0:c.pressed,onClick:u,children:s.jsx(hr,{icon:ro[l],label:(c==null?void 0:c.label)??Oo[l]})},l)};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(Ta,{className:"af-auto__switch",action:"active",label:Oo.active,checked:e.summary.status==="active",unavailableReason:t.active.enabled?null:t.active.reason??"Not available now.",describedBy:r.describedBy.active,busy:e.busy,hint:Im("active",e.summary),onChange:()=>e.onCommand(AS(e.summary))},"active"),o("run_now",()=>e.onCommand(Po.run_now)),o("stop_current",()=>e.onCommand(Po.stop_current)),o("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),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})]}),r.lines.length?s.jsxs("p",{className:"af-auto__reasons",children:[s.jsx(Qe,{name:"info",size:12,className:"af-auto__reasons-icon"}),r.lines.map(l=>s.jsx("span",{id:l.id,children:l.text},l.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?s.jsxs("div",{className:"af-auto__confirm",role:"group","aria-label":"Confirm archive",children:[s.jsxs("p",{children:["Archive “",e.summary.title,"”? Its history stays readable; it will not run again. The current run, if any, finishes."]}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"archive-confirm",disabled:!t.archive.enabled,onClick:()=>e.onCommand(Po.archive),children:s.jsx(hr,{icon:"archive",label:"Archive"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:s.jsx(hr,{icon:"x",label:"Keep it"})})]})]}):null]})}const Oy=[["m","minutes"],["h","hours"],["d","days"]];function sk(e,t){const n=C=>{const N=e.elements.namedItem(C);return N&&typeof N.value=="string"?N.value:null},r=n("every_amount"),o=n("every_unit"),l=r!==null&&o!==null?`${r.trim()}${o}`:t.every,u=e.elements.namedItem("context"),c=u&&(u.value==="growing"||u.value==="independent")?u.value:t.context,f=n("prompt"),_=e.elements.namedItem("tool_approval"),p=_&&(_.value==="auto"||_.value==="ask")?_.value:t.toolApproval??null,y=e.elements.namedItem("notify_email"),w=y&&typeof y.checked=="boolean"?y.checked:t.notifyEmail??null,x=e.elements.namedItem("email_recipients"),S=n("email_recipient_list"),j=x&&(x.value==="self"||x.value==="list")?{mode:x.value,addresses:S??""}:t.emailRecipients??null;return{title:n("title")??t.title,every:l,context:c,prompt:f??t.prompt??null,toolApproval:p,notifyEmail:w,emailRecipients:j}}function rk(e){const t=ax(e.summary,e.definition),n=t.every?Yf(t.every):null,r=n&&n.unit==="s"?[["s","seconds"],...Oy]:Oy,o=`af-auto-revise-${e.summary.automation_id}`,l=r_(e.emailStatus),u=s_(e.summary.trigger);return s.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${o}-heading`,onSubmit:c=>{c.preventDefault(),e.onSubmit(sk(c.currentTarget,t))},onKeyDown:c=>{c.key==="Escape"&&(c.preventDefault(),e.onCancel())},children:[s.jsxs("h3",{className:"af-auto__form-title",id:`${o}-heading`,children:[s.jsx(Qe,{name:"edit",size:14})," Edit automation"]}),s.jsxs("label",{className:"af-auto__field",htmlFor:`${o}-title`,children:[s.jsx("span",{children:"Title"}),s.jsx("input",{id:`${o}-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:`${o}-prompt`,children:[s.jsx("span",{children:"Task"}),s.jsx("textarea",{id:`${o}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
57
+ `).length+1)),required:!0})]}):null,n?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:u?Bt.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:r.map(([c,f])=>s.jsx("option",{value:c,children:f},c))})]}),u?s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:Bt.interval_rule}):null]}):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"})," Independent — each run starts fresh"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing"})," Growing — each run sees the previous runs"]})]}),t.toolApproval?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Tools"}),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"}),l?null:s.jsx(qp,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),s.jsx($j,{variant:"row",action:"notify-email",name:"notify_email",label:Bt.notify_label,defaultChecked:!!t.notifyEmail,unavailableReason:!l&&!t.notifyEmail?"Connect a mailbox first.":null}),s.jsx("p",{className:"af-auto__hint",children:Bt.notify_hint}),s.jsxs("fieldset",{className:"af-auto__field","data-field":"email-recipients",children:[s.jsx("legend",{children:Bt.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",Bt.recipients_self]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"list",defaultChecked:t.emailRecipients.mode==="list",disabled:!l&&t.emailRecipients.mode!=="list"})," ",Bt.recipients_list]}),s.jsx("textarea",{name:"email_recipient_list","aria-label":Bt.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!l&&t.emailRecipients.mode!=="list"}),s.jsx("p",{className:"af-auto__hint",children:Bt.recipients_hint})]})]}):null,s.jsx("p",{className:"af-auto__hint",children:"Changes apply from the next run; a new interval never fires past ticks."}),e.errors.length?s.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:e.errors.map(c=>s.jsx("li",{children:c},c))}):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(hr,{icon:"check",label:"Save changes"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"edit-cancel",onClick:e.onCancel,children:s.jsx(hr,{icon:"x",label:"Cancel"})})]})]})}function Gp(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function ik(e){const t=e.wait,n=`${e.idBase}-${t.run_id}-${t.wait_key}-prompt`,r=u=>e.onAnswerWait(t.run_id,t.wait_key,u),o=e.renderText??i_,l=u=>s.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[s.jsx("span",{className:"af-auto-wait__kind",children:lx[t.kind]??"Waiting"}),t.prompt?o(t.prompt):s.jsxs("span",{children:[" ",u]})]});if(t.kind==="tool_approval"){const u=zS(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:[l("A tool call needs your approval."),u&&u.length?s.jsx("ul",{className:"af-auto-wait__calls","aria-label":"Tool calls to approve",children:u.map((c,f)=>s.jsxs("li",{"data-tool":c.name,children:[s.jsx("code",{className:"af-auto-wait__tool",children:c.name}),s.jsx("pre",{className:"af-auto-wait__args",children:JSON.stringify(c.arguments,null,2)})]},c.call_id??`${c.name}:${f}`))}):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(hr,{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(hr,{icon:"x",label:"Deny"})})]})]})}return t.kind==="event"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--event","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{var f;u.preventDefault();const c=BS(Gp(u.currentTarget,"payload"));c.ok?r({payload:c.payload}):(f=e.onWaitError)==null||f.call(e,c.error)},children:[l("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(hr,{icon:"send",label:"Send event"})})})]}):t.kind==="ask_user"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--ask_user","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{u.preventDefault();const c=Gp(u.currentTarget,"response");c&&r({response:c})},children:[l("The run is waiting for your input."),t.choices&&t.choices.length?s.jsx("div",{className:"af-auto__row",role:"group","aria-label":"Choices",children:t.choices.map(u=>s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"wait-choice",disabled:e.busy,onClick:()=>r({response:u}),children:u},u))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("input",{name:"response","aria-label":"Your answer",placeholder:"Your answer",disabled:e.busy}),s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-answer",disabled:e.busy,children:s.jsx(hr,{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:[l("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 ok(e){const{row:t,tone:n,badge:r,statusText:o}=e.view,l=`af-auto-occ-${t.run_id}`,u=e.renderText??i_,c=e.discuss.enabled&&e.view.canDiscuss&&!e.busy,f=e.discuss.enabled?e.view.canDiscuss?null:"Available once this occurrence finishes.":e.discuss.reason??"Not available.",_=(w,x)=>e.renderTurn?e.renderTurn({kind:w,role:w==="trigger"?"user":"assistant",text:x,index:t.index,runId:t.run_id}):u(x),p=e.renderTurn?" af-auto-turn--card":"",y=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":`${l}-h`,children:[s.jsxs("div",{className:`af-auto-turn af-auto-turn--trigger${p}`,"data-turn":"trigger",children:[s.jsxs("div",{className:"af-auto-turn__meta",id:`${l}-h`,children:[s.jsxs("span",{className:"af-auto-turn__index",children:["#",t.index]})," · ",t.trigger.summary," · fired ",Ca(t.fired_at)]}),s.jsx("div",{className:"af-auto-turn__text",children:_("trigger",t.user_turn)})]}),s.jsxs("div",{className:`af-auto-turn af-auto-turn--answer${p}`,"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:o}),t.finished_at?s.jsxs("span",{children:[" · ",Ca(t.finished_at)]}):null]}),t.notify?s.jsxs("div",{className:"af-auto-notify","data-notify":"true",children:[s.jsx("strong",{children:t.notify.title}),t.notify.body?s.jsx("div",{className:"af-auto-notify__body",children:u(t.notify.body)}):null]}):null,t.failure?s.jsxs("div",{className:"af-auto-failure","data-failure":t.failure.reason_code,children:[s.jsx("strong",{children:t.failure.reason_code}),": ",t.failure.message," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["(after ",t.failure.attempts," ",t.failure.attempts===1?"attempt":"attempts",")"]})]}):null,t.answer?s.jsx("div",{className:"af-auto-turn__text",children:_("answer",t.answer)}):s.jsx("div",{className:"af-auto-turn__empty",children:y}),t.artifacts.length?s.jsx("ul",{className:"af-auto-artifacts","aria-label":"Artifacts",children:t.artifacts.map(w=>s.jsxs("li",{children:[e.onOpenResource?s.jsxs("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-artifact",onClick:()=>{var x;return(x=e.onOpenResource)==null?void 0:x.call(e,{kind:"artifact",url:w.url,name:w.name,mimeType:w.mime_type,runId:t.run_id})},children:[s.jsx(Qe,{name:"file",size:13,className:"af-auto__btn-icon"})," ",w.name]}):s.jsx("span",{className:"af-auto-artifact__name",children:w.name})," ",s.jsx("span",{className:"af-auto-turn__muted",children:w.mime_type})]},w.artifact_id))}):null,t.waits.map(w=>s.jsx(ik,{wait:w,busy:e.busy,idBase:l,onAnswerWait:e.onAnswerWait,onWaitError:e.onWaitError,renderText:e.renderText},`${w.run_id}:${w.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(hr,{icon:"list",label:"Open run ledger"})}),e.onOpenResource?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-ledger-json",onClick:()=>{var w;return(w=e.onOpenResource)==null?void 0:w.call(e,{kind:"ledger",url:t.ledger_url,name:`run-${t.run_id}-ledger.json`,runId:t.run_id})},children:s.jsx(hr,{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 w;return(w=e.onOpenWorkspace)==null?void 0:w.call(e,t.run_id)},children:s.jsx(hr,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?s.jsxs("form",{className:"af-auto-discuss","aria-label":`${Hp}, from occurrence ${t.index}`,onSubmit:w=>{w.preventDefault();const x=Gp(w.currentTarget,"prompt");x&&e.onDiscussSubmit(t.index,x)},children:[s.jsxs("p",{className:"af-auto__hint",children:["Starts a new session that forks this automation at #",t.index," with its full history (runs 1–",t.index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation's session."]}),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(hr,{icon:"send",label:"Start discussion"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:s.jsx(hr,{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:!c,title:Vp.discuss,"aria-description":Vp.discuss,"aria-describedby":f?`${l}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:s.jsx(hr,{icon:ro.discuss,label:Hp})}),f?s.jsx("span",{className:"af-auto__reasons",id:`${l}-discuss-why`,children:f}):null]})]})]})}const ak=5e3,lk={[Po.pause]:"Automation paused.",[Po.resume]:"Automation active.",[Po.run_now]:"Run requested.",[Po.stop_current]:"Stop requested."};function ck(e){const{summary:t,busy:n}=e,r=e.renderText??i_,o=m.useId(),l=m.useRef(null),[u,c]=m.useState(!1),f=e.editOpen!==void 0,p=Rm(t,e.occurrences,!1).revise.enabled&&(f?e.editOpen===!0:u),y=m.useRef(null);p?(!y.current||y.current.summary.automation_id!==t.automation_id)&&(y.current={summary:t,definition:e.definition}):y.current=null;const w=y.current,x=m.useRef(e.onEditOpenChange);x.current=e.onEditOpenChange;const S=X=>{var le;f||c(X),(le=x.current)==null||le.call(x,X)},[j,C]=m.useState([]),[N,T]=m.useState(!1),[L,P]=m.useState(null),[W,G]=m.useState(null),[Y,J]=m.useState(null);m.useEffect(()=>{if(!Y)return;const X=setTimeout(()=>J(null),ak);return()=>clearTimeout(X)},[Y]),m.useEffect(()=>{var le;if(!p)return;C([]);const X=Ly(l.current,['.af-auto__revise [name="title"]']);X==null||X.focus(),(le=X==null?void 0:X.scrollIntoView)==null||le.call(X,{block:"nearest"})},[p,t.automation_id]);const[re,ae]=m.useState(null);m.useEffect(()=>{var X;re&&((X=Ly(l.current,[...re,".af-auto__notice",".af-auto__title"]))==null||X.focus(),ae(null))},[re]);const ue=m.useRef(null);ue.current||(ue.current=new US(e.newId??qS));const B=ue.current,A=X=>G(YS(X)),$=(X,le,_e)=>{G(null),J(null),le(B.idFor(X)).then(he=>{B.settle(X,{ok:!0}),_e(he)},he=>{B.settle(X,{ok:!1,error:he}),A(he)})},z=RS(t),E=m.useRef(e.onSeen);E.current=e.onSeen;const te=m.useRef(null);te.current||(te.current=new HS),m.useEffect(()=>{const X=te.current,le=z?`${t.automation_id}|${z}`:null;if(!z||!X.next(le,t))return;const _e=t;E.current(z).then(()=>X.succeeded(le),he=>{X.failed(le,_e),A(he)})});const O=Rm(t,e.occurrences,n),F=MS(e.occurrences),K=t.occurrence_count-e.occurrences.length,R=W??e.error??null,Q=R?Lm(R):null,Z=t.attention;return s.jsxs("section",{ref:l,className:`af-auto${e.className?` ${e.className}`:""}`,"aria-labelledby":o,"aria-busy":n,"data-text-rendering":e.renderText?"rich":"unformatted",children:[s.jsx(XS,{summary:t,triggerSources:e.triggerSources,titleId:o,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace}),s.jsx(nk,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:N,reviseOpen:p,notice:Y,onDismissNotice:()=>J(null),idBase:`${o}-ctl`,onCommand:X=>$(`command:${X}`,le=>e.onCommand(X,void 0,{command_id:le}),()=>{X===Po.archive?(T(!1),J("Archive requested."),ae(['[data-action="archive"]'])):J(lk[X]??"Command sent.")}),onToggleRevise:()=>{C([]),S(!p)},onAskArchive:()=>T(!0),onCancelArchive:()=>{T(!1),ae(['[data-action="archive"]'])}}),p&&w?s.jsx(rk,{summary:w.summary,definition:w.definition,busy:n,errors:j,emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,onCancel:()=>{S(!1),ae(['[data-action="edit"]'])},onSubmit:X=>{const le=w.summary,_e=IS(le,X,w.definition);if(_e===null){C(["Nothing changed."]);return}if("errors"in _e){C(_e.errors);return}C([]),$(`revise:${le.revision}:${JSON.stringify(_e)}`,he=>e.onRevise(_e,le.revision,{command_id:he}),()=>{J("Saved; applies from the next run."),S(!1),ae(['[data-action="edit"]'])})}}):e.definition?s.jsx(ZS,{definition:e.definition,renderText:r}):null,Q?s.jsxs("div",{className:"af-auto__error",role:"alert","data-code":R==null?void 0:R.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:Q.title})," ",s.jsx("span",{children:Q.detail})]}),W?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:()=>G(null),children:s.jsx(Qe,{name:"x",size:12})}):null]}):null,Z.items.length||Z.waits.length?s.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:s.jsxs("ul",{children:[Z.items.map(X=>s.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${X.kind}`,"data-cursor":X.cursor,children:[s.jsx("span",{className:`af-auto-badge af-auto-badge--${X.kind==="failure"?"failed":"notified"}`,children:X.kind==="failure"?"Failed":"Notified"})," ",s.jsx("strong",{children:X.title})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",X.index," · ",Ca(X.at)]}),X.body?s.jsx("div",{className:"af-auto__attention-body",children:r(X.body)}):null]},X.cursor)),Z.waits.map(X=>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":X.kind,children:lx[X.kind]??"Waiting for you"})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",X.index]}),X.prompt?s.jsx("div",{className:"af-auto__attention-body",children:r(X.prompt)}):null]},`${X.run_id}:${X.wait_key}`))]})}):null,K>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(hr,{icon:"history",label:`Load earlier occurrences (${K} more)`})}):null,F.length?s.jsx("ol",{className:"af-auto__timeline","aria-label":"Occurrences",children:F.map(X=>{const le=`[data-index="${X.row.index}"]`;return s.jsx(ok,{view:X,busy:n,discuss:O.discuss,renderText:r,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?_e=>{var he;G(null);try{Promise.resolve((he=e.onOpenResource)==null?void 0:he.call(e,_e)).catch(A)}catch(ye){A(ye)}}:void 0,discussOpen:L===X.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(_e,he,ye)=>{G(null),e.onAnswerWait(_e,he,ye).then(()=>J("Answer sent."),A)},onWaitError:_e=>G({status:0,code:"invalid_payload",message:_e}),onDiscussOpen:P,onDiscussCancel:()=>{P(null),ae([`${le} [data-action="discuss"]`])},onDiscussSubmit:(_e,he)=>$(`discuss:${_e}:${he}`,ye=>e.onDiscuss(_e,he,{request_id:ye}),ye=>{P(null),J(`Discussion started (session ${ye.session_id}).`),ae([`${le} [data-action="discuss"]`])})},X.row.run_id)})}):s.jsx("p",{className:"af-auto__empty",children:"No occurrences yet."})]})}async function ux(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 o=document.execCommand("copy")===!0;return document.body.removeChild(r),o}catch{return!1}}const uk=3,dk=Number.MAX_SAFE_INTEGER;function dx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function fx(e){return Array.isArray(e)}function fk(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 hk(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Bu({kind:e,children:t}){return s.jsx("span",{className:`json-token ${e}`,children:t})}function mk(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[r,o]=m.useState(!n||e.expansion_mode==="unfolded");return m.useEffect(()=>{n&&o(e.expansion_mode==="unfolded")},[n,e.expansion_mode,e.expansion_version]),n?s.jsxs("span",{className:`json-string ${r?"open":"collapsed"}`,children:[s.jsx("button",{type:"button",className:"json-string__toggle",onClick:()=>o(l=>!l),"aria-label":r?"Collapse string value":"Expand string value","aria-expanded":r,children:r?"▾":"▸"}),r?s.jsx("span",{className:"json-token string json-string__value",children:t}):s.jsxs("button",{type:"button",className:"json-string__preview",onClick:()=>o(!0),"aria-label":"Expand string value",children:[s.jsx("span",{className:"json-token string json-string__preview_text",children:t}),s.jsx("span",{className:"json-string__suffix",children:"(...)"})]})]}):s.jsx(Bu,{kind:"string",children:t})}function _k(e,t,n){return e===null?s.jsx(Bu,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(mk,{value:e,expansion_mode:t,expansion_version:n}):typeof e=="number"?s.jsx(Bu,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx(Bu,{kind:"boolean",children:e?"true":"false"}):s.jsx(Bu,{kind:"string",children:JSON.stringify(String(e))})}function pk(e){return fx(e)?e.length===1?"1 item":`${e.length} items`:dx(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function hx(e){const{label:t,value:n,depth:r,collapse_after_depth:o,expansion_mode:l,expansion_version:u,trailing_comma:c}=e,f=r*14,_=dx(n),p=fx(n),y=_||p,w=r<o,[x,S]=m.useState(w);m.useEffect(()=>{S(w)},[w,u]);const j=t?s.jsxs(s.Fragment,{children:[s.jsx(Bu,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!y)return s.jsxs("div",{className:"json-viewer__line",style:{paddingLeft:f},children:[j,_k(n,l,u),c?",":""]});const C=p?"[":"{",N=p?"]":"}",T=pk(n),L=x?`${C}`:`${C}…${N}${T?` (${T})`:""}`,P=p?n.map((W,G)=>({key:String(G),label:void 0,value:W})):Object.entries(n).map(([W,G])=>({key:W,label:W,value:G}));return s.jsxs("details",{className:"json-viewer__details",open:x,onToggle:W=>S(W.currentTarget.open),children:[s.jsxs("summary",{className:"json-viewer__summary",style:{paddingLeft:f},children:[j,s.jsx("span",{className:"json-viewer__caret","aria-hidden":"true",children:x?"▾":"▸"}),s.jsx("span",{className:"json-viewer__punct",children:L}),!x&&c?s.jsx("span",{className:"json-viewer__punct",children:","}):null]}),x?s.jsx("div",{className:"json-viewer__children",children:P.length===0?s.jsxs("div",{className:"json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"json-viewer__punct",children:N}),c?",":""]}):s.jsxs(s.Fragment,{children:[P.map((W,G)=>{const Y=G===P.length-1;return s.jsx(hx,{label:W.label,value:W.value,depth:r+1,collapse_after_depth:o,expansion_mode:l,expansion_version:u,trailing_comma:!Y},`${r}:${t||"root"}:${W.key}`)}),s.jsxs("div",{className:"json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"json-viewer__punct",children:N}),c?",":""]})]})}):null]})}function mx(e){const{value:t,className:n,showCopy:r=!0}=e,[o,l]=m.useState({mode:"folded",version:0}),u=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):uk,c=o.mode==="unfolded"?dk:u,f=m.useMemo(()=>typeof t=="string"?fk(t):t,[t]),_=m.useMemo(()=>hk(t),[t]),p=["json-viewer",n].filter(Boolean).join(" ");m.useEffect(()=>{l(w=>({mode:"folded",version:w.version+1}))},[f]);const y=()=>{l(w=>({mode:w.mode==="unfolded"?"folded":"unfolded",version:w.version+1}))};return s.jsxs("div",{className:p,children:[s.jsxs("div",{className:"json-viewer__toolbar",children:[s.jsx("button",{type:"button",className:"json-viewer__btn json-viewer__toggle-all",onClick:y,"aria-expanded":o.mode==="unfolded",children:o.mode==="unfolded"?"Fold all":"Unfold all"}),r?s.jsx("button",{type:"button",className:"json-viewer__btn json-viewer__copy",onClick:()=>void ux(_),children:"Copy"}):null]}),s.jsx("div",{className:"json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:s.jsx(hx,{value:f,depth:0,collapse_after_depth:c,expansion_mode:o.mode,expansion_version:o.version,trailing_comma:!1})})]})}function Y_(e){const t=[],n=String(e??"");let r=0,o="";const l=()=>{o&&(t.push(o),o="")};for(;r<n.length;){const u=n[r];if(u==="`"){const c=n.indexOf("`",r+1);if(c!==-1){l(),t.push(s.jsx("code",{children:n.slice(r+1,c)},`code:${r}`)),r=c+1;continue}}if(u==="*"&&n[r+1]==="*"){const c=n.indexOf("**",r+2);if(c!==-1){l(),t.push(s.jsx("strong",{children:n.slice(r+2,c)},`bold:${r}`)),r=c+2;continue}}o+=u,r+=1}return l(),t}function gk(e){return String(e??"").replace(/\r\n/g,`
58
+ `).replace(/\r/g,`
59
+ `).split(`
60
+ `)}function yk({text:e,className:t}){const n=gk(e),r=[];let o=0;for(;o<n.length;){const u=n[o],c=String(u??"");if(!c.trim()){o+=1;continue}if(c.trim().startsWith("```")){const w=c.trim().replace(/```/g,"").trim(),x=[];for(o+=1;o<n.length&&!String(n[o]??"").trim().startsWith("```");)x.push(String(n[o]??"")),o+=1;o<n.length&&(o+=1);const S=x.join(`
61
+ `);r.push(s.jsx("pre",{className:"mf-md_pre",children:s.jsx("code",{className:w?`language-${w}`:void 0,children:S})},`pre:${o}`));continue}const f=c.match(/^(#{1,3})\s+(.*)$/);if(f){const y=f[1].length,w=f[2]||"",x=Y_(w);y===1?r.push(s.jsx("h1",{children:x},`h1:${o}`)):y===2?r.push(s.jsx("h2",{children:x},`h2:${o}`)):r.push(s.jsx("h3",{children:x},`h3:${o}`)),o+=1;continue}const _=y=>{const w=y.trimStart();return w.startsWith("- ")||w.startsWith("* ")};if(_(c)){const y=[];for(;o<n.length&&_(String(n[o]??""));){const w=String(n[o]??"").trimStart();y.push(w.slice(2)),o+=1}r.push(s.jsx("ul",{className:"mf-md_ul",children:y.map((w,x)=>s.jsx("li",{children:Y_(w)},`li:${o}:${x}`))},`ul:${o}`));continue}const p=[];for(;o<n.length&&String(n[o]??"").trim();)p.push(String(n[o]??"")),o+=1;r.push(s.jsx("p",{className:"mf-md_p",children:p.map((y,w)=>s.jsxs(ve.Fragment,{children:[Y_(y),w<p.length-1?s.jsx("br",{}):null]},`pl:${o}:${w}`))},`p:${o}`))}const l=["mf-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:l,children:r})}const Py="observe";function Tr(e){return!e||typeof e!="object"?null:e}function Kp(e,t){const n=String(e||"").replace(/\s+/g," ").trim();return n?n.length<=t?n:`${n.slice(0,Math.max(0,t-1)).trimEnd()}…`:""}function Dy(e){const t=Tr(e);if(!t)return null;const n=typeof t.role=="string"?String(t.role).trim():"",r=typeof t.content=="string"?String(t.content):"";if(!n||r==="")return null;const o=typeof t.name=="string"?String(t.name).trim():"";return{role:n,content:r,name:o||void 0}}function wk(e){if(Array.isArray(e)){if(e.length===0)return null;const n=[];for(const r of e){const o=Dy(r);if(!o)return null;n.push(o)}return n}const t=Dy(e);return t?[t]:null}function vk(e){const t=String(e||"").trim();if(!t)return null;const n=t[0],r=t[t.length-1];if(!(n==="{"&&r==="}"||n==="["&&r==="]"))return null;try{const l=JSON.parse(t);return l&&typeof l=="object"||Array.isArray(l)?l:null}catch{return null}}function xk(e){const t=String(e||"");return t.trim()?!!(t.includes("```")||/\n\s*#{1,3}\s+/.test(t)||/\n\s*[-*]\s+/.test(t)||/\n\s*\d+[\.\)]\s+/.test(t)||t.includes("**")||t.includes("`")):!1}function Fy({text:e}){const t=String(e||""),n=vk(t);if(n!==null)return s.jsx(mx,{value:n});const r=t.trim();return r.startsWith("{")||r.startsWith("[")?s.jsx("pre",{className:"run-details-output",children:t||"(none)"}):t.includes(`
62
+ `)||xk(t)?s.jsx("div",{className:"run-details-output",children:s.jsx(yk,{text:t})}):s.jsx("pre",{className:"run-details-output",children:t||"(none)"})}function _x({value:e}){if(e==null)return s.jsx("pre",{className:"run-details-output",children:"(none)"});const t=wk(e);return t?s.jsx("div",{className:"mf-msg-list",children:t.map((n,r)=>s.jsxs("div",{className:"mf-msg",children:[s.jsxs("div",{className:"mf-msg-meta",children:[s.jsx("span",{className:`mf-msg-role ${n.role}`,children:n.role}),n.name?s.jsx("span",{className:"mf-msg-name",children:n.name}):null]}),s.jsx("div",{className:"mf-msg-content",children:s.jsx(Fy,{text:n.content})})]},`${n.role}:${r}`))}):typeof e=="string"?s.jsx(Fy,{text:e}):s.jsx(mx,{value:e})}function px(e){const t=e.effect;return!t||typeof t!="object"?null:t}function wl(e){const t=px(e);return(t&&typeof t.type=="string"?t.type:"")||"effect"}function o_(e){const t=px(e),n=t==null?void 0:t.payload;return!n||typeof n!="object"?null:n}function Og(e){const t=e.result;return!t||typeof t!="object"?null:t}function gx(e){if(wl(e)!=="tool_calls")return[];const n=Og(e),r=n&&Array.isArray(n.results)?n.results:null;if(!r)return[];const o=[];for(const l of r){const u=Tr(l);if(!u)continue;const c=typeof u.name=="string"?u.name.trim():"";c&&o.push({call_id:typeof u.call_id=="string"?u.call_id:void 0,name:c,success:!!u.success,output:u.output,error:u.error})}return o}function yx(e){if(wl(e)!=="tool_calls")return[];const n=o_(e),r=n&&Array.isArray(n.tool_calls)?n.tool_calls:null;if(!r)return[];const o=[];for(const l of r){const u=Tr(l);if(!u)continue;const c=typeof u.name=="string"?u.name.trim():"";if(!c)continue;const f=Tr(u.args)||Tr(u.arguments)||{};o.push({call_id:typeof u.call_id=="string"?u.call_id:void 0,name:c,args:f})}return o}function a_(e){const t=e.error;if(typeof t=="string")return t.trim();const n=Tr(t);if(n){const r=typeof n.message=="string"?n.message.trim():"",o=typeof n.stack=="string"?n.stack.trim():"";return r||o||""}return""}function wx(e){if(!e)return"";const t=e.reasoning;if(typeof t=="string")return t.trim();const n=Tr(t);return n&&typeof n.text=="string"?n.text.trim():""}function vx(e){const t=wl(e),n=o_(e),r=Og(e),o=(l,u)=>{const c=String(l||"").replace(/\s+/g," ").trim();return c?c.length<=u?c:`${c.slice(0,Math.max(0,u-1)).trimEnd()}…`:""};if(t==="llm_call"){const l=r==null?void 0:r.content,u=typeof l=="string"?l.replace(/\s+/g," ").trim():"",c=wx(r),f=Array.isArray(r==null?void 0:r.tool_calls)?r.tool_calls:null,p=!!(f&&f.length>0)?c||u:u||c;return o(p,220)}if(t==="tool_calls"){const l=r&&Array.isArray(r.results)?r.results:null;if(!l)return"";const u=l.filter(c=>{var f;return((f=Tr(c))==null?void 0:f.success)===!1});return u.length>0?`${u.length} tool call(s) failed`:`${l.length} tool call(s) executed`}return t==="ask_user"&&n&&typeof n.prompt=="string"?String(n.prompt).trim():""}function Om(e){const t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||a_(e.step)?"failed":t}function bk(e){const t=e.map(n=>Om(n));return t.some(n=>n==="failed")?"failed":t.some(n=>n==="waiting")?"waiting":t.some(n=>n==="running")?"running":"completed"}function J_(e){return e.filter(t=>!t.hidden)}function jk(e){const t=wl(e),n=a_(e);return J_(t==="llm_call"?[{id:"system",label:"System"},{id:"user",label:"User"},{id:"tools",label:"Tools"},{id:"response",label:"Response"},{id:"reasoning",label:"Reasoning"},{id:"errors",label:"Errors",hidden:!n},{id:"raw",label:"Raw"}]:t==="tool_calls"?[{id:"tools",label:"Tools"},{id:"errors",label:"Errors",hidden:!n},{id:"raw",label:"Raw"}]:[{id:"errors",label:"Errors",hidden:!n},{id:"raw",label:"Raw"}])}function Sk(e){const t=wl(e);return t==="llm_call"?"user":t==="tool_calls"?"tools":a_(e)?"errors":"raw"}function kk(e){const t=new Map,n=o_(e),r=n&&Array.isArray(n.tools)?n.tools:null;if(!r)return t;for(const o of r){const l=Tr(o);if(!l)continue;const u=typeof l.name=="string"?l.name.trim():"";if(!u)continue;const f=(Array.isArray(l.parameters)?l.parameters:[]).map(_=>{const p=Tr(_);return(p&&typeof p.id=="string"?p.id.trim():"")||""}).filter(Boolean);t.set(u,f)}return t}function xx(e,t,n){const r=Object.keys(t||{}),o=n&&n.length?n.filter(f=>r.includes(f)):[],l=r.filter(f=>!o.includes(f)).sort(),u=[...o,...l],c=u.slice(0,5).map(f=>{const _=t[f];return typeof _=="string"?`${f}=${JSON.stringify(Kp(_,42))}`:typeof _=="number"||typeof _=="boolean"?`${f}=${String(_)}`:_==null?`${f}=null`:`${f}=${Kp(JSON.stringify(_),42)}`});return`${e}(${c.join(", ")}${u.length>5?", …":""})`}function Nk(e){const t=e.ts?String(e.ts):"";if(!t)return"";try{const n=new Date(t);return Number.isFinite(n.getTime())?n.toLocaleTimeString():""}catch{return""}}function X_({item:e,label:t,toolDefs:n,defaultOpen:r=!1}){const o=e.step,l=wl(o),u=jk(o),c=Sk(o),[f,_]=m.useState(c),[p,y]=m.useState(!!r),w=o_(o),x=Og(o),S=a_(o),j=Nk(e),C=e.nodeId?String(e.nodeId):"",N=e.runId?String(e.runId):"",T=l==="tool_calls"?yx(o):[],L=l==="tool_calls"?gx(o):[],P=T.map(ae=>xx(ae.name,ae.args,n.get(ae.name)||null)),G=(()=>{if(f==="raw")return o;if(f==="errors")return S||null;if(l==="llm_call"){const ae=w||{},ue=typeof ae.system_prompt=="string"?String(ae.system_prompt):"",B=typeof ae.prompt=="string"?String(ae.prompt):"",A=Tr(x==null?void 0:x.metadata),$=A?Tr(A._runtime_observability):null,z=$?Tr($.llm_generate_kwargs):null,E=z&&Array.isArray(z.messages)?z.messages:null,te=A?Tr(A._provider_request):null,O=te?Tr(te.payload):null,F=O&&Array.isArray(O.messages)?O.messages:null,K=Array.isArray(ae.messages)?ae.messages:[],R=E||F||K,Q=R.filter(X=>String((X==null?void 0:X.role)||"").trim()==="system"),Z=R.filter(X=>String((X==null?void 0:X.role)||"").trim()==="user");if(f==="system"){const X=[],le=ue.trim(),_e=!!le&&Q.some(he=>typeof(he==null?void 0:he.content)=="string"&&String(he.content).trim()===le);return le&&!_e&&X.push({role:"system",name:"system_prompt",content:ue}),X.push(...Q),X}if(f==="user"){const X=[],le=B.trim(),_e=!!le&&Z.some(he=>typeof(he==null?void 0:he.content)=="string"&&String(he.content).trim()===le);return le&&!_e&&X.push({role:"user",name:"prompt",content:B}),X.push(...Z),X}if(f==="tools")return ae.tools||[];if(f==="response"){const X=x==null?void 0:x.content;if(typeof X=="string"&&X.trim())return X;const le=x==null?void 0:x.output;if(le!==void 0)return le;const _e=Array.isArray(x==null?void 0:x.tool_calls)?x.tool_calls:null;return _e&&_e.length?{tool_calls:_e}:x}if(f==="reasoning")return wx(x)||null}return l==="tool_calls"&&f==="tools"?{tool_calls:T,tool_signatures:P,results:L}:o})(),Y=vx(o),J=Om(e),re=J==="completed"?"OK":J==="failed"?"ERROR":J==="waiting"?"WAITING":J.toUpperCase();return s.jsxs("details",{className:`agent-trace-entry ${J}`,open:p,onToggle:ae=>y(ae.currentTarget.open),children:[s.jsxs("summary",{className:"agent-trace-summary",children:[s.jsx("span",{className:`agent-trace-status ${J}`,children:re}),s.jsx("span",{className:"agent-cycle-stage","data-stage":t,children:t}),s.jsx("span",{className:"agent-trace-kind",children:l}),j?s.jsx("span",{className:"agent-trace-node",children:j}):null,C?s.jsx("span",{className:"agent-trace-node",children:C}):null,N?s.jsx("span",{className:"agent-trace-run",children:N}):null]}),Y?s.jsx("div",{className:"agent-trace-preview",children:Y}):null,s.jsxs("div",{className:"agent-trace-body",children:[s.jsx("div",{className:"agent-trace-tabs",children:u.map(ae=>s.jsx("button",{type:"button",className:`agent-trace-tab ${ae.id===f?"active":""}`,onClick:()=>_(ae.id),children:ae.label},ae.id))}),s.jsx(_x,{value:G})]})]})}function Ck({acts:e}){const t=e.flatMap(l=>gx(l.step)),n=t.filter(l=>l.success===!1),r=n.length?`${n.length} error(s)`:t.length?`${t.length} tool result(s)`:"(none)",o=n.length?"failed":"completed";return s.jsxs("details",{className:`agent-trace-entry ${o}`,open:!1,children:[s.jsxs("summary",{className:"agent-trace-summary",children:[s.jsx("span",{className:`agent-trace-status ${o}`,children:n.length?"ERROR":"OK"}),s.jsx("span",{className:"agent-cycle-stage","data-stage":Py,children:Py}),s.jsx("span",{className:"agent-trace-kind",children:"OBSERVATIONS"}),s.jsx("span",{className:"agent-trace-preview-inline",children:r})]}),s.jsx("div",{className:"agent-observe-body",children:t.length===0?s.jsx("div",{className:"agent-observe-empty",children:"(no tool results)"}):s.jsx("div",{className:"agent-observe-results",children:t.map((l,u)=>{const c=l.success?"completed":"failed",f=l.success?"OK":"ERROR",_=l.success?l.output:l.error??l.output;return s.jsxs("details",{className:`agent-observe-result ${c}`,open:!1,children:[s.jsxs("summary",{className:"agent-observe-summary",children:[s.jsx("span",{className:`agent-trace-status ${c}`,children:f}),s.jsx("span",{className:"agent-observe-name",children:l.name}),l.call_id?s.jsx("span",{className:"agent-observe-callid",children:l.call_id}):null]}),s.jsx(_x,{value:_})]},`${l.name}:${l.call_id||""}:${u}`)})})})]})}function Ek({items:e,subRunId:t,title:n,subtitle:r,onOpenSubRun:o,defaultOpenLatest:l=!0}){const u=m.useMemo(()=>{const y=Array.isArray(e)?e.slice():[];return y.sort((w,x)=>{const S=w.ts?new Date(w.ts).getTime():NaN,j=x.ts?new Date(x.ts).getTime():NaN;return Number.isFinite(S)&&Number.isFinite(j)?S-j:0}),y},[e]),c=m.useMemo(()=>{const y=[];let w=null,x=0;for(const S of u){const j=wl(S.step);if(j==="llm_call"){x+=1,w={id:`cycle:${S.runId}:${x}:${S.ts||""}`,index:x,items:[S],think:S,acts:[],others:[],status:Om(S),ts:S.ts},y.push(w);continue}w||(x+=1,w={id:`cycle:${S.runId}:${x}:${S.ts||""}`,index:x,items:[],think:null,acts:[],others:[],status:Om(S),ts:S.ts},y.push(w)),w.items.push(S),j==="tool_calls"?w.acts.push(S):w.others.push(S),w.status=bk(w.items)}return y},[u]),f=typeof n=="string"&&n.trim()?n.trim():"Agent calls",_=typeof r=="string"&&r.trim()?r.trim():"Live per-effect trace (LLM/tool calls).",p=typeof t=="string"?t.trim():"";return s.jsxs("div",{className:"agent-trace-panel",children:[s.jsxs("div",{className:"agent-trace-header",children:[s.jsx("div",{className:"agent-trace-title",children:f}),s.jsxs("div",{className:"agent-trace-subtitle",children:[_,p?s.jsxs("span",{className:"agent-trace-subrun",children:[" ","sub_run_id: ",p,s.jsx("button",{type:"button",className:"agent-trace-copy",onClick:y=>{y.stopPropagation(),ux(p)},title:`Copy sub_run_id: ${p}`,"aria-label":"Copy sub run id",children:"⧉"}),o?s.jsx("button",{type:"button",className:"agent-trace-open",onClick:y=>{y.stopPropagation(),o()},title:"Open sub-run",children:"Open"}):null]}):null]})]}),u.length===0?s.jsx("div",{className:"agent-trace-empty",children:"No trace entries yet."}):s.jsxs("div",{className:"agent-cycle-list",children:[s.jsxs("div",{className:"agent-cycle-meta",children:[c.length," cycle(s)"]}),c.map(y=>{const w=y.status,x=w==="completed"?"OK":w==="failed"?"ERROR":w==="waiting"?"WAITING":w.toUpperCase(),S=w==="completed"?"✓":w==="failed"?"✗":"",j=S?`${S} ${x}`:x,C=y.think?vx(y.think.step):"",N=y.think?kk(y.think.step):new Map,L=y.acts.flatMap(W=>yx(W.step)).map(W=>xx(W.name,W.args,N.get(W.name)||null)),P=l&&y.index===c.length;return s.jsxs("details",{className:`agent-cycle ${w}`,open:P,children:[s.jsxs("summary",{className:"agent-cycle-summary",children:[s.jsx("span",{className:`agent-trace-status ${w}`,children:j}),s.jsx("span",{className:"agent-cycle-label",children:"cycle"}),s.jsxs("span",{className:"agent-cycle-index",children:["#",y.index]}),L.length?s.jsxs("span",{className:"agent-trace-badges",children:[L.slice(0,3).map(W=>s.jsx("span",{className:"run-metric-badge metric-tool",title:W,children:Kp(W,62)},W)),L.length>3?s.jsxs("span",{className:"run-metric-badge metric-tool",children:["+",L.length-3]}):null]}):null,s.jsx("span",{className:"agent-cycle-spacer"}),C?s.jsx("span",{className:"agent-cycle-preview",children:C}):null]}),s.jsxs("div",{className:"agent-cycle-body",children:[y.think?s.jsx(X_,{item:y.think,label:"think",toolDefs:N,defaultOpen:P}):null,y.acts.map(W=>s.jsx(X_,{item:W,label:"act",toolDefs:N},W.id)),s.jsx(Ck,{acts:y.acts}),y.others.length?s.jsxs("div",{className:"agent-cycle-others",children:[s.jsx("div",{className:"agent-cycle-others-title",children:"other"}),y.others.map(W=>{const G=P&&wl(W.step)==="answer_user";return s.jsx(X_,{item:W,label:"other",toolDefs:N,defaultOpen:G},W.id)})]}):null]})]},y.id)})]})]})}function ao(e){return typeof e=="string"?e.trim():""}function $k(e){var t;return ao(e.run_id)||ao((t=e.record)==null?void 0:t.run_id)}function Yp(e){return ao(e==null?void 0:e.node_id)}const Ak=new Set(["reason","act","observe","thought","think"]);function Jp(e){const t=ao(e);if(!t.includes("::"))return t;const n=t.split("::");if(n.length<2)return t;const r=String(n[n.length-1]||"").trim().toLowerCase();return Ak.has(r)?n.slice(0,-1).join("::"):t}function bx(e){var t;return ao((t=e==null?void 0:e.effect)==null?void 0:t.type)}function Tk(e){return ao(e==null?void 0:e.status)||"unknown"}function zy(e){return ao(e==null?void 0:e.step_id)}function Mk(e){return ao(e==null?void 0:e.ended_at)||ao(e==null?void 0:e.started_at)}function Rk(e){const t=new Map,n=new Map;for(const o of e){const l=Jp(Yp(o));if(!l)continue;const u=bx(o);u==="llm_call"?t.set(l,(t.get(l)||0)+1):u==="tool_calls"&&n.set(l,(n.get(l)||0)+1)}const r=o=>{let l="",u=-1;for(const[c,f]of o)f>u&&(l=c,u=f);return l};return r(t)||r(n)||""}function Lk(e,t){const n=ao(t.run_id);if(!n)return{run_id:"",node_id:"",items:[]};const r=(Array.isArray(e)?e:[]).filter(x=>x&&x.record&&$k(x)===n).map(x=>({cursor:x.cursor,record:x.record})).sort((x,S)=>(x.cursor||0)-(S.cursor||0)),o=r.map(x=>x.record),l=Jp(ao(t.node_id)),u=l||Rk(o),c=new Set(["llm_call","tool_calls","ask_user","answer_user"]);let f=r.filter(x=>c.has(bx(x.record)));l&&(f=f.filter(x=>Jp(Yp(x.record))===l));const _=new Map,p=[];for(const x of f){const S=zy(x.record);if(!S){p.push(x);continue}const j=_.get(S);(!j||(x.cursor||0)>(j.cursor||0))&&_.set(S,x)}const w=[...p,...Array.from(_.values())].sort((x,S)=>(x.cursor||0)-(S.cursor||0)).map(x=>{const S=x.record,j=Yp(S)||"(node?)",C=Mk(S),N=zy(S);return{id:`ledger:${n}:${x.cursor}:${N||""}`,runId:n,nodeId:j,ts:C||void 0,status:Tk(S),step:S}});return{run_id:n,node_id:u,items:w}}function l_(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 Ik(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Ok(e){const t=String(e.role||"message").trim()||"message",n=String(e.title||"").trim(),r=String(e.ts||"").trim(),o=[t];return n&&o.push(n),r&&o.push(r),o.join(" · ")}function Pk(e){return e.endsWith(`
63
+ `)?e:`${e}
64
+ `}function Dk(e){return String(e||"").trimStart().startsWith("```")}function Fk(e,t){const r=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const o of e){const l=Ok(o);r.push(`## ${l}`,"");const u=String(o.content||""),c=l_(u);c!==null&&!Dk(u)?r.push("```json",Ik(c).trimEnd(),"```",""):r.push(Pk(u).trimEnd(),""),r.push("---","")}for(;r.length&&!r[r.length-1].trim();)r.pop();return r.length&&r[r.length-1]==="---"&&r.pop(),`${r.join(`
65
+ `).trimEnd()}
66
+ `}async function $c(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 o=document.execCommand("copy")===!0;return document.body.removeChild(r),o}catch{return!1}}function zk(e){const t=String(e.filename||"").trim()||"export.txt",n=String(e.text||""),r=String(e.mime),o=new Blob([n],{type:r}),l=URL.createObjectURL(o),u=document.createElement("a");u.href=l,u.download=t,document.body.appendChild(u),u.click(),u.remove(),window.setTimeout(()=>URL.revokeObjectURL(l),1e3)}const Bk=3,Uk=Number.MAX_SAFE_INTEGER;function jx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Sx(e){return Array.isArray(e)}function Wk(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Uu({kind:e,children:t}){return s.jsx("span",{className:`pc-json-token ${e}`,children:t})}function qk(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[r,o]=m.useState(!n||e.expansionMode==="unfolded");return m.useEffect(()=>{n&&o(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:()=>o(l=>!l),"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:()=>o(!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(Uu,{kind:"string",children:t})}function Hk(e,t,n){return e===null?s.jsx(Uu,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(qk,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?s.jsx(Uu,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx(Uu,{kind:"boolean",children:e?"true":"false"}):s.jsx(Uu,{kind:"string",children:JSON.stringify(String(e))})}function Vk(e){return Sx(e)?e.length===1?"1 item":`${e.length} items`:jx(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function kx(e){const{label:t,value:n,depth:r,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:c}=e,f=r*14,_=jx(n),p=Sx(n),y=_||p,w=r<o,[x,S]=m.useState(w);m.useEffect(()=>{S(w)},[w,u]);const j=t?s.jsxs(s.Fragment,{children:[s.jsx(Uu,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!y)return s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[j,Hk(n,l,u),c?",":""]});const C=p?"[":"{",N=p?"]":"}",T=Vk(n),L=x?`${C}`:`${C}…${N}${T?` (${T})`:""}`,P=p?n.map((W,G)=>({key:String(G),label:void 0,value:W})):Object.entries(n).map(([W,G])=>({key:W,label:W,value:G}));return s.jsxs("details",{className:"pc-json-viewer__details",open:x,onToggle:W=>S(W.currentTarget.open),children:[s.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:f},children:[j,s.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:x?"▾":"▸"}),s.jsx("span",{className:"pc-json-viewer__punct",children:L}),!x&&c?s.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),x?s.jsx("div",{className:"pc-json-viewer__children",children:P.length===0?s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:N}),c?",":""]}):s.jsxs(s.Fragment,{children:[P.map((W,G)=>{const Y=G===P.length-1;return s.jsx(kx,{label:W.label,value:W.value,depth:r+1,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:!Y},`${r}:${t||"root"}:${W.key}`)}),s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:N}),c?",":""]})]})}):null]})}function Gk(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 mr(e){const{value:t,className:n,showCopy:r=!0}=e,[o,l]=m.useState({mode:"folded",version:0}),[u,c]=m.useState("idle"),f=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):Bk,_=o.mode==="unfolded"?Uk:f,p=m.useMemo(()=>typeof t=="string"?Gk(t):t,[t]),y=m.useMemo(()=>Wk(t),[t]),w=["pc-json-viewer",n].filter(Boolean).join(" ");m.useEffect(()=>{l(S=>({mode:"folded",version:S.version+1}))},[p]);const x=()=>{l(S=>({mode:S.mode==="unfolded"?"folded":"unfolded",version:S.version+1}))};return s.jsxs("div",{className:w,children:[s.jsxs("div",{className:"pc-json-viewer__toolbar",children:[s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__toggle-all",onClick:x,"aria-expanded":o.mode==="unfolded",children:o.mode==="unfolded"?"Fold all":"Unfold all"}),r?s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__copy",onClick:()=>void $c(y).then(S=>{c(S?"copied":"failed"),window.setTimeout(()=>c("idle"),2e3)}),children:u==="copied"?"Copied":u==="failed"?"Copy failed — select and copy":"Copy JSON"}):null]}),s.jsx("div",{className:"pc-json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:s.jsx(kx,{value:p,depth:0,collapseAfterDepth:_,expansionMode:o.mode,expansionVersion:o.version,trailingComma:!1})})]})}function df(e,t){const n=String(e??"");if(!t||!t.needles.length)return[n];const r=[],o=n.toLowerCase();let l=0;for(;l<n.length;){let u=-1,c="";for(let p=0;p<t.needlesLower.length;p++){const y=t.needlesLower[p];if(!y)continue;const w=o.indexOf(y,l);if(w===-1)continue;const x=t.needles[p]||"";x&&(u===-1||w<u||w===u&&x.length>c.length)&&(u=w,c=x)}if(u===-1||!c){r.push(n.slice(l));break}u>l&&r.push(n.slice(l,u));const f=t.hits===0&&t.id?t.id:void 0,_=n.slice(u,u+c.length);r.push(s.jsx("span",{id:f,className:t.className,children:_},`hl:${t.hits}`)),t.hits+=1,l=u+c.length}return r}function Nx(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const Xp="http://same-origin.invalid/";function Kk(e){try{const t=new URL(e,Xp);return t.protocol==="http:"&&t.origin===new URL(Xp).origin}catch{return!1}}function Cx(e){const t=String(e||"").trim();return Nx(t)??(t&&Kk(t)?t:void 0)}let Sc=null;function Yk(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??Xp;let o,l;try{o=new URL(r).origin,l=new URL(t,r)}catch{return!1}return l.protocol!=="http:"&&l.protocol!=="https:"?!1:l.origin===o}function Ex(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 hl(e,t){const n=[],r=String(e??"");let o=0,l="";const u=()=>{if(l){for(const c of df(l,t))n.push(c);l=""}};for(;o<r.length;){const c=r[o];if(c==="!"&&r[o+1]==="["){const f=r.indexOf("]",o+2);if(f!==-1&&r[f+1]==="("){const _=r.indexOf(")",f+2);if(_!==-1){const p=r.slice(o+2,f),y=Cx(r.slice(f+2,_));if(y&&Sc&&!Sc(y)){u(),n.push(Ex(`img:${o}`,y,p)),o=_+1;continue}if(y){u(),n.push(s.jsxs("span",{className:"pc-md_image_inline",children:[s.jsx("img",{className:"pc-md_img",src:y,alt:p,loading:"lazy"}),p?s.jsx("span",{className:"pc-md_img_caption",children:t?df(p,t):p}):null]},`img:${o}`)),o=_+1;continue}}}}if(c==="["){const f=r.indexOf("]",o+1);if(f!==-1&&r[f+1]==="("){const _=r.indexOf(")",f+2);if(_!==-1){const p=r.slice(o+1,f),y=Nx(r.slice(f+2,_));if(y){u(),n.push(s.jsx("a",{className:"pc-md_link",href:y,target:y.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:hl(p,t)},`link:${o}`)),o=_+1;continue}}}}if(c==="`"){const f=r.indexOf("`",o+1);if(f!==-1){u();const _=r.slice(o+1,f);n.push(s.jsx("code",{children:t?df(_,t):_},`code:${o}`)),o=f+1;continue}}if(c==="*"&&r[o+1]==="*"){const f=r.indexOf("**",o+2);if(f!==-1){u();const _=r.slice(o+2,f);n.push(s.jsx("strong",{children:t?df(_,t):_},`bold:${o}`)),o=f+2;continue}}if(c==="*"&&r[o+1]!=="*"){const f=r.indexOf("*",o+1);if(f!==-1){u();const _=r.slice(o+1,f);n.push(s.jsx("em",{children:t?df(_,t):_},`em:${o}`)),o=f+1;continue}}l+=c,o+=1}return u(),n}function Jk(e){return String(e??"").replace(/\r\n/g,`
67
+ `).replace(/\r/g,`
68
+ `).split(`
69
+ `)}function Sm(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 Xk(e){const t=[];for(const o of e){const l=Sm(o);l?t.push(l):t.length>0&&o.trim()&&(t[t.length-1].content+=` ${o.trim()}`)}const n=[],r=[];for(const o of t){for(;r.length>0&&o.indent<r[r.length-1].indent;)r.pop();let l=r.length>0?r[r.length-1]:null;if(l&&o.indent>l.indent){const u=l.node.items,c=u[u.length-1];if(c){const f={ordered:o.ordered,start:o.start,items:[]};c.children.push(f),r.push({indent:o.indent,node:f}),l=r[r.length-1]}}else if(l&&l.node.ordered!==o.ordered){r.pop();const u=r.length>0?r[r.length-1]:null,c={ordered:o.ordered,start:o.start,items:[]};if(u){const f=u.node.items,_=f[f.length-1];_?_.children.push(c):u.node.items.push({content:"",children:[c]})}else n.push(c);r.push({indent:o.indent,node:c}),l=r[r.length-1]}if(!l){const u={ordered:o.ordered,start:o.start,items:[]};n.push(u),r.push({indent:o.indent,node:u}),l=r[r.length-1]}l.node.items.push({content:o.content,children:[]})}return n}function $x(e,t,n){const r=e.items.map((o,l)=>s.jsxs("li",{children:[hl(o.content,t),o.children.map((u,c)=>$x(u,t,`${n}:${l}:${c}`))]},`${n}:li:${l}`));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 Zk(e,t,n){return Xk(e).map((r,o)=>$x(r,t,`${n}:${o}`))}function By(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 Uy(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 Wy=/^(#{1,5})\s+(.*)$/;function qy(e){return e.trim().startsWith("```")}function Hy(e){return e.trimStart().startsWith(">")}function Mi(e){const t=Sc;Sc=e.images==="link"?e.inlineImage||Yk:null;try{return Qk(e)}finally{Sc=t}}function Qk({text:e,className:t,highlight:n,highlights:r,highlightClassName:o,highlightId:l}){const u=Jk(e),c=[],f=[];Array.isArray(r)&&f.push(...r),typeof n=="string"&&n.trim()&&f.push(n);const _=Array.from(new Set(f.map(x=>String(x??"").trim()).filter(Boolean))).filter(x=>x.length>=4),p=_.length?{needles:_,needlesLower:_.map(x=>x.toLowerCase()),className:o||"pc-md_hl",id:l,hits:0}:null;let y=0;for(;y<u.length;){const x=String(u[y]??"");if(!x.trim()){y+=1;continue}const S=x.trim();if(/^([-_*])(\s*\1){2,}$/.test(S)){c.push(s.jsx("hr",{className:"pc-md_hr"},`hr:${y}`)),y+=1;continue}const j=x.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(j){const T=Cx(j[2]||"");if(T&&Sc&&!Sc(T)){c.push(s.jsx("p",{className:"pc-md_p",children:Ex(`img:${y}`,T,j[1]||"")},`p:${y}`)),y+=1;continue}if(T){const L=j[1]||"";c.push(s.jsxs("figure",{className:"pc-md_figure",children:[s.jsx("img",{className:"pc-md_img",src:T,alt:L,loading:"lazy"}),L?s.jsx("figcaption",{children:hl(L,p)}):null]},`figure:${y}`)),y+=1;continue}}if(qy(x)){const L=x.trim().replace(/```/g,"").trim(),P=[];for(y+=1;y<u.length&&!String(u[y]??"").trim().startsWith("```");)P.push(String(u[y]??"")),y+=1;y<u.length&&(y+=1);const W=P.join(`
70
+ `);c.push(s.jsx("pre",{className:"pc-md_pre",children:s.jsx("code",{className:L?`language-${L}`:void 0,children:W})},`pre:${y}`));continue}const C=x.match(Wy);if(C){const T=C[1].length,L=C[2]||"",P=hl(L,p);T===1?c.push(s.jsx("h1",{children:P},`h1:${y}`)):T===2?c.push(s.jsx("h2",{children:P},`h2:${y}`)):T===3?c.push(s.jsx("h3",{children:P},`h3:${y}`)):T===4?c.push(s.jsx("h4",{children:P},`h4:${y}`)):c.push(s.jsx("h5",{children:P},`h5:${y}`)),y+=1;continue}if(Hy(x)){const T=[];for(;y<u.length&&String(u[y]??"").trimStart().startsWith(">");){const P=String(u[y]??"").trimStart();T.push(P.replace(/^>\s?/,"")),y+=1}c.push(s.jsx("blockquote",{className:"pc-md_quote",children:T.map((L,P)=>s.jsxs(ve.Fragment,{children:[hl(L,p),P<T.length-1?s.jsx("br",{}):null]},`q:${y}:${P}`))},`quote:${y}`));continue}if(x.includes("|")&&y+1<u.length&&Uy(String(u[y+1]??""))){const T=By(x),L=Math.max(1,T.length),P=[];for(y+=2;y<u.length;){const W=String(u[y]??"");if(!W.trim()||!W.includes("|"))break;const G=By(W),Y=[];for(let J=0;J<L;J++)Y.push(G[J]??"");P.push(Y),y+=1}c.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:T.slice(0,L).map((W,G)=>s.jsx("th",{children:hl(W,p)},`th:${y}:${G}`))})}),s.jsx("tbody",{children:P.map((W,G)=>s.jsx("tr",{children:W.map((Y,J)=>s.jsx("td",{children:hl(Y,p)},`td:${y}:${G}:${J}`))},`tr:${y}:${G}`))})]})},`table:${y}`));continue}if(Sm(x)){const T=[];for(;y<u.length;){const L=String(u[y]??"");if(!L.trim()||L.trimStart().startsWith("```"))break;if(Sm(L)||/^\s{2,}\S/.test(L)){T.push(L),y+=1;continue}break}c.push(s.jsx(ve.Fragment,{children:Zk(T,p,`list:${y}`)},`list:${y}`));continue}const N=[];for(;y<u.length&&String(u[y]??"").trim()&&!(N.length>0&&Sm(String(u[y]??"")));){const T=String(u[y]??"");if(N.length>0&&(Wy.test(T)||qy(T)||Hy(T))||N.length>0&&T.includes("|")&&y+1<u.length&&Uy(String(u[y+1]??"")))break;N.push(T),y+=1}c.push(s.jsx("p",{className:"pc-md_p",children:N.map((T,L)=>s.jsxs(ve.Fragment,{children:[hl(T,p),L<N.length-1?s.jsx("br",{}):null]},`pl:${y}:${L}`))},`p:${y}`))}const w=["pc-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:w,children:c})}function Ax(e){const t=String(e.text??""),n=m.useMemo(()=>l_(t),[t]),r=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?s.jsx("div",{className:r,children:s.jsx(mr,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?s.jsx("div",{className:r,children:e.renderMarkdown(t)}):s.jsx("div",{className:r,children:s.jsx(Mi,{text:t,images:e.images,inlineImage:e.inlineImage})})}function Tx(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function eN(e){const t=Tx(e);if(!t||typeof t!="object"||Array.isArray(t))return{label:"input",value:t==null?"":String(t)};const n=Object.entries(t),o=["command","query","url","file_path","path","pattern","name"].map(l=>n.find(([u])=>u===l)).find(Boolean)||n[0];return o?{label:o[0].replace(/_/g," "),value:typeof o[1]=="string"?o[1]:JSON.stringify(o[1])??""}:{label:"",value:""}}function Mx({tool:e,showCopy:t=!0}){const[n,r]=m.useState(!1),o=Tx(e.arguments),l=eN(e.arguments),u=["file path","path"].includes(l.label)&&l.value.length>60?`${l.value.split(/[\\/]/).pop()} · ${l.value.slice(0,24)}…`:l.value,c=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,f={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},_=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,p=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o):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:l.value,children:l.value?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pc-tool-activity__key",children:l.label}),u]}):"No parameters"}),s.jsx("span",{className:"pc-tool-activity__status",children:f[e.status]}),Number.isFinite(_)&&_>=0?s.jsxs("span",{className:"pc-tool-activity__duration",children:[(_/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:c}):null]}),s.jsxs("div",{className:"pc-tool-activity__detail",children:[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 $c(JSON.stringify(e,null,2))),children:[s.jsx(Qe,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),p?s.jsx("dl",{className:"pc-tool-activity__parameters",children:p.map(([y,w])=>s.jsxs(ve.Fragment,{children:[s.jsx("dt",{children:y}),s.jsx("dd",{children:w&&typeof w=="object"?s.jsx(mr,{value:w}):s.jsx("code",{children:typeof w=="string"?w:JSON.stringify(w)})})]},y))}):e.arguments===void 0?s.jsx("p",{children:"Arguments are unavailable in this ledger."}):s.jsx(mr,{value:o}),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(mr,{value:e.output})})]}):null]})]})}function Rx({tools:e,showCopy:t}){const n=r=>e.filter(o=>o.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(Mx,{tool:r,showCopy:t},r.id))]})}const Zs="not reported",Ar=e=>e===void 0?Zs:Math.round(e).toLocaleString(),Yr=e=>{if(e===void 0)return Zs;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`},Lx=e=>e===void 0?Zs:`${Math.round(e).toLocaleString()} tok/s`,tN=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",kc=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,nN=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function sN(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 Pm(e){const t=[],n=(e.models||[]).map(nN),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 rN(e){const t=e.modelCalls||[],n=[],r=[{label:"Input",value:Ar(e.inputTokens)},{label:"Output",value:Ar(e.outputTokens)}];if(e.reasoningTokens!==void 0&&r.push({label:"Reasoning",value:Ar(e.reasoningTokens),hint:"part of output"}),r.push({label:"Total",value:Ar(e.totalTokens)}),n.push({heading:`Usage · ${kc(e.llmCalls,"model call")}`,rows:r}),e.measuredCacheCalls){const l=e.cachedTokens||0,u=e.fedTokens||0,c=[{label:"Reused from cache",value:`${Ar(l)}${l+u?` (${tN(l,l+u)})`:""}`},{label:"Newly processed",value:Ar(e.fedTokens)},{label:"Outcome",value:sN(t.map(f=>f.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Zs},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Zs}];e.measuredCacheCalls!==e.llmCalls&&c.push({label:"Measured on",value:`${e.measuredCacheCalls} of ${e.llmCalls} calls`}),n.push({heading:"Prompt cache",rows:c})}else e.llmCalls&&n.push({heading:"Prompt cache",rows:[{label:"Cache reuse",value:Zs}]});const o=t.filter(l=>l.inputTokens!==void 0);return o.length===1&&t.length===1?n.push({heading:"Context",rows:[{label:"Prompt size",value:`${Ar(o[0].inputTokens)} tokens`}]}):o.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${Ar(o[0].inputTokens)} → ${Ar(o[o.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((l,u)=>[String(u+1),Ar(l.inputTokens),l.cachedTokens===void 0?"—":Ar(l.cachedTokens),l.fedTokens===void 0?"—":Ar(l.fedTokens),Ar(l.outputTokens),l.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Zs:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:Pm(e)}}function em(e,t,n,r){if(e===void 0)return Zs;const o=[Yr(e)];return t!==void 0&&o.push(`${t.toLocaleString()} ${r}${n!==void 0?` at ${Lx(n)}`:""}`),o.join(" · ")}function iN(e){var _,p,y;const t=e.modelCalls||[],n=[],r=e.durationMs,o=[{label:"Wall clock",value:Yr(r)}];if(o.push({label:"Model",value:e.genTimeMs===void 0?Zs:`${Yr(e.genTimeMs)} · ${kc(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),o.push({label:"Tools",value:e.toolTimeMs!==void 0?`${Yr(e.toolTimeMs)} · ${kc(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Zs:"none",hint:e.toolTimeIncludesApproval?"includes approval wait":void 0}),r!==void 0&&e.genTimeMs!==void 0){const w=r-e.genTimeMs-(e.toolTimeMs||0);o.push({label:"Orchestration",value:w>=0?Yr(w):"overlaps (parallel runs)",hint:"wall − model − tools: routing, hand-offs, model load"})}n.push({heading:"Turn",rows:o});const l=[],u=e.ttftCalls||0,c=e.promptPhaseCalls||0;e.promptPhaseMs!==void 0?l.push({label:u&&u===c?"Prefill (TTFT)":"Prefill",value:em(e.promptPhaseMs,e.promptPhaseNewTokens,e.promptPhaseTokensPerSecond,"new tok"),hint:u===c?"measured time to first token":u?`TTFT measured on ${u} of ${c}; rest from provider rate`:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0&&e.prefillNewTokensPerSecond!==void 0?l.push({label:"Prefill",value:em(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${Yr(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${Lx(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):l.push({label:"Prefill",value:Zs}),e.cachedTokens&&(e.promptPhaseMs??e.prefillMs)!==void 0&&l.push({label:"Restored",value:`${e.cachedTokens.toLocaleString()} tok from cache`,hint:"not recomputed"}),l.push({label:"Generation",value:e.generationPhaseMs!==void 0?em(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):em(e.decodeMs,e.outputTokens,e.generationTokensPerSecond,"tok")}),e.measuredSpeedCalls&&e.measuredSpeedCalls!==e.llmCalls&&l.push({label:"Speeds from",value:`${e.measuredSpeedCalls} of ${e.llmCalls} calls`}),n.push({heading:"Model",rows:l});const f=e.speculation;if(f){const w=(f.draftKinds||[]).map(S=>S.toUpperCase()).join(", "),x=[{label:"Mode",value:`${f.used?"on":"off"}${w?` · ${w}`:""}${(_=f.modes)!=null&&_.length?` (${f.modes.join(", ")})`:""}`,hint:f.calls!==e.llmCalls||f.used!==f.calls?`used on ${f.used} of ${e.llmCalls} calls`:void 0},{label:"Acceptance",value:f.acceptanceRate===void 0?Zs:`${Math.round(f.acceptanceRate*100)}% · ${Ar(f.acceptedTokens)} of ${Ar(f.draftedTokens)} drafted`}];((p=f.draftLengths)!=null&&p.length||f.rounds!==void 0)&&x.push({label:"Draft length",value:`${(y=f.draftLengths)!=null&&y.length?`${f.draftLengths.join("/")} tok/round`:Zs}${f.rounds!==void 0?` · ${f.rounds.toLocaleString()} rounds`:""}`}),n.push({heading:"Speculation",rows:x})}return e.slowestToolBatch&&n.push({heading:"Tools",rows:[{label:"Total",value:`${Yr(e.toolTimeMs)} · ${kc(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${Yr(e.slowestToolBatch.ms)} · ${Ix(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((w,x)=>[String(x+1),w.promptMs===void 0?"—":`${Yr(w.promptMs)}${w.promptSource==="rate"?"*":""}`,w.promptNewTokensPerSecond===void 0?"—":Math.round(w.promptNewTokensPerSecond).toLocaleString(),w.generationMs===void 0?"—":Yr(w.generationMs),w.generationTokensPerSecond===void 0?"—":Math.round(w.generationTokensPerSecond).toLocaleString(),w.cacheOutcome||"—"])},note:t.some(w=>w.promptSource==="rate")?"* derived from the provider's prompt rate (no TTFT event).":void 0}),{kind:"time",title:"Time",headline:r===void 0?Zs:`${Yr(r)} wall clock`,sections:n,footer:Pm(e)}}function Ix(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${kc(e.calls,"call")} (${e.tools.join(", ")})`}function oN(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:Pm(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 o=Object.entries(e.toolBreakdown||{}).sort((c,f)=>f[1].calls-c[1].calls||c[0].localeCompare(f[0]));o.length&&t.push({heading:"By tool",table:{columns:["Tool","Calls","Failed","Time"],rows:o.map(([c,f])=>[c,f.calls.toLocaleString(),f.failed.toLocaleString(),f.ms!==void 0?`${Yr(f.ms)}${f.sharedBatches?" +shared":""}`:f.sharedBatches?"shared":Zs])},note:o.some(([,c])=>c.sharedBatches)?"A batch that mixed tools ran them together; its time is not split between them.":void 0});const l=o.filter(([,c])=>c.errors&&Object.keys(c.errors).length);l.length&&t.push({heading:"Failures",rows:l.map(([c,f])=>({label:c,value:Object.entries(f.errors).sort((_,p)=>p[1]-_[1]).map(([_,p])=>p>1?`${_} ×${p}`:_).join(" · ")}))});const u=[{label:"Tool time",value:e.toolTimeMs===void 0?Zs:`${Yr(e.toolTimeMs)} · ${kc(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${Yr(e.slowestToolBatch.ms)} · ${Ix(e.slowestToolBatch)}`}),t.push({heading:"Timing",rows:u,note:e.toolTimeIncludesApproval?"Gated calls are timed from request to result, so this includes waiting for your approval.":void 0}),{kind:"tools",title:"Tools",headline:`${kc(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:Pm(e)}}function Z_(e,t){return e==="tokens"?rN(t):e==="time"?iN(t):oN(t)}function aN(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(o=>s.jsxs(ve.Fragment,{children:[s.jsx("dt",{children:o.label}),s.jsxs("dd",{children:[s.jsx("span",{className:o.value===Zs?"pc-stat-detail-value pc-stat-detail-value--absent":"pc-stat-detail-value",children:o.value}),o.hint?s.jsx("span",{className:"pc-stat-detail-hint",children:o.hint}):null]})]},o.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(o=>s.jsx("th",{scope:"col",children:o},o))})}),s.jsx("tbody",{children:n.table.rows.map((o,l)=>s.jsx("tr",{children:o.map((u,c)=>s.jsx("td",{children:u},c))},l))})]}):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 xa=8;function lN(e){const[t,n]=m.useState(!!e.defaultOpen),[r,o]=m.useState(null),l=m.useRef(null),u=m.useRef(null),c=m.useRef(null),f=`pc-stat-${m.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,_=m.useCallback(()=>{c.current!==null&&window.clearTimeout(c.current),c.current=null},[]),p=m.useCallback(()=>{_(),n(!0)},[_]),y=m.useCallback(()=>{_(),c.current=window.setTimeout(()=>n(!1),120)},[_]);m.useEffect(()=>_,[_]),m.useLayoutEffect(()=>{if(!t){o(null);return}const j=()=>{const C=l.current,N=u.current;if(!C||!N)return;const T=C.getBoundingClientRect(),L=N.offsetWidth,P=N.offsetHeight,W=window.innerWidth,G=window.innerHeight,Y=T.top-xa-P,J=T.bottom+xa,re=Y>=xa?Y:J+P<=G-xa?J:Math.max(xa,G-xa-P),ae=Math.min(Math.max(xa,T.left),Math.max(xa,W-xa-L));o({top:re,left:ae})};return j(),window.addEventListener("resize",j),window.addEventListener("scroll",j,!0),()=>{window.removeEventListener("resize",j),window.removeEventListener("scroll",j,!0)}},[t]),m.useEffect(()=>{if(!t)return;const j=C=>{C.key==="Escape"&&n(!1)};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[t]);const w=typeof e.onClick=="function",x=w?"button":"span",S=t?s.jsx(aN,{detail:e.detail,id:f,panelRef:u,onMouseEnter:_,onMouseLeave:y,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(x,{ref:l,...w?{type:"button"}:{tabIndex:0},className:["pc-chat-stat","pc-chat-stat--detail",w?"pc-chat-stat--clickable":"",e.className].filter(Boolean).join(" "),"aria-label":`${e.label} — ${e.detail.title.toLowerCase()} details`,"aria-describedby":t?f:void 0,"data-stat-kind":e.detail.kind,onMouseEnter:p,onMouseLeave:y,onFocus:p,onBlur:()=>n(!1),onKeyDown:j=>{j.key==="Escape"&&n(!1)},onClick:w?()=>{var j;return(j=e.onClick)==null?void 0:j.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})]}),S&&typeof document<"u"?Bv.createPortal(S,document.body):S]})}function cN(e){const t=e.totalTokens!==void 0?Z_("tokens",e):null,n=Z_("tools",e),r=e.durationMs!==void 0?Z_("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(`
71
+ `)}]:[],...r?[{label:`${(e.durationMs/1e3).toFixed(e.durationMs<1e4?1:0)}s`,detail:r}]:[]]}function uN(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"}}function Pg(e){var N;const t=e.message,n=m.useMemo(()=>uN(t),[t.kind,t.level,t.role,t.title]),r=String(t.ts||"").trim(),o=m.useMemo(()=>{if(!r)return"";const T=new Date(r);return Number.isFinite(T.getTime())?T.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""},[r]),[l,u]=m.useState("idle"),c=m.useRef(null);m.useEffect(()=>()=>{c.current!==null&&window.clearTimeout(c.current)},[]);const f=t.live,_=!f&&typeof e.onSpeakToggle=="function"&&n.variant==="assistant"&&!!String(t.content||"").trim(),p=_&&((N=e.getSpeakState)==null?void 0:N.call(e,t))||"idle",y=p==="loading"?"loader":p==="playing"?"pause":"speaker",w=p==="loading"?"Generating audio…":p==="playing"?"Pause":p==="paused"?"Resume":"Speak (TTS)",x=e.showCopy!==!1,S=Array.isArray(e.attachments)?e.attachments:[],j=t.statistics,C=m.useMemo(()=>Array.isArray(e.stats)?e.stats:j?cN(j):[],[e.stats,j]);return t.toolActivity?s.jsx(Mx,{tool:t.toolActivity,showCopy:e.showCopy}):s.jsxs("div",{className:["pc-chat-item",`pc-chat-item--${n.variant}`,f?"pc-chat-item--live":"",e.className].filter(Boolean).join(" "),...f?{"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}),f?s.jsxs("span",{className:"pc-chat-live-indicator",title:"The reply is still being written",children:[s.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),"streaming"]}):null,f!=null&&f.caption?s.jsx("span",{className:"pc-chat-live-caption",children:f.caption}):null,s.jsx("span",{className:"pc-chat-header-spacer"}),o?s.jsx("span",{className:"pc-chat-time",children:o}):null,s.jsxs("div",{className:"pc-chat-header-actions",children:[_?s.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":w,title:w,onClick:()=>{var T;return(T=e.onSpeakToggle)==null?void 0:T.call(e,t)},children:s.jsx(Qe,{name:y,size:22})}):null,x?s.jsx("button",{className:`pc-chat-icon-btn ${l!=="idle"?`pc-chat-icon-btn--${l}`:""}`.trim(),type:"button","aria-label":"Copy message",title:l==="idle"?"Copy":l==="copied"?"Copied":"Copy failed",onClick:async()=>{const T=await $c(String(t.content||""));u(T?"copied":"failed"),c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>u("idle"),900)},children:s.jsx(Qe,{name:"copy",size:22})}):null]})]}),f!=null&&f.reasoning?s.jsxs("details",{className:"pc-chat-thinking",children:[s.jsx("summary",{children:"Thinking"}),s.jsx("div",{className:"pc-chat-thinking-body",children:f.reasoning})]}):null,!f||String(t.content||"").trim()?s.jsx("div",{className:"pc-chat-body",children:s.jsx(Ax,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,S.length?s.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:S.slice(0,24).map((T,L)=>{const P=String(T.label||"").trim()||"attachment",W=String(T.target||"").trim(),G=String(T.title||"").trim(),Y=!!T.disabled||typeof T.onClick!="function";return s.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:G||P,onClick:Y?void 0:T.onClick,disabled:Y,children:[s.jsx(Qe,{name:"paperclip",size:14}),W?s.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${W}`,children:W}):null,s.jsx("span",{className:"pc-chat-attachment-name",children:P})]},T.id||`${P}:${L}`)})}):null,C.length?s.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:C.slice(0,12).map((T,L)=>{const P=String(T.label||"").trim();if(!P)return null;if(T.detail)return s.jsx(lN,{label:P,detail:T.detail,icon:T.icon,onClick:T.onClick},T.id||`${P}:${L}`);const W=String(T.title||"").trim(),G=typeof T.onClick=="function",Y=G?"button":"span";return s.jsxs(Y,{...G?{type:"button"}:{},className:["pc-chat-stat",G?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:W||void 0,onClick:G?()=>{var J;return(J=T.onClick)==null?void 0:J.call(T)}:void 0,children:[T.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:T.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:P})]},T.id||`${P}:${L}`)})}):null]})}function dN(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function Dg(e){const t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,r=m.useRef(null),o=m.useRef(null),[l,u]=m.useState(!0),c=m.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),f=m.useMemo(()=>{var y;const p=[];for(const w of c){const x=p[p.length-1];w.toolActivity&&((y=x==null?void 0:x[0])!=null&&y.toolActivity)&&x[0].runId===w.runId?x.push(w):p.push([w])}return p},[c]);m.useEffect(()=>{if(!n)return;const p=r.current;if(!p)return;const y=()=>{u(dN(p,t))};return p.addEventListener("scroll",y,{passive:!0}),y(),()=>p.removeEventListener("scroll",y)},[n,t]);const _=m.useMemo(()=>{let p=0;for(const y of c)p+=String(y.content??"").length;return`${c.length}:${p}:${String(e.afterKey??"")}`},[c,e.afterKey]);return m.useEffect(()=>{if(!n||!l)return;const p=r.current;p&&(p.scrollTop=p.scrollHeight)},[n,l,_]),s.jsxs("div",{ref:r,className:["pc-chat-thread",e.className].filter(Boolean).join(" "),children:[c.length?null:e.empty||null,f.map((p,y)=>{var S;const w=p[0],x=String(w.id||"")||String(w.ts||"")+":"+String(w.role||"")+":"+y;return w.toolActivity?s.jsx(Rx,{tools:p.map(j=>j.toolActivity),showCopy:(S=e.messageProps)==null?void 0:S.showCopy},x):s.jsx(Pg,{message:w,...e.messageProps||{}},x)}),e.after,s.jsx("div",{ref:o})]})}const Fg=ve.forwardRef(function(t,n){const r=typeof t.rows=="number"&&Number.isFinite(t.rows)?Math.max(1,Math.trunc(t.rows)):3,o=!!t.disabled,l=!!t.busy,u=!o&&!l&&!!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:c=>t.onChange(c.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:o,autoFocus:!!t.autoFocus,onPaste:t.onPaste,onKeyDown:c=>{c.key!=="Enter"||c.shiftKey||c.nativeEvent.isComposing||c.keyCode===229||(c.preventDefault(),u&&t.onSubmit())}}),s.jsxs("div",{className:"pc-composer__row",children:[s.jsx("div",{className:"pc-composer__actions",children:t.actions}),s.jsx("button",{type:"button",className:t.sendButtonClassName||"pc-btn",disabled:!u,onClick:()=>t.onSubmit(),children:l?t.busyLabel||"Thinking…":t.sendLabel||"Send"})]}),t.overlay]})});function fN(e){return!!(e&&typeof e[Symbol.asyncIterator]=="function")}function hN(e){const[t,n]=m.useState([]),r=e.messages??t,o=j=>{e.onMessagesChange&&e.onMessagesChange(j),e.messages===void 0&&n(j)},l=m.useRef(r);l.current=r;const[u,c]=m.useState(""),[f,_]=m.useState(!1),p=m.useRef(null),y=e.assistantName||"Assistant",w=!!e.blockedNotice,x=async j=>{const C=String(j||"").trim();if(!C||f||w)return;c("");const N=l.current,T=[...N,{role:"user",content:C,ts:new Date().toISOString()}];o(T),_(!0);const L=new AbortController;p.current=L;try{const P=e.ask(C,{signal:L.signal,history:N});if(fN(P)){let W="";const G=[...T,{role:"assistant",title:y,content:"",ts:new Date().toISOString()}];o(G);for await(const Y of P){if(L.signal.aborted)break;W+=String(Y??""),o([...T,{role:"assistant",title:y,content:W,ts:new Date().toISOString()}])}!W.trim()&&!L.signal.aborted&&o([...T,{role:"assistant",title:y,content:"#FALLBACK the assistant returned no answer.",level:"warn",ts:new Date().toISOString()}])}else{const W=String(await P??"").trim();o([...T,W?{role:"assistant",title:y,content:W,ts:new Date().toISOString()}:{role:"assistant",title:y,content:"#FALLBACK the assistant returned no answer.",level:"warn",ts:new Date().toISOString()}])}}catch(P){L.signal.aborted||o([...l.current,{role:"assistant",title:y,content:`#FALLBACK assistant request failed: ${String((P==null?void 0:P.message)||P||"unknown error")}`,level:"error",ts:new Date().toISOString()}])}finally{p.current===L&&(p.current=null),_(!1)}},S=m.useMemo(()=>r.length>0?null:s.jsxs("div",{className:"pc-assistant__empty",children:[s.jsx("div",{className:"pc-assistant__empty-text",children:e.emptyState||"Ask about this app — answers are grounded in its documentation."}),e.suggestions&&e.suggestions.length>0?s.jsx("div",{className:"pc-assistant__suggestions",children:e.suggestions.map(j=>s.jsx("button",{type:"button",className:"pc-assistant__suggestion",onClick:()=>void x(j),disabled:f||w,children:j},j))}):null]}),[r.length,e.emptyState,e.suggestions,f,w]);return s.jsxs("div",{className:`pc-assistant${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"pc-assistant__thread",children:[S,s.jsx(Dg,{messages:r,autoScroll:!0}),w?s.jsx("div",{className:"pc-assistant__blocked",children:e.blockedNotice}):null]}),s.jsx("div",{className:"pc-assistant__composer",children:s.jsx(Fg,{value:u,onChange:c,onSubmit:()=>void x(u),placeholder:e.placeholder||"Ask about this app…",disabled:w,busy:f,rows:2,actions:f?s.jsx("button",{type:"button",className:"pc-btn",onClick:()=>{var j;(j=p.current)==null||j.abort()},children:"Stop"}):null})})]})}const bn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},km=e=>Array.isArray(e)?e.map(bn):[],Zt=e=>typeof e=="string"?e:"",ff=e=>Zt(e.runtime_call_id||e.call_uid),hf=e=>Zt(e.call_id||e.id);function Ox(e,t){const n=t.record,r=bn(n.effect);if(r.type!=="tool_calls")return[];const o=bn(n.result),l=km(bn(r.payload).tool_calls),u=l.length||n.status!=="waiting"?l:km(bn(bn(o.wait).details).tool_calls),c=km(o.results),f=u.length?u:c,_=[];return f.forEach((p,y)=>{let w=ff(p)?c.filter(G=>ff(G)===ff(p)):[];!w.length&&hf(p)&&u.filter(G=>hf(G)===hf(p)).length===1&&(w=c.filter(G=>hf(G)===hf(p)));const x=u.length?w.length===1?w[0]:u.length===c.length?c[y]:{}:p,S=ff(p)||ff(x)||`${Zt(n.idempotency_key)||Zt(n.step_id)||t.cursor}:${y}`,j=`${t.runId}:${S}`,C=e.get(j),N=Zt(p.name||x.name)||(C==null?void 0:C.name);if(!N)return;const T=n.status==="completed"||n.status==="failed",L=n.status==="failed"||x.success===!1||!!x.error,P=p.arguments??x.arguments??(C==null?void 0:C.arguments),W={...C,id:j,runId:t.runId,name:N,arguments:P,status:T?L?"failed":"completed":n.status==="waiting"?"waiting":"running",...typeof x.success=="boolean"?{success:x.success}:{},...x.output!==void 0||x.result!==void 0?{output:x.output??x.result}:{},...x.error?{error:String(x.error)}:{},startedAt:(C==null?void 0:C.startedAt)||Zt(n.started_at)||void 0,endedAt:T&&Zt(n.ended_at)||(C==null?void 0:C.endedAt)};C&&["completed","failed"].includes(C.status)&&!T||(e.set(j,W),_.push(W))}),_}function Fu(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function Io(e,t){for(const n of t){const r=e==null?void 0:e[n];if(r==null||r===""||typeof r=="boolean")continue;const o=Number(r);if(Number.isFinite(o)&&o>=0)return Math.trunc(o)}}function Px(e){if(typeof e=="string")try{return bn(JSON.parse(e))}catch{return{}}return bn(e)}function Mu(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function mN(e){return Io(e,["reasoning_tokens","thinking_tokens"])??Io(bn(e.completion_tokens_details),["reasoning_tokens"])??Io(bn(e.output_tokens_details),["reasoning_tokens"])}function _N(e){const t=bn(typeof e=="string"&&e.trim().startsWith("{")?Px(e):e);return Zt(t.error_class)}function pN(e){const t=new Map;for(const n of e){const r=n.record;if(bn(r.effect).type!=="emit_event")continue;const o=bn(r.result);if(Zt(o.name)!=="abstract.progress")continue;const l=bn(o.payload);if(Zt(l.kind)!=="llm"||!Zt(l.step_id))continue;const u=`${Zt(l.run_id)||n.runId}:${Zt(l.step_id)}`,c=t.get(u)||{},f=Fu(l.ttft_s);f!==void 0&&(c.ttftS=f),c.provider=c.provider||Zt(l.provider)||void 0,c.model=c.model||Zt(l.model)||void 0,t.set(u,c)}return t}function Q_(e){var j,C,N,T;const t=new Map,n=new Set,r=new Set,o={llmCalls:0,toolCalls:0,changedFiles:[]};let l=1/0,u=-1/0,c=!1,f=0,_=0,p=0;const y=pN(e),w=[],x=new Set;for(const L of e){const P=L.record,W=`${L.runId}:${P.step_id||L.cursor}:${P.status}`;if(n.has(W))continue;n.add(W);for(const ye of[P.started_at,P.ended_at]){const Ee=Date.parse(Zt(ye));Number.isFinite(Ee)&&(l=Math.min(l,Ee),u=Math.max(u,Ee))}for(const ye of Ox(t,L))ye.status==="waiting"&&x.add(ye.id);if(bn(P.effect).type!=="llm_call"||P.status!=="completed")continue;o.llmCalls+=1;const G=bn(P.result),Y=bn(G.output),J=bn(G.usage||G.token_usage||G.tokens||Y.usage||Y.token_usage||Y.tokens),re=Io(J,["input_tokens","prompt_tokens","prompt","input","in"]),ae=Io(J,["output_tokens","completion_tokens","completion","output","out"]),ue=Io(J,["total_tokens","total"])??(re!==void 0||ae!==void 0?(re||0)+(ae||0):void 0);ue!==void 0&&(re===void 0||ae===void 0||re+ae!==ue)&&(c=!0),re!==void 0&&(o.inputTokens=(o.inputTokens||0)+re),ae!==void 0&&(o.outputTokens=(o.outputTokens||0)+ae),ue!==void 0&&(o.totalTokens=(o.totalTokens||0)+ue);const B=Fu(G.gen_time??Y.gen_time);B!==void 0&&(o.genTimeMs=(o.genTimeMs||0)+B,o.timedCalls=(o.timedCalls||0)+1);const A=bn(G.metadata||Y.metadata),$=bn(A.performance),z=Fu($.prompt_tokens_per_second),E=Fu($.generation_tokens_per_second),te=bn(A.prompt_cache),O=Fu(te.cached_tokens),F=Fu(te.fed_tokens);if(z!==void 0||E!==void 0){if(o.measuredSpeedCalls=(o.measuredSpeedCalls||0)+1,z!==void 0&&z>0&&(o.promptTokensPerSecond=(o.promptTokensPerSecond||0)+z,re!==void 0)){const ye=re/z*1e3;o.prefillMs=(o.prefillMs||0)+ye,F!==void 0&&(f+=F,_+=ye)}E!==void 0&&E>0&&(o.generationTokensPerSecond=(o.generationTokensPerSecond||0)+E,ae!==void 0&&(o.decodeMs=(o.decodeMs||0)+ae/E*1e3))}if(O!==void 0||F!==void 0){o.measuredCacheCalls=(o.measuredCacheCalls||0)+1,o.cachedTokens=(o.cachedTokens||0)+(O||0),o.fedTokens=(o.fedTokens||0)+(F||0);const ye=Zt(te.outcome);if(ye){const Ee=o.cacheOutcomes||[];Ee.includes(ye)||Ee.push(ye),o.cacheOutcomes=Ee}}const K=Zt(P.step_id)||void 0,R=K&&y.get(`${L.runId}:${K}`)||{},Q=bn(G.route),Z={runId:L.runId};K&&(Z.stepId=K),Zt(P.started_at)&&(Z.startedAt=Zt(P.started_at));const X=Zt(G.model||Y.model)||Zt(Q.model)||R.model,le=Zt(Q.provider)||Zt(bn(A._provider_request).provider)||R.provider||Zt(G.provider);X&&(Z.model=X),le&&(Z.provider=le),X&&(o.models=Mu(o.models,X)),le&&(o.providers=Mu(o.providers,le)),(ue===void 0||re!==void 0&&ae!==void 0&&re+ae===ue)&&(re!==void 0&&(Z.inputTokens=re),ae!==void 0&&(Z.outputTokens=ae)),ue!==void 0&&(Z.totalTokens=ue);const _e=mN(J);_e!==void 0&&(Z.reasoningTokens=_e,o.reasoningTokens=(o.reasoningTokens||0)+_e),O!==void 0&&(Z.cachedTokens=O),F!==void 0&&(Z.fedTokens=F),Zt(te.outcome)&&(Z.cacheOutcome=Zt(te.outcome)),Zt(te.backend)&&(Z.cacheBackend=Zt(te.backend),o.cacheBackends=Mu(o.cacheBackends,Z.cacheBackend)),B!==void 0&&(Z.genTimeMs=B),z!==void 0&&z>0&&(Z.promptTokensPerSecond=z),E!==void 0&&E>0&&(Z.generationTokensPerSecond=E),R.ttftS!==void 0?(Z.ttftMs=R.ttftS*1e3,Z.promptMs=Z.ttftMs,Z.promptSource="ttft",o.ttftMs=(o.ttftMs||0)+Z.ttftMs,o.ttftCalls=(o.ttftCalls||0)+1):Z.promptTokensPerSecond!==void 0&&re!==void 0&&(Z.promptMs=re/Z.promptTokensPerSecond*1e3,Z.promptSource="rate"),Z.promptMs!==void 0&&(o.promptPhaseMs=(o.promptPhaseMs||0)+Z.promptMs,o.promptPhaseCalls=(o.promptPhaseCalls||0)+1,F!==void 0&&Z.promptMs>0&&(Z.promptNewTokensPerSecond=F/(Z.promptMs/1e3),o.promptPhaseNewTokens=(o.promptPhaseNewTokens||0)+F,p+=Z.promptMs)),Z.ttftMs!==void 0&&B!==void 0&&B>=Z.ttftMs?Z.generationMs=B-Z.ttftMs:Z.generationTokensPerSecond!==void 0&&ae!==void 0&&(Z.generationMs=ae/Z.generationTokensPerSecond*1e3),Z.generationMs!==void 0&&ae!==void 0&&(o.generationPhaseMs=(o.generationPhaseMs||0)+Z.generationMs,o.generationPhaseTokens=(o.generationPhaseTokens||0)+ae);const he=bn(A.speculation);if(Object.keys(he).length){const ye={};Zt(he.mode)&&(ye.mode=Zt(he.mode)),typeof he.used=="boolean"&&(ye.used=he.used),Zt(he.draft_kind)&&(ye.draftKind=Zt(he.draft_kind));const Ee=Io(he,["accepted_tokens"]),ze=Io(he,["drafted_tokens"]),Be=Io(he,["rounds"]),gt=Io(he,["num_draft_tokens"]);Ee!==void 0&&(ye.acceptedTokens=Ee),ze!==void 0&&(ye.draftedTokens=ze),Ee!==void 0&&ze&&(ye.acceptanceRate=Ee/ze),Be!==void 0&&(ye.rounds=Be),gt!==void 0&&(ye.draftLength=gt),Z.speculation=ye;const Fe=o.speculation||(o.speculation={calls:0,used:0});Fe.calls+=1,ye.used&&(Fe.used+=1),ye.mode&&(Fe.modes=Mu(Fe.modes,ye.mode)),ye.draftKind&&(Fe.draftKinds=Mu(Fe.draftKinds,ye.draftKind)),Ee!==void 0&&ze!==void 0&&(Fe.acceptedTokens=(Fe.acceptedTokens||0)+Ee,Fe.draftedTokens=(Fe.draftedTokens||0)+ze),Be!==void 0&&(Fe.rounds=(Fe.rounds||0)+Be),gt!==void 0&&(Fe.draftLengths=Mu(Fe.draftLengths,gt))}w.push(Z)}w.length&&(w.every(L=>L.startedAt)&&w.sort((L,P)=>Date.parse(L.startedAt)-Date.parse(P.startedAt)),o.modelCalls=w),p>0&&o.promptPhaseNewTokens!==void 0&&(o.promptPhaseTokensPerSecond=o.promptPhaseNewTokens/(p/1e3)),o.generationPhaseMs&&o.generationPhaseTokens!==void 0&&(o.generationPhaseTokensPerSecond=o.generationPhaseTokens/(o.generationPhaseMs/1e3)),(j=o.speculation)!=null&&j.draftedTokens&&(o.speculation.acceptanceRate=(o.speculation.acceptedTokens||0)/o.speculation.draftedTokens),o.measuredSpeedCalls&&(o.promptTokensPerSecond!==void 0&&(o.promptTokensPerSecond/=o.measuredSpeedCalls),o.generationTokensPerSecond!==void 0&&(o.generationTokensPerSecond/=o.measuredSpeedCalls)),_>0&&(o.prefillNewTokens=f,o.prefillNewTokensPerSecond=f/(_/1e3));const S=new Map;for(const L of t.values()){if(L.status==="waiting"){o.toolsWaiting=(o.toolsWaiting||0)+1;continue}if(L.status==="running"){o.toolsRunning=(o.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(L.status))continue;o.toolCalls+=1;const P=L.status==="failed";P&&(o.toolsFailed=(o.toolsFailed||0)+1);const W=o.toolBreakdown||(o.toolBreakdown={}),G=W[L.name]||(W[L.name]={calls:0,failed:0});if(G.calls+=1,P){G.failed+=1;const ue=_N(L.output);ue&&((G.errors||(G.errors={}))[ue]=(((C=G.errors)==null?void 0:C[ue])||0)+1)}const Y=Date.parse(Zt(L.startedAt)),J=Date.parse(Zt(L.endedAt));if(Number.isFinite(Y)&&Number.isFinite(J)&&J>=Y){const ue=`${L.runId}|${L.startedAt}|${L.endedAt}`,B=S.get(ue)||{ms:J-Y,calls:0,names:new Map,waited:!1};B.calls+=1,B.names.set(L.name,(B.names.get(L.name)||0)+1),x.has(L.id)&&(B.waited=!0),S.set(ue,B)}if(L.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(L.name))continue;const re=Px(L.arguments),ae=Zt(re.destination||re.destination_path||re.file_path||re.path||re.filename);ae&&r.add(ae)}for(const L of S.values()){o.toolBatches=(o.toolBatches||0)+1,o.toolTimeMs=(o.toolTimeMs||0)+L.ms,L.waited&&(o.toolTimeIncludesApproval=!0);const P=[...L.names.keys()].sort();(!o.slowestToolBatch||L.ms>o.slowestToolBatch.ms)&&(o.slowestToolBatch={ms:L.ms,calls:L.calls,tools:P});const W=(N=o.toolBreakdown)==null?void 0:N[P[0]];if(P.length===1&&W)W.ms=(W.ms||0)+L.ms;else for(const G of P){const Y=(T=o.toolBreakdown)==null?void 0:T[G];Y&&(Y.sharedBatches=(Y.sharedBatches||0)+1)}}return o.changedFiles=[...r],c&&(delete o.inputTokens,delete o.outputTokens),Number.isFinite(l)&&Number.isFinite(u)&&(o.durationMs=Math.max(0,u-l)),{tools:[...t.values()],statistics:o}}function gN(e){const t=bn(bn(e).ledgers);return Object.entries(t).flatMap(([n,r])=>km(bn(r).items).map((o,l)=>({runId:n,cursor:Number(o.cursor)||l+1,record:Object.keys(bn(o.record)).length?bn(o.record):o})))}function tm(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function Vy(e){var r;const t=e==null?void 0:e.items;if(!t||!t.length)return null;let n=0;for(let o=0;o<t.length;o+=1)((r=t[o])==null?void 0:r.kind)==="file"&&(n+=1);return n>0?n:null}function Gy(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function Dx(e){const t=[],n=[],r=e==null?void 0:e.items;if(r&&r.length){for(let l=0;l<r.length;l+=1){const u=r[l];if(!u||u.kind!=="file")continue;const c=typeof u.webkitGetAsEntry=="function"?u.webkitGetAsEntry():null,f=typeof u.getAsFile=="function"?u.getAsFile():null;c!=null&&c.isDirectory?n.push(c.name||(f==null?void 0:f.name)||"folder"):f&&t.push(f)}return{files:t,folders:n}}const o=e==null?void 0:e.files;if(o)for(let l=0;l<o.length;l+=1)o[l]&&t.push(o[l]);return{files:t,folders:n}}function yN(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 wN={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function mf(e){return String(e).padStart(2,"0")}function vN(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 o=wN[String(t||"").toLowerCase()]||r.split(".").pop()||"bin",l=`${n.getFullYear()}-${mf(n.getMonth()+1)}-${mf(n.getDate())} at ${mf(n.getHours())}.${mf(n.getMinutes())}.${mf(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!r?"Pasted image":"Pasted file"} ${l}.${o}`}function xN(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}=Dx(e);return r.map(o=>{const l=vN(o.name,o.type,t);return l===o.name?o:new File([o],l,{type:o.type,lastModified:o.lastModified})})}class bN{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}}function jN(e,t){if(e.kind==="ask-user"){if(t.kind==="choice"||t.kind==="free-text")return e.onSubmit(t.answer);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();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")}function SN(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function kN(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"})]})}function NN(e){var Y;const t=e.interaction,[n,r]=m.useState(""),[o,l]=m.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[u,c]=m.useState(null),[f,_]=m.useState(!1),[p,y]=m.useState(""),[w,x]=m.useState(null),S=`${t.kind}:${t.id}`,j=m.useRef(S),C=m.useRef(!1),N=m.useRef(!1),T=m.useRef(!0),L=m.useRef(0);j.current!==S&&(j.current=S,C.current=!1,N.current=!1,L.current+=1);const P=!!e.disabled||u!==null||f||C.current||N.current,W=async(J,re)=>{var B;if(e.disabled||C.current||N.current)return;const ae=S,ue=++L.current;C.current=!0,x(null),y(""),c(J);try{if(await re(),!T.current||j.current!==ae||L.current!==ue)return;N.current=!0,_(!0),y("Response sent. Waiting for the workflow to continue.")}catch(A){if(!T.current||j.current!==ae||L.current!==ue)return;x({submission:J,message:SN(A)}),y("The action failed. You can try again."),(B=e.onError)==null||B.call(e,A)}finally{if(!T.current||j.current!==ae||L.current!==ue)return;C.current=!1,c(null)}};m.useEffect(()=>{r(""),l(t.kind==="event-wait"&&t.initialPayload||""),x(null),c(null),_(!1),y("")},[S]),m.useEffect(()=>(T.current=!0,()=>{T.current=!1,L.current+=1,C.current=!1}),[]);const G=()=>{w&&W(w.submission,()=>jN(t,w.submission))};return s.jsxs("section",{className:"pc-workflow-interaction","aria-labelledby":`pc-workflow-interaction-${S}`,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:16}),s.jsxs("div",{children:[s.jsx("h3",{tabIndex:-1,id:`pc-workflow-interaction-${S}`,children:t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required")}),t.description?s.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),t.kind==="ask-user"?s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),(Y=t.choices)!=null&&Y.length?s.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(J=>s.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice",disabled:P||J.disabled,onClick:()=>void W({kind:"choice",answer:J.id},()=>t.onSubmit(J.id)),children:[s.jsx("span",{children:J.label}),J.description?s.jsx("small",{children:J.description}):null]},J.id))}):null,t.allowFreeText!==!1?s.jsxs("div",{className:"pc-workflow-interaction__entry",children:[s.jsx("textarea",{"aria-label":"Response",value:n,onChange:J=>r(J.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:2,disabled:P,onKeyDown:J=>{J.key!=="Enter"||J.shiftKey||J.nativeEvent.isComposing||J.keyCode===229||(J.preventDefault(),n.trim()&&W({kind:"free-text",answer:n},()=>t.onSubmit(n)))}},`${S}:text`),s.jsx("button",{type:"button",className:"pc-btn",disabled:P||!n.trim(),onClick:()=>void W({kind:"free-text",answer:n},()=>t.onSubmit(n)),children:(u==null?void 0:u.kind)==="free-text"?"Sending…":t.submitLabel||"Submit"})]}):null]}):t.kind==="tool-approval"?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?s.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail}):null,s.jsxs("div",{className:"pc-workflow-interaction__buttons",children:[s.jsx("button",{type:"button",className:"pc-workflow-interaction__deny",disabled:P,onClick:()=>void W({kind:"deny"},t.onDeny),children:(u==null?void 0:u.kind)==="deny"?"Denying…":t.denyLabel||"Deny"}),s.jsx("button",{type:"button",className:"pc-btn",disabled:P,onClick:()=>void W({kind:"approve"},t.onApprove),children:(u==null?void 0:u.kind)==="approve"?"Approving…":t.approveLabel||"Approve"}),t.onApproveAll?s.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-all",disabled:P,onClick:()=>void W({kind:"approve-all"},t.onApproveAll),children:(u==null?void 0:u.kind)==="approve-all"?"Approving…":t.approveAllLabel||"Allow all"}):null]}),t.onApproveAll&&t.approveAllDescription?s.jsx("p",{className:"pc-workflow-interaction__scope",children:t.approveAllDescription}):null]}):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:J=>l(J.target.value),placeholder:t.payloadPlaceholder||"Enter payload",rows:2,"aria-label":t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload"),disabled:P},`${S}:payload`)]}),s.jsx("div",{className:"pc-workflow-interaction__buttons",children:s.jsx("button",{type:"button",className:"pc-btn",disabled:P,onClick:()=>void W({kind:"event",payload:o},()=>t.onSend(o)),children:(u==null?void 0:u.kind)==="event"?"Sending…":t.sendLabel||"Send event"})})]}),w?s.jsx(kN,{message:w.message,onRetry:G,disabled:P}):null,s.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:p})]})}function nm(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function CN(e){const[t,n]=m.useState(!1),[r,o]=m.useState(!1),[l,u]=m.useState(!1),[c,f]=m.useState(null),_=m.useRef(!0),p=m.useRef(!1),y=m.useRef(!1),w=m.useRef(!1),x=m.useRef(0),S=m.useRef(0),j=m.useRef(0);m.useEffect(()=>(_.current=!0,()=>{_.current=!1,x.current+=1,S.current+=1,j.current+=1,p.current=!1,y.current=!1,w.current=!1}),[]);const C=!!e.blockedNotice,N=!!e.disabled||C,T=!!e.busy||t,L=t||!!e.busy&&!e.sendWhileBusy,P=e.stopState||null,W=(P==null?void 0:P.phase)==="stopping",G=typeof e.onFiles=="function",Y=m.useRef(null),[J,re]=m.useState(null),[ae,ue]=m.useState(""),B=m.useRef(e.onFiles);B.current=e.onFiles;const A=m.useRef(N);A.current=N;const $=async(Z,X)=>{const le=B.current;if(le){if(A.current){f({action:"attach",message:"attachments are unavailable right now."});return}if(X.length)f({action:"attach",message:yN(X)});else if(Z.length)f(null);else{f({action:"attach",message:"the drop contained no files."});return}if(Z.length){ue(`Attaching ${Z.length} ${Z.length===1?"file":"files"}…`);try{await le(Z)}catch(_e){_.current&&f({action:"attach",message:nm(_e)})}}}},z=m.useRef($);z.current=$,m.useEffect(()=>{if(!G||typeof window>"u")return;const Z=new bN;let X=0;const le=Fe=>!!(Y.current&&Fe instanceof Node&&Y.current.contains(Fe)),_e=()=>{Z.reset(),X&&window.clearInterval(X),X=0,re(null)},he=()=>{X||(X=window.setInterval(()=>{Z.active(Date.now())||_e()},250))},ye=Fe=>{var Ye;if(!tm((Ye=Fe.dataTransfer)==null?void 0:Ye.types))return;Z.enter(Date.now());const tt=le(Fe.target),lt=Vy(Fe.dataTransfer);re(Se=>Se&&Se.over===tt&&Se.count===(lt??Se.count)?Se:{count:lt??(Se==null?void 0:Se.count)??null,over:tt}),he()},Ee=Fe=>{var lt;if(!tm((lt=Fe.dataTransfer)==null?void 0:lt.types))return;Fe.preventDefault(),Z.over(Date.now());const tt=le(Fe.target);Fe.dataTransfer&&(Fe.dataTransfer.dropEffect=tt&&!A.current?"copy":"none"),re(Ye=>Ye&&Ye.over===tt?Ye:{count:(Ye==null?void 0:Ye.count)??Vy(Fe.dataTransfer),over:tt}),he()},ze=Fe=>{var tt;tm((tt=Fe.dataTransfer)==null?void 0:tt.types)&&(Z.leave(Date.now())||_e())},Be=Fe=>{var Re;if(!tm((Re=Fe.dataTransfer)==null?void 0:Re.types))return;const tt=le(Fe.target),lt=Fe.defaultPrevented&&!tt;if(Fe.preventDefault(),_e(),lt)return;if(!tt){f({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:Ye,folders:Se}=Dx(Fe.dataTransfer);z.current(Ye,Se)},gt=Fe=>{Fe.key==="Escape"&&Z.depth>0&&_e()};return window.addEventListener("dragenter",ye),window.addEventListener("dragover",Ee),window.addEventListener("dragleave",ze),window.addEventListener("drop",Be),window.addEventListener("dragend",_e),window.addEventListener("blur",_e),window.addEventListener("keydown",gt),()=>{window.removeEventListener("dragenter",ye),window.removeEventListener("dragover",Ee),window.removeEventListener("dragleave",ze),window.removeEventListener("drop",Be),window.removeEventListener("dragend",_e),window.removeEventListener("blur",_e),window.removeEventListener("keydown",gt),X&&window.clearInterval(X)}},[G]);const E=Z=>{if(!G||N)return;const X=xN(Z.clipboardData);X.length&&(Z.preventDefault(),$(X,[]))},te=J?s.jsxs("div",{className:["pc-workflow-chat__dropzone",J.over?"is-over":"",N?"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:N?"Attachments are unavailable right now":Gy(J.count)}),N?null:s.jsx("span",{children:J.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,O=J?N?"Attachments are unavailable right now":Gy(J.count):ae,F=async()=>{const Z=String(e.draft||"");if(N||p.current||!e.sendWhileBusy&&e.busy||!Z.trim())return;const X=++x.current;p.current=!0,f(null),n(!0);try{await e.onSend(Z)}catch(le){_.current&&x.current===X&&f({action:"send",message:nm(le)})}finally{_.current&&x.current===X&&(p.current=!1,n(!1))}},K=async()=>{if(N||y.current||!e.onCancel)return;const Z=++S.current;y.current=!0,f(null),o(!0);try{await e.onCancel()}catch(X){_.current&&S.current===Z&&f({action:"cancel",message:nm(X)})}finally{_.current&&S.current===Z&&(y.current=!1,o(!1))}},R=async()=>{if(N||w.current||!e.onAttach)return;const Z=++j.current;w.current=!0,f(null),u(!0);try{await e.onAttach()}catch(X){_.current&&j.current===Z&&f({action:"attach",message:nm(X)})}finally{_.current&&j.current===Z&&(w.current=!1,u(!1))}},Q=()=>{c&&(c.action==="send"&&F(),c.action==="cancel"&&K(),c.action==="attach"&&R())};return s.jsxs("section",{ref:Y,className:["pc-workflow-chat",J?"pc-workflow-chat--dragging":"",J!=null&&J.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?s.jsx("header",{className:"pc-workflow-chat__header",children:e.header}):null,s.jsx("div",{className:"pc-workflow-chat__transcript",children:s.jsx(Dg,{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(NN,{interaction:e.interaction,disabled:N}):null,C?s.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${C?"blocked":""}`})}),c?s.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[s.jsxs("span",{children:["Could not ",c.action==="send"?"send this message":c.action==="attach"?"attach a file":"stop the run",": ",c.message]}),s.jsx("button",{type:"button",onClick:Q,disabled:N,children:"Try again"})]}):null,s.jsxs("div",{className:"pc-workflow-chat__composer",children:[s.jsx(Fg,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void F(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:N,busy:L,sendLabel:e.sendLabel,busyLabel:e.busyLabel,rows:2,leading:e.attachments?s.jsx("div",{className:"pc-workflow-chat__attachments",children:e.attachments}):null,overlay:te,onPaste:G?E: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",title:"Attach file",disabled:N||l,onClick:()=>void R(),children:[s.jsx(Qe,{name:"paperclip",size:16}),s.jsx("span",{children:l?"Attaching…":"Attach"})]}):null,e.composerExtras,T&&e.onCancel?s.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:N||r||W,onClick:()=>void K(),children:[s.jsx(Qe,{name:"x",size:14}),s.jsx("span",{children:r||W?"Stopping…":"Stop"})]}):P?s.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${P.phase}`,role:"status","aria-live":"polite",children:P.label}):null]})}),G?s.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:O}):null]}),e.footer?s.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}const ep="llm.delta",sm="llm.delta_end";function EN(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function pc(e){return typeof e=="string"&&e.trim()!==""}function $N(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function AN(e){return"reason"in e}function TN(e,t){const n=EN(e),r=n==null?void 0:n.kind,o=typeof r=="string"&&r?r:n&&"reason"in n?sm:ep,l=f=>{throw new Error(`Malformed ${o} event from the gateway: ${f}`)};if(!n)return l("the payload is not an object");r!==void 0&&r!==ep&&r!==sm&&l(`unknown kind ${JSON.stringify(r)}`),pc(n.run_id)||l("run_id is missing"),pc(n.call_id)||l("call_id is missing"),$N(n.seq)||l("seq is not a non-negative integer");const u=r?r===sm:"reason"in n;n.root_run_id!==void 0&&!pc(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!pc(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");const c={run_id:n.run_id,...pc(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...pc(n.node_id)?{node_id:n.node_id}:{},call_id:n.call_id,seq:n.seq};return u?(["completed","failed","cancelled","unavailable"].includes(String(n.reason))||l(`unknown reason ${JSON.stringify(n.reason)}`),n.detail!==void 0&&n.detail!==null&&typeof n.detail!="string"&&l("detail is not a string"),{kind:sm,...c,reason:n.reason,...pc(n.detail)?{detail:n.detail}:{}}):(typeof n.text!="string"&&l("text is not a string"),n.channel!=="content"&&n.channel!=="reasoning"&&l(`unknown channel ${JSON.stringify(n.channel)}`),typeof n.snapshot!="boolean"&&l("snapshot is not a boolean"),{kind:ep,...c,text:n.text,channel:n.channel,snapshot:n.snapshot})}const MN={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 RN(e){return`This reply is not streamed: ${e?MN[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}function LN(e){return e.toolApprovalGranted?null:e.interaction}const Ky={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function Nt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function vt(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function Cf(e){return Array.isArray(e)?e:[]}function Kr(e){return vt(e==null?void 0:e.status).toLowerCase()||"unknown"}function vs(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function cl(e){const t=Nt(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function IN(e){const t=Nt(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function tp(e){const t=n=>{if(Array.isArray(n))return n.map(t);const r=Nt(n);if(!r)return n;const o={};for(const l of Object.keys(r).sort())o[l]=t(r[l]);return o};try{return JSON.stringify(t(e))}catch{return"[unserializable]"}}function Zp(e){if(typeof e=="string")return e.trim();const t=Nt(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 Ru(e){const t=Zp(e);if(t)return t;if(!Nt(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function Yy(e){if(!e)return"";for(const r of["prompt","request","task","message","query","input"]){const o=vt(e[r]);if(o)return o}const t=Nt(e.context);for(const r of["task","message"]){const o=vt(t==null?void 0:t[r]);if(o)return o}const n=Cf(t==null?void 0:t.messages);for(let r=n.length-1;r>=0;r-=1){const o=Nt(n[r]);if(vt(o==null?void 0:o.role).toLowerCase()!=="user")continue;const l=vt(o==null?void 0:o.content);if(l)return l}return""}function Fx(e){const t=Nt(e.result);return Nt(t==null?void 0:t.wait)}function np(e){return e?vt(e.reason)==="subworkflow"||vt(e.wait_key).startsWith("subworkflow:"):!1}function Jy(e,t){return!!(e&&e.runId===t.runId&&vt(e.wait.wait_key)===vt(t.wait.wait_key))}function Qp(e){return Nt(e.effect)||{}}function ON(e,t){return vt(e.run_id)||t}function Xy(e){return vt(e.ended_at)||vt(e.started_at)||void 0}function Zy(e){const t=new Set,n=_=>{const p=vt(_);p&&t.add(p)},r=Nt(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 o=Qp(e),l=Nt(o.payload);vt(o.type)==="start_subworkflow"&&(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 u=Fx(e),c=Nt(u==null?void 0:u.details);n(c==null?void 0:c.sub_run_id),n(c==null?void 0:c.subRunId),n(c==null?void 0:c.child_run_id);const f=vt(u==null?void 0:u.wait_key);return f.startsWith("subworkflow:")&&n(f.slice(12)),[...t]}class PN{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...Ky},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;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}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.historicalEvidence.clear(),this.approvedWaits.clear(),this.grantedToolWaits.clear(),this.resolvedWaits.clear(),this.liveReplies.clear(),this.closedLiveCalls.clear(),this.shownLiveCalls.clear(),this.liveDirty.clear(),this.lastLiveRender=-1/0,this.liveRenderTimer&&(clearTimeout(this.liveRenderTimer),this.liveRenderTimer=null),this.set({...Ky})}dispose(){this.reset(),this.subscribers.clear()}async load(t){const n=vt(t);if(this.reset(),!n)return;const r=++this.generation,o=new AbortController;this.controller=o,this.rootRunId=n,this.set({...this.snapshot,loading:!0,status:"loading",error:null,connection:"connecting"});try{const[l,u]=await Promise.all([this.transport.getRun(n,o.signal),this.transport.getHistory(n,o.signal)]);if(!this.live(r))return;const c=Nt(l),f=Nt(c==null?void 0:c.waiting),_=Kr(c);if(await this.ingestHistory(u,n,r),!this.live(r))return;if(this.set({...this.snapshot,run:c,status:_,loading:!1,...f&&!vs(_)?{interaction:this.interactionWith({runId:n,wait:f})}:{}}),c&&this.updateRunState(n,c),f)for(const p of Zy({result:{wait:f}}))p!==n&&this.catchUpAndWatch(p,r);await this.catchUpAndWatch(n,r),this.pollRootLifecycle(n,r)}catch(l){!o.signal.aborted&&this.live(r)&&this.fail(l)}}async sendCommand(t,n={}){var p,y;t==="cancel"&&(this.toolApprovalStopped=!0,this.revokeToolApproval(),this.stopRequested=!0,this.recomputeStop());const r=vt(n.wait_key),o=t==="resume"?r?this.interactionRunId()||this.rootRunId:this.rootRunId:t==="emit_event"?this.interactionRunId()||this.rootRunId:this.rootRunId;if(!o)throw new Error("No workflow run is loaded");const l=t==="resume"&&r&&((p=this.snapshot.interaction)==null?void 0:p.stepId)||"",u=`${o}\0${t}\0${l}\0${tp(n)}`;let c=this.commandIds.get(u);c||(c=this.newCommandId(),this.commandIds.set(u,c));const f=this.generation,_=(y=this.controller)==null?void 0:y.signal;try{const w=await this.transport.submitCommand({command_id:c,run_id:o,type:t,payload:n,...this.options.clientId?{client_id:this.options.clientId}:{}},_);if(!this.live(f))return w;const x=Nt(w);if(x&&x.accepted===!1)throw t==="cancel"&&(this.stopRequested=!1,this.recomputeStop()),new Error(vt(x.detail)||"Gateway did not accept the command");return this.commandIds.delete(u),o===this.rootRunId&&["pause","resume","cancel"].includes(t)&&this.refreshRunState(o,f),w}catch(w){throw this.live(f)&&this.fail(w,!1),w}}resume(t){const n=this.requireInteraction();return this.sendCommand("resume",{wait_key:vt(n.wait.wait_key),payload:{response:t}})}approve(t,n){const r=this.requireInteraction();if(vs(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(r.runId!==n.runId||vt(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 o=this.generation;return this.sendCommand("resume",{wait_key:vt(r.wait.wait_key),payload:{approved:!!t}}).then(l=>{if(!this.live(o))return l;const u=this.occurrenceKey(r);return this.approvedWaits.add(u),t&&this.isToolApproval(r)&&!this.grantedToolWaits.has(u)&&(this.grantedToolWaits.add(u),this.set({...this.snapshot})),l})}async approveWithPolicyChange(t,n){const r=this.generation,o=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)||o!==this.approvalEpoch||this.toolApprovalStopped||vs(this.snapshot.status))&&n()}async allowAllToolsForRun(t){const n=this.generation,r=this.approvalEpoch,o=this.requireInteraction();if(!this.isToolApproval(o))throw new Error("This is not a tool approval request.");await this.approve(!0,t),!(!this.live(n)||r!==this.approvalEpoch||vs(this.snapshot.status))&&(this.approvedWaits.add(`${t.runId}:${t.waitKey}${o.stepId?`:${o.stepId}`:""}`),this.set({...this.snapshot,autoApproveTools:!0}))}revokeToolApproval(){this.approvalEpoch+=1,this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1})}setToolApprovalPolicy(t){tp(t)!==tp(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}:${vt(t.wait.wait_key)}${t.stepId?`:${t.stepId}`:""}`}interactionWith(t){const n=this.snapshot.interaction;return n&&np(t.wait)&&!np(n.wait)?n:n&&Jy(n,t)&&t.stepId===void 0&&n.stepId!==void 0?{...t,stepId:n.stepId}:t}adoptDurableWait(t,n){const r=Nt(n.waiting);if(!r||Kr(n)!=="waiting"||np(r)||vs(this.snapshot.status)||this.resolvedWaits.has(`${t}:${vt(r.wait_key)}`))return;const o=this.interactionWith({runId:t,wait:r}),l=this.snapshot.interaction;l&&Jy(l,o)&&l.stepId===o.stepId||this.set({...this.snapshot,interaction:o})}coveredByStandingPermission(t,n){var r;return t.loading||this.toolApprovalStopped||this.toolApprovalSuspended||!this.toolApprovalPolicy&&!t.autoApproveTools||vs(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:!!vt(n.wait.wait_key)}present(t){const n=t.interaction,r=n?this.occurrenceKey(n):"",o=!!(n&&this.isToolApproval(n)&&(this.grantedToolWaits.has(r)||!this.approvedWaits.has(r)&&this.coveredByStandingPermission({...t,loading:!1},n)));if(!o&&!this.snapshot.toolApprovalGranted&&!t.toolApprovalGranted)return t.toolApprovalGranted===!1?t:{...t,toolApprovalGranted:!1};let l=!1;const u=t.messages.map(c=>{var p;const f=c.toolActivity;if(!f||((p=this.toolActivities.get(f.id))==null?void 0:p.status)!=="waiting")return c;const _=o&&f.runId===(n==null?void 0:n.runId)?"running":"waiting";return f.status===_?c:(l=!0,this.toolMessage({...f,status:_}))});return{...t,toolApprovalGranted:o,...l?{messages:u}:{}}}toolCallsMatch(t,n){var o;const r=Cf((o=Nt(t.wait.details))==null?void 0:o.tool_calls);return r.length>0&&r.every(l=>{var c;const u=vt((c=Nt(l))==null?void 0:c.name);return!!u&&n.includes(u)})}isToolApproval(t){const n=Nt(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:vt(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 o=this.generation,l=this.approvalEpoch;this.approve(!0,n).catch(u=>{if(this.live(o)){if(this.grantedToolWaits.delete(r),l!==this.approvalEpoch){this.set({...this.snapshot});return}this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1}),this.fail(u,!1)}})}emitEvent(t){return this.sendCommand("emit_event",t)}cancel(){return this.sendCommand("cancel",{})}requireInteraction(){if(!this.snapshot.interaction)throw new Error("This workflow is not waiting for input");if(!vt(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(t);for(const n of this.subscribers)n();this.autoApproveCurrentWait()}async catchUpAndWatch(t,n){var r;if(!(!this.live(n)||this.watchedRuns.has(t))){this.watchedRuns.add(t);try{if(t!==this.rootRunId)try{const o=Nt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));if(!this.live(n))return;o&&this.updateRunState(t,o)}catch(o){if(!this.live(n))return;if(cl(o))throw o;this.fail(o,!1)}if(await this.catchUp(t,n),!this.live(n)||vs(Kr(this.runStates.get(t)||null)))return;this.childCatchUpAttempts.delete(t),this.watch(t,n)}catch(o){if(!this.live(n))return;if(this.watchedRuns.delete(t),t===this.rootRunId)throw o;if(cl(o)){this.fail(o);return}const l=(this.childCatchUpAttempts.get(t)||0)+1;if(this.childCatchUpAttempts.set(t,l),this.fail(o,!1),l>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(l-1))),this.live(n)&&this.catchUpAndWatch(t,n)}}}async catchUp(t,n){var r;for(let o=0;o<100&&this.live(n);o+=1){const l=this.cursors.get(t)||0,u=await this.transport.getLedger(t,l,(r=this.controller)==null?void 0:r.signal);if(!this.live(n))return;const c=Nt(u),f=Array.isArray(u)?u:Cf(c==null?void 0:c.items);for(const p of f)this.ingestItem(t,p);const _=Number(c==null?void 0:c.next_after);if(!f.length||!Number.isFinite(_)||_<=l)break;this.cursors.set(t,_)}}async watch(t,n){try{await this.followStream(t,n)}finally{this.live(n)&&this.closeLiveRepliesVia(t)}}async followStream(t,n){var o;let r=0;for(;this.live(n)&&!vs(Kr(this.runStates.get(t)||null));){const l=this.cursors.get(t)||0;this.set({...this.snapshot,connection:r?"reconnecting":"connecting"});try{let u=!1;const c=()=>{!this.live(n)||u||(u=!0,this.set({...this.snapshot,connection:"connected",error:null}))};if(this.dropLiveRepliesVia(t),await this.transport.streamLedger(t,l,_=>{this.live(n)&&(c(),this.ingestItem(t,_))},this.controller.signal,c,_=>{this.live(n)&&(c(),this.ingestDelta(t,_))}),!this.live(n)||(await this.catchUp(t,n),!this.live(n)))return;const f=Nt(await this.transport.getRun(t,(o=this.controller)==null?void 0:o.signal));if(!this.live(n))return;f&&this.updateRunState(t,f),r+=1}catch(u){if(!this.live(n))return;if(r+=1,this.fail(u,!1),cl(u)){this.set({...this.snapshot,connection:"disconnected"});return}}if(r>=5||!this.live(n))break;await this.waitForRetry(Math.min(2e3,150*2**(r-1)))}if(this.live(n)){if(vs(Kr(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 o=Nt(t);if(!o)return;const l=Nt(o.session),u=Cf(l==null?void 0:l.turns).map(Nt).filter(_=>!!_);if(await this.hydrateHistoricalSessionRuns(u,n,r),!this.live(r))return;for(const _ of u){const p=vt(_==null?void 0:_.run_id)||n;this.ingestSessionTurn(_,n,p!==n&&this.historicalRuns.get(p)||null)}const c=`turn:${n}:user`;if(!this.seenMessages.has(c)){const _=Yy(Nt(o.input_data));_&&this.addMessage({id:c,role:"user",content:_})}const f=Nt(o.ledgers);if(f)for(const[_,p]of Object.entries(f)){const y=Nt(p);for(const w of Cf(y==null?void 0:y.items))this.ingestItem(_,w)}}ingestSessionTurn(t,n,r){if(!t)return;const o=vt(t.run_id)||n,l=Nt(t.input_data)||Nt(t.input)||{},u=vt(t.prompt)||Yy(l);u&&this.addMessage({id:`turn:${o}:user`,role:"user",content:u,ts:vt(t.created_at)||void 0});const c=this.historicalRunFailures.get(o);if(c){const y=vt(t.answer)||Zp(t.output),w=c.missing?"is unavailable because the run no longer exists":"could not be restored",x=y?` Saved reply (not verified as the final result): ${y}`:"";this.addMessage({id:`history:${o}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${w}.${x}`});return}const _=(r&&vs(Kr(r))?Ru(r.output):"")||(r?vt(t.answer)||Zp(t.output):""),p=this.historicalEvidence.get(o);for(const y of(p==null?void 0:p.tools)||[])this.upsertTool(y);_&&this.addRunAssistantMessage(o,{id:`final:${o}`,role:"assistant",content:_,runId:o,statistics:p==null?void 0:p.statistics,ts:vt(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,r){const o=[...new Set(t.map(f=>vt(f.run_id)).filter(f=>f&&f!==n&&!this.historicalRuns.has(f)&&!this.historicalRunFailures.has(f)))];if(!o.length||!this.live(r))return;let l=0,u=!1;const c=async()=>{var f,_,p;for(;!u&&this.live(r);){const y=o[l++];if(!y)return;try{const w=Nt(await this.transport.getRun(y,(f=this.controller)==null?void 0:f.signal));if(!this.live(r))return;if(w){this.historicalRuns.set(y,w);try{const x=await this.transport.getHistory(y,(_=this.controller)==null?void 0:_.signal);if(!this.live(r))return;this.historicalEvidence.set(y,Q_(gN(x)))}catch(x){if(!this.live(r))return;if(cl(x))throw x;this.fail(new Error(`Earlier turn activity could not be restored: ${x instanceof Error?x.message:String(x)}`),!1)}}else this.historicalRuns.set(y,null),this.historicalRunFailures.set(y,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(w){if(!this.live(r))return;const x=IN(w)===404;this.historicalRuns.set(y,null),this.historicalRunFailures.set(y,{missing:x,detail:w instanceof Error?w.message:vt((p=Nt(w))==null?void 0:p.detail)||"request failed"}),cl(w)&&(u=!0,this.fail(w))}}};if(await Promise.all(Array.from({length:Math.min(4,o.length)},()=>c())),u&&this.live(r))for(const f of o)!this.historicalRuns.has(f)&&!this.historicalRunFailures.has(f)&&(this.historicalRuns.set(f,null),this.historicalRunFailures.set(f,{missing:!1,detail:"authorization expired before this historical run could be restored"}))}ingestItem(t,n){const r=Nt(n),o=Nt(r==null?void 0:r.record)||r;if(!o)return;const l=ON(o,t),u=Number(r==null?void 0:r.cursor),c=Number.isFinite(u)&&u>0?u:(this.cursors.get(l)||0)+1,f=`${l}:${c}`;if(!this.seenRecords.has(f)){if(this.seenRecords.add(f),this.cursors.set(l,Math.max(this.cursors.get(l)||0,c)),this.set({...this.snapshot,records:[...this.snapshot.records,{cursor:c,record:o,runId:l}]}),this.foldRecord(l,o,f),this.snapshot.messages.some(_=>_.id===`final:${this.rootRunId}`)){const _=Q_(this.snapshot.records).statistics;this.set({...this.snapshot,messages:this.snapshot.messages.map(p=>p.id===`final:${this.rootRunId}`?{...p,statistics:_}:p)})}for(const _ of Zy(o))_!==l&&this.catchUpAndWatch(_,this.generation)}}foldRecord(t,n,r){var p,y,w;const o=Qp(n),l=vt(o.type).toLowerCase(),u=Nt(n.result),c=vt(n.status).toLowerCase(),f=Xy(n);if(this.foldStopEvidence(t,n,l,c),["llm_call","tool_calls"].includes(l)&&["started","running"].includes(c)){const x=Date.parse(f||"");(!Number.isFinite(x)||x>=this.displayStatusAt)&&(Number.isFinite(x)&&(this.displayStatusAt=x),this.snapshot.displayStatus&&this.set({...this.snapshot,displayStatus:""}))}if(l==="answer_user"&&c==="completed"){const x=Ru(u)||Ru(Nt(o.payload));x&&this.addRunAssistantMessage(t,{id:`answer:${t}:${r}`,role:"assistant",content:x,ts:f})}if(l==="emit_event"&&c==="completed"){const x=Nt(o.payload)||{},S=Nt(u),j=vt(x.name)||vt(S==null?void 0:S.name),C=x.payload!==void 0?x.payload:S==null?void 0:S.payload;if(["abstract.message","abstractcode.message"].includes(j)){const N=Ru(C);if(N){const T=vt((p=Nt(C))==null?void 0:p.level).toLowerCase(),L=T==="error"?"error":["warn","warning"].includes(T)?"warn":"info";this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Workflow",content:N,level:L,ts:f})}}if(["abstract.status","abstractcode.status"].includes(j)){const N=Nt(C),T=N?N.status??N.text??N.value:C,L=Date.parse(f||"");!vs(this.snapshot.status)&&typeof T=="string"&&(!Number.isFinite(L)||L>=this.displayStatusAt)&&(Number.isFinite(L)&&(this.displayStatusAt=L),this.set({...this.snapshot,displayStatus:T.trim()}))}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(j)){const N=Ru(C);N&&this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Tool activity",content:N,ts:f})}}const _=Fx(n);if(c==="waiting"&&_&&!vs(this.snapshot.status)&&!vs(Kr(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${vt(_.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:_,...vt(n.step_id)?{stepId:vt(n.step_id)}:{}})})),l==="tool_calls")for(const x of Ox(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(x);if(l==="resume"&&(u==null?void 0:u.resumed)===!0){const x=vt((y=Nt(o.payload))==null?void 0:y.wait_key);x&&this.resolvedWaits.add(`${t}:${x}`),((w=this.snapshot.interaction)==null?void 0:w.runId)===t&&(this.set({...this.snapshot,interaction:null}),this.refreshRunState(t,this.generation))}}foldStopEvidence(t,n,r,o){let l=!1;if(r==="llm_call"){const u=vt(n.step_id);if(u){const c=`${t}:${u}`;o==="started"?(this.openLlmSteps.add(c),l=!0):["completed","failed","cancelled","waiting"].includes(o)&&(l=this.openLlmSteps.delete(c)||l),["completed","failed","cancelled"].includes(o)&&this.closeLiveReply(c)}}if(r==="emit_event"&&o==="completed"){const u=Nt(Qp(n).payload)||{},c=Nt(n.result),f=vt(u.name)||vt(c==null?void 0:c.name),_=Nt(u.payload!==void 0?u.payload:c==null?void 0:c.payload);f==="abstract.status"&&vt(_==null?void 0:_.killed_by)==="kill_switch"&&(this.forcedStop=_,l=!0)}l&&this.recomputeStop()}recomputeStop(){let t=null;this.forcedStop?t={phase:"forced",label:vt(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,o=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 l=[this.rootRunId,...[...this.watchedRuns].filter(c=>c!==this.rootRunId)];let u=!1;for(const c of l)try{await this.catchUp(c,t)}catch(f){u=!0,this.live(t)&&(this.fail(f,!1),o=this.snapshot.error)}!u&&o&&this.snapshot.error===o&&(this.set({...this.snapshot,error:null}),o=null),r=Math.min(5e3,r*2)}}finally{this.generation===t&&(this.stopFollowing=!1)}}}addMessage(t){const n=vt(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){return{id:`tool:${t.id}`,role:"system",kind:"tool_activity",title:"Tool activity",runId:t.runId,toolActivity:t,content:JSON.stringify({tool:t.name,status:t.status,arguments:t.arguments,output:t.output,error:t.error},null,2),ts:t.endedAt||t.startedAt}}upsertTool(t){const n=this.toolMessage(t),r=this.snapshot.messages.findIndex(l=>l.id===n.id);if(r<0){this.addMessage(n);return}const o=[...this.snapshot.messages];o[r]=n,this.set({...this.snapshot,messages:o})}addRunAssistantMessage(t,n){this.closeLiveRepliesOfRun(t);const r=`answer:${t}:`,o=`final:${t}`;this.snapshot.messages.some(l=>l.role==="assistant"&&l.content===n.content&&(l.id===o||String(l.id||"").startsWith(r)))||this.addMessage(n)}ingestDelta(t,n){let r;try{r=TN(n)}catch(f){this.fail(f,!1);return}const o=`${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(o,"restarted");return}this.closeLiveReply(o,r.reason==="completed"?void 0:r.reason);return}if(this.closedLiveCalls.has(o)||this.runEnded(r.run_id)||this.runEnded(this.rootRunId))return;const l=this.liveReplies.get(o)||{runId:r.run_id,callId:r.call_id,nodeId:r.node_id||"",via:t,text:"",reasoning:"",seq:{content:-1,reasoning:-1}},u=r.channel==="reasoning"?"reasoning":"text",c=l.seq[r.channel];if(r.snapshot){if(r.seq<c)return;l[u]=r.text}else{if(r.seq<=c)return;l[u]+=r.text}l.seq[r.channel]=r.seq,l.via=t,this.liveReplies.set(o,l),this.liveDirty.add(o),this.scheduleLiveRender()}runEnded(t){return vs(Kr(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 o=this.liveMessage(r),l=t.findIndex(u=>u.id===o.id);l<0?t.push(o):t[l]=o,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 o=`live:${r.runId}:${r.callId}`,l=this.snapshot.messages.findIndex(c=>c.id===o);if(l<0)return;const u=[...this.snapshot.messages];if(n==="restarted"){const c=this.restartNote(t);this.seenMessages.add(String(c.id)),u[l]=c}else if(n){const c=`live-end:${r.runId}:${r.callId}`;this.seenMessages.add(c),u[l]={id:c,role:"system",level:"warn",title:"Reply",runId:r.runId,content:n==="failed"?"The reply stopped because the model call failed.":"The reply stopped because the model call was cancelled."}}else u.splice(l,1);this.set({...this.snapshot,messages:u})}restartNote(t){const n=t.slice(0,t.indexOf(":"));return{id:`live-end:${t}`,role:"system",level:"info",title:"Reply",runId:n,content:"Reply restarted: the model call was interrupted and is running again."}}noteStreamUnavailable(t){const n=`${t.run_id}:${t.call_id}`;this.closeLiveReply(n),this.addMessage({id:`stream-unavailable:${t.run_id}:${t.detail||"unknown"}`,role:"system",level:"info",title:"Reply",runId:t.run_id,content:RN(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 o of[...this.liveReplies.values()])this.closeLiveReply(`${o.runId}:${o.callId}`,r);this.closedLiveCalls.clear(),this.shownLiveCalls.clear();return}this.closeLiveRepliesVia(t,r);for(const o of[...this.closedLiveCalls])o.startsWith(`${t}:`)&&this.closedLiveCalls.delete(o);for(const o of[...this.shownLiveCalls])o.startsWith(`${t}:`)&&this.shownLiveCalls.delete(o)}dropLiveRepliesVia(t){const n=new Set;for(const[r,o]of this.liveReplies)o.via===t&&(this.liveReplies.delete(r),this.liveDirty.delete(r),n.add(`live:${o.runId}:${o.callId}`));n.size&&this.set({...this.snapshot,messages:this.snapshot.messages.filter(r=>!n.has(String(r.id)))})}fail(t,n=!0){var r,o,l;cl(t)&&(this.approvalEpoch+=1,this.toolApprovalStopped=!0,this.toolApprovalSuspended=!0,(o=(r=this.options).onAuthError)==null||o.call(r,t)),this.set({...this.snapshot,error:t instanceof Error?t.message:vt((l=Nt(t))==null?void 0:l.detail)||String(t),...cl(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,o=>o.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 l;if(this.runStates.set(t,n),vs(Kr(n))&&this.endLiveRepliesOfRun(t,Kr(n)),t!==this.rootRunId){vs(Kr(n))&&((l=this.snapshot.interaction)==null?void 0:l.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const r=Kr(n),o=vs(r);if(o){const u=Ru(n.output);u&&this.upsertFinal(t,u,Xy(n))}this.set({...this.snapshot,run:n,status:r,...o?{interaction:null,autoApproveTools:!1,displayStatus:""}:{}}),o||this.adoptDurableWait(t,n),(this.stopRequested||this.forcedStop)&&this.recomputeStop()}upsertFinal(t,n,r){this.closeLiveRepliesOfRun(t);const o=`final:${t}`;this.seenMessages.add(o);const l={id:o,role:"assistant",content:n,ts:r,runId:t,statistics:Q_(this.snapshot.records).statistics},u=this.snapshot.messages.findIndex(f=>f.id===o||String(f.id||"").startsWith(`answer:${t}:`)&&f.content===n);if(u<0){this.set({...this.snapshot,messages:[...this.snapshot.messages,l]});return}const c=[...this.snapshot.messages];c[u]=l,this.set({...this.snapshot,messages:c})}async refreshRunState(t,n){var r;try{const o=Nt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));o&&this.live(n)&&this.updateRunState(t,o)}catch(o){this.live(n)&&this.fail(o,!1)}}async pollRootLifecycle(t,n){var r;for(;this.live(n)&&this.rootRunId===t&&!vs(Kr(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||vs(Kr(this.runStates.get(t)||null)))return;try{const o=Nt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));o&&this.live(n)&&this.rootRunId===t&&this.updateRunState(t,o)}catch(o){if(!this.live(n))return;if(cl(o)){this.fail(o);return}this.fail(o,!1)}}}waitForRetry(t){var o;const n=(o=this.controller)==null?void 0:o.signal;if(!n||n.aborted)return Promise.resolve();const r=n;return new Promise(l=>{const u=setTimeout(f,t),c=()=>{clearTimeout(u),f()};function f(){r.removeEventListener("abort",c),l()}r.addEventListener("abort",c,{once:!0})})}}function DN(e){const t=m.useMemo(()=>new PN(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=m.useSyncExternalStore(o=>t.subscribe(o),()=>t.getSnapshot(),()=>t.getSnapshot()),r=String(e.runId||"").trim();return m.useEffect(()=>{t.setToolApprovalPolicy(e.enabled===!1?{enabledTools:[],autoApproveTools:[]}:e.toolApprovalPolicy??null)},[t,e.toolApprovalPolicy,e.enabled]),m.useEffect(()=>{if(e.enabled===!1||!r){t.reset();return}return t.load(r),()=>t.reset()},[t,r,e.enabled]),{controller:t,snapshot:n}}function gc(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 Qy(e){return["session","workflow","run","global"].includes(e)?e:null}function dl(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 FN(e,t){const n=e.wait,r=fr(n.wait_key),o=[dl(n),dl(gc(n.details))];for(const l of t){if(l.runId!==e.runId)continue;const u=l.record,c=gc(u.result),f=gc(c==null?void 0:c.wait),_=gc(u.effect),p=gc(_==null?void 0:_.payload);fr(f==null?void 0:f.wait_key)!==r&&fr(p==null?void 0:p.wait_key)!==r||o.push(dl(u),dl(p),dl(gc(p==null?void 0:p.details)),dl(f),dl(gc(f==null?void 0:f.details)))}return o}function sp(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function zx(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function zN(e,t,n){if(!n)return null;const r=`evt:${t}:${n}:`;if(!e.startsWith(r))return null;const o=e.slice(r.length);return o?zx(t,n,o):null}function BN(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const r=fr(e.wait.wait_key),o=/^evt:(session|workflow|run|global):/.exec(r);if(!o)return{target:null,error:"The gateway did not provide a canonical event wait key."};const l=Qy(o[1]);if(!l)return{target:null,error:"The event wait uses an unsupported scope."};const u=FN(e,Array.isArray(t)?t:[]),c=new Map;for(const w of u){const x=Qy(w.scope);if(!x||!w.name)continue;if(x!==l)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const S=`evt:${x}:`,j=`:${w.name}`;if(!r.startsWith(S)||!r.endsWith(j)||r.length<=S.length+j.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const C=r.slice(S.length,-j.length),N=sp(x,w);if(N&&N!==C)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const T=zx(x,C,w.name);c.set(`${T.scope}\0${T.scopeId}\0${T.name}`,T)}if(c.size>1)return{target:null,error:"Multiple event targets match this wait; routing is unavailable."};if(c.size===1)return{target:[...c.values()][0]};const f=new Set;l==="run"&&f.add(e.runId),l==="global"&&f.add("global");for(const w of u){const x=sp(l,w);x&&f.add(x)}if(fr(n==null?void 0:n.run_id)===e.runId){const w=dl(n||null),x=sp(l,w);x&&f.add(x)}const p=[...f].map(w=>zN(r,l,w)).filter(w=>!!w),y=new Map(p.map(w=>[`${w.scope}\0${w.scopeId}\0${w.name}`,w]));return y.size===1?{target:[...y.values()][0]}:y.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."}}const zg=e=>bt(`runs/${encodeURIComponent(e)}/workspace`);function UN(e){return zg(e)}function WN(e,t){return`${zg(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function qN(e,t){return`${zg(e)}/content?${new URLSearchParams({path:t})}`}async function c_(e,t){let n="";try{const r=await e.text();try{const o=JSON.parse(r),l=(o==null?void 0:o.detail)??(o==null?void 0:o.error)??(o==null?void 0:o.message);n=typeof l=="string"?l:l&&typeof l.message=="string"?l.message:r}catch{n=r}}catch{n=""}return new Error(`${t} (HTTP ${e.status}): ${n.trim()||e.statusText||"no reason given"}`)}function HN(e,t){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null,r=u=>{throw new Error(`Unexpected /workspace/files response from the gateway: ${u}.`)};if(!n)return r("not an object");Array.isArray(n.entries)||r("no `entries` list"),typeof n.truncated!="boolean"&&r("no `truncated` flag");const o=n.entries.map((u,c)=>{const f=u&&typeof u=="object"?u:{};return(typeof f.name!="string"||typeof f.path!="string"||f.type!=="file"&&f.type!=="dir")&&r(`entry ${c+1} lacks a name, path or file/dir type`),f}),l=n.hidden&&typeof n.hidden=="object"&&!Array.isArray(n.hidden)?n.hidden:void 0;return{path:typeof n.path=="string"?n.path:t,entries:o,truncated:n.truncated,...l?{hidden:l}:{}}}async function VN(e,t,n){const r=await e(UN(t),{signal:n});if(!r.ok)throw await c_(r,"The workspace is not available");const o=await r.json();if(!o||typeof o.workspace_root!="string"||typeof o.exists!="boolean")throw new Error("Unexpected /workspace response from the gateway: no `workspace_root` / `exists`.");return o}async function GN(e,t,n,r){const o=await e(WN(t,n),{signal:r});if(!o.ok)throw await c_(o,"The folder could not be listed");return HN(await o.json(),n)}async function KN(e,t,n,r){const o=await e(qN(t,n),{signal:r});if(!o.ok)throw await c_(o,"The file could not be read");return await o.blob()}async function YN(e,t,n,r){const o=await VN(e,t,r);return{where:o,listing:o.exists?await GN(e,t,n,r):null}}function JN(e){const t=String(e||"").split("/").filter(Boolean),n=[{label:"Workspace",path:""}];return t.forEach((r,o)=>n.push({label:r,path:t.slice(0,o+1).join("/")})),n}function XN(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 ZN(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function QN(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 e1=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function t1(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return e1.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 Bx(e,t,n){const r=n==="open"?t1(e.type):{mode:"download"},o=r.mode==="open"&&r.type!==e.type?new Blob([e],{type:r.type}):e,l=URL.createObjectURL(o);if(r.mode==="open")window.open(l,"_blank","noopener");else{const u=document.createElement("a");u.href=l,u.download=t,document.body.appendChild(u),u.click(),u.remove()}window.setTimeout(()=>URL.revokeObjectURL(l),6e4)}async function n1(e,t,n){const r=await e(kj(t),{signal:n.signal});if(!r.ok)throw await c_(r,`${n.name} could not be read`);Bx(await r.blob(),n.name,n.mode??"open")}function Ux(e){const{fetchGateway:t,runId:n}=e,[r,o]=m.useState({runId:n,path:""}),l=r.runId===n?r.path:"",[u,c]=m.useState(null),[f,_]=m.useState(""),[p,y]=m.useState(!!n),[w,x]=m.useState(""),[S,j]=m.useState(0);m.useEffect(()=>{if(!n)return;const T=new AbortController;return y(!0),_(""),(async()=>{try{const L=await YN(t,n,l,T.signal);T.signal.aborted||c({runId:n,...L})}catch(L){T.signal.aborted||_(String((L==null?void 0:L.message)||L))}finally{T.signal.aborted||y(!1)}})(),()=>T.abort()},[t,n,l,S,e.refreshKey]);const C=u&&u.runId===n?u:null,N=m.useCallback(async(T,L)=>{x(T.path),_("");try{Bx(await KN(t,n,T.path),T.name,L)}catch(P){_(String((P==null?void 0:P.message)||P))}finally{x("")}},[t,n]);return s.jsx(s1,{title:e.title,note:e.note,where:(C==null?void 0:C.where)??null,path:l,listing:(C==null?void 0:C.listing)??null,error:f,loading:p,fileBusy:w,selectedPath:e.selectedPath,className:e.className,onNavigate:T=>o({runId:n,path:T}),onRefresh:()=>j(T=>T+1),onFile:e.onSelectFile?void 0:(T,L)=>void N(T,L),onSelectFile:e.onSelectFile,onClose:e.onClose})}function s1(e){var r,o,l,u;const t=e.listing?QN(e.listing):"",n=(o=(r=e.where)==null?void 0:r.host)==null?void 0:o.hostname;return s.jsxs("section",{className:`pc-ws${e.className?` ${e.className}`:""}`,"aria-label":e.title,"data-workspace-root":((l=e.where)==null?void 0:l.workspace_root)||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("code",{children:e.where.workspace_root}),n&&((u=e.where.host)==null?void 0:u.caller_is_this_machine)!==!0?s.jsxs("span",{className:"pc-ws__muted",children:[" on the gateway host ",n]}):null]}):null,e.note?s.jsx("div",{className:"pc-ws__muted",children:e.note}):null,s.jsx("nav",{className:"pc-ws__crumbs","aria-label":"Folder",children:JN(e.path).map((c,f,_)=>f===_.length-1?s.jsx("span",{"aria-current":"page",children:c.label},c.path):s.jsxs(ve.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-ws__crumb",onClick:()=>e.onNavigate(c.path),children:c.label}),s.jsx("span",{className:"pc-ws__muted",children:" / "})]},c.path))}),e.error?s.jsx("div",{className:"pc-ws__error",role:"alert",children:e.error}):null,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:ZN(e.listing.entries).map(c=>s.jsx("li",{className:`pc-ws__entry${e.selectedPath===c.path?" is-selected":""}`,"data-type":c.type,"data-path":c.path,children:c.type==="dir"?s.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"open-dir",onClick:()=>e.onNavigate(c.path),children:[s.jsx(Qe,{name:"folder",size:14})," ",c.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===c.path,onClick:()=>{var f;return(f=e.onSelectFile)==null?void 0:f.call(e,c)},children:[s.jsx(Qe,{name:"file",size:14})," ",c.name]}):s.jsxs("span",{className:"pc-ws__name",children:[s.jsx(Qe,{name:"file",size:14})," ",c.name]}),s.jsx("span",{className:"pc-ws__size",children:XN(c.size_bytes)}),e.onFile?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-ws__btn","data-action":"open-file",disabled:e.fileBusy===c.path,onClick:()=>{var f;return(f=e.onFile)==null?void 0:f.call(e,c,"open")},children:"Open"}),s.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"download-file",disabled:e.fileBusy===c.path,onClick:()=>{var f;return(f=e.onFile)==null?void 0:f.call(e,c,"download")},title:`Download ${c.name}`,"aria-label":`Download ${c.name}`,children:s.jsx(Qe,{name:"download",size:14})})]}):null]})},c.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]})}function Wx(e){return s.jsx(Ax,{text:e,images:"link"})}const r1={trigger:"Trigger",answer:"Automation"};function i1(e){return s.jsx(Pg,{message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:r1[e.kind],runId:e.runId},images:"link"})}const o1={renderText:Wx,renderTurn:i1};function a1(e){const{fetchGateway:t,...n}=e,r=n.onOpenResource??(t?o=>n1(t,o.url,{name:o.name}):void 0);return s.jsx(ck,{...n,onOpenResource:r,...o1})}function l1(e,t,n={}){if(!e)return null;const r=e.wait,o=`${e.runId}:${r.wait_key}:${e.stepId||""}`,l=r.details||{};if(l.mode==="approval_required"||l.kind==="tool_approval"){const c=Array.isArray(l.tool_calls)?l.tool_calls:[],f={runId:e.runId,waitKey:String(r.wait_key||""),stepId:e.stepId},_=[...new Set(c.map(y=>String((y==null?void 0:y.name)||"tool")))],p=n.onPermissionsAll;return{id:o,kind:"tool-approval",title:`${c.length||"Requested"} ${c.length===1?"action needs":"actions need"} permission`,toolName:_.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(Rx,{tools:c.map((y,w)=>({id:String((y==null?void 0:y.call_id)||(y==null?void 0:y.id)||w),runId:e.runId,name:(y==null?void 0:y.name)||"Tool",arguments:y==null?void 0:y.arguments,status:"waiting"}))}),s.jsxs("details",{children:[s.jsx("summary",{children:"Review full tool arguments (JSON)"}),s.jsx(mr,{value:c.length?c:l})]})]}),approveLabel:"Allow once",denyLabel:"Deny",approveAllLabel:p?"Allow all enabled tools":void 0,approveAllDescription:p?"Sets permissions: all for this Gateway account, including future turns. Unchecked tools stay unavailable; explicit Ask overrides and Gateway restrictions remain enforced. Questions still need your answer.":void 0,onApproveAll:p?async()=>{await t.approveWithPolicyChange(f,()=>{p()})}:void 0,onApprove:async()=>{await t.approve(!0,f)},onDeny:async()=>{await t.approve(!1,f)}}}if(r.reason==="user"||r.reason==="ask_user")return{id:o,kind:"ask-user",title:"A question for you",prompt:String(r.prompt||l.prompt||"How would you like to continue?"),allowFreeText:r.allow_free_text!==!1,choices:(Array.isArray(r.choices)?r.choices:[]).map(c=>typeof c=="object"&&c!==null?{id:String(c.value??c.id??c.label),label:String(c.label??c.text??c.value??c.id),description:c.description}:{id:String(c),label:String(c)}),onSubmit:async c=>{await t.resume(c)}};const u=String(r.wait_key||"");if(r.reason==="event"||u.startsWith("evt:")){const c=BN(e,n.records||[],n.currentRun??null),f=c.target,_=(f==null?void 0:f.name)||"";return{id:o,kind:"event-wait",title:f?"Waiting for an event":"Event routing unavailable",eventName:_,prompt:String(r.prompt||`This workflow will continue when “${_||"its trigger"}” arrives.`),description:f?"You can also send the expected event here.":`This event cannot be sent safely. ${c.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async p=>{if(!f)throw new Error(c.error);const y=JSON.parse(p||"{}"),w={name:f.name,scope:f.scope,payload:y};f.scope==="session"?w.session_id=f.scopeId:f.scope==="workflow"?w.workflow_id=f.scopeId:f.scope==="run"&&(w.run_id=f.scopeId),await t.emitEvent(w)}}}return null}const c1='# AbstractObserver\n\n> Gateway-only observability UI (Web/PWA) for AbstractFramework runs: a browser SPA + tiny Node.js CLI that connects to an AbstractGateway HTTP API (HTTP fetch + SSE ledger streaming) and submits durable commands.\n\nThis repository is UI-only:\n- The packaged CLI (`bin/cli.js` + `bin/server.js`) serves `dist/` (SPA fallback) at `/` or through the gateway at `/apps/observer/` (app-server mount contract: identity header, `<base href>`, cookie path, forwarded client address) and proxies `api/` to the Gateway after browser-session sign-in, using `@abstractframework/app-server`.\n- The browser talks to same-origin `/api` in hosted mode; direct Gateway URLs remain available for local development via `src/lib/gateway_client.ts` (treat this file as the source of truth for HTTP endpoints and request shapes).\n- Hosted sign-in uses Gateway URL + user + token only to create an app-scoped browser session. Settings persistence strips Gateway bearer tokens. With `@abstractframework/app-server` 0.1.10 or newer the proxy sends the browser\'s connection address as `X-Forwarded-For` and `X-AbstractFramework-App-Proxy: abstractobserver` to the Gateway.\n- On non-local hosted UI hostnames, the server-configured Gateway URL is authoritative; browser-supplied Gateway URL changes are rejected unless `ABSTRACTOBSERVER_ALLOW_REMOTE_BROWSER_GATEWAY_CONFIG=1` is enabled behind access control. Forwarded host headers are trusted only when `ABSTRACTOBSERVER_TRUST_PROXY_HEADERS=1` or `ABSTRACTGATEWAY_TRUST_PROXY_HEADERS=1`.\n\n## Quickstart\n- Run packaged UI server (no build step): `npx --yes --package @abstractframework/observer -- abstractobserver`\n- Dev server (Vite; proxies `/api` in dev): `npm install && npm run dev`\n- Unit tests (Vitest): `npm test`\n- Production build (writes `dist/`): `npm run build`\n- Regenerate `llms-full.txt`: `npm run llms:full`\n\nNotes:\n- Build output lives in `dist/` and is served by `bin/cli.js` (don’t edit `dist/` manually).\n- `@abstractframework/ui-kit` and `@abstractframework/panel-chat` are npm dependencies; the monitor packages are Vite aliases to sibling `../abstractuic/*/src` (see `vite.config.ts` and `docs/development.md`).\n- Responsive layout (phones, tablets, small windows): `docs/getting-started.md` → "Responsive layout"; rules in `src/ui/responsive.css`.\n- On/off switches and opening the Observer over plain http from another computer (voice needs https): `docs/getting-started.md` → "Switches", "Open the Observer from another computer over http"; fallbacks in `src/lib/secure-context.ts`.\n- `llms.txt` format reference: https://llmstxt.org/\n\n## Documentation (start here)\n- [README](README.md): Install and quickstart\n- [Getting started](docs/getting-started.md): Run the UI and connect to a gateway; Ask about a run (whole conversation, History note when the 50k-token window drops older messages, error cards never sent back) vs the top-bar Assistant (one gateway session per conversation, New conversation, no tools)\n- [FAQ](docs/faq.md): Common questions (grounded in code), including the CLI `/api` session proxy, the About dialog, chat history windows and the tool-less Assistant\n- [Docs index](docs/README.md): What to read next\n- [Architecture](docs/architecture.md): Components, data flow, diagrams\n- [Configuration](docs/configuration.md): launch flags, serving under the gateway at /apps/observer/, UI settings, deployment patterns\n- [API](docs/api.md): Gateway endpoints used by the UI, including Runtime Activity run pages and canonical artifact envelope search/stats for Runtime Artifact Explorer\n- [Automations](docs/automations.md): Launch → Automate (what, when in UTC intervals, independent/growing context, tool approval), the Automations page (icon controls, Edit: the row\'s Edit opens the form — title, task, interval, context, tools —, 409 conflicts), runs as a conversation, answering waits by kind, the automation\'s files (browse, open, download through the gateway), Discuss as an in-page chat with a fork, automation tags on Board/Observe/System, legacy schedules and Recreate, the stub gateway\n- [Development](docs/development.md): Local dev, workspace deps, tests, build\n- [Security](docs/security.md): Trust boundaries and operational guidance\n- [Troubleshooting](docs/troubleshooting.md): Common issues and fixes (CORS, mixed content, 401 under `/api`, About shows the gateway unavailable, stale service worker, automations)\n\n## Key entrypoints (code)\n- [CLI](bin/cli.js) and [app server](bin/server.js): launch flags (`--gateway-url`, `--port`, `--host`, `--monitor-gpu`, `--entity-app-url`, `--gateway-dir`), mount-capable handler, session proxy, folder reveal (browsers on this machine only)\n- [App shell + pages](src/ui/app.tsx): settings, page routing, observe/launch flows, durable commands\n- [Gateway client](src/lib/gateway_client.ts): HTTP client + SSE ledger streaming (API source of truth)\n- [Automations rules + controller](src/ui/automations.ts): workflow choice (`@default`), create body, run tags, capability gate, legacy prefill, typed wait answers, page controller\n- [Automations page](src/ui/automations_page.tsx) and [Automate fields](src/ui/automate_form.tsx): the page, rows and the ui-kit `AutomationPanel` wiring; the When/Context/Tools fields\n- [Discussion chat](src/ui/automation_discussion.tsx): panel-chat `WorkflowChat` + `presentInteraction` over the gateway client; folders through panel-chat `WorkspaceBrowser` (`/runs/{id}/workspace*`)\n- [Automations stub gateway](scripts/automations_stub_server.mjs): dev/test stub serving the ui-kit fixtures\n- [Vite config](vite.config.ts): workspace aliases + dev session proxy and `/api` fallback proxy\n- [Package metadata](package.json): npm name/version, scripts, Node engine\n- [llms-full generator](scripts/generate-llms-full.mjs): defines which files are embedded into `llms-full.txt`\n\n## Ecosystem context\n- [AbstractFramework](https://github.com/lpalbou/AbstractFramework): ecosystem entrypoint and component map\n- [AbstractRuntime](https://github.com/lpalbou/abstractruntime): durable workflow runtime behind the gateway ledger\n- [AbstractCore](https://github.com/lpalbou/abstractcore): unified LLM + tools layer commonly used by workflows\n\n## Common tasks\n- Add/change a gateway capability: update `src/lib/gateway_client.ts` (source of truth) → update `docs/api.md` → run `npm test` + `npm run build`.\n- Change CLI behavior/config: update `bin/cli.js` / `bin/server.js` → update `docs/configuration.md` → run `npm run build`.\n- Update docs for agents: edit docs → regenerate `llms-full.txt` with `npm run llms:full`.\n\n## Optional (project meta)\n- [Changelog](CHANGELOG.md): Release notes\n- [Contributing](CONTRIBUTING.md): How to develop and submit changes\n- [Security policy](SECURITY.md): Responsible vulnerability reporting\n- [Acknowledgments](ACKNOWLEDGMENTS.md): Credits\n- [Code of conduct](CODE_OF_CONDUCT.md): Conduct expectations and reporting\n- [License](LICENSE): MIT license\n';function xs(){return n_()}function u1(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function rm(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function d1(e){const t=rm(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=rm(e.replayed_messages),r=rm(e.dropped_tokens),o=rm(e.max_tokens),l=[`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"}`+(o?` (history window: the most recent ${o.toLocaleString("en-US")} tokens of whole messages).`:".")];return e.oversize_turn_kept&&l.push("Your latest message alone is larger than the window; it was sent whole."),l.join(" ")}function qx(e){const t=d1(e.history);return t?s.jsx(Pg,{message:{role:"system",level:"info",title:"History",content:t}}):null}const f1=1500,h1=12e4;function m1(e,t){return new Promise((n,r)=>{const o=setTimeout(n,e);t.addEventListener("abort",()=>{clearTimeout(o),r(new DOMException("aborted","AbortError"))},{once:!0})})}const _1=["You are the AbstractObserver in-app assistant. Answer questions about","using and understanding the AbstractObserver web app (pages: Board,","Observe/run page with Story/Ledger/Flow/Ask tabs, System with","Activity/Artifacts/Memory/Logs, Launch, Settings). Ground every answer","in the documentation index below; when the docs don't cover something,","say so plainly instead of guessing. Be concise and concrete.","","=== DOCUMENTATION INDEX (llms.txt) ===",c1,"=== END DOCUMENTATION ==="].join(`
72
+ `),p1="observer-docs-assistant";function ew(){return`${p1}:${xs()}`}function g1(e){return{prompt:e,system:_1,tools:[],use_session_history:!0,use_context:!0}}function y1(e){var t,n;for(let r=e.length-1;r>=0;r--){const o=e[r],l=o!=null&&o.result&&typeof o.result=="object"?o.result:null,u=[(t=l==null?void 0:l.response)==null?void 0:t.content,(n=l==null?void 0:l.response)==null?void 0:n.text,l==null?void 0:l.output,l==null?void 0:l.content,l==null?void 0:l.text];for(const c of u){const f=typeof c=="string"?c.trim():"";if(f)return f}}return""}function w1(e,t,n=()=>{}){return async(r,o)=>{var f;const l=e(),u=await l.start_run(null,g1(r),{bundle_id:"basic-agent",session_id:t()}),c=Date.now();for(;;){if(await m1(f1,o.signal),Date.now()-c>h1)throw new Error("The assistant run timed out (120s). The run is still visible on the Observe page.");const _=await l.get_run(u),p=String((_==null?void 0:_.status)||"").trim().toLowerCase();if(p==="failed"||p==="cancelled"){const y=String(((f=_==null?void 0:_.error)==null?void 0:f.message)||(_==null?void 0:_.error)||"run "+p).slice(0,400);throw new Error(`The assistant run ${p}: ${y}`)}if(p==="completed"){n((_==null?void 0:_.session_history)??null);const y=await l.get_ledger(u,{after:0,limit:500,signal:o.signal});return y1(y.items)||"(the run completed but produced no readable answer — inspect it on the Observe page)"}}}}function v1(e){const t=m.useRef(e.gateway);t.current=e.gateway;const n=m.useRef(ew()),[r,o]=m.useState([]),[l,u]=m.useState(null),c=m.useMemo(()=>w1(()=>t.current,()=>n.current,u),[]),[f]=m.useState(void 0),_=()=>{n.current=ew(),o([]),u(null)};return s.jsxs(Bj,{open:e.open,onClose:e.onClose,label:"Observer assistant",title:"Assistant",width:420,topOffset:e.topOffset,headerActions:s.jsx("button",{className:"btn",type:"button",disabled:!r.length,onClick:_,title:"Start a new conversation (nothing earlier is replayed)",children:"New conversation"}),children:[s.jsx(qx,{history:l}),s.jsx(hN,{ask:c,messages:r,onMessagesChange:o,assistantName:"Observer",placeholder:"Ask about the observer…",blockedNotice:e.connected?f:"Connect to the gateway to use the assistant.",suggestions:["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?"],emptyState:s.jsx("div",{children:"Answers are grounded in this app's documentation. Each question runs once through the connected gateway's basic agent."})})]})}function x1(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 b1(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 j1(e,t,n){return e<=0?-1:t<0?n?e-1:0:(t+(n?e-1:1))%e}const S1='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function k1(e){return typeof document>"u"?!1:Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e)}function N1(e){const[t,n]=m.useReducer(x1,!1),r=m.useRef(null),o=m.useRef(null),l=m.useRef(!1);return m.useEffect(()=>{n({type:"page_change"})},[e.page]),m.useEffect(()=>{n({type:"layout_change"})},[e.is_drawer]),m.useEffect(()=>{var u;if(t){l.current=!0;const c=o.current,f=(c==null?void 0:c.querySelector(".shell_nav_item.active"))||(c==null?void 0:c.querySelector(".shell_nav_item"));f==null||f.focus();const _=p=>{if(p.key==="Escape"){n({type:"escape",default_prevented:p.defaultPrevented,other_modal_open:k1(o.current)});return}if(p.key!=="Tab"||!o.current)return;const y=Array.from(o.current.querySelectorAll(S1)).filter(x=>x.offsetParent!==null||x===document.activeElement),w=j1(y.length,y.indexOf(document.activeElement),p.shiftKey);w>=0&&(p.preventDefault(),y[w].focus())};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)}l.current&&(l.current=!1,(u=r.current)==null||u.focus())},[t]),{open:t,set_open:u=>n({type:u?"open":"close"}),toggle_ref:r,sidebar_ref:o,attrs:b1(e.is_drawer,t)}}const C1="api/local/reveal",E1="sw.js",tw="#run/";function Hx(e){const t=String(e||"");if(!t.startsWith(tw))return"";const n=t.slice(tw.length);if(!n||n.includes("/"))return"";try{return decodeURIComponent(n).trim()}catch{return""}}function $1(e){return`Run ${e} cannot be opened: it does not exist on this gateway, or your account cannot see it.`}function A1(e){const t=Hx(e.hash);if(t)return t;const n=u=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(u),r=u=>{const c=u.split("/").filter(Boolean);return c.length?c[c.length-1].trim():""},o=r(String(e.hash||"").replace(/^#/,""));if(n(o))return o;const l=r(String(e.pathname||""));return n(l)?l:""}const Dm="@default:",Fm="abstractcode.agent.v1";function T1(e){const t=String(e||"").trim();if(t.startsWith(Dm)){const r=t.slice(Dm.length).trim();return r?{kind:"default",interface:r}:null}const n=t.indexOf(":");return n<=0||n>=t.length-1?null:{kind:"bundle",bundle_id:t.slice(0,n),flow_id:t.slice(n+1)}}function M1(e){return e?e.kind==="default"?`${Dm}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function R1(e){const t={};for(const r of e)for(const o of r.agent_default_interfaces||[])o&&!t[o]&&(t[o]=r.label);return[Fm,...Object.keys(t).filter(r=>r!==Fm).sort()].map(r=>({interface:r,value:`${Dm}${r}`,label:`Gateway default agent · ${r}${t[r]?` (now: ${t[r]})`:""}`}))}function L1(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 I1(e){const t={};for(const[n,r]of Object.entries(e||{}))if(typeof r=="string"){const o=r.trim();o&&(t[n]=o)}else r!==void 0&&(t[n]=r);return t}const O1={once:"Run once: start this workflow now, a single run you can watch in Observe.",automate:"Automate: create an automation that runs this workflow on a schedule (every N minutes, hours or days), when an email arrives, or when you ask; manage it on the Automations page."};function P1(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 D1="#launch/automate";function F1(e){const t=Hx(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 eg={when:"every",email:Qv,notify_email:!1,email_recipients:Lg,amount:"24",unit:"h",once_at:"",context:"independent",tool_approval:"auto",title:"",start_at:"",count:"",until:""},nw={independent:"Each run starts fresh in its own session. Runs never see each other.",growing:"Each run is a new turn of one conversation and sees the previous runs. The history is bounded: the most recent 50,000 tokens of whole turns are replayed; older runs drop out."},Vx=["use_context"],z1="This choice also sets the workflow's Use Context input: the workflow always reads the history the automation gives it.";function tg(e,t,n=!1){const r=e.when==="every";return{prompt:t,when:e.when==="once"?{kind:"once",at:e.once_at}:{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,toolApproval:e.tool_approval,title:e.title,...r&&e.start_at?{startAt:e.start_at}:{},...r&&e.count.trim()?{count:Number(e.count)}:{},...r&&e.until?{until:e.until}:{}}}function B1(e,t){if(t.input_data===null)return{ok:!1,errors:["The inputs are not valid JSON."]};if(e.when==="email"&&!t.email_usable)return{ok:!1,errors:[Bt.not_set_up]};const n=I1(t.input_data),r=typeof n.prompt=="string"?n.prompt:"";delete n.prompt;for(const l of Vx)delete n[l];let o;try{o=L1(t.choice,t.bundle_ref_for,n)}catch(l){return{ok:!1,errors:[String((l==null?void 0:l.message)||l)]}}return Wp(tg(e,r,t.email_usable===!0),{target:o,requestId:t.request_id})}function U1(e,t=!1){if(e.when==="email"){if(!t)return"";const l=Wp(tg(e,"preview",!0),{target:{flow_id:"@default",interface:Fm},requestId:"preview"});return l.ok?`Runs ${tx(l.body.trigger.config)}.`:""}const n=Wp(tg(e,"preview"),{target:{flow_id:"@default",interface:Fm},requestId:"preview"});if(!n.ok)return"";const r=n.body.trigger.config,o=Gv(r);return e.when==="once"?`Runs ${o}.`:`Runs ${o}, first run ${r.start_at?`at ${Ca(r.start_at)}`:"now"}.`}class W1{constructor(t){Xs(this,"key","");Xs(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 q1(e,t,n){const r=B1(e,{...t,request_id:""});if(!r.ok)return r;const{request_id:o,...l}=r.body,u=n.id_for(JSON.stringify(l));return{ok:!0,body:{...r.body,request_id:u}}}function ba(e){return typeof e=="string"?e:e??null}function H1(e){var t,n,r,o,l,u;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:ba(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:ba(e==null?void 0:e.created_at),updated_at:ba(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:ba(e==null?void 0:e.parent_run_id),session_id:ba(e==null?void 0:e.session_id),actor_id:ba(e==null?void 0:e.actor_id),session_kind:ba(e==null?void 0:e.session_kind),automation_id:ba(e==null?void 0:e.automation_id),role:ba(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,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():((o=e==null?void 0:e.schedule)==null?void 0:o.interval)??null,schedule_target_workflow_id:typeof((l=e==null?void 0:e.schedule)==null?void 0:l.target_workflow_id)=="string"?String(e.schedule.target_workflow_id).trim():((u=e==null?void 0:e.schedule)==null?void 0:u.target_workflow_id)??null,current_node:typeof(e==null?void 0:e.current_node)=="string"?String(e.current_node).trim():(e==null?void 0:e.current_node)??null,llm_calls:typeof(e==null?void 0:e.llm_calls)=="number"?Number(e.llm_calls):(e==null?void 0:e.llm_calls)??null,tool_calls:typeof(e==null?void 0:e.tool_calls)=="number"?Number(e.tool_calls):(e==null?void 0:e.tool_calls)??null,tokens_total:typeof(e==null?void 0:e.tokens_total)=="number"?Number(e.tokens_total):(e==null?void 0:e.tokens_total)??null,error:(e==null?void 0:e.error)??null,waiting:(e==null?void 0:e.waiting)??null}}function Mf(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 Gx(e){const t=Mf(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`occurrence #${e.occurrence_index}`:"occurrence":t==="legacy"?"legacy schedule":t||""}function sw(e){return String((e==null?void 0:e.role)||"").trim()==="controller"}function V1(e){var n,r,o;const t=(o=(r=(n=e==null?void 0:e.capabilities)==null?void 0:n.contracts)==null?void 0:r.common)==null?void 0:o.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 Nc(e){return e.legacy===!0||e.capabilities.includes("legacy")}function Kx(e,t=Date.now()){const n=Nc(e),r=e.last_occurrence,o=r&&r.attempts>1?` after ${r.attempts} attempts`:"",l=e.attention.unread||e.attention.pending_waits>0;return{id:e.automation_id,title:e.title,cadence:Tg(e.trigger),next_run:e.next_fire_at?`${Ca(e.next_fire_at)} (${ix(e.next_fire_at,t)})`:e.status==="paused"?"none while paused":"none scheduled",current:rx(e),state:e.status,last:r?r.excerpt:"",last_status:r?`#${r.index} ${r.status}${o}`:"no runs yet",attention:l?ox(e):null,legacy:n}}function Yx(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 G1(e,t){const n=Rm(e,[],t),r=Yx(e),o=t?{enabled:!1,reason:"Working…"}:Nc(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:o}}function K1(e,t){const n=l=>({enabled:!1,reason:l});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",o=e.status==="active"||e.status==="paused";return{legacy_pause:r?n("Already suspended."):o?{enabled:!0}:n("The schedule has ended."),legacy_resume:r?{enabled:!0}:n(o?"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 Y1(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 J1=/^([1-9][0-9]*)([smhd])$/;function X1(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 Z1(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(),o=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(),l=String(n.target_flow_id||(t==null?void 0:t.flow_id)||"").trim();if(!o||!l)throw new Error("The legacy schedule does not name its target workflow.");const u=[],c={...eg},f=typeof n.interval=="string"?n.interval.trim():"";if(!f)c.when="once",u.push("The legacy schedule ran once; pick the date and time (UTC) to run.");else{const w=J1.exec(f);let x=w?Number(w[1]):0,S=w?w[2]:"";S==="s"&&x%60===0&&(x=x/60,S="m"),S==="m"||S==="h"||S==="d"?(c.amount=String(x),c.unit=S):u.push(`The legacy interval "${f}" is not a whole number of minutes, hours or days; choose an interval.`)}typeof n.repeat_count=="number"&&n.repeat_count>=1&&(c.count=String(n.repeat_count));const _=X1(n.repeat_until);_&&(c.until=_),c.context=n.share_context===!1?"independent":"growing";const p=t&&typeof t.input_data=="object"&&t.input_data&&!Array.isArray(t.input_data)?t.input_data:{},y={};for(const[w,x]of Object.entries(p))w==="workflow_selection"||w.startsWith("_")||(y[w]=x);return{choice:{kind:"bundle",bundle_id:o,flow_id:l},input_data:y,form:c,notes:u}}const Q1={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};function e2(e,t,n){return{answer_wait:async(r,o,l)=>{await e.submit_command({command_id:t(),run_id:r,type:"resume",payload:{wait_key:o,payload:l},client_id:"web_pwa"})},legacy_command:async(r,o,l)=>{await e.submit_command({command_id:t(),run_id:r,type:o,payload:l,client_id:"web_pwa"})},now_iso:n}}function t2(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 rp(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function rw(e){return e.items.filter(t=>t.status==="archived").length}function Bg(e,t){return`Discussion started from #${e} (session ${t.session_id}). It works in its own workspace ${t.workspace_root}; the automation's files are mounted read-only at ${t.mounted_workspace} for the file tools (shell commands are not sandboxed), and nothing is written back into the automation's session.`}const n2=3e4,im=50;function to(e){return Ig(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function ip(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,o)=>o.index-r.index)}class s2{constructor(t,n,r=[1500,4e3]){Xs(this,"state",{...Q1});Xs(this,"listeners",new Set);Xs(this,"list_seq",0);Xs(this,"detail_seq",0);Xs(this,"sources_loaded",!1);this.client=t,this.host=n,this.followups_ms=r}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 o=await this.client.listAutomations({...this.state.status_filter?{status:this.state.status_filter}:{},...n?{cursor:n}:{},limit:im});if(t.push(...o.items),!o.next_cursor)return t;n=o.next_cursor}throw new Error("GET /api/gateway/automations kept returning next_cursor after 200 pages.")}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 r_(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(),t!==this.list_seq)return;const r=this.state.detail,o=r?n.find(l=>l.automation_id===r.automation_id):void 0;this.set({items:n,loaded:!0,loading:!1,list_error:null,refreshed_at:Date.now(),...r&&o?{detail:{...r,summary:o}}:{}}),r&&await this.reload_occurrences(r.automation_id)}catch(n){if(t!==this.list_seq)return;this.set({loading:!1,loaded:!0,list_error:to(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 o;const n=String(t||"").trim(),r=++this.detail_seq;if(!n){this.set({selected_id:"",detail:null});return}this.set({selected_id:n,notice:"",...((o=this.state.detail)==null?void 0:o.automation_id)!==n?{detail:null}:{}});try{const l=this.state.items.find(f=>f.automation_id===n);if(l&&Nc(l)){this.set({detail:{automation_id:n,summary:l,definition:null,occurrences:[],next_cursor:null,error:null}});return}const[u,c]=await Promise.all([this.client.getAutomation(n),this.client.listOccurrences(n,{limit:im})]);if(r!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:l??u.summary,definition:u.definition,occurrences:ip([],c.items),next_cursor:c.next_cursor,error:null}}),await this.load_trigger_sources()}catch(l){if(r!==this.detail_seq)return;this.set({error:to(l)})}}async reload_occurrences(t){const n=this.state.detail;if(!n||n.automation_id!==t||Nc(n.summary))return;const[r,o]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:im})]),l=this.state.detail;if(!l||l.automation_id!==t)return;const u=this.state.items.find(c=>c.automation_id===t);this.set({detail:{...l,summary:u??r.summary,definition:r.definition,occurrences:ip(l.occurrences,o.items),next_cursor:l.occurrences.length>o.items.length?l.next_cursor:o.next_cursor}})}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:im}),r=this.state.detail;if(!r||r.automation_id!==t.automation_id)return;this.set({detail:{...r,occurrences:ip(r.occurrences,n.items),next_cursor:n.next_cursor}})}catch(n){this.set({error:to(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,o){this.set({busy:!0});try{const l=await this.client.sendAutomationCommand(t,{type:n,...r?{payload:r}:{},...o?{command_id:o}:{}});return await this.after_change(t),l}catch(l){throw to(l)}finally{this.set({busy:!1})}}async revise(t,n,r,o){this.set({busy:!0});try{const l=await this.client.reviseAutomation(t,{changes:n,...r!==null?{expected_revision:r}:{},...o?{command_id:o}:{}});return await this.after_change(t),l}catch(l){throw to(l)}finally{this.set({busy:!1})}}async discuss(t,n,r,o){this.set({busy:!0});try{const l=await this.client.discuss(t,{occurrence_index:n,prompt:r,...o?{request_id:o}:{}});return this.set({notice:Bg(n,l)}),l}catch(l){throw to(l)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(r){throw to(r)}}async answer_wait(t,n,r,o){var l;this.set({busy:!0});try{const u=(((l=this.state.detail)==null?void 0:l.occurrences)||[]).flatMap(c=>c.waits).find(c=>c.run_id===n&&c.wait_key===r);if(!u)throw new Error(`No loaded wait ${r} on run ${n}; reload the automation.`);await this.host.answer_wait(n,r,t2(u.kind,o)),await this.after_change(t)}catch(u){throw to(u)}finally{this.set({busy:!1})}}async row_action(t,n){const r=`automation.${n}`;this.set({error:null,notice:""});try{await this.command(t.automation_id,r),this.set({notice:n==="run_now"&&t.status==="paused"?`Run now sent to “${t.title}”; it stays paused.`:n==="pause"||n==="resume"?iw(t.title,n==="resume"):`${r2[n]} sent to “${t.title}”.`,confirm_archive_id:""})}catch(o){this.set({error:to(o)})}}set_show_archived(t){this.set({show_archived:t})}ask_archive(t){this.set({confirm_archive_id:t})}async legacy_action(t,n){if(!Nc(t))throw new Error("legacy_action on a non-legacy automation");const r=Y1(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}”.`:iw(t.title,n==="legacy_resume")}),await this.refresh()}catch(o){this.set({error:to(o)})}finally{this.set({busy:!1})}}report_error(t){this.set({error:to(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 iw(e,t){return t?`“${e}” is active: it runs on its schedule.`:`“${e}” is paused: scheduled runs are skipped.`}const r2={run_now:"Run now",archive:"Archive"};function i2(e){const t=(n,r,o)=>s.jsx("button",{type:"button",role:"radio","aria-checked":e.mode===n,className:`seg_btn ${e.mode===n?"active":""}`,"data-mode":n,title:o,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:O1[e.mode]})]})}function o2(e){const t=e.form,n=r_(e.email_status),r=t.when==="email"&&!n?"every":t.when,o=U1(t,n);return s.jsxs("div",{className:"automate_fields",children:[s.jsxs("fieldset",{"data-section":"when",children:[s.jsx("legend",{children:"When (UTC)"}),s.jsxs("div",{className:"automate_row",role:"radiogroup","aria-label":"Schedule kind",children:[s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:"every",checked:r==="every",disabled:e.disabled,onChange:()=>e.on_change({when:"every"})})," Repeat"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:"once",checked:r==="once",disabled:e.disabled,onChange:()=>e.on_change({when:"once"})})," Once at…"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:"email",checked:r==="email",disabled:e.disabled||!n,onChange:()=>e.on_change({when:"email"})})," ",Bt.trigger_label]})]}),n?null:s.jsx(qp,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),r==="email"?s.jsx(VS,{value:t.email,onChange:l=>e.on_change({email:l}),disabled:e.disabled,idBase:"automate"}):r==="every"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"automate_row",role:"group","aria-label":"Presets",children:OS.map(l=>l.when.kind==="every"?s.jsx("button",{type:"button",className:"btn btn_sm","data-preset":l.label,"aria-pressed":Number(t.amount)===l.when.amount&&t.unit===l.when.unit,disabled:e.disabled,onClick:()=>{l.when.kind==="every"&&e.on_change({amount:String(l.when.amount),unit:l.when.unit})},children:l.label},l.label):null)}),s.jsxs("div",{className:"automate_row",children:[s.jsx("span",{children:"Every"}),s.jsx("input",{type:"number",min:1,step:1,value:t.amount,disabled:e.disabled,"aria-label":"Interval amount",onChange:l=>e.on_change({amount:l.target.value})}),s.jsxs("select",{value:t.unit,disabled:e.disabled,"aria-label":"Interval unit",onChange:l=>e.on_change({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.jsxs("label",{className:"automate_row",children:[s.jsx("span",{children:"Run once at (UTC)"}),s.jsx("input",{type:"datetime-local",value:t.once_at,disabled:e.disabled,onChange:l=>e.on_change({once_at:l.target.value})})]}),s.jsx("div",{className:"automate_preview","aria-live":"polite","data-preview":"true",children:o||(r==="email"?"Incomplete email trigger.":"Incomplete schedule.")})]}),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) — ",nw.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"})," — ",nw.growing]}),s.jsx("p",{className:"help_text muted","data-context-owns":"use_context",children:z1})]}),s.jsxs("fieldset",{"data-section":"tools",children:[s.jsx("legend",{children:"Tools"}),r==="email"?s.jsx("p",{className:"help_text muted","data-email-rule":"untrusted",children:Bt.untrusted_hint}):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"})})," ",FS,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"]})]}),s.jsxs("fieldset",{"data-section":"email",children:[s.jsx("legend",{children:"Email"}),n?null:s.jsx(qp,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),s.jsx(GS,{notifyEmail:n&&t.notify_email,onNotifyEmailChange:l=>e.on_change({notify_email:l}),recipients:n?t.email_recipients:Lg,onRecipientsChange:l=>e.on_change({email_recipients:l}),disabled:e.disabled||!n,idBase:"automate"})]})]})}function a2(e){const t=e.form;return s.jsxs("div",{className:"automate_fields launch_grid","data-section":"advanced-schedule",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 prompt's first line",onChange:n=>e.on_change({title:n.target.value})})]}),t.when==="every"?s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"launch_grid_cell",children:[s.jsx("span",{className:"launch_label",children:"First run at (UTC; empty = now)"}),s.jsx("input",{type:"datetime-local",value:t.start_at,disabled:e.disabled,onChange:n=>e.on_change({start_at:n.target.value})})]}),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 at (UTC)"}),s.jsx("input",{type:"datetime-local",value:t.until,disabled:e.disabled,onChange:n=>e.on_change({until:n.target.value})})]})]}):null]})}const l2="abstractobserver";function c2(e){return{getRun:t=>e.get_run(t),getHistory:t=>e.get_run_history_bundle(t,{include_subruns:!0,include_session:!0,ledger_mode:"full"}),getLedger:(t,n,r)=>e.get_ledger(t,{after:n,limit:200,signal:r}),streamLedger:(t,n,r,o,l)=>e.stream_ledger(t,{after:n,on_step:r,signal:o,on_open:l}),submitCommand:t=>e.submit_command(t)}}function u2(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 d2=new Set(["completed","failed","cancelled"]);function f2(e){var L;const{gateway:t,discussion:n}=e,r=m.useMemo(()=>c2(t),[t]),[o,l]=m.useState(((L=n.session)==null?void 0:L.run_id)||""),[u,c]=m.useState(""),[f,_]=m.useState(!1),[p,y]=m.useState(""),{controller:w,snapshot:x}=DN({transport:r,runId:o,enabled:e.connected,clientId:l2}),S=n.session,j=!!o&&!d2.has(x.status)&&x.status!=="idle",C=LN(x),N=async P=>{var G;const W=P.trim();if(W){_(!0);try{if(S){const Y=String(((G=x.run)==null?void 0:G.workflow_id)||""),J=u2(Y),re=await t.start_run(J.flow_id,{prompt:W},{bundle_id:J.bundle_id,session_id:S.session_id});l(re)}else{const Y=await e.on_fork(n.automation_id,n.occurrence_index,W);l(Y.run_id)}c("")}finally{_(!1)}}},T=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"}),S?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`btn btn_sm${p==="own"?" active":""}`,"data-action":"discussion-files",onClick:()=>y(p==="own"?"":"own"),title:S.workspace_root,children:[s.jsx(Qe,{name:"folder",size:14})," Its files"]}),s.jsxs("button",{type:"button",className:`btn btn_sm${p==="mounted"?" active":""}`,"data-action":"automation-files",onClick:()=>y(p==="mounted"?"":"mounted"),title:S.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":(S==null?void 0:S.session_id)||void 0,children:[p&&S?s.jsx(Ux,{fetchGateway:t.fetch_gateway,runId:p==="own"?S.run_id:n.automation_id,title:p==="own"?"Discussion files":"Automation files",note:p==="own"?"The discussion's own writable folder.":"Mounted read-only for the discussion's file tools; nothing is written back.",onClose:()=>y(""),refreshKey:x.status}):null,s.jsx(CN,{header:T,messages:x.messages,draft:u,onDraftChange:c,onSend:N,busy:j||f,busyLabel:f?S?"Starting…":"Forking the automation…":C?"Waiting for you":"Working…",onCancel:j?()=>w.cancel():void 0,stopState:x.stop??null,disabled:!e.connected,interaction:l1(C,w,{records:x.records,currentRun:x.run}),placeholder:S?"Ask a follow-up…":`Ask about run #${n.occurrence_index}…`,emptyState:s.jsxs("div",{className:"help_text muted discussion_intro",children:["A new session that forks this automation at #",n.occurrence_index," with its history (runs 1–",n.occurrence_index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation."]}),footer:x.error?s.jsx("div",{className:"observe_context_card error",role:"alert",children:x.error}):null})]})}function Jx(e){return`abstractobserver_list_open_${e}`}function Xx(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function h2(e,t=Xx()){try{return(t==null?void 0:t.getItem(Jx(e)))!=="0"}catch{return!0}}function m2(e,t,n=Xx()){try{n==null||n.setItem(Jx(e),t?"1":"0")}catch{}}function Rf(e){const[t,n]=m.useState(()=>h2(e)),r=m.useCallback(()=>{n(o=>{const l=!o;return m2(e,l),l})},[e]);return[t,r]}function Lf(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 _2=5e3,p2=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],g2={pause:Oo.pause,resume:Oo.resume,run_now:Oo.run_now,edit:Oo.revise,archive:`${Oo.archive}…`,discuss:Oo.discuss},y2={pause:ro.pause,resume:ro.resume,run_now:ro.run_now,edit:ro.revise,archive:ro.archive,discuss:ro.discuss},w2={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},v2={legacy_pause:ro.pause,legacy_resume:ro.resume,legacy_run_now:ro.run_now,open_run:"list",recreate:"refresh"};function x2(e){return s.jsx("span",{className:"auto_state","data-field":"state",children:s.jsx(cx,{status:e.status})})}function om(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 b2={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"},j2="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function ow(e){const t=e.busy||e.ctl.enabled?null:e.ctl.reason||"Not available now.";return s.jsx(Ta,{variant:"sm",className:"auto_switch",action:"active",id:`auto-active-${e.summary.automation_id}`,label:Oo.active,checked:e.summary.status==="active",unavailableReason:t,busy:e.busy,hint:e.hint,onChange:e.onChange})}function S2(e){const t=e.summary,n=Kx(t),r=e.state.selected_id===t.automation_id,o=e.state.busy,l=(f,_,p,y,w,x,S,j)=>s.jsxs("button",{type:"button",className:`btn btn_sm auto_action${S?" auto_action_icon":""}${w?` ${w}`:""}`,"data-action":f,disabled:!p.enabled,title:[S?_:null,p.enabled?null:p.reason,j].filter(Boolean).join(`
73
+ `)||void 0,"aria-label":S?_:void 0,"aria-description":j,onClick:y,children:[x?s.jsx(Qe,{name:x,size:13}):null,S?null:s.jsx("span",{children:_})]},f);let u;if(n.legacy){const f=K1(t,o),_=t.status==="paused"?"legacy_resume":"legacy_pause",p=["legacy_run_now","open_run","recreate"];u=[s.jsx(ow,{summary:t,busy:o,ctl:f[_],hint:j2,onChange:()=>e.h.on_legacy_action(t,_)},"active"),...p.map(y=>l(y,b2[y],f[y],()=>e.h.on_legacy_action(t,y),void 0,v2[y]))]}else{const f=G1(t,o),_=t.status==="active"?"pause":"resume",p=["run_now","edit","discuss","archive"];u=[s.jsx(ow,{summary:t,busy:o,ctl:f.active,hint:Im("active",t),onChange:()=>e.h.on_row_action(t,_)},"active"),...p.map(y=>l(y,g2[y],f[y],()=>e.h.on_row_action(t,y),y==="archive"?"danger auto_action_end":void 0,y2[y],y==="archive",Im(w2[y],t)))]}const c=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(x2,{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(om,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?s.jsx(om,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,s.jsxs(om,{icon:"clock",field:"next",label:"Next run",children:["next: ",n.next_run]}),s.jsx(om,{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:Wx(n.last)}):null]}),s.jsx("div",{className:"auto_row_actions",role:"toolbar","aria-label":`Controls for ${n.title}`,children:u}),c?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:o,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 k2(e){const t=e.state,n=e.list?e.list.open:!0,r=t.error??t.list_error,o=r?Lm(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(Lf,{open:n,on_toggle:e.list.on_toggle,controls:"auto_list_body",title:"Automations",count:rp(t).length}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_title",children:"Automations"}),s.jsx("span",{className:"pane_count",children:rp(t).length})]}),s.jsx("span",{className:"pane_spacer"}),s.jsx("select",{className:"seg_select",value:t.status_filter,onChange:l=>e.h.on_status_filter(l.target.value),"aria-label":"Filter by status",children:p2.map(([l,u])=>s.jsx("option",{value:l,children:u},l||"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:D1,"aria-disabled":!e.available.available,title:"New automation: opens Launch in Automate mode","aria-label":"New automation",onClick:l=>{l.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}),o?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:o.title})," ",s.jsx("span",{children:o.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.items.length?s.jsx("div",{className:"help_text muted",children:"No automations yet. Create one from Launch → Automate."}):null,rw(t)>0&&t.status_filter!=="archived"?s.jsx("div",{className:"auto_show_archived",children:s.jsx(Ta,{variant:"sm",action:"show-archived",label:`Archived (${rw(t)})`,hint:"List archived automations too. Their history stays readable; they do not run.",checked:t.show_archived,onChange:l=>e.h.on_show_archived(l)})}):null,s.jsx("ul",{className:"auto_rows",children:rp(t).map(l=>s.jsx(S2,{summary:l,state:t,h:e.h},l.automation_id))})]})]})}function N2(e,t,n){const r=e.state,o=r.detail;if(!o||Nc(o.summary))return null;const l=o.automation_id;return{summary:o.summary,...o.definition?{definition:o.definition}:{},occurrences:o.occurrences,triggerSources:r.trigger_sources,busy:r.busy,...o.error?{error:o.error}:{},onRevise:(u,c,f)=>e.revise(l,u,c,f==null?void 0:f.command_id),onCommand:(u,c,f)=>e.command(l,u,c,f==null?void 0:f.command_id),onDiscuss:async(u,c,f)=>{const _=await e.discuss(l,u,c,f==null?void 0:f.request_id);return t.on_open_session(_,Bg(u,_),u),_},onSeen:u=>e.seen(l,u),onLoadMore:()=>void e.load_more(),onOpenRun:u=>t.on_open_run(u),...t.on_open_workspace?{onOpenWorkspace:t.on_open_workspace}:{},...t.fetch_gateway?{fetchGateway:t.fetch_gateway}:{},onAnswerWait:(u,c,f)=>e.answer_wait(l,u,c,f),...n?{editOpen:n.open,onEditOpenChange:n.on_change}:{},emailStatus:r.email_status,...t.on_open_my_email?{onOpenMyEmail:()=>{var u;return(u=t.on_open_my_email)==null?void 0:u.call(t)}}:{}}}function C2(e){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("div",{className:"help_text muted",children:"Loading…"})});if(!t)return s.jsx("section",{className:"pane auto_detail auto_detail_empty",children:s.jsxs("div",{className:"help_text muted",children:["Select an automation to read its runs as a conversation, change it, or discuss a result (",Hp.toLowerCase(),")."]})});if(Nc(t.summary)){const r=Kx(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:r.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 (",r.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=N2(e.ctl,e.host,e.edit);return s.jsxs("section",{className:"pane auto_detail",children:[e.browser??null,n?s.jsx(a1,{...n}):null]})}function E2(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=Yx(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function $2(e){const t=e.ctl,[n,r]=Rf("automations"),[o,l]=m.useState(null),u=N=>l(T=>({...N,opened:((T==null?void 0:T.opened)||0)+1})),[c,f]=m.useState(""),[_,p]=m.useState("");m.useSyncExternalStore(N=>t.subscribe(N),()=>t.state,()=>t.state);const[y,w]=m.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");m.useEffect(()=>{const N=()=>w(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",N),()=>document.removeEventListener("visibilitychange",N)},[]),m.useEffect(()=>{if(!e.active||!y||!e.available.available)return;t.refresh();const N=window.setInterval(()=>void t.refresh(),n2);return()=>window.clearInterval(N)},[t,e.active,y,e.available.available]);const x=t.state.detail,S=t.state.notice;m.useEffect(()=>{if(!S)return;const N=window.setTimeout(()=>t.dismiss_notice(),_2);return()=>window.clearTimeout(N)},[t,S]);const j={...e.host,on_open_workspace:N=>f(T=>T===N?"":N),fetch_gateway:e.gateway.fetch_gateway,on_open_session:(N,T,L)=>{e.host.on_open_session(N,T,L),x&&u({automation_id:x.automation_id,automation_title:x.summary.title,occurrence_index:L,session:N})}},C={...e.h,on_select:N=>{l(null),f(""),N!==_&&p(""),e.h.on_select(N)},on_dismiss_notice:()=>t.dismiss_notice(),on_dismiss_error:()=>t.dismiss_error(),on_row_action:(N,T)=>{const L=E2(N,T);L.kind==="forward"?e.h.on_row_action(N,T):L.kind==="edit"?(l(null),f(""),p(N.automation_id),e.h.on_select(N.automation_id)):L.kind==="discuss"&&(e.h.on_select(N.automation_id),u({automation_id:N.automation_id,automation_title:N.title,occurrence_index:L.index}))}};return s.jsxs("div",{className:`page auto_page${n?"":" list_collapsed"}`,children:[s.jsx(k2,{state:t.state,available:e.available,h:C,list:{open:n,on_toggle:r}}),o?s.jsx(f2,{gateway:e.gateway,discussion:o,connected:e.active,on_fork:async(N,T,L)=>{const P=await t.discuss(N,T,L);return e.host.on_open_session(P,Bg(T,P),T),l(W=>W&&{...W,session:P}),P},on_close:()=>l(null)},o.opened):s.jsx(C2,{ctl:t,host:j,h:C,edit:{open:!!x&&_===x.automation_id,on_change:N=>p(N&&x?x.automation_id:"")},browser:c?s.jsx(Ux,{fetchGateway:e.gateway.fetch_gateway,runId:c,title:c===(x==null?void 0:x.automation_id)?"Automation files":"Run files",onClose:()=>f("")}):void 0})]})}function A2(e){return s.jsx(Ta,{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 T2(e){return s.jsx("div",{className:`settings_choice ${e.checked?"on":""}`,children:s.jsx(Ta,{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 M2="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function R2(e){return s.jsx(Ta,{variant:"sm",action:"schedule-active",className:"observe_schedule_switch",label:"Active",hint:M2,checked:e.active,unavailableReason:e.unavailableReason,busy:e.busy,onChange:e.onChange})}function L2(e){return s.jsx(Ta,{variant:"sm",action:"mindmap-live",label:"Live",hint:"Refresh the map as new memory arrives.",checked:e.checked,onChange:e.onChange})}function I2(e){return s.jsx(Ta,{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})}function O2(){const e="0.5.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 P2(){return Vj("abstractobserver",O2())}async function D2(e){let t;try{t=await e.gateway_about()}catch(n){return Ey(null,n instanceof Error?n.message||n.name:String(n))}return Ey(t)}class zm{constructor(t){this._maxSize=zm._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=zm._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 F2(e){try{return new URL(String(e)),!0}catch{return!1}}function z2({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return F2(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function B2({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function U2({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function W2(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(l=>Number(l&&l.utilization_gpu_pct)).filter(l=>Number.isFinite(l));return r.length?r.reduce((l,u)=>l+u,0)/r.length:null}return null}async function q2({baseUrl:e,endpoint:t,token:n,getToken:r,signal:o,fetchImpl:l}={}){const u=z2({baseUrl:e,endpoint:t}),c=await B2({token:n,getToken:r}),f=l||globalThis.fetch;if(typeof f!="function")return{ok:!1,status:0,error:"fetch_unavailable",payload:null};let _;try{_=await f(u,{method:"GET",headers:{Accept:"application/json",...U2({token:c})},signal:o})}catch(y){return{ok:!1,status:0,error:"network_error",detail:y instanceof Error?y.message:String(y),payload:null}}let p=null;try{p=await _.json()}catch{p=null}return{ok:_.ok,status:_.status,error:_.ok?null:"http_error",payload:p}}const _f=Object.freeze({tickMs:1500,historySize:20,endpoint:"api/gateway/host/metrics/gpu",baseUrl:"",mode:"full"});function H2(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function aw(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function lw(e,t){const n=Number(e);return Number.isFinite(n)?Math.floor(n):t}function op(e,t=1){const n=aw(Number(e)/100,0,1),r=Math.round(140-140*n),o=aw(Number(t),0,1);return o>=1?`hsl(${r} 85% 55%)`:`hsl(${r} 85% 55% / ${o})`}function cw(e){const t={..._f,...e||{}};return t.tickMs=Math.max(250,lw(t.tickMs,_f.tickMs)),t.historySize=Math.max(1,Math.min(200,lw(t.historySize,_f.historySize))),t.endpoint=String(t.endpoint||_f.endpoint),t.baseUrl=String(t.baseUrl||""),t.mode=String(t.mode||_f.mode).trim().toLowerCase(),t.mode!=="icon"&&(t.mode="full"),t}function V2(){return`
74
+ :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}
75
+ .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)}
76
+ .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))}
77
+ .wrap.icon .top{display:none}
78
+ .wrap.icon .bars{height:var(--monitor-gpu-bars-height,18px)}
79
+ .top{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
80
+ .label{font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.9}
81
+ .value{font-variant-numeric:tabular-nums;font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.95}
82
+ .bars{display:flex;align-items:flex-end;gap:2px;height:var(--monitor-gpu-bars-height,34px);overflow:hidden}
83
+ .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}
84
+ .bar.missing{background:var(--monitor-gpu-bar-missing,#62708a);opacity:.35}
85
+ .bar.error{background:var(--monitor-gpu-bar-error,#ff6b6b);opacity:.7}
86
+ .muted{opacity:.6}
87
+ `}class G2{constructor(t,n={}){if(!t||typeof t!="object")throw new TypeError("target element is required");this._target=t,this._opts=cw(n),this._buffer=new zm(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=V2();const r=document.createElement("div");r.className=this._opts.mode==="icon"?"wrap icon":"wrap";const o=document.createElement("div");o.className="top";const l=document.createElement("div");l.className="label",l.textContent="GPU";const u=document.createElement("div");u.className="value muted",u.textContent="—",o.appendChild(l),o.appendChild(u);const c=document.createElement("div");c.className="bars",r.appendChild(o),r.appendChild(c),t.appendChild(n),t.appendChild(r),this._els={wrap:r,value:u,bars:c},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=cw({...this._opts,...t||{}}),r=n.historySize!==this._opts.historySize,o=n.tickMs!==this._opts.tickMs,l=n.mode!==this._opts.mode;this._opts=n,l&&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()),o&&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:o}=this._els,l=this._buffer.values(),u=this._buffer.last(),c=Number.isFinite(u)?Math.max(0,Math.min(100,u)):null;c==null?(r.textContent=t?"N/A":"—",r.classList.add("muted")):(r.textContent=`${c.toFixed(0)}%`,r.classList.remove("muted")),n&&(n.title=c==null?"GPU —":`GPU ${c.toFixed(0)}%`,c==null?(n.style.removeProperty("--monitor-gpu-accent"),n.style.removeProperty("--monitor-gpu-accent-glow")):(n.style.setProperty("--monitor-gpu-accent",op(c,.95)),n.style.setProperty("--monitor-gpu-accent-glow",op(c,.35))));const f=Array.from(o.children),_=Math.max(0,f.length-l.length),p=Math.max(2,o&&typeof o.clientHeight=="number"&&o.clientHeight>0?o.clientHeight:34);for(let y=0;y<f.length;y+=1){const w=f[y],x=y-_,S=x>=0?l[x]:null,j=Number.isFinite(S)?S:null,C=j==null?0:H2(j/100),N=Math.max(2,Math.min(p,Math.round(C*p)));w.style.height=`${N}px`,w.style.background=j==null?"":op(j),w.className="bar",j==null&&w.classList.add("missing"),t&&w.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 o=await q2({baseUrl:this._opts.baseUrl,endpoint:this._opts.endpoint,token:t,getToken:n,signal:this._abort.signal}),l=o&&o.payload,u=l&&typeof l=="object"?l.supported!==!1:!0,c=W2(l);if(!o.ok){if(this._buffer.push(null),this._render({error:!0}),o.status===401||o.status===403){const f=String(this._token||"").trim(),_=typeof this._getToken=="function";if(!r&&(!!f||_))return;this._stoppedForAuth=!0,this.stop()}else o.status===429&&(this.stop(),this._resumeTimer=setTimeout(()=>{this._resumeTimer=null,this._mounted&&this.start()},3e4));return}if(!u||c==null){this._buffer.push(null),this._render();return}this._buffer.push(c),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 K2(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 o=this._shadow||this;this._controller=new G2(o,{}),this._upgradeProperty("token"),this._upgradeProperty("getToken"),this._upgradeProperty("mode")}_upgradeProperty(o){if(!Object.prototype.hasOwnProperty.call(this,o))return;const l=this[o];try{delete this[o]}catch{}this[o]=l}connectedCallback(){this._controller.setOptions(this._readAttrs());const o=()=>{this.isConnected&&this._controller.start()};typeof queueMicrotask=="function"?queueMicrotask(o):Promise.resolve().then(o)}disconnectedCallback(){this._controller.destroy()}attributeChangedCallback(){this._controller.setOptions(this._readAttrs())}_readAttrs(){const o=this.getAttribute("tick-ms"),l=this.getAttribute("history-size"),u=this.getAttribute("endpoint"),c=this.getAttribute("base-url"),f=this.getAttribute("mode");return{...o!=null?{tickMs:o}:{},...l!=null?{historySize:l}:{},...u!=null?{endpoint:u}:{},...c!=null?{baseUrl:c}:{},...f!=null?{mode:f}:{}}}set token(o){this._controller.token=o}get token(){return this._controller.token}set getToken(o){this._controller.getToken=o}get getToken(){return this._controller.getToken}set tickMs(o){this._controller.setOptions({tickMs:o})}get tickMs(){return this._controller.options.tickMs}set historySize(o){this._controller.setOptions({historySize:o})}get historySize(){return this._controller.options.historySize}set endpoint(o){this._controller.setOptions({endpoint:o})}get endpoint(){return this._controller.options.endpoint}set baseUrl(o){this._controller.setOptions({baseUrl:o})}get baseUrl(){return this._controller.options.baseUrl}set mode(o){this._controller.setOptions({mode:o})}get mode(){return this._controller.options.mode}}globalThis.customElements.define(e,n)}function kt(){return new Date().toISOString()}function Y2(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Os(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 _t(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,l=String(e||"").replace(/\r\n/g,`
88
+ `).replace(/\r/g,`
89
+ `).split(`
90
+ `),u=l.slice(0,Math.max(1,r)).join(`
91
+ `),c=l.length>r,f=u.length>n?`${u.slice(0,Math.max(0,n-1))}…`:u;return c&&f===u?`${u}…`:f}function Lt(e,t){const n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function ap(e){const t=String(e||"").trim();return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function Nn(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 J2(e){const t=Date.now()-e,n=Math.floor(t/1e3),r=Math.floor(n/60),o=Math.floor(r/60),l=Math.floor(o/24);return n<60?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<=3?`${l}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function ka(e){const t=Nn(e);return t===null?"—":J2(t)}function uw(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),o=Math.floor(r/24),l=t%60,u=n%60,c=r%24;return o>0?`${o}d ${c}h`:r>0?`${r}h ${u}m`:n>0?`${n}m ${l}s`:`${t}s`}function Ug(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),o=r%60,l=Math.floor(r/60),u=l%24,c=Math.floor(l/24);return c>0?`${c}d ${u}h`:l>0?`${l}h ${o}m`:r>0?`${r}m ${n}s`:`${Math.max(0,t)}s`}function Ea(e){const t=Nn(e);return t===null?"—":new Date(t).toLocaleString()}function dn(...e){for(const t of e){const n=String(t??"").trim();if(n)return n}return""}function X2(...e){for(const t of e){const n=Number(t);if(Number.isFinite(n))return n}return null}function Ri(e){const t=String(e||"").trim().toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}function Xu(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function vc(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function Zx(e){const t=String((e==null?void 0:e.status)||"").trim();return Ri(t)?String((e==null?void 0:e.finished_at)||(e==null?void 0:e.updated_at)||"").trim():""}function Wg(e,t=Date.now()){const n=Nn(vc(e));if(n===null)return-1;const r=Nn(Zx(e));return Math.max(0,(r!==null?r:t)-n)}function Ac(e,t=Date.now()){return Ug(Wg(e,t))}function Z2(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 Zu(e){return String(e||"").trim().toLowerCase()}function u_(e){return`${(e==null?void 0:e.filename)||""} ${(e==null?void 0:e.source_path)||""}`.trim().toLowerCase()}function Af(e,t){return t.some(n=>e.endsWith(n))}function Q2(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 eC(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 tC(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 Qx(e,t){var u,c,f,_,p;const n=Zu(e==null?void 0:e.content_type),r=u_(e),o=[e==null?void 0:e.semantic_kind,e==null?void 0:e.render_kind,e==null?void 0:e.task,(u=e==null?void 0:e.tags)==null?void 0:u.semantic_kind,(c=e==null?void 0:e.tags)==null?void 0:c.render_kind,(f=e==null?void 0:e.tags)==null?void 0:f.task,(_=e==null?void 0:e.tags)==null?void 0:_.kind,(p=e==null?void 0:e.tags)==null?void 0:p.type].map(y=>String(y||"").trim().toLowerCase()).filter(Boolean).join(" ");if(/(^|[^a-z0-9])(code|source_code|script|program|executable)([^a-z0-9]|$)/i.test(o)||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")||Af(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 l=String(t||"").replace(/\r\n/g,`
92
+ `).replace(/\r/g,`
93
+ `).split(`
94
+ `);return eb(l)}function nC(e){const n=String(e||"").replace(/\r\n/g,`
95
+ `).replace(/\r/g,`
96
+ `).split(`
97
+ `),r=n.findIndex(u=>/^Markdown Content:\s*$/i.test(u.trim()));if(r===-1)return null;const o=[];for(const u of n.slice(0,r)){const c=u.match(/^\s*([A-Za-z][A-Za-z0-9 /_-]{1,40}):\s*(.+?)\s*$/);c&&o.push({label:c[1].trim(),value:c[2].trim()})}const l=n.slice(r+1).join(`
98
+ `).trim();return!o.length&&!l?null:{metadata:o,body:l}}function sC(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(o=>o.split(n).length);if(r[0]>=3&&r.every(o=>Math.abs(o-r[0])<=1))return!0}return!1}function rC(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:eb(e)}function eb(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 iC(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 o=t.replace(/\r\n/g,`
99
+ `).replace(/\r/g,`
100
+ `).split(`
101
+ `).map(f=>f.trim()).filter(Boolean).slice(0,80);if(o.length<12)return!1;const l=o.filter(f=>f.length<=28).length,u=o.filter(f=>/^[,.;:()†]+$/.test(f)).length;return o.filter(f=>/^(abstract\.?|introduction|references|appendix|figure\s+\d+|table\s+\d+)\b/i.test(f)).length>=2&&(l/o.length>=.45||u>=2)}function oC(e,t){var _;const n=String(t||""),r=Q2(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 o=n.replace(/\r\n/g,`
102
+ `).replace(/\r/g,`
103
+ `).split(`
104
+ `),l=o.map(p=>p.trim()).filter(Boolean);if(l.length<2||iC(n)||sC(o)||rC(o))return!1;const u=((_=n.match(/[A-Za-z][A-Za-z'-]+/g))==null?void 0:_.length)||0,c=o.filter(p=>!p.trim()).length,f=l.filter(p=>/[A-Za-z]{3,}/.test(p)&&p.length>=12).length;return u>=24&&f>=2&&(c>=1||l[0].length<=140)}function Tf(e){const t=Zu(e==null?void 0:e.modality),n=Zu(e==null?void 0:e.content_type),r=u_(e),o=eC(e);return t==="image"||n.startsWith("image/")||Af(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(o)||Af(r,[".wav",".mp3",".m4a",".aac",".flac",".ogg",".opus",".aiff",".mid",".midi"])?"audio":t==="video"||n.startsWith("video/")||Af(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")||Qx(e,"")?"text":"binary"}function Bm(e,t){const n=Zu(e==null?void 0:e.content_type),r=u_(e),o=String(t||"").trim();return n.includes("html")||r.endsWith(".html")||r.endsWith(".htm")||tC(t)?"html":Qx(e,t)?"code":n.includes("markdown")||r.endsWith(".md")||r.endsWith(".markdown")?"markdown":n.includes("json")||r.endsWith(".json")||r.endsWith(".jsonl")||(o.startsWith("{")||o.startsWith("["))&&l_(o)!==null?"json":oC(e,t)?"markdown":"text"}function qg(e,t=""){const n=Tf(e);if(n==="image"||n==="video")return n;if(n==="audio"){const r=(e==null?void 0:e.tags)||{},o=[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(l=>String(l||"").trim().toLowerCase()).filter(Boolean).join(" ");return/(^|[^a-z0-9])(voice|tts|speech)([^a-z0-9]|$)/i.test(o)?"voice":/(^|[^a-z0-9])(music|song|instrumental|t2m)([^a-z0-9]|$)/i.test(o)?"music":/(^|[^a-z0-9])(sound|sfx|recording)([^a-z0-9]|$)/i.test(o)?"sound":"audio"}if(n==="binary"){const r=Zu(e==null?void 0:e.modality),o=Zu(e==null?void 0:e.content_type),l=u_(e);return r==="document"||o.includes("pdf")||Af(l,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return Bm(e,t)}function lp(e){var _,p;const t=String(e||"").replace(/\r\n/g,`
105
+ `).replace(/\r/g,`
106
+ `).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],o=[];let l=0,u="";const c=y=>" ".repeat(Math.max(0,y)),f=(y,w)=>{const x=y.match(/^(<\/?|<!)([^\s/>]+)([\s\S]*?)(\/?>)$/);if(!x||y.length<=120||y.startsWith("</")||y.startsWith("<!"))return[`${c(w)}${y.trim()}`];const S=(x[3]||"").trim();if(!S)return[`${c(w)}${y.trim()}`];const j=S.match(/[^\s="'<>`]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>`]+))?/g)||[S];return[`${c(w)}${x[1]}${x[2]}`,...j.map(C=>`${c(w+1)}${C.trim()}`),`${c(w)}${x[4]}`]};for(const y of r){const w=String(y||"");if(!w.trim())continue;const x=w.trim().toLowerCase();if(x.startsWith("</")){const j=((_=x.match(/^<\/\s*([a-z0-9:-]+)/))==null?void 0:_[1])||"";u&&j===u&&(u=""),l=Math.max(0,l-1),o.push(`${c(l)}${w.trim()}`);continue}if(w.trimStart().startsWith("<")){o.push(...f(w,l));const j=((p=x.match(/^<\s*([a-z0-9:-]+)/))==null?void 0:p[1])||"";/\/>\s*$/.test(w)||x.startsWith("<!")||n.has(j)||(l+=1,(j==="script"||j==="style")&&(u=j));continue}if(u){const j=w.trim();j&&o.push(...j.split(`
107
+ `).map(C=>`${c(l)}${C.trimEnd()}`));continue}const S=w.replace(/\s+/g," ").trim();S&&o.push(`${c(l)}${S}`)}return o.join(`
108
+ `)}function aC(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 Um(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 vl(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"?"info":"muted"}const lC=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function Hg(e){const t=typeof e=="string"?e:String(e??""),n=lC.exec(t);if(!n)return{text:t.trim(),metadata:null,stripped:!1};let r=null;try{const o=JSON.parse(String(n[1]||"").trim());o&&typeof o=="object"&&!Array.isArray(o)&&(r=o)}catch{r=null}return{text:t.slice(n[0].length).trim(),metadata:r,stripped:!0}}function tb(...e){const t={};for(const n of e)if(!(!n||typeof n!="object"||Array.isArray(n)))for(const[r,o]of Object.entries(n))o==null||String(o).trim()===""||(t[r]=o);return Object.keys(t).length?t:null}function ng(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>ng(t)).filter(Boolean).join(`
109
+ `).trim();if(typeof e=="object"){const t=e.text??e.content??e.message??e.value;if(t!==e){const n=ng(t);if(n)return n}}return""}function nb(e){const t=Hg(ng(e));return{text:t.text,runtime_metadata:t.metadata}}function cC(e){var r,o;if(!e)return{text:"",runtime_metadata:null};const t=typeof e.prompt=="string"?String(e.prompt).trim():"";if(t){const l=Hg(t);return{text:l.text,runtime_metadata:l.metadata}}const n=[(r=e.context)==null?void 0:r.messages,e.messages,e.conversation,e.history].filter(Array.isArray);for(const l of n)for(let u=l.length-1;u>=0;u-=1){const c=l[u],f=String((c==null?void 0:c.role)||(c==null?void 0:c.speaker)||"").trim().toLowerCase();if(f&&f!=="user"&&f!=="human")continue;const _=nb((c==null?void 0:c.content)??(c==null?void 0:c.text)??c);if(_.text)return{text:_.text,runtime_metadata:tb(_.runtime_metadata,c!=null&&c.runtime_metadata&&typeof c.runtime_metadata=="object"?c.runtime_metadata:null,(o=c==null?void 0:c.metadata)!=null&&o.runtime_metadata&&typeof c.metadata.runtime_metadata=="object"?c.metadata.runtime_metadata:null)}}return{text:"",runtime_metadata:null}}function uC(e,t=6){var l,u;if(!e)return[];const r=[(l=e.context)==null?void 0:l.messages,e.messages,e.conversation,e.history].filter(Array.isArray).find(c=>c.length)||[],o=[];for(const c of r){const f=String((c==null?void 0:c.role)||(c==null?void 0:c.speaker)||(c==null?void 0:c.author)||"").trim().toLowerCase()||"message",_=nb((c==null?void 0:c.content)??(c==null?void 0:c.text)??(c==null?void 0:c.message)??c),p=_.text;if(!p)continue;const y=String((c==null?void 0:c.ts)||(c==null?void 0:c.timestamp)||(c==null?void 0:c.created_at)||(c==null?void 0:c.time)||"").trim(),w=tb(_.runtime_metadata,c!=null&&c.runtime_metadata&&typeof c.runtime_metadata=="object"?c.runtime_metadata:null,(u=c==null?void 0:c.metadata)!=null&&u.runtime_metadata&&typeof c.metadata.runtime_metadata=="object"?c.metadata.runtime_metadata:null);o.push({role:f,text:p,ts:y,runtime_metadata:w})}return o.slice(Math.max(0,o.length-Math.max(1,t)))}function sb(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function dC(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 rb="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function ib(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(),o=[];return(t.includes("execute_command")||t.includes("terminal")||r)&&o.push("Shell"),/[;&|]?\s*(rm|rmdir|mv|chmod|chown|sudo)\b/.test(r)&&o.push("Destructive risk"),/(^|\s)(curl|wget|scp|ssh|nc|ncat|ftp)\b/.test(r)&&o.push("Network"),/(^|\s)(cat|sed|rg|grep|ls|find|pwd)\b/.test(r)&&!/[>|]\s*\S/.test(r)&&o.push("Read path"),/[>|]\s*\S|(^|\s)(tee|touch|mkdir|cp)\b/.test(r)&&o.push("Filesystem write"),o.length||o.push("Tool call"),Array.from(new Set(o)).slice(0,4)}function Vg(e,t){const n=String((e==null?void 0:e.reason)||"").trim().toLowerCase(),r=dC(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 ob(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 ab(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),r=Hg(n),o=cC(t);return r.text&&!sb(r.text)?{text:r.text,runtime_metadata:r.metadata}:o.text?o:{text:r.text||n,runtime_metadata:r.metadata}}function fC(e,t){return ab(e,t).text}function hC(e,t){return e||String(t||"").trim()||{}}function $i(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 xl(e){const t=String(e.status||"unknown").trim()||"unknown";return s.jsx("span",{className:`run_status_pill ${vl(t)}`,children:t})}function mC(e){var l;const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Ri(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(),o=Array.isArray((l=n==null?void 0:n.details)==null?void 0:l.tool_calls)?n.details.tool_calls:[];return o.length?Vg(n,o):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 Wm(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?_t(t,{max_chars:220,max_lines:2}):_t(Os(t,400),{max_chars:220,max_lines:2}):""}function _C(e){const t=mC(e);if(t)return t;const n=Wm(e);if(n)return n;const r=String((e==null?void 0:e.current_node)||"").trim();if(r)return`Current node: ${r}`;const o=String((e==null?void 0:e.status)||"").trim().toLowerCase();return o==="running"?"Running":Ri(o)?"Terminal":"No current activity reported"}function lb(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 dw(e){const t=lb(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:{},o=dn(e==null?void 0:e.modality,t==null?void 0:t.modality,n==null?void 0:n.modality,r.modality).toLowerCase();if(o)return o;const l=dn(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 l.startsWith("image/")?"image":l.startsWith("audio/")?"audio":l.startsWith("video/")?"video":l.includes("pdf")?"document":l.startsWith("text/")||l.includes("json")||l.includes("markdown")||l.includes("csv")?"text":"artifact"}function pC(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 gC(e,t){if(!e||typeof e!="object")return null;const n=pC(e),r=lb(e),o=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},l=n!=null&&n.descriptor&&typeof n.descriptor=="object"?n.descriptor:e!=null&&e.descriptor&&typeof e.descriptor=="object"?e.descriptor:{},u=dn(n.artifact_id,e.artifact_id,e.$artifact,e.id,r.artifact_id,r.$artifact,r.id,o.artifact_id,o.$artifact);if(!u)return null;const c={...r.tags&&typeof r.tags=="object"?r.tags:{},...o.tags&&typeof o.tags=="object"?o.tags:{},...n.tags&&typeof n.tags=="object"?n.tags:{},...e.tags&&typeof e.tags=="object"?e.tags:{}},f={};for(const[P,W]of Object.entries(c)){const G=String(P||"").trim();G&&(f[G]=String(W??""))}const _=dn(n.filename,e.filename,r.filename,o.filename,f.filename,f.name,e.name,r.name),p=dn(n.source_path,e.source_path,r.source_path,o.source_path,e.path,r.path,f.path,f.source_path,f.file_path),y=dn(n.content_type,e.content_type,e.mime_type,e.mime,r.content_type,r.mime_type,r.mime,o.content_type,f.content_type),w=dn(n.render_kind,l.render_kind,e.render_kind,f.render_kind),x=dn(n.semantic_kind,l.semantic_kind,e.semantic_kind,f.semantic_kind,f.artifact_type),S=n.access&&typeof n.access=="object"?n.access:e.access&&typeof e.access=="object"?e.access:{},j=n.producer&&typeof n.producer=="object"?n.producer:e.producer&&typeof e.producer=="object"?e.producer:l.producer&&typeof l.producer=="object"?l.producer:{},C=n.provenance&&typeof n.provenance=="object"?n.provenance:e.provenance&&typeof e.provenance=="object"?e.provenance:l.provenance&&typeof l.provenance=="object"?l.provenance:{},N=n.generation&&typeof n.generation=="object"?n.generation:e.generation&&typeof e.generation=="object"?e.generation:l.generation&&typeof l.generation=="object"?l.generation:{},T=n.media&&typeof n.media=="object"?n.media:e.media&&typeof e.media=="object"?e.media:l.media&&typeof l.media=="object"?l.media:{},L=n.links&&typeof n.links=="object"?n.links:e.links&&typeof e.links=="object"?e.links:l.links&&typeof l.links=="object"?l.links:{};return{artifact_id:u,run_id:dn(n.run_id,e.run_id,r.run_id,o.run_id,f.run_id,C.run_id),content_type:y,modality:dn(n.modality,e.modality,l.modality,f.modality)||dw({...e,ref:r,metadata:o,tags:f}),semantic_kind:x||dw({...e,ref:r,metadata:o,tags:f}),render_kind:w||qg({content_type:y,filename:_,source_path:p,modality:dn(n.modality,e.modality,f.modality),tags:f}),task:dn(n.task,l.task,e.task,f.task,f.provider_task),classification_source:dn(n.classification_source,l.classification_source,e.classification_source),session_id:dn(n.session_id,l.session_id,e.session_id,f.session_id),workflow_id:dn(n.workflow_id,l.workflow_id,e.workflow_id,f.workflow_id,f.workflow),node_id:dn(n.node_id,l.node_id,e.node_id,f.node_id,f.node),step_id:dn(n.step_id,l.step_id,e.step_id,f.step_id),effect_id:dn(n.effect_id,l.effect_id,e.effect_id,f.effect_id,f.effect_idempotency_key),turn_id:dn(n.turn_id,l.turn_id,e.turn_id,f.turn_id,f.turn),ledger_cursor:dn(n.ledger_cursor,l.ledger_cursor,e.ledger_cursor,f.ledger_cursor,f.step_cursor),parent_run_id:dn(n.parent_run_id,l.parent_run_id,e.parent_run_id,f.parent_run_id),actor_id:dn(n.actor_id,l.actor_id,e.actor_id,f.actor_id),title:dn(n.title,e.title,f.title,f.label,f.name),created_at:dn(n.created_at,e.created_at,r.created_at,o.created_at,f.created_at),size_bytes:X2(n.size_bytes,e.size_bytes,r.size_bytes,o.size_bytes,f.size_bytes),filename:_,source_path:p,sha256:dn(n.sha256,e.sha256,r.sha256,o.sha256,f.sha256),tags:f,producer:j,provenance:C,generation:N,media:T,source_refs:Array.isArray(n.source_refs)?n.source_refs:Array.isArray(e.source_refs)?e.source_refs:[],access:S,links:L,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(dn(n.classification_source,l.classification_source,e.classification_source))),descriptor:l,source:t,raw:e}}function sg(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||Lt(e.artifact_id,16)}function yC(e,t){if(t==="type")return Vu(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return rg(e);if(t==="node")return Hu(e)||"(node unknown)";if(t==="workflow")return Gg(e)||"(workflow unknown)";if(t==="location"){const o=(e.source_path||e.filename||"").split("/").filter(Boolean);return o.length>1?o.slice(0,-1).join("/"):"(root)"}if(t==="source")return If(e)||e.source||"artifact";const n=Nn(e.created_at);return n===null?"(unknown time)":new Date(n).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Gg(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 Hu(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 o=String((e==null?void 0:e.source_path)||t.path||"").trim().match(/(?:^|[._:/-])(node-[A-Za-z0-9_-]+)/);return o!=null&&o[1]?String(o[1]):""}function rg(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=Hu(e),o=Nn(e==null?void 0:e.created_at),l=o===null?"unknown time":new Date(o).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),u=e!=null&&e.run_id?Lt(String(e.run_id),10):"unknown run";return r?`${u} · ${r} · ${l}`:`${u} · ${l}`}function fw(e){if(!e)return"provenance unavailable";const t=[],n=Gg(e),r=Hu(e),o=If(e),l=cb(e);return n&&t.push(n),r&&t.push(r),o&&t.push(o),l&&t.push(l),t.length?t.join(" · "):"provenance unavailable"}function xc(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 o=r===0?0:n>=10?1:2;return`${n.toFixed(o)} ${t[r]}`}function Vu(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,l=>l.toUpperCase())}function wC(e){return e==="html"?"HTML":e==="json"?"JSON":e==="audio"?"Unclassified audio":e==="code"?"Code":e.slice(0,1).toUpperCase()+e.slice(1)}function vC(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 xC(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 hw(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 bC(e){const t=Ea(e.created_at),n=ka(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function mw(e){var o;const t=e.tags||{},n=String(((o=e.access)==null?void 0:o.last_accessed_at)||t.last_accessed_at||t.accessed_at||t.updated_at||e.created_at||"").trim(),r=Ea(n);return r==="—"?"—":r}function _w(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 o=If(e),l=Vu(e);return o?`${l} ${o}`:`${l} artifact`}function If(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 cb(e){var r,o,l,u,c,f,_,p;if(!e)return"";const t=dn((r=e.producer)==null?void 0:r.provider,(o=e.producer)==null?void 0:o.provider_id,(l=e.provenance)==null?void 0:l.provider,(u=e.generation)==null?void 0:u.provider),n=dn((c=e.producer)==null?void 0:c.model,(f=e.producer)==null?void 0:f.model_id,(_=e.provenance)==null?void 0:_.model,(p=e.generation)==null?void 0:p.model);return t&&n?`${t} / ${n}`:t||n}function jC(e){var t,n,r,o;return e?dn((t=e.generation)==null?void 0:t.prompt,(n=e.generation)==null?void 0:n.input,(r=e.generation)==null?void 0:r.text,(o=e.provenance)==null?void 0:o.prompt):""}function pw(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),o=Number(t.height??t.image_height??t.video_height),l=Number(t.sample_rate??t.sample_rate_hz),u=Number(t.channels);if(Number.isFinite(n)&&n>0){const f=[`${n>=60?`${Math.floor(n/60)}m ${Math.round(n%60)}s`:`${n.toFixed(n>=10?1:2)}s`}`];return Number.isFinite(l)&&l>0&&f.push(`${Math.round(l/1e3)} kHz`),Number.isFinite(u)&&u>0&&f.push(`${u} ch`),f.join(" · ")}if(Number.isFinite(r)&&Number.isFinite(o)&&r>0&&o>0)return`${Math.round(r)} x ${Math.round(o)}`;const c=Number(t.page_count??t.pages);return Number.isFinite(c)&&c>0?`${Math.round(c)} pages`:""}function gw(e){return e.source_path||e.filename||""}function qm(e,t,n){const r=e.run_id&&t[e.run_id]||null;if(!r)return e;const o=$i(r,n),l={...e.tags||{}};return o&&!l.workflow&&(l.workflow=o),o&&!l.workflow_id&&(l.workflow_id=o),{...e,workflow_id:e.workflow_id||o,tags:l}}function ig(e,t,n,r=""){const o=qm(e,t,n),l=qg(o,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"}[l]||Vu(o)}function no(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 am(e){var l,u,c;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(((l=n==null?void 0:n.payload)==null?void 0:l.name)||((u=n==null?void 0:n.payload)==null?void 0:u.event_name)||"").trim();if(!r)return null;const o=(c=n==null?void 0:n.payload)==null?void 0:c.payload;return{name:r,payload:o}}function nd(e){const t=e,n=t==null?void 0:t.details;if(!n||typeof n!="object")return[];if(Array.isArray(n))return n.filter(o=>o&&typeof o=="object"&&typeof o.name=="string");const r=n==null?void 0:n.tool_calls;return Array.isArray(r)?r:[]}function SC(e){var o,l;const t=String((e==null?void 0:e.status)||"").trim(),n=String(((o=e==null?void 0:e.effect)==null?void 0:o.type)||"").trim(),r=(l=e==null?void 0:e.effect)!=null&&l.payload&&typeof e.effect.payload=="object"?String(e.effect.payload.name||"").trim():"";return n==="emit_event"&&r?r:n||t||"record"}function ub(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),r=SC(e),o=no(e);if(o){const l=String(o.reason||"").trim();if(String(o.prompt||"").trim())return`${t||"node"} is waiting for a response`;if(l)return`${t||"node"} is waiting (${l})`}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 Lu(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):Os(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:Os(e,320),duration:-1}}function Xf(e){var u,c,f,_,p,y,w,x,S;if(!e||typeof e!="object")return"";const t=String(((u=e==null?void 0:e.effect)==null?void 0:u.type)||"").trim(),n=e==null?void 0:e.result,r=j=>typeof j=="string"?j.trim():j==null?"":typeof j=="number"||typeof j=="boolean"?String(j):"",o=j=>{if(!j||typeof j!="object")return"";const C=j,N=[C.response,C.answer,C.message,C.text,C.content];for(const T of N){const L=r(T);if(L)return L}return""};if(t==="answer_user"){const j=r(n==null?void 0:n.message)||r((c=n==null?void 0:n.output)==null?void 0:c.message)||r((f=n==null?void 0:n.output)==null?void 0:f.response)||r((p=(_=e==null?void 0:e.effect)==null?void 0:_.payload)==null?void 0:p.message)||r((w=(y=e==null?void 0:e.effect)==null?void 0:y.payload)==null?void 0:w.text)||r((S=(x=e==null?void 0:e.effect)==null?void 0:x.payload)==null?void 0:S.content);if(j)return j}if(t==="llm_call"){const j=o(n)||r(n==null?void 0:n.output)||o(n==null?void 0:n.output)||r(n==null?void 0:n.response);if(j)return j}return r(n==null?void 0:n.output)||o(n==null?void 0:n.output)||o(n)||r(n==null?void 0:n.response)}function Nm(e){var o;const t=String((e==null?void 0:e.node_id)||""),n=String((e==null?void 0:e.status)||""),r=String(((o=e==null?void 0:e.effect)==null?void 0:o.type)||"");return`${t||"(node?)"} • ${n||"(status?)"} • ${r||"(effect?)"}`}function kC(e){return!!(e&&String(e.status||"")==="waiting")}function db(e){var n,r;const t=[];for(const o of e||[]){const l=o.record;if(String(((n=l==null?void 0:l.effect)==null?void 0:n.type)||"").trim()!=="llm_call")continue;const c=(r=l==null?void 0:l.effect)!=null&&r.payload&&typeof l.effect.payload=="object"?l.effect.payload:{},f=l!=null&&l.result&&typeof l.result=="object"?l.result:{},_=(f==null?void 0:f.usage)||(f==null?void 0:f.token_usage)||{},p=typeof c.prompt=="string"?c.prompt:Array.isArray(c.messages)?Os(c.messages,1800):"",y=typeof f.content=="string"?f.content:typeof f.response=="string"?f.response:typeof l.result=="string"?String(l.result):"",w=Nn(l.started_at),x=Nn(l.ended_at),S=Number(_.prompt_tokens??_.input_tokens??0)||0,j=Number(_.completion_tokens??_.output_tokens??0)||0;t.push({id:`${String(o.run_id||l.run_id||"")}:${o.cursor}`,cursor:Number(o.cursor||0),ts:String(l.ended_at||l.started_at||""),run_id:String(o.run_id||l.run_id||"").trim(),node_id:String(l.node_id||"").trim(),provider:String(c.provider||f.provider||f.runtime_provider||"").trim(),model:String(c.model||f.model||f.runtime_model||"").trim(),prompt_preview:_t(p,{max_chars:1200,max_lines:10}),response_preview:_t(y,{max_chars:1200,max_lines:10}),missing_response:!String(y||"").trim(),tokens:{prompt:S,completion:j,total:Number(_.total_tokens??S+j)||0},duration_ms:w!==null&&x!==null?Math.max(0,x-w):typeof f.gen_time=="number"?Number(f.gen_time)*1e3:null,status:String(l.status||"").trim(),error:l.error?Os(l.error,500):"",raw:l})}return t.sort((o,l)=>(Nn(l.ts)??0)-(Nn(o.ts)??0))}function yw(e){const t=e.size||18,n=Tf(e.artifact),r=qg(e.artifact,""),o=`artifact_glyph ${r==="code"?"code":n}`,l={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:o,children:s.jsxs("svg",{...l,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:o,children:s.jsxs("svg",{...l,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:o,children:s.jsxs("svg",{...l,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:o,children:s.jsxs("svg",{...l,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:o,children:s.jsxs("svg",{...l,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:o,children:s.jsxs("svg",{...l,children:[s.jsx("path",{d:"M7 3h7l5 5v13H7z"}),s.jsx("path",{d:"M14 3v6h6"}),s.jsx("path",{d:"M9 14h8"})]})})}const NC=2,CC=Number.MAX_SAFE_INTEGER;function EC(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 $C(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:lp(t)||t}];try{const n=new DOMParser().parseFromString(t,"text/html"),r=[];n.doctype&&r.push({kind:"doctype",name:n.doctype.name||"html"});const o=l=>{if(l.nodeType===Node.TEXT_NODE){const u=String(l.textContent||"").trim();return u?{kind:"text",text:u}:null}if(l.nodeType===Node.COMMENT_NODE)return{kind:"comment",text:String(l.textContent||"")};if(l.nodeType===Node.ELEMENT_NODE){const u=l,c=Array.from(u.attributes||[]).map(_=>({name:_.name,value:_.value})),f=Array.from(u.childNodes||[]).map(o).filter(Boolean);return{kind:"element",tag:u.tagName.toLowerCase(),attrs:c,children:f}}return null};if(n.documentElement){const l=o(n.documentElement);l&&r.push(l)}return r.length?r:[{kind:"text",text:lp(t)||t}]}catch{return[{kind:"text",text:lp(t)||t}]}}function cp(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(ve.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 fb(e){const t=e.node,n=e.depth*14,r=e.depth<e.collapseAfterDepth,[o,l]=m.useState(r);if(m.useEffect(()=>{l(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(cp,{tag:t.tag,attrs:t.attrs,selfClosing:!0})});const u=t.children.find(c=>c.kind==="text");return s.jsxs("details",{className:"html-tree__details",open:o,onToggle:c=>l(c.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:o?"▾":"▸"}),s.jsx(cp,{tag:t.tag,attrs:t.attrs}),!o&&u?s.jsxs("span",{className:"html-tree__summary_text",children:[" ",EC(u.text)]}):null]}),o?s.jsxs("div",{className:"html-tree__children",children:[t.children.map((c,f)=>s.jsx(fb,{node:c,depth:e.depth+1,collapseAfterDepth:e.collapseAfterDepth,expansionMode:e.expansionMode,expansionVersion:e.expansionVersion},`${e.depth}:${t.kind}:${t.tag}:${f}`)),s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx(cp,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function AC(e){const t=m.useMemo(()=>$C(e.text),[e.text]),[n,r]=m.useState({mode:"folded",version:0}),o=n.mode==="unfolded"?CC:NC;m.useEffect(()=>{r(u=>({mode:"folded",version:u.version+1}))},[e.text]);const l=()=>{r(u=>({mode:u.mode==="unfolded"?"folded":"unfolded",version:u.version+1}))};return s.jsxs("div",{className:`${e.className} structured html_source_preview`,children:[s.jsx("div",{className:"html-tree__toolbar",children:s.jsx("button",{type:"button",className:"btn html-tree__toggle",onClick:l,"aria-expanded":n.mode==="unfolded",children:n.mode==="unfolded"?"Fold all":"Unfold all"})}),s.jsx("div",{className:"html-tree__tree",role:"tree","aria-label":"HTML source tree",children:t.map((u,c)=>s.jsx(fb,{node:u,depth:0,collapseAfterDepth:o,expansionMode:n.mode,expansionVersion:n.version},`root:${c}`))})]})}function TC(e){var r;const t=nC(e.text);if(!t)return s.jsx("div",{className:`${e.className} structured markdown_preview`,children:s.jsx(Mi,{text:e.text})});const n=((r=t.metadata.find(o=>o.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(o=>{const l=/^https?:\/\//i.test(o.value);return s.jsxs("div",{children:[s.jsx("dt",{children:o.label}),s.jsx("dd",{children:l?s.jsx("a",{href:o.value,target:"_blank",rel:"noreferrer",children:o.value}):o.value})]},`${o.label}:${o.value}`)})}):null,s.jsx(Mi,{text:t.body||e.text})]})}function hb(e){const t=String(e.text||""),n=Bm(e.artifact,t);if(n==="json"){const r=l_(t);if(r!==null)return s.jsx("div",{className:`${e.className} structured`,children:s.jsx(mr,{value:r,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?s.jsx(TC,{text:t,className:e.className}):n==="html"?s.jsx(AC,{text:t,className:e.className}):s.jsx("pre",{className:`mono ${e.className}`,children:t})}function MC(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:sg(n)}):t.kind==="audio"&&t.url?s.jsx("audio",{className:"runtime_inline_preview audio",src:t.url,controls:!0}):t.kind==="video"&&t.url?s.jsx("video",{className:"runtime_inline_preview media",src:t.url,controls:!0}):s.jsx(hb,{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 Kg(e){const t=e==null?void 0:e.waiting;return t&&typeof t=="object"?t:null}function mb(e){const t=Kg(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function ww(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 RC(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 sd(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Ri(t)||t!=="waiting")return"none";const n=Kg(e),r=mb(e);return nd(n).length?"tool_approval":r==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":r==="subworkflow"?"subworkflow":r==="event"?ww(n)?"user_response":"external_event":r==="user"||ww(n)?"user_response":"unknown_wait"}function _b(e){const t=Kg(e),n=nd(t),r=sd(e);return r==="tool_approval"?`Tool approval: ${RC(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 LC(e){const t=sd(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.":Ri(n)?"Open the ledger and artifacts for the final outcome.":"Open the run to inspect current activity."}function vw(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 IC(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label??"",o=String(e.status||"unknown").trim().toLowerCase()||"unknown",l=sd(e),u=Ri(o),c=Wg(e,n),f=Nn(e.updated_at||e.created_at)??0,_=o==="running"&&c>=14400*1e3,p=_b(e)||vw(e)||(e.current_node?`Current node: ${e.current_node}`:o==="running"?"Running":u?"Terminal":"No current activity reported");let y="all";l==="tool_approval"?y="tool_approval":l==="user_response"?y="user_wait":l==="scheduled"?y="scheduled":l==="subworkflow"||l==="external_event"?y="subflows":o==="failed"?y="failed":o==="running"?y="running":u&&(y="finished");const w=l==="tool_approval"?0:l==="user_response"?1:l==="unknown_wait"?2:o==="failed"?3:_?4:o==="running"?5:l!=="none"?6:u?8:7,x=l==="tool_approval"||l==="user_response",S=l==="tool_approval"?"Open approval":l==="user_response"?"Open wait":"Open Observe",j=[e.run_id,e.workflow_id,r,e.session_id,e.parent_run_id,e.status,e.current_node,mb(e),p,vw(e)].join(" ").toLowerCase();return{run:e,run_id:String(e.run_id||"").trim(),status:o,wait_kind:l,queue:y,attention_rank:w,reason:p,expected_action:LC(e),action_label:S,search_text:j,is_terminal:u,needs_user_action:x,is_stale:_,duration_ms:c,updated_ms:f}}function OC(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label_by_id??{};return e.map(o=>IC(o,{now_ms:n,workflow_label:r[String(o.workflow_id||"")]||String(o.workflow_id||"")}))}function PC(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 DC(e,t){const n=t.queue,o=(t.query??"").trim().toLowerCase();return e.filter(l=>{if(n==="attention"){if(!(l.needs_user_action||l.status==="failed"||l.is_stale||l.wait_kind==="unknown_wait"))return!1}else if(n!=="all"&&l.queue!==n)return!1;return!o||l.search_text.includes(o)})}function FC(e,t){const n=[...e];return n.sort((r,o)=>{if(t==="recent")return o.updated_ms-r.updated_ms;if(t==="oldest")return r.updated_ms-o.updated_ms;if(t==="duration")return o.duration_ms-r.duration_ms;if(t==="tokens")return(Number(o.run.tokens_total||0)||0)-(Number(r.run.tokens_total||0)||0);if(t==="workflow")return String(r.run.workflow_id||"").localeCompare(String(o.run.workflow_id||""));const l=r.attention_rank-o.attention_rank;return l!==0?l:o.updated_ms-r.updated_ms}),n}function zC(e){const[t,n]=m.useState("attention"),[r,o]=Rf("system_queues"),[l,u]=Rf("system_runs"),[c,f]=m.useState(""),[_,p]=m.useState("attention"),[y,w]=m.useState(""),x=m.useMemo(()=>{const E={};for(const te of e.artifacts){const O=String(te.run_id||"").trim();O&&(E[O]=(E[O]||0)+1)}return E},[e.artifacts]),S=m.useMemo(()=>OC(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),j=m.useMemo(()=>PC(S),[S]),C=m.useMemo(()=>{const E=DC(S,{queue:t,query:c});return FC(E,_)},[S,t,c,_]),N=C.find(E=>String(E.run_id||"")===y)||C.find(E=>String(E.run_id||"")===e.selected_run_id)||C[0]||null,T=(N==null?void 0:N.run)||null,L=String((T==null?void 0:T.run_id)||"").trim(),P=String((T==null?void 0:T.session_id)||"").trim(),W=m.useMemo(()=>P?new Set(e.runs.filter(E=>String(E.session_id||"").trim()===P).map(E=>String(E.run_id||"").trim()).filter(Boolean)):new Set,[e.runs,P]),G=P?W.size:0,Y=m.useMemo(()=>P?e.artifacts.filter(E=>String(E.session_id||"").trim()===P||W.has(String(E.run_id||"").trim())).length:0,[e.artifacts,P,W]),J=T!=null&&T.waiting&&typeof T.waiting=="object"?T.waiting:null,re=J?nd(J):[],ae=(N==null?void 0:N.reason)||(J?Vg(J,re):""),ue=(N==null?void 0:N.expected_action)||(J?ob(J,re):""),B=J?fC(J,null):"",A=L&&x[L]||0,$=Ri(T==null?void 0:T.status),z=[{key:"attention",label:"Needs attention",count:j.attention},{key:"user_wait",label:"Needs my response",count:j.user_wait},{key:"tool_approval",label:"Tool approvals",count:j.tool_approval},{key:"running",label:"Running",count:j.running},{key:"failed",label:"Failed",count:j.failed},{key:"scheduled",label:"Scheduled",count:j.scheduled},{key:"subflows",label:"Subflows / external events",count:j.subflows},{key:"finished",label:"Finished",count:j.finished},{key:"all",label:"All loaded",count:j.all}];return s.jsxs("div",{className:`runtime_ops_layout${r?"":" queues_collapsed"}${l?"":" 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(Lf,{open:r,on_toggle:o,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:[z.map(E=>s.jsxs("button",{className:`runtime_ops_filter ${t===E.key?"selected":""}`,"aria-pressed":t===E.key,onClick:()=>n(E.key),children:[s.jsx("span",{children:E.label}),s.jsx("strong",{children:E.count.toLocaleString()})]},E.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${l?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"pane_header runtime_ops_list_header",children:[s.jsx(Lf,{open:l,on_toggle:u,controls:"runtime_ops_runs",title:"Runs",count:C.length.toLocaleString()}),s.jsx("div",{className:"pane_spacer"}),s.jsx("input",{value:c,onChange:E=>f(E.target.value),placeholder:"Search workflow, run, node, status, error"}),s.jsxs("select",{className:"seg_select",value:_,onChange:E=>p(E.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:!l,children:[C.length?null: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."}),C.map(E=>{const te=E.run,O=String(te.run_id||"").trim(),F=x[O]||0;return s.jsxs("div",{className:`raised runtime_ops_row ${O===L?"selected":""}`,"aria-current":O===L?"true":void 0,tabIndex:0,onClick:()=>{w(O),e.on_select_run(O)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),w(O),e.on_select_run(O))},children:[s.jsxs("div",{className:"runtime_ops_row_top",children:[s.jsx("strong",{className:"runtime_ops_row_name",children:$i(te,e.workflow_label_by_id)}),E.is_stale?s.jsx("span",{className:"chip warn",children:"stale"}):null,s.jsx(xl,{status:te.status})]}),s.jsxs("div",{className:"runtime_ops_row_sub",children:[s.jsx("span",{className:"mono",children:Lt(O,18)}),s.jsx("span",{children:ka(te.updated_at||te.created_at)}),s.jsx("span",{children:Ac(te)}),s.jsx("span",{className:"runtime_ops_row_reason",title:E.reason,children:E.reason})]}),s.jsxs("div",{className:"runtime_ops_row_foot",children:[s.jsxs("span",{className:"runtime_ops_row_facts",children:[s.jsxs("span",{children:[Number(te.llm_calls||0).toLocaleString()," llm"]}),s.jsxs("span",{children:[Number(te.tool_calls||0).toLocaleString()," tools"]}),s.jsxs("span",{children:[Number(te.tokens_total||0).toLocaleString()," tok"]}),s.jsxs("span",{children:[F.toLocaleString()," artifacts"]})]}),s.jsxs("div",{className:"runtime_ops_actions",children:[E.needs_user_action?s.jsx("button",{className:"btn primary",onClick:K=>{K.stopPropagation(),e.on_open_run(O)},children:E.action_label}):s.jsx("button",{className:"btn",onClick:K=>{K.stopPropagation(),e.on_open_run(O)},children:"Open"}),s.jsx("button",{className:"btn",onClick:K=>{K.stopPropagation(),e.on_open_ledger(O)},children:"Ledger"}),s.jsx("button",{className:"btn",onClick:K=>{K.stopPropagation(),e.on_select_run(O),e.on_open_logs()},children:"Logs"}),s.jsx("button",{className:"btn",onClick:K=>{K.stopPropagation(),e.on_filter_artifacts(O)},children:"Artifacts"})]})]})]},O)})]})]}),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"}),T?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pane_spacer"}),s.jsx(xl,{status:T.status})]}):null]}),s.jsx("div",{className:"pane_body scroll runtime_ops_inspector_body",children:T?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_ops_inspector_head",children:[s.jsx("h3",{children:$i(T,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Lt(L,28)})]}),s.jsxs("div",{className:"runtime_ops_decision",children:[s.jsx("strong",{children:(N==null?void 0:N.reason)||_C(T)}),s.jsx("span",{children:(N==null?void 0:N.expected_action)||(String(T.status||"").toLowerCase()==="waiting"?"This run is paused until the pending wait is resolved or the run is cancelled.":$?"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:Ea(vc(T))})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:Ac(T)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last event"}),s.jsx("strong",{children:Ea(T.updated_at||T.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:T.session_id?Lt(String(T.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:T.current_node||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Visible artifacts"}),s.jsx("strong",{children:A.toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:Number(T.llm_calls||0).toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Tokens"}),s.jsx("strong",{children:Number(T.tokens_total||0).toLocaleString()})]})]}),P?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:Lt(P,30)})]}),s.jsxs("div",{className:"runtime_ops_session_facts",children:[s.jsxs("span",{children:[G.toLocaleString()," loaded run",G===1?"":"s"]}),s.jsxs("span",{children:[Y.toLocaleString()," visible artifact",Y===1?"":"s"]})]}),s.jsxs("div",{className:"runtime_detail_actions compact",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_filter_session_artifacts(P),children:"Open session artifacts"}),s.jsx("button",{className:"btn",onClick:()=>void $c(P),children:"Copy session id"})]})]}):null,J?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:ae})]}),s.jsx("p",{children:ue}),B?s.jsxs("div",{className:"runtime_ops_wait_request",children:[s.jsx("span",{children:"Request"}),s.jsx(Mi,{text:B})]}):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."}),re.length?s.jsx("div",{className:"runtime_ops_wait_tools",children:re.map((E,te)=>s.jsxs(ve.Fragment,{children:[s.jsx("span",{className:"chip mono warn",children:String((E==null?void 0:E.name)||"tool")}),ib(E).map(O=>s.jsxs("span",{className:"chip muted",title:rb,children:[O,"~"]},`${te}:${O}`))]},`${String((E==null?void 0:E.name)||"tool")}:${te}`))}):null,s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"muted",children:"Raw wait payload"}),s.jsx(mr,{value:J,collapseAfterDepth:3,showCopy:!0})]})]}):null,Wm(T)?s.jsx("div",{className:"warn_callout",children:Wm(T)}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(L),children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(L),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>e.on_filter_artifacts(L),children:"Open artifacts"}),s.jsx("button",{className:"btn",onClick:e.on_open_logs,children:"Open logs"}),s.jsx("button",{className:"btn",onClick:()=>void $c(L),children:"Copy run id"})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run to inspect why it is active or blocked."})})]})]})}function BC(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"}],o=m.useMemo(()=>new Set(e.type_filters),[e.type_filters]),l=Math.max(0,Number(e.artifact_total_count||0)),u=!!e.query.trim()||e.type_filters.length>0||e.date_filter!=="all"||e.scope!=="all"||!!e.artifact_run_filter.trim(),c=Math.max(1,Number(e.artifact_page_size||500)),f=Math.max(1,Math.ceil(l/c)),_=Math.min(Math.max(0,Number(e.artifact_page||0)),f-1),p=l?_*c+1:0,y=Math.min(l,_*c+e.artifacts.length),w=m.useMemo(()=>{const A={},$=e.artifact_type_facets&&Object.keys(e.artifact_type_facets).length?e.artifact_type_facets:e.artifact_facets,z=($==null?void 0:$.semantic_kind)||{},E=($==null?void 0:$.render_kind)||{};for(const te of n)A[te]=Number(z[te]||E[te]||0);return A.audio=Number(z.audio||0),A.other=Number(z.other||0)+Number(z.artifact||0)+Number(z.binary||0)+Number(z["(none)"]||0),A},[e.artifact_facets,e.artifact_type_facets]),x=A=>{const $=new Set(o);$.has(A)?$.delete(A):$.add(A),e.on_type_filters_change(Array.from($.values()))},S=m.useMemo(()=>{const A={waiting:[],running:[],failed:[],cancelled:[],completed:[],other:[]};for(const $ of e.runs){const z=String($.status||"").trim().toLowerCase();z==="waiting"?A.waiting.push($):z==="running"?A.running.push($):z==="failed"?A.failed.push($):z==="cancelled"?A.cancelled.push($):z==="completed"?A.completed.push($):A.other.push($)}return A},[e.runs]),j=t!=null&&t.run_id&&e.run_by_id[t.run_id]||null,C=e.artifact_run_filter?$i(e.run_by_id[e.artifact_run_filter],e.workflow_label_by_id):"",N=m.useMemo(()=>{var z;const A=new Set,$=((z=e.artifact_facets)==null?void 0:z.run_id)||{};for(const E of Object.keys($))E&&E!=="(none)"&&A.add(E);for(const E of e.artifacts)E.run_id&&A.add(E.run_id);for(const E of e.active_runs)E.run_id&&A.add(String(E.run_id));return Array.from(A).map(E=>e.run_by_id[E]||{run_id:E,workflow_id:null,status:"",created_at:null,updated_at:null}).sort((E,te)=>{const O=Xu(E.status)?0:1,F=Xu(te.status)?0:1;if(O!==F)return O-F;const K=Nn(E.updated_at||E.created_at)??0;return(Nn(te.updated_at||te.created_at)??0)-K}).slice(0,160)},[e.artifacts,e.active_runs,e.run_by_id,e.artifact_facets]),T=A=>{e.on_artifact_run_filter_change(A),e.on_session_filter_change(""),e.on_scope_change(A?"run":"all")},L=A=>e.gateway_connected?Math.max(0,Number(A||0)).toLocaleString():"—",P=e.selected_run_id&&e.run_by_id[e.selected_run_id]||null,W=m.useMemo(()=>{const A=e.runtime_log_query.trim().toLowerCase(),$=e.runtime_ledger_log_items||[];return A?$.filter(z=>{var O,F;const E=z.record||{};return[z.cursor,E.run_id,E.node_id,E.status,(O=E.effect)==null?void 0:O.type,E.started_at,E.ended_at,Os(((F=E.effect)==null?void 0:F.payload)??{},900),Os(E.result??{},900)].join(" ").toLowerCase().includes(A)}):$},[e.runtime_ledger_log_items,e.runtime_log_query]),G=m.useMemo(()=>{const A=e.runtime_log_query.trim().toLowerCase(),$=db(e.runtime_ledger_log_items);return A?$.filter(z=>[z.provider,z.model,z.run_id,z.node_id,z.status,z.error,z.prompt_preview,z.response_preview,z.tokens.prompt,z.tokens.completion,z.tokens.total].join(" ").toLowerCase().includes(A)):$},[e.runtime_ledger_log_items,e.runtime_log_query]),Y=G.reduce((A,$)=>A+(Number($.tokens.total)||0),0),J=G.filter(A=>A.missing_response||A.error).length,re=m.useMemo(()=>{const A=e.runtime_log_query.trim().toLowerCase(),$=String(e.audit_log_text||"").replace(/\r\n/g,`
110
+ `).replace(/\r/g,`
111
+ `).split(`
112
+ `).filter(Boolean);return A?$.filter(z=>z.toLowerCase().includes(A)):$},[e.audit_log_text,e.runtime_log_query]),ae=e.runtime_log_source==="run_ledger"||e.runtime_log_source==="provider_calls",ue=e.runtime_log_source==="run_ledger"?"Selected Run Ledger":e.runtime_log_source==="provider_calls"?"Provider Calls":"Gateway HTTP Audit",B=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:Lt(e.artifact_run_filter,18)})]}):null,e.session_id?s.jsxs("span",{className:"chip muted",children:["session ",s.jsx("span",{className:"mono",children:Lt(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:L(S.waiting.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Running"}),s.jsx("strong",{children:L(S.running.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Failed"}),s.jsx("strong",{children:L(S.failed.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsxs("span",{children:["Artifacts",u?" (filtered)":""]}),s.jsx("strong",{children:L(l)})]})]})]}),s.jsx("nav",{className:"runtime_mode_tabs",role:"tablist","aria-label":"System sections",children:["activity","artifacts","memory","logs"].map(A=>s.jsxs("button",{role:"tab","aria-selected":e.tab===A,className:`runtime_mode_tab ${e.tab===A?"active":""}`,onClick:()=>e.on_tab_change(A),children:[s.jsx(Qe,{name:A==="activity"?"history":A==="artifacts"?"download":A==="memory"?"agent":"terminal",size:14}),s.jsx("span",{children:A==="activity"?"Activity":A==="artifacts"?"Artifacts":A==="memory"?"Memory":"Logs"})]},A))}),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(zC,{gateway_connected:e.gateway_connected,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:A=>{T(A),e.on_select_run(A),e.on_tab_change("artifacts")},on_filter_session_artifacts:A=>{A&&(e.on_artifact_run_filter_change(""),e.on_session_filter_change(A),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:A=>e.on_query_change(A.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:A=>{const $=A.target.value;$!=="run"&&e.on_artifact_run_filter_change(""),$==="session"?e.on_session_filter_change(e.session_id):e.on_session_filter_change(""),e.on_scope_change($)},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:A=>e.on_group_by_change(A.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:A=>e.on_sort_by_change(A.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(A=>{const $=o.has(A),z=w[A]||0,E=wC(A);return s.jsxs("button",{type:"button","aria-pressed":$,"aria-label":`${E} artifact type filter. Type filters combine with OR.`,title:`${E}: ${$?"in the filter":"not in the filter"}. Type filters combine with OR.`,className:`artifact_filter_chip ${$?"active":""}`,onClick:()=>x(A),children:[s.jsx("span",{children:E}),s.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?z.toLocaleString():"—"})]},A)}),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(A=>s.jsx("button",{type:"button","aria-pressed":e.date_filter===A.value,className:`artifact_filter_chip ${e.date_filter===A.value?"active":""}`,onClick:()=>e.on_date_filter_change(A.value),children:A.label},A.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:C||Lt(e.artifact_run_filter,18)}),".",s.jsx("button",{className:"btn",onClick:()=>T(""),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 ",xc(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:()=>T(""),children:[s.jsx("strong",{children:"All artifacts"}),s.jsx("span",{children:e.gateway_connected?`${l.toLocaleString()} match${l===1?"":"es"}`:"counts unavailable"})]}),N.map(A=>{const $=String(A.run_id||"").trim(),z=$===e.artifact_run_filter||$===(t==null?void 0:t.run_id);return s.jsxs("button",{className:`artifact_filter_run ${z?"selected":""}`,onClick:()=>T($),title:$,children:[s.jsx("strong",{children:$i(A,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Lt($,15)}),s.jsx("span",{children:Ac(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:l?`${p.toLocaleString()}-${y.toLocaleString()} of ${l.toLocaleString()}`:"0 items"}),s.jsx("div",{className:"pane_spacer"}),f>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:_<=0,children:"First"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(_-1),disabled:_<=0,children:"Prev"}),s.jsxs("span",{className:"muted artifact_page_label",children:["Page ",(_+1).toLocaleString()," / ",f.toLocaleString()]}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(_+1),disabled:_>=f-1,children:"Next"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(f-1),disabled:_>=f-1,children:"Last"})]}):null]}),s.jsxs("div",{className:"pane_body scroll artifact_browser_body",children:[e.artifact_groups.length?null: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."}),s.jsx("div",{className:"artifact_group_list",children:e.artifact_groups.map(A=>s.jsxs("section",{className:"artifact_group",children:[s.jsxs("div",{className:"artifact_group_header",children:[s.jsx("span",{children:A.key}),s.jsx("span",{className:"artifact_group_count",children:A.items.length})]}),A.items.map($=>{var F;const z=$.run_id&&e.run_by_id[$.run_id]||null,E=z?$i(z,e.workflow_label_by_id):Gg($),te=pw($),O=Number(((F=$.access)==null?void 0:F.access_count)||0)||0;return s.jsxs("button",{className:`artifact_row ${(t==null?void 0:t.artifact_id)===$.artifact_id?"selected":""}`,onClick:()=>{e.on_select_artifact($.artifact_id),$.run_id&&e.on_select_run($.run_id)},title:$.artifact_id,children:[s.jsx(yw,{artifact:$,size:18}),s.jsxs("div",{className:"artifact_row_main",children:[s.jsxs("div",{className:"artifact_row_title",children:[s.jsx("strong",{children:_w(qm($,e.run_by_id,e.workflow_label_by_id))}),s.jsx("span",{className:"artifact_type_badge",children:Vu($)}),$.render_kind&&$.render_kind!==$.semantic_kind?s.jsx("span",{className:"artifact_type_badge muted",children:$.render_kind}):null,$.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"})," ",bC($)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Size"})," ",xc($.size_bytes)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Last seen"})," ",mw($)]}),O?s.jsxs("span",{children:[s.jsx("b",{children:"Accesses"})," ",O.toLocaleString()]}):null,te?s.jsxs("span",{children:[s.jsx("b",{children:"Media"})," ",te]}):null,$.content_type?s.jsxs("span",{children:[s.jsx("b",{children:"MIME"})," ",$.content_type]}):null]}),s.jsxs("div",{className:"artifact_row_facts secondary",children:[E?s.jsxs("span",{children:[s.jsx("b",{children:"Workflow"})," ",E]}):null,$.run_id?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Run"})," ",Lt($.run_id,13)]}):null,s.jsxs("span",{children:[s.jsx("b",{children:"Turn"})," ",rg($)]}),Hu($)?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Node"})," ",Hu($)]}):null,If($)?s.jsxs("span",{children:[s.jsx("b",{children:"Source"})," ",If($)]}):null]}),s.jsxs("div",{className:"artifact_row_facts tertiary",children:[s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"ID"})," ",Lt($.artifact_id,22)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Provenance"})," ",fw($)]})]}),gw($)?s.jsx("div",{className:"artifact_row_path mono",children:gw($)}):null]})]},$.artifact_id)})]},A.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?ig(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):ig(t,e.run_by_id,e.workflow_label_by_id)}):null]}),t?s.jsxs(s.Fragment,{children:[(()=>{var F,K,R,Q,Z,X,le;const A=jC(t),$=cb(t),z=pw(t),E=Number(((F=t.access)==null?void 0:F.access_count)||0)||0,te=dn((K=t.links)==null?void 0:K.provider_trace,(R=t.links)==null?void 0:R.provider_trace_url,(Q=t.links)==null?void 0:Q.provider_trace_id),O=dn((Z=t.links)==null?void 0:Z.audit,(X=t.links)==null?void 0:X.audit_tail,(le=t.links)==null?void 0:le.audit_url);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"artifact_detail_header",children:[s.jsx(yw,{artifact:t,size:22}),s.jsxs("div",{children:[s.jsx("div",{className:"artifact_detail_title",children:_w(qm(t,e.run_by_id,e.workflow_label_by_id))}),s.jsxs("div",{className:"artifact_detail_subtitle",children:[Vu(t)," • ",t.render_kind||e.embedded_preview.render_kind||t.modality||"artifact"," • ",t.content_type||"unknown MIME"," • ",xc(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),s.jsx(MC,{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:Vu(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:Ea(t.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Size"}),s.jsx("strong",{children:xc(t.size_bytes)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last seen"}),s.jsx("strong",{children:mw(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Accesses"}),s.jsx("strong",{children:E?E.toLocaleString():"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:t.run_id?Lt(t.run_id,24):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:j?$i(j,e.workflow_label_by_id):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Turn"}),s.jsx("strong",{children:rg(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Hu(t)||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider/model"}),s.jsx("strong",{children:$||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Media facts"}),s.jsx("strong",{children:z||"—"})]}),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:fw(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Artifact id"}),s.jsx("strong",{className:"mono",children:Lt(t.artifact_id,30)})]}),t.sha256?s.jsxs("div",{children:[s.jsx("span",{children:"sha256"}),s.jsx("strong",{className:"mono",children:Lt(t.sha256,30)})]}):null]}),A?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:A})]}):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(mr,{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(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:()=>{te&&window.open(te,"_blank","noopener,noreferrer")},disabled:!te,children:"Open provider trace"}),s.jsx("button",{className:"btn",onClick:()=>{O?window.open(O,"_blank","noopener,noreferrer"):e.on_tab_change("logs")},disabled:!O&&!t.audit_available,children:"Open audit trail"}),s.jsx("button",{className:"btn",onClick:()=>void $c(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(mr,{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:ue}),s.jsx("div",{className:"mono muted",children:B})]}),s.jsxs("div",{className:"actions",style:{marginTop:0},children:[ae&&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:()=>{ae?e.on_refresh_runtime_ledger(e.selected_run_id):e.on_refresh_audit()},disabled:ae?e.runtime_ledger_log_loading:e.audit_log_loading,children:[s.jsx(Qe,{name:"refresh",size:14}),ae?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:A=>e.on_runtime_log_query_change(A.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:P?$i(P,e.workflow_label_by_id):e.selected_run_id?Lt(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Lt(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:P!=null&&P.session_id?Lt(String(P.session_id),28):e.session_id?Lt(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:()=>T(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&&!W.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:W.map(A=>{var Z,X;const $=A.record||{},z=String(((Z=$==null?void 0:$.effect)==null?void 0:Z.type)||"").trim(),E=String(($==null?void 0:$.status)||"").trim(),te=String(($==null?void 0:$.node_id)||"").trim(),O=dn($==null?void 0:$.ended_at,$==null?void 0:$.started_at,$==null?void 0:$.ts),F=no($),K=ub($),R=z?_t(Os(((X=$==null?void 0:$.effect)==null?void 0:X.payload)??{},1200),{max_chars:1200,max_lines:6}):"",Q=Xf($)||(F?`Waiting for ${String(F.reason||"input")}`:"")||(($==null?void 0:$.result)!==void 0?Os($.result,700):"");return s.jsxs("article",{className:`runtime_log_event ${vl(E)}`,children:[s.jsxs("div",{className:"runtime_log_event_header",children:[s.jsxs("span",{className:"mono",children:["#",A.cursor]}),s.jsx(xl,{status:E||"record"}),z?s.jsx("span",{className:"chip mono muted",children:z}):null,te?s.jsx("strong",{className:"mono",children:te}):null,O?s.jsx("span",{className:"mono muted",children:Ea(O)}):null]}),s.jsxs("div",{className:"runtime_log_event_body",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Request / activity"}),s.jsx("p",{children:[K||Nm($),R&&R!=="{}"?R:""].filter(Boolean).join(`
113
+ `)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:_t(Q||"—",{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(mr,{value:$,collapseAfterDepth:3,showCopy:!0})]})]},`${e.selected_run_id}:${A.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:P?$i(P,e.workflow_label_by_id):e.selected_run_id?Lt(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Lt(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:G.length.toLocaleString()}),s.jsx("em",{className:"mono",children:Y?`${Y.toLocaleString()} tokens`:"tokens not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Issues"}),s.jsx("strong",{children:J.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&&!G.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:G.map(A=>s.jsxs("article",{className:`provider_activity ${A.error||A.missing_response?"danger":""}`,children:[s.jsxs("div",{className:"provider_activity_header",children:[s.jsxs("div",{children:[s.jsx("h4",{children:[A.provider||"provider unknown",A.model||"model unknown"].join(" / ")}),s.jsxs("div",{className:"timeline_subtitle",children:[A.node_id?s.jsx("span",{className:"mono",children:A.node_id}):null,A.run_id?s.jsx("span",{className:"mono",children:Lt(A.run_id,16)}):null,s.jsx("span",{children:Ug(A.duration_ms)}),A.status?s.jsx(xl,{status:A.status}):null]})]}),s.jsxs("div",{className:"provider_tokens mono",children:[A.tokens.total?A.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:A.prompt_preview||"No prompt payload captured"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Response / error"}),s.jsx("p",{children:A.response_preview||A.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(mr,{value:A.raw,collapseAfterDepth:3,showCopy:!0})]})]},A.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:re.length?re.join(`
114
+ `):"(audit tail not loaded or no lines match search)"})]})]}):null]})}const lm=30;function UC(e){const[t,n]=m.useState(""),r=Array.isArray(e.wait.choices)?e.wait.choices:[],o=e.wait.allow_free_text!==!1,l=e.disabled===!0,u=String(e.wait.prompt||"").trim();return s.jsxs(s.Fragment,{children:[r.length?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Expected response"}),s.jsxs("select",{className:"mono",value:t,onChange:c=>n(c.target.value),children:[s.jsx("option",{value:"",children:"(select)"}),r.map((c,f)=>s.jsx("option",{value:String(c),children:String(c)},f))]})]}):null,o?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:r.length?"Or type a response":u?"Your answer":"Response to resume this wait"}),s.jsx("textarea",{className:"mono wait_response_input",value:t,onChange:c=>n(c.target.value),placeholder:u?"Type your answer to the request above…":"Type the response the workflow is waiting for…",rows:4})]}):null,s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn primary",disabled:l||!t.trim(),onClick:()=>e.on_submit(t.trim()),children:"Submit response"})})]})}function xw(e,t,n){if(Mf(e)==="automation"){const r=String(e.automation_id||e.run_id||"").trim();return n[r]||"Automation"}return $i(e,t)}function bw(e){const t=Mf(e.run);return t?s.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:Gx(e.run)}):null}function WC(e){const t=e.selected_run_id.trim(),n=e.list?e.list.open:!0,r=e.root_run_id.trim()||t,o=e.sections.reduce((l,u)=>l+u.rows.reduce((c,f)=>{const _=[f.run,...f.children];return c+_.filter(p=>Xu(p.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(Lf,{open:n,on_toggle:e.list.on_toggle,controls:"run_nav_controls run_nav_tree",title:"Runs",count:`${e.total_runs.toLocaleString()} runs • ${o.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 • ",o.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:l=>e.on_search(l.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(l=>s.jsx("button",{className:`seg_btn ${e.filter===l?"active":""}`,onClick:()=>e.on_filter(l),children:l},l))}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:l=>e.on_group_by(l.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?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(l=>s.jsxs("section",{className:"run_tree_section",children:[s.jsxs("div",{className:"run_tree_section_header",children:[s.jsx("span",{children:l.label}),s.jsx("span",{className:"mono",children:l.rows.length})]}),l.rows.map(u=>{const c=u.run,f=String(c.run_id||"").trim(),_=f===t;return s.jsxs("div",{className:"run_tree_group",children:[s.jsxs("button",{className:`run_tree_item ${_?"selected":""} ${f===r?"root_context":""}`,onClick:()=>e.on_select(f,f),title:f,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:xw(c,e.workflow_label_by_id,e.automation_titles)}),s.jsx(bw,{run:c}),c.status?s.jsx(xl,{status:Um(c)}):null]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Lt(f,13)}),s.jsx("span",{children:vc(c)?ka(vc(c)):"no start"}),s.jsx("span",{children:Ac(c)})]})]}),u.children.length?s.jsx("div",{className:"run_tree_children",children:u.children.map(p=>{const y=String(p.run_id||"").trim();return s.jsxs("button",{className:`run_tree_item run_tree_child ${y===t?"selected":""}`,onClick:()=>e.on_select(y,f),title:y,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:xw(p,e.workflow_label_by_id,e.automation_titles)}),s.jsx(bw,{run:p}),s.jsx(xl,{status:Um(p)})]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Lt(y,13)}),s.jsx("span",{children:vc(p)?ka(vc(p)):"child"}),s.jsx("span",{children:Ac(p)})]})]},y)})}):null]},f)})]},l.key))]})]})}function jw(){return s.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.7-.9L9.2 3.9A2 2 0 0 0 7.5 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})})}function qC(e){var C,N,T,L,P,W,G;const t=e.run_id.trim(),[n,r]=m.useState(!1);if(!t)return s.jsx("div",{className:"run_overview",children:s.jsx("div",{className:"empty_state_inline",style:{padding:"48px 24px",textAlign:"center"},children:"Select a run on the left to inspect it — or start one from Launch."})});const o=$i(e.run,e.workflow_label_by_id),l=vc(e.run)||String(((C=e.run_state)==null?void 0:C.started_at)||((N=e.run_state)==null?void 0:N.created_at)||"").trim(),u=Zx(e.run)||(Ri(e.status_label)?String(((T=e.run_state)==null?void 0:T.updated_at)||"").trim():""),c=e.run?Ac(e.run):l?Ug((Nn(u)??Date.now())-(Nn(l)??Date.now())):"—",f=e.provider_activities.length,_=e.provider_activities.reduce((Y,J)=>Y+(Number(J.tokens.total)||0),0),p=e.provider_activities.filter(Y=>Y.missing_response||Y.error).length,y=String(((L=e.latest_summary)==null?void 0:L.text)||"").trim(),w=e.wait_state,x=Ri(e.status_label),S=Wm(e.run)||String(((P=e.run_state)==null?void 0:P.error)||"").trim();let j="";for(let Y=e.records.length-1;Y>=0;Y--){const J=Xf((W=e.records[Y])==null?void 0:W.record);if(J){j=J;break}}return s.jsxs("div",{className:"run_overview",children:[s.jsxs("section",{className:"run_hero run_hero_line",children:[s.jsx("h2",{className:"run_hero_title",title:o,children:o}),s.jsx(xl,{status:e.status_label}),t?s.jsx("span",{className:"chip mono muted",title:t,children:Lt(t,18)}):null,e.root_run_id&&e.root_run_id!==t?s.jsxs("span",{className:"chip mono muted",title:e.root_run_id,children:["root ",Lt(e.root_run_id,12)]}):null,s.jsx("span",{className:"run_hero_spacer"}),e.workspace_root?s.jsxs("button",{className:"btn btn_icon",onClick:e.on_reveal_workspace,title:`Open the run's workspace folder
115
+ ${e.workspace_root}`,children:[s.jsx(jw,{}),"Folder"]}):null,s.jsx("button",{className:"btn",onClick:e.on_generate_summary,disabled:!t||e.summary_generating,children:e.summary_generating?"Summarizing…":y?"Refresh summary":"Summarize"}),s.jsx("button",{className:"btn",onClick:e.on_open_runtime,title:"Open this run's artifacts in the System explorer",children:"Run artifacts"})]}),x?s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Outcome"}),s.jsx("span",{className:`chip mono ${vl(e.status_label)}`,children:e.status_label||(S?"failed":"completed")})]}),S?s.jsx("div",{className:"error_callout",children:S}):null,j?s.jsx(Mi,{text:_t(j,{max_chars:4e3,max_lines:60})}):null,!S&&!j?s.jsx("div",{className:"empty_state_inline",children:"No final text output was recorded for this run — produced files, if any, live under Run artifacts (above)."}):null]}):null,(()=>{const Y=Array.isArray(e.run_artifacts)?e.run_artifacts:[],J=A=>{const $=String((A!=null&&A.tags&&typeof A.tags=="object"?A.tags.source:"")||"").trim();return $==="run_store_offload"||$==="node_trace_offload"},re=A=>{const $=A!=null&&A.tags&&typeof A.tags=="object"?A.tags:{},z=String((A==null?void 0:A.filename)||$.filename||"").trim();if(z)return z;const E=String($.path||(A==null?void 0:A.source_path)||"").trim();return E?E.split("/").pop()||E:String((A==null?void 0:A.title)||"").trim()||String((A==null?void 0:A.artifact_id)||"").slice(0,14)},ae=A=>{var $;return s.jsxs("div",{className:"run_artifact_row",children:[s.jsx("span",{className:"run_artifact_name",title:String((($=A==null?void 0:A.tags)==null?void 0:$.path)||(A==null?void 0:A.source_path)||(A==null?void 0:A.artifact_id)||""),children:re(A)}),s.jsx("span",{className:"chip mono muted",children:String((A==null?void 0:A.content_type)||"?").replace(/^application\//,"").replace(/^text\//,"")}),s.jsx("span",{className:"run_artifact_size",children:typeof(A==null?void 0:A.size_bytes)=="number"?`${(A.size_bytes/1024).toFixed(A.size_bytes>1e5?0:1)} kB`:""}),s.jsxs("span",{className:"run_artifact_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_preview_run_artifact(A),children:"Preview"}),s.jsx("button",{className:"btn",onClick:()=>e.on_download_run_artifact(A),children:"Download"})]})]},String((A==null?void 0:A.artifact_id)||Math.random()))},ue=Y.filter(A=>!J(A)),B=Y.filter(J);return s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Artifacts"}),s.jsx("span",{className:"mono muted",children:Y.length?Y.length.toLocaleString():""}),e.workspace_root?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_reveal_workspace,title:`Open the run's workspace folder
116
+ ${e.workspace_root}`,children:[s.jsx(jw,{}),"Workspace"]})]}):null]}),e.run_artifacts_error?s.jsx("div",{className:"warn_callout",children:e.run_artifacts_error}):null,e.run_artifacts_loading&&!Y.length?s.jsx("div",{className:"empty_state_inline",children:"Loading artifacts…"}):null,!e.run_artifacts_loading&&!Y.length&&!e.run_artifacts_error?s.jsxs("div",{className:"empty_state_inline",children:["The runtime recorded no durable artifacts for this run.",e.workspace_root?" Files written to the workspace folder (if any) are reachable via the Folder button.":""]}):null,ue.length?s.jsx("div",{className:"run_artifact_list",children:ue.map(ae)}):null,!ue.length&&Y.length?s.jsxs("div",{className:"empty_state_inline",children:["No file products — this run's durable artifacts are internal state offloads (below).",e.workspace_root?" Report files written to the workspace are reachable via the Folder button.":""]}):null,B.length?s.jsxs("details",{className:"runtime_raw_details",children:[s.jsxs("summary",{className:"muted",children:["Internal state offloads (",B.length,")"]}),s.jsx("div",{className:"run_artifact_list",children:B.map(ae)})]}):null]})})(),s.jsxs("div",{className:"metric_grid",children:[s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Started"}),s.jsx("strong",{children:Ea(l)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:u?"Finished":"Running for"}),s.jsx("strong",{children:u?Ea(u):c})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Total duration"}),s.jsx("strong",{children:c})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Ledger"}),s.jsx("strong",{children:(e.records_count+e.child_records_count).toLocaleString()})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Subworkflows"}),s.jsx("strong",{children:e.subrun_ids.length.toLocaleString()})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:f.toLocaleString()})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Tokens"}),s.jsx("strong",{children:_?_.toLocaleString():"—"})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Assets"}),s.jsx("strong",{children:e.attachments_count.toLocaleString()})]})]}),s.jsxs("div",{className:"overview_columns",children:[s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:x?"What happened":"What is happening"}),w?s.jsx("span",{className:"chip mono info",children:"waiting"}):null]}),w?s.jsxs("div",{className:"overview_fact_list",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Reason"}),s.jsx("strong",{children:String(w.reason||"unknown")})]}),w.wait_key?s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:Lt(String(w.wait_key),34)})]}):null,(G=w==null?void 0:w.details)!=null&&G.sub_run_id?s.jsxs("div",{children:[s.jsx("span",{children:"Subworkflow"}),s.jsx("strong",{className:"mono",children:Lt(String(w.details.sub_run_id),24)})]}):null,w.prompt?s.jsxs("div",{children:[s.jsx("span",{children:"Prompt"}),s.jsx("strong",{children:_t(String(w.prompt),{max_chars:260,max_lines:3})})]}):null,e.on_answer_wait&&w.wait_key&&String(w.reason||"")==="user"?s.jsx("div",{className:"overview_fact_actions",children:s.jsx("button",{className:"btn primary",onClick:e.on_answer_wait,children:"Review & answer…"})}):null]}):(()=>{var A;const Y=e.timeline_items.length?e.timeline_items[e.timeline_items.length-1]:null,J=(Y==null?void 0:Y.record)||null,re=String((J==null?void 0:J.node_id)||"").trim(),ae=re&&e.node_index?e.node_index[re]:null,ue=String((ae==null?void 0:ae.label)||re||"").trim(),B=String(((A=J==null?void 0:J.effect)==null?void 0:A.type)||"").trim();return ue||B?s.jsxs("div",{className:"overview_fact_list",children:[ue?s.jsxs("div",{children:[s.jsx("span",{children:x?"Ended at":"Last step"}),s.jsx("strong",{children:ue})]}):null,B?s.jsxs("div",{children:[s.jsx("span",{children:"Effect"}),s.jsx("strong",{className:"mono",children:B})]}):null]}):s.jsx("div",{className:"empty_state_inline",children:x?"Nothing in flight — the run is finished.":"No active wait is reported for this run."})})(),p?s.jsxs("div",{className:"warn_callout",children:[p," provider call(s) have missing responses or errors."]}):null]}),s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Summary"}),e.latest_summary?s.jsx("span",{className:"chip mono ok",children:"saved"}):s.jsx("span",{className:"chip mono muted",children:"none"})]}),e.summary_error?s.jsx("div",{className:"warn_callout",children:e.summary_error}):null,y?s.jsx(Mi,{text:y}):s.jsx("div",{className:"empty_state_inline",children:"Generate a grounded summary from the root run and its subflows."})]})]}),e.subrun_ids.length?s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Subworkflows"}),s.jsx("span",{className:"mono muted",children:e.subrun_ids.length})]}),s.jsx("div",{className:"subrun_chip_list",children:e.subrun_ids.map(Y=>s.jsx("button",{className:"subrun_chip mono",onClick:()=>e.on_open_subrun(Y),title:Y,children:Lt(Y,22)},Y))})]}):null,e.attachments.length||e.session_id?s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Session files"}),s.jsx("span",{className:"mono muted",children:e.attachments.length?`${e.attachments.length} file${e.attachments.length===1?"":"s"}`:""}),s.jsx("button",{className:"btn btn_sm",onClick:e.on_refresh_attachments,disabled:e.attachments_loading||!e.session_id,children:e.attachments_loading?"Refreshing…":"Refresh"})]}),e.attachments_error?s.jsx("div",{className:"warn_callout",children:e.attachments_error}):null,e.attachments.length?s.jsx("div",{className:"produced_list",children:e.attachments.map(Y=>{const J=String((Y==null?void 0:Y.artifact_id)||"").trim();if(!J)return null;const re=Y!=null&&Y.tags&&typeof Y.tags=="object"?Y.tags:{},ae=String((re==null?void 0:re.path)||"").trim()?`@${String(re.path).trim()}`:String((re==null?void 0:re.filename)||"").trim()||J,ue=typeof(Y==null?void 0:Y.size_bytes)=="number"?Number(Y.size_bytes):null,B=e.attachments_loading||!e.attachments_ready;return s.jsxs("div",{className:"produced_row",children:[s.jsx("span",{className:"produced_name mono",title:J,children:ae}),s.jsx("span",{className:"mono muted",children:ue!==null?`${ue.toLocaleString()} B`:""}),s.jsxs("span",{className:"produced_actions",children:[s.jsx("button",{className:"btn btn_sm",onClick:()=>e.on_preview_attachment(Y),disabled:B,children:"Preview"}),s.jsx("button",{className:"btn btn_sm",onClick:()=>e.on_download_attachment(Y),disabled:B,children:"Download"})]})]},J)})}):s.jsx("div",{className:"empty_state_inline",children:x?"No files were attached to this run's session.":"No files in this run's session yet."})]}):null,e.timeline_items.length?s.jsxs("section",{className:"overview_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Chronology"}),s.jsx("span",{className:"mono muted",children:n||e.timeline_items.length<=lm?`${e.timeline_items.length} steps`:`last ${lm} of ${e.timeline_items.length} steps`}),e.timeline_items.length>lm?s.jsx("button",{className:"btn btn_sm",onClick:()=>r(Y=>!Y),children:n?"Show fewer":"Show all"}):null]}),s.jsx(HC,{items:n?e.timeline_items:e.timeline_items.slice(-lm),node_index:e.node_index,workflow_label_by_id:e.workflow_label_by_id,on_copy:e.on_copy})]}):null]})}function HC(e){const t=n=>{var N,T;const r=n,o=n.record||{},l=String(((N=o==null?void 0:o.effect)==null?void 0:N.type)||r.effect_type||"").trim(),u=String((o==null?void 0:o.status)||r.status||"").trim(),c=String((o==null?void 0:o.node_id)||r.node_id||"").trim(),f=c&&e.node_index?e.node_index[c]:null,_=String((f==null?void 0:f.label)||c||r.title||"Step").trim(),p=no(o),y=(T=o==null?void 0:o.effect)==null?void 0:T.payload,w=o==null?void 0:o.result,x=Xf(o),S=l?Os(y??{},900):_t(String(r.preview||""),{max_chars:900,max_lines:8}),j=x||(p?`Waiting for ${String(p.reason||"input")}${p.wait_key?` (${Lt(String(p.wait_key),18)})`:""}`:"")||(w!==void 0?Os(w,900):"");return{title:l==="llm_call"?"Model call":l==="tool_calls"?"Tool execution":l==="answer_user"?"User-facing response":l==="start_subworkflow"?"Subworkflow launched":l==="ask_user"?"User input requested":l||r.title||"Ledger event",subtitle:_,request:_t(S,{max_chars:900,max_lines:7}),outcome:_t(j,{max_chars:1100,max_lines:9}),cls:vl(u)}};return s.jsxs("div",{className:"human_timeline",children:[e.items.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger records yet."}),e.items.map(n=>{const r=n.record||{},o=t(n),l=String(r.ended_at||r.started_at||n.ts||"").trim();return s.jsxs("article",{className:`timeline_event ${o.cls}`,children:[s.jsx("div",{className:"timeline_marker"}),s.jsxs("div",{className:"timeline_event_body",children:[s.jsxs("div",{className:"timeline_event_header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:o.title}),s.jsxs("div",{className:"timeline_subtitle",children:[s.jsx("span",{children:o.subtitle}),n.run_id?s.jsx("span",{className:"mono",children:Lt(String(n.run_id),13)}):null]})]}),s.jsxs("div",{className:"timeline_time",children:[s.jsx("span",{children:ka(l)}),s.jsx("span",{className:"mono",title:l,children:Ea(l)})]})]}),s.jsxs("div",{className:"timeline_payload_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Requested"}),s.jsx("p",{className:"mono",children:o.request||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:o.outcome||"—"})]})]}),s.jsx("div",{className:"timeline_actions",children:s.jsxs("button",{className:"btn btn_icon",onClick:()=>e.on_copy(JSON.stringify(r,null,2)),children:[s.jsx(Qe,{name:"copy",size:14}),"JSON"]})})]})]},`${String(n.run_id||r.run_id||"")}:${n.cursor}`)})]})}function VC(e){const t=e.item,n=String(t.node_id||"").trim(),r=n&&e.node_index&&typeof e.node_index=="object"?e.node_index[n]:null,o=typeof(r==null?void 0:r.label)=="string"&&r.label.trim()?r.label.trim():n||t.title,l=typeof(r==null?void 0:r.type)=="string"&&r.type.trim()?r.type.trim():"",u=typeof(r==null?void 0:r.headerColor)=="string"&&r.headerColor.trim()?r.headerColor.trim():"",c=t.kind==="step"?o:t.title,f=u||(t.kind==="error"?"rgba(239, 68, 68, 0.85)":t.kind==="message"?"rgba(167, 139, 250, 0.85)":t.kind==="event"?"rgba(96, 165, 250, 0.85)":t.status==="waiting"?"rgba(96, 165, 250, 0.65)":t.status==="completed"?"rgba(34, 197, 94, 0.65)":"rgba(255, 255, 255, 0.14)"),_=String(t.status||"").trim(),p=_.toLowerCase(),y=vl(p),w=Xf(t.data),x=!!(w&&w.trim()),S=ka(t.ts);return s.jsxs("div",{className:`lc ${y}`,style:{"--lc-accent":f},children:[s.jsxs("div",{className:"lc_header",children:[s.jsx("span",{className:"lc_title",children:c}),s.jsxs("div",{className:"lc_header_right",children:[_?s.jsx("span",{className:`lc_status ${y}`,children:_}):null,s.jsx("span",{className:"lc_time",title:t.ts,children:S})]})]}),s.jsxs("div",{className:"lc_meta",children:[l?s.jsx("span",{className:"lc_chip",children:l}):null,t.effect_type?s.jsx("span",{className:"lc_chip",children:String(t.effect_type)}):null,t.cursor?s.jsxs("span",{className:"lc_chip",children:["#",t.cursor]}):null,t.run_id?s.jsx("span",{className:"lc_chip",children:Lt(String(t.run_id),10)}):null,t.kind!=="step"&&n?s.jsx("span",{className:"lc_chip",children:n}):null]}),t.preview?s.jsx("div",{className:"lc_preview",children:t.preview}):null,t.data?s.jsxs("div",{className:"lc_actions",children:[x?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"lc_btn",onClick:e.on_toggle_response,children:e.response_open?"Fold Response":"Unfold Response"}),s.jsx("button",{className:"lc_btn",onClick:()=>e.on_copy(String(w||"")),children:"Copy Response"})]}):null,s.jsx("button",{className:"lc_btn",onClick:e.on_toggle,children:e.open?"Fold JSON":"Unfold JSON"}),s.jsx("button",{className:"lc_btn",onClick:()=>{try{e.on_copy(JSON.stringify(t.data,null,2))}catch{e.on_copy(String(t.data))}},children:"Copy JSON"})]}):null,e.response_open&&x?s.jsx("div",{className:"lc_body",children:s.jsx(Mi,{text:String(w||"")})}):null,e.open&&t.data?s.jsx("div",{className:"lc_body lc_body_json mono",children:s.jsx(mr,{value:t.data,collapseAfterDepth:3,showCopy:!1})}):null]})}class GC{constructor(){Xs(this,"_buffer","");Xs(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const r=this._buffer.indexOf(`
117
+ `);if(r===-1)return;const o=this._buffer.slice(0,r);this._buffer=this._buffer.slice(r+1);const l=o.endsWith("\r")?o.slice(0,-1):o;if(l.startsWith(":"))continue;if(l===""){if(this._current.data_lines.length>0||this._current.event||this._current.id){const _={id:this._current.id,event:this._current.event,data:this._current.data_lines.join(`
118
+ `)};n(_)}this._current={data_lines:[]};continue}const u=l.indexOf(":"),c=u===-1?l:l.slice(0,u),f=u===-1?"":l.slice(u+1).trimStart();if(c==="id"){this._current.id=f;continue}if(c==="event"){this._current.event=f;continue}if(c==="data"){this._current.data_lines.push(f);continue}}}}const Dt=Uv;function Ei(e,t=3e4){const n=AbortSignal.timeout(t);if(!e)return n;const r=AbortSignal.any;return typeof r=="function"?r([e,n]):e}function pb(){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 Rt(e){const t=(e||"").trim(),n={};return t&&(n.Authorization=`Bearer ${t}`),{...n,...pb()}}async function Kn(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class KC extends Error{constructor(n,r){super(r);Xs(this,"status");this.name="GatewayRequestError",this.status=n}}async function cm(e,t){let n="";try{n=(await e.text()).trim()}catch{n=""}let r=n;try{const o=JSON.parse(n),l=o&&typeof o=="object"?o.detail:void 0;typeof l=="string"&&l.trim()?r=l.trim():l&&typeof l=="object"&&typeof l.message=="string"&&l.message.trim()&&(r=l.message.trim())}catch{}return new KC(e.status,`${t} (HTTP ${e.status}): ${r||e.statusText||"no reason given"}`)}class up{constructor(t){Xs(this,"_cfg");Xs(this,"fetch_gateway",(t,n)=>fetch(Dt(this._cfg.base_url,t),{...n,headers:{...n==null?void 0:n.headers,...Rt(this._cfg.auth_token)}}));this._cfg={...t,base_url:(t.base_url||"").trim()}}async start_run(t,n,r){const o=String((r==null?void 0:r.bundle_id)||"").trim(),l=(r==null?void 0:r.session_id)===null||(r==null?void 0:r.session_id)===void 0?"":String(r.session_id||"").trim(),u=String(t||"").trim(),c=String((r==null?void 0:r.interface)||"").trim();if(u==="@default"&&(!c||o))throw new Error("start_run: flow_id '@default' needs `interface` and no bundle_id");const f={input_data:n||{}};o&&(f.bundle_id=o),u&&(f.flow_id=u),u==="@default"&&(f.interface=c),l&&(f.session_id=l);const _=await fetch(Dt(this._cfg.base_url,bt("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...Rt(this._cfg.auth_token)},body:JSON.stringify(f)});if(!_.ok)throw new Error(`start_run failed: ${_.status}`);const p=await _.json(),y=p==null?void 0:p.run_id;if(typeof y!="string"||!y)throw new Error("start_run: missing run_id");return y}async list_mcp_servers(){for(const t of[bt("mcp/servers"),bt("mcp"),bt("discovery/mcp")])try{const n=await fetch(Dt(this._cfg.base_url,t),{headers:{...Rt(this._cfg.auth_token)},signal:Ei()});if(n.status===404||!n.ok)continue;const r=await n.json(),o=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(!o)continue;return o.map(l=>({name:String((l==null?void 0:l.name)||(l==null?void 0:l.id)||"").trim(),url:typeof(l==null?void 0:l.url)=="string"?l.url:void 0,description:typeof(l==null?void 0:l.description)=="string"?l.description:void 0,auth_required:typeof(l==null?void 0:l.auth_required)=="boolean"?l.auth_required:void 0})).filter(l=>l.name)}catch{return null}return null}async list_skills(){for(const t of[bt("skills"),bt("skills/registry")])try{const n=await fetch(Dt(this._cfg.base_url,t),{headers:{...Rt(this._cfg.auth_token)},signal:Ei()});if(n.status===404||!n.ok)continue;const r=await n.json(),o=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(!o)continue;return o.map(l=>({name:String((l==null?void 0:l.name)||(l==null?void 0:l.id)||"").trim(),description:typeof(l==null?void 0:l.description)=="string"?l.description:void 0,version:typeof(l==null?void 0:l.version)=="string"?l.version:void 0,trust_level:typeof(l==null?void 0:l.trust_level)=="string"?l.trust_level:void 0,blocked:typeof(l==null?void 0:l.blocked)=="boolean"?l.blocked:void 0,requires_review:typeof(l==null?void 0:l.requires_review)=="boolean"?l.requires_review:void 0,tree_hash:typeof(l==null?void 0:l.tree_hash)=="string"?l.tree_hash:void 0,reasons:Array.isArray(l==null?void 0:l.reasons)?l.reasons.map(u=>String(u||"")).filter(Boolean):void 0})).filter(l=>l.name)}catch{return null}return null}async get_run(t){const n=await fetch(Dt(this._cfg.base_url,bt(`runs/${encodeURIComponent(t)}`)),{headers:{...Rt(this._cfg.auth_token)}});if(!n.ok)throw new Error(`get_run failed: ${await Kn(n)}`);return await n.json()}async find_run(t){const n=await fetch(Dt(this._cfg.base_url,bt(`runs/${encodeURIComponent(t)}`)),{headers:{...Rt(this._cfg.auth_token)}});if(n.status===404||n.status===403)return null;if(!n.ok)throw await cm(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 o=new URLSearchParams;(n==null?void 0:n.include_subruns)===!1&&o.set("include_subruns","false"),(n==null?void 0:n.include_session)===!0&&o.set("include_session","true"),typeof(n==null?void 0:n.session_turn_limit)=="number"&&Number.isFinite(n.session_turn_limit)&&o.set("session_turn_limit",String(Math.max(1,Math.trunc(n.session_turn_limit)))),n!=null&&n.ledger_mode&&o.set("ledger_mode",String(n.ledger_mode)),typeof(n==null?void 0:n.ledger_max_items)=="number"&&Number.isFinite(n.ledger_max_items)&&o.set("ledger_max_items",String(Math.max(0,Math.trunc(n.ledger_max_items))));const l=Dt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/history_bundle?${o.toString()}`)),u=await fetch(l,{headers:{...Rt(this._cfg.auth_token)}});if(!u.ok)throw new Error(`get_run_history_bundle failed: ${await Kn(u)}`);return await u.json()}async list_runs(t){const n=typeof(t==null?void 0:t.limit)=="number"?t.limit:50,r=String((t==null?void 0:t.status)||"").trim(),o=String((t==null?void 0:t.workflow_id)||"").trim(),l=String((t==null?void 0:t.session_id)||"").trim(),u=(t==null?void 0:t.root_only)===!0,c=new URLSearchParams;c.set("limit",String(n)),r&&c.set("status",r),o&&c.set("workflow_id",o),l&&c.set("session_id",l),u&&c.set("root_only","true"),typeof(t==null?void 0:t.include_ledger_len)=="boolean"&&c.set("include_ledger_len",String(t.include_ledger_len)),typeof(t==null?void 0:t.include_metrics)=="boolean"&&c.set("include_metrics",String(t.include_metrics)),typeof(t==null?void 0:t.include_drafts)=="boolean"&&c.set("include_drafts",String(t.include_drafts));const f=Dt(this._cfg.base_url,bt(`runs?${c.toString()}`)),_=await fetch(f,{headers:{...Rt(this._cfg.auth_token)},signal:AbortSignal.timeout(3e4)});if(!_.ok)throw new Error(`list_runs failed: ${await Kn(_)}`);return await _.json()}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=Dt(this._cfg.base_url,bt(`audit/tail?max_bytes=${encodeURIComponent(String(n))}`)),o=await fetch(r,{headers:{...Rt(this._cfg.auth_token)}});if(!o.ok)throw new Error(`audit_log_tail failed: ${await Kn(o)}`);return await o.json()}async gateway_about(){const t=await fetch(Dt(this._cfg.base_url,bt("about")),{headers:{...Rt(this._cfg.auth_token)},signal:Ei(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 fetch(Dt(this._cfg.base_url,bt(`runs/${encodeURIComponent(n)}/input_data`)),{headers:{...Rt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_run_input_data failed: ${await Kn(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 o=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,l=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,u=Dt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),c=await fetch(u,{headers:{...Rt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_run_artifacts failed: ${await Kn(c)}`);return await c.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 o=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,l=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,u=Dt(this._cfg.base_url,bt(`sessions/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),c=await fetch(u,{headers:{...Rt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_session_artifacts failed: ${await Kn(c)}`);return await c.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(),o=String((t==null?void 0:t.run_id)||"").trim(),l=String((t==null?void 0:t.modality)||"").trim(),u=String((t==null?void 0:t.artifact_kind)||"").trim(),c=String((t==null?void 0:t.semantic_kind)||"").trim(),f=String((t==null?void 0:t.render_kind)||"").trim(),_=String((t==null?void 0:t.workflow_id)||"").trim(),p=String((t==null?void 0:t.node_id)||"").trim(),y=String((t==null?void 0:t.content_type)||"").trim(),w=String((t==null?void 0:t.query)||"").trim(),x=String((t==null?void 0:t.tags)||"").trim(),S=String((t==null?void 0:t.cursor)||"").trim(),j=String((t==null?void 0:t.order_by)||"").trim(),C=String((t==null?void 0:t.order)||"").trim(),N=String((t==null?void 0:t.created_after)||"").trim(),T=String((t==null?void 0:t.created_before)||"").trim(),L=typeof(t==null?void 0:t.limit)=="number"?t.limit:500,P=typeof(t==null?void 0:t.offset)=="number"?Math.max(0,Math.floor(t.offset)):0;r&&n.set("session_id",r),o&&n.set("run_id",o),l&&n.set("modality",l),u&&n.set("artifact_kind",u),c&&n.set("semantic_kind",c),f&&n.set("render_kind",f),_&&n.set("workflow_id",_),p&&n.set("node_id",p),y&&n.set("content_type",y),w&&n.set("query",w),x&&n.set("tags",x),S&&n.set("cursor",S),j&&n.set("order_by",j),C&&n.set("order",C),N&&n.set("created_after",N),T&&n.set("created_before",T),t!=null&&t.include_stats&&n.set("include_stats","true"),n.set("limit",String(L)),n.set("offset",String(P));const W=await fetch(Dt(this._cfg.base_url,bt(`artifacts/search?${n.toString()}`)),{headers:{...Rt(this._cfg.auth_token)}});if(!W.ok)throw new Error(`search_artifacts failed: ${await Kn(W)}`);return await W.json()}async artifact_stats(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");for(const o of["session_id","run_id","modality","semantic_kind","render_kind","workflow_id","node_id","content_type","query","tags","created_after","created_before"]){const l=String((t==null?void 0:t[o])||"").trim();l&&n.set(o,l)}const r=await fetch(Dt(this._cfg.base_url,bt(`artifacts/stats?${n.toString()}`)),{headers:{...Rt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`artifact_stats failed: ${await Kn(r)}`);return await r.json()}async download_run_artifact_content(t,n,r){const o=String(t||"").trim(),l=String(n||"").trim();if(!o)throw new Error("download_run_artifact_content: run_id is required");if(!l)throw new Error("download_run_artifact_content: artifact_id is required");const u=String((r==null?void 0:r.access)||"").trim(),c=u?`?access=${encodeURIComponent(u)}`:"",f=Dt(this._cfg.base_url,bt(`runs/${encodeURIComponent(o)}/artifacts/${encodeURIComponent(l)}/content${c}`)),_=await fetch(f,{headers:{...Rt(this._cfg.auth_token)}});if(!_.ok)throw new Error(`download_run_artifact_content failed: ${await Kn(_)}`);return await _.blob()}async list_entities(){const t=await fetch(Dt(this._cfg.base_url,bt("entities")),{headers:{...Rt(this._cfg.auth_token)},signal:Ei()});if(!t.ok)throw new Error(`list_entities failed: ${await Kn(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 fetch(Dt(this._cfg.base_url,bt("entities/spec/phases")),{headers:{...Rt(this._cfg.auth_token)},signal:Ei()});if(!t.ok)throw new Error(`get_entity_phases_spec failed: ${await Kn(t)}`);return await t.json()}async get_entity_cognition(t){const n=await fetch(Dt(this._cfg.base_url,bt(`entities/${encodeURIComponent(t)}/cognition`)),{headers:{...Rt(this._cfg.auth_token)},signal:Ei()});if(!n.ok)throw new Error(`get_entity_cognition failed: ${await Kn(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 fetch(Dt(this._cfg.base_url,bt(`entities/${encodeURIComponent(n)}/card`)),{headers:{...Rt(this._cfg.auth_token)},signal:Ei()});if(!r.ok)throw new Error(`get_entity_card failed: ${await Kn(r)}`);return await r.json()}async read_entity_diary_entry(t,n){const r=String(t||"").trim(),o=String(n||"").trim();if(!r||!o)throw new Error("read_entity_diary_entry: name and entry_id are required");const l=Dt(this._cfg.base_url,bt(`entities/${encodeURIComponent(r)}/diary/${encodeURIComponent(o)}?reason=${encodeURIComponent("observer board hint chip")}`)),u=await fetch(l,{headers:{...Rt(this._cfg.auth_token)},signal:Ei()});if(!u.ok)throw new Error(`read_entity_diary_entry failed: ${await Kn(u)}`);return await u.json()}async get_ledger(t,n){const r=Number((n==null?void 0:n.after)||0),o=Number((n==null?void 0:n.limit)||0),l=Dt(this._cfg.base_url,bt(`runs/${encodeURIComponent(t)}/ledger?after=${encodeURIComponent(String(r))}&limit=${encodeURIComponent(String(o))}`)),u=await fetch(l,{headers:{...Rt(this._cfg.auth_token)},signal:Ei(n==null?void 0:n.signal)});if(!u.ok)throw new Error(`get_ledger failed: ${u.status}`);const c=await u.json(),f=Array.isArray(c==null?void 0:c.items)?c.items:[],_=typeof(c==null?void 0:c.next_after)=="number"?c.next_after:r;return{items:f,next_after:_}}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),o=await fetch(Dt(this._cfg.base_url,bt("runs/ledger/batch")),{method:"POST",headers:{"Content-Type":"application/json",...Rt(this._cfg.auth_token)},body:JSON.stringify({runs:n,limit:r}),signal:Ei()});if(!o.ok)throw new Error(`get_ledger_batch failed: ${o.status}`);const l=await o.json(),c=(l&&typeof l=="object"?l:{}).runs;return{runs:c&&typeof c=="object"?c:{}}}async generate_run_summary(t,n){const r=String(t||"").trim();if(!r)throw new Error("generate_run_summary: run_id is required");const o={include_subruns:(n==null?void 0:n.include_subruns)!==!1},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(o.provider=l);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(o.model=u);const c=await fetch(Dt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/summary`)),{method:"POST",headers:{"Content-Type":"application/json",...Rt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await cm(c,"The gateway could not summarize this run");return await c.json()}async run_chat(t,n){const r=String(t||"").trim();if(!r)throw new Error("run_chat: run_id is required");const o={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)},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(o.provider=l);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(o.model=u);const c=await fetch(Dt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/chat`)),{method:"POST",headers:{"Content-Type":"application/json",...Rt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await cm(c,"The gateway could not answer");return await c.json()}async audio_transcribe(t,n){const r=String(t||"").trim();if(!r)throw new Error("audio_transcribe: run_id is required");const o=n==null?void 0:n.audio_artifact;if(!o||typeof o!="object")throw new Error("audio_transcribe: audio_artifact is required");if(!String(o.$artifact||"").trim())throw new Error("audio_transcribe: audio_artifact.$artifact is required");const u={audio_artifact:o},c=String((n==null?void 0:n.language)||"").trim();c&&(u.language=c);const f=String((n==null?void 0:n.request_id)||"").trim();f&&(u.request_id=f);const _=await fetch(Dt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...Rt(this._cfg.auth_token)},body:JSON.stringify(u)});if(!_.ok)throw new Error(`audio_transcribe failed: ${await Kn(_)}`);const p=await _.json(),y=String((p==null?void 0:p.text)||"");return{ok:!!(p!=null&&p.ok),run_id:String((p==null?void 0:p.run_id)||""),request_id:String((p==null?void 0:p.request_id)||""),text:y,transcript_artifact:p==null?void 0:p.transcript_artifact}}async voice_tts(t,n){const r=String(t||"").trim();if(!r)throw new Error("voice_tts: run_id is required");const o=String((n==null?void 0:n.text)||"").trim();if(!o)throw new Error("voice_tts: text is required");const l={text:o},u=String((n==null?void 0:n.voice)||"").trim();u&&(l.voice=u);const c=String((n==null?void 0:n.format)||"").trim();c&&(l.format=c);const f=String((n==null?void 0:n.request_id)||"").trim();f&&(l.request_id=f);const _=await fetch(Dt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/voice/tts`)),{method:"POST",headers:{"Content-Type":"application/json",...Rt(this._cfg.auth_token)},body:JSON.stringify(l)});if(!_.ok)throw new Error(`voice_tts failed: ${await Kn(_)}`);const p=await _.json();return{ok:!!(p!=null&&p.ok),run_id:String((p==null?void 0:p.run_id)||""),request_id:String((p==null?void 0:p.request_id)||""),audio_artifact:p==null?void 0:p.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 o={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[]},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(o.provider=l);const u=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";u&&(o.model=u);const c=typeof(n==null?void 0:n.title)=="string"?String(n.title).trim():"";c&&(o.title=c);const f=await fetch(Dt(this._cfg.base_url,bt(`runs/${encodeURIComponent(r)}/chat_threads`)),{method:"POST",headers:{"Content-Type":"application/json",...Rt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!f.ok)throw new Error(`save_chat_thread failed: ${await Kn(f)}`);return await f.json()}async list_bundles(){const t=await fetch(Dt(this._cfg.base_url,bt("bundles")),{headers:{...Rt(this._cfg.auth_token)},signal:Ei()});if(!t.ok)throw new Error(`list_bundles failed: ${t.status}`);return await t.json()}async reload_bundles(){const t=await fetch(Dt(this._cfg.base_url,bt("bundles/reload")),{method:"POST",headers:{...Rt(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,o=(n==null?void 0:n.reload)!==!1,l=new FormData;l.set("overwrite",r?"true":"false"),l.set("reload",o?"true":"false"),l.set("file",t,t.name||"upload.flow");const u=await fetch(Dt(this._cfg.base_url,bt("bundles/upload")),{method:"POST",headers:{...Rt(this._cfg.auth_token)},body:l});if(!u.ok)throw new Error(`upload_bundle failed: ${await Kn(u)}`);return await u.json()}async attachments_upload(t,n,r){const o=String(t||"").trim();if(!o)throw new Error("attachments_upload: session_id is required");if(!n)throw new Error("attachments_upload: file is required");const l=String((r==null?void 0:r.filename)||"").trim()||String((n==null?void 0:n.name)||"").trim()||"upload.bin",u=String((r==null?void 0:r.content_type)||"").trim()||String((n==null?void 0:n.type)||"").trim(),c=new FormData;c.append("session_id",o),c.append("file",n,l),c.append("filename",l),u&&c.append("content_type",u);const f=await fetch(Dt(this._cfg.base_url,bt("attachments/upload")),{method:"POST",headers:{...Rt(this._cfg.auth_token)},body:c});if(!f.ok)throw new Error(`attachments_upload failed: ${await Kn(f)}`);const _=await f.json(),p=_==null?void 0:_.attachment;if(!p||typeof p!="object")throw new Error("attachments_upload: missing attachment");if(!String(p.$artifact||"").trim())throw new Error("attachments_upload: missing attachment.$artifact");return p}async remove_bundle(t,n){const r=String(t||"").trim();if(!r)throw new Error("remove_bundle: bundle_id is required");const o=new URLSearchParams,l=String((n==null?void 0:n.bundle_version)||"").trim();l&&o.set("bundle_version",l),o.set("reload",(n==null?void 0:n.reload)===!1?"false":"true");const u=Dt(this._cfg.base_url,bt(`bundles/${encodeURIComponent(r)}?${o.toString()}`)),c=await fetch(u,{method:"DELETE",headers:{...Rt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`remove_bundle failed: ${await Kn(c)}`);return await c.json()}async discovery_tools(){const t=await fetch(Dt(this._cfg.base_url,bt("discovery/tools")),{headers:{...Rt(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=Dt(this._cfg.base_url,bt(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),o=await fetch(r,{headers:{...Rt(this._cfg.auth_token)}});if(!o.ok)throw new Error(`discovery_providers failed: ${o.status}`);return await o.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 fetch(Dt(this._cfg.base_url,bt(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...Rt(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 fetch(Dt(this._cfg.base_url,bt(`bundles/${encodeURIComponent(n)}`)),{headers:{...Rt(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(),o=String(n||"").trim();if(!r)throw new Error("get_bundle_flow: bundle_id is required");if(!o)throw new Error("get_bundle_flow: flow_id is required");const l=await fetch(Dt(this._cfg.base_url,bt(`bundles/${encodeURIComponent(r)}/flows/${encodeURIComponent(o)}`)),{headers:{...Rt(this._cfg.auth_token)}});if(!l.ok)throw new Error(`get_bundle_flow failed: ${l.status}`);return await l.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 fetch(Dt(this._cfg.base_url,bt(`workflows/${encodeURIComponent(n)}/flow`)),{headers:{...Rt(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 fetch(Dt(this._cfg.base_url,bt("discovery/capabilities")),{headers:{...Rt(this._cfg.auth_token)},signal:Ei()});if(!t.ok)throw new Error(`discovery_capabilities failed: ${await Kn(t)}`);return await t.json()}automations_client(){const t=this._cfg.auth_token;return uS({fetch:(n,r)=>fetch(n,r),baseUrl:this._cfg.base_url,headers:()=>Rt(t)})}async submit_command(t){const n=await fetch(Dt(this._cfg.base_url,bt("commands")),{method:"POST",headers:{"Content-Type":"application/json",...Rt(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(),o=typeof(t==null?void 0:t.limit)=="number"&&Number.isFinite(t.limit)?Number(t.limit):500,l={scope:n,order:r,limit:o},u=String((t==null?void 0:t.run_id)||"").trim();u&&(l.run_id=u);const c=String((t==null?void 0:t.session_id)||"").trim();c&&(l.session_id=c);const f=String((t==null?void 0:t.owner_id)||"").trim();f&&(l.owner_id=f),t!=null&&t.all_owners&&(l.all_owners=!0);const _=String((t==null?void 0:t.subject)||"").trim();_&&(l.subject=_);const p=String((t==null?void 0:t.predicate)||"").trim();p&&(l.predicate=p);const y=String((t==null?void 0:t.object)||"").trim();y&&(l.object=y);const w=String((t==null?void 0:t.since)||"").trim();w&&(l.since=w);const x=String((t==null?void 0:t.until)||"").trim();x&&(l.until=x);const S=String((t==null?void 0:t.active_at)||"").trim();S&&(l.active_at=S);const j=String((t==null?void 0:t.query_text)||"").trim();j&&(l.query_text=j),typeof(t==null?void 0:t.min_score)=="number"&&Number.isFinite(t.min_score)&&(l.min_score=Number(t.min_score));const C=await fetch(Dt(this._cfg.base_url,bt("kg/query")),{method:"POST",headers:{"Content-Type":"application/json",...Rt(this._cfg.auth_token)},body:JSON.stringify(l)});if(!C.ok)throw new Error(`kg_query failed: ${await Kn(C)}`);return await C.json()}async stream_ledger(t,n){var y;const r=Number((n==null?void 0:n.after)||0),o=n.on_step,l=n.signal,u=Dt(this._cfg.base_url,bt(`runs/${encodeURIComponent(t)}/ledger/stream?after=${encodeURIComponent(String(r))}`)),c=await fetch(u,{headers:{Accept:"text/event-stream",...Rt(this._cfg.auth_token)},signal:l});if(!c.ok)throw await cm(c,"The ledger stream was refused");if(!c.body)throw new Error("stream_ledger: response body is missing");(y=n.on_open)==null||y.call(n);const f=c.body.getReader(),_=new TextDecoder("utf-8"),p=new GC;for(;;){const{value:w,done:x}=await f.read();if(x)return;const S=_.decode(w,{stream:!0});p.push(S,j=>{if(!(j.event!=="step"||!j.data))try{const C=JSON.parse(j.data);C&&typeof C.cursor=="number"&&C.record&&o(C)}catch{}})}}}const og=Oj("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).",YC="Copy failed — select and copy";function ag(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function JC(e){var o;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{(o=r==null?void 0:r.focus)==null||o.call(r)}catch{}}}async function XC(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 JC(t)}const ZC=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 QC(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 o=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),l=new Uint32Array(64),u=(c,f)=>c>>>f|c<<32-f;for(let c=0;c<n.length;c+=64){for(let C=0;C<16;C++)l[C]=r.getUint32(c+C*4,!1);for(let C=16;C<64;C++){const N=u(l[C-15],7)^u(l[C-15],18)^l[C-15]>>>3,T=u(l[C-2],17)^u(l[C-2],19)^l[C-2]>>>10;l[C]=l[C-16]+N+l[C-7]+T>>>0}let[f,_,p,y,w,x,S,j]=[o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7]];for(let C=0;C<64;C++){const N=u(w,6)^u(w,11)^u(w,25),T=w&x^~w&S,L=j+N+T+ZC[C]+l[C]>>>0,P=u(f,2)^u(f,13)^u(f,22),W=f&_^f&p^_&p,G=P+W>>>0;j=S,S=x,x=w,w=y+L>>>0,y=p,p=_,_=f,f=L+G>>>0}o[0]=o[0]+f>>>0,o[1]=o[1]+_>>>0,o[2]=o[2]+p>>>0,o[3]=o[3]+y>>>0,o[4]=o[4]+w>>>0,o[5]=o[5]+x>>>0,o[6]=o[6]+S>>>0,o[7]=o[7]+j>>>0}return Array.from(o,c=>c.toString(16).padStart(8,"0")).join("")}async function eE(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 o=await n.digest("SHA-256",t);return Array.from(new Uint8Array(o),l=>l.toString(16).padStart(2,"0")).join("")}return QC(t)}function tE(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class nE{constructor(t){Xs(this,"_cfg");this._cfg={...t,url:(t.url||"").trim()}}async call_tool(t){const n=String((t==null?void 0:t.name)||"").trim(),r=String((t==null?void 0:t.call_id)||(t==null?void 0:t.id)||xs()),o=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 l={jsonrpc:"2.0",id:xs(),method:"tools/call",params:{name:n,arguments:o}},u=await fetch(this._cfg.url,{method:"POST",headers:{"Content-Type":"application/json",...tE(this._cfg.auth_token)},body:JSON.stringify(l)});if(!u.ok)return{call_id:r,name:n,success:!1,output:null,error:`Worker HTTP ${u.status}`};const c=await u.json().catch(()=>null),f=c==null?void 0:c.result,_=!!(f!=null&&f.isError),y=(Array.isArray(f==null?void 0:f.content)?f.content:[]).find(x=>x&&x.type==="text"&&typeof x.text=="string"),w=(y==null?void 0:y.text)??"";return _?{call_id:r,name:n,success:!1,output:null,error:w||"Tool failed"}:{call_id:r,name:n,success:!0,output:w,error:null}}}class Sw{constructor(t,n){Xs(this,"pending",[]);Xs(this,"scheduled",!1);Xs(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 kw(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 sE(e,t){const n=Nn(e.updated_at||e.created_at)??0;return(Nn(t.updated_at||t.created_at)??0)-n}function rE(e,t){const n=t.query.trim().toLowerCase(),r=[...e],o={};for(const w of r){const x=String(w.run_id||"").trim();x&&(o[x]=w)}for(const w of e){const x=kw(w);if(String(w.role||"")==="occurrence"&&x&&!o[x]){const S={run_id:x,workflow_id:null,status:"",role:"controller",session_kind:"automation",automation_id:x,updated_at:w.updated_at??null,created_at:w.created_at??null};o[x]=S,r.push(S)}}const l={},u={};for(const w of r){const x=String(w.run_id||"").trim();if(!x)continue;const S=kw(w,t.parent_hint?t.parent_hint(x):"");u[x]=S,S&&(l[S]||(l[S]=[])).push(w)}const c=w=>{const x=String(w.status||"").trim().toLowerCase();return t.filter==="all"?!0:t.filter==="active"?Xu(x):t.filter==="waiting"?x==="waiting":t.filter==="terminal"?Ri(x):t.filter==="failed"?x==="failed":!0},f=w=>{if(!n)return!0;const x=String(w.workflow_id||w.schedule_target_workflow_id||"").trim(),S=x?t.workflow_label_by_id[x]||x:"";return[w.run_id,x,S,w.session_id,w.status,w.session_kind,w.automation_id].join(" ").toLowerCase().includes(n)},_=[];for(const w of r){const x=String(w.run_id||"").trim();if(!x)continue;const S=u[x];(!S||!o[S])&&_.push(x)}const p={},y=w=>{if(t.group_by==="workflow"){const S=String(w.schedule_target_workflow_id||w.workflow_id||"").trim()||"(unknown workflow)";return{key:S,label:t.workflow_label_by_id[S]||S}}if(t.group_by==="session"){const S=String(w.session_id||"").trim()||"(no session)";return{key:S,label:S}}const x=String(w.status||"").trim().toLowerCase()||"unknown";return Xu(x)?{key:"active",label:"Active"}:x==="failed"?{key:"failed",label:"Failed"}:Ri(x)?{key:"finished",label:"Finished"}:{key:x,label:x}};for(const w of _){const x=o[w];if(!x)continue;const S=[...l[w]||[]].sort(sE),j=S.some(N=>c(N)&&f(N));if(!(c(x)&&f(x))&&!j)continue;const C=y(x);p[C.key]||(p[C.key]={key:C.key,label:C.label,rows:[]}),p[C.key].rows.push({run:x,children:S})}return Object.values(p).sort((w,x)=>{const S={active:0,waiting:1,failed:2,finished:3},j=S[w.key]??10,C=S[x.key]??10;return j!==C?j-C:w.label.localeCompare(x.label)})}const iE={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"},oE=[{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 aE(){const[e,t]=m.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:[oE.map(n=>s.jsxs("div",{className:"pin-legend-row",children:[s.jsx("span",{className:"pin-legend-shape",style:{color:iE[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[])'})]})]})]})]})}function ln(e){return typeof e=="string"?e:e==null?"":String(e)}function Nw(e,t){const n=ln(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function gb(e){const t=ln(e==null?void 0:e.targetHandle),n=ln(e==null?void 0:e.sourceHandle);return!!(t==="exec-in"||n==="exec-out"||t.includes("exec")||n.includes("exec"))}function yb(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{};return ln((t==null?void 0:t.nodeType)||(e==null?void 0:e.type)||"").trim()}function wb(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=ln(n).trim();if(!r)return"";if(r.includes(":")){const o=r.split(":",2);if(o.length===2&&o[1])return o[1].trim()}return r}function lE(e){const t=ln(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(yb(r)==="on_flow_start"){const o=ln(r==null?void 0:r.id).trim();if(o)return o}return""}function dp(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 pf(e,t){const n=ln(e).trim(),r=ln(t).trim();return r?n?`${n}::${r}`:r:""}function cE(e){const t=e.root&&typeof e.root=="object"?e.root:{};if(!e.expand_subflows)return t;const n=[],r=[],o=new Set,l=(u,c,f,_)=>{if(!u||typeof u!="object"||n.length>=e.max_nodes||r.length>=e.max_edges)return;const p=Array.isArray(u.nodes)?u.nodes:[],y=Array.isArray(u.edges)?u.edges:[];for(const w of p){const x=ln(w==null?void 0:w.id).trim();if(!x)continue;const S=pf(c,x);if(!S||o.has(S))continue;const j=dp(w),C={...w,id:S,position:{x:j.x+f.x,y:j.y+f.y}};if(n.push(C),o.add(S),n.length>=e.max_nodes)break}for(const w of y){if(!gb(w))continue;const x=ln(w==null?void 0:w.source).trim(),S=ln(w==null?void 0:w.target).trim();if(!x||!S)continue;const j=pf(c,x),C=pf(c,S);if(!j||!C)continue;const N=ln(w==null?void 0:w.id).trim(),T=N?`${j}->${C}::${N}`:`${j}->${C}`;if(r.push({...w,id:T,source:j,target:C}),r.length>=e.max_edges)break}if(!(_>=e.max_depth))for(const w of p){if(n.length>=e.max_nodes||r.length>=e.max_edges)return;if(yb(w)!=="subflow")continue;const x=wb(w);if(!x)continue;const S=e.flow_by_id[x];if(!S||typeof S!="object")continue;const j=pf(c,ln(w==null?void 0:w.id));if(!j)continue;const C=lE(S);if(!C)continue;const T=(Array.isArray(S.nodes)?S.nodes:[]).find(re=>ln(re==null?void 0:re.id).trim()===C)||null;if(!T)continue;const L=dp(w),P=dp(T),Y={x:L.x+f.x+240-P.x,y:L.y+f.y+0-P.y},J=pf(j,C);r.push({id:`${j}=>${J}`,source:j,target:J,sourceHandle:"exec-out",targetHandle:"exec-in"}),l(S,j,Y,_+1)}};return l(t,"",{x:0,y:0},0),{...t,id:ln(t.id),nodes:n,edges:r}}function uE(e){const t=ln(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 dE(e){const t=e.nodes.filter(l=>e.keep_id(l.id)),n=new Set(t.map(l=>l.id)),r={};for(const l of e.edges)r[l.source]||(r[l.source]=[]),r[l.source].push(l.target);const o=new Map;for(const l of t){const u=new Set,c=(r[l.id]||[]).slice();for(;c.length;){const f=c.pop();if(!f||u.has(f))continue;if(u.add(f),n.has(f)){const p=`${l.id}->${f}`;o.has(p)||o.set(p,{id:p,source:l.id,target:f});continue}const _=r[f]||[];for(const p of _)u.has(p)||c.push(p);if(o.size>=e.max_edges)break}if(o.size>=e.max_edges)break}return{nodes:t,edges:Array.from(o.values())}}function Cw(e,t){const o=Math.max(t.w*8,160),l=Math.max(t.h*8,120),u=Math.max(160,Math.min(o,e.w)),c=Math.max(120,Math.min(l,e.h));return{x:e.x,y:e.y,w:u,h:c}}function fE(e){const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=e.flow,r=ln(e.active_node_id),o=e.recent_nodes||{},l=e.visited_nodes||{},u=e.highlight_path===!0,c=typeof e.vertical_compact=="number"?Math.max(.4,Math.min(1,e.vertical_compact)):.78,{nodes:f,edges:_,bounds:p}=m.useMemo(()=>{const O=cE({root:n||{},flow_by_id:e.flow_by_id||{},expand_subflows:e.expand_subflows===!0,max_depth:3,max_nodes:700,max_edges:900}),F=Array.isArray(O.nodes)?O.nodes:[],K=Array.isArray(O.edges)?O.edges:[];let R=[];for(const Se of F){const Re=ln(Se==null?void 0:Se.id).trim();if(!Re)continue;const ht=Se!=null&&Se.position&&typeof Se.position=="object"?Se.position:{},xe=typeof ht.x=="number"?ht.x:0,Le=typeof ht.y=="number"?ht.y:0,Ue=Se!=null&&Se.data&&typeof Se.data=="object"?Se.data:{},Ft=ln((Ue==null?void 0:Ue.label)||(Se==null?void 0:Se.label)||Re)||Re,Qt=ln((Ue==null?void 0:Ue.nodeType)||(Se==null?void 0:Se.type)||"unknown")||"unknown",yn=ln((Ue==null?void 0:Ue.headerColor)||(Se==null?void 0:Se.headerColor)||"")||"",Ut=Ue!=null&&Ue.eventConfig&&typeof Ue.eventConfig=="object"?Ue.eventConfig:null,It=Ut&&typeof Ut.schedule=="string"?ln(Ut.schedule).trim():"",jn=Ut&&typeof Ut.recurrent=="boolean"?!!Ut.recurrent:void 0,ns=Qt==="subflow"?wb(Se):"",$t=It||jn!==void 0||ns?{schedule:It||void 0,recurrent:jn,subflow_id:ns||void 0}:void 0;R.push({id:Re,x:xe,y:Le,label:Ft,type:Qt,color:yn,meta:$t})}const Q={};for(const Se of R)Q[Se.id]=Se;let Z=[];for(const Se of K){if(!gb(Se))continue;const Re=ln(Se==null?void 0:Se.source).trim(),ht=ln(Se==null?void 0:Se.target).trim();!Re||!ht||Z.push({id:ln((Se==null?void 0:Se.id)||`${Re}->${ht}`),source:Re,target:ht})}const X=new Set(R.map(Se=>Se.id));if(Z=Z.filter(Se=>X.has(Se.source)&&X.has(Se.target)),e.simplify===!0){const Re=dE({nodes:R,edges:Z,keep_id:ht=>{if(r&&ht===r)return!0;const xe=Q[ht];if(!xe)return!1;const Le=ln(xe.type).trim().toLowerCase();return Le==="on_flow_start"||Le==="on_flow_end"||Le==="subflow"?!0:!uE(Le)},max_edges:900});R=Re.nodes,Z=Re.edges}if(e.prefer_vertical===!0&&R.length>=2){const Se=R.map(Ue=>Ue.x),Re=R.map(Ue=>Ue.y),ht=Math.max(...Se)-Math.min(...Se),xe=Math.max(...Re)-Math.min(...Re);ht>=xe&&(R=R.map(Ue=>({...Ue,x:Ue.y,y:Ue.x})));const Le=Math.min(...R.map(Ue=>Ue.y));R=R.map(Ue=>({...Ue,y:Le+(Ue.y-Le)*c}))}const le={};for(const Se of R)le[Se.id]=Se;const _e=160,he=56,ye=_e/2,Ee=he/2;let ze=0,Be=0,gt=0,Fe=0;R.length&&(ze=Math.min(...R.map(Se=>Se.x)),Be=Math.min(...R.map(Se=>Se.y)),gt=Math.max(...R.map(Se=>Se.x+_e)),Fe=Math.max(...R.map(Se=>Se.y+he)));let tt=0;if(Z.length){const Se=new Set(Z.map(Re=>`${Re.source}->${Re.target}`));for(const Re of Z){if(!Se.has(`${Re.target}->${Re.source}`))continue;const ht=le[Re.source],xe=le[Re.target];if(!ht||!xe)continue;const Le=ht.x+ye,Ue=ht.y+Ee,Ft=xe.x+ye,Qt=xe.y+Ee,yn=Math.max(1,Math.hypot(Ft-Le,Qt-Ue)),Ut=Math.max(28,Math.min(72,yn*.14)),It=Math.min(200,Ut*3.5);It>tt&&(tt=It)}}const lt=60+tt,Ye={x:ze-lt,y:Be-lt,w:gt-ze+lt*2,h:Fe-Be+lt*2,node_w:_e,node_h:he};return{nodes:R,edges:Z,bounds:Ye}},[n,e.flow_by_id,e.expand_subflows,e.simplify,e.prefer_vertical,r,c]);if(!n)return s.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"});const y=m.useRef(null),[w,x]=m.useState(()=>({x:p.x,y:p.y,w:p.w,h:p.h})),S=m.useRef(w);S.current=w,m.useEffect(()=>{x({x:p.x,y:p.y,w:p.w,h:p.h})},[p.x,p.y,p.w,p.h]);const j=m.useRef(new Map),C=m.useRef(null),N=`${w.x} ${w.y} ${w.w} ${w.h}`,T={};for(const O of f)T[O.id]=O;const L=O=>{let F=ln(O).trim();if(!F)return"";if(T[F])return F;for(;F.includes("::");)if(F=F.slice(0,Math.max(0,F.lastIndexOf("::"))),T[F])return F;return""},P=L(r),W={};for(const[O,F]of Object.entries(o)){if(typeof F!="number")continue;const K=L(O);K&&(W[K]=Math.max(W[K]||0,F))}const G={};if(u)for(const[O,F]of Object.entries(l)){if(typeof F!="number")continue;const K=L(O);K&&(G[K]=typeof G[K]=="number"?Math.min(G[K],F):F)}const Y=ln(e.schedule_next_in).trim(),J=ln(e.schedule_interval).trim(),re=e.node_last_ms&&typeof e.node_last_ms=="object"?e.node_last_ms:{},ae=O=>{try{const F=new Date(O),K=String(F.getHours()).padStart(2,"0"),R=String(F.getMinutes()).padStart(2,"0");return`${K}:${R}`}catch{return""}},ue=(O,F)=>{var Z,X;const K=ln((Z=O.meta)==null?void 0:Z.schedule).trim();if(!(((X=O.meta)==null?void 0:X.recurrent)===!0))return F&&Y?`next ${Y}`:K&&K.length<=12&&!K.includes("T")?`in ${K}`:"scheduled";const Q=K||J;return Q?F&&Y?`${Q} • next ${Y}`:`every ${Q}`:F&&Y?`next ${Y}`:"scheduled"},B=O=>{var _e;const F=ln((_e=O.meta)==null?void 0:_e.subflow_id).trim(),K=F&&e.flow_by_id?e.flow_by_id[F]:null,Q=ln(K==null?void 0:K.name).trim()||F||O.label||O.id,Z=typeof re[O.id]=="number"?Number(re[O.id]):null,X=Z!==null?ae(Z):"",le=X?`last ${X}`:"subflow";return{label:Q,sub:le}},A=(O,F,K)=>{const R=K||S.current,Q=y.current;if(!Q)return{x:O,y:F};const Z=Q.getBoundingClientRect(),X=Z.width>0?(O-Z.left)/Z.width:0,le=Z.height>0?(F-Z.top)/Z.height:0;return{x:R.x+X*R.w,y:R.y+le*R.h}},$=(O,F,K)=>{const R=K||S.current,Q=Math.max(.12,Math.min(8,F)),Z=R.w*Q,X=R.h*Q,le=R.w>0?(O.x-R.x)/R.w:.5,_e=R.h>0?(O.y-R.y)/R.h:.5,he=O.x-le*Z,ye=O.y-_e*X;x(Cw({x:he,y:ye,w:Z,h:X},p))},z=(O,F,K)=>{const R=K||S.current,Q=y.current;if(!Q)return;const Z=Q.getBoundingClientRect(),X=.88,le=Z.width>0?O/Z.width*R.w*X:0,_e=Z.height>0?F/Z.height*R.h*X:0;x(he=>Cw({x:(K||he).x-le,y:(K||he).y-_e,w:(K||he).w,h:(K||he).h},p))},E=m.useMemo(()=>{const O=new Set;for(const F of _)O.add(`${F.source}->${F.target}`);return O},[_]),te=(O,F,K,R)=>{const Q=p.node_w,Z=p.node_h,X=Math.abs(K),le=Math.abs(R);if(X<1e-6&&le<1e-6)return{x:O,y:F};const _e=X>1e-6?Q/2/X:Number.POSITIVE_INFINITY,he=le>1e-6?Z/2/le:Number.POSITIVE_INFINITY,ye=Math.min(_e,he);return{x:O+K*ye,y:F+R*ye}};return s.jsxs("div",{className:"graph_wrap",children:[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:()=>x({x:p.x,y:p.y,w:p.w,h:p.h}),title:"Recenter",children:"⤢"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const O=y.current;if(!O)return;const F=O.getBoundingClientRect(),K=A(F.left+F.width/2,F.top+F.height/2);$(K,.84)},title:"Zoom in",children:"+"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const O=y.current;if(!O)return;const F=O.getBoundingClientRect(),K=A(F.left+F.width/2,F.top+F.height/2);$(K,1.18)},title:"Zoom out",children:"−"})]}),s.jsx(aE,{})]}),s.jsxs("svg",{ref:y,className:"graph_svg",viewBox:N,role:"img","aria-label":"Workflow execution graph",onWheel:O=>{O.preventDefault();const F=A(O.clientX,O.clientY),K=typeof O.deltaY=="number"?O.deltaY:0,R=typeof O.deltaMode=="number"?Number(O.deltaMode):0,Q=R===1?K*24:R===2?K*800:K,Z=45e-5*1.15*1.1;let X=Math.exp(Q*Z);X=Math.max(.86,Math.min(1.16,X)),$(F,X)},onPointerDown:O=>{var K,R;(R=(K=O.currentTarget).setPointerCapture)==null||R.call(K,O.pointerId),j.current.set(O.pointerId,{x:O.clientX,y:O.clientY});const F=Array.from(j.current.values());if(F.length===1)C.current={mode:"pan",start_view:S.current,start_client:{x:O.clientX,y:O.clientY},start_dist:0,anchor_svg:{x:0,y:0}};else if(F.length>=2){const Q=F[0],Z=F[1],X=Q.x-Z.x,le=Q.y-Z.y,_e=Math.max(1,Math.hypot(X,le)),he={x:(Q.x+Z.x)/2,y:(Q.y+Z.y)/2},ye=S.current;C.current={mode:"pinch",start_view:ye,start_client:he,start_dist:_e,anchor_svg:A(he.x,he.y,ye)}}},onPointerMove:O=>{if(!j.current.has(O.pointerId))return;j.current.set(O.pointerId,{x:O.clientX,y:O.clientY});const F=C.current;if(!F)return;const K=Array.from(j.current.values());if(F.mode==="pan"&&K.length===1){const R=O.clientX-F.start_client.x,Q=O.clientY-F.start_client.y;z(R,Q,F.start_view)}else if(F.mode==="pinch"&&K.length>=2){const R=K[0],Q=K[1],Z=R.x-Q.x,X=R.y-Q.y,le=Math.max(1,Math.hypot(Z,X)),_e=F.start_dist/le;$(F.anchor_svg,_e,F.start_view)}},onPointerUp:O=>{j.current.delete(O.pointerId),j.current.size===0&&(C.current=null)},onPointerCancel:O=>{j.current.delete(O.pointerId),j.current.size===0&&(C.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"})]})]})]}),_.map(O=>{const F=T[O.source],K=T[O.target];if(!F||!K)return null;const R=F.x+p.node_w/2,Q=F.y+p.node_h/2,Z=K.x+p.node_w/2,X=K.y+p.node_h/2,le=Z-R,_e=X-Q,he=te(R,Q,le,_e),ye=te(Z,X,-le,-_e),Ee=O.source!==O.target&&E.has(`${O.target}->${O.source}`),ze=Math.max(1,Math.hypot(le,_e)),Be=-_e/ze,gt=le/ze,Fe=String(O.source)<String(O.target)?1:-1,lt=Math.abs(le)>=Math.abs(_e)?le>=0:_e>=0,Ye=!Ee||lt,Se=Math.max(28,Math.min(72,ze*.14)),Re=Math.min(200,Se*3.5),ht=Ee&&!Ye?Re*Fe:0,xe=(he.x+ye.x)/2+Be*ht,Le=(he.y+ye.y)/2+gt*ht,Ue=Ee&&!Ye?`M ${he.x} ${he.y} Q ${xe} ${Le} ${ye.x} ${ye.y}`:`M ${he.x} ${he.y} L ${ye.x} ${ye.y}`,Ft=u&&G&&G[O.source]!==void 0&&G[O.target]!==void 0;return s.jsx("path",{d:Ue,className:`graph_edge ${Ft?"visited":""}`,markerEnd:"url(#arrow)",fill:"none"},O.id)}),f.map(O=>{const K=(typeof W[O.id]=="number"?W[O.id]:0)>t,R=P&&O.id===P,Q=u&&G&&G[O.id]!==void 0,Z=`graph_node ${R?"active":K?"recent":""} ${Q?"visited":""}`,X=O.color||"rgba(255,255,255,0.16)";let le=O.label||O.id,_e=O.type;if(O.type==="on_schedule")_e=ue(O,!!R);else if(O.type==="subflow"){const Ee=B(O);le=Ee.label,_e=Ee.sub}const he=Nw(le,22),ye=Nw(_e,22);return s.jsxs("g",{className:Z,transform:`translate(${O.x}, ${O.y})`,children:[s.jsx("rect",{className:"graph_node_bg",width:p.node_w,height:p.node_h,rx:12,ry:12}),s.jsx("rect",{className:"graph_node_bar",width:p.node_w,height:6,rx:12,ry:12,fill:X}),s.jsx("text",{className:"graph_node_label",x:12,y:28,children:he}),s.jsx("text",{className:"graph_node_type",x:12,y:46,children:ye}),O.type==="on_schedule"?s.jsx("text",{className:"graph_node_icon",x:p.node_w-18,y:18,children:"⏰"}):null]},O.id)})]})]})}function Qs(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=Qs(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var fp={exports:{}},hp={},mp={exports:{}},_p={};/**
119
+ * @license React
120
+ * use-sync-external-store-shim.production.js
121
+ *
122
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
123
+ *
124
+ * This source code is licensed under the MIT license found in the
125
+ * LICENSE file in the root directory of this source tree.
126
+ */var Ew;function hE(){if(Ew)return _p;Ew=1;var e=Gf();function t(y,w){return y===w&&(y!==0||1/y===1/w)||y!==y&&w!==w}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,l=e.useLayoutEffect,u=e.useDebugValue;function c(y,w){var x=w(),S=r({inst:{value:x,getSnapshot:w}}),j=S[0].inst,C=S[1];return l(function(){j.value=x,j.getSnapshot=w,f(j)&&C({inst:j})},[y,x,w]),o(function(){return f(j)&&C({inst:j}),y(function(){f(j)&&C({inst:j})})},[y]),u(x),x}function f(y){var w=y.getSnapshot;y=y.value;try{var x=w();return!n(y,x)}catch{return!0}}function _(y,w){return w()}var p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?_:c;return _p.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,_p}var $w;function mE(){return $w||($w=1,mp.exports=hE()),mp.exports}/**
127
+ * @license React
128
+ * use-sync-external-store-shim/with-selector.production.js
129
+ *
130
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
131
+ *
132
+ * This source code is licensed under the MIT license found in the
133
+ * LICENSE file in the root directory of this source tree.
134
+ */var Aw;function _E(){if(Aw)return hp;Aw=1;var e=Gf(),t=mE();function n(_,p){return _===p&&(_!==0||1/_===1/p)||_!==_&&p!==p}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,l=e.useRef,u=e.useEffect,c=e.useMemo,f=e.useDebugValue;return hp.useSyncExternalStoreWithSelector=function(_,p,y,w,x){var S=l(null);if(S.current===null){var j={hasValue:!1,value:null};S.current=j}else j=S.current;S=c(function(){function N(G){if(!T){if(T=!0,L=G,G=w(G),x!==void 0&&j.hasValue){var Y=j.value;if(x(Y,G))return P=Y}return P=G}if(Y=P,r(L,G))return Y;var J=w(G);return x!==void 0&&x(Y,J)?(L=G,Y):(L=G,P=J)}var T=!1,L,P,W=y===void 0?null:y;return[function(){return N(p())},W===null?void 0:function(){return N(W())}]},[p,y,w,x]);var C=o(_,S[0],S[1]);return u(function(){j.hasValue=!0,j.value=C},[C]),f(C),C},hp}var Tw;function pE(){return Tw||(Tw=1,fp.exports=_E()),fp.exports}var gE=pE();const yE=Ag(gE),wE={},Mw=e=>{let t;const n=new Set,r=(p,y)=>{const w=typeof p=="function"?p(t):p;if(!Object.is(w,t)){const x=t;t=y??(typeof w!="object"||w===null)?w:Object.assign({},t,w),n.forEach(S=>S(t,x))}},o=()=>t,f={setState:r,getState:o,getInitialState:()=>_,subscribe:p=>(n.add(p),()=>n.delete(p)),destroy:()=>{(wE?"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()}},_=t=e(r,o,f);return f},vE=e=>e?Mw(e):Mw,{useDebugValue:xE}=ve,{useSyncExternalStoreWithSelector:bE}=yE,jE=e=>e;function vb(e,t=jE,n){const r=bE(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return xE(r),r}const Rw=(e,t)=>{const n=vE(e),r=(o,l=t)=>vb(n,o,l);return Object.assign(r,n),r},SE=(e,t)=>e?Rw(e,t):Rw;function Ps(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,o]of e)if(!Object.is(o,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 kE={value:()=>{}};function d_(){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 Cm(n)}function Cm(e){this._=e}function NE(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",o=n.indexOf(".");if(o>=0&&(r=n.slice(o+1),n=n.slice(0,o)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}Cm.prototype=d_.prototype={constructor:Cm,on:function(e,t){var n=this._,r=NE(e+"",n),o,l=-1,u=r.length;if(arguments.length<2){for(;++l<u;)if((o=(e=r[l]).type)&&(o=CE(n[o],e.name)))return o;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++l<u;)if(o=(e=r[l]).type)n[o]=Lw(n[o],e.name,t);else if(t==null)for(o in n)n[o]=Lw(n[o],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new Cm(e)},call:function(e,t){if((o=arguments.length-2)>0)for(var n=new Array(o),r=0,o,l;r<o;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(l=this._[e],r=0,o=l.length;r<o;++r)l[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],o=0,l=r.length;o<l;++o)r[o].value.apply(t,n)}};function CE(e,t){for(var n=0,r=e.length,o;n<r;++n)if((o=e[n]).name===t)return o.value}function Lw(e,t,n){for(var r=0,o=e.length;r<o;++r)if(e[r].name===t){e[r]=kE,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var lg="http://www.w3.org/1999/xhtml";const Iw={svg:"http://www.w3.org/2000/svg",xhtml:lg,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function f_(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),Iw.hasOwnProperty(t)?{space:Iw[t],local:e}:e}function EE(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===lg&&t.documentElement.namespaceURI===lg?t.createElement(e):t.createElementNS(n,e)}}function $E(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function xb(e){var t=f_(e);return(t.local?$E:EE)(t)}function AE(){}function Yg(e){return e==null?AE:function(){return this.querySelector(e)}}function TE(e){typeof e!="function"&&(e=Yg(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var l=t[o],u=l.length,c=r[o]=new Array(u),f,_,p=0;p<u;++p)(f=l[p])&&(_=e.call(f,f.__data__,p,l))&&("__data__"in f&&(_.__data__=f.__data__),c[p]=_);return new fi(r,this._parents)}function ME(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function RE(){return[]}function bb(e){return e==null?RE:function(){return this.querySelectorAll(e)}}function LE(e){return function(){return ME(e.apply(this,arguments))}}function IE(e){typeof e=="function"?e=LE(e):e=bb(e);for(var t=this._groups,n=t.length,r=[],o=[],l=0;l<n;++l)for(var u=t[l],c=u.length,f,_=0;_<c;++_)(f=u[_])&&(r.push(e.call(f,f.__data__,_,u)),o.push(f));return new fi(r,o)}function jb(e){return function(){return this.matches(e)}}function Sb(e){return function(t){return t.matches(e)}}var OE=Array.prototype.find;function PE(e){return function(){return OE.call(this.children,e)}}function DE(){return this.firstElementChild}function FE(e){return this.select(e==null?DE:PE(typeof e=="function"?e:Sb(e)))}var zE=Array.prototype.filter;function BE(){return Array.from(this.children)}function UE(e){return function(){return zE.call(this.children,e)}}function WE(e){return this.selectAll(e==null?BE:UE(typeof e=="function"?e:Sb(e)))}function qE(e){typeof e!="function"&&(e=jb(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var l=t[o],u=l.length,c=r[o]=[],f,_=0;_<u;++_)(f=l[_])&&e.call(f,f.__data__,_,l)&&c.push(f);return new fi(r,this._parents)}function kb(e){return new Array(e.length)}function HE(){return new fi(this._enter||this._groups.map(kb),this._parents)}function Hm(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}Hm.prototype={constructor:Hm,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 VE(e){return function(){return e}}function GE(e,t,n,r,o,l){for(var u=0,c,f=t.length,_=l.length;u<_;++u)(c=t[u])?(c.__data__=l[u],r[u]=c):n[u]=new Hm(e,l[u]);for(;u<f;++u)(c=t[u])&&(o[u]=c)}function KE(e,t,n,r,o,l,u){var c,f,_=new Map,p=t.length,y=l.length,w=new Array(p),x;for(c=0;c<p;++c)(f=t[c])&&(w[c]=x=u.call(f,f.__data__,c,t)+"",_.has(x)?o[c]=f:_.set(x,f));for(c=0;c<y;++c)x=u.call(e,l[c],c,l)+"",(f=_.get(x))?(r[c]=f,f.__data__=l[c],_.delete(x)):n[c]=new Hm(e,l[c]);for(c=0;c<p;++c)(f=t[c])&&_.get(w[c])===f&&(o[c]=f)}function YE(e){return e.__data__}function JE(e,t){if(!arguments.length)return Array.from(this,YE);var n=t?KE:GE,r=this._parents,o=this._groups;typeof e!="function"&&(e=VE(e));for(var l=o.length,u=new Array(l),c=new Array(l),f=new Array(l),_=0;_<l;++_){var p=r[_],y=o[_],w=y.length,x=XE(e.call(p,p&&p.__data__,_,r)),S=x.length,j=c[_]=new Array(S),C=u[_]=new Array(S),N=f[_]=new Array(w);n(p,y,j,C,N,x,t);for(var T=0,L=0,P,W;T<S;++T)if(P=j[T]){for(T>=L&&(L=T+1);!(W=C[L])&&++L<S;);P._next=W||null}}return u=new fi(u,r),u._enter=c,u._exit=f,u}function XE(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function ZE(){return new fi(this._exit||this._groups.map(kb),this._parents)}function QE(e,t,n){var r=this.enter(),o=this,l=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(o=t(o),o&&(o=o.selection())),n==null?l.remove():n(l),r&&o?r.merge(o).order():o}function e$(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,o=n.length,l=r.length,u=Math.min(o,l),c=new Array(o),f=0;f<u;++f)for(var _=n[f],p=r[f],y=_.length,w=c[f]=new Array(y),x,S=0;S<y;++S)(x=_[S]||p[S])&&(w[S]=x);for(;f<o;++f)c[f]=n[f];return new fi(c,this._parents)}function t$(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],o=r.length-1,l=r[o],u;--o>=0;)(u=r[o])&&(l&&u.compareDocumentPosition(l)^4&&l.parentNode.insertBefore(u,l),l=u);return this}function n$(e){e||(e=s$);function t(y,w){return y&&w?e(y.__data__,w.__data__):!y-!w}for(var n=this._groups,r=n.length,o=new Array(r),l=0;l<r;++l){for(var u=n[l],c=u.length,f=o[l]=new Array(c),_,p=0;p<c;++p)(_=u[p])&&(f[p]=_);f.sort(t)}return new fi(o,this._parents).order()}function s$(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function r$(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function i$(){return Array.from(this)}function o$(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,l=r.length;o<l;++o){var u=r[o];if(u)return u}return null}function a$(){let e=0;for(const t of this)++e;return e}function l$(){return!this.node()}function c$(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var o=t[n],l=0,u=o.length,c;l<u;++l)(c=o[l])&&e.call(c,c.__data__,l,o);return this}function u$(e){return function(){this.removeAttribute(e)}}function d$(e){return function(){this.removeAttributeNS(e.space,e.local)}}function f$(e,t){return function(){this.setAttribute(e,t)}}function h$(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function m$(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function _$(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 p$(e,t){var n=f_(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?d$:u$:typeof t=="function"?n.local?_$:m$:n.local?h$:f$)(n,t))}function Nb(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function g$(e){return function(){this.style.removeProperty(e)}}function y$(e,t,n){return function(){this.style.setProperty(e,t,n)}}function w$(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function v$(e,t,n){return arguments.length>1?this.each((t==null?g$:typeof t=="function"?w$:y$)(e,t,n??"")):Qu(this.node(),e)}function Qu(e,t){return e.style.getPropertyValue(t)||Nb(e).getComputedStyle(e,null).getPropertyValue(t)}function x$(e){return function(){delete this[e]}}function b$(e,t){return function(){this[e]=t}}function j$(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function S$(e,t){return arguments.length>1?this.each((t==null?x$:typeof t=="function"?j$:b$)(e,t)):this.node()[e]}function Cb(e){return e.trim().split(/^|\s+/)}function Jg(e){return e.classList||new Eb(e)}function Eb(e){this._node=e,this._names=Cb(e.getAttribute("class")||"")}Eb.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 $b(e,t){for(var n=Jg(e),r=-1,o=t.length;++r<o;)n.add(t[r])}function Ab(e,t){for(var n=Jg(e),r=-1,o=t.length;++r<o;)n.remove(t[r])}function k$(e){return function(){$b(this,e)}}function N$(e){return function(){Ab(this,e)}}function C$(e,t){return function(){(t.apply(this,arguments)?$b:Ab)(this,e)}}function E$(e,t){var n=Cb(e+"");if(arguments.length<2){for(var r=Jg(this.node()),o=-1,l=n.length;++o<l;)if(!r.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?C$:t?k$:N$)(n,t))}function $$(){this.textContent=""}function A$(e){return function(){this.textContent=e}}function T$(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function M$(e){return arguments.length?this.each(e==null?$$:(typeof e=="function"?T$:A$)(e)):this.node().textContent}function R$(){this.innerHTML=""}function L$(e){return function(){this.innerHTML=e}}function I$(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function O$(e){return arguments.length?this.each(e==null?R$:(typeof e=="function"?I$:L$)(e)):this.node().innerHTML}function P$(){this.nextSibling&&this.parentNode.appendChild(this)}function D$(){return this.each(P$)}function F$(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function z$(){return this.each(F$)}function B$(e){var t=typeof e=="function"?e:xb(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function U$(){return null}function W$(e,t){var n=typeof e=="function"?e:xb(e),r=t==null?U$:typeof t=="function"?t:Yg(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function q$(){var e=this.parentNode;e&&e.removeChild(this)}function H$(){return this.each(q$)}function V$(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function G$(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function K$(e){return this.select(e?G$:V$)}function Y$(e){return arguments.length?this.property("__data__",e):this.node().__data__}function J$(e){return function(t){e.call(this,t,this.__data__)}}function X$(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 Z$(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,o=t.length,l;n<o;++n)l=t[n],(!e.type||l.type===e.type)&&l.name===e.name?this.removeEventListener(l.type,l.listener,l.options):t[++r]=l;++r?t.length=r:delete this.__on}}}function Q$(e,t,n){return function(){var r=this.__on,o,l=J$(t);if(r){for(var u=0,c=r.length;u<c;++u)if((o=r[u]).type===e.type&&o.name===e.name){this.removeEventListener(o.type,o.listener,o.options),this.addEventListener(o.type,o.listener=l,o.options=n),o.value=t;return}}this.addEventListener(e.type,l,n),o={type:e.type,name:e.name,value:t,listener:l,options:n},r?r.push(o):this.__on=[o]}}function eA(e,t,n){var r=X$(e+""),o,l=r.length,u;if(arguments.length<2){var c=this.node().__on;if(c){for(var f=0,_=c.length,p;f<_;++f)for(o=0,p=c[f];o<l;++o)if((u=r[o]).type===p.type&&u.name===p.name)return p.value}return}for(c=t?Q$:Z$,o=0;o<l;++o)this.each(c(r[o],t,n));return this}function Tb(e,t,n){var r=Nb(e),o=r.CustomEvent;typeof o=="function"?o=new o(t,n):(o=r.document.createEvent("Event"),n?(o.initEvent(t,n.bubbles,n.cancelable),o.detail=n.detail):o.initEvent(t,!1,!1)),e.dispatchEvent(o)}function tA(e,t){return function(){return Tb(this,e,t)}}function nA(e,t){return function(){return Tb(this,e,t.apply(this,arguments))}}function sA(e,t){return this.each((typeof t=="function"?nA:tA)(e,t))}function*rA(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,l=r.length,u;o<l;++o)(u=r[o])&&(yield u)}var Mb=[null];function fi(e,t){this._groups=e,this._parents=t}function Zf(){return new fi([[document.documentElement]],Mb)}function iA(){return this}fi.prototype=Zf.prototype={constructor:fi,select:TE,selectAll:IE,selectChild:FE,selectChildren:WE,filter:qE,data:JE,enter:HE,exit:ZE,join:QE,merge:e$,selection:iA,order:t$,sort:n$,call:r$,nodes:i$,node:o$,size:a$,empty:l$,each:c$,attr:p$,style:v$,property:S$,classed:E$,text:M$,html:O$,raise:D$,lower:z$,append:B$,insert:W$,remove:H$,clone:K$,datum:Y$,on:eA,dispatch:sA,[Symbol.iterator]:rA};function Ai(e){return typeof e=="string"?new fi([[document.querySelector(e)]],[document.documentElement]):new fi([[e]],Mb)}function oA(e){let t;for(;t=e.sourceEvent;)e=t;return e}function so(e,t){if(e=oA(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 o=t.getBoundingClientRect();return[e.clientX-o.left-t.clientLeft,e.clientY-o.top-t.clientTop]}}return[e.pageX,e.pageY]}const aA={passive:!1},Of={capture:!0,passive:!1};function pp(e){e.stopImmediatePropagation()}function Gu(e){e.preventDefault(),e.stopImmediatePropagation()}function Rb(e){var t=e.document.documentElement,n=Ai(e).on("dragstart.drag",Gu,Of);"onselectstart"in t?n.on("selectstart.drag",Gu,Of):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function Lb(e,t){var n=e.document.documentElement,r=Ai(e).on("dragstart.drag",null);t&&(r.on("click.drag",Gu,Of),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 um=e=>()=>e;function cg(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:l,x:u,y:c,dx:f,dy:_,dispatch:p}){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:o,enumerable:!0,configurable:!0},active:{value:l,enumerable:!0,configurable:!0},x:{value:u,enumerable:!0,configurable:!0},y:{value:c,enumerable:!0,configurable:!0},dx:{value:f,enumerable:!0,configurable:!0},dy:{value:_,enumerable:!0,configurable:!0},_:{value:p}})}cg.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function lA(e){return!e.ctrlKey&&!e.button}function cA(){return this.parentNode}function uA(e,t){return t??{x:e.x,y:e.y}}function dA(){return navigator.maxTouchPoints||"ontouchstart"in this}function fA(){var e=lA,t=cA,n=uA,r=dA,o={},l=d_("start","drag","end"),u=0,c,f,_,p,y=0;function w(P){P.on("mousedown.drag",x).filter(r).on("touchstart.drag",C).on("touchmove.drag",N,aA).on("touchend.drag touchcancel.drag",T).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function x(P,W){if(!(p||!e.call(this,P,W))){var G=L(this,t.call(this,P,W),P,W,"mouse");G&&(Ai(P.view).on("mousemove.drag",S,Of).on("mouseup.drag",j,Of),Rb(P.view),pp(P),_=!1,c=P.clientX,f=P.clientY,G("start",P))}}function S(P){if(Gu(P),!_){var W=P.clientX-c,G=P.clientY-f;_=W*W+G*G>y}o.mouse("drag",P)}function j(P){Ai(P.view).on("mousemove.drag mouseup.drag",null),Lb(P.view,_),Gu(P),o.mouse("end",P)}function C(P,W){if(e.call(this,P,W)){var G=P.changedTouches,Y=t.call(this,P,W),J=G.length,re,ae;for(re=0;re<J;++re)(ae=L(this,Y,P,W,G[re].identifier,G[re]))&&(pp(P),ae("start",P,G[re]))}}function N(P){var W=P.changedTouches,G=W.length,Y,J;for(Y=0;Y<G;++Y)(J=o[W[Y].identifier])&&(Gu(P),J("drag",P,W[Y]))}function T(P){var W=P.changedTouches,G=W.length,Y,J;for(p&&clearTimeout(p),p=setTimeout(function(){p=null},500),Y=0;Y<G;++Y)(J=o[W[Y].identifier])&&(pp(P),J("end",P,W[Y]))}function L(P,W,G,Y,J,re){var ae=l.copy(),ue=so(re||G,W),B,A,$;if(($=n.call(P,new cg("beforestart",{sourceEvent:G,target:w,identifier:J,active:u,x:ue[0],y:ue[1],dx:0,dy:0,dispatch:ae}),Y))!=null)return B=$.x-ue[0]||0,A=$.y-ue[1]||0,function z(E,te,O){var F=ue,K;switch(E){case"start":o[J]=z,K=u++;break;case"end":delete o[J],--u;case"drag":ue=so(O||te,W),K=u;break}ae.call(E,P,new cg(E,{sourceEvent:te,subject:$,target:w,identifier:J,active:K,x:ue[0]+B,y:ue[1]+A,dx:ue[0]-F[0],dy:ue[1]-F[1],dispatch:ae}),Y)}}return w.filter=function(P){return arguments.length?(e=typeof P=="function"?P:um(!!P),w):e},w.container=function(P){return arguments.length?(t=typeof P=="function"?P:um(P),w):t},w.subject=function(P){return arguments.length?(n=typeof P=="function"?P:um(P),w):n},w.touchable=function(P){return arguments.length?(r=typeof P=="function"?P:um(!!P),w):r},w.on=function(){var P=l.on.apply(l,arguments);return P===l?w:P},w.clickDistance=function(P){return arguments.length?(y=(P=+P)*P,w):Math.sqrt(y)},w}function Xg(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function Ib(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Qf(){}var Pf=.7,Vm=1/Pf,Ku="\\s*([+-]?\\d+)\\s*",Df="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Do="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",hA=/^#([0-9a-f]{3,8})$/,mA=new RegExp(`^rgb\\(${Ku},${Ku},${Ku}\\)$`),_A=new RegExp(`^rgb\\(${Do},${Do},${Do}\\)$`),pA=new RegExp(`^rgba\\(${Ku},${Ku},${Ku},${Df}\\)$`),gA=new RegExp(`^rgba\\(${Do},${Do},${Do},${Df}\\)$`),yA=new RegExp(`^hsl\\(${Df},${Do},${Do}\\)$`),wA=new RegExp(`^hsla\\(${Df},${Do},${Do},${Df}\\)$`),Ow={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};Xg(Qf,Ff,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Pw,formatHex:Pw,formatHex8:vA,formatHsl:xA,formatRgb:Dw,toString:Dw});function Pw(){return this.rgb().formatHex()}function vA(){return this.rgb().formatHex8()}function xA(){return Ob(this).formatHsl()}function Dw(){return this.rgb().formatRgb()}function Ff(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=hA.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Fw(t):n===3?new Jr(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?dm(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?dm(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=mA.exec(e))?new Jr(t[1],t[2],t[3],1):(t=_A.exec(e))?new Jr(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=pA.exec(e))?dm(t[1],t[2],t[3],t[4]):(t=gA.exec(e))?dm(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=yA.exec(e))?Uw(t[1],t[2]/100,t[3]/100,1):(t=wA.exec(e))?Uw(t[1],t[2]/100,t[3]/100,t[4]):Ow.hasOwnProperty(e)?Fw(Ow[e]):e==="transparent"?new Jr(NaN,NaN,NaN,0):null}function Fw(e){return new Jr(e>>16&255,e>>8&255,e&255,1)}function dm(e,t,n,r){return r<=0&&(e=t=n=NaN),new Jr(e,t,n,r)}function bA(e){return e instanceof Qf||(e=Ff(e)),e?(e=e.rgb(),new Jr(e.r,e.g,e.b,e.opacity)):new Jr}function ug(e,t,n,r){return arguments.length===1?bA(e):new Jr(e,t,n,r??1)}function Jr(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Xg(Jr,ug,Ib(Qf,{brighter(e){return e=e==null?Vm:Math.pow(Vm,e),new Jr(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Pf:Math.pow(Pf,e),new Jr(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Jr(Cc(this.r),Cc(this.g),Cc(this.b),Gm(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:zw,formatHex:zw,formatHex8:jA,formatRgb:Bw,toString:Bw}));function zw(){return`#${bc(this.r)}${bc(this.g)}${bc(this.b)}`}function jA(){return`#${bc(this.r)}${bc(this.g)}${bc(this.b)}${bc((isNaN(this.opacity)?1:this.opacity)*255)}`}function Bw(){const e=Gm(this.opacity);return`${e===1?"rgb(":"rgba("}${Cc(this.r)}, ${Cc(this.g)}, ${Cc(this.b)}${e===1?")":`, ${e})`}`}function Gm(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Cc(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function bc(e){return e=Cc(e),(e<16?"0":"")+e.toString(16)}function Uw(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new io(e,t,n,r)}function Ob(e){if(e instanceof io)return new io(e.h,e.s,e.l,e.opacity);if(e instanceof Qf||(e=Ff(e)),!e)return new io;if(e instanceof io)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,o=Math.min(t,n,r),l=Math.max(t,n,r),u=NaN,c=l-o,f=(l+o)/2;return c?(t===l?u=(n-r)/c+(n<r)*6:n===l?u=(r-t)/c+2:u=(t-n)/c+4,c/=f<.5?l+o:2-l-o,u*=60):c=f>0&&f<1?0:u,new io(u,c,f,e.opacity)}function SA(e,t,n,r){return arguments.length===1?Ob(e):new io(e,t,n,r??1)}function io(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Xg(io,SA,Ib(Qf,{brighter(e){return e=e==null?Vm:Math.pow(Vm,e),new io(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Pf:Math.pow(Pf,e),new io(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,o=2*n-r;return new Jr(gp(e>=240?e-240:e+120,o,r),gp(e,o,r),gp(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new io(Ww(this.h),fm(this.s),fm(this.l),Gm(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=Gm(this.opacity);return`${e===1?"hsl(":"hsla("}${Ww(this.h)}, ${fm(this.s)*100}%, ${fm(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Ww(e){return e=(e||0)%360,e<0?e+360:e}function fm(e){return Math.max(0,Math.min(1,e||0))}function gp(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 Pb=e=>()=>e;function kA(e,t){return function(n){return e+n*t}}function NA(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 CA(e){return(e=+e)==1?Db:function(t,n){return n-t?NA(t,n,e):Pb(isNaN(t)?n:t)}}function Db(e,t){var n=t-e;return n?kA(e,n):Pb(isNaN(e)?t:e)}const qw=(function e(t){var n=CA(t);function r(o,l){var u=n((o=ug(o)).r,(l=ug(l)).r),c=n(o.g,l.g),f=n(o.b,l.b),_=Db(o.opacity,l.opacity);return function(p){return o.r=u(p),o.g=c(p),o.b=f(p),o.opacity=_(p),o+""}}return r.gamma=e,r})(1);function ml(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var dg=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,yp=new RegExp(dg.source,"g");function EA(e){return function(){return e}}function $A(e){return function(t){return e(t)+""}}function AA(e,t){var n=dg.lastIndex=yp.lastIndex=0,r,o,l,u=-1,c=[],f=[];for(e=e+"",t=t+"";(r=dg.exec(e))&&(o=yp.exec(t));)(l=o.index)>n&&(l=t.slice(n,l),c[u]?c[u]+=l:c[++u]=l),(r=r[0])===(o=o[0])?c[u]?c[u]+=o:c[++u]=o:(c[++u]=null,f.push({i:u,x:ml(r,o)})),n=yp.lastIndex;return n<t.length&&(l=t.slice(n),c[u]?c[u]+=l:c[++u]=l),c.length<2?f[0]?$A(f[0].x):EA(t):(t=f.length,function(_){for(var p=0,y;p<t;++p)c[(y=f[p]).i]=y.x(_);return c.join("")})}var Hw=180/Math.PI,fg={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Fb(e,t,n,r,o,l){var u,c,f;return(u=Math.sqrt(e*e+t*t))&&(e/=u,t/=u),(f=e*n+t*r)&&(n-=e*f,r-=t*f),(c=Math.sqrt(n*n+r*r))&&(n/=c,r/=c,f/=c),e*r<t*n&&(e=-e,t=-t,f=-f,u=-u),{translateX:o,translateY:l,rotate:Math.atan2(t,e)*Hw,skewX:Math.atan(f)*Hw,scaleX:u,scaleY:c}}var hm;function TA(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?fg:Fb(t.a,t.b,t.c,t.d,t.e,t.f)}function MA(e){return e==null||(hm||(hm=document.createElementNS("http://www.w3.org/2000/svg","g")),hm.setAttribute("transform",e),!(e=hm.transform.baseVal.consolidate()))?fg:(e=e.matrix,Fb(e.a,e.b,e.c,e.d,e.e,e.f))}function zb(e,t,n,r){function o(_){return _.length?_.pop()+" ":""}function l(_,p,y,w,x,S){if(_!==y||p!==w){var j=x.push("translate(",null,t,null,n);S.push({i:j-4,x:ml(_,y)},{i:j-2,x:ml(p,w)})}else(y||w)&&x.push("translate("+y+t+w+n)}function u(_,p,y,w){_!==p?(_-p>180?p+=360:p-_>180&&(_+=360),w.push({i:y.push(o(y)+"rotate(",null,r)-2,x:ml(_,p)})):p&&y.push(o(y)+"rotate("+p+r)}function c(_,p,y,w){_!==p?w.push({i:y.push(o(y)+"skewX(",null,r)-2,x:ml(_,p)}):p&&y.push(o(y)+"skewX("+p+r)}function f(_,p,y,w,x,S){if(_!==y||p!==w){var j=x.push(o(x)+"scale(",null,",",null,")");S.push({i:j-4,x:ml(_,y)},{i:j-2,x:ml(p,w)})}else(y!==1||w!==1)&&x.push(o(x)+"scale("+y+","+w+")")}return function(_,p){var y=[],w=[];return _=e(_),p=e(p),l(_.translateX,_.translateY,p.translateX,p.translateY,y,w),u(_.rotate,p.rotate,y,w),c(_.skewX,p.skewX,y,w),f(_.scaleX,_.scaleY,p.scaleX,p.scaleY,y,w),_=p=null,function(x){for(var S=-1,j=w.length,C;++S<j;)y[(C=w[S]).i]=C.x(x);return y.join("")}}}var RA=zb(TA,"px, ","px)","deg)"),LA=zb(MA,", ",")",")"),IA=1e-12;function Vw(e){return((e=Math.exp(e))+1/e)/2}function OA(e){return((e=Math.exp(e))-1/e)/2}function PA(e){return((e=Math.exp(2*e))-1)/(e+1)}const DA=(function e(t,n,r){function o(l,u){var c=l[0],f=l[1],_=l[2],p=u[0],y=u[1],w=u[2],x=p-c,S=y-f,j=x*x+S*S,C,N;if(j<IA)N=Math.log(w/_)/t,C=function(Y){return[c+Y*x,f+Y*S,_*Math.exp(t*Y*N)]};else{var T=Math.sqrt(j),L=(w*w-_*_+r*j)/(2*_*n*T),P=(w*w-_*_-r*j)/(2*w*n*T),W=Math.log(Math.sqrt(L*L+1)-L),G=Math.log(Math.sqrt(P*P+1)-P);N=(G-W)/t,C=function(Y){var J=Y*N,re=Vw(W),ae=_/(n*T)*(re*PA(t*J+W)-OA(W));return[c+ae*x,f+ae*S,_*re/Vw(t*J+W)]}}return C.duration=N*1e3*t/Math.SQRT2,C}return o.rho=function(l){var u=Math.max(.001,+l),c=u*u,f=c*c;return e(u,c,f)},o})(Math.SQRT2,2,4);var ed=0,Ef=0,gf=0,Bb=1e3,Km,$f,Ym=0,Tc=0,h_=0,zf=typeof performance=="object"&&performance.now?performance:Date,Ub=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Zg(){return Tc||(Ub(FA),Tc=zf.now()+h_)}function FA(){Tc=0}function Jm(){this._call=this._time=this._next=null}Jm.prototype=Wb.prototype={constructor:Jm,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Zg():+n)+(t==null?0:+t),!this._next&&$f!==this&&($f?$f._next=this:Km=this,$f=this),this._call=e,this._time=n,hg()},stop:function(){this._call&&(this._call=null,this._time=1/0,hg())}};function Wb(e,t,n){var r=new Jm;return r.restart(e,t,n),r}function zA(){Zg(),++ed;for(var e=Km,t;e;)(t=Tc-e._time)>=0&&e._call.call(void 0,t),e=e._next;--ed}function Gw(){Tc=(Ym=zf.now())+h_,ed=Ef=0;try{zA()}finally{ed=0,UA(),Tc=0}}function BA(){var e=zf.now(),t=e-Ym;t>Bb&&(h_-=t,Ym=e)}function UA(){for(var e,t=Km,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:Km=n);$f=e,hg(r)}function hg(e){if(!ed){Ef&&(Ef=clearTimeout(Ef));var t=e-Tc;t>24?(e<1/0&&(Ef=setTimeout(Gw,e-zf.now()-h_)),gf&&(gf=clearInterval(gf))):(gf||(Ym=zf.now(),gf=setInterval(BA,Bb)),ed=1,Ub(Gw))}}function Kw(e,t,n){var r=new Jm;return t=t==null?0:+t,r.restart(o=>{r.stop(),e(o+t)},t,n),r}var WA=d_("start","end","cancel","interrupt"),qA=[],qb=0,Yw=1,mg=2,Em=3,Jw=4,_g=5,$m=6;function m_(e,t,n,r,o,l){var u=e.__transition;if(!u)e.__transition={};else if(n in u)return;HA(e,n,{name:t,index:r,group:o,on:WA,tween:qA,time:l.time,delay:l.delay,duration:l.duration,ease:l.ease,timer:null,state:qb})}function Qg(e,t){var n=lo(e,t);if(n.state>qb)throw new Error("too late; already scheduled");return n}function Fo(e,t){var n=lo(e,t);if(n.state>Em)throw new Error("too late; already running");return n}function lo(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function HA(e,t,n){var r=e.__transition,o;r[t]=n,n.timer=Wb(l,0,n.time);function l(_){n.state=Yw,n.timer.restart(u,n.delay,n.time),n.delay<=_&&u(_-n.delay)}function u(_){var p,y,w,x;if(n.state!==Yw)return f();for(p in r)if(x=r[p],x.name===n.name){if(x.state===Em)return Kw(u);x.state===Jw?(x.state=$m,x.timer.stop(),x.on.call("interrupt",e,e.__data__,x.index,x.group),delete r[p]):+p<t&&(x.state=$m,x.timer.stop(),x.on.call("cancel",e,e.__data__,x.index,x.group),delete r[p])}if(Kw(function(){n.state===Em&&(n.state=Jw,n.timer.restart(c,n.delay,n.time),c(_))}),n.state=mg,n.on.call("start",e,e.__data__,n.index,n.group),n.state===mg){for(n.state=Em,o=new Array(w=n.tween.length),p=0,y=-1;p<w;++p)(x=n.tween[p].value.call(e,e.__data__,n.index,n.group))&&(o[++y]=x);o.length=y+1}}function c(_){for(var p=_<n.duration?n.ease.call(null,_/n.duration):(n.timer.restart(f),n.state=_g,1),y=-1,w=o.length;++y<w;)o[y].call(e,p);n.state===_g&&(n.on.call("end",e,e.__data__,n.index,n.group),f())}function f(){n.state=$m,n.timer.stop(),delete r[t];for(var _ in r)return;delete e.__transition}}function Am(e,t){var n=e.__transition,r,o,l=!0,u;if(n){t=t==null?null:t+"";for(u in n){if((r=n[u]).name!==t){l=!1;continue}o=r.state>mg&&r.state<_g,r.state=$m,r.timer.stop(),r.on.call(o?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[u]}l&&delete e.__transition}}function VA(e){return this.each(function(){Am(this,e)})}function GA(e,t){var n,r;return function(){var o=Fo(this,e),l=o.tween;if(l!==n){r=n=l;for(var u=0,c=r.length;u<c;++u)if(r[u].name===t){r=r.slice(),r.splice(u,1);break}}o.tween=r}}function KA(e,t,n){var r,o;if(typeof n!="function")throw new Error;return function(){var l=Fo(this,e),u=l.tween;if(u!==r){o=(r=u).slice();for(var c={name:t,value:n},f=0,_=o.length;f<_;++f)if(o[f].name===t){o[f]=c;break}f===_&&o.push(c)}l.tween=o}}function YA(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=lo(this.node(),n).tween,o=0,l=r.length,u;o<l;++o)if((u=r[o]).name===e)return u.value;return null}return this.each((t==null?GA:KA)(n,e,t))}function ey(e,t,n){var r=e._id;return e.each(function(){var o=Fo(this,r);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return lo(o,r).value[t]}}function Hb(e,t){var n;return(typeof t=="number"?ml:t instanceof Ff?qw:(n=Ff(t))?(t=n,qw):AA)(e,t)}function JA(e){return function(){this.removeAttribute(e)}}function XA(e){return function(){this.removeAttributeNS(e.space,e.local)}}function ZA(e,t,n){var r,o=n+"",l;return function(){var u=this.getAttribute(e);return u===o?null:u===r?l:l=t(r=u,n)}}function QA(e,t,n){var r,o=n+"",l;return function(){var u=this.getAttributeNS(e.space,e.local);return u===o?null:u===r?l:l=t(r=u,n)}}function eT(e,t,n){var r,o,l;return function(){var u,c=n(this),f;return c==null?void this.removeAttribute(e):(u=this.getAttribute(e),f=c+"",u===f?null:u===r&&f===o?l:(o=f,l=t(r=u,c)))}}function tT(e,t,n){var r,o,l;return function(){var u,c=n(this),f;return c==null?void this.removeAttributeNS(e.space,e.local):(u=this.getAttributeNS(e.space,e.local),f=c+"",u===f?null:u===r&&f===o?l:(o=f,l=t(r=u,c)))}}function nT(e,t){var n=f_(e),r=n==="transform"?LA:Hb;return this.attrTween(e,typeof t=="function"?(n.local?tT:eT)(n,r,ey(this,"attr."+e,t)):t==null?(n.local?XA:JA)(n):(n.local?QA:ZA)(n,r,t))}function sT(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function rT(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function iT(e,t){var n,r;function o(){var l=t.apply(this,arguments);return l!==r&&(n=(r=l)&&rT(e,l)),n}return o._value=t,o}function oT(e,t){var n,r;function o(){var l=t.apply(this,arguments);return l!==r&&(n=(r=l)&&sT(e,l)),n}return o._value=t,o}function aT(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=f_(e);return this.tween(n,(r.local?iT:oT)(r,t))}function lT(e,t){return function(){Qg(this,e).delay=+t.apply(this,arguments)}}function cT(e,t){return t=+t,function(){Qg(this,e).delay=t}}function uT(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?lT:cT)(t,e)):lo(this.node(),t).delay}function dT(e,t){return function(){Fo(this,e).duration=+t.apply(this,arguments)}}function fT(e,t){return t=+t,function(){Fo(this,e).duration=t}}function hT(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?dT:fT)(t,e)):lo(this.node(),t).duration}function mT(e,t){if(typeof t!="function")throw new Error;return function(){Fo(this,e).ease=t}}function _T(e){var t=this._id;return arguments.length?this.each(mT(t,e)):lo(this.node(),t).ease}function pT(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Fo(this,e).ease=n}}function gT(e){if(typeof e!="function")throw new Error;return this.each(pT(this._id,e))}function yT(e){typeof e!="function"&&(e=jb(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var l=t[o],u=l.length,c=r[o]=[],f,_=0;_<u;++_)(f=l[_])&&e.call(f,f.__data__,_,l)&&c.push(f);return new $a(r,this._parents,this._name,this._id)}function wT(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,o=n.length,l=Math.min(r,o),u=new Array(r),c=0;c<l;++c)for(var f=t[c],_=n[c],p=f.length,y=u[c]=new Array(p),w,x=0;x<p;++x)(w=f[x]||_[x])&&(y[x]=w);for(;c<r;++c)u[c]=t[c];return new $a(u,this._parents,this._name,this._id)}function vT(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 xT(e,t,n){var r,o,l=vT(t)?Qg:Fo;return function(){var u=l(this,e),c=u.on;c!==r&&(o=(r=c).copy()).on(t,n),u.on=o}}function bT(e,t){var n=this._id;return arguments.length<2?lo(this.node(),n).on.on(e):this.each(xT(n,e,t))}function jT(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function ST(){return this.on("end.remove",jT(this._id))}function kT(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Yg(e));for(var r=this._groups,o=r.length,l=new Array(o),u=0;u<o;++u)for(var c=r[u],f=c.length,_=l[u]=new Array(f),p,y,w=0;w<f;++w)(p=c[w])&&(y=e.call(p,p.__data__,w,c))&&("__data__"in p&&(y.__data__=p.__data__),_[w]=y,m_(_[w],t,n,w,_,lo(p,n)));return new $a(l,this._parents,t,n)}function NT(e){var t=this._name,n=this._id;typeof e!="function"&&(e=bb(e));for(var r=this._groups,o=r.length,l=[],u=[],c=0;c<o;++c)for(var f=r[c],_=f.length,p,y=0;y<_;++y)if(p=f[y]){for(var w=e.call(p,p.__data__,y,f),x,S=lo(p,n),j=0,C=w.length;j<C;++j)(x=w[j])&&m_(x,t,n,j,w,S);l.push(w),u.push(p)}return new $a(l,u,t,n)}var CT=Zf.prototype.constructor;function ET(){return new CT(this._groups,this._parents)}function $T(e,t){var n,r,o;return function(){var l=Qu(this,e),u=(this.style.removeProperty(e),Qu(this,e));return l===u?null:l===n&&u===r?o:o=t(n=l,r=u)}}function Vb(e){return function(){this.style.removeProperty(e)}}function AT(e,t,n){var r,o=n+"",l;return function(){var u=Qu(this,e);return u===o?null:u===r?l:l=t(r=u,n)}}function TT(e,t,n){var r,o,l;return function(){var u=Qu(this,e),c=n(this),f=c+"";return c==null&&(f=c=(this.style.removeProperty(e),Qu(this,e))),u===f?null:u===r&&f===o?l:(o=f,l=t(r=u,c))}}function MT(e,t){var n,r,o,l="style."+t,u="end."+l,c;return function(){var f=Fo(this,e),_=f.on,p=f.value[l]==null?c||(c=Vb(t)):void 0;(_!==n||o!==p)&&(r=(n=_).copy()).on(u,o=p),f.on=r}}function RT(e,t,n){var r=(e+="")=="transform"?RA:Hb;return t==null?this.styleTween(e,$T(e,r)).on("end.style."+e,Vb(e)):typeof t=="function"?this.styleTween(e,TT(e,r,ey(this,"style."+e,t))).each(MT(this._id,e)):this.styleTween(e,AT(e,r,t),n).on("end.style."+e,null)}function LT(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function IT(e,t,n){var r,o;function l(){var u=t.apply(this,arguments);return u!==o&&(r=(o=u)&&LT(e,u,n)),r}return l._value=t,l}function OT(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,IT(e,t,n??""))}function PT(e){return function(){this.textContent=e}}function DT(e){return function(){var t=e(this);this.textContent=t??""}}function FT(e){return this.tween("text",typeof e=="function"?DT(ey(this,"text",e)):PT(e==null?"":e+""))}function zT(e){return function(t){this.textContent=e.call(this,t)}}function BT(e){var t,n;function r(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&zT(o)),t}return r._value=e,r}function UT(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,BT(e))}function WT(){for(var e=this._name,t=this._id,n=Gb(),r=this._groups,o=r.length,l=0;l<o;++l)for(var u=r[l],c=u.length,f,_=0;_<c;++_)if(f=u[_]){var p=lo(f,t);m_(f,e,n,_,u,{time:p.time+p.delay+p.duration,delay:0,duration:p.duration,ease:p.ease})}return new $a(r,this._parents,e,n)}function qT(){var e,t,n=this,r=n._id,o=n.size();return new Promise(function(l,u){var c={value:u},f={value:function(){--o===0&&l()}};n.each(function(){var _=Fo(this,r),p=_.on;p!==e&&(t=(e=p).copy(),t._.cancel.push(c),t._.interrupt.push(c),t._.end.push(f)),_.on=t}),o===0&&l()})}var HT=0;function $a(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Gb(){return++HT}var ja=Zf.prototype;$a.prototype={constructor:$a,select:kT,selectAll:NT,selectChild:ja.selectChild,selectChildren:ja.selectChildren,filter:yT,merge:wT,selection:ET,transition:WT,call:ja.call,nodes:ja.nodes,node:ja.node,size:ja.size,empty:ja.empty,each:ja.each,on:bT,attr:nT,attrTween:aT,style:RT,styleTween:OT,text:FT,textTween:UT,remove:ST,tween:YA,delay:uT,duration:hT,ease:_T,easeVarying:gT,end:qT,[Symbol.iterator]:ja[Symbol.iterator]};function VT(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var GT={time:null,delay:0,duration:250,ease:VT};function KT(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 YT(e){var t,n;e instanceof $a?(t=e._id,e=e._name):(t=Gb(),(n=GT).time=Zg(),e=e==null?null:e+"");for(var r=this._groups,o=r.length,l=0;l<o;++l)for(var u=r[l],c=u.length,f,_=0;_<c;++_)(f=u[_])&&m_(f,e,t,_,u,n||KT(f,t));return new $a(r,this._parents,e,t)}Zf.prototype.interrupt=VA;Zf.prototype.transition=YT;const mm=e=>()=>e;function JT(e,{sourceEvent:t,target:n,transform:r,dispatch:o}){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:o}})}function Sa(e,t,n){this.k=e,this.x=t,this.y=n}Sa.prototype={constructor:Sa,scale:function(e){return e===1?this:new Sa(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Sa(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 Na=new Sa(1,0,0);Sa.prototype;function wp(e){e.stopImmediatePropagation()}function yf(e){e.preventDefault(),e.stopImmediatePropagation()}function XT(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function ZT(){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 Xw(){return this.__zoom||Na}function QT(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function eM(){return navigator.maxTouchPoints||"ontouchstart"in this}function tM(e,t,n){var r=e.invertX(t[0][0])-n[0][0],o=e.invertX(t[1][0])-n[1][0],l=e.invertY(t[0][1])-n[0][1],u=e.invertY(t[1][1])-n[1][1];return e.translate(o>r?(r+o)/2:Math.min(0,r)||Math.max(0,o),u>l?(l+u)/2:Math.min(0,l)||Math.max(0,u))}function Kb(){var e=XT,t=ZT,n=tM,r=QT,o=eM,l=[0,1/0],u=[[-1/0,-1/0],[1/0,1/0]],c=250,f=DA,_=d_("start","zoom","end"),p,y,w,x=500,S=150,j=0,C=10;function N($){$.property("__zoom",Xw).on("wheel.zoom",J,{passive:!1}).on("mousedown.zoom",re).on("dblclick.zoom",ae).filter(o).on("touchstart.zoom",ue).on("touchmove.zoom",B).on("touchend.zoom touchcancel.zoom",A).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}N.transform=function($,z,E,te){var O=$.selection?$.selection():$;O.property("__zoom",Xw),$!==O?W($,z,E,te):O.interrupt().each(function(){G(this,arguments).event(te).start().zoom(null,typeof z=="function"?z.apply(this,arguments):z).end()})},N.scaleBy=function($,z,E,te){N.scaleTo($,function(){var O=this.__zoom.k,F=typeof z=="function"?z.apply(this,arguments):z;return O*F},E,te)},N.scaleTo=function($,z,E,te){N.transform($,function(){var O=t.apply(this,arguments),F=this.__zoom,K=E==null?P(O):typeof E=="function"?E.apply(this,arguments):E,R=F.invert(K),Q=typeof z=="function"?z.apply(this,arguments):z;return n(L(T(F,Q),K,R),O,u)},E,te)},N.translateBy=function($,z,E,te){N.transform($,function(){return n(this.__zoom.translate(typeof z=="function"?z.apply(this,arguments):z,typeof E=="function"?E.apply(this,arguments):E),t.apply(this,arguments),u)},null,te)},N.translateTo=function($,z,E,te,O){N.transform($,function(){var F=t.apply(this,arguments),K=this.__zoom,R=te==null?P(F):typeof te=="function"?te.apply(this,arguments):te;return n(Na.translate(R[0],R[1]).scale(K.k).translate(typeof z=="function"?-z.apply(this,arguments):-z,typeof E=="function"?-E.apply(this,arguments):-E),F,u)},te,O)};function T($,z){return z=Math.max(l[0],Math.min(l[1],z)),z===$.k?$:new Sa(z,$.x,$.y)}function L($,z,E){var te=z[0]-E[0]*$.k,O=z[1]-E[1]*$.k;return te===$.x&&O===$.y?$:new Sa($.k,te,O)}function P($){return[(+$[0][0]+ +$[1][0])/2,(+$[0][1]+ +$[1][1])/2]}function W($,z,E,te){$.on("start.zoom",function(){G(this,arguments).event(te).start()}).on("interrupt.zoom end.zoom",function(){G(this,arguments).event(te).end()}).tween("zoom",function(){var O=this,F=arguments,K=G(O,F).event(te),R=t.apply(O,F),Q=E==null?P(R):typeof E=="function"?E.apply(O,F):E,Z=Math.max(R[1][0]-R[0][0],R[1][1]-R[0][1]),X=O.__zoom,le=typeof z=="function"?z.apply(O,F):z,_e=f(X.invert(Q).concat(Z/X.k),le.invert(Q).concat(Z/le.k));return function(he){if(he===1)he=le;else{var ye=_e(he),Ee=Z/ye[2];he=new Sa(Ee,Q[0]-ye[0]*Ee,Q[1]-ye[1]*Ee)}K.zoom(null,he)}})}function G($,z,E){return!E&&$.__zooming||new Y($,z)}function Y($,z){this.that=$,this.args=z,this.active=0,this.sourceEvent=null,this.extent=t.apply($,z),this.taps=0}Y.prototype={event:function($){return $&&(this.sourceEvent=$),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function($,z){return this.mouse&&$!=="mouse"&&(this.mouse[1]=z.invert(this.mouse[0])),this.touch0&&$!=="touch"&&(this.touch0[1]=z.invert(this.touch0[0])),this.touch1&&$!=="touch"&&(this.touch1[1]=z.invert(this.touch1[0])),this.that.__zoom=z,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function($){var z=Ai(this.that).datum();_.call($,this.that,new JT($,{sourceEvent:this.sourceEvent,target:N,transform:this.that.__zoom,dispatch:_}),z)}};function J($,...z){if(!e.apply(this,arguments))return;var E=G(this,z).event($),te=this.__zoom,O=Math.max(l[0],Math.min(l[1],te.k*Math.pow(2,r.apply(this,arguments)))),F=so($);if(E.wheel)(E.mouse[0][0]!==F[0]||E.mouse[0][1]!==F[1])&&(E.mouse[1]=te.invert(E.mouse[0]=F)),clearTimeout(E.wheel);else{if(te.k===O)return;E.mouse=[F,te.invert(F)],Am(this),E.start()}yf($),E.wheel=setTimeout(K,S),E.zoom("mouse",n(L(T(te,O),E.mouse[0],E.mouse[1]),E.extent,u));function K(){E.wheel=null,E.end()}}function re($,...z){if(w||!e.apply(this,arguments))return;var E=$.currentTarget,te=G(this,z,!0).event($),O=Ai($.view).on("mousemove.zoom",Q,!0).on("mouseup.zoom",Z,!0),F=so($,E),K=$.clientX,R=$.clientY;Rb($.view),wp($),te.mouse=[F,this.__zoom.invert(F)],Am(this),te.start();function Q(X){if(yf(X),!te.moved){var le=X.clientX-K,_e=X.clientY-R;te.moved=le*le+_e*_e>j}te.event(X).zoom("mouse",n(L(te.that.__zoom,te.mouse[0]=so(X,E),te.mouse[1]),te.extent,u))}function Z(X){O.on("mousemove.zoom mouseup.zoom",null),Lb(X.view,te.moved),yf(X),te.event(X).end()}}function ae($,...z){if(e.apply(this,arguments)){var E=this.__zoom,te=so($.changedTouches?$.changedTouches[0]:$,this),O=E.invert(te),F=E.k*($.shiftKey?.5:2),K=n(L(T(E,F),te,O),t.apply(this,z),u);yf($),c>0?Ai(this).transition().duration(c).call(W,K,te,$):Ai(this).call(N.transform,K,te,$)}}function ue($,...z){if(e.apply(this,arguments)){var E=$.touches,te=E.length,O=G(this,z,$.changedTouches.length===te).event($),F,K,R,Q;for(wp($),K=0;K<te;++K)R=E[K],Q=so(R,this),Q=[Q,this.__zoom.invert(Q),R.identifier],O.touch0?!O.touch1&&O.touch0[2]!==Q[2]&&(O.touch1=Q,O.taps=0):(O.touch0=Q,F=!0,O.taps=1+!!p);p&&(p=clearTimeout(p)),F&&(O.taps<2&&(y=Q[0],p=setTimeout(function(){p=null},x)),Am(this),O.start())}}function B($,...z){if(this.__zooming){var E=G(this,z).event($),te=$.changedTouches,O=te.length,F,K,R,Q;for(yf($),F=0;F<O;++F)K=te[F],R=so(K,this),E.touch0&&E.touch0[2]===K.identifier?E.touch0[0]=R:E.touch1&&E.touch1[2]===K.identifier&&(E.touch1[0]=R);if(K=E.that.__zoom,E.touch1){var Z=E.touch0[0],X=E.touch0[1],le=E.touch1[0],_e=E.touch1[1],he=(he=le[0]-Z[0])*he+(he=le[1]-Z[1])*he,ye=(ye=_e[0]-X[0])*ye+(ye=_e[1]-X[1])*ye;K=T(K,Math.sqrt(he/ye)),R=[(Z[0]+le[0])/2,(Z[1]+le[1])/2],Q=[(X[0]+_e[0])/2,(X[1]+_e[1])/2]}else if(E.touch0)R=E.touch0[0],Q=E.touch0[1];else return;E.zoom("touch",n(L(K,R,Q),E.extent,u))}}function A($,...z){if(this.__zooming){var E=G(this,z).event($),te=$.changedTouches,O=te.length,F,K;for(wp($),w&&clearTimeout(w),w=setTimeout(function(){w=null},x),F=0;F<O;++F)K=te[F],E.touch0&&E.touch0[2]===K.identifier?delete E.touch0:E.touch1&&E.touch1[2]===K.identifier&&delete E.touch1;if(E.touch1&&!E.touch0&&(E.touch0=E.touch1,delete E.touch1),E.touch0)E.touch0[1]=this.__zoom.invert(E.touch0[0]);else if(E.end(),E.taps===2&&(K=so(K,this),Math.hypot(y[0]-K[0],y[1]-K[1])<C)){var R=Ai(this).on("dblclick.zoom");R&&R.apply(this,arguments)}}}return N.wheelDelta=function($){return arguments.length?(r=typeof $=="function"?$:mm(+$),N):r},N.filter=function($){return arguments.length?(e=typeof $=="function"?$:mm(!!$),N):e},N.touchable=function($){return arguments.length?(o=typeof $=="function"?$:mm(!!$),N):o},N.extent=function($){return arguments.length?(t=typeof $=="function"?$:mm([[+$[0][0],+$[0][1]],[+$[1][0],+$[1][1]]]),N):t},N.scaleExtent=function($){return arguments.length?(l[0]=+$[0],l[1]=+$[1],N):[l[0],l[1]]},N.translateExtent=function($){return arguments.length?(u[0][0]=+$[0][0],u[1][0]=+$[1][0],u[0][1]=+$[0][1],u[1][1]=+$[1][1],N):[[u[0][0],u[0][1]],[u[1][0],u[1][1]]]},N.constrain=function($){return arguments.length?(n=$,N):n},N.duration=function($){return arguments.length?(c=+$,N):c},N.interpolate=function($){return arguments.length?(f=$,N):f},N.on=function(){var $=_.on.apply(_,arguments);return $===_?N:$},N.clickDistance=function($){return arguments.length?(j=($=+$)*$,N):Math.sqrt(j)},N.tapDistance=function($){return arguments.length?(C=+$,N):C},N}const __=m.createContext(null),nM=__.Provider,Aa={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.`},Yb=Aa.error001();function In(e,t){const n=m.useContext(__);if(n===null)throw new Error(Yb);return vb(n,e,t)}const bs=()=>{const e=m.useContext(__);if(e===null)throw new Error(Yb);return m.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},sM=e=>e.userSelectionActive?"none":"all";function Bf({position:e,children:t,className:n,style:r,...o}){const l=In(sM),u=`${e}`.split("-");return ve.createElement("div",{className:Qs(["react-flow__panel",n,...u]),style:{...r,pointerEvents:l},...o},t)}function rM({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:ve.createElement(Bf,{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"},ve.createElement("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution"},"React Flow"))}const iM=({x:e,y:t,label:n,labelStyle:r={},labelShowBg:o=!0,labelBgStyle:l={},labelBgPadding:u=[2,4],labelBgBorderRadius:c=2,children:f,className:_,...p})=>{const y=m.useRef(null),[w,x]=m.useState({x:0,y:0,width:0,height:0}),S=Qs(["react-flow__edge-textwrapper",_]);return m.useEffect(()=>{if(y.current){const j=y.current.getBBox();x({x:j.x,y:j.y,width:j.width,height:j.height})}},[n]),typeof n>"u"||!n?null:ve.createElement("g",{transform:`translate(${e-w.width/2} ${t-w.height/2})`,className:S,visibility:w.width?"visible":"hidden",...p},o&&ve.createElement("rect",{width:w.width+2*u[0],x:-u[0],y:-u[1],height:w.height+2*u[1],className:"react-flow__edge-textbg",style:l,rx:c,ry:c}),ve.createElement("text",{className:"react-flow__edge-text",y:w.height/2,dy:"0.3em",ref:y,style:r},n),f)};var oM=m.memo(iM);const ty=e=>({width:e.offsetWidth,height:e.offsetHeight}),td=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),ny=(e={x:0,y:0},t)=>({x:td(e.x,t[0][0],t[1][0]),y:td(e.y,t[0][1],t[1][1])}),Zw=(e,t,n)=>e<t?td(Math.abs(e-t),1,50)/50:e>n?-td(Math.abs(e-n),1,50)/50:0,Jb=(e,t)=>{const n=Zw(e.x,35,t.width-35)*20,r=Zw(e.y,35,t.height-35)*20;return[n,r]},Xb=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},Zb=(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)}),Uf=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Qb=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Qw=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),aM=(e,t)=>Qb(Zb(Uf(e),Uf(t))),pg=(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)},lM=e=>Ti(e.width)&&Ti(e.height)&&Ti(e.x)&&Ti(e.y),Ti=e=>!isNaN(e)&&isFinite(e),ds=Symbol.for("internals"),e0=["Enter"," ","Escape"],cM=(e,t)=>{},uM=e=>"nativeEvent"in e;function gg(e){var o,l;const t=uM(e)?e.nativeEvent:e,n=((l=(o=t.composedPath)==null?void 0:o.call(t))==null?void 0:l[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 t0=e=>"clientX"in e,yl=(e,t)=>{var l,u;const n=t0(e),r=n?e.clientX:(l=e.touches)==null?void 0:l[0].clientX,o=n?e.clientY:(u=e.touches)==null?void 0:u[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:o-((t==null?void 0:t.top)??0)}},Xm=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0},eh=({id:e,path:t,labelX:n,labelY:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:y,markerStart:w,interactionWidth:x=20})=>ve.createElement(ve.Fragment,null,ve.createElement("path",{id:e,style:p,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:y,markerStart:w}),x&&ve.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:x,className:"react-flow__edge-interaction"}),o&&Ti(n)&&Ti(r)?ve.createElement(oM,{x:n,y:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_}):null);eh.displayName="BaseEdge";function wf(e,t,n){return n===void 0?n:r=>{const o=t().edges.find(l=>l.id===e);o&&n(r,{...o})}}function n0({sourceX:e,sourceY:t,targetX:n,targetY:r}){const o=Math.abs(n-e)/2,l=n<e?n+o:n-o,u=Math.abs(r-t)/2,c=r<t?r+u:r-u;return[l,c,o,u]}function s0({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:o,sourceControlY:l,targetControlX:u,targetControlY:c}){const f=e*.125+o*.375+u*.375+n*.125,_=t*.125+l*.375+c*.375+r*.125,p=Math.abs(f-e),y=Math.abs(_-t);return[f,_,p,y]}var Mc;(function(e){e.Strict="strict",e.Loose="loose"})(Mc||(Mc={}));var jc;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(jc||(jc={}));var Wf;(function(e){e.Partial="partial",e.Full="full"})(Wf||(Wf={}));var gl;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(gl||(gl={}));var qf;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(qf||(qf={}));var pt;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(pt||(pt={}));function ev({pos:e,x1:t,y1:n,x2:r,y2:o}){return e===pt.Left||e===pt.Right?[.5*(t+r),n]:[t,.5*(n+o)]}function r0({sourceX:e,sourceY:t,sourcePosition:n=pt.Bottom,targetX:r,targetY:o,targetPosition:l=pt.Top}){const[u,c]=ev({pos:n,x1:e,y1:t,x2:r,y2:o}),[f,_]=ev({pos:l,x1:r,y1:o,x2:e,y2:t}),[p,y,w,x]=s0({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:u,sourceControlY:c,targetControlX:f,targetControlY:_});return[`M${e},${t} C${u},${c} ${f},${_} ${r},${o}`,p,y,w,x]}const sy=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:o=pt.Bottom,targetPosition:l=pt.Top,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:y,style:w,markerEnd:x,markerStart:S,interactionWidth:j})=>{const[C,N,T]=r0({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:r,targetPosition:l});return ve.createElement(eh,{path:C,labelX:N,labelY:T,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:y,style:w,markerEnd:x,markerStart:S,interactionWidth:j})});sy.displayName="SimpleBezierEdge";const tv={[pt.Left]:{x:-1,y:0},[pt.Right]:{x:1,y:0},[pt.Top]:{x:0,y:-1},[pt.Bottom]:{x:0,y:1}},dM=({source:e,sourcePosition:t=pt.Bottom,target:n})=>t===pt.Left||t===pt.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},nv=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function fM({source:e,sourcePosition:t=pt.Bottom,target:n,targetPosition:r=pt.Top,center:o,offset:l}){const u=tv[t],c=tv[r],f={x:e.x+u.x*l,y:e.y+u.y*l},_={x:n.x+c.x*l,y:n.y+c.y*l},p=dM({source:f,sourcePosition:t,target:_}),y=p.x!==0?"x":"y",w=p[y];let x=[],S,j;const C={x:0,y:0},N={x:0,y:0},[T,L,P,W]=n0({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(u[y]*c[y]===-1){S=o.x||T,j=o.y||L;const Y=[{x:S,y:f.y},{x:S,y:_.y}],J=[{x:f.x,y:j},{x:_.x,y:j}];u[y]===w?x=y==="x"?Y:J:x=y==="x"?J:Y}else{const Y=[{x:f.x,y:_.y}],J=[{x:_.x,y:f.y}];if(y==="x"?x=u.x===w?J:Y:x=u.y===w?Y:J,t===r){const A=Math.abs(e[y]-n[y]);if(A<=l){const $=Math.min(l-1,l-A);u[y]===w?C[y]=(f[y]>e[y]?-1:1)*$:N[y]=(_[y]>n[y]?-1:1)*$}}if(t!==r){const A=y==="x"?"y":"x",$=u[y]===c[A],z=f[A]>_[A],E=f[A]<_[A];(u[y]===1&&(!$&&z||$&&E)||u[y]!==1&&(!$&&E||$&&z))&&(x=y==="x"?Y:J)}const re={x:f.x+C.x,y:f.y+C.y},ae={x:_.x+N.x,y:_.y+N.y},ue=Math.max(Math.abs(re.x-x[0].x),Math.abs(ae.x-x[0].x)),B=Math.max(Math.abs(re.y-x[0].y),Math.abs(ae.y-x[0].y));ue>=B?(S=(re.x+ae.x)/2,j=x[0].y):(S=x[0].x,j=(re.y+ae.y)/2)}return[[e,{x:f.x+C.x,y:f.y+C.y},...x,{x:_.x+N.x,y:_.y+N.y},n],S,j,P,W]}function hM(e,t,n,r){const o=Math.min(nv(e,t)/2,nv(t,n)/2,r),{x:l,y:u}=t;if(e.x===l&&l===n.x||e.y===u&&u===n.y)return`L${l} ${u}`;if(e.y===u){const _=e.x<n.x?-1:1,p=e.y<n.y?1:-1;return`L ${l+o*_},${u}Q ${l},${u} ${l},${u+o*p}`}const c=e.x<n.x?1:-1,f=e.y<n.y?-1:1;return`L ${l},${u+o*f}Q ${l},${u} ${l+o*c},${u}`}function yg({sourceX:e,sourceY:t,sourcePosition:n=pt.Bottom,targetX:r,targetY:o,targetPosition:l=pt.Top,borderRadius:u=5,centerX:c,centerY:f,offset:_=20}){const[p,y,w,x,S]=fM({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:l,center:{x:c,y:f},offset:_});return[p.reduce((C,N,T)=>{let L="";return T>0&&T<p.length-1?L=hM(p[T-1],N,p[T+1],u):L=`${T===0?"M":"L"}${N.x} ${N.y}`,C+=L,C},""),y,w,x,S]}const p_=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,sourcePosition:y=pt.Bottom,targetPosition:w=pt.Top,markerEnd:x,markerStart:S,pathOptions:j,interactionWidth:C})=>{const[N,T,L]=yg({sourceX:e,sourceY:t,sourcePosition:y,targetX:n,targetY:r,targetPosition:w,borderRadius:j==null?void 0:j.borderRadius,offset:j==null?void 0:j.offset});return ve.createElement(eh,{path:N,labelX:T,labelY:L,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:x,markerStart:S,interactionWidth:C})});p_.displayName="SmoothStepEdge";const ry=m.memo(e=>{var t;return ve.createElement(p_,{...e,pathOptions:m.useMemo(()=>{var n;return{borderRadius:0,offset:(n=e.pathOptions)==null?void 0:n.offset}},[(t=e.pathOptions)==null?void 0:t.offset])})});ry.displayName="StepEdge";function mM({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[o,l,u,c]=n0({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,l,u,c]}const iy=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:y,markerStart:w,interactionWidth:x})=>{const[S,j,C]=mM({sourceX:e,sourceY:t,targetX:n,targetY:r});return ve.createElement(eh,{path:S,labelX:j,labelY:C,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:_,style:p,markerEnd:y,markerStart:w,interactionWidth:x})});iy.displayName="StraightEdge";function _m(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function sv({pos:e,x1:t,y1:n,x2:r,y2:o,c:l}){switch(e){case pt.Left:return[t-_m(t-r,l),n];case pt.Right:return[t+_m(r-t,l),n];case pt.Top:return[t,n-_m(n-o,l)];case pt.Bottom:return[t,n+_m(o-n,l)]}}function i0({sourceX:e,sourceY:t,sourcePosition:n=pt.Bottom,targetX:r,targetY:o,targetPosition:l=pt.Top,curvature:u=.25}){const[c,f]=sv({pos:n,x1:e,y1:t,x2:r,y2:o,c:u}),[_,p]=sv({pos:l,x1:r,y1:o,x2:e,y2:t,c:u}),[y,w,x,S]=s0({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:c,sourceControlY:f,targetControlX:_,targetControlY:p});return[`M${e},${t} C${c},${f} ${_},${p} ${r},${o}`,y,w,x,S]}const Zm=m.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:o=pt.Bottom,targetPosition:l=pt.Top,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:y,style:w,markerEnd:x,markerStart:S,pathOptions:j,interactionWidth:C})=>{const[N,T,L]=i0({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:r,targetPosition:l,curvature:j==null?void 0:j.curvature});return ve.createElement(eh,{path:N,labelX:T,labelY:L,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:_,labelBgPadding:p,labelBgBorderRadius:y,style:w,markerEnd:x,markerStart:S,interactionWidth:C})});Zm.displayName="BezierEdge";const oy=m.createContext(null),_M=oy.Provider;oy.Consumer;const pM=()=>m.useContext(oy),gM=e=>"id"in e&&"source"in e&&"target"in e,yM=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`reactflow__edge-${e}${t||""}-${n}${r||""}`,wg=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`,wM=(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)),vM=(e,t)=>{if(!e.source||!e.target)return t;let n;return gM(e)?n={...e}:n={...e,id:yM(e)},wM(n,t)?t:t.concat(n)},vg=({x:e,y:t},[n,r,o],l,[u,c])=>{const f={x:(e-n)/o,y:(t-r)/o};return l?{x:u*Math.round(f.x/u),y:c*Math.round(f.y/c)}:f},o0=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r}),Ec=(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],o={x:e.position.x-n,y:e.position.y-r};return{...o,positionAbsolute:e.positionAbsolute?{x:e.positionAbsolute.x-n,y:e.positionAbsolute.y-r}:o}},g_=(e,t=[0,0])=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,o)=>{const{x:l,y:u}=Ec(o,t).positionAbsolute;return Zb(r,Uf({x:l,y:u,width:o.width||0,height:o.height||0}))},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Qb(n)},a0=(e,t,[n,r,o]=[0,0,1],l=!1,u=!1,c=[0,0])=>{const f={x:(t.x-n)/o,y:(t.y-r)/o,width:t.width/o,height:t.height/o},_=[];return e.forEach(p=>{const{width:y,height:w,selectable:x=!0,hidden:S=!1}=p;if(u&&!x||S)return!1;const{positionAbsolute:j}=Ec(p,c),C={x:j.x,y:j.y,width:y||0,height:w||0},N=pg(f,C),T=typeof y>"u"||typeof w>"u"||y===null||w===null,L=l&&N>0,P=(y||0)*(w||0);(T||L||N>=P||p.dragging)&&_.push(p)}),_},l0=(e,t)=>{const n=e.map(r=>r.id);return t.filter(r=>n.includes(r.source)||n.includes(r.target))},c0=(e,t,n,r,o,l=.1)=>{const u=t/(e.width*(1+l)),c=n/(e.height*(1+l)),f=Math.min(u,c),_=td(f,r,o),p=e.x+e.width/2,y=e.y+e.height/2,w=t/2-p*_,x=n/2-y*_;return{x:w,y:x,zoom:_}},yc=(e,t=0)=>e.transition().duration(t);function rv(e,t,n,r){return(t[n]||[]).reduce((o,l)=>{var u,c;return`${e.id}-${l.id}-${n}`!==r&&o.push({id:l.id||null,type:n,nodeId:e.id,x:(((u=e.positionAbsolute)==null?void 0:u.x)??0)+l.x+l.width/2,y:(((c=e.positionAbsolute)==null?void 0:c.y)??0)+l.y+l.height/2}),o},[])}function xM(e,t,n,r,o,l){const{x:u,y:c}=yl(e),_=t.elementsFromPoint(u,c).find(S=>S.classList.contains("react-flow__handle"));if(_){const S=_.getAttribute("data-nodeid");if(S){const j=ay(void 0,_),C=_.getAttribute("data-handleid"),N=l({nodeId:S,id:C,type:j});if(N){const T=o.find(L=>L.nodeId===S&&L.type===j&&L.id===C);return{handle:{id:C,type:j,nodeId:S,x:(T==null?void 0:T.x)||n.x,y:(T==null?void 0:T.y)||n.y},validHandleResult:N}}}}let p=[],y=1/0;if(o.forEach(S=>{const j=Math.sqrt((S.x-n.x)**2+(S.y-n.y)**2);if(j<=r){const C=l(S);j<=y&&(j<y?p=[{handle:S,validHandleResult:C}]:j===y&&p.push({handle:S,validHandleResult:C}),y=j)}}),!p.length)return{handle:null,validHandleResult:u0()};if(p.length===1)return p[0];const w=p.some(({validHandleResult:S})=>S.isValid),x=p.some(({handle:S})=>S.type==="target");return p.find(({handle:S,validHandleResult:j})=>x?S.type==="target":w?j.isValid:!0)||p[0]}const bM={source:null,target:null,sourceHandle:null,targetHandle:null},u0=()=>({handleDomNode:null,isValid:!1,connection:bM,endHandle:null});function d0(e,t,n,r,o,l,u){const c=o==="target",f=u.querySelector(`.react-flow__handle[data-id="${e==null?void 0:e.nodeId}-${e==null?void 0:e.id}-${e==null?void 0:e.type}"]`),_={...u0(),handleDomNode:f};if(f){const p=ay(void 0,f),y=f.getAttribute("data-nodeid"),w=f.getAttribute("data-handleid"),x=f.classList.contains("connectable"),S=f.classList.contains("connectableend"),j={source:c?y:n,sourceHandle:c?w:r,target:c?n:y,targetHandle:c?r:w};_.connection=j,x&&S&&(t===Mc.Strict?c&&p==="source"||!c&&p==="target":y!==n||w!==r)&&(_.endHandle={nodeId:y,handleId:w,type:p},_.isValid=l(j))}return _}function jM({nodes:e,nodeId:t,handleId:n,handleType:r}){return e.reduce((o,l)=>{if(l[ds]){const{handleBounds:u}=l[ds];let c=[],f=[];u&&(c=rv(l,u,"source",`${t}-${n}-${r}`),f=rv(l,u,"target",`${t}-${n}-${r}`)),o.push(...c,...f)}return o},[])}function ay(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function vp(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function SM(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function f0({event:e,handleId:t,nodeId:n,onConnect:r,isTarget:o,getState:l,setState:u,isValidConnection:c,edgeUpdaterType:f,onEdgeUpdateEnd:_}){const p=Xb(e.target),{connectionMode:y,domNode:w,autoPanOnConnect:x,connectionRadius:S,onConnectStart:j,panBy:C,getNodes:N,cancelConnection:T}=l();let L=0,P;const{x:W,y:G}=yl(e),Y=p==null?void 0:p.elementFromPoint(W,G),J=ay(f,Y),re=w==null?void 0:w.getBoundingClientRect();if(!re||!J)return;let ae,ue=yl(e,re),B=!1,A=null,$=!1,z=null;const E=jM({nodes:N(),nodeId:n,handleId:t,handleType:J}),te=()=>{if(!x)return;const[K,R]=Jb(ue,re);C({x:K,y:R}),L=requestAnimationFrame(te)};u({connectionPosition:ue,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:J,connectionStartHandle:{nodeId:n,handleId:t,type:J},connectionEndHandle:null}),j==null||j(e,{nodeId:n,handleId:t,handleType:J});function O(K){const{transform:R}=l();ue=yl(K,re);const{handle:Q,validHandleResult:Z}=xM(K,p,vg(ue,R,!1,[1,1]),S,E,X=>d0(X,y,n,t,o?"target":"source",c,p));if(P=Q,B||(te(),B=!0),z=Z.handleDomNode,A=Z.connection,$=Z.isValid,u({connectionPosition:P&&$?o0({x:P.x,y:P.y},R):ue,connectionStatus:SM(!!P,$),connectionEndHandle:Z.endHandle}),!P&&!$&&!z)return vp(ae);A.source!==A.target&&z&&(vp(ae),ae=z,z.classList.add("connecting","react-flow__handle-connecting"),z.classList.toggle("valid",$),z.classList.toggle("react-flow__handle-valid",$))}function F(K){var R,Q;(P||z)&&A&&$&&(r==null||r(A)),(Q=(R=l()).onConnectEnd)==null||Q.call(R,K),f&&(_==null||_(K)),vp(ae),T(),cancelAnimationFrame(L),B=!1,$=!1,A=null,z=null,p.removeEventListener("mousemove",O),p.removeEventListener("mouseup",F),p.removeEventListener("touchmove",O),p.removeEventListener("touchend",F)}p.addEventListener("mousemove",O),p.addEventListener("mouseup",F),p.addEventListener("touchmove",O),p.addEventListener("touchend",F)}const iv=()=>!0,kM=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),NM=(e,t,n)=>r=>{const{connectionStartHandle:o,connectionEndHandle:l,connectionClickStartHandle:u}=r;return{connecting:(o==null?void 0:o.nodeId)===e&&(o==null?void 0:o.handleId)===t&&(o==null?void 0:o.type)===n||(l==null?void 0:l.nodeId)===e&&(l==null?void 0:l.handleId)===t&&(l==null?void 0:l.type)===n,clickConnecting:(u==null?void 0:u.nodeId)===e&&(u==null?void 0:u.handleId)===t&&(u==null?void 0:u.type)===n}},h0=m.forwardRef(({type:e="source",position:t=pt.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:o=!0,isConnectableEnd:l=!0,id:u,onConnect:c,children:f,className:_,onMouseDown:p,onTouchStart:y,...w},x)=>{var re,ae;const S=u||null,j=e==="target",C=bs(),N=pM(),{connectOnClick:T,noPanClassName:L}=In(kM,Ps),{connecting:P,clickConnecting:W}=In(NM(N,S,e),Ps);N||(ae=(re=C.getState()).onError)==null||ae.call(re,"010",Aa.error010());const G=ue=>{const{defaultEdgeOptions:B,onConnect:A,hasDefaultEdges:$}=C.getState(),z={...B,...ue};if($){const{edges:E,setEdges:te}=C.getState();te(vM(z,E))}A==null||A(z),c==null||c(z)},Y=ue=>{if(!N)return;const B=t0(ue);o&&(B&&ue.button===0||!B)&&f0({event:ue,handleId:S,nodeId:N,onConnect:G,isTarget:j,getState:C.getState,setState:C.setState,isValidConnection:n||C.getState().isValidConnection||iv}),B?p==null||p(ue):y==null||y(ue)},J=ue=>{const{onClickConnectStart:B,onClickConnectEnd:A,connectionClickStartHandle:$,connectionMode:z,isValidConnection:E}=C.getState();if(!N||!$&&!o)return;if(!$){B==null||B(ue,{nodeId:N,handleId:S,handleType:e}),C.setState({connectionClickStartHandle:{nodeId:N,type:e,handleId:S}});return}const te=Xb(ue.target),O=n||E||iv,{connection:F,isValid:K}=d0({nodeId:N,id:S,type:e},z,$.nodeId,$.handleId||null,$.type,O,te);K&&G(F),A==null||A(ue),C.setState({connectionClickStartHandle:null})};return ve.createElement("div",{"data-handleid":S,"data-nodeid":N,"data-handlepos":t,"data-id":`${N}-${S}-${e}`,className:Qs(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",L,_,{source:!j,target:j,connectable:r,connectablestart:o,connectableend:l,connecting:W,connectionindicator:r&&(o&&!P||l&&P)}]),onMouseDown:Y,onTouchStart:Y,onClick:T?J:void 0,ref:x,...w},f)});h0.displayName="Handle";var Qm=m.memo(h0);const m0=({data:e,isConnectable:t,targetPosition:n=pt.Top,sourcePosition:r=pt.Bottom})=>ve.createElement(ve.Fragment,null,ve.createElement(Qm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,ve.createElement(Qm,{type:"source",position:r,isConnectable:t}));m0.displayName="DefaultNode";var xg=m.memo(m0);const _0=({data:e,isConnectable:t,sourcePosition:n=pt.Bottom})=>ve.createElement(ve.Fragment,null,e==null?void 0:e.label,ve.createElement(Qm,{type:"source",position:n,isConnectable:t}));_0.displayName="InputNode";var p0=m.memo(_0);const g0=({data:e,isConnectable:t,targetPosition:n=pt.Top})=>ve.createElement(ve.Fragment,null,ve.createElement(Qm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);g0.displayName="OutputNode";var y0=m.memo(g0);const ly=()=>null;ly.displayName="GroupNode";const CM=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),pm=e=>e.id;function EM(e,t){return Ps(e.selectedNodes.map(pm),t.selectedNodes.map(pm))&&Ps(e.selectedEdges.map(pm),t.selectedEdges.map(pm))}const w0=m.memo(({onSelectionChange:e})=>{const t=bs(),{selectedNodes:n,selectedEdges:r}=In(CM,EM);return m.useEffect(()=>{const o={nodes:n,edges:r};e==null||e(o),t.getState().onSelectionChange.forEach(l=>l(o))},[n,r,e]),null});w0.displayName="SelectionListener";const $M=e=>!!e.onSelectionChange;function AM({onSelectionChange:e}){const t=In($M);return e||t?ve.createElement(w0,{onSelectionChange:e}):null}const TM=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 Iu(e,t){m.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function Gt(e,t,n){m.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const MM=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:o,onConnectStart:l,onConnectEnd:u,onClickConnectStart:c,onClickConnectEnd:f,nodesDraggable:_,nodesConnectable:p,nodesFocusable:y,edgesFocusable:w,edgesUpdatable:x,elevateNodesOnSelect:S,minZoom:j,maxZoom:C,nodeExtent:N,onNodesChange:T,onEdgesChange:L,elementsSelectable:P,connectionMode:W,snapGrid:G,snapToGrid:Y,translateExtent:J,connectOnClick:re,defaultEdgeOptions:ae,fitView:ue,fitViewOptions:B,onNodesDelete:A,onEdgesDelete:$,onNodeDrag:z,onNodeDragStart:E,onNodeDragStop:te,onSelectionDrag:O,onSelectionDragStart:F,onSelectionDragStop:K,noPanClassName:R,nodeOrigin:Q,rfId:Z,autoPanOnConnect:X,autoPanOnNodeDrag:le,onError:_e,connectionRadius:he,isValidConnection:ye,nodeDragThreshold:Ee})=>{const{setNodes:ze,setEdges:Be,setDefaultNodesAndEdges:gt,setMinZoom:Fe,setMaxZoom:tt,setTranslateExtent:lt,setNodeExtent:Ye,reset:Se}=In(TM,Ps),Re=bs();return m.useEffect(()=>{const ht=r==null?void 0:r.map(xe=>({...xe,...ae}));return gt(n,ht),()=>{Se()}},[]),Gt("defaultEdgeOptions",ae,Re.setState),Gt("connectionMode",W,Re.setState),Gt("onConnect",o,Re.setState),Gt("onConnectStart",l,Re.setState),Gt("onConnectEnd",u,Re.setState),Gt("onClickConnectStart",c,Re.setState),Gt("onClickConnectEnd",f,Re.setState),Gt("nodesDraggable",_,Re.setState),Gt("nodesConnectable",p,Re.setState),Gt("nodesFocusable",y,Re.setState),Gt("edgesFocusable",w,Re.setState),Gt("edgesUpdatable",x,Re.setState),Gt("elementsSelectable",P,Re.setState),Gt("elevateNodesOnSelect",S,Re.setState),Gt("snapToGrid",Y,Re.setState),Gt("snapGrid",G,Re.setState),Gt("onNodesChange",T,Re.setState),Gt("onEdgesChange",L,Re.setState),Gt("connectOnClick",re,Re.setState),Gt("fitViewOnInit",ue,Re.setState),Gt("fitViewOnInitOptions",B,Re.setState),Gt("onNodesDelete",A,Re.setState),Gt("onEdgesDelete",$,Re.setState),Gt("onNodeDrag",z,Re.setState),Gt("onNodeDragStart",E,Re.setState),Gt("onNodeDragStop",te,Re.setState),Gt("onSelectionDrag",O,Re.setState),Gt("onSelectionDragStart",F,Re.setState),Gt("onSelectionDragStop",K,Re.setState),Gt("noPanClassName",R,Re.setState),Gt("nodeOrigin",Q,Re.setState),Gt("rfId",Z,Re.setState),Gt("autoPanOnConnect",X,Re.setState),Gt("autoPanOnNodeDrag",le,Re.setState),Gt("onError",_e,Re.setState),Gt("connectionRadius",he,Re.setState),Gt("isValidConnection",ye,Re.setState),Gt("nodeDragThreshold",Ee,Re.setState),Iu(e,ze),Iu(t,Be),Iu(j,Fe),Iu(C,tt),Iu(J,lt),Iu(N,Ye),null},ov={display:"none"},RM={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},v0="react-flow__node-desc",x0="react-flow__edge-desc",LM="react-flow__aria-live",IM=e=>e.ariaLiveMessage;function OM({rfId:e}){const t=In(IM);return ve.createElement("div",{id:`${LM}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:RM},t)}function PM({rfId:e,disableKeyboardA11y:t}){return ve.createElement(ve.Fragment,null,ve.createElement("div",{id:`${v0}-${e}`,style:ov},"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."," "),ve.createElement("div",{id:`${x0}-${e}`,style:ov},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&ve.createElement(OM,{rfId:e}))}var Hf=(e=null,t={actInsideInputWithModifier:!0})=>{const[n,r]=m.useState(!1),o=m.useRef(!1),l=m.useRef(new Set([])),[u,c]=m.useMemo(()=>{if(e!==null){const _=(Array.isArray(e)?e:[e]).filter(y=>typeof y=="string").map(y=>y.split("+")),p=_.reduce((y,w)=>y.concat(...w),[]);return[_,p]}return[[],[]]},[e]);return m.useEffect(()=>{const f=typeof document<"u"?document:null,_=(t==null?void 0:t.target)||f;if(e!==null){const p=x=>{if(o.current=x.ctrlKey||x.metaKey||x.shiftKey,(!o.current||o.current&&!t.actInsideInputWithModifier)&&gg(x))return!1;const j=lv(x.code,c);l.current.add(x[j]),av(u,l.current,!1)&&(x.preventDefault(),r(!0))},y=x=>{if((!o.current||o.current&&!t.actInsideInputWithModifier)&&gg(x))return!1;const j=lv(x.code,c);av(u,l.current,!0)?(r(!1),l.current.clear()):l.current.delete(x[j]),x.key==="Meta"&&l.current.clear(),o.current=!1},w=()=>{l.current.clear(),r(!1)};return _==null||_.addEventListener("keydown",p),_==null||_.addEventListener("keyup",y),window.addEventListener("blur",w),()=>{_==null||_.removeEventListener("keydown",p),_==null||_.removeEventListener("keyup",y),window.removeEventListener("blur",w)}}},[e,r]),n};function av(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(o=>t.has(o)))}function lv(e,t){return t.includes(e)?"code":"key"}function b0(e,t,n,r){var u,c;if(!e.parentNode)return n;const o=t.get(e.parentNode),l=Ec(o,r);return b0(o,t,{x:(n.x??0)+l.x,y:(n.y??0)+l.y,z:(((u=o[ds])==null?void 0:u.z)??0)>(n.z??0)?((c=o[ds])==null?void 0:c.z)??0:n.z??0},r)}function j0(e,t,n){e.forEach(r=>{var o;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:l,y:u,z:c}=b0(r,e,{...r.position,z:((o=r[ds])==null?void 0:o.z)??0},t);r.positionAbsolute={x:l,y:u},r[ds].z=c,n!=null&&n[r.id]&&(r[ds].isParent=!0)}})}function xp(e,t,n,r){const o=new Map,l={},u=r?1e3:0;return e.forEach(c=>{var w;const f=(Ti(c.zIndex)?c.zIndex:0)+(c.selected?u:0),_=t.get(c.id),p={...c,positionAbsolute:{x:c.position.x,y:c.position.y}};c.parentNode&&(l[c.parentNode]=!0);const y=(_==null?void 0:_.type)&&(_==null?void 0:_.type)!==c.type;Object.defineProperty(p,ds,{enumerable:!1,value:{handleBounds:y||(w=_==null?void 0:_[ds])==null?void 0:w.handleBounds,z:f}}),o.set(c.id,p)}),j0(o,n,l),o}function S0(e,t={}){const{getNodes:n,width:r,height:o,minZoom:l,maxZoom:u,d3Zoom:c,d3Selection:f,fitViewOnInitDone:_,fitViewOnInit:p,nodeOrigin:y}=e(),w=t.initial&&!_&&p;if(c&&f&&(w||!t.initial)){const S=n().filter(C=>{var T;const N=t.includeHiddenNodes?C.width&&C.height:!C.hidden;return(T=t.nodes)!=null&&T.length?N&&t.nodes.some(L=>L.id===C.id):N}),j=S.every(C=>C.width&&C.height);if(S.length>0&&j){const C=g_(S,y),{x:N,y:T,zoom:L}=c0(C,r,o,t.minZoom??l,t.maxZoom??u,t.padding??.1),P=Na.translate(N,T).scale(L);return typeof t.duration=="number"&&t.duration>0?c.transform(yc(f,t.duration),P):c.transform(f,P),!0}}return!1}function DM(e,t){return e.forEach(n=>{const r=t.get(n.id);r&&t.set(r.id,{...r,[ds]:r[ds],selected:n.selected})}),new Map(t)}function FM(e,t){return t.map(n=>{const r=e.find(o=>o.id===n.id);return r&&(n.selected=r.selected),n})}function gm({changedNodes:e,changedEdges:t,get:n,set:r}){const{nodeInternals:o,edges:l,onNodesChange:u,onEdgesChange:c,hasDefaultNodes:f,hasDefaultEdges:_}=n();e!=null&&e.length&&(f&&r({nodeInternals:DM(e,o)}),u==null||u(e)),t!=null&&t.length&&(_&&r({edges:FM(t,l)}),c==null||c(t))}const Ou=()=>{},zM={zoomIn:Ou,zoomOut:Ou,zoomTo:Ou,getZoom:()=>1,setViewport:Ou,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:Ou,fitBounds:Ou,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},BM=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),UM=()=>{const e=bs(),{d3Zoom:t,d3Selection:n}=In(BM,Ps);return m.useMemo(()=>n&&t?{zoomIn:o=>t.scaleBy(yc(n,o==null?void 0:o.duration),1.2),zoomOut:o=>t.scaleBy(yc(n,o==null?void 0:o.duration),1/1.2),zoomTo:(o,l)=>t.scaleTo(yc(n,l==null?void 0:l.duration),o),getZoom:()=>e.getState().transform[2],setViewport:(o,l)=>{const[u,c,f]=e.getState().transform,_=Na.translate(o.x??u,o.y??c).scale(o.zoom??f);t.transform(yc(n,l==null?void 0:l.duration),_)},getViewport:()=>{const[o,l,u]=e.getState().transform;return{x:o,y:l,zoom:u}},fitView:o=>S0(e.getState,o),setCenter:(o,l,u)=>{const{width:c,height:f,maxZoom:_}=e.getState(),p=typeof(u==null?void 0:u.zoom)<"u"?u.zoom:_,y=c/2-o*p,w=f/2-l*p,x=Na.translate(y,w).scale(p);t.transform(yc(n,u==null?void 0:u.duration),x)},fitBounds:(o,l)=>{const{width:u,height:c,minZoom:f,maxZoom:_}=e.getState(),{x:p,y,zoom:w}=c0(o,u,c,f,_,(l==null?void 0:l.padding)??.1),x=Na.translate(p,y).scale(w);t.transform(yc(n,l==null?void 0:l.duration),x)},project:o=>{const{transform:l,snapToGrid:u,snapGrid:c}=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"),vg(o,l,u,c)},screenToFlowPosition:o=>{const{transform:l,snapToGrid:u,snapGrid:c,domNode:f}=e.getState();if(!f)return o;const{x:_,y:p}=f.getBoundingClientRect(),y={x:o.x-_,y:o.y-p};return vg(y,l,u,c)},flowToScreenPosition:o=>{const{transform:l,domNode:u}=e.getState();if(!u)return o;const{x:c,y:f}=u.getBoundingClientRect(),_=o0(o,l);return{x:_.x+c,y:_.y+f}},viewportInitialized:!0}:zM,[t,n])};function cy(){const e=UM(),t=bs(),n=m.useCallback(()=>t.getState().getNodes().map(j=>({...j})),[]),r=m.useCallback(j=>t.getState().nodeInternals.get(j),[]),o=m.useCallback(()=>{const{edges:j=[]}=t.getState();return j.map(C=>({...C}))},[]),l=m.useCallback(j=>{const{edges:C=[]}=t.getState();return C.find(N=>N.id===j)},[]),u=m.useCallback(j=>{const{getNodes:C,setNodes:N,hasDefaultNodes:T,onNodesChange:L}=t.getState(),P=C(),W=typeof j=="function"?j(P):j;if(T)N(W);else if(L){const G=W.length===0?P.map(Y=>({type:"remove",id:Y.id})):W.map(Y=>({item:Y,type:"reset"}));L(G)}},[]),c=m.useCallback(j=>{const{edges:C=[],setEdges:N,hasDefaultEdges:T,onEdgesChange:L}=t.getState(),P=typeof j=="function"?j(C):j;if(T)N(P);else if(L){const W=P.length===0?C.map(G=>({type:"remove",id:G.id})):P.map(G=>({item:G,type:"reset"}));L(W)}},[]),f=m.useCallback(j=>{const C=Array.isArray(j)?j:[j],{getNodes:N,setNodes:T,hasDefaultNodes:L,onNodesChange:P}=t.getState();if(L){const G=[...N(),...C];T(G)}else if(P){const W=C.map(G=>({item:G,type:"add"}));P(W)}},[]),_=m.useCallback(j=>{const C=Array.isArray(j)?j:[j],{edges:N=[],setEdges:T,hasDefaultEdges:L,onEdgesChange:P}=t.getState();if(L)T([...N,...C]);else if(P){const W=C.map(G=>({item:G,type:"add"}));P(W)}},[]),p=m.useCallback(()=>{const{getNodes:j,edges:C=[],transform:N}=t.getState(),[T,L,P]=N;return{nodes:j().map(W=>({...W})),edges:C.map(W=>({...W})),viewport:{x:T,y:L,zoom:P}}},[]),y=m.useCallback(({nodes:j,edges:C})=>{const{nodeInternals:N,getNodes:T,edges:L,hasDefaultNodes:P,hasDefaultEdges:W,onNodesDelete:G,onEdgesDelete:Y,onNodesChange:J,onEdgesChange:re}=t.getState(),ae=(j||[]).map(z=>z.id),ue=(C||[]).map(z=>z.id),B=T().reduce((z,E)=>{const te=!ae.includes(E.id)&&E.parentNode&&z.find(F=>F.id===E.parentNode);return(typeof E.deletable=="boolean"?E.deletable:!0)&&(ae.includes(E.id)||te)&&z.push(E),z},[]),A=L.filter(z=>typeof z.deletable=="boolean"?z.deletable:!0),$=A.filter(z=>ue.includes(z.id));if(B||$){const z=l0(B,A),E=[...$,...z],te=E.reduce((O,F)=>(O.includes(F.id)||O.push(F.id),O),[]);if((W||P)&&(W&&t.setState({edges:L.filter(O=>!te.includes(O.id))}),P&&(B.forEach(O=>{N.delete(O.id)}),t.setState({nodeInternals:new Map(N)}))),te.length>0&&(Y==null||Y(E),re&&re(te.map(O=>({id:O,type:"remove"})))),B.length>0&&(G==null||G(B),J)){const O=B.map(F=>({id:F.id,type:"remove"}));J(O)}}},[]),w=m.useCallback(j=>{const C=lM(j),N=C?null:t.getState().nodeInternals.get(j.id);return!C&&!N?[null,null,C]:[C?j:Qw(N),N,C]},[]),x=m.useCallback((j,C=!0,N)=>{const[T,L,P]=w(j);return T?(N||t.getState().getNodes()).filter(W=>{if(!P&&(W.id===L.id||!W.positionAbsolute))return!1;const G=Qw(W),Y=pg(G,T);return C&&Y>0||Y>=T.width*T.height}):[]},[]),S=m.useCallback((j,C,N=!0)=>{const[T]=w(j);if(!T)return!1;const L=pg(T,C);return N&&L>0||L>=T.width*T.height},[]);return m.useMemo(()=>({...e,getNodes:n,getNode:r,getEdges:o,getEdge:l,setNodes:u,setEdges:c,addNodes:f,addEdges:_,toObject:p,deleteElements:y,getIntersectingNodes:x,isNodeIntersecting:S}),[e,n,r,o,l,u,c,f,_,p,y,x,S])}const WM={actInsideInputWithModifier:!1};var qM=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=bs(),{deleteElements:r}=cy(),o=Hf(e,WM),l=Hf(t);m.useEffect(()=>{if(o){const{edges:u,getNodes:c}=n.getState(),f=c().filter(p=>p.selected),_=u.filter(p=>p.selected);r({nodes:f,edges:_}),n.setState({nodesSelectionActive:!1})}},[o]),m.useEffect(()=>{n.setState({multiSelectionActive:l})},[l])};function HM(e){const t=bs();m.useEffect(()=>{let n;const r=()=>{var l,u;if(!e.current)return;const o=ty(e.current);(o.height===0||o.width===0)&&((u=(l=t.getState()).onError)==null||u.call(l,"004",Aa.error004())),t.setState({width:o.width||500,height:o.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 uy={position:"absolute",width:"100%",height:"100%",top:0,left:0},VM=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,ym=e=>({x:e.x,y:e.y,zoom:e.k}),Pu=(e,t)=>e.target.closest(`.${t}`),cv=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),uv=e=>{const t=e.ctrlKey&&Xm()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},GM=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),KM=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:r,zoomOnScroll:o=!0,zoomOnPinch:l=!0,panOnScroll:u=!1,panOnScrollSpeed:c=.5,panOnScrollMode:f=jc.Free,zoomOnDoubleClick:_=!0,elementsSelectable:p,panOnDrag:y=!0,defaultViewport:w,translateExtent:x,minZoom:S,maxZoom:j,zoomActivationKeyCode:C,preventScrolling:N=!0,children:T,noWheelClassName:L,noPanClassName:P})=>{const W=m.useRef(),G=bs(),Y=m.useRef(!1),J=m.useRef(!1),re=m.useRef(null),ae=m.useRef({x:0,y:0,zoom:0}),{d3Zoom:ue,d3Selection:B,d3ZoomHandler:A,userSelectionActive:$}=In(GM,Ps),z=Hf(C),E=m.useRef(0),te=m.useRef(!1),O=m.useRef();return HM(re),m.useEffect(()=>{if(re.current){const F=re.current.getBoundingClientRect(),K=Kb().scaleExtent([S,j]).translateExtent(x),R=Ai(re.current).call(K),Q=Na.translate(w.x,w.y).scale(td(w.zoom,S,j)),Z=[[0,0],[F.width,F.height]],X=K.constrain()(Q,Z,x);K.transform(R,X),K.wheelDelta(uv),G.setState({d3Zoom:K,d3Selection:R,d3ZoomHandler:R.on("wheel.zoom"),transform:[X.x,X.y,X.k],domNode:re.current.closest(".react-flow")})}},[]),m.useEffect(()=>{B&&ue&&(u&&!z&&!$?B.on("wheel.zoom",F=>{if(Pu(F,L))return!1;F.preventDefault(),F.stopImmediatePropagation();const K=B.property("__zoom").k||1,R=Xm();if(F.ctrlKey&&l&&R){const Ee=so(F),ze=uv(F),Be=K*Math.pow(2,ze);ue.scaleTo(B,Be,Ee,F);return}const Q=F.deltaMode===1?20:1;let Z=f===jc.Vertical?0:F.deltaX*Q,X=f===jc.Horizontal?0:F.deltaY*Q;!R&&F.shiftKey&&f!==jc.Vertical&&(Z=F.deltaY*Q,X=0),ue.translateBy(B,-(Z/K)*c,-(X/K)*c,{internal:!0});const le=ym(B.property("__zoom")),{onViewportChangeStart:_e,onViewportChange:he,onViewportChangeEnd:ye}=G.getState();clearTimeout(O.current),te.current||(te.current=!0,t==null||t(F,le),_e==null||_e(le)),te.current&&(e==null||e(F,le),he==null||he(le),O.current=setTimeout(()=>{n==null||n(F,le),ye==null||ye(le),te.current=!1},150))},{passive:!1}):typeof A<"u"&&B.on("wheel.zoom",function(F,K){if(!N||Pu(F,L))return null;F.preventDefault(),A.call(this,F,K)},{passive:!1}))},[$,u,f,B,ue,A,z,l,N,L,t,e,n]),m.useEffect(()=>{ue&&ue.on("start",F=>{var Q,Z;if(!F.sourceEvent||F.sourceEvent.internal)return null;E.current=(Q=F.sourceEvent)==null?void 0:Q.button;const{onViewportChangeStart:K}=G.getState(),R=ym(F.transform);Y.current=!0,ae.current=R,((Z=F.sourceEvent)==null?void 0:Z.type)==="mousedown"&&G.setState({paneDragging:!0}),K==null||K(R),t==null||t(F.sourceEvent,R)})},[ue,t]),m.useEffect(()=>{ue&&($&&!Y.current?ue.on("zoom",null):$||ue.on("zoom",F=>{var R;const{onViewportChange:K}=G.getState();if(G.setState({transform:[F.transform.x,F.transform.y,F.transform.k]}),J.current=!!(r&&cv(y,E.current??0)),(e||K)&&!((R=F.sourceEvent)!=null&&R.internal)){const Q=ym(F.transform);K==null||K(Q),e==null||e(F.sourceEvent,Q)}}))},[$,ue,e,y,r]),m.useEffect(()=>{ue&&ue.on("end",F=>{if(!F.sourceEvent||F.sourceEvent.internal)return null;const{onViewportChangeEnd:K}=G.getState();if(Y.current=!1,G.setState({paneDragging:!1}),r&&cv(y,E.current??0)&&!J.current&&r(F.sourceEvent),J.current=!1,(n||K)&&VM(ae.current,F.transform)){const R=ym(F.transform);ae.current=R,clearTimeout(W.current),W.current=setTimeout(()=>{K==null||K(R),n==null||n(F.sourceEvent,R)},u?150:0)}})},[ue,u,y,n,r]),m.useEffect(()=>{ue&&ue.filter(F=>{const K=z||o,R=l&&F.ctrlKey;if((y===!0||Array.isArray(y)&&y.includes(1))&&F.button===1&&F.type==="mousedown"&&(Pu(F,"react-flow__node")||Pu(F,"react-flow__edge")))return!0;if(!y&&!K&&!u&&!_&&!l||$||!_&&F.type==="dblclick"||Pu(F,L)&&F.type==="wheel"||Pu(F,P)&&(F.type!=="wheel"||u&&F.type==="wheel"&&!z)||!l&&F.ctrlKey&&F.type==="wheel"||!K&&!u&&!R&&F.type==="wheel"||!y&&(F.type==="mousedown"||F.type==="touchstart")||Array.isArray(y)&&!y.includes(F.button)&&(F.type==="mousedown"||F.type==="touchstart"))return!1;const Q=Array.isArray(y)&&y.includes(F.button)||!F.button||F.button<=1;return(!F.ctrlKey||F.type==="wheel")&&Q})},[$,ue,o,l,u,_,y,p,z]),ve.createElement("div",{className:"react-flow__renderer",ref:re,style:uy},T)},YM=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function JM(){const{userSelectionActive:e,userSelectionRect:t}=In(YM,Ps);return e&&t?ve.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 dv(e,t){const n=e.find(r=>r.id===t.parentNode);if(n){const r=t.position.x+t.width-n.width,o=t.position.y+t.height-n.height;if(r>0||o>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),o>0&&(n.style.height+=o),t.position.x<0){const l=Math.abs(t.position.x);n.position.x=n.position.x-l,n.style.width+=l,t.position.x=0}if(t.position.y<0){const l=Math.abs(t.position.y);n.position.y=n.position.y-l,n.style.height+=l,t.position.y=0}n.width=n.style.width,n.height=n.style.height}}}function XM(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,o)=>{const l=e.filter(c=>c.id===o.id);if(l.length===0)return r.push(o),r;const u={...o};for(const c of l)if(c)switch(c.type){case"select":{u.selected=c.selected;break}case"position":{typeof c.position<"u"&&(u.position=c.position),typeof c.positionAbsolute<"u"&&(u.positionAbsolute=c.positionAbsolute),typeof c.dragging<"u"&&(u.dragging=c.dragging),u.expandParent&&dv(r,u);break}case"dimensions":{typeof c.dimensions<"u"&&(u.width=c.dimensions.width,u.height=c.dimensions.height),typeof c.updateStyle<"u"&&(u.style={...u.style||{},...c.dimensions}),typeof c.resizing=="boolean"&&(u.resizing=c.resizing),u.expandParent&&dv(r,u);break}case"remove":return r}return r.push(u),r},n)}function ZM(e,t){return XM(e,t)}const _l=(e,t)=>({id:e,type:"select",selected:t});function Wu(e,t){return e.reduce((n,r)=>{const o=t.includes(r.id);return!r.selected&&o?(r.selected=!0,n.push(_l(r.id,!0))):r.selected&&!o&&(r.selected=!1,n.push(_l(r.id,!1))),n},[])}const bp=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},QM=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),k0=m.memo(({isSelecting:e,selectionMode:t=Wf.Full,panOnDrag:n,onSelectionStart:r,onSelectionEnd:o,onPaneClick:l,onPaneContextMenu:u,onPaneScroll:c,onPaneMouseEnter:f,onPaneMouseMove:_,onPaneMouseLeave:p,children:y})=>{const w=m.useRef(null),x=bs(),S=m.useRef(0),j=m.useRef(0),C=m.useRef(),{userSelectionActive:N,elementsSelectable:T,dragging:L}=In(QM,Ps),P=()=>{x.setState({userSelectionActive:!1,userSelectionRect:null}),S.current=0,j.current=0},W=A=>{l==null||l(A),x.getState().resetSelectedElements(),x.setState({nodesSelectionActive:!1})},G=A=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){A.preventDefault();return}u==null||u(A)},Y=c?A=>c(A):void 0,J=A=>{const{resetSelectedElements:$,domNode:z}=x.getState();if(C.current=z==null?void 0:z.getBoundingClientRect(),!T||!e||A.button!==0||A.target!==w.current||!C.current)return;const{x:E,y:te}=yl(A,C.current);$(),x.setState({userSelectionRect:{width:0,height:0,startX:E,startY:te,x:E,y:te}}),r==null||r(A)},re=A=>{const{userSelectionRect:$,nodeInternals:z,edges:E,transform:te,onNodesChange:O,onEdgesChange:F,nodeOrigin:K,getNodes:R}=x.getState();if(!e||!C.current||!$)return;x.setState({userSelectionActive:!0,nodesSelectionActive:!1});const Q=yl(A,C.current),Z=$.startX??0,X=$.startY??0,le={...$,x:Q.x<Z?Q.x:Z,y:Q.y<X?Q.y:X,width:Math.abs(Q.x-Z),height:Math.abs(Q.y-X)},_e=R(),he=a0(z,le,te,t===Wf.Partial,!0,K),ye=l0(he,E).map(ze=>ze.id),Ee=he.map(ze=>ze.id);if(S.current!==Ee.length){S.current=Ee.length;const ze=Wu(_e,Ee);ze.length&&(O==null||O(ze))}if(j.current!==ye.length){j.current=ye.length;const ze=Wu(E,ye);ze.length&&(F==null||F(ze))}x.setState({userSelectionRect:le})},ae=A=>{if(A.button!==0)return;const{userSelectionRect:$}=x.getState();!N&&$&&A.target===w.current&&(W==null||W(A)),x.setState({nodesSelectionActive:S.current>0}),P(),o==null||o(A)},ue=A=>{N&&(x.setState({nodesSelectionActive:S.current>0}),o==null||o(A)),P()},B=T&&(e||N);return ve.createElement("div",{className:Qs(["react-flow__pane",{dragging:L,selection:e}]),onClick:B?void 0:bp(W,w),onContextMenu:bp(G,w),onWheel:bp(Y,w),onMouseEnter:B?void 0:f,onMouseDown:B?J:void 0,onMouseMove:B?re:_,onMouseUp:B?ae:void 0,onMouseLeave:B?ue:p,ref:w,style:uy},y,ve.createElement(JM,null))});k0.displayName="Pane";function N0(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:N0(n,t):!1}function fv(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 eR(e,t,n,r){return Array.from(e.values()).filter(o=>(o.selected||o.id===r)&&(!o.parentNode||!N0(o,e))&&(o.draggable||t&&typeof o.draggable>"u")).map(o=>{var l,u;return{id:o.id,position:o.position||{x:0,y:0},positionAbsolute:o.positionAbsolute||{x:0,y:0},distance:{x:n.x-(((l=o.positionAbsolute)==null?void 0:l.x)??0),y:n.y-(((u=o.positionAbsolute)==null?void 0:u.y)??0)},delta:{x:0,y:0},extent:o.extent,parentNode:o.parentNode,width:o.width,height:o.height,expandParent:o.expandParent}})}function tR(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function C0(e,t,n,r,o=[0,0],l){const u=tR(e,e.extent||r);let c=u;if(e.extent==="parent"&&!e.expandParent)if(e.parentNode&&e.width&&e.height){const p=n.get(e.parentNode),{x:y,y:w}=Ec(p,o).positionAbsolute;c=p&&Ti(y)&&Ti(w)&&Ti(p.width)&&Ti(p.height)?[[y+e.width*o[0],w+e.height*o[1]],[y+p.width-e.width+e.width*o[0],w+p.height-e.height+e.height*o[1]]]:c}else l==null||l("005",Aa.error005()),c=u;else if(e.extent&&e.parentNode&&e.extent!=="parent"){const p=n.get(e.parentNode),{x:y,y:w}=Ec(p,o).positionAbsolute;c=[[e.extent[0][0]+y,e.extent[0][1]+w],[e.extent[1][0]+y,e.extent[1][1]+w]]}let f={x:0,y:0};if(e.parentNode){const p=n.get(e.parentNode);f=Ec(p,o).positionAbsolute}const _=c&&c!=="parent"?ny(t,c):t;return{position:{x:_.x-f.x,y:_.y-f.y},positionAbsolute:_}}function jp({nodeId:e,dragItems:t,nodeInternals:n}){const r=t.map(o=>({...n.get(o.id),position:o.position,positionAbsolute:o.positionAbsolute}));return[e?r.find(o=>o.id===e):r[0],r]}const hv=(e,t,n,r)=>{const o=t.querySelectorAll(e);if(!o||!o.length)return null;const l=Array.from(o),u=t.getBoundingClientRect(),c={x:u.width*r[0],y:u.height*r[1]};return l.map(f=>{const _=f.getBoundingClientRect();return{id:f.getAttribute("data-handleid"),position:f.getAttribute("data-handlepos"),x:(_.left-u.left-c.x)/n,y:(_.top-u.top-c.y)/n,...ty(f)}})};function vf(e,t,n){return n===void 0?n:r=>{const o=t().nodeInternals.get(e);o&&n(r,{...o})}}function bg({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:o,unselectNodesAndEdges:l,multiSelectionActive:u,nodeInternals:c,onError:f}=t.getState(),_=c.get(e);if(!_){f==null||f("012",Aa.error012(e));return}t.setState({nodesSelectionActive:!1}),_.selected?(n||_.selected&&u)&&(l({nodes:[_],edges:[]}),requestAnimationFrame(()=>{var p;return(p=r==null?void 0:r.current)==null?void 0:p.blur()})):o([e])}function nR(){const e=bs();return m.useCallback(({sourceEvent:n})=>{const{transform:r,snapGrid:o,snapToGrid:l}=e.getState(),u=n.touches?n.touches[0].clientX:n.clientX,c=n.touches?n.touches[0].clientY:n.clientY,f={x:(u-r[0])/r[2],y:(c-r[1])/r[2]};return{xSnapped:l?o[0]*Math.round(f.x/o[0]):f.x,ySnapped:l?o[1]*Math.round(f.y/o[1]):f.y,...f}},[])}function Sp(e){return(t,n,r)=>e==null?void 0:e(t,r)}function E0({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:o,isSelectable:l,selectNodesOnDrag:u}){const c=bs(),[f,_]=m.useState(!1),p=m.useRef([]),y=m.useRef({x:null,y:null}),w=m.useRef(0),x=m.useRef(null),S=m.useRef({x:0,y:0}),j=m.useRef(null),C=m.useRef(!1),N=m.useRef(!1),T=nR();return m.useEffect(()=>{if(e!=null&&e.current){const L=Ai(e.current),P=({x:Y,y:J})=>{const{nodeInternals:re,onNodeDrag:ae,onSelectionDrag:ue,updateNodePositions:B,nodeExtent:A,snapGrid:$,snapToGrid:z,nodeOrigin:E,onError:te}=c.getState();y.current={x:Y,y:J};let O=!1,F={x:0,y:0,x2:0,y2:0};if(p.current.length>1&&A){const R=g_(p.current,E);F=Uf(R)}if(p.current=p.current.map(R=>{const Q={x:Y-R.distance.x,y:J-R.distance.y};z&&(Q.x=$[0]*Math.round(Q.x/$[0]),Q.y=$[1]*Math.round(Q.y/$[1]));const Z=[[A[0][0],A[0][1]],[A[1][0],A[1][1]]];p.current.length>1&&A&&!R.extent&&(Z[0][0]=R.positionAbsolute.x-F.x+A[0][0],Z[1][0]=R.positionAbsolute.x+(R.width??0)-F.x2+A[1][0],Z[0][1]=R.positionAbsolute.y-F.y+A[0][1],Z[1][1]=R.positionAbsolute.y+(R.height??0)-F.y2+A[1][1]);const X=C0(R,Q,re,Z,E,te);return O=O||R.position.x!==X.position.x||R.position.y!==X.position.y,R.position=X.position,R.positionAbsolute=X.positionAbsolute,R}),!O)return;B(p.current,!0,!0),_(!0);const K=o?ae:Sp(ue);if(K&&j.current){const[R,Q]=jp({nodeId:o,dragItems:p.current,nodeInternals:re});K(j.current,R,Q)}},W=()=>{if(!x.current)return;const[Y,J]=Jb(S.current,x.current);if(Y!==0||J!==0){const{transform:re,panBy:ae}=c.getState();y.current.x=(y.current.x??0)-Y/re[2],y.current.y=(y.current.y??0)-J/re[2],ae({x:Y,y:J})&&P(y.current)}w.current=requestAnimationFrame(W)},G=Y=>{var E;const{nodeInternals:J,multiSelectionActive:re,nodesDraggable:ae,unselectNodesAndEdges:ue,onNodeDragStart:B,onSelectionDragStart:A}=c.getState();N.current=!0;const $=o?B:Sp(A);(!u||!l)&&!re&&o&&((E=J.get(o))!=null&&E.selected||ue()),o&&l&&u&&bg({id:o,store:c,nodeRef:e});const z=T(Y);if(y.current=z,p.current=eR(J,ae,z,o),$&&p.current){const[te,O]=jp({nodeId:o,dragItems:p.current,nodeInternals:J});$(Y.sourceEvent,te,O)}};if(t)L.on(".drag",null);else{const Y=fA().on("start",J=>{const{domNode:re,nodeDragThreshold:ae}=c.getState();ae===0&&G(J);const ue=T(J);y.current=ue,x.current=(re==null?void 0:re.getBoundingClientRect())||null,S.current=yl(J.sourceEvent,x.current)}).on("drag",J=>{var B,A;const re=T(J),{autoPanOnNodeDrag:ae,nodeDragThreshold:ue}=c.getState();if(!C.current&&N.current&&ae&&(C.current=!0,W()),!N.current){const $=re.xSnapped-(((B=y==null?void 0:y.current)==null?void 0:B.x)??0),z=re.ySnapped-(((A=y==null?void 0:y.current)==null?void 0:A.y)??0);Math.sqrt($*$+z*z)>ue&&G(J)}(y.current.x!==re.xSnapped||y.current.y!==re.ySnapped)&&p.current&&N.current&&(j.current=J.sourceEvent,S.current=yl(J.sourceEvent,x.current),P(re))}).on("end",J=>{if(N.current&&(_(!1),C.current=!1,N.current=!1,cancelAnimationFrame(w.current),p.current)){const{updateNodePositions:re,nodeInternals:ae,onNodeDragStop:ue,onSelectionDragStop:B}=c.getState(),A=o?ue:Sp(B);if(re(p.current,!1,!1),A){const[$,z]=jp({nodeId:o,dragItems:p.current,nodeInternals:ae});A(J.sourceEvent,$,z)}}}).filter(J=>{const re=J.target;return!J.button&&(!n||!fv(re,`.${n}`,e))&&(!r||fv(re,r,e))});return L.call(Y),()=>{L.on(".drag",null)}}}},[e,t,n,r,l,c,o,u,T]),f}function $0(){const e=bs();return m.useCallback(n=>{const{nodeInternals:r,nodeExtent:o,updateNodePositions:l,getNodes:u,snapToGrid:c,snapGrid:f,onError:_,nodesDraggable:p}=e.getState(),y=u().filter(T=>T.selected&&(T.draggable||p&&typeof T.draggable>"u")),w=c?f[0]:5,x=c?f[1]:5,S=n.isShiftPressed?4:1,j=n.x*w*S,C=n.y*x*S,N=y.map(T=>{if(T.positionAbsolute){const L={x:T.positionAbsolute.x+j,y:T.positionAbsolute.y+C};c&&(L.x=f[0]*Math.round(L.x/f[0]),L.y=f[1]*Math.round(L.y/f[1]));const{positionAbsolute:P,position:W}=C0(T,L,r,o,void 0,_);T.position=W,T.positionAbsolute=P}return T});l(N,!0,!1)},[])}const Yu={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var xf=e=>{const t=({id:n,type:r,data:o,xPos:l,yPos:u,xPosOrigin:c,yPosOrigin:f,selected:_,onClick:p,onMouseEnter:y,onMouseMove:w,onMouseLeave:x,onContextMenu:S,onDoubleClick:j,style:C,className:N,isDraggable:T,isSelectable:L,isConnectable:P,isFocusable:W,selectNodesOnDrag:G,sourcePosition:Y,targetPosition:J,hidden:re,resizeObserver:ae,dragHandle:ue,zIndex:B,isParent:A,noDragClassName:$,noPanClassName:z,initialized:E,disableKeyboardA11y:te,ariaLabel:O,rfId:F,hasHandleBounds:K})=>{const R=bs(),Q=m.useRef(null),Z=m.useRef(Y),X=m.useRef(J),le=m.useRef(r),_e=L||T||p||y||w||x,he=$0(),ye=vf(n,R.getState,y),Ee=vf(n,R.getState,w),ze=vf(n,R.getState,x),Be=vf(n,R.getState,S),gt=vf(n,R.getState,j),Fe=Ye=>{const{nodeDragThreshold:Se}=R.getState();if(L&&(!G||!T||Se>0)&&bg({id:n,store:R,nodeRef:Q}),p){const Re=R.getState().nodeInternals.get(n);Re&&p(Ye,{...Re})}},tt=Ye=>{if(!gg(Ye))if(e0.includes(Ye.key)&&L){const Se=Ye.key==="Escape";bg({id:n,store:R,unselect:Se,nodeRef:Q})}else!te&&T&&_&&Object.prototype.hasOwnProperty.call(Yu,Ye.key)&&(R.setState({ariaLiveMessage:`Moved selected node ${Ye.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~l}, y: ${~~u}`}),he({x:Yu[Ye.key].x,y:Yu[Ye.key].y,isShiftPressed:Ye.shiftKey}))};m.useEffect(()=>()=>{Q.current&&(ae==null||ae.unobserve(Q.current))},[]),m.useEffect(()=>{if(Q.current&&!re){const Ye=Q.current;(!E||!K)&&(ae==null||ae.unobserve(Ye),ae==null||ae.observe(Ye))}},[re,E,K]),m.useEffect(()=>{const Ye=le.current!==r,Se=Z.current!==Y,Re=X.current!==J;Q.current&&(Ye||Se||Re)&&(Ye&&(le.current=r),Se&&(Z.current=Y),Re&&(X.current=J),R.getState().updateNodeDimensions([{id:n,nodeElement:Q.current,forceUpdate:!0}]))},[n,r,Y,J]);const lt=E0({nodeRef:Q,disabled:re||!T,noDragClassName:$,handleSelector:ue,nodeId:n,isSelectable:L,selectNodesOnDrag:G});return re?null:ve.createElement("div",{className:Qs(["react-flow__node",`react-flow__node-${r}`,{[z]:T},N,{selected:_,selectable:L,parent:A,dragging:lt}]),ref:Q,style:{zIndex:B,transform:`translate(${c}px,${f}px)`,pointerEvents:_e?"all":"none",visibility:E?"visible":"hidden",...C},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:ye,onMouseMove:Ee,onMouseLeave:ze,onContextMenu:Be,onClick:Fe,onDoubleClick:gt,onKeyDown:W?tt:void 0,tabIndex:W?0:void 0,role:W?"button":void 0,"aria-describedby":te?void 0:`${v0}-${F}`,"aria-label":O},ve.createElement(_M,{value:n},ve.createElement(e,{id:n,data:o,type:r,xPos:l,yPos:u,selected:_,isConnectable:P,sourcePosition:Y,targetPosition:J,dragging:lt,dragHandle:ue,zIndex:B})))};return t.displayName="NodeWrapper",m.memo(t)};const sR=e=>{const t=e.getNodes().filter(n=>n.selected);return{...g_(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function rR({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=bs(),{width:o,height:l,x:u,y:c,transformString:f,userSelectionActive:_}=In(sR,Ps),p=$0(),y=m.useRef(null);if(m.useEffect(()=>{var S;n||(S=y.current)==null||S.focus({preventScroll:!0})},[n]),E0({nodeRef:y}),_||!o||!l)return null;const w=e?S=>{const j=r.getState().getNodes().filter(C=>C.selected);e(S,j)}:void 0,x=S=>{Object.prototype.hasOwnProperty.call(Yu,S.key)&&p({x:Yu[S.key].x,y:Yu[S.key].y,isShiftPressed:S.shiftKey})};return ve.createElement("div",{className:Qs(["react-flow__nodesselection","react-flow__container",t]),style:{transform:f}},ve.createElement("div",{ref:y,className:"react-flow__nodesselection-rect",onContextMenu:w,tabIndex:n?void 0:-1,onKeyDown:n?void 0:x,style:{width:o,height:l,top:c,left:u}}))}var iR=m.memo(rR);const oR=e=>e.nodesSelectionActive,A0=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,deleteKeyCode:c,onMove:f,onMoveStart:_,onMoveEnd:p,selectionKeyCode:y,selectionOnDrag:w,selectionMode:x,onSelectionStart:S,onSelectionEnd:j,multiSelectionKeyCode:C,panActivationKeyCode:N,zoomActivationKeyCode:T,elementsSelectable:L,zoomOnScroll:P,zoomOnPinch:W,panOnScroll:G,panOnScrollSpeed:Y,panOnScrollMode:J,zoomOnDoubleClick:re,panOnDrag:ae,defaultViewport:ue,translateExtent:B,minZoom:A,maxZoom:$,preventScrolling:z,onSelectionContextMenu:E,noWheelClassName:te,noPanClassName:O,disableKeyboardA11y:F})=>{const K=In(oR),R=Hf(y),Q=Hf(N),Z=Q||ae,X=Q||G,le=R||w&&Z!==!0;return qM({deleteKeyCode:c,multiSelectionKeyCode:C}),ve.createElement(KM,{onMove:f,onMoveStart:_,onMoveEnd:p,onPaneContextMenu:l,elementsSelectable:L,zoomOnScroll:P,zoomOnPinch:W,panOnScroll:X,panOnScrollSpeed:Y,panOnScrollMode:J,zoomOnDoubleClick:re,panOnDrag:!R&&Z,defaultViewport:ue,translateExtent:B,minZoom:A,maxZoom:$,zoomActivationKeyCode:T,preventScrolling:z,noWheelClassName:te,noPanClassName:O},ve.createElement(k0,{onSelectionStart:S,onSelectionEnd:j,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,panOnDrag:Z,isSelecting:!!le,selectionMode:x},e,K&&ve.createElement(iR,{onSelectionContextMenu:E,noPanClassName:O,disableKeyboardA11y:F})))};A0.displayName="FlowRenderer";var aR=m.memo(A0);function lR(e){return In(m.useCallback(n=>e?a0(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function cR(e){const t={input:xf(e.input||p0),default:xf(e.default||xg),output:xf(e.output||y0),group:xf(e.group||ly)},n={},r=Object.keys(e).filter(o=>!["input","default","output","group"].includes(o)).reduce((o,l)=>(o[l]=xf(e[l]||xg),o),n);return{...t,...r}}const uR=({x:e,y:t,width:n,height:r,origin:o})=>!n||!r?{x:e,y:t}:o[0]<0||o[1]<0||o[0]>1||o[1]>1?{x:e,y:t}:{x:e-n*o[0],y:t-r*o[1]},dR=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),T0=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,updateNodeDimensions:l,onError:u}=In(dR,Ps),c=lR(e.onlyRenderVisibleElements),f=m.useRef(),_=m.useMemo(()=>{if(typeof ResizeObserver>"u")return null;const p=new ResizeObserver(y=>{const w=y.map(x=>({id:x.target.getAttribute("data-id"),nodeElement:x.target,forceUpdate:!0}));l(w)});return f.current=p,p},[]);return m.useEffect(()=>()=>{var p;(p=f==null?void 0:f.current)==null||p.disconnect()},[]),ve.createElement("div",{className:"react-flow__nodes",style:uy},c.map(p=>{var W,G,Y;let y=p.type||"default";e.nodeTypes[y]||(u==null||u("003",Aa.error003(y)),y="default");const w=e.nodeTypes[y]||e.nodeTypes.default,x=!!(p.draggable||t&&typeof p.draggable>"u"),S=!!(p.selectable||o&&typeof p.selectable>"u"),j=!!(p.connectable||n&&typeof p.connectable>"u"),C=!!(p.focusable||r&&typeof p.focusable>"u"),N=e.nodeExtent?ny(p.positionAbsolute,e.nodeExtent):p.positionAbsolute,T=(N==null?void 0:N.x)??0,L=(N==null?void 0:N.y)??0,P=uR({x:T,y:L,width:p.width??0,height:p.height??0,origin:e.nodeOrigin});return ve.createElement(w,{key:p.id,id:p.id,className:p.className,style:p.style,type:y,data:p.data,sourcePosition:p.sourcePosition||pt.Bottom,targetPosition:p.targetPosition||pt.Top,hidden:p.hidden,xPos:T,yPos:L,xPosOrigin:P.x,yPosOrigin:P.y,selectNodesOnDrag:e.selectNodesOnDrag,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,selected:!!p.selected,isDraggable:x,isSelectable:S,isConnectable:j,isFocusable:C,resizeObserver:_,dragHandle:p.dragHandle,zIndex:((W=p[ds])==null?void 0:W.z)??0,isParent:!!((G=p[ds])!=null&&G.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!p.width&&!!p.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:p.ariaLabel,hasHandleBounds:!!((Y=p[ds])!=null&&Y.handleBounds)})}))};T0.displayName="NodeRenderer";var fR=m.memo(T0);const hR=(e,t,n)=>n===pt.Left?e-t:n===pt.Right?e+t:e,mR=(e,t,n)=>n===pt.Top?e-t:n===pt.Bottom?e+t:e,mv="react-flow__edgeupdater",_v=({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:o,onMouseEnter:l,onMouseOut:u,type:c})=>ve.createElement("circle",{onMouseDown:o,onMouseEnter:l,onMouseOut:u,className:Qs([mv,`${mv}-${c}`]),cx:hR(t,r,e),cy:mR(n,r,e),r,stroke:"transparent",fill:"transparent"}),_R=()=>!0;var Du=e=>{const t=({id:n,className:r,type:o,data:l,onClick:u,onEdgeDoubleClick:c,selected:f,animated:_,label:p,labelStyle:y,labelShowBg:w,labelBgStyle:x,labelBgPadding:S,labelBgBorderRadius:j,style:C,source:N,target:T,sourceX:L,sourceY:P,targetX:W,targetY:G,sourcePosition:Y,targetPosition:J,elementsSelectable:re,hidden:ae,sourceHandleId:ue,targetHandleId:B,onContextMenu:A,onMouseEnter:$,onMouseMove:z,onMouseLeave:E,edgeUpdaterRadius:te,onEdgeUpdate:O,onEdgeUpdateStart:F,onEdgeUpdateEnd:K,markerEnd:R,markerStart:Q,rfId:Z,ariaLabel:X,isFocusable:le,isUpdatable:_e,pathOptions:he,interactionWidth:ye})=>{const Ee=m.useRef(null),[ze,Be]=m.useState(!1),[gt,Fe]=m.useState(!1),tt=bs(),lt=m.useMemo(()=>`url('#${wg(Q,Z)}')`,[Q,Z]),Ye=m.useMemo(()=>`url('#${wg(R,Z)}')`,[R,Z]);if(ae)return null;const Se=$t=>{var _n;const{edges:fn,addSelectedEdges:Un,unselectNodesAndEdges:En,multiSelectionActive:hn}=tt.getState(),On=fn.find(js=>js.id===n);On&&(re&&(tt.setState({nodesSelectionActive:!1}),On.selected&&hn?(En({nodes:[],edges:[On]}),(_n=Ee.current)==null||_n.blur()):Un([n])),u&&u($t,On))},Re=wf(n,tt.getState,c),ht=wf(n,tt.getState,A),xe=wf(n,tt.getState,$),Le=wf(n,tt.getState,z),Ue=wf(n,tt.getState,E),Ft=($t,fn)=>{if($t.button!==0)return;const{edges:Un,isValidConnection:En}=tt.getState(),hn=fn?T:N,On=(fn?B:ue)||null,_n=fn?"target":"source",js=En||_R,Yn=fn,Ss=Un.find(ce=>ce.id===n);Fe(!0),F==null||F($t,Ss,_n);const Mr=ce=>{Fe(!1),K==null||K(ce,Ss,_n)};f0({event:$t,handleId:On,nodeId:hn,onConnect:ce=>O==null?void 0:O(Ss,ce),isTarget:Yn,getState:tt.getState,setState:tt.setState,isValidConnection:js,edgeUpdaterType:_n,onEdgeUpdateEnd:Mr})},Qt=$t=>Ft($t,!0),yn=$t=>Ft($t,!1),Ut=()=>Be(!0),It=()=>Be(!1),jn=!re&&!u,ns=$t=>{var fn;if(e0.includes($t.key)&&re){const{unselectNodesAndEdges:Un,addSelectedEdges:En,edges:hn}=tt.getState();$t.key==="Escape"?((fn=Ee.current)==null||fn.blur(),Un({edges:[hn.find(_n=>_n.id===n)]})):En([n])}};return ve.createElement("g",{className:Qs(["react-flow__edge",`react-flow__edge-${o}`,r,{selected:f,animated:_,inactive:jn,updating:ze}]),onClick:Se,onDoubleClick:Re,onContextMenu:ht,onMouseEnter:xe,onMouseMove:Le,onMouseLeave:Ue,onKeyDown:le?ns:void 0,tabIndex:le?0:void 0,role:le?"button":"img","data-testid":`rf__edge-${n}`,"aria-label":X===null?void 0:X||`Edge from ${N} to ${T}`,"aria-describedby":le?`${x0}-${Z}`:void 0,ref:Ee},!gt&&ve.createElement(e,{id:n,source:N,target:T,selected:f,animated:_,label:p,labelStyle:y,labelShowBg:w,labelBgStyle:x,labelBgPadding:S,labelBgBorderRadius:j,data:l,style:C,sourceX:L,sourceY:P,targetX:W,targetY:G,sourcePosition:Y,targetPosition:J,sourceHandleId:ue,targetHandleId:B,markerStart:lt,markerEnd:Ye,pathOptions:he,interactionWidth:ye}),_e&&ve.createElement(ve.Fragment,null,(_e==="source"||_e===!0)&&ve.createElement(_v,{position:Y,centerX:L,centerY:P,radius:te,onMouseDown:Qt,onMouseEnter:Ut,onMouseOut:It,type:"source"}),(_e==="target"||_e===!0)&&ve.createElement(_v,{position:J,centerX:W,centerY:G,radius:te,onMouseDown:yn,onMouseEnter:Ut,onMouseOut:It,type:"target"})))};return t.displayName="EdgeWrapper",m.memo(t)};function pR(e){const t={default:Du(e.default||Zm),straight:Du(e.bezier||iy),step:Du(e.step||ry),smoothstep:Du(e.step||p_),simplebezier:Du(e.simplebezier||sy)},n={},r=Object.keys(e).filter(o=>!["default","bezier"].includes(o)).reduce((o,l)=>(o[l]=Du(e[l]||Zm),o),n);return{...t,...r}}function pv(e,t,n=null){const r=((n==null?void 0:n.x)||0)+t.x,o=((n==null?void 0:n.y)||0)+t.y,l=(n==null?void 0:n.width)||t.width,u=(n==null?void 0:n.height)||t.height;switch(e){case pt.Top:return{x:r+l/2,y:o};case pt.Right:return{x:r+l,y:o+u/2};case pt.Bottom:return{x:r+l/2,y:o+u};case pt.Left:return{x:r,y:o+u/2}}}function gv(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const gR=(e,t,n,r,o,l)=>{const u=pv(n,e,t),c=pv(l,r,o);return{sourceX:u.x,sourceY:u.y,targetX:c.x,targetY:c.y}};function yR({sourcePos:e,targetPos:t,sourceWidth:n,sourceHeight:r,targetWidth:o,targetHeight:l,width:u,height:c,transform:f}){const _={x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x+n,t.x+o),y2:Math.max(e.y+r,t.y+l)};_.x===_.x2&&(_.x2+=1),_.y===_.y2&&(_.y2+=1);const p=Uf({x:(0-f[0])/f[2],y:(0-f[1])/f[2],width:u/f[2],height:c/f[2]}),y=Math.max(0,Math.min(p.x2,_.x2)-Math.max(p.x,_.x)),w=Math.max(0,Math.min(p.y2,_.y2)-Math.max(p.y,_.y));return Math.ceil(y*w)>0}function yv(e){var r,o,l,u,c;const t=((r=e==null?void 0:e[ds])==null?void 0:r.handleBounds)||null,n=t&&(e==null?void 0:e.width)&&(e==null?void 0:e.height)&&typeof((o=e==null?void 0:e.positionAbsolute)==null?void 0:o.x)<"u"&&typeof((l=e==null?void 0:e.positionAbsolute)==null?void 0:l.y)<"u";return[{x:((u=e==null?void 0:e.positionAbsolute)==null?void 0:u.x)||0,y:((c=e==null?void 0:e.positionAbsolute)==null?void 0:c.y)||0,width:(e==null?void 0:e.width)||0,height:(e==null?void 0:e.height)||0},t,!!n]}const wR=[{level:0,isMaxLevel:!0,edges:[]}];function vR(e,t,n=!1){let r=-1;const o=e.reduce((u,c)=>{var p,y;const f=Ti(c.zIndex);let _=f?c.zIndex:0;if(n){const w=t.get(c.target),x=t.get(c.source),S=c.selected||(w==null?void 0:w.selected)||(x==null?void 0:x.selected),j=Math.max(((p=x==null?void 0:x[ds])==null?void 0:p.z)||0,((y=w==null?void 0:w[ds])==null?void 0:y.z)||0,1e3);_=(f?c.zIndex:0)+(S?j:0)}return u[_]?u[_].push(c):u[_]=[c],r=_>r?_:r,u},{}),l=Object.entries(o).map(([u,c])=>{const f=+u;return{edges:c,level:f,isMaxLevel:f===r}});return l.length===0?wR:l}function xR(e,t,n){const r=In(m.useCallback(o=>e?o.edges.filter(l=>{const u=t.get(l.source),c=t.get(l.target);return(u==null?void 0:u.width)&&(u==null?void 0:u.height)&&(c==null?void 0:c.width)&&(c==null?void 0:c.height)&&yR({sourcePos:u.positionAbsolute||{x:0,y:0},targetPos:c.positionAbsolute||{x:0,y:0},sourceWidth:u.width,sourceHeight:u.height,targetWidth:c.width,targetHeight:c.height,width:o.width,height:o.height,transform:o.transform})}):o.edges,[e,t]));return vR(r,t,n)}const bR=({color:e="none",strokeWidth:t=1})=>ve.createElement("polyline",{style:{stroke:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",fill:"none",points:"-5,-4 0,0 -5,4"}),jR=({color:e="none",strokeWidth:t=1})=>ve.createElement("polyline",{style:{stroke:e,fill:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"}),wv={[qf.Arrow]:bR,[qf.ArrowClosed]:jR};function SR(e){const t=bs();return m.useMemo(()=>{var o,l;return Object.prototype.hasOwnProperty.call(wv,e)?wv[e]:((l=(o=t.getState()).onError)==null||l.call(o,"009",Aa.error009(e)),null)},[e])}const kR=({id:e,type:t,color:n,width:r=12.5,height:o=12.5,markerUnits:l="strokeWidth",strokeWidth:u,orient:c="auto-start-reverse"})=>{const f=SR(t);return f?ve.createElement("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${o}`,viewBox:"-10 -10 20 20",markerUnits:l,orient:c,refX:"0",refY:"0"},ve.createElement(f,{color:n,strokeWidth:u})):null},NR=({defaultColor:e,rfId:t})=>n=>{const r=[];return n.edges.reduce((o,l)=>([l.markerStart,l.markerEnd].forEach(u=>{if(u&&typeof u=="object"){const c=wg(u,t);r.includes(c)||(o.push({id:c,color:u.color||e,...u}),r.push(c))}}),o),[]).sort((o,l)=>o.id.localeCompare(l.id))},M0=({defaultColor:e,rfId:t})=>{const n=In(m.useCallback(NR({defaultColor:e,rfId:t}),[e,t]),(r,o)=>!(r.length!==o.length||r.some((l,u)=>l.id!==o[u].id)));return ve.createElement("defs",null,n.map(r=>ve.createElement(kR,{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})))};M0.displayName="MarkerDefinitions";var CR=m.memo(M0);const ER=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}),R0=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:r,edgeTypes:o,noPanClassName:l,onEdgeUpdate:u,onEdgeContextMenu:c,onEdgeMouseEnter:f,onEdgeMouseMove:_,onEdgeMouseLeave:p,onEdgeClick:y,edgeUpdaterRadius:w,onEdgeDoubleClick:x,onEdgeUpdateStart:S,onEdgeUpdateEnd:j,children:C})=>{const{edgesFocusable:N,edgesUpdatable:T,elementsSelectable:L,width:P,height:W,connectionMode:G,nodeInternals:Y,onError:J}=In(ER,Ps),re=xR(t,Y,n);return P?ve.createElement(ve.Fragment,null,re.map(({level:ae,edges:ue,isMaxLevel:B})=>ve.createElement("svg",{key:ae,style:{zIndex:ae},width:P,height:W,className:"react-flow__edges react-flow__container"},B&&ve.createElement(CR,{defaultColor:e,rfId:r}),ve.createElement("g",null,ue.map(A=>{const[$,z,E]=yv(Y.get(A.source)),[te,O,F]=yv(Y.get(A.target));if(!E||!F)return null;let K=A.type||"default";o[K]||(J==null||J("011",Aa.error011(K)),K="default");const R=o[K]||o.default,Q=G===Mc.Strict?O.target:(O.target??[]).concat(O.source??[]),Z=gv(z.source,A.sourceHandle),X=gv(Q,A.targetHandle),le=(Z==null?void 0:Z.position)||pt.Bottom,_e=(X==null?void 0:X.position)||pt.Top,he=!!(A.focusable||N&&typeof A.focusable>"u"),ye=typeof u<"u"&&(A.updatable||T&&typeof A.updatable>"u");if(!Z||!X)return J==null||J("008",Aa.error008(Z,A)),null;const{sourceX:Ee,sourceY:ze,targetX:Be,targetY:gt}=gR($,Z,le,te,X,_e);return ve.createElement(R,{key:A.id,id:A.id,className:Qs([A.className,l]),type:K,data:A.data,selected:!!A.selected,animated:!!A.animated,hidden:!!A.hidden,label:A.label,labelStyle:A.labelStyle,labelShowBg:A.labelShowBg,labelBgStyle:A.labelBgStyle,labelBgPadding:A.labelBgPadding,labelBgBorderRadius:A.labelBgBorderRadius,style:A.style,source:A.source,target:A.target,sourceHandleId:A.sourceHandle,targetHandleId:A.targetHandle,markerEnd:A.markerEnd,markerStart:A.markerStart,sourceX:Ee,sourceY:ze,targetX:Be,targetY:gt,sourcePosition:le,targetPosition:_e,elementsSelectable:L,onEdgeUpdate:u,onContextMenu:c,onMouseEnter:f,onMouseMove:_,onMouseLeave:p,onClick:y,edgeUpdaterRadius:w,onEdgeDoubleClick:x,onEdgeUpdateStart:S,onEdgeUpdateEnd:j,rfId:r,ariaLabel:A.ariaLabel,isFocusable:he,isUpdatable:ye,pathOptions:"pathOptions"in A?A.pathOptions:void 0,interactionWidth:A.interactionWidth})})))),C):null};R0.displayName="EdgeRenderer";var $R=m.memo(R0);const AR=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function TR({children:e}){const t=In(AR);return ve.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function MR(e){const t=cy(),n=m.useRef(!1);m.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const RR={[pt.Left]:pt.Right,[pt.Right]:pt.Left,[pt.Top]:pt.Bottom,[pt.Bottom]:pt.Top},L0=({nodeId:e,handleType:t,style:n,type:r=gl.Bezier,CustomComponent:o,connectionStatus:l})=>{var G,Y,J;const{fromNode:u,handleId:c,toX:f,toY:_,connectionMode:p}=In(m.useCallback(re=>({fromNode:re.nodeInternals.get(e),handleId:re.connectionHandleId,toX:(re.connectionPosition.x-re.transform[0])/re.transform[2],toY:(re.connectionPosition.y-re.transform[1])/re.transform[2],connectionMode:re.connectionMode}),[e]),Ps),y=(G=u==null?void 0:u[ds])==null?void 0:G.handleBounds;let w=y==null?void 0:y[t];if(p===Mc.Loose&&(w=w||(y==null?void 0:y[t==="source"?"target":"source"])),!u||!w)return null;const x=c?w.find(re=>re.id===c):w[0],S=x?x.x+x.width/2:(u.width??0)/2,j=x?x.y+x.height/2:u.height??0,C=(((Y=u.positionAbsolute)==null?void 0:Y.x)??0)+S,N=(((J=u.positionAbsolute)==null?void 0:J.y)??0)+j,T=x==null?void 0:x.position,L=T?RR[T]:null;if(!T||!L)return null;if(o)return ve.createElement(o,{connectionLineType:r,connectionLineStyle:n,fromNode:u,fromHandle:x,fromX:C,fromY:N,toX:f,toY:_,fromPosition:T,toPosition:L,connectionStatus:l});let P="";const W={sourceX:C,sourceY:N,sourcePosition:T,targetX:f,targetY:_,targetPosition:L};return r===gl.Bezier?[P]=i0(W):r===gl.Step?[P]=yg({...W,borderRadius:0}):r===gl.SmoothStep?[P]=yg(W):r===gl.SimpleBezier?[P]=r0(W):P=`M${C},${N} ${f},${_}`,ve.createElement("path",{d:P,fill:"none",className:"react-flow__connection-path",style:n})};L0.displayName="ConnectionLine";const LR=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function IR({containerStyle:e,style:t,type:n,component:r}){const{nodeId:o,handleType:l,nodesConnectable:u,width:c,height:f,connectionStatus:_}=In(LR,Ps);return!(o&&l&&c&&u)?null:ve.createElement("svg",{style:e,width:c,height:f,className:"react-flow__edges react-flow__connectionline react-flow__container"},ve.createElement("g",{className:Qs(["react-flow__connection",_])},ve.createElement(L0,{nodeId:o,handleType:l,style:t,type:n,CustomComponent:r,connectionStatus:_})))}function vv(e,t){return m.useRef(null),bs(),m.useMemo(()=>t(e),[e])}const I0=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:r,onMoveEnd:o,onInit:l,onNodeClick:u,onEdgeClick:c,onNodeDoubleClick:f,onEdgeDoubleClick:_,onNodeMouseEnter:p,onNodeMouseMove:y,onNodeMouseLeave:w,onNodeContextMenu:x,onSelectionContextMenu:S,onSelectionStart:j,onSelectionEnd:C,connectionLineType:N,connectionLineStyle:T,connectionLineComponent:L,connectionLineContainerStyle:P,selectionKeyCode:W,selectionOnDrag:G,selectionMode:Y,multiSelectionKeyCode:J,panActivationKeyCode:re,zoomActivationKeyCode:ae,deleteKeyCode:ue,onlyRenderVisibleElements:B,elementsSelectable:A,selectNodesOnDrag:$,defaultViewport:z,translateExtent:E,minZoom:te,maxZoom:O,preventScrolling:F,defaultMarkerColor:K,zoomOnScroll:R,zoomOnPinch:Q,panOnScroll:Z,panOnScrollSpeed:X,panOnScrollMode:le,zoomOnDoubleClick:_e,panOnDrag:he,onPaneClick:ye,onPaneMouseEnter:Ee,onPaneMouseMove:ze,onPaneMouseLeave:Be,onPaneScroll:gt,onPaneContextMenu:Fe,onEdgeUpdate:tt,onEdgeContextMenu:lt,onEdgeMouseEnter:Ye,onEdgeMouseMove:Se,onEdgeMouseLeave:Re,edgeUpdaterRadius:ht,onEdgeUpdateStart:xe,onEdgeUpdateEnd:Le,noDragClassName:Ue,noWheelClassName:Ft,noPanClassName:Qt,elevateEdgesOnSelect:yn,disableKeyboardA11y:Ut,nodeOrigin:It,nodeExtent:jn,rfId:ns})=>{const $t=vv(e,cR),fn=vv(t,pR);return MR(l),ve.createElement(aR,{onPaneClick:ye,onPaneMouseEnter:Ee,onPaneMouseMove:ze,onPaneMouseLeave:Be,onPaneContextMenu:Fe,onPaneScroll:gt,deleteKeyCode:ue,selectionKeyCode:W,selectionOnDrag:G,selectionMode:Y,onSelectionStart:j,onSelectionEnd:C,multiSelectionKeyCode:J,panActivationKeyCode:re,zoomActivationKeyCode:ae,elementsSelectable:A,onMove:n,onMoveStart:r,onMoveEnd:o,zoomOnScroll:R,zoomOnPinch:Q,zoomOnDoubleClick:_e,panOnScroll:Z,panOnScrollSpeed:X,panOnScrollMode:le,panOnDrag:he,defaultViewport:z,translateExtent:E,minZoom:te,maxZoom:O,onSelectionContextMenu:S,preventScrolling:F,noDragClassName:Ue,noWheelClassName:Ft,noPanClassName:Qt,disableKeyboardA11y:Ut},ve.createElement(TR,null,ve.createElement($R,{edgeTypes:fn,onEdgeClick:c,onEdgeDoubleClick:_,onEdgeUpdate:tt,onlyRenderVisibleElements:B,onEdgeContextMenu:lt,onEdgeMouseEnter:Ye,onEdgeMouseMove:Se,onEdgeMouseLeave:Re,onEdgeUpdateStart:xe,onEdgeUpdateEnd:Le,edgeUpdaterRadius:ht,defaultMarkerColor:K,noPanClassName:Qt,elevateEdgesOnSelect:!!yn,disableKeyboardA11y:Ut,rfId:ns},ve.createElement(IR,{style:T,type:N,component:L,containerStyle:P})),ve.createElement("div",{className:"react-flow__edgelabel-renderer"}),ve.createElement(fR,{nodeTypes:$t,onNodeClick:u,onNodeDoubleClick:f,onNodeMouseEnter:p,onNodeMouseMove:y,onNodeMouseLeave:w,onNodeContextMenu:x,selectNodesOnDrag:$,onlyRenderVisibleElements:B,noPanClassName:Qt,noDragClassName:Ue,disableKeyboardA11y:Ut,nodeOrigin:It,nodeExtent:jn,rfId:ns})))};I0.displayName="GraphView";var OR=m.memo(I0);const jg=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],ul={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:jg,nodeExtent:jg,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:Mc.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:cM,isValidConnection:void 0},PR=()=>SE((e,t)=>({...ul,setNodes:n=>{const{nodeInternals:r,nodeOrigin:o,elevateNodesOnSelect:l}=t();e({nodeInternals:xp(n,r,o,l)})},getNodes:()=>Array.from(t().nodeInternals.values()),setEdges:n=>{const{defaultEdgeOptions:r={}}=t();e({edges:n.map(o=>({...r,...o}))})},setDefaultNodesAndEdges:(n,r)=>{const o=typeof n<"u",l=typeof r<"u",u=o?xp(n,new Map,t().nodeOrigin,t().elevateNodesOnSelect):new Map;e({nodeInternals:u,edges:l?r:[],hasDefaultNodes:o,hasDefaultEdges:l})},updateNodeDimensions:n=>{const{onNodesChange:r,nodeInternals:o,fitViewOnInit:l,fitViewOnInitDone:u,fitViewOnInitOptions:c,domNode:f,nodeOrigin:_}=t(),p=f==null?void 0:f.querySelector(".react-flow__viewport");if(!p)return;const y=window.getComputedStyle(p),{m22:w}=new window.DOMMatrixReadOnly(y.transform),x=n.reduce((j,C)=>{const N=o.get(C.id);if(N){const T=ty(C.nodeElement);!!(T.width&&T.height&&(N.width!==T.width||N.height!==T.height||C.forceUpdate))&&(o.set(N.id,{...N,[ds]:{...N[ds],handleBounds:{source:hv(".source",C.nodeElement,w,_),target:hv(".target",C.nodeElement,w,_)}},...T}),j.push({id:N.id,type:"dimensions",dimensions:T}))}return j},[]);j0(o,_);const S=u||l&&!u&&S0(t,{initial:!0,...c});e({nodeInternals:new Map(o),fitViewOnInitDone:S}),(x==null?void 0:x.length)>0&&(r==null||r(x))},updateNodePositions:(n,r=!0,o=!1)=>{const{triggerNodeChanges:l}=t(),u=n.map(c=>{const f={id:c.id,type:"position",dragging:o};return r&&(f.positionAbsolute=c.positionAbsolute,f.position=c.position),f});l(u)},triggerNodeChanges:n=>{const{onNodesChange:r,nodeInternals:o,hasDefaultNodes:l,nodeOrigin:u,getNodes:c,elevateNodesOnSelect:f}=t();if(n!=null&&n.length){if(l){const _=ZM(n,c()),p=xp(_,o,u,f);e({nodeInternals:p})}r==null||r(n)}},addSelectedNodes:n=>{const{multiSelectionActive:r,edges:o,getNodes:l}=t();let u,c=null;r?u=n.map(f=>_l(f,!0)):(u=Wu(l(),n),c=Wu(o,[])),gm({changedNodes:u,changedEdges:c,get:t,set:e})},addSelectedEdges:n=>{const{multiSelectionActive:r,edges:o,getNodes:l}=t();let u,c=null;r?u=n.map(f=>_l(f,!0)):(u=Wu(o,n),c=Wu(l(),[])),gm({changedNodes:c,changedEdges:u,get:t,set:e})},unselectNodesAndEdges:({nodes:n,edges:r}={})=>{const{edges:o,getNodes:l}=t(),u=n||l(),c=r||o,f=u.map(p=>(p.selected=!1,_l(p.id,!1))),_=c.map(p=>_l(p.id,!1));gm({changedNodes:f,changedEdges:_,get:t,set:e})},setMinZoom:n=>{const{d3Zoom:r,maxZoom:o}=t();r==null||r.scaleExtent([n,o]),e({minZoom:n})},setMaxZoom:n=>{const{d3Zoom:r,minZoom:o}=t();r==null||r.scaleExtent([o,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(),l=r().filter(c=>c.selected).map(c=>_l(c.id,!1)),u=n.filter(c=>c.selected).map(c=>_l(c.id,!1));gm({changedNodes:l,changedEdges:u,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:r}=t();r.forEach(o=>{o.positionAbsolute=ny(o.position,n)}),e({nodeExtent:n,nodeInternals:new Map(r)})},panBy:n=>{const{transform:r,width:o,height:l,d3Zoom:u,d3Selection:c,translateExtent:f}=t();if(!u||!c||!n.x&&!n.y)return!1;const _=Na.translate(r[0]+n.x,r[1]+n.y).scale(r[2]),p=[[0,0],[o,l]],y=u==null?void 0:u.constrain()(_,p,f);return u.transform(c,y),r[0]!==y.x||r[1]!==y.y||r[2]!==y.k},cancelConnection:()=>e({connectionNodeId:ul.connectionNodeId,connectionHandleId:ul.connectionHandleId,connectionHandleType:ul.connectionHandleType,connectionStatus:ul.connectionStatus,connectionStartHandle:ul.connectionStartHandle,connectionEndHandle:ul.connectionEndHandle}),reset:()=>e({...ul})}),Object.is),dy=({children:e})=>{const t=m.useRef(null);return t.current||(t.current=PR()),ve.createElement(nM,{value:t.current},e)};dy.displayName="ReactFlowProvider";const O0=({children:e})=>m.useContext(__)?ve.createElement(ve.Fragment,null,e):ve.createElement(dy,null,e);O0.displayName="ReactFlowWrapper";const DR={input:p0,default:xg,output:y0,group:ly},FR={default:Zm,straight:iy,step:ry,smoothstep:p_,simplebezier:sy},zR=[0,0],BR=[15,15],UR={x:0,y:0,zoom:1},WR={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},P0=m.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:o,nodeTypes:l=DR,edgeTypes:u=FR,onNodeClick:c,onEdgeClick:f,onInit:_,onMove:p,onMoveStart:y,onMoveEnd:w,onConnect:x,onConnectStart:S,onConnectEnd:j,onClickConnectStart:C,onClickConnectEnd:N,onNodeMouseEnter:T,onNodeMouseMove:L,onNodeMouseLeave:P,onNodeContextMenu:W,onNodeDoubleClick:G,onNodeDragStart:Y,onNodeDrag:J,onNodeDragStop:re,onNodesDelete:ae,onEdgesDelete:ue,onSelectionChange:B,onSelectionDragStart:A,onSelectionDrag:$,onSelectionDragStop:z,onSelectionContextMenu:E,onSelectionStart:te,onSelectionEnd:O,connectionMode:F=Mc.Strict,connectionLineType:K=gl.Bezier,connectionLineStyle:R,connectionLineComponent:Q,connectionLineContainerStyle:Z,deleteKeyCode:X="Backspace",selectionKeyCode:le="Shift",selectionOnDrag:_e=!1,selectionMode:he=Wf.Full,panActivationKeyCode:ye="Space",multiSelectionKeyCode:Ee=Xm()?"Meta":"Control",zoomActivationKeyCode:ze=Xm()?"Meta":"Control",snapToGrid:Be=!1,snapGrid:gt=BR,onlyRenderVisibleElements:Fe=!1,selectNodesOnDrag:tt=!0,nodesDraggable:lt,nodesConnectable:Ye,nodesFocusable:Se,nodeOrigin:Re=zR,edgesFocusable:ht,edgesUpdatable:xe,elementsSelectable:Le,defaultViewport:Ue=UR,minZoom:Ft=.5,maxZoom:Qt=2,translateExtent:yn=jg,preventScrolling:Ut=!0,nodeExtent:It,defaultMarkerColor:jn="#b1b1b7",zoomOnScroll:ns=!0,zoomOnPinch:$t=!0,panOnScroll:fn=!1,panOnScrollSpeed:Un=.5,panOnScrollMode:En=jc.Free,zoomOnDoubleClick:hn=!0,panOnDrag:On=!0,onPaneClick:_n,onPaneMouseEnter:js,onPaneMouseMove:Yn,onPaneMouseLeave:Ss,onPaneScroll:Mr,onPaneContextMenu:Pn,children:ce,onEdgeUpdate:je,onEdgeContextMenu:Je,onEdgeDoubleClick:Ve,onEdgeMouseEnter:rt,onEdgeMouseMove:ct,onEdgeMouseLeave:Et,onEdgeUpdateStart:St,onEdgeUpdateEnd:Kt,edgeUpdaterRadius:xt=10,onNodesChange:Yt,onEdgesChange:Wt,noDragClassName:Ot="nodrag",noWheelClassName:At="nowheel",noPanClassName:Tt="nopan",fitView:De=!1,fitViewOptions:sn,connectOnClick:dt=!0,attributionPosition:en,proOptions:ft,defaultEdgeOptions:Wn,elevateNodesOnSelect:cn=!0,elevateEdgesOnSelect:er=!1,disableKeyboardA11y:ss=!1,autoPanOnConnect:Xr=!0,autoPanOnNodeDrag:_r=!0,connectionRadius:hi=20,isValidConnection:mi,onError:Ds,style:de,id:pr,nodeDragThreshold:co,...gr},Rr)=>{const Zr=pr||"1";return ve.createElement("div",{...gr,style:{...de,...WR},ref:Rr,className:Qs(["react-flow",o]),"data-testid":"rf__wrapper",id:pr},ve.createElement(O0,null,ve.createElement(OR,{onInit:_,onMove:p,onMoveStart:y,onMoveEnd:w,onNodeClick:c,onEdgeClick:f,onNodeMouseEnter:T,onNodeMouseMove:L,onNodeMouseLeave:P,onNodeContextMenu:W,onNodeDoubleClick:G,nodeTypes:l,edgeTypes:u,connectionLineType:K,connectionLineStyle:R,connectionLineComponent:Q,connectionLineContainerStyle:Z,selectionKeyCode:le,selectionOnDrag:_e,selectionMode:he,deleteKeyCode:X,multiSelectionKeyCode:Ee,panActivationKeyCode:ye,zoomActivationKeyCode:ze,onlyRenderVisibleElements:Fe,selectNodesOnDrag:tt,defaultViewport:Ue,translateExtent:yn,minZoom:Ft,maxZoom:Qt,preventScrolling:Ut,zoomOnScroll:ns,zoomOnPinch:$t,zoomOnDoubleClick:hn,panOnScroll:fn,panOnScrollSpeed:Un,panOnScrollMode:En,panOnDrag:On,onPaneClick:_n,onPaneMouseEnter:js,onPaneMouseMove:Yn,onPaneMouseLeave:Ss,onPaneScroll:Mr,onPaneContextMenu:Pn,onSelectionContextMenu:E,onSelectionStart:te,onSelectionEnd:O,onEdgeUpdate:je,onEdgeContextMenu:Je,onEdgeDoubleClick:Ve,onEdgeMouseEnter:rt,onEdgeMouseMove:ct,onEdgeMouseLeave:Et,onEdgeUpdateStart:St,onEdgeUpdateEnd:Kt,edgeUpdaterRadius:xt,defaultMarkerColor:jn,noDragClassName:Ot,noWheelClassName:At,noPanClassName:Tt,elevateEdgesOnSelect:er,rfId:Zr,disableKeyboardA11y:ss,nodeOrigin:Re,nodeExtent:It}),ve.createElement(MM,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:x,onConnectStart:S,onConnectEnd:j,onClickConnectStart:C,onClickConnectEnd:N,nodesDraggable:lt,nodesConnectable:Ye,nodesFocusable:Se,edgesFocusable:ht,edgesUpdatable:xe,elementsSelectable:Le,elevateNodesOnSelect:cn,minZoom:Ft,maxZoom:Qt,nodeExtent:It,onNodesChange:Yt,onEdgesChange:Wt,snapToGrid:Be,snapGrid:gt,connectionMode:F,translateExtent:yn,connectOnClick:dt,defaultEdgeOptions:Wn,fitView:De,fitViewOptions:sn,onNodesDelete:ae,onEdgesDelete:ue,onNodeDragStart:Y,onNodeDrag:J,onNodeDragStop:re,onSelectionDrag:$,onSelectionDragStart:A,onSelectionDragStop:z,noPanClassName:Tt,nodeOrigin:Re,rfId:Zr,autoPanOnConnect:Xr,autoPanOnNodeDrag:_r,onError:Ds,connectionRadius:hi,isValidConnection:mi,nodeDragThreshold:co}),ve.createElement(AM,{onSelectionChange:B}),ce,ve.createElement(rM,{proOptions:ft,position:en}),ve.createElement(PM,{rfId:Zr,disableKeyboardA11y:ss})))});P0.displayName="ReactFlow";const D0=({id:e,x:t,y:n,width:r,height:o,style:l,color:u,strokeColor:c,strokeWidth:f,className:_,borderRadius:p,shapeRendering:y,onClick:w,selected:x})=>{const{background:S,backgroundColor:j}=l||{},C=u||S||j;return ve.createElement("rect",{className:Qs(["react-flow__minimap-node",{selected:x},_]),x:t,y:n,rx:p,ry:p,width:r,height:o,fill:C,stroke:c,strokeWidth:f,shapeRendering:y,onClick:w?N=>w(N,e):void 0})};D0.displayName="MiniMapNode";var qR=m.memo(D0);const HR=e=>e.nodeOrigin,VR=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),kp=e=>e instanceof Function?e:()=>e;function GR({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o=2,nodeComponent:l=qR,onClick:u}){const c=In(VR,Ps),f=In(HR),_=kp(t),p=kp(e),y=kp(n),w=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return ve.createElement(ve.Fragment,null,c.map(x=>{const{x:S,y:j}=Ec(x,f).positionAbsolute;return ve.createElement(l,{key:x.id,x:S,y:j,width:x.width,height:x.height,style:x.style,selected:x.selected,className:y(x),color:_(x),borderRadius:r,strokeColor:p(x),strokeWidth:o,shapeRendering:w,onClick:u,id:x.id})}))}var KR=m.memo(GR);const YR=200,JR=150,XR=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?aM(g_(t,e.nodeOrigin),n):n,rfId:e.rfId}},ZR="react-flow__minimap-desc";function F0({style:e,className:t,nodeStrokeColor:n="transparent",nodeColor:r="#e2e2e2",nodeClassName:o="",nodeBorderRadius:l=5,nodeStrokeWidth:u=2,nodeComponent:c,maskColor:f="rgb(240, 240, 240, 0.6)",maskStrokeColor:_="none",maskStrokeWidth:p=1,position:y="bottom-right",onClick:w,onNodeClick:x,pannable:S=!1,zoomable:j=!1,ariaLabel:C="React Flow mini map",inversePan:N=!1,zoomStep:T=10,offsetScale:L=5}){const P=bs(),W=m.useRef(null),{boundingRect:G,viewBB:Y,rfId:J}=In(XR,Ps),re=(e==null?void 0:e.width)??YR,ae=(e==null?void 0:e.height)??JR,ue=G.width/re,B=G.height/ae,A=Math.max(ue,B),$=A*re,z=A*ae,E=L*A,te=G.x-($-G.width)/2-E,O=G.y-(z-G.height)/2-E,F=$+E*2,K=z+E*2,R=`${ZR}-${J}`,Q=m.useRef(0);Q.current=A,m.useEffect(()=>{if(W.current){const le=Ai(W.current),_e=Ee=>{const{transform:ze,d3Selection:Be,d3Zoom:gt}=P.getState();if(Ee.sourceEvent.type!=="wheel"||!Be||!gt)return;const Fe=-Ee.sourceEvent.deltaY*(Ee.sourceEvent.deltaMode===1?.05:Ee.sourceEvent.deltaMode?1:.002)*T,tt=ze[2]*Math.pow(2,Fe);gt.scaleTo(Be,tt)},he=Ee=>{const{transform:ze,d3Selection:Be,d3Zoom:gt,translateExtent:Fe,width:tt,height:lt}=P.getState();if(Ee.sourceEvent.type!=="mousemove"||!Be||!gt)return;const Ye=Q.current*Math.max(1,ze[2])*(N?-1:1),Se={x:ze[0]-Ee.sourceEvent.movementX*Ye,y:ze[1]-Ee.sourceEvent.movementY*Ye},Re=[[0,0],[tt,lt]],ht=Na.translate(Se.x,Se.y).scale(ze[2]),xe=gt.constrain()(ht,Re,Fe);gt.transform(Be,xe)},ye=Kb().on("zoom",S?he:null).on("zoom.wheel",j?_e:null);return le.call(ye),()=>{le.on("zoom",null)}}},[S,j,N,T]);const Z=w?le=>{const _e=so(le);w(le,{x:_e[0],y:_e[1]})}:void 0,X=x?(le,_e)=>{const he=P.getState().nodeInternals.get(_e);x(le,he)}:void 0;return ve.createElement(Bf,{position:y,style:e,className:Qs(["react-flow__minimap",t]),"data-testid":"rf__minimap"},ve.createElement("svg",{width:re,height:ae,viewBox:`${te} ${O} ${F} ${K}`,role:"img","aria-labelledby":R,ref:W,onClick:Z},C&&ve.createElement("title",{id:R},C),ve.createElement(KR,{onClick:X,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:l,nodeClassName:o,nodeStrokeWidth:u,nodeComponent:c}),ve.createElement("path",{className:"react-flow__minimap-mask",d:`M${te-E},${O-E}h${F+E*2}v${K+E*2}h${-F-E*2}z
135
+ M${Y.x},${Y.y}h${Y.width}v${Y.height}h${-Y.width}z`,fill:f,fillRule:"evenodd",stroke:_,strokeWidth:p,pointerEvents:"none"})))}F0.displayName="MiniMap";var QR=m.memo(F0);function eL(){return ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32"},ve.createElement("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"}))}function tL(){return ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},ve.createElement("path",{d:"M0 0h32v4.2H0z"}))}function nL(){return ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30"},ve.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 sL(){return ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},ve.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 rL(){return ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},ve.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 qu=({children:e,className:t,...n})=>ve.createElement("button",{type:"button",className:Qs(["react-flow__controls-button",t]),...n},e);qu.displayName="ControlButton";const iL=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),z0=({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:o,onZoomIn:l,onZoomOut:u,onFitView:c,onInteractiveChange:f,className:_,children:p,position:y="bottom-left"})=>{const w=bs(),[x,S]=m.useState(!1),{isInteractive:j,minZoomReached:C,maxZoomReached:N}=In(iL,Ps),{zoomIn:T,zoomOut:L,fitView:P}=cy();if(m.useEffect(()=>{S(!0)},[]),!x)return null;const W=()=>{T(),l==null||l()},G=()=>{L(),u==null||u()},Y=()=>{P(o),c==null||c()},J=()=>{w.setState({nodesDraggable:!j,nodesConnectable:!j,elementsSelectable:!j}),f==null||f(!j)};return ve.createElement(Bf,{className:Qs(["react-flow__controls",_]),position:y,style:e,"data-testid":"rf__controls"},t&&ve.createElement(ve.Fragment,null,ve.createElement(qu,{onClick:W,className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:N},ve.createElement(eL,null)),ve.createElement(qu,{onClick:G,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:C},ve.createElement(tL,null))),n&&ve.createElement(qu,{className:"react-flow__controls-fitview",onClick:Y,title:"fit view","aria-label":"fit view"},ve.createElement(nL,null)),r&&ve.createElement(qu,{className:"react-flow__controls-interactive",onClick:J,title:"toggle interactivity","aria-label":"toggle interactivity"},j?ve.createElement(rL,null):ve.createElement(sL,null)),p)};z0.displayName="Controls";var oL=m.memo(z0),oo;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(oo||(oo={}));function aL({color:e,dimensions:t,lineWidth:n}){return ve.createElement("path",{stroke:e,strokeWidth:n,d:`M${t[0]/2} 0 V${t[1]} M0 ${t[1]/2} H${t[0]}`})}function lL({color:e,radius:t}){return ve.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const cL={[oo.Dots]:"#91919a",[oo.Lines]:"#eee",[oo.Cross]:"#e2e2e2"},uL={[oo.Dots]:1,[oo.Lines]:1,[oo.Cross]:6},dL=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function B0({id:e,variant:t=oo.Dots,gap:n=20,size:r,lineWidth:o=1,offset:l=2,color:u,style:c,className:f}){const _=m.useRef(null),{transform:p,patternId:y}=In(dL,Ps),w=u||cL[t],x=r||uL[t],S=t===oo.Dots,j=t===oo.Cross,C=Array.isArray(n)?n:[n,n],N=[C[0]*p[2]||1,C[1]*p[2]||1],T=x*p[2],L=j?[T,T]:N,P=S?[T/l,T/l]:[L[0]/l,L[1]/l];return ve.createElement("svg",{className:Qs(["react-flow__background",f]),style:{...c,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:_,"data-testid":"rf__background"},ve.createElement("pattern",{id:y+e,x:p[0]%N[0],y:p[1]%N[1],width:N[0],height:N[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${P[0]},-${P[1]})`},S?ve.createElement(lL,{color:w,radius:T/l}):ve.createElement(aL,{dimensions:L,color:w,lineWidth:o})),ve.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${y+e})`}))}B0.displayName="Background";var fL=m.memo(B0);function U0(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,o=typeof n.y=="number"&&Number.isFinite(n.y)?n.y:null,l=typeof n.zoom=="number"&&Number.isFinite(n.zoom)?n.zoom:null;if(r===null||o===null||l===null)return null;const u=typeof t.maxAbsTranslate=="number"&&Number.isFinite(t.maxAbsTranslate)?Math.abs(t.maxAbsTranslate):1e6;if(Math.abs(r)>u||Math.abs(o)>u)return null;const c=typeof t.minZoom=="number"&&Number.isFinite(t.minZoom)?t.minZoom:.025,f=typeof t.maxZoom=="number"&&Number.isFinite(t.maxZoom)?t.maxZoom:6,_=Math.min(c,f),p=Math.max(c,f);return{x:r,y:o,zoom:Math.min(p,Math.max(_,l))}}function e_(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 hL(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(),o=t.slice(n+1).toLowerCase();if(r==="ex"){const l=o.indexOf("-"),u=l>0?o.slice(0,l):o;return u==="person"?"person":u==="org"?"org":u==="concept"?"concept":u==="claim"?"claim":u==="event"?"event":u==="doc"?"doc":u==="thing"?"thing":"entity"}return r==="schema"||r==="skos"||r==="dcterms"||r==="rdf"||r==="cito"?"vocab":"entity"}function mL(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return e_(t);const r=t.slice(0,n).toLowerCase(),o=t.slice(n+1);if(r==="ex"){const l=o.indexOf("-");if(l>0&&l<o.length-1)return o.slice(l+1)}return e_(t)}function Sg(e){const r=Math.max(1,Math.ceil(Math.sqrt(e.length))),o={};for(let l=0;l<e.length;l++){const u=Math.floor(l/r),c=l%r;o[e[l]]={x:c*240,y:u*120}}return o}function kg(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 W0(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 _L(e,t){const n={},r=e.length;if(!r)return n;const o=Math.max(260,Math.sqrt(r)*150),l=t%360*Math.PI/180;for(let u=0;u<r;u++){const c=l+2*Math.PI*u/r;n[e[u]]={x:o*Math.cos(c),y:o*Math.sin(c)}}return n}function xv(e,t,n){var S;const r={};if(!e.length)return r;const o=new Map;for(const j of e)o.set(j,new Set);for(const j of t){const C=String((j==null?void 0:j.source)||"").trim(),N=String((j==null?void 0:j.target)||"").trim();if(!C||!N||C===N)continue;const T=o.get(C),L=o.get(N);T&&T.add(N),L&&L.add(C)}let l=e[0],u=-1;for(const j of e){const C=((S=o.get(j))==null?void 0:S.size)??0;(C>u||C===u&&j.localeCompare(l)<0)&&(l=j,u=C)}const c=new Map,f=[];for(c.set(l,0),f.push(l);f.length;){const j=f.shift(),C=c.get(j)??0,N=Array.from(o.get(j)??[]);N.sort((T,L)=>T.localeCompare(L));for(const T of N)c.has(T)||(c.set(T,C+1),f.push(T))}let _=0;for(const j of c.values())_=Math.max(_,j);for(const j of e)c.has(j)||c.set(j,_+1);const p=new Map;for(const j of e){const C=c.get(j)??0,N=p.get(C);N?N.push(j):p.set(C,[j])}const y=Array.from(p.keys()).sort((j,C)=>j-C),w=260,x=n%360*Math.PI/180;for(const j of y){const C=p.get(j)||[];if(C.sort((P,W)=>P.localeCompare(W)),j===0){if(C.length===1)r[C[0]]={x:0,y:0};else for(let W=0;W<C.length;W++){const G=x+2*Math.PI*W/C.length;r[C[W]]={x:80*Math.cos(G),y:80*Math.sin(G)}}continue}const N=w*j,T=C.length;if(T===1){r[C[0]]={x:N,y:0};continue}const L=x+j*.35;for(let P=0;P<T;P++){const W=L+2*Math.PI*P/T;r[C[P]]={x:N*Math.cos(W),y:N*Math.sin(W)}}}return r}function zu(e,t={}){const n=t.kind??"grid",r=typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):0,o=e.nodes.map(l=>l.id);if(n==="grid")return Sg(o);if(n==="circle")return _L(o,r);if(n==="radial")return xv(o,e.edges,r);if(n==="force"){const l=xv(o,e.edges,r),u=W0(r||1),c=Math.max(10,Math.min(42,Math.sqrt(o.length)*2.75)),f={};for(const _ of o){const p=l[_]||{x:0,y:0};f[_]={x:p.x+(u()-.5)*c,y:p.y+(u()-.5)*c}}return f}return Sg(o)}function pL(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 gL(e,t={}){const n=!!(t.groupEdges??!0),r=Math.max(1,t.maxEdgeLabelPredicates??3),o=pL(e),l=new Set;for(const w of o){const x=String(w.subject||"").trim(),S=String(w.object||"").trim();x&&l.add(x),S&&l.add(S)}const u=Array.from(l);u.sort((w,x)=>w.localeCompare(x));const c=Sg(u),f=u.map(w=>({id:w,type:"default",data:{label:mL(w),kind:hL(w)},position:c[w]||{x:0,y:0}})),_=new Map,p=(w,x)=>{const S=String(w.subject||"").trim(),j=String(w.object||"").trim(),C=String(w.predicate||"").trim();return n?`edge:${S}:${j}`:`edge:${x}:${S}:${C}:${j}`};for(let w=0;w<o.length;w++){const x=o[w],S=p(x,w),j=_.get(S);j?j.push(x):_.set(S,[x])}const y=[];for(const[w,x]of _.entries()){const S=x[0],j=String(S.subject||"").trim(),C=String(S.object||"").trim();if(!j||!C)continue;const N=new Map;for(const Y of x){const J=String(Y.predicate||"").trim();J&&N.set(J,(N.get(J)||0)+1)}const T=Array.from(N.entries());T.sort((Y,J)=>J[1]-Y[1]||Y[0].localeCompare(J[0]));const P=T.slice(0,r).map(([Y,J])=>J>1?`${e_(Y)}×${J}`:e_(Y)).join(" | "),W=T.length>r?` +${T.length-r}`:"",G=`${P}${W}`.trim();y.push({id:w,source:j,target:C,label:G,animated:!1,data:{assertions:x,predicateSummary:G}})}return{nodes:f,edges:y}}function yL(e,t,n,r={}){const o=r.directed!==!1,l=String(t||"").trim(),u=String(n||"").trim();if(!l||!u)return null;if(l===u)return{nodeIds:[l],edgeIds:[]};const c=new Map,f=(j,C,N)=>{const T=c.get(j);T?T.push({to:C,edgeId:N}):c.set(j,[{to:C,edgeId:N}])};for(const j of e.edges)f(j.source,j.target,j.id),o||f(j.target,j.source,j.id);const _=[l],p=new Map,y=new Map;for(p.set(l,null),y.set(l,null);_.length;){const j=_.shift(),C=c.get(j)||[];for(const N of C)if(!p.has(N.to)){if(p.set(N.to,j),y.set(N.to,N.edgeId),N.to===u){_.length=0;break}_.push(N.to)}}if(!p.has(u))return null;const w=[],x=[];let S=u;for(;S;){w.push(S);const j=y.get(S);j&&x.push(j),S=p.get(S)||null}return w.reverse(),x.reverse(),{nodeIds:w,edgeIds:x}}const bv={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function wm(e,t={}){const n={...bv,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):bv.seed},r=e.nodes.map(x=>x.id),o=r.length,l=new Float64Array(2*o),u=new Float64Array(2*o),c=new Float64Array(2*o),f=new Map;for(let x=0;x<o;x++)f.set(r[x],x);const _=t.positions??zu(e,{kind:"force",seed:n.seed}),p=W0(n.seed||1),y=Math.max(8,Math.min(38,Math.sqrt(o)*2.25));for(let x=0;x<o;x++){const S=r[x],j=_[S],C=typeof(j==null?void 0:j.x)=="number"&&Number.isFinite(j.x)?j.x:(p()-.5)*500,N=typeof(j==null?void 0:j.y)=="number"&&Number.isFinite(j.y)?j.y:(p()-.5)*500;l[2*x]=C+(p()-.5)*y,l[2*x+1]=N+(p()-.5)*y,u[2*x]=0,u[2*x+1]=0}const w=[];for(const x of e.edges){const S=f.get(String((x==null?void 0:x.source)||"").trim()),j=f.get(String((x==null?void 0:x.target)||"").trim());typeof S!="number"||typeof j!="number"||S===j||w.push(S,j)}return{nodeIds:r,pos:l,vel:u,acc:c,edges:new Uint32Array(w),options:n,tick:0}}function wL(e,t=1){const n=e.nodeIds.length;if(!n)return;const r=e.options,o=r.dt;for(let l=0;l<Math.max(1,Math.trunc(t));l++){if(e.acc.fill(0),n<=r.maxRepulsionNodes){const x=r.repulsionStrength;for(let S=0;S<n;S++){const j=e.pos[2*S],C=e.pos[2*S+1];for(let N=S+1;N<n;N++){const T=e.pos[2*N]-j,L=e.pos[2*N+1]-C,P=T*T+L*L+1e-6,W=1/Math.sqrt(P),G=x/P,Y=G*T*W,J=G*L*W;e.acc[2*S]-=Y,e.acc[2*S+1]-=J,e.acc[2*N]+=Y,e.acc[2*N+1]+=J}}}const c=r.springLength,f=r.springStrength,_=e.edges;for(let x=0;x<_.length;x+=2){const S=_[x],j=_[x+1],C=e.pos[2*S],N=e.pos[2*S+1],T=e.pos[2*j],L=e.pos[2*j+1],P=T-C,W=L-N,G=P*P+W*W+1e-6,Y=Math.sqrt(G),J=f*(Y-c),re=J*P/Y,ae=J*W/Y;e.acc[2*S]+=re,e.acc[2*S+1]+=ae,e.acc[2*j]-=re,e.acc[2*j+1]-=ae}const p=r.centeringStrength;for(let x=0;x<n;x++)e.acc[2*x]+=-p*e.pos[2*x],e.acc[2*x+1]+=-p*e.pos[2*x+1];const y=r.damping,w=r.maxSpeed;for(let x=0;x<n;x++){let S=(e.vel[2*x]+e.acc[2*x]*o)*y,j=(e.vel[2*x+1]+e.acc[2*x+1]*o)*y;const C=Math.sqrt(S*S+j*j);if(C>w){const N=w/C;S*=N,j*=N}e.vel[2*x]=S,e.vel[2*x+1]=j,e.pos[2*x]+=S*o,e.pos[2*x+1]+=j*o}e.tick+=1}}function vL(e){const t=e.nodeIds.length;if(!t)return 0;let n=0;for(let r=0;r<t;r++){const o=e.vel[2*r],l=e.vel[2*r+1];n+=Math.sqrt(o*o+l*l)}return n/t}function xL(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 jv(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function bL(){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 jL(){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 q0(e,t,n,r){const o=typeof e=="number"&&Number.isFinite(e)?e:r;return Math.min(n,Math.max(t,o))}function bf(e){const t=q0(e,.6,2.4,1),n=240*t,r=9e3*t*t;return{springLength:n,repulsionStrength:r}}const Vf="abstractuic_amx_saved_layouts_v1",Ng=.025,Cg=6,H0=1e6;function fy(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function Eg(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function SL(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 Sv(e){const t=fy();if(!t)return null;const n=String(e??"").trim();if(!n)return null;try{const r=t.getItem(Vf);if(!r)return null;const o=JSON.parse(r),l=o&&typeof o=="object"&&!Array.isArray(o)?o:null;if(!l)return null;const u=l[n],c=u&&typeof u=="object"&&!Array.isArray(u)?u:null;if(!c)return null;const f=c.version===1?1:null;if(f===null)return null;const _=Eg(c.kind,"grid"),p=typeof c.seed=="number"&&Number.isFinite(c.seed)?Math.trunc(c.seed):kg(n),y=c.positions&&typeof c.positions=="object"&&!Array.isArray(c.positions)?c.positions:null,w={};if(y)for(const[j,C]of Object.entries(y)){const N=SL(C);N&&(w[String(j)]=N)}const x=U0(c.viewport,{minZoom:Ng,maxZoom:Cg,maxAbsTranslate:H0})??void 0,S=typeof c.saved_at=="string"&&c.saved_at.trim()?c.saved_at.trim():"";return{version:f,kind:_,seed:p,positions:w,viewport:x,saved_at:S}}catch{return null}}function kL(e,t){const n=fy();if(!n)return;const r=String(e??"").trim();if(r)try{const o=n.getItem(Vf),l=o?JSON.parse(o):null,u=l&&typeof l=="object"&&!Array.isArray(l)?{...l}:{};u[r]=t,n.setItem(Vf,JSON.stringify(u))}catch{}}function NL(e){const t=fy();if(!t)return;const n=String(e??"").trim();if(n)try{const r=t.getItem(Vf);if(!r)return;const o=JSON.parse(r),l=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:null;if(!l||!(n in l))return;delete l[n],t.setItem(Vf,JSON.stringify(l))}catch{}}function CL(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function Np(e,t){const n=!!(t!=null&&t.allowZero),r=!!(t!=null&&t.allowNegativeOne),o=String(e??"").trim();if(!o)return;const l=Number(o);if(!Number.isFinite(l))return;const u=Math.trunc(l);if(r&&u===-1)return-1;if(!(!n&&u<=0)&&!(n&&u<0))return u}function EL(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,o=[];return n&&o.push(`recall_level=${n}`),r&&(typeof r.limit=="number"&&o.push(`limit=${r.limit}`),typeof r.min_score=="number"&&o.push(`min_score=${r.min_score}`),typeof r.max_input_tokens=="number"&&o.push(`max_input_tokens=${r.max_input_tokens}`)),o.length?o.join(" · "):null}function $L(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 o=typeof e.confidence=="number"&&Number.isFinite(e.confidence)?e.confidence:null;o!==null&&t.push(`confidence=${o.toFixed(3)}`);const l=e.provenance&&typeof e.provenance=="object"&&!Array.isArray(e.provenance)?e.provenance:null;if(l){const _=typeof l.writer_run_id=="string"?l.writer_run_id.trim():"",p=typeof l.writer_workflow_id=="string"?l.writer_workflow_id.trim():"";_&&t.push(`writer_run_id=${_}`),p&&t.push(`writer_workflow_id=${p}`)}const u=e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)?e.attributes:null,c=u&&u._retrieval&&typeof u._retrieval=="object"&&!Array.isArray(u._retrieval)?u._retrieval:null,f=c&&typeof c.score=="number"&&Number.isFinite(c.score)?c.score:null;return f!==null&&t.push(`score=${f.toFixed(3)}`),t.length?t.join(" · "):null}function AL(e,t){const n=String(e??""),r=String(t??"").trim();if(!r)return n;const o=n.toLowerCase().indexOf(r.toLowerCase());if(o<0)return n;const l=n.slice(0,o),u=n.slice(o,o+r.length),c=n.slice(o+r.length);return s.jsxs(s.Fragment,{children:[l,s.jsx("span",{className:"amx-hl",children:u}),c]})}function jf(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 TL(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 Sf(e){const t=TL(e);if(t===null)return"";const n=new Date(t),r=n.getUTCFullYear(),o=String(n.getUTCMonth()+1).padStart(2,"0"),l=String(n.getUTCDate()).padStart(2,"0"),u=String(n.getUTCHours()).padStart(2,"0"),c=String(n.getUTCMinutes()).padStart(2,"0");return`${r}/${o}/${l} ${u}:${c}`}function V0(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 Cp(e,t){const n=String(e??"").trim().toLowerCase();return!!(n&&t.has(n))}function ML(e,t={}){const n=Math.max(1,t.maxPredicates??3),r=new Map;for(const f of e){const _=String((f==null?void 0:f.predicate)||"").trim();_&&r.set(_,(r.get(_)||0)+1)}const o=Array.from(r.entries());o.sort((f,_)=>_[1]-f[1]||f[0].localeCompare(_[0]));const u=o.slice(0,n).map(([f,_])=>{const p=V0(f);return _>1?`${p}×${_}`:p}).join(" | "),c=o.length>n?` +${o.length-n}`:"";return`${u}${c}`.trim()}function RL({resetKey:e,queryMode:t,items:n,activeMemoryText:r,packets:o,packetsVersion:l,packedCount:u,dropped:c,estimatedTokens:f,effort:_,warnings:p,onQuery:y,onItemsReplace:w,onOpenSpan:x,onOpenTranscript:S}){var gi;const j=m.useRef(null),C=m.useMemo(()=>{const U=n==null?void 0:n[0],ie=n==null?void 0:n[n.length-1],be=U?`${U.subject}|${U.predicate}|${U.object}`:"",ke=ie?`${ie.subject}|${ie.predicate}|${ie.object}`:"";return`${(n==null?void 0:n.length)||0}:${be}:${ke}`},[n]),N=String(e??C),T=t==="replace"?"replace":"override",[L,P]=m.useState(null),[W,G]=m.useState(null),[Y,J]=m.useState(!1),[re,ae]=m.useState(""),[ue,B]=m.useState(!1),[A,$]=m.useState("");m.useEffect(()=>{P(null),G(null),ae(""),J(!1),$(""),B(!1)},[N]);const[z,E]=m.useState(""),[te,O]=m.useState(!0),[F,K]=m.useState(!1),[R,Q]=m.useState(!0),[Z]=m.useState(()=>({compact:bL(),show:!1})),X=Z.compact,[le,_e]=m.useState(Z.show),[he,ye]=m.useState(!1),Ee=N,ze=m.useMemo(()=>kg(Ee),[Ee]),[Be,gt]=m.useState("grid"),[Fe,tt]=m.useState(ze),[lt,Ye]=m.useState(!1),[Se,Re]=m.useState(1),ht=m.useRef(null),xe=m.useRef(null),Le=m.useRef(!1),[Ue,Ft]=m.useState(0),Qt=m.useRef(null),yn=m.useRef(0),Ut=m.useRef(0),It=m.useRef(0),jn=m.useRef(0),[ns,$t]=m.useState(!1),[fn,Un]=m.useState(""),[En,hn]=m.useState({}),On=m.useRef({});m.useEffect(()=>{On.current=En},[En]);const[_n,js]=m.useState(""),[Yn,Ss]=m.useState(""),Mr=m.useMemo(()=>{var ie;const U=(ie=n==null?void 0:n[0])==null?void 0:ie.scope;return jv(U,"session")},[n]),[Pn,ce]=m.useState(Mr),[je,Je]=m.useState("standard"),[Ve,rt]=m.useState(""),[ct,Et]=m.useState(""),[St,Kt]=m.useState(""),[xt,Yt]=m.useState(""),[Wt,Ot]=m.useState(""),[At,Tt]=m.useState(""),[De,sn]=m.useState(""),[dt,en]=m.useState("qwen/qwen3-next-80b");m.useEffect(()=>{ce(Mr)},[N]);const ft=Array.isArray(n)?n:[],Wn=typeof r=="string"?r:"",cn=Array.isArray(o)?o:[],er=typeof l=="number"?l:void 0,ss=typeof u=="number"?u:void 0,Xr=typeof c=="number"?c:void 0,_r=typeof f=="number"?f:void 0,hi=_,mi=p,Ds=T==="override"&&(L!=null&&L.items)&&Array.isArray(L.items)?L.items:ft,de=typeof(L==null?void 0:L.active_memory_text)=="string"&&L.active_memory_text.trim()?L.active_memory_text:Wn,pr=(L==null?void 0:L.effort)??hi,co=(L==null?void 0:L.warnings)??mi,gr=m.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),Rr=m.useMemo(()=>R?Ds:(Ds||[]).filter(U=>!Cp(U==null?void 0:U.predicate,gr)),[Ds,R,gr]),Zr=m.useMemo(()=>gL(Ds,{groupEdges:te}),[Ds,te]),it=m.useMemo(()=>{if(R)return Zr;const U=[];for(const ie of Zr.edges){const ke=(ie&&ie.data&&Array.isArray(ie.data.assertions)?ie.data.assertions:[]).filter(qe=>!Cp(qe==null?void 0:qe.predicate,gr));if(!ke.length)continue;const Ae=ML(ke);U.push({...ie,label:Ae,data:{...ie.data,assertions:ke,predicateSummary:Ae}})}return{nodes:Zr.nodes,edges:U}},[Zr,R,gr]),on=m.useMemo(()=>it.nodes.map(U=>U.id),[it.nodes]),Fs=m.useMemo(()=>{const U=on[0]||"",ie=on[on.length-1]||"";return`${on.length}:${U}:${ie}`},[on]),Qr=m.useMemo(()=>{var ie;const U=new Map;for(const be of it.nodes)U.set(be.id,String(((ie=be.data)==null?void 0:ie.label)||be.id));return U},[it.nodes]),rs=m.useMemo(()=>{var ie;const U=new Map;for(const be of it.nodes)U.set(be.id,String(((ie=be.data)==null?void 0:ie.kind)||""));return U},[it.nodes]),zo=z.trim().toLowerCase(),Bo=m.useMemo(()=>{var ie;if(!zo)return new Set;const U=new Set;for(const be of it.nodes){const ke=String(be.id||"").toLowerCase(),Ae=String(((ie=be.data)==null?void 0:ie.label)||"").toLowerCase();(ke.includes(zo)||Ae.includes(zo))&&U.add(be.id)}return U},[it.nodes,zo]),Uo=m.useCallback((U,ie)=>{const be={};for(const ke of on){const Ae=U[ke]||ie[ke];be[ke]=Ae?{x:Ae.x,y:Ae.y}:{x:0,y:0}}return be},[on]);m.useEffect(()=>{hn(U=>{const ie=zu(it,{kind:Be,seed:Fe}),be={};for(const ke of on){const Ae=U[ke]||ie[ke];be[ke]=Ae?{x:Ae.x,y:Ae.y}:{x:0,y:0}}return be})},[it,Be,Fe,on,Fs]),m.useEffect(()=>{if(!Le.current)return;const U=j.current;if(!(!U||typeof U.fitView!="function")&&on.length){Le.current=!1;try{U.fitView({padding:.2,duration:0})}catch{try{U.fitView({padding:.2})}catch{}}}},[on.length,Fs,En]),m.useEffect(()=>{Ye(!1),ht.current=null,xe.current=null,Le.current=!1,yn.current=0,Ut.current=0,It.current=0;const U=Sv(Ee);if(U&&Object.keys(U.positions||{}).length){if(gt(U.kind),tt(U.seed),$t(!0),Un(U.saved_at||""),U.viewport){xe.current=U.viewport;const Ae=j.current;if(Ae&&typeof Ae.setViewport=="function"){try{Ae.setViewport(U.viewport,{duration:0})}catch{try{Ae.setViewport(U.viewport)}catch{}}xe.current=null}}else Le.current=!0;const ke=zu(it,{kind:U.kind,seed:U.seed});hn(Uo(U.positions,ke));return}$t(!1),Un("");const ie=kg(Ee);tt(ie);const be=zu(it,{kind:Be,seed:ie});hn(be),Be==="force"&&it.nodes.length>0&&it.nodes.length<=320&&(ht.current=wm(it,{seed:ie,positions:be,...bf(Se)}),Ye(!0))},[Ee]);const Dn=m.useMemo(()=>{const U=String(_n||"").trim(),ie=String(Yn||"").trim();return!U||!ie?null:yL(it,U,ie,{directed:F})},[it,_n,Yn,F]),yr=!!(Dn&&String(_n||"").trim()&&String(Yn||"").trim()),qn=m.useMemo(()=>{const U=String(_n||"").trim(),ie=String(Yn||"").trim();if(!U||!ie)return null;const be=F,ke=new Map,Ae=(ot,mt)=>{const Pt=ke.get(ot);Pt?Pt.push(mt):ke.set(ot,[mt])};for(const ot of it.edges)Ae(ot.source,ot.target),be||Ae(ot.target,ot.source);const qe=new Set,et=[];for(qe.add(U),et.push(U);et.length;){const ot=et.shift(),mt=ke.get(ot)||[];for(const Pt of mt)qe.has(Pt)||(qe.add(Pt),et.push(Pt))}return{reachableFromStart:qe.size,endReachable:qe.has(ie),nodes:it.nodes.length,edges:it.edges.length,assertions:Rr.length}},[F,it.edges,it.nodes.length,Yn,_n,Rr.length]),uo=m.useMemo(()=>new Set((Dn==null?void 0:Dn.nodeIds)||[]),[Dn]),_i=m.useMemo(()=>new Set((Dn==null?void 0:Dn.edgeIds)||[]),[Dn]),[$n,zs]=m.useState(""),[fs,tr]=m.useState(""),hs=!!(String($n||"").trim()||String(fs||"").trim()),Ma=m.useMemo(()=>{const U=new Set,ie=new Set,be=String($n||"").trim(),ke=String(fs||"").trim();if(be){U.add(be);for(const Ae of it.edges)(Ae.source===be||Ae.target===be)&&(ie.add(Ae.id),U.add(Ae.source),U.add(Ae.target));return{nodes:U,edges:ie}}if(ke){const Ae=it.edges.find(qe=>qe.id===ke);Ae&&(ie.add(Ae.id),U.add(Ae.source),U.add(Ae.target))}return{nodes:U,edges:ie}},[it.edges,fs,$n]);m.useEffect(()=>{zs(""),tr(""),js(""),Ss("")},[N]);const[fo,rn]=m.useState(!1);m.useEffect(()=>{rn(!1)},[N]),m.useEffect(()=>{lt||(ht.current=null)},[lt]),m.useEffect(()=>{if(Be!=="force")return;const U=ht.current;if(!U)return;const ie=bf(Se);U.options.springLength=ie.springLength,U.options.repulsionStrength=ie.repulsionStrength},[Be,Se]),m.useEffect(()=>{Be!=="force"&&lt&&Ye(!1)},[Be,lt]),m.useEffect(()=>{if(!lt||Be!=="force"||it.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;ht.current||(ht.current=wm(it,{seed:Fe,positions:On.current,...bf(Se)}));let U=0,ie=0,be=0;const ke=it.nodes.length<=140?2:1,Ae=1600,qe=.08,et=ot=>{if(U=window.requestAnimationFrame(et),ot-ie<33)return;ie=ot;const mt=ht.current;if(!mt){Ye(!1);return}wL(mt,ke),be+=ke,hn(xL(mt)),(vL(mt)<=qe||be>=Ae)&&Ye(!1)};return U=window.requestAnimationFrame(et),()=>{window.cancelAnimationFrame(U)}},[it,Be,lt,Fe]);const Ra=m.useMemo(()=>it.nodes.map(U=>{var an;const ie=uo.has(U.id),be=Bo.has(U.id),ke=$n===U.id,Ae=hs&&Ma.nodes.has(U.id),qe=jf((an=U.data)==null?void 0:an.kind),et="rgba(34, 211, 238, 0.88)",ot=be?"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)":"",mt=ie?"rgba(168, 85, 247, 0.9)":be?et:qe.stroke,Pt=ke?"0 0 0 2px rgba(255,255,255,0.20), 0 18px 46px rgba(0,0,0,0.55)":Ae?"0 0 0 1px rgba(96, 165, 250, 0.28), 0 12px 34px rgba(0,0,0,0.45)":void 0,Jt=ot&&Pt?`${ot}, ${Pt}`:Pt||ot||void 0,Zn=ie?"rgba(168, 85, 247, 0.10)":be?"rgba(34, 211, 238, 0.08)":qe.bg,zt=yr?ie||ke?1:.16:hs?Ae||ke?1:.1:1;return{...U,position:En[U.id]?{x:En[U.id].x,y:En[U.id].y}:U.position,style:{...U.style||{},border:`1px solid ${mt}`,borderRadius:10,background:Zn,color:"rgba(255,255,255,0.92)",opacity:zt,padding:8,fontSize:12,boxShadow:Jt,width:180,cursor:"pointer"}}}),[it.nodes,yr,Bo,En,$n,uo,hs,Ma.nodes]),Rc=m.useMemo(()=>it.edges.map(U=>{const ie=_i.has(U.id),be=fs===U.id,ke=hs&&Ma.edges.has(U.id),Ae=ie?"rgba(168, 85, 247, 0.9)":hs?ke||be?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",qe=ie?2.75:hs?ke||be?2.25:1.25:1.5,et=be?"drop-shadow(0 0 10px rgba(168, 85, 247, 0.25))":void 0,ot=ie?"rgba(168, 85, 247, 0.9)":yr?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",mt=yr?ie||be?1:.1:hs?ke||be?1:.08:1,Pt=yr?ie||be?1:0:hs?ke||be?1:0:1,Jt=yr?ie||be?String(U.label||""):"":String(U.label||"");return{...U,label:Jt,style:{...U.style||{},stroke:Ae,strokeWidth:qe,filter:et,opacity:mt},animated:!1,markerEnd:{type:qf.ArrowClosed,color:ot,width:20,height:20},labelShowBg:!0,labelBgPadding:[6,3],labelBgBorderRadius:10,labelBgStyle:{fill:`rgba(0, 0, 0, ${.38*Pt})`,stroke:`rgba(255, 255, 255, ${.14*Pt})`,strokeWidth:1},labelStyle:{fill:`rgba(255, 255, 255, ${.92*Pt})`,fontSize:10,fontWeight:600,letterSpacing:.2,textTransform:"lowercase"}}}),[it.edges,yr,fs,_i,hs,Ma.edges]),Wo=m.useMemo(()=>{if(!fs)return[];const U=it.edges.find(be=>be.id===fs),ie=U&&U.data&&Array.isArray(U.data.assertions)?U.data.assertions:[];return Array.isArray(ie)?ie:[]},[it.edges,fs]),ms=m.useMemo(()=>fs&&it.edges.find(U=>U.id===fs)||null,[it.edges,fs]),Lr=m.useMemo(()=>{const U=String($n||"").trim();return U?Ds.filter(ie=>!ie||typeof ie!="object"||!(ie.subject===U||ie.object===U)?!1:R?!0:!Cp(ie.predicate,gr)):[]},[Ds,$n,R,gr]),Ir=m.useMemo(()=>fs?Wo:Lr,[Wo,fs,Lr]),ho=m.useMemo(()=>{const U=new Map;for(const ie of Ir){if(!ie||typeof ie!="object")continue;const be=ie.provenance&&typeof ie.provenance=="object"&&!Array.isArray(ie.provenance)?ie.provenance:null,ke=be&&typeof be.span_id=="string"?be.span_id.trim():"",Ae=be&&typeof be.writer_run_id=="string"?be.writer_run_id.trim():"",qe=typeof ie.owner_id=="string"?ie.owner_id.trim():"",et=Ae||qe;if(!et||!ke)continue;const ot=`${et}|${ke}`,mt=U.get(ot),Pt=typeof ie.observed_at=="string"?ie.observed_at.trim():"";mt?(mt.count+=1,Pt&&(!mt.last_observed_at||Pt>mt.last_observed_at)&&(mt.last_observed_at=Pt,mt.last_observed_at_fmt=Sf(Pt),mt.assertion=ie)):U.set(ot,{span_run_id:et,span_id:ke,writer_run_id:Ae,count:1,last_observed_at:Pt,last_observed_at_fmt:Sf(Pt),assertion:ie})}return Array.from(U.values()).sort((ie,be)=>String(be.last_observed_at||"").localeCompare(String(ie.last_observed_at||"")))},[Ir]),wr=m.useMemo(()=>{const U=new Map;for(const ie of Ir){if(!ie||typeof ie!="object")continue;const be=ie.provenance&&typeof ie.provenance=="object"&&!Array.isArray(ie.provenance)?ie.provenance:null,ke=be&&typeof be.span_id=="string"?be.span_id.trim():"",Ae=be&&typeof be.writer_run_id=="string"?be.writer_run_id.trim():"";if(!Ae||ke)continue;const qe=U.get(Ae),et=typeof ie.observed_at=="string"?ie.observed_at.trim():"";qe?(qe.count+=1,et&&(!qe.last_observed_at||et>qe.last_observed_at)&&(qe.last_observed_at=et,qe.last_observed_at_fmt=Sf(et),qe.assertion=ie)):U.set(Ae,{run_id:Ae,count:1,last_observed_at:et,last_observed_at_fmt:Sf(et),assertion:ie})}return Array.from(U.values()).sort((ie,be)=>String(be.last_observed_at||"").localeCompare(String(ie.last_observed_at||"")))},[Ir]),ks=m.useCallback(U=>{const ie=String(U.run_id||"").trim(),be=typeof U.span_id=="string"?String(U.span_id).trim():"";if(ie){if(S){try{S({run_id:ie,span_id:be||void 0,assertion:U.assertion})}catch{}return}if(x&&be)try{x({run_id:ie,span_id:be,assertion:U.assertion})}catch{}}},[x,S]),vr=m.useCallback(async U=>{var be;const ie=String(U??"");if(ie){try{if(typeof((be=navigator.clipboard)==null?void 0:be.writeText)=="function"){await navigator.clipboard.writeText(ie);return}}catch{}try{const ke=document.createElement("textarea");ke.value=ie,ke.style.position="fixed",ke.style.left="-9999px",document.body.appendChild(ke),ke.select(),document.execCommand("copy"),document.body.removeChild(ke)}catch{}}},[]),Or=m.useCallback(()=>{const U=j.current;if(!(!U||typeof U.fitView!="function")){if($n&&typeof U.getNode=="function"){const ie=U.getNode($n);if(ie){U.fitView({nodes:[ie],padding:.55,duration:350});return}}U.fitView({padding:.2,duration:350})}},[$n]),nr=m.useCallback(U=>{const ie=U.kind,be=Math.trunc(U.seed);Ye(!1),ht.current=null,xe.current=null,gt(ie),tt(be);const ke=zu(it,{kind:ie,seed:be});hn(ke),ie==="force"&&(U.autoPlay??!0)&&it.nodes.length>0&&it.nodes.length<=320&&(ht.current=wm(it,{seed:be,positions:ke,...bf(Se)}),Ye(!0))},[it,Se]),Li=m.useCallback(()=>{if(Be==="force"){if(lt){Ye(!1);return}ht.current=wm(it,{seed:Fe,positions:On.current,...bf(Se)}),Ye(!0)}},[it,Be,lt,Fe,Se]);m.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&jn.current&&window.cancelAnimationFrame(jn.current)},[]);const is=m.useCallback(()=>{const U=j.current;if(!U||typeof U.getViewport!="function"||!on.length)return null;const ie=Qt.current;if(!ie)return null;const be=ie.getBoundingClientRect();if(!Number.isFinite(be.width)||!Number.isFinite(be.height)||be.width<64||be.height<64)return null;const ke=U.getViewport(),Ae=typeof(ke==null?void 0:ke.zoom)=="number"&&Number.isFinite(ke.zoom)?ke.zoom:null,qe=typeof(ke==null?void 0:ke.x)=="number"&&Number.isFinite(ke.x)?ke.x:null,et=typeof(ke==null?void 0:ke.y)=="number"&&Number.isFinite(ke.y)?ke.y:null;if(Ae===null||qe===null||et===null||Ae<=0)return null;const ot=140,mt=Math.min(on.length,180),Pt=On.current;let Jt=0,Zn=0;for(const zt of on){const an=Pt[zt];if(!an||!Number.isFinite(an.x)||!Number.isFinite(an.y))continue;Zn+=1;const pn=[{x:an.x,y:an.y},{x:an.x+90,y:an.y+24}];for(const wn of pn){const _s=wn.x*Ae+qe,Ns=wn.y*Ae+et;if(_s>-ot&&_s<be.width+ot&&Ns>-ot&&Ns<be.height+ot)return!1}if(Jt++,Jt>=mt)break}return Zn?!0:null},[on]),Pr=m.useCallback(U=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||jn.current||(jn.current=window.requestAnimationFrame(()=>{jn.current=0;const ie=is();if(ie===null){if(It.current>=12)return;It.current+=1,window.setTimeout(()=>Pr(`${U}:probe`),120);return}if(ie!==!0){It.current=0,Ut.current=0;return}It.current=0;const be=j.current;if(be&&typeof be.fitView=="function")try{be.fitView({padding:.2,duration:0})}catch{try{be.fitView({padding:.2})}catch{}}if(Ut.current+=1,Ut.current>=4&&yn.current<1){Ut.current=0,yn.current+=1,Ft(ke=>ke+1);return}Ut.current<8&&window.setTimeout(()=>Pr(`${U}:retry`),220)}))},[is]);m.useEffect(()=>{Ut.current=0,yn.current=0,It.current=0,Pr("mount")},[N,Pr]),m.useEffect(()=>{Pr("graph change")},[Fs,Pr]),m.useEffect(()=>{const U=Qt.current;if(!U||typeof window>"u"||typeof ResizeObserver!="function")return;const ie=new ResizeObserver(()=>Pr("resize"));return ie.observe(U),()=>ie.disconnect()},[Pr]);const La=m.useCallback(()=>{const U=new Date().toISOString(),ie={};for(const et of on){const ot=On.current[et];ot&&typeof ot.x=="number"&&typeof ot.y=="number"&&(ie[et]={x:ot.x,y:ot.y})}const be=j.current,ke=be&&typeof be.toObject=="function"?be.toObject():null,Ae=ke&&ke.viewport?ke.viewport:be&&typeof be.getViewport=="function"?be.getViewport():null,qe=U0(Ae,{minZoom:Ng,maxZoom:Cg,maxAbsTranslate:H0})??void 0;kL(Ee,{version:1,kind:Be,seed:Fe,positions:ie,viewport:qe,saved_at:U}),$t(!0),Un(U),Ye(!1)},[Ee,Be,Fe,on]),xr=m.useCallback(()=>{const U=Sv(Ee);if(!U)return;Ye(!1),ht.current=null,gt(U.kind),tt(U.seed),$t(!0),Un(U.saved_at||""),xe.current=U.viewport||null,Le.current=!U.viewport;const ie=zu(it,{kind:U.kind,seed:U.seed});if(hn(Uo(U.positions,ie)),U.viewport){const be=j.current;if(be&&typeof be.setViewport=="function"){try{be.setViewport(U.viewport,{duration:0})}catch{try{be.setViewport(U.viewport)}catch{}}xe.current=null}}},[Uo,it,Ee]),mo=m.useCallback(()=>{NL(Ee),$t(!1),Un("")},[Ee]),Lc=m.useCallback(U=>{if(!Array.isArray(U)||U.length===0)return;let ie=!1;hn(be=>{let ke=be,Ae=!1;for(const qe of U){const et=qe&&typeof qe=="object"&&"id"in qe&&typeof qe.id=="string"?String(qe.id):"",ot=(qe==null?void 0:qe.type)==="position"?qe==null?void 0:qe.position:null;et&&ot&&typeof ot.x=="number"&&typeof ot.y=="number"&&(Ae||(ke={...be},Ae=!0),ke[et]={x:ot.x,y:ot.y},qe!=null&&qe.dragging&&(ie=!0))}return Ae?ke:be}),ie&&lt&&Ye(!1)},[lt]),Ii=m.useMemo(()=>{const U=new Map;for(const ie of it.edges)U.set(ie.id,ie);return U},[it.edges]),sr=m.useMemo(()=>{var ke;if(!Dn)return[];const U=Dn.nodeIds||[],ie=Dn.edgeIds||[],be=[];for(let Ae=0;Ae<Math.min(U.length-1,ie.length);Ae++){const qe=U[Ae],et=U[Ae+1],ot=ie[Ae],mt=Ii.get(ot),Pt=String(((ke=mt==null?void 0:mt.data)==null?void 0:ke.predicateSummary)||(mt==null?void 0:mt.label)||"").trim(),Jt=mt&&mt.source===qe&&mt.target===et?"forward":mt&&mt.source===et&&mt.target===qe?"reverse":"unknown";be.push({from:qe,to:et,edgeId:ot,predicate:Pt,dir:Jt})}return be},[Ii,Dn]),rd=m.useCallback(async()=>{if(y){ae(""),$(""),J(!0);try{const U=CL(Wt),ie=Np(At,{allowZero:!0,allowNegativeOne:!0}),be=Np(De,{allowZero:!0}),ke=await y({scope:Pn,owner_id:void 0,recall_level:je,query_text:Ve||void 0,subject:ct||void 0,predicate:St||void 0,object:xt||void 0,min_score:U,limit:ie,max_input_tokens:be,model:dt||void 0});P(ke),G("live query"),T==="replace"&&w&&ke&&Array.isArray(ke.items)&&w(ke.items,{kind:"live query",result:ke})}catch(U){const ie=U instanceof Error?U.message:String(U);ae(ie||"Query failed")}finally{J(!1)}}},[At,De,Wt,dt,xt,w,y,St,T,Ve,je,Pn,ct]),rr=m.useCallback(async()=>{if(!y)return;const U=String(_n||"").trim(),ie=String(Yn||"").trim();if(!U||!ie)return;const be=Math.max(200,Np(At)??80),ke=60;$(""),ae(""),B(!0);try{const Ae=[],qe=new Set,et=zt=>{if(!zt||typeof zt!="object"||typeof zt.subject!="string"||typeof zt.predicate!="string"||typeof zt.object!="string")return;const an=`${zt.subject}|${zt.predicate}|${zt.object}|${String(zt.observed_at||"")}|${String(zt.scope||"")}|${String(zt.owner_id||"")}`;qe.has(an)||(qe.add(an),Ae.push(zt))};for(const zt of Ds)et(zt);const ot=F,mt=new Set,Pt=[U],Jt=new Set([U]),Zn=async zt=>{const an=await y({scope:Pn,recall_level:je,min_score:0,limit:be,subject:zt,query_text:void 0,max_input_tokens:0,model:void 0});if(an&&Array.isArray(an.items)){for(const pn of an.items)if(et(pn),typeof pn.subject=="string"&&pn.subject.trim()===zt&&typeof pn.object=="string"){const wn=pn.object.trim();wn&&!Jt.has(wn)&&(Jt.add(wn),Pt.push(wn))}}if(!ot){const pn=await y({scope:Pn,recall_level:je,min_score:0,limit:be,object:zt,query_text:void 0,max_input_tokens:0,model:void 0});if(pn&&Array.isArray(pn.items)){for(const wn of pn.items)if(et(wn),typeof wn.object=="string"&&wn.object.trim()===zt&&typeof wn.subject=="string"){const _s=wn.subject.trim();_s&&!Jt.has(_s)&&(Jt.add(_s),Pt.push(_s))}}}};for(;Pt.length&&mt.size<ke&&!Jt.has(ie);){const zt=Pt.shift();!zt||mt.has(zt)||(mt.add(zt),await Zn(zt))}P({ok:!0,count:Ae.length,items:Ae,active_memory_text:de,raw:{expanded_for_path:!0,expanded_nodes:mt.size,discovered_nodes:Jt.size,merged:Ae.length,directed:ot}}),G("expanded neighborhood"),T==="replace"&&w&&w(Ae,{kind:"expanded neighborhood",result:{ok:!0,count:Ae.length,items:Ae,active_memory_text:de,raw:{expanded_for_path:!0,expanded_nodes:mt.size,discovered_nodes:Jt.size,merged:Ae.length,directed:ot}}})}catch(Ae){const qe=Ae instanceof Error?Ae.message:String(Ae);$(qe||"Expand neighborhood failed")}finally{B(!1)}},[F,de,Ds,At,w,y,Yn,_n,T,je,Pn]),_o=m.useCallback(()=>{P(null),G(null),ae(""),J(!1),$(""),B(!1),js(""),Ss(""),zs(""),tr("")},[]),ir="Search KG",qo=it.nodes.length,pi=it.edges.length,bl=Rr.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:Be,onChange:U=>gt(Eg(U.target.value,Be)),disabled:!on.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)"})]}),Be==="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:Se,onChange:U=>Re(q0(Number(U.target.value),.7,2.2,1))}),s.jsxs("span",{className:"amx-small",children:[Se.toFixed(1),"×"]})]}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>nr({kind:Be,seed:Fe}),disabled:!on.length,children:"Apply"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Li,disabled:!on.length||Be!=="force",children:lt?"Pause simulation":"Play simulation"})]})}),s.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:Qt,children:[s.jsx(dy,{children:s.jsxs(P0,{nodes:Ra,edges:Rc,defaultViewport:{x:0,y:0,zoom:1},minZoom:Ng,maxZoom:Cg,onInit:U=>{j.current=U;const ie=xe.current;if(ie&&typeof U.setViewport=="function")try{U.setViewport(ie,{duration:0})}catch{try{U.setViewport(ie)}catch{}}if(Le.current&&typeof U.fitView=="function")try{U.fitView({padding:.2,duration:0})}catch{try{U.fitView({padding:.2})}catch{}}xe.current=null,Le.current=!1,Pr("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:Lc,onNodeClick:(U,ie)=>{tr(""),zs(ie.id)},onEdgeClick:(U,ie)=>{zs(""),tr(ie.id)},onPaneClick:()=>{zs(""),tr("")},children:[s.jsx(oL,{className:"amx-flow-controls",children:s.jsx(qu,{type:"button",className:`amx-control-legend ${he?"amx-control-legend-active":""}`,onClick:()=>ye(U=>!U),title:he?"Hide node color legend":"Show node color legend","aria-label":he?"Hide node color legend":"Show node color legend",children:s.jsx(jL,{})})}),s.jsx(Bf,{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:()=>_e(U=>!U),title:le?"Hide minimap preview":"Show minimap preview","aria-label":le?"Hide minimap preview":"Show minimap preview",children:le?"minimap on":"minimap off"})})}),le?s.jsx(QR,{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:X?120:160,height:X?80:110,marginBottom:56},nodeColor:U=>{var ie;return jf((ie=U.data)==null?void 0:ie.kind).minimap}}):null,he?s.jsxs(Bf,{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:U,label:ie})=>s.jsx("span",{className:"amx-legend-item",style:{borderColor:jf(U).stroke},children:ie},U))})]}):null,s.jsx(fL,{gap:20,size:1,color:"rgba(255,255,255,0.06)"})]})},Ue),s.jsxs("details",{className:"amx-panel amx-controls",children:[s.jsxs("summary",{children:[s.jsx("span",{className:"amx-controls-title",children:ir}),s.jsxs("span",{className:"amx-small",children:[bl," assertions · ",qo," nodes · ",pi," 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:z,onChange:U=>E(U.target.value),placeholder:"filter nodes by id/label"})]}),s.jsxs("label",{children:["group edges",s.jsxs("select",{value:String(te),onChange:U=>O(U.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(R),onChange:U=>Q(U.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(F),onChange:U=>K(U.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:Be,onChange:U=>gt(Eg(U.target.value,Be)),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:Fe,onChange:U=>tt(Math.trunc(Number(U.target.value||0)||0))})]})]}),s.jsxs("div",{className:"amx-actions",style:{marginTop:10},children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>nr({kind:Be,seed:Fe}),disabled:!on.length,children:"Apply layout"}),Be==="force"?s.jsx("button",{type:"button",className:"amx-btn",onClick:Li,disabled:!on.length,children:lt?"Pause simulation":"Play simulation"}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:La,disabled:!on.length,children:"Save layout"}),ns?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:xr,children:"Load saved"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:mo,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.",ns?s.jsxs("span",{children:[" ","(saved",fn?`: ${fn}`:"",")"]}):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:_n,onChange:U=>js(U.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),on.map(U=>s.jsx("option",{value:U,children:(()=>{const ie=Qr.get(U)||U;return ie===U?ie:`${ie} (${U})`})()},U))]})]}),s.jsxs("label",{children:["path end",s.jsxs("select",{value:Yn,onChange:U=>Ss(U.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),on.map(U=>s.jsx("option",{value:U,children:(()=>{const ie=Qr.get(U)||U;return ie===U?ie:`${ie} (${U})`})()},U))]})]})]}),Dn?s.jsx("div",{className:"amx-small",style:{marginTop:10},children:sr.map((U,ie)=>{const be=Qr.get(U.from)||U.from,ke=Qr.get(U.to)||U.to,Ae=U.dir==="reverse"?" ← ":" → ",qe=U.predicate?` (${U.predicate})`:"";return s.jsxs("div",{children:[ie===0?s.jsx("span",{children:be}):null,Ae,s.jsxs("span",{children:[ke,qe]})]},`${U.edgeId}:${ie}`)})}):_n&&Yn?s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["No path found in the current subgraph (",(qn==null?void 0:qn.assertions)??bl," assertions · ",(qn==null?void 0:qn.nodes)??it.nodes.length," nodes ·"," ",(qn==null?void 0:qn.edges)??it.edges.length," edges). Start reaches ",(qn==null?void 0:qn.reachableFromStart)??0," nodes.",y?s.jsx("div",{style:{marginTop:10},children:s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void rr(),disabled:ue,children:ue?"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:Ve,onChange:U=>rt(U.target.value),placeholder:"e.g. emotion chip"})]}),s.jsxs("label",{children:["subject (exact)",s.jsx("input",{value:ct,onChange:U=>Et(U.target.value),placeholder:"e.g. ex:person-data"})]}),s.jsxs("label",{children:["predicate (exact)",s.jsx("input",{value:St,onChange:U=>Kt(U.target.value),placeholder:"e.g. schema:about"})]}),s.jsxs("label",{children:["object (exact)",s.jsx("input",{value:xt,onChange:U=>Yt(U.target.value),placeholder:"e.g. ex:concept-emotion-chip"})]}),s.jsxs("label",{children:["min_score",s.jsx("input",{type:"number",step:"any",value:Wt,onChange:U=>Ot(U.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["limit",s.jsx("input",{type:"number",min:"-1",step:"1",value:At,onChange:U=>Tt(U.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:Pn,onChange:U=>ce(jv(U.target.value,Pn)),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:je,onChange:U=>Je(U.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:De,onChange:U=>sn(U.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["model (budgeting)",s.jsx("input",{value:dt,onChange:U=>en(U.target.value),placeholder:"qwen/qwen3-next-80b"})]})]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void rd(),disabled:!y||Y,children:Y?"Querying…":"Query store"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:_o,disabled:!L&&!re&&!Y,children:"Reset to step output"}),L?s.jsxs("span",{className:"amx-small",children:["showing: ",W||"live query"]}):s.jsx("span",{className:"amx-small",children:"showing: step output"}),re?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:re}):null,A?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:A}):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 U=EL(pr);return U?s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:U}):null})(),(()=>{const U=co;if(!U)return null;const ie=typeof U=="string"?U:Array.isArray(U)?U.map(be=>String(be)).join(" · "):JSON.stringify(U);return!ie||!ie.trim()?null:s.jsx("div",{className:"amx-small",style:{marginBottom:8,color:"var(--warning, rgba(255, 180, 90, 0.95))"},children:ie})})(),s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:(()=>{const U=(L==null?void 0:L.packets_version)??er,ie=(L==null?void 0:L.packed_count)??ss,be=(L==null?void 0:L.dropped)??Xr,ke=(L==null?void 0:L.estimated_tokens)??_r,Ae=[];return typeof U=="number"&&Ae.push(`packets_v${U}`),typeof ie=="number"&&Ae.push(`packed=${ie}`),typeof be=="number"&&Ae.push(`dropped=${be}`),typeof ke=="number"&&Ae.push(`est_tokens=${ke}`),Ae.length?Ae.join(" · "):"No packetization stats (set max_input_tokens > 0)."})()}),s.jsx("div",{className:"amx-active-memory",children:AL(de||"(empty)",z)}),(()=>{const U=L!=null&&L.packets&&Array.isArray(L.packets)?L.packets:cn;return!Array.isArray(U)||U.length===0?null:s.jsxs("div",{style:{marginTop:10},children:[s.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>rn(ie=>!ie),children:[fo?"Hide":"Show"," packets (",U.length,")"]}),fo?s.jsx("div",{className:"amx-list",style:{marginTop:10},children:U.slice(0,120).map((ie,be)=>{const ke=ie&&typeof ie=="object"&&!Array.isArray(ie)?ie:null,Ae=ke&&typeof ke.statement=="string"?ke.statement:typeof ie=="string"?ie:"",qe=ke&&(typeof ke.retrieval_score=="number"||typeof ke.retrieval_score=="string")?ke.retrieval_score:null,et=ke&&typeof ke.observed_at=="string"?ke.observed_at:null;return s.jsxs("div",{className:"amx-item",children:[s.jsx("div",{className:"amx-mono",children:Ae||"(packet)"}),et||qe!==null?s.jsxs("div",{className:"amx-small",children:[et?`[${et}]`:null,et&&qe!==null?" ":null,qe!==null?`score:${qe}`:null]}):null]},be)})}):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."}),$n?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:Qr.get($n)||$n}),s.jsxs("div",{className:"amx-small",children:["kind=",rs.get($n)||"entity"," · id=",$n]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void vr($n),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Or,children:"Focus"})]})]}):ms&&ms.source&&ms.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:[ms.source," —",String(ms.label||((gi=ms.data)==null?void 0:gi.predicateSummary)||"").trim()||"?","→ ",ms.target]}),s.jsxs("div",{className:"amx-small",children:["edge_id=",ms.id]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void vr(ms.id),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Or,children:"Fit"})]})]}):s.jsx("div",{className:"amx-small",style:{marginBottom:10,opacity:.9},children:"(no selection)"}),s.jsx("div",{className:"amx-list",children:Ir.slice(0,80).map((U,ie)=>{const be=String(U.subject||"").trim(),ke=String(U.predicate||"").trim(),Ae=String(U.object||"").trim(),qe=Qr.get(be)||be,et=Qr.get(Ae)||Ae,ot=rs.get(be)||"entity",mt=rs.get(Ae)||"entity",Pt=jf(ot),Jt=jf(mt),Zn=Sf(U.observed_at),zt=$L(U),an=U.provenance&&typeof U.provenance=="object"&&!Array.isArray(U.provenance)?U.provenance:null,pn=an&&typeof an.span_id=="string"?an.span_id.trim():"",wn=an&&typeof an.writer_run_id=="string"?an.writer_run_id.trim():"",_s=typeof U.owner_id=="string"?U.owner_id.trim():"",Ns=wn||_s,br=!!((S||x)&&pn&&Ns),Ho=!!(S&&wn&&!pn),Vo=br||Ho;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:Pt.stroke,background:Pt.bg},title:be,onClick:()=>{be&&(tr(""),zs(be))},children:qe||be||"(subject)"}),s.jsx("span",{className:"amx-arrow",children:"—"}),s.jsx("span",{className:"amx-predicate",title:ke,children:V0(ke)||"(predicate)"}),s.jsx("span",{className:"amx-arrow",children:"→"}),s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Jt.stroke,background:Jt.bg},title:Ae,onClick:()=>{Ae&&(tr(""),zs(Ae))},children:et||Ae||"(object)"})]}),s.jsxs("div",{className:"amx-triple-meta",children:[Zn?s.jsxs("span",{className:"amx-small",title:String(U.observed_at||""),children:["[",Zn,"]"]}):null,zt?s.jsx("span",{className:"amx-small",children:zt}):null]}),pn||wn?s.jsxs("div",{className:"amx-triple-actions",children:[pn?s.jsxs("span",{className:"amx-small",children:["span:",pn]}):null,wn?s.jsxs("span",{className:"amx-small",children:["run:",wn]}):null,Vo?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(br&&pn&&Ns){ks({run_id:Ns,span_id:pn,assertion:U});return}Ho&&wn&&ks({run_id:wn,assertion:U})},children:"Open transcript"}):null]}):null]},ie)})})]}),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)."}),ho.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:ho.slice(0,60).map(U=>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:",U.span_id]}),s.jsxs("div",{className:"amx-small",children:["run_id=",U.span_run_id," · assertions=",U.count,U.last_observed_at_fmt?` · last=[${U.last_observed_at_fmt}]`:""]})]}),x||S?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>ks({run_id:U.span_run_id,span_id:U.span_id,assertion:U.assertion}),children:"Open transcript"}):null]},`${U.span_run_id}|${U.span_id}`))})]}):null,S&&wr.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:wr.slice(0,40).map(U=>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:",U.run_id]}),s.jsxs("div",{className:"amx-small",children:["assertions=",U.count,U.last_observed_at_fmt?` · last=[${U.last_observed_at_fmt}]`:""]})]}),s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>ks({run_id:U.run_id,assertion:U.assertion}),children:"Open transcript"})]},U.run_id))})]}):null,!ho.length&&!(S&&wr.length)?s.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})})}function pl({open:e,title:t,children:n,actions:r,variant:o="default",onClose:l}){const u=m.useId();if(m.useEffect(()=>{if(!e)return;const f=_=>{_.key==="Escape"&&l()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,l]),!e)return null;const c=o==="fullscreen";return s.jsx("div",{className:`modal_backdrop${c?" fullscreen":""}`,onMouseDown:f=>{f.target===f.currentTarget&&l()},children:s.jsxs("div",{className:`modal_panel${c?" fullscreen":""}`,role:"dialog","aria-modal":"true","aria-labelledby":u,children:[s.jsxs("div",{className:"modal_header",children:[s.jsx("div",{className:"modal_title",id:u,children:t}),s.jsx("button",{className:"btn",onClick:l,children:"Close"})]}),s.jsx("div",{className:"modal_body",children:n}),r?s.jsx("div",{className:"modal_footer",children:r}):null]})})}function Ep(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function fl(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 wc(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"),o=String(t.getUTCDate()).padStart(2,"0"),l=String(t.getUTCHours()).padStart(2,"0"),u=String(t.getUTCMinutes()).padStart(2,"0");return`${n}/${r}/${o} ${l}:${u}`}function LL(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=fl(t);return n!==null?wc(n):t}function hy(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,`
136
+ `).replace(/\\n/g,`
137
+ `).replace(/\\t/g," "):""}function G0(e){return String(e??"").replace(/[*_`~]/g,"")}function vm(e,t){const n=!!(t!=null&&t.strip_punct),r=hy(e);let o=G0(r).replace(/\s+/g," ").trim().toLowerCase();return n&&(o=o.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),o}function xm(e,t){const n=String(t??"").trim();if(!n)return!1;const r=vm(n,{strip_punct:!1});if(!r)return!1;if(vm(String(e??""),{strip_punct:!1}).includes(r))return!0;const l=vm(n,{strip_punct:!0});return l?vm(String(e??""),{strip_punct:!0}).includes(l):!1}function kv(e){const t=hy(e).trim();if(!t)return[];const n=[],r=u=>{const c=String(u??"").replace(/\s+/g," ").trim();c&&(c.length<6||n.includes(c)||n.push(c))},o=t.search(/[`*_~]/);if(o>0){const u=t.slice(0,o);u.replace(/\s+/g," ").trim().length>=10&&r(u)}const l=[/`([^`]+)`/g,/\*\*([^*]+)\*\*/g,/__([^_]+)__/g,/\*([^*]+)\*/g,/_([^_]+)_/g];for(const u of l){let c;for(;(c=u.exec(t))!==null;){const f=String(c[1]??"").trim();f&&r(f)}}return r(G0(t)),n}function IL(e){const t=String(e??"").replace(/\r\n/g,`
138
+ `).replace(/\r/g,`
139
+ `);if(!t)return null;const n=t.split(`
140
+ `);let r;const o=[],l=[];let u=null,c=[],f=!1;const _=()=>{if(!u)return;const w=c.join(`
141
+ `).trim();w&&l.push({role:u,lines:[w]}),u=null,c=[]};for(const w of n){const x=r?null:w.match(/^\s*created_at\s*=\s*(.+)\s*$/i);if(x&&x[1]){r=x[1].trim();continue}const S=w.match(/^\s*(USER|ASSISTANT|SYSTEM)\s*:\s*(.*)$/i);if(S){f=!0,_();const j=String(S[1]||"").trim().toLowerCase();u=j==="user"?"user":j==="assistant"?"assistant":"system";const C=String(S[2]??"");c=C?[C]:[];continue}u?c.push(w):o.push(w)}if(_(),!f||!l.length)return null;const p=o.join(`
142
+ `).trim(),y={messages:[]};r&&(y.created_at=r),p&&y.messages.push({role:"system",content:p});for(const w of l)y.messages.push({role:w.role,content:w.lines.join(`
143
+ `)});return y.messages.length?y:null}function Nv(e,t){const n=String(e||""),r=String(t||"");return r>n?r:n}function Cv(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(),o=String((e==null?void 0:e.observed_at)||"").trim(),l=String((e==null?void 0:e.scope)||"").trim(),u=String((e==null?void 0:e.owner_id)||"").trim();return`${t}|${n}|${r}|${o}|${l}|${u}`}function OL(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(),o=String((e==null?void 0:e.object)||"").trim(),l=String((e==null?void 0:e.scope)||"").trim(),u=String((e==null?void 0:e.owner_id)||"").trim(),c=[];l&&c.push(`scope=${l}`),u&&c.push(`owner=${u}`);const f=c.length?` (${c.join(", ")})`:"";return`${t?`[${t}] `:""}${n} --${r}--> ${o}${f}`}function PL({gateway:e,selected_run_id:t,selected_session_id:n}){const[r,o]=m.useState(String(t||"").trim()),[l,u]=m.useState(String(n||"").trim()),[c,f]=m.useState("all"),_=c==="all",[p,y]=m.useState(!0),[w,x]=m.useState(750),[S,j]=m.useState(5e3),[C,N]=m.useState([]),[T,L]=m.useState(void 0),[P,W]=m.useState(""),[G,Y]=m.useState(!1),[J,re]=m.useState([]),[ae,ue]=m.useState(!1),[B,A]=m.useState(!1),[$,z]=m.useState(""),[E,te]=m.useState(""),[O,F]=m.useState(""),[K,R]=m.useState(""),[Q,Z]=m.useState("artifact"),[X,le]=m.useState(null),[_e,he]=m.useState(""),[ye,Ee]=m.useState(null),ze=m.useRef(!1),Be=m.useMemo(()=>{const ce=ye,je=ce!=null&&ce.attributes&&typeof ce.attributes=="object"&&!Array.isArray(ce.attributes)?ce.attributes:null;return(je&&typeof je.evidence_quote=="string"?String(je.evidence_quote):"").trim()},[ye]),gt=m.useMemo(()=>{const ce=X,je=ce&&typeof ce=="object"&&!Array.isArray(ce)?ce:null,Je=je&&typeof je.note=="string"?String(je.note):"";return hy(Je).trim()},[X]),Fe=m.useMemo(()=>{const ce=X&&typeof X=="object"&&!Array.isArray(X)?X:null,je=ce&&Array.isArray(ce.messages)?ce.messages:null;return Array.isArray(je)?je:null},[X]),tt=m.useMemo(()=>{const ce=gt,je=Be;return!ce||!je?!1:xm(ce,je)},[Be,gt]),lt=m.useMemo(()=>{const ce=Fe,je=Be;if(!ce||!je)return[];const Je=[];for(let Ve=0;Ve<Math.min(ce.length,500);Ve++){const rt=ce[Ve],ct=(rt==null?void 0:rt.content)==null?"":String(rt.content);xm(ct,je)&&Je.push(Ve)}return Je},[Be,Fe]),Ye=m.useMemo(()=>new Set(lt),[lt]),Se=lt.length?lt[0]:null,Re=m.useCallback(ce=>{const je=document.getElementById(`source_msg_${ce}`);je&&typeof je.scrollIntoView=="function"&&je.scrollIntoView({block:"center",behavior:"smooth"})},[]),ht=m.useCallback(()=>{const ce=document.getElementById("source_note_hit_0")||document.getElementById("source_note_msg_hit_0");ce&&typeof ce.scrollIntoView=="function"&&ce.scrollIntoView({block:"center",behavior:"smooth"})},[]);m.useEffect(()=>{if(ae&&!(B||$)&&!ze.current){if(Se!==null){ze.current=!0,window.setTimeout(()=>Re(Se),0);return}if(tt){ze.current=!0,window.setTimeout(()=>ht(),0);return}}},[Re,ht,$,Se,B,tt,ae]);const xe=m.useRef(new Set),Le=m.useRef(""),Ue=m.useRef(null),Ft=m.useRef(null);m.useEffect(()=>{o(String(t||"").trim())},[t]),m.useEffect(()=>{u(String(n||"").trim())},[n]);const Qt=m.useMemo(()=>{const ce=String(r||"").trim(),je=String(l||"").trim();return`mindmap:${c}:${ce}:${je}`},[r,l,c]),yn=m.useMemo(()=>{let ce=null,je=null;for(const Je of C){const Ve=fl(Je==null?void 0:Je.observed_at);Ve!==null&&(ce=ce===null?Ve:Math.min(ce,Ve),je=je===null?Ve:Math.max(je,Ve))}return{min_ms:ce,max_ms:je}},[C]),Ut=1e3,It=m.useMemo(()=>{const ce=yn.min_ms,je=yn.max_ms;if(typeof ce!="number"||typeof je!="number"||!Number.isFinite(ce)||!Number.isFinite(je))return null;if(je<=ce)return{min_ms:ce,max_ms:ce,real_max_ms:je};const Je=ce+Math.ceil((je-ce)/Ut)*Ut;return{min_ms:ce,max_ms:Je,real_max_ms:je}},[yn.max_ms,yn.min_ms]),[jn,ns]=m.useState(!0),[$t,fn]=m.useState(null);m.useEffect(()=>{jn&&It&&fn(It.max_ms)},[jn,It]);const Un=m.useMemo(()=>{const ce=typeof $t=="number"?$t:null;return ce===null?C:C.filter(je=>{const Je=fl(je==null?void 0:je.observed_at);return Je===null?!0:Je<=ce})},[C,$t]),En=m.useCallback((ce,je)=>{const Je=Array.isArray(ce)?ce:[],Ve=String(Le.current||"").trim(),rt=new Set,ct=[];let Et="";for(const St of Je){if(!St||typeof St!="object"||typeof St.subject!="string"||typeof St.predicate!="string"||typeof St.object!="string")continue;const Kt=Cv(St);if(rt.has(Kt))continue;rt.add(Kt),ct.push(St);const xt=String(St.observed_at||"").trim();xt&&(Et=Nv(Et,xt))}N(ct),L(je==null?void 0:je.warnings),xe.current=rt,Le.current=Et||Ve},[]),hn=m.useCallback(async ce=>{const je=Ep(ce.scope,"session"),Je=String(ce.subject||"").trim(),Ve=String(ce.predicate||"").trim(),rt=String(ce.object||"").trim(),ct=String(ce.since||"").trim(),Et=String(ce.until||"").trim(),St=String(ce.active_at||"").trim(),Kt=String(ce.query_text||"").trim(),xt=typeof ce.min_score=="number"&&Number.isFinite(ce.min_score)?Number(ce.min_score):void 0,Yt=ce.order==="asc"?"asc":"desc",Wt=typeof ce.limit=="number"&&Number.isFinite(ce.limit)?Number(ce.limit):0,Ot=String(r||"").trim(),At=String(l||"").trim(),Tt={scope:je,all_owners:_,limit:Wt,order:Yt};Je&&(Tt.subject=Je),Ve&&(Tt.predicate=Ve),rt&&(Tt.object=rt),ct&&(Tt.since=ct),Et&&(Tt.until=Et),St&&(Tt.active_at=St),Kt&&(Tt.query_text=Kt),typeof xt=="number"&&(Tt.min_score=xt),_||(je==="run"?Ot&&(Tt.run_id=Ot):je==="session"?At?Tt.session_id=At:Ot&&(Tt.run_id=Ot):je==="all"&&(Ot?Tt.run_id=Ot:At&&(Tt.session_id=At)));try{const De=await e.kg_query(Tt),sn=Array.isArray(De==null?void 0:De.items)?De.items:[],dt=De==null?void 0:De.warnings;return{ok:(De==null?void 0:De.ok)!==!1,count:Number((De==null?void 0:De.count)||sn.length),items:sn,warnings:dt,raw:De}}catch(De){const sn=De instanceof Error?De.message:String(De);if(sn.includes("Run '")&&sn.includes("not found")&&!At&&(je==="session"||je==="all")&&Ot){const en=await e.kg_query({...Tt,run_id:void 0,session_id:Ot}),ft=Array.isArray(en==null?void 0:en.items)?en.items:[],Wn=en==null?void 0:en.warnings;return{ok:(en==null?void 0:en.ok)!==!1,count:Number((en==null?void 0:en.count)||ft.length),items:ft,warnings:Wn,raw:en}}throw new Error(sn||"KG query failed")}},[_,e,r,l]),On=m.useCallback(async ce=>{var Ve;const je=String(ce.run_id||"").trim(),Je=String(ce.span_id||"").trim();if(!(!je||!Je)){ue(!0),A(!0),z(""),F(je),R(Je),Z("artifact"),te(`source span:${Je}`),le(null),he(""),Ee(ce.assertion&&typeof ce.assertion=="object"?ce.assertion:null),ze.current=!1;try{const rt=[je],ct=typeof((Ve=ce.assertion)==null?void 0:Ve.owner_id)=="string"?String(ce.assertion.owner_id).trim():"";ct&&ct!==je&&rt.push(ct);let Et=null,St=null;for(const Kt of rt)try{St=await(await e.download_run_artifact_content(Kt,Je)).text(),Kt!==je&&F(Kt);break}catch(xt){Et=xt instanceof Error?xt.message:String(xt)}if(St==null)throw new Error(Et||"Failed to load source span");he(St);try{const Kt=JSON.parse(St);le(Kt)}catch{le(null)}}catch(rt){const ct=rt instanceof Error?rt.message:String(rt);z(ct||"Failed to load source span")}finally{A(!1)}}},[e]),_n=m.useCallback(async ce=>{const je=String(ce.run_id||"").trim();if(!je)return null;try{const Je=await e.list_run_artifacts(je,{limit:200}),rt=(Array.isArray(Je==null?void 0:Je.items)?Je.items:[]).map(xt=>{const Yt=typeof(xt==null?void 0:xt.artifact_id)=="string"?String(xt.artifact_id).trim():"",Wt=xt!=null&&xt.tags&&typeof xt.tags=="object"&&!Array.isArray(xt.tags)?xt.tags:null,Ot=Wt&&typeof Wt.kind=="string"?String(Wt.kind).trim():"";return{artifact_id:Yt,kind:Ot}}).filter(xt=>!!(xt.artifact_id&&(xt.kind==="conversation_span"||xt.kind==="memory_note")));if(!rt.length)return null;if(rt.length===1)return rt[0].artifact_id;const ct=ce.assertion,Et=ct!=null&&ct.attributes&&typeof ct.attributes=="object"&&!Array.isArray(ct.attributes)?ct.attributes:null,Kt=(Et&&typeof Et.evidence_quote=="string"?String(Et.evidence_quote):"").trim();if(!Kt)return null;for(const xt of rt.slice(0,10))try{const Wt=await(await e.download_run_artifact_content(je,xt.artifact_id)).text(),Ot=JSON.parse(Wt);if(Ot&&typeof Ot=="object"){const At=typeof Ot.note=="string"?String(Ot.note):"";if(At&&At.includes(Kt))return xt.artifact_id;const Tt=Array.isArray(Ot.messages)?Ot.messages:null;if(Tt){for(const De of Tt.slice(0,200))if(((De==null?void 0:De.content)==null?"":String(De.content)).includes(Kt))return xt.artifact_id}}}catch{}}catch{}return null},[e]),js=m.useCallback(async ce=>{const je=String(ce.run_id||"").trim();if(je){ue(!0),A(!0),z(""),F(je),R(""),Z("run_input"),te(`transcript run:${je}`),le(null),he(""),Ee(ce.assertion&&typeof ce.assertion=="object"?ce.assertion:null),ze.current=!1;try{const Je=await _n({run_id:je,assertion:ce.assertion});if(Je){await On({run_id:je,span_id:Je,assertion:ce.assertion});return}const Ve=await e.get_run_input_data(je),rt=Ve&&typeof Ve=="object"&&!Array.isArray(Ve)?Ve.input_data:null,ct={kind:"run_input_data",run_id:je};if(Ve&&typeof(Ve==null?void 0:Ve.workflow_id)=="string"&&(ct.workflow_id=String(Ve.workflow_id)),rt&&typeof rt=="object"&&!Array.isArray(rt)){const Et=rt.context,Kt=(Et&&typeof Et=="object"&&Array.isArray(Et.messages)?Et.messages:null)||(Array.isArray(rt.messages)?rt.messages:null);Array.isArray(Kt)&&(ct.messages=Kt);const xt=["text","prompt","task","message"];for(const Yt of xt){const Wt=rt[Yt];if(typeof Wt=="string"&&Wt.trim()){ct.note=Wt.trim();break}}ct.input_data=rt}!ct.messages&&!ct.note&&(ct.note=JSON.stringify(rt??Ve??{},null,2));try{const Et=await e.get_run(je),St=Et&&typeof(Et==null?void 0:Et.created_at)=="string"?String(Et.created_at):"";St&&(ct.created_at=St)}catch{}le(ct),he(JSON.stringify(Ve,null,2))}catch(Je){const Ve=Je instanceof Error?Je.message:String(Je);z(Ve||"Failed to load run input transcript")}finally{A(!1)}}},[e,On,_n]),Yn=m.useCallback(async()=>{W(""),Y(!0);try{const ce=c==="all"?"all":c,je=await hn({scope:ce,limit:0,order:"desc"});En(je.items||[],{warnings:je.warnings}),Ue.current={scope:ce}}catch(ce){const je=ce instanceof Error?ce.message:String(ce);W(je||"Load failed")}finally{Y(!1)}},[hn,En,c]);m.useEffect(()=>{C.length||Yn()},[]);const Ss=m.useCallback(async ce=>{const je=Ep(ce.scope,"session");return Ft.current=ce,await hn({scope:je,subject:ce.subject,predicate:ce.predicate,object:ce.object,query_text:ce.query_text,min_score:ce.min_score,since:ce.since,until:ce.until,active_at:ce.active_at,limit:typeof ce.limit=="number"?ce.limit:0,order:"desc"})},[hn]),Mr=m.useCallback((ce,je)=>{var Je;if((je==null?void 0:je.kind)==="live query"){const Ve=Ft.current;Ve&&(Ue.current={scope:Ep(Ve.scope,"session"),subject:typeof Ve.subject=="string"?Ve.subject:void 0,predicate:typeof Ve.predicate=="string"?Ve.predicate:void 0,object:typeof Ve.object=="string"?Ve.object:void 0})}En(ce,{warnings:(Je=je==null?void 0:je.result)==null?void 0:Je.warnings})},[En]),Pn=m.useCallback(async()=>{const ce=Ue.current;if(!ce)return;const je=String(Le.current||"").trim(),Je=await hn({scope:ce.scope,subject:ce.subject,predicate:ce.predicate,object:ce.object,since:je||void 0,order:"asc",limit:0}),Ve=Array.isArray(Je.items)?Je.items:[];if(!Ve.length)return;const ct=Date.now()+Math.max(250,Math.min(2e4,S)),Et=xe.current,St=[],Kt=[];let xt=String(Le.current||"").trim();for(const Yt of Ve){if(!Yt||typeof Yt!="object"||typeof Yt.subject!="string"||typeof Yt.predicate!="string"||typeof Yt.object!="string")continue;const Wt=Cv(Yt);if(Et.has(Wt))continue;Et.add(Wt),St.push(Yt),Kt.push({id:Wt,assertion:Yt,expires_at_ms:ct});const Ot=String(Yt.observed_at||"").trim();Ot&&(xt=Nv(xt,Ot))}St.length&&(Le.current=xt,N(Yt=>{const Wt=Yt.concat(St);return Wt.sort((Ot,At)=>String((At==null?void 0:At.observed_at)||"").localeCompare(String((Ot==null?void 0:Ot.observed_at)||""))),Wt}),re(Yt=>{const Wt=Yt.concat(Kt);return Wt.sort((Ot,At)=>At.expires_at_ms-Ot.expires_at_ms),Wt.slice(0,30)}))},[S,hn]);return m.useEffect(()=>{if(!p)return;let ce=!1,je=null;const Je=async()=>{if(!ce){try{await Pn()}catch{}ce||(je=window.setTimeout(()=>void Je(),Math.max(250,Math.min(6e4,w))))}};return Je(),()=>{ce=!0,je!==null&&window.clearTimeout(je)}},[p,w,Pn]),m.useEffect(()=>{if(!J.length)return;const ce=window.setInterval(()=>{const je=Date.now();re(Je=>Je.filter(Ve=>Ve.expires_at_ms>je))},250);return()=>window.clearInterval(ce)},[J.length]),s.jsxs("div",{className:"mindmap_root",children:[s.jsxs("div",{className:"mindmap_bar",children:[s.jsx("button",{className:"btn",onClick:()=>void Yn(),disabled:G,children:G?"Loading…":"Load snapshot"}),s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"source"}),s.jsxs("select",{value:c,onChange:ce=>{const je=String(ce.target.value||"").trim();(je==="all"||je==="global"||je==="session"||je==="run")&&f(je)},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(L2,{checked:p,onChange:y}),c==="session"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"session_id"}),s.jsx("input",{className:"mono",value:l,onChange:ce=>u(String(ce.target.value||"")),placeholder:"(required)"})]}):null,c==="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:ce=>o(String(ce.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:w,onChange:ce=>x(Math.max(250,Number(ce.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:S,onChange:ce=>j(Math.max(250,Number(ce.target.value||0)||5e3))})]})})]})]}),P?s.jsx("div",{className:"mindmap_error mono",children:P}):null,s.jsxs("div",{className:"mindmap_explorer",children:[s.jsx(RL,{title:"mindmap",resetKey:Qt,queryMode:"replace",items:Un,warnings:T,onQuery:Ss,onItemsReplace:Mr,onOpenSpan:({run_id:ce,span_id:je,assertion:Je})=>{On({run_id:ce,span_id:je,assertion:Je})},onOpenTranscript:({run_id:ce,span_id:je,assertion:Je})=>{const Ve=String(ce||"").trim(),rt=typeof je=="string"?String(je).trim():"";Ve&&(rt?On({run_id:Ve,span_id:rt,assertion:Je}):js({run_id:Ve,assertion:Je}))}},Qt),J.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:J.slice().sort((ce,je)=>je.expires_at_ms-ce.expires_at_ms).slice(0,12).map(ce=>s.jsx("div",{className:"mindmap_recent_item mono",children:OL(ce.assertion)},ce.id))})]}):null,It?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:wc(Math.min(typeof $t=="number"?$t:It.max_ms,It.real_max_ms))}),s.jsx("input",{className:"mindmap_slider",type:"range",min:It.min_ms,max:It.max_ms,step:Ut,value:typeof $t=="number"?$t:It.max_ms,onChange:ce=>{const je=Number(ce.target.value||0);fn(je),ns(je>=It.max_ms)}}),s.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[Un.length.toLocaleString(),"/",C.length.toLocaleString()]})]})}):null]}),s.jsxs(pl,{open:ae,title:E||"source",onClose:()=>{ue(!1)},children:[B?s.jsx("div",{className:"mono muted",children:"Loading…"}):null,$?s.jsx("div",{className:"mindmap_error mono",children:$}):null,!B&&!$?s.jsxs("div",{className:"source_span",children:[(()=>{const ce=ye;if(!ce)return null;const je=String(ce.subject||"").trim(),Je=String(ce.predicate||"").trim(),Ve=String(ce.object||"").trim(),rt=wc(fl(ce.observed_at)),ct=ce.attributes&&typeof ce.attributes=="object"&&!Array.isArray(ce.attributes)?ce.attributes:null,Et=ct&&typeof ct.evidence_quote=="string"?String(ct.evidence_quote):"",St=ct&&typeof ct.original_context=="string"?String(ct.original_context):"";return s.jsxs("div",{className:"source_header",children:[s.jsxs("div",{className:"mono source_triple",title:`${je} --${Je}--> ${Ve}`,children:[je," ",s.jsxs("span",{className:"muted",children:["—",Je,"→"]})," ",Ve," ",rt?s.jsxs("span",{className:"muted",children:["[",rt,"]"]}):null]}),Et?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:Et}),St?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:St})]}):null]}):null]})})(),s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["run_id=",O," · ",Q==="artifact"?`span_id=${K}`:"source=input_data"]}),s.jsxs("div",{className:"source_actions",children:[Se!==null?s.jsx("button",{className:"btn",onClick:()=>Re(Se),children:"Jump to evidence"}):null,Se===null&&tt?s.jsx("button",{className:"btn",onClick:()=>ht(),children:"Jump to evidence"}):null]}),(()=>{const ce=X,je=ce&&typeof ce=="object"&&!Array.isArray(ce)?ce:null,Je=Fe,Ve=gt,rt=je&&typeof je.created_at=="string"?String(je.created_at):"",ct=rt?fl(rt):null,Et=ct!==null?wc(ct):rt,St=je&&je.span&&typeof je.span=="object"&&!Array.isArray(je.span)?je.span:null,Kt=St&&typeof St.from_timestamp=="string"?String(St.from_timestamp):"",xt=St&&typeof St.to_timestamp=="string"?String(St.to_timestamp):"",Yt=Kt?fl(Kt):null,Wt=xt?fl(xt):null,Ot=Yt!==null&&Wt!==null?`${wc(Yt)} → ${wc(Wt)}`:"";if(Ve){const At=IL(Ve);if(At){const Tt=Be,De=Tt?At.messages.findIndex(ft=>xm(ft.content,Tt)):-1,sn=Tt?kv(Tt):[],dt=At.created_at||rt,en=dt?LL(dt):rt?Et:"";return s.jsx("div",{className:"source_chat",children:At.messages.map((ft,Wn)=>{const cn=ft.role,er=!!(Tt&&xm(ft.content,Tt)),ss=cn==="user"?"USER":cn==="assistant"?"ASSISTANT":"SYSTEM";return s.jsxs("div",{id:Wn===De?"source_note_msg_hit_0":void 0,className:`source_msg source_${cn} ${er?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Wn+1," · ",ss,er?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),en?s.jsx("span",{title:dt||"",children:en}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Mi,{text:ft.content,highlights:er&&sn.length?sn:void 0,highlightClassName:"source_note_hit",highlightId:Wn===De?"source_note_hit_0":void 0})})]},`note_msg:${Wn}`)})})}return s.jsxs("div",{className:"source_note",children:[rt?s.jsx("div",{className:"mono muted",style:{marginBottom:10},children:s.jsxs("span",{title:rt,children:["created_at=",Et]})}):null,s.jsx(Mi,{text:Ve,highlights:Be?kv(Be):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(Je){const At=new Map;for(const De of Je){const sn=typeof(De==null?void 0:De.role)=="string"?String(De.role):"unknown";At.set(sn,(At.get(sn)||0)+1)}const Tt=Array.from(At.entries()).sort((De,sn)=>sn[1]-De[1]||De[0].localeCompare(sn[0])).map(([De,sn])=>`${De}×${sn}`).join(" · ");return s.jsxs("div",{className:"source_chat",children:[rt?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:[s.jsxs("span",{title:rt,children:["created_at=",Et]})," · messages=",Je.length]}):null,Ot?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["span=",Ot]}):null,Tt?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["participants: ",Tt]}):null,Je.slice(0,200).map((De,sn)=>{var Xr,_r;const dt=typeof(De==null?void 0:De.role)=="string"?String(De.role):"unknown",en=(De==null?void 0:De.content)==null?"":String(De.content),ft=typeof(De==null?void 0:De.timestamp)=="string"?String(De.timestamp):"",Wn=ft?fl(ft):null,cn=Wn!==null?wc(Wn):ft,er=typeof(De==null?void 0:De.message_id)=="string"?String(De.message_id):typeof((Xr=De==null?void 0:De.metadata)==null?void 0:Xr.message_id)=="string"?String(De.metadata.message_id):typeof((_r=De==null?void 0:De.metadata)==null?void 0:_r.id)=="string"?String(De.metadata.id):"",ss=Ye.has(sn);return s.jsxs("div",{id:`source_msg_${sn}`,className:`source_msg source_${dt} ${ss?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",sn+1," · ",dt,ss?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null,er?s.jsx("span",{className:"source_msg_id",children:er}):null]}),ft?s.jsx("span",{title:ft,children:cn}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Mi,{text:en})})]},sn)})]})}return s.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof ce=="string"?ce:_e)||"(empty)"})})()]}):null]})]})}const $p=4;function DL(e){var l;const t=(l=e==null?void 0:e.discoveries)==null?void 0:l.dreams_signals_brief;if(!t||typeof t!="object"||Array.isArray(t))return null;const n=typeof t.count=="number"&&Number.isInteger(t.count)&&t.count>0?t.count:0;if(!n)return null;const r=u=>Array.isArray(u)?u.filter(c=>typeof c=="string").map(c=>c.trim()).filter(Boolean):[],o=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:o}}function Ev(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 FL(e){var c,f;const t=_=>{var y;const p=(y=e==null?void 0:e[_])==null?void 0:y.open;return Array.isArray(p)?p.map(Ev).filter(w=>w!==null):[]},n=t("questions"),r=t("problems"),o=(c=e==null?void 0:e.lessons)==null?void 0:c.lessons,l=Array.isArray(o)?o.map(Ev).filter(_=>_!==null):[],u=typeof((f=e==null?void 0:e.lessons)==null?void 0:f.total)=="number"?e.lessons.total:l.length;return{questions:n.slice(0,$p),questions_total:n.length,problems:r.slice(0,$p),problems_total:r.length,lessons:l.slice(0,$p),lessons_total:u}}function Ap(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`}const $v={review:"Review",working:"Working",pending:"Pending",done:"Done"},zL={review:"nothing needs you",working:"idle",pending:"nothing scheduled",done:"no recent runs"},BL={pending:"scheduled or queued — will run without you",working:"running or parked listening — no action needed",review:"needs a human decision — act here",done:"terminal — read the outcome"};function UL(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Ri(t))return"done";const n=sd(e);return n==="tool_approval"||n==="user_response"?"review":n==="scheduled"||t==="pending"||t==="queued"||t==="created"?"pending":"working"}function WL(e){const t=sd(e);return t==="tool_approval"||t==="user_response"}function Av(e,t=Date.now()){const n=UL(e),r=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,o=nd(r),l=Nn((r==null?void 0:r.since)||(e==null?void 0:e.updated_at)||(e==null?void 0:e.created_at)||"");return{run_id:String((e==null?void 0:e.run_id)||""),column:n,workflow:String((e==null?void 0:e.workflow_id)||"").trim()||"(workflow?)",status:String((e==null?void 0:e.status)||"").trim().toLowerCase(),wait_kind:sd(e),reason:_b(e),tool_names:o.map(u=>String((u==null?void 0:u.name)||"tool")).filter(Boolean),wait_key:String((r==null?void 0:r.wait_key)||"").trim(),allow_free_text:(r==null?void 0:r.allow_free_text)!==!1,prompt:String((r==null?void 0:r.prompt)||"").trim(),since_ms:l,duration_ms:Wg(e,t),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,is_scheduled:!!(e!=null&&e.is_scheduled),schedule_interval:String((e==null?void 0:e.schedule_interval)||"").trim(),failed:String((e==null?void 0:e.status)||"").trim().toLowerCase()==="failed",error:String((e==null?void 0:e.error)||"").trim(),paused:!!(e!=null&&e.paused),is_subrun:!!String((e==null?void 0:e.parent_run_id)||"").trim(),tag:Mf(e),tag_label:Gx(e),automation_id:Mf(e)==="occurrence"?String((e==null?void 0:e.automation_id)||"").trim():""}}function qL(e,t,n=Date.now()){const r={pending:[],working:[],review:[],done:[]},o=t&&t.length?t:e,l=new Set;for(const u of o||[]){const c=String((u==null?void 0:u.run_id)||"").trim();!u||!c||l.has(c)||sw(u)||WL(u)&&(l.add(c),r.review.push(Av(u,n)))}for(const u of e||[]){const c=String((u==null?void 0:u.run_id)||"").trim();if(!u||!c||l.has(c)||sw(u))continue;const f=Av(u,n);r[f.column].push(f)}return r.review.sort((u,c)=>(u.since_ms??0)-(c.since_ms??0)),r.working.sort((u,c)=>(c.since_ms??0)-(u.since_ms??0)),r.pending.sort((u,c)=>(c.since_ms??0)-(u.since_ms??0)),r.done.sort((u,c)=>Number(c.failed)-Number(u.failed)||(c.since_ms??0)-(u.since_ms??0)),r}const $g={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},Tp={"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"},Tv="48h";function HL(e,t,n=Date.now()){const r=$g[t]??null;if(r===null)return{visible:e,hidden_count:0};const o=n-r,l=[];let u=0;for(const c of e)c.since_ms===null||c.since_ms>=o?l.push(c):u+=1;return{visible:l,hidden_count:u}}function VL(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 GL=6e4;function kf(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 KL(e){return!Number.isFinite(e)||e<0?"":e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.floor(e/6e4)}m${Math.round(e%6e4/1e3)}s`:`${(e/36e5).toFixed(1)}h`}function YL(e){const t=String(e||"");return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function Mp(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function JL(e){const t=String(e||"");let n=t.includes(":")?t.slice(t.lastIndexOf(":")+1):t;if(t.includes(":")&&/^[0-9a-f]{6,}$/i.test(n.trim())){const r=t.slice(0,t.lastIndexOf(":"));/[a-z]/i.test(r)&&!/^[0-9a-f]+$/i.test(r.replace(/[@.\-_]/g,""))&&(n=r)}return n.length>34?`${n.slice(0,32)}…`:n}function Tm(e){return e.toLowerCase().replace(/[_-]+/g," ")}function XL(e){var _,p;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(y=>y&&typeof y=="string");if(!r.length)return null;const o=[];for(const y of r){o.push({needle:Tm(y),phase:y});const w=(_=n[y])==null?void 0:_.spoken_synonyms;if(Array.isArray(w))for(const x of w){const S=Tm(String(x||"").trim());S&&o.push({needle:S,phase:y})}}const u=(typeof t.initial_phase=="string"&&r.includes(t.initial_phase)?t.initial_phase:null)??(r.includes("sleep")?"sleep":null);if(!u)return null;const c=[],f=(p=t==null?void 0:t.state_mode_axis)==null?void 0:p.words;if(f&&typeof f=="object"&&!Array.isArray(f))for(const[y,w]of Object.entries(f)){const x=String((w==null?void 0:w.phase)||"").trim(),S=Tm(String(y||"").trim());S&&r.includes(x)&&c.push({needle:S,phase:x})}return{phases:r,synonyms:o,modes:c,initial:u,version:typeof t.version=="number"?t.version:null,sha256:String((e==null?void 0:e.sha256)||"").trim()}}const ZL=["asleep","sleep","dream"],QL=["rest"],e3=["awake","idle"];function t3(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const r=Tm(n),o=t.synonyms.filter(u=>r.includes(u.needle)).sort((u,c)=>c.needle.length-u.needle.length);if(o.length)return o[0].phase;const l=t.modes.filter(u=>r.includes(u.needle)).sort((u,c)=>c.needle.length-u.needle.length);return l.length?l[0].phase:n.includes("task")&&!n.includes("no_task")&&t.phases.includes("work")?"work":ZL.some(u=>n.includes(u))?t.initial:QL.some(u=>n.includes(u))&&t.phases.includes("personal")?"personal":e3.some(u=>n.includes(u))?t.initial:n.includes("stop")?"stopped":n.includes("pause")?"paused":n}return n.includes("visit")?"visit":n.includes("sleep")||n.includes("dream")?"sleep":n.includes("personal")||n.includes("own_time")||n.includes("own time")?"personal":n.includes("task")&&!n.includes("no_task")||n.includes("work")?"work":n.includes("awake")||n.includes("idle")?"sleep":n.includes("stop")?"stopped":n.includes("pause")?"paused":n.includes("rest")?"resting":n}const n3=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),s3=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function r3(e){if(!e)return n3;const t=e.phases.filter(n=>s3.has(n));return new Set([...t,"paused","stopped","unknown"])}function i3(e){const[t,n]=Rf(`board_${e.col}`),r=`mc_column_body_${e.col}`;return s.jsxs("div",{className:`mc_column mc_column_${e.col}${t?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"mc_column_head",children:[s.jsx(Lf,{open:t,on_toggle:n,controls:r,title:e.title,className:"mc_column_title"}),e.head]}),s.jsx("div",{className:"mc_column_body",id:r,hidden:!t,children:e.children})]})}function o3(e){var G,Y,J,re,ae,ue;const t=Date.now(),n=m.useMemo(()=>qL(e.runs,e.all_runs,Date.now()),[e.runs,e.all_runs]),[r,o]=m.useState(""),[l,u]=m.useState(""),[c,f]=m.useState(!1),[_,p]=m.useState(()=>{try{const B=localStorage.getItem("abstractobserver_done_window_v1");return B&&B in $g?B:Tv}catch{return Tv}}),y=m.useMemo(()=>HL(n.done,_,t),[n.done,_]),w=kf(e.runs_refreshed_at,t),x=n.review.length,S=y.visible.filter(B=>B.failed).length,[j,C]=m.useState(""),[N,T]=m.useState(null),L=B=>`${B.run_id}:${B.wait_key}:${B.since_ms??""}`;m.useEffect(()=>{r&&(n.review.some(B=>L(B)===r)||o(""))},[n,r]);async function P(B,A){o(L(B)),u("");try{await e.on_resume_wait(B.run_id,B.wait_key,A)}catch($){u(`${B.run_id}: ${String(($==null?void 0:$.message)||$||"resume failed")}`),o("")}}function W(B){const A=r===L(B),$=B.column==="review",z=$&&!B.wait_key;return s.jsxs("div",{className:`mc_card ${$?"mc_card_review":""} ${B.failed?"mc_card_failed":""}`,onClick:()=>e.on_open_run(B.run_id),role:"button",tabIndex:0,onKeyDown:E=>{E.key==="Enter"&&E.target===E.currentTarget&&e.on_open_run(B.run_id)},children:[s.jsxs("div",{className:"mc_card_head",children:[s.jsx("span",{className:"mc_card_title",title:B.workflow,children:JL(B.workflow)}),(()=>{const E=B.failed?"failed":Um({status:B.status,paused:B.paused});return s.jsx("span",{className:`mc_status ${vl(E)}`,children:E==="unknown"?"?":E})})()]}),s.jsxs("div",{className:"mc_card_meta",children:[s.jsx("span",{className:"mono",title:B.run_id,children:YL(B.run_id)}),B.is_subrun?s.jsx("span",{title:"This wait lives in a child run of an agent workflow",children:"subrun"}):null,B.tag?s.jsx("span",{className:"mc_pill","data-tag":B.tag,children:B.tag_label}):null,B.automation_id?s.jsx("button",{type:"button",className:"btn btn_sm",title:"Open this occurrence's automation",onClick:E=>{E.stopPropagation(),e.on_open_automation(B.automation_id)},onKeyDown:E=>E.stopPropagation(),children:"Automation"}):null,B.duration_ms>=0?s.jsx("span",{children:KL(B.duration_ms)}):null,B.tokens_total!==null?s.jsxs("span",{children:[B.tokens_total.toLocaleString()," tk"]}):null,B.tool_calls!==null&&B.tool_calls>0?s.jsxs("span",{children:[B.tool_calls," tools"]}):null]}),B.is_scheduled&&B.schedule_interval?s.jsxs("div",{className:"mc_card_line",children:["every ",B.schedule_interval]}):null,B.failed&&B.error?s.jsx("div",{className:"mc_card_error",title:B.error,children:B.error.length>120?`${B.error.slice(0,118)}…`:B.error}):null,$?s.jsxs("div",{className:"mc_card_review_body",onClick:E=>E.stopPropagation(),onKeyDown:E=>E.stopPropagation(),children:[s.jsx("div",{className:"mc_card_reason",children:B.reason||"Needs a decision"}),B.prompt?s.jsx("div",{className:"mc_card_prompt",title:B.prompt,children:B.prompt.length>240?`${B.prompt.slice(0,238)}…`:B.prompt}):null,B.tool_names.length?s.jsxs("div",{className:"mc_card_tools",title:"Tool calls awaiting your approval",children:[B.tool_names.slice(0,4).map((E,te)=>s.jsx("span",{className:"mc_tool_chip mono",children:E},`${E}_${te}`)),B.tool_names.length>4?s.jsxs("span",{className:"mc_tool_chip",children:["+",B.tool_names.length-4," more"]}):null]}):null,B.since_ms!==null?s.jsxs("div",{className:"mc_card_waiting",children:["waiting ",kf(B.since_ms,t)]}):null,z?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,z?s.jsx("div",{className:"mc_card_actions",children:s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(B.run_id),children:"Open the run →"})}):B.wait_kind==="tool_approval"?s.jsxs("div",{className:"mc_card_actions",children:[s.jsx("button",{className:"btn success",disabled:A,onClick:()=>void P(B,{approved:!0}),children:A?"Resuming…":"Approve"}),s.jsx("button",{className:"btn danger",disabled:A,onClick:()=>void P(B,{approved:!1}),children:"Reject"})]}):s.jsx("div",{className:"mc_card_actions",children:s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(B.run_id),children:"Review & answer →"})})]}):null]},B.run_id)}return s.jsxs("div",{className:"page page_scroll mc_page",children:[s.jsxs("div",{className:"mc_health",children:[s.jsx("span",{className:`mc_led ${e.gateway_connected?"ok":"bad"}`,title:e.gateway_connected?"Gateway connected":"Gateway unreachable"}),e.gateway_connected?null:s.jsx("span",{className:"mc_health_text",children:"gateway unreachable"}),e.runs_refreshed_at===null?s.jsx("span",{className:"mc_health_text muted mc_loading",children:"loading runs…"}):s.jsxs("div",{className:"mc_stats",children:[s.jsxs("div",{className:`mc_stat ${x?"is_hot":""}`,title:"runs blocked on a human decision (Review column)",children:[s.jsx("span",{className:"mc_stat_value",children:x}),s.jsx("span",{className:"mc_stat_label",children:"need you"})]}),s.jsxs("div",{className:`mc_stat ${S?"is_bad":""}`,title:"failed runs in the Done column",children:[s.jsx("span",{className:"mc_stat_value",children:S}),s.jsx("span",{className:"mc_stat_label",children:"failed"})]}),s.jsxs("div",{className:"mc_stat",title:"runs executing or parked listening",children:[s.jsx("span",{className:"mc_stat_value",children:n.working.length}),s.jsx("span",{className:"mc_stat_label",children:"working"})]})]}),s.jsx("span",{className:"mc_spacer"}),s.jsxs("div",{className:"mc_health_side",children:[w?s.jsxs("span",{className:"mc_health_text muted",title:"age of the last runs poll — the board is only as live as this",children:["data ",w," old"]}):null,s.jsx("button",{className:"btn",onClick:e.on_refresh,disabled:e.refreshing,children:e.refreshing?"Refreshing…":"Refresh"})]})]}),l?s.jsx("div",{className:"mc_error",children:l}):null,e.entities.length||e.entities_error?s.jsxs("div",{className:"mc_entities",children:[s.jsxs("div",{className:"mc_entities_head",children:[s.jsxs("span",{children:["Entities",e.entities_total>e.entities.length?` (${e.entities.length} of ${e.entities_total} — open the entity app for all)`:""]}),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,s.jsx("div",{className:"mc_entities_row",children:e.entities.map(B=>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(B.name)}&live=1`,target:"_blank",rel:"noreferrer",title:[B.error,B.age_days!==null?`${B.age_days.toFixed(0)} days old`:"",B.last_moment].filter(Boolean).join(" — ")||B.name,children:[s.jsx("span",{className:"mc_entity_name",children:B.name}),(()=>{var F;const A=String(B.live_phase||B.state||"").trim(),$=t3(A,e.phase_graph),z=r3(e.phase_graph).has($)?$:"other",E=((F=e.phase_graph)==null?void 0:F.initial)??"sleep",te=/awake|idle/i.test(A)&&$===E,O=A&&A.toLowerCase()!==$?` — wire word: ${A}${te?" (settling)":""}`:"";return s.jsx("span",{className:`mc_entity_phase mc_phase_${z}`,title:(B.live_phase?"phase (cognition wire)":"phase from card state — cognition wire unavailable")+O,children:$})})(),B.last_moment?s.jsx("span",{className:"mc_entity_moment",title:B.last_moment,children:B.last_moment.replace(/_/g," ")}):null,(()=>{if(B.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 A=VL(B.last_moment_at,t);return B.working===!1?s.jsxs("span",{className:"mc_entity_live muted",title:"idle (cognition wire)",children:["idle",A!==null?` · ${kf(t-A,t)} ago`:""]}):A===null?null:A<=GL?s.jsx("span",{className:"mc_entity_live",title:`last moment ${kf(t-A,t)} ago`,children:"● active"}):s.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[kf(t-A,t)," ago"]})})(),B.tokens_total!==null?s.jsxs("span",{className:"muted mc_entity_spend",title:`lifetime billed tokens (home run ledger)${B.live_visit_tokens!==null?`; open visit: ${Ap(B.live_visit_tokens)} tk`:""}${B.spend_warning?`; ${B.spend_warning}`:""}`,children:[Ap(B.tokens_total)," tk",B.live_visit_tokens!==null?` (+${Ap(B.live_visit_tokens)})`:"",B.spend_warning?"*":""]}):null]}),B.open_questions_total||B.open_problems_total||B.lessons_total||B.dreams_brief?s.jsx("button",{type:"button",className:"mc_entity_hints_btn","aria-expanded":j===B.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>C(j===B.name?"":B.name),children:[B.open_questions_total?`${B.open_questions_total} question${B.open_questions_total>1?"s":""}`:"",B.open_problems_total?`${B.open_problems_total} problem${B.open_problems_total>1?"s":""}`:"",B.lessons_total?`${B.lessons_total} lesson${B.lessons_total>1?"s":""}`:"",B.dreams_brief?`night: ${B.dreams_brief.count} signal${B.dreams_brief.count>1?"s":""}`:""].filter(Boolean).join(" · ")}):null]},B.name))}),(()=>{if(!j)return null;const B=e.entities.find(z=>z.name===j);if(!B||!B.open_questions.length&&!B.open_problems.length&&!B.lessons.length&&!B.dreams_brief)return null;const A=e.on_read_diary?async z=>{const E=await e.on_read_diary(B.name,z);T({entity:B.name,entry:(E==null?void 0:E.entry)??E,seq:typeof(E==null?void 0:E.read_recorded_at_seq)=="number"?E.read_recorded_at_seq:null})}:void 0,$=B.open_questions_total-B.open_questions.length+(B.open_problems_total-B.open_problems.length)+(B.lessons_total-B.lessons.length);return s.jsxs("div",{className:"mc_entity_hints_panel",children:[B.open_questions.map((z,E)=>s.jsx(q_,{kind:"question",label:z.title||Mp(z.statement),entryId:z.entry_id,onOpen:A,title:z.statement||z.title},`q_${z.record_id||E}`)),B.open_problems.map((z,E)=>s.jsx(q_,{kind:"problem",label:z.title||Mp(z.statement),entryId:z.entry_id,onOpen:A,title:z.statement||z.title},`p_${z.record_id||E}`)),B.lessons.map((z,E)=>s.jsx(q_,{kind:"lesson",label:z.title||Mp(z.statement),entryId:z.entry_id,onOpen:A,title:z.statement||z.title},`l_${z.record_id||E}`)),B.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: ",B.dreams_brief.count,B.dreams_brief.dreams?` across ${B.dreams_brief.dreams} dream${B.dreams_brief.dreams>1?"s":""}`:"",B.dreams_brief.kinds.length?` — ${B.dreams_brief.kinds.slice(0,6).join(", ")}${B.dreams_brief.kinds.length>6?` +${B.dreams_brief.kinds.length-6} more`:""}`:"",B.dreams_brief.felt_tones.length?` · felt: ${B.dreams_brief.felt_tones.slice(0,6).join(", ")}`:""]}):null,$>0?s.jsxs("span",{className:"muted mc_entity_hints_more",children:["+",$," more — open the entity app"]}):null]})})()]}):null,N?s.jsx(pl,{open:!0,title:`${N.entity} — diary entry`,onClose:()=>T(null),children:s.jsxs("div",{className:"mc_diary_entry",children:[s.jsx("div",{className:"mc_diary_meta muted",children:[(G=N.entry)!=null&&G.kind?`kind: ${N.entry.kind}`:"",(Y=N.entry)!=null&&Y.visibility?`visibility: ${N.entry.visibility}`:"",(J=N.entry)!=null&&J.written_at?`written: ${N.entry.written_at}`:"",(re=N.entry)!=null&&re.entry_id?`id: ${N.entry.entry_id}`:""].filter(Boolean).join(" · ")}),s.jsxs("div",{className:"mc_diary_recorded muted",children:["this read was recorded in ",N.entity,"’s stream",N.seq!==null?` (seq ${N.seq})`:""]}),(ae=N.entry)!=null&&ae.gist?s.jsx("div",{className:"mc_diary_gist",children:String(N.entry.gist)}):null,s.jsx("pre",{className:"mc_diary_text",children:String(((ue=N.entry)==null?void 0:ue.text)||"(entry carries no text)")})]})}):null,s.jsx("div",{className:"mc_board",children:Object.keys($v).map(B=>{const A=B==="done"?y.visible:n[B],$=B==="done"&&!c?A.slice(0,8):A;return s.jsxs(i3,{col:B,title:$v[B],head:s.jsxs(s.Fragment,{children:[B==="done"?s.jsx("select",{className:"mc_window_select",value:_,title:"Show terminal runs from this time window",onClick:z=>z.stopPropagation(),onChange:z=>{const E=z.target.value;p(E),f(!1);try{localStorage.setItem("abstractobserver_done_window_v1",E)}catch{}},children:Object.keys($g).map(z=>s.jsx("option",{value:z,children:Tp[z]},z))}):null,s.jsx("span",{className:"mc_column_count",title:B==="done"&&y.hidden_count?`${y.hidden_count} older run(s) outside this window`:void 0,children:A.length})]}),children:[s.jsx("div",{className:"mc_column_hint muted",children:BL[B]}),s.jsxs("div",{className:"mc_column_cards",children:[$.map(z=>W(z)),A.length?null:s.jsx("div",{className:"mc_empty muted",children:e.runs_refreshed_at===null?"loading…":B==="done"&&y.hidden_count?`none in the ${Tp[_]} — ${y.hidden_count} older`:zL[B]}),B==="done"&&A.length>8&&!c?s.jsxs("button",{className:"btn mc_more",onClick:()=>f(!0),children:["show all ",A.length]}):null,B==="done"&&y.hidden_count&&A.length?s.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",y.hidden_count," older outside ",Tp[_]]}):null]})]},B)})})]})}function Mv(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 Rv(e){const t=e.disabled===!0,n=m.useMemo(()=>Mv(e.options||[]),[e.options]),r=m.useMemo(()=>Mv(e.value||[]),[e.value]),[o,l]=m.useState(!1),[u,c]=m.useState(""),f=m.useMemo(()=>{const y=u.trim().toLowerCase();return y?n.filter(w=>w.toLowerCase().includes(y)):n},[n,u]),_=m.useMemo(()=>new Set(r),[r]),p=typeof e.max_list_height_px=="number"?e.max_list_height_px:220;return s.jsxs("div",{className:"multi_select",children:[s.jsxs("div",{className:"multi_select_row",children:[s.jsxs("button",{className:"btn",type:"button",onClick:()=>l(y=>!y),disabled:t||!n.length,"aria-expanded":o,children:[o?"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:"multi_select_chips",children:r.map(y=>s.jsxs("span",{className:"multi_select_chip",title:y,onClick:()=>{if(t)return;const w=new Set(_);w.delete(y),e.onChange(Array.from(w.values()))},children:[y,t?null:s.jsx("span",{className:"multi_select_chip_x",children:"×"})]},y))}):null,o?s.jsxs("div",{className:"multi_select_panel",children:[s.jsx("input",{className:"mono",value:u,onChange:y=>c(String(y.target.value||"")),placeholder:"filter…",disabled:t}),s.jsxs("div",{className:"multi_select_list",style:{maxHeight:`${p}px`},children:[f.map(y=>{const w=_.has(y);return s.jsxs("label",{className:`multi_select_item mono ${w?"checked":""}`,children:[s.jsx("input",{type:"checkbox",checked:w,disabled:t,onChange:x=>{const S=new Set(_);x.target.checked?S.add(y):S.delete(y),e.onChange(Array.from(S.values()))}}),s.jsx("span",{children:y})]},y)}),f.length?null:s.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function a3(){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 l3(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function c3(){const e=window.MediaRecorder,t=r=>{var o;try{return!!((o=e==null?void 0:e.isTypeSupported)!=null&&o.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 u3(e,t){var o;const n=t.slice(0),r=(o=e.decodeAudioData)==null?void 0:o.bind(e);if(typeof r!="function")throw new Error("decodeAudioData not available");try{const l=r(n);if(l&&typeof l.then=="function")return await l}catch{}return await new Promise((l,u)=>{try{r(n,l,u)}catch(c){u(c)}})}function d3(e){const t=z=>{var E;return(E=e.on_error)==null?void 0:E.call(e,z)},n=m.useMemo(()=>l3(),[]),r=m.useMemo(()=>a3(),[]),[o,l]=m.useState({key:"",status:"idle"}),u=m.useRef(""),c=m.useRef(""),f=m.useRef(null),_=m.useRef(null),p=m.useRef(null),y=m.useRef(null),w=m.useRef(0),x=m.useRef(0),S=()=>{try{const z=globalThis,E=(z==null?void 0:z.AudioContext)||(z==null?void 0:z.webkitAudioContext);if(!E)return null;if(!f.current){const F=new E,K=F.createGain();K.gain.value=1,K.connect(F.destination),f.current=F,_.current=K}const te=f.current,O=_.current;if(!te||!O)return null;try{te.state==="suspended"&&te.resume()}catch{}return{ctx:te,gain:O}}catch{return null}},j=()=>{const z=p.current;if(p.current=null,!!z){try{z.onended=null}catch{}try{z.stop()}catch{}try{z.disconnect()}catch{}}},C=()=>{j(),c.current="",u.current="",y.current=null,w.current=0,x.current=0,l({key:"",status:"idle"})};m.useEffect(()=>()=>{var z,E;C();try{(z=_.current)==null||z.disconnect()}catch{}try{(E=f.current)==null||E.close()}catch{}f.current=null,_.current=null,y.current=null},[]);const N=async(z,E,te)=>{const O=S();if(!O)throw new Error("TTS playback is not supported in this browser");const{ctx:F,gain:K}=O;try{F.state==="suspended"&&await F.resume()}catch{}j();const R=F.createBufferSource();R.buffer=E,R.connect(K);const Q=Number.isFinite(Number(E.duration))?Number(E.duration):0,Z=Math.max(0,Math.min(Number(te||0),Q>0?Math.max(0,Q-.01):0));x.current=F.currentTime-Z,w.current=Z,p.current=R,u.current=z,R.onended=()=>{p.current===R&&(p.current=null,w.current=0,x.current=0,u.current="",l({key:"",status:"idle"}))},R.start(0,Z),l({key:z,status:"playing"})},T=async(z,E)=>{const te=String(z||"").trim(),O=String(E||"").trim();if(!te||!O)return;const F=e.gateway,K=String(e.run_id||"").trim();if(!F){t==null||t("Connect to the gateway first.");return}if(!K){t==null||t("Voice store not available (missing run_id).");return}const R=S();if(!R){t==null||t("TTS playback is not supported in this browser.");return}const Q=o.key===te;if(Q&&o.status==="playing"){const Z=Math.max(0,R.ctx.currentTime-Number(x.current||0));w.current=Z,j(),l({key:te,status:"paused"});return}if(Q&&o.status==="paused"){const Z=y.current;if(Z){t==null||t("");try{await N(te,Z,w.current)}catch(X){t==null||t(String((X==null?void 0:X.message)||X||"TTS play failed")),l({key:"",status:"idle"})}return}}if(!(Q&&o.status==="loading")){j(),y.current=null,w.current=0,x.current=0,u.current=te,c.current=te,l({key:te,status:"loading"}),t==null||t("");try{const Z=await F.voice_tts(K,{text:O,request_id:xs()}),X=Z==null?void 0:Z.audio_artifact,le=X&&typeof X=="object"&&!Array.isArray(X)?String(X.$artifact||"").trim():"";if(!le)throw new Error("TTS failed: missing audio artifact");const he=await(await F.download_run_artifact_content(K,le)).arrayBuffer();if(c.current!==te)return;const ye=await u3(R.ctx,he);if(c.current!==te)return;y.current=ye,w.current=0,await N(te,ye,0)}catch(Z){c.current===te&&(c.current="",u.current="",l({key:"",status:"idle"})),t==null||t(String((Z==null?void 0:Z.message)||Z||"TTS failed"))}}},[L,P]=m.useState(!1),[W,G]=m.useState(!1),Y=m.useRef(null),J=m.useRef(null),re=m.useRef([]),ae=m.useRef("");function ue(){var z,E;try{(E=(z=Y.current)==null?void 0:z.getTracks)==null||E.call(z).forEach(te=>{try{te.stop()}catch{}})}catch{}Y.current=null}m.useEffect(()=>()=>{var z,E;try{(E=(z=J.current)==null?void 0:z.stop)==null||E.call(z)}catch{}J.current=null,ue()},[]);async function B(z,E){var K;if(t==null||t(""),!z||!z.size||W)return;const te=e.gateway,O=String(e.session_id||"").trim(),F=String(e.run_id||"").trim();if(!te){t==null||t("Connect to the gateway first.");return}if(!O){t==null||t("Voice input unavailable (missing session_id).");return}if(!F){t==null||t("Voice input unavailable (missing run_id).");return}G(!0);try{const R=String(E||z.type||"").toLowerCase(),Q=R.includes("mp4")?"m4a":R.includes("ogg")?"ogg":R.includes("wav")?"wav":"webm",Z=new File([z],`recording.${Q}`,{type:R||"audio/webm"}),X=await te.attachments_upload(O,Z,{filename:Z.name,content_type:Z.type}),le=await te.audio_transcribe(F,{audio_artifact:X,request_id:xs()}),_e=String((le==null?void 0:le.text)||"").trim();_e&&((K=e.on_transcript)==null||K.call(e,_e))}catch(R){t==null||t(String((R==null?void 0:R.message)||R||"Transcription failed"))}finally{G(!1)}}async function A(){if(t==null||t(""),!r){t==null||t(ag()?"Voice recording is not supported in this browser (MediaRecorder unavailable).":og);return}if(!W&&!(L||J.current)){re.current=[];try{const z=await navigator.mediaDevices.getUserMedia({audio:!0});Y.current=z;const E=c3();ae.current=E;const te=E?new MediaRecorder(z,{mimeType:E}):new MediaRecorder(z);J.current=te,te.ondataavailable=O=>{try{O!=null&&O.data&&re.current.push(O.data)}catch{}},te.onerror=()=>{t==null||t("Recording failed.")},te.onstop=()=>{P(!1),ue(),J.current=null;try{const O=new Blob(re.current,{type:ae.current||""});B(O,ae.current)}catch(O){t==null||t(String((O==null?void 0:O.message)||O||"Failed to build recording"))}},te.start(),P(!0)}catch(z){ue(),J.current=null,P(!1);const E=String((z==null?void 0:z.message)||z||"Failed to access microphone");t==null||t(E.toLowerCase().includes("permission")?`Microphone permission denied: ${E}`:E)}}}function $(){const z=J.current;if(!(!L||!z)){J.current=null,P(!1);try{z.stop()}catch(E){t==null||t(String((E==null?void 0:E.message)||E||"Failed to stop recording"))}}}return m.useEffect(()=>{if(!L)return;const z=()=>$();return window.addEventListener("pointerup",z),window.addEventListener("pointercancel",z),()=>{window.removeEventListener("pointerup",z),window.removeEventListener("pointercancel",z)}},[L]),{tts_supported:n,tts_playback:o,toggle_tts:T,stop_tts:C,voice_ptt_supported:r,voice_ptt_recording:L,voice_ptt_busy:W,start_voice_ptt_recording:A,stop_voice_ptt_recording:$}}const bm=500,t_="http://127.0.0.1:8080";function Lv(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 Nf(e){const t=String(e||"").trim();return t.startsWith("abstractcode.")?`abstract.${t.slice(13)}`:t}function Rp(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 Lp(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function f3(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 h3(e){if(!e||typeof e!="object")return[];const t=Array.isArray(e.nodes)?e.nodes:[];if(!t.length)return[];let n=null;for(const c of t){if(!c||typeof c!="object")continue;const f=c.data&&typeof c.data=="object"?c.data:{};if(String(f.nodeType||c.type||"").trim()==="on_flow_start"){n=c;break}}if(!n)return[];const r=n.data&&typeof n.data=="object"?n.data:{},o=Array.isArray(r.outputs)?r.outputs:[],l=r.pinDefaults&&typeof r.pinDefaults=="object"?r.pinDefaults:{},u=[];for(const c of o){if(!c||typeof c!="object")continue;const f=String(c.id||"").trim();if(!f)continue;const _=String(c.type||"").trim();if(_==="execution"||f==="exec-out"||f==="exec")continue;const p=String(c.label||f).trim()||f,y={id:f,label:p,type:_||"unknown"};l&&Object.prototype.hasOwnProperty.call(l,f)&&(y.default=l[f]),u.push(y)}return u}function Ip(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}const m3=/^[a-zA-Z0-9_-]+$/;function Iv(e){return m3.test(String(e||"").trim())}async function _3(e){const t=String(e||"");return eE(t)}async function Ov(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(Iv(t)){const r=`session_memory_${t}`;if(Iv(r))return r}return`session_memory_sha_${(await _3(t)).slice(0,32)}`}const Pv=new Set(["abstract.status","abstract.summary","abstract.chat"]);function p3(e){if(!e)return!1;if(e.kind==="error")return!0;if(e.kind==="info")return!1;const t=String(e.emit_name||"").trim();if((e.kind==="event"||e.kind==="message")&&t)return!Pv.has(t);const n=String(e.effect_type||"").trim();if(n){if(n==="tool_calls"||n==="llm_call"||n==="ask_user"||n==="answer_user"||n==="memory_compact"||n==="start_subworkflow")return!0;if(n==="emit_event")return!(t&&Pv.has(t))}if(String(e.status||"").trim()==="waiting"){const l=no(e.data),u=String((l==null?void 0:l.reason)||"").trim();return!!(u==="user"||u==="event"||nd(l).length)}return!!Xf(e.data)}function g3(){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)||t_),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:t_,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 y3(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function w3(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=[],n=(o,l)=>{const u=String(l??"").trim();u&&(t.some(c=>c.label===o&&c.value===u)||t.push({label:o,value:u}))},r=String(e.display??"").trim().replace(/^\[/,"").replace(/\]$/,"");return n("time",r||e.local_datetime),n("tz",e.timezone),n("country",e.country),n("user",e.user),t}function Dv(e){const t=w3(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 v3(){return typeof window>"u"?"":A1(window.location)}function x3(){try{const e="abstractobserver_session_id_v1",t=window.sessionStorage.getItem(e);if(t&&t.trim())return t.trim();const n=`obs_${xs()}`;return window.sessionStorage.setItem(e,n),n}catch{return""}}function b3(){var sf,Au,_c,Hh,Vh,rf,of,Lo,Gh,va,af,Bn,Kh;const[e,t]=m.useState("board"),[n,r]=m.useState(()=>g3()),o=typeof window<"u"&&((sf=window.__ABSTRACT_UI_CONFIG__)==null?void 0:sf.monitor_gpu)===!0,l=typeof window<"u"&&(((Au=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Au.entity_app_url)||"").trim().replace(/\/+$/,"")||"http://127.0.0.1:3007",u=m.useRef(null),[c,f]=m.useState(""),[_,p]=m.useState(""),[y,w]=m.useState(()=>v3()),[x,S]=m.useState(""),[j,C]=m.useState(""),[N,T]=m.useState(""),[L,P]=m.useState("{}"),[W]=m.useState(()=>x3()),[G,Y]=m.useState(null),[J,re]=m.useState(!1),[ae,ue]=m.useState(""),[B,A]=m.useState(!1),[$,z]=m.useState(""),[E,te]=m.useState(!1),O=Rj({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((_c=window.__ABSTRACT_UI_CONFIG__)==null?void 0:_c.gateway_url)||t_,onStatusChange:g=>_u(g)}),[F,K]=m.useState(null),[R,Q]=m.useState(null),[Z,X]=m.useState(!1),[le,_e]=m.useState(null),[he,ye]=m.useState("once"),[Ee,ze]=m.useState(""),[Be,gt]=m.useState(eg),[Fe,tt]=m.useState([]),[lt,Ye]=m.useState(null),[Se,Re]=m.useState(!1),[ht,xe]=m.useState([]),Le=m.useRef(new W1(xs)),[Ue,Ft]=m.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[Qt,yn]=sS("abstractobserver",{legacyKey:"abstractobserver_settings"}),[Ut,It]=m.useState(!1),[jn,ns]=m.useState(!1),[$t,fn]=m.useState([]),[Un,En]=m.useState([]),[hn,On]=m.useState([]),[_n,js]=m.useState(!1),[Yn,Ss]=m.useState(null),[Mr,Pn]=m.useState([]),[ce,je]=m.useState(0),[Je,Ve]=m.useState(""),rt=m.useRef(!1),ct=m.useRef(0),Et=m.useRef(0),[St,Kt]=m.useState(!1),[xt,Yt]=m.useState([]),[Wt,Ot]=m.useState([]),[At,Tt]=m.useState({}),[De,sn]=m.useState(!1),[dt,en]=m.useState(!1),[ft,Wn]=m.useState(!1),[cn,er]=m.useState([]),[ss,Xr]=m.useState([]),_r=m.useRef(0),hi=m.useRef(null);hi.current||(hi.current=new Sw(g=>window.setTimeout(g,40),g=>er(k=>k.concat(g))));const mi=m.useRef(null);mi.current||(mi.current=new Sw(g=>window.setTimeout(g,40),g=>Xr(k=>k.concat(g))));const Ds=m.useRef({scanned:0,found:null}),[de,pr]=m.useState(null),[co,gr]=m.useState(""),[Rr,Zr]=m.useState(!1),it=m.useRef(null),[on,Fs]=m.useState({}),[Qr,rs]=m.useState({}),[zo,Bo]=m.useState(!1),[Uo,Dn]=m.useState(""),[yr,qn]=m.useState(!0),[uo,_i]=m.useState(""),[$n,zs]=m.useState(!1),[fs,tr]=m.useState(!1),[hs,Ma]=m.useState(6),[fo,rn]=m.useState("standard"),[Ra,Rc]=m.useState(""),[Wo,ms]=m.useState(""),[Lr,Ir]=m.useState(!1),[ho,wr]=m.useState(!1),[ks,vr]=m.useState("pause"),[Or,nr]=m.useState(""),[Li,is]=m.useState(""),[Pr,La]=m.useState(""),xr=m.useRef(null),mo=m.useRef(null),[Lc,Ii]=m.useState(!1),sr=m.useRef(null),[rd,rr]=m.useState(""),[_o,ir]=m.useState(""),[qo,pi]=m.useState(""),[bl,gi]=m.useState(""),[U,ie]=m.useState(""),[be,ke]=m.useState(!1),[Ae,qe]=m.useState("idle"),[et,ot]=m.useState([]),[mt,Pt]=m.useState(null),Jt=m.useRef(null),[Zn,zt]=m.useState(!1),[an,pn]=m.useState(""),[wn,_s]=m.useState(""),[Ns,br]=m.useState(""),[Ho,Vo]=m.useState([]),[jl,Ic]=m.useState(!1),[Oc,Pc]=m.useState(""),[id,Dc]=m.useState(""),[Fc,zc]=m.useState(!1),[od,Go]=m.useState(""),th=m.useMemo(()=>{if(!et.length)return"";try{return JSON.stringify(et.map(g=>({role:g.role,content:g.content,ts:g.ts})))}catch{return"1"}},[et]),ad=m.useMemo(()=>et.length?Ns?th!==Ns:!0:!1,[th,et.length,Ns]),ld=m.useMemo(()=>Ho.map(g=>{const k=String(g.title||"").trim()||`Chat ${String(g.thread_id||"").slice(0,8)}`,M=String(g.created_at||"").trim(),D=M?M.replace("T"," ").slice(0,19):"",V=String(g.run_id||"").trim()?String(g.run_id).slice(0,8):"",H=[k,D&&`(${D})`,V&&`run ${V}`].filter(Boolean).join(" • ");return{value:String(g.thread_id||""),label:H}}),[Ho]);m.useEffect(()=>{o&&K2()},[o]),m.useEffect(()=>{if(!o)return;const g=u.current;g&&(g.token=n.gateway_auth_mode==="direct"&&n.auth_token||"")},[o,n.auth_token,n.gateway_auth_mode]);const[Sl,cd]=m.useState([]),[y_,ud]=m.useState({}),[nh,sh]=m.useState({}),[dd,tn]=m.useState(""),[fd,w_]=m.useState(""),[hd,v_]=m.useState("all"),[kl,Nl]=m.useState("status"),[ps,Oi]=m.useState("overview"),md=Ny(B_.md),rh=Ny(`${B_.sm}, ${B_.short}`),Ko=N1({is_drawer:md,page:e}),Bc=Ko.open,yi=Ko.set_open,[ih,x_]=Rf("observe_runs"),b_=Ko.toggle_ref,oh=Ko.sidebar_ref,_d=m.useRef(null),[Pi,Cl]=m.useState(!0),[El,Ia]=m.useState("steps"),[j_,pd]=m.useState(""),[$l,Al]=m.useState(""),[gd,Tl]=m.useState([]),[yd,ah]=m.useState(!1),[S_,Uc]=m.useState(""),[lh,wd]=m.useState(""),[ei,Yo]=m.useState([]),[ch,vd]=m.useState(!1),[uh,Wc]=m.useState(""),[xd,bd]=m.useState(!1),[k_,Oa]=m.useState(""),[jd,wi]=m.useState(""),[qc,Ml]=m.useState(""),[Hc,Di]=m.useState(!1),[po,Pa]=m.useState(""),[Fi,Da]=m.useState(null),[Rl,Vc]=m.useState({}),[Sd,Fa]=m.useState(!1),[kd,Dr]=m.useState(""),[Jo,Nd]=m.useState(!1),[Cd,N_]=m.useState(!1),[Ll,Gc]=m.useState(()=>Date.now()),[vi,Xo]=m.useState(""),[Cn,za]=m.useState({}),[Kc,Zo]=m.useState({}),Ba=m.useRef([]),or=m.useRef(null),Fr=m.useRef(""),Qo=m.useRef({}),ti=m.useRef({}),Yc=m.useRef({}),Il=m.useRef(new Set),[zi,Ol]=m.useState([]),go=m.useRef(""),Bi=m.useRef({}),xi=m.useRef(null),Cs=m.useRef(null),Ui=m.useRef(0),yo=m.useRef({}),Jc=m.useRef(!1),wo=m.useRef(new Set),[Ed,Xc]=m.useState(""),[zr,Bs]=m.useState(""),ni=m.useRef(""),[ea,Br]=m.useState(!1),[Pl,Ur]=m.useState(""),Zc=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[Dl,dh]=m.useState("activity"),[Wi,Ua]=m.useState([]),[ta,Fl]=m.useState(0),[$d,na]=m.useState(0),[vo,Sn]=m.useState({}),[kn,qi]=m.useState({}),[Es,Us]=m.useState(!1),[sa,ra]=m.useState(""),[os,Qc]=m.useState(""),[Wa,eu]=m.useState("all"),[ia,Ad]=m.useState(""),[ar,tu]=m.useState([]),[qa,fh]=m.useState("all"),[Ha,xo]=m.useState("type"),[Hi,Va]=m.useState("newest"),[si,zl]=m.useState(""),[$s,As]=m.useState(""),[bo,ri]=m.useState(""),[jr,Vi]=m.useState(0),[oa,Bl]=m.useState(()=>Zc()),[Td,Ws]=m.useState(!1),[lr,An]=m.useState(""),[ii,aa]=m.useState(""),[Ts,Ga]=m.useState(""),[Ul,hh]=m.useState("text"),[nu,su]=m.useState(null),[Ka,Ya]=m.useState(!1),[mh,jo]=m.useState(""),[Wl,Md]=m.useState(""),[_h,la]=m.useState(""),[Rd,ql]=m.useState(!1),[ru,ca]=m.useState(""),[Ja,Ld]=m.useState("run_ledger"),[Id,Od]=m.useState(""),[Xa,cr]=m.useState([]),[ua,Hl]=m.useState(""),[ph,bi]=m.useState(!1),[So,Vl]=m.useState(""),Ie=m.useMemo(()=>new up({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]),gn=m.useMemo(()=>new s2(Ie.automations_client(),e2(Ie,xs,kt)),[Ie]),ji=m.useSyncExternalStore(g=>gn.subscribe(g),()=>gn.state),Gl=P1(n.gateway_url),iu=Gl?()=>{window.open(Gl,"_blank","noopener,noreferrer")}:void 0;m.useEffect(()=>{e==="launch"&&he==="automate"&&E&&gn.load_email_status()},[e,he,E,gn]),m.useEffect(()=>{const g=()=>{const k=F1(window.location.hash);if(k){if(k.page==="run"){w(k.run_id);return}k.page==="launch"&&ye(k.mode),t(k.page)}};return g(),window.addEventListener("hashchange",g),()=>window.removeEventListener("hashchange",g)},[]);const ou=m.useMemo(()=>{const g={};for(const k of ji.items)g[k.automation_id]=k.title;return g},[ji.items]),gh=m.useMemo(()=>P2(),[]),[Kl,oi]=m.useState([]),Za=m.useRef(0);function Yl(){const g=++Za.current;oi([["Gateway","checking…"]]),D2(Ie).then(k=>{g===Za.current&&oi(k)})}const Si=m.useMemo(()=>n.worker_url.trim()?new nE({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),gs=cn.length?cn[cn.length-1].record:null,qt=m.useMemo(()=>no(gs),[gs]),ys=m.useMemo(()=>{const g=N.trim();if(!G||!g||String(G.bundle_id||"").trim()&&String(G.bundle_id||"").trim()!==g)return null;const k=Array.isArray(G.entrypoints)?G.entrypoints:[];if(!k.length)return null;const M=j.trim();if(M)return k.find(V=>String(V.flow_id||"").trim()===M)||null;if(k.length===1)return k[0];const D=String(G.default_entrypoint||"").trim();return D&&k.find(V=>String(V.flow_id||"").trim()===D)||null},[G,N,j]),Jl=m.useMemo(()=>{const g=ys==null?void 0:ys.inputs;return Array.isArray(g)?g:[]},[ys]),Tn=m.useMemo(()=>h3(Fi),[Fi]),ko=m.useMemo(()=>Jl.length?Jl:Tn,[Jl,Tn]),au=m.useMemo(()=>{const g=typeof(de==null?void 0:de.workflow_id)=="string"?String(de.workflow_id):"",k=Lv(g);if(k&&G&&String(G.bundle_id||"").trim()===k.bundle_id){const V=(Array.isArray(G.entrypoints)?G.entrypoints:[]).find(H=>String((H==null?void 0:H.flow_id)||"").trim()===k.flow_id);if(V&&V.node_index&&typeof V.node_index=="object")return V.node_index}const M=ys==null?void 0:ys.node_index;return M&&typeof M=="object"?M:{}},[de,G,ys]);m.useEffect(()=>{y3(n)},[n]),m.useEffect(()=>()=>{xi.current&&xi.current.abort(),Cs.current&&Cs.current.abort(),xr.current&&window.clearTimeout(xr.current),mo.current&&window.clearTimeout(mo.current),or.current&&window.clearTimeout(or.current),sr.current&&window.clearTimeout(sr.current)},[]);const ut=m.useMemo(()=>{const g=L.trim();if(!g)return{};try{const k=JSON.parse(g);return typeof k!="object"||k===null||Array.isArray(k)?null:k}catch{return null}},[L]),lu=typeof(ut==null?void 0:ut.prompt)=="string"?String(ut.prompt):"",Xl=typeof(ut==null?void 0:ut.provider)=="string"?String(ut.provider):"",da=typeof(ut==null?void 0:ut.model)=="string"?String(ut.model):"",Fn=typeof(ut==null?void 0:ut.workspace_root)=="string"?String(ut.workspace_root):"",Jn=typeof(ut==null?void 0:ut.workspace_access_mode)=="string"?String(ut.workspace_access_mode):"",as=m.useMemo(()=>{const g=ut==null?void 0:ut.workspace_allowed_paths;return Array.isArray(g)?g.map(k=>String(k||"").trim()).filter(Boolean).join(`
144
+ `):typeof g=="string"?String(g):""},[ut]),cu=m.useMemo(()=>{const g=ut==null?void 0:ut.workspace_ignored_paths;return Array.isArray(g)?g.map(k=>String(k||"").trim()).filter(Boolean).join(`
145
+ `):typeof g=="string"?String(g):""},[ut]),Zl=ko.length>0&&!!N.trim(),fa=g=>{const k=String(g||"").trim().toLowerCase();return k==="object"||k==="memory"||k==="assertion"||k==="assertions"||k==="any"};m.useEffect(()=>{rs({})},[N,j]),m.useEffect(()=>{ut!==null&&Fs(g=>{const k={};for(const M of ko){if(!M||typeof M!="object")continue;const D=String(M.id||"").trim();if(!D)continue;const V=String(M.type||"").trim();if(!fa(V))continue;if(String(Qr[D]||"").trim()){k[D]=typeof g[D]=="string"?g[D]:"";continue}const q=ut==null?void 0:ut[D];q===void 0?k[D]="":k[D]=Y2(q)}return k})},[ko,ut,Qr]);const Qa=Ee?{kind:"default",interface:Ee}:N.trim()&&j.trim()?{kind:"bundle",bundle_id:N.trim(),flow_id:j.trim()}:null,Ms=M1(Qa),Wr=Array.isArray(ut==null?void 0:ut.skills)?ut.skills.map(g=>String(g||"").trim()).filter(Boolean):[],Sr=m.useMemo(()=>{const g={};for(const k of $t){const M=String(k.workflow_id||"").trim(),D=String(k.label||"").trim();M&&D&&(g[M]=D)}return g},[$t]),uu=m.useMemo(()=>$t.filter(g=>g.has_interface),[$t]),ki=m.useMemo(()=>{const g=new Set;for(const k of Array.isArray(Wt)?Wt:[]){const M=String((k==null?void 0:k.name)||"").trim();M&&g.add(M)}return Array.from(g).sort()},[Wt]),qr=m.useMemo(()=>{const g=[];for(const k of Array.isArray(Wt)?Wt:[]){const M=String((k==null?void 0:k.name)||"").trim();if(!M)continue;const D=String((k==null?void 0:k.display_name)||"").trim();g.push({name:M,display_name:D||void 0})}return g},[Wt]),Ql=m.useMemo(()=>{const g=new Set;for(const k of xt||[]){if(!k||typeof k!="object")continue;const M=String(k.name||"").trim();M&&g.add(M)}return Array.from(g).sort()},[xt]),du=m.useMemo(()=>{const g=n.maintenance_ai_provider.trim();if(!g)return{models:[],error:""};const k=At[g];return k?{models:(Array.isArray(k.models)?k.models:[]).map(D=>String(D||"").trim()).filter(Boolean),error:String(k.error||"")}:{models:[],error:""}},[At,n.maintenance_ai_provider]),ec=n.maintenance_ai_provider.trim(),yh=!!(ec&&E&&!Object.prototype.hasOwnProperty.call(At,ec));m.useEffect(()=>{const g=Xl.trim();if(!g||At[g]||Bi.current[g])return;Bi.current[g]=!0;let k=!1;return(async()=>{try{const D=await Ie.discovery_provider_models(g);if(k)return;const V=Array.isArray(D==null?void 0:D.models)?D.models:[],H=typeof(D==null?void 0:D.error)=="string"?String(D.error):"";Tt(q=>({...q,[g]:{models:V,error:H||void 0}}))}catch(D){if(k)return;Tt(V=>({...V,[g]:{models:[],error:String((D==null?void 0:D.message)||D||"Failed to load models")}}))}finally{delete Bi.current[g]}})(),()=>{k=!0}},[Xl,At,Ie]),m.useEffect(()=>{const g=n.maintenance_ai_provider.trim();if(!g||!E||At[g]||Bi.current[g])return;Bi.current[g]=!0;let k=!1;return(async()=>{try{const D=await Ie.discovery_provider_models(g);if(k)return;const V=Array.isArray(D==null?void 0:D.models)?D.models:[],H=typeof(D==null?void 0:D.error)=="string"?String(D.error):"";Tt(q=>({...q,[g]:{models:V,error:H||void 0}}))}catch(D){if(k)return;Tt(V=>({...V,[g]:{models:[],error:String((D==null?void 0:D.message)||D||"Failed to load models")}}))}finally{delete Bi.current[g]}})(),()=>{k=!0}},[n.maintenance_ai_provider,At,Ie,E]);function Mn(g,k){const M=String(g||"").trim();if(!M)return;let D={};try{const V=JSON.parse(L||"{}");typeof V=="object"&&V!==null&&!Array.isArray(V)&&(D=V)}catch{D={}}if(k==null){delete D[M],P(JSON.stringify(D,null,2));return}if(typeof k=="string")k?D[M]=k:delete D[M];else if(Array.isArray(k)){const V=k.map(H=>H).filter(H=>H!=null);V.length?D[M]=V:delete D[M]}else D[M]=k;P(JSON.stringify(D,null,2))}async function Pd(g){const k=String(g||"").trim();if(!k)return ue("Missing bundle_id"),null;ue(""),re(!0);try{const M=await Ie.get_bundle(k);return Y(M),Xt({ts:kt(),kind:"info",title:`Loaded bundle ${k}`}),M}catch(M){return Y(null),ue(String((M==null?void 0:M.message)||M||"Failed to load bundle")),null}finally{re(!1)}}function fu(g){const k=[],M=Array.isArray(g==null?void 0:g.items)?g.items:[];for(const D of M){const V=String((D==null?void 0:D.bundle_id)||"").trim();if(!V)continue;const H=Array.isArray(D==null?void 0:D.entrypoints)?D.entrypoints:[];if(H.length)for(const q of H){const ne=String((q==null?void 0:q.flow_id)||"").trim();if(!ne||(q==null?void 0:q.deprecated)===!0)continue;const Ce=`${V}:${ne}`,me=String((q==null?void 0:q.name)||"").trim(),ge=me?`${V} · ${me}`:`${V} · ${ne}`,Ne=String((q==null?void 0:q.description)||"").trim(),He=(Array.isArray(q==null?void 0:q.interfaces)?q.interfaces:[]).some(Ke=>String(Ke||"").trim().length>0),Xe=Array.isArray(q==null?void 0:q.agent_default_interfaces)?q.agent_default_interfaces.map(Ke=>String(Ke||"").trim()).filter(Boolean):[];k.push({workflow_id:Ce,bundle_id:V,bundle_ref:String((D==null?void 0:D.bundle_ref)||"").trim(),flow_id:ne,label:ge,description:Ne||void 0,has_interface:He,agent_default_interfaces:Xe})}}return k.sort((D,V)=>D.label.localeCompare(V.label)),k}async function qs(g=Ie,k){if(rt.current&&!(k!=null&&k.force))return;rt.current=!0;const M=Gi.current;js(!0);try{const D=me=>me.map(H1).filter(ge=>!!ge.run_id),[V,H]=await Promise.all([g.list_runs({limit:200,root_only:!0,include_metrics:!0}),g.list_runs({limit:500,root_only:!1,include_metrics:!0})]);if(M!==Gi.current)return;const q=Array.isArray(V==null?void 0:V.items)?V.items:[],ne=Array.isArray(H==null?void 0:H.items)?H.items:[],Ce=D(q).filter(me=>!String(me.parent_run_id||"").trim()||me.role==="occurrence");En(Ce),On(D(ne).filter(me=>!!me.run_id)),Ss(Date.now()),Et.current=0,ct.current=0}catch(D){const V=String((D==null?void 0:D.message)||D||"");if(Xt({ts:kt(),kind:"error",title:"Refresh runs failed",preview:_t(V)}),(/\b40[13]\b/.test(V)||/unauthorized|forbidden/i.test(V))&&O.refresh().catch(()=>{}),/\b429\b/.test(V)||/too many requests/i.test(V)){const H=Math.min(12e4,Math.max(15e3,Et.current*2||15e3));Et.current=H,ct.current=Date.now()+H,Xt({ts:kt(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(H/1e3)}s`})}}finally{rt.current=!1,js(!1)}}async function Dd(g){var ne,Ce,me;const k=Gi.current;te(!0),Tt({});const[M,,D,V,H]=await Promise.allSettled([g.list_bundles(),qs(g),g.discovery_tools(),g.discovery_providers({include_models:!1}),g.discovery_capabilities()]);if(k!==Gi.current)return;if(M.status==="rejected"&&D.status==="rejected"&&V.status==="rejected"){te(!1),z(Ip(M.reason,n)),Xt({ts:kt(),kind:"error",title:"Discovery failed",preview:_t(String(M.reason||""))});return}Ft(H.status==="fulfilled"?V1(H.value):{available:!1,reason:`Could not read the gateway capabilities: ${String(((ne=H.reason)==null?void 0:ne.message)||H.reason)}`});let q=0;if(M.status==="fulfilled"){const ge=fu(M.value);q=ge.length,fn(ge)}else fn([]),Xt({ts:kt(),kind:"error",title:"Discovery bundles failed",preview:_t(String(M.reason||""))});if(D.status==="fulfilled"){const ge=Array.isArray((Ce=D.value)==null?void 0:Ce.items)?D.value.items:[];Yt(ge)}else Yt([]),Xt({ts:kt(),kind:"error",title:"Discovery tools failed",preview:_t(String(D.reason||""))});if(V.status==="fulfilled"){const ge=Array.isArray((me=V.value)==null?void 0:me.items)?V.value.items:[];Ot(ge)}else Ot([]),Xt({ts:kt(),kind:"error",title:"Discovery providers failed",preview:_t(String(V.reason||""))});Xt({ts:kt(),kind:"info",title:"Gateway discovery loaded",preview:_t(`workflows: ${q}`)})}async function el(g){var k,M;z(""),te(!1),A(!0);try{if(!(g!=null&&g.prefer_direct)&&(await O.refresh(),hu.current))return;const D=String(n.auth_token||"").trim();if(!D){g!=null&&g.open_modal_if_needed&&O.openModal();return}const V=String(n.gateway_url||"").trim();if(V){const q=V.toLowerCase();if(!q.startsWith("http://")&&!q.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(((k=window==null?void 0:window.location)==null?void 0:k.protocol)||"")==="https:"&&q.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 Ce=new URL(V),me=String(((M=window==null?void 0:window.location)==null?void 0:M.hostname)||"").trim().toLowerCase(),ge=String(Ce.hostname||"").trim().toLowerCase(),Ne=Oe=>Oe==="localhost"||Oe==="127.0.0.1"||Oe==="::1";if(Ne(ge)&&me&&!Ne(me))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(ne){throw new Error(String((ne==null?void 0:ne.message)||ne||"Invalid Gateway URL"))}}const H=new up({base_url:V,auth_token:D});await H.list_bundles(),r(q=>({...q,gateway_auth_mode:"direct"})),await Dd(H)}catch(D){z(Ip(D,n))}finally{A(!1)}}const hu=m.useRef(!1),Gi=m.useRef(0),mu=m.useRef(!1);function _u(g){var M,D,V;K(g);const k=!!(g&&g.has_session&&((M=g.gateway)!=null&&M.ok));if(hu.current=k,k){if(mu.current=!1,E&&n.gateway_auth_mode==="direct")return;const H=String(((V=(D=g==null?void 0:g.gateway)==null?void 0:D.principal)==null?void 0:V.user_id)||"").trim();if(r(q=>({...q,gateway_auth_mode:"session",auth_token:"",gateway_user:H||q.gateway_user})),E&&n.gateway_auth_mode==="session")return;z(""),A(!0),Dd(new up({base_url:"",auth_token:""})).catch(q=>z(Ip(q,n))).finally(()=>A(!1));return}g&&!g.has_session&&(n.gateway_auth_mode==="session"&&tc({keep_session:!0}),String(n.auth_token||"").trim()&&!E&&!mu.current&&(mu.current=!0,el({prefer_direct:!0})))}async function pu(){if(!(St||B)){Kt(!0);try{await Ie.reload_bundles();const g=await Ie.list_bundles(),k=fu(g);fn(k),Xt({ts:kt(),kind:"info",title:"Bundles reloaded",preview:_t(`workflows: ${k.length}`)})}catch(g){const k=String((g==null?void 0:g.message)||g||"Bundle reload failed");Xt({ts:kt(),kind:"error",title:"Bundle reload failed",preview:_t(k),data:{error:k}})}finally{Kt(!1)}}}async function wh(g){if(Rr||B||!E)return;const k=g;if(k){Zr(!0),tn("");try{const M=await Ie.upload_bundle(k,{overwrite:!1,reload:!0});Xt({ts:kt(),kind:"info",title:"Bundle uploaded",preview:_t(String((M==null?void 0:M.bundle_ref)||""))});const D=await Ie.list_bundles(),V=fu(D);fn(V)}catch(M){const D=String((M==null?void 0:M.message)||M||"Upload failed");tn(D),Xt({ts:kt(),kind:"error",title:"Upload .flow failed",preview:_t(D),data:{error:D}})}finally{Zr(!1);try{it.current&&(it.current.value="")}catch{}}}}function tc(g){Gi.current+=1,g!=null&&g.keep_session||(O.signOut().catch(()=>{}),hu.current=!1),vu(),T(""),C(""),Pa(""),Y(null),ue(""),re(!1),fn([]),En([]),On([]),Ss(null),Pn([]),Yt([]),Ot([]),Tt({}),z(""),te(!1),K(null),r(k=>({...k,auth_token:""})),Xt({ts:kt(),kind:"info",title:"Gateway disconnected"})}async function gu(g){const k=String(g??"");k&&Xn(await XC(k)?"Copied to clipboard":YC,2)}m.useEffect(()=>{const g=c.trim();if(!De||!g)return;let k=!1;const M=async()=>{if(!(ct.current>Date.now()))try{const V=await Ie.get_run(g);k||pr(V)}catch{}};M();const D=window.setInterval(M,2e3);return()=>{k=!0,window.clearInterval(D)}},[De,c,Ie]),m.useEffect(()=>{if(!E)return;let g=null,k=!1,M=!1;const D=q=>{k||(g!==null&&window.clearTimeout(g),g=window.setTimeout(()=>void V(),q))},V=async()=>{if(M)return;const q=ct.current-Date.now();if(q>0){D(q+500);return}M=!0;const ne=Date.now();try{await qs(Ie)}finally{M=!1;const Ce=Date.now()-ne,me=document.visibilityState==="hidden"?3e4:5e3;D(Math.max(me,Ce*3))}},H=()=>{document.visibilityState==="visible"&&V()};return V(),document.addEventListener("visibilitychange",H),()=>{k=!0,g!==null&&window.clearTimeout(g),document.removeEventListener("visibilitychange",H)}},[E,Ie]);const[vh,yu]=m.useState(null);m.useEffect(()=>{if(!E){yu(null);return}let g=!1;return(async()=>{try{const k=await Ie.get_entity_phases_spec();if(g)return;const M=XL(k);if(yu(M),M)try{const D=localStorage.getItem("abstractobserver_phase_graph_id_v1"),V=D?JSON.parse(D):null;V&&V.sha256&&M.sha256&&V.sha256!==M.sha256&&V.version===M.version&&Xt({ts:kt(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:_t(`v${M.version}: ${String(V.sha256).slice(0,12)}… -> ${String(M.sha256).slice(0,12)}…`),data:{prev:V,now:{sha256:M.sha256,version:M.version}}}),localStorage.setItem("abstractobserver_phase_graph_id_v1",JSON.stringify({sha256:M.sha256,version:M.version}))}catch{}}catch(k){if(!g){yu(null);const M=String((k==null?void 0:k.message)||k||"");/404|not found/i.test(M)||Xt({ts:kt(),kind:"info",title:"Phase-graph fetch failed — pre-wire fallback vocabulary in use (#FALLBACK)",preview:_t(M),data:{error:M}})}}})(),()=>{g=!0}},[E]),m.useEffect(()=>{if(!E){Pn([]),Ve("");return}let g=!1,k=null;const M=async()=>{if(!(ct.current>Date.now())){try{const D=await Ie.list_entities(),V=D.entities.map(q=>String((q==null?void 0:q.name)||(q==null?void 0:q.slug)||"").trim()).filter(Boolean).slice(0,12),H=await Promise.all(V.map(async q=>{var ne,Ce;try{const[me,ge]=await Promise.all([Ie.get_entity_card(q),Ie.get_entity_cognition(q).catch(()=>null)]),Ne=me!=null&&me.state&&typeof me.state=="object"?me.state:null,Oe=Array.isArray(me==null?void 0:me.moments)?me.moments:[],He=Oe.length?Oe[Oe.length-1]:null,Xe=(ne=ge==null?void 0:ge.spend)==null?void 0:ne.lifetime,Ke=(Ce=ge==null?void 0:ge.spend)==null?void 0:Ce.live_visit,nn=Array.isArray(ge==null?void 0:ge.warnings)?ge.warnings.map(We=>String(We||"")).filter(Boolean):[],Mt=FL(me);return{name:q,state:String((Ne==null?void 0:Ne.state)??(typeof(me==null?void 0:me.state)=="string"?me.state:"")).trim(),age_days:typeof(me==null?void 0:me.age_days)=="number"?me.age_days:null,last_moment:String((He==null?void 0:He.kind)||"").trim(),last_moment_at:String((He==null?void 0:He.at)||"").trim(),working:typeof(ge==null?void 0:ge.working)=="boolean"?ge.working:null,tokens_total:typeof(Xe==null?void 0:Xe.tokens_total)=="number"?Xe.tokens_total:null,live_visit_tokens:typeof(Ke==null?void 0:Ke.tokens_total)=="number"?Ke.tokens_total:null,spend_warning:nn.join(" | "),live_phase:typeof(ge==null?void 0:ge.phase)=="string"?ge.phase:"",open_questions:Mt.questions,open_questions_total:Mt.questions_total,open_problems:Mt.problems,open_problems_total:Mt.problems_total,lessons:Mt.lessons,lessons_total:Mt.lessons_total,dreams_brief:DL(me),error:""}}catch(me){return{name:q,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((me==null?void 0:me.message)||me||"card failed")}}}));g||(Pn(H),je(D.entities.length),Ve(""))}catch(D){if(!g){Pn([]);const V=String((D==null?void 0:D.message)||D||"");Ve(/404|not found/i.test(V)?"":V)}}g||(k=window.setTimeout(()=>void M(),3e4))}};return M(),()=>{g=!0,k!==null&&window.clearTimeout(k)}},[E,Ie]);async function xh(g,k,M){const D=String(k||"").trim();if(!g||!D)throw new Error("This wait has no wait_key yet — open the run to inspect.");await Ie.submit_command({command_id:xs(),run_id:g,type:"resume",payload:{wait_key:D,payload:M||{}},client_id:"web_pwa"}),Xt({ts:kt(),kind:"info",title:"Board resume submitted",preview:_t(`run ${g} · wait ${D}`),data:{run_id:g,wait_key:D}}),qs(Ie,{force:!0}),window.setTimeout(()=>void qs(Ie,{force:!0}),1200)}const kr=m.useMemo(()=>{const g=de==null?void 0:de.session_id;return typeof g=="string"?g.trim():g==null?"":String(g||"").trim()},[de]),ha=m.useMemo(()=>{const g=String(kr||"").trim();return g||String(W||"").trim()},[kr,W]);m.useEffect(()=>{if(!E||!ha){ie(""),gi("");return}(async()=>{try{const g=await Ov(ha);ie(g)}catch{ie("")}})()},[E,ha]);const Hn=d3({gateway:E?Ie:null,session_id:ha,run_id:U,on_error:gi,on_transcript:g=>{const k=String(g||"").trim();k&&(ir(M=>{const D=String(M||"");return D.trim()?`${D.trimEnd()}
146
+ ${k}`:k}),window.setTimeout(()=>{var M;return(M=Jt.current)==null?void 0:M.focus()},0))}});function Fd(g,k){try{const M=URL.createObjectURL(g),D=document.createElement("a");D.href=M,D.download=k||"download",D.rel="noreferrer",document.body.appendChild(D),D.click(),document.body.removeChild(D),window.setTimeout(()=>URL.revokeObjectURL(M),5e3)}catch{}}async function bh(){if(!yd){if(!E||!kr){Al(""),Tl([]),Uc("");return}ah(!0),Uc("");try{const g=await Ov(kr);Al(g);const k=await Ie.list_run_artifacts(g,{limit:800}),D=(Array.isArray(k==null?void 0:k.items)?k.items:[]).filter(V=>{const H=V==null?void 0:V.tags;return H&&typeof H=="object"&&String(H.kind||"").trim()==="attachment"});Tl(D)}catch(g){const k=String((g==null?void 0:g.message)||g||"Failed to load session attachments"),M=k.toLowerCase();k.includes("404")||M.includes("session_memory_")&&M.includes("not found")||M.includes('"detail"')&&M.includes("not found")&&M.includes("session_memory_")?(Tl([]),Uc("")):(Tl([]),Uc(k)),Al("")}finally{ah(!1)}}}async function jh(){const g=lh.trim();if(!g){Xn("This run recorded no workspace folder",2);return}try{const k=await fetch(C1,{method:"POST",headers:{"Content-Type":"application/json",...pb()},body:JSON.stringify({path:g})}),M=await k.json().catch(()=>({}));k.ok&&(M!=null&&M.ok)?Xn(`Opened ${String(M.path||g)}`,2):Xn(String((M==null?void 0:M.error)||`Folder reveal failed (${k.status})`),3)}catch(k){Xn(String((k==null?void 0:k.message)||k||"Folder reveal failed"),3)}}async function C_(g){const k=String($l||"").trim();if(!k){Xn("No session attachment store yet",2);return}const M=String((g==null?void 0:g.artifact_id)||"").trim();if(!M)return;const D=g!=null&&g.tags&&typeof g.tags=="object"?g.tags:{},V=String(D.filename||"").trim(),H=String(D.path||"").trim(),q=V||(H?H.split("/").pop():"")||M,ne=ap(q);try{const Ce=await Ie.download_run_artifact_content(k,M,{access:"download"});Fd(Ce,ne),Xn("Downloaded attachment",2)}catch(Ce){Xn(String((Ce==null?void 0:Ce.message)||Ce||"Download failed"),3)}}async function E_(g){const k=String($l||"").trim(),M=String((g==null?void 0:g.artifact_id)||"").trim();if(!k||!M)return;const D=g!=null&&g.tags&&typeof g.tags=="object"?g.tags:{},V=String(D.filename||"").trim(),H=String(D.path||"").trim(),q=H?`@${H}`:V||M,ne=typeof(g==null?void 0:g.size_bytes)=="number"?Number(g.size_bytes):null,Ce=String((g==null?void 0:g.content_type)||D.content_type||"").trim().toLowerCase();if(Oa(q),wi(""),Ml(""),bd(!0),typeof ne=="number"&&ne>1e6){wi(`(Attachment is ${ne.toLocaleString()} bytes; download to view.)`);return}if(!(!Ce||Ce.startsWith("text/")||Ce.includes("json")||Ce.includes("yaml")||Ce.includes("toml")||Ce.includes("xml"))){wi(`(Binary attachment: ${Ce||"unknown"}; download to view.)`);return}Di(!0);try{const Ne=await(await Ie.download_run_artifact_content(k,M,{access:"download"})).text(),Oe=14e3,He=Ne.length>Oe?`${Ne.slice(0,Math.max(0,Oe-1))}…`:Ne;wi(He)}catch(ge){Ml(String((ge==null?void 0:ge.message)||ge||"Preview failed"))}finally{Di(!1)}}async function zd(g){const k=String((g==null?void 0:g.run_id)||"").trim(),M=String((g==null?void 0:g.artifact_id)||"").trim();if(!k||!M){Xn("Artifact download needs a run id",3);return}const D=sg(g)||M;try{const V=await Ie.download_run_artifact_content(k,M,{access:"preview"});Fd(V,ap(D)),Xn("Downloaded artifact",2)}catch(V){Xn(String((V==null?void 0:V.message)||V||"Download failed"),3)}}async function Bd(g){const k=String((g==null?void 0:g.run_id)||"").trim(),M=String((g==null?void 0:g.artifact_id)||"").trim();if(!k||!M){Xn("Artifact preview needs a run id",3);return}const D=sg(g),V=String((g==null?void 0:g.content_type)||"").trim().toLowerCase(),H=Tf(g);if(An(D||M),aa(""),jo(""),hh(H),su(g),Ws(!0),Ts&&(URL.revokeObjectURL(Ts),Ga("")),H==="binary"){aa(`(Binary artifact: ${V||"unknown"}; download to view.)`);return}if(H==="text"&&typeof g.size_bytes=="number"&&g.size_bytes>15e5){aa(`(Text artifact is ${g.size_bytes.toLocaleString()} bytes; download to view.)`);return}Ya(!0);try{const q=await Ie.download_run_artifact_content(k,M,{access:"preview"});if(H==="text"){const ne=await q.text(),Ce=Bm(g,ne),me=Ce==="json"?15e5:Ce==="markdown"?25e4:Ce==="html"?3e5:22e3;aa(ne.length>me&&Ce!=="text"?`${xc(g.size_bytes??ne.length)} ${Ce.toUpperCase()} artifact. Download to inspect it.`:ne.length>me?`${ne.slice(0,Math.max(0,me-1))}…`:ne)}else Ga(URL.createObjectURL(q))}catch(q){jo(String((q==null?void 0:q.message)||q||"Preview failed"))}finally{Ya(!1)}}m.useEffect(()=>()=>{Ts&&URL.revokeObjectURL(Ts)},[Ts]);async function Sh(g){const k=String(g.artifact_id||"").trim(),M=String(g.run_id||"").trim(),D=Tf(g);if(!M||!k)return{artifact_id:k,kind:D,render_kind:"",text:"Preview needs artifact run metadata.",url:"",loading:!1,error:""};if(D==="binary")return{artifact_id:k,kind:D,render_kind:"",text:`Preview unavailable for ${g.content_type||g.modality||"this artifact"}. Download to inspect it.`,url:"",loading:!1,error:""};if(D==="text"&&typeof g.size_bytes=="number"&&g.size_bytes>5e5)return{artifact_id:k,kind:D,render_kind:"",text:`${xc(g.size_bytes)} text artifact. Use Preview for a larger view or Download to inspect locally.`,url:"",loading:!1,error:""};try{const V=await Ie.download_run_artifact_content(M,k,{access:"preview"});if(D==="text"){const H=await V.text(),q=Bm(g,H),ne=q==="json"?5e5:q==="markdown"?12e4:q==="html"?3e5:8e3;return{artifact_id:k,kind:D,render_kind:q,text:H.length>ne&&q!=="text"?`${xc(g.size_bytes??H.length)} ${q.toUpperCase()} artifact. Use Larger preview or Download to inspect it.`:H.length>ne?`${H.slice(0,Math.max(0,ne-1))}…`:H,url:"",loading:!1,error:""}}return{artifact_id:k,kind:D,render_kind:"",text:"",url:URL.createObjectURL(V),loading:!1,error:""}}catch(V){return{artifact_id:k,kind:D,render_kind:"",text:"",url:"",loading:!1,error:String((V==null?void 0:V.message)||V||"Preview failed")}}}async function wu(g){if(oa.url&&URL.revokeObjectURL(oa.url),!g){Bl(Zc());return}const k=String(g.artifact_id||"").trim(),M=Tf(g);Bl({artifact_id:k,kind:M,render_kind:"",text:"",url:"",loading:!0,error:""}),Bl(await Sh(g))}m.useEffect(()=>{bh()},[Ie,E,kr]);function Xt(g){const k=String(g.id||"").trim()||xs();cd(M=>[{...g,id:k},...M].slice(0,800))}function Xn(g,k){La(g),mo.current&&window.clearTimeout(mo.current),Ii(!1),window.requestAnimationFrame(()=>Ii(!0)),mo.current=window.setTimeout(()=>{Ii(!1),mo.current=null},1500),xr.current&&(window.clearTimeout(xr.current),xr.current=null),k>0&&(xr.current=window.setTimeout(()=>{La(""),xr.current=null},Math.max(1,k)*1e3))}function Nr(g,k){const M=String(g||"").trim(),D=String(k||"").trim();if(!D)return"";const V=M?String(Qo.current[M]||"").trim():"";return V?`${V}::${D}`:D}function Cr(g,k,M){const D=String(g||"").trim(),V=String(k||"").trim(),H=String(M||"").trim();if(!D||!V||!H)return;const q=Nr(D,V);q&&(Qo.current[H]=q,ti.current[H]=D,Yc.current[H]={parent_run_id:D,parent_node_id:V},Il.current.has(H)||(Il.current.add(H),Ol(ne=>ne.includes(H)?ne:[...ne,H])))}function tl(g){const k=String(g||"").trim();if(!k)return;const M=Date.now(),D=Fr.current;Fr.current=k,Gc(M),za(V=>{const H={};for(const[me,ge]of Object.entries(V))typeof ge=="number"&&ge>M&&(H[me]=ge);H[k]=Math.max(H[k]||0,M+2e3),D&&D!==k&&(H[D]=Math.max(H[D]||0,M+2e3));const q=Object.keys(H);if(q.length<=200)return H;const ne=q.sort((me,ge)=>(H[ge]||0)-(H[me]||0)).slice(0,200),Ce={};for(const me of ne)Ce[me]=H[me]||0;return Ce}),Zo(V=>{if(typeof V[k]=="number")return V;const H={...V,[k]:M};if(Ba.current.push(k),Ba.current.length>8e3){const q=Ba.current.splice(0,1500);for(const ne of q)delete H[ne]}return H}),or.current&&window.clearTimeout(or.current),or.current=window.setTimeout(()=>{const V=Date.now();za(H=>{const q={};for(const[ne,Ce]of Object.entries(H))typeof Ce=="number"&&Ce>V&&(q[ne]=Ce);return q}),Gc(V),or.current=null},2200)}function nc(g,k){var Ke,nn,Mt;const M=String(k||"").trim()||c.trim();_r.current=g.cursor,(Ke=hi.current)==null||Ke.push({cursor:g.cursor,record:g.record}),M&&wo.current.add(`${M}:${g.cursor}`);const D=am(g.record),V=D&&D.name?Nf(D.name):"",H=g.record,q=typeof(H==null?void 0:H.node_id)=="string"?H.node_id:"",ne=typeof(H==null?void 0:H.status)=="string"?H.status:"",Ce=typeof((nn=H==null?void 0:H.effect)==null?void 0:nn.type)=="string"?H.effect.type:"",me=typeof(H==null?void 0:H.run_id)=="string"?H.run_id:"",ge=me||M;if(V==="abstract.status"&&ge===M){const{text:We,duration:jt}=Lu(D==null?void 0:D.payload);Xn(We,jt)}const Ne=q?Nr(ge,q):"";if(ne==="waiting"){const We=no(H);if(String((We==null?void 0:We.reason)||"").trim()==="subworkflow"){const mn=typeof((Mt=We==null?void 0:We.details)==null?void 0:Mt.sub_run_id)=="string"?String(We.details.sub_run_id):"";mn&&q&&Cr(ge,q,mn)}}if(q&&(tl(Nr(ge,q)),ne==="waiting"||ne==="running")){const We=Nr(ge,q);We&&(Fr.current=We,Xo(We))}let Oe="step",He=Ne||q||"(node?)",Xe="";if(D&&D.name&&Lp(D.name))Oe=V==="abstract.message"?"message":"event",He=V||D.name,Xe=_t(V==="abstract.steer_seen"?Rp(D==null?void 0:D.payload):Lu(D==null?void 0:D.payload).text);else if(H!=null&&H.error)Oe="error",He="error",Xe=_t(Os(H.error,360));else if(ne==="waiting"){const We=no(H),jt=String((We==null?void 0:We.reason)||"").trim();Xe=_t(jt?`waiting • ${jt}`:"waiting")}else H!=null&&H.result?Xe=_t(Os(H.result,360)):Ce?Xe=_t(Ce):Xe=_t(Nm(H));Xt({id:`step:${me||M||"?"}:${g.cursor}`,ts:String((H==null?void 0:H.ended_at)||(H==null?void 0:H.started_at)||kt()),kind:Oe,title:He,preview:Xe,data:H,cursor:g.cursor,run_id:me||M||void 0,node_id:Ne||q,status:ne,effect_type:Ce,emit_name:V||(D==null?void 0:D.name)||void 0})}function kh(g,k){var Xe,Ke,nn;Ui.current=Math.max(Ui.current,k.cursor);const M=`${g}:${k.cursor}`;if(!!wo.current.has(M))return;wo.current.add(M),(Xe=mi.current)==null||Xe.push({run_id:g,cursor:k.cursor,record:k.record});const V=am(k.record),H=V&&V.name?Nf(V.name):"",q=k.record,ne=typeof(q==null?void 0:q.node_id)=="string"?q.node_id:"",Ce=ne?Nr(g,ne):"",me=typeof(q==null?void 0:q.status)=="string"?q.status:"",ge=typeof((Ke=q==null?void 0:q.effect)==null?void 0:Ke.type)=="string"?q.effect.type:"";if(me==="waiting"){const Mt=no(q);if(String((Mt==null?void 0:Mt.reason)||"").trim()==="subworkflow"){const jt=typeof((nn=Mt==null?void 0:Mt.details)==null?void 0:nn.sub_run_id)=="string"?String(Mt.details.sub_run_id):"";jt&&ne&&Cr(g,ne,jt),jt&&ni.current.trim()===String(g||"").trim()&&(ni.current=jt,Bs(jt))}}if(ne&&(tl(Nr(g,ne)),me==="waiting"||me==="running")){const Mt=Nr(g,ne);Mt&&(Fr.current=Mt,Xo(Mt))}if((me==="completed"||me==="failed")&&ni.current.trim()===String(g||"").trim()){const Mt=String(ti.current[String(g||"").trim()]||"").trim();Mt&&Mt!==c.trim()?(ni.current=Mt,Bs(Mt)):(ni.current="",Bs(""))}if(H==="abstract.status"&&g===c.trim()){const{text:Mt,duration:We}=Lu(V==null?void 0:V.payload);Xn(Mt,We)}let Ne="step",Oe=Ce||ne||"(node?)",He="";if(V&&V.name&&Lp(V.name))Ne=H==="abstract.message"?"message":"event",Oe=`subrun • ${H||V.name}`,He=_t(H==="abstract.steer_seen"?Rp(V==null?void 0:V.payload):Lu(V==null?void 0:V.payload).text);else if(q!=null&&q.error)Ne="error",Oe="error",He=_t(Os(q.error,360));else if(me==="waiting"){const Mt=no(q),We=String((Mt==null?void 0:Mt.reason)||"").trim();He=_t(We?`waiting • ${We}`:"waiting")}else q!=null&&q.result?He=_t(Os(q.result,360)):ge?He=_t(ge):He=_t(Nm(q));Xt({id:`step:${g}:${k.cursor}`,ts:String((q==null?void 0:q.ended_at)||(q==null?void 0:q.started_at)||kt()),kind:Ne,title:Oe,preview:He,data:q,cursor:k.cursor,run_id:g,node_id:Ce||ne,status:me,effect_type:ge,emit_name:H||(V==null?void 0:V.name)||""})}function Nh(g,k){var Ke,nn,Mt;const M=String(g||"").trim();if(!M)return;const D=`${M}:${k.cursor}`;if(!!wo.current.has(D))return;wo.current.add(D),(Ke=mi.current)==null||Ke.push({run_id:M,cursor:k.cursor,record:k.record});const H=am(k.record),q=H&&H.name?Nf(H.name):"",ne=k.record,Ce=typeof(ne==null?void 0:ne.node_id)=="string"?ne.node_id:"",me=Ce?Nr(M,Ce):"",ge=typeof(ne==null?void 0:ne.status)=="string"?ne.status:"",Ne=typeof((nn=ne==null?void 0:ne.effect)==null?void 0:nn.type)=="string"?ne.effect.type:"";if(ge==="waiting"){const We=no(ne);if(String((We==null?void 0:We.reason)||"").trim()==="subworkflow"){const mn=typeof((Mt=We==null?void 0:We.details)==null?void 0:Mt.sub_run_id)=="string"?String(We.details.sub_run_id):"";mn&&Ce&&Cr(M,Ce,mn)}}if(Ce&&(tl(Nr(M,Ce)),ge==="waiting"||ge==="running")){const We=Nr(M,Ce);We&&(Fr.current=We,Xo(We))}if(q==="abstract.status"&&M===c.trim()){const{text:We,duration:jt}=Lu(H==null?void 0:H.payload);Xn(We,jt)}let Oe="step",He=me||Ce||"(node?)",Xe="";if(H&&H.name&&Lp(H.name))Oe=q==="abstract.message"?"message":"event",He=`subrun • ${q||H.name}`,Xe=_t(q==="abstract.steer_seen"?Rp(H==null?void 0:H.payload):Lu(H==null?void 0:H.payload).text);else if(ne!=null&&ne.error)Oe="error",He="error",Xe=_t(Os(ne.error,360));else if(ge==="waiting"){const We=no(ne),jt=String((We==null?void 0:We.reason)||"").trim();Xe=_t(jt?`waiting • ${jt}`:"waiting")}else ne!=null&&ne.result?Xe=_t(Os(ne.result,360)):Ne?Xe=_t(Ne):Xe=_t(Nm(ne));Xt({id:`step:${M}:${k.cursor}`,ts:String((ne==null?void 0:ne.ended_at)||(ne==null?void 0:ne.started_at)||kt()),kind:Oe,title:He,preview:Xe,data:ne,cursor:k.cursor,run_id:M,node_id:me||Ce,status:ge,effect_type:Ne,emit_name:q||(H==null?void 0:H.name)||""})}async function Ud(g,k){var D,V;let M=k.after;for(;;){if((D=k.signal)!=null&&D.aborted)return M;const H=await Ie.get_ledger(g,{after:M,limit:200,signal:k.signal});if((V=k.signal)!=null&&V.aborted)return M;const q=Array.isArray(H.items)?H.items:[];if(!q.length)return _r.current=M,M;const ne=M;for(let Ce=0;Ce<q.length;Ce++){const me=q[Ce];nc({cursor:ne+Ce+1,record:me},g)}M=typeof H.next_after=="number"?H.next_after:M}}async function ma(g){var H,q,ne,Ce;const k=String(g||"").trim();tn(""),en(!0),sn(!1),(H=hi.current)==null||H.reset(),(q=mi.current)==null||q.reset(),Ds.current={scanned:0,found:null},er([]),_r.current=0,Xr([]),wo.current=new Set,cd([]),ud({}),sh({}),Ia("steps"),pd(""),La(""),pr(null),rr(""),wd(""),Yo([]),Wc(""),Xo(""),Fr.current="",za({}),Zo({}),Ba.current=[],Gc(Date.now()),Qo.current=k?{[k]:""}:{},ti.current={},Yc.current={},Il.current=new Set,Ol([]),go.current="",ni.current="",Bs(""),yo.current={},or.current&&window.clearTimeout(or.current),or.current=null,sr.current&&window.clearTimeout(sr.current),sr.current=null,xi.current&&xi.current.abort(),Cs.current&&Cs.current.abort(),Cs.current=null,Ui.current=0,Xc("");const M=new AbortController;xi.current=M;let D=!1;try{let me="",ge="";try{const Ne=await Ie.get_run(k);pr(Ne);const Oe=typeof(Ne==null?void 0:Ne.workflow_id)=="string"?String(Ne.workflow_id):"",He=Lv(Oe);He&&(me=He.bundle_id,ge=He.flow_id)}catch{}try{const Ne=await Ie.get_run_input_data(k);typeof(Ne==null?void 0:Ne.bundle_id)=="string"&&(me=String(Ne.bundle_id||"").trim()||me),typeof(Ne==null?void 0:Ne.flow_id)=="string"&&(ge=String(Ne.flow_id||"").trim()||ge);const Oe=Ne&&typeof Ne.input_data=="object"&&Ne.input_data&&!Array.isArray(Ne.input_data)?Ne.input_data:null;Oe&&P(JSON.stringify(Oe,null,2));const He=Ne==null?void 0:Ne.workspace,Xe=typeof(He==null?void 0:He.workspace_root)=="string"?String(He.workspace_root).trim():"";wd(Xe)}catch{wd("")}(async()=>{vd(!0),Wc("");try{const Ne=await Ie.list_run_artifacts(k,{limit:200}),Oe=Array.isArray(Ne==null?void 0:Ne.items)?Ne.items:[];M.signal.aborted||Yo(Oe)}catch(Ne){M.signal.aborted||(Yo([]),Wc(String((Ne==null?void 0:Ne.message)||Ne||"artifact listing failed")))}finally{M.signal.aborted||vd(!1)}})(),me&&ge&&(T(me),C(ge),Pa(ge),await Pd(me)),await Ud(k,{after:0,signal:M.signal});try{const Ne=await Ie.get_run_history_bundle(k,{include_subruns:!0,include_session:!1,ledger_mode:"tail",ledger_max_items:1}),Oe=Ne&&typeof Ne=="object"?Ne.ledgers:null,Xe=(Oe&&typeof Oe=="object"?Object.keys(Oe):[]).map(Ke=>String(Ke||"").trim()).filter(Boolean).filter(Ke=>Ke!==k);if(Xe.length){for(const Ke of Xe)Il.current.add(Ke);Ol(Ke=>Array.from(new Set([...Ke,...Xe])));try{const Ke=typeof((ne=Oe==null?void 0:Oe[k])==null?void 0:ne.total)=="number"?Number(Oe[k].total):0;let nn="",Mt=-1;for(const We of Xe){const jt=typeof((Ce=Oe==null?void 0:Oe[We])==null?void 0:Ce.total)=="number"?Number(Oe[We].total):0;jt>Mt&&(nn=We,Mt=jt)}nn&&Mt>Math.max(Ke*3,Ke+20)&&(ni.current=nn,Bs(nn))}catch{}}}catch{}sn(!0),Xt({ts:kt(),kind:"info",title:`Attached to run ${k}`,data:{run_id:k}}),D=!0}catch(me){const ge=String((me==null?void 0:me.message)||me||"unknown error");tn(ge),Xt({ts:kt(),kind:"error",title:"Connection error",preview:_t(ge),data:{error:ge}}),sn(!1)}finally{en(!1)}if(!D||M.signal.aborted)return;(async()=>{let me=250;for(;!M.signal.aborted;){try{const ge=await Ud(k,{after:_r.current,signal:M.signal});await Ie.stream_ledger(k,{after:ge,on_step:Ne=>nc(Ne,k),signal:M.signal})}catch(ge){if(M.signal.aborted)break;const Ne=String((ge==null?void 0:ge.message)||ge||"stream error");Xt({ts:kt(),kind:"error",title:"Ledger stream error (will retry)",preview:_t(Ne),data:{error:Ne}})}if(M.signal.aborted)break;await new Promise(ge=>setTimeout(ge,me)),me=Math.min(5e3,Math.floor(me*1.6))}})()}async function nl(){const g=Qa,k=(g==null?void 0:g.kind)==="bundle"?g.flow_id:(g==null?void 0:g.kind)==="default"?"@default":"",M=(g==null?void 0:g.kind)==="bundle"?g.bundle_id:"";if(!g){const D="Select a workflow first (Launch → pick a workflow).";return tn(D),D}tn(""),en(!0);try{let D={};const V=L.trim();if(V)try{if(D=JSON.parse(V),typeof D!="object"||D===null||Array.isArray(D))throw new Error("input_data must be a JSON object")}catch(ge){const Ne=`Invalid input_data JSON: ${String((ge==null?void 0:ge.message)||ge)}`;return tn(Ne),Ne}for(const[ge,Ne]of Object.entries(D)){if(typeof Ne!="string")continue;const Oe=Ne.trim();Oe?D[ge]=Oe:delete D[ge]}const H=(ko||[]).find(ge=>ge&&typeof ge=="object"&&ge.id==="prompt"),q=H&&typeof H=="object"&&Object.prototype.hasOwnProperty.call(H,"default"),ne=D==null?void 0:D.prompt,Ce=typeof ne=="string"?ne.trim():"";if(H&&!q&&!Ce){const ge="Missing required input_data.prompt";return tn(ge),ge}const me=await Ie.start_run(k,D,{...M?{bundle_id:M}:{},...g.kind==="default"?{interface:g.interface}:{},session_id:String(W||"").trim()||null});return p(me),f(me),gr(""),await ma(me),qs(),null}catch(D){const V=String((D==null?void 0:D.message)||D||"start failed");return tn(V),V}finally{en(!1)}}async function Wd(){if(tt([]),Ye(null),!Ue.available){tt([Ue.reason]);return}const g=q1(Be,{choice:Qa,bundle_ref_for:k=>{var M;return((M=$t.find(D=>D.bundle_id===k))==null?void 0:M.bundle_ref)||""},input_data:ut,email_usable:gn.email_usable},Le.current);if(!g.ok){tt(g.errors);return}Re(!0);try{const k=await Ie.automations_client().createAutomation(g.body);Le.current.reset(),xe([]),gt(eg),Xt({ts:kt(),kind:"info",title:"Automation created",preview:_t(`${g.body.title} · ${k.automation_id}`)}),t("automations"),await gn.refresh(),await gn.select(k.automation_id)}catch(k){const M=(k&&typeof k=="object"&&typeof k.code=="string"?k:null)||{status:0,code:"client_error",message:String((k==null?void 0:k.message)||k||"Create failed")};Ye(M)}finally{Re(!1)}}async function qd(){if(gr(""),he==="automate"){await Wd();return}const g=await nl();if(g){gr(g);return}Oi("overview"),t("observe")}async function Ch(g){if(Mn("skills",void 0),!!g){if(g.kind==="default"){ze(g.interface),T(""),C(""),Y(null);return}ze(""),T(g.bundle_id),C(g.flow_id),Pa(g.flow_id),await Pd(g.bundle_id)}}async function Hd(g){const[k,M]=await Promise.all([Ie.get_run(g),Ie.get_run_input_data(g)]),D=Z1(k,M);await Ch(D.choice),P(JSON.stringify(D.input_data,null,2)),gt(D.form),xe([`Recreating the legacy schedule ${Lt(g,14)} as an automation. The legacy schedule keeps running until you suspend it.`,...D.notes]),Le.current.reset(),ye("automate"),t("launch")}async function No(g,k){const M=String(g||"").trim();if(!M)return;if(dt){Xn(`Still attaching — retry in a moment (${Lt(M,14)})`,2500);return}tn(""),S("");const D=String((k==null?void 0:k.root_run_id)||M).trim()||M;p(D),f(M),await ma(M)}m.useEffect(()=>{const g=String(y||"").trim();if(!g)return;let k=!1;return(async()=>{try{if(E||await el({open_modal_if_needed:!0}),k)return;Oi("overview"),t("observe");const M=await Ie.find_run(g);if(k)return;if(M===null){vu(),S(g);return}await No(g),ui()}catch(M){k||tn(String((M==null?void 0:M.message)||M||"Failed to attach run from URL"))}finally{k||w("")}})(),()=>{k=!0}},[y]);function vu(){var g,k;xi.current&&xi.current.abort(),xi.current=null,Cs.current&&Cs.current.abort(),Cs.current=null,Ui.current=0,Xc(""),f(""),p(""),Qo.current={},ti.current={},Yc.current={},Il.current=new Set,Ol([]),go.current="",ni.current="",Bs(""),yo.current={},rr(""),or.current&&window.clearTimeout(or.current),or.current=null,sr.current&&window.clearTimeout(sr.current),sr.current=null,sn(!1),en(!1),Wn(!1),_r.current=0,(g=hi.current)==null||g.reset(),(k=mi.current)==null||k.reset(),Ds.current={scanned:0,found:null},er([]),Xr([]),wo.current=new Set,pr(null),cd([]),ud({}),Xo(""),Fr.current="",za({}),Zo({}),Ba.current=[],Gc(Date.now()),Xn("",-1),tn(""),Br(!1),Ur(""),ot([]),Pt(null),ir(""),pi(""),ke(!1),zt(!1),pn(""),_s(""),br(""),Vo([]),Ic(!1),Pc(""),Dc(""),zc(!1),Go("")}m.useEffect(()=>{ot([]),Pt(null),ir(""),pi(""),ke(!1),zt(!1),pn(""),_s(""),br(""),Vo([]),Ic(!1),Pc(""),Dc(""),zc(!1),Go("")},[c]),m.useEffect(()=>{ps==="chat"&&c.trim()&&E&&ju()},[ps,c,E,de==null?void 0:de.workflow_id]);async function Vd(g,k,M){const D=String(g||"").trim();if(!D)return tn("Missing run_id"),"Missing run_id";tn("");try{const V={},H=String((M==null?void 0:M.reason)||"").trim();H&&(V.reason=H),await Ie.submit_command({command_id:xs(),run_id:D,type:k,payload:V,client_id:"web_pwa"}),Xt({ts:kt(),kind:"info",title:`${k} submitted`,preview:H?`reason: ${H}`:"",data:{run_id:D,type:k,reason:H}});try{if(D===c.trim()){const q=await Ie.get_run(D);pr(q)}}catch{}return qs(Ie,{force:!0}),window.setTimeout(()=>void qs(Ie,{force:!0}),900),window.setTimeout(()=>void qs(Ie,{force:!0}),2400),null}catch(V){const H=String((V==null?void 0:V.message)||V||`${k} failed`);return tn(H),H}}async function xu(g,k){return Vd(c.trim(),g,k)}async function Eh(g,k="Stopped from AbstractObserver"){const M=String(g||"").trim();if(!M||!window.confirm(`Cancel run ${Lt(M,24)}?`))return;await Vd(M,"cancel",{reason:k})||Xn("Cancel submitted",2)}async function ur(){var M;const g=c.trim();if(!g){tn("Select a run first.");return}if(!E){tn("Connect to the gateway first.");return}if(ft)return;const k=String(((M=de==null?void 0:de.waiting)==null?void 0:M.reason)||"").trim().toLowerCase()||String(Qn||"").trim().toLowerCase();if(!Gs||$r||Yi||Co.toLowerCase()!=="waiting"||k!=="until"){tn("This run is not a scheduled wait that can be triggered now.");return}tn(""),Wn(!0);try{const D={payload:{mode:"run_now",requested_at:kt()}},V=String(Rs||"").trim();V&&(D.wait_key=V),await Ie.submit_command({command_id:xs(),run_id:g,type:"resume",payload:D,client_id:"web_pwa"}),Xt({ts:kt(),kind:"info",title:"Scheduled run triggered",preview:_t(`run ${g}`),data:{run_id:g,until:Er||null}});try{const H=await Ie.get_run(g);pr(H)}catch{}}catch(D){tn(String((D==null?void 0:D.message)||D||"Failed to trigger scheduled run"))}finally{Wn(!1)}}async function Hs(g){const k=c.trim();if(!k)return tn("Missing run_id"),"Missing run_id";if($n)return"Schedule update already in progress";const M=String(g.interval||"").trim();if(!/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.test(M)){const V="Invalid interval (expected like '20m', '1h', '0.5s', '250ms')";return _i(V),V}_i(""),tn(""),zs(!0),en(!0);try{await Ie.submit_command({command_id:xs(),run_id:k,type:"update_schedule",payload:{interval:M,apply_immediately:g.apply_immediately!==!1},client_id:"web_pwa"}),Xt({ts:kt(),kind:"info",title:"Schedule updated",preview:_t(`interval: ${M}`),data:{interval:M},run_id:k});try{const V=await Ie.get_run(k);pr(V)}catch{}return null}catch(V){const H=String((V==null?void 0:V.message)||V||"update_schedule failed");return _i(H),tn(H),H}finally{en(!1),zs(!1)}}async function $h(g){const k=c.trim();if(!k)return tn("Missing run_id"),"Missing run_id";if(Lr)return"Compaction already in progress";const M=typeof(g==null?void 0:g.preserve_recent)=="number"?g.preserve_recent:hs,D=Math.max(0,Math.min(500,Math.floor(Number.isFinite(M)?M:6))),V=(g==null?void 0:g.compression_mode)||fo,H=String((g==null?void 0:g.focus)??Ra??"").trim();ms(""),tn(""),Ir(!0),en(!0);try{const q={preserve_recent:D,compression_mode:V};return H&&(q.focus=H),await Ie.submit_command({command_id:xs(),run_id:k,type:"compact_memory",payload:q,client_id:"web_pwa"}),Xt({ts:kt(),kind:"info",title:"Compaction requested",preview:_t(`mode: ${V} • preserve_recent: ${D}`),data:q,run_id:k}),null}catch(q){const ne=String((q==null?void 0:q.message)||q||"compact_memory failed");return ms(ne),tn(ne),ne}finally{en(!1),Ir(!1)}}async function Ah(){const g=c.trim();if(!g){Ur("Missing run_id");return}if(!ea){Ur(""),Br(!0);try{const k=n.maintenance_ai_provider.trim(),M=n.maintenance_ai_model.trim();await Ie.generate_run_summary(g,{provider:k||void 0,model:M||void 0,include_subruns:!0}),Xt({ts:kt(),kind:"info",title:"Summary generation requested",preview:_t(`run ${g}`)})}catch(k){Ur(String((k==null?void 0:k.message)||k||"Failed to generate summary"))}finally{Br(!1)}}}async function Th(){const g=c.trim();if(!g){pi("Select a run first.");return}if(!E){pi("Connect to the gateway first.");return}const k=_o.trim();if(!k||be)return;if(Hn.voice_ptt_busy){gi("Wait for transcription to finish.");return}pi(""),gi(""),ke(!0);const D={id:`local:${xs()}`,role:"user",content:k,ts:kt()};ot(V=>[...V,D]),ir("");try{const V=u1(et,D),H=n.maintenance_ai_provider.trim(),q=n.maintenance_ai_model.trim(),ne=await Ie.run_chat(g,{provider:H||void 0,model:q||void 0,include_subruns:!0,messages:V}),Ce=String((ne==null?void 0:ne.answer)||"").trim()||"(empty response)",me=String((ne==null?void 0:ne.generated_at)||"").trim()||kt();Pt((ne==null?void 0:ne.history)??null),ot(ge=>[...ge,{id:`local:${xs()}`,role:"assistant",content:Ce,ts:me}])}catch(V){const H=Z2(V);pi(H),ot(q=>[...q,{id:`local:${xs()}`,role:"assistant",content:`(error: ${H})`,ts:kt(),local_error:!0}])}finally{ke(!1)}}function Mh(g){const k=String(g.id||g.ts||"").trim(),M=String(g.content||"").trim();!k||!M||(gi(""),Hn.toggle_tts(k,M))}function Rh(g){const k=String(g.id||g.ts||"").trim(),M=Hn.tts_playback;return!k||!M.key||M.key!==k?"idle":M.status}function bu(g){if(!et.length)return;const k=c.trim(),M=k?`Run ${k}`:"Chat",D=Fk(et.map(V=>({role:V.role,content:V.content,ts:V.ts})),{heading:M});if(g==="download"){const V=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),H=`abstractobserver-chat-${ap(k||"run")}-${V}.md`;zk({filename:H,text:D,mime:"text/markdown;charset=utf-8"});return}(async()=>{const V=await $c(D);qe(V?"copied":"failed"),window.setTimeout(()=>qe("idle"),900)})()}async function ju(){const g=typeof(de==null?void 0:de.workflow_id)=="string"?String(de.workflow_id).trim():"";if(!g){Vo([]);return}if(E&&!jl){Pc(""),Ic(!0);try{const k=await Ie.list_runs({limit:200,workflow_id:g,root_only:!0}),M=Array.isArray(k==null?void 0:k.items)?k.items:[],D=[];for(const me of M){const ge=typeof(me==null?void 0:me.run_id)=="string"?String(me.run_id).trim():"";if(!ge)continue;const Ne=typeof(me==null?void 0:me.ledger_len)=="number"?Number(me.ledger_len):0;D.push({run_id:ge,ledger_len:Number.isFinite(Ne)?Ne:0})}if(!D.length){Vo([]);return}const V=400,H=D.map(me=>({run_id:me.run_id,after:Math.max(0,(me.ledger_len||0)-V)})),q=await Ie.get_ledger_batch({runs:H,limit:V}),ne=[],Ce=new Set;for(const me of D){const ge=q!=null&&q.runs&&typeof q.runs=="object"?q.runs[me.run_id]:null,Ne=Array.isArray(ge==null?void 0:ge.items)?ge.items:[];for(const Oe of Ne){const He=Oe==null?void 0:Oe.effect;if(!He||typeof He!="object"||String(He.type||"")!=="emit_event")continue;const Xe=He.payload;if(!Xe||typeof Xe!="object"||String(Xe.name||"")!=="abstract.chat.thread")continue;const Ke=Xe.payload;if(!Ke||typeof Ke!="object")continue;const nn=typeof Ke.thread_id=="string"?String(Ke.thread_id).trim():"";if(!nn||Ce.has(nn))continue;Ce.add(nn);const Mt=typeof Ke.created_at=="string"?String(Ke.created_at):"",We=typeof Ke.title=="string"?String(Ke.title):"",jt=typeof Ke.workflow_id=="string"?String(Ke.workflow_id):g,mn=typeof Ke.run_id=="string"?String(Ke.run_id):me.run_id,xn=typeof Ke.provider=="string"?String(Ke.provider):"",Js=typeof Ke.model=="string"?String(Ke.model):"",dr=typeof Ke.message_count=="number"?Number(Ke.message_count):null,di=Ke.chat_artifact,al=di&&typeof di=="object"&&typeof di.$artifact=="string"?String(di.$artifact):"";al&&ne.push({thread_id:nn,created_at:Mt,title:We||`Chat ${nn.slice(0,8)}`,run_id:mn,workflow_id:jt,message_count:dr,provider:xn,model:Js,artifact_id:al})}}ne.sort((me,ge)=>String(ge.created_at||"").localeCompare(String(me.created_at||""))),Vo(ne)}catch(k){Pc(String((k==null?void 0:k.message)||k||"Failed to load saved discussions"))}finally{Ic(!1)}}}async function Gd(){const g=c.trim();if(!g){pn("Select a run first.");return}if(!E){pn("Connect to the gateway first.");return}if(et.length&&!Zn){pn(""),zt(!0);try{const k=n.maintenance_ai_provider.trim(),M=n.maintenance_ai_model.trim(),D=await Ie.save_chat_thread(g,{provider:k||void 0,model:M||void 0,include_subruns:!0,messages:et.map(q=>({role:q.role,content:q.content,ts:q.ts}))}),V=typeof(D==null?void 0:D.created_at)=="string"?String(D.created_at):kt();_s(V);try{const q=JSON.stringify(et.map(ne=>({role:ne.role,content:ne.content,ts:ne.ts})));br(q)}catch{br("1")}typeof(D==null?void 0:D.thread_id)=="string"&&String(D.thread_id).trim()&&Dc(String(D.thread_id).trim());const H=!!(D!=null&&D.duplicate);Xn(H?"Already saved":"Saved discussion",2),await ju()}catch(k){pn(String((k==null?void 0:k.message)||k||"Failed to save discussion"))}finally{zt(!1)}}}async function Lh(){const g=String(id||"").trim();if(!g)return;const k=Ho.find(V=>String(V.thread_id||"").trim()===g)||null;if(!k){Go("Saved discussion not found (refresh list).");return}if(!E){Go("Connect to the gateway first.");return}if(Fc)return;const M=et.length>0,D=(()=>{if(!M)return!1;if(!Ns)return!0;try{return JSON.stringify(et.map(H=>({role:H.role,content:H.content,ts:H.ts})))!==Ns}catch{return!0}})();if(!(M&&D&&!window.confirm("Replace the current chat with the selected saved discussion? Unsaved changes will be lost."))){Go(""),zc(!0);try{const H=await(await Ie.download_run_artifact_content(k.run_id,k.artifact_id)).text(),q=JSON.parse(H),ne=Array.isArray(q==null?void 0:q.messages)?q.messages:[],Ce=typeof(q==null?void 0:q.created_at)=="string"?String(q.created_at):String(k.created_at||""),me=[];for(let ge=0;ge<ne.length;ge++){const Ne=ne[ge];if(!Ne||typeof Ne!="object")continue;const Oe=String(Ne.role||"").trim()==="assistant"?"assistant":"user",He=typeof Ne.content=="string"?String(Ne.content):"";if(!He.trim())continue;const Xe=typeof Ne.ts=="string"?String(Ne.ts):Ce||kt();me.push({id:`thread:${g}:${ge}`,role:Oe,content:He.trim(),ts:Xe})}ot(me),Pt(null),ir(""),pi(""),pn(""),_s(Ce||"");try{const ge=JSON.stringify(me.map(Ne=>({role:Ne.role,content:Ne.content,ts:Ne.ts})));br(ge)}catch{br("1")}Xn("Loaded discussion",2)}catch(V){Go(String((V==null?void 0:V.message)||V||"Failed to load saved discussion"))}finally{zc(!1)}}}async function sc(g){const k=c.trim(),M=String((qt==null?void 0:qt.wait_key)||"").trim();if(!k||!M){tn("No active wait to resume");return}if(String((qt==null?void 0:qt.reason)||"").trim()==="subworkflow"){tn("This run is waiting on a subworkflow; attach to the child run instead of resuming manually.");return}tn(""),Wn(!0);try{await Ie.submit_command({command_id:xs(),run_id:k,type:"resume",payload:{wait_key:M,payload:g||{}},client_id:"web_pwa"}),Xt({ts:kt(),kind:"info",title:"Resume submitted",preview:_t(`wait_key: ${M}`),data:{wait_key:M,payload:g||{}}}),rr(M);try{const D=await Ie.get_run(k);pr(D)}catch{}qs(Ie,{force:!0}),window.setTimeout(()=>void qs(Ie,{force:!0}),900),window.setTimeout(()=>void qs(Ie,{force:!0}),2400),sr.current&&window.clearTimeout(sr.current),sr.current=window.setTimeout(()=>{rr(D=>D===M?"":D)},2e3)}catch(D){tn(String((D==null?void 0:D.message)||D||"resume failed"))}finally{Wn(!1)}}async function Kd(g){if(!Si){tn("No worker configured");return}if(!ft){tn(""),Wn(!0);try{const k=[];for(const M of g){const D=await Si.call_tool(M);k.push(D)}await sc({mode:"executed",results:k})}finally{Wn(!1)}}}const Ki=m.useMemo(()=>nd(qt),[qt]),Rs=String((qt==null?void 0:qt.wait_key)||"").trim(),Qn=String((qt==null?void 0:qt.reason)||"").trim(),Er=typeof(qt==null?void 0:qt.until)=="string"?String(qt.until):"",Co=typeof(de==null?void 0:de.status)=="string"?String(de.status):"",Yi=!!(de!=null&&de.paused),$r=Co==="completed"||Co==="failed"||Co==="cancelled",Ih=Qn==="until"&&!!Er,_a=!$r&&kC(gs)&&(!!Rs||Ih),Ji=Qn==="user",Yd=Qn==="event"?Nf(f3(Rs)):"",Oh=Qn==="event"&&Yd==="abstract.ask",Jd=Ki.length>0,Xd=_a&&Rs&&(Ji||Oh||Jd)&&rd!==Rs&&e!=="board",Eo=typeof((Hh=qt==null?void 0:qt.details)==null?void 0:Hh.sub_run_id)=="string"?String(qt.details.sub_run_id):"",Xi={run_id:c.trim(),workflow_id:typeof(de==null?void 0:de.workflow_id)=="string"?String(de.workflow_id):null,status:Co,created_at:typeof(de==null?void 0:de.created_at)=="string"?String(de.created_at):null,updated_at:typeof(de==null?void 0:de.updated_at)=="string"?String(de.updated_at):null,session_id:typeof(de==null?void 0:de.session_id)=="string"?String(de.session_id):null,current_node:typeof(de==null?void 0:de.current_node)=="string"?String(de.current_node):null},ws=cn.slice(-10).map(g=>{var k,M,D,V,H,q;return{cursor:g.cursor,node_id:String(((k=g.record)==null?void 0:k.node_id)||"").trim(),status:String(((M=g.record)==null?void 0:M.status)||"").trim(),effect_type:String(((V=(D=g.record)==null?void 0:D.effect)==null?void 0:V.type)||"").trim(),ts:String(((H=g.record)==null?void 0:H.ended_at)||((q=g.record)==null?void 0:q.started_at)||"").trim(),summary:ub(g.record)}}),Ph=Vg(qt,Ki),$_=ob(qt,Ki),rc=ab(qt,ut),Vn=rc.text,A_=rc.runtime_metadata,Ge=String((qt==null?void 0:qt.prompt)||"").trim(),pa=uC(ut,6),Zd=!!(Ge&&sb(Ge)),Su=!!(Ge&&!Zd),T_=Su?"Question from workflow":Vn&&Vn!==Ge?"Closest prior user request":"Request context",ic=hC(ut,L),ku=!!L.trim(),Vs=de!=null&&de.schedule&&typeof de.schedule=="object"?de.schedule:null,ga=typeof(Vs==null?void 0:Vs.interval)=="string"?String(Vs.interval).trim():"",Dh=typeof(Vs==null?void 0:Vs.share_context)=="boolean"?!!Vs.share_context:null,Qd=typeof(Vs==null?void 0:Vs.repeat_count)=="number"?Number(Vs.repeat_count):null,Gs=!!(de!=null&&de.is_scheduled)||!!Vs,oc=Gs&&!!ga,ls=Co==="running"&&!Yi?"Pause":"Resume",Hr=Gs?Yi?"resume":"pause":ls==="Pause"?"pause":"resume",$o=Gs?!c.trim()||dt||ft||$r:!c.trim()||dt||ft||$r||Hr==="resume"&&!Yi,Fh=c.trim()?$r?"The schedule has ended.":null:"No run selected.",zh=Gs&&!Yi&&!$r&&!dt&&!ft&&Co.toLowerCase()==="waiting"&&(String(((Vh=de==null?void 0:de.waiting)==null?void 0:Vh.reason)||"").trim().toLowerCase()==="until"||Qn==="until")&&!!String(Er||"").trim(),zn=(rf=de==null?void 0:de.limits)==null?void 0:rf.tokens,sl=typeof(zn==null?void 0:zn.pct)=="number"?Number(zn.pct):null,ai=zn==null?void 0:zn.estimated_used,Bh=(zn==null?void 0:zn.max_input_tokens)??(zn==null?void 0:zn.max_tokens),Uh=m.useMemo(()=>{const g=Ds.current;cn.length<g.scanned&&(g.scanned=0,g.found=null);for(let k=g.scanned;k<cn.length;k++){const M=cn[k],D=M==null?void 0:M.record;if(!D)continue;const V=am(D);if((V&&V.name?Nf(V.name):"")!=="abstract.summary")continue;const q=V!=null&&V.payload&&typeof V.payload=="object"?V.payload:{},ne=typeof(q==null?void 0:q.text)=="string"?String(q.text):"";ne.trim()&&(g.found={cursor:M.cursor,ts:String((D==null?void 0:D.ended_at)||(D==null?void 0:D.started_at)||""),text:ne,provider:typeof(q==null?void 0:q.provider)=="string"?String(q.provider):void 0,model:typeof(q==null?void 0:q.model)=="string"?String(q.model):void 0,generated_at:typeof(q==null?void 0:q.generated_at)=="string"?String(q.generated_at):void 0,source:q==null?void 0:q.source})}return g.scanned=cn.length,g.found},[cn]);m.useEffect(()=>{ni.current=zr.trim()},[zr]),m.useEffect(()=>{const g=c.trim(),k=Eo.trim();if(!(De&&Qn==="subworkflow"&&!!k&&k!==g)){go.current="",zr.trim()&&Bs("");return}go.current!==k&&(go.current=k,ni.current=k,Bs(k))},[De,c,Qn,Eo,zr]),m.useEffect(()=>{Vc({})},[N]);const ef=m.useMemo(()=>((Array.isArray(G==null?void 0:G.entrypoints)?G==null?void 0:G.entrypoints:[])||[]).map(k=>String((k==null?void 0:k.flow_id)||"").trim()).filter(Boolean),[G]),Ni=m.useMemo(()=>{const g=String((de==null?void 0:de.workflow_id)||"").trim();return De&&Gs?g:""},[De,Gs,de==null?void 0:de.workflow_id]),Wh=m.useMemo(()=>{var q;if(!De||!c.trim()||!Ni.trim())return vi;const g=String((de==null?void 0:de.status)||"").trim().toLowerCase(),k=String((de==null?void 0:de.current_node)||"").trim();if(g!=="waiting"&&g!=="running"||!k)return vi;const M=Nr(c.trim(),k);if(!M)return vi;const D=String(Qn||((q=de==null?void 0:de.waiting)==null?void 0:q.reason)||"").trim().toLowerCase(),V=typeof(gs==null?void 0:gs.node_id)=="string"?String(gs.node_id).trim():"",H=typeof(gs==null?void 0:gs.status)=="string"?String(gs.status).trim().toLowerCase():"";return g==="waiting"&&D==="until"||!vi.trim()||(H==="waiting"||H==="running")&&!V?M:vi},[De,c,Ni,de==null?void 0:de.status,de==null?void 0:de.current_node,(of=de==null?void 0:de.waiting)==null?void 0:of.reason,Qn,vi,gs]),M_=m.useMemo(()=>{const g={},k=c.trim(),M=(D,V)=>{if(!V)return;const H=typeof(V==null?void 0:V.node_id)=="string"?String(V.node_id).trim():"";if(!H)return;const q=Nr(D,H);if(!q)return;const ne=String((V==null?void 0:V.ended_at)||(V==null?void 0:V.started_at)||"").trim(),Ce=Nn(ne);Ce!==null&&(g[q]=Math.max(g[q]||0,Ce))};for(const D of cn)D&&D.record&&M(k,D.record);for(const D of ss)D&&D.record&&M(String(D.run_id||"").trim(),D.record);return g},[cn,ss,c,zi]);m.useEffect(()=>{var M;if(!De||!c.trim()||!Ni.trim())return;const g=String((de==null?void 0:de.current_node)||"").trim();!g||String(((M=de==null?void 0:de.waiting)==null?void 0:M.reason)||"").trim()==="subworkflow"||tl(Nr(c.trim(),g))},[De,c,Ni,de==null?void 0:de.current_node,(Lo=de==null?void 0:de.waiting)==null?void 0:Lo.reason]),m.useEffect(()=>{const g=String((ys==null?void 0:ys.flow_id)||"").trim();g&&(po.trim()||Pa(g))},[ys,po]),m.useEffect(()=>{const g=Ni.trim(),k=N.trim(),M=po.trim();if(g){let V=!1;return Fa(!0),Dr(""),Ie.get_workflow_flow(g).then(H=>{if(V)return;const q=H==null?void 0:H.flow;Da(q&&typeof q=="object"?q:null)}).catch(H=>{V||(Da(null),Dr(String((H==null?void 0:H.message)||H||"Failed to load workflow flow")))}).finally(()=>{V||Fa(!1)}),()=>{V=!0}}if(!k||!M){Da(null),Dr(""),Fa(!1);return}let D=!1;return Fa(!0),Dr(""),Ie.get_bundle_flow(k,M).then(V=>{if(D)return;const H=V==null?void 0:V.flow,q=H&&typeof H=="object"?H:null;Da(q),q&&Vc(ne=>({...ne,[M]:q}))}).catch(V=>{D||(Da(null),Dr(String((V==null?void 0:V.message)||V||"Failed to load flow")))}).finally(()=>{D||Fa(!1)}),()=>{D=!0}},[Ni,N,po,Ie]),m.useEffect(()=>{const g=N.trim();if(!Jo||!g||!Fi)return;let k=!1;const M=3,D=me=>{const ge=Array.isArray(me==null?void 0:me.nodes)?me.nodes:[],Ne=[];for(const Oe of ge){const He=Oe!=null&&Oe.data&&typeof Oe.data=="object"?Oe.data:{};if(String((He==null?void 0:He.nodeType)||(Oe==null?void 0:Oe.type)||"").trim()!=="subflow")continue;const Ke=(He==null?void 0:He.subflowId)||(He==null?void 0:He.flowId),nn=typeof Ke=="string"?Ke.trim():"";nn&&Ne.push(nn.includes(":")?nn.split(":",2)[1]:nn)}return Ne},V=new Set,H=new Set,q=(me,ge)=>{if(!(!me||ge>=M))for(const Ne of D(me)){const Oe=String(Ne||"").trim();if(!Oe||V.has(Oe))continue;V.add(Oe),H.add(Oe);const He=Rl[Oe];He&&q(He,ge+1)}};q(Fi,0);const ne=Array.from(H).filter(me=>!Rl[me]).slice(0,20);return ne.length?((async()=>{for(const me of ne){if(k)return;try{const ge=await Ie.get_bundle_flow(g,me),Ne=ge==null?void 0:ge.flow,Oe=Ne&&typeof Ne=="object"?Ne:null;if(!Oe)continue;Vc(He=>He[me]?He:{...He,[me]:Oe})}catch{}}})(),()=>{k=!0}):void 0},[Jo,N,Fi,Rl,Ie]);const ac=m.useMemo(()=>{const k=(Array.isArray(G==null?void 0:G.flows)?G==null?void 0:G.flows:[]).map(M=>String(M||"").trim()).filter(Boolean);return k.length?Array.from(new Set(k)).sort():Array.from(new Set(ef)).sort()},[G,ef]);m.useEffect(()=>{$r&&vi.trim()&&(Xo(""),Fr.current="")},[$r,c,vi]),m.useEffect(()=>{const g=zr.trim(),k=c.trim();if(!(De&&!!g&&g!==k)){Cs.current&&Cs.current.abort(),Cs.current=null,Ui.current=0,Ed&&Xc("");return}if(Ed===g)return;Cs.current&&Cs.current.abort();const D=new AbortController;Cs.current=D,Ui.current=0,Xc(g),Xt({ts:kt(),kind:"info",title:`Following run ${g} (status/events)`});let V=250;return(async()=>{for(;!D.signal.aborted;){try{await Ie.stream_ledger(g,{after:Ui.current,on_step:q=>kh(g,q),signal:D.signal});return}catch(q){if(D.signal.aborted)break;const ne=String((q==null?void 0:q.message)||q||"stream error");Xt({ts:kt(),kind:"error",title:"Child ledger stream error (will retry)",preview:_t(ne),data:{child_run_id:g,error:ne}})}if(D.signal.aborted)break;await new Promise(q=>setTimeout(q,V)),V=Math.min(5e3,Math.floor(V*1.6))}})(),()=>{D.abort()}},[De,zr,c,Ie,Ed]),m.useEffect(()=>{if(!De||!c.trim())return;let g=!1;const k=async()=>{if(!g&&!Jc.current&&zi.length&&!(ct.current>Date.now())){Jc.current=!0;try{const D=zi.map(ne=>String(ne||"").trim()).filter(Boolean);if(!D.length)return;const V=D.map(ne=>({run_id:ne,after:Number(yo.current[ne]||0)})),H=await Ie.get_ledger_batch({runs:V,limit:200}),q=H&&typeof H=="object"?H.runs:{};for(const ne of D){if(g)return;const Ce=q&&typeof q=="object"?q[ne]:null,me=Array.isArray(Ce==null?void 0:Ce.items)?Ce.items:[],ge=typeof(Ce==null?void 0:Ce.next_after)=="number"?Ce.next_after:Number(yo.current[ne]||0),Ne=Number(yo.current[ne]||0);for(let Oe=0;Oe<me.length;Oe++){const He=me[Oe];Nh(ne,{cursor:Ne+Oe+1,record:He})}yo.current[ne]=ge}}catch(D){if(g)return;Xt({ts:kt(),kind:"error",title:"Subrun digest poll failed",preview:_t(String((D==null?void 0:D.message)||D||""))})}finally{Jc.current=!1}}};k();const M=window.setInterval(()=>void k(),2e3);return()=>{g=!0,window.clearInterval(M),Jc.current=!1}},[De,c,zi,Ie]);const lc=m.useMemo(()=>Pi?Sl.filter(p3):Sl,[Pi,Sl]),Gn=m.useMemo(()=>{const g=c.trim(),k=[];for(const M of cn)!M||!M.record||k.push({run_id:g,cursor:M.cursor,record:M.record});for(const M of ss)!M||!M.record||k.push({run_id:String(M.run_id||"").trim(),cursor:M.cursor,record:M.record});return k},[cn,ss,c]),Ht=m.useMemo(()=>{var k,M,D;const g={};for(const V of Gn){const H=String(V.run_id||((k=V.record)==null?void 0:k.run_id)||"").trim();!H||String(((D=(M=V.record)==null?void 0:M.effect)==null?void 0:D.type)||"").trim()!=="llm_call"||(g[H]=(g[H]||0)+1)}return g},[Gn]),cs=m.useMemo(()=>{const g=zr.trim();if(g)return g;let k="",M=-1;for(const[D,V]of Object.entries(Ht))V>M&&(k=D,M=V);return k||c.trim()},[Ht,zr,c]),vn=(j_.trim()||cs).trim(),es=m.useMemo(()=>{var V;const g=new Set,k=c.trim(),M=zr.trim();k&&g.add(k),M&&g.add(M);for(const H of zi){const q=String(H||"").trim();q&&g.add(q)}for(const H of Gn){const q=String(H.run_id||((V=H.record)==null?void 0:V.run_id)||"").trim();q&&g.add(q)}const D=Array.from(g);return D.sort((H,q)=>k&&H===k&&q!==k?-1:k&&q===k&&H!==k?1:M&&H===M&&q!==M?-1:M&&q===M&&H!==M?1:H<q?-1:H>q?1:0),D},[c,zr,zi,Gn]),Ks=m.useMemo(()=>Lk(Gn,{run_id:vn}),[Gn,vn]),Rn=m.useMemo(()=>{const g=c.trim();return g&&(hn.find(k=>String(k.run_id||"").trim()===g)||Un.find(k=>String(k.run_id||"").trim()===g))||null},[hn,Un,c]),Ln=String((de==null?void 0:de.status)||(Rn==null?void 0:Rn.status)||"").trim(),cc=String(Qn||((Gh=de==null?void 0:de.waiting)==null?void 0:Gh.reason)||(Rn==null?void 0:Rn.waiting_reason)||"").trim().toLowerCase(),Ao=!!(de!=null&&de.is_scheduled||Rn!=null&&Rn.is_scheduled),uc=!!(de!=null&&de.paused||Rn!=null&&Rn.paused),Nu=Ao&&Ln.toLowerCase()==="waiting",rl=Nu&&cc==="until",Ys=Nn(Er),dc=rl&&Ys!==null?uw(Ys-Date.now()):"",Ci=aC(de),Vr=Ao&&uc?"Suspended":Nu?"Scheduled":Um({status:Ln,paused:uc,stop_reason:Ci});async function fc(){if(E){Us(!0),ra("");try{const g=Wa,k=g==="session"?String(ia||kr||W||"").trim():"",M=g==="run"?String(si||c||"").trim():"",D=vC(qa),V=ar.length?ar.join(","):"",H=xC(Hi),q=Math.max(0,jr)*bm,ne=await Ie.search_artifacts({scope:g,session_id:k||void 0,run_id:M||void 0,query:os||void 0,artifact_kind:V||void 0,created_after:D||void 0,include_stats:!0,limit:bm,offset:q,order_by:H.order_by,order:H.order}),Ce=[],me=new Set;for(const Xe of Array.isArray(ne==null?void 0:ne.items)?ne.items:[]){const Ke=gC(Xe,"search");!Ke||me.has(Ke.artifact_id)||(me.add(Ke.artifact_id),Ce.push(Ke))}const ge=ne!=null&&ne.stats&&typeof ne.stats=="object"?ne.stats:{},Ne=Number((ge==null?void 0:ge.total)??(ne==null?void 0:ne.total)??Ce.length),Oe=hw(ne);let He=Oe;if(ar.length)try{const Xe=await Ie.search_artifacts({scope:g,session_id:k||void 0,run_id:M||void 0,query:os||void 0,created_after:D||void 0,include_stats:!0,limit:1,offset:0,order_by:H.order_by,order:H.order});He=hw(Xe)}catch{He=Oe}Fl(Number.isFinite(Ne)?Math.max(0,Ne):Ce.length),na(Number((ge==null?void 0:ge.total_bytes)??(ge==null?void 0:ge.byte_total)??0)||0),Sn(Oe),qi(He),Ua(Ce),ri(Xe=>{var Ke;return Xe&&Ce.some(nn=>nn.artifact_id===Xe)?Xe:((Ke=Ce[0])==null?void 0:Ke.artifact_id)||""})}catch(g){ra(String((g==null?void 0:g.message)||g||"Failed to load artifacts")),Ua([]),Fl(0),na(0),Sn({}),qi({}),ri("")}finally{Us(!1)}}}async function Cu(){if(E){ql(!0),ca("");try{const g=await Ie.audit_log_tail({max_bytes:16e4}),k=typeof(g==null?void 0:g.bytes)=="number"?Number(g.bytes):0,M=!!(g!=null&&g.truncated);Md(String((g==null?void 0:g.content)||"")),la(`${k.toLocaleString()} bytes${M?" (tail)":""}`)}catch(g){ca(String((g==null?void 0:g.message)||g||"Failed to load audit log")),Md(""),la("")}finally{ql(!1)}}}async function Zi(g){if(!E)return;const k=String(g||$s||si||c||"").trim();if(!k){cr([]),Hl(""),Vl("Select a run in Activity or Artifacts to load its runtime ledger.");return}bi(!0),Vl("");try{const M=await Ie.get_ledger(k,{after:0,limit:2e3}),D=Array.isArray(M.items)?M.items:[];cr(D.map((H,q)=>({cursor:q+1,record:H})));const V=typeof M.next_after=="number"?Number(M.next_after):D.length;Hl(`${D.length.toLocaleString()} record${D.length===1?"":"s"}${V>=2e3?" (first 2,000)":""}`)}catch(M){Vl(String((M==null?void 0:M.message)||M||"Failed to load run ledger")),cr([]),Hl("")}finally{bi(!1)}}m.useEffect(()=>{E&&e==="runtime"&&fc()},[E,e,Wa,ia,si,os,ar,qa,Hi,jr]),m.useEffect(()=>{E&&(Rd||Wl||e==="runtime"&&Cu())},[E,e,ps]),m.useEffect(()=>{if(!E||e!=="runtime"||Dl!=="logs"||Ja!=="run_ledger"&&Ja!=="provider_calls")return;const g=String($s||si||c||"").trim();g&&Zi(g)},[E,e,Dl,Ja,$s,si,c]);const li=m.useMemo(()=>{const g=new Map;for(const k of[...Un,...hn]){const M=String(k.run_id||"").trim();M&&g.set(M,k)}for(const k of zi){const M=String(k||"").trim();!M||g.has(M)||g.set(M,{run_id:M,workflow_id:null,status:"",created_at:null,updated_at:null,ledger_len:null,parent_run_id:ti.current[M]||null,session_id:kr||null})}return c.trim()&&!g.has(c.trim())&&g.set(c.trim(),{run_id:c.trim(),workflow_id:typeof(de==null?void 0:de.workflow_id)=="string"?String(de.workflow_id):null,status:typeof(de==null?void 0:de.status)=="string"?String(de.status):"",created_at:typeof(de==null?void 0:de.created_at)=="string"?String(de.created_at):null,updated_at:typeof(de==null?void 0:de.updated_at)=="string"?String(de.updated_at):null,ledger_len:cn.length||null,parent_run_id:typeof(de==null?void 0:de.parent_run_id)=="string"?String(de.parent_run_id):null,session_id:typeof(de==null?void 0:de.session_id)=="string"?String(de.session_id):kr||null}),Array.from(g.values()).sort((k,M)=>{const D=Nn(k.updated_at||k.created_at)??0;return(Nn(M.updated_at||M.created_at)??0)-D})},[hn,Un,c,de,cn.length,zi,kr]),To=m.useMemo(()=>rE(li,{query:fd,filter:hd,group_by:kl,workflow_label_by_id:Sr,parent_hint:g=>ti.current[g]||""}),[li,fd,hd,kl,Sr]),Eu=m.useMemo(()=>db(Gn),[Gn]),hc=m.useMemo(()=>{const g=[...Gn];return g.sort((k,M)=>{var H,q,ne,Ce;const D=Nn(((H=k.record)==null?void 0:H.ended_at)||((q=k.record)==null?void 0:q.started_at))??0,V=Nn(((ne=M.record)==null?void 0:ne.ended_at)||((Ce=M.record)==null?void 0:Ce.started_at))??0;return D-V}),g.slice(-240)},[Gn]),Qi=m.useMemo(()=>{const g={};for(const k of li){const M=String(k.run_id||"").trim();M&&(g[M]=k)}return g},[li]),il=String($s||si||c||"").trim(),ol=il&&Qi[il]||null,Ls=String(ia||(ol==null?void 0:ol.session_id)||kr||W||"").trim(),eo=m.useMemo(()=>Wi.map(g=>qm(g,Qi,Sr)),[Wi,Qi,Sr]);m.useEffect(()=>{Vi(0)},[os,ar,qa,si,Hi,Ha,Wa,ia]);const ci=Math.max(1,Math.ceil(ta/bm)),us=Math.min(Math.max(0,jr),ci-1);m.useEffect(()=>{jr!==us&&Vi(us)},[jr,us]);const Mo=m.useMemo(()=>eo,[eo,us]),tf=m.useMemo(()=>{const g={};for(const k of Mo){const M=Ha==="type"?ig(k,Qi,Sr):yC(k,Ha);g[M]||(g[M]=[]),g[M].push(k)}return Object.entries(g).map(([k,M])=>({key:k,items:M})).sort((k,M)=>{var D,V;if(Ha==="time"){const H=Nn((D=k.items[0])==null?void 0:D.created_at)??0,q=Nn((V=M.items[0])==null?void 0:V.created_at)??0;if(H!==q)return q-H}return k.key.localeCompare(M.key)})},[Mo,Ha,Qi,Sr]),ya=m.useMemo(()=>{const g=bo.trim();return g?Mo.find(k=>k.artifact_id===g)||Mo[0]||null:Mo[0]||null},[Mo,bo]);m.useEffect(()=>{e!=="runtime"||Dl!=="artifacts"||wu(ya)},[e,Dl,ya==null?void 0:ya.artifact_id]),m.useEffect(()=>()=>{oa.url&&URL.revokeObjectURL(oa.url)},[oa.url]);const R_=m.useMemo(()=>li.filter(g=>Xu(g.status)),[li]);m.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!E||Z)return;let g=!1;return(async()=>{const[k,M]=await Promise.all([Ie.list_skills(),Ie.list_mcp_servers()]);g||(Q(k),_e(M),X(!0))})(),()=>{g=!0}},[e,E,Z]);function ui(){rh&&window.setTimeout(()=>{var g;return(g=_d.current)==null?void 0:g.scrollIntoView({block:"start"})},60)}function mc(g){Oi(g),ui()}const nf=[{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:"launch",label:"Launch",icon:s.jsx(Qe,{name:"send",size:16})},{id:"automations",label:"Automations",icon:s.jsx(Qe,{name:"refresh",size:16})}],wa={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},$u=s.jsxs(s.Fragment,{children:[Qa?s.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",Wr.length?` · ${Wr.length} skill${Wr.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."}),R===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."}):R.length?s.jsx("div",{className:"launch_skill_list",children:R.map(g=>{var V;const k=Wr.includes(g.name),M=g.blocked===!0,D=g.requires_review===!0&&!M;return s.jsxs("label",{className:`launch_skill_row ${M?"is_blocked":""} ${k?"is_on":""}`,title:[g.description||"",g.tree_hash?`tree ${g.tree_hash.slice(0,16)}…`:"",M&&((V=g.reasons)!=null&&V.length)?`blocked: ${g.reasons.join("; ")}`:""].filter(Boolean).join(`
147
+ `),children:[s.jsx("input",{type:"checkbox",checked:k,disabled:M||dt||ft||Se,onChange:H=>{const q=H.target.checked?Array.from(new Set([...Wr,g.name])):Wr.filter(ne=>ne!==g.name);Mn("skills",q.length?q:void 0)}}),s.jsx("span",{className:"launch_skill_name",children:g.name}),g.trust_level?s.jsx("span",{className:`chip ${M?"danger":D?"warn":"muted"}`,children:M?"blocked":D?"review":g.trust_level}):null,g.description?s.jsx("span",{className:"launch_skill_desc",children:g.description}):null]},g.name)})}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"The gateway's skills shelf is empty."}),Wr.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,s.jsxs("details",{style:{marginTop:"10px"},children:[s.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Workspace"}),s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Controls what the agent can access via filesystem tools."}),s.jsxs("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:"Workspace Root"}),s.jsx("input",{className:"mono",value:Fn,onChange:g=>Mn("workspace_root",g.target.value),placeholder:"/path/to/workspace",disabled:dt||ft}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Empty = gateway default (isolated per-run workspace)"})]}),s.jsxs("div",{className:"launch_grid_cell",children:[s.jsx("label",{className:"launch_label",children:"Access Mode"}),s.jsxs("select",{className:"mono",value:(Jn||"workspace_only").trim()||"workspace_only",onChange:g=>Mn("workspace_access_mode",g.target.value),disabled:dt||ft,children:[s.jsx("option",{value:"workspace_only",children:"workspace_only"}),s.jsx("option",{value:"workspace_or_allowed",children:"workspace_or_allowed"}),s.jsx("option",{value:"all_except_ignored",children:"all_except_ignored"})]}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"workspace_only: absolute paths must stay under root. workspace_or_allowed: allow additional roots."})]})]}),(Jn||"").trim()==="workspace_or_allowed"?s.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[s.jsx("label",{className:"launch_label",children:"Allowed Paths"}),s.jsx("textarea",{className:"mono",rows:3,value:as,onChange:g=>Mn("workspace_allowed_paths",g.target.value),placeholder:`/path/to/project
148
+ /path/to/workspace`,disabled:dt||ft,spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off"}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Newline-separated directories (absolute or relative to workspace_root)"})]}):null,s.jsxs("div",{className:"field",style:{marginTop:"8px"},children:[s.jsx("label",{className:"launch_label",children:"Ignored Paths"}),s.jsx("textarea",{className:"mono",rows:3,value:cu,onChange:g=>Mn("workspace_ignored_paths",g.target.value),placeholder:`node_modules
149
+ runtime
150
+ secret`,disabled:dt||ft,spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off"}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Newline-separated paths to block (absolute or relative to workspace_root)"})]})]}),s.jsxs("details",{className:"launch_bundles",style:{marginTop:"10px"},children:[s.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Workflow bundles"}),s.jsxs("div",{className:"launch_workflow_bar",style:{marginTop:"8px"},children:[s.jsx("input",{ref:it,type:"file",accept:".flow",style:{display:"none"},onChange:g=>{const k=g.target.files&&g.target.files.length?g.target.files[0]:null;k&&wh(k)}}),s.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var g;return(g=it.current)==null?void 0:g.click()},disabled:!E||B||Rr||dt||ft,title:"Upload a .flow bundle",children:Rr?"…":"Upload .flow"}),s.jsxs("button",{type:"button",className:"btn launch_btn_reload",onClick:()=>void pu(),disabled:!E||B||St||dt||ft,title:"Reload picks up server-side edits",children:[s.jsx(Qe,{name:"refresh",size:14}),St?"…":"Reload bundles"]})]})]})]});function Ro(g){t("observe"),Oi("overview"),No(g)}const qh={on_select:g=>void gn.select(g),on_row_action:(g,k)=>{if(k==="discuss"||k==="edit")throw new Error(`${k} is routed by AutomationsPage (route_row_action), not the app handlers.`);if(k==="archive"){gn.ask_archive(g.automation_id);return}gn.row_action(g,k)},on_legacy_action:(g,k)=>{if(k==="open_run"){Ro(g.automation_id);return}if(k==="recreate"){Hd(g.automation_id).catch(M=>gn.report_error(M));return}gn.legacy_action(g,k)},on_confirm_archive:g=>void gn.row_action(g,"archive"),on_cancel_archive:()=>gn.ask_archive(""),on_status_filter:g=>void gn.set_status_filter(g),on_refresh:()=>void gn.refresh(),on_new:()=>{ye("automate"),t("launch")},on_show_archived:g=>gn.set_show_archived(g)};return s.jsxs("div",{className:`app-shell shell${Bc?" nav_open":""}`,children:[md&&Bc?s.jsx("div",{className:"shell_nav_backdrop","aria-hidden":"true",onClick:()=>yi(!1)}):null,s.jsxs("aside",{className:"shell_sidebar",id:"shell_nav",ref:oh,...Ko.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:()=>yi(!1),children:s.jsx(Qe,{name:"x",size:16})})]}),s.jsxs("nav",{className:"shell_nav",children:[nf.map(g=>s.jsxs("button",{className:`shell_nav_item ${e===g.id?"active":""}`,onClick:()=>{t(g.id),yi(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:g.icon}),s.jsx("span",{className:"shell_nav_label",children:g.label})]},g.id)),s.jsxs("a",{className:"shell_nav_item",href:l,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"),yi(!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:E?"Gateway connected":B?"Gateway: connecting…":"Gateway: signed out",children:[s.jsx("span",{className:`gateway_led ${E?"ok":B?"warn":"err"}`,"aria-hidden":"true"}),s.jsx("span",{className:`shell_connection_label ${E&&((af=(va=F==null?void 0:F.gateway)==null?void 0:va.principal)!=null&&af.user_id)?"mono":""}`,children:E?((Kh=(Bn=F==null?void 0:F.gateway)==null?void 0:Bn.principal)==null?void 0:Kh.user_id)||(n.gateway_auth_mode==="direct"?"direct dev":"connected"):B?"connecting…":"signed out"})]})})]}),s.jsxs("div",{className:"shell_main",...Ko.attrs.main,children:[s.jsxs("header",{className:"shell_header",children:[s.jsx("button",{ref:b_,type:"button",className:"shell_nav_toggle","data-nav-toggle":!0,"aria-label":"Open navigation","aria-controls":"shell_nav","aria-expanded":Bc,title:"Navigation",onClick:()=>yi(!0),children:s.jsx(Qe,{name:"list",size:18})}),s.jsx("div",{className:"shell_header_title",children:wa[e]||"Observer"}),s.jsxs("div",{className:"shell_header_actions",children:[o?s.jsx("monitor-gpu",{ref:u,mode:"icon","history-size":"5","tick-ms":"1500","base-url":n.gateway_auth_mode==="session"?"":n.gateway_url,title:"GPU usage (host)",style:{"--monitor-gpu-width":"34px","--monitor-gpu-bars-height":"22px","--monitor-gpu-padding":"2px 4px","--monitor-gpu-radius":"999px","--monitor-gpu-bg":"rgba(0,0,0,0.22)","--monitor-gpu-border":"rgba(255,255,255,0.16)",flexShrink:0}}):null,s.jsx(eS,{assistant:{open:jn,onToggle:()=>ns(g=>!g),label:"Observer assistant (docs-grounded)"},appearance:{onOpen:()=>It(!0)},about:{identity:gh,extraRows:Kl,onOpen:Yl},connection:{phase:O.phase,signingOut:O.signingOut,onConnect:()=>O.openModal(),onDisconnect:()=>tc()}})]})]}),s.jsx(Tj,{...O.modalProps}),s.jsx(rS,{open:Ut,onClose:()=>It(!1),value:Qt,onChange:yn}),s.jsx(v1,{open:jn,onClose:()=>ns(!1),connected:E,topOffset:44,gateway:Ie}),s.jsxs("div",{className:"app-body shell_content",children:[e==="board"?E?s.jsx(o3,{gateway_connected:E,runs:Un,all_runs:hn,runs_refreshed_at:Yn,entities:Mr,entities_total:ce,entities_error:Je,refreshing:_n,on_refresh:()=>void qs(Ie,{force:!0}),on_open_run:g=>{t("observe"),Oi("overview"),No(g)},on_resume_wait:xh,on_open_automation:g=>{t("automations"),gn.refresh().then(()=>gn.select(g))},entity_app_href:l,on_read_diary:(g,k)=>Ie.read_entity_diary_entry(g,k),phase_graph:vh}):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.",$?` Last attempt: ${$}`:""]}),s.jsxs("div",{className:"row",style:{gap:"8px",alignItems:"center"},children:[s.jsx("button",{className:"btn primary",onClick:()=>O.openModal(),disabled:B,children:B?"Connecting…":"Sign in"}),s.jsx("button",{className:"btn",onClick:()=>void el({open_modal_if_needed:!0}),disabled:B,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 ${E?"ok":"warn"}`,children:qv(F).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:()=>O.openModal(),children:"Manage connection…"}),E?s.jsx("button",{className:"btn",onClick:()=>tc(),title:"Sign this browser out of the gateway (this app's session only)",children:"Sign out"}):null]})]}),$?s.jsx("div",{className:"warn_callout",children:$}):null,s.jsx("div",{className:"settings_row",children:s.jsx(A2,{checked:n.auto_connect_gateway,onChange:g=>r(k=>({...k,auto_connect_gateway:g}))})}),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:g=>r(k=>({...k,gateway_url:g.target.value})),placeholder:t_})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Dev bearer token"}),s.jsx("input",{type:"password",value:n.auth_token,onChange:g=>r(k=>({...k,auth_token:g.target.value,gateway_auth_mode:"direct"})),placeholder:"development only — prefer the sign-in dialog"})]}),s.jsx("button",{className:"btn",onClick:()=>void el({prefer_direct:!0}),disabled:B,children:B?"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(gj,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:qr,models:du.models,loadingProviders:B,loadingModels:yh,modelError:ec?du.error:"",allowCustomProvider:!0,allowCustomModel:!0,allowGatewayDefault:!0,gatewayDefaultLabel:"(gateway default)",onChange:g=>r(k=>({...k,maintenance_ai_provider:g.provider,maintenance_ai_model:g.model}))}),s.jsx("div",{className:"settings_subhead",children:"Skills"}),R===null?s.jsx("div",{className:"settings_row_help",children:E?Z?"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)."}):R.length?s.jsx("div",{className:"settings_choice_list",children:R.map(g=>{const k=n.assistant_skill_names.includes(g.name);return s.jsx(T2,{name:g.name,version:g.version,description:g.description,checked:k,onChange:M=>r(D=>({...D,assistant_skill_names:M?Array.from(new Set([...D.assistant_skill_names,g.name])):D.assistant_skill_names.filter(V=>V!==g.name)}))},g.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:g=>r(k=>({...k,worker_url:g.target.value})),placeholder:"https://your-mcp-worker-endpoint"}),s.jsx("input",{className:"mono",type:"password",value:n.worker_token,onChange:g=>r(k=>({...k,worker_token:g.target.value})),placeholder:"Bearer token (optional)"}),s.jsx("span",{className:`chip ${n.worker_url.trim()?"ok":"muted"}`,children:n.worker_url.trim()?"configured":"none"})]})]})]})]})}):null,e==="launch"?s.jsx("div",{className:"page page_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card",children:[s.jsx(i2,{mode:he,automate_available:Ue.available,automate_reason:Ue.reason,on_change:ye}),he==="automate"&&!Ue.available&&E?s.jsx("div",{className:"warn_callout",role:"note",children:Ue.reason}):null,he==="automate"&&ht.length?s.jsx("div",{className:"help_text",role:"note",children:ht.map(g=>s.jsx("div",{children:g},g))}):null,E?null:s.jsxs("div",{className:"warn_callout",children:["Not connected."," ",s.jsx("button",{className:"btn primary",onClick:()=>O.openModal(),children:"Sign in"})," ","to launch workflows on this gateway."]}),he==="automate"?s.jsx("div",{className:"section_title",children:"What"}):null,s.jsx("div",{className:"launch_workflow_bar",children:s.jsxs("select",{className:"launch_workflow_select","aria-label":"Workflow",value:Ms,onChange:async g=>{const k=T1(String(g.target.value||""));k&&await Ch(k)},disabled:B||!E,children:[s.jsx("option",{value:"",children:uu.length?"(select workflow)":De?B?"(loading workflows…)":"(no executable workflows published on this gateway)":"(sign in to load workflows)"}),s.jsx("optgroup",{label:"Gateway default",children:R1($t).map(g=>s.jsx("option",{value:g.value,children:g.label},g.value))}),s.jsx("optgroup",{label:"Workflows",children:uu.map(g=>s.jsx("option",{value:g.workflow_id,children:g.label},g.workflow_id))})]})}),s.jsxs("div",{className:"field",children:[ys!=null&&ys.description?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(ys.description)}):null,J?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading workflow…"}):null,ae?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:ae}):null]}),s.jsx("div",{className:"section_divider"}),s.jsx("div",{className:"section_title",children:"Inputs"}),Qa?ut===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:kt()})]}),s.jsx("div",{className:"body mono",children:"Invalid input JSON — reselect the workflow to reset its inputs."})]}):Zl?s.jsx("div",{className:"launch_inputs",children:(()=>{const g=dt||ft,k=[],M=[];for(const H of ko){if(!H||typeof H!="object")continue;const q=String(H.id||"").trim();if(!q||he==="automate"&&Vx.includes(q))continue;const ne=String(H.type||"").trim().toLowerCase();ne==="tools"||ne==="skills"||ne==="mcp"||ne==="mcp_servers"||q==="skills"||q==="mcp"||q==="mcp_servers"||ne==="array"||fa(ne)||q==="prompt"||q==="system"?k.push(H):M.push(H)}const D=H=>String(H||"").trim().replace(/_/g," ").replace(/\b\w/g,q=>q.toUpperCase()),V=(H,q)=>{const ne=String(H.id||"").trim();if(!ne)return null;const Ce=String(H.label||ne).trim()||ne,me=Ce===ne?D(ne):Ce,ge=String(H.type||"").trim().toLowerCase(),Ne=Object.prototype.hasOwnProperty.call(H,"default"),Oe=Ne?H.default:void 0,He=Ne?typeof Oe=="string"?Oe:Os(Oe,80):"",Xe=ut==null?void 0:ut[ne],Ke=Ne?`${He}`:"";if(ge==="tools"){const We=Array.isArray(Xe)?Xe.map(xn=>String(xn||"").trim()).filter(Boolean):[],jt=Array.isArray(Oe)?Oe.map(xn=>String(xn||"").trim()).filter(Boolean):[],mn=Array.from(new Set([...Ql,...We,...jt])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:me}),s.jsx(Rv,{options:mn,value:We,disabled:g,placeholder:"(no tools selected)",onChange:xn=>Mn(ne,xn)})]},ne)}if(ge==="skills"||ne==="skills")return null;if(ge==="mcp"||ge==="mcp_servers"||ne==="mcp"||ne==="mcp_servers"){const We=Array.isArray(Xe)?Xe.map(xn=>String(xn||"").trim()).filter(Boolean):[];if(le===null&&!We.length)return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:me}),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."})]},ne);const jt=(le||[]).map(xn=>xn.name),mn=Array.from(new Set([...jt,...We])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:me}),s.jsx(Rv,{options:mn,value:We,disabled:g,placeholder:"(no MCP servers selected)",onChange:xn=>Mn(ne,xn)})]},ne)}if(ge==="provider"||ge==="provider_text"){const We=typeof Xe=="string"?String(Xe):"";return s.jsxs("div",{className:q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:me}),s.jsxs("select",{value:We,onChange:jt=>Mn(ne,jt.target.value),disabled:g,children:[s.jsx("option",{value:"",children:Ke||"(select)"}),ki.map(jt=>s.jsx("option",{value:jt,children:jt},jt))]})]},ne)}if(ge==="model"||ge==="model_text"){const We=typeof Xe=="string"?String(Xe):"",jt=String((ut==null?void 0:ut.provider)||"").trim(),mn=jt?At[jt]:void 0,xn=mn&&Array.isArray(mn.models)?mn.models.map(Js=>String(Js||"").trim()).filter(Boolean):[];return s.jsxs("div",{className:q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:me}),xn.length?s.jsxs("select",{value:We,onChange:Js=>Mn(ne,Js.target.value),disabled:g,children:[s.jsx("option",{value:"",children:Ke||"(select)"}),xn.map(Js=>s.jsx("option",{value:Js,children:Js},Js))]}):s.jsx("input",{value:We,onChange:Js=>Mn(ne,Js.target.value),placeholder:Ke||"model id",disabled:g})]},ne)}if(ge==="boolean"){const We=typeof Xe=="boolean"?Xe?"true":"false":"";return s.jsxs("div",{className:q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:me}),s.jsxs("select",{value:We,onChange:jt=>{const mn=String(jt.target.value||"").trim();mn?Mn(ne,mn==="true"):Mn(ne,void 0)},disabled:g,children:[s.jsx("option",{value:"",children:Ke||"(default)"}),s.jsx("option",{value:"true",children:"Yes"}),s.jsx("option",{value:"false",children:"No"})]})]},ne)}if(ge==="number"){const We=typeof Xe=="number"&&Number.isFinite(Xe)?String(Xe):"";return s.jsxs("div",{className:q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:me}),s.jsx("input",{type:"number",value:We,onChange:jt=>{const mn=String(jt.target.value||"").trim();if(!mn){Mn(ne,void 0);return}const xn=Number(mn);Number.isFinite(xn)&&Mn(ne,xn)},placeholder:Ke,disabled:g})]},ne)}if(ge==="array"){const We=Array.isArray(Xe)?Xe.map(jt=>String(jt||"").trim()).filter(Boolean).join(`
151
+ `):"";return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:me}),s.jsx("textarea",{className:"mono",value:We,onChange:jt=>{const mn=String(jt.target.value||"").split(/\r?\n/g).map(xn=>String(xn||"").trim()).filter(Boolean);Mn(ne,mn.length?mn:void 0)},placeholder:Ke||"(one item per line)",rows:2,disabled:g})]},ne)}if(fa(ge)){const We=typeof on[ne]=="string"?on[ne]:"",jt=String(Qr[ne]||"").trim();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsxs("label",{className:"launch_label",children:[me," ",s.jsx("span",{className:"launch_label_type",children:ge})]}),s.jsx("textarea",{className:"mono",value:We,onChange:mn=>{const xn=String(mn.target.value??"");Fs(dr=>({...dr,[ne]:xn}));const Js=xn.trim();if(!Js){rs(dr=>{const di={...dr};return delete di[ne],di}),Mn(ne,void 0);return}try{const dr=JSON.parse(Js);rs(di=>{const al={...di};return delete al[ne],al}),Mn(ne,dr)}catch(dr){rs(di=>({...di,[ne]:String((dr==null?void 0:dr.message)||dr||"Invalid JSON")}))}},placeholder:Ke||"{...}",rows:3,disabled:g}),jt?s.jsx("div",{className:"launch_field_error",children:jt}):null]},ne)}const nn=typeof Xe=="string"?String(Xe):"";return ne==="prompt"||ne==="system"?s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:me}),s.jsx("textarea",{value:nn,onChange:We=>Mn(ne,We.target.value),placeholder:Ke||(ne==="prompt"?"What should the agent do?":"System instructions (optional)"),rows:3,disabled:g})]},ne):s.jsxs("div",{className:q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:me}),s.jsx("input",{value:nn,onChange:We=>Mn(ne,We.target.value),placeholder:Ke,disabled:g})]},ne)};return k.sort((H,q)=>{const ne={system:0,prompt:1,tools:2};return(ne[String(H.id||"")]??10)-(ne[String(q.id||"")]??10)}),s.jsxs(s.Fragment,{children:[k.map(H=>V(H)),M.length>0?s.jsx("div",{className:"launch_grid",children:M.map(H=>V(H,"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:lu,onChange:g=>Mn("prompt",g.target.value),placeholder:"What do you want the workflow/agent to do?",rows:3,disabled:dt||ft})]}),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:Xl,onChange:g=>Mn("provider",g.target.value),placeholder:"lmstudio / ollama / openai / ...",disabled:dt||ft})]})}),s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Model (common)"}),s.jsx("input",{value:da,onChange:g=>Mn("model",g.target.value),placeholder:"qwen/qwen3-next-80b / gpt-4.1 / ...",disabled:dt||ft})]})})]})]}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Select a workflow above to configure inputs."}),he==="automate"?s.jsxs(s.Fragment,{children:[s.jsx(o2,{form:Be,email_status:ji.email_status,on_open_my_email:iu,tools:Array.isArray(ut==null?void 0:ut.tools)?ut.tools.map(g=>String(g)):void 0,disabled:Se,on_change:g=>gt(k=>({...k,...g}))}),s.jsxs("details",{className:"launch_advanced",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Advanced",Wr.length?` · ${Wr.length} skill${Wr.length===1?"":"s"}`:""]}),s.jsx(a2,{form:Be,disabled:Se,on_change:g=>gt(k=>({...k,...g}))}),$u]})]}):$u,s.jsx("div",{className:"section_divider"}),co?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:co})]}):null,he==="automate"&&Fe.length?s.jsx("ul",{className:"automate_errors",role:"alert",children:Fe.map(g=>s.jsx("li",{children:g},g))}):null,he==="automate"&&lt?s.jsxs("div",{className:"observe_context_card error",role:"alert","data-code":lt.code,style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:lt.code}),s.jsxs("span",{children:[s.jsx("strong",{children:Lm(lt).title})," ",Lm(lt).detail,lt.field?s.jsxs("span",{className:"mono",children:[" (",lt.field,")"]}):null]})]}):null,s.jsx("div",{className:"launch_actions_bar launch_actions_stack",children:(()=>{const g=he==="automate",k=E?Qa?ut===null?"Inputs contain invalid JSON":g&&!Ue.available?"Automations unavailable on this gateway":dt||ft?"Attaching to a run…":B||J?"Loading…":Se?"Submitting…":"":"Select a workflow":"Sign in first";return s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"launch_submit_btn",onClick:()=>void qd(),disabled:!!k,title:k,children:g?Se?"Creating…":"Create automation":dt?"Launching…":"Launch now"}),k&&!Se&&!dt?s.jsx("span",{className:"mono muted launch_disabled_reason",children:k}):null]})})()})]})})}):null,e==="automations"?s.jsx($2,{ctl:gn,gateway:Ie,active:e==="automations"&&E,available:Ue,h:qh,host:{on_open_run:g=>Ro(g),...iu?{on_open_my_email:iu}:{},on_open_session:(g,k)=>{Xt({ts:kt(),kind:"info",title:"Discussion started",preview:_t(k),data:g})}}}):null,e==="runtime"?s.jsx(BC,{gateway_connected:E,tab:Dl,runs:li,active_runs:R_,all_artifacts:Wi,artifacts:Mo,artifact_total_count:ta,artifact_total_bytes:$d,artifact_facets:vo,artifact_type_facets:kn,artifact_page:us,artifact_page_size:bm,artifact_groups:tf,selected_artifact:ya,embedded_preview:oa,loading:Es,error:sa,query:os,scope:Wa,type_filters:ar,date_filter:qa,group_by:Ha,sort_by:Hi,artifact_run_filter:si,audit_log_text:Wl,audit_log_meta:_h,audit_log_loading:Rd,audit_log_error:ru,workflow_label_by_id:Sr,run_by_id:Qi,selected_run_id:il,session_id:Ls,runtime_log_source:Ja,runtime_log_query:Id,runtime_ledger_log_items:Xa,runtime_ledger_log_meta:ua,runtime_ledger_log_loading:ph,runtime_ledger_log_error:So,on_tab_change:dh,on_query_change:Qc,on_scope_change:eu,on_session_filter_change:Ad,on_type_filters_change:tu,on_date_filter_change:fh,on_group_by_change:xo,on_sort_by_change:Va,on_artifact_page_change:Vi,on_artifact_run_filter_change:g=>{const k=String(g||"").trim();zl(k),k&&As(k),k&&Wa!=="run"&&eu("run")},on_refresh_artifacts:()=>void fc(),on_refresh_audit:()=>void Cu(),on_refresh_runtime_ledger:g=>void Zi(g),on_runtime_log_source_change:Ld,on_runtime_log_query_change:Od,on_select_run:g=>{const k=String(g||"").trim();As(k);const M=k&&Qi[k]||null,D=String((M==null?void 0:M.session_id)||"").trim();D&&Ad(D)},on_select_artifact:ri,on_preview_artifact:g=>void Bd(g),on_download_artifact:g=>void zd(g),on_open_run:g=>{As(String(g||"").trim()),t("observe"),Oi("overview"),No(g)},on_open_ledger:g=>{As(String(g||"").trim()),t("observe"),Oi("ledger"),No(g)},on_refresh_runs:()=>void qs(Ie,{force:!0}),on_reconnect:()=>void el({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:E?s.jsx(PL,{gateway:Ie,selected_run_id:$s,selected_session_id:Ls}):null}):null,e==="observe"?s.jsx("div",{className:"page observe_page",children:s.jsxs("div",{className:`observatory_layout${ih?"":" list_collapsed"}`,children:[s.jsx(WC,{sections:To,selected_run_id:c,root_run_id:_,search:fd,filter:hd,group_by:kl,loading:_n,connected:E,on_sign_in:()=>O.openModal(),total_runs:li.length,workflow_label_by_id:Sr,automation_titles:ou,on_search:w_,on_filter:v_,on_group_by:Nl,on_refresh:()=>void qs(),on_select:(g,k)=>{No(g,{root_run_id:k||g}),ui()},list:{open:ih,on_toggle:x_}}),s.jsxs("div",{className:"observatory_main",children:[s.jsxs("div",{className:"observe_toolbar",children:[s.jsxs("div",{className:"observe_toolbar_row",children:[c.trim()?s.jsxs("div",{className:"observe_run_identity",title:c.trim(),children:[s.jsx("span",{className:"observe_run_name",children:Sr[String((Rn==null?void 0:Rn.workflow_id)||"")]||String((Rn==null?void 0:Rn.workflow_id)||"").trim()||Lt(c.trim(),22)}),s.jsx("span",{className:"chip mono muted",children:Lt(c.trim(),14)}),s.jsx("span",{className:`chip ${vl(Vr||Ln,Ci)}`,title:String((Ci==null?void 0:Ci.headline)||""),children:Vr||Ln||"unknown"})]}):x?s.jsx("span",{className:"observe_run_identity_empty observe_run_link_missing",role:"alert",children:$1(x)}):s.jsx("span",{className:"observe_run_identity_empty",children:"No run selected"}),s.jsx("span",{className:"observe_toolbar_spacer"}),c.trim()?s.jsxs(s.Fragment,{children:[Gs?s.jsx(R2,{active:!Yi,unavailableReason:Fh,busy:dt||ft,onChange:g=>{if(!g){vr("pause"),nr(""),is(""),wr(!0);return}xu("resume")}}):s.jsx("button",{className:"btn",onClick:()=>{if(Hr==="pause"){vr("pause"),nr(""),is(""),wr(!0);return}xu("resume")},disabled:$o,children:ls}),zh?s.jsx("button",{className:"btn primary",onClick:()=>void ur(),disabled:dt||ft||$r||Yi,children:"Run now"}):null,s.jsx("button",{className:"btn danger",onClick:()=>{vr("cancel"),nr(""),is(""),wr(!0)},disabled:dt||ft||$r,children:"Cancel"}),s.jsx("button",{className:"btn btn_icon",onClick:vu,title:"Clear the run view",children:s.jsx(Qe,{name:"x",size:14})})]}):null]}),c.trim()&&!$r?s.jsx("div",{className:"observe_steer_row",children:s.jsx(zj,{runId:c.trim(),parked:_a,submit:(g,k)=>Ie.submit_command({command_id:`steer-${xs()}`,run_id:g,type:"inject_guidance",payload:{guidance:k},client_id:"web_pwa"}).then(M=>({accepted:!!(M!=null&&M.accepted),duplicate:!!(M!=null&&M.duplicate),seq:Number((M==null?void 0:M.seq)??0)})),onSent:()=>Xt({ts:kt(),kind:"info",title:"Steer queued",preview:"inject_guidance submitted — delivery shows as abstract.steer_seen in the ledger"})})}):null,_a||Gs||dd?s.jsxs("div",{className:"observe_toolbar_context",children:[_a?s.jsxs("div",{className:"observe_context_card info",children:[s.jsxs("div",{className:"observe_context_label",children:[(()=>{const g=Gs?Yi?"suspended":"scheduled":"waiting";return s.jsx("span",{className:`chip ${vl(g)}`,children:g})})(),s.jsx("span",{className:"muted",children:Qn||"unknown"})]}),s.jsxs("div",{className:"observe_context_body",children:[Rs?s.jsxs("span",{className:"mono",title:Rs,children:[s.jsx("span",{className:"muted",children:"wait_key"}),": ",Lt(Rs,46)]}):null,Qn==="event"&&Yd?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"event"}),": ",Yd]}):null,Qn==="subworkflow"&&Eo?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"child"}),": ",Lt(Eo,18)]}):null,Qn==="until"&&Er?s.jsxs("span",{className:"mono",title:Er,children:[s.jsx("span",{className:"muted",children:"until"}),": ",Lt(Er,46)]}):null,Qn==="until"&&Er?s.jsx("span",{className:"mono muted",children:(()=>{const g=Nn(Er),k=g!==null?new Date(g).toLocaleString():Er,M=g!==null?uw(g-Date.now()):"";return`Next at ${k}${M?` (in ${M})`:""}`})()}):null]}),Qn==="subworkflow"&&Eo?s.jsxs("div",{className:"observe_context_actions",children:[s.jsx("button",{className:"btn primary",onClick:async()=>{f(Eo),await ma(Eo)},disabled:dt,children:"Attach to child"}),_.trim()&&_.trim()!==c.trim()?s.jsx("button",{className:"btn",onClick:async()=>{f(_.trim()),await ma(_.trim())},disabled:dt,children:"Back to root"}):null]}):null]}):null,Gs?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:oc?`every ${ga}`:"once"})]}),s.jsxs("div",{className:"observe_context_body",children:[ga?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"interval"}),": ",ga]}):null,s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"share ctx"}),": ",Dh?"yes":"no"]}),typeof Qd=="number"?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"repeats"}),": ",Qd]}):null]}),sl!==null?s.jsxs("div",{className:"observe_context_budget",children:[s.jsxs("span",{className:"mono muted",children:[typeof ai=="number"&&typeof Bh=="number"?`${ai.toLocaleString()} / ${Bh.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,sl))*100)}%`]}),s.jsx("div",{className:"observe_budget_bar",children:s.jsx("div",{className:`observe_budget_fill ${sl>=.9?"danger":sl>=.75?"warn":"ok"}`,style:{width:`${Math.round(Math.max(0,Math.min(1,sl))*100)}%`}})})]}):null,s.jsxs("div",{className:"observe_context_actions",children:[oc?s.jsx("button",{className:"btn",onClick:()=>{Dn(ga||""),qn(!0),_i(""),Bo(!0)},disabled:dt||$n,children:"Edit schedule"}):null,oc?s.jsx("button",{className:"btn",onClick:()=>{ms(""),tr(!0)},disabled:dt||Lr,children:"Compact context"}):null,s.jsx("button",{className:"btn",onClick:()=>void Hd(c.trim()).catch(g=>tn(String((g==null?void 0:g.message)||g))),disabled:dt||!c.trim(),title:"Open Launch → Automate prefilled from this schedule (this schedule is not changed)",children:"Recreate as automation"})]})]}):null,dd?s.jsxs("div",{className:"observe_context_card error",children:[s.jsx("span",{className:"chip danger",children:"error"}),s.jsx("span",{className:"mono",children:dd})]}):null]}):null]}),s.jsxs("div",{className:"card panel_card card_scroll observe_viewer observe_viewer_full",ref:_d,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":ps==="overview",className:`tab ${ps==="overview"?"active":""}`,onClick:()=>mc("overview"),children:"Story"}),s.jsx("button",{role:"tab","aria-selected":ps==="ledger",className:`tab ${ps==="ledger"?"active":""}`,onClick:()=>mc("ledger"),children:"Ledger"}),s.jsx("button",{role:"tab","aria-selected":ps==="graph",className:`tab ${ps==="graph"?"active":""}`,onClick:()=>mc("graph"),children:"Flow"}),s.jsx("button",{role:"tab","aria-selected":ps==="chat",className:`tab ${ps==="chat"?"active":""}`,onClick:()=>mc("chat"),children:"Ask"})]}),ps==="ledger"&&(lc.length>0||El==="cycles")?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsxs("div",{className:"seg_toggle",children:[s.jsx("button",{className:`seg_btn ${El==="steps"?"active":""}`,onClick:()=>Ia("steps"),children:"Steps"}),s.jsx("button",{className:`seg_btn ${El==="cycles"?"active":""}`,onClick:()=>Ia("cycles"),children:"Cycles"})]}),El==="steps"?s.jsx("button",{className:`seg_action ${Pi?"active":""}`,"aria-pressed":Pi,onClick:()=>Cl(g=>!g),title:Pi?"Condensed: only the key steps are shown":"Condensed is off: every step is shown",children:"Condensed"}):s.jsxs("select",{className:"mono seg_select",value:vn,onChange:g=>pd(String(g.target.value||"")),disabled:!es.length,title:"Select run for cycles view",children:[es.length?null:s.jsx("option",{value:"",children:"(no runs)"}),es.map(g=>{const k=typeof Ht[g]=="number"?Number(Ht[g]):0,M=`${Lt(g,18)}${k?` • ${k} llm`:""}`;return s.jsx("option",{value:g,children:M},g)})]}),s.jsx("button",{className:"seg_action",disabled:!cn.length&&!ss.length,title:"Copy full ledger as JSONL",onClick:()=>{const M=[...cn.map(H=>({run_id:c.trim()||H.record.run_id||"",cursor:H.cursor,record:H.record})),...ss.map(H=>({run_id:H.run_id,cursor:H.cursor,record:H.record}))].map(H=>{var Ce,me;const q=String(((Ce=H.record)==null?void 0:Ce.ended_at)||((me=H.record)==null?void 0:me.started_at)||"").trim(),ne=Nn(q);return{...H,_ms:ne??0}});M.sort((H,q)=>(H._ms||0)-(q._ms||0));const V=(M.length>5e3?M.slice(M.length-5e3):M).map(({_ms:H,...q})=>JSON.stringify(q)).join(`
152
+ `);gu(V)},children:"Copy JSONL"})]}):null,ps==="graph"?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsx("button",{className:`seg_action ${Jo?"active":""}`,"aria-pressed":Jo,onClick:()=>Nd(g=>!g),children:"Subflows"}),s.jsx("button",{className:`seg_action ${Cd?"active":""}`,"aria-pressed":Cd,onClick:()=>N_(g=>!g),children:"Path"}),ac.length?s.jsx("select",{className:"mono seg_select",value:po,onChange:g=>Pa(String(g.target.value||"")),disabled:!!Ni.trim()||!N.trim()||Sd,children:ac.map(g=>s.jsx("option",{value:g,children:g},g))}):null]}):null]}),ps==="overview"?s.jsx(qC,{run_id:c,run:Rn,run_state:de,status_label:Vr||Ln||"unknown",workflow_label_by_id:Sr,root_run_id:_,subrun_ids:zi,session_id:kr,records_count:cn.length,records:cn,child_records_count:ss.length,provider_activities:Eu,attachments_count:gd.length,latest_summary:Uh,wait_state:qt,summary_generating:ea,summary_error:Pl,on_generate_summary:()=>void Ah(),on_open_runtime:()=>{const g=String(c||"").trim();g&&(As(g),zl(g),eu("run")),dh("artifacts"),t("runtime")},on_open_subrun:g=>void No(g,{root_run_id:_||c||g}),on_answer_wait:()=>rr(""),workspace_root:lh,on_reveal_workspace:()=>void jh(),run_artifacts:ei,run_artifacts_loading:ch,run_artifacts_error:uh,on_preview_run_artifact:g=>void Bd(g),on_download_run_artifact:g=>void zd(g),timeline_items:hc,node_index:au,attachments:gd,attachments_loading:yd,attachments_error:S_,attachments_ready:!!$l.trim(),on_refresh_attachments:()=>void bh(),on_preview_attachment:g=>void E_(g),on_download_attachment:g=>void C_(g),on_copy:g=>void gu(g)}):null,ps==="ledger"?s.jsx(s.Fragment,{children:El==="steps"?s.jsxs("div",{className:"log log_scroll",children:[lc.map(g=>s.jsx(VC,{item:g,open:y_[g.id]===!0,on_toggle:()=>ud(k=>({...k,[g.id]:!k[g.id]})),response_open:nh[g.id]===!0,on_toggle_response:()=>sh(k=>({...k,[g.id]:!k[g.id]})),node_index:au,on_copy:k=>void gu(k)},g.id)),lc.length?null:s.jsx("div",{className:"empty_state_inline",children:"(no ledger items)"})]}):s.jsx("div",{className:"log log_scroll",children:s.jsx(Ek,{items:Ks.items,title:"Agent",subtitle:Ks.node_id?`node_id: ${Ks.node_id}`:"Live per-effect trace (LLM/tool calls).",subRunId:vn,onOpenSubRun:vn&&vn!==c.trim()?()=>{f(vn),ma(vn)}:void 0})})}):null,ps==="graph"?s.jsxs(s.Fragment,{children:[kd?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:kt()})]}),s.jsx("div",{className:"body mono",children:kd})]}):null,Sd?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:Ni.trim()?Ni.trim():po})]}),s.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,s.jsx("div",{className:"graph_panel",children:s.jsx(fE,{flow:Fi,flow_by_id:Rl,expand_subflows:Jo,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:dc,schedule_interval:ga,node_last_ms:M_,active_node_id:Wh,recent_nodes:Cn,visited_nodes:Kc,highlight_path:Cd,now_ms:Ll})})]}):null,s.jsxs(pl,{open:xd,title:k_||"Attachment",onClose:()=>{bd(!1),wi(""),Ml(""),Di(!1)},actions:s.jsx(s.Fragment,{children:s.jsx("button",{className:"btn",onClick:()=>{bd(!1),wi(""),Ml(""),Di(!1)},children:"Close"})}),children:[Hc?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,qc?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:qc}):null,s.jsx("pre",{className:"mono",style:{whiteSpace:"pre-wrap",maxHeight:"62vh",overflow:"auto",margin:0},children:jd||"(empty)"})]}),ps==="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(Ju,{value:id,options:ld,placeholder:jl?"Loading…":ld.length?"Select a saved discussion…":"(none saved)",disabled:!c.trim()||!E||!ld.length,loading:jl,searchable:!0,clearable:!0,onChange:g=>{Dc(g),Go("")}})}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[s.jsx("button",{className:"btn",type:"button",disabled:!id.trim()||!E||Fc,onClick:()=>void Lh(),children:Fc?"Loading…":"Load"}),s.jsx("button",{className:"btn",type:"button",disabled:!et.length||be||Zn||Fc,onClick:()=>{ot([]),Pt(null),ir(""),pi(""),pn(""),_s(""),br("")},children:"Clear"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>void ju(),disabled:!c.trim()||!E||jl,children:jl?"Refreshing…":"Refresh"})]})]}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:"8px",flexWrap:"wrap"},children:[s.jsx("button",{className:"btn",type:"button",disabled:!et.length||!c.trim()||!E||Zn||!ad,onClick:()=>void Gd(),title:ad?"":"No changes since last save",children:Zn?"Saving…":!ad&&wn?"Saved":"Save discussion"}),s.jsx("button",{className:"btn",type:"button",disabled:!et.length,onClick:()=>bu("download"),children:"Export Markdown"}),s.jsx("button",{className:"btn",type:"button",disabled:!et.length,onClick:()=>bu("copy"),children:Ae==="copied"?"Copied":Ae==="failed"?"Copy failed":"Copy Markdown"})]}),wn?s.jsxs("div",{className:"chat_hint",children:["Last saved: ",ka(wn)]}):null,an?s.jsx("div",{className:"chat_hint chat_hint_danger",children:an}):null,od?s.jsx("div",{className:"chat_hint chat_hint_danger",children:od}):null,Oc?s.jsx("div",{className:"chat_hint chat_hint_danger",children:Oc}):null]})]}),qo?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:kt()})]}),s.jsx("div",{className:"body mono",children:qo})]}):null,bl?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:kt()})]}),s.jsx("div",{className:"body mono",children:bl})]}):null,s.jsx("div",{className:"chat_messages",style:{marginTop:"10px"},children:s.jsx(Dg,{messages:et,className:"log_scroll",after:s.jsx(qx,{history:mt}),afterKey:mt?`${mt.replayed_messages}:${mt.dropped_messages}`:null,messageProps:Hn.tts_supported&&E&&U.trim()?{onSpeakToggle:Mh,getSpeakState:Rh,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(Fg,{ref:Jt,value:_o,onChange:ir,onSubmit:()=>void Th(),placeholder:"Ask about this run…",disabled:!c.trim()||!E||be,busy:be||Hn.voice_ptt_busy,busyLabel:Hn.voice_ptt_busy?"Transcribing…":"Thinking…",rows:3,sendButtonClassName:"btn primary",actions:s.jsxs("button",{className:`btn btn_icon voice_btn${Hn.voice_ptt_recording?" danger":""}`,type:"button",disabled:!E||!ha.trim()||!U.trim()||be||Hn.voice_ptt_busy||!Hn.voice_ptt_supported,title:Hn.voice_ptt_supported?Hn.voice_ptt_busy?"Transcribing…":Hn.voice_ptt_recording?"Recording… release to transcribe":"Hold to talk (record + transcribe)":ag()?"Voice recording is not supported in this browser":og,"aria-label":"Voice input",onPointerDown:g=>{var k,M;if(!(!E||!ha.trim()||!U.trim()||be||Hn.voice_ptt_busy||!Hn.voice_ptt_supported)){g.preventDefault();try{(M=(k=g.currentTarget)==null?void 0:k.setPointerCapture)==null||M.call(k,g.pointerId)}catch{}Hn.start_voice_ptt_recording()}},onPointerUp:g=>{g.preventDefault(),Hn.stop_voice_ptt_recording()},onPointerCancel:g=>{g.preventDefault(),Hn.stop_voice_ptt_recording()},children:[s.jsx(Qe,{name:Hn.voice_ptt_recording?"x":"mic",size:16}),Hn.voice_ptt_busy?"Transcribing…":Hn.voice_ptt_recording?"Recording…":"Voice"]})}),ag()?null:s.jsx("div",{className:"mono muted","data-testid":"voice-https-hint",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:og})]})]}):null,c.trim()?s.jsxs("div",{className:`status_bar ${Lc?"pulse":""}`,children:[s.jsx("strong",{children:"Run"}),":"," ",s.jsx("span",{className:"mono",children:Vr||Ln||"unknown"}),rl&&dc?s.jsxs("span",{className:"mono muted",children:[" • next in ",dc]}):null,Pr?s.jsxs("span",{className:"mono muted",children:[" • ",Pr]}):null]}):null]})]})]})}):null,s.jsxs(pl,{open:Td,title:lr||"Artifact",onClose:()=>{Ws(!1),aa(""),jo(""),Ya(!1),su(null),Ts&&(URL.revokeObjectURL(Ts),Ga(""))},actions:s.jsx("button",{className:"btn",onClick:()=>{Ws(!1),aa(""),jo(""),Ya(!1),su(null),Ts&&(URL.revokeObjectURL(Ts),Ga(""))},children:"Close"}),children:[Ka?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,mh?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:mh}):null,Ul==="image"&&Ts?s.jsx("img",{className:"runtime_preview_media",src:Ts,alt:lr||"Artifact preview"}):Ul==="audio"&&Ts?s.jsx("audio",{className:"runtime_preview_media",controls:!0,src:Ts}):Ul==="video"&&Ts?s.jsx("video",{className:"runtime_preview_media",controls:!0,src:Ts}):s.jsx(hb,{artifact:nu,text:ii||"(empty)",className:"runtime_preview_text"})]}),zo?s.jsxs(pl,{open:zo,title:"Edit schedule",onClose:()=>{Bo(!1),Dn(""),qn(!0),_i(""),zs(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Bo(!1),Dn(""),qn(!0),_i(""),zs(!1)},disabled:dt||$n,children:"Back"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await Hs({interval:Uo,apply_immediately:yr})||(Bo(!1),_i(""),zs(!1))},disabled:dt||$n||!Uo.trim(),children:"Save"})]}),children:[uo?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:kt()})]}),s.jsx("div",{className:"body mono",children:uo})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Interval"}),s.jsx("input",{className:"mono",value:Uo,onChange:g=>Dn(String(g.target.value||"")),placeholder:"20m / 1h / 0.5s / 250ms",disabled:dt||$n}),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(g=>s.jsx("button",{className:"btn",onClick:()=>Dn(g),disabled:dt||$n,children:g},g))})]}),s.jsx("div",{className:"field",children:s.jsx(I2,{checked:yr,busy:dt||$n,onChange:qn})})]}):null,fs?s.jsxs(pl,{open:fs,title:"Compact scheduled context",onClose:()=>{tr(!1),ms(""),Ir(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{tr(!1),ms(""),Ir(!1)},disabled:dt||Lr,children:"Cancel"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await $h({preserve_recent:hs,compression_mode:fo,focus:Ra})||(tr(!1),ms(""),Ir(!1))},disabled:dt||Lr,children:Lr?"Compacting…":"Compact"})]}),children:[Wo?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:kt()})]}),s.jsx("div",{className:"body mono",children:Wo})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Preserve recent turns"}),s.jsx("input",{type:"number",min:1,value:String(hs),onChange:g=>Ma(Math.max(1,parseInt(g.target.value||"6",10)||6)),disabled:dt||Lr})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Mode"}),s.jsxs("select",{value:fo,onChange:g=>rn(g.target.value),disabled:dt||Lr,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:Ra,onChange:g=>Rc(String(g.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:dt||Lr})]})]}):null,ho?s.jsxs(pl,{open:ho,title:ks==="cancel"?"Cancel run":Gs?"Suspend schedule":"Pause run",onClose:()=>{wr(!1),nr(""),is("")},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{wr(!1),nr(""),is("")},disabled:dt||ft,children:"Back"}),s.jsx("button",{className:`btn ${ks==="cancel"?"danger":"primary"}`,onClick:async()=>{is("");const g=await xu(ks,{reason:Or});if(g){is(g);return}wr(!1),nr(""),is("")},disabled:dt||ft,children:ks==="pause"?Gs?"Suspend":"Pause":"Cancel"})]}),children:[Li?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:kt()})]}),s.jsx("div",{className:"body mono",children:Li})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Reason (optional)"}),s.jsx("input",{className:"mono",value:Or,onChange:g=>nr(g.target.value),placeholder:"reason…"})]})]}):null,Xd?s.jsxs(pl,{open:Xd,title:Ph,onClose:()=>{Rs&&rr(Rs)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Oi("ledger"),t("observe"),ui(),Rs&&rr(Rs)},disabled:!c.trim(),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>Rs&&rr(Rs),disabled:ft,children:"Dismiss"}),Ki.length?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn danger",disabled:ft,onClick:()=>sc({approved:!1}),children:"Reject"}),s.jsx("button",{className:"btn",disabled:ft,onClick:()=>sc({approved:!0}),children:"Approve only"}),s.jsx("button",{className:"btn primary",disabled:!Si||ft,onClick:()=>Kd(Ki),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:Ph}),s.jsx("p",{children:$_})]}),s.jsx(xl,{status:Co||"waiting"})]}),Vn?s.jsxs("div",{className:`wait_request_card ${Su?"":"inferred"}`,children:[s.jsx("span",{children:T_}),s.jsx(Dv,{metadata:A_}),s.jsx(Mi,{text:Vn}),Su?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."}),pa.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:pa.map((g,k)=>s.jsxs("div",{className:`wait_turn_row role_${g.role.replace(/[^a-z0-9_-]+/g,"_")}`,children:[s.jsxs("div",{className:"wait_turn_meta",children:[s.jsx("strong",{children:g.role==="assistant"?"Assistant":g.role==="user"||g.role==="human"?"User":g.role}),g.ts?s.jsx("span",{className:"mono muted",children:ka(g.ts)}):null]}),s.jsx(Dv,{metadata:g.runtime_metadata}),s.jsx(Mi,{text:_t(g.text,{max_chars:1200,max_lines:10})})]},`${g.role}:${k}`))})]}):null,s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:$i(Xi,Sr)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:Lt(c.trim(),24)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Xi.current_node||String((gs==null?void 0:gs.node_id)||"—")})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:Ac(Xi)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:Xi.session_id?Lt(String(Xi.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:Lt(Rs,28)})]})]}),ku?s.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!Vn,children:[s.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(mr,{value:ic,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:[ws.map(g=>s.jsxs("div",{className:"wait_event_row",children:[s.jsxs("span",{className:"mono",children:["#",g.cursor]}),s.jsx("strong",{children:g.summary||g.effect_type||g.status||"event"}),s.jsx("span",{className:"mono muted",children:[g.node_id,g.status,ka(g.ts)].filter(Boolean).join(" · ")})]},`${g.cursor}:${g.node_id}:${g.status}`)),ws.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),Ki.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:Ki.map((g,k)=>s.jsxs("div",{className:"wait_tool_card",children:[s.jsxs("div",{className:"wait_tool_header",children:[s.jsx("strong",{children:String((g==null?void 0:g.name)||"tool")}),s.jsxs("div",{className:"wait_tool_badges",children:[s.jsx("span",{className:"chip mono warn",children:"approval"}),ib(g).map(M=>s.jsxs("span",{className:"chip mono muted",title:rb,children:[M,"~"]},M))]})]}),s.jsx("div",{className:"wait_tool_args",children:s.jsx(mr,{value:(g==null?void 0:g.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((g==null?void 0:g.name)||"tool")}:${k}`))}),Si?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 Eh(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||ft,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(mr,{value:qt||{},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:Vn||"No explicit prompt was provided. Open the ledger for context before responding."}),s.jsx(UC,{wait:qt,disabled:ft,on_submit:g=>sc({response:g})}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void Eh(c.trim(),"Cancelled from wait prompt"),disabled:!c.trim()||ft,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(mr,{value:qt||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(E1).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}mj();lj.createRoot(document.getElementById("root")).render(s.jsx(ve.StrictMode,{children:s.jsx(b3,{})}));
153
+ //# sourceMappingURL=index-9R3haXwn.js.map