@abstractframework/observer 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/assets/index-CDAE9Eth.js +150 -0
- package/dist/assets/index-CDAE9Eth.js.map +1 -0
- package/dist/assets/index-DlDs-R7p.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +3 -3
- package/dist/assets/index-9R3haXwn.js +0 -153
- package/dist/assets/index-9R3haXwn.js.map +0 -1
- package/dist/assets/index-CZE7wy2D.css +0 -1
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
var Y0=Object.defineProperty;var J0=(e,t,n)=>t in e?Y0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Vs=(e,t,n)=>J0(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 rg(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var m_={exports:{}},zd={},__={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 ty;function X0(){if(ty)return Vt;ty=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"),m=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),g=Symbol.iterator;function w(R){return R===null||typeof R!="object"?null:(R=g&&R[g]||R["@@iterator"],typeof R=="function"?R:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},k=Object.assign,j={};function N(R,Z,X){this.props=R,this.context=Z,this.refs=j,this.updater=X||x}N.prototype.isReactComponent={},N.prototype.setState=function(R,Z){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,Z,"setState")},N.prototype.forceUpdate=function(R){this.updater.enqueueForceUpdate(this,R,"forceUpdate")};function C(){}C.prototype=N.prototype;function E(R,Z,X){this.props=R,this.context=Z,this.refs=j,this.updater=X||x}var T=E.prototype=new C;T.constructor=E,k(T,N.prototype),T.isPureReactComponent=!0;var I=Array.isArray,K=Object.prototype.hasOwnProperty,U={current:null},J={key:!0,ref:!0,__self:!0,__source:!0};function Y(R,Z,X){var Q,le={},ge=null,pe=null;if(Z!=null)for(Q in Z.ref!==void 0&&(pe=Z.ref),Z.key!==void 0&&(ge=""+Z.key),Z)K.call(Z,Q)&&!J.hasOwnProperty(Q)&&(le[Q]=Z[Q]);var ye=arguments.length-2;if(ye===1)le.children=X;else if(1<ye){for(var Ne=Array(ye),Ue=0;Ue<ye;Ue++)Ne[Ue]=arguments[Ue+2];le.children=Ne}if(R&&R.defaultProps)for(Q in ye=R.defaultProps,ye)le[Q]===void 0&&(le[Q]=ye[Q]);return{$$typeof:e,type:R,key:ge,ref:pe,props:le,_owner:U.current}}function re(R,Z){return{$$typeof:e,type:R.type,key:Z,ref:R.ref,props:R.props,_owner:R._owner}}function ce(R){return typeof R=="object"&&R!==null&&R.$$typeof===e}function fe(R){var Z={"=":"=0",":":"=2"};return"$"+R.replace(/[=:]/g,function(X){return Z[X]})}var W=/\/+/g;function O(R,Z){return typeof R=="object"&&R!==null&&R.key!=null?fe(""+R.key):Z.toString(36)}function $(R,Z,X,Q,le){var ge=typeof R;(ge==="undefined"||ge==="boolean")&&(R=null);var pe=!1;if(R===null)pe=!0;else switch(ge){case"string":case"number":pe=!0;break;case"object":switch(R.$$typeof){case e:case t:pe=!0}}if(pe)return pe=R,le=le(pe),R=Q===""?"."+O(pe,0):Q,I(le)?(X="",R!=null&&(X=R.replace(W,"$&/")+"/"),$(le,Z,X,"",function(Ue){return Ue})):le!=null&&(ce(le)&&(le=re(le,X+(!le.key||pe&&pe.key===le.key?"":(""+le.key).replace(W,"$&/")+"/")+R)),Z.push(le)),1;if(pe=0,Q=Q===""?".":Q+":",I(R))for(var ye=0;ye<R.length;ye++){ge=R[ye];var Ne=Q+O(ge,ye);pe+=$(ge,Z,X,Ne,le)}else if(Ne=w(R),typeof Ne=="function")for(R=Ne.call(R),ye=0;!(ge=R.next()).done;)ge=ge.value,Ne=Q+O(ge,ye++),pe+=$(ge,Z,X,Ne,le);else if(ge==="object")throw Z=String(R),Error("Objects are not valid as a React child (found: "+(Z==="[object Object]"?"object with keys {"+Object.keys(R).join(", ")+"}":Z)+"). If you meant to render a collection of children, use an array instead.");return pe}function z(R,Z,X){if(R==null)return R;var Q=[],le=0;return $(R,Q,"","",function(ge){return Z.call(X,ge,le++)}),Q}function A(R){if(R._status===-1){var Z=R._result;Z=Z(),Z.then(function(X){(R._status===0||R._status===-1)&&(R._status=1,R._result=X)},function(X){(R._status===0||R._status===-1)&&(R._status=2,R._result=X)}),R._status===-1&&(R._status=0,R._result=Z)}if(R._status===1)return R._result.default;throw R._result}var te={current:null},P={transition:null},F={ReactCurrentDispatcher:te,ReactCurrentBatchConfig:P,ReactCurrentOwner:U};function G(){throw Error("act(...) is not supported in production builds of React.")}return Vt.Children={map:z,forEach:function(R,Z,X){z(R,function(){Z.apply(this,arguments)},X)},count:function(R){var Z=0;return z(R,function(){Z++}),Z},toArray:function(R){return z(R,function(Z){return Z})||[]},only:function(R){if(!ce(R))throw Error("React.Children.only expected to receive a single React element child.");return R}},Vt.Component=N,Vt.Fragment=n,Vt.Profiler=o,Vt.PureComponent=E,Vt.StrictMode=r,Vt.Suspense=f,Vt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=F,Vt.act=G,Vt.cloneElement=function(R,Z,X){if(R==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+R+".");var Q=k({},R.props),le=R.key,ge=R.ref,pe=R._owner;if(Z!=null){if(Z.ref!==void 0&&(ge=Z.ref,pe=U.current),Z.key!==void 0&&(le=""+Z.key),R.type&&R.type.defaultProps)var ye=R.type.defaultProps;for(Ne in Z)K.call(Z,Ne)&&!J.hasOwnProperty(Ne)&&(Q[Ne]=Z[Ne]===void 0&&ye!==void 0?ye[Ne]:Z[Ne])}var Ne=arguments.length-2;if(Ne===1)Q.children=X;else if(1<Ne){ye=Array(Ne);for(var Ue=0;Ue<Ne;Ue++)ye[Ue]=arguments[Ue+2];Q.children=ye}return{$$typeof:e,type:R.type,key:le,ref:ge,props:Q,_owner:pe}},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=Y,Vt.createFactory=function(R){var Z=Y.bind(null,R);return Z.type=R,Z},Vt.createRef=function(){return{current:null}},Vt.forwardRef=function(R){return{$$typeof:c,render:R}},Vt.isValidElement=ce,Vt.lazy=function(R){return{$$typeof:_,_payload:{_status:-1,_result:R},_init:A}},Vt.memo=function(R,Z){return{$$typeof:m,type:R,compare:Z===void 0?null:Z}},Vt.startTransition=function(R){var Z=P.transition;P.transition={};try{R()}finally{P.transition=Z}},Vt.unstable_act=G,Vt.useCallback=function(R,Z){return te.current.useCallback(R,Z)},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,Z){return te.current.useEffect(R,Z)},Vt.useId=function(){return te.current.useId()},Vt.useImperativeHandle=function(R,Z,X){return te.current.useImperativeHandle(R,Z,X)},Vt.useInsertionEffect=function(R,Z){return te.current.useInsertionEffect(R,Z)},Vt.useLayoutEffect=function(R,Z){return te.current.useLayoutEffect(R,Z)},Vt.useMemo=function(R,Z){return te.current.useMemo(R,Z)},Vt.useReducer=function(R,Z,X){return te.current.useReducer(R,Z,X)},Vt.useRef=function(R){return te.current.useRef(R)},Vt.useState=function(R){return te.current.useState(R)},Vt.useSyncExternalStore=function(R,Z,X){return te.current.useSyncExternalStore(R,Z,X)},Vt.useTransition=function(){return te.current.useTransition()},Vt.version="18.3.1",Vt}var ny;function Cf(){return ny||(ny=1,__.exports=X0()),__.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 sy;function Z0(){if(sy)return zd;sy=1;var e=Cf(),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,m){var _,g={},w=null,x=null;m!==void 0&&(w=""+m),f.key!==void 0&&(w=""+f.key),f.ref!==void 0&&(x=f.ref);for(_ in f)r.call(f,_)&&!l.hasOwnProperty(_)&&(g[_]=f[_]);if(c&&c.defaultProps)for(_ in f=c.defaultProps,f)g[_]===void 0&&(g[_]=f[_]);return{$$typeof:t,type:c,key:w,ref:x,props:g,_owner:o.current}}return zd.Fragment=n,zd.jsx=u,zd.jsxs=u,zd}var ry;function Q0(){return ry||(ry=1,m_.exports=Z0()),m_.exports}var s=Q0(),p=Cf();const ve=rg(p);var Nh={},p_={exports:{}},Fr={},g_={exports:{}},y_={};/**
|
|
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 iy;function ej(){return iy||(iy=1,(function(e){function t(P,F){var G=P.length;P.push(F);e:for(;0<G;){var R=G-1>>>1,Z=P[R];if(0<o(Z,F))P[R]=F,P[G]=Z,G=R;else break e}}function n(P){return P.length===0?null:P[0]}function r(P){if(P.length===0)return null;var F=P[0],G=P.pop();if(G!==F){P[0]=G;e:for(var R=0,Z=P.length,X=Z>>>1;R<X;){var Q=2*(R+1)-1,le=P[Q],ge=Q+1,pe=P[ge];if(0>o(le,G))ge<Z&&0>o(pe,le)?(P[R]=pe,P[ge]=G,R=ge):(P[R]=le,P[Q]=G,R=Q);else if(ge<Z&&0>o(pe,G))P[R]=pe,P[ge]=G,R=ge;else break e}}return F}function o(P,F){var G=P.sortIndex-F.sortIndex;return G!==0?G:P.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=[],m=[],_=1,g=null,w=3,x=!1,k=!1,j=!1,N=typeof setTimeout=="function"?setTimeout:null,C=typeof clearTimeout=="function"?clearTimeout:null,E=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function T(P){for(var F=n(m);F!==null;){if(F.callback===null)r(m);else if(F.startTime<=P)r(m),F.sortIndex=F.expirationTime,t(f,F);else break;F=n(m)}}function I(P){if(j=!1,T(P),!k)if(n(f)!==null)k=!0,A(K);else{var F=n(m);F!==null&&te(I,F.startTime-P)}}function K(P,F){k=!1,j&&(j=!1,C(Y),Y=-1),x=!0;var G=w;try{for(T(F),g=n(f);g!==null&&(!(g.expirationTime>F)||P&&!fe());){var R=g.callback;if(typeof R=="function"){g.callback=null,w=g.priorityLevel;var Z=R(g.expirationTime<=F);F=e.unstable_now(),typeof Z=="function"?g.callback=Z:g===n(f)&&r(f),T(F)}else r(f);g=n(f)}if(g!==null)var X=!0;else{var Q=n(m);Q!==null&&te(I,Q.startTime-F),X=!1}return X}finally{g=null,w=G,x=!1}}var U=!1,J=null,Y=-1,re=5,ce=-1;function fe(){return!(e.unstable_now()-ce<re)}function W(){if(J!==null){var P=e.unstable_now();ce=P;var F=!0;try{F=J(!0,P)}finally{F?O():(U=!1,J=null)}}else U=!1}var O;if(typeof E=="function")O=function(){E(W)};else if(typeof MessageChannel<"u"){var $=new MessageChannel,z=$.port2;$.port1.onmessage=W,O=function(){z.postMessage(null)}}else O=function(){N(W,0)};function A(P){J=P,U||(U=!0,O())}function te(P,F){Y=N(function(){P(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(P){P.callback=null},e.unstable_continueExecution=function(){k||x||(k=!0,A(K))},e.unstable_forceFrameRate=function(P){0>P||125<P?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):re=0<P?Math.floor(1e3/P):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_getFirstCallbackNode=function(){return n(f)},e.unstable_next=function(P){switch(w){case 1:case 2:case 3:var F=3;break;default:F=w}var G=w;w=F;try{return P()}finally{w=G}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(P,F){switch(P){case 1:case 2:case 3:case 4:case 5:break;default:P=3}var G=w;w=P;try{return F()}finally{w=G}},e.unstable_scheduleCallback=function(P,F,G){var R=e.unstable_now();switch(typeof G=="object"&&G!==null?(G=G.delay,G=typeof G=="number"&&0<G?R+G:R):G=R,P){case 1:var Z=-1;break;case 2:Z=250;break;case 5:Z=1073741823;break;case 4:Z=1e4;break;default:Z=5e3}return Z=G+Z,P={id:_++,callback:F,priorityLevel:P,startTime:G,expirationTime:Z,sortIndex:-1},G>R?(P.sortIndex=G,t(m,P),n(f)===null&&P===n(m)&&(j?(C(Y),Y=-1):j=!0,te(I,G-R))):(P.sortIndex=Z,t(f,P),k||x||(k=!0,A(K))),P},e.unstable_shouldYield=fe,e.unstable_wrapCallback=function(P){var F=w;return function(){var G=w;w=F;try{return P.apply(this,arguments)}finally{w=G}}}})(y_)),y_}var oy;function tj(){return oy||(oy=1,g_.exports=ej()),g_.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 ay;function nj(){if(ay)return Fr;ay=1;var e=Cf(),t=tj();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,m=/^[: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]*$/,_={},g={};function w(i){return f.call(g,i)?!0:f.call(_,i)?!1:m.test(i)?g[i]=!0:(_[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 k(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,L){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=L}var N={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(i){N[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];N[a]=new j(a,1,!1,i[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(i){N[i]=new j(i,2,!1,i.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(i){N[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){N[i]=new j(i,3,!1,i.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(i){N[i]=new j(i,3,!0,i,null,!1,!1)}),["capture","download"].forEach(function(i){N[i]=new j(i,4,!1,i,null,!1,!1)}),["cols","rows","size","span"].forEach(function(i){N[i]=new j(i,6,!1,i,null,!1,!1)}),["rowSpan","start"].forEach(function(i){N[i]=new j(i,5,!1,i.toLowerCase(),null,!1,!1)});var C=/[\-:]([a-z])/g;function E(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(C,E);N[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(C,E);N[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(C,E);N[a]=new j(a,1,!1,i,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(i){N[i]=new j(i,1,!1,i.toLowerCase(),null,!1,!1)}),N.xlinkHref=new j("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(i){N[i]=new j(i,1,!1,i.toLowerCase(),null,!0,!0)});function T(i,a,d,h){var v=N.hasOwnProperty(a)?N[a]:null;(v!==null?v.type!==0:h||!(2<a.length)||a[0]!=="o"&&a[0]!=="O"||a[1]!=="n"&&a[1]!=="N")&&(k(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 I=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,K=Symbol.for("react.element"),U=Symbol.for("react.portal"),J=Symbol.for("react.fragment"),Y=Symbol.for("react.strict_mode"),re=Symbol.for("react.profiler"),ce=Symbol.for("react.provider"),fe=Symbol.for("react.context"),W=Symbol.for("react.forward_ref"),O=Symbol.for("react.suspense"),$=Symbol.for("react.suspense_list"),z=Symbol.for("react.memo"),A=Symbol.for("react.lazy"),te=Symbol.for("react.offscreen"),P=Symbol.iterator;function F(i){return i===null||typeof i!="object"?null:(i=P&&i[P]||i["@@iterator"],typeof i=="function"?i:null)}var G=Object.assign,R;function Z(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 X=!1;function Q(i,a){if(!i||X)return"";X=!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
|
+
`),L=v.length-1,ee=b.length-1;1<=L&&0<=ee&&v[L]!==b[ee];)ee--;for(;1<=L&&0<=ee;L--,ee--)if(v[L]!==b[ee]){if(L!==1||ee!==1)do if(L--,ee--,0>ee||v[L]!==b[ee]){var se=`
|
|
37
|
+
`+v[L].replace(" at new "," at ");return i.displayName&&se.includes("<anonymous>")&&(se=se.replace("<anonymous>",i.displayName)),se}while(1<=L&&0<=ee);break}}}finally{X=!1,Error.prepareStackTrace=d}return(i=i?i.displayName||i.name:"")?Z(i):""}function le(i){switch(i.tag){case 5:return Z(i.type);case 16:return Z("Lazy");case 13:return Z("Suspense");case 19:return Z("SuspenseList");case 0:case 2:case 15:return i=Q(i.type,!1),i;case 11:return i=Q(i.type.render,!1),i;case 1:return i=Q(i.type,!0),i;default:return""}}function ge(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 J:return"Fragment";case U:return"Portal";case re:return"Profiler";case Y:return"StrictMode";case O:return"Suspense";case $:return"SuspenseList"}if(typeof i=="object")switch(i.$$typeof){case fe:return(i.displayName||"Context")+".Consumer";case ce:return(i._context.displayName||"Context")+".Provider";case W: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:ge(i.type)||"Memo";case A:a=i._payload,i=i._init;try{return ge(i(a))}catch{}}return null}function pe(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 ge(a);case 8:return a===Y?"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 Ne(i){var a=i.type;return(i=i.nodeName)&&i.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function Ue(i){var a=Ne(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(L){h=""+L,b.call(this,L)}}),Object.defineProperty(i,a,{enumerable:d.enumerable}),{getValue:function(){return h},setValue:function(L){h=""+L},stopTracking:function(){i._valueTracker=null,delete i[a]}}}}function We(i){i._valueTracker||(i._valueTracker=Ue(i))}function pt(i){if(!i)return!1;var a=i._valueTracker;if(!a)return!0;var d=a.getValue(),h="";return i&&(h=Ne(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 G({},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 Ke(i,a){a=a.checked,a!=null&&T(i,"checked",a,!1)}function ke(i,a){Ke(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 Ie(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 qe(i,a){if(a.dangerouslySetInnerHTML!=null)throw Error(n(91));return G({},a,{value:void 0,defaultValue:void 0,children:""+i._wrapperState.initialValue})}function zt(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 en(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 bn(i){var a=i.textContent;a===i._wrapperState.initialValue&&a!==""&&a!==null&&(i.value=a)}function Wt(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"?Wt(a):i==="http://www.w3.org/2000/svg"&&a==="foreignObject"?"http://www.w3.org/1999/xhtml":i}var Sn,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(Sn=Sn||document.createElement("div"),Sn.innerHTML="<svg>"+a.valueOf().toString()+"</svg>",a=Sn.firstChild;i.firstChild;)i.removeChild(i.firstChild);for(;a.firstChild;)i.appendChild(a.firstChild)}});function Ot(i,a){if(a){var d=i.firstChild;if(d&&d===i.lastChild&&d.nodeType===3){d.nodeValue=a;return}}i.textContent=a}var pn={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},Bn=["Webkit","ms","Moz","O"];Object.keys(pn).forEach(function(i){Bn.forEach(function(a){a=a+i.charAt(0).toUpperCase()+i.substring(1),pn[a]=pn[i]})});function An(i,a,d){return a==null||typeof a=="boolean"||a===""?"":d||typeof a!="number"||a===0||pn.hasOwnProperty(i)&&pn[i]?(""+a).trim():a+"px"}function gn(i,a){i=i.style;for(var d in a)if(a.hasOwnProperty(d)){var h=d.indexOf("--")===0,v=An(d,a[d],h);d==="float"&&(d="cssFloat"),h?i.setProperty(d,v):i[d]=v}}var In=G({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 wn(i,a){if(a){if(In[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 Kn=null;function ks(i){return i=i.target||i.srcElement||window,i.correspondingUseElement&&(i=i.correspondingUseElement),i.nodeType===3?i.parentNode:i}var Nr=null,On=null,ae=null;function je(i){if(i=Uo(i)){if(typeof Nr!="function")throw Error(n(280));var a=i.stateNode;a&&(a=Ma(a),Nr(i.stateNode,i.type,a))}}function Ye(i){On?ae?ae.push(i):ae=[i]:On=i}function Ge(){if(On){var i=On,a=ae;if(ae=On=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 jt(i,a,d){if(Et)return i(a,d);Et=!0;try{return rt(i,a,d)}finally{Et=!1,(On!==null||ae!==null)&&(ct(),Ge())}}function Kt(i,a){var d=i.stateNode;if(d===null)return null;var h=Ma(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 qt(i,a,d,h,v,b,L,ee,se){var we=Array.prototype.slice.call(arguments,3);try{a.apply(d,we)}catch($e){this.onError($e)}}var Pt=!1,At=null,$t=!1,De=null,on={onError:function(i){Pt=!0,At=i}};function dt(i,a,d,h,v,b,L,ee,se){Pt=!1,At=null,qt.apply(on,arguments)}function tn(i,a,d,h,v,b,L,ee,se){if(dt.apply(this,arguments),Pt){if(Pt){var we=At;Pt=!1,At=null}else throw Error(n(198));$t||($t=!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 Un(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 an(i){if(ft(i)!==i)throw Error(n(188))}function Ys(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 an(v),i;if(b===h)return an(v),a;b=b.sibling}throw Error(n(188))}if(d.return!==h.return)d=v,h=b;else{for(var L=!1,ee=v.child;ee;){if(ee===d){L=!0,d=v,h=b;break}if(ee===h){L=!0,h=v,d=b;break}ee=ee.sibling}if(!L){for(ee=b.child;ee;){if(ee===d){L=!0,d=b,h=v;break}if(ee===h){L=!0,h=b,d=v;break}ee=ee.sibling}if(!L)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=Ys(i),i!==null?Wr(i):null}function Wr(i){if(i.tag===5||i.tag===6)return i;for(i=i.child;i!==null;){var a=Wr(i);if(a!==null)return a;i=i.sibling}return null}var dr=t.unstable_scheduleCallback,ii=t.unstable_cancelCallback,oi=t.unstable_shouldYield,Ps=t.unstable_requestPaint,ue=t.unstable_now,fr=t.unstable_getCurrentPriorityLevel,Vi=t.unstable_ImmediatePriority,hr=t.unstable_UserBlockingPriority,Cr=t.unstable_NormalPriority,qr=t.unstable_LowPriority,it=t.unstable_IdlePriority,cn=null,Ds=null;function Hr(i){if(Ds&&typeof Ds.onCommitFiberRoot=="function")try{Ds.onCommitFiberRoot(cn,i,void 0,(i.current.flags&128)===128)}catch{}}var rs=Math.clz32?Math.clz32:$o,Eo=Math.log,Ao=Math.LN2;function $o(i){return i>>>=0,i===0?32:31-(Eo(i)/Ao|0)|0}var Pn=64,mr=4194304;function Hn(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 Gi(i,a){var d=i.pendingLanes;if(d===0)return 0;var h=0,v=i.suspendedLanes,b=i.pingedLanes,L=d&268435455;if(L!==0){var ee=L&~v;ee!==0?h=Hn(ee):(b&=L,b!==0&&(h=Hn(b)))}else L=d&~v,L!==0?h=Hn(L):b!==0&&(h=Hn(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 ai(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 L=31-rs(b),ee=1<<L,se=v[L];se===-1?((ee&d)===0||(ee&h)!==0)&&(v[L]=ai(ee,a)):se<=a&&(i.expiredLanes|=ee),b&=~ee}}function Fs(i){return i=i.pendingLanes&-1073741825,i!==0?i:i&1073741824?1073741824:0}function hs(){var i=Pn;return Pn<<=1,(Pn&4194240)===0&&(Pn=64),i}function Js(i){for(var a=[],d=0;31>d;d++)a.push(i);return a}function ms(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 da(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 Ki(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 ln=0;function fa(i){return i&=-i,1<i?4<i?(i&268435455)!==0?16:536870912:4:1}var uc,To,_s,Er,Ar,Yi=!1,_r=[],Ss=null,pr=null,$r=null,Xs=new Map,Si=new Map,is=[],Tr="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 ha(i,a){switch(i){case"focusin":case"focusout":Ss=null;break;case"dragenter":case"dragleave":pr=null;break;case"mouseover":case"mouseout":$r=null;break;case"pointerover":case"pointerout":Xs.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":Si.delete(a.pointerId)}}function gr(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=Uo(a),a!==null&&To(a)),i):(i.eventSystemFlags|=h,a=i.targetContainers,v!==null&&a.indexOf(v)===-1&&a.push(v),i)}function Ji(i,a,d,h,v){switch(a){case"focusin":return Ss=gr(Ss,i,a,d,h,v),!0;case"dragenter":return pr=gr(pr,i,a,d,h,v),!0;case"mouseover":return $r=gr($r,i,a,d,h,v),!0;case"pointerover":var b=v.pointerId;return Xs.set(b,gr(Xs.get(b)||null,i,a,d,h,v)),!0;case"gotpointercapture":return b=v.pointerId,Si.set(b,gr(Si.get(b)||null,i,a,d,h,v)),!0}return!1}function dc(i){var a=Gr(i.target);if(a!==null){var d=ft(a);if(d!==null){if(a=d.tag,a===13){if(a=Un(d),a!==null){i.blockedOn=a,Ar(i.priority,function(){_s(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 Ni(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);Kn=h,d.target.dispatchEvent(h),Kn=null}else return a=Uo(d),a!==null&&To(a),i.blockedOn=d,!1;a.shift()}return!0}function Zs(i,a,d){Ni(i)&&d.delete(a)}function $u(){Yi=!1,Ss!==null&&Ni(Ss)&&(Ss=null),pr!==null&&Ni(pr)&&(pr=null),$r!==null&&Ni($r)&&($r=null),Xs.forEach(Zs),Si.forEach(Zs)}function Qs(i,a){i.blockedOn===a&&(i.blockedOn=null,Yi||(Yi=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,$u)))}function Xi(i){function a(v){return Qs(v,i)}if(0<_r.length){Qs(_r[0],i);for(var d=1;d<_r.length;d++){var h=_r[d];h.blockedOn===i&&(h.blockedOn=null)}}for(Ss!==null&&Qs(Ss,i),pr!==null&&Qs(pr,i),$r!==null&&Qs($r,i),Xs.forEach(a),Si.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);)dc(d),d.blockedOn===null&&is.shift()}var er=I.ReactCurrentBatchConfig,Mo=!0;function li(i,a,d,h){var v=ln,b=er.transition;er.transition=null;try{ln=1,ci(i,a,d,h)}finally{ln=v,er.transition=b}}function al(i,a,d,h){var v=ln,b=er.transition;er.transition=null;try{ln=4,ci(i,a,d,h)}finally{ln=v,er.transition=b}}function ci(i,a,d,h){if(Mo){var v=ie(i,a,d,h);if(v===null)Yu(i,a,h,B,d),ha(i,h);else if(Ji(v,i,a,d,h))h.stopPropagation();else if(ha(i,h),a&4&&-1<Tr.indexOf(i)){for(;v!==null;){var b=Uo(v);if(b!==null&&uc(b),b=ie(i,a,d,h),b===null&&Yu(i,a,h,B,d),b===v)break;v=b}v!==null&&h.stopPropagation()}else Yu(i,a,h,null,d)}}var B=null;function ie(i,a,d,h){if(B=null,i=ks(h),i=Gr(i),i!==null)if(a=ft(i),a===null)i=null;else if(d=a.tag,d===13){if(i=Un(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 B=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(fr()){case Vi:return 1;case hr:return 4;case Cr:case qr:return 16;case it:return 536870912;default:return 16}default:return 16}}var Se=null,Ee=null,He=null;function Qe(){if(He)return He;var i,a=Ee,d=a.length,h,v="value"in Se?Se.value:Se.textContent,b=v.length;for(i=0;i<d&&a[i]===v[i];i++);var L=d-i;for(h=1;h<=L&&a[d-h]===v[b-h];h++);return He=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 Dt(){return!1}function Xt(i){function a(d,h,v,b,L){this._reactName=d,this._targetInst=v,this.type=h,this.nativeEvent=b,this.target=L,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:Dt,this.isPropagationStopped=Dt,this}return G(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 Xn={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(i){return i.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Bt=Xt(Xn),un=G({},Xn,{view:0,detail:0}),vn=Xt(un),jn,ps,Ns,yr=G({},un,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Iu,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"?(jn=i.screenX-Ns.screenX,ps=i.screenY-Ns.screenY):ps=jn=0,Ns=i),jn)},movementY:function(i){return"movementY"in i?i.movementY:ps}}),Ro=Xt(yr),Lo=G({},yr,{dataTransfer:0}),ll=Xt(Lo),fc=G({},un,{relatedTarget:0}),hc=Xt(fc),mc=G({},Xn,{animationName:0,elapsedTime:0,pseudoElement:0}),Tu=Xt(mc),_c=G({},Xn,{clipboardData:function(i){return"clipboardData"in i?i.clipboardData:window.clipboardData}}),pc=Xt(_c),gc=G({},Xn,{data:0}),Mu=Xt(gc),Io={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},If={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"},Ru={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Lu(i){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(i):(i=Ru[i])?!!a[i]:!1}function Iu(){return Lu}var Ou=G({},un,{key:function(i){if(i.key){var a=Io[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"?If[i.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Iu,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}}),Pu=Xt(Ou),nn=G({},yr,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),yc=Xt(nn),zm=G({},un,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Iu}),Du=Xt(zm),Bm=G({},Xn,{propertyName:0,elapsedTime:0,pseudoElement:0}),Fu=Xt(Bm),Um=G({},yr,{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}),tr=Xt(Um),Zi=[9,13,27,32],wc=c&&"CompositionEvent"in window,cl=null;c&&"documentMode"in document&&(cl=document.documentMode);var ma=c&&"TextEvent"in window&&!cl,vc=c&&(!wc||cl&&8<cl&&11>=cl),_a=" ",zu=!1;function Of(i,a){switch(i){case"keyup":return Zi.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Pf(i){return i=i.detail,typeof i=="object"&&"data"in i?i.data:null}var pa=!1;function Df(i,a){switch(i){case"compositionend":return Pf(a);case"keypress":return a.which!==32?null:(zu=!0,_a);case"textInput":return i=a.data,i===_a&&zu?null:i;default:return null}}function Wm(i,a){if(pa)return i==="compositionend"||!wc&&Of(i,a)?(i=Qe(),He=Ee=Se=null,pa=!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 vc&&a.locale!=="ko"?null:a.data;default:return null}}var Ff={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 zf(i){var a=i&&i.nodeName&&i.nodeName.toLowerCase();return a==="input"?!!Ff[i.type]:a==="textarea"}function Bu(i,a,d,h){Ye(h),a=kc(a,"onChange"),0<a.length&&(d=new Bt("onChange","change",null,d,h),i.push({event:d,listeners:a}))}var ga=null,Oo=null;function ya(i){bc(i,0)}function Qi(i){var a=Kr(i);if(pt(a))return i}function wa(i,a){if(i==="change")return a}var va=!1;if(c){var xa;if(c){var ul="oninput"in document;if(!ul){var Uu=document.createElement("div");Uu.setAttribute("oninput","return;"),ul=typeof Uu.oninput=="function"}xa=ul}else xa=!1;va=xa&&(!document.documentMode||9<document.documentMode)}function ba(){ga&&(ga.detachEvent("onpropertychange",Wu),Oo=ga=null)}function Wu(i){if(i.propertyName==="value"&&Qi(Oo)){var a=[];Bu(a,Oo,i,ks(i)),jt(ya,a)}}function dl(i,a,d){i==="focusin"?(ba(),ga=a,Oo=d,ga.attachEvent("onpropertychange",Wu)):i==="focusout"&&ba()}function fl(i){if(i==="selectionchange"||i==="keyup"||i==="keydown")return Qi(Oo)}function qm(i,a){if(i==="click")return Qi(a)}function qu(i,a){if(i==="input"||i==="change")return Qi(a)}function Hm(i,a){return i===a&&(i!==0||1/i===1/a)||i!==i&&a!==a}var Vr=typeof Object.is=="function"?Object.is:Hm;function eo(i,a){if(Vr(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)||!Vr(i[v],a[v]))return!1}return!0}function ui(i){for(;i&&i.firstChild;)i=i.firstChild;return i}function Po(i,a){var d=ui(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=ui(d)}}function Bf(i,a){return i&&a?i===a?!0:i&&i.nodeType===3?!1:a&&a.nodeType===3?Bf(i,a.parentNode):"contains"in i?i.contains(a):i.compareDocumentPosition?!!(i.compareDocumentPosition(a)&16):!1:!1}function hl(){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 Hu(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 Vu(i){var a=hl(),d=i.focusedElem,h=i.selectionRange;if(a!==d&&d&&d.ownerDocument&&Bf(d.ownerDocument.documentElement,d)){if(h!==null&&Hu(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=Po(d,b);var L=Po(d,h);v&&L&&(i.rangeCount!==1||i.anchorNode!==v.node||i.anchorOffset!==v.offset||i.focusNode!==L.node||i.focusOffset!==L.offset)&&(a=a.createRange(),a.setStart(v.node,v.offset),i.removeAllRanges(),b>h?(i.addRange(a),i.extend(L.node,L.offset)):(a.setEnd(L.node,L.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 ml=c&&"documentMode"in document&&11>=document.documentMode,gs=null,di=null,to=null,no=!1;function xc(i,a,d){var h=d.window===d?d.document:d.nodeType===9?d:d.ownerDocument;no||gs==null||gs!==Fe(h)||(h=gs,"selectionStart"in h&&Hu(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}),to&&eo(to,h)||(to=h,h=kc(di,"onSelect"),0<h.length&&(a=new Bt("onSelect","select",null,a,d),i.push({event:a,listeners:h}),a.target=gs)))}function so(i,a){var d={};return d[i.toLowerCase()]=a.toLowerCase(),d["Webkit"+i]="webkit"+a,d["Moz"+i]="moz"+a,d}var wr={animationend:so("Animation","AnimationEnd"),animationiteration:so("Animation","AnimationIteration"),animationstart:so("Animation","AnimationStart"),transitionend:so("Transition","TransitionEnd")},ja={},ka={};c&&(ka=document.createElement("div").style,"AnimationEvent"in window||(delete wr.animationend.animation,delete wr.animationiteration.animation,delete wr.animationstart.animation),"TransitionEvent"in window||delete wr.transitionend.transition);function Ci(i){if(ja[i])return ja[i];if(!wr[i])return i;var a=wr[i],d;for(d in a)if(a.hasOwnProperty(d)&&d in ka)return ja[i]=a[d];return i}var Ei=Ci("animationend"),zs=Ci("animationiteration"),ro=Ci("animationstart"),Do=Ci("transitionend"),_l=new Map,io="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 fi(i,a){_l.set(i,a),l(a,[i])}for(var Sa=0;Sa<io.length;Sa++){var Mr=io[Sa],oo=Mr.toLowerCase(),hi=Mr[0].toUpperCase()+Mr.slice(1);fi(oo,"on"+hi)}fi(Ei,"onAnimationEnd"),fi(zs,"onAnimationIteration"),fi(ro,"onAnimationStart"),fi("dblclick","onDoubleClick"),fi("focusin","onFocus"),fi("focusout","onBlur"),fi(Do,"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 Na="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(" "),pl=new Set("cancel close invalid load scroll toggle".split(" ").concat(Na));function Gu(i,a,d){var h=i.type||"unknown-event";i.currentTarget=d,tn(h,a,void 0,i),i.currentTarget=null}function bc(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 L=h.length-1;0<=L;L--){var ee=h[L],se=ee.instance,we=ee.currentTarget;if(ee=ee.listener,se!==b&&v.isPropagationStopped())break e;Gu(v,ee,we),b=se}else for(L=0;L<h.length;L++){if(ee=h[L],se=ee.instance,we=ee.currentTarget,ee=ee.listener,se!==b&&v.isPropagationStopped())break e;Gu(v,ee,we),b=se}}}if($t)throw i=De,$t=!1,De=null,i}function Nn(i,a){var d=a[Bo];d===void 0&&(d=a[Bo]=new Set);var h=i+"__bubble";d.has(h)||(Ku(a,i,2,!1),d.add(h))}function jc(i,a,d){var h=0;a&&(h|=4),Ku(d,i,h,a)}var gl="_reactListening"+Math.random().toString(36).slice(2);function yl(i){if(!i[gl]){i[gl]=!0,r.forEach(function(d){d!=="selectionchange"&&(pl.has(d)||jc(d,!1,i),jc(d,!0,i))});var a=i.nodeType===9?i:i.ownerDocument;a===null||a[gl]||(a[gl]=!0,jc("selectionchange",!1,a))}}function Ku(i,a,d,h){switch(be(a)){case 1:var v=li;break;case 4:v=al;break;default:v=ci}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 Yu(i,a,d,h,v){var b=h;if((a&1)===0&&(a&2)===0&&h!==null)e:for(;;){if(h===null)return;var L=h.tag;if(L===3||L===4){var ee=h.stateNode.containerInfo;if(ee===v||ee.nodeType===8&&ee.parentNode===v)break;if(L===4)for(L=h.return;L!==null;){var se=L.tag;if((se===3||se===4)&&(se=L.stateNode.containerInfo,se===v||se.nodeType===8&&se.parentNode===v))return;L=L.return}for(;ee!==null;){if(L=Gr(ee),L===null)return;if(se=L.tag,se===5||se===6){h=b=L;continue e}ee=ee.parentNode}}h=h.return}jt(function(){var we=b,$e=ks(d),Me=[];e:{var Ce=_l.get(i);if(Ce!==void 0){var Je=Bt,nt=i;switch(i){case"keypress":if(ot(d)===0)break e;case"keydown":case"keyup":Je=Pu;break;case"focusin":nt="focus",Je=hc;break;case"focusout":nt="blur",Je=hc;break;case"beforeblur":case"afterblur":Je=hc;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":Je=Ro;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Je=ll;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Je=Du;break;case Ei:case zs:case ro:Je=Tu;break;case Do:Je=Fu;break;case"scroll":Je=vn;break;case"wheel":Je=tr;break;case"copy":case"cut":case"paste":Je=pc;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Je=yc}var st=(a&4)!==0,ts=!st&&i==="scroll",de=st?Ce!==null?Ce+"Capture":null:Ce;st=[];for(var oe=we,me;oe!==null;){me=oe;var Pe=me.stateNode;if(me.tag===5&&Pe!==null&&(me=Pe,de!==null&&(Pe=Kt(oe,de),Pe!=null&&st.push(Ca(oe,Pe,me)))),ts)break;oe=oe.return}0<st.length&&(Ce=new Je(Ce,nt,null,d,$e),Me.push({event:Ce,listeners:st}))}}if((a&7)===0){e:{if(Ce=i==="mouseover"||i==="pointerover",Je=i==="mouseout"||i==="pointerout",Ce&&d!==Kn&&(nt=d.relatedTarget||d.fromElement)&&(Gr(nt)||nt[vr]))break e;if((Je||Ce)&&(Ce=$e.window===$e?$e:(Ce=$e.ownerDocument)?Ce.defaultView||Ce.parentWindow:window,Je?(nt=d.relatedTarget||d.toElement,Je=we,nt=nt?Gr(nt):null,nt!==null&&(ts=ft(nt),nt!==ts||nt.tag!==5&&nt.tag!==6)&&(nt=null)):(Je=null,nt=we),Je!==nt)){if(st=Ro,Pe="onMouseLeave",de="onMouseEnter",oe="mouse",(i==="pointerout"||i==="pointerover")&&(st=yc,Pe="onPointerLeave",de="onPointerEnter",oe="pointer"),ts=Je==null?Ce:Kr(Je),me=nt==null?Ce:Kr(nt),Ce=new st(Pe,oe+"leave",Je,d,$e),Ce.target=ts,Ce.relatedTarget=me,Pe=null,Gr($e)===we&&(st=new st(de,oe+"enter",nt,d,$e),st.target=me,st.relatedTarget=ts,Pe=st),ts=Pe,Je&&nt)t:{for(st=Je,de=nt,oe=0,me=st;me;me=Fo(me))oe++;for(me=0,Pe=de;Pe;Pe=Fo(Pe))me++;for(;0<oe-me;)st=Fo(st),oe--;for(;0<me-oe;)de=Fo(de),me--;for(;oe--;){if(st===de||de!==null&&st===de.alternate)break t;st=Fo(st),de=Fo(de)}st=null}else st=null;Je!==null&&Uf(Me,Ce,Je,st,!1),nt!==null&&ts!==null&&Uf(Me,ts,nt,st,!0)}}e:{if(Ce=we?Kr(we):window,Je=Ce.nodeName&&Ce.nodeName.toLowerCase(),Je==="select"||Je==="input"&&Ce.type==="file")var at=wa;else if(zf(Ce))if(va)at=qu;else{at=fl;var gt=dl}else(Je=Ce.nodeName)&&Je.toLowerCase()==="input"&&(Ce.type==="checkbox"||Ce.type==="radio")&&(at=qm);if(at&&(at=at(i,we))){Bu(Me,at,d,$e);break e}gt&>(i,Ce,we),i==="focusout"&&(gt=Ce._wrapperState)&>.controlled&&Ce.type==="number"&&ht(Ce,"number",Ce.value)}switch(gt=we?Kr(we):window,i){case"focusin":(zf(gt)||gt.contentEditable==="true")&&(gs=gt,di=we,to=null);break;case"focusout":to=di=gs=null;break;case"mousedown":no=!0;break;case"contextmenu":case"mouseup":case"dragend":no=!1,xc(Me,d,$e);break;case"selectionchange":if(ml)break;case"keydown":case"keyup":xc(Me,d,$e)}var yt;if(wc)e:{switch(i){case"compositionstart":var Nt="onCompositionStart";break e;case"compositionend":Nt="onCompositionEnd";break e;case"compositionupdate":Nt="onCompositionUpdate";break e}Nt=void 0}else pa?Of(i,d)&&(Nt="onCompositionEnd"):i==="keydown"&&d.keyCode===229&&(Nt="onCompositionStart");Nt&&(vc&&d.locale!=="ko"&&(pa||Nt!=="onCompositionStart"?Nt==="onCompositionEnd"&&pa&&(yt=Qe()):(Se=$e,Ee="value"in Se?Se.value:Se.textContent,pa=!0)),gt=kc(we,Nt),0<gt.length&&(Nt=new Mu(Nt,i,null,d,$e),Me.push({event:Nt,listeners:gt}),yt?Nt.data=yt:(yt=Pf(d),yt!==null&&(Nt.data=yt)))),(yt=ma?Df(i,d):Wm(i,d))&&(we=kc(we,"onBeforeInput"),0<we.length&&($e=new Mu("onBeforeInput","beforeinput",null,d,$e),Me.push({event:$e,listeners:we}),$e.data=yt))}bc(Me,a)})}function Ca(i,a,d){return{instance:i,listener:a,currentTarget:d}}function kc(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(Ca(i,b,v)),b=Kt(i,a),b!=null&&h.push(Ca(i,b,v))),i=i.return}return h}function Fo(i){if(i===null)return null;do i=i.return;while(i&&i.tag!==5);return i||null}function Uf(i,a,d,h,v){for(var b=a._reactName,L=[];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&&L.unshift(Ca(d,se,ee))):v||(se=Kt(d,b),se!=null&&L.push(Ca(d,se,ee)))),d=d.return}L.length!==0&&i.push({event:a,listeners:L})}var Wf=/\r\n?/g,Vm=/\u0000|\uFFFD/g;function Ju(i){return(typeof i=="string"?i:""+i).replace(Wf,`
|
|
38
|
+
`).replace(Vm,"")}function ao(i,a,d){if(a=Ju(a),Ju(i)!==a&&d)throw Error(n(425))}function Sc(){}var zo=null,wl=null;function Ea(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 Nc=typeof setTimeout=="function"?setTimeout:void 0,Aa=typeof clearTimeout=="function"?clearTimeout:void 0,qf=typeof Promise=="function"?Promise:void 0,Cc=typeof queueMicrotask=="function"?queueMicrotask:typeof qf<"u"?function(i){return qf.resolve(null).then(i).catch(Gm)}:Nc;function Gm(i){setTimeout(function(){throw i})}function lo(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),Xi(a);return}h--}else d!=="$"&&d!=="$?"&&d!=="$!"||h++;d=v}while(d);Xi(a)}function co(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 vl(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 $a=Math.random().toString(36).slice(2),ys="__reactFiber$"+$a,Ta="__reactProps$"+$a,vr="__reactContainer$"+$a,Bo="__reactEvents$"+$a,Hf="__reactListeners$"+$a,Xu="__reactHandles$"+$a;function Gr(i){var a=i[ys];if(a)return a;for(var d=i.parentNode;d;){if(a=d[vr]||d[ys]){if(d=a.alternate,a.child!==null||d!==null&&d.child!==null)for(i=vl(i);i!==null;){if(d=i[ys])return d;i=vl(i)}return a}i=d,d=i.parentNode}return null}function Uo(i){return i=i[ys]||i[vr],!i||i.tag!==5&&i.tag!==6&&i.tag!==13&&i.tag!==3?null:i}function Kr(i){if(i.tag===5||i.tag===6)return i.stateNode;throw Error(n(33))}function Ma(i){return i[Ta]||null}var Zu=[],uo=-1;function Ai(i){return{current:i}}function En(i){0>uo||(i.current=Zu[uo],Zu[uo]=null,uo--)}function Cn(i,a){uo++,Zu[uo]=i.current,i.current=a}var xr={},fn=Ai(xr),ws=Ai(!1),$i=xr;function Ra(i,a){var d=i.type.contextTypes;if(!d)return xr;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 nr(i){return i=i.childContextTypes,i!=null}function La(){En(ws),En(fn)}function Vf(i,a,d){if(fn.current!==xr)throw Error(n(168));Cn(fn,a),Cn(ws,d)}function xl(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,pe(i)||"Unknown",v));return G({},d,h)}function bl(i){return i=(i=i.stateNode)&&i.__reactInternalMemoizedMergedChildContext||xr,$i=fn.current,Cn(fn,i),Cn(ws,ws.current),!0}function jl(i,a,d){var h=i.stateNode;if(!h)throw Error(n(169));d?(i=xl(i,a,$i),h.__reactInternalMemoizedMergedChildContext=i,En(ws),En(fn),Cn(fn,i)):En(ws),Cn(ws,d)}var mi=null,kl=!1,Qu=!1;function ed(i){mi===null?mi=[i]:mi.push(i)}function Gf(i){kl=!0,ed(i)}function Ti(){if(!Qu&&mi!==null){Qu=!0;var i=0,a=ln;try{var d=mi;for(ln=1;i<d.length;i++){var h=d[i];do h=h(!0);while(h!==null)}mi=null,kl=!1}catch(v){throw mi!==null&&(mi=mi.slice(i+1)),dr(Vi,Ti),v}finally{ln=a,Qu=!1}}return null}var Ia=[],Wo=0,qo=null,Ec=0,Rr=[],Lr=0,Ho=null,Yr=1,Mi="";function Ri(i,a){Ia[Wo++]=Ec,Ia[Wo++]=qo,qo=i,Ec=a}function Kf(i,a,d){Rr[Lr++]=Yr,Rr[Lr++]=Mi,Rr[Lr++]=Ho,Ho=i;var h=Yr;i=Mi;var v=32-rs(h)-1;h&=~(1<<v),d+=1;var b=32-rs(a)+v;if(30<b){var L=v-v%5;b=(h&(1<<L)-1).toString(32),h>>=L,v-=L,Yr=1<<32-rs(a)+v|d<<v|h,Mi=b+i}else Yr=1<<b|d<<v|h,Mi=i}function Ac(i){i.return!==null&&(Ri(i,1),Kf(i,1,0))}function td(i){for(;i===qo;)qo=Ia[--Wo],Ia[Wo]=null,Ec=Ia[--Wo],Ia[Wo]=null;for(;i===Ho;)Ho=Rr[--Lr],Rr[Lr]=null,Mi=Rr[--Lr],Rr[Lr]=null,Yr=Rr[--Lr],Rr[Lr]=null}var Bs=null,Te=null,Tt=!1,br=null;function nd(i,a){var d=xi(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 $c(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,Bs=i,Te=co(a.firstChild),!0):!1;case 6:return a=i.pendingProps===""||a.nodeType!==3?null:a,a!==null?(i.stateNode=a,Bs=i,Te=null,!0):!1;case 13:return a=a.nodeType!==8?null:a,a!==null?(d=Ho!==null?{id:Yr,overflow:Mi}:null,i.memoizedState={dehydrated:a,treeContext:d,retryLane:1073741824},d=xi(18,null,null,0),d.stateNode=a,d.return=i,i.child=d,Bs=i,Te=null,!0):!1;default:return!1}}function sd(i){return(i.mode&1)!==0&&(i.flags&128)===0}function rd(i){if(Tt){var a=Te;if(a){var d=a;if(!$c(i,a)){if(sd(i))throw Error(n(418));a=co(d.nextSibling);var h=Bs;a&&$c(i,a)?nd(h,d):(i.flags=i.flags&-4097|2,Tt=!1,Bs=i)}}else{if(sd(i))throw Error(n(418));i.flags=i.flags&-4097|2,Tt=!1,Bs=i}}}function Yf(i){for(i=i.return;i!==null&&i.tag!==5&&i.tag!==3&&i.tag!==13;)i=i.return;Bs=i}function Sl(i){if(i!==Bs)return!1;if(!Tt)return Yf(i),Tt=!0,!1;var a;if((a=i.tag!==3)&&!(a=i.tag!==5)&&(a=i.type,a=a!=="head"&&a!=="body"&&!Ea(i.type,i.memoizedProps)),a&&(a=Te)){if(sd(i))throw id(),Error(n(418));for(;a;)nd(i,a),a=co(a.nextSibling)}if(Yf(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){Te=co(i.nextSibling);break e}a--}else d!=="$"&&d!=="$!"&&d!=="$?"||a++}i=i.nextSibling}Te=null}}else Te=Bs?co(i.stateNode.nextSibling):null;return!0}function id(){for(var i=Te;i;)i=co(i.nextSibling)}function Oa(){Te=Bs=null,Tt=!1}function Pa(i){br===null?br=[i]:br.push(i)}var Us=I.ReactCurrentBatchConfig;function Ft(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(L){var ee=v.refs;L===null?delete ee[b]:ee[b]=L},a._stringRef=b,a)}if(typeof i!="string")throw Error(n(284));if(!d._owner)throw Error(n(290,i))}return i}function Zn(i,a){throw i=Object.prototype.toString.call(a),Error(n(31,i==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":i))}function Tc(i){var a=i._init;return a(i._payload)}function od(i){function a(de,oe){if(i){var me=de.deletions;me===null?(de.deletions=[oe],de.flags|=16):me.push(oe)}}function d(de,oe){if(!i)return null;for(;oe!==null;)a(de,oe),oe=oe.sibling;return null}function h(de,oe){for(de=new Map;oe!==null;)oe.key!==null?de.set(oe.key,oe):de.set(oe.index,oe),oe=oe.sibling;return de}function v(de,oe){return de=Ya(de,oe),de.index=0,de.sibling=null,de}function b(de,oe,me){return de.index=me,i?(me=de.alternate,me!==null?(me=me.index,me<oe?(de.flags|=2,oe):me):(de.flags|=2,oe)):(de.flags|=1048576,oe)}function L(de){return i&&de.alternate===null&&(de.flags|=2),de}function ee(de,oe,me,Pe){return oe===null||oe.tag!==6?(oe=l_(me,de.mode,Pe),oe.return=de,oe):(oe=v(oe,me),oe.return=de,oe)}function se(de,oe,me,Pe){var at=me.type;return at===J?$e(de,oe,me.props.children,Pe,me.key):oe!==null&&(oe.elementType===at||typeof at=="object"&&at!==null&&at.$$typeof===A&&Tc(at)===oe.type)?(Pe=v(oe,me.props),Pe.ref=Ft(de,oe,me),Pe.return=de,Pe):(Pe=yh(me.type,me.key,me.props,null,de.mode,Pe),Pe.ref=Ft(de,oe,me),Pe.return=de,Pe)}function we(de,oe,me,Pe){return oe===null||oe.tag!==4||oe.stateNode.containerInfo!==me.containerInfo||oe.stateNode.implementation!==me.implementation?(oe=c_(me,de.mode,Pe),oe.return=de,oe):(oe=v(oe,me.children||[]),oe.return=de,oe)}function $e(de,oe,me,Pe,at){return oe===null||oe.tag!==7?(oe=Wl(me,de.mode,Pe,at),oe.return=de,oe):(oe=v(oe,me),oe.return=de,oe)}function Me(de,oe,me){if(typeof oe=="string"&&oe!==""||typeof oe=="number")return oe=l_(""+oe,de.mode,me),oe.return=de,oe;if(typeof oe=="object"&&oe!==null){switch(oe.$$typeof){case K:return me=yh(oe.type,oe.key,oe.props,null,de.mode,me),me.ref=Ft(de,null,oe),me.return=de,me;case U:return oe=c_(oe,de.mode,me),oe.return=de,oe;case A:var Pe=oe._init;return Me(de,Pe(oe._payload),me)}if(xe(oe)||F(oe))return oe=Wl(oe,de.mode,me,null),oe.return=de,oe;Zn(de,oe)}return null}function Ce(de,oe,me,Pe){var at=oe!==null?oe.key:null;if(typeof me=="string"&&me!==""||typeof me=="number")return at!==null?null:ee(de,oe,""+me,Pe);if(typeof me=="object"&&me!==null){switch(me.$$typeof){case K:return me.key===at?se(de,oe,me,Pe):null;case U:return me.key===at?we(de,oe,me,Pe):null;case A:return at=me._init,Ce(de,oe,at(me._payload),Pe)}if(xe(me)||F(me))return at!==null?null:$e(de,oe,me,Pe,null);Zn(de,me)}return null}function Je(de,oe,me,Pe,at){if(typeof Pe=="string"&&Pe!==""||typeof Pe=="number")return de=de.get(me)||null,ee(oe,de,""+Pe,at);if(typeof Pe=="object"&&Pe!==null){switch(Pe.$$typeof){case K:return de=de.get(Pe.key===null?me:Pe.key)||null,se(oe,de,Pe,at);case U:return de=de.get(Pe.key===null?me:Pe.key)||null,we(oe,de,Pe,at);case A:var gt=Pe._init;return Je(de,oe,me,gt(Pe._payload),at)}if(xe(Pe)||F(Pe))return de=de.get(me)||null,$e(oe,de,Pe,at,null);Zn(oe,Pe)}return null}function nt(de,oe,me,Pe){for(var at=null,gt=null,yt=oe,Nt=oe=0,Rs=null;yt!==null&&Nt<me.length;Nt++){yt.index>Nt?(Rs=yt,yt=null):Rs=yt.sibling;var mn=Ce(de,yt,me[Nt],Pe);if(mn===null){yt===null&&(yt=Rs);break}i&&yt&&mn.alternate===null&&a(de,yt),oe=b(mn,oe,Nt),gt===null?at=mn:gt.sibling=mn,gt=mn,yt=Rs}if(Nt===me.length)return d(de,yt),Tt&&Ri(de,Nt),at;if(yt===null){for(;Nt<me.length;Nt++)yt=Me(de,me[Nt],Pe),yt!==null&&(oe=b(yt,oe,Nt),gt===null?at=yt:gt.sibling=yt,gt=yt);return Tt&&Ri(de,Nt),at}for(yt=h(de,yt);Nt<me.length;Nt++)Rs=Je(yt,de,Nt,me[Nt],Pe),Rs!==null&&(i&&Rs.alternate!==null&&yt.delete(Rs.key===null?Nt:Rs.key),oe=b(Rs,oe,Nt),gt===null?at=Rs:gt.sibling=Rs,gt=Rs);return i&&yt.forEach(function(Ja){return a(de,Ja)}),Tt&&Ri(de,Nt),at}function st(de,oe,me,Pe){var at=F(me);if(typeof at!="function")throw Error(n(150));if(me=at.call(me),me==null)throw Error(n(151));for(var gt=at=null,yt=oe,Nt=oe=0,Rs=null,mn=me.next();yt!==null&&!mn.done;Nt++,mn=me.next()){yt.index>Nt?(Rs=yt,yt=null):Rs=yt.sibling;var Ja=Ce(de,yt,mn.value,Pe);if(Ja===null){yt===null&&(yt=Rs);break}i&&yt&&Ja.alternate===null&&a(de,yt),oe=b(Ja,oe,Nt),gt===null?at=Ja:gt.sibling=Ja,gt=Ja,yt=Rs}if(mn.done)return d(de,yt),Tt&&Ri(de,Nt),at;if(yt===null){for(;!mn.done;Nt++,mn=me.next())mn=Me(de,mn.value,Pe),mn!==null&&(oe=b(mn,oe,Nt),gt===null?at=mn:gt.sibling=mn,gt=mn);return Tt&&Ri(de,Nt),at}for(yt=h(de,yt);!mn.done;Nt++,mn=me.next())mn=Je(yt,de,Nt,mn.value,Pe),mn!==null&&(i&&mn.alternate!==null&&yt.delete(mn.key===null?Nt:mn.key),oe=b(mn,oe,Nt),gt===null?at=mn:gt.sibling=mn,gt=mn);return i&&yt.forEach(function(K0){return a(de,K0)}),Tt&&Ri(de,Nt),at}function ts(de,oe,me,Pe){if(typeof me=="object"&&me!==null&&me.type===J&&me.key===null&&(me=me.props.children),typeof me=="object"&&me!==null){switch(me.$$typeof){case K:e:{for(var at=me.key,gt=oe;gt!==null;){if(gt.key===at){if(at=me.type,at===J){if(gt.tag===7){d(de,gt.sibling),oe=v(gt,me.props.children),oe.return=de,de=oe;break e}}else if(gt.elementType===at||typeof at=="object"&&at!==null&&at.$$typeof===A&&Tc(at)===gt.type){d(de,gt.sibling),oe=v(gt,me.props),oe.ref=Ft(de,gt,me),oe.return=de,de=oe;break e}d(de,gt);break}else a(de,gt);gt=gt.sibling}me.type===J?(oe=Wl(me.props.children,de.mode,Pe,me.key),oe.return=de,de=oe):(Pe=yh(me.type,me.key,me.props,null,de.mode,Pe),Pe.ref=Ft(de,oe,me),Pe.return=de,de=Pe)}return L(de);case U:e:{for(gt=me.key;oe!==null;){if(oe.key===gt)if(oe.tag===4&&oe.stateNode.containerInfo===me.containerInfo&&oe.stateNode.implementation===me.implementation){d(de,oe.sibling),oe=v(oe,me.children||[]),oe.return=de,de=oe;break e}else{d(de,oe);break}else a(de,oe);oe=oe.sibling}oe=c_(me,de.mode,Pe),oe.return=de,de=oe}return L(de);case A:return gt=me._init,ts(de,oe,gt(me._payload),Pe)}if(xe(me))return nt(de,oe,me,Pe);if(F(me))return st(de,oe,me,Pe);Zn(de,me)}return typeof me=="string"&&me!==""||typeof me=="number"?(me=""+me,oe!==null&&oe.tag===6?(d(de,oe.sibling),oe=v(oe,me),oe.return=de,de=oe):(d(de,oe),oe=l_(me,de.mode,Pe),oe.return=de,de=oe),L(de)):d(de,oe)}return ts}var _i=od(!0),Vo=od(!1),ut=Ai(null),Mc=null,fo=null,ad=null;function ld(){ad=fo=Mc=null}function Rc(i){var a=ut.current;En(ut),i._currentValue=a}function cd(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 Da(i,a){Mc=i,ad=fo=null,i=i.dependencies,i!==null&&i.firstContext!==null&&((i.lanes&a)!==0&&(As=!0),i.firstContext=null)}function Ir(i){var a=i._currentValue;if(ad!==i)if(i={context:i,memoizedValue:a,next:null},fo===null){if(Mc===null)throw Error(n(308));fo=i,Mc.dependencies={lanes:0,firstContext:i}}else fo=fo.next=i;return a}var Li=null;function Jr(i){Li===null?Li=[i]:Li.push(i)}function ud(i,a,d,h){var v=a.interleaved;return v===null?(d.next=d,Jr(a)):(d.next=v.next,v.next=d),a.interleaved=d,os(i,h)}function os(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 as=!1;function Nl(i){i.updateQueue={baseState:i.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Jf(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 Ii(i,a){return{eventTime:i,lane:a,tag:0,payload:null,callback:null,next:null}}function ho(i,a,d){var h=i.updateQueue;if(h===null)return null;if(h=h.shared,(sn&2)!==0){var v=h.pending;return v===null?a.next=a:(a.next=v.next,v.next=a),h.pending=a,os(i,d)}return v=h.interleaved,v===null?(a.next=a,Jr(h)):(a.next=v.next,v.next=a),h.interleaved=a,os(i,d)}function Cl(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,Ki(i,d)}}function Lc(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 L={eventTime:d.eventTime,lane:d.lane,tag:d.tag,payload:d.payload,callback:d.callback,next:null};b===null?v=b=L:b=b.next=L,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 Ic(i,a,d,h){var v=i.updateQueue;as=!1;var b=v.firstBaseUpdate,L=v.lastBaseUpdate,ee=v.shared.pending;if(ee!==null){v.shared.pending=null;var se=ee,we=se.next;se.next=null,L===null?b=we:L.next=we,L=se;var $e=i.alternate;$e!==null&&($e=$e.updateQueue,ee=$e.lastBaseUpdate,ee!==L&&(ee===null?$e.firstBaseUpdate=we:ee.next=we,$e.lastBaseUpdate=se))}if(b!==null){var Me=v.baseState;L=0,$e=we=se=null,ee=b;do{var Ce=ee.lane,Je=ee.eventTime;if((h&Ce)===Ce){$e!==null&&($e=$e.next={eventTime:Je,lane:0,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null});e:{var nt=i,st=ee;switch(Ce=a,Je=d,st.tag){case 1:if(nt=st.payload,typeof nt=="function"){Me=nt.call(Je,Me,Ce);break e}Me=nt;break e;case 3:nt.flags=nt.flags&-65537|128;case 0:if(nt=st.payload,Ce=typeof nt=="function"?nt.call(Je,Me,Ce):nt,Ce==null)break e;Me=G({},Me,Ce);break e;case 2:as=!0}}ee.callback!==null&&ee.lane!==0&&(i.flags|=64,Ce=v.effects,Ce===null?v.effects=[ee]:Ce.push(ee))}else Je={eventTime:Je,lane:Ce,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null},$e===null?(we=$e=Je,se=Me):$e=$e.next=Je,L|=Ce;if(ee=ee.next,ee===null){if(ee=v.shared.pending,ee===null)break;Ce=ee,ee=Ce.next,Ce.next=null,v.lastBaseUpdate=Ce,v.shared.pending=null}}while(!0);if($e===null&&(se=Me),v.baseState=se,v.firstBaseUpdate=we,v.lastBaseUpdate=$e,a=v.shared.interleaved,a!==null){v=a;do L|=v.lane,v=v.next;while(v!==a)}else b===null&&(v.shared.lanes=0);wo|=L,i.lanes=L,i.memoizedState=Me}}function Tn(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 Fa={},Or=Ai(Fa),ls=Ai(Fa),za=Ai(Fa);function Xr(i){if(i===Fa)throw Error(n(174));return i}function El(i,a){switch(Cn(za,a),Cn(ls,i),Cn(Or,Fa),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)}En(Or),Cn(Or,a)}function pi(){En(Or),En(ls),En(za)}function Oc(i){Xr(za.current);var a=Xr(Or.current),d=It(a,i.type);a!==d&&(Cn(ls,i),Cn(Or,d))}function dd(i){ls.current===i&&(En(Or),En(ls))}var Dn=Ai(0);function Pc(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 Al=[];function Dc(){for(var i=0;i<Al.length;i++)Al[i]._workInProgressVersionPrimary=null;Al.length=0}var Fc=I.ReactCurrentDispatcher,$l=I.ReactCurrentBatchConfig,Go=0,yn=null,Mn=null,Ht=null,zc=!1,Tl=!1,Ml=0,Km=0;function Cs(){throw Error(n(321))}function fd(i,a){if(a===null)return!1;for(var d=0;d<a.length&&d<i.length;d++)if(!Vr(i[d],a[d]))return!1;return!0}function Jt(i,a,d,h,v,b){if(Go=b,yn=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,Fc.current=i===null||i.memoizedState===null?_o:ti,i=d(h,v),Tl){b=0;do{if(Tl=!1,Ml=0,25<=b)throw Error(n(301));b+=1,Ht=Mn=null,a.updateQueue=null,Fc.current=Xm,i=d(h,v)}while(Tl)}if(Fc.current=ei,a=Mn!==null&&Mn.next!==null,Go=0,Ht=Mn=yn=null,zc=!1,a)throw Error(n(300));return i}function Qn(){var i=Ml!==0;return Ml=0,i}function Fn(){var i={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Ht===null?yn.memoizedState=Ht=i:Ht=Ht.next=i,Ht}function sr(){if(Mn===null){var i=yn.alternate;i=i!==null?i.memoizedState:null}else i=Mn.next;var a=Ht===null?yn.memoizedState:Ht.next;if(a!==null)Ht=a,Mn=i;else{if(i===null)throw Error(n(310));Mn=i,i={memoizedState:Mn.memoizedState,baseState:Mn.baseState,baseQueue:Mn.baseQueue,queue:Mn.queue,next:null},Ht===null?yn.memoizedState=Ht=i:Ht=Ht.next=i}return Ht}function mo(i,a){return typeof a=="function"?a(i):a}function Bc(i){var a=sr(),d=a.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=i;var h=Mn,v=h.baseQueue,b=d.pending;if(b!==null){if(v!==null){var L=v.next;v.next=b.next,b.next=L}h.baseQueue=v=b,d.pending=null}if(v!==null){b=v.next,h=h.baseState;var ee=L=null,se=null,we=b;do{var $e=we.lane;if((Go&$e)===$e)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:$e,action:we.action,hasEagerState:we.hasEagerState,eagerState:we.eagerState,next:null};se===null?(ee=se=Me,L=h):se=se.next=Me,yn.lanes|=$e,wo|=$e}we=we.next}while(we!==null&&we!==b);se===null?L=h:se.next=ee,Vr(h,a.memoizedState)||(As=!0),a.memoizedState=h,a.baseState=L,a.baseQueue=se,d.lastRenderedState=h}if(i=d.interleaved,i!==null){v=i;do b=v.lane,yn.lanes|=b,wo|=b,v=v.next;while(v!==i)}else v===null&&(d.lanes=0);return[a.memoizedState,d.dispatch]}function hd(i){var a=sr(),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 L=v=v.next;do b=i(b,L.action),L=L.next;while(L!==v);Vr(b,a.memoizedState)||(As=!0),a.memoizedState=b,a.baseQueue===null&&(a.baseState=b),d.lastRenderedState=b}return[b,h]}function Xf(){}function md(i,a){var d=yn,h=sr(),v=a(),b=!Vr(h.memoizedState,v);if(b&&(h.memoizedState=v,As=!0),h=h.queue,yd(Qf.bind(null,d,h,i),[i]),h.getSnapshot!==a||b||Ht!==null&&Ht.memoizedState.tag&1){if(d.flags|=2048,Zr(9,Zf.bind(null,d,h,v,a),void 0,null),es===null)throw Error(n(349));(Go&30)!==0||Rl(d,a,v)}return v}function Rl(i,a,d){i.flags|=16384,i={getSnapshot:a,value:d},a=yn.updateQueue,a===null?(a={lastEffect:null,stores:null},yn.updateQueue=a,a.stores=[i]):(d=a.stores,d===null?a.stores=[i]:d.push(i))}function Zf(i,a,d,h){a.value=d,a.getSnapshot=h,eh(a)&&_d(i)}function Qf(i,a,d){return d(function(){eh(a)&&_d(i)})}function eh(i){var a=i.getSnapshot;i=i.value;try{var d=a();return!Vr(i,d)}catch{return!0}}function _d(i){var a=os(i,1);a!==null&&Oe(a,i,1,-1)}function pd(i){var a=Fn();return typeof i=="function"&&(i=i()),a.memoizedState=a.baseState=i,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:mo,lastRenderedState:i},a.queue=i,i=i.dispatch=Ko.bind(null,yn,i),[a.memoizedState,i]}function Zr(i,a,d,h){return i={tag:i,create:a,destroy:d,deps:h,next:null},a=yn.updateQueue,a===null?(a={lastEffect:null,stores:null},yn.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 Uc(){return sr().memoizedState}function Ll(i,a,d,h){var v=Fn();yn.flags|=i,v.memoizedState=Zr(1|a,d,void 0,h===void 0?null:h)}function Ba(i,a,d,h){var v=sr();h=h===void 0?null:h;var b=void 0;if(Mn!==null){var L=Mn.memoizedState;if(b=L.destroy,h!==null&&fd(h,L.deps)){v.memoizedState=Zr(a,d,b,h);return}}yn.flags|=i,v.memoizedState=Zr(1|a,d,b,h)}function gd(i,a){return Ll(8390656,8,i,a)}function yd(i,a){return Ba(2048,8,i,a)}function th(i,a){return Ba(4,2,i,a)}function nh(i,a){return Ba(4,4,i,a)}function sh(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 rh(i,a,d){return d=d!=null?d.concat([i]):null,Ba(4,4,sh.bind(null,a,i),d)}function wd(){}function vd(i,a){var d=sr();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&fd(a,h[1])?h[0]:(d.memoizedState=[i,a],i)}function Wc(i,a){var d=sr();a=a===void 0?null:a;var h=d.memoizedState;return h!==null&&a!==null&&fd(a,h[1])?h[0]:(i=i(),d.memoizedState=[i,a],i)}function ih(i,a,d){return(Go&21)===0?(i.baseState&&(i.baseState=!1,As=!0),i.memoizedState=d):(Vr(d,a)||(d=hs(),yn.lanes|=d,wo|=d,i.baseState=!0),a)}function Ym(i,a){var d=ln;ln=d!==0&&4>d?d:4,i(!0);var h=$l.transition;$l.transition={};try{i(!1),a()}finally{ln=d,$l.transition=h}}function Il(){return sr().memoizedState}function Jm(i,a,d){var h=Ae(i);if(d={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null},Es(i))cs(a,d);else if(d=ud(i,a,d,h),d!==null){var v=he();Oe(d,i,h,v),Qr(d,a,h)}}function Ko(i,a,d){var h=Ae(i),v={lane:h,action:d,hasEagerState:!1,eagerState:null,next:null};if(Es(i))cs(a,v);else{var b=i.alternate;if(i.lanes===0&&(b===null||b.lanes===0)&&(b=a.lastRenderedReducer,b!==null))try{var L=a.lastRenderedState,ee=b(L,d);if(v.hasEagerState=!0,v.eagerState=ee,Vr(ee,L)){var se=a.interleaved;se===null?(v.next=v,Jr(a)):(v.next=se.next,se.next=v),a.interleaved=v;return}}catch{}finally{}d=ud(i,a,v,h),d!==null&&(v=he(),Oe(d,i,h,v),Qr(d,a,h))}}function Es(i){var a=i.alternate;return i===yn||a!==null&&a===yn}function cs(i,a){Tl=zc=!0;var d=i.pending;d===null?a.next=a:(a.next=d.next,d.next=a),i.pending=a}function Qr(i,a,d){if((d&4194240)!==0){var h=a.lanes;h&=i.pendingLanes,d|=h,a.lanes=d,Ki(i,d)}}var ei={readContext:Ir,useCallback:Cs,useContext:Cs,useEffect:Cs,useImperativeHandle:Cs,useInsertionEffect:Cs,useLayoutEffect:Cs,useMemo:Cs,useReducer:Cs,useRef:Cs,useState:Cs,useDebugValue:Cs,useDeferredValue:Cs,useTransition:Cs,useMutableSource:Cs,useSyncExternalStore:Cs,useId:Cs,unstable_isNewReconciler:!1},_o={readContext:Ir,useCallback:function(i,a){return Fn().memoizedState=[i,a===void 0?null:a],i},useContext:Ir,useEffect:gd,useImperativeHandle:function(i,a,d){return d=d!=null?d.concat([i]):null,Ll(4194308,4,sh.bind(null,a,i),d)},useLayoutEffect:function(i,a){return Ll(4194308,4,i,a)},useInsertionEffect:function(i,a){return Ll(4,2,i,a)},useMemo:function(i,a){var d=Fn();return a=a===void 0?null:a,i=i(),d.memoizedState=[i,a],i},useReducer:function(i,a,d){var h=Fn();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=Jm.bind(null,yn,i),[h.memoizedState,i]},useRef:function(i){var a=Fn();return i={current:i},a.memoizedState=i},useState:pd,useDebugValue:wd,useDeferredValue:function(i){return Fn().memoizedState=i},useTransition:function(){var i=pd(!1),a=i[0];return i=Ym.bind(null,i[1]),Fn().memoizedState=i,[a,i]},useMutableSource:function(){},useSyncExternalStore:function(i,a,d){var h=yn,v=Fn();if(Tt){if(d===void 0)throw Error(n(407));d=d()}else{if(d=a(),es===null)throw Error(n(349));(Go&30)!==0||Rl(h,a,d)}v.memoizedState=d;var b={value:d,getSnapshot:a};return v.queue=b,gd(Qf.bind(null,h,b,i),[i]),h.flags|=2048,Zr(9,Zf.bind(null,h,b,d,a),void 0,null),d},useId:function(){var i=Fn(),a=es.identifierPrefix;if(Tt){var d=Mi,h=Yr;d=(h&~(1<<32-rs(h)-1)).toString(32)+d,a=":"+a+"R"+d,d=Ml++,0<d&&(a+="H"+d.toString(32)),a+=":"}else d=Km++,a=":"+a+"r"+d.toString(32)+":";return i.memoizedState=a},unstable_isNewReconciler:!1},ti={readContext:Ir,useCallback:vd,useContext:Ir,useEffect:yd,useImperativeHandle:rh,useInsertionEffect:th,useLayoutEffect:nh,useMemo:Wc,useReducer:Bc,useRef:Uc,useState:function(){return Bc(mo)},useDebugValue:wd,useDeferredValue:function(i){var a=sr();return ih(a,Mn.memoizedState,i)},useTransition:function(){var i=Bc(mo)[0],a=sr().memoizedState;return[i,a]},useMutableSource:Xf,useSyncExternalStore:md,useId:Il,unstable_isNewReconciler:!1},Xm={readContext:Ir,useCallback:vd,useContext:Ir,useEffect:yd,useImperativeHandle:rh,useInsertionEffect:th,useLayoutEffect:nh,useMemo:Wc,useReducer:hd,useRef:Uc,useState:function(){return hd(mo)},useDebugValue:wd,useDeferredValue:function(i){var a=sr();return Mn===null?a.memoizedState=i:ih(a,Mn.memoizedState,i)},useTransition:function(){var i=hd(mo)[0],a=sr().memoizedState;return[i,a]},useMutableSource:Xf,useSyncExternalStore:md,useId:Il,unstable_isNewReconciler:!1};function rr(i,a){if(i&&i.defaultProps){a=G({},a),i=i.defaultProps;for(var d in i)a[d]===void 0&&(a[d]=i[d]);return a}return a}function xd(i,a,d,h){a=i.memoizedState,d=d(h,a),d=d==null?a:G({},a,d),i.memoizedState=d,i.lanes===0&&(i.updateQueue.baseState=d)}var Ua={isMounted:function(i){return(i=i._reactInternals)?ft(i)===i:!1},enqueueSetState:function(i,a,d){i=i._reactInternals;var h=he(),v=Ae(i),b=Ii(h,v);b.payload=a,d!=null&&(b.callback=d),a=ho(i,b,v),a!==null&&(Oe(a,i,v,h),Cl(a,i,v))},enqueueReplaceState:function(i,a,d){i=i._reactInternals;var h=he(),v=Ae(i),b=Ii(h,v);b.tag=1,b.payload=a,d!=null&&(b.callback=d),a=ho(i,b,v),a!==null&&(Oe(a,i,v,h),Cl(a,i,v))},enqueueForceUpdate:function(i,a){i=i._reactInternals;var d=he(),h=Ae(i),v=Ii(d,h);v.tag=2,a!=null&&(v.callback=a),a=ho(i,v,h),a!==null&&(Oe(a,i,h,d),Cl(a,i,h))}};function oh(i,a,d,h,v,b,L){return i=i.stateNode,typeof i.shouldComponentUpdate=="function"?i.shouldComponentUpdate(h,b,L):a.prototype&&a.prototype.isPureReactComponent?!eo(d,h)||!eo(v,b):!0}function ah(i,a,d){var h=!1,v=xr,b=a.contextType;return typeof b=="object"&&b!==null?b=Ir(b):(v=nr(a)?$i:fn.current,h=a.contextTypes,b=(h=h!=null)?Ra(i,v):xr),a=new a(d,b),i.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,a.updater=Ua,i.stateNode=a,a._reactInternals=i,h&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=v,i.__reactInternalMemoizedMaskedChildContext=b),a}function bd(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&&Ua.enqueueReplaceState(a,a.state,null)}function Oi(i,a,d,h){var v=i.stateNode;v.props=d,v.state=i.memoizedState,v.refs={},Nl(i);var b=a.contextType;typeof b=="object"&&b!==null?v.context=Ir(b):(b=nr(a)?$i:fn.current,v.context=Ra(i,b)),v.state=i.memoizedState,b=a.getDerivedStateFromProps,typeof b=="function"&&(xd(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&&Ua.enqueueReplaceState(v,v.state,null),Ic(i,d,v,h),v.state=i.memoizedState),typeof v.componentDidMount=="function"&&(i.flags|=4194308)}function gi(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 qc(i,a,d){return{value:i,source:null,stack:d??null,digest:a??null}}function Hc(i,a){try{console.error(a.value)}catch(d){setTimeout(function(){throw d})}}var Zm=typeof WeakMap=="function"?WeakMap:Map;function jd(i,a,d){d=Ii(-1,d),d.tag=3,d.payload={element:null};var h=a.value;return d.callback=function(){y||(y=!0,S=h),Hc(i,a)},d}function Yo(i,a,d){d=Ii(-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(){Hc(i,a)}}var b=i.stateNode;return b!==null&&typeof b.componentDidCatch=="function"&&(d.callback=function(){Hc(i,a),typeof h!="function"&&(M===null?M=new Set([this]):M.add(this));var L=a.stack;this.componentDidCatch(a.value,{componentStack:L!==null?L:""})}),d}function lh(i,a,d){var h=i.pingCache;if(h===null){h=i.pingCache=new Zm;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=P0.bind(null,i,a,d),a.then(i,i))}function Ol(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 kd(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=Ii(-1,1),a.tag=2,ho(d,a,1))),d.lanes|=1),i):(i.flags|=65536,i.lanes=v,i)}var Qm=I.ReactCurrentOwner,As=!1;function Ws(i,a,d,h){a.child=i===null?Vo(a,null,d,h):_i(a,i.child,d,h)}function ch(i,a,d,h,v){d=d.render;var b=a.ref;return Da(a,v),h=Jt(i,a,d,h,b,v),d=Qn(),i!==null&&!As?(a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~v,Pi(i,a,v)):(Tt&&d&&Ac(a),a.flags|=1,Ws(i,a,h,v),a.child)}function uh(i,a,d,h,v){if(i===null){var b=d.type;return typeof b=="function"&&!a_(b)&&b.defaultProps===void 0&&d.compare===null&&d.defaultProps===void 0?(a.tag=15,a.type=b,ir(i,a,b,h,v)):(i=yh(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 L=b.memoizedProps;if(d=d.compare,d=d!==null?d:eo,d(L,h)&&i.ref===a.ref)return Pi(i,a,v)}return a.flags|=1,i=Ya(b,h),i.ref=a.ref,i.return=a,a.child=i}function ir(i,a,d,h,v){if(i!==null){var b=i.memoizedProps;if(eo(b,h)&&i.ref===a.ref)if(As=!1,a.pendingProps=h=b,(i.lanes&v)!==0)(i.flags&131072)!==0&&(As=!0);else return a.lanes=i.lanes,Pi(i,a,v)}return Vc(i,a,d,h,v)}function Jo(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},Cn(Qo,ar),ar|=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,Cn(Qo,ar),ar|=i,null;a.memoizedState={baseLanes:0,cachePool:null,transitions:null},h=b!==null?b.baseLanes:d,Cn(Qo,ar),ar|=h}else b!==null?(h=b.baseLanes|d,a.memoizedState=null):h=d,Cn(Qo,ar),ar|=h;return Ws(i,a,v,d),a.child}function dh(i,a){var d=a.ref;(i===null&&d!==null||i!==null&&i.ref!==d)&&(a.flags|=512,a.flags|=2097152)}function Vc(i,a,d,h,v){var b=nr(d)?$i:fn.current;return b=Ra(a,b),Da(a,v),d=Jt(i,a,d,h,b,v),h=Qn(),i!==null&&!As?(a.updateQueue=i.updateQueue,a.flags&=-2053,i.lanes&=~v,Pi(i,a,v)):(Tt&&h&&Ac(a),a.flags|=1,Ws(i,a,d,v),a.child)}function or(i,a,d,h,v){if(nr(d)){var b=!0;bl(a)}else b=!1;if(Da(a,v),a.stateNode===null)Pr(i,a),ah(a,d,h),Oi(a,d,h,v),h=!0;else if(i===null){var L=a.stateNode,ee=a.memoizedProps;L.props=ee;var se=L.context,we=d.contextType;typeof we=="object"&&we!==null?we=Ir(we):(we=nr(d)?$i:fn.current,we=Ra(a,we));var $e=d.getDerivedStateFromProps,Me=typeof $e=="function"||typeof L.getSnapshotBeforeUpdate=="function";Me||typeof L.UNSAFE_componentWillReceiveProps!="function"&&typeof L.componentWillReceiveProps!="function"||(ee!==h||se!==we)&&bd(a,L,h,we),as=!1;var Ce=a.memoizedState;L.state=Ce,Ic(a,h,L,v),se=a.memoizedState,ee!==h||Ce!==se||ws.current||as?(typeof $e=="function"&&(xd(a,d,$e,h),se=a.memoizedState),(ee=as||oh(a,d,ee,h,Ce,se,we))?(Me||typeof L.UNSAFE_componentWillMount!="function"&&typeof L.componentWillMount!="function"||(typeof L.componentWillMount=="function"&&L.componentWillMount(),typeof L.UNSAFE_componentWillMount=="function"&&L.UNSAFE_componentWillMount()),typeof L.componentDidMount=="function"&&(a.flags|=4194308)):(typeof L.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=h,a.memoizedState=se),L.props=h,L.state=se,L.context=we,h=ee):(typeof L.componentDidMount=="function"&&(a.flags|=4194308),h=!1)}else{L=a.stateNode,Jf(i,a),ee=a.memoizedProps,we=a.type===a.elementType?ee:rr(a.type,ee),L.props=we,Me=a.pendingProps,Ce=L.context,se=d.contextType,typeof se=="object"&&se!==null?se=Ir(se):(se=nr(d)?$i:fn.current,se=Ra(a,se));var Je=d.getDerivedStateFromProps;($e=typeof Je=="function"||typeof L.getSnapshotBeforeUpdate=="function")||typeof L.UNSAFE_componentWillReceiveProps!="function"&&typeof L.componentWillReceiveProps!="function"||(ee!==Me||Ce!==se)&&bd(a,L,h,se),as=!1,Ce=a.memoizedState,L.state=Ce,Ic(a,h,L,v);var nt=a.memoizedState;ee!==Me||Ce!==nt||ws.current||as?(typeof Je=="function"&&(xd(a,d,Je,h),nt=a.memoizedState),(we=as||oh(a,d,we,h,Ce,nt,se)||!1)?($e||typeof L.UNSAFE_componentWillUpdate!="function"&&typeof L.componentWillUpdate!="function"||(typeof L.componentWillUpdate=="function"&&L.componentWillUpdate(h,nt,se),typeof L.UNSAFE_componentWillUpdate=="function"&&L.UNSAFE_componentWillUpdate(h,nt,se)),typeof L.componentDidUpdate=="function"&&(a.flags|=4),typeof L.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof L.componentDidUpdate!="function"||ee===i.memoizedProps&&Ce===i.memoizedState||(a.flags|=4),typeof L.getSnapshotBeforeUpdate!="function"||ee===i.memoizedProps&&Ce===i.memoizedState||(a.flags|=1024),a.memoizedProps=h,a.memoizedState=nt),L.props=h,L.state=nt,L.context=se,h=we):(typeof L.componentDidUpdate!="function"||ee===i.memoizedProps&&Ce===i.memoizedState||(a.flags|=4),typeof L.getSnapshotBeforeUpdate!="function"||ee===i.memoizedProps&&Ce===i.memoizedState||(a.flags|=1024),h=!1)}return Pl(i,a,d,h,b,v)}function Pl(i,a,d,h,v,b){dh(i,a);var L=(a.flags&128)!==0;if(!h&&!L)return v&&jl(a,d,!1),Pi(i,a,b);h=a.stateNode,Qm.current=a;var ee=L&&typeof d.getDerivedStateFromError!="function"?null:h.render();return a.flags|=1,i!==null&&L?(a.child=_i(a,i.child,null,b),a.child=_i(a,null,ee,b)):Ws(i,a,ee,b),a.memoizedState=h.state,v&&jl(a,d,!0),a.child}function Sd(i){var a=i.stateNode;a.pendingContext?Vf(i,a.pendingContext,a.pendingContext!==a.context):a.context&&Vf(i,a.context,!1),El(i,a.containerInfo)}function Nd(i,a,d,h,v){return Oa(),Pa(v),a.flags|=256,Ws(i,a,d,h),a.child}var Cd={dehydrated:null,treeContext:null,retryLane:0};function Ed(i){return{baseLanes:i,cachePool:null,transitions:null}}function fh(i,a,d){var h=a.pendingProps,v=Dn.current,b=!1,L=(a.flags&128)!==0,ee;if((ee=L)||(ee=i!==null&&i.memoizedState===null?!1:(v&2)!==0),ee?(b=!0,a.flags&=-129):(i===null||i.memoizedState!==null)&&(v|=1),Cn(Dn,v&1),i===null)return rd(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):(L=h.children,i=h.fallback,b?(h=a.mode,b=a.child,L={mode:"hidden",children:L},(h&1)===0&&b!==null?(b.childLanes=0,b.pendingProps=L):b=wh(L,h,0,null),i=Wl(i,h,d,null),b.return=a,i.return=a,b.sibling=i,a.child=b,a.child.memoizedState=Ed(d),a.memoizedState=Cd,i):qs(a,L));if(v=i.memoizedState,v!==null&&(ee=v.dehydrated,ee!==null))return hh(i,a,L,h,ee,v,d);if(b){b=h.fallback,L=a.mode,v=i.child,ee=v.sibling;var se={mode:"hidden",children:h.children};return(L&1)===0&&a.child!==v?(h=a.child,h.childLanes=0,h.pendingProps=se,a.deletions=null):(h=Ya(v,se),h.subtreeFlags=v.subtreeFlags&14680064),ee!==null?b=Ya(ee,b):(b=Wl(b,L,d,null),b.flags|=2),b.return=a,h.return=a,h.sibling=b,a.child=h,h=b,b=a.child,L=i.child.memoizedState,L=L===null?Ed(d):{baseLanes:L.baseLanes|d,cachePool:null,transitions:L.transitions},b.memoizedState=L,b.childLanes=i.childLanes&~d,a.memoizedState=Cd,h}return b=i.child,i=b.sibling,h=Ya(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 qs(i,a){return a=wh({mode:"visible",children:a},i.mode,0,null),a.return=i,i.child=a}function po(i,a,d,h){return h!==null&&Pa(h),_i(a,i.child,null,d),i=qs(a,a.pendingProps.children),i.flags|=2,a.memoizedState=null,i}function hh(i,a,d,h,v,b,L){if(d)return a.flags&256?(a.flags&=-257,h=qc(Error(n(422))),po(i,a,L,h)):a.memoizedState!==null?(a.child=i.child,a.flags|=128,null):(b=h.fallback,v=a.mode,h=wh({mode:"visible",children:h.children},v,0,null),b=Wl(b,v,L,null),b.flags|=2,h.return=a,b.return=a,h.sibling=b,a.child=h,(a.mode&1)!==0&&_i(a,i.child,null,L),a.child.memoizedState=Ed(L),a.memoizedState=Cd,b);if((a.mode&1)===0)return po(i,a,L,null);if(v.data==="$!"){if(h=v.nextSibling&&v.nextSibling.dataset,h)var ee=h.dgst;return h=ee,b=Error(n(419)),h=qc(b,h,void 0),po(i,a,L,h)}if(ee=(L&i.childLanes)!==0,As||ee){if(h=es,h!==null){switch(L&-L){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|L))!==0?0:v,v!==0&&v!==b.retryLane&&(b.retryLane=v,os(i,v),Oe(h,i,v,-1))}return o_(),h=qc(Error(n(421))),po(i,a,L,h)}return v.data==="$?"?(a.flags|=128,a.child=i.child,a=D0.bind(null,i),v._reactRetry=a,null):(i=b.treeContext,Te=co(v.nextSibling),Bs=a,Tt=!0,br=null,i!==null&&(Rr[Lr++]=Yr,Rr[Lr++]=Mi,Rr[Lr++]=Ho,Yr=i.id,Mi=i.overflow,Ho=a),a=qs(a,h.children),a.flags|=4096,a)}function Ad(i,a,d){i.lanes|=a;var h=i.alternate;h!==null&&(h.lanes|=a),cd(i.return,a,d)}function Dl(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 $d(i,a,d){var h=a.pendingProps,v=h.revealOrder,b=h.tail;if(Ws(i,a,h.children,d),h=Dn.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&&Ad(i,d,a);else if(i.tag===19)Ad(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(Cn(Dn,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&&Pc(i)===null&&(v=d),d=d.sibling;d=v,d===null?(v=a.child,a.child=null):(v=d.sibling,d.sibling=null),Dl(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&&Pc(i)===null){a.child=v;break}i=v.sibling,v.sibling=d,d=v,v=i}Dl(a,!0,d,null,b);break;case"together":Dl(a,!1,null,null,void 0);break;default:a.memoizedState=null}return a.child}function Pr(i,a){(a.mode&1)===0&&i!==null&&(i.alternate=null,a.alternate=null,a.flags|=2)}function Pi(i,a,d){if(i!==null&&(a.dependencies=i.dependencies),wo|=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=Ya(i,i.pendingProps),a.child=d,d.return=a;i.sibling!==null;)i=i.sibling,d=d.sibling=Ya(i,i.pendingProps),d.return=a;d.sibling=null}return a.child}function e_(i,a,d){switch(a.tag){case 3:Sd(a),Oa();break;case 5:Oc(a);break;case 1:nr(a.type)&&bl(a);break;case 4:El(a,a.stateNode.containerInfo);break;case 10:var h=a.type._context,v=a.memoizedProps.value;Cn(ut,h._currentValue),h._currentValue=v;break;case 13:if(h=a.memoizedState,h!==null)return h.dehydrated!==null?(Cn(Dn,Dn.current&1),a.flags|=128,null):(d&a.child.childLanes)!==0?fh(i,a,d):(Cn(Dn,Dn.current&1),i=Pi(i,a,d),i!==null?i.sibling:null);Cn(Dn,Dn.current&1);break;case 19:if(h=(d&a.childLanes)!==0,(i.flags&128)!==0){if(h)return $d(i,a,d);a.flags|=128}if(v=a.memoizedState,v!==null&&(v.rendering=null,v.tail=null,v.lastEffect=null),Cn(Dn,Dn.current),h)break;return null;case 22:case 23:return a.lanes=0,Jo(i,a,d)}return Pi(i,a,d)}var Td,go,Gc,mh;Td=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}},go=function(){},Gc=function(i,a,d,h){var v=i.memoizedProps;if(v!==h){i=a.stateNode,Xr(Or.current);var b=null;switch(d){case"input":v=tt(i,v),h=tt(i,h),b=[];break;case"select":v=G({},v,{value:void 0}),h=G({},h,{value:void 0}),b=[];break;case"textarea":v=qe(i,v),h=qe(i,h),b=[];break;default:typeof v.onClick!="function"&&typeof h.onClick=="function"&&(i.onclick=Sc)}wn(d,h);var L;d=null;for(we in v)if(!h.hasOwnProperty(we)&&v.hasOwnProperty(we)&&v[we]!=null)if(we==="style"){var ee=v[we];for(L in ee)ee.hasOwnProperty(L)&&(d||(d={}),d[L]="")}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(L in ee)!ee.hasOwnProperty(L)||se&&se.hasOwnProperty(L)||(d||(d={}),d[L]="");for(L in se)se.hasOwnProperty(L)&&ee[L]!==se[L]&&(d||(d={}),d[L]=se[L])}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"&&Nn("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)}},mh=function(i,a,d,h){d!==h&&(a.flags|=4)};function Fl(i,a){if(!Tt)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 $s(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 t_(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 $s(a),null;case 1:return nr(a.type)&&La(),$s(a),null;case 3:return h=a.stateNode,pi(),En(ws),En(fn),Dc(),h.pendingContext&&(h.context=h.pendingContext,h.pendingContext=null),(i===null||i.child===null)&&(Sl(a)?a.flags|=4:i===null||i.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,br!==null&&(rn(br),br=null))),go(i,a),$s(a),null;case 5:dd(a);var v=Xr(za.current);if(d=a.type,i!==null&&a.stateNode!=null)Gc(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 $s(a),null}if(i=Xr(Or.current),Sl(a)){h=a.stateNode,d=a.type;var b=a.memoizedProps;switch(h[ys]=a,h[Ta]=b,i=(a.mode&1)!==0,d){case"dialog":Nn("cancel",h),Nn("close",h);break;case"iframe":case"object":case"embed":Nn("load",h);break;case"video":case"audio":for(v=0;v<Na.length;v++)Nn(Na[v],h);break;case"source":Nn("error",h);break;case"img":case"image":case"link":Nn("error",h),Nn("load",h);break;case"details":Nn("toggle",h);break;case"input":lt(h,b),Nn("invalid",h);break;case"select":h._wrapperState={wasMultiple:!!b.multiple},Nn("invalid",h);break;case"textarea":zt(h,b),Nn("invalid",h)}wn(d,b),v=null;for(var L in b)if(b.hasOwnProperty(L)){var ee=b[L];L==="children"?typeof ee=="string"?h.textContent!==ee&&(b.suppressHydrationWarning!==!0&&ao(h.textContent,ee,i),v=["children",ee]):typeof ee=="number"&&h.textContent!==""+ee&&(b.suppressHydrationWarning!==!0&&ao(h.textContent,ee,i),v=["children",""+ee]):o.hasOwnProperty(L)&&ee!=null&&L==="onScroll"&&Nn("scroll",h)}switch(d){case"input":We(h),Re(h,b,!0);break;case"textarea":We(h),bn(h);break;case"select":case"option":break;default:typeof b.onClick=="function"&&(h.onclick=Sc)}h=v,a.updateQueue=h,h!==null&&(a.flags|=4)}else{L=v.nodeType===9?v:v.ownerDocument,i==="http://www.w3.org/1999/xhtml"&&(i=Wt(d)),i==="http://www.w3.org/1999/xhtml"?d==="script"?(i=L.createElement("div"),i.innerHTML="<script><\/script>",i=i.removeChild(i.firstChild)):typeof h.is=="string"?i=L.createElement(d,{is:h.is}):(i=L.createElement(d),d==="select"&&(L=i,h.multiple?L.multiple=!0:h.size&&(L.size=h.size))):i=L.createElementNS(i,d),i[ys]=a,i[Ta]=h,Td(i,a,!1,!1),a.stateNode=i;e:{switch(L=js(d,h),d){case"dialog":Nn("cancel",i),Nn("close",i),v=h;break;case"iframe":case"object":case"embed":Nn("load",i),v=h;break;case"video":case"audio":for(v=0;v<Na.length;v++)Nn(Na[v],i);v=h;break;case"source":Nn("error",i),v=h;break;case"img":case"image":case"link":Nn("error",i),Nn("load",i),v=h;break;case"details":Nn("toggle",i),v=h;break;case"input":lt(i,h),v=tt(i,h),Nn("invalid",i);break;case"option":v=h;break;case"select":i._wrapperState={wasMultiple:!!h.multiple},v=G({},h,{value:void 0}),Nn("invalid",i);break;case"textarea":zt(i,h),v=qe(i,h),Nn("invalid",i);break;default:v=h}wn(d,v),ee=v;for(b in ee)if(ee.hasOwnProperty(b)){var se=ee[b];b==="style"?gn(i,se):b==="dangerouslySetInnerHTML"?(se=se?se.__html:void 0,se!=null&&ns(i,se)):b==="children"?typeof se=="string"?(d!=="textarea"||se!=="")&&Ot(i,se):typeof se=="number"&&Ot(i,""+se):b!=="suppressContentEditableWarning"&&b!=="suppressHydrationWarning"&&b!=="autoFocus"&&(o.hasOwnProperty(b)?se!=null&&b==="onScroll"&&Nn("scroll",i):se!=null&&T(i,b,se,L))}switch(d){case"input":We(i),Re(i,h,!1);break;case"textarea":We(i),bn(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?Ie(i,!!h.multiple,b,!1):h.defaultValue!=null&&Ie(i,!!h.multiple,h.defaultValue,!0);break;default:typeof v.onClick=="function"&&(i.onclick=Sc)}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 $s(a),null;case 6:if(i&&a.stateNode!=null)mh(i,a,i.memoizedProps,h);else{if(typeof h!="string"&&a.stateNode===null)throw Error(n(166));if(d=Xr(za.current),Xr(Or.current),Sl(a)){if(h=a.stateNode,d=a.memoizedProps,h[ys]=a,(b=h.nodeValue!==d)&&(i=Bs,i!==null))switch(i.tag){case 3:ao(h.nodeValue,d,(i.mode&1)!==0);break;case 5:i.memoizedProps.suppressHydrationWarning!==!0&&ao(h.nodeValue,d,(i.mode&1)!==0)}b&&(a.flags|=4)}else h=(d.nodeType===9?d:d.ownerDocument).createTextNode(h),h[ys]=a,a.stateNode=h}return $s(a),null;case 13:if(En(Dn),h=a.memoizedState,i===null||i.memoizedState!==null&&i.memoizedState.dehydrated!==null){if(Tt&&Te!==null&&(a.mode&1)!==0&&(a.flags&128)===0)id(),Oa(),a.flags|=98560,b=!1;else if(b=Sl(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[ys]=a}else Oa(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;$s(a),b=!1}else br!==null&&(rn(br),br=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||(Dn.current&1)!==0?Yn===0&&(Yn=3):o_())),a.updateQueue!==null&&(a.flags|=4),$s(a),null);case 4:return pi(),go(i,a),i===null&&yl(a.stateNode.containerInfo),$s(a),null;case 10:return Rc(a.type._context),$s(a),null;case 17:return nr(a.type)&&La(),$s(a),null;case 19:if(En(Dn),b=a.memoizedState,b===null)return $s(a),null;if(h=(a.flags&128)!==0,L=b.rendering,L===null)if(h)Fl(b,!1);else{if(Yn!==0||i!==null&&(i.flags&128)!==0)for(i=a.child;i!==null;){if(L=Pc(i),L!==null){for(a.flags|=128,Fl(b,!1),h=L.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,L=b.alternate,L===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=L.childLanes,b.lanes=L.lanes,b.child=L.child,b.subtreeFlags=0,b.deletions=null,b.memoizedProps=L.memoizedProps,b.memoizedState=L.memoizedState,b.updateQueue=L.updateQueue,b.type=L.type,i=L.dependencies,b.dependencies=i===null?null:{lanes:i.lanes,firstContext:i.firstContext}),d=d.sibling;return Cn(Dn,Dn.current&1|2),a.child}i=i.sibling}b.tail!==null&&ue()>ea&&(a.flags|=128,h=!0,Fl(b,!1),a.lanes=4194304)}else{if(!h)if(i=Pc(L),i!==null){if(a.flags|=128,h=!0,d=i.updateQueue,d!==null&&(a.updateQueue=d,a.flags|=4),Fl(b,!0),b.tail===null&&b.tailMode==="hidden"&&!L.alternate&&!Tt)return $s(a),null}else 2*ue()-b.renderingStartTime>ea&&d!==1073741824&&(a.flags|=128,h=!0,Fl(b,!1),a.lanes=4194304);b.isBackwards?(L.sibling=a.child,a.child=L):(d=b.last,d!==null?d.sibling=L:a.child=L,b.last=L)}return b.tail!==null?(a=b.tail,b.rendering=a,b.tail=a.sibling,b.renderingStartTime=ue(),a.sibling=null,d=Dn.current,Cn(Dn,h?d&1|2:d&1),a):($s(a),null);case 22:case 23:return Ms(),h=a.memoizedState!==null,i!==null&&i.memoizedState!==null!==h&&(a.flags|=8192),h&&(a.mode&1)!==0?(ar&1073741824)!==0&&($s(a),a.subtreeFlags&6&&(a.flags|=8192)):$s(a),null;case 24:return null;case 25:return null}throw Error(n(156,a.tag))}function n_(i,a){switch(td(a),a.tag){case 1:return nr(a.type)&&La(),i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 3:return pi(),En(ws),En(fn),Dc(),i=a.flags,(i&65536)!==0&&(i&128)===0?(a.flags=i&-65537|128,a):null;case 5:return dd(a),null;case 13:if(En(Dn),i=a.memoizedState,i!==null&&i.dehydrated!==null){if(a.alternate===null)throw Error(n(340));Oa()}return i=a.flags,i&65536?(a.flags=i&-65537|128,a):null;case 19:return En(Dn),null;case 4:return pi(),null;case 10:return Rc(a.type._context),null;case 22:case 23:return Ms(),null;case 24:return null;default:return null}}var Rn=!1,Vn=!1,s_=typeof WeakSet=="function"?WeakSet:Set,Xe=null;function Xo(i,a){var d=i.ref;if(d!==null)if(typeof d=="function")try{d(null)}catch(h){Jn(i,a,h)}else d.current=null}function Kc(i,a,d){try{d()}catch(h){Jn(i,a,h)}}var Md=!1;function _h(i,a){if(zo=Mo,i=hl(),Hu(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 L=0,ee=-1,se=-1,we=0,$e=0,Me=i,Ce=null;t:for(;;){for(var Je;Me!==d||v!==0&&Me.nodeType!==3||(ee=L+v),Me!==b||h!==0&&Me.nodeType!==3||(se=L+h),Me.nodeType===3&&(L+=Me.nodeValue.length),(Je=Me.firstChild)!==null;)Ce=Me,Me=Je;for(;;){if(Me===i)break t;if(Ce===d&&++we===v&&(ee=L),Ce===b&&++$e===h&&(se=L),(Je=Me.nextSibling)!==null)break;Me=Ce,Ce=Me.parentNode}Me=Je}d=ee===-1||se===-1?null:{start:ee,end:se}}else d=null}d=d||{start:0,end:0}}else d=null;for(wl={focusedElem:i,selectionRange:d},Mo=!1,Xe=a;Xe!==null;)if(a=Xe,i=a.child,(a.subtreeFlags&1028)!==0&&i!==null)i.return=a,Xe=i;else for(;Xe!==null;){a=Xe;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,de=a.stateNode,oe=de.getSnapshotBeforeUpdate(a.elementType===a.type?st:rr(a.type,st),ts);de.__reactInternalSnapshotBeforeUpdate=oe}break;case 3:var me=a.stateNode.containerInfo;me.nodeType===1?me.textContent="":me.nodeType===9&&me.documentElement&&me.removeChild(me.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(Pe){Jn(a,a.return,Pe)}if(i=a.sibling,i!==null){i.return=a.return,Xe=i;break}Xe=a.return}return nt=Md,Md=!1,nt}function Zo(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&&Kc(a,d,b)}v=v.next}while(v!==h)}}function yo(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 Wa(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 Rd(i){var a=i.alternate;a!==null&&(i.alternate=null,Rd(a)),i.child=null,i.deletions=null,i.sibling=null,i.tag===5&&(a=i.stateNode,a!==null&&(delete a[ys],delete a[Ta],delete a[Bo],delete a[Hf],delete a[Xu])),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 Ld(i){return i.tag===5||i.tag===3||i.tag===4}function Id(i){e:for(;;){for(;i.sibling===null;){if(i.return===null||Ld(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 yi(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=Sc));else if(h!==4&&(i=i.child,i!==null))for(yi(i,a,d),i=i.sibling;i!==null;)yi(i,a,d),i=i.sibling}function Od(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(Od(i,a,d),i=i.sibling;i!==null;)Od(i,a,d),i=i.sibling}var zn=null,jr=!1;function wi(i,a,d){for(d=d.child;d!==null;)Pd(i,a,d),d=d.sibling}function Pd(i,a,d){if(Ds&&typeof Ds.onCommitFiberUnmount=="function")try{Ds.onCommitFiberUnmount(cn,d)}catch{}switch(d.tag){case 5:Vn||Xo(d,a);case 6:var h=zn,v=jr;zn=null,wi(i,a,d),zn=h,jr=v,zn!==null&&(jr?(i=zn,d=d.stateNode,i.nodeType===8?i.parentNode.removeChild(d):i.removeChild(d)):zn.removeChild(d.stateNode));break;case 18:zn!==null&&(jr?(i=zn,d=d.stateNode,i.nodeType===8?lo(i.parentNode,d):i.nodeType===1&&lo(i,d),Xi(i)):lo(zn,d.stateNode));break;case 4:h=zn,v=jr,zn=d.stateNode.containerInfo,jr=!0,wi(i,a,d),zn=h,jr=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,L=b.destroy;b=b.tag,L!==void 0&&((b&2)!==0||(b&4)!==0)&&Kc(d,a,L),v=v.next}while(v!==h)}wi(i,a,d);break;case 1:if(!Vn&&(Xo(d,a),h=d.stateNode,typeof h.componentWillUnmount=="function"))try{h.props=d.memoizedProps,h.state=d.memoizedState,h.componentWillUnmount()}catch(ee){Jn(d,a,ee)}wi(i,a,d);break;case 21:wi(i,a,d);break;case 22:d.mode&1?(Vn=(h=Vn)||d.memoizedState!==null,wi(i,a,d),Vn=h):wi(i,a,d);break;default:wi(i,a,d)}}function Dd(i){var a=i.updateQueue;if(a!==null){i.updateQueue=null;var d=i.stateNode;d===null&&(d=i.stateNode=new s_),a.forEach(function(h){var v=F0.bind(null,i,h);d.has(h)||(d.add(h),h.then(v,v))})}}function ni(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,L=a,ee=L;e:for(;ee!==null;){switch(ee.tag){case 5:zn=ee.stateNode,jr=!1;break e;case 3:zn=ee.stateNode.containerInfo,jr=!0;break e;case 4:zn=ee.stateNode.containerInfo,jr=!0;break e}ee=ee.return}if(zn===null)throw Error(n(160));Pd(b,L,v),zn=null,jr=!1;var se=v.alternate;se!==null&&(se.return=null),v.return=null}catch(we){Jn(v,a,we)}}if(a.subtreeFlags&12854)for(a=a.child;a!==null;)qa(a,i),a=a.sibling}function qa(i,a){var d=i.alternate,h=i.flags;switch(i.tag){case 0:case 11:case 14:case 15:if(ni(a,i),Ts(i),h&4){try{Zo(3,i,i.return),yo(3,i)}catch(st){Jn(i,i.return,st)}try{Zo(5,i,i.return)}catch(st){Jn(i,i.return,st)}}break;case 1:ni(a,i),Ts(i),h&512&&d!==null&&Xo(d,d.return);break;case 5:if(ni(a,i),Ts(i),h&512&&d!==null&&Xo(d,d.return),i.flags&32){var v=i.stateNode;try{Ot(v,"")}catch(st){Jn(i,i.return,st)}}if(h&4&&(v=i.stateNode,v!=null)){var b=i.memoizedProps,L=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&&Ke(v,b),js(ee,L);var we=js(ee,b);for(L=0;L<se.length;L+=2){var $e=se[L],Me=se[L+1];$e==="style"?gn(v,Me):$e==="dangerouslySetInnerHTML"?ns(v,Me):$e==="children"?Ot(v,Me):T(v,$e,Me,we)}switch(ee){case"input":ke(v,b);break;case"textarea":en(v,b);break;case"select":var Ce=v._wrapperState.wasMultiple;v._wrapperState.wasMultiple=!!b.multiple;var Je=b.value;Je!=null?Ie(v,!!b.multiple,Je,!1):Ce!==!!b.multiple&&(b.defaultValue!=null?Ie(v,!!b.multiple,b.defaultValue,!0):Ie(v,!!b.multiple,b.multiple?[]:"",!1))}v[Ta]=b}catch(st){Jn(i,i.return,st)}}break;case 6:if(ni(a,i),Ts(i),h&4){if(i.stateNode===null)throw Error(n(162));v=i.stateNode,b=i.memoizedProps;try{v.nodeValue=b}catch(st){Jn(i,i.return,st)}}break;case 3:if(ni(a,i),Ts(i),h&4&&d!==null&&d.memoizedState.isDehydrated)try{Xi(a.containerInfo)}catch(st){Jn(i,i.return,st)}break;case 4:ni(a,i),Ts(i);break;case 13:ni(a,i),Ts(i),v=i.child,v.flags&8192&&(b=v.memoizedState!==null,v.stateNode.isHidden=b,!b||v.alternate!==null&&v.alternate.memoizedState!==null||(Qc=ue())),h&4&&Dd(i);break;case 22:if($e=d!==null&&d.memoizedState!==null,i.mode&1?(Vn=(we=Vn)||$e,ni(a,i),Vn=we):ni(a,i),Ts(i),h&8192){if(we=i.memoizedState!==null,(i.stateNode.isHidden=we)&&!$e&&(i.mode&1)!==0)for(Xe=i,$e=i.child;$e!==null;){for(Me=Xe=$e;Xe!==null;){switch(Ce=Xe,Je=Ce.child,Ce.tag){case 0:case 11:case 14:case 15:Zo(4,Ce,Ce.return);break;case 1:Xo(Ce,Ce.return);var nt=Ce.stateNode;if(typeof nt.componentWillUnmount=="function"){h=Ce,d=Ce.return;try{a=h,nt.props=a.memoizedProps,nt.state=a.memoizedState,nt.componentWillUnmount()}catch(st){Jn(h,d,st)}}break;case 5:Xo(Ce,Ce.return);break;case 22:if(Ce.memoizedState!==null){zl(Me);continue}}Je!==null?(Je.return=Ce,Xe=Je):zl(Me)}$e=$e.sibling}e:for($e=null,Me=i;;){if(Me.tag===5){if($e===null){$e=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,L=se!=null&&se.hasOwnProperty("display")?se.display:null,ee.style.display=An("display",L))}catch(st){Jn(i,i.return,st)}}}else if(Me.tag===6){if($e===null)try{Me.stateNode.nodeValue=we?"":Me.memoizedProps}catch(st){Jn(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;$e===Me&&($e=null),Me=Me.return}$e===Me&&($e=null),Me.sibling.return=Me.return,Me=Me.sibling}}break;case 19:ni(a,i),Ts(i),h&4&&Dd(i);break;case 21:break;default:ni(a,i),Ts(i)}}function Ts(i){var a=i.flags;if(a&2){try{e:{for(var d=i.return;d!==null;){if(Ld(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&&(Ot(v,""),h.flags&=-33);var b=Id(i);Od(i,b,v);break;case 3:case 4:var L=h.stateNode.containerInfo,ee=Id(i);yi(i,ee,L);break;default:throw Error(n(161))}}catch(se){Jn(i,i.return,se)}i.flags&=-3}a&4096&&(i.flags&=-4097)}function r_(i,a,d){Xe=i,Ha(i)}function Ha(i,a,d){for(var h=(i.mode&1)!==0;Xe!==null;){var v=Xe,b=v.child;if(v.tag===22&&h){var L=v.memoizedState!==null||Rn;if(!L){var ee=v.alternate,se=ee!==null&&ee.memoizedState!==null||Vn;ee=Rn;var we=Vn;if(Rn=L,(Vn=se)&&!we)for(Xe=v;Xe!==null;)L=Xe,se=L.child,L.tag===22&&L.memoizedState!==null?Yc(v):se!==null?(se.return=L,Xe=se):Yc(v);for(;b!==null;)Xe=b,Ha(b),b=b.sibling;Xe=v,Rn=ee,Vn=we}ph(i)}else(v.subtreeFlags&8772)!==0&&b!==null?(b.return=v,Xe=b):ph(i)}}function ph(i){for(;Xe!==null;){var a=Xe;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||yo(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:rr(a.type,d.memoizedProps);h.componentDidUpdate(v,d.memoizedState,h.__reactInternalSnapshotBeforeUpdate)}var b=a.updateQueue;b!==null&&Tn(a,b,h);break;case 3:var L=a.updateQueue;if(L!==null){if(d=null,a.child!==null)switch(a.child.tag){case 5:d=a.child.stateNode;break;case 1:d=a.child.stateNode}Tn(a,L,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 $e=we.memoizedState;if($e!==null){var Me=$e.dehydrated;Me!==null&&Xi(Me)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}Vn||a.flags&512&&Wa(a)}catch(Ce){Jn(a,a.return,Ce)}}if(a===i){Xe=null;break}if(d=a.sibling,d!==null){d.return=a.return,Xe=d;break}Xe=a.return}}function zl(i){for(;Xe!==null;){var a=Xe;if(a===i){Xe=null;break}var d=a.sibling;if(d!==null){d.return=a.return,Xe=d;break}Xe=a.return}}function Yc(i){for(;Xe!==null;){var a=Xe;try{switch(a.tag){case 0:case 11:case 15:var d=a.return;try{yo(4,a)}catch(se){Jn(a,d,se)}break;case 1:var h=a.stateNode;if(typeof h.componentDidMount=="function"){var v=a.return;try{h.componentDidMount()}catch(se){Jn(a,v,se)}}var b=a.return;try{Wa(a)}catch(se){Jn(a,b,se)}break;case 5:var L=a.return;try{Wa(a)}catch(se){Jn(a,L,se)}}}catch(se){Jn(a,a.return,se)}if(a===i){Xe=null;break}var ee=a.sibling;if(ee!==null){ee.return=a.return,Xe=ee;break}Xe=a.return}}var i_=Math.ceil,Jc=I.ReactCurrentDispatcher,Xc=I.ReactCurrentOwner,kr=I.ReactCurrentBatchConfig,sn=0,es=null,Gn=null,us=0,ar=0,Qo=Ai(0),Yn=0,Va=null,wo=0,Bl=0,Zc=0,Ga=null,Hs=null,Qc=0,ea=1/0,vi=null,y=!1,S=null,M=null,D=!1,q=null,H=0,V=0,ne=null,Le=-1,_e=0;function he(){return(sn&6)!==0?ue():Le!==-1?Le:Le=ue()}function Ae(i){return(i.mode&1)===0?1:(sn&2)!==0&&us!==0?us&-us:Us.transition!==null?(_e===0&&(_e=hs()),_e):(i=ln,i!==0||(i=window.event,i=i===void 0?16:be(i.type)),i)}function Oe(i,a,d,h){if(50<V)throw V=0,ne=null,Error(n(185));ms(i,d,h),((sn&2)===0||i!==es)&&(i===es&&((sn&2)===0&&(Bl|=d),Yn===4&&Be(i,us)),ze(i,h),d===1&&sn===0&&(a.mode&1)===0&&(ea=ue()+500,kl&&Ti()))}function ze(i,a){var d=i.callbackNode;$n(i,a);var h=Gi(i,i===es?us:0);if(h===0)d!==null&&ii(d),i.callbackNode=null,i.callbackPriority=0;else if(a=h&-h,i.callbackPriority!==a){if(d!=null&&ii(d),a===1)i.tag===0?Gf(bt.bind(null,i)):ed(bt.bind(null,i)),Cc(function(){(sn&6)===0&&Ti()}),d=null;else{switch(fa(h)){case 1:d=Vi;break;case 4:d=hr;break;case 16:d=Cr;break;case 536870912:d=it;break;default:d=Cr}d=Yg(d,Ze.bind(null,i))}i.callbackPriority=a,i.callbackNode=d}}function Ze(i,a){if(Le=-1,_e=0,(sn&6)!==0)throw Error(n(327));var d=i.callbackNode;if(eu()&&i.callbackNode!==d)return null;var h=Gi(i,i===es?us:0);if(h===0)return null;if((h&30)!==0||(h&i.expiredLanes)!==0||a)a=gh(i,h);else{a=h;var v=sn;sn|=2;var b=Ka();(es!==i||us!==a)&&(vi=null,ea=ue()+500,ds(i,a));do try{I0();break}catch(ee){Dr(i,ee)}while(!0);ld(),Jc.current=b,sn=v,Gn!==null?a=0:(es=null,us=0,a=Yn)}if(a!==0){if(a===2&&(v=Fs(i),v!==0&&(h=v,a=Ve(i,v))),a===1)throw d=Va,ds(i,0),Be(i,h),ze(i,ue()),d;if(a===6)Be(i,h);else{if(v=i.current.alternate,(h&30)===0&&!Rt(v)&&(a=gh(i,h),a===2&&(b=Fs(i),b!==0&&(h=b,a=Ve(i,b))),a===1))throw d=Va,ds(i,0),Be(i,h),ze(i,ue()),d;switch(i.finishedWork=v,i.finishedLanes=h,a){case 0:case 1:throw Error(n(345));case 2:Ul(i,Hs,vi);break;case 3:if(Be(i,h),(h&130023424)===h&&(a=Qc+500-ue(),10<a)){if(Gi(i,0)!==0)break;if(v=i.suspendedLanes,(v&h)!==h){he(),i.pingedLanes|=i.suspendedLanes&v;break}i.timeoutHandle=Nc(Ul.bind(null,i,Hs,vi),a);break}Ul(i,Hs,vi);break;case 4:if(Be(i,h),(h&4194240)===h)break;for(a=i.eventTimes,v=-1;0<h;){var L=31-rs(h);b=1<<L,L=a[L],L>v&&(v=L),h&=~b}if(h=v,h=ue()-h,h=(120>h?120:480>h?480:1080>h?1080:1920>h?1920:3e3>h?3e3:4320>h?4320:1960*i_(h/1960))-h,10<h){i.timeoutHandle=Nc(Ul.bind(null,i,Hs,vi),h);break}Ul(i,Hs,vi);break;case 5:Ul(i,Hs,vi);break;default:throw Error(n(329))}}}return ze(i,ue()),i.callbackNode===d?Ze.bind(null,i):null}function Ve(i,a){var d=Ga;return i.current.memoizedState.isDehydrated&&(ds(i,a).flags|=256),i=gh(i,a),i!==2&&(a=Hs,Hs=d,a!==null&&rn(a)),i}function rn(i){Hs===null?Hs=i:Hs.push.apply(Hs,i)}function Rt(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(!Vr(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 Be(i,a){for(a&=~Zc,a&=~Bl,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 bt(i){if((sn&6)!==0)throw Error(n(327));eu();var a=Gi(i,0);if((a&1)===0)return ze(i,ue()),null;var d=gh(i,a);if(i.tag!==0&&d===2){var h=Fs(i);h!==0&&(a=h,d=Ve(i,h))}if(d===1)throw d=Va,ds(i,0),Be(i,a),ze(i,ue()),d;if(d===6)throw Error(n(345));return i.finishedWork=i.current.alternate,i.finishedLanes=a,Ul(i,Hs,vi),ze(i,ue()),null}function xn(i,a){var d=sn;sn|=1;try{return i(a)}finally{sn=d,sn===0&&(ea=ue()+500,kl&&Ti())}}function hn(i){q!==null&&q.tag===0&&(sn&6)===0&&eu();var a=sn;sn|=1;var d=kr.transition,h=ln;try{if(kr.transition=null,ln=1,i)return i()}finally{ln=h,kr.transition=d,sn=a,(sn&6)===0&&Ti()}}function Ms(){ar=Qo.current,En(Qo)}function ds(i,a){i.finishedWork=null,i.finishedLanes=0;var d=i.timeoutHandle;if(d!==-1&&(i.timeoutHandle=-1,Aa(d)),Gn!==null)for(d=Gn.return;d!==null;){var h=d;switch(td(h),h.tag){case 1:h=h.type.childContextTypes,h!=null&&La();break;case 3:pi(),En(ws),En(fn),Dc();break;case 5:dd(h);break;case 4:pi();break;case 13:En(Dn);break;case 19:En(Dn);break;case 10:Rc(h.type._context);break;case 22:case 23:Ms()}d=d.return}if(es=i,Gn=i=Ya(i.current,null),us=ar=a,Yn=0,Va=null,Zc=Bl=wo=0,Hs=Ga=null,Li!==null){for(a=0;a<Li.length;a++)if(d=Li[a],h=d.interleaved,h!==null){d.interleaved=null;var v=h.next,b=d.pending;if(b!==null){var L=b.next;b.next=v,h.next=L}d.pending=h}Li=null}return i}function Dr(i,a){do{var d=Gn;try{if(ld(),Fc.current=ei,zc){for(var h=yn.memoizedState;h!==null;){var v=h.queue;v!==null&&(v.pending=null),h=h.next}zc=!1}if(Go=0,Ht=Mn=yn=null,Tl=!1,Ml=0,Xc.current=null,d===null||d.return===null){Yn=1,Va=a,Gn=null;break}e:{var b=i,L=d.return,ee=d,se=a;if(a=us,ee.flags|=32768,se!==null&&typeof se=="object"&&typeof se.then=="function"){var we=se,$e=ee,Me=$e.tag;if(($e.mode&1)===0&&(Me===0||Me===11||Me===15)){var Ce=$e.alternate;Ce?($e.updateQueue=Ce.updateQueue,$e.memoizedState=Ce.memoizedState,$e.lanes=Ce.lanes):($e.updateQueue=null,$e.memoizedState=null)}var Je=Ol(L);if(Je!==null){Je.flags&=-257,kd(Je,L,ee,b,a),Je.mode&1&&lh(b,we,a),a=Je,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){lh(b,we,a),o_();break e}se=Error(n(426))}}else if(Tt&&ee.mode&1){var ts=Ol(L);if(ts!==null){(ts.flags&65536)===0&&(ts.flags|=256),kd(ts,L,ee,b,a),Pa(gi(se,ee));break e}}b=se=gi(se,ee),Yn!==4&&(Yn=2),Ga===null?Ga=[b]:Ga.push(b),b=L;do{switch(b.tag){case 3:b.flags|=65536,a&=-a,b.lanes|=a;var de=jd(b,se,a);Lc(b,de);break e;case 1:ee=se;var oe=b.type,me=b.stateNode;if((b.flags&128)===0&&(typeof oe.getDerivedStateFromError=="function"||me!==null&&typeof me.componentDidCatch=="function"&&(M===null||!M.has(me)))){b.flags|=65536,a&=-a,b.lanes|=a;var Pe=Yo(b,ee,a);Lc(b,Pe);break e}}b=b.return}while(b!==null)}Hg(d)}catch(at){a=at,Gn===d&&d!==null&&(Gn=d=d.return);continue}break}while(!0)}function Ka(){var i=Jc.current;return Jc.current=ei,i===null?ei:i}function o_(){(Yn===0||Yn===3||Yn===2)&&(Yn=4),es===null||(wo&268435455)===0&&(Bl&268435455)===0||Be(es,us)}function gh(i,a){var d=sn;sn|=2;var h=Ka();(es!==i||us!==a)&&(vi=null,ds(i,a));do try{L0();break}catch(v){Dr(i,v)}while(!0);if(ld(),sn=d,Jc.current=h,Gn!==null)throw Error(n(261));return es=null,us=0,Yn}function L0(){for(;Gn!==null;)qg(Gn)}function I0(){for(;Gn!==null&&!oi();)qg(Gn)}function qg(i){var a=Kg(i.alternate,i,ar);i.memoizedProps=i.pendingProps,a===null?Hg(i):Gn=a,Xc.current=null}function Hg(i){var a=i;do{var d=a.alternate;if(i=a.return,(a.flags&32768)===0){if(d=t_(d,a,ar),d!==null){Gn=d;return}}else{if(d=n_(d,a),d!==null){d.flags&=32767,Gn=d;return}if(i!==null)i.flags|=32768,i.subtreeFlags=0,i.deletions=null;else{Yn=6,Gn=null;return}}if(a=a.sibling,a!==null){Gn=a;return}Gn=a=i}while(a!==null);Yn===0&&(Yn=5)}function Ul(i,a,d){var h=ln,v=kr.transition;try{kr.transition=null,ln=1,O0(i,a,d,h)}finally{kr.transition=v,ln=h}return null}function O0(i,a,d,h){do eu();while(q!==null);if((sn&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(da(i,b),i===es&&(Gn=es=null,us=0),(d.subtreeFlags&2064)===0&&(d.flags&2064)===0||D||(D=!0,Yg(Cr,function(){return eu(),null})),b=(d.flags&15990)!==0,(d.subtreeFlags&15990)!==0||b){b=kr.transition,kr.transition=null;var L=ln;ln=1;var ee=sn;sn|=4,Xc.current=null,_h(i,d),qa(d,i),Vu(wl),Mo=!!zo,wl=zo=null,i.current=d,r_(d),Ps(),sn=ee,ln=L,kr.transition=b}else i.current=d;if(D&&(D=!1,q=i,H=v),b=i.pendingLanes,b===0&&(M=null),Hr(d.stateNode),ze(i,ue()),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(y)throw y=!1,i=S,S=null,i;return(H&1)!==0&&i.tag!==0&&eu(),b=i.pendingLanes,(b&1)!==0?i===ne?V++:(V=0,ne=i):V=0,Ti(),null}function eu(){if(q!==null){var i=fa(H),a=kr.transition,d=ln;try{if(kr.transition=null,ln=16>i?16:i,q===null)var h=!1;else{if(i=q,q=null,H=0,(sn&6)!==0)throw Error(n(331));var v=sn;for(sn|=4,Xe=i.current;Xe!==null;){var b=Xe,L=b.child;if((Xe.flags&16)!==0){var ee=b.deletions;if(ee!==null){for(var se=0;se<ee.length;se++){var we=ee[se];for(Xe=we;Xe!==null;){var $e=Xe;switch($e.tag){case 0:case 11:case 15:Zo(8,$e,b)}var Me=$e.child;if(Me!==null)Me.return=$e,Xe=Me;else for(;Xe!==null;){$e=Xe;var Ce=$e.sibling,Je=$e.return;if(Rd($e),$e===we){Xe=null;break}if(Ce!==null){Ce.return=Je,Xe=Ce;break}Xe=Je}}}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)}}Xe=b}}if((b.subtreeFlags&2064)!==0&&L!==null)L.return=b,Xe=L;else e:for(;Xe!==null;){if(b=Xe,(b.flags&2048)!==0)switch(b.tag){case 0:case 11:case 15:Zo(9,b,b.return)}var de=b.sibling;if(de!==null){de.return=b.return,Xe=de;break e}Xe=b.return}}var oe=i.current;for(Xe=oe;Xe!==null;){L=Xe;var me=L.child;if((L.subtreeFlags&2064)!==0&&me!==null)me.return=L,Xe=me;else e:for(L=oe;Xe!==null;){if(ee=Xe,(ee.flags&2048)!==0)try{switch(ee.tag){case 0:case 11:case 15:yo(9,ee)}}catch(at){Jn(ee,ee.return,at)}if(ee===L){Xe=null;break e}var Pe=ee.sibling;if(Pe!==null){Pe.return=ee.return,Xe=Pe;break e}Xe=ee.return}}if(sn=v,Ti(),Ds&&typeof Ds.onPostCommitFiberRoot=="function")try{Ds.onPostCommitFiberRoot(cn,i)}catch{}h=!0}return h}finally{ln=d,kr.transition=a}}return!1}function Vg(i,a,d){a=gi(d,a),a=jd(i,a,1),i=ho(i,a,1),a=he(),i!==null&&(ms(i,1,a),ze(i,a))}function Jn(i,a,d){if(i.tag===3)Vg(i,i,d);else for(;a!==null;){if(a.tag===3){Vg(a,i,d);break}else if(a.tag===1){var h=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof h.componentDidCatch=="function"&&(M===null||!M.has(h))){i=gi(d,i),i=Yo(a,i,1),a=ho(a,i,1),i=he(),a!==null&&(ms(a,1,i),ze(a,i));break}}a=a.return}}function P0(i,a,d){var h=i.pingCache;h!==null&&h.delete(a),a=he(),i.pingedLanes|=i.suspendedLanes&d,es===i&&(us&d)===d&&(Yn===4||Yn===3&&(us&130023424)===us&&500>ue()-Qc?ds(i,0):Zc|=d),ze(i,a)}function Gg(i,a){a===0&&((i.mode&1)===0?a=1:(a=mr,mr<<=1,(mr&130023424)===0&&(mr=4194304)));var d=he();i=os(i,a),i!==null&&(ms(i,a,d),ze(i,d))}function D0(i){var a=i.memoizedState,d=0;a!==null&&(d=a.retryLane),Gg(i,d)}function F0(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),Gg(i,d)}var Kg;Kg=function(i,a,d){if(i!==null)if(i.memoizedProps!==a.pendingProps||ws.current)As=!0;else{if((i.lanes&d)===0&&(a.flags&128)===0)return As=!1,e_(i,a,d);As=(i.flags&131072)!==0}else As=!1,Tt&&(a.flags&1048576)!==0&&Kf(a,Ec,a.index);switch(a.lanes=0,a.tag){case 2:var h=a.type;Pr(i,a),i=a.pendingProps;var v=Ra(a,fn.current);Da(a,d),v=Jt(null,a,h,i,v,d);var b=Qn();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,nr(h)?(b=!0,bl(a)):b=!1,a.memoizedState=v.state!==null&&v.state!==void 0?v.state:null,Nl(a),v.updater=Ua,a.stateNode=v,v._reactInternals=a,Oi(a,h,i,d),a=Pl(null,a,h,!0,b,d)):(a.tag=0,Tt&&b&&Ac(a),Ws(null,a,v,d),a=a.child),a;case 16:h=a.elementType;e:{switch(Pr(i,a),i=a.pendingProps,v=h._init,h=v(h._payload),a.type=h,v=a.tag=B0(h),i=rr(h,i),v){case 0:a=Vc(null,a,h,i,d);break e;case 1:a=or(null,a,h,i,d);break e;case 11:a=ch(null,a,h,i,d);break e;case 14:a=uh(null,a,h,rr(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:rr(h,v),Vc(i,a,h,v,d);case 1:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:rr(h,v),or(i,a,h,v,d);case 3:e:{if(Sd(a),i===null)throw Error(n(387));h=a.pendingProps,b=a.memoizedState,v=b.element,Jf(i,a),Ic(a,h,null,d);var L=a.memoizedState;if(h=L.element,b.isDehydrated)if(b={element:h,isDehydrated:!1,cache:L.cache,pendingSuspenseBoundaries:L.pendingSuspenseBoundaries,transitions:L.transitions},a.updateQueue.baseState=b,a.memoizedState=b,a.flags&256){v=gi(Error(n(423)),a),a=Nd(i,a,h,d,v);break e}else if(h!==v){v=gi(Error(n(424)),a),a=Nd(i,a,h,d,v);break e}else for(Te=co(a.stateNode.containerInfo.firstChild),Bs=a,Tt=!0,br=null,d=Vo(a,null,h,d),a.child=d;d;)d.flags=d.flags&-3|4096,d=d.sibling;else{if(Oa(),h===v){a=Pi(i,a,d);break e}Ws(i,a,h,d)}a=a.child}return a;case 5:return Oc(a),i===null&&rd(a),h=a.type,v=a.pendingProps,b=i!==null?i.memoizedProps:null,L=v.children,Ea(h,v)?L=null:b!==null&&Ea(h,b)&&(a.flags|=32),dh(i,a),Ws(i,a,L,d),a.child;case 6:return i===null&&rd(a),null;case 13:return fh(i,a,d);case 4:return El(a,a.stateNode.containerInfo),h=a.pendingProps,i===null?a.child=_i(a,null,h,d):Ws(i,a,h,d),a.child;case 11:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:rr(h,v),ch(i,a,h,v,d);case 7:return Ws(i,a,a.pendingProps,d),a.child;case 8:return Ws(i,a,a.pendingProps.children,d),a.child;case 12:return Ws(i,a,a.pendingProps.children,d),a.child;case 10:e:{if(h=a.type._context,v=a.pendingProps,b=a.memoizedProps,L=v.value,Cn(ut,h._currentValue),h._currentValue=L,b!==null)if(Vr(b.value,L)){if(b.children===v.children&&!ws.current){a=Pi(i,a,d);break e}}else for(b=a.child,b!==null&&(b.return=a);b!==null;){var ee=b.dependencies;if(ee!==null){L=b.child;for(var se=ee.firstContext;se!==null;){if(se.context===h){if(b.tag===1){se=Ii(-1,d&-d),se.tag=2;var we=b.updateQueue;if(we!==null){we=we.shared;var $e=we.pending;$e===null?se.next=se:(se.next=$e.next,$e.next=se),we.pending=se}}b.lanes|=d,se=b.alternate,se!==null&&(se.lanes|=d),cd(b.return,d,a),ee.lanes|=d;break}se=se.next}}else if(b.tag===10)L=b.type===a.type?null:b.child;else if(b.tag===18){if(L=b.return,L===null)throw Error(n(341));L.lanes|=d,ee=L.alternate,ee!==null&&(ee.lanes|=d),cd(L,d,a),L=b.sibling}else L=b.child;if(L!==null)L.return=b;else for(L=b;L!==null;){if(L===a){L=null;break}if(b=L.sibling,b!==null){b.return=L.return,L=b;break}L=L.return}b=L}Ws(i,a,v.children,d),a=a.child}return a;case 9:return v=a.type,h=a.pendingProps.children,Da(a,d),v=Ir(v),h=h(v),a.flags|=1,Ws(i,a,h,d),a.child;case 14:return h=a.type,v=rr(h,a.pendingProps),v=rr(h.type,v),uh(i,a,h,v,d);case 15:return ir(i,a,a.type,a.pendingProps,d);case 17:return h=a.type,v=a.pendingProps,v=a.elementType===h?v:rr(h,v),Pr(i,a),a.tag=1,nr(h)?(i=!0,bl(a)):i=!1,Da(a,d),ah(a,h,v),Oi(a,h,v,d),Pl(null,a,h,!0,i,d);case 19:return $d(i,a,d);case 22:return Jo(i,a,d)}throw Error(n(156,a.tag))};function Yg(i,a){return dr(i,a)}function z0(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 xi(i,a,d,h){return new z0(i,a,d,h)}function a_(i){return i=i.prototype,!(!i||!i.isReactComponent)}function B0(i){if(typeof i=="function")return a_(i)?1:0;if(i!=null){if(i=i.$$typeof,i===W)return 11;if(i===z)return 14}return 2}function Ya(i,a){var d=i.alternate;return d===null?(d=xi(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 yh(i,a,d,h,v,b){var L=2;if(h=i,typeof i=="function")a_(i)&&(L=1);else if(typeof i=="string")L=5;else e:switch(i){case J:return Wl(d.children,v,b,a);case Y:L=8,v|=8;break;case re:return i=xi(12,d,a,v|2),i.elementType=re,i.lanes=b,i;case O:return i=xi(13,d,a,v),i.elementType=O,i.lanes=b,i;case $:return i=xi(19,d,a,v),i.elementType=$,i.lanes=b,i;case te:return wh(d,v,b,a);default:if(typeof i=="object"&&i!==null)switch(i.$$typeof){case ce:L=10;break e;case fe:L=9;break e;case W:L=11;break e;case z:L=14;break e;case A:L=16,h=null;break e}throw Error(n(130,i==null?i:typeof i,""))}return a=xi(L,d,a,v),a.elementType=i,a.type=h,a.lanes=b,a}function Wl(i,a,d,h){return i=xi(7,i,h,a),i.lanes=d,i}function wh(i,a,d,h){return i=xi(22,i,h,a),i.elementType=te,i.lanes=d,i.stateNode={isHidden:!1},i}function l_(i,a,d){return i=xi(6,i,null,a),i.lanes=d,i}function c_(i,a,d){return a=xi(4,i.children!==null?i.children:[],i.key,a),a.lanes=d,a.stateNode={containerInfo:i.containerInfo,pendingChildren:null,implementation:i.implementation},a}function U0(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=Js(0),this.expirationTimes=Js(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Js(0),this.identifierPrefix=h,this.onRecoverableError=v,this.mutableSourceEagerHydrationData=null}function u_(i,a,d,h,v,b,L,ee,se){return i=new U0(i,a,d,ee,se),a===1?(a=1,b===!0&&(a|=8)):a=0,b=xi(3,null,null,a),i.current=b,b.stateNode=i,b.memoizedState={element:h,isDehydrated:d,cache:null,transitions:null,pendingSuspenseBoundaries:null},Nl(b),i}function W0(i,a,d){var h=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:U,key:h==null?null:""+h,children:i,containerInfo:a,implementation:d}}function Jg(i){if(!i)return xr;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(nr(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(nr(d))return xl(i,d,a)}return a}function Xg(i,a,d,h,v,b,L,ee,se){return i=u_(d,h,!0,i,v,b,L,ee,se),i.context=Jg(null),d=i.current,h=he(),v=Ae(d),b=Ii(h,v),b.callback=a??null,ho(d,b,v),i.current.lanes=v,ms(i,v,h),ze(i,h),i}function vh(i,a,d,h){var v=a.current,b=he(),L=Ae(v);return d=Jg(d),a.context===null?a.context=d:a.pendingContext=d,a=Ii(b,L),a.payload={element:i},h=h===void 0?null:h,h!==null&&(a.callback=h),i=ho(v,a,L),i!==null&&(Oe(i,v,L,b),Cl(i,v,L)),L}function xh(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 Zg(i,a){if(i=i.memoizedState,i!==null&&i.dehydrated!==null){var d=i.retryLane;i.retryLane=d!==0&&d<a?d:a}}function d_(i,a){Zg(i,a),(i=i.alternate)&&Zg(i,a)}function q0(){return null}var Qg=typeof reportError=="function"?reportError:function(i){console.error(i)};function f_(i){this._internalRoot=i}bh.prototype.render=f_.prototype.render=function(i){var a=this._internalRoot;if(a===null)throw Error(n(409));vh(i,a,null,null)},bh.prototype.unmount=f_.prototype.unmount=function(){var i=this._internalRoot;if(i!==null){this._internalRoot=null;var a=i.containerInfo;hn(function(){vh(null,i,null,null)}),a[vr]=null}};function bh(i){this._internalRoot=i}bh.prototype.unstable_scheduleHydration=function(i){if(i){var a=Er();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&&dc(i)}};function h_(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 ey(){}function H0(i,a,d,h,v){if(v){if(typeof h=="function"){var b=h;h=function(){var we=xh(L);b.call(we)}}var L=Xg(a,h,i,0,null,!1,!1,"",ey);return i._reactRootContainer=L,i[vr]=L.current,yl(i.nodeType===8?i.parentNode:i),hn(),L}for(;v=i.lastChild;)i.removeChild(v);if(typeof h=="function"){var ee=h;h=function(){var we=xh(se);ee.call(we)}}var se=u_(i,0,!1,null,null,!1,!1,"",ey);return i._reactRootContainer=se,i[vr]=se.current,yl(i.nodeType===8?i.parentNode:i),hn(function(){vh(a,se,d,h)}),se}function kh(i,a,d,h,v){var b=d._reactRootContainer;if(b){var L=b;if(typeof v=="function"){var ee=v;v=function(){var se=xh(L);ee.call(se)}}vh(a,L,i,v)}else L=H0(d,a,i,v,h);return xh(L)}uc=function(i){switch(i.tag){case 3:var a=i.stateNode;if(a.current.memoizedState.isDehydrated){var d=Hn(a.pendingLanes);d!==0&&(Ki(a,d|1),ze(a,ue()),(sn&6)===0&&(ea=ue()+500,Ti()))}break;case 13:hn(function(){var h=os(i,1);if(h!==null){var v=he();Oe(h,i,1,v)}}),d_(i,1)}},To=function(i){if(i.tag===13){var a=os(i,134217728);if(a!==null){var d=he();Oe(a,i,134217728,d)}d_(i,134217728)}},_s=function(i){if(i.tag===13){var a=Ae(i),d=os(i,a);if(d!==null){var h=he();Oe(d,i,a,h)}d_(i,a)}},Er=function(){return ln},Ar=function(i,a){var d=ln;try{return ln=i,a()}finally{ln=d}},Nr=function(i,a,d){switch(a){case"input":if(ke(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=Ma(h);if(!v)throw Error(n(90));pt(h),ke(h,v)}}}break;case"textarea":en(i,d);break;case"select":a=d.value,a!=null&&Ie(i,!!d.multiple,a,!1)}},rt=xn,ct=hn;var V0={usingClientEntryPoint:!1,Events:[Uo,Kr,Ma,Ye,Ge,xn]},Fd={findFiberByHostInstance:Gr,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},G0={bundleType:Fd.bundleType,version:Fd.version,rendererPackageName:Fd.rendererPackageName,rendererConfig:Fd.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:I.ReactCurrentDispatcher,findHostInstanceByFiber:function(i){return i=ss(i),i===null?null:i.stateNode},findFiberByHostInstance:Fd.findFiberByHostInstance||q0,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 Sh=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Sh.isDisabled&&Sh.supportsFiber)try{cn=Sh.inject(G0),Ds=Sh}catch{}}return Fr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=V0,Fr.createPortal=function(i,a){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!h_(a))throw Error(n(200));return W0(i,a,null,d)},Fr.createRoot=function(i,a){if(!h_(i))throw Error(n(299));var d=!1,h="",v=Qg;return a!=null&&(a.unstable_strictMode===!0&&(d=!0),a.identifierPrefix!==void 0&&(h=a.identifierPrefix),a.onRecoverableError!==void 0&&(v=a.onRecoverableError)),a=u_(i,1,!1,null,null,d,!1,h,v),i[vr]=a.current,yl(i.nodeType===8?i.parentNode:i),new f_(a)},Fr.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},Fr.flushSync=function(i){return hn(i)},Fr.hydrate=function(i,a,d){if(!jh(a))throw Error(n(200));return kh(null,i,a,!0,d)},Fr.hydrateRoot=function(i,a,d){if(!h_(i))throw Error(n(405));var h=d!=null&&d.hydratedSources||null,v=!1,b="",L=Qg;if(d!=null&&(d.unstable_strictMode===!0&&(v=!0),d.identifierPrefix!==void 0&&(b=d.identifierPrefix),d.onRecoverableError!==void 0&&(L=d.onRecoverableError)),a=Xg(a,null,i,1,d??null,v,!1,b,L),i[vr]=a.current,yl(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 bh(a)},Fr.render=function(i,a,d){if(!jh(a))throw Error(n(200));return kh(null,i,a,!1,d)},Fr.unmountComponentAtNode=function(i){if(!jh(i))throw Error(n(40));return i._reactRootContainer?(hn(function(){kh(null,null,i,!1,function(){i._reactRootContainer=null,i[vr]=null})}),!0):!1},Fr.unstable_batchedUpdates=xn,Fr.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 kh(i,a,d,!1,h)},Fr.version="18.3.1-next-f1338f8080-20240426",Fr}var ly;function Sv(){if(ly)return p_.exports;ly=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(),p_.exports=nj(),p_.exports}var cy;function sj(){if(cy)return Nh;cy=1;var e=Sv();return Nh.createRoot=e.createRoot,Nh.hydrateRoot=e.hydrateRoot,Nh}var rj=sj();const ij=rg(rj),Nv=[{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"]}];Nv.map(e=>({id:e.id,label:e.label}));function oj(e){return`theme-${String(e||"").trim()||"dark"}`}function uy(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(oj(e))}catch{}}const dp=[{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}],fp=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function aj(e){const t=String(e).trim();return dp.find(n=>n.id===t)||dp[1]}function lj(e){const t=String(e).trim();return fp.find(n=>n.id===t)||fp[1]}function dy(e){try{const t=document.documentElement,n=aj(e.font_scale||"md"),r=lj(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(r.density))}catch{}}const w_={sm:"(max-width: 767.98px)",md:"(max-width: 1023.98px)",short:"(max-height: 500px)"};function cj(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function fy(e){const[t,n]=p.useState(()=>cj(e));return p.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 Bd=null;function uj(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 dj(){if(Bd)return Bd;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}=uj(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),Bd=()=>{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"),Bd=null},Bd}var Cv=Sv();function tu(...e){return e.filter(Boolean).join(" ")}function xu({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:m=240,variant:_="panel",className:g,triggerClassName:w,ariaLabel:x,id:k,includeValueOption:j=!1,onOpen:N,customOptionLabel:C,validateCustomValue:E,onChange:T,renderOption:I,renderValue:K}){const U=p.useRef(null),J=p.useRef(null),Y=p.useRef(null),re=p.useRef(N),ce=p.useId(),fe=k||`af-select-${ce.replace(/[^a-zA-Z0-9_-]/g,"")}`,W=`${fe}-listbox`,[O,$]=p.useState(!1),[z,A]=p.useState(""),[te,P]=p.useState(0),[F,G]=p.useState("bottom"),[R,Z]=p.useState({left:0,top:0,width:0});p.useEffect(()=>{re.current=N},[N]);const X=p.useMemo(()=>{if(!j)return t;const xe=String(e??"").trim();return!xe||t.some(Ie=>Ie.value===xe)?t:[...t,{value:xe,label:xe}]},[j,t,e]),Q=p.useMemo(()=>{const xe=String(e??"");return X.find(Ie=>Ie.value===xe)||null},[X,e]),le=p.useMemo(()=>(Q==null?void 0:Q.label)||String(e||"").trim()||"",[Q,e]),ge=p.useMemo(()=>{const xe=z.trim().toLowerCase();return xe?X.filter(Ie=>Ie.label.toLowerCase().includes(xe)||Ie.value.toLowerCase().includes(xe)):X},[X,z]),pe=p.useMemo(()=>{if(!c)return null;const xe=z.trim();if(!xe||X.some(zt=>zt.value===xe))return null;const qe=(E==null?void 0:E(xe,{options:X}))||"";return{value:xe,label:C?C(xe):`Use "${xe}"`,disabled:!!qe,reason:qe}},[c,C,X,z,E]),ye=p.useMemo(()=>{const xe=pe?[pe,...ge]:ge;if(xe.length>0)return xe;const Ie=String(e??"").trim();return o&&Ie?[{value:Ie,label:le||Ie}]:xe},[pe,ge,o,le,e]),Ne=p.useCallback(()=>{const xe=U.current;if(!xe)return;const Ie=xe.getBoundingClientRect(),qe=Math.max(Ie.width,m),zt=Math.max(8,Math.min(Ie.left,window.innerWidth-qe-8)),en=window.innerHeight-Ie.bottom,bn=Ie.top,Wt=en>=220||en>=bn?"bottom":"top";G(Wt);const It=Wt==="bottom"?Ie.bottom+6:Ie.top-6;Z({left:zt,top:It,width:qe})},[m]),Ue=p.useCallback(()=>{$(!1),A("")},[]);p.useEffect(()=>{var xe;O&&((xe=re.current)==null||xe.call(re))},[O]),p.useEffect(()=>{if(!O)return;Ne();const xe=()=>Ne();return window.addEventListener("resize",xe),window.addEventListener("scroll",xe,!0),()=>{window.removeEventListener("resize",xe),window.removeEventListener("scroll",xe,!0)}},[O,Ne]),p.useEffect(()=>{if(!O)return;const xe=Ie=>{var zt,en;const qe=Ie.target;qe&&((zt=U.current)!=null&&zt.contains(qe)||(en=J.current)!=null&&en.contains(qe)||Ue())};return document.addEventListener("mousedown",xe,!0),()=>document.removeEventListener("mousedown",xe,!0)},[O,Ue]),p.useEffect(()=>{if(!O)return;const xe=Math.max(0,ye.findIndex(Ie=>Ie.value===e));P(xe===-1?0:xe),l&&setTimeout(()=>{var Ie;return(Ie=Y.current)==null?void 0:Ie.focus()},0)},[O,l,e,ye]);const We=xe=>{var qe;const Ie=ye.find(zt=>zt.value===xe);Ie!=null&&Ie.disabled||(T(xe),Ue(),(qe=U.current)==null||qe.focus())},pt=xe=>{var Ie,qe;if(xe.key==="Escape")return xe.preventDefault(),Ue(),(Ie=U.current)==null||Ie.focus(),!0;if(xe.key==="Tab")return Ue(),(qe=U.current)==null||qe.focus(),!1;if(xe.key==="ArrowDown")return xe.preventDefault(),P(zt=>Math.min(zt+1,Math.max(0,ye.length-1))),!0;if(xe.key==="ArrowUp")return xe.preventDefault(),P(zt=>Math.max(zt-1,0)),!0;if(xe.key==="Home")return xe.preventDefault(),P(0),!0;if(xe.key==="End")return xe.preventDefault(),P(Math.max(0,ye.length-1)),!0;if(xe.key==="Enter"){xe.preventDefault();const zt=ye[te];return zt&&We(zt.value),!0}return!1},Fe=xe=>{if(!r){if(O){if(pt(xe))return;if(xe.key===" "&&!l){xe.preventDefault();const Ie=ye[te];Ie&&We(Ie.value)}return}(xe.key==="Enter"||xe.key===" "||xe.key==="ArrowDown"||xe.key==="ArrowUp")&&(xe.preventDefault(),$(!0))}},tt=!!String(e||"").trim(),lt=tt?le:n,Ke=pe!=null&&pe.disabled?pe.reason||"Unavailable":"",ke=O&&ye.length>0?`${fe}-opt-${te}`:void 0,Re=s.jsx("span",{className:tu("af-select-value",!tt&&"af-select-value--placeholder"),children:o&&!tt?"Loading…":lt}),ht=K?K(Q,String(e||"")):Re;return s.jsxs("span",{className:tu("af-select",_==="pin"?"af-select--pin":"af-select--panel",g),children:[s.jsxs("button",{ref:U,id:fe,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&&$(Ie=>!Ie)},onKeyDown:Fe,role:l?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":O,"aria-controls":O?W:void 0,"aria-activedescendant":l?void 0:ke,"aria-label":x,children:[ht,s.jsx("span",{className:tu("af-select-caret",O&&"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 Ie;xe.preventDefault(),xe.stopPropagation(),T(""),Ue(),(Ie=U.current)==null||Ie.focus()},title:"Clear",children:"×"}):null,O?Cv.createPortal(s.jsxs("div",{ref:J,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:pt,tabIndex:-1,children:[l?s.jsxs("div",{className:"af-select-search",children:[s.jsx("input",{ref:Y,className:"af-select-search-input",value:z,onChange:xe=>A(xe.target.value),placeholder:u,onKeyDown:pt,role:"combobox","aria-expanded":!0,"aria-controls":W,"aria-activedescendant":ke,"aria-invalid":!!Ke,"aria-describedby":Ke?`${fe}-custom-error`:void 0}),Ke?s.jsx("div",{id:`${fe}-custom-error`,className:"af-select-custom-error",role:"alert",children:Ke}):null]}):null,s.jsx("div",{className:"af-select-options",role:"listbox",id:W,"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,Ie)=>{var It;const qe=xe.value===e,zt=Ie===te,en=String(xe.group||"").trim(),bn=Ie>0?String(((It=ye[Ie-1])==null?void 0:It.group)||"").trim():"",Wt=!!en&&en!==bn;return s.jsxs(ve.Fragment,{children:[Wt?s.jsx("div",{className:"af-select-group",role:"presentation",children:en}):null,s.jsx("div",{id:`${fe}-opt-${Ie}`,role:"option","aria-selected":qe,className:tu("af-select-option",qe&&"af-select-option--selected",zt&&"af-select-option--highlighted",xe.disabled&&"af-select-option--disabled"),title:xe.disabled?xe.reason||"Unavailable":void 0,onMouseEnter:()=>P(Ie),onMouseDown:Sn=>{Sn.preventDefault(),Sn.stopPropagation()},onClick:()=>We(xe.value),"aria-disabled":xe.disabled?!0:void 0,children:I?I(xe,{selected:qe,highlighted:zt}):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]}),qe?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},xe.value)})})]}),document.body):null]})}function fj(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 hj(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 mj(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)"),m=String(e.provider||"").trim(),_=String(e.model||"").trim(),g=fj(e.providers),w=hj(e.models),x=t||!!e.loadingProviders,k=t||!!e.loadingModels,j=[...r?[{value:"",label:o}]:[],...g.map(C=>({value:C.name,label:C.display_name?`${C.display_name} (${C.name})`:C.name}))],N=[...r?[{value:"",label:o}]:[],...w.map(C=>({value:C,label:C}))];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(xu,{value:m,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:C=>e.onChange({provider:String(C||"").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(xu,{value:_,options:N,placeholder:r?o:f,disabled:k,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:u,onChange:C=>e.onChange({provider:m,model:String(C||"").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 hy(...e){return e.filter(Boolean).join(" ")}function _j({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:m,userPlaceholder:_="admin",onUserIdChange:g,token:w,tokenPlaceholder:x="Paste Gateway user token",showToken:k=!1,onTokenChange:j,onShowTokenChange:N,remember:C=!1,rememberLabel:E="Remember this browser",onRememberChange:T,loading:I=!1,submitting:K=!1,submitDisabled:U=!1,submitLabel:J="Sign in",submittingLabel:Y="Signing in...",closeLabel:re="Close",signOutLabel:ce="Sign out",showClose:fe=!1,showSignOut:W=!1,error:O,message:$,className:z,onSubmit:A,onClose:te,onSignOut:P}){const F=I||K,G=F||U||!String(m||"").trim()||!String(w||"").trim(),R=Z=>{Z.preventDefault(),!G&&A()};return s.jsxs("form",{className:hy("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:hy("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:Z=>f==null?void 0:f(Z.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:m,onChange:Z=>g(Z.target.value),placeholder:_,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:k?"text":"password",value:w,onChange:Z=>j(Z.target.value),placeholder:x,autoComplete:"off","data-1p-ignore":"","data-lpignore":"true","data-bwignore":"",spellCheck:!1,disabled:F}),s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>N==null?void 0:N(!k),disabled:F,children:k?"Hide":"Show"})]}),s.jsxs("label",{className:"af-gateway-signin__checkbox",children:[s.jsx("input",{type:"checkbox",checked:!!C,onChange:Z=>T==null?void 0:T(Z.target.checked),disabled:F}),E]})]}),O?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:O}):null,!O&&$?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:$}):null,s.jsxs("div",{className:"af-gateway-signin__actions",children:[fe?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:te,disabled:F,children:re}):null,W?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(P==null?void 0:P()),disabled:F,children:ce}):null,s.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:G,children:K?Y:J})]})]})}function pj(e){return e==="light"?"Light":"Dark"}function gj(e){const t=e.themes&&e.themes.length?e.themes:Nv,n=e.showSwatches!==!1,r=e.variant||"panel",o=p.useMemo(()=>{const u={};for(const c of t)u[c.id]=c;return u},[t]),l=p.useMemo(()=>t.map(u=>({value:u.id,label:u.label,group:pj(u.group)})),[t]);return s.jsx(xu,{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(),m=o[f],_=(m==null?void 0:m.label)||f||e.placeholder||"Select theme…",g=(m==null?void 0:m.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:_}),n&&g?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:g.map((x,k)=>s.jsx("span",{className:"af-theme-swatch",style:{background:x}},`${f}:${k}`))}):null]})},renderOption:(u,c)=>{const f=String(u.value||"").trim(),m=o[f],_=(m==null?void 0:m.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&&_?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:_.map((g,w)=>s.jsx("span",{className:"af-theme-swatch",style:{background:g}},`${f}:${w}`))}):null,c.selected?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function yj(e){const t=e.scales&&e.scales.length?e.scales:dp,n=e.variant||"panel",r=p.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(xu,{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 wj(e){const t=e.densities&&e.densities.length?e.densities:fp,n=e.variant||"panel",r=p.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return s.jsx(xu,{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 vj=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function xj(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 et({name:e,size:t=16,className:n,title:r,...o}){const l=r?void 0:!0,u=vj.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,xj(e)]})}const hp="api/gateway",Ef="api/connection/gateway";function wt(e){const t=String(e||"");if(t.startsWith("/"))throw new Error(`gatewayApiPath takes a route relative to the gateway API, got ${JSON.stringify(t)}.`);return t?`${hp}/${t}`:hp}function ig(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 bj(e){const t=String(e||""),n=`/${hp}/`;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 jj(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function kj(e){return jj(e)?!e.checked:null}let Sj=0;function No(e){const{label:t,checked:n,onChange:r,description:o,reasonVisible:l=!0,describedBy:u,hint:c,busy:f=!1,variant:m="inline",ariaLabel:_,className:g,id:w,action:x}=e,k=String(e.unavailableReason||"").trim(),j=!!k,N=u||(w?`${w}-reason`:j?`af-switch-reason-${++Sj}`:void 0),C=["af-switch",m==="row"?"af-switch--row":m==="sm"?"af-switch--sm":"",j?"af-switch--unavailable":"",g||""].filter(Boolean).join(" "),E=I=>{const K=kj({checked:n,unavailableReason:k,busy:f});if(K===null){I.preventDefault();return}r==null||r(K)},T=s.jsxs("button",{type:"button",role:"switch",id:w,className:C,"data-action":x,"aria-checked":n?"true":"false","aria-disabled":j?"true":void 0,"aria-describedby":j?N:void 0,"aria-busy":f?"true":void 0,"aria-label":_,"aria-description":o?void 0:c,title:j?c?`${k}
|
|
41
|
+
${c}`:k:c,onClick:E,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?T:s.jsxs("span",{className:m==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[T,s.jsx("span",{id:N,className:l?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:k})]})}function Nj(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,onChange:l=>{var u;return(u=e.onChange)==null?void 0:u.call(e,l.target.checked)},disabled:!!t,"aria-describedby":r}),s.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:s.jsx("span",{className:"af-switch__thumb"})}),s.jsx("span",{className:"af-switch__text",children:s.jsx("span",{className:"af-switch__label",children:e.label})})]});return t?s.jsxs("span",{className:e.variant==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[o,s.jsx("span",{id:r,className:"af-switch__reason",children:t})]}):o}async function mp(e=Ef){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 Cj(e,t=Ef){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 Ev(e=Ef){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 v_(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 Av(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 Ej(e){const t=e.connectionPath||Ef,[n,r]=p.useState(!1),[o,l]=p.useState(!1),[u,c]=p.useState(null),[f,m]=p.useState(!1);p.useEffect(()=>{e.isOpen||m(!1)},[e.isOpen]);const[_,g]=p.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[w,x]=p.useState("admin"),[k,j]=p.useState(""),[N,C]=p.useState(!1),[E,T]=p.useState(!0),[I,K]=p.useState(""),[U,J]=p.useState(""),Y=p.useMemo(()=>Av(u),[u]),re=O=>{var $;c(O),($=e.onStatusChange)==null||$.call(e,O)},ce=p.useRef(!1);if(p.useEffect(()=>{var $;if(!e.isOpen)return;const O=!ce.current;if(ce.current=!0,O&&e.initialStatus!==void 0&&e.initialStatus!==null){const z=e.initialStatus;re(z),typeof z.gateway_url=="string"&&z.gateway_url.trim()&&g(v_(z.gateway_url));const A=($=z.gateway)==null?void 0:$.principal;A!=null&&A.user_id&&x(A.user_id);return}r(!0),K(""),mp(t).then(z=>{var te;re(z),typeof z.gateway_url=="string"&&z.gateway_url.trim()&&g(v_(z.gateway_url));const A=(te=z.gateway)==null?void 0:te.principal;A!=null&&A.user_id&&x(A.user_id)}).catch(z=>K(`Failed to load connection status: ${String((z==null?void 0:z.message)||z)}`)).finally(()=>r(!1))},[e.isOpen]),p.useEffect(()=>{if(!e.isOpen)return;const O=$=>{$.key==="Escape"&&!$.defaultPrevented&&!e.blocking&&($.preventDefault(),e.onClose())};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||f)return null;const fe=async()=>{l(!0),K(""),J("");try{const O=v_(_);g(O);const $=await Cj({gateway_url:O,gateway_user_id:w,gateway_token:k,persist:E},t);re($),j(""),m(!0),e.onClose()}catch(O){K(String((O==null?void 0:O.message)||O))}finally{l(!1)}},W=async()=>{l(!0),K(""),J("");try{await Ev(t),j("");const O=await mp(t).catch(()=>null);re(O),J("Signed out. This browser no longer holds a gateway session.")}catch(O){K(String((O==null?void 0:O.message)||O))}finally{l(!1)}};return s.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:O=>{!e.blocking&&O.target===O.currentTarget&&e.onClose()},children:s.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:s.jsx(_j,{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:Y.label,statusTone:Y.tone,showGatewayUrl:!0,gatewayUrl:_,onGatewayUrlChange:O=>g(O),userId:w,onUserIdChange:x,token:k,tokenPlaceholder:u!=null&&u.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:N,onTokenChange:j,onShowTokenChange:C,remember:E,rememberLabel:"Keep this browser signed in",onRememberChange:T,loading:n,submitting:o,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(u!=null&&u.has_session),onSignOut:W,error:I,message:U,onSubmit:fe})})})}function Aj(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function $j(e){const t=e||{},n=t.connectionPath||Ef,r=t.variant||"dismissable",o=p.useRef(t.onStatusChange);o.current=t.onStatusChange;const l=p.useRef(r);l.current=r;const u=p.useRef(!!t.autoOpenMidSession);u.current=!!t.autoOpenMidSession;const[c,f]=p.useState(null),[m,_]=p.useState("loading"),[g,w]=p.useState(!1),x=p.useRef(!1),k=p.useRef(!1),j=p.useRef("loading"),N=p.useRef("none"),C=p.useRef(!1),E=p.useRef(0),T=p.useCallback($=>{var A;E.current+=1,f($),(A=o.current)==null||A.call(o,$);const z=Aj($);if(z)_("connected"),j.current="connected",x.current=!1,N.current="none",k.current||w(!1);else if($!==null){const te=j.current;_("disconnected"),j.current="disconnected",te!=="disconnected"&&(N.current=C.current?"signout":te==="connected"?"mid":"boot");const P=l.current==="blocking"||N.current!=="mid"||u.current;!x.current&&P&&w(!0)}$!==null&&(k.current=z)},[]),I=p.useCallback(async()=>{const $=E.current;try{const z=await mp(n);if(E.current!==$)return;T(z)}catch{if(E.current!==$)return;T(null)}},[n,T]),[K,U]=p.useState(!1),[J,Y]=p.useState(null),re=p.useCallback(async()=>{U(!0),Y(null),E.current+=1;let $=null;try{await Ev(n)}catch(z){$=String((z==null?void 0:z.message)||z||"Sign-out request failed")}C.current=!0;try{await I()}finally{C.current=!1}Y($),U(!1)},[n,I]),ce=p.useRef(!1);p.useEffect(()=>{ce.current||(ce.current=!0,I())},[I]);const fe=p.useCallback(()=>{w(!0)},[]),W=p.useCallback(()=>{const $=j.current;r==="blocking"&&$==="disconnected"||($==="disconnected"&&(x.current=!0),w(!1))},[r]),O=p.useMemo(()=>({isOpen:g,onClose:W,blocking:r==="blocking"&&m!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:c,onStatusChange:T}),[g,W,r,m,t.appName,n,t.defaultGatewayUrl,c,T]);return{status:c,phase:m,connected:m==="connected",modalOpen:g,signingOut:K,signOutError:J,openModal:fe,refresh:I,signOut:re,modalProps:O}}function Tj(){return globalThis.crypto}function Mj(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 Nm(){const e=Tj();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return Mj(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function Rj(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 Lj(){return Nm()}function Ij(){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 Oj(e){const t=e.commandsPath||wt("commands"),n=Lj(),r=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),o=e.csrfToken!==void 0?[e.csrfToken]:Ij();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 m=f&&typeof f=="object"&&f.detail?String(f.detail):`HTTP ${c.status}`;if(l=new Error(m),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 Pj(e){const[t,n]=p.useState(""),[r,o]=p.useState({kind:"idle"}),l=p.useRef(!1),u=p.useRef(0);p.useEffect(()=>{u.current+=1,o({kind:"idle"})},[e.runId]);const c=!e.disabled&&t.trim().length>0&&r.kind!=="sending",f=p.useMemo(()=>e.parked?"Run is waiting — your guidance delivers at its next wake (steers do not wake runs).":"Delivers at the run's next loop boundary.",[e.parked]),m=async()=>{var x;const g=t.trim();if(!g||l.current||e.disabled)return;l.current=!0;const w=u.current;o({kind:"sending"});try{const k=e.submit?await e.submit(e.runId,g):await Oj({runId:e.runId,guidance:g,commandsPath:e.commandsPath});if(u.current!==w)return;if(!k.accepted&&!k.duplicate){o({kind:"error",detail:"The gateway did not accept this steer (accepted=false)."});return}o({kind:"queued",seq:k.seq,duplicate:k.duplicate}),n(""),(x=e.onSent)==null||x.call(e,{...k,guidance:g})}catch(k){u.current===w&&o({kind:"error",detail:String((k==null?void 0:k.message)||k)})}finally{l.current=!1}},_=g=>{g.key==="Enter"&&(g.metaKey||g.ctrlKey)&&(g.preventDefault(),m())};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:g=>{n(g.target.value),(r.kind==="error"||r.kind==="queued")&&o({kind:"idle"})},onKeyDown:_}),s.jsx("button",{type:"button",className:"af-steer__send",disabled:!c,onClick:()=>void m(),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 Dj(e){const t=e.closeOnEscape!==!1,n=p.useRef(null);return p.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]),p.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 Fj={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"},zj={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"}},Bj={framework:Fj,apps:zj},im=Bj;function Uj(){return Object.keys(im.apps).sort()}function Wj(e,t){const n=Object.prototype.hasOwnProperty.call(im.apps,e)?im.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${Uj().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 qj(e,t){const n=im.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 x_(e){return typeof e=="string"?e.trim():""}function my(e,t){if(t!=null)return[["Gateway",`unavailable (${String(t).trim()||"unknown error"})`]];const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=x_(n.abstractgateway);if(!r)return[["Gateway","unavailable (the gateway did not report its version)"]];const o=x_(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,m)=>f<m?-1:f>m?1:0);for(const f of c){const m=x_(u[f]);m&&l.push([`Gateway package ${f}`,m])}return l}const Hj='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function Vj(e,t,n){if(e.key!=="Tab"||!t)return;const r=Array.from(t.querySelectorAll(Hj));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 Gj=/https?:\/\/[^\s<>"]+/g;function Kj(e,t){if(e==="Contact")return[{text:t,href:`mailto:${t}`}];const n=[];let r=0;for(const o of t.matchAll(Gj)){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 Yj({label:e,value:t}){return s.jsx("span",{children:Kj(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 Jj(e){const t=p.useRef(null),n=p.useRef(null),r=p.useId(),o=p.useRef(e.onClose);if(o.current=e.onClose,p.useEffect(()=>{var m;if(!e.open)return;const c=document.activeElement;(m=t.current)==null||m.focus();const f=_=>{if(!_.defaultPrevented){if(_.key==="Escape"){_.preventDefault(),o.current();return}Vj(_,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=qj(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],m)=>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(Yj,{label:c,value:f})})]},`${m}:${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 Xj(e){const{connection:t}=e,n=t.phase,r=t.signingOut===!0,[o,l]=p.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(et,{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(et,{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 m;l(!0),(m=u.onOpen)==null||m.call(u)},children:s.jsx(et,{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(Jj,{open:o,onClose:()=>l(!1),identity:u.identity,extraRows:u.extraRows}):null]})}const Jh={theme:"dark",font_scale:"md",header_density:"standard"};function Zj(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:Jh.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:Jh.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:Jh.header_density}}function Qj(e){return`af_appearance_${e}_v1`}function ek(e,t){const n=Qj(e),r=p.useMemo(()=>({...Jh,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[o,l]=p.useState(()=>{let u=r;try{const c=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);c&&(u=Zj({...r,...JSON.parse(c)}))}catch{}try{uy(u.theme),dy({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return p.useEffect(()=>{uy(o.theme),dy({font_scale:o.font_scale,header_density:o.header_density});try{localStorage.setItem(n,JSON.stringify(o))}catch{}},[n,o]),[o,l]}function tk(e){return p.useEffect(()=>{if(!e.open)return;const t=n=>{n.key!=="Escape"||n.defaultPrevented||(n.preventDefault(),e.onClose())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[e.open,e.onClose]),e.open?s.jsx("div",{className:"af-appearance-overlay",onClick:e.onClose,role:"presentation",children:s.jsxs("div",{className:"af-appearance",role:"dialog","aria-modal":"true","aria-label":e.title||"Appearance",onClick:t=>t.stopPropagation(),children:[s.jsx("div",{className:"af-appearance__title",children:e.title||"Appearance"}),s.jsx("div",{className:"af-appearance__note",children:e.note||"Stored locally in this browser, per app."}),s.jsxs("div",{className:"af-appearance__grid",children:[s.jsx("label",{className:"af-appearance__label",children:"Theme"}),s.jsx(gj,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),s.jsx("label",{className:"af-appearance__label",children:"Font size"}),s.jsx(yj,{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(wj,{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 nk={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 b_(e){const[t,n]=p.useState(!1),[r,o]=p.useState(null),l=p.useRef(!1),u=typeof e.entryId=="string"&&e.entryId.trim()?e.entryId.trim():null,c=e.kind&&nk[e.kind]||"var(--text-muted)",f=p.useCallback(async()=>{if(!(!u||!e.onOpen||l.current)){l.current=!0,n(!0),o(null);try{await e.onOpen(u)}catch(m){o(String((m==null?void 0:m.message)||m||"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 j_=wt("automations"),sk=wt("trigger-sources"),rk=wt("me/email");class py 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 ik(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 k_(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 ok(){return Nm()}function ak(e){const t=e.newId??ok,n=o=>`${j_}/${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 m=await e.fetch(ig(e.baseUrl,l),f),_=await m.text();let g,w=!1;if(_)try{g=JSON.parse(_),w=!0}catch{w=!1}if(!m.ok)throw new py(ik(m.status,g));if(!w||g===null||typeof g!="object")throw new py({status:m.status,code:"invalid_response",message:`The gateway answered ${o} ${l} with a body that is not a JSON object.`});return g}return{listAutomations:(o={})=>r("GET",`${j_}${k_({status:o.status,cursor:o.cursor,limit:o.limit})}`),getAutomation:o=>r("GET",n(o)),createAutomation:o=>r("POST",j_,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${k_({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${k_({cursor:l.cursor,limit:l.limit})}`),listTriggerSources:()=>r("GET",sk),getMyEmail:()=>r("GET",rk)}}const lk={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",discuss:"Discuss"},ck={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.`},uk="Next scheduled run: {time}.",dk="Growing context: later runs see this run in their history.",fk={run_now:{name:"playCircle"}},hk={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 result",notify_hint:"Email each completed run’s result to the selected recipients.",recipients_legend:"Recipients",recipients_self:"Only me (default)",recipients_list:"Me and these addresses",recipients_hint:"Separate multiple addresses with commas."},$v={labels:lk,hints:ck,run_now_next_run_line:uk,run_now_growing_line:dk,icons:fk,email:hk},mk=/^([1-9][0-9]*)([smhd])$/,_k={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function Af(e){if(typeof e!="string")return null;const t=mk.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function Tv(e){const t=Af(e);if(!t)return`every ${e}`;const[n,r]=_k[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${r}`}function la(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 Mv(e){const t=e;if(typeof t.every!="string")return t.start_at?`once at ${la(t.start_at)}`:"once, now";const n=[`${Tv(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 ${la(t.until)}`),n.join(" · ")}function og(e){return e.source_id==="schedule"&&e.source_version===1?Mv(e.config):e.source_id==="manual"&&e.source_version===1?"manual runs only":Cm(e)?zv(e.config):`${e.source_id}@${e.source_version}`}function Rv(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const pk={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},Ut=$v.email,Lv="email.received",Iv=1,gk="1h",yk="60s",Ov=60,ag=100,_p=1e3,gy=200,yy=200,wy=50;function Cm(e){return!!e&&e.source_id===Lv&&e.source_version===Iv}function Em(e){return!!e&&e.effective_enabled===!0}function Pv(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 wk=/[\s<>,;:"()[\]]/;function pp(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!wk.test(t)}function vk(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const Dv={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function lg(e){return e?gk:yk}function Fv(e){const t=Af(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function S_(e,t,n,r,o){const l=Pv(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>gy&&o.push(`${t}: at most ${gy} entries.`),l}function xk(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=lg(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&&(Fv(n.every)??0)<Ov&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=ag:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>_p?t.push(`At most this many emails per run: a whole number from 1 to ${_p}.`):n.max_batch=e.maxBatch;const r={},o=S_(e.fromIn,Ut.from_in,pp,"an email address",t);o&&(r.from_in=o);const l=S_(e.fromDomainIn,Ut.from_domain_in,vk,"a domain like example.com",t);l&&(r.from_domain_in=l);const u=S_(e.toIn,Ut.to_in,pp,"an email address",t);u&&(r.to_in=u);const c=e.subjectContains.trim();return c&&(c.length>yy||/[\r\n]/.test(c)?t.push(`${Ut.subject_contains}: one line of at most ${yy} 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 zv(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:lg(t.uses_model!==!1);r.push(`checked ${Tv(l)}`);const u=typeof t.max_batch=="number"?t.max_batch:ag;return r.push(`up to ${u} per run`),r.join(" · ")}const lf={mode:"self",addresses:""};function gp(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=Pv(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=>!pp(o));return r.length&&t.push(`${Ut.recipients_list}: ${r.join(", ")} ${r.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>wy&&t.push(`At most ${wy-1} addresses.`),{recipients:["self",...n],errors:t}}function bk(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function jk(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function Bv(e,t=["self"]){return{channels:e?["console","email"]:["console"],...t.some(n=>n!=="self")?{recipients:t}:{}}}function Uv(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function kk(e){return Uv(e)?"In the console and by email":"In the console"}const jo={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive"},Sk=new Set(["running","waiting","backoff"]);function Nk(e,t=[]){return e.current_occurrence!=null}function Wv(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 qv(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 om(e,t=[],n=!1){const r=new Set(e.capabilities),o=e.status,l=Nk(e,t),u=(_,g,w)=>n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:r.has(_)?o==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:g?{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 Ck(e){return e.status==="active"?jo.pause:jo.resume}function Ek(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 Ak(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=Ek(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:!Sk.has(t.status)}})}function $k(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function Hv(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 Tk={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 am(e){return{title:Tk[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function cg(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 Vv(e,t){var l,u,c;const n=e.trigger,r=n.source_id==="schedule"||Cm(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,growingMaxTokens:Number(((u=(l=t==null?void 0:t.context)==null?void 0:l.growing)==null?void 0:u.max_tokens)??e.growing_max_tokens??df),prompt:typeof o=="string"?o:null,toolApproval:t?t.policy.tool_approval:null,notifyEmail:t?Uv(t.notify):null,emailRecipients:t?bk((c=t.notify)==null?void 0:c.recipients):null}}function Mk(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=Vv(e,n);if(t.every!==u.every&&t.every!==null){const f=Cm(e.trigger);if(!Af(t.every))r.push("Interval must be a whole number of minutes, hours or days.");else if(f&&(Fv(t.every)??0)<Ov)r.push("The check interval is at least 60 seconds.");else{const m={...e.trigger.config,every:t.every};f&&delete m.start_at,o.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:m}}}const c=t.context==="growing"?t.growingMaxTokens??u.growingMaxTokens:u.growingMaxTokens;if(Kv(c)||r.push(Gv),(t.context!==e.context_mode||c!==u.growingMaxTokens)&&(o.context=Yv(t.context,c)),n&&typeof u.prompt=="string"&&typeof t.prompt=="string"&&t.prompt.trim()!==u.prompt.trim()){const f=t.prompt.trim();f?o.target={bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:{...n.target.input_data,prompt:f}}:r.push("Task is required.")}if(n&&t.toolApproval&&t.toolApproval!==u.toolApproval&&(o.policy={tool_approval:t.toolApproval}),n&&typeof t.notifyEmail=="boolean"){const f=gp(t.notifyEmail?t.emailRecipients??lf:u.emailRecipients??lf),m=gp(u.emailRecipients??lf).recipients;f.errors.length?r.push(...f.errors):(t.notifyEmail!==u.notifyEmail||JSON.stringify(f.recipients)!==JSON.stringify(m))&&(o.notify=Bv(t.notifyEmail,f.recipients))}return r.length?{errors:r}:Object.keys(o).length?o:null}const df=5e4,Rk="Keeps the most recent whole turns within this token budget. The newest turn is kept whole even if it exceeds the budget. Changes apply to future runs.",Gv="Max growing context must be a positive whole number of tokens.";function Kv(e){return Number.isSafeInteger(e)&&e>0}function Yv(e,t){return{mode:e,...t!==df?{growing:{max_tokens:t}}:{}}}const Lk=[{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 N_(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 Ik(e){const t=e.trim().split(`
|
|
53
|
+
`)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}function Ok(e){const t=[],n={};if(e.when.kind==="once"){const o=N_(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=N_(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=N_(e.until);o?n.until=o:t.push("Stop at must be a date and time (UTC).")}return{config:n,errors:t}}function yp(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()||Ik(r);o.length>120&&n.push("Title is at most 120 characters.");const l=e.trigger==="email",u=l?xk(e.email??Dv):Ok(e);n.push(...u.errors);const c=e.notifyEmail&&e.emailRecipients&&e.emailRecipients.mode==="list"?gp(e.emailRecipients):null;c&&n.push(...c.errors);const f=e.growingMaxTokens??df;if(e.context==="growing"&&!Kv(f)&&n.push(Gv),n.length||!t.target)return{ok:!1,errors:n};const m={...t.target,input_data:{...t.target.input_data??{},prompt:r}},_={request_id:t.requestId,title:o,target:m,trigger:l?{source_id:Lv,source_version:Iv,config:u.config}:{source_id:"schedule",source_version:1,config:u.config},context:Yv(e.context,e.context==="growing"?f:df),policy:{tool_approval:e.toolApproval??"auto"}};return e.notifyEmail===!0&&(_.notify=Bv(!0,c==null?void 0:c.recipients)),{ok:!0,body:_}}const Pk="Tools run without asking (you approve them now by creating this automation)";function Dk(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 Fk(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 Jv={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class zk{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||Bk(n.error))&&this.open.delete(t)}}function Bk(e){return cg(e)&&e.status>0&&e.code!=="invalid_response"}function Uk(){return Nm()}class Wk{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 vy(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 wp(e){if(Em(e.status))return null;const t=Ut.not_set_up,n=Ut.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 qk(e){const t=e.value,n=c=>e.onChange({...t,...c}),r=c=>`${e.idBase}-email-${c}`,o=Af(lg(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:Ut.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:Ut.interval_rule}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("batch"),children:[s.jsx("span",{children:Ut.max_batch_label}),s.jsx("input",{id:r("batch"),name:"email_max_batch",type:"number",min:1,max:_p,step:1,disabled:u,value:String(t.maxBatch??ag),onChange:c=>n({maxBatch:c.target.value.trim()===""?null:Number(c.target.value)})})]}),s.jsx("p",{className:"af-auto__hint",children:Ut.max_batch_hint}),s.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:u,children:[s.jsx("legend",{children:Ut.filters_legend}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("from"),children:[s.jsx("span",{children:Ut.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:Ut.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:Ut.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:Ut.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:Ut.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:Ut.has_attachment_any}),s.jsx("option",{value:"yes",children:Ut.has_attachment_yes}),s.jsx("option",{value:"no",children:Ut.has_attachment_no})]})]}),s.jsx("p",{className:"af-auto__hint",children:Ut.list_hint})]})]})}function Hk(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(No,{variant:"row",action:"notify-email",label:Ut.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:Ut.notify_hint}),e.notifyEmail?s.jsxs("fieldset",{className:"af-auto__field",disabled:n,"data-field":"email-recipients",children:[s.jsx("legend",{children:Ut.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"})})," ",Ut.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"})})," ",Ut.recipients_list]}),e.recipients.mode==="list"?s.jsx("textarea",{name:"email_recipient_list","aria-label":Ut.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:Ut.recipients_hint})]}):null]})}const Vk={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function Xv(e){const t=String(e.status),n=Vk[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:pk[t]??t}),n?s.jsx(et,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const vp="Discuss — fork at this occurrence (own workspace, automation files read-only)",Am=e=>s.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function Gk(e){return cg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function xy(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 Kk(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 Yk(e){const t=e.summary,n=Wv(t),r=Kk(t,e.triggerSources),o=t.next_fire_at?`${la(t.next_fire_at)} (${qv(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(Xv,{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:[og(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:Rv(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(et,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(xy,{path:t.workspace_root})]}):s.jsxs("span",{className:"af-auto__path af-auto__path--static",children:[s.jsx(et,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(xy,{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:Hv(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 Jk(e){var u,c;const t=e.definition,n=e.renderText??Am,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(et,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),s.jsx(et,{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," · ",og(t.trigger),s.jsx("pre",{className:"af-auto__json",children:JSON.stringify(t.trigger.config,null,2)})]}),s.jsx("dt",{children:"Context"}),s.jsxs("dd",{"data-def":"context",children:[Rv(t.context.mode),t.context.mode==="growing"?` · ${Number(((u=t.context.growing)==null?void 0:u.max_tokens)??5e4).toLocaleString()} tokens`:""]}),s.jsx("dt",{children:"Tools"}),s.jsx("dd",{"data-def":"tool_approval",children: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:kk(t.notify)}),(c=t.notify)!=null&&c.channels.includes("email")?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Recipients"}),s.jsx("dd",{"data-def":"email_recipients",children:jk(t.notify.recipients)})]}):null,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 $f=$v,xo=$f.labels,zi={active:"play",pause:"pause",resume:"play",run_now:$f.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",discuss:"chat"},xp=$f.hints,Xk=$f.run_now_next_run_line,Zk=$f.run_now_growing_line;function lm(e,t){const n=[xp[e]];return e==="run_now"&&t&&(t.next_fire_at&&n.push(Xk.replace("{time}",la(t.next_fire_at))),t.context_mode==="growing"&&n.push(Zk)),n.join(`
|
|
55
|
+
`)}function Qk(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 m=`${n}-why-${f}`;o.push({id:m,text:`${c.map(_=>xo[_]).join(", ")}: ${u}`});for(const _ of c)l[_]=m}),{lines:o,describedBy:l}}function ur(e){return s.jsxs(s.Fragment,{children:[s.jsx(et,{name:e.icon,size:14,className:"af-auto__btn-icon"}),s.jsx("span",{children:e.label})]})}function eS(e){const t=om(e.summary,e.occurrences,e.busy),r=Qk(t,["active","run_now","stop_current","revise","archive"],e.idBase??`af-auto-${e.summary.automation_id}`),o=(l,u,c)=>{const f=lm(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(ur,{icon:zi[l],label:(c==null?void 0:c.label)??xo[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(No,{className:"af-auto__switch",action:"active",label:xo.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:lm("active",e.summary),onChange:()=>e.onCommand(Ck(e.summary))},"active"),o("run_now",()=>e.onCommand(jo.run_now)),o("stop_current",()=>e.onCommand(jo.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(et,{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(et,{name:"x",size:12})}):null]}):null})]}),r.lines.length?s.jsxs("p",{className:"af-auto__reasons",children:[s.jsx(et,{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(jo.archive),children:s.jsx(ur,{icon:"archive",label:"Archive"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:s.jsx(ur,{icon:"x",label:"Keep it"})})]})]}):null]})}const by=[["m","minutes"],["h","hours"],["d","days"]];function tS(e,t){const n=N=>{const C=e.elements.namedItem(N);return C&&typeof C.value=="string"?C.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"),m=e.elements.namedItem("tool_approval"),_=m&&(m.value==="auto"||m.value==="ask")?m.value:t.toolApproval??null,g=e.elements.namedItem("notify_email"),w=g&&typeof g.checked=="boolean"?g.checked:t.notifyEmail??null,x=e.elements.namedItem("email_recipients"),k=n("email_recipient_list"),j=x&&(x.value==="self"||x.value==="list")?{mode:x.value,addresses:k??""}:t.emailRecipients??null;return{title:n("title")??t.title,every:l,context:c,growingMaxTokens:n("growing_max_tokens")===null?t.growingMaxTokens:Number(n("growing_max_tokens")),prompt:f??t.prompt??null,toolApproval:_,notifyEmail:w,emailRecipients:j}}function nS(e){const t=Vv(e.summary,e.definition),[n,r]=p.useState(t.context),[o,l]=p.useState(!!t.notifyEmail),u=t.every?Af(t.every):null,c=u&&u.unit==="s"?[["s","seconds"],...by]:by,f=`af-auto-revise-${e.summary.automation_id}`,m=Em(e.emailStatus),_=Cm(e.summary.trigger);return s.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${f}-heading`,onSubmit:g=>{g.preventDefault(),e.onSubmit(tS(g.currentTarget,t))},onKeyDown:g=>{g.key==="Escape"&&(g.preventDefault(),e.onCancel())},children:[s.jsxs("h3",{className:"af-auto__form-title",id:`${f}-heading`,children:[s.jsx(et,{name:"edit",size:14})," Edit automation"]}),s.jsxs("label",{className:"af-auto__field",htmlFor:`${f}-title`,children:[s.jsx("span",{children:"Title"}),s.jsx("input",{id:`${f}-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:`${f}-prompt`,children:[s.jsx("span",{children:"Task"}),s.jsx("textarea",{id:`${f}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
|
|
57
|
+
`).length+1)),required:!0})]}):null,u?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:_?Ut.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:u.amount,"aria-label":"Interval amount"}),s.jsx("select",{name:"every_unit",defaultValue:u.unit,"aria-label":"Interval unit",children:c.map(([g,w])=>s.jsx("option",{value:g,children:w},g))})]}),_?s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:Ut.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",onChange:()=>r("independent")})," Independent — each run starts fresh"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing",onChange:()=>r("growing")})," Growing — each run sees the previous runs"]}),s.jsx("div",{hidden:n!=="growing",children:s.jsxs("label",{className:"af-auto__field",children:[s.jsx("span",{children:"Max growing context (tokens)"}),s.jsx("input",{name:"growing_max_tokens",type:"number",min:1,step:1,disabled:e.busy||n!=="growing",defaultValue:t.growingMaxTokens}),s.jsx("span",{className:"af-auto__hint",children:Rk})]})})]}),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"}),m?null:s.jsx(wp,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),s.jsx(Nj,{variant:"row",action:"notify-email",name:"notify_email",label:Ut.notify_label,defaultChecked:!!t.notifyEmail,onChange:l,unavailableReason:!m&&!t.notifyEmail?"Connect a mailbox first.":null}),s.jsx("p",{className:"af-auto__hint",children:Ut.notify_hint}),s.jsx("div",{hidden:!o,children:s.jsxs("fieldset",{className:"af-auto__field",disabled:!o,"data-field":"email-recipients",children:[s.jsx("legend",{children:Ut.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",Ut.recipients_self]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"list",defaultChecked:t.emailRecipients.mode==="list",disabled:!m&&t.emailRecipients.mode!=="list"})," ",Ut.recipients_list]}),s.jsx("textarea",{name:"email_recipient_list","aria-label":Ut.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!m&&t.emailRecipients.mode!=="list"}),s.jsx("p",{className:"af-auto__hint",children:Ut.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(g=>s.jsx("li",{children:g},g))}):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(ur,{icon:"check",label:"Save changes"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"edit-cancel",onClick:e.onCancel,children:s.jsx(ur,{icon:"x",label:"Cancel"})})]})]})}function bp(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function sS(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??Am,l=u=>s.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[s.jsx("span",{className:"af-auto-wait__kind",children:Jv[t.kind]??"Waiting"}),t.prompt?o(t.prompt):s.jsxs("span",{children:[" ",u]})]});if(t.kind==="tool_approval"){const u=Dk(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(ur,{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(ur,{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=Fk(bp(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(ur,{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=bp(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(ur,{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 rS(e){const{row:t,tone:n,badge:r,statusText:o}=e.view,l=`af-auto-occ-${t.run_id}`,u=e.renderText??Am,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.",m=(w,x)=>e.renderTurn?e.renderTurn({kind:w,role:w==="trigger"?"user":"assistant",text:x,index:t.index,runId:t.run_id}):u(x),_=e.renderTurn?" af-auto-turn--card":"",g=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${_}`,"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 ",la(t.fired_at)]}),s.jsx("div",{className:"af-auto-turn__text",children:m("trigger",t.user_turn)})]}),s.jsxs("div",{className:`af-auto-turn af-auto-turn--answer${_}`,"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:[" · ",la(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:m("answer",t.answer)}):s.jsx("div",{className:"af-auto-turn__empty",children:g}),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(et,{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(sS,{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(ur,{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(ur,{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(ur,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?s.jsxs("form",{className:"af-auto-discuss","aria-label":`${vp}, from occurrence ${t.index}`,onSubmit:w=>{w.preventDefault();const x=bp(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(ur,{icon:"send",label:"Start discussion"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:s.jsx(ur,{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:xp.discuss,"aria-description":xp.discuss,"aria-describedby":f?`${l}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:s.jsx(ur,{icon:zi.discuss,label:vp})}),f?s.jsx("span",{className:"af-auto__reasons",id:`${l}-discuss-why`,children:f}):null]})]})]})}const iS=5e3,oS={[jo.pause]:"Automation paused.",[jo.resume]:"Automation active.",[jo.run_now]:"Run requested.",[jo.stop_current]:"Stop requested."};function aS(e){const{summary:t,busy:n}=e,r=e.renderText??Am,o=p.useId(),l=p.useRef(null),[u,c]=p.useState(!1),f=e.editOpen!==void 0,_=om(t,e.occurrences,!1).revise.enabled&&(f?e.editOpen===!0:u),g=p.useRef(null);_?(!g.current||g.current.summary.automation_id!==t.automation_id)&&(g.current={summary:t,definition:e.definition}):g.current=null;const w=g.current,x=p.useRef(e.onEditOpenChange);x.current=e.onEditOpenChange;const k=Q=>{var le;f||c(Q),(le=x.current)==null||le.call(x,Q)},[j,N]=p.useState([]),[C,E]=p.useState(!1),[T,I]=p.useState(null),[K,U]=p.useState(null),[J,Y]=p.useState(null);p.useEffect(()=>{if(!J)return;const Q=setTimeout(()=>Y(null),iS);return()=>clearTimeout(Q)},[J]),p.useEffect(()=>{var le;if(!_)return;N([]);const Q=vy(l.current,['.af-auto__revise [name="title"]']);Q==null||Q.focus(),(le=Q==null?void 0:Q.scrollIntoView)==null||le.call(Q,{block:"nearest"})},[_,t.automation_id]);const[re,ce]=p.useState(null);p.useEffect(()=>{var Q;re&&((Q=vy(l.current,[...re,".af-auto__notice",".af-auto__title"]))==null||Q.focus(),ce(null))},[re]);const fe=p.useRef(null);fe.current||(fe.current=new zk(e.newId??Uk));const W=fe.current,O=Q=>U(Gk(Q)),$=(Q,le,ge)=>{U(null),Y(null),le(W.idFor(Q)).then(pe=>{W.settle(Q,{ok:!0}),ge(pe)},pe=>{W.settle(Q,{ok:!1,error:pe}),O(pe)})},z=$k(t),A=p.useRef(e.onSeen);A.current=e.onSeen;const te=p.useRef(null);te.current||(te.current=new Wk),p.useEffect(()=>{const Q=te.current,le=z?`${t.automation_id}|${z}`:null;if(!z||!Q.next(le,t))return;const ge=t;A.current(z).then(()=>Q.succeeded(le),pe=>{Q.failed(le,ge),O(pe)})});const P=om(t,e.occurrences,n),F=Ak(e.occurrences),G=t.occurrence_count-e.occurrences.length,R=K??e.error??null,Z=R?am(R):null,X=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(Yk,{summary:t,triggerSources:e.triggerSources,titleId:o,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace}),s.jsx(eS,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:C,reviseOpen:_,notice:J,onDismissNotice:()=>Y(null),idBase:`${o}-ctl`,onCommand:Q=>$(`command:${Q}`,le=>e.onCommand(Q,void 0,{command_id:le}),()=>{Q===jo.archive?(E(!1),Y("Archive requested."),ce(['[data-action="archive"]'])):Y(oS[Q]??"Command sent.")}),onToggleRevise:()=>{N([]),k(!_)},onAskArchive:()=>E(!0),onCancelArchive:()=>{E(!1),ce(['[data-action="archive"]'])}}),_&&w?s.jsx(nS,{summary:w.summary,definition:w.definition,busy:n,errors:j,emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,onCancel:()=>{k(!1),ce(['[data-action="edit"]'])},onSubmit:Q=>{const le=w.summary,ge=Mk(le,Q,w.definition);if(ge===null){N(["Nothing changed."]);return}if("errors"in ge){N(ge.errors);return}N([]),$(`revise:${le.revision}:${JSON.stringify(ge)}`,pe=>e.onRevise(ge,le.revision,{command_id:pe}),()=>{Y("Saved; applies from the next run."),k(!1),ce(['[data-action="edit"]'])})}}):e.definition?s.jsx(Jk,{definition:e.definition,renderText:r}):null,Z?s.jsxs("div",{className:"af-auto__error",role:"alert","data-code":R==null?void 0:R.code,children:[s.jsx(et,{name:"error",size:14,className:"af-auto__btn-icon"}),s.jsxs("span",{className:"af-auto__error-text",children:[s.jsx("strong",{children:Z.title})," ",s.jsx("span",{children:Z.detail})]}),K?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:()=>U(null),children:s.jsx(et,{name:"x",size:12})}):null]}):null,X.items.length||X.waits.length?s.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:s.jsxs("ul",{children:[X.items.map(Q=>s.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${Q.kind}`,"data-cursor":Q.cursor,children:[s.jsx("span",{className:`af-auto-badge af-auto-badge--${Q.kind==="failure"?"failed":"notified"}`,children:Q.kind==="failure"?"Failed":"Notified"})," ",s.jsx("strong",{children:Q.title})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",Q.index," · ",la(Q.at)]}),Q.body?s.jsx("div",{className:"af-auto__attention-body",children:r(Q.body)}):null]},Q.cursor)),X.waits.map(Q=>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":Q.kind,children:Jv[Q.kind]??"Waiting for you"})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",Q.index]}),Q.prompt?s.jsx("div",{className:"af-auto__attention-body",children:r(Q.prompt)}):null]},`${Q.run_id}:${Q.wait_key}`))]})}):null,G>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(ur,{icon:"history",label:`Load earlier occurrences (${G} more)`})}):null,F.length?s.jsx("ol",{className:"af-auto__timeline","aria-label":"Occurrences",children:F.map(Q=>{const le=`[data-index="${Q.row.index}"]`;return s.jsx(rS,{view:Q,busy:n,discuss:P.discuss,renderText:r,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?ge=>{var pe;U(null);try{Promise.resolve((pe=e.onOpenResource)==null?void 0:pe.call(e,ge)).catch(O)}catch(ye){O(ye)}}:void 0,discussOpen:T===Q.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(ge,pe,ye)=>{U(null),e.onAnswerWait(ge,pe,ye).then(()=>Y("Answer sent."),O)},onWaitError:ge=>U({status:0,code:"invalid_payload",message:ge}),onDiscussOpen:I,onDiscussCancel:()=>{I(null),ce([`${le} [data-action="discuss"]`])},onDiscussSubmit:(ge,pe)=>$(`discuss:${ge}:${pe}`,ye=>e.onDiscuss(ge,pe,{request_id:ye}),ye=>{I(null),Y(`Discussion started (session ${ye.session_id}).`),ce([`${le} [data-action="discuss"]`])})},Q.row.run_id)})}):s.jsx("p",{className:"af-auto__empty",children:"No occurrences yet."})]})}const Zv="@default",Qv="No workflows available for this app — ask your admin.",ex={shared:"Shared",mine:"Mine"};class Xa extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function lS(e,t={}){const n=String(e||"").trim();if(!n)throw new Error("executableWorkflowsPath needs the interface the app runs (e.g. abstractcode.agent.v1).");return`bundles?executable_for=${encodeURIComponent(n)}${t.allVersions?"&all_versions=true":""}`}function cS(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function uS(e,t={}){return e===null?cS(t):lS(e,t)}function ia(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Ls(e){return typeof e=="string"?e.trim():""}const Ch="update the gateway";function dS(e,t){var c,f;const n=ia(e.default_agent_workflows);if(!n)return{status:"unavailable",reason:"the gateway does not report a default workflow"};const r=ia(n[t]);if(!r)return{status:"unavailable",reason:Ls((f=ia((c=ia(e.default_agent_workflows_unavailable))==null?void 0:c[t]))==null?void 0:f.reason)||`no default workflow for ${t}`};const o=Ls(r.bundle_id),l=Ls(r.flow_id);if(!o||!l)return{status:"unavailable",reason:"the gateway's default workflow is missing its bundle or flow"};const u=Ls(r.bundle_version);return{status:"ok",name:Ls(r.name)||l,bundleId:o,bundleVersion:u,flowId:l,workflowId:Ls(r.workflow_id)||`${o}${u?`@${u}`:""}:${l}`}}function fS(e,t,n={}){var c;const r=ia(e);if(!r)throw new Xa("The gateway's workflow list is not a JSON object.");const o=Ls(r.executable_for);if(t===null){if(o)throw new Xa(`Asked for every workflow, the gateway listed only ${o}.`)}else if(o!==t)throw new Xa(o?`The gateway listed workflows for ${o}, not ${t}.`:`This gateway does not filter workflows per app (no executable_for in its answer): ${Ch}.`);if(!Array.isArray(r.items))throw new Xa("The gateway's workflow list has no items.");const l=[];for(const f of r.items){const m=ia(f),_=Ls(m==null?void 0:m.bundle_id);if(!m||!_)throw new Xa("The gateway listed a workflow without a bundle id.");const g=ia(m.owner),w=Ls(g==null?void 0:g.kind);if(w!=="gateway"&&w!=="user")throw new Xa(`The gateway did not say who owns ${_} (owner missing): ${Ch}.`);if(typeof m.shipped!="boolean")throw new Xa(`The gateway did not say whether ${_} ships with it (shipped missing): ${Ch}.`);const x=Ls(m.bundle_version),k=Array.isArray(m.entrypoints)?m.entrypoints:[];for(const j of k){const N=ia(j),C=Ls(N==null?void 0:N.flow_id);if(!N||!C)continue;const E=Array.isArray(N.interfaces)?N.interfaces.map(Ls).filter(Boolean):[];if(t===null){if(!E.length)continue}else if(!E.includes(t))throw new Xa(`The gateway offered ${_}:${C}, which does not declare ${t}: ${Ch}.`);l.push({value:Ls(N.workflow_id)||`${_}${x?`@${x}`:""}:${C}`,bundleId:_,bundleVersion:x,flowId:C,name:Ls(N.name)||Ls((c=ia(m.metadata))==null?void 0:c.name)||_,description:Ls(N.description)||Ls(m.description),registryScope:Ls(m.registry_scope)||"private",group:w==="user"?"mine":"shared",shipped:m.shipped,interfaces:E,...t===null?{showInterfaces:!0}:{}})}}const u=n.defaultInterface??t;return{interfaceId:t,entries:l,gatewayDefault:u?dS(r,u):{status:"unavailable",reason:"no interface named for the gateway default"}}}function hS(e){const t=(n,r)=>n.name.localeCompare(r.name)||r.bundleVersion.localeCompare(n.bundleVersion,void 0,{numeric:!0})||n.value.localeCompare(r.value);return["shared","mine"].map(n=>({id:n,label:ex[n],entries:e.filter(r=>r.group===n).sort(t)})).filter(n=>n.entries.length>0)}const mS={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function _S(e){return mS[e]??e}function pS(e,t=[]){const n=e.bundleVersion?`@${e.bundleVersion}`:"";return e.showInterfaces?[[...new Set(e.interfaces.map(_S))].join(", "),n].filter(Boolean).join(" · "):n}function gS(e){return e.value}function yS(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function wS(e,t,n){return n<=0?null:e==="ArrowDown"?t<0?0:Math.min(n-1,t+1):e==="ArrowUp"?t<0?n-1:Math.max(0,t-1):e==="Home"?0:e==="End"?n-1:null}function vS(e,t=!0){const n=(e==null?void 0:e.entries)??[],r=[];t&&r.push({key:"default",value:Zv,name:"Gateway default",detail:yS((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const o of hS(n))for(const l of o.entries)r.push({key:l.value,value:l.value,name:l.name,detail:pS(l,n),title:gS(l),group:o.id,entry:l});return r}async function xS(e,t,n){var l;const r=await fetch(ig(e,wt(t)),{credentials:"include",headers:{Accept:"application/json"},signal:n}),o=await r.json().catch(()=>null);if(!r.ok){const u=((l=o==null?void 0:o.detail)==null?void 0:l.message)||(o==null?void 0:o.message)||(typeof(o==null?void 0:o.detail)=="string"?o.detail:"");throw new Error(u||`The gateway answered ${r.status}.`)}return o}function bS(e){var n;const t=e;return String(((n=t==null?void 0:t.detail)==null?void 0:n.message)||(t==null?void 0:t.message)||t||"The workflow list could not be loaded.")}function tx(e){const{interfaceId:t,defaultInterface:n,allVersions:r=!1,enabled:o=!0,gatewayBaseUrl:l,reloadKey:u}=e,c=p.useRef(e.request);c.current=e.request;const[f,m]=p.useState(0),[_,g]=p.useState({status:"idle",data:null,error:""});p.useEffect(()=>{if(!o){g({status:"idle",data:null,error:""});return}const x=new AbortController;g(N=>({...N,status:"loading",error:""}));const k=uS(t,{allVersions:r});return(c.current?c.current(k,{signal:x.signal}):xS(l,k,x.signal)).then(N=>{x.signal.aborted||g({status:"ready",data:fS(N,t,{defaultInterface:n}),error:""})}).catch(N=>{x.signal.aborted||g({status:"error",data:null,error:bS(N)})}),()=>x.abort()},[t,n,r,o,l,u,f]);const w=p.useCallback(()=>m(x=>x+1),[]);return{..._,reload:w}}function jS(e){if(!e||typeof window>"u")return{};const t=e.getBoundingClientRect(),n=window.innerWidth,r=window.innerHeight,o=Math.min(Math.max(t.width,300),440,n-32),l=Math.max(16,Math.min(t.left,n-16-o)),u=r-t.bottom-16;return u>=220||u>=t.top?{position:"fixed",left:l,width:o,top:t.bottom+4,maxHeight:Math.max(160,u)}:{position:"fixed",left:l,width:o,bottom:r-t.top+4,maxHeight:Math.max(160,t.top-16)}}function nx(...e){return e.filter(Boolean).join(" ")}function kS(e){const t=tx({interfaceId:e.interfaceId,defaultInterface:e.defaultInterface,request:e.request,gatewayBaseUrl:e.gatewayBaseUrl,allVersions:e.allVersions,enabled:e.workflows?!1:e.enabled!==!1}),n=e.workflows??t,r=e.showDefault!==!1&&(e.interfaceId!==null||!!e.defaultInterface),o=p.useId().replace(/:/g,""),l=`${o}-list`,[u,c]=p.useState(!1),[f,m]=p.useState(-1),_=p.useRef(null),g=p.useRef(null),[w,x]=p.useState({}),k=p.useMemo(()=>vS(n.data,r),[n.data,r]),j=k.find(J=>J.value===e.value),N=j?{name:j.name,detail:j.detail}:e.currentLabel?{name:e.currentLabel.name,detail:e.currentLabel.detail||""}:n.status==="loading"?{name:"Loading workflows…",detail:""}:{name:e.value===Zv?"Gateway default":"Choose a workflow",detail:""},C=String(e.unavailableReason||"").trim(),E=!C&&n.status==="ready",T=p.useCallback(()=>{c(!1),m(-1)},[]),I=p.useCallback(()=>{if(!E)return;x(jS(g.current)),c(!0);const J=k.findIndex(Y=>Y.value===e.value);m(J>=0?J:0)},[E,k,e.value]),K=p.useCallback(J=>{var Y;T(),J.value!==e.value&&e.onChange(J.value,J.entry),(Y=g.current)==null||Y.focus()},[T,e]);p.useEffect(()=>{if(!u)return;const J=re=>{_.current&&!_.current.contains(re.target)&&T()},Y=()=>T();return document.addEventListener("mousedown",J),document.addEventListener("touchstart",J),window.addEventListener("resize",Y),()=>{document.removeEventListener("mousedown",J),document.removeEventListener("touchstart",J),window.removeEventListener("resize",Y)}},[u,T]),p.useEffect(()=>{var Y;if(!u||f<0)return;const J=typeof document<"u"?document.getElementById(`${o}-opt-${f}`):null;(Y=J==null?void 0:J.scrollIntoView)==null||Y.call(J,{block:"nearest"})},[u,f,o]);const U=J=>{if(!u){["Enter"," ","ArrowDown","ArrowUp"].includes(J.key)&&(J.preventDefault(),I());return}if(J.key==="Escape"){J.preventDefault(),T();return}if(J.key==="Tab"){T();return}if(J.key==="Enter"||J.key===" "){J.preventDefault(),f>=0&&k[f]&&K(k[f]);return}const Y=wS(J.key,f,k.length);Y!==null&&(J.preventDefault(),m(Y))};return s.jsxs("div",{ref:_,className:nx("af-workflow-picker",e.className),"data-interface":e.interfaceId??"any",children:[s.jsxs("button",{ref:g,id:e.id,type:"button",role:"combobox",className:"af-workflow-picker__trigger","aria-label":e.ariaLabel||"Workflow","aria-describedby":`${o}-value`,"aria-haspopup":"listbox","aria-expanded":u,"aria-controls":l,"aria-activedescendant":u&&f>=0?`${o}-opt-${f}`:void 0,"aria-disabled":E?void 0:!0,title:C||void 0,onClick:()=>u?T():I(),onKeyDown:U,children:[s.jsxs("span",{className:"af-workflow-picker__value",id:`${o}-value`,children:[s.jsx("span",{className:"af-workflow-picker__name",children:N.name}),N.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:N.detail}):null]}),s.jsx("span",{className:"af-workflow-picker__caret","aria-hidden":"true"})]}),u?s.jsx(SS,{id:l,idBase:o,rows:k,value:e.value,highlight:f,ariaLabel:e.ariaLabel||"Workflow",style:w,onHighlight:m,onChoose:K}):null,n.status==="error"?s.jsx("span",{className:"af-workflow-picker__error",role:"alert",children:n.error}):n.status==="ready"&&k.every(J=>!J.entry)&&!r?s.jsx("span",{className:"af-workflow-picker__empty",role:"status",children:Qv}):null]})}function SS(e){const t=(l,u)=>s.jsxs("div",{id:`${e.idBase}-opt-${u}`,role:"option","aria-selected":l.value===e.value,"data-value":l.value,title:l.title,className:nx("af-workflow-picker__option",u===e.highlight&&"af-workflow-picker__option--highlighted",l.value===e.value&&"af-workflow-picker__option--selected"),onMouseEnter:()=>e.onHighlight(u),onMouseDown:c=>c.preventDefault(),onClick:()=>e.onChoose(l),children:[s.jsx("span",{className:"af-workflow-picker__name",children:l.name}),l.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:l.detail}):null]},l.key),n=e.rows.map((l,u)=>({row:l,index:u})),r=n.filter(l=>l.row.group===null),o=["shared","mine"].map(l=>({g:l,items:n.filter(u=>u.row.group===l)})).filter(l=>l.items.length>0);return s.jsxs("div",{id:e.id,role:"listbox","aria-label":e.ariaLabel,className:"af-workflow-picker__list",style:e.style,children:[r.map(l=>t(l.row,l.index)),o.map(({g:l,items:u})=>s.jsxs("div",{role:"group","aria-labelledby":`${e.idBase}-g-${l}`,"data-group":l,children:[s.jsx("div",{id:`${e.idBase}-g-${l}`,className:"af-workflow-picker__group",role:"presentation",children:ex[l]}),u.map(c=>t(c.row,c.index))]},l)),o.length===0?s.jsx("p",{className:"af-workflow-picker__empty",children:Qv}):null]})}function $m(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 NS(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function CS(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 ES(e){return e.endsWith(`
|
|
58
|
+
`)?e:`${e}
|
|
59
|
+
`}function AS(e){return String(e||"").trimStart().startsWith("```")}function $S(e,t){const r=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const o of e){const l=CS(o);r.push(`## ${l}`,"");const u=String(o.content||""),c=$m(u);c!==null&&!AS(u)?r.push("```json",NS(c).trimEnd(),"```",""):r.push(ES(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(`
|
|
60
|
+
`).trimEnd()}
|
|
61
|
+
`}async function rc(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 TS(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 MS=3,RS=Number.MAX_SAFE_INTEGER;function sx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function rx(e){return Array.isArray(e)}function LS(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function du({kind:e,children:t}){return s.jsx("span",{className:`pc-json-token ${e}`,children:t})}function IS(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[r,o]=p.useState(!n||e.expansionMode==="unfolded");return p.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(du,{kind:"string",children:t})}function OS(e,t,n){return e===null?s.jsx(du,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(IS,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?s.jsx(du,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx(du,{kind:"boolean",children:e?"true":"false"}):s.jsx(du,{kind:"string",children:JSON.stringify(String(e))})}function PS(e){return rx(e)?e.length===1?"1 item":`${e.length} items`:sx(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function ix(e){const{label:t,value:n,depth:r,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:c}=e,f=r*14,m=sx(n),_=rx(n),g=m||_,w=r<o,[x,k]=p.useState(w);p.useEffect(()=>{k(w)},[w,u]);const j=t?s.jsxs(s.Fragment,{children:[s.jsx(du,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!g)return s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[j,OS(n,l,u),c?",":""]});const N=_?"[":"{",C=_?"]":"}",E=PS(n),T=x?`${N}`:`${N}…${C}${E?` (${E})`:""}`,I=_?n.map((K,U)=>({key:String(U),label:void 0,value:K})):Object.entries(n).map(([K,U])=>({key:K,label:K,value:U}));return s.jsxs("details",{className:"pc-json-viewer__details",open:x,onToggle:K=>k(K.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:T}),!x&&c?s.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),x?s.jsx("div",{className:"pc-json-viewer__children",children:I.length===0?s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:C}),c?",":""]}):s.jsxs(s.Fragment,{children:[I.map((K,U)=>{const J=U===I.length-1;return s.jsx(ix,{label:K.label,value:K.value,depth:r+1,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:!J},`${r}:${t||"root"}:${K.key}`)}),s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:C}),c?",":""]})]})}):null]})}function DS(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 Is(e){const{value:t,className:n,showCopy:r=!0}=e,[o,l]=p.useState({mode:"folded",version:0}),[u,c]=p.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):MS,m=o.mode==="unfolded"?RS:f,_=p.useMemo(()=>typeof t=="string"?DS(t):t,[t]),g=p.useMemo(()=>LS(t),[t]),w=["pc-json-viewer",n].filter(Boolean).join(" ");p.useEffect(()=>{l(k=>({mode:"folded",version:k.version+1}))},[_]);const x=()=>{l(k=>({mode:k.mode==="unfolded"?"folded":"unfolded",version:k.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 rc(g).then(k=>{c(k?"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(ix,{value:_,depth:0,collapseAfterDepth:m,expansionMode:o.mode,expansionVersion:o.version,trailingComma:!1})})]})}function Ud(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 _=0;_<t.needlesLower.length;_++){const g=t.needlesLower[_];if(!g)continue;const w=o.indexOf(g,l);if(w===-1)continue;const x=t.needles[_]||"";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,m=n.slice(u,u+c.length);r.push(s.jsx("span",{id:f,className:t.className,children:m},`hl:${t.hits}`)),t.hits+=1,l=u+c.length}return r}function ox(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const jp="http://same-origin.invalid/";function FS(e){try{const t=new URL(e,jp);return t.protocol==="http:"&&t.origin===new URL(jp).origin}catch{return!1}}function ax(e){const t=String(e||"").trim();return ox(t)??(t&&FS(t)?t:void 0)}let Zl=null;function zS(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??jp;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 lx(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 nl(e,t){const n=[],r=String(e??"");let o=0,l="";const u=()=>{if(l){for(const c of Ud(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 m=r.indexOf(")",f+2);if(m!==-1){const _=r.slice(o+2,f),g=ax(r.slice(f+2,m));if(g&&Zl&&!Zl(g)){u(),n.push(lx(`img:${o}`,g,_)),o=m+1;continue}if(g){u(),n.push(s.jsxs("span",{className:"pc-md_image_inline",children:[s.jsx("img",{className:"pc-md_img",src:g,alt:_,loading:"lazy"}),_?s.jsx("span",{className:"pc-md_img_caption",children:t?Ud(_,t):_}):null]},`img:${o}`)),o=m+1;continue}}}}if(c==="["){const f=r.indexOf("]",o+1);if(f!==-1&&r[f+1]==="("){const m=r.indexOf(")",f+2);if(m!==-1){const _=r.slice(o+1,f),g=ox(r.slice(f+2,m));if(g){u(),n.push(s.jsx("a",{className:"pc-md_link",href:g,target:g.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:nl(_,t)},`link:${o}`)),o=m+1;continue}}}}if(c==="`"){const f=r.indexOf("`",o+1);if(f!==-1){u();const m=r.slice(o+1,f);n.push(s.jsx("code",{children:t?Ud(m,t):m},`code:${o}`)),o=f+1;continue}}if(c==="*"&&r[o+1]==="*"){const f=r.indexOf("**",o+2);if(f!==-1){u();const m=r.slice(o+2,f);n.push(s.jsx("strong",{children:t?Ud(m,t):m},`bold:${o}`)),o=f+2;continue}}if(c==="*"&&r[o+1]!=="*"){const f=r.indexOf("*",o+1);if(f!==-1){u();const m=r.slice(o+1,f);n.push(s.jsx("em",{children:t?Ud(m,t):m},`em:${o}`)),o=f+1;continue}}l+=c,o+=1}return u(),n}function BS(e){return String(e??"").replace(/\r\n/g,`
|
|
62
|
+
`).replace(/\r/g,`
|
|
63
|
+
`).split(`
|
|
64
|
+
`)}function Xh(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 US(e){const t=[];for(const o of e){const l=Xh(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,m=f[f.length-1];m?m.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 cx(e,t,n){const r=e.items.map((o,l)=>s.jsxs("li",{children:[nl(o.content,t),o.children.map((u,c)=>cx(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 WS(e,t,n){return US(e).map((r,o)=>cx(r,t,`${n}:${o}`))}function jy(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 ky(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 Sy=/^(#{1,5})\s+(.*)$/;function Ny(e){return e.trim().startsWith("```")}function Cy(e){return e.trimStart().startsWith(">")}function Wi(e){const t=Zl;Zl=e.images==="link"?e.inlineImage||zS:null;try{return qS(e)}finally{Zl=t}}function qS({text:e,className:t,highlight:n,highlights:r,highlightClassName:o,highlightId:l}){const u=BS(e),c=[],f=[];Array.isArray(r)&&f.push(...r),typeof n=="string"&&n.trim()&&f.push(n);const m=Array.from(new Set(f.map(x=>String(x??"").trim()).filter(Boolean))).filter(x=>x.length>=4),_=m.length?{needles:m,needlesLower:m.map(x=>x.toLowerCase()),className:o||"pc-md_hl",id:l,hits:0}:null;let g=0;for(;g<u.length;){const x=String(u[g]??"");if(!x.trim()){g+=1;continue}const k=x.trim();if(/^([-_*])(\s*\1){2,}$/.test(k)){c.push(s.jsx("hr",{className:"pc-md_hr"},`hr:${g}`)),g+=1;continue}const j=x.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(j){const E=ax(j[2]||"");if(E&&Zl&&!Zl(E)){c.push(s.jsx("p",{className:"pc-md_p",children:lx(`img:${g}`,E,j[1]||"")},`p:${g}`)),g+=1;continue}if(E){const T=j[1]||"";c.push(s.jsxs("figure",{className:"pc-md_figure",children:[s.jsx("img",{className:"pc-md_img",src:E,alt:T,loading:"lazy"}),T?s.jsx("figcaption",{children:nl(T,_)}):null]},`figure:${g}`)),g+=1;continue}}if(Ny(x)){const T=x.trim().replace(/```/g,"").trim(),I=[];for(g+=1;g<u.length&&!String(u[g]??"").trim().startsWith("```");)I.push(String(u[g]??"")),g+=1;g<u.length&&(g+=1);const K=I.join(`
|
|
65
|
+
`);c.push(s.jsx("pre",{className:"pc-md_pre",children:s.jsx("code",{className:T?`language-${T}`:void 0,children:K})},`pre:${g}`));continue}const N=x.match(Sy);if(N){const E=N[1].length,T=N[2]||"",I=nl(T,_);E===1?c.push(s.jsx("h1",{children:I},`h1:${g}`)):E===2?c.push(s.jsx("h2",{children:I},`h2:${g}`)):E===3?c.push(s.jsx("h3",{children:I},`h3:${g}`)):E===4?c.push(s.jsx("h4",{children:I},`h4:${g}`)):c.push(s.jsx("h5",{children:I},`h5:${g}`)),g+=1;continue}if(Cy(x)){const E=[];for(;g<u.length&&String(u[g]??"").trimStart().startsWith(">");){const I=String(u[g]??"").trimStart();E.push(I.replace(/^>\s?/,"")),g+=1}c.push(s.jsx("blockquote",{className:"pc-md_quote",children:E.map((T,I)=>s.jsxs(ve.Fragment,{children:[nl(T,_),I<E.length-1?s.jsx("br",{}):null]},`q:${g}:${I}`))},`quote:${g}`));continue}if(x.includes("|")&&g+1<u.length&&ky(String(u[g+1]??""))){const E=jy(x),T=Math.max(1,E.length),I=[];for(g+=2;g<u.length;){const K=String(u[g]??"");if(!K.trim()||!K.includes("|"))break;const U=jy(K),J=[];for(let Y=0;Y<T;Y++)J.push(U[Y]??"");I.push(J),g+=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:E.slice(0,T).map((K,U)=>s.jsx("th",{children:nl(K,_)},`th:${g}:${U}`))})}),s.jsx("tbody",{children:I.map((K,U)=>s.jsx("tr",{children:K.map((J,Y)=>s.jsx("td",{children:nl(J,_)},`td:${g}:${U}:${Y}`))},`tr:${g}:${U}`))})]})},`table:${g}`));continue}if(Xh(x)){const E=[];for(;g<u.length;){const T=String(u[g]??"");if(!T.trim()||T.trimStart().startsWith("```"))break;if(Xh(T)||/^\s{2,}\S/.test(T)){E.push(T),g+=1;continue}break}c.push(s.jsx(ve.Fragment,{children:WS(E,_,`list:${g}`)},`list:${g}`));continue}const C=[];for(;g<u.length&&String(u[g]??"").trim()&&!(C.length>0&&Xh(String(u[g]??"")));){const E=String(u[g]??"");if(C.length>0&&(Sy.test(E)||Ny(E)||Cy(E))||C.length>0&&E.includes("|")&&g+1<u.length&&ky(String(u[g+1]??"")))break;C.push(E),g+=1}c.push(s.jsx("p",{className:"pc-md_p",children:C.map((E,T)=>s.jsxs(ve.Fragment,{children:[nl(E,_),T<C.length-1?s.jsx("br",{}):null]},`pl:${g}:${T}`))},`p:${g}`))}const w=["pc-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:w,children:c})}function ux(e){const t=String(e.text??""),n=p.useMemo(()=>$m(t),[t]),r=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?s.jsx("div",{className:r,children:s.jsx(Is,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?s.jsx("div",{className:r,children:e.renderMarkdown(t)}):s.jsx("div",{className:r,children:s.jsx(Wi,{text:t,images:e.images,inlineImage:e.inlineImage})})}function dx(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function HS(e){const t=dx(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 fx({tool:e,showCopy:t=!0}){const[n,r]=p.useState(!1),o=dx(e.arguments),l=HS(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"},m=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,_=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(et,{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(m)&&m>=0?s.jsxs("span",{className:"pc-tool-activity__duration",children:[(m/1e3).toFixed(1),"s"]}):null,s.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:s.jsx(et,{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 rc(JSON.stringify(e,null,2))),children:[s.jsx(et,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),_?s.jsx("dl",{className:"pc-tool-activity__parameters",children:_.map(([g,w])=>s.jsxs(ve.Fragment,{children:[s.jsx("dt",{children:g}),s.jsx("dd",{children:w&&typeof w=="object"?s.jsx(Is,{value:w}):s.jsx("code",{children:typeof w=="string"?w:JSON.stringify(w)})})]},g))}):e.arguments===void 0?s.jsx("p",{children:"Arguments are unavailable in this ledger."}):s.jsx(Is,{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(Is,{value:e.output})})]}):null]})]})}function hx({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(et,{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(fx,{tool:r,showCopy:t},r.id))]})}const Gs="not reported",Sr=e=>e===void 0?Gs:Math.round(e).toLocaleString(),Br=e=>{if(e===void 0)return Gs;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`},mx=e=>e===void 0?Gs:`${Math.round(e).toLocaleString()} tok/s`,VS=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",Ql=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,GS=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function KS(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 cm(e){const t=[],n=(e.models||[]).map(GS),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 YS(e){const t=e.modelCalls||[],n=[],r=[{label:"Input",value:Sr(e.inputTokens)},{label:"Output",value:Sr(e.outputTokens)}];if(e.reasoningTokens!==void 0&&r.push({label:"Reasoning",value:Sr(e.reasoningTokens),hint:"part of output"}),r.push({label:"Total",value:Sr(e.totalTokens)}),n.push({heading:`Usage · ${Ql(e.llmCalls,"model call")}`,rows:r}),e.measuredCacheCalls){const l=e.cachedTokens||0,u=e.fedTokens||0,c=[{label:"Reused from cache",value:`${Sr(l)}${l+u?` (${VS(l,l+u)})`:""}`},{label:"Newly processed",value:Sr(e.fedTokens)},{label:"Outcome",value:KS(t.map(f=>f.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Gs},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Gs}];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:Gs}]});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:`${Sr(o[0].inputTokens)} tokens`}]}):o.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${Sr(o[0].inputTokens)} → ${Sr(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),Sr(l.inputTokens),l.cachedTokens===void 0?"—":Sr(l.cachedTokens),l.fedTokens===void 0?"—":Sr(l.fedTokens),Sr(l.outputTokens),l.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Gs:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:cm(e)}}function Eh(e,t,n,r){if(e===void 0)return Gs;const o=[Br(e)];return t!==void 0&&o.push(`${t.toLocaleString()} ${r}${n!==void 0?` at ${mx(n)}`:""}`),o.join(" · ")}function JS(e){var m,_,g;const t=e.modelCalls||[],n=[],r=e.durationMs,o=[{label:"Wall clock",value:Br(r)}];if(o.push({label:"Model",value:e.genTimeMs===void 0?Gs:`${Br(e.genTimeMs)} · ${Ql(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),o.push({label:"Tools",value:e.toolTimeMs!==void 0?`${Br(e.toolTimeMs)} · ${Ql(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Gs:"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?Br(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:Eh(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:Eh(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${Br(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${mx(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):l.push({label:"Prefill",value:Gs}),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?Eh(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):Eh(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(k=>k.toUpperCase()).join(", "),x=[{label:"Mode",value:`${f.used?"on":"off"}${w?` · ${w}`:""}${(m=f.modes)!=null&&m.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?Gs:`${Math.round(f.acceptanceRate*100)}% · ${Sr(f.acceptedTokens)} of ${Sr(f.draftedTokens)} drafted`}];((_=f.draftLengths)!=null&&_.length||f.rounds!==void 0)&&x.push({label:"Draft length",value:`${(g=f.draftLengths)!=null&&g.length?`${f.draftLengths.join("/")} tok/round`:Gs}${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:`${Br(e.toolTimeMs)} · ${Ql(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${Br(e.slowestToolBatch.ms)} · ${_x(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?"—":`${Br(w.promptMs)}${w.promptSource==="rate"?"*":""}`,w.promptNewTokensPerSecond===void 0?"—":Math.round(w.promptNewTokensPerSecond).toLocaleString(),w.generationMs===void 0?"—":Br(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?Gs:`${Br(r)} wall clock`,sections:n,footer:cm(e)}}function _x(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${Ql(e.calls,"call")} (${e.tools.join(", ")})`}function XS(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:cm(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?`${Br(f.ms)}${f.sharedBatches?" +shared":""}`:f.sharedBatches?"shared":Gs])},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((m,_)=>_[1]-m[1]).map(([m,_])=>_>1?`${m} ×${_}`:m).join(" · ")}))});const u=[{label:"Tool time",value:e.toolTimeMs===void 0?Gs:`${Br(e.toolTimeMs)} · ${Ql(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${Br(e.slowestToolBatch.ms)} · ${_x(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:`${Ql(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:cm(e)}}function C_(e,t){return e==="tokens"?YS(t):e==="time"?JS(t):XS(t)}function ZS(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===Gs?"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 ta=8;function QS(e){const[t,n]=p.useState(!!e.defaultOpen),[r,o]=p.useState(null),l=p.useRef(null),u=p.useRef(null),c=p.useRef(null),f=`pc-stat-${p.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,m=p.useCallback(()=>{c.current!==null&&window.clearTimeout(c.current),c.current=null},[]),_=p.useCallback(()=>{m(),n(!0)},[m]),g=p.useCallback(()=>{m(),c.current=window.setTimeout(()=>n(!1),120)},[m]);p.useEffect(()=>m,[m]),p.useLayoutEffect(()=>{if(!t){o(null);return}const j=()=>{const N=l.current,C=u.current;if(!N||!C)return;const E=N.getBoundingClientRect(),T=C.offsetWidth,I=C.offsetHeight,K=window.innerWidth,U=window.innerHeight,J=E.top-ta-I,Y=E.bottom+ta,re=J>=ta?J:Y+I<=U-ta?Y:Math.max(ta,U-ta-I),ce=Math.min(Math.max(ta,E.left),Math.max(ta,K-ta-T));o({top:re,left:ce})};return j(),window.addEventListener("resize",j),window.addEventListener("scroll",j,!0),()=>{window.removeEventListener("resize",j),window.removeEventListener("scroll",j,!0)}},[t]),p.useEffect(()=>{if(!t)return;const j=N=>{N.key==="Escape"&&n(!1)};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[t]);const w=typeof e.onClick=="function",x=w?"button":"span",k=t?s.jsx(ZS,{detail:e.detail,id:f,panelRef:u,onMouseEnter:m,onMouseLeave:g,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:_,onMouseLeave:g,onFocus:_,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})]}),k&&typeof document<"u"?Cv.createPortal(k,document.body):k]})}function e1(e){const t=e.totalTokens!==void 0?C_("tokens",e):null,n=C_("tools",e),r=e.durationMs!==void 0?C_("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(`
|
|
66
|
+
`)}]:[],...r?[{label:`${(e.durationMs/1e3).toFixed(e.durationMs<1e4?1:0)}s`,detail:r}]:[]]}function t1(e){const t=String(e.role||"").trim().toLowerCase()||"system",n=String(e.kind||"").trim().toLowerCase(),r=String(e.level||"").trim().toLowerCase();return t==="system"&&n==="report_bug"?{label:String(e.title||"").trim()||"Bug report",icon:"warning",variant:"report_bug"}:t==="system"&&n==="report_feature"?{label:String(e.title||"").trim()||"Feature request",icon:"check",variant:"report_feature"}:t==="user"?{label:String(e.title||"").trim()||"You",icon:"user",variant:"user"}:t==="assistant"?{label:String(e.title||"").trim()||"Agent",icon:"bot",variant:"assistant"}:{label:String(e.title||"").trim()||(r==="error"?"Error":r==="warn"?"Warning":"System"),icon:r==="error"?"error":r==="warn"?"warning":"info",variant:r==="error"?"error":r==="warn"?"warn":"status"}}const n1=new Set(["blob:","data:","http:","https:"]);function Ey(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return n1.has(new URL(t,n).protocol)?t:void 0}catch{return}}function s1({item:e}){const[t,n]=p.useState(!1),r=Ey(e.src),o=e.href?Ey(e.href):void 0,l=e.kind==="image"||e.kind==="audio"||e.kind==="video"?e.kind:null;if(!l||!r&&!o)return null;const u=l==="image"?"Image":l==="video"?"Video":"Audio",c=String(e.label||"").trim()||`Generated ${u.toLowerCase()}`,f=()=>n(!0);return s.jsxs("figure",{className:`pc-chat-media__item pc-chat-media__item--${l}`,children:[r&&l==="image"?s.jsx("img",{className:"pc-chat-media__image",src:r,alt:c,loading:"lazy",onError:f}):null,r&&l==="video"?s.jsx("video",{className:"pc-chat-media__video",src:r,controls:!0,playsInline:!0,preload:"metadata","aria-label":c,onError:f}):null,r&&l==="audio"?s.jsx("audio",{className:"pc-chat-media__audio",src:r,controls:!0,preload:"metadata","aria-label":c,onError:f}):null,t?s.jsxs("div",{className:"pc-chat-media__error",role:"note",children:[u," could not be decoded by this browser",o?"; open the raw file with the link.":"."]}):null,o?s.jsx("figcaption",{className:"pc-chat-media__caption",children:s.jsx("a",{className:"pc-chat-media__link",href:o,target:"_blank",rel:"noopener noreferrer",children:c})}):null]})}function ug(e){var K;const t=e.message,n=p.useMemo(()=>t1(t),[t.kind,t.level,t.role,t.title]),r=String(t.ts||"").trim(),o=p.useMemo(()=>{if(!r)return"";const U=new Date(r);return Number.isFinite(U.getTime())?U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""},[r]),[l,u]=p.useState("idle"),c=p.useRef(null);p.useEffect(()=>()=>{c.current!==null&&window.clearTimeout(c.current)},[]);const f=t.live,m=!f&&typeof e.onSpeakToggle=="function"&&n.variant==="assistant"&&!!String(t.content||"").trim(),_=m&&((K=e.getSpeakState)==null?void 0:K.call(e,t))||"idle",g=_==="loading"?"loader":_==="playing"?"pause":"speaker",w=_==="loading"?"Generating audio…":_==="playing"?"Pause":_==="paused"?"Resume":"Speak (TTS)",x=e.showCopy!==!1,k=Array.isArray(e.attachments)?e.attachments:[],j=t.statistics,N=t.stats,C=p.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(N)?N:j?e1(j):[],[e.stats,N,j]),E=Array.isArray(t.media)?t.media:[],T=String(f?f.reasoning||"":t.reasoning||""),I=!!String(t.content||"").trim();return t.toolActivity?s.jsx(fx,{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(et,{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:f.label?`Pending: ${f.label}`:"The reply is still being written",children:[s.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),f.label||"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:[m?s.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":w,title:w,onClick:()=>{var U;return(U=e.onSpeakToggle)==null?void 0:U.call(e,t)},children:s.jsx(et,{name:g,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 U=await rc(String(t.content||""));u(U?"copied":"failed"),c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>u("idle"),900)},children:s.jsx(et,{name:"copy",size:22})}):null]})]}),T.trim()?s.jsxs("details",{className:"pc-chat-thinking",children:[s.jsx("summary",{children:"Thinking"}),s.jsx("div",{className:"pc-chat-thinking-body",children:T})]}):null,I||!f&&!E.length?s.jsx("div",{className:"pc-chat-body",children:s.jsx(ux,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,E.length?s.jsx("div",{className:"pc-chat-media",children:E.slice(0,24).map((U,J)=>s.jsx(s1,{item:U},U.id||`${U.kind}:${U.src}:${J}`))}):null,k.length?s.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:k.slice(0,24).map((U,J)=>{const Y=String(U.label||"").trim()||"attachment",re=String(U.target||"").trim(),ce=String(U.title||"").trim(),fe=!!U.disabled||typeof U.onClick!="function";return s.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:ce||Y,onClick:fe?void 0:U.onClick,disabled:fe,children:[s.jsx(et,{name:"paperclip",size:14}),re?s.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${re}`,children:re}):null,s.jsx("span",{className:"pc-chat-attachment-name",children:Y})]},U.id||`${Y}:${J}`)})}):null,C.length?s.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:C.slice(0,12).map((U,J)=>{const Y=String(U.label||"").trim();if(!Y)return null;if(U.detail)return s.jsx(QS,{label:Y,detail:U.detail,icon:U.icon,onClick:U.onClick},U.id||`${Y}:${J}`);const re=String(U.title||"").trim(),ce=typeof U.onClick=="function",fe=ce?"button":"span";return s.jsxs(fe,{...ce?{type:"button"}:{},className:["pc-chat-stat",ce?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:re||void 0,onClick:ce?()=>{var W;return(W=U.onClick)==null?void 0:W.call(U)}:void 0,children:[U.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:U.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:Y})]},U.id||`${Y}:${J}`)})}):null]})}function r1(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=p.useRef(null),o=p.useRef(null),[l,u]=p.useState(!0),c=p.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),f=p.useMemo(()=>{var g;const _=[];for(const w of c){const x=_[_.length-1];w.toolActivity&&((g=x==null?void 0:x[0])!=null&&g.toolActivity)&&x[0].runId===w.runId?x.push(w):_.push([w])}return _},[c]);p.useEffect(()=>{if(!n)return;const _=r.current;if(!_)return;const g=()=>{u(r1(_,t))};return _.addEventListener("scroll",g,{passive:!0}),g(),()=>_.removeEventListener("scroll",g)},[n,t]);const m=p.useMemo(()=>{let _=0;for(const g of c)if(_+=String(g.content??"").length,Array.isArray(g.media))for(const w of g.media)_+=String((w==null?void 0:w.src)??"").length+1;return`${c.length}:${_}:${String(e.afterKey??"")}`},[c,e.afterKey]);return p.useEffect(()=>{if(!n||!l)return;const _=r.current;_&&(_.scrollTop=_.scrollHeight)},[n,l,m]),p.useEffect(()=>{if(!n)return;const _=r.current;if(!_)return;const g=()=>{l&&(_.scrollTop=_.scrollHeight)};return _.addEventListener("load",g,!0),_.addEventListener("loadedmetadata",g,!0),()=>{_.removeEventListener("load",g,!0),_.removeEventListener("loadedmetadata",g,!0)}},[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((_,g)=>{var k;const w=_[0],x=String(w.id||"")||String(w.ts||"")+":"+String(w.role||"")+":"+g;return w.toolActivity?s.jsx(hx,{tools:_.map(j=>j.toolActivity),showCopy:(k=e.messageProps)==null?void 0:k.showCopy},x):s.jsx(ug,{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 i1(e){return!!(e&&typeof e[Symbol.asyncIterator]=="function")}function o1(e){const[t,n]=p.useState([]),r=e.messages??t,o=j=>{e.onMessagesChange&&e.onMessagesChange(j),e.messages===void 0&&n(j)},l=p.useRef(r);l.current=r;const[u,c]=p.useState(""),[f,m]=p.useState(!1),_=p.useRef(null),g=e.assistantName||"Assistant",w=!!e.blockedNotice,x=async j=>{const N=String(j||"").trim();if(!N||f||w)return;c("");const C=l.current,E=[...C,{role:"user",content:N,ts:new Date().toISOString()}];o(E),m(!0);const T=new AbortController;_.current=T;try{const I=e.ask(N,{signal:T.signal,history:C});if(i1(I)){let K="";const U=[...E,{role:"assistant",title:g,content:"",ts:new Date().toISOString()}];o(U);for await(const J of I){if(T.signal.aborted)break;K+=String(J??""),o([...E,{role:"assistant",title:g,content:K,ts:new Date().toISOString()}])}!K.trim()&&!T.signal.aborted&&o([...E,{role:"assistant",title:g,content:"#FALLBACK the assistant returned no answer.",level:"warn",ts:new Date().toISOString()}])}else{const K=String(await I??"").trim();o([...E,K?{role:"assistant",title:g,content:K,ts:new Date().toISOString()}:{role:"assistant",title:g,content:"#FALLBACK the assistant returned no answer.",level:"warn",ts:new Date().toISOString()}])}}catch(I){T.signal.aborted||o([...l.current,{role:"assistant",title:g,content:`#FALLBACK assistant request failed: ${String((I==null?void 0:I.message)||I||"unknown error")}`,level:"error",ts:new Date().toISOString()}])}finally{_.current===T&&(_.current=null),m(!1)}},k=p.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:[k,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=_.current)==null||j.abort()},children:"Stop"}):null})})]})}const kn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Zh=e=>Array.isArray(e)?e.map(kn):[],Zt=e=>typeof e=="string"?e:"",Wd=e=>Zt(e.runtime_call_id||e.call_uid),qd=e=>Zt(e.call_id||e.id);function px(e,t){const n=t.record,r=kn(n.effect);if(r.type!=="tool_calls")return[];const o=kn(n.result),l=Zh(kn(r.payload).tool_calls),u=l.length||n.status!=="waiting"?l:Zh(kn(kn(o.wait).details).tool_calls),c=Zh(o.results),f=u.length?u:c,m=[];return f.forEach((_,g)=>{let w=Wd(_)?c.filter(U=>Wd(U)===Wd(_)):[];!w.length&&qd(_)&&u.filter(U=>qd(U)===qd(_)).length===1&&(w=c.filter(U=>qd(U)===qd(_)));const x=u.length?w.length===1?w[0]:u.length===c.length?c[g]:{}:_,k=Wd(_)||Wd(x)||`${Zt(n.idempotency_key)||Zt(n.step_id)||t.cursor}:${g}`,j=`${t.runId}:${k}`,N=e.get(j),C=Zt(_.name||x.name)||(N==null?void 0:N.name);if(!C)return;const E=n.status==="completed"||n.status==="failed",T=n.status==="failed"||x.success===!1||!!x.error,I=_.arguments??x.arguments??(N==null?void 0:N.arguments),K={...N,id:j,runId:t.runId,name:C,arguments:I,status:E?T?"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:(N==null?void 0:N.startedAt)||Zt(n.started_at)||void 0,endedAt:E&&Zt(n.ended_at)||(N==null?void 0:N.endedAt)};N&&["completed","failed"].includes(N.status)&&!E||(e.set(j,K),m.push(K))}),m}function cu(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function vo(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 gx(e){if(typeof e=="string")try{return kn(JSON.parse(e))}catch{return{}}return kn(e)}function nu(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function a1(e){return vo(e,["reasoning_tokens","thinking_tokens"])??vo(kn(e.completion_tokens_details),["reasoning_tokens"])??vo(kn(e.output_tokens_details),["reasoning_tokens"])}function l1(e){const t=kn(typeof e=="string"&&e.trim().startsWith("{")?gx(e):e);return Zt(t.error_class)}function c1(e){const t=new Map;for(const n of e){const r=n.record;if(kn(r.effect).type!=="emit_event")continue;const o=kn(r.result);if(Zt(o.name)!=="abstract.progress")continue;const l=kn(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=cu(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 E_(e){var j,N,C,E;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,m=0,_=0;const g=c1(e),w=[],x=new Set;for(const T of e){const I=T.record,K=`${T.runId}:${I.step_id||T.cursor}:${I.status}`;if(n.has(K))continue;n.add(K);for(const ye of[I.started_at,I.ended_at]){const Ne=Date.parse(Zt(ye));Number.isFinite(Ne)&&(l=Math.min(l,Ne),u=Math.max(u,Ne))}for(const ye of px(t,T))ye.status==="waiting"&&x.add(ye.id);if(kn(I.effect).type!=="llm_call"||I.status!=="completed")continue;o.llmCalls+=1;const U=kn(I.result),J=kn(U.output),Y=kn(U.usage||U.token_usage||U.tokens||J.usage||J.token_usage||J.tokens),re=vo(Y,["input_tokens","prompt_tokens","prompt","input","in"]),ce=vo(Y,["output_tokens","completion_tokens","completion","output","out"]),fe=vo(Y,["total_tokens","total"])??(re!==void 0||ce!==void 0?(re||0)+(ce||0):void 0);fe!==void 0&&(re===void 0||ce===void 0||re+ce!==fe)&&(c=!0),re!==void 0&&(o.inputTokens=(o.inputTokens||0)+re),ce!==void 0&&(o.outputTokens=(o.outputTokens||0)+ce),fe!==void 0&&(o.totalTokens=(o.totalTokens||0)+fe);const W=cu(U.gen_time??J.gen_time);W!==void 0&&(o.genTimeMs=(o.genTimeMs||0)+W,o.timedCalls=(o.timedCalls||0)+1);const O=kn(U.metadata||J.metadata),$=kn(O.performance),z=cu($.prompt_tokens_per_second),A=cu($.generation_tokens_per_second),te=kn(O.prompt_cache),P=cu(te.cached_tokens),F=cu(te.fed_tokens);if(z!==void 0||A!==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,m+=ye)}A!==void 0&&A>0&&(o.generationTokensPerSecond=(o.generationTokensPerSecond||0)+A,ce!==void 0&&(o.decodeMs=(o.decodeMs||0)+ce/A*1e3))}if(P!==void 0||F!==void 0){o.measuredCacheCalls=(o.measuredCacheCalls||0)+1,o.cachedTokens=(o.cachedTokens||0)+(P||0),o.fedTokens=(o.fedTokens||0)+(F||0);const ye=Zt(te.outcome);if(ye){const Ne=o.cacheOutcomes||[];Ne.includes(ye)||Ne.push(ye),o.cacheOutcomes=Ne}}const G=Zt(I.step_id)||void 0,R=G&&g.get(`${T.runId}:${G}`)||{},Z=kn(U.route),X={runId:T.runId};G&&(X.stepId=G),Zt(I.started_at)&&(X.startedAt=Zt(I.started_at));const Q=Zt(U.model||J.model)||Zt(Z.model)||R.model,le=Zt(Z.provider)||Zt(kn(O._provider_request).provider)||R.provider||Zt(U.provider);Q&&(X.model=Q),le&&(X.provider=le),Q&&(o.models=nu(o.models,Q)),le&&(o.providers=nu(o.providers,le)),(fe===void 0||re!==void 0&&ce!==void 0&&re+ce===fe)&&(re!==void 0&&(X.inputTokens=re),ce!==void 0&&(X.outputTokens=ce)),fe!==void 0&&(X.totalTokens=fe);const ge=a1(Y);ge!==void 0&&(X.reasoningTokens=ge,o.reasoningTokens=(o.reasoningTokens||0)+ge),P!==void 0&&(X.cachedTokens=P),F!==void 0&&(X.fedTokens=F),Zt(te.outcome)&&(X.cacheOutcome=Zt(te.outcome)),Zt(te.backend)&&(X.cacheBackend=Zt(te.backend),o.cacheBackends=nu(o.cacheBackends,X.cacheBackend)),W!==void 0&&(X.genTimeMs=W),z!==void 0&&z>0&&(X.promptTokensPerSecond=z),A!==void 0&&A>0&&(X.generationTokensPerSecond=A),R.ttftS!==void 0?(X.ttftMs=R.ttftS*1e3,X.promptMs=X.ttftMs,X.promptSource="ttft",o.ttftMs=(o.ttftMs||0)+X.ttftMs,o.ttftCalls=(o.ttftCalls||0)+1):X.promptTokensPerSecond!==void 0&&re!==void 0&&(X.promptMs=re/X.promptTokensPerSecond*1e3,X.promptSource="rate"),X.promptMs!==void 0&&(o.promptPhaseMs=(o.promptPhaseMs||0)+X.promptMs,o.promptPhaseCalls=(o.promptPhaseCalls||0)+1,F!==void 0&&X.promptMs>0&&(X.promptNewTokensPerSecond=F/(X.promptMs/1e3),o.promptPhaseNewTokens=(o.promptPhaseNewTokens||0)+F,_+=X.promptMs)),X.ttftMs!==void 0&&W!==void 0&&W>=X.ttftMs?X.generationMs=W-X.ttftMs:X.generationTokensPerSecond!==void 0&&ce!==void 0&&(X.generationMs=ce/X.generationTokensPerSecond*1e3),X.generationMs!==void 0&&ce!==void 0&&(o.generationPhaseMs=(o.generationPhaseMs||0)+X.generationMs,o.generationPhaseTokens=(o.generationPhaseTokens||0)+ce);const pe=kn(O.speculation);if(Object.keys(pe).length){const ye={};Zt(pe.mode)&&(ye.mode=Zt(pe.mode)),typeof pe.used=="boolean"&&(ye.used=pe.used),Zt(pe.draft_kind)&&(ye.draftKind=Zt(pe.draft_kind));const Ne=vo(pe,["accepted_tokens"]),Ue=vo(pe,["drafted_tokens"]),We=vo(pe,["rounds"]),pt=vo(pe,["num_draft_tokens"]);Ne!==void 0&&(ye.acceptedTokens=Ne),Ue!==void 0&&(ye.draftedTokens=Ue),Ne!==void 0&&Ue&&(ye.acceptanceRate=Ne/Ue),We!==void 0&&(ye.rounds=We),pt!==void 0&&(ye.draftLength=pt),X.speculation=ye;const Fe=o.speculation||(o.speculation={calls:0,used:0});Fe.calls+=1,ye.used&&(Fe.used+=1),ye.mode&&(Fe.modes=nu(Fe.modes,ye.mode)),ye.draftKind&&(Fe.draftKinds=nu(Fe.draftKinds,ye.draftKind)),Ne!==void 0&&Ue!==void 0&&(Fe.acceptedTokens=(Fe.acceptedTokens||0)+Ne,Fe.draftedTokens=(Fe.draftedTokens||0)+Ue),We!==void 0&&(Fe.rounds=(Fe.rounds||0)+We),pt!==void 0&&(Fe.draftLengths=nu(Fe.draftLengths,pt))}w.push(X)}w.length&&(w.every(T=>T.startedAt)&&w.sort((T,I)=>Date.parse(T.startedAt)-Date.parse(I.startedAt)),o.modelCalls=w),_>0&&o.promptPhaseNewTokens!==void 0&&(o.promptPhaseTokensPerSecond=o.promptPhaseNewTokens/(_/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)),m>0&&(o.prefillNewTokens=f,o.prefillNewTokensPerSecond=f/(m/1e3));const k=new Map;for(const T of t.values()){if(T.status==="waiting"){o.toolsWaiting=(o.toolsWaiting||0)+1;continue}if(T.status==="running"){o.toolsRunning=(o.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(T.status))continue;o.toolCalls+=1;const I=T.status==="failed";I&&(o.toolsFailed=(o.toolsFailed||0)+1);const K=o.toolBreakdown||(o.toolBreakdown={}),U=K[T.name]||(K[T.name]={calls:0,failed:0});if(U.calls+=1,I){U.failed+=1;const fe=l1(T.output);fe&&((U.errors||(U.errors={}))[fe]=(((N=U.errors)==null?void 0:N[fe])||0)+1)}const J=Date.parse(Zt(T.startedAt)),Y=Date.parse(Zt(T.endedAt));if(Number.isFinite(J)&&Number.isFinite(Y)&&Y>=J){const fe=`${T.runId}|${T.startedAt}|${T.endedAt}`,W=k.get(fe)||{ms:Y-J,calls:0,names:new Map,waited:!1};W.calls+=1,W.names.set(T.name,(W.names.get(T.name)||0)+1),x.has(T.id)&&(W.waited=!0),k.set(fe,W)}if(T.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(T.name))continue;const re=gx(T.arguments),ce=Zt(re.destination||re.destination_path||re.file_path||re.path||re.filename);ce&&r.add(ce)}for(const T of k.values()){o.toolBatches=(o.toolBatches||0)+1,o.toolTimeMs=(o.toolTimeMs||0)+T.ms,T.waited&&(o.toolTimeIncludesApproval=!0);const I=[...T.names.keys()].sort();(!o.slowestToolBatch||T.ms>o.slowestToolBatch.ms)&&(o.slowestToolBatch={ms:T.ms,calls:T.calls,tools:I});const K=(C=o.toolBreakdown)==null?void 0:C[I[0]];if(I.length===1&&K)K.ms=(K.ms||0)+T.ms;else for(const U of I){const J=(E=o.toolBreakdown)==null?void 0:E[U];J&&(J.sharedBatches=(J.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 u1(e){const t=kn(kn(e).ledgers);return Object.entries(t).flatMap(([n,r])=>Zh(kn(r).items).map((o,l)=>({runId:n,cursor:Number(o.cursor)||l+1,record:Object.keys(kn(o.record)).length?kn(o.record):o})))}function Ah(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function Ay(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 $y(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function yx(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 d1(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 f1={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function Hd(e){return String(e).padStart(2,"0")}function h1(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=f1[String(t||"").toLowerCase()]||r.split(".").pop()||"bin",l=`${n.getFullYear()}-${Hd(n.getMonth()+1)}-${Hd(n.getDate())} at ${Hd(n.getHours())}.${Hd(n.getMinutes())}.${Hd(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!r?"Pasted image":"Pasted file"} ${l}.${o}`}function m1(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}=yx(e);return r.map(o=>{const l=h1(o.name,o.type,t);return l===o.name?o:new File([o],l,{type:o.type,lastModified:o.lastModified})})}class _1{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 p1(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 g1(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function y1(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 w1(e){var J;const t=e.interaction,[n,r]=p.useState(""),[o,l]=p.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[u,c]=p.useState(null),[f,m]=p.useState(!1),[_,g]=p.useState(""),[w,x]=p.useState(null),k=`${t.kind}:${t.id}`,j=p.useRef(k),N=p.useRef(!1),C=p.useRef(!1),E=p.useRef(!0),T=p.useRef(0);j.current!==k&&(j.current=k,N.current=!1,C.current=!1,T.current+=1);const I=!!e.disabled||u!==null||f||N.current||C.current,K=async(Y,re)=>{var W;if(e.disabled||N.current||C.current)return;const ce=k,fe=++T.current;N.current=!0,x(null),g(""),c(Y);try{if(await re(),!E.current||j.current!==ce||T.current!==fe)return;C.current=!0,m(!0),g("Response sent. Waiting for the workflow to continue.")}catch(O){if(!E.current||j.current!==ce||T.current!==fe)return;x({submission:Y,message:g1(O)}),g("The action failed. You can try again."),(W=e.onError)==null||W.call(e,O)}finally{if(!E.current||j.current!==ce||T.current!==fe)return;N.current=!1,c(null)}};p.useEffect(()=>{r(""),l(t.kind==="event-wait"&&t.initialPayload||""),x(null),c(null),m(!1),g("")},[k]),p.useEffect(()=>(E.current=!0,()=>{E.current=!1,T.current+=1,N.current=!1}),[]);const U=()=>{w&&K(w.submission,()=>p1(t,w.submission))};return s.jsxs("section",{className:"pc-workflow-interaction","aria-labelledby":`pc-workflow-interaction-${k}`,children:[s.jsxs("div",{className:"pc-workflow-interaction__heading",children:[s.jsx(et,{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-${k}`,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}),(J=t.choices)!=null&&J.length?s.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(Y=>s.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice",disabled:I||Y.disabled,onClick:()=>void K({kind:"choice",answer:Y.id},()=>t.onSubmit(Y.id)),children:[s.jsx("span",{children:Y.label}),Y.description?s.jsx("small",{children:Y.description}):null]},Y.id))}):null,t.allowFreeText!==!1?s.jsxs("div",{className:"pc-workflow-interaction__entry",children:[s.jsx("textarea",{"aria-label":"Response",value:n,onChange:Y=>r(Y.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:2,disabled:I,onKeyDown:Y=>{Y.key!=="Enter"||Y.shiftKey||Y.nativeEvent.isComposing||Y.keyCode===229||(Y.preventDefault(),n.trim()&&K({kind:"free-text",answer:n},()=>t.onSubmit(n)))}},`${k}:text`),s.jsx("button",{type:"button",className:"pc-btn",disabled:I||!n.trim(),onClick:()=>void K({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:I,onClick:()=>void K({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:I,onClick:()=>void K({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:I,onClick:()=>void K({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:Y=>l(Y.target.value),placeholder:t.payloadPlaceholder||"Enter payload",rows:2,"aria-label":t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload"),disabled:I},`${k}:payload`)]}),s.jsx("div",{className:"pc-workflow-interaction__buttons",children:s.jsx("button",{type:"button",className:"pc-btn",disabled:I,onClick:()=>void K({kind:"event",payload:o},()=>t.onSend(o)),children:(u==null?void 0:u.kind)==="event"?"Sending…":t.sendLabel||"Send event"})})]}),w?s.jsx(y1,{message:w.message,onRetry:U,disabled:I}):null,s.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:_})]})}function $h(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function v1(e){const[t,n]=p.useState(!1),[r,o]=p.useState(!1),[l,u]=p.useState(!1),[c,f]=p.useState(null),m=p.useRef(!0),_=p.useRef(!1),g=p.useRef(!1),w=p.useRef(!1),x=p.useRef(0),k=p.useRef(0),j=p.useRef(0);p.useEffect(()=>(m.current=!0,()=>{m.current=!1,x.current+=1,k.current+=1,j.current+=1,_.current=!1,g.current=!1,w.current=!1}),[]);const N=!!e.blockedNotice,C=!!e.disabled||N,E=!!e.busy||t,T=t||!!e.busy&&!e.sendWhileBusy,I=e.stopState||null,K=(I==null?void 0:I.phase)==="stopping",U=typeof e.onFiles=="function",J=p.useRef(null),[Y,re]=p.useState(null),[ce,fe]=p.useState(""),W=p.useRef(e.onFiles);W.current=e.onFiles;const O=p.useRef(C);O.current=C;const $=async(X,Q)=>{const le=W.current;if(le){if(O.current){f({action:"attach",message:"attachments are unavailable right now."});return}if(Q.length)f({action:"attach",message:d1(Q)});else if(X.length)f(null);else{f({action:"attach",message:"the drop contained no files."});return}if(X.length){fe(`Attaching ${X.length} ${X.length===1?"file":"files"}…`);try{await le(X)}catch(ge){m.current&&f({action:"attach",message:$h(ge)})}}}},z=p.useRef($);z.current=$,p.useEffect(()=>{if(!U||typeof window>"u")return;const X=new _1;let Q=0;const le=Fe=>!!(J.current&&Fe instanceof Node&&J.current.contains(Fe)),ge=()=>{X.reset(),Q&&window.clearInterval(Q),Q=0,re(null)},pe=()=>{Q||(Q=window.setInterval(()=>{X.active(Date.now())||ge()},250))},ye=Fe=>{var Ke;if(!Ah((Ke=Fe.dataTransfer)==null?void 0:Ke.types))return;X.enter(Date.now());const tt=le(Fe.target),lt=Ay(Fe.dataTransfer);re(ke=>ke&&ke.over===tt&&ke.count===(lt??ke.count)?ke:{count:lt??(ke==null?void 0:ke.count)??null,over:tt}),pe()},Ne=Fe=>{var lt;if(!Ah((lt=Fe.dataTransfer)==null?void 0:lt.types))return;Fe.preventDefault(),X.over(Date.now());const tt=le(Fe.target);Fe.dataTransfer&&(Fe.dataTransfer.dropEffect=tt&&!O.current?"copy":"none"),re(Ke=>Ke&&Ke.over===tt?Ke:{count:(Ke==null?void 0:Ke.count)??Ay(Fe.dataTransfer),over:tt}),pe()},Ue=Fe=>{var tt;Ah((tt=Fe.dataTransfer)==null?void 0:tt.types)&&(X.leave(Date.now())||ge())},We=Fe=>{var Re;if(!Ah((Re=Fe.dataTransfer)==null?void 0:Re.types))return;const tt=le(Fe.target),lt=Fe.defaultPrevented&&!tt;if(Fe.preventDefault(),ge(),lt)return;if(!tt){f({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:Ke,folders:ke}=yx(Fe.dataTransfer);z.current(Ke,ke)},pt=Fe=>{Fe.key==="Escape"&&X.depth>0&&ge()};return window.addEventListener("dragenter",ye),window.addEventListener("dragover",Ne),window.addEventListener("dragleave",Ue),window.addEventListener("drop",We),window.addEventListener("dragend",ge),window.addEventListener("blur",ge),window.addEventListener("keydown",pt),()=>{window.removeEventListener("dragenter",ye),window.removeEventListener("dragover",Ne),window.removeEventListener("dragleave",Ue),window.removeEventListener("drop",We),window.removeEventListener("dragend",ge),window.removeEventListener("blur",ge),window.removeEventListener("keydown",pt),Q&&window.clearInterval(Q)}},[U]);const A=X=>{if(!U||C)return;const Q=m1(X.clipboardData);Q.length&&(X.preventDefault(),$(Q,[]))},te=Y?s.jsxs("div",{className:["pc-workflow-chat__dropzone",Y.over?"is-over":"",C?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[s.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:s.jsx(et,{name:"paperclip",size:18})}),s.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[s.jsx("strong",{children:C?"Attachments are unavailable right now":$y(Y.count)}),C?null:s.jsx("span",{children:Y.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,P=Y?C?"Attachments are unavailable right now":$y(Y.count):ce,F=async()=>{const X=String(e.draft||"");if(C||_.current||!e.sendWhileBusy&&e.busy||!X.trim())return;const Q=++x.current;_.current=!0,f(null),n(!0);try{await e.onSend(X)}catch(le){m.current&&x.current===Q&&f({action:"send",message:$h(le)})}finally{m.current&&x.current===Q&&(_.current=!1,n(!1))}},G=async()=>{if(C||g.current||!e.onCancel)return;const X=++k.current;g.current=!0,f(null),o(!0);try{await e.onCancel()}catch(Q){m.current&&k.current===X&&f({action:"cancel",message:$h(Q)})}finally{m.current&&k.current===X&&(g.current=!1,o(!1))}},R=async()=>{if(C||w.current||!e.onAttach)return;const X=++j.current;w.current=!0,f(null),u(!0);try{await e.onAttach()}catch(Q){m.current&&j.current===X&&f({action:"attach",message:$h(Q)})}finally{m.current&&j.current===X&&(w.current=!1,u(!1))}},Z=()=>{c&&(c.action==="send"&&F(),c.action==="cancel"&&G(),c.action==="attach"&&R())};return s.jsxs("section",{ref:J,className:["pc-workflow-chat",Y?"pc-workflow-chat--dragging":"",Y!=null&&Y.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(w1,{interaction:e.interaction,disabled:C}):null,N?s.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${N?"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:Z,disabled:C,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:C,busy:T,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:U?A: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:C||l,onClick:()=>void R(),children:[s.jsx(et,{name:"paperclip",size:16}),s.jsx("span",{children:l?"Attaching…":"Attach"})]}):null,e.composerExtras,E&&e.onCancel?s.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:C||r||K,onClick:()=>void G(),children:[s.jsx(et,{name:"x",size:14}),s.jsx("span",{children:r||K?"Stopping…":"Stop"})]}):I?s.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${I.phase}`,role:"status","aria-live":"polite",children:I.label}):null]})}),U?s.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:P}):null]}),e.footer?s.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}const A_="llm.delta",Th="llm.delta_end";function x1(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ql(e){return typeof e=="string"&&e.trim()!==""}function b1(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function j1(e){return"reason"in e}function k1(e,t){const n=x1(e),r=n==null?void 0:n.kind,o=typeof r=="string"&&r?r:n&&"reason"in n?Th:A_,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!==A_&&r!==Th&&l(`unknown kind ${JSON.stringify(r)}`),ql(n.run_id)||l("run_id is missing"),ql(n.call_id)||l("call_id is missing"),b1(n.seq)||l("seq is not a non-negative integer");const u=r?r===Th:"reason"in n;n.root_run_id!==void 0&&!ql(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!ql(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");const c={run_id:n.run_id,...ql(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...ql(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:Th,...c,reason:n.reason,...ql(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:A_,...c,text:n.text,channel:n.channel,snapshot:n.snapshot})}const S1={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 N1(e){return`This reply is not streamed: ${e?S1[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}function C1(e){return e.toolApprovalGranted?null:e.interaction}const Ty={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function St(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 rf(e){return Array.isArray(e)?e:[]}function zr(e){return vt(e==null?void 0:e.status).toLowerCase()||"unknown"}function vs(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function Za(e){const t=St(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function E1(e){const t=St(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function $_(e){const t=n=>{if(Array.isArray(n))return n.map(t);const r=St(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 kp(e){if(typeof e=="string")return e.trim();const t=St(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 su(e){const t=kp(e);if(t)return t;if(!St(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function My(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=St(e.context);for(const r of["task","message"]){const o=vt(t==null?void 0:t[r]);if(o)return o}const n=rf(t==null?void 0:t.messages);for(let r=n.length-1;r>=0;r-=1){const o=St(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 wx(e){const t=St(e.result);return St(t==null?void 0:t.wait)}function T_(e){return e?vt(e.reason)==="subworkflow"||vt(e.wait_key).startsWith("subworkflow:"):!1}function Ry(e,t){return!!(e&&e.runId===t.runId&&vt(e.wait.wait_key)===vt(t.wait.wait_key))}function Sp(e){return St(e.effect)||{}}function A1(e,t){return vt(e.run_id)||t}function Ly(e){return vt(e.ended_at)||vt(e.started_at)||void 0}function Iy(e){const t=new Set,n=m=>{const _=vt(m);_&&t.add(_)},r=St(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=Sp(e),l=St(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=wx(e),c=St(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 $1{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...Ty},this.subscribers=new Set,this.controller=null,this.generation=0,this.rootRunId="",this.cursors=new Map,this.seenRecords=new Set,this.seenMessages=new Set,this.watchedRuns=new Set,this.childCatchUpAttempts=new Map,this.runStates=new Map,this.historicalRuns=new Map,this.historicalRunFailures=new Map,this.commandIds=new Map,this.toolActivities=new Map,this.historicalEvidence=new Map,this.approvedWaits=new Set,this.grantedToolWaits=new Set,this.resolvedWaits=new Set,this.approvalEpoch=0,this.toolApprovalPolicy=null,this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps=new Set,this.forcedStop=null,this.liveReplies=new Map,this.closedLiveCalls=new Set,this.shownLiveCalls=new Set,this.liveDirty=new Set,this.liveRenderTimer=null,this.lastLiveRender=-1/0;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({...Ty})}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=St(l),f=St(c==null?void 0:c.waiting),m=zr(c);if(await this.ingestHistory(u,n,r),!this.live(r))return;if(this.set({...this.snapshot,run:c,status:m,loading:!1,...f&&!vs(m)?{interaction:this.interactionWith({runId:n,wait:f})}:{}}),c&&this.updateRunState(n,c),f)for(const _ of Iy({result:{wait:f}}))_!==n&&this.catchUpAndWatch(_,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 _,g;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&&((_=this.snapshot.interaction)==null?void 0:_.stepId)||"",u=`${o}\0${t}\0${l}\0${$_(n)}`;let c=this.commandIds.get(u);c||(c=this.newCommandId(),this.commandIds.set(u,c));const f=this.generation,m=(g=this.controller)==null?void 0:g.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}:{}},m);if(!this.live(f))return w;const x=St(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){$_(t)!==$_(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&&T_(t.wait)&&!T_(n.wait)?n:n&&Ry(n,t)&&t.stepId===void 0&&n.stepId!==void 0?{...t,stepId:n.stepId}:t}adoptDurableWait(t,n){const r=St(n.waiting);if(!r||zr(n)!=="waiting"||T_(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&&Ry(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 _;const f=c.toolActivity;if(!f||((_=this.toolActivities.get(f.id))==null?void 0:_.status)!=="waiting")return c;const m=o&&f.runId===(n==null?void 0:n.runId)?"running":"waiting";return f.status===m?c:(l=!0,this.toolMessage({...f,status:m}))});return{...t,toolApprovalGranted:o,...l?{messages:u}:{}}}toolCallsMatch(t,n){var o;const r=rf((o=St(t.wait.details))==null?void 0:o.tool_calls);return r.length>0&&r.every(l=>{var c;const u=vt((c=St(l))==null?void 0:c.name);return!!u&&n.includes(u)})}isToolApproval(t){const n=St(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=St(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(Za(o))throw o;this.fail(o,!1)}if(await this.catchUp(t,n),!this.live(n)||vs(zr(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(Za(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=St(u),f=Array.isArray(u)?u:rf(c==null?void 0:c.items);for(const _ of f)this.ingestItem(t,_);const m=Number(c==null?void 0:c.next_after);if(!f.length||!Number.isFinite(m)||m<=l)break;this.cursors.set(t,m)}}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(zr(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,m=>{this.live(n)&&(c(),this.ingestItem(t,m))},this.controller.signal,c,m=>{this.live(n)&&(c(),this.ingestDelta(t,m))}),!this.live(n)||(await this.catchUp(t,n),!this.live(n)))return;const f=St(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),Za(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(zr(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=St(t);if(!o)return;const l=St(o.session),u=rf(l==null?void 0:l.turns).map(St).filter(m=>!!m);if(await this.hydrateHistoricalSessionRuns(u,n,r),!this.live(r))return;for(const m of u){const _=vt(m==null?void 0:m.run_id)||n;this.ingestSessionTurn(m,n,_!==n&&this.historicalRuns.get(_)||null)}const c=`turn:${n}:user`;if(!this.seenMessages.has(c)){const m=My(St(o.input_data));m&&this.addMessage({id:c,role:"user",content:m})}const f=St(o.ledgers);if(f)for(const[m,_]of Object.entries(f)){const g=St(_);for(const w of rf(g==null?void 0:g.items))this.ingestItem(m,w)}}ingestSessionTurn(t,n,r){if(!t)return;const o=vt(t.run_id)||n,l=St(t.input_data)||St(t.input)||{},u=vt(t.prompt)||My(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 g=vt(t.answer)||kp(t.output),w=c.missing?"is unavailable because the run no longer exists":"could not be restored",x=g?` Saved reply (not verified as the final result): ${g}`:"";this.addMessage({id:`history:${o}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${w}.${x}`});return}const m=(r&&vs(zr(r))?su(r.output):"")||(r?vt(t.answer)||kp(t.output):""),_=this.historicalEvidence.get(o);for(const g of(_==null?void 0:_.tools)||[])this.upsertTool(g);m&&this.addRunAssistantMessage(o,{id:`final:${o}`,role:"assistant",content:m,runId:o,statistics:_==null?void 0:_.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,m,_;for(;!u&&this.live(r);){const g=o[l++];if(!g)return;try{const w=St(await this.transport.getRun(g,(f=this.controller)==null?void 0:f.signal));if(!this.live(r))return;if(w){this.historicalRuns.set(g,w);try{const x=await this.transport.getHistory(g,(m=this.controller)==null?void 0:m.signal);if(!this.live(r))return;this.historicalEvidence.set(g,E_(u1(x)))}catch(x){if(!this.live(r))return;if(Za(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(g,null),this.historicalRunFailures.set(g,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(w){if(!this.live(r))return;const x=E1(w)===404;this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:x,detail:w instanceof Error?w.message:vt((_=St(w))==null?void 0:_.detail)||"request failed"}),Za(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=St(n),o=St(r==null?void 0:r.record)||r;if(!o)return;const l=A1(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(m=>m.id===`final:${this.rootRunId}`)){const m=E_(this.snapshot.records).statistics;this.set({...this.snapshot,messages:this.snapshot.messages.map(_=>_.id===`final:${this.rootRunId}`?{..._,statistics:m}:_)})}for(const m of Iy(o))m!==l&&this.catchUpAndWatch(m,this.generation)}}foldRecord(t,n,r){var _,g,w;const o=Sp(n),l=vt(o.type).toLowerCase(),u=St(n.result),c=vt(n.status).toLowerCase(),f=Ly(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=su(u)||su(St(o.payload));x&&this.addRunAssistantMessage(t,{id:`answer:${t}:${r}`,role:"assistant",content:x,ts:f})}if(l==="emit_event"&&c==="completed"){const x=St(o.payload)||{},k=St(u),j=vt(x.name)||vt(k==null?void 0:k.name),N=x.payload!==void 0?x.payload:k==null?void 0:k.payload;if(["abstract.message","abstractcode.message"].includes(j)){const C=su(N);if(C){const E=vt((_=St(N))==null?void 0:_.level).toLowerCase(),T=E==="error"?"error":["warn","warning"].includes(E)?"warn":"info";this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Workflow",content:C,level:T,ts:f})}}if(["abstract.status","abstractcode.status"].includes(j)){const C=St(N),E=C?C.status??C.text??C.value:N,T=Date.parse(f||"");!vs(this.snapshot.status)&&typeof E=="string"&&(!Number.isFinite(T)||T>=this.displayStatusAt)&&(Number.isFinite(T)&&(this.displayStatusAt=T),this.set({...this.snapshot,displayStatus:E.trim()}))}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(j)){const C=su(N);C&&this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Tool activity",content:C,ts:f})}}const m=wx(n);if(c==="waiting"&&m&&!vs(this.snapshot.status)&&!vs(zr(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${vt(m.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:m,...vt(n.step_id)?{stepId:vt(n.step_id)}:{}})})),l==="tool_calls")for(const x of px(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((g=St(o.payload))==null?void 0:g.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=St(Sp(n).payload)||{},c=St(n.result),f=vt(u.name)||vt(c==null?void 0:c.name),m=St(u.payload!==void 0?u.payload:c==null?void 0:c.payload);f==="abstract.status"&&vt(m==null?void 0:m.killed_by)==="kill_switch"&&(this.forcedStop=m,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=k1(n)}catch(f){this.fail(f,!1);return}const o=`${r.run_id}:${r.call_id}`;if(j1(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(zr(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:N1(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;Za(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=St(t))==null?void 0:l.detail)||String(t),...Za(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(zr(n))&&this.endLiveRepliesOfRun(t,zr(n)),t!==this.rootRunId){vs(zr(n))&&((l=this.snapshot.interaction)==null?void 0:l.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const r=zr(n),o=vs(r);if(o){const u=su(n.output);u&&this.upsertFinal(t,u,Ly(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:E_(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=St(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(zr(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||vs(zr(this.runStates.get(t)||null)))return;try{const o=St(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(Za(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 T1(e){const t=p.useMemo(()=>new $1(e.transport,{onAuthError:e.onAuthError,clientId:e.clientId,...e.liveRenderIntervalMs!==void 0?{liveRenderIntervalMs:e.liveRenderIntervalMs}:{}}),[e.transport,e.onAuthError,e.clientId,e.authScopeKey,e.liveRenderIntervalMs]),n=p.useSyncExternalStore(o=>t.subscribe(o),()=>t.getSnapshot(),()=>t.getSnapshot()),r=String(e.runId||"").trim();return p.useEffect(()=>{t.setToolApprovalPolicy(e.enabled===!1?{enabledTools:[],autoApproveTools:[]}:e.toolApprovalPolicy??null)},[t,e.toolApprovalPolicy,e.enabled]),p.useEffect(()=>{if(e.enabled===!1||!r){t.reset();return}return t.load(r),()=>t.reset()},[t,r,e.enabled]),{controller:t,snapshot:n}}function Hl(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function lr(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function Oy(e){return["session","workflow","run","global"].includes(e)?e:null}function el(e){return{scope:lr(e==null?void 0:e.scope).toLowerCase(),name:lr(e==null?void 0:e.name)||lr(e==null?void 0:e.event_name),scopeId:lr(e==null?void 0:e.scope_id)||lr(e==null?void 0:e.scopeId),sessionId:lr(e==null?void 0:e.session_id)||lr(e==null?void 0:e.sessionId),workflowId:lr(e==null?void 0:e.workflow_id)||lr(e==null?void 0:e.workflowId),runId:lr(e==null?void 0:e.run_id)||lr(e==null?void 0:e.runId)}}function M1(e,t){const n=e.wait,r=lr(n.wait_key),o=[el(n),el(Hl(n.details))];for(const l of t){if(l.runId!==e.runId)continue;const u=l.record,c=Hl(u.result),f=Hl(c==null?void 0:c.wait),m=Hl(u.effect),_=Hl(m==null?void 0:m.payload);lr(f==null?void 0:f.wait_key)!==r&&lr(_==null?void 0:_.wait_key)!==r||o.push(el(u),el(_),el(Hl(_==null?void 0:_.details)),el(f),el(Hl(f==null?void 0:f.details)))}return o}function M_(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function vx(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function R1(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?vx(t,n,o):null}function L1(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const r=lr(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=Oy(o[1]);if(!l)return{target:null,error:"The event wait uses an unsupported scope."};const u=M1(e,Array.isArray(t)?t:[]),c=new Map;for(const w of u){const x=Oy(w.scope);if(!x||!w.name)continue;if(x!==l)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const k=`evt:${x}:`,j=`:${w.name}`;if(!r.startsWith(k)||!r.endsWith(j)||r.length<=k.length+j.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const N=r.slice(k.length,-j.length),C=M_(x,w);if(C&&C!==N)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const E=vx(x,N,w.name);c.set(`${E.scope}\0${E.scopeId}\0${E.name}`,E)}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=M_(l,w);x&&f.add(x)}if(lr(n==null?void 0:n.run_id)===e.runId){const w=el(n||null),x=M_(l,w);x&&f.add(x)}const _=[...f].map(w=>R1(r,l,w)).filter(w=>!!w),g=new Map(_.map(w=>[`${w.scope}\0${w.scopeId}\0${w.name}`,w]));return g.size===1?{target:[...g.values()][0]}:g.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 hg=e=>wt(`runs/${encodeURIComponent(e)}/workspace`);function I1(e){return hg(e)}function O1(e,t){return`${hg(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function P1(e,t){return`${hg(e)}/content?${new URLSearchParams({path:t})}`}async function Tm(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 D1(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 F1(e,t,n){const r=await e(I1(t),{signal:n});if(!r.ok)throw await Tm(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 z1(e,t,n,r){const o=await e(O1(t,n),{signal:r});if(!o.ok)throw await Tm(o,"The folder could not be listed");return D1(await o.json(),n)}async function B1(e,t,n,r){const o=await e(P1(t,n),{signal:r});if(!o.ok)throw await Tm(o,"The file could not be read");return await o.blob()}async function U1(e,t,n,r){const o=await F1(e,t,r);return{where:o,listing:o.exists?await z1(e,t,n,r):null}}function W1(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 q1(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 H1(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function V1(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 G1=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function K1(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return G1.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 xx(e,t,n){const r=n==="open"?K1(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 Y1(e,t,n){const r=await e(bj(t),{signal:n.signal});if(!r.ok)throw await Tm(r,`${n.name} could not be read`);xx(await r.blob(),n.name,n.mode??"open")}function bx(e){const{fetchGateway:t,runId:n}=e,[r,o]=p.useState({runId:n,path:""}),l=r.runId===n?r.path:"",[u,c]=p.useState(null),[f,m]=p.useState(""),[_,g]=p.useState(!!n),[w,x]=p.useState(""),[k,j]=p.useState(0);p.useEffect(()=>{if(!n)return;const E=new AbortController;return g(!0),m(""),(async()=>{try{const T=await U1(t,n,l,E.signal);E.signal.aborted||c({runId:n,...T})}catch(T){E.signal.aborted||m(String((T==null?void 0:T.message)||T))}finally{E.signal.aborted||g(!1)}})(),()=>E.abort()},[t,n,l,k,e.refreshKey]);const N=u&&u.runId===n?u:null,C=p.useCallback(async(E,T)=>{x(E.path),m("");try{xx(await B1(t,n,E.path),E.name,T)}catch(I){m(String((I==null?void 0:I.message)||I))}finally{x("")}},[t,n]);return s.jsx(J1,{title:e.title,note:e.note,where:(N==null?void 0:N.where)??null,path:l,listing:(N==null?void 0:N.listing)??null,error:f,loading:_,fileBusy:w,selectedPath:e.selectedPath,className:e.className,onNavigate:E=>o({runId:n,path:E}),onRefresh:()=>j(E=>E+1),onFile:e.onSelectFile?void 0:(E,T)=>void C(E,T),onSelectFile:e.onSelectFile,onClose:e.onClose})}function J1(e){var r,o,l,u;const t=e.listing?V1(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(et,{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(et,{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(et,{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:W1(e.path).map((c,f,m)=>f===m.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:H1(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(et,{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(et,{name:"file",size:14})," ",c.name]}):s.jsxs("span",{className:"pc-ws__name",children:[s.jsx(et,{name:"file",size:14})," ",c.name]}),s.jsx("span",{className:"pc-ws__size",children:q1(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(et,{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 jx(e){return s.jsx(ux,{text:e,images:"link"})}const X1={trigger:"Trigger",answer:"Automation"};function Z1(e){return s.jsx(ug,{message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:X1[e.kind],runId:e.runId},images:"link"})}const Q1={renderText:jx,renderTurn:Z1};function eN(e){const{fetchGateway:t,...n}=e,r=n.onOpenResource??(t?o=>Y1(t,o.url,{name:o.name}):void 0);return s.jsx(aS,{...n,onOpenResource:r,...Q1})}function tN(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},m=[...new Set(c.map(g=>String((g==null?void 0:g.name)||"tool")))],_=n.onPermissionsAll;return{id:o,kind:"tool-approval",title:`${c.length||"Requested"} ${c.length===1?"action needs":"actions need"} permission`,toolName:m.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(hx,{tools:c.map((g,w)=>({id:String((g==null?void 0:g.call_id)||(g==null?void 0:g.id)||w),runId:e.runId,name:(g==null?void 0:g.name)||"Tool",arguments:g==null?void 0:g.arguments,status:"waiting"}))}),s.jsxs("details",{children:[s.jsx("summary",{children:"Review full tool arguments (JSON)"}),s.jsx(Is,{value:c.length?c:l})]})]}),approveLabel:"Allow once",denyLabel:"Deny",approveAllLabel:_?"Allow all enabled tools":void 0,approveAllDescription:_?"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:_?async()=>{await t.approveWithPolicyChange(f,()=>{_()})}: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=L1(e,n.records||[],n.currentRun??null),f=c.target,m=(f==null?void 0:f.name)||"";return{id:o,kind:"event-wait",title:f?"Waiting for an event":"Event routing unavailable",eventName:m,prompt:String(r.prompt||`This workflow will continue when “${m||"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 _=>{if(!f)throw new Error(c.error);const g=JSON.parse(_||"{}"),w={name:f.name,scope:f.scope,payload:g};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 nN='# 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): configurable growing-context budgets and result email; 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 Nm()}function sN(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function Mh(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function rN(e){const t=Mh(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=Mh(e.replayed_messages),r=Mh(e.dropped_tokens),o=Mh(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 kx(e){const t=rN(e.history);return t?s.jsx(ug,{message:{role:"system",level:"info",title:"History",content:t}}):null}const iN=1500,oN=12e4;function aN(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 lN=["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) ===",nN,"=== END DOCUMENTATION ==="].join(`
|
|
67
|
+
`),cN="observer-docs-assistant";function Py(){return`${cN}:${xs()}`}function uN(e){return{prompt:e,system:lN,tools:[],use_session_history:!0,use_context:!0}}function dN(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 fN(e,t,n=()=>{}){return async(r,o)=>{var f;const l=e(),u=await l.start_run(null,uN(r),{bundle_id:"basic-agent",session_id:t()}),c=Date.now();for(;;){if(await aN(iN,o.signal),Date.now()-c>oN)throw new Error("The assistant run timed out (120s). The run is still visible on the Observe page.");const m=await l.get_run(u),_=String((m==null?void 0:m.status)||"").trim().toLowerCase();if(_==="failed"||_==="cancelled"){const g=String(((f=m==null?void 0:m.error)==null?void 0:f.message)||(m==null?void 0:m.error)||"run "+_).slice(0,400);throw new Error(`The assistant run ${_}: ${g}`)}if(_==="completed"){n((m==null?void 0:m.session_history)??null);const g=await l.get_ledger(u,{after:0,limit:500,signal:o.signal});return dN(g.items)||"(the run completed but produced no readable answer — inspect it on the Observe page)"}}}}function hN(e){const t=p.useRef(e.gateway);t.current=e.gateway;const n=p.useRef(Py()),[r,o]=p.useState([]),[l,u]=p.useState(null),c=p.useMemo(()=>fN(()=>t.current,()=>n.current,u),[]),[f]=p.useState(void 0),m=()=>{n.current=Py(),o([]),u(null)};return s.jsxs(Dj,{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:m,title:"Start a new conversation (nothing earlier is replayed)",children:"New conversation"}),children:[s.jsx(kx,{history:l}),s.jsx(o1,{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 mN(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 _N(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 pN(e,t,n){return e<=0?-1:t<0?n?e-1:0:(t+(n?e-1:1))%e}const gN='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function yN(e){return typeof document>"u"?!1:Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e)}function wN(e){const[t,n]=p.useReducer(mN,!1),r=p.useRef(null),o=p.useRef(null),l=p.useRef(!1);return p.useEffect(()=>{n({type:"page_change"})},[e.page]),p.useEffect(()=>{n({type:"layout_change"})},[e.is_drawer]),p.useEffect(()=>{var u;if(t){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 m=_=>{if(_.key==="Escape"){n({type:"escape",default_prevented:_.defaultPrevented,other_modal_open:yN(o.current)});return}if(_.key!=="Tab"||!o.current)return;const g=Array.from(o.current.querySelectorAll(gN)).filter(x=>x.offsetParent!==null||x===document.activeElement),w=pN(g.length,g.indexOf(document.activeElement),_.shiftKey);w>=0&&(_.preventDefault(),g[w].focus())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)}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:_N(e.is_drawer,t)}}const vN="api/local/reveal",xN="sw.js",Np="#run/";function bN(e){return`${Np}${encodeURIComponent(String(e||"").trim())}`}function Sx(e){const t=String(e||"");if(!t.startsWith(Np))return"";const n=t.slice(Np.length).split("?")[0];if(!n||n.includes("/"))return"";try{return decodeURIComponent(n).trim()}catch{return""}}function jN(e){return`Run ${e} cannot be opened: it does not exist on this gateway, or your account cannot see it.`}function kN(e){const t=Sx(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 SN={llm_call:"llm_call",tool_calls:"tool",tool_invoke:"tool",entity_tools_execute:"tool",start_subworkflow:"subflow",emit_event:"event",wait_event:"wait",wait_until:"wait",resume:"resume",ask_user:"ask",answer_user:"answer",model_residency:"model",memory_query:"memory",memory_tag:"memory",memory_compact:"memory",memory_note:"memory",memory_rehydrate:"memory",memory_kg_assert:"memory",memory_kg_query:"memory",memory_kg_resolve:"memory",memory_recall:"memory",memory_access:"memory",memory_form:"memory",memory_adjust:"memory",memory_appraise:"memory",memory_consolidate:"memory",memory_probe:"memory",memory_tend:"memory",diary_write:"memory",diary_read:"memory",life_query:"memory",entity_tools_query:"memory",vars_query:"memory"},NN=new Set(["wait","resume","memory","model","node"]),CN=new Set(["abstract.status","abstract.progress","abstract.steer_seen","abstract.summary"]),EN={llm_call:"LLM call",tool:"Tools",subflow:"Subflow",event:"Event",wait:"Wait",resume:"Resume",ask:"Question",answer:"Answer",memory:"Memory",model:"Model",node:"Node",other:"Effect"};function AN(e){const t=String(e||"").trim();return t?SN[t]||"other":"node"}function $N(e,t,n){return n?!1:e==="event"?CN.has(String(t||"").trim()):NN.has(e)}const TN=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 MN(e){const t=new TextEncoder().encode(e),n=t.length*8,r=t.length+9+63>>6<<6,o=new Uint8Array(r);o.set(t),o[t.length]=128;const l=new DataView(o.buffer);l.setUint32(r-8,Math.floor(n/4294967296)),l.setUint32(r-4,n>>>0);const u=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),c=new Uint32Array(64);for(let f=0;f<r;f+=64){for(let C=0;C<16;C++)c[C]=l.getUint32(f+C*4);for(let C=16;C<64;C++){const E=c[C-15],T=c[C-2],I=(E>>>7|E<<25)^(E>>>18|E<<14)^E>>>3,K=(T>>>17|T<<15)^(T>>>19|T<<13)^T>>>10;c[C]=c[C-16]+I+c[C-7]+K>>>0}let[m,_,g,w,x,k,j,N]=u;for(let C=0;C<64;C++){const E=(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7),T=x&k^~x&j,I=N+E+T+TN[C]+c[C]>>>0,K=(m>>>2|m<<30)^(m>>>13|m<<19)^(m>>>22|m<<10),U=m&_^m&g^_&g,J=K+U>>>0;N=j,j=k,k=x,x=w+I>>>0,w=g,g=_,_=m,m=I+J>>>0}u[0]=u[0]+m>>>0,u[1]=u[1]+_>>>0,u[2]=u[2]+g>>>0,u[3]=u[3]+w>>>0,u[4]=u[4]+x>>>0,u[5]=u[5]+k>>>0,u[6]=u[6]+j>>>0,u[7]=u[7]+N>>>0}return Array.from(u,f=>f.toString(16).padStart(8,"0")).join("")}const Cp="$slim";function RN(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&e[Cp]&&typeof e[Cp]=="object")}function LN(e){const t=new Map;for(const n of e||[]){if(!n||typeof n!="object"||String(n.status||"")!=="started")continue;const r=String(n.step_id||""),o=n.effect&&typeof n.effect=="object"?n.effect.payload:null;r&&o&&typeof o=="object"&&!t.has(r)&&t.set(r,o)}return t}function IN(e,t){const n=[];for(const r of t)if(r==="system"){if(typeof e.system_prompt!="string"||!e.system_prompt)return null;n.push({role:"system",content:e.system_prompt})}else if(r==="messages"){if(!Array.isArray(e.messages))return null;for(const o of e.messages)o&&typeof o=="object"&&n.push({...o})}else if(r==="prompt"){if(typeof e.prompt!="string"||!e.prompt)return null;n.push({role:"user",content:e.prompt})}else return null;return n}function ON(e,t){const n=e&&e[Cp];if(!n||typeof n!="object")return{state:"missing",reason:"not a $slim marker"};const r=t.get(String(n.step_id||""));if(!r)return{state:"missing",reason:"its started record is not in the loaded ledger"};let o;if(n.kind==="started_payload_field"){const u=String(n.field||"");if(!(u in r))return{state:"missing",reason:`the started record has no "${u}" field`};o=r[u]}else if(n.kind==="started_messages_layout"){if(o=Array.isArray(n.layout)?IN(r,n.layout.map(String)):null,!o)return{state:"missing",reason:"the started record cannot rebuild these messages"}}else return{state:"missing",reason:`unknown $slim kind "${String(n.kind||"")}"`};if(Array.isArray(n.appendix)&&n.appendix.length){if(!Array.isArray(o))return{state:"missing",reason:"appendix on a non-list value"};const u=o.map(f=>f&&typeof f=="object"?{...f}:f),c=[...n.appendix].sort((f,m)=>Number((f==null?void 0:f.at)??-1)-Number((m==null?void 0:m.at)??-1));for(const f of c){const m=Number(f==null?void 0:f.at);if(!Number.isInteger(m)||m<0||m>u.length)return{state:"missing",reason:"appendix position out of range"};u.splice(m,0,f.item)}o=u}return MN(JSON.stringify(o))!==String(n.sha256||"")?{state:"unverified",value:o,reason:"checksum differs from the record"}:{state:"resolved",value:o}}function PN(e,t){const n=[],r=[],o=(l,u,c)=>{if(c>14)return l;if(RN(l)){const f=ON(l,t);return f.state==="missing"?(n.push({path:u,reason:f.reason}),l):(f.state==="unverified"&&r.push({path:u,reason:f.reason}),f.value)}if(Array.isArray(l)){let f=null;return l.forEach((m,_)=>{const g=o(m,`${u}[${_}]`,c+1);g!==m&&((f??(f=[...l]))[_]=g)}),f??l}if(l&&typeof l=="object"){let f=null;for(const m of Object.keys(l)){const _=o(l[m],u?`${u}.${m}`:m,c+1);_!==l[m]&&((f??(f={...l}))[m]=_)}return f??l}return l};return{value:o(e,"",0),unresolved:n,unverified:r}}function Dy(e){const t=Date.parse(String(e||""));return Number.isFinite(t)?t:null}function Nx(e){const t=e==null?void 0:e.result;return t&&typeof t=="object"&&Array.isArray(t.results)?t.results:[]}function DN(e,t){return e?String(e.status||"")==="failed"||e.error?!0:t==="tool"&&Nx(e).some(n=>n&&n.success===!1):!1}function Cx(e,t){var m,_,g,w,x,k;const n=String(t||"").trim(),r=(e||[]).filter(j=>j&&j.record&&String(j.run_id||j.record.run_id||"").trim()===n).sort((j,N)=>(j.cursor||0)-(N.cursor||0)),o=LN(r.map(j=>j.record)),l=new Map,u=[];for(const j of r){const N=j.record,E=String(N.step_id||"")||`cursor:${j.cursor}`;let T=l.get(E);T||(T={cursor:j.cursor,started:null,latest:N,latest_cursor:j.cursor},l.set(E,T),u.push(E)),String(N.status||"")==="started"&&!T.started&&(T.started=N),j.cursor>=T.latest_cursor&&(T.latest=N,T.latest_cursor=j.cursor)}let c=0;const f=[];for(const j of u){const N=l.get(j),C=PN(N.latest,o),E=C.value,T=String(((m=E==null?void 0:E.effect)==null?void 0:m.type)||((g=(_=N.started)==null?void 0:_.effect)==null?void 0:g.type)||"").trim(),I=AN(T),K=I==="event"?String(((x=(w=E==null?void 0:E.effect)==null?void 0:w.payload)==null?void 0:x.name)||"").trim():"";I==="llm_call"&&(c+=1);const U=DN(E,I),J=String(((k=N.started)==null?void 0:k.started_at)||(E==null?void 0:E.started_at)||""),Y=String((E==null?void 0:E.ended_at)||""),re=Dy(J),ce=Dy(Y);f.push({id:`${n}:${j}`,run_id:n,step_id:String((E==null?void 0:E.step_id)||""),node_id:String((E==null?void 0:E.node_id)||""),kind:I,effect_type:T,event_name:K,status:String((E==null?void 0:E.status)||""),cursor:N.cursor,started_at:J,ended_at:Y,duration_ms:re!==null&&ce!==null?Math.max(0,ce-re):null,started:N.started,record:E,failed:U,housekeeping:$N(I,K,U),cycle:c,unresolved:C.unresolved,unverified:C.unverified})}return f}function FN(e){const t=[];for(const n of e){let r=t[t.length-1];(!r||r.cycle!==n.cycle)&&(r={cycle:n.cycle,steps:[],llm:null},t.push(r)),n.kind==="llm_call"&&!r.llm&&(r.llm=n),r.steps.push(n)}return t}const zN={view:"cycles",only:"all",all_steps:!1,q:""};function BN(e,t,n){const r=String(t.q||"").trim().toLowerCase();return e.filter(o=>!(t.only==="llm"&&o.kind!=="llm_call"||t.only==="tools"&&o.kind!=="tool"||t.only==="failed"&&!o.failed||t.only==="all"&&!t.all_steps&&o.housekeeping||r&&!n(o).includes(r)))}const UN=["all","llm","tools","failed"];function Fy(e){const t=String(e||""),n=t.indexOf("?");if(n<0)return{...zN};const r=new URLSearchParams(t.slice(n+1)),o=String(r.get("only")||"");return{view:r.get("view")==="steps"?"steps":"cycles",only:UN.includes(o)?o:"all",all_steps:r.get("all")==="1",q:String(r.get("q")||"")}}function WN(e,t){const n=String(e||"").split("?")[0],r=new URLSearchParams;t.view!=="cycles"&&r.set("view",t.view),t.only!=="all"&&r.set("only",t.only),t.all_steps&&r.set("all","1"),t.q.trim()&&r.set("q",t.q);const o=r.toString();return o?`${n}?${o}`:n}function _u(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof(t==null?void 0:t.text)=="string"?t.text:t!=null&&t.type?`[${String(t.type)}]`:JSON.stringify(t)).join(`
|
|
68
|
+
`):e==null?"":JSON.stringify(e,null,2)}function Ex(e){if(typeof e!="string")return e??{};try{return JSON.parse(e)}catch{return e}}function Ax(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object").map(t=>{var n,r;return{name:String(t.name||((n=t.function)==null?void 0:n.name)||"?"),arguments:Ex(t.arguments??((r=t.function)==null?void 0:r.arguments))}}):[]}function zy(e){const t={role:String((e==null?void 0:e.role)||"?"),content:_u(e==null?void 0:e.content)},n=Ax(e==null?void 0:e.tool_calls);return n.length&&(t.tool_calls=n),e!=null&&e.name&&(t.name=String(e.name)),t}function By(e){const t=Number(e);return Number.isFinite(t)&&e!==null&&e!==void 0?t:null}const qN={"effect.payload.system_prompt":"System","effect.payload.messages":"Messages","effect.payload.prompt":"Prompt","effect.payload.tools":"Tools offered","result.metadata._provider_request.payload.messages":"Messages sent"};function mg(e){var x,k,j,N,C,E;const t=e.record||{},n=((k=(x=e.started)==null?void 0:x.effect)!=null&&k.payload&&typeof e.started.effect.payload=="object"?e.started.effect.payload:(j=t==null?void 0:t.effect)==null?void 0:j.payload)||{},r=t!=null&&t.result&&typeof t.result=="object"?t.result:{},o=r.usage||r.token_usage||{},l=[],u=e.unverified.map(T=>`${T.path}: ${T.reason}`);for(const T of e.unresolved){const I=qN[T.path];I&&l.push(`${I}: ${T.reason}`)}const c=(C=(N=r==null?void 0:r.metadata)==null?void 0:N._provider_request)==null?void 0:C.payload;let f="",m=[],_="";if(c&&Array.isArray(c.messages)){_="sent";for(const T of c.messages)String((T==null?void 0:T.role)||"")==="system"&&!m.length?f+=(f?`
|
|
69
|
+
|
|
70
|
+
`:"")+_u(T.content):m.push(zy(T))}else(Array.isArray(n.messages)||typeof n.prompt=="string")&&(_="payload",m=(Array.isArray(n.messages)?n.messages:[]).map(zy),typeof n.prompt=="string"&&n.prompt.trim()&&m.push({role:"user",content:n.prompt}));!f&&typeof n.system_prompt=="string"&&(f=n.system_prompt);const w=(Array.isArray(n.tools)?n.tools:Array.isArray(c==null?void 0:c.tools)?c.tools:[]).filter(T=>T&&typeof T=="object").map(T=>{const I=T.function&&typeof T.function=="object"?T.function:T;return{name:String(I.name||"?"),description:String(I.description||""),schema:I.parameters??I.input_schema??null}});return{provider:String(n.provider||r.provider||""),model:String(n.model||r.model||""),tokens_in:By(o.prompt_tokens??o.input_tokens),tokens_out:By(o.completion_tokens??o.output_tokens),system:f,messages:m,messages_source:_,tools:w,response:_u(r.content??r.response??""),tool_calls:Ax(r.tool_calls),reasoning:_u(r.reasoning??((E=r==null?void 0:r.metadata)==null?void 0:E.reasoning)??""),missing:l,unverified:u}}function _g(e){var o,l,u,c;const t=((l=(o=e.record)==null?void 0:o.effect)==null?void 0:l.payload)||((c=(u=e.started)==null?void 0:u.effect)==null?void 0:c.payload)||{},n=(Array.isArray(t.tool_calls)?t.tool_calls:[]).map(f=>{var m,_;return{name:String((f==null?void 0:f.name)||((m=f==null?void 0:f.function)==null?void 0:m.name)||"?"),arguments:Ex((f==null?void 0:f.arguments)??((_=f==null?void 0:f.function)==null?void 0:_.arguments)),call_id:String((f==null?void 0:f.call_id)||(f==null?void 0:f.id)||"")}}),r=Nx(e.record).map(f=>({name:String((f==null?void 0:f.name)||"?"),success:typeof(f==null?void 0:f.success)=="boolean"?f.success:null,output:(f==null?void 0:f.output)==null?"":_u(f.output),error:(f==null?void 0:f.error)==null?"":_u(f.error),call_id:String((f==null?void 0:f.call_id)||"")}));return{calls:n,results:r}}function HN(e){return e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).map(([t,n])=>`${t}=${JSON.stringify(n)}`).join(", "):typeof e=="string"?e:JSON.stringify(e??"")}function $x(e){var r,o,l;const t=(r=e==null?void 0:e.result)==null?void 0:r.wait,n=typeof(t==null?void 0:t.wait_key)=="string"&&t.wait_key.startsWith("subworkflow:")?t.wait_key.slice(12):"";return String(((o=t==null?void 0:t.details)==null?void 0:o.sub_run_id)||((l=e==null?void 0:e.result)==null?void 0:l.sub_run_id)||n||"").trim()}function Tx(e){var n,r,o,l,u,c,f,m,_,g,w;const t=e.record||{};switch(e.kind){case"llm_call":{const x=mg(e);return x.tokens_in!==null||x.tokens_out!==null?`${(x.tokens_in??0).toLocaleString("en-US")} in · ${(x.tokens_out??0).toLocaleString("en-US")} out`:""}case"tool":{const x=_g(e).calls;if(!x.length)return"";const k=`${x[0].name}(${HN(x[0].arguments)})`;return x.length>1?`${k} +${x.length-1} more`:k}case"event":return e.event_name;case"subflow":{const x=$x(t);return[String(((r=(n=t==null?void 0:t.effect)==null?void 0:n.payload)==null?void 0:r.workflow_id)||""),x].filter(Boolean).join(" · ")}case"wait":case"resume":return String(((l=(o=t==null?void 0:t.result)==null?void 0:o.wait)==null?void 0:l.reason)||((c=(u=t==null?void 0:t.effect)==null?void 0:u.payload)==null?void 0:c.reason)||"");case"ask":return String(((m=(f=t==null?void 0:t.effect)==null?void 0:f.payload)==null?void 0:m.prompt)||"");case"answer":return String(((g=(_=t==null?void 0:t.effect)==null?void 0:_.payload)==null?void 0:g.message)||((w=t==null?void 0:t.result)==null?void 0:w.message)||"");default:return e.effect_type}}function Mx(e){return e.kind==="llm_call"?mg(e).model:""}function VN(e,t){var r,o;const n=[e.kind,e.effect_type,e.event_name,e.node_id,t,e.status,Tx(e),Mx(e)];try{n.push(JSON.stringify(((o=(r=e.started)==null?void 0:r.effect)==null?void 0:o.payload)??null)),n.push(JSON.stringify(e.record??null))}catch{}return n.join(`
|
|
71
|
+
`).toLowerCase()}function GN(e){var r,o;const t=Array.from(new Set((e||[]).map(l=>{var u;return String(l.run_id||((u=l.record)==null?void 0:u.run_id)||"").trim()}).filter(Boolean))),n={llm_calls:0,tokens:0,tool_calls:0,tool_failures:0};for(const l of t)for(const u of Cx(e,l))if(u.kind==="llm_call"){n.llm_calls+=1;const c=((o=(r=u.record)==null?void 0:r.result)==null?void 0:o.usage)||{};n.tokens+=Number(c.total_tokens??Number(c.prompt_tokens??c.input_tokens??0)+Number(c.completion_tokens??c.output_tokens??0))||0}else if(u.kind==="tool"){const c=_g(u);n.tool_calls+=Math.max(c.calls.length,c.results.length),n.tool_failures+=c.results.filter(f=>f.success===!1).length}return n}function KN(e){const t=[];return e.llm_calls&&t.push(`${e.llm_calls} LLM call${e.llm_calls===1?"":"s"}`),e.tokens&&t.push(`${e.tokens.toLocaleString("en-US")} tokens`),e.tool_calls&&t.push(`${e.tool_calls} tool call${e.tool_calls===1?"":"s"}${e.tool_failures?`, ${e.tool_failures} failed`:""}`),t.join(" · ")}function Ct(){return new Date().toISOString()}function YN(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function cr(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 kt(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,`
|
|
72
|
+
`).replace(/\r/g,`
|
|
73
|
+
`).split(`
|
|
74
|
+
`),u=l.slice(0,Math.max(1,r)).join(`
|
|
75
|
+
`),c=l.length>r,f=u.length>n?`${u.slice(0,Math.max(0,n-1))}…`:u;return c&&f===u?`${u}…`:f}function Qt(e,t){const n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function Uy(e){const t=String(e||"").trim();return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function qn(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 JN(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 ec(e){const t=qn(e);return t===null?"—":JN(t)}function Wy(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 pg(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 bu(e){const t=qn(e);return t===null?"—":new Date(t).toLocaleString()}function _n(...e){for(const t of e){const n=String(t??"").trim();if(n)return n}return""}function XN(...e){for(const t of e){const n=Number(t);if(Number.isFinite(n))return n}return null}function So(e){const t=String(e||"").trim().toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}function ju(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function fu(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function ZN(e){const t=String((e==null?void 0:e.status)||"").trim();return So(t)?String((e==null?void 0:e.finished_at)||(e==null?void 0:e.updated_at)||"").trim():""}function gg(e,t=Date.now()){const n=qn(fu(e));if(n===null)return-1;const r=qn(ZN(e));return Math.max(0,(r!==null?r:t)-n)}function ic(e,t=Date.now()){return pg(gg(e,t))}function QN(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 e2(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 oc(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 t2={all:"All",llm:"LLM calls",tools:"Tools",failed:"Failed"};function bi(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function bo(e){return s.jsxs("details",{className:"rs_section",open:e.open,children:[s.jsxs("summary",{children:[s.jsx("span",{className:"rs_section_title",children:e.title}),e.meta?s.jsx("span",{className:"rs_section_meta",children:e.meta}):null,e.copy!==void 0?s.jsx("button",{type:"button",className:"rs_copy",onClick:t=>{t.preventDefault(),t.stopPropagation(),e.on_copy(e.copy||"")},children:"Copy"}):null]}),s.jsx("div",{className:"rs_section_body",children:e.children})]})}function R_(e){return`${e.toLocaleString("en-US")} chars`}function yg(e){const t=e.step.started&&e.step.started!==e.step.record?{started:e.step.started,record:e.step.record}:e.step.record;return s.jsx(bo,{title:"Raw JSON",copy:bi(t),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(Is,{value:t,collapseAfterDepth:2,showCopy:!1})})})}function n2(e){const t=mg(e.step),n=!t.system&&!t.messages.length&&!t.missing.length;return s.jsxs(s.Fragment,{children:[t.missing.map(r=>s.jsxs("p",{className:"rs_notice",children:["Prompt body not kept: ",r,"."]},r)),n?s.jsx("p",{className:"rs_notice",children:"Prompt body not kept: this record carries no request messages."}):null,t.unverified.length?s.jsxs("p",{className:"rs_notice",children:["Rebuilt prompt may differ from what was sent: ",t.unverified.join("; "),"."]}):null,t.system?s.jsx(bo,{title:"System",meta:R_(t.system.length),copy:t.system,on_copy:e.on_copy,children:s.jsx("pre",{className:"rs_text",children:t.system})}):null,t.messages.length?s.jsx(bo,{title:"Messages",meta:`${t.messages.length}${t.messages_source==="sent"?" · as sent":""}`,copy:bi(t.messages),on_copy:e.on_copy,children:s.jsx("ol",{className:"rs_messages",children:t.messages.map((r,o)=>{var l;return s.jsxs("li",{className:`rs_msg rs_msg_${r.role}`,children:[s.jsxs("span",{className:"rs_role",children:[r.role,r.name?` · ${r.name}`:""]}),r.content?s.jsx("pre",{className:"rs_text",children:r.content}):null,(l=r.tool_calls)==null?void 0:l.map((u,c)=>s.jsx("pre",{className:"rs_text mono",children:`${u.name}(${bi(u.arguments)})`},c))]},o)})})}):null,t.tools.length?s.jsx(bo,{title:"Tools offered",meta:String(t.tools.length),copy:bi(t.tools),on_copy:e.on_copy,children:s.jsx("ul",{className:"rs_tools",children:t.tools.map(r=>s.jsxs("li",{children:[s.jsx("strong",{className:"mono",children:r.name}),r.description?s.jsxs("span",{children:[" — ",r.description]}):null]},r.name))})}):null,s.jsxs(bo,{title:"Response",meta:t.tool_calls.length?`${t.tool_calls.length} tool call${t.tool_calls.length===1?"":"s"}`:t.response?R_(t.response.length):"empty",copy:t.response||bi(t.tool_calls),open:!0,on_copy:e.on_copy,children:[t.response?s.jsx("div",{className:"rs_markdown",children:s.jsx(Wi,{text:t.response})}):null,t.tool_calls.map((r,o)=>s.jsx("pre",{className:"rs_text mono",children:`${r.name}(${bi(r.arguments)})`},o)),!t.response&&!t.tool_calls.length?s.jsx("p",{className:"rs_muted",children:"No text and no tool call."}):null]}),t.reasoning?s.jsx(bo,{title:"Reasoning",meta:R_(t.reasoning.length),copy:t.reasoning,on_copy:e.on_copy,children:s.jsx("pre",{className:"rs_text",children:t.reasoning})}):null,s.jsx(yg,{step:e.step,on_copy:e.on_copy})]})}function s2(e){const t=_g(e.step);return s.jsxs(s.Fragment,{children:[s.jsx(bo,{title:"Calls",meta:String(t.calls.length),copy:bi(t.calls),open:!0,on_copy:e.on_copy,children:t.calls.map((n,r)=>s.jsx("pre",{className:"rs_text mono",children:`${n.name}(${bi(n.arguments)})`},r))}),s.jsxs(bo,{title:"Results",meta:String(t.results.length),copy:bi(t.results),open:!0,on_copy:e.on_copy,children:[t.results.length?null:s.jsx("p",{className:"rs_muted",children:"No result recorded yet."}),s.jsx("ol",{className:"rs_messages",children:t.results.map((n,r)=>s.jsxs("li",{className:`rs_msg ${n.success===!1?"rs_msg_failed":""}`,children:[s.jsxs("span",{className:"rs_role",children:[n.name," · ",n.success===!1?"failed":n.success?"ok":"unknown"]}),n.error?s.jsx("pre",{className:"rs_text",children:n.error}):null,n.output?s.jsx("pre",{className:"rs_text",children:n.output}):null]},r))})]}),s.jsx(yg,{step:e.step,on_copy:e.on_copy})]})}function r2(e){var o,l,u;const t=e.step.record||{},n=((l=(o=e.step.started)==null?void 0:o.effect)==null?void 0:l.payload)??((u=t==null?void 0:t.effect)==null?void 0:u.payload),r=e.step.kind==="subflow"?$x(t):"";return s.jsxs(s.Fragment,{children:[r&&e.on_open_run?s.jsxs("p",{className:"rs_line_actions",children:[s.jsx("span",{className:"mono",children:r}),s.jsx("button",{type:"button",className:"btn btn_sm",onClick:()=>{var c;return(c=e.on_open_run)==null?void 0:c.call(e,r)},children:"Open"})]}):null,t.error?s.jsx("pre",{className:"rs_text rs_error",children:typeof t.error=="string"?t.error:bi(t.error)}):null,n!=null?s.jsx(bo,{title:"Payload",copy:bi(n),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(Is,{value:n,collapseAfterDepth:2,showCopy:!1})})}):null,t.result!==void 0&&t.result!==null?s.jsx(bo,{title:"Result",copy:bi(t.result),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(Is,{value:t.result,collapseAfterDepth:2,showCopy:!1})})}):null,s.jsx(yg,{step:e.step,on_copy:e.on_copy})]})}function i2(e){const t=e.step,n=Tx(t),r=Mx(t),o=t.failed&&t.status!=="failed"?"failed":t.status;return s.jsxs("article",{className:`rs_card ${t.failed?"rs_failed":""}`,"data-kind":t.kind,"data-step-id":t.step_id||void 0,children:[s.jsxs("button",{type:"button",className:"rs_card_head","aria-expanded":e.open,onClick:e.on_toggle,children:[s.jsx("span",{className:"rs_chevron","aria-hidden":"true",children:e.open?"▾":"▸"}),s.jsx("span",{className:"rs_kind",children:EN[t.kind]}),s.jsx("span",{className:"rs_node",children:e.node_label||t.node_id||t.effect_type||"step"}),s.jsx("span",{className:`rs_status ${oc(o)}`,children:o||"—"}),s.jsx("span",{className:"rs_dur",children:t.duration_ms!==null?pg(t.duration_ms):""}),r?s.jsx("span",{className:"rs_detail",children:r}):null,n?s.jsx("span",{className:"rs_line",children:n}):null]}),e.open?s.jsx("div",{className:"rs_card_body",children:t.kind==="llm_call"?s.jsx(n2,{step:t,on_copy:e.on_copy}):t.kind==="tool"?s.jsx(s2,{step:t,on_copy:e.on_copy}):s.jsx(r2,{step:t,on_copy:e.on_copy,on_open_run:e.on_open_run})}):null]})}function o2(e){const{state:t}=e,n=p.useMemo(()=>Cx(e.items,e.run_id),[e.items,e.run_id]),[r,o]=p.useState({}),l=k=>e.node_label(k.run_id,k.node_id),u=p.useMemo(()=>new Map,[n]),f=BN(n,t,k=>{let j=u.get(k.id);return j===void 0&&(j=VN(k,l(k)),u.set(k.id,j)),j}),m=n.some(k=>k.kind==="llm_call"),_=n.reduce((k,j)=>j.kind==="llm_call"?k+1:k,0),g=n.length-f.length,w=k=>e.on_state({...t,...k}),x=k=>s.jsx(i2,{step:k,node_label:l(k),open:r[k.id]===!0,on_toggle:()=>o(j=>({...j,[k.id]:!j[k.id]})),on_copy:e.on_copy,on_open_run:e.on_open_run},k.id);return s.jsxs("div",{className:"rs_view",children:[s.jsxs("div",{className:"rs_count",children:[s.jsxs("span",{children:[f.length," of ",n.length," steps",m?` · ${_} cycle${_===1?"":"s"}`:"",g&&t.only==="all"&&!t.all_steps&&!t.q?` · ${g} housekeeping hidden`:""]}),e.run_options.length>1?s.jsx("select",{className:"seg_select mono",value:e.run_id,onChange:k=>e.on_select_run(String(k.target.value||"")),"aria-label":"Run",children:e.run_options.map(k=>s.jsxs("option",{value:k,children:[Qt(k,14),e.run_llm_counts[k]?` · ${e.run_llm_counts[k]} LLM`:""]},k))}):null]}),s.jsxs("div",{className:"rs_toolbar",children:[s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Layout",children:["cycles","steps"].map(k=>s.jsx("button",{type:"button",role:"radio","aria-checked":t.view===k,className:`seg_btn ${t.view===k?"active":""}`,onClick:()=>w({view:k}),children:k==="cycles"?"Cycles":"Steps"},k))}),s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Show",children:["all","llm","tools","failed"].map(k=>s.jsx("button",{type:"button",role:"radio","data-filter":k,"aria-checked":t.only===k,className:`seg_btn ${t.only===k?"active":""}`,onClick:()=>w({only:k}),children:t2[k]},k))}),s.jsx("input",{className:"rs_search",type:"search",value:t.q,onChange:k=>w({q:k.target.value}),placeholder:"Search steps","aria-label":"Search steps",autoComplete:"off",spellCheck:!1}),t.only==="all"?s.jsx(No,{label:"All steps",action:"show-all-steps",hint:"Also list status events, waits, resumes and memory bookkeeping.",checked:t.all_steps,onChange:k=>w({all_steps:k})}):null]}),n.length?null:s.jsx("p",{className:"rs_muted",children:"No steps recorded for this run yet."}),n.length&&!f.length?s.jsx("p",{className:"rs_muted",children:"No step matches."}):null,t.view==="cycles"&&m?FN(f).map(k=>s.jsxs("section",{className:"rs_cycle","data-cycle":k.cycle,children:[s.jsx("h3",{className:"rs_cycle_head",children:k.cycle===0?"Before the first call":`Cycle ${k.cycle}`}),k.steps.map(x)]},k.cycle)):f.map(x)]})}function a2(e){const[t,n]=p.useState(!1),r=e.answer.length>qy,o=t||!r?e.answer:`${e.answer.slice(0,qy).trimEnd()}…`;return s.jsxs("section",{className:"rs_outcome","aria-label":"Run summary",children:[s.jsxs("p",{className:"rs_outcome_facts",children:[s.jsx("span",{className:`rs_status ${oc(e.status)}`,children:e.status||"unknown"}),[e.duration,e.facts].filter(Boolean).join(" · ")]}),e.error?s.jsx("p",{className:"rs_text rs_error",children:e.error}):null,!e.error&&e.answer?s.jsxs("div",{className:"rs_markdown rs_outcome_text",children:[s.jsx(Wi,{text:o}),r?s.jsx("button",{type:"button",className:"rs_link","aria-expanded":t,onClick:()=>n(l=>!l),children:t?"Less":"More"}):null]}):null,s.jsxs("div",{className:"rs_outcome_actions",children:[e.waiting_for_user&&e.on_answer_wait?s.jsx("button",{type:"button",className:"btn primary",onClick:e.on_answer_wait,children:"Answer"}):null,s.jsx("button",{type:"button",className:"btn",onClick:e.on_open_artifacts,title:"This run's artifacts in System",children:"Artifacts"}),e.workspace_root?s.jsx("button",{type:"button",className:"btn",onClick:e.on_reveal_workspace,title:e.workspace_root,children:"Folder"}):null]})]})}const qy=600,l2="@default:",ku="abstractcode.agent.v1";function Hy(e,t){var n;return e?e.kind==="default"?e.interface===ku?"@default":"":((n=t.find(r=>r.bundleId===e.bundle_id&&r.flowId===e.flow_id))==null?void 0:n.value)??"":""}function c2(e,t){return e==="@default"?{kind:"default",interface:ku}:t?{kind:"bundle",bundle_id:t.bundleId,flow_id:t.flowId}:null}function u2(e){return e?e.kind==="default"?`${l2}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function d2(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 f2(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 h2={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 m2(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 _2="#launch/automate";function p2(e){const t=Sx(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 Ep={when:"every",email:Dv,notify_email:!1,email_recipients:lf,amount:"24",unit:"h",once_at:"",context:"independent",growing_max_tokens:String(df),tool_approval:"auto",title:"",start_at:"",count:"",until:""},Vy={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 most recent whole turns are replayed within your token budget; older runs drop out. The newest turn is kept whole even if it exceeds the budget."},Rx=["use_context"],g2="This choice also sets the workflow's Use Context input: the workflow always reads the history the automation gives it.";function Ap(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,growingMaxTokens:Number(e.growing_max_tokens),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 y2(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:[Ut.not_set_up]};const n=f2(t.input_data),r=typeof n.prompt=="string"?n.prompt:"";delete n.prompt;for(const l of Rx)delete n[l];let o;try{o=d2(t.choice,t.bundle_ref_for,n)}catch(l){return{ok:!1,errors:[String((l==null?void 0:l.message)||l)]}}return yp(Ap(e,r,t.email_usable===!0),{target:o,requestId:t.request_id})}function w2(e,t=!1){if(e.when==="email"){if(!t)return"";const l=yp(Ap(e,"preview",!0),{target:{flow_id:"@default",interface:ku},requestId:"preview"});return l.ok?`Runs ${zv(l.body.trigger.config)}.`:""}const n=yp(Ap(e,"preview"),{target:{flow_id:"@default",interface:ku},requestId:"preview"});if(!n.ok)return"";const r=n.body.trigger.config,o=Mv(r);return e.when==="once"?`Runs ${o}.`:`Runs ${o}, first run ${r.start_at?`at ${la(r.start_at)}`:"now"}.`}class v2{constructor(t){Vs(this,"key","");Vs(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 x2(e,t,n){const r=y2(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 na(e){return typeof e=="string"?e:e??null}function b2(e){var t,n,r,o,l,u;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:na(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:na(e==null?void 0:e.created_at),updated_at:na(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:na(e==null?void 0:e.parent_run_id),session_id:na(e==null?void 0:e.session_id),actor_id:na(e==null?void 0:e.actor_id),session_kind:na(e==null?void 0:e.session_kind),automation_id:na(e==null?void 0:e.automation_id),role:na(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 ff(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 Lx(e){const t=ff(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`occurrence #${e.occurrence_index}`:"occurrence":t==="legacy"?"legacy schedule":t||""}function Gy(e){return String((e==null?void 0:e.role)||"").trim()==="controller"}function j2(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 tc(e){return e.legacy===!0||e.capabilities.includes("legacy")}function Ix(e,t=Date.now()){const n=tc(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:og(e.trigger),next_run:e.next_fire_at?`${la(e.next_fire_at)} (${qv(e.next_fire_at,t)})`:e.status==="paused"?"none while paused":"none scheduled",current:Wv(e),state:e.status,last:r?r.excerpt:"",last_status:r?`#${r.index} ${r.status}${o}`:"no runs yet",attention:l?Hv(e):null,legacy:n}}function Ox(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 k2(e,t){const n=om(e,[],t),r=Ox(e),o=t?{enabled:!1,reason:"Working…"}:tc(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 S2(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 N2(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 C2=/^([1-9][0-9]*)([smhd])$/;function E2(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 A2(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={...Ep},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=C2.exec(f);let x=w?Number(w[1]):0,k=w?w[2]:"";k==="s"&&x%60===0&&(x=x/60,k="m"),k==="m"||k==="h"||k==="d"?(c.amount=String(x),c.unit=k):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 m=E2(n.repeat_until);m&&(c.until=m),c.context=n.share_context===!1?"independent":"growing";const _=t&&typeof t.input_data=="object"&&t.input_data&&!Array.isArray(t.input_data)?t.input_data:{},g={};for(const[w,x]of Object.entries(_))w==="workflow_selection"||w.startsWith("_")||(g[w]=x);return{choice:{kind:"bundle",bundle_id:o,flow_id:l},input_data:g,form:c,notes:u}}const $2={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 T2(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 M2(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 L_(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function Ky(e){return e.items.filter(t=>t.status==="archived").length}function wg(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 R2=3e4,Rh=50;function Di(e){return cg(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function I_(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 L2{constructor(t,n,r=[1500,4e3]){Vs(this,"state",{...$2});Vs(this,"listeners",new Set);Vs(this,"list_seq",0);Vs(this,"detail_seq",0);Vs(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:Rh});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 Em(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:Di(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&&tc(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:Rh})]);if(r!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:l??u.summary,definition:u.definition,occurrences:I_([],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:Di(l)})}}async reload_occurrences(t){const n=this.state.detail;if(!n||n.automation_id!==t||tc(n.summary))return;const[r,o]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:Rh})]),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:I_(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:Rh}),r=this.state.detail;if(!r||r.automation_id!==t.automation_id)return;this.set({detail:{...r,occurrences:I_(r.occurrences,n.items),next_cursor:n.next_cursor}})}catch(n){this.set({error:Di(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 Di(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 Di(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:wg(n,l)}),l}catch(l){throw Di(l)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(r){throw Di(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,M2(u.kind,o)),await this.after_change(t)}catch(u){throw Di(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"?Yy(t.title,n==="resume"):`${I2[n]} sent to “${t.title}”.`,confirm_archive_id:""})}catch(o){this.set({error:Di(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(!tc(t))throw new Error("legacy_action on a non-legacy automation");const r=N2(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}”.`:Yy(t.title,n==="legacy_resume")}),await this.refresh()}catch(o){this.set({error:Di(o)})}finally{this.set({busy:!1})}}report_error(t){this.set({error:Di(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 Yy(e,t){return t?`“${e}” is active: it runs on its schedule.`:`“${e}” is paused: scheduled runs are skipped.`}const I2={run_now:"Run now",archive:"Archive"};function O2(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:h2[e.mode]})]})}function P2(e){const t=e.form,n=Em(e.email_status),r=t.when==="email"&&!n?"every":t.when,o=w2(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"})})," ",Ut.trigger_label]})]}),n?null:s.jsx(wp,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),r==="email"?s.jsx(qk,{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:Lk.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) — ",Vy.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"})," — ",Vy.growing]}),t.context==="growing"?s.jsxs("label",{children:["Max growing context (tokens)",s.jsx("input",{type:"number",min:1,step:1,required:!0,value:t.growing_max_tokens,disabled:e.disabled,onChange:l=>e.on_change({growing_max_tokens:l.target.value})})]}):null,s.jsx("p",{className:"help_text muted","data-context-owns":"use_context",children:g2})]}),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:Ut.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"})})," ",Pk,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(wp,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),s.jsx(Hk,{notifyEmail:n&&t.notify_email,onNotifyEmailChange:l=>e.on_change({notify_email:l}),recipients:n?t.email_recipients:lf,onRecipientsChange:l=>e.on_change({email_recipients:l}),disabled:e.disabled||!n,idBase:"automate"})]})]})}function D2(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 F2="abstractobserver";function z2(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 B2(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 U2=new Set(["completed","failed","cancelled"]);function W2(e){var T;const{gateway:t,discussion:n}=e,r=p.useMemo(()=>z2(t),[t]),[o,l]=p.useState(((T=n.session)==null?void 0:T.run_id)||""),[u,c]=p.useState(""),[f,m]=p.useState(!1),[_,g]=p.useState(""),{controller:w,snapshot:x}=T1({transport:r,runId:o,enabled:e.connected,clientId:F2}),k=n.session,j=!!o&&!U2.has(x.status)&&x.status!=="idle",N=C1(x),C=async I=>{var U;const K=I.trim();if(K){m(!0);try{if(k){const J=String(((U=x.run)==null?void 0:U.workflow_id)||""),Y=B2(J),re=await t.start_run(Y.flow_id,{prompt:K},{bundle_id:Y.bundle_id,session_id:k.session_id});l(re)}else{const J=await e.on_fork(n.automation_id,n.occurrence_index,K);l(J.run_id)}c("")}finally{m(!1)}}},E=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(et,{name:"chevronRight",size:13,className:"flip_x"})," ",n.automation_title]}),s.jsxs("span",{className:"discussion_title",children:[s.jsx(et,{name:"chat",size:15})," Discussion — fork at #",n.occurrence_index]}),s.jsx("span",{className:"pane_spacer"}),k?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`btn btn_sm${_==="own"?" active":""}`,"data-action":"discussion-files",onClick:()=>g(_==="own"?"":"own"),title:k.workspace_root,children:[s.jsx(et,{name:"folder",size:14})," Its files"]}),s.jsxs("button",{type:"button",className:`btn btn_sm${_==="mounted"?" active":""}`,"data-action":"automation-files",onClick:()=>g(_==="mounted"?"":"mounted"),title:k.mounted_workspace,children:[s.jsx(et,{name:"folder",size:14})," Automation files"]})]}):null]});return s.jsxs("section",{className:"pane auto_detail auto_discussion","data-discussion-session":(k==null?void 0:k.session_id)||void 0,children:[_&&k?s.jsx(bx,{fetchGateway:t.fetch_gateway,runId:_==="own"?k.run_id:n.automation_id,title:_==="own"?"Discussion files":"Automation files",note:_==="own"?"The discussion's own writable folder.":"Mounted read-only for the discussion's file tools; nothing is written back.",onClose:()=>g(""),refreshKey:x.status}):null,s.jsx(v1,{header:E,messages:x.messages,draft:u,onDraftChange:c,onSend:C,busy:j||f,busyLabel:f?k?"Starting…":"Forking the automation…":N?"Waiting for you":"Working…",onCancel:j?()=>w.cancel():void 0,stopState:x.stop??null,disabled:!e.connected,interaction:tN(N,w,{records:x.records,currentRun:x.run}),placeholder:k?"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 Px(e){return`abstractobserver_list_open_${e}`}function Dx(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function q2(e,t=Dx()){try{return(t==null?void 0:t.getItem(Px(e)))!=="0"}catch{return!0}}function H2(e,t,n=Dx()){try{n==null||n.setItem(Px(e),t?"1":"0")}catch{}}function hf(e){const[t,n]=p.useState(()=>q2(e)),r=p.useCallback(()=>{n(o=>{const l=!o;return H2(e,l),l})},[e]);return[t,r]}function mf(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(et,{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 V2=5e3,G2=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],K2={pause:xo.pause,resume:xo.resume,run_now:xo.run_now,edit:xo.revise,archive:`${xo.archive}…`,discuss:xo.discuss},Y2={pause:zi.pause,resume:zi.resume,run_now:zi.run_now,edit:zi.revise,archive:zi.archive,discuss:zi.discuss},J2={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},X2={legacy_pause:zi.pause,legacy_resume:zi.resume,legacy_run_now:zi.run_now,open_run:"list",recreate:"refresh"};function Z2(e){return s.jsx("span",{className:"auto_state","data-field":"state",children:s.jsx(Xv,{status:e.status})})}function Lh(e){return s.jsxs("span",{className:`auto_fact${e.className?` ${e.className}`:""}`,"data-field":e.field,title:e.label,children:[s.jsx(et,{name:e.icon,size:12}),s.jsx("span",{children:e.children})]})}const Q2={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"},eC="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function Jy(e){const t=e.busy||e.ctl.enabled?null:e.ctl.reason||"Not available now.";return s.jsx(No,{variant:"sm",className:"auto_switch",action:"active",id:`auto-active-${e.summary.automation_id}`,label:xo.active,checked:e.summary.status==="active",unavailableReason:t,busy:e.busy,hint:e.hint,onChange:e.onChange})}function tC(e){const t=e.summary,n=Ix(t),r=e.state.selected_id===t.automation_id,o=e.state.busy,l=(f,m,_,g,w,x,k,j)=>s.jsxs("button",{type:"button",className:`btn btn_sm auto_action${k?" auto_action_icon":""}${w?` ${w}`:""}`,"data-action":f,disabled:!_.enabled,title:[k?m:null,_.enabled?null:_.reason,j].filter(Boolean).join(`
|
|
76
|
+
`)||void 0,"aria-label":k?m:void 0,"aria-description":j,onClick:g,children:[x?s.jsx(et,{name:x,size:13}):null,k?null:s.jsx("span",{children:m})]},f);let u;if(n.legacy){const f=S2(t,o),m=t.status==="paused"?"legacy_resume":"legacy_pause",_=["legacy_run_now","open_run","recreate"];u=[s.jsx(Jy,{summary:t,busy:o,ctl:f[m],hint:eC,onChange:()=>e.h.on_legacy_action(t,m)},"active"),..._.map(g=>l(g,Q2[g],f[g],()=>e.h.on_legacy_action(t,g),void 0,X2[g]))]}else{const f=k2(t,o),m=t.status==="active"?"pause":"resume",_=["run_now","edit","discuss","archive"];u=[s.jsx(Jy,{summary:t,busy:o,ctl:f.active,hint:lm("active",t),onChange:()=>e.h.on_row_action(t,m)},"active"),..._.map(g=>l(g,K2[g],f[g],()=>e.h.on_row_action(t,g),g==="archive"?"danger auto_action_end":void 0,Y2[g],g==="archive",lm(J2[g],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(Z2,{status:n.state}),n.attention?s.jsxs("span",{className:"chip warn auto_row_attention","data-field":"attention",children:[s.jsx(et,{name:"warning",size:12})," ",n.attention]}):null]}),s.jsxs("span",{className:"auto_row_facts",children:[s.jsx(Lh,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?s.jsx(Lh,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,s.jsxs(Lh,{icon:"clock",field:"next",label:"Next run",children:["next: ",n.next_run]}),s.jsx(Lh,{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:jx(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(et,{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(et,{name:"x",size:13}),s.jsx("span",{children:"Keep it"})]})]}):null]})}function nC(e){const t=e.state,n=e.list?e.list.open:!0,r=t.error??t.list_error,o=r?am(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(mf,{open:n,on_toggle:e.list.on_toggle,controls:"auto_list_body",title:"Automations",count:L_(t).length}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_title",children:"Automations"}),s.jsx("span",{className:"pane_count",children:L_(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:G2.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(et,{name:t.loading?"loader":"refresh",size:14})}),s.jsxs("a",{className:`btn btn_sm auto_new${e.available.available?"":" disabled"}`,"data-action":"new",href:_2,"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(et,{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(et,{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(et,{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(et,{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(et,{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,Ky(t)>0&&t.status_filter!=="archived"?s.jsx("div",{className:"auto_show_archived",children:s.jsx(No,{variant:"sm",action:"show-archived",label:`Archived (${Ky(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:L_(t).map(l=>s.jsx(tC,{summary:l,state:t,h:e.h},l.automation_id))})]})]})}function sC(e,t,n){const r=e.state,o=r.detail;if(!o||tc(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 m=await e.discuss(l,u,c,f==null?void 0:f.request_id);return t.on_open_session(m,wg(u,m),u),m},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 rC(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 (",vp.toLowerCase(),")."]})});if(tc(t.summary)){const r=Ix(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=sC(e.ctl,e.host,e.edit);return s.jsxs("section",{className:"pane auto_detail",children:[e.browser??null,n?s.jsx(eN,{...n}):null]})}function iC(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=Ox(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function oC(e){const t=e.ctl,[n,r]=hf("automations"),[o,l]=p.useState(null),u=C=>l(E=>({...C,opened:((E==null?void 0:E.opened)||0)+1})),[c,f]=p.useState(""),[m,_]=p.useState("");p.useSyncExternalStore(C=>t.subscribe(C),()=>t.state,()=>t.state);const[g,w]=p.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");p.useEffect(()=>{const C=()=>w(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",C),()=>document.removeEventListener("visibilitychange",C)},[]),p.useEffect(()=>{if(!e.active||!g||!e.available.available)return;t.refresh();const C=window.setInterval(()=>void t.refresh(),R2);return()=>window.clearInterval(C)},[t,e.active,g,e.available.available]);const x=t.state.detail,k=t.state.notice;p.useEffect(()=>{if(!k)return;const C=window.setTimeout(()=>t.dismiss_notice(),V2);return()=>window.clearTimeout(C)},[t,k]);const j={...e.host,on_open_workspace:C=>f(E=>E===C?"":C),fetch_gateway:e.gateway.fetch_gateway,on_open_session:(C,E,T)=>{e.host.on_open_session(C,E,T),x&&u({automation_id:x.automation_id,automation_title:x.summary.title,occurrence_index:T,session:C})}},N={...e.h,on_select:C=>{l(null),f(""),C!==m&&_(""),e.h.on_select(C)},on_dismiss_notice:()=>t.dismiss_notice(),on_dismiss_error:()=>t.dismiss_error(),on_row_action:(C,E)=>{const T=iC(C,E);T.kind==="forward"?e.h.on_row_action(C,E):T.kind==="edit"?(l(null),f(""),_(C.automation_id),e.h.on_select(C.automation_id)):T.kind==="discuss"&&(e.h.on_select(C.automation_id),u({automation_id:C.automation_id,automation_title:C.title,occurrence_index:T.index}))}};return s.jsxs("div",{className:`page auto_page${n?"":" list_collapsed"}`,children:[s.jsx(nC,{state:t.state,available:e.available,h:N,list:{open:n,on_toggle:r}}),o?s.jsx(W2,{gateway:e.gateway,discussion:o,connected:e.active,on_fork:async(C,E,T)=>{const I=await t.discuss(C,E,T);return e.host.on_open_session(I,wg(E,I),E),l(K=>K&&{...K,session:I}),I},on_close:()=>l(null)},o.opened):s.jsx(rC,{ctl:t,host:j,h:N,edit:{open:!!x&&m===x.automation_id,on_change:C=>_(C&&x?x.automation_id:"")},browser:c?s.jsx(bx,{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 aC(e){return s.jsx(No,{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 lC(e){return s.jsx("div",{className:`settings_choice ${e.checked?"on":""}`,children:s.jsx(No,{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 cC="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function uC(e){return s.jsx(No,{variant:"sm",action:"schedule-active",className:"observe_schedule_switch",label:"Active",hint:cC,checked:e.active,unavailableReason:e.unavailableReason,busy:e.busy,onChange:e.onChange})}function dC(e){return s.jsx(No,{variant:"sm",action:"mindmap-live",label:"Live",hint:"Refresh the map as new memory arrives.",checked:e.checked,onChange:e.onChange})}function fC(e){return s.jsx(No,{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 hC(){const e="0.6.1".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 mC(){return Wj("abstractobserver",hC())}async function _C(e){let t;try{t=await e.gateway_about()}catch(n){return my(null,n instanceof Error?n.message||n.name:String(n))}return my(t)}class dm{constructor(t){this._maxSize=dm._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=dm._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 pC(e){try{return new URL(String(e)),!0}catch{return!1}}function gC({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return pC(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function yC({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function wC({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function vC(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 xC({baseUrl:e,endpoint:t,token:n,getToken:r,signal:o,fetchImpl:l}={}){const u=gC({baseUrl:e,endpoint:t}),c=await yC({token:n,getToken:r}),f=l||globalThis.fetch;if(typeof f!="function")return{ok:!1,status:0,error:"fetch_unavailable",payload:null};let m;try{m=await f(u,{method:"GET",headers:{Accept:"application/json",...wC({token:c})},signal:o})}catch(g){return{ok:!1,status:0,error:"network_error",detail:g instanceof Error?g.message:String(g),payload:null}}let _=null;try{_=await m.json()}catch{_=null}return{ok:m.ok,status:m.status,error:m.ok?null:"http_error",payload:_}}const Vd=Object.freeze({tickMs:1500,historySize:20,endpoint:"api/gateway/host/metrics/gpu",baseUrl:"",mode:"full"});function bC(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Xy(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function Zy(e,t){const n=Number(e);return Number.isFinite(n)?Math.floor(n):t}function O_(e,t=1){const n=Xy(Number(e)/100,0,1),r=Math.round(140-140*n),o=Xy(Number(t),0,1);return o>=1?`hsl(${r} 85% 55%)`:`hsl(${r} 85% 55% / ${o})`}function Qy(e){const t={...Vd,...e||{}};return t.tickMs=Math.max(250,Zy(t.tickMs,Vd.tickMs)),t.historySize=Math.max(1,Math.min(200,Zy(t.historySize,Vd.historySize))),t.endpoint=String(t.endpoint||Vd.endpoint),t.baseUrl=String(t.baseUrl||""),t.mode=String(t.mode||Vd.mode).trim().toLowerCase(),t.mode!=="icon"&&(t.mode="full"),t}function jC(){return`
|
|
77
|
+
: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}
|
|
78
|
+
.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)}
|
|
79
|
+
.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))}
|
|
80
|
+
.wrap.icon .top{display:none}
|
|
81
|
+
.wrap.icon .bars{height:var(--monitor-gpu-bars-height,18px)}
|
|
82
|
+
.top{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
|
|
83
|
+
.label{font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.9}
|
|
84
|
+
.value{font-variant-numeric:tabular-nums;font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.95}
|
|
85
|
+
.bars{display:flex;align-items:flex-end;gap:2px;height:var(--monitor-gpu-bars-height,34px);overflow:hidden}
|
|
86
|
+
.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}
|
|
87
|
+
.bar.missing{background:var(--monitor-gpu-bar-missing,#62708a);opacity:.35}
|
|
88
|
+
.bar.error{background:var(--monitor-gpu-bar-error,#ff6b6b);opacity:.7}
|
|
89
|
+
.muted{opacity:.6}
|
|
90
|
+
`}class kC{constructor(t,n={}){if(!t||typeof t!="object")throw new TypeError("target element is required");this._target=t,this._opts=Qy(n),this._buffer=new dm(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=jC();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=Qy({...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",O_(c,.95)),n.style.setProperty("--monitor-gpu-accent-glow",O_(c,.35))));const f=Array.from(o.children),m=Math.max(0,f.length-l.length),_=Math.max(2,o&&typeof o.clientHeight=="number"&&o.clientHeight>0?o.clientHeight:34);for(let g=0;g<f.length;g+=1){const w=f[g],x=g-m,k=x>=0?l[x]:null,j=Number.isFinite(k)?k:null,N=j==null?0:bC(j/100),C=Math.max(2,Math.min(_,Math.round(N*_)));w.style.height=`${C}px`,w.style.background=j==null?"":O_(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 xC({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=vC(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(),m=typeof this._getToken=="function";if(!r&&(!!f||m))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 SC(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 kC(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 Su(e){return String(e||"").trim().toLowerCase()}function Mm(e){return`${(e==null?void 0:e.filename)||""} ${(e==null?void 0:e.source_path)||""}`.trim().toLowerCase()}function cf(e,t){return t.some(n=>e.endsWith(n))}function NC(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 CC(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 EC(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 Fx(e,t){var u,c,f,m,_;const n=Su(e==null?void 0:e.content_type),r=Mm(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,(m=e==null?void 0:e.tags)==null?void 0:m.kind,(_=e==null?void 0:e.tags)==null?void 0:_.type].map(g=>String(g||"").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")||cf(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,`
|
|
91
|
+
`).replace(/\r/g,`
|
|
92
|
+
`).split(`
|
|
93
|
+
`);return zx(l)}function AC(e){const n=String(e||"").replace(/\r\n/g,`
|
|
94
|
+
`).replace(/\r/g,`
|
|
95
|
+
`).split(`
|
|
96
|
+
`),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(`
|
|
97
|
+
`).trim();return!o.length&&!l?null:{metadata:o,body:l}}function $C(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 TC(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:zx(e)}function zx(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 MC(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,`
|
|
98
|
+
`).replace(/\r/g,`
|
|
99
|
+
`).split(`
|
|
100
|
+
`).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 RC(e,t){var m;const n=String(t||""),r=NC(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,`
|
|
101
|
+
`).replace(/\r/g,`
|
|
102
|
+
`).split(`
|
|
103
|
+
`),l=o.map(_=>_.trim()).filter(Boolean);if(l.length<2||MC(n)||$C(o)||TC(o))return!1;const u=((m=n.match(/[A-Za-z][A-Za-z'-]+/g))==null?void 0:m.length)||0,c=o.filter(_=>!_.trim()).length,f=l.filter(_=>/[A-Za-z]{3,}/.test(_)&&_.length>=12).length;return u>=24&&f>=2&&(c>=1||l[0].length<=140)}function uf(e){const t=Su(e==null?void 0:e.modality),n=Su(e==null?void 0:e.content_type),r=Mm(e),o=CC(e);return t==="image"||n.startsWith("image/")||cf(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)||cf(r,[".wav",".mp3",".m4a",".aac",".flac",".ogg",".opus",".aiff",".mid",".midi"])?"audio":t==="video"||n.startsWith("video/")||cf(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")||Fx(e,"")?"text":"binary"}function fm(e,t){const n=Su(e==null?void 0:e.content_type),r=Mm(e),o=String(t||"").trim();return n.includes("html")||r.endsWith(".html")||r.endsWith(".htm")||EC(t)?"html":Fx(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("["))&&$m(o)!==null?"json":RC(e,t)?"markdown":"text"}function vg(e,t=""){const n=uf(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=Su(e==null?void 0:e.modality),o=Su(e==null?void 0:e.content_type),l=Mm(e);return r==="document"||o.includes("pdf")||cf(l,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return fm(e,t)}function P_(e){var m,_;const t=String(e||"").replace(/\r\n/g,`
|
|
104
|
+
`).replace(/\r/g,`
|
|
105
|
+
`).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=g=>" ".repeat(Math.max(0,g)),f=(g,w)=>{const x=g.match(/^(<\/?|<!)([^\s/>]+)([\s\S]*?)(\/?>)$/);if(!x||g.length<=120||g.startsWith("</")||g.startsWith("<!"))return[`${c(w)}${g.trim()}`];const k=(x[3]||"").trim();if(!k)return[`${c(w)}${g.trim()}`];const j=k.match(/[^\s="'<>`]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>`]+))?/g)||[k];return[`${c(w)}${x[1]}${x[2]}`,...j.map(N=>`${c(w+1)}${N.trim()}`),`${c(w)}${x[4]}`]};for(const g of r){const w=String(g||"");if(!w.trim())continue;const x=w.trim().toLowerCase();if(x.startsWith("</")){const j=((m=x.match(/^<\/\s*([a-z0-9:-]+)/))==null?void 0:m[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=((_=x.match(/^<\s*([a-z0-9:-]+)/))==null?void 0:_[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(`
|
|
106
|
+
`).map(N=>`${c(l)}${N.trimEnd()}`));continue}const k=w.replace(/\s+/g," ").trim();k&&o.push(`${c(l)}${k}`)}return o.join(`
|
|
107
|
+
`)}const LC=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function xg(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 Bx(...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 $p(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>$p(t)).filter(Boolean).join(`
|
|
108
|
+
`).trim();if(typeof e=="object"){const t=e.text??e.content??e.message??e.value;if(t!==e){const n=$p(t);if(n)return n}}return""}function Ux(e){const t=xg($p(e));return{text:t.text,runtime_metadata:t.metadata}}function IC(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=xg(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 m=Ux((c==null?void 0:c.content)??(c==null?void 0:c.text)??c);if(m.text)return{text:m.text,runtime_metadata:Bx(m.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 OC(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",m=Ux((c==null?void 0:c.content)??(c==null?void 0:c.text)??(c==null?void 0:c.message)??c),_=m.text;if(!_)continue;const g=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=Bx(m.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:_,ts:g,runtime_metadata:w})}return o.slice(Math.max(0,o.length-Math.max(1,t)))}function Wx(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function PC(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 qx="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function Hx(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 bg(e,t){const n=String((e==null?void 0:e.reason)||"").trim().toLowerCase(),r=PC(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 Vx(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 Gx(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),r=xg(n),o=IC(t);return r.text&&!Wx(r.text)?{text:r.text,runtime_metadata:r.metadata}:o.text?o:{text:r.text||n,runtime_metadata:r.metadata}}function DC(e,t){return Gx(e,t).text}function FC(e,t){return e||String(t||"").trim()||{}}function Bi(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 ac(e){const t=String(e.status||"unknown").trim()||"unknown";return s.jsx("span",{className:`run_status_pill ${oc(t)}`,children:t})}function zC(e){var l;const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(So(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?bg(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 hm(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?kt(t,{max_chars:220,max_lines:2}):kt(cr(t,400),{max_chars:220,max_lines:2}):""}function BC(e){const t=zC(e);if(t)return t;const n=hm(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":So(o)?"Terminal":"No current activity reported"}function Kx(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 ew(e){const t=Kx(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=_n(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=_n(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 UC(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 WC(e,t){if(!e||typeof e!="object")return null;const n=UC(e),r=Kx(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=_n(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[I,K]of Object.entries(c)){const U=String(I||"").trim();U&&(f[U]=String(K??""))}const m=_n(n.filename,e.filename,r.filename,o.filename,f.filename,f.name,e.name,r.name),_=_n(n.source_path,e.source_path,r.source_path,o.source_path,e.path,r.path,f.path,f.source_path,f.file_path),g=_n(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=_n(n.render_kind,l.render_kind,e.render_kind,f.render_kind),x=_n(n.semantic_kind,l.semantic_kind,e.semantic_kind,f.semantic_kind,f.artifact_type),k=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:{},N=n.provenance&&typeof n.provenance=="object"?n.provenance:e.provenance&&typeof e.provenance=="object"?e.provenance:l.provenance&&typeof l.provenance=="object"?l.provenance:{},C=n.generation&&typeof n.generation=="object"?n.generation:e.generation&&typeof e.generation=="object"?e.generation:l.generation&&typeof l.generation=="object"?l.generation:{},E=n.media&&typeof n.media=="object"?n.media:e.media&&typeof e.media=="object"?e.media:l.media&&typeof l.media=="object"?l.media:{},T=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:_n(n.run_id,e.run_id,r.run_id,o.run_id,f.run_id,N.run_id),content_type:g,modality:_n(n.modality,e.modality,l.modality,f.modality)||ew({...e,ref:r,metadata:o,tags:f}),semantic_kind:x||ew({...e,ref:r,metadata:o,tags:f}),render_kind:w||vg({content_type:g,filename:m,source_path:_,modality:_n(n.modality,e.modality,f.modality),tags:f}),task:_n(n.task,l.task,e.task,f.task,f.provider_task),classification_source:_n(n.classification_source,l.classification_source,e.classification_source),session_id:_n(n.session_id,l.session_id,e.session_id,f.session_id),workflow_id:_n(n.workflow_id,l.workflow_id,e.workflow_id,f.workflow_id,f.workflow),node_id:_n(n.node_id,l.node_id,e.node_id,f.node_id,f.node),step_id:_n(n.step_id,l.step_id,e.step_id,f.step_id),effect_id:_n(n.effect_id,l.effect_id,e.effect_id,f.effect_id,f.effect_idempotency_key),turn_id:_n(n.turn_id,l.turn_id,e.turn_id,f.turn_id,f.turn),ledger_cursor:_n(n.ledger_cursor,l.ledger_cursor,e.ledger_cursor,f.ledger_cursor,f.step_cursor),parent_run_id:_n(n.parent_run_id,l.parent_run_id,e.parent_run_id,f.parent_run_id),actor_id:_n(n.actor_id,l.actor_id,e.actor_id,f.actor_id),title:_n(n.title,e.title,f.title,f.label,f.name),created_at:_n(n.created_at,e.created_at,r.created_at,o.created_at,f.created_at),size_bytes:XN(n.size_bytes,e.size_bytes,r.size_bytes,o.size_bytes,f.size_bytes),filename:m,source_path:_,sha256:_n(n.sha256,e.sha256,r.sha256,o.sha256,f.sha256),tags:f,producer:j,provenance:N,generation:C,media:E,source_refs:Array.isArray(n.source_refs)?n.source_refs:Array.isArray(e.source_refs)?e.source_refs:[],access:k,links:T,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(_n(n.classification_source,l.classification_source,e.classification_source))),descriptor:l,source:t,raw:e}}function Tp(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||Qt(e.artifact_id,16)}function qC(e,t){if(t==="type")return gu(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return Mp(e);if(t==="node")return pu(e)||"(node unknown)";if(t==="workflow")return jg(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 _f(e)||e.source||"artifact";const n=qn(e.created_at);return n===null?"(unknown time)":new Date(n).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function jg(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 pu(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 Mp(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=pu(e),o=qn(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?Qt(String(e.run_id),10):"unknown run";return r?`${u} · ${r} · ${l}`:`${u} · ${l}`}function tw(e){if(!e)return"provenance unavailable";const t=[],n=jg(e),r=pu(e),o=_f(e),l=Yx(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 Yl(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 gu(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 HC(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 GC(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 nw(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 KC(e){const t=bu(e.created_at),n=ec(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function sw(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=bu(n);return r==="—"?"—":r}function rw(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=_f(e),l=gu(e);return o?`${l} ${o}`:`${l} artifact`}function _f(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 Yx(e){var r,o,l,u,c,f,m,_;if(!e)return"";const t=_n((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=_n((c=e.producer)==null?void 0:c.model,(f=e.producer)==null?void 0:f.model_id,(m=e.provenance)==null?void 0:m.model,(_=e.generation)==null?void 0:_.model);return t&&n?`${t} / ${n}`:t||n}function YC(e){var t,n,r,o;return e?_n((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 iw(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 ow(e){return e.source_path||e.filename||""}function mm(e,t,n){const r=e.run_id&&t[e.run_id]||null;if(!r)return e;const o=Bi(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 Rp(e,t,n,r=""){const o=mm(e,t,n),l=vg(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]||gu(o)}function ra(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 Ih(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 Tf(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 JC(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 Jx(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),r=JC(e),o=ra(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 ru(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):cr(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:cr(e,320),duration:-1}}function Xx(e){var u,c,f,m,_,g,w,x,k;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 N=j,C=[N.response,N.answer,N.message,N.text,N.content];for(const E of C){const T=r(E);if(T)return T}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((_=(m=e==null?void 0:e.effect)==null?void 0:m.payload)==null?void 0:_.message)||r((w=(g=e==null?void 0:e.effect)==null?void 0:g.payload)==null?void 0:w.text)||r((k=(x=e==null?void 0:e.effect)==null?void 0:x.payload)==null?void 0:k.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 Qh(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 XC(e){return!!(e&&String(e.status||"")==="waiting")}function ZC(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:{},m=(f==null?void 0:f.usage)||(f==null?void 0:f.token_usage)||{},_=typeof c.prompt=="string"?c.prompt:Array.isArray(c.messages)?cr(c.messages,1800):"",g=typeof f.content=="string"?f.content:typeof f.response=="string"?f.response:typeof l.result=="string"?String(l.result):"",w=qn(l.started_at),x=qn(l.ended_at),k=Number(m.prompt_tokens??m.input_tokens??0)||0,j=Number(m.completion_tokens??m.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:kt(_,{max_chars:1200,max_lines:10}),response_preview:kt(g,{max_chars:1200,max_lines:10}),missing_response:!String(g||"").trim(),tokens:{prompt:k,completion:j,total:Number(m.total_tokens??k+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?cr(l.error,500):"",raw:l})}return t.sort((o,l)=>(qn(l.ts)??0)-(qn(o.ts)??0))}function aw(e){const t=e.size||18,n=uf(e.artifact),r=vg(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 QC=2,eE=Number.MAX_SAFE_INTEGER;function tE(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 nE(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:P_(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(m=>({name:m.name,value:m.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:P_(t)||t}]}catch{return[{kind:"text",text:P_(t)||t}]}}function D_(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 Zx(e){const t=e.node,n=e.depth*14,r=e.depth<e.collapseAfterDepth,[o,l]=p.useState(r);if(p.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(D_,{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(D_,{tag:t.tag,attrs:t.attrs}),!o&&u?s.jsxs("span",{className:"html-tree__summary_text",children:[" ",tE(u.text)]}):null]}),o?s.jsxs("div",{className:"html-tree__children",children:[t.children.map((c,f)=>s.jsx(Zx,{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(D_,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function sE(e){const t=p.useMemo(()=>nE(e.text),[e.text]),[n,r]=p.useState({mode:"folded",version:0}),o=n.mode==="unfolded"?eE:QC;p.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(Zx,{node:u,depth:0,collapseAfterDepth:o,expansionMode:n.mode,expansionVersion:n.version},`root:${c}`))})]})}function rE(e){var r;const t=AC(e.text);if(!t)return s.jsx("div",{className:`${e.className} structured markdown_preview`,children:s.jsx(Wi,{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(Wi,{text:t.body||e.text})]})}function Qx(e){const t=String(e.text||""),n=fm(e.artifact,t);if(n==="json"){const r=$m(t);if(r!==null)return s.jsx("div",{className:`${e.className} structured`,children:s.jsx(Is,{value:r,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?s.jsx(rE,{text:t,className:e.className}):n==="html"?s.jsx(sE,{text:t,className:e.className}):s.jsx("pre",{className:`mono ${e.className}`,children:t})}function iE(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:Tp(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(Qx,{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 eb(e){const t=kg(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function lw(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 oE(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 Au(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(So(t)||t!=="waiting")return"none";const n=kg(e),r=eb(e);return Tf(n).length?"tool_approval":r==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":r==="subworkflow"?"subworkflow":r==="event"?lw(n)?"user_response":"external_event":r==="user"||lw(n)?"user_response":"unknown_wait"}function tb(e){const t=kg(e),n=Tf(t),r=Au(e);return r==="tool_approval"?`Tool approval: ${oE(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 aE(e){const t=Au(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.":So(n)?"Open the ledger and artifacts for the final outcome.":"Open the run to inspect current activity."}function cw(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 lE(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label??"",o=String(e.status||"unknown").trim().toLowerCase()||"unknown",l=Au(e),u=So(o),c=gg(e,n),f=qn(e.updated_at||e.created_at)??0,m=o==="running"&&c>=14400*1e3,_=tb(e)||cw(e)||(e.current_node?`Current node: ${e.current_node}`:o==="running"?"Running":u?"Terminal":"No current activity reported");let g="all";l==="tool_approval"?g="tool_approval":l==="user_response"?g="user_wait":l==="scheduled"?g="scheduled":l==="subworkflow"||l==="external_event"?g="subflows":o==="failed"?g="failed":o==="running"?g="running":u&&(g="finished");const w=l==="tool_approval"?0:l==="user_response"?1:l==="unknown_wait"?2:o==="failed"?3:m?4:o==="running"?5:l!=="none"?6:u?8:7,x=l==="tool_approval"||l==="user_response",k=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,eb(e),_,cw(e)].join(" ").toLowerCase();return{run:e,run_id:String(e.run_id||"").trim(),status:o,wait_kind:l,queue:g,attention_rank:w,reason:_,expected_action:aE(e),action_label:k,search_text:j,is_terminal:u,needs_user_action:x,is_stale:m,duration_ms:c,updated_ms:f}}function cE(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label_by_id??{};return e.map(o=>lE(o,{now_ms:n,workflow_label:r[String(o.workflow_id||"")]||String(o.workflow_id||"")}))}function uE(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 dE(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 fE(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 hE(e){const[t,n]=p.useState("attention"),[r,o]=hf("system_queues"),[l,u]=hf("system_runs"),[c,f]=p.useState(""),[m,_]=p.useState("attention"),[g,w]=p.useState(""),x=p.useMemo(()=>{const A={};for(const te of e.artifacts){const P=String(te.run_id||"").trim();P&&(A[P]=(A[P]||0)+1)}return A},[e.artifacts]),k=p.useMemo(()=>cE(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),j=p.useMemo(()=>uE(k),[k]),N=p.useMemo(()=>{const A=dE(k,{queue:t,query:c});return fE(A,m)},[k,t,c,m]),C=N.find(A=>String(A.run_id||"")===g)||N.find(A=>String(A.run_id||"")===e.selected_run_id)||N[0]||null,E=(C==null?void 0:C.run)||null,T=String((E==null?void 0:E.run_id)||"").trim(),I=String((E==null?void 0:E.session_id)||"").trim(),K=p.useMemo(()=>I?new Set(e.runs.filter(A=>String(A.session_id||"").trim()===I).map(A=>String(A.run_id||"").trim()).filter(Boolean)):new Set,[e.runs,I]),U=I?K.size:0,J=p.useMemo(()=>I?e.artifacts.filter(A=>String(A.session_id||"").trim()===I||K.has(String(A.run_id||"").trim())).length:0,[e.artifacts,I,K]),Y=E!=null&&E.waiting&&typeof E.waiting=="object"?E.waiting:null,re=Y?Tf(Y):[],ce=(C==null?void 0:C.reason)||(Y?bg(Y,re):""),fe=(C==null?void 0:C.expected_action)||(Y?Vx(Y,re):""),W=Y?DC(Y,null):"",O=T&&x[T]||0,$=So(E==null?void 0:E.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(mf,{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(et,{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(A=>s.jsxs("button",{className:`runtime_ops_filter ${t===A.key?"selected":""}`,"aria-pressed":t===A.key,onClick:()=>n(A.key),children:[s.jsx("span",{children:A.label}),s.jsx("strong",{children:A.count.toLocaleString()})]},A.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(mf,{open:l,on_toggle:u,controls:"runtime_ops_runs",title:"Runs",count:N.length.toLocaleString()}),s.jsx("div",{className:"pane_spacer"}),s.jsx("input",{value:c,onChange:A=>f(A.target.value),placeholder:"Search workflow, run, node, status, error"}),s.jsxs("select",{className:"seg_select",value:m,onChange:A=>_(A.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:[N.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."}),N.map(A=>{const te=A.run,P=String(te.run_id||"").trim(),F=x[P]||0;return s.jsxs("div",{className:`raised runtime_ops_row ${P===T?"selected":""}`,"aria-current":P===T?"true":void 0,tabIndex:0,onClick:()=>{w(P),e.on_select_run(P)},onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),w(P),e.on_select_run(P))},children:[s.jsxs("div",{className:"runtime_ops_row_top",children:[s.jsx("strong",{className:"runtime_ops_row_name",children:Bi(te,e.workflow_label_by_id)}),A.is_stale?s.jsx("span",{className:"chip warn",children:"stale"}):null,s.jsx(ac,{status:te.status})]}),s.jsxs("div",{className:"runtime_ops_row_sub",children:[s.jsx("span",{className:"mono",children:Qt(P,18)}),s.jsx("span",{children:ec(te.updated_at||te.created_at)}),s.jsx("span",{children:ic(te)}),s.jsx("span",{className:"runtime_ops_row_reason",title:A.reason,children:A.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:[A.needs_user_action?s.jsx("button",{className:"btn primary",onClick:G=>{G.stopPropagation(),e.on_open_run(P)},children:A.action_label}):s.jsx("button",{className:"btn",onClick:G=>{G.stopPropagation(),e.on_open_run(P)},children:"Open"}),s.jsx("button",{className:"btn",onClick:G=>{G.stopPropagation(),e.on_open_ledger(P)},children:"Ledger"}),s.jsx("button",{className:"btn",onClick:G=>{G.stopPropagation(),e.on_select_run(P),e.on_open_logs()},children:"Logs"}),s.jsx("button",{className:"btn",onClick:G=>{G.stopPropagation(),e.on_filter_artifacts(P)},children:"Artifacts"})]})]})]},P)})]})]}),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"}),E?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pane_spacer"}),s.jsx(ac,{status:E.status})]}):null]}),s.jsx("div",{className:"pane_body scroll runtime_ops_inspector_body",children:E?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_ops_inspector_head",children:[s.jsx("h3",{children:Bi(E,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Qt(T,28)})]}),s.jsxs("div",{className:"runtime_ops_decision",children:[s.jsx("strong",{children:(C==null?void 0:C.reason)||BC(E)}),s.jsx("span",{children:(C==null?void 0:C.expected_action)||(String(E.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:bu(fu(E))})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:ic(E)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last event"}),s.jsx("strong",{children:bu(E.updated_at||E.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:E.session_id?Qt(String(E.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:E.current_node||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Visible artifacts"}),s.jsx("strong",{children:O.toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:Number(E.llm_calls||0).toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Tokens"}),s.jsx("strong",{children:Number(E.tokens_total||0).toLocaleString()})]})]}),I?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:Qt(I,30)})]}),s.jsxs("div",{className:"runtime_ops_session_facts",children:[s.jsxs("span",{children:[U.toLocaleString()," loaded run",U===1?"":"s"]}),s.jsxs("span",{children:[J.toLocaleString()," visible artifact",J===1?"":"s"]})]}),s.jsxs("div",{className:"runtime_detail_actions compact",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_filter_session_artifacts(I),children:"Open session artifacts"}),s.jsx("button",{className:"btn",onClick:()=>void rc(I),children:"Copy session id"})]})]}):null,Y?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:ce})]}),s.jsx("p",{children:fe}),W?s.jsxs("div",{className:"runtime_ops_wait_request",children:[s.jsx("span",{children:"Request"}),s.jsx(Wi,{text:W})]}):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((A,te)=>s.jsxs(ve.Fragment,{children:[s.jsx("span",{className:"chip mono warn",children:String((A==null?void 0:A.name)||"tool")}),Hx(A).map(P=>s.jsxs("span",{className:"chip muted",title:qx,children:[P,"~"]},`${te}:${P}`))]},`${String((A==null?void 0:A.name)||"tool")}:${te}`))}):null,s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"muted",children:"Raw wait payload"}),s.jsx(Is,{value:Y,collapseAfterDepth:3,showCopy:!0})]})]}):null,hm(E)?s.jsx("div",{className:"warn_callout",children:hm(E)}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(T),children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(T),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>e.on_filter_artifacts(T),children:"Open artifacts"}),s.jsx("button",{className:"btn",onClick:e.on_open_logs,children:"Open logs"}),s.jsx("button",{className:"btn",onClick:()=>void rc(T),children:"Copy run id"})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run to inspect why it is active or blocked."})})]})]})}function mE(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=p.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)),m=Math.min(Math.max(0,Number(e.artifact_page||0)),f-1),_=l?m*c+1:0,g=Math.min(l,m*c+e.artifacts.length),w=p.useMemo(()=>{const O={},$=e.artifact_type_facets&&Object.keys(e.artifact_type_facets).length?e.artifact_type_facets:e.artifact_facets,z=($==null?void 0:$.semantic_kind)||{},A=($==null?void 0:$.render_kind)||{};for(const te of n)O[te]=Number(z[te]||A[te]||0);return O.audio=Number(z.audio||0),O.other=Number(z.other||0)+Number(z.artifact||0)+Number(z.binary||0)+Number(z["(none)"]||0),O},[e.artifact_facets,e.artifact_type_facets]),x=O=>{const $=new Set(o);$.has(O)?$.delete(O):$.add(O),e.on_type_filters_change(Array.from($.values()))},k=p.useMemo(()=>{const O={waiting:[],running:[],failed:[],cancelled:[],completed:[],other:[]};for(const $ of e.runs){const z=String($.status||"").trim().toLowerCase();z==="waiting"?O.waiting.push($):z==="running"?O.running.push($):z==="failed"?O.failed.push($):z==="cancelled"?O.cancelled.push($):z==="completed"?O.completed.push($):O.other.push($)}return O},[e.runs]),j=t!=null&&t.run_id&&e.run_by_id[t.run_id]||null,N=e.artifact_run_filter?Bi(e.run_by_id[e.artifact_run_filter],e.workflow_label_by_id):"",C=p.useMemo(()=>{var z;const O=new Set,$=((z=e.artifact_facets)==null?void 0:z.run_id)||{};for(const A of Object.keys($))A&&A!=="(none)"&&O.add(A);for(const A of e.artifacts)A.run_id&&O.add(A.run_id);for(const A of e.active_runs)A.run_id&&O.add(String(A.run_id));return Array.from(O).map(A=>e.run_by_id[A]||{run_id:A,workflow_id:null,status:"",created_at:null,updated_at:null}).sort((A,te)=>{const P=ju(A.status)?0:1,F=ju(te.status)?0:1;if(P!==F)return P-F;const G=qn(A.updated_at||A.created_at)??0;return(qn(te.updated_at||te.created_at)??0)-G}).slice(0,160)},[e.artifacts,e.active_runs,e.run_by_id,e.artifact_facets]),E=O=>{e.on_artifact_run_filter_change(O),e.on_session_filter_change(""),e.on_scope_change(O?"run":"all")},T=O=>e.gateway_connected?Math.max(0,Number(O||0)).toLocaleString():"—",I=e.selected_run_id&&e.run_by_id[e.selected_run_id]||null,K=p.useMemo(()=>{const O=e.runtime_log_query.trim().toLowerCase(),$=e.runtime_ledger_log_items||[];return O?$.filter(z=>{var P,F;const A=z.record||{};return[z.cursor,A.run_id,A.node_id,A.status,(P=A.effect)==null?void 0:P.type,A.started_at,A.ended_at,cr(((F=A.effect)==null?void 0:F.payload)??{},900),cr(A.result??{},900)].join(" ").toLowerCase().includes(O)}):$},[e.runtime_ledger_log_items,e.runtime_log_query]),U=p.useMemo(()=>{const O=e.runtime_log_query.trim().toLowerCase(),$=ZC(e.runtime_ledger_log_items);return O?$.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(O)):$},[e.runtime_ledger_log_items,e.runtime_log_query]),J=U.reduce((O,$)=>O+(Number($.tokens.total)||0),0),Y=U.filter(O=>O.missing_response||O.error).length,re=p.useMemo(()=>{const O=e.runtime_log_query.trim().toLowerCase(),$=String(e.audit_log_text||"").replace(/\r\n/g,`
|
|
109
|
+
`).replace(/\r/g,`
|
|
110
|
+
`).split(`
|
|
111
|
+
`).filter(Boolean);return O?$.filter(z=>z.toLowerCase().includes(O)):$},[e.audit_log_text,e.runtime_log_query]),ce=e.runtime_log_source==="run_ledger"||e.runtime_log_source==="provider_calls",fe=e.runtime_log_source==="run_ledger"?"Selected Run Ledger":e.runtime_log_source==="provider_calls"?"Provider Calls":"Gateway HTTP Audit",W=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:Qt(e.artifact_run_filter,18)})]}):null,e.session_id?s.jsxs("span",{className:"chip muted",children:["session ",s.jsx("span",{className:"mono",children:Qt(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:T(k.waiting.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Running"}),s.jsx("strong",{children:T(k.running.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Failed"}),s.jsx("strong",{children:T(k.failed.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsxs("span",{children:["Artifacts",u?" (filtered)":""]}),s.jsx("strong",{children:T(l)})]})]})]}),s.jsx("nav",{className:"runtime_mode_tabs",role:"tablist","aria-label":"System sections",children:["activity","artifacts","memory","logs"].map(O=>s.jsxs("button",{role:"tab","aria-selected":e.tab===O,className:`runtime_mode_tab ${e.tab===O?"active":""}`,onClick:()=>e.on_tab_change(O),children:[s.jsx(et,{name:O==="activity"?"history":O==="artifacts"?"download":O==="memory"?"agent":"terminal",size:14}),s.jsx("span",{children:O==="activity"?"Activity":O==="artifacts"?"Artifacts":O==="memory"?"Memory":"Logs"})]},O))}),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(hE,{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:O=>{E(O),e.on_select_run(O),e.on_tab_change("artifacts")},on_filter_session_artifacts:O=>{O&&(e.on_artifact_run_filter_change(""),e.on_session_filter_change(O),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:O=>e.on_query_change(O.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:O=>{const $=O.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:O=>e.on_group_by_change(O.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:O=>e.on_sort_by_change(O.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(et,{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(O=>{const $=o.has(O),z=w[O]||0,A=HC(O);return s.jsxs("button",{type:"button","aria-pressed":$,"aria-label":`${A} artifact type filter. Type filters combine with OR.`,title:`${A}: ${$?"in the filter":"not in the filter"}. Type filters combine with OR.`,className:`artifact_filter_chip ${$?"active":""}`,onClick:()=>x(O),children:[s.jsx("span",{children:A}),s.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?z.toLocaleString():"—"})]},O)}),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(O=>s.jsx("button",{type:"button","aria-pressed":e.date_filter===O.value,className:`artifact_filter_chip ${e.date_filter===O.value?"active":""}`,onClick:()=>e.on_date_filter_change(O.value),children:O.label},O.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:N||Qt(e.artifact_run_filter,18)}),".",s.jsx("button",{className:"btn",onClick:()=>E(""),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 ",Yl(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:C.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:()=>E(""),children:[s.jsx("strong",{children:"All artifacts"}),s.jsx("span",{children:e.gateway_connected?`${l.toLocaleString()} match${l===1?"":"es"}`:"counts unavailable"})]}),C.map(O=>{const $=String(O.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:()=>E($),title:$,children:[s.jsx("strong",{children:Bi(O,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Qt($,15)}),s.jsx("span",{children:ic(O)})]},$)})]})]}),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?`${_.toLocaleString()}-${g.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:m<=0,children:"First"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(m-1),disabled:m<=0,children:"Prev"}),s.jsxs("span",{className:"muted artifact_page_label",children:["Page ",(m+1).toLocaleString()," / ",f.toLocaleString()]}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(m+1),disabled:m>=f-1,children:"Next"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(f-1),disabled:m>=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(O=>s.jsxs("section",{className:"artifact_group",children:[s.jsxs("div",{className:"artifact_group_header",children:[s.jsx("span",{children:O.key}),s.jsx("span",{className:"artifact_group_count",children:O.items.length})]}),O.items.map($=>{var F;const z=$.run_id&&e.run_by_id[$.run_id]||null,A=z?Bi(z,e.workflow_label_by_id):jg($),te=iw($),P=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(aw,{artifact:$,size:18}),s.jsxs("div",{className:"artifact_row_main",children:[s.jsxs("div",{className:"artifact_row_title",children:[s.jsx("strong",{children:rw(mm($,e.run_by_id,e.workflow_label_by_id))}),s.jsx("span",{className:"artifact_type_badge",children:gu($)}),$.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"})," ",KC($)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Size"})," ",Yl($.size_bytes)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Last seen"})," ",sw($)]}),P?s.jsxs("span",{children:[s.jsx("b",{children:"Accesses"})," ",P.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:[A?s.jsxs("span",{children:[s.jsx("b",{children:"Workflow"})," ",A]}):null,$.run_id?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Run"})," ",Qt($.run_id,13)]}):null,s.jsxs("span",{children:[s.jsx("b",{children:"Turn"})," ",Mp($)]}),pu($)?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Node"})," ",pu($)]}):null,_f($)?s.jsxs("span",{children:[s.jsx("b",{children:"Source"})," ",_f($)]}):null]}),s.jsxs("div",{className:"artifact_row_facts tertiary",children:[s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"ID"})," ",Qt($.artifact_id,22)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Provenance"})," ",tw($)]})]}),ow($)?s.jsx("div",{className:"artifact_row_path mono",children:ow($)}):null]})]},$.artifact_id)})]},O.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?Rp(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):Rp(t,e.run_by_id,e.workflow_label_by_id)}):null]}),t?s.jsxs(s.Fragment,{children:[(()=>{var F,G,R,Z,X,Q,le;const O=YC(t),$=Yx(t),z=iw(t),A=Number(((F=t.access)==null?void 0:F.access_count)||0)||0,te=_n((G=t.links)==null?void 0:G.provider_trace,(R=t.links)==null?void 0:R.provider_trace_url,(Z=t.links)==null?void 0:Z.provider_trace_id),P=_n((X=t.links)==null?void 0:X.audit,(Q=t.links)==null?void 0:Q.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(aw,{artifact:t,size:22}),s.jsxs("div",{children:[s.jsx("div",{className:"artifact_detail_title",children:rw(mm(t,e.run_by_id,e.workflow_label_by_id))}),s.jsxs("div",{className:"artifact_detail_subtitle",children:[gu(t)," • ",t.render_kind||e.embedded_preview.render_kind||t.modality||"artifact"," • ",t.content_type||"unknown MIME"," • ",Yl(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),s.jsx(iE,{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:gu(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:bu(t.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Size"}),s.jsx("strong",{children:Yl(t.size_bytes)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last seen"}),s.jsx("strong",{children:sw(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Accesses"}),s.jsx("strong",{children:A?A.toLocaleString():"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:t.run_id?Qt(t.run_id,24):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:j?Bi(j,e.workflow_label_by_id):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Turn"}),s.jsx("strong",{children:Mp(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:pu(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:tw(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Artifact id"}),s.jsx("strong",{className:"mono",children:Qt(t.artifact_id,30)})]}),t.sha256?s.jsxs("div",{children:[s.jsx("span",{children:"sha256"}),s.jsx("strong",{className:"mono",children:Qt(t.sha256,30)})]}):null]}),O?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:O})]}):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(Is,{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:()=>E(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:()=>{P?window.open(P,"_blank","noopener,noreferrer"):e.on_tab_change("logs")},disabled:!P&&!t.audit_available,children:"Open audit trail"}),s.jsx("button",{className:"btn",onClick:()=>void rc(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(Is,{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:fe}),s.jsx("div",{className:"mono muted",children:W})]}),s.jsxs("div",{className:"actions",style:{marginTop:0},children:[ce&&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:()=>{ce?e.on_refresh_runtime_ledger(e.selected_run_id):e.on_refresh_audit()},disabled:ce?e.runtime_ledger_log_loading:e.audit_log_loading,children:[s.jsx(et,{name:"refresh",size:14}),ce?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:O=>e.on_runtime_log_query_change(O.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:I?Bi(I,e.workflow_label_by_id):e.selected_run_id?Qt(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Qt(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:I!=null&&I.session_id?Qt(String(I.session_id),28):e.session_id?Qt(e.session_id,28):"—"})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>E(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&&!K.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:K.map(O=>{var X,Q;const $=O.record||{},z=String(((X=$==null?void 0:$.effect)==null?void 0:X.type)||"").trim(),A=String(($==null?void 0:$.status)||"").trim(),te=String(($==null?void 0:$.node_id)||"").trim(),P=_n($==null?void 0:$.ended_at,$==null?void 0:$.started_at,$==null?void 0:$.ts),F=ra($),G=Jx($),R=z?kt(cr(((Q=$==null?void 0:$.effect)==null?void 0:Q.payload)??{},1200),{max_chars:1200,max_lines:6}):"",Z=Xx($)||(F?`Waiting for ${String(F.reason||"input")}`:"")||(($==null?void 0:$.result)!==void 0?cr($.result,700):"");return s.jsxs("article",{className:`runtime_log_event ${oc(A)}`,children:[s.jsxs("div",{className:"runtime_log_event_header",children:[s.jsxs("span",{className:"mono",children:["#",O.cursor]}),s.jsx(ac,{status:A||"record"}),z?s.jsx("span",{className:"chip mono muted",children:z}):null,te?s.jsx("strong",{className:"mono",children:te}):null,P?s.jsx("span",{className:"mono muted",children:bu(P)}):null]}),s.jsxs("div",{className:"runtime_log_event_body",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Request / activity"}),s.jsx("p",{children:[G||Qh($),R&&R!=="{}"?R:""].filter(Boolean).join(`
|
|
112
|
+
`)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:kt(Z||"—",{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(Is,{value:$,collapseAfterDepth:3,showCopy:!0})]})]},`${e.selected_run_id}:${O.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:I?Bi(I,e.workflow_label_by_id):e.selected_run_id?Qt(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Qt(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:U.length.toLocaleString()}),s.jsx("em",{className:"mono",children:J?`${J.toLocaleString()} tokens`:"tokens not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Issues"}),s.jsx("strong",{children:Y.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&&!U.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:U.map(O=>s.jsxs("article",{className:`provider_activity ${O.error||O.missing_response?"danger":""}`,children:[s.jsxs("div",{className:"provider_activity_header",children:[s.jsxs("div",{children:[s.jsx("h4",{children:[O.provider||"provider unknown",O.model||"model unknown"].join(" / ")}),s.jsxs("div",{className:"timeline_subtitle",children:[O.node_id?s.jsx("span",{className:"mono",children:O.node_id}):null,O.run_id?s.jsx("span",{className:"mono",children:Qt(O.run_id,16)}):null,s.jsx("span",{children:pg(O.duration_ms)}),O.status?s.jsx(ac,{status:O.status}):null]})]}),s.jsxs("div",{className:"provider_tokens mono",children:[O.tokens.total?O.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:O.prompt_preview||"No prompt payload captured"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Response / error"}),s.jsx("p",{children:O.response_preview||O.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(Is,{value:O.raw,collapseAfterDepth:3,showCopy:!0})]})]},O.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(`
|
|
113
|
+
`):"(audit tail not loaded or no lines match search)"})]})]}):null]})}function _E(e){const[t,n]=p.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 uw(e,t,n){if(ff(e)==="automation"){const r=String(e.automation_id||e.run_id||"").trim();return n[r]||"Automation"}return Bi(e,t)}function dw(e){const t=ff(e.run);return t?s.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:Lx(e.run)}):null}function pE(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 m=[f.run,...f.children];return c+m.filter(_=>ju(_.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(mf,{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(et,{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(),m=f===t;return s.jsxs("div",{className:"run_tree_group",children:[s.jsxs("button",{className:`run_tree_item ${m?"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:uw(c,e.workflow_label_by_id,e.automation_titles)}),s.jsx(dw,{run:c}),c.status?s.jsx(ac,{status:um(c)}):null]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Qt(f,13)}),s.jsx("span",{children:fu(c)?ec(fu(c)):"no start"}),s.jsx("span",{children:ic(c)})]})]}),u.children.length?s.jsx("div",{className:"run_tree_children",children:u.children.map(_=>{const g=String(_.run_id||"").trim();return s.jsxs("button",{className:`run_tree_item run_tree_child ${g===t?"selected":""}`,onClick:()=>e.on_select(g,f),title:g,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:uw(_,e.workflow_label_by_id,e.automation_titles)}),s.jsx(dw,{run:_}),s.jsx(ac,{status:um(_)})]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Qt(g,13)}),s.jsx("span",{children:fu(_)?ec(fu(_)):"child"}),s.jsx("span",{children:ic(_)})]})]},g)})}):null]},f)})]},l.key))]})]})}class gE{constructor(){Vs(this,"_buffer","");Vs(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const r=this._buffer.indexOf(`
|
|
114
|
+
`);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 m={id:this._current.id,event:this._current.event,data:this._current.data_lines.join(`
|
|
115
|
+
`)};n(m)}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 Lt=ig;function si(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 nb(){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 Mt(e){const t=(e||"").trim(),n={};return t&&(n.Authorization=`Bearer ${t}`),{...n,...nb()}}async function Wn(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class yE extends Error{constructor(n,r){super(r);Vs(this,"status");this.name="GatewayRequestError",this.status=n}}async function Oh(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 yE(e.status,`${t} (HTTP ${e.status}): ${r||e.statusText||"no reason given"}`)}class F_{constructor(t){Vs(this,"_cfg");Vs(this,"fetch_gateway",(t,n)=>fetch(Lt(this._cfg.base_url,t),{...n,headers:{...n==null?void 0:n.headers,...Mt(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 m=await fetch(Lt(this._cfg.base_url,wt("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(f)});if(!m.ok)throw new Error(`start_run failed: ${m.status}`);const _=await m.json(),g=_==null?void 0:_.run_id;if(typeof g!="string"||!g)throw new Error("start_run: missing run_id");return g}async list_mcp_servers(){for(const t of[wt("mcp/servers"),wt("mcp"),wt("discovery/mcp")])try{const n=await fetch(Lt(this._cfg.base_url,t),{headers:{...Mt(this._cfg.auth_token)},signal:si()});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[wt("skills"),wt("skills/registry")])try{const n=await fetch(Lt(this._cfg.base_url,t),{headers:{...Mt(this._cfg.auth_token)},signal:si()});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(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}`)),{headers:{...Mt(this._cfg.auth_token)}});if(!n.ok)throw new Error(`get_run failed: ${await Wn(n)}`);return await n.json()}async find_run(t){const n=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}`)),{headers:{...Mt(this._cfg.auth_token)}});if(n.status===404||n.status===403)return null;if(!n.ok)throw await Oh(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=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/history_bundle?${o.toString()}`)),u=await fetch(l,{headers:{...Mt(this._cfg.auth_token)}});if(!u.ok)throw new Error(`get_run_history_bundle failed: ${await Wn(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=Lt(this._cfg.base_url,wt(`runs?${c.toString()}`)),m=await fetch(f,{headers:{...Mt(this._cfg.auth_token)},signal:AbortSignal.timeout(3e4)});if(!m.ok)throw new Error(`list_runs failed: ${await Wn(m)}`);return await m.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=Lt(this._cfg.base_url,wt(`audit/tail?max_bytes=${encodeURIComponent(String(n))}`)),o=await fetch(r,{headers:{...Mt(this._cfg.auth_token)}});if(!o.ok)throw new Error(`audit_log_tail failed: ${await Wn(o)}`);return await o.json()}async gateway_about(){const t=await fetch(Lt(this._cfg.base_url,wt("about")),{headers:{...Mt(this._cfg.auth_token)},signal:si(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(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(n)}/input_data`)),{headers:{...Mt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_run_input_data failed: ${await Wn(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=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),c=await fetch(u,{headers:{...Mt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_run_artifacts failed: ${await Wn(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=Lt(this._cfg.base_url,wt(`sessions/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(o))}&offset=${encodeURIComponent(String(l))}`)),c=await fetch(u,{headers:{...Mt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`list_session_artifacts failed: ${await Wn(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(),m=String((t==null?void 0:t.workflow_id)||"").trim(),_=String((t==null?void 0:t.node_id)||"").trim(),g=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(),k=String((t==null?void 0:t.cursor)||"").trim(),j=String((t==null?void 0:t.order_by)||"").trim(),N=String((t==null?void 0:t.order)||"").trim(),C=String((t==null?void 0:t.created_after)||"").trim(),E=String((t==null?void 0:t.created_before)||"").trim(),T=typeof(t==null?void 0:t.limit)=="number"?t.limit:500,I=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),m&&n.set("workflow_id",m),_&&n.set("node_id",_),g&&n.set("content_type",g),w&&n.set("query",w),x&&n.set("tags",x),k&&n.set("cursor",k),j&&n.set("order_by",j),N&&n.set("order",N),C&&n.set("created_after",C),E&&n.set("created_before",E),t!=null&&t.include_stats&&n.set("include_stats","true"),n.set("limit",String(T)),n.set("offset",String(I));const K=await fetch(Lt(this._cfg.base_url,wt(`artifacts/search?${n.toString()}`)),{headers:{...Mt(this._cfg.auth_token)}});if(!K.ok)throw new Error(`search_artifacts failed: ${await Wn(K)}`);return await K.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(Lt(this._cfg.base_url,wt(`artifacts/stats?${n.toString()}`)),{headers:{...Mt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`artifact_stats failed: ${await Wn(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=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(o)}/artifacts/${encodeURIComponent(l)}/content${c}`)),m=await fetch(f,{headers:{...Mt(this._cfg.auth_token)}});if(!m.ok)throw new Error(`download_run_artifact_content failed: ${await Wn(m)}`);return await m.blob()}async list_entities(){const t=await fetch(Lt(this._cfg.base_url,wt("entities")),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!t.ok)throw new Error(`list_entities failed: ${await Wn(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(Lt(this._cfg.base_url,wt("entities/spec/phases")),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!t.ok)throw new Error(`get_entity_phases_spec failed: ${await Wn(t)}`);return await t.json()}async get_entity_cognition(t){const n=await fetch(Lt(this._cfg.base_url,wt(`entities/${encodeURIComponent(t)}/cognition`)),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!n.ok)throw new Error(`get_entity_cognition failed: ${await Wn(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(Lt(this._cfg.base_url,wt(`entities/${encodeURIComponent(n)}/card`)),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!r.ok)throw new Error(`get_entity_card failed: ${await Wn(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=Lt(this._cfg.base_url,wt(`entities/${encodeURIComponent(r)}/diary/${encodeURIComponent(o)}?reason=${encodeURIComponent("observer board hint chip")}`)),u=await fetch(l,{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!u.ok)throw new Error(`read_entity_diary_entry failed: ${await Wn(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=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}/ledger?after=${encodeURIComponent(String(r))}&limit=${encodeURIComponent(String(o))}`)),u=await fetch(l,{headers:{...Mt(this._cfg.auth_token)},signal:si(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:[],m=typeof(c==null?void 0:c.next_after)=="number"?c.next_after:r;return{items:f,next_after:m}}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(Lt(this._cfg.base_url,wt("runs/ledger/batch")),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify({runs:n,limit:r}),signal:si()});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(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/summary`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await Oh(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(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/chat`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)throw await Oh(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 m=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(u)});if(!m.ok)throw new Error(`audio_transcribe failed: ${await Wn(m)}`);const _=await m.json(),g=String((_==null?void 0:_.text)||"");return{ok:!!(_!=null&&_.ok),run_id:String((_==null?void 0:_.run_id)||""),request_id:String((_==null?void 0:_.request_id)||""),text:g,transcript_artifact:_==null?void 0:_.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 m=await fetch(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/voice/tts`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(l)});if(!m.ok)throw new Error(`voice_tts failed: ${await Wn(m)}`);const _=await m.json();return{ok:!!(_!=null&&_.ok),run_id:String((_==null?void 0:_.run_id)||""),request_id:String((_==null?void 0:_.request_id)||""),audio_artifact:_==null?void 0:_.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(Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/chat_threads`)),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!f.ok)throw new Error(`save_chat_thread failed: ${await Wn(f)}`);return await f.json()}async list_bundles(){const t=await fetch(Lt(this._cfg.base_url,wt("bundles")),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!t.ok)throw new Error(`list_bundles failed: ${t.status}`);return await t.json()}async get_gateway_json(t,n){const r=await fetch(Lt(this._cfg.base_url,wt(t)),{headers:{...Mt(this._cfg.auth_token)},signal:n??si()});if(!r.ok)throw new Error(await Wn(r));return await r.json()}async reload_bundles(){const t=await fetch(Lt(this._cfg.base_url,wt("bundles/reload")),{method:"POST",headers:{...Mt(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(Lt(this._cfg.base_url,wt("bundles/upload")),{method:"POST",headers:{...Mt(this._cfg.auth_token)},body:l});if(!u.ok)throw new Error(`upload_bundle failed: ${await Wn(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(Lt(this._cfg.base_url,wt("attachments/upload")),{method:"POST",headers:{...Mt(this._cfg.auth_token)},body:c});if(!f.ok)throw new Error(`attachments_upload failed: ${await Wn(f)}`);const m=await f.json(),_=m==null?void 0:m.attachment;if(!_||typeof _!="object")throw new Error("attachments_upload: missing attachment");if(!String(_.$artifact||"").trim())throw new Error("attachments_upload: missing attachment.$artifact");return _}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=Lt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(r)}?${o.toString()}`)),c=await fetch(u,{method:"DELETE",headers:{...Mt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`remove_bundle failed: ${await Wn(c)}`);return await c.json()}async discovery_tools(){const t=await fetch(Lt(this._cfg.base_url,wt("discovery/tools")),{headers:{...Mt(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=Lt(this._cfg.base_url,wt(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),o=await fetch(r,{headers:{...Mt(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(Lt(this._cfg.base_url,wt(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...Mt(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(Lt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(n)}`)),{headers:{...Mt(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(Lt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(r)}/flows/${encodeURIComponent(o)}`)),{headers:{...Mt(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(Lt(this._cfg.base_url,wt(`workflows/${encodeURIComponent(n)}/flow`)),{headers:{...Mt(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(Lt(this._cfg.base_url,wt("discovery/capabilities")),{headers:{...Mt(this._cfg.auth_token)},signal:si()});if(!t.ok)throw new Error(`discovery_capabilities failed: ${await Wn(t)}`);return await t.json()}automations_client(){const t=this._cfg.auth_token;return ak({fetch:(n,r)=>fetch(n,r),baseUrl:this._cfg.base_url,headers:()=>Mt(t)})}async submit_command(t){const n=await fetch(Lt(this._cfg.base_url,wt("commands")),{method:"POST",headers:{"Content-Type":"application/json",...Mt(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 m=String((t==null?void 0:t.subject)||"").trim();m&&(l.subject=m);const _=String((t==null?void 0:t.predicate)||"").trim();_&&(l.predicate=_);const g=String((t==null?void 0:t.object)||"").trim();g&&(l.object=g);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 k=String((t==null?void 0:t.active_at)||"").trim();k&&(l.active_at=k);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 N=await fetch(Lt(this._cfg.base_url,wt("kg/query")),{method:"POST",headers:{"Content-Type":"application/json",...Mt(this._cfg.auth_token)},body:JSON.stringify(l)});if(!N.ok)throw new Error(`kg_query failed: ${await Wn(N)}`);return await N.json()}async stream_ledger(t,n){var g;const r=Number((n==null?void 0:n.after)||0),o=n.on_step,l=n.signal,u=Lt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}/ledger/stream?after=${encodeURIComponent(String(r))}`)),c=await fetch(u,{headers:{Accept:"text/event-stream",...Mt(this._cfg.auth_token)},signal:l});if(!c.ok)throw await Oh(c,"The ledger stream was refused");if(!c.body)throw new Error("stream_ledger: response body is missing");(g=n.on_open)==null||g.call(n);const f=c.body.getReader(),m=new TextDecoder("utf-8"),_=new gE;for(;;){const{value:w,done:x}=await f.read();if(x)return;const k=m.decode(w,{stream:!0});_.push(k,j=>{if(!(j.event!=="step"||!j.data))try{const N=JSON.parse(j.data);N&&typeof N.cursor=="number"&&N.record&&o(N)}catch{}})}}}const Lp=Rj("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).",wE="Copy failed — select and copy";function Ip(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function vE(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 xE(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 vE(t)}const bE=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 jE(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 N=0;N<16;N++)l[N]=r.getUint32(c+N*4,!1);for(let N=16;N<64;N++){const C=u(l[N-15],7)^u(l[N-15],18)^l[N-15]>>>3,E=u(l[N-2],17)^u(l[N-2],19)^l[N-2]>>>10;l[N]=l[N-16]+C+l[N-7]+E>>>0}let[f,m,_,g,w,x,k,j]=[o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7]];for(let N=0;N<64;N++){const C=u(w,6)^u(w,11)^u(w,25),E=w&x^~w&k,T=j+C+E+bE[N]+l[N]>>>0,I=u(f,2)^u(f,13)^u(f,22),K=f&m^f&_^m&_,U=I+K>>>0;j=k,k=x,x=w,w=g+T>>>0,g=_,_=m,m=f,f=T+U>>>0}o[0]=o[0]+f>>>0,o[1]=o[1]+m>>>0,o[2]=o[2]+_>>>0,o[3]=o[3]+g>>>0,o[4]=o[4]+w>>>0,o[5]=o[5]+x>>>0,o[6]=o[6]+k>>>0,o[7]=o[7]+j>>>0}return Array.from(o,c=>c.toString(16).padStart(8,"0")).join("")}async function kE(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 jE(t)}function SE(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class NE{constructor(t){Vs(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",...SE(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,m=!!(f!=null&&f.isError),g=(Array.isArray(f==null?void 0:f.content)?f.content:[]).find(x=>x&&x.type==="text"&&typeof x.text=="string"),w=(g==null?void 0:g.text)??"";return m?{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 fw{constructor(t,n){Vs(this,"pending",[]);Vs(this,"scheduled",!1);Vs(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 hw(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 CE(e,t){const n=qn(e.updated_at||e.created_at)??0;return(qn(t.updated_at||t.created_at)??0)-n}function EE(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=hw(w);if(String(w.role||"")==="occurrence"&&x&&!o[x]){const k={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]=k,r.push(k)}}const l={},u={};for(const w of r){const x=String(w.run_id||"").trim();if(!x)continue;const k=hw(w,t.parent_hint?t.parent_hint(x):"");u[x]=k,k&&(l[k]||(l[k]=[])).push(w)}const c=w=>{const x=String(w.status||"").trim().toLowerCase();return t.filter==="all"?!0:t.filter==="active"?ju(x):t.filter==="waiting"?x==="waiting":t.filter==="terminal"?So(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(),k=x?t.workflow_label_by_id[x]||x:"";return[w.run_id,x,k,w.session_id,w.status,w.session_kind,w.automation_id].join(" ").toLowerCase().includes(n)},m=[];for(const w of r){const x=String(w.run_id||"").trim();if(!x)continue;const k=u[x];(!k||!o[k])&&m.push(x)}const _={},g=w=>{if(t.group_by==="workflow"){const k=String(w.schedule_target_workflow_id||w.workflow_id||"").trim()||"(unknown workflow)";return{key:k,label:t.workflow_label_by_id[k]||k}}if(t.group_by==="session"){const k=String(w.session_id||"").trim()||"(no session)";return{key:k,label:k}}const x=String(w.status||"").trim().toLowerCase()||"unknown";return ju(x)?{key:"active",label:"Active"}:x==="failed"?{key:"failed",label:"Failed"}:So(x)?{key:"finished",label:"Finished"}:{key:x,label:x}};for(const w of m){const x=o[w];if(!x)continue;const k=[...l[w]||[]].sort(CE),j=k.some(C=>c(C)&&f(C));if(!(c(x)&&f(x))&&!j)continue;const N=g(x);_[N.key]||(_[N.key]={key:N.key,label:N.label,rows:[]}),_[N.key].rows.push({run:x,children:k})}return Object.values(_).sort((w,x)=>{const k={active:0,waiting:1,failed:2,finished:3},j=k[w.key]??10,N=k[x.key]??10;return j!==N?j-N:w.label.localeCompare(x.label)})}const AE={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"},$E=[{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 TE(){const[e,t]=p.useState(!0);return s.jsxs("div",{className:"pin-legend",children:[s.jsxs("button",{className:"pin-legend-toggle mono",type:"button",onClick:()=>t(n=>!n),title:"Pin Type Legend",children:[e?"?":"×"," Pin Types"]}),e?null:s.jsxs("div",{className:"pin-legend-content",children:[$E.map(n=>s.jsxs("div",{className:"pin-legend-row",children:[s.jsx("span",{className:"pin-legend-shape",style:{color:AE[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 dn(e){return typeof e=="string"?e:e==null?"":String(e)}function mw(e,t){const n=dn(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function sb(e){const t=dn(e==null?void 0:e.targetHandle),n=dn(e==null?void 0:e.sourceHandle);return!!(t==="exec-in"||n==="exec-out"||t.includes("exec")||n.includes("exec"))}function rb(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{};return dn((t==null?void 0:t.nodeType)||(e==null?void 0:e.type)||"").trim()}function ib(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=dn(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 ME(e){const t=dn(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(rb(r)==="on_flow_start"){const o=dn(r==null?void 0:r.id).trim();if(o)return o}return""}function z_(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 Gd(e,t){const n=dn(e).trim(),r=dn(t).trim();return r?n?`${n}::${r}`:r:""}function RE(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,m)=>{if(!u||typeof u!="object"||n.length>=e.max_nodes||r.length>=e.max_edges)return;const _=Array.isArray(u.nodes)?u.nodes:[],g=Array.isArray(u.edges)?u.edges:[];for(const w of _){const x=dn(w==null?void 0:w.id).trim();if(!x)continue;const k=Gd(c,x);if(!k||o.has(k))continue;const j=z_(w),N={...w,id:k,position:{x:j.x+f.x,y:j.y+f.y}};if(n.push(N),o.add(k),n.length>=e.max_nodes)break}for(const w of g){if(!sb(w))continue;const x=dn(w==null?void 0:w.source).trim(),k=dn(w==null?void 0:w.target).trim();if(!x||!k)continue;const j=Gd(c,x),N=Gd(c,k);if(!j||!N)continue;const C=dn(w==null?void 0:w.id).trim(),E=C?`${j}->${N}::${C}`:`${j}->${N}`;if(r.push({...w,id:E,source:j,target:N}),r.length>=e.max_edges)break}if(!(m>=e.max_depth))for(const w of _){if(n.length>=e.max_nodes||r.length>=e.max_edges)return;if(rb(w)!=="subflow")continue;const x=ib(w);if(!x)continue;const k=e.flow_by_id[x];if(!k||typeof k!="object")continue;const j=Gd(c,dn(w==null?void 0:w.id));if(!j)continue;const N=ME(k);if(!N)continue;const E=(Array.isArray(k.nodes)?k.nodes:[]).find(re=>dn(re==null?void 0:re.id).trim()===N)||null;if(!E)continue;const T=z_(w),I=z_(E),J={x:T.x+f.x+240-I.x,y:T.y+f.y+0-I.y},Y=Gd(j,N);r.push({id:`${j}=>${Y}`,source:j,target:Y,sourceHandle:"exec-out",targetHandle:"exec-in"}),l(k,j,J,m+1)}};return l(t,"",{x:0,y:0},0),{...t,id:dn(t.id),nodes:n,edges:r}}function LE(e){const t=dn(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 IE(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 _=`${l.id}->${f}`;o.has(_)||o.set(_,{id:_,source:l.id,target:f});continue}const m=r[f]||[];for(const _ of m)u.has(_)||c.push(_);if(o.size>=e.max_edges)break}if(o.size>=e.max_edges)break}return{nodes:t,edges:Array.from(o.values())}}function _w(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 OE(e){const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=e.flow,r=dn(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:m,bounds:_}=p.useMemo(()=>{const P=RE({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(P.nodes)?P.nodes:[],G=Array.isArray(P.edges)?P.edges:[];let R=[];for(const ke of F){const Re=dn(ke==null?void 0:ke.id).trim();if(!Re)continue;const ht=ke!=null&&ke.position&&typeof ke.position=="object"?ke.position:{},xe=typeof ht.x=="number"?ht.x:0,Ie=typeof ht.y=="number"?ht.y:0,qe=ke!=null&&ke.data&&typeof ke.data=="object"?ke.data:{},zt=dn((qe==null?void 0:qe.label)||(ke==null?void 0:ke.label)||Re)||Re,en=dn((qe==null?void 0:qe.nodeType)||(ke==null?void 0:ke.type)||"unknown")||"unknown",bn=dn((qe==null?void 0:qe.headerColor)||(ke==null?void 0:ke.headerColor)||"")||"",Wt=qe!=null&&qe.eventConfig&&typeof qe.eventConfig=="object"?qe.eventConfig:null,It=Wt&&typeof Wt.schedule=="string"?dn(Wt.schedule).trim():"",Sn=Wt&&typeof Wt.recurrent=="boolean"?!!Wt.recurrent:void 0,ns=en==="subflow"?ib(ke):"",Ot=It||Sn!==void 0||ns?{schedule:It||void 0,recurrent:Sn,subflow_id:ns||void 0}:void 0;R.push({id:Re,x:xe,y:Ie,label:zt,type:en,color:bn,meta:Ot})}const Z={};for(const ke of R)Z[ke.id]=ke;let X=[];for(const ke of G){if(!sb(ke))continue;const Re=dn(ke==null?void 0:ke.source).trim(),ht=dn(ke==null?void 0:ke.target).trim();!Re||!ht||X.push({id:dn((ke==null?void 0:ke.id)||`${Re}->${ht}`),source:Re,target:ht})}const Q=new Set(R.map(ke=>ke.id));if(X=X.filter(ke=>Q.has(ke.source)&&Q.has(ke.target)),e.simplify===!0){const Re=IE({nodes:R,edges:X,keep_id:ht=>{if(r&&ht===r)return!0;const xe=Z[ht];if(!xe)return!1;const Ie=dn(xe.type).trim().toLowerCase();return Ie==="on_flow_start"||Ie==="on_flow_end"||Ie==="subflow"?!0:!LE(Ie)},max_edges:900});R=Re.nodes,X=Re.edges}if(e.prefer_vertical===!0&&R.length>=2){const ke=R.map(qe=>qe.x),Re=R.map(qe=>qe.y),ht=Math.max(...ke)-Math.min(...ke),xe=Math.max(...Re)-Math.min(...Re);ht>=xe&&(R=R.map(qe=>({...qe,x:qe.y,y:qe.x})));const Ie=Math.min(...R.map(qe=>qe.y));R=R.map(qe=>({...qe,y:Ie+(qe.y-Ie)*c}))}const le={};for(const ke of R)le[ke.id]=ke;const ge=160,pe=56,ye=ge/2,Ne=pe/2;let Ue=0,We=0,pt=0,Fe=0;R.length&&(Ue=Math.min(...R.map(ke=>ke.x)),We=Math.min(...R.map(ke=>ke.y)),pt=Math.max(...R.map(ke=>ke.x+ge)),Fe=Math.max(...R.map(ke=>ke.y+pe)));let tt=0;if(X.length){const ke=new Set(X.map(Re=>`${Re.source}->${Re.target}`));for(const Re of X){if(!ke.has(`${Re.target}->${Re.source}`))continue;const ht=le[Re.source],xe=le[Re.target];if(!ht||!xe)continue;const Ie=ht.x+ye,qe=ht.y+Ne,zt=xe.x+ye,en=xe.y+Ne,bn=Math.max(1,Math.hypot(zt-Ie,en-qe)),Wt=Math.max(28,Math.min(72,bn*.14)),It=Math.min(200,Wt*3.5);It>tt&&(tt=It)}}const lt=60+tt,Ke={x:Ue-lt,y:We-lt,w:pt-Ue+lt*2,h:Fe-We+lt*2,node_w:ge,node_h:pe};return{nodes:R,edges:X,bounds:Ke}},[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 g=p.useRef(null),[w,x]=p.useState(()=>({x:_.x,y:_.y,w:_.w,h:_.h})),k=p.useRef(w);k.current=w,p.useEffect(()=>{x({x:_.x,y:_.y,w:_.w,h:_.h})},[_.x,_.y,_.w,_.h]);const j=p.useRef(new Map),N=p.useRef(null),C=`${w.x} ${w.y} ${w.w} ${w.h}`,E={};for(const P of f)E[P.id]=P;const T=P=>{let F=dn(P).trim();if(!F)return"";if(E[F])return F;for(;F.includes("::");)if(F=F.slice(0,Math.max(0,F.lastIndexOf("::"))),E[F])return F;return""},I=T(r),K={};for(const[P,F]of Object.entries(o)){if(typeof F!="number")continue;const G=T(P);G&&(K[G]=Math.max(K[G]||0,F))}const U={};if(u)for(const[P,F]of Object.entries(l)){if(typeof F!="number")continue;const G=T(P);G&&(U[G]=typeof U[G]=="number"?Math.min(U[G],F):F)}const J=dn(e.schedule_next_in).trim(),Y=dn(e.schedule_interval).trim(),re=e.node_last_ms&&typeof e.node_last_ms=="object"?e.node_last_ms:{},ce=P=>{try{const F=new Date(P),G=String(F.getHours()).padStart(2,"0"),R=String(F.getMinutes()).padStart(2,"0");return`${G}:${R}`}catch{return""}},fe=(P,F)=>{var X,Q;const G=dn((X=P.meta)==null?void 0:X.schedule).trim();if(!(((Q=P.meta)==null?void 0:Q.recurrent)===!0))return F&&J?`next ${J}`:G&&G.length<=12&&!G.includes("T")?`in ${G}`:"scheduled";const Z=G||Y;return Z?F&&J?`${Z} • next ${J}`:`every ${Z}`:F&&J?`next ${J}`:"scheduled"},W=P=>{var ge;const F=dn((ge=P.meta)==null?void 0:ge.subflow_id).trim(),G=F&&e.flow_by_id?e.flow_by_id[F]:null,Z=dn(G==null?void 0:G.name).trim()||F||P.label||P.id,X=typeof re[P.id]=="number"?Number(re[P.id]):null,Q=X!==null?ce(X):"",le=Q?`last ${Q}`:"subflow";return{label:Z,sub:le}},O=(P,F,G)=>{const R=G||k.current,Z=g.current;if(!Z)return{x:P,y:F};const X=Z.getBoundingClientRect(),Q=X.width>0?(P-X.left)/X.width:0,le=X.height>0?(F-X.top)/X.height:0;return{x:R.x+Q*R.w,y:R.y+le*R.h}},$=(P,F,G)=>{const R=G||k.current,Z=Math.max(.12,Math.min(8,F)),X=R.w*Z,Q=R.h*Z,le=R.w>0?(P.x-R.x)/R.w:.5,ge=R.h>0?(P.y-R.y)/R.h:.5,pe=P.x-le*X,ye=P.y-ge*Q;x(_w({x:pe,y:ye,w:X,h:Q},_))},z=(P,F,G)=>{const R=G||k.current,Z=g.current;if(!Z)return;const X=Z.getBoundingClientRect(),Q=.88,le=X.width>0?P/X.width*R.w*Q:0,ge=X.height>0?F/X.height*R.h*Q:0;x(pe=>_w({x:(G||pe).x-le,y:(G||pe).y-ge,w:(G||pe).w,h:(G||pe).h},_))},A=p.useMemo(()=>{const P=new Set;for(const F of m)P.add(`${F.source}->${F.target}`);return P},[m]),te=(P,F,G,R)=>{const Z=_.node_w,X=_.node_h,Q=Math.abs(G),le=Math.abs(R);if(Q<1e-6&&le<1e-6)return{x:P,y:F};const ge=Q>1e-6?Z/2/Q:Number.POSITIVE_INFINITY,pe=le>1e-6?X/2/le:Number.POSITIVE_INFINITY,ye=Math.min(ge,pe);return{x:P+G*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:_.x,y:_.y,w:_.w,h:_.h}),title:"Recenter",children:"⤢"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const P=g.current;if(!P)return;const F=P.getBoundingClientRect(),G=O(F.left+F.width/2,F.top+F.height/2);$(G,.84)},title:"Zoom in",children:"+"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const P=g.current;if(!P)return;const F=P.getBoundingClientRect(),G=O(F.left+F.width/2,F.top+F.height/2);$(G,1.18)},title:"Zoom out",children:"−"})]}),s.jsx(TE,{})]}),s.jsxs("svg",{ref:g,className:"graph_svg",viewBox:C,role:"img","aria-label":"Workflow execution graph",onWheel:P=>{P.preventDefault();const F=O(P.clientX,P.clientY),G=typeof P.deltaY=="number"?P.deltaY:0,R=typeof P.deltaMode=="number"?Number(P.deltaMode):0,Z=R===1?G*24:R===2?G*800:G,X=45e-5*1.15*1.1;let Q=Math.exp(Z*X);Q=Math.max(.86,Math.min(1.16,Q)),$(F,Q)},onPointerDown:P=>{var G,R;(R=(G=P.currentTarget).setPointerCapture)==null||R.call(G,P.pointerId),j.current.set(P.pointerId,{x:P.clientX,y:P.clientY});const F=Array.from(j.current.values());if(F.length===1)N.current={mode:"pan",start_view:k.current,start_client:{x:P.clientX,y:P.clientY},start_dist:0,anchor_svg:{x:0,y:0}};else if(F.length>=2){const Z=F[0],X=F[1],Q=Z.x-X.x,le=Z.y-X.y,ge=Math.max(1,Math.hypot(Q,le)),pe={x:(Z.x+X.x)/2,y:(Z.y+X.y)/2},ye=k.current;N.current={mode:"pinch",start_view:ye,start_client:pe,start_dist:ge,anchor_svg:O(pe.x,pe.y,ye)}}},onPointerMove:P=>{if(!j.current.has(P.pointerId))return;j.current.set(P.pointerId,{x:P.clientX,y:P.clientY});const F=N.current;if(!F)return;const G=Array.from(j.current.values());if(F.mode==="pan"&&G.length===1){const R=P.clientX-F.start_client.x,Z=P.clientY-F.start_client.y;z(R,Z,F.start_view)}else if(F.mode==="pinch"&&G.length>=2){const R=G[0],Z=G[1],X=R.x-Z.x,Q=R.y-Z.y,le=Math.max(1,Math.hypot(X,Q)),ge=F.start_dist/le;$(F.anchor_svg,ge,F.start_view)}},onPointerUp:P=>{j.current.delete(P.pointerId),j.current.size===0&&(N.current=null)},onPointerCancel:P=>{j.current.delete(P.pointerId),j.current.size===0&&(N.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"})]})]})]}),m.map(P=>{const F=E[P.source],G=E[P.target];if(!F||!G)return null;const R=F.x+_.node_w/2,Z=F.y+_.node_h/2,X=G.x+_.node_w/2,Q=G.y+_.node_h/2,le=X-R,ge=Q-Z,pe=te(R,Z,le,ge),ye=te(X,Q,-le,-ge),Ne=P.source!==P.target&&A.has(`${P.target}->${P.source}`),Ue=Math.max(1,Math.hypot(le,ge)),We=-ge/Ue,pt=le/Ue,Fe=String(P.source)<String(P.target)?1:-1,lt=Math.abs(le)>=Math.abs(ge)?le>=0:ge>=0,Ke=!Ne||lt,ke=Math.max(28,Math.min(72,Ue*.14)),Re=Math.min(200,ke*3.5),ht=Ne&&!Ke?Re*Fe:0,xe=(pe.x+ye.x)/2+We*ht,Ie=(pe.y+ye.y)/2+pt*ht,qe=Ne&&!Ke?`M ${pe.x} ${pe.y} Q ${xe} ${Ie} ${ye.x} ${ye.y}`:`M ${pe.x} ${pe.y} L ${ye.x} ${ye.y}`,zt=u&&U&&U[P.source]!==void 0&&U[P.target]!==void 0;return s.jsx("path",{d:qe,className:`graph_edge ${zt?"visited":""}`,markerEnd:"url(#arrow)",fill:"none"},P.id)}),f.map(P=>{const G=(typeof K[P.id]=="number"?K[P.id]:0)>t,R=I&&P.id===I,Z=u&&U&&U[P.id]!==void 0,X=`graph_node ${R?"active":G?"recent":""} ${Z?"visited":""}`,Q=P.color||"rgba(255,255,255,0.16)";let le=P.label||P.id,ge=P.type;if(P.type==="on_schedule")ge=fe(P,!!R);else if(P.type==="subflow"){const Ne=W(P);le=Ne.label,ge=Ne.sub}const pe=mw(le,22),ye=mw(ge,22);return s.jsxs("g",{className:X,transform:`translate(${P.x}, ${P.y})`,children:[s.jsx("rect",{className:"graph_node_bg",width:_.node_w,height:_.node_h,rx:12,ry:12}),s.jsx("rect",{className:"graph_node_bar",width:_.node_w,height:6,rx:12,ry:12,fill:Q}),s.jsx("text",{className:"graph_node_label",x:12,y:28,children:pe}),s.jsx("text",{className:"graph_node_type",x:12,y:46,children:ye}),P.type==="on_schedule"?s.jsx("text",{className:"graph_node_icon",x:_.node_w-18,y:18,children:"⏰"}):null]},P.id)})]})]})}function Ks(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=Ks(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var B_={exports:{}},U_={},W_={exports:{}},q_={};/**
|
|
116
|
+
* @license React
|
|
117
|
+
* use-sync-external-store-shim.production.js
|
|
118
|
+
*
|
|
119
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
120
|
+
*
|
|
121
|
+
* This source code is licensed under the MIT license found in the
|
|
122
|
+
* LICENSE file in the root directory of this source tree.
|
|
123
|
+
*/var pw;function PE(){if(pw)return q_;pw=1;var e=Cf();function t(g,w){return g===w&&(g!==0||1/g===1/w)||g!==g&&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(g,w){var x=w(),k=r({inst:{value:x,getSnapshot:w}}),j=k[0].inst,N=k[1];return l(function(){j.value=x,j.getSnapshot=w,f(j)&&N({inst:j})},[g,x,w]),o(function(){return f(j)&&N({inst:j}),g(function(){f(j)&&N({inst:j})})},[g]),u(x),x}function f(g){var w=g.getSnapshot;g=g.value;try{var x=w();return!n(g,x)}catch{return!0}}function m(g,w){return w()}var _=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?m:c;return q_.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:_,q_}var gw;function DE(){return gw||(gw=1,W_.exports=PE()),W_.exports}/**
|
|
124
|
+
* @license React
|
|
125
|
+
* use-sync-external-store-shim/with-selector.production.js
|
|
126
|
+
*
|
|
127
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
128
|
+
*
|
|
129
|
+
* This source code is licensed under the MIT license found in the
|
|
130
|
+
* LICENSE file in the root directory of this source tree.
|
|
131
|
+
*/var yw;function FE(){if(yw)return U_;yw=1;var e=Cf(),t=DE();function n(m,_){return m===_&&(m!==0||1/m===1/_)||m!==m&&_!==_}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 U_.useSyncExternalStoreWithSelector=function(m,_,g,w,x){var k=l(null);if(k.current===null){var j={hasValue:!1,value:null};k.current=j}else j=k.current;k=c(function(){function C(U){if(!E){if(E=!0,T=U,U=w(U),x!==void 0&&j.hasValue){var J=j.value;if(x(J,U))return I=J}return I=U}if(J=I,r(T,U))return J;var Y=w(U);return x!==void 0&&x(J,Y)?(T=U,J):(T=U,I=Y)}var E=!1,T,I,K=g===void 0?null:g;return[function(){return C(_())},K===null?void 0:function(){return C(K())}]},[_,g,w,x]);var N=o(m,k[0],k[1]);return u(function(){j.hasValue=!0,j.value=N},[N]),f(N),N},U_}var ww;function zE(){return ww||(ww=1,B_.exports=FE()),B_.exports}var BE=zE();const UE=rg(BE),WE={},vw=e=>{let t;const n=new Set,r=(_,g)=>{const w=typeof _=="function"?_(t):_;if(!Object.is(w,t)){const x=t;t=g??(typeof w!="object"||w===null)?w:Object.assign({},t,w),n.forEach(k=>k(t,x))}},o=()=>t,f={setState:r,getState:o,getInitialState:()=>m,subscribe:_=>(n.add(_),()=>n.delete(_)),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()}},m=t=e(r,o,f);return f},qE=e=>e?vw(e):vw,{useDebugValue:HE}=ve,{useSyncExternalStoreWithSelector:VE}=UE,GE=e=>e;function ob(e,t=GE,n){const r=VE(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return HE(r),r}const xw=(e,t)=>{const n=qE(e),r=(o,l=t)=>ob(n,o,l);return Object.assign(r,n),r},KE=(e,t)=>e?xw(e,t):xw;function Os(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 YE={value:()=>{}};function Rm(){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 em(n)}function em(e){this._=e}function JE(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}})}em.prototype=Rm.prototype={constructor:em,on:function(e,t){var n=this._,r=JE(e+"",n),o,l=-1,u=r.length;if(arguments.length<2){for(;++l<u;)if((o=(e=r[l]).type)&&(o=XE(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]=bw(n[o],e.name,t);else if(t==null)for(o in n)n[o]=bw(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 em(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 XE(e,t){for(var n=0,r=e.length,o;n<r;++n)if((o=e[n]).name===t)return o.value}function bw(e,t,n){for(var r=0,o=e.length;r<o;++r)if(e[r].name===t){e[r]=YE,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Op="http://www.w3.org/1999/xhtml";const jw={svg:"http://www.w3.org/2000/svg",xhtml:Op,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Lm(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),jw.hasOwnProperty(t)?{space:jw[t],local:e}:e}function ZE(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Op&&t.documentElement.namespaceURI===Op?t.createElement(e):t.createElementNS(n,e)}}function QE(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function ab(e){var t=Lm(e);return(t.local?QE:ZE)(t)}function eA(){}function Sg(e){return e==null?eA:function(){return this.querySelector(e)}}function tA(e){typeof e!="function"&&(e=Sg(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,m,_=0;_<u;++_)(f=l[_])&&(m=e.call(f,f.__data__,_,l))&&("__data__"in f&&(m.__data__=f.__data__),c[_]=m);return new ri(r,this._parents)}function nA(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function sA(){return[]}function lb(e){return e==null?sA:function(){return this.querySelectorAll(e)}}function rA(e){return function(){return nA(e.apply(this,arguments))}}function iA(e){typeof e=="function"?e=rA(e):e=lb(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,m=0;m<c;++m)(f=u[m])&&(r.push(e.call(f,f.__data__,m,u)),o.push(f));return new ri(r,o)}function cb(e){return function(){return this.matches(e)}}function ub(e){return function(t){return t.matches(e)}}var oA=Array.prototype.find;function aA(e){return function(){return oA.call(this.children,e)}}function lA(){return this.firstElementChild}function cA(e){return this.select(e==null?lA:aA(typeof e=="function"?e:ub(e)))}var uA=Array.prototype.filter;function dA(){return Array.from(this.children)}function fA(e){return function(){return uA.call(this.children,e)}}function hA(e){return this.selectAll(e==null?dA:fA(typeof e=="function"?e:ub(e)))}function mA(e){typeof e!="function"&&(e=cb(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,m=0;m<u;++m)(f=l[m])&&e.call(f,f.__data__,m,l)&&c.push(f);return new ri(r,this._parents)}function db(e){return new Array(e.length)}function _A(){return new ri(this._enter||this._groups.map(db),this._parents)}function _m(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}_m.prototype={constructor:_m,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 pA(e){return function(){return e}}function gA(e,t,n,r,o,l){for(var u=0,c,f=t.length,m=l.length;u<m;++u)(c=t[u])?(c.__data__=l[u],r[u]=c):n[u]=new _m(e,l[u]);for(;u<f;++u)(c=t[u])&&(o[u]=c)}function yA(e,t,n,r,o,l,u){var c,f,m=new Map,_=t.length,g=l.length,w=new Array(_),x;for(c=0;c<_;++c)(f=t[c])&&(w[c]=x=u.call(f,f.__data__,c,t)+"",m.has(x)?o[c]=f:m.set(x,f));for(c=0;c<g;++c)x=u.call(e,l[c],c,l)+"",(f=m.get(x))?(r[c]=f,f.__data__=l[c],m.delete(x)):n[c]=new _m(e,l[c]);for(c=0;c<_;++c)(f=t[c])&&m.get(w[c])===f&&(o[c]=f)}function wA(e){return e.__data__}function vA(e,t){if(!arguments.length)return Array.from(this,wA);var n=t?yA:gA,r=this._parents,o=this._groups;typeof e!="function"&&(e=pA(e));for(var l=o.length,u=new Array(l),c=new Array(l),f=new Array(l),m=0;m<l;++m){var _=r[m],g=o[m],w=g.length,x=xA(e.call(_,_&&_.__data__,m,r)),k=x.length,j=c[m]=new Array(k),N=u[m]=new Array(k),C=f[m]=new Array(w);n(_,g,j,N,C,x,t);for(var E=0,T=0,I,K;E<k;++E)if(I=j[E]){for(E>=T&&(T=E+1);!(K=N[T])&&++T<k;);I._next=K||null}}return u=new ri(u,r),u._enter=c,u._exit=f,u}function xA(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function bA(){return new ri(this._exit||this._groups.map(db),this._parents)}function jA(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 kA(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 m=n[f],_=r[f],g=m.length,w=c[f]=new Array(g),x,k=0;k<g;++k)(x=m[k]||_[k])&&(w[k]=x);for(;f<o;++f)c[f]=n[f];return new ri(c,this._parents)}function SA(){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 NA(e){e||(e=CA);function t(g,w){return g&&w?e(g.__data__,w.__data__):!g-!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),m,_=0;_<c;++_)(m=u[_])&&(f[_]=m);f.sort(t)}return new ri(o,this._parents).order()}function CA(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function EA(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function AA(){return Array.from(this)}function $A(){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 TA(){let e=0;for(const t of this)++e;return e}function MA(){return!this.node()}function RA(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 LA(e){return function(){this.removeAttribute(e)}}function IA(e){return function(){this.removeAttributeNS(e.space,e.local)}}function OA(e,t){return function(){this.setAttribute(e,t)}}function PA(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function DA(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function FA(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 zA(e,t){var n=Lm(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?IA:LA:typeof t=="function"?n.local?FA:DA:n.local?PA:OA)(n,t))}function fb(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function BA(e){return function(){this.style.removeProperty(e)}}function UA(e,t,n){return function(){this.style.setProperty(e,t,n)}}function WA(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function qA(e,t,n){return arguments.length>1?this.each((t==null?BA:typeof t=="function"?WA:UA)(e,t,n??"")):Nu(this.node(),e)}function Nu(e,t){return e.style.getPropertyValue(t)||fb(e).getComputedStyle(e,null).getPropertyValue(t)}function HA(e){return function(){delete this[e]}}function VA(e,t){return function(){this[e]=t}}function GA(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function KA(e,t){return arguments.length>1?this.each((t==null?HA:typeof t=="function"?GA:VA)(e,t)):this.node()[e]}function hb(e){return e.trim().split(/^|\s+/)}function Ng(e){return e.classList||new mb(e)}function mb(e){this._node=e,this._names=hb(e.getAttribute("class")||"")}mb.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=Ng(e),r=-1,o=t.length;++r<o;)n.add(t[r])}function pb(e,t){for(var n=Ng(e),r=-1,o=t.length;++r<o;)n.remove(t[r])}function YA(e){return function(){_b(this,e)}}function JA(e){return function(){pb(this,e)}}function XA(e,t){return function(){(t.apply(this,arguments)?_b:pb)(this,e)}}function ZA(e,t){var n=hb(e+"");if(arguments.length<2){for(var r=Ng(this.node()),o=-1,l=n.length;++o<l;)if(!r.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?XA:t?YA:JA)(n,t))}function QA(){this.textContent=""}function e$(e){return function(){this.textContent=e}}function t$(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function n$(e){return arguments.length?this.each(e==null?QA:(typeof e=="function"?t$:e$)(e)):this.node().textContent}function s$(){this.innerHTML=""}function r$(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?s$:(typeof e=="function"?i$:r$)(e)):this.node().innerHTML}function a$(){this.nextSibling&&this.parentNode.appendChild(this)}function l$(){return this.each(a$)}function c$(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function u$(){return this.each(c$)}function d$(e){var t=typeof e=="function"?e:ab(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function f$(){return null}function h$(e,t){var n=typeof e=="function"?e:ab(e),r=t==null?f$:typeof t=="function"?t:Sg(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function m$(){var e=this.parentNode;e&&e.removeChild(this)}function _$(){return this.each(m$)}function p$(){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 y$(e){return this.select(e?g$:p$)}function w$(e){return arguments.length?this.property("__data__",e):this.node().__data__}function v$(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 b$(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 j$(e,t,n){return function(){var r=this.__on,o,l=v$(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 k$(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,m=c.length,_;f<m;++f)for(o=0,_=c[f];o<l;++o)if((u=r[o]).type===_.type&&u.name===_.name)return _.value}return}for(c=t?j$:b$,o=0;o<l;++o)this.each(c(r[o],t,n));return this}function gb(e,t,n){var r=fb(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 S$(e,t){return function(){return gb(this,e,t)}}function N$(e,t){return function(){return gb(this,e,t.apply(this,arguments))}}function C$(e,t){return this.each((typeof t=="function"?N$:S$)(e,t))}function*E$(){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 yb=[null];function ri(e,t){this._groups=e,this._parents=t}function Mf(){return new ri([[document.documentElement]],yb)}function A$(){return this}ri.prototype=Mf.prototype={constructor:ri,select:tA,selectAll:iA,selectChild:cA,selectChildren:hA,filter:mA,data:vA,enter:_A,exit:bA,join:jA,merge:kA,selection:A$,order:SA,sort:NA,call:EA,nodes:AA,node:$A,size:TA,empty:MA,each:RA,attr:zA,style:qA,property:KA,classed:ZA,text:n$,html:o$,raise:l$,lower:u$,append:d$,insert:h$,remove:_$,clone:y$,datum:w$,on:k$,dispatch:C$,[Symbol.iterator]:E$};function ji(e){return typeof e=="string"?new ri([[document.querySelector(e)]],[document.documentElement]):new ri([[e]],yb)}function $$(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Fi(e,t){if(e=$$(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 T$={passive:!1},pf={capture:!0,passive:!1};function H_(e){e.stopImmediatePropagation()}function yu(e){e.preventDefault(),e.stopImmediatePropagation()}function wb(e){var t=e.document.documentElement,n=ji(e).on("dragstart.drag",yu,pf);"onselectstart"in t?n.on("selectstart.drag",yu,pf):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function vb(e,t){var n=e.document.documentElement,r=ji(e).on("dragstart.drag",null);t&&(r.on("click.drag",yu,pf),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 Ph=e=>()=>e;function Pp(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:l,x:u,y:c,dx:f,dy:m,dispatch:_}){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:m,enumerable:!0,configurable:!0},_:{value:_}})}Pp.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function M$(e){return!e.ctrlKey&&!e.button}function R$(){return this.parentNode}function L$(e,t){return t??{x:e.x,y:e.y}}function I$(){return navigator.maxTouchPoints||"ontouchstart"in this}function O$(){var e=M$,t=R$,n=L$,r=I$,o={},l=Rm("start","drag","end"),u=0,c,f,m,_,g=0;function w(I){I.on("mousedown.drag",x).filter(r).on("touchstart.drag",N).on("touchmove.drag",C,T$).on("touchend.drag touchcancel.drag",E).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function x(I,K){if(!(_||!e.call(this,I,K))){var U=T(this,t.call(this,I,K),I,K,"mouse");U&&(ji(I.view).on("mousemove.drag",k,pf).on("mouseup.drag",j,pf),wb(I.view),H_(I),m=!1,c=I.clientX,f=I.clientY,U("start",I))}}function k(I){if(yu(I),!m){var K=I.clientX-c,U=I.clientY-f;m=K*K+U*U>g}o.mouse("drag",I)}function j(I){ji(I.view).on("mousemove.drag mouseup.drag",null),vb(I.view,m),yu(I),o.mouse("end",I)}function N(I,K){if(e.call(this,I,K)){var U=I.changedTouches,J=t.call(this,I,K),Y=U.length,re,ce;for(re=0;re<Y;++re)(ce=T(this,J,I,K,U[re].identifier,U[re]))&&(H_(I),ce("start",I,U[re]))}}function C(I){var K=I.changedTouches,U=K.length,J,Y;for(J=0;J<U;++J)(Y=o[K[J].identifier])&&(yu(I),Y("drag",I,K[J]))}function E(I){var K=I.changedTouches,U=K.length,J,Y;for(_&&clearTimeout(_),_=setTimeout(function(){_=null},500),J=0;J<U;++J)(Y=o[K[J].identifier])&&(H_(I),Y("end",I,K[J]))}function T(I,K,U,J,Y,re){var ce=l.copy(),fe=Fi(re||U,K),W,O,$;if(($=n.call(I,new Pp("beforestart",{sourceEvent:U,target:w,identifier:Y,active:u,x:fe[0],y:fe[1],dx:0,dy:0,dispatch:ce}),J))!=null)return W=$.x-fe[0]||0,O=$.y-fe[1]||0,function z(A,te,P){var F=fe,G;switch(A){case"start":o[Y]=z,G=u++;break;case"end":delete o[Y],--u;case"drag":fe=Fi(P||te,K),G=u;break}ce.call(A,I,new Pp(A,{sourceEvent:te,subject:$,target:w,identifier:Y,active:G,x:fe[0]+W,y:fe[1]+O,dx:fe[0]-F[0],dy:fe[1]-F[1],dispatch:ce}),J)}}return w.filter=function(I){return arguments.length?(e=typeof I=="function"?I:Ph(!!I),w):e},w.container=function(I){return arguments.length?(t=typeof I=="function"?I:Ph(I),w):t},w.subject=function(I){return arguments.length?(n=typeof I=="function"?I:Ph(I),w):n},w.touchable=function(I){return arguments.length?(r=typeof I=="function"?I:Ph(!!I),w):r},w.on=function(){var I=l.on.apply(l,arguments);return I===l?w:I},w.clickDistance=function(I){return arguments.length?(g=(I=+I)*I,w):Math.sqrt(g)},w}function Cg(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function xb(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Rf(){}var gf=.7,pm=1/gf,wu="\\s*([+-]?\\d+)\\s*",yf="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ko="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",P$=/^#([0-9a-f]{3,8})$/,D$=new RegExp(`^rgb\\(${wu},${wu},${wu}\\)$`),F$=new RegExp(`^rgb\\(${ko},${ko},${ko}\\)$`),z$=new RegExp(`^rgba\\(${wu},${wu},${wu},${yf}\\)$`),B$=new RegExp(`^rgba\\(${ko},${ko},${ko},${yf}\\)$`),U$=new RegExp(`^hsl\\(${yf},${ko},${ko}\\)$`),W$=new RegExp(`^hsla\\(${yf},${ko},${ko},${yf}\\)$`),kw={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};Cg(Rf,wf,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Sw,formatHex:Sw,formatHex8:q$,formatHsl:H$,formatRgb:Nw,toString:Nw});function Sw(){return this.rgb().formatHex()}function q$(){return this.rgb().formatHex8()}function H$(){return bb(this).formatHsl()}function Nw(){return this.rgb().formatRgb()}function wf(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=P$.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Cw(t):n===3?new Ur(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Dh(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Dh(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=D$.exec(e))?new Ur(t[1],t[2],t[3],1):(t=F$.exec(e))?new Ur(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=z$.exec(e))?Dh(t[1],t[2],t[3],t[4]):(t=B$.exec(e))?Dh(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=U$.exec(e))?$w(t[1],t[2]/100,t[3]/100,1):(t=W$.exec(e))?$w(t[1],t[2]/100,t[3]/100,t[4]):kw.hasOwnProperty(e)?Cw(kw[e]):e==="transparent"?new Ur(NaN,NaN,NaN,0):null}function Cw(e){return new Ur(e>>16&255,e>>8&255,e&255,1)}function Dh(e,t,n,r){return r<=0&&(e=t=n=NaN),new Ur(e,t,n,r)}function V$(e){return e instanceof Rf||(e=wf(e)),e?(e=e.rgb(),new Ur(e.r,e.g,e.b,e.opacity)):new Ur}function Dp(e,t,n,r){return arguments.length===1?V$(e):new Ur(e,t,n,r??1)}function Ur(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Cg(Ur,Dp,xb(Rf,{brighter(e){return e=e==null?pm:Math.pow(pm,e),new Ur(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?gf:Math.pow(gf,e),new Ur(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Ur(nc(this.r),nc(this.g),nc(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:Ew,formatHex:Ew,formatHex8:G$,formatRgb:Aw,toString:Aw}));function Ew(){return`#${Jl(this.r)}${Jl(this.g)}${Jl(this.b)}`}function G$(){return`#${Jl(this.r)}${Jl(this.g)}${Jl(this.b)}${Jl((isNaN(this.opacity)?1:this.opacity)*255)}`}function Aw(){const e=gm(this.opacity);return`${e===1?"rgb(":"rgba("}${nc(this.r)}, ${nc(this.g)}, ${nc(this.b)}${e===1?")":`, ${e})`}`}function gm(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function nc(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Jl(e){return e=nc(e),(e<16?"0":"")+e.toString(16)}function $w(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Ui(e,t,n,r)}function bb(e){if(e instanceof Ui)return new Ui(e.h,e.s,e.l,e.opacity);if(e instanceof Rf||(e=wf(e)),!e)return new Ui;if(e instanceof Ui)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 Ui(u,c,f,e.opacity)}function K$(e,t,n,r){return arguments.length===1?bb(e):new Ui(e,t,n,r??1)}function Ui(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Cg(Ui,K$,xb(Rf,{brighter(e){return e=e==null?pm:Math.pow(pm,e),new Ui(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?gf:Math.pow(gf,e),new Ui(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 Ur(V_(e>=240?e-240:e+120,o,r),V_(e,o,r),V_(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new Ui(Tw(this.h),Fh(this.s),Fh(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("}${Tw(this.h)}, ${Fh(this.s)*100}%, ${Fh(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Tw(e){return e=(e||0)%360,e<0?e+360:e}function Fh(e){return Math.max(0,Math.min(1,e||0))}function V_(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 jb=e=>()=>e;function Y$(e,t){return function(n){return e+n*t}}function J$(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 X$(e){return(e=+e)==1?kb:function(t,n){return n-t?J$(t,n,e):jb(isNaN(t)?n:t)}}function kb(e,t){var n=t-e;return n?Y$(e,n):jb(isNaN(e)?t:e)}const Mw=(function e(t){var n=X$(t);function r(o,l){var u=n((o=Dp(o)).r,(l=Dp(l)).r),c=n(o.g,l.g),f=n(o.b,l.b),m=kb(o.opacity,l.opacity);return function(_){return o.r=u(_),o.g=c(_),o.b=f(_),o.opacity=m(_),o+""}}return r.gamma=e,r})(1);function sl(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var Fp=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,G_=new RegExp(Fp.source,"g");function Z$(e){return function(){return e}}function Q$(e){return function(t){return e(t)+""}}function eT(e,t){var n=Fp.lastIndex=G_.lastIndex=0,r,o,l,u=-1,c=[],f=[];for(e=e+"",t=t+"";(r=Fp.exec(e))&&(o=G_.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:sl(r,o)})),n=G_.lastIndex;return n<t.length&&(l=t.slice(n),c[u]?c[u]+=l:c[++u]=l),c.length<2?f[0]?Q$(f[0].x):Z$(t):(t=f.length,function(m){for(var _=0,g;_<t;++_)c[(g=f[_]).i]=g.x(m);return c.join("")})}var Rw=180/Math.PI,zp={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Sb(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)*Rw,skewX:Math.atan(f)*Rw,scaleX:u,scaleY:c}}var zh;function tT(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?zp:Sb(t.a,t.b,t.c,t.d,t.e,t.f)}function nT(e){return e==null||(zh||(zh=document.createElementNS("http://www.w3.org/2000/svg","g")),zh.setAttribute("transform",e),!(e=zh.transform.baseVal.consolidate()))?zp:(e=e.matrix,Sb(e.a,e.b,e.c,e.d,e.e,e.f))}function Nb(e,t,n,r){function o(m){return m.length?m.pop()+" ":""}function l(m,_,g,w,x,k){if(m!==g||_!==w){var j=x.push("translate(",null,t,null,n);k.push({i:j-4,x:sl(m,g)},{i:j-2,x:sl(_,w)})}else(g||w)&&x.push("translate("+g+t+w+n)}function u(m,_,g,w){m!==_?(m-_>180?_+=360:_-m>180&&(m+=360),w.push({i:g.push(o(g)+"rotate(",null,r)-2,x:sl(m,_)})):_&&g.push(o(g)+"rotate("+_+r)}function c(m,_,g,w){m!==_?w.push({i:g.push(o(g)+"skewX(",null,r)-2,x:sl(m,_)}):_&&g.push(o(g)+"skewX("+_+r)}function f(m,_,g,w,x,k){if(m!==g||_!==w){var j=x.push(o(x)+"scale(",null,",",null,")");k.push({i:j-4,x:sl(m,g)},{i:j-2,x:sl(_,w)})}else(g!==1||w!==1)&&x.push(o(x)+"scale("+g+","+w+")")}return function(m,_){var g=[],w=[];return m=e(m),_=e(_),l(m.translateX,m.translateY,_.translateX,_.translateY,g,w),u(m.rotate,_.rotate,g,w),c(m.skewX,_.skewX,g,w),f(m.scaleX,m.scaleY,_.scaleX,_.scaleY,g,w),m=_=null,function(x){for(var k=-1,j=w.length,N;++k<j;)g[(N=w[k]).i]=N.x(x);return g.join("")}}}var sT=Nb(tT,"px, ","px)","deg)"),rT=Nb(nT,", ",")",")"),iT=1e-12;function Lw(e){return((e=Math.exp(e))+1/e)/2}function oT(e){return((e=Math.exp(e))-1/e)/2}function aT(e){return((e=Math.exp(2*e))-1)/(e+1)}const lT=(function e(t,n,r){function o(l,u){var c=l[0],f=l[1],m=l[2],_=u[0],g=u[1],w=u[2],x=_-c,k=g-f,j=x*x+k*k,N,C;if(j<iT)C=Math.log(w/m)/t,N=function(J){return[c+J*x,f+J*k,m*Math.exp(t*J*C)]};else{var E=Math.sqrt(j),T=(w*w-m*m+r*j)/(2*m*n*E),I=(w*w-m*m-r*j)/(2*w*n*E),K=Math.log(Math.sqrt(T*T+1)-T),U=Math.log(Math.sqrt(I*I+1)-I);C=(U-K)/t,N=function(J){var Y=J*C,re=Lw(K),ce=m/(n*E)*(re*aT(t*Y+K)-oT(K));return[c+ce*x,f+ce*k,m*re/Lw(t*Y+K)]}}return N.duration=C*1e3*t/Math.SQRT2,N}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 Cu=0,of=0,Kd=0,Cb=1e3,ym,af,wm=0,lc=0,Im=0,vf=typeof performance=="object"&&performance.now?performance:Date,Eb=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Eg(){return lc||(Eb(cT),lc=vf.now()+Im)}function cT(){lc=0}function vm(){this._call=this._time=this._next=null}vm.prototype=Ab.prototype={constructor:vm,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Eg():+n)+(t==null?0:+t),!this._next&&af!==this&&(af?af._next=this:ym=this,af=this),this._call=e,this._time=n,Bp()},stop:function(){this._call&&(this._call=null,this._time=1/0,Bp())}};function Ab(e,t,n){var r=new vm;return r.restart(e,t,n),r}function uT(){Eg(),++Cu;for(var e=ym,t;e;)(t=lc-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Cu}function Iw(){lc=(wm=vf.now())+Im,Cu=of=0;try{uT()}finally{Cu=0,fT(),lc=0}}function dT(){var e=vf.now(),t=e-wm;t>Cb&&(Im-=t,wm=e)}function fT(){for(var e,t=ym,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:ym=n);af=e,Bp(r)}function Bp(e){if(!Cu){of&&(of=clearTimeout(of));var t=e-lc;t>24?(e<1/0&&(of=setTimeout(Iw,e-vf.now()-Im)),Kd&&(Kd=clearInterval(Kd))):(Kd||(wm=vf.now(),Kd=setInterval(dT,Cb)),Cu=1,Eb(Iw))}}function Ow(e,t,n){var r=new vm;return t=t==null?0:+t,r.restart(o=>{r.stop(),e(o+t)},t,n),r}var hT=Rm("start","end","cancel","interrupt"),mT=[],$b=0,Pw=1,Up=2,tm=3,Dw=4,Wp=5,nm=6;function Om(e,t,n,r,o,l){var u=e.__transition;if(!u)e.__transition={};else if(n in u)return;_T(e,n,{name:t,index:r,group:o,on:hT,tween:mT,time:l.time,delay:l.delay,duration:l.duration,ease:l.ease,timer:null,state:$b})}function Ag(e,t){var n=Hi(e,t);if(n.state>$b)throw new Error("too late; already scheduled");return n}function Co(e,t){var n=Hi(e,t);if(n.state>tm)throw new Error("too late; already running");return n}function Hi(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function _T(e,t,n){var r=e.__transition,o;r[t]=n,n.timer=Ab(l,0,n.time);function l(m){n.state=Pw,n.timer.restart(u,n.delay,n.time),n.delay<=m&&u(m-n.delay)}function u(m){var _,g,w,x;if(n.state!==Pw)return f();for(_ in r)if(x=r[_],x.name===n.name){if(x.state===tm)return Ow(u);x.state===Dw?(x.state=nm,x.timer.stop(),x.on.call("interrupt",e,e.__data__,x.index,x.group),delete r[_]):+_<t&&(x.state=nm,x.timer.stop(),x.on.call("cancel",e,e.__data__,x.index,x.group),delete r[_])}if(Ow(function(){n.state===tm&&(n.state=Dw,n.timer.restart(c,n.delay,n.time),c(m))}),n.state=Up,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Up){for(n.state=tm,o=new Array(w=n.tween.length),_=0,g=-1;_<w;++_)(x=n.tween[_].value.call(e,e.__data__,n.index,n.group))&&(o[++g]=x);o.length=g+1}}function c(m){for(var _=m<n.duration?n.ease.call(null,m/n.duration):(n.timer.restart(f),n.state=Wp,1),g=-1,w=o.length;++g<w;)o[g].call(e,_);n.state===Wp&&(n.on.call("end",e,e.__data__,n.index,n.group),f())}function f(){n.state=nm,n.timer.stop(),delete r[t];for(var m in r)return;delete e.__transition}}function sm(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>Up&&r.state<Wp,r.state=nm,r.timer.stop(),r.on.call(o?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[u]}l&&delete e.__transition}}function pT(e){return this.each(function(){sm(this,e)})}function gT(e,t){var n,r;return function(){var o=Co(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 yT(e,t,n){var r,o;if(typeof n!="function")throw new Error;return function(){var l=Co(this,e),u=l.tween;if(u!==r){o=(r=u).slice();for(var c={name:t,value:n},f=0,m=o.length;f<m;++f)if(o[f].name===t){o[f]=c;break}f===m&&o.push(c)}l.tween=o}}function wT(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Hi(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?gT:yT)(n,e,t))}function $g(e,t,n){var r=e._id;return e.each(function(){var o=Co(this,r);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return Hi(o,r).value[t]}}function Tb(e,t){var n;return(typeof t=="number"?sl:t instanceof wf?Mw:(n=wf(t))?(t=n,Mw):eT)(e,t)}function vT(e){return function(){this.removeAttribute(e)}}function xT(e){return function(){this.removeAttributeNS(e.space,e.local)}}function bT(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 jT(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 kT(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 ST(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=Lm(e),r=n==="transform"?rT:Tb;return this.attrTween(e,typeof t=="function"?(n.local?ST:kT)(n,r,$g(this,"attr."+e,t)):t==null?(n.local?xT:vT)(n):(n.local?jT:bT)(n,r,t))}function CT(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function ET(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function AT(e,t){var n,r;function o(){var l=t.apply(this,arguments);return l!==r&&(n=(r=l)&&ET(e,l)),n}return o._value=t,o}function $T(e,t){var n,r;function o(){var l=t.apply(this,arguments);return l!==r&&(n=(r=l)&&CT(e,l)),n}return o._value=t,o}function TT(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=Lm(e);return this.tween(n,(r.local?AT:$T)(r,t))}function MT(e,t){return function(){Ag(this,e).delay=+t.apply(this,arguments)}}function RT(e,t){return t=+t,function(){Ag(this,e).delay=t}}function LT(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?MT:RT)(t,e)):Hi(this.node(),t).delay}function IT(e,t){return function(){Co(this,e).duration=+t.apply(this,arguments)}}function OT(e,t){return t=+t,function(){Co(this,e).duration=t}}function PT(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?IT:OT)(t,e)):Hi(this.node(),t).duration}function DT(e,t){if(typeof t!="function")throw new Error;return function(){Co(this,e).ease=t}}function FT(e){var t=this._id;return arguments.length?this.each(DT(t,e)):Hi(this.node(),t).ease}function zT(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Co(this,e).ease=n}}function BT(e){if(typeof e!="function")throw new Error;return this.each(zT(this._id,e))}function UT(e){typeof e!="function"&&(e=cb(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,m=0;m<u;++m)(f=l[m])&&e.call(f,f.__data__,m,l)&&c.push(f);return new ca(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],m=n[c],_=f.length,g=u[c]=new Array(_),w,x=0;x<_;++x)(w=f[x]||m[x])&&(g[x]=w);for(;c<r;++c)u[c]=t[c];return new ca(u,this._parents,this._name,this._id)}function qT(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 HT(e,t,n){var r,o,l=qT(t)?Ag:Co;return function(){var u=l(this,e),c=u.on;c!==r&&(o=(r=c).copy()).on(t,n),u.on=o}}function VT(e,t){var n=this._id;return arguments.length<2?Hi(this.node(),n).on.on(e):this.each(HT(n,e,t))}function GT(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function KT(){return this.on("end.remove",GT(this._id))}function YT(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Sg(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,m=l[u]=new Array(f),_,g,w=0;w<f;++w)(_=c[w])&&(g=e.call(_,_.__data__,w,c))&&("__data__"in _&&(g.__data__=_.__data__),m[w]=g,Om(m[w],t,n,w,m,Hi(_,n)));return new ca(l,this._parents,t,n)}function JT(e){var t=this._name,n=this._id;typeof e!="function"&&(e=lb(e));for(var r=this._groups,o=r.length,l=[],u=[],c=0;c<o;++c)for(var f=r[c],m=f.length,_,g=0;g<m;++g)if(_=f[g]){for(var w=e.call(_,_.__data__,g,f),x,k=Hi(_,n),j=0,N=w.length;j<N;++j)(x=w[j])&&Om(x,t,n,j,w,k);l.push(w),u.push(_)}return new ca(l,u,t,n)}var XT=Mf.prototype.constructor;function ZT(){return new XT(this._groups,this._parents)}function QT(e,t){var n,r,o;return function(){var l=Nu(this,e),u=(this.style.removeProperty(e),Nu(this,e));return l===u?null:l===n&&u===r?o:o=t(n=l,r=u)}}function Mb(e){return function(){this.style.removeProperty(e)}}function eM(e,t,n){var r,o=n+"",l;return function(){var u=Nu(this,e);return u===o?null:u===r?l:l=t(r=u,n)}}function tM(e,t,n){var r,o,l;return function(){var u=Nu(this,e),c=n(this),f=c+"";return c==null&&(f=c=(this.style.removeProperty(e),Nu(this,e))),u===f?null:u===r&&f===o?l:(o=f,l=t(r=u,c))}}function nM(e,t){var n,r,o,l="style."+t,u="end."+l,c;return function(){var f=Co(this,e),m=f.on,_=f.value[l]==null?c||(c=Mb(t)):void 0;(m!==n||o!==_)&&(r=(n=m).copy()).on(u,o=_),f.on=r}}function sM(e,t,n){var r=(e+="")=="transform"?sT:Tb;return t==null?this.styleTween(e,QT(e,r)).on("end.style."+e,Mb(e)):typeof t=="function"?this.styleTween(e,tM(e,r,$g(this,"style."+e,t))).each(nM(this._id,e)):this.styleTween(e,eM(e,r,t),n).on("end.style."+e,null)}function rM(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function iM(e,t,n){var r,o;function l(){var u=t.apply(this,arguments);return u!==o&&(r=(o=u)&&rM(e,u,n)),r}return l._value=t,l}function oM(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,iM(e,t,n??""))}function aM(e){return function(){this.textContent=e}}function lM(e){return function(){var t=e(this);this.textContent=t??""}}function cM(e){return this.tween("text",typeof e=="function"?lM($g(this,"text",e)):aM(e==null?"":e+""))}function uM(e){return function(t){this.textContent=e.call(this,t)}}function dM(e){var t,n;function r(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&uM(o)),t}return r._value=e,r}function fM(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,dM(e))}function hM(){for(var e=this._name,t=this._id,n=Rb(),r=this._groups,o=r.length,l=0;l<o;++l)for(var u=r[l],c=u.length,f,m=0;m<c;++m)if(f=u[m]){var _=Hi(f,t);Om(f,e,n,m,u,{time:_.time+_.delay+_.duration,delay:0,duration:_.duration,ease:_.ease})}return new ca(r,this._parents,e,n)}function mM(){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 m=Co(this,r),_=m.on;_!==e&&(t=(e=_).copy(),t._.cancel.push(c),t._.interrupt.push(c),t._.end.push(f)),m.on=t}),o===0&&l()})}var _M=0;function ca(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Rb(){return++_M}var sa=Mf.prototype;ca.prototype={constructor:ca,select:YT,selectAll:JT,selectChild:sa.selectChild,selectChildren:sa.selectChildren,filter:UT,merge:WT,selection:ZT,transition:hM,call:sa.call,nodes:sa.nodes,node:sa.node,size:sa.size,empty:sa.empty,each:sa.each,on:VT,attr:NT,attrTween:TT,style:sM,styleTween:oM,text:cM,textTween:fM,remove:KT,tween:wT,delay:LT,duration:PT,ease:FT,easeVarying:BT,end:mM,[Symbol.iterator]:sa[Symbol.iterator]};function pM(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var gM={time:null,delay:0,duration:250,ease:pM};function yM(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 wM(e){var t,n;e instanceof ca?(t=e._id,e=e._name):(t=Rb(),(n=gM).time=Eg(),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,m=0;m<c;++m)(f=u[m])&&Om(f,e,t,m,u,n||yM(f,t));return new ca(r,this._parents,e,t)}Mf.prototype.interrupt=pT;Mf.prototype.transition=wM;const Bh=e=>()=>e;function vM(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 oa(e,t,n){this.k=e,this.x=t,this.y=n}oa.prototype={constructor:oa,scale:function(e){return e===1?this:new oa(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new oa(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 aa=new oa(1,0,0);oa.prototype;function K_(e){e.stopImmediatePropagation()}function Yd(e){e.preventDefault(),e.stopImmediatePropagation()}function xM(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function bM(){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 Fw(){return this.__zoom||aa}function jM(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function kM(){return navigator.maxTouchPoints||"ontouchstart"in this}function SM(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 Lb(){var e=xM,t=bM,n=SM,r=jM,o=kM,l=[0,1/0],u=[[-1/0,-1/0],[1/0,1/0]],c=250,f=lT,m=Rm("start","zoom","end"),_,g,w,x=500,k=150,j=0,N=10;function C($){$.property("__zoom",Fw).on("wheel.zoom",Y,{passive:!1}).on("mousedown.zoom",re).on("dblclick.zoom",ce).filter(o).on("touchstart.zoom",fe).on("touchmove.zoom",W).on("touchend.zoom touchcancel.zoom",O).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}C.transform=function($,z,A,te){var P=$.selection?$.selection():$;P.property("__zoom",Fw),$!==P?K($,z,A,te):P.interrupt().each(function(){U(this,arguments).event(te).start().zoom(null,typeof z=="function"?z.apply(this,arguments):z).end()})},C.scaleBy=function($,z,A,te){C.scaleTo($,function(){var P=this.__zoom.k,F=typeof z=="function"?z.apply(this,arguments):z;return P*F},A,te)},C.scaleTo=function($,z,A,te){C.transform($,function(){var P=t.apply(this,arguments),F=this.__zoom,G=A==null?I(P):typeof A=="function"?A.apply(this,arguments):A,R=F.invert(G),Z=typeof z=="function"?z.apply(this,arguments):z;return n(T(E(F,Z),G,R),P,u)},A,te)},C.translateBy=function($,z,A,te){C.transform($,function(){return n(this.__zoom.translate(typeof z=="function"?z.apply(this,arguments):z,typeof A=="function"?A.apply(this,arguments):A),t.apply(this,arguments),u)},null,te)},C.translateTo=function($,z,A,te,P){C.transform($,function(){var F=t.apply(this,arguments),G=this.__zoom,R=te==null?I(F):typeof te=="function"?te.apply(this,arguments):te;return n(aa.translate(R[0],R[1]).scale(G.k).translate(typeof z=="function"?-z.apply(this,arguments):-z,typeof A=="function"?-A.apply(this,arguments):-A),F,u)},te,P)};function E($,z){return z=Math.max(l[0],Math.min(l[1],z)),z===$.k?$:new oa(z,$.x,$.y)}function T($,z,A){var te=z[0]-A[0]*$.k,P=z[1]-A[1]*$.k;return te===$.x&&P===$.y?$:new oa($.k,te,P)}function I($){return[(+$[0][0]+ +$[1][0])/2,(+$[0][1]+ +$[1][1])/2]}function K($,z,A,te){$.on("start.zoom",function(){U(this,arguments).event(te).start()}).on("interrupt.zoom end.zoom",function(){U(this,arguments).event(te).end()}).tween("zoom",function(){var P=this,F=arguments,G=U(P,F).event(te),R=t.apply(P,F),Z=A==null?I(R):typeof A=="function"?A.apply(P,F):A,X=Math.max(R[1][0]-R[0][0],R[1][1]-R[0][1]),Q=P.__zoom,le=typeof z=="function"?z.apply(P,F):z,ge=f(Q.invert(Z).concat(X/Q.k),le.invert(Z).concat(X/le.k));return function(pe){if(pe===1)pe=le;else{var ye=ge(pe),Ne=X/ye[2];pe=new oa(Ne,Z[0]-ye[0]*Ne,Z[1]-ye[1]*Ne)}G.zoom(null,pe)}})}function U($,z,A){return!A&&$.__zooming||new J($,z)}function J($,z){this.that=$,this.args=z,this.active=0,this.sourceEvent=null,this.extent=t.apply($,z),this.taps=0}J.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=ji(this.that).datum();m.call($,this.that,new vM($,{sourceEvent:this.sourceEvent,target:C,transform:this.that.__zoom,dispatch:m}),z)}};function Y($,...z){if(!e.apply(this,arguments))return;var A=U(this,z).event($),te=this.__zoom,P=Math.max(l[0],Math.min(l[1],te.k*Math.pow(2,r.apply(this,arguments)))),F=Fi($);if(A.wheel)(A.mouse[0][0]!==F[0]||A.mouse[0][1]!==F[1])&&(A.mouse[1]=te.invert(A.mouse[0]=F)),clearTimeout(A.wheel);else{if(te.k===P)return;A.mouse=[F,te.invert(F)],sm(this),A.start()}Yd($),A.wheel=setTimeout(G,k),A.zoom("mouse",n(T(E(te,P),A.mouse[0],A.mouse[1]),A.extent,u));function G(){A.wheel=null,A.end()}}function re($,...z){if(w||!e.apply(this,arguments))return;var A=$.currentTarget,te=U(this,z,!0).event($),P=ji($.view).on("mousemove.zoom",Z,!0).on("mouseup.zoom",X,!0),F=Fi($,A),G=$.clientX,R=$.clientY;wb($.view),K_($),te.mouse=[F,this.__zoom.invert(F)],sm(this),te.start();function Z(Q){if(Yd(Q),!te.moved){var le=Q.clientX-G,ge=Q.clientY-R;te.moved=le*le+ge*ge>j}te.event(Q).zoom("mouse",n(T(te.that.__zoom,te.mouse[0]=Fi(Q,A),te.mouse[1]),te.extent,u))}function X(Q){P.on("mousemove.zoom mouseup.zoom",null),vb(Q.view,te.moved),Yd(Q),te.event(Q).end()}}function ce($,...z){if(e.apply(this,arguments)){var A=this.__zoom,te=Fi($.changedTouches?$.changedTouches[0]:$,this),P=A.invert(te),F=A.k*($.shiftKey?.5:2),G=n(T(E(A,F),te,P),t.apply(this,z),u);Yd($),c>0?ji(this).transition().duration(c).call(K,G,te,$):ji(this).call(C.transform,G,te,$)}}function fe($,...z){if(e.apply(this,arguments)){var A=$.touches,te=A.length,P=U(this,z,$.changedTouches.length===te).event($),F,G,R,Z;for(K_($),G=0;G<te;++G)R=A[G],Z=Fi(R,this),Z=[Z,this.__zoom.invert(Z),R.identifier],P.touch0?!P.touch1&&P.touch0[2]!==Z[2]&&(P.touch1=Z,P.taps=0):(P.touch0=Z,F=!0,P.taps=1+!!_);_&&(_=clearTimeout(_)),F&&(P.taps<2&&(g=Z[0],_=setTimeout(function(){_=null},x)),sm(this),P.start())}}function W($,...z){if(this.__zooming){var A=U(this,z).event($),te=$.changedTouches,P=te.length,F,G,R,Z;for(Yd($),F=0;F<P;++F)G=te[F],R=Fi(G,this),A.touch0&&A.touch0[2]===G.identifier?A.touch0[0]=R:A.touch1&&A.touch1[2]===G.identifier&&(A.touch1[0]=R);if(G=A.that.__zoom,A.touch1){var X=A.touch0[0],Q=A.touch0[1],le=A.touch1[0],ge=A.touch1[1],pe=(pe=le[0]-X[0])*pe+(pe=le[1]-X[1])*pe,ye=(ye=ge[0]-Q[0])*ye+(ye=ge[1]-Q[1])*ye;G=E(G,Math.sqrt(pe/ye)),R=[(X[0]+le[0])/2,(X[1]+le[1])/2],Z=[(Q[0]+ge[0])/2,(Q[1]+ge[1])/2]}else if(A.touch0)R=A.touch0[0],Z=A.touch0[1];else return;A.zoom("touch",n(T(G,R,Z),A.extent,u))}}function O($,...z){if(this.__zooming){var A=U(this,z).event($),te=$.changedTouches,P=te.length,F,G;for(K_($),w&&clearTimeout(w),w=setTimeout(function(){w=null},x),F=0;F<P;++F)G=te[F],A.touch0&&A.touch0[2]===G.identifier?delete A.touch0:A.touch1&&A.touch1[2]===G.identifier&&delete A.touch1;if(A.touch1&&!A.touch0&&(A.touch0=A.touch1,delete A.touch1),A.touch0)A.touch0[1]=this.__zoom.invert(A.touch0[0]);else if(A.end(),A.taps===2&&(G=Fi(G,this),Math.hypot(g[0]-G[0],g[1]-G[1])<N)){var R=ji(this).on("dblclick.zoom");R&&R.apply(this,arguments)}}}return C.wheelDelta=function($){return arguments.length?(r=typeof $=="function"?$:Bh(+$),C):r},C.filter=function($){return arguments.length?(e=typeof $=="function"?$:Bh(!!$),C):e},C.touchable=function($){return arguments.length?(o=typeof $=="function"?$:Bh(!!$),C):o},C.extent=function($){return arguments.length?(t=typeof $=="function"?$:Bh([[+$[0][0],+$[0][1]],[+$[1][0],+$[1][1]]]),C):t},C.scaleExtent=function($){return arguments.length?(l[0]=+$[0],l[1]=+$[1],C):[l[0],l[1]]},C.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],C):[[u[0][0],u[0][1]],[u[1][0],u[1][1]]]},C.constrain=function($){return arguments.length?(n=$,C):n},C.duration=function($){return arguments.length?(c=+$,C):c},C.interpolate=function($){return arguments.length?(f=$,C):f},C.on=function(){var $=m.on.apply(m,arguments);return $===m?C:$},C.clickDistance=function($){return arguments.length?(j=($=+$)*$,C):Math.sqrt(j)},C.tapDistance=function($){return arguments.length?(N=+$,C):N},C}const Pm=p.createContext(null),NM=Pm.Provider,ua={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.`},Ib=ua.error001();function Ln(e,t){const n=p.useContext(Pm);if(n===null)throw new Error(Ib);return ob(n,e,t)}const bs=()=>{const e=p.useContext(Pm);if(e===null)throw new Error(Ib);return p.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},CM=e=>e.userSelectionActive?"none":"all";function xf({position:e,children:t,className:n,style:r,...o}){const l=Ln(CM),u=`${e}`.split("-");return ve.createElement("div",{className:Ks(["react-flow__panel",n,...u]),style:{...r,pointerEvents:l},...o},t)}function EM({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:ve.createElement(xf,{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 AM=({x:e,y:t,label:n,labelStyle:r={},labelShowBg:o=!0,labelBgStyle:l={},labelBgPadding:u=[2,4],labelBgBorderRadius:c=2,children:f,className:m,..._})=>{const g=p.useRef(null),[w,x]=p.useState({x:0,y:0,width:0,height:0}),k=Ks(["react-flow__edge-textwrapper",m]);return p.useEffect(()=>{if(g.current){const j=g.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:k,visibility:w.width?"visible":"hidden",..._},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:g,style:r},n),f)};var $M=p.memo(AM);const Tg=e=>({width:e.offsetWidth,height:e.offsetHeight}),Eu=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Mg=(e={x:0,y:0},t)=>({x:Eu(e.x,t[0][0],t[1][0]),y:Eu(e.y,t[0][1],t[1][1])}),zw=(e,t,n)=>e<t?Eu(Math.abs(e-t),1,50)/50:e>n?-Eu(Math.abs(e-n),1,50)/50:0,Ob=(e,t)=>{const n=zw(e.x,35,t.width-35)*20,r=zw(e.y,35,t.height-35)*20;return[n,r]},Pb=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},Db=(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)}),bf=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Fb=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Bw=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),TM=(e,t)=>Fb(Db(bf(e),bf(t))),qp=(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)},MM=e=>ki(e.width)&&ki(e.height)&&ki(e.x)&&ki(e.y),ki=e=>!isNaN(e)&&isFinite(e),fs=Symbol.for("internals"),zb=["Enter"," ","Escape"],RM=(e,t)=>{},LM=e=>"nativeEvent"in e;function Hp(e){var o,l;const t=LM(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 Bb=e=>"clientX"in e,ol=(e,t)=>{var l,u;const n=Bb(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},Lf=({id:e,path:t,labelX:n,labelY:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:_,markerEnd:g,markerStart:w,interactionWidth:x=20})=>ve.createElement(ve.Fragment,null,ve.createElement("path",{id:e,style:_,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:g,markerStart:w}),x&&ve.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:x,className:"react-flow__edge-interaction"}),o&&ki(n)&&ki(r)?ve.createElement($M,{x:n,y:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m}):null);Lf.displayName="BaseEdge";function Jd(e,t,n){return n===void 0?n:r=>{const o=t().edges.find(l=>l.id===e);o&&n(r,{...o})}}function Ub({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 Wb({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,m=t*.125+l*.375+c*.375+r*.125,_=Math.abs(f-e),g=Math.abs(m-t);return[f,m,_,g]}var cc;(function(e){e.Strict="strict",e.Loose="loose"})(cc||(cc={}));var Xl;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Xl||(Xl={}));var jf;(function(e){e.Partial="partial",e.Full="full"})(jf||(jf={}));var il;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(il||(il={}));var kf;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(kf||(kf={}));var _t;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(_t||(_t={}));function Uw({pos:e,x1:t,y1:n,x2:r,y2:o}){return e===_t.Left||e===_t.Right?[.5*(t+r),n]:[t,.5*(n+o)]}function qb({sourceX:e,sourceY:t,sourcePosition:n=_t.Bottom,targetX:r,targetY:o,targetPosition:l=_t.Top}){const[u,c]=Uw({pos:n,x1:e,y1:t,x2:r,y2:o}),[f,m]=Uw({pos:l,x1:r,y1:o,x2:e,y2:t}),[_,g,w,x]=Wb({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:u,sourceControlY:c,targetControlX:f,targetControlY:m});return[`M${e},${t} C${u},${c} ${f},${m} ${r},${o}`,_,g,w,x]}const Rg=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:o=_t.Bottom,targetPosition:l=_t.Top,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:m,labelBgPadding:_,labelBgBorderRadius:g,style:w,markerEnd:x,markerStart:k,interactionWidth:j})=>{const[N,C,E]=qb({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:r,targetPosition:l});return ve.createElement(Lf,{path:N,labelX:C,labelY:E,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:m,labelBgPadding:_,labelBgBorderRadius:g,style:w,markerEnd:x,markerStart:k,interactionWidth:j})});Rg.displayName="SimpleBezierEdge";const Ww={[_t.Left]:{x:-1,y:0},[_t.Right]:{x:1,y:0},[_t.Top]:{x:0,y:-1},[_t.Bottom]:{x:0,y:1}},IM=({source:e,sourcePosition:t=_t.Bottom,target:n})=>t===_t.Left||t===_t.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},qw=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function OM({source:e,sourcePosition:t=_t.Bottom,target:n,targetPosition:r=_t.Top,center:o,offset:l}){const u=Ww[t],c=Ww[r],f={x:e.x+u.x*l,y:e.y+u.y*l},m={x:n.x+c.x*l,y:n.y+c.y*l},_=IM({source:f,sourcePosition:t,target:m}),g=_.x!==0?"x":"y",w=_[g];let x=[],k,j;const N={x:0,y:0},C={x:0,y:0},[E,T,I,K]=Ub({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(u[g]*c[g]===-1){k=o.x||E,j=o.y||T;const J=[{x:k,y:f.y},{x:k,y:m.y}],Y=[{x:f.x,y:j},{x:m.x,y:j}];u[g]===w?x=g==="x"?J:Y:x=g==="x"?Y:J}else{const J=[{x:f.x,y:m.y}],Y=[{x:m.x,y:f.y}];if(g==="x"?x=u.x===w?Y:J:x=u.y===w?J:Y,t===r){const O=Math.abs(e[g]-n[g]);if(O<=l){const $=Math.min(l-1,l-O);u[g]===w?N[g]=(f[g]>e[g]?-1:1)*$:C[g]=(m[g]>n[g]?-1:1)*$}}if(t!==r){const O=g==="x"?"y":"x",$=u[g]===c[O],z=f[O]>m[O],A=f[O]<m[O];(u[g]===1&&(!$&&z||$&&A)||u[g]!==1&&(!$&&A||$&&z))&&(x=g==="x"?J:Y)}const re={x:f.x+N.x,y:f.y+N.y},ce={x:m.x+C.x,y:m.y+C.y},fe=Math.max(Math.abs(re.x-x[0].x),Math.abs(ce.x-x[0].x)),W=Math.max(Math.abs(re.y-x[0].y),Math.abs(ce.y-x[0].y));fe>=W?(k=(re.x+ce.x)/2,j=x[0].y):(k=x[0].x,j=(re.y+ce.y)/2)}return[[e,{x:f.x+N.x,y:f.y+N.y},...x,{x:m.x+C.x,y:m.y+C.y},n],k,j,I,K]}function PM(e,t,n,r){const o=Math.min(qw(e,t)/2,qw(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 m=e.x<n.x?-1:1,_=e.y<n.y?1:-1;return`L ${l+o*m},${u}Q ${l},${u} ${l},${u+o*_}`}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 Vp({sourceX:e,sourceY:t,sourcePosition:n=_t.Bottom,targetX:r,targetY:o,targetPosition:l=_t.Top,borderRadius:u=5,centerX:c,centerY:f,offset:m=20}){const[_,g,w,x,k]=OM({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:l,center:{x:c,y:f},offset:m});return[_.reduce((N,C,E)=>{let T="";return E>0&&E<_.length-1?T=PM(_[E-1],C,_[E+1],u):T=`${E===0?"M":"L"}${C.x} ${C.y}`,N+=T,N},""),g,w,x,k]}const Dm=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:_,sourcePosition:g=_t.Bottom,targetPosition:w=_t.Top,markerEnd:x,markerStart:k,pathOptions:j,interactionWidth:N})=>{const[C,E,T]=Vp({sourceX:e,sourceY:t,sourcePosition:g,targetX:n,targetY:r,targetPosition:w,borderRadius:j==null?void 0:j.borderRadius,offset:j==null?void 0:j.offset});return ve.createElement(Lf,{path:C,labelX:E,labelY:T,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:_,markerEnd:x,markerStart:k,interactionWidth:N})});Dm.displayName="SmoothStepEdge";const Lg=p.memo(e=>{var t;return ve.createElement(Dm,{...e,pathOptions:p.useMemo(()=>{var n;return{borderRadius:0,offset:(n=e.pathOptions)==null?void 0:n.offset}},[(t=e.pathOptions)==null?void 0:t.offset])})});Lg.displayName="StepEdge";function DM({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[o,l,u,c]=Ub({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,l,u,c]}const Ig=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:_,markerEnd:g,markerStart:w,interactionWidth:x})=>{const[k,j,N]=DM({sourceX:e,sourceY:t,targetX:n,targetY:r});return ve.createElement(Lf,{path:k,labelX:j,labelY:N,label:o,labelStyle:l,labelShowBg:u,labelBgStyle:c,labelBgPadding:f,labelBgBorderRadius:m,style:_,markerEnd:g,markerStart:w,interactionWidth:x})});Ig.displayName="StraightEdge";function Uh(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Hw({pos:e,x1:t,y1:n,x2:r,y2:o,c:l}){switch(e){case _t.Left:return[t-Uh(t-r,l),n];case _t.Right:return[t+Uh(r-t,l),n];case _t.Top:return[t,n-Uh(n-o,l)];case _t.Bottom:return[t,n+Uh(o-n,l)]}}function Hb({sourceX:e,sourceY:t,sourcePosition:n=_t.Bottom,targetX:r,targetY:o,targetPosition:l=_t.Top,curvature:u=.25}){const[c,f]=Hw({pos:n,x1:e,y1:t,x2:r,y2:o,c:u}),[m,_]=Hw({pos:l,x1:r,y1:o,x2:e,y2:t,c:u}),[g,w,x,k]=Wb({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:c,sourceControlY:f,targetControlX:m,targetControlY:_});return[`M${e},${t} C${c},${f} ${m},${_} ${r},${o}`,g,w,x,k]}const bm=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:o=_t.Bottom,targetPosition:l=_t.Top,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:m,labelBgPadding:_,labelBgBorderRadius:g,style:w,markerEnd:x,markerStart:k,pathOptions:j,interactionWidth:N})=>{const[C,E,T]=Hb({sourceX:e,sourceY:t,sourcePosition:o,targetX:n,targetY:r,targetPosition:l,curvature:j==null?void 0:j.curvature});return ve.createElement(Lf,{path:C,labelX:E,labelY:T,label:u,labelStyle:c,labelShowBg:f,labelBgStyle:m,labelBgPadding:_,labelBgBorderRadius:g,style:w,markerEnd:x,markerStart:k,interactionWidth:N})});bm.displayName="BezierEdge";const Og=p.createContext(null),FM=Og.Provider;Og.Consumer;const zM=()=>p.useContext(Og),BM=e=>"id"in e&&"source"in e&&"target"in e,UM=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`reactflow__edge-${e}${t||""}-${n}${r||""}`,Gp=(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)),qM=(e,t)=>{if(!e.source||!e.target)return t;let n;return BM(e)?n={...e}:n={...e,id:UM(e)},WM(n,t)?t:t.concat(n)},Kp=({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},Vb=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r}),sc=(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}},Fm=(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}=sc(o,t).positionAbsolute;return Db(r,bf({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 Fb(n)},Gb=(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},m=[];return e.forEach(_=>{const{width:g,height:w,selectable:x=!0,hidden:k=!1}=_;if(u&&!x||k)return!1;const{positionAbsolute:j}=sc(_,c),N={x:j.x,y:j.y,width:g||0,height:w||0},C=qp(f,N),E=typeof g>"u"||typeof w>"u"||g===null||w===null,T=l&&C>0,I=(g||0)*(w||0);(E||T||C>=I||_.dragging)&&m.push(_)}),m},Kb=(e,t)=>{const n=e.map(r=>r.id);return t.filter(r=>n.includes(r.source)||n.includes(r.target))},Yb=(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),m=Eu(f,r,o),_=e.x+e.width/2,g=e.y+e.height/2,w=t/2-_*m,x=n/2-g*m;return{x:w,y:x,zoom:m}},Vl=(e,t=0)=>e.transition().duration(t);function Vw(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 HM(e,t,n,r,o,l){const{x:u,y:c}=ol(e),m=t.elementsFromPoint(u,c).find(k=>k.classList.contains("react-flow__handle"));if(m){const k=m.getAttribute("data-nodeid");if(k){const j=Pg(void 0,m),N=m.getAttribute("data-handleid"),C=l({nodeId:k,id:N,type:j});if(C){const E=o.find(T=>T.nodeId===k&&T.type===j&&T.id===N);return{handle:{id:N,type:j,nodeId:k,x:(E==null?void 0:E.x)||n.x,y:(E==null?void 0:E.y)||n.y},validHandleResult:C}}}}let _=[],g=1/0;if(o.forEach(k=>{const j=Math.sqrt((k.x-n.x)**2+(k.y-n.y)**2);if(j<=r){const N=l(k);j<=g&&(j<g?_=[{handle:k,validHandleResult:N}]:j===g&&_.push({handle:k,validHandleResult:N}),g=j)}}),!_.length)return{handle:null,validHandleResult:Jb()};if(_.length===1)return _[0];const w=_.some(({validHandleResult:k})=>k.isValid),x=_.some(({handle:k})=>k.type==="target");return _.find(({handle:k,validHandleResult:j})=>x?k.type==="target":w?j.isValid:!0)||_[0]}const VM={source:null,target:null,sourceHandle:null,targetHandle:null},Jb=()=>({handleDomNode:null,isValid:!1,connection:VM,endHandle:null});function Xb(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}"]`),m={...Jb(),handleDomNode:f};if(f){const _=Pg(void 0,f),g=f.getAttribute("data-nodeid"),w=f.getAttribute("data-handleid"),x=f.classList.contains("connectable"),k=f.classList.contains("connectableend"),j={source:c?g:n,sourceHandle:c?w:r,target:c?n:g,targetHandle:c?r:w};m.connection=j,x&&k&&(t===cc.Strict?c&&_==="source"||!c&&_==="target":g!==n||w!==r)&&(m.endHandle={nodeId:g,handleId:w,type:_},m.isValid=l(j))}return m}function GM({nodes:e,nodeId:t,handleId:n,handleType:r}){return e.reduce((o,l)=>{if(l[fs]){const{handleBounds:u}=l[fs];let c=[],f=[];u&&(c=Vw(l,u,"source",`${t}-${n}-${r}`),f=Vw(l,u,"target",`${t}-${n}-${r}`)),o.push(...c,...f)}return o},[])}function Pg(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function Y_(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function KM(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function Zb({event:e,handleId:t,nodeId:n,onConnect:r,isTarget:o,getState:l,setState:u,isValidConnection:c,edgeUpdaterType:f,onEdgeUpdateEnd:m}){const _=Pb(e.target),{connectionMode:g,domNode:w,autoPanOnConnect:x,connectionRadius:k,onConnectStart:j,panBy:N,getNodes:C,cancelConnection:E}=l();let T=0,I;const{x:K,y:U}=ol(e),J=_==null?void 0:_.elementFromPoint(K,U),Y=Pg(f,J),re=w==null?void 0:w.getBoundingClientRect();if(!re||!Y)return;let ce,fe=ol(e,re),W=!1,O=null,$=!1,z=null;const A=GM({nodes:C(),nodeId:n,handleId:t,handleType:Y}),te=()=>{if(!x)return;const[G,R]=Ob(fe,re);N({x:G,y:R}),T=requestAnimationFrame(te)};u({connectionPosition:fe,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:Y,connectionStartHandle:{nodeId:n,handleId:t,type:Y},connectionEndHandle:null}),j==null||j(e,{nodeId:n,handleId:t,handleType:Y});function P(G){const{transform:R}=l();fe=ol(G,re);const{handle:Z,validHandleResult:X}=HM(G,_,Kp(fe,R,!1,[1,1]),k,A,Q=>Xb(Q,g,n,t,o?"target":"source",c,_));if(I=Z,W||(te(),W=!0),z=X.handleDomNode,O=X.connection,$=X.isValid,u({connectionPosition:I&&$?Vb({x:I.x,y:I.y},R):fe,connectionStatus:KM(!!I,$),connectionEndHandle:X.endHandle}),!I&&!$&&!z)return Y_(ce);O.source!==O.target&&z&&(Y_(ce),ce=z,z.classList.add("connecting","react-flow__handle-connecting"),z.classList.toggle("valid",$),z.classList.toggle("react-flow__handle-valid",$))}function F(G){var R,Z;(I||z)&&O&&$&&(r==null||r(O)),(Z=(R=l()).onConnectEnd)==null||Z.call(R,G),f&&(m==null||m(G)),Y_(ce),E(),cancelAnimationFrame(T),W=!1,$=!1,O=null,z=null,_.removeEventListener("mousemove",P),_.removeEventListener("mouseup",F),_.removeEventListener("touchmove",P),_.removeEventListener("touchend",F)}_.addEventListener("mousemove",P),_.addEventListener("mouseup",F),_.addEventListener("touchmove",P),_.addEventListener("touchend",F)}const Gw=()=>!0,YM=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),JM=(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}},Qb=p.forwardRef(({type:e="source",position:t=_t.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:o=!0,isConnectableEnd:l=!0,id:u,onConnect:c,children:f,className:m,onMouseDown:_,onTouchStart:g,...w},x)=>{var re,ce;const k=u||null,j=e==="target",N=bs(),C=zM(),{connectOnClick:E,noPanClassName:T}=Ln(YM,Os),{connecting:I,clickConnecting:K}=Ln(JM(C,k,e),Os);C||(ce=(re=N.getState()).onError)==null||ce.call(re,"010",ua.error010());const U=fe=>{const{defaultEdgeOptions:W,onConnect:O,hasDefaultEdges:$}=N.getState(),z={...W,...fe};if($){const{edges:A,setEdges:te}=N.getState();te(qM(z,A))}O==null||O(z),c==null||c(z)},J=fe=>{if(!C)return;const W=Bb(fe);o&&(W&&fe.button===0||!W)&&Zb({event:fe,handleId:k,nodeId:C,onConnect:U,isTarget:j,getState:N.getState,setState:N.setState,isValidConnection:n||N.getState().isValidConnection||Gw}),W?_==null||_(fe):g==null||g(fe)},Y=fe=>{const{onClickConnectStart:W,onClickConnectEnd:O,connectionClickStartHandle:$,connectionMode:z,isValidConnection:A}=N.getState();if(!C||!$&&!o)return;if(!$){W==null||W(fe,{nodeId:C,handleId:k,handleType:e}),N.setState({connectionClickStartHandle:{nodeId:C,type:e,handleId:k}});return}const te=Pb(fe.target),P=n||A||Gw,{connection:F,isValid:G}=Xb({nodeId:C,id:k,type:e},z,$.nodeId,$.handleId||null,$.type,P,te);G&&U(F),O==null||O(fe),N.setState({connectionClickStartHandle:null})};return ve.createElement("div",{"data-handleid":k,"data-nodeid":C,"data-handlepos":t,"data-id":`${C}-${k}-${e}`,className:Ks(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",T,m,{source:!j,target:j,connectable:r,connectablestart:o,connectableend:l,connecting:K,connectionindicator:r&&(o&&!I||l&&I)}]),onMouseDown:J,onTouchStart:J,onClick:E?Y:void 0,ref:x,...w},f)});Qb.displayName="Handle";var jm=p.memo(Qb);const e0=({data:e,isConnectable:t,targetPosition:n=_t.Top,sourcePosition:r=_t.Bottom})=>ve.createElement(ve.Fragment,null,ve.createElement(jm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,ve.createElement(jm,{type:"source",position:r,isConnectable:t}));e0.displayName="DefaultNode";var Yp=p.memo(e0);const t0=({data:e,isConnectable:t,sourcePosition:n=_t.Bottom})=>ve.createElement(ve.Fragment,null,e==null?void 0:e.label,ve.createElement(jm,{type:"source",position:n,isConnectable:t}));t0.displayName="InputNode";var n0=p.memo(t0);const s0=({data:e,isConnectable:t,targetPosition:n=_t.Top})=>ve.createElement(ve.Fragment,null,ve.createElement(jm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);s0.displayName="OutputNode";var r0=p.memo(s0);const Dg=()=>null;Dg.displayName="GroupNode";const XM=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),Wh=e=>e.id;function ZM(e,t){return Os(e.selectedNodes.map(Wh),t.selectedNodes.map(Wh))&&Os(e.selectedEdges.map(Wh),t.selectedEdges.map(Wh))}const i0=p.memo(({onSelectionChange:e})=>{const t=bs(),{selectedNodes:n,selectedEdges:r}=Ln(XM,ZM);return p.useEffect(()=>{const o={nodes:n,edges:r};e==null||e(o),t.getState().onSelectionChange.forEach(l=>l(o))},[n,r,e]),null});i0.displayName="SelectionListener";const QM=e=>!!e.onSelectionChange;function eR({onSelectionChange:e}){const t=Ln(QM);return e||t?ve.createElement(i0,{onSelectionChange:e}):null}const tR=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){p.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function Gt(e,t,n){p.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const nR=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:o,onConnectStart:l,onConnectEnd:u,onClickConnectStart:c,onClickConnectEnd:f,nodesDraggable:m,nodesConnectable:_,nodesFocusable:g,edgesFocusable:w,edgesUpdatable:x,elevateNodesOnSelect:k,minZoom:j,maxZoom:N,nodeExtent:C,onNodesChange:E,onEdgesChange:T,elementsSelectable:I,connectionMode:K,snapGrid:U,snapToGrid:J,translateExtent:Y,connectOnClick:re,defaultEdgeOptions:ce,fitView:fe,fitViewOptions:W,onNodesDelete:O,onEdgesDelete:$,onNodeDrag:z,onNodeDragStart:A,onNodeDragStop:te,onSelectionDrag:P,onSelectionDragStart:F,onSelectionDragStop:G,noPanClassName:R,nodeOrigin:Z,rfId:X,autoPanOnConnect:Q,autoPanOnNodeDrag:le,onError:ge,connectionRadius:pe,isValidConnection:ye,nodeDragThreshold:Ne})=>{const{setNodes:Ue,setEdges:We,setDefaultNodesAndEdges:pt,setMinZoom:Fe,setMaxZoom:tt,setTranslateExtent:lt,setNodeExtent:Ke,reset:ke}=Ln(tR,Os),Re=bs();return p.useEffect(()=>{const ht=r==null?void 0:r.map(xe=>({...xe,...ce}));return pt(n,ht),()=>{ke()}},[]),Gt("defaultEdgeOptions",ce,Re.setState),Gt("connectionMode",K,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",m,Re.setState),Gt("nodesConnectable",_,Re.setState),Gt("nodesFocusable",g,Re.setState),Gt("edgesFocusable",w,Re.setState),Gt("edgesUpdatable",x,Re.setState),Gt("elementsSelectable",I,Re.setState),Gt("elevateNodesOnSelect",k,Re.setState),Gt("snapToGrid",J,Re.setState),Gt("snapGrid",U,Re.setState),Gt("onNodesChange",E,Re.setState),Gt("onEdgesChange",T,Re.setState),Gt("connectOnClick",re,Re.setState),Gt("fitViewOnInit",fe,Re.setState),Gt("fitViewOnInitOptions",W,Re.setState),Gt("onNodesDelete",O,Re.setState),Gt("onEdgesDelete",$,Re.setState),Gt("onNodeDrag",z,Re.setState),Gt("onNodeDragStart",A,Re.setState),Gt("onNodeDragStop",te,Re.setState),Gt("onSelectionDrag",P,Re.setState),Gt("onSelectionDragStart",F,Re.setState),Gt("onSelectionDragStop",G,Re.setState),Gt("noPanClassName",R,Re.setState),Gt("nodeOrigin",Z,Re.setState),Gt("rfId",X,Re.setState),Gt("autoPanOnConnect",Q,Re.setState),Gt("autoPanOnNodeDrag",le,Re.setState),Gt("onError",ge,Re.setState),Gt("connectionRadius",pe,Re.setState),Gt("isValidConnection",ye,Re.setState),Gt("nodeDragThreshold",Ne,Re.setState),iu(e,Ue),iu(t,We),iu(j,Fe),iu(N,tt),iu(Y,lt),iu(C,Ke),null},Kw={display:"none"},sR={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},o0="react-flow__node-desc",a0="react-flow__edge-desc",rR="react-flow__aria-live",iR=e=>e.ariaLiveMessage;function oR({rfId:e}){const t=Ln(iR);return ve.createElement("div",{id:`${rR}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:sR},t)}function aR({rfId:e,disableKeyboardA11y:t}){return ve.createElement(ve.Fragment,null,ve.createElement("div",{id:`${o0}-${e}`,style:Kw},"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:`${a0}-${e}`,style:Kw},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&ve.createElement(oR,{rfId:e}))}var Sf=(e=null,t={actInsideInputWithModifier:!0})=>{const[n,r]=p.useState(!1),o=p.useRef(!1),l=p.useRef(new Set([])),[u,c]=p.useMemo(()=>{if(e!==null){const m=(Array.isArray(e)?e:[e]).filter(g=>typeof g=="string").map(g=>g.split("+")),_=m.reduce((g,w)=>g.concat(...w),[]);return[m,_]}return[[],[]]},[e]);return p.useEffect(()=>{const f=typeof document<"u"?document:null,m=(t==null?void 0:t.target)||f;if(e!==null){const _=x=>{if(o.current=x.ctrlKey||x.metaKey||x.shiftKey,(!o.current||o.current&&!t.actInsideInputWithModifier)&&Hp(x))return!1;const j=Jw(x.code,c);l.current.add(x[j]),Yw(u,l.current,!1)&&(x.preventDefault(),r(!0))},g=x=>{if((!o.current||o.current&&!t.actInsideInputWithModifier)&&Hp(x))return!1;const j=Jw(x.code,c);Yw(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 m==null||m.addEventListener("keydown",_),m==null||m.addEventListener("keyup",g),window.addEventListener("blur",w),()=>{m==null||m.removeEventListener("keydown",_),m==null||m.removeEventListener("keyup",g),window.removeEventListener("blur",w)}}},[e,r]),n};function Yw(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(o=>t.has(o)))}function Jw(e,t){return t.includes(e)?"code":"key"}function l0(e,t,n,r){var u,c;if(!e.parentNode)return n;const o=t.get(e.parentNode),l=sc(o,r);return l0(o,t,{x:(n.x??0)+l.x,y:(n.y??0)+l.y,z:(((u=o[fs])==null?void 0:u.z)??0)>(n.z??0)?((c=o[fs])==null?void 0:c.z)??0:n.z??0},r)}function c0(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}=l0(r,e,{...r.position,z:((o=r[fs])==null?void 0:o.z)??0},t);r.positionAbsolute={x:l,y:u},r[fs].z=c,n!=null&&n[r.id]&&(r[fs].isParent=!0)}})}function J_(e,t,n,r){const o=new Map,l={},u=r?1e3:0;return e.forEach(c=>{var w;const f=(ki(c.zIndex)?c.zIndex:0)+(c.selected?u:0),m=t.get(c.id),_={...c,positionAbsolute:{x:c.position.x,y:c.position.y}};c.parentNode&&(l[c.parentNode]=!0);const g=(m==null?void 0:m.type)&&(m==null?void 0:m.type)!==c.type;Object.defineProperty(_,fs,{enumerable:!1,value:{handleBounds:g||(w=m==null?void 0:m[fs])==null?void 0:w.handleBounds,z:f}}),o.set(c.id,_)}),c0(o,n,l),o}function u0(e,t={}){const{getNodes:n,width:r,height:o,minZoom:l,maxZoom:u,d3Zoom:c,d3Selection:f,fitViewOnInitDone:m,fitViewOnInit:_,nodeOrigin:g}=e(),w=t.initial&&!m&&_;if(c&&f&&(w||!t.initial)){const k=n().filter(N=>{var E;const C=t.includeHiddenNodes?N.width&&N.height:!N.hidden;return(E=t.nodes)!=null&&E.length?C&&t.nodes.some(T=>T.id===N.id):C}),j=k.every(N=>N.width&&N.height);if(k.length>0&&j){const N=Fm(k,g),{x:C,y:E,zoom:T}=Yb(N,r,o,t.minZoom??l,t.maxZoom??u,t.padding??.1),I=aa.translate(C,E).scale(T);return typeof t.duration=="number"&&t.duration>0?c.transform(Vl(f,t.duration),I):c.transform(f,I),!0}}return!1}function lR(e,t){return e.forEach(n=>{const r=t.get(n.id);r&&t.set(r.id,{...r,[fs]:r[fs],selected:n.selected})}),new Map(t)}function cR(e,t){return t.map(n=>{const r=e.find(o=>o.id===n.id);return r&&(n.selected=r.selected),n})}function qh({changedNodes:e,changedEdges:t,get:n,set:r}){const{nodeInternals:o,edges:l,onNodesChange:u,onEdgesChange:c,hasDefaultNodes:f,hasDefaultEdges:m}=n();e!=null&&e.length&&(f&&r({nodeInternals:lR(e,o)}),u==null||u(e)),t!=null&&t.length&&(m&&r({edges:cR(t,l)}),c==null||c(t))}const ou=()=>{},uR={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},dR=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),fR=()=>{const e=bs(),{d3Zoom:t,d3Selection:n}=Ln(dR,Os);return p.useMemo(()=>n&&t?{zoomIn:o=>t.scaleBy(Vl(n,o==null?void 0:o.duration),1.2),zoomOut:o=>t.scaleBy(Vl(n,o==null?void 0:o.duration),1/1.2),zoomTo:(o,l)=>t.scaleTo(Vl(n,l==null?void 0:l.duration),o),getZoom:()=>e.getState().transform[2],setViewport:(o,l)=>{const[u,c,f]=e.getState().transform,m=aa.translate(o.x??u,o.y??c).scale(o.zoom??f);t.transform(Vl(n,l==null?void 0:l.duration),m)},getViewport:()=>{const[o,l,u]=e.getState().transform;return{x:o,y:l,zoom:u}},fitView:o=>u0(e.getState,o),setCenter:(o,l,u)=>{const{width:c,height:f,maxZoom:m}=e.getState(),_=typeof(u==null?void 0:u.zoom)<"u"?u.zoom:m,g=c/2-o*_,w=f/2-l*_,x=aa.translate(g,w).scale(_);t.transform(Vl(n,u==null?void 0:u.duration),x)},fitBounds:(o,l)=>{const{width:u,height:c,minZoom:f,maxZoom:m}=e.getState(),{x:_,y:g,zoom:w}=Yb(o,u,c,f,m,(l==null?void 0:l.padding)??.1),x=aa.translate(_,g).scale(w);t.transform(Vl(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"),Kp(o,l,u,c)},screenToFlowPosition:o=>{const{transform:l,snapToGrid:u,snapGrid:c,domNode:f}=e.getState();if(!f)return o;const{x:m,y:_}=f.getBoundingClientRect(),g={x:o.x-m,y:o.y-_};return Kp(g,l,u,c)},flowToScreenPosition:o=>{const{transform:l,domNode:u}=e.getState();if(!u)return o;const{x:c,y:f}=u.getBoundingClientRect(),m=Vb(o,l);return{x:m.x+c,y:m.y+f}},viewportInitialized:!0}:uR,[t,n])};function Fg(){const e=fR(),t=bs(),n=p.useCallback(()=>t.getState().getNodes().map(j=>({...j})),[]),r=p.useCallback(j=>t.getState().nodeInternals.get(j),[]),o=p.useCallback(()=>{const{edges:j=[]}=t.getState();return j.map(N=>({...N}))},[]),l=p.useCallback(j=>{const{edges:N=[]}=t.getState();return N.find(C=>C.id===j)},[]),u=p.useCallback(j=>{const{getNodes:N,setNodes:C,hasDefaultNodes:E,onNodesChange:T}=t.getState(),I=N(),K=typeof j=="function"?j(I):j;if(E)C(K);else if(T){const U=K.length===0?I.map(J=>({type:"remove",id:J.id})):K.map(J=>({item:J,type:"reset"}));T(U)}},[]),c=p.useCallback(j=>{const{edges:N=[],setEdges:C,hasDefaultEdges:E,onEdgesChange:T}=t.getState(),I=typeof j=="function"?j(N):j;if(E)C(I);else if(T){const K=I.length===0?N.map(U=>({type:"remove",id:U.id})):I.map(U=>({item:U,type:"reset"}));T(K)}},[]),f=p.useCallback(j=>{const N=Array.isArray(j)?j:[j],{getNodes:C,setNodes:E,hasDefaultNodes:T,onNodesChange:I}=t.getState();if(T){const U=[...C(),...N];E(U)}else if(I){const K=N.map(U=>({item:U,type:"add"}));I(K)}},[]),m=p.useCallback(j=>{const N=Array.isArray(j)?j:[j],{edges:C=[],setEdges:E,hasDefaultEdges:T,onEdgesChange:I}=t.getState();if(T)E([...C,...N]);else if(I){const K=N.map(U=>({item:U,type:"add"}));I(K)}},[]),_=p.useCallback(()=>{const{getNodes:j,edges:N=[],transform:C}=t.getState(),[E,T,I]=C;return{nodes:j().map(K=>({...K})),edges:N.map(K=>({...K})),viewport:{x:E,y:T,zoom:I}}},[]),g=p.useCallback(({nodes:j,edges:N})=>{const{nodeInternals:C,getNodes:E,edges:T,hasDefaultNodes:I,hasDefaultEdges:K,onNodesDelete:U,onEdgesDelete:J,onNodesChange:Y,onEdgesChange:re}=t.getState(),ce=(j||[]).map(z=>z.id),fe=(N||[]).map(z=>z.id),W=E().reduce((z,A)=>{const te=!ce.includes(A.id)&&A.parentNode&&z.find(F=>F.id===A.parentNode);return(typeof A.deletable=="boolean"?A.deletable:!0)&&(ce.includes(A.id)||te)&&z.push(A),z},[]),O=T.filter(z=>typeof z.deletable=="boolean"?z.deletable:!0),$=O.filter(z=>fe.includes(z.id));if(W||$){const z=Kb(W,O),A=[...$,...z],te=A.reduce((P,F)=>(P.includes(F.id)||P.push(F.id),P),[]);if((K||I)&&(K&&t.setState({edges:T.filter(P=>!te.includes(P.id))}),I&&(W.forEach(P=>{C.delete(P.id)}),t.setState({nodeInternals:new Map(C)}))),te.length>0&&(J==null||J(A),re&&re(te.map(P=>({id:P,type:"remove"})))),W.length>0&&(U==null||U(W),Y)){const P=W.map(F=>({id:F.id,type:"remove"}));Y(P)}}},[]),w=p.useCallback(j=>{const N=MM(j),C=N?null:t.getState().nodeInternals.get(j.id);return!N&&!C?[null,null,N]:[N?j:Bw(C),C,N]},[]),x=p.useCallback((j,N=!0,C)=>{const[E,T,I]=w(j);return E?(C||t.getState().getNodes()).filter(K=>{if(!I&&(K.id===T.id||!K.positionAbsolute))return!1;const U=Bw(K),J=qp(U,E);return N&&J>0||J>=E.width*E.height}):[]},[]),k=p.useCallback((j,N,C=!0)=>{const[E]=w(j);if(!E)return!1;const T=qp(E,N);return C&&T>0||T>=E.width*E.height},[]);return p.useMemo(()=>({...e,getNodes:n,getNode:r,getEdges:o,getEdge:l,setNodes:u,setEdges:c,addNodes:f,addEdges:m,toObject:_,deleteElements:g,getIntersectingNodes:x,isNodeIntersecting:k}),[e,n,r,o,l,u,c,f,m,_,g,x,k])}const hR={actInsideInputWithModifier:!1};var mR=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=bs(),{deleteElements:r}=Fg(),o=Sf(e,hR),l=Sf(t);p.useEffect(()=>{if(o){const{edges:u,getNodes:c}=n.getState(),f=c().filter(_=>_.selected),m=u.filter(_=>_.selected);r({nodes:f,edges:m}),n.setState({nodesSelectionActive:!1})}},[o]),p.useEffect(()=>{n.setState({multiSelectionActive:l})},[l])};function _R(e){const t=bs();p.useEffect(()=>{let n;const r=()=>{var l,u;if(!e.current)return;const o=Tg(e.current);(o.height===0||o.width===0)&&((u=(l=t.getState()).onError)==null||u.call(l,"004",ua.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 zg={position:"absolute",width:"100%",height:"100%",top:0,left:0},pR=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,Hh=e=>({x:e.x,y:e.y,zoom:e.k}),au=(e,t)=>e.target.closest(`.${t}`),Xw=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Zw=e=>{const t=e.ctrlKey&&xm()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},gR=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),yR=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:r,zoomOnScroll:o=!0,zoomOnPinch:l=!0,panOnScroll:u=!1,panOnScrollSpeed:c=.5,panOnScrollMode:f=Xl.Free,zoomOnDoubleClick:m=!0,elementsSelectable:_,panOnDrag:g=!0,defaultViewport:w,translateExtent:x,minZoom:k,maxZoom:j,zoomActivationKeyCode:N,preventScrolling:C=!0,children:E,noWheelClassName:T,noPanClassName:I})=>{const K=p.useRef(),U=bs(),J=p.useRef(!1),Y=p.useRef(!1),re=p.useRef(null),ce=p.useRef({x:0,y:0,zoom:0}),{d3Zoom:fe,d3Selection:W,d3ZoomHandler:O,userSelectionActive:$}=Ln(gR,Os),z=Sf(N),A=p.useRef(0),te=p.useRef(!1),P=p.useRef();return _R(re),p.useEffect(()=>{if(re.current){const F=re.current.getBoundingClientRect(),G=Lb().scaleExtent([k,j]).translateExtent(x),R=ji(re.current).call(G),Z=aa.translate(w.x,w.y).scale(Eu(w.zoom,k,j)),X=[[0,0],[F.width,F.height]],Q=G.constrain()(Z,X,x);G.transform(R,Q),G.wheelDelta(Zw),U.setState({d3Zoom:G,d3Selection:R,d3ZoomHandler:R.on("wheel.zoom"),transform:[Q.x,Q.y,Q.k],domNode:re.current.closest(".react-flow")})}},[]),p.useEffect(()=>{W&&fe&&(u&&!z&&!$?W.on("wheel.zoom",F=>{if(au(F,T))return!1;F.preventDefault(),F.stopImmediatePropagation();const G=W.property("__zoom").k||1,R=xm();if(F.ctrlKey&&l&&R){const Ne=Fi(F),Ue=Zw(F),We=G*Math.pow(2,Ue);fe.scaleTo(W,We,Ne,F);return}const Z=F.deltaMode===1?20:1;let X=f===Xl.Vertical?0:F.deltaX*Z,Q=f===Xl.Horizontal?0:F.deltaY*Z;!R&&F.shiftKey&&f!==Xl.Vertical&&(X=F.deltaY*Z,Q=0),fe.translateBy(W,-(X/G)*c,-(Q/G)*c,{internal:!0});const le=Hh(W.property("__zoom")),{onViewportChangeStart:ge,onViewportChange:pe,onViewportChangeEnd:ye}=U.getState();clearTimeout(P.current),te.current||(te.current=!0,t==null||t(F,le),ge==null||ge(le)),te.current&&(e==null||e(F,le),pe==null||pe(le),P.current=setTimeout(()=>{n==null||n(F,le),ye==null||ye(le),te.current=!1},150))},{passive:!1}):typeof O<"u"&&W.on("wheel.zoom",function(F,G){if(!C||au(F,T))return null;F.preventDefault(),O.call(this,F,G)},{passive:!1}))},[$,u,f,W,fe,O,z,l,C,T,t,e,n]),p.useEffect(()=>{fe&&fe.on("start",F=>{var Z,X;if(!F.sourceEvent||F.sourceEvent.internal)return null;A.current=(Z=F.sourceEvent)==null?void 0:Z.button;const{onViewportChangeStart:G}=U.getState(),R=Hh(F.transform);J.current=!0,ce.current=R,((X=F.sourceEvent)==null?void 0:X.type)==="mousedown"&&U.setState({paneDragging:!0}),G==null||G(R),t==null||t(F.sourceEvent,R)})},[fe,t]),p.useEffect(()=>{fe&&($&&!J.current?fe.on("zoom",null):$||fe.on("zoom",F=>{var R;const{onViewportChange:G}=U.getState();if(U.setState({transform:[F.transform.x,F.transform.y,F.transform.k]}),Y.current=!!(r&&Xw(g,A.current??0)),(e||G)&&!((R=F.sourceEvent)!=null&&R.internal)){const Z=Hh(F.transform);G==null||G(Z),e==null||e(F.sourceEvent,Z)}}))},[$,fe,e,g,r]),p.useEffect(()=>{fe&&fe.on("end",F=>{if(!F.sourceEvent||F.sourceEvent.internal)return null;const{onViewportChangeEnd:G}=U.getState();if(J.current=!1,U.setState({paneDragging:!1}),r&&Xw(g,A.current??0)&&!Y.current&&r(F.sourceEvent),Y.current=!1,(n||G)&&pR(ce.current,F.transform)){const R=Hh(F.transform);ce.current=R,clearTimeout(K.current),K.current=setTimeout(()=>{G==null||G(R),n==null||n(F.sourceEvent,R)},u?150:0)}})},[fe,u,g,n,r]),p.useEffect(()=>{fe&&fe.filter(F=>{const G=z||o,R=l&&F.ctrlKey;if((g===!0||Array.isArray(g)&&g.includes(1))&&F.button===1&&F.type==="mousedown"&&(au(F,"react-flow__node")||au(F,"react-flow__edge")))return!0;if(!g&&!G&&!u&&!m&&!l||$||!m&&F.type==="dblclick"||au(F,T)&&F.type==="wheel"||au(F,I)&&(F.type!=="wheel"||u&&F.type==="wheel"&&!z)||!l&&F.ctrlKey&&F.type==="wheel"||!G&&!u&&!R&&F.type==="wheel"||!g&&(F.type==="mousedown"||F.type==="touchstart")||Array.isArray(g)&&!g.includes(F.button)&&(F.type==="mousedown"||F.type==="touchstart"))return!1;const Z=Array.isArray(g)&&g.includes(F.button)||!F.button||F.button<=1;return(!F.ctrlKey||F.type==="wheel")&&Z})},[$,fe,o,l,u,m,g,_,z]),ve.createElement("div",{className:"react-flow__renderer",ref:re,style:zg},E)},wR=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function vR(){const{userSelectionActive:e,userSelectionRect:t}=Ln(wR,Os);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 Qw(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 xR(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&&Qw(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&&Qw(r,u);break}case"remove":return r}return r.push(u),r},n)}function bR(e,t){return xR(e,t)}const rl=(e,t)=>({id:e,type:"select",selected:t});function hu(e,t){return e.reduce((n,r)=>{const o=t.includes(r.id);return!r.selected&&o?(r.selected=!0,n.push(rl(r.id,!0))):r.selected&&!o&&(r.selected=!1,n.push(rl(r.id,!1))),n},[])}const X_=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},jR=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),d0=p.memo(({isSelecting:e,selectionMode:t=jf.Full,panOnDrag:n,onSelectionStart:r,onSelectionEnd:o,onPaneClick:l,onPaneContextMenu:u,onPaneScroll:c,onPaneMouseEnter:f,onPaneMouseMove:m,onPaneMouseLeave:_,children:g})=>{const w=p.useRef(null),x=bs(),k=p.useRef(0),j=p.useRef(0),N=p.useRef(),{userSelectionActive:C,elementsSelectable:E,dragging:T}=Ln(jR,Os),I=()=>{x.setState({userSelectionActive:!1,userSelectionRect:null}),k.current=0,j.current=0},K=O=>{l==null||l(O),x.getState().resetSelectedElements(),x.setState({nodesSelectionActive:!1})},U=O=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){O.preventDefault();return}u==null||u(O)},J=c?O=>c(O):void 0,Y=O=>{const{resetSelectedElements:$,domNode:z}=x.getState();if(N.current=z==null?void 0:z.getBoundingClientRect(),!E||!e||O.button!==0||O.target!==w.current||!N.current)return;const{x:A,y:te}=ol(O,N.current);$(),x.setState({userSelectionRect:{width:0,height:0,startX:A,startY:te,x:A,y:te}}),r==null||r(O)},re=O=>{const{userSelectionRect:$,nodeInternals:z,edges:A,transform:te,onNodesChange:P,onEdgesChange:F,nodeOrigin:G,getNodes:R}=x.getState();if(!e||!N.current||!$)return;x.setState({userSelectionActive:!0,nodesSelectionActive:!1});const Z=ol(O,N.current),X=$.startX??0,Q=$.startY??0,le={...$,x:Z.x<X?Z.x:X,y:Z.y<Q?Z.y:Q,width:Math.abs(Z.x-X),height:Math.abs(Z.y-Q)},ge=R(),pe=Gb(z,le,te,t===jf.Partial,!0,G),ye=Kb(pe,A).map(Ue=>Ue.id),Ne=pe.map(Ue=>Ue.id);if(k.current!==Ne.length){k.current=Ne.length;const Ue=hu(ge,Ne);Ue.length&&(P==null||P(Ue))}if(j.current!==ye.length){j.current=ye.length;const Ue=hu(A,ye);Ue.length&&(F==null||F(Ue))}x.setState({userSelectionRect:le})},ce=O=>{if(O.button!==0)return;const{userSelectionRect:$}=x.getState();!C&&$&&O.target===w.current&&(K==null||K(O)),x.setState({nodesSelectionActive:k.current>0}),I(),o==null||o(O)},fe=O=>{C&&(x.setState({nodesSelectionActive:k.current>0}),o==null||o(O)),I()},W=E&&(e||C);return ve.createElement("div",{className:Ks(["react-flow__pane",{dragging:T,selection:e}]),onClick:W?void 0:X_(K,w),onContextMenu:X_(U,w),onWheel:X_(J,w),onMouseEnter:W?void 0:f,onMouseDown:W?Y:void 0,onMouseMove:W?re:m,onMouseUp:W?ce:void 0,onMouseLeave:W?fe:_,ref:w,style:zg},g,ve.createElement(vR,null))});d0.displayName="Pane";function f0(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:f0(n,t):!1}function ev(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 kR(e,t,n,r){return Array.from(e.values()).filter(o=>(o.selected||o.id===r)&&(!o.parentNode||!f0(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 SR(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function h0(e,t,n,r,o=[0,0],l){const u=SR(e,e.extent||r);let c=u;if(e.extent==="parent"&&!e.expandParent)if(e.parentNode&&e.width&&e.height){const _=n.get(e.parentNode),{x:g,y:w}=sc(_,o).positionAbsolute;c=_&&ki(g)&&ki(w)&&ki(_.width)&&ki(_.height)?[[g+e.width*o[0],w+e.height*o[1]],[g+_.width-e.width+e.width*o[0],w+_.height-e.height+e.height*o[1]]]:c}else l==null||l("005",ua.error005()),c=u;else if(e.extent&&e.parentNode&&e.extent!=="parent"){const _=n.get(e.parentNode),{x:g,y:w}=sc(_,o).positionAbsolute;c=[[e.extent[0][0]+g,e.extent[0][1]+w],[e.extent[1][0]+g,e.extent[1][1]+w]]}let f={x:0,y:0};if(e.parentNode){const _=n.get(e.parentNode);f=sc(_,o).positionAbsolute}const m=c&&c!=="parent"?Mg(t,c):t;return{position:{x:m.x-f.x,y:m.y-f.y},positionAbsolute:m}}function Z_({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 tv=(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 m=f.getBoundingClientRect();return{id:f.getAttribute("data-handleid"),position:f.getAttribute("data-handlepos"),x:(m.left-u.left-c.x)/n,y:(m.top-u.top-c.y)/n,...Tg(f)}})};function Xd(e,t,n){return n===void 0?n:r=>{const o=t().nodeInternals.get(e);o&&n(r,{...o})}}function Jp({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:o,unselectNodesAndEdges:l,multiSelectionActive:u,nodeInternals:c,onError:f}=t.getState(),m=c.get(e);if(!m){f==null||f("012",ua.error012(e));return}t.setState({nodesSelectionActive:!1}),m.selected?(n||m.selected&&u)&&(l({nodes:[m],edges:[]}),requestAnimationFrame(()=>{var _;return(_=r==null?void 0:r.current)==null?void 0:_.blur()})):o([e])}function NR(){const e=bs();return p.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 Q_(e){return(t,n,r)=>e==null?void 0:e(t,r)}function m0({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:o,isSelectable:l,selectNodesOnDrag:u}){const c=bs(),[f,m]=p.useState(!1),_=p.useRef([]),g=p.useRef({x:null,y:null}),w=p.useRef(0),x=p.useRef(null),k=p.useRef({x:0,y:0}),j=p.useRef(null),N=p.useRef(!1),C=p.useRef(!1),E=NR();return p.useEffect(()=>{if(e!=null&&e.current){const T=ji(e.current),I=({x:J,y:Y})=>{const{nodeInternals:re,onNodeDrag:ce,onSelectionDrag:fe,updateNodePositions:W,nodeExtent:O,snapGrid:$,snapToGrid:z,nodeOrigin:A,onError:te}=c.getState();g.current={x:J,y:Y};let P=!1,F={x:0,y:0,x2:0,y2:0};if(_.current.length>1&&O){const R=Fm(_.current,A);F=bf(R)}if(_.current=_.current.map(R=>{const Z={x:J-R.distance.x,y:Y-R.distance.y};z&&(Z.x=$[0]*Math.round(Z.x/$[0]),Z.y=$[1]*Math.round(Z.y/$[1]));const X=[[O[0][0],O[0][1]],[O[1][0],O[1][1]]];_.current.length>1&&O&&!R.extent&&(X[0][0]=R.positionAbsolute.x-F.x+O[0][0],X[1][0]=R.positionAbsolute.x+(R.width??0)-F.x2+O[1][0],X[0][1]=R.positionAbsolute.y-F.y+O[0][1],X[1][1]=R.positionAbsolute.y+(R.height??0)-F.y2+O[1][1]);const Q=h0(R,Z,re,X,A,te);return P=P||R.position.x!==Q.position.x||R.position.y!==Q.position.y,R.position=Q.position,R.positionAbsolute=Q.positionAbsolute,R}),!P)return;W(_.current,!0,!0),m(!0);const G=o?ce:Q_(fe);if(G&&j.current){const[R,Z]=Z_({nodeId:o,dragItems:_.current,nodeInternals:re});G(j.current,R,Z)}},K=()=>{if(!x.current)return;const[J,Y]=Ob(k.current,x.current);if(J!==0||Y!==0){const{transform:re,panBy:ce}=c.getState();g.current.x=(g.current.x??0)-J/re[2],g.current.y=(g.current.y??0)-Y/re[2],ce({x:J,y:Y})&&I(g.current)}w.current=requestAnimationFrame(K)},U=J=>{var A;const{nodeInternals:Y,multiSelectionActive:re,nodesDraggable:ce,unselectNodesAndEdges:fe,onNodeDragStart:W,onSelectionDragStart:O}=c.getState();C.current=!0;const $=o?W:Q_(O);(!u||!l)&&!re&&o&&((A=Y.get(o))!=null&&A.selected||fe()),o&&l&&u&&Jp({id:o,store:c,nodeRef:e});const z=E(J);if(g.current=z,_.current=kR(Y,ce,z,o),$&&_.current){const[te,P]=Z_({nodeId:o,dragItems:_.current,nodeInternals:Y});$(J.sourceEvent,te,P)}};if(t)T.on(".drag",null);else{const J=O$().on("start",Y=>{const{domNode:re,nodeDragThreshold:ce}=c.getState();ce===0&&U(Y);const fe=E(Y);g.current=fe,x.current=(re==null?void 0:re.getBoundingClientRect())||null,k.current=ol(Y.sourceEvent,x.current)}).on("drag",Y=>{var W,O;const re=E(Y),{autoPanOnNodeDrag:ce,nodeDragThreshold:fe}=c.getState();if(!N.current&&C.current&&ce&&(N.current=!0,K()),!C.current){const $=re.xSnapped-(((W=g==null?void 0:g.current)==null?void 0:W.x)??0),z=re.ySnapped-(((O=g==null?void 0:g.current)==null?void 0:O.y)??0);Math.sqrt($*$+z*z)>fe&&U(Y)}(g.current.x!==re.xSnapped||g.current.y!==re.ySnapped)&&_.current&&C.current&&(j.current=Y.sourceEvent,k.current=ol(Y.sourceEvent,x.current),I(re))}).on("end",Y=>{if(C.current&&(m(!1),N.current=!1,C.current=!1,cancelAnimationFrame(w.current),_.current)){const{updateNodePositions:re,nodeInternals:ce,onNodeDragStop:fe,onSelectionDragStop:W}=c.getState(),O=o?fe:Q_(W);if(re(_.current,!1,!1),O){const[$,z]=Z_({nodeId:o,dragItems:_.current,nodeInternals:ce});O(Y.sourceEvent,$,z)}}}).filter(Y=>{const re=Y.target;return!Y.button&&(!n||!ev(re,`.${n}`,e))&&(!r||ev(re,r,e))});return T.call(J),()=>{T.on(".drag",null)}}}},[e,t,n,r,l,c,o,u,E]),f}function _0(){const e=bs();return p.useCallback(n=>{const{nodeInternals:r,nodeExtent:o,updateNodePositions:l,getNodes:u,snapToGrid:c,snapGrid:f,onError:m,nodesDraggable:_}=e.getState(),g=u().filter(E=>E.selected&&(E.draggable||_&&typeof E.draggable>"u")),w=c?f[0]:5,x=c?f[1]:5,k=n.isShiftPressed?4:1,j=n.x*w*k,N=n.y*x*k,C=g.map(E=>{if(E.positionAbsolute){const T={x:E.positionAbsolute.x+j,y:E.positionAbsolute.y+N};c&&(T.x=f[0]*Math.round(T.x/f[0]),T.y=f[1]*Math.round(T.y/f[1]));const{positionAbsolute:I,position:K}=h0(E,T,r,o,void 0,m);E.position=K,E.positionAbsolute=I}return E});l(C,!0,!1)},[])}const vu={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var Zd=e=>{const t=({id:n,type:r,data:o,xPos:l,yPos:u,xPosOrigin:c,yPosOrigin:f,selected:m,onClick:_,onMouseEnter:g,onMouseMove:w,onMouseLeave:x,onContextMenu:k,onDoubleClick:j,style:N,className:C,isDraggable:E,isSelectable:T,isConnectable:I,isFocusable:K,selectNodesOnDrag:U,sourcePosition:J,targetPosition:Y,hidden:re,resizeObserver:ce,dragHandle:fe,zIndex:W,isParent:O,noDragClassName:$,noPanClassName:z,initialized:A,disableKeyboardA11y:te,ariaLabel:P,rfId:F,hasHandleBounds:G})=>{const R=bs(),Z=p.useRef(null),X=p.useRef(J),Q=p.useRef(Y),le=p.useRef(r),ge=T||E||_||g||w||x,pe=_0(),ye=Xd(n,R.getState,g),Ne=Xd(n,R.getState,w),Ue=Xd(n,R.getState,x),We=Xd(n,R.getState,k),pt=Xd(n,R.getState,j),Fe=Ke=>{const{nodeDragThreshold:ke}=R.getState();if(T&&(!U||!E||ke>0)&&Jp({id:n,store:R,nodeRef:Z}),_){const Re=R.getState().nodeInternals.get(n);Re&&_(Ke,{...Re})}},tt=Ke=>{if(!Hp(Ke))if(zb.includes(Ke.key)&&T){const ke=Ke.key==="Escape";Jp({id:n,store:R,unselect:ke,nodeRef:Z})}else!te&&E&&m&&Object.prototype.hasOwnProperty.call(vu,Ke.key)&&(R.setState({ariaLiveMessage:`Moved selected node ${Ke.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~l}, y: ${~~u}`}),pe({x:vu[Ke.key].x,y:vu[Ke.key].y,isShiftPressed:Ke.shiftKey}))};p.useEffect(()=>()=>{Z.current&&(ce==null||ce.unobserve(Z.current))},[]),p.useEffect(()=>{if(Z.current&&!re){const Ke=Z.current;(!A||!G)&&(ce==null||ce.unobserve(Ke),ce==null||ce.observe(Ke))}},[re,A,G]),p.useEffect(()=>{const Ke=le.current!==r,ke=X.current!==J,Re=Q.current!==Y;Z.current&&(Ke||ke||Re)&&(Ke&&(le.current=r),ke&&(X.current=J),Re&&(Q.current=Y),R.getState().updateNodeDimensions([{id:n,nodeElement:Z.current,forceUpdate:!0}]))},[n,r,J,Y]);const lt=m0({nodeRef:Z,disabled:re||!E,noDragClassName:$,handleSelector:fe,nodeId:n,isSelectable:T,selectNodesOnDrag:U});return re?null:ve.createElement("div",{className:Ks(["react-flow__node",`react-flow__node-${r}`,{[z]:E},C,{selected:m,selectable:T,parent:O,dragging:lt}]),ref:Z,style:{zIndex:W,transform:`translate(${c}px,${f}px)`,pointerEvents:ge?"all":"none",visibility:A?"visible":"hidden",...N},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:ye,onMouseMove:Ne,onMouseLeave:Ue,onContextMenu:We,onClick:Fe,onDoubleClick:pt,onKeyDown:K?tt:void 0,tabIndex:K?0:void 0,role:K?"button":void 0,"aria-describedby":te?void 0:`${o0}-${F}`,"aria-label":P},ve.createElement(FM,{value:n},ve.createElement(e,{id:n,data:o,type:r,xPos:l,yPos:u,selected:m,isConnectable:I,sourcePosition:J,targetPosition:Y,dragging:lt,dragHandle:fe,zIndex:W})))};return t.displayName="NodeWrapper",p.memo(t)};const CR=e=>{const t=e.getNodes().filter(n=>n.selected);return{...Fm(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function ER({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=bs(),{width:o,height:l,x:u,y:c,transformString:f,userSelectionActive:m}=Ln(CR,Os),_=_0(),g=p.useRef(null);if(p.useEffect(()=>{var k;n||(k=g.current)==null||k.focus({preventScroll:!0})},[n]),m0({nodeRef:g}),m||!o||!l)return null;const w=e?k=>{const j=r.getState().getNodes().filter(N=>N.selected);e(k,j)}:void 0,x=k=>{Object.prototype.hasOwnProperty.call(vu,k.key)&&_({x:vu[k.key].x,y:vu[k.key].y,isShiftPressed:k.shiftKey})};return ve.createElement("div",{className:Ks(["react-flow__nodesselection","react-flow__container",t]),style:{transform:f}},ve.createElement("div",{ref:g,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 AR=p.memo(ER);const $R=e=>e.nodesSelectionActive,p0=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,deleteKeyCode:c,onMove:f,onMoveStart:m,onMoveEnd:_,selectionKeyCode:g,selectionOnDrag:w,selectionMode:x,onSelectionStart:k,onSelectionEnd:j,multiSelectionKeyCode:N,panActivationKeyCode:C,zoomActivationKeyCode:E,elementsSelectable:T,zoomOnScroll:I,zoomOnPinch:K,panOnScroll:U,panOnScrollSpeed:J,panOnScrollMode:Y,zoomOnDoubleClick:re,panOnDrag:ce,defaultViewport:fe,translateExtent:W,minZoom:O,maxZoom:$,preventScrolling:z,onSelectionContextMenu:A,noWheelClassName:te,noPanClassName:P,disableKeyboardA11y:F})=>{const G=Ln($R),R=Sf(g),Z=Sf(C),X=Z||ce,Q=Z||U,le=R||w&&X!==!0;return mR({deleteKeyCode:c,multiSelectionKeyCode:N}),ve.createElement(yR,{onMove:f,onMoveStart:m,onMoveEnd:_,onPaneContextMenu:l,elementsSelectable:T,zoomOnScroll:I,zoomOnPinch:K,panOnScroll:Q,panOnScrollSpeed:J,panOnScrollMode:Y,zoomOnDoubleClick:re,panOnDrag:!R&&X,defaultViewport:fe,translateExtent:W,minZoom:O,maxZoom:$,zoomActivationKeyCode:E,preventScrolling:z,noWheelClassName:te,noPanClassName:P},ve.createElement(d0,{onSelectionStart:k,onSelectionEnd:j,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:l,onPaneScroll:u,panOnDrag:X,isSelecting:!!le,selectionMode:x},e,G&&ve.createElement(AR,{onSelectionContextMenu:A,noPanClassName:P,disableKeyboardA11y:F})))};p0.displayName="FlowRenderer";var TR=p.memo(p0);function MR(e){return Ln(p.useCallback(n=>e?Gb(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function RR(e){const t={input:Zd(e.input||n0),default:Zd(e.default||Yp),output:Zd(e.output||r0),group:Zd(e.group||Dg)},n={},r=Object.keys(e).filter(o=>!["input","default","output","group"].includes(o)).reduce((o,l)=>(o[l]=Zd(e[l]||Yp),o),n);return{...t,...r}}const LR=({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]},IR=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),g0=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,updateNodeDimensions:l,onError:u}=Ln(IR,Os),c=MR(e.onlyRenderVisibleElements),f=p.useRef(),m=p.useMemo(()=>{if(typeof ResizeObserver>"u")return null;const _=new ResizeObserver(g=>{const w=g.map(x=>({id:x.target.getAttribute("data-id"),nodeElement:x.target,forceUpdate:!0}));l(w)});return f.current=_,_},[]);return p.useEffect(()=>()=>{var _;(_=f==null?void 0:f.current)==null||_.disconnect()},[]),ve.createElement("div",{className:"react-flow__nodes",style:zg},c.map(_=>{var K,U,J;let g=_.type||"default";e.nodeTypes[g]||(u==null||u("003",ua.error003(g)),g="default");const w=e.nodeTypes[g]||e.nodeTypes.default,x=!!(_.draggable||t&&typeof _.draggable>"u"),k=!!(_.selectable||o&&typeof _.selectable>"u"),j=!!(_.connectable||n&&typeof _.connectable>"u"),N=!!(_.focusable||r&&typeof _.focusable>"u"),C=e.nodeExtent?Mg(_.positionAbsolute,e.nodeExtent):_.positionAbsolute,E=(C==null?void 0:C.x)??0,T=(C==null?void 0:C.y)??0,I=LR({x:E,y:T,width:_.width??0,height:_.height??0,origin:e.nodeOrigin});return ve.createElement(w,{key:_.id,id:_.id,className:_.className,style:_.style,type:g,data:_.data,sourcePosition:_.sourcePosition||_t.Bottom,targetPosition:_.targetPosition||_t.Top,hidden:_.hidden,xPos:E,yPos:T,xPosOrigin:I.x,yPosOrigin:I.y,selectNodesOnDrag:e.selectNodesOnDrag,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,selected:!!_.selected,isDraggable:x,isSelectable:k,isConnectable:j,isFocusable:N,resizeObserver:m,dragHandle:_.dragHandle,zIndex:((K=_[fs])==null?void 0:K.z)??0,isParent:!!((U=_[fs])!=null&&U.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!_.width&&!!_.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:_.ariaLabel,hasHandleBounds:!!((J=_[fs])!=null&&J.handleBounds)})}))};g0.displayName="NodeRenderer";var OR=p.memo(g0);const PR=(e,t,n)=>n===_t.Left?e-t:n===_t.Right?e+t:e,DR=(e,t,n)=>n===_t.Top?e-t:n===_t.Bottom?e+t:e,nv="react-flow__edgeupdater",sv=({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:Ks([nv,`${nv}-${c}`]),cx:PR(t,r,e),cy:DR(n,r,e),r,stroke:"transparent",fill:"transparent"}),FR=()=>!0;var lu=e=>{const t=({id:n,className:r,type:o,data:l,onClick:u,onEdgeDoubleClick:c,selected:f,animated:m,label:_,labelStyle:g,labelShowBg:w,labelBgStyle:x,labelBgPadding:k,labelBgBorderRadius:j,style:N,source:C,target:E,sourceX:T,sourceY:I,targetX:K,targetY:U,sourcePosition:J,targetPosition:Y,elementsSelectable:re,hidden:ce,sourceHandleId:fe,targetHandleId:W,onContextMenu:O,onMouseEnter:$,onMouseMove:z,onMouseLeave:A,edgeUpdaterRadius:te,onEdgeUpdate:P,onEdgeUpdateStart:F,onEdgeUpdateEnd:G,markerEnd:R,markerStart:Z,rfId:X,ariaLabel:Q,isFocusable:le,isUpdatable:ge,pathOptions:pe,interactionWidth:ye})=>{const Ne=p.useRef(null),[Ue,We]=p.useState(!1),[pt,Fe]=p.useState(!1),tt=bs(),lt=p.useMemo(()=>`url('#${Gp(Z,X)}')`,[Z,X]),Ke=p.useMemo(()=>`url('#${Gp(R,X)}')`,[R,X]);if(ce)return null;const ke=Ot=>{var wn;const{edges:pn,addSelectedEdges:Bn,unselectNodesAndEdges:An,multiSelectionActive:gn}=tt.getState(),In=pn.find(js=>js.id===n);In&&(re&&(tt.setState({nodesSelectionActive:!1}),In.selected&&gn?(An({nodes:[],edges:[In]}),(wn=Ne.current)==null||wn.blur()):Bn([n])),u&&u(Ot,In))},Re=Jd(n,tt.getState,c),ht=Jd(n,tt.getState,O),xe=Jd(n,tt.getState,$),Ie=Jd(n,tt.getState,z),qe=Jd(n,tt.getState,A),zt=(Ot,pn)=>{if(Ot.button!==0)return;const{edges:Bn,isValidConnection:An}=tt.getState(),gn=pn?E:C,In=(pn?W:fe)||null,wn=pn?"target":"source",js=An||FR,Kn=pn,ks=Bn.find(ae=>ae.id===n);Fe(!0),F==null||F(Ot,ks,wn);const Nr=ae=>{Fe(!1),G==null||G(ae,ks,wn)};Zb({event:Ot,handleId:In,nodeId:gn,onConnect:ae=>P==null?void 0:P(ks,ae),isTarget:Kn,getState:tt.getState,setState:tt.setState,isValidConnection:js,edgeUpdaterType:wn,onEdgeUpdateEnd:Nr})},en=Ot=>zt(Ot,!0),bn=Ot=>zt(Ot,!1),Wt=()=>We(!0),It=()=>We(!1),Sn=!re&&!u,ns=Ot=>{var pn;if(zb.includes(Ot.key)&&re){const{unselectNodesAndEdges:Bn,addSelectedEdges:An,edges:gn}=tt.getState();Ot.key==="Escape"?((pn=Ne.current)==null||pn.blur(),Bn({edges:[gn.find(wn=>wn.id===n)]})):An([n])}};return ve.createElement("g",{className:Ks(["react-flow__edge",`react-flow__edge-${o}`,r,{selected:f,animated:m,inactive:Sn,updating:Ue}]),onClick:ke,onDoubleClick:Re,onContextMenu:ht,onMouseEnter:xe,onMouseMove:Ie,onMouseLeave:qe,onKeyDown:le?ns:void 0,tabIndex:le?0:void 0,role:le?"button":"img","data-testid":`rf__edge-${n}`,"aria-label":Q===null?void 0:Q||`Edge from ${C} to ${E}`,"aria-describedby":le?`${a0}-${X}`:void 0,ref:Ne},!pt&&ve.createElement(e,{id:n,source:C,target:E,selected:f,animated:m,label:_,labelStyle:g,labelShowBg:w,labelBgStyle:x,labelBgPadding:k,labelBgBorderRadius:j,data:l,style:N,sourceX:T,sourceY:I,targetX:K,targetY:U,sourcePosition:J,targetPosition:Y,sourceHandleId:fe,targetHandleId:W,markerStart:lt,markerEnd:Ke,pathOptions:pe,interactionWidth:ye}),ge&&ve.createElement(ve.Fragment,null,(ge==="source"||ge===!0)&&ve.createElement(sv,{position:J,centerX:T,centerY:I,radius:te,onMouseDown:en,onMouseEnter:Wt,onMouseOut:It,type:"source"}),(ge==="target"||ge===!0)&&ve.createElement(sv,{position:Y,centerX:K,centerY:U,radius:te,onMouseDown:bn,onMouseEnter:Wt,onMouseOut:It,type:"target"})))};return t.displayName="EdgeWrapper",p.memo(t)};function zR(e){const t={default:lu(e.default||bm),straight:lu(e.bezier||Ig),step:lu(e.step||Lg),smoothstep:lu(e.step||Dm),simplebezier:lu(e.simplebezier||Rg)},n={},r=Object.keys(e).filter(o=>!["default","bezier"].includes(o)).reduce((o,l)=>(o[l]=lu(e[l]||bm),o),n);return{...t,...r}}function rv(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 _t.Top:return{x:r+l/2,y:o};case _t.Right:return{x:r+l,y:o+u/2};case _t.Bottom:return{x:r+l/2,y:o+u};case _t.Left:return{x:r,y:o+u/2}}}function iv(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const BR=(e,t,n,r,o,l)=>{const u=rv(n,e,t),c=rv(l,r,o);return{sourceX:u.x,sourceY:u.y,targetX:c.x,targetY:c.y}};function UR({sourcePos:e,targetPos:t,sourceWidth:n,sourceHeight:r,targetWidth:o,targetHeight:l,width:u,height:c,transform:f}){const m={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)};m.x===m.x2&&(m.x2+=1),m.y===m.y2&&(m.y2+=1);const _=bf({x:(0-f[0])/f[2],y:(0-f[1])/f[2],width:u/f[2],height:c/f[2]}),g=Math.max(0,Math.min(_.x2,m.x2)-Math.max(_.x,m.x)),w=Math.max(0,Math.min(_.y2,m.y2)-Math.max(_.y,m.y));return Math.ceil(g*w)>0}function ov(e){var r,o,l,u,c;const t=((r=e==null?void 0:e[fs])==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 qR(e,t,n=!1){let r=-1;const o=e.reduce((u,c)=>{var _,g;const f=ki(c.zIndex);let m=f?c.zIndex:0;if(n){const w=t.get(c.target),x=t.get(c.source),k=c.selected||(w==null?void 0:w.selected)||(x==null?void 0:x.selected),j=Math.max(((_=x==null?void 0:x[fs])==null?void 0:_.z)||0,((g=w==null?void 0:w[fs])==null?void 0:g.z)||0,1e3);m=(f?c.zIndex:0)+(k?j:0)}return u[m]?u[m].push(c):u[m]=[c],r=m>r?m: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 HR(e,t,n){const r=Ln(p.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)&&UR({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 qR(r,t,n)}const VR=({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"}),GR=({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"}),av={[kf.Arrow]:VR,[kf.ArrowClosed]:GR};function KR(e){const t=bs();return p.useMemo(()=>{var o,l;return Object.prototype.hasOwnProperty.call(av,e)?av[e]:((l=(o=t.getState()).onError)==null||l.call(o,"009",ua.error009(e)),null)},[e])}const YR=({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=KR(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},JR=({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=Gp(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))},y0=({defaultColor:e,rfId:t})=>{const n=Ln(p.useCallback(JR({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(YR,{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})))};y0.displayName="MarkerDefinitions";var XR=p.memo(y0);const ZR=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}),w0=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:r,edgeTypes:o,noPanClassName:l,onEdgeUpdate:u,onEdgeContextMenu:c,onEdgeMouseEnter:f,onEdgeMouseMove:m,onEdgeMouseLeave:_,onEdgeClick:g,edgeUpdaterRadius:w,onEdgeDoubleClick:x,onEdgeUpdateStart:k,onEdgeUpdateEnd:j,children:N})=>{const{edgesFocusable:C,edgesUpdatable:E,elementsSelectable:T,width:I,height:K,connectionMode:U,nodeInternals:J,onError:Y}=Ln(ZR,Os),re=HR(t,J,n);return I?ve.createElement(ve.Fragment,null,re.map(({level:ce,edges:fe,isMaxLevel:W})=>ve.createElement("svg",{key:ce,style:{zIndex:ce},width:I,height:K,className:"react-flow__edges react-flow__container"},W&&ve.createElement(XR,{defaultColor:e,rfId:r}),ve.createElement("g",null,fe.map(O=>{const[$,z,A]=ov(J.get(O.source)),[te,P,F]=ov(J.get(O.target));if(!A||!F)return null;let G=O.type||"default";o[G]||(Y==null||Y("011",ua.error011(G)),G="default");const R=o[G]||o.default,Z=U===cc.Strict?P.target:(P.target??[]).concat(P.source??[]),X=iv(z.source,O.sourceHandle),Q=iv(Z,O.targetHandle),le=(X==null?void 0:X.position)||_t.Bottom,ge=(Q==null?void 0:Q.position)||_t.Top,pe=!!(O.focusable||C&&typeof O.focusable>"u"),ye=typeof u<"u"&&(O.updatable||E&&typeof O.updatable>"u");if(!X||!Q)return Y==null||Y("008",ua.error008(X,O)),null;const{sourceX:Ne,sourceY:Ue,targetX:We,targetY:pt}=BR($,X,le,te,Q,ge);return ve.createElement(R,{key:O.id,id:O.id,className:Ks([O.className,l]),type:G,data:O.data,selected:!!O.selected,animated:!!O.animated,hidden:!!O.hidden,label:O.label,labelStyle:O.labelStyle,labelShowBg:O.labelShowBg,labelBgStyle:O.labelBgStyle,labelBgPadding:O.labelBgPadding,labelBgBorderRadius:O.labelBgBorderRadius,style:O.style,source:O.source,target:O.target,sourceHandleId:O.sourceHandle,targetHandleId:O.targetHandle,markerEnd:O.markerEnd,markerStart:O.markerStart,sourceX:Ne,sourceY:Ue,targetX:We,targetY:pt,sourcePosition:le,targetPosition:ge,elementsSelectable:T,onEdgeUpdate:u,onContextMenu:c,onMouseEnter:f,onMouseMove:m,onMouseLeave:_,onClick:g,edgeUpdaterRadius:w,onEdgeDoubleClick:x,onEdgeUpdateStart:k,onEdgeUpdateEnd:j,rfId:r,ariaLabel:O.ariaLabel,isFocusable:pe,isUpdatable:ye,pathOptions:"pathOptions"in O?O.pathOptions:void 0,interactionWidth:O.interactionWidth})})))),N):null};w0.displayName="EdgeRenderer";var QR=p.memo(w0);const e3=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function t3({children:e}){const t=Ln(e3);return ve.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function n3(e){const t=Fg(),n=p.useRef(!1);p.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const s3={[_t.Left]:_t.Right,[_t.Right]:_t.Left,[_t.Top]:_t.Bottom,[_t.Bottom]:_t.Top},v0=({nodeId:e,handleType:t,style:n,type:r=il.Bezier,CustomComponent:o,connectionStatus:l})=>{var U,J,Y;const{fromNode:u,handleId:c,toX:f,toY:m,connectionMode:_}=Ln(p.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]),Os),g=(U=u==null?void 0:u[fs])==null?void 0:U.handleBounds;let w=g==null?void 0:g[t];if(_===cc.Loose&&(w=w||(g==null?void 0:g[t==="source"?"target":"source"])),!u||!w)return null;const x=c?w.find(re=>re.id===c):w[0],k=x?x.x+x.width/2:(u.width??0)/2,j=x?x.y+x.height/2:u.height??0,N=(((J=u.positionAbsolute)==null?void 0:J.x)??0)+k,C=(((Y=u.positionAbsolute)==null?void 0:Y.y)??0)+j,E=x==null?void 0:x.position,T=E?s3[E]:null;if(!E||!T)return null;if(o)return ve.createElement(o,{connectionLineType:r,connectionLineStyle:n,fromNode:u,fromHandle:x,fromX:N,fromY:C,toX:f,toY:m,fromPosition:E,toPosition:T,connectionStatus:l});let I="";const K={sourceX:N,sourceY:C,sourcePosition:E,targetX:f,targetY:m,targetPosition:T};return r===il.Bezier?[I]=Hb(K):r===il.Step?[I]=Vp({...K,borderRadius:0}):r===il.SmoothStep?[I]=Vp(K):r===il.SimpleBezier?[I]=qb(K):I=`M${N},${C} ${f},${m}`,ve.createElement("path",{d:I,fill:"none",className:"react-flow__connection-path",style:n})};v0.displayName="ConnectionLine";const r3=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function i3({containerStyle:e,style:t,type:n,component:r}){const{nodeId:o,handleType:l,nodesConnectable:u,width:c,height:f,connectionStatus:m}=Ln(r3,Os);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:Ks(["react-flow__connection",m])},ve.createElement(v0,{nodeId:o,handleType:l,style:t,type:n,CustomComponent:r,connectionStatus:m})))}function lv(e,t){return p.useRef(null),bs(),p.useMemo(()=>t(e),[e])}const x0=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:r,onMoveEnd:o,onInit:l,onNodeClick:u,onEdgeClick:c,onNodeDoubleClick:f,onEdgeDoubleClick:m,onNodeMouseEnter:_,onNodeMouseMove:g,onNodeMouseLeave:w,onNodeContextMenu:x,onSelectionContextMenu:k,onSelectionStart:j,onSelectionEnd:N,connectionLineType:C,connectionLineStyle:E,connectionLineComponent:T,connectionLineContainerStyle:I,selectionKeyCode:K,selectionOnDrag:U,selectionMode:J,multiSelectionKeyCode:Y,panActivationKeyCode:re,zoomActivationKeyCode:ce,deleteKeyCode:fe,onlyRenderVisibleElements:W,elementsSelectable:O,selectNodesOnDrag:$,defaultViewport:z,translateExtent:A,minZoom:te,maxZoom:P,preventScrolling:F,defaultMarkerColor:G,zoomOnScroll:R,zoomOnPinch:Z,panOnScroll:X,panOnScrollSpeed:Q,panOnScrollMode:le,zoomOnDoubleClick:ge,panOnDrag:pe,onPaneClick:ye,onPaneMouseEnter:Ne,onPaneMouseMove:Ue,onPaneMouseLeave:We,onPaneScroll:pt,onPaneContextMenu:Fe,onEdgeUpdate:tt,onEdgeContextMenu:lt,onEdgeMouseEnter:Ke,onEdgeMouseMove:ke,onEdgeMouseLeave:Re,edgeUpdaterRadius:ht,onEdgeUpdateStart:xe,onEdgeUpdateEnd:Ie,noDragClassName:qe,noWheelClassName:zt,noPanClassName:en,elevateEdgesOnSelect:bn,disableKeyboardA11y:Wt,nodeOrigin:It,nodeExtent:Sn,rfId:ns})=>{const Ot=lv(e,RR),pn=lv(t,zR);return n3(l),ve.createElement(TR,{onPaneClick:ye,onPaneMouseEnter:Ne,onPaneMouseMove:Ue,onPaneMouseLeave:We,onPaneContextMenu:Fe,onPaneScroll:pt,deleteKeyCode:fe,selectionKeyCode:K,selectionOnDrag:U,selectionMode:J,onSelectionStart:j,onSelectionEnd:N,multiSelectionKeyCode:Y,panActivationKeyCode:re,zoomActivationKeyCode:ce,elementsSelectable:O,onMove:n,onMoveStart:r,onMoveEnd:o,zoomOnScroll:R,zoomOnPinch:Z,zoomOnDoubleClick:ge,panOnScroll:X,panOnScrollSpeed:Q,panOnScrollMode:le,panOnDrag:pe,defaultViewport:z,translateExtent:A,minZoom:te,maxZoom:P,onSelectionContextMenu:k,preventScrolling:F,noDragClassName:qe,noWheelClassName:zt,noPanClassName:en,disableKeyboardA11y:Wt},ve.createElement(t3,null,ve.createElement(QR,{edgeTypes:pn,onEdgeClick:c,onEdgeDoubleClick:m,onEdgeUpdate:tt,onlyRenderVisibleElements:W,onEdgeContextMenu:lt,onEdgeMouseEnter:Ke,onEdgeMouseMove:ke,onEdgeMouseLeave:Re,onEdgeUpdateStart:xe,onEdgeUpdateEnd:Ie,edgeUpdaterRadius:ht,defaultMarkerColor:G,noPanClassName:en,elevateEdgesOnSelect:!!bn,disableKeyboardA11y:Wt,rfId:ns},ve.createElement(i3,{style:E,type:C,component:T,containerStyle:I})),ve.createElement("div",{className:"react-flow__edgelabel-renderer"}),ve.createElement(OR,{nodeTypes:Ot,onNodeClick:u,onNodeDoubleClick:f,onNodeMouseEnter:_,onNodeMouseMove:g,onNodeMouseLeave:w,onNodeContextMenu:x,selectNodesOnDrag:$,onlyRenderVisibleElements:W,noPanClassName:en,noDragClassName:qe,disableKeyboardA11y:Wt,nodeOrigin:It,nodeExtent:Sn,rfId:ns})))};x0.displayName="GraphView";var o3=p.memo(x0);const Xp=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Qa={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:Xp,nodeExtent:Xp,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:cc.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:RM,isValidConnection:void 0},a3=()=>KE((e,t)=>({...Qa,setNodes:n=>{const{nodeInternals:r,nodeOrigin:o,elevateNodesOnSelect:l}=t();e({nodeInternals:J_(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?J_(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:m}=t(),_=f==null?void 0:f.querySelector(".react-flow__viewport");if(!_)return;const g=window.getComputedStyle(_),{m22:w}=new window.DOMMatrixReadOnly(g.transform),x=n.reduce((j,N)=>{const C=o.get(N.id);if(C){const E=Tg(N.nodeElement);!!(E.width&&E.height&&(C.width!==E.width||C.height!==E.height||N.forceUpdate))&&(o.set(C.id,{...C,[fs]:{...C[fs],handleBounds:{source:tv(".source",N.nodeElement,w,m),target:tv(".target",N.nodeElement,w,m)}},...E}),j.push({id:C.id,type:"dimensions",dimensions:E}))}return j},[]);c0(o,m);const k=u||l&&!u&&u0(t,{initial:!0,...c});e({nodeInternals:new Map(o),fitViewOnInitDone:k}),(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 m=bR(n,c()),_=J_(m,o,u,f);e({nodeInternals:_})}r==null||r(n)}},addSelectedNodes:n=>{const{multiSelectionActive:r,edges:o,getNodes:l}=t();let u,c=null;r?u=n.map(f=>rl(f,!0)):(u=hu(l(),n),c=hu(o,[])),qh({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=>rl(f,!0)):(u=hu(o,n),c=hu(l(),[])),qh({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(_=>(_.selected=!1,rl(_.id,!1))),m=c.map(_=>rl(_.id,!1));qh({changedNodes:f,changedEdges:m,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=>rl(c.id,!1)),u=n.filter(c=>c.selected).map(c=>rl(c.id,!1));qh({changedNodes:l,changedEdges:u,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:r}=t();r.forEach(o=>{o.positionAbsolute=Mg(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 m=aa.translate(r[0]+n.x,r[1]+n.y).scale(r[2]),_=[[0,0],[o,l]],g=u==null?void 0:u.constrain()(m,_,f);return u.transform(c,g),r[0]!==g.x||r[1]!==g.y||r[2]!==g.k},cancelConnection:()=>e({connectionNodeId:Qa.connectionNodeId,connectionHandleId:Qa.connectionHandleId,connectionHandleType:Qa.connectionHandleType,connectionStatus:Qa.connectionStatus,connectionStartHandle:Qa.connectionStartHandle,connectionEndHandle:Qa.connectionEndHandle}),reset:()=>e({...Qa})}),Object.is),Bg=({children:e})=>{const t=p.useRef(null);return t.current||(t.current=a3()),ve.createElement(NM,{value:t.current},e)};Bg.displayName="ReactFlowProvider";const b0=({children:e})=>p.useContext(Pm)?ve.createElement(ve.Fragment,null,e):ve.createElement(Bg,null,e);b0.displayName="ReactFlowWrapper";const l3={input:n0,default:Yp,output:r0,group:Dg},c3={default:bm,straight:Ig,step:Lg,smoothstep:Dm,simplebezier:Rg},u3=[0,0],d3=[15,15],f3={x:0,y:0,zoom:1},h3={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},j0=p.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:o,nodeTypes:l=l3,edgeTypes:u=c3,onNodeClick:c,onEdgeClick:f,onInit:m,onMove:_,onMoveStart:g,onMoveEnd:w,onConnect:x,onConnectStart:k,onConnectEnd:j,onClickConnectStart:N,onClickConnectEnd:C,onNodeMouseEnter:E,onNodeMouseMove:T,onNodeMouseLeave:I,onNodeContextMenu:K,onNodeDoubleClick:U,onNodeDragStart:J,onNodeDrag:Y,onNodeDragStop:re,onNodesDelete:ce,onEdgesDelete:fe,onSelectionChange:W,onSelectionDragStart:O,onSelectionDrag:$,onSelectionDragStop:z,onSelectionContextMenu:A,onSelectionStart:te,onSelectionEnd:P,connectionMode:F=cc.Strict,connectionLineType:G=il.Bezier,connectionLineStyle:R,connectionLineComponent:Z,connectionLineContainerStyle:X,deleteKeyCode:Q="Backspace",selectionKeyCode:le="Shift",selectionOnDrag:ge=!1,selectionMode:pe=jf.Full,panActivationKeyCode:ye="Space",multiSelectionKeyCode:Ne=xm()?"Meta":"Control",zoomActivationKeyCode:Ue=xm()?"Meta":"Control",snapToGrid:We=!1,snapGrid:pt=d3,onlyRenderVisibleElements:Fe=!1,selectNodesOnDrag:tt=!0,nodesDraggable:lt,nodesConnectable:Ke,nodesFocusable:ke,nodeOrigin:Re=u3,edgesFocusable:ht,edgesUpdatable:xe,elementsSelectable:Ie,defaultViewport:qe=f3,minZoom:zt=.5,maxZoom:en=2,translateExtent:bn=Xp,preventScrolling:Wt=!0,nodeExtent:It,defaultMarkerColor:Sn="#b1b1b7",zoomOnScroll:ns=!0,zoomOnPinch:Ot=!0,panOnScroll:pn=!1,panOnScrollSpeed:Bn=.5,panOnScrollMode:An=Xl.Free,zoomOnDoubleClick:gn=!0,panOnDrag:In=!0,onPaneClick:wn,onPaneMouseEnter:js,onPaneMouseMove:Kn,onPaneMouseLeave:ks,onPaneScroll:Nr,onPaneContextMenu:On,children:ae,onEdgeUpdate:je,onEdgeContextMenu:Ye,onEdgeDoubleClick:Ge,onEdgeMouseEnter:rt,onEdgeMouseMove:ct,onEdgeMouseLeave:Et,onEdgeUpdateStart:jt,onEdgeUpdateEnd:Kt,edgeUpdaterRadius:xt=10,onNodesChange:Yt,onEdgesChange:qt,noDragClassName:Pt="nodrag",noWheelClassName:At="nowheel",noPanClassName:$t="nopan",fitView:De=!1,fitViewOptions:on,connectOnClick:dt=!0,attributionPosition:tn,proOptions:ft,defaultEdgeOptions:Un,elevateNodesOnSelect:an=!0,elevateEdgesOnSelect:Ys=!1,disableKeyboardA11y:ss=!1,autoPanOnConnect:Wr=!0,autoPanOnNodeDrag:dr=!0,connectionRadius:ii=20,isValidConnection:oi,onError:Ps,style:ue,id:fr,nodeDragThreshold:Vi,...hr},Cr)=>{const qr=fr||"1";return ve.createElement("div",{...hr,style:{...ue,...h3},ref:Cr,className:Ks(["react-flow",o]),"data-testid":"rf__wrapper",id:fr},ve.createElement(b0,null,ve.createElement(o3,{onInit:m,onMove:_,onMoveStart:g,onMoveEnd:w,onNodeClick:c,onEdgeClick:f,onNodeMouseEnter:E,onNodeMouseMove:T,onNodeMouseLeave:I,onNodeContextMenu:K,onNodeDoubleClick:U,nodeTypes:l,edgeTypes:u,connectionLineType:G,connectionLineStyle:R,connectionLineComponent:Z,connectionLineContainerStyle:X,selectionKeyCode:le,selectionOnDrag:ge,selectionMode:pe,deleteKeyCode:Q,multiSelectionKeyCode:Ne,panActivationKeyCode:ye,zoomActivationKeyCode:Ue,onlyRenderVisibleElements:Fe,selectNodesOnDrag:tt,defaultViewport:qe,translateExtent:bn,minZoom:zt,maxZoom:en,preventScrolling:Wt,zoomOnScroll:ns,zoomOnPinch:Ot,zoomOnDoubleClick:gn,panOnScroll:pn,panOnScrollSpeed:Bn,panOnScrollMode:An,panOnDrag:In,onPaneClick:wn,onPaneMouseEnter:js,onPaneMouseMove:Kn,onPaneMouseLeave:ks,onPaneScroll:Nr,onPaneContextMenu:On,onSelectionContextMenu:A,onSelectionStart:te,onSelectionEnd:P,onEdgeUpdate:je,onEdgeContextMenu:Ye,onEdgeDoubleClick:Ge,onEdgeMouseEnter:rt,onEdgeMouseMove:ct,onEdgeMouseLeave:Et,onEdgeUpdateStart:jt,onEdgeUpdateEnd:Kt,edgeUpdaterRadius:xt,defaultMarkerColor:Sn,noDragClassName:Pt,noWheelClassName:At,noPanClassName:$t,elevateEdgesOnSelect:Ys,rfId:qr,disableKeyboardA11y:ss,nodeOrigin:Re,nodeExtent:It}),ve.createElement(nR,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:x,onConnectStart:k,onConnectEnd:j,onClickConnectStart:N,onClickConnectEnd:C,nodesDraggable:lt,nodesConnectable:Ke,nodesFocusable:ke,edgesFocusable:ht,edgesUpdatable:xe,elementsSelectable:Ie,elevateNodesOnSelect:an,minZoom:zt,maxZoom:en,nodeExtent:It,onNodesChange:Yt,onEdgesChange:qt,snapToGrid:We,snapGrid:pt,connectionMode:F,translateExtent:bn,connectOnClick:dt,defaultEdgeOptions:Un,fitView:De,fitViewOptions:on,onNodesDelete:ce,onEdgesDelete:fe,onNodeDragStart:J,onNodeDrag:Y,onNodeDragStop:re,onSelectionDrag:$,onSelectionDragStart:O,onSelectionDragStop:z,noPanClassName:$t,nodeOrigin:Re,rfId:qr,autoPanOnConnect:Wr,autoPanOnNodeDrag:dr,onError:Ps,connectionRadius:ii,isValidConnection:oi,nodeDragThreshold:Vi}),ve.createElement(eR,{onSelectionChange:W}),ae,ve.createElement(EM,{proOptions:ft,position:tn}),ve.createElement(aR,{rfId:qr,disableKeyboardA11y:ss})))});j0.displayName="ReactFlow";const k0=({id:e,x:t,y:n,width:r,height:o,style:l,color:u,strokeColor:c,strokeWidth:f,className:m,borderRadius:_,shapeRendering:g,onClick:w,selected:x})=>{const{background:k,backgroundColor:j}=l||{},N=u||k||j;return ve.createElement("rect",{className:Ks(["react-flow__minimap-node",{selected:x},m]),x:t,y:n,rx:_,ry:_,width:r,height:o,fill:N,stroke:c,strokeWidth:f,shapeRendering:g,onClick:w?C=>w(C,e):void 0})};k0.displayName="MiniMapNode";var m3=p.memo(k0);const _3=e=>e.nodeOrigin,p3=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),ep=e=>e instanceof Function?e:()=>e;function g3({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o=2,nodeComponent:l=m3,onClick:u}){const c=Ln(p3,Os),f=Ln(_3),m=ep(t),_=ep(e),g=ep(n),w=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return ve.createElement(ve.Fragment,null,c.map(x=>{const{x:k,y:j}=sc(x,f).positionAbsolute;return ve.createElement(l,{key:x.id,x:k,y:j,width:x.width,height:x.height,style:x.style,selected:x.selected,className:g(x),color:m(x),borderRadius:r,strokeColor:_(x),strokeWidth:o,shapeRendering:w,onClick:u,id:x.id})}))}var y3=p.memo(g3);const w3=200,v3=150,x3=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?TM(Fm(t,e.nodeOrigin),n):n,rfId:e.rfId}},b3="react-flow__minimap-desc";function S0({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:m="none",maskStrokeWidth:_=1,position:g="bottom-right",onClick:w,onNodeClick:x,pannable:k=!1,zoomable:j=!1,ariaLabel:N="React Flow mini map",inversePan:C=!1,zoomStep:E=10,offsetScale:T=5}){const I=bs(),K=p.useRef(null),{boundingRect:U,viewBB:J,rfId:Y}=Ln(x3,Os),re=(e==null?void 0:e.width)??w3,ce=(e==null?void 0:e.height)??v3,fe=U.width/re,W=U.height/ce,O=Math.max(fe,W),$=O*re,z=O*ce,A=T*O,te=U.x-($-U.width)/2-A,P=U.y-(z-U.height)/2-A,F=$+A*2,G=z+A*2,R=`${b3}-${Y}`,Z=p.useRef(0);Z.current=O,p.useEffect(()=>{if(K.current){const le=ji(K.current),ge=Ne=>{const{transform:Ue,d3Selection:We,d3Zoom:pt}=I.getState();if(Ne.sourceEvent.type!=="wheel"||!We||!pt)return;const Fe=-Ne.sourceEvent.deltaY*(Ne.sourceEvent.deltaMode===1?.05:Ne.sourceEvent.deltaMode?1:.002)*E,tt=Ue[2]*Math.pow(2,Fe);pt.scaleTo(We,tt)},pe=Ne=>{const{transform:Ue,d3Selection:We,d3Zoom:pt,translateExtent:Fe,width:tt,height:lt}=I.getState();if(Ne.sourceEvent.type!=="mousemove"||!We||!pt)return;const Ke=Z.current*Math.max(1,Ue[2])*(C?-1:1),ke={x:Ue[0]-Ne.sourceEvent.movementX*Ke,y:Ue[1]-Ne.sourceEvent.movementY*Ke},Re=[[0,0],[tt,lt]],ht=aa.translate(ke.x,ke.y).scale(Ue[2]),xe=pt.constrain()(ht,Re,Fe);pt.transform(We,xe)},ye=Lb().on("zoom",k?pe:null).on("zoom.wheel",j?ge:null);return le.call(ye),()=>{le.on("zoom",null)}}},[k,j,C,E]);const X=w?le=>{const ge=Fi(le);w(le,{x:ge[0],y:ge[1]})}:void 0,Q=x?(le,ge)=>{const pe=I.getState().nodeInternals.get(ge);x(le,pe)}:void 0;return ve.createElement(xf,{position:g,style:e,className:Ks(["react-flow__minimap",t]),"data-testid":"rf__minimap"},ve.createElement("svg",{width:re,height:ce,viewBox:`${te} ${P} ${F} ${G}`,role:"img","aria-labelledby":R,ref:K,onClick:X},N&&ve.createElement("title",{id:R},N),ve.createElement(y3,{onClick:Q,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:l,nodeClassName:o,nodeStrokeWidth:u,nodeComponent:c}),ve.createElement("path",{className:"react-flow__minimap-mask",d:`M${te-A},${P-A}h${F+A*2}v${G+A*2}h${-F-A*2}z
|
|
132
|
+
M${J.x},${J.y}h${J.width}v${J.height}h${-J.width}z`,fill:f,fillRule:"evenodd",stroke:m,strokeWidth:_,pointerEvents:"none"})))}S0.displayName="MiniMap";var j3=p.memo(S0);function k3(){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 S3(){return ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},ve.createElement("path",{d:"M0 0h32v4.2H0z"}))}function N3(){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 C3(){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 E3(){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 mu=({children:e,className:t,...n})=>ve.createElement("button",{type:"button",className:Ks(["react-flow__controls-button",t]),...n},e);mu.displayName="ControlButton";const A3=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),N0=({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:o,onZoomIn:l,onZoomOut:u,onFitView:c,onInteractiveChange:f,className:m,children:_,position:g="bottom-left"})=>{const w=bs(),[x,k]=p.useState(!1),{isInteractive:j,minZoomReached:N,maxZoomReached:C}=Ln(A3,Os),{zoomIn:E,zoomOut:T,fitView:I}=Fg();if(p.useEffect(()=>{k(!0)},[]),!x)return null;const K=()=>{E(),l==null||l()},U=()=>{T(),u==null||u()},J=()=>{I(o),c==null||c()},Y=()=>{w.setState({nodesDraggable:!j,nodesConnectable:!j,elementsSelectable:!j}),f==null||f(!j)};return ve.createElement(xf,{className:Ks(["react-flow__controls",m]),position:g,style:e,"data-testid":"rf__controls"},t&&ve.createElement(ve.Fragment,null,ve.createElement(mu,{onClick:K,className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:C},ve.createElement(k3,null)),ve.createElement(mu,{onClick:U,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:N},ve.createElement(S3,null))),n&&ve.createElement(mu,{className:"react-flow__controls-fitview",onClick:J,title:"fit view","aria-label":"fit view"},ve.createElement(N3,null)),r&&ve.createElement(mu,{className:"react-flow__controls-interactive",onClick:Y,title:"toggle interactivity","aria-label":"toggle interactivity"},j?ve.createElement(E3,null):ve.createElement(C3,null)),_)};N0.displayName="Controls";var $3=p.memo(N0),qi;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(qi||(qi={}));function T3({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 M3({color:e,radius:t}){return ve.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const R3={[qi.Dots]:"#91919a",[qi.Lines]:"#eee",[qi.Cross]:"#e2e2e2"},L3={[qi.Dots]:1,[qi.Lines]:1,[qi.Cross]:6},I3=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function C0({id:e,variant:t=qi.Dots,gap:n=20,size:r,lineWidth:o=1,offset:l=2,color:u,style:c,className:f}){const m=p.useRef(null),{transform:_,patternId:g}=Ln(I3,Os),w=u||R3[t],x=r||L3[t],k=t===qi.Dots,j=t===qi.Cross,N=Array.isArray(n)?n:[n,n],C=[N[0]*_[2]||1,N[1]*_[2]||1],E=x*_[2],T=j?[E,E]:C,I=k?[E/l,E/l]:[T[0]/l,T[1]/l];return ve.createElement("svg",{className:Ks(["react-flow__background",f]),style:{...c,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:m,"data-testid":"rf__background"},ve.createElement("pattern",{id:g+e,x:_[0]%C[0],y:_[1]%C[1],width:C[0],height:C[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${I[0]},-${I[1]})`},k?ve.createElement(M3,{color:w,radius:E/l}):ve.createElement(T3,{dimensions:T,color:w,lineWidth:o})),ve.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${g+e})`}))}C0.displayName="Background";var O3=p.memo(C0);function E0(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,m=Math.min(c,f),_=Math.max(c,f);return{x:r,y:o,zoom:Math.min(_,Math.max(m,l))}}function km(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 P3(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 D3(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return km(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 km(t)}function Zp(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 Qp(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 A0(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 F3(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 cv(e,t,n){var k;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 N=String((j==null?void 0:j.source)||"").trim(),C=String((j==null?void 0:j.target)||"").trim();if(!N||!C||N===C)continue;const E=o.get(N),T=o.get(C);E&&E.add(C),T&&T.add(N)}let l=e[0],u=-1;for(const j of e){const N=((k=o.get(j))==null?void 0:k.size)??0;(N>u||N===u&&j.localeCompare(l)<0)&&(l=j,u=N)}const c=new Map,f=[];for(c.set(l,0),f.push(l);f.length;){const j=f.shift(),N=c.get(j)??0,C=Array.from(o.get(j)??[]);C.sort((E,T)=>E.localeCompare(T));for(const E of C)c.has(E)||(c.set(E,N+1),f.push(E))}let m=0;for(const j of c.values())m=Math.max(m,j);for(const j of e)c.has(j)||c.set(j,m+1);const _=new Map;for(const j of e){const N=c.get(j)??0,C=_.get(N);C?C.push(j):_.set(N,[j])}const g=Array.from(_.keys()).sort((j,N)=>j-N),w=260,x=n%360*Math.PI/180;for(const j of g){const N=_.get(j)||[];if(N.sort((I,K)=>I.localeCompare(K)),j===0){if(N.length===1)r[N[0]]={x:0,y:0};else for(let K=0;K<N.length;K++){const U=x+2*Math.PI*K/N.length;r[N[K]]={x:80*Math.cos(U),y:80*Math.sin(U)}}continue}const C=w*j,E=N.length;if(E===1){r[N[0]]={x:C,y:0};continue}const T=x+j*.35;for(let I=0;I<E;I++){const K=T+2*Math.PI*I/E;r[N[I]]={x:C*Math.cos(K),y:C*Math.sin(K)}}}return r}function uu(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 Zp(o);if(n==="circle")return F3(o,r);if(n==="radial")return cv(o,e.edges,r);if(n==="force"){const l=cv(o,e.edges,r),u=A0(r||1),c=Math.max(10,Math.min(42,Math.sqrt(o.length)*2.75)),f={};for(const m of o){const _=l[m]||{x:0,y:0};f[m]={x:_.x+(u()-.5)*c,y:_.y+(u()-.5)*c}}return f}return Zp(o)}function z3(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 B3(e,t={}){const n=!!(t.groupEdges??!0),r=Math.max(1,t.maxEdgeLabelPredicates??3),o=z3(e),l=new Set;for(const w of o){const x=String(w.subject||"").trim(),k=String(w.object||"").trim();x&&l.add(x),k&&l.add(k)}const u=Array.from(l);u.sort((w,x)=>w.localeCompare(x));const c=Zp(u),f=u.map(w=>({id:w,type:"default",data:{label:D3(w),kind:P3(w)},position:c[w]||{x:0,y:0}})),m=new Map,_=(w,x)=>{const k=String(w.subject||"").trim(),j=String(w.object||"").trim(),N=String(w.predicate||"").trim();return n?`edge:${k}:${j}`:`edge:${x}:${k}:${N}:${j}`};for(let w=0;w<o.length;w++){const x=o[w],k=_(x,w),j=m.get(k);j?j.push(x):m.set(k,[x])}const g=[];for(const[w,x]of m.entries()){const k=x[0],j=String(k.subject||"").trim(),N=String(k.object||"").trim();if(!j||!N)continue;const C=new Map;for(const J of x){const Y=String(J.predicate||"").trim();Y&&C.set(Y,(C.get(Y)||0)+1)}const E=Array.from(C.entries());E.sort((J,Y)=>Y[1]-J[1]||J[0].localeCompare(Y[0]));const I=E.slice(0,r).map(([J,Y])=>Y>1?`${km(J)}×${Y}`:km(J)).join(" | "),K=E.length>r?` +${E.length-r}`:"",U=`${I}${K}`.trim();g.push({id:w,source:j,target:N,label:U,animated:!1,data:{assertions:x,predicateSummary:U}})}return{nodes:f,edges:g}}function U3(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,N,C)=>{const E=c.get(j);E?E.push({to:N,edgeId:C}):c.set(j,[{to:N,edgeId:C}])};for(const j of e.edges)f(j.source,j.target,j.id),o||f(j.target,j.source,j.id);const m=[l],_=new Map,g=new Map;for(_.set(l,null),g.set(l,null);m.length;){const j=m.shift(),N=c.get(j)||[];for(const C of N)if(!_.has(C.to)){if(_.set(C.to,j),g.set(C.to,C.edgeId),C.to===u){m.length=0;break}m.push(C.to)}}if(!_.has(u))return null;const w=[],x=[];let k=u;for(;k;){w.push(k);const j=g.get(k);j&&x.push(j),k=_.get(k)||null}return w.reverse(),x.reverse(),{nodeIds:w,edgeIds:x}}const uv={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function Vh(e,t={}){const n={...uv,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):uv.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 m=t.positions??uu(e,{kind:"force",seed:n.seed}),_=A0(n.seed||1),g=Math.max(8,Math.min(38,Math.sqrt(o)*2.25));for(let x=0;x<o;x++){const k=r[x],j=m[k],N=typeof(j==null?void 0:j.x)=="number"&&Number.isFinite(j.x)?j.x:(_()-.5)*500,C=typeof(j==null?void 0:j.y)=="number"&&Number.isFinite(j.y)?j.y:(_()-.5)*500;l[2*x]=N+(_()-.5)*g,l[2*x+1]=C+(_()-.5)*g,u[2*x]=0,u[2*x+1]=0}const w=[];for(const x of e.edges){const k=f.get(String((x==null?void 0:x.source)||"").trim()),j=f.get(String((x==null?void 0:x.target)||"").trim());typeof k!="number"||typeof j!="number"||k===j||w.push(k,j)}return{nodeIds:r,pos:l,vel:u,acc:c,edges:new Uint32Array(w),options:n,tick:0}}function W3(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 k=0;k<n;k++){const j=e.pos[2*k],N=e.pos[2*k+1];for(let C=k+1;C<n;C++){const E=e.pos[2*C]-j,T=e.pos[2*C+1]-N,I=E*E+T*T+1e-6,K=1/Math.sqrt(I),U=x/I,J=U*E*K,Y=U*T*K;e.acc[2*k]-=J,e.acc[2*k+1]-=Y,e.acc[2*C]+=J,e.acc[2*C+1]+=Y}}}const c=r.springLength,f=r.springStrength,m=e.edges;for(let x=0;x<m.length;x+=2){const k=m[x],j=m[x+1],N=e.pos[2*k],C=e.pos[2*k+1],E=e.pos[2*j],T=e.pos[2*j+1],I=E-N,K=T-C,U=I*I+K*K+1e-6,J=Math.sqrt(U),Y=f*(J-c),re=Y*I/J,ce=Y*K/J;e.acc[2*k]+=re,e.acc[2*k+1]+=ce,e.acc[2*j]-=re,e.acc[2*j+1]-=ce}const _=r.centeringStrength;for(let x=0;x<n;x++)e.acc[2*x]+=-_*e.pos[2*x],e.acc[2*x+1]+=-_*e.pos[2*x+1];const g=r.damping,w=r.maxSpeed;for(let x=0;x<n;x++){let k=(e.vel[2*x]+e.acc[2*x]*o)*g,j=(e.vel[2*x+1]+e.acc[2*x+1]*o)*g;const N=Math.sqrt(k*k+j*j);if(N>w){const C=w/N;k*=C,j*=C}e.vel[2*x]=k,e.vel[2*x+1]=j,e.pos[2*x]+=k*o,e.pos[2*x+1]+=j*o}e.tick+=1}}function q3(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 H3(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 dv(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function V3(){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 G3(){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 $0(e,t,n,r){const o=typeof e=="number"&&Number.isFinite(e)?e:r;return Math.min(n,Math.max(t,o))}function Qd(e){const t=$0(e,.6,2.4,1),n=240*t,r=9e3*t*t;return{springLength:n,repulsionStrength:r}}const Nf="abstractuic_amx_saved_layouts_v1",eg=.025,tg=6,T0=1e6;function Ug(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function ng(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function K3(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 fv(e){const t=Ug();if(!t)return null;const n=String(e??"").trim();if(!n)return null;try{const r=t.getItem(Nf);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 m=ng(c.kind,"grid"),_=typeof c.seed=="number"&&Number.isFinite(c.seed)?Math.trunc(c.seed):Qp(n),g=c.positions&&typeof c.positions=="object"&&!Array.isArray(c.positions)?c.positions:null,w={};if(g)for(const[j,N]of Object.entries(g)){const C=K3(N);C&&(w[String(j)]=C)}const x=E0(c.viewport,{minZoom:eg,maxZoom:tg,maxAbsTranslate:T0})??void 0,k=typeof c.saved_at=="string"&&c.saved_at.trim()?c.saved_at.trim():"";return{version:f,kind:m,seed:_,positions:w,viewport:x,saved_at:k}}catch{return null}}function Y3(e,t){const n=Ug();if(!n)return;const r=String(e??"").trim();if(r)try{const o=n.getItem(Nf),l=o?JSON.parse(o):null,u=l&&typeof l=="object"&&!Array.isArray(l)?{...l}:{};u[r]=t,n.setItem(Nf,JSON.stringify(u))}catch{}}function J3(e){const t=Ug();if(!t)return;const n=String(e??"").trim();if(n)try{const r=t.getItem(Nf);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(Nf,JSON.stringify(l))}catch{}}function X3(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function tp(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 Z3(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 Q3(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 m=typeof l.writer_run_id=="string"?l.writer_run_id.trim():"",_=typeof l.writer_workflow_id=="string"?l.writer_workflow_id.trim():"";m&&t.push(`writer_run_id=${m}`),_&&t.push(`writer_workflow_id=${_}`)}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 eL(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 ef(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 tf(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 M0(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 np(e,t){const n=String(e??"").trim().toLowerCase();return!!(n&&t.has(n))}function nL(e,t={}){const n=Math.max(1,t.maxPredicates??3),r=new Map;for(const f of e){const m=String((f==null?void 0:f.predicate)||"").trim();m&&r.set(m,(r.get(m)||0)+1)}const o=Array.from(r.entries());o.sort((f,m)=>m[1]-f[1]||f[0].localeCompare(m[0]));const u=o.slice(0,n).map(([f,m])=>{const _=M0(f);return m>1?`${_}×${m}`:_}).join(" | "),c=o.length>n?` +${o.length-n}`:"";return`${u}${c}`.trim()}function sL({resetKey:e,queryMode:t,items:n,activeMemoryText:r,packets:o,packetsVersion:l,packedCount:u,dropped:c,estimatedTokens:f,effort:m,warnings:_,onQuery:g,onItemsReplace:w,onOpenSpan:x,onOpenTranscript:k}){var ci;const j=p.useRef(null),N=p.useMemo(()=>{const B=n==null?void 0:n[0],ie=n==null?void 0:n[n.length-1],be=B?`${B.subject}|${B.predicate}|${B.object}`:"",Se=ie?`${ie.subject}|${ie.predicate}|${ie.object}`:"";return`${(n==null?void 0:n.length)||0}:${be}:${Se}`},[n]),C=String(e??N),E=t==="replace"?"replace":"override",[T,I]=p.useState(null),[K,U]=p.useState(null),[J,Y]=p.useState(!1),[re,ce]=p.useState(""),[fe,W]=p.useState(!1),[O,$]=p.useState("");p.useEffect(()=>{I(null),U(null),ce(""),Y(!1),$(""),W(!1)},[C]);const[z,A]=p.useState(""),[te,P]=p.useState(!0),[F,G]=p.useState(!1),[R,Z]=p.useState(!0),[X]=p.useState(()=>({compact:V3(),show:!1})),Q=X.compact,[le,ge]=p.useState(X.show),[pe,ye]=p.useState(!1),Ne=C,Ue=p.useMemo(()=>Qp(Ne),[Ne]),[We,pt]=p.useState("grid"),[Fe,tt]=p.useState(Ue),[lt,Ke]=p.useState(!1),[ke,Re]=p.useState(1),ht=p.useRef(null),xe=p.useRef(null),Ie=p.useRef(!1),[qe,zt]=p.useState(0),en=p.useRef(null),bn=p.useRef(0),Wt=p.useRef(0),It=p.useRef(0),Sn=p.useRef(0),[ns,Ot]=p.useState(!1),[pn,Bn]=p.useState(""),[An,gn]=p.useState({}),In=p.useRef({});p.useEffect(()=>{In.current=An},[An]);const[wn,js]=p.useState(""),[Kn,ks]=p.useState(""),Nr=p.useMemo(()=>{var ie;const B=(ie=n==null?void 0:n[0])==null?void 0:ie.scope;return dv(B,"session")},[n]),[On,ae]=p.useState(Nr),[je,Ye]=p.useState("standard"),[Ge,rt]=p.useState(""),[ct,Et]=p.useState(""),[jt,Kt]=p.useState(""),[xt,Yt]=p.useState(""),[qt,Pt]=p.useState(""),[At,$t]=p.useState(""),[De,on]=p.useState(""),[dt,tn]=p.useState("qwen/qwen3-next-80b");p.useEffect(()=>{ae(Nr)},[C]);const ft=Array.isArray(n)?n:[],Un=typeof r=="string"?r:"",an=Array.isArray(o)?o:[],Ys=typeof l=="number"?l:void 0,ss=typeof u=="number"?u:void 0,Wr=typeof c=="number"?c:void 0,dr=typeof f=="number"?f:void 0,ii=m,oi=_,Ps=E==="override"&&(T!=null&&T.items)&&Array.isArray(T.items)?T.items:ft,ue=typeof(T==null?void 0:T.active_memory_text)=="string"&&T.active_memory_text.trim()?T.active_memory_text:Un,fr=(T==null?void 0:T.effort)??ii,Vi=(T==null?void 0:T.warnings)??oi,hr=p.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),Cr=p.useMemo(()=>R?Ps:(Ps||[]).filter(B=>!np(B==null?void 0:B.predicate,hr)),[Ps,R,hr]),qr=p.useMemo(()=>B3(Ps,{groupEdges:te}),[Ps,te]),it=p.useMemo(()=>{if(R)return qr;const B=[];for(const ie of qr.edges){const Se=(ie&&ie.data&&Array.isArray(ie.data.assertions)?ie.data.assertions:[]).filter(He=>!np(He==null?void 0:He.predicate,hr));if(!Se.length)continue;const Ee=nL(Se);B.push({...ie,label:Ee,data:{...ie.data,assertions:Se,predicateSummary:Ee}})}return{nodes:qr.nodes,edges:B}},[qr,R,hr]),cn=p.useMemo(()=>it.nodes.map(B=>B.id),[it.nodes]),Ds=p.useMemo(()=>{const B=cn[0]||"",ie=cn[cn.length-1]||"";return`${cn.length}:${B}:${ie}`},[cn]),Hr=p.useMemo(()=>{var ie;const B=new Map;for(const be of it.nodes)B.set(be.id,String(((ie=be.data)==null?void 0:ie.label)||be.id));return B},[it.nodes]),rs=p.useMemo(()=>{var ie;const B=new Map;for(const be of it.nodes)B.set(be.id,String(((ie=be.data)==null?void 0:ie.kind)||""));return B},[it.nodes]),Eo=z.trim().toLowerCase(),Ao=p.useMemo(()=>{var ie;if(!Eo)return new Set;const B=new Set;for(const be of it.nodes){const Se=String(be.id||"").toLowerCase(),Ee=String(((ie=be.data)==null?void 0:ie.label)||"").toLowerCase();(Se.includes(Eo)||Ee.includes(Eo))&&B.add(be.id)}return B},[it.nodes,Eo]),$o=p.useCallback((B,ie)=>{const be={};for(const Se of cn){const Ee=B[Se]||ie[Se];be[Se]=Ee?{x:Ee.x,y:Ee.y}:{x:0,y:0}}return be},[cn]);p.useEffect(()=>{gn(B=>{const ie=uu(it,{kind:We,seed:Fe}),be={};for(const Se of cn){const Ee=B[Se]||ie[Se];be[Se]=Ee?{x:Ee.x,y:Ee.y}:{x:0,y:0}}return be})},[it,We,Fe,cn,Ds]),p.useEffect(()=>{if(!Ie.current)return;const B=j.current;if(!(!B||typeof B.fitView!="function")&&cn.length){Ie.current=!1;try{B.fitView({padding:.2,duration:0})}catch{try{B.fitView({padding:.2})}catch{}}}},[cn.length,Ds,An]),p.useEffect(()=>{Ke(!1),ht.current=null,xe.current=null,Ie.current=!1,bn.current=0,Wt.current=0,It.current=0;const B=fv(Ne);if(B&&Object.keys(B.positions||{}).length){if(pt(B.kind),tt(B.seed),Ot(!0),Bn(B.saved_at||""),B.viewport){xe.current=B.viewport;const Ee=j.current;if(Ee&&typeof Ee.setViewport=="function"){try{Ee.setViewport(B.viewport,{duration:0})}catch{try{Ee.setViewport(B.viewport)}catch{}}xe.current=null}}else Ie.current=!0;const Se=uu(it,{kind:B.kind,seed:B.seed});gn($o(B.positions,Se));return}Ot(!1),Bn("");const ie=Qp(Ne);tt(ie);const be=uu(it,{kind:We,seed:ie});gn(be),We==="force"&&it.nodes.length>0&&it.nodes.length<=320&&(ht.current=Vh(it,{seed:ie,positions:be,...Qd(ke)}),Ke(!0))},[Ne]);const Pn=p.useMemo(()=>{const B=String(wn||"").trim(),ie=String(Kn||"").trim();return!B||!ie?null:U3(it,B,ie,{directed:F})},[it,wn,Kn,F]),mr=!!(Pn&&String(wn||"").trim()&&String(Kn||"").trim()),Hn=p.useMemo(()=>{const B=String(wn||"").trim(),ie=String(Kn||"").trim();if(!B||!ie)return null;const be=F,Se=new Map,Ee=(ot,mt)=>{const Dt=Se.get(ot);Dt?Dt.push(mt):Se.set(ot,[mt])};for(const ot of it.edges)Ee(ot.source,ot.target),be||Ee(ot.target,ot.source);const He=new Set,Qe=[];for(He.add(B),Qe.push(B);Qe.length;){const ot=Qe.shift(),mt=Se.get(ot)||[];for(const Dt of mt)He.has(Dt)||(He.add(Dt),Qe.push(Dt))}return{reachableFromStart:He.size,endReachable:He.has(ie),nodes:it.nodes.length,edges:it.edges.length,assertions:Cr.length}},[F,it.edges,it.nodes.length,Kn,wn,Cr.length]),Gi=p.useMemo(()=>new Set((Pn==null?void 0:Pn.nodeIds)||[]),[Pn]),ai=p.useMemo(()=>new Set((Pn==null?void 0:Pn.edgeIds)||[]),[Pn]),[$n,Fs]=p.useState(""),[hs,Js]=p.useState(""),ms=!!(String($n||"").trim()||String(hs||"").trim()),da=p.useMemo(()=>{const B=new Set,ie=new Set,be=String($n||"").trim(),Se=String(hs||"").trim();if(be){B.add(be);for(const Ee of it.edges)(Ee.source===be||Ee.target===be)&&(ie.add(Ee.id),B.add(Ee.source),B.add(Ee.target));return{nodes:B,edges:ie}}if(Se){const Ee=it.edges.find(He=>He.id===Se);Ee&&(ie.add(Ee.id),B.add(Ee.source),B.add(Ee.target))}return{nodes:B,edges:ie}},[it.edges,hs,$n]);p.useEffect(()=>{Fs(""),Js(""),js(""),ks("")},[C]);const[Ki,ln]=p.useState(!1);p.useEffect(()=>{ln(!1)},[C]),p.useEffect(()=>{lt||(ht.current=null)},[lt]),p.useEffect(()=>{if(We!=="force")return;const B=ht.current;if(!B)return;const ie=Qd(ke);B.options.springLength=ie.springLength,B.options.repulsionStrength=ie.repulsionStrength},[We,ke]),p.useEffect(()=>{We!=="force"&<&&Ke(!1)},[We,lt]),p.useEffect(()=>{if(!lt||We!=="force"||it.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;ht.current||(ht.current=Vh(it,{seed:Fe,positions:In.current,...Qd(ke)}));let B=0,ie=0,be=0;const Se=it.nodes.length<=140?2:1,Ee=1600,He=.08,Qe=ot=>{if(B=window.requestAnimationFrame(Qe),ot-ie<33)return;ie=ot;const mt=ht.current;if(!mt){Ke(!1);return}W3(mt,Se),be+=Se,gn(H3(mt)),(q3(mt)<=He||be>=Ee)&&Ke(!1)};return B=window.requestAnimationFrame(Qe),()=>{window.cancelAnimationFrame(B)}},[it,We,lt,Fe]);const fa=p.useMemo(()=>it.nodes.map(B=>{var un;const ie=Gi.has(B.id),be=Ao.has(B.id),Se=$n===B.id,Ee=ms&&da.nodes.has(B.id),He=ef((un=B.data)==null?void 0:un.kind),Qe="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?Qe:He.stroke,Dt=Se?"0 0 0 2px rgba(255,255,255,0.20), 0 18px 46px rgba(0,0,0,0.55)":Ee?"0 0 0 1px rgba(96, 165, 250, 0.28), 0 12px 34px rgba(0,0,0,0.45)":void 0,Xt=ot&&Dt?`${ot}, ${Dt}`:Dt||ot||void 0,Xn=ie?"rgba(168, 85, 247, 0.10)":be?"rgba(34, 211, 238, 0.08)":He.bg,Bt=mr?ie||Se?1:.16:ms?Ee||Se?1:.1:1;return{...B,position:An[B.id]?{x:An[B.id].x,y:An[B.id].y}:B.position,style:{...B.style||{},border:`1px solid ${mt}`,borderRadius:10,background:Xn,color:"rgba(255,255,255,0.92)",opacity:Bt,padding:8,fontSize:12,boxShadow:Xt,width:180,cursor:"pointer"}}}),[it.nodes,mr,Ao,An,$n,Gi,ms,da.nodes]),uc=p.useMemo(()=>it.edges.map(B=>{const ie=ai.has(B.id),be=hs===B.id,Se=ms&&da.edges.has(B.id),Ee=ie?"rgba(168, 85, 247, 0.9)":ms?Se||be?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",He=ie?2.75:ms?Se||be?2.25:1.25:1.5,Qe=be?"drop-shadow(0 0 10px rgba(168, 85, 247, 0.25))":void 0,ot=ie?"rgba(168, 85, 247, 0.9)":mr?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",mt=mr?ie||be?1:.1:ms?Se||be?1:.08:1,Dt=mr?ie||be?1:0:ms?Se||be?1:0:1,Xt=mr?ie||be?String(B.label||""):"":String(B.label||"");return{...B,label:Xt,style:{...B.style||{},stroke:Ee,strokeWidth:He,filter:Qe,opacity:mt},animated:!1,markerEnd:{type:kf.ArrowClosed,color:ot,width:20,height:20},labelShowBg:!0,labelBgPadding:[6,3],labelBgBorderRadius:10,labelBgStyle:{fill:`rgba(0, 0, 0, ${.38*Dt})`,stroke:`rgba(255, 255, 255, ${.14*Dt})`,strokeWidth:1},labelStyle:{fill:`rgba(255, 255, 255, ${.92*Dt})`,fontSize:10,fontWeight:600,letterSpacing:.2,textTransform:"lowercase"}}}),[it.edges,mr,hs,ai,ms,da.edges]),To=p.useMemo(()=>{if(!hs)return[];const B=it.edges.find(be=>be.id===hs),ie=B&&B.data&&Array.isArray(B.data.assertions)?B.data.assertions:[];return Array.isArray(ie)?ie:[]},[it.edges,hs]),_s=p.useMemo(()=>hs&&it.edges.find(B=>B.id===hs)||null,[it.edges,hs]),Er=p.useMemo(()=>{const B=String($n||"").trim();return B?Ps.filter(ie=>!ie||typeof ie!="object"||!(ie.subject===B||ie.object===B)?!1:R?!0:!np(ie.predicate,hr)):[]},[Ps,$n,R,hr]),Ar=p.useMemo(()=>hs?To:Er,[To,hs,Er]),Yi=p.useMemo(()=>{const B=new Map;for(const ie of Ar){if(!ie||typeof ie!="object")continue;const be=ie.provenance&&typeof ie.provenance=="object"&&!Array.isArray(ie.provenance)?ie.provenance:null,Se=be&&typeof be.span_id=="string"?be.span_id.trim():"",Ee=be&&typeof be.writer_run_id=="string"?be.writer_run_id.trim():"",He=typeof ie.owner_id=="string"?ie.owner_id.trim():"",Qe=Ee||He;if(!Qe||!Se)continue;const ot=`${Qe}|${Se}`,mt=B.get(ot),Dt=typeof ie.observed_at=="string"?ie.observed_at.trim():"";mt?(mt.count+=1,Dt&&(!mt.last_observed_at||Dt>mt.last_observed_at)&&(mt.last_observed_at=Dt,mt.last_observed_at_fmt=tf(Dt),mt.assertion=ie)):B.set(ot,{span_run_id:Qe,span_id:Se,writer_run_id:Ee,count:1,last_observed_at:Dt,last_observed_at_fmt:tf(Dt),assertion:ie})}return Array.from(B.values()).sort((ie,be)=>String(be.last_observed_at||"").localeCompare(String(ie.last_observed_at||"")))},[Ar]),_r=p.useMemo(()=>{const B=new Map;for(const ie of Ar){if(!ie||typeof ie!="object")continue;const be=ie.provenance&&typeof ie.provenance=="object"&&!Array.isArray(ie.provenance)?ie.provenance:null,Se=be&&typeof be.span_id=="string"?be.span_id.trim():"",Ee=be&&typeof be.writer_run_id=="string"?be.writer_run_id.trim():"";if(!Ee||Se)continue;const He=B.get(Ee),Qe=typeof ie.observed_at=="string"?ie.observed_at.trim():"";He?(He.count+=1,Qe&&(!He.last_observed_at||Qe>He.last_observed_at)&&(He.last_observed_at=Qe,He.last_observed_at_fmt=tf(Qe),He.assertion=ie)):B.set(Ee,{run_id:Ee,count:1,last_observed_at:Qe,last_observed_at_fmt:tf(Qe),assertion:ie})}return Array.from(B.values()).sort((ie,be)=>String(be.last_observed_at||"").localeCompare(String(ie.last_observed_at||"")))},[Ar]),Ss=p.useCallback(B=>{const ie=String(B.run_id||"").trim(),be=typeof B.span_id=="string"?String(B.span_id).trim():"";if(ie){if(k){try{k({run_id:ie,span_id:be||void 0,assertion:B.assertion})}catch{}return}if(x&&be)try{x({run_id:ie,span_id:be,assertion:B.assertion})}catch{}}},[x,k]),pr=p.useCallback(async B=>{var be;const ie=String(B??"");if(ie){try{if(typeof((be=navigator.clipboard)==null?void 0:be.writeText)=="function"){await navigator.clipboard.writeText(ie);return}}catch{}try{const Se=document.createElement("textarea");Se.value=ie,Se.style.position="fixed",Se.style.left="-9999px",document.body.appendChild(Se),Se.select(),document.execCommand("copy"),document.body.removeChild(Se)}catch{}}},[]),$r=p.useCallback(()=>{const B=j.current;if(!(!B||typeof B.fitView!="function")){if($n&&typeof B.getNode=="function"){const ie=B.getNode($n);if(ie){B.fitView({nodes:[ie],padding:.55,duration:350});return}}B.fitView({padding:.2,duration:350})}},[$n]),Xs=p.useCallback(B=>{const ie=B.kind,be=Math.trunc(B.seed);Ke(!1),ht.current=null,xe.current=null,pt(ie),tt(be);const Se=uu(it,{kind:ie,seed:be});gn(Se),ie==="force"&&(B.autoPlay??!0)&&it.nodes.length>0&&it.nodes.length<=320&&(ht.current=Vh(it,{seed:be,positions:Se,...Qd(ke)}),Ke(!0))},[it,ke]),Si=p.useCallback(()=>{if(We==="force"){if(lt){Ke(!1);return}ht.current=Vh(it,{seed:Fe,positions:In.current,...Qd(ke)}),Ke(!0)}},[it,We,lt,Fe,ke]);p.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&Sn.current&&window.cancelAnimationFrame(Sn.current)},[]);const is=p.useCallback(()=>{const B=j.current;if(!B||typeof B.getViewport!="function"||!cn.length)return null;const ie=en.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 Se=B.getViewport(),Ee=typeof(Se==null?void 0:Se.zoom)=="number"&&Number.isFinite(Se.zoom)?Se.zoom:null,He=typeof(Se==null?void 0:Se.x)=="number"&&Number.isFinite(Se.x)?Se.x:null,Qe=typeof(Se==null?void 0:Se.y)=="number"&&Number.isFinite(Se.y)?Se.y:null;if(Ee===null||He===null||Qe===null||Ee<=0)return null;const ot=140,mt=Math.min(cn.length,180),Dt=In.current;let Xt=0,Xn=0;for(const Bt of cn){const un=Dt[Bt];if(!un||!Number.isFinite(un.x)||!Number.isFinite(un.y))continue;Xn+=1;const vn=[{x:un.x,y:un.y},{x:un.x+90,y:un.y+24}];for(const jn of vn){const ps=jn.x*Ee+He,Ns=jn.y*Ee+Qe;if(ps>-ot&&ps<be.width+ot&&Ns>-ot&&Ns<be.height+ot)return!1}if(Xt++,Xt>=mt)break}return Xn?!0:null},[cn]),Tr=p.useCallback(B=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||Sn.current||(Sn.current=window.requestAnimationFrame(()=>{Sn.current=0;const ie=is();if(ie===null){if(It.current>=12)return;It.current+=1,window.setTimeout(()=>Tr(`${B}:probe`),120);return}if(ie!==!0){It.current=0,Wt.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(Wt.current+=1,Wt.current>=4&&bn.current<1){Wt.current=0,bn.current+=1,zt(Se=>Se+1);return}Wt.current<8&&window.setTimeout(()=>Tr(`${B}:retry`),220)}))},[is]);p.useEffect(()=>{Wt.current=0,bn.current=0,It.current=0,Tr("mount")},[C,Tr]),p.useEffect(()=>{Tr("graph change")},[Ds,Tr]),p.useEffect(()=>{const B=en.current;if(!B||typeof window>"u"||typeof ResizeObserver!="function")return;const ie=new ResizeObserver(()=>Tr("resize"));return ie.observe(B),()=>ie.disconnect()},[Tr]);const ha=p.useCallback(()=>{const B=new Date().toISOString(),ie={};for(const Qe of cn){const ot=In.current[Qe];ot&&typeof ot.x=="number"&&typeof ot.y=="number"&&(ie[Qe]={x:ot.x,y:ot.y})}const be=j.current,Se=be&&typeof be.toObject=="function"?be.toObject():null,Ee=Se&&Se.viewport?Se.viewport:be&&typeof be.getViewport=="function"?be.getViewport():null,He=E0(Ee,{minZoom:eg,maxZoom:tg,maxAbsTranslate:T0})??void 0;Y3(Ne,{version:1,kind:We,seed:Fe,positions:ie,viewport:He,saved_at:B}),Ot(!0),Bn(B),Ke(!1)},[Ne,We,Fe,cn]),gr=p.useCallback(()=>{const B=fv(Ne);if(!B)return;Ke(!1),ht.current=null,pt(B.kind),tt(B.seed),Ot(!0),Bn(B.saved_at||""),xe.current=B.viewport||null,Ie.current=!B.viewport;const ie=uu(it,{kind:B.kind,seed:B.seed});if(gn($o(B.positions,ie)),B.viewport){const be=j.current;if(be&&typeof be.setViewport=="function"){try{be.setViewport(B.viewport,{duration:0})}catch{try{be.setViewport(B.viewport)}catch{}}xe.current=null}}},[$o,it,Ne]),Ji=p.useCallback(()=>{J3(Ne),Ot(!1),Bn("")},[Ne]),dc=p.useCallback(B=>{if(!Array.isArray(B)||B.length===0)return;let ie=!1;gn(be=>{let Se=be,Ee=!1;for(const He of B){const Qe=He&&typeof He=="object"&&"id"in He&&typeof He.id=="string"?String(He.id):"",ot=(He==null?void 0:He.type)==="position"?He==null?void 0:He.position:null;Qe&&ot&&typeof ot.x=="number"&&typeof ot.y=="number"&&(Ee||(Se={...be},Ee=!0),Se[Qe]={x:ot.x,y:ot.y},He!=null&&He.dragging&&(ie=!0))}return Ee?Se:be}),ie&<&&Ke(!1)},[lt]),Ni=p.useMemo(()=>{const B=new Map;for(const ie of it.edges)B.set(ie.id,ie);return B},[it.edges]),Zs=p.useMemo(()=>{var Se;if(!Pn)return[];const B=Pn.nodeIds||[],ie=Pn.edgeIds||[],be=[];for(let Ee=0;Ee<Math.min(B.length-1,ie.length);Ee++){const He=B[Ee],Qe=B[Ee+1],ot=ie[Ee],mt=Ni.get(ot),Dt=String(((Se=mt==null?void 0:mt.data)==null?void 0:Se.predicateSummary)||(mt==null?void 0:mt.label)||"").trim(),Xt=mt&&mt.source===He&&mt.target===Qe?"forward":mt&&mt.source===Qe&&mt.target===He?"reverse":"unknown";be.push({from:He,to:Qe,edgeId:ot,predicate:Dt,dir:Xt})}return be},[Ni,Pn]),$u=p.useCallback(async()=>{if(g){ce(""),$(""),Y(!0);try{const B=X3(qt),ie=tp(At,{allowZero:!0,allowNegativeOne:!0}),be=tp(De,{allowZero:!0}),Se=await g({scope:On,owner_id:void 0,recall_level:je,query_text:Ge||void 0,subject:ct||void 0,predicate:jt||void 0,object:xt||void 0,min_score:B,limit:ie,max_input_tokens:be,model:dt||void 0});I(Se),U("live query"),E==="replace"&&w&&Se&&Array.isArray(Se.items)&&w(Se.items,{kind:"live query",result:Se})}catch(B){const ie=B instanceof Error?B.message:String(B);ce(ie||"Query failed")}finally{Y(!1)}}},[At,De,qt,dt,xt,w,g,jt,E,Ge,je,On,ct]),Qs=p.useCallback(async()=>{if(!g)return;const B=String(wn||"").trim(),ie=String(Kn||"").trim();if(!B||!ie)return;const be=Math.max(200,tp(At)??80),Se=60;$(""),ce(""),W(!0);try{const Ee=[],He=new Set,Qe=Bt=>{if(!Bt||typeof Bt!="object"||typeof Bt.subject!="string"||typeof Bt.predicate!="string"||typeof Bt.object!="string")return;const un=`${Bt.subject}|${Bt.predicate}|${Bt.object}|${String(Bt.observed_at||"")}|${String(Bt.scope||"")}|${String(Bt.owner_id||"")}`;He.has(un)||(He.add(un),Ee.push(Bt))};for(const Bt of Ps)Qe(Bt);const ot=F,mt=new Set,Dt=[B],Xt=new Set([B]),Xn=async Bt=>{const un=await g({scope:On,recall_level:je,min_score:0,limit:be,subject:Bt,query_text:void 0,max_input_tokens:0,model:void 0});if(un&&Array.isArray(un.items)){for(const vn of un.items)if(Qe(vn),typeof vn.subject=="string"&&vn.subject.trim()===Bt&&typeof vn.object=="string"){const jn=vn.object.trim();jn&&!Xt.has(jn)&&(Xt.add(jn),Dt.push(jn))}}if(!ot){const vn=await g({scope:On,recall_level:je,min_score:0,limit:be,object:Bt,query_text:void 0,max_input_tokens:0,model:void 0});if(vn&&Array.isArray(vn.items)){for(const jn of vn.items)if(Qe(jn),typeof jn.object=="string"&&jn.object.trim()===Bt&&typeof jn.subject=="string"){const ps=jn.subject.trim();ps&&!Xt.has(ps)&&(Xt.add(ps),Dt.push(ps))}}}};for(;Dt.length&&mt.size<Se&&!Xt.has(ie);){const Bt=Dt.shift();!Bt||mt.has(Bt)||(mt.add(Bt),await Xn(Bt))}I({ok:!0,count:Ee.length,items:Ee,active_memory_text:ue,raw:{expanded_for_path:!0,expanded_nodes:mt.size,discovered_nodes:Xt.size,merged:Ee.length,directed:ot}}),U("expanded neighborhood"),E==="replace"&&w&&w(Ee,{kind:"expanded neighborhood",result:{ok:!0,count:Ee.length,items:Ee,active_memory_text:ue,raw:{expanded_for_path:!0,expanded_nodes:mt.size,discovered_nodes:Xt.size,merged:Ee.length,directed:ot}}})}catch(Ee){const He=Ee instanceof Error?Ee.message:String(Ee);$(He||"Expand neighborhood failed")}finally{W(!1)}},[F,ue,Ps,At,w,g,Kn,wn,E,je,On]),Xi=p.useCallback(()=>{I(null),U(null),ce(""),Y(!1),$(""),W(!1),js(""),ks(""),Fs(""),Js("")},[]),er="Search KG",Mo=it.nodes.length,li=it.edges.length,al=Cr.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:We,onChange:B=>pt(ng(B.target.value,We)),disabled:!cn.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)"})]}),We==="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:ke,onChange:B=>Re($0(Number(B.target.value),.7,2.2,1))}),s.jsxs("span",{className:"amx-small",children:[ke.toFixed(1),"×"]})]}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Xs({kind:We,seed:Fe}),disabled:!cn.length,children:"Apply"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Si,disabled:!cn.length||We!=="force",children:lt?"Pause simulation":"Play simulation"})]})}),s.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:en,children:[s.jsx(Bg,{children:s.jsxs(j0,{nodes:fa,edges:uc,defaultViewport:{x:0,y:0,zoom:1},minZoom:eg,maxZoom:tg,onInit:B=>{j.current=B;const ie=xe.current;if(ie&&typeof B.setViewport=="function")try{B.setViewport(ie,{duration:0})}catch{try{B.setViewport(ie)}catch{}}if(Ie.current&&typeof B.fitView=="function")try{B.fitView({padding:.2,duration:0})}catch{try{B.fitView({padding:.2})}catch{}}xe.current=null,Ie.current=!1,Tr("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:dc,onNodeClick:(B,ie)=>{Js(""),Fs(ie.id)},onEdgeClick:(B,ie)=>{Fs(""),Js(ie.id)},onPaneClick:()=>{Fs(""),Js("")},children:[s.jsx($3,{className:"amx-flow-controls",children:s.jsx(mu,{type:"button",className:`amx-control-legend ${pe?"amx-control-legend-active":""}`,onClick:()=>ye(B=>!B),title:pe?"Hide node color legend":"Show node color legend","aria-label":pe?"Hide node color legend":"Show node color legend",children:s.jsx(G3,{})})}),s.jsx(xf,{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:()=>ge(B=>!B),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(j3,{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:Q?120:160,height:Q?80:110,marginBottom:56},nodeColor:B=>{var ie;return ef((ie=B.data)==null?void 0:ie.kind).minimap}}):null,pe?s.jsxs(xf,{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:B,label:ie})=>s.jsx("span",{className:"amx-legend-item",style:{borderColor:ef(B).stroke},children:ie},B))})]}):null,s.jsx(O3,{gap:20,size:1,color:"rgba(255,255,255,0.06)"})]})},qe),s.jsxs("details",{className:"amx-panel amx-controls",children:[s.jsxs("summary",{children:[s.jsx("span",{className:"amx-controls-title",children:er}),s.jsxs("span",{className:"amx-small",children:[al," assertions · ",Mo," nodes · ",li," 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:B=>A(B.target.value),placeholder:"filter nodes by id/label"})]}),s.jsxs("label",{children:["group edges",s.jsxs("select",{value:String(te),onChange:B=>P(B.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:B=>Z(B.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:B=>G(B.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:We,onChange:B=>pt(ng(B.target.value,We)),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:B=>tt(Math.trunc(Number(B.target.value||0)||0))})]})]}),s.jsxs("div",{className:"amx-actions",style:{marginTop:10},children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Xs({kind:We,seed:Fe}),disabled:!cn.length,children:"Apply layout"}),We==="force"?s.jsx("button",{type:"button",className:"amx-btn",onClick:Si,disabled:!cn.length,children:lt?"Pause simulation":"Play simulation"}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:ha,disabled:!cn.length,children:"Save layout"}),ns?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:gr,children:"Load saved"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Ji,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",pn?`: ${pn}`:"",")"]}):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:wn,onChange:B=>js(B.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),cn.map(B=>s.jsx("option",{value:B,children:(()=>{const ie=Hr.get(B)||B;return ie===B?ie:`${ie} (${B})`})()},B))]})]}),s.jsxs("label",{children:["path end",s.jsxs("select",{value:Kn,onChange:B=>ks(B.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),cn.map(B=>s.jsx("option",{value:B,children:(()=>{const ie=Hr.get(B)||B;return ie===B?ie:`${ie} (${B})`})()},B))]})]})]}),Pn?s.jsx("div",{className:"amx-small",style:{marginTop:10},children:Zs.map((B,ie)=>{const be=Hr.get(B.from)||B.from,Se=Hr.get(B.to)||B.to,Ee=B.dir==="reverse"?" ← ":" → ",He=B.predicate?` (${B.predicate})`:"";return s.jsxs("div",{children:[ie===0?s.jsx("span",{children:be}):null,Ee,s.jsxs("span",{children:[Se,He]})]},`${B.edgeId}:${ie}`)})}):wn&&Kn?s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["No path found in the current subgraph (",(Hn==null?void 0:Hn.assertions)??al," assertions · ",(Hn==null?void 0:Hn.nodes)??it.nodes.length," nodes ·"," ",(Hn==null?void 0:Hn.edges)??it.edges.length," edges). Start reaches ",(Hn==null?void 0:Hn.reachableFromStart)??0," nodes.",g?s.jsx("div",{style:{marginTop:10},children:s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Qs(),disabled:fe,children:fe?"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:Ge,onChange:B=>rt(B.target.value),placeholder:"e.g. emotion chip"})]}),s.jsxs("label",{children:["subject (exact)",s.jsx("input",{value:ct,onChange:B=>Et(B.target.value),placeholder:"e.g. ex:person-data"})]}),s.jsxs("label",{children:["predicate (exact)",s.jsx("input",{value:jt,onChange:B=>Kt(B.target.value),placeholder:"e.g. schema:about"})]}),s.jsxs("label",{children:["object (exact)",s.jsx("input",{value:xt,onChange:B=>Yt(B.target.value),placeholder:"e.g. ex:concept-emotion-chip"})]}),s.jsxs("label",{children:["min_score",s.jsx("input",{type:"number",step:"any",value:qt,onChange:B=>Pt(B.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["limit",s.jsx("input",{type:"number",min:"-1",step:"1",value:At,onChange:B=>$t(B.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:On,onChange:B=>ae(dv(B.target.value,On)),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:B=>Ye(B.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:B=>on(B.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["model (budgeting)",s.jsx("input",{value:dt,onChange:B=>tn(B.target.value),placeholder:"qwen/qwen3-next-80b"})]})]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void $u(),disabled:!g||J,children:J?"Querying…":"Query store"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Xi,disabled:!T&&!re&&!J,children:"Reset to step output"}),T?s.jsxs("span",{className:"amx-small",children:["showing: ",K||"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,O?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:O}):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 B=Z3(fr);return B?s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:B}):null})(),(()=>{const B=Vi;if(!B)return null;const ie=typeof B=="string"?B:Array.isArray(B)?B.map(be=>String(be)).join(" · "):JSON.stringify(B);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 B=(T==null?void 0:T.packets_version)??Ys,ie=(T==null?void 0:T.packed_count)??ss,be=(T==null?void 0:T.dropped)??Wr,Se=(T==null?void 0:T.estimated_tokens)??dr,Ee=[];return typeof B=="number"&&Ee.push(`packets_v${B}`),typeof ie=="number"&&Ee.push(`packed=${ie}`),typeof be=="number"&&Ee.push(`dropped=${be}`),typeof Se=="number"&&Ee.push(`est_tokens=${Se}`),Ee.length?Ee.join(" · "):"No packetization stats (set max_input_tokens > 0)."})()}),s.jsx("div",{className:"amx-active-memory",children:eL(ue||"(empty)",z)}),(()=>{const B=T!=null&&T.packets&&Array.isArray(T.packets)?T.packets:an;return!Array.isArray(B)||B.length===0?null:s.jsxs("div",{style:{marginTop:10},children:[s.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>ln(ie=>!ie),children:[Ki?"Hide":"Show"," packets (",B.length,")"]}),Ki?s.jsx("div",{className:"amx-list",style:{marginTop:10},children:B.slice(0,120).map((ie,be)=>{const Se=ie&&typeof ie=="object"&&!Array.isArray(ie)?ie:null,Ee=Se&&typeof Se.statement=="string"?Se.statement:typeof ie=="string"?ie:"",He=Se&&(typeof Se.retrieval_score=="number"||typeof Se.retrieval_score=="string")?Se.retrieval_score:null,Qe=Se&&typeof Se.observed_at=="string"?Se.observed_at:null;return s.jsxs("div",{className:"amx-item",children:[s.jsx("div",{className:"amx-mono",children:Ee||"(packet)"}),Qe||He!==null?s.jsxs("div",{className:"amx-small",children:[Qe?`[${Qe}]`:null,Qe&&He!==null?" ":null,He!==null?`score:${He}`: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:Hr.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 pr($n),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:$r,children:"Focus"})]})]}):_s&&_s.source&&_s.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:[_s.source," —",String(_s.label||((ci=_s.data)==null?void 0:ci.predicateSummary)||"").trim()||"?","→ ",_s.target]}),s.jsxs("div",{className:"amx-small",children:["edge_id=",_s.id]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void pr(_s.id),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:$r,children:"Fit"})]})]}):s.jsx("div",{className:"amx-small",style:{marginBottom:10,opacity:.9},children:"(no selection)"}),s.jsx("div",{className:"amx-list",children:Ar.slice(0,80).map((B,ie)=>{const be=String(B.subject||"").trim(),Se=String(B.predicate||"").trim(),Ee=String(B.object||"").trim(),He=Hr.get(be)||be,Qe=Hr.get(Ee)||Ee,ot=rs.get(be)||"entity",mt=rs.get(Ee)||"entity",Dt=ef(ot),Xt=ef(mt),Xn=tf(B.observed_at),Bt=Q3(B),un=B.provenance&&typeof B.provenance=="object"&&!Array.isArray(B.provenance)?B.provenance:null,vn=un&&typeof un.span_id=="string"?un.span_id.trim():"",jn=un&&typeof un.writer_run_id=="string"?un.writer_run_id.trim():"",ps=typeof B.owner_id=="string"?B.owner_id.trim():"",Ns=jn||ps,yr=!!((k||x)&&vn&&Ns),Ro=!!(k&&jn&&!vn),Lo=yr||Ro;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:Dt.stroke,background:Dt.bg},title:be,onClick:()=>{be&&(Js(""),Fs(be))},children:He||be||"(subject)"}),s.jsx("span",{className:"amx-arrow",children:"—"}),s.jsx("span",{className:"amx-predicate",title:Se,children:M0(Se)||"(predicate)"}),s.jsx("span",{className:"amx-arrow",children:"→"}),s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Xt.stroke,background:Xt.bg},title:Ee,onClick:()=>{Ee&&(Js(""),Fs(Ee))},children:Qe||Ee||"(object)"})]}),s.jsxs("div",{className:"amx-triple-meta",children:[Xn?s.jsxs("span",{className:"amx-small",title:String(B.observed_at||""),children:["[",Xn,"]"]}):null,Bt?s.jsx("span",{className:"amx-small",children:Bt}):null]}),vn||jn?s.jsxs("div",{className:"amx-triple-actions",children:[vn?s.jsxs("span",{className:"amx-small",children:["span:",vn]}):null,jn?s.jsxs("span",{className:"amx-small",children:["run:",jn]}):null,Lo?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(yr&&vn&&Ns){Ss({run_id:Ns,span_id:vn,assertion:B});return}Ro&&jn&&Ss({run_id:jn,assertion:B})},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)."}),Yi.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:Yi.slice(0,60).map(B=>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:",B.span_id]}),s.jsxs("div",{className:"amx-small",children:["run_id=",B.span_run_id," · assertions=",B.count,B.last_observed_at_fmt?` · last=[${B.last_observed_at_fmt}]`:""]})]}),x||k?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ss({run_id:B.span_run_id,span_id:B.span_id,assertion:B.assertion}),children:"Open transcript"}):null]},`${B.span_run_id}|${B.span_id}`))})]}):null,k&&_r.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:_r.slice(0,40).map(B=>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:",B.run_id]}),s.jsxs("div",{className:"amx-small",children:["assertions=",B.count,B.last_observed_at_fmt?` · last=[${B.last_observed_at_fmt}]`:""]})]}),s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ss({run_id:B.run_id,assertion:B.assertion}),children:"Open transcript"})]},B.run_id))})]}):null,!Yi.length&&!(k&&_r.length)?s.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})})}function Kl({open:e,title:t,children:n,actions:r,variant:o="default",onClose:l}){const u=p.useId();if(p.useEffect(()=>{if(!e)return;const f=m=>{m.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 sp(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}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 Gl(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 rL(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=tl(t);return n!==null?Gl(n):t}function Wg(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,`
|
|
133
|
+
`).replace(/\\n/g,`
|
|
134
|
+
`).replace(/\\t/g," "):""}function R0(e){return String(e??"").replace(/[*_`~]/g,"")}function Gh(e,t){const n=!!(t!=null&&t.strip_punct),r=Wg(e);let o=R0(r).replace(/\s+/g," ").trim().toLowerCase();return n&&(o=o.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),o}function Kh(e,t){const n=String(t??"").trim();if(!n)return!1;const r=Gh(n,{strip_punct:!1});if(!r)return!1;if(Gh(String(e??""),{strip_punct:!1}).includes(r))return!0;const l=Gh(n,{strip_punct:!0});return l?Gh(String(e??""),{strip_punct:!0}).includes(l):!1}function hv(e){const t=Wg(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(R0(t)),n}function iL(e){const t=String(e??"").replace(/\r\n/g,`
|
|
135
|
+
`).replace(/\r/g,`
|
|
136
|
+
`);if(!t)return null;const n=t.split(`
|
|
137
|
+
`);let r;const o=[],l=[];let u=null,c=[],f=!1;const m=()=>{if(!u)return;const w=c.join(`
|
|
138
|
+
`).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 k=w.match(/^\s*(USER|ASSISTANT|SYSTEM)\s*:\s*(.*)$/i);if(k){f=!0,m();const j=String(k[1]||"").trim().toLowerCase();u=j==="user"?"user":j==="assistant"?"assistant":"system";const N=String(k[2]??"");c=N?[N]:[];continue}u?c.push(w):o.push(w)}if(m(),!f||!l.length)return null;const _=o.join(`
|
|
139
|
+
`).trim(),g={messages:[]};r&&(g.created_at=r),_&&g.messages.push({role:"system",content:_});for(const w of l)g.messages.push({role:w.role,content:w.lines.join(`
|
|
140
|
+
`)});return g.messages.length?g:null}function mv(e,t){const n=String(e||""),r=String(t||"");return r>n?r:n}function _v(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 aL({gateway:e,selected_run_id:t,selected_session_id:n}){const[r,o]=p.useState(String(t||"").trim()),[l,u]=p.useState(String(n||"").trim()),[c,f]=p.useState("all"),m=c==="all",[_,g]=p.useState(!0),[w,x]=p.useState(750),[k,j]=p.useState(5e3),[N,C]=p.useState([]),[E,T]=p.useState(void 0),[I,K]=p.useState(""),[U,J]=p.useState(!1),[Y,re]=p.useState([]),[ce,fe]=p.useState(!1),[W,O]=p.useState(!1),[$,z]=p.useState(""),[A,te]=p.useState(""),[P,F]=p.useState(""),[G,R]=p.useState(""),[Z,X]=p.useState("artifact"),[Q,le]=p.useState(null),[ge,pe]=p.useState(""),[ye,Ne]=p.useState(null),Ue=p.useRef(!1),We=p.useMemo(()=>{const ae=ye,je=ae!=null&&ae.attributes&&typeof ae.attributes=="object"&&!Array.isArray(ae.attributes)?ae.attributes:null;return(je&&typeof je.evidence_quote=="string"?String(je.evidence_quote):"").trim()},[ye]),pt=p.useMemo(()=>{const ae=Q,je=ae&&typeof ae=="object"&&!Array.isArray(ae)?ae:null,Ye=je&&typeof je.note=="string"?String(je.note):"";return Wg(Ye).trim()},[Q]),Fe=p.useMemo(()=>{const ae=Q&&typeof Q=="object"&&!Array.isArray(Q)?Q:null,je=ae&&Array.isArray(ae.messages)?ae.messages:null;return Array.isArray(je)?je:null},[Q]),tt=p.useMemo(()=>{const ae=pt,je=We;return!ae||!je?!1:Kh(ae,je)},[We,pt]),lt=p.useMemo(()=>{const ae=Fe,je=We;if(!ae||!je)return[];const Ye=[];for(let Ge=0;Ge<Math.min(ae.length,500);Ge++){const rt=ae[Ge],ct=(rt==null?void 0:rt.content)==null?"":String(rt.content);Kh(ct,je)&&Ye.push(Ge)}return Ye},[We,Fe]),Ke=p.useMemo(()=>new Set(lt),[lt]),ke=lt.length?lt[0]:null,Re=p.useCallback(ae=>{const je=document.getElementById(`source_msg_${ae}`);je&&typeof je.scrollIntoView=="function"&&je.scrollIntoView({block:"center",behavior:"smooth"})},[]),ht=p.useCallback(()=>{const ae=document.getElementById("source_note_hit_0")||document.getElementById("source_note_msg_hit_0");ae&&typeof ae.scrollIntoView=="function"&&ae.scrollIntoView({block:"center",behavior:"smooth"})},[]);p.useEffect(()=>{if(ce&&!(W||$)&&!Ue.current){if(ke!==null){Ue.current=!0,window.setTimeout(()=>Re(ke),0);return}if(tt){Ue.current=!0,window.setTimeout(()=>ht(),0);return}}},[Re,ht,$,ke,W,tt,ce]);const xe=p.useRef(new Set),Ie=p.useRef(""),qe=p.useRef(null),zt=p.useRef(null);p.useEffect(()=>{o(String(t||"").trim())},[t]),p.useEffect(()=>{u(String(n||"").trim())},[n]);const en=p.useMemo(()=>{const ae=String(r||"").trim(),je=String(l||"").trim();return`mindmap:${c}:${ae}:${je}`},[r,l,c]),bn=p.useMemo(()=>{let ae=null,je=null;for(const Ye of N){const Ge=tl(Ye==null?void 0:Ye.observed_at);Ge!==null&&(ae=ae===null?Ge:Math.min(ae,Ge),je=je===null?Ge:Math.max(je,Ge))}return{min_ms:ae,max_ms:je}},[N]),Wt=1e3,It=p.useMemo(()=>{const ae=bn.min_ms,je=bn.max_ms;if(typeof ae!="number"||typeof je!="number"||!Number.isFinite(ae)||!Number.isFinite(je))return null;if(je<=ae)return{min_ms:ae,max_ms:ae,real_max_ms:je};const Ye=ae+Math.ceil((je-ae)/Wt)*Wt;return{min_ms:ae,max_ms:Ye,real_max_ms:je}},[bn.max_ms,bn.min_ms]),[Sn,ns]=p.useState(!0),[Ot,pn]=p.useState(null);p.useEffect(()=>{Sn&&It&&pn(It.max_ms)},[Sn,It]);const Bn=p.useMemo(()=>{const ae=typeof Ot=="number"?Ot:null;return ae===null?N:N.filter(je=>{const Ye=tl(je==null?void 0:je.observed_at);return Ye===null?!0:Ye<=ae})},[N,Ot]),An=p.useCallback((ae,je)=>{const Ye=Array.isArray(ae)?ae:[],Ge=String(Ie.current||"").trim(),rt=new Set,ct=[];let Et="";for(const jt of Ye){if(!jt||typeof jt!="object"||typeof jt.subject!="string"||typeof jt.predicate!="string"||typeof jt.object!="string")continue;const Kt=_v(jt);if(rt.has(Kt))continue;rt.add(Kt),ct.push(jt);const xt=String(jt.observed_at||"").trim();xt&&(Et=mv(Et,xt))}C(ct),T(je==null?void 0:je.warnings),xe.current=rt,Ie.current=Et||Ge},[]),gn=p.useCallback(async ae=>{const je=sp(ae.scope,"session"),Ye=String(ae.subject||"").trim(),Ge=String(ae.predicate||"").trim(),rt=String(ae.object||"").trim(),ct=String(ae.since||"").trim(),Et=String(ae.until||"").trim(),jt=String(ae.active_at||"").trim(),Kt=String(ae.query_text||"").trim(),xt=typeof ae.min_score=="number"&&Number.isFinite(ae.min_score)?Number(ae.min_score):void 0,Yt=ae.order==="asc"?"asc":"desc",qt=typeof ae.limit=="number"&&Number.isFinite(ae.limit)?Number(ae.limit):0,Pt=String(r||"").trim(),At=String(l||"").trim(),$t={scope:je,all_owners:m,limit:qt,order:Yt};Ye&&($t.subject=Ye),Ge&&($t.predicate=Ge),rt&&($t.object=rt),ct&&($t.since=ct),Et&&($t.until=Et),jt&&($t.active_at=jt),Kt&&($t.query_text=Kt),typeof xt=="number"&&($t.min_score=xt),m||(je==="run"?Pt&&($t.run_id=Pt):je==="session"?At?$t.session_id=At:Pt&&($t.run_id=Pt):je==="all"&&(Pt?$t.run_id=Pt:At&&($t.session_id=At)));try{const De=await e.kg_query($t),on=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)||on.length),items:on,warnings:dt,raw:De}}catch(De){const on=De instanceof Error?De.message:String(De);if(on.includes("Run '")&&on.includes("not found")&&!At&&(je==="session"||je==="all")&&Pt){const tn=await e.kg_query({...$t,run_id:void 0,session_id:Pt}),ft=Array.isArray(tn==null?void 0:tn.items)?tn.items:[],Un=tn==null?void 0:tn.warnings;return{ok:(tn==null?void 0:tn.ok)!==!1,count:Number((tn==null?void 0:tn.count)||ft.length),items:ft,warnings:Un,raw:tn}}throw new Error(on||"KG query failed")}},[m,e,r,l]),In=p.useCallback(async ae=>{var Ge;const je=String(ae.run_id||"").trim(),Ye=String(ae.span_id||"").trim();if(!(!je||!Ye)){fe(!0),O(!0),z(""),F(je),R(Ye),X("artifact"),te(`source span:${Ye}`),le(null),pe(""),Ne(ae.assertion&&typeof ae.assertion=="object"?ae.assertion:null),Ue.current=!1;try{const rt=[je],ct=typeof((Ge=ae.assertion)==null?void 0:Ge.owner_id)=="string"?String(ae.assertion.owner_id).trim():"";ct&&ct!==je&&rt.push(ct);let Et=null,jt=null;for(const Kt of rt)try{jt=await(await e.download_run_artifact_content(Kt,Ye)).text(),Kt!==je&&F(Kt);break}catch(xt){Et=xt instanceof Error?xt.message:String(xt)}if(jt==null)throw new Error(Et||"Failed to load source span");pe(jt);try{const Kt=JSON.parse(jt);le(Kt)}catch{le(null)}}catch(rt){const ct=rt instanceof Error?rt.message:String(rt);z(ct||"Failed to load source span")}finally{O(!1)}}},[e]),wn=p.useCallback(async ae=>{const je=String(ae.run_id||"").trim();if(!je)return null;try{const Ye=await e.list_run_artifacts(je,{limit:200}),rt=(Array.isArray(Ye==null?void 0:Ye.items)?Ye.items:[]).map(xt=>{const Yt=typeof(xt==null?void 0:xt.artifact_id)=="string"?String(xt.artifact_id).trim():"",qt=xt!=null&&xt.tags&&typeof xt.tags=="object"&&!Array.isArray(xt.tags)?xt.tags:null,Pt=qt&&typeof qt.kind=="string"?String(qt.kind).trim():"";return{artifact_id:Yt,kind:Pt}}).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=ae.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 qt=await(await e.download_run_artifact_content(je,xt.artifact_id)).text(),Pt=JSON.parse(qt);if(Pt&&typeof Pt=="object"){const At=typeof Pt.note=="string"?String(Pt.note):"";if(At&&At.includes(Kt))return xt.artifact_id;const $t=Array.isArray(Pt.messages)?Pt.messages:null;if($t){for(const De of $t.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=p.useCallback(async ae=>{const je=String(ae.run_id||"").trim();if(je){fe(!0),O(!0),z(""),F(je),R(""),X("run_input"),te(`transcript run:${je}`),le(null),pe(""),Ne(ae.assertion&&typeof ae.assertion=="object"?ae.assertion:null),Ue.current=!1;try{const Ye=await wn({run_id:je,assertion:ae.assertion});if(Ye){await In({run_id:je,span_id:Ye,assertion:ae.assertion});return}const Ge=await e.get_run_input_data(je),rt=Ge&&typeof Ge=="object"&&!Array.isArray(Ge)?Ge.input_data:null,ct={kind:"run_input_data",run_id:je};if(Ge&&typeof(Ge==null?void 0:Ge.workflow_id)=="string"&&(ct.workflow_id=String(Ge.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 qt=rt[Yt];if(typeof qt=="string"&&qt.trim()){ct.note=qt.trim();break}}ct.input_data=rt}!ct.messages&&!ct.note&&(ct.note=JSON.stringify(rt??Ge??{},null,2));try{const Et=await e.get_run(je),jt=Et&&typeof(Et==null?void 0:Et.created_at)=="string"?String(Et.created_at):"";jt&&(ct.created_at=jt)}catch{}le(ct),pe(JSON.stringify(Ge,null,2))}catch(Ye){const Ge=Ye instanceof Error?Ye.message:String(Ye);z(Ge||"Failed to load run input transcript")}finally{O(!1)}}},[e,In,wn]),Kn=p.useCallback(async()=>{K(""),J(!0);try{const ae=c==="all"?"all":c,je=await gn({scope:ae,limit:0,order:"desc"});An(je.items||[],{warnings:je.warnings}),qe.current={scope:ae}}catch(ae){const je=ae instanceof Error?ae.message:String(ae);K(je||"Load failed")}finally{J(!1)}},[gn,An,c]);p.useEffect(()=>{N.length||Kn()},[]);const ks=p.useCallback(async ae=>{const je=sp(ae.scope,"session");return zt.current=ae,await gn({scope:je,subject:ae.subject,predicate:ae.predicate,object:ae.object,query_text:ae.query_text,min_score:ae.min_score,since:ae.since,until:ae.until,active_at:ae.active_at,limit:typeof ae.limit=="number"?ae.limit:0,order:"desc"})},[gn]),Nr=p.useCallback((ae,je)=>{var Ye;if((je==null?void 0:je.kind)==="live query"){const Ge=zt.current;Ge&&(qe.current={scope:sp(Ge.scope,"session"),subject:typeof Ge.subject=="string"?Ge.subject:void 0,predicate:typeof Ge.predicate=="string"?Ge.predicate:void 0,object:typeof Ge.object=="string"?Ge.object:void 0})}An(ae,{warnings:(Ye=je==null?void 0:je.result)==null?void 0:Ye.warnings})},[An]),On=p.useCallback(async()=>{const ae=qe.current;if(!ae)return;const je=String(Ie.current||"").trim(),Ye=await gn({scope:ae.scope,subject:ae.subject,predicate:ae.predicate,object:ae.object,since:je||void 0,order:"asc",limit:0}),Ge=Array.isArray(Ye.items)?Ye.items:[];if(!Ge.length)return;const ct=Date.now()+Math.max(250,Math.min(2e4,k)),Et=xe.current,jt=[],Kt=[];let xt=String(Ie.current||"").trim();for(const Yt of Ge){if(!Yt||typeof Yt!="object"||typeof Yt.subject!="string"||typeof Yt.predicate!="string"||typeof Yt.object!="string")continue;const qt=_v(Yt);if(Et.has(qt))continue;Et.add(qt),jt.push(Yt),Kt.push({id:qt,assertion:Yt,expires_at_ms:ct});const Pt=String(Yt.observed_at||"").trim();Pt&&(xt=mv(xt,Pt))}jt.length&&(Ie.current=xt,C(Yt=>{const qt=Yt.concat(jt);return qt.sort((Pt,At)=>String((At==null?void 0:At.observed_at)||"").localeCompare(String((Pt==null?void 0:Pt.observed_at)||""))),qt}),re(Yt=>{const qt=Yt.concat(Kt);return qt.sort((Pt,At)=>At.expires_at_ms-Pt.expires_at_ms),qt.slice(0,30)}))},[k,gn]);return p.useEffect(()=>{if(!_)return;let ae=!1,je=null;const Ye=async()=>{if(!ae){try{await On()}catch{}ae||(je=window.setTimeout(()=>void Ye(),Math.max(250,Math.min(6e4,w))))}};return Ye(),()=>{ae=!0,je!==null&&window.clearTimeout(je)}},[_,w,On]),p.useEffect(()=>{if(!Y.length)return;const ae=window.setInterval(()=>{const je=Date.now();re(Ye=>Ye.filter(Ge=>Ge.expires_at_ms>je))},250);return()=>window.clearInterval(ae)},[Y.length]),s.jsxs("div",{className:"mindmap_root",children:[s.jsxs("div",{className:"mindmap_bar",children:[s.jsx("button",{className:"btn",onClick:()=>void Kn(),disabled:U,children:U?"Loading…":"Load snapshot"}),s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"source"}),s.jsxs("select",{value:c,onChange:ae=>{const je=String(ae.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(dC,{checked:_,onChange:g}),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:ae=>u(String(ae.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:ae=>o(String(ae.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:ae=>x(Math.max(250,Number(ae.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:k,onChange:ae=>j(Math.max(250,Number(ae.target.value||0)||5e3))})]})})]})]}),I?s.jsx("div",{className:"mindmap_error mono",children:I}):null,s.jsxs("div",{className:"mindmap_explorer",children:[s.jsx(sL,{title:"mindmap",resetKey:en,queryMode:"replace",items:Bn,warnings:E,onQuery:ks,onItemsReplace:Nr,onOpenSpan:({run_id:ae,span_id:je,assertion:Ye})=>{In({run_id:ae,span_id:je,assertion:Ye})},onOpenTranscript:({run_id:ae,span_id:je,assertion:Ye})=>{const Ge=String(ae||"").trim(),rt=typeof je=="string"?String(je).trim():"";Ge&&(rt?In({run_id:Ge,span_id:rt,assertion:Ye}):js({run_id:Ge,assertion:Ye}))}},en),Y.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:Y.slice().sort((ae,je)=>je.expires_at_ms-ae.expires_at_ms).slice(0,12).map(ae=>s.jsx("div",{className:"mindmap_recent_item mono",children:oL(ae.assertion)},ae.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:Gl(Math.min(typeof Ot=="number"?Ot:It.max_ms,It.real_max_ms))}),s.jsx("input",{className:"mindmap_slider",type:"range",min:It.min_ms,max:It.max_ms,step:Wt,value:typeof Ot=="number"?Ot:It.max_ms,onChange:ae=>{const je=Number(ae.target.value||0);pn(je),ns(je>=It.max_ms)}}),s.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[Bn.length.toLocaleString(),"/",N.length.toLocaleString()]})]})}):null]}),s.jsxs(Kl,{open:ce,title:A||"source",onClose:()=>{fe(!1)},children:[W?s.jsx("div",{className:"mono muted",children:"Loading…"}):null,$?s.jsx("div",{className:"mindmap_error mono",children:$}):null,!W&&!$?s.jsxs("div",{className:"source_span",children:[(()=>{const ae=ye;if(!ae)return null;const je=String(ae.subject||"").trim(),Ye=String(ae.predicate||"").trim(),Ge=String(ae.object||"").trim(),rt=Gl(tl(ae.observed_at)),ct=ae.attributes&&typeof ae.attributes=="object"&&!Array.isArray(ae.attributes)?ae.attributes:null,Et=ct&&typeof ct.evidence_quote=="string"?String(ct.evidence_quote):"",jt=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} --${Ye}--> ${Ge}`,children:[je," ",s.jsxs("span",{className:"muted",children:["—",Ye,"→"]})," ",Ge," ",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}),jt?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:jt})]}):null]}):null]})})(),s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["run_id=",P," · ",Z==="artifact"?`span_id=${G}`:"source=input_data"]}),s.jsxs("div",{className:"source_actions",children:[ke!==null?s.jsx("button",{className:"btn",onClick:()=>Re(ke),children:"Jump to evidence"}):null,ke===null&&tt?s.jsx("button",{className:"btn",onClick:()=>ht(),children:"Jump to evidence"}):null]}),(()=>{const ae=Q,je=ae&&typeof ae=="object"&&!Array.isArray(ae)?ae:null,Ye=Fe,Ge=pt,rt=je&&typeof je.created_at=="string"?String(je.created_at):"",ct=rt?tl(rt):null,Et=ct!==null?Gl(ct):rt,jt=je&&je.span&&typeof je.span=="object"&&!Array.isArray(je.span)?je.span:null,Kt=jt&&typeof jt.from_timestamp=="string"?String(jt.from_timestamp):"",xt=jt&&typeof jt.to_timestamp=="string"?String(jt.to_timestamp):"",Yt=Kt?tl(Kt):null,qt=xt?tl(xt):null,Pt=Yt!==null&&qt!==null?`${Gl(Yt)} → ${Gl(qt)}`:"";if(Ge){const At=iL(Ge);if(At){const $t=We,De=$t?At.messages.findIndex(ft=>Kh(ft.content,$t)):-1,on=$t?hv($t):[],dt=At.created_at||rt,tn=dt?rL(dt):rt?Et:"";return s.jsx("div",{className:"source_chat",children:At.messages.map((ft,Un)=>{const an=ft.role,Ys=!!($t&&Kh(ft.content,$t)),ss=an==="user"?"USER":an==="assistant"?"ASSISTANT":"SYSTEM";return s.jsxs("div",{id:Un===De?"source_note_msg_hit_0":void 0,className:`source_msg source_${an} ${Ys?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Un+1," · ",ss,Ys?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),tn?s.jsx("span",{title:dt||"",children:tn}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Wi,{text:ft.content,highlights:Ys&&on.length?on:void 0,highlightClassName:"source_note_hit",highlightId:Un===De?"source_note_hit_0":void 0})})]},`note_msg:${Un}`)})})}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(Wi,{text:Ge,highlights:We?hv(We):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(Ye){const At=new Map;for(const De of Ye){const on=typeof(De==null?void 0:De.role)=="string"?String(De.role):"unknown";At.set(on,(At.get(on)||0)+1)}const $t=Array.from(At.entries()).sort((De,on)=>on[1]-De[1]||De[0].localeCompare(on[0])).map(([De,on])=>`${De}×${on}`).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=",Ye.length]}):null,Pt?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["span=",Pt]}):null,$t?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["participants: ",$t]}):null,Ye.slice(0,200).map((De,on)=>{var Wr,dr;const dt=typeof(De==null?void 0:De.role)=="string"?String(De.role):"unknown",tn=(De==null?void 0:De.content)==null?"":String(De.content),ft=typeof(De==null?void 0:De.timestamp)=="string"?String(De.timestamp):"",Un=ft?tl(ft):null,an=Un!==null?Gl(Un):ft,Ys=typeof(De==null?void 0:De.message_id)=="string"?String(De.message_id):typeof((Wr=De==null?void 0:De.metadata)==null?void 0:Wr.message_id)=="string"?String(De.metadata.message_id):typeof((dr=De==null?void 0:De.metadata)==null?void 0:dr.id)=="string"?String(De.metadata.id):"",ss=Ke.has(on);return s.jsxs("div",{id:`source_msg_${on}`,className:`source_msg source_${dt} ${ss?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",on+1," · ",dt,ss?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null,Ys?s.jsx("span",{className:"source_msg_id",children:Ys}):null]}),ft?s.jsx("span",{title:ft,children:an}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Wi,{text:tn})})]},on)})]})}return s.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof ae=="string"?ae:ge)||"(empty)"})})()]}):null]})]})}const rp=4;function lL(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 pv(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 cL(e){var c,f;const t=m=>{var g;const _=(g=e==null?void 0:e[m])==null?void 0:g.open;return Array.isArray(_)?_.map(pv).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(pv).filter(m=>m!==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,rp),questions_total:n.length,problems:r.slice(0,rp),problems_total:r.length,lessons:l.slice(0,rp),lessons_total:u}}function ip(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 gv={review:"Review",working:"Working",pending:"Pending",done:"Done"},uL={review:"nothing needs you",working:"idle",pending:"nothing scheduled",done:"no recent runs"},dL={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 fL(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(So(t))return"done";const n=Au(e);return n==="tool_approval"||n==="user_response"?"review":n==="scheduled"||t==="pending"||t==="queued"||t==="created"?"pending":"working"}function hL(e){const t=Au(e);return t==="tool_approval"||t==="user_response"}function yv(e,t=Date.now()){const n=fL(e),r=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,o=Tf(r),l=qn((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:Au(e),reason:tb(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:gg(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:ff(e),tag_label:Lx(e),automation_id:ff(e)==="occurrence"?String((e==null?void 0:e.automation_id)||"").trim():""}}function mL(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)||Gy(u)||hL(u)&&(l.add(c),r.review.push(yv(u,n)))}for(const u of e||[]){const c=String((u==null?void 0:u.run_id)||"").trim();if(!u||!c||l.has(c)||Gy(u))continue;const f=yv(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 sg={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},op={"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"},wv="48h";function _L(e,t,n=Date.now()){const r=sg[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 pL(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 nf(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 yL(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 wL(e){const t=String(e||"");return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function ap(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function vL(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 rm(e){return e.toLowerCase().replace(/[_-]+/g," ")}function xL(e){var m,_;const t=e!=null&&e.spec&&typeof e.spec=="object"?e.spec:null,n=t!=null&&t.phases&&typeof t.phases=="object"&&!Array.isArray(t.phases)?t.phases:null;if(!n)return null;const r=Object.keys(n).filter(g=>g&&typeof g=="string");if(!r.length)return null;const o=[];for(const g of r){o.push({needle:rm(g),phase:g});const w=(m=n[g])==null?void 0:m.spoken_synonyms;if(Array.isArray(w))for(const x of w){const k=rm(String(x||"").trim());k&&o.push({needle:k,phase:g})}}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=(_=t==null?void 0:t.state_mode_axis)==null?void 0:_.words;if(f&&typeof f=="object"&&!Array.isArray(f))for(const[g,w]of Object.entries(f)){const x=String((w==null?void 0:w.phase)||"").trim(),k=rm(String(g||"").trim());k&&r.includes(x)&&c.push({needle:k,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 bL=["asleep","sleep","dream"],jL=["rest"],kL=["awake","idle"];function SL(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const r=rm(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":bL.some(u=>n.includes(u))?t.initial:jL.some(u=>n.includes(u))&&t.phases.includes("personal")?"personal":kL.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 NL=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),CL=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function EL(e){if(!e)return NL;const t=e.phases.filter(n=>CL.has(n));return new Set([...t,"paused","stopped","unknown"])}function AL(e){const[t,n]=hf(`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(mf,{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 $L(e){var U,J,Y,re,ce,fe;const t=Date.now(),n=p.useMemo(()=>mL(e.runs,e.all_runs,Date.now()),[e.runs,e.all_runs]),[r,o]=p.useState(""),[l,u]=p.useState(""),[c,f]=p.useState(!1),[m,_]=p.useState(()=>{try{const W=localStorage.getItem("abstractobserver_done_window_v1");return W&&W in sg?W:wv}catch{return wv}}),g=p.useMemo(()=>_L(n.done,m,t),[n.done,m]),w=nf(e.runs_refreshed_at,t),x=n.review.length,k=g.visible.filter(W=>W.failed).length,[j,N]=p.useState(""),[C,E]=p.useState(null),T=W=>`${W.run_id}:${W.wait_key}:${W.since_ms??""}`;p.useEffect(()=>{r&&(n.review.some(W=>T(W)===r)||o(""))},[n,r]);async function I(W,O){o(T(W)),u("");try{await e.on_resume_wait(W.run_id,W.wait_key,O)}catch($){u(`${W.run_id}: ${String(($==null?void 0:$.message)||$||"resume failed")}`),o("")}}function K(W){const O=r===T(W),$=W.column==="review",z=$&&!W.wait_key;return s.jsxs("div",{className:`mc_card ${$?"mc_card_review":""} ${W.failed?"mc_card_failed":""}`,onClick:()=>e.on_open_run(W.run_id),role:"button",tabIndex:0,onKeyDown:A=>{A.key==="Enter"&&A.target===A.currentTarget&&e.on_open_run(W.run_id)},children:[s.jsxs("div",{className:"mc_card_head",children:[s.jsx("span",{className:"mc_card_title",title:W.workflow,children:vL(W.workflow)}),(()=>{const A=W.failed?"failed":um({status:W.status,paused:W.paused});return s.jsx("span",{className:`mc_status ${oc(A)}`,children:A==="unknown"?"?":A})})()]}),s.jsxs("div",{className:"mc_card_meta",children:[s.jsx("span",{className:"mono",title:W.run_id,children:wL(W.run_id)}),W.is_subrun?s.jsx("span",{title:"This wait lives in a child run of an agent workflow",children:"subrun"}):null,W.tag?s.jsx("span",{className:"mc_pill","data-tag":W.tag,children:W.tag_label}):null,W.automation_id?s.jsx("button",{type:"button",className:"btn btn_sm",title:"Open this occurrence's automation",onClick:A=>{A.stopPropagation(),e.on_open_automation(W.automation_id)},onKeyDown:A=>A.stopPropagation(),children:"Automation"}):null,W.duration_ms>=0?s.jsx("span",{children:yL(W.duration_ms)}):null,W.tokens_total!==null?s.jsxs("span",{children:[W.tokens_total.toLocaleString()," tk"]}):null,W.tool_calls!==null&&W.tool_calls>0?s.jsxs("span",{children:[W.tool_calls," tools"]}):null]}),W.is_scheduled&&W.schedule_interval?s.jsxs("div",{className:"mc_card_line",children:["every ",W.schedule_interval]}):null,W.failed&&W.error?s.jsx("div",{className:"mc_card_error",title:W.error,children:W.error.length>120?`${W.error.slice(0,118)}…`:W.error}):null,$?s.jsxs("div",{className:"mc_card_review_body",onClick:A=>A.stopPropagation(),onKeyDown:A=>A.stopPropagation(),children:[s.jsx("div",{className:"mc_card_reason",children:W.reason||"Needs a decision"}),W.prompt?s.jsx("div",{className:"mc_card_prompt",title:W.prompt,children:W.prompt.length>240?`${W.prompt.slice(0,238)}…`:W.prompt}):null,W.tool_names.length?s.jsxs("div",{className:"mc_card_tools",title:"Tool calls awaiting your approval",children:[W.tool_names.slice(0,4).map((A,te)=>s.jsx("span",{className:"mc_tool_chip mono",children:A},`${A}_${te}`)),W.tool_names.length>4?s.jsxs("span",{className:"mc_tool_chip",children:["+",W.tool_names.length-4," more"]}):null]}):null,W.since_ms!==null?s.jsxs("div",{className:"mc_card_waiting",children:["waiting ",nf(W.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(W.run_id),children:"Open the run →"})}):W.wait_kind==="tool_approval"?s.jsxs("div",{className:"mc_card_actions",children:[s.jsx("button",{className:"btn success",disabled:O,onClick:()=>void I(W,{approved:!0}),children:O?"Resuming…":"Approve"}),s.jsx("button",{className:"btn danger",disabled:O,onClick:()=>void I(W,{approved:!1}),children:"Reject"})]}):s.jsx("div",{className:"mc_card_actions",children:s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(W.run_id),children:"Review & answer →"})})]}):null]},W.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 ${k?"is_bad":""}`,title:"failed runs in the Done column",children:[s.jsx("span",{className:"mc_stat_value",children:k}),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(W=>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(W.name)}&live=1`,target:"_blank",rel:"noreferrer",title:[W.error,W.age_days!==null?`${W.age_days.toFixed(0)} days old`:"",W.last_moment].filter(Boolean).join(" — ")||W.name,children:[s.jsx("span",{className:"mc_entity_name",children:W.name}),(()=>{var F;const O=String(W.live_phase||W.state||"").trim(),$=SL(O,e.phase_graph),z=EL(e.phase_graph).has($)?$:"other",A=((F=e.phase_graph)==null?void 0:F.initial)??"sleep",te=/awake|idle/i.test(O)&&$===A,P=O&&O.toLowerCase()!==$?` — wire word: ${O}${te?" (settling)":""}`:"";return s.jsx("span",{className:`mc_entity_phase mc_phase_${z}`,title:(W.live_phase?"phase (cognition wire)":"phase from card state — cognition wire unavailable")+P,children:$})})(),W.last_moment?s.jsx("span",{className:"mc_entity_moment",title:W.last_moment,children:W.last_moment.replace(/_/g," ")}):null,(()=>{if(W.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 O=pL(W.last_moment_at,t);return W.working===!1?s.jsxs("span",{className:"mc_entity_live muted",title:"idle (cognition wire)",children:["idle",O!==null?` · ${nf(t-O,t)} ago`:""]}):O===null?null:O<=gL?s.jsx("span",{className:"mc_entity_live",title:`last moment ${nf(t-O,t)} ago`,children:"● active"}):s.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[nf(t-O,t)," ago"]})})(),W.tokens_total!==null?s.jsxs("span",{className:"muted mc_entity_spend",title:`lifetime billed tokens (home run ledger)${W.live_visit_tokens!==null?`; open visit: ${ip(W.live_visit_tokens)} tk`:""}${W.spend_warning?`; ${W.spend_warning}`:""}`,children:[ip(W.tokens_total)," tk",W.live_visit_tokens!==null?` (+${ip(W.live_visit_tokens)})`:"",W.spend_warning?"*":""]}):null]}),W.open_questions_total||W.open_problems_total||W.lessons_total||W.dreams_brief?s.jsx("button",{type:"button",className:"mc_entity_hints_btn","aria-expanded":j===W.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>N(j===W.name?"":W.name),children:[W.open_questions_total?`${W.open_questions_total} question${W.open_questions_total>1?"s":""}`:"",W.open_problems_total?`${W.open_problems_total} problem${W.open_problems_total>1?"s":""}`:"",W.lessons_total?`${W.lessons_total} lesson${W.lessons_total>1?"s":""}`:"",W.dreams_brief?`night: ${W.dreams_brief.count} signal${W.dreams_brief.count>1?"s":""}`:""].filter(Boolean).join(" · ")}):null]},W.name))}),(()=>{if(!j)return null;const W=e.entities.find(z=>z.name===j);if(!W||!W.open_questions.length&&!W.open_problems.length&&!W.lessons.length&&!W.dreams_brief)return null;const O=e.on_read_diary?async z=>{const A=await e.on_read_diary(W.name,z);E({entity:W.name,entry:(A==null?void 0:A.entry)??A,seq:typeof(A==null?void 0:A.read_recorded_at_seq)=="number"?A.read_recorded_at_seq:null})}:void 0,$=W.open_questions_total-W.open_questions.length+(W.open_problems_total-W.open_problems.length)+(W.lessons_total-W.lessons.length);return s.jsxs("div",{className:"mc_entity_hints_panel",children:[W.open_questions.map((z,A)=>s.jsx(b_,{kind:"question",label:z.title||ap(z.statement),entryId:z.entry_id,onOpen:O,title:z.statement||z.title},`q_${z.record_id||A}`)),W.open_problems.map((z,A)=>s.jsx(b_,{kind:"problem",label:z.title||ap(z.statement),entryId:z.entry_id,onOpen:O,title:z.statement||z.title},`p_${z.record_id||A}`)),W.lessons.map((z,A)=>s.jsx(b_,{kind:"lesson",label:z.title||ap(z.statement),entryId:z.entry_id,onOpen:O,title:z.statement||z.title},`l_${z.record_id||A}`)),W.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: ",W.dreams_brief.count,W.dreams_brief.dreams?` across ${W.dreams_brief.dreams} dream${W.dreams_brief.dreams>1?"s":""}`:"",W.dreams_brief.kinds.length?` — ${W.dreams_brief.kinds.slice(0,6).join(", ")}${W.dreams_brief.kinds.length>6?` +${W.dreams_brief.kinds.length-6} more`:""}`:"",W.dreams_brief.felt_tones.length?` · felt: ${W.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,C?s.jsx(Kl,{open:!0,title:`${C.entity} — diary entry`,onClose:()=>E(null),children:s.jsxs("div",{className:"mc_diary_entry",children:[s.jsx("div",{className:"mc_diary_meta muted",children:[(U=C.entry)!=null&&U.kind?`kind: ${C.entry.kind}`:"",(J=C.entry)!=null&&J.visibility?`visibility: ${C.entry.visibility}`:"",(Y=C.entry)!=null&&Y.written_at?`written: ${C.entry.written_at}`:"",(re=C.entry)!=null&&re.entry_id?`id: ${C.entry.entry_id}`:""].filter(Boolean).join(" · ")}),s.jsxs("div",{className:"mc_diary_recorded muted",children:["this read was recorded in ",C.entity,"’s stream",C.seq!==null?` (seq ${C.seq})`:""]}),(ce=C.entry)!=null&&ce.gist?s.jsx("div",{className:"mc_diary_gist",children:String(C.entry.gist)}):null,s.jsx("pre",{className:"mc_diary_text",children:String(((fe=C.entry)==null?void 0:fe.text)||"(entry carries no text)")})]})}):null,s.jsx("div",{className:"mc_board",children:Object.keys(gv).map(W=>{const O=W==="done"?g.visible:n[W],$=W==="done"&&!c?O.slice(0,8):O;return s.jsxs(AL,{col:W,title:gv[W],head:s.jsxs(s.Fragment,{children:[W==="done"?s.jsx("select",{className:"mc_window_select",value:m,title:"Show terminal runs from this time window",onClick:z=>z.stopPropagation(),onChange:z=>{const A=z.target.value;_(A),f(!1);try{localStorage.setItem("abstractobserver_done_window_v1",A)}catch{}},children:Object.keys(sg).map(z=>s.jsx("option",{value:z,children:op[z]},z))}):null,s.jsx("span",{className:"mc_column_count",title:W==="done"&&g.hidden_count?`${g.hidden_count} older run(s) outside this window`:void 0,children:O.length})]}),children:[s.jsx("div",{className:"mc_column_hint muted",children:dL[W]}),s.jsxs("div",{className:"mc_column_cards",children:[$.map(z=>K(z)),O.length?null:s.jsx("div",{className:"mc_empty muted",children:e.runs_refreshed_at===null?"loading…":W==="done"&&g.hidden_count?`none in the ${op[m]} — ${g.hidden_count} older`:uL[W]}),W==="done"&&O.length>8&&!c?s.jsxs("button",{className:"btn mc_more",onClick:()=>f(!0),children:["show all ",O.length]}):null,W==="done"&&g.hidden_count&&O.length?s.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",g.hidden_count," older outside ",op[m]]}):null]})]},W)})})]})}function vv(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 xv(e){const t=e.disabled===!0,n=p.useMemo(()=>vv(e.options||[]),[e.options]),r=p.useMemo(()=>vv(e.value||[]),[e.value]),[o,l]=p.useState(!1),[u,c]=p.useState(""),f=p.useMemo(()=>{const g=u.trim().toLowerCase();return g?n.filter(w=>w.toLowerCase().includes(g)):n},[n,u]),m=p.useMemo(()=>new Set(r),[r]),_=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(g=>!g),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(g=>s.jsxs("span",{className:"multi_select_chip",title:g,onClick:()=>{if(t)return;const w=new Set(m);w.delete(g),e.onChange(Array.from(w.values()))},children:[g,t?null:s.jsx("span",{className:"multi_select_chip_x",children:"×"})]},g))}):null,o?s.jsxs("div",{className:"multi_select_panel",children:[s.jsx("input",{className:"mono",value:u,onChange:g=>c(String(g.target.value||"")),placeholder:"filter…",disabled:t}),s.jsxs("div",{className:"multi_select_list",style:{maxHeight:`${_}px`},children:[f.map(g=>{const w=m.has(g);return s.jsxs("label",{className:`multi_select_item mono ${w?"checked":""}`,children:[s.jsx("input",{type:"checkbox",checked:w,disabled:t,onChange:x=>{const k=new Set(m);x.target.checked?k.add(g):k.delete(g),e.onChange(Array.from(k.values()))}}),s.jsx("span",{children:g})]},g)}),f.length?null:s.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function TL(){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 ML(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function RL(){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 LL(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 IL(e){const t=z=>{var A;return(A=e.on_error)==null?void 0:A.call(e,z)},n=p.useMemo(()=>ML(),[]),r=p.useMemo(()=>TL(),[]),[o,l]=p.useState({key:"",status:"idle"}),u=p.useRef(""),c=p.useRef(""),f=p.useRef(null),m=p.useRef(null),_=p.useRef(null),g=p.useRef(null),w=p.useRef(0),x=p.useRef(0),k=()=>{try{const z=globalThis,A=(z==null?void 0:z.AudioContext)||(z==null?void 0:z.webkitAudioContext);if(!A)return null;if(!f.current){const F=new A,G=F.createGain();G.gain.value=1,G.connect(F.destination),f.current=F,m.current=G}const te=f.current,P=m.current;if(!te||!P)return null;try{te.state==="suspended"&&te.resume()}catch{}return{ctx:te,gain:P}}catch{return null}},j=()=>{const z=_.current;if(_.current=null,!!z){try{z.onended=null}catch{}try{z.stop()}catch{}try{z.disconnect()}catch{}}},N=()=>{j(),c.current="",u.current="",g.current=null,w.current=0,x.current=0,l({key:"",status:"idle"})};p.useEffect(()=>()=>{var z,A;N();try{(z=m.current)==null||z.disconnect()}catch{}try{(A=f.current)==null||A.close()}catch{}f.current=null,m.current=null,g.current=null},[]);const C=async(z,A,te)=>{const P=k();if(!P)throw new Error("TTS playback is not supported in this browser");const{ctx:F,gain:G}=P;try{F.state==="suspended"&&await F.resume()}catch{}j();const R=F.createBufferSource();R.buffer=A,R.connect(G);const Z=Number.isFinite(Number(A.duration))?Number(A.duration):0,X=Math.max(0,Math.min(Number(te||0),Z>0?Math.max(0,Z-.01):0));x.current=F.currentTime-X,w.current=X,_.current=R,u.current=z,R.onended=()=>{_.current===R&&(_.current=null,w.current=0,x.current=0,u.current="",l({key:"",status:"idle"}))},R.start(0,X),l({key:z,status:"playing"})},E=async(z,A)=>{const te=String(z||"").trim(),P=String(A||"").trim();if(!te||!P)return;const F=e.gateway,G=String(e.run_id||"").trim();if(!F){t==null||t("Connect to the gateway first.");return}if(!G){t==null||t("Voice store not available (missing run_id).");return}const R=k();if(!R){t==null||t("TTS playback is not supported in this browser.");return}const Z=o.key===te;if(Z&&o.status==="playing"){const X=Math.max(0,R.ctx.currentTime-Number(x.current||0));w.current=X,j(),l({key:te,status:"paused"});return}if(Z&&o.status==="paused"){const X=g.current;if(X){t==null||t("");try{await C(te,X,w.current)}catch(Q){t==null||t(String((Q==null?void 0:Q.message)||Q||"TTS play failed")),l({key:"",status:"idle"})}return}}if(!(Z&&o.status==="loading")){j(),g.current=null,w.current=0,x.current=0,u.current=te,c.current=te,l({key:te,status:"loading"}),t==null||t("");try{const X=await F.voice_tts(G,{text:P,request_id:xs()}),Q=X==null?void 0:X.audio_artifact,le=Q&&typeof Q=="object"&&!Array.isArray(Q)?String(Q.$artifact||"").trim():"";if(!le)throw new Error("TTS failed: missing audio artifact");const pe=await(await F.download_run_artifact_content(G,le)).arrayBuffer();if(c.current!==te)return;const ye=await LL(R.ctx,pe);if(c.current!==te)return;g.current=ye,w.current=0,await C(te,ye,0)}catch(X){c.current===te&&(c.current="",u.current="",l({key:"",status:"idle"})),t==null||t(String((X==null?void 0:X.message)||X||"TTS failed"))}}},[T,I]=p.useState(!1),[K,U]=p.useState(!1),J=p.useRef(null),Y=p.useRef(null),re=p.useRef([]),ce=p.useRef("");function fe(){var z,A;try{(A=(z=J.current)==null?void 0:z.getTracks)==null||A.call(z).forEach(te=>{try{te.stop()}catch{}})}catch{}J.current=null}p.useEffect(()=>()=>{var z,A;try{(A=(z=Y.current)==null?void 0:z.stop)==null||A.call(z)}catch{}Y.current=null,fe()},[]);async function W(z,A){var G;if(t==null||t(""),!z||!z.size||K)return;const te=e.gateway,P=String(e.session_id||"").trim(),F=String(e.run_id||"").trim();if(!te){t==null||t("Connect to the gateway first.");return}if(!P){t==null||t("Voice input unavailable (missing session_id).");return}if(!F){t==null||t("Voice input unavailable (missing run_id).");return}U(!0);try{const R=String(A||z.type||"").toLowerCase(),Z=R.includes("mp4")?"m4a":R.includes("ogg")?"ogg":R.includes("wav")?"wav":"webm",X=new File([z],`recording.${Z}`,{type:R||"audio/webm"}),Q=await te.attachments_upload(P,X,{filename:X.name,content_type:X.type}),le=await te.audio_transcribe(F,{audio_artifact:Q,request_id:xs()}),ge=String((le==null?void 0:le.text)||"").trim();ge&&((G=e.on_transcript)==null||G.call(e,ge))}catch(R){t==null||t(String((R==null?void 0:R.message)||R||"Transcription failed"))}finally{U(!1)}}async function O(){if(t==null||t(""),!r){t==null||t(Ip()?"Voice recording is not supported in this browser (MediaRecorder unavailable).":Lp);return}if(!K&&!(T||Y.current)){re.current=[];try{const z=await navigator.mediaDevices.getUserMedia({audio:!0});J.current=z;const A=RL();ce.current=A;const te=A?new MediaRecorder(z,{mimeType:A}):new MediaRecorder(z);Y.current=te,te.ondataavailable=P=>{try{P!=null&&P.data&&re.current.push(P.data)}catch{}},te.onerror=()=>{t==null||t("Recording failed.")},te.onstop=()=>{I(!1),fe(),Y.current=null;try{const P=new Blob(re.current,{type:ce.current||""});W(P,ce.current)}catch(P){t==null||t(String((P==null?void 0:P.message)||P||"Failed to build recording"))}},te.start(),I(!0)}catch(z){fe(),Y.current=null,I(!1);const A=String((z==null?void 0:z.message)||z||"Failed to access microphone");t==null||t(A.toLowerCase().includes("permission")?`Microphone permission denied: ${A}`:A)}}}function $(){const z=Y.current;if(!(!T||!z)){Y.current=null,I(!1);try{z.stop()}catch(A){t==null||t(String((A==null?void 0:A.message)||A||"Failed to stop recording"))}}}return p.useEffect(()=>{if(!T)return;const z=()=>$();return window.addEventListener("pointerup",z),window.addEventListener("pointercancel",z),()=>{window.removeEventListener("pointerup",z),window.removeEventListener("pointercancel",z)}},[T]),{tts_supported:n,tts_playback:o,toggle_tts:E,stop_tts:N,voice_ptt_supported:r,voice_ptt_recording:T,voice_ptt_busy:K,start_voice_ptt_recording:O,stop_voice_ptt_recording:$}}const Yh=500,Sm="http://127.0.0.1:8080";function bv(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 sf(e){const t=String(e||"").trim();return t.startsWith("abstractcode.")?`abstract.${t.slice(13)}`:t}function lp(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 cp(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function OL(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 PL(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 m=String(c.type||"").trim();if(m==="execution"||f==="exec-out"||f==="exec")continue;const _=String(c.label||f).trim()||f,g={id:f,label:_,type:m||"unknown"};l&&Object.prototype.hasOwnProperty.call(l,f)&&(g.default=l[f]),u.push(g)}return u}function up(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 DL=/^[a-zA-Z0-9_-]+$/;function jv(e){return DL.test(String(e||"").trim())}async function FL(e){const t=String(e||"");return kE(t)}async function zL(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(jv(t)){const r=`session_memory_${t}`;if(jv(r))return r}return`session_memory_sha_${(await FL(t)).slice(0,32)}`}function BL(){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)||Sm),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:Sm,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 UL(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function WL(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 kv(e){const t=WL(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 qL(){return typeof window>"u"?"":kN(window.location)}function HL(){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 VL(){var es,Gn,us,ar,Qo,Yn,Va,wo,Bl,Zc,Ga,Hs,Qc,ea,vi;const[e,t]=p.useState("board"),[n,r]=p.useState(()=>BL()),o=typeof window<"u"&&((es=window.__ABSTRACT_UI_CONFIG__)==null?void 0:es.monitor_gpu)===!0,l=typeof window<"u"&&(((Gn=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Gn.entity_app_url)||"").trim().replace(/\/+$/,"")||"http://127.0.0.1:3007",u=p.useRef(null),[c,f]=p.useState(""),[m,_]=p.useState(""),[g,w]=p.useState(()=>qL()),[x,k]=p.useState(""),[j,N]=p.useState(""),[C,E]=p.useState(""),[T,I]=p.useState("{}"),[K]=p.useState(()=>HL()),[U,J]=p.useState(null),[Y,re]=p.useState(!1),[ce,fe]=p.useState(""),[W,O]=p.useState(!1),[$,z]=p.useState(""),[A,te]=p.useState(!1),P=$j({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((us=window.__ABSTRACT_UI_CONFIG__)==null?void 0:us.gateway_url)||Sm,onStatusChange:y=>dd(y)}),[F,G]=p.useState(null),[R,Z]=p.useState(null),[X,Q]=p.useState(!1),[le,ge]=p.useState(null),[pe,ye]=p.useState("once"),[Ne,Ue]=p.useState(""),[We,pt]=p.useState(Ep),[Fe,tt]=p.useState([]),[lt,Ke]=p.useState(null),[ke,Re]=p.useState(!1),[ht,xe]=p.useState([]),Ie=p.useRef(new v2(xs)),[qe,zt]=p.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[en,bn]=ek("abstractobserver",{legacyKey:"abstractobserver_settings"}),[Wt,It]=p.useState(!1),[Sn,ns]=p.useState(!1),[Ot,pn]=p.useState([]),[Bn,An]=p.useState([]),[gn,In]=p.useState([]),[wn,js]=p.useState(!1),[Kn,ks]=p.useState(null),[Nr,On]=p.useState([]),[ae,je]=p.useState(0),[Ye,Ge]=p.useState(""),rt=p.useRef(!1),ct=p.useRef(0),Et=p.useRef(0),[jt,Kt]=p.useState(!1),[xt,Yt]=p.useState([]),[qt,Pt]=p.useState([]),[At,$t]=p.useState({}),[De,on]=p.useState(!1),[dt,tn]=p.useState(!1),[ft,Un]=p.useState(!1),[an,Ys]=p.useState([]),[ss,Wr]=p.useState([]),dr=p.useRef(0),ii=p.useRef(null);ii.current||(ii.current=new fw(y=>window.setTimeout(y,40),y=>Ys(S=>S.concat(y))));const oi=p.useRef(null);oi.current||(oi.current=new fw(y=>window.setTimeout(y,40),y=>Wr(S=>S.concat(y))));const Ps=p.useRef({scanned:0,found:null}),[ue,fr]=p.useState(null),[Vi,hr]=p.useState(""),[Cr,qr]=p.useState(!1),it=p.useRef(null),[cn,Ds]=p.useState({}),[Hr,rs]=p.useState({}),[Eo,Ao]=p.useState(!1),[$o,Pn]=p.useState(""),[mr,Hn]=p.useState(!0),[Gi,ai]=p.useState(""),[$n,Fs]=p.useState(!1),[hs,Js]=p.useState(!1),[ms,da]=p.useState(6),[Ki,ln]=p.useState("standard"),[fa,uc]=p.useState(""),[To,_s]=p.useState(""),[Er,Ar]=p.useState(!1),[Yi,_r]=p.useState(!1),[Ss,pr]=p.useState("pause"),[$r,Xs]=p.useState(""),[Si,is]=p.useState(""),[Tr,ha]=p.useState(""),gr=p.useRef(null),Ji=p.useRef(null),[dc,Ni]=p.useState(!1),Zs=p.useRef(null),[$u,Qs]=p.useState(""),[Xi,er]=p.useState(""),[Mo,li]=p.useState(""),[al,ci]=p.useState(""),[B,ie]=p.useState(""),[be,Se]=p.useState(!1),[Ee,He]=p.useState("idle"),[Qe,ot]=p.useState([]),[mt,Dt]=p.useState(null),Xt=p.useRef(null),[Xn,Bt]=p.useState(!1),[un,vn]=p.useState(""),[jn,ps]=p.useState(""),[Ns,yr]=p.useState(""),[Ro,Lo]=p.useState([]),[ll,fc]=p.useState(!1),[hc,mc]=p.useState(""),[Tu,_c]=p.useState(""),[pc,gc]=p.useState(!1),[Mu,Io]=p.useState(""),If=p.useMemo(()=>{if(!Qe.length)return"";try{return JSON.stringify(Qe.map(y=>({role:y.role,content:y.content,ts:y.ts})))}catch{return"1"}},[Qe]),Ru=p.useMemo(()=>Qe.length?Ns?If!==Ns:!0:!1,[If,Qe.length,Ns]),Lu=p.useMemo(()=>Ro.map(y=>{const S=String(y.title||"").trim()||`Chat ${String(y.thread_id||"").slice(0,8)}`,M=String(y.created_at||"").trim(),D=M?M.replace("T"," ").slice(0,19):"",q=String(y.run_id||"").trim()?String(y.run_id).slice(0,8):"",H=[S,D&&`(${D})`,q&&`run ${q}`].filter(Boolean).join(" • ");return{value:String(y.thread_id||""),label:H}}),[Ro]);p.useEffect(()=>{o&&SC()},[o]),p.useEffect(()=>{if(!o)return;const y=u.current;y&&(y.token=n.gateway_auth_mode==="direct"&&n.auth_token||"")},[o,n.auth_token,n.gateway_auth_mode]);const[Iu,Ou]=p.useState([]),[Pu,nn]=p.useState(""),[yc,zm]=p.useState(""),[Du,Bm]=p.useState("all"),[Fu,Um]=p.useState("status"),[tr,Zi]=p.useState("ledger"),wc=fy(w_.md),cl=fy(`${w_.sm}, ${w_.short}`),ma=wN({is_drawer:wc,page:e}),vc=ma.open,_a=ma.set_open,[zu,Of]=hf("observe_runs"),Pf=ma.toggle_ref,pa=ma.sidebar_ref,Df=p.useRef(null),[Wm,Ff]=p.useState(()=>Fy(typeof window<"u"?window.location.hash:"")),[zf,Bu]=p.useState(""),[ga,Oo]=p.useState(""),[ya,Qi]=p.useState(""),[wa,va]=p.useState(null),[xa,ul]=p.useState({}),[Uu,ba]=p.useState(!1),[Wu,dl]=p.useState(""),[fl,qm]=p.useState(!1),[qu,Hm]=p.useState(!1),[Vr,eo]=p.useState(()=>Date.now()),[ui,Po]=p.useState(""),[Bf,hl]=p.useState({}),[Hu,Vu]=p.useState({}),ml=p.useRef([]),gs=p.useRef(null),di=p.useRef(""),to=p.useRef({}),no=p.useRef({}),xc=p.useRef({}),so=p.useRef(new Set),[wr,ja]=p.useState([]),ka=p.useRef(""),Ci=p.useRef({}),Ei=p.useRef(null),zs=p.useRef(null),ro=p.useRef(0),Do=p.useRef({}),_l=p.useRef(!1),io=p.useRef(new Set),[fi,Sa]=p.useState(""),[Mr,oo]=p.useState(""),hi=p.useRef(""),Na=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[pl,Gu]=p.useState("activity"),[bc,Nn]=p.useState([]),[jc,gl]=p.useState(0),[yl,Ku]=p.useState(0),[Yu,Ca]=p.useState({}),[kc,Fo]=p.useState({}),[Uf,Wf]=p.useState(!1),[Vm,Ju]=p.useState(""),[ao,Sc]=p.useState(""),[zo,wl]=p.useState("all"),[Ea,Nc]=p.useState(""),[Aa,qf]=p.useState([]),[Cc,Gm]=p.useState("all"),[lo,co]=p.useState("type"),[vl,$a]=p.useState("newest"),[ys,Ta]=p.useState(""),[vr,Bo]=p.useState(""),[Hf,Xu]=p.useState(""),[Gr,Uo]=p.useState(0),[Kr,Ma]=p.useState(()=>Na()),[Zu,uo]=p.useState(!1),[Ai,En]=p.useState(""),[Cn,xr]=p.useState(""),[fn,ws]=p.useState(""),[$i,Ra]=p.useState("text"),[nr,La]=p.useState(null),[Vf,xl]=p.useState(!1),[bl,jl]=p.useState(""),[mi,kl]=p.useState(""),[Qu,ed]=p.useState(""),[Gf,Ti]=p.useState(!1),[Ia,Wo]=p.useState(""),[qo,Ec]=p.useState("run_ledger"),[Rr,Lr]=p.useState(""),[Ho,Yr]=p.useState([]),[Mi,Ri]=p.useState(""),[Kf,Ac]=p.useState(!1),[td,Bs]=p.useState(""),Te=p.useMemo(()=>new F_({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]),Tt=p.useMemo(()=>new L2(Te.automations_client(),T2(Te,xs,Ct)),[Te]),br=p.useSyncExternalStore(y=>Tt.subscribe(y),()=>Tt.state),nd=m2(n.gateway_url),$c=nd?()=>{window.open(nd,"_blank","noopener,noreferrer")}:void 0;p.useEffect(()=>{e==="launch"&&pe==="automate"&&A&&Tt.load_email_status()},[e,pe,A,Tt]),p.useEffect(()=>{const y=()=>{const S=p2(window.location.hash);if(S){if(S.page==="run"){w(S.run_id),Ff(Fy(window.location.hash));return}S.page==="launch"&&ye(S.mode),t(S.page)}};return y(),window.addEventListener("hashchange",y),()=>window.removeEventListener("hashchange",y)},[]);const sd=p.useMemo(()=>{const y={};for(const S of br.items)y[S.automation_id]=S.title;return y},[br.items]),rd=p.useMemo(()=>mC(),[]),[Yf,Sl]=p.useState([]),id=p.useRef(0);function Oa(){const y=++id.current;Sl([["Gateway","checking…"]]),_C(Te).then(S=>{y===id.current&&Sl(S)})}const Pa=p.useMemo(()=>n.worker_url.trim()?new NE({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),Us=an.length?an[an.length-1].record:null,Ft=p.useMemo(()=>ra(Us),[Us]),Zn=p.useMemo(()=>{const y=C.trim();if(!U||!y||String(U.bundle_id||"").trim()&&String(U.bundle_id||"").trim()!==y)return null;const S=Array.isArray(U.entrypoints)?U.entrypoints:[];if(!S.length)return null;const M=j.trim();if(M)return S.find(q=>String(q.flow_id||"").trim()===M)||null;if(S.length===1)return S[0];const D=String(U.default_entrypoint||"").trim();return D&&S.find(q=>String(q.flow_id||"").trim()===D)||null},[U,C,j]),Tc=p.useMemo(()=>{const y=Zn==null?void 0:Zn.inputs;return Array.isArray(y)?y:[]},[Zn]),od=p.useMemo(()=>PL(wa),[wa]),_i=p.useMemo(()=>Tc.length?Tc:od,[Tc,od]),Vo=p.useMemo(()=>{const y=typeof(ue==null?void 0:ue.workflow_id)=="string"?String(ue.workflow_id):"",S=bv(y);if(S&&U&&String(U.bundle_id||"").trim()===S.bundle_id){const q=(Array.isArray(U.entrypoints)?U.entrypoints:[]).find(H=>String((H==null?void 0:H.flow_id)||"").trim()===S.flow_id);if(q&&q.node_index&&typeof q.node_index=="object")return q.node_index}const M=Zn==null?void 0:Zn.node_index;return M&&typeof M=="object"?M:{}},[ue,U,Zn]);p.useEffect(()=>{UL(n)},[n]),p.useEffect(()=>()=>{Ei.current&&Ei.current.abort(),zs.current&&zs.current.abort(),gr.current&&window.clearTimeout(gr.current),Ji.current&&window.clearTimeout(Ji.current),gs.current&&window.clearTimeout(gs.current),Zs.current&&window.clearTimeout(Zs.current)},[]);const ut=p.useMemo(()=>{const y=T.trim();if(!y)return{};try{const S=JSON.parse(y);return typeof S!="object"||S===null||Array.isArray(S)?null:S}catch{return null}},[T]),Mc=typeof(ut==null?void 0:ut.prompt)=="string"?String(ut.prompt):"",fo=typeof(ut==null?void 0:ut.provider)=="string"?String(ut.provider):"",ad=typeof(ut==null?void 0:ut.model)=="string"?String(ut.model):"",ld=typeof(ut==null?void 0:ut.workspace_root)=="string"?String(ut.workspace_root):"",Rc=typeof(ut==null?void 0:ut.workspace_access_mode)=="string"?String(ut.workspace_access_mode):"",cd=p.useMemo(()=>{const y=ut==null?void 0:ut.workspace_allowed_paths;return Array.isArray(y)?y.map(S=>String(S||"").trim()).filter(Boolean).join(`
|
|
141
|
+
`):typeof y=="string"?String(y):""},[ut]),Da=p.useMemo(()=>{const y=ut==null?void 0:ut.workspace_ignored_paths;return Array.isArray(y)?y.map(S=>String(S||"").trim()).filter(Boolean).join(`
|
|
142
|
+
`):typeof y=="string"?String(y):""},[ut]),Ir=_i.length>0&&!!C.trim(),Li=y=>{const S=String(y||"").trim().toLowerCase();return S==="object"||S==="memory"||S==="assertion"||S==="assertions"||S==="any"};p.useEffect(()=>{rs({})},[C,j]),p.useEffect(()=>{ut!==null&&Ds(y=>{const S={};for(const M of _i){if(!M||typeof M!="object")continue;const D=String(M.id||"").trim();if(!D)continue;const q=String(M.type||"").trim();if(!Li(q))continue;if(String(Hr[D]||"").trim()){S[D]=typeof y[D]=="string"?y[D]:"";continue}const V=ut==null?void 0:ut[D];V===void 0?S[D]="":S[D]=YN(V)}return S})},[_i,ut,Hr]);const Jr=Ne?{kind:"default",interface:Ne}:C.trim()&&j.trim()?{kind:"bundle",bundle_id:C.trim(),flow_id:j.trim()}:null,ud=u2(Jr),os=Array.isArray(ut==null?void 0:ut.skills)?ut.skills.map(y=>String(y||"").trim()).filter(Boolean):[],as=p.useMemo(()=>{const y={};for(const S of Ot){const M=String(S.workflow_id||"").trim(),D=String(S.label||"").trim();M&&D&&(y[M]=D)}return y},[Ot]),Nl=tx({interfaceId:null,defaultInterface:ku,request:(y,S)=>Te.get_gateway_json(y,S.signal),enabled:A,reloadKey:Ot}),Jf=p.useMemo(()=>{const y=new Set;for(const S of Array.isArray(qt)?qt:[]){const M=String((S==null?void 0:S.name)||"").trim();M&&y.add(M)}return Array.from(y).sort()},[qt]),Ii=p.useMemo(()=>{const y=[];for(const S of Array.isArray(qt)?qt:[]){const M=String((S==null?void 0:S.name)||"").trim();if(!M)continue;const D=String((S==null?void 0:S.display_name)||"").trim();y.push({name:M,display_name:D||void 0})}return y},[qt]),ho=p.useMemo(()=>{const y=new Set;for(const S of xt||[]){if(!S||typeof S!="object")continue;const M=String(S.name||"").trim();M&&y.add(M)}return Array.from(y).sort()},[xt]),Cl=p.useMemo(()=>{const y=n.maintenance_ai_provider.trim();if(!y)return{models:[],error:""};const S=At[y];return S?{models:(Array.isArray(S.models)?S.models:[]).map(D=>String(D||"").trim()).filter(Boolean),error:String(S.error||"")}:{models:[],error:""}},[At,n.maintenance_ai_provider]),Lc=n.maintenance_ai_provider.trim(),Ic=!!(Lc&&A&&!Object.prototype.hasOwnProperty.call(At,Lc));p.useEffect(()=>{const y=fo.trim();if(!y||At[y]||Ci.current[y])return;Ci.current[y]=!0;let S=!1;return(async()=>{try{const D=await Te.discovery_provider_models(y);if(S)return;const q=Array.isArray(D==null?void 0:D.models)?D.models:[],H=typeof(D==null?void 0:D.error)=="string"?String(D.error):"";$t(V=>({...V,[y]:{models:q,error:H||void 0}}))}catch(D){if(S)return;$t(q=>({...q,[y]:{models:[],error:String((D==null?void 0:D.message)||D||"Failed to load models")}}))}finally{delete Ci.current[y]}})(),()=>{S=!0}},[fo,At,Te]),p.useEffect(()=>{const y=n.maintenance_ai_provider.trim();if(!y||!A||At[y]||Ci.current[y])return;Ci.current[y]=!0;let S=!1;return(async()=>{try{const D=await Te.discovery_provider_models(y);if(S)return;const q=Array.isArray(D==null?void 0:D.models)?D.models:[],H=typeof(D==null?void 0:D.error)=="string"?String(D.error):"";$t(V=>({...V,[y]:{models:q,error:H||void 0}}))}catch(D){if(S)return;$t(q=>({...q,[y]:{models:[],error:String((D==null?void 0:D.message)||D||"Failed to load models")}}))}finally{delete Ci.current[y]}})(),()=>{S=!0}},[n.maintenance_ai_provider,At,Te,A]);function Tn(y,S){const M=String(y||"").trim();if(!M)return;let D={};try{const q=JSON.parse(T||"{}");typeof q=="object"&&q!==null&&!Array.isArray(q)&&(D=q)}catch{D={}}if(S==null){delete D[M],I(JSON.stringify(D,null,2));return}if(typeof S=="string")S?D[M]=S:delete D[M];else if(Array.isArray(S)){const q=S.map(H=>H).filter(H=>H!=null);q.length?D[M]=q:delete D[M]}else D[M]=S;I(JSON.stringify(D,null,2))}async function Fa(y){const S=String(y||"").trim();if(!S)return fe("Missing bundle_id"),null;fe(""),re(!0);try{const M=await Te.get_bundle(S);return J(M),Jt({ts:Ct(),kind:"info",title:`Loaded bundle ${S}`}),M}catch(M){return J(null),fe(String((M==null?void 0:M.message)||M||"Failed to load bundle")),null}finally{re(!1)}}function Or(y){const S=[],M=Array.isArray(y==null?void 0:y.items)?y.items:[];for(const D of M){const q=String((D==null?void 0:D.bundle_id)||"").trim();if(!q)continue;const H=Array.isArray(D==null?void 0:D.entrypoints)?D.entrypoints:[];if(H.length)for(const V of H){const ne=String((V==null?void 0:V.flow_id)||"").trim();if(!ne||(V==null?void 0:V.deprecated)===!0)continue;const Le=`${q}:${ne}`,_e=String((V==null?void 0:V.name)||"").trim(),he=_e?`${q} · ${_e}`:`${q} · ${ne}`,Ae=String((V==null?void 0:V.description)||"").trim(),ze=(Array.isArray(V==null?void 0:V.interfaces)?V.interfaces:[]).some(Ve=>String(Ve||"").trim().length>0),Ze=Array.isArray(V==null?void 0:V.agent_default_interfaces)?V.agent_default_interfaces.map(Ve=>String(Ve||"").trim()).filter(Boolean):[];S.push({workflow_id:Le,bundle_id:q,bundle_ref:String((D==null?void 0:D.bundle_ref)||"").trim(),flow_id:ne,label:he,description:Ae||void 0,has_interface:ze,agent_default_interfaces:Ze})}}return S.sort((D,q)=>D.label.localeCompare(q.label)),S}async function ls(y=Te,S){if(rt.current&&!(S!=null&&S.force))return;rt.current=!0;const M=pi.current;js(!0);try{const D=_e=>_e.map(b2).filter(he=>!!he.run_id),[q,H]=await Promise.all([y.list_runs({limit:200,root_only:!0,include_metrics:!0}),y.list_runs({limit:500,root_only:!1,include_metrics:!0})]);if(M!==pi.current)return;const V=Array.isArray(q==null?void 0:q.items)?q.items:[],ne=Array.isArray(H==null?void 0:H.items)?H.items:[],Le=D(V).filter(_e=>!String(_e.parent_run_id||"").trim()||_e.role==="occurrence");An(Le),In(D(ne).filter(_e=>!!_e.run_id)),ks(Date.now()),Et.current=0,ct.current=0}catch(D){const q=String((D==null?void 0:D.message)||D||"");if(Jt({ts:Ct(),kind:"error",title:"Refresh runs failed",preview:kt(q)}),(/\b40[13]\b/.test(q)||/unauthorized|forbidden/i.test(q))&&P.refresh().catch(()=>{}),/\b429\b/.test(q)||/too many requests/i.test(q)){const H=Math.min(12e4,Math.max(15e3,Et.current*2||15e3));Et.current=H,ct.current=Date.now()+H,Jt({ts:Ct(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(H/1e3)}s`})}}finally{rt.current=!1,js(!1)}}async function za(y){var ne,Le,_e;const S=pi.current;te(!0),$t({});const[M,,D,q,H]=await Promise.allSettled([y.list_bundles(),ls(y),y.discovery_tools(),y.discovery_providers({include_models:!1}),y.discovery_capabilities()]);if(S!==pi.current)return;if(M.status==="rejected"&&D.status==="rejected"&&q.status==="rejected"){te(!1),z(up(M.reason,n)),Jt({ts:Ct(),kind:"error",title:"Discovery failed",preview:kt(String(M.reason||""))});return}zt(H.status==="fulfilled"?j2(H.value):{available:!1,reason:`Could not read the gateway capabilities: ${String(((ne=H.reason)==null?void 0:ne.message)||H.reason)}`});let V=0;if(M.status==="fulfilled"){const he=Or(M.value);V=he.length,pn(he)}else pn([]),Jt({ts:Ct(),kind:"error",title:"Discovery bundles failed",preview:kt(String(M.reason||""))});if(D.status==="fulfilled"){const he=Array.isArray((Le=D.value)==null?void 0:Le.items)?D.value.items:[];Yt(he)}else Yt([]),Jt({ts:Ct(),kind:"error",title:"Discovery tools failed",preview:kt(String(D.reason||""))});if(q.status==="fulfilled"){const he=Array.isArray((_e=q.value)==null?void 0:_e.items)?q.value.items:[];Pt(he)}else Pt([]),Jt({ts:Ct(),kind:"error",title:"Discovery providers failed",preview:kt(String(q.reason||""))});Jt({ts:Ct(),kind:"info",title:"Gateway discovery loaded",preview:kt(`workflows: ${V}`)})}async function Xr(y){var S,M;z(""),te(!1),O(!0);try{if(!(y!=null&&y.prefer_direct)&&(await P.refresh(),El.current))return;const D=String(n.auth_token||"").trim();if(!D){y!=null&&y.open_modal_if_needed&&P.openModal();return}const q=String(n.gateway_url||"").trim();if(q){const V=q.toLowerCase();if(!V.startsWith("http://")&&!V.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(((S=window==null?void 0:window.location)==null?void 0:S.protocol)||"")==="https:"&&V.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 Le=new URL(q),_e=String(((M=window==null?void 0:window.location)==null?void 0:M.hostname)||"").trim().toLowerCase(),he=String(Le.hostname||"").trim().toLowerCase(),Ae=Oe=>Oe==="localhost"||Oe==="127.0.0.1"||Oe==="::1";if(Ae(he)&&_e&&!Ae(_e))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 F_({base_url:q,auth_token:D});await H.list_bundles(),r(V=>({...V,gateway_auth_mode:"direct"})),await za(H)}catch(D){z(up(D,n))}finally{O(!1)}}const El=p.useRef(!1),pi=p.useRef(0),Oc=p.useRef(!1);function dd(y){var M,D,q;G(y);const S=!!(y&&y.has_session&&((M=y.gateway)!=null&&M.ok));if(El.current=S,S){if(Oc.current=!1,A&&n.gateway_auth_mode==="direct")return;const H=String(((q=(D=y==null?void 0:y.gateway)==null?void 0:D.principal)==null?void 0:q.user_id)||"").trim();if(r(V=>({...V,gateway_auth_mode:"session",auth_token:"",gateway_user:H||V.gateway_user})),A&&n.gateway_auth_mode==="session")return;z(""),O(!0),za(new F_({base_url:"",auth_token:""})).catch(V=>z(up(V,n))).finally(()=>O(!1));return}y&&!y.has_session&&(n.gateway_auth_mode==="session"&&Al({keep_session:!0}),String(n.auth_token||"").trim()&&!A&&!Oc.current&&(Oc.current=!0,Xr({prefer_direct:!0})))}async function Dn(){if(!(jt||W)){Kt(!0);try{await Te.reload_bundles();const y=await Te.list_bundles(),S=Or(y);pn(S),Jt({ts:Ct(),kind:"info",title:"Bundles reloaded",preview:kt(`workflows: ${S.length}`)})}catch(y){const S=String((y==null?void 0:y.message)||y||"Bundle reload failed");Jt({ts:Ct(),kind:"error",title:"Bundle reload failed",preview:kt(S),data:{error:S}})}finally{Kt(!1)}}}async function Pc(y){if(Cr||W||!A)return;const S=y;if(S){qr(!0),nn("");try{const M=await Te.upload_bundle(S,{overwrite:!1,reload:!0});Jt({ts:Ct(),kind:"info",title:"Bundle uploaded",preview:kt(String((M==null?void 0:M.bundle_ref)||""))});const D=await Te.list_bundles(),q=Or(D);pn(q)}catch(M){const D=String((M==null?void 0:M.message)||M||"Upload failed");nn(D),Jt({ts:Ct(),kind:"error",title:"Upload .flow failed",preview:kt(D),data:{error:D}})}finally{qr(!1);try{it.current&&(it.current.value="")}catch{}}}}function Al(y){pi.current+=1,y!=null&&y.keep_session||(P.signOut().catch(()=>{}),El.current=!1),Uc(),E(""),N(""),Qi(""),J(null),fe(""),re(!1),pn([]),An([]),In([]),ks(null),On([]),Yt([]),Pt([]),$t({}),z(""),te(!1),G(null),r(S=>({...S,auth_token:""})),Jt({ts:Ct(),kind:"info",title:"Gateway disconnected"})}async function Dc(y){const S=String(y??"");S&&Qn(await xE(S)?"Copied to clipboard":wE,2)}p.useEffect(()=>{const y=c.trim();if(!De||!y)return;let S=!1;const M=async()=>{if(!(ct.current>Date.now()))try{const q=await Te.get_run(y);S||fr(q)}catch{}};M();const D=window.setInterval(M,2e3);return()=>{S=!0,window.clearInterval(D)}},[De,c,Te]),p.useEffect(()=>{if(!A)return;let y=null,S=!1,M=!1;const D=V=>{S||(y!==null&&window.clearTimeout(y),y=window.setTimeout(()=>void q(),V))},q=async()=>{if(M)return;const V=ct.current-Date.now();if(V>0){D(V+500);return}M=!0;const ne=Date.now();try{await ls(Te)}finally{M=!1;const Le=Date.now()-ne,_e=document.visibilityState==="hidden"?3e4:5e3;D(Math.max(_e,Le*3))}},H=()=>{document.visibilityState==="visible"&&q()};return q(),document.addEventListener("visibilitychange",H),()=>{S=!0,y!==null&&window.clearTimeout(y),document.removeEventListener("visibilitychange",H)}},[A,Te]);const[Fc,$l]=p.useState(null);p.useEffect(()=>{if(!A){$l(null);return}let y=!1;return(async()=>{try{const S=await Te.get_entity_phases_spec();if(y)return;const M=xL(S);if($l(M),M)try{const D=localStorage.getItem("abstractobserver_phase_graph_id_v1"),q=D?JSON.parse(D):null;q&&q.sha256&&M.sha256&&q.sha256!==M.sha256&&q.version===M.version&&Jt({ts:Ct(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:kt(`v${M.version}: ${String(q.sha256).slice(0,12)}… -> ${String(M.sha256).slice(0,12)}…`),data:{prev:q,now:{sha256:M.sha256,version:M.version}}}),localStorage.setItem("abstractobserver_phase_graph_id_v1",JSON.stringify({sha256:M.sha256,version:M.version}))}catch{}}catch(S){if(!y){$l(null);const M=String((S==null?void 0:S.message)||S||"");/404|not found/i.test(M)||Jt({ts:Ct(),kind:"info",title:"Phase-graph fetch failed — pre-wire fallback vocabulary in use (#FALLBACK)",preview:kt(M),data:{error:M}})}}})(),()=>{y=!0}},[A]),p.useEffect(()=>{if(!A){On([]),Ge("");return}let y=!1,S=null;const M=async()=>{if(!(ct.current>Date.now())){try{const D=await Te.list_entities(),q=D.entities.map(V=>String((V==null?void 0:V.name)||(V==null?void 0:V.slug)||"").trim()).filter(Boolean).slice(0,12),H=await Promise.all(q.map(async V=>{var ne,Le;try{const[_e,he]=await Promise.all([Te.get_entity_card(V),Te.get_entity_cognition(V).catch(()=>null)]),Ae=_e!=null&&_e.state&&typeof _e.state=="object"?_e.state:null,Oe=Array.isArray(_e==null?void 0:_e.moments)?_e.moments:[],ze=Oe.length?Oe[Oe.length-1]:null,Ze=(ne=he==null?void 0:he.spend)==null?void 0:ne.lifetime,Ve=(Le=he==null?void 0:he.spend)==null?void 0:Le.live_visit,rn=Array.isArray(he==null?void 0:he.warnings)?he.warnings.map(Be=>String(Be||"")).filter(Boolean):[],Rt=cL(_e);return{name:V,state:String((Ae==null?void 0:Ae.state)??(typeof(_e==null?void 0:_e.state)=="string"?_e.state:"")).trim(),age_days:typeof(_e==null?void 0:_e.age_days)=="number"?_e.age_days:null,last_moment:String((ze==null?void 0:ze.kind)||"").trim(),last_moment_at:String((ze==null?void 0:ze.at)||"").trim(),working:typeof(he==null?void 0:he.working)=="boolean"?he.working:null,tokens_total:typeof(Ze==null?void 0:Ze.tokens_total)=="number"?Ze.tokens_total:null,live_visit_tokens:typeof(Ve==null?void 0:Ve.tokens_total)=="number"?Ve.tokens_total:null,spend_warning:rn.join(" | "),live_phase:typeof(he==null?void 0:he.phase)=="string"?he.phase:"",open_questions:Rt.questions,open_questions_total:Rt.questions_total,open_problems:Rt.problems,open_problems_total:Rt.problems_total,lessons:Rt.lessons,lessons_total:Rt.lessons_total,dreams_brief:lL(_e),error:""}}catch(_e){return{name:V,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((_e==null?void 0:_e.message)||_e||"card failed")}}}));y||(On(H),je(D.entities.length),Ge(""))}catch(D){if(!y){On([]);const q=String((D==null?void 0:D.message)||D||"");Ge(/404|not found/i.test(q)?"":q)}}y||(S=window.setTimeout(()=>void M(),3e4))}};return M(),()=>{y=!0,S!==null&&window.clearTimeout(S)}},[A,Te]);async function Go(y,S,M){const D=String(S||"").trim();if(!y||!D)throw new Error("This wait has no wait_key yet — open the run to inspect.");await Te.submit_command({command_id:xs(),run_id:y,type:"resume",payload:{wait_key:D,payload:M||{}},client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Board resume submitted",preview:kt(`run ${y} · wait ${D}`),data:{run_id:y,wait_key:D}}),ls(Te,{force:!0}),window.setTimeout(()=>void ls(Te,{force:!0}),1200)}const yn=p.useMemo(()=>{const y=ue==null?void 0:ue.session_id;return typeof y=="string"?y.trim():y==null?"":String(y||"").trim()},[ue]),Mn=p.useMemo(()=>{const y=String(yn||"").trim();return y||String(K||"").trim()},[yn,K]);p.useEffect(()=>{if(!A||!Mn){ie(""),ci("");return}(async()=>{try{const y=await zL(Mn);ie(y)}catch{ie("")}})()},[A,Mn]);const Ht=IL({gateway:A?Te:null,session_id:Mn,run_id:B,on_error:ci,on_transcript:y=>{const S=String(y||"").trim();S&&(er(M=>{const D=String(M||"");return D.trim()?`${D.trimEnd()}
|
|
143
|
+
${S}`:S}),window.setTimeout(()=>{var M;return(M=Xt.current)==null?void 0:M.focus()},0))}});function zc(y,S){try{const M=URL.createObjectURL(y),D=document.createElement("a");D.href=M,D.download=S||"download",D.rel="noreferrer",document.body.appendChild(D),D.click(),document.body.removeChild(D),window.setTimeout(()=>URL.revokeObjectURL(M),5e3)}catch{}}async function Tl(){const y=ga.trim();if(!y){Qn("This run recorded no workspace folder",2);return}try{const S=await fetch(vN,{method:"POST",headers:{"Content-Type":"application/json",...nb()},body:JSON.stringify({path:y})}),M=await S.json().catch(()=>({}));S.ok&&(M!=null&&M.ok)?Qn(`Opened ${String(M.path||y)}`,2):Qn(String((M==null?void 0:M.error)||`Folder reveal failed (${S.status})`),3)}catch(S){Qn(String((S==null?void 0:S.message)||S||"Folder reveal failed"),3)}}async function Ml(y){const S=String((y==null?void 0:y.run_id)||"").trim(),M=String((y==null?void 0:y.artifact_id)||"").trim();if(!S||!M){Qn("Artifact download needs a run id",3);return}const D=Tp(y)||M;try{const q=await Te.download_run_artifact_content(S,M,{access:"preview"});zc(q,Uy(D)),Qn("Downloaded artifact",2)}catch(q){Qn(String((q==null?void 0:q.message)||q||"Download failed"),3)}}async function Km(y){const S=String((y==null?void 0:y.run_id)||"").trim(),M=String((y==null?void 0:y.artifact_id)||"").trim();if(!S||!M){Qn("Artifact preview needs a run id",3);return}const D=Tp(y),q=String((y==null?void 0:y.content_type)||"").trim().toLowerCase(),H=uf(y);if(En(D||M),xr(""),jl(""),Ra(H),La(y),uo(!0),fn&&(URL.revokeObjectURL(fn),ws("")),H==="binary"){xr(`(Binary artifact: ${q||"unknown"}; download to view.)`);return}if(H==="text"&&typeof y.size_bytes=="number"&&y.size_bytes>15e5){xr(`(Text artifact is ${y.size_bytes.toLocaleString()} bytes; download to view.)`);return}xl(!0);try{const V=await Te.download_run_artifact_content(S,M,{access:"preview"});if(H==="text"){const ne=await V.text(),Le=fm(y,ne),_e=Le==="json"?15e5:Le==="markdown"?25e4:Le==="html"?3e5:22e3;xr(ne.length>_e&&Le!=="text"?`${Yl(y.size_bytes??ne.length)} ${Le.toUpperCase()} artifact. Download to inspect it.`:ne.length>_e?`${ne.slice(0,Math.max(0,_e-1))}…`:ne)}else ws(URL.createObjectURL(V))}catch(V){jl(String((V==null?void 0:V.message)||V||"Preview failed"))}finally{xl(!1)}}p.useEffect(()=>()=>{fn&&URL.revokeObjectURL(fn)},[fn]);async function Cs(y){const S=String(y.artifact_id||"").trim(),M=String(y.run_id||"").trim(),D=uf(y);if(!M||!S)return{artifact_id:S,kind:D,render_kind:"",text:"Preview needs artifact run metadata.",url:"",loading:!1,error:""};if(D==="binary")return{artifact_id:S,kind:D,render_kind:"",text:`Preview unavailable for ${y.content_type||y.modality||"this artifact"}. Download to inspect it.`,url:"",loading:!1,error:""};if(D==="text"&&typeof y.size_bytes=="number"&&y.size_bytes>5e5)return{artifact_id:S,kind:D,render_kind:"",text:`${Yl(y.size_bytes)} text artifact. Use Preview for a larger view or Download to inspect locally.`,url:"",loading:!1,error:""};try{const q=await Te.download_run_artifact_content(M,S,{access:"preview"});if(D==="text"){const H=await q.text(),V=fm(y,H),ne=V==="json"?5e5:V==="markdown"?12e4:V==="html"?3e5:8e3;return{artifact_id:S,kind:D,render_kind:V,text:H.length>ne&&V!=="text"?`${Yl(y.size_bytes??H.length)} ${V.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:S,kind:D,render_kind:"",text:"",url:URL.createObjectURL(q),loading:!1,error:""}}catch(q){return{artifact_id:S,kind:D,render_kind:"",text:"",url:"",loading:!1,error:String((q==null?void 0:q.message)||q||"Preview failed")}}}async function fd(y){if(Kr.url&&URL.revokeObjectURL(Kr.url),!y){Ma(Na());return}const S=String(y.artifact_id||"").trim(),M=uf(y);Ma({artifact_id:S,kind:M,render_kind:"",text:"",url:"",loading:!0,error:""}),Ma(await Cs(y))}function Jt(y){const S=String(y.id||"").trim()||xs();Ou(M=>[{...y,id:S},...M].slice(0,800))}function Qn(y,S){ha(y),Ji.current&&window.clearTimeout(Ji.current),Ni(!1),window.requestAnimationFrame(()=>Ni(!0)),Ji.current=window.setTimeout(()=>{Ni(!1),Ji.current=null},1500),gr.current&&(window.clearTimeout(gr.current),gr.current=null),S>0&&(gr.current=window.setTimeout(()=>{ha(""),gr.current=null},Math.max(1,S)*1e3))}function Fn(y,S){const M=String(y||"").trim(),D=String(S||"").trim();if(!D)return"";const q=M?String(to.current[M]||"").trim():"";return q?`${q}::${D}`:D}function sr(y,S,M){const D=String(y||"").trim(),q=String(S||"").trim(),H=String(M||"").trim();if(!D||!q||!H)return;const V=Fn(D,q);V&&(to.current[H]=V,no.current[H]=D,xc.current[H]={parent_run_id:D,parent_node_id:q},so.current.has(H)||(so.current.add(H),ja(ne=>ne.includes(H)?ne:[...ne,H])))}function mo(y){const S=String(y||"").trim();if(!S)return;const M=Date.now(),D=di.current;di.current=S,eo(M),hl(q=>{const H={};for(const[_e,he]of Object.entries(q))typeof he=="number"&&he>M&&(H[_e]=he);H[S]=Math.max(H[S]||0,M+2e3),D&&D!==S&&(H[D]=Math.max(H[D]||0,M+2e3));const V=Object.keys(H);if(V.length<=200)return H;const ne=V.sort((_e,he)=>(H[he]||0)-(H[_e]||0)).slice(0,200),Le={};for(const _e of ne)Le[_e]=H[_e]||0;return Le}),Vu(q=>{if(typeof q[S]=="number")return q;const H={...q,[S]:M};if(ml.current.push(S),ml.current.length>8e3){const V=ml.current.splice(0,1500);for(const ne of V)delete H[ne]}return H}),gs.current&&window.clearTimeout(gs.current),gs.current=window.setTimeout(()=>{const q=Date.now();hl(H=>{const V={};for(const[ne,Le]of Object.entries(H))typeof Le=="number"&&Le>q&&(V[ne]=Le);return V}),eo(q),gs.current=null},2200)}function Bc(y,S){var Ve,rn,Rt;const M=String(S||"").trim()||c.trim();dr.current=y.cursor,(Ve=ii.current)==null||Ve.push({cursor:y.cursor,record:y.record}),M&&io.current.add(`${M}:${y.cursor}`);const D=Ih(y.record),q=D&&D.name?sf(D.name):"",H=y.record,V=typeof(H==null?void 0:H.node_id)=="string"?H.node_id:"",ne=typeof(H==null?void 0:H.status)=="string"?H.status:"",Le=typeof((rn=H==null?void 0:H.effect)==null?void 0:rn.type)=="string"?H.effect.type:"",_e=typeof(H==null?void 0:H.run_id)=="string"?H.run_id:"",he=_e||M;if(q==="abstract.status"&&he===M){const{text:Be,duration:bt}=ru(D==null?void 0:D.payload);Qn(Be,bt)}const Ae=V?Fn(he,V):"";if(ne==="waiting"){const Be=ra(H);if(String((Be==null?void 0:Be.reason)||"").trim()==="subworkflow"){const xn=typeof((Rt=Be==null?void 0:Be.details)==null?void 0:Rt.sub_run_id)=="string"?String(Be.details.sub_run_id):"";xn&&V&&sr(he,V,xn)}}if(V&&(mo(Fn(he,V)),ne==="waiting"||ne==="running")){const Be=Fn(he,V);Be&&(di.current=Be,Po(Be))}let Oe="step",ze=Ae||V||"(node?)",Ze="";if(D&&D.name&&cp(D.name))Oe=q==="abstract.message"?"message":"event",ze=q||D.name,Ze=kt(q==="abstract.steer_seen"?lp(D==null?void 0:D.payload):ru(D==null?void 0:D.payload).text);else if(H!=null&&H.error)Oe="error",ze="error",Ze=kt(cr(H.error,360));else if(ne==="waiting"){const Be=ra(H),bt=String((Be==null?void 0:Be.reason)||"").trim();Ze=kt(bt?`waiting • ${bt}`:"waiting")}else H!=null&&H.result?Ze=kt(cr(H.result,360)):Le?Ze=kt(Le):Ze=kt(Qh(H));Jt({id:`step:${_e||M||"?"}:${y.cursor}`,ts:String((H==null?void 0:H.ended_at)||(H==null?void 0:H.started_at)||Ct()),kind:Oe,title:ze,preview:Ze,data:H,cursor:y.cursor,run_id:_e||M||void 0,node_id:Ae||V,status:ne,effect_type:Le,emit_name:q||(D==null?void 0:D.name)||void 0})}function hd(y,S){var Ze,Ve,rn;ro.current=Math.max(ro.current,S.cursor);const M=`${y}:${S.cursor}`;if(!!io.current.has(M))return;io.current.add(M),(Ze=oi.current)==null||Ze.push({run_id:y,cursor:S.cursor,record:S.record});const q=Ih(S.record),H=q&&q.name?sf(q.name):"",V=S.record,ne=typeof(V==null?void 0:V.node_id)=="string"?V.node_id:"",Le=ne?Fn(y,ne):"",_e=typeof(V==null?void 0:V.status)=="string"?V.status:"",he=typeof((Ve=V==null?void 0:V.effect)==null?void 0:Ve.type)=="string"?V.effect.type:"";if(_e==="waiting"){const Rt=ra(V);if(String((Rt==null?void 0:Rt.reason)||"").trim()==="subworkflow"){const bt=typeof((rn=Rt==null?void 0:Rt.details)==null?void 0:rn.sub_run_id)=="string"?String(Rt.details.sub_run_id):"";bt&&ne&&sr(y,ne,bt),bt&&hi.current.trim()===String(y||"").trim()&&(hi.current=bt,oo(bt))}}if(ne&&(mo(Fn(y,ne)),_e==="waiting"||_e==="running")){const Rt=Fn(y,ne);Rt&&(di.current=Rt,Po(Rt))}if((_e==="completed"||_e==="failed")&&hi.current.trim()===String(y||"").trim()){const Rt=String(no.current[String(y||"").trim()]||"").trim();Rt&&Rt!==c.trim()?(hi.current=Rt,oo(Rt)):(hi.current="",oo(""))}if(H==="abstract.status"&&y===c.trim()){const{text:Rt,duration:Be}=ru(q==null?void 0:q.payload);Qn(Rt,Be)}let Ae="step",Oe=Le||ne||"(node?)",ze="";if(q&&q.name&&cp(q.name))Ae=H==="abstract.message"?"message":"event",Oe=`subrun • ${H||q.name}`,ze=kt(H==="abstract.steer_seen"?lp(q==null?void 0:q.payload):ru(q==null?void 0:q.payload).text);else if(V!=null&&V.error)Ae="error",Oe="error",ze=kt(cr(V.error,360));else if(_e==="waiting"){const Rt=ra(V),Be=String((Rt==null?void 0:Rt.reason)||"").trim();ze=kt(Be?`waiting • ${Be}`:"waiting")}else V!=null&&V.result?ze=kt(cr(V.result,360)):he?ze=kt(he):ze=kt(Qh(V));Jt({id:`step:${y}:${S.cursor}`,ts:String((V==null?void 0:V.ended_at)||(V==null?void 0:V.started_at)||Ct()),kind:Ae,title:Oe,preview:ze,data:V,cursor:S.cursor,run_id:y,node_id:Le||ne,status:_e,effect_type:he,emit_name:H||(q==null?void 0:q.name)||""})}function Xf(y,S){var Ve,rn,Rt;const M=String(y||"").trim();if(!M)return;const D=`${M}:${S.cursor}`;if(!!io.current.has(D))return;io.current.add(D),(Ve=oi.current)==null||Ve.push({run_id:M,cursor:S.cursor,record:S.record});const H=Ih(S.record),V=H&&H.name?sf(H.name):"",ne=S.record,Le=typeof(ne==null?void 0:ne.node_id)=="string"?ne.node_id:"",_e=Le?Fn(M,Le):"",he=typeof(ne==null?void 0:ne.status)=="string"?ne.status:"",Ae=typeof((rn=ne==null?void 0:ne.effect)==null?void 0:rn.type)=="string"?ne.effect.type:"";if(he==="waiting"){const Be=ra(ne);if(String((Be==null?void 0:Be.reason)||"").trim()==="subworkflow"){const xn=typeof((Rt=Be==null?void 0:Be.details)==null?void 0:Rt.sub_run_id)=="string"?String(Be.details.sub_run_id):"";xn&&Le&&sr(M,Le,xn)}}if(Le&&(mo(Fn(M,Le)),he==="waiting"||he==="running")){const Be=Fn(M,Le);Be&&(di.current=Be,Po(Be))}if(V==="abstract.status"&&M===c.trim()){const{text:Be,duration:bt}=ru(H==null?void 0:H.payload);Qn(Be,bt)}let Oe="step",ze=_e||Le||"(node?)",Ze="";if(H&&H.name&&cp(H.name))Oe=V==="abstract.message"?"message":"event",ze=`subrun • ${V||H.name}`,Ze=kt(V==="abstract.steer_seen"?lp(H==null?void 0:H.payload):ru(H==null?void 0:H.payload).text);else if(ne!=null&&ne.error)Oe="error",ze="error",Ze=kt(cr(ne.error,360));else if(he==="waiting"){const Be=ra(ne),bt=String((Be==null?void 0:Be.reason)||"").trim();Ze=kt(bt?`waiting • ${bt}`:"waiting")}else ne!=null&&ne.result?Ze=kt(cr(ne.result,360)):Ae?Ze=kt(Ae):Ze=kt(Qh(ne));Jt({id:`step:${M}:${S.cursor}`,ts:String((ne==null?void 0:ne.ended_at)||(ne==null?void 0:ne.started_at)||Ct()),kind:Oe,title:ze,preview:Ze,data:ne,cursor:S.cursor,run_id:M,node_id:_e||Le,status:he,effect_type:Ae,emit_name:V||(H==null?void 0:H.name)||""})}async function md(y,S){var D,q;let M=S.after;for(;;){if((D=S.signal)!=null&&D.aborted)return M;const H=await Te.get_ledger(y,{after:M,limit:200,signal:S.signal});if((q=S.signal)!=null&&q.aborted)return M;const V=Array.isArray(H.items)?H.items:[];if(!V.length)return dr.current=M,M;const ne=M;for(let Le=0;Le<V.length;Le++){const _e=V[Le];Bc({cursor:ne+Le+1,record:_e},y)}M=typeof H.next_after=="number"?H.next_after:M}}async function Rl(y){var H,V,ne,Le;const S=String(y||"").trim();nn(""),tn(!0),on(!1),(H=ii.current)==null||H.reset(),(V=oi.current)==null||V.reset(),Ps.current={scanned:0,found:null},Ys([]),dr.current=0,Wr([]),io.current=new Set,Ou([]),Bu(""),ha(""),fr(null),Qs(""),Oo(""),Po(""),di.current="",hl({}),Vu({}),ml.current=[],eo(Date.now()),to.current=S?{[S]:""}:{},no.current={},xc.current={},so.current=new Set,ja([]),ka.current="",hi.current="",oo(""),Do.current={},gs.current&&window.clearTimeout(gs.current),gs.current=null,Zs.current&&window.clearTimeout(Zs.current),Zs.current=null,Ei.current&&Ei.current.abort(),zs.current&&zs.current.abort(),zs.current=null,ro.current=0,Sa("");const M=new AbortController;Ei.current=M;let D=!1;try{let _e="",he="";try{const Ae=await Te.get_run(S);fr(Ae);const Oe=typeof(Ae==null?void 0:Ae.workflow_id)=="string"?String(Ae.workflow_id):"",ze=bv(Oe);ze&&(_e=ze.bundle_id,he=ze.flow_id)}catch{}try{const Ae=await Te.get_run_input_data(S);typeof(Ae==null?void 0:Ae.bundle_id)=="string"&&(_e=String(Ae.bundle_id||"").trim()||_e),typeof(Ae==null?void 0:Ae.flow_id)=="string"&&(he=String(Ae.flow_id||"").trim()||he);const Oe=Ae&&typeof Ae.input_data=="object"&&Ae.input_data&&!Array.isArray(Ae.input_data)?Ae.input_data:null;Oe&&I(JSON.stringify(Oe,null,2));const ze=Ae==null?void 0:Ae.workspace,Ze=typeof(ze==null?void 0:ze.workspace_root)=="string"?String(ze.workspace_root).trim():"";Oo(Ze)}catch{Oo("")}_e&&he&&(E(_e),N(he),Qi(he),await Fa(_e)),await md(S,{after:0,signal:M.signal});try{const Ae=await Te.get_run_history_bundle(S,{include_subruns:!0,include_session:!1,ledger_mode:"tail",ledger_max_items:1}),Oe=Ae&&typeof Ae=="object"?Ae.ledgers:null,Ze=(Oe&&typeof Oe=="object"?Object.keys(Oe):[]).map(Ve=>String(Ve||"").trim()).filter(Boolean).filter(Ve=>Ve!==S);if(Ze.length){for(const Ve of Ze)so.current.add(Ve);ja(Ve=>Array.from(new Set([...Ve,...Ze])));try{const Ve=typeof((ne=Oe==null?void 0:Oe[S])==null?void 0:ne.total)=="number"?Number(Oe[S].total):0;let rn="",Rt=-1;for(const Be of Ze){const bt=typeof((Le=Oe==null?void 0:Oe[Be])==null?void 0:Le.total)=="number"?Number(Oe[Be].total):0;bt>Rt&&(rn=Be,Rt=bt)}rn&&Rt>Math.max(Ve*3,Ve+20)&&(hi.current=rn,oo(rn))}catch{}}}catch{}on(!0),Jt({ts:Ct(),kind:"info",title:`Attached to run ${S}`,data:{run_id:S}}),D=!0}catch(_e){const he=String((_e==null?void 0:_e.message)||_e||"unknown error");nn(he),Jt({ts:Ct(),kind:"error",title:"Connection error",preview:kt(he),data:{error:he}}),on(!1)}finally{tn(!1)}if(!D||M.signal.aborted)return;(async()=>{let _e=250;for(;!M.signal.aborted;){try{const he=await md(S,{after:dr.current,signal:M.signal});await Te.stream_ledger(S,{after:he,on_step:Ae=>Bc(Ae,S),signal:M.signal})}catch(he){if(M.signal.aborted)break;const Ae=String((he==null?void 0:he.message)||he||"stream error");Jt({ts:Ct(),kind:"error",title:"Ledger stream error (will retry)",preview:kt(Ae),data:{error:Ae}})}if(M.signal.aborted)break;await new Promise(he=>setTimeout(he,_e)),_e=Math.min(5e3,Math.floor(_e*1.6))}})()}async function Zf(){const y=Jr,S=(y==null?void 0:y.kind)==="bundle"?y.flow_id:(y==null?void 0:y.kind)==="default"?"@default":"",M=(y==null?void 0:y.kind)==="bundle"?y.bundle_id:"";if(!y){const D="Select a workflow first (Launch → pick a workflow).";return nn(D),D}nn(""),tn(!0);try{let D={};const q=T.trim();if(q)try{if(D=JSON.parse(q),typeof D!="object"||D===null||Array.isArray(D))throw new Error("input_data must be a JSON object")}catch(he){const Ae=`Invalid input_data JSON: ${String((he==null?void 0:he.message)||he)}`;return nn(Ae),Ae}for(const[he,Ae]of Object.entries(D)){if(typeof Ae!="string")continue;const Oe=Ae.trim();Oe?D[he]=Oe:delete D[he]}const H=(_i||[]).find(he=>he&&typeof he=="object"&&he.id==="prompt"),V=H&&typeof H=="object"&&Object.prototype.hasOwnProperty.call(H,"default"),ne=D==null?void 0:D.prompt,Le=typeof ne=="string"?ne.trim():"";if(H&&!V&&!Le){const he="Missing required input_data.prompt";return nn(he),he}const _e=await Te.start_run(S,D,{...M?{bundle_id:M}:{},...y.kind==="default"?{interface:y.interface}:{},session_id:String(K||"").trim()||null});return _(_e),f(_e),hr(""),await Rl(_e),ls(),null}catch(D){const q=String((D==null?void 0:D.message)||D||"start failed");return nn(q),q}finally{tn(!1)}}async function Qf(){if(tt([]),Ke(null),!qe.available){tt([qe.reason]);return}const y=x2(We,{choice:Jr,bundle_ref_for:S=>{var M;return((M=Ot.find(D=>D.bundle_id===S))==null?void 0:M.bundle_ref)||""},input_data:ut,email_usable:Tt.email_usable},Ie.current);if(!y.ok){tt(y.errors);return}Re(!0);try{const S=await Te.automations_client().createAutomation(y.body);Ie.current.reset(),xe([]),pt(Ep),Jt({ts:Ct(),kind:"info",title:"Automation created",preview:kt(`${y.body.title} · ${S.automation_id}`)}),t("automations"),await Tt.refresh(),await Tt.select(S.automation_id)}catch(S){const M=(S&&typeof S=="object"&&typeof S.code=="string"?S:null)||{status:0,code:"client_error",message:String((S==null?void 0:S.message)||S||"Create failed")};Ke(M)}finally{Re(!1)}}async function eh(){if(hr(""),pe==="automate"){await Qf();return}const y=await Zf();if(y){hr(y);return}Zi("ledger"),t("observe")}async function _d(y){if(Tn("skills",void 0),!!y){if(y.kind==="default"){Ue(y.interface),E(""),N(""),J(null);return}Ue(""),E(y.bundle_id),N(y.flow_id),Qi(y.flow_id),await Fa(y.bundle_id)}}async function pd(y){const[S,M]=await Promise.all([Te.get_run(y),Te.get_run_input_data(y)]),D=A2(S,M);await _d(D.choice),I(JSON.stringify(D.input_data,null,2)),pt(D.form),xe([`Recreating the legacy schedule ${Qt(y,14)} as an automation. The legacy schedule keeps running until you suspend it.`,...D.notes]),Ie.current.reset(),ye("automate"),t("launch")}async function Zr(y,S){const M=String(y||"").trim();if(!M)return;if(dt){Qn(`Still attaching — retry in a moment (${Qt(M,14)})`,2500);return}nn(""),k("");const D=String((S==null?void 0:S.root_run_id)||M).trim()||M;_(D),f(M),await Rl(M)}p.useEffect(()=>{const y=String(g||"").trim();if(!y)return;let S=!1;return(async()=>{try{if(A||await Xr({open_modal_if_needed:!0}),S)return;Zi("ledger"),t("observe");const M=await Te.find_run(y);if(S)return;if(M===null){Uc(),k(y);return}await Zr(y),zl()}catch(M){S||nn(String((M==null?void 0:M.message)||M||"Failed to attach run from URL"))}finally{S||w("")}})(),()=>{S=!0}},[g]);function Uc(){var y,S;Ei.current&&Ei.current.abort(),Ei.current=null,zs.current&&zs.current.abort(),zs.current=null,ro.current=0,Sa(""),f(""),_(""),to.current={},no.current={},xc.current={},so.current=new Set,ja([]),ka.current="",hi.current="",oo(""),Do.current={},Qs(""),gs.current&&window.clearTimeout(gs.current),gs.current=null,Zs.current&&window.clearTimeout(Zs.current),Zs.current=null,on(!1),tn(!1),Un(!1),dr.current=0,(y=ii.current)==null||y.reset(),(S=oi.current)==null||S.reset(),Ps.current={scanned:0,found:null},Ys([]),Wr([]),io.current=new Set,fr(null),Ou([]),Po(""),di.current="",hl({}),Vu({}),ml.current=[],eo(Date.now()),Qn("",-1),nn(""),ot([]),Dt(null),er(""),li(""),Se(!1),Bt(!1),vn(""),ps(""),yr(""),Lo([]),fc(!1),mc(""),_c(""),gc(!1),Io("")}p.useEffect(()=>{ot([]),Dt(null),er(""),li(""),Se(!1),Bt(!1),vn(""),ps(""),yr(""),Lo([]),fc(!1),mc(""),_c(""),gc(!1),Io("")},[c]),p.useEffect(()=>{tr==="chat"&&c.trim()&&A&&Wc()},[tr,c,A,ue==null?void 0:ue.workflow_id]);async function Ll(y,S,M){const D=String(y||"").trim();if(!D)return nn("Missing run_id"),"Missing run_id";nn("");try{const q={},H=String((M==null?void 0:M.reason)||"").trim();H&&(q.reason=H),await Te.submit_command({command_id:xs(),run_id:D,type:S,payload:q,client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:`${S} submitted`,preview:H?`reason: ${H}`:"",data:{run_id:D,type:S,reason:H}});try{if(D===c.trim()){const V=await Te.get_run(D);fr(V)}}catch{}return ls(Te,{force:!0}),window.setTimeout(()=>void ls(Te,{force:!0}),900),window.setTimeout(()=>void ls(Te,{force:!0}),2400),null}catch(q){const H=String((q==null?void 0:q.message)||q||`${S} failed`);return nn(H),H}}async function Ba(y,S){return Ll(c.trim(),y,S)}async function gd(y,S="Stopped from AbstractObserver"){const M=String(y||"").trim();if(!M||!window.confirm(`Cancel run ${Qt(M,24)}?`))return;await Ll(M,"cancel",{reason:S})||Qn("Cancel submitted",2)}async function yd(){var M;const y=c.trim();if(!y){nn("Select a run first.");return}if(!A){nn("Connect to the gateway first.");return}if(ft)return;const S=String(((M=ue==null?void 0:ue.waiting)==null?void 0:M.reason)||"").trim().toLowerCase()||String(cs||"").trim().toLowerCase();if(!or||ti||_o||ei.toLowerCase()!=="waiting"||S!=="until"){nn("This run is not a scheduled wait that can be triggered now.");return}nn(""),Un(!0);try{const D={payload:{mode:"run_now",requested_at:Ct()}},q=String(Es||"").trim();q&&(D.wait_key=q),await Te.submit_command({command_id:xs(),run_id:y,type:"resume",payload:D,client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Scheduled run triggered",preview:kt(`run ${y}`),data:{run_id:y,until:Qr||null}});try{const H=await Te.get_run(y);fr(H)}catch{}}catch(D){nn(String((D==null?void 0:D.message)||D||"Failed to trigger scheduled run"))}finally{Un(!1)}}async function th(y){const S=c.trim();if(!S)return nn("Missing run_id"),"Missing run_id";if($n)return"Schedule update already in progress";const M=String(y.interval||"").trim();if(!/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.test(M)){const q="Invalid interval (expected like '20m', '1h', '0.5s', '250ms')";return ai(q),q}ai(""),nn(""),Fs(!0),tn(!0);try{await Te.submit_command({command_id:xs(),run_id:S,type:"update_schedule",payload:{interval:M,apply_immediately:y.apply_immediately!==!1},client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Schedule updated",preview:kt(`interval: ${M}`),data:{interval:M},run_id:S});try{const q=await Te.get_run(S);fr(q)}catch{}return null}catch(q){const H=String((q==null?void 0:q.message)||q||"update_schedule failed");return ai(H),nn(H),H}finally{tn(!1),Fs(!1)}}async function nh(y){const S=c.trim();if(!S)return nn("Missing run_id"),"Missing run_id";if(Er)return"Compaction already in progress";const M=typeof(y==null?void 0:y.preserve_recent)=="number"?y.preserve_recent:ms,D=Math.max(0,Math.min(500,Math.floor(Number.isFinite(M)?M:6))),q=(y==null?void 0:y.compression_mode)||Ki,H=String((y==null?void 0:y.focus)??fa??"").trim();_s(""),nn(""),Ar(!0),tn(!0);try{const V={preserve_recent:D,compression_mode:q};return H&&(V.focus=H),await Te.submit_command({command_id:xs(),run_id:S,type:"compact_memory",payload:V,client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Compaction requested",preview:kt(`mode: ${q} • preserve_recent: ${D}`),data:V,run_id:S}),null}catch(V){const ne=String((V==null?void 0:V.message)||V||"compact_memory failed");return _s(ne),nn(ne),ne}finally{tn(!1),Ar(!1)}}async function sh(){const y=c.trim();if(!y){li("Select a run first.");return}if(!A){li("Connect to the gateway first.");return}const S=Xi.trim();if(!S||be)return;if(Ht.voice_ptt_busy){ci("Wait for transcription to finish.");return}li(""),ci(""),Se(!0);const D={id:`local:${xs()}`,role:"user",content:S,ts:Ct()};ot(q=>[...q,D]),er("");try{const q=sN(Qe,D),H=n.maintenance_ai_provider.trim(),V=n.maintenance_ai_model.trim(),ne=await Te.run_chat(y,{provider:H||void 0,model:V||void 0,include_subruns:!0,messages:q}),Le=String((ne==null?void 0:ne.answer)||"").trim()||"(empty response)",_e=String((ne==null?void 0:ne.generated_at)||"").trim()||Ct();Dt((ne==null?void 0:ne.history)??null),ot(he=>[...he,{id:`local:${xs()}`,role:"assistant",content:Le,ts:_e}])}catch(q){const H=QN(q);li(H),ot(V=>[...V,{id:`local:${xs()}`,role:"assistant",content:`(error: ${H})`,ts:Ct(),local_error:!0}])}finally{Se(!1)}}function rh(y){const S=String(y.id||y.ts||"").trim(),M=String(y.content||"").trim();!S||!M||(ci(""),Ht.toggle_tts(S,M))}function wd(y){const S=String(y.id||y.ts||"").trim(),M=Ht.tts_playback;return!S||!M.key||M.key!==S?"idle":M.status}function vd(y){if(!Qe.length)return;const S=c.trim(),M=S?`Run ${S}`:"Chat",D=$S(Qe.map(q=>({role:q.role,content:q.content,ts:q.ts})),{heading:M});if(y==="download"){const q=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),H=`abstractobserver-chat-${Uy(S||"run")}-${q}.md`;TS({filename:H,text:D,mime:"text/markdown;charset=utf-8"});return}(async()=>{const q=await rc(D);He(q?"copied":"failed"),window.setTimeout(()=>He("idle"),900)})()}async function Wc(){const y=typeof(ue==null?void 0:ue.workflow_id)=="string"?String(ue.workflow_id).trim():"";if(!y){Lo([]);return}if(A&&!ll){mc(""),fc(!0);try{const S=await Te.list_runs({limit:200,workflow_id:y,root_only:!0}),M=Array.isArray(S==null?void 0:S.items)?S.items:[],D=[];for(const _e of M){const he=typeof(_e==null?void 0:_e.run_id)=="string"?String(_e.run_id).trim():"";if(!he)continue;const Ae=typeof(_e==null?void 0:_e.ledger_len)=="number"?Number(_e.ledger_len):0;D.push({run_id:he,ledger_len:Number.isFinite(Ae)?Ae:0})}if(!D.length){Lo([]);return}const q=400,H=D.map(_e=>({run_id:_e.run_id,after:Math.max(0,(_e.ledger_len||0)-q)})),V=await Te.get_ledger_batch({runs:H,limit:q}),ne=[],Le=new Set;for(const _e of D){const he=V!=null&&V.runs&&typeof V.runs=="object"?V.runs[_e.run_id]:null,Ae=Array.isArray(he==null?void 0:he.items)?he.items:[];for(const Oe of Ae){const ze=Oe==null?void 0:Oe.effect;if(!ze||typeof ze!="object"||String(ze.type||"")!=="emit_event")continue;const Ze=ze.payload;if(!Ze||typeof Ze!="object"||String(Ze.name||"")!=="abstract.chat.thread")continue;const Ve=Ze.payload;if(!Ve||typeof Ve!="object")continue;const rn=typeof Ve.thread_id=="string"?String(Ve.thread_id).trim():"";if(!rn||Le.has(rn))continue;Le.add(rn);const Rt=typeof Ve.created_at=="string"?String(Ve.created_at):"",Be=typeof Ve.title=="string"?String(Ve.title):"",bt=typeof Ve.workflow_id=="string"?String(Ve.workflow_id):y,xn=typeof Ve.run_id=="string"?String(Ve.run_id):_e.run_id,hn=typeof Ve.provider=="string"?String(Ve.provider):"",Ms=typeof Ve.model=="string"?String(Ve.model):"",ds=typeof Ve.message_count=="number"?Number(Ve.message_count):null,Dr=Ve.chat_artifact,Ka=Dr&&typeof Dr=="object"&&typeof Dr.$artifact=="string"?String(Dr.$artifact):"";Ka&&ne.push({thread_id:rn,created_at:Rt,title:Be||`Chat ${rn.slice(0,8)}`,run_id:xn,workflow_id:bt,message_count:ds,provider:hn,model:Ms,artifact_id:Ka})}}ne.sort((_e,he)=>String(he.created_at||"").localeCompare(String(_e.created_at||""))),Lo(ne)}catch(S){mc(String((S==null?void 0:S.message)||S||"Failed to load saved discussions"))}finally{fc(!1)}}}async function ih(){const y=c.trim();if(!y){vn("Select a run first.");return}if(!A){vn("Connect to the gateway first.");return}if(Qe.length&&!Xn){vn(""),Bt(!0);try{const S=n.maintenance_ai_provider.trim(),M=n.maintenance_ai_model.trim(),D=await Te.save_chat_thread(y,{provider:S||void 0,model:M||void 0,include_subruns:!0,messages:Qe.map(V=>({role:V.role,content:V.content,ts:V.ts}))}),q=typeof(D==null?void 0:D.created_at)=="string"?String(D.created_at):Ct();ps(q);try{const V=JSON.stringify(Qe.map(ne=>({role:ne.role,content:ne.content,ts:ne.ts})));yr(V)}catch{yr("1")}typeof(D==null?void 0:D.thread_id)=="string"&&String(D.thread_id).trim()&&_c(String(D.thread_id).trim());const H=!!(D!=null&&D.duplicate);Qn(H?"Already saved":"Saved discussion",2),await Wc()}catch(S){vn(String((S==null?void 0:S.message)||S||"Failed to save discussion"))}finally{Bt(!1)}}}async function Ym(){const y=String(Tu||"").trim();if(!y)return;const S=Ro.find(q=>String(q.thread_id||"").trim()===y)||null;if(!S){Io("Saved discussion not found (refresh list).");return}if(!A){Io("Connect to the gateway first.");return}if(pc)return;const M=Qe.length>0,D=(()=>{if(!M)return!1;if(!Ns)return!0;try{return JSON.stringify(Qe.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."))){Io(""),gc(!0);try{const H=await(await Te.download_run_artifact_content(S.run_id,S.artifact_id)).text(),V=JSON.parse(H),ne=Array.isArray(V==null?void 0:V.messages)?V.messages:[],Le=typeof(V==null?void 0:V.created_at)=="string"?String(V.created_at):String(S.created_at||""),_e=[];for(let he=0;he<ne.length;he++){const Ae=ne[he];if(!Ae||typeof Ae!="object")continue;const Oe=String(Ae.role||"").trim()==="assistant"?"assistant":"user",ze=typeof Ae.content=="string"?String(Ae.content):"";if(!ze.trim())continue;const Ze=typeof Ae.ts=="string"?String(Ae.ts):Le||Ct();_e.push({id:`thread:${y}:${he}`,role:Oe,content:ze.trim(),ts:Ze})}ot(_e),Dt(null),er(""),li(""),vn(""),ps(Le||"");try{const he=JSON.stringify(_e.map(Ae=>({role:Ae.role,content:Ae.content,ts:Ae.ts})));yr(he)}catch{yr("1")}Qn("Loaded discussion",2)}catch(q){Io(String((q==null?void 0:q.message)||q||"Failed to load saved discussion"))}finally{gc(!1)}}}async function Il(y){const S=c.trim(),M=String((Ft==null?void 0:Ft.wait_key)||"").trim();if(!S||!M){nn("No active wait to resume");return}if(String((Ft==null?void 0:Ft.reason)||"").trim()==="subworkflow"){nn("This run is waiting on a subworkflow; attach to the child run instead of resuming manually.");return}nn(""),Un(!0);try{await Te.submit_command({command_id:xs(),run_id:S,type:"resume",payload:{wait_key:M,payload:y||{}},client_id:"web_pwa"}),Jt({ts:Ct(),kind:"info",title:"Resume submitted",preview:kt(`wait_key: ${M}`),data:{wait_key:M,payload:y||{}}}),Qs(M);try{const D=await Te.get_run(S);fr(D)}catch{}ls(Te,{force:!0}),window.setTimeout(()=>void ls(Te,{force:!0}),900),window.setTimeout(()=>void ls(Te,{force:!0}),2400),Zs.current&&window.clearTimeout(Zs.current),Zs.current=window.setTimeout(()=>{Qs(D=>D===M?"":D)},2e3)}catch(D){nn(String((D==null?void 0:D.message)||D||"resume failed"))}finally{Un(!1)}}async function Jm(y){if(!Pa){nn("No worker configured");return}if(!ft){nn(""),Un(!0);try{const S=[];for(const M of y){const D=await Pa.call_tool(M);S.push(D)}await Il({mode:"executed",results:S})}finally{Un(!1)}}}const Ko=p.useMemo(()=>Tf(Ft),[Ft]),Es=String((Ft==null?void 0:Ft.wait_key)||"").trim(),cs=String((Ft==null?void 0:Ft.reason)||"").trim(),Qr=typeof(Ft==null?void 0:Ft.until)=="string"?String(Ft.until):"",ei=typeof(ue==null?void 0:ue.status)=="string"?String(ue.status):"",_o=!!(ue!=null&&ue.paused),ti=ei==="completed"||ei==="failed"||ei==="cancelled",Xm=cs==="until"&&!!Qr,rr=!ti&&XC(Us)&&(!!Es||Xm),xd=cs==="user",Ua=cs==="event"?sf(OL(Es)):"",oh=cs==="event"&&Ua==="abstract.ask",ah=Ko.length>0,bd=rr&&Es&&(xd||oh||ah)&&$u!==Es&&e!=="board",Oi=typeof((ar=Ft==null?void 0:Ft.details)==null?void 0:ar.sub_run_id)=="string"?String(Ft.details.sub_run_id):"",gi={run_id:c.trim(),workflow_id:typeof(ue==null?void 0:ue.workflow_id)=="string"?String(ue.workflow_id):null,status:ei,created_at:typeof(ue==null?void 0:ue.created_at)=="string"?String(ue.created_at):null,updated_at:typeof(ue==null?void 0:ue.updated_at)=="string"?String(ue.updated_at):null,session_id:typeof(ue==null?void 0:ue.session_id)=="string"?String(ue.session_id):null,current_node:typeof(ue==null?void 0:ue.current_node)=="string"?String(ue.current_node):null},qc=an.slice(-10).map(y=>{var S,M,D,q,H,V;return{cursor:y.cursor,node_id:String(((S=y.record)==null?void 0:S.node_id)||"").trim(),status:String(((M=y.record)==null?void 0:M.status)||"").trim(),effect_type:String(((q=(D=y.record)==null?void 0:D.effect)==null?void 0:q.type)||"").trim(),ts:String(((H=y.record)==null?void 0:H.ended_at)||((V=y.record)==null?void 0:V.started_at)||"").trim(),summary:Jx(y.record)}}),Hc=bg(Ft,Ko),Zm=Vx(Ft,Ko),jd=Gx(Ft,ut),Yo=jd.text,lh=jd.runtime_metadata,Ol=String((Ft==null?void 0:Ft.prompt)||"").trim(),kd=OC(ut,6),Qm=!!(Ol&&Wx(Ol)),As=!!(Ol&&!Qm),Ws=As?"Question from workflow":Yo&&Yo!==Ol?"Closest prior user request":"Request context",ch=FC(ut,T),uh=!!T.trim(),ir=ue!=null&&ue.schedule&&typeof ue.schedule=="object"?ue.schedule:null,Jo=typeof(ir==null?void 0:ir.interval)=="string"?String(ir.interval).trim():"",dh=typeof(ir==null?void 0:ir.share_context)=="boolean"?!!ir.share_context:null,Vc=typeof(ir==null?void 0:ir.repeat_count)=="number"?Number(ir.repeat_count):null,or=!!(ue!=null&&ue.is_scheduled)||!!ir,Pl=or&&!!Jo,Sd=ei==="running"&&!_o?"Pause":"Resume",Nd=or?_o?"resume":"pause":Sd==="Pause"?"pause":"resume",Cd=or?!c.trim()||dt||ft||ti:!c.trim()||dt||ft||ti||Nd==="resume"&&!_o,Ed=c.trim()?ti?"The schedule has ended.":null:"No run selected.",fh=or&&!_o&&!ti&&!dt&&!ft&&ei.toLowerCase()==="waiting"&&(String(((Qo=ue==null?void 0:ue.waiting)==null?void 0:Qo.reason)||"").trim().toLowerCase()==="until"||cs==="until")&&!!String(Qr||"").trim(),qs=(Yn=ue==null?void 0:ue.limits)==null?void 0:Yn.tokens,po=typeof(qs==null?void 0:qs.pct)=="number"?Number(qs.pct):null,hh=qs==null?void 0:qs.estimated_used,Ad=(qs==null?void 0:qs.max_input_tokens)??(qs==null?void 0:qs.max_tokens),Dl=p.useMemo(()=>{const y=Ps.current;an.length<y.scanned&&(y.scanned=0,y.found=null);for(let S=y.scanned;S<an.length;S++){const M=an[S],D=M==null?void 0:M.record;if(!D)continue;const q=Ih(D);if((q&&q.name?sf(q.name):"")!=="abstract.summary")continue;const V=q!=null&&q.payload&&typeof q.payload=="object"?q.payload:{},ne=typeof(V==null?void 0:V.text)=="string"?String(V.text):"";ne.trim()&&(y.found={cursor:M.cursor,ts:String((D==null?void 0:D.ended_at)||(D==null?void 0:D.started_at)||""),text:ne,provider:typeof(V==null?void 0:V.provider)=="string"?String(V.provider):void 0,model:typeof(V==null?void 0:V.model)=="string"?String(V.model):void 0,generated_at:typeof(V==null?void 0:V.generated_at)=="string"?String(V.generated_at):void 0,source:V==null?void 0:V.source})}return y.scanned=an.length,y.found},[an]);p.useEffect(()=>{hi.current=Mr.trim()},[Mr]),p.useEffect(()=>{const y=c.trim(),S=Oi.trim();if(!(De&&cs==="subworkflow"&&!!S&&S!==y)){ka.current="",Mr.trim()&&oo("");return}ka.current!==S&&(ka.current=S,hi.current=S,oo(S))},[De,c,cs,Oi,Mr]),p.useEffect(()=>{ul({})},[C]);const $d=p.useMemo(()=>((Array.isArray(U==null?void 0:U.entrypoints)?U==null?void 0:U.entrypoints:[])||[]).map(S=>String((S==null?void 0:S.flow_id)||"").trim()).filter(Boolean),[U]),Pr=p.useMemo(()=>{const y=String((ue==null?void 0:ue.workflow_id)||"").trim();return De&&or?y:""},[De,or,ue==null?void 0:ue.workflow_id]),Pi=p.useMemo(()=>{var V;if(!De||!c.trim()||!Pr.trim())return ui;const y=String((ue==null?void 0:ue.status)||"").trim().toLowerCase(),S=String((ue==null?void 0:ue.current_node)||"").trim();if(y!=="waiting"&&y!=="running"||!S)return ui;const M=Fn(c.trim(),S);if(!M)return ui;const D=String(cs||((V=ue==null?void 0:ue.waiting)==null?void 0:V.reason)||"").trim().toLowerCase(),q=typeof(Us==null?void 0:Us.node_id)=="string"?String(Us.node_id).trim():"",H=typeof(Us==null?void 0:Us.status)=="string"?String(Us.status).trim().toLowerCase():"";return y==="waiting"&&D==="until"||!ui.trim()||(H==="waiting"||H==="running")&&!q?M:ui},[De,c,Pr,ue==null?void 0:ue.status,ue==null?void 0:ue.current_node,(Va=ue==null?void 0:ue.waiting)==null?void 0:Va.reason,cs,ui,Us]),e_=p.useMemo(()=>{const y={},S=c.trim(),M=(D,q)=>{if(!q)return;const H=typeof(q==null?void 0:q.node_id)=="string"?String(q.node_id).trim():"";if(!H)return;const V=Fn(D,H);if(!V)return;const ne=String((q==null?void 0:q.ended_at)||(q==null?void 0:q.started_at)||"").trim(),Le=qn(ne);Le!==null&&(y[V]=Math.max(y[V]||0,Le))};for(const D of an)D&&D.record&&M(S,D.record);for(const D of ss)D&&D.record&&M(String(D.run_id||"").trim(),D.record);return y},[an,ss,c,wr]);p.useEffect(()=>{var M;if(!De||!c.trim()||!Pr.trim())return;const y=String((ue==null?void 0:ue.current_node)||"").trim();!y||String(((M=ue==null?void 0:ue.waiting)==null?void 0:M.reason)||"").trim()==="subworkflow"||mo(Fn(c.trim(),y))},[De,c,Pr,ue==null?void 0:ue.current_node,(wo=ue==null?void 0:ue.waiting)==null?void 0:wo.reason]),p.useEffect(()=>{const y=String((Zn==null?void 0:Zn.flow_id)||"").trim();y&&(ya.trim()||Qi(y))},[Zn,ya]),p.useEffect(()=>{const y=Pr.trim(),S=C.trim(),M=ya.trim();if(y){let q=!1;return ba(!0),dl(""),Te.get_workflow_flow(y).then(H=>{if(q)return;const V=H==null?void 0:H.flow;va(V&&typeof V=="object"?V:null)}).catch(H=>{q||(va(null),dl(String((H==null?void 0:H.message)||H||"Failed to load workflow flow")))}).finally(()=>{q||ba(!1)}),()=>{q=!0}}if(!S||!M){va(null),dl(""),ba(!1);return}let D=!1;return ba(!0),dl(""),Te.get_bundle_flow(S,M).then(q=>{if(D)return;const H=q==null?void 0:q.flow,V=H&&typeof H=="object"?H:null;va(V),V&&ul(ne=>({...ne,[M]:V}))}).catch(q=>{D||(va(null),dl(String((q==null?void 0:q.message)||q||"Failed to load flow")))}).finally(()=>{D||ba(!1)}),()=>{D=!0}},[Pr,C,ya,Te]),p.useEffect(()=>{const y=C.trim();if(!fl||!y||!wa)return;let S=!1;const M=3,D=_e=>{const he=Array.isArray(_e==null?void 0:_e.nodes)?_e.nodes:[],Ae=[];for(const Oe of he){const ze=Oe!=null&&Oe.data&&typeof Oe.data=="object"?Oe.data:{};if(String((ze==null?void 0:ze.nodeType)||(Oe==null?void 0:Oe.type)||"").trim()!=="subflow")continue;const Ve=(ze==null?void 0:ze.subflowId)||(ze==null?void 0:ze.flowId),rn=typeof Ve=="string"?Ve.trim():"";rn&&Ae.push(rn.includes(":")?rn.split(":",2)[1]:rn)}return Ae},q=new Set,H=new Set,V=(_e,he)=>{if(!(!_e||he>=M))for(const Ae of D(_e)){const Oe=String(Ae||"").trim();if(!Oe||q.has(Oe))continue;q.add(Oe),H.add(Oe);const ze=xa[Oe];ze&&V(ze,he+1)}};V(wa,0);const ne=Array.from(H).filter(_e=>!xa[_e]).slice(0,20);return ne.length?((async()=>{for(const _e of ne){if(S)return;try{const he=await Te.get_bundle_flow(y,_e),Ae=he==null?void 0:he.flow,Oe=Ae&&typeof Ae=="object"?Ae:null;if(!Oe)continue;ul(ze=>ze[_e]?ze:{...ze,[_e]:Oe})}catch{}}})(),()=>{S=!0}):void 0},[fl,C,wa,xa,Te]);const Td=p.useMemo(()=>{const S=(Array.isArray(U==null?void 0:U.flows)?U==null?void 0:U.flows:[]).map(M=>String(M||"").trim()).filter(Boolean);return S.length?Array.from(new Set(S)).sort():Array.from(new Set($d)).sort()},[U,$d]);p.useEffect(()=>{ti&&ui.trim()&&(Po(""),di.current="")},[ti,c,ui]),p.useEffect(()=>{const y=Mr.trim(),S=c.trim();if(!(De&&!!y&&y!==S)){zs.current&&zs.current.abort(),zs.current=null,ro.current=0,fi&&Sa("");return}if(fi===y)return;zs.current&&zs.current.abort();const D=new AbortController;zs.current=D,ro.current=0,Sa(y),Jt({ts:Ct(),kind:"info",title:`Following run ${y} (status/events)`});let q=250;return(async()=>{for(;!D.signal.aborted;){try{await Te.stream_ledger(y,{after:ro.current,on_step:V=>hd(y,V),signal:D.signal});return}catch(V){if(D.signal.aborted)break;const ne=String((V==null?void 0:V.message)||V||"stream error");Jt({ts:Ct(),kind:"error",title:"Child ledger stream error (will retry)",preview:kt(ne),data:{child_run_id:y,error:ne}})}if(D.signal.aborted)break;await new Promise(V=>setTimeout(V,q)),q=Math.min(5e3,Math.floor(q*1.6))}})(),()=>{D.abort()}},[De,Mr,c,Te,fi]),p.useEffect(()=>{if(!De||!c.trim())return;let y=!1;const S=async()=>{if(!y&&!_l.current&&wr.length&&!(ct.current>Date.now())){_l.current=!0;try{const D=wr.map(ne=>String(ne||"").trim()).filter(Boolean);if(!D.length)return;const q=D.map(ne=>({run_id:ne,after:Number(Do.current[ne]||0)})),H=await Te.get_ledger_batch({runs:q,limit:200}),V=H&&typeof H=="object"?H.runs:{};for(const ne of D){if(y)return;const Le=V&&typeof V=="object"?V[ne]:null,_e=Array.isArray(Le==null?void 0:Le.items)?Le.items:[],he=typeof(Le==null?void 0:Le.next_after)=="number"?Le.next_after:Number(Do.current[ne]||0),Ae=Number(Do.current[ne]||0);for(let Oe=0;Oe<_e.length;Oe++){const ze=_e[Oe];Xf(ne,{cursor:Ae+Oe+1,record:ze})}Do.current[ne]=he}}catch(D){if(y)return;Jt({ts:Ct(),kind:"error",title:"Subrun digest poll failed",preview:kt(String((D==null?void 0:D.message)||D||""))})}finally{_l.current=!1}}};S();const M=window.setInterval(()=>void S(),2e3);return()=>{y=!0,window.clearInterval(M),_l.current=!1}},[De,c,wr,Te]);const go=p.useMemo(()=>{const y=c.trim(),S=[];for(const M of an)!M||!M.record||S.push({run_id:y,cursor:M.cursor,record:M.record});for(const M of ss)!M||!M.record||S.push({run_id:String(M.run_id||"").trim(),cursor:M.cursor,record:M.record});return S},[an,ss,c]),Gc=p.useMemo(()=>{var S,M,D,q;const y={};for(const H of go){const V=String(H.run_id||((S=H.record)==null?void 0:S.run_id)||"").trim();!V||String(((D=(M=H.record)==null?void 0:M.effect)==null?void 0:D.type)||"").trim()!=="llm_call"||String(((q=H.record)==null?void 0:q.status)||"")!=="started"&&(y[V]=(y[V]||0)+1)}return y},[go]),mh=p.useMemo(()=>{const y=Mr.trim();if(y)return y;let S="",M=-1;for(const[D,q]of Object.entries(Gc))q>M&&(S=D,M=q);return S||c.trim()},[Gc,Mr,c]),Fl=(zf.trim()||mh).trim(),$s=p.useMemo(()=>{var q;const y=new Set,S=c.trim(),M=Mr.trim();S&&y.add(S),M&&y.add(M);for(const H of wr){const V=String(H||"").trim();V&&y.add(V)}for(const H of go){const V=String(H.run_id||((q=H.record)==null?void 0:q.run_id)||"").trim();V&&y.add(V)}const D=Array.from(y);return D.sort((H,V)=>S&&H===S&&V!==S?-1:S&&V===S&&H!==S?1:M&&H===M&&V!==M?-1:M&&V===M&&H!==M?1:H<V?-1:H>V?1:0),D},[c,Mr,wr,go]),t_=p.useMemo(()=>{var y;for(let S=an.length-1;S>=0;S--){const M=Xx((y=an[S])==null?void 0:y.record);if(M)return M}return""},[an]);function n_(y){Ff(y);const S=c.trim();if(!(!S||typeof window>"u"))try{window.history.replaceState(null,"",WN(bN(S),y))}catch{}}const Rn=p.useMemo(()=>{const y=c.trim();return y&&(gn.find(S=>String(S.run_id||"").trim()===y)||Bn.find(S=>String(S.run_id||"").trim()===y))||null},[gn,Bn,c]),Vn=String((ue==null?void 0:ue.status)||(Rn==null?void 0:Rn.status)||"").trim(),s_=String(cs||((Bl=ue==null?void 0:ue.waiting)==null?void 0:Bl.reason)||(Rn==null?void 0:Rn.waiting_reason)||"").trim().toLowerCase(),Xe=!!(ue!=null&&ue.is_scheduled||Rn!=null&&Rn.is_scheduled),Xo=!!(ue!=null&&ue.paused||Rn!=null&&Rn.paused),Kc=Xe&&Vn.toLowerCase()==="waiting",Md=Kc&&s_==="until",_h=qn(Qr),Zo=Md&&_h!==null?Wy(_h-Date.now()):"",yo=e2(ue),Wa=Xe&&Xo?"Suspended":Kc?"Scheduled":um({status:Vn,paused:Xo,stop_reason:yo});async function Rd(){if(A){Wf(!0),Ju("");try{const y=zo,S=y==="session"?String(Ea||yn||K||"").trim():"",M=y==="run"?String(ys||c||"").trim():"",D=VC(Cc),q=Aa.length?Aa.join(","):"",H=GC(vl),V=Math.max(0,Gr)*Yh,ne=await Te.search_artifacts({scope:y,session_id:S||void 0,run_id:M||void 0,query:ao||void 0,artifact_kind:q||void 0,created_after:D||void 0,include_stats:!0,limit:Yh,offset:V,order_by:H.order_by,order:H.order}),Le=[],_e=new Set;for(const Ze of Array.isArray(ne==null?void 0:ne.items)?ne.items:[]){const Ve=WC(Ze,"search");!Ve||_e.has(Ve.artifact_id)||(_e.add(Ve.artifact_id),Le.push(Ve))}const he=ne!=null&&ne.stats&&typeof ne.stats=="object"?ne.stats:{},Ae=Number((he==null?void 0:he.total)??(ne==null?void 0:ne.total)??Le.length),Oe=nw(ne);let ze=Oe;if(Aa.length)try{const Ze=await Te.search_artifacts({scope:y,session_id:S||void 0,run_id:M||void 0,query:ao||void 0,created_after:D||void 0,include_stats:!0,limit:1,offset:0,order_by:H.order_by,order:H.order});ze=nw(Ze)}catch{ze=Oe}gl(Number.isFinite(Ae)?Math.max(0,Ae):Le.length),Ku(Number((he==null?void 0:he.total_bytes)??(he==null?void 0:he.byte_total)??0)||0),Ca(Oe),Fo(ze),Nn(Le),Xu(Ze=>{var Ve;return Ze&&Le.some(rn=>rn.artifact_id===Ze)?Ze:((Ve=Le[0])==null?void 0:Ve.artifact_id)||""})}catch(y){Ju(String((y==null?void 0:y.message)||y||"Failed to load artifacts")),Nn([]),gl(0),Ku(0),Ca({}),Fo({}),Xu("")}finally{Wf(!1)}}}async function Ld(){if(A){Ti(!0),Wo("");try{const y=await Te.audit_log_tail({max_bytes:16e4}),S=typeof(y==null?void 0:y.bytes)=="number"?Number(y.bytes):0,M=!!(y!=null&&y.truncated);kl(String((y==null?void 0:y.content)||"")),ed(`${S.toLocaleString()} bytes${M?" (tail)":""}`)}catch(y){Wo(String((y==null?void 0:y.message)||y||"Failed to load audit log")),kl(""),ed("")}finally{Ti(!1)}}}async function Id(y){if(!A)return;const S=String(y||vr||ys||c||"").trim();if(!S){Yr([]),Ri(""),Bs("Select a run in Activity or Artifacts to load its runtime ledger.");return}Ac(!0),Bs("");try{const M=await Te.get_ledger(S,{after:0,limit:2e3}),D=Array.isArray(M.items)?M.items:[];Yr(D.map((H,V)=>({cursor:V+1,record:H})));const q=typeof M.next_after=="number"?Number(M.next_after):D.length;Ri(`${D.length.toLocaleString()} record${D.length===1?"":"s"}${q>=2e3?" (first 2,000)":""}`)}catch(M){Bs(String((M==null?void 0:M.message)||M||"Failed to load run ledger")),Yr([]),Ri("")}finally{Ac(!1)}}p.useEffect(()=>{A&&e==="runtime"&&Rd()},[A,e,zo,Ea,ys,ao,Aa,Cc,vl,Gr]),p.useEffect(()=>{A&&(Gf||mi||e==="runtime"&&Ld())},[A,e,tr]),p.useEffect(()=>{if(!A||e!=="runtime"||pl!=="logs"||qo!=="run_ledger"&&qo!=="provider_calls")return;const y=String(vr||ys||c||"").trim();y&&Id(y)},[A,e,pl,qo,vr,ys,c]);const yi=p.useMemo(()=>{const y=new Map;for(const S of[...Bn,...gn]){const M=String(S.run_id||"").trim();M&&y.set(M,S)}for(const S of wr){const M=String(S||"").trim();!M||y.has(M)||y.set(M,{run_id:M,workflow_id:null,status:"",created_at:null,updated_at:null,ledger_len:null,parent_run_id:no.current[M]||null,session_id:yn||null})}return c.trim()&&!y.has(c.trim())&&y.set(c.trim(),{run_id:c.trim(),workflow_id:typeof(ue==null?void 0:ue.workflow_id)=="string"?String(ue.workflow_id):null,status:typeof(ue==null?void 0:ue.status)=="string"?String(ue.status):"",created_at:typeof(ue==null?void 0:ue.created_at)=="string"?String(ue.created_at):null,updated_at:typeof(ue==null?void 0:ue.updated_at)=="string"?String(ue.updated_at):null,ledger_len:an.length||null,parent_run_id:typeof(ue==null?void 0:ue.parent_run_id)=="string"?String(ue.parent_run_id):null,session_id:typeof(ue==null?void 0:ue.session_id)=="string"?String(ue.session_id):yn||null}),Array.from(y.values()).sort((S,M)=>{const D=qn(S.updated_at||S.created_at)??0;return(qn(M.updated_at||M.created_at)??0)-D})},[gn,Bn,c,ue,an.length,wr,yn]),Od=p.useMemo(()=>EE(yi,{query:yc,filter:Du,group_by:Fu,workflow_label_by_id:as,parent_hint:y=>no.current[y]||""}),[yi,yc,Du,Fu,as]),zn=p.useMemo(()=>{const y={};for(const S of yi){const M=String(S.run_id||"").trim();M&&(y[M]=S)}return y},[yi]),jr=String(vr||ys||c||"").trim(),wi=jr&&zn[jr]||null,Pd=String(Ea||(wi==null?void 0:wi.session_id)||yn||K||"").trim(),Dd=p.useMemo(()=>bc.map(y=>mm(y,zn,as)),[bc,zn,as]);p.useEffect(()=>{Uo(0)},[ao,Aa,Cc,ys,vl,lo,zo,Ea]);const ni=Math.max(1,Math.ceil(jc/Yh)),qa=Math.min(Math.max(0,Gr),ni-1);p.useEffect(()=>{Gr!==qa&&Uo(qa)},[Gr,qa]);const Ts=p.useMemo(()=>Dd,[Dd,qa]),r_=p.useMemo(()=>{const y={};for(const S of Ts){const M=lo==="type"?Rp(S,zn,as):qC(S,lo);y[M]||(y[M]=[]),y[M].push(S)}return Object.entries(y).map(([S,M])=>({key:S,items:M})).sort((S,M)=>{var D,q;if(lo==="time"){const H=qn((D=S.items[0])==null?void 0:D.created_at)??0,V=qn((q=M.items[0])==null?void 0:q.created_at)??0;if(H!==V)return V-H}return S.key.localeCompare(M.key)})},[Ts,lo,zn,as]),Ha=p.useMemo(()=>{const y=Hf.trim();return y?Ts.find(S=>S.artifact_id===y)||Ts[0]||null:Ts[0]||null},[Ts,Hf]);p.useEffect(()=>{e!=="runtime"||pl!=="artifacts"||fd(Ha)},[e,pl,Ha==null?void 0:Ha.artifact_id]),p.useEffect(()=>()=>{Kr.url&&URL.revokeObjectURL(Kr.url)},[Kr.url]);const ph=p.useMemo(()=>yi.filter(y=>ju(y.status)),[yi]);p.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!A||X)return;let y=!1;return(async()=>{const[S,M]=await Promise.all([Te.list_skills(),Te.list_mcp_servers()]);y||(Z(S),ge(M),Q(!0))})(),()=>{y=!0}},[e,A,X]);function zl(){cl&&window.setTimeout(()=>{var y;return(y=Df.current)==null?void 0:y.scrollIntoView({block:"start"})},60)}function Yc(y){Zi(y),zl()}const i_=[{id:"board",label:"Board",icon:s.jsx(et,{name:"board",size:16})},{id:"observe",label:"Observe",icon:s.jsx(et,{name:"history",size:16})},{id:"runtime",label:"System",icon:s.jsx(et,{name:"server",size:16})},{id:"launch",label:"Launch",icon:s.jsx(et,{name:"send",size:16})},{id:"automations",label:"Automations",icon:s.jsx(et,{name:"refresh",size:16})}],Jc={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},Xc=s.jsxs(s.Fragment,{children:[Jr?s.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",os.length?` · ${os.length} skill${os.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(y=>{var q;const S=os.includes(y.name),M=y.blocked===!0,D=y.requires_review===!0&&!M;return s.jsxs("label",{className:`launch_skill_row ${M?"is_blocked":""} ${S?"is_on":""}`,title:[y.description||"",y.tree_hash?`tree ${y.tree_hash.slice(0,16)}…`:"",M&&((q=y.reasons)!=null&&q.length)?`blocked: ${y.reasons.join("; ")}`:""].filter(Boolean).join(`
|
|
144
|
+
`),children:[s.jsx("input",{type:"checkbox",checked:S,disabled:M||dt||ft||ke,onChange:H=>{const V=H.target.checked?Array.from(new Set([...os,y.name])):os.filter(ne=>ne!==y.name);Tn("skills",V.length?V:void 0)}}),s.jsx("span",{className:"launch_skill_name",children:y.name}),y.trust_level?s.jsx("span",{className:`chip ${M?"danger":D?"warn":"muted"}`,children:M?"blocked":D?"review":y.trust_level}):null,y.description?s.jsx("span",{className:"launch_skill_desc",children:y.description}):null]},y.name)})}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"The gateway's skills shelf is empty."}),os.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:ld,onChange:y=>Tn("workspace_root",y.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:(Rc||"workspace_only").trim()||"workspace_only",onChange:y=>Tn("workspace_access_mode",y.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."})]})]}),(Rc||"").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:cd,onChange:y=>Tn("workspace_allowed_paths",y.target.value),placeholder:`/path/to/project
|
|
145
|
+
/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:Da,onChange:y=>Tn("workspace_ignored_paths",y.target.value),placeholder:`node_modules
|
|
146
|
+
runtime
|
|
147
|
+
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:y=>{const S=y.target.files&&y.target.files.length?y.target.files[0]:null;S&&Pc(S)}}),s.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var y;return(y=it.current)==null?void 0:y.click()},disabled:!A||W||Cr||dt||ft,title:"Upload a .flow bundle",children:Cr?"…":"Upload .flow"}),s.jsxs("button",{type:"button",className:"btn launch_btn_reload",onClick:()=>void Dn(),disabled:!A||W||jt||dt||ft,title:"Reload picks up server-side edits",children:[s.jsx(et,{name:"refresh",size:14}),jt?"…":"Reload bundles"]})]})]})]});function kr(y){t("observe"),Zi("ledger"),Zr(y)}const sn={on_select:y=>void Tt.select(y),on_row_action:(y,S)=>{if(S==="discuss"||S==="edit")throw new Error(`${S} is routed by AutomationsPage (route_row_action), not the app handlers.`);if(S==="archive"){Tt.ask_archive(y.automation_id);return}Tt.row_action(y,S)},on_legacy_action:(y,S)=>{if(S==="open_run"){kr(y.automation_id);return}if(S==="recreate"){pd(y.automation_id).catch(M=>Tt.report_error(M));return}Tt.legacy_action(y,S)},on_confirm_archive:y=>void Tt.row_action(y,"archive"),on_cancel_archive:()=>Tt.ask_archive(""),on_status_filter:y=>void Tt.set_status_filter(y),on_refresh:()=>void Tt.refresh(),on_new:()=>{ye("automate"),t("launch")},on_show_archived:y=>Tt.set_show_archived(y)};return s.jsxs("div",{className:`app-shell shell${vc?" nav_open":""}`,children:[wc&&vc?s.jsx("div",{className:"shell_nav_backdrop","aria-hidden":"true",onClick:()=>_a(!1)}):null,s.jsxs("aside",{className:"shell_sidebar",id:"shell_nav",ref:pa,...ma.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:()=>_a(!1),children:s.jsx(et,{name:"x",size:16})})]}),s.jsxs("nav",{className:"shell_nav",children:[i_.map(y=>s.jsxs("button",{className:`shell_nav_item ${e===y.id?"active":""}`,onClick:()=>{t(y.id),_a(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:y.icon}),s.jsx("span",{className:"shell_nav_label",children:y.label})]},y.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(et,{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"),_a(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(et,{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:A?"Gateway connected":W?"Gateway: connecting…":"Gateway: signed out",children:[s.jsx("span",{className:`gateway_led ${A?"ok":W?"warn":"err"}`,"aria-hidden":"true"}),s.jsx("span",{className:`shell_connection_label ${A&&((Ga=(Zc=F==null?void 0:F.gateway)==null?void 0:Zc.principal)!=null&&Ga.user_id)?"mono":""}`,children:A?((Qc=(Hs=F==null?void 0:F.gateway)==null?void 0:Hs.principal)==null?void 0:Qc.user_id)||(n.gateway_auth_mode==="direct"?"direct dev":"connected"):W?"connecting…":"signed out"})]})})]}),s.jsxs("div",{className:"shell_main",...ma.attrs.main,children:[s.jsxs("header",{className:"shell_header",children:[s.jsx("button",{ref:Pf,type:"button",className:"shell_nav_toggle","data-nav-toggle":!0,"aria-label":"Open navigation","aria-controls":"shell_nav","aria-expanded":vc,title:"Navigation",onClick:()=>_a(!0),children:s.jsx(et,{name:"list",size:18})}),s.jsx("div",{className:"shell_header_title",children:Jc[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(Xj,{assistant:{open:Sn,onToggle:()=>ns(y=>!y),label:"Observer assistant (docs-grounded)"},appearance:{onOpen:()=>It(!0)},about:{identity:rd,extraRows:Yf,onOpen:Oa},connection:{phase:P.phase,signingOut:P.signingOut,onConnect:()=>P.openModal(),onDisconnect:()=>Al()}})]})]}),s.jsx(Ej,{...P.modalProps}),s.jsx(tk,{open:Wt,onClose:()=>It(!1),value:en,onChange:bn}),s.jsx(hN,{open:Sn,onClose:()=>ns(!1),connected:A,topOffset:44,gateway:Te}),s.jsxs("div",{className:"app-body shell_content",children:[e==="board"?A?s.jsx($L,{gateway_connected:A,runs:Bn,all_runs:gn,runs_refreshed_at:Kn,entities:Nr,entities_total:ae,entities_error:Ye,refreshing:wn,on_refresh:()=>void ls(Te,{force:!0}),on_open_run:y=>{t("observe"),Zi("ledger"),Zr(y)},on_resume_wait:Go,on_open_automation:y=>{t("automations"),Tt.refresh().then(()=>Tt.select(y))},entity_app_href:l,on_read_diary:(y,S)=>Te.read_entity_diary_entry(y,S),phase_graph:Fc}):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:()=>P.openModal(),disabled:W,children:W?"Connecting…":"Sign in"}),s.jsx("button",{className:"btn",onClick:()=>void Xr({open_modal_if_needed:!0}),disabled:W,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 ${A?"ok":"warn"}`,children:Av(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:()=>P.openModal(),children:"Manage connection…"}),A?s.jsx("button",{className:"btn",onClick:()=>Al(),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(aC,{checked:n.auto_connect_gateway,onChange:y=>r(S=>({...S,auto_connect_gateway:y}))})}),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:y=>r(S=>({...S,gateway_url:y.target.value})),placeholder:Sm})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Dev bearer token"}),s.jsx("input",{type:"password",value:n.auth_token,onChange:y=>r(S=>({...S,auth_token:y.target.value,gateway_auth_mode:"direct"})),placeholder:"development only — prefer the sign-in dialog"})]}),s.jsx("button",{className:"btn",onClick:()=>void Xr({prefer_direct:!0}),disabled:W,children:W?"Connecting…":"Connect directly"})]})]})]}),s.jsxs("section",{className:"pane",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Assistant"}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:"chip muted",children:"docs Q&A + run Ask"})]}),s.jsxs("div",{className:"pane_body settings_body",children:[s.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"The model answering the header assistant and the run page's Ask tab. Blank fields follow the gateway defaults."}),s.jsx(mj,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:Ii,models:Cl.models,loadingProviders:W,loadingModels:Ic,modelError:Lc?Cl.error:"",allowCustomProvider:!0,allowCustomModel:!0,allowGatewayDefault:!0,gatewayDefaultLabel:"(gateway default)",onChange:y=>r(S=>({...S,maintenance_ai_provider:y.provider,maintenance_ai_model:y.model}))}),s.jsx("div",{className:"settings_subhead",children:"Skills"}),R===null?s.jsx("div",{className:"settings_row_help",children:A?X?"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(y=>{const S=n.assistant_skill_names.includes(y.name);return s.jsx(lC,{name:y.name,version:y.version,description:y.description,checked:S,onChange:M=>r(D=>({...D,assistant_skill_names:M?Array.from(new Set([...D.assistant_skill_names,y.name])):D.assistant_skill_names.filter(q=>q!==y.name)}))},y.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:y=>r(S=>({...S,worker_url:y.target.value})),placeholder:"https://your-mcp-worker-endpoint"}),s.jsx("input",{className:"mono",type:"password",value:n.worker_token,onChange:y=>r(S=>({...S,worker_token:y.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(O2,{mode:pe,automate_available:qe.available,automate_reason:qe.reason,on_change:ye}),pe==="automate"&&!qe.available&&A?s.jsx("div",{className:"warn_callout",role:"note",children:qe.reason}):null,pe==="automate"&&ht.length?s.jsx("div",{className:"help_text",role:"note",children:ht.map(y=>s.jsx("div",{children:y},y))}):null,A?null:s.jsxs("div",{className:"warn_callout",children:["Not connected."," ",s.jsx("button",{className:"btn primary",onClick:()=>P.openModal(),children:"Sign in"})," ","to launch workflows on this gateway."]}),pe==="automate"?s.jsx("div",{className:"section_title",children:"What"}):null,s.jsx("div",{className:"launch_workflow_bar",children:s.jsx(kS,{id:"launch-workflow-picker",className:"launch_workflow_picker",interfaceId:null,defaultInterface:ku,ariaLabel:"Workflow",workflows:Nl,value:Hy(Jr,((ea=Nl.data)==null?void 0:ea.entries)??[]),currentLabel:Jr&&!Hy(Jr,((vi=Nl.data)==null?void 0:vi.entries)??[])?{name:as[ud]||ud}:null,unavailableReason:A?W?"Loading workflows…":null:"Sign in to load workflows.",onChange:(y,S)=>{const M=c2(y,S);M&&_d(M)}})}),s.jsxs("div",{className:"field",children:[Zn!=null&&Zn.description?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(Zn.description)}):null,Y?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading workflow…"}):null,ce?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:ce}):null]}),s.jsx("div",{className:"section_divider"}),s.jsx("div",{className:"section_title",children:"Inputs"}),Jr?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:Ct()})]}),s.jsx("div",{className:"body mono",children:"Invalid input JSON — reselect the workflow to reset its inputs."})]}):Ir?s.jsx("div",{className:"launch_inputs",children:(()=>{const y=dt||ft,S=[],M=[];for(const H of _i){if(!H||typeof H!="object")continue;const V=String(H.id||"").trim();if(!V||pe==="automate"&&Rx.includes(V))continue;const ne=String(H.type||"").trim().toLowerCase();ne==="tools"||ne==="skills"||ne==="mcp"||ne==="mcp_servers"||V==="skills"||V==="mcp"||V==="mcp_servers"||ne==="array"||Li(ne)||V==="prompt"||V==="system"?S.push(H):M.push(H)}const D=H=>String(H||"").trim().replace(/_/g," ").replace(/\b\w/g,V=>V.toUpperCase()),q=(H,V)=>{const ne=String(H.id||"").trim();if(!ne)return null;const Le=String(H.label||ne).trim()||ne,_e=Le===ne?D(ne):Le,he=String(H.type||"").trim().toLowerCase(),Ae=Object.prototype.hasOwnProperty.call(H,"default"),Oe=Ae?H.default:void 0,ze=Ae?typeof Oe=="string"?Oe:cr(Oe,80):"",Ze=ut==null?void 0:ut[ne],Ve=Ae?`${ze}`:"";if(he==="tools"){const Be=Array.isArray(Ze)?Ze.map(hn=>String(hn||"").trim()).filter(Boolean):[],bt=Array.isArray(Oe)?Oe.map(hn=>String(hn||"").trim()).filter(Boolean):[],xn=Array.from(new Set([...ho,...Be,...bt])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsx(xv,{options:xn,value:Be,disabled:y,placeholder:"(no tools selected)",onChange:hn=>Tn(ne,hn)})]},ne)}if(he==="skills"||ne==="skills")return null;if(he==="mcp"||he==="mcp_servers"||ne==="mcp"||ne==="mcp_servers"){const Be=Array.isArray(Ze)?Ze.map(hn=>String(hn||"").trim()).filter(Boolean):[];if(le===null&&!Be.length)return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:_e}),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 bt=(le||[]).map(hn=>hn.name),xn=Array.from(new Set([...bt,...Be])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsx(xv,{options:xn,value:Be,disabled:y,placeholder:"(no MCP servers selected)",onChange:hn=>Tn(ne,hn)})]},ne)}if(he==="provider"||he==="provider_text"){const Be=typeof Ze=="string"?String(Ze):"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsxs("select",{value:Be,onChange:bt=>Tn(ne,bt.target.value),disabled:y,children:[s.jsx("option",{value:"",children:Ve||"(select)"}),Jf.map(bt=>s.jsx("option",{value:bt,children:bt},bt))]})]},ne)}if(he==="model"||he==="model_text"){const Be=typeof Ze=="string"?String(Ze):"",bt=String((ut==null?void 0:ut.provider)||"").trim(),xn=bt?At[bt]:void 0,hn=xn&&Array.isArray(xn.models)?xn.models.map(Ms=>String(Ms||"").trim()).filter(Boolean):[];return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:_e}),hn.length?s.jsxs("select",{value:Be,onChange:Ms=>Tn(ne,Ms.target.value),disabled:y,children:[s.jsx("option",{value:"",children:Ve||"(select)"}),hn.map(Ms=>s.jsx("option",{value:Ms,children:Ms},Ms))]}):s.jsx("input",{value:Be,onChange:Ms=>Tn(ne,Ms.target.value),placeholder:Ve||"model id",disabled:y})]},ne)}if(he==="boolean"){const Be=typeof Ze=="boolean"?Ze?"true":"false":"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsxs("select",{value:Be,onChange:bt=>{const xn=String(bt.target.value||"").trim();xn?Tn(ne,xn==="true"):Tn(ne,void 0)},disabled:y,children:[s.jsx("option",{value:"",children:Ve||"(default)"}),s.jsx("option",{value:"true",children:"Yes"}),s.jsx("option",{value:"false",children:"No"})]})]},ne)}if(he==="number"){const Be=typeof Ze=="number"&&Number.isFinite(Ze)?String(Ze):"";return s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsx("input",{type:"number",value:Be,onChange:bt=>{const xn=String(bt.target.value||"").trim();if(!xn){Tn(ne,void 0);return}const hn=Number(xn);Number.isFinite(hn)&&Tn(ne,hn)},placeholder:Ve,disabled:y})]},ne)}if(he==="array"){const Be=Array.isArray(Ze)?Ze.map(bt=>String(bt||"").trim()).filter(Boolean).join(`
|
|
148
|
+
`):"";return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsx("textarea",{className:"mono",value:Be,onChange:bt=>{const xn=String(bt.target.value||"").split(/\r?\n/g).map(hn=>String(hn||"").trim()).filter(Boolean);Tn(ne,xn.length?xn:void 0)},placeholder:Ve||"(one item per line)",rows:2,disabled:y})]},ne)}if(Li(he)){const Be=typeof cn[ne]=="string"?cn[ne]:"",bt=String(Hr[ne]||"").trim();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsxs("label",{className:"launch_label",children:[_e," ",s.jsx("span",{className:"launch_label_type",children:he})]}),s.jsx("textarea",{className:"mono",value:Be,onChange:xn=>{const hn=String(xn.target.value??"");Ds(ds=>({...ds,[ne]:hn}));const Ms=hn.trim();if(!Ms){rs(ds=>{const Dr={...ds};return delete Dr[ne],Dr}),Tn(ne,void 0);return}try{const ds=JSON.parse(Ms);rs(Dr=>{const Ka={...Dr};return delete Ka[ne],Ka}),Tn(ne,ds)}catch(ds){rs(Dr=>({...Dr,[ne]:String((ds==null?void 0:ds.message)||ds||"Invalid JSON")}))}},placeholder:Ve||"{...}",rows:3,disabled:y}),bt?s.jsx("div",{className:"launch_field_error",children:bt}):null]},ne)}const rn=typeof Ze=="string"?String(Ze):"";return ne==="prompt"||ne==="system"?s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsx("textarea",{value:rn,onChange:Be=>Tn(ne,Be.target.value),placeholder:Ve||(ne==="prompt"?"What should the agent do?":"System instructions (optional)"),rows:3,disabled:y})]},ne):s.jsxs("div",{className:V||"launch_field",children:[s.jsx("label",{className:"launch_label",children:_e}),s.jsx("input",{value:rn,onChange:Be=>Tn(ne,Be.target.value),placeholder:Ve,disabled:y})]},ne)};return S.sort((H,V)=>{const ne={system:0,prompt:1,tools:2};return(ne[String(H.id||"")]??10)-(ne[String(V.id||"")]??10)}),s.jsxs(s.Fragment,{children:[S.map(H=>q(H)),M.length>0?s.jsx("div",{className:"launch_grid",children:M.map(H=>q(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:Mc,onChange:y=>Tn("prompt",y.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:fo,onChange:y=>Tn("provider",y.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:ad,onChange:y=>Tn("model",y.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."}),pe==="automate"?s.jsxs(s.Fragment,{children:[s.jsx(P2,{form:We,email_status:br.email_status,on_open_my_email:$c,tools:Array.isArray(ut==null?void 0:ut.tools)?ut.tools.map(y=>String(y)):void 0,disabled:ke,on_change:y=>pt(S=>({...S,...y}))}),s.jsxs("details",{className:"launch_advanced",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Advanced",os.length?` · ${os.length} skill${os.length===1?"":"s"}`:""]}),s.jsx(D2,{form:We,disabled:ke,on_change:y=>pt(S=>({...S,...y}))}),Xc]})]}):Xc,s.jsx("div",{className:"section_divider"}),Vi?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:Vi})]}):null,pe==="automate"&&Fe.length?s.jsx("ul",{className:"automate_errors",role:"alert",children:Fe.map(y=>s.jsx("li",{children:y},y))}):null,pe==="automate"&<?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:am(lt).title})," ",am(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 y=pe==="automate",S=A?Jr?ut===null?"Inputs contain invalid JSON":y&&!qe.available?"Automations unavailable on this gateway":dt||ft?"Attaching to a run…":W||Y?"Loading…":ke?"Submitting…":"":"Select a workflow":"Sign in first";return s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"launch_submit_btn",onClick:()=>void eh(),disabled:!!S,title:S,children:y?ke?"Creating…":"Create automation":dt?"Launching…":"Launch now"}),S&&!ke&&!dt?s.jsx("span",{className:"mono muted launch_disabled_reason",children:S}):null]})})()})]})})}):null,e==="automations"?s.jsx(oC,{ctl:Tt,gateway:Te,active:e==="automations"&&A,available:qe,h:sn,host:{on_open_run:y=>kr(y),...$c?{on_open_my_email:$c}:{},on_open_session:(y,S)=>{Jt({ts:Ct(),kind:"info",title:"Discussion started",preview:kt(S),data:y})}}}):null,e==="runtime"?s.jsx(mE,{gateway_connected:A,tab:pl,runs:yi,active_runs:ph,all_artifacts:bc,artifacts:Ts,artifact_total_count:jc,artifact_total_bytes:yl,artifact_facets:Yu,artifact_type_facets:kc,artifact_page:qa,artifact_page_size:Yh,artifact_groups:r_,selected_artifact:Ha,embedded_preview:Kr,loading:Uf,error:Vm,query:ao,scope:zo,type_filters:Aa,date_filter:Cc,group_by:lo,sort_by:vl,artifact_run_filter:ys,audit_log_text:mi,audit_log_meta:Qu,audit_log_loading:Gf,audit_log_error:Ia,workflow_label_by_id:as,run_by_id:zn,selected_run_id:jr,session_id:Pd,runtime_log_source:qo,runtime_log_query:Rr,runtime_ledger_log_items:Ho,runtime_ledger_log_meta:Mi,runtime_ledger_log_loading:Kf,runtime_ledger_log_error:td,on_tab_change:Gu,on_query_change:Sc,on_scope_change:wl,on_session_filter_change:Nc,on_type_filters_change:qf,on_date_filter_change:Gm,on_group_by_change:co,on_sort_by_change:$a,on_artifact_page_change:Uo,on_artifact_run_filter_change:y=>{const S=String(y||"").trim();Ta(S),S&&Bo(S),S&&zo!=="run"&&wl("run")},on_refresh_artifacts:()=>void Rd(),on_refresh_audit:()=>void Ld(),on_refresh_runtime_ledger:y=>void Id(y),on_runtime_log_source_change:Ec,on_runtime_log_query_change:Lr,on_select_run:y=>{const S=String(y||"").trim();Bo(S);const M=S&&zn[S]||null,D=String((M==null?void 0:M.session_id)||"").trim();D&&Nc(D)},on_select_artifact:Xu,on_preview_artifact:y=>void Km(y),on_download_artifact:y=>void Ml(y),on_open_run:y=>{Bo(String(y||"").trim()),t("observe"),Zi("ledger"),Zr(y)},on_open_ledger:y=>{Bo(String(y||"").trim()),t("observe"),Zi("ledger"),Zr(y)},on_refresh_runs:()=>void ls(Te,{force:!0}),on_reconnect:()=>void Xr({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:A?s.jsx(aL,{gateway:Te,selected_run_id:vr,selected_session_id:Pd}):null}):null,e==="observe"?s.jsx("div",{className:"page observe_page",children:s.jsxs("div",{className:`observatory_layout${zu?"":" list_collapsed"}`,children:[s.jsx(pE,{sections:Od,selected_run_id:c,root_run_id:m,search:yc,filter:Du,group_by:Fu,loading:wn,connected:A,on_sign_in:()=>P.openModal(),total_runs:yi.length,workflow_label_by_id:as,automation_titles:sd,on_search:zm,on_filter:Bm,on_group_by:Um,on_refresh:()=>void ls(),on_select:(y,S)=>{Zr(y,{root_run_id:S||y}),zl()},list:{open:zu,on_toggle:Of}}),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:as[String((Rn==null?void 0:Rn.workflow_id)||"")]||String((Rn==null?void 0:Rn.workflow_id)||"").trim()||Qt(c.trim(),22)}),s.jsx("span",{className:"chip mono muted",children:Qt(c.trim(),14)}),s.jsx("span",{className:`chip ${oc(Wa||Vn,yo)}`,title:String((yo==null?void 0:yo.headline)||""),children:Wa||Vn||"unknown"})]}):x?s.jsx("span",{className:"observe_run_identity_empty observe_run_link_missing",role:"alert",children:jN(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:[or?s.jsx(uC,{active:!_o,unavailableReason:Ed,busy:dt||ft,onChange:y=>{if(!y){pr("pause"),Xs(""),is(""),_r(!0);return}Ba("resume")}}):s.jsx("button",{className:"btn",onClick:()=>{if(Nd==="pause"){pr("pause"),Xs(""),is(""),_r(!0);return}Ba("resume")},disabled:Cd,children:Sd}),fh?s.jsx("button",{className:"btn primary",onClick:()=>void yd(),disabled:dt||ft||ti||_o,children:"Run now"}):null,s.jsx("button",{className:"btn danger",onClick:()=>{pr("cancel"),Xs(""),is(""),_r(!0)},disabled:dt||ft||ti,children:"Cancel"}),s.jsx("button",{className:"btn btn_icon",onClick:Uc,title:"Clear the run view",children:s.jsx(et,{name:"x",size:14})})]}):null]}),c.trim()&&!ti?s.jsx("div",{className:"observe_steer_row",children:s.jsx(Pj,{runId:c.trim(),parked:rr,submit:(y,S)=>Te.submit_command({command_id:`steer-${xs()}`,run_id:y,type:"inject_guidance",payload:{guidance:S},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:()=>Jt({ts:Ct(),kind:"info",title:"Steer queued",preview:"inject_guidance submitted — delivery shows as abstract.steer_seen in the ledger"})})}):null,rr||or||Pu?s.jsxs("div",{className:"observe_toolbar_context",children:[rr?s.jsxs("div",{className:"observe_context_card info",children:[s.jsxs("div",{className:"observe_context_label",children:[(()=>{const y=or?_o?"suspended":"scheduled":"waiting";return s.jsx("span",{className:`chip ${oc(y)}`,children:y})})(),s.jsx("span",{className:"muted",children:cs||"unknown"})]}),s.jsxs("div",{className:"observe_context_body",children:[Es?s.jsxs("span",{className:"mono",title:Es,children:[s.jsx("span",{className:"muted",children:"wait_key"}),": ",Qt(Es,46)]}):null,cs==="event"&&Ua?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"event"}),": ",Ua]}):null,cs==="subworkflow"&&Oi?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"child"}),": ",Qt(Oi,18)]}):null,cs==="until"&&Qr?s.jsxs("span",{className:"mono",title:Qr,children:[s.jsx("span",{className:"muted",children:"until"}),": ",Qt(Qr,46)]}):null,cs==="until"&&Qr?s.jsx("span",{className:"mono muted",children:(()=>{const y=qn(Qr),S=y!==null?new Date(y).toLocaleString():Qr,M=y!==null?Wy(y-Date.now()):"";return`Next at ${S}${M?` (in ${M})`:""}`})()}):null]}),cs==="subworkflow"&&Oi?s.jsxs("div",{className:"observe_context_actions",children:[s.jsx("button",{className:"btn primary",onClick:async()=>{f(Oi),await Rl(Oi)},disabled:dt,children:"Attach to child"}),m.trim()&&m.trim()!==c.trim()?s.jsx("button",{className:"btn",onClick:async()=>{f(m.trim()),await Rl(m.trim())},disabled:dt,children:"Back to root"}):null]}):null]}):null,or?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:Pl?`every ${Jo}`:"once"})]}),s.jsxs("div",{className:"observe_context_body",children:[Jo?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"interval"}),": ",Jo]}):null,s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"share ctx"}),": ",dh?"yes":"no"]}),typeof Vc=="number"?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"repeats"}),": ",Vc]}):null]}),po!==null?s.jsxs("div",{className:"observe_context_budget",children:[s.jsxs("span",{className:"mono muted",children:[typeof hh=="number"&&typeof Ad=="number"?`${hh.toLocaleString()} / ${Ad.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,po))*100)}%`]}),s.jsx("div",{className:"observe_budget_bar",children:s.jsx("div",{className:`observe_budget_fill ${po>=.9?"danger":po>=.75?"warn":"ok"}`,style:{width:`${Math.round(Math.max(0,Math.min(1,po))*100)}%`}})})]}):null,s.jsxs("div",{className:"observe_context_actions",children:[Pl?s.jsx("button",{className:"btn",onClick:()=>{Pn(Jo||""),Hn(!0),ai(""),Ao(!0)},disabled:dt||$n,children:"Edit schedule"}):null,Pl?s.jsx("button",{className:"btn",onClick:()=>{_s(""),Js(!0)},disabled:dt||Er,children:"Compact context"}):null,s.jsx("button",{className:"btn",onClick:()=>void pd(c.trim()).catch(y=>nn(String((y==null?void 0:y.message)||y))),disabled:dt||!c.trim(),title:"Open Launch → Automate prefilled from this schedule (this schedule is not changed)",children:"Recreate as automation"})]})]}):null,Pu?s.jsxs("div",{className:"observe_context_card error",children:[s.jsx("span",{className:"chip danger",children:"error"}),s.jsx("span",{className:"mono",children:Pu})]}):null]}):null]}),s.jsxs("div",{className:"card panel_card card_scroll observe_viewer observe_viewer_full",ref:Df,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":tr==="ledger",className:`tab ${tr==="ledger"?"active":""}`,onClick:()=>Yc("ledger"),children:"Ledger"}),s.jsx("button",{role:"tab","aria-selected":tr==="graph",className:`tab ${tr==="graph"?"active":""}`,onClick:()=>Yc("graph"),children:"Flow"}),s.jsx("button",{role:"tab","aria-selected":tr==="chat",className:`tab ${tr==="chat"?"active":""}`,onClick:()=>Yc("chat"),children:"Ask"})]}),tr==="ledger"&&(an.length>0||ss.length>0)?s.jsx("div",{className:"tab_bar_controls",children:s.jsx("button",{className:"seg_action",disabled:!an.length&&!ss.length,title:"Copy full ledger as JSONL",onClick:()=>{const M=[...an.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 Le,_e;const V=String(((Le=H.record)==null?void 0:Le.ended_at)||((_e=H.record)==null?void 0:_e.started_at)||"").trim(),ne=qn(V);return{...H,_ms:ne??0}});M.sort((H,V)=>(H._ms||0)-(V._ms||0));const q=(M.length>5e3?M.slice(M.length-5e3):M).map(({_ms:H,...V})=>JSON.stringify(V)).join(`
|
|
149
|
+
`);Dc(q)},children:"Copy JSONL"})}):null,tr==="graph"?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsx("button",{className:`seg_action ${fl?"active":""}`,"aria-pressed":fl,onClick:()=>qm(y=>!y),children:"Subflows"}),s.jsx("button",{className:`seg_action ${qu?"active":""}`,"aria-pressed":qu,onClick:()=>Hm(y=>!y),children:"Path"}),Td.length?s.jsx("select",{className:"mono seg_select",value:ya,onChange:y=>Qi(String(y.target.value||"")),disabled:!!Pr.trim()||!C.trim()||Uu,children:Td.map(y=>s.jsx("option",{value:y,children:y},y))}):null]}):null]}),tr==="ledger"?c.trim()?s.jsxs("div",{className:"rs_page",children:[s.jsx(a2,{status:Wa||Vn||"unknown",duration:Rn?ic(Rn):"",facts:KN(GN(go)),error:hm(Rn)||String((ue==null?void 0:ue.error)||"").trim(),answer:t_||String((Dl==null?void 0:Dl.text)||"").trim(),waiting_for_user:!!(Ft!=null&&Ft.wait_key)&&String((Ft==null?void 0:Ft.reason)||"")==="user",on_answer_wait:()=>Qs(""),workspace_root:ga,on_reveal_workspace:()=>void Tl(),on_open_artifacts:()=>{const y=String(c||"").trim();y&&(Bo(y),Ta(y),wl("run")),Gu("artifacts"),t("runtime")}}),Iu.filter(y=>y.kind==="error"&&!y.data).slice(0,3).map(y=>s.jsxs("p",{className:"rs_notice",children:[y.title,": ",y.preview]},y.id)),s.jsx(o2,{items:go,run_id:Fl,run_options:$s,run_llm_counts:Gc,on_select_run:y=>Bu(y),state:Wm,on_state:n_,node_label:(y,S)=>{const M=S?(Vo==null?void 0:Vo[Fn(y,S)])||(Vo==null?void 0:Vo[S]):null;return String((M==null?void 0:M.label)||S||"").trim()},on_copy:y=>void Dc(y),on_open_run:y=>void Zr(y,{root_run_id:m||c||y})})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run on the left to inspect it — or start one from Launch."}):null,tr==="graph"?s.jsxs(s.Fragment,{children:[Wu?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:Ct()})]}),s.jsx("div",{className:"body mono",children:Wu})]}):null,Uu?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:Pr.trim()?Pr.trim():ya})]}),s.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,s.jsx("div",{className:"graph_panel",children:s.jsx(OE,{flow:wa,flow_by_id:xa,expand_subflows:fl,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:Zo,schedule_interval:Jo,node_last_ms:e_,active_node_id:Pi,recent_nodes:Bf,visited_nodes:Hu,highlight_path:qu,now_ms:Vr})})]}):null,tr==="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(xu,{value:Tu,options:Lu,placeholder:ll?"Loading…":Lu.length?"Select a saved discussion…":"(none saved)",disabled:!c.trim()||!A||!Lu.length,loading:ll,searchable:!0,clearable:!0,onChange:y=>{_c(y),Io("")}})}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[s.jsx("button",{className:"btn",type:"button",disabled:!Tu.trim()||!A||pc,onClick:()=>void Ym(),children:pc?"Loading…":"Load"}),s.jsx("button",{className:"btn",type:"button",disabled:!Qe.length||be||Xn||pc,onClick:()=>{ot([]),Dt(null),er(""),li(""),vn(""),ps(""),yr("")},children:"Clear"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>void Wc(),disabled:!c.trim()||!A||ll,children:ll?"Refreshing…":"Refresh"})]})]}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:"8px",flexWrap:"wrap"},children:[s.jsx("button",{className:"btn",type:"button",disabled:!Qe.length||!c.trim()||!A||Xn||!Ru,onClick:()=>void ih(),title:Ru?"":"No changes since last save",children:Xn?"Saving…":!Ru&&jn?"Saved":"Save discussion"}),s.jsx("button",{className:"btn",type:"button",disabled:!Qe.length,onClick:()=>vd("download"),children:"Export Markdown"}),s.jsx("button",{className:"btn",type:"button",disabled:!Qe.length,onClick:()=>vd("copy"),children:Ee==="copied"?"Copied":Ee==="failed"?"Copy failed":"Copy Markdown"})]}),jn?s.jsxs("div",{className:"chat_hint",children:["Last saved: ",ec(jn)]}):null,un?s.jsx("div",{className:"chat_hint chat_hint_danger",children:un}):null,Mu?s.jsx("div",{className:"chat_hint chat_hint_danger",children:Mu}):null,hc?s.jsx("div",{className:"chat_hint chat_hint_danger",children:hc}):null]})]}),Mo?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:Ct()})]}),s.jsx("div",{className:"body mono",children:Mo})]}):null,al?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:Ct()})]}),s.jsx("div",{className:"body mono",children:al})]}):null,s.jsx("div",{className:"chat_messages",style:{marginTop:"10px"},children:s.jsx(dg,{messages:Qe,className:"log_scroll",after:s.jsx(kx,{history:mt}),afterKey:mt?`${mt.replayed_messages}:${mt.dropped_messages}`:null,messageProps:Ht.tts_supported&&A&&B.trim()?{onSpeakToggle:rh,getSpeakState:wd,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:Xt,value:Xi,onChange:er,onSubmit:()=>void sh(),placeholder:"Ask about this run…",disabled:!c.trim()||!A||be,busy:be||Ht.voice_ptt_busy,busyLabel:Ht.voice_ptt_busy?"Transcribing…":"Thinking…",rows:3,sendButtonClassName:"btn primary",actions:s.jsxs("button",{className:`btn btn_icon voice_btn${Ht.voice_ptt_recording?" danger":""}`,type:"button",disabled:!A||!Mn.trim()||!B.trim()||be||Ht.voice_ptt_busy||!Ht.voice_ptt_supported,title:Ht.voice_ptt_supported?Ht.voice_ptt_busy?"Transcribing…":Ht.voice_ptt_recording?"Recording… release to transcribe":"Hold to talk (record + transcribe)":Ip()?"Voice recording is not supported in this browser":Lp,"aria-label":"Voice input",onPointerDown:y=>{var S,M;if(!(!A||!Mn.trim()||!B.trim()||be||Ht.voice_ptt_busy||!Ht.voice_ptt_supported)){y.preventDefault();try{(M=(S=y.currentTarget)==null?void 0:S.setPointerCapture)==null||M.call(S,y.pointerId)}catch{}Ht.start_voice_ptt_recording()}},onPointerUp:y=>{y.preventDefault(),Ht.stop_voice_ptt_recording()},onPointerCancel:y=>{y.preventDefault(),Ht.stop_voice_ptt_recording()},children:[s.jsx(et,{name:Ht.voice_ptt_recording?"x":"mic",size:16}),Ht.voice_ptt_busy?"Transcribing…":Ht.voice_ptt_recording?"Recording…":"Voice"]})}),Ip()?null:s.jsx("div",{className:"mono muted","data-testid":"voice-https-hint",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:Lp})]})]}):null,c.trim()?s.jsxs("div",{className:`status_bar ${dc?"pulse":""}`,children:[s.jsx("strong",{children:"Run"}),":"," ",s.jsx("span",{className:"mono",children:Wa||Vn||"unknown"}),Md&&Zo?s.jsxs("span",{className:"mono muted",children:[" • next in ",Zo]}):null,Tr?s.jsxs("span",{className:"mono muted",children:[" • ",Tr]}):null]}):null]})]})]})}):null,s.jsxs(Kl,{open:Zu,title:Ai||"Artifact",onClose:()=>{uo(!1),xr(""),jl(""),xl(!1),La(null),fn&&(URL.revokeObjectURL(fn),ws(""))},actions:s.jsx("button",{className:"btn",onClick:()=>{uo(!1),xr(""),jl(""),xl(!1),La(null),fn&&(URL.revokeObjectURL(fn),ws(""))},children:"Close"}),children:[Vf?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,bl?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:bl}):null,$i==="image"&&fn?s.jsx("img",{className:"runtime_preview_media",src:fn,alt:Ai||"Artifact preview"}):$i==="audio"&&fn?s.jsx("audio",{className:"runtime_preview_media",controls:!0,src:fn}):$i==="video"&&fn?s.jsx("video",{className:"runtime_preview_media",controls:!0,src:fn}):s.jsx(Qx,{artifact:nr,text:Cn||"(empty)",className:"runtime_preview_text"})]}),Eo?s.jsxs(Kl,{open:Eo,title:"Edit schedule",onClose:()=>{Ao(!1),Pn(""),Hn(!0),ai(""),Fs(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Ao(!1),Pn(""),Hn(!0),ai(""),Fs(!1)},disabled:dt||$n,children:"Back"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await th({interval:$o,apply_immediately:mr})||(Ao(!1),ai(""),Fs(!1))},disabled:dt||$n||!$o.trim(),children:"Save"})]}),children:[Gi?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:Ct()})]}),s.jsx("div",{className:"body mono",children:Gi})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Interval"}),s.jsx("input",{className:"mono",value:$o,onChange:y=>Pn(String(y.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(y=>s.jsx("button",{className:"btn",onClick:()=>Pn(y),disabled:dt||$n,children:y},y))})]}),s.jsx("div",{className:"field",children:s.jsx(fC,{checked:mr,busy:dt||$n,onChange:Hn})})]}):null,hs?s.jsxs(Kl,{open:hs,title:"Compact scheduled context",onClose:()=>{Js(!1),_s(""),Ar(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Js(!1),_s(""),Ar(!1)},disabled:dt||Er,children:"Cancel"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await nh({preserve_recent:ms,compression_mode:Ki,focus:fa})||(Js(!1),_s(""),Ar(!1))},disabled:dt||Er,children:Er?"Compacting…":"Compact"})]}),children:[To?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:Ct()})]}),s.jsx("div",{className:"body mono",children:To})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Preserve recent turns"}),s.jsx("input",{type:"number",min:1,value:String(ms),onChange:y=>da(Math.max(1,parseInt(y.target.value||"6",10)||6)),disabled:dt||Er})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Mode"}),s.jsxs("select",{value:Ki,onChange:y=>ln(y.target.value),disabled:dt||Er,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:fa,onChange:y=>uc(String(y.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:dt||Er})]})]}):null,Yi?s.jsxs(Kl,{open:Yi,title:Ss==="cancel"?"Cancel run":or?"Suspend schedule":"Pause run",onClose:()=>{_r(!1),Xs(""),is("")},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{_r(!1),Xs(""),is("")},disabled:dt||ft,children:"Back"}),s.jsx("button",{className:`btn ${Ss==="cancel"?"danger":"primary"}`,onClick:async()=>{is("");const y=await Ba(Ss,{reason:$r});if(y){is(y);return}_r(!1),Xs(""),is("")},disabled:dt||ft,children:Ss==="pause"?or?"Suspend":"Pause":"Cancel"})]}),children:[Si?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:Ct()})]}),s.jsx("div",{className:"body mono",children:Si})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Reason (optional)"}),s.jsx("input",{className:"mono",value:$r,onChange:y=>Xs(y.target.value),placeholder:"reason…"})]})]}):null,bd?s.jsxs(Kl,{open:bd,title:Hc,onClose:()=>{Es&&Qs(Es)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Zi("ledger"),t("observe"),zl(),Es&&Qs(Es)},disabled:!c.trim(),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>Es&&Qs(Es),disabled:ft,children:"Dismiss"}),Ko.length?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn danger",disabled:ft,onClick:()=>Il({approved:!1}),children:"Reject"}),s.jsx("button",{className:"btn",disabled:ft,onClick:()=>Il({approved:!0}),children:"Approve only"}),s.jsx("button",{className:"btn primary",disabled:!Pa||ft,onClick:()=>Jm(Ko),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:Hc}),s.jsx("p",{children:Zm})]}),s.jsx(ac,{status:ei||"waiting"})]}),Yo?s.jsxs("div",{className:`wait_request_card ${As?"":"inferred"}`,children:[s.jsx("span",{children:Ws}),s.jsx(kv,{metadata:lh}),s.jsx(Wi,{text:Yo}),As?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."}),kd.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:kd.map((y,S)=>s.jsxs("div",{className:`wait_turn_row role_${y.role.replace(/[^a-z0-9_-]+/g,"_")}`,children:[s.jsxs("div",{className:"wait_turn_meta",children:[s.jsx("strong",{children:y.role==="assistant"?"Assistant":y.role==="user"||y.role==="human"?"User":y.role}),y.ts?s.jsx("span",{className:"mono muted",children:ec(y.ts)}):null]}),s.jsx(kv,{metadata:y.runtime_metadata}),s.jsx(Wi,{text:kt(y.text,{max_chars:1200,max_lines:10})})]},`${y.role}:${S}`))})]}):null,s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:Bi(gi,as)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:Qt(c.trim(),24)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:gi.current_node||String((Us==null?void 0:Us.node_id)||"—")})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:ic(gi)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:gi.session_id?Qt(String(gi.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:Qt(Es,28)})]})]}),uh?s.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!Yo,children:[s.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(Is,{value:ch,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:[qc.map(y=>s.jsxs("div",{className:"wait_event_row",children:[s.jsxs("span",{className:"mono",children:["#",y.cursor]}),s.jsx("strong",{children:y.summary||y.effect_type||y.status||"event"}),s.jsx("span",{className:"mono muted",children:[y.node_id,y.status,ec(y.ts)].filter(Boolean).join(" · ")})]},`${y.cursor}:${y.node_id}:${y.status}`)),qc.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),Ko.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:Ko.map((y,S)=>s.jsxs("div",{className:"wait_tool_card",children:[s.jsxs("div",{className:"wait_tool_header",children:[s.jsx("strong",{children:String((y==null?void 0:y.name)||"tool")}),s.jsxs("div",{className:"wait_tool_badges",children:[s.jsx("span",{className:"chip mono warn",children:"approval"}),Hx(y).map(M=>s.jsxs("span",{className:"chip mono muted",title:qx,children:[M,"~"]},M))]})]}),s.jsx("div",{className:"wait_tool_args",children:s.jsx(Is,{value:(y==null?void 0:y.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((y==null?void 0:y.name)||"tool")}:${S}`))}),Pa?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 gd(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(Is,{value:Ft||{},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:Yo||"No explicit prompt was provided. Open the ledger for context before responding."}),s.jsx(_E,{wait:Ft,disabled:ft,on_submit:y=>Il({response:y})}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void gd(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(Is,{value:Ft||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(xN).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}dj();ij.createRoot(document.getElementById("root")).render(s.jsx(ve.StrictMode,{children:s.jsx(VL,{})}));
|
|
150
|
+
//# sourceMappingURL=index-CDAE9Eth.js.map
|